vite 6.0.11 → 6.1.0-beta.1

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,7 +1,7 @@
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';
@@ -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)));
@@ -16084,7 +16097,8 @@ function resolvePlugin(resolveOptions) {
16084
16097
  }
16085
16098
  }
16086
16099
  if (id.startsWith("file://")) {
16087
- id = fileURLToPath$1(id);
16100
+ const { file, postfix } = splitFileAndPostfix(id);
16101
+ id = fileURLToPath$1(file) + postfix;
16088
16102
  }
16089
16103
  if (isWindows$3 && id[0] === "/") {
16090
16104
  const basedir = importer ? path$d.dirname(importer) : process.cwd();
@@ -16127,34 +16141,45 @@ function resolvePlugin(resolveOptions) {
16127
16141
  if (res = tryNodeResolve(id, importer, options, depsOptimizer, external)) {
16128
16142
  return res;
16129
16143
  }
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);
16144
+ if (currentEnvironmentOptions.consumer === "server" && isBuiltin(options.builtins, id)) {
16145
+ return options.idOnly ? id : { id, external: true, moduleSideEffects: false };
16146
+ } else if (currentEnvironmentOptions.consumer === "server" && isNodeLikeBuiltin(id)) {
16147
+ if (!(options.external === true || options.external.includes(id))) {
16148
+ let message = `Automatically externalized node built-in module "${id}"`;
16149
+ if (importer) {
16150
+ message += ` imported from "${path$d.relative(
16151
+ process.cwd(),
16152
+ importer
16153
+ )}"`;
16144
16154
  }
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
- );
16155
+ message += `. Consider adding it to environments.${this.environment.name}.external if it is intended.`;
16156
+ this.warn(message);
16157
+ }
16158
+ return options.idOnly ? id : { id, external: true, moduleSideEffects: false };
16159
+ } else if (currentEnvironmentOptions.consumer === "client" && isNodeLikeBuiltin(id)) {
16160
+ if (options.noExternal === true && // if both noExternal and external are true, noExternal will take the higher priority and bundle it.
16161
+ // only if the id is explicitly listed in external, we will externalize it and skip this error.
16162
+ (options.external === true || !options.external.includes(id))) {
16163
+ let message = `Cannot bundle built-in module "${id}"`;
16164
+ if (importer) {
16165
+ message += ` imported from "${path$d.relative(
16166
+ process.cwd(),
16167
+ importer
16168
+ )}"`;
16155
16169
  }
16156
- return isProduction ? browserExternalId : `${browserExternalId}:${id}`;
16170
+ message += `. Consider disabling environments.${this.environment.name}.noExternal or remove the built-in dependency.`;
16171
+ this.error(message);
16157
16172
  }
16173
+ if (!asSrc) {
16174
+ debug$e?.(
16175
+ `externalized node built-in "${id}" to empty module. (imported by: ${colors$1.white(colors$1.dim(importer))})`
16176
+ );
16177
+ } else if (isProduction) {
16178
+ this.warn(
16179
+ `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.`
16180
+ );
16181
+ }
16182
+ return isProduction ? browserExternalId : `${browserExternalId}:${id}`;
16158
16183
  }
16159
16184
  }
16160
16185
  debug$e?.(`[fallthrough] ${colors$1.dim(id)}`);
@@ -16237,7 +16262,7 @@ function tryCleanFsResolve(file, options, tryIndex = true, skipPackageJson = fal
16237
16262
  const fileResult = tryResolveRealFileOrType(file, options.preserveSymlinks);
16238
16263
  if (fileResult?.path) return fileResult.path;
16239
16264
  let res;
16240
- const possibleJsToTs = options.isFromTsImporter && isPossibleTsOutput(file);
16265
+ const possibleJsToTs = isPossibleTsOutput(file);
16241
16266
  if (possibleJsToTs || options.extensions.length || tryPrefix) {
16242
16267
  const dirPath = path$d.dirname(file);
16243
16268
  if (isDirectory(dirPath)) {
@@ -16316,15 +16341,16 @@ function tryNodeResolve(id, importer, options, depsOptimizer, externalize) {
16316
16341
  } else {
16317
16342
  basedir = root;
16318
16343
  }
16344
+ const isModuleBuiltin = (id2) => isBuiltin(options.builtins, id2);
16319
16345
  let selfPkg = null;
16320
- if (!isBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
16346
+ if (!isModuleBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
16321
16347
  const selfPackageData = findNearestPackageData(basedir, packageCache);
16322
16348
  selfPkg = selfPackageData?.data.exports && selfPackageData.data.name === pkgId ? selfPackageData : null;
16323
16349
  }
16324
16350
  const pkg = selfPkg || resolvePackageData(pkgId, basedir, preserveSymlinks, packageCache);
16325
16351
  if (!pkg) {
16326
16352
  if (basedir !== root && // root has no peer dep
16327
- !isBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
16353
+ !isModuleBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
16328
16354
  const mainPkg = findNearestMainPackageData(basedir, packageCache)?.data;
16329
16355
  if (mainPkg) {
16330
16356
  const pkgName = getNpmPackageName(id);
@@ -16720,7 +16746,7 @@ function esbuildDepPlugin(environment, qualified, external) {
16720
16746
  namespace: "optional-peer-dep"
16721
16747
  };
16722
16748
  }
16723
- if (environment.config.consumer === "server" && isBuiltin(resolved)) {
16749
+ if (isBuiltin(environment.config.resolve.builtins, resolved)) {
16724
16750
  return;
16725
16751
  }
16726
16752
  if (isExternalUrl(resolved)) {
@@ -17965,7 +17991,6 @@ class ScanEnvironment extends BaseEnvironment {
17965
17991
  this,
17966
17992
  this.plugins
17967
17993
  );
17968
- await this._pluginContainer.buildStart();
17969
17994
  }
17970
17995
  }
17971
17996
  function devToScanEnvironment(environment) {
@@ -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"
@@ -30777,9 +30807,9 @@ async function instantiateModule(url, runner, environment, fixStacktrace) {
30777
30807
  ssrFixStacktrace(e, environment.moduleGraph);
30778
30808
  }
30779
30809
  environment.logger.error(
30780
- colors$1.red(`Error when evaluating SSR module ${url}:
30781
- |- ${e.stack}
30782
- `),
30810
+ buildErrorMessage(e, [
30811
+ colors$1.red(`Error when evaluating SSR module ${url}: ${e.message}`)
30812
+ ]),
30783
30813
  {
30784
30814
  timestamp: true,
30785
30815
  clear: environment.config.clearScreen,
@@ -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(),
@@ -31553,7 +31588,7 @@ function isRefIdentifier(id, parent, parentStack) {
31553
31588
  if (parent.type === "MemberExpression" && parent.property === id && !parent.computed) {
31554
31589
  return false;
31555
31590
  }
31556
- if (parent.type === "ExportSpecifier") {
31591
+ if (parent.type === "ExportSpecifier" || parent.type === "ExportAllDeclaration") {
31557
31592
  return false;
31558
31593
  }
31559
31594
  if (id.name === "arguments") {
@@ -37784,7 +37819,7 @@ const wsServerEvents = [
37784
37819
  "listening",
37785
37820
  "message"
37786
37821
  ];
37787
- function noop$3() {
37822
+ function noop$2() {
37788
37823
  }
37789
37824
  function hasValidToken(config, url) {
37790
37825
  const token = url.searchParams.get("token");
@@ -37808,9 +37843,9 @@ function createWebSocketServer(server, config, httpsOptions) {
37808
37843
  },
37809
37844
  async close() {
37810
37845
  },
37811
- on: noop$3,
37812
- off: noop$3,
37813
- setInvokeHandler: noop$3,
37846
+ on: noop$2,
37847
+ off: noop$2,
37848
+ setInvokeHandler: noop$2,
37814
37849
  handleInvoke: async () => ({
37815
37850
  error: {
37816
37851
  name: "TransportError",
@@ -37818,8 +37853,8 @@ function createWebSocketServer(server, config, httpsOptions) {
37818
37853
  stack: new Error().stack
37819
37854
  }
37820
37855
  }),
37821
- listen: noop$3,
37822
- send: noop$3
37856
+ listen: noop$2,
37857
+ send: noop$2
37823
37858
  };
37824
37859
  }
37825
37860
  let wsHttpServer = undefined;
@@ -37905,7 +37940,9 @@ function createWebSocketServer(server, config, httpsOptions) {
37905
37940
  wsHttpServer.on("error", (e) => {
37906
37941
  if (e.code === "EADDRINUSE") {
37907
37942
  config.logger.error(
37908
- colors$1.red(`WebSocket server error: Port is already in use`),
37943
+ colors$1.red(
37944
+ `WebSocket server error: Port ${e.port} is already in use`
37945
+ ),
37909
37946
  { error: e }
37910
37947
  );
37911
37948
  } else {
@@ -37949,7 +37986,7 @@ ${err.stack}`, {
37949
37986
  wss.on("error", (e) => {
37950
37987
  if (e.code === "EADDRINUSE") {
37951
37988
  config.logger.error(
37952
- colors$1.red(`WebSocket server error: Port is already in use`),
37989
+ colors$1.red(`WebSocket server error: Port ${e.port} is already in use`),
37953
37990
  { error: e }
37954
37991
  );
37955
37992
  } else {
@@ -38981,7 +39018,7 @@ var WriteAfterEndError = createErrorType(
38981
39018
  );
38982
39019
 
38983
39020
  // istanbul ignore next
38984
- var destroy = Writable.prototype.destroy || noop$2;
39021
+ var destroy = Writable.prototype.destroy || noop$1;
38985
39022
 
38986
39023
  // An HTTP(S) request that can be redirected
38987
39024
  function RedirectableRequest(options, responseCallback) {
@@ -39465,7 +39502,7 @@ function wrap(protocols) {
39465
39502
  return exports;
39466
39503
  }
39467
39504
 
39468
- function noop$2() { /* empty */ }
39505
+ function noop$1() { /* empty */ }
39469
39506
 
39470
39507
  function parseUrl(input) {
39471
39508
  var parsed;
@@ -39561,7 +39598,7 @@ function destroyRequest(request, error) {
39561
39598
  for (var event of events) {
39562
39599
  request.removeListener(event, eventHandlers[event]);
39563
39600
  }
39564
- request.on("error", noop$2);
39601
+ request.on("error", noop$1);
39565
39602
  request.destroy(error);
39566
39603
  }
39567
39604
 
@@ -40311,21 +40348,34 @@ ${err.stack}`,
40311
40348
  proxies[context] = [proxy, { ...opts }];
40312
40349
  });
40313
40350
  if (httpServer) {
40314
- httpServer.on("upgrade", (req, socket, head) => {
40351
+ httpServer.on("upgrade", async (req, socket, head) => {
40315
40352
  const url = req.url;
40316
40353
  for (const context in proxies) {
40317
40354
  if (doesProxyContextMatchUrl(context, url)) {
40318
40355
  const [proxy, opts] = proxies[context];
40319
40356
  if (opts.ws || opts.target?.toString().startsWith("ws:") || opts.target?.toString().startsWith("wss:")) {
40320
40357
  if (opts.bypass) {
40321
- const bypassResult = opts.bypass(req, undefined, opts);
40322
- if (typeof bypassResult === "string") {
40323
- req.url = bypassResult;
40324
- debug$5?.(`bypass: ${req.url} -> ${bypassResult}`);
40325
- return;
40326
- } else if (bypassResult === false) {
40327
- debug$5?.(`bypass: ${req.url} -> 404`);
40328
- socket.end("HTTP/1.1 404 Not Found\r\n\r\n", "");
40358
+ try {
40359
+ const bypassResult = await opts.bypass(req, undefined, opts);
40360
+ if (typeof bypassResult === "string") {
40361
+ debug$5?.(`bypass: ${req.url} -> ${bypassResult}`);
40362
+ req.url = bypassResult;
40363
+ return;
40364
+ }
40365
+ if (bypassResult === false) {
40366
+ debug$5?.(`bypass: ${req.url} -> 404`);
40367
+ socket.end("HTTP/1.1 404 Not Found\r\n\r\n", "");
40368
+ return;
40369
+ }
40370
+ } catch (err) {
40371
+ config.logger.error(
40372
+ `${colors$1.red(`ws proxy bypass error:`)}
40373
+ ${err.stack}`,
40374
+ {
40375
+ timestamp: true,
40376
+ error: err
40377
+ }
40378
+ );
40329
40379
  return;
40330
40380
  }
40331
40381
  }
@@ -40340,22 +40390,31 @@ ${err.stack}`,
40340
40390
  }
40341
40391
  });
40342
40392
  }
40343
- return function viteProxyMiddleware(req, res, next) {
40393
+ return async function viteProxyMiddleware(req, res, next) {
40344
40394
  const url = req.url;
40345
40395
  for (const context in proxies) {
40346
40396
  if (doesProxyContextMatchUrl(context, url)) {
40347
40397
  const [proxy, opts] = proxies[context];
40348
40398
  const options2 = {};
40349
40399
  if (opts.bypass) {
40350
- const bypassResult = opts.bypass(req, res, opts);
40351
- if (typeof bypassResult === "string") {
40352
- req.url = bypassResult;
40353
- debug$5?.(`bypass: ${req.url} -> ${bypassResult}`);
40354
- return next();
40355
- } else if (bypassResult === false) {
40356
- debug$5?.(`bypass: ${req.url} -> 404`);
40357
- res.statusCode = 404;
40358
- return res.end();
40400
+ try {
40401
+ const bypassResult = await opts.bypass(req, res, opts);
40402
+ if (typeof bypassResult === "string") {
40403
+ debug$5?.(`bypass: ${req.url} -> ${bypassResult}`);
40404
+ req.url = bypassResult;
40405
+ if (res.writableEnded) {
40406
+ return;
40407
+ }
40408
+ return next();
40409
+ }
40410
+ if (bypassResult === false) {
40411
+ debug$5?.(`bypass: ${req.url} -> 404`);
40412
+ res.statusCode = 404;
40413
+ return res.end();
40414
+ }
40415
+ } catch (e) {
40416
+ debug$5?.(`bypass: ${req.url} -> ${e}`);
40417
+ return next(e);
40359
40418
  }
40360
40419
  }
40361
40420
  debug$5?.(`${req.url} -> ${opts.target || opts.forward}`);
@@ -40663,7 +40722,7 @@ function parse(req) {
40663
40722
  return req._parsedUrl = { pathname, search, query, raw };
40664
40723
  }
40665
40724
 
40666
- const noop$1 = () => {};
40725
+ const noop = () => {};
40667
40726
 
40668
40727
  function isMatch(uri, arr) {
40669
40728
  for (let i=0; i < arr.length; i++) {
@@ -40779,7 +40838,7 @@ function sirv (dir, opts={}) {
40779
40838
  dir = resolve$4(dir || '.');
40780
40839
 
40781
40840
  let isNotFound = opts.onNoMatch || is404;
40782
- let setHeaders = opts.setHeaders || noop$1;
40841
+ let setHeaders = opts.setHeaders || noop;
40783
40842
 
40784
40843
  let extensions = opts.extensions || ['html', 'htm'];
40785
40844
  let gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz');
@@ -44241,9 +44300,7 @@ async function restartServer(server) {
44241
44300
  let inlineConfig = server.config.inlineConfig;
44242
44301
  if (server._forceOptimizeOnRestart) {
44243
44302
  inlineConfig = mergeConfig(inlineConfig, {
44244
- optimizeDeps: {
44245
- force: true
44246
- }
44303
+ forceOptimizeDeps: true
44247
44304
  });
44248
44305
  }
44249
44306
  {
@@ -44786,7 +44843,9 @@ function propagateUpdate(node, traversedModules, boundaries, currentChain = [nod
44786
44843
  if (!node.importers.size) {
44787
44844
  return true;
44788
44845
  }
44789
- if (!isCSSRequest(node.url) && [...node.importers].every((i) => isCSSRequest(i.url))) {
44846
+ if (!isCSSRequest(node.url) && // we assume .svg is never an entrypoint and does not need a full reload
44847
+ // to avoid frequent full reloads when an SVG file is referenced in CSS files (#18979)
44848
+ !node.file?.endsWith(".svg") && [...node.importers].every((i) => isCSSRequest(i.url))) {
44790
44849
  return true;
44791
44850
  }
44792
44851
  }
@@ -45250,8 +45309,8 @@ async function bundleWorkerEntry(config, id) {
45250
45309
  plugins: workerEnvironment.plugins.map(
45251
45310
  (p) => injectEnvironmentToHooks(workerEnvironment, p)
45252
45311
  ),
45253
- onwarn(warning, warn) {
45254
- onRollupWarning(warning, warn, workerEnvironment);
45312
+ onLog(level, log) {
45313
+ onRollupLog(level, log, workerEnvironment);
45255
45314
  },
45256
45315
  preserveEntrySignatures: false
45257
45316
  });
@@ -45811,7 +45870,7 @@ function importAnalysisPlugin(config) {
45811
45870
  });
45812
45871
  if (!resolved || resolved.meta?.["vite:alias"]?.noResolved) {
45813
45872
  if (ssr) {
45814
- return [url, url];
45873
+ return [url, null];
45815
45874
  }
45816
45875
  importerModule.isSelfAccepting = false;
45817
45876
  moduleGraph._hasResolveFailedErrorModules.add(importerModule);
@@ -45837,21 +45896,21 @@ function importAnalysisPlugin(config) {
45837
45896
  url = injectQuery(url, versionMatch[1]);
45838
45897
  }
45839
45898
  }
45840
- try {
45841
- const depModule = await moduleGraph._ensureEntryFromUrl(
45842
- unwrapId$1(url),
45843
- canSkipImportAnalysis(url) || forceSkipImportAnalysis,
45844
- resolved
45845
- );
45846
- if (depModule.lastHMRTimestamp > 0) {
45847
- url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`);
45848
- }
45849
- } catch (e) {
45850
- e.pos = pos;
45851
- throw e;
45899
+ }
45900
+ try {
45901
+ const depModule = await moduleGraph._ensureEntryFromUrl(
45902
+ unwrapId$1(url),
45903
+ canSkipImportAnalysis(url) || forceSkipImportAnalysis,
45904
+ resolved
45905
+ );
45906
+ if (environment.config.consumer === "client" && depModule.lastHMRTimestamp > 0) {
45907
+ url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`);
45852
45908
  }
45853
- if (!ssr) url = joinUrlSegments(base, url);
45909
+ } catch (e) {
45910
+ e.pos = pos;
45911
+ throw e;
45854
45912
  }
45913
+ if (!ssr) url = joinUrlSegments(base, url);
45855
45914
  return [url, resolved.id];
45856
45915
  };
45857
45916
  const orderedImportedUrls = new Array(imports.length);
@@ -45919,7 +45978,7 @@ function importAnalysisPlugin(config) {
45919
45978
  if (shouldExternalize(environment, specifier, importer)) {
45920
45979
  return;
45921
45980
  }
45922
- if (isBuiltin(specifier)) {
45981
+ if (isBuiltin(environment.config.resolve.builtins, specifier)) {
45923
45982
  return;
45924
45983
  }
45925
45984
  }
@@ -45934,7 +45993,8 @@ function importAnalysisPlugin(config) {
45934
45993
  )} instead.`
45935
45994
  );
45936
45995
  }
45937
- const [url, resolvedId] = await normalizeUrl(specifier, start);
45996
+ let [url, resolvedId] = await normalizeUrl(specifier, start);
45997
+ resolvedId = resolvedId || url;
45938
45998
  config.safeModulePaths.add(fsPathFromUrl(stripBase(url, base)));
45939
45999
  if (url !== specifier) {
45940
46000
  let rewriteDone = false;
@@ -46069,9 +46129,37 @@ See ${colors$1.blue(
46069
46129
  }
46070
46130
  const normalizedAcceptedUrls = /* @__PURE__ */ new Set();
46071
46131
  for (const { url, start, end } of acceptedUrls) {
46072
- const [normalized] = await moduleGraph.resolveUrl(toAbsoluteUrl(url));
46132
+ let [normalized, resolvedId] = await normalizeUrl(url, start).catch(
46133
+ () => []
46134
+ );
46135
+ if (resolvedId) {
46136
+ const mod = moduleGraph.getModuleById(resolvedId);
46137
+ if (!mod) {
46138
+ this.error(
46139
+ `module was not found for ${JSON.stringify(resolvedId)}`,
46140
+ start
46141
+ );
46142
+ return;
46143
+ }
46144
+ normalized = mod.url;
46145
+ } else {
46146
+ try {
46147
+ const [resolved] = await moduleGraph.resolveUrl(toAbsoluteUrl(url));
46148
+ normalized = resolved;
46149
+ if (resolved) {
46150
+ this.warn({
46151
+ message: `Failed to resolve ${JSON.stringify(url)} from ${importer}. An id should be written. Did you pass a URL?`,
46152
+ pos: start
46153
+ });
46154
+ }
46155
+ } catch {
46156
+ this.error(`Failed to resolve ${JSON.stringify(url)}`, start);
46157
+ return;
46158
+ }
46159
+ }
46073
46160
  normalizedAcceptedUrls.add(normalized);
46074
- str().overwrite(start, end, JSON.stringify(normalized), {
46161
+ const hmrAccept = normalizeHmrUrl(normalized);
46162
+ str().overwrite(start, end, JSON.stringify(hmrAccept), {
46075
46163
  contentOnly: true
46076
46164
  });
46077
46165
  }
@@ -46431,13 +46519,62 @@ function err(e, pos) {
46431
46519
  error.pos = pos;
46432
46520
  return error;
46433
46521
  }
46434
- function parseWorkerOptions(rawOpts, optsStartIndex) {
46522
+ function findClosingParen(input, fromIndex) {
46523
+ let count = 1;
46524
+ for (let i = fromIndex + 1; i < input.length; i++) {
46525
+ if (input[i] === "(") count++;
46526
+ if (input[i] === ")") count--;
46527
+ if (count === 0) return i;
46528
+ }
46529
+ return -1;
46530
+ }
46531
+ function extractWorkerTypeFromAst(expression, optsStartIndex) {
46532
+ if (expression.type !== "ObjectExpression") {
46533
+ return;
46534
+ }
46535
+ let lastSpreadElementIndex = -1;
46536
+ let typeProperty = null;
46537
+ let typePropertyIndex = -1;
46538
+ for (let i = 0; i < expression.properties.length; i++) {
46539
+ const property = expression.properties[i];
46540
+ if (property.type === "SpreadElement") {
46541
+ lastSpreadElementIndex = i;
46542
+ continue;
46543
+ }
46544
+ if (property.type === "Property" && (property.key.type === "Identifier" && property.key.name === "type" || property.key.type === "Literal" && property.key.value === "type")) {
46545
+ typeProperty = property;
46546
+ typePropertyIndex = i;
46547
+ }
46548
+ }
46549
+ if (typePropertyIndex === -1 && lastSpreadElementIndex === -1) {
46550
+ return "classic";
46551
+ }
46552
+ if (typePropertyIndex < lastSpreadElementIndex) {
46553
+ throw err(
46554
+ "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.",
46555
+ optsStartIndex
46556
+ );
46557
+ }
46558
+ if (typeProperty?.value.type !== "Literal") {
46559
+ throw err(
46560
+ "Expected worker options type property to be a literal value.",
46561
+ optsStartIndex
46562
+ );
46563
+ }
46564
+ return typeProperty?.value.value === "module" ? "module" : "classic";
46565
+ }
46566
+ async function parseWorkerOptions(rawOpts, optsStartIndex) {
46435
46567
  let opts = {};
46436
46568
  try {
46437
46569
  opts = evalValue(rawOpts);
46438
46570
  } catch {
46571
+ const optsNode = (await parseAstAsync(`(${rawOpts})`)).body[0].expression;
46572
+ const type = extractWorkerTypeFromAst(optsNode, optsStartIndex);
46573
+ if (type) {
46574
+ return { type };
46575
+ }
46439
46576
  throw err(
46440
- "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.",
46577
+ "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.",
46441
46578
  optsStartIndex
46442
46579
  );
46443
46580
  }
@@ -46452,12 +46589,12 @@ function parseWorkerOptions(rawOpts, optsStartIndex) {
46452
46589
  }
46453
46590
  return opts;
46454
46591
  }
46455
- function getWorkerType(raw, clean, i) {
46592
+ async function getWorkerType(raw, clean, i) {
46456
46593
  const commaIndex = clean.indexOf(",", i);
46457
46594
  if (commaIndex === -1) {
46458
46595
  return "classic";
46459
46596
  }
46460
- const endIndex = clean.indexOf(")", i);
46597
+ const endIndex = findClosingParen(clean, i);
46461
46598
  if (commaIndex > endIndex) {
46462
46599
  return "classic";
46463
46600
  }
@@ -46470,7 +46607,7 @@ function getWorkerType(raw, clean, i) {
46470
46607
  if (!cleanWorkerOptString.length) {
46471
46608
  return "classic";
46472
46609
  }
46473
- const workerOpts = parseWorkerOptions(workerOptString, commaIndex + 1);
46610
+ const workerOpts = await parseWorkerOptions(workerOptString, commaIndex + 1);
46474
46611
  if (workerOpts.type && (workerOpts.type === "module" || workerOpts.type === "classic")) {
46475
46612
  return workerOpts.type;
46476
46613
  }
@@ -46516,12 +46653,12 @@ function workerImportMetaUrlPlugin(config) {
46516
46653
  );
46517
46654
  }
46518
46655
  s ||= new MagicString(code);
46519
- const workerType = getWorkerType(code, cleanString, endIndex);
46656
+ const workerType = await getWorkerType(code, cleanString, endIndex);
46520
46657
  const url = rawUrl.slice(1, -1);
46521
46658
  let file;
46522
46659
  if (url[0] === ".") {
46523
46660
  file = path$d.resolve(path$d.dirname(id), url);
46524
- file = tryFsResolve(file, fsResolveOptions) ?? file;
46661
+ file = slash$1(tryFsResolve(file, fsResolveOptions) ?? file);
46525
46662
  } else {
46526
46663
  workerResolver ??= createBackCompatIdResolver(config, {
46527
46664
  extensions: [],
@@ -47113,8 +47250,6 @@ const viteAliasCustomResolver = async function(id, importer, options) {
47113
47250
  return resolved || { id, meta: { "vite:alias": { noResolved: true } } };
47114
47251
  };
47115
47252
 
47116
- const noop = () => {
47117
- };
47118
47253
  const EMPTY_OBJECT = Object.freeze({});
47119
47254
  const debugSourcemapCombineFilter = process.env.DEBUG_VITE_SOURCEMAP_COMBINE_FILTER;
47120
47255
  const debugSourcemapCombine = createDebugger("vite:sourcemap-combine", {
@@ -47127,6 +47262,9 @@ const debugPluginResolve = createDebugger("vite:plugin-resolve", {
47127
47262
  const debugPluginTransform = createDebugger("vite:plugin-transform", {
47128
47263
  onlyWhenFocused: "vite:plugin"
47129
47264
  });
47265
+ const debugPluginContainerContext = createDebugger(
47266
+ "vite:plugin-container-context"
47267
+ );
47130
47268
  const ERR_CLOSED_SERVER = "ERR_CLOSED_SERVER";
47131
47269
  function throwClosedServerError() {
47132
47270
  const err = new Error(
@@ -47152,18 +47290,10 @@ class EnvironmentPluginContainer {
47152
47290
  this.environment = environment;
47153
47291
  this.plugins = plugins;
47154
47292
  this.watcher = watcher;
47155
- this.minimalContext = {
47156
- meta: {
47157
- rollupVersion,
47158
- watchMode: true
47159
- },
47160
- debug: noop,
47161
- info: noop,
47162
- warn: noop,
47163
- // @ts-expect-error noop
47164
- error: noop,
47293
+ this.minimalContext = new MinimalPluginContext(
47294
+ { rollupVersion, watchMode: true },
47165
47295
  environment
47166
- };
47296
+ );
47167
47297
  const utils = createPluginHookUtils(plugins);
47168
47298
  this.getSortedPlugins = utils.getSortedPlugins;
47169
47299
  this.getSortedPluginHooks = utils.getSortedPluginHooks;
@@ -47454,12 +47584,44 @@ class EnvironmentPluginContainer {
47454
47584
  );
47455
47585
  }
47456
47586
  }
47457
- class PluginContext {
47587
+ class MinimalPluginContext {
47588
+ constructor(meta, environment) {
47589
+ this.meta = meta;
47590
+ this.environment = environment;
47591
+ }
47592
+ debug(rawLog) {
47593
+ const log = this._normalizeRawLog(rawLog);
47594
+ const msg = buildErrorMessage(log, [`debug: ${log.message}`], false);
47595
+ debugPluginContainerContext?.(msg);
47596
+ }
47597
+ info(rawLog) {
47598
+ const log = this._normalizeRawLog(rawLog);
47599
+ const msg = buildErrorMessage(log, [`info: ${log.message}`], false);
47600
+ this.environment.logger.info(msg, { clear: true, timestamp: true });
47601
+ }
47602
+ warn(rawLog) {
47603
+ const log = this._normalizeRawLog(rawLog);
47604
+ const msg = buildErrorMessage(
47605
+ log,
47606
+ [colors$1.yellow(`warning: ${log.message}`)],
47607
+ false
47608
+ );
47609
+ this.environment.logger.warn(msg, { clear: true, timestamp: true });
47610
+ }
47611
+ error(e) {
47612
+ const err = typeof e === "string" ? new Error(e) : e;
47613
+ throw err;
47614
+ }
47615
+ _normalizeRawLog(rawLog) {
47616
+ const logValue = typeof rawLog === "function" ? rawLog() : rawLog;
47617
+ return typeof logValue === "string" ? new Error(logValue) : logValue;
47618
+ }
47619
+ }
47620
+ class PluginContext extends MinimalPluginContext {
47458
47621
  constructor(_plugin, _container) {
47622
+ super(_container.minimalContext.meta, _container.environment);
47459
47623
  this._plugin = _plugin;
47460
47624
  this._container = _container;
47461
- this.environment = this._container.environment;
47462
- this.meta = this._container.minimalContext.meta;
47463
47625
  }
47464
47626
  ssr = false;
47465
47627
  _scan = false;
@@ -47467,8 +47629,6 @@ class PluginContext {
47467
47629
  _activeCode = null;
47468
47630
  _resolveSkips;
47469
47631
  _resolveSkipCalls;
47470
- meta;
47471
- environment;
47472
47632
  parse(code, opts) {
47473
47633
  return parseAst(code, opts);
47474
47634
  }
@@ -47553,24 +47713,25 @@ class PluginContext {
47553
47713
  this._warnIncompatibleMethod(`getFileName`);
47554
47714
  return "";
47555
47715
  }
47556
- warn(e, position) {
47557
- const err = this._formatError(typeof e === "function" ? e() : e, position);
47558
- const msg = buildErrorMessage(
47559
- err,
47560
- [colors$1.yellow(`warning: ${err.message}`)],
47561
- false
47716
+ debug(log) {
47717
+ const err = this._formatLog(typeof log === "function" ? log() : log);
47718
+ super.debug(err);
47719
+ }
47720
+ info(log) {
47721
+ const err = this._formatLog(typeof log === "function" ? log() : log);
47722
+ super.info(err);
47723
+ }
47724
+ warn(log, position) {
47725
+ const err = this._formatLog(
47726
+ typeof log === "function" ? log() : log,
47727
+ position
47562
47728
  );
47563
- this.environment.logger.warn(msg, {
47564
- clear: true,
47565
- timestamp: true
47566
- });
47729
+ super.warn(err);
47567
47730
  }
47568
47731
  error(e, position) {
47569
- throw this._formatError(e, position);
47732
+ throw this._formatLog(e, position);
47570
47733
  }
47571
- debug = noop;
47572
- info = noop;
47573
- _formatError(e, position) {
47734
+ _formatLog(e, position) {
47574
47735
  const err = typeof e === "string" ? new Error(e) : e;
47575
47736
  if (err.pluginCode) {
47576
47737
  return err;
@@ -47999,20 +48160,20 @@ function cssPlugin(config) {
47999
48160
  return;
48000
48161
  }
48001
48162
  const resolveUrl = (url, importer) => idResolver(environment, url, importer);
48002
- const urlReplacer = async (url, importer) => {
48163
+ const urlResolver = async (url, importer) => {
48003
48164
  const decodedUrl = decodeURI(url);
48004
48165
  if (checkPublicFile(decodedUrl, config)) {
48005
48166
  if (encodePublicUrlsInCSS(config)) {
48006
- return publicFileToBuiltUrl(decodedUrl, config);
48167
+ return [publicFileToBuiltUrl(decodedUrl, config), undefined];
48007
48168
  } else {
48008
- return joinUrlSegments(config.base, decodedUrl);
48169
+ return [joinUrlSegments(config.base, decodedUrl), undefined];
48009
48170
  }
48010
48171
  }
48011
48172
  const [id2, fragment] = decodedUrl.split("#");
48012
48173
  let resolved = await resolveUrl(id2, importer);
48013
48174
  if (resolved) {
48014
48175
  if (fragment) resolved += "#" + fragment;
48015
- return fileToUrl$1(this, resolved);
48176
+ return [await fileToUrl$1(this, resolved), resolved];
48016
48177
  }
48017
48178
  if (config.command === "build") {
48018
48179
  const isExternal = config.build.rollupOptions.external ? resolveUserExternal(
@@ -48029,7 +48190,7 @@ ${decodedUrl} referenced in ${id2} didn't resolve at build time, it will remain
48029
48190
  );
48030
48191
  }
48031
48192
  }
48032
- return url;
48193
+ return [url, undefined];
48033
48194
  };
48034
48195
  const {
48035
48196
  code: css,
@@ -48041,7 +48202,7 @@ ${decodedUrl} referenced in ${id2} didn't resolve at build time, it will remain
48041
48202
  id,
48042
48203
  raw,
48043
48204
  preprocessorWorkerController,
48044
- urlReplacer
48205
+ urlResolver
48045
48206
  );
48046
48207
  if (modules) {
48047
48208
  moduleCache.set(id, modules);
@@ -48497,16 +48658,21 @@ function cssAnalysisPlugin(config) {
48497
48658
  if (pluginImports) {
48498
48659
  const depModules = /* @__PURE__ */ new Set();
48499
48660
  for (const file of pluginImports) {
48500
- depModules.add(
48501
- isCSSRequest(file) ? moduleGraph.createFileOnlyEntry(file) : await moduleGraph.ensureEntryFromUrl(
48502
- await fileToDevUrl(
48503
- this.environment,
48504
- file,
48505
- /* skipBase */
48506
- true
48507
- )
48508
- )
48509
- );
48661
+ if (isCSSRequest(file)) {
48662
+ depModules.add(moduleGraph.createFileOnlyEntry(file));
48663
+ } else {
48664
+ const url = await fileToDevUrl(
48665
+ this.environment,
48666
+ file,
48667
+ /* skipBase */
48668
+ true
48669
+ );
48670
+ if (url.startsWith("data:")) {
48671
+ depModules.add(moduleGraph.createFileOnlyEntry(file));
48672
+ } else {
48673
+ depModules.add(await moduleGraph.ensureEntryFromUrl(url));
48674
+ }
48675
+ }
48510
48676
  }
48511
48677
  moduleGraph.updateModuleInfo(
48512
48678
  thisModule,
@@ -48649,23 +48815,12 @@ function getAtImportResolvers(config) {
48649
48815
  }
48650
48816
  return atImportResolvers;
48651
48817
  }
48652
- async function compileCSS(environment, id, code, workerController, urlReplacer) {
48818
+ async function compileCSS(environment, id, code, workerController, urlResolver) {
48653
48819
  const { config } = environment;
48654
48820
  if (config.css.transformer === "lightningcss") {
48655
- return compileLightningCSS(id, code, environment, urlReplacer);
48821
+ return compileLightningCSS(id, code, environment, urlResolver);
48656
48822
  }
48657
- const { modules: modulesOptions, devSourcemap } = config.css;
48658
- const isModule = modulesOptions !== false && cssModuleRE.test(id);
48659
- const needInlineImport = code.includes("@import");
48660
- const hasUrl = cssUrlRE.test(code) || cssImageSetRE.test(code);
48661
48823
  const lang = CSS_LANGS_RE.exec(id)?.[1];
48662
- const postcssConfig = await resolvePostcssConfig(
48663
- environment.getTopLevelConfig()
48664
- );
48665
- if (lang === "css" && !postcssConfig && !isModule && !needInlineImport && !hasUrl) {
48666
- return { code, map: null };
48667
- }
48668
- let modules;
48669
48824
  const deps = /* @__PURE__ */ new Set();
48670
48825
  let preprocessorMap;
48671
48826
  if (isPreProcessor(lang)) {
@@ -48680,10 +48835,19 @@ async function compileCSS(environment, id, code, workerController, urlReplacer)
48680
48835
  preprocessorMap = preprocessorResult.map;
48681
48836
  preprocessorResult.deps?.forEach((dep) => deps.add(dep));
48682
48837
  }
48838
+ const { modules: modulesOptions, devSourcemap } = config.css;
48839
+ const isModule = modulesOptions !== false && cssModuleRE.test(id);
48840
+ const needInlineImport = code.includes("@import");
48841
+ const hasUrl = cssUrlRE.test(code) || cssImageSetRE.test(code);
48842
+ const postcssConfig = await resolvePostcssConfig(
48843
+ environment.getTopLevelConfig()
48844
+ );
48845
+ if (lang !== "sss" && !postcssConfig && !isModule && !needInlineImport && !hasUrl) {
48846
+ return { code, map: preprocessorMap ?? null, deps };
48847
+ }
48683
48848
  const atImportResolvers = getAtImportResolvers(
48684
48849
  environment.getTopLevelConfig()
48685
48850
  );
48686
- const postcssOptions = postcssConfig?.options ?? {};
48687
48851
  const postcssPlugins = postcssConfig?.plugins.slice() ?? [];
48688
48852
  if (needInlineImport) {
48689
48853
  postcssPlugins.unshift(
@@ -48735,14 +48899,19 @@ async function compileCSS(environment, id, code, workerController, urlReplacer)
48735
48899
  })
48736
48900
  );
48737
48901
  }
48738
- if (urlReplacer) {
48902
+ if (urlResolver && // if there's an @import, we need to add this plugin
48903
+ // regradless of whether it contains url() or image-set(),
48904
+ // because we don't know the content referenced by @import
48905
+ (needInlineImport || hasUrl)) {
48739
48906
  postcssPlugins.push(
48740
48907
  UrlRewritePostcssPlugin({
48741
- replacer: urlReplacer,
48908
+ resolver: urlResolver,
48909
+ deps,
48742
48910
  logger: environment.logger
48743
48911
  })
48744
48912
  );
48745
48913
  }
48914
+ let modules;
48746
48915
  if (isModule) {
48747
48916
  postcssPlugins.unshift(
48748
48917
  (await importPostcssModules()).default({
@@ -48770,7 +48939,9 @@ async function compileCSS(environment, id, code, workerController, urlReplacer)
48770
48939
  })
48771
48940
  );
48772
48941
  }
48773
- if (!postcssPlugins.length) {
48942
+ const postcssOptions = postcssConfig?.options ?? {};
48943
+ const postcssParser = lang === "sss" ? loadSss(config.root) : postcssOptions.parser;
48944
+ if (!postcssPlugins.length && !postcssParser) {
48774
48945
  return {
48775
48946
  code,
48776
48947
  map: preprocessorMap,
@@ -48783,7 +48954,7 @@ async function compileCSS(environment, id, code, workerController, urlReplacer)
48783
48954
  const postcss = await importPostcss();
48784
48955
  postcssResult = await postcss.default(postcssPlugins).process(code, {
48785
48956
  ...postcssOptions,
48786
- parser: lang === "sss" ? loadSss(config.root) : postcssOptions.parser,
48957
+ parser: postcssParser,
48787
48958
  to: source,
48788
48959
  from: source,
48789
48960
  ...devSourcemap ? {
@@ -48845,7 +49016,6 @@ ${generateCodeFrame(
48845
49016
  }
48846
49017
  if (!devSourcemap) {
48847
49018
  return {
48848
- ast: postcssResult,
48849
49019
  code: postcssResult.css,
48850
49020
  map: { mappings: "" },
48851
49021
  modules,
@@ -48860,7 +49030,6 @@ ${generateCodeFrame(
48860
49030
  cleanUrl(id)
48861
49031
  );
48862
49032
  return {
48863
- ast: postcssResult,
48864
49033
  code: postcssResult.css,
48865
49034
  map: combineSourcemapsIfExists(cleanUrl(id), postcssMap, preprocessorMap),
48866
49035
  modules,
@@ -48879,8 +49048,8 @@ function createCachedImport(imp) {
48879
49048
  return cached;
48880
49049
  };
48881
49050
  }
48882
- const importPostcssImport = createCachedImport(() => import('./dep-DSNpxjPn.js').then(function (n) { return n.i; }));
48883
- const importPostcssModules = createCachedImport(() => import('./dep-BSWb06ib.js').then(function (n) { return n.i; }));
49051
+ const importPostcssImport = createCachedImport(() => import('./dep-BFhA-Un-.js').then(function (n) { return n.i; }));
49052
+ const importPostcssModules = createCachedImport(() => import('./dep-B0BOsDX1.js').then(function (n) { return n.i; }));
48884
49053
  const importPostcss = createCachedImport(() => import('postcss'));
48885
49054
  const preprocessorWorkerControllerCache = /* @__PURE__ */ new WeakMap();
48886
49055
  let alwaysFakeWorkerWorkerControllerCache;
@@ -48998,8 +49167,12 @@ const UrlRewritePostcssPlugin = (opts) => {
48998
49167
  const isCssUrl = cssUrlRE.test(declaration.value);
48999
49168
  const isCssImageSet = cssImageSetRE.test(declaration.value);
49000
49169
  if (isCssUrl || isCssImageSet) {
49001
- const replacerForDeclaration = (rawUrl) => {
49002
- return opts.replacer(rawUrl, importer);
49170
+ const replacerForDeclaration = async (rawUrl) => {
49171
+ const [newUrl, resolvedId] = await opts.resolver(rawUrl, importer);
49172
+ if (newUrl.startsWith("data:") && resolvedId) {
49173
+ opts.deps.add(resolvedId);
49174
+ }
49175
+ return newUrl;
49003
49176
  };
49004
49177
  if (isCssUrl && isCssImageSet) {
49005
49178
  promises.push(
@@ -49617,13 +49790,17 @@ async function rebaseUrls(environment, file, rootFile, alias, variablePrefix, re
49617
49790
  };
49618
49791
  }
49619
49792
  const makeLessWorker = (environment, resolvers, alias, maxWorkers) => {
49620
- const viteLessResolve = async (filename, dir, rootFile) => {
49793
+ const viteLessResolve = async (filename, dir, rootFile, mime) => {
49621
49794
  const resolved = await resolvers.less(
49622
49795
  environment,
49623
49796
  filename,
49624
49797
  path$d.join(dir, "*")
49625
49798
  );
49626
49799
  if (!resolved) return undefined;
49800
+ if (mime === "application/javascript") {
49801
+ const file = path$d.resolve(resolved);
49802
+ return { resolved: file };
49803
+ }
49627
49804
  const result = await rebaseUrls(
49628
49805
  environment,
49629
49806
  resolved,
@@ -49657,7 +49834,12 @@ const makeLessWorker = (environment, resolvers, alias, maxWorkers) => {
49657
49834
  return false;
49658
49835
  }
49659
49836
  async loadFile(filename, dir, opts, env) {
49660
- const result = await viteLessResolve(filename, dir, this.rootFile);
49837
+ const result = await viteLessResolve(
49838
+ filename,
49839
+ dir,
49840
+ this.rootFile,
49841
+ opts.mime
49842
+ );
49661
49843
  if (result) {
49662
49844
  return {
49663
49845
  filename: path2.resolve(result.resolved),
@@ -49931,7 +50113,7 @@ function isPreProcessor(lang) {
49931
50113
  return lang && preprocessorSet.has(lang);
49932
50114
  }
49933
50115
  const importLightningCSS = createCachedImport(() => import('lightningcss'));
49934
- async function compileLightningCSS(id, src, environment, urlReplacer) {
50116
+ async function compileLightningCSS(id, src, environment, urlResolver) {
49935
50117
  const { config } = environment;
49936
50118
  const deps = /* @__PURE__ */ new Set();
49937
50119
  const filename = id.replace("\0", NULL_BYTE_PLACEHOLDER);
@@ -49987,6 +50169,16 @@ async function compileLightningCSS(id, src, environment, urlReplacer) {
49987
50169
  column: e.loc.column - 1
49988
50170
  // 1-based
49989
50171
  };
50172
+ try {
50173
+ const code = fs__default.readFileSync(e.fileName, "utf-8");
50174
+ 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.";
50175
+ if (/[\s;{]\*[a-zA-Z-][\w-]+\s*:/.test(code)) {
50176
+ e.message += ".\nThis file contains star property hack (e.g. `*zoom`)" + commonIeMessage;
50177
+ } else if (/min-width:\s*0\\0/.test(code)) {
50178
+ e.message += ".\nThis file contains @media zero hack (e.g. `@media (min-width: 0\\0)`)" + commonIeMessage;
50179
+ }
50180
+ } catch {
50181
+ }
49990
50182
  }
49991
50183
  throw e;
49992
50184
  }
@@ -50007,11 +50199,15 @@ ${generateCodeFrame(src, {
50007
50199
  let replaceUrl;
50008
50200
  if (skipUrlReplacer(dep.url)) {
50009
50201
  replaceUrl = dep.url;
50010
- } else if (urlReplacer) {
50011
- replaceUrl = await urlReplacer(
50202
+ } else if (urlResolver) {
50203
+ const [newUrl, resolvedId] = await urlResolver(
50012
50204
  dep.url,
50013
50205
  dep.loc.filePath.replace(NULL_BYTE_PLACEHOLDER, "\0")
50014
50206
  );
50207
+ if (newUrl.startsWith("data:") && resolvedId) {
50208
+ deps.add(resolvedId);
50209
+ }
50210
+ replaceUrl = newUrl;
50015
50211
  } else {
50016
50212
  replaceUrl = dep.url;
50017
50213
  }
@@ -50914,8 +51110,8 @@ async function buildEnvironment(environment) {
50914
51110
  input,
50915
51111
  plugins,
50916
51112
  external: options.rollupOptions.external,
50917
- onwarn(warning, warn) {
50918
- onRollupWarning(warning, warn, environment);
51113
+ onLog(level, log) {
51114
+ onRollupLog(level, log, environment);
50919
51115
  }
50920
51116
  };
50921
51117
  function extractStack(e) {
@@ -50939,7 +51135,12 @@ ${trimmedPadding}
50939
51135
  const enhanceRollupError = (e) => {
50940
51136
  const stackOnly = extractStack(e);
50941
51137
  let msg = colors$1.red((e.plugin ? `[${e.plugin}] ` : "") + e.message);
50942
- if (e.id) {
51138
+ if (e.loc && e.loc.file && e.loc.file !== e.id) {
51139
+ msg += `
51140
+ file: ${colors$1.cyan(
51141
+ `${e.loc.file}:${e.loc.line}:${e.loc.column}` + (e.id ? ` (${e.id})` : "")
51142
+ )}`;
51143
+ } else if (e.id) {
50943
51144
  msg += `
50944
51145
  file: ${colors$1.cyan(
50945
51146
  e.id + (e.loc ? `:${e.loc.line}:${e.loc.column}` : "")
@@ -51204,54 +51405,80 @@ function clearLine() {
51204
51405
  process.stdout.cursorTo(0);
51205
51406
  }
51206
51407
  }
51207
- function onRollupWarning(warning, warn, environment) {
51208
- const viteWarn = (warnLog) => {
51209
- let warning2;
51210
- if (typeof warnLog === "function") {
51211
- warning2 = warnLog();
51212
- } else {
51213
- warning2 = warnLog;
51214
- }
51215
- if (typeof warning2 === "object") {
51216
- if (warning2.code === "UNRESOLVED_IMPORT") {
51217
- const id = warning2.id;
51218
- const exporter = warning2.exporter;
51219
- if (!id || !id.endsWith("?commonjs-external")) {
51220
- throw new Error(
51221
- `[vite]: Rollup failed to resolve import "${exporter}" from "${id}".
51408
+ function onRollupLog(level, log, environment) {
51409
+ const debugLogger = createDebugger("vite:build");
51410
+ const viteLog = (logLeveling, rawLogging) => {
51411
+ const logging = typeof rawLogging === "object" ? rawLogging : { message: rawLogging };
51412
+ if (logging.code === "UNRESOLVED_IMPORT") {
51413
+ const id = logging.id;
51414
+ const exporter = logging.exporter;
51415
+ if (!id || !id.endsWith("?commonjs-external")) {
51416
+ throw new Error(
51417
+ `[vite]: Rollup failed to resolve import "${exporter}" from "${id}".
51222
51418
  This is most likely unintended because it can break your application at runtime.
51223
51419
  If you do want to externalize this module explicitly add it to
51224
51420
  \`build.rollupOptions.external\``
51225
- );
51226
- }
51421
+ );
51227
51422
  }
51228
- if (warning2.plugin === "rollup-plugin-dynamic-import-variables" && dynamicImportWarningIgnoreList.some(
51229
- (msg) => warning2.message.includes(msg)
51423
+ }
51424
+ if (logLeveling === "warn") {
51425
+ if (logging.plugin === "rollup-plugin-dynamic-import-variables" && dynamicImportWarningIgnoreList.some(
51426
+ (msg) => logging.message.includes(msg)
51230
51427
  )) {
51231
51428
  return;
51232
51429
  }
51233
- if (warningIgnoreList.includes(warning2.code)) {
51430
+ if (warningIgnoreList.includes(logging.code)) {
51234
51431
  return;
51235
51432
  }
51236
- if (warning2.code === "PLUGIN_WARNING") {
51237
- environment.logger.warn(
51238
- `${colors$1.bold(
51239
- colors$1.yellow(`[plugin:${warning2.plugin}]`)
51240
- )} ${colors$1.yellow(warning2.message)}`
51241
- );
51433
+ }
51434
+ switch (logLeveling) {
51435
+ case "info":
51436
+ environment.logger.info(logging.message);
51437
+ return;
51438
+ case "warn":
51439
+ environment.logger.warn(colors$1.yellow(logging.message));
51440
+ return;
51441
+ case "error":
51442
+ environment.logger.error(colors$1.red(logging.message));
51443
+ return;
51444
+ case "debug":
51445
+ debugLogger?.(logging.message);
51446
+ return;
51447
+ default:
51448
+ environment.logger.info(logging.message);
51242
51449
  return;
51243
- }
51244
51450
  }
51245
- warn(warnLog);
51246
51451
  };
51247
51452
  clearLine();
51248
- const userOnWarn = environment.config.build.rollupOptions.onwarn;
51249
- if (userOnWarn) {
51250
- userOnWarn(warning, viteWarn);
51453
+ const userOnLog = environment.config.build.rollupOptions?.onLog;
51454
+ const userOnWarn = environment.config.build.rollupOptions?.onwarn;
51455
+ if (userOnLog) {
51456
+ if (userOnWarn) {
51457
+ const normalizedUserOnWarn = normalizeUserOnWarn(userOnWarn, viteLog);
51458
+ userOnLog(level, log, normalizedUserOnWarn);
51459
+ } else {
51460
+ userOnLog(level, log, viteLog);
51461
+ }
51462
+ } else if (userOnWarn) {
51463
+ const normalizedUserOnWarn = normalizeUserOnWarn(userOnWarn, viteLog);
51464
+ normalizedUserOnWarn(level, log);
51251
51465
  } else {
51252
- viteWarn(warning);
51466
+ viteLog(level, log);
51253
51467
  }
51254
51468
  }
51469
+ function normalizeUserOnWarn(userOnWarn, defaultHandler) {
51470
+ return (logLevel, logging) => {
51471
+ if (logLevel === "warn") {
51472
+ userOnWarn(
51473
+ normalizeLog(logging),
51474
+ (log) => defaultHandler("warn", typeof log === "function" ? log() : log)
51475
+ );
51476
+ } else {
51477
+ defaultHandler(logLevel, logging);
51478
+ }
51479
+ };
51480
+ }
51481
+ const normalizeLog = (log) => typeof log === "string" ? { message: log } : log;
51255
51482
  function resolveUserExternal(user, id, parentId, isResolved) {
51256
51483
  if (typeof user === "function") {
51257
51484
  return user(id, parentId, isResolved);
@@ -51599,7 +51826,7 @@ var build$1 = {
51599
51826
  createBuilder: createBuilder,
51600
51827
  createToImportMetaURLBasedRelativeRuntime: createToImportMetaURLBasedRelativeRuntime,
51601
51828
  injectEnvironmentToHooks: injectEnvironmentToHooks,
51602
- onRollupWarning: onRollupWarning,
51829
+ onRollupLog: onRollupLog,
51603
51830
  resolveBuildEnvironmentOptions: resolveBuildEnvironmentOptions,
51604
51831
  resolveBuildOutputs: resolveBuildOutputs,
51605
51832
  resolveBuildPlugins: resolveBuildPlugins,
@@ -51613,7 +51840,7 @@ var build$1 = {
51613
51840
  };
51614
51841
 
51615
51842
  async function fetchModule(environment, url, importer, options = {}) {
51616
- if (url.startsWith("data:") || isBuiltin(url)) {
51843
+ if (url.startsWith("data:") || isBuiltin(environment.config.resolve.builtins, url)) {
51617
51844
  return { externalize: url, type: "builtin" };
51618
51845
  }
51619
51846
  const isFileUrl = url.startsWith("file://");
@@ -51635,7 +51862,8 @@ async function fetchModule(environment, url, importer, options = {}) {
51635
51862
  isBuild: false,
51636
51863
  isProduction,
51637
51864
  root,
51638
- packageCache: environment.config.packageCache
51865
+ packageCache: environment.config.packageCache,
51866
+ builtins: environment.config.resolve.builtins
51639
51867
  });
51640
51868
  if (!resolved) {
51641
51869
  const err = new Error(
@@ -53184,6 +53412,61 @@ function resolveSSROptions(ssr, preserveSymlinks) {
53184
53412
  return mergeWithDefaults(defaults, ssr);
53185
53413
  }
53186
53414
 
53415
+ async function runnerImport(moduleId, inlineConfig) {
53416
+ const isModuleSyncConditionEnabled = (await import('#module-sync-enabled')).default;
53417
+ const config = await resolveConfig(
53418
+ mergeConfig(inlineConfig || {}, {
53419
+ configFile: false,
53420
+ envFile: false,
53421
+ cacheDir: process.cwd(),
53422
+ environments: {
53423
+ inline: {
53424
+ consumer: "server",
53425
+ dev: {
53426
+ moduleRunnerTransform: true
53427
+ },
53428
+ resolve: {
53429
+ external: true,
53430
+ mainFields: [],
53431
+ conditions: [
53432
+ "node",
53433
+ ...isModuleSyncConditionEnabled ? ["module-sync"] : []
53434
+ ]
53435
+ }
53436
+ }
53437
+ }
53438
+ }),
53439
+ "serve"
53440
+ );
53441
+ const environment = createRunnableDevEnvironment("inline", config, {
53442
+ runnerOptions: {
53443
+ hmr: {
53444
+ logger: false
53445
+ }
53446
+ },
53447
+ hot: false
53448
+ });
53449
+ await environment.init();
53450
+ try {
53451
+ const module = await environment.runner.import(moduleId);
53452
+ const modules = [
53453
+ ...environment.runner.evaluatedModules.urlToIdModuleMap.values()
53454
+ ];
53455
+ const dependencies = modules.filter((m) => {
53456
+ if (!m.meta || "externalize" in m.meta) {
53457
+ return false;
53458
+ }
53459
+ return m.exports !== module;
53460
+ }).map((m) => m.file);
53461
+ return {
53462
+ module,
53463
+ dependencies
53464
+ };
53465
+ } finally {
53466
+ await environment.close();
53467
+ }
53468
+ }
53469
+
53187
53470
  const debug = createDebugger("vite:config", { depth: 10 });
53188
53471
  const promisifiedRealpath = promisify$4(fs__default.realpath);
53189
53472
  function defineConfig(config) {
@@ -53301,12 +53584,12 @@ const configDefaults = Object.freeze({
53301
53584
  environments: {},
53302
53585
  appType: "spa"
53303
53586
  });
53304
- function resolveDevEnvironmentOptions(dev, environmentName, consumer, skipSsrTransform) {
53587
+ function resolveDevEnvironmentOptions(dev, environmentName, consumer, skipSsrTransform, preTransformRequest) {
53305
53588
  const resolved = mergeWithDefaults(
53306
53589
  {
53307
53590
  ...configDefaults.dev,
53308
53591
  sourcemapIgnoreList: isInNodeModules$1,
53309
- preTransformRequests: consumer === "client",
53592
+ preTransformRequests: preTransformRequest ?? consumer === "client",
53310
53593
  createEnvironment: environmentName === "client" ? defaultCreateClientDevEnvironment : defaultCreateDevEnvironment,
53311
53594
  recoverable: consumer === "client",
53312
53595
  moduleRunnerTransform: skipSsrTransform !== undefined && consumer === "server" ? skipSsrTransform : consumer === "server"
@@ -53318,7 +53601,7 @@ function resolveDevEnvironmentOptions(dev, environmentName, consumer, skipSsrTra
53318
53601
  sourcemapIgnoreList: resolved.sourcemapIgnoreList === false ? () => false : resolved.sourcemapIgnoreList
53319
53602
  };
53320
53603
  }
53321
- function resolveEnvironmentOptions(options, alias, preserveSymlinks, logger, environmentName, skipSsrTransform, isSsrTargetWebworkerSet) {
53604
+ function resolveEnvironmentOptions(options, alias, preserveSymlinks, forceOptimizeDeps, logger, environmentName, skipSsrTransform, isSsrTargetWebworkerSet, preTransformRequests) {
53322
53605
  const isClientEnvironment = environmentName === "client";
53323
53606
  const consumer = options.consumer ?? (isClientEnvironment ? "client" : "server");
53324
53607
  const isSsrTargetWebworkerEnvironment = isSsrTargetWebworkerSet && environmentName === "ssr";
@@ -53338,13 +53621,15 @@ function resolveEnvironmentOptions(options, alias, preserveSymlinks, logger, env
53338
53621
  optimizeDeps: resolveDepOptimizationOptions(
53339
53622
  options.optimizeDeps,
53340
53623
  resolve.preserveSymlinks,
53624
+ forceOptimizeDeps,
53341
53625
  consumer
53342
53626
  ),
53343
53627
  dev: resolveDevEnvironmentOptions(
53344
53628
  options.dev,
53345
53629
  environmentName,
53346
53630
  consumer,
53347
- skipSsrTransform
53631
+ skipSsrTransform,
53632
+ preTransformRequests
53348
53633
  ),
53349
53634
  build: resolveBuildEnvironmentOptions(
53350
53635
  options.build ?? {},
@@ -53402,7 +53687,7 @@ function resolveEnvironmentResolveOptions(resolve, alias, preserveSymlinks, logg
53402
53687
  ...configDefaults.resolve,
53403
53688
  mainFields: consumer === undefined || consumer === "client" || isSsrTargetWebworkerEnvironment ? DEFAULT_CLIENT_MAIN_FIELDS : DEFAULT_SERVER_MAIN_FIELDS,
53404
53689
  conditions: consumer === undefined || consumer === "client" || isSsrTargetWebworkerEnvironment ? DEFAULT_CLIENT_CONDITIONS : DEFAULT_SERVER_CONDITIONS.filter((c) => c !== "browser"),
53405
- enableBuiltinNoExternalCheck: !!isSsrTargetWebworkerEnvironment
53690
+ builtins: resolve?.builtins ?? (consumer === "server" ? isSsrTargetWebworkerEnvironment && resolve?.noExternal === true ? [] : nodeLikeBuiltins : [])
53406
53691
  },
53407
53692
  resolve ?? {}
53408
53693
  );
@@ -53440,7 +53725,7 @@ function resolveResolveOptions(resolve, logger) {
53440
53725
  undefined
53441
53726
  );
53442
53727
  }
53443
- function resolveDepOptimizationOptions(optimizeDeps, preserveSymlinks, consumer) {
53728
+ function resolveDepOptimizationOptions(optimizeDeps, preserveSymlinks, forceOptimizeDeps, consumer) {
53444
53729
  return mergeWithDefaults(
53445
53730
  {
53446
53731
  ...configDefaults.optimizeDeps,
@@ -53449,7 +53734,8 @@ function resolveDepOptimizationOptions(optimizeDeps, preserveSymlinks, consumer)
53449
53734
  noDiscovery: consumer !== "client",
53450
53735
  esbuildOptions: {
53451
53736
  preserveSymlinks
53452
- }
53737
+ },
53738
+ force: forceOptimizeDeps ?? configDefaults.optimizeDeps.force
53453
53739
  },
53454
53740
  optimizeDeps ?? {}
53455
53741
  );
@@ -53476,7 +53762,8 @@ async function resolveConfig(inlineConfig, command, defaultMode = "development",
53476
53762
  configFile,
53477
53763
  config.root,
53478
53764
  config.logLevel,
53479
- config.customLogger
53765
+ config.customLogger,
53766
+ config.configLoader
53480
53767
  );
53481
53768
  if (loadResult) {
53482
53769
  config = mergeConfig(loadResult.config, config);
@@ -53599,10 +53886,12 @@ async function resolveConfig(inlineConfig, command, defaultMode = "development",
53599
53886
  config.environments[environmentName],
53600
53887
  resolvedDefaultResolve.alias,
53601
53888
  resolvedDefaultResolve.preserveSymlinks,
53889
+ inlineConfig.forceOptimizeDeps,
53602
53890
  logger,
53603
53891
  environmentName,
53604
53892
  config.experimental?.skipSsrTransform,
53605
- config.ssr?.target === "webworker"
53893
+ config.ssr?.target === "webworker",
53894
+ config.server?.preTransformRequests
53606
53895
  );
53607
53896
  }
53608
53897
  const backwardCompatibleOptimizeDeps = resolvedEnvironments.client.optimizeDeps;
@@ -53935,7 +54224,12 @@ function sortUserPlugins(plugins) {
53935
54224
  }
53936
54225
  return [prePlugins, normalPlugins, postPlugins];
53937
54226
  }
53938
- async function loadConfigFromFile(configEnv, configFile, configRoot = process.cwd(), logLevel, customLogger) {
54227
+ async function loadConfigFromFile(configEnv, configFile, configRoot = process.cwd(), logLevel, customLogger, configLoader = "bundle") {
54228
+ if (configLoader !== "bundle" && configLoader !== "runner") {
54229
+ throw new Error(
54230
+ `Unsupported configLoader: ${configLoader}. Accepted values are 'bundle' and 'runner'.`
54231
+ );
54232
+ }
53939
54233
  const start = performance.now();
53940
54234
  const getTime = () => `${(performance.now() - start).toFixed(2)}ms`;
53941
54235
  let resolvedPath;
@@ -53953,23 +54247,18 @@ async function loadConfigFromFile(configEnv, configFile, configRoot = process.cw
53953
54247
  debug?.("no config file found.");
53954
54248
  return null;
53955
54249
  }
53956
- const isESM = typeof process.versions.deno === "string" || isFilePathESM(resolvedPath);
53957
54250
  try {
53958
- const bundled = await bundleConfigFile(resolvedPath, isESM);
53959
- const userConfig = await loadConfigFromBundledFile(
53960
- resolvedPath,
53961
- bundled.code,
53962
- isESM
53963
- );
53964
- debug?.(`bundled config file loaded in ${getTime()}`);
53965
- const config = await (typeof userConfig === "function" ? userConfig(configEnv) : userConfig);
54251
+ const resolver = configLoader === "bundle" ? bundleAndLoadConfigFile : importConfigFile;
54252
+ const { configExport, dependencies } = await resolver(resolvedPath);
54253
+ debug?.(`config file loaded in ${getTime()}`);
54254
+ const config = await (typeof configExport === "function" ? configExport(configEnv) : configExport);
53966
54255
  if (!isObject$2(config)) {
53967
54256
  throw new Error(`config must export or return an object.`);
53968
54257
  }
53969
54258
  return {
53970
54259
  path: normalizePath$3(resolvedPath),
53971
54260
  config,
53972
- dependencies: bundled.dependencies
54261
+ dependencies
53973
54262
  };
53974
54263
  } catch (e) {
53975
54264
  createLogger(logLevel, { customLogger }).error(
@@ -53981,6 +54270,26 @@ async function loadConfigFromFile(configEnv, configFile, configRoot = process.cw
53981
54270
  throw e;
53982
54271
  }
53983
54272
  }
54273
+ async function importConfigFile(resolvedPath) {
54274
+ const { module, dependencies } = await runnerImport(resolvedPath);
54275
+ return {
54276
+ configExport: module.default,
54277
+ dependencies
54278
+ };
54279
+ }
54280
+ async function bundleAndLoadConfigFile(resolvedPath) {
54281
+ const isESM = typeof process.versions.deno === "string" || isFilePathESM(resolvedPath);
54282
+ const bundled = await bundleConfigFile(resolvedPath, isESM);
54283
+ const userConfig = await loadConfigFromBundledFile(
54284
+ resolvedPath,
54285
+ bundled.code,
54286
+ isESM
54287
+ );
54288
+ return {
54289
+ configExport: userConfig,
54290
+ dependencies: bundled.dependencies
54291
+ };
54292
+ }
53984
54293
  async function bundleConfigFile(fileName, isESM) {
53985
54294
  const isModuleSyncConditionEnabled = (await import('#module-sync-enabled')).default;
53986
54295
  const dirnameVarName = "__vite_injected_original_dirname";
@@ -54030,7 +54339,8 @@ async function bundleConfigFile(fileName, isESM) {
54030
54339
  extensions: configDefaults.resolve.extensions,
54031
54340
  preserveSymlinks: false,
54032
54341
  packageCache,
54033
- isRequire
54342
+ isRequire,
54343
+ builtins: nodeLikeBuiltins
54034
54344
  })?.id;
54035
54345
  };
54036
54346
  build2.onResolve(
@@ -54039,7 +54349,7 @@ async function bundleConfigFile(fileName, isESM) {
54039
54349
  if (kind === "entry-point" || path$d.isAbsolute(id) || isNodeBuiltin(id)) {
54040
54350
  return;
54041
54351
  }
54042
- if (isBuiltin(id)) {
54352
+ if (isNodeLikeBuiltin(id)) {
54043
54353
  return { external: true };
54044
54354
  }
54045
54355
  const isImport = isESM || kind === "dynamic-import";
@@ -54207,4 +54517,4 @@ function optimizeDepsDisabledBackwardCompatibility(resolved, optimizeDeps, optim
54207
54517
  }
54208
54518
  }
54209
54519
 
54210
- 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 };
54520
+ 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 };