vite 4.3.0-beta.5 → 4.3.0-beta.7

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 require$$0__default from 'fs';
2
2
  import require$$0 from 'postcss';
3
- import { D as commonjsGlobal } from './dep-a26366f0.js';
3
+ import { D as commonjsGlobal } from './dep-f1f8facc.js';
4
4
  import require$$0$1 from 'path';
5
5
  import require$$5 from 'crypto';
6
6
  import require$$0$2 from 'util';
@@ -28621,29 +28621,43 @@ function optimizedDepsPlugin(config) {
28621
28621
  };
28622
28622
  }
28623
28623
  function optimizedDepsBuildPlugin(config) {
28624
+ let buildStartCalled = false;
28624
28625
  return {
28625
28626
  name: 'vite:optimized-deps-build',
28626
28627
  buildStart() {
28627
- if (!config.isWorker) {
28628
- // This will be run for the current active optimizer, during build
28629
- // it will be the SSR optimizer if config.build.ssr is defined
28628
+ // Only reset the registered ids after a rebuild during build --watch
28629
+ if (!config.isWorker && buildStartCalled) {
28630
28630
  getDepsOptimizer(config)?.resetRegisteredIds();
28631
28631
  }
28632
+ buildStartCalled = true;
28632
28633
  },
28633
- resolveId(id, importer, { ssr }) {
28634
- if (getDepsOptimizer(config, ssr)?.isOptimizedDepFile(id)) {
28634
+ async resolveId(id, importer, options) {
28635
+ const depsOptimizer = getDepsOptimizer(config);
28636
+ if (!depsOptimizer)
28637
+ return;
28638
+ if (depsOptimizer.isOptimizedDepFile(id)) {
28635
28639
  return id;
28636
28640
  }
28641
+ else {
28642
+ if (options?.custom?.['vite:pre-alias']) {
28643
+ // Skip registering the id if it is being resolved from the pre-alias plugin
28644
+ // When a optimized dep is aliased, we need to avoid waiting for it before optimizing
28645
+ return;
28646
+ }
28647
+ const resolved = await this.resolve(id, importer, {
28648
+ ...options,
28649
+ skipSelf: true,
28650
+ });
28651
+ if (resolved) {
28652
+ depsOptimizer.delayDepsOptimizerUntil(resolved.id, async () => {
28653
+ await this.load(resolved);
28654
+ });
28655
+ return resolved;
28656
+ }
28657
+ }
28637
28658
  },
28638
- transform(_code, id, options) {
28639
- const ssr = options?.ssr === true;
28640
- getDepsOptimizer(config, ssr)?.delayDepsOptimizerUntil(id, async () => {
28641
- await this.load({ id });
28642
- });
28643
- },
28644
- async load(id, options) {
28645
- const ssr = options?.ssr === true;
28646
- const depsOptimizer = getDepsOptimizer(config, ssr);
28659
+ async load(id) {
28660
+ const depsOptimizer = getDepsOptimizer(config);
28647
28661
  if (!depsOptimizer?.isOptimizedDepFile(id)) {
28648
28662
  return;
28649
28663
  }
@@ -37821,8 +37835,14 @@ function cssPlugin(config) {
37821
37835
  return fileToUrl(resolved, config, this);
37822
37836
  }
37823
37837
  if (config.command === 'build') {
37824
- // #9800 If we cannot resolve the css url, leave a warning.
37825
- config.logger.warnOnce(`\n${url} referenced in ${id} didn't resolve at build time, it will remain unchanged to be resolved at runtime`);
37838
+ const isExternal = config.build.rollupOptions.external
37839
+ ? resolveUserExternal(config.build.rollupOptions.external, url, // use URL as id since id could not be resolved
37840
+ id, false)
37841
+ : false;
37842
+ if (!isExternal) {
37843
+ // #9800 If we cannot resolve the css url, leave a warning.
37844
+ config.logger.warnOnce(`\n${url} referenced in ${id} didn't resolve at build time, it will remain unchanged to be resolved at runtime`);
37845
+ }
37826
37846
  }
37827
37847
  return url;
37828
37848
  };
@@ -38485,7 +38505,7 @@ function createCachedImport(imp) {
38485
38505
  };
38486
38506
  }
38487
38507
  const importPostcssImport = createCachedImport(() => import('./dep-e3f470e2.js').then(function (n) { return n.i; }));
38488
- const importPostcssModules = createCachedImport(() => import('./dep-970ed287.js').then(function (n) { return n.i; }));
38508
+ const importPostcssModules = createCachedImport(() => import('./dep-1a577c21.js').then(function (n) { return n.i; }));
38489
38509
  const importPostcss = createCachedImport(() => import('postcss'));
38490
38510
  /**
38491
38511
  * @experimental
@@ -40602,7 +40622,7 @@ function importAnalysisPlugin(config) {
40602
40622
  }
40603
40623
  else if (needsInterop) {
40604
40624
  debug$a?.(`${url} needs interop`);
40605
- interopNamedImports(str(), importSpecifier, url, index);
40625
+ interopNamedImports(str(), importSpecifier, url, index, importer, config);
40606
40626
  rewriteDone = true;
40607
40627
  }
40608
40628
  }
@@ -40611,7 +40631,7 @@ function importAnalysisPlugin(config) {
40611
40631
  // correctly throw the error message.
40612
40632
  else if (url.includes(browserExternalId) &&
40613
40633
  source.slice(expStart, start).includes('{')) {
40614
- interopNamedImports(str(), importSpecifier, url, index);
40634
+ interopNamedImports(str(), importSpecifier, url, index, importer, config);
40615
40635
  rewriteDone = true;
40616
40636
  }
40617
40637
  if (!rewriteDone) {
@@ -40756,7 +40776,7 @@ function mergeAcceptedUrls(orderedUrls) {
40756
40776
  }
40757
40777
  return acceptedUrls;
40758
40778
  }
40759
- function interopNamedImports(str, importSpecifier, rewrittenUrl, importIndex) {
40779
+ function interopNamedImports(str, importSpecifier, rewrittenUrl, importIndex, importer, config) {
40760
40780
  const source = str.original;
40761
40781
  const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex, } = importSpecifier;
40762
40782
  if (dynamicIndex > -1) {
@@ -40766,7 +40786,7 @@ function interopNamedImports(str, importSpecifier, rewrittenUrl, importIndex) {
40766
40786
  else {
40767
40787
  const exp = source.slice(expStart, expEnd);
40768
40788
  const rawUrl = source.slice(start, end);
40769
- const rewritten = transformCjsImport(exp, rewrittenUrl, rawUrl, importIndex);
40789
+ const rewritten = transformCjsImport(exp, rewrittenUrl, rawUrl, importIndex, importer, config);
40770
40790
  if (rewritten) {
40771
40791
  str.overwrite(expStart, expEnd, rewritten, { contentOnly: true });
40772
40792
  }
@@ -40789,12 +40809,18 @@ function interopNamedImports(str, importSpecifier, rewrittenUrl, importIndex) {
40789
40809
  *
40790
40810
  * Credits \@csr632 via #837
40791
40811
  */
40792
- function transformCjsImport(importExp, url, rawUrl, importIndex) {
40812
+ function transformCjsImport(importExp, url, rawUrl, importIndex, importer, config) {
40793
40813
  const node = parse$d(importExp, {
40794
40814
  ecmaVersion: 'latest',
40795
40815
  sourceType: 'module',
40796
40816
  }).body[0];
40797
- if (node.type === 'ImportDeclaration' ||
40817
+ // `export * from '...'` may cause unexpected problem, so give it a warning
40818
+ if (config.command === 'serve' &&
40819
+ node.type === 'ExportAllDeclaration' &&
40820
+ !node.exported) {
40821
+ config.logger.warn(picocolorsExports.yellow(`\nUnable to interop \`${importExp}\` in ${importer}, this may lose module exports. Please export "${rawUrl}" as ESM or use named exports instead, e.g. \`export { A, B } from "${rawUrl}"\``));
40822
+ }
40823
+ else if (node.type === 'ImportDeclaration' ||
40798
40824
  node.type === 'ExportNamedDeclaration') {
40799
40825
  if (!node.specifiers.length) {
40800
40826
  return `import "${url}"`;
@@ -41358,8 +41384,9 @@ function preAliasPlugin(config) {
41358
41384
  return optimizedId; // aliased dep already optimized
41359
41385
  }
41360
41386
  const resolved = await this.resolve(id, importer, {
41361
- skipSelf: true,
41362
41387
  ...options,
41388
+ custom: { ...options.custom, 'vite:pre-alias': true },
41389
+ skipSelf: true,
41363
41390
  });
41364
41391
  if (resolved && !depsOptimizer.isOptimizedDepFile(resolved.id)) {
41365
41392
  const optimizeDeps = depsOptimizer.options;
@@ -42119,6 +42146,14 @@ async function resolvePlugins(config, prePlugins, normalPlugins, postPlugins) {
42119
42146
  : { pre: [], post: [] };
42120
42147
  const { modulePreload } = config.build;
42121
42148
  return [
42149
+ ...(isDepsOptimizerEnabled(config, false) ||
42150
+ isDepsOptimizerEnabled(config, true)
42151
+ ? [
42152
+ isBuild
42153
+ ? optimizedDepsBuildPlugin(config)
42154
+ : optimizedDepsPlugin(config),
42155
+ ]
42156
+ : []),
42122
42157
  isWatch ? ensureWatchPlugin() : null,
42123
42158
  isBuild ? metadataPlugin() : null,
42124
42159
  watchPackageDataPlugin(config.packageCache),
@@ -42129,14 +42164,6 @@ async function resolvePlugins(config, prePlugins, normalPlugins, postPlugins) {
42129
42164
  (typeof modulePreload === 'object' && modulePreload.polyfill)
42130
42165
  ? modulePreloadPolyfillPlugin(config)
42131
42166
  : null,
42132
- ...(isDepsOptimizerEnabled(config, false) ||
42133
- isDepsOptimizerEnabled(config, true)
42134
- ? [
42135
- isBuild
42136
- ? optimizedDepsBuildPlugin(config)
42137
- : optimizedDepsPlugin(config),
42138
- ]
42139
- : []),
42140
42167
  resolvePlugin({
42141
42168
  ...config.resolve,
42142
42169
  root: config.root,
@@ -43363,7 +43390,7 @@ async function createDepsOptimizer(config, server) {
43363
43390
  const ssr = isBuild && !!config.build.ssr; // safe as Dev SSR don't use this optimizer
43364
43391
  const sessionTimestamp = Date.now().toString();
43365
43392
  const cachedMetadata = await loadCachedDepOptimizationMetadata(config, ssr);
43366
- let handle;
43393
+ let debounceProcessingHandle;
43367
43394
  let closed = false;
43368
43395
  let metadata = cachedMetadata || initDepsOptimizerMetadata(config, ssr, sessionTimestamp);
43369
43396
  const depsOptimizer = {
@@ -43379,7 +43406,6 @@ async function createDepsOptimizer(config, server) {
43379
43406
  ensureFirstRun,
43380
43407
  close,
43381
43408
  options: getDepOptimizationConfig(config, ssr),
43382
- server,
43383
43409
  };
43384
43410
  depsOptimizerMap.set(config, depsOptimizer);
43385
43411
  let newDepsDiscovered = false;
@@ -43404,12 +43430,23 @@ async function createDepsOptimizer(config, server) {
43404
43430
  };
43405
43431
  let enqueuedRerun;
43406
43432
  let currentlyProcessing = false;
43407
- // If there wasn't a cache or it is outdated, we need to prepare a first run
43408
43433
  let firstRunCalled = !!cachedMetadata;
43434
+ // During build, we wait for every module to be scanned before resolving
43435
+ // optimized deps loading for rollup on each rebuild. It will be recreated
43436
+ // after each buildStart.
43437
+ // During dev, if this is a cold run, we wait for static imports discovered
43438
+ // from the first request before resolving to minimize full page reloads.
43439
+ // On warm start or after the first optimization is run, we use a simpler
43440
+ // debounce strategy each time a new dep is discovered.
43441
+ let crawlEndFinder;
43442
+ if (isBuild || !cachedMetadata) {
43443
+ crawlEndFinder = setupOnCrawlEnd(onCrawlEnd);
43444
+ }
43409
43445
  let optimizationResult;
43410
43446
  let discover;
43411
43447
  async function close() {
43412
43448
  closed = true;
43449
+ crawlEndFinder?.cancel();
43413
43450
  await Promise.allSettled([
43414
43451
  discover?.cancel(),
43415
43452
  depsOptimizer.scanProcessing,
@@ -43502,8 +43539,8 @@ async function createDepsOptimizer(config, server) {
43502
43539
  // Ensure that rerun is called sequentially
43503
43540
  enqueuedRerun = undefined;
43504
43541
  // Ensure that a rerun will not be issued for current discovered deps
43505
- if (handle)
43506
- clearTimeout(handle);
43542
+ if (debounceProcessingHandle)
43543
+ clearTimeout(debounceProcessingHandle);
43507
43544
  if (closed || Object.keys(metadata.discovered).length === 0) {
43508
43545
  currentlyProcessing = false;
43509
43546
  return;
@@ -43632,12 +43669,12 @@ async function createDepsOptimizer(config, server) {
43632
43669
  enqueuedRerun?.();
43633
43670
  }
43634
43671
  function fullReload() {
43635
- if (depsOptimizer.server) {
43672
+ if (server) {
43636
43673
  // Cached transform results have stale imports (resolved to
43637
43674
  // old locations) so they need to be invalidated before the page is
43638
43675
  // reloaded.
43639
- depsOptimizer.server.moduleGraph.invalidateAll();
43640
- depsOptimizer.server.ws.send({
43676
+ server.moduleGraph.invalidateAll();
43677
+ server.ws.send({
43641
43678
  type: 'full-reload',
43642
43679
  path: '*',
43643
43680
  });
@@ -43675,7 +43712,10 @@ async function createDepsOptimizer(config, server) {
43675
43712
  // We'll wait until the user codebase is eagerly processed by Vite so
43676
43713
  // we can get a list of every missing dependency before giving to the
43677
43714
  // browser a dependency that may be outdated, thus avoiding full page reloads
43678
- if (firstRunCalled) {
43715
+ if (!crawlEndFinder) {
43716
+ if (isBuild) {
43717
+ logger.error('Vite Internal Error: Missing dependency found after crawling ended');
43718
+ }
43679
43719
  // Debounced rerun, let other missing dependencies be discovered before
43680
43720
  // the running next optimizeDeps
43681
43721
  debouncedProcessing();
@@ -43708,25 +43748,33 @@ async function createDepsOptimizer(config, server) {
43708
43748
  // Debounced rerun, let other missing dependencies be discovered before
43709
43749
  // the running next optimizeDeps
43710
43750
  enqueuedRerun = undefined;
43711
- if (handle)
43712
- clearTimeout(handle);
43751
+ if (debounceProcessingHandle)
43752
+ clearTimeout(debounceProcessingHandle);
43713
43753
  if (newDepsToLogHandle)
43714
43754
  clearTimeout(newDepsToLogHandle);
43715
43755
  newDepsToLogHandle = undefined;
43716
- handle = setTimeout(() => {
43717
- handle = undefined;
43756
+ debounceProcessingHandle = setTimeout(() => {
43757
+ debounceProcessingHandle = undefined;
43718
43758
  enqueuedRerun = rerun;
43719
43759
  if (!currentlyProcessing) {
43720
43760
  enqueuedRerun();
43721
43761
  }
43722
43762
  }, timeout);
43723
43763
  }
43764
+ // During dev, onCrawlEnd is called once when the server starts and all static
43765
+ // imports after the first request have been crawled (dynamic imports may also
43766
+ // be crawled if the browser requests them right away).
43767
+ // During build, onCrawlEnd will be called once after each buildStart (so in
43768
+ // watch mode it will be called after each rebuild has processed every module).
43769
+ // All modules are transformed first in this case (both static and dynamic).
43724
43770
  async function onCrawlEnd() {
43771
+ // On build time, a missing dep appearing after onCrawlEnd is an internal error
43772
+ // On dev, switch after this point to a simple debounce strategy
43773
+ crawlEndFinder = undefined;
43725
43774
  debug$8?.(picocolorsExports.green(`✨ static imports crawl ended`));
43726
- if (firstRunCalled) {
43775
+ if (closed) {
43727
43776
  return;
43728
43777
  }
43729
- currentlyProcessing = false;
43730
43778
  const crawlDeps = Object.keys(metadata.discovered);
43731
43779
  // Await for the scan+optimize step running in the background
43732
43780
  // It normally should be over by the time crawling of user code ended
@@ -43734,6 +43782,7 @@ async function createDepsOptimizer(config, server) {
43734
43782
  if (!isBuild && optimizationResult) {
43735
43783
  const result = await optimizationResult.result;
43736
43784
  optimizationResult = undefined;
43785
+ currentlyProcessing = false;
43737
43786
  const scanDeps = Object.keys(result.metadata.optimized);
43738
43787
  if (scanDeps.length === 0 && crawlDeps.length === 0) {
43739
43788
  debug$8?.(picocolorsExports.green(`✨ no dependencies found by the scanner or crawling static imports`));
@@ -43766,6 +43815,7 @@ async function createDepsOptimizer(config, server) {
43766
43815
  }
43767
43816
  }
43768
43817
  else {
43818
+ currentlyProcessing = false;
43769
43819
  if (crawlDeps.length === 0) {
43770
43820
  debug$8?.(picocolorsExports.green(`✨ no dependencies found while crawling the static imports`));
43771
43821
  firstRunCalled = true;
@@ -43776,29 +43826,51 @@ async function createDepsOptimizer(config, server) {
43776
43826
  }
43777
43827
  }
43778
43828
  }
43779
- const runOptimizerIfIdleAfterMs = 50;
43780
- let registeredIds = [];
43781
- let seenIds = new Set();
43782
- let workersSources = new Set();
43783
- const waitingOn = new Set();
43784
- let firstRunEnsured = false;
43829
+ // Called during buildStart at build time, when build --watch is used.
43785
43830
  function resetRegisteredIds() {
43786
- registeredIds = [];
43787
- seenIds = new Set();
43788
- workersSources = new Set();
43789
- waitingOn.clear();
43790
- firstRunEnsured = false;
43831
+ crawlEndFinder?.cancel();
43832
+ crawlEndFinder = setupOnCrawlEnd(onCrawlEnd);
43833
+ }
43834
+ function registerWorkersSource(id) {
43835
+ crawlEndFinder?.registerWorkersSource(id);
43836
+ }
43837
+ function delayDepsOptimizerUntil(id, done) {
43838
+ if (crawlEndFinder && !depsOptimizer.isOptimizedDepFile(id)) {
43839
+ crawlEndFinder.delayDepsOptimizerUntil(id, done);
43840
+ }
43841
+ }
43842
+ function ensureFirstRun() {
43843
+ crawlEndFinder?.ensureFirstRun();
43844
+ }
43845
+ }
43846
+ const callCrawlEndIfIdleAfterMs = 50;
43847
+ function setupOnCrawlEnd(onCrawlEnd) {
43848
+ const registeredIds = new Set();
43849
+ const seenIds = new Set();
43850
+ const workersSources = new Set();
43851
+ let timeoutHandle;
43852
+ let cancelled = false;
43853
+ function cancel() {
43854
+ cancelled = true;
43855
+ }
43856
+ let crawlEndCalled = false;
43857
+ function callOnCrawlEnd() {
43858
+ if (!cancelled && !crawlEndCalled) {
43859
+ crawlEndCalled = true;
43860
+ onCrawlEnd();
43861
+ }
43791
43862
  }
43792
43863
  // If all the inputs are dependencies, we aren't going to get any
43793
43864
  // delayDepsOptimizerUntil(id) calls. We need to guard against this
43794
43865
  // by forcing a rerun if no deps have been registered
43866
+ let firstRunEnsured = false;
43795
43867
  function ensureFirstRun() {
43796
- if (!firstRunEnsured && !firstRunCalled && registeredIds.length === 0) {
43868
+ if (!firstRunEnsured && seenIds.size === 0) {
43797
43869
  setTimeout(() => {
43798
- if (!closed && registeredIds.length === 0) {
43799
- onCrawlEnd();
43870
+ if (seenIds.size === 0) {
43871
+ callOnCrawlEnd();
43800
43872
  }
43801
- }, runOptimizerIfIdleAfterMs);
43873
+ }, 200);
43802
43874
  }
43803
43875
  firstRunEnsured = true;
43804
43876
  }
@@ -43806,56 +43878,42 @@ async function createDepsOptimizer(config, server) {
43806
43878
  workersSources.add(id);
43807
43879
  // Avoid waiting for this id, as it may be blocked by the rollup
43808
43880
  // bundling process of the worker that also depends on the optimizer
43809
- registeredIds = registeredIds.filter((registered) => registered.id !== id);
43810
- if (waitingOn.has(id)) {
43811
- waitingOn.delete(id);
43812
- runOptimizerWhenIdle();
43813
- }
43881
+ registeredIds.delete(id);
43882
+ checkIfCrawlEndAfterTimeout();
43814
43883
  }
43815
43884
  function delayDepsOptimizerUntil(id, done) {
43816
- if (!depsOptimizer.isOptimizedDepFile(id) && !seenIds.has(id)) {
43885
+ if (!seenIds.has(id)) {
43817
43886
  seenIds.add(id);
43818
- registeredIds.push({ id, done });
43819
- runOptimizerWhenIdle();
43887
+ if (!workersSources.has(id)) {
43888
+ registeredIds.add(id);
43889
+ done()
43890
+ .catch(() => { })
43891
+ .finally(() => markIdAsDone(id));
43892
+ }
43820
43893
  }
43821
43894
  }
43822
- async function runOptimizerWhenIdle() {
43823
- if (waitingOn.size > 0)
43895
+ function markIdAsDone(id) {
43896
+ registeredIds.delete(id);
43897
+ checkIfCrawlEndAfterTimeout();
43898
+ }
43899
+ function checkIfCrawlEndAfterTimeout() {
43900
+ if (cancelled || registeredIds.size > 0)
43824
43901
  return;
43825
- const processingRegisteredIds = registeredIds;
43826
- registeredIds = [];
43827
- const donePromises = processingRegisteredIds.map(async (registeredId) => {
43828
- waitingOn.add(registeredId.id);
43829
- try {
43830
- await registeredId.done();
43831
- }
43832
- finally {
43833
- waitingOn.delete(registeredId.id);
43834
- }
43835
- });
43836
- const afterLoad = () => {
43837
- if (closed)
43838
- return;
43839
- if (registeredIds.length > 0 &&
43840
- registeredIds.every((registeredId) => workersSources.has(registeredId.id))) {
43841
- return;
43842
- }
43843
- if (registeredIds.length > 0) {
43844
- runOptimizerWhenIdle();
43845
- }
43846
- else {
43847
- onCrawlEnd();
43848
- }
43849
- };
43850
- const results = await Promise.allSettled(donePromises);
43851
- if (registeredIds.length > 0 ||
43852
- results.some((result) => result.status === 'rejected')) {
43853
- afterLoad();
43854
- }
43855
- else {
43856
- setTimeout(afterLoad, runOptimizerIfIdleAfterMs);
43857
- }
43902
+ if (timeoutHandle)
43903
+ clearTimeout(timeoutHandle);
43904
+ timeoutHandle = setTimeout(callOnCrawlEndWhenIdle, callCrawlEndIfIdleAfterMs);
43905
+ }
43906
+ async function callOnCrawlEndWhenIdle() {
43907
+ if (cancelled || registeredIds.size > 0)
43908
+ return;
43909
+ callOnCrawlEnd();
43858
43910
  }
43911
+ return {
43912
+ ensureFirstRun,
43913
+ registerWorkersSource,
43914
+ delayDepsOptimizerUntil,
43915
+ cancel,
43916
+ };
43859
43917
  }
43860
43918
  async function createDevSsrDepsOptimizer(config) {
43861
43919
  const metadata = await optimizeServerSsrDeps(config);
@@ -43962,22 +44020,18 @@ function addOptimizedDepInfo(metadata, type, depInfo) {
43962
44020
  metadata.depInfoList.push(depInfo);
43963
44021
  return depInfo;
43964
44022
  }
44023
+ let firstLoadCachedDepOptimizationMetadata = true;
43965
44024
  /**
43966
44025
  * Creates the initial dep optimization metadata, loading it from the deps cache
43967
44026
  * if it exists and pre-bundling isn't forced
43968
44027
  */
43969
44028
  async function loadCachedDepOptimizationMetadata(config, ssr, force = config.optimizeDeps.force, asCommand = false) {
43970
44029
  const log = asCommand ? config.logger.info : debug$7;
43971
- setTimeout(() => {
43972
- // Before Vite 2.9, dependencies were cached in the root of the cacheDir
43973
- // For compat, we remove the cache if we find the old structure
43974
- if (fs$l.existsSync(path$o.join(config.cacheDir, '_metadata.json'))) {
43975
- emptyDir(config.cacheDir);
43976
- }
43977
- // Fire a clean up of stale cache dirs, in case old processes didn't
43978
- // terminate correctly
43979
- cleanupDepsCacheStaleDirs(config);
43980
- }, 100);
44030
+ if (firstLoadCachedDepOptimizationMetadata) {
44031
+ firstLoadCachedDepOptimizationMetadata = false;
44032
+ // Fire up a clean up of stale processing deps dirs if older process exited early
44033
+ setTimeout(() => cleanupDepsCacheStaleDirs(config), 0);
44034
+ }
43981
44035
  const depsCacheDir = getDepsCacheDir(config, ssr);
43982
44036
  if (!force) {
43983
44037
  let cachedMetadata;
@@ -44081,6 +44135,9 @@ function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.command
44081
44135
  metadata,
44082
44136
  cancel: cleanUp,
44083
44137
  commit: async () => {
44138
+ if (cleaned) {
44139
+ throw new Error('Can not commit a Deps Optimization run as it was cancelled');
44140
+ }
44084
44141
  // Ignore clean up requests after this point so the temp folder isn't deleted before
44085
44142
  // we finish commiting the new deps cache files to the deps folder
44086
44143
  committed = true;
@@ -44221,7 +44278,7 @@ async function prepareEsbuildOptimizerRun(resolvedConfig, depsInfo, ssr, process
44221
44278
  const idToExports = {};
44222
44279
  const optimizeDeps = getDepOptimizationConfig(config, ssr);
44223
44280
  const { plugins: pluginsFromConfig = [], ...esbuildOptions } = optimizeDeps?.esbuildOptions ?? {};
44224
- for (const id in depsInfo) {
44281
+ await Promise.all(Object.keys(depsInfo).map(async (id) => {
44225
44282
  const src = depsInfo[id].src;
44226
44283
  const exportsData = await (depsInfo[id].exportsData ??
44227
44284
  extractExportsData(src, config, ssr));
@@ -44236,7 +44293,7 @@ async function prepareEsbuildOptimizerRun(resolvedConfig, depsInfo, ssr, process
44236
44293
  const flatId = flattenId(id);
44237
44294
  flatIdDeps[flatId] = src;
44238
44295
  idToExports[id] = exportsData;
44239
- }
44296
+ }));
44240
44297
  if (optimizerContext.cancelled)
44241
44298
  return { context: undefined, idToExports };
44242
44299
  // esbuild automatically replaces process.env.NODE_ENV for platform 'browser'
@@ -44981,7 +45038,7 @@ function buildImportAnalysisPlugin(config) {
44981
45038
  }
44982
45039
  else if (needsInterop) {
44983
45040
  // config.logger.info(`${url} needs interop`)
44984
- interopNamedImports(str(), imports[index], url, index);
45041
+ interopNamedImports(str(), imports[index], url, index, importer, config);
44985
45042
  rewriteDone = true;
44986
45043
  }
44987
45044
  if (!rewriteDone) {
@@ -46228,6 +46285,7 @@ var build$1 = {
46228
46285
  resolveBuildOutputs: resolveBuildOutputs,
46229
46286
  resolveBuildPlugins: resolveBuildPlugins,
46230
46287
  resolveLibFilename: resolveLibFilename,
46288
+ resolveUserExternal: resolveUserExternal,
46231
46289
  toOutputFilePathInCss: toOutputFilePathInCss,
46232
46290
  toOutputFilePathInHtml: toOutputFilePathInHtml,
46233
46291
  toOutputFilePathInJS: toOutputFilePathInJS,
@@ -63154,10 +63212,6 @@ async function createServer(inlineConfig = {}) {
63154
63212
  }
63155
63213
  async function _createServer(inlineConfig = {}, options) {
63156
63214
  const config = await resolveConfig(inlineConfig, 'serve');
63157
- if (isDepsOptimizerEnabled(config, false)) {
63158
- // start optimizer in the background, we still need to await the setup
63159
- await initDepsOptimizer(config);
63160
- }
63161
63215
  const { root, server: serverConfig } = config;
63162
63216
  const httpsOptions = await resolveHttpsConfig(config.server.https);
63163
63217
  const { middlewareMode } = serverConfig;
@@ -63396,12 +63450,6 @@ async function _createServer(inlineConfig = {}, options) {
63396
63450
  }
63397
63451
  // error handler
63398
63452
  middlewares.use(errorMiddleware(server, middlewareMode));
63399
- // when the optimizer is ready, hook server so that it can reload the page
63400
- // or invalidate the module graph when needed
63401
- const depsOptimizer = getDepsOptimizer(config);
63402
- if (depsOptimizer) {
63403
- depsOptimizer.server = server;
63404
- }
63405
63453
  // httpServer.listen can be called multiple times
63406
63454
  // when port when using next port number
63407
63455
  // this code is to avoid calling buildStart multiple times
@@ -63414,6 +63462,10 @@ async function _createServer(inlineConfig = {}, options) {
63414
63462
  return initingServer;
63415
63463
  initingServer = (async function () {
63416
63464
  await container.buildStart({});
63465
+ // start deps optimizer after all container plugins are ready
63466
+ if (isDepsOptimizerEnabled(config, false)) {
63467
+ await initDepsOptimizer(config, server);
63468
+ }
63417
63469
  initingServer = undefined;
63418
63470
  serverInited = true;
63419
63471
  })();
@@ -63616,7 +63668,7 @@ function compression() {
63616
63668
  // disable Brotli on Node<12.7 where it is unsupported:
63617
63669
  if (!zlib$1.createBrotliCompress)
63618
63670
  brotli = false;
63619
- return (req, res, next = noop) => {
63671
+ return function viteCompressionMiddleware(req, res, next = noop) {
63620
63672
  const accept = req.headers['accept-encoding'] + '';
63621
63673
  const encoding = ((brotli && accept.match(/\bbr\b/)) ||
63622
63674
  (accept.match(/\bgzip\b/)) ||
@@ -63773,7 +63825,7 @@ async function preview(inlineConfig = {}) {
63773
63825
  const previewBase = config.base === './' || config.base === '' ? '/' : config.base;
63774
63826
  // static assets
63775
63827
  const headers = config.preview.headers;
63776
- const assetServer = sirv(distDir, {
63828
+ const viteAssetMiddleware = (...args) => sirv(distDir, {
63777
63829
  etag: true,
63778
63830
  dev: true,
63779
63831
  single: config.appType === 'spa',
@@ -63787,8 +63839,8 @@ async function preview(inlineConfig = {}) {
63787
63839
  shouldServe(filePath) {
63788
63840
  return shouldServeFile(filePath, distDir);
63789
63841
  },
63790
- });
63791
- app.use(previewBase, assetServer);
63842
+ })(...args);
63843
+ app.use(previewBase, viteAssetMiddleware);
63792
63844
  // apply post server hooks from plugins
63793
63845
  postHooks.forEach((fn) => fn && fn());
63794
63846
  const hostname = await resolveHostname(options.host);
@@ -64378,7 +64430,7 @@ async function loadConfigFromBundledFile(fileName, bundledCode, isESM) {
64378
64430
  if (isESM) {
64379
64431
  const fileBase = `${fileName}.timestamp-${Date.now()}-${Math.random()
64380
64432
  .toString(16)
64381
- .slice(2)})}`;
64433
+ .slice(2)}`;
64382
64434
  const fileNameTmp = `${fileBase}.mjs`;
64383
64435
  const fileUrl = `${pathToFileURL(fileBase)}.mjs`;
64384
64436
  await fsp.writeFile(fileNameTmp, bundledCode);
package/dist/node/cli.js CHANGED
@@ -2,7 +2,7 @@ import path from 'node:path';
2
2
  import fs from 'node:fs';
3
3
  import { performance } from 'node:perf_hooks';
4
4
  import { EventEmitter } from 'events';
5
- import { B as picocolorsExports, C as bindShortcuts, x as createLogger, h as resolveConfig } from './chunks/dep-a26366f0.js';
5
+ import { B as picocolorsExports, C as bindShortcuts, x as createLogger, h as resolveConfig } from './chunks/dep-f1f8facc.js';
6
6
  import { VERSION } from './constants.js';
7
7
  import 'node:fs/promises';
8
8
  import 'node:url';
@@ -728,7 +728,7 @@ cli
728
728
  filterDuplicateOptions(options);
729
729
  // output structure is preserved even after bundling so require()
730
730
  // is ok here
731
- const { createServer } = await import('./chunks/dep-a26366f0.js').then(function (n) { return n.G; });
731
+ const { createServer } = await import('./chunks/dep-f1f8facc.js').then(function (n) { return n.G; });
732
732
  try {
733
733
  const server = await createServer({
734
734
  root,
@@ -806,7 +806,7 @@ cli
806
806
  .option('-w, --watch', `[boolean] rebuilds when modules have changed on disk`)
807
807
  .action(async (root, options) => {
808
808
  filterDuplicateOptions(options);
809
- const { build } = await import('./chunks/dep-a26366f0.js').then(function (n) { return n.F; });
809
+ const { build } = await import('./chunks/dep-f1f8facc.js').then(function (n) { return n.F; });
810
810
  const buildOptions = cleanOptions(options);
811
811
  try {
812
812
  await build({
@@ -834,7 +834,7 @@ cli
834
834
  .option('--force', `[boolean] force the optimizer to ignore the cache and re-bundle`)
835
835
  .action(async (root, options) => {
836
836
  filterDuplicateOptions(options);
837
- const { optimizeDeps } = await import('./chunks/dep-a26366f0.js').then(function (n) { return n.E; });
837
+ const { optimizeDeps } = await import('./chunks/dep-f1f8facc.js').then(function (n) { return n.E; });
838
838
  try {
839
839
  const config = await resolveConfig({
840
840
  root,
@@ -860,7 +860,7 @@ cli
860
860
  .option('--outDir <dir>', `[string] output directory (default: dist)`)
861
861
  .action(async (root, options) => {
862
862
  filterDuplicateOptions(options);
863
- const { preview } = await import('./chunks/dep-a26366f0.js').then(function (n) { return n.H; });
863
+ const { preview } = await import('./chunks/dep-f1f8facc.js').then(function (n) { return n.H; });
864
864
  try {
865
865
  const server = await preview({
866
866
  root,
@@ -680,7 +680,6 @@ export declare interface DepsOptimizer {
680
680
  ensureFirstRun: () => void;
681
681
  close: () => Promise<void>;
682
682
  options: DepOptimizationOptions;
683
- server?: ViteDevServer;
684
683
  }
685
684
 
686
685
  export { ErrorPayload }
@@ -1,5 +1,5 @@
1
- import { i as isInNodeModules } from './chunks/dep-a26366f0.js';
2
- export { b as build, e as buildErrorMessage, v as createFilter, x as createLogger, c as createServer, g as defineConfig, f as formatPostcssSourceMap, k as getDepOptimizationConfig, m as isDepsOptimizerEnabled, l as loadConfigFromFile, z as loadEnv, u as mergeAlias, q as mergeConfig, n as normalizePath, o as optimizeDeps, a as preprocessCSS, p as preview, j as resolveBaseUrl, h as resolveConfig, A as resolveEnvPrefix, d as resolvePackageData, r as resolvePackageEntry, y as searchForWorkspaceRoot, w as send, s as sortUserPlugins, t as transformWithEsbuild } from './chunks/dep-a26366f0.js';
1
+ import { i as isInNodeModules } from './chunks/dep-f1f8facc.js';
2
+ export { b as build, e as buildErrorMessage, v as createFilter, x as createLogger, c as createServer, g as defineConfig, f as formatPostcssSourceMap, k as getDepOptimizationConfig, m as isDepsOptimizerEnabled, l as loadConfigFromFile, z as loadEnv, u as mergeAlias, q as mergeConfig, n as normalizePath, o as optimizeDeps, a as preprocessCSS, p as preview, j as resolveBaseUrl, h as resolveConfig, A as resolveEnvPrefix, d as resolvePackageData, r as resolvePackageEntry, y as searchForWorkspaceRoot, w as send, s as sortUserPlugins, t as transformWithEsbuild } from './chunks/dep-f1f8facc.js';
3
3
  export { VERSION as version } from './constants.js';
4
4
  export { version as esbuildVersion } from 'esbuild';
5
5
  export { VERSION as rollupVersion } from 'rollup';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite",
3
- "version": "4.3.0-beta.5",
3
+ "version": "4.3.0-beta.7",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "author": "Evan You",