vite 3.0.0-beta.7 → 3.0.0

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.
@@ -22,7 +22,7 @@ import { createHash as createHash$2 } from 'node:crypto';
22
22
  import { promisify as promisify$4 } from 'node:util';
23
23
  import { promises } from 'node:dns';
24
24
  import resolve$5 from 'resolve';
25
- import { CLIENT_ENTRY, DEFAULT_EXTENSIONS as DEFAULT_EXTENSIONS$1, OPTIMIZABLE_ENTRY_RE, VALID_ID_PREFIX, FS_PREFIX, wildcardHosts, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH, loopbackHosts, DEFAULT_MAIN_FIELDS, DEP_VERSION_RE, SPECIAL_QUERY_RE, KNOWN_ASSET_TYPES, JS_TYPES_RE, ESBUILD_MODULES_TARGET, CLIENT_DIR, NULL_BYTE_PLACEHOLDER, VERSION, VITE_PACKAGE_DIR, ENV_ENTRY, DEFAULT_ASSETS_RE, DEFAULT_CONFIG_FILES } from '../constants.js';
25
+ import { CLIENT_ENTRY, DEFAULT_EXTENSIONS as DEFAULT_EXTENSIONS$1, OPTIMIZABLE_ENTRY_RE, VALID_ID_PREFIX, FS_PREFIX, wildcardHosts, loopbackHosts, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH, DEFAULT_MAIN_FIELDS, DEP_VERSION_RE, SPECIAL_QUERY_RE, KNOWN_ASSET_TYPES, JS_TYPES_RE, ESBUILD_MODULES_TARGET, CLIENT_DIR, NULL_BYTE_PLACEHOLDER, VERSION, VITE_PACKAGE_DIR, ENV_ENTRY, DEFAULT_ASSETS_RE, DEFAULT_CONFIG_FILES } from '../constants.js';
26
26
  import require$$5 from 'crypto';
27
27
  import require$$0$a from 'buffer';
28
28
  import require$$0$8, { createRequire as createRequire$2 } from 'module';
@@ -12172,7 +12172,49 @@ async function resolveHostname(optionsHost) {
12172
12172
  name = localhostAddr;
12173
12173
  }
12174
12174
  }
12175
- return { host, name, implicit: optionsHost === undefined };
12175
+ return { host, name };
12176
+ }
12177
+ async function resolveServerUrls(server, options, config) {
12178
+ const address = server.address();
12179
+ const isAddressInfo = (x) => x?.address;
12180
+ if (!isAddressInfo(address)) {
12181
+ return { local: [], network: [] };
12182
+ }
12183
+ const local = [];
12184
+ const network = [];
12185
+ const hostname = await resolveHostname(options.host);
12186
+ const protocol = options.https ? 'https' : 'http';
12187
+ const port = address.port;
12188
+ const base = config.base === './' || config.base === '' ? '/' : config.base;
12189
+ if (hostname.host && loopbackHosts.has(hostname.host)) {
12190
+ let hostnameName = hostname.name;
12191
+ if (hostnameName === '::1' ||
12192
+ hostnameName === '0000:0000:0000:0000:0000:0000:0000:0001') {
12193
+ hostnameName = `[${hostnameName}]`;
12194
+ }
12195
+ local.push(`${protocol}://${hostnameName}:${port}${base}`);
12196
+ }
12197
+ else {
12198
+ Object.values(os$3.networkInterfaces())
12199
+ .flatMap((nInterface) => nInterface ?? [])
12200
+ .filter((detail) => detail &&
12201
+ detail.address &&
12202
+ // Node < v18
12203
+ ((typeof detail.family === 'string' && detail.family === 'IPv4') ||
12204
+ // Node >= v18
12205
+ (typeof detail.family === 'number' && detail.family === 4)))
12206
+ .forEach((detail) => {
12207
+ const host = detail.address.replace('127.0.0.1', hostname.name);
12208
+ const url = `${protocol}://${host}:${port}${base}`;
12209
+ if (detail.address.includes('127.0.0.1')) {
12210
+ local.push(url);
12211
+ }
12212
+ else {
12213
+ network.push(url);
12214
+ }
12215
+ });
12216
+ }
12217
+ return { local, network };
12176
12218
  }
12177
12219
  function arraify(target) {
12178
12220
  return Array.isArray(target) ? target : [target];
@@ -12491,64 +12533,18 @@ function createLogger(level = 'info', options = {}) {
12491
12533
  };
12492
12534
  return logger;
12493
12535
  }
12494
- async function printCommonServerUrls(server, options, config) {
12495
- const address = server.address();
12496
- const isAddressInfo = (x) => x?.address;
12497
- if (isAddressInfo(address)) {
12498
- const hostname = await resolveHostname(options.host);
12499
- const protocol = options.https ? 'https' : 'http';
12500
- const base = config.base === './' || config.base === '' ? '/' : config.base;
12501
- printServerUrls(hostname, protocol, address.port, base, config.logger.info);
12536
+ function printServerUrls(urls, optionsHost, info) {
12537
+ const colorUrl = (url) => picocolors.exports.cyan(url.replace(/:(\d+)\//, (_, port) => `:${picocolors.exports.bold(port)}/`));
12538
+ for (const url of urls.local) {
12539
+ info(` ${picocolors.exports.green('➜')} ${picocolors.exports.bold('Local')}: ${colorUrl(url)}`);
12502
12540
  }
12503
- }
12504
- function printServerUrls(hostname, protocol, port, base, info) {
12505
- const urls = [];
12506
- const notes = [];
12507
- if (hostname.host && loopbackHosts.has(hostname.host)) {
12508
- let hostnameName = hostname.name;
12509
- if (hostnameName === '::1' ||
12510
- hostnameName === '0000:0000:0000:0000:0000:0000:0000:0001') {
12511
- hostnameName = `[${hostnameName}]`;
12512
- }
12513
- urls.push({
12514
- label: 'Local',
12515
- url: picocolors.exports.cyan(`${protocol}://${hostnameName}:${picocolors.exports.bold(port)}${base}`)
12516
- });
12517
- if (hostname.implicit) {
12518
- urls.push({
12519
- label: 'Network',
12520
- url: `use ${picocolors.exports.white(picocolors.exports.bold('--host'))} to expose`,
12521
- disabled: true
12522
- });
12523
- }
12541
+ for (const url of urls.network) {
12542
+ info(` ${picocolors.exports.green('➜')} ${picocolors.exports.bold('Network')}: ${colorUrl(url)}`);
12524
12543
  }
12525
- else {
12526
- Object.values(os$3.networkInterfaces())
12527
- .flatMap((nInterface) => nInterface ?? [])
12528
- .filter((detail) => detail &&
12529
- detail.address &&
12530
- // Node < v18
12531
- ((typeof detail.family === 'string' && detail.family === 'IPv4') ||
12532
- // Node >= v18
12533
- (typeof detail.family === 'number' && detail.family === 4)))
12534
- .forEach((detail) => {
12535
- const host = detail.address.replace('127.0.0.1', hostname.name);
12536
- const url = `${protocol}://${host}:${picocolors.exports.bold(port)}${base}`;
12537
- const label = detail.address.includes('127.0.0.1') ? 'Local' : 'Network';
12538
- urls.push({ label, url: picocolors.exports.cyan(url) });
12539
- });
12544
+ if (urls.network.length === 0 && optionsHost === undefined) {
12545
+ const note = `use ${picocolors.exports.white(picocolors.exports.bold('--host'))} to expose`;
12546
+ info(picocolors.exports.dim(` ${picocolors.exports.green('➜')} ${picocolors.exports.bold('Network')}: ${note}`));
12540
12547
  }
12541
- const length = Math.max(...[...urls, ...notes].map(({ label }) => label.length));
12542
- const print = (iconWithColor, label, messageWithColor, disabled) => {
12543
- const message = ` ${iconWithColor} ${label ? picocolors.exports.bold(label) + ':' : ' '} ${' '.repeat(length - label.length)}${messageWithColor}`;
12544
- info(disabled ? picocolors.exports.dim(message) : message);
12545
- };
12546
- urls.forEach(({ label, url: text, disabled }) => {
12547
- print(picocolors.exports.green('➜'), label, text, disabled);
12548
- });
12549
- notes.forEach(({ label, message: text }) => {
12550
- print(picocolors.exports.white('❖'), label, text);
12551
- });
12552
12548
  }
12553
12549
 
12554
12550
  const writeColors = {
@@ -33823,7 +33819,8 @@ function resolvePlugin(resolveOptions) {
33823
33819
  scan: resolveOpts?.scan ?? resolveOptions.scan
33824
33820
  };
33825
33821
  if (importer) {
33826
- if (isTsRequest(importer)) {
33822
+ if (isTsRequest(importer) ||
33823
+ resolveOpts.custom?.depScan?.loader?.startsWith('ts')) {
33827
33824
  options.isFromTsImporter = true;
33828
33825
  }
33829
33826
  else {
@@ -34950,6 +34947,8 @@ async function createPluginContainer({ plugins, logger, root, build: { rollupOpt
34950
34947
  skip.add(this._activePlugin);
34951
34948
  }
34952
34949
  let out = await container.resolveId(id, importer, {
34950
+ custom: options?.custom,
34951
+ isEntry: !!options?.isEntry,
34953
34952
  skip,
34954
34953
  ssr: this.ssr,
34955
34954
  scan: this._scan
@@ -35168,7 +35167,6 @@ async function createPluginContainer({ plugins, logger, root, build: { rollupOpt
35168
35167
  const skip = options?.skip;
35169
35168
  const ssr = options?.ssr;
35170
35169
  const scan = !!options?.scan;
35171
- const isEntry = !!options?.isEntry;
35172
35170
  const ctx = new Context();
35173
35171
  ctx.ssr = !!ssr;
35174
35172
  ctx._scan = scan;
@@ -35183,7 +35181,12 @@ async function createPluginContainer({ plugins, logger, root, build: { rollupOpt
35183
35181
  continue;
35184
35182
  ctx._activePlugin = plugin;
35185
35183
  const pluginResolveStart = isDebug ? performance.now() : 0;
35186
- const result = await plugin.resolveId.call(ctx, rawId, importer, { ssr, scan, isEntry });
35184
+ const result = await plugin.resolveId.call(ctx, rawId, importer, {
35185
+ custom: options?.custom,
35186
+ isEntry: !!options?.isEntry,
35187
+ ssr,
35188
+ scan
35189
+ });
35187
35190
  if (!result)
35188
35191
  continue;
35189
35192
  if (typeof result === 'string') {
@@ -35788,12 +35791,13 @@ const langRE = /\blang\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/im;
35788
35791
  const contextRE = /\bcontext\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/im;
35789
35792
  function esbuildScanPlugin(config, container, depImports, missing, entries) {
35790
35793
  const seen = new Map();
35791
- const resolve = async (id, importer) => {
35794
+ const resolve = async (id, importer, options) => {
35792
35795
  const key = id + (importer && path$n.dirname(importer));
35793
35796
  if (seen.has(key)) {
35794
35797
  return seen.get(key);
35795
35798
  }
35796
35799
  const resolved = await container.resolveId(id, importer && normalizePath$3(importer), {
35800
+ ...options,
35797
35801
  scan: true
35798
35802
  });
35799
35803
  const res = resolved?.id;
@@ -35910,13 +35914,19 @@ function esbuildScanPlugin(config, container, depImports, missing, entries) {
35910
35914
  }
35911
35915
  scripts[key] = {
35912
35916
  loader: 'js',
35913
- contents: (await transformGlobImport(transpiledContents, path, config.root, resolve))?.s.toString() || transpiledContents
35917
+ contents: (await transformGlobImport(transpiledContents, path, config.root, resolve))?.s.toString() || transpiledContents,
35918
+ pluginData: {
35919
+ htmlType: { loader }
35920
+ }
35914
35921
  };
35915
35922
  }
35916
35923
  else {
35917
35924
  scripts[key] = {
35918
35925
  loader,
35919
- contents
35926
+ contents,
35927
+ pluginData: {
35928
+ htmlType: { loader }
35929
+ }
35920
35930
  };
35921
35931
  }
35922
35932
  const virtualModulePath = JSON.stringify(virtualModulePrefix + key);
@@ -36006,9 +36016,13 @@ function esbuildScanPlugin(config, container, depImports, missing, entries) {
36006
36016
  // catch all -------------------------------------------------------------
36007
36017
  build.onResolve({
36008
36018
  filter: /.*/
36009
- }, async ({ path: id, importer }) => {
36019
+ }, async ({ path: id, importer, pluginData }) => {
36010
36020
  // use vite resolver to support urls and omitted extensions
36011
- const resolved = await resolve(id, importer);
36021
+ const resolved = await resolve(id, importer, {
36022
+ custom: {
36023
+ depScan: { loader: pluginData?.htmlType?.loader }
36024
+ }
36025
+ });
36012
36026
  if (resolved) {
36013
36027
  if (shouldExternalizeDep(resolved, id) || !isScannable(resolved)) {
36014
36028
  return externalUnlessEntry({ path: id });
@@ -36189,41 +36203,41 @@ async function createDepsOptimizer(config, server) {
36189
36203
  }
36190
36204
  if (!isBuild) {
36191
36205
  // Important, the scanner is dev only
36192
- runScanner();
36193
- }
36194
- }
36195
- async function runScanner() {
36196
- const scanPhaseProcessing = newDepOptimizationProcessing();
36197
- depsOptimizer.scanProcessing = scanPhaseProcessing.promise;
36198
- try {
36199
- debuggerViteDeps(picocolors.exports.green(`scanning for dependencies...`));
36200
- const deps = await discoverProjectDependencies(config);
36201
- debuggerViteDeps(picocolors.exports.green(Object.keys(deps).length > 0
36202
- ? `dependencies found by scanner: ${depsLogString(Object.keys(deps))}`
36203
- : `no dependencies found by scanner`));
36204
- // Add these dependencies to the discovered list, as these are currently
36205
- // used by the preAliasPlugin to support aliased and optimized deps.
36206
- // This is also used by the CJS externalization heuristics in legacy mode
36207
- for (const id of Object.keys(deps)) {
36208
- if (!metadata.discovered[id]) {
36209
- addMissingDep(id, deps[id]);
36210
- }
36211
- }
36212
- if (!isBuild) {
36213
- const knownDeps = prepareKnownDeps();
36214
- // For dev, we run the scanner and the first optimization
36215
- // run on the background, but we wait until crawling has ended
36216
- // to decide if we send this result to the browser or we need to
36217
- // do another optimize step
36218
- postScanOptimizationResult = runOptimizeDeps(config, knownDeps);
36219
- }
36220
- }
36221
- catch (e) {
36222
- logger.error(e.message);
36223
- }
36224
- finally {
36225
- scanPhaseProcessing.resolve();
36226
- depsOptimizer.scanProcessing = undefined;
36206
+ const scanPhaseProcessing = newDepOptimizationProcessing();
36207
+ depsOptimizer.scanProcessing = scanPhaseProcessing.promise;
36208
+ // Ensure server listen is called before the scanner
36209
+ setTimeout(async () => {
36210
+ try {
36211
+ debuggerViteDeps(picocolors.exports.green(`scanning for dependencies...`));
36212
+ const deps = await discoverProjectDependencies(config);
36213
+ debuggerViteDeps(picocolors.exports.green(Object.keys(deps).length > 0
36214
+ ? `dependencies found by scanner: ${depsLogString(Object.keys(deps))}`
36215
+ : `no dependencies found by scanner`));
36216
+ // Add these dependencies to the discovered list, as these are currently
36217
+ // used by the preAliasPlugin to support aliased and optimized deps.
36218
+ // This is also used by the CJS externalization heuristics in legacy mode
36219
+ for (const id of Object.keys(deps)) {
36220
+ if (!metadata.discovered[id]) {
36221
+ addMissingDep(id, deps[id]);
36222
+ }
36223
+ }
36224
+ if (!isBuild) {
36225
+ const knownDeps = prepareKnownDeps();
36226
+ // For dev, we run the scanner and the first optimization
36227
+ // run on the background, but we wait until crawling has ended
36228
+ // to decide if we send this result to the browser or we need to
36229
+ // do another optimize step
36230
+ postScanOptimizationResult = runOptimizeDeps(config, knownDeps);
36231
+ }
36232
+ }
36233
+ catch (e) {
36234
+ logger.error(e.message);
36235
+ }
36236
+ finally {
36237
+ scanPhaseProcessing.resolve();
36238
+ depsOptimizer.scanProcessing = undefined;
36239
+ }
36240
+ }, 0);
36227
36241
  }
36228
36242
  }
36229
36243
  async function startNextDiscoveredBatch() {
@@ -36640,7 +36654,8 @@ const isDebugEnabled = _debug('vite:deps').enabled;
36640
36654
  const jsExtensionRE = /\.js$/i;
36641
36655
  const jsMapExtensionRE = /\.js\.map$/i;
36642
36656
  /**
36643
- * Used by Vite CLI when running `vite optimize`
36657
+ * Scan and optimize dependencies within a project.
36658
+ * Used by Vite CLI when running `vite optimize`.
36644
36659
  */
36645
36660
  async function optimizeDeps(config, force = config.optimizeDeps.force, asCommand = false) {
36646
36661
  const log = asCommand ? config.logger.info : debug$a;
@@ -36870,8 +36885,7 @@ async function runOptimizeDeps(resolvedConfig, depsInfo, ssr = !!resolvedConfig.
36870
36885
  // They're not supported yet because `optimizeDeps.exclude` currently only accepts strings
36871
36886
  if (!Array.isArray(rollupOptionsExternal) ||
36872
36887
  rollupOptionsExternal.some((ext) => typeof ext !== 'string')) {
36873
- throw new Error(`[vite] 'build.rollupOptions.external' can only be an array of strings or a string.\n` +
36874
- `You can turn on 'legacy.buildRollupPluginCommonjs' to support more advanced options.`);
36888
+ throw new Error(`[vite] 'build.rollupOptions.external' can only be an array of strings or a string when using esbuild optimization at build time.`);
36875
36889
  }
36876
36890
  external.push(...rollupOptionsExternal);
36877
36891
  }
@@ -37941,18 +37955,22 @@ function createIsConfiguredAsSsrExternal(config) {
37941
37955
  const noExternalFilter = noExternal !== 'undefined' &&
37942
37956
  typeof noExternal !== 'boolean' &&
37943
37957
  createFilter(undefined, noExternal, { resolve: false });
37958
+ // Returns true if it is configured as external, false if it is filtered
37959
+ // by noExternal and undefined if it isn't affected by the explicit config
37944
37960
  return (id) => {
37945
37961
  const { ssr } = config;
37946
- if (!ssr || ssr.external?.includes(id)) {
37947
- return true;
37948
- }
37949
- if (typeof noExternal === 'boolean') {
37950
- return !noExternal;
37951
- }
37952
- if (noExternalFilter) {
37953
- return noExternalFilter(id);
37962
+ if (ssr) {
37963
+ if (ssr.external?.includes(id)) {
37964
+ return true;
37965
+ }
37966
+ if (typeof noExternal === 'boolean') {
37967
+ return !noExternal;
37968
+ }
37969
+ if (noExternalFilter && !noExternalFilter(id)) {
37970
+ return false;
37971
+ }
37954
37972
  }
37955
- return true;
37973
+ return undefined;
37956
37974
  };
37957
37975
  }
37958
37976
  function createIsSsrExternal(config) {
@@ -37976,9 +37994,11 @@ function createIsSsrExternal(config) {
37976
37994
  if (processedIds.has(id)) {
37977
37995
  return processedIds.get(id);
37978
37996
  }
37979
- const external = !id.startsWith('.') &&
37980
- !path$n.isAbsolute(id) &&
37981
- (isBuiltin(id) || (isConfiguredAsExternal(id) && isValidPackageEntry(id)));
37997
+ let external = false;
37998
+ if (!id.startsWith('.') && !path$n.isAbsolute(id)) {
37999
+ external =
38000
+ isBuiltin(id) || (isConfiguredAsExternal(id) ?? isValidPackageEntry(id));
38001
+ }
37982
38002
  processedIds.set(id, external);
37983
38003
  return external;
37984
38004
  };
@@ -38760,11 +38780,11 @@ const ssrImportKey = `__vite_ssr_import__`;
38760
38780
  const ssrDynamicImportKey = `__vite_ssr_dynamic_import__`;
38761
38781
  const ssrExportAllKey = `__vite_ssr_exportAll__`;
38762
38782
  const ssrImportMetaKey = `__vite_ssr_import_meta__`;
38763
- async function ssrTransform(code, inMap, url, options) {
38783
+ async function ssrTransform(code, inMap, url, originalCode, options) {
38764
38784
  if (options?.json?.stringify && isJSONRequest(url)) {
38765
38785
  return ssrTransformJSON(code, inMap);
38766
38786
  }
38767
- return ssrTransformScript(code, inMap, url);
38787
+ return ssrTransformScript(code, inMap, url, originalCode);
38768
38788
  }
38769
38789
  async function ssrTransformJSON(code, inMap) {
38770
38790
  return {
@@ -38774,7 +38794,7 @@ async function ssrTransformJSON(code, inMap) {
38774
38794
  dynamicDeps: []
38775
38795
  };
38776
38796
  }
38777
- async function ssrTransformScript(code, inMap, url) {
38797
+ async function ssrTransformScript(code, inMap, url, originalCode) {
38778
38798
  const s = new MagicString(code);
38779
38799
  let ast;
38780
38800
  try {
@@ -38953,11 +38973,13 @@ async function ssrTransformScript(code, inMap, url) {
38953
38973
  sourcesContent: inMap.sourcesContent
38954
38974
  },
38955
38975
  inMap
38956
- ]);
38976
+ ], false);
38957
38977
  }
38958
38978
  else {
38959
38979
  map.sources = [url];
38960
- map.sourcesContent = [code];
38980
+ // needs to use originalCode instead of code
38981
+ // because code might be already transformed even if map is null
38982
+ map.sourcesContent = [originalCode];
38961
38983
  }
38962
38984
  return {
38963
38985
  code: s.toString(),
@@ -39474,7 +39496,7 @@ function serveStaticMiddleware(dir, server) {
39474
39496
  return;
39475
39497
  }
39476
39498
  if (redirected) {
39477
- req.url = redirected;
39499
+ req.url = encodeURIComponent(redirected);
39478
39500
  }
39479
39501
  serve(req, res, next);
39480
39502
  };
@@ -39496,7 +39518,7 @@ function serveRawFsMiddleware(server) {
39496
39518
  url = url.slice(FS_PREFIX.length);
39497
39519
  if (isWindows$4)
39498
39520
  url = url.replace(/^[A-Z]:/i, '');
39499
- req.url = url;
39521
+ req.url = encodeURIComponent(url);
39500
39522
  serveFromRoot(req, res, next);
39501
39523
  }
39502
39524
  else {
@@ -39719,6 +39741,7 @@ async function loadAndTransform(id, url, server, options, timestamp) {
39719
39741
  inMap: map,
39720
39742
  ssr
39721
39743
  });
39744
+ const originalCode = code;
39722
39745
  if (transformResult == null ||
39723
39746
  (isObject$2(transformResult) && transformResult.code == null)) {
39724
39747
  // no transform applied, keep code as-is
@@ -39737,7 +39760,7 @@ async function loadAndTransform(id, url, server, options, timestamp) {
39737
39760
  }
39738
39761
  }
39739
39762
  const result = ssr
39740
- ? await ssrTransform(code, map, url, {
39763
+ ? await ssrTransform(code, map, url, originalCode, {
39741
39764
  json: { stringify: !!server.config.json?.stringify }
39742
39765
  })
39743
39766
  : {
@@ -40083,7 +40106,7 @@ function importAnalysisPlugin(config) {
40083
40106
  if (ssr) {
40084
40107
  return [url, url];
40085
40108
  }
40086
- this.error(`Failed to resolve import "${url}" from "${path$n.relative(process.cwd(), importerFile)}". Does the file exist?`, pos);
40109
+ return this.error(`Failed to resolve import "${url}" from "${path$n.relative(process.cwd(), importerFile)}". Does the file exist?`, pos);
40087
40110
  }
40088
40111
  const isRelative = url.startsWith('.');
40089
40112
  const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer);
@@ -40455,6 +40478,7 @@ function transformCjsImport(importExp, url, rawUrl, importIndex) {
40455
40478
  else if (spec.type === 'ExportSpecifier' &&
40456
40479
  spec.exported.type === 'Identifier') {
40457
40480
  // for ExportSpecifier, local name is same as imported name
40481
+ // prefix the variable name to avoid clashing with other local variables
40458
40482
  const importedName = spec.local.name;
40459
40483
  // we want to specify exported name as variable and re-export it
40460
40484
  const exportedName = spec.exported.name;
@@ -40463,8 +40487,9 @@ function transformCjsImport(importExp, url, rawUrl, importIndex) {
40463
40487
  importNames.push({ importedName, localName: defaultExports });
40464
40488
  }
40465
40489
  else {
40466
- importNames.push({ importedName, localName: exportedName });
40467
- exportNames.push(exportedName);
40490
+ const localName = makeLegalIdentifier(`__vite__cjsExport_${exportedName}`);
40491
+ importNames.push({ importedName, localName });
40492
+ exportNames.push(`${localName} as ${exportedName}`);
40468
40493
  }
40469
40494
  }
40470
40495
  }
@@ -40627,7 +40652,7 @@ function buildImportAnalysisPlugin(config) {
40627
40652
  if (ssr) {
40628
40653
  return [url, url];
40629
40654
  }
40630
- this.error(`Failed to resolve import "${url}" from "${path$n.relative(process.cwd(), importerFile)}". Does the file exist?`, pos);
40655
+ return this.error(`Failed to resolve import "${url}" from "${path$n.relative(process.cwd(), importerFile)}". Does the file exist?`, pos);
40631
40656
  }
40632
40657
  // normalize all imports into resolved URLs
40633
40658
  // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js'`
@@ -41002,7 +41027,7 @@ const assetAttrsConfig = {
41002
41027
  const isAsyncScriptMap = new WeakMap();
41003
41028
  async function traverseHtml(html, filePath, visitor) {
41004
41029
  // lazy load compiler
41005
- const { parse, transform } = await import('./dep-5d9e5830.js').then(function (n) { return n.c; });
41030
+ const { parse, transform } = await import('./dep-f2ffe191.js').then(function (n) { return n.c; });
41006
41031
  // @vue/compiler-core doesn't like lowercase doctypes
41007
41032
  html = html.replace(/<!doctype\s/i, '<!DOCTYPE ');
41008
41033
  try {
@@ -42132,7 +42157,7 @@ async function compileCSS(id, code, config, urlReplacer, atImportResolvers, serv
42132
42157
  logger: config.logger
42133
42158
  }));
42134
42159
  if (isModule) {
42135
- postcssPlugins.unshift((await import('./dep-d3bbad19.js').then(function (n) { return n.i; })).default({
42160
+ postcssPlugins.unshift((await import('./dep-eb5668bc.js').then(function (n) { return n.i; })).default({
42136
42161
  ...modulesOptions,
42137
42162
  getJSON(cssFileName, _modules, outputFileName) {
42138
42163
  modules = _modules;
@@ -43193,13 +43218,14 @@ function resolveBuildOptions(raw, isBuild, logger) {
43193
43218
  }
43194
43219
  function resolveBuildPlugins(config) {
43195
43220
  const options = config.build;
43221
+ const { commonjsOptions } = options;
43222
+ const usePluginCommonjs = !Array.isArray(commonjsOptions?.include) ||
43223
+ commonjsOptions?.include.length !== 0;
43196
43224
  return {
43197
43225
  pre: [
43198
43226
  ...(options.watch ? [ensureWatchPlugin()] : []),
43199
43227
  watchPackageDataPlugin(config),
43200
- ...(config.legacy?.buildRollupPluginCommonjs
43201
- ? [commonjs(options.commonjsOptions)]
43202
- : []),
43228
+ ...(usePluginCommonjs ? [commonjs(options.commonjsOptions)] : []),
43203
43229
  dataURIPlugin(),
43204
43230
  assetImportMetaUrlPlugin(config),
43205
43231
  ...(options.rollupOptions.plugins
@@ -49989,9 +50015,6 @@ async function resolveHttpsConfig(https, cacheDir) {
49989
50015
  key: readFileIfExists(key),
49990
50016
  pfx: readFileIfExists(pfx)
49991
50017
  });
49992
- if (!httpsOption.key || !httpsOption.cert) {
49993
- httpsOption.cert = httpsOption.key = await getCertificate(cacheDir);
49994
- }
49995
50018
  return httpsOption;
49996
50019
  }
49997
50020
  function readFileIfExists(value) {
@@ -50005,27 +50028,6 @@ function readFileIfExists(value) {
50005
50028
  }
50006
50029
  return value;
50007
50030
  }
50008
- async function getCertificate(cacheDir) {
50009
- const cachePath = path$n.join(cacheDir, '_cert.pem');
50010
- try {
50011
- const [stat, content] = await Promise.all([
50012
- promises$2.stat(cachePath),
50013
- promises$2.readFile(cachePath, 'utf8')
50014
- ]);
50015
- if (Date.now() - stat.ctime.valueOf() > 30 * 24 * 60 * 60 * 1000) {
50016
- throw new Error('cache is outdated.');
50017
- }
50018
- return content;
50019
- }
50020
- catch {
50021
- const content = (await import('./dep-e8d443bf.js')).createCertificate();
50022
- promises$2
50023
- .mkdir(cacheDir, { recursive: true })
50024
- .then(() => promises$2.writeFile(cachePath, content))
50025
- .catch(() => { });
50026
- return content;
50027
- }
50028
- }
50029
50031
  async function httpServerStart(httpServer, serverOptions) {
50030
50032
  let { port, strictPort, host, logger } = serverOptions;
50031
50033
  return new Promise((resolve, reject) => {
@@ -58896,7 +58898,7 @@ function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) {
58896
58898
  async function createServer(inlineConfig = {}) {
58897
58899
  const config = await resolveConfig(inlineConfig, 'serve', 'development');
58898
58900
  const { root, server: serverConfig } = config;
58899
- const httpsOptions = await resolveHttpsConfig(config.server.https, config.cacheDir);
58901
+ const httpsOptions = await resolveHttpsConfig(config.server.https);
58900
58902
  const { middlewareMode } = serverConfig;
58901
58903
  const middlewares = connect();
58902
58904
  const httpServer = middlewareMode
@@ -58928,8 +58930,9 @@ async function createServer(inlineConfig = {}) {
58928
58930
  pluginContainer: container,
58929
58931
  ws,
58930
58932
  moduleGraph,
58933
+ resolvedUrls: null,
58931
58934
  ssrTransform(code, inMap, url) {
58932
- return ssrTransform(code, inMap, url, {
58935
+ return ssrTransform(code, inMap, url, code, {
58933
58936
  json: { stringify: server.config.json?.stringify }
58934
58937
  });
58935
58938
  },
@@ -58953,8 +58956,12 @@ async function createServer(inlineConfig = {}) {
58953
58956
  ssrRewriteStacktrace(stack) {
58954
58957
  return ssrRewriteStacktrace(stack, moduleGraph);
58955
58958
  },
58956
- listen(port, isRestart) {
58957
- return startServer(server, port, isRestart);
58959
+ async listen(port, isRestart) {
58960
+ await startServer(server, port, isRestart);
58961
+ if (httpServer) {
58962
+ server.resolvedUrls = await resolveServerUrls(httpServer, config.server, config);
58963
+ }
58964
+ return server;
58958
58965
  },
58959
58966
  async close() {
58960
58967
  if (!middlewareMode) {
@@ -58969,14 +58976,18 @@ async function createServer(inlineConfig = {}) {
58969
58976
  container.close(),
58970
58977
  closeHttpServer()
58971
58978
  ]);
58979
+ server.resolvedUrls = null;
58972
58980
  },
58973
- async printUrls() {
58974
- if (httpServer) {
58975
- await printCommonServerUrls(httpServer, config.server, config);
58981
+ printUrls() {
58982
+ if (server.resolvedUrls) {
58983
+ printServerUrls(server.resolvedUrls, serverConfig.host, config.logger.info);
58976
58984
  }
58977
- else {
58985
+ else if (middlewareMode) {
58978
58986
  throw new Error('cannot print server URLs in middleware mode.');
58979
58987
  }
58988
+ else {
58989
+ throw new Error('cannot print server URLs before server.listen is called.');
58990
+ }
58980
58991
  },
58981
58992
  async restart(forceOptimize) {
58982
58993
  if (!server._restartPromise) {
@@ -59185,7 +59196,6 @@ async function startServer(server, inlinePort, isRestart = false) {
59185
59196
  ? path
59186
59197
  : `${protocol}://${hostname.name}:${serverPort}${path}`, true, server.config.logger);
59187
59198
  }
59188
- return server;
59189
59199
  }
59190
59200
  function createServerCloseFn(server) {
59191
59201
  if (!server) {
@@ -59452,7 +59462,7 @@ function resolvePreviewOptions(preview, server) {
59452
59462
  async function preview(inlineConfig = {}) {
59453
59463
  const config = await resolveConfig(inlineConfig, 'serve', 'production');
59454
59464
  const app = connect();
59455
- const httpServer = await resolveHttpServer(config.preview, app, await resolveHttpsConfig(config.preview?.https, config.cacheDir));
59465
+ const httpServer = await resolveHttpServer(config.preview, app, await resolveHttpsConfig(config.preview?.https));
59456
59466
  // apply server hooks from plugins
59457
59467
  const postHooks = [];
59458
59468
  for (const plugin of config.plugins) {
@@ -59492,6 +59502,7 @@ async function preview(inlineConfig = {}) {
59492
59502
  host: hostname.host,
59493
59503
  logger
59494
59504
  });
59505
+ const resolvedUrls = await resolveServerUrls(httpServer, config.preview, config);
59495
59506
  if (options.open) {
59496
59507
  const path = typeof options.open === 'string' ? options.open : previewBase;
59497
59508
  openBrowser(path.startsWith('http')
@@ -59501,8 +59512,9 @@ async function preview(inlineConfig = {}) {
59501
59512
  return {
59502
59513
  config,
59503
59514
  httpServer,
59504
- async printUrls() {
59505
- await printCommonServerUrls(httpServer, config.preview, config);
59515
+ resolvedUrls,
59516
+ printUrls() {
59517
+ printServerUrls(resolvedUrls, options.host, logger.info);
59506
59518
  }
59507
59519
  };
59508
59520
  }
@@ -59525,6 +59537,10 @@ function clientInjectionsPlugin(config) {
59525
59537
  name: 'vite:client-inject',
59526
59538
  async transform(code, id, options) {
59527
59539
  if (id === normalizedClientEntry || id === normalizedEnvEntry) {
59540
+ const resolvedServerHostname = (await resolveHostname(config.server.host)).name;
59541
+ const resolvedServerPort = config.server.port;
59542
+ const devBase = config.base;
59543
+ const serverHost = `${resolvedServerHostname}:${resolvedServerPort}${devBase}`;
59528
59544
  let hmrConfig = config.server.hmr;
59529
59545
  hmrConfig = isObject$2(hmrConfig) ? hmrConfig : undefined;
59530
59546
  const host = hmrConfig?.host || null;
@@ -59537,9 +59553,8 @@ function clientInjectionsPlugin(config) {
59537
59553
  if (config.server.middlewareMode) {
59538
59554
  port || (port = 24678);
59539
59555
  }
59540
- const devBase = config.base;
59541
- let directTarget = hmrConfig?.host || (await resolveHostname(config.server.host)).name;
59542
- directTarget += `:${hmrConfig?.port || config.server.port}`;
59556
+ let directTarget = hmrConfig?.host || resolvedServerHostname;
59557
+ directTarget += `:${hmrConfig?.port || resolvedServerPort}`;
59543
59558
  directTarget += devBase;
59544
59559
  let hmrBase = devBase;
59545
59560
  if (hmrConfig?.path) {
@@ -59549,6 +59564,7 @@ function clientInjectionsPlugin(config) {
59549
59564
  .replace(`__MODE__`, JSON.stringify(config.mode))
59550
59565
  .replace(`__BASE__`, JSON.stringify(devBase))
59551
59566
  .replace(`__DEFINES__`, serializeDefine(config.define || {}))
59567
+ .replace(`__SERVER_HOST__`, JSON.stringify(serverHost))
59552
59568
  .replace(`__HMR_PROTOCOL__`, JSON.stringify(protocol))
59553
59569
  .replace(`__HMR_HOSTNAME__`, JSON.stringify(host))
59554
59570
  .replace(`__HMR_PORT__`, JSON.stringify(port))
@@ -62221,6 +62237,7 @@ function resolveSSROptions(ssr, buildSsrCjsExternalHeuristics, preserveSymlinks)
62221
62237
  target,
62222
62238
  ...ssr,
62223
62239
  optimizeDeps: {
62240
+ disabled: true,
62224
62241
  ...optimizeDeps,
62225
62242
  esbuildOptions: {
62226
62243
  preserveSymlinks,
@@ -62250,6 +62267,10 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62250
62267
  if (mode === 'production') {
62251
62268
  process.env.NODE_ENV = 'production';
62252
62269
  }
62270
+ // production env would not work in serve, fallback to development
62271
+ if (command === 'serve' && process.env.NODE_ENV === 'production') {
62272
+ process.env.NODE_ENV = 'development';
62273
+ }
62253
62274
  const configEnv = {
62254
62275
  mode,
62255
62276
  command,
@@ -62304,6 +62325,14 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62304
62325
  }
62305
62326
  }
62306
62327
  }
62328
+ if (process.env.VITE_TEST_WITHOUT_PLUGIN_COMMONJS) {
62329
+ config = mergeConfig(config, {
62330
+ optimizeDeps: { disabled: false },
62331
+ ssr: { optimizeDeps: { disabled: false } }
62332
+ });
62333
+ config.build ?? (config.build = {});
62334
+ config.build.commonjsOptions = { include: [] };
62335
+ }
62307
62336
  // resolve root
62308
62337
  const resolvedRoot = normalizePath$3(config.root ? path$n.resolve(config.root) : process.cwd());
62309
62338
  const clientAlias = [
@@ -62403,12 +62432,6 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62403
62432
  const ssr = resolveSSROptions(config.ssr, config.legacy?.buildSsrCjsExternalHeuristics, config.resolve?.preserveSymlinks);
62404
62433
  const middlewareMode = config?.server?.middlewareMode;
62405
62434
  const optimizeDeps = config.optimizeDeps || {};
62406
- if (process.env.VITE_TEST_LEGACY_CJS_PLUGIN) {
62407
- config.legacy = {
62408
- ...config.legacy,
62409
- buildRollupPluginCommonjs: true
62410
- };
62411
- }
62412
62435
  const BASE_URL = resolvedBase;
62413
62436
  const resolved = {
62414
62437
  ...config,
@@ -62444,6 +62467,7 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62444
62467
  packageCache: new Map(),
62445
62468
  createResolver,
62446
62469
  optimizeDeps: {
62470
+ disabled: 'build',
62447
62471
  ...optimizeDeps,
62448
62472
  esbuildOptions: {
62449
62473
  preserveSymlinks: config.resolve?.preserveSymlinks,
@@ -62451,7 +62475,7 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62451
62475
  }
62452
62476
  },
62453
62477
  worker: resolvedWorkerOptions,
62454
- appType: config.appType ?? middlewareMode === 'ssr' ? 'custom' : 'spa',
62478
+ appType: config.appType ?? (middlewareMode === 'ssr' ? 'custom' : 'spa'),
62455
62479
  experimental: {
62456
62480
  importGlobRestoreExtension: false,
62457
62481
  hmrPartialAccept: false,
@@ -62470,22 +62494,6 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62470
62494
  resolved.optimizeDeps.force = true;
62471
62495
  logger.warn(picocolors.exports.yellow(`server.force is deprecated, use optimizeDeps.force instead`));
62472
62496
  }
62473
- if (resolved.legacy?.buildRollupPluginCommonjs) {
62474
- const optimizerDisabled = resolved.optimizeDeps.disabled;
62475
- if (!optimizerDisabled) {
62476
- resolved.optimizeDeps.disabled = 'build';
62477
- }
62478
- else if (optimizerDisabled === 'dev') {
62479
- resolved.optimizeDeps.disabled = true; // Also disabled during build
62480
- }
62481
- const ssrOptimizerDisabled = resolved.ssr.optimizeDeps.disabled;
62482
- if (!ssrOptimizerDisabled) {
62483
- resolved.ssr.optimizeDeps.disabled = 'build';
62484
- }
62485
- else if (ssrOptimizerDisabled === 'dev') {
62486
- resolved.ssr.optimizeDeps.disabled = true; // Also disabled during build
62487
- }
62488
- }
62489
62497
  // Some plugins that aren't intended to work in the bundling of workers (doing post-processing at build time for example).
62490
62498
  // And Plugins may also have cached that could be corrupted by being used in these extra rollup calls.
62491
62499
  // So we need to separate the worker plugin from the plugin that vite needs to run.