vite 2.9.0-beta.6 → 2.9.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.

@@ -19086,7 +19086,7 @@ async function compileCSS(id, code, config, urlReplacer, atImportResolvers, serv
19086
19086
  replacer: urlReplacer
19087
19087
  }));
19088
19088
  if (isModule) {
19089
- postcssPlugins.unshift((await Promise.resolve().then(function () { return require('./dep-b1024ee7.js'); }).then(function (n) { return n.index; })).default({
19089
+ postcssPlugins.unshift((await Promise.resolve().then(function () { return require('./dep-d52558aa.js'); }).then(function (n) { return n.index; })).default({
19090
19090
  ...modulesOptions,
19091
19091
  getJSON(cssFileName, _modules, outputFileName) {
19092
19092
  modules = _modules;
@@ -21632,7 +21632,7 @@ const assetAttrsConfig = {
21632
21632
  const isAsyncScriptMap = new WeakMap();
21633
21633
  async function traverseHtml(html, filePath, visitor) {
21634
21634
  // lazy load compiler
21635
- const { parse, transform } = await Promise.resolve().then(function () { return require('./dep-5ae06c1f.js'); }).then(function (n) { return n.compilerDom_cjs; });
21635
+ const { parse, transform } = await Promise.resolve().then(function () { return require('./dep-ee121766.js'); }).then(function (n) { return n.compilerDom_cjs; });
21636
21636
  // @vue/compiler-core doesn't like lowercase doctypes
21637
21637
  html = html.replace(/<!doctype\s/i, '<!DOCTYPE ');
21638
21638
  try {
@@ -30217,17 +30217,18 @@ const externalTypes = [
30217
30217
  'tsx',
30218
30218
  ...KNOWN_ASSET_TYPES
30219
30219
  ];
30220
- function esbuildDepPlugin(qualified, exportsData, config, ssr) {
30220
+ function esbuildDepPlugin(qualified, exportsData, config) {
30221
30221
  // remove optimizable extensions from `externalTypes` list
30222
30222
  const allExternalTypes = config.optimizeDeps.extensions
30223
30223
  ? externalTypes.filter((type) => { var _a; return !((_a = config.optimizeDeps.extensions) === null || _a === void 0 ? void 0 : _a.includes('.' + type)); })
30224
30224
  : externalTypes;
30225
30225
  // default resolver which prefers ESM
30226
- const _resolve = config.createResolver({ asSrc: false });
30226
+ const _resolve = config.createResolver({ asSrc: false, scan: true });
30227
30227
  // cjs resolver that prefers Node
30228
30228
  const _resolveRequire = config.createResolver({
30229
30229
  asSrc: false,
30230
- isRequire: true
30230
+ isRequire: true,
30231
+ scan: true
30231
30232
  });
30232
30233
  const resolve = (id, importer, kind, resolveDir) => {
30233
30234
  let _importer;
@@ -30241,7 +30242,7 @@ function esbuildDepPlugin(qualified, exportsData, config, ssr) {
30241
30242
  _importer = importer in qualified ? qualified[importer] : importer;
30242
30243
  }
30243
30244
  const resolver = kind.startsWith('require') ? _resolveRequire : _resolve;
30244
- return resolver(id, _importer, undefined, ssr);
30245
+ return resolver(id, _importer, undefined);
30245
30246
  };
30246
30247
  return {
30247
30248
  name: 'vite:dep-pre-bundle',
@@ -36138,6 +36139,7 @@ async function createPluginContainer({ plugins, logger, root, build: { rollupOpt
36138
36139
  constructor(initialPlugin) {
36139
36140
  this.meta = minimalContext.meta;
36140
36141
  this.ssr = false;
36142
+ this._scan = false;
36141
36143
  this._activeId = null;
36142
36144
  this._activeCode = null;
36143
36145
  this._addedImports = null;
@@ -36157,7 +36159,11 @@ async function createPluginContainer({ plugins, logger, root, build: { rollupOpt
36157
36159
  skip = new Set(this._resolveSkips);
36158
36160
  skip.add(this._activePlugin);
36159
36161
  }
36160
- let out = await container.resolveId(id, importer, { skip, ssr: this.ssr });
36162
+ let out = await container.resolveId(id, importer, {
36163
+ skip,
36164
+ ssr: this.ssr,
36165
+ scan: this._scan
36166
+ });
36161
36167
  if (typeof out === 'string')
36162
36168
  out = { id: out };
36163
36169
  return out;
@@ -36364,8 +36370,10 @@ async function createPluginContainer({ plugins, logger, root, build: { rollupOpt
36364
36370
  async resolveId(rawId, importer = path$p.join(root, 'index.html'), options) {
36365
36371
  const skip = options === null || options === void 0 ? void 0 : options.skip;
36366
36372
  const ssr = options === null || options === void 0 ? void 0 : options.ssr;
36373
+ const scan = !!(options === null || options === void 0 ? void 0 : options.scan);
36367
36374
  const ctx = new Context();
36368
36375
  ctx.ssr = !!ssr;
36376
+ ctx._scan = scan;
36369
36377
  ctx._resolveSkips = skip;
36370
36378
  const resolveStart = isDebug ? perf_hooks.performance.now() : 0;
36371
36379
  let id = null;
@@ -36377,7 +36385,7 @@ async function createPluginContainer({ plugins, logger, root, build: { rollupOpt
36377
36385
  continue;
36378
36386
  ctx._activePlugin = plugin;
36379
36387
  const pluginResolveStart = isDebug ? perf_hooks.performance.now() : 0;
36380
- const result = await plugin.resolveId.call(ctx, rawId, importer, { ssr });
36388
+ const result = await plugin.resolveId.call(ctx, rawId, importer, { ssr, scan });
36381
36389
  if (!result)
36382
36390
  continue;
36383
36391
  if (typeof result === 'string') {
@@ -36549,10 +36557,17 @@ async function scanImports(config) {
36549
36557
  })));
36550
36558
  debug$d(`Scan completed in ${(perf_hooks.performance.now() - start).toFixed(2)}ms:`, deps);
36551
36559
  return {
36552
- deps,
36560
+ // Ensure a fixed order so hashes are stable and improve logs
36561
+ deps: orderedDependencies(deps),
36553
36562
  missing
36554
36563
  };
36555
36564
  }
36565
+ function orderedDependencies(deps) {
36566
+ const depsList = Object.entries(deps);
36567
+ // Ensure the same browserHash for the same set of dependencies
36568
+ depsList.sort((a, b) => a[0].localeCompare(b[0]));
36569
+ return Object.fromEntries(depsList);
36570
+ }
36556
36571
  function globEntries(pattern, config) {
36557
36572
  return out(pattern, {
36558
36573
  cwd: config.root,
@@ -36579,7 +36594,9 @@ function esbuildScanPlugin(config, container, depImports, missing, entries) {
36579
36594
  if (seen.has(key)) {
36580
36595
  return seen.get(key);
36581
36596
  }
36582
- const resolved = await container.resolveId(id, importer && normalizePath$4(importer));
36597
+ const resolved = await container.resolveId(id, importer && normalizePath$4(importer), {
36598
+ scan: true
36599
+ });
36583
36600
  const res = resolved === null || resolved === void 0 ? void 0 : resolved.id;
36584
36601
  seen.set(key, res);
36585
36602
  return res;
@@ -36885,75 +36902,124 @@ function isScannable(id) {
36885
36902
  return JS_TYPES_RE.test(id) || htmlTypesRE.test(id);
36886
36903
  }
36887
36904
 
36888
- const debug$c = createDebugger('vite:deps');
36889
- const isDebugEnabled = _debug('vite:deps').enabled;
36905
+ const debuggerViteDeps = createDebugger('vite:deps');
36906
+ const debug$c = debuggerViteDeps;
36907
+ const isDebugEnabled$1 = _debug('vite:deps').enabled;
36890
36908
  const jsExtensionRE = /\.js$/i;
36891
36909
  const jsMapExtensionRE = /\.js\.map$/i;
36892
36910
  /**
36893
36911
  * Used by Vite CLI when running `vite optimize`
36894
36912
  */
36895
- async function optimizeDeps(config, force = config.server.force, asCommand = false, newDeps, // missing imports encountered after server has started
36896
- ssr) {
36897
- const { metadata, run } = await createOptimizeDepsRun(config, force, asCommand, null, newDeps, ssr);
36898
- const result = await run();
36913
+ async function optimizeDeps(config, force = config.server.force, asCommand = false) {
36914
+ const log = asCommand ? config.logger.info : debug$c;
36915
+ const cachedMetadata = loadCachedDepOptimizationMetadata(config, force, asCommand);
36916
+ if (cachedMetadata) {
36917
+ return cachedMetadata;
36918
+ }
36919
+ const depsInfo = await discoverProjectDependencies(config);
36920
+ const depsString = depsLogString(Object.keys(depsInfo));
36921
+ log(colors$1.green(`Optimizing dependencies:\n ${depsString}`));
36922
+ const result = await runOptimizeDeps(config, depsInfo);
36899
36923
  result.commit();
36900
- return metadata;
36924
+ return result.metadata;
36925
+ }
36926
+ function createOptimizedDepsMetadata(config, timestamp) {
36927
+ const hash = getDepHash(config);
36928
+ return {
36929
+ hash,
36930
+ browserHash: getOptimizedBrowserHash(hash, {}, timestamp),
36931
+ optimized: {},
36932
+ chunks: {},
36933
+ discovered: {},
36934
+ depInfoList: []
36935
+ };
36936
+ }
36937
+ function addOptimizedDepInfo(metadata, type, depInfo) {
36938
+ metadata[type][depInfo.id] = depInfo;
36939
+ metadata.depInfoList.push(depInfo);
36940
+ return depInfo;
36901
36941
  }
36902
36942
  /**
36903
- * Internally, Vite uses this function to prepare a optimizeDeps run. When Vite starts, we can get
36904
- * the metadata and start the server without waiting for the optimizeDeps processing to be completed
36943
+ * Creates the initial dep optimization metadata, loading it from the deps cache
36944
+ * if it exists and pre-bundling isn't forced
36905
36945
  */
36906
- async function createOptimizeDepsRun(config, force = config.server.force, asCommand = false, currentData = null, newDeps, // missing imports encountered after server has started
36907
- ssr) {
36908
- config = {
36909
- ...config,
36910
- command: 'build'
36911
- };
36912
- const { root, logger } = config;
36913
- const log = asCommand ? logger.info : debug$c;
36946
+ function loadCachedDepOptimizationMetadata(config, force = config.server.force, asCommand = false) {
36947
+ const log = asCommand ? config.logger.info : debug$c;
36914
36948
  // Before Vite 2.9, dependencies were cached in the root of the cacheDir
36915
36949
  // For compat, we remove the cache if we find the old structure
36916
36950
  if (fs__default.existsSync(path__default.join(config.cacheDir, '_metadata.json'))) {
36917
36951
  emptyDir(config.cacheDir);
36918
36952
  }
36919
36953
  const depsCacheDir = getDepsCacheDir(config);
36920
- const processingCacheDir = getProcessingDepsCacheDir(config);
36921
- const mainHash = getDepHash(root, config);
36922
- const processing = newDepOptimizationProcessing();
36923
- const metadata = {
36924
- hash: mainHash,
36925
- browserHash: mainHash,
36926
- optimized: {},
36927
- chunks: {},
36928
- discovered: {}
36929
- };
36930
36954
  if (!force) {
36931
- let prevData;
36955
+ let cachedMetadata;
36932
36956
  try {
36933
- const prevDataPath = path__default.join(depsCacheDir, '_metadata.json');
36934
- prevData = parseOptimizedDepsMetadata(fs__default.readFileSync(prevDataPath, 'utf-8'), depsCacheDir);
36957
+ const cachedMetadataPath = path__default.join(depsCacheDir, '_metadata.json');
36958
+ cachedMetadata = parseOptimizedDepsMetadata(fs__default.readFileSync(cachedMetadataPath, 'utf-8'), depsCacheDir);
36935
36959
  }
36936
36960
  catch (e) { }
36937
36961
  // hash is consistent, no need to re-bundle
36938
- if (prevData && prevData.hash === metadata.hash) {
36962
+ if (cachedMetadata && cachedMetadata.hash === getDepHash(config)) {
36939
36963
  log('Hash is consistent. Skipping. Use --force to override.');
36940
36964
  // Nothing to commit or cancel as we are using the cache, we only
36941
36965
  // need to resolve the processing promise so requests can move on
36942
- const resolve = () => {
36943
- processing.resolve();
36944
- };
36945
- return {
36946
- metadata: prevData,
36947
- run: async () => {
36948
- return {
36949
- alteredFiles: false,
36950
- commit: resolve,
36951
- cancel: resolve
36952
- };
36953
- }
36954
- };
36966
+ return cachedMetadata;
36955
36967
  }
36956
36968
  }
36969
+ // Start with a fresh cache
36970
+ removeDirSync(depsCacheDir);
36971
+ }
36972
+ /**
36973
+ * Initial optimizeDeps at server start. Perform a fast scan using esbuild to
36974
+ * find deps to pre-bundle and include user hard-coded dependencies
36975
+ */
36976
+ async function discoverProjectDependencies(config, timestamp) {
36977
+ const { deps, missing } = await scanImports(config);
36978
+ const missingIds = Object.keys(missing);
36979
+ if (missingIds.length) {
36980
+ throw new Error(`The following dependencies are imported but could not be resolved:\n\n ${missingIds
36981
+ .map((id) => `${colors$1.cyan(id)} ${colors$1.white(colors$1.dim(`(imported by ${missing[id]})`))}`)
36982
+ .join(`\n `)}\n\nAre they installed?`);
36983
+ }
36984
+ await addManuallyIncludedOptimizeDeps(deps, config);
36985
+ const browserHash = getOptimizedBrowserHash(getDepHash(config), deps, timestamp);
36986
+ const discovered = {};
36987
+ for (const id in deps) {
36988
+ const entry = deps[id];
36989
+ discovered[id] = {
36990
+ id,
36991
+ file: getOptimizedDepPath(id, config),
36992
+ src: entry,
36993
+ browserHash: browserHash
36994
+ };
36995
+ }
36996
+ return discovered;
36997
+ }
36998
+ function depsLogString(qualifiedIds) {
36999
+ if (isDebugEnabled$1) {
37000
+ return colors$1.yellow(qualifiedIds.join(`\n `));
37001
+ }
37002
+ else {
37003
+ const total = qualifiedIds.length;
37004
+ const maxListed = 5;
37005
+ const listed = Math.min(total, maxListed);
37006
+ const extra = Math.max(0, total - maxListed);
37007
+ return colors$1.yellow(qualifiedIds.slice(0, listed).join(`, `) +
37008
+ (extra > 0 ? `, ...and ${extra} more` : ``));
37009
+ }
37010
+ }
37011
+ /**
37012
+ * Internally, Vite uses this function to prepare a optimizeDeps run. When Vite starts, we can get
37013
+ * the metadata and start the server without waiting for the optimizeDeps processing to be completed
37014
+ */
37015
+ async function runOptimizeDeps(config, depsInfo) {
37016
+ var _a, _b, _c, _d;
37017
+ config = {
37018
+ ...config,
37019
+ command: 'build'
37020
+ };
37021
+ const depsCacheDir = getDepsCacheDir(config);
37022
+ const processingCacheDir = getProcessingDepsCacheDir(config);
36957
37023
  // Create a temporal directory so we don't need to delete optimized deps
36958
37024
  // until they have been processed. This also avoids leaving the deps cache
36959
37025
  // directory in a corrupted state if there is an error
@@ -36966,256 +37032,156 @@ ssr) {
36966
37032
  // a hint for Node.js
36967
37033
  // all files in the cache directory should be recognized as ES modules
36968
37034
  writeFile(path__default.resolve(processingCacheDir, 'package.json'), JSON.stringify({ type: 'module' }));
36969
- let newBrowserHash;
36970
- let deps;
36971
- if (!newDeps) {
36972
- // Initial optimizeDeps at server start. Perform a fast scan using esbuild to
36973
- // find deps to pre-bundle and include user hard-coded dependencies
36974
- let missing;
36975
- ({ deps, missing } = await scanImports(config));
36976
- const missingIds = Object.keys(missing);
36977
- if (missingIds.length) {
36978
- processing.resolve();
36979
- throw new Error(`The following dependencies are imported but could not be resolved:\n\n ${missingIds
36980
- .map((id) => `${colors$1.cyan(id)} ${colors$1.white(colors$1.dim(`(imported by ${missing[id]})`))}`)
36981
- .join(`\n `)}\n\nAre they installed?`);
36982
- }
36983
- try {
36984
- await addManuallyIncludedOptimizeDeps(deps, config);
36985
- }
36986
- catch (e) {
36987
- processing.resolve();
36988
- throw e;
36989
- }
36990
- // update browser hash
36991
- newBrowserHash = metadata.browserHash = getOptimizedBrowserHash(metadata.hash, deps);
36992
- // We generate the mapping of dependency ids to their cache file location
36993
- // before processing the dependencies with esbuild. This allow us to continue
36994
- // processing files in the importAnalysis and resolve plugins
36995
- for (const id in deps) {
36996
- const entry = deps[id];
36997
- metadata.optimized[id] = {
36998
- file: getOptimizedDepPath(id, config),
36999
- src: entry,
37000
- browserHash: newBrowserHash,
37001
- processing: processing.promise
37002
- };
37003
- }
37035
+ const metadata = createOptimizedDepsMetadata(config);
37036
+ metadata.browserHash = getOptimizedBrowserHash(metadata.hash, depsFromOptimizedDepInfo(depsInfo));
37037
+ // We prebundle dependencies with esbuild and cache them, but there is no need
37038
+ // to wait here. Code that needs to access the cached deps needs to await
37039
+ // the optimizedDepInfo.processing promise for each dep
37040
+ const qualifiedIds = Object.keys(depsInfo);
37041
+ if (!qualifiedIds.length) {
37042
+ return {
37043
+ metadata,
37044
+ commit() {
37045
+ // Write metadata file, delete `deps` folder and rename the `processing` folder to `deps`
37046
+ commitProcessingDepsCacheSync();
37047
+ config.logger.info(`No dependencies to bundle. Skipping.\n\n\n`);
37048
+ },
37049
+ cancel
37050
+ };
37004
37051
  }
37005
- else {
37006
- // Missing dependencies were found at run-time, optimizeDeps called while the
37007
- // server is running
37008
- deps = depsFromOptimizedDepInfo(newDeps);
37009
- metadata.optimized = newDeps;
37010
- // For reruns keep current global browser hash and newDeps individual hashes until we know
37011
- // if files are stable so we can avoid a full page reload
37012
- metadata.browserHash = currentData.browserHash;
37013
- newBrowserHash = getOptimizedBrowserHash(metadata.hash, deps);
37014
- }
37015
- return { metadata, run: prebundleDeps };
37016
- async function prebundleDeps() {
37017
- // We prebundle dependencies with esbuild and cache them, but there is no need
37018
- // to wait here. Code that needs to access the cached deps needs to await
37019
- // the optimizeDepInfo.processing promise for each dep
37020
- var _a, _b, _c, _d, _e;
37021
- const qualifiedIds = Object.keys(deps);
37022
- if (!qualifiedIds.length) {
37023
- return {
37024
- alteredFiles: false,
37025
- commit() {
37026
- // Write metadata file, delete `deps` folder and rename the `processing` folder to `deps`
37027
- commitProcessingDepsCacheSync();
37028
- log(`No dependencies to bundle. Skipping.\n\n\n`);
37029
- processing.resolve();
37030
- },
37031
- cancel
37032
- };
37033
- }
37034
- let depsString;
37035
- if (isDebugEnabled) {
37036
- depsString = colors$1.yellow(qualifiedIds.join(`\n `));
37052
+ // esbuild generates nested directory output with lowest common ancestor base
37053
+ // this is unpredictable and makes it difficult to analyze entry / output
37054
+ // mapping. So what we do here is:
37055
+ // 1. flatten all ids to eliminate slash
37056
+ // 2. in the plugin, read the entry ourselves as virtual files to retain the
37057
+ // path.
37058
+ const flatIdDeps = {};
37059
+ const idToExports = {};
37060
+ const flatIdToExports = {};
37061
+ const { plugins = [], ...esbuildOptions } = (_b = (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.esbuildOptions) !== null && _b !== void 0 ? _b : {};
37062
+ await init;
37063
+ for (const id in depsInfo) {
37064
+ const flatId = flattenId(id);
37065
+ const filePath = (flatIdDeps[flatId] = depsInfo[id].src);
37066
+ let exportsData;
37067
+ if ((_c = config.optimizeDeps.extensions) === null || _c === void 0 ? void 0 : _c.some((ext) => filePath.endsWith(ext))) {
37068
+ // For custom supported extensions, build the entry file to transform it into JS,
37069
+ // and then parse with es-module-lexer. Note that the `bundle` option is not `true`,
37070
+ // so only the entry file is being transformed.
37071
+ const result = await esbuild.build({
37072
+ ...esbuildOptions,
37073
+ plugins,
37074
+ entryPoints: [filePath],
37075
+ write: false,
37076
+ format: 'esm'
37077
+ });
37078
+ exportsData = parse$f(result.outputFiles[0].text);
37037
37079
  }
37038
37080
  else {
37039
- const total = qualifiedIds.length;
37040
- const maxListed = 5;
37041
- const listed = Math.min(total, maxListed);
37042
- const extra = Math.max(0, total - maxListed);
37043
- depsString = colors$1.yellow(qualifiedIds.slice(0, listed).join(`\n `) +
37044
- (extra > 0 ? `\n (...and ${extra} more)` : ``));
37045
- }
37046
- if (!asCommand) {
37047
- if (!newDeps) {
37048
- // This is auto run on server start - let the user know that we are
37049
- // pre-optimizing deps
37050
- logger.info(colors$1.green(`Pre-bundling dependencies:\n ${depsString}`));
37051
- logger.info(`(this will be run only when your dependencies or config have changed)`);
37081
+ const entryContent = fs__default.readFileSync(filePath, 'utf-8');
37082
+ try {
37083
+ exportsData = parse$f(entryContent);
37052
37084
  }
37053
- }
37054
- else {
37055
- logger.info(colors$1.green(`Optimizing dependencies:\n ${depsString}`));
37056
- }
37057
- // esbuild generates nested directory output with lowest common ancestor base
37058
- // this is unpredictable and makes it difficult to analyze entry / output
37059
- // mapping. So what we do here is:
37060
- // 1. flatten all ids to eliminate slash
37061
- // 2. in the plugin, read the entry ourselves as virtual files to retain the
37062
- // path.
37063
- const flatIdDeps = {};
37064
- const idToExports = {};
37065
- const flatIdToExports = {};
37066
- const { plugins = [], ...esbuildOptions } = (_b = (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.esbuildOptions) !== null && _b !== void 0 ? _b : {};
37067
- await init;
37068
- for (const id in deps) {
37069
- const flatId = flattenId(id);
37070
- const filePath = (flatIdDeps[flatId] = deps[id]);
37071
- let exportsData;
37072
- if ((_c = config.optimizeDeps.extensions) === null || _c === void 0 ? void 0 : _c.some((ext) => filePath.endsWith(ext))) {
37073
- // For custom supported extensions, build the entry file to transform it into JS,
37074
- // and then parse with es-module-lexer. Note that the `bundle` option is not `true`,
37075
- // so only the entry file is being transformed.
37076
- const result = await esbuild.build({
37077
- ...esbuildOptions,
37078
- plugins,
37079
- entryPoints: [filePath],
37080
- write: false,
37081
- format: 'esm'
37085
+ catch {
37086
+ debug$c(`Unable to parse dependency: ${id}. Trying again with a JSX transform.`);
37087
+ const transformed = await transformWithEsbuild(entryContent, filePath, {
37088
+ loader: 'jsx'
37082
37089
  });
37083
- exportsData = parse$f(result.outputFiles[0].text);
37090
+ // Ensure that optimization won't fail by defaulting '.js' to the JSX parser.
37091
+ // This is useful for packages such as Gatsby.
37092
+ esbuildOptions.loader = {
37093
+ '.js': 'jsx',
37094
+ ...esbuildOptions.loader
37095
+ };
37096
+ exportsData = parse$f(transformed.code);
37084
37097
  }
37085
- else {
37086
- const entryContent = fs__default.readFileSync(filePath, 'utf-8');
37087
- try {
37088
- exportsData = parse$f(entryContent);
37089
- }
37090
- catch {
37091
- debug$c(`Unable to parse dependency: ${id}. Trying again with a JSX transform.`);
37092
- const transformed = await transformWithEsbuild(entryContent, filePath, {
37093
- loader: 'jsx'
37094
- });
37095
- // Ensure that optimization won't fail by defaulting '.js' to the JSX parser.
37096
- // This is useful for packages such as Gatsby.
37097
- esbuildOptions.loader = {
37098
- '.js': 'jsx',
37099
- ...esbuildOptions.loader
37100
- };
37101
- exportsData = parse$f(transformed.code);
37102
- }
37103
- for (const { ss, se } of exportsData[0]) {
37104
- const exp = entryContent.slice(ss, se);
37105
- if (/export\s+\*\s+from/.test(exp)) {
37106
- exportsData.hasReExports = true;
37107
- }
37098
+ for (const { ss, se } of exportsData[0]) {
37099
+ const exp = entryContent.slice(ss, se);
37100
+ if (/export\s+\*\s+from/.test(exp)) {
37101
+ exportsData.hasReExports = true;
37108
37102
  }
37109
37103
  }
37110
- idToExports[id] = exportsData;
37111
- flatIdToExports[flatId] = exportsData;
37112
- }
37113
- const define = {
37114
- 'process.env.NODE_ENV': JSON.stringify(config.mode)
37115
- };
37116
- for (const key in config.define) {
37117
- const value = config.define[key];
37118
- define[key] = typeof value === 'string' ? value : JSON.stringify(value);
37119
37104
  }
37120
- const start = perf_hooks.performance.now();
37121
- const result = await esbuild.build({
37122
- absWorkingDir: process.cwd(),
37123
- entryPoints: Object.keys(flatIdDeps),
37124
- bundle: true,
37125
- format: 'esm',
37126
- target: config.build.target || undefined,
37127
- external: (_d = config.optimizeDeps) === null || _d === void 0 ? void 0 : _d.exclude,
37128
- logLevel: 'error',
37129
- splitting: true,
37130
- sourcemap: true,
37131
- outdir: processingCacheDir,
37132
- ignoreAnnotations: true,
37133
- metafile: true,
37134
- define,
37135
- plugins: [
37136
- ...plugins,
37137
- esbuildDepPlugin(flatIdDeps, flatIdToExports, config, ssr)
37138
- ],
37139
- ...esbuildOptions
37105
+ idToExports[id] = exportsData;
37106
+ flatIdToExports[flatId] = exportsData;
37107
+ }
37108
+ const define = {
37109
+ 'process.env.NODE_ENV': JSON.stringify(config.mode)
37110
+ };
37111
+ for (const key in config.define) {
37112
+ const value = config.define[key];
37113
+ define[key] = typeof value === 'string' ? value : JSON.stringify(value);
37114
+ }
37115
+ const start = perf_hooks.performance.now();
37116
+ const result = await esbuild.build({
37117
+ absWorkingDir: process.cwd(),
37118
+ entryPoints: Object.keys(flatIdDeps),
37119
+ bundle: true,
37120
+ format: 'esm',
37121
+ target: config.build.target || undefined,
37122
+ external: (_d = config.optimizeDeps) === null || _d === void 0 ? void 0 : _d.exclude,
37123
+ logLevel: 'error',
37124
+ splitting: true,
37125
+ sourcemap: true,
37126
+ outdir: processingCacheDir,
37127
+ ignoreAnnotations: true,
37128
+ metafile: true,
37129
+ define,
37130
+ plugins: [
37131
+ ...plugins,
37132
+ esbuildDepPlugin(flatIdDeps, flatIdToExports, config)
37133
+ ],
37134
+ ...esbuildOptions
37135
+ });
37136
+ const meta = result.metafile;
37137
+ // the paths in `meta.outputs` are relative to `process.cwd()`
37138
+ const processingCacheDirOutputPath = path__default.relative(process.cwd(), processingCacheDir);
37139
+ for (const id in depsInfo) {
37140
+ const output = esbuildOutputFromId(meta.outputs, id, processingCacheDir);
37141
+ addOptimizedDepInfo(metadata, 'optimized', {
37142
+ ...depsInfo[id],
37143
+ needsInterop: needsInterop(id, idToExports[id], output),
37144
+ // We only need to hash the output.imports in to check for stability, but adding the hash
37145
+ // and file path gives us a unique hash that may be useful for other things in the future
37146
+ fileHash: getHash(metadata.hash + depsInfo[id].file + JSON.stringify(output.imports)),
37147
+ browserHash: metadata.browserHash
37140
37148
  });
37141
- const meta = result.metafile;
37142
- // the paths in `meta.outputs` are relative to `process.cwd()`
37143
- const processingCacheDirOutputPath = path__default.relative(process.cwd(), processingCacheDir);
37144
- for (const id in deps) {
37145
- const optimizedInfo = metadata.optimized[id];
37146
- optimizedInfo.needsInterop = needsInterop(id, idToExports[id], meta.outputs, processingCacheDirOutputPath);
37147
- const output = meta.outputs[path__default.relative(process.cwd(), getProcessingDepPath(id, config))];
37148
- if (output) {
37149
- // We only need to hash the output.imports in to check for stability, but adding the hash
37150
- // and file path gives us a unique hash that may be useful for other things in the future
37151
- optimizedInfo.fileHash = getHash(metadata.hash + optimizedInfo.file + JSON.stringify(output.imports));
37152
- }
37153
- }
37154
- // This only runs when missing deps are processed. Previous optimized deps are stable if
37155
- // the newly discovered deps don't have common chunks with them. Comparing their fileHash we
37156
- // can find out if it is safe to keep the current browser state. If one of the file hashes
37157
- // changed, a full page reload is needed
37158
- let alteredFiles = false;
37159
- if (currentData) {
37160
- alteredFiles = Object.keys(currentData.optimized).some((dep) => {
37161
- const currentInfo = currentData.optimized[dep];
37162
- const info = metadata.optimized[dep];
37163
- return (!(info === null || info === void 0 ? void 0 : info.fileHash) ||
37164
- !(currentInfo === null || currentInfo === void 0 ? void 0 : currentInfo.fileHash) ||
37165
- (info === null || info === void 0 ? void 0 : info.fileHash) !== (currentInfo === null || currentInfo === void 0 ? void 0 : currentInfo.fileHash));
37166
- });
37167
- debug$c(`optimized deps have altered files: ${alteredFiles}`);
37168
- }
37169
- for (const o of Object.keys(meta.outputs)) {
37170
- if (!o.match(jsMapExtensionRE)) {
37171
- const id = path__default
37172
- .relative(processingCacheDirOutputPath, o)
37173
- .replace(jsExtensionRE, '');
37174
- const file = getOptimizedDepPath(id, config);
37175
- if (!findFileInfo(metadata.optimized, file)) {
37176
- metadata.chunks[id] = {
37177
- file,
37178
- src: '',
37179
- needsInterop: false,
37180
- browserHash: (!alteredFiles && ((_e = currentData === null || currentData === void 0 ? void 0 : currentData.chunks[id]) === null || _e === void 0 ? void 0 : _e.browserHash)) ||
37181
- newBrowserHash
37182
- };
37183
- }
37149
+ }
37150
+ for (const o of Object.keys(meta.outputs)) {
37151
+ if (!o.match(jsMapExtensionRE)) {
37152
+ const id = path__default
37153
+ .relative(processingCacheDirOutputPath, o)
37154
+ .replace(jsExtensionRE, '');
37155
+ const file = getOptimizedDepPath(id, config);
37156
+ if (!findOptimizedDepInfoInRecord(metadata.optimized, (depInfo) => depInfo.file === file)) {
37157
+ addOptimizedDepInfo(metadata, 'chunks', {
37158
+ id,
37159
+ file,
37160
+ needsInterop: false,
37161
+ browserHash: metadata.browserHash
37162
+ });
37184
37163
  }
37185
37164
  }
37186
- if (alteredFiles) {
37187
- metadata.browserHash = newBrowserHash;
37188
- }
37189
- debug$c(`deps bundled in ${(perf_hooks.performance.now() - start).toFixed(2)}ms`);
37190
- return {
37191
- alteredFiles,
37192
- commit() {
37193
- if (alteredFiles) {
37194
- // Overwrite individual hashes with the new global browserHash, a full page reload is required
37195
- // New deps that ended up with a different hash replaced while doing analysis import are going to
37196
- // return a not found so the browser doesn't cache them. And will properly get loaded after the reload
37197
- for (const id in deps) {
37198
- metadata.optimized[id].browserHash = newBrowserHash;
37199
- }
37200
- }
37201
- // Write metadata file, delete `deps` folder and rename the new `processing` folder to `deps` in sync
37202
- commitProcessingDepsCacheSync();
37203
- processing.resolve();
37204
- },
37205
- cancel
37206
- };
37207
37165
  }
37166
+ const dataPath = path__default.join(processingCacheDir, '_metadata.json');
37167
+ writeFile(dataPath, stringifyOptimizedDepsMetadata(metadata, depsCacheDir));
37168
+ debug$c(`deps bundled in ${(perf_hooks.performance.now() - start).toFixed(2)}ms`);
37169
+ return {
37170
+ metadata,
37171
+ commit() {
37172
+ // Write metadata file, delete `deps` folder and rename the new `processing` folder to `deps` in sync
37173
+ commitProcessingDepsCacheSync();
37174
+ },
37175
+ cancel
37176
+ };
37208
37177
  function commitProcessingDepsCacheSync() {
37209
- // Rewire the file paths from the temporal processing dir to the final deps cache dir
37210
- const dataPath = path__default.join(processingCacheDir, '_metadata.json');
37211
- writeFile(dataPath, stringifyOptimizedDepsMetadata(metadata, depsCacheDir));
37212
37178
  // Processing is done, we can now replace the depsCacheDir with processingCacheDir
37179
+ // Rewire the file paths from the temporal processing dir to the final deps cache dir
37213
37180
  removeDirSync(depsCacheDir);
37214
37181
  fs__default.renameSync(processingCacheDir, depsCacheDir);
37215
37182
  }
37216
37183
  function cancel() {
37217
37184
  removeDirSync(processingCacheDir);
37218
- processing.resolve();
37219
37185
  }
37220
37186
  }
37221
37187
  function removeDirSync(dir) {
@@ -37262,27 +37228,12 @@ function newDepOptimizationProcessing() {
37262
37228
  function depsFromOptimizedDepInfo(depsInfo) {
37263
37229
  return Object.fromEntries(Object.entries(depsInfo).map((d) => [d[0], d[1].src]));
37264
37230
  }
37265
- function getHash(text) {
37266
- return require$$1$1.createHash('sha256').update(text).digest('hex').substring(0, 8);
37267
- }
37268
- function getOptimizedBrowserHash(hash, deps) {
37269
- return getHash(hash + JSON.stringify(deps));
37270
- }
37271
- function getCachedDepFilePath(id, depsCacheDir) {
37272
- return normalizePath$4(path__default.resolve(depsCacheDir, flattenId(id) + '.js'));
37273
- }
37274
37231
  function getOptimizedDepPath(id, config) {
37275
- return getCachedDepFilePath(id, getDepsCacheDir(config));
37232
+ return normalizePath$4(path__default.resolve(getDepsCacheDir(config), flattenId(id) + '.js'));
37276
37233
  }
37277
37234
  function getDepsCacheDir(config) {
37278
37235
  return normalizePath$4(path__default.resolve(config.cacheDir, 'deps'));
37279
37236
  }
37280
- function getProcessingDepFilePath(id, processingCacheDir) {
37281
- return normalizePath$4(path__default.resolve(processingCacheDir, flattenId(id) + '.js'));
37282
- }
37283
- function getProcessingDepPath(id, config) {
37284
- return getProcessingDepFilePath(id, getProcessingDepsCacheDir(config));
37285
- }
37286
37237
  function getProcessingDepsCacheDir(config) {
37287
37238
  return normalizePath$4(path__default.resolve(config.cacheDir, 'processing'));
37288
37239
  }
@@ -37306,7 +37257,7 @@ function createIsOptimizedDepUrl(config) {
37306
37257
  };
37307
37258
  }
37308
37259
  function parseOptimizedDepsMetadata(jsonMetadata, depsCacheDir) {
37309
- const metadata = JSON.parse(jsonMetadata, (key, value) => {
37260
+ const { hash, browserHash, optimized, chunks } = JSON.parse(jsonMetadata, (key, value) => {
37310
37261
  // Paths can be absolute or relative to the deps cache dir where
37311
37262
  // the _metadata.json is located
37312
37263
  if (key === 'file' || key === 'src') {
@@ -37314,18 +37265,34 @@ function parseOptimizedDepsMetadata(jsonMetadata, depsCacheDir) {
37314
37265
  }
37315
37266
  return value;
37316
37267
  });
37317
- const { browserHash } = metadata;
37318
- for (const o of Object.keys(metadata.optimized)) {
37319
- const depInfo = metadata.optimized[o];
37320
- depInfo.browserHash = browserHash;
37321
- }
37322
- metadata.chunks || (metadata.chunks = {}); // Support missing chunks for back compat
37323
- for (const o of Object.keys(metadata.chunks)) {
37324
- const depInfo = metadata.chunks[o];
37325
- depInfo.src = '';
37326
- depInfo.browserHash = browserHash;
37327
- }
37328
- metadata.discovered = {};
37268
+ if (!chunks ||
37269
+ Object.values(optimized).some((depInfo) => !depInfo.fileHash)) {
37270
+ // outdated _metadata.json version, ignore
37271
+ return;
37272
+ }
37273
+ const metadata = {
37274
+ hash,
37275
+ browserHash,
37276
+ optimized: {},
37277
+ discovered: {},
37278
+ chunks: {},
37279
+ depInfoList: []
37280
+ };
37281
+ for (const id of Object.keys(optimized)) {
37282
+ addOptimizedDepInfo(metadata, 'optimized', {
37283
+ ...optimized[id],
37284
+ id,
37285
+ browserHash
37286
+ });
37287
+ }
37288
+ for (const id of Object.keys(chunks)) {
37289
+ addOptimizedDepInfo(metadata, 'chunks', {
37290
+ ...chunks[id],
37291
+ id,
37292
+ browserHash,
37293
+ needsInterop: false
37294
+ });
37295
+ }
37329
37296
  return metadata;
37330
37297
  }
37331
37298
  /**
@@ -37335,44 +37302,38 @@ function parseOptimizedDepsMetadata(jsonMetadata, depsCacheDir) {
37335
37302
  * browserHash to allow long term caching
37336
37303
  */
37337
37304
  function stringifyOptimizedDepsMetadata(metadata, depsCacheDir) {
37338
- return JSON.stringify(metadata, (key, value) => {
37339
- if (key === 'discovered' || key === 'processing') {
37340
- return;
37341
- }
37305
+ const { hash, browserHash, optimized, chunks } = metadata;
37306
+ return JSON.stringify({
37307
+ hash,
37308
+ browserHash,
37309
+ optimized: Object.fromEntries(Object.values(optimized).map(({ id, src, file, fileHash, needsInterop }) => [
37310
+ id,
37311
+ {
37312
+ src,
37313
+ file,
37314
+ fileHash,
37315
+ needsInterop
37316
+ }
37317
+ ])),
37318
+ chunks: Object.fromEntries(Object.values(chunks).map(({ id, file }) => [id, { file }]))
37319
+ }, (key, value) => {
37320
+ // Paths can be absolute or relative to the deps cache dir where
37321
+ // the _metadata.json is located
37342
37322
  if (key === 'file' || key === 'src') {
37343
37323
  return normalizePath$4(path__default.relative(depsCacheDir, value));
37344
37324
  }
37345
- if (key === 'optimized') {
37346
- // Only remove browserHash for individual dep info
37347
- const cleaned = {};
37348
- for (const dep of Object.keys(value)) {
37349
- const { browserHash, ...c } = value[dep];
37350
- cleaned[dep] = c;
37351
- }
37352
- return cleaned;
37353
- }
37354
- if (key === 'optimized') {
37355
- return Object.keys(value).reduce((cleaned, dep) => {
37356
- const { browserHash, ...c } = value[dep];
37357
- cleaned[dep] = c;
37358
- return cleaned;
37359
- }, {});
37360
- }
37361
- if (key === 'chunks') {
37362
- return Object.keys(value).reduce((cleaned, dep) => {
37363
- const { browserHash, needsInterop, src, ...c } = value[dep];
37364
- cleaned[dep] = c;
37365
- return cleaned;
37366
- }, {});
37367
- }
37368
37325
  return value;
37369
37326
  }, 2);
37370
37327
  }
37328
+ function esbuildOutputFromId(outputs, id, cacheDirOutputPath) {
37329
+ const flatId = flattenId(id) + '.js';
37330
+ return outputs[normalizePath$4(path__default.relative(process.cwd(), path__default.join(cacheDirOutputPath, flatId)))];
37331
+ }
37371
37332
  // https://github.com/vitejs/vite/issues/1724#issuecomment-767619642
37372
37333
  // a list of modules that pretends to be ESM but still uses `require`.
37373
37334
  // this causes esbuild to wrap them as CJS even when its entry appears to be ESM.
37374
37335
  const KNOWN_INTEROP_IDS = new Set(['moment']);
37375
- function needsInterop(id, exportsData, outputs, cacheDirOutputPath) {
37336
+ function needsInterop(id, exportsData, output) {
37376
37337
  if (KNOWN_INTEROP_IDS.has(id)) {
37377
37338
  return true;
37378
37339
  }
@@ -37384,15 +37345,7 @@ function needsInterop(id, exportsData, outputs, cacheDirOutputPath) {
37384
37345
  // if a peer dependency used require() on a ESM dependency, esbuild turns the
37385
37346
  // ESM dependency's entry chunk into a single default export... detect
37386
37347
  // such cases by checking exports mismatch, and force interop.
37387
- const flatId = flattenId(id) + '.js';
37388
- let generatedExports;
37389
- for (const output in outputs) {
37390
- if (normalizePath$4(output) ===
37391
- normalizePath$4(path__default.join(cacheDirOutputPath, flatId))) {
37392
- generatedExports = outputs[output].exports;
37393
- break;
37394
- }
37395
- }
37348
+ const generatedExports = output.exports;
37396
37349
  if (!generatedExports ||
37397
37350
  (isSingleDefaultExport(generatedExports) && !isSingleDefaultExport(exports))) {
37398
37351
  return true;
@@ -37403,9 +37356,9 @@ function isSingleDefaultExport(exports) {
37403
37356
  return exports.length === 1 && exports[0] === 'default';
37404
37357
  }
37405
37358
  const lockfileFormats = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml'];
37406
- function getDepHash(root, config) {
37359
+ function getDepHash(config) {
37407
37360
  var _a, _b, _c, _d, _e, _f;
37408
- let content = lookupFile(root, lockfileFormats) || '';
37361
+ let content = lookupFile(config.root, lockfileFormats) || '';
37409
37362
  // also take config into account
37410
37363
  // only a subset of config options that can affect dep optimization
37411
37364
  content += JSON.stringify({
@@ -37430,23 +37383,30 @@ function getDepHash(root, config) {
37430
37383
  }
37431
37384
  return value;
37432
37385
  });
37433
- return require$$1$1.createHash('sha256').update(content).digest('hex').substring(0, 8);
37386
+ return getHash(content);
37434
37387
  }
37435
- function optimizeDepInfoFromFile(metadata, file) {
37436
- return (findFileInfo(metadata.optimized, file) ||
37437
- findFileInfo(metadata.discovered, file) ||
37438
- findFileInfo(metadata.chunks, file));
37388
+ function getOptimizedBrowserHash(hash, deps, timestamp = '') {
37389
+ return getHash(hash + JSON.stringify(deps) + timestamp);
37439
37390
  }
37440
- function findFileInfo(dependenciesInfo, file) {
37391
+ function getHash(text) {
37392
+ return require$$1$1.createHash('sha256').update(text).digest('hex').substring(0, 8);
37393
+ }
37394
+ function optimizedDepInfoFromId(metadata, id) {
37395
+ return (metadata.optimized[id] || metadata.discovered[id] || metadata.chunks[id]);
37396
+ }
37397
+ function optimizedDepInfoFromFile(metadata, file) {
37398
+ return metadata.depInfoList.find((depInfo) => depInfo.file === file);
37399
+ }
37400
+ function findOptimizedDepInfoInRecord(dependenciesInfo, callbackFn) {
37441
37401
  for (const o of Object.keys(dependenciesInfo)) {
37442
37402
  const info = dependenciesInfo[o];
37443
- if (info.file === file) {
37403
+ if (callbackFn(info, o)) {
37444
37404
  return info;
37445
37405
  }
37446
37406
  }
37447
37407
  }
37448
37408
  async function optimizedDepNeedsInterop(metadata, file) {
37449
- const depInfo = optimizeDepInfoFromFile(metadata, file);
37409
+ const depInfo = optimizedDepInfoFromFile(metadata, file);
37450
37410
  if (!depInfo)
37451
37411
  return undefined;
37452
37412
  // Wait until the dependency has been pre-bundled
@@ -37456,17 +37416,25 @@ async function optimizedDepNeedsInterop(metadata, file) {
37456
37416
 
37457
37417
  var index$1 = {
37458
37418
  __proto__: null,
37419
+ debuggerViteDeps: debuggerViteDeps,
37459
37420
  optimizeDeps: optimizeDeps,
37460
- createOptimizeDepsRun: createOptimizeDepsRun,
37421
+ createOptimizedDepsMetadata: createOptimizedDepsMetadata,
37422
+ addOptimizedDepInfo: addOptimizedDepInfo,
37423
+ loadCachedDepOptimizationMetadata: loadCachedDepOptimizationMetadata,
37424
+ discoverProjectDependencies: discoverProjectDependencies,
37425
+ depsLogString: depsLogString,
37426
+ runOptimizeDeps: runOptimizeDeps,
37461
37427
  findKnownImports: findKnownImports,
37462
37428
  newDepOptimizationProcessing: newDepOptimizationProcessing,
37463
37429
  depsFromOptimizedDepInfo: depsFromOptimizedDepInfo,
37464
- getHash: getHash,
37465
37430
  getOptimizedDepPath: getOptimizedDepPath,
37466
37431
  getDepsCacheDir: getDepsCacheDir,
37467
37432
  isOptimizedDepFile: isOptimizedDepFile,
37468
37433
  createIsOptimizedDepUrl: createIsOptimizedDepUrl,
37469
- optimizeDepInfoFromFile: optimizeDepInfoFromFile,
37434
+ getDepHash: getDepHash,
37435
+ getHash: getHash,
37436
+ optimizedDepInfoFromId: optimizedDepInfoFromId,
37437
+ optimizedDepInfoFromFile: optimizedDepInfoFromFile,
37470
37438
  optimizedDepNeedsInterop: optimizedDepNeedsInterop
37471
37439
  };
37472
37440
 
@@ -37720,8 +37688,8 @@ function resolvePlugin(baseOptions) {
37720
37688
  server = _server;
37721
37689
  isOptimizedDepUrl = createIsOptimizedDepUrl(server.config);
37722
37690
  },
37723
- resolveId(id, importer, resolveOpts) {
37724
- var _a, _b, _c, _d;
37691
+ async resolveId(id, importer, resolveOpts) {
37692
+ var _a, _b, _c, _d, _e;
37725
37693
  const ssr = (resolveOpts === null || resolveOpts === void 0 ? void 0 : resolveOpts.ssr) === true;
37726
37694
  if (id.startsWith(browserExternalId)) {
37727
37695
  return id;
@@ -37736,16 +37704,18 @@ function resolvePlugin(baseOptions) {
37736
37704
  const options = {
37737
37705
  isRequire,
37738
37706
  ...baseOptions,
37739
- isFromTsImporter: isTsRequest(importer !== null && importer !== void 0 ? importer : '')
37707
+ isFromTsImporter: isTsRequest(importer !== null && importer !== void 0 ? importer : ''),
37708
+ scan: (_d = resolveOpts === null || resolveOpts === void 0 ? void 0 : resolveOpts.scan) !== null && _d !== void 0 ? _d : baseOptions.scan
37740
37709
  };
37741
37710
  let res;
37742
37711
  // resolve pre-bundled deps requests, these could be resolved by
37743
37712
  // tryFileResolve or /fs/ resolution but these files may not yet
37744
37713
  // exists if we are in the middle of a deps re-processing
37745
37714
  if (asSrc && (isOptimizedDepUrl === null || isOptimizedDepUrl === void 0 ? void 0 : isOptimizedDepUrl(id))) {
37746
- return id.startsWith(FS_PREFIX)
37715
+ const optimizedPath = id.startsWith(FS_PREFIX)
37747
37716
  ? fsPathFromId(id)
37748
37717
  : normalizePath$4(ensureVolumeInPath(path__default.resolve(root, id.slice(1))));
37718
+ return optimizedPath;
37749
37719
  }
37750
37720
  // explicit fs paths that starts with /@fs/*
37751
37721
  if (asSrc && id.startsWith(FS_PREFIX)) {
@@ -37771,11 +37741,12 @@ function resolvePlugin(baseOptions) {
37771
37741
  const fsPath = path__default.resolve(basedir, id);
37772
37742
  // handle browser field mapping for relative imports
37773
37743
  const normalizedFsPath = normalizePath$4(fsPath);
37774
- if (server && isOptimizedDepFile(normalizedFsPath, server.config)) {
37744
+ if ((server === null || server === void 0 ? void 0 : server._optimizedDeps) &&
37745
+ isOptimizedDepFile(normalizedFsPath, server.config)) {
37775
37746
  // Optimized files could not yet exist in disk, resolve to the full path
37776
37747
  // Inject the current browserHash version if the path doesn't have one
37777
37748
  if (!normalizedFsPath.match(DEP_VERSION_RE)) {
37778
- const browserHash = (_d = optimizeDepInfoFromFile(server._optimizeDepsMetadata, normalizedFsPath)) === null || _d === void 0 ? void 0 : _d.browserHash;
37749
+ const browserHash = (_e = optimizedDepInfoFromFile(server._optimizedDeps.metadata, normalizedFsPath)) === null || _e === void 0 ? void 0 : _e.browserHash;
37779
37750
  if (browserHash) {
37780
37751
  return injectQuery(normalizedFsPath, `v=${browserHash}`);
37781
37752
  }
@@ -37832,7 +37803,8 @@ function resolvePlugin(baseOptions) {
37832
37803
  if (asSrc &&
37833
37804
  server &&
37834
37805
  !ssr &&
37835
- (res = tryOptimizedResolve(id, server, importer))) {
37806
+ !options.scan &&
37807
+ (res = await tryOptimizedResolve(id, server, importer))) {
37836
37808
  return res;
37837
37809
  }
37838
37810
  if (targetWeb &&
@@ -37967,7 +37939,7 @@ function tryResolveFile(file, postfix, options, tryIndex, targetWeb, tryPrefix,
37967
37939
  }
37968
37940
  const idToPkgMap = new Map();
37969
37941
  function tryNodeResolve(id, importer, options, targetWeb, server, ssr) {
37970
- var _a, _b;
37942
+ var _a;
37971
37943
  const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options;
37972
37944
  // split id by last '>' for nested selected packages, for example:
37973
37945
  // 'foo > bar > baz' => 'foo > bar' & 'baz'
@@ -38058,7 +38030,8 @@ function tryNodeResolve(id, importer, options, targetWeb, server, ssr) {
38058
38030
  else {
38059
38031
  if (!resolved.includes('node_modules') || // linked
38060
38032
  !server || // build
38061
- !server._registerMissingImport // initial esbuild scan phase
38033
+ !server._optimizedDeps || // resolving before listening to the server
38034
+ options.scan // initial esbuild scan phase
38062
38035
  ) {
38063
38036
  return { id: resolved };
38064
38037
  }
@@ -38076,7 +38049,7 @@ function tryNodeResolve(id, importer, options, targetWeb, server, ssr) {
38076
38049
  // can cache it without re-validation, but only do so for known js types.
38077
38050
  // otherwise we may introduce duplicated modules for externalized files
38078
38051
  // from pre-bundled deps.
38079
- const versionHash = (_b = server._optimizeDepsMetadata) === null || _b === void 0 ? void 0 : _b.browserHash;
38052
+ const versionHash = server._optimizedDeps.metadata.browserHash;
38080
38053
  if (versionHash && isJsType) {
38081
38054
  resolved = injectQuery(resolved, `v=${versionHash}`);
38082
38055
  }
@@ -38084,31 +38057,30 @@ function tryNodeResolve(id, importer, options, targetWeb, server, ssr) {
38084
38057
  else {
38085
38058
  // this is a missing import, queue optimize-deps re-run and
38086
38059
  // get a resolved its optimized info
38087
- const optimizedInfo = server._registerMissingImport(id, resolved, ssr);
38060
+ const optimizedInfo = server._optimizedDeps.registerMissingImport(id, resolved);
38088
38061
  resolved = getOptimizedUrl(optimizedInfo);
38089
38062
  }
38090
38063
  return { id: resolved };
38091
38064
  }
38092
38065
  }
38093
38066
  const getOptimizedUrl = (optimizedData) => `${optimizedData.file}?v=${optimizedData.browserHash}`;
38094
- function tryOptimizedResolve(id, server, importer) {
38095
- const depData = server._optimizeDepsMetadata;
38096
- if (!depData)
38067
+ async function tryOptimizedResolve(id, server, importer) {
38068
+ const optimizedDeps = server._optimizedDeps;
38069
+ if (!optimizedDeps)
38097
38070
  return;
38098
- // check if id has been optimized
38099
- const isOptimized = depData.optimized[id];
38100
- if (isOptimized) {
38101
- return getOptimizedUrl(isOptimized);
38102
- }
38103
- const isChunk = depData.chunks[id];
38104
- if (isChunk) {
38105
- return getOptimizedUrl(isChunk);
38071
+ await optimizedDeps.scanProcessing;
38072
+ const depInfo = optimizedDepInfoFromId(optimizedDeps.metadata, id);
38073
+ if (depInfo) {
38074
+ return getOptimizedUrl(depInfo);
38106
38075
  }
38107
38076
  if (!importer)
38108
38077
  return;
38109
38078
  // further check if id is imported by nested dependency
38110
38079
  let resolvedSrc;
38111
- for (const [pkgPath, optimizedData] of Object.entries(depData.optimized)) {
38080
+ for (const optimizedData of optimizedDeps.metadata.depInfoList) {
38081
+ if (!optimizedData.src)
38082
+ continue; // Ignore chunks
38083
+ const pkgPath = optimizedData.id;
38112
38084
  // check for scenarios, e.g.
38113
38085
  // pkgPath => "my-lib > foo"
38114
38086
  // id => "foo"
@@ -44841,7 +44813,7 @@ async function getCertificate(cacheDir) {
44841
44813
  return content;
44842
44814
  }
44843
44815
  catch {
44844
- const content = (await Promise.resolve().then(function () { return require('./dep-00d6c1ad.js'); })).createCertificate();
44816
+ const content = (await Promise.resolve().then(function () { return require('./dep-b2e77f82.js'); })).createCertificate();
44845
44817
  fs$n.promises
44846
44818
  .mkdir(cacheDir, { recursive: true })
44847
44819
  .then(() => fs$n.promises.writeFile(cachePath, content))
@@ -52866,8 +52838,9 @@ function optimizedDepsPlugin() {
52866
52838
  server = _server;
52867
52839
  },
52868
52840
  async load(id) {
52841
+ var _a, _b;
52869
52842
  if (server && isOptimizedDepFile(id, server.config)) {
52870
- const metadata = server === null || server === void 0 ? void 0 : server._optimizeDepsMetadata;
52843
+ const metadata = (_a = server === null || server === void 0 ? void 0 : server._optimizedDeps) === null || _a === void 0 ? void 0 : _a.metadata;
52871
52844
  if (metadata) {
52872
52845
  const file = cleanUrl(id);
52873
52846
  const versionMatch = id.match(DEP_VERSION_RE);
@@ -52875,7 +52848,7 @@ function optimizedDepsPlugin() {
52875
52848
  ? versionMatch[1].split('=')[1]
52876
52849
  : undefined;
52877
52850
  // Search in both the currently optimized and newly discovered deps
52878
- const info = optimizeDepInfoFromFile(metadata, file);
52851
+ const info = optimizedDepInfoFromFile(metadata, file);
52879
52852
  if (info) {
52880
52853
  if (browserHash && info.browserHash !== browserHash) {
52881
52854
  throwOutdatedRequest(id);
@@ -52891,9 +52864,9 @@ function optimizedDepsPlugin() {
52891
52864
  throwProcessingError(id);
52892
52865
  return;
52893
52866
  }
52894
- const newMetadata = server._optimizeDepsMetadata;
52867
+ const newMetadata = (_b = server._optimizedDeps) === null || _b === void 0 ? void 0 : _b.metadata;
52895
52868
  if (metadata !== newMetadata) {
52896
- const currentInfo = optimizeDepInfoFromFile(newMetadata, file);
52869
+ const currentInfo = optimizedDepInfoFromFile(newMetadata, file);
52897
52870
  if (info.browserHash !== (currentInfo === null || currentInfo === void 0 ? void 0 : currentInfo.browserHash)) {
52898
52871
  throwOutdatedRequest(id);
52899
52872
  }
@@ -55768,16 +55741,31 @@ function isPrimitive(value) {
55768
55741
  return !value || (typeof value !== 'object' && typeof value !== 'function');
55769
55742
  }
55770
55743
 
55744
+ const isDebugEnabled = _debug('vite:deps').enabled;
55771
55745
  /**
55772
55746
  * The amount to wait for requests to register newly found dependencies before triggering
55773
55747
  * a re-bundle + page reload
55774
55748
  */
55775
55749
  const debounceMs = 100;
55776
- function createMissingImporterRegisterFn(server, initialProcessingPromise) {
55777
- const { logger } = server.config;
55778
- let metadata = server._optimizeDepsMetadata;
55750
+ function createOptimizedDeps(server) {
55751
+ const { config } = server;
55752
+ const { logger } = config;
55753
+ const sessionTimestamp = Date.now().toString();
55754
+ const cachedMetadata = loadCachedDepOptimizationMetadata(config);
55755
+ const optimizedDeps = {
55756
+ metadata: cachedMetadata || createOptimizedDepsMetadata(config, sessionTimestamp),
55757
+ registerMissingImport
55758
+ };
55779
55759
  let handle;
55780
55760
  let newDepsDiscovered = false;
55761
+ let newDepsToLog = [];
55762
+ let newDepsToLogHandle;
55763
+ const logNewDeps = () => {
55764
+ config.logger.info(colors$1.green(`✨ dependencies optimized: ${depsLogString(newDepsToLog)}`), {
55765
+ timestamp: true
55766
+ });
55767
+ newDepsToLog = [];
55768
+ };
55781
55769
  let depOptimizationProcessing = newDepOptimizationProcessing();
55782
55770
  let depOptimizationProcessingQueue = [];
55783
55771
  const resolveEnqueuedProcessingPromises = () => {
@@ -55788,28 +55776,59 @@ function createMissingImporterRegisterFn(server, initialProcessingPromise) {
55788
55776
  depOptimizationProcessingQueue = [];
55789
55777
  };
55790
55778
  let enqueuedRerun;
55791
- let currentlyProcessing = true;
55792
- initialProcessingPromise.then(() => {
55793
- currentlyProcessing = false;
55794
- enqueuedRerun === null || enqueuedRerun === void 0 ? void 0 : enqueuedRerun();
55795
- });
55796
- async function rerun(ssr) {
55797
- // debounce time to wait for new missing deps finished, issue a new
55798
- // optimization of deps (both old and newly found) once the previous
55799
- // optimizeDeps processing is finished
55779
+ let currentlyProcessing = false;
55780
+ // If there wasn't a cache or it is outdated, perform a fast scan with esbuild
55781
+ // to quickly find project dependencies and do a first optimize run
55782
+ if (!cachedMetadata) {
55783
+ currentlyProcessing = true;
55784
+ const scanPhaseProcessing = newDepOptimizationProcessing();
55785
+ optimizedDeps.scanProcessing = scanPhaseProcessing.promise;
55786
+ const warmUp = async () => {
55787
+ try {
55788
+ debuggerViteDeps(colors$1.green(`scanning for dependencies...`), {
55789
+ timestamp: true
55790
+ });
55791
+ const { metadata } = optimizedDeps;
55792
+ const discovered = await discoverProjectDependencies(config, sessionTimestamp);
55793
+ // Respect the scan phase discover order to improve reproducibility
55794
+ for (const depInfo of Object.values(discovered)) {
55795
+ addOptimizedDepInfo(metadata, 'discovered', {
55796
+ ...depInfo,
55797
+ processing: depOptimizationProcessing.promise
55798
+ });
55799
+ }
55800
+ debuggerViteDeps(colors$1.green(`dependencies found: ${depsLogString(Object.keys(discovered))}`), {
55801
+ timestamp: true
55802
+ });
55803
+ scanPhaseProcessing.resolve();
55804
+ optimizedDeps.scanProcessing = undefined;
55805
+ runOptimizer();
55806
+ }
55807
+ catch (e) {
55808
+ logger.error(e.message);
55809
+ if (optimizedDeps.scanProcessing) {
55810
+ scanPhaseProcessing.resolve();
55811
+ optimizedDeps.scanProcessing = undefined;
55812
+ }
55813
+ }
55814
+ };
55815
+ setTimeout(warmUp, 0);
55816
+ }
55817
+ async function runOptimizer() {
55818
+ // Ensure that rerun is called sequentially
55819
+ enqueuedRerun = undefined;
55820
+ currentlyProcessing = true;
55821
+ // Ensure that a rerun will not be issued for current discovered deps
55822
+ if (handle)
55823
+ clearTimeout(handle);
55800
55824
  // a succesful completion of the optimizeDeps rerun will end up
55801
55825
  // creating new bundled version of all current and discovered deps
55802
55826
  // in the cache dir and a new metadata info object assigned
55803
- // to server._optimizeDepsMetadata. A fullReload is only issued if
55827
+ // to optimizeDeps.metadata. A fullReload is only issued if
55804
55828
  // the previous bundled dependencies have changed.
55805
- // if the rerun fails, server._optimizeDepsMetadata remains untouched,
55829
+ // if the rerun fails, optimizeDeps.metadata remains untouched,
55806
55830
  // current discovered deps are cleaned, and a fullReload is issued
55807
- // Ensure that rerun is called sequentially
55808
- enqueuedRerun = undefined;
55809
- currentlyProcessing = true;
55810
- logger.info(colors$1.yellow(`new dependencies found: ${Object.keys(metadata.discovered).join(', ')}, updating...`), {
55811
- timestamp: true
55812
- });
55831
+ let { metadata } = optimizedDeps;
55813
55832
  // All deps, previous known and newly discovered are rebundled,
55814
55833
  // respect insertion order to keep the metadata file stable
55815
55834
  const newDeps = {};
@@ -55817,9 +55836,10 @@ function createMissingImporterRegisterFn(server, initialProcessingPromise) {
55817
55836
  for (const dep of Object.keys(metadata.optimized)) {
55818
55837
  newDeps[dep] = { ...metadata.optimized[dep] };
55819
55838
  }
55820
- // Don't clone discovered info objects, they are read after awaited
55821
55839
  for (const dep of Object.keys(metadata.discovered)) {
55822
- newDeps[dep] = metadata.discovered[dep];
55840
+ // Clone the discovered info discarding its processing promise
55841
+ const { processing, ...info } = metadata.discovered[dep];
55842
+ newDeps[dep] = info;
55823
55843
  }
55824
55844
  newDepsDiscovered = false;
55825
55845
  // Add the current depOptimizationProcessing to the queue, these
@@ -55828,32 +55848,69 @@ function createMissingImporterRegisterFn(server, initialProcessingPromise) {
55828
55848
  // Create a new promise for the next rerun, discovered missing
55829
55849
  // dependencies will be asigned this promise from this point
55830
55850
  depOptimizationProcessing = newDepOptimizationProcessing();
55831
- let newData = null;
55832
55851
  try {
55833
- const optimizeDeps = await createOptimizeDepsRun(server.config, true, false, metadata, newDeps, ssr);
55834
- const processingResult = await optimizeDeps.run();
55852
+ const processingResult = await runOptimizeDeps(config, newDeps);
55853
+ const newData = processingResult.metadata;
55854
+ // After a re-optimization, if the internal bundled chunks change a full page reload
55855
+ // is required. If the files are stable, we can avoid the reload that is expensive
55856
+ // for large applications. Comparing their fileHash we can find out if it is safe to
55857
+ // keep the current browser state.
55858
+ const needsReload = metadata.hash !== newData.hash ||
55859
+ Object.keys(metadata.optimized).some((dep) => {
55860
+ return (metadata.optimized[dep].fileHash !== newData.optimized[dep].fileHash);
55861
+ });
55835
55862
  const commitProcessing = () => {
55836
55863
  processingResult.commit();
55837
- newData = optimizeDeps.metadata;
55838
- // update ssr externals
55839
- if (ssr) {
55840
- server._ssrExternals = resolveSSRExternal(server.config, Object.keys(newData.optimized));
55841
- }
55842
55864
  // While optimizeDeps is running, new missing deps may be discovered,
55843
55865
  // in which case they will keep being added to metadata.discovered
55844
- for (const o of Object.keys(metadata.discovered)) {
55845
- if (!newData.optimized[o]) {
55846
- newData.discovered[o] = metadata.discovered[o];
55866
+ for (const id in metadata.discovered) {
55867
+ if (!newData.optimized[id]) {
55868
+ addOptimizedDepInfo(newData, 'discovered', metadata.discovered[id]);
55847
55869
  }
55848
55870
  }
55849
- metadata = server._optimizeDepsMetadata = newData;
55871
+ // If we don't reload the page, we need to keep browserHash stable
55872
+ if (!needsReload) {
55873
+ newData.browserHash = metadata.browserHash;
55874
+ for (const dep in newData.chunks) {
55875
+ newData.chunks[dep].browserHash = metadata.browserHash;
55876
+ }
55877
+ for (const dep in newData.optimized) {
55878
+ newData.optimized[dep].browserHash = (metadata.optimized[dep] || metadata.discovered[dep]).browserHash;
55879
+ }
55880
+ }
55881
+ // Commit hash and needsInterop changes to the discovered deps info
55882
+ // object. Allow for code to await for the discovered processing promise
55883
+ // and use the information in the same object
55884
+ for (const o in newData.optimized) {
55885
+ const discovered = metadata.discovered[o];
55886
+ if (discovered) {
55887
+ const optimized = newData.optimized[o];
55888
+ discovered.browserHash = optimized.browserHash;
55889
+ discovered.fileHash = optimized.fileHash;
55890
+ discovered.needsInterop = optimized.needsInterop;
55891
+ discovered.processing = undefined;
55892
+ }
55893
+ }
55894
+ newDepsToLog.push(...Object.keys(newData.optimized).filter((dep) => !metadata.optimized[dep]));
55895
+ metadata = optimizedDeps.metadata = newData;
55850
55896
  resolveEnqueuedProcessingPromises();
55851
55897
  };
55852
- if (!processingResult.alteredFiles) {
55898
+ if (!needsReload) {
55853
55899
  commitProcessing();
55854
- logger.info(colors$1.green(`✨ new dependencies pre-bundled...`), {
55855
- timestamp: true
55856
- });
55900
+ if (isDebugEnabled) {
55901
+ logNewDeps();
55902
+ debuggerViteDeps(colors$1.green(`✨ previous optimized dependencies unchanged`), {
55903
+ timestamp: true
55904
+ });
55905
+ }
55906
+ else {
55907
+ if (newDepsToLogHandle)
55908
+ clearTimeout(newDepsToLogHandle);
55909
+ newDepsToLogHandle = setTimeout(() => {
55910
+ newDepsToLogHandle = undefined;
55911
+ logNewDeps();
55912
+ }, 2 * debounceMs);
55913
+ }
55857
55914
  }
55858
55915
  else {
55859
55916
  if (newDepsDiscovered) {
@@ -55862,13 +55919,17 @@ function createMissingImporterRegisterFn(server, initialProcessingPromise) {
55862
55919
  // We don't resolve the processing promise, as they will be resolved
55863
55920
  // once a rerun is committed
55864
55921
  processingResult.cancel();
55865
- logger.info(colors$1.green(`✨ delaying reload as new dependencies have been found...`), {
55922
+ debuggerViteDeps(colors$1.green(`✨ delaying reload as new dependencies have been found...`), {
55866
55923
  timestamp: true
55867
55924
  });
55868
55925
  }
55869
55926
  else {
55870
55927
  commitProcessing();
55871
- logger.info(colors$1.green(`✨ dependencies updated, reloading page...`), {
55928
+ if (newDepsToLogHandle)
55929
+ clearTimeout(newDepsToLogHandle);
55930
+ newDepsToLogHandle = undefined;
55931
+ logNewDeps();
55932
+ logger.info(colors$1.green(`✨ previous optimized dependencies have changed, reloading page`), {
55872
55933
  timestamp: true
55873
55934
  });
55874
55935
  fullReload();
@@ -55896,14 +55957,25 @@ function createMissingImporterRegisterFn(server, initialProcessingPromise) {
55896
55957
  path: '*'
55897
55958
  });
55898
55959
  }
55899
- const discoveredTimestamp = Date.now();
55960
+ async function rerun() {
55961
+ // debounce time to wait for new missing deps finished, issue a new
55962
+ // optimization of deps (both old and newly found) once the previous
55963
+ // optimizeDeps processing is finished
55964
+ const deps = Object.keys(optimizedDeps.metadata.discovered);
55965
+ const depsString = depsLogString(deps);
55966
+ debuggerViteDeps(colors$1.green(`new dependencies found: ${depsString}`), {
55967
+ timestamp: true
55968
+ });
55969
+ runOptimizer();
55970
+ }
55900
55971
  function getDiscoveredBrowserHash(hash, deps, missing) {
55901
- return getHash(hash +
55902
- JSON.stringify(deps) +
55903
- JSON.stringify(missing) +
55904
- discoveredTimestamp);
55972
+ return getHash(hash + JSON.stringify(deps) + JSON.stringify(missing) + sessionTimestamp);
55905
55973
  }
55906
- return function registerMissingImport(id, resolved, ssr) {
55974
+ function registerMissingImport(id, resolved, ssr) {
55975
+ if (optimizedDeps.scanProcessing) {
55976
+ config.logger.error('Vite internal error: registering missing import before initial scanning is over');
55977
+ }
55978
+ const { metadata } = optimizedDeps;
55907
55979
  const optimized = metadata.optimized[id];
55908
55980
  if (optimized) {
55909
55981
  return optimized;
@@ -55919,7 +55991,8 @@ function createMissingImporterRegisterFn(server, initialProcessingPromise) {
55919
55991
  return missing;
55920
55992
  }
55921
55993
  newDepsDiscovered = true;
55922
- missing = metadata.discovered[id] = {
55994
+ missing = addOptimizedDepInfo(metadata, 'discovered', {
55995
+ id,
55923
55996
  file: getOptimizedDepPath(id, server.config),
55924
55997
  src: resolved,
55925
55998
  // Assing a browserHash to this missing dependency that is unique to
@@ -55930,15 +56003,18 @@ function createMissingImporterRegisterFn(server, initialProcessingPromise) {
55930
56003
  // loading of this pre-bundled dep needs to await for its processing
55931
56004
  // promise to be resolved
55932
56005
  processing: depOptimizationProcessing.promise
55933
- };
56006
+ });
55934
56007
  // Debounced rerun, let other missing dependencies be discovered before
55935
56008
  // the running next optimizeDeps
55936
56009
  enqueuedRerun = undefined;
55937
56010
  if (handle)
55938
56011
  clearTimeout(handle);
56012
+ if (newDepsToLogHandle)
56013
+ clearTimeout(newDepsToLogHandle);
56014
+ newDepsToLogHandle = undefined;
55939
56015
  handle = setTimeout(() => {
55940
56016
  handle = undefined;
55941
- enqueuedRerun = () => rerun(ssr);
56017
+ enqueuedRerun = rerun;
55942
56018
  if (!currentlyProcessing) {
55943
56019
  enqueuedRerun();
55944
56020
  }
@@ -55946,7 +56022,8 @@ function createMissingImporterRegisterFn(server, initialProcessingPromise) {
55946
56022
  // Return the path for the optimized bundle, this path is known before
55947
56023
  // esbuild is run to generate the pre-bundle
55948
56024
  return missing;
55949
- };
56025
+ }
56026
+ return optimizedDeps;
55950
56027
  }
55951
56028
 
55952
56029
  // https://github.com/vitejs/vite/issues/2820#issuecomment-812495079
@@ -56056,12 +56133,18 @@ async function createServer(inlineConfig = {}) {
56056
56133
  },
56057
56134
  transformIndexHtml: null,
56058
56135
  async ssrLoadModule(url, opts) {
56059
- let configFileDependencies = [];
56060
- const metadata = server._optimizeDepsMetadata;
56061
- if (metadata) {
56062
- configFileDependencies = Object.keys(metadata.optimized);
56136
+ if (!server._ssrExternals) {
56137
+ let knownImports = [];
56138
+ const optimizedDeps = server._optimizedDeps;
56139
+ if (optimizedDeps) {
56140
+ await optimizedDeps.scanProcessing;
56141
+ knownImports = [
56142
+ ...Object.keys(optimizedDeps.metadata.optimized),
56143
+ ...Object.keys(optimizedDeps.metadata.discovered)
56144
+ ];
56145
+ }
56146
+ server._ssrExternals = resolveSSRExternal(config, knownImports);
56063
56147
  }
56064
- server._ssrExternals || (server._ssrExternals = resolveSSRExternal(config, configFileDependencies));
56065
56148
  return ssrLoadModule(url, server, undefined, undefined, opts === null || opts === void 0 ? void 0 : opts.fixStacktrace);
56066
56149
  },
56067
56150
  ssrFixStacktrace(e) {
@@ -56106,12 +56189,11 @@ async function createServer(inlineConfig = {}) {
56106
56189
  }
56107
56190
  return server._restartPromise;
56108
56191
  },
56109
- _optimizeDepsMetadata: null,
56192
+ _optimizedDeps: null,
56110
56193
  _ssrExternals: null,
56111
56194
  _globImporters: Object.create(null),
56112
56195
  _restartPromise: null,
56113
56196
  _forceOptimizeOnRestart: false,
56114
- _registerMissingImport: null,
56115
56197
  _pendingRequests: new Map()
56116
56198
  };
56117
56199
  server.transformIndexHtml = createDevHtmlTransformFn(server);
@@ -56230,29 +56312,15 @@ async function createServer(inlineConfig = {}) {
56230
56312
  }
56231
56313
  // error handler
56232
56314
  middlewares.use(errorMiddleware(server, !!middlewareMode));
56233
- const runOptimize = async () => {
56234
- const optimizeDeps = await createOptimizeDepsRun(config, config.server.force);
56235
- // Don't await for the optimization to finish, we can start the
56236
- // server right away here
56237
- server._optimizeDepsMetadata = optimizeDeps.metadata;
56238
- // Run deps optimization in parallel
56239
- const initialProcessingPromise = optimizeDeps
56240
- .run()
56241
- .then((result) => result.commit());
56242
- // While running the first optimizeDeps, _registerMissingImport is null
56243
- // so the resolve plugin resolves straight to node_modules during the
56244
- // deps discovery scan phase
56245
- server._registerMissingImport = createMissingImporterRegisterFn(server, initialProcessingPromise);
56246
- };
56247
56315
  if (!middlewareMode && httpServer) {
56248
56316
  let isOptimized = false;
56249
- // overwrite listen to run optimizer before server start
56317
+ // overwrite listen to init optimizer before server start
56250
56318
  const listen = httpServer.listen.bind(httpServer);
56251
56319
  httpServer.listen = (async (port, ...args) => {
56252
56320
  if (!isOptimized) {
56253
56321
  try {
56254
56322
  await container.buildStart({});
56255
- await runOptimize();
56323
+ server._optimizedDeps = createOptimizedDeps(server);
56256
56324
  isOptimized = true;
56257
56325
  }
56258
56326
  catch (e) {
@@ -56265,7 +56333,7 @@ async function createServer(inlineConfig = {}) {
56265
56333
  }
56266
56334
  else {
56267
56335
  await container.buildStart({});
56268
- await runOptimize();
56336
+ server._optimizedDeps = createOptimizedDeps(server);
56269
56337
  }
56270
56338
  return server;
56271
56339
  }
@@ -56847,15 +56915,20 @@ function importAnalysisPlugin(config) {
56847
56915
  url = url.replace(base, '/');
56848
56916
  }
56849
56917
  let importerFile = importer;
56850
- if (moduleListContains((_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.exclude, url) &&
56851
- server._optimizeDepsMetadata) {
56852
- // if the dependency encountered in the optimized file was excluded from the optimization
56853
- // the dependency needs to be resolved starting from the original source location of the optimized file
56854
- // because starting from node_modules/.vite will not find the dependency if it was not hoisted
56855
- // (that is, if it is under node_modules directory in the package source of the optimized file)
56856
- for (const optimizedModule of Object.values(server._optimizeDepsMetadata.optimized)) {
56857
- if (optimizedModule.file === importerModule.file) {
56858
- importerFile = optimizedModule.src;
56918
+ if (moduleListContains((_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.exclude, url)) {
56919
+ const optimizedDeps = server._optimizedDeps;
56920
+ if (optimizedDeps) {
56921
+ await optimizedDeps.scanProcessing;
56922
+ // if the dependency encountered in the optimized file was excluded from the optimization
56923
+ // the dependency needs to be resolved starting from the original source location of the optimized file
56924
+ // because starting from node_modules/.vite will not find the dependency if it was not hoisted
56925
+ // (that is, if it is under node_modules directory in the package source of the optimized file)
56926
+ for (const optimizedModule of optimizedDeps.metadata.depInfoList) {
56927
+ if (!optimizedModule.src)
56928
+ continue; // Ignore chunks
56929
+ if (optimizedModule.file === importerModule.file) {
56930
+ importerFile = optimizedModule.src;
56931
+ }
56859
56932
  }
56860
56933
  }
56861
56934
  }
@@ -57021,14 +57094,15 @@ function importAnalysisPlugin(config) {
57021
57094
  if (url !== specifier) {
57022
57095
  importRewrites.push(async () => {
57023
57096
  let rewriteDone = false;
57024
- if (isOptimizedDepFile(resolvedId, config) &&
57097
+ if ((server === null || server === void 0 ? void 0 : server._optimizedDeps) &&
57098
+ isOptimizedDepFile(resolvedId, config) &&
57025
57099
  !resolvedId.match(optimizedDepChunkRE)) {
57026
57100
  // for optimized cjs deps, support named imports by rewriting named imports to const assignments.
57027
57101
  // internal optimized chunks don't need es interop and are excluded
57028
57102
  // The browserHash in resolvedId could be stale in which case there will be a full
57029
57103
  // page reload. We could return a 404 in that case but it is safe to return the request
57030
57104
  const file = cleanUrl(resolvedId); // Remove ?v={hash}
57031
- const needsInterop = await optimizedDepNeedsInterop(server._optimizeDepsMetadata, file);
57105
+ const needsInterop = await optimizedDepNeedsInterop(server._optimizedDeps.metadata, file);
57032
57106
  if (needsInterop === undefined) {
57033
57107
  // Non-entry dynamic imports from dependencies will reach here as there isn't
57034
57108
  // optimize info for them, but they don't need es interop. If the request isn't
@@ -57531,9 +57605,9 @@ function preAliasPlugin() {
57531
57605
  configureServer(_server) {
57532
57606
  server = _server;
57533
57607
  },
57534
- resolveId(id, importer, options) {
57535
- if (!(options === null || options === void 0 ? void 0 : options.ssr) && bareImportRE.test(id)) {
57536
- return tryOptimizedResolve(id, server, importer);
57608
+ async resolveId(id, importer, options) {
57609
+ if (!(options === null || options === void 0 ? void 0 : options.ssr) && bareImportRE.test(id) && !(options === null || options === void 0 ? void 0 : options.scan)) {
57610
+ return await tryOptimizedResolve(id, server, importer);
57537
57611
  }
57538
57612
  }
57539
57613
  };