vite 6.0.10 → 6.1.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,14 +1,14 @@
1
1
  import * as fs$8 from 'node:fs';
2
2
  import fs__default, { promises as promises$1, existsSync as existsSync$1, readFileSync as readFileSync$1 } from 'node:fs';
3
- import fsp, { constants as constants$9 } from 'node:fs/promises';
4
3
  import path$d, { posix as posix$1, isAbsolute as isAbsolute$1, join as join$1, resolve as resolve$4, normalize, dirname as dirname$2, relative as relative$2, basename as basename$2, extname as extname$1 } from 'node:path';
4
+ import fsp, { constants as constants$9 } from 'node:fs/promises';
5
5
  import require$$1$1, { fileURLToPath as fileURLToPath$1, URL as URL$3, pathToFileURL as pathToFileURL$1 } from 'node:url';
6
6
  import { promisify as promisify$4, format as format$2, inspect, stripVTControlCharacters } from 'node:util';
7
7
  import { performance } from 'node:perf_hooks';
8
8
  import require$$0$6, { createRequire as createRequire$1, builtinModules } from 'node:module';
9
9
  import crypto$2 from 'node:crypto';
10
10
  import esbuild, { transform as transform$1, formatMessages, build as build$b } from 'esbuild';
11
- import { CLIENT_ENTRY, OPTIMIZABLE_ENTRY_RE, wildcardHosts, loopbackHosts, FS_PREFIX, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH, DEFAULT_ASSETS_INLINE_LIMIT, ENV_ENTRY, DEP_VERSION_RE, SPECIAL_QUERY_RE, DEV_PROD_CONDITION, JS_TYPES_RE, KNOWN_ASSET_TYPES, CSS_LANGS_RE, METADATA_FILENAME, ESBUILD_MODULES_TARGET, ERR_OPTIMIZE_DEPS_PROCESSING_ERROR, ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR, VITE_PACKAGE_DIR, DEFAULT_DEV_PORT, CLIENT_DIR, VERSION, ROLLUP_HOOKS, DEFAULT_PREVIEW_PORT, DEFAULT_ASSETS_RE, DEFAULT_CONFIG_FILES, DEFAULT_CLIENT_MAIN_FIELDS, DEFAULT_SERVER_MAIN_FIELDS, DEFAULT_CLIENT_CONDITIONS, DEFAULT_SERVER_CONDITIONS } from '../constants.js';
11
+ import { CLIENT_ENTRY, OPTIMIZABLE_ENTRY_RE, wildcardHosts, loopbackHosts, FS_PREFIX, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH, DEFAULT_ASSETS_INLINE_LIMIT, ENV_ENTRY, DEP_VERSION_RE, SPECIAL_QUERY_RE, DEV_PROD_CONDITION, JS_TYPES_RE, KNOWN_ASSET_TYPES, CSS_LANGS_RE, METADATA_FILENAME, ESBUILD_MODULES_TARGET, ERR_OPTIMIZE_DEPS_PROCESSING_ERROR, ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR, VITE_PACKAGE_DIR, DEFAULT_DEV_PORT, defaultAllowedOrigins, CLIENT_DIR, VERSION, ROLLUP_HOOKS, DEFAULT_PREVIEW_PORT, DEFAULT_ASSETS_RE, DEFAULT_CONFIG_FILES, DEFAULT_CLIENT_MAIN_FIELDS, DEFAULT_SERVER_MAIN_FIELDS, DEFAULT_CLIENT_CONDITIONS, DEFAULT_SERVER_CONDITIONS } from '../constants.js';
12
12
  import require$$0$2, { posix, win32, isAbsolute, resolve as resolve$3, relative as relative$1, basename as basename$1, extname, dirname as dirname$1, join, sep } from 'path';
13
13
  import require$$0$3, { existsSync, readFileSync, statSync, readdirSync } from 'fs';
14
14
  import childProcess$2, { exec, execFile, execSync } from 'node:child_process';
@@ -9619,10 +9619,32 @@ const NODE_BUILTIN_NAMESPACE = "node:";
9619
9619
  const NPM_BUILTIN_NAMESPACE = "npm:";
9620
9620
  const BUN_BUILTIN_NAMESPACE = "bun:";
9621
9621
  const nodeBuiltins = builtinModules.filter((id) => !id.includes(":"));
9622
- function isBuiltin(id) {
9623
- if (process.versions.deno && id.startsWith(NPM_BUILTIN_NAMESPACE)) return true;
9624
- if (process.versions.bun && id.startsWith(BUN_BUILTIN_NAMESPACE)) return true;
9625
- return isNodeBuiltin(id);
9622
+ const isBuiltinCache = /* @__PURE__ */ new WeakMap();
9623
+ function isBuiltin(builtins, id) {
9624
+ let isBuiltin2 = isBuiltinCache.get(builtins);
9625
+ if (!isBuiltin2) {
9626
+ isBuiltin2 = createIsBuiltin(builtins);
9627
+ isBuiltinCache.set(builtins, isBuiltin2);
9628
+ }
9629
+ return isBuiltin2(id);
9630
+ }
9631
+ function createIsBuiltin(builtins) {
9632
+ const plainBuiltinsSet = new Set(
9633
+ builtins.filter((builtin) => typeof builtin === "string")
9634
+ );
9635
+ const regexBuiltins = builtins.filter(
9636
+ (builtin) => typeof builtin !== "string"
9637
+ );
9638
+ return (id) => plainBuiltinsSet.has(id) || regexBuiltins.some((regexp) => regexp.test(id));
9639
+ }
9640
+ const nodeLikeBuiltins = [
9641
+ ...nodeBuiltins,
9642
+ new RegExp(`^${NODE_BUILTIN_NAMESPACE}`),
9643
+ new RegExp(`^${NPM_BUILTIN_NAMESPACE}`),
9644
+ new RegExp(`^${BUN_BUILTIN_NAMESPACE}`)
9645
+ ];
9646
+ function isNodeLikeBuiltin(id) {
9647
+ return isBuiltin(nodeLikeBuiltins, id);
9626
9648
  }
9627
9649
  function isNodeBuiltin(id) {
9628
9650
  if (id.startsWith(NODE_BUILTIN_NAMESPACE)) return true;
@@ -9729,8 +9751,6 @@ const isJSRequest = (url) => {
9729
9751
  }
9730
9752
  return false;
9731
9753
  };
9732
- const knownTsRE = /\.(?:ts|mts|cts|tsx)(?:$|\?)/;
9733
- const isTsRequest = (url) => knownTsRE.test(url);
9734
9754
  const importQueryRE = /(\?|&)import=?(?:&|$)/;
9735
9755
  const directRequestRE$1 = /(\?|&)direct=?(?:&|$)/;
9736
9756
  const internalPrefixes = [
@@ -10285,7 +10305,7 @@ function deepClone(value) {
10285
10305
  return value;
10286
10306
  }
10287
10307
  if (value instanceof RegExp) {
10288
- return structuredClone(value);
10308
+ return new RegExp(value);
10289
10309
  }
10290
10310
  if (typeof value === "object" && value != null) {
10291
10311
  throw new Error("Cannot deep clone non-plain object");
@@ -10713,7 +10733,7 @@ const groups = [
10713
10733
  { name: "CSS", color: colors$1.magenta },
10714
10734
  { name: "JS", color: colors$1.cyan }
10715
10735
  ];
10716
- const COMPRESSIBLE_ASSETS_RE = /\.(?:html|json|svg|txt|xml|xhtml)$/;
10736
+ const COMPRESSIBLE_ASSETS_RE = /\.(?:html|json|svg|txt|xml|xhtml|wasm)$/;
10717
10737
  function buildReporterPlugin(config) {
10718
10738
  const compress = promisify$4(gzip);
10719
10739
  const numberFormatter = new Intl.NumberFormat("en", {
@@ -13388,6 +13408,7 @@ function registerCustomMime() {
13388
13408
  mimes["cur"] = "image/x-icon";
13389
13409
  mimes["flac"] = "audio/flac";
13390
13410
  mimes["eot"] = "application/vnd.ms-fontobject";
13411
+ mimes["jxl"] = "image/jxl";
13391
13412
  }
13392
13413
  function renderAssetUrlInJS(pluginContext, chunk, opts, code) {
13393
13414
  const { environment } = pluginContext;
@@ -15970,7 +15991,7 @@ function createIsExternal(environment) {
15970
15991
  }
15971
15992
  let isExternal = false;
15972
15993
  if (id[0] !== "." && !path$d.isAbsolute(id)) {
15973
- isExternal = isBuiltin(id) || isConfiguredAsExternal2(id, importer);
15994
+ isExternal = isBuiltin(environment.config.resolve.builtins, id) || isConfiguredAsExternal2(id, importer);
15974
15995
  }
15975
15996
  processedIds.set(id, isExternal);
15976
15997
  return isExternal;
@@ -16021,14 +16042,6 @@ function resolvePlugin(resolveOptions) {
16021
16042
  return normalizePath$3(path$d.join(root, id));
16022
16043
  }
16023
16044
  }
16024
- if (importer) {
16025
- if (isTsRequest(importer) || resolveOpts.custom?.depScan?.loader?.startsWith("ts")) {
16026
- options.isFromTsImporter = true;
16027
- } else {
16028
- const moduleLang = this.getModuleInfo(importer)?.meta.vite?.lang;
16029
- options.isFromTsImporter = moduleLang && isTsRequest(`.${moduleLang}`);
16030
- }
16031
- }
16032
16045
  let res;
16033
16046
  if (asSrc && depsOptimizer?.isOptimizedDepUrl(id)) {
16034
16047
  const optimizedPath = id.startsWith(FS_PREFIX) ? fsPathFromId(id) : normalizePath$3(path$d.resolve(root, id.slice(1)));
@@ -16127,34 +16140,45 @@ function resolvePlugin(resolveOptions) {
16127
16140
  if (res = tryNodeResolve(id, importer, options, depsOptimizer, external)) {
16128
16141
  return res;
16129
16142
  }
16130
- if (isBuiltin(id)) {
16131
- if (currentEnvironmentOptions.consumer === "server") {
16132
- if (options.enableBuiltinNoExternalCheck && options.noExternal === true && // if both noExternal and external are true, noExternal will take the higher priority and bundle it.
16133
- // only if the id is explicitly listed in external, we will externalize it and skip this error.
16134
- (options.external === true || !options.external.includes(id))) {
16135
- let message = `Cannot bundle Node.js built-in "${id}"`;
16136
- if (importer) {
16137
- message += ` imported from "${path$d.relative(
16138
- process.cwd(),
16139
- importer
16140
- )}"`;
16141
- }
16142
- message += `. Consider disabling environments.${this.environment.name}.noExternal or remove the built-in dependency.`;
16143
- this.error(message);
16143
+ if (currentEnvironmentOptions.consumer === "server" && isBuiltin(options.builtins, id)) {
16144
+ return options.idOnly ? id : { id, external: true, moduleSideEffects: false };
16145
+ } else if (currentEnvironmentOptions.consumer === "server" && isNodeLikeBuiltin(id)) {
16146
+ if (!(options.external === true || options.external.includes(id))) {
16147
+ let message = `Automatically externalized node built-in module "${id}"`;
16148
+ if (importer) {
16149
+ message += ` imported from "${path$d.relative(
16150
+ process.cwd(),
16151
+ importer
16152
+ )}"`;
16144
16153
  }
16145
- return options.idOnly ? id : { id, external: true, moduleSideEffects: false };
16146
- } else {
16147
- if (!asSrc) {
16148
- debug$e?.(
16149
- `externalized node built-in "${id}" to empty module. (imported by: ${colors$1.white(colors$1.dim(importer))})`
16150
- );
16151
- } else if (isProduction) {
16152
- this.warn(
16153
- `Module "${id}" has been externalized for browser compatibility, imported by "${importer}". See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`
16154
- );
16154
+ message += `. Consider adding it to environments.${this.environment.name}.external if it is intended.`;
16155
+ this.error(message);
16156
+ }
16157
+ return options.idOnly ? id : { id, external: true, moduleSideEffects: false };
16158
+ } else if (currentEnvironmentOptions.consumer === "client" && isNodeLikeBuiltin(id)) {
16159
+ if (options.noExternal === true && // if both noExternal and external are true, noExternal will take the higher priority and bundle it.
16160
+ // only if the id is explicitly listed in external, we will externalize it and skip this error.
16161
+ (options.external === true || !options.external.includes(id))) {
16162
+ let message = `Cannot bundle built-in module "${id}"`;
16163
+ if (importer) {
16164
+ message += ` imported from "${path$d.relative(
16165
+ process.cwd(),
16166
+ importer
16167
+ )}"`;
16155
16168
  }
16156
- return isProduction ? browserExternalId : `${browserExternalId}:${id}`;
16169
+ message += `. Consider disabling environments.${this.environment.name}.noExternal or remove the built-in dependency.`;
16170
+ this.error(message);
16157
16171
  }
16172
+ if (!asSrc) {
16173
+ debug$e?.(
16174
+ `externalized node built-in "${id}" to empty module. (imported by: ${colors$1.white(colors$1.dim(importer))})`
16175
+ );
16176
+ } else if (isProduction) {
16177
+ this.warn(
16178
+ `Module "${id}" has been externalized for browser compatibility, imported by "${importer}". See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`
16179
+ );
16180
+ }
16181
+ return isProduction ? browserExternalId : `${browserExternalId}:${id}`;
16158
16182
  }
16159
16183
  }
16160
16184
  debug$e?.(`[fallthrough] ${colors$1.dim(id)}`);
@@ -16237,7 +16261,7 @@ function tryCleanFsResolve(file, options, tryIndex = true, skipPackageJson = fal
16237
16261
  const fileResult = tryResolveRealFileOrType(file, options.preserveSymlinks);
16238
16262
  if (fileResult?.path) return fileResult.path;
16239
16263
  let res;
16240
- const possibleJsToTs = options.isFromTsImporter && isPossibleTsOutput(file);
16264
+ const possibleJsToTs = isPossibleTsOutput(file);
16241
16265
  if (possibleJsToTs || options.extensions.length || tryPrefix) {
16242
16266
  const dirPath = path$d.dirname(file);
16243
16267
  if (isDirectory(dirPath)) {
@@ -16316,15 +16340,16 @@ function tryNodeResolve(id, importer, options, depsOptimizer, externalize) {
16316
16340
  } else {
16317
16341
  basedir = root;
16318
16342
  }
16343
+ const isModuleBuiltin = (id2) => isBuiltin(options.builtins, id2);
16319
16344
  let selfPkg = null;
16320
- if (!isBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
16345
+ if (!isModuleBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
16321
16346
  const selfPackageData = findNearestPackageData(basedir, packageCache);
16322
16347
  selfPkg = selfPackageData?.data.exports && selfPackageData.data.name === pkgId ? selfPackageData : null;
16323
16348
  }
16324
16349
  const pkg = selfPkg || resolvePackageData(pkgId, basedir, preserveSymlinks, packageCache);
16325
16350
  if (!pkg) {
16326
16351
  if (basedir !== root && // root has no peer dep
16327
- !isBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
16352
+ !isModuleBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
16328
16353
  const mainPkg = findNearestMainPackageData(basedir, packageCache)?.data;
16329
16354
  if (mainPkg) {
16330
16355
  const pkgName = getNpmPackageName(id);
@@ -16720,7 +16745,7 @@ function esbuildDepPlugin(environment, qualified, external) {
16720
16745
  namespace: "optional-peer-dep"
16721
16746
  };
16722
16747
  }
16723
- if (environment.config.consumer === "server" && isBuiltin(resolved)) {
16748
+ if (isBuiltin(environment.config.resolve.builtins, resolved)) {
16724
16749
  return;
16725
16750
  }
16726
16751
  if (isExternalUrl(resolved)) {
@@ -18184,22 +18209,19 @@ const svelteScriptModuleRE = /\bcontext\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+)
18184
18209
  const svelteModuleRE = /\smodule\b/i;
18185
18210
  function esbuildScanPlugin(environment, depImports, missing, entries) {
18186
18211
  const seen = /* @__PURE__ */ new Map();
18187
- async function resolveId(id, importer, options) {
18212
+ async function resolveId(id, importer) {
18188
18213
  return environment.pluginContainer.resolveId(
18189
18214
  id,
18190
18215
  importer && normalizePath$3(importer),
18191
- {
18192
- ...options,
18193
- scan: true
18194
- }
18216
+ { scan: true }
18195
18217
  );
18196
18218
  }
18197
- const resolve = async (id, importer, options) => {
18219
+ const resolve = async (id, importer) => {
18198
18220
  const key = id + (importer && path$d.dirname(importer));
18199
18221
  if (seen.has(key)) {
18200
18222
  return seen.get(key);
18201
18223
  }
18202
- const resolved = await resolveId(id, importer, options);
18224
+ const resolved = await resolveId(id, importer);
18203
18225
  const res = resolved?.id;
18204
18226
  seen.set(key, res);
18205
18227
  return res;
@@ -18357,18 +18379,14 @@ function esbuildScanPlugin(environment, depImports, missing, entries) {
18357
18379
  // avoid matching windows volume
18358
18380
  filter: /^[\w@][^:]/
18359
18381
  },
18360
- async ({ path: id, importer, pluginData }) => {
18382
+ async ({ path: id, importer }) => {
18361
18383
  if (moduleListContains(exclude, id)) {
18362
18384
  return externalUnlessEntry({ path: id });
18363
18385
  }
18364
18386
  if (depImports[id]) {
18365
18387
  return externalUnlessEntry({ path: id });
18366
18388
  }
18367
- const resolved = await resolve(id, importer, {
18368
- custom: {
18369
- depScan: { loader: pluginData?.htmlType?.loader }
18370
- }
18371
- });
18389
+ const resolved = await resolve(id, importer);
18372
18390
  if (resolved) {
18373
18391
  if (shouldExternalizeDep(resolved, id)) {
18374
18392
  return externalUnlessEntry({ path: id });
@@ -18411,12 +18429,8 @@ function esbuildScanPlugin(environment, depImports, missing, entries) {
18411
18429
  {
18412
18430
  filter: /.*/
18413
18431
  },
18414
- async ({ path: id, importer, pluginData }) => {
18415
- const resolved = await resolve(id, importer, {
18416
- custom: {
18417
- depScan: { loader: pluginData?.htmlType?.loader }
18418
- }
18419
- });
18432
+ async ({ path: id, importer }) => {
18433
+ const resolved = await resolve(id, importer);
18420
18434
  if (resolved) {
18421
18435
  if (shouldExternalizeDep(resolved, id) || !isScannable(resolved, optimizeDepsOptions.extensions)) {
18422
18436
  return externalUnlessEntry({ path: id });
@@ -18689,21 +18703,33 @@ async function loadCachedDepOptimizationMetadata(environment, force = environmen
18689
18703
  if (cachedMetadata) {
18690
18704
  if (cachedMetadata.lockfileHash !== getLockfileHash(environment)) {
18691
18705
  environment.logger.info(
18692
- "Re-optimizing dependencies because lockfile has changed"
18706
+ "Re-optimizing dependencies because lockfile has changed",
18707
+ {
18708
+ timestamp: true
18709
+ }
18693
18710
  );
18694
18711
  } else if (cachedMetadata.configHash !== getConfigHash(environment)) {
18695
18712
  environment.logger.info(
18696
- "Re-optimizing dependencies because vite config has changed"
18713
+ "Re-optimizing dependencies because vite config has changed",
18714
+ {
18715
+ timestamp: true
18716
+ }
18697
18717
  );
18698
18718
  } else {
18699
- log?.("Hash is consistent. Skipping. Use --force to override.");
18719
+ log?.(
18720
+ `(${environment.name}) Hash is consistent. Skipping. Use --force to override.`
18721
+ );
18700
18722
  return cachedMetadata;
18701
18723
  }
18702
18724
  }
18703
18725
  } else {
18704
- environment.logger.info("Forced re-optimization of dependencies");
18726
+ environment.logger.info("Forced re-optimization of dependencies", {
18727
+ timestamp: true
18728
+ });
18705
18729
  }
18706
- debug$c?.(colors$1.green(`removing old cache dir ${depsCacheDir}`));
18730
+ debug$c?.(
18731
+ `(${environment.name}) ${colors$1.green(`removing old cache dir ${depsCacheDir}`)}`
18732
+ );
18707
18733
  await fsp.rm(depsCacheDir, { recursive: true, force: true });
18708
18734
  }
18709
18735
  function discoverProjectDependencies(environment) {
@@ -19293,7 +19319,11 @@ const lockfileFormats = [
19293
19319
  manager: "pnpm"
19294
19320
  },
19295
19321
  {
19296
- name: "bun.lockb",
19322
+ path: "bun.lock",
19323
+ checkPatchesDir: "patches",
19324
+ manager: "bun"
19325
+ },
19326
+ {
19297
19327
  path: "bun.lockb",
19298
19328
  checkPatchesDir: "patches",
19299
19329
  manager: "bun"
@@ -31371,14 +31401,19 @@ Object.defineProperty(${ssrModuleExportsKey}, "default", { enumerable: true, con
31371
31401
  }
31372
31402
  }
31373
31403
  });
31374
- let map = s.generateMap({ hires: "boundary" });
31375
- map.sources = [path$d.basename(url)];
31376
- map.sourcesContent = [originalCode];
31377
- if (inMap && inMap.mappings && "sources" in inMap && inMap.sources.length > 0) {
31378
- map = combineSourcemaps(url, [
31379
- map,
31380
- inMap
31381
- ]);
31404
+ let map;
31405
+ if (inMap?.mappings === "") {
31406
+ map = inMap;
31407
+ } else {
31408
+ map = s.generateMap({ hires: "boundary" });
31409
+ map.sources = [path$d.basename(url)];
31410
+ map.sourcesContent = [originalCode];
31411
+ if (inMap && inMap.mappings && "sources" in inMap && inMap.sources.length > 0) {
31412
+ map = combineSourcemaps(url, [
31413
+ map,
31414
+ inMap
31415
+ ]);
31416
+ }
31382
31417
  }
31383
31418
  return {
31384
31419
  code: s.toString(),
@@ -37670,7 +37705,8 @@ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {
37670
37705
 
37671
37706
  var WebSocketServerRaw_ = /*@__PURE__*/getDefaultExportFromCjs(websocketServer);
37672
37707
 
37673
- const allowedHostsCache = /* @__PURE__ */ new WeakMap();
37708
+ const allowedHostsServerCache = /* @__PURE__ */ new WeakMap();
37709
+ const allowedHostsPreviewCache = /* @__PURE__ */ new WeakMap();
37674
37710
  const isFileOrExtensionProtocolRE = /^(?:file|.+-extension):/i;
37675
37711
  function getAdditionalAllowedHosts(resolvedServerOptions, resolvedPreviewOptions) {
37676
37712
  const list = [];
@@ -37727,39 +37763,42 @@ function isHostAllowedWithoutCache(allowedHosts, additionalAllowedHosts, host) {
37727
37763
  }
37728
37764
  return false;
37729
37765
  }
37730
- function isHostAllowed(config, host) {
37731
- if (config.server.allowedHosts === true) {
37766
+ function isHostAllowed(config, isPreview, host) {
37767
+ const allowedHosts = isPreview ? config.preview.allowedHosts : config.server.allowedHosts;
37768
+ if (allowedHosts === true) {
37732
37769
  return true;
37733
37770
  }
37734
- if (!allowedHostsCache.has(config)) {
37735
- allowedHostsCache.set(config, /* @__PURE__ */ new Set());
37771
+ const cache = isPreview ? allowedHostsPreviewCache : allowedHostsServerCache;
37772
+ if (!cache.has(config)) {
37773
+ cache.set(config, /* @__PURE__ */ new Set());
37736
37774
  }
37737
- const allowedHosts = allowedHostsCache.get(config);
37738
- if (allowedHosts.has(host)) {
37775
+ const cachedAllowedHosts = cache.get(config);
37776
+ if (cachedAllowedHosts.has(host)) {
37739
37777
  return true;
37740
37778
  }
37741
37779
  const result = isHostAllowedWithoutCache(
37742
- config.server.allowedHosts,
37780
+ allowedHosts,
37743
37781
  config.additionalAllowedHosts,
37744
37782
  host
37745
37783
  );
37746
37784
  if (result) {
37747
- allowedHosts.add(host);
37785
+ cachedAllowedHosts.add(host);
37748
37786
  }
37749
37787
  return result;
37750
37788
  }
37751
- function hostCheckMiddleware(config) {
37789
+ function hostCheckMiddleware(config, isPreview) {
37752
37790
  return function viteHostCheckMiddleware(req, res, next) {
37753
37791
  const hostHeader = req.headers.host;
37754
- if (!hostHeader || !isHostAllowed(config, hostHeader)) {
37792
+ if (!hostHeader || !isHostAllowed(config, isPreview, hostHeader)) {
37755
37793
  const hostname = hostHeader?.replace(/:\d+$/, "");
37756
37794
  const hostnameWithQuotes = JSON.stringify(hostname);
37795
+ const optionName = `${isPreview ? "preview" : "server"}.allowedHosts`;
37757
37796
  res.writeHead(403, {
37758
37797
  "Content-Type": "text/plain"
37759
37798
  });
37760
37799
  res.end(
37761
37800
  `Blocked request. This host (${hostnameWithQuotes}) is not allowed.
37762
- To allow this host, add ${hostnameWithQuotes} to \`server.allowedHosts\` in vite.config.js.`
37801
+ To allow this host, add ${hostnameWithQuotes} to \`${optionName}\` in vite.config.js.`
37763
37802
  );
37764
37803
  return;
37765
37804
  }
@@ -37780,7 +37819,7 @@ const wsServerEvents = [
37780
37819
  "listening",
37781
37820
  "message"
37782
37821
  ];
37783
- function noop$3() {
37822
+ function noop$2() {
37784
37823
  }
37785
37824
  function hasValidToken(config, url) {
37786
37825
  const token = url.searchParams.get("token");
@@ -37804,9 +37843,9 @@ function createWebSocketServer(server, config, httpsOptions) {
37804
37843
  },
37805
37844
  async close() {
37806
37845
  },
37807
- on: noop$3,
37808
- off: noop$3,
37809
- setInvokeHandler: noop$3,
37846
+ on: noop$2,
37847
+ off: noop$2,
37848
+ setInvokeHandler: noop$2,
37810
37849
  handleInvoke: async () => ({
37811
37850
  error: {
37812
37851
  name: "TransportError",
@@ -37814,8 +37853,8 @@ function createWebSocketServer(server, config, httpsOptions) {
37814
37853
  stack: new Error().stack
37815
37854
  }
37816
37855
  }),
37817
- listen: noop$3,
37818
- send: noop$3
37856
+ listen: noop$2,
37857
+ send: noop$2
37819
37858
  };
37820
37859
  }
37821
37860
  let wsHttpServer = undefined;
@@ -37833,7 +37872,7 @@ function createWebSocketServer(server, config, httpsOptions) {
37833
37872
  const protocol = req.headers["sec-websocket-protocol"];
37834
37873
  if (protocol === "vite-ping") return true;
37835
37874
  const hostHeader = req.headers.host;
37836
- if (!hostHeader || !isHostAllowed(config, hostHeader)) {
37875
+ if (!hostHeader || !isHostAllowed(config, false, hostHeader)) {
37837
37876
  return false;
37838
37877
  }
37839
37878
  if (config.legacy?.skipWebSocketTokenCheck) {
@@ -38977,7 +39016,7 @@ var WriteAfterEndError = createErrorType(
38977
39016
  );
38978
39017
 
38979
39018
  // istanbul ignore next
38980
- var destroy = Writable.prototype.destroy || noop$2;
39019
+ var destroy = Writable.prototype.destroy || noop$1;
38981
39020
 
38982
39021
  // An HTTP(S) request that can be redirected
38983
39022
  function RedirectableRequest(options, responseCallback) {
@@ -39461,7 +39500,7 @@ function wrap(protocols) {
39461
39500
  return exports;
39462
39501
  }
39463
39502
 
39464
- function noop$2() { /* empty */ }
39503
+ function noop$1() { /* empty */ }
39465
39504
 
39466
39505
  function parseUrl(input) {
39467
39506
  var parsed;
@@ -39557,7 +39596,7 @@ function destroyRequest(request, error) {
39557
39596
  for (var event of events) {
39558
39597
  request.removeListener(event, eventHandlers[event]);
39559
39598
  }
39560
- request.on("error", noop$2);
39599
+ request.on("error", noop$1);
39561
39600
  request.destroy(error);
39562
39601
  }
39563
39602
 
@@ -40307,21 +40346,34 @@ ${err.stack}`,
40307
40346
  proxies[context] = [proxy, { ...opts }];
40308
40347
  });
40309
40348
  if (httpServer) {
40310
- httpServer.on("upgrade", (req, socket, head) => {
40349
+ httpServer.on("upgrade", async (req, socket, head) => {
40311
40350
  const url = req.url;
40312
40351
  for (const context in proxies) {
40313
40352
  if (doesProxyContextMatchUrl(context, url)) {
40314
40353
  const [proxy, opts] = proxies[context];
40315
40354
  if (opts.ws || opts.target?.toString().startsWith("ws:") || opts.target?.toString().startsWith("wss:")) {
40316
40355
  if (opts.bypass) {
40317
- const bypassResult = opts.bypass(req, undefined, opts);
40318
- if (typeof bypassResult === "string") {
40319
- req.url = bypassResult;
40320
- debug$5?.(`bypass: ${req.url} -> ${bypassResult}`);
40321
- return;
40322
- } else if (bypassResult === false) {
40323
- debug$5?.(`bypass: ${req.url} -> 404`);
40324
- socket.end("HTTP/1.1 404 Not Found\r\n\r\n", "");
40356
+ try {
40357
+ const bypassResult = await opts.bypass(req, undefined, opts);
40358
+ if (typeof bypassResult === "string") {
40359
+ debug$5?.(`bypass: ${req.url} -> ${bypassResult}`);
40360
+ req.url = bypassResult;
40361
+ return;
40362
+ }
40363
+ if (bypassResult === false) {
40364
+ debug$5?.(`bypass: ${req.url} -> 404`);
40365
+ socket.end("HTTP/1.1 404 Not Found\r\n\r\n", "");
40366
+ return;
40367
+ }
40368
+ } catch (err) {
40369
+ config.logger.error(
40370
+ `${colors$1.red(`ws proxy bypass error:`)}
40371
+ ${err.stack}`,
40372
+ {
40373
+ timestamp: true,
40374
+ error: err
40375
+ }
40376
+ );
40325
40377
  return;
40326
40378
  }
40327
40379
  }
@@ -40336,22 +40388,28 @@ ${err.stack}`,
40336
40388
  }
40337
40389
  });
40338
40390
  }
40339
- return function viteProxyMiddleware(req, res, next) {
40391
+ return async function viteProxyMiddleware(req, res, next) {
40340
40392
  const url = req.url;
40341
40393
  for (const context in proxies) {
40342
40394
  if (doesProxyContextMatchUrl(context, url)) {
40343
40395
  const [proxy, opts] = proxies[context];
40344
40396
  const options2 = {};
40345
40397
  if (opts.bypass) {
40346
- const bypassResult = opts.bypass(req, res, opts);
40347
- if (typeof bypassResult === "string") {
40348
- req.url = bypassResult;
40349
- debug$5?.(`bypass: ${req.url} -> ${bypassResult}`);
40350
- return next();
40351
- } else if (bypassResult === false) {
40352
- debug$5?.(`bypass: ${req.url} -> 404`);
40353
- res.statusCode = 404;
40354
- return res.end();
40398
+ try {
40399
+ const bypassResult = await opts.bypass(req, res, opts);
40400
+ if (typeof bypassResult === "string") {
40401
+ debug$5?.(`bypass: ${req.url} -> ${bypassResult}`);
40402
+ req.url = bypassResult;
40403
+ return next();
40404
+ }
40405
+ if (bypassResult === false) {
40406
+ debug$5?.(`bypass: ${req.url} -> 404`);
40407
+ res.statusCode = 404;
40408
+ return res.end();
40409
+ }
40410
+ } catch (e) {
40411
+ debug$5?.(`bypass: ${req.url} -> ${e}`);
40412
+ return next(e);
40355
40413
  }
40356
40414
  }
40357
40415
  debug$5?.(`${req.url} -> ${opts.target || opts.forward}`);
@@ -40659,7 +40717,7 @@ function parse(req) {
40659
40717
  return req._parsedUrl = { pathname, search, query, raw };
40660
40718
  }
40661
40719
 
40662
- const noop$1 = () => {};
40720
+ const noop = () => {};
40663
40721
 
40664
40722
  function isMatch(uri, arr) {
40665
40723
  for (let i=0; i < arr.length; i++) {
@@ -40775,7 +40833,7 @@ function sirv (dir, opts={}) {
40775
40833
  dir = resolve$4(dir || '.');
40776
40834
 
40777
40835
  let isNotFound = opts.onNoMatch || is404;
40778
- let setHeaders = opts.setHeaders || noop$1;
40836
+ let setHeaders = opts.setHeaders || noop;
40779
40837
 
40780
40838
  let extensions = opts.extensions || ['html', 'htm'];
40781
40839
  let gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz');
@@ -44033,7 +44091,7 @@ async function _createServer(inlineConfig = {}, options) {
44033
44091
  }
44034
44092
  const { allowedHosts } = serverConfig;
44035
44093
  if (allowedHosts !== true && !serverConfig.https) {
44036
- middlewares.use(hostCheckMiddleware(config));
44094
+ middlewares.use(hostCheckMiddleware(config, false));
44037
44095
  }
44038
44096
  middlewares.use(cachedTransformMiddleware(server));
44039
44097
  const { proxy } = serverConfig;
@@ -44159,7 +44217,7 @@ const serverConfigDefaults = Object.freeze({
44159
44217
  https: undefined,
44160
44218
  open: false,
44161
44219
  proxy: undefined,
44162
- cors: false,
44220
+ cors: { origin: defaultAllowedOrigins },
44163
44221
  headers: {},
44164
44222
  // hmr
44165
44223
  // ws
@@ -44237,9 +44295,7 @@ async function restartServer(server) {
44237
44295
  let inlineConfig = server.config.inlineConfig;
44238
44296
  if (server._forceOptimizeOnRestart) {
44239
44297
  inlineConfig = mergeConfig(inlineConfig, {
44240
- optimizeDeps: {
44241
- force: true
44242
- }
44298
+ forceOptimizeDeps: true
44243
44299
  });
44244
44300
  }
44245
44301
  {
@@ -44782,7 +44838,9 @@ function propagateUpdate(node, traversedModules, boundaries, currentChain = [nod
44782
44838
  if (!node.importers.size) {
44783
44839
  return true;
44784
44840
  }
44785
- if (!isCSSRequest(node.url) && [...node.importers].every((i) => isCSSRequest(i.url))) {
44841
+ if (!isCSSRequest(node.url) && // we assume .svg is never an entrypoint and does not need a full reload
44842
+ // to avoid frequent full reloads when an SVG file is referenced in CSS files (#18979)
44843
+ !node.file?.endsWith(".svg") && [...node.importers].every((i) => isCSSRequest(i.url))) {
44786
44844
  return true;
44787
44845
  }
44788
44846
  }
@@ -45246,8 +45304,8 @@ async function bundleWorkerEntry(config, id) {
45246
45304
  plugins: workerEnvironment.plugins.map(
45247
45305
  (p) => injectEnvironmentToHooks(workerEnvironment, p)
45248
45306
  ),
45249
- onwarn(warning, warn) {
45250
- onRollupWarning(warning, warn, workerEnvironment);
45307
+ onLog(level, log) {
45308
+ onRollupLog(level, log, workerEnvironment);
45251
45309
  },
45252
45310
  preserveEntrySignatures: false
45253
45311
  });
@@ -45807,7 +45865,7 @@ function importAnalysisPlugin(config) {
45807
45865
  });
45808
45866
  if (!resolved || resolved.meta?.["vite:alias"]?.noResolved) {
45809
45867
  if (ssr) {
45810
- return [url, url];
45868
+ return [url, null];
45811
45869
  }
45812
45870
  importerModule.isSelfAccepting = false;
45813
45871
  moduleGraph._hasResolveFailedErrorModules.add(importerModule);
@@ -45833,21 +45891,21 @@ function importAnalysisPlugin(config) {
45833
45891
  url = injectQuery(url, versionMatch[1]);
45834
45892
  }
45835
45893
  }
45836
- try {
45837
- const depModule = await moduleGraph._ensureEntryFromUrl(
45838
- unwrapId$1(url),
45839
- canSkipImportAnalysis(url) || forceSkipImportAnalysis,
45840
- resolved
45841
- );
45842
- if (depModule.lastHMRTimestamp > 0) {
45843
- url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`);
45844
- }
45845
- } catch (e) {
45846
- e.pos = pos;
45847
- throw e;
45894
+ }
45895
+ try {
45896
+ const depModule = await moduleGraph._ensureEntryFromUrl(
45897
+ unwrapId$1(url),
45898
+ canSkipImportAnalysis(url) || forceSkipImportAnalysis,
45899
+ resolved
45900
+ );
45901
+ if (environment.config.consumer === "client" && depModule.lastHMRTimestamp > 0) {
45902
+ url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`);
45848
45903
  }
45849
- if (!ssr) url = joinUrlSegments(base, url);
45904
+ } catch (e) {
45905
+ e.pos = pos;
45906
+ throw e;
45850
45907
  }
45908
+ if (!ssr) url = joinUrlSegments(base, url);
45851
45909
  return [url, resolved.id];
45852
45910
  };
45853
45911
  const orderedImportedUrls = new Array(imports.length);
@@ -45915,7 +45973,7 @@ function importAnalysisPlugin(config) {
45915
45973
  if (shouldExternalize(environment, specifier, importer)) {
45916
45974
  return;
45917
45975
  }
45918
- if (isBuiltin(specifier)) {
45976
+ if (isBuiltin(environment.config.resolve.builtins, specifier)) {
45919
45977
  return;
45920
45978
  }
45921
45979
  }
@@ -45930,7 +45988,8 @@ function importAnalysisPlugin(config) {
45930
45988
  )} instead.`
45931
45989
  );
45932
45990
  }
45933
- const [url, resolvedId] = await normalizeUrl(specifier, start);
45991
+ let [url, resolvedId] = await normalizeUrl(specifier, start);
45992
+ resolvedId = resolvedId || url;
45934
45993
  config.safeModulePaths.add(fsPathFromUrl(stripBase(url, base)));
45935
45994
  if (url !== specifier) {
45936
45995
  let rewriteDone = false;
@@ -46065,9 +46124,37 @@ See ${colors$1.blue(
46065
46124
  }
46066
46125
  const normalizedAcceptedUrls = /* @__PURE__ */ new Set();
46067
46126
  for (const { url, start, end } of acceptedUrls) {
46068
- const [normalized] = await moduleGraph.resolveUrl(toAbsoluteUrl(url));
46127
+ let [normalized, resolvedId] = await normalizeUrl(url, start).catch(
46128
+ () => []
46129
+ );
46130
+ if (resolvedId) {
46131
+ const mod = moduleGraph.getModuleById(resolvedId);
46132
+ if (!mod) {
46133
+ this.error(
46134
+ `module was not found for ${JSON.stringify(resolvedId)}`,
46135
+ start
46136
+ );
46137
+ return;
46138
+ }
46139
+ normalized = mod.url;
46140
+ } else {
46141
+ try {
46142
+ const [resolved] = await moduleGraph.resolveUrl(toAbsoluteUrl(url));
46143
+ normalized = resolved;
46144
+ if (resolved) {
46145
+ this.warn({
46146
+ message: `Failed to resolve ${JSON.stringify(url)} from ${importer}. An id should be written. Did you pass a URL?`,
46147
+ pos: start
46148
+ });
46149
+ }
46150
+ } catch {
46151
+ this.error(`Failed to resolve ${JSON.stringify(url)}`, start);
46152
+ return;
46153
+ }
46154
+ }
46069
46155
  normalizedAcceptedUrls.add(normalized);
46070
- str().overwrite(start, end, JSON.stringify(normalized), {
46156
+ const hmrAccept = normalizeHmrUrl(normalized);
46157
+ str().overwrite(start, end, JSON.stringify(hmrAccept), {
46071
46158
  contentOnly: true
46072
46159
  });
46073
46160
  }
@@ -46427,13 +46514,62 @@ function err(e, pos) {
46427
46514
  error.pos = pos;
46428
46515
  return error;
46429
46516
  }
46430
- function parseWorkerOptions(rawOpts, optsStartIndex) {
46517
+ function findClosingParen(input, fromIndex) {
46518
+ let count = 1;
46519
+ for (let i = fromIndex + 1; i < input.length; i++) {
46520
+ if (input[i] === "(") count++;
46521
+ if (input[i] === ")") count--;
46522
+ if (count === 0) return i;
46523
+ }
46524
+ return -1;
46525
+ }
46526
+ function extractWorkerTypeFromAst(expression, optsStartIndex) {
46527
+ if (expression.type !== "ObjectExpression") {
46528
+ return;
46529
+ }
46530
+ let lastSpreadElementIndex = -1;
46531
+ let typeProperty = null;
46532
+ let typePropertyIndex = -1;
46533
+ for (let i = 0; i < expression.properties.length; i++) {
46534
+ const property = expression.properties[i];
46535
+ if (property.type === "SpreadElement") {
46536
+ lastSpreadElementIndex = i;
46537
+ continue;
46538
+ }
46539
+ if (property.type === "Property" && (property.key.type === "Identifier" && property.key.name === "type" || property.key.type === "Literal" && property.key.value === "type")) {
46540
+ typeProperty = property;
46541
+ typePropertyIndex = i;
46542
+ }
46543
+ }
46544
+ if (typePropertyIndex === -1 && lastSpreadElementIndex === -1) {
46545
+ return "classic";
46546
+ }
46547
+ if (typePropertyIndex < lastSpreadElementIndex) {
46548
+ throw err(
46549
+ "Expected object spread to be used before the definition of the type property. Vite needs a static value for the type property to correctly infer it.",
46550
+ optsStartIndex
46551
+ );
46552
+ }
46553
+ if (typeProperty?.value.type !== "Literal") {
46554
+ throw err(
46555
+ "Expected worker options type property to be a literal value.",
46556
+ optsStartIndex
46557
+ );
46558
+ }
46559
+ return typeProperty?.value.value === "module" ? "module" : "classic";
46560
+ }
46561
+ async function parseWorkerOptions(rawOpts, optsStartIndex) {
46431
46562
  let opts = {};
46432
46563
  try {
46433
46564
  opts = evalValue(rawOpts);
46434
46565
  } catch {
46566
+ const optsNode = (await parseAstAsync(`(${rawOpts})`)).body[0].expression;
46567
+ const type = extractWorkerTypeFromAst(optsNode, optsStartIndex);
46568
+ if (type) {
46569
+ return { type };
46570
+ }
46435
46571
  throw err(
46436
- "Vite is unable to parse the worker options as the value is not static.To ignore this error, please use /* @vite-ignore */ in the worker options.",
46572
+ "Vite is unable to parse the worker options as the value is not static. To ignore this error, please use /* @vite-ignore */ in the worker options.",
46437
46573
  optsStartIndex
46438
46574
  );
46439
46575
  }
@@ -46448,12 +46584,12 @@ function parseWorkerOptions(rawOpts, optsStartIndex) {
46448
46584
  }
46449
46585
  return opts;
46450
46586
  }
46451
- function getWorkerType(raw, clean, i) {
46587
+ async function getWorkerType(raw, clean, i) {
46452
46588
  const commaIndex = clean.indexOf(",", i);
46453
46589
  if (commaIndex === -1) {
46454
46590
  return "classic";
46455
46591
  }
46456
- const endIndex = clean.indexOf(")", i);
46592
+ const endIndex = findClosingParen(clean, i);
46457
46593
  if (commaIndex > endIndex) {
46458
46594
  return "classic";
46459
46595
  }
@@ -46466,7 +46602,7 @@ function getWorkerType(raw, clean, i) {
46466
46602
  if (!cleanWorkerOptString.length) {
46467
46603
  return "classic";
46468
46604
  }
46469
- const workerOpts = parseWorkerOptions(workerOptString, commaIndex + 1);
46605
+ const workerOpts = await parseWorkerOptions(workerOptString, commaIndex + 1);
46470
46606
  if (workerOpts.type && (workerOpts.type === "module" || workerOpts.type === "classic")) {
46471
46607
  return workerOpts.type;
46472
46608
  }
@@ -46512,12 +46648,12 @@ function workerImportMetaUrlPlugin(config) {
46512
46648
  );
46513
46649
  }
46514
46650
  s ||= new MagicString(code);
46515
- const workerType = getWorkerType(code, cleanString, endIndex);
46651
+ const workerType = await getWorkerType(code, cleanString, endIndex);
46516
46652
  const url = rawUrl.slice(1, -1);
46517
46653
  let file;
46518
46654
  if (url[0] === ".") {
46519
46655
  file = path$d.resolve(path$d.dirname(id), url);
46520
- file = tryFsResolve(file, fsResolveOptions) ?? file;
46656
+ file = slash$1(tryFsResolve(file, fsResolveOptions) ?? file);
46521
46657
  } else {
46522
46658
  workerResolver ??= createBackCompatIdResolver(config, {
46523
46659
  extensions: [],
@@ -47109,8 +47245,6 @@ const viteAliasCustomResolver = async function(id, importer, options) {
47109
47245
  return resolved || { id, meta: { "vite:alias": { noResolved: true } } };
47110
47246
  };
47111
47247
 
47112
- const noop = () => {
47113
- };
47114
47248
  const EMPTY_OBJECT = Object.freeze({});
47115
47249
  const debugSourcemapCombineFilter = process.env.DEBUG_VITE_SOURCEMAP_COMBINE_FILTER;
47116
47250
  const debugSourcemapCombine = createDebugger("vite:sourcemap-combine", {
@@ -47123,6 +47257,9 @@ const debugPluginResolve = createDebugger("vite:plugin-resolve", {
47123
47257
  const debugPluginTransform = createDebugger("vite:plugin-transform", {
47124
47258
  onlyWhenFocused: "vite:plugin"
47125
47259
  });
47260
+ const debugPluginContainerContext = createDebugger(
47261
+ "vite:plugin-container-context"
47262
+ );
47126
47263
  const ERR_CLOSED_SERVER = "ERR_CLOSED_SERVER";
47127
47264
  function throwClosedServerError() {
47128
47265
  const err = new Error(
@@ -47148,18 +47285,10 @@ class EnvironmentPluginContainer {
47148
47285
  this.environment = environment;
47149
47286
  this.plugins = plugins;
47150
47287
  this.watcher = watcher;
47151
- this.minimalContext = {
47152
- meta: {
47153
- rollupVersion,
47154
- watchMode: true
47155
- },
47156
- debug: noop,
47157
- info: noop,
47158
- warn: noop,
47159
- // @ts-expect-error noop
47160
- error: noop,
47288
+ this.minimalContext = new MinimalPluginContext(
47289
+ { rollupVersion, watchMode: true },
47161
47290
  environment
47162
- };
47291
+ );
47163
47292
  const utils = createPluginHookUtils(plugins);
47164
47293
  this.getSortedPlugins = utils.getSortedPlugins;
47165
47294
  this.getSortedPluginHooks = utils.getSortedPluginHooks;
@@ -47450,12 +47579,44 @@ class EnvironmentPluginContainer {
47450
47579
  );
47451
47580
  }
47452
47581
  }
47453
- class PluginContext {
47582
+ class MinimalPluginContext {
47583
+ constructor(meta, environment) {
47584
+ this.meta = meta;
47585
+ this.environment = environment;
47586
+ }
47587
+ debug(rawLog) {
47588
+ const log = this._normalizeRawLog(rawLog);
47589
+ const msg = buildErrorMessage(log, [`debug: ${log.message}`], false);
47590
+ debugPluginContainerContext?.(msg);
47591
+ }
47592
+ info(rawLog) {
47593
+ const log = this._normalizeRawLog(rawLog);
47594
+ const msg = buildErrorMessage(log, [`info: ${log.message}`], false);
47595
+ this.environment.logger.info(msg, { clear: true, timestamp: true });
47596
+ }
47597
+ warn(rawLog) {
47598
+ const log = this._normalizeRawLog(rawLog);
47599
+ const msg = buildErrorMessage(
47600
+ log,
47601
+ [colors$1.yellow(`warning: ${log.message}`)],
47602
+ false
47603
+ );
47604
+ this.environment.logger.warn(msg, { clear: true, timestamp: true });
47605
+ }
47606
+ error(e) {
47607
+ const err = typeof e === "string" ? new Error(e) : e;
47608
+ throw err;
47609
+ }
47610
+ _normalizeRawLog(rawLog) {
47611
+ const logValue = typeof rawLog === "function" ? rawLog() : rawLog;
47612
+ return typeof logValue === "string" ? new Error(logValue) : logValue;
47613
+ }
47614
+ }
47615
+ class PluginContext extends MinimalPluginContext {
47454
47616
  constructor(_plugin, _container) {
47617
+ super(_container.minimalContext.meta, _container.environment);
47455
47618
  this._plugin = _plugin;
47456
47619
  this._container = _container;
47457
- this.environment = this._container.environment;
47458
- this.meta = this._container.minimalContext.meta;
47459
47620
  }
47460
47621
  ssr = false;
47461
47622
  _scan = false;
@@ -47463,8 +47624,6 @@ class PluginContext {
47463
47624
  _activeCode = null;
47464
47625
  _resolveSkips;
47465
47626
  _resolveSkipCalls;
47466
- meta;
47467
- environment;
47468
47627
  parse(code, opts) {
47469
47628
  return parseAst(code, opts);
47470
47629
  }
@@ -47549,24 +47708,25 @@ class PluginContext {
47549
47708
  this._warnIncompatibleMethod(`getFileName`);
47550
47709
  return "";
47551
47710
  }
47552
- warn(e, position) {
47553
- const err = this._formatError(typeof e === "function" ? e() : e, position);
47554
- const msg = buildErrorMessage(
47555
- err,
47556
- [colors$1.yellow(`warning: ${err.message}`)],
47557
- false
47711
+ debug(log) {
47712
+ const err = this._formatLog(typeof log === "function" ? log() : log);
47713
+ super.debug(err);
47714
+ }
47715
+ info(log) {
47716
+ const err = this._formatLog(typeof log === "function" ? log() : log);
47717
+ super.info(err);
47718
+ }
47719
+ warn(log, position) {
47720
+ const err = this._formatLog(
47721
+ typeof log === "function" ? log() : log,
47722
+ position
47558
47723
  );
47559
- this.environment.logger.warn(msg, {
47560
- clear: true,
47561
- timestamp: true
47562
- });
47724
+ super.warn(err);
47563
47725
  }
47564
47726
  error(e, position) {
47565
- throw this._formatError(e, position);
47727
+ throw this._formatLog(e, position);
47566
47728
  }
47567
- debug = noop;
47568
- info = noop;
47569
- _formatError(e, position) {
47729
+ _formatLog(e, position) {
47570
47730
  const err = typeof e === "string" ? new Error(e) : e;
47571
47731
  if (err.pluginCode) {
47572
47732
  return err;
@@ -47995,20 +48155,20 @@ function cssPlugin(config) {
47995
48155
  return;
47996
48156
  }
47997
48157
  const resolveUrl = (url, importer) => idResolver(environment, url, importer);
47998
- const urlReplacer = async (url, importer) => {
48158
+ const urlResolver = async (url, importer) => {
47999
48159
  const decodedUrl = decodeURI(url);
48000
48160
  if (checkPublicFile(decodedUrl, config)) {
48001
48161
  if (encodePublicUrlsInCSS(config)) {
48002
- return publicFileToBuiltUrl(decodedUrl, config);
48162
+ return [publicFileToBuiltUrl(decodedUrl, config), undefined];
48003
48163
  } else {
48004
- return joinUrlSegments(config.base, decodedUrl);
48164
+ return [joinUrlSegments(config.base, decodedUrl), undefined];
48005
48165
  }
48006
48166
  }
48007
48167
  const [id2, fragment] = decodedUrl.split("#");
48008
48168
  let resolved = await resolveUrl(id2, importer);
48009
48169
  if (resolved) {
48010
48170
  if (fragment) resolved += "#" + fragment;
48011
- return fileToUrl$1(this, resolved);
48171
+ return [await fileToUrl$1(this, resolved), resolved];
48012
48172
  }
48013
48173
  if (config.command === "build") {
48014
48174
  const isExternal = config.build.rollupOptions.external ? resolveUserExternal(
@@ -48025,7 +48185,7 @@ ${decodedUrl} referenced in ${id2} didn't resolve at build time, it will remain
48025
48185
  );
48026
48186
  }
48027
48187
  }
48028
- return url;
48188
+ return [url, undefined];
48029
48189
  };
48030
48190
  const {
48031
48191
  code: css,
@@ -48037,7 +48197,7 @@ ${decodedUrl} referenced in ${id2} didn't resolve at build time, it will remain
48037
48197
  id,
48038
48198
  raw,
48039
48199
  preprocessorWorkerController,
48040
- urlReplacer
48200
+ urlResolver
48041
48201
  );
48042
48202
  if (modules) {
48043
48203
  moduleCache.set(id, modules);
@@ -48493,16 +48653,21 @@ function cssAnalysisPlugin(config) {
48493
48653
  if (pluginImports) {
48494
48654
  const depModules = /* @__PURE__ */ new Set();
48495
48655
  for (const file of pluginImports) {
48496
- depModules.add(
48497
- isCSSRequest(file) ? moduleGraph.createFileOnlyEntry(file) : await moduleGraph.ensureEntryFromUrl(
48498
- await fileToDevUrl(
48499
- this.environment,
48500
- file,
48501
- /* skipBase */
48502
- true
48503
- )
48504
- )
48505
- );
48656
+ if (isCSSRequest(file)) {
48657
+ depModules.add(moduleGraph.createFileOnlyEntry(file));
48658
+ } else {
48659
+ const url = await fileToDevUrl(
48660
+ this.environment,
48661
+ file,
48662
+ /* skipBase */
48663
+ true
48664
+ );
48665
+ if (url.startsWith("data:")) {
48666
+ depModules.add(moduleGraph.createFileOnlyEntry(file));
48667
+ } else {
48668
+ depModules.add(await moduleGraph.ensureEntryFromUrl(url));
48669
+ }
48670
+ }
48506
48671
  }
48507
48672
  moduleGraph.updateModuleInfo(
48508
48673
  thisModule,
@@ -48645,23 +48810,12 @@ function getAtImportResolvers(config) {
48645
48810
  }
48646
48811
  return atImportResolvers;
48647
48812
  }
48648
- async function compileCSS(environment, id, code, workerController, urlReplacer) {
48813
+ async function compileCSS(environment, id, code, workerController, urlResolver) {
48649
48814
  const { config } = environment;
48650
48815
  if (config.css.transformer === "lightningcss") {
48651
- return compileLightningCSS(id, code, environment, urlReplacer);
48816
+ return compileLightningCSS(id, code, environment, urlResolver);
48652
48817
  }
48653
- const { modules: modulesOptions, devSourcemap } = config.css;
48654
- const isModule = modulesOptions !== false && cssModuleRE.test(id);
48655
- const needInlineImport = code.includes("@import");
48656
- const hasUrl = cssUrlRE.test(code) || cssImageSetRE.test(code);
48657
48818
  const lang = CSS_LANGS_RE.exec(id)?.[1];
48658
- const postcssConfig = await resolvePostcssConfig(
48659
- environment.getTopLevelConfig()
48660
- );
48661
- if (lang === "css" && !postcssConfig && !isModule && !needInlineImport && !hasUrl) {
48662
- return { code, map: null };
48663
- }
48664
- let modules;
48665
48819
  const deps = /* @__PURE__ */ new Set();
48666
48820
  let preprocessorMap;
48667
48821
  if (isPreProcessor(lang)) {
@@ -48676,10 +48830,19 @@ async function compileCSS(environment, id, code, workerController, urlReplacer)
48676
48830
  preprocessorMap = preprocessorResult.map;
48677
48831
  preprocessorResult.deps?.forEach((dep) => deps.add(dep));
48678
48832
  }
48833
+ const { modules: modulesOptions, devSourcemap } = config.css;
48834
+ const isModule = modulesOptions !== false && cssModuleRE.test(id);
48835
+ const needInlineImport = code.includes("@import");
48836
+ const hasUrl = cssUrlRE.test(code) || cssImageSetRE.test(code);
48837
+ const postcssConfig = await resolvePostcssConfig(
48838
+ environment.getTopLevelConfig()
48839
+ );
48840
+ if (lang !== "sss" && !postcssConfig && !isModule && !needInlineImport && !hasUrl) {
48841
+ return { code, map: preprocessorMap ?? null, deps };
48842
+ }
48679
48843
  const atImportResolvers = getAtImportResolvers(
48680
48844
  environment.getTopLevelConfig()
48681
48845
  );
48682
- const postcssOptions = postcssConfig?.options ?? {};
48683
48846
  const postcssPlugins = postcssConfig?.plugins.slice() ?? [];
48684
48847
  if (needInlineImport) {
48685
48848
  postcssPlugins.unshift(
@@ -48731,14 +48894,19 @@ async function compileCSS(environment, id, code, workerController, urlReplacer)
48731
48894
  })
48732
48895
  );
48733
48896
  }
48734
- if (urlReplacer) {
48897
+ if (urlResolver && // if there's an @import, we need to add this plugin
48898
+ // regradless of whether it contains url() or image-set(),
48899
+ // because we don't know the content referenced by @import
48900
+ (needInlineImport || hasUrl)) {
48735
48901
  postcssPlugins.push(
48736
48902
  UrlRewritePostcssPlugin({
48737
- replacer: urlReplacer,
48903
+ resolver: urlResolver,
48904
+ deps,
48738
48905
  logger: environment.logger
48739
48906
  })
48740
48907
  );
48741
48908
  }
48909
+ let modules;
48742
48910
  if (isModule) {
48743
48911
  postcssPlugins.unshift(
48744
48912
  (await importPostcssModules()).default({
@@ -48766,7 +48934,9 @@ async function compileCSS(environment, id, code, workerController, urlReplacer)
48766
48934
  })
48767
48935
  );
48768
48936
  }
48769
- if (!postcssPlugins.length) {
48937
+ const postcssOptions = postcssConfig?.options ?? {};
48938
+ const postcssParser = lang === "sss" ? loadSss(config.root) : postcssOptions.parser;
48939
+ if (!postcssPlugins.length && !postcssParser) {
48770
48940
  return {
48771
48941
  code,
48772
48942
  map: preprocessorMap,
@@ -48779,7 +48949,7 @@ async function compileCSS(environment, id, code, workerController, urlReplacer)
48779
48949
  const postcss = await importPostcss();
48780
48950
  postcssResult = await postcss.default(postcssPlugins).process(code, {
48781
48951
  ...postcssOptions,
48782
- parser: lang === "sss" ? loadSss(config.root) : postcssOptions.parser,
48952
+ parser: postcssParser,
48783
48953
  to: source,
48784
48954
  from: source,
48785
48955
  ...devSourcemap ? {
@@ -48841,7 +49011,6 @@ ${generateCodeFrame(
48841
49011
  }
48842
49012
  if (!devSourcemap) {
48843
49013
  return {
48844
- ast: postcssResult,
48845
49014
  code: postcssResult.css,
48846
49015
  map: { mappings: "" },
48847
49016
  modules,
@@ -48856,7 +49025,6 @@ ${generateCodeFrame(
48856
49025
  cleanUrl(id)
48857
49026
  );
48858
49027
  return {
48859
- ast: postcssResult,
48860
49028
  code: postcssResult.css,
48861
49029
  map: combineSourcemapsIfExists(cleanUrl(id), postcssMap, preprocessorMap),
48862
49030
  modules,
@@ -48875,8 +49043,8 @@ function createCachedImport(imp) {
48875
49043
  return cached;
48876
49044
  };
48877
49045
  }
48878
- const importPostcssImport = createCachedImport(() => import('./dep-a6F3bn0a.js').then(function (n) { return n.i; }));
48879
- const importPostcssModules = createCachedImport(() => import('./dep-BgKqB7IO.js').then(function (n) { return n.i; }));
49046
+ const importPostcssImport = createCachedImport(() => import('./dep-BADA5W91.js').then(function (n) { return n.i; }));
49047
+ const importPostcssModules = createCachedImport(() => import('./dep-7ffYZsA7.js').then(function (n) { return n.i; }));
48880
49048
  const importPostcss = createCachedImport(() => import('postcss'));
48881
49049
  const preprocessorWorkerControllerCache = /* @__PURE__ */ new WeakMap();
48882
49050
  let alwaysFakeWorkerWorkerControllerCache;
@@ -48994,8 +49162,12 @@ const UrlRewritePostcssPlugin = (opts) => {
48994
49162
  const isCssUrl = cssUrlRE.test(declaration.value);
48995
49163
  const isCssImageSet = cssImageSetRE.test(declaration.value);
48996
49164
  if (isCssUrl || isCssImageSet) {
48997
- const replacerForDeclaration = (rawUrl) => {
48998
- return opts.replacer(rawUrl, importer);
49165
+ const replacerForDeclaration = async (rawUrl) => {
49166
+ const [newUrl, resolvedId] = await opts.resolver(rawUrl, importer);
49167
+ if (newUrl.startsWith("data:") && resolvedId) {
49168
+ opts.deps.add(resolvedId);
49169
+ }
49170
+ return newUrl;
48999
49171
  };
49000
49172
  if (isCssUrl && isCssImageSet) {
49001
49173
  promises.push(
@@ -49927,7 +50099,7 @@ function isPreProcessor(lang) {
49927
50099
  return lang && preprocessorSet.has(lang);
49928
50100
  }
49929
50101
  const importLightningCSS = createCachedImport(() => import('lightningcss'));
49930
- async function compileLightningCSS(id, src, environment, urlReplacer) {
50102
+ async function compileLightningCSS(id, src, environment, urlResolver) {
49931
50103
  const { config } = environment;
49932
50104
  const deps = /* @__PURE__ */ new Set();
49933
50105
  const filename = id.replace("\0", NULL_BYTE_PLACEHOLDER);
@@ -49983,6 +50155,16 @@ async function compileLightningCSS(id, src, environment, urlReplacer) {
49983
50155
  column: e.loc.column - 1
49984
50156
  // 1-based
49985
50157
  };
50158
+ try {
50159
+ const code = fs__default.readFileSync(e.fileName, "utf-8");
50160
+ const commonIeMessage = ", which was used in the past to support old Internet Explorer versions. This is not a valid CSS syntax and will be ignored by modern browsers. \nWhile this is not supported by LightningCSS, you can set `css.lightningcss.errorRecovery: true` to strip these codes.";
50161
+ if (/[\s;{]\*[a-zA-Z-][\w-]+\s*:/.test(code)) {
50162
+ e.message += ".\nThis file contains star property hack (e.g. `*zoom`)" + commonIeMessage;
50163
+ } else if (/min-width:\s*0\\0/.test(code)) {
50164
+ e.message += ".\nThis file contains @media zero hack (e.g. `@media (min-width: 0\\0)`)" + commonIeMessage;
50165
+ }
50166
+ } catch {
50167
+ }
49986
50168
  }
49987
50169
  throw e;
49988
50170
  }
@@ -50003,11 +50185,15 @@ ${generateCodeFrame(src, {
50003
50185
  let replaceUrl;
50004
50186
  if (skipUrlReplacer(dep.url)) {
50005
50187
  replaceUrl = dep.url;
50006
- } else if (urlReplacer) {
50007
- replaceUrl = await urlReplacer(
50188
+ } else if (urlResolver) {
50189
+ const [newUrl, resolvedId] = await urlResolver(
50008
50190
  dep.url,
50009
50191
  dep.loc.filePath.replace(NULL_BYTE_PLACEHOLDER, "\0")
50010
50192
  );
50193
+ if (newUrl.startsWith("data:") && resolvedId) {
50194
+ deps.add(resolvedId);
50195
+ }
50196
+ replaceUrl = newUrl;
50011
50197
  } else {
50012
50198
  replaceUrl = dep.url;
50013
50199
  }
@@ -50910,8 +51096,8 @@ async function buildEnvironment(environment) {
50910
51096
  input,
50911
51097
  plugins,
50912
51098
  external: options.rollupOptions.external,
50913
- onwarn(warning, warn) {
50914
- onRollupWarning(warning, warn, environment);
51099
+ onLog(level, log) {
51100
+ onRollupLog(level, log, environment);
50915
51101
  }
50916
51102
  };
50917
51103
  function extractStack(e) {
@@ -50935,7 +51121,12 @@ ${trimmedPadding}
50935
51121
  const enhanceRollupError = (e) => {
50936
51122
  const stackOnly = extractStack(e);
50937
51123
  let msg = colors$1.red((e.plugin ? `[${e.plugin}] ` : "") + e.message);
50938
- if (e.id) {
51124
+ if (e.loc && e.loc.file && e.loc.file !== e.id) {
51125
+ msg += `
51126
+ file: ${colors$1.cyan(
51127
+ `${e.loc.file}:${e.loc.line}:${e.loc.column}` + (e.id ? ` (${e.id})` : "")
51128
+ )}`;
51129
+ } else if (e.id) {
50939
51130
  msg += `
50940
51131
  file: ${colors$1.cyan(
50941
51132
  e.id + (e.loc ? `:${e.loc.line}:${e.loc.column}` : "")
@@ -51200,54 +51391,80 @@ function clearLine() {
51200
51391
  process.stdout.cursorTo(0);
51201
51392
  }
51202
51393
  }
51203
- function onRollupWarning(warning, warn, environment) {
51204
- const viteWarn = (warnLog) => {
51205
- let warning2;
51206
- if (typeof warnLog === "function") {
51207
- warning2 = warnLog();
51208
- } else {
51209
- warning2 = warnLog;
51210
- }
51211
- if (typeof warning2 === "object") {
51212
- if (warning2.code === "UNRESOLVED_IMPORT") {
51213
- const id = warning2.id;
51214
- const exporter = warning2.exporter;
51215
- if (!id || !id.endsWith("?commonjs-external")) {
51216
- throw new Error(
51217
- `[vite]: Rollup failed to resolve import "${exporter}" from "${id}".
51394
+ function onRollupLog(level, log, environment) {
51395
+ const debugLogger = createDebugger("vite:build");
51396
+ const viteLog = (logLeveling, rawLogging) => {
51397
+ const logging = typeof rawLogging === "object" ? rawLogging : { message: rawLogging };
51398
+ if (logging.code === "UNRESOLVED_IMPORT") {
51399
+ const id = logging.id;
51400
+ const exporter = logging.exporter;
51401
+ if (!id || !id.endsWith("?commonjs-external")) {
51402
+ throw new Error(
51403
+ `[vite]: Rollup failed to resolve import "${exporter}" from "${id}".
51218
51404
  This is most likely unintended because it can break your application at runtime.
51219
51405
  If you do want to externalize this module explicitly add it to
51220
51406
  \`build.rollupOptions.external\``
51221
- );
51222
- }
51407
+ );
51223
51408
  }
51224
- if (warning2.plugin === "rollup-plugin-dynamic-import-variables" && dynamicImportWarningIgnoreList.some(
51225
- (msg) => warning2.message.includes(msg)
51409
+ }
51410
+ if (logLeveling === "warn") {
51411
+ if (logging.plugin === "rollup-plugin-dynamic-import-variables" && dynamicImportWarningIgnoreList.some(
51412
+ (msg) => logging.message.includes(msg)
51226
51413
  )) {
51227
51414
  return;
51228
51415
  }
51229
- if (warningIgnoreList.includes(warning2.code)) {
51416
+ if (warningIgnoreList.includes(logging.code)) {
51230
51417
  return;
51231
51418
  }
51232
- if (warning2.code === "PLUGIN_WARNING") {
51233
- environment.logger.warn(
51234
- `${colors$1.bold(
51235
- colors$1.yellow(`[plugin:${warning2.plugin}]`)
51236
- )} ${colors$1.yellow(warning2.message)}`
51237
- );
51419
+ }
51420
+ switch (logLeveling) {
51421
+ case "info":
51422
+ environment.logger.info(logging.message);
51423
+ return;
51424
+ case "warn":
51425
+ environment.logger.warn(colors$1.yellow(logging.message));
51426
+ return;
51427
+ case "error":
51428
+ environment.logger.error(colors$1.red(logging.message));
51429
+ return;
51430
+ case "debug":
51431
+ debugLogger?.(logging.message);
51432
+ return;
51433
+ default:
51434
+ environment.logger.info(logging.message);
51238
51435
  return;
51239
- }
51240
51436
  }
51241
- warn(warnLog);
51242
51437
  };
51243
51438
  clearLine();
51244
- const userOnWarn = environment.config.build.rollupOptions.onwarn;
51245
- if (userOnWarn) {
51246
- userOnWarn(warning, viteWarn);
51439
+ const userOnLog = environment.config.build.rollupOptions?.onLog;
51440
+ const userOnWarn = environment.config.build.rollupOptions?.onwarn;
51441
+ if (userOnLog) {
51442
+ if (userOnWarn) {
51443
+ const normalizedUserOnWarn = normalizeUserOnWarn(userOnWarn, viteLog);
51444
+ userOnLog(level, log, normalizedUserOnWarn);
51445
+ } else {
51446
+ userOnLog(level, log, viteLog);
51447
+ }
51448
+ } else if (userOnWarn) {
51449
+ const normalizedUserOnWarn = normalizeUserOnWarn(userOnWarn, viteLog);
51450
+ normalizedUserOnWarn(level, log);
51247
51451
  } else {
51248
- viteWarn(warning);
51452
+ viteLog(level, log);
51249
51453
  }
51250
51454
  }
51455
+ function normalizeUserOnWarn(userOnWarn, defaultHandler) {
51456
+ return (logLevel, logging) => {
51457
+ if (logLevel === "warn") {
51458
+ userOnWarn(
51459
+ normalizeLog(logging),
51460
+ (log) => defaultHandler("warn", typeof log === "function" ? log() : log)
51461
+ );
51462
+ } else {
51463
+ defaultHandler(logLevel, logging);
51464
+ }
51465
+ };
51466
+ }
51467
+ const normalizeLog = (log) => typeof log === "string" ? { message: log } : log;
51251
51468
  function resolveUserExternal(user, id, parentId, isResolved) {
51252
51469
  if (typeof user === "function") {
51253
51470
  return user(id, parentId, isResolved);
@@ -51595,7 +51812,7 @@ var build$1 = {
51595
51812
  createBuilder: createBuilder,
51596
51813
  createToImportMetaURLBasedRelativeRuntime: createToImportMetaURLBasedRelativeRuntime,
51597
51814
  injectEnvironmentToHooks: injectEnvironmentToHooks,
51598
- onRollupWarning: onRollupWarning,
51815
+ onRollupLog: onRollupLog,
51599
51816
  resolveBuildEnvironmentOptions: resolveBuildEnvironmentOptions,
51600
51817
  resolveBuildOutputs: resolveBuildOutputs,
51601
51818
  resolveBuildPlugins: resolveBuildPlugins,
@@ -51609,7 +51826,7 @@ var build$1 = {
51609
51826
  };
51610
51827
 
51611
51828
  async function fetchModule(environment, url, importer, options = {}) {
51612
- if (url.startsWith("data:") || isBuiltin(url)) {
51829
+ if (url.startsWith("data:") || isBuiltin(environment.config.resolve.builtins, url)) {
51613
51830
  return { externalize: url, type: "builtin" };
51614
51831
  }
51615
51832
  const isFileUrl = url.startsWith("file://");
@@ -51631,7 +51848,8 @@ async function fetchModule(environment, url, importer, options = {}) {
51631
51848
  isBuild: false,
51632
51849
  isProduction,
51633
51850
  root,
51634
- packageCache: environment.config.packageCache
51851
+ packageCache: environment.config.packageCache,
51852
+ builtins: environment.config.resolve.builtins
51635
51853
  });
51636
51854
  if (!resolved) {
51637
51855
  const err = new Error(
@@ -53102,7 +53320,7 @@ async function preview(inlineConfig = {}) {
53102
53320
  }
53103
53321
  const { allowedHosts } = config.preview;
53104
53322
  if (allowedHosts !== true && !config.preview.https) {
53105
- app.use(hostCheckMiddleware(config));
53323
+ app.use(hostCheckMiddleware(config, true));
53106
53324
  }
53107
53325
  const { proxy } = config.preview;
53108
53326
  if (proxy) {
@@ -53180,6 +53398,61 @@ function resolveSSROptions(ssr, preserveSymlinks) {
53180
53398
  return mergeWithDefaults(defaults, ssr);
53181
53399
  }
53182
53400
 
53401
+ async function runnerImport(moduleId, inlineConfig) {
53402
+ const isModuleSyncConditionEnabled = (await import('#module-sync-enabled')).default;
53403
+ const config = await resolveConfig(
53404
+ mergeConfig(inlineConfig || {}, {
53405
+ configFile: false,
53406
+ envFile: false,
53407
+ cacheDir: process.cwd(),
53408
+ environments: {
53409
+ inline: {
53410
+ consumer: "server",
53411
+ dev: {
53412
+ moduleRunnerTransform: true
53413
+ },
53414
+ resolve: {
53415
+ external: true,
53416
+ mainFields: [],
53417
+ conditions: [
53418
+ "node",
53419
+ ...isModuleSyncConditionEnabled ? ["module-sync"] : []
53420
+ ]
53421
+ }
53422
+ }
53423
+ }
53424
+ }),
53425
+ "serve"
53426
+ );
53427
+ const environment = createRunnableDevEnvironment("inline", config, {
53428
+ runnerOptions: {
53429
+ hmr: {
53430
+ logger: false
53431
+ }
53432
+ },
53433
+ hot: false
53434
+ });
53435
+ await environment.init();
53436
+ try {
53437
+ const module = await environment.runner.import(moduleId);
53438
+ const modules = [
53439
+ ...environment.runner.evaluatedModules.urlToIdModuleMap.values()
53440
+ ];
53441
+ const dependencies = modules.filter((m) => {
53442
+ if (!m.meta || "externalize" in m.meta) {
53443
+ return false;
53444
+ }
53445
+ return m.exports !== module;
53446
+ }).map((m) => m.file);
53447
+ return {
53448
+ module,
53449
+ dependencies
53450
+ };
53451
+ } finally {
53452
+ await environment.close();
53453
+ }
53454
+ }
53455
+
53183
53456
  const debug = createDebugger("vite:config", { depth: 10 });
53184
53457
  const promisifiedRealpath = promisify$4(fs__default.realpath);
53185
53458
  function defineConfig(config) {
@@ -53314,7 +53587,7 @@ function resolveDevEnvironmentOptions(dev, environmentName, consumer, skipSsrTra
53314
53587
  sourcemapIgnoreList: resolved.sourcemapIgnoreList === false ? () => false : resolved.sourcemapIgnoreList
53315
53588
  };
53316
53589
  }
53317
- function resolveEnvironmentOptions(options, alias, preserveSymlinks, logger, environmentName, skipSsrTransform, isSsrTargetWebworkerSet) {
53590
+ function resolveEnvironmentOptions(options, alias, preserveSymlinks, forceOptimizeDeps, logger, environmentName, skipSsrTransform, isSsrTargetWebworkerSet) {
53318
53591
  const isClientEnvironment = environmentName === "client";
53319
53592
  const consumer = options.consumer ?? (isClientEnvironment ? "client" : "server");
53320
53593
  const isSsrTargetWebworkerEnvironment = isSsrTargetWebworkerSet && environmentName === "ssr";
@@ -53334,6 +53607,7 @@ function resolveEnvironmentOptions(options, alias, preserveSymlinks, logger, env
53334
53607
  optimizeDeps: resolveDepOptimizationOptions(
53335
53608
  options.optimizeDeps,
53336
53609
  resolve.preserveSymlinks,
53610
+ forceOptimizeDeps,
53337
53611
  consumer
53338
53612
  ),
53339
53613
  dev: resolveDevEnvironmentOptions(
@@ -53398,7 +53672,7 @@ function resolveEnvironmentResolveOptions(resolve, alias, preserveSymlinks, logg
53398
53672
  ...configDefaults.resolve,
53399
53673
  mainFields: consumer === undefined || consumer === "client" || isSsrTargetWebworkerEnvironment ? DEFAULT_CLIENT_MAIN_FIELDS : DEFAULT_SERVER_MAIN_FIELDS,
53400
53674
  conditions: consumer === undefined || consumer === "client" || isSsrTargetWebworkerEnvironment ? DEFAULT_CLIENT_CONDITIONS : DEFAULT_SERVER_CONDITIONS.filter((c) => c !== "browser"),
53401
- enableBuiltinNoExternalCheck: !!isSsrTargetWebworkerEnvironment
53675
+ builtins: resolve?.builtins ?? (consumer === "server" && !isSsrTargetWebworkerEnvironment ? nodeLikeBuiltins : [])
53402
53676
  },
53403
53677
  resolve ?? {}
53404
53678
  );
@@ -53436,7 +53710,7 @@ function resolveResolveOptions(resolve, logger) {
53436
53710
  undefined
53437
53711
  );
53438
53712
  }
53439
- function resolveDepOptimizationOptions(optimizeDeps, preserveSymlinks, consumer) {
53713
+ function resolveDepOptimizationOptions(optimizeDeps, preserveSymlinks, forceOptimizeDeps, consumer) {
53440
53714
  return mergeWithDefaults(
53441
53715
  {
53442
53716
  ...configDefaults.optimizeDeps,
@@ -53445,7 +53719,8 @@ function resolveDepOptimizationOptions(optimizeDeps, preserveSymlinks, consumer)
53445
53719
  noDiscovery: consumer !== "client",
53446
53720
  esbuildOptions: {
53447
53721
  preserveSymlinks
53448
- }
53722
+ },
53723
+ force: forceOptimizeDeps ?? configDefaults.optimizeDeps.force
53449
53724
  },
53450
53725
  optimizeDeps ?? {}
53451
53726
  );
@@ -53472,7 +53747,8 @@ async function resolveConfig(inlineConfig, command, defaultMode = "development",
53472
53747
  configFile,
53473
53748
  config.root,
53474
53749
  config.logLevel,
53475
- config.customLogger
53750
+ config.customLogger,
53751
+ config.configLoader
53476
53752
  );
53477
53753
  if (loadResult) {
53478
53754
  config = mergeConfig(loadResult.config, config);
@@ -53595,6 +53871,7 @@ async function resolveConfig(inlineConfig, command, defaultMode = "development",
53595
53871
  config.environments[environmentName],
53596
53872
  resolvedDefaultResolve.alias,
53597
53873
  resolvedDefaultResolve.preserveSymlinks,
53874
+ inlineConfig.forceOptimizeDeps,
53598
53875
  logger,
53599
53876
  environmentName,
53600
53877
  config.experimental?.skipSsrTransform,
@@ -53931,7 +54208,12 @@ function sortUserPlugins(plugins) {
53931
54208
  }
53932
54209
  return [prePlugins, normalPlugins, postPlugins];
53933
54210
  }
53934
- async function loadConfigFromFile(configEnv, configFile, configRoot = process.cwd(), logLevel, customLogger) {
54211
+ async function loadConfigFromFile(configEnv, configFile, configRoot = process.cwd(), logLevel, customLogger, configLoader = "bundle") {
54212
+ if (configLoader !== "bundle" && configLoader !== "runner") {
54213
+ throw new Error(
54214
+ `Unsupported configLoader: ${configLoader}. Accepted values are 'bundle' and 'runner'.`
54215
+ );
54216
+ }
53935
54217
  const start = performance.now();
53936
54218
  const getTime = () => `${(performance.now() - start).toFixed(2)}ms`;
53937
54219
  let resolvedPath;
@@ -53949,23 +54231,18 @@ async function loadConfigFromFile(configEnv, configFile, configRoot = process.cw
53949
54231
  debug?.("no config file found.");
53950
54232
  return null;
53951
54233
  }
53952
- const isESM = typeof process.versions.deno === "string" || isFilePathESM(resolvedPath);
53953
54234
  try {
53954
- const bundled = await bundleConfigFile(resolvedPath, isESM);
53955
- const userConfig = await loadConfigFromBundledFile(
53956
- resolvedPath,
53957
- bundled.code,
53958
- isESM
53959
- );
53960
- debug?.(`bundled config file loaded in ${getTime()}`);
53961
- const config = await (typeof userConfig === "function" ? userConfig(configEnv) : userConfig);
54235
+ const resolver = configLoader === "bundle" ? bundleAndLoadConfigFile : importConfigFile;
54236
+ const { configExport, dependencies } = await resolver(resolvedPath);
54237
+ debug?.(`config file loaded in ${getTime()}`);
54238
+ const config = await (typeof configExport === "function" ? configExport(configEnv) : configExport);
53962
54239
  if (!isObject$2(config)) {
53963
54240
  throw new Error(`config must export or return an object.`);
53964
54241
  }
53965
54242
  return {
53966
54243
  path: normalizePath$3(resolvedPath),
53967
54244
  config,
53968
- dependencies: bundled.dependencies
54245
+ dependencies
53969
54246
  };
53970
54247
  } catch (e) {
53971
54248
  createLogger(logLevel, { customLogger }).error(
@@ -53977,6 +54254,26 @@ async function loadConfigFromFile(configEnv, configFile, configRoot = process.cw
53977
54254
  throw e;
53978
54255
  }
53979
54256
  }
54257
+ async function importConfigFile(resolvedPath) {
54258
+ const { module, dependencies } = await runnerImport(resolvedPath);
54259
+ return {
54260
+ configExport: module.default,
54261
+ dependencies
54262
+ };
54263
+ }
54264
+ async function bundleAndLoadConfigFile(resolvedPath) {
54265
+ const isESM = typeof process.versions.deno === "string" || isFilePathESM(resolvedPath);
54266
+ const bundled = await bundleConfigFile(resolvedPath, isESM);
54267
+ const userConfig = await loadConfigFromBundledFile(
54268
+ resolvedPath,
54269
+ bundled.code,
54270
+ isESM
54271
+ );
54272
+ return {
54273
+ configExport: userConfig,
54274
+ dependencies: bundled.dependencies
54275
+ };
54276
+ }
53980
54277
  async function bundleConfigFile(fileName, isESM) {
53981
54278
  const isModuleSyncConditionEnabled = (await import('#module-sync-enabled')).default;
53982
54279
  const dirnameVarName = "__vite_injected_original_dirname";
@@ -54026,7 +54323,8 @@ async function bundleConfigFile(fileName, isESM) {
54026
54323
  extensions: configDefaults.resolve.extensions,
54027
54324
  preserveSymlinks: false,
54028
54325
  packageCache,
54029
- isRequire
54326
+ isRequire,
54327
+ builtins: nodeLikeBuiltins
54030
54328
  })?.id;
54031
54329
  };
54032
54330
  build2.onResolve(
@@ -54035,7 +54333,7 @@ async function bundleConfigFile(fileName, isESM) {
54035
54333
  if (kind === "entry-point" || path$d.isAbsolute(id) || isNodeBuiltin(id)) {
54036
54334
  return;
54037
54335
  }
54038
- if (isBuiltin(id)) {
54336
+ if (isNodeLikeBuiltin(id)) {
54039
54337
  return { external: true };
54040
54338
  }
54041
54339
  const isImport = isESM || kind === "dynamic-import";
@@ -54203,4 +54501,4 @@ function optimizeDepsDisabledBackwardCompatibility(resolved, optimizeDeps, optim
54203
54501
  }
54204
54502
  }
54205
54503
 
54206
- export { mergeAlias as A, BuildEnvironment as B, createFilter as C, DevEnvironment as D, rollupVersion as E, send$1 as F, createLogger as G, searchForWorkspaceRoot as H, isFileServingAllowed as I, isFileLoadingAllowed as J, loadEnv as K, resolveEnvPrefix as L, colors$1 as M, getDefaultExportFromCjs as N, commonjsGlobal as O, index$1 as P, index as Q, build$1 as R, preview$1 as S, arraify as a, perEnvironmentState as b, createServer as c, defineConfig as d, preview as e, build as f, createBuilder as g, createIdResolver as h, isInNodeModules$1 as i, formatPostcssSourceMap as j, preprocessCSS as k, loadConfigFromFile as l, buildErrorMessage as m, createRunnableDevEnvironment as n, optimizeDeps as o, perEnvironmentPlugin as p, isRunnableDevEnvironment as q, resolveConfig as r, sortUserPlugins as s, transformWithEsbuild as t, fetchModule as u, createServerModuleRunner as v, createServerHotChannel as w, ssrTransform as x, normalizePath$3 as y, mergeConfig as z };
54504
+ export { normalizePath$3 as A, BuildEnvironment as B, mergeConfig as C, DevEnvironment as D, mergeAlias as E, createFilter as F, rollupVersion as G, send$1 as H, createLogger as I, searchForWorkspaceRoot as J, isFileServingAllowed as K, isFileLoadingAllowed as L, loadEnv as M, resolveEnvPrefix as N, colors$1 as O, getDefaultExportFromCjs as P, commonjsGlobal as Q, index$1 as R, index as S, build$1 as T, preview$1 as U, arraify as a, perEnvironmentState as b, createServer as c, defineConfig as d, preview as e, build as f, createBuilder as g, createIdResolver as h, isInNodeModules$1 as i, formatPostcssSourceMap as j, preprocessCSS as k, loadConfigFromFile as l, buildErrorMessage as m, createRunnableDevEnvironment as n, optimizeDeps as o, perEnvironmentPlugin as p, isRunnableDevEnvironment as q, resolveConfig as r, sortUserPlugins as s, transformWithEsbuild as t, runnerImport as u, fetchModule as v, createServerModuleRunner as w, createServerModuleRunnerTransport as x, createServerHotChannel as y, ssrTransform as z };