vite 4.3.0-beta.6 → 4.3.0-beta.8

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.

Potentially problematic release.


This version of vite might be problematic. Click here for more details.

@@ -1,6 +1,6 @@
1
1
  import fs$l, { promises as promises$2 } from 'node:fs';
2
2
  import fsp from 'node:fs/promises';
3
- import path$o, { posix as posix$1, isAbsolute as isAbsolute$2, join as join$2, relative as relative$2, dirname as dirname$2, basename as basename$2, extname as extname$1 } from 'node:path';
3
+ import path$o, { dirname as dirname$2, join as join$2, posix as posix$1, isAbsolute as isAbsolute$2, relative as relative$2, basename as basename$2, extname as extname$1 } from 'node:path';
4
4
  import { fileURLToPath, URL as URL$3, URLSearchParams, parse as parse$i, pathToFileURL } from 'node:url';
5
5
  import { performance as performance$1 } from 'node:perf_hooks';
6
6
  import { createRequire as createRequire$1, builtinModules } from 'node:module';
@@ -11562,7 +11562,9 @@ function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageC
11562
11562
  return packageCache.get(cacheKey);
11563
11563
  let pkg;
11564
11564
  try {
11565
- pkg = pnp.resolveToUnqualified(pkgName, basedir);
11565
+ pkg = pnp.resolveToUnqualified(pkgName, basedir, {
11566
+ considerBuiltins: false,
11567
+ });
11566
11568
  }
11567
11569
  catch {
11568
11570
  return null;
@@ -13632,6 +13634,63 @@ var TSConfckParseError = class extends Error {
13632
13634
  }
13633
13635
  };
13634
13636
 
13637
+ // https://github.com/vitejs/vite/issues/2820#issuecomment-812495079
13638
+ const ROOT_FILES = [
13639
+ // '.git',
13640
+ // https://pnpm.io/workspaces/
13641
+ 'pnpm-workspace.yaml',
13642
+ // https://rushjs.io/pages/advanced/config_files/
13643
+ // 'rush.json',
13644
+ // https://nx.dev/latest/react/getting-started/nx-setup
13645
+ // 'workspace.json',
13646
+ // 'nx.json',
13647
+ // https://github.com/lerna/lerna#lernajson
13648
+ 'lerna.json',
13649
+ ];
13650
+ // npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces
13651
+ // yarn: https://classic.yarnpkg.com/en/docs/workspaces/#toc-how-to-use-it
13652
+ function hasWorkspacePackageJSON(root) {
13653
+ const path = join$2(root, 'package.json');
13654
+ if (!isFileReadable(path)) {
13655
+ return false;
13656
+ }
13657
+ const content = JSON.parse(fs$l.readFileSync(path, 'utf-8')) || {};
13658
+ return !!content.workspaces;
13659
+ }
13660
+ function hasRootFile(root) {
13661
+ return ROOT_FILES.some((file) => fs$l.existsSync(join$2(root, file)));
13662
+ }
13663
+ function hasPackageJSON(root) {
13664
+ const path = join$2(root, 'package.json');
13665
+ return fs$l.existsSync(path);
13666
+ }
13667
+ /**
13668
+ * Search up for the nearest `package.json`
13669
+ */
13670
+ function searchForPackageRoot(current, root = current) {
13671
+ if (hasPackageJSON(current))
13672
+ return current;
13673
+ const dir = dirname$2(current);
13674
+ // reach the fs root
13675
+ if (!dir || dir === current)
13676
+ return root;
13677
+ return searchForPackageRoot(dir, root);
13678
+ }
13679
+ /**
13680
+ * Search up for the nearest workspace root
13681
+ */
13682
+ function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) {
13683
+ if (hasRootFile(current))
13684
+ return current;
13685
+ if (hasWorkspacePackageJSON(current))
13686
+ return current;
13687
+ const dir = dirname$2(current);
13688
+ // reach the fs root
13689
+ if (!dir || dir === current)
13690
+ return root;
13691
+ return searchForWorkspaceRoot(dir, root);
13692
+ }
13693
+
13635
13694
  const debug$f = createDebugger('vite:esbuild');
13636
13695
  const INJECT_HELPERS_IIFE_RE = /^(.*?)((?:const|var)\s+\S+\s*=\s*function\s*\([^)]*\)\s*\{.*?"use strict";)/s;
13637
13696
  const INJECT_HELPERS_UMD_RE = /^(.*?)(\(function\([^)]*\)\s*\{.+?amd.+?function\([^)]*\)\s*\{.*?"use strict";)/s;
@@ -28652,6 +28711,7 @@ function optimizedDepsBuildPlugin(config) {
28652
28711
  depsOptimizer.delayDepsOptimizerUntil(resolved.id, async () => {
28653
28712
  await this.load(resolved);
28654
28713
  });
28714
+ return resolved;
28655
28715
  }
28656
28716
  }
28657
28717
  },
@@ -37834,8 +37894,14 @@ function cssPlugin(config) {
37834
37894
  return fileToUrl(resolved, config, this);
37835
37895
  }
37836
37896
  if (config.command === 'build') {
37837
- // #9800 If we cannot resolve the css url, leave a warning.
37838
- config.logger.warnOnce(`\n${url} referenced in ${id} didn't resolve at build time, it will remain unchanged to be resolved at runtime`);
37897
+ const isExternal = config.build.rollupOptions.external
37898
+ ? resolveUserExternal(config.build.rollupOptions.external, url, // use URL as id since id could not be resolved
37899
+ id, false)
37900
+ : false;
37901
+ if (!isExternal) {
37902
+ // #9800 If we cannot resolve the css url, leave a warning.
37903
+ config.logger.warnOnce(`\n${url} referenced in ${id} didn't resolve at build time, it will remain unchanged to be resolved at runtime`);
37904
+ }
37839
37905
  }
37840
37906
  return url;
37841
37907
  };
@@ -38498,7 +38564,7 @@ function createCachedImport(imp) {
38498
38564
  };
38499
38565
  }
38500
38566
  const importPostcssImport = createCachedImport(() => import('./dep-e3f470e2.js').then(function (n) { return n.i; }));
38501
- const importPostcssModules = createCachedImport(() => import('./dep-9ae8857c.js').then(function (n) { return n.i; }));
38567
+ const importPostcssModules = createCachedImport(() => import('./dep-4190ce4e.js').then(function (n) { return n.i; }));
38502
38568
  const importPostcss = createCachedImport(() => import('postcss'));
38503
38569
  /**
38504
38570
  * @experimental
@@ -43836,18 +43902,17 @@ async function createDepsOptimizer(config, server) {
43836
43902
  crawlEndFinder?.ensureFirstRun();
43837
43903
  }
43838
43904
  }
43839
- const runOptimizerIfIdleAfterMs = 50;
43905
+ const callCrawlEndIfIdleAfterMs = 50;
43840
43906
  function setupOnCrawlEnd(onCrawlEnd) {
43841
- let registeredIds = [];
43907
+ const registeredIds = new Set();
43842
43908
  const seenIds = new Set();
43843
43909
  const workersSources = new Set();
43844
- const waitingOn = new Map();
43845
- let firstRunEnsured = false;
43846
- let crawlEndCalled = false;
43910
+ let timeoutHandle;
43847
43911
  let cancelled = false;
43848
43912
  function cancel() {
43849
43913
  cancelled = true;
43850
43914
  }
43915
+ let crawlEndCalled = false;
43851
43916
  function callOnCrawlEnd() {
43852
43917
  if (!cancelled && !crawlEndCalled) {
43853
43918
  crawlEndCalled = true;
@@ -43857,13 +43922,14 @@ function setupOnCrawlEnd(onCrawlEnd) {
43857
43922
  // If all the inputs are dependencies, we aren't going to get any
43858
43923
  // delayDepsOptimizerUntil(id) calls. We need to guard against this
43859
43924
  // by forcing a rerun if no deps have been registered
43925
+ let firstRunEnsured = false;
43860
43926
  function ensureFirstRun() {
43861
43927
  if (!firstRunEnsured && seenIds.size === 0) {
43862
43928
  setTimeout(() => {
43863
43929
  if (seenIds.size === 0) {
43864
43930
  callOnCrawlEnd();
43865
43931
  }
43866
- }, runOptimizerIfIdleAfterMs);
43932
+ }, 200);
43867
43933
  }
43868
43934
  firstRunEnsured = true;
43869
43935
  }
@@ -43871,60 +43937,35 @@ function setupOnCrawlEnd(onCrawlEnd) {
43871
43937
  workersSources.add(id);
43872
43938
  // Avoid waiting for this id, as it may be blocked by the rollup
43873
43939
  // bundling process of the worker that also depends on the optimizer
43874
- registeredIds = registeredIds.filter((registered) => registered.id !== id);
43875
- const resolve = waitingOn.get(id);
43876
- // Forced resolve to avoid waiting for the bundling of the worker to finish
43877
- resolve?.();
43940
+ registeredIds.delete(id);
43941
+ checkIfCrawlEndAfterTimeout();
43878
43942
  }
43879
43943
  function delayDepsOptimizerUntil(id, done) {
43880
43944
  if (!seenIds.has(id)) {
43881
43945
  seenIds.add(id);
43882
- registeredIds.push({ id, done });
43883
- callOnCrawlEndWhenIdle();
43946
+ if (!workersSources.has(id)) {
43947
+ registeredIds.add(id);
43948
+ done()
43949
+ .catch(() => { })
43950
+ .finally(() => markIdAsDone(id));
43951
+ }
43884
43952
  }
43885
43953
  }
43954
+ function markIdAsDone(id) {
43955
+ registeredIds.delete(id);
43956
+ checkIfCrawlEndAfterTimeout();
43957
+ }
43958
+ function checkIfCrawlEndAfterTimeout() {
43959
+ if (cancelled || registeredIds.size > 0)
43960
+ return;
43961
+ if (timeoutHandle)
43962
+ clearTimeout(timeoutHandle);
43963
+ timeoutHandle = setTimeout(callOnCrawlEndWhenIdle, callCrawlEndIfIdleAfterMs);
43964
+ }
43886
43965
  async function callOnCrawlEndWhenIdle() {
43887
- if (cancelled || waitingOn.size > 0)
43966
+ if (cancelled || registeredIds.size > 0)
43888
43967
  return;
43889
- const processingRegisteredIds = registeredIds;
43890
- registeredIds = [];
43891
- const donePromises = processingRegisteredIds.map(async (registeredId) => {
43892
- // During build, we need to cancel workers
43893
- let resolve;
43894
- const waitUntilDone = new Promise((_resolve) => {
43895
- resolve = _resolve;
43896
- registeredId
43897
- .done()
43898
- .catch(() => {
43899
- // Ignore errors
43900
- })
43901
- .finally(() => resolve());
43902
- });
43903
- waitingOn.set(registeredId.id, () => resolve());
43904
- await waitUntilDone;
43905
- waitingOn.delete(registeredId.id);
43906
- });
43907
- const afterLoad = () => {
43908
- if (cancelled)
43909
- return;
43910
- if (registeredIds.length > 0 &&
43911
- registeredIds.every((registeredId) => workersSources.has(registeredId.id))) {
43912
- return;
43913
- }
43914
- if (registeredIds.length > 0) {
43915
- callOnCrawlEndWhenIdle();
43916
- }
43917
- else {
43918
- callOnCrawlEnd();
43919
- }
43920
- };
43921
- await Promise.allSettled(donePromises);
43922
- if (registeredIds.length > 0) {
43923
- afterLoad();
43924
- }
43925
- else {
43926
- setTimeout(afterLoad, runOptimizerIfIdleAfterMs);
43927
- }
43968
+ callOnCrawlEnd();
43928
43969
  }
43929
43970
  return {
43930
43971
  ensureFirstRun,
@@ -44038,22 +44079,18 @@ function addOptimizedDepInfo(metadata, type, depInfo) {
44038
44079
  metadata.depInfoList.push(depInfo);
44039
44080
  return depInfo;
44040
44081
  }
44082
+ let firstLoadCachedDepOptimizationMetadata = true;
44041
44083
  /**
44042
44084
  * Creates the initial dep optimization metadata, loading it from the deps cache
44043
44085
  * if it exists and pre-bundling isn't forced
44044
44086
  */
44045
44087
  async function loadCachedDepOptimizationMetadata(config, ssr, force = config.optimizeDeps.force, asCommand = false) {
44046
44088
  const log = asCommand ? config.logger.info : debug$7;
44047
- setTimeout(() => {
44048
- // Before Vite 2.9, dependencies were cached in the root of the cacheDir
44049
- // For compat, we remove the cache if we find the old structure
44050
- if (fs$l.existsSync(path$o.join(config.cacheDir, '_metadata.json'))) {
44051
- emptyDir(config.cacheDir);
44052
- }
44053
- // Fire a clean up of stale cache dirs, in case old processes didn't
44054
- // terminate correctly
44055
- cleanupDepsCacheStaleDirs(config);
44056
- }, 100);
44089
+ if (firstLoadCachedDepOptimizationMetadata) {
44090
+ firstLoadCachedDepOptimizationMetadata = false;
44091
+ // Fire up a clean up of stale processing deps dirs if older process exited early
44092
+ setTimeout(() => cleanupDepsCacheStaleDirs(config), 0);
44093
+ }
44057
44094
  const depsCacheDir = getDepsCacheDir(config, ssr);
44058
44095
  if (!force) {
44059
44096
  let cachedMetadata;
@@ -44300,7 +44337,7 @@ async function prepareEsbuildOptimizerRun(resolvedConfig, depsInfo, ssr, process
44300
44337
  const idToExports = {};
44301
44338
  const optimizeDeps = getDepOptimizationConfig(config, ssr);
44302
44339
  const { plugins: pluginsFromConfig = [], ...esbuildOptions } = optimizeDeps?.esbuildOptions ?? {};
44303
- for (const id in depsInfo) {
44340
+ await Promise.all(Object.keys(depsInfo).map(async (id) => {
44304
44341
  const src = depsInfo[id].src;
44305
44342
  const exportsData = await (depsInfo[id].exportsData ??
44306
44343
  extractExportsData(src, config, ssr));
@@ -44315,7 +44352,7 @@ async function prepareEsbuildOptimizerRun(resolvedConfig, depsInfo, ssr, process
44315
44352
  const flatId = flattenId(id);
44316
44353
  flatIdDeps[flatId] = src;
44317
44354
  idToExports[id] = exportsData;
44318
- }
44355
+ }));
44319
44356
  if (optimizerContext.cancelled)
44320
44357
  return { context: undefined, idToExports };
44321
44358
  // esbuild automatically replaces process.env.NODE_ENV for platform 'browser'
@@ -45587,61 +45624,489 @@ function send$2(req, res, content, type, options) {
45587
45624
  return;
45588
45625
  }
45589
45626
 
45590
- // https://github.com/vitejs/vite/issues/2820#issuecomment-812495079
45591
- const ROOT_FILES = [
45592
- // '.git',
45593
- // https://pnpm.io/workspaces/
45594
- 'pnpm-workspace.yaml',
45595
- // https://rushjs.io/pages/advanced/config_files/
45596
- // 'rush.json',
45597
- // https://nx.dev/latest/react/getting-started/nx-setup
45598
- // 'workspace.json',
45599
- // 'nx.json',
45600
- // https://github.com/lerna/lerna#lernajson
45601
- 'lerna.json',
45602
- ];
45603
- // npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces
45604
- // yarn: https://classic.yarnpkg.com/en/docs/workspaces/#toc-how-to-use-it
45605
- function hasWorkspacePackageJSON(root) {
45606
- const path = join$2(root, 'package.json');
45607
- if (!isFileReadable(path)) {
45608
- return false;
45609
- }
45610
- const content = JSON.parse(fs$l.readFileSync(path, 'utf-8')) || {};
45611
- return !!content.workspaces;
45627
+ function totalist(dir, callback, pre='') {
45628
+ dir = resolve$3('.', dir);
45629
+ let arr = readdirSync(dir);
45630
+ let i=0, abs, stats;
45631
+ for (; i < arr.length; i++) {
45632
+ abs = join$1(dir, arr[i]);
45633
+ stats = statSync$1(abs);
45634
+ stats.isDirectory()
45635
+ ? totalist(abs, callback, join$1(pre, arr[i]))
45636
+ : callback(join$1(pre, arr[i]), abs, stats);
45637
+ }
45612
45638
  }
45613
- function hasRootFile(root) {
45614
- return ROOT_FILES.some((file) => fs$l.existsSync(join$2(root, file)));
45639
+
45640
+ /**
45641
+ * @typedef ParsedURL
45642
+ * @type {import('.').ParsedURL}
45643
+ */
45644
+
45645
+ /**
45646
+ * @typedef Request
45647
+ * @property {string} url
45648
+ * @property {ParsedURL} _parsedUrl
45649
+ */
45650
+
45651
+ /**
45652
+ * @param {Request} req
45653
+ * @returns {ParsedURL|void}
45654
+ */
45655
+ function parse$8(req) {
45656
+ let raw = req.url;
45657
+ if (raw == null) return;
45658
+
45659
+ let prev = req._parsedUrl;
45660
+ if (prev && prev.raw === raw) return prev;
45661
+
45662
+ let pathname=raw, search='', query;
45663
+
45664
+ if (raw.length > 1) {
45665
+ let idx = raw.indexOf('?', 1);
45666
+
45667
+ if (idx !== -1) {
45668
+ search = raw.substring(idx);
45669
+ pathname = raw.substring(0, idx);
45670
+ if (search.length > 1) {
45671
+ query = qs.parse(search.substring(1));
45672
+ }
45673
+ }
45674
+ }
45675
+
45676
+ return req._parsedUrl = { pathname, search, query, raw };
45615
45677
  }
45616
- function hasPackageJSON(root) {
45617
- const path = join$2(root, 'package.json');
45618
- return fs$l.existsSync(path);
45678
+
45679
+ const noop$2 = () => {};
45680
+
45681
+ function isMatch(uri, arr) {
45682
+ for (let i=0; i < arr.length; i++) {
45683
+ if (arr[i].test(uri)) return true;
45684
+ }
45685
+ }
45686
+
45687
+ function toAssume(uri, extns) {
45688
+ let i=0, x, len=uri.length - 1;
45689
+ if (uri.charCodeAt(len) === 47) {
45690
+ uri = uri.substring(0, len);
45691
+ }
45692
+
45693
+ let arr=[], tmp=`${uri}/index`;
45694
+ for (; i < extns.length; i++) {
45695
+ x = extns[i] ? `.${extns[i]}` : '';
45696
+ if (uri) arr.push(uri + x);
45697
+ arr.push(tmp + x);
45698
+ }
45699
+
45700
+ return arr;
45701
+ }
45702
+
45703
+ function viaCache(cache, uri, extns) {
45704
+ let i=0, data, arr=toAssume(uri, extns);
45705
+ for (; i < arr.length; i++) {
45706
+ if (data = cache[arr[i]]) return data;
45707
+ }
45708
+ }
45709
+
45710
+ function viaLocal(dir, isEtag, uri, extns, shouldServe) {
45711
+ let i=0, arr=toAssume(uri, extns);
45712
+ let abs, stats, name, headers;
45713
+ for (; i < arr.length; i++) {
45714
+ abs = normalize(join$1(dir, name=arr[i]));
45715
+ if (abs.startsWith(dir) && require$$0$2.existsSync(abs)) {
45716
+ stats = require$$0$2.statSync(abs);
45717
+ if (stats.isDirectory()) continue;
45718
+ if (shouldServe && !shouldServe(abs)) continue;
45719
+ headers = toHeaders(name, stats, isEtag);
45720
+ headers['Cache-Control'] = isEtag ? 'no-cache' : 'no-store';
45721
+ return { abs, stats, headers };
45722
+ }
45723
+ }
45724
+ }
45725
+
45726
+ function is404(req, res) {
45727
+ return (res.statusCode=404,res.end());
45728
+ }
45729
+
45730
+ function send$1(req, res, file, stats, headers) {
45731
+ let code=200, tmp, opts={};
45732
+ headers = { ...headers };
45733
+
45734
+ for (let key in headers) {
45735
+ tmp = res.getHeader(key);
45736
+ if (tmp) headers[key] = tmp;
45737
+ }
45738
+
45739
+ if (tmp = res.getHeader('content-type')) {
45740
+ headers['Content-Type'] = tmp;
45741
+ }
45742
+
45743
+ if (req.headers.range) {
45744
+ code = 206;
45745
+ let [x, y] = req.headers.range.replace('bytes=', '').split('-');
45746
+ let end = opts.end = parseInt(y, 10) || stats.size - 1;
45747
+ let start = opts.start = parseInt(x, 10) || 0;
45748
+
45749
+ if (start >= stats.size || end >= stats.size) {
45750
+ res.setHeader('Content-Range', `bytes */${stats.size}`);
45751
+ res.statusCode = 416;
45752
+ return res.end();
45753
+ }
45754
+
45755
+ headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}`;
45756
+ headers['Content-Length'] = (end - start + 1);
45757
+ headers['Accept-Ranges'] = 'bytes';
45758
+ }
45759
+
45760
+ res.writeHead(code, headers);
45761
+ require$$0$2.createReadStream(file, opts).pipe(res);
45762
+ }
45763
+
45764
+ const ENCODING = {
45765
+ '.br': 'br',
45766
+ '.gz': 'gzip',
45767
+ };
45768
+
45769
+ function toHeaders(name, stats, isEtag) {
45770
+ let enc = ENCODING[name.slice(-3)];
45771
+
45772
+ let ctype = lookup(name.slice(0, enc && -3)) || '';
45773
+ if (ctype === 'text/html') ctype += ';charset=utf-8';
45774
+
45775
+ let headers = {
45776
+ 'Content-Length': stats.size,
45777
+ 'Content-Type': ctype,
45778
+ 'Last-Modified': stats.mtime.toUTCString(),
45779
+ };
45780
+
45781
+ if (enc) headers['Content-Encoding'] = enc;
45782
+ if (isEtag) headers['ETag'] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
45783
+
45784
+ return headers;
45785
+ }
45786
+
45787
+ function sirv (dir, opts={}) {
45788
+ dir = resolve$3(dir || '.');
45789
+
45790
+ let isNotFound = opts.onNoMatch || is404;
45791
+ let setHeaders = opts.setHeaders || noop$2;
45792
+
45793
+ let extensions = opts.extensions || ['html', 'htm'];
45794
+ let gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz');
45795
+ let brots = opts.brotli && extensions.map(x => `${x}.br`).concat('br');
45796
+
45797
+ const FILES = {};
45798
+
45799
+ let fallback = '/';
45800
+ let isEtag = !!opts.etag;
45801
+ let isSPA = !!opts.single;
45802
+ if (typeof opts.single === 'string') {
45803
+ let idx = opts.single.lastIndexOf('.');
45804
+ fallback += !!~idx ? opts.single.substring(0, idx) : opts.single;
45805
+ }
45806
+
45807
+ let ignores = [];
45808
+ if (opts.ignores !== false) {
45809
+ ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/); // any extn
45810
+ if (opts.dotfiles) ignores.push(/\/\.\w/);
45811
+ else ignores.push(/\/\.well-known/);
45812
+ [].concat(opts.ignores || []).forEach(x => {
45813
+ ignores.push(new RegExp(x, 'i'));
45814
+ });
45815
+ }
45816
+
45817
+ let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
45818
+ if (cc && opts.immutable) cc += ',immutable';
45819
+ else if (cc && opts.maxAge === 0) cc += ',must-revalidate';
45820
+
45821
+ if (!opts.dev) {
45822
+ totalist(dir, (name, abs, stats) => {
45823
+ if (/\.well-known[\\+\/]/.test(name)) ; // keep
45824
+ else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
45825
+
45826
+ let headers = toHeaders(name, stats, isEtag);
45827
+ if (cc) headers['Cache-Control'] = cc;
45828
+
45829
+ FILES['/' + name.normalize().replace(/\\+/g, '/')] = { abs, stats, headers };
45830
+ });
45831
+ }
45832
+
45833
+ let lookup = opts.dev ? viaLocal.bind(0, dir, isEtag) : viaCache.bind(0, FILES);
45834
+
45835
+ return function (req, res, next) {
45836
+ let extns = [''];
45837
+ let pathname = parse$8(req).pathname;
45838
+ let val = req.headers['accept-encoding'] || '';
45839
+ if (gzips && val.includes('gzip')) extns.unshift(...gzips);
45840
+ if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
45841
+ extns.push(...extensions); // [...br, ...gz, orig, ...exts]
45842
+
45843
+ if (pathname.indexOf('%') !== -1) {
45844
+ try { pathname = decodeURIComponent(pathname); }
45845
+ catch (err) { /* malform uri */ }
45846
+ }
45847
+
45848
+ let data = lookup(pathname, extns, opts.shouldServe) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns, opts.shouldServe);
45849
+ if (!data) return next ? next() : isNotFound(req, res);
45850
+
45851
+ if (isEtag && req.headers['if-none-match'] === data.headers['ETag']) {
45852
+ res.writeHead(304);
45853
+ return res.end();
45854
+ }
45855
+
45856
+ if (gzips || brots) {
45857
+ res.setHeader('Vary', 'Accept-Encoding');
45858
+ }
45859
+
45860
+ setHeaders(res, pathname, data.stats);
45861
+ send$1(req, res, data.abs, data.stats, data.headers);
45862
+ };
45619
45863
  }
45864
+
45865
+ /*!
45866
+ * escape-html
45867
+ * Copyright(c) 2012-2013 TJ Holowaychuk
45868
+ * Copyright(c) 2015 Andreas Lubbe
45869
+ * Copyright(c) 2015 Tiancheng "Timothy" Gu
45870
+ * MIT Licensed
45871
+ */
45872
+
45620
45873
  /**
45621
- * Search up for the nearest `package.json`
45874
+ * Module variables.
45875
+ * @private
45622
45876
  */
45623
- function searchForPackageRoot(current, root = current) {
45624
- if (hasPackageJSON(current))
45625
- return current;
45626
- const dir = dirname$2(current);
45627
- // reach the fs root
45628
- if (!dir || dir === current)
45629
- return root;
45630
- return searchForPackageRoot(dir, root);
45877
+
45878
+ var matchHtmlRegExp = /["'&<>]/;
45879
+
45880
+ /**
45881
+ * Module exports.
45882
+ * @public
45883
+ */
45884
+
45885
+ var escapeHtml_1 = escapeHtml$1;
45886
+
45887
+ /**
45888
+ * Escape special characters in the given string of html.
45889
+ *
45890
+ * @param {string} string The string to escape for inserting into HTML
45891
+ * @return {string}
45892
+ * @public
45893
+ */
45894
+
45895
+ function escapeHtml$1(string) {
45896
+ var str = '' + string;
45897
+ var match = matchHtmlRegExp.exec(str);
45898
+
45899
+ if (!match) {
45900
+ return str;
45901
+ }
45902
+
45903
+ var escape;
45904
+ var html = '';
45905
+ var index = 0;
45906
+ var lastIndex = 0;
45907
+
45908
+ for (index = match.index; index < str.length; index++) {
45909
+ switch (str.charCodeAt(index)) {
45910
+ case 34: // "
45911
+ escape = '&quot;';
45912
+ break;
45913
+ case 38: // &
45914
+ escape = '&amp;';
45915
+ break;
45916
+ case 39: // '
45917
+ escape = '&#39;';
45918
+ break;
45919
+ case 60: // <
45920
+ escape = '&lt;';
45921
+ break;
45922
+ case 62: // >
45923
+ escape = '&gt;';
45924
+ break;
45925
+ default:
45926
+ continue;
45927
+ }
45928
+
45929
+ if (lastIndex !== index) {
45930
+ html += str.substring(lastIndex, index);
45931
+ }
45932
+
45933
+ lastIndex = index + 1;
45934
+ html += escape;
45935
+ }
45936
+
45937
+ return lastIndex !== index
45938
+ ? html + str.substring(lastIndex, index)
45939
+ : html;
45940
+ }
45941
+
45942
+ const knownJavascriptExtensionRE = /\.[tj]sx?$/;
45943
+ const sirvOptions = ({ headers, shouldServe, }) => {
45944
+ return {
45945
+ dev: true,
45946
+ etag: true,
45947
+ extensions: [],
45948
+ setHeaders(res, pathname) {
45949
+ // Matches js, jsx, ts, tsx.
45950
+ // The reason this is done, is that the .ts file extension is reserved
45951
+ // for the MIME type video/mp2t. In almost all cases, we can expect
45952
+ // these files to be TypeScript files, and for Vite to serve them with
45953
+ // this Content-Type.
45954
+ if (knownJavascriptExtensionRE.test(pathname)) {
45955
+ res.setHeader('Content-Type', 'application/javascript');
45956
+ }
45957
+ if (headers) {
45958
+ for (const name in headers) {
45959
+ res.setHeader(name, headers[name]);
45960
+ }
45961
+ }
45962
+ },
45963
+ shouldServe,
45964
+ };
45965
+ };
45966
+ function servePublicMiddleware(dir, headers) {
45967
+ const serve = sirv(dir, sirvOptions({
45968
+ headers,
45969
+ shouldServe: (filePath) => shouldServeFile(filePath, dir),
45970
+ }));
45971
+ // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
45972
+ return function viteServePublicMiddleware(req, res, next) {
45973
+ // skip import request and internal requests `/@fs/ /@vite-client` etc...
45974
+ if (isImportRequest(req.url) || isInternalRequest(req.url)) {
45975
+ return next();
45976
+ }
45977
+ serve(req, res, next);
45978
+ };
45979
+ }
45980
+ function serveStaticMiddleware(dir, server) {
45981
+ const serve = sirv(dir, sirvOptions({
45982
+ headers: server.config.server.headers,
45983
+ }));
45984
+ // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
45985
+ return function viteServeStaticMiddleware(req, res, next) {
45986
+ // only serve the file if it's not an html request or ends with `/`
45987
+ // so that html requests can fallthrough to our html middleware for
45988
+ // special processing
45989
+ // also skip internal requests `/@fs/ /@vite-client` etc...
45990
+ const cleanedUrl = cleanUrl(req.url);
45991
+ if (cleanedUrl[cleanedUrl.length - 1] === '/' ||
45992
+ path$o.extname(cleanedUrl) === '.html' ||
45993
+ isInternalRequest(req.url)) {
45994
+ return next();
45995
+ }
45996
+ const url = new URL(req.url, 'http://example.com');
45997
+ const pathname = decodeURIComponent(url.pathname);
45998
+ // apply aliases to static requests as well
45999
+ let redirectedPathname;
46000
+ for (const { find, replacement } of server.config.resolve.alias) {
46001
+ const matches = typeof find === 'string'
46002
+ ? pathname.startsWith(find)
46003
+ : find.test(pathname);
46004
+ if (matches) {
46005
+ redirectedPathname = pathname.replace(find, replacement);
46006
+ break;
46007
+ }
46008
+ }
46009
+ if (redirectedPathname) {
46010
+ // dir is pre-normalized to posix style
46011
+ if (redirectedPathname.startsWith(dir)) {
46012
+ redirectedPathname = redirectedPathname.slice(dir.length);
46013
+ }
46014
+ }
46015
+ const resolvedPathname = redirectedPathname || pathname;
46016
+ let fileUrl = path$o.resolve(dir, removeLeadingSlash(resolvedPathname));
46017
+ if (resolvedPathname[resolvedPathname.length - 1] === '/' &&
46018
+ fileUrl[fileUrl.length - 1] !== '/') {
46019
+ fileUrl = fileUrl + '/';
46020
+ }
46021
+ if (!ensureServingAccess(fileUrl, server, res, next)) {
46022
+ return;
46023
+ }
46024
+ if (redirectedPathname) {
46025
+ url.pathname = encodeURIComponent(redirectedPathname);
46026
+ req.url = url.href.slice(url.origin.length);
46027
+ }
46028
+ serve(req, res, next);
46029
+ };
46030
+ }
46031
+ function serveRawFsMiddleware(server) {
46032
+ const serveFromRoot = sirv('/', sirvOptions({ headers: server.config.server.headers }));
46033
+ // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
46034
+ return function viteServeRawFsMiddleware(req, res, next) {
46035
+ const url = new URL(req.url, 'http://example.com');
46036
+ // In some cases (e.g. linked monorepos) files outside of root will
46037
+ // reference assets that are also out of served root. In such cases
46038
+ // the paths are rewritten to `/@fs/` prefixed paths and must be served by
46039
+ // searching based from fs root.
46040
+ if (url.pathname.startsWith(FS_PREFIX)) {
46041
+ const pathname = decodeURIComponent(url.pathname);
46042
+ // restrict files outside of `fs.allow`
46043
+ if (!ensureServingAccess(slash$1(path$o.resolve(fsPathFromId(pathname))), server, res, next)) {
46044
+ return;
46045
+ }
46046
+ let newPathname = pathname.slice(FS_PREFIX.length);
46047
+ if (isWindows$4)
46048
+ newPathname = newPathname.replace(/^[A-Z]:/i, '');
46049
+ url.pathname = encodeURIComponent(newPathname);
46050
+ req.url = url.href.slice(url.origin.length);
46051
+ serveFromRoot(req, res, next);
46052
+ }
46053
+ else {
46054
+ next();
46055
+ }
46056
+ };
45631
46057
  }
45632
46058
  /**
45633
- * Search up for the nearest workspace root
46059
+ * Check if the url is allowed to be served, via the `server.fs` config.
45634
46060
  */
45635
- function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) {
45636
- if (hasRootFile(current))
45637
- return current;
45638
- if (hasWorkspacePackageJSON(current))
45639
- return current;
45640
- const dir = dirname$2(current);
45641
- // reach the fs root
45642
- if (!dir || dir === current)
45643
- return root;
45644
- return searchForWorkspaceRoot(dir, root);
46061
+ function isFileServingAllowed(url, server) {
46062
+ if (!server.config.server.fs.strict)
46063
+ return true;
46064
+ const file = fsPathFromUrl(url);
46065
+ if (server._fsDenyGlob(file))
46066
+ return false;
46067
+ if (server.moduleGraph.safeModulesPath.has(file))
46068
+ return true;
46069
+ if (server.config.server.fs.allow.some((dir) => isParentDirectory(dir, file)))
46070
+ return true;
46071
+ return false;
46072
+ }
46073
+ function ensureServingAccess(url, server, res, next) {
46074
+ if (isFileServingAllowed(url, server)) {
46075
+ return true;
46076
+ }
46077
+ if (isFileReadable(cleanUrl(url))) {
46078
+ const urlMessage = `The request url "${url}" is outside of Vite serving allow list.`;
46079
+ const hintMessage = `
46080
+ ${server.config.server.fs.allow.map((i) => `- ${i}`).join('\n')}
46081
+
46082
+ Refer to docs https://vitejs.dev/config/server-options.html#server-fs-allow for configurations and more details.`;
46083
+ server.config.logger.error(urlMessage);
46084
+ server.config.logger.warnOnce(hintMessage + '\n');
46085
+ res.statusCode = 403;
46086
+ res.write(renderRestrictedErrorHTML(urlMessage + '\n' + hintMessage));
46087
+ res.end();
46088
+ }
46089
+ else {
46090
+ // if the file doesn't exist, we shouldn't restrict this path as it can
46091
+ // be an API call. Middlewares would issue a 404 if the file isn't handled
46092
+ next();
46093
+ }
46094
+ return false;
46095
+ }
46096
+ function renderRestrictedErrorHTML(msg) {
46097
+ // to have syntax highlighting and autocompletion in IDE
46098
+ const html = String.raw;
46099
+ return html `
46100
+ <body>
46101
+ <h1>403 Restricted</h1>
46102
+ <p>${escapeHtml_1(msg).replace(/\n/g, '<br/>')}</p>
46103
+ <style>
46104
+ body {
46105
+ padding: 1em 2em;
46106
+ }
46107
+ </style>
46108
+ </body>
46109
+ `;
45645
46110
  }
45646
46111
 
45647
46112
  function resolveBuildOptions(raw, logger, root) {
@@ -46307,6 +46772,7 @@ var build$1 = {
46307
46772
  resolveBuildOutputs: resolveBuildOutputs,
46308
46773
  resolveBuildPlugins: resolveBuildPlugins,
46309
46774
  resolveLibFilename: resolveLibFilename,
46775
+ resolveUserExternal: resolveUserExternal,
46310
46776
  toOutputFilePathInCss: toOutputFilePathInCss,
46311
46777
  toOutputFilePathInHtml: toOutputFilePathInHtml,
46312
46778
  toOutputFilePathInJS: toOutputFilePathInJS,
@@ -47234,83 +47700,6 @@ function encodeUrl$1 (url) {
47234
47700
  .replace(ENCODE_CHARS_REGEXP, encodeURI)
47235
47701
  }
47236
47702
 
47237
- /*!
47238
- * escape-html
47239
- * Copyright(c) 2012-2013 TJ Holowaychuk
47240
- * Copyright(c) 2015 Andreas Lubbe
47241
- * Copyright(c) 2015 Tiancheng "Timothy" Gu
47242
- * MIT Licensed
47243
- */
47244
-
47245
- /**
47246
- * Module variables.
47247
- * @private
47248
- */
47249
-
47250
- var matchHtmlRegExp = /["'&<>]/;
47251
-
47252
- /**
47253
- * Module exports.
47254
- * @public
47255
- */
47256
-
47257
- var escapeHtml_1 = escapeHtml$1;
47258
-
47259
- /**
47260
- * Escape special characters in the given string of html.
47261
- *
47262
- * @param {string} string The string to escape for inserting into HTML
47263
- * @return {string}
47264
- * @public
47265
- */
47266
-
47267
- function escapeHtml$1(string) {
47268
- var str = '' + string;
47269
- var match = matchHtmlRegExp.exec(str);
47270
-
47271
- if (!match) {
47272
- return str;
47273
- }
47274
-
47275
- var escape;
47276
- var html = '';
47277
- var index = 0;
47278
- var lastIndex = 0;
47279
-
47280
- for (index = match.index; index < str.length; index++) {
47281
- switch (str.charCodeAt(index)) {
47282
- case 34: // "
47283
- escape = '&quot;';
47284
- break;
47285
- case 38: // &
47286
- escape = '&amp;';
47287
- break;
47288
- case 39: // '
47289
- escape = '&#39;';
47290
- break;
47291
- case 60: // <
47292
- escape = '&lt;';
47293
- break;
47294
- case 62: // >
47295
- escape = '&gt;';
47296
- break;
47297
- default:
47298
- continue;
47299
- }
47300
-
47301
- if (lastIndex !== index) {
47302
- html += str.substring(lastIndex, index);
47303
- }
47304
-
47305
- lastIndex = index + 1;
47306
- html += escape;
47307
- }
47308
-
47309
- return lastIndex !== index
47310
- ? html + str.substring(lastIndex, index)
47311
- : html;
47312
- }
47313
-
47314
47703
  var onFinishedExports = {};
47315
47704
  var onFinished$2 = {
47316
47705
  get exports(){ return onFinishedExports; },
@@ -47625,7 +48014,7 @@ var parseurl$1 = {
47625
48014
  */
47626
48015
 
47627
48016
  var url$3 = require$$0$9;
47628
- var parse$8 = url$3.parse;
48017
+ var parse$7 = url$3.parse;
47629
48018
  var Url = url$3.Url;
47630
48019
 
47631
48020
  /**
@@ -47704,7 +48093,7 @@ function originalurl (req) {
47704
48093
 
47705
48094
  function fastparse (str) {
47706
48095
  if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) {
47707
- return parse$8(str)
48096
+ return parse$7(str)
47708
48097
  }
47709
48098
 
47710
48099
  var pathname = str;
@@ -47731,7 +48120,7 @@ function fastparse (str) {
47731
48120
  case 0x23: /* # */
47732
48121
  case 0xa0:
47733
48122
  case 0xfeff:
47734
- return parse$8(str)
48123
+ return parse$7(str)
47735
48124
  }
47736
48125
  }
47737
48126
 
@@ -48144,7 +48533,7 @@ function finalhandler$1 (req, res, options) {
48144
48533
  }
48145
48534
 
48146
48535
  // send response
48147
- send$1(req, res, status, headers, msg);
48536
+ send(req, res, status, headers, msg);
48148
48537
  }
48149
48538
  }
48150
48539
 
@@ -48283,7 +48672,7 @@ function headersSent (res) {
48283
48672
  * @private
48284
48673
  */
48285
48674
 
48286
- function send$1 (req, res, status, headers, message) {
48675
+ function send (req, res, status, headers, message) {
48287
48676
  function write () {
48288
48677
  // response body
48289
48678
  var body = createHtmlDocument(message);
@@ -48801,7 +49190,7 @@ function append (header, field) {
48801
49190
 
48802
49191
  // get fields array
48803
49192
  var fields = !Array.isArray(field)
48804
- ? parse$7(String(field))
49193
+ ? parse$6(String(field))
48805
49194
  : field;
48806
49195
 
48807
49196
  // assert on invalid field names
@@ -48818,7 +49207,7 @@ function append (header, field) {
48818
49207
 
48819
49208
  // enumerate current values
48820
49209
  var val = header;
48821
- var vals = parse$7(header.toLowerCase());
49210
+ var vals = parse$6(header.toLowerCase());
48822
49211
 
48823
49212
  // unspecified vary
48824
49213
  if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) {
@@ -48848,7 +49237,7 @@ function append (header, field) {
48848
49237
  * @private
48849
49238
  */
48850
49239
 
48851
- function parse$7 (header) {
49240
+ function parse$6 (header) {
48852
49241
  var end = 0;
48853
49242
  var list = [];
48854
49243
  var start = 0;
@@ -52100,7 +52489,7 @@ for (var i = 0; i < 4; i++) {
52100
52489
  }
52101
52490
 
52102
52491
  shellQuote$1.parse = function (s, env, opts) {
52103
- var mapped = parse$6(s, env, opts);
52492
+ var mapped = parse$5(s, env, opts);
52104
52493
  if (typeof env !== 'function') return mapped;
52105
52494
  return mapped.reduce(function (acc, s) {
52106
52495
  if (typeof s === 'object') return acc.concat(s);
@@ -52115,7 +52504,7 @@ shellQuote$1.parse = function (s, env, opts) {
52115
52504
  }, []);
52116
52505
  };
52117
52506
 
52118
- function parse$6 (s, env, opts) {
52507
+ function parse$5 (s, env, opts) {
52119
52508
  var chunker = new RegExp([
52120
52509
  '(' + CONTROL + ')', // control chars
52121
52510
  '(' + BAREWORD + '|' + SINGLE_QUOTE + '|' + DOUBLE_QUOTE + ')*'
@@ -52783,411 +53172,6 @@ function setClientErrorHandler(server, logger) {
52783
53172
  });
52784
53173
  }
52785
53174
 
52786
- function totalist(dir, callback, pre='') {
52787
- dir = resolve$3('.', dir);
52788
- let arr = readdirSync(dir);
52789
- let i=0, abs, stats;
52790
- for (; i < arr.length; i++) {
52791
- abs = join$1(dir, arr[i]);
52792
- stats = statSync$1(abs);
52793
- stats.isDirectory()
52794
- ? totalist(abs, callback, join$1(pre, arr[i]))
52795
- : callback(join$1(pre, arr[i]), abs, stats);
52796
- }
52797
- }
52798
-
52799
- /**
52800
- * @typedef ParsedURL
52801
- * @type {import('.').ParsedURL}
52802
- */
52803
-
52804
- /**
52805
- * @typedef Request
52806
- * @property {string} url
52807
- * @property {ParsedURL} _parsedUrl
52808
- */
52809
-
52810
- /**
52811
- * @param {Request} req
52812
- * @returns {ParsedURL|void}
52813
- */
52814
- function parse$5(req) {
52815
- let raw = req.url;
52816
- if (raw == null) return;
52817
-
52818
- let prev = req._parsedUrl;
52819
- if (prev && prev.raw === raw) return prev;
52820
-
52821
- let pathname=raw, search='', query;
52822
-
52823
- if (raw.length > 1) {
52824
- let idx = raw.indexOf('?', 1);
52825
-
52826
- if (idx !== -1) {
52827
- search = raw.substring(idx);
52828
- pathname = raw.substring(0, idx);
52829
- if (search.length > 1) {
52830
- query = qs.parse(search.substring(1));
52831
- }
52832
- }
52833
- }
52834
-
52835
- return req._parsedUrl = { pathname, search, query, raw };
52836
- }
52837
-
52838
- const noop$2 = () => {};
52839
-
52840
- function isMatch(uri, arr) {
52841
- for (let i=0; i < arr.length; i++) {
52842
- if (arr[i].test(uri)) return true;
52843
- }
52844
- }
52845
-
52846
- function toAssume(uri, extns) {
52847
- let i=0, x, len=uri.length - 1;
52848
- if (uri.charCodeAt(len) === 47) {
52849
- uri = uri.substring(0, len);
52850
- }
52851
-
52852
- let arr=[], tmp=`${uri}/index`;
52853
- for (; i < extns.length; i++) {
52854
- x = extns[i] ? `.${extns[i]}` : '';
52855
- if (uri) arr.push(uri + x);
52856
- arr.push(tmp + x);
52857
- }
52858
-
52859
- return arr;
52860
- }
52861
-
52862
- function viaCache(cache, uri, extns) {
52863
- let i=0, data, arr=toAssume(uri, extns);
52864
- for (; i < arr.length; i++) {
52865
- if (data = cache[arr[i]]) return data;
52866
- }
52867
- }
52868
-
52869
- function viaLocal(dir, isEtag, uri, extns, shouldServe) {
52870
- let i=0, arr=toAssume(uri, extns);
52871
- let abs, stats, name, headers;
52872
- for (; i < arr.length; i++) {
52873
- abs = normalize(join$1(dir, name=arr[i]));
52874
- if (abs.startsWith(dir) && require$$0$2.existsSync(abs)) {
52875
- stats = require$$0$2.statSync(abs);
52876
- if (stats.isDirectory()) continue;
52877
- if (shouldServe && !shouldServe(abs)) continue;
52878
- headers = toHeaders(name, stats, isEtag);
52879
- headers['Cache-Control'] = isEtag ? 'no-cache' : 'no-store';
52880
- return { abs, stats, headers };
52881
- }
52882
- }
52883
- }
52884
-
52885
- function is404(req, res) {
52886
- return (res.statusCode=404,res.end());
52887
- }
52888
-
52889
- function send(req, res, file, stats, headers) {
52890
- let code=200, tmp, opts={};
52891
- headers = { ...headers };
52892
-
52893
- for (let key in headers) {
52894
- tmp = res.getHeader(key);
52895
- if (tmp) headers[key] = tmp;
52896
- }
52897
-
52898
- if (tmp = res.getHeader('content-type')) {
52899
- headers['Content-Type'] = tmp;
52900
- }
52901
-
52902
- if (req.headers.range) {
52903
- code = 206;
52904
- let [x, y] = req.headers.range.replace('bytes=', '').split('-');
52905
- let end = opts.end = parseInt(y, 10) || stats.size - 1;
52906
- let start = opts.start = parseInt(x, 10) || 0;
52907
-
52908
- if (start >= stats.size || end >= stats.size) {
52909
- res.setHeader('Content-Range', `bytes */${stats.size}`);
52910
- res.statusCode = 416;
52911
- return res.end();
52912
- }
52913
-
52914
- headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}`;
52915
- headers['Content-Length'] = (end - start + 1);
52916
- headers['Accept-Ranges'] = 'bytes';
52917
- }
52918
-
52919
- res.writeHead(code, headers);
52920
- require$$0$2.createReadStream(file, opts).pipe(res);
52921
- }
52922
-
52923
- const ENCODING = {
52924
- '.br': 'br',
52925
- '.gz': 'gzip',
52926
- };
52927
-
52928
- function toHeaders(name, stats, isEtag) {
52929
- let enc = ENCODING[name.slice(-3)];
52930
-
52931
- let ctype = lookup(name.slice(0, enc && -3)) || '';
52932
- if (ctype === 'text/html') ctype += ';charset=utf-8';
52933
-
52934
- let headers = {
52935
- 'Content-Length': stats.size,
52936
- 'Content-Type': ctype,
52937
- 'Last-Modified': stats.mtime.toUTCString(),
52938
- };
52939
-
52940
- if (enc) headers['Content-Encoding'] = enc;
52941
- if (isEtag) headers['ETag'] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
52942
-
52943
- return headers;
52944
- }
52945
-
52946
- function sirv (dir, opts={}) {
52947
- dir = resolve$3(dir || '.');
52948
-
52949
- let isNotFound = opts.onNoMatch || is404;
52950
- let setHeaders = opts.setHeaders || noop$2;
52951
-
52952
- let extensions = opts.extensions || ['html', 'htm'];
52953
- let gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz');
52954
- let brots = opts.brotli && extensions.map(x => `${x}.br`).concat('br');
52955
-
52956
- const FILES = {};
52957
-
52958
- let fallback = '/';
52959
- let isEtag = !!opts.etag;
52960
- let isSPA = !!opts.single;
52961
- if (typeof opts.single === 'string') {
52962
- let idx = opts.single.lastIndexOf('.');
52963
- fallback += !!~idx ? opts.single.substring(0, idx) : opts.single;
52964
- }
52965
-
52966
- let ignores = [];
52967
- if (opts.ignores !== false) {
52968
- ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/); // any extn
52969
- if (opts.dotfiles) ignores.push(/\/\.\w/);
52970
- else ignores.push(/\/\.well-known/);
52971
- [].concat(opts.ignores || []).forEach(x => {
52972
- ignores.push(new RegExp(x, 'i'));
52973
- });
52974
- }
52975
-
52976
- let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
52977
- if (cc && opts.immutable) cc += ',immutable';
52978
- else if (cc && opts.maxAge === 0) cc += ',must-revalidate';
52979
-
52980
- if (!opts.dev) {
52981
- totalist(dir, (name, abs, stats) => {
52982
- if (/\.well-known[\\+\/]/.test(name)) ; // keep
52983
- else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
52984
-
52985
- let headers = toHeaders(name, stats, isEtag);
52986
- if (cc) headers['Cache-Control'] = cc;
52987
-
52988
- FILES['/' + name.normalize().replace(/\\+/g, '/')] = { abs, stats, headers };
52989
- });
52990
- }
52991
-
52992
- let lookup = opts.dev ? viaLocal.bind(0, dir, isEtag) : viaCache.bind(0, FILES);
52993
-
52994
- return function (req, res, next) {
52995
- let extns = [''];
52996
- let pathname = parse$5(req).pathname;
52997
- let val = req.headers['accept-encoding'] || '';
52998
- if (gzips && val.includes('gzip')) extns.unshift(...gzips);
52999
- if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
53000
- extns.push(...extensions); // [...br, ...gz, orig, ...exts]
53001
-
53002
- if (pathname.indexOf('%') !== -1) {
53003
- try { pathname = decodeURIComponent(pathname); }
53004
- catch (err) { /* malform uri */ }
53005
- }
53006
-
53007
- let data = lookup(pathname, extns, opts.shouldServe) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns, opts.shouldServe);
53008
- if (!data) return next ? next() : isNotFound(req, res);
53009
-
53010
- if (isEtag && req.headers['if-none-match'] === data.headers['ETag']) {
53011
- res.writeHead(304);
53012
- return res.end();
53013
- }
53014
-
53015
- if (gzips || brots) {
53016
- res.setHeader('Vary', 'Accept-Encoding');
53017
- }
53018
-
53019
- setHeaders(res, pathname, data.stats);
53020
- send(req, res, data.abs, data.stats, data.headers);
53021
- };
53022
- }
53023
-
53024
- const knownJavascriptExtensionRE = /\.[tj]sx?$/;
53025
- const sirvOptions = ({ headers, shouldServe, }) => {
53026
- return {
53027
- dev: true,
53028
- etag: true,
53029
- extensions: [],
53030
- setHeaders(res, pathname) {
53031
- // Matches js, jsx, ts, tsx.
53032
- // The reason this is done, is that the .ts file extension is reserved
53033
- // for the MIME type video/mp2t. In almost all cases, we can expect
53034
- // these files to be TypeScript files, and for Vite to serve them with
53035
- // this Content-Type.
53036
- if (knownJavascriptExtensionRE.test(pathname)) {
53037
- res.setHeader('Content-Type', 'application/javascript');
53038
- }
53039
- if (headers) {
53040
- for (const name in headers) {
53041
- res.setHeader(name, headers[name]);
53042
- }
53043
- }
53044
- },
53045
- shouldServe,
53046
- };
53047
- };
53048
- function servePublicMiddleware(dir, headers) {
53049
- const serve = sirv(dir, sirvOptions({
53050
- headers,
53051
- shouldServe: (filePath) => shouldServeFile(filePath, dir),
53052
- }));
53053
- // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
53054
- return function viteServePublicMiddleware(req, res, next) {
53055
- // skip import request and internal requests `/@fs/ /@vite-client` etc...
53056
- if (isImportRequest(req.url) || isInternalRequest(req.url)) {
53057
- return next();
53058
- }
53059
- serve(req, res, next);
53060
- };
53061
- }
53062
- function serveStaticMiddleware(dir, server) {
53063
- const serve = sirv(dir, sirvOptions({
53064
- headers: server.config.server.headers,
53065
- }));
53066
- // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
53067
- return function viteServeStaticMiddleware(req, res, next) {
53068
- // only serve the file if it's not an html request or ends with `/`
53069
- // so that html requests can fallthrough to our html middleware for
53070
- // special processing
53071
- // also skip internal requests `/@fs/ /@vite-client` etc...
53072
- const cleanedUrl = cleanUrl(req.url);
53073
- if (cleanedUrl[cleanedUrl.length - 1] === '/' ||
53074
- path$o.extname(cleanedUrl) === '.html' ||
53075
- isInternalRequest(req.url)) {
53076
- return next();
53077
- }
53078
- const url = new URL(req.url, 'http://example.com');
53079
- const pathname = decodeURIComponent(url.pathname);
53080
- // apply aliases to static requests as well
53081
- let redirectedPathname;
53082
- for (const { find, replacement } of server.config.resolve.alias) {
53083
- const matches = typeof find === 'string'
53084
- ? pathname.startsWith(find)
53085
- : find.test(pathname);
53086
- if (matches) {
53087
- redirectedPathname = pathname.replace(find, replacement);
53088
- break;
53089
- }
53090
- }
53091
- if (redirectedPathname) {
53092
- // dir is pre-normalized to posix style
53093
- if (redirectedPathname.startsWith(dir)) {
53094
- redirectedPathname = redirectedPathname.slice(dir.length);
53095
- }
53096
- }
53097
- const resolvedPathname = redirectedPathname || pathname;
53098
- let fileUrl = path$o.resolve(dir, removeLeadingSlash(resolvedPathname));
53099
- if (resolvedPathname[resolvedPathname.length - 1] === '/' &&
53100
- fileUrl[fileUrl.length - 1] !== '/') {
53101
- fileUrl = fileUrl + '/';
53102
- }
53103
- if (!ensureServingAccess(fileUrl, server, res, next)) {
53104
- return;
53105
- }
53106
- if (redirectedPathname) {
53107
- url.pathname = encodeURIComponent(redirectedPathname);
53108
- req.url = url.href.slice(url.origin.length);
53109
- }
53110
- serve(req, res, next);
53111
- };
53112
- }
53113
- function serveRawFsMiddleware(server) {
53114
- const serveFromRoot = sirv('/', sirvOptions({ headers: server.config.server.headers }));
53115
- // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
53116
- return function viteServeRawFsMiddleware(req, res, next) {
53117
- const url = new URL(req.url, 'http://example.com');
53118
- // In some cases (e.g. linked monorepos) files outside of root will
53119
- // reference assets that are also out of served root. In such cases
53120
- // the paths are rewritten to `/@fs/` prefixed paths and must be served by
53121
- // searching based from fs root.
53122
- if (url.pathname.startsWith(FS_PREFIX)) {
53123
- const pathname = decodeURIComponent(url.pathname);
53124
- // restrict files outside of `fs.allow`
53125
- if (!ensureServingAccess(slash$1(path$o.resolve(fsPathFromId(pathname))), server, res, next)) {
53126
- return;
53127
- }
53128
- let newPathname = pathname.slice(FS_PREFIX.length);
53129
- if (isWindows$4)
53130
- newPathname = newPathname.replace(/^[A-Z]:/i, '');
53131
- url.pathname = encodeURIComponent(newPathname);
53132
- req.url = url.href.slice(url.origin.length);
53133
- serveFromRoot(req, res, next);
53134
- }
53135
- else {
53136
- next();
53137
- }
53138
- };
53139
- }
53140
- function isFileServingAllowed(url, server) {
53141
- if (!server.config.server.fs.strict)
53142
- return true;
53143
- const file = fsPathFromUrl(url);
53144
- if (server._fsDenyGlob(file))
53145
- return false;
53146
- if (server.moduleGraph.safeModulesPath.has(file))
53147
- return true;
53148
- if (server.config.server.fs.allow.some((dir) => isParentDirectory(dir, file)))
53149
- return true;
53150
- return false;
53151
- }
53152
- function ensureServingAccess(url, server, res, next) {
53153
- if (isFileServingAllowed(url, server)) {
53154
- return true;
53155
- }
53156
- if (isFileReadable(cleanUrl(url))) {
53157
- const urlMessage = `The request url "${url}" is outside of Vite serving allow list.`;
53158
- const hintMessage = `
53159
- ${server.config.server.fs.allow.map((i) => `- ${i}`).join('\n')}
53160
-
53161
- Refer to docs https://vitejs.dev/config/server-options.html#server-fs-allow for configurations and more details.`;
53162
- server.config.logger.error(urlMessage);
53163
- server.config.logger.warnOnce(hintMessage + '\n');
53164
- res.statusCode = 403;
53165
- res.write(renderRestrictedErrorHTML(urlMessage + '\n' + hintMessage));
53166
- res.end();
53167
- }
53168
- else {
53169
- // if the file doesn't exist, we shouldn't restrict this path as it can
53170
- // be an API call. Middlewares would issue a 404 if the file isn't handled
53171
- next();
53172
- }
53173
- return false;
53174
- }
53175
- function renderRestrictedErrorHTML(msg) {
53176
- // to have syntax highlighting and autocompletion in IDE
53177
- const html = String.raw;
53178
- return html `
53179
- <body>
53180
- <h1>403 Restricted</h1>
53181
- <p>${msg.replace(/\n/g, '<br/>')}</p>
53182
- <style>
53183
- body {
53184
- padding: 1em 2em;
53185
- }
53186
- </style>
53187
- </body>
53188
- `;
53189
- }
53190
-
53191
53175
  const ERR_LOAD_URL = 'ERR_LOAD_URL';
53192
53176
  const ERR_LOAD_PUBLIC_URL = 'ERR_LOAD_PUBLIC_URL';
53193
53177
  const debugLoad = createDebugger('vite:load');
@@ -63671,8 +63655,7 @@ var index = {
63671
63655
  __proto__: null,
63672
63656
  _createServer: _createServer,
63673
63657
  createServer: createServer,
63674
- resolveServerOptions: resolveServerOptions,
63675
- searchForWorkspaceRoot: searchForWorkspaceRoot
63658
+ resolveServerOptions: resolveServerOptions
63676
63659
  };
63677
63660
 
63678
63661
  /* eslint-disable */
@@ -63689,7 +63672,7 @@ function compression() {
63689
63672
  // disable Brotli on Node<12.7 where it is unsupported:
63690
63673
  if (!zlib$1.createBrotliCompress)
63691
63674
  brotli = false;
63692
- return (req, res, next = noop) => {
63675
+ return function viteCompressionMiddleware(req, res, next = noop) {
63693
63676
  const accept = req.headers['accept-encoding'] + '';
63694
63677
  const encoding = ((brotli && accept.match(/\bbr\b/)) ||
63695
63678
  (accept.match(/\bgzip\b/)) ||
@@ -63846,7 +63829,7 @@ async function preview(inlineConfig = {}) {
63846
63829
  const previewBase = config.base === './' || config.base === '' ? '/' : config.base;
63847
63830
  // static assets
63848
63831
  const headers = config.preview.headers;
63849
- const assetServer = sirv(distDir, {
63832
+ const viteAssetMiddleware = (...args) => sirv(distDir, {
63850
63833
  etag: true,
63851
63834
  dev: true,
63852
63835
  single: config.appType === 'spa',
@@ -63860,8 +63843,8 @@ async function preview(inlineConfig = {}) {
63860
63843
  shouldServe(filePath) {
63861
63844
  return shouldServeFile(filePath, distDir);
63862
63845
  },
63863
- });
63864
- app.use(previewBase, assetServer);
63846
+ })(...args);
63847
+ app.use(previewBase, viteAssetMiddleware);
63865
63848
  // apply post server hooks from plugins
63866
63849
  postHooks.forEach((fn) => fn && fn());
63867
63850
  const hostname = await resolveHostname(options.host);
@@ -64508,4 +64491,4 @@ function isDepsOptimizerEnabled(config, ssr) {
64508
64491
  (command === 'serve' && disabled === 'dev'));
64509
64492
  }
64510
64493
 
64511
- export { resolveEnvPrefix as A, picocolorsExports as B, bindShortcuts as C, commonjsGlobal as D, index$1 as E, build$1 as F, index as G, preview$1 as H, preprocessCSS as a, build as b, createServer as c, resolvePackageData as d, buildErrorMessage as e, formatPostcssSourceMap as f, defineConfig as g, resolveConfig as h, isInNodeModules as i, resolveBaseUrl as j, getDepOptimizationConfig as k, loadConfigFromFile as l, isDepsOptimizerEnabled as m, normalizePath$3 as n, optimizeDeps as o, preview as p, mergeConfig as q, resolvePackageEntry as r, sortUserPlugins as s, transformWithEsbuild as t, mergeAlias as u, createFilter as v, send$2 as w, createLogger as x, searchForWorkspaceRoot as y, loadEnv as z };
64494
+ export { loadEnv as A, resolveEnvPrefix as B, picocolorsExports as C, bindShortcuts as D, commonjsGlobal as E, index$1 as F, build$1 as G, index as H, preview$1 as I, preprocessCSS as a, build as b, createServer as c, resolvePackageData as d, buildErrorMessage as e, formatPostcssSourceMap as f, defineConfig as g, resolveConfig as h, isInNodeModules as i, resolveBaseUrl as j, getDepOptimizationConfig as k, loadConfigFromFile as l, isDepsOptimizerEnabled as m, normalizePath$3 as n, optimizeDeps as o, preview as p, mergeConfig as q, resolvePackageEntry as r, sortUserPlugins as s, transformWithEsbuild as t, mergeAlias as u, createFilter as v, send$2 as w, createLogger as x, searchForWorkspaceRoot as y, isFileServingAllowed as z };