vite 6.0.0-beta.7 → 6.0.0-beta.9

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.
@@ -7,7 +7,7 @@ import { promisify, format, inspect } from 'node:util';
7
7
  import { performance } from 'node:perf_hooks';
8
8
  import require$$0$3, { createRequire, builtinModules } from 'node:module';
9
9
  import esbuild, { transform, formatMessages, build as build$3 } from 'esbuild';
10
- import { CLIENT_ENTRY, OPTIMIZABLE_ENTRY_RE, wildcardHosts, loopbackHosts, FS_PREFIX, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH, DEFAULT_ASSETS_INLINE_LIMIT, ENV_ENTRY, SPECIAL_QUERY_RE, DEP_VERSION_RE, JS_TYPES_RE, KNOWN_ASSET_TYPES, CSS_LANGS_RE, METADATA_FILENAME, ESBUILD_MODULES_TARGET, ERR_OPTIMIZE_DEPS_PROCESSING_ERROR, ERR_OUTDATED_OPTIMIZED_DEP, ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR, VITE_PACKAGE_DIR, CLIENT_DIR, DEFAULT_DEV_PORT, VERSION, ROLLUP_HOOKS, DEFAULT_PREVIEW_PORT, DEFAULT_ASSETS_RE, DEFAULT_CONFIG_FILES, DEFAULT_EXTENSIONS, DEFAULT_MAIN_FIELDS } from '../constants.js';
10
+ import { CLIENT_ENTRY, OPTIMIZABLE_ENTRY_RE, wildcardHosts, loopbackHosts, FS_PREFIX, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH, DEFAULT_ASSETS_INLINE_LIMIT, ENV_ENTRY, SPECIAL_QUERY_RE, DEP_VERSION_RE, DEV_PROD_CONDITION, JS_TYPES_RE, KNOWN_ASSET_TYPES, CSS_LANGS_RE, METADATA_FILENAME, ESBUILD_MODULES_TARGET, ERR_OPTIMIZE_DEPS_PROCESSING_ERROR, ERR_OUTDATED_OPTIMIZED_DEP, ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR, VITE_PACKAGE_DIR, CLIENT_DIR, DEFAULT_DEV_PORT, VERSION, ROLLUP_HOOKS, DEFAULT_PREVIEW_PORT, DEFAULT_ASSETS_RE, DEFAULT_CONFIG_FILES, DEFAULT_MAIN_FIELDS, DEFAULT_CONDITIONS, DEFAULT_EXTENSIONS, DEFAULT_EXTERNAL_CONDITIONS } from '../constants.js';
11
11
  import * as sysPath from 'path';
12
12
  import sysPath__default, { posix, win32, isAbsolute, resolve as resolve$2, relative as relative$1, basename as basename$1, extname, dirname as dirname$1, join, sep } from 'path';
13
13
  import require$$0$1, { existsSync, readFileSync, statSync, lstatSync, unwatchFile, watchFile, watch as watch$1, stat as stat$1, readdirSync } from 'fs';
@@ -2308,6 +2308,15 @@ function withTrailingSlash(path) {
2308
2308
  }
2309
2309
  return path;
2310
2310
  }
2311
+ function promiseWithResolvers() {
2312
+ let resolve;
2313
+ let reject;
2314
+ const promise = new Promise((_resolve, _reject) => {
2315
+ resolve = _resolve;
2316
+ reject = _reject;
2317
+ });
2318
+ return { promise, resolve, reject };
2319
+ }
2311
2320
 
2312
2321
  // @ts-check
2313
2322
  /** @typedef { import('estree').BaseNode} BaseNode */
@@ -9651,14 +9660,24 @@ function loadPackageData(pkgPath) {
9651
9660
  function getResolveCacheKey(key, options) {
9652
9661
  return [
9653
9662
  key,
9654
- options.webCompatible ? "1" : "0",
9655
9663
  options.isRequire ? "1" : "0",
9656
9664
  options.conditions.join("_"),
9657
- options.overrideConditions?.join("_") || "",
9658
9665
  options.extensions.join("_"),
9659
9666
  options.mainFields.join("_")
9660
9667
  ].join("|");
9661
9668
  }
9669
+ function findNearestNodeModules(basedir) {
9670
+ while (basedir) {
9671
+ const pkgPath = path.join(basedir, "node_modules");
9672
+ if (tryStatSync(pkgPath)?.isDirectory()) {
9673
+ return pkgPath;
9674
+ }
9675
+ const nextBasedir = path.dirname(basedir);
9676
+ if (nextBasedir === basedir) break;
9677
+ basedir = nextBasedir;
9678
+ }
9679
+ return null;
9680
+ }
9662
9681
  function watchPackageDataPlugin(packageCache) {
9663
9682
  const watchQueue = /* @__PURE__ */ new Set();
9664
9683
  const watchedDirs = /* @__PURE__ */ new Set();
@@ -9791,7 +9810,7 @@ const DEBUG = process.env.DEBUG;
9791
9810
  function createDebugger(namespace, options = {}) {
9792
9811
  const log = debug$e(namespace);
9793
9812
  const { onlyWhenFocused, depth } = options;
9794
- if (depth && log.inspectOpts.depth == null) {
9813
+ if (depth && log.inspectOpts && log.inspectOpts.depth == null) {
9795
9814
  log.inspectOpts.depth = options.depth;
9796
9815
  }
9797
9816
  let enabled = log.enabled;
@@ -10604,15 +10623,6 @@ function getPackageManagerCommand(type = "install") {
10604
10623
  function isDevServer(server) {
10605
10624
  return "pluginContainer" in server;
10606
10625
  }
10607
- function promiseWithResolvers() {
10608
- let resolve;
10609
- let reject;
10610
- const promise = new Promise((_resolve, _reject) => {
10611
- resolve = _resolve;
10612
- reject = _reject;
10613
- });
10614
- return { promise, resolve, reject };
10615
- }
10616
10626
  function createSerialPromiseQueue() {
10617
10627
  let previousTask;
10618
10628
  return {
@@ -13313,6 +13323,9 @@ function checkPublicFile(url, config) {
13313
13323
 
13314
13324
  const assetUrlRE = /__VITE_ASSET__([\w$]+)__(?:\$_(.*?)__)?/g;
13315
13325
  const jsSourceMapRE = /\.[cm]?js\.map$/;
13326
+ const noInlineRE = /[?&]no-inline\b/;
13327
+ const inlineRE$2 = /[?&]inline\b/;
13328
+ const svgExtRE = /\.svg(?:$|\?)/;
13316
13329
  const assetCache = /* @__PURE__ */ new WeakMap();
13317
13330
  const cssEntriesMap = /* @__PURE__ */ new WeakMap();
13318
13331
  function registerCustomMime() {
@@ -13401,10 +13414,11 @@ function assetPlugin(config) {
13401
13414
  }
13402
13415
  id = removeUrlQuery(id);
13403
13416
  let url = await fileToUrl$1(this, id);
13404
- const environment = this.environment;
13405
- const mod = environment.mode === "dev" && environment.moduleGraph.getModuleById(id);
13406
- if (mod && mod.lastHMRTimestamp > 0) {
13407
- url = injectQuery(url, `t=${mod.lastHMRTimestamp}`);
13417
+ if (!url.startsWith("data:") && this.environment.mode === "dev") {
13418
+ const mod = this.environment.moduleGraph.getModuleById(id);
13419
+ if (mod && mod.lastHMRTimestamp > 0) {
13420
+ url = injectQuery(url, `t=${mod.lastHMRTimestamp}`);
13421
+ }
13408
13422
  }
13409
13423
  return {
13410
13424
  code: `export default ${JSON.stringify(encodeURIPath(url))}`,
@@ -13445,14 +13459,28 @@ function assetPlugin(config) {
13445
13459
  async function fileToUrl$1(pluginContext, id) {
13446
13460
  const { environment } = pluginContext;
13447
13461
  if (environment.config.command === "serve") {
13448
- return fileToDevUrl(id, environment.getTopLevelConfig());
13462
+ return fileToDevUrl(environment, id);
13449
13463
  } else {
13450
13464
  return fileToBuiltUrl(pluginContext, id);
13451
13465
  }
13452
13466
  }
13453
- function fileToDevUrl(id, config, skipBase = false) {
13467
+ async function fileToDevUrl(environment, id, skipBase = false) {
13468
+ const config = environment.getTopLevelConfig();
13469
+ const publicFile = checkPublicFile(id, config);
13470
+ if (inlineRE$2.test(id)) {
13471
+ const file = publicFile || cleanUrl(id);
13472
+ const content = await fsp.readFile(file);
13473
+ return assetToDataURL(environment, file, content);
13474
+ }
13475
+ if (svgExtRE.test(id)) {
13476
+ const file = publicFile || cleanUrl(id);
13477
+ const content = await fsp.readFile(file);
13478
+ if (shouldInline(environment, file, id, content, void 0, void 0)) {
13479
+ return assetToDataURL(environment, file, content);
13480
+ }
13481
+ }
13454
13482
  let rtn;
13455
- if (checkPublicFile(id, config)) {
13483
+ if (publicFile) {
13456
13484
  rtn = id;
13457
13485
  } else if (id.startsWith(withTrailingSlash(config.root))) {
13458
13486
  rtn = "/" + path.posix.relative(config.root, id);
@@ -13493,8 +13521,15 @@ function isGitLfsPlaceholder(content) {
13493
13521
  async function fileToBuiltUrl(pluginContext, id, skipPublicCheck = false, forceInline) {
13494
13522
  const environment = pluginContext.environment;
13495
13523
  const topLevelConfig = environment.getTopLevelConfig();
13496
- if (!skipPublicCheck && checkPublicFile(id, topLevelConfig)) {
13497
- return publicFileToBuiltUrl(id, topLevelConfig);
13524
+ if (!skipPublicCheck) {
13525
+ const publicFile = checkPublicFile(id, topLevelConfig);
13526
+ if (publicFile) {
13527
+ if (inlineRE$2.test(id)) {
13528
+ id = publicFile;
13529
+ } else {
13530
+ return publicFileToBuiltUrl(id, topLevelConfig);
13531
+ }
13532
+ }
13498
13533
  }
13499
13534
  const cache = assetCache.get(environment);
13500
13535
  const cached = cache.get(id);
@@ -13504,18 +13539,8 @@ async function fileToBuiltUrl(pluginContext, id, skipPublicCheck = false, forceI
13504
13539
  const { file, postfix } = splitFileAndPostfix(id);
13505
13540
  const content = await fsp.readFile(file);
13506
13541
  let url;
13507
- if (shouldInline(pluginContext, file, id, content, forceInline)) {
13508
- if (environment.config.build.lib && isGitLfsPlaceholder(content)) {
13509
- environment.logger.warn(
13510
- colors.yellow(`Inlined file ${id} was not downloaded via Git LFS`)
13511
- );
13512
- }
13513
- if (file.endsWith(".svg")) {
13514
- url = svgToDataURL(content);
13515
- } else {
13516
- const mimeType = lookup(file) ?? "application/octet-stream";
13517
- url = `data:${mimeType};base64,${content.toString("base64")}`;
13518
- }
13542
+ if (shouldInline(environment, file, id, content, pluginContext, forceInline)) {
13543
+ url = assetToDataURL(environment, file, content);
13519
13544
  } else {
13520
13545
  const originalFileName = normalizePath$1(
13521
13546
  path.relative(environment.config.root, file)
@@ -13546,13 +13571,18 @@ async function urlToBuiltUrl(pluginContext, url, importer, forceInline) {
13546
13571
  forceInline
13547
13572
  );
13548
13573
  }
13549
- const shouldInline = (pluginContext, file, id, content, forceInline) => {
13550
- const environment = pluginContext.environment;
13551
- const { assetsInlineLimit } = environment.config.build;
13552
- if (environment.config.build.lib) return true;
13553
- if (pluginContext.getModuleInfo(id)?.isEntry) return false;
13574
+ function shouldInline(environment, file, id, content, buildPluginContext, forceInline) {
13575
+ if (noInlineRE.test(id)) return false;
13576
+ if (inlineRE$2.test(id)) return true;
13577
+ if (buildPluginContext) {
13578
+ if (environment.config.build.lib) return true;
13579
+ if (buildPluginContext.getModuleInfo(id)?.isEntry) return false;
13580
+ }
13554
13581
  if (forceInline !== void 0) return forceInline;
13582
+ if (file.endsWith(".html")) return false;
13583
+ if (file.endsWith(".svg") && id.includes("#")) return false;
13555
13584
  let limit;
13585
+ const { assetsInlineLimit } = environment.config.build;
13556
13586
  if (typeof assetsInlineLimit === "function") {
13557
13587
  const userShouldInline = assetsInlineLimit(file, content);
13558
13588
  if (userShouldInline != null) return userShouldInline;
@@ -13560,10 +13590,21 @@ const shouldInline = (pluginContext, file, id, content, forceInline) => {
13560
13590
  } else {
13561
13591
  limit = Number(assetsInlineLimit);
13562
13592
  }
13563
- if (file.endsWith(".html")) return false;
13564
- if (file.endsWith(".svg") && id.includes("#")) return false;
13565
13593
  return content.length < limit && !isGitLfsPlaceholder(content);
13566
- };
13594
+ }
13595
+ function assetToDataURL(environment, file, content) {
13596
+ if (environment.config.build.lib && isGitLfsPlaceholder(content)) {
13597
+ environment.logger.warn(
13598
+ colors.yellow(`Inlined file ${file} was not downloaded via Git LFS`)
13599
+ );
13600
+ }
13601
+ if (file.endsWith(".svg")) {
13602
+ return svgToDataURL(content);
13603
+ } else {
13604
+ const mimeType = lookup(file) ?? "application/octet-stream";
13605
+ return `data:${mimeType};base64,${content.toString("base64")}`;
13606
+ }
13607
+ }
13567
13608
  const nestedQuotesRE = /"[^"']*'[^"]*"|'[^'"]*"[^']*'/;
13568
13609
  function svgToDataURL(content) {
13569
13610
  const stringContent = content.toString();
@@ -15820,283 +15861,6 @@ function hasESMSyntax(code, opts = {}) {
15820
15861
  return ESM_RE.test(code);
15821
15862
  }
15822
15863
 
15823
- const commonFsUtils = {
15824
- existsSync: fs__default.existsSync,
15825
- isDirectory,
15826
- tryResolveRealFile,
15827
- tryResolveRealFileWithExtensions,
15828
- tryResolveRealFileOrType
15829
- };
15830
- const cachedFsUtilsMap = /* @__PURE__ */ new WeakMap();
15831
- function getFsUtils(config) {
15832
- let fsUtils = cachedFsUtilsMap.get(config);
15833
- if (!fsUtils) {
15834
- if (config.command !== "serve" || config.server.fs.cachedChecks !== true || config.server.watch?.ignored || process.versions.pnp) {
15835
- fsUtils = commonFsUtils;
15836
- } else if (!config.resolve.preserveSymlinks && config.root !== getRealPath(config.root)) {
15837
- fsUtils = commonFsUtils;
15838
- } else {
15839
- fsUtils = createCachedFsUtils(config);
15840
- }
15841
- cachedFsUtilsMap.set(config, fsUtils);
15842
- }
15843
- return fsUtils;
15844
- }
15845
- function readDirCacheSync(file) {
15846
- let dirents;
15847
- try {
15848
- dirents = fs__default.readdirSync(file, { withFileTypes: true });
15849
- } catch {
15850
- return;
15851
- }
15852
- return direntsToDirentMap(dirents);
15853
- }
15854
- function direntsToDirentMap(fsDirents) {
15855
- const dirents = /* @__PURE__ */ new Map();
15856
- for (const dirent of fsDirents) {
15857
- const type = dirent.isDirectory() ? "directory" : dirent.isSymbolicLink() ? "symlink" : dirent.isFile() ? "file" : void 0;
15858
- if (type) {
15859
- dirents.set(dirent.name, { type });
15860
- }
15861
- }
15862
- return dirents;
15863
- }
15864
- function ensureFileMaybeSymlinkIsResolved(direntCache, filePath) {
15865
- if (direntCache.type !== "file_maybe_symlink") return;
15866
- const isSymlink = fs__default.lstatSync(filePath, { throwIfNoEntry: false })?.isSymbolicLink();
15867
- direntCache.type = isSymlink === void 0 ? "error" : isSymlink ? "symlink" : "file";
15868
- }
15869
- function pathUntilPart(root, parts, i) {
15870
- let p = root;
15871
- for (let k = 0; k < i; k++) p += "/" + parts[k];
15872
- return p;
15873
- }
15874
- function createCachedFsUtils(config) {
15875
- const root = config.root;
15876
- const rootDirPath = `${root}/`;
15877
- const rootCache = { type: "directory" };
15878
- const getDirentCacheSync = (parts) => {
15879
- let direntCache = rootCache;
15880
- for (let i = 0; i < parts.length; i++) {
15881
- if (direntCache.type === "directory") {
15882
- let dirPath;
15883
- if (!direntCache.dirents) {
15884
- dirPath = pathUntilPart(root, parts, i);
15885
- const dirents = readDirCacheSync(dirPath);
15886
- if (!dirents) {
15887
- direntCache.type = "error";
15888
- return;
15889
- }
15890
- direntCache.dirents = dirents;
15891
- }
15892
- const nextDirentCache = direntCache.dirents.get(parts[i]);
15893
- if (!nextDirentCache) {
15894
- return;
15895
- }
15896
- if (nextDirentCache.type === "directory_maybe_symlink") {
15897
- dirPath ??= pathUntilPart(root, parts, i + 1);
15898
- const isSymlink = fs__default.lstatSync(dirPath, { throwIfNoEntry: false })?.isSymbolicLink();
15899
- nextDirentCache.type = isSymlink ? "symlink" : "directory";
15900
- }
15901
- direntCache = nextDirentCache;
15902
- } else if (direntCache.type === "symlink") {
15903
- return direntCache;
15904
- } else if (direntCache.type === "error") {
15905
- return direntCache;
15906
- } else {
15907
- if (i !== parts.length - 1) {
15908
- return;
15909
- }
15910
- if (direntCache.type === "file_maybe_symlink") {
15911
- ensureFileMaybeSymlinkIsResolved(
15912
- direntCache,
15913
- pathUntilPart(root, parts, i)
15914
- );
15915
- return direntCache;
15916
- } else if (direntCache.type === "file") {
15917
- return direntCache;
15918
- } else {
15919
- return;
15920
- }
15921
- }
15922
- }
15923
- return direntCache;
15924
- };
15925
- function getDirentCacheFromPath(normalizedFile) {
15926
- if (normalizedFile[normalizedFile.length - 1] === "/") {
15927
- normalizedFile = normalizedFile.slice(0, -1);
15928
- }
15929
- if (normalizedFile === root) {
15930
- return rootCache;
15931
- }
15932
- if (!normalizedFile.startsWith(rootDirPath)) {
15933
- return void 0;
15934
- }
15935
- const pathFromRoot = normalizedFile.slice(rootDirPath.length);
15936
- const parts = pathFromRoot.split("/");
15937
- const direntCache = getDirentCacheSync(parts);
15938
- if (!direntCache || direntCache.type === "error") {
15939
- return false;
15940
- }
15941
- return direntCache;
15942
- }
15943
- function onPathAdd(file, type) {
15944
- const direntCache = getDirentCacheFromPath(
15945
- normalizePath$1(path.dirname(file))
15946
- );
15947
- if (direntCache && direntCache.type === "directory" && direntCache.dirents) {
15948
- direntCache.dirents.set(path.basename(file), { type });
15949
- }
15950
- }
15951
- function onPathUnlink(file) {
15952
- const direntCache = getDirentCacheFromPath(
15953
- normalizePath$1(path.dirname(file))
15954
- );
15955
- if (direntCache && direntCache.type === "directory" && direntCache.dirents) {
15956
- direntCache.dirents.delete(path.basename(file));
15957
- }
15958
- }
15959
- return {
15960
- existsSync(file) {
15961
- if (isInNodeModules$1(file)) {
15962
- return fs__default.existsSync(file);
15963
- }
15964
- const normalizedFile = normalizePath$1(file);
15965
- const direntCache = getDirentCacheFromPath(normalizedFile);
15966
- if (direntCache === void 0 || direntCache && direntCache.type === "symlink") {
15967
- return fs__default.existsSync(file);
15968
- }
15969
- return !!direntCache;
15970
- },
15971
- tryResolveRealFile(file, preserveSymlinks) {
15972
- if (isInNodeModules$1(file)) {
15973
- return tryResolveRealFile(file, preserveSymlinks);
15974
- }
15975
- const normalizedFile = normalizePath$1(file);
15976
- const direntCache = getDirentCacheFromPath(normalizedFile);
15977
- if (direntCache === void 0 || direntCache && direntCache.type === "symlink") {
15978
- return tryResolveRealFile(file, preserveSymlinks);
15979
- }
15980
- if (!direntCache || direntCache.type === "directory") {
15981
- return;
15982
- }
15983
- return normalizedFile;
15984
- },
15985
- tryResolveRealFileWithExtensions(file, extensions, preserveSymlinks) {
15986
- if (isInNodeModules$1(file)) {
15987
- return tryResolveRealFileWithExtensions(
15988
- file,
15989
- extensions,
15990
- preserveSymlinks
15991
- );
15992
- }
15993
- const normalizedFile = normalizePath$1(file);
15994
- const dirPath = path.posix.dirname(normalizedFile);
15995
- const direntCache = getDirentCacheFromPath(dirPath);
15996
- if (direntCache === void 0 || direntCache && direntCache.type === "symlink") {
15997
- return tryResolveRealFileWithExtensions(
15998
- file,
15999
- extensions,
16000
- preserveSymlinks
16001
- );
16002
- }
16003
- if (!direntCache || direntCache.type !== "directory") {
16004
- return;
16005
- }
16006
- if (!direntCache.dirents) {
16007
- const dirents = readDirCacheSync(dirPath);
16008
- if (!dirents) {
16009
- direntCache.type = "error";
16010
- return;
16011
- }
16012
- direntCache.dirents = dirents;
16013
- }
16014
- const base = path.posix.basename(normalizedFile);
16015
- for (const ext of extensions) {
16016
- const fileName = base + ext;
16017
- const fileDirentCache = direntCache.dirents.get(fileName);
16018
- if (fileDirentCache) {
16019
- const filePath = dirPath + "/" + fileName;
16020
- ensureFileMaybeSymlinkIsResolved(fileDirentCache, filePath);
16021
- if (fileDirentCache.type === "symlink") {
16022
- return tryResolveRealFile(filePath, preserveSymlinks);
16023
- }
16024
- if (fileDirentCache.type === "file") {
16025
- return filePath;
16026
- }
16027
- }
16028
- }
16029
- },
16030
- tryResolveRealFileOrType(file, preserveSymlinks) {
16031
- if (isInNodeModules$1(file)) {
16032
- return tryResolveRealFileOrType(file, preserveSymlinks);
16033
- }
16034
- const normalizedFile = normalizePath$1(file);
16035
- const direntCache = getDirentCacheFromPath(normalizedFile);
16036
- if (direntCache === void 0 || direntCache && direntCache.type === "symlink") {
16037
- return tryResolveRealFileOrType(file, preserveSymlinks);
16038
- }
16039
- if (!direntCache) {
16040
- return;
16041
- }
16042
- if (direntCache.type === "directory") {
16043
- return { type: "directory" };
16044
- }
16045
- return { path: normalizedFile, type: "file" };
16046
- },
16047
- isDirectory(dirPath) {
16048
- if (isInNodeModules$1(dirPath)) {
16049
- return isDirectory(dirPath);
16050
- }
16051
- const direntCache = getDirentCacheFromPath(normalizePath$1(dirPath));
16052
- if (direntCache === void 0 || direntCache && direntCache.type === "symlink") {
16053
- return isDirectory(dirPath);
16054
- }
16055
- return direntCache && direntCache.type === "directory";
16056
- },
16057
- initWatcher(watcher) {
16058
- watcher.on("add", (file) => {
16059
- onPathAdd(file, "file_maybe_symlink");
16060
- });
16061
- watcher.on("addDir", (dir) => {
16062
- onPathAdd(dir, "directory_maybe_symlink");
16063
- });
16064
- watcher.on("unlink", onPathUnlink);
16065
- watcher.on("unlinkDir", onPathUnlink);
16066
- }
16067
- };
16068
- }
16069
- function tryResolveRealFile(file, preserveSymlinks) {
16070
- const stat = tryStatSync(file);
16071
- if (stat?.isFile()) return getRealPath(file, preserveSymlinks);
16072
- }
16073
- function tryResolveRealFileWithExtensions(filePath, extensions, preserveSymlinks) {
16074
- for (const ext of extensions) {
16075
- const res = tryResolveRealFile(filePath + ext, preserveSymlinks);
16076
- if (res) return res;
16077
- }
16078
- }
16079
- function tryResolveRealFileOrType(file, preserveSymlinks) {
16080
- const fileStat = tryStatSync(file);
16081
- if (fileStat?.isFile()) {
16082
- return { path: getRealPath(file, preserveSymlinks), type: "file" };
16083
- }
16084
- if (fileStat?.isDirectory()) {
16085
- return { type: "directory" };
16086
- }
16087
- return;
16088
- }
16089
- function getRealPath(resolved, preserveSymlinks) {
16090
- if (!preserveSymlinks) {
16091
- resolved = safeRealpathSync(resolved);
16092
- }
16093
- return normalizePath$1(resolved);
16094
- }
16095
- function isDirectory(path2) {
16096
- const stat = tryStatSync(path2);
16097
- return stat?.isDirectory() ?? false;
16098
- }
16099
-
16100
15864
  const debug$b = createDebugger("vite:external");
16101
15865
  const isExternalCache = /* @__PURE__ */ new WeakMap();
16102
15866
  function shouldExternalize(environment, id, importer) {
@@ -16118,7 +15882,7 @@ function isConfiguredAsExternal(environment, id, importer) {
16118
15882
  }
16119
15883
  function createIsConfiguredAsExternal(environment) {
16120
15884
  const { config } = environment;
16121
- const { root, resolve, webCompatible } = config;
15885
+ const { root, resolve } = config;
16122
15886
  const { external, noExternal } = resolve;
16123
15887
  const noExternalFilter = typeof noExternal !== "boolean" && !(Array.isArray(noExternal) && noExternal.length === 0) && createFilter(void 0, noExternal, { resolve: false });
16124
15888
  const targetConditions = resolve.externalConditions || [];
@@ -16127,8 +15891,7 @@ function createIsConfiguredAsExternal(environment) {
16127
15891
  root,
16128
15892
  isProduction: false,
16129
15893
  isBuild: true,
16130
- conditions: targetConditions,
16131
- webCompatible
15894
+ conditions: targetConditions
16132
15895
  };
16133
15896
  const isExternalizable = (id, importer, configuredAsExternal) => {
16134
15897
  if (!bareImportRE.test(id) || id.includes("\0")) {
@@ -16210,7 +15973,7 @@ const startsWithWordCharRE = /^\w/;
16210
15973
  const debug$a = createDebugger("vite:resolve-details", {
16211
15974
  onlyWhenFocused: true
16212
15975
  });
16213
- function resolvePlugin(resolveOptions, environmentsOptions) {
15976
+ function resolvePlugin(resolveOptions) {
16214
15977
  const { root, isProduction, asSrc, preferRelative = false } = resolveOptions;
16215
15978
  const rootInRoot = tryStatSync(path.join(root, root))?.isDirectory() ?? false;
16216
15979
  return {
@@ -16220,29 +15983,19 @@ function resolvePlugin(resolveOptions, environmentsOptions) {
16220
15983
  id.startsWith("/virtual:")) {
16221
15984
  return;
16222
15985
  }
16223
- const ssr = resolveOpts?.ssr === true;
16224
15986
  const depsOptimizer = resolveOptions.optimizeDeps && this.environment.mode === "dev" ? this.environment.depsOptimizer : void 0;
16225
15987
  if (id.startsWith(browserExternalId)) {
16226
15988
  return id;
16227
15989
  }
16228
15990
  const isRequire = resolveOpts?.custom?.["node-resolve"]?.isRequire ?? false;
16229
- const environmentName = this.environment.name ?? (ssr ? "ssr" : "client");
16230
- const currentEnvironmentOptions = this.environment.config || environmentsOptions?.[environmentName];
16231
- const environmentResolveOptions = currentEnvironmentOptions?.resolve;
16232
- if (!environmentResolveOptions) {
16233
- throw new Error(
16234
- `Missing ResolveOptions for ${environmentName} environment`
16235
- );
16236
- }
15991
+ const currentEnvironmentOptions = this.environment.config;
16237
15992
  const options = {
16238
15993
  isRequire,
16239
- ...environmentResolveOptions,
16240
- webCompatible: currentEnvironmentOptions.webCompatible,
15994
+ ...currentEnvironmentOptions.resolve,
16241
15995
  ...resolveOptions,
16242
15996
  // plugin options + resolve options overrides
16243
15997
  scan: resolveOpts?.scan ?? resolveOptions.scan
16244
15998
  };
16245
- const depsOptimizerOptions = this.environment.config.optimizeDeps;
16246
15999
  const resolvedImports = resolveSubpathImports(id, importer, options);
16247
16000
  if (resolvedImports) {
16248
16001
  id = resolvedImports;
@@ -16266,13 +16019,13 @@ function resolvePlugin(resolveOptions, environmentsOptions) {
16266
16019
  if (asSrc && id.startsWith(FS_PREFIX)) {
16267
16020
  res = fsPathFromId(id);
16268
16021
  debug$a?.(`[@fs] ${colors.cyan(id)} -> ${colors.dim(res)}`);
16269
- return ensureVersionQuery(res, id, options, ssr, depsOptimizer);
16022
+ return ensureVersionQuery(res, id, options, depsOptimizer);
16270
16023
  }
16271
16024
  if (asSrc && id[0] === "/" && (rootInRoot || !id.startsWith(withTrailingSlash(root)))) {
16272
16025
  const fsPath = path.resolve(root, id.slice(1));
16273
16026
  if (res = tryFsResolve(fsPath, options)) {
16274
16027
  debug$a?.(`[url] ${colors.cyan(id)} -> ${colors.dim(res)}`);
16275
- return ensureVersionQuery(res, id, options, ssr, depsOptimizer);
16028
+ return ensureVersionQuery(res, id, options, depsOptimizer);
16276
16029
  }
16277
16030
  }
16278
16031
  if (id[0] === "." || (preferRelative || importer?.endsWith(".html")) && startsWithWordCharRE.test(id)) {
@@ -16291,18 +16044,11 @@ function resolvePlugin(resolveOptions, environmentsOptions) {
16291
16044
  }
16292
16045
  return normalizedFsPath;
16293
16046
  }
16294
- if (options.webCompatible && options.mainFields.includes("browser") && (res = tryResolveBrowserMapping(
16295
- fsPath,
16296
- importer,
16297
- options,
16298
- true,
16299
- void 0,
16300
- depsOptimizerOptions
16301
- ))) {
16047
+ if (options.mainFields.includes("browser") && (res = tryResolveBrowserMapping(fsPath, importer, options, true))) {
16302
16048
  return res;
16303
16049
  }
16304
16050
  if (res = tryFsResolve(fsPath, options)) {
16305
- res = ensureVersionQuery(res, id, options, ssr, depsOptimizer);
16051
+ res = ensureVersionQuery(res, id, options, depsOptimizer);
16306
16052
  debug$a?.(`[relative] ${colors.cyan(id)} -> ${colors.dim(res)}`);
16307
16053
  if (!options.idOnly && !options.scan && options.isBuild) {
16308
16054
  const resPkg = findNearestPackageData(
@@ -16327,12 +16073,12 @@ function resolvePlugin(resolveOptions, environmentsOptions) {
16327
16073
  const fsPath = path.resolve(basedir, id);
16328
16074
  if (res = tryFsResolve(fsPath, options)) {
16329
16075
  debug$a?.(`[drive-relative] ${colors.cyan(id)} -> ${colors.dim(res)}`);
16330
- return ensureVersionQuery(res, id, options, ssr, depsOptimizer);
16076
+ return ensureVersionQuery(res, id, options, depsOptimizer);
16331
16077
  }
16332
16078
  }
16333
16079
  if (isNonDriveRelativeAbsolutePath(id) && (res = tryFsResolve(id, options))) {
16334
16080
  debug$a?.(`[fs] ${colors.cyan(id)} -> ${colors.dim(res)}`);
16335
- return ensureVersionQuery(res, id, options, ssr, depsOptimizer);
16081
+ return ensureVersionQuery(res, id, options, depsOptimizer);
16336
16082
  }
16337
16083
  if (isExternalUrl(id)) {
16338
16084
  return options.idOnly ? id : { id, external: true };
@@ -16351,13 +16097,12 @@ function resolvePlugin(resolveOptions, environmentsOptions) {
16351
16097
  ))) {
16352
16098
  return res;
16353
16099
  }
16354
- if (options.webCompatible && options.mainFields.includes("browser") && (res = tryResolveBrowserMapping(
16100
+ if (options.mainFields.includes("browser") && (res = tryResolveBrowserMapping(
16355
16101
  id,
16356
16102
  importer,
16357
16103
  options,
16358
16104
  false,
16359
- external,
16360
- depsOptimizerOptions
16105
+ external
16361
16106
  ))) {
16362
16107
  return res;
16363
16108
  }
@@ -16367,14 +16112,13 @@ function resolvePlugin(resolveOptions, environmentsOptions) {
16367
16112
  options,
16368
16113
  depsOptimizer,
16369
16114
  external,
16370
- void 0,
16371
- depsOptimizerOptions
16115
+ void 0
16372
16116
  )) {
16373
16117
  return res;
16374
16118
  }
16375
16119
  if (isBuiltin(id)) {
16376
16120
  if (currentEnvironmentOptions.consumer === "server") {
16377
- if (options.webCompatible && options.noExternal === true && // if both noExternal and external are true, noExternal will take the higher priority and bundle it.
16121
+ if (options.noExternal === true && // if both noExternal and external are true, noExternal will take the higher priority and bundle it.
16378
16122
  // only if the id is explicitly listed in external, we will externalize it and skip this error.
16379
16123
  (options.external === true || !options.external.includes(id))) {
16380
16124
  let message = `Cannot bundle Node.js built-in "${id}"`;
@@ -16384,7 +16128,7 @@ function resolvePlugin(resolveOptions, environmentsOptions) {
16384
16128
  importer
16385
16129
  )}"`;
16386
16130
  }
16387
- message += `. Consider disabling environments.${environmentName}.noExternal or remove the built-in dependency.`;
16131
+ message += `. Consider disabling environments.${this.environment.name}.noExternal or remove the built-in dependency.`;
16388
16132
  this.error(message);
16389
16133
  }
16390
16134
  return options.idOnly ? id : { id, external: true, moduleSideEffects: false };
@@ -16449,8 +16193,8 @@ function resolveSubpathImports(id, importer, options) {
16449
16193
  }
16450
16194
  return importsPath + postfix;
16451
16195
  }
16452
- function ensureVersionQuery(resolved, id, options, ssr, depsOptimizer) {
16453
- if (!ssr && !options.isBuild && !options.scan && depsOptimizer && !(resolved === normalizedClientEntry$1 || resolved === normalizedEnvEntry$1)) {
16196
+ function ensureVersionQuery(resolved, id, options, depsOptimizer) {
16197
+ if (!options.isBuild && !options.scan && depsOptimizer && !(resolved === normalizedClientEntry$1 || resolved === normalizedEnvEntry$1)) {
16454
16198
  const isNodeModule = isInNodeModules$1(id) || isInNodeModules$1(resolved);
16455
16199
  if (isNodeModule && !DEP_VERSION_RE.test(resolved)) {
16456
16200
  const versionHash = depsOptimizer.metadata.browserHash;
@@ -16479,32 +16223,25 @@ const knownTsOutputRE = /\.(?:js|mjs|cjs|jsx)$/;
16479
16223
  const isPossibleTsOutput = (url) => knownTsOutputRE.test(url);
16480
16224
  function tryCleanFsResolve(file, options, tryIndex = true, skipPackageJson = false) {
16481
16225
  const { tryPrefix, extensions, preserveSymlinks } = options;
16482
- const fsUtils = options.fsUtils ?? commonFsUtils;
16483
- const fileResult = fsUtils.tryResolveRealFileOrType(
16484
- file,
16485
- options.preserveSymlinks
16486
- );
16226
+ const fileResult = tryResolveRealFileOrType(file, options.preserveSymlinks);
16487
16227
  if (fileResult?.path) return fileResult.path;
16488
16228
  let res;
16489
16229
  const possibleJsToTs = options.isFromTsImporter && isPossibleTsOutput(file);
16490
16230
  if (possibleJsToTs || options.extensions.length || tryPrefix) {
16491
16231
  const dirPath = path.dirname(file);
16492
- if (fsUtils.isDirectory(dirPath)) {
16232
+ if (isDirectory(dirPath)) {
16493
16233
  if (possibleJsToTs) {
16494
16234
  const fileExt = path.extname(file);
16495
16235
  const fileName = file.slice(0, -fileExt.length);
16496
- if (res = fsUtils.tryResolveRealFile(
16236
+ if (res = tryResolveRealFile(
16497
16237
  fileName + fileExt.replace("js", "ts"),
16498
16238
  preserveSymlinks
16499
16239
  ))
16500
16240
  return res;
16501
- if (fileExt === ".js" && (res = fsUtils.tryResolveRealFile(
16502
- fileName + ".tsx",
16503
- preserveSymlinks
16504
- )))
16241
+ if (fileExt === ".js" && (res = tryResolveRealFile(fileName + ".tsx", preserveSymlinks)))
16505
16242
  return res;
16506
16243
  }
16507
- if (res = fsUtils.tryResolveRealFileWithExtensions(
16244
+ if (res = tryResolveRealFileWithExtensions(
16508
16245
  file,
16509
16246
  extensions,
16510
16247
  preserveSymlinks
@@ -16512,9 +16249,8 @@ function tryCleanFsResolve(file, options, tryIndex = true, skipPackageJson = fal
16512
16249
  return res;
16513
16250
  if (tryPrefix) {
16514
16251
  const prefixed = `${dirPath}/${options.tryPrefix}${path.basename(file)}`;
16515
- if (res = fsUtils.tryResolveRealFile(prefixed, preserveSymlinks))
16516
- return res;
16517
- if (res = fsUtils.tryResolveRealFileWithExtensions(
16252
+ if (res = tryResolveRealFile(prefixed, preserveSymlinks)) return res;
16253
+ if (res = tryResolveRealFileWithExtensions(
16518
16254
  prefixed,
16519
16255
  extensions,
16520
16256
  preserveSymlinks
@@ -16528,7 +16264,7 @@ function tryCleanFsResolve(file, options, tryIndex = true, skipPackageJson = fal
16528
16264
  if (!skipPackageJson) {
16529
16265
  let pkgPath = `${dirPath}/package.json`;
16530
16266
  try {
16531
- if (fsUtils.existsSync(pkgPath)) {
16267
+ if (fs__default.existsSync(pkgPath)) {
16532
16268
  if (!options.preserveSymlinks) {
16533
16269
  pkgPath = safeRealpathSync(pkgPath);
16534
16270
  }
@@ -16540,14 +16276,14 @@ function tryCleanFsResolve(file, options, tryIndex = true, skipPackageJson = fal
16540
16276
  throw e;
16541
16277
  }
16542
16278
  }
16543
- if (res = fsUtils.tryResolveRealFileWithExtensions(
16279
+ if (res = tryResolveRealFileWithExtensions(
16544
16280
  `${dirPath}/index`,
16545
16281
  extensions,
16546
16282
  preserveSymlinks
16547
16283
  ))
16548
16284
  return res;
16549
16285
  if (tryPrefix) {
16550
- if (res = fsUtils.tryResolveRealFileWithExtensions(
16286
+ if (res = tryResolveRealFileWithExtensions(
16551
16287
  `${dirPath}/${options.tryPrefix}index`,
16552
16288
  extensions,
16553
16289
  preserveSymlinks
@@ -16556,7 +16292,7 @@ function tryCleanFsResolve(file, options, tryIndex = true, skipPackageJson = fal
16556
16292
  }
16557
16293
  }
16558
16294
  }
16559
- function tryNodeResolve(id, importer, options, depsOptimizer, externalize, allowLinkedExternal = true, depsOptimizerOptions) {
16295
+ function tryNodeResolve(id, importer, options, depsOptimizer, externalize, allowLinkedExternal = true) {
16560
16296
  const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options;
16561
16297
  const deepMatch = deepImportRE.exec(id);
16562
16298
  const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : cleanUrl(id);
@@ -16619,47 +16355,30 @@ function tryNodeResolve(id, importer, options, depsOptimizer, externalize, allow
16619
16355
  }
16620
16356
  return { ...resolved2, id: resolvedId, external: true };
16621
16357
  };
16622
- if (!options.idOnly && (!options.scan && isBuild && !depsOptimizer || externalize)) {
16358
+ if (!options.idOnly && (!options.scan && isBuild || externalize)) {
16623
16359
  return processResult({
16624
16360
  id: resolved,
16625
16361
  moduleSideEffects: pkg.hasSideEffects(resolved)
16626
16362
  });
16627
16363
  }
16628
- if (!options.ssrOptimizeCheck && (!isInNodeModules$1(resolved) || // linked
16364
+ if (!isInNodeModules$1(resolved) || // linked
16629
16365
  !depsOptimizer || // resolving before listening to the server
16630
- options.scan)) {
16366
+ options.scan) {
16631
16367
  return { id: resolved };
16632
16368
  }
16633
- const isJsType = depsOptimizer ? isOptimizable(resolved, depsOptimizer.options) : OPTIMIZABLE_ENTRY_RE.test(resolved);
16634
- let exclude = depsOptimizer?.options.exclude;
16635
- if (options.ssrOptimizeCheck) {
16636
- exclude = depsOptimizerOptions?.exclude;
16637
- }
16638
- const skipOptimization = !options.ssrOptimizeCheck && depsOptimizer?.options.noDiscovery || !isJsType || importer && isInNodeModules$1(importer) || exclude?.includes(pkgId) || exclude?.includes(id) || SPECIAL_QUERY_RE.test(resolved);
16639
- if (options.ssrOptimizeCheck) {
16640
- return {
16641
- id: skipOptimization ? injectQuery(resolved, `__vite_skip_optimization`) : resolved
16642
- };
16643
- }
16369
+ const isJsType = isOptimizable(resolved, depsOptimizer.options);
16370
+ const exclude = depsOptimizer.options.exclude;
16371
+ const skipOptimization = depsOptimizer.options.noDiscovery || !isJsType || importer && isInNodeModules$1(importer) || exclude?.includes(pkgId) || exclude?.includes(id) || SPECIAL_QUERY_RE.test(resolved);
16644
16372
  if (skipOptimization) {
16645
- if (!isBuild) {
16646
- const versionHash = depsOptimizer.metadata.browserHash;
16647
- if (versionHash && isJsType) {
16648
- resolved = injectQuery(resolved, `v=${versionHash}`);
16649
- }
16373
+ const versionHash = depsOptimizer.metadata.browserHash;
16374
+ if (versionHash && isJsType) {
16375
+ resolved = injectQuery(resolved, `v=${versionHash}`);
16650
16376
  }
16651
16377
  } else {
16652
16378
  const optimizedInfo = depsOptimizer.registerMissingImport(id, resolved);
16653
16379
  resolved = depsOptimizer.getOptimizedDepId(optimizedInfo);
16654
16380
  }
16655
- if (!options.idOnly && !options.scan && isBuild) {
16656
- return {
16657
- id: resolved,
16658
- moduleSideEffects: pkg.hasSideEffects(resolved)
16659
- };
16660
- } else {
16661
- return { id: resolved };
16662
- }
16381
+ return { id: resolved };
16663
16382
  }
16664
16383
  async function tryOptimizedResolve(depsOptimizer, id, importer, preserveSymlinks, packageCache) {
16665
16384
  await depsOptimizer.scanProcessing;
@@ -16705,11 +16424,9 @@ function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache
16705
16424
  if (!entryPoint) {
16706
16425
  for (const field of options.mainFields) {
16707
16426
  if (field === "browser") {
16708
- if (options.webCompatible) {
16709
- entryPoint = tryResolveBrowserEntry(dir, data, options);
16710
- if (entryPoint) {
16711
- break;
16712
- }
16427
+ entryPoint = tryResolveBrowserEntry(dir, data, options);
16428
+ if (entryPoint) {
16429
+ break;
16713
16430
  }
16714
16431
  } else if (typeof data[field] === "string") {
16715
16432
  entryPoint = data[field];
@@ -16726,7 +16443,7 @@ function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache
16726
16443
  skipPackageJson = true;
16727
16444
  } else {
16728
16445
  const { browser: browserField } = data;
16729
- if (options.webCompatible && options.mainFields.includes("browser") && isObject(browserField)) {
16446
+ if (options.mainFields.includes("browser") && isObject(browserField)) {
16730
16447
  entry = mapWithBrowserField(entry, browserField) || entry;
16731
16448
  }
16732
16449
  }
@@ -16760,29 +16477,19 @@ function packageEntryFailure(id, details) {
16760
16477
  throw err;
16761
16478
  }
16762
16479
  function resolveExportsOrImports(pkg, key, options, type) {
16763
- const additionalConditions = new Set(
16764
- options.overrideConditions || [
16765
- "production",
16766
- "development",
16767
- "module",
16768
- ...options.conditions
16769
- ]
16770
- );
16771
- const conditions = [...additionalConditions].filter((condition) => {
16772
- switch (condition) {
16773
- case "production":
16774
- return options.isProduction;
16775
- case "development":
16776
- return !options.isProduction;
16480
+ const conditions = options.conditions.map((condition) => {
16481
+ if (condition === DEV_PROD_CONDITION) {
16482
+ return options.isProduction ? "production" : "development";
16777
16483
  }
16778
- return true;
16484
+ return condition;
16779
16485
  });
16486
+ if (options.isRequire) {
16487
+ conditions.push("require");
16488
+ } else {
16489
+ conditions.push("import");
16490
+ }
16780
16491
  const fn = type === "imports" ? f : o;
16781
- const result = fn(pkg, key, {
16782
- browser: options.webCompatible && !additionalConditions.has("node"),
16783
- require: options.isRequire && !additionalConditions.has("import"),
16784
- conditions
16785
- });
16492
+ const result = fn(pkg, key, { conditions, unsafe: true });
16786
16493
  return result ? result[0] : void 0;
16787
16494
  }
16788
16495
  function resolveDeepImport(id, { setResolvedCache, getResolvedCache, dir, data }, options) {
@@ -16809,7 +16516,7 @@ function resolveDeepImport(id, { setResolvedCache, getResolvedCache, dir, data }
16809
16516
  `Package subpath '${relativeId}' is not defined by "exports" in ${path.join(dir, "package.json")}.`
16810
16517
  );
16811
16518
  }
16812
- } else if (options.webCompatible && options.mainFields.includes("browser") && isObject(browserField)) {
16519
+ } else if (options.mainFields.includes("browser") && isObject(browserField)) {
16813
16520
  const { file, postfix } = splitFileAndPostfix(relativeId);
16814
16521
  const mapped = mapWithBrowserField(file, browserField);
16815
16522
  if (mapped) {
@@ -16835,7 +16542,7 @@ function resolveDeepImport(id, { setResolvedCache, getResolvedCache, dir, data }
16835
16542
  }
16836
16543
  }
16837
16544
  }
16838
- function tryResolveBrowserMapping(id, importer, options, isFilePath, externalize, depsOptimizerOptions) {
16545
+ function tryResolveBrowserMapping(id, importer, options, isFilePath, externalize) {
16839
16546
  let res;
16840
16547
  const pkg = importer && findNearestPackageData(path.dirname(importer), options.packageCache);
16841
16548
  if (pkg && isObject(pkg.data.browser)) {
@@ -16848,8 +16555,7 @@ function tryResolveBrowserMapping(id, importer, options, isFilePath, externalize
16848
16555
  options,
16849
16556
  void 0,
16850
16557
  void 0,
16851
- void 0,
16852
- depsOptimizerOptions
16558
+ void 0
16853
16559
  )?.id : tryFsResolve(path.join(pkg.dir, browserMappedPath), options)) {
16854
16560
  debug$a?.(`[browser mapped] ${colors.cyan(id)} -> ${colors.dim(res)}`);
16855
16561
  let result = { id: res };
@@ -16908,6 +16614,36 @@ function mapWithBrowserField(relativePathInPkgDir, map) {
16908
16614
  function equalWithoutSuffix(path2, key, suffix) {
16909
16615
  return key.endsWith(suffix) && key.slice(0, -suffix.length) === path2;
16910
16616
  }
16617
+ function tryResolveRealFile(file, preserveSymlinks) {
16618
+ const stat = tryStatSync(file);
16619
+ if (stat?.isFile()) return getRealPath(file, preserveSymlinks);
16620
+ }
16621
+ function tryResolveRealFileWithExtensions(filePath, extensions, preserveSymlinks) {
16622
+ for (const ext of extensions) {
16623
+ const res = tryResolveRealFile(filePath + ext, preserveSymlinks);
16624
+ if (res) return res;
16625
+ }
16626
+ }
16627
+ function tryResolveRealFileOrType(file, preserveSymlinks) {
16628
+ const fileStat = tryStatSync(file);
16629
+ if (fileStat?.isFile()) {
16630
+ return { path: getRealPath(file, preserveSymlinks), type: "file" };
16631
+ }
16632
+ if (fileStat?.isDirectory()) {
16633
+ return { type: "directory" };
16634
+ }
16635
+ return;
16636
+ }
16637
+ function getRealPath(resolved, preserveSymlinks) {
16638
+ if (!preserveSymlinks) {
16639
+ resolved = safeRealpathSync(resolved);
16640
+ }
16641
+ return normalizePath$1(resolved);
16642
+ }
16643
+ function isDirectory(path2) {
16644
+ const stat = tryStatSync(path2);
16645
+ return stat?.isDirectory() ?? false;
16646
+ }
16911
16647
 
16912
16648
  const externalWithConversionNamespace = "vite:dep-pre-bundle:external-conversion";
16913
16649
  const convertedExternalPrefix = "vite-dep-pre-bundle-external:";
@@ -17179,7 +16915,6 @@ function getDefaultResolvedEnvironmentOptions(config) {
17179
16915
  define: config.define,
17180
16916
  resolve: config.resolve,
17181
16917
  consumer: "server",
17182
- webCompatible: false,
17183
16918
  optimizeDeps: config.optimizeDeps,
17184
16919
  dev: config.dev,
17185
16920
  build: config.build
@@ -18727,7 +18462,6 @@ function createOptimizeDepsIncludeResolver(environment) {
18727
18462
  const resolve = createBackCompatIdResolver(topLevelConfig, {
18728
18463
  asSrc: false,
18729
18464
  scan: true,
18730
- ssrOptimizeCheck: environment.config.consumer === "server",
18731
18465
  packageCache: /* @__PURE__ */ new Map()
18732
18466
  });
18733
18467
  return async (id) => {
@@ -19195,7 +18929,7 @@ async function prepareEsbuildOptimizerRun(environment, depsInfo, processingCache
19195
18929
  process.env.NODE_ENV || environment.config.mode
19196
18930
  )
19197
18931
  };
19198
- const platform = environment.config.webCompatible ? "browser" : "node";
18932
+ const platform = environment.config.consumer === "client" ? "browser" : "node";
19199
18933
  const external = [...optimizeDeps2?.exclude ?? []];
19200
18934
  const plugins = [...pluginsFromConfig];
19201
18935
  if (external.length) {
@@ -19262,9 +18996,7 @@ async function addManuallyIncludedOptimizeDeps(environment, deps) {
19262
18996
  const entry = await resolve(id);
19263
18997
  if (entry) {
19264
18998
  if (isOptimizable(entry, optimizeDeps2)) {
19265
- if (!entry.endsWith("?__vite_skip_optimization")) {
19266
- deps[normalizedId] = entry;
19267
- }
18999
+ deps[normalizedId] = entry;
19268
19000
  } else {
19269
19001
  unableToOptimize(id, "Cannot optimize dependency");
19270
19002
  }
@@ -19505,8 +19237,7 @@ function getConfigHash(environment) {
19505
19237
  ...optimizeDeps2?.esbuildOptions,
19506
19238
  plugins: optimizeDeps2?.esbuildOptions?.plugins?.map((p) => p.name)
19507
19239
  }
19508
- },
19509
- webCompatible: config.webCompatible
19240
+ }
19510
19241
  },
19511
19242
  (_, value) => {
19512
19243
  if (typeof value === "function" || value instanceof RegExp) {
@@ -19640,6 +19371,7 @@ var index$1 = {
19640
19371
  };
19641
19372
 
19642
19373
  const jsonExtRE = /\.json(?:$|\?)(?!commonjs-(?:proxy|external))/;
19374
+ const jsonObjRE = /^\s*\{/;
19643
19375
  const jsonLangs = `\\.(?:json|json5)(?:$|\\?)`;
19644
19376
  const jsonLangRE = new RegExp(jsonLangs);
19645
19377
  const isJSONRequest = (request) => jsonLangRE.test(request);
@@ -19652,31 +19384,29 @@ function jsonPlugin(options = {}, isBuild) {
19652
19384
  json = stripBomTag(json);
19653
19385
  try {
19654
19386
  if (options.stringify !== false) {
19655
- if (options.namedExports) {
19387
+ if (options.namedExports && jsonObjRE.test(json)) {
19656
19388
  const parsed = JSON.parse(json);
19657
- if (typeof parsed === "object" && parsed != null) {
19658
- const keys = Object.keys(parsed);
19659
- let code = "";
19660
- let defaultObjectCode = "{\n";
19661
- for (const key of keys) {
19662
- if (key === makeLegalIdentifier(key)) {
19663
- code += `export const ${key} = ${serializeValue(parsed[key])};
19389
+ const keys = Object.keys(parsed);
19390
+ let code = "";
19391
+ let defaultObjectCode = "{\n";
19392
+ for (const key of keys) {
19393
+ if (key === makeLegalIdentifier(key)) {
19394
+ code += `export const ${key} = ${serializeValue(parsed[key])};
19664
19395
  `;
19665
- defaultObjectCode += ` ${key},
19396
+ defaultObjectCode += ` ${key},
19666
19397
  `;
19667
- } else {
19668
- defaultObjectCode += ` ${JSON.stringify(key)}: ${serializeValue(parsed[key])},
19398
+ } else {
19399
+ defaultObjectCode += ` ${JSON.stringify(key)}: ${serializeValue(parsed[key])},
19669
19400
  `;
19670
- }
19671
19401
  }
19672
- defaultObjectCode += "}";
19673
- code += `export default ${defaultObjectCode};
19674
- `;
19675
- return {
19676
- code,
19677
- map: { mappings: "" }
19678
- };
19679
19402
  }
19403
+ defaultObjectCode += "}";
19404
+ code += `export default ${defaultObjectCode};
19405
+ `;
19406
+ return {
19407
+ code,
19408
+ map: { mappings: "" }
19409
+ };
19680
19410
  }
19681
19411
  if (options.stringify === true || // use 10kB as a threshold
19682
19412
  // https://v8.dev/blog/cost-of-javascript-2019#:~:text=A%20good%20rule%20of%20thumb%20is%20to%20apply%20this%20technique%20for%20objects%20of%2010%20kB%20or%20larger
@@ -26091,6 +25821,90 @@ function ssrFixStacktrace(e, moduleGraph) {
26091
25821
  rewroteStacktraces.add(e);
26092
25822
  }
26093
25823
 
25824
+ function createHMROptions(environment, options) {
25825
+ if (environment.config.server.hmr === false || options.hmr === false) {
25826
+ return false;
25827
+ }
25828
+ if (!("api" in environment.hot)) return false;
25829
+ return {
25830
+ logger: options.hmr?.logger
25831
+ };
25832
+ }
25833
+ const prepareStackTrace = {
25834
+ retrieveFile(id) {
25835
+ if (existsSync$1(id)) {
25836
+ return readFileSync$1(id, "utf-8");
25837
+ }
25838
+ }
25839
+ };
25840
+ function resolveSourceMapOptions(options) {
25841
+ if (options.sourcemapInterceptor != null) {
25842
+ if (options.sourcemapInterceptor === "prepareStackTrace") {
25843
+ return prepareStackTrace;
25844
+ }
25845
+ if (typeof options.sourcemapInterceptor === "object") {
25846
+ return { ...prepareStackTrace, ...options.sourcemapInterceptor };
25847
+ }
25848
+ return options.sourcemapInterceptor;
25849
+ }
25850
+ if (typeof process !== "undefined" && "setSourceMapsEnabled" in process) {
25851
+ return "node";
25852
+ }
25853
+ return prepareStackTrace;
25854
+ }
25855
+ const createServerModuleRunnerTransport = (options) => {
25856
+ const hmrClient = {
25857
+ send: (payload) => {
25858
+ if (payload.type !== "custom") {
25859
+ throw new Error(
25860
+ "Cannot send non-custom events from the client to the server."
25861
+ );
25862
+ }
25863
+ options.channel.send(payload);
25864
+ }
25865
+ };
25866
+ let handler;
25867
+ return {
25868
+ connect({ onMessage }) {
25869
+ options.channel.api.outsideEmitter.on("send", onMessage);
25870
+ onMessage({ type: "connected" });
25871
+ handler = onMessage;
25872
+ },
25873
+ disconnect() {
25874
+ if (handler) {
25875
+ options.channel.api.outsideEmitter.off("send", handler);
25876
+ }
25877
+ },
25878
+ send(payload) {
25879
+ if (payload.type !== "custom") {
25880
+ throw new Error(
25881
+ "Cannot send non-custom events from the server to the client."
25882
+ );
25883
+ }
25884
+ options.channel.api.innerEmitter.emit(
25885
+ payload.event,
25886
+ payload.data,
25887
+ hmrClient
25888
+ );
25889
+ }
25890
+ };
25891
+ };
25892
+ function createServerModuleRunner(environment, options = {}) {
25893
+ const hmr = createHMROptions(environment, options);
25894
+ return new ModuleRunner(
25895
+ {
25896
+ ...options,
25897
+ root: environment.config.root,
25898
+ transport: createServerModuleRunnerTransport({
25899
+ channel: environment.hot
25900
+ }),
25901
+ hmr,
25902
+ sourcemapInterceptor: resolveSourceMapOptions(options)
25903
+ },
25904
+ options.evaluator || new ESModulesEvaluator()
25905
+ );
25906
+ }
25907
+
26094
25908
  async function ssrLoadModule(url, server, fixStacktrace) {
26095
25909
  const environment = server.environments.ssr;
26096
25910
  server._ssrCompatModuleRunner ||= new SSRCompatModuleRunner(environment);
@@ -26131,9 +25945,9 @@ class SSRCompatModuleRunner extends ModuleRunner {
26131
25945
  super(
26132
25946
  {
26133
25947
  root: environment.config.root,
26134
- transport: {
26135
- fetchModule: (id, importer, options) => environment.fetchModule(id, importer, options)
26136
- },
25948
+ transport: createServerModuleRunnerTransport({
25949
+ channel: environment.hot
25950
+ }),
26137
25951
  sourcemapInterceptor: false,
26138
25952
  hmr: false
26139
25953
  },
@@ -33199,6 +33013,14 @@ function createWebSocketServer(server, config, httpsOptions) {
33199
33013
  },
33200
33014
  on: noop$2,
33201
33015
  off: noop$2,
33016
+ setInvokeHandler: noop$2,
33017
+ handleInvoke: async () => ({
33018
+ e: {
33019
+ name: "TransportError",
33020
+ message: "handleInvoke not implemented",
33021
+ stack: new Error().stack
33022
+ }
33023
+ }),
33202
33024
  listen: noop$2,
33203
33025
  send: noop$2
33204
33026
  };
@@ -33290,7 +33112,9 @@ ${e.stack || e.message}`),
33290
33112
  const listeners = customListeners.get(parsed.event);
33291
33113
  if (!listeners?.size) return;
33292
33114
  const client = getSocketClient(socket);
33293
- listeners.forEach((listener) => listener(parsed.data, client));
33115
+ listeners.forEach(
33116
+ (listener) => listener(parsed.data, client, parsed.invoke)
33117
+ );
33294
33118
  });
33295
33119
  socket.on("error", (err) => {
33296
33120
  config.logger.error(`${colors.red(`ws error:`)}
@@ -33322,17 +33146,7 @@ ${e.stack || e.message}`),
33322
33146
  function getSocketClient(socket) {
33323
33147
  if (!clientsMap.has(socket)) {
33324
33148
  clientsMap.set(socket, {
33325
- send: (...args) => {
33326
- let payload;
33327
- if (typeof args[0] === "string") {
33328
- payload = {
33329
- type: "custom",
33330
- event: args[0],
33331
- data: args[1]
33332
- };
33333
- } else {
33334
- payload = args[0];
33335
- }
33149
+ send: (payload) => {
33336
33150
  socket.send(JSON.stringify(payload));
33337
33151
  },
33338
33152
  socket
@@ -33341,78 +33155,84 @@ ${e.stack || e.message}`),
33341
33155
  return clientsMap.get(socket);
33342
33156
  }
33343
33157
  let bufferedError = null;
33344
- return {
33345
- [isWebSocketServer]: true,
33346
- listen: () => {
33347
- wsHttpServer?.listen(port, host);
33348
- },
33349
- on: (event, fn) => {
33350
- if (wsServerEvents.includes(event)) wss.on(event, fn);
33351
- else {
33158
+ const normalizedHotChannel = normalizeHotChannel(
33159
+ {
33160
+ send(payload) {
33161
+ if (payload.type === "error" && !wss.clients.size) {
33162
+ bufferedError = payload;
33163
+ return;
33164
+ }
33165
+ const stringified = JSON.stringify(payload);
33166
+ wss.clients.forEach((client) => {
33167
+ if (client.readyState === 1) {
33168
+ client.send(stringified);
33169
+ }
33170
+ });
33171
+ },
33172
+ on(event, fn) {
33352
33173
  if (!customListeners.has(event)) {
33353
33174
  customListeners.set(event, /* @__PURE__ */ new Set());
33354
33175
  }
33355
33176
  customListeners.get(event).add(fn);
33177
+ },
33178
+ off(event, fn) {
33179
+ customListeners.get(event)?.delete(fn);
33180
+ },
33181
+ listen() {
33182
+ wsHttpServer?.listen(port, host);
33183
+ },
33184
+ close() {
33185
+ if (hmrServerWsListener && wsServer) {
33186
+ wsServer.off("upgrade", hmrServerWsListener);
33187
+ }
33188
+ return new Promise((resolve, reject) => {
33189
+ wss.clients.forEach((client) => {
33190
+ client.terminate();
33191
+ });
33192
+ wss.close((err) => {
33193
+ if (err) {
33194
+ reject(err);
33195
+ } else {
33196
+ if (wsHttpServer) {
33197
+ wsHttpServer.close((err2) => {
33198
+ if (err2) {
33199
+ reject(err2);
33200
+ } else {
33201
+ resolve();
33202
+ }
33203
+ });
33204
+ } else {
33205
+ resolve();
33206
+ }
33207
+ }
33208
+ });
33209
+ });
33210
+ }
33211
+ },
33212
+ config.server.hmr !== false
33213
+ );
33214
+ return {
33215
+ ...normalizedHotChannel,
33216
+ on: (event, fn) => {
33217
+ if (wsServerEvents.includes(event)) {
33218
+ wss.on(event, fn);
33219
+ return;
33356
33220
  }
33221
+ normalizedHotChannel.on(event, fn);
33357
33222
  },
33358
33223
  off: (event, fn) => {
33359
33224
  if (wsServerEvents.includes(event)) {
33360
33225
  wss.off(event, fn);
33361
- } else {
33362
- customListeners.get(event)?.delete(fn);
33226
+ return;
33363
33227
  }
33228
+ normalizedHotChannel.off(event, fn);
33364
33229
  },
33230
+ async close() {
33231
+ await normalizedHotChannel.close();
33232
+ },
33233
+ [isWebSocketServer]: true,
33365
33234
  get clients() {
33366
33235
  return new Set(Array.from(wss.clients).map(getSocketClient));
33367
- },
33368
- send(...args) {
33369
- let payload;
33370
- if (typeof args[0] === "string") {
33371
- payload = {
33372
- type: "custom",
33373
- event: args[0],
33374
- data: args[1]
33375
- };
33376
- } else {
33377
- payload = args[0];
33378
- }
33379
- if (payload.type === "error" && !wss.clients.size) {
33380
- bufferedError = payload;
33381
- return;
33382
- }
33383
- const stringified = JSON.stringify(payload);
33384
- wss.clients.forEach((client) => {
33385
- if (client.readyState === 1) {
33386
- client.send(stringified);
33387
- }
33388
- });
33389
- },
33390
- close() {
33391
- if (hmrServerWsListener && wsServer) {
33392
- wsServer.off("upgrade", hmrServerWsListener);
33393
- }
33394
- return new Promise((resolve, reject) => {
33395
- wss.clients.forEach((client) => {
33396
- client.terminate();
33397
- });
33398
- wss.close((err) => {
33399
- if (err) {
33400
- reject(err);
33401
- } else {
33402
- if (wsHttpServer) {
33403
- wsHttpServer.close((err2) => {
33404
- if (err2) {
33405
- reject(err2);
33406
- } else {
33407
- resolve();
33408
- }
33409
- });
33410
- } else {
33411
- resolve();
33412
- }
33413
- }
33414
- });
33415
- });
33416
33236
  }
33417
33237
  };
33418
33238
  }
@@ -35791,7 +35611,7 @@ function doesProxyContextMatchUrl(context, url) {
35791
35611
  }
35792
35612
 
35793
35613
  const debug$4 = createDebugger("vite:html-fallback");
35794
- function htmlFallbackMiddleware(root, spaFallback, fsUtils = commonFsUtils) {
35614
+ function htmlFallbackMiddleware(root, spaFallback) {
35795
35615
  return function viteHtmlFallbackMiddleware(req, _res, next) {
35796
35616
  if (
35797
35617
  // Only accept GET or HEAD
@@ -35807,14 +35627,14 @@ function htmlFallbackMiddleware(root, spaFallback, fsUtils = commonFsUtils) {
35807
35627
  const pathname = decodeURIComponent(url);
35808
35628
  if (pathname.endsWith(".html")) {
35809
35629
  const filePath = path.join(root, pathname);
35810
- if (fsUtils.existsSync(filePath)) {
35630
+ if (fs__default.existsSync(filePath)) {
35811
35631
  debug$4?.(`Rewriting ${req.method} ${req.url} to ${url}`);
35812
35632
  req.url = url;
35813
35633
  return next();
35814
35634
  }
35815
35635
  } else if (pathname[pathname.length - 1] === "/") {
35816
35636
  const filePath = path.join(root, pathname, "index.html");
35817
- if (fsUtils.existsSync(filePath)) {
35637
+ if (fs__default.existsSync(filePath)) {
35818
35638
  const newUrl = url + "index.html";
35819
35639
  debug$4?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
35820
35640
  req.url = newUrl;
@@ -35822,7 +35642,7 @@ function htmlFallbackMiddleware(root, spaFallback, fsUtils = commonFsUtils) {
35822
35642
  }
35823
35643
  } else {
35824
35644
  const filePath = path.join(root, pathname + ".html");
35825
- if (fsUtils.existsSync(filePath)) {
35645
+ if (fs__default.existsSync(filePath)) {
35826
35646
  const newUrl = url + ".html";
35827
35647
  debug$4?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
35828
35648
  req.url = newUrl;
@@ -36743,6 +36563,108 @@ async function handleModuleSoftInvalidation(environment, mod, timestamp) {
36743
36563
  return result;
36744
36564
  }
36745
36565
 
36566
+ const ALLOWED_META_NAME = [
36567
+ "msapplication-tileimage",
36568
+ "msapplication-square70x70logo",
36569
+ "msapplication-square150x150logo",
36570
+ "msapplication-wide310x150logo",
36571
+ "msapplication-square310x310logo",
36572
+ "msapplication-config",
36573
+ "twitter:image"
36574
+ ];
36575
+ const ALLOWED_META_PROPERTY = [
36576
+ "og:image",
36577
+ "og:image:url",
36578
+ "og:image:secure_url",
36579
+ "og:audio",
36580
+ "og:audio:secure_url",
36581
+ "og:video",
36582
+ "og:video:secure_url"
36583
+ ];
36584
+ const DEFAULT_HTML_ASSET_SOURCES = {
36585
+ audio: {
36586
+ srcAttributes: ["src"]
36587
+ },
36588
+ embed: {
36589
+ srcAttributes: ["src"]
36590
+ },
36591
+ img: {
36592
+ srcAttributes: ["src"],
36593
+ srcsetAttributes: ["srcset"]
36594
+ },
36595
+ image: {
36596
+ srcAttributes: ["href", "xlink:href"]
36597
+ },
36598
+ input: {
36599
+ srcAttributes: ["src"]
36600
+ },
36601
+ link: {
36602
+ srcAttributes: ["href"],
36603
+ srcsetAttributes: ["imagesrcset"]
36604
+ },
36605
+ object: {
36606
+ srcAttributes: ["data"]
36607
+ },
36608
+ source: {
36609
+ srcAttributes: ["src"],
36610
+ srcsetAttributes: ["srcset"]
36611
+ },
36612
+ track: {
36613
+ srcAttributes: ["src"]
36614
+ },
36615
+ use: {
36616
+ srcAttributes: ["href", "xlink:href"]
36617
+ },
36618
+ video: {
36619
+ srcAttributes: ["src", "poster"]
36620
+ },
36621
+ meta: {
36622
+ srcAttributes: ["content"],
36623
+ filter({ attributes }) {
36624
+ if (attributes.name && ALLOWED_META_NAME.includes(attributes.name.trim().toLowerCase())) {
36625
+ return true;
36626
+ }
36627
+ if (attributes.property && ALLOWED_META_PROPERTY.includes(attributes.property.trim().toLowerCase())) {
36628
+ return true;
36629
+ }
36630
+ return false;
36631
+ }
36632
+ }
36633
+ };
36634
+ function getNodeAssetAttributes(node) {
36635
+ const matched = DEFAULT_HTML_ASSET_SOURCES[node.nodeName];
36636
+ if (!matched) return [];
36637
+ const attributes = {};
36638
+ for (const attr of node.attrs) {
36639
+ attributes[getAttrKey(attr)] = attr.value;
36640
+ }
36641
+ if ("vite-ignore" in attributes) {
36642
+ return [
36643
+ {
36644
+ type: "remove",
36645
+ key: "vite-ignore",
36646
+ value: "",
36647
+ attributes,
36648
+ location: node.sourceCodeLocation.attrs["vite-ignore"]
36649
+ }
36650
+ ];
36651
+ }
36652
+ const actions = [];
36653
+ function handleAttributeKey(key, type) {
36654
+ const value = attributes[key];
36655
+ if (!value) return;
36656
+ if (matched.filter && !matched.filter({ key, value, attributes })) return;
36657
+ const location = node.sourceCodeLocation.attrs[key];
36658
+ actions.push({ type, key, value, attributes, location });
36659
+ }
36660
+ matched.srcAttributes?.forEach((key) => handleAttributeKey(key, "src"));
36661
+ matched.srcsetAttributes?.forEach((key) => handleAttributeKey(key, "srcset"));
36662
+ return actions;
36663
+ }
36664
+ function getAttrKey(attr) {
36665
+ return attr.prefix === void 0 ? attr.name : `${attr.prefix}:${attr.name}`;
36666
+ }
36667
+
36746
36668
  const modulePreloadPolyfillId = "vite/modulepreload-polyfill";
36747
36669
  const resolvedModulePreloadPolyfillId = "\0" + modulePreloadPolyfillId + ".js";
36748
36670
  function modulePreloadPolyfillPlugin(config) {
@@ -36859,14 +36781,6 @@ function addToHTMLProxyCache(config, filePath, index, result) {
36859
36781
  function addToHTMLProxyTransformResult(hash, code) {
36860
36782
  htmlProxyResult.set(hash, code);
36861
36783
  }
36862
- const assetAttrsConfig = {
36863
- link: ["href"],
36864
- video: ["src", "poster"],
36865
- source: ["src", "srcset"],
36866
- img: ["src", "srcset"],
36867
- image: ["xlink:href", "href"],
36868
- use: ["xlink:href", "href"]
36869
- };
36870
36784
  const noInlineLinkRels = /* @__PURE__ */ new Set([
36871
36785
  "icon",
36872
36786
  "apple-touch-icon",
@@ -37120,84 +37034,69 @@ import "${id}?html-proxy&index=${inlineModuleIndex}.js"`;
37120
37034
  }
37121
37035
  }
37122
37036
  }
37123
- const assetAttrs = assetAttrsConfig[node.nodeName];
37124
- if (assetAttrs) {
37125
- const nodeAttrs = {};
37126
- for (const attr of node.attrs) {
37127
- nodeAttrs[getAttrKey(attr)] = attr.value;
37128
- }
37129
- const shouldIgnore = node.nodeName === "link" && "vite-ignore" in nodeAttrs;
37130
- if (shouldIgnore) {
37131
- removeViteIgnoreAttr(s, node.sourceCodeLocation);
37132
- } else {
37133
- for (const attrKey in nodeAttrs) {
37134
- const attrValue = nodeAttrs[attrKey];
37135
- if (attrValue && assetAttrs.includes(attrKey)) {
37136
- if (attrKey === "srcset") {
37137
- assetUrlsPromises.push(
37138
- (async () => {
37139
- const processedEncodedUrl = await processSrcSet(
37140
- attrValue,
37141
- async ({ url }) => {
37142
- const decodedUrl = decodeURI(url);
37143
- if (!isExcludedUrl(decodedUrl)) {
37144
- const result = await processAssetUrl(url);
37145
- return result !== decodedUrl ? encodeURIPath(result) : url;
37146
- }
37147
- return url;
37148
- }
37149
- );
37150
- if (processedEncodedUrl !== attrValue) {
37151
- overwriteAttrValue(
37152
- s,
37153
- getAttrSourceCodeLocation(node, attrKey),
37154
- processedEncodedUrl
37155
- );
37156
- }
37157
- })()
37158
- );
37159
- } else {
37160
- const url = decodeURI(attrValue);
37161
- if (checkPublicFile(url, config)) {
37162
- overwriteAttrValue(
37163
- s,
37164
- getAttrSourceCodeLocation(node, attrKey),
37165
- partialEncodeURIPath(toOutputPublicFilePath(url))
37166
- );
37167
- } else if (!isExcludedUrl(url)) {
37168
- if (node.nodeName === "link" && isCSSRequest(url) && // should not be converted if following attributes are present (#6748)
37169
- !("media" in nodeAttrs || "disabled" in nodeAttrs)) {
37170
- const importExpression = `
37171
- import ${JSON.stringify(url)}`;
37172
- styleUrls.push({
37173
- url,
37174
- start: nodeStartWithLeadingWhitespace(node),
37175
- end: node.sourceCodeLocation.endOffset
37176
- });
37177
- js += importExpression;
37178
- } else {
37179
- const isNoInlineLink = node.nodeName === "link" && nodeAttrs.rel && parseRelAttr(nodeAttrs.rel).some(
37180
- (v) => noInlineLinkRels.has(v)
37181
- );
37182
- const shouldInline = isNoInlineLink ? false : void 0;
37183
- assetUrlsPromises.push(
37184
- (async () => {
37185
- const processedUrl = await processAssetUrl(
37186
- url,
37187
- shouldInline
37188
- );
37189
- if (processedUrl !== url) {
37190
- overwriteAttrValue(
37191
- s,
37192
- getAttrSourceCodeLocation(node, attrKey),
37193
- partialEncodeURIPath(processedUrl)
37194
- );
37195
- }
37196
- })()
37197
- );
37037
+ const assetAttributes = getNodeAssetAttributes(node);
37038
+ for (const attr of assetAttributes) {
37039
+ if (attr.type === "remove") {
37040
+ s.remove(attr.location.startOffset, attr.location.endOffset);
37041
+ continue;
37042
+ } else if (attr.type === "srcset") {
37043
+ assetUrlsPromises.push(
37044
+ (async () => {
37045
+ const processedEncodedUrl = await processSrcSet(
37046
+ attr.value,
37047
+ async ({ url }) => {
37048
+ const decodedUrl = decodeURI(url);
37049
+ if (!isExcludedUrl(decodedUrl)) {
37050
+ const result = await processAssetUrl(url);
37051
+ return result !== decodedUrl ? encodeURIPath(result) : url;
37198
37052
  }
37053
+ return url;
37199
37054
  }
37055
+ );
37056
+ if (processedEncodedUrl !== attr.value) {
37057
+ overwriteAttrValue(s, attr.location, processedEncodedUrl);
37200
37058
  }
37059
+ })()
37060
+ );
37061
+ } else if (attr.type === "src") {
37062
+ const url = decodeURI(attr.value);
37063
+ if (checkPublicFile(url, config)) {
37064
+ overwriteAttrValue(
37065
+ s,
37066
+ attr.location,
37067
+ partialEncodeURIPath(toOutputPublicFilePath(url))
37068
+ );
37069
+ } else if (!isExcludedUrl(url)) {
37070
+ if (node.nodeName === "link" && isCSSRequest(url) && // should not be converted if following attributes are present (#6748)
37071
+ !("media" in attr.attributes || "disabled" in attr.attributes)) {
37072
+ const importExpression = `
37073
+ import ${JSON.stringify(url)}`;
37074
+ styleUrls.push({
37075
+ url,
37076
+ start: nodeStartWithLeadingWhitespace(node),
37077
+ end: node.sourceCodeLocation.endOffset
37078
+ });
37079
+ js += importExpression;
37080
+ } else {
37081
+ const isNoInlineLink = node.nodeName === "link" && attr.attributes.rel && parseRelAttr(attr.attributes.rel).some(
37082
+ (v) => noInlineLinkRels.has(v)
37083
+ );
37084
+ const shouldInline = isNoInlineLink ? false : void 0;
37085
+ assetUrlsPromises.push(
37086
+ (async () => {
37087
+ const processedUrl = await processAssetUrl(
37088
+ url,
37089
+ shouldInline
37090
+ );
37091
+ if (processedUrl !== url) {
37092
+ overwriteAttrValue(
37093
+ s,
37094
+ attr.location,
37095
+ partialEncodeURIPath(processedUrl)
37096
+ );
37097
+ }
37098
+ })()
37099
+ );
37201
37100
  }
37202
37101
  }
37203
37102
  }
@@ -37868,12 +37767,6 @@ function serializeAttrs(attrs) {
37868
37767
  function incrementIndent(indent = "") {
37869
37768
  return `${indent}${indent[0] === " " ? " " : " "}`;
37870
37769
  }
37871
- function getAttrKey(attr) {
37872
- return attr.prefix === void 0 ? attr.name : `${attr.prefix}:${attr.name}`;
37873
- }
37874
- function getAttrSourceCodeLocation(node, attrKey) {
37875
- return node.sourceCodeLocation.attrs[attrKey];
37876
- }
37877
37770
 
37878
37771
  const debugCache = createDebugger("vite:cache");
37879
37772
  const knownIgnoreList = /* @__PURE__ */ new Set(["/", "/favicon.ico"]);
@@ -38156,7 +38049,7 @@ const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl
38156
38049
  let proxyModulePath;
38157
38050
  let proxyModuleUrl;
38158
38051
  const trailingSlash = htmlPath.endsWith("/");
38159
- if (!trailingSlash && getFsUtils(config).existsSync(filename)) {
38052
+ if (!trailingSlash && fs__default.existsSync(filename)) {
38160
38053
  proxyModulePath = htmlPath;
38161
38054
  proxyModuleUrl = proxyModulePath;
38162
38055
  } else {
@@ -38210,7 +38103,8 @@ const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl
38210
38103
  } else if (src) {
38211
38104
  const processedUrl = processNodeUrl(
38212
38105
  src.value,
38213
- getAttrKey(src) === "srcset",
38106
+ /* useSrcSetReplacer */
38107
+ false,
38214
38108
  config,
38215
38109
  htmlPath,
38216
38110
  originalUrl,
@@ -38259,34 +38153,20 @@ const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl
38259
38153
  code: children.value
38260
38154
  });
38261
38155
  }
38262
- const assetAttrs = assetAttrsConfig[node.nodeName];
38263
- if (assetAttrs) {
38264
- const nodeAttrs = {};
38265
- for (const attr of node.attrs) {
38266
- nodeAttrs[getAttrKey(attr)] = attr.value;
38267
- }
38268
- const shouldIgnore = node.nodeName === "link" && "vite-ignore" in nodeAttrs;
38269
- if (shouldIgnore) {
38270
- removeViteIgnoreAttr(s, node.sourceCodeLocation);
38156
+ const assetAttributes = getNodeAssetAttributes(node);
38157
+ for (const attr of assetAttributes) {
38158
+ if (attr.type === "remove") {
38159
+ s.remove(attr.location.startOffset, attr.location.endOffset);
38271
38160
  } else {
38272
- for (const attrKey in nodeAttrs) {
38273
- const attrValue = nodeAttrs[attrKey];
38274
- if (attrValue && assetAttrs.includes(attrKey)) {
38275
- const processedUrl = processNodeUrl(
38276
- attrValue,
38277
- attrKey === "srcset",
38278
- config,
38279
- htmlPath,
38280
- originalUrl
38281
- );
38282
- if (processedUrl !== attrValue) {
38283
- overwriteAttrValue(
38284
- s,
38285
- node.sourceCodeLocation.attrs[attrKey],
38286
- processedUrl
38287
- );
38288
- }
38289
- }
38161
+ const processedUrl = processNodeUrl(
38162
+ attr.value,
38163
+ attr.type === "srcset",
38164
+ config,
38165
+ htmlPath,
38166
+ originalUrl
38167
+ );
38168
+ if (processedUrl !== attr.value) {
38169
+ overwriteAttrValue(s, attr.location, processedUrl);
38290
38170
  }
38291
38171
  }
38292
38172
  }
@@ -38351,7 +38231,6 @@ const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl
38351
38231
  };
38352
38232
  function indexHtmlMiddleware(root, server) {
38353
38233
  const isDev = isDevServer(server);
38354
- const fsUtils = getFsUtils(server.config);
38355
38234
  return async function viteIndexHtmlMiddleware(req, res, next) {
38356
38235
  if (res.writableEnded) {
38357
38236
  return next();
@@ -38364,7 +38243,7 @@ function indexHtmlMiddleware(root, server) {
38364
38243
  } else {
38365
38244
  filePath = path.join(root, decodeURIComponent(url));
38366
38245
  }
38367
- if (fsUtils.existsSync(filePath)) {
38246
+ if (fs__default.existsSync(filePath)) {
38368
38247
  const headers = isDev ? server.config.server.headers : server.config.preview.headers;
38369
38248
  try {
38370
38249
  let html = await fsp.readFile(filePath, "utf-8");
@@ -39044,7 +38923,8 @@ async function _createServer(inlineConfig = {}, options) {
39044
38923
  }
39045
38924
  const watcher = chokidar.watch(
39046
38925
  // config file dependencies and env file might be outside of root
39047
- [
38926
+ // eslint-disable-next-line eqeqeq -- null means disabled
38927
+ serverConfig.watch === null ? [] : [
39048
38928
  root,
39049
38929
  ...config.configFileDependencies,
39050
38930
  ...getEnvFilesForMode(config.mode, config.envDir),
@@ -39058,6 +38938,7 @@ async function _createServer(inlineConfig = {}, options) {
39058
38938
  watcher.add = function() {
39059
38939
  return this;
39060
38940
  };
38941
+ await watcher.close();
39061
38942
  }
39062
38943
  const environments = {};
39063
38944
  for (const [name, environmentOptions] of Object.entries(
@@ -39315,7 +39196,6 @@ async function _createServer(inlineConfig = {}, options) {
39315
39196
  }
39316
39197
  await onHMRUpdate("update", file);
39317
39198
  });
39318
- getFsUtils(config).initWatcher?.(watcher);
39319
39199
  watcher.on("add", (file) => {
39320
39200
  onFileAddUnlink(file, false);
39321
39201
  });
@@ -39362,13 +39242,7 @@ async function _createServer(inlineConfig = {}, options) {
39362
39242
  middlewares.use(serveRawFsMiddleware(server));
39363
39243
  middlewares.use(serveStaticMiddleware(server));
39364
39244
  if (config.appType === "spa" || config.appType === "mpa") {
39365
- middlewares.use(
39366
- htmlFallbackMiddleware(
39367
- root,
39368
- config.appType === "spa",
39369
- getFsUtils(config)
39370
- )
39371
- );
39245
+ middlewares.use(htmlFallbackMiddleware(root, config.appType === "spa"));
39372
39246
  }
39373
39247
  postHooks.forEach((fn) => fn && fn());
39374
39248
  if (config.appType === "spa" || config.appType === "mpa") {
@@ -39501,8 +39375,7 @@ function resolveServerOptions(root, raw, logger) {
39501
39375
  server.fs = {
39502
39376
  strict: server.fs?.strict ?? true,
39503
39377
  allow: allowDirs,
39504
- deny,
39505
- cachedChecks: server.fs?.cachedChecks
39378
+ deny
39506
39379
  };
39507
39380
  if (server.origin?.endsWith("/")) {
39508
39381
  server.origin = server.origin.slice(0, -1);
@@ -39598,6 +39471,130 @@ const normalizedClientDir = normalizePath$1(CLIENT_DIR);
39598
39471
  function getShortName(file, root) {
39599
39472
  return file.startsWith(withTrailingSlash(root)) ? path.posix.relative(root, file) : file;
39600
39473
  }
39474
+ const normalizeHotChannel = (channel, enableHmr) => {
39475
+ const normalizedListenerMap = /* @__PURE__ */ new WeakMap();
39476
+ const listenersForEvents = /* @__PURE__ */ new Map();
39477
+ let invokeHandlers;
39478
+ let listenerForInvokeHandler;
39479
+ const handleInvoke = async (payload) => {
39480
+ if (!invokeHandlers) {
39481
+ return {
39482
+ e: {
39483
+ name: "TransportError",
39484
+ message: "invokeHandlers is not set",
39485
+ stack: new Error().stack
39486
+ }
39487
+ };
39488
+ }
39489
+ const data = payload.data;
39490
+ const { name, data: args } = data;
39491
+ try {
39492
+ const invokeHandler = invokeHandlers[name];
39493
+ const result = await invokeHandler(...args);
39494
+ return { r: result };
39495
+ } catch (error2) {
39496
+ return {
39497
+ e: {
39498
+ name: error2.name,
39499
+ message: error2.message,
39500
+ stack: error2.stack
39501
+ }
39502
+ };
39503
+ }
39504
+ };
39505
+ return {
39506
+ ...channel,
39507
+ on: (event, fn) => {
39508
+ if (event === "connection") {
39509
+ channel.on?.(event, fn);
39510
+ return;
39511
+ }
39512
+ const listenerWithNormalizedClient = (data, client) => {
39513
+ const normalizedClient = {
39514
+ send: (...args) => {
39515
+ let payload;
39516
+ if (typeof args[0] === "string") {
39517
+ payload = {
39518
+ type: "custom",
39519
+ event: args[0],
39520
+ data: args[1]
39521
+ };
39522
+ } else {
39523
+ payload = args[0];
39524
+ }
39525
+ client.send(payload);
39526
+ }
39527
+ };
39528
+ fn(data, normalizedClient);
39529
+ };
39530
+ normalizedListenerMap.set(fn, listenerWithNormalizedClient);
39531
+ channel.on?.(event, listenerWithNormalizedClient);
39532
+ if (!listenersForEvents.has(event)) {
39533
+ listenersForEvents.set(event, /* @__PURE__ */ new Set());
39534
+ }
39535
+ listenersForEvents.get(event).add(listenerWithNormalizedClient);
39536
+ },
39537
+ off: (event, fn) => {
39538
+ if (event === "connection") {
39539
+ channel.off?.(event, fn);
39540
+ return;
39541
+ }
39542
+ const normalizedListener = normalizedListenerMap.get(fn);
39543
+ if (normalizedListener) {
39544
+ channel.off?.(event, normalizedListener);
39545
+ listenersForEvents.get(event)?.delete(normalizedListener);
39546
+ }
39547
+ },
39548
+ setInvokeHandler(_invokeHandlers) {
39549
+ invokeHandlers = _invokeHandlers;
39550
+ if (!_invokeHandlers) {
39551
+ if (listenerForInvokeHandler) {
39552
+ channel.off?.("vite:invoke", listenerForInvokeHandler);
39553
+ }
39554
+ return;
39555
+ }
39556
+ listenerForInvokeHandler = async (payload, client) => {
39557
+ const responseInvoke = payload.id.replace("send", "response");
39558
+ client.send({
39559
+ type: "custom",
39560
+ event: "vite:invoke",
39561
+ data: {
39562
+ name: payload.name,
39563
+ id: responseInvoke,
39564
+ data: await handleInvoke({
39565
+ type: "custom",
39566
+ event: "vite:invoke",
39567
+ data: payload
39568
+ })
39569
+ }
39570
+ });
39571
+ };
39572
+ channel.on?.("vite:invoke", listenerForInvokeHandler);
39573
+ },
39574
+ handleInvoke,
39575
+ send: (...args) => {
39576
+ let payload;
39577
+ if (typeof args[0] === "string") {
39578
+ payload = {
39579
+ type: "custom",
39580
+ event: args[0],
39581
+ data: args[1]
39582
+ };
39583
+ } else {
39584
+ payload = args[0];
39585
+ }
39586
+ if (enableHmr || payload.type === "connected" || payload.type === "ping" || payload.type === "custom" || payload.type === "error") {
39587
+ channel.send?.(payload);
39588
+ }
39589
+ },
39590
+ listen() {
39591
+ return channel.listen?.();
39592
+ },
39593
+ close() {
39594
+ return channel.close?.();
39595
+ }
39596
+ };
39597
+ };
39601
39598
  function getSortedPluginsByHotUpdateHook(plugins) {
39602
39599
  const sortedPlugins = [];
39603
39600
  let pre = 0, normal = 0, post = 0;
@@ -40141,17 +40138,7 @@ function createServerHotChannel() {
40141
40138
  const innerEmitter = new EventEmitter$1();
40142
40139
  const outsideEmitter = new EventEmitter$1();
40143
40140
  return {
40144
- send(...args) {
40145
- let payload;
40146
- if (typeof args[0] === "string") {
40147
- payload = {
40148
- type: "custom",
40149
- event: args[0],
40150
- data: args[1]
40151
- };
40152
- } else {
40153
- payload = args[0];
40154
- }
40141
+ send(payload) {
40155
40142
  outsideEmitter.emit("send", payload);
40156
40143
  },
40157
40144
  off(event, listener) {
@@ -40173,23 +40160,20 @@ function createServerHotChannel() {
40173
40160
  }
40174
40161
  };
40175
40162
  }
40176
- function createNoopHotChannel() {
40177
- function noop() {
40178
- }
40179
- return {
40180
- send: noop,
40181
- on: noop,
40182
- off: noop,
40183
- listen: noop,
40184
- close: noop
40185
- };
40186
- }
40187
40163
  function createDeprecatedHotBroadcaster(ws) {
40188
40164
  const broadcaster = {
40189
40165
  on: ws.on,
40190
40166
  off: ws.off,
40191
40167
  listen: ws.listen,
40192
40168
  send: ws.send,
40169
+ setInvokeHandler: ws.setInvokeHandler,
40170
+ handleInvoke: async () => ({
40171
+ e: {
40172
+ name: "TransportError",
40173
+ message: "handleInvoke not implemented",
40174
+ stack: new Error().stack
40175
+ }
40176
+ }),
40193
40177
  get channels() {
40194
40178
  return [ws];
40195
40179
  },
@@ -40197,7 +40181,9 @@ function createDeprecatedHotBroadcaster(ws) {
40197
40181
  return broadcaster;
40198
40182
  },
40199
40183
  close() {
40200
- return Promise.all(broadcaster.channels.map((channel) => channel.close()));
40184
+ return Promise.all(
40185
+ broadcaster.channels.map((channel) => channel.close?.())
40186
+ );
40201
40187
  }
40202
40188
  };
40203
40189
  return broadcaster;
@@ -40236,6 +40222,7 @@ function definePlugin(config) {
40236
40222
  importMetaFallbackKeys["import.meta.env"] = `undefined`;
40237
40223
  }
40238
40224
  function generatePattern(environment) {
40225
+ const keepProcessEnv = environment.config.keepProcessEnv;
40239
40226
  const userDefine = {};
40240
40227
  const userDefineEnv = {};
40241
40228
  for (const key in environment.config.define) {
@@ -40244,9 +40231,8 @@ function definePlugin(config) {
40244
40231
  userDefineEnv[key.slice(16)] = environment.config.define[key];
40245
40232
  }
40246
40233
  }
40247
- const replaceProcessEnv = environment.config.webCompatible;
40248
40234
  const define = {
40249
- ...replaceProcessEnv ? processEnv : {},
40235
+ ...keepProcessEnv ? {} : processEnv,
40250
40236
  ...importMetaKeys,
40251
40237
  ...userDefine,
40252
40238
  ...importMetaFallbackKeys
@@ -40264,7 +40250,7 @@ function definePlugin(config) {
40264
40250
  ...userDefineEnv
40265
40251
  });
40266
40252
  const patternKeys = Object.keys(userDefine);
40267
- if (replaceProcessEnv && Object.keys(processEnv).length) {
40253
+ if (!keepProcessEnv && Object.keys(processEnv).length) {
40268
40254
  patternKeys.push("process.env");
40269
40255
  }
40270
40256
  if (Object.keys(importMetaKeys).length) {
@@ -40743,7 +40729,6 @@ function isSameContent(a, b) {
40743
40729
  function preAliasPlugin(config) {
40744
40730
  const findPatterns = getAliasPatterns(config.resolve.alias);
40745
40731
  const isBuild = config.command === "build";
40746
- const fsUtils = getFsUtils(config);
40747
40732
  return {
40748
40733
  name: "vite:pre-alias",
40749
40734
  async resolveId(id, importer, options) {
@@ -40770,7 +40755,7 @@ function preAliasPlugin(config) {
40770
40755
  const optimizeDeps = depsOptimizer.options;
40771
40756
  const resolvedId = cleanUrl(resolved.id);
40772
40757
  const isVirtual = resolvedId === id || resolvedId.includes("\0");
40773
- if (!isVirtual && fsUtils.existsSync(resolvedId) && !moduleListContains(optimizeDeps.exclude, id) && path.isAbsolute(resolvedId) && (isInNodeModules$1(resolvedId) || optimizeDeps.include?.includes(id)) && isOptimizable(resolvedId, optimizeDeps) && !(isBuild && ssr && isConfiguredAsExternal(environment, id, importer)) && (!ssr || optimizeAliasReplacementForSSR(resolvedId, optimizeDeps))) {
40758
+ if (!isVirtual && fs__default.existsSync(resolvedId) && !moduleListContains(optimizeDeps.exclude, id) && path.isAbsolute(resolvedId) && (isInNodeModules$1(resolvedId) || optimizeDeps.include?.includes(id)) && isOptimizable(resolvedId, optimizeDeps) && !(isBuild && ssr && isConfiguredAsExternal(environment, id, importer)) && (!ssr || optimizeAliasReplacementForSSR(resolvedId, optimizeDeps))) {
40774
40759
  const optimizedInfo = depsOptimizer.registerMissingImport(
40775
40760
  id,
40776
40761
  resolvedId
@@ -40831,13 +40816,12 @@ function isExplicitImportRequired(url) {
40831
40816
  function normalizeResolvedIdToUrl(environment, url, resolved) {
40832
40817
  const root = environment.config.root;
40833
40818
  const depsOptimizer = environment.depsOptimizer;
40834
- const fsUtils = getFsUtils(environment.getTopLevelConfig());
40835
40819
  if (resolved.id.startsWith(withTrailingSlash(root))) {
40836
40820
  url = resolved.id.slice(root.length);
40837
40821
  } else if (depsOptimizer?.isOptimizedDepFile(resolved.id) || // vite-plugin-react isn't following the leading \0 virtual module convention.
40838
40822
  // This is a temporary hack to avoid expensive fs checks for React apps.
40839
40823
  // We'll remove this as soon we're able to fix the react plugins.
40840
- resolved.id !== "/@react-refresh" && path.isAbsolute(resolved.id) && fsUtils.existsSync(cleanUrl(resolved.id))) {
40824
+ resolved.id !== "/@react-refresh" && path.isAbsolute(resolved.id) && fs__default.existsSync(cleanUrl(resolved.id))) {
40841
40825
  url = path.posix.join(FS_PREFIX, resolved.id);
40842
40826
  } else {
40843
40827
  url = resolved.id;
@@ -41768,7 +41752,7 @@ function assetImportMetaUrlPlugin(config) {
41768
41752
  const templateLiteral = ast.body[0].expression;
41769
41753
  if (templateLiteral.expressions.length) {
41770
41754
  const pattern = buildGlobPattern(templateLiteral);
41771
- if (pattern.startsWith("**")) {
41755
+ if (pattern.startsWith("*")) {
41772
41756
  continue;
41773
41757
  }
41774
41758
  const globOptions = {
@@ -41843,19 +41827,17 @@ ${rawExp} doesn't exist at build time, it will remain unchanged to be resolved a
41843
41827
  }
41844
41828
  function buildGlobPattern(ast) {
41845
41829
  let pattern = "";
41846
- let lastElementIndex = -1;
41847
- for (const exp of ast.expressions) {
41848
- for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) {
41849
- const el = ast.quasis[i];
41850
- if (el.end < exp.start) {
41851
- pattern += el.value.raw;
41852
- lastElementIndex = i;
41853
- }
41830
+ let lastIsGlob = false;
41831
+ for (let i = 0; i < ast.quasis.length; i++) {
41832
+ const str = ast.quasis[i].value.raw;
41833
+ if (str) {
41834
+ pattern += str;
41835
+ lastIsGlob = false;
41836
+ }
41837
+ if (ast.expressions[i] && !lastIsGlob) {
41838
+ pattern += "*";
41839
+ lastIsGlob = true;
41854
41840
  }
41855
- pattern += "**";
41856
- }
41857
- for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) {
41858
- pattern += ast.quasis[i].value.raw;
41859
41841
  }
41860
41842
  return pattern;
41861
41843
  }
@@ -42206,19 +42188,15 @@ async function resolvePlugins(config, prePlugins, normalPlugins, postPlugins) {
42206
42188
  }),
42207
42189
  ...prePlugins,
42208
42190
  modulePreload !== false && modulePreload.polyfill ? modulePreloadPolyfillPlugin(config) : null,
42209
- resolvePlugin(
42210
- {
42211
- root: config.root,
42212
- isProduction: config.isProduction,
42213
- isBuild,
42214
- packageCache: config.packageCache,
42215
- asSrc: true,
42216
- fsUtils: getFsUtils(config),
42217
- optimizeDeps: true,
42218
- externalize: true
42219
- },
42220
- config.environments
42221
- ),
42191
+ resolvePlugin({
42192
+ root: config.root,
42193
+ isProduction: config.isProduction,
42194
+ isBuild,
42195
+ packageCache: config.packageCache,
42196
+ asSrc: true,
42197
+ optimizeDeps: true,
42198
+ externalize: true
42199
+ }),
42222
42200
  htmlInlineProxyPlugin(config),
42223
42201
  cssPlugin(config),
42224
42202
  config.esbuild !== false ? esbuildPlugin(config) : null,
@@ -42466,12 +42444,13 @@ class EnvironmentPluginContainer {
42466
42444
  return;
42467
42445
  }
42468
42446
  this._started = true;
42447
+ const config = this.environment.getTopLevelConfig();
42469
42448
  this._buildStartPromise = this.handleHookPromise(
42470
42449
  this.hookParallel(
42471
42450
  "buildStart",
42472
42451
  (plugin) => this._getPluginContext(plugin),
42473
42452
  () => [this.options],
42474
- (plugin) => this.environment.name === "client" || plugin.perEnvironmentStartEndDuringDev === true
42453
+ (plugin) => this.environment.name === "client" || config.server.perEnvironmentStartEndDuringDev || plugin.perEnvironmentStartEndDuringDev
42475
42454
  )
42476
42455
  );
42477
42456
  await this._buildStartPromise;
@@ -42623,11 +42602,12 @@ class EnvironmentPluginContainer {
42623
42602
  if (this._closed) return;
42624
42603
  this._closed = true;
42625
42604
  await Promise.allSettled(Array.from(this._processesing));
42605
+ const config = this.environment.getTopLevelConfig();
42626
42606
  await this.hookParallel(
42627
42607
  "buildEnd",
42628
42608
  (plugin) => this._getPluginContext(plugin),
42629
42609
  () => [],
42630
- (plugin) => this.environment.name === "client" || plugin.perEnvironmentStartEndDuringDev !== true
42610
+ (plugin) => this.environment.name === "client" || config.server.perEnvironmentStartEndDuringDev || plugin.perEnvironmentStartEndDuringDev
42631
42611
  );
42632
42612
  await this.hookParallel(
42633
42613
  "closeBundle",
@@ -43010,7 +42990,6 @@ function createIdResolver(config, options) {
43010
42990
  preferRelative: false,
43011
42991
  tryIndex: true,
43012
42992
  ...options,
43013
- fsUtils: getFsUtils(config),
43014
42993
  // Ignore sideEffects and other computations as we only need the id
43015
42994
  idOnly: true
43016
42995
  })
@@ -43195,7 +43174,6 @@ function cssPostPlugin(config) {
43195
43174
  let pureCssChunks;
43196
43175
  let hasEmitted = false;
43197
43176
  let chunkCSSMap;
43198
- let cssBundleName;
43199
43177
  const rollupOptionsOutput = config.build.rollupOptions.output;
43200
43178
  const assetFileNames = (Array.isArray(rollupOptionsOutput) ? rollupOptionsOutput[0] : rollupOptionsOutput)?.assetFileNames;
43201
43179
  const getCssAssetDirname = (cssAssetName) => {
@@ -43217,6 +43195,17 @@ function cssPostPlugin(config) {
43217
43195
  );
43218
43196
  }
43219
43197
  };
43198
+ function getCssBundleName() {
43199
+ const cached = cssBundleNameCache.get(config);
43200
+ if (cached) return cached;
43201
+ const cssBundleName = config.build.lib ? resolveLibCssFilename(
43202
+ config.build.lib,
43203
+ config.root,
43204
+ config.packageCache
43205
+ ) : defaultCssBundleName;
43206
+ cssBundleNameCache.set(config, cssBundleName);
43207
+ return cssBundleName;
43208
+ }
43220
43209
  return {
43221
43210
  name: "vite:css-post",
43222
43211
  renderStart() {
@@ -43224,12 +43213,6 @@ function cssPostPlugin(config) {
43224
43213
  hasEmitted = false;
43225
43214
  chunkCSSMap = /* @__PURE__ */ new Map();
43226
43215
  codeSplitEmitQueue = createSerialPromiseQueue();
43227
- cssBundleName = config.build.lib ? resolveLibCssFilename(
43228
- config.build.lib,
43229
- config.root,
43230
- config.packageCache
43231
- ) : defaultCssBundleName;
43232
- cssBundleNameCache.set(config, cssBundleName);
43233
43216
  },
43234
43217
  async transform(css, id) {
43235
43218
  if (!isCSSRequest(id) || commonjsProxyRE.test(id) || SPECIAL_QUERY_RE.test(id)) {
@@ -43495,7 +43478,7 @@ function cssPostPlugin(config) {
43495
43478
  s.appendRight(injectionPoint, injectCode);
43496
43479
  }
43497
43480
  } else {
43498
- chunkCSS = resolveAssetUrlsInCss(chunkCSS, cssBundleName);
43481
+ chunkCSS = resolveAssetUrlsInCss(chunkCSS, getCssBundleName());
43499
43482
  chunkCSSMap.set(chunk.fileName, chunkCSS);
43500
43483
  }
43501
43484
  }
@@ -43524,7 +43507,7 @@ function cssPostPlugin(config) {
43524
43507
  if (opts.__vite_skip_asset_emit__) {
43525
43508
  return;
43526
43509
  }
43527
- if (!config.build.cssCodeSplit && !hasEmitted) {
43510
+ if (!this.environment.config.build.cssCodeSplit && !hasEmitted) {
43528
43511
  let collect2 = function(chunk) {
43529
43512
  if (!chunk || chunk.type !== "chunk" || collected.has(chunk)) return;
43530
43513
  collected.add(chunk);
@@ -43549,7 +43532,7 @@ function cssPostPlugin(config) {
43549
43532
  hasEmitted = true;
43550
43533
  extractedCss = await finalizeCss(extractedCss, true, config);
43551
43534
  this.emitFile({
43552
- name: cssBundleName,
43535
+ name: getCssBundleName(),
43553
43536
  type: "asset",
43554
43537
  source: extractedCss
43555
43538
  });
@@ -43622,9 +43605,9 @@ function cssAnalysisPlugin(config) {
43622
43605
  for (const file of pluginImports) {
43623
43606
  depModules.add(
43624
43607
  isCSSRequest(file) ? moduleGraph.createFileOnlyEntry(file) : await moduleGraph.ensureEntryFromUrl(
43625
- fileToDevUrl(
43608
+ await fileToDevUrl(
43609
+ this.environment,
43626
43610
  file,
43627
- config,
43628
43611
  /* skipBase */
43629
43612
  true
43630
43613
  )
@@ -43669,7 +43652,7 @@ function createCSSResolvers(config) {
43669
43652
  return cssResolve ??= createBackCompatIdResolver(config, {
43670
43653
  extensions: [".css"],
43671
43654
  mainFields: ["style"],
43672
- conditions: ["style"],
43655
+ conditions: ["style", DEV_PROD_CONDITION],
43673
43656
  tryIndex: false,
43674
43657
  preferRelative: true
43675
43658
  });
@@ -43679,7 +43662,7 @@ function createCSSResolvers(config) {
43679
43662
  const resolver = createBackCompatIdResolver(config, {
43680
43663
  extensions: [".scss", ".sass", ".css"],
43681
43664
  mainFields: ["sass", "style"],
43682
- conditions: ["sass", "style"],
43665
+ conditions: ["sass", "style", DEV_PROD_CONDITION],
43683
43666
  tryIndex: true,
43684
43667
  tryPrefix: "_",
43685
43668
  preferRelative: true
@@ -43697,7 +43680,7 @@ function createCSSResolvers(config) {
43697
43680
  return lessResolve ??= createBackCompatIdResolver(config, {
43698
43681
  extensions: [".less", ".css"],
43699
43682
  mainFields: ["less", "style"],
43700
- conditions: ["less", "style"],
43683
+ conditions: ["less", "style", DEV_PROD_CONDITION],
43701
43684
  tryIndex: false,
43702
43685
  preferRelative: true
43703
43686
  });
@@ -43989,8 +43972,8 @@ function createCachedImport(imp) {
43989
43972
  return cached;
43990
43973
  };
43991
43974
  }
43992
- const importPostcssImport = createCachedImport(() => import('./dep-C35rJP-t.js').then(function (n) { return n.i; }));
43993
- const importPostcssModules = createCachedImport(() => import('./dep-BLM335V-.js').then(function (n) { return n.i; }));
43975
+ const importPostcssImport = createCachedImport(() => import('./dep-DIgjieZc.js').then(function (n) { return n.i; }));
43976
+ const importPostcssModules = createCachedImport(() => import('./dep-BLfo3Ie2.js').then(function (n) { return n.i; }));
43994
43977
  const importPostcss = createCachedImport(() => import('postcss'));
43995
43978
  const preprocessorWorkerControllerCache = /* @__PURE__ */ new WeakMap();
43996
43979
  let alwaysFakeWorkerWorkerControllerCache;
@@ -44082,9 +44065,9 @@ ${stack}`;
44082
44065
  postcssConfigCache.set(config, result);
44083
44066
  return result;
44084
44067
  }
44085
- const cssUrlRE = /(?<=^|[^\w\-\u0080-\uffff])url\((\s*('[^']+'|"[^"]+")\s*|[^'")]+)\)/;
44068
+ const cssUrlRE = /(?<!@import\s+)(?<=^|[^\w\-\u0080-\uffff])url\((\s*('[^']+'|"[^"]+")\s*|[^'")]+)\)/;
44086
44069
  const cssDataUriRE = /(?<=^|[^\w\-\u0080-\uffff])data-uri\((\s*('[^']+'|"[^"]+")\s*|[^'")]+)\)/;
44087
- const importCssRE = /@import ('[^']+\.css'|"[^"]+\.css"|[^'")]+\.css)/;
44070
+ const importCssRE = /@import\s+(?:url\()?('[^']+\.css'|"[^"]+\.css"|[^'"\s)]+\.css)/;
44088
44071
  const cssImageSetRE = /(?<=image-set\()((?:[\w-]{1,256}\([^)]*\)|[^)])*)(?=\))/;
44089
44072
  const UrlRewritePostcssPlugin = (opts) => {
44090
44073
  if (!opts) {
@@ -44193,7 +44176,8 @@ async function doImportCSSReplace(rawUrl, matched, replacer) {
44193
44176
  if (isExternalUrl(rawUrl) || isDataUrl(rawUrl) || rawUrl[0] === "#") {
44194
44177
  return matched;
44195
44178
  }
44196
- return `@import ${wrap}${await replacer(rawUrl)}${wrap}`;
44179
+ const prefix = matched.includes("url(") ? "url(" : "";
44180
+ return `@import ${prefix}${wrap}${await replacer(rawUrl)}${wrap}`;
44197
44181
  }
44198
44182
  async function minifyCSS(css, config, inlined) {
44199
44183
  if (config.build.cssMinify === "lightningcss") {
@@ -44631,6 +44615,11 @@ const scssProcessor = (maxWorkers) => {
44631
44615
  e.message = `[sass] ${e.message}`;
44632
44616
  e.id = e.file;
44633
44617
  e.frame = e.formatted;
44618
+ if (e.span?.start) {
44619
+ e.line = e.span.start.line + 1;
44620
+ e.column = e.span.start.column + 1;
44621
+ e.frame = e.message;
44622
+ }
44634
44623
  return { code: "", error: e, deps: [] };
44635
44624
  }
44636
44625
  }
@@ -45780,7 +45769,7 @@ function completeSystemWrapPlugin() {
45780
45769
  };
45781
45770
  }
45782
45771
 
45783
- function resolveBuildEnvironmentOptions(raw, logger, consumer) {
45772
+ function resolveBuildEnvironmentOptions(raw, logger, consumer, isSsrTargetWebworkerEnvironment) {
45784
45773
  const deprecatedPolyfillModulePreload = raw?.polyfillModulePreload;
45785
45774
  const { polyfillModulePreload, ...rest } = raw;
45786
45775
  raw = rest;
@@ -45854,6 +45843,17 @@ function resolveBuildEnvironmentOptions(raw, logger, consumer) {
45854
45843
  if (resolved.cssMinify == null) {
45855
45844
  resolved.cssMinify = consumer === "server" ? "esbuild" : !!resolved.minify;
45856
45845
  }
45846
+ if (isSsrTargetWebworkerEnvironment) {
45847
+ resolved.rollupOptions ??= {};
45848
+ resolved.rollupOptions.output ??= {};
45849
+ const output = resolved.rollupOptions.output;
45850
+ for (const out of arraify(output)) {
45851
+ out.entryFileNames ??= `[name].js`;
45852
+ out.chunkFileNames ??= `[name]-[hash].js`;
45853
+ const input = resolved.rollupOptions.input;
45854
+ out.inlineDynamicImports ??= !input || typeof input === "string" || Object.keys(input).length === 1;
45855
+ }
45856
+ }
45857
45857
  return resolved;
45858
45858
  }
45859
45859
  async function resolveBuildPlugins(config) {
@@ -46022,7 +46022,7 @@ ${stackOnly}`;
46022
46022
  );
46023
46023
  }
46024
46024
  const format = output.format || "es";
46025
- const jsExt = !environment.config.webCompatible || libOptions ? resolveOutputJsExtension(
46025
+ const jsExt = environment.config.consumer === "server" || libOptions ? resolveOutputJsExtension(
46026
46026
  format,
46027
46027
  findNearestPackageData(root, packageCache)?.data.type
46028
46028
  ) : "js";
@@ -46048,7 +46048,7 @@ ${stackOnly}`;
46048
46048
  ) : path.posix.join(options.assetsDir, `[name]-[hash].${jsExt}`),
46049
46049
  chunkFileNames: libOptions ? `[name]-[hash].${jsExt}` : path.posix.join(options.assetsDir, `[name]-[hash].${jsExt}`),
46050
46050
  assetFileNames: libOptions ? `[name].[ext]` : path.posix.join(options.assetsDir, `[name]-[hash].[ext]`),
46051
- inlineDynamicImports: output.format === "umd" || output.format === "iife" || environment.config.consumer === "server" && environment.config.webCompatible && (typeof input === "string" || Object.keys(input).length === 1),
46051
+ inlineDynamicImports: output.format === "umd" || output.format === "iife",
46052
46052
  ...output
46053
46053
  };
46054
46054
  };
@@ -46659,19 +46659,17 @@ async function fetchModule(environment, url, importer, options = {}) {
46659
46659
  const { externalConditions, dedupe, preserveSymlinks } = environment.config.resolve;
46660
46660
  const resolved = tryNodeResolve(url, importer, {
46661
46661
  mainFields: ["main"],
46662
- conditions: [],
46662
+ conditions: externalConditions,
46663
46663
  externalConditions,
46664
46664
  external: [],
46665
46665
  noExternal: [],
46666
- overrideConditions: [...externalConditions, "production", "development"],
46667
46666
  extensions: [".js", ".cjs", ".json"],
46668
46667
  dedupe,
46669
46668
  preserveSymlinks,
46670
46669
  isBuild: false,
46671
46670
  isProduction,
46672
46671
  root,
46673
- packageCache: environment.config.packageCache,
46674
- webCompatible: environment.config.webCompatible
46672
+ packageCache: environment.config.packageCache
46675
46673
  });
46676
46674
  if (!resolved) {
46677
46675
  const err = new Error(
@@ -47707,10 +47705,14 @@ class DevEnvironment extends BaseEnvironment {
47707
47705
  name,
47708
47706
  (url) => this.pluginContainer.resolveId(url, void 0)
47709
47707
  );
47710
- this.hot = context.hot || createNoopHotChannel();
47711
47708
  this._crawlEndFinder = setupOnCrawlEnd();
47712
47709
  this._remoteRunnerOptions = context.remoteRunner ?? {};
47713
- context.remoteRunner?.transport?.register(this);
47710
+ this.hot = context.transport ? isWebSocketServer in context.transport ? context.transport : normalizeHotChannel(context.transport, context.hot) : normalizeHotChannel({}, context.hot);
47711
+ this.hot.setInvokeHandler({
47712
+ fetchModule: (id, importer, options2) => {
47713
+ return this.fetchModule(id, importer, options2);
47714
+ }
47715
+ });
47714
47716
  this.hot.on("vite:invalidate", async ({ path, message }) => {
47715
47717
  invalidateModule(this, {
47716
47718
  path,
@@ -47783,7 +47785,7 @@ class DevEnvironment extends BaseEnvironment {
47783
47785
  this.pluginContainer.close(),
47784
47786
  this.depsOptimizer?.close(),
47785
47787
  // WebSocketServer is independent of HotChannel and should not be closed on environment close
47786
- isWebSocketServer in this.hot ? Promise.resolve() : this.hot.close(),
47788
+ isWebSocketServer in this.hot ? Promise.resolve() : this.hot.close?.(),
47787
47789
  (async () => {
47788
47790
  while (this._pendingRequests.size > 0) {
47789
47791
  await Promise.allSettled(
@@ -47881,117 +47883,12 @@ function setupOnCrawlEnd() {
47881
47883
  };
47882
47884
  }
47883
47885
 
47884
- class ServerHMRBroadcasterClient {
47885
- constructor(hotChannel) {
47886
- this.hotChannel = hotChannel;
47887
- }
47888
- send(...args) {
47889
- let payload;
47890
- if (typeof args[0] === "string") {
47891
- payload = {
47892
- type: "custom",
47893
- event: args[0],
47894
- data: args[1]
47895
- };
47896
- } else {
47897
- payload = args[0];
47898
- }
47899
- if (payload.type !== "custom") {
47900
- throw new Error(
47901
- "Cannot send non-custom events from the client to the server."
47902
- );
47903
- }
47904
- this.hotChannel.send(payload);
47905
- }
47906
- }
47907
- class ServerHMRConnector {
47908
- constructor(hotChannel) {
47909
- this.hotChannel = hotChannel;
47910
- this.hmrClient = new ServerHMRBroadcasterClient(hotChannel);
47911
- hotChannel.api.outsideEmitter.on("send", (payload) => {
47912
- this.handlers.forEach((listener) => listener(payload));
47913
- });
47914
- this.hotChannel = hotChannel;
47915
- }
47916
- handlers = [];
47917
- hmrClient;
47918
- connected = false;
47919
- isReady() {
47920
- return this.connected;
47921
- }
47922
- send(payload_) {
47923
- const payload = payload_;
47924
- this.hotChannel.api.innerEmitter.emit(
47925
- payload.event,
47926
- payload.data,
47927
- this.hmrClient
47928
- );
47929
- }
47930
- onUpdate(handler) {
47931
- this.handlers.push(handler);
47932
- handler({ type: "connected" });
47933
- this.connected = true;
47934
- }
47935
- }
47936
-
47937
- function createHMROptions(environment, options) {
47938
- if (environment.config.server.hmr === false || options.hmr === false) {
47939
- return false;
47940
- }
47941
- if (options.hmr?.connection) {
47942
- return {
47943
- connection: options.hmr.connection,
47944
- logger: options.hmr.logger
47945
- };
47946
- }
47947
- if (!("api" in environment.hot)) return false;
47948
- const connection = new ServerHMRConnector(environment.hot);
47949
- return {
47950
- connection,
47951
- logger: options.hmr?.logger
47952
- };
47953
- }
47954
- const prepareStackTrace = {
47955
- retrieveFile(id) {
47956
- if (existsSync$1(id)) {
47957
- return readFileSync$1(id, "utf-8");
47958
- }
47959
- }
47960
- };
47961
- function resolveSourceMapOptions(options) {
47962
- if (options.sourcemapInterceptor != null) {
47963
- if (options.sourcemapInterceptor === "prepareStackTrace") {
47964
- return prepareStackTrace;
47965
- }
47966
- if (typeof options.sourcemapInterceptor === "object") {
47967
- return { ...prepareStackTrace, ...options.sourcemapInterceptor };
47968
- }
47969
- return options.sourcemapInterceptor;
47970
- }
47971
- if (typeof process !== "undefined" && "setSourceMapsEnabled" in process) {
47972
- return "node";
47973
- }
47974
- return prepareStackTrace;
47975
- }
47976
- function createServerModuleRunner(environment, options = {}) {
47977
- const hmr = createHMROptions(environment, options);
47978
- return new ModuleRunner(
47979
- {
47980
- ...options,
47981
- root: environment.config.root,
47982
- transport: {
47983
- fetchModule: (id, importer, options2) => environment.fetchModule(id, importer, options2)
47984
- },
47985
- hmr,
47986
- sourcemapInterceptor: resolveSourceMapOptions(options)
47987
- },
47988
- options.evaluator || new ESModulesEvaluator()
47989
- );
47990
- }
47991
-
47992
47886
  function createRunnableDevEnvironment(name, config, context = {}) {
47887
+ if (context.transport == null) {
47888
+ context.transport = createServerHotChannel();
47889
+ }
47993
47890
  if (context.hot == null) {
47994
- context.hot = createServerHotChannel();
47891
+ context.hot = true;
47995
47892
  }
47996
47893
  return new RunnableDevEnvironment(name, config, context);
47997
47894
  }
@@ -48302,16 +48199,12 @@ function defineConfig(config) {
48302
48199
  }
48303
48200
  function defaultCreateClientDevEnvironment(name, config, context) {
48304
48201
  return new DevEnvironment(name, config, {
48305
- hot: context.ws
48202
+ hot: true,
48203
+ transport: context.ws
48306
48204
  });
48307
48205
  }
48308
- function defaultCreateSsrDevEnvironment(name, config) {
48309
- return createRunnableDevEnvironment(name, config);
48310
- }
48311
48206
  function defaultCreateDevEnvironment(name, config) {
48312
- return new DevEnvironment(name, config, {
48313
- hot: false
48314
- });
48207
+ return createRunnableDevEnvironment(name, config);
48315
48208
  }
48316
48209
  function resolveDevEnvironmentOptions(dev, environmentName, consumer, skipSsrTransform) {
48317
48210
  return {
@@ -48319,25 +48212,28 @@ function resolveDevEnvironmentOptions(dev, environmentName, consumer, skipSsrTra
48319
48212
  sourcemapIgnoreList: dev?.sourcemapIgnoreList === false ? () => false : dev?.sourcemapIgnoreList || isInNodeModules$1,
48320
48213
  preTransformRequests: dev?.preTransformRequests ?? consumer === "client",
48321
48214
  warmup: dev?.warmup ?? [],
48322
- createEnvironment: dev?.createEnvironment ?? (environmentName === "client" ? defaultCreateClientDevEnvironment : environmentName === "ssr" ? defaultCreateSsrDevEnvironment : defaultCreateDevEnvironment),
48215
+ createEnvironment: dev?.createEnvironment ?? (environmentName === "client" ? defaultCreateClientDevEnvironment : defaultCreateDevEnvironment),
48323
48216
  recoverable: dev?.recoverable ?? consumer === "client",
48324
48217
  moduleRunnerTransform: dev?.moduleRunnerTransform ?? (skipSsrTransform !== void 0 && consumer === "server" ? skipSsrTransform : consumer === "server")
48325
48218
  };
48326
48219
  }
48327
- function resolveEnvironmentOptions(options, alias, preserveSymlinks, logger, environmentName, skipSsrTransform) {
48220
+ function resolveEnvironmentOptions(options, alias, preserveSymlinks, logger, environmentName, skipSsrTransform, ssrTargetWebworker) {
48221
+ const isClientEnvironment = environmentName === "client";
48222
+ const consumer = options.consumer ?? (isClientEnvironment ? "client" : "server");
48223
+ const isSsrTargetWebworkerEnvironment = ssrTargetWebworker && environmentName === "ssr";
48328
48224
  const resolve = resolveEnvironmentResolveOptions(
48329
48225
  options.resolve,
48330
48226
  alias,
48331
48227
  preserveSymlinks,
48332
- logger
48228
+ logger,
48229
+ consumer,
48230
+ isSsrTargetWebworkerEnvironment
48333
48231
  );
48334
- const isClientEnvironment = environmentName === "client";
48335
- const consumer = options.consumer ?? (isClientEnvironment ? "client" : "server");
48336
48232
  return {
48337
48233
  define: options.define,
48338
48234
  resolve,
48235
+ keepProcessEnv: options.keepProcessEnv ?? (isSsrTargetWebworkerEnvironment ? false : consumer === "server"),
48339
48236
  consumer,
48340
- webCompatible: options.webCompatible ?? consumer === "client",
48341
48237
  optimizeDeps: resolveDepOptimizationOptions(
48342
48238
  options.optimizeDeps,
48343
48239
  resolve.preserveSymlinks,
@@ -48352,14 +48248,20 @@ function resolveEnvironmentOptions(options, alias, preserveSymlinks, logger, env
48352
48248
  build: resolveBuildEnvironmentOptions(
48353
48249
  options.build ?? {},
48354
48250
  logger,
48355
- consumer
48251
+ consumer,
48252
+ isSsrTargetWebworkerEnvironment
48356
48253
  )
48357
48254
  };
48358
48255
  }
48359
48256
  function getDefaultEnvironmentOptions(config) {
48360
48257
  return {
48361
48258
  define: config.define,
48362
- resolve: config.resolve,
48259
+ resolve: {
48260
+ ...config.resolve,
48261
+ // mainFields and conditions are not inherited
48262
+ mainFields: void 0,
48263
+ conditions: void 0
48264
+ },
48363
48265
  dev: config.dev,
48364
48266
  build: config.build
48365
48267
  };
@@ -48394,12 +48296,16 @@ const clientAlias = [
48394
48296
  replacement: path.posix.join(FS_PREFIX, normalizePath$1(CLIENT_ENTRY))
48395
48297
  }
48396
48298
  ];
48397
- function resolveEnvironmentResolveOptions(resolve, alias, preserveSymlinks, logger) {
48299
+ function resolveEnvironmentResolveOptions(resolve, alias, preserveSymlinks, logger, consumer, isSsrTargetWebworkerEnvironment) {
48300
+ let mainFields = resolve?.mainFields;
48301
+ mainFields ??= consumer === "client" || isSsrTargetWebworkerEnvironment ? DEFAULT_MAIN_FIELDS : DEFAULT_MAIN_FIELDS.filter((f) => f !== "browser");
48302
+ let conditions = resolve?.conditions;
48303
+ conditions ??= consumer === "client" || isSsrTargetWebworkerEnvironment ? DEFAULT_CONDITIONS.filter((c) => c !== "node") : DEFAULT_CONDITIONS.filter((c) => c !== "browser");
48398
48304
  const resolvedResolve = {
48399
- mainFields: resolve?.mainFields ?? DEFAULT_MAIN_FIELDS,
48400
- conditions: resolve?.conditions ?? [],
48401
- externalConditions: resolve?.externalConditions ?? [],
48402
- external: resolve?.external ?? [],
48305
+ mainFields,
48306
+ conditions,
48307
+ externalConditions: resolve?.externalConditions ?? DEFAULT_EXTERNAL_CONDITIONS,
48308
+ external: resolve?.external ?? (consumer === "server" && !isSsrTargetWebworkerEnvironment ? builtinModules : []),
48403
48309
  noExternal: resolve?.noExternal ?? [],
48404
48310
  extensions: resolve?.extensions ?? DEFAULT_EXTENSIONS,
48405
48311
  dedupe: resolve?.dedupe ?? [],
@@ -48421,11 +48327,19 @@ function resolveEnvironmentResolveOptions(resolve, alias, preserveSymlinks, logg
48421
48327
  function resolveResolveOptions(resolve, logger) {
48422
48328
  const alias = normalizeAlias(mergeAlias(clientAlias, resolve?.alias || []));
48423
48329
  const preserveSymlinks = resolve?.preserveSymlinks ?? false;
48330
+ if (alias.some((a) => a.find === "/")) {
48331
+ logger.warn(
48332
+ colors.yellow(
48333
+ `\`resolve.alias\` contains an alias that maps \`/\`. This is not recommended as it can cause unexpected behavior when resolving paths.`
48334
+ )
48335
+ );
48336
+ }
48424
48337
  return resolveEnvironmentResolveOptions(
48425
48338
  resolve,
48426
48339
  alias,
48427
48340
  preserveSymlinks,
48428
- logger
48341
+ logger,
48342
+ void 0
48429
48343
  );
48430
48344
  }
48431
48345
  function resolveDepOptimizationOptions(optimizeDeps, preserveSymlinks, consumer) {
@@ -48532,9 +48446,6 @@ async function resolveConfig(inlineConfig, command, defaultMode = "development",
48532
48446
  configEnvironmentsSsr.resolve.externalConditions ??= config.ssr?.resolve?.externalConditions;
48533
48447
  configEnvironmentsSsr.resolve.external ??= config.ssr?.external;
48534
48448
  configEnvironmentsSsr.resolve.noExternal ??= config.ssr?.noExternal;
48535
- if (config.ssr?.target === "webworker") {
48536
- configEnvironmentsSsr.webCompatible = true;
48537
- }
48538
48449
  }
48539
48450
  if (config.build?.ssrEmitAssets !== void 0) {
48540
48451
  configEnvironmentsSsr ??= {};
@@ -48549,13 +48460,16 @@ async function resolveConfig(inlineConfig, command, defaultMode = "development",
48549
48460
  const defaultEnvironmentOptions = getDefaultEnvironmentOptions(config);
48550
48461
  const defaultClientEnvironmentOptions = {
48551
48462
  ...defaultEnvironmentOptions,
48463
+ resolve: config.resolve,
48464
+ // inherit everything including mainFields and conditions
48552
48465
  optimizeDeps: config.optimizeDeps
48553
48466
  };
48554
48467
  const defaultNonClientEnvironmentOptions = {
48555
48468
  ...defaultEnvironmentOptions,
48556
48469
  dev: {
48557
48470
  ...defaultEnvironmentOptions.dev,
48558
- createEnvironment: void 0
48471
+ createEnvironment: void 0,
48472
+ warmup: void 0
48559
48473
  },
48560
48474
  build: {
48561
48475
  ...defaultEnvironmentOptions.build,
@@ -48578,7 +48492,8 @@ async function resolveConfig(inlineConfig, command, defaultMode = "development",
48578
48492
  resolvedDefaultResolve.preserveSymlinks,
48579
48493
  logger,
48580
48494
  environmentName,
48581
- config.experimental?.skipSsrTransform
48495
+ config.experimental?.skipSsrTransform,
48496
+ config.ssr?.target === "webworker"
48582
48497
  );
48583
48498
  }
48584
48499
  const backwardCompatibleOptimizeDeps = resolvedEnvironments.client.optimizeDeps;
@@ -48980,17 +48895,15 @@ async function bundleConfigFile(fileName, isESM) {
48980
48895
  preferRelative: false,
48981
48896
  tryIndex: true,
48982
48897
  mainFields: [],
48983
- conditions: [],
48898
+ conditions: ["node"],
48984
48899
  externalConditions: [],
48985
48900
  external: [],
48986
48901
  noExternal: [],
48987
- overrideConditions: ["node"],
48988
48902
  dedupe: [],
48989
48903
  extensions: DEFAULT_EXTENSIONS,
48990
48904
  preserveSymlinks: false,
48991
48905
  packageCache,
48992
- isRequire,
48993
- webCompatible: false
48906
+ isRequire
48994
48907
  })?.id;
48995
48908
  };
48996
48909
  build2.onResolve(
@@ -49066,14 +48979,22 @@ async function bundleConfigFile(fileName, isESM) {
49066
48979
  const _require = createRequire(import.meta.url);
49067
48980
  async function loadConfigFromBundledFile(fileName, bundledCode, isESM) {
49068
48981
  if (isESM) {
49069
- const fileBase = `${fileName}.timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
49070
- const fileNameTmp = `${fileBase}.mjs`;
49071
- const fileUrl = `${pathToFileURL(fileBase)}.mjs`;
49072
- await fsp.writeFile(fileNameTmp, bundledCode);
48982
+ const nodeModulesDir = findNearestNodeModules(path.dirname(fileName));
48983
+ if (nodeModulesDir) {
48984
+ await fsp.mkdir(path.resolve(nodeModulesDir, ".vite-temp/"), {
48985
+ recursive: true
48986
+ });
48987
+ }
48988
+ const hash = `timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
48989
+ const tempFileName = nodeModulesDir ? path.resolve(
48990
+ nodeModulesDir,
48991
+ `.vite-temp/${path.basename(fileName)}.${hash}.mjs`
48992
+ ) : `${fileName}.${hash}.mjs`;
48993
+ await fsp.writeFile(tempFileName, bundledCode);
49073
48994
  try {
49074
- return (await import(fileUrl)).default;
48995
+ return (await import(pathToFileURL(tempFileName).href)).default;
49075
48996
  } finally {
49076
- fs__default.unlink(fileNameTmp, () => {
48997
+ fs__default.unlink(tempFileName, () => {
49077
48998
  });
49078
48999
  }
49079
49000
  } else {
@@ -49152,4 +49073,4 @@ function optimizeDepsDisabledBackwardCompatibility(resolved, optimizeDeps, optim
49152
49073
  }
49153
49074
  }
49154
49075
 
49155
- export { rollupVersion as A, BuildEnvironment as B, send$1 as C, DevEnvironment as D, createLogger as E, searchForWorkspaceRoot as F, isFileServingAllowed as G, isFileLoadingAllowed as H, loadEnv as I, resolveEnvPrefix as J, colors as K, getDefaultExportFromCjs as L, commonjsGlobal as M, index$1 as N, index as O, build$1 as P, preview$1 as Q, ServerHMRConnector as S, arraify as a, build as b, createServer as c, defineConfig as d, createBuilder as e, createIdResolver as f, formatPostcssSourceMap as g, preprocessCSS as h, isInNodeModules$1 as i, buildErrorMessage as j, createRunnableDevEnvironment as k, loadConfigFromFile as l, isRunnableDevEnvironment as m, fetchModule as n, optimizeDeps as o, preview as p, createServerModuleRunner as q, resolveConfig as r, sortUserPlugins as s, transformWithEsbuild as t, createServerHotChannel as u, ssrTransform as v, normalizePath$1 as w, mergeConfig as x, mergeAlias as y, createFilter as z };
49076
+ export { rollupVersion as A, BuildEnvironment as B, send$1 as C, DevEnvironment as D, createLogger as E, searchForWorkspaceRoot as F, isFileServingAllowed as G, isFileLoadingAllowed as H, loadEnv as I, resolveEnvPrefix as J, colors as K, getDefaultExportFromCjs as L, commonjsGlobal as M, index$1 as N, index as O, build$1 as P, preview$1 as Q, arraify as a, build as b, createServer as c, defineConfig as d, createBuilder as e, createIdResolver as f, formatPostcssSourceMap as g, preprocessCSS as h, isInNodeModules$1 as i, buildErrorMessage as j, createRunnableDevEnvironment as k, loadConfigFromFile as l, isRunnableDevEnvironment as m, fetchModule as n, optimizeDeps as o, preview as p, createServerModuleRunner as q, resolveConfig as r, sortUserPlugins as s, transformWithEsbuild as t, createServerHotChannel as u, ssrTransform as v, normalizePath$1 as w, mergeConfig as x, mergeAlias as y, createFilter as z };