@voidzero-dev/vite-plus-core 0.1.16-alpha.3 → 0.1.16

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.
@@ -2,7 +2,7 @@ import { n as __require$1, r as __toESM, t as __commonJSMin } from "./chunk.js";
2
2
  import { A as OPTIMIZABLE_ENTRY_RE, C as ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR, D as JS_TYPES_RE, E as FS_PREFIX, I as defaultAllowedOrigins, L as loopbackHosts, M as SPECIAL_QUERY_RE, N as VERSION, O as KNOWN_ASSET_TYPES, P as VITE_PACKAGE_DIR, R as wildcardHosts, S as ENV_PUBLIC_PATH, T as ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET, _ as DEFAULT_SERVER_CONDITIONS, a as CLIENT_ENTRY, b as DEV_PROD_CONDITION, c as DEFAULT_ASSETS_INLINE_LIMIT, d as DEFAULT_CLIENT_MAIN_FIELDS, f as DEFAULT_CONFIG_FILES, g as DEFAULT_PREVIEW_PORT, h as DEFAULT_EXTERNAL_CONDITIONS, i as CLIENT_DIR, j as ROLLUP_HOOKS, k as METADATA_FILENAME, l as DEFAULT_ASSETS_RE, m as DEFAULT_EXTENSIONS, n as createLogger, o as CLIENT_PUBLIC_PATH, p as DEFAULT_DEV_PORT, r as printServerUrls, s as CSS_LANGS_RE, t as LogLevels, u as DEFAULT_CLIENT_CONDITIONS, v as DEFAULT_SERVER_MAIN_FIELDS, w as ERR_OPTIMIZE_DEPS_PROCESSING_ERROR, x as ENV_ENTRY, y as DEP_VERSION_RE, z as require_picocolors } from "./logger.js";
3
3
  import { builtinModules, createRequire } from "node:module";
4
4
  import { parseAst, parseAstAsync } from "@voidzero-dev/vite-plus-core/rolldown/parseAst";
5
- import { esmExternalRequirePlugin } from "@voidzero-dev/vite-plus-core/rolldown/plugins";
5
+ import { esmExternalRequirePlugin, esmExternalRequirePlugin as esmExternalRequirePlugin$1 } from "@voidzero-dev/vite-plus-core/rolldown/plugins";
6
6
  import { TsconfigCache, Visitor, minify, minifySync, parse, parseSync, transformSync } from "@voidzero-dev/vite-plus-core/rolldown/utils";
7
7
  import * as fs$1 from "node:fs";
8
8
  import fs, { existsSync, readFileSync } from "node:fs";
@@ -2914,7 +2914,7 @@ const require$1 = createRequire(import.meta.url);
2914
2914
  function log$1(...args) {
2915
2915
  process.stderr.write(`${formatWithOptions(inspectOpts, ...args)}\n`);
2916
2916
  }
2917
- const colors$36 = process.stderr.getColorDepth && process.stderr.getColorDepth() > 2 ? [
2917
+ const colors$37 = process.stderr.getColorDepth && process.stderr.getColorDepth() > 2 ? [
2918
2918
  20,
2919
2919
  21,
2920
2920
  26,
@@ -3044,7 +3044,7 @@ function getDate() {
3044
3044
  function init$1(debug) {
3045
3045
  debug.inspectOpts = Object.assign({}, inspectOpts);
3046
3046
  }
3047
- const createDebug = setup(useColors(), colors$36, log$1, load, save, formatArgs, init$1);
3047
+ const createDebug = setup(useColors(), colors$37, log$1, load, save, formatArgs, init$1);
3048
3048
  createDebug.inspectOpts = inspectOpts;
3049
3049
  createDebug.formatters.o = function(v) {
3050
3050
  this.inspectOpts.colors = this.useColors;
@@ -4101,7 +4101,7 @@ function hasBothRollupOptionsAndRolldownOptions(options) {
4101
4101
  options.worker,
4102
4102
  options.optimizeDeps,
4103
4103
  options.ssr?.optimizeDeps
4104
- ]) if (opt != null && opt.rollupOptions != null && opt.rolldownOptions != null) return true;
4104
+ ]) if (opt != null && opt.rollupOptions != null && opt.rolldownOptions != null && opt.rollupOptions !== opt.rolldownOptions) return true;
4105
4105
  return false;
4106
4106
  }
4107
4107
  function mergeConfigRecursively(defaults, overrides, rootPath) {
@@ -4370,6 +4370,25 @@ function monotonicDateNow() {
4370
4370
  lastDateNow++;
4371
4371
  return lastDateNow;
4372
4372
  }
4373
+ function formatAndTruncateFileList(files) {
4374
+ const MAX_LOG_LENGTH = 500;
4375
+ let log = "";
4376
+ let truncated = false;
4377
+ for (let i = 0; i < files.length; i++) {
4378
+ const file = files[i];
4379
+ if (log === "") log = file;
4380
+ else if (log.length + 2 + file.length < MAX_LOG_LENGTH) log += ", " + file;
4381
+ else {
4382
+ log += ` and ${files.length - i} more`;
4383
+ truncated = true;
4384
+ break;
4385
+ }
4386
+ }
4387
+ return {
4388
+ formatted: log,
4389
+ truncated
4390
+ };
4391
+ }
4373
4392
  //#endregion
4374
4393
  //#region ../../vite/packages/vite/src/node/plugin.ts
4375
4394
  async function resolveEnvironmentPlugins(environment) {
@@ -4648,7 +4667,7 @@ async function reloadOnTsconfigChange(server, changedFile) {
4648
4667
  }
4649
4668
  }
4650
4669
  //#endregion
4651
- //#region ../../node_modules/.pnpm/artichokie@0.4.2/node_modules/artichokie/dist/index.js
4670
+ //#region ../../node_modules/.pnpm/artichokie@0.4.3/node_modules/artichokie/dist/index.js
4652
4671
  const AsyncFunction = async function() {}.constructor;
4653
4672
  const codeToDataUrl = (code) => `data:application/javascript,${encodeURIComponent(code + "\n//# sourceURL=[worker-eval(artichokie)]")}`;
4654
4673
  const viteSsrDynamicImport = "__vite_ssr_dynamic_import__";
@@ -4877,10 +4896,10 @@ function genWorkerCode(fn, isModule, waitTimeout, parentFunctions) {
4877
4896
  else return resArgs.result;
4878
4897
  };
4879
4898
  asyncPort.on("message", (args) => {
4880
- const id$1 = args.id;
4881
- if (resolvers.has(id$1)) {
4882
- const { resolve, reject } = resolvers.get(id$1);
4883
- resolvers.delete(id$1);
4899
+ const id = args.id;
4900
+ if (resolvers.has(id)) {
4901
+ const { resolve, reject } = resolvers.get(id);
4902
+ resolvers.delete(id);
4884
4903
  if ("result" in args) resolve(args.result);
4885
4904
  else reject(args.error);
4886
4905
  }
@@ -20827,7 +20846,7 @@ require_subprotocol();
20827
20846
  require_websocket();
20828
20847
  var import_websocket_server = /* @__PURE__ */ __toESM(require_websocket_server(), 1);
20829
20848
  //#endregion
20830
- //#region ../../node_modules/.pnpm/host-validation-middleware@0.1.2/node_modules/host-validation-middleware/dist/index.js
20849
+ //#region ../../node_modules/.pnpm/host-validation-middleware@0.1.4/node_modules/host-validation-middleware/dist/index.js
20831
20850
  /**
20832
20851
  * This function assumes that the input is not malformed.
20833
20852
  * This is because we only care about browser requests.
@@ -20889,8 +20908,8 @@ function isHostAllowed(hostHeader, allowedHosts) {
20889
20908
  * If the host header is not in the allowed hosts list, a 403 Forbidden response
20890
20909
  * is sent.
20891
20910
  */
20892
- function hostValidationMiddleware$2(options) {
20893
- return async function hostValidationMiddleware$1(req, res, next) {
20911
+ function hostValidationMiddleware$1(options) {
20912
+ return async function hostValidationMiddleware(req, res, next) {
20894
20913
  const hostHeader = req.headers.host;
20895
20914
  if (!isHostAllowed(hostHeader, options.allowedHosts)) {
20896
20915
  const hostname = hostHeader?.replace(/:\d+$/, "") ?? "";
@@ -25482,6 +25501,25 @@ var import_convert_source_map = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commo
25482
25501
  };
25483
25502
  })))(), 1);
25484
25503
  const debug$10 = createDebugger("vite:sourcemap", { onlyWhenFocused: true });
25504
+ /**
25505
+ * Given a file path inside node_modules, returns the package root directory.
25506
+ * For scoped packages like `node_modules/@scope/pkg/dist/foo.js`, returns `node_modules/@scope/pkg`.
25507
+ * Returns `undefined` if the file is not inside node_modules.
25508
+ */
25509
+ function getNodeModulesPackageRoot(filePath) {
25510
+ const normalized = normalizePath$1(filePath);
25511
+ const nodeModulesIndex = normalized.lastIndexOf("/node_modules/");
25512
+ if (nodeModulesIndex === -1) return void 0;
25513
+ const packageStart = nodeModulesIndex + 14;
25514
+ const rest = normalized.slice(packageStart);
25515
+ const firstSlash = rest.indexOf("/");
25516
+ let packageName;
25517
+ if (rest.startsWith("@")) {
25518
+ const secondSlash = rest.indexOf("/", firstSlash + 1);
25519
+ packageName = secondSlash === -1 ? rest : rest.slice(0, secondSlash);
25520
+ } else packageName = firstSlash === -1 ? rest : rest.slice(0, firstSlash);
25521
+ return normalized.slice(0, packageStart) + packageName;
25522
+ }
25485
25523
  const virtualSourceRE = /^(?:dep:|browser-external:|virtual:)|\0/;
25486
25524
  async function computeSourceRoute(map, file) {
25487
25525
  let sourceRoot;
@@ -25492,6 +25530,7 @@ async function computeSourceRoute(map, file) {
25492
25530
  }
25493
25531
  async function injectSourcesContent(map, file, logger) {
25494
25532
  let sourceRootPromise;
25533
+ const packageRoot = getNodeModulesPackageRoot(file);
25495
25534
  const missingSources = [];
25496
25535
  const sourcesContent = map.sourcesContent || [];
25497
25536
  const sourcesContentPromises = [];
@@ -25502,6 +25541,14 @@ async function injectSourcesContent(map, file, logger) {
25502
25541
  const sourceRoot = await sourceRootPromise;
25503
25542
  let resolvedSourcePath = cleanUrl(decodeURI(sourcePath));
25504
25543
  if (sourceRoot) resolvedSourcePath = path.resolve(sourceRoot, resolvedSourcePath);
25544
+ if (packageRoot) {
25545
+ const resolvedSourcePathNormalized = normalizePath$1(path.resolve(resolvedSourcePath));
25546
+ if (!isParentDirectory(packageRoot, resolvedSourcePathNormalized)) {
25547
+ sourcesContent[index] = null;
25548
+ logger.warnOnce(import_picocolors.default.yellow(`Sourcemap for ${JSON.stringify(file)} points to a source file outside its package: ${JSON.stringify(resolvedSourcePathNormalized)}`));
25549
+ return;
25550
+ }
25551
+ }
25505
25552
  sourcesContent[index] = await fsp.readFile(resolvedSourcePath, "utf-8").catch(() => {
25506
25553
  missingSources.push(resolvedSourcePath);
25507
25554
  return null;
@@ -25541,16 +25588,22 @@ function applySourcemapIgnoreList(map, sourcemapPath, sourcemapIgnoreList, logge
25541
25588
  }
25542
25589
  }
25543
25590
  }
25544
- function extractSourcemapFromFile(code, filePath) {
25545
- const map = (import_convert_source_map.fromSource(code) || import_convert_source_map.fromMapFileSource(code, createConvertSourceMapReadMap(filePath)))?.toObject();
25591
+ function extractSourcemapFromFile(code, filePath, logger) {
25592
+ const map = (import_convert_source_map.fromSource(code) || import_convert_source_map.fromMapFileSource(code, createConvertSourceMapReadMap(filePath, logger)))?.toObject();
25546
25593
  if (map) return {
25547
25594
  code: code.replace(import_convert_source_map.default.mapFileCommentRegex, blankReplacer),
25548
25595
  map
25549
25596
  };
25550
25597
  }
25551
- function createConvertSourceMapReadMap(originalFileName) {
25598
+ function createConvertSourceMapReadMap(originalFileName, logger) {
25599
+ const packageRoot = getNodeModulesPackageRoot(originalFileName);
25552
25600
  return (filename) => {
25553
- return fs.readFileSync(path.resolve(path.dirname(originalFileName), filename), "utf-8");
25601
+ const resolvedPath = path.resolve(path.dirname(originalFileName), filename);
25602
+ if (packageRoot && !isParentDirectory(packageRoot, normalizePath$1(resolvedPath))) {
25603
+ logger.warnOnce(import_picocolors.default.yellow(`Sourcemap in "${originalFileName}" references a map file outside its package: "${filename}"`));
25604
+ return "{}";
25605
+ }
25606
+ return fs.readFileSync(resolvedPath, "utf-8");
25554
25607
  };
25555
25608
  }
25556
25609
  //#endregion
@@ -28513,7 +28566,7 @@ async function getHmrImplementation(config) {
28513
28566
  //#endregion
28514
28567
  //#region ../../vite/packages/vite/src/node/ssr/fetchModule.ts
28515
28568
  /**
28516
- * Fetch module information for Vite runner.
28569
+ * Fetch module information for Vite module runner.
28517
28570
  * @experimental
28518
28571
  */
28519
28572
  async function fetchModule(environment, url, importer, options = {}) {
@@ -28676,6 +28729,9 @@ function createDepsOptimizer(environment) {
28676
28729
  (async () => {
28677
28730
  try {
28678
28731
  debug$9?.(import_picocolors.default.green(`scanning for dependencies...`));
28732
+ const scanTimer = setTimeout(() => {
28733
+ logger.info("[optimizer] scanning dependencies...", { timestamp: true });
28734
+ }, 1e3);
28679
28735
  let deps;
28680
28736
  try {
28681
28737
  discover = discoverProjectDependencies(devToScanEnvironment(environment));
@@ -28684,6 +28740,8 @@ function createDepsOptimizer(environment) {
28684
28740
  } catch (e) {
28685
28741
  environment.logger.error(import_picocolors.default.red("(!) Failed to run dependency scan. Skipping dependency pre-bundling. " + e.stack));
28686
28742
  return;
28743
+ } finally {
28744
+ clearTimeout(scanTimer);
28687
28745
  }
28688
28746
  const manuallyIncluded = Object.keys(manuallyIncludedDepsInfo);
28689
28747
  discoveredDepsWhileScanning.push(...Object.keys(metadata.discovered).filter((dep) => !deps[dep] && !manuallyIncluded.includes(dep)));
@@ -29614,15 +29672,239 @@ function renderRestrictedErrorHTML(msg) {
29614
29672
  `;
29615
29673
  }
29616
29674
  //#endregion
29617
- //#region ../../vite/packages/vite/src/node/server/transformRequest.ts
29675
+ //#region ../../vite/packages/vite/src/node/server/send.ts
29618
29676
  var import_etag = /* @__PURE__ */ __toESM(require_etag(), 1);
29677
+ const debug$8 = createDebugger("vite:send", { onlyWhenFocused: true });
29678
+ const alias = {
29679
+ js: "text/javascript",
29680
+ css: "text/css",
29681
+ html: "text/html",
29682
+ json: "application/json"
29683
+ };
29684
+ function send(req, res, content, type, options) {
29685
+ const { etag = (0, import_etag.default)(content, { weak: true }), cacheControl = "no-cache", headers, map } = options;
29686
+ if (res.writableEnded) return;
29687
+ if (req.headers["if-none-match"] === etag) {
29688
+ res.statusCode = 304;
29689
+ res.end();
29690
+ return;
29691
+ }
29692
+ res.setHeader("Content-Type", alias[type] || type);
29693
+ res.setHeader("Cache-Control", cacheControl);
29694
+ res.setHeader("Etag", etag);
29695
+ if (headers) for (const name in headers) res.setHeader(name, headers[name]);
29696
+ if (map && "version" in map && map.mappings) {
29697
+ if (type === "js" || type === "css") content = getCodeWithSourcemap(type, content.toString(), map);
29698
+ } else if (type === "js" && (!map || map.mappings !== "")) {
29699
+ const code = content.toString();
29700
+ if (import_convert_source_map.default.mapFileCommentRegex.test(code)) debug$8?.(`Skipped injecting fallback sourcemap for ${req.url}`);
29701
+ else {
29702
+ const urlWithoutTimestamp = removeTimestampQuery(req.url);
29703
+ content = getCodeWithSourcemap(type, code, new MagicString(code).generateMap({
29704
+ source: path.basename(urlWithoutTimestamp),
29705
+ hires: "boundary",
29706
+ includeContent: true
29707
+ }));
29708
+ }
29709
+ }
29710
+ res.statusCode = 200;
29711
+ if (req.method === "HEAD") res.end();
29712
+ else res.end(content);
29713
+ }
29714
+ //#endregion
29715
+ //#region ../../vite/packages/vite/src/node/server/middlewares/transform.ts
29716
+ const debugCache$1 = createDebugger("vite:cache");
29717
+ const knownIgnoreList = new Set(["/", "/favicon.ico"]);
29718
+ const documentFetchDests = new Set([
29719
+ "document",
29720
+ "iframe",
29721
+ "frame",
29722
+ "fencedframe"
29723
+ ]);
29724
+ function isDocumentFetchDest(req) {
29725
+ const fetchDest = req.headers["sec-fetch-dest"];
29726
+ return fetchDest !== void 0 && documentFetchDests.has(fetchDest);
29727
+ }
29728
+ const urlRE = /[?&]url\b/;
29729
+ const rawRE = /[?&]raw\b/;
29730
+ const inlineRE$1 = /[?&]inline\b/;
29731
+ const svgRE = /\.svg\b/;
29732
+ function isServerAccessDeniedForTransform(config, id) {
29733
+ if (rawRE.test(id) || urlRE.test(id) || inlineRE$1.test(id) || svgRE.test(id)) return checkLoadingAccess(config, cleanUrl(id)) !== "allowed" || checkLoadingAccess(config, id) !== "allowed";
29734
+ return false;
29735
+ }
29736
+ /**
29737
+ * A middleware that short-circuits the middleware chain to serve cached transformed modules
29738
+ */
29739
+ function cachedTransformMiddleware(server) {
29740
+ return function viteCachedTransformMiddleware(req, res, next) {
29741
+ const environment = server.environments.client;
29742
+ if (isDocumentFetchDest(req)) {
29743
+ res.appendHeader("Vary", "Sec-Fetch-Dest");
29744
+ return next();
29745
+ }
29746
+ const ifNoneMatch = req.headers["if-none-match"];
29747
+ if (ifNoneMatch) {
29748
+ const moduleByEtag = environment.moduleGraph.getModuleByEtag(ifNoneMatch);
29749
+ if (moduleByEtag?.transformResult?.etag === ifNoneMatch && moduleByEtag.url === req.url) {
29750
+ if (!isCSSRequest(req.url)) {
29751
+ debugCache$1?.(`[304] ${prettifyUrl(req.url, server.config.root)}`);
29752
+ res.statusCode = 304;
29753
+ return res.end();
29754
+ }
29755
+ }
29756
+ }
29757
+ next();
29758
+ };
29759
+ }
29760
+ function transformMiddleware(server) {
29761
+ const { root, publicDir } = server.config;
29762
+ const publicDirInRoot = publicDir.startsWith(withTrailingSlash(root));
29763
+ const publicPath = `${publicDir.slice(root.length)}/`;
29764
+ return async function viteTransformMiddleware(req, res, next) {
29765
+ const environment = server.environments.client;
29766
+ if (req.method !== "GET" && req.method !== "HEAD" || knownIgnoreList.has(req.url) || isDocumentFetchDest(req)) return next();
29767
+ let url;
29768
+ try {
29769
+ url = decodeURI(removeTimestampQuery(req.url)).replace(NULL_BYTE_PLACEHOLDER, "\0");
29770
+ } catch (e) {
29771
+ if (e instanceof URIError) {
29772
+ server.config.logger.warn(import_picocolors.default.yellow(`Malformed URI sequence in request URL: ${removeTimestampQuery(req.url)}`));
29773
+ return next();
29774
+ }
29775
+ return next(e);
29776
+ }
29777
+ const withoutQuery = cleanUrl(url);
29778
+ try {
29779
+ if (withoutQuery.endsWith(".map")) {
29780
+ const depsOptimizer = environment.depsOptimizer;
29781
+ if (depsOptimizer?.isOptimizedDepUrl(url)) {
29782
+ const sourcemapPath = url.startsWith(FS_PREFIX) ? fsPathFromId(url) : normalizePath$1(path.resolve(server.config.root, url.slice(1)));
29783
+ if (!depsOptimizer.isOptimizedDepFile(sourcemapPath)) return next();
29784
+ try {
29785
+ const map = JSON.parse(await fsp.readFile(sourcemapPath, "utf-8"));
29786
+ applySourcemapIgnoreList(map, sourcemapPath, server.config.server.sourcemapIgnoreList, server.config.logger);
29787
+ return send(req, res, JSON.stringify(map), "json", { headers: server.config.server.headers });
29788
+ } catch {
29789
+ const dummySourceMap = {
29790
+ version: 3,
29791
+ file: sourcemapPath.replace(/\.map$/, ""),
29792
+ sources: [],
29793
+ sourcesContent: [],
29794
+ names: [],
29795
+ mappings: ";;;;;;;;;"
29796
+ };
29797
+ return send(req, res, JSON.stringify(dummySourceMap), "json", {
29798
+ cacheControl: "no-cache",
29799
+ headers: server.config.server.headers
29800
+ });
29801
+ }
29802
+ } else {
29803
+ const originalUrl = url.replace(/\.map($|\?)/, "$1");
29804
+ const map = (await environment.moduleGraph.getModuleByUrl(originalUrl))?.transformResult?.map;
29805
+ if (map) return send(req, res, JSON.stringify(map), "json", { headers: server.config.server.headers });
29806
+ else return next();
29807
+ }
29808
+ }
29809
+ if (publicDirInRoot && url.startsWith(publicPath)) warnAboutExplicitPublicPathInUrl(url);
29810
+ if (req.headers["sec-fetch-dest"] === "script" || isJSRequest(url) || isImportRequest(url) || isCSSRequest(url) || isHTMLProxy(url)) {
29811
+ url = removeImportQuery(url);
29812
+ url = unwrapId(url);
29813
+ if (isCSSRequest(url)) {
29814
+ if (req.headers.accept?.includes("text/css") && !isDirectRequest(url)) url = injectQuery(url, "direct");
29815
+ const ifNoneMatch = req.headers["if-none-match"];
29816
+ if (ifNoneMatch && (await environment.moduleGraph.getModuleByUrl(url))?.transformResult?.etag === ifNoneMatch) {
29817
+ debugCache$1?.(`[304] ${prettifyUrl(url, server.config.root)}`);
29818
+ res.statusCode = 304;
29819
+ return res.end();
29820
+ }
29821
+ }
29822
+ const result = await environment.transformRequest(url);
29823
+ if (result) {
29824
+ const depsOptimizer = environment.depsOptimizer;
29825
+ const type = isDirectCSSRequest(url) ? "css" : "js";
29826
+ const isDep = DEP_VERSION_RE.test(url) || depsOptimizer?.isOptimizedDepUrl(url);
29827
+ return send(req, res, result.code, type, {
29828
+ etag: result.etag,
29829
+ cacheControl: isDep ? "max-age=31536000,immutable" : "no-cache",
29830
+ headers: server.config.server.headers,
29831
+ map: result.map
29832
+ });
29833
+ }
29834
+ }
29835
+ } catch (e) {
29836
+ if (e?.code === "ERR_OPTIMIZE_DEPS_PROCESSING_ERROR") {
29837
+ if (!res.writableEnded) {
29838
+ res.statusCode = 504;
29839
+ res.statusMessage = "Optimize Deps Processing Error";
29840
+ res.end();
29841
+ }
29842
+ server.config.logger.error(e.message);
29843
+ return;
29844
+ }
29845
+ if (e?.code === "ERR_OUTDATED_OPTIMIZED_DEP") {
29846
+ if (!res.writableEnded) {
29847
+ res.statusCode = 504;
29848
+ res.statusMessage = "Outdated Optimize Dep";
29849
+ res.end();
29850
+ }
29851
+ return;
29852
+ }
29853
+ if (e?.code === "ERR_CLOSED_SERVER") {
29854
+ if (!res.writableEnded) {
29855
+ res.statusCode = 504;
29856
+ res.statusMessage = "Outdated Request";
29857
+ res.end();
29858
+ }
29859
+ return;
29860
+ }
29861
+ if (e?.code === "ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR") {
29862
+ if (!res.writableEnded) {
29863
+ res.statusCode = 404;
29864
+ res.end();
29865
+ }
29866
+ server.config.logger.warn(import_picocolors.default.yellow(e.message));
29867
+ return;
29868
+ }
29869
+ if (e?.code === "ERR_LOAD_URL") return next();
29870
+ if (e?.code === "ERR_DENIED_ID") {
29871
+ const id = e.id;
29872
+ let servingAccessResult = checkLoadingAccess(server.config, cleanUrl(id));
29873
+ if (servingAccessResult === "allowed") servingAccessResult = checkLoadingAccess(server.config, id);
29874
+ if (servingAccessResult === "denied") {
29875
+ respondWithAccessDenied(id, server, res);
29876
+ return true;
29877
+ }
29878
+ if (servingAccessResult === "fallback") {
29879
+ next();
29880
+ return true;
29881
+ }
29882
+ throw new Error(`Unexpected access result for id ${id}`);
29883
+ }
29884
+ return next(e);
29885
+ }
29886
+ next();
29887
+ };
29888
+ function warnAboutExplicitPublicPathInUrl(url) {
29889
+ let warning;
29890
+ if (isImportRequest(url)) {
29891
+ const rawUrl = removeImportQuery(url);
29892
+ 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, "/"))}.`;
29893
+ else warning = `Assets in public directory cannot be imported from JavaScript.
29894
+ 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"))}.`;
29895
+ } 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, "/"))}.`;
29896
+ server.config.logger.warn(import_picocolors.default.yellow(warning));
29897
+ }
29898
+ }
29899
+ //#endregion
29900
+ //#region ../../vite/packages/vite/src/node/server/transformRequest.ts
29619
29901
  const ERR_LOAD_URL = "ERR_LOAD_URL";
29620
29902
  const ERR_LOAD_PUBLIC_URL = "ERR_LOAD_PUBLIC_URL";
29621
29903
  const ERR_DENIED_ID = "ERR_DENIED_ID";
29622
29904
  const debugLoad = createDebugger("vite:load");
29623
29905
  const debugTransform = createDebugger("vite:transform");
29624
- const debugCache$1 = createDebugger("vite:cache");
29625
- function transformRequest(environment, url, options = {}) {
29906
+ const debugCache = createDebugger("vite:cache");
29907
+ function transformRequest(environment, url, options) {
29626
29908
  if (environment._closing && environment.config.dev.recoverable) throwClosedServerError();
29627
29909
  const timestamp = monotonicDateNow();
29628
29910
  url = removeTimestampQuery(url);
@@ -29670,15 +29952,15 @@ async function doTransform(environment, url, options, timestamp) {
29670
29952
  return result;
29671
29953
  }
29672
29954
  async function getCachedTransformResult(environment, url, module, timestamp) {
29673
- const prettyUrl = debugCache$1 ? prettifyUrl(url, environment.config.root) : "";
29955
+ const prettyUrl = debugCache ? prettifyUrl(url, environment.config.root) : "";
29674
29956
  const softInvalidatedTransformResult = await handleModuleSoftInvalidation(environment, module, timestamp);
29675
29957
  if (softInvalidatedTransformResult) {
29676
- debugCache$1?.(`[memory-hmr] ${prettyUrl}`);
29958
+ debugCache?.(`[memory-hmr] ${prettyUrl}`);
29677
29959
  return softInvalidatedTransformResult;
29678
29960
  }
29679
29961
  const cached = module.transformResult;
29680
29962
  if (cached) {
29681
- debugCache$1?.(`[memory] ${prettyUrl}`);
29963
+ debugCache?.(`[memory] ${prettyUrl}`);
29682
29964
  return cached;
29683
29965
  }
29684
29966
  }
@@ -29686,7 +29968,7 @@ async function loadAndTransform(environment, id, url, options, timestamp, mod, r
29686
29968
  const { config, pluginContainer, logger } = environment;
29687
29969
  const prettyUrl = debugLoad || debugTransform ? prettifyUrl(url, config.root) : "";
29688
29970
  const moduleGraph = environment.moduleGraph;
29689
- if (options.allowId && !options.allowId(id)) {
29971
+ if (!options.skipFsCheck && id[0] !== "\0" && isServerAccessDeniedForTransform(config, id)) {
29690
29972
  const err = /* @__PURE__ */ new Error(`Denied ID ${id}`);
29691
29973
  err.code = ERR_DENIED_ID;
29692
29974
  err.id = id;
@@ -29699,7 +29981,7 @@ async function loadAndTransform(environment, id, url, options, timestamp, mod, r
29699
29981
  const loadResult = await pluginContainer.load(id);
29700
29982
  if (loadResult == null) {
29701
29983
  const file = cleanUrl(id);
29702
- if (environment.config.consumer === "server" || isFileLoadingAllowed(environment.getTopLevelConfig(), slash(file))) {
29984
+ if (options.skipFsCheck || isFileLoadingAllowed(environment.getTopLevelConfig(), slash(file))) {
29703
29985
  try {
29704
29986
  code = await fsp.readFile(file, "utf-8");
29705
29987
  debugLoad?.(`${timeFrom(loadStart)} [fs] ${prettyUrl}`);
@@ -29709,7 +29991,7 @@ async function loadAndTransform(environment, id, url, options, timestamp, mod, r
29709
29991
  if (code != null && environment.pluginContainer.watcher) ensureWatchedFile(environment.pluginContainer.watcher, file, config.root);
29710
29992
  }
29711
29993
  if (code) try {
29712
- const extracted = extractSourcemapFromFile(code, file);
29994
+ const extracted = extractSourcemapFromFile(code, file, logger);
29713
29995
  if (extracted) {
29714
29996
  code = extracted.code;
29715
29997
  map = extracted.map;
@@ -29913,6 +30195,10 @@ var DevEnvironment = class extends BaseEnvironment {
29913
30195
  * @internal
29914
30196
  */
29915
30197
  _remoteRunnerOptions;
30198
+ /**
30199
+ * @internal
30200
+ */
30201
+ _skipFsCheck;
29916
30202
  get pluginContainer() {
29917
30203
  if (!this._pluginContainer) throw new Error(`${this.name} environment.pluginContainer called before initialized`);
29918
30204
  return this._pluginContainer;
@@ -29950,9 +30236,11 @@ var DevEnvironment = class extends BaseEnvironment {
29950
30236
  this.moduleGraph = new EnvironmentModuleGraph(name, (url) => this.pluginContainer.resolveId(url, void 0));
29951
30237
  this._crawlEndFinder = setupOnCrawlEnd();
29952
30238
  this._remoteRunnerOptions = context.remoteRunner ?? {};
30239
+ this._skipFsCheck = !!(context.transport && !(isWebSocketServer in context.transport) && context.transport.skipFsCheck);
29953
30240
  this.hot = context.transport ? isWebSocketServer in context.transport ? context.transport : normalizeHotChannel(context.transport, context.hot) : normalizeHotChannel({}, context.hot);
29954
30241
  this.hot.setInvokeHandler({
29955
30242
  fetchModule: (id, importer, options) => {
30243
+ if (context.disableFetchModule) throw new Error("fetchModule is disabled in this environment");
29956
30244
  return this.fetchModule(id, importer, options);
29957
30245
  },
29958
30246
  getBuiltins: async () => {
@@ -29996,6 +30284,12 @@ var DevEnvironment = class extends BaseEnvironment {
29996
30284
  await this.depsOptimizer?.init();
29997
30285
  warmupFiles(server, this);
29998
30286
  }
30287
+ /**
30288
+ * Called by the module runner to retrieve information about the specified
30289
+ * module. Internally calls `transformRequest` and wraps the result in the
30290
+ * format that the module runner understands.
30291
+ * This method is not meant to be called manually.
30292
+ */
29999
30293
  fetchModule(id, importer, options) {
30000
30294
  return fetchModule(this, id, importer, {
30001
30295
  ...this._remoteRunnerOptions,
@@ -30005,12 +30299,12 @@ var DevEnvironment = class extends BaseEnvironment {
30005
30299
  async reloadModule(module) {
30006
30300
  if (this.config.server.hmr !== false && module.file) updateModules(this, module.file, [module], monotonicDateNow());
30007
30301
  }
30008
- transformRequest(url, options) {
30009
- return transformRequest(this, url, options);
30302
+ transformRequest(url) {
30303
+ return transformRequest(this, url, { skipFsCheck: this._skipFsCheck });
30010
30304
  }
30011
30305
  async warmupRequest(url) {
30012
30306
  try {
30013
- await this.transformRequest(url);
30307
+ await transformRequest(this, url, { skipFsCheck: true });
30014
30308
  } catch (e) {
30015
30309
  if (e?.code === "ERR_OUTDATED_OPTIMIZED_DEP" || e?.code === "ERR_CLOSED_SERVER") return;
30016
30310
  this.logger.error(buildErrorMessage(e, [`Pre-transform error: ${e.message}`], false), {
@@ -30103,7 +30397,7 @@ function setupOnCrawlEnd() {
30103
30397
  }
30104
30398
  //#endregion
30105
30399
  //#region ../../vite/packages/vite/src/node/server/environments/fullBundleEnvironment.ts
30106
- const debug$8 = createDebugger("vite:full-bundle-mode");
30400
+ const debug$7 = createDebugger("vite:full-bundle-mode");
30107
30401
  var MemoryFiles = class {
30108
30402
  files = /* @__PURE__ */ new Map();
30109
30403
  get size() {
@@ -30150,7 +30444,7 @@ var FullBundleDevEnvironment = class extends DevEnvironment {
30150
30444
  }
30151
30445
  async listen(_server) {
30152
30446
  this.hot.listen();
30153
- debug$8?.("INITIAL: setup bundle options");
30447
+ debug$7?.("INITIAL: setup bundle options");
30154
30448
  const rollupOptions = await this.getRolldownOptions();
30155
30449
  if (Array.isArray(rollupOptions.output) && rollupOptions.output.length > 1) throw new Error("multiple output options are not supported in dev mode");
30156
30450
  const outputOptions = Array.isArray(rollupOptions.output) ? rollupOptions.output[0] : rollupOptions.output;
@@ -30174,7 +30468,7 @@ var FullBundleDevEnvironment = class extends DevEnvironment {
30174
30468
  const { updates, changedFiles } = result;
30175
30469
  if (changedFiles.length === 0) return;
30176
30470
  if (updates.every((update) => update.update.type === "Noop")) {
30177
- debug$8?.(`ignored file change for ${changedFiles.join(", ")}`);
30471
+ debug$7?.(`ignored file change for ${changedFiles.join(", ")}`);
30178
30472
  return;
30179
30473
  }
30180
30474
  for (const { clientId, update } of updates) {
@@ -30204,14 +30498,14 @@ var FullBundleDevEnvironment = class extends DevEnvironment {
30204
30498
  },
30205
30499
  watch: { skipWrite: true }
30206
30500
  });
30207
- debug$8?.("INITIAL: setup dev engine");
30501
+ debug$7?.("INITIAL: setup dev engine");
30208
30502
  this.devEngine.run().then(() => {
30209
- debug$8?.("INITIAL: run done");
30503
+ debug$7?.("INITIAL: run done");
30210
30504
  }, (e) => {
30211
- debug$8?.("INITIAL: run error", e);
30505
+ debug$7?.("INITIAL: run error", e);
30212
30506
  });
30213
30507
  this.waitForInitialBuildFinish().then(() => {
30214
- debug$8?.("INITIAL: build done");
30508
+ debug$7?.("INITIAL: build done");
30215
30509
  this.hot.send({
30216
30510
  type: "full-reload",
30217
30511
  path: "*"
@@ -30230,10 +30524,10 @@ var FullBundleDevEnvironment = class extends DevEnvironment {
30230
30524
  (async () => {
30231
30525
  const invalidateCalledModules = this.invalidateCalledModules.get(client);
30232
30526
  if (invalidateCalledModules?.has(m.path)) {
30233
- debug$8?.(`INVALIDATE: invalidate received from ${m.path}, but ignored because it was already invalidated`);
30527
+ debug$7?.(`INVALIDATE: invalidate received from ${m.path}, but ignored because it was already invalidated`);
30234
30528
  return;
30235
30529
  }
30236
- debug$8?.(`INVALIDATE: invalidate received from ${m.path}, re-triggering HMR`);
30530
+ debug$7?.(`INVALIDATE: invalidate received from ${m.path}, re-triggering HMR`);
30237
30531
  if (!invalidateCalledModules) this.invalidateCalledModules.set(client, /* @__PURE__ */ new Set([]));
30238
30532
  this.invalidateCalledModules.get(client).add(m.path);
30239
30533
  let update;
@@ -30258,7 +30552,7 @@ var FullBundleDevEnvironment = class extends DevEnvironment {
30258
30552
  this.devEngine.ensureLatestBuildOutput().then(() => {
30259
30553
  this.debouncedFullReload();
30260
30554
  });
30261
- debug$8?.(`TRIGGER: access to stale bundle, triggered bundle re-generation`);
30555
+ debug$7?.(`TRIGGER: access to stale bundle, triggered bundle re-generation`);
30262
30556
  }
30263
30557
  return shouldTrigger;
30264
30558
  }
@@ -30304,7 +30598,7 @@ var FullBundleDevEnvironment = class extends DevEnvironment {
30304
30598
  });
30305
30599
  return;
30306
30600
  }
30307
- debug$8?.(`handle hmr output for ${shortFile}`, {
30601
+ debug$7?.(`handle hmr output for ${shortFile}`, {
30308
30602
  ...hmrOutput,
30309
30603
  code: typeof hmrOutput.code === "string" ? "[code]" : hmrOutput.code
30310
30604
  });
@@ -30324,7 +30618,10 @@ var FullBundleDevEnvironment = class extends DevEnvironment {
30324
30618
  type: "update",
30325
30619
  updates
30326
30620
  });
30327
- this.logger.info(import_picocolors.default.green(`hmr update `) + import_picocolors.default.dim([...new Set(updates.map((u) => u.path))].join(", ")), {
30621
+ const filePaths = [...new Set(updates.map((u) => u.path))];
30622
+ const { formatted, truncated } = formatAndTruncateFileList(filePaths);
30623
+ if (truncated) debugHmr?.(`hmr update ${filePaths.join(", ")}`);
30624
+ this.logger.info(import_picocolors.default.green(`hmr update `) + import_picocolors.default.dim(formatted), {
30328
30625
  clear: !invalidateInformation,
30329
30626
  timestamp: true
30330
30627
  });
@@ -30368,7 +30665,7 @@ function debounce(time, cb) {
30368
30665
  }
30369
30666
  //#endregion
30370
30667
  //#region ../../vite/packages/vite/src/node/server/middlewares/htmlFallback.ts
30371
- const debug$7 = createDebugger("vite:html-fallback");
30668
+ const debug$6 = createDebugger("vite:html-fallback");
30372
30669
  function htmlFallbackMiddleware(root, spaFallback, clientEnvironment) {
30373
30670
  const memoryFiles = clientEnvironment instanceof FullBundleDevEnvironment ? clientEnvironment.memoryFiles : void 0;
30374
30671
  function checkFileExists(relativePath) {
@@ -30385,252 +30682,31 @@ function htmlFallbackMiddleware(root, spaFallback, clientEnvironment) {
30385
30682
  }
30386
30683
  if (pathname.endsWith(".html")) {
30387
30684
  if (checkFileExists(pathname)) {
30388
- debug$7?.(`Rewriting ${req.method} ${req.url} to ${url}`);
30685
+ debug$6?.(`Rewriting ${req.method} ${req.url} to ${url}`);
30389
30686
  req.url = url;
30390
30687
  return next();
30391
30688
  }
30392
30689
  } else if (pathname.endsWith("/")) {
30393
30690
  if (checkFileExists(joinUrlSegments(pathname, "index.html"))) {
30394
30691
  const newUrl = url + "index.html";
30395
- debug$7?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
30692
+ debug$6?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
30396
30693
  req.url = newUrl;
30397
30694
  return next();
30398
30695
  }
30399
30696
  } else if (checkFileExists(pathname + ".html")) {
30400
30697
  const newUrl = url + ".html";
30401
- debug$7?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
30698
+ debug$6?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
30402
30699
  req.url = newUrl;
30403
30700
  return next();
30404
30701
  }
30405
30702
  if (spaFallback) {
30406
- debug$7?.(`Rewriting ${req.method} ${req.url} to /index.html`);
30703
+ debug$6?.(`Rewriting ${req.method} ${req.url} to /index.html`);
30407
30704
  req.url = "/index.html";
30408
30705
  }
30409
30706
  next();
30410
30707
  };
30411
30708
  }
30412
30709
  //#endregion
30413
- //#region ../../vite/packages/vite/src/node/server/send.ts
30414
- const debug$6 = createDebugger("vite:send", { onlyWhenFocused: true });
30415
- const alias = {
30416
- js: "text/javascript",
30417
- css: "text/css",
30418
- html: "text/html",
30419
- json: "application/json"
30420
- };
30421
- function send(req, res, content, type, options) {
30422
- const { etag = (0, import_etag.default)(content, { weak: true }), cacheControl = "no-cache", headers, map } = options;
30423
- if (res.writableEnded) return;
30424
- if (req.headers["if-none-match"] === etag) {
30425
- res.statusCode = 304;
30426
- res.end();
30427
- return;
30428
- }
30429
- res.setHeader("Content-Type", alias[type] || type);
30430
- res.setHeader("Cache-Control", cacheControl);
30431
- res.setHeader("Etag", etag);
30432
- if (headers) for (const name in headers) res.setHeader(name, headers[name]);
30433
- if (map && "version" in map && map.mappings) {
30434
- if (type === "js" || type === "css") content = getCodeWithSourcemap(type, content.toString(), map);
30435
- } else if (type === "js" && (!map || map.mappings !== "")) {
30436
- const code = content.toString();
30437
- if (import_convert_source_map.default.mapFileCommentRegex.test(code)) debug$6?.(`Skipped injecting fallback sourcemap for ${req.url}`);
30438
- else {
30439
- const urlWithoutTimestamp = removeTimestampQuery(req.url);
30440
- content = getCodeWithSourcemap(type, code, new MagicString(code).generateMap({
30441
- source: path.basename(urlWithoutTimestamp),
30442
- hires: "boundary",
30443
- includeContent: true
30444
- }));
30445
- }
30446
- }
30447
- res.statusCode = 200;
30448
- if (req.method === "HEAD") res.end();
30449
- else res.end(content);
30450
- }
30451
- //#endregion
30452
- //#region ../../vite/packages/vite/src/node/server/middlewares/transform.ts
30453
- const debugCache = createDebugger("vite:cache");
30454
- const knownIgnoreList = new Set(["/", "/favicon.ico"]);
30455
- const documentFetchDests = new Set([
30456
- "document",
30457
- "iframe",
30458
- "frame",
30459
- "fencedframe"
30460
- ]);
30461
- function isDocumentFetchDest(req) {
30462
- const fetchDest = req.headers["sec-fetch-dest"];
30463
- return fetchDest !== void 0 && documentFetchDests.has(fetchDest);
30464
- }
30465
- const urlRE = /[?&]url\b/;
30466
- const rawRE = /[?&]raw\b/;
30467
- const inlineRE$1 = /[?&]inline\b/;
30468
- const svgRE = /\.svg\b/;
30469
- function isServerAccessDeniedForTransform(config, id) {
30470
- if (rawRE.test(id) || urlRE.test(id) || inlineRE$1.test(id) || svgRE.test(id)) return checkLoadingAccess(config, id) !== "allowed";
30471
- return false;
30472
- }
30473
- /**
30474
- * A middleware that short-circuits the middleware chain to serve cached transformed modules
30475
- */
30476
- function cachedTransformMiddleware(server) {
30477
- return function viteCachedTransformMiddleware(req, res, next) {
30478
- const environment = server.environments.client;
30479
- if (isDocumentFetchDest(req)) {
30480
- res.appendHeader("Vary", "Sec-Fetch-Dest");
30481
- return next();
30482
- }
30483
- const ifNoneMatch = req.headers["if-none-match"];
30484
- if (ifNoneMatch) {
30485
- const moduleByEtag = environment.moduleGraph.getModuleByEtag(ifNoneMatch);
30486
- if (moduleByEtag?.transformResult?.etag === ifNoneMatch && moduleByEtag.url === req.url) {
30487
- if (!isCSSRequest(req.url)) {
30488
- debugCache?.(`[304] ${prettifyUrl(req.url, server.config.root)}`);
30489
- res.statusCode = 304;
30490
- return res.end();
30491
- }
30492
- }
30493
- }
30494
- next();
30495
- };
30496
- }
30497
- function transformMiddleware(server) {
30498
- const { root, publicDir } = server.config;
30499
- const publicDirInRoot = publicDir.startsWith(withTrailingSlash(root));
30500
- const publicPath = `${publicDir.slice(root.length)}/`;
30501
- return async function viteTransformMiddleware(req, res, next) {
30502
- const environment = server.environments.client;
30503
- if (req.method !== "GET" && req.method !== "HEAD" || knownIgnoreList.has(req.url) || isDocumentFetchDest(req)) return next();
30504
- let url;
30505
- try {
30506
- url = decodeURI(removeTimestampQuery(req.url)).replace(NULL_BYTE_PLACEHOLDER, "\0");
30507
- } catch (e) {
30508
- if (e instanceof URIError) {
30509
- server.config.logger.warn(import_picocolors.default.yellow(`Malformed URI sequence in request URL: ${removeTimestampQuery(req.url)}`));
30510
- return next();
30511
- }
30512
- return next(e);
30513
- }
30514
- const withoutQuery = cleanUrl(url);
30515
- try {
30516
- if (withoutQuery.endsWith(".map")) if (environment.depsOptimizer?.isOptimizedDepUrl(url)) {
30517
- const sourcemapPath = url.startsWith(FS_PREFIX) ? fsPathFromId(url) : normalizePath$1(path.resolve(server.config.root, url.slice(1)));
30518
- try {
30519
- const map = JSON.parse(await fsp.readFile(sourcemapPath, "utf-8"));
30520
- applySourcemapIgnoreList(map, sourcemapPath, server.config.server.sourcemapIgnoreList, server.config.logger);
30521
- return send(req, res, JSON.stringify(map), "json", { headers: server.config.server.headers });
30522
- } catch {
30523
- const dummySourceMap = {
30524
- version: 3,
30525
- file: sourcemapPath.replace(/\.map$/, ""),
30526
- sources: [],
30527
- sourcesContent: [],
30528
- names: [],
30529
- mappings: ";;;;;;;;;"
30530
- };
30531
- return send(req, res, JSON.stringify(dummySourceMap), "json", {
30532
- cacheControl: "no-cache",
30533
- headers: server.config.server.headers
30534
- });
30535
- }
30536
- } else {
30537
- const originalUrl = url.replace(/\.map($|\?)/, "$1");
30538
- const map = (await environment.moduleGraph.getModuleByUrl(originalUrl))?.transformResult?.map;
30539
- if (map) return send(req, res, JSON.stringify(map), "json", { headers: server.config.server.headers });
30540
- else return next();
30541
- }
30542
- if (publicDirInRoot && url.startsWith(publicPath)) warnAboutExplicitPublicPathInUrl(url);
30543
- if (req.headers["sec-fetch-dest"] === "script" || isJSRequest(url) || isImportRequest(url) || isCSSRequest(url) || isHTMLProxy(url)) {
30544
- url = removeImportQuery(url);
30545
- url = unwrapId(url);
30546
- if (isCSSRequest(url)) {
30547
- if (req.headers.accept?.includes("text/css") && !isDirectRequest(url)) url = injectQuery(url, "direct");
30548
- const ifNoneMatch = req.headers["if-none-match"];
30549
- if (ifNoneMatch && (await environment.moduleGraph.getModuleByUrl(url))?.transformResult?.etag === ifNoneMatch) {
30550
- debugCache?.(`[304] ${prettifyUrl(url, server.config.root)}`);
30551
- res.statusCode = 304;
30552
- return res.end();
30553
- }
30554
- }
30555
- const result = await environment.transformRequest(url, { allowId(id) {
30556
- return id[0] === "\0" || !isServerAccessDeniedForTransform(server.config, id);
30557
- } });
30558
- if (result) {
30559
- const depsOptimizer = environment.depsOptimizer;
30560
- const type = isDirectCSSRequest(url) ? "css" : "js";
30561
- const isDep = DEP_VERSION_RE.test(url) || depsOptimizer?.isOptimizedDepUrl(url);
30562
- return send(req, res, result.code, type, {
30563
- etag: result.etag,
30564
- cacheControl: isDep ? "max-age=31536000,immutable" : "no-cache",
30565
- headers: server.config.server.headers,
30566
- map: result.map
30567
- });
30568
- }
30569
- }
30570
- } catch (e) {
30571
- if (e?.code === "ERR_OPTIMIZE_DEPS_PROCESSING_ERROR") {
30572
- if (!res.writableEnded) {
30573
- res.statusCode = 504;
30574
- res.statusMessage = "Optimize Deps Processing Error";
30575
- res.end();
30576
- }
30577
- server.config.logger.error(e.message);
30578
- return;
30579
- }
30580
- if (e?.code === "ERR_OUTDATED_OPTIMIZED_DEP") {
30581
- if (!res.writableEnded) {
30582
- res.statusCode = 504;
30583
- res.statusMessage = "Outdated Optimize Dep";
30584
- res.end();
30585
- }
30586
- return;
30587
- }
30588
- if (e?.code === "ERR_CLOSED_SERVER") {
30589
- if (!res.writableEnded) {
30590
- res.statusCode = 504;
30591
- res.statusMessage = "Outdated Request";
30592
- res.end();
30593
- }
30594
- return;
30595
- }
30596
- if (e?.code === "ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR") {
30597
- if (!res.writableEnded) {
30598
- res.statusCode = 404;
30599
- res.end();
30600
- }
30601
- server.config.logger.warn(import_picocolors.default.yellow(e.message));
30602
- return;
30603
- }
30604
- if (e?.code === "ERR_LOAD_URL") return next();
30605
- if (e?.code === "ERR_DENIED_ID") {
30606
- const id = e.id;
30607
- const servingAccessResult = checkLoadingAccess(server.config, id);
30608
- if (servingAccessResult === "denied") {
30609
- respondWithAccessDenied(id, server, res);
30610
- return true;
30611
- }
30612
- if (servingAccessResult === "fallback") {
30613
- next();
30614
- return true;
30615
- }
30616
- throw new Error(`Unexpected access result for id ${id}`);
30617
- }
30618
- return next(e);
30619
- }
30620
- next();
30621
- };
30622
- function warnAboutExplicitPublicPathInUrl(url) {
30623
- let warning;
30624
- if (isImportRequest(url)) {
30625
- const rawUrl = removeImportQuery(url);
30626
- 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, "/"))}.`;
30627
- else warning = `Assets in public directory cannot be imported from JavaScript.
30628
- 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"))}.`;
30629
- } 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, "/"))}.`;
30630
- server.config.logger.warn(import_picocolors.default.yellow(warning));
30631
- }
30632
- }
30633
- //#endregion
30634
30710
  //#region ../../vite/packages/vite/src/node/server/middlewares/indexHtml.ts
30635
30711
  function createDevHtmlTransformFn(config) {
30636
30712
  const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms(config.plugins);
@@ -31374,7 +31450,7 @@ function getAdditionalAllowedHosts(resolvedServerOptions, resolvedPreviewOptions
31374
31450
  return list;
31375
31451
  }
31376
31452
  function hostValidationMiddleware(allowedHosts, isPreview) {
31377
- return hostValidationMiddleware$2({
31453
+ return hostValidationMiddleware$1({
31378
31454
  allowedHosts: Object.freeze([...allowedHosts]),
31379
31455
  generateErrorMessage(hostname) {
31380
31456
  const hostnameWithQuotes = JSON.stringify(hostname);
@@ -32250,7 +32326,10 @@ function updateModules(environment, file, modules, timestamp, firstInvalidatedBy
32250
32326
  debugHmr?.(import_picocolors.default.yellow(`no update happened `) + import_picocolors.default.dim(file));
32251
32327
  return;
32252
32328
  }
32253
- environment.logger.info(import_picocolors.default.green(`hmr update `) + import_picocolors.default.dim([...new Set(updates.map((u) => u.path))].join(", ")), {
32329
+ const filePaths = [...new Set(updates.map((u) => u.path))];
32330
+ const { formatted, truncated } = formatAndTruncateFileList(filePaths);
32331
+ if (truncated) debugHmr?.(`hmr update ${filePaths.join(", ")}`);
32332
+ environment.logger.info(import_picocolors.default.green(`hmr update `) + import_picocolors.default.dim(formatted), {
32254
32333
  clear: !firstInvalidatedBy,
32255
32334
  timestamp: true
32256
32335
  });
@@ -32456,6 +32535,7 @@ function createServerHotChannel() {
32456
32535
  const innerEmitter = new EventEmitter();
32457
32536
  const outsideEmitter = new EventEmitter();
32458
32537
  return {
32538
+ skipFsCheck: true,
32459
32539
  send(payload) {
32460
32540
  outsideEmitter.emit("send", payload);
32461
32541
  },
@@ -34625,7 +34705,7 @@ function createFilterForTransform(idFilter, codeFilter, moduleTypeFilter, cwd) {
34625
34705
  };
34626
34706
  }
34627
34707
  //#endregion
34628
- //#region ../../node_modules/.pnpm/@vitest+utils@4.1.0/node_modules/@vitest/utils/dist/helpers.js
34708
+ //#region ../../node_modules/.pnpm/@vitest+utils@4.1.2/node_modules/@vitest/utils/dist/helpers.js
34629
34709
  function notNullish(v) {
34630
34710
  return v != null;
34631
34711
  }
@@ -34633,7 +34713,7 @@ function isPrimitive(value) {
34633
34713
  return value === null || typeof value !== "function" && typeof value !== "object";
34634
34714
  }
34635
34715
  //#endregion
34636
- //#region ../../node_modules/.pnpm/@vitest+utils@4.1.0/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js
34716
+ //#region ../../node_modules/.pnpm/@vitest+utils@4.1.2/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js
34637
34717
  const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
34638
34718
  function normalizeWindowsPath(input = "") {
34639
34719
  if (!input) return input;
@@ -34712,7 +34792,7 @@ const isAbsolute$2 = function(p) {
34712
34792
  return _IS_ABSOLUTE_RE.test(p);
34713
34793
  };
34714
34794
  //#endregion
34715
- //#region ../../node_modules/.pnpm/@vitest+utils@4.1.0/node_modules/@vitest/utils/dist/source-map.js
34795
+ //#region ../../node_modules/.pnpm/@vitest+utils@4.1.2/node_modules/@vitest/utils/dist/source-map.js
34716
34796
  var comma = ",".charCodeAt(0);
34717
34797
  var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
34718
34798
  var intToChar = new Uint8Array(64);
@@ -35116,7 +35196,7 @@ function formatError(payload, environment, sourceMapCache) {
35116
35196
  const result = environment.moduleGraph.getModuleById(id)?.transformResult;
35117
35197
  if (result && !result.map) try {
35118
35198
  const filePath = id.split("?")[0];
35119
- const extracted = extractSourcemapFromFile(result.code, filePath);
35199
+ const extracted = extractSourcemapFromFile(result.code, filePath, environment.config.logger);
35120
35200
  sourceMapCache.set(id, extracted?.map);
35121
35201
  return extracted?.map;
35122
35202
  } catch {
@@ -36921,9 +37001,15 @@ function runOptimizeDeps(environment, depsInfo) {
36921
37001
  cancel: cleanUp
36922
37002
  };
36923
37003
  const start = performance$1.now();
37004
+ const bundleTimer = setTimeout(() => {
37005
+ environment.logger.info("[optimizer] bundling dependencies...", { timestamp: true });
37006
+ }, 1e3);
36924
37007
  const preparedRun = prepareRolldownOptimizerRun(environment, depsInfo, processingCacheDir, optimizerContext);
36925
37008
  const runResult = preparedRun.then(({ context, idToExports }) => {
36926
- if (!context || optimizerContext.cancelled) return cancelledResult;
37009
+ if (!context || optimizerContext.cancelled) {
37010
+ clearTimeout(bundleTimer);
37011
+ return cancelledResult;
37012
+ }
36927
37013
  return context.build().then((result) => {
36928
37014
  const depForEntryFileName = {};
36929
37015
  for (const dep of Object.values(depsInfo)) {
@@ -36954,9 +37040,11 @@ function runOptimizeDeps(environment, depsInfo) {
36954
37040
  });
36955
37041
  }
36956
37042
  }
37043
+ clearTimeout(bundleTimer);
36957
37044
  debug$2?.(`Dependencies bundled in ${(performance$1.now() - start).toFixed(2)}ms`);
36958
37045
  return successfulResult;
36959
37046
  }).catch((e) => {
37047
+ clearTimeout(bundleTimer);
36960
37048
  if (e.errors && e.message.includes("The build was canceled")) return cancelledResult;
36961
37049
  e.message = import_picocolors.default.red("Error during dependency optimization:\n\n") + e.message;
36962
37050
  throw e;
@@ -37584,6 +37672,7 @@ function resolveSubpathImports(id, importer, options) {
37584
37672
  importsPath = path.relative(basedir, path.join(pkgData.dir, importsPath));
37585
37673
  if (!relativePrefixRE.test(importsPath)) importsPath = `./${importsPath}`;
37586
37674
  }
37675
+ if (importsPath == null) return;
37587
37676
  return importsPath + postfix;
37588
37677
  }
37589
37678
  function ensureVersionQuery(resolved, id, options, depsOptimizer) {
@@ -38217,7 +38306,7 @@ const _buildEnvironmentOptionsDefaults = Object.freeze({
38217
38306
  watch: null
38218
38307
  });
38219
38308
  const buildEnvironmentOptionsDefaults = _buildEnvironmentOptionsDefaults;
38220
- function resolveBuildEnvironmentOptions(raw, logger, consumer, isBundledDev) {
38309
+ function resolveBuildEnvironmentOptions(raw, logger, consumer, isBundledDev, isSsrTargetWebworkerEnvironment) {
38221
38310
  const deprecatedPolyfillModulePreload = raw.polyfillModulePreload;
38222
38311
  const { polyfillModulePreload, ...rest } = raw;
38223
38312
  raw = rest;
@@ -38235,7 +38324,7 @@ function resolveBuildEnvironmentOptions(raw, logger, consumer, isBundledDev) {
38235
38324
  }, raw);
38236
38325
  setupRollupOptionCompat(merged, "build");
38237
38326
  merged.rolldownOptions = {
38238
- platform: consumer === "server" ? "node" : "browser",
38327
+ platform: consumer === "client" || isSsrTargetWebworkerEnvironment ? "browser" : "node",
38239
38328
  ...merged.rolldownOptions
38240
38329
  };
38241
38330
  if (merged.target === "baseline-widely-available") merged.target = ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET;
@@ -38329,6 +38418,7 @@ function resolveRolldownOptions(environment, chunkMetadataMap) {
38329
38418
  }
38330
38419
  };
38331
38420
  const isSsrTargetWebworkerEnvironment = environment.name === "ssr" && environment.getTopLevelConfig().ssr?.target === "webworker";
38421
+ if (isSsrTargetWebworkerEnvironment) plugins.push(esmExternalRequirePlugin());
38332
38422
  const buildOutputOptions = (output = {}) => {
38333
38423
  if (output.output) logger.warn("You've set \"rollupOptions.output.output\" in your config. This is deprecated and will override all Vite.js default output options. Please use \"rollupOptions.output\" instead.");
38334
38424
  if (output.file) throw new Error("Vite does not support \"rollupOptions.output.file\". Please use \"rollupOptions.output.dir\" and \"rollupOptions.output.entryFileNames\" instead.");
@@ -39324,7 +39414,8 @@ function defaultCreateClientDevEnvironment(name, config, context) {
39324
39414
  });
39325
39415
  return new DevEnvironment(name, config, {
39326
39416
  hot: true,
39327
- transport: context.ws
39417
+ transport: context.ws,
39418
+ disableFetchModule: true
39328
39419
  });
39329
39420
  }
39330
39421
  function defaultCreateDevEnvironment(name, config) {
@@ -39449,7 +39540,7 @@ function resolveEnvironmentOptions(options, alias, preserveSymlinks, forceOptimi
39449
39540
  consumer,
39450
39541
  optimizeDeps: resolveDepOptimizationOptions(options.optimizeDeps, resolve.preserveSymlinks, forceOptimizeDeps, consumer, logger),
39451
39542
  dev: resolveDevEnvironmentOptions(options.dev, environmentName, consumer, preTransformRequests),
39452
- build: resolveBuildEnvironmentOptions(options.build ?? {}, logger, consumer, isBundledDev),
39543
+ build: resolveBuildEnvironmentOptions(options.build ?? {}, logger, consumer, isBundledDev, isSsrTargetWebworkerEnvironment),
39453
39544
  plugins: void 0,
39454
39545
  optimizeDepsPluginNames: void 0
39455
39546
  };
@@ -40245,4 +40336,4 @@ const parseAst$1 = parseAst;
40245
40336
  const parseAstAsync$1 = parseAstAsync;
40246
40337
  const esbuildVersion = "0.25.0";
40247
40338
  //#endregion
40248
- 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$1 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 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 };
40339
+ 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$1 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 };