vite 4.2.1 → 4.3.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of vite might be problematic. Click here for more details.

@@ -1,13 +1,13 @@
1
1
  import fs$l, { promises as promises$2 } from 'node:fs';
2
2
  import path$o, { posix as posix$1, isAbsolute as isAbsolute$2, join as join$2, relative as relative$2, dirname as dirname$2, basename as basename$2, extname as extname$1 } from 'node:path';
3
3
  import { URL as URL$3, URLSearchParams, parse as parse$i, pathToFileURL } from 'node:url';
4
- import { performance } from 'node:perf_hooks';
4
+ import { performance as performance$1 } from 'node:perf_hooks';
5
5
  import { createRequire as createRequire$1, builtinModules } from 'node:module';
6
6
  import require$$0$3 from 'tty';
7
7
  import esbuild, { transform as transform$2, formatMessages, build as build$3 } from 'esbuild';
8
- import require$$0$4, { win32, posix, isAbsolute as isAbsolute$1, resolve as resolve$3, relative as relative$1, basename as basename$1, extname, dirname as dirname$1, join as join$1, sep, normalize } from 'path';
8
+ import require$$0$4, { win32, posix, isAbsolute as isAbsolute$1, resolve as resolve$3, relative as relative$1, basename as basename$1, extname, dirname as dirname$1, join as join$1, sep as sep$1, normalize } from 'path';
9
9
  import * as require$$0$2 from 'fs';
10
- import require$$0__default, { existsSync, readFileSync, statSync as statSync$1, promises as promises$1, readdirSync } from 'fs';
10
+ import require$$0__default, { existsSync, readFileSync, statSync as statSync$1, promises as promises$1, readdir as readdir$4, readdirSync } from 'fs';
11
11
  import require$$0$5 from 'events';
12
12
  import require$$5 from 'assert';
13
13
  import require$$0$6 from 'util';
@@ -22,7 +22,7 @@ import { createHash as createHash$2 } from 'node:crypto';
22
22
  import { promisify as promisify$4, format as format$2, inspect } from 'node:util';
23
23
  import { promises } from 'node:dns';
24
24
  import resolve$4 from 'resolve';
25
- import { CLIENT_ENTRY, OPTIMIZABLE_ENTRY_RE, DEFAULT_EXTENSIONS as DEFAULT_EXTENSIONS$1, wildcardHosts, loopbackHosts, VALID_ID_PREFIX, NULL_BYTE_PLACEHOLDER, FS_PREFIX, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH, ENV_ENTRY, DEFAULT_MAIN_FIELDS, SPECIAL_QUERY_RE, DEP_VERSION_RE, CSS_LANGS_RE, KNOWN_ASSET_TYPES, CLIENT_DIR, JS_TYPES_RE, ESBUILD_MODULES_TARGET, VERSION as VERSION$1, VITE_PACKAGE_DIR, DEFAULT_DEV_PORT, DEFAULT_PREVIEW_PORT, DEFAULT_ASSETS_RE, DEFAULT_CONFIG_FILES } from '../constants.js';
25
+ import { CLIENT_ENTRY, OPTIMIZABLE_ENTRY_RE, wildcardHosts, loopbackHosts, VALID_ID_PREFIX, NULL_BYTE_PLACEHOLDER, FS_PREFIX, DEFAULT_EXTENSIONS as DEFAULT_EXTENSIONS$1, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH, ENV_ENTRY, DEFAULT_MAIN_FIELDS, SPECIAL_QUERY_RE, DEP_VERSION_RE, CSS_LANGS_RE, KNOWN_ASSET_TYPES, CLIENT_DIR, JS_TYPES_RE, ESBUILD_MODULES_TARGET, VERSION as VERSION$1, VITE_PACKAGE_DIR, DEFAULT_DEV_PORT, DEFAULT_PREVIEW_PORT, DEFAULT_ASSETS_RE, DEFAULT_CONFIG_FILES } from '../constants.js';
26
26
  import require$$5$1 from 'crypto';
27
27
  import { Buffer as Buffer$1 } from 'node:buffer';
28
28
  import fsp from 'node:fs/promises';
@@ -40,7 +40,7 @@ import { createServer as createServer$2 } from 'node:https';
40
40
  import { VERSION } from 'rollup';
41
41
  import * as qs from 'querystring';
42
42
  import readline from 'node:readline';
43
- import { execSync } from 'node:child_process';
43
+ import { exec } from 'node:child_process';
44
44
  import zlib$1, { gzip } from 'node:zlib';
45
45
 
46
46
  import { fileURLToPath as __cjs_fileURLToPath } from 'node:url';
@@ -425,7 +425,7 @@ let SyncWalker$1 = class SyncWalker extends WalkerBase$1 {
425
425
  * }} walker
426
426
  * @returns {BaseNode}
427
427
  */
428
- function walk$3(ast, { enter, leave }) {
428
+ function walk$4(ast, { enter, leave }) {
429
429
  const instance = new SyncWalker$1(enter, leave);
430
430
  return instance.visit(ast, null);
431
431
  }
@@ -2573,7 +2573,7 @@ let Scope$1 = class Scope {
2573
2573
  };
2574
2574
  const attachScopes = function attachScopes(ast, propertyName = 'scope') {
2575
2575
  let scope = new Scope$1();
2576
- walk$3(ast, {
2576
+ walk$4(ast, {
2577
2577
  enter(n, parent) {
2578
2578
  const node = n;
2579
2579
  // function foo () {...}
@@ -7892,7 +7892,7 @@ function getEsImportProxy(id, defaultIsModuleExports) {
7892
7892
  /* eslint-disable no-param-reassign, no-undefined */
7893
7893
 
7894
7894
  function getCandidatesForExtension(resolved, extension) {
7895
- return [resolved + extension, `${resolved}${sep}index${extension}`];
7895
+ return [resolved + extension, `${resolved}${sep$1}index${extension}`];
7896
7896
  }
7897
7897
 
7898
7898
  function getCandidates(resolved, extensions) {
@@ -8907,7 +8907,7 @@ async function transformCommonjs(
8907
8907
  const importedVariables = new Set();
8908
8908
  const indentExclusionRanges = [];
8909
8909
 
8910
- walk$3(ast, {
8910
+ walk$4(ast, {
8911
8911
  enter(node, parent) {
8912
8912
  if (skippedNodes.has(node)) {
8913
8913
  this.skip();
@@ -11541,8 +11541,9 @@ function requireNode$1 () {
11541
11541
  var _debug = /*@__PURE__*/getDefaultExportFromCjs(srcExports$1);
11542
11542
 
11543
11543
  const createFilter = createFilter$1;
11544
+ const windowsSlashRE = /\\/g;
11544
11545
  function slash$1(p) {
11545
- return p.replace(/\\/g, '/');
11546
+ return p.replace(windowsSlashRE, '/');
11546
11547
  }
11547
11548
  /**
11548
11549
  * Prepend `/@id/` and replace null byte so the id is URL-safe.
@@ -11562,12 +11563,16 @@ function unwrapId(id) {
11562
11563
  ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, '\0')
11563
11564
  : id;
11564
11565
  }
11566
+ const replaceSlashOrColonRE = /[/:]/g;
11567
+ const replaceDotRE = /\./g;
11568
+ const replaceNestedIdRE = /(\s*>\s*)/g;
11569
+ const replaceHashRE = /#/g;
11565
11570
  const flattenId = (id) => id
11566
- .replace(/[/:]/g, '_')
11567
- .replace(/\./g, '__')
11568
- .replace(/(\s*>\s*)/g, '___')
11569
- .replace(/#/g, '____');
11570
- const normalizeId = (id) => id.replace(/(\s*>\s*)/g, ' > ');
11571
+ .replace(replaceSlashOrColonRE, '_')
11572
+ .replace(replaceDotRE, '__')
11573
+ .replace(replaceNestedIdRE, '___')
11574
+ .replace(replaceHashRE, '____');
11575
+ const normalizeId = (id) => id.replace(replaceNestedIdRE, ' > ');
11571
11576
  //TODO: revisit later to see if the edge case that "compiling using node v12 code to be run in node v16 in the server" is what we intend to support.
11572
11577
  const builtins = new Set([
11573
11578
  ...builtinModules,
@@ -11585,8 +11590,11 @@ const builtins = new Set([
11585
11590
  'util/types',
11586
11591
  'wasi',
11587
11592
  ]);
11593
+ const NODE_BUILTIN_NAMESPACE = 'node:';
11588
11594
  function isBuiltin(id) {
11589
- return builtins.has(id.replace(/^node:/, ''));
11595
+ return builtins.has(id.startsWith(NODE_BUILTIN_NAMESPACE)
11596
+ ? id.slice(NODE_BUILTIN_NAMESPACE.length)
11597
+ : id);
11590
11598
  }
11591
11599
  function moduleListContains(moduleList, id) {
11592
11600
  return moduleList?.some((m) => m === id || id.startsWith(m + '/'));
@@ -11597,13 +11605,9 @@ function isOptimizable(id, optimizeDeps) {
11597
11605
  (extensions?.some((ext) => id.endsWith(ext)) ?? false));
11598
11606
  }
11599
11607
  const bareImportRE = /^[\w@](?!.*:\/\/)/;
11600
- let isRunningWithYarnPnp;
11608
+ const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//;
11601
11609
  // TODO: use import()
11602
11610
  const _require$3 = createRequire$1(import.meta.url);
11603
- try {
11604
- isRunningWithYarnPnp = Boolean(_require$3('pnpapi'));
11605
- }
11606
- catch { }
11607
11611
  const ssrExtensions = ['.js', '.cjs', '.json', '.node'];
11608
11612
  function resolveFrom(id, basedir, preserveSymlinks = false, ssr = false) {
11609
11613
  return resolve$4.sync(id, {
@@ -11611,23 +11615,9 @@ function resolveFrom(id, basedir, preserveSymlinks = false, ssr = false) {
11611
11615
  paths: [],
11612
11616
  extensions: ssr ? ssrExtensions : DEFAULT_EXTENSIONS$1,
11613
11617
  // necessary to work with pnpm
11614
- preserveSymlinks: preserveSymlinks || isRunningWithYarnPnp || false,
11618
+ preserveSymlinks: preserveSymlinks || !!process.versions.pnp || false,
11615
11619
  });
11616
11620
  }
11617
- /**
11618
- * like `resolveFrom` but supports resolving `>` path in `id`,
11619
- * for example: `foo > bar > baz`
11620
- */
11621
- function nestedResolveFrom(id, basedir, preserveSymlinks = false, ssr = false) {
11622
- const pkgs = id.split('>').map((pkg) => pkg.trim());
11623
- try {
11624
- for (const pkg of pkgs) {
11625
- basedir = resolveFrom(pkg, basedir, preserveSymlinks, ssr);
11626
- }
11627
- }
11628
- catch { }
11629
- return basedir;
11630
- }
11631
11621
  // set in bin/vite.js
11632
11622
  const filter = process.env.VITE_DEBUG_FILTER;
11633
11623
  const DEBUG = process.env.DEBUG;
@@ -11655,6 +11645,15 @@ function testCaseInsensitiveFS() {
11655
11645
  }
11656
11646
  return fs$l.existsSync(CLIENT_ENTRY.replace('client.mjs', 'cLiEnT.mjs'));
11657
11647
  }
11648
+ function isUrl(path) {
11649
+ try {
11650
+ new URL$3(path);
11651
+ return true;
11652
+ }
11653
+ catch {
11654
+ return false;
11655
+ }
11656
+ }
11658
11657
  const isCaseInsensitiveFS = testCaseInsensitiveFS();
11659
11658
  const isWindows$4 = os$3.platform() === 'win32';
11660
11659
  const VOLUME_RE = /^[A-Z]:/i;
@@ -11663,9 +11662,7 @@ function normalizePath$3(id) {
11663
11662
  }
11664
11663
  function fsPathFromId(id) {
11665
11664
  const fsPath = normalizePath$3(id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id);
11666
- return fsPath.startsWith('/') || fsPath.match(VOLUME_RE)
11667
- ? fsPath
11668
- : `/${fsPath}`;
11665
+ return fsPath[0] === '/' || fsPath.match(VOLUME_RE) ? fsPath : `/${fsPath}`;
11669
11666
  }
11670
11667
  function fsPathFromUrl(url) {
11671
11668
  return fsPathFromId(cleanUrl(url));
@@ -11680,7 +11677,7 @@ function fsPathFromUrl(url) {
11680
11677
  * @returns true if dir is a parent of file
11681
11678
  */
11682
11679
  function isParentDirectory(dir, file) {
11683
- if (!dir.endsWith('/')) {
11680
+ if (dir[dir.length - 1] !== '/') {
11684
11681
  dir = `${dir}/`;
11685
11682
  }
11686
11683
  return (file.startsWith(dir) ||
@@ -11704,7 +11701,7 @@ const isJSRequest = (url) => {
11704
11701
  if (knownJsSrcRE.test(url)) {
11705
11702
  return true;
11706
11703
  }
11707
- if (!path$o.extname(url) && !url.endsWith('/')) {
11704
+ if (!path$o.extname(url) && url[url.length - 1] !== '/') {
11708
11705
  return true;
11709
11706
  }
11710
11707
  return false;
@@ -11713,10 +11710,11 @@ const knownTsRE = /\.(?:ts|mts|cts|tsx)$/;
11713
11710
  const knownTsOutputRE = /\.(?:js|mjs|cjs|jsx)$/;
11714
11711
  const isTsRequest = (url) => knownTsRE.test(url);
11715
11712
  const isPossibleTsOutput = (url) => knownTsOutputRE.test(cleanUrl(url));
11713
+ const splitFilePathAndQueryRE = /(\.(?:[cm]?js|jsx))(\?.*)?$/;
11716
11714
  function getPotentialTsSrcPaths(filePath) {
11717
- const [name, type, query = ''] = filePath.split(/(\.(?:[cm]?js|jsx))(\?.*)?$/);
11715
+ const [name, type, query = ''] = filePath.split(splitFilePathAndQueryRE);
11718
11716
  const paths = [name + type.replace('js', 'ts') + query];
11719
- if (!type.endsWith('x')) {
11717
+ if (type[type.length - 1] !== 'x') {
11720
11718
  paths.push(name + type.replace('js', 'tsx') + query);
11721
11719
  }
11722
11720
  return paths;
@@ -11739,10 +11737,11 @@ function removeImportQuery(url) {
11739
11737
  function removeDirectQuery(url) {
11740
11738
  return url.replace(directRequestRE$1, '$1').replace(trailingSeparatorRE, '');
11741
11739
  }
11740
+ const replacePercentageRE = /%/g;
11742
11741
  function injectQuery(url, queryToInject) {
11743
11742
  // encode percents for consistent behavior with pathToFileURL
11744
11743
  // see #2614 for details
11745
- const resolvedUrl = new URL$3(url.replace(/%/g, '%25'), 'relative:///');
11744
+ const resolvedUrl = new URL$3(url.replace(replacePercentageRE, '%25'), 'relative:///');
11746
11745
  const { search, hash } = resolvedUrl;
11747
11746
  let pathname = cleanUrl(url);
11748
11747
  pathname = isWindows$4 ? slash$1(pathname) : pathname;
@@ -11765,7 +11764,7 @@ async function asyncReplace(input, re, replacer) {
11765
11764
  return rewritten;
11766
11765
  }
11767
11766
  function timeFrom(start, subtract = 0) {
11768
- const time = performance.now() - start - subtract;
11767
+ const time = performance$1.now() - start - subtract;
11769
11768
  const timeString = (time.toFixed(2) + `ms`).padEnd(5, ' ');
11770
11769
  if (time < 10) {
11771
11770
  return picocolorsExports.green(timeString);
@@ -11784,17 +11783,7 @@ function prettifyUrl(url, root) {
11784
11783
  url = removeTimestampQuery(url);
11785
11784
  const isAbsoluteFile = url.startsWith(root);
11786
11785
  if (isAbsoluteFile || url.startsWith(FS_PREFIX)) {
11787
- let file = path$o.relative(root, isAbsoluteFile ? url : fsPathFromId(url));
11788
- const seg = file.split('/');
11789
- const npmIndex = seg.indexOf(`node_modules`);
11790
- const isSourceMap = file.endsWith('.map');
11791
- if (npmIndex > 0) {
11792
- file = seg[npmIndex + 1];
11793
- if (file.startsWith('@')) {
11794
- file = `${file}/${seg[npmIndex + 2]}`;
11795
- }
11796
- file = `npm: ${picocolorsExports.dim(file)}${isSourceMap ? ` (source map)` : ``}`;
11797
- }
11786
+ const file = path$o.relative(root, isAbsoluteFile ? url : fsPathFromId(url));
11798
11787
  return picocolorsExports.dim(file);
11799
11788
  }
11800
11789
  else {
@@ -11982,6 +11971,12 @@ const removeDir = isWindows$4
11982
11971
  }
11983
11972
  };
11984
11973
  const renameDir = isWindows$4 ? promisify$4(gracefulRename) : fs$l.renameSync;
11974
+ // `fs.realpathSync.native` resolves differently in Windows network drive,
11975
+ // causing file read errors. skip for now.
11976
+ // https://github.com/nodejs/node/issues/37737
11977
+ const safeRealpathSync = isWindows$4
11978
+ ? fs$l.realpathSync
11979
+ : fs$l.realpathSync.native;
11985
11980
  function ensureWatchedFile(watcher, file, root) {
11986
11981
  if (file &&
11987
11982
  // only need to watch if out of root
@@ -12026,10 +12021,11 @@ function processSrcSetSync(srcs, replacer) {
12026
12021
  descriptor,
12027
12022
  })));
12028
12023
  }
12024
+ const cleanSrcSetRE = /(?:url|image|gradient|cross-fade)\([^)]*\)|"([^"]|(?<=\\)")*"|'([^']|(?<=\\)')*'/g;
12029
12025
  function splitSrcSet(srcs) {
12030
12026
  const parts = [];
12031
12027
  // There could be a ',' inside of url(data:...), linear-gradient(...) or "data:..."
12032
- const cleanedSrcs = srcs.replace(/(?:url|image|gradient|cross-fade)\([^)]*\)|"([^"]|(?<=\\)")*"|'([^']|(?<=\\)')*'/g, blankReplacer);
12028
+ const cleanedSrcs = srcs.replace(cleanSrcSetRE, blankReplacer);
12033
12029
  let startIndex = 0;
12034
12030
  let splitIndex;
12035
12031
  do {
@@ -12039,21 +12035,25 @@ function splitSrcSet(srcs) {
12039
12035
  } while (splitIndex !== -1);
12040
12036
  return parts;
12041
12037
  }
12038
+ const windowsDriveRE = /^[A-Z]:/;
12039
+ const replaceWindowsDriveRE = /^([A-Z]):\//;
12040
+ const linuxAbsolutePathRE = /^\/[^/]/;
12042
12041
  function escapeToLinuxLikePath(path) {
12043
- if (/^[A-Z]:/.test(path)) {
12044
- return path.replace(/^([A-Z]):\//, '/windows/$1/');
12042
+ if (windowsDriveRE.test(path)) {
12043
+ return path.replace(replaceWindowsDriveRE, '/windows/$1/');
12045
12044
  }
12046
- if (/^\/[^/]/.test(path)) {
12045
+ if (linuxAbsolutePathRE.test(path)) {
12047
12046
  return `/linux${path}`;
12048
12047
  }
12049
12048
  return path;
12050
12049
  }
12050
+ const revertWindowsDriveRE = /^\/windows\/([A-Z])\//;
12051
12051
  function unescapeToLinuxLikePath(path) {
12052
12052
  if (path.startsWith('/linux/')) {
12053
12053
  return path.slice('/linux'.length);
12054
12054
  }
12055
12055
  if (path.startsWith('/windows/')) {
12056
- return path.replace(/^\/windows\/([A-Z])\//, '$1:/');
12056
+ return path.replace(revertWindowsDriveRE, '$1:/');
12057
12057
  }
12058
12058
  return path;
12059
12059
  }
@@ -12373,8 +12373,8 @@ function normalizeAlias(o = []) {
12373
12373
  // work around https://github.com/rollup/plugins/issues/759
12374
12374
  function normalizeSingleAlias({ find, replacement, customResolver, }) {
12375
12375
  if (typeof find === 'string' &&
12376
- find.endsWith('/') &&
12377
- replacement.endsWith('/')) {
12376
+ find[find.length - 1] === '/' &&
12377
+ replacement[replacement.length - 1] === '/') {
12378
12378
  find = find.slice(0, find.length - 1);
12379
12379
  replacement = replacement.slice(0, replacement.length - 1);
12380
12380
  }
@@ -12419,7 +12419,7 @@ const windowsDrivePathPrefixRE = /^[A-Za-z]:[/\\]/;
12419
12419
  */
12420
12420
  const isNonDriveRelativeAbsolutePath = (p) => {
12421
12421
  if (!isWindows$4)
12422
- return p.startsWith('/');
12422
+ return p[0] === '/';
12423
12423
  return windowsDrivePathPrefixRE.test(p);
12424
12424
  };
12425
12425
  /**
@@ -12449,20 +12449,23 @@ function joinUrlSegments(a, b) {
12449
12449
  if (!a || !b) {
12450
12450
  return a || b || '';
12451
12451
  }
12452
- if (a.endsWith('/')) {
12452
+ if (a[a.length - 1] === '/') {
12453
12453
  a = a.substring(0, a.length - 1);
12454
12454
  }
12455
- if (!b.startsWith('/')) {
12455
+ if (b[0] !== '/') {
12456
12456
  b = '/' + b;
12457
12457
  }
12458
12458
  return a + b;
12459
12459
  }
12460
+ function removeLeadingSlash(str) {
12461
+ return str[0] === '/' ? str.slice(1) : str;
12462
+ }
12460
12463
  function stripBase(path, base) {
12461
12464
  if (path === base) {
12462
12465
  return '/';
12463
12466
  }
12464
- const devBase = base.endsWith('/') ? base : base + '/';
12465
- return path.replace(RegExp('^' + devBase), '/');
12467
+ const devBase = base[base.length - 1] === '/' ? base : base + '/';
12468
+ return path.startsWith(devBase) ? path.slice(devBase.length - 1) : path;
12466
12469
  }
12467
12470
  function arrayEqual(a, b) {
12468
12471
  if (a === b)
@@ -12482,6 +12485,10 @@ function evalValue(rawValue) {
12482
12485
  `);
12483
12486
  return fn();
12484
12487
  }
12488
+ const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g;
12489
+ function escapeRegex(str) {
12490
+ return str.replace(escapeRegexRE, '\\$&');
12491
+ }
12485
12492
 
12486
12493
  /* eslint no-console: 0 */
12487
12494
  const LogLevels = {
@@ -12876,32 +12883,46 @@ async function tsconfigInDir(dir, options) {
12876
12883
  }
12877
12884
  }
12878
12885
  }
12886
+ var sep = require$$0$4.sep;
12879
12887
  async function findAll(dir, options) {
12880
- const files = [];
12881
- for await (const tsconfigFile of findTSConfig(require$$0$4.resolve(dir), options)) {
12882
- files.push(tsconfigFile);
12883
- }
12884
- return files;
12888
+ const state = {
12889
+ files: [],
12890
+ calls: 0,
12891
+ skip: options == null ? void 0 : options.skip,
12892
+ err: false
12893
+ };
12894
+ return new Promise((resolve, reject) => {
12895
+ walk$3(require$$0$4.resolve(dir), state, (err, files) => err ? reject(err) : resolve(files));
12896
+ });
12885
12897
  }
12886
- async function* findTSConfig(dir, options, visited = /* @__PURE__ */ new Set()) {
12887
- if (!visited.has(dir)) {
12888
- visited.add(dir);
12889
- try {
12890
- const dirents = await promises$1.readdir(dir, { withFileTypes: true });
12891
- for (const dirent of dirents) {
12892
- if (dirent.isDirectory() && (!(options == null ? void 0 : options.skip) || !options.skip(dirent.name))) {
12893
- yield* findTSConfig(require$$0$4.resolve(dir, dirent.name), options, visited);
12894
- } else if (dirent.isFile() && dirent.name === "tsconfig.json") {
12895
- yield require$$0$4.resolve(dir, dirent.name);
12898
+ function walk$3(dir, state, done) {
12899
+ if (state.err) {
12900
+ return;
12901
+ }
12902
+ state.calls++;
12903
+ readdir$4(dir, { withFileTypes: true }, (err, entries = []) => {
12904
+ var _a;
12905
+ if (state.err) {
12906
+ return;
12907
+ }
12908
+ if (err && !(err.code === "ENOENT" || err.code === "EACCES")) {
12909
+ state.err = true;
12910
+ done(err);
12911
+ } else {
12912
+ for (const ent of entries) {
12913
+ if (ent.isDirectory() && !((_a = state.skip) == null ? void 0 : _a.call(state, ent.name))) {
12914
+ walk$3(`${dir}${sep}${ent.name}`, state, done);
12915
+ } else if (ent.isFile() && ent.name === "tsconfig.json") {
12916
+ state.files.push(`${dir}${sep}tsconfig.json`);
12896
12917
  }
12897
12918
  }
12898
- } catch (e) {
12899
- if (e.code === "EACCES" || e.code === "ENOENT") {
12900
- return;
12919
+ if (--state.calls === 0) {
12920
+ if (!state.err) {
12921
+ done(null, state.files);
12922
+ }
12901
12923
  }
12902
- throw e;
12903
12924
  }
12904
- }
12925
+ });
12905
12926
  }
12906
12927
 
12907
12928
  // src/to-json.ts
@@ -13395,9 +13416,12 @@ var TSConfckParseError = class extends Error {
13395
13416
  }
13396
13417
  };
13397
13418
 
13398
- const debug$f = createDebugger('vite:esbuild');
13419
+ const isDebug$6 = process.env.DEBUG;
13420
+ const debug$e = createDebugger('vite:esbuild');
13399
13421
  const INJECT_HELPERS_IIFE_RE = /^(.*?)((?:const|var)\s+\S+\s*=\s*function\s*\([^)]*\)\s*\{.*?"use strict";)/s;
13400
13422
  const INJECT_HELPERS_UMD_RE = /^(.*?)(\(function\([^)]*\)\s*\{.+?amd.+?function\([^)]*\)\s*\{.*?"use strict";)/s;
13423
+ const validExtensionRE = /\.\w+$/;
13424
+ const jsxExtensionsRE = /\.(?:j|t)sx\b/;
13401
13425
  let server;
13402
13426
  async function transformWithEsbuild(code, filename, options, inMap) {
13403
13427
  let loader = options?.loader;
@@ -13405,7 +13429,7 @@ async function transformWithEsbuild(code, filename, options, inMap) {
13405
13429
  // if the id ends with a valid ext, use it (e.g. vue blocks)
13406
13430
  // otherwise, cleanup the query before checking the ext
13407
13431
  const ext = path$o
13408
- .extname(/\.\w+$/.test(filename) ? filename : cleanUrl(filename))
13432
+ .extname(validExtensionRE.test(filename) ? filename : cleanUrl(filename))
13409
13433
  .slice(1);
13410
13434
  if (ext === 'cjs' || ext === 'mjs') {
13411
13435
  loader = 'js';
@@ -13444,30 +13468,37 @@ async function transformWithEsbuild(code, filename, options, inMap) {
13444
13468
  }
13445
13469
  }
13446
13470
  }
13447
- tsconfigRaw = {
13448
- ...tsconfigRaw,
13449
- compilerOptions: {
13450
- ...compilerOptionsForFile,
13451
- ...tsconfigRaw?.compilerOptions,
13452
- },
13471
+ const compilerOptions = {
13472
+ ...compilerOptionsForFile,
13473
+ ...tsconfigRaw?.compilerOptions,
13453
13474
  };
13454
- const { compilerOptions } = tsconfigRaw;
13455
- if (compilerOptions) {
13456
- // esbuild derives `useDefineForClassFields` from `target` instead of `tsconfig.compilerOptions.target`
13457
- // https://github.com/evanw/esbuild/issues/2584
13458
- // but we want `useDefineForClassFields` to be derived from `tsconfig.compilerOptions.target`
13459
- if (compilerOptions.useDefineForClassFields === undefined) {
13460
- const lowercaseTarget = compilerOptions.target?.toLowerCase() ?? 'es3';
13461
- if (lowercaseTarget.startsWith('es')) {
13462
- const esVersion = lowercaseTarget.slice(2);
13463
- compilerOptions.useDefineForClassFields =
13464
- esVersion === 'next' || +esVersion >= 2022;
13465
- }
13466
- else {
13467
- compilerOptions.useDefineForClassFields = false;
13468
- }
13475
+ // esbuild derives `useDefineForClassFields` from `target` instead of `tsconfig.compilerOptions.target`
13476
+ // https://github.com/evanw/esbuild/issues/2584
13477
+ // but we want `useDefineForClassFields` to be derived from `tsconfig.compilerOptions.target`
13478
+ if (compilerOptions.useDefineForClassFields === undefined) {
13479
+ const lowercaseTarget = compilerOptions.target?.toLowerCase() ?? 'es3';
13480
+ if (lowercaseTarget.startsWith('es')) {
13481
+ const esVersion = lowercaseTarget.slice(2);
13482
+ compilerOptions.useDefineForClassFields =
13483
+ esVersion === 'next' || +esVersion >= 2022;
13484
+ }
13485
+ else {
13486
+ compilerOptions.useDefineForClassFields = false;
13469
13487
  }
13470
13488
  }
13489
+ // esbuild uses tsconfig fields when both the normal options and tsconfig was set
13490
+ // but we want to prioritize the normal options
13491
+ if (options) {
13492
+ options.jsx && (compilerOptions.jsx = undefined);
13493
+ options.jsxFactory && (compilerOptions.jsxFactory = undefined);
13494
+ options.jsxFragment && (compilerOptions.jsxFragmentFactory = undefined);
13495
+ options.jsxImportSource && (compilerOptions.jsxImportSource = undefined);
13496
+ options.target && (compilerOptions.target = undefined);
13497
+ }
13498
+ tsconfigRaw = {
13499
+ ...tsconfigRaw,
13500
+ compilerOptions,
13501
+ };
13471
13502
  }
13472
13503
  const resolvedOptions = {
13473
13504
  sourcemap: true,
@@ -13477,22 +13508,8 @@ async function transformWithEsbuild(code, filename, options, inMap) {
13477
13508
  loader,
13478
13509
  tsconfigRaw,
13479
13510
  };
13480
- // esbuild uses tsconfig fields when both the normal options and tsconfig was set
13481
- // but we want to prioritize the normal options
13482
- if (options &&
13483
- typeof resolvedOptions.tsconfigRaw === 'object' &&
13484
- resolvedOptions.tsconfigRaw.compilerOptions) {
13485
- options.jsx && (resolvedOptions.tsconfigRaw.compilerOptions.jsx = undefined);
13486
- options.jsxFactory &&
13487
- (resolvedOptions.tsconfigRaw.compilerOptions.jsxFactory = undefined);
13488
- options.jsxFragment &&
13489
- (resolvedOptions.tsconfigRaw.compilerOptions.jsxFragmentFactory =
13490
- undefined);
13491
- options.jsxImportSource &&
13492
- (resolvedOptions.tsconfigRaw.compilerOptions.jsxImportSource = undefined);
13493
- options.target &&
13494
- (resolvedOptions.tsconfigRaw.compilerOptions.target = undefined);
13495
- }
13511
+ // Some projects in the ecosystem are calling this function with an ESBuildOptions
13512
+ // object and esbuild throws an error for extra fields
13496
13513
  delete resolvedOptions.include;
13497
13514
  delete resolvedOptions.exclude;
13498
13515
  delete resolvedOptions.jsxInject;
@@ -13519,7 +13536,7 @@ async function transformWithEsbuild(code, filename, options, inMap) {
13519
13536
  };
13520
13537
  }
13521
13538
  catch (e) {
13522
- debug$f(`esbuild error with options used: `, resolvedOptions);
13539
+ debug$e(`esbuild error with options used: `, resolvedOptions);
13523
13540
  // patch error information
13524
13541
  if (e.errors) {
13525
13542
  e.frame = '';
@@ -13531,14 +13548,16 @@ async function transformWithEsbuild(code, filename, options, inMap) {
13531
13548
  throw e;
13532
13549
  }
13533
13550
  }
13534
- function esbuildPlugin(options) {
13535
- const filter = createFilter(options.include || /\.(m?ts|[jt]sx)$/, options.exclude || /\.js$/);
13551
+ function esbuildPlugin(config) {
13552
+ const options = config.esbuild;
13553
+ const { jsxInject, include, exclude, ...esbuildTransformOptions } = options;
13554
+ const filter = createFilter(include || /\.(m?ts|[jt]sx)$/, exclude || /\.js$/);
13536
13555
  // Remove optimization options for dev as we only need to transpile them,
13537
13556
  // and for build as the final optimization is in `buildEsbuildPlugin`
13538
13557
  const transformOptions = {
13539
13558
  target: 'esnext',
13540
13559
  charset: 'utf8',
13541
- ...options,
13560
+ ...esbuildTransformOptions,
13542
13561
  minify: false,
13543
13562
  minifyIdentifiers: false,
13544
13563
  minifySyntax: false,
@@ -13549,6 +13568,7 @@ function esbuildPlugin(options) {
13549
13568
  // tree-shaking. (#9164)
13550
13569
  keepNames: false,
13551
13570
  };
13571
+ initTSConfck(config.root);
13552
13572
  return {
13553
13573
  name: 'vite:esbuild',
13554
13574
  configureServer(_server) {
@@ -13558,9 +13578,6 @@ function esbuildPlugin(options) {
13558
13578
  .on('change', reloadOnTsconfigChange)
13559
13579
  .on('unlink', reloadOnTsconfigChange);
13560
13580
  },
13561
- async configResolved(config) {
13562
- await initTSConfck(config);
13563
- },
13564
13581
  buildEnd() {
13565
13582
  // recycle serve to avoid preventing Node self-exit (#6815)
13566
13583
  server = null;
@@ -13573,8 +13590,8 @@ function esbuildPlugin(options) {
13573
13590
  this.warn(prettifyMessage(m, code));
13574
13591
  });
13575
13592
  }
13576
- if (options.jsxInject && /\.(?:j|t)sx\b/.test(id)) {
13577
- result.code = options.jsxInject + ';' + result.code;
13593
+ if (jsxInject && jsxExtensionsRE.test(id)) {
13594
+ result.code = jsxInject + ';' + result.code;
13578
13595
  }
13579
13596
  return {
13580
13597
  code: result.code,
@@ -13598,11 +13615,9 @@ const rollupToEsbuildFormatMap = {
13598
13615
  iife: undefined,
13599
13616
  };
13600
13617
  const buildEsbuildPlugin = (config) => {
13618
+ initTSConfck(config.root);
13601
13619
  return {
13602
13620
  name: 'vite:esbuild-transpile',
13603
- async configResolved(config) {
13604
- await initTSConfck(config);
13605
- },
13606
13621
  async renderChunk(code, chunk, opts) {
13607
13622
  // @ts-expect-error injected by @vitejs/plugin-legacy
13608
13623
  if (opts.__vite_skip_esbuild__) {
@@ -13728,27 +13743,38 @@ function prettifyMessage(m, code) {
13728
13743
  }
13729
13744
  return res + `\n`;
13730
13745
  }
13731
- const tsconfckParseOptions = {
13732
- cache: new Map(),
13733
- tsConfigPaths: undefined,
13734
- root: undefined,
13735
- resolveWithEmptyIfConfigNotFound: true,
13736
- };
13737
- async function initTSConfck(config) {
13738
- const workspaceRoot = searchForWorkspaceRoot(config.root);
13739
- debug$f(`init tsconfck (root: ${picocolorsExports.cyan(workspaceRoot)})`);
13740
- tsconfckParseOptions.cache.clear();
13741
- tsconfckParseOptions.root = workspaceRoot;
13742
- tsconfckParseOptions.tsConfigPaths = new Set([
13743
- ...(await findAll(workspaceRoot, {
13746
+ let tsconfckRoot;
13747
+ let tsconfckParseOptions = { resolveWithEmptyIfConfigNotFound: true };
13748
+ function initTSConfck(root, force = false) {
13749
+ // bail if already cached
13750
+ if (!force && root === tsconfckRoot)
13751
+ return;
13752
+ const workspaceRoot = searchForWorkspaceRoot(root);
13753
+ tsconfckRoot = root;
13754
+ tsconfckParseOptions = initTSConfckParseOptions(workspaceRoot);
13755
+ // cached as the options value itself when promise is resolved
13756
+ tsconfckParseOptions.then((options) => {
13757
+ if (root === tsconfckRoot) {
13758
+ tsconfckParseOptions = options;
13759
+ }
13760
+ });
13761
+ }
13762
+ async function initTSConfckParseOptions(workspaceRoot) {
13763
+ const start = isDebug$6 ? performance.now() : 0;
13764
+ const options = {
13765
+ cache: new Map(),
13766
+ root: workspaceRoot,
13767
+ tsConfigPaths: new Set(await findAll(workspaceRoot, {
13744
13768
  skip: (dir) => dir === 'node_modules' || dir === '.git',
13745
13769
  })),
13746
- ]);
13747
- debug$f(`init tsconfck end`);
13770
+ resolveWithEmptyIfConfigNotFound: true,
13771
+ };
13772
+ isDebug$6 && debug$e(timeFrom(start), 'tsconfck init', picocolorsExports.dim(workspaceRoot));
13773
+ return options;
13748
13774
  }
13749
13775
  async function loadTsconfigJsonForFile(filename) {
13750
13776
  try {
13751
- const result = await parse$f(filename, tsconfckParseOptions);
13777
+ const result = await parse$f(filename, await tsconfckParseOptions);
13752
13778
  // tsconfig could be out of root, make sure it is watched on dev
13753
13779
  if (server && result.tsconfigFile !== 'no_tsconfig_file_found') {
13754
13780
  ensureWatchedFile(server.watcher, result.tsconfigFile, server.config.root);
@@ -13765,7 +13791,7 @@ async function loadTsconfigJsonForFile(filename) {
13765
13791
  throw e;
13766
13792
  }
13767
13793
  }
13768
- function reloadOnTsconfigChange(changedFile) {
13794
+ async function reloadOnTsconfigChange(changedFile) {
13769
13795
  // server could be closed externally after a file change is detected
13770
13796
  if (!server)
13771
13797
  return;
@@ -13773,21 +13799,20 @@ function reloadOnTsconfigChange(changedFile) {
13773
13799
  // any json file in the tsconfig cache could have been used to compile ts
13774
13800
  if (path$o.basename(changedFile) === 'tsconfig.json' ||
13775
13801
  (changedFile.endsWith('.json') &&
13776
- tsconfckParseOptions?.cache?.has(changedFile))) {
13802
+ (await tsconfckParseOptions)?.cache?.has(changedFile))) {
13777
13803
  server.config.logger.info(`changed tsconfig file detected: ${changedFile} - Clearing cache and forcing full-reload to ensure TypeScript is compiled with updated config values.`, { clear: server.config.clearScreen, timestamp: true });
13778
13804
  // clear module graph to remove code compiled with outdated config
13779
13805
  server.moduleGraph.invalidateAll();
13780
13806
  // reset tsconfck so that recompile works with up2date configs
13781
- initTSConfck(server.config).finally(() => {
13782
- // server may not be available if vite config is updated at the same time
13783
- if (server) {
13784
- // force full reload
13785
- server.ws.send({
13786
- type: 'full-reload',
13787
- path: '*',
13788
- });
13789
- }
13790
- });
13807
+ initTSConfck(server.config.root, true);
13808
+ // server may not be available if vite config is updated at the same time
13809
+ if (server) {
13810
+ // force full reload
13811
+ server.ws.send({
13812
+ type: 'full-reload',
13813
+ path: '*',
13814
+ });
13815
+ }
13791
13816
  }
13792
13817
  }
13793
13818
 
@@ -15598,6 +15623,7 @@ const assetUrlRE = /__VITE_ASSET__([a-z\d]+)__(?:\$_(.*?)__)?/g;
15598
15623
  const rawRE = /(?:\?|&)raw(?:&|$)/;
15599
15624
  const urlRE = /(\?|&)url(?:&|$)/;
15600
15625
  const jsSourceMapRE = /\.[cm]?js\.map$/;
15626
+ const unnededFinalQueryCharRE = /[?&]$/;
15601
15627
  const assetCache = new WeakMap();
15602
15628
  const generatedAssets = new WeakMap();
15603
15629
  // add own dictionary entry by directly assigning mrmime
@@ -15608,6 +15634,8 @@ function registerCustomMime() {
15608
15634
  mimes$1['flac'] = 'audio/flac';
15609
15635
  // mrmime and mime-db is not released yet: https://github.com/jshttp/mime-db/commit/c9242a9b7d4bb25d7a0c9244adec74aeef08d8a1
15610
15636
  mimes$1['aac'] = 'audio/aac';
15637
+ // https://wiki.xiph.org/MIME_Types_and_File_Extensions#.opus_-_audio/ogg
15638
+ mimes$1['opus'] = 'audio/ogg';
15611
15639
  // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
15612
15640
  mimes$1['eot'] = 'application/vnd.ms-fontobject';
15613
15641
  }
@@ -15671,7 +15699,7 @@ function assetPlugin(config) {
15671
15699
  }
15672
15700
  },
15673
15701
  async load(id) {
15674
- if (id.startsWith('\0')) {
15702
+ if (id[0] === '\0') {
15675
15703
  // Rollup convention, this id should be handled by the
15676
15704
  // plugin that marked it with \0
15677
15705
  return;
@@ -15685,7 +15713,7 @@ function assetPlugin(config) {
15685
15713
  if (!config.assetsInclude(cleanUrl(id)) && !urlRE.test(id)) {
15686
15714
  return;
15687
15715
  }
15688
- id = id.replace(urlRE, '$1').replace(/[?&]$/, '');
15716
+ id = id.replace(urlRE, '$1').replace(unnededFinalQueryCharRE, '');
15689
15717
  const url = await fileToUrl(id, config, this);
15690
15718
  return `export default ${JSON.stringify(url)}`;
15691
15719
  },
@@ -15720,7 +15748,7 @@ function assetPlugin(config) {
15720
15748
  function checkPublicFile(url, { publicDir }) {
15721
15749
  // note if the file is in /public, the resolver would have returned it
15722
15750
  // as-is so it's not going to be a fully resolved path.
15723
- if (!publicDir || !url.startsWith('/')) {
15751
+ if (!publicDir || url[0] !== '/') {
15724
15752
  return;
15725
15753
  }
15726
15754
  const publicFile = path$o.join(publicDir, cleanUrl(url));
@@ -15759,7 +15787,7 @@ function fileToDevUrl(id, config) {
15759
15787
  rtn = path$o.posix.join(FS_PREFIX, id);
15760
15788
  }
15761
15789
  const base = joinUrlSegments(config.server?.origin ?? '', config.base);
15762
- return joinUrlSegments(base, rtn.replace(/^\//, ''));
15790
+ return joinUrlSegments(base, removeLeadingSlash(rtn));
15763
15791
  }
15764
15792
  function getPublicAssetFilename(hash, config) {
15765
15793
  return publicAssetUrlCache.get(config)?.get(hash);
@@ -15838,7 +15866,7 @@ async function urlToBuiltUrl(url, importer, config, pluginContext) {
15838
15866
  if (checkPublicFile(url, config)) {
15839
15867
  return publicFileToBuiltUrl(url, config);
15840
15868
  }
15841
- const file = url.startsWith('/')
15869
+ const file = url[0] === '/'
15842
15870
  ? path$o.join(config.root, url)
15843
15871
  : path$o.join(path$o.dirname(importer), url);
15844
15872
  return fileToBuiltUrl(file, config, pluginContext,
@@ -15970,7 +15998,8 @@ function manifestPlugin(config) {
15970
15998
 
15971
15999
  // This is based on @rollup/plugin-data-uri
15972
16000
  const dataUriRE = /^([^/]+\/[^;,]+)(;base64)?,([\s\S]*)$/;
15973
- const dataUriPrefix = `/@data-uri/`;
16001
+ const base64RE = /base64/i;
16002
+ const dataUriPrefix = `\0/@data-uri/`;
15974
16003
  /**
15975
16004
  * Build only, since importing from a data URI works natively.
15976
16005
  */
@@ -15979,36 +16008,35 @@ function dataURIPlugin() {
15979
16008
  return {
15980
16009
  name: 'vite:data-uri',
15981
16010
  buildStart() {
15982
- resolved = {};
16011
+ resolved = new Map();
15983
16012
  },
15984
16013
  resolveId(id) {
15985
16014
  if (!dataUriRE.test(id)) {
15986
- return null;
16015
+ return;
15987
16016
  }
15988
16017
  const uri = new URL$3(id);
15989
16018
  if (uri.protocol !== 'data:') {
15990
- return null;
16019
+ return;
15991
16020
  }
15992
16021
  const match = uri.pathname.match(dataUriRE);
15993
16022
  if (!match) {
15994
- return null;
16023
+ return;
15995
16024
  }
15996
16025
  const [, mime, format, data] = match;
15997
16026
  if (mime !== 'text/javascript') {
15998
- throw new Error(`data URI with non-JavaScript mime type is not supported.`);
16027
+ throw new Error(`data URI with non-JavaScript mime type is not supported. If you're using legacy JavaScript MIME types (such as 'application/javascript'), please use 'text/javascript' instead.`);
15999
16028
  }
16000
16029
  // decode data
16001
- const base64 = format && /base64/i.test(format.substring(1));
16030
+ const base64 = format && base64RE.test(format.substring(1));
16002
16031
  const content = base64
16003
16032
  ? Buffer.from(data, 'base64').toString('utf-8')
16004
16033
  : data;
16005
- resolved[id] = content;
16034
+ resolved.set(id, content);
16006
16035
  return dataUriPrefix + id;
16007
16036
  },
16008
16037
  load(id) {
16009
16038
  if (id.startsWith(dataUriPrefix)) {
16010
- id = id.slice(dataUriPrefix.length);
16011
- return resolved[id] || null;
16039
+ return resolved.get(id.slice(dataUriPrefix.length));
16012
16040
  }
16013
16041
  },
16014
16042
  };
@@ -16017,8 +16045,8 @@ function dataURIPlugin() {
16017
16045
  /* es-module-lexer 1.2.0 */
16018
16046
  const A=1===new Uint8Array(new Uint16Array([1]).buffer)[0];function parse$e(E,g="@"){if(!C)return init.then((()=>parse$e(E)));const I=E.length+1,o=(C.__heap_base.value||C.__heap_base)+4*I-C.memory.buffer.byteLength;o>0&&C.memory.grow(Math.ceil(o/65536));const K=C.sa(I-1);if((A?B:Q)(E,new Uint16Array(C.memory.buffer,K,I)),!C.parse())throw Object.assign(new Error(`Parse error ${g}:${E.slice(0,C.e()).split("\n").length}:${C.e()-E.lastIndexOf("\n",C.e()-1)}`),{idx:C.e()});const D=[],k=[];for(;C.ri();){const A=C.is(),Q=C.ie(),B=C.ai(),g=C.id(),I=C.ss(),o=C.se();let K;C.ip()&&(K=J(E.slice(-1===g?A-1:A,-1===g?Q+1:Q))),D.push({n:K,s:A,e:Q,ss:I,se:o,d:g,a:B});}for(;C.re();){const A=C.es(),Q=C.ee(),B=C.els(),g=C.ele(),I=E.slice(A,Q),o=I[0],K=B<0?void 0:E.slice(B,g),D=K?K[0]:"";k.push({s:A,e:Q,ls:B,le:g,n:'"'===o||"'"===o?J(I):I,ln:'"'===D||"'"===D?J(K):K});}function J(A){try{return (0, eval)(A)}catch(A){}}return [D,k,!!C.f()]}function Q(A,Q){const B=A.length;let C=0;for(;C<B;){const B=A.charCodeAt(C);Q[C++]=(255&B)<<8|B>>>8;}}function B(A,Q){const B=A.length;let C=0;for(;C<B;)Q[C]=A.charCodeAt(C++);}let C;const init=WebAssembly.compile((E="AGFzbQEAAAABKghgAX8Bf2AEf39/fwBgAAF/YAAAYAF/AGADf39/AX9gAn9/AX9gAn9/AAMvLgABAQICAgICAgICAgICAgICAgIAAwMDBAQAAAADAAAAAAMDAAUGAAAABwAGAgUEBQFwAQEBBQMBAAEGDwJ/AUGw8gALfwBBsPIACwdwEwZtZW1vcnkCAAJzYQAAAWUAAwJpcwAEAmllAAUCc3MABgJzZQAHAmFpAAgCaWQACQJpcAAKAmVzAAsCZWUADANlbHMADQNlbGUADgJyaQAPAnJlABABZgARBXBhcnNlABILX19oZWFwX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AQQAoAqQKIQECQAJAA0AgAEECaiECIAAgAU8NAQJAAkAgAi8BACIDQaR/ag4CAQQACyACIQAgA0F2ag4EAgEBAgELIABBBGohAAwACwtBACACNgKgChAiQQAPC0EAIAI2AqAKQd0AC0kBA39BACEDAkAgAkUNAAJAA0AgAC0AACIEIAEtAAAiBUcNASABQQFqIQEgAEEBaiEAIAJBf2oiAg0ADAILCyAEIAVrIQMLIAMLC+IBAgBBgAgLxAEAAHgAcABvAHIAdABtAHAAbwByAHQAZQB0AGEAcgBvAG0AdQBuAGMAdABpAG8AbgBzAHMAZQByAHQAdgBvAHkAaQBlAGQAZQBsAGUAYwBvAG4AdABpAG4AaQBuAHMAdABhAG4AdAB5AGIAcgBlAGEAcgBlAHQAdQByAGQAZQBiAHUAZwBnAGUAYQB3AGEAaQB0AGgAcgB3AGgAaQBsAGUAZgBvAHIAaQBmAGMAYQB0AGMAZgBpAG4AYQBsAGwAZQBsAHMAAEHECQsQAQAAAAIAAAAABAAAMDkAAA==","undefined"!=typeof Buffer?Buffer.from(E,"base64"):Uint8Array.from(atob(E),(A=>A.charCodeAt(0))))).then(WebAssembly.instantiate).then((({exports:A})=>{C=A;}));var E;
16019
16047
 
16020
- const isDebug$6 = !!process.env.DEBUG;
16021
- const debug$e = createDebugger('vite:sourcemap', {
16048
+ const isDebug$5 = !!process.env.DEBUG;
16049
+ const debug$d = createDebugger('vite:sourcemap', {
16022
16050
  onlyWhenFocused: true,
16023
16051
  });
16024
16052
  // Virtual modules should be prefixed with a null byte to avoid a
@@ -16051,7 +16079,7 @@ async function injectSourcesContent(map, file, logger) {
16051
16079
  // …to log the missing sources.
16052
16080
  if (missingSources.length) {
16053
16081
  logger.warnOnce(`Sourcemap for "${file}" points to missing source files`);
16054
- isDebug$6 && debug$e(`Missing sources:\n ` + missingSources.join(`\n `));
16082
+ isDebug$5 && debug$d(`Missing sources:\n ` + missingSources.join(`\n `));
16055
16083
  }
16056
16084
  }
16057
16085
  function genSourceMapUrl(map) {
@@ -16061,7 +16089,7 @@ function genSourceMapUrl(map) {
16061
16089
  return `data:application/json;base64,${Buffer.from(map).toString('base64')}`;
16062
16090
  }
16063
16091
  function getCodeWithSourcemap(type, code, map) {
16064
- if (isDebug$6) {
16092
+ if (isDebug$5) {
16065
16093
  code += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, '*\\/')}*/\n`;
16066
16094
  }
16067
16095
  if (type === 'js') {
@@ -16073,6 +16101,235 @@ function getCodeWithSourcemap(type, code, map) {
16073
16101
  return code;
16074
16102
  }
16075
16103
 
16104
+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports
16105
+ let pnp;
16106
+ if (process.versions.pnp) {
16107
+ try {
16108
+ pnp = createRequire$1(import.meta.url)('pnpapi');
16109
+ }
16110
+ catch { }
16111
+ }
16112
+ function invalidatePackageData(packageCache, pkgPath) {
16113
+ packageCache.delete(pkgPath);
16114
+ const pkgDir = path$o.dirname(pkgPath);
16115
+ packageCache.forEach((pkg, cacheKey) => {
16116
+ if (pkg.dir === pkgDir) {
16117
+ packageCache.delete(cacheKey);
16118
+ }
16119
+ });
16120
+ }
16121
+ function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageCache) {
16122
+ if (pnp) {
16123
+ const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks);
16124
+ if (packageCache?.has(cacheKey))
16125
+ return packageCache.get(cacheKey);
16126
+ const pkg = pnp.resolveToUnqualified(pkgName, basedir);
16127
+ if (!pkg)
16128
+ return null;
16129
+ const pkgData = loadPackageData(path$o.join(pkg, 'package.json'));
16130
+ packageCache?.set(cacheKey, pkgData);
16131
+ return pkgData;
16132
+ }
16133
+ const originalBasedir = basedir;
16134
+ while (basedir) {
16135
+ if (packageCache) {
16136
+ const cached = getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks);
16137
+ if (cached)
16138
+ return cached;
16139
+ }
16140
+ const pkg = path$o.join(basedir, 'node_modules', pkgName, 'package.json');
16141
+ try {
16142
+ if (fs$l.existsSync(pkg)) {
16143
+ const pkgPath = preserveSymlinks ? pkg : safeRealpathSync(pkg);
16144
+ const pkgData = loadPackageData(pkgPath);
16145
+ if (packageCache) {
16146
+ setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks);
16147
+ }
16148
+ return pkgData;
16149
+ }
16150
+ }
16151
+ catch { }
16152
+ const nextBasedir = path$o.dirname(basedir);
16153
+ if (nextBasedir === basedir)
16154
+ break;
16155
+ basedir = nextBasedir;
16156
+ }
16157
+ return null;
16158
+ }
16159
+ function findNearestPackageData(basedir, packageCache) {
16160
+ const originalBasedir = basedir;
16161
+ while (basedir) {
16162
+ if (packageCache) {
16163
+ const cached = getFnpdCache(packageCache, basedir, originalBasedir);
16164
+ if (cached)
16165
+ return cached;
16166
+ }
16167
+ const pkgPath = path$o.join(basedir, 'package.json');
16168
+ try {
16169
+ if (fs$l.statSync(pkgPath, { throwIfNoEntry: false })?.isFile()) {
16170
+ const pkgData = loadPackageData(pkgPath);
16171
+ if (packageCache) {
16172
+ setFnpdCache(packageCache, pkgData, basedir, originalBasedir);
16173
+ }
16174
+ return pkgData;
16175
+ }
16176
+ }
16177
+ catch { }
16178
+ const nextBasedir = path$o.dirname(basedir);
16179
+ if (nextBasedir === basedir)
16180
+ break;
16181
+ basedir = nextBasedir;
16182
+ }
16183
+ return null;
16184
+ }
16185
+ function loadPackageData(pkgPath) {
16186
+ const data = JSON.parse(fs$l.readFileSync(pkgPath, 'utf-8'));
16187
+ const pkgDir = path$o.dirname(pkgPath);
16188
+ const { sideEffects } = data;
16189
+ let hasSideEffects;
16190
+ if (typeof sideEffects === 'boolean') {
16191
+ hasSideEffects = () => sideEffects;
16192
+ }
16193
+ else if (Array.isArray(sideEffects)) {
16194
+ const finalPackageSideEffects = sideEffects.map((sideEffect) => {
16195
+ /*
16196
+ * The array accepts simple glob patterns to the relevant files... Patterns like *.css, which do not include a /, will be treated like **\/*.css.
16197
+ * https://webpack.js.org/guides/tree-shaking/
16198
+ * https://github.com/vitejs/vite/pull/11807
16199
+ */
16200
+ if (sideEffect.includes('/')) {
16201
+ return sideEffect;
16202
+ }
16203
+ return `**/${sideEffect}`;
16204
+ });
16205
+ hasSideEffects = createFilter(finalPackageSideEffects, null, {
16206
+ resolve: pkgDir,
16207
+ });
16208
+ }
16209
+ else {
16210
+ hasSideEffects = () => true;
16211
+ }
16212
+ const pkg = {
16213
+ dir: pkgDir,
16214
+ data,
16215
+ hasSideEffects,
16216
+ webResolvedImports: {},
16217
+ nodeResolvedImports: {},
16218
+ setResolvedCache(key, entry, targetWeb) {
16219
+ if (targetWeb) {
16220
+ pkg.webResolvedImports[key] = entry;
16221
+ }
16222
+ else {
16223
+ pkg.nodeResolvedImports[key] = entry;
16224
+ }
16225
+ },
16226
+ getResolvedCache(key, targetWeb) {
16227
+ if (targetWeb) {
16228
+ return pkg.webResolvedImports[key];
16229
+ }
16230
+ else {
16231
+ return pkg.nodeResolvedImports[key];
16232
+ }
16233
+ },
16234
+ };
16235
+ return pkg;
16236
+ }
16237
+ function watchPackageDataPlugin(config) {
16238
+ const watchQueue = new Set();
16239
+ let watchFile = (id) => {
16240
+ watchQueue.add(id);
16241
+ };
16242
+ const { packageCache } = config;
16243
+ const setPackageData = packageCache.set.bind(packageCache);
16244
+ packageCache.set = (id, pkg) => {
16245
+ if (id.endsWith('.json')) {
16246
+ watchFile(id);
16247
+ }
16248
+ return setPackageData(id, pkg);
16249
+ };
16250
+ return {
16251
+ name: 'vite:watch-package-data',
16252
+ buildStart() {
16253
+ watchFile = this.addWatchFile;
16254
+ watchQueue.forEach(watchFile);
16255
+ watchQueue.clear();
16256
+ },
16257
+ buildEnd() {
16258
+ watchFile = (id) => watchQueue.add(id);
16259
+ },
16260
+ watchChange(id) {
16261
+ if (id.endsWith('/package.json')) {
16262
+ invalidatePackageData(packageCache, id);
16263
+ }
16264
+ },
16265
+ };
16266
+ }
16267
+ /**
16268
+ * Get cached `resolvePackageData` value based on `basedir`. When one is found,
16269
+ * and we've already traversed some directories between `basedir` and `originalBasedir`,
16270
+ * we cache the value for those in-between directories as well.
16271
+ *
16272
+ * This makes it so the fs is only read once for a shared `basedir`.
16273
+ */
16274
+ function getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks) {
16275
+ const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks);
16276
+ const pkgData = packageCache.get(cacheKey);
16277
+ if (pkgData) {
16278
+ traverseBetweenDirs(originalBasedir, basedir, (dir) => {
16279
+ packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData);
16280
+ });
16281
+ return pkgData;
16282
+ }
16283
+ }
16284
+ function setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks) {
16285
+ packageCache.set(getRpdCacheKey(pkgName, basedir, preserveSymlinks), pkgData);
16286
+ traverseBetweenDirs(originalBasedir, basedir, (dir) => {
16287
+ packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData);
16288
+ });
16289
+ }
16290
+ // package cache key for `resolvePackageData`
16291
+ function getRpdCacheKey(pkgName, basedir, preserveSymlinks) {
16292
+ return `rpd_${pkgName}_${basedir}_${preserveSymlinks}`;
16293
+ }
16294
+ /**
16295
+ * Get cached `findNearestPackageData` value based on `basedir`. When one is found,
16296
+ * and we've already traversed some directories between `basedir` and `originalBasedir`,
16297
+ * we cache the value for those in-between directories as well.
16298
+ *
16299
+ * This makes it so the fs is only read once for a shared `basedir`.
16300
+ */
16301
+ function getFnpdCache(packageCache, basedir, originalBasedir) {
16302
+ const cacheKey = getFnpdCacheKey(basedir);
16303
+ const pkgData = packageCache.get(cacheKey);
16304
+ if (pkgData) {
16305
+ traverseBetweenDirs(originalBasedir, basedir, (dir) => {
16306
+ packageCache.set(getFnpdCacheKey(dir), pkgData);
16307
+ });
16308
+ return pkgData;
16309
+ }
16310
+ }
16311
+ function setFnpdCache(packageCache, pkgData, basedir, originalBasedir) {
16312
+ packageCache.set(getFnpdCacheKey(basedir), pkgData);
16313
+ traverseBetweenDirs(originalBasedir, basedir, (dir) => {
16314
+ packageCache.set(getFnpdCacheKey(dir), pkgData);
16315
+ });
16316
+ }
16317
+ // package cache key for `findNearestPackageData`
16318
+ function getFnpdCacheKey(basedir) {
16319
+ return `fnpd_${basedir}`;
16320
+ }
16321
+ /**
16322
+ * Traverse between `longerDir` (inclusive) and `shorterDir` (exclusive) and call `cb` for each dir.
16323
+ * @param longerDir Longer dir path, e.g. `/User/foo/bar/baz`
16324
+ * @param shorterDir Shorter dir path, e.g. `/User/foo`
16325
+ */
16326
+ function traverseBetweenDirs(longerDir, shorterDir, cb) {
16327
+ while (longerDir !== shorterDir) {
16328
+ cb(longerDir);
16329
+ longerDir = path$o.dirname(longerDir);
16330
+ }
16331
+ }
16332
+
16076
16333
  function e(e,n,r){throw new Error(r?`No known conditions for "${n}" specifier in "${e}" package`:`Missing "${n}" specifier in "${e}" package`)}function n(n,i,o,f){let s,u,l=r(n,o),c=function(e){let n=new Set(["default",...e.conditions||[]]);return e.unsafe||n.add(e.require?"require":"import"),e.unsafe||n.add(e.browser?"browser":"node"),n}(f||{}),a=i[l];if(void 0===a){let e,n,r,t;for(t in i)n&&t.length<n.length||("/"===t[t.length-1]&&l.startsWith(t)?(u=l.substring(t.length),n=t):t.length>1&&(r=t.indexOf("*",2),~r&&(e=RegExp("^"+t.substring(0,r)+"(.*)"+t.substring(1+r)).exec(l),e&&e[1]&&(u=e[1],n=t))));a=i[n];}return a||e(n,l),s=t(a,c),s||e(n,l,1),u&&function(e,n){let r,t=0,i=e.length,o=/[*]/g,f=/[/]$/;for(;t<i;t++)e[t]=o.test(r=e[t])?r.replace(o,n):f.test(r)?r+n:r;}(s,u),s}function r(e,n,r){if(e===n||"."===n)return ".";let t=e+"/",i=t.length,o=n.slice(0,i)===t,f=o?n.slice(i):n;return "#"===f[0]?f:o||!r?"./"===f.slice(0,2)?f:"./"+f:f}function t(e,n,r){if(e){if("string"==typeof e)return r&&r.add(e),[e];let i,o;if(Array.isArray(e)){for(o=r||new Set,i=0;i<e.length;i++)t(e[i],n,o);if(!r&&o.size)return [...o]}else for(i in e)if(n.has(i))return t(e[i],n,r)}}function o(e,r,t){let i,o=e.exports;if(o){if("string"==typeof o)o={".":o};else for(i in o){"."!==i[0]&&(o={".":o});break}return n(e.name,o,r||".",t)}}function f(e,r,t){if(e.imports)return n(e.name,e.imports,r,t)}
16077
16334
 
16078
16335
  // This file was generated. Do not modify manually!
@@ -22130,139 +22387,6 @@ function hasESMSyntax(code) {
22130
22387
  return ESM_RE.test(code);
22131
22388
  }
22132
22389
 
22133
- const isDebug$5 = process.env.DEBUG;
22134
- const debug$d = createDebugger('vite:resolve-details', {
22135
- onlyWhenFocused: true,
22136
- });
22137
- function invalidatePackageData(packageCache, pkgPath) {
22138
- packageCache.delete(pkgPath);
22139
- const pkgDir = path$o.dirname(pkgPath);
22140
- packageCache.forEach((pkg, cacheKey) => {
22141
- if (pkg.dir === pkgDir) {
22142
- packageCache.delete(cacheKey);
22143
- }
22144
- });
22145
- }
22146
- function resolvePackageData(id, basedir, preserveSymlinks = false, packageCache) {
22147
- let pkg;
22148
- let cacheKey;
22149
- if (packageCache) {
22150
- cacheKey = `${id}&${basedir}&${preserveSymlinks}`;
22151
- if ((pkg = packageCache.get(cacheKey))) {
22152
- return pkg;
22153
- }
22154
- }
22155
- let pkgPath;
22156
- try {
22157
- pkgPath = resolveFrom(`${id}/package.json`, basedir, preserveSymlinks);
22158
- pkg = loadPackageData(pkgPath, true, packageCache);
22159
- if (packageCache) {
22160
- packageCache.set(cacheKey, pkg);
22161
- }
22162
- return pkg;
22163
- }
22164
- catch (e) {
22165
- if (e instanceof SyntaxError) {
22166
- isDebug$5 && debug$d(`Parsing failed: ${pkgPath}`);
22167
- }
22168
- // Ignore error for missing package.json
22169
- else if (e.code !== 'MODULE_NOT_FOUND') {
22170
- throw e;
22171
- }
22172
- }
22173
- return null;
22174
- }
22175
- function loadPackageData(pkgPath, preserveSymlinks, packageCache) {
22176
- if (!preserveSymlinks) {
22177
- pkgPath = fs$l.realpathSync.native(pkgPath);
22178
- }
22179
- let cached;
22180
- if ((cached = packageCache?.get(pkgPath))) {
22181
- return cached;
22182
- }
22183
- const data = JSON.parse(fs$l.readFileSync(pkgPath, 'utf-8'));
22184
- const pkgDir = path$o.dirname(pkgPath);
22185
- const { sideEffects } = data;
22186
- let hasSideEffects;
22187
- if (typeof sideEffects === 'boolean') {
22188
- hasSideEffects = () => sideEffects;
22189
- }
22190
- else if (Array.isArray(sideEffects)) {
22191
- const finalPackageSideEffects = sideEffects.map((sideEffect) => {
22192
- /*
22193
- * The array accepts simple glob patterns to the relevant files... Patterns like *.css, which do not include a /, will be treated like **\/*.css.
22194
- * https://webpack.js.org/guides/tree-shaking/
22195
- * https://github.com/vitejs/vite/pull/11807
22196
- */
22197
- if (sideEffect.includes('/')) {
22198
- return sideEffect;
22199
- }
22200
- return `**/${sideEffect}`;
22201
- });
22202
- hasSideEffects = createFilter(finalPackageSideEffects, null, {
22203
- resolve: pkgDir,
22204
- });
22205
- }
22206
- else {
22207
- hasSideEffects = () => true;
22208
- }
22209
- const pkg = {
22210
- dir: pkgDir,
22211
- data,
22212
- hasSideEffects,
22213
- webResolvedImports: {},
22214
- nodeResolvedImports: {},
22215
- setResolvedCache(key, entry, targetWeb) {
22216
- if (targetWeb) {
22217
- pkg.webResolvedImports[key] = entry;
22218
- }
22219
- else {
22220
- pkg.nodeResolvedImports[key] = entry;
22221
- }
22222
- },
22223
- getResolvedCache(key, targetWeb) {
22224
- if (targetWeb) {
22225
- return pkg.webResolvedImports[key];
22226
- }
22227
- else {
22228
- return pkg.nodeResolvedImports[key];
22229
- }
22230
- },
22231
- };
22232
- packageCache?.set(pkgPath, pkg);
22233
- return pkg;
22234
- }
22235
- function watchPackageDataPlugin(config) {
22236
- const watchQueue = new Set();
22237
- let watchFile = (id) => {
22238
- watchQueue.add(id);
22239
- };
22240
- const { packageCache } = config;
22241
- const setPackageData = packageCache.set.bind(packageCache);
22242
- packageCache.set = (id, pkg) => {
22243
- if (id.endsWith('.json')) {
22244
- watchFile(id);
22245
- }
22246
- return setPackageData(id, pkg);
22247
- };
22248
- return {
22249
- name: 'vite:watch-package-data',
22250
- buildStart() {
22251
- watchFile = this.addWatchFile;
22252
- watchQueue.forEach(watchFile);
22253
- watchQueue.clear();
22254
- },
22255
- buildEnd() {
22256
- watchFile = (id) => watchQueue.add(id);
22257
- },
22258
- watchChange(id) {
22259
- if (id.endsWith('/package.json')) {
22260
- invalidatePackageData(packageCache, id);
22261
- }
22262
- },
22263
- };
22264
- }
22265
-
22266
22390
  const WORKER_FILE_ID = 'worker_file';
22267
22391
  const workerCache = new WeakMap();
22268
22392
  function isWorkerRequest(id) {
@@ -22568,6 +22692,7 @@ const browserExternalId = '__vite-browser-external';
22568
22692
  const optionalPeerDepId = '__vite-optional-peer-dep';
22569
22693
  const nodeModulesInPathRE = /(?:^|\/)node_modules\//;
22570
22694
  const subpathImportsPrefix = '#';
22695
+ const startsWithWordCharRE = /^\w/;
22571
22696
  const isDebug$4 = process.env.DEBUG;
22572
22697
  const debug$c = createDebugger('vite:resolve-details', {
22573
22698
  onlyWhenFocused: true,
@@ -22575,6 +22700,12 @@ const debug$c = createDebugger('vite:resolve-details', {
22575
22700
  function resolvePlugin(resolveOptions) {
22576
22701
  const { root, isProduction, asSrc, ssrConfig, preferRelative = false, } = resolveOptions;
22577
22702
  const { target: ssrTarget, noExternal: ssrNoExternal } = ssrConfig ?? {};
22703
+ // In unix systems, absolute paths inside root first needs to be checked as an
22704
+ // absolute URL (/root/root/path-to-file) resulting in failed checks before falling
22705
+ // back to checking the path as absolute. If /root/root isn't a valid path, we can
22706
+ // avoid these checks. Absolute paths inside root are common in user code as many
22707
+ // paths are resolved by the user. For example for an alias.
22708
+ const rootInRoot = tryStatSync(path$o.join(root, root))?.isDirectory() ?? false;
22578
22709
  return {
22579
22710
  name: 'vite:resolve',
22580
22711
  async resolveId(id, importer, resolveOpts) {
@@ -22593,26 +22724,7 @@ function resolvePlugin(resolveOptions) {
22593
22724
  ...resolveOptions,
22594
22725
  scan: resolveOpts?.scan ?? resolveOptions.scan,
22595
22726
  };
22596
- const resolveSubpathImports = (id, importer) => {
22597
- if (!importer || !id.startsWith(subpathImportsPrefix))
22598
- return;
22599
- const basedir = path$o.dirname(importer);
22600
- const pkgJsonPath = lookupFile(basedir, ['package.json'], {
22601
- pathOnly: true,
22602
- });
22603
- if (!pkgJsonPath)
22604
- return;
22605
- const pkgData = loadPackageData(pkgJsonPath, options.preserveSymlinks);
22606
- let importsPath = resolveExportsOrImports(pkgData.data, id, options, targetWeb, 'imports');
22607
- if (importsPath?.startsWith('.')) {
22608
- importsPath = path$o.relative(basedir, path$o.join(path$o.dirname(pkgJsonPath), importsPath));
22609
- if (!importsPath.startsWith('.')) {
22610
- importsPath = `./${importsPath}`;
22611
- }
22612
- }
22613
- return importsPath;
22614
- };
22615
- const resolvedImports = resolveSubpathImports(id, importer);
22727
+ const resolvedImports = resolveSubpathImports(id, importer, options, targetWeb);
22616
22728
  if (resolvedImports) {
22617
22729
  id = resolvedImports;
22618
22730
  }
@@ -22639,27 +22751,6 @@ function resolvePlugin(resolveOptions) {
22639
22751
  : normalizePath$3(ensureVolumeInPath(path$o.resolve(root, id.slice(1))));
22640
22752
  return optimizedPath;
22641
22753
  }
22642
- const ensureVersionQuery = (resolved) => {
22643
- if (!options.isBuild &&
22644
- !options.scan &&
22645
- depsOptimizer &&
22646
- !(resolved === normalizedClientEntry$1 ||
22647
- resolved === normalizedEnvEntry$1)) {
22648
- // Ensure that direct imports of node_modules have the same version query
22649
- // as if they would have been imported through a bare import
22650
- // Use the original id to do the check as the resolved id may be the real
22651
- // file path after symlinks resolution
22652
- const isNodeModule = nodeModulesInPathRE.test(normalizePath$3(id)) ||
22653
- nodeModulesInPathRE.test(normalizePath$3(resolved));
22654
- if (isNodeModule && !resolved.match(DEP_VERSION_RE)) {
22655
- const versionHash = depsOptimizer.metadata.browserHash;
22656
- if (versionHash && isOptimizable(resolved, depsOptimizer.options)) {
22657
- resolved = injectQuery(resolved, `v=${versionHash}`);
22658
- }
22659
- }
22660
- }
22661
- return resolved;
22662
- };
22663
22754
  // explicit fs paths that starts with /@fs/*
22664
22755
  if (asSrc && id.startsWith(FS_PREFIX)) {
22665
22756
  const fsPath = fsPathFromId(id);
@@ -22667,20 +22758,21 @@ function resolvePlugin(resolveOptions) {
22667
22758
  isDebug$4 && debug$c(`[@fs] ${picocolorsExports.cyan(id)} -> ${picocolorsExports.dim(res)}`);
22668
22759
  // always return here even if res doesn't exist since /@fs/ is explicit
22669
22760
  // if the file doesn't exist it should be a 404
22670
- return ensureVersionQuery(res || fsPath);
22761
+ return ensureVersionQuery(res || fsPath, id, options, depsOptimizer);
22671
22762
  }
22672
22763
  // URL
22673
22764
  // /foo -> /fs-root/foo
22674
- if (asSrc && id.startsWith('/')) {
22765
+ if (asSrc && id[0] === '/' && (rootInRoot || !id.startsWith(root))) {
22675
22766
  const fsPath = path$o.resolve(root, id.slice(1));
22676
22767
  if ((res = tryFsResolve(fsPath, options))) {
22677
22768
  isDebug$4 && debug$c(`[url] ${picocolorsExports.cyan(id)} -> ${picocolorsExports.dim(res)}`);
22678
- return ensureVersionQuery(res);
22769
+ return ensureVersionQuery(res, id, options, depsOptimizer);
22679
22770
  }
22680
22771
  }
22681
22772
  // relative
22682
- if (id.startsWith('.') ||
22683
- ((preferRelative || importer?.endsWith('.html')) && /^\w/.test(id))) {
22773
+ if (id[0] === '.' ||
22774
+ ((preferRelative || importer?.endsWith('.html')) &&
22775
+ startsWithWordCharRE.test(id))) {
22684
22776
  const basedir = importer ? path$o.dirname(importer) : process.cwd();
22685
22777
  const fsPath = path$o.resolve(basedir, id);
22686
22778
  // handle browser field mapping for relative imports
@@ -22702,7 +22794,7 @@ function resolvePlugin(resolveOptions) {
22702
22794
  return res;
22703
22795
  }
22704
22796
  if ((res = tryFsResolve(fsPath, options))) {
22705
- res = ensureVersionQuery(res);
22797
+ res = ensureVersionQuery(res, id, options, depsOptimizer);
22706
22798
  isDebug$4 &&
22707
22799
  debug$c(`[relative] ${picocolorsExports.cyan(id)} -> ${picocolorsExports.dim(res)}`);
22708
22800
  const pkg = importer != null && idToPkgMap.get(importer);
@@ -22717,20 +22809,20 @@ function resolvePlugin(resolveOptions) {
22717
22809
  }
22718
22810
  }
22719
22811
  // drive relative fs paths (only windows)
22720
- if (isWindows$4 && id.startsWith('/')) {
22812
+ if (isWindows$4 && id[0] === '/') {
22721
22813
  const basedir = importer ? path$o.dirname(importer) : process.cwd();
22722
22814
  const fsPath = path$o.resolve(basedir, id);
22723
22815
  if ((res = tryFsResolve(fsPath, options))) {
22724
22816
  isDebug$4 &&
22725
22817
  debug$c(`[drive-relative] ${picocolorsExports.cyan(id)} -> ${picocolorsExports.dim(res)}`);
22726
- return ensureVersionQuery(res);
22818
+ return ensureVersionQuery(res, id, options, depsOptimizer);
22727
22819
  }
22728
22820
  }
22729
22821
  // absolute fs paths
22730
22822
  if (isNonDriveRelativeAbsolutePath(id) &&
22731
22823
  (res = tryFsResolve(id, options))) {
22732
22824
  isDebug$4 && debug$c(`[fs] ${picocolorsExports.cyan(id)} -> ${picocolorsExports.dim(res)}`);
22733
- return ensureVersionQuery(res);
22825
+ return ensureVersionQuery(res, id, options, depsOptimizer);
22734
22826
  }
22735
22827
  // external
22736
22828
  if (isExternalUrl(id)) {
@@ -22819,6 +22911,42 @@ export default new Proxy({}, {
22819
22911
  },
22820
22912
  };
22821
22913
  }
22914
+ function resolveSubpathImports(id, importer, options, targetWeb) {
22915
+ if (!importer || !id.startsWith(subpathImportsPrefix))
22916
+ return;
22917
+ const basedir = path$o.dirname(importer);
22918
+ const pkgData = findNearestPackageData(basedir, options.packageCache);
22919
+ if (!pkgData)
22920
+ return;
22921
+ let importsPath = resolveExportsOrImports(pkgData.data, id, options, targetWeb, 'imports');
22922
+ if (importsPath?.[0] === '.') {
22923
+ importsPath = path$o.relative(basedir, path$o.join(pkgData.dir, importsPath));
22924
+ if (importsPath[0] !== '.') {
22925
+ importsPath = `./${importsPath}`;
22926
+ }
22927
+ }
22928
+ return importsPath;
22929
+ }
22930
+ function ensureVersionQuery(resolved, id, options, depsOptimizer) {
22931
+ if (!options.isBuild &&
22932
+ !options.scan &&
22933
+ depsOptimizer &&
22934
+ !(resolved === normalizedClientEntry$1 || resolved === normalizedEnvEntry$1)) {
22935
+ // Ensure that direct imports of node_modules have the same version query
22936
+ // as if they would have been imported through a bare import
22937
+ // Use the original id to do the check as the resolved id may be the real
22938
+ // file path after symlinks resolution
22939
+ const isNodeModule = nodeModulesInPathRE.test(normalizePath$3(id)) ||
22940
+ nodeModulesInPathRE.test(normalizePath$3(resolved));
22941
+ if (isNodeModule && !resolved.match(DEP_VERSION_RE)) {
22942
+ const versionHash = depsOptimizer.metadata.browserHash;
22943
+ if (versionHash && isOptimizable(resolved, depsOptimizer.options)) {
22944
+ resolved = injectQuery(resolved, `v=${versionHash}`);
22945
+ }
22946
+ }
22947
+ }
22948
+ return resolved;
22949
+ }
22822
22950
  function splitFileAndPostfix(path) {
22823
22951
  let file = path;
22824
22952
  let postfix = '';
@@ -22832,111 +22960,117 @@ function splitFileAndPostfix(path) {
22832
22960
  }
22833
22961
  return { file, postfix };
22834
22962
  }
22835
- function tryFsResolve(fsPath, options, tryIndex = true, targetWeb = true) {
22836
- const { file, postfix } = splitFileAndPostfix(fsPath);
22837
- let res;
22838
- // if there is a postfix, try resolving it as a complete path first (#4703)
22839
- if (postfix &&
22840
- (res = tryResolveFile(fsPath, '', options, false, targetWeb, options.tryPrefix, options.skipPackageJson))) {
22841
- return res;
22963
+ function tryFsResolve(fsPath, options, tryIndex = true, targetWeb = true, skipPackageJson = false) {
22964
+ let postfixIndex = fsPath.indexOf('?');
22965
+ if (postfixIndex < 0) {
22966
+ postfixIndex = fsPath.indexOf('#');
22967
+ // Dependencies like es5-ext use `#` in their paths. We don't support `#` in user
22968
+ // source code so we only need to perform the check for dependencies.
22969
+ // We don't support `?` in node_modules paths, so we only need to check in this branch.
22970
+ if (postfixIndex >= 0 && fsPath.includes('node_modules')) {
22971
+ const res = tryCleanFsResolve(fsPath, options, tryIndex, targetWeb, skipPackageJson);
22972
+ if (res)
22973
+ return res;
22974
+ }
22842
22975
  }
22843
- if ((res = tryResolveFile(file, postfix, options, false, targetWeb, options.tryPrefix, options.skipPackageJson))) {
22844
- return res;
22976
+ let file = fsPath;
22977
+ let postfix = '';
22978
+ if (postfixIndex >= 0) {
22979
+ file = fsPath.slice(0, postfixIndex);
22980
+ postfix = fsPath.slice(postfixIndex);
22981
+ }
22982
+ const res = tryCleanFsResolve(file, options, tryIndex, targetWeb, skipPackageJson);
22983
+ if (res)
22984
+ return res + postfix;
22985
+ }
22986
+ function tryCleanFsResolve(file, options, tryIndex = true, targetWeb = true, skipPackageJson = false) {
22987
+ const { tryPrefix, extensions, preserveSymlinks } = options;
22988
+ const fileStat = tryStatSync(file);
22989
+ // Try direct match first
22990
+ if (fileStat?.isFile())
22991
+ return getRealPath(file, options.preserveSymlinks);
22992
+ let res;
22993
+ // If path.dirname is a valid directory, try extensions and ts resolution logic
22994
+ const possibleJsToTs = options.isFromTsImporter && isPossibleTsOutput(file);
22995
+ if (possibleJsToTs || extensions.length || tryPrefix) {
22996
+ const dirPath = path$o.dirname(file);
22997
+ const dirStat = tryStatSync(dirPath);
22998
+ if (dirStat?.isDirectory()) {
22999
+ if (possibleJsToTs) {
23000
+ // try resolve .js, .mjs, .mts or .jsx import to typescript file
23001
+ const tsSrcPaths = getPotentialTsSrcPaths(file);
23002
+ for (const srcPath of tsSrcPaths) {
23003
+ if ((res = tryResolveRealFile(srcPath, preserveSymlinks)))
23004
+ return res;
23005
+ }
23006
+ }
23007
+ if ((res = tryResolveRealFileWithExtensions(file, extensions, preserveSymlinks)))
23008
+ return res;
23009
+ if (tryPrefix) {
23010
+ const prefixed = `${dirPath}/${options.tryPrefix}${path$o.basename(file)}`;
23011
+ if ((res = tryResolveRealFile(prefixed, preserveSymlinks)))
23012
+ return res;
23013
+ if ((res = tryResolveRealFileWithExtensions(prefixed, extensions, preserveSymlinks)))
23014
+ return res;
23015
+ }
23016
+ }
22845
23017
  }
22846
- for (const ext of options.extensions) {
22847
- if (postfix &&
22848
- (res = tryResolveFile(fsPath + ext, '', options, false, targetWeb, options.tryPrefix, options.skipPackageJson, false))) {
22849
- return res;
23018
+ if (tryIndex && fileStat) {
23019
+ // Path points to a directory, check for package.json and entry and /index file
23020
+ const dirPath = file;
23021
+ if (!skipPackageJson) {
23022
+ let pkgPath = `${dirPath}/package.json`;
23023
+ try {
23024
+ if (fs$l.existsSync(pkgPath)) {
23025
+ if (!options.preserveSymlinks) {
23026
+ pkgPath = safeRealpathSync(pkgPath);
23027
+ }
23028
+ // path points to a node package
23029
+ const pkg = loadPackageData(pkgPath);
23030
+ return resolvePackageEntry(dirPath, pkg, targetWeb, options);
23031
+ }
23032
+ }
23033
+ catch (e) {
23034
+ if (e.code !== 'ENOENT')
23035
+ throw e;
23036
+ }
22850
23037
  }
22851
- if ((res = tryResolveFile(file + ext, postfix, options, false, targetWeb, options.tryPrefix, options.skipPackageJson, false))) {
23038
+ if ((res = tryResolveRealFileWithExtensions(`${dirPath}/index`, extensions, preserveSymlinks)))
22852
23039
  return res;
23040
+ if (tryPrefix) {
23041
+ if ((res = tryResolveRealFileWithExtensions(`${dirPath}/${options.tryPrefix}index`, extensions, preserveSymlinks)))
23042
+ return res;
22853
23043
  }
22854
23044
  }
22855
- // if `tryIndex` false, skip as we've already tested above
22856
- if (!tryIndex)
22857
- return;
22858
- if (postfix &&
22859
- (res = tryResolveFile(fsPath, '', options, tryIndex, targetWeb, options.tryPrefix, options.skipPackageJson))) {
22860
- return res;
22861
- }
22862
- if ((res = tryResolveFile(file, postfix, options, tryIndex, targetWeb, options.tryPrefix, options.skipPackageJson))) {
22863
- return res;
23045
+ }
23046
+ function tryResolveRealFile(file, preserveSymlinks) {
23047
+ const stat = tryStatSync(file);
23048
+ if (stat?.isFile())
23049
+ return getRealPath(file, preserveSymlinks);
23050
+ }
23051
+ function tryResolveRealFileWithExtensions(filePath, extensions, preserveSymlinks) {
23052
+ for (const ext of extensions) {
23053
+ const res = tryResolveRealFile(filePath + ext, preserveSymlinks);
23054
+ if (res)
23055
+ return res;
22864
23056
  }
22865
23057
  }
22866
- function tryResolveFile(file, postfix, options, tryIndex, targetWeb, tryPrefix, skipPackageJson, skipTsExtension) {
22867
- let stat;
23058
+ function tryStatSync(file) {
22868
23059
  try {
22869
- stat = fs$l.statSync(file, { throwIfNoEntry: false });
23060
+ return fs$l.statSync(file, { throwIfNoEntry: false });
22870
23061
  }
22871
23062
  catch {
22872
- return;
22873
- }
22874
- if (stat) {
22875
- if (!stat.isDirectory()) {
22876
- return getRealPath(file, options.preserveSymlinks) + postfix;
22877
- }
22878
- else if (tryIndex) {
22879
- if (!skipPackageJson) {
22880
- const pkgPath = file + '/package.json';
22881
- try {
22882
- // path points to a node package
22883
- const pkg = loadPackageData(pkgPath, options.preserveSymlinks);
22884
- const resolved = resolvePackageEntry(file, pkg, targetWeb, options);
22885
- return resolved;
22886
- }
22887
- catch (e) {
22888
- if (e.code !== 'ENOENT') {
22889
- throw e;
22890
- }
22891
- }
22892
- }
22893
- const index = tryFsResolve(file + '/index', options);
22894
- if (index)
22895
- return index + postfix;
22896
- }
22897
- }
22898
- // try resolve .js import to typescript file
22899
- if (!skipTsExtension &&
22900
- options.isFromTsImporter &&
22901
- isPossibleTsOutput(file)) {
22902
- const tsSrcPaths = getPotentialTsSrcPaths(file);
22903
- for (const srcPath of tsSrcPaths) {
22904
- const res = tryResolveFile(srcPath, postfix, options, tryIndex, targetWeb, tryPrefix, skipPackageJson, true);
22905
- if (res)
22906
- return res;
22907
- }
22908
- return;
22909
- }
22910
- if (tryPrefix) {
22911
- const prefixed = `${path$o.dirname(file)}/${tryPrefix}${path$o.basename(file)}`;
22912
- return tryResolveFile(prefixed, postfix, options, tryIndex, targetWeb);
23063
+ // Ignore errors
22913
23064
  }
22914
23065
  }
22915
23066
  const idToPkgMap = new Map();
22916
23067
  function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr = false, externalize, allowLinkedExternal = true) {
22917
23068
  const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options;
22918
- const possiblePkgIds = [];
22919
- for (let prevSlashIndex = -1;;) {
22920
- let slashIndex = id.indexOf('/', prevSlashIndex + 1);
22921
- if (slashIndex < 0) {
22922
- slashIndex = id.length;
22923
- }
22924
- const part = id.slice(prevSlashIndex + 1, (prevSlashIndex = slashIndex));
22925
- if (!part) {
22926
- break;
22927
- }
22928
- // Assume path parts with an extension are not package roots, except for the
22929
- // first path part (since periods are sadly allowed in package names).
22930
- // At the same time, skip the first path part if it begins with "@"
22931
- // (since "@foo/bar" should be treated as the top-level path).
22932
- if (possiblePkgIds.length ? path$o.extname(part) : part[0] === '@') {
22933
- continue;
22934
- }
22935
- const possiblePkgId = id.slice(0, slashIndex);
22936
- possiblePkgIds.push(possiblePkgId);
22937
- }
23069
+ // check for deep import, e.g. "my-lib/foo"
23070
+ const deepMatch = id.match(deepImportRE);
23071
+ const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : id;
22938
23072
  let basedir;
22939
- if (dedupe?.some((id) => possiblePkgIds.includes(id))) {
23073
+ if (dedupe?.includes(pkgId)) {
22940
23074
  basedir = root;
22941
23075
  }
22942
23076
  else if (importer &&
@@ -22947,25 +23081,8 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr = f
22947
23081
  else {
22948
23082
  basedir = root;
22949
23083
  }
22950
- let pkg;
22951
- let pkgId;
22952
- // nearest package.json
22953
- let nearestPkg;
22954
- const rootPkgId = possiblePkgIds[0];
22955
- const rootPkg = resolvePackageData(rootPkgId, basedir, preserveSymlinks, packageCache);
22956
- const nearestPkgId = [...possiblePkgIds].reverse().find((pkgId) => {
22957
- nearestPkg = resolvePackageData(pkgId, basedir, preserveSymlinks, packageCache);
22958
- return nearestPkg;
22959
- });
22960
- if (rootPkg?.data?.exports) {
22961
- pkgId = rootPkgId;
22962
- pkg = rootPkg;
22963
- }
22964
- else {
22965
- pkgId = nearestPkgId;
22966
- pkg = nearestPkg;
22967
- }
22968
- if (!pkg || !nearestPkg) {
23084
+ const pkg = resolvePackageData(pkgId, basedir, preserveSymlinks, packageCache);
23085
+ if (!pkg) {
22969
23086
  // if import can't be found, check if it's an optional peer dep.
22970
23087
  // if so, we can resolve to a special id that errors only when imported.
22971
23088
  if (basedir !== root && // root has no peer dep
@@ -22988,13 +23105,8 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr = f
22988
23105
  }
22989
23106
  return;
22990
23107
  }
22991
- let resolveId = resolvePackageEntry;
22992
- let unresolvedId = pkgId;
22993
- const isDeepImport = unresolvedId !== id;
22994
- if (isDeepImport) {
22995
- resolveId = resolveDeepImport;
22996
- unresolvedId = '.' + id.slice(pkgId.length);
22997
- }
23108
+ const resolveId = deepMatch ? resolveDeepImport : resolvePackageEntry;
23109
+ const unresolvedId = deepMatch ? '.' + id.slice(pkgId.length) : pkgId;
22998
23110
  let resolved;
22999
23111
  try {
23000
23112
  resolved = resolveId(unresolvedId, pkg, targetWeb, options);
@@ -23032,12 +23144,10 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr = f
23032
23144
  return resolved;
23033
23145
  }
23034
23146
  let resolvedId = id;
23035
- if (isDeepImport) {
23036
- if (!pkg?.data.exports && path$o.extname(id) !== resolvedExt) {
23037
- resolvedId = resolved.id.slice(resolved.id.indexOf(id));
23038
- isDebug$4 &&
23039
- debug$c(`[processResult] ${picocolorsExports.cyan(id)} -> ${picocolorsExports.dim(resolvedId)}`);
23040
- }
23147
+ if (deepMatch && !pkg?.data.exports && path$o.extname(id) !== resolvedExt) {
23148
+ resolvedId = resolved.id.slice(resolved.id.indexOf(id));
23149
+ isDebug$4 &&
23150
+ debug$c(`[processResult] ${picocolorsExports.cyan(id)} -> ${picocolorsExports.dim(resolvedId)}`);
23041
23151
  }
23042
23152
  return { ...resolved, id: resolvedId, external: true };
23043
23153
  };
@@ -23052,7 +23162,6 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr = f
23052
23162
  });
23053
23163
  }
23054
23164
  const ext = path$o.extname(resolved);
23055
- const isCJS = ext === '.cjs' || (ext === '.js' && nearestPkg.data.type !== 'module');
23056
23165
  if (!options.ssrOptimizeCheck &&
23057
23166
  (!resolved.includes('node_modules') || // linked
23058
23167
  !depsOptimizer || // resolving before listening to the server
@@ -23081,7 +23190,12 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr = f
23081
23190
  // The only optimized deps are the ones explicitly listed in the config.
23082
23191
  (!options.ssrOptimizeCheck && !isBuild && ssr) ||
23083
23192
  // Only optimize non-external CJS deps during SSR by default
23084
- (ssr && !isCJS && !(include?.includes(pkgId) || include?.includes(id)));
23193
+ (ssr &&
23194
+ !(ext === '.cjs' ||
23195
+ (ext === '.js' &&
23196
+ findNearestPackageData(path$o.dirname(resolved), options.packageCache)
23197
+ ?.data.type !== 'module')) &&
23198
+ !(include?.includes(pkgId) || include?.includes(id)));
23085
23199
  if (options.ssrOptimizeCheck) {
23086
23200
  return {
23087
23201
  id: skipOptimization
@@ -23237,18 +23351,21 @@ function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache
23237
23351
  : ['index.js', 'index.json', 'index.node'];
23238
23352
  for (let entry of entryPoints) {
23239
23353
  // make sure we don't get scripts when looking for sass
23354
+ let skipPackageJson = false;
23240
23355
  if (options.mainFields[0] === 'sass' &&
23241
23356
  !options.extensions.includes(path$o.extname(entry))) {
23242
23357
  entry = '';
23243
- options.skipPackageJson = true;
23358
+ skipPackageJson = true;
23244
23359
  }
23245
- // resolve object browser field in package.json
23246
- const { browser: browserField } = data;
23247
- if (targetWeb && options.browserField && isObject$2(browserField)) {
23248
- entry = mapWithBrowserField(entry, browserField) || entry;
23360
+ else {
23361
+ // resolve object browser field in package.json
23362
+ const { browser: browserField } = data;
23363
+ if (targetWeb && options.browserField && isObject$2(browserField)) {
23364
+ entry = mapWithBrowserField(entry, browserField) || entry;
23365
+ }
23249
23366
  }
23250
23367
  const entryPointPath = path$o.join(dir, entry);
23251
- const resolvedEntryPoint = tryFsResolve(entryPointPath, options);
23368
+ const resolvedEntryPoint = tryFsResolve(entryPointPath, options, true, true, skipPackageJson);
23252
23369
  if (resolvedEntryPoint) {
23253
23370
  isDebug$4 &&
23254
23371
  debug$c(`[package entry] ${picocolorsExports.cyan(id)} -> ${picocolorsExports.dim(resolvedEntryPoint)}`);
@@ -23352,7 +23469,9 @@ function resolveDeepImport(id, { webResolvedImports, setResolvedCache, getResolv
23352
23469
  }
23353
23470
  function tryResolveBrowserMapping(id, importer, options, isFilePath, externalize) {
23354
23471
  let res;
23355
- const pkg = importer && (idToPkgMap.get(importer) || resolvePkg(importer, options));
23472
+ const pkg = importer &&
23473
+ (idToPkgMap.get(importer) ||
23474
+ findNearestPackageData(path$o.dirname(importer), options.packageCache));
23356
23475
  if (pkg && isObject$2(pkg.data.browser)) {
23357
23476
  const mapId = isFilePath ? './' + slash$1(path$o.relative(pkg.dir, id)) : id;
23358
23477
  const browserMappedPath = mapWithBrowserField(mapId, pkg.data.browser);
@@ -23400,40 +23519,10 @@ function equalWithoutSuffix(path, key, suffix) {
23400
23519
  function getRealPath(resolved, preserveSymlinks) {
23401
23520
  resolved = ensureVolumeInPath(resolved);
23402
23521
  if (!preserveSymlinks && browserExternalId !== resolved) {
23403
- resolved = fs$l.realpathSync(resolved);
23522
+ resolved = safeRealpathSync(resolved);
23404
23523
  }
23405
23524
  return normalizePath$3(resolved);
23406
23525
  }
23407
- /**
23408
- * if importer was not resolved by vite's resolver previously
23409
- * (when esbuild resolved it)
23410
- * resolve importer's pkg and add to idToPkgMap
23411
- */
23412
- function resolvePkg(importer, options) {
23413
- const { root, preserveSymlinks, packageCache } = options;
23414
- if (importer.includes('\x00')) {
23415
- return null;
23416
- }
23417
- const possiblePkgIds = [];
23418
- for (let prevSlashIndex = -1;;) {
23419
- const slashIndex = importer.indexOf(isWindows$4 ? '\\' : '/', prevSlashIndex);
23420
- if (slashIndex < 0) {
23421
- break;
23422
- }
23423
- prevSlashIndex = slashIndex + 1;
23424
- const possiblePkgId = importer.slice(0, slashIndex);
23425
- possiblePkgIds.push(possiblePkgId);
23426
- }
23427
- let pkg;
23428
- possiblePkgIds.reverse().find((pkgId) => {
23429
- pkg = resolvePackageData(pkgId, root, preserveSymlinks, packageCache);
23430
- return pkg;
23431
- });
23432
- if (pkg) {
23433
- idToPkgMap.set(importer, pkg);
23434
- }
23435
- return pkg;
23436
- }
23437
23526
 
23438
23527
  const externalWithConversionNamespace = 'vite:dep-pre-bundle:external-conversion';
23439
23528
  const convertedExternalPrefix = 'vite-dep-pre-bundle-external:';
@@ -23469,13 +23558,22 @@ function esbuildDepPlugin(qualified, external, config, ssr) {
23469
23558
  const allExternalTypes = extensions
23470
23559
  ? externalTypes.filter((type) => !extensions?.includes('.' + type))
23471
23560
  : externalTypes;
23561
+ // use separate package cache for optimizer as it caches paths around node_modules
23562
+ // and it's unlikely for the core Vite process to traverse into node_modules again
23563
+ const esmPackageCache = new Map();
23564
+ const cjsPackageCache = new Map();
23472
23565
  // default resolver which prefers ESM
23473
- const _resolve = config.createResolver({ asSrc: false, scan: true });
23566
+ const _resolve = config.createResolver({
23567
+ asSrc: false,
23568
+ scan: true,
23569
+ packageCache: esmPackageCache,
23570
+ });
23474
23571
  // cjs resolver that prefers Node
23475
23572
  const _resolveRequire = config.createResolver({
23476
23573
  asSrc: false,
23477
23574
  isRequire: true,
23478
23575
  scan: true,
23576
+ packageCache: cjsPackageCache,
23479
23577
  });
23480
23578
  const resolve = (id, importer, kind, resolveDir) => {
23481
23579
  let _importer;
@@ -23520,6 +23618,11 @@ function esbuildDepPlugin(qualified, external, config, ssr) {
23520
23618
  return {
23521
23619
  name: 'vite:dep-pre-bundle',
23522
23620
  setup(build) {
23621
+ // clear package cache when esbuild is finished
23622
+ build.onEnd(() => {
23623
+ esmPackageCache.clear();
23624
+ cjsPackageCache.clear();
23625
+ });
23523
23626
  // externalize assets and commonly known non-js file types
23524
23627
  // See #8459 for more details about this require-import conversion
23525
23628
  build.onResolve({
@@ -23647,14 +23750,14 @@ module.exports = Object.create(new Proxy({}, {
23647
23750
  },
23648
23751
  };
23649
23752
  }
23753
+ const matchesEntireLine = (text) => `^${escapeRegex(text)}$`;
23650
23754
  // esbuild doesn't transpile `require('foo')` into `import` statements if 'foo' is externalized
23651
23755
  // https://github.com/evanw/esbuild/issues/566#issuecomment-735551834
23652
23756
  function esbuildCjsExternalPlugin(externals, platform) {
23653
23757
  return {
23654
23758
  name: 'cjs-external',
23655
23759
  setup(build) {
23656
- const escape = (text) => `^${text.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')}$`;
23657
- const filter = new RegExp(externals.map(escape).join('|'));
23760
+ const filter = new RegExp(externals.map(matchesEntireLine).join('|'));
23658
23761
  build.onResolve({ filter: new RegExp(`^${nonFacadePrefix}`) }, (args) => {
23659
23762
  return {
23660
23763
  path: args.path.slice(nonFacadePrefix.length),
@@ -28341,7 +28444,7 @@ function createIsSsrExternal(config) {
28341
28444
  return processedIds.get(id);
28342
28445
  }
28343
28446
  let external = false;
28344
- if (!id.startsWith('.') && !path$o.isAbsolute(id)) {
28447
+ if (id[0] !== '.' && !path$o.isAbsolute(id)) {
28345
28448
  external = isBuiltin(id) || isConfiguredAsExternal(id);
28346
28449
  }
28347
28450
  processedIds.set(id, external);
@@ -28381,18 +28484,17 @@ function cjsSsrCollectExternals(root, resolveOptions, ssrExternals, seen, logger
28381
28484
  requireEntry = normalizePath$3(_require$2.resolve(id, { paths: [root] }));
28382
28485
  }
28383
28486
  catch (e) {
28384
- try {
28385
- // no main entry, but deep imports may be allowed
28386
- const pkgPath = resolveFrom(`${id}/package.json`, root);
28387
- if (pkgPath.includes('node_modules')) {
28487
+ // no main entry, but deep imports may be allowed
28488
+ const pkgDir = resolvePackageData(id, root)?.dir;
28489
+ if (pkgDir) {
28490
+ if (pkgDir.includes('node_modules')) {
28388
28491
  ssrExternals.add(id);
28389
28492
  }
28390
28493
  else {
28391
- depsToTrace.add(path$o.dirname(pkgPath));
28494
+ depsToTrace.add(path$o.dirname(pkgDir));
28392
28495
  }
28393
28496
  continue;
28394
28497
  }
28395
- catch { }
28396
28498
  // resolve failed, assume include
28397
28499
  debug$b(`Failed to resolve entries for package "${id}"\n`, e);
28398
28500
  continue;
@@ -28403,8 +28505,10 @@ function cjsSsrCollectExternals(root, resolveOptions, ssrExternals, seen, logger
28403
28505
  }
28404
28506
  // trace the dependencies of linked packages
28405
28507
  else if (!esmEntry.includes('node_modules')) {
28406
- const pkgPath = resolveFrom(`${id}/package.json`, root);
28407
- depsToTrace.add(path$o.dirname(pkgPath));
28508
+ const pkgDir = resolvePackageData(id, root)?.dir;
28509
+ if (pkgDir) {
28510
+ depsToTrace.add(pkgDir);
28511
+ }
28408
28512
  }
28409
28513
  // has separate esm/require entry, assume require entry is cjs
28410
28514
  else if (esmEntry !== requireEntry) {
@@ -28414,12 +28518,10 @@ function cjsSsrCollectExternals(root, resolveOptions, ssrExternals, seen, logger
28414
28518
  // or are there others like SystemJS / AMD that we'd need to handle?
28415
28519
  // for now, we'll just leave this as is
28416
28520
  else if (/\.m?js$/.test(esmEntry)) {
28417
- const pkgPath = resolveFrom(`${id}/package.json`, root);
28418
- const pkgContent = fs$l.readFileSync(pkgPath, 'utf-8');
28419
- if (!pkgContent) {
28521
+ const pkg = resolvePackageData(id, root)?.data;
28522
+ if (!pkg) {
28420
28523
  continue;
28421
28524
  }
28422
- const pkg = JSON.parse(pkgContent);
28423
28525
  if (pkg.type === 'module' || esmEntry.endsWith('.mjs')) {
28424
28526
  ssrExternals.add(id);
28425
28527
  continue;
@@ -28455,7 +28557,7 @@ function cjsShouldExternalizeForSSR(id, externals) {
28455
28557
  }
28456
28558
  function getNpmPackageName(importPath) {
28457
28559
  const parts = importPath.split('/');
28458
- if (parts[0].startsWith('@')) {
28560
+ if (parts[0][0] === '@') {
28459
28561
  if (!parts[1])
28460
28562
  return null;
28461
28563
  return `${parts[0]}/${parts[1]}`;
@@ -28528,7 +28630,7 @@ const debug$a = createDebugger('vite:optimize-deps');
28528
28630
  function optimizedDepsPlugin(config) {
28529
28631
  return {
28530
28632
  name: 'vite:optimized-deps',
28531
- async resolveId(id, source, { ssr }) {
28633
+ resolveId(id, source, { ssr }) {
28532
28634
  if (getDepsOptimizer(config, ssr)?.isOptimizedDepFile(id)) {
28533
28635
  return id;
28534
28636
  }
@@ -28596,7 +28698,7 @@ function optimizedDepsBuildPlugin(config) {
28596
28698
  getDepsOptimizer(config)?.resetRegisteredIds();
28597
28699
  }
28598
28700
  },
28599
- async resolveId(id, importer, { ssr }) {
28701
+ resolveId(id, importer, { ssr }) {
28600
28702
  if (getDepsOptimizer(config, ssr)?.isOptimizedDepFile(id)) {
28601
28703
  return id;
28602
28704
  }
@@ -37090,7 +37192,7 @@ function buildHtmlPlugin(config) {
37090
37192
  preHooks.push(htmlEnvHook(config));
37091
37193
  postHooks.push(postImportMapHook());
37092
37194
  const processedHtml = new Map();
37093
- const isExcludedUrl = (url) => url.startsWith('#') ||
37195
+ const isExcludedUrl = (url) => url[0] === '#' ||
37094
37196
  isExternalUrl(url) ||
37095
37197
  isDataUrl(url) ||
37096
37198
  checkPublicFile(url, config);
@@ -37269,7 +37371,7 @@ function buildHtmlPlugin(config) {
37269
37371
  const content = decodeURI(attr.value);
37270
37372
  if (content !== '' && // Empty attribute
37271
37373
  !namedOutput.includes(content) && // Direct reference to named output
37272
- !namedOutput.includes(content.replace(/^\//, '')) // Allow for absolute references as named output can't be an absolute path
37374
+ !namedOutput.includes(removeLeadingSlash(content)) // Allow for absolute references as named output can't be an absolute path
37273
37375
  ) {
37274
37376
  try {
37275
37377
  const url = attr.prefix === undefined && attr.name === 'srcset'
@@ -37469,7 +37571,10 @@ function buildHtmlPlugin(config) {
37469
37571
  return toOutputAssetFilePath(this.getFileName(fileHash)) + postfix;
37470
37572
  });
37471
37573
  result = result.replace(publicAssetUrlRE, (_, fileHash) => {
37472
- return normalizePath$3(toOutputPublicAssetFilePath(getPublicAssetFilename(fileHash, config)));
37574
+ const publicAssetPath = toOutputPublicAssetFilePath(getPublicAssetFilename(fileHash, config));
37575
+ return isUrl(publicAssetPath)
37576
+ ? publicAssetPath
37577
+ : normalizePath$3(publicAssetPath);
37473
37578
  });
37474
37579
  if (chunk && canInlineEntry) {
37475
37580
  // all imports from entry have been inlined to html, prevent rollup from outputting it
@@ -37755,7 +37860,7 @@ const isDirectCSSRequest = (request) => CSS_LANGS_RE.test(request) && directRequ
37755
37860
  const isDirectRequest = (request) => directRequestRE.test(request);
37756
37861
  const cssModulesCache = new WeakMap();
37757
37862
  const removedPureCssFilesCache = new WeakMap();
37758
- const postcssConfigCache = {};
37863
+ const postcssConfigCache = new WeakMap();
37759
37864
  function encodePublicUrlsInCSS(config) {
37760
37865
  return config.command === 'build';
37761
37866
  }
@@ -37770,6 +37875,8 @@ function cssPlugin(config) {
37770
37875
  tryIndex: false,
37771
37876
  extensions: [],
37772
37877
  });
37878
+ // warm up cache for resolved postcss config
37879
+ resolvePostcssConfig(config);
37773
37880
  return {
37774
37881
  name: 'vite:css',
37775
37882
  configureServer(_server) {
@@ -38017,9 +38124,7 @@ function cssPostPlugin(config) {
38017
38124
  const toRelative = (filename, importer) => {
38018
38125
  // relative base + extracted CSS
38019
38126
  const relativePath = path$o.posix.relative(cssAssetDirname, filename);
38020
- return relativePath.startsWith('.')
38021
- ? relativePath
38022
- : './' + relativePath;
38127
+ return relativePath[0] === '.' ? relativePath : './' + relativePath;
38023
38128
  };
38024
38129
  // replace asset url references with resolved url.
38025
38130
  chunkCSS = chunkCSS.replace(assetUrlRE, (_, fileHash, postfix = '') => {
@@ -38231,7 +38336,7 @@ async function compileCSS(id, code, config, urlReplacer) {
38231
38336
  const needInlineImport = code.includes('@import');
38232
38337
  const hasUrl = cssUrlRE.test(code) || cssImageSetRE.test(code);
38233
38338
  const lang = id.match(CSS_LANGS_RE)?.[1];
38234
- const postcssConfig = await resolvePostcssConfig(config, getCssDialect(lang));
38339
+ const postcssConfig = await resolvePostcssConfig(config);
38235
38340
  // 1. plain css that needs no processing
38236
38341
  if (lang === 'css' &&
38237
38342
  !postcssConfig &&
@@ -38291,10 +38396,6 @@ async function compileCSS(id, code, config, urlReplacer) {
38291
38396
  }
38292
38397
  // 3. postcss
38293
38398
  const postcssOptions = (postcssConfig && postcssConfig.options) || {};
38294
- // for sugarss change parser
38295
- if (lang === 'sss') {
38296
- postcssOptions.parser = loadPreprocessor("sugarss" /* PostCssDialectLang.sss */, config.root);
38297
- }
38298
38399
  const postcssPlugins = postcssConfig && postcssConfig.plugins ? postcssConfig.plugins.slice() : [];
38299
38400
  if (needInlineImport) {
38300
38401
  postcssPlugins.unshift((await import('./dep-53dc1ef4.js').then(function (n) { return n.i; })).default({
@@ -38321,7 +38422,7 @@ async function compileCSS(id, code, config, urlReplacer) {
38321
38422
  }));
38322
38423
  }
38323
38424
  if (isModule) {
38324
- postcssPlugins.unshift((await import('./dep-f63b56ae.js').then(function (n) { return n.i; })).default({
38425
+ postcssPlugins.unshift((await import('./dep-be7bf3d1.js').then(function (n) { return n.i; })).default({
38325
38426
  ...modulesOptions,
38326
38427
  localsConvention: modulesOptions?.localsConvention,
38327
38428
  getJSON(cssFileName, _modules, outputFileName) {
@@ -38355,6 +38456,9 @@ async function compileCSS(id, code, config, urlReplacer) {
38355
38456
  .default(postcssPlugins)
38356
38457
  .process(code, {
38357
38458
  ...postcssOptions,
38459
+ parser: lang === 'sss'
38460
+ ? loadPreprocessor("sugarss" /* PostCssDialectLang.sss */, config.root)
38461
+ : postcssOptions.parser,
38358
38462
  to: source,
38359
38463
  from: source,
38360
38464
  ...(devSourcemap
@@ -38438,12 +38542,12 @@ async function compileCSS(id, code, config, urlReplacer) {
38438
38542
  async function preprocessCSS(code, filename, config) {
38439
38543
  return await compileCSS(filename, code, config);
38440
38544
  }
38545
+ const postcssReturnsVirtualFilesRE = /^<.+>$/;
38441
38546
  async function formatPostcssSourceMap(rawMap, file) {
38442
38547
  const inputFileDir = path$o.dirname(file);
38443
38548
  const sources = rawMap.sources.map((source) => {
38444
38549
  const cleanSource = cleanUrl(decodeURIComponent(source));
38445
- // postcss returns virtual files
38446
- if (/^<.+>$/.test(cleanSource)) {
38550
+ if (postcssReturnsVirtualFilesRE.test(cleanSource)) {
38447
38551
  return `\0${cleanSource}`;
38448
38552
  }
38449
38553
  return normalizePath$3(path$o.resolve(inputFileDir, cleanSource));
@@ -38477,11 +38581,10 @@ async function finalizeCss(css, minify, config) {
38477
38581
  }
38478
38582
  return css;
38479
38583
  }
38480
- async function resolvePostcssConfig(config, dialect = 'css') {
38481
- postcssConfigCache[dialect] ?? (postcssConfigCache[dialect] = new WeakMap());
38482
- let result = postcssConfigCache[dialect].get(config);
38584
+ async function resolvePostcssConfig(config) {
38585
+ let result = postcssConfigCache.get(config);
38483
38586
  if (result !== undefined) {
38484
- return result;
38587
+ return await result;
38485
38588
  }
38486
38589
  // inline postcss config via vite config
38487
38590
  const inlineOptions = config.css?.postcss;
@@ -38495,10 +38598,7 @@ async function resolvePostcssConfig(config, dialect = 'css') {
38495
38598
  }
38496
38599
  else {
38497
38600
  const searchPath = typeof inlineOptions === 'string' ? inlineOptions : config.root;
38498
- try {
38499
- result = await src$1({}, searchPath);
38500
- }
38501
- catch (e) {
38601
+ result = src$1({}, searchPath).catch((e) => {
38502
38602
  if (!/No PostCSS Config found/.test(e.message)) {
38503
38603
  if (e instanceof Error) {
38504
38604
  const { name, message, stack } = e;
@@ -38511,10 +38611,14 @@ async function resolvePostcssConfig(config, dialect = 'css') {
38511
38611
  throw new Error(`Failed to load PostCSS config: ${e}`);
38512
38612
  }
38513
38613
  }
38514
- result = null;
38515
- }
38614
+ return null;
38615
+ });
38616
+ // replace cached promise to result object when finished
38617
+ result.then((resolved) => {
38618
+ postcssConfigCache.set(config, resolved);
38619
+ });
38516
38620
  }
38517
- postcssConfigCache[dialect].set(config, result);
38621
+ postcssConfigCache.set(config, result);
38518
38622
  return result;
38519
38623
  }
38520
38624
  // https://drafts.csswg.org/css-syntax-3/#identifier-code-point
@@ -38608,7 +38712,7 @@ async function doUrlReplace(rawUrl, matched, replacer, funcName = 'url') {
38608
38712
  }
38609
38713
  if (isExternalUrl(rawUrl) ||
38610
38714
  isDataUrl(rawUrl) ||
38611
- rawUrl.startsWith('#') ||
38715
+ rawUrl[0] === '#' ||
38612
38716
  varRE.test(rawUrl)) {
38613
38717
  return matched;
38614
38718
  }
@@ -38626,7 +38730,7 @@ async function doImportCSSReplace(rawUrl, matched, replacer) {
38626
38730
  wrap = first;
38627
38731
  rawUrl = rawUrl.slice(1, -1);
38628
38732
  }
38629
- if (isExternalUrl(rawUrl) || isDataUrl(rawUrl) || rawUrl.startsWith('#')) {
38733
+ if (isExternalUrl(rawUrl) || isDataUrl(rawUrl) || rawUrl[0] === '#') {
38630
38734
  return matched;
38631
38735
  }
38632
38736
  return `@import ${wrap}${await replacer(rawUrl)}${wrap}`;
@@ -38729,7 +38833,7 @@ function cleanScssBugUrl(url) {
38729
38833
  if (
38730
38834
  // check bug via `window` and `location` global
38731
38835
  typeof window !== 'undefined' &&
38732
- typeof location !== 'undefined') {
38836
+ typeof location?.href === 'string') {
38733
38837
  const prefix = location.href.replace(/\/$/, '');
38734
38838
  return url.replace(prefix, '');
38735
38839
  }
@@ -38849,7 +38953,7 @@ async function rebaseUrls(file, rootFile, alias, variablePrefix) {
38849
38953
  }
38850
38954
  let rebased;
38851
38955
  const rebaseFn = (url) => {
38852
- if (url.startsWith('/'))
38956
+ if (url[0] === '/')
38853
38957
  return url;
38854
38958
  // ignore url's starting with variable
38855
38959
  if (url.startsWith(variablePrefix))
@@ -39055,9 +39159,6 @@ const preProcessors = Object.freeze({
39055
39159
  function isPreProcessor(lang) {
39056
39160
  return lang && lang in preProcessors;
39057
39161
  }
39058
- function getCssDialect(lang) {
39059
- return lang === 'sss' ? 'sss' : 'css';
39060
- }
39061
39162
 
39062
39163
  // AST walker module for Mozilla Parser API compatible trees
39063
39164
 
@@ -39608,7 +39709,7 @@ async function transformGlobImport(code, id, root, resolveId, isProduction, rest
39608
39709
  : typeof options.query === 'string'
39609
39710
  ? options.query
39610
39711
  : stringifyQuery(options.query);
39611
- if (query && !query.startsWith('?'))
39712
+ if (query && query[0] !== '?')
39612
39713
  query = `?${query}`;
39613
39714
  const resolvePaths = (file) => {
39614
39715
  if (!dir) {
@@ -39618,7 +39719,7 @@ async function transformGlobImport(code, id, root, resolveId, isProduction, rest
39618
39719
  return { filePath, importPath: filePath };
39619
39720
  }
39620
39721
  let importPath = relative(dir, file);
39621
- if (!importPath.startsWith('.'))
39722
+ if (importPath[0] !== '.')
39622
39723
  importPath = `./${importPath}`;
39623
39724
  let filePath;
39624
39725
  if (isRelative) {
@@ -39626,7 +39727,7 @@ async function transformGlobImport(code, id, root, resolveId, isProduction, rest
39626
39727
  }
39627
39728
  else {
39628
39729
  filePath = relative(root, file);
39629
- if (!filePath.startsWith('.'))
39730
+ if (filePath[0] !== '.')
39630
39731
  filePath = `/${filePath}`;
39631
39732
  }
39632
39733
  return { filePath, importPath };
@@ -39727,13 +39828,13 @@ function globSafeResolvedPath(resolved, glob) {
39727
39828
  }
39728
39829
  async function toAbsoluteGlob(glob, root, importer, resolveId) {
39729
39830
  let pre = '';
39730
- if (glob.startsWith('!')) {
39831
+ if (glob[0] === '!') {
39731
39832
  pre = '!';
39732
39833
  glob = glob.slice(1);
39733
39834
  }
39734
39835
  root = globSafePath(root);
39735
39836
  const dir = importer ? globSafePath(dirname(importer)) : root;
39736
- if (glob.startsWith('/'))
39837
+ if (glob[0] === '/')
39737
39838
  return pre + posix$1.join(root, glob.slice(1));
39738
39839
  if (glob.startsWith('./'))
39739
39840
  return pre + posix$1.join(dir, glob.slice(2));
@@ -39749,7 +39850,7 @@ async function toAbsoluteGlob(glob, root, importer, resolveId) {
39749
39850
  }
39750
39851
  function getCommonBase(globsResolved) {
39751
39852
  const bases = globsResolved
39752
- .filter((g) => !g.startsWith('!'))
39853
+ .filter((g) => g[0] !== '!')
39753
39854
  .map((glob) => {
39754
39855
  let { base } = scan(glob);
39755
39856
  // `scan('a/foo.js')` returns `base: 'a/foo.js'`
@@ -39774,10 +39875,11 @@ function getCommonBase(globsResolved) {
39774
39875
  }
39775
39876
  function isVirtualModule(id) {
39776
39877
  // https://vitejs.dev/guide/api-plugin.html#virtual-modules-convention
39777
- return id.startsWith('virtual:') || id.startsWith('\0') || !id.includes('/');
39878
+ return id.startsWith('virtual:') || id[0] === '\0' || !id.includes('/');
39778
39879
  }
39779
39880
 
39780
39881
  const debugHmr = createDebugger('vite:hmr');
39882
+ const whitespaceRE = /\s/;
39781
39883
  const normalizedClientDir = normalizePath$3(CLIENT_DIR);
39782
39884
  function getShortName(file, root) {
39783
39885
  return file.startsWith(root + '/') ? path$o.posix.relative(root, file) : file;
@@ -40035,7 +40137,7 @@ function lexAcceptedHmrDeps(code, start, urls) {
40035
40137
  prevState = state;
40036
40138
  state = 3 /* LexerState.inTemplateString */;
40037
40139
  }
40038
- else if (/\s/.test(char)) {
40140
+ else if (whitespaceRE.test(char)) {
40039
40141
  continue;
40040
40142
  }
40041
40143
  else {
@@ -40126,7 +40228,7 @@ function lexAcceptedHmrExports(code, start, exportNames) {
40126
40228
  return urls.size > 0;
40127
40229
  }
40128
40230
  function normalizeHmrUrl(url) {
40129
- if (!url.startsWith('.') && !url.startsWith('/')) {
40231
+ if (url[0] !== '.' && url[0] !== '/') {
40130
40232
  url = wrapId(url);
40131
40233
  }
40132
40234
  return url;
@@ -40770,6 +40872,7 @@ function sirv (dir, opts={}) {
40770
40872
  };
40771
40873
  }
40772
40874
 
40875
+ const knownJavascriptExtensionRE = /\.[tj]sx?$/;
40773
40876
  const sirvOptions = ({ headers, shouldServe, }) => {
40774
40877
  return {
40775
40878
  dev: true,
@@ -40781,7 +40884,7 @@ const sirvOptions = ({ headers, shouldServe, }) => {
40781
40884
  // for the MIME type video/mp2t. In almost all cases, we can expect
40782
40885
  // these files to be TypeScript files, and for Vite to serve them with
40783
40886
  // this Content-Type.
40784
- if (/\.[tj]sx?$/.test(pathname)) {
40887
+ if (knownJavascriptExtensionRE.test(pathname)) {
40785
40888
  res.setHeader('Content-Type', 'application/javascript');
40786
40889
  }
40787
40890
  if (headers) {
@@ -40818,7 +40921,7 @@ function serveStaticMiddleware(dir, server) {
40818
40921
  // special processing
40819
40922
  // also skip internal requests `/@fs/ /@vite-client` etc...
40820
40923
  const cleanedUrl = cleanUrl(req.url);
40821
- if (cleanedUrl.endsWith('/') ||
40924
+ if (cleanedUrl[cleanedUrl.length - 1] === '/' ||
40822
40925
  path$o.extname(cleanedUrl) === '.html' ||
40823
40926
  isInternalRequest(req.url)) {
40824
40927
  return next();
@@ -40843,8 +40946,9 @@ function serveStaticMiddleware(dir, server) {
40843
40946
  }
40844
40947
  }
40845
40948
  const resolvedPathname = redirectedPathname || pathname;
40846
- let fileUrl = path$o.resolve(dir, resolvedPathname.replace(/^\//, ''));
40847
- if (resolvedPathname.endsWith('/') && !fileUrl.endsWith('/')) {
40949
+ let fileUrl = path$o.resolve(dir, removeLeadingSlash(resolvedPathname));
40950
+ if (resolvedPathname[resolvedPathname.length - 1] === '/' &&
40951
+ fileUrl[fileUrl.length - 1] !== '/') {
40848
40952
  fileUrl = fileUrl + '/';
40849
40953
  }
40850
40954
  if (!ensureServingAccess(fileUrl, server, res, next)) {
@@ -41034,7 +41138,7 @@ async function loadAndTransform(id, url, server, options, timestamp) {
41034
41138
  let code = null;
41035
41139
  let map = null;
41036
41140
  // load
41037
- const loadStart = isDebug$2 ? performance.now() : 0;
41141
+ const loadStart = isDebug$2 ? performance$1.now() : 0;
41038
41142
  const loadResult = await pluginContainer.load(id, { ssr });
41039
41143
  if (loadResult == null) {
41040
41144
  // if this is an html request and there is no load result, skip ahead to
@@ -41101,7 +41205,7 @@ async function loadAndTransform(id, url, server, options, timestamp) {
41101
41205
  const mod = await moduleGraph.ensureEntryFromUrl(url, ssr);
41102
41206
  ensureWatchedFile(watcher, mod.file, root);
41103
41207
  // transform
41104
- const transformStart = isDebug$2 ? performance.now() : 0;
41208
+ const transformStart = isDebug$2 ? performance$1.now() : 0;
41105
41209
  const transformResult = await pluginContainer.transform(code, id, {
41106
41210
  inMap: map,
41107
41211
  ssr,
@@ -41180,6 +41284,10 @@ const skipRE = /\.(?:map|json)(?:$|\?)/;
41180
41284
  const canSkipImportAnalysis = (id) => skipRE.test(id) || isDirectCSSRequest(id);
41181
41285
  const optimizedDepChunkRE$1 = /\/chunk-[A-Z\d]{8}\.js/;
41182
41286
  const optimizedDepDynamicRE$1 = /-[A-Z\d]{8}\.js/;
41287
+ const hasImportInQueryParamsRE = /[?&]import=?\b/;
41288
+ const hasViteIgnoreRE = /\/\*\s*@vite-ignore\s*\*\//;
41289
+ const cleanUpRawUrlRE = /\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm;
41290
+ const urlIsStringRE = /^(?:'.*'|".*"|`.*`)$/;
41183
41291
  function isExplicitImportRequired(url) {
41184
41292
  return !isJSRequest(cleanUrl(url)) && !isCSSRequest(url);
41185
41293
  }
@@ -41291,7 +41399,7 @@ function importAnalysisPlugin(config) {
41291
41399
  isDebug$1 && debug$9(picocolorsExports.dim(`[skipped] ${prettyImporter}`));
41292
41400
  return null;
41293
41401
  }
41294
- const start = performance.now();
41402
+ const start = performance$1.now();
41295
41403
  await init;
41296
41404
  let imports;
41297
41405
  let exports;
@@ -41377,7 +41485,7 @@ function importAnalysisPlugin(config) {
41377
41485
  importerModule.isSelfAccepting = false;
41378
41486
  return this.error(`Failed to resolve import "${url}" from "${path$o.relative(process.cwd(), importerFile)}". Does the file exist?`, pos);
41379
41487
  }
41380
- const isRelative = url.startsWith('.');
41488
+ const isRelative = url[0] === '.';
41381
41489
  const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer);
41382
41490
  // normalize all imports into resolved URLs
41383
41491
  // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js'`
@@ -41400,7 +41508,7 @@ function importAnalysisPlugin(config) {
41400
41508
  // if the resolved id is not a valid browser import specifier,
41401
41509
  // prefix it to make it valid. We will strip this before feeding it
41402
41510
  // back into the transform pipeline
41403
- if (!url.startsWith('.') && !url.startsWith('/')) {
41511
+ if (url[0] !== '.' && url[0] !== '/') {
41404
41512
  url = wrapId(resolved.id);
41405
41513
  }
41406
41514
  // make the URL browser-valid if not SSR
@@ -41413,7 +41521,7 @@ function importAnalysisPlugin(config) {
41413
41521
  // do not do this for unknown type imports, otherwise the appended
41414
41522
  // query can break 3rd party plugin's extension checks.
41415
41523
  if ((isRelative || isSelfImport) &&
41416
- !/[?&]import=?\b/.test(url) &&
41524
+ !hasImportInQueryParamsRE.test(url) &&
41417
41525
  !url.match(DEP_VERSION_RE)) {
41418
41526
  const versionMatch = importer.match(DEP_VERSION_RE);
41419
41527
  if (versionMatch) {
@@ -41500,7 +41608,7 @@ function importAnalysisPlugin(config) {
41500
41608
  continue;
41501
41609
  }
41502
41610
  // warn imports to non-asset /public files
41503
- if (specifier.startsWith('/') &&
41611
+ if (specifier[0] === '/' &&
41504
41612
  !config.assetsInclude(cleanUrl(specifier)) &&
41505
41613
  !specifier.endsWith('.json') &&
41506
41614
  checkPublicFile(specifier, config)) {
@@ -41588,7 +41696,7 @@ function importAnalysisPlugin(config) {
41588
41696
  else if (!importer.startsWith(clientDir)) {
41589
41697
  if (!importer.includes('node_modules')) {
41590
41698
  // check @vite-ignore which suppresses dynamic import warning
41591
- const hasViteIgnore = /\/\*\s*@vite-ignore\s*\*\//.test(
41699
+ const hasViteIgnore = hasViteIgnoreRE.test(
41592
41700
  // complete expression inside parens
41593
41701
  source.slice(dynamicIndex + 1, end));
41594
41702
  if (!hasViteIgnore) {
@@ -41604,10 +41712,8 @@ function importAnalysisPlugin(config) {
41604
41712
  }
41605
41713
  }
41606
41714
  if (!ssr) {
41607
- const url = rawUrl
41608
- .replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, '')
41609
- .trim();
41610
- if (!/^(?:'.*'|".*"|`.*`)$/.test(url) ||
41715
+ const url = rawUrl.replace(cleanUpRawUrlRE, '').trim();
41716
+ if (!urlIsStringRE.test(url) ||
41611
41717
  isExplicitImportRequired(url.slice(1, -1))) {
41612
41718
  needQueryInjectHelper = true;
41613
41719
  str().overwrite(start, end, `__vite__injectQuery(${url}, 'import')`, { contentOnly: true });
@@ -41803,6 +41909,7 @@ function transformCjsImport(importExp, url, rawUrl, importIndex) {
41803
41909
  }
41804
41910
  }
41805
41911
 
41912
+ const process_env_NODE_ENV_RE = /(\bglobal(This)?\.)?\bprocess\.env\.NODE_ENV\b/g;
41806
41913
  // ids in transform are normalized to unix style
41807
41914
  const normalizedClientEntry = normalizePath$3(CLIENT_ENTRY);
41808
41915
  const normalizedEnvEntry = normalizePath$3(ENV_ENTRY);
@@ -41811,57 +41918,80 @@ const normalizedEnvEntry = normalizePath$3(ENV_ENTRY);
41811
41918
  * @server-only
41812
41919
  */
41813
41920
  function clientInjectionsPlugin(config) {
41921
+ let injectConfigValues;
41814
41922
  return {
41815
41923
  name: 'vite:client-inject',
41816
- async transform(code, id, options) {
41817
- if (id === normalizedClientEntry || id === normalizedEnvEntry) {
41818
- const resolvedServerHostname = (await resolveHostname(config.server.host)).name;
41819
- const resolvedServerPort = config.server.port;
41820
- const devBase = config.base;
41821
- const serverHost = `${resolvedServerHostname}:${resolvedServerPort}${devBase}`;
41822
- let hmrConfig = config.server.hmr;
41823
- hmrConfig = isObject$2(hmrConfig) ? hmrConfig : undefined;
41824
- const host = hmrConfig?.host || null;
41825
- const protocol = hmrConfig?.protocol || null;
41826
- const timeout = hmrConfig?.timeout || 30000;
41827
- const overlay = hmrConfig?.overlay !== false;
41828
- const isHmrServerSpecified = !!hmrConfig?.server;
41829
- // hmr.clientPort -> hmr.port
41830
- // -> (24678 if middleware mode and HMR server is not specified) -> new URL(import.meta.url).port
41831
- let port = hmrConfig?.clientPort || hmrConfig?.port || null;
41832
- if (config.server.middlewareMode && !isHmrServerSpecified) {
41833
- port || (port = 24678);
41834
- }
41835
- let directTarget = hmrConfig?.host || resolvedServerHostname;
41836
- directTarget += `:${hmrConfig?.port || resolvedServerPort}`;
41837
- directTarget += devBase;
41838
- let hmrBase = devBase;
41839
- if (hmrConfig?.path) {
41840
- hmrBase = path$o.posix.join(hmrBase, hmrConfig.path);
41841
- }
41924
+ async buildStart() {
41925
+ const resolvedServerHostname = (await resolveHostname(config.server.host))
41926
+ .name;
41927
+ const resolvedServerPort = config.server.port;
41928
+ const devBase = config.base;
41929
+ const serverHost = `${resolvedServerHostname}:${resolvedServerPort}${devBase}`;
41930
+ let hmrConfig = config.server.hmr;
41931
+ hmrConfig = isObject$2(hmrConfig) ? hmrConfig : undefined;
41932
+ const host = hmrConfig?.host || null;
41933
+ const protocol = hmrConfig?.protocol || null;
41934
+ const timeout = hmrConfig?.timeout || 30000;
41935
+ const overlay = hmrConfig?.overlay !== false;
41936
+ const isHmrServerSpecified = !!hmrConfig?.server;
41937
+ // hmr.clientPort -> hmr.port
41938
+ // -> (24678 if middleware mode and HMR server is not specified) -> new URL(import.meta.url).port
41939
+ let port = hmrConfig?.clientPort || hmrConfig?.port || null;
41940
+ if (config.server.middlewareMode && !isHmrServerSpecified) {
41941
+ port || (port = 24678);
41942
+ }
41943
+ let directTarget = hmrConfig?.host || resolvedServerHostname;
41944
+ directTarget += `:${hmrConfig?.port || resolvedServerPort}`;
41945
+ directTarget += devBase;
41946
+ let hmrBase = devBase;
41947
+ if (hmrConfig?.path) {
41948
+ hmrBase = path$o.posix.join(hmrBase, hmrConfig.path);
41949
+ }
41950
+ const serializedDefines = serializeDefine(config.define || {});
41951
+ const modeReplacement = escapeReplacement(config.mode);
41952
+ const baseReplacement = escapeReplacement(devBase);
41953
+ const definesReplacement = () => serializedDefines;
41954
+ const serverHostReplacement = escapeReplacement(serverHost);
41955
+ const hmrProtocolReplacement = escapeReplacement(protocol);
41956
+ const hmrHostnameReplacement = escapeReplacement(host);
41957
+ const hmrPortReplacement = escapeReplacement(port);
41958
+ const hmrDirectTargetReplacement = escapeReplacement(directTarget);
41959
+ const hmrBaseReplacement = escapeReplacement(hmrBase);
41960
+ const hmrTimeoutReplacement = escapeReplacement(timeout);
41961
+ const hmrEnableOverlayReplacement = escapeReplacement(overlay);
41962
+ injectConfigValues = (code) => {
41842
41963
  return code
41843
- .replace(`__MODE__`, JSON.stringify(config.mode))
41844
- .replace(/__BASE__/g, JSON.stringify(devBase))
41845
- .replace(`__DEFINES__`, serializeDefine(config.define || {}))
41846
- .replace(`__SERVER_HOST__`, JSON.stringify(serverHost))
41847
- .replace(`__HMR_PROTOCOL__`, JSON.stringify(protocol))
41848
- .replace(`__HMR_HOSTNAME__`, JSON.stringify(host))
41849
- .replace(`__HMR_PORT__`, JSON.stringify(port))
41850
- .replace(`__HMR_DIRECT_TARGET__`, JSON.stringify(directTarget))
41851
- .replace(`__HMR_BASE__`, JSON.stringify(hmrBase))
41852
- .replace(`__HMR_TIMEOUT__`, JSON.stringify(timeout))
41853
- .replace(`__HMR_ENABLE_OVERLAY__`, JSON.stringify(overlay));
41964
+ .replace(`__MODE__`, modeReplacement)
41965
+ .replace(/__BASE__/g, baseReplacement)
41966
+ .replace(`__DEFINES__`, definesReplacement)
41967
+ .replace(`__SERVER_HOST__`, serverHostReplacement)
41968
+ .replace(`__HMR_PROTOCOL__`, hmrProtocolReplacement)
41969
+ .replace(`__HMR_HOSTNAME__`, hmrHostnameReplacement)
41970
+ .replace(`__HMR_PORT__`, hmrPortReplacement)
41971
+ .replace(`__HMR_DIRECT_TARGET__`, hmrDirectTargetReplacement)
41972
+ .replace(`__HMR_BASE__`, hmrBaseReplacement)
41973
+ .replace(`__HMR_TIMEOUT__`, hmrTimeoutReplacement)
41974
+ .replace(`__HMR_ENABLE_OVERLAY__`, hmrEnableOverlayReplacement);
41975
+ };
41976
+ },
41977
+ transform(code, id, options) {
41978
+ if (id === normalizedClientEntry || id === normalizedEnvEntry) {
41979
+ return injectConfigValues(code);
41854
41980
  }
41855
41981
  else if (!options?.ssr && code.includes('process.env.NODE_ENV')) {
41856
41982
  // replace process.env.NODE_ENV instead of defining a global
41857
41983
  // for it to avoid shimming a `process` object during dev,
41858
41984
  // avoiding inconsistencies between dev and build
41859
- return code.replace(/(\bglobal(This)?\.)?\bprocess\.env\.NODE_ENV\b/g, config.define?.['process.env.NODE_ENV'] ||
41985
+ return code.replace(process_env_NODE_ENV_RE, config.define?.['process.env.NODE_ENV'] ||
41860
41986
  JSON.stringify(process.env.NODE_ENV || config.mode));
41861
41987
  }
41862
41988
  },
41863
41989
  };
41864
41990
  }
41991
+ function escapeReplacement(value) {
41992
+ const jsonValue = JSON.stringify(value);
41993
+ return () => jsonValue;
41994
+ }
41865
41995
  function serializeDefine(define) {
41866
41996
  let res = `{`;
41867
41997
  for (const key in define) {
@@ -42130,11 +42260,7 @@ function definePlugin(config) {
42130
42260
  // Mustn't be preceded by a char that can be part of an identifier
42131
42261
  // or a '.' that isn't part of a spread operator
42132
42262
  '(?<![\\p{L}\\p{N}_$]|(?<!\\.\\.)\\.)(' +
42133
- replacementsKeys
42134
- .map((str) => {
42135
- return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
42136
- })
42137
- .join('|') +
42263
+ replacementsKeys.map(escapeRegex).join('|') +
42138
42264
  // Mustn't be followed by a char that can be part of an identifier
42139
42265
  // or an assignment (but allow equality operators)
42140
42266
  ')(?:(?<=\\.)|(?![\\p{L}\\p{N}_$]|\\s*?=[^=]))', 'gu')
@@ -42263,14 +42389,14 @@ function workerImportMetaUrlPlugin(config) {
42263
42389
  const urlEnd = urlStart + emptyUrl.length;
42264
42390
  const rawUrl = code.slice(urlStart, urlEnd);
42265
42391
  // potential dynamic template string
42266
- if (rawUrl[0] === '`' && /\$\{/.test(rawUrl)) {
42392
+ if (rawUrl[0] === '`' && rawUrl.includes('${')) {
42267
42393
  this.error(`\`new URL(url, import.meta.url)\` is not supported in dynamic template string.`, urlIndex);
42268
42394
  }
42269
42395
  s || (s = new MagicString(code));
42270
42396
  const workerType = getWorkerType(code, cleanString, index + allExp.length);
42271
42397
  const url = rawUrl.slice(1, -1);
42272
42398
  let file;
42273
- if (url.startsWith('.')) {
42399
+ if (url[0] === '.') {
42274
42400
  file = path$o.resolve(path$o.dirname(id), url);
42275
42401
  }
42276
42402
  else {
@@ -42280,7 +42406,7 @@ function workerImportMetaUrlPlugin(config) {
42280
42406
  preferRelative: true,
42281
42407
  }));
42282
42408
  file = await workerResolver(url, id);
42283
- file ?? (file = url.startsWith('/')
42409
+ file ?? (file = url[0] === '/'
42284
42410
  ? slash$1(path$o.join(config.publicDir, url))
42285
42411
  : slash$1(path$o.resolve(path$o.dirname(id), url)));
42286
42412
  }
@@ -42337,7 +42463,7 @@ function assetImportMetaUrlPlugin(config) {
42337
42463
  if (!s)
42338
42464
  s = new MagicString(code);
42339
42465
  // potential dynamic template string
42340
- if (rawUrl[0] === '`' && /\$\{/.test(rawUrl)) {
42466
+ if (rawUrl[0] === '`' && rawUrl.includes('${')) {
42341
42467
  const ast = this.parse(rawUrl);
42342
42468
  const templateLiteral = ast.body[0].expression;
42343
42469
  if (templateLiteral.expressions.length) {
@@ -42352,7 +42478,7 @@ function assetImportMetaUrlPlugin(config) {
42352
42478
  }
42353
42479
  const url = rawUrl.slice(1, -1);
42354
42480
  let file;
42355
- if (url.startsWith('.')) {
42481
+ if (url[0] === '.') {
42356
42482
  file = slash$1(path$o.resolve(path$o.dirname(id), url));
42357
42483
  }
42358
42484
  else {
@@ -42573,6 +42699,7 @@ function dynamicImportToGlob(node, sourceString) {
42573
42699
  }
42574
42700
 
42575
42701
  const dynamicImportHelperId = '\0vite/dynamic-import-helper';
42702
+ const relativePathRE = /^\.{1,2}\//;
42576
42703
  const dynamicImportHelper = (glob, path) => {
42577
42704
  const v = glob[path];
42578
42705
  if (v) {
@@ -42629,7 +42756,7 @@ async function transformDynamicImport(importSource, importer, resolve, root) {
42629
42756
  ? `, ${JSON.stringify({ ...globParams, import: '*' })}`
42630
42757
  : '';
42631
42758
  let newRawPattern = posix$1.relative(posix$1.dirname(importer), await toAbsoluteGlob(rawPattern, root, importer, resolve));
42632
- if (!/^\.{1,2}\//.test(newRawPattern)) {
42759
+ if (!relativePathRE.test(newRawPattern)) {
42633
42760
  newRawPattern = `./${newRawPattern}`;
42634
42761
  }
42635
42762
  const exp = `(import.meta.glob(${JSON.stringify(userPattern)}${params}))`;
@@ -42758,7 +42885,7 @@ async function resolvePlugins(config, prePlugins, normalPlugins, postPlugins) {
42758
42885
  }),
42759
42886
  htmlInlineProxyPlugin(config),
42760
42887
  cssPlugin(config),
42761
- config.esbuild !== false ? esbuildPlugin(config.esbuild) : null,
42888
+ config.esbuild !== false ? esbuildPlugin(config) : null,
42762
42889
  jsonPlugin({
42763
42890
  namedExports: true,
42764
42891
  ...config.json,
@@ -43298,7 +43425,7 @@ async function createPluginContainer(config, moduleGraph, watcher) {
43298
43425
  ctx.ssr = !!ssr;
43299
43426
  ctx._scan = scan;
43300
43427
  ctx._resolveSkips = skip;
43301
- const resolveStart = isDebug ? performance.now() : 0;
43428
+ const resolveStart = isDebug ? performance$1.now() : 0;
43302
43429
  let id = null;
43303
43430
  const partial = {};
43304
43431
  for (const plugin of getSortedPlugins('resolveId')) {
@@ -43307,7 +43434,7 @@ async function createPluginContainer(config, moduleGraph, watcher) {
43307
43434
  if (skip?.has(plugin))
43308
43435
  continue;
43309
43436
  ctx._activePlugin = plugin;
43310
- const pluginResolveStart = isDebug ? performance.now() : 0;
43437
+ const pluginResolveStart = isDebug ? performance$1.now() : 0;
43311
43438
  const handler = 'handler' in plugin.resolveId
43312
43439
  ? plugin.resolveId.handler
43313
43440
  : plugin.resolveId;
@@ -43378,7 +43505,7 @@ async function createPluginContainer(config, moduleGraph, watcher) {
43378
43505
  ctx._activePlugin = plugin;
43379
43506
  ctx._activeId = id;
43380
43507
  ctx._activeCode = code;
43381
- const start = isDebug ? performance.now() : 0;
43508
+ const start = isDebug ? performance$1.now() : 0;
43382
43509
  let result;
43383
43510
  const handler = 'handler' in plugin.transform
43384
43511
  ? plugin.transform.handler
@@ -43440,7 +43567,7 @@ const htmlTypesRE = /\.(html|vue|svelte|astro|imba)$/;
43440
43567
  const importsRE = /(?<!\/\/.*)(?<=^|;|\*\/)\s*import(?!\s+type)(?:[\w*{}\n\r\t, ]+from)?\s*("[^"]+"|'[^']+')\s*(?=$|;|\/\/|\/\*)/gm;
43441
43568
  function scanImports(config) {
43442
43569
  // Only used to scan non-ssr code
43443
- const start = performance.now();
43570
+ const start = performance$1.now();
43444
43571
  const deps = {};
43445
43572
  const missing = {};
43446
43573
  let entries;
@@ -43508,7 +43635,7 @@ function scanImports(config) {
43508
43635
  throw e;
43509
43636
  })
43510
43637
  .finally(() => {
43511
- debug$8(`Scan completed in ${(performance.now() - start).toFixed(2)}ms:`, deps);
43638
+ debug$8(`Scan completed in ${(performance$1.now() - start).toFixed(2)}ms:`, deps);
43512
43639
  });
43513
43640
  return {
43514
43641
  cancel: async () => {
@@ -44492,6 +44619,7 @@ const debug$7 = debuggerViteDeps;
44492
44619
  const isDebugEnabled = _debug('vite:deps').enabled;
44493
44620
  const jsExtensionRE = /\.js$/i;
44494
44621
  const jsMapExtensionRE = /\.js\.map$/i;
44622
+ const reExportRE = /export\s+\*\s+from/;
44495
44623
  /**
44496
44624
  * Scan and optimize dependencies within a project.
44497
44625
  * Used by Vite CLI when running `vite optimize`.
@@ -44692,7 +44820,7 @@ function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.command
44692
44820
  result: Promise.resolve(createProcessingResult()),
44693
44821
  };
44694
44822
  }
44695
- const start = performance.now();
44823
+ const start = performance$1.now();
44696
44824
  const preparedRun = prepareEsbuildOptimizerRun(resolvedConfig, depsInfo, ssr, processingCacheDir, optimizerContext);
44697
44825
  const result = preparedRun.then(({ context, idToExports }) => {
44698
44826
  function disposeContext() {
@@ -44744,7 +44872,7 @@ function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.command
44744
44872
  }
44745
44873
  const dataPath = path$o.join(processingCacheDir, '_metadata.json');
44746
44874
  writeFile(dataPath, stringifyDepsOptimizerMetadata(metadata, depsCacheDir));
44747
- debug$7(`deps bundled in ${(performance.now() - start).toFixed(2)}ms`);
44875
+ debug$7(`deps bundled in ${(performance$1.now() - start).toFixed(2)}ms`);
44748
44876
  return createProcessingResult();
44749
44877
  })
44750
44878
  .catch((e) => {
@@ -44927,10 +45055,20 @@ function createOptimizeDepsIncludeResolver(config, ssr) {
44927
45055
  // 'foo > bar > baz' => 'foo > bar' & 'baz'
44928
45056
  const nestedRoot = id.substring(0, lastArrowIndex).trim();
44929
45057
  const nestedPath = id.substring(lastArrowIndex + 1).trim();
44930
- const basedir = nestedResolveFrom(nestedRoot, config.root, config.resolve.preserveSymlinks, ssr);
45058
+ const basedir = nestedResolveBasedir(nestedRoot, config.root, config.resolve.preserveSymlinks);
44931
45059
  return await resolve(nestedPath, basedir, undefined, ssr);
44932
45060
  };
44933
45061
  }
45062
+ /**
45063
+ * Continously resolve the basedir of packages separated by '>'
45064
+ */
45065
+ function nestedResolveBasedir(id, basedir, preserveSymlinks = false) {
45066
+ const pkgs = id.split('>').map((pkg) => pkg.trim());
45067
+ for (const pkg of pkgs) {
45068
+ basedir = resolvePackageData(pkg, basedir, preserveSymlinks)?.dir || basedir;
45069
+ }
45070
+ return basedir;
45071
+ }
44934
45072
  function newDepOptimizationProcessing() {
44935
45073
  let resolve;
44936
45074
  const promise = new Promise((_resolve) => {
@@ -44981,7 +45119,7 @@ function createIsOptimizedDepUrl(config) {
44981
45119
  const depsCacheDirPrefix = depsCacheDirRelative.startsWith('../')
44982
45120
  ? // if the cache directory is outside root, the url prefix would be something
44983
45121
  // like '/@fs/absolute/path/to/node_modules/.vite'
44984
- `/@fs/${normalizePath$3(depsCacheDir).replace(/^\//, '')}`
45122
+ `/@fs/${removeLeadingSlash(normalizePath$3(depsCacheDir))}`
44985
45123
  : // if the cache directory is inside root, the url prefix would be something
44986
45124
  // like '/node_modules/.vite'
44987
45125
  `/${depsCacheDirRelative}`;
@@ -45123,7 +45261,7 @@ async function extractExportsData(filePath, config, ssr) {
45123
45261
  facade,
45124
45262
  hasReExports: imports.some(({ ss, se }) => {
45125
45263
  const exp = entryContent.slice(ss, se);
45126
- return /export\s+\*\s+from/.test(exp);
45264
+ return reExportRE.test(exp);
45127
45265
  }),
45128
45266
  jsxLoader: usedJsxLoader,
45129
45267
  };
@@ -45299,7 +45437,7 @@ const optimizedDepChunkRE = /\/chunk-[A-Z\d]{8}\.js/;
45299
45437
  const optimizedDepDynamicRE = /-[A-Z\d]{8}\.js/;
45300
45438
  function toRelativePath(filename, importer) {
45301
45439
  const relPath = path$o.relative(path$o.dirname(importer), filename);
45302
- return relPath.startsWith('.') ? relPath : `./${relPath}`;
45440
+ return relPath[0] === '.' ? relPath : `./${relPath}`;
45303
45441
  }
45304
45442
  /**
45305
45443
  * Helper for preloading CSS and direct imports of async chunks in parallel to
@@ -46298,7 +46436,7 @@ function getPkgJson(root) {
46298
46436
  return JSON.parse(lookupFile(root, ['package.json']) || `{}`);
46299
46437
  }
46300
46438
  function getPkgName(name) {
46301
- return name?.startsWith('@') ? name.split('/')[1] : name;
46439
+ return name?.[0] === '@' ? name.split('/')[1] : name;
46302
46440
  }
46303
46441
  function resolveOutputJsExtension(format, type = 'commonjs') {
46304
46442
  if (type === 'module') {
@@ -53414,10 +53552,12 @@ async function ssrTransformScript(code, inMap, url, originalCode) {
53414
53552
  const dynamicDeps = new Set();
53415
53553
  const idToImportMap = new Map();
53416
53554
  const declaredConst = new Set();
53417
- function defineImport(node, source) {
53555
+ function defineImport(source) {
53418
53556
  deps.add(source);
53419
53557
  const importId = `__vite_ssr_import_${uid++}__`;
53420
- s.appendRight(node.start, `const ${importId} = await ${ssrImportKey}(${JSON.stringify(source)});\n`);
53558
+ // There will be an error if the module is called before it is imported,
53559
+ // so the module import statement is hoisted to the top
53560
+ s.appendLeft(0, `const ${importId} = await ${ssrImportKey}(${JSON.stringify(source)});\n`);
53421
53561
  return importId;
53422
53562
  }
53423
53563
  function defineExport(position, name, local = name) {
@@ -53430,8 +53570,8 @@ async function ssrTransformScript(code, inMap, url, originalCode) {
53430
53570
  // import { baz } from 'foo' --> baz -> __import_foo__.baz
53431
53571
  // import * as ok from 'foo' --> ok -> __import_foo__
53432
53572
  if (node.type === 'ImportDeclaration') {
53573
+ const importId = defineImport(node.source.value);
53433
53574
  s.remove(node.start, node.end);
53434
- const importId = defineImport(node, node.source.value);
53435
53575
  for (const spec of node.specifiers) {
53436
53576
  if (spec.type === 'ImportSpecifier') {
53437
53577
  idToImportMap.set(spec.local.name, `${importId}.${spec.imported.name}`);
@@ -53471,9 +53611,10 @@ async function ssrTransformScript(code, inMap, url, originalCode) {
53471
53611
  s.remove(node.start, node.end);
53472
53612
  if (node.source) {
53473
53613
  // export { foo, bar } from './foo'
53474
- const importId = defineImport(node, node.source.value);
53614
+ const importId = defineImport(node.source.value);
53615
+ // hoist re-exports near the defined import so they are immediately exported
53475
53616
  for (const spec of node.specifiers) {
53476
- defineExport(node.end, spec.exported.name, `${importId}.${spec.local.name}`);
53617
+ defineExport(0, spec.exported.name, `${importId}.${spec.local.name}`);
53477
53618
  }
53478
53619
  }
53479
53620
  else {
@@ -53508,12 +53649,13 @@ async function ssrTransformScript(code, inMap, url, originalCode) {
53508
53649
  // export * from './foo'
53509
53650
  if (node.type === 'ExportAllDeclaration') {
53510
53651
  s.remove(node.start, node.end);
53511
- const importId = defineImport(node, node.source.value);
53652
+ const importId = defineImport(node.source.value);
53653
+ // hoist re-exports near the defined import so they are immediately exported
53512
53654
  if (node.exported) {
53513
- defineExport(node.end, node.exported.name, `${importId}`);
53655
+ defineExport(0, node.exported.name, `${importId}`);
53514
53656
  }
53515
53657
  else {
53516
- s.appendLeft(node.end, `${ssrExportAllKey}(${importId});`);
53658
+ s.appendLeft(0, `${ssrExportAllKey}(${importId});\n`);
53517
53659
  }
53518
53660
  }
53519
53661
  }
@@ -57583,7 +57725,11 @@ function initAsClient(websocket, address, protocols, options) {
57583
57725
  });
57584
57726
  });
57585
57727
 
57586
- req.end();
57728
+ if (opts.finishRequest) {
57729
+ opts.finishRequest(req, websocket);
57730
+ } else {
57731
+ req.end();
57732
+ }
57587
57733
  }
57588
57734
 
57589
57735
  /**
@@ -60867,7 +61013,7 @@ function proxyMiddleware(httpServer, options, config) {
60867
61013
  };
60868
61014
  }
60869
61015
  function doesProxyContextMatchUrl(context, url) {
60870
- return ((context.startsWith('^') && new RegExp(context).test(url)) ||
61016
+ return ((context[0] === '^' && new RegExp(context).test(url)) ||
60871
61017
  url.startsWith(context));
60872
61018
  }
60873
61019
 
@@ -61236,7 +61382,7 @@ const processNodeUrl = (attr, sourceCodeLocation, s, config, htmlPath, originalU
61236
61382
  const fullUrl = path$o.posix.join(devBase, url);
61237
61383
  overwriteAttrValue(s, sourceCodeLocation, fullUrl);
61238
61384
  }
61239
- else if (url.startsWith('.') &&
61385
+ else if (url[0] === '.' &&
61240
61386
  originalUrl &&
61241
61387
  originalUrl !== '/' &&
61242
61388
  htmlPath === '/index.html') {
@@ -61281,7 +61427,7 @@ const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl
61281
61427
  const contentNode = node.childNodes[0];
61282
61428
  const code = contentNode.value;
61283
61429
  let map;
61284
- if (!proxyModulePath.startsWith('\0')) {
61430
+ if (proxyModulePath[0] !== '\0') {
61285
61431
  map = new MagicString(html)
61286
61432
  .snip(contentNode.sourceCodeLocation.startOffset, contentNode.sourceCodeLocation.endOffset)
61287
61433
  .generateMap({ hires: true });
@@ -61386,7 +61532,7 @@ const logTime = createDebugger('vite:time');
61386
61532
  function timeMiddleware(root) {
61387
61533
  // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
61388
61534
  return function viteTimeMiddleware(req, res, next) {
61389
- const start = performance.now();
61535
+ const start = performance$1.now();
61390
61536
  const end = res.end;
61391
61537
  res.end = (...args) => {
61392
61538
  logTime(`${timeFrom(start)} ${prettifyUrl(req.url, root)}`);
@@ -62660,22 +62806,20 @@ crossSpawnExports._enoent = enoent;
62660
62806
  */
62661
62807
  /**
62662
62808
  * Reads the BROWSER environment variable and decides what to do with it.
62663
- * Returns true if it opened a browser or ran a node.js script, otherwise false.
62664
62809
  */
62665
62810
  function openBrowser(url, opt, logger) {
62666
62811
  // The browser executable to open.
62667
62812
  // See https://github.com/sindresorhus/open#app for documentation.
62668
62813
  const browser = typeof opt === 'string' ? opt : process.env.BROWSER || '';
62669
62814
  if (browser.toLowerCase().endsWith('.js')) {
62670
- return executeNodeScript(browser, url, logger);
62815
+ executeNodeScript(browser, url, logger);
62671
62816
  }
62672
62817
  else if (browser.toLowerCase() !== 'none') {
62673
62818
  const browserArgs = process.env.BROWSER_ARGS
62674
62819
  ? process.env.BROWSER_ARGS.split(' ')
62675
62820
  : [];
62676
- return startBrowserProcess(browser, browserArgs, url);
62821
+ startBrowserProcess(browser, browserArgs, url);
62677
62822
  }
62678
- return false;
62679
62823
  }
62680
62824
  function executeNodeScript(scriptPath, url, logger) {
62681
62825
  const extraArgs = process.argv.slice(2);
@@ -62687,7 +62831,6 @@ function executeNodeScript(scriptPath, url, logger) {
62687
62831
  logger.error(picocolorsExports.red(`\nThe script specified as BROWSER environment variable failed.\n\n${picocolorsExports.cyan(scriptPath)} exited with code ${code}.`), { error: null });
62688
62832
  }
62689
62833
  });
62690
- return true;
62691
62834
  }
62692
62835
  const supportedChromiumBrowsers = [
62693
62836
  'Google Chrome Canary',
@@ -62699,7 +62842,7 @@ const supportedChromiumBrowsers = [
62699
62842
  'Vivaldi',
62700
62843
  'Chromium',
62701
62844
  ];
62702
- function startBrowserProcess(browser, browserArgs, url) {
62845
+ async function startBrowserProcess(browser, browserArgs, url) {
62703
62846
  // If we're on OS X, the user hasn't specifically
62704
62847
  // requested a different browser, we can try opening
62705
62848
  // a Chromium browser with AppleScript. This lets us reuse an
@@ -62710,15 +62853,14 @@ function startBrowserProcess(browser, browserArgs, url) {
62710
62853
  supportedChromiumBrowsers.includes(preferredOSXBrowser));
62711
62854
  if (shouldTryOpenChromeWithAppleScript) {
62712
62855
  try {
62713
- const ps = execSync('ps cax').toString();
62856
+ const ps = await execAsync('ps cax');
62714
62857
  const openedBrowser = preferredOSXBrowser && ps.includes(preferredOSXBrowser)
62715
62858
  ? preferredOSXBrowser
62716
62859
  : supportedChromiumBrowsers.find((b) => ps.includes(b));
62717
62860
  if (openedBrowser) {
62718
62861
  // Try our best to reuse existing tab with AppleScript
62719
- execSync(`osascript openChrome.applescript "${encodeURI(url)}" "${openedBrowser}"`, {
62862
+ await execAsync(`osascript openChrome.applescript "${encodeURI(url)}" "${openedBrowser}"`, {
62720
62863
  cwd: join$2(VITE_PACKAGE_DIR, 'bin'),
62721
- stdio: 'ignore',
62722
62864
  });
62723
62865
  return true;
62724
62866
  }
@@ -62747,6 +62889,18 @@ function startBrowserProcess(browser, browserArgs, url) {
62747
62889
  return false;
62748
62890
  }
62749
62891
  }
62892
+ function execAsync(command, options) {
62893
+ return new Promise((resolve, reject) => {
62894
+ exec(command, options, (error, stdout) => {
62895
+ if (error) {
62896
+ reject(error);
62897
+ }
62898
+ else {
62899
+ resolve(stdout.toString());
62900
+ }
62901
+ });
62902
+ });
62903
+ }
62750
62904
 
62751
62905
  async function createServer(inlineConfig = {}) {
62752
62906
  const config = await resolveConfig(inlineConfig, 'serve');
@@ -63124,7 +63278,7 @@ function resolveServerOptions(root, raw, logger) {
63124
63278
  return server;
63125
63279
  }
63126
63280
  async function restartServer(server) {
63127
- global.__vite_start_time = performance.now();
63281
+ global.__vite_start_time = performance$1.now();
63128
63282
  const { port: prevPort, host: prevHost } = server.config.server;
63129
63283
  const shortcutsOptions = server._shortcutsOptions;
63130
63284
  const oldUrls = server.resolvedUrls;
@@ -63772,7 +63926,7 @@ assetFileNames isn't equal for every build.rollupOptions.output. A single patter
63772
63926
  * electron or expects to deploy
63773
63927
  */
63774
63928
  function resolveBaseUrl(base = '/', isBuild, logger) {
63775
- if (base.startsWith('.')) {
63929
+ if (base[0] === '.') {
63776
63930
  logger.warn(picocolorsExports.yellow(picocolorsExports.bold(`(!) invalid "base" option: ${base}. The value can only be an absolute ` +
63777
63931
  `URL, ./, or an empty string.`)));
63778
63932
  return '/';
@@ -63780,14 +63934,14 @@ function resolveBaseUrl(base = '/', isBuild, logger) {
63780
63934
  // external URL flag
63781
63935
  const isExternal = isExternalUrl(base);
63782
63936
  // no leading slash warn
63783
- if (!isExternal && !base.startsWith('/')) {
63937
+ if (!isExternal && base[0] !== '/') {
63784
63938
  logger.warn(picocolorsExports.yellow(picocolorsExports.bold(`(!) "base" option should start with a slash.`)));
63785
63939
  }
63786
63940
  // parse base when command is serve or base is not External URL
63787
63941
  if (!isBuild || !isExternal) {
63788
63942
  base = new URL(base, 'http://vitejs.dev').pathname;
63789
63943
  // ensure leading slash
63790
- if (!base.startsWith('/')) {
63944
+ if (base[0] !== '/') {
63791
63945
  base = '/' + base;
63792
63946
  }
63793
63947
  }
@@ -63810,8 +63964,8 @@ function sortUserPlugins(plugins) {
63810
63964
  return [prePlugins, normalPlugins, postPlugins];
63811
63965
  }
63812
63966
  async function loadConfigFromFile(configEnv, configFile, configRoot = process.cwd(), logLevel) {
63813
- const start = performance.now();
63814
- const getTime = () => `${(performance.now() - start).toFixed(2)}ms`;
63967
+ const start = performance$1.now();
63968
+ const getTime = () => `${(performance$1.now() - start).toFixed(2)}ms`;
63815
63969
  let resolvedPath;
63816
63970
  if (configFile) {
63817
63971
  // explicit config path is always resolved from cwd
@@ -63959,7 +64113,9 @@ async function loadConfigFromBundledFile(fileName, bundledCode, isESM) {
63959
64113
  // with --experimental-loader themselves, we have to do a hack here:
63960
64114
  // write it to disk, load it with native Node ESM, then delete the file.
63961
64115
  if (isESM) {
63962
- const fileBase = `${fileName}.timestamp-${Date.now()}`;
64116
+ const fileBase = `${fileName}.timestamp-${Date.now()}-${Math.random()
64117
+ .toString(16)
64118
+ .slice(2)})}`;
63963
64119
  const fileNameTmp = `${fileBase}.mjs`;
63964
64120
  const fileUrl = `${pathToFileURL(fileBase)}.mjs`;
63965
64121
  fs$l.writeFileSync(fileNameTmp, bundledCode);