vite 5.0.4 → 5.0.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.
@@ -2769,7 +2769,17 @@ function serialize(obj, indent, baseIndent) {
2769
2769
  return `${obj}n`;
2770
2770
  return stringify$8(obj);
2771
2771
  }
2772
+ // isWellFormed exists from Node.js 20
2773
+ const hasStringIsWellFormed = 'isWellFormed' in String.prototype;
2774
+ function isWellFormedString(input) {
2775
+ // @ts-expect-error String::isWellFormed exists from ES2024. tsconfig lib is set to ES6
2776
+ if (hasStringIsWellFormed)
2777
+ return input.isWellFormed();
2778
+ // https://github.com/tc39/proposal-is-usv-string/blob/main/README.md#algorithm
2779
+ return !/\p{Surrogate}/u.test(input);
2780
+ }
2772
2781
  const dataToEsm = function dataToEsm(data, options = {}) {
2782
+ var _a, _b;
2773
2783
  const t = options.compact ? '' : 'indent' in options ? options.indent : '\t';
2774
2784
  const _ = options.compact ? '' : ' ';
2775
2785
  const n = options.compact ? '' : '\n';
@@ -2784,8 +2794,17 @@ const dataToEsm = function dataToEsm(data, options = {}) {
2784
2794
  const magic = _ || (/^[{[\-\/]/.test(code) ? '' : ' '); // eslint-disable-line no-useless-escape
2785
2795
  return `export default${magic}${code};`;
2786
2796
  }
2797
+ let maxUnderbarPrefixLength = 0;
2798
+ for (const key of Object.keys(data)) {
2799
+ const underbarPrefixLength = (_b = (_a = key.match(/^(_+)/)) === null || _a === void 0 ? void 0 : _a[0].length) !== null && _b !== void 0 ? _b : 0;
2800
+ if (underbarPrefixLength > maxUnderbarPrefixLength) {
2801
+ maxUnderbarPrefixLength = underbarPrefixLength;
2802
+ }
2803
+ }
2804
+ const arbitraryNamePrefix = `${'_'.repeat(maxUnderbarPrefixLength + 1)}arbitrary`;
2787
2805
  let namedExportCode = '';
2788
2806
  const defaultExportRows = [];
2807
+ const arbitraryNameExportRows = [];
2789
2808
  for (const [key, value] of Object.entries(data)) {
2790
2809
  if (key === makeLegalIdentifier(key)) {
2791
2810
  if (options.objectShorthand)
@@ -2796,9 +2815,18 @@ const dataToEsm = function dataToEsm(data, options = {}) {
2796
2815
  }
2797
2816
  else {
2798
2817
  defaultExportRows.push(`${stringify$8(key)}:${_}${serialize(value, options.compact ? null : t, '')}`);
2818
+ if (options.includeArbitraryNames && isWellFormedString(key)) {
2819
+ const variableName = `${arbitraryNamePrefix}${arbitraryNameExportRows.length}`;
2820
+ namedExportCode += `${declarationType} ${variableName}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`;
2821
+ arbitraryNameExportRows.push(`${variableName} as ${JSON.stringify(key)}`);
2822
+ }
2799
2823
  }
2800
2824
  }
2801
- return `${namedExportCode}export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;
2825
+ const arbitraryExportCode = arbitraryNameExportRows.length > 0
2826
+ ? `export${_}{${n}${t}${arbitraryNameExportRows.join(`,${n}${t}`)}${n}};${n}`
2827
+ : '';
2828
+ const defaultExportCode = `export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;
2829
+ return `${namedExportCode}${arbitraryExportCode}${defaultExportCode}`;
2802
2830
  };
2803
2831
 
2804
2832
  var path$l = require$$0$4;
@@ -12069,7 +12097,7 @@ function normalizePath$3(id) {
12069
12097
  }
12070
12098
  function fsPathFromId(id) {
12071
12099
  const fsPath = normalizePath$3(id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id);
12072
- return fsPath[0] === '/' || fsPath.match(VOLUME_RE) ? fsPath : `/${fsPath}`;
12100
+ return fsPath[0] === '/' || VOLUME_RE.test(fsPath) ? fsPath : `/${fsPath}`;
12073
12101
  }
12074
12102
  function fsPathFromUrl(url) {
12075
12103
  return fsPathFromId(cleanUrl(url));
@@ -14611,7 +14639,7 @@ const buildEsbuildPlugin = (config) => {
14611
14639
  // the headers don't modify the sourcemap
14612
14640
  const esbuildCode = res.code;
14613
14641
  const contentIndex = opts.format === 'iife'
14614
- ? esbuildCode.match(IIFE_BEGIN_RE)?.index || 0
14642
+ ? Math.max(esbuildCode.search(IIFE_BEGIN_RE), 0)
14615
14643
  : opts.format === 'umd'
14616
14644
  ? esbuildCode.indexOf(`(function(`) // same for minified or not
14617
14645
  : 0;
@@ -17115,32 +17143,43 @@ const debug$g = createDebugger('vite:sourcemap', {
17115
17143
  // false positive "missing source" warning. We also check for certain
17116
17144
  // prefixes used for special handling in esbuildDepPlugin.
17117
17145
  const virtualSourceRE = /^(?:dep:|browser-external:|virtual:)|\0/;
17118
- async function injectSourcesContent(map, file, logger) {
17146
+ async function computeSourceRoute(map, file) {
17119
17147
  let sourceRoot;
17120
17148
  try {
17121
17149
  // The source root is undefined for virtual modules and permission errors.
17122
17150
  sourceRoot = await fsp.realpath(path$o.resolve(path$o.dirname(file), map.sourceRoot || ''));
17123
17151
  }
17124
17152
  catch { }
17153
+ return sourceRoot;
17154
+ }
17155
+ async function injectSourcesContent(map, file, logger) {
17156
+ let sourceRootPromise;
17125
17157
  const missingSources = [];
17126
17158
  const sourcesContent = map.sourcesContent || [];
17127
- await Promise.all(map.sources.map(async (sourcePath, index) => {
17128
- let content = null;
17129
- if (sourcePath && !virtualSourceRE.test(sourcePath)) {
17130
- sourcePath = decodeURI(sourcePath);
17131
- if (sourceRoot) {
17132
- sourcePath = path$o.resolve(sourceRoot, sourcePath);
17133
- }
17134
- // inject content from source file when sourcesContent is null
17135
- content =
17136
- sourcesContent[index] ??
17137
- (await fsp.readFile(sourcePath, 'utf-8').catch(() => {
17138
- missingSources.push(sourcePath);
17139
- return null;
17140
- }));
17159
+ const sourcesContentPromises = [];
17160
+ for (let index = 0; index < map.sources.length; index++) {
17161
+ const sourcePath = map.sources[index];
17162
+ if (!sourcesContent[index] &&
17163
+ sourcePath &&
17164
+ !virtualSourceRE.test(sourcePath)) {
17165
+ sourcesContentPromises.push((async () => {
17166
+ // inject content from source file when sourcesContent is null
17167
+ sourceRootPromise ??= computeSourceRoute(map, file);
17168
+ const sourceRoot = await sourceRootPromise;
17169
+ let resolvedSourcePath = decodeURI(sourcePath);
17170
+ if (sourceRoot) {
17171
+ resolvedSourcePath = path$o.resolve(sourceRoot, resolvedSourcePath);
17172
+ }
17173
+ sourcesContent[index] = await fsp
17174
+ .readFile(resolvedSourcePath, 'utf-8')
17175
+ .catch(() => {
17176
+ missingSources.push(resolvedSourcePath);
17177
+ return null;
17178
+ });
17179
+ })());
17141
17180
  }
17142
- sourcesContent[index] = content;
17143
- }));
17181
+ }
17182
+ await Promise.all(sourcesContentPromises);
17144
17183
  map.sourcesContent = sourcesContent;
17145
17184
  // Use this command…
17146
17185
  // DEBUG="vite:sourcemap" vite build
@@ -28496,7 +28535,7 @@ function resolvePlugin(resolveOptions) {
28496
28535
  // Optimized files could not yet exist in disk, resolve to the full path
28497
28536
  // Inject the current browserHash version if the path doesn't have one
28498
28537
  if (!resolveOptions.isBuild &&
28499
- !normalizedFsPath.match(DEP_VERSION_RE)) {
28538
+ !DEP_VERSION_RE.test(normalizedFsPath)) {
28500
28539
  const browserHash = optimizedDepInfoFromFile(depsOptimizer.metadata, normalizedFsPath)?.browserHash;
28501
28540
  if (browserHash) {
28502
28541
  return injectQuery(normalizedFsPath, `v=${browserHash}`);
@@ -28655,7 +28694,7 @@ function ensureVersionQuery(resolved, id, options, depsOptimizer) {
28655
28694
  // Use the original id to do the check as the resolved id may be the real
28656
28695
  // file path after symlinks resolution
28657
28696
  const isNodeModule = isInNodeModules$1(id) || isInNodeModules$1(resolved);
28658
- if (isNodeModule && !resolved.match(DEP_VERSION_RE)) {
28697
+ if (isNodeModule && !DEP_VERSION_RE.test(resolved)) {
28659
28698
  const versionHash = depsOptimizer.metadata.browserHash;
28660
28699
  if (versionHash && isOptimizable(resolved, depsOptimizer.options)) {
28661
28700
  resolved = injectQuery(resolved, `v=${versionHash}`);
@@ -37858,7 +37897,7 @@ function loadEnv(mode, envDir, prefixes = 'VITE_') {
37858
37897
  }
37859
37898
  function resolveEnvPrefix({ envPrefix = 'VITE_', }) {
37860
37899
  envPrefix = arraify(envPrefix);
37861
- if (envPrefix.some((prefix) => prefix === '')) {
37900
+ if (envPrefix.includes('')) {
37862
37901
  throw new Error(`envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`);
37863
37902
  }
37864
37903
  return envPrefix;
@@ -37937,7 +37976,9 @@ function polyfill() {
37937
37976
  const htmlProxyRE$1 = /\?html-proxy=?(?:&inline-css)?(?:&style-attr)?&index=(\d+)\.(js|css)$/;
37938
37977
  const inlineCSSRE$1 = /__VITE_INLINE_CSS__([a-z\d]{8}_\d+)__/g;
37939
37978
  // Do not allow preceding '.', but do allow preceding '...' for spread operations
37940
- const inlineImportRE = /(?<!(?<!\.\.)\.)\bimport\s*\(("(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*')\)/g;
37979
+ const inlineImportRE =
37980
+ // eslint-disable-next-line regexp/no-unused-capturing-group -- https://github.com/ota-meshi/eslint-plugin-regexp/issues/675
37981
+ /(?<!(?<!\.\.)\.)\bimport\s*\(("(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*')\)/dg;
37941
37982
  const htmlLangRE = /\.(?:html|htm)$/;
37942
37983
  const importMapRE = /[ \t]*<script[^>]*type\s*=\s*(?:"importmap"|'importmap'|importmap)[^>]*>.*?<\/script>/is;
37943
37984
  const moduleScriptRE = /[ \t]*<script[^>]*type\s*=\s*(?:"module"|'module'|module)[^>]*>/i;
@@ -38559,10 +38600,9 @@ function extractImportExpressionFromClassicScript(scriptTextNode) {
38559
38600
  let match;
38560
38601
  inlineImportRE.lastIndex = 0;
38561
38602
  while ((match = inlineImportRE.exec(cleanCode))) {
38562
- const { 1: url, index } = match;
38563
- const startUrl = cleanCode.indexOf(url, index);
38564
- const start = startUrl + 1;
38565
- const end = start + url.length - 2;
38603
+ const [, [urlStart, urlEnd]] = match.indices;
38604
+ const start = urlStart + 1;
38605
+ const end = urlEnd - 1;
38566
38606
  scriptUrls.push({
38567
38607
  start: start + startOffset,
38568
38608
  end: end + startOffset,
@@ -38573,11 +38613,11 @@ function extractImportExpressionFromClassicScript(scriptTextNode) {
38573
38613
  }
38574
38614
  function preImportMapHook(config) {
38575
38615
  return (html, ctx) => {
38576
- const importMapIndex = html.match(importMapRE)?.index;
38577
- if (importMapIndex === undefined)
38616
+ const importMapIndex = html.search(importMapRE);
38617
+ if (importMapIndex < 0)
38578
38618
  return;
38579
- const importMapAppendIndex = html.match(importMapAppendRE)?.index;
38580
- if (importMapAppendIndex === undefined)
38619
+ const importMapAppendIndex = html.search(importMapAppendRE);
38620
+ if (importMapAppendIndex < 0)
38581
38621
  return;
38582
38622
  if (importMapAppendIndex < importMapIndex) {
38583
38623
  const relativeHtml = normalizePath$3(path$o.relative(config.root, ctx.filename));
@@ -39663,8 +39703,8 @@ function createCachedImport(imp) {
39663
39703
  return cached;
39664
39704
  };
39665
39705
  }
39666
- const importPostcssImport = createCachedImport(() => import('./dep-nbvvoiwS.js').then(function (n) { return n.i; }));
39667
- const importPostcssModules = createCachedImport(() => import('./dep-GiiHpyM6.js').then(function (n) { return n.i; }));
39706
+ const importPostcssImport = createCachedImport(() => import('./dep-mpgFWQ-7.js').then(function (n) { return n.i; }));
39707
+ const importPostcssModules = createCachedImport(() => import('./dep-IrrVD4is.js').then(function (n) { return n.i; }));
39668
39708
  const importPostcss = createCachedImport(() => import('postcss'));
39669
39709
  /**
39670
39710
  * @experimental
@@ -39672,12 +39712,12 @@ const importPostcss = createCachedImport(() => import('postcss'));
39672
39712
  async function preprocessCSS(code, filename, config) {
39673
39713
  return await compileCSS(filename, code, config);
39674
39714
  }
39675
- const postcssReturnsVirtualFilesRE = /^<.+>$/;
39676
39715
  async function formatPostcssSourceMap(rawMap, file) {
39677
39716
  const inputFileDir = path$o.dirname(file);
39678
39717
  const sources = rawMap.sources.map((source) => {
39679
39718
  const cleanSource = cleanUrl(decodeURIComponent(source));
39680
- if (postcssReturnsVirtualFilesRE.test(cleanSource)) {
39719
+ // postcss virtual files
39720
+ if (cleanSource[0] === '<' && cleanSource[cleanSource.length - 1] === '>') {
39681
39721
  return `\0${cleanSource}`;
39682
39722
  }
39683
39723
  return normalizePath$3(path$o.resolve(inputFileDir, cleanSource));
@@ -39729,7 +39769,7 @@ async function resolvePostcssConfig(config) {
39729
39769
  else {
39730
39770
  const searchPath = typeof inlineOptions === 'string' ? inlineOptions : config.root;
39731
39771
  result = postcssrc({}, searchPath).catch((e) => {
39732
- if (!/No PostCSS Config found/.test(e.message)) {
39772
+ if (!e.message.includes('No PostCSS Config found')) {
39733
39773
  if (e instanceof Error) {
39734
39774
  const { name, message, stack } = e;
39735
39775
  e.name = 'Failed to load PostCSS config';
@@ -39943,6 +39983,8 @@ function resolveMinifyCssEsbuildOptions(options) {
39943
39983
  return { ...base, minify: true };
39944
39984
  }
39945
39985
  }
39986
+ const atImportRE = /@import(?:\s*(?:url\([^)]*\)|"(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*').*?|[^;]*);/g;
39987
+ const atCharsetRE = /@charset(?:\s*(?:"(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*').*?|[^;]*);/g;
39946
39988
  async function hoistAtRules(css) {
39947
39989
  const s = new MagicString(css);
39948
39990
  const cleanCss = emptyCssComments(css);
@@ -39951,7 +39993,7 @@ async function hoistAtRules(css) {
39951
39993
  // CSS @import can only appear at top of the file. We need to hoist all @import
39952
39994
  // to top when multiple files are concatenated.
39953
39995
  // match until semicolon that's not in quotes
39954
- const atImportRE = /@import(?:\s*(?:url\([^)]*\)|"(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*').*?|[^;]*);/g;
39996
+ atImportRE.lastIndex = 0;
39955
39997
  while ((match = atImportRE.exec(cleanCss))) {
39956
39998
  s.remove(match.index, match.index + match[0].length);
39957
39999
  // Use `appendLeft` instead of `prepend` to preserve original @import order
@@ -39959,7 +40001,7 @@ async function hoistAtRules(css) {
39959
40001
  }
39960
40002
  // #6333
39961
40003
  // CSS @charset must be the top-first in the file, hoist the first to top
39962
- const atCharsetRE = /@charset(?:\s*(?:"(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*').*?|[^;]*);/g;
40004
+ atCharsetRE.lastIndex = 0;
39963
40005
  let foundCharset = false;
39964
40006
  while ((match = atCharsetRE.exec(cleanCss))) {
39965
40007
  s.remove(match.index, match.index + match[0].length);
@@ -40470,8 +40512,8 @@ const convertTargets = (esbuildTarget) => {
40470
40512
  for (const entry of entriesWithoutES) {
40471
40513
  if (entry === 'esnext')
40472
40514
  continue;
40473
- const index = entry.match(versionRE)?.index;
40474
- if (index) {
40515
+ const index = entry.search(versionRE);
40516
+ if (index >= 0) {
40475
40517
  const browser = map[entry.slice(0, index)];
40476
40518
  if (browser === false)
40477
40519
  continue; // No mapping available
@@ -40893,16 +40935,24 @@ function jsonPlugin(options = {}, isBuild) {
40893
40935
  };
40894
40936
  }
40895
40937
  catch (e) {
40896
- const errorMessageList = /\d+/.exec(e.message);
40897
- const position = errorMessageList && parseInt(errorMessageList[0], 10);
40938
+ const position = extractJsonErrorPosition(e.message, json.length);
40898
40939
  const msg = position
40899
- ? `, invalid JSON syntax found at line ${position}`
40940
+ ? `, invalid JSON syntax found at position ${position}`
40900
40941
  : `.`;
40901
- this.error(`Failed to parse JSON file` + msg, e.idx);
40942
+ this.error(`Failed to parse JSON file` + msg, position);
40902
40943
  }
40903
40944
  },
40904
40945
  };
40905
40946
  }
40947
+ function extractJsonErrorPosition(errorMessage, inputLength) {
40948
+ if (errorMessage.startsWith('Unexpected end of JSON input')) {
40949
+ return inputLength - 1;
40950
+ }
40951
+ const errorMessageList = /at position (\d+)/.exec(errorMessage);
40952
+ return errorMessageList
40953
+ ? Math.max(parseInt(errorMessageList[1], 10) - 1, 0)
40954
+ : undefined;
40955
+ }
40906
40956
 
40907
40957
  const ERR_OPTIMIZE_DEPS_PROCESSING_ERROR = 'ERR_OPTIMIZE_DEPS_PROCESSING_ERROR';
40908
40958
  const ERR_OUTDATED_OPTIMIZED_DEP = 'ERR_OUTDATED_OPTIMIZED_DEP';
@@ -51373,6 +51423,8 @@ function bindCLIShortcuts(server, opts) {
51373
51423
  if (loggedKeys.has(shortcut.key))
51374
51424
  continue;
51375
51425
  loggedKeys.add(shortcut.key);
51426
+ if (shortcut.action == null)
51427
+ continue;
51376
51428
  server.config.logger.info(colors$1.dim(' press ') +
51377
51429
  colors$1.bold(`${shortcut.key} + enter`) +
51378
51430
  colors$1.dim(` to ${shortcut.description}`));
@@ -51380,7 +51432,7 @@ function bindCLIShortcuts(server, opts) {
51380
51432
  return;
51381
51433
  }
51382
51434
  const shortcut = shortcuts.find((shortcut) => shortcut.key === input);
51383
- if (!shortcut)
51435
+ if (!shortcut || shortcut.action == null)
51384
51436
  return;
51385
51437
  actionRunning = true;
51386
51438
  await shortcut.action(server);
@@ -58682,7 +58734,6 @@ const processNodeUrl = (url, useSrcSetReplacer, config, htmlPath, originalUrl, s
58682
58734
  const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl }) => {
58683
58735
  const { config, moduleGraph, watcher } = server;
58684
58736
  const base = config.base || '/';
58685
- htmlPath = decodeURI(htmlPath);
58686
58737
  let proxyModulePath;
58687
58738
  let proxyModuleUrl;
58688
58739
  const trailingSlash = htmlPath.endsWith('/');
@@ -58702,7 +58753,9 @@ const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl
58702
58753
  }
58703
58754
  const s = new MagicString(html);
58704
58755
  let inlineModuleIndex = -1;
58705
- const proxyCacheUrl = cleanUrl(proxyModulePath).replace(normalizePath$3(config.root), '');
58756
+ // The key to the proxyHtml cache is decoded, as it will be compared
58757
+ // against decoded URLs by the HTML plugins.
58758
+ const proxyCacheUrl = decodeURI(cleanUrl(proxyModulePath).replace(normalizePath$3(config.root), ''));
58706
58759
  const styleUrl = [];
58707
58760
  const inlineStyles = [];
58708
58761
  const addInlineModule = (node, ext) => {
@@ -58873,7 +58926,13 @@ function preTransformRequest(server, url, base) {
58873
58926
  if (!server.config.server.preTransformRequests)
58874
58927
  return;
58875
58928
  // transform all url as non-ssr as html includes client-side assets only
58876
- url = unwrapId(stripBase(url, base));
58929
+ try {
58930
+ url = unwrapId(stripBase(decodeURI(url), base));
58931
+ }
58932
+ catch {
58933
+ // ignore
58934
+ return;
58935
+ }
58877
58936
  server.warmupRequest(url);
58878
58937
  }
58879
58938
 
@@ -60266,6 +60325,11 @@ function isNodeWithinCircularImports(node, nodeChain, currentChain = [node], tra
60266
60325
  // Node may import itself which is safe
60267
60326
  if (importer === node)
60268
60327
  continue;
60328
+ // a PostCSS plugin like Tailwind JIT may register
60329
+ // any file as a dependency to a CSS file.
60330
+ // But in that case, the actual dependency chain is separate.
60331
+ if (isCSSRequest(importer.url))
60332
+ continue;
60269
60333
  // Check circular imports
60270
60334
  const importerIndex = nodeChain.indexOf(importer);
60271
60335
  if (importerIndex > -1) {
@@ -60930,7 +60994,8 @@ function webWorkerPlugin(config) {
60930
60994
  : null,
60931
60995
  });
60932
60996
  };
60933
- if (code.match(workerAssetUrlRE)) {
60997
+ workerAssetUrlRE.lastIndex = 0;
60998
+ if (workerAssetUrlRE.test(code)) {
60934
60999
  const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(outputOptions.format, config.isWorker);
60935
61000
  let match;
60936
61001
  s = new MagicString(code);
@@ -61088,9 +61153,8 @@ function importAnalysisPlugin(config) {
61088
61153
  return null;
61089
61154
  }
61090
61155
  const ssr = options?.ssr === true;
61091
- const prettyImporter = prettifyUrl(importer, root);
61092
61156
  if (canSkipImportAnalysis(importer)) {
61093
- debug$4?.(colors$1.dim(`[skipped] ${prettyImporter}`));
61157
+ debug$4?.(colors$1.dim(`[skipped] ${prettifyUrl(importer, root)}`));
61094
61158
  return null;
61095
61159
  }
61096
61160
  const start = performance.now();
@@ -61120,7 +61184,7 @@ function importAnalysisPlugin(config) {
61120
61184
  }
61121
61185
  if (!imports.length && !this._addedImports) {
61122
61186
  importerModule.isSelfAccepting = false;
61123
- debug$4?.(`${timeFrom(start)} ${colors$1.dim(`[no imports] ${prettyImporter}`)}`);
61187
+ debug$4?.(`${timeFrom(start)} ${colors$1.dim(`[no imports] ${prettifyUrl(importer, root)}`)}`);
61124
61188
  return source;
61125
61189
  }
61126
61190
  let hasHMR = false;
@@ -61202,7 +61266,7 @@ function importAnalysisPlugin(config) {
61202
61266
  // query can break 3rd party plugin's extension checks.
61203
61267
  if ((isRelative || isSelfImport) &&
61204
61268
  !hasImportInQueryParamsRE.test(url) &&
61205
- !url.match(DEP_VERSION_RE)) {
61269
+ !DEP_VERSION_RE.test(url)) {
61206
61270
  const versionMatch = importer.match(DEP_VERSION_RE);
61207
61271
  if (versionMatch) {
61208
61272
  url = injectQuery(url, versionMatch[1]);
@@ -61320,7 +61384,7 @@ function importAnalysisPlugin(config) {
61320
61384
  if (url !== specifier) {
61321
61385
  let rewriteDone = false;
61322
61386
  if (depsOptimizer?.isOptimizedDepFile(resolvedId) &&
61323
- !resolvedId.match(optimizedDepChunkRE$1)) {
61387
+ !optimizedDepChunkRE$1.test(resolvedId)) {
61324
61388
  // for optimized cjs deps, support named imports by rewriting named imports to const assignments.
61325
61389
  // internal optimized chunks don't need es interop and are excluded
61326
61390
  // The browserHash in resolvedId could be stale in which case there will be a full
@@ -61331,7 +61395,7 @@ function importAnalysisPlugin(config) {
61331
61395
  // Non-entry dynamic imports from dependencies will reach here as there isn't
61332
61396
  // optimize info for them, but they don't need es interop. If the request isn't
61333
61397
  // a dynamic import, then it is an internal Vite error
61334
- if (!file.match(optimizedDepDynamicRE$1)) {
61398
+ if (!optimizedDepDynamicRE$1.test(file)) {
61335
61399
  config.logger.error(colors$1.red(`Vite Error, ${url} optimized info should be defined`));
61336
61400
  }
61337
61401
  }
@@ -61427,7 +61491,7 @@ function importAnalysisPlugin(config) {
61427
61491
  ? `[accepts-exports]`
61428
61492
  : acceptedUrls.size
61429
61493
  ? `[accepts-deps]`
61430
- : `[detected api usage]`} ${prettyImporter}`);
61494
+ : `[detected api usage]`} ${prettifyUrl(importer, root)}`);
61431
61495
  // inject hot context
61432
61496
  str().prepend(`import { createHotContext as __vite__createHotContext } from "${clientPublicPath}";` +
61433
61497
  `import.meta.hot = __vite__createHotContext(${JSON.stringify(normalizeHmrUrl(importerModule.url))});`);
@@ -61477,7 +61541,7 @@ function importAnalysisPlugin(config) {
61477
61541
  handlePrunedModules(prunedImports, server);
61478
61542
  }
61479
61543
  }
61480
- debug$4?.(`${timeFrom(start)} ${colors$1.dim(`[${importedUrls.size} imports rewritten] ${prettyImporter}`)}`);
61544
+ debug$4?.(`${timeFrom(start)} ${colors$1.dim(`[${importedUrls.size} imports rewritten] ${prettifyUrl(importer, root)}`)}`);
61481
61545
  if (s) {
61482
61546
  return transformStableResult(s, importer, config);
61483
61547
  }
@@ -61997,20 +62061,19 @@ function workerImportMetaUrlPlugin(config) {
61997
62061
  const query = parseRequest(id);
61998
62062
  let s;
61999
62063
  const cleanString = stripLiteral(code);
62000
- const workerImportMetaUrlRE = /\bnew\s+(?:Worker|SharedWorker)\s*\(\s*(new\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*\))/g;
62064
+ const workerImportMetaUrlRE =
62065
+ // eslint-disable-next-line regexp/no-unused-capturing-group -- https://github.com/ota-meshi/eslint-plugin-regexp/issues/675
62066
+ /\bnew\s+(?:Worker|SharedWorker)\s*\(\s*(new\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*\))/dg;
62001
62067
  let match;
62002
62068
  while ((match = workerImportMetaUrlRE.exec(cleanString))) {
62003
- const { 0: allExp, 1: exp, 2: emptyUrl, index } = match;
62004
- const urlIndex = allExp.indexOf(exp) + index;
62005
- const urlStart = cleanString.indexOf(emptyUrl, index);
62006
- const urlEnd = urlStart + emptyUrl.length;
62069
+ const [[, endIndex], [expStart, expEnd], [urlStart, urlEnd]] = match.indices;
62007
62070
  const rawUrl = code.slice(urlStart, urlEnd);
62008
62071
  // potential dynamic template string
62009
62072
  if (rawUrl[0] === '`' && rawUrl.includes('${')) {
62010
- this.error(`\`new URL(url, import.meta.url)\` is not supported in dynamic template string.`, urlIndex);
62073
+ this.error(`\`new URL(url, import.meta.url)\` is not supported in dynamic template string.`, expStart);
62011
62074
  }
62012
62075
  s ||= new MagicString(code);
62013
- const workerType = getWorkerType(code, cleanString, index + allExp.length);
62076
+ const workerType = getWorkerType(code, cleanString, endIndex);
62014
62077
  const url = rawUrl.slice(1, -1);
62015
62078
  let file;
62016
62079
  if (url[0] === '.') {
@@ -62039,7 +62102,7 @@ function workerImportMetaUrlPlugin(config) {
62039
62102
  builtUrl = injectQuery(builtUrl, WORKER_FILE_ID);
62040
62103
  builtUrl = injectQuery(builtUrl, `type=${workerType}`);
62041
62104
  }
62042
- s.update(urlIndex, urlIndex + exp.length,
62105
+ s.update(expStart, expEnd,
62043
62106
  // add `'' +` to skip vite:asset-import-meta-url plugin
62044
62107
  `new URL('' + ${JSON.stringify(builtUrl)}, import.meta.url)`);
62045
62108
  }
@@ -62083,13 +62146,13 @@ function assetImportMetaUrlPlugin(config) {
62083
62146
  code.includes('new URL') &&
62084
62147
  code.includes(`import.meta.url`)) {
62085
62148
  let s;
62086
- const assetImportMetaUrlRE = /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*(?:,\s*)?\)/g;
62149
+ const assetImportMetaUrlRE =
62150
+ // eslint-disable-next-line regexp/no-unused-capturing-group -- https://github.com/ota-meshi/eslint-plugin-regexp/issues/675
62151
+ /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*(?:,\s*)?\)/dg;
62087
62152
  const cleanString = stripLiteral(code);
62088
62153
  let match;
62089
62154
  while ((match = assetImportMetaUrlRE.exec(cleanString))) {
62090
- const { 0: exp, 1: emptyUrl, index } = match;
62091
- const urlStart = cleanString.indexOf(emptyUrl, index);
62092
- const urlEnd = urlStart + emptyUrl.length;
62155
+ const [[startIndex, endIndex], [urlStart, urlEnd]] = match.indices;
62093
62156
  const rawUrl = code.slice(urlStart, urlEnd);
62094
62157
  if (!s)
62095
62158
  s = new MagicString(code);
@@ -62118,7 +62181,7 @@ function assetImportMetaUrlPlugin(config) {
62118
62181
  // A hack to allow 'as' & 'query' exist at the same time
62119
62182
  query: injectQuery(queryString, 'url'),
62120
62183
  };
62121
- s.update(index, index + exp.length, `new URL((import.meta.glob(${JSON.stringify(pattern)}, ${JSON.stringify(globOptions)}))[${pureUrl}], import.meta.url)`);
62184
+ s.update(startIndex, endIndex, `new URL((import.meta.glob(${JSON.stringify(pattern)}, ${JSON.stringify(globOptions)}))[${pureUrl}], import.meta.url)`);
62122
62185
  continue;
62123
62186
  }
62124
62187
  }
@@ -62159,11 +62222,11 @@ function assetImportMetaUrlPlugin(config) {
62159
62222
  }
62160
62223
  }
62161
62224
  if (!builtUrl) {
62162
- const rawExp = code.slice(index, index + exp.length);
62225
+ const rawExp = code.slice(startIndex, endIndex);
62163
62226
  config.logger.warnOnce(`\n${rawExp} doesn't exist at build time, it will remain unchanged to be resolved at runtime`);
62164
62227
  builtUrl = url;
62165
62228
  }
62166
- s.update(index, index + exp.length, `new URL(${JSON.stringify(builtUrl)}, import.meta.url)`);
62229
+ s.update(startIndex, endIndex, `new URL(${JSON.stringify(builtUrl)}, import.meta.url)`);
62167
62230
  }
62168
62231
  if (s) {
62169
62232
  return transformStableResult(s, id, config);
@@ -63433,9 +63496,10 @@ function esbuildScanPlugin(config, container, depImports, missing, entries) {
63433
63496
  '@vite/client',
63434
63497
  '@vite/env',
63435
63498
  ];
63499
+ const isUnlessEntry = (path) => !entries.includes(path);
63436
63500
  const externalUnlessEntry = ({ path }) => ({
63437
63501
  path,
63438
- external: !entries.includes(path),
63502
+ external: isUnlessEntry(path),
63439
63503
  });
63440
63504
  const doTransformGlobImport = async (contents, id, loader) => {
63441
63505
  let transpiledContents;
@@ -63640,19 +63704,32 @@ function esbuildScanPlugin(config, container, depImports, missing, entries) {
63640
63704
  // should be faster than doing it in the catch-all via js
63641
63705
  // they are done after the bare import resolve because a package name
63642
63706
  // may end with these extensions
63707
+ const setupExternalize = (filter, doExternalize) => {
63708
+ build.onResolve({ filter }, ({ path }) => {
63709
+ return {
63710
+ path,
63711
+ external: doExternalize(path),
63712
+ };
63713
+ });
63714
+ // onResolve is not called for glob imports.
63715
+ // we need to add that here as well until esbuild calls onResolve for glob imports.
63716
+ // https://github.com/evanw/esbuild/issues/3317
63717
+ build.onLoad({ filter, namespace: 'file' }, () => {
63718
+ const externalOnLoadResult = {
63719
+ loader: 'js',
63720
+ contents: 'export default {}',
63721
+ };
63722
+ return externalOnLoadResult;
63723
+ });
63724
+ };
63643
63725
  // css
63644
- build.onResolve({ filter: CSS_LANGS_RE }, externalUnlessEntry);
63726
+ setupExternalize(CSS_LANGS_RE, isUnlessEntry);
63645
63727
  // json & wasm
63646
- build.onResolve({ filter: /\.(json|json5|wasm)$/ }, externalUnlessEntry);
63728
+ setupExternalize(/\.(json|json5|wasm)$/, isUnlessEntry);
63647
63729
  // known asset types
63648
- build.onResolve({
63649
- filter: new RegExp(`\\.(${KNOWN_ASSET_TYPES.join('|')})$`),
63650
- }, externalUnlessEntry);
63730
+ setupExternalize(new RegExp(`\\.(${KNOWN_ASSET_TYPES.join('|')})$`), isUnlessEntry);
63651
63731
  // known vite query types: ?worker, ?raw
63652
- build.onResolve({ filter: SPECIAL_QUERY_RE }, ({ path }) => ({
63653
- path,
63654
- external: true,
63655
- }));
63732
+ setupExternalize(SPECIAL_QUERY_RE, () => true);
63656
63733
  // catch all -------------------------------------------------------------
63657
63734
  build.onResolve({
63658
63735
  filter: /.*/,
@@ -64775,7 +64852,7 @@ function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.command
64775
64852
  });
64776
64853
  }
64777
64854
  for (const o of Object.keys(meta.outputs)) {
64778
- if (!o.match(jsMapExtensionRE)) {
64855
+ if (!jsMapExtensionRE.test(o)) {
64779
64856
  const id = path$o
64780
64857
  .relative(processingCacheDirOutputPath, o)
64781
64858
  .replace(jsExtensionRE, '');
@@ -65343,7 +65420,7 @@ const isModernFlag = `__VITE_IS_MODERN__`;
65343
65420
  const preloadMethod = `__vitePreload`;
65344
65421
  const preloadMarker = `__VITE_PRELOAD__`;
65345
65422
  const preloadHelperId = '\0vite/preload-helper.js';
65346
- const preloadMarkerWithQuote = new RegExp(`['"]${preloadMarker}['"]`);
65423
+ const preloadMarkerWithQuote = new RegExp(`['"]${preloadMarker}['"]`, 'g');
65347
65424
  const dynamicImportPrefixRE = /import\s*\(/;
65348
65425
  // TODO: abstract
65349
65426
  const optimizedDepChunkRE = /\/chunk-[A-Z\d]{8}\.js/;
@@ -65353,11 +65430,9 @@ function toRelativePath(filename, importer) {
65353
65430
  return relPath[0] === '.' ? relPath : `./${relPath}`;
65354
65431
  }
65355
65432
  function indexOfMatchInSlice(str, reg, pos = 0) {
65356
- if (pos !== 0) {
65357
- str = str.slice(pos);
65358
- }
65359
- const matcher = str.match(reg);
65360
- return matcher?.index !== undefined ? matcher.index + pos : -1;
65433
+ reg.lastIndex = pos;
65434
+ const result = reg.exec(str);
65435
+ return result?.index ?? -1;
65361
65436
  }
65362
65437
  /**
65363
65438
  * Helper for preloading CSS and direct imports of async chunks in parallel to
@@ -65370,51 +65445,52 @@ function detectScriptRel() {
65370
65445
  : 'preload';
65371
65446
  }
65372
65447
  function preload(baseModule, deps, importerUrl) {
65448
+ let promise = Promise.resolve();
65373
65449
  // @ts-expect-error __VITE_IS_MODERN__ will be replaced with boolean later
65374
- if (!__VITE_IS_MODERN__ || !deps || deps.length === 0) {
65375
- return baseModule();
65376
- }
65377
- const links = document.getElementsByTagName('link');
65378
- return Promise.all(deps.map((dep) => {
65379
- // @ts-expect-error assetsURL is declared before preload.toString()
65380
- dep = assetsURL(dep, importerUrl);
65381
- if (dep in seen)
65382
- return;
65383
- seen[dep] = true;
65384
- const isCss = dep.endsWith('.css');
65385
- const cssSelector = isCss ? '[rel="stylesheet"]' : '';
65386
- const isBaseRelative = !!importerUrl;
65387
- // check if the file is already preloaded by SSR markup
65388
- if (isBaseRelative) {
65389
- // When isBaseRelative is true then we have `importerUrl` and `dep` is
65390
- // already converted to an absolute URL by the `assetsURL` function
65391
- for (let i = links.length - 1; i >= 0; i--) {
65392
- const link = links[i];
65393
- // The `links[i].href` is an absolute URL thanks to browser doing the work
65394
- // for us. See https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#reflecting-content-attributes-in-idl-attributes:idl-domstring-5
65395
- if (link.href === dep && (!isCss || link.rel === 'stylesheet')) {
65396
- return;
65450
+ if (__VITE_IS_MODERN__ && deps && deps.length > 0) {
65451
+ const links = document.getElementsByTagName('link');
65452
+ promise = Promise.all(deps.map((dep) => {
65453
+ // @ts-expect-error assetsURL is declared before preload.toString()
65454
+ dep = assetsURL(dep, importerUrl);
65455
+ if (dep in seen)
65456
+ return;
65457
+ seen[dep] = true;
65458
+ const isCss = dep.endsWith('.css');
65459
+ const cssSelector = isCss ? '[rel="stylesheet"]' : '';
65460
+ const isBaseRelative = !!importerUrl;
65461
+ // check if the file is already preloaded by SSR markup
65462
+ if (isBaseRelative) {
65463
+ // When isBaseRelative is true then we have `importerUrl` and `dep` is
65464
+ // already converted to an absolute URL by the `assetsURL` function
65465
+ for (let i = links.length - 1; i >= 0; i--) {
65466
+ const link = links[i];
65467
+ // The `links[i].href` is an absolute URL thanks to browser doing the work
65468
+ // for us. See https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#reflecting-content-attributes-in-idl-attributes:idl-domstring-5
65469
+ if (link.href === dep && (!isCss || link.rel === 'stylesheet')) {
65470
+ return;
65471
+ }
65397
65472
  }
65398
65473
  }
65399
- }
65400
- else if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) {
65401
- return;
65402
- }
65403
- const link = document.createElement('link');
65404
- link.rel = isCss ? 'stylesheet' : scriptRel;
65405
- if (!isCss) {
65406
- link.as = 'script';
65407
- link.crossOrigin = '';
65408
- }
65409
- link.href = dep;
65410
- document.head.appendChild(link);
65411
- if (isCss) {
65412
- return new Promise((res, rej) => {
65413
- link.addEventListener('load', res);
65414
- link.addEventListener('error', () => rej(new Error(`Unable to preload CSS for ${dep}`)));
65415
- });
65416
- }
65417
- }))
65474
+ else if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) {
65475
+ return;
65476
+ }
65477
+ const link = document.createElement('link');
65478
+ link.rel = isCss ? 'stylesheet' : scriptRel;
65479
+ if (!isCss) {
65480
+ link.as = 'script';
65481
+ link.crossOrigin = '';
65482
+ }
65483
+ link.href = dep;
65484
+ document.head.appendChild(link);
65485
+ if (isCss) {
65486
+ return new Promise((res, rej) => {
65487
+ link.addEventListener('load', res);
65488
+ link.addEventListener('error', () => rej(new Error(`Unable to preload CSS for ${dep}`)));
65489
+ });
65490
+ }
65491
+ }));
65492
+ }
65493
+ return promise
65418
65494
  .then(() => baseModule())
65419
65495
  .catch((err) => {
65420
65496
  const e = new Event('vite:preloadError', { cancelable: true });
@@ -65565,7 +65641,7 @@ function buildImportAnalysisPlugin(config) {
65565
65641
  const [url, resolvedId] = await normalizeUrl(specifier, start);
65566
65642
  if (url !== specifier) {
65567
65643
  if (depsOptimizer.isOptimizedDepFile(resolvedId) &&
65568
- !resolvedId.match(optimizedDepChunkRE)) {
65644
+ !optimizedDepChunkRE.test(resolvedId)) {
65569
65645
  const file = cleanUrl(resolvedId); // Remove ?v={hash}
65570
65646
  const needsInterop = await optimizedDepNeedsInterop(depsOptimizer.metadata, file, config, ssr);
65571
65647
  let rewriteDone = false;
@@ -65573,7 +65649,7 @@ function buildImportAnalysisPlugin(config) {
65573
65649
  // Non-entry dynamic imports from dependencies will reach here as there isn't
65574
65650
  // optimize info for them, but they don't need es interop. If the request isn't
65575
65651
  // a dynamic import, then it is an internal Vite error
65576
- if (!file.match(optimizedDepDynamicRE)) {
65652
+ if (!optimizedDepDynamicRE.test(file)) {
65577
65653
  config.logger.error(colors$1.red(`Vite Error, ${url} optimized info should be defined`));
65578
65654
  }
65579
65655
  }
@@ -66395,7 +66471,7 @@ function onRollupWarning(warning, warn, config) {
66395
66471
  const id = warning.id;
66396
66472
  const exporter = warning.exporter;
66397
66473
  // throw unless it's commonjs external...
66398
- if (!id || !/\?commonjs-external$/.test(id)) {
66474
+ if (!id || !id.endsWith('?commonjs-external')) {
66399
66475
  throw new Error(`[vite]: Rollup failed to resolve import "${exporter}" from "${id}".\n` +
66400
66476
  `This is most likely unintended because it can break your application at runtime.\n` +
66401
66477
  `If you do want to externalize this module explicitly add it to\n` +