vite 4.0.0-alpha.0 → 4.0.0-alpha.1

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.
@@ -1,5 +1,5 @@
1
1
  import require$$0$1 from 'postcss';
2
- import { A as commonjsGlobal } from './dep-f991744a.js';
2
+ import { A as commonjsGlobal } from './dep-7d777026.js';
3
3
  import require$$0 from 'path';
4
4
  import require$$5 from 'crypto';
5
5
  import require$$0__default from 'fs';
@@ -12232,7 +12232,7 @@ async function resolveServerUrls(server, options, config) {
12232
12232
  const hostname = await resolveHostname(options.host);
12233
12233
  const protocol = options.https ? 'https' : 'http';
12234
12234
  const port = address.port;
12235
- const base = config.base === './' || config.base === '' ? '/' : config.base;
12235
+ const base = config.rawBase === './' || config.rawBase === '' ? '/' : config.rawBase;
12236
12236
  if (hostname.host && loopbackHosts.has(hostname.host)) {
12237
12237
  let hostnameName = hostname.name;
12238
12238
  if (hostnameName === '::1' ||
@@ -12299,12 +12299,15 @@ function getHash(text) {
12299
12299
  return createHash$2('sha256').update(text).digest('hex').substring(0, 8);
12300
12300
  }
12301
12301
  const requireResolveFromRootWithFallback = (root, id) => {
12302
+ const paths = _require$4.resolve.paths?.(id) || [];
12302
12303
  // Search in the root directory first, and fallback to the default require paths.
12303
- const fallbackPaths = _require$4.resolve.paths?.(id) || [];
12304
- const path = _require$4.resolve(id, {
12305
- paths: [root, ...fallbackPaths]
12306
- });
12307
- return path;
12304
+ paths.unshift(root);
12305
+ // Use `resolve` package to check existence first, so if the package is not found,
12306
+ // it won't be cached by nodejs, since there isn't a way to invalidate them:
12307
+ // https://github.com/nodejs/node/issues/44663
12308
+ resolve$5.sync(id, { basedir: root, paths });
12309
+ // Use `require.resolve` again as the `resolve` package doesn't support the `exports` field
12310
+ return _require$4.resolve(id, { paths });
12308
12311
  };
12309
12312
  // Based on node-graceful-fs
12310
12313
  // The ISC License
@@ -12484,6 +12487,37 @@ const isNonDriveRelativeAbsolutePath = (p) => {
12484
12487
  return p.startsWith('/');
12485
12488
  return windowsDrivePathPrefixRE.test(p);
12486
12489
  };
12490
+ /**
12491
+ * Determine if a file is being requested with the correct case, to ensure
12492
+ * consistent behaviour between dev and prod and across operating systems.
12493
+ */
12494
+ function shouldServe(url, assetsDir) {
12495
+ // viteTestUrl is set to something like http://localhost:4173/ and then many tests make calls
12496
+ // like `await page.goto(viteTestUrl + '/example')` giving us URLs beginning with a double slash
12497
+ const pathname = decodeURI(new URL$3(url.startsWith('//') ? url.substring(1) : url, 'http://example.com')
12498
+ .pathname);
12499
+ const file = path$o.join(assetsDir, pathname);
12500
+ if (!fs$l.existsSync(file) ||
12501
+ (isCaseInsensitiveFS && // can skip case check on Linux
12502
+ !fs$l.statSync(file).isDirectory() &&
12503
+ !hasCorrectCase(file, assetsDir))) {
12504
+ return false;
12505
+ }
12506
+ return true;
12507
+ }
12508
+ /**
12509
+ * Note that we can't use realpath here, because we don't want to follow
12510
+ * symlinks.
12511
+ */
12512
+ function hasCorrectCase(file, assets) {
12513
+ if (file === assets)
12514
+ return true;
12515
+ const parent = path$o.dirname(file);
12516
+ if (fs$l.readdirSync(parent).includes(path$o.basename(file))) {
12517
+ return hasCorrectCase(parent, assets);
12518
+ }
12519
+ return false;
12520
+ }
12487
12521
  function joinUrlSegments(a, b) {
12488
12522
  if (!a || !b) {
12489
12523
  return a || b || '';
@@ -12496,6 +12530,13 @@ function joinUrlSegments(a, b) {
12496
12530
  }
12497
12531
  return a + b;
12498
12532
  }
12533
+ function stripBase(path, base) {
12534
+ if (path === base) {
12535
+ return '/';
12536
+ }
12537
+ const devBase = base.endsWith('/') ? base : base + '/';
12538
+ return path.replace(RegExp('^' + devBase), '/');
12539
+ }
12499
12540
  function arrayEqual(a, b) {
12500
12541
  if (a === b)
12501
12542
  return true;
@@ -13412,6 +13453,7 @@ function esbuildPlugin(options = {}) {
13412
13453
  // and for build as the final optimization is in `buildEsbuildPlugin`
13413
13454
  const transformOptions = {
13414
13455
  target: 'esnext',
13456
+ charset: 'utf8',
13415
13457
  ...options,
13416
13458
  minify: false,
13417
13459
  minifyIdentifiers: false,
@@ -13518,6 +13560,7 @@ function resolveEsbuildTranspileOptions(config, format) {
13518
13560
  const isEsLibBuild = config.build.lib && format === 'es';
13519
13561
  const esbuildOptions = config.esbuild || {};
13520
13562
  const options = {
13563
+ charset: 'utf8',
13521
13564
  ...esbuildOptions,
13522
13565
  target: target || undefined,
13523
13566
  format: rollupToEsbuildFormatMap[format],
@@ -32442,7 +32485,7 @@ function fileToDevUrl(id, config) {
32442
32485
  else {
32443
32486
  // outside of project root, use absolute fs path
32444
32487
  // (this is special handled by the serve static middleware
32445
- rtn = path$o.posix.join(FS_PREFIX + id);
32488
+ rtn = path$o.posix.join(FS_PREFIX, id);
32446
32489
  }
32447
32490
  const base = joinUrlSegments(config.server?.origin ?? '', config.base);
32448
32491
  return joinUrlSegments(base, rtn.replace(/^\//, ''));
@@ -34298,7 +34341,7 @@ const externalTypes = [
34298
34341
  'tsx',
34299
34342
  ...KNOWN_ASSET_TYPES
34300
34343
  ];
34301
- function esbuildDepPlugin(qualified, exportsData, external, config, ssr) {
34344
+ function esbuildDepPlugin(qualified, external, config, ssr) {
34302
34345
  const { extensions } = getDepOptimizationConfig(config, ssr);
34303
34346
  // remove optimizable extensions from `externalTypes` list
34304
34347
  const allExternalTypes = extensions
@@ -36329,7 +36372,10 @@ function servePublicMiddleware(dir, headers) {
36329
36372
  if (isImportRequest(req.url) || isInternalRequest(req.url)) {
36330
36373
  return next();
36331
36374
  }
36332
- serve(req, res, next);
36375
+ if (shouldServe(req.url, dir)) {
36376
+ return serve(req, res, next);
36377
+ }
36378
+ next();
36333
36379
  };
36334
36380
  }
36335
36381
  function serveStaticMiddleware(dir, server) {
@@ -36458,6 +36504,8 @@ function renderRestrictedErrorHTML(msg) {
36458
36504
  `;
36459
36505
  }
36460
36506
 
36507
+ const ERR_LOAD_URL = 'ERR_LOAD_URL';
36508
+ const ERR_LOAD_PUBLIC_URL = 'ERR_LOAD_PUBLIC_URL';
36461
36509
  const debugLoad = createDebugger('vite:load');
36462
36510
  const debugTransform = createDebugger('vite:transform');
36463
36511
  const debugCache$1 = createDebugger('vite:cache');
@@ -36603,15 +36651,15 @@ async function loadAndTransform(id, url, server, options, timestamp) {
36603
36651
  }
36604
36652
  }
36605
36653
  if (code == null) {
36606
- if (checkPublicFile(url, config)) {
36607
- throw new Error(`Failed to load url ${url} (resolved id: ${id}). ` +
36608
- `This file is in /public and will be copied as-is during build without ` +
36654
+ const isPublicFile = checkPublicFile(url, config);
36655
+ const msg = isPublicFile
36656
+ ? `This file is in /public and will be copied as-is during build without ` +
36609
36657
  `going through the plugin transforms, and therefore should not be ` +
36610
- `imported from source code. It can only be referenced via HTML tags.`);
36611
- }
36612
- else {
36613
- return null;
36614
- }
36658
+ `imported from source code. It can only be referenced via HTML tags.`
36659
+ : `Does the file exist?`;
36660
+ const err = new Error(`Failed to load url ${url} (resolved id: ${id}). ${msg}`);
36661
+ err.code = isPublicFile ? ERR_LOAD_PUBLIC_URL : ERR_LOAD_URL;
36662
+ throw err;
36615
36663
  }
36616
36664
  // ensure module in graph after successful load
36617
36665
  const mod = await moduleGraph.ensureEntryFromUrl(url, ssr);
@@ -36813,9 +36861,7 @@ function importAnalysisPlugin(config) {
36813
36861
  : null;
36814
36862
  const toAbsoluteUrl = (url) => path$o.posix.resolve(path$o.posix.dirname(importerModule.url), url);
36815
36863
  const normalizeUrl = async (url, pos) => {
36816
- if (base !== '/' && url.startsWith(base)) {
36817
- url = url.replace(base, '/');
36818
- }
36864
+ url = stripBase(url, base);
36819
36865
  let importerFile = importer;
36820
36866
  const optimizeDeps = getDepOptimizationConfig(config, ssr);
36821
36867
  if (moduleListContains(optimizeDeps?.exclude, url)) {
@@ -36856,7 +36902,7 @@ function importAnalysisPlugin(config) {
36856
36902
  fs$l.existsSync(cleanUrl(resolved.id))) {
36857
36903
  // an optimized deps may not yet exists in the filesystem, or
36858
36904
  // a regular file exists but is out of root: rewrite to absolute /@fs/ paths
36859
- url = path$o.posix.join(FS_PREFIX + resolved.id);
36905
+ url = path$o.posix.join(FS_PREFIX, resolved.id);
36860
36906
  }
36861
36907
  else {
36862
36908
  url = resolved.id;
@@ -36903,8 +36949,8 @@ function importAnalysisPlugin(config) {
36903
36949
  e.pos = pos;
36904
36950
  throw e;
36905
36951
  }
36906
- // prepend base (dev base is guaranteed to have ending slash)
36907
- url = base + url.replace(/^\//, '');
36952
+ // prepend base
36953
+ url = joinUrlSegments(base, url);
36908
36954
  }
36909
36955
  return [url, resolved.id];
36910
36956
  };
@@ -37021,7 +37067,7 @@ function importAnalysisPlugin(config) {
37021
37067
  }
37022
37068
  // record for HMR import chain analysis
37023
37069
  // make sure to unwrap and normalize away base
37024
- const hmrUrl = unwrapId(url.replace(base, '/'));
37070
+ const hmrUrl = unwrapId(stripBase(url, base));
37025
37071
  importedUrls.add(hmrUrl);
37026
37072
  if (enablePartialAccept && importedBindings) {
37027
37073
  extractImportedBindings(resolvedId, source, imports[index], importedBindings);
@@ -37134,7 +37180,7 @@ function importAnalysisPlugin(config) {
37134
37180
  // These requests will also be registered in transformRequest to be awaited
37135
37181
  // by the deps optimizer
37136
37182
  if (config.server.preTransformRequests && staticImportedUrls.size) {
37137
- staticImportedUrls.forEach(({ url, id }) => {
37183
+ staticImportedUrls.forEach(({ url }) => {
37138
37184
  url = removeImportQuery(url);
37139
37185
  transformRequest(url, server, { ssr }).catch((e) => {
37140
37186
  if (e?.code === ERR_OUTDATED_OPTIMIZED_DEP) {
@@ -41463,7 +41509,6 @@ async function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.co
41463
41509
  // path.
41464
41510
  const flatIdDeps = {};
41465
41511
  const idToExports = {};
41466
- const flatIdToExports = {};
41467
41512
  const optimizeDeps = getDepOptimizationConfig(config, ssr);
41468
41513
  const { plugins: pluginsFromConfig = [], ...esbuildOptions } = optimizeDeps?.esbuildOptions ?? {};
41469
41514
  for (const id in depsInfo) {
@@ -41481,7 +41526,6 @@ async function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.co
41481
41526
  const flatId = flattenId(id);
41482
41527
  flatIdDeps[flatId] = src;
41483
41528
  idToExports[id] = exportsData;
41484
- flatIdToExports[flatId] = exportsData;
41485
41529
  }
41486
41530
  // esbuild automatically replaces process.env.NODE_ENV for platform 'browser'
41487
41531
  // In lib mode, we need to keep process.env.NODE_ENV untouched, so to at build
@@ -41513,7 +41557,7 @@ async function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.co
41513
41557
  if (external.length) {
41514
41558
  plugins.push(esbuildCjsExternalPlugin(external));
41515
41559
  }
41516
- plugins.push(esbuildDepPlugin(flatIdDeps, flatIdToExports, external, config, ssr));
41560
+ plugins.push(esbuildDepPlugin(flatIdDeps, external, config, ssr));
41517
41561
  const start = performance.now();
41518
41562
  const result = await build$3({
41519
41563
  absWorkingDir: process.cwd(),
@@ -41540,6 +41584,7 @@ async function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.co
41540
41584
  ignoreAnnotations: !isBuild,
41541
41585
  metafile: true,
41542
41586
  plugins,
41587
+ charset: 'utf8',
41543
41588
  ...esbuildOptions,
41544
41589
  supported: {
41545
41590
  'dynamic-import': true,
@@ -43341,7 +43386,7 @@ function cssPlugin(config) {
43341
43386
  for (const file of deps) {
43342
43387
  depModules.add(isCSSRequest(file)
43343
43388
  ? moduleGraph.createFileOnlyEntry(file)
43344
- : await moduleGraph.ensureEntryFromUrl((await fileToUrl(file, config, this)).replace((config.server?.origin ?? '') + devBase, '/'), ssr));
43389
+ : await moduleGraph.ensureEntryFromUrl(stripBase(await fileToUrl(file, config, this), (config.server?.origin ?? '') + devBase), ssr));
43345
43390
  }
43346
43391
  moduleGraph.updateModuleInfo(thisModule, depModules, null,
43347
43392
  // The root CSS proxy module is self-accepting and should not
@@ -43808,7 +43853,7 @@ async function compileCSS(id, code, config, urlReplacer) {
43808
43853
  }));
43809
43854
  }
43810
43855
  if (isModule) {
43811
- postcssPlugins.unshift((await import('./dep-cb778398.js').then(function (n) { return n.i; })).default({
43856
+ postcssPlugins.unshift((await import('./dep-6d760e82.js').then(function (n) { return n.i; })).default({
43812
43857
  ...modulesOptions,
43813
43858
  // TODO: convert null to undefined (`null` should be removed from `CSSModulesOptions.localsConvention`)
43814
43859
  localsConvention: modulesOptions?.localsConvention ?? undefined,
@@ -45096,10 +45141,16 @@ function loadEnv(mode, envDir, prefixes = 'VITE_') {
45096
45141
  }));
45097
45142
  }));
45098
45143
  // let environment variables use each other
45099
- main({
45100
- parsed,
45144
+ const expandParsed = main({
45145
+ parsed: {
45146
+ ...process.env,
45147
+ ...parsed
45148
+ },
45101
45149
  // prevent process.env mutation
45102
45150
  ignoreProcessEnv: true
45151
+ }).parsed;
45152
+ Object.keys(parsed).forEach((key) => {
45153
+ parsed[key] = expandParsed[key];
45103
45154
  });
45104
45155
  // only keys that start with prefix are exposed to client
45105
45156
  for (const [key, value] of Object.entries(parsed)) {
@@ -45509,29 +45560,30 @@ function resolveLibFilename(libOptions, format, entryName, root, extension) {
45509
45560
  }
45510
45561
  function resolveBuildOutputs(outputs, libOptions, logger) {
45511
45562
  if (libOptions) {
45512
- const hasMultipleEntries = typeof libOptions.entry !== 'string' &&
45563
+ const libHasMultipleEntries = typeof libOptions.entry !== 'string' &&
45513
45564
  Object.values(libOptions.entry).length > 1;
45514
- const formats = libOptions.formats || (hasMultipleEntries ? ['es', 'cjs'] : ['es', 'umd']);
45515
- if (formats.includes('umd') || formats.includes('iife')) {
45516
- if (hasMultipleEntries) {
45517
- throw new Error(`Multiple entry points are not supported when output formats include "umd" or "iife".`);
45518
- }
45519
- if (!libOptions.name) {
45520
- throw new Error(`Option "build.lib.name" is required when output formats ` +
45521
- `include "umd" or "iife".`);
45565
+ const libFormats = libOptions.formats ||
45566
+ (libHasMultipleEntries ? ['es', 'cjs'] : ['es', 'umd']);
45567
+ if (!Array.isArray(outputs)) {
45568
+ if (libFormats.includes('umd') || libFormats.includes('iife')) {
45569
+ if (libHasMultipleEntries) {
45570
+ throw new Error('Multiple entry points are not supported when output formats include "umd" or "iife".');
45571
+ }
45572
+ if (!libOptions.name) {
45573
+ throw new Error('Option "build.lib.name" is required when output formats include "umd" or "iife".');
45574
+ }
45522
45575
  }
45576
+ return libFormats.map((format) => ({ ...outputs, format }));
45523
45577
  }
45524
- if (!outputs) {
45525
- return formats.map((format) => ({ format }));
45526
- }
45527
- else if (!Array.isArray(outputs)) {
45528
- return formats.map((format) => ({ ...outputs, format }));
45529
- }
45530
- else if (libOptions.formats) {
45531
- // user explicitly specifying own output array
45532
- logger.warn(picocolors.exports.yellow(`"build.lib.formats" will be ignored because ` +
45533
- `"build.rollupOptions.output" is already an array format`));
45578
+ // By this point, we know "outputs" is an Array.
45579
+ if (libOptions.formats) {
45580
+ logger.warn(picocolors.exports.yellow('"build.lib.formats" will be ignored because "build.rollupOptions.output" is already an array format.'));
45534
45581
  }
45582
+ outputs.forEach((output) => {
45583
+ if (['umd', 'iife'].includes(output.format) && !output.name) {
45584
+ throw new Error('Entries in "build.rollupOptions.output" must specify "name" when the format is "umd" or "iife".');
45585
+ }
45586
+ });
45535
45587
  }
45536
45588
  return outputs;
45537
45589
  }
@@ -45762,7 +45814,7 @@ function toOutputFilePathWithoutRuntime(filename, type, hostId, hostType, config
45762
45814
  return toRelative(filename, hostId);
45763
45815
  }
45764
45816
  else {
45765
- return config.base + filename;
45817
+ return joinUrlSegments(config.base, filename);
45766
45818
  }
45767
45819
  }
45768
45820
  const toOutputFilePathInCss = toOutputFilePathWithoutRuntime;
@@ -55288,7 +55340,7 @@ const EventTarget = {
55288
55340
  * Register an event listener.
55289
55341
  *
55290
55342
  * @param {String} type A string representing the event type to listen for
55291
- * @param {Function} listener The listener to add
55343
+ * @param {(Function|Object)} handler The listener to add
55292
55344
  * @param {Object} [options] An options object specifies characteristics about
55293
55345
  * the event listener
55294
55346
  * @param {Boolean} [options.once=false] A `Boolean` indicating that the
@@ -55296,7 +55348,17 @@ const EventTarget = {
55296
55348
  * the listener would be automatically removed when invoked.
55297
55349
  * @public
55298
55350
  */
55299
- addEventListener(type, listener, options = {}) {
55351
+ addEventListener(type, handler, options = {}) {
55352
+ for (const listener of this.listeners(type)) {
55353
+ if (
55354
+ !options[kForOnEventAttribute$1] &&
55355
+ listener[kListener$1] === handler &&
55356
+ !listener[kForOnEventAttribute$1]
55357
+ ) {
55358
+ return;
55359
+ }
55360
+ }
55361
+
55300
55362
  let wrapper;
55301
55363
 
55302
55364
  if (type === 'message') {
@@ -55306,7 +55368,7 @@ const EventTarget = {
55306
55368
  });
55307
55369
 
55308
55370
  event[kTarget] = this;
55309
- listener.call(this, event);
55371
+ callListener(handler, this, event);
55310
55372
  };
55311
55373
  } else if (type === 'close') {
55312
55374
  wrapper = function onClose(code, message) {
@@ -55317,7 +55379,7 @@ const EventTarget = {
55317
55379
  });
55318
55380
 
55319
55381
  event[kTarget] = this;
55320
- listener.call(this, event);
55382
+ callListener(handler, this, event);
55321
55383
  };
55322
55384
  } else if (type === 'error') {
55323
55385
  wrapper = function onError(error) {
@@ -55327,21 +55389,21 @@ const EventTarget = {
55327
55389
  });
55328
55390
 
55329
55391
  event[kTarget] = this;
55330
- listener.call(this, event);
55392
+ callListener(handler, this, event);
55331
55393
  };
55332
55394
  } else if (type === 'open') {
55333
55395
  wrapper = function onOpen() {
55334
55396
  const event = new Event('open');
55335
55397
 
55336
55398
  event[kTarget] = this;
55337
- listener.call(this, event);
55399
+ callListener(handler, this, event);
55338
55400
  };
55339
55401
  } else {
55340
55402
  return;
55341
55403
  }
55342
55404
 
55343
55405
  wrapper[kForOnEventAttribute$1] = !!options[kForOnEventAttribute$1];
55344
- wrapper[kListener$1] = listener;
55406
+ wrapper[kListener$1] = handler;
55345
55407
 
55346
55408
  if (options.once) {
55347
55409
  this.once(type, wrapper);
@@ -55354,7 +55416,7 @@ const EventTarget = {
55354
55416
  * Remove an event listener.
55355
55417
  *
55356
55418
  * @param {String} type A string representing the event type to remove
55357
- * @param {Function} handler The listener to remove
55419
+ * @param {(Function|Object)} handler The listener to remove
55358
55420
  * @public
55359
55421
  */
55360
55422
  removeEventListener(type, handler) {
@@ -55375,6 +55437,22 @@ var eventTarget = {
55375
55437
  MessageEvent
55376
55438
  };
55377
55439
 
55440
+ /**
55441
+ * Call an event listener
55442
+ *
55443
+ * @param {(Function|Object)} listener The listener to call
55444
+ * @param {*} thisArg The value to use as `this`` when calling the listener
55445
+ * @param {Event} event The event to pass to the listener
55446
+ * @private
55447
+ */
55448
+ function callListener(listener, thisArg, event) {
55449
+ if (typeof listener === 'object' && listener.handleEvent) {
55450
+ listener.handleEvent.call(listener, event);
55451
+ } else {
55452
+ listener.call(thisArg, event);
55453
+ }
55454
+ }
55455
+
55378
55456
  const { tokenChars: tokenChars$1 } = validation.exports;
55379
55457
 
55380
55458
  /**
@@ -57668,18 +57746,18 @@ function createWebSocketServer(server, config, httpsOptions) {
57668
57746
  };
57669
57747
  }
57670
57748
 
57671
- // this middleware is only active when (config.base !== '/')
57749
+ // this middleware is only active when (base !== '/')
57672
57750
  function baseMiddleware({ config }) {
57673
- const devBase = config.base.endsWith('/') ? config.base : config.base + '/';
57674
57751
  // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
57675
57752
  return function viteBaseMiddleware(req, res, next) {
57676
57753
  const url = req.url;
57677
57754
  const parsed = new URL(url, 'http://vitejs.dev');
57678
57755
  const path = parsed.pathname || '/';
57679
- if (path.startsWith(devBase)) {
57756
+ const base = config.rawBase;
57757
+ if (path.startsWith(base)) {
57680
57758
  // rewrite url to remove base. this ensures that other middleware does
57681
57759
  // not need to consider base being prepended or not
57682
- req.url = url.replace(devBase, '/');
57760
+ req.url = stripBase(url, base);
57683
57761
  return next();
57684
57762
  }
57685
57763
  // skip redirect and error fallback on middleware mode, #4057
@@ -57689,18 +57767,18 @@ function baseMiddleware({ config }) {
57689
57767
  if (path === '/' || path === '/index.html') {
57690
57768
  // redirect root visit to based url with search and hash
57691
57769
  res.writeHead(302, {
57692
- Location: config.base + (parsed.search || '') + (parsed.hash || '')
57770
+ Location: base + (parsed.search || '') + (parsed.hash || '')
57693
57771
  });
57694
57772
  res.end();
57695
57773
  return;
57696
57774
  }
57697
57775
  else if (req.headers.accept?.includes('text/html')) {
57698
57776
  // non-based page visit
57699
- const redirectPath = joinUrlSegments(config.base, url);
57777
+ const redirectPath = url + '/' !== base ? joinUrlSegments(base, url) : base;
57700
57778
  res.writeHead(404, {
57701
57779
  'Content-Type': 'text/html'
57702
57780
  });
57703
- res.end(`The server is configured with a public base URL of ${config.base} - ` +
57781
+ res.end(`The server is configured with a public base URL of ${base} - ` +
57704
57782
  `did you mean to visit <a href="${redirectPath}">${redirectPath}</a> instead?`);
57705
57783
  return;
57706
57784
  }
@@ -60145,6 +60223,10 @@ function transformMiddleware(server) {
60145
60223
  // error but a normal part of the missing deps discovery flow
60146
60224
  return;
60147
60225
  }
60226
+ if (e?.code === ERR_LOAD_URL) {
60227
+ // Let other middleware handle if we can't load the url via transformRequest
60228
+ return next();
60229
+ }
60148
60230
  return next(e);
60149
60231
  }
60150
60232
  next();
@@ -61936,28 +62018,12 @@ async function startServer(server, inlinePort, isRestart = false) {
61936
62018
  const port = inlinePort ?? options.port ?? 5173;
61937
62019
  const hostname = await resolveHostname(options.host);
61938
62020
  const protocol = options.https ? 'https' : 'http';
61939
- const info = server.config.logger.info;
61940
62021
  const serverPort = await httpServerStart(httpServer, {
61941
62022
  port,
61942
62023
  strictPort: options.strictPort,
61943
62024
  host: hostname.host,
61944
62025
  logger: server.config.logger
61945
62026
  });
61946
- // @ts-ignore
61947
- const profileSession = global.__vite_profile_session;
61948
- if (profileSession) {
61949
- profileSession.post('Profiler.stop', (err, { profile }) => {
61950
- // Write profile to disk, upload, etc.
61951
- if (!err) {
61952
- const outPath = path$o.resolve('./vite-profile.cpuprofile');
61953
- fs$l.writeFileSync(outPath, JSON.stringify(profile));
61954
- info(picocolors.exports.yellow(` CPU profile written to ${picocolors.exports.white(picocolors.exports.dim(outPath))}\n`));
61955
- }
61956
- else {
61957
- throw err;
61958
- }
61959
- });
61960
- }
61961
62027
  if (options.open && !isRestart) {
61962
62028
  const path = typeof options.open === 'string' ? options.open : server.config.base;
61963
62029
  openBrowser(path.startsWith('http')
@@ -62252,7 +62318,7 @@ async function preview(inlineConfig = {}) {
62252
62318
  // static assets
62253
62319
  const distDir = path$o.resolve(config.root, config.build.outDir);
62254
62320
  const headers = config.preview.headers;
62255
- app.use(previewBase, sirv(distDir, {
62321
+ const assetServer = sirv(distDir, {
62256
62322
  etag: true,
62257
62323
  dev: true,
62258
62324
  single: config.appType === 'spa',
@@ -62263,7 +62329,13 @@ async function preview(inlineConfig = {}) {
62263
62329
  }
62264
62330
  }
62265
62331
  }
62266
- }));
62332
+ });
62333
+ app.use(previewBase, async (req, res, next) => {
62334
+ if (shouldServe(req.url, distDir)) {
62335
+ return assetServer(req, res, next);
62336
+ }
62337
+ next();
62338
+ });
62267
62339
  // apply post server hooks from plugins
62268
62340
  postHooks.forEach((fn) => fn && fn());
62269
62341
  const options = config.preview;
@@ -62367,11 +62439,6 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62367
62439
  configFileDependencies = loadResult.dependencies;
62368
62440
  }
62369
62441
  }
62370
- // Define logger
62371
- const logger = createLogger(config.logLevel, {
62372
- allowClearScreen: config.clearScreen,
62373
- customLogger: config.customLogger
62374
- });
62375
62442
  // user config may provide an alternative mode. But --mode has a higher priority
62376
62443
  mode = inlineConfig.mode || config.mode || mode;
62377
62444
  configEnv.mode = mode;
@@ -62407,6 +62474,11 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62407
62474
  config.build ?? (config.build = {});
62408
62475
  config.build.commonjsOptions = { include: [] };
62409
62476
  }
62477
+ // Define logger
62478
+ const logger = createLogger(config.logLevel, {
62479
+ allowClearScreen: config.clearScreen,
62480
+ customLogger: config.customLogger
62481
+ });
62410
62482
  // resolve root
62411
62483
  const resolvedRoot = normalizePath$3(config.root ? path$o.resolve(config.root) : process.cwd());
62412
62484
  const clientAlias = [
@@ -62537,7 +62609,8 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62537
62609
  configFileDependencies: configFileDependencies.map((name) => normalizePath$3(path$o.resolve(name))),
62538
62610
  inlineConfig,
62539
62611
  root: resolvedRoot,
62540
- base: resolvedBase,
62612
+ base: resolvedBase.endsWith('/') ? resolvedBase : resolvedBase + '/',
62613
+ rawBase: resolvedBase,
62541
62614
  resolve: resolveOptions,
62542
62615
  publicDir: resolvedPublicDir,
62543
62616
  cacheDir,
@@ -62659,28 +62732,22 @@ function resolveBaseUrl(base = '/', isBuild, logger) {
62659
62732
  if (base.startsWith('.')) {
62660
62733
  logger.warn(picocolors.exports.yellow(picocolors.exports.bold(`(!) invalid "base" option: ${base}. The value can only be an absolute ` +
62661
62734
  `URL, ./, or an empty string.`)));
62662
- base = '/';
62735
+ return '/';
62663
62736
  }
62664
- // external URL
62665
- if (isExternalUrl(base)) {
62666
- if (!isBuild) {
62667
- // get base from full url during dev
62668
- const parsed = parse$j(base);
62669
- base = parsed.pathname || '/';
62670
- }
62737
+ // external URL flag
62738
+ const isExternal = isExternalUrl(base);
62739
+ // no leading slash warn
62740
+ if (!isExternal && !base.startsWith('/')) {
62741
+ logger.warn(picocolors.exports.yellow(picocolors.exports.bold(`(!) "base" option should start with a slash.`)));
62671
62742
  }
62672
- else {
62743
+ // parse base when command is serve or base is not External URL
62744
+ if (!isBuild || !isExternal) {
62745
+ base = new URL(base, 'http://vitejs.dev').pathname;
62673
62746
  // ensure leading slash
62674
62747
  if (!base.startsWith('/')) {
62675
- logger.warn(picocolors.exports.yellow(picocolors.exports.bold(`(!) "base" option should start with a slash.`)));
62676
62748
  base = '/' + base;
62677
62749
  }
62678
62750
  }
62679
- // ensure ending slash
62680
- if (!base.endsWith('/')) {
62681
- logger.warn(picocolors.exports.yellow(picocolors.exports.bold(`(!) "base" option should end with a slash.`)));
62682
- base += '/';
62683
- }
62684
62751
  return base;
62685
62752
  }
62686
62753
  function sortUserPlugins(plugins) {
package/dist/node/cli.js CHANGED
@@ -1,9 +1,9 @@
1
+ import path from 'node:path';
2
+ import fs from 'node:fs';
1
3
  import { performance } from 'node:perf_hooks';
2
4
  import { EventEmitter } from 'events';
3
- import { z as picocolors, v as createLogger, g as resolveConfig } from './chunks/dep-f991744a.js';
5
+ import { z as picocolors, v as createLogger, g as resolveConfig } from './chunks/dep-7d777026.js';
4
6
  import { VERSION } from './constants.js';
5
- import 'node:fs';
6
- import 'node:path';
7
7
  import 'node:url';
8
8
  import 'node:module';
9
9
  import 'tty';
@@ -651,6 +651,23 @@ class CAC extends EventEmitter {
651
651
  const cac = (name = "") => new CAC(name);
652
652
 
653
653
  const cli = cac('vite');
654
+ const stopProfiler = (log) => {
655
+ // @ts-ignore
656
+ const profileSession = global.__vite_profile_session;
657
+ if (profileSession) {
658
+ profileSession.post('Profiler.stop', (err, { profile }) => {
659
+ // Write profile to disk, upload, etc.
660
+ if (!err) {
661
+ const outPath = path.resolve('./vite-profile.cpuprofile');
662
+ fs.writeFileSync(outPath, JSON.stringify(profile));
663
+ log(picocolors.exports.yellow(`CPU profile written to ${picocolors.exports.white(picocolors.exports.dim(outPath))}`));
664
+ }
665
+ else {
666
+ throw err;
667
+ }
668
+ });
669
+ }
670
+ };
654
671
  const filterDuplicateOptions = (options) => {
655
672
  for (const [key, value] of Object.entries(options)) {
656
673
  if (Array.isArray(value)) {
@@ -702,7 +719,7 @@ cli
702
719
  filterDuplicateOptions(options);
703
720
  // output structure is preserved even after bundling so require()
704
721
  // is ok here
705
- const { createServer } = await import('./chunks/dep-f991744a.js').then(function (n) { return n.D; });
722
+ const { createServer } = await import('./chunks/dep-7d777026.js').then(function (n) { return n.D; });
706
723
  try {
707
724
  const server = await createServer({
708
725
  root,
@@ -726,9 +743,14 @@ cli
726
743
  : '';
727
744
  info(`\n ${picocolors.exports.green(`${picocolors.exports.bold('VITE')} v${VERSION}`)} ${startupDurationString}\n`, { clear: !server.config.logger.hasWarned });
728
745
  server.printUrls();
746
+ stopProfiler((message) => server.config.logger.info(` ${message}`));
729
747
  }
730
748
  catch (e) {
731
- createLogger(options.logLevel).error(picocolors.exports.red(`error when starting dev server:\n${e.stack}`), { error: e });
749
+ const logger = createLogger(options.logLevel);
750
+ logger.error(picocolors.exports.red(`error when starting dev server:\n${e.stack}`), {
751
+ error: e
752
+ });
753
+ stopProfiler(logger.info);
732
754
  process.exit(1);
733
755
  }
734
756
  });
@@ -750,7 +772,7 @@ cli
750
772
  .option('-w, --watch', `[boolean] rebuilds when modules have changed on disk`)
751
773
  .action(async (root, options) => {
752
774
  filterDuplicateOptions(options);
753
- const { build } = await import('./chunks/dep-f991744a.js').then(function (n) { return n.C; });
775
+ const { build } = await import('./chunks/dep-7d777026.js').then(function (n) { return n.C; });
754
776
  const buildOptions = cleanOptions(options);
755
777
  try {
756
778
  await build({
@@ -768,6 +790,9 @@ cli
768
790
  createLogger(options.logLevel).error(picocolors.exports.red(`error during build:\n${e.stack}`), { error: e });
769
791
  process.exit(1);
770
792
  }
793
+ finally {
794
+ stopProfiler((message) => createLogger(options.logLevel).info(message));
795
+ }
771
796
  });
772
797
  // optimize
773
798
  cli
@@ -775,7 +800,7 @@ cli
775
800
  .option('--force', `[boolean] force the optimizer to ignore the cache and re-bundle`)
776
801
  .action(async (root, options) => {
777
802
  filterDuplicateOptions(options);
778
- const { optimizeDeps } = await import('./chunks/dep-f991744a.js').then(function (n) { return n.B; });
803
+ const { optimizeDeps } = await import('./chunks/dep-7d777026.js').then(function (n) { return n.B; });
779
804
  try {
780
805
  const config = await resolveConfig({
781
806
  root,
@@ -800,7 +825,7 @@ cli
800
825
  .option('--outDir <dir>', `[string] output directory (default: dist)`)
801
826
  .action(async (root, options) => {
802
827
  filterDuplicateOptions(options);
803
- const { preview } = await import('./chunks/dep-f991744a.js').then(function (n) { return n.E; });
828
+ const { preview } = await import('./chunks/dep-7d777026.js').then(function (n) { return n.E; });
804
829
  try {
805
830
  const server = await preview({
806
831
  root,
@@ -825,7 +850,12 @@ cli
825
850
  createLogger(options.logLevel).error(picocolors.exports.red(`error when starting preview server:\n${e.stack}`), { error: e });
826
851
  process.exit(1);
827
852
  }
853
+ finally {
854
+ stopProfiler((message) => createLogger(options.logLevel).info(message));
855
+ }
828
856
  });
829
857
  cli.help();
830
858
  cli.version(VERSION);
831
859
  cli.parse();
860
+
861
+ export { stopProfiler };
@@ -1626,6 +1626,7 @@ export declare type ResolvedConfig = Readonly<Omit<UserConfig, 'plugins' | 'asse
1626
1626
  inlineConfig: InlineConfig;
1627
1627
  root: string;
1628
1628
  base: string;
1629
+ /* Excluded from this release type: rawBase */
1629
1630
  publicDir: string;
1630
1631
  cacheDir: string;
1631
1632
  command: 'build' | 'serve';
@@ -1,4 +1,4 @@
1
- export { b as build, q as createFilter, v as createLogger, c as createServer, e as defineConfig, f as formatPostcssSourceMap, i as getDepOptimizationConfig, j as isDepsOptimizerEnabled, l as loadConfigFromFile, x as loadEnv, k as mergeAlias, m as mergeConfig, n as normalizePath, o as optimizeDeps, a as preprocessCSS, p as preview, h as resolveBaseUrl, g as resolveConfig, y as resolveEnvPrefix, d as resolvePackageData, r as resolvePackageEntry, w as searchForWorkspaceRoot, u as send, s as sortUserPlugins, t as transformWithEsbuild } from './chunks/dep-f991744a.js';
1
+ export { b as build, q as createFilter, v as createLogger, c as createServer, e as defineConfig, f as formatPostcssSourceMap, i as getDepOptimizationConfig, j as isDepsOptimizerEnabled, l as loadConfigFromFile, x as loadEnv, k as mergeAlias, m as mergeConfig, n as normalizePath, o as optimizeDeps, a as preprocessCSS, p as preview, h as resolveBaseUrl, g as resolveConfig, y as resolveEnvPrefix, d as resolvePackageData, r as resolvePackageEntry, w as searchForWorkspaceRoot, u as send, s as sortUserPlugins, t as transformWithEsbuild } from './chunks/dep-7d777026.js';
2
2
  export { VERSION as version } from './constants.js';
3
3
  export { version as esbuildVersion } from 'esbuild';
4
4
  export { VERSION as rollupVersion } from 'rollup';
@@ -4179,10 +4179,16 @@ function loadEnv(mode, envDir, prefixes = 'VITE_') {
4179
4179
  }));
4180
4180
  }));
4181
4181
  // let environment variables use each other
4182
- main({
4183
- parsed,
4182
+ const expandParsed = main({
4183
+ parsed: {
4184
+ ...process.env,
4185
+ ...parsed
4186
+ },
4184
4187
  // prevent process.env mutation
4185
4188
  ignoreProcessEnv: true
4189
+ }).parsed;
4190
+ Object.keys(parsed).forEach((key) => {
4191
+ parsed[key] = expandParsed[key];
4186
4192
  });
4187
4193
  // only keys that start with prefix are exposed to client
4188
4194
  for (const [key, value] of Object.entries(parsed)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite",
3
- "version": "4.0.0-alpha.0",
3
+ "version": "4.0.0-alpha.1",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "author": "Evan You",
@@ -61,20 +61,20 @@
61
61
  "esbuild": "^0.15.9",
62
62
  "postcss": "^8.4.18",
63
63
  "resolve": "^1.22.1",
64
- "rollup": "~3.2.3"
64
+ "rollup": "~3.3.0"
65
65
  },
66
66
  "optionalDependencies": {
67
67
  "fsevents": "~2.3.2"
68
68
  },
69
69
  "devDependencies": {
70
70
  "@ampproject/remapping": "^2.2.0",
71
- "@babel/parser": "^7.20.0",
72
- "@babel/types": "^7.20.0",
71
+ "@babel/parser": "^7.20.2",
72
+ "@babel/types": "^7.20.2",
73
73
  "@jridgewell/trace-mapping": "^0.3.17",
74
74
  "@rollup/plugin-alias": "^4.0.2",
75
75
  "@rollup/plugin-commonjs": "^23.0.2",
76
76
  "@rollup/plugin-dynamic-import-vars": "^2.0.1",
77
- "@rollup/plugin-json": "^4.1.0",
77
+ "@rollup/plugin-json": "^5.0.1",
78
78
  "@rollup/plugin-node-resolve": "14.1.0",
79
79
  "@rollup/plugin-typescript": "^8.5.0",
80
80
  "@rollup/pluginutils": "^4.2.1",
@@ -117,10 +117,10 @@
117
117
  "strip-ansi": "^7.0.1",
118
118
  "strip-literal": "^0.4.2",
119
119
  "tsconfck": "^2.0.1",
120
- "tslib": "^2.4.0",
120
+ "tslib": "^2.4.1",
121
121
  "types": "link:./types",
122
122
  "ufo": "^0.8.6",
123
- "ws": "^8.10.0"
123
+ "ws": "^8.11.0"
124
124
  },
125
125
  "peerDependencies": {
126
126
  "@types/node": ">= 14",