vite 5.0.6 → 5.0.8

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.
@@ -1,4 +1,4 @@
1
- import { z as commonjsGlobal, y as getDefaultExportFromCjs } from './dep-YJaePtkC.js';
1
+ import { z as commonjsGlobal, y as getDefaultExportFromCjs } from './dep-uAHLeuC6.js';
2
2
  import require$$0__default from 'fs';
3
3
  import require$$0 from 'postcss';
4
4
  import require$$0$1 from 'path';
@@ -1,4 +1,4 @@
1
- import { y as getDefaultExportFromCjs } from './dep-YJaePtkC.js';
1
+ import { y as getDefaultExportFromCjs } from './dep-uAHLeuC6.js';
2
2
  import require$$0 from 'path';
3
3
  import require$$0__default from 'fs';
4
4
  import { l as lib } from './dep-8a-6Quh6.js';
@@ -7709,7 +7709,7 @@ function getPackageEntryPoint(dirPath) {
7709
7709
  return entryPoint;
7710
7710
  }
7711
7711
 
7712
- function isDirectory(path) {
7712
+ function isDirectory$1(path) {
7713
7713
  try {
7714
7714
  if (statSync$1(path).isDirectory()) return true;
7715
7715
  } catch (ignored) {
@@ -7730,7 +7730,7 @@ function getDynamicRequireModules(patterns, dynamicRequireRoot) {
7730
7730
  for (const path of glob$1.sync(isNegated ? pattern.substr(1) : pattern)) {
7731
7731
  const resolvedPath = resolve$3(path);
7732
7732
  const requirePath = normalizePathSlashes(resolvedPath);
7733
- if (isDirectory(resolvedPath)) {
7733
+ if (isDirectory$1(resolvedPath)) {
7734
7734
  dirNames.add(resolvedPath);
7735
7735
  const modulePath = resolve$3(join$1(resolvedPath, getPackageEntryPoint(path)));
7736
7736
  modifyMap(requirePath, modulePath);
@@ -12419,6 +12419,7 @@ function copyDir(srcDir, destDir) {
12419
12419
  }
12420
12420
  }
12421
12421
  }
12422
+ const ERR_SYMLINK_IN_RECURSIVE_READDIR = 'ERR_SYMLINK_IN_RECURSIVE_READDIR';
12422
12423
  async function recursiveReaddir(dir) {
12423
12424
  if (!fs$l.existsSync(dir)) {
12424
12425
  return [];
@@ -12434,6 +12435,11 @@ async function recursiveReaddir(dir) {
12434
12435
  }
12435
12436
  throw e;
12436
12437
  }
12438
+ if (dirents.some((dirent) => dirent.isSymbolicLink())) {
12439
+ const err = new Error('Symbolic links are not supported in recursiveReaddir');
12440
+ err.code = ERR_SYMLINK_IN_RECURSIVE_READDIR;
12441
+ throw err;
12442
+ }
12437
12443
  const files = await Promise.all(dirents.map((dirent) => {
12438
12444
  const res = path$o.resolve(dir, dirent.name);
12439
12445
  return dirent.isDirectory() ? recursiveReaddir(res) : normalizePath$3(res);
@@ -16424,7 +16430,16 @@ function lookup(extn) {
16424
16430
 
16425
16431
  const publicFilesMap = new WeakMap();
16426
16432
  async function initPublicFiles(config) {
16427
- const fileNames = await recursiveReaddir(config.publicDir);
16433
+ let fileNames;
16434
+ try {
16435
+ fileNames = await recursiveReaddir(config.publicDir);
16436
+ }
16437
+ catch (e) {
16438
+ if (e.code === ERR_SYMLINK_IN_RECURSIVE_READDIR) {
16439
+ return;
16440
+ }
16441
+ throw e;
16442
+ }
16428
16443
  const publicFiles = new Set(fileNames.map((fileName) => fileName.slice(config.publicDir.length)));
16429
16444
  publicFilesMap.set(config, publicFiles);
16430
16445
  return publicFiles;
@@ -16662,7 +16677,7 @@ function isGitLfsPlaceholder(content) {
16662
16677
  * Register an asset to be emitted as part of the bundle (if necessary)
16663
16678
  * and returns the resolved public URL
16664
16679
  */
16665
- async function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false) {
16680
+ async function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false, shouldInline) {
16666
16681
  if (!skipPublicCheck && checkPublicFile(id, config)) {
16667
16682
  return publicFileToBuiltUrl(id, config);
16668
16683
  }
@@ -16673,13 +16688,17 @@ async function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false
16673
16688
  }
16674
16689
  const file = cleanUrl(id);
16675
16690
  const content = await fsp.readFile(file);
16691
+ if (shouldInline == null) {
16692
+ shouldInline =
16693
+ !!config.build.lib ||
16694
+ // Don't inline SVG with fragments, as they are meant to be reused
16695
+ (!(file.endsWith('.svg') && id.includes('#')) &&
16696
+ !file.endsWith('.html') &&
16697
+ content.length < Number(config.build.assetsInlineLimit) &&
16698
+ !isGitLfsPlaceholder(content));
16699
+ }
16676
16700
  let url;
16677
- if (config.build.lib ||
16678
- // Don't inline SVG with fragments, as they are meant to be reused
16679
- (!(file.endsWith('.svg') && id.includes('#')) &&
16680
- !file.endsWith('.html') &&
16681
- content.length < Number(config.build.assetsInlineLimit) &&
16682
- !isGitLfsPlaceholder(content))) {
16701
+ if (shouldInline) {
16683
16702
  if (config.build.lib && isGitLfsPlaceholder(content)) {
16684
16703
  config.logger.warn(colors$1.yellow(`Inlined file ${id} was not downloaded via Git LFS`));
16685
16704
  }
@@ -16709,7 +16728,7 @@ async function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false
16709
16728
  cache.set(id, url);
16710
16729
  return url;
16711
16730
  }
16712
- async function urlToBuiltUrl(url, importer, config, pluginContext) {
16731
+ async function urlToBuiltUrl(url, importer, config, pluginContext, shouldInline) {
16713
16732
  if (checkPublicFile(url, config)) {
16714
16733
  return publicFileToBuiltUrl(url, config);
16715
16734
  }
@@ -16718,7 +16737,7 @@ async function urlToBuiltUrl(url, importer, config, pluginContext) {
16718
16737
  : path$o.join(path$o.dirname(importer), url);
16719
16738
  return fileToBuiltUrl(file, config, pluginContext,
16720
16739
  // skip public check since we just did it above
16721
- true);
16740
+ true, shouldInline);
16722
16741
  }
16723
16742
  // Inspired by https://github.com/iconify/iconify/blob/main/packages/utils/src/svg/url.ts
16724
16743
  function svgToDataURL(content) {
@@ -28461,6 +28480,324 @@ function hasESMSyntax(code) {
28461
28480
  return ESM_RE.test(code);
28462
28481
  }
28463
28482
 
28483
+ // An implementation of fsUtils without caching
28484
+ const commonFsUtils = {
28485
+ existsSync: fs$l.existsSync,
28486
+ isDirectory,
28487
+ tryResolveRealFile,
28488
+ tryResolveRealFileWithExtensions,
28489
+ tryResolveRealFileOrType,
28490
+ };
28491
+ const cachedFsUtilsMap = new WeakMap();
28492
+ function getFsUtils(config) {
28493
+ let fsUtils = cachedFsUtilsMap.get(config);
28494
+ if (!fsUtils) {
28495
+ if (config.command !== 'serve' || !config.server.fs.cachedChecks) {
28496
+ // cached fsUtils is only used in the dev server for now, and only when the watcher isn't configured
28497
+ // we can support custom ignored patterns later
28498
+ fsUtils = commonFsUtils;
28499
+ } /* TODO: Enabling for testing, we need to review if this guard is needed
28500
+ else if (config.server.watch === null || config.server.watch?.ignored) {
28501
+ config.logger.warn(
28502
+ colors.yellow(
28503
+ `${colors.bold(
28504
+ `(!)`,
28505
+ )} server.fs.cachedChecks isn't supported if server.watch is null or a custom server.watch.ignored is configured\n`,
28506
+ ),
28507
+ )
28508
+ fsUtils = commonFsUtils
28509
+ } */
28510
+ else if (!config.resolve.preserveSymlinks &&
28511
+ config.root !== getRealPath(config.root)) {
28512
+ config.logger.warn(colors$1.yellow(`${colors$1.bold(`(!)`)} server.fs.cachedChecks isn't supported when resolve.preserveSymlinks is false and root is symlinked\n`));
28513
+ fsUtils = commonFsUtils;
28514
+ }
28515
+ else {
28516
+ fsUtils = createCachedFsUtils(config);
28517
+ }
28518
+ cachedFsUtilsMap.set(config, fsUtils);
28519
+ }
28520
+ return fsUtils;
28521
+ }
28522
+ function readDirCacheSync(file) {
28523
+ let dirents;
28524
+ try {
28525
+ dirents = fs$l.readdirSync(file, { withFileTypes: true });
28526
+ }
28527
+ catch {
28528
+ return;
28529
+ }
28530
+ return direntsToDirentMap(dirents);
28531
+ }
28532
+ function direntsToDirentMap(fsDirents) {
28533
+ const dirents = new Map();
28534
+ for (const dirent of fsDirents) {
28535
+ // We ignore non directory, file, and symlink entries
28536
+ const type = dirent.isDirectory()
28537
+ ? 'directory'
28538
+ : dirent.isSymbolicLink()
28539
+ ? 'symlink'
28540
+ : dirent.isFile()
28541
+ ? 'file'
28542
+ : undefined;
28543
+ if (type) {
28544
+ dirents.set(dirent.name, { type });
28545
+ }
28546
+ }
28547
+ return dirents;
28548
+ }
28549
+ function ensureFileMaybeSymlinkIsResolved(direntCache, filePath) {
28550
+ if (direntCache.type !== 'file_maybe_symlink')
28551
+ return;
28552
+ const isSymlink = fs$l
28553
+ .lstatSync(filePath, { throwIfNoEntry: false })
28554
+ ?.isSymbolicLink();
28555
+ direntCache.type =
28556
+ isSymlink === undefined ? 'error' : isSymlink ? 'symlink' : 'file';
28557
+ }
28558
+ function pathUntilPart(root, parts, i) {
28559
+ let p = root;
28560
+ for (let k = 0; k < i; k++)
28561
+ p += '/' + parts[k];
28562
+ return p;
28563
+ }
28564
+ function createCachedFsUtils(config) {
28565
+ const root = config.root; // root is resolved and normalized, so it doesn't have a trailing slash
28566
+ const rootDirPath = `${root}/`;
28567
+ const rootCache = { type: 'directory' }; // dirents will be computed lazily
28568
+ const getDirentCacheSync = (parts) => {
28569
+ let direntCache = rootCache;
28570
+ for (let i = 0; i < parts.length; i++) {
28571
+ if (direntCache.type === 'directory') {
28572
+ let dirPath;
28573
+ if (!direntCache.dirents) {
28574
+ dirPath = pathUntilPart(root, parts, i);
28575
+ const dirents = readDirCacheSync(dirPath);
28576
+ if (!dirents) {
28577
+ direntCache.type = 'error';
28578
+ return;
28579
+ }
28580
+ direntCache.dirents = dirents;
28581
+ }
28582
+ const nextDirentCache = direntCache.dirents.get(parts[i]);
28583
+ if (!nextDirentCache) {
28584
+ return;
28585
+ }
28586
+ if (nextDirentCache.type === 'directory_maybe_symlink') {
28587
+ dirPath ??= pathUntilPart(root, parts, i);
28588
+ const isSymlink = fs$l
28589
+ .lstatSync(dirPath, { throwIfNoEntry: false })
28590
+ ?.isSymbolicLink();
28591
+ direntCache.type = isSymlink ? 'symlink' : 'directory';
28592
+ }
28593
+ direntCache = nextDirentCache;
28594
+ }
28595
+ else if (direntCache.type === 'symlink') {
28596
+ // early return if we encounter a symlink
28597
+ return direntCache;
28598
+ }
28599
+ else if (direntCache.type === 'error') {
28600
+ return direntCache;
28601
+ }
28602
+ else {
28603
+ if (i !== parts.length - 1) {
28604
+ return;
28605
+ }
28606
+ if (direntCache.type === 'file_maybe_symlink') {
28607
+ ensureFileMaybeSymlinkIsResolved(direntCache, pathUntilPart(root, parts, i));
28608
+ return direntCache;
28609
+ }
28610
+ else if (direntCache.type === 'file') {
28611
+ return direntCache;
28612
+ }
28613
+ else {
28614
+ return;
28615
+ }
28616
+ }
28617
+ }
28618
+ return direntCache;
28619
+ };
28620
+ function getDirentCacheFromPath(normalizedFile) {
28621
+ if (normalizedFile === root) {
28622
+ return rootCache;
28623
+ }
28624
+ if (!normalizedFile.startsWith(rootDirPath)) {
28625
+ return undefined;
28626
+ }
28627
+ const pathFromRoot = normalizedFile.slice(rootDirPath.length);
28628
+ const parts = pathFromRoot.split('/');
28629
+ const direntCache = getDirentCacheSync(parts);
28630
+ if (!direntCache || direntCache.type === 'error') {
28631
+ return false;
28632
+ }
28633
+ return direntCache;
28634
+ }
28635
+ function onPathAdd(file, type) {
28636
+ const direntCache = getDirentCacheFromPath(path$o.dirname(file));
28637
+ if (direntCache &&
28638
+ direntCache.type === 'directory' &&
28639
+ direntCache.dirents) {
28640
+ direntCache.dirents.set(path$o.basename(file), { type });
28641
+ }
28642
+ }
28643
+ function onPathUnlink(file) {
28644
+ const direntCache = getDirentCacheFromPath(path$o.dirname(file));
28645
+ if (direntCache &&
28646
+ direntCache.type === 'directory' &&
28647
+ direntCache.dirents) {
28648
+ direntCache.dirents.delete(path$o.basename(file));
28649
+ }
28650
+ }
28651
+ return {
28652
+ existsSync(file) {
28653
+ if (isInNodeModules$1(file)) {
28654
+ return fs$l.existsSync(file);
28655
+ }
28656
+ const normalizedFile = normalizePath$3(file);
28657
+ const direntCache = getDirentCacheFromPath(normalizedFile);
28658
+ if (direntCache === undefined ||
28659
+ (direntCache && direntCache.type === 'symlink')) {
28660
+ // fallback to built-in fs for out-of-root and symlinked files
28661
+ return fs$l.existsSync(file);
28662
+ }
28663
+ return !!direntCache;
28664
+ },
28665
+ tryResolveRealFile(file, preserveSymlinks) {
28666
+ if (isInNodeModules$1(file)) {
28667
+ return tryResolveRealFile(file, preserveSymlinks);
28668
+ }
28669
+ const normalizedFile = normalizePath$3(file);
28670
+ const direntCache = getDirentCacheFromPath(normalizedFile);
28671
+ if (direntCache === undefined ||
28672
+ (direntCache && direntCache.type === 'symlink')) {
28673
+ // fallback to built-in fs for out-of-root and symlinked files
28674
+ return tryResolveRealFile(file, preserveSymlinks);
28675
+ }
28676
+ if (!direntCache || direntCache.type === 'directory') {
28677
+ return;
28678
+ }
28679
+ // We can avoid getRealPath even if preserveSymlinks is false because we know it's
28680
+ // a file without symlinks in its path
28681
+ return normalizedFile;
28682
+ },
28683
+ tryResolveRealFileWithExtensions(file, extensions, preserveSymlinks) {
28684
+ if (isInNodeModules$1(file)) {
28685
+ return tryResolveRealFileWithExtensions(file, extensions, preserveSymlinks);
28686
+ }
28687
+ const normalizedFile = normalizePath$3(file);
28688
+ const dirPath = path$o.posix.dirname(normalizedFile);
28689
+ const direntCache = getDirentCacheFromPath(dirPath);
28690
+ if (direntCache === undefined ||
28691
+ (direntCache && direntCache.type === 'symlink')) {
28692
+ // fallback to built-in fs for out-of-root and symlinked files
28693
+ return tryResolveRealFileWithExtensions(file, extensions, preserveSymlinks);
28694
+ }
28695
+ if (!direntCache || direntCache.type !== 'directory') {
28696
+ return;
28697
+ }
28698
+ if (!direntCache.dirents) {
28699
+ const dirents = readDirCacheSync(dirPath);
28700
+ if (!dirents) {
28701
+ direntCache.type = 'error';
28702
+ return;
28703
+ }
28704
+ direntCache.dirents = dirents;
28705
+ }
28706
+ const base = path$o.posix.basename(normalizedFile);
28707
+ for (const ext of extensions) {
28708
+ const fileName = base + ext;
28709
+ const fileDirentCache = direntCache.dirents.get(fileName);
28710
+ if (fileDirentCache) {
28711
+ const filePath = dirPath + '/' + fileName;
28712
+ ensureFileMaybeSymlinkIsResolved(fileDirentCache, filePath);
28713
+ if (fileDirentCache.type === 'symlink') {
28714
+ // fallback to built-in fs for symlinked files
28715
+ return tryResolveRealFile(filePath, preserveSymlinks);
28716
+ }
28717
+ if (fileDirentCache.type === 'file') {
28718
+ return filePath;
28719
+ }
28720
+ }
28721
+ }
28722
+ },
28723
+ tryResolveRealFileOrType(file, preserveSymlinks) {
28724
+ if (isInNodeModules$1(file)) {
28725
+ return tryResolveRealFileOrType(file, preserveSymlinks);
28726
+ }
28727
+ const normalizedFile = normalizePath$3(file);
28728
+ const direntCache = getDirentCacheFromPath(normalizedFile);
28729
+ if (direntCache === undefined ||
28730
+ (direntCache && direntCache.type === 'symlink')) {
28731
+ // fallback to built-in fs for out-of-root and symlinked files
28732
+ return tryResolveRealFileOrType(file, preserveSymlinks);
28733
+ }
28734
+ if (!direntCache) {
28735
+ return;
28736
+ }
28737
+ if (direntCache.type === 'directory') {
28738
+ return { type: 'directory' };
28739
+ }
28740
+ // We can avoid getRealPath even if preserveSymlinks is false because we know it's
28741
+ // a file without symlinks in its path
28742
+ return { path: normalizedFile, type: 'file' };
28743
+ },
28744
+ isDirectory(dirPath) {
28745
+ if (isInNodeModules$1(dirPath)) {
28746
+ return isDirectory(dirPath);
28747
+ }
28748
+ const direntCache = getDirentCacheFromPath(normalizePath$3(dirPath));
28749
+ if (direntCache === undefined ||
28750
+ (direntCache && direntCache.type === 'symlink')) {
28751
+ // fallback to built-in fs for out-of-root and symlinked files
28752
+ return isDirectory(dirPath);
28753
+ }
28754
+ return direntCache && direntCache.type === 'directory';
28755
+ },
28756
+ initWatcher(watcher) {
28757
+ watcher.on('add', (file) => {
28758
+ onPathAdd(file, 'file_maybe_symlink');
28759
+ });
28760
+ watcher.on('addDir', (dir) => {
28761
+ onPathAdd(dir, 'directory_maybe_symlink');
28762
+ });
28763
+ watcher.on('unlink', onPathUnlink);
28764
+ watcher.on('unlinkDir', onPathUnlink);
28765
+ },
28766
+ };
28767
+ }
28768
+ function tryResolveRealFile(file, preserveSymlinks) {
28769
+ const stat = tryStatSync(file);
28770
+ if (stat?.isFile())
28771
+ return getRealPath(file, preserveSymlinks);
28772
+ }
28773
+ function tryResolveRealFileWithExtensions(filePath, extensions, preserveSymlinks) {
28774
+ for (const ext of extensions) {
28775
+ const res = tryResolveRealFile(filePath + ext, preserveSymlinks);
28776
+ if (res)
28777
+ return res;
28778
+ }
28779
+ }
28780
+ function tryResolveRealFileOrType(file, preserveSymlinks) {
28781
+ const fileStat = tryStatSync(file);
28782
+ if (fileStat?.isFile()) {
28783
+ return { path: getRealPath(file, preserveSymlinks), type: 'file' };
28784
+ }
28785
+ if (fileStat?.isDirectory()) {
28786
+ return { type: 'directory' };
28787
+ }
28788
+ return;
28789
+ }
28790
+ function getRealPath(resolved, preserveSymlinks) {
28791
+ if (!preserveSymlinks) {
28792
+ resolved = safeRealpathSync(resolved);
28793
+ }
28794
+ return normalizePath$3(resolved);
28795
+ }
28796
+ function isDirectory(path) {
28797
+ const stat = tryStatSync(path);
28798
+ return stat?.isDirectory() ?? false;
28799
+ }
28800
+
28464
28801
  const normalizedClientEntry$1 = normalizePath$3(CLIENT_ENTRY);
28465
28802
  const normalizedEnvEntry$1 = normalizePath$3(ENV_ENTRY);
28466
28803
  const ERR_RESOLVE_PACKAGE_ENTRY_FAIL = 'ERR_RESOLVE_PACKAGE_ENTRY_FAIL';
@@ -28767,46 +29104,46 @@ const knownTsOutputRE = /\.(?:js|mjs|cjs|jsx)$/;
28767
29104
  const isPossibleTsOutput = (url) => knownTsOutputRE.test(url);
28768
29105
  function tryCleanFsResolve(file, options, tryIndex = true, targetWeb = true, skipPackageJson = false) {
28769
29106
  const { tryPrefix, extensions, preserveSymlinks } = options;
28770
- const fileStat = tryStatSync(file);
28771
- // Try direct match first
28772
- if (fileStat?.isFile())
28773
- return getRealPath(file, options.preserveSymlinks);
29107
+ const fsUtils = options.fsUtils ?? commonFsUtils;
29108
+ // Optimization to get the real type or file type (directory, file, other)
29109
+ const fileResult = fsUtils.tryResolveRealFileOrType(file, options.preserveSymlinks);
29110
+ if (fileResult?.path)
29111
+ return fileResult.path;
28774
29112
  let res;
28775
29113
  // If path.dirname is a valid directory, try extensions and ts resolution logic
28776
29114
  const possibleJsToTs = options.isFromTsImporter && isPossibleTsOutput(file);
28777
- if (possibleJsToTs || extensions.length || tryPrefix) {
29115
+ if (possibleJsToTs || options.extensions.length || tryPrefix) {
28778
29116
  const dirPath = path$o.dirname(file);
28779
- const dirStat = tryStatSync(dirPath);
28780
- if (dirStat?.isDirectory()) {
29117
+ if (fsUtils.isDirectory(dirPath)) {
28781
29118
  if (possibleJsToTs) {
28782
29119
  // try resolve .js, .mjs, .cjs or .jsx import to typescript file
28783
29120
  const fileExt = path$o.extname(file);
28784
29121
  const fileName = file.slice(0, -fileExt.length);
28785
- if ((res = tryResolveRealFile(fileName + fileExt.replace('js', 'ts'), preserveSymlinks)))
29122
+ if ((res = fsUtils.tryResolveRealFile(fileName + fileExt.replace('js', 'ts'), preserveSymlinks)))
28786
29123
  return res;
28787
29124
  // for .js, also try .tsx
28788
29125
  if (fileExt === '.js' &&
28789
- (res = tryResolveRealFile(fileName + '.tsx', preserveSymlinks)))
29126
+ (res = fsUtils.tryResolveRealFile(fileName + '.tsx', preserveSymlinks)))
28790
29127
  return res;
28791
29128
  }
28792
- if ((res = tryResolveRealFileWithExtensions(file, extensions, preserveSymlinks)))
29129
+ if ((res = fsUtils.tryResolveRealFileWithExtensions(file, extensions, preserveSymlinks)))
28793
29130
  return res;
28794
29131
  if (tryPrefix) {
28795
29132
  const prefixed = `${dirPath}/${options.tryPrefix}${path$o.basename(file)}`;
28796
- if ((res = tryResolveRealFile(prefixed, preserveSymlinks)))
29133
+ if ((res = fsUtils.tryResolveRealFile(prefixed, preserveSymlinks)))
28797
29134
  return res;
28798
- if ((res = tryResolveRealFileWithExtensions(prefixed, extensions, preserveSymlinks)))
29135
+ if ((res = fsUtils.tryResolveRealFileWithExtensions(prefixed, extensions, preserveSymlinks)))
28799
29136
  return res;
28800
29137
  }
28801
29138
  }
28802
29139
  }
28803
- if (tryIndex && fileStat) {
29140
+ if (tryIndex && fileResult?.type === 'directory') {
28804
29141
  // Path points to a directory, check for package.json and entry and /index file
28805
29142
  const dirPath = file;
28806
29143
  if (!skipPackageJson) {
28807
29144
  let pkgPath = `${dirPath}/package.json`;
28808
29145
  try {
28809
- if (fs$l.existsSync(pkgPath)) {
29146
+ if (fsUtils.existsSync(pkgPath)) {
28810
29147
  if (!options.preserveSymlinks) {
28811
29148
  pkgPath = safeRealpathSync(pkgPath);
28812
29149
  }
@@ -28821,26 +29158,14 @@ function tryCleanFsResolve(file, options, tryIndex = true, targetWeb = true, ski
28821
29158
  throw e;
28822
29159
  }
28823
29160
  }
28824
- if ((res = tryResolveRealFileWithExtensions(`${dirPath}/index`, extensions, preserveSymlinks)))
29161
+ if ((res = fsUtils.tryResolveRealFileWithExtensions(`${dirPath}/index`, extensions, preserveSymlinks)))
28825
29162
  return res;
28826
29163
  if (tryPrefix) {
28827
- if ((res = tryResolveRealFileWithExtensions(`${dirPath}/${options.tryPrefix}index`, extensions, preserveSymlinks)))
29164
+ if ((res = fsUtils.tryResolveRealFileWithExtensions(`${dirPath}/${options.tryPrefix}index`, extensions, preserveSymlinks)))
28828
29165
  return res;
28829
29166
  }
28830
29167
  }
28831
29168
  }
28832
- function tryResolveRealFile(file, preserveSymlinks) {
28833
- const stat = tryStatSync(file);
28834
- if (stat?.isFile())
28835
- return getRealPath(file, preserveSymlinks);
28836
- }
28837
- function tryResolveRealFileWithExtensions(filePath, extensions, preserveSymlinks) {
28838
- for (const ext of extensions) {
28839
- const res = tryResolveRealFile(filePath + ext, preserveSymlinks);
28840
- if (res)
28841
- return res;
28842
- }
28843
- }
28844
29169
  function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr = false, externalize, allowLinkedExternal = true) {
28845
29170
  const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options;
28846
29171
  // check for deep import, e.g. "my-lib/foo"
@@ -29294,12 +29619,6 @@ function mapWithBrowserField(relativePathInPkgDir, map) {
29294
29619
  function equalWithoutSuffix(path, key, suffix) {
29295
29620
  return key.endsWith(suffix) && key.slice(0, -suffix.length) === path;
29296
29621
  }
29297
- function getRealPath(resolved, preserveSymlinks) {
29298
- if (!preserveSymlinks && browserExternalId !== resolved) {
29299
- resolved = safeRealpathSync(resolved);
29300
- }
29301
- return normalizePath$3(resolved);
29302
- }
29303
29622
 
29304
29623
  var dist = {};
29305
29624
 
@@ -38014,6 +38333,7 @@ const inlineCSSRE$1 = /__VITE_INLINE_CSS__([a-z\d]{8}_\d+)__/g;
38014
38333
  // Do not allow preceding '.', but do allow preceding '...' for spread operations
38015
38334
  const inlineImportRE = /(?<!(?<!\.\.)\.)\bimport\s*\(("(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*')\)/dg;
38016
38335
  const htmlLangRE = /\.(?:html|htm)$/;
38336
+ const spaceRe = /[\t\n\f\r ]/;
38017
38337
  const importMapRE = /[ \t]*<script[^>]*type\s*=\s*(?:"importmap"|'importmap'|importmap)[^>]*>.*?<\/script>/is;
38018
38338
  const moduleScriptRE = /[ \t]*<script[^>]*type\s*=\s*(?:"module"|'module'|module)[^>]*>/i;
38019
38339
  const modulePreloadLinkRE = /[ \t]*<link[^>]*rel\s*=\s*(?:"modulepreload"|'modulepreload'|modulepreload)[\s\S]*?\/>/i;
@@ -38076,6 +38396,16 @@ const assetAttrsConfig = {
38076
38396
  image: ['xlink:href', 'href'],
38077
38397
  use: ['xlink:href', 'href'],
38078
38398
  };
38399
+ // Some `<link rel>` elements should not be inlined in build. Excluding:
38400
+ // - `shortcut` : only valid for IE <9, use `icon`
38401
+ // - `mask-icon` : deprecated since Safari 12 (for pinned tabs)
38402
+ // - `apple-touch-icon-precomposed` : only valid for iOS <7 (for avoiding gloss effect)
38403
+ const noInlineLinkRels = new Set([
38404
+ 'icon',
38405
+ 'apple-touch-icon',
38406
+ 'apple-touch-startup-image',
38407
+ 'manifest',
38408
+ ]);
38079
38409
  const isAsyncScriptMap = new WeakMap();
38080
38410
  function nodeIsElement(node) {
38081
38411
  return node.nodeName[0] !== '#';
@@ -38237,13 +38567,13 @@ function buildHtmlPlugin(config) {
38237
38567
  // references the post-build location, ignoring empty attributes and
38238
38568
  // attributes that directly reference named output.
38239
38569
  const namedOutput = Object.keys(config?.build?.rollupOptions?.input || {});
38240
- const processAssetUrl = async (url) => {
38570
+ const processAssetUrl = async (url, shouldInline) => {
38241
38571
  if (url !== '' && // Empty attribute
38242
38572
  !namedOutput.includes(url) && // Direct reference to named output
38243
38573
  !namedOutput.includes(removeLeadingSlash(url)) // Allow for absolute references as named output can't be an absolute path
38244
38574
  ) {
38245
38575
  try {
38246
- return await urlToBuiltUrl(url, id, config, this);
38576
+ return await urlToBuiltUrl(url, id, config, this, shouldInline);
38247
38577
  }
38248
38578
  catch (e) {
38249
38579
  if (e.code !== 'ENOENT') {
@@ -38343,8 +38673,16 @@ function buildHtmlPlugin(config) {
38343
38673
  js += importExpression;
38344
38674
  }
38345
38675
  else {
38676
+ // If the node is a link, check if it can be inlined. If not, set `shouldInline`
38677
+ // to `false` to force no inline. If `undefined`, it leaves to the default heuristics.
38678
+ const isNoInlineLink = node.nodeName === 'link' &&
38679
+ node.attrs.some((p) => p.name === 'rel' &&
38680
+ p.value
38681
+ .split(spaceRe)
38682
+ .some((v) => noInlineLinkRels.has(v.toLowerCase())));
38683
+ const shouldInline = isNoInlineLink ? false : undefined;
38346
38684
  assetUrlsPromises.push((async () => {
38347
- const processedUrl = await processAssetUrl(url);
38685
+ const processedUrl = await processAssetUrl(url, shouldInline);
38348
38686
  if (processedUrl !== url) {
38349
38687
  overwriteAttrValue(s, getAttrSourceCodeLocation(node, attrKey), processedUrl);
38350
38688
  }
@@ -38987,26 +39325,27 @@ function cssPlugin(config) {
38987
39325
  }
38988
39326
  const ssr = options?.ssr === true;
38989
39327
  const urlReplacer = async (url, importer) => {
38990
- if (checkPublicFile(url, config)) {
39328
+ const decodedUrl = decodeURI(url);
39329
+ if (checkPublicFile(decodedUrl, config)) {
38991
39330
  if (encodePublicUrlsInCSS(config)) {
38992
- return publicFileToBuiltUrl(url, config);
39331
+ return publicFileToBuiltUrl(decodedUrl, config);
38993
39332
  }
38994
39333
  else {
38995
- return joinUrlSegments(config.base, url);
39334
+ return joinUrlSegments(config.base, decodedUrl);
38996
39335
  }
38997
39336
  }
38998
- const resolved = await resolveUrl(url, importer);
39337
+ const resolved = await resolveUrl(decodedUrl, importer);
38999
39338
  if (resolved) {
39000
39339
  return fileToUrl$1(resolved, config, this);
39001
39340
  }
39002
39341
  if (config.command === 'build') {
39003
39342
  const isExternal = config.build.rollupOptions.external
39004
- ? resolveUserExternal(config.build.rollupOptions.external, url, // use URL as id since id could not be resolved
39343
+ ? resolveUserExternal(config.build.rollupOptions.external, decodedUrl, // use URL as id since id could not be resolved
39005
39344
  id, false)
39006
39345
  : false;
39007
39346
  if (!isExternal) {
39008
39347
  // #9800 If we cannot resolve the css url, leave a warning.
39009
- config.logger.warnOnce(`\n${url} referenced in ${id} didn't resolve at build time, it will remain unchanged to be resolved at runtime`);
39348
+ config.logger.warnOnce(`\n${decodedUrl} referenced in ${id} didn't resolve at build time, it will remain unchanged to be resolved at runtime`);
39010
39349
  }
39011
39350
  }
39012
39351
  return url;
@@ -39737,8 +40076,8 @@ function createCachedImport(imp) {
39737
40076
  return cached;
39738
40077
  };
39739
40078
  }
39740
- const importPostcssImport = createCachedImport(() => import('./dep-I1uDMLJL.js').then(function (n) { return n.i; }));
39741
- const importPostcssModules = createCachedImport(() => import('./dep-Sacttr-6.js').then(function (n) { return n.i; }));
40079
+ const importPostcssImport = createCachedImport(() => import('./dep-Y5q53UKR.js').then(function (n) { return n.i; }));
40080
+ const importPostcssModules = createCachedImport(() => import('./dep-WV5u8Hxr.js').then(function (n) { return n.i; }));
39742
40081
  const importPostcss = createCachedImport(() => import('postcss'));
39743
40082
  /**
39744
40083
  * @experimental
@@ -41125,7 +41464,7 @@ function throwOutdatedRequest(id) {
41125
41464
  throw err;
41126
41465
  }
41127
41466
 
41128
- // AST walker module for Mozilla Parser API compatible trees
41467
+ // AST walker module for ESTree compatible trees
41129
41468
 
41130
41469
 
41131
41470
  function makeTest(test) {
@@ -48719,7 +49058,7 @@ function servePublicMiddleware(server, publicFiles) {
48719
49058
  // To avoid the performance impact of `existsSync` on every request, we check against an
48720
49059
  // in-memory set of known public files. This set is updated on restarts.
48721
49060
  // also skip import request and internal requests `/@fs/ /@vite-client` etc...
48722
- if (!publicFiles.has(toFilePath(req.url)) ||
49061
+ if ((publicFiles && !publicFiles.has(toFilePath(req.url))) ||
48723
49062
  isImportRequest(req.url) ||
48724
49063
  isInternalRequest(req.url)) {
48725
49064
  return next();
@@ -50186,8 +50525,8 @@ async function instantiateModule(url, server, context = { global }, urlStack = [
50186
50525
  // In node@12+ we can use dynamic import to load CJS and ESM
50187
50526
  async function nodeImport(id, importer, resolveOptions, metadata) {
50188
50527
  let url;
50189
- const isRuntimeHandled = id.startsWith('data:') || isBuiltin(id);
50190
- if (isRuntimeHandled) {
50528
+ let filePath;
50529
+ if (id.startsWith('data:') || isBuiltin(id)) {
50191
50530
  url = id;
50192
50531
  }
50193
50532
  else {
@@ -50197,18 +50536,19 @@ async function nodeImport(id, importer, resolveOptions, metadata) {
50197
50536
  err.code = 'ERR_MODULE_NOT_FOUND';
50198
50537
  throw err;
50199
50538
  }
50539
+ filePath = resolved.id;
50200
50540
  url = pathToFileURL(resolved.id).toString();
50201
50541
  }
50202
50542
  const mod = await import(url);
50203
50543
  if (resolveOptions.legacyProxySsrExternalModules) {
50204
50544
  return proxyESM(mod);
50205
50545
  }
50206
- else if (isRuntimeHandled) {
50207
- return mod;
50546
+ else if (filePath) {
50547
+ analyzeImportedModDifference(mod, filePath, id, metadata, resolveOptions.packageCache);
50548
+ return proxyGuardOnlyEsm(mod, id);
50208
50549
  }
50209
50550
  else {
50210
- analyzeImportedModDifference(mod, url, id, metadata, resolveOptions.packageCache);
50211
- return proxyGuardOnlyEsm(mod, id);
50551
+ return mod;
50212
50552
  }
50213
50553
  }
50214
50554
  // rollup-style default import interop for cjs
@@ -52479,6 +52819,9 @@ let Receiver$1 = class Receiver extends Writable$1 {
52479
52819
  * Creates a Receiver instance.
52480
52820
  *
52481
52821
  * @param {Object} [options] Options object
52822
+ * @param {Boolean} [options.allowMultipleEventsPerMicrotask=false] Specifies
52823
+ * whether or not to process more than one of the `'message'`, `'ping'`,
52824
+ * and `'pong'` events per microtask
52482
52825
  * @param {String} [options.binaryType=nodebuffer] The type for binary data
52483
52826
  * @param {Object} [options.extensions] An object containing the negotiated
52484
52827
  * extensions
@@ -52491,6 +52834,8 @@ let Receiver$1 = class Receiver extends Writable$1 {
52491
52834
  constructor(options = {}) {
52492
52835
  super();
52493
52836
 
52837
+ this._allowMultipleEventsPerMicrotask =
52838
+ !!options.allowMultipleEventsPerMicrotask;
52494
52839
  this._binaryType = options.binaryType || BINARY_TYPES$1[0];
52495
52840
  this._extensions = options.extensions || {};
52496
52841
  this._isServer = !!options.isServer;
@@ -53001,7 +53346,9 @@ let Receiver$1 = class Receiver extends Writable$1 {
53001
53346
  }
53002
53347
  }
53003
53348
 
53004
- this._state = WAIT_MICROTASK;
53349
+ this._state = this._allowMultipleEventsPerMicrotask
53350
+ ? GET_INFO
53351
+ : WAIT_MICROTASK;
53005
53352
  }
53006
53353
 
53007
53354
  /**
@@ -53018,8 +53365,6 @@ let Receiver$1 = class Receiver extends Writable$1 {
53018
53365
  if (data.length === 0) {
53019
53366
  this.emit('conclude', 1005, EMPTY_BUFFER$2);
53020
53367
  this.end();
53021
-
53022
- this._state = GET_INFO;
53023
53368
  } else {
53024
53369
  const code = data.readUInt16BE(0);
53025
53370
 
@@ -53051,16 +53396,16 @@ let Receiver$1 = class Receiver extends Writable$1 {
53051
53396
 
53052
53397
  this.emit('conclude', code, buf);
53053
53398
  this.end();
53054
-
53055
- this._state = GET_INFO;
53056
53399
  }
53057
- } else if (this._opcode === 0x09) {
53058
- this.emit('ping', data);
53059
- this._state = WAIT_MICROTASK;
53060
- } else {
53061
- this.emit('pong', data);
53062
- this._state = WAIT_MICROTASK;
53400
+
53401
+ this._state = GET_INFO;
53402
+ return;
53063
53403
  }
53404
+
53405
+ this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);
53406
+ this._state = this._allowMultipleEventsPerMicrotask
53407
+ ? GET_INFO
53408
+ : WAIT_MICROTASK;
53064
53409
  }
53065
53410
  };
53066
53411
 
@@ -54276,6 +54621,9 @@ let WebSocket$1 = class WebSocket extends EventEmitter$1 {
54276
54621
  * @param {Duplex} socket The network socket between the server and client
54277
54622
  * @param {Buffer} head The first packet of the upgraded stream
54278
54623
  * @param {Object} options Options object
54624
+ * @param {Boolean} [options.allowMultipleEventsPerMicrotask=false] Specifies
54625
+ * whether or not to process more than one of the `'message'`, `'ping'`,
54626
+ * and `'pong'` events per microtask
54279
54627
  * @param {Function} [options.generateMask] The function used to generate the
54280
54628
  * masking key
54281
54629
  * @param {Number} [options.maxPayload=0] The maximum allowed message size
@@ -54285,6 +54633,7 @@ let WebSocket$1 = class WebSocket extends EventEmitter$1 {
54285
54633
  */
54286
54634
  setSocket(socket, head, options) {
54287
54635
  const receiver = new Receiver({
54636
+ allowMultipleEventsPerMicrotask: options.allowMultipleEventsPerMicrotask,
54288
54637
  binaryType: this.binaryType,
54289
54638
  extensions: this._extensions,
54290
54639
  isServer: this._isServer,
@@ -54702,6 +55051,11 @@ var websocket = WebSocket$1;
54702
55051
  * @param {(String|URL)} address The URL to which to connect
54703
55052
  * @param {Array} protocols The subprotocols
54704
55053
  * @param {Object} [options] Connection options
55054
+ * @param {Boolean} [options.allowMultipleEventsPerMicrotask=false] Specifies
55055
+ * whether or not to process more than one of the `'message'`, `'ping'`,
55056
+ * and `'pong'` events per microtask
55057
+ * @param {Function} [options.finishRequest] A function which can be used to
55058
+ * customize the headers of each http request before it is sent
54705
55059
  * @param {Boolean} [options.followRedirects=false] Whether or not to follow
54706
55060
  * redirects
54707
55061
  * @param {Function} [options.generateMask] The function used to generate the
@@ -54724,6 +55078,7 @@ var websocket = WebSocket$1;
54724
55078
  */
54725
55079
  function initAsClient(websocket, address, protocols, options) {
54726
55080
  const opts = {
55081
+ allowMultipleEventsPerMicrotask: false,
54727
55082
  protocolVersion: protocolVersions[1],
54728
55083
  maxPayload: 100 * 1024 * 1024,
54729
55084
  skipUTF8Validation: false,
@@ -54890,8 +55245,8 @@ function initAsClient(websocket, address, protocols, options) {
54890
55245
  ? opts.socketPath === websocket._originalHostOrSocketPath
54891
55246
  : false
54892
55247
  : websocket._originalIpc
54893
- ? false
54894
- : parsedUrl.host === websocket._originalHostOrSocketPath;
55248
+ ? false
55249
+ : parsedUrl.host === websocket._originalHostOrSocketPath;
54895
55250
 
54896
55251
  if (!isSameHost || (websocket._originalSecure && !isSecure)) {
54897
55252
  //
@@ -55075,6 +55430,7 @@ function initAsClient(websocket, address, protocols, options) {
55075
55430
  }
55076
55431
 
55077
55432
  websocket.setSocket(socket, head, {
55433
+ allowMultipleEventsPerMicrotask: opts.allowMultipleEventsPerMicrotask,
55078
55434
  generateMask: opts.generateMask,
55079
55435
  maxPayload: opts.maxPayload,
55080
55436
  skipUTF8Validation: opts.skipUTF8Validation
@@ -55491,6 +55847,9 @@ class WebSocketServer extends EventEmitter {
55491
55847
  * Create a `WebSocketServer` instance.
55492
55848
  *
55493
55849
  * @param {Object} options Configuration options
55850
+ * @param {Boolean} [options.allowMultipleEventsPerMicrotask=false] Specifies
55851
+ * whether or not to process more than one of the `'message'`, `'ping'`,
55852
+ * and `'pong'` events per microtask
55494
55853
  * @param {Number} [options.backlog=511] The maximum length of the queue of
55495
55854
  * pending connections
55496
55855
  * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
@@ -55517,6 +55876,7 @@ class WebSocketServer extends EventEmitter {
55517
55876
  super();
55518
55877
 
55519
55878
  options = {
55879
+ allowMultipleEventsPerMicrotask: false,
55520
55880
  maxPayload: 100 * 1024 * 1024,
55521
55881
  skipUTF8Validation: false,
55522
55882
  perMessageDeflate: false,
@@ -55871,6 +56231,8 @@ class WebSocketServer extends EventEmitter {
55871
56231
  socket.removeListener('error', socketOnError);
55872
56232
 
55873
56233
  ws.setSocket(socket, head, {
56234
+ allowMultipleEventsPerMicrotask:
56235
+ this.options.allowMultipleEventsPerMicrotask,
55874
56236
  maxPayload: this.options.maxPayload,
55875
56237
  skipUTF8Validation: this.options.skipUTF8Validation
55876
56238
  });
@@ -58410,7 +58772,7 @@ function doesProxyContextMatchUrl(context, url) {
58410
58772
  }
58411
58773
 
58412
58774
  const debug$6 = createDebugger('vite:html-fallback');
58413
- function htmlFallbackMiddleware(root, spaFallback) {
58775
+ function htmlFallbackMiddleware(root, spaFallback, fsUtils = commonFsUtils) {
58414
58776
  // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
58415
58777
  return function viteHtmlFallbackMiddleware(req, res, next) {
58416
58778
  if (
@@ -58429,7 +58791,7 @@ function htmlFallbackMiddleware(root, spaFallback) {
58429
58791
  // so we need to check if the file exists
58430
58792
  if (pathname.endsWith('.html')) {
58431
58793
  const filePath = path$o.join(root, pathname);
58432
- if (fs$l.existsSync(filePath)) {
58794
+ if (fsUtils.existsSync(filePath)) {
58433
58795
  debug$6?.(`Rewriting ${req.method} ${req.url} to ${url}`);
58434
58796
  req.url = url;
58435
58797
  return next();
@@ -58438,7 +58800,7 @@ function htmlFallbackMiddleware(root, spaFallback) {
58438
58800
  // trailing slash should check for fallback index.html
58439
58801
  else if (pathname[pathname.length - 1] === '/') {
58440
58802
  const filePath = path$o.join(root, pathname, 'index.html');
58441
- if (fs$l.existsSync(filePath)) {
58803
+ if (fsUtils.existsSync(filePath)) {
58442
58804
  const newUrl = url + 'index.html';
58443
58805
  debug$6?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
58444
58806
  req.url = newUrl;
@@ -58448,7 +58810,7 @@ function htmlFallbackMiddleware(root, spaFallback) {
58448
58810
  // non-trailing slash should check for fallback .html
58449
58811
  else {
58450
58812
  const filePath = path$o.join(root, pathname + '.html');
58451
- if (fs$l.existsSync(filePath)) {
58813
+ if (fsUtils.existsSync(filePath)) {
58452
58814
  const newUrl = url + '.html';
58453
58815
  debug$6?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
58454
58816
  req.url = newUrl;
@@ -58740,6 +59102,9 @@ function shouldPreTransform(url, config) {
58740
59102
  return (!checkPublicFile(url, config) && (isJSRequest(url) || isCSSRequest(url)));
58741
59103
  }
58742
59104
  const wordCharRE = /\w/;
59105
+ function isBareRelative(url) {
59106
+ return wordCharRE.test(url[0]) && !url.includes(':');
59107
+ }
58743
59108
  const isSrcSet = (attr) => attr.name === 'srcset' && attr.prefix === undefined;
58744
59109
  const processNodeUrl = (url, useSrcSetReplacer, config, htmlPath, originalUrl, server) => {
58745
59110
  // prefix with base (dev only, base is never relative)
@@ -58759,20 +59124,25 @@ const processNodeUrl = (url, useSrcSetReplacer, config, htmlPath, originalUrl, s
58759
59124
  // rewrite `./index.js` -> `localhost:5173/a/index.js`.
58760
59125
  // rewrite `../index.js` -> `localhost:5173/index.js`.
58761
59126
  // rewrite `relative/index.js` -> `localhost:5173/a/relative/index.js`.
58762
- ((url[0] === '.' || (wordCharRE.test(url[0]) && !url.includes(':'))) &&
59127
+ ((url[0] === '.' || isBareRelative(url)) &&
58763
59128
  originalUrl &&
58764
59129
  originalUrl !== '/' &&
58765
59130
  htmlPath === '/index.html')) {
58766
- const devBase = config.base;
58767
- const fullUrl = path$o.posix.join(devBase, url);
58768
- if (server && shouldPreTransform(url, config)) {
58769
- preTransformRequest(server, fullUrl, devBase);
58770
- }
58771
- return fullUrl;
59131
+ url = path$o.posix.join(config.base, url);
58772
59132
  }
58773
- else {
58774
- return url;
59133
+ if (server && shouldPreTransform(url, config)) {
59134
+ let preTransformUrl;
59135
+ if (url[0] === '/') {
59136
+ preTransformUrl = url;
59137
+ }
59138
+ else if (url[0] === '.' || isBareRelative(url)) {
59139
+ preTransformUrl = path$o.posix.join(config.base, path$o.posix.dirname(htmlPath), url);
59140
+ }
59141
+ if (preTransformUrl) {
59142
+ preTransformRequest(server, preTransformUrl, config.base);
59143
+ }
58775
59144
  }
59145
+ return url;
58776
59146
  };
58777
59147
  const processedUrl = useSrcSetReplacer
58778
59148
  ? processSrcSetSync(url, ({ url }) => replacer(url))
@@ -58785,7 +59155,7 @@ const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl
58785
59155
  let proxyModulePath;
58786
59156
  let proxyModuleUrl;
58787
59157
  const trailingSlash = htmlPath.endsWith('/');
58788
- if (!trailingSlash && fs$l.existsSync(filename)) {
59158
+ if (!trailingSlash && getFsUtils(config).existsSync(filename)) {
58789
59159
  proxyModulePath = htmlPath;
58790
59160
  proxyModuleUrl = joinUrlSegments(base, htmlPath);
58791
59161
  }
@@ -58936,6 +59306,7 @@ const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl
58936
59306
  };
58937
59307
  function indexHtmlMiddleware(root, server) {
58938
59308
  const isDev = isDevServer(server);
59309
+ const fsUtils = getFsUtils(server.config);
58939
59310
  // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
58940
59311
  return async function viteIndexHtmlMiddleware(req, res, next) {
58941
59312
  if (res.writableEnded) {
@@ -58951,7 +59322,7 @@ function indexHtmlMiddleware(root, server) {
58951
59322
  else {
58952
59323
  filePath = path$o.join(root, decodeURIComponent(url));
58953
59324
  }
58954
- if (fs$l.existsSync(filePath)) {
59325
+ if (fsUtils.existsSync(filePath)) {
58955
59326
  const headers = isDev
58956
59327
  ? server.config.server.headers
58957
59328
  : server.config.preview.headers;
@@ -59807,11 +60178,14 @@ async function _createServer(inlineConfig = {}, options) {
59807
60178
  }
59808
60179
  }
59809
60180
  };
60181
+ const normalizedPublicDir = normalizePath$3(config.publicDir);
59810
60182
  const onFileAddUnlink = async (file, isUnlink) => {
59811
60183
  file = normalizePath$3(file);
59812
60184
  await container.watchChange(file, { event: isUnlink ? 'delete' : 'create' });
59813
- if (config.publicDir && file.startsWith(config.publicDir)) {
59814
- publicFiles[isUnlink ? 'delete' : 'add'](file.slice(config.publicDir.length));
60185
+ if (config.publicDir && publicFiles) {
60186
+ if (file.startsWith(normalizedPublicDir)) {
60187
+ publicFiles[isUnlink ? 'delete' : 'add'](file.slice(normalizedPublicDir.length));
60188
+ }
59815
60189
  }
59816
60190
  await handleFileAddUnlink(file, server, isUnlink);
59817
60191
  await onHMRUpdate(file, true);
@@ -59823,8 +60197,13 @@ async function _createServer(inlineConfig = {}, options) {
59823
60197
  moduleGraph.onFileChange(file);
59824
60198
  await onHMRUpdate(file, false);
59825
60199
  });
59826
- watcher.on('add', (file) => onFileAddUnlink(file, false));
59827
- watcher.on('unlink', (file) => onFileAddUnlink(file, true));
60200
+ getFsUtils(config).initWatcher?.(watcher);
60201
+ watcher.on('add', (file) => {
60202
+ onFileAddUnlink(file, false);
60203
+ });
60204
+ watcher.on('unlink', (file) => {
60205
+ onFileAddUnlink(file, true);
60206
+ });
59828
60207
  ws.on('vite:invalidate', async ({ path, message }) => {
59829
60208
  const mod = moduleGraph.urlToModuleMap.get(path);
59830
60209
  if (mod && mod.isSelfAccepting && mod.lastHMRTimestamp > 0) {
@@ -59893,7 +60272,7 @@ async function _createServer(inlineConfig = {}, options) {
59893
60272
  middlewares.use(serveStaticMiddleware(server));
59894
60273
  // html fallback
59895
60274
  if (config.appType === 'spa' || config.appType === 'mpa') {
59896
- middlewares.use(htmlFallbackMiddleware(root, config.appType === 'spa'));
60275
+ middlewares.use(htmlFallbackMiddleware(root, config.appType === 'spa', getFsUtils(config)));
59897
60276
  }
59898
60277
  // run post config hooks
59899
60278
  // This is applied before the html middleware so that user middleware can
@@ -60035,6 +60414,7 @@ function resolveServerOptions(root, raw, logger) {
60035
60414
  strict: server.fs?.strict ?? true,
60036
60415
  allow: allowDirs,
60037
60416
  deny,
60417
+ cachedChecks: server.fs?.cachedChecks ?? !!process.env.VITE_SERVER_FS_CACHED_CHECKS,
60038
60418
  };
60039
60419
  if (server.origin?.endsWith('/')) {
60040
60420
  server.origin = server.origin.slice(0, -1);
@@ -61166,6 +61546,7 @@ function extractImportedBindings(id, source, importSpec, importedBindings) {
61166
61546
  */
61167
61547
  function importAnalysisPlugin(config) {
61168
61548
  const { root, base } = config;
61549
+ const fsUtils = getFsUtils(config);
61169
61550
  const clientPublicPath = path$o.posix.join(base, CLIENT_PUBLIC_PATH);
61170
61551
  const enablePartialAccept = config.experimental?.hmrPartialAccept;
61171
61552
  let server;
@@ -61294,7 +61675,7 @@ function importAnalysisPlugin(config) {
61294
61675
  }
61295
61676
  else if (depsOptimizer?.isOptimizedDepFile(resolved.id) ||
61296
61677
  (path$o.isAbsolute(cleanUrl(resolved.id)) &&
61297
- fs$l.existsSync(cleanUrl(resolved.id)))) {
61678
+ fsUtils.existsSync(cleanUrl(resolved.id)))) {
61298
61679
  // an optimized deps may not yet exists in the filesystem, or
61299
61680
  // a regular file exists but is out of root: rewrite to absolute /@fs/ paths
61300
61681
  url = path$o.posix.join(FS_PREFIX, resolved.id);
@@ -61948,6 +62329,7 @@ function preAliasPlugin(config) {
61948
62329
  const findPatterns = getAliasPatterns(config.resolve.alias);
61949
62330
  const isConfiguredAsExternal = createIsConfiguredAsSsrExternal(config);
61950
62331
  const isBuild = config.command === 'build';
62332
+ const fsUtils = getFsUtils(config);
61951
62333
  return {
61952
62334
  name: 'vite:pre-alias',
61953
62335
  async resolveId(id, importer, options) {
@@ -61976,7 +62358,7 @@ function preAliasPlugin(config) {
61976
62358
  const resolvedId = cleanUrl(resolved.id);
61977
62359
  const isVirtual = resolvedId === id || resolvedId.includes('\0');
61978
62360
  if (!isVirtual &&
61979
- fs$l.existsSync(resolvedId) &&
62361
+ fsUtils.existsSync(resolvedId) &&
61980
62362
  !moduleListContains(optimizeDeps.exclude, id) &&
61981
62363
  path$o.isAbsolute(resolvedId) &&
61982
62364
  (isInNodeModules$1(resolvedId) ||
@@ -62674,6 +63056,7 @@ async function resolvePlugins(config, prePlugins, normalPlugins, postPlugins) {
62674
63056
  packageCache: config.packageCache,
62675
63057
  ssrConfig: config.ssr,
62676
63058
  asSrc: true,
63059
+ fsUtils: getFsUtils(config),
62677
63060
  getDepsOptimizer: (ssr) => getDepsOptimizer(config, ssr),
62678
63061
  shouldExternalize: isBuild && config.build.ssr
62679
63062
  ? (id, importer) => shouldExternalizeForSSR(id, importer, config)
@@ -64210,7 +64593,7 @@ async function createDepsOptimizer(config, server) {
64210
64593
  // Ensure that a rerun will not be issued for current discovered deps
64211
64594
  if (debounceProcessingHandle)
64212
64595
  clearTimeout(debounceProcessingHandle);
64213
- if (closed || Object.keys(metadata.discovered).length === 0) {
64596
+ if (closed) {
64214
64597
  currentlyProcessing = false;
64215
64598
  return;
64216
64599
  }
@@ -64411,9 +64794,6 @@ async function createDepsOptimizer(config, server) {
64411
64794
  });
64412
64795
  }
64413
64796
  function debouncedProcessing(timeout = debounceMs) {
64414
- if (!newDepsDiscovered) {
64415
- return;
64416
- }
64417
64797
  // Debounced rerun, let other missing dependencies be discovered before
64418
64798
  // the running next optimizeDeps
64419
64799
  enqueuedRerun = undefined;
@@ -64455,8 +64835,10 @@ async function createDepsOptimizer(config, server) {
64455
64835
  const scanDeps = Object.keys(result.metadata.optimized);
64456
64836
  if (scanDeps.length === 0 && crawlDeps.length === 0) {
64457
64837
  debug$2?.(colors$1.green(`✨ no dependencies found by the scanner or crawling static imports`));
64458
- result.cancel();
64459
- firstRunCalled = true;
64838
+ // We still commit the result so the scanner isn't run on the next cold start
64839
+ // for projects without dependencies
64840
+ startNextDiscoveredBatch();
64841
+ runOptimizer(result);
64460
64842
  return;
64461
64843
  }
64462
64844
  const needsInteropMismatch = findInteropMismatches(metadata.discovered, result.metadata.optimized);
@@ -64490,10 +64872,8 @@ async function createDepsOptimizer(config, server) {
64490
64872
  debug$2?.(colors$1.green(`✨ no dependencies found while crawling the static imports`));
64491
64873
  firstRunCalled = true;
64492
64874
  }
64493
- else {
64494
- // queue the first optimizer run
64495
- debouncedProcessing(0);
64496
- }
64875
+ // queue the first optimizer run, even without deps so the result is cached
64876
+ debouncedProcessing(0);
64497
64877
  }
64498
64878
  }
64499
64879
  // Called during buildStart at build time, when build --watch is used.
@@ -67200,6 +67580,7 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development',
67200
67580
  tryIndex: true,
67201
67581
  ...options,
67202
67582
  idOnly: true,
67583
+ fsUtils: getFsUtils(resolved),
67203
67584
  }),
67204
67585
  ],
67205
67586
  }));
@@ -67337,7 +67718,9 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development',
67337
67718
  },
67338
67719
  });
67339
67720
  // validate config
67340
- if (config.build?.terserOptions && config.build.minify !== 'terser') {
67721
+ if (config.build?.terserOptions &&
67722
+ config.build.minify &&
67723
+ config.build.minify !== 'terser') {
67341
67724
  logger.warn(colors$1.yellow(`build.terserOptions is specified but build.minify is not set to use Terser. ` +
67342
67725
  `Note Vite now defaults to use esbuild for minification. If you still ` +
67343
67726
  `prefer Terser, set build.minify to "terser".`));
package/dist/node/cli.js CHANGED
@@ -2,7 +2,7 @@ import path from 'node:path';
2
2
  import fs from 'node:fs';
3
3
  import { performance } from 'node:perf_hooks';
4
4
  import { EventEmitter } from 'events';
5
- import { x as colors, k as createLogger, r as resolveConfig } from './chunks/dep-YJaePtkC.js';
5
+ import { x as colors, k as createLogger, r as resolveConfig } from './chunks/dep-uAHLeuC6.js';
6
6
  import { VERSION } from './constants.js';
7
7
  import 'node:fs/promises';
8
8
  import 'node:url';
@@ -759,7 +759,7 @@ cli
759
759
  filterDuplicateOptions(options);
760
760
  // output structure is preserved even after bundling so require()
761
761
  // is ok here
762
- const { createServer } = await import('./chunks/dep-YJaePtkC.js').then(function (n) { return n.A; });
762
+ const { createServer } = await import('./chunks/dep-uAHLeuC6.js').then(function (n) { return n.A; });
763
763
  try {
764
764
  const server = await createServer({
765
765
  root,
@@ -839,7 +839,7 @@ cli
839
839
  .option('-w, --watch', `[boolean] rebuilds when modules have changed on disk`)
840
840
  .action(async (root, options) => {
841
841
  filterDuplicateOptions(options);
842
- const { build } = await import('./chunks/dep-YJaePtkC.js').then(function (n) { return n.C; });
842
+ const { build } = await import('./chunks/dep-uAHLeuC6.js').then(function (n) { return n.C; });
843
843
  const buildOptions = cleanOptions(options);
844
844
  try {
845
845
  await build({
@@ -867,7 +867,7 @@ cli
867
867
  .option('--force', `[boolean] force the optimizer to ignore the cache and re-bundle`)
868
868
  .action(async (root, options) => {
869
869
  filterDuplicateOptions(options);
870
- const { optimizeDeps } = await import('./chunks/dep-YJaePtkC.js').then(function (n) { return n.B; });
870
+ const { optimizeDeps } = await import('./chunks/dep-uAHLeuC6.js').then(function (n) { return n.B; });
871
871
  try {
872
872
  const config = await resolveConfig({
873
873
  root,
@@ -893,7 +893,7 @@ cli
893
893
  .option('--outDir <dir>', `[string] output directory (default: dist)`)
894
894
  .action(async (root, options) => {
895
895
  filterDuplicateOptions(options);
896
- const { preview } = await import('./chunks/dep-YJaePtkC.js').then(function (n) { return n.D; });
896
+ const { preview } = await import('./chunks/dep-uAHLeuC6.js').then(function (n) { return n.D; });
897
897
  try {
898
898
  const server = await preview({
899
899
  root,
@@ -1572,6 +1572,13 @@ interface FileSystemServeOptions {
1572
1572
  * @default ['.env', '.env.*', '*.crt', '*.pem']
1573
1573
  */
1574
1574
  deny?: string[];
1575
+ /**
1576
+ * Enable caching of fs calls.
1577
+ *
1578
+ * @experimental
1579
+ * @default false
1580
+ */
1581
+ cachedChecks?: boolean;
1575
1582
  }
1576
1583
  type ServerHook = (this: void, server: ViteDevServer) => (() => void) | void | Promise<(() => void) | void>;
1577
1584
  type HttpServer = http.Server | Http2SecureServer;
@@ -2634,6 +2641,18 @@ interface ResolvedSSROptions extends SSROptions {
2634
2641
  optimizeDeps: SsrDepOptimizationOptions;
2635
2642
  }
2636
2643
 
2644
+ interface FsUtils {
2645
+ existsSync: (path: string) => boolean;
2646
+ isDirectory: (path: string) => boolean;
2647
+ tryResolveRealFile: (path: string, preserveSymlinks?: boolean) => string | undefined;
2648
+ tryResolveRealFileWithExtensions: (path: string, extensions: string[], preserveSymlinks?: boolean) => string | undefined;
2649
+ tryResolveRealFileOrType: (path: string, preserveSymlinks?: boolean) => {
2650
+ path?: string;
2651
+ type: 'directory' | 'file';
2652
+ } | undefined;
2653
+ initWatcher?: (watcher: FSWatcher) => void;
2654
+ }
2655
+
2637
2656
  interface ResolveOptions {
2638
2657
  /**
2639
2658
  * @default ['browser', 'module', 'jsnext:main', 'jsnext']
@@ -2656,6 +2675,7 @@ interface InternalResolveOptions extends Required<ResolveOptions> {
2656
2675
  isProduction: boolean;
2657
2676
  ssrConfig?: SSROptions;
2658
2677
  packageCache?: PackageCache;
2678
+ fsUtils?: FsUtils;
2659
2679
  /**
2660
2680
  * src code mode also attempts the following:
2661
2681
  * - resolving /xxx as URLs
@@ -1,6 +1,6 @@
1
1
  export { parseAst, parseAstAsync } from 'rollup/parseAst';
2
- import { i as isInNodeModules } from './chunks/dep-YJaePtkC.js';
3
- export { b as build, e as buildErrorMessage, h as createFilter, k as createLogger, c as createServer, d as defineConfig, f as formatPostcssSourceMap, u as isFileServingAllowed, l as loadConfigFromFile, v as loadEnv, g as mergeAlias, m as mergeConfig, n as normalizePath, o as optimizeDeps, a as preprocessCSS, p as preview, r as resolveConfig, w as resolveEnvPrefix, q as searchForWorkspaceRoot, j as send, s as sortUserPlugins, t as transformWithEsbuild } from './chunks/dep-YJaePtkC.js';
2
+ import { i as isInNodeModules } from './chunks/dep-uAHLeuC6.js';
3
+ export { b as build, e as buildErrorMessage, h as createFilter, k as createLogger, c as createServer, d as defineConfig, f as formatPostcssSourceMap, u as isFileServingAllowed, l as loadConfigFromFile, v as loadEnv, g as mergeAlias, m as mergeConfig, n as normalizePath, o as optimizeDeps, a as preprocessCSS, p as preview, r as resolveConfig, w as resolveEnvPrefix, q as searchForWorkspaceRoot, j as send, s as sortUserPlugins, t as transformWithEsbuild } from './chunks/dep-uAHLeuC6.js';
4
4
  export { VERSION as version } from './constants.js';
5
5
  export { version as esbuildVersion } from 'esbuild';
6
6
  export { VERSION as rollupVersion } from 'rollup';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite",
3
- "version": "5.0.6",
3
+ "version": "5.0.8",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "author": "Evan You",
@@ -70,7 +70,7 @@
70
70
  },
71
71
  "devDependencies": {
72
72
  "@ampproject/remapping": "^2.2.1",
73
- "@babel/parser": "^7.23.5",
73
+ "@babel/parser": "^7.23.6",
74
74
  "@jridgewell/trace-mapping": "^0.3.20",
75
75
  "@rollup/plugin-alias": "^5.1.0",
76
76
  "@rollup/plugin-commonjs": "^25.0.7",
@@ -82,7 +82,7 @@
82
82
  "@types/escape-html": "^1.0.4",
83
83
  "@types/pnpapi": "^0.0.5",
84
84
  "acorn": "^8.11.2",
85
- "acorn-walk": "^8.3.0",
85
+ "acorn-walk": "^8.3.1",
86
86
  "cac": "^6.7.14",
87
87
  "chokidar": "^3.5.3",
88
88
  "connect": "^3.7.0",
@@ -126,7 +126,7 @@
126
126
  "tslib": "^2.6.2",
127
127
  "types": "link:./types",
128
128
  "ufo": "^1.3.2",
129
- "ws": "^8.14.2"
129
+ "ws": "^8.15.0"
130
130
  },
131
131
  "peerDependencies": {
132
132
  "@types/node": "^18.0.0 || >=20.0.0",