vite 8.0.4 → 8.0.6

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,5 +1,5 @@
1
1
  import "@vite/env";
2
- //#region \0@oxc-project+runtime@0.122.0/helpers/typeof.js
2
+ //#region \0@oxc-project+runtime@0.123.0/helpers/typeof.js
3
3
  function _typeof(o) {
4
4
  "@babel/helpers - typeof";
5
5
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -9,7 +9,7 @@ function _typeof(o) {
9
9
  }, _typeof(o);
10
10
  }
11
11
  //#endregion
12
- //#region \0@oxc-project+runtime@0.122.0/helpers/toPrimitive.js
12
+ //#region \0@oxc-project+runtime@0.123.0/helpers/toPrimitive.js
13
13
  function toPrimitive(t, r) {
14
14
  if ("object" != _typeof(t) || !t) return t;
15
15
  var e = t[Symbol.toPrimitive];
@@ -21,13 +21,13 @@ function toPrimitive(t, r) {
21
21
  return ("string" === r ? String : Number)(t);
22
22
  }
23
23
  //#endregion
24
- //#region \0@oxc-project+runtime@0.122.0/helpers/toPropertyKey.js
24
+ //#region \0@oxc-project+runtime@0.123.0/helpers/toPropertyKey.js
25
25
  function toPropertyKey(t) {
26
26
  var i = toPrimitive(t, "string");
27
27
  return "symbol" == _typeof(i) ? i : i + "";
28
28
  }
29
29
  //#endregion
30
- //#region \0@oxc-project+runtime@0.122.0/helpers/defineProperty.js
30
+ //#region \0@oxc-project+runtime@0.123.0/helpers/defineProperty.js
31
31
  function _defineProperty(e, r, t) {
32
32
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
33
33
  value: t,
@@ -1088,11 +1088,11 @@ function getDate() {
1088
1088
  function init$1(debug) {
1089
1089
  debug.inspectOpts = Object.assign({}, inspectOpts);
1090
1090
  }
1091
- var require$1, colors$36, inspectOpts, humanize$1, createDebug, node_default;
1091
+ var require$1, colors$37, inspectOpts, humanize$1, createDebug, node_default;
1092
1092
  var init_node = __esmMin((() => {
1093
1093
  init_core();
1094
1094
  require$1 = createRequire(import.meta.url);
1095
- colors$36 = process.stderr.getColorDepth && process.stderr.getColorDepth() > 2 ? [
1095
+ colors$37 = process.stderr.getColorDepth && process.stderr.getColorDepth() > 2 ? [
1096
1096
  20,
1097
1097
  21,
1098
1098
  26,
@@ -1194,7 +1194,7 @@ var init_node = __esmMin((() => {
1194
1194
  } catch (_unused) {
1195
1195
  humanize$1 = humanize;
1196
1196
  }
1197
- createDebug = setup(useColors(), colors$36, log, load, save, formatArgs, init$1);
1197
+ createDebug = setup(useColors(), colors$37, log, load, save, formatArgs, init$1);
1198
1198
  createDebug.inspectOpts = inspectOpts;
1199
1199
  createDebug.formatters.o = function(v) {
1200
1200
  this.inspectOpts.colors = this.useColors;
@@ -2063,9 +2063,11 @@ function unique(arr) {
2063
2063
  * Even if defaultResultOrder is `ipv4first`, `dns.lookup` result maybe same.
2064
2064
  * For example, when IPv6 is not supported on that machine/network.
2065
2065
  */
2066
- async function getLocalhostAddressIfDiffersFromDNS() {
2067
- const [nodeResult, dnsResult] = await Promise.all([promises.lookup("localhost"), promises.lookup("localhost", { verbatim: true })]);
2068
- return nodeResult.family === dnsResult.family && nodeResult.address === dnsResult.address ? void 0 : nodeResult.address;
2066
+ function getLocalhostAddressIfDiffersFromDNS() {
2067
+ if (promises.getDefaultResultOrder() === "verbatim") return;
2068
+ return Promise.all([promises.lookup("localhost"), promises.lookup("localhost", { verbatim: true })]).then(([nodeResult, dnsResult]) => {
2069
+ return nodeResult.family === dnsResult.family && nodeResult.address === dnsResult.address ? void 0 : nodeResult.address;
2070
+ });
2069
2071
  }
2070
2072
  function diffDnsOrderChange(oldUrls, newUrls) {
2071
2073
  return !(oldUrls === newUrls || oldUrls && newUrls && arrayEqual(oldUrls.local, newUrls.local) && arrayEqual(oldUrls.network, newUrls.network));
@@ -2540,6 +2542,10 @@ function formatAndTruncateFileList(files) {
2540
2542
  truncated
2541
2543
  };
2542
2544
  }
2545
+ const hashbangRE = /^#!.*\n/;
2546
+ function getFileStartIndex(code) {
2547
+ return hashbangRE.exec(code)?.[0].length ?? 0;
2548
+ }
2543
2549
  //#endregion
2544
2550
  //#region src/node/plugin.ts
2545
2551
  async function resolveEnvironmentPlugins(environment) {
@@ -11071,7 +11077,6 @@ const ssrDynamicImportKey = `__vite_ssr_dynamic_import__`;
11071
11077
  const ssrExportAllKey = `__vite_ssr_exportAll__`;
11072
11078
  const ssrExportNameKey = `__vite_ssr_exportName__`;
11073
11079
  const ssrImportMetaKey = `__vite_ssr_import_meta__`;
11074
- const hashbangRE = /^#!.*\n/;
11075
11080
  async function ssrTransform(code, inMap, url, originalCode, options) {
11076
11081
  if (options?.json?.stringify && isJSONRequest(url)) return ssrTransformJSON(code, inMap);
11077
11082
  return ssrTransformScript(code, inMap, url, originalCode);
@@ -11108,7 +11113,7 @@ async function ssrTransformScript(code, inMap, url, originalCode) {
11108
11113
  const dynamicDeps = /* @__PURE__ */ new Set();
11109
11114
  const idToImportMap = /* @__PURE__ */ new Map();
11110
11115
  const declaredConst = /* @__PURE__ */ new Set();
11111
- const fileStartIndex = hashbangRE.exec(code)?.[0].length ?? 0;
11116
+ const fileStartIndex = getFileStartIndex(code);
11112
11117
  let hoistIndex = fileStartIndex;
11113
11118
  function defineImport(index, importNode, metadata) {
11114
11119
  const source = importNode.source.value;
@@ -19932,6 +19937,25 @@ var import_convert_source_map = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commo
19932
19937
  };
19933
19938
  })))(), 1);
19934
19939
  const debug$10 = createDebugger("vite:sourcemap", { onlyWhenFocused: true });
19940
+ /**
19941
+ * Given a file path inside node_modules, returns the package root directory.
19942
+ * For scoped packages like `node_modules/@scope/pkg/dist/foo.js`, returns `node_modules/@scope/pkg`.
19943
+ * Returns `undefined` if the file is not inside node_modules.
19944
+ */
19945
+ function getNodeModulesPackageRoot(filePath) {
19946
+ const normalized = normalizePath(filePath);
19947
+ const nodeModulesIndex = normalized.lastIndexOf("/node_modules/");
19948
+ if (nodeModulesIndex === -1) return void 0;
19949
+ const packageStart = nodeModulesIndex + 14;
19950
+ const rest = normalized.slice(packageStart);
19951
+ const firstSlash = rest.indexOf("/");
19952
+ let packageName;
19953
+ if (rest.startsWith("@")) {
19954
+ const secondSlash = rest.indexOf("/", firstSlash + 1);
19955
+ packageName = secondSlash === -1 ? rest : rest.slice(0, secondSlash);
19956
+ } else packageName = firstSlash === -1 ? rest : rest.slice(0, firstSlash);
19957
+ return normalized.slice(0, packageStart) + packageName;
19958
+ }
19935
19959
  const virtualSourceRE = /^(?:dep:|browser-external:|virtual:)|\0/;
19936
19960
  async function computeSourceRoute(map, file) {
19937
19961
  let sourceRoot;
@@ -19942,6 +19966,7 @@ async function computeSourceRoute(map, file) {
19942
19966
  }
19943
19967
  async function injectSourcesContent(map, file, logger) {
19944
19968
  let sourceRootPromise;
19969
+ const packageRoot = getNodeModulesPackageRoot(file);
19945
19970
  const missingSources = [];
19946
19971
  const sourcesContent = map.sourcesContent || [];
19947
19972
  const sourcesContentPromises = [];
@@ -19952,6 +19977,14 @@ async function injectSourcesContent(map, file, logger) {
19952
19977
  const sourceRoot = await sourceRootPromise;
19953
19978
  let resolvedSourcePath = cleanUrl(decodeURI(sourcePath));
19954
19979
  if (sourceRoot) resolvedSourcePath = path.resolve(sourceRoot, resolvedSourcePath);
19980
+ if (packageRoot) {
19981
+ const resolvedSourcePathNormalized = normalizePath(path.resolve(resolvedSourcePath));
19982
+ if (!isParentDirectory(packageRoot, resolvedSourcePathNormalized)) {
19983
+ sourcesContent[index] = null;
19984
+ logger.warnOnce(import_picocolors.default.yellow(`Sourcemap for ${JSON.stringify(file)} points to a source file outside its package: ${JSON.stringify(resolvedSourcePathNormalized)}`));
19985
+ return;
19986
+ }
19987
+ }
19955
19988
  sourcesContent[index] = await fsp.readFile(resolvedSourcePath, "utf-8").catch(() => {
19956
19989
  missingSources.push(resolvedSourcePath);
19957
19990
  return null;
@@ -19991,16 +20024,22 @@ function applySourcemapIgnoreList(map, sourcemapPath, sourcemapIgnoreList, logge
19991
20024
  }
19992
20025
  }
19993
20026
  }
19994
- function extractSourcemapFromFile(code, filePath) {
19995
- const map = (import_convert_source_map.fromSource(code) || import_convert_source_map.fromMapFileSource(code, createConvertSourceMapReadMap(filePath)))?.toObject();
20027
+ function extractSourcemapFromFile(code, filePath, logger) {
20028
+ const map = (import_convert_source_map.fromSource(code) || import_convert_source_map.fromMapFileSource(code, createConvertSourceMapReadMap(filePath, logger)))?.toObject();
19996
20029
  if (map) return {
19997
20030
  code: code.replace(import_convert_source_map.default.mapFileCommentRegex, blankReplacer),
19998
20031
  map
19999
20032
  };
20000
20033
  }
20001
- function createConvertSourceMapReadMap(originalFileName) {
20034
+ function createConvertSourceMapReadMap(originalFileName, logger) {
20035
+ const packageRoot = getNodeModulesPackageRoot(originalFileName);
20002
20036
  return (filename) => {
20003
- return fs.readFileSync(path.resolve(path.dirname(originalFileName), filename), "utf-8");
20037
+ const resolvedPath = path.resolve(path.dirname(originalFileName), filename);
20038
+ if (packageRoot && !isParentDirectory(packageRoot, normalizePath(resolvedPath))) {
20039
+ logger.warnOnce(import_picocolors.default.yellow(`Sourcemap in "${originalFileName}" references a map file outside its package: "${filename}"`));
20040
+ return "{}";
20041
+ }
20042
+ return fs.readFileSync(resolvedPath, "utf-8");
20004
20043
  };
20005
20044
  }
20006
20045
  //#endregion
@@ -21385,6 +21424,7 @@ const makeScssWorker = (environment, resolvers, _maxWorkers) => {
21385
21424
  const scssProcessor = (maxWorkers) => {
21386
21425
  let worker;
21387
21426
  let failedSassEmbedded;
21427
+ const normalizedErrors = /* @__PURE__ */ new WeakSet();
21388
21428
  return {
21389
21429
  close() {
21390
21430
  worker?.stop();
@@ -21420,13 +21460,16 @@ const scssProcessor = (maxWorkers) => {
21420
21460
  deps
21421
21461
  };
21422
21462
  } catch (e) {
21423
- e.message = `[sass] ${e.message}`;
21424
- e.id = e.file;
21425
- e.frame = e.formatted;
21426
- if (e.span?.start) {
21427
- e.line = e.span.start.line + 1;
21428
- e.column = e.span.start.column + 1;
21429
- e.frame = e.message;
21463
+ if (!normalizedErrors.has(e)) {
21464
+ e.message = `[sass] ${e.message}`;
21465
+ e.id = e.file;
21466
+ e.frame = e.formatted;
21467
+ if (e.span?.start) {
21468
+ e.line = e.span.start.line + 1;
21469
+ e.column = e.span.start.column + 1;
21470
+ e.frame = e.message;
21471
+ }
21472
+ normalizedErrors.add(e);
21430
21473
  }
21431
21474
  return {
21432
21475
  code: "",
@@ -24069,15 +24112,239 @@ function renderRestrictedErrorHTML(msg) {
24069
24112
  `;
24070
24113
  }
24071
24114
  //#endregion
24072
- //#region src/node/server/transformRequest.ts
24115
+ //#region src/node/server/send.ts
24073
24116
  var import_etag = /* @__PURE__ */ __toESM(require_etag(), 1);
24117
+ const debug$8 = createDebugger("vite:send", { onlyWhenFocused: true });
24118
+ const alias = {
24119
+ js: "text/javascript",
24120
+ css: "text/css",
24121
+ html: "text/html",
24122
+ json: "application/json"
24123
+ };
24124
+ function send(req, res, content, type, options) {
24125
+ const { etag = (0, import_etag.default)(content, { weak: true }), cacheControl = "no-cache", headers, map } = options;
24126
+ if (res.writableEnded) return;
24127
+ if (req.headers["if-none-match"] === etag) {
24128
+ res.statusCode = 304;
24129
+ res.end();
24130
+ return;
24131
+ }
24132
+ res.setHeader("Content-Type", alias[type] || type);
24133
+ res.setHeader("Cache-Control", cacheControl);
24134
+ res.setHeader("Etag", etag);
24135
+ if (headers) for (const name in headers) res.setHeader(name, headers[name]);
24136
+ if (map && "version" in map && map.mappings) {
24137
+ if (type === "js" || type === "css") content = getCodeWithSourcemap(type, content.toString(), map);
24138
+ } else if (type === "js" && (!map || map.mappings !== "")) {
24139
+ const code = content.toString();
24140
+ if (import_convert_source_map.default.mapFileCommentRegex.test(code)) debug$8?.(`Skipped injecting fallback sourcemap for ${req.url}`);
24141
+ else {
24142
+ const urlWithoutTimestamp = removeTimestampQuery(req.url);
24143
+ content = getCodeWithSourcemap(type, code, new MagicString(code).generateMap({
24144
+ source: path.basename(urlWithoutTimestamp),
24145
+ hires: "boundary",
24146
+ includeContent: true
24147
+ }));
24148
+ }
24149
+ }
24150
+ res.statusCode = 200;
24151
+ if (req.method === "HEAD") res.end();
24152
+ else res.end(content);
24153
+ }
24154
+ //#endregion
24155
+ //#region src/node/server/middlewares/transform.ts
24156
+ const debugCache$1 = createDebugger("vite:cache");
24157
+ const knownIgnoreList = new Set(["/", "/favicon.ico"]);
24158
+ const documentFetchDests = new Set([
24159
+ "document",
24160
+ "iframe",
24161
+ "frame",
24162
+ "fencedframe"
24163
+ ]);
24164
+ function isDocumentFetchDest(req) {
24165
+ const fetchDest = req.headers["sec-fetch-dest"];
24166
+ return fetchDest !== void 0 && documentFetchDests.has(fetchDest);
24167
+ }
24168
+ const urlRE = /[?&]url\b/;
24169
+ const rawRE = /[?&]raw\b/;
24170
+ const inlineRE$1 = /[?&]inline\b/;
24171
+ const svgRE = /\.svg\b/;
24172
+ function isServerAccessDeniedForTransform(config, id) {
24173
+ if (rawRE.test(id) || urlRE.test(id) || inlineRE$1.test(id) || svgRE.test(id)) return checkLoadingAccess(config, cleanUrl(id)) !== "allowed" || checkLoadingAccess(config, id) !== "allowed";
24174
+ return false;
24175
+ }
24176
+ /**
24177
+ * A middleware that short-circuits the middleware chain to serve cached transformed modules
24178
+ */
24179
+ function cachedTransformMiddleware(server) {
24180
+ return function viteCachedTransformMiddleware(req, res, next) {
24181
+ const environment = server.environments.client;
24182
+ if (isDocumentFetchDest(req)) {
24183
+ res.appendHeader("Vary", "Sec-Fetch-Dest");
24184
+ return next();
24185
+ }
24186
+ const ifNoneMatch = req.headers["if-none-match"];
24187
+ if (ifNoneMatch) {
24188
+ const moduleByEtag = environment.moduleGraph.getModuleByEtag(ifNoneMatch);
24189
+ if (moduleByEtag?.transformResult?.etag === ifNoneMatch && moduleByEtag.url === req.url) {
24190
+ if (!isCSSRequest(req.url)) {
24191
+ debugCache$1?.(`[304] ${prettifyUrl(req.url, server.config.root)}`);
24192
+ res.statusCode = 304;
24193
+ return res.end();
24194
+ }
24195
+ }
24196
+ }
24197
+ next();
24198
+ };
24199
+ }
24200
+ function transformMiddleware(server) {
24201
+ const { root, publicDir } = server.config;
24202
+ const publicDirInRoot = publicDir.startsWith(withTrailingSlash(root));
24203
+ const publicPath = `${publicDir.slice(root.length)}/`;
24204
+ return async function viteTransformMiddleware(req, res, next) {
24205
+ const environment = server.environments.client;
24206
+ if (req.method !== "GET" && req.method !== "HEAD" || knownIgnoreList.has(req.url) || isDocumentFetchDest(req)) return next();
24207
+ let url;
24208
+ try {
24209
+ url = decodeURI(removeTimestampQuery(req.url)).replace(NULL_BYTE_PLACEHOLDER, "\0");
24210
+ } catch (e) {
24211
+ if (e instanceof URIError) {
24212
+ server.config.logger.warn(import_picocolors.default.yellow(`Malformed URI sequence in request URL: ${removeTimestampQuery(req.url)}`));
24213
+ return next();
24214
+ }
24215
+ return next(e);
24216
+ }
24217
+ const withoutQuery = cleanUrl(url);
24218
+ try {
24219
+ if (withoutQuery.endsWith(".map")) {
24220
+ const depsOptimizer = environment.depsOptimizer;
24221
+ if (depsOptimizer?.isOptimizedDepUrl(url)) {
24222
+ const sourcemapPath = url.startsWith(FS_PREFIX) ? fsPathFromId(url) : normalizePath(path.resolve(server.config.root, url.slice(1)));
24223
+ if (!depsOptimizer.isOptimizedDepFile(sourcemapPath)) return next();
24224
+ try {
24225
+ const map = JSON.parse(await fsp.readFile(sourcemapPath, "utf-8"));
24226
+ applySourcemapIgnoreList(map, sourcemapPath, server.config.server.sourcemapIgnoreList, server.config.logger);
24227
+ return send(req, res, JSON.stringify(map), "json", { headers: server.config.server.headers });
24228
+ } catch {
24229
+ const dummySourceMap = {
24230
+ version: 3,
24231
+ file: sourcemapPath.replace(/\.map$/, ""),
24232
+ sources: [],
24233
+ sourcesContent: [],
24234
+ names: [],
24235
+ mappings: ";;;;;;;;;"
24236
+ };
24237
+ return send(req, res, JSON.stringify(dummySourceMap), "json", {
24238
+ cacheControl: "no-cache",
24239
+ headers: server.config.server.headers
24240
+ });
24241
+ }
24242
+ } else {
24243
+ const originalUrl = url.replace(/\.map($|\?)/, "$1");
24244
+ const map = (await environment.moduleGraph.getModuleByUrl(originalUrl))?.transformResult?.map;
24245
+ if (map) return send(req, res, JSON.stringify(map), "json", { headers: server.config.server.headers });
24246
+ else return next();
24247
+ }
24248
+ }
24249
+ if (publicDirInRoot && url.startsWith(publicPath)) warnAboutExplicitPublicPathInUrl(url);
24250
+ if (req.headers["sec-fetch-dest"] === "script" || isJSRequest(url) || isImportRequest(url) || isCSSRequest(url) || isHTMLProxy(url)) {
24251
+ url = removeImportQuery(url);
24252
+ url = unwrapId(url);
24253
+ if (isCSSRequest(url)) {
24254
+ if (req.headers.accept?.includes("text/css") && !isDirectRequest(url)) url = injectQuery(url, "direct");
24255
+ const ifNoneMatch = req.headers["if-none-match"];
24256
+ if (ifNoneMatch && (await environment.moduleGraph.getModuleByUrl(url))?.transformResult?.etag === ifNoneMatch) {
24257
+ debugCache$1?.(`[304] ${prettifyUrl(url, server.config.root)}`);
24258
+ res.statusCode = 304;
24259
+ return res.end();
24260
+ }
24261
+ }
24262
+ const result = await environment.transformRequest(url);
24263
+ if (result) {
24264
+ const depsOptimizer = environment.depsOptimizer;
24265
+ const type = isDirectCSSRequest(url) ? "css" : "js";
24266
+ const isDep = DEP_VERSION_RE.test(url) || depsOptimizer?.isOptimizedDepUrl(url);
24267
+ return send(req, res, result.code, type, {
24268
+ etag: result.etag,
24269
+ cacheControl: isDep ? "max-age=31536000,immutable" : "no-cache",
24270
+ headers: server.config.server.headers,
24271
+ map: result.map
24272
+ });
24273
+ }
24274
+ }
24275
+ } catch (e) {
24276
+ if (e?.code === "ERR_OPTIMIZE_DEPS_PROCESSING_ERROR") {
24277
+ if (!res.writableEnded) {
24278
+ res.statusCode = 504;
24279
+ res.statusMessage = "Optimize Deps Processing Error";
24280
+ res.end();
24281
+ }
24282
+ server.config.logger.error(e.message);
24283
+ return;
24284
+ }
24285
+ if (e?.code === "ERR_OUTDATED_OPTIMIZED_DEP") {
24286
+ if (!res.writableEnded) {
24287
+ res.statusCode = 504;
24288
+ res.statusMessage = "Outdated Optimize Dep";
24289
+ res.end();
24290
+ }
24291
+ return;
24292
+ }
24293
+ if (e?.code === "ERR_CLOSED_SERVER") {
24294
+ if (!res.writableEnded) {
24295
+ res.statusCode = 504;
24296
+ res.statusMessage = "Outdated Request";
24297
+ res.end();
24298
+ }
24299
+ return;
24300
+ }
24301
+ if (e?.code === "ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR") {
24302
+ if (!res.writableEnded) {
24303
+ res.statusCode = 404;
24304
+ res.end();
24305
+ }
24306
+ server.config.logger.warn(import_picocolors.default.yellow(e.message));
24307
+ return;
24308
+ }
24309
+ if (e?.code === "ERR_LOAD_URL") return next();
24310
+ if (e?.code === "ERR_DENIED_ID") {
24311
+ const id = e.id;
24312
+ let servingAccessResult = checkLoadingAccess(server.config, cleanUrl(id));
24313
+ if (servingAccessResult === "allowed") servingAccessResult = checkLoadingAccess(server.config, id);
24314
+ if (servingAccessResult === "denied") {
24315
+ respondWithAccessDenied(id, server, res);
24316
+ return true;
24317
+ }
24318
+ if (servingAccessResult === "fallback") {
24319
+ next();
24320
+ return true;
24321
+ }
24322
+ throw new Error(`Unexpected access result for id ${id}`);
24323
+ }
24324
+ return next(e);
24325
+ }
24326
+ next();
24327
+ };
24328
+ function warnAboutExplicitPublicPathInUrl(url) {
24329
+ let warning;
24330
+ if (isImportRequest(url)) {
24331
+ const rawUrl = removeImportQuery(url);
24332
+ if (urlRE.test(url)) warning = `Assets in the public directory are served at the root path.\nInstead of ${import_picocolors.default.cyan(rawUrl)}, use ${import_picocolors.default.cyan(rawUrl.replace(publicPath, "/"))}.`;
24333
+ else warning = `Assets in public directory cannot be imported from JavaScript.
24334
+ If you intend to import that asset, put the file in the src directory, and use ${import_picocolors.default.cyan(rawUrl.replace(publicPath, "/src/"))} instead of ${import_picocolors.default.cyan(rawUrl)}.\nIf you intend to use the URL of that asset, use ${import_picocolors.default.cyan(injectQuery(rawUrl.replace(publicPath, "/"), "url"))}.`;
24335
+ } else warning = `Files in the public directory are served at the root path.\nInstead of ${import_picocolors.default.cyan(url)}, use ${import_picocolors.default.cyan(url.replace(publicPath, "/"))}.`;
24336
+ server.config.logger.warn(import_picocolors.default.yellow(warning));
24337
+ }
24338
+ }
24339
+ //#endregion
24340
+ //#region src/node/server/transformRequest.ts
24074
24341
  const ERR_LOAD_URL = "ERR_LOAD_URL";
24075
24342
  const ERR_LOAD_PUBLIC_URL = "ERR_LOAD_PUBLIC_URL";
24076
24343
  const ERR_DENIED_ID = "ERR_DENIED_ID";
24077
24344
  const debugLoad = createDebugger("vite:load");
24078
24345
  const debugTransform = createDebugger("vite:transform");
24079
- const debugCache$1 = createDebugger("vite:cache");
24080
- function transformRequest(environment, url, options = {}) {
24346
+ const debugCache = createDebugger("vite:cache");
24347
+ function transformRequest(environment, url, options) {
24081
24348
  if (environment._closing && environment.config.dev.recoverable) throwClosedServerError();
24082
24349
  const timestamp = monotonicDateNow();
24083
24350
  url = removeTimestampQuery(url);
@@ -24125,15 +24392,15 @@ async function doTransform(environment, url, options, timestamp) {
24125
24392
  return result;
24126
24393
  }
24127
24394
  async function getCachedTransformResult(environment, url, module, timestamp) {
24128
- const prettyUrl = debugCache$1 ? prettifyUrl(url, environment.config.root) : "";
24395
+ const prettyUrl = debugCache ? prettifyUrl(url, environment.config.root) : "";
24129
24396
  const softInvalidatedTransformResult = await handleModuleSoftInvalidation(environment, module, timestamp);
24130
24397
  if (softInvalidatedTransformResult) {
24131
- debugCache$1?.(`[memory-hmr] ${prettyUrl}`);
24398
+ debugCache?.(`[memory-hmr] ${prettyUrl}`);
24132
24399
  return softInvalidatedTransformResult;
24133
24400
  }
24134
24401
  const cached = module.transformResult;
24135
24402
  if (cached) {
24136
- debugCache$1?.(`[memory] ${prettyUrl}`);
24403
+ debugCache?.(`[memory] ${prettyUrl}`);
24137
24404
  return cached;
24138
24405
  }
24139
24406
  }
@@ -24141,7 +24408,7 @@ async function loadAndTransform(environment, id, url, options, timestamp, mod, r
24141
24408
  const { config, pluginContainer, logger } = environment;
24142
24409
  const prettyUrl = debugLoad || debugTransform ? prettifyUrl(url, config.root) : "";
24143
24410
  const moduleGraph = environment.moduleGraph;
24144
- if (options.allowId && !options.allowId(id)) {
24411
+ if (!options.skipFsCheck && id[0] !== "\0" && isServerAccessDeniedForTransform(config, id)) {
24145
24412
  const err = /* @__PURE__ */ new Error(`Denied ID ${id}`);
24146
24413
  err.code = ERR_DENIED_ID;
24147
24414
  err.id = id;
@@ -24154,7 +24421,7 @@ async function loadAndTransform(environment, id, url, options, timestamp, mod, r
24154
24421
  const loadResult = await pluginContainer.load(id);
24155
24422
  if (loadResult == null) {
24156
24423
  const file = cleanUrl(id);
24157
- if (environment.config.consumer === "server" || isFileLoadingAllowed(environment.getTopLevelConfig(), slash(file))) {
24424
+ if (options.skipFsCheck || isFileLoadingAllowed(environment.getTopLevelConfig(), slash(file))) {
24158
24425
  try {
24159
24426
  code = await fsp.readFile(file, "utf-8");
24160
24427
  debugLoad?.(`${timeFrom(loadStart)} [fs] ${prettyUrl}`);
@@ -24164,7 +24431,7 @@ async function loadAndTransform(environment, id, url, options, timestamp, mod, r
24164
24431
  if (code != null && environment.pluginContainer.watcher) ensureWatchedFile(environment.pluginContainer.watcher, file, config.root);
24165
24432
  }
24166
24433
  if (code) try {
24167
- const extracted = extractSourcemapFromFile(code, file);
24434
+ const extracted = extractSourcemapFromFile(code, file, logger);
24168
24435
  if (extracted) {
24169
24436
  code = extracted.code;
24170
24437
  map = extracted.map;
@@ -24368,6 +24635,10 @@ var DevEnvironment = class extends BaseEnvironment {
24368
24635
  * @internal
24369
24636
  */
24370
24637
  _remoteRunnerOptions;
24638
+ /**
24639
+ * @internal
24640
+ */
24641
+ _skipFsCheck;
24371
24642
  get pluginContainer() {
24372
24643
  if (!this._pluginContainer) throw new Error(`${this.name} environment.pluginContainer called before initialized`);
24373
24644
  return this._pluginContainer;
@@ -24405,9 +24676,11 @@ var DevEnvironment = class extends BaseEnvironment {
24405
24676
  this.moduleGraph = new EnvironmentModuleGraph(name, (url) => this.pluginContainer.resolveId(url, void 0));
24406
24677
  this._crawlEndFinder = setupOnCrawlEnd();
24407
24678
  this._remoteRunnerOptions = context.remoteRunner ?? {};
24679
+ this._skipFsCheck = !!(context.transport && !(isWebSocketServer in context.transport) && context.transport.skipFsCheck);
24408
24680
  this.hot = context.transport ? isWebSocketServer in context.transport ? context.transport : normalizeHotChannel(context.transport, context.hot) : normalizeHotChannel({}, context.hot);
24409
24681
  this.hot.setInvokeHandler({
24410
24682
  fetchModule: (id, importer, options) => {
24683
+ if (context.disableFetchModule) throw new Error("fetchModule is disabled in this environment");
24411
24684
  return this.fetchModule(id, importer, options);
24412
24685
  },
24413
24686
  getBuiltins: async () => {
@@ -24466,12 +24739,12 @@ var DevEnvironment = class extends BaseEnvironment {
24466
24739
  async reloadModule(module) {
24467
24740
  if (this.config.server.hmr !== false && module.file) updateModules(this, module.file, [module], monotonicDateNow());
24468
24741
  }
24469
- transformRequest(url, options) {
24470
- return transformRequest(this, url, options);
24742
+ transformRequest(url) {
24743
+ return transformRequest(this, url, { skipFsCheck: this._skipFsCheck });
24471
24744
  }
24472
24745
  async warmupRequest(url) {
24473
24746
  try {
24474
- await this.transformRequest(url);
24747
+ await transformRequest(this, url, { skipFsCheck: true });
24475
24748
  } catch (e) {
24476
24749
  if (e?.code === "ERR_OUTDATED_OPTIMIZED_DEP" || e?.code === "ERR_CLOSED_SERVER") return;
24477
24750
  this.logger.error(buildErrorMessage(e, [`Pre-transform error: ${e.message}`], false), {
@@ -24564,7 +24837,7 @@ function setupOnCrawlEnd() {
24564
24837
  }
24565
24838
  //#endregion
24566
24839
  //#region src/node/server/environments/fullBundleEnvironment.ts
24567
- const debug$8 = createDebugger("vite:full-bundle-mode");
24840
+ const debug$7 = createDebugger("vite:full-bundle-mode");
24568
24841
  var MemoryFiles = class {
24569
24842
  files = /* @__PURE__ */ new Map();
24570
24843
  get size() {
@@ -24611,7 +24884,7 @@ var FullBundleDevEnvironment = class extends DevEnvironment {
24611
24884
  }
24612
24885
  async listen(_server) {
24613
24886
  this.hot.listen();
24614
- debug$8?.("INITIAL: setup bundle options");
24887
+ debug$7?.("INITIAL: setup bundle options");
24615
24888
  const rollupOptions = await this.getRolldownOptions();
24616
24889
  if (Array.isArray(rollupOptions.output) && rollupOptions.output.length > 1) throw new Error("multiple output options are not supported in dev mode");
24617
24890
  const outputOptions = Array.isArray(rollupOptions.output) ? rollupOptions.output[0] : rollupOptions.output;
@@ -24635,7 +24908,7 @@ var FullBundleDevEnvironment = class extends DevEnvironment {
24635
24908
  const { updates, changedFiles } = result;
24636
24909
  if (changedFiles.length === 0) return;
24637
24910
  if (updates.every((update) => update.update.type === "Noop")) {
24638
- debug$8?.(`ignored file change for ${changedFiles.join(", ")}`);
24911
+ debug$7?.(`ignored file change for ${changedFiles.join(", ")}`);
24639
24912
  return;
24640
24913
  }
24641
24914
  for (const { clientId, update } of updates) {
@@ -24665,14 +24938,14 @@ var FullBundleDevEnvironment = class extends DevEnvironment {
24665
24938
  },
24666
24939
  watch: { skipWrite: true }
24667
24940
  });
24668
- debug$8?.("INITIAL: setup dev engine");
24941
+ debug$7?.("INITIAL: setup dev engine");
24669
24942
  this.devEngine.run().then(() => {
24670
- debug$8?.("INITIAL: run done");
24943
+ debug$7?.("INITIAL: run done");
24671
24944
  }, (e) => {
24672
- debug$8?.("INITIAL: run error", e);
24945
+ debug$7?.("INITIAL: run error", e);
24673
24946
  });
24674
24947
  this.waitForInitialBuildFinish().then(() => {
24675
- debug$8?.("INITIAL: build done");
24948
+ debug$7?.("INITIAL: build done");
24676
24949
  this.hot.send({
24677
24950
  type: "full-reload",
24678
24951
  path: "*"
@@ -24691,10 +24964,10 @@ var FullBundleDevEnvironment = class extends DevEnvironment {
24691
24964
  (async () => {
24692
24965
  const invalidateCalledModules = this.invalidateCalledModules.get(client);
24693
24966
  if (invalidateCalledModules?.has(m.path)) {
24694
- debug$8?.(`INVALIDATE: invalidate received from ${m.path}, but ignored because it was already invalidated`);
24967
+ debug$7?.(`INVALIDATE: invalidate received from ${m.path}, but ignored because it was already invalidated`);
24695
24968
  return;
24696
24969
  }
24697
- debug$8?.(`INVALIDATE: invalidate received from ${m.path}, re-triggering HMR`);
24970
+ debug$7?.(`INVALIDATE: invalidate received from ${m.path}, re-triggering HMR`);
24698
24971
  if (!invalidateCalledModules) this.invalidateCalledModules.set(client, /* @__PURE__ */ new Set([]));
24699
24972
  this.invalidateCalledModules.get(client).add(m.path);
24700
24973
  let update;
@@ -24719,7 +24992,7 @@ var FullBundleDevEnvironment = class extends DevEnvironment {
24719
24992
  this.devEngine.ensureLatestBuildOutput().then(() => {
24720
24993
  this.debouncedFullReload();
24721
24994
  });
24722
- debug$8?.(`TRIGGER: access to stale bundle, triggered bundle re-generation`);
24995
+ debug$7?.(`TRIGGER: access to stale bundle, triggered bundle re-generation`);
24723
24996
  }
24724
24997
  return shouldTrigger;
24725
24998
  }
@@ -24765,7 +25038,7 @@ var FullBundleDevEnvironment = class extends DevEnvironment {
24765
25038
  });
24766
25039
  return;
24767
25040
  }
24768
- debug$8?.(`handle hmr output for ${shortFile}`, {
25041
+ debug$7?.(`handle hmr output for ${shortFile}`, {
24769
25042
  ...hmrOutput,
24770
25043
  code: typeof hmrOutput.code === "string" ? "[code]" : hmrOutput.code
24771
25044
  });
@@ -24832,7 +25105,7 @@ function debounce(time, cb) {
24832
25105
  }
24833
25106
  //#endregion
24834
25107
  //#region src/node/server/middlewares/htmlFallback.ts
24835
- const debug$7 = createDebugger("vite:html-fallback");
25108
+ const debug$6 = createDebugger("vite:html-fallback");
24836
25109
  function htmlFallbackMiddleware(root, spaFallback, clientEnvironment) {
24837
25110
  const memoryFiles = clientEnvironment instanceof FullBundleDevEnvironment ? clientEnvironment.memoryFiles : void 0;
24838
25111
  function checkFileExists(relativePath) {
@@ -24849,252 +25122,31 @@ function htmlFallbackMiddleware(root, spaFallback, clientEnvironment) {
24849
25122
  }
24850
25123
  if (pathname.endsWith(".html")) {
24851
25124
  if (checkFileExists(pathname)) {
24852
- debug$7?.(`Rewriting ${req.method} ${req.url} to ${url}`);
25125
+ debug$6?.(`Rewriting ${req.method} ${req.url} to ${url}`);
24853
25126
  req.url = url;
24854
25127
  return next();
24855
25128
  }
24856
25129
  } else if (pathname.endsWith("/")) {
24857
25130
  if (checkFileExists(joinUrlSegments(pathname, "index.html"))) {
24858
25131
  const newUrl = url + "index.html";
24859
- debug$7?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
25132
+ debug$6?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
24860
25133
  req.url = newUrl;
24861
25134
  return next();
24862
25135
  }
24863
25136
  } else if (checkFileExists(pathname + ".html")) {
24864
25137
  const newUrl = url + ".html";
24865
- debug$7?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
25138
+ debug$6?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
24866
25139
  req.url = newUrl;
24867
25140
  return next();
24868
25141
  }
24869
25142
  if (spaFallback) {
24870
- debug$7?.(`Rewriting ${req.method} ${req.url} to /index.html`);
25143
+ debug$6?.(`Rewriting ${req.method} ${req.url} to /index.html`);
24871
25144
  req.url = "/index.html";
24872
25145
  }
24873
25146
  next();
24874
25147
  };
24875
25148
  }
24876
25149
  //#endregion
24877
- //#region src/node/server/send.ts
24878
- const debug$6 = createDebugger("vite:send", { onlyWhenFocused: true });
24879
- const alias = {
24880
- js: "text/javascript",
24881
- css: "text/css",
24882
- html: "text/html",
24883
- json: "application/json"
24884
- };
24885
- function send(req, res, content, type, options) {
24886
- const { etag = (0, import_etag.default)(content, { weak: true }), cacheControl = "no-cache", headers, map } = options;
24887
- if (res.writableEnded) return;
24888
- if (req.headers["if-none-match"] === etag) {
24889
- res.statusCode = 304;
24890
- res.end();
24891
- return;
24892
- }
24893
- res.setHeader("Content-Type", alias[type] || type);
24894
- res.setHeader("Cache-Control", cacheControl);
24895
- res.setHeader("Etag", etag);
24896
- if (headers) for (const name in headers) res.setHeader(name, headers[name]);
24897
- if (map && "version" in map && map.mappings) {
24898
- if (type === "js" || type === "css") content = getCodeWithSourcemap(type, content.toString(), map);
24899
- } else if (type === "js" && (!map || map.mappings !== "")) {
24900
- const code = content.toString();
24901
- if (import_convert_source_map.default.mapFileCommentRegex.test(code)) debug$6?.(`Skipped injecting fallback sourcemap for ${req.url}`);
24902
- else {
24903
- const urlWithoutTimestamp = removeTimestampQuery(req.url);
24904
- content = getCodeWithSourcemap(type, code, new MagicString(code).generateMap({
24905
- source: path.basename(urlWithoutTimestamp),
24906
- hires: "boundary",
24907
- includeContent: true
24908
- }));
24909
- }
24910
- }
24911
- res.statusCode = 200;
24912
- if (req.method === "HEAD") res.end();
24913
- else res.end(content);
24914
- }
24915
- //#endregion
24916
- //#region src/node/server/middlewares/transform.ts
24917
- const debugCache = createDebugger("vite:cache");
24918
- const knownIgnoreList = new Set(["/", "/favicon.ico"]);
24919
- const documentFetchDests = new Set([
24920
- "document",
24921
- "iframe",
24922
- "frame",
24923
- "fencedframe"
24924
- ]);
24925
- function isDocumentFetchDest(req) {
24926
- const fetchDest = req.headers["sec-fetch-dest"];
24927
- return fetchDest !== void 0 && documentFetchDests.has(fetchDest);
24928
- }
24929
- const urlRE = /[?&]url\b/;
24930
- const rawRE = /[?&]raw\b/;
24931
- const inlineRE$1 = /[?&]inline\b/;
24932
- const svgRE = /\.svg\b/;
24933
- function isServerAccessDeniedForTransform(config, id) {
24934
- if (rawRE.test(id) || urlRE.test(id) || inlineRE$1.test(id) || svgRE.test(id)) return checkLoadingAccess(config, id) !== "allowed";
24935
- return false;
24936
- }
24937
- /**
24938
- * A middleware that short-circuits the middleware chain to serve cached transformed modules
24939
- */
24940
- function cachedTransformMiddleware(server) {
24941
- return function viteCachedTransformMiddleware(req, res, next) {
24942
- const environment = server.environments.client;
24943
- if (isDocumentFetchDest(req)) {
24944
- res.appendHeader("Vary", "Sec-Fetch-Dest");
24945
- return next();
24946
- }
24947
- const ifNoneMatch = req.headers["if-none-match"];
24948
- if (ifNoneMatch) {
24949
- const moduleByEtag = environment.moduleGraph.getModuleByEtag(ifNoneMatch);
24950
- if (moduleByEtag?.transformResult?.etag === ifNoneMatch && moduleByEtag.url === req.url) {
24951
- if (!isCSSRequest(req.url)) {
24952
- debugCache?.(`[304] ${prettifyUrl(req.url, server.config.root)}`);
24953
- res.statusCode = 304;
24954
- return res.end();
24955
- }
24956
- }
24957
- }
24958
- next();
24959
- };
24960
- }
24961
- function transformMiddleware(server) {
24962
- const { root, publicDir } = server.config;
24963
- const publicDirInRoot = publicDir.startsWith(withTrailingSlash(root));
24964
- const publicPath = `${publicDir.slice(root.length)}/`;
24965
- return async function viteTransformMiddleware(req, res, next) {
24966
- const environment = server.environments.client;
24967
- if (req.method !== "GET" && req.method !== "HEAD" || knownIgnoreList.has(req.url) || isDocumentFetchDest(req)) return next();
24968
- let url;
24969
- try {
24970
- url = decodeURI(removeTimestampQuery(req.url)).replace(NULL_BYTE_PLACEHOLDER, "\0");
24971
- } catch (e) {
24972
- if (e instanceof URIError) {
24973
- server.config.logger.warn(import_picocolors.default.yellow(`Malformed URI sequence in request URL: ${removeTimestampQuery(req.url)}`));
24974
- return next();
24975
- }
24976
- return next(e);
24977
- }
24978
- const withoutQuery = cleanUrl(url);
24979
- try {
24980
- if (withoutQuery.endsWith(".map")) if (environment.depsOptimizer?.isOptimizedDepUrl(url)) {
24981
- const sourcemapPath = url.startsWith(FS_PREFIX) ? fsPathFromId(url) : normalizePath(path.resolve(server.config.root, url.slice(1)));
24982
- try {
24983
- const map = JSON.parse(await fsp.readFile(sourcemapPath, "utf-8"));
24984
- applySourcemapIgnoreList(map, sourcemapPath, server.config.server.sourcemapIgnoreList, server.config.logger);
24985
- return send(req, res, JSON.stringify(map), "json", { headers: server.config.server.headers });
24986
- } catch {
24987
- const dummySourceMap = {
24988
- version: 3,
24989
- file: sourcemapPath.replace(/\.map$/, ""),
24990
- sources: [],
24991
- sourcesContent: [],
24992
- names: [],
24993
- mappings: ";;;;;;;;;"
24994
- };
24995
- return send(req, res, JSON.stringify(dummySourceMap), "json", {
24996
- cacheControl: "no-cache",
24997
- headers: server.config.server.headers
24998
- });
24999
- }
25000
- } else {
25001
- const originalUrl = url.replace(/\.map($|\?)/, "$1");
25002
- const map = (await environment.moduleGraph.getModuleByUrl(originalUrl))?.transformResult?.map;
25003
- if (map) return send(req, res, JSON.stringify(map), "json", { headers: server.config.server.headers });
25004
- else return next();
25005
- }
25006
- if (publicDirInRoot && url.startsWith(publicPath)) warnAboutExplicitPublicPathInUrl(url);
25007
- if (req.headers["sec-fetch-dest"] === "script" || isJSRequest(url) || isImportRequest(url) || isCSSRequest(url) || isHTMLProxy(url)) {
25008
- url = removeImportQuery(url);
25009
- url = unwrapId(url);
25010
- if (isCSSRequest(url)) {
25011
- if (req.headers.accept?.includes("text/css") && !isDirectRequest(url)) url = injectQuery(url, "direct");
25012
- const ifNoneMatch = req.headers["if-none-match"];
25013
- if (ifNoneMatch && (await environment.moduleGraph.getModuleByUrl(url))?.transformResult?.etag === ifNoneMatch) {
25014
- debugCache?.(`[304] ${prettifyUrl(url, server.config.root)}`);
25015
- res.statusCode = 304;
25016
- return res.end();
25017
- }
25018
- }
25019
- const result = await environment.transformRequest(url, { allowId(id) {
25020
- return id[0] === "\0" || !isServerAccessDeniedForTransform(server.config, id);
25021
- } });
25022
- if (result) {
25023
- const depsOptimizer = environment.depsOptimizer;
25024
- const type = isDirectCSSRequest(url) ? "css" : "js";
25025
- const isDep = DEP_VERSION_RE.test(url) || depsOptimizer?.isOptimizedDepUrl(url);
25026
- return send(req, res, result.code, type, {
25027
- etag: result.etag,
25028
- cacheControl: isDep ? "max-age=31536000,immutable" : "no-cache",
25029
- headers: server.config.server.headers,
25030
- map: result.map
25031
- });
25032
- }
25033
- }
25034
- } catch (e) {
25035
- if (e?.code === "ERR_OPTIMIZE_DEPS_PROCESSING_ERROR") {
25036
- if (!res.writableEnded) {
25037
- res.statusCode = 504;
25038
- res.statusMessage = "Optimize Deps Processing Error";
25039
- res.end();
25040
- }
25041
- server.config.logger.error(e.message);
25042
- return;
25043
- }
25044
- if (e?.code === "ERR_OUTDATED_OPTIMIZED_DEP") {
25045
- if (!res.writableEnded) {
25046
- res.statusCode = 504;
25047
- res.statusMessage = "Outdated Optimize Dep";
25048
- res.end();
25049
- }
25050
- return;
25051
- }
25052
- if (e?.code === "ERR_CLOSED_SERVER") {
25053
- if (!res.writableEnded) {
25054
- res.statusCode = 504;
25055
- res.statusMessage = "Outdated Request";
25056
- res.end();
25057
- }
25058
- return;
25059
- }
25060
- if (e?.code === "ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR") {
25061
- if (!res.writableEnded) {
25062
- res.statusCode = 404;
25063
- res.end();
25064
- }
25065
- server.config.logger.warn(import_picocolors.default.yellow(e.message));
25066
- return;
25067
- }
25068
- if (e?.code === "ERR_LOAD_URL") return next();
25069
- if (e?.code === "ERR_DENIED_ID") {
25070
- const id = e.id;
25071
- const servingAccessResult = checkLoadingAccess(server.config, id);
25072
- if (servingAccessResult === "denied") {
25073
- respondWithAccessDenied(id, server, res);
25074
- return true;
25075
- }
25076
- if (servingAccessResult === "fallback") {
25077
- next();
25078
- return true;
25079
- }
25080
- throw new Error(`Unexpected access result for id ${id}`);
25081
- }
25082
- return next(e);
25083
- }
25084
- next();
25085
- };
25086
- function warnAboutExplicitPublicPathInUrl(url) {
25087
- let warning;
25088
- if (isImportRequest(url)) {
25089
- const rawUrl = removeImportQuery(url);
25090
- if (urlRE.test(url)) warning = `Assets in the public directory are served at the root path.\nInstead of ${import_picocolors.default.cyan(rawUrl)}, use ${import_picocolors.default.cyan(rawUrl.replace(publicPath, "/"))}.`;
25091
- else warning = `Assets in public directory cannot be imported from JavaScript.
25092
- If you intend to import that asset, put the file in the src directory, and use ${import_picocolors.default.cyan(rawUrl.replace(publicPath, "/src/"))} instead of ${import_picocolors.default.cyan(rawUrl)}.\nIf you intend to use the URL of that asset, use ${import_picocolors.default.cyan(injectQuery(rawUrl.replace(publicPath, "/"), "url"))}.`;
25093
- } else warning = `Files in the public directory are served at the root path.\nInstead of ${import_picocolors.default.cyan(url)}, use ${import_picocolors.default.cyan(url.replace(publicPath, "/"))}.`;
25094
- server.config.logger.warn(import_picocolors.default.yellow(warning));
25095
- }
25096
- }
25097
- //#endregion
25098
25150
  //#region src/node/server/middlewares/indexHtml.ts
25099
25151
  function createDevHtmlTransformFn(config) {
25100
25152
  const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms(config.plugins);
@@ -26923,6 +26975,7 @@ function createServerHotChannel() {
26923
26975
  const innerEmitter = new EventEmitter();
26924
26976
  const outsideEmitter = new EventEmitter();
26925
26977
  return {
26978
+ skipFsCheck: true,
26926
26979
  send(payload) {
26927
26980
  outsideEmitter.emit("send", payload);
26928
26981
  },
@@ -27762,8 +27815,10 @@ function interopNamedImports(str, importSpecifier, rewrittenUrl, importIndex, im
27762
27815
  if (dynamicIndex > -1) str.overwrite(expStart, expEnd, `import('${rewrittenUrl}').then(m => (${interopHelperStr})(m.default, ${!!config.legacy?.inconsistentCjsInterop ? 0 : 1}))` + getLineBreaks(exp), { contentOnly: true });
27763
27816
  else {
27764
27817
  const rewritten = transformCjsImport(exp, rewrittenUrl, source.slice(start, end), importIndex, importer, isNodeMode, config);
27765
- if (rewritten) str.overwrite(expStart, expEnd, rewritten + getLineBreaks(exp), { contentOnly: true });
27766
- else str.overwrite(start, end, rewrittenUrl + getLineBreaks(source.slice(start, end)), { contentOnly: true });
27818
+ if (rewritten) {
27819
+ str.overwrite(expStart, expEnd, rewritten.importLine + getLineBreaks(exp), { contentOnly: true });
27820
+ if (rewritten.hoistedAssignments) str.appendLeft(getFileStartIndex(source), rewritten.hoistedAssignments + ";");
27821
+ } else str.overwrite(start, end, rewrittenUrl + getLineBreaks(source.slice(start, end)), { contentOnly: true });
27767
27822
  }
27768
27823
  }
27769
27824
  function getLineBreaks(str) {
@@ -27786,7 +27841,7 @@ function transformCjsImport(importExp, url, rawUrl, importIndex, importer, isNod
27786
27841
  const node = parseAst(importExp).body[0];
27787
27842
  if (config.command === "serve" && node.type === "ExportAllDeclaration" && !node.exported) config.logger.warn(import_picocolors.default.yellow(`\nUnable to interop \`${importExp}\` in ${importer}, this may lose module exports. Please export "${rawUrl}" as ESM or use named exports instead, e.g. \`export { A, B } from "${rawUrl}"\``));
27788
27843
  else if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration") {
27789
- if (!node.specifiers.length) return `import "${url}"`;
27844
+ if (!node.specifiers.length) return { importLine: `import "${url}"` };
27790
27845
  const importNames = [];
27791
27846
  const exportNames = [];
27792
27847
  let defaultExports = "";
@@ -27823,7 +27878,8 @@ function transformCjsImport(importExp, url, rawUrl, importIndex, importer, isNod
27823
27878
  }
27824
27879
  }
27825
27880
  const cjsModuleName = makeLegalIdentifier(`__vite__cjsImport${importIndex}_${rawUrl}`);
27826
- const lines = [`import ${cjsModuleName} from "${url}"`];
27881
+ const importLine = `import ${cjsModuleName} from "${url}"`;
27882
+ const lines = [];
27827
27883
  importNames.forEach(({ importedName, localName }) => {
27828
27884
  if (importedName === "*") lines.push(`const ${localName} = (${interopHelperStr})(${cjsModuleName}, ${+isNodeMode})`);
27829
27885
  else if (importedName === "default") if (isNodeMode) lines.push(`const ${localName} = ${cjsModuleName}`);
@@ -27832,7 +27888,10 @@ function transformCjsImport(importExp, url, rawUrl, importIndex, importer, isNod
27832
27888
  });
27833
27889
  if (defaultExports) lines.push(`export default ${defaultExports}`);
27834
27890
  if (exportNames.length) lines.push(`export { ${exportNames.join(", ")} }`);
27835
- return lines.join("; ");
27891
+ return {
27892
+ importLine,
27893
+ hoistedAssignments: lines.join("; ")
27894
+ };
27836
27895
  }
27837
27896
  }
27838
27897
  function getIdentifierNameOrLiteralValue(node) {
@@ -29583,7 +29642,7 @@ function formatError(payload, environment, sourceMapCache) {
29583
29642
  const result = environment.moduleGraph.getModuleById(id)?.transformResult;
29584
29643
  if (result && !result.map) try {
29585
29644
  const filePath = id.split("?")[0];
29586
- const extracted = extractSourcemapFromFile(result.code, filePath);
29645
+ const extracted = extractSourcemapFromFile(result.code, filePath, environment.config.logger);
29587
29646
  sourceMapCache.set(id, extracted?.map);
29588
29647
  return extracted?.map;
29589
29648
  } catch {
@@ -33801,7 +33860,8 @@ function defaultCreateClientDevEnvironment(name, config, context) {
33801
33860
  });
33802
33861
  return new DevEnvironment(name, config, {
33803
33862
  hot: true,
33804
- transport: context.ws
33863
+ transport: context.ws,
33864
+ disableFetchModule: true
33805
33865
  });
33806
33866
  }
33807
33867
  function defaultCreateDevEnvironment(name, config) {
@@ -34722,4 +34782,4 @@ const parseAst$1 = parseAst;
34722
34782
  const parseAstAsync$1 = parseAstAsync;
34723
34783
  const esbuildVersion = "0.25.0";
34724
34784
  //#endregion
34725
- export { depsFromOptimizedDepInfo as $, builderOptionsDefaults as A, searchForWorkspaceRoot as At, resolveBuilderOptions as B, transformWithEsbuild as Bt, resolvePreviewOptions as C, send as Ct, ChunkMetadataMap as D, fetchModule as Dt, BuildEnvironment as E, isFileServingAllowed as Et, injectEnvironmentToHooks as F, createServerModuleRunnerTransport as Ft, toOutputFilePathInHtml as G, mergeConfig as Gt, resolveRolldownOptions as H, createFilter$1 as Ht, onRollupLog as I, buildErrorMessage as It, addManuallyIncludedOptimizeDeps as J, rollupVersion as Jt, toOutputFilePathInJS as K, normalizePath as Kt, resolveBuildEnvironmentOptions as L, loadEnv as Lt, createBuilder as M, perEnvironmentState as Mt, createToImportMetaURLBasedRelativeRuntime as N, ssrTransform as Nt, build as O, formatPostcssSourceMap as Ot, enhanceRollupError as P, createServerModuleRunner as Pt, createIsOptimizedDepUrl as Q, resolveBuildOutputs as R, resolveEnvPrefix as Rt, preview as S, serverConfigDefaults as St, isRunnableDevEnvironment as T, isFileLoadingAllowed as Tt, resolveUserExternal as U, isCSSRequest as Ut, resolveLibFilename as V, perEnvironmentPlugin as Vt, toOutputFilePathInCss as W, mergeAlias as Wt, cleanupDepsCacheStaleDirs as X, addOptimizedDepInfo as Y, withFilter as Yt, createIsOptimizedDepFile as Z, resolveConfig as _, createServer$2 as _t, minifySync as a, initDepsOptimizerMetadata as at, sortUserPlugins as b, resolveServerOptions as bt, parseAstAsync$1 as c, optimizeDeps as ct, isFetchableDevEnvironment as d, optimizedDepInfoFromId as dt, depsLogString as et, defineConfig as f, optimizedDepNeedsInterop as ft, resolveBaseUrl as g, _createServer as gt, loadConfigFromFile as h, createServerHotChannel as ht, minify as i, getOptimizedDepPath as it, clearLine as j, createIdResolver as jt, buildEnvironmentOptionsDefaults as k, preprocessCSS as kt, parseSync as l, optimizeExplicitEnvironmentDeps as lt, isResolvedConfig as m, toDiscoveredDependencies as mt, esbuildVersion as n, extractExportsData as nt, parse as o, isDepOptimizationDisabled as ot, getDefaultEnvironmentOptions as p, runOptimizeDeps as pt, toOutputFilePathWithoutRuntime as q, rolldownVersion as qt, esmExternalRequirePlugin$1 as r, getDepsCacheDir as rt, parseAst$1 as s, loadCachedDepOptimizationMetadata as st, Visitor as t, discoverProjectDependencies as tt, createFetchableDevEnvironment as u, optimizedDepInfoFromFile as ut, resolveDevEnvironmentOptions as v, createServerCloseFn as vt, createRunnableDevEnvironment as w, DevEnvironment as wt, runnerImport as x, restartServerWithUrls as xt, resolveDevToolsConfig as y, resolveForwardConsoleOptions as yt, resolveBuildPlugins as z, transformWithOxc as zt };
34785
+ export { depsFromOptimizedDepInfo as $, builderOptionsDefaults as A, searchForWorkspaceRoot as At, resolveBuilderOptions as B, transformWithEsbuild as Bt, resolvePreviewOptions as C, DevEnvironment as Ct, ChunkMetadataMap as D, fetchModule as Dt, BuildEnvironment as E, isFileServingAllowed as Et, injectEnvironmentToHooks as F, createServerModuleRunnerTransport as Ft, toOutputFilePathInHtml as G, mergeConfig as Gt, resolveRolldownOptions as H, createFilter$1 as Ht, onRollupLog as I, buildErrorMessage as It, addManuallyIncludedOptimizeDeps as J, rollupVersion as Jt, toOutputFilePathInJS as K, normalizePath as Kt, resolveBuildEnvironmentOptions as L, loadEnv as Lt, createBuilder as M, perEnvironmentState as Mt, createToImportMetaURLBasedRelativeRuntime as N, ssrTransform as Nt, build as O, formatPostcssSourceMap as Ot, enhanceRollupError as P, createServerModuleRunner as Pt, createIsOptimizedDepUrl as Q, resolveBuildOutputs as R, resolveEnvPrefix as Rt, preview as S, serverConfigDefaults as St, isRunnableDevEnvironment as T, isFileLoadingAllowed as Tt, resolveUserExternal as U, isCSSRequest as Ut, resolveLibFilename as V, perEnvironmentPlugin as Vt, toOutputFilePathInCss as W, mergeAlias as Wt, cleanupDepsCacheStaleDirs as X, addOptimizedDepInfo as Y, withFilter as Yt, createIsOptimizedDepFile as Z, resolveConfig as _, createServer$2 as _t, minifySync as a, initDepsOptimizerMetadata as at, sortUserPlugins as b, resolveServerOptions as bt, parseAstAsync$1 as c, optimizeDeps as ct, isFetchableDevEnvironment as d, optimizedDepInfoFromId as dt, depsLogString as et, defineConfig as f, optimizedDepNeedsInterop as ft, resolveBaseUrl as g, _createServer as gt, loadConfigFromFile as h, createServerHotChannel as ht, minify as i, getOptimizedDepPath as it, clearLine as j, createIdResolver as jt, buildEnvironmentOptionsDefaults as k, preprocessCSS as kt, parseSync as l, optimizeExplicitEnvironmentDeps as lt, isResolvedConfig as m, toDiscoveredDependencies as mt, esbuildVersion as n, extractExportsData as nt, parse as o, isDepOptimizationDisabled as ot, getDefaultEnvironmentOptions as p, runOptimizeDeps as pt, toOutputFilePathWithoutRuntime as q, rolldownVersion as qt, esmExternalRequirePlugin$1 as r, getDepsCacheDir as rt, parseAst$1 as s, loadCachedDepOptimizationMetadata as st, Visitor as t, discoverProjectDependencies as tt, createFetchableDevEnvironment as u, optimizedDepInfoFromFile as ut, resolveDevEnvironmentOptions as v, createServerCloseFn as vt, createRunnableDevEnvironment as w, send as wt, runnerImport as x, restartServerWithUrls as xt, resolveDevToolsConfig as y, resolveForwardConsoleOptions as yt, resolveBuildPlugins as z, transformWithOxc as zt };
@@ -1019,7 +1019,6 @@ interface TransformOptions {
1019
1019
  */
1020
1020
  ssr?: boolean;
1021
1021
  }
1022
- interface TransformOptionsInternal {}
1023
1022
  //#endregion
1024
1023
  //#region src/node/server/moduleGraph.d.ts
1025
1024
  declare class EnvironmentModuleNode {
@@ -1184,6 +1183,11 @@ interface HotChannelClient {
1184
1183
  }
1185
1184
  type HotChannelListener<T extends string = string> = (data: InferCustomEventPayload<T>, client: HotChannelClient) => void;
1186
1185
  interface HotChannel<Api = any> {
1186
+ /**
1187
+ * When true, the fs access check is skipped in fetchModule.
1188
+ * Set this for transports that is not exposed over the network.
1189
+ */
1190
+ skipFsCheck?: boolean;
1187
1191
  /**
1188
1192
  * Broadcast events to all clients
1189
1193
  */
@@ -1616,7 +1620,7 @@ declare class DevEnvironment extends BaseEnvironment {
1616
1620
  */
1617
1621
  fetchModule(id: string, importer?: string, options?: FetchFunctionOptions): Promise<moduleRunner_FetchResult>;
1618
1622
  reloadModule(module: EnvironmentModuleNode): Promise<void>;
1619
- transformRequest(url: string, options?: TransformOptionsInternal): Promise<TransformResult | null>;
1623
+ transformRequest(url: string): Promise<TransformResult | null>;
1620
1624
  warmupRequest(url: string): Promise<void>;
1621
1625
  protected invalidateModule(m: {
1622
1626
  path: string;
@@ -1,3 +1,3 @@
1
1
  import { F as defaultAllowedOrigins, N as VERSION, _ as DEFAULT_SERVER_CONDITIONS, d as DEFAULT_CLIENT_MAIN_FIELDS, h as DEFAULT_EXTERNAL_CONDITIONS, n as createLogger, u as DEFAULT_CLIENT_CONDITIONS, v as DEFAULT_SERVER_MAIN_FIELDS } from "./chunks/logger.js";
2
- import { At as searchForWorkspaceRoot, Bt as transformWithEsbuild, Ct as send, Dt as fetchModule, E as BuildEnvironment, Et as isFileServingAllowed, Ft as createServerModuleRunnerTransport, Gt as mergeConfig, Ht as createFilter, It as buildErrorMessage, Jt as rollupVersion, Kt as normalizePath, Lt as loadEnv, M as createBuilder, Mt as perEnvironmentState, Nt as ssrTransform, O as build, Ot as formatPostcssSourceMap, Pt as createServerModuleRunner, Rt as resolveEnvPrefix, S as preview, T as isRunnableDevEnvironment, Tt as isFileLoadingAllowed, Ut as isCSSRequest, Vt as perEnvironmentPlugin, Wt as mergeAlias, Yt as withFilter, _ as resolveConfig, _t as createServer, a as minifySync, b as sortUserPlugins, c as parseAstAsync, ct as optimizeDeps, d as isFetchableDevEnvironment, f as defineConfig, h as loadConfigFromFile, ht as createServerHotChannel, i as minify, jt as createIdResolver, kt as preprocessCSS, l as parseSync, n as esbuildVersion, o as parse, qt as rolldownVersion, r as esmExternalRequirePlugin, s as parseAst, t as Visitor, u as createFetchableDevEnvironment, w as createRunnableDevEnvironment, wt as DevEnvironment, x as runnerImport, zt as transformWithOxc } from "./chunks/node.js";
2
+ import { At as searchForWorkspaceRoot, Bt as transformWithEsbuild, Ct as DevEnvironment, Dt as fetchModule, E as BuildEnvironment, Et as isFileServingAllowed, Ft as createServerModuleRunnerTransport, Gt as mergeConfig, Ht as createFilter, It as buildErrorMessage, Jt as rollupVersion, Kt as normalizePath, Lt as loadEnv, M as createBuilder, Mt as perEnvironmentState, Nt as ssrTransform, O as build, Ot as formatPostcssSourceMap, Pt as createServerModuleRunner, Rt as resolveEnvPrefix, S as preview, T as isRunnableDevEnvironment, Tt as isFileLoadingAllowed, Ut as isCSSRequest, Vt as perEnvironmentPlugin, Wt as mergeAlias, Yt as withFilter, _ as resolveConfig, _t as createServer, a as minifySync, b as sortUserPlugins, c as parseAstAsync, ct as optimizeDeps, d as isFetchableDevEnvironment, f as defineConfig, h as loadConfigFromFile, ht as createServerHotChannel, i as minify, jt as createIdResolver, kt as preprocessCSS, l as parseSync, n as esbuildVersion, o as parse, qt as rolldownVersion, r as esmExternalRequirePlugin, s as parseAst, t as Visitor, u as createFetchableDevEnvironment, w as createRunnableDevEnvironment, wt as send, x as runnerImport, zt as transformWithOxc } from "./chunks/node.js";
3
3
  export { BuildEnvironment, DevEnvironment, Visitor, build, buildErrorMessage, createBuilder, createFetchableDevEnvironment, createFilter, createIdResolver, createLogger, createRunnableDevEnvironment, createServer, createServerHotChannel, createServerModuleRunner, createServerModuleRunnerTransport, defaultAllowedOrigins, DEFAULT_CLIENT_CONDITIONS as defaultClientConditions, DEFAULT_CLIENT_MAIN_FIELDS as defaultClientMainFields, DEFAULT_EXTERNAL_CONDITIONS as defaultExternalConditions, DEFAULT_SERVER_CONDITIONS as defaultServerConditions, DEFAULT_SERVER_MAIN_FIELDS as defaultServerMainFields, defineConfig, esbuildVersion, esmExternalRequirePlugin, fetchModule, formatPostcssSourceMap, isCSSRequest, isFetchableDevEnvironment, isFileLoadingAllowed, isFileServingAllowed, isRunnableDevEnvironment, loadConfigFromFile, loadEnv, mergeAlias, mergeConfig, minify, minifySync, ssrTransform as moduleRunnerTransform, normalizePath, optimizeDeps, parse, parseAst, parseAstAsync, parseSync, perEnvironmentPlugin, perEnvironmentState, preprocessCSS, preview, resolveConfig, resolveEnvPrefix, rolldownVersion, rollupVersion, runnerImport, searchForWorkspaceRoot, send, sortUserPlugins, transformWithEsbuild, transformWithOxc, VERSION as version, withFilter };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite",
3
- "version": "8.0.4",
3
+ "version": "8.0.6",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "author": "Evan You",
@@ -63,7 +63,7 @@
63
63
  "lightningcss": "^1.32.0",
64
64
  "picomatch": "^4.0.4",
65
65
  "postcss": "^8.5.8",
66
- "rolldown": "1.0.0-rc.12",
66
+ "rolldown": "1.0.0-rc.13",
67
67
  "tinyglobby": "^0.2.15"
68
68
  },
69
69
  "optionalDependencies": {
@@ -186,7 +186,7 @@
186
186
  "build-types-check": "tsc --project tsconfig.check.json",
187
187
  "typecheck": "tsc && tsc -p src/node && tsc -p src/module-runner && tsc -p src/shared && tsc -p src/node/__tests_dts__ && tsc -p src/module-runner/__tests_dts__",
188
188
  "lint": "eslint --cache --ext .ts src/**",
189
- "format": "prettier --write --cache --parser typescript \"src/**/*.ts\"",
189
+ "format": "oxfmt",
190
190
  "generate-target": "tsx scripts/generateTarget.ts"
191
191
  }
192
192
  }