vite 3.0.0-alpha.0 → 3.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.
@@ -11727,6 +11727,9 @@ const timestampRE = /\bt=\d{13}&?\b/;
11727
11727
  function removeTimestampQuery(url) {
11728
11728
  return url.replace(timestampRE, '').replace(trailingSeparatorRE, '');
11729
11729
  }
11730
+ function isRelativeBase(base) {
11731
+ return base === '' || base.startsWith('.');
11732
+ }
11730
11733
  async function asyncReplace(input, re, replacer) {
11731
11734
  let match;
11732
11735
  let remaining = input;
@@ -32352,6 +32355,7 @@ const emittedHashMap = new WeakMap();
32352
32355
  function assetPlugin(config) {
32353
32356
  // assetHashToFilenameMap initialization in buildStart causes getAssetFilename to return undefined
32354
32357
  assetHashToFilenameMap.set(config, new Map());
32358
+ const relativeBase = isRelativeBase(config.base);
32355
32359
  // add own dictionary entry by directly assigning mrmine
32356
32360
  // https://github.com/lukeed/mrmime/issues/3
32357
32361
  mimes$1['ico'] = 'image/x-icon';
@@ -32394,8 +32398,9 @@ function assetPlugin(config) {
32394
32398
  renderChunk(code, chunk) {
32395
32399
  let match;
32396
32400
  let s;
32401
+ const absoluteUrlPathInterpolation = (filename) => `"+new URL(${JSON.stringify(path__default.posix.relative(path__default.dirname(chunk.fileName), filename))},import.meta.url).href+"`;
32397
32402
  // Urls added with JS using e.g.
32398
- // imgElement.src = "my/file.png" are using quotes
32403
+ // imgElement.src = "__VITE_ASSET__5aa0ddc0__" are using quotes
32399
32404
  // Urls added in CSS that is imported in JS end up like
32400
32405
  // var inlined = ".inlined{color:green;background:url(__VITE_ASSET__5aa0ddc0__)}\n";
32401
32406
  // In both cases, the wrapping should already be fine
@@ -32403,14 +32408,30 @@ function assetPlugin(config) {
32403
32408
  s = s || (s = new MagicString(code));
32404
32409
  const [full, hash, postfix = ''] = match;
32405
32410
  // some internal plugins may still need to emit chunks (e.g. worker) so
32406
- // fallback to this.getFileName for that.
32411
+ // fallback to this.getFileName for that. TODO: remove, not needed
32407
32412
  const file = getAssetFilename(hash, config) || this.getFileName(hash);
32408
32413
  chunk.viteMetadata.importedAssets.add(cleanUrl(file));
32409
- const outputFilepath = config.base + file + postfix;
32414
+ const filename = file + postfix;
32415
+ const outputFilepath = relativeBase
32416
+ ? absoluteUrlPathInterpolation(filename)
32417
+ : JSON.stringify(config.base + filename).slice(1, -1);
32410
32418
  s.overwrite(match.index, match.index + full.length, outputFilepath, {
32411
32419
  contentOnly: true
32412
32420
  });
32413
32421
  }
32422
+ // Replace __VITE_PUBLIC_ASSET__5aa0ddc0__ with absolute paths
32423
+ if (relativeBase) {
32424
+ const publicAssetUrlMap = publicAssetUrlCache.get(config);
32425
+ while ((match = publicAssetUrlRE.exec(code))) {
32426
+ s = s || (s = new MagicString(code));
32427
+ const [full, hash] = match;
32428
+ const publicUrl = publicAssetUrlMap.get(hash);
32429
+ const replacement = absoluteUrlPathInterpolation(publicUrl.slice(1));
32430
+ s.overwrite(match.index, match.index + full.length, replacement, {
32431
+ contentOnly: true
32432
+ });
32433
+ }
32434
+ }
32414
32435
  if (s) {
32415
32436
  return {
32416
32437
  code: s.toString(),
@@ -32538,6 +32559,23 @@ function assetFileNamesToFileName(assetFileNames, file, contentHash, content) {
32538
32559
  });
32539
32560
  return fileName;
32540
32561
  }
32562
+ const publicAssetUrlCache = new WeakMap();
32563
+ const publicAssetUrlRE = /__VITE_PUBLIC_ASSET__([a-z\d]{8})__/g;
32564
+ function publicFileToBuiltUrl(url, config) {
32565
+ if (!isRelativeBase(config.base)) {
32566
+ return config.base + url.slice(1);
32567
+ }
32568
+ const hash = getHash(url);
32569
+ let cache = publicAssetUrlCache.get(config);
32570
+ if (!cache) {
32571
+ cache = new Map();
32572
+ publicAssetUrlCache.set(config, cache);
32573
+ }
32574
+ if (!cache.get(hash)) {
32575
+ cache.set(hash, url);
32576
+ }
32577
+ return `__VITE_PUBLIC_ASSET__${hash}__`;
32578
+ }
32541
32579
  /**
32542
32580
  * Register an asset to be emitted as part of the bundle (if necessary)
32543
32581
  * and returns the resolved public URL
@@ -32545,7 +32583,7 @@ function assetFileNamesToFileName(assetFileNames, file, contentHash, content) {
32545
32583
  async function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false) {
32546
32584
  var _a, _b, _c;
32547
32585
  if (!skipPublicCheck && checkPublicFile(id, config)) {
32548
- return config.base + id.slice(1);
32586
+ return publicFileToBuiltUrl(id, config);
32549
32587
  }
32550
32588
  const cache = assetCache.get(config);
32551
32589
  const cached = cache.get(id);
@@ -32600,7 +32638,7 @@ async function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false
32600
32638
  }
32601
32639
  async function urlToBuiltUrl(url, importer, config, pluginContext) {
32602
32640
  if (checkPublicFile(url, config)) {
32603
- return config.base + url.slice(1);
32641
+ return publicFileToBuiltUrl(url, config);
32604
32642
  }
32605
32643
  const file = url.startsWith('/')
32606
32644
  ? path__default.join(config.root, url)
@@ -32746,7 +32784,7 @@ const assetAttrsConfig = {
32746
32784
  const isAsyncScriptMap = new WeakMap();
32747
32785
  async function traverseHtml(html, filePath, visitor) {
32748
32786
  // lazy load compiler
32749
- const { parse, transform } = await Promise.resolve().then(function () { return require('./dep-63fe0f22.js'); }).then(function (n) { return n.compilerDom_cjs; });
32787
+ const { parse, transform } = await Promise.resolve().then(function () { return require('./dep-99df5764.js'); }).then(function (n) { return n.compilerDom_cjs; });
32750
32788
  // @vue/compiler-core doesn't like lowercase doctypes
32751
32789
  html = html.replace(/<!doctype\s/i, '<!DOCTYPE ');
32752
32790
  try {
@@ -32819,7 +32857,9 @@ function buildHtmlPlugin(config) {
32819
32857
  async transform(html, id) {
32820
32858
  var _a, _b;
32821
32859
  if (id.endsWith('.html')) {
32822
- const publicPath = `/${slash$1(path__default.relative(config.root, id))}`;
32860
+ const relativeUrlPath = slash$1(path__default.relative(config.root, id));
32861
+ const publicPath = `/${relativeUrlPath}`;
32862
+ const publicBase = getPublicBase(relativeUrlPath, config);
32823
32863
  // pre-transform
32824
32864
  html = await applyHtmlTransforms(html, preHooks, {
32825
32865
  path: publicPath,
@@ -32846,7 +32886,7 @@ function buildHtmlPlugin(config) {
32846
32886
  const isPublicFile = !!(url && checkPublicFile(url, config));
32847
32887
  if (isPublicFile) {
32848
32888
  // referencing public dir url, prefix with base
32849
- s.overwrite(src.value.loc.start.offset, src.value.loc.end.offset, `"${config.base + url.slice(1)}"`, { contentOnly: true });
32889
+ s.overwrite(src.value.loc.start.offset, src.value.loc.end.offset, `"${normalizePublicPath(url, publicBase)}"`, { contentOnly: true });
32850
32890
  }
32851
32891
  if (isModule) {
32852
32892
  inlineModuleIndex++;
@@ -32920,7 +32960,7 @@ function buildHtmlPlugin(config) {
32920
32960
  }
32921
32961
  }
32922
32962
  else if (checkPublicFile(url, config)) {
32923
- s.overwrite(p.value.loc.start.offset, p.value.loc.end.offset, `"${config.base + url.slice(1)}"`, { contentOnly: true });
32963
+ s.overwrite(p.value.loc.start.offset, p.value.loc.end.offset, `"${normalizePublicPath(url, publicBase)}"`, { contentOnly: true });
32924
32964
  }
32925
32965
  }
32926
32966
  }
@@ -33000,7 +33040,7 @@ function buildHtmlPlugin(config) {
33000
33040
  s.overwrite(start, end, await urlToBuiltUrl(url, id, config, this), { contentOnly: true });
33001
33041
  }
33002
33042
  else if (checkPublicFile(url, config)) {
33003
- s.overwrite(start, end, config.base + url.slice(1), {
33043
+ s.overwrite(start, end, normalizePublicPath(url, publicBase), {
33004
33044
  contentOnly: true
33005
33045
  });
33006
33046
  }
@@ -33044,31 +33084,31 @@ function buildHtmlPlugin(config) {
33044
33084
  });
33045
33085
  return chunks;
33046
33086
  };
33047
- const toScriptTag = (chunk, isAsync) => ({
33087
+ const toScriptTag = (chunk, publicBase, isAsync) => ({
33048
33088
  tag: 'script',
33049
33089
  attrs: {
33050
33090
  ...(isAsync ? { async: true } : {}),
33051
33091
  type: 'module',
33052
33092
  crossorigin: true,
33053
- src: toPublicPath(chunk.fileName, config)
33093
+ src: toPublicPath(chunk.fileName, publicBase)
33054
33094
  }
33055
33095
  });
33056
- const toPreloadTag = (chunk) => ({
33096
+ const toPreloadTag = (chunk, publicBase) => ({
33057
33097
  tag: 'link',
33058
33098
  attrs: {
33059
33099
  rel: 'modulepreload',
33060
33100
  crossorigin: true,
33061
- href: toPublicPath(chunk.fileName, config)
33101
+ href: toPublicPath(chunk.fileName, publicBase)
33062
33102
  }
33063
33103
  });
33064
- const getCssTagsForChunk = (chunk, seen = new Set()) => {
33104
+ const getCssTagsForChunk = (chunk, publicBase, seen = new Set()) => {
33065
33105
  const tags = [];
33066
33106
  if (!analyzedChunk.has(chunk)) {
33067
33107
  analyzedChunk.set(chunk, 1);
33068
33108
  chunk.imports.forEach((file) => {
33069
33109
  const importee = bundle[file];
33070
33110
  if ((importee === null || importee === void 0 ? void 0 : importee.type) === 'chunk') {
33071
- tags.push(...getCssTagsForChunk(importee, seen));
33111
+ tags.push(...getCssTagsForChunk(importee, publicBase, seen));
33072
33112
  }
33073
33113
  });
33074
33114
  }
@@ -33079,7 +33119,7 @@ function buildHtmlPlugin(config) {
33079
33119
  tag: 'link',
33080
33120
  attrs: {
33081
33121
  rel: 'stylesheet',
33082
- href: toPublicPath(file, config)
33122
+ href: toPublicPath(file, publicBase)
33083
33123
  }
33084
33124
  });
33085
33125
  }
@@ -33087,6 +33127,8 @@ function buildHtmlPlugin(config) {
33087
33127
  return tags;
33088
33128
  };
33089
33129
  for (const [id, html] of processedHtml) {
33130
+ const relativeUrlPath = path__default.posix.relative(config.root, id);
33131
+ const publicBase = getPublicBase(relativeUrlPath, config);
33090
33132
  const isAsync = isAsyncScriptMap.get(config).get(id);
33091
33133
  let result = html;
33092
33134
  // find corresponding entry chunk
@@ -33106,9 +33148,12 @@ function buildHtmlPlugin(config) {
33106
33148
  // when inlined, discard entry chunk and inject <script> for everything in post-order
33107
33149
  const imports = getImportedChunks(chunk);
33108
33150
  const assetTags = canInlineEntry
33109
- ? imports.map((chunk) => toScriptTag(chunk, isAsync))
33110
- : [toScriptTag(chunk, isAsync), ...imports.map(toPreloadTag)];
33111
- assetTags.push(...getCssTagsForChunk(chunk));
33151
+ ? imports.map((chunk) => toScriptTag(chunk, publicBase, isAsync))
33152
+ : [
33153
+ toScriptTag(chunk, publicBase, isAsync),
33154
+ ...imports.map((i) => toPreloadTag(i, publicBase))
33155
+ ];
33156
+ assetTags.push(...getCssTagsForChunk(chunk, publicBase));
33112
33157
  result = injectToHead(result, assetTags);
33113
33158
  }
33114
33159
  // inject css link when cssCodeSplit is false
@@ -33120,7 +33165,7 @@ function buildHtmlPlugin(config) {
33120
33165
  tag: 'link',
33121
33166
  attrs: {
33122
33167
  rel: 'stylesheet',
33123
- href: toPublicPath(cssChunk.fileName, config)
33168
+ href: toPublicPath(cssChunk.fileName, publicBase)
33124
33169
  }
33125
33170
  }
33126
33171
  ]);
@@ -33138,7 +33183,6 @@ function buildHtmlPlugin(config) {
33138
33183
  if (s) {
33139
33184
  result = s.toString();
33140
33185
  }
33141
- const relativeUrlPath = path__default.posix.relative(config.root, id);
33142
33186
  result = await applyHtmlTransforms(result, postHooks, {
33143
33187
  path: '/' + relativeUrlPath,
33144
33188
  filename: id,
@@ -33147,7 +33191,7 @@ function buildHtmlPlugin(config) {
33147
33191
  });
33148
33192
  // resolve asset url references
33149
33193
  result = result.replace(assetUrlRE, (_, fileHash, postfix = '') => {
33150
- return config.base + getAssetFilename(fileHash, config) + postfix;
33194
+ return publicBase + getAssetFilename(fileHash, config) + postfix;
33151
33195
  });
33152
33196
  if (chunk && canInlineEntry) {
33153
33197
  // all imports from entry have been inlined to html, prevent rollup from outputting it
@@ -33242,8 +33286,16 @@ function isEntirelyImport(code) {
33242
33286
  // the regexes will remove too little in some exotic cases, but false-negatives are alright
33243
33287
  return !code.replace(importRE, '').replace(commentRE$1, '').trim().length;
33244
33288
  }
33245
- function toPublicPath(filename, config) {
33246
- return isExternalUrl(filename) ? filename : config.base + filename;
33289
+ function getPublicBase(urlRelativePath, config) {
33290
+ return isRelativeBase(config.base)
33291
+ ? path__default.posix.join(path__default.posix.relative(urlRelativePath, '').slice(0, -2), './')
33292
+ : config.base;
33293
+ }
33294
+ function toPublicPath(filename, publicBase) {
33295
+ return isExternalUrl(filename) ? filename : publicBase + filename;
33296
+ }
33297
+ function normalizePublicPath(publicPath, publicBase) {
33298
+ return publicBase + publicPath.slice(1);
33247
33299
  }
33248
33300
  const headInjectRE = /([ \t]*)<\/head>/i;
33249
33301
  const headPrependInjectRE = /([ \t]*)<head[^>]*>/i;
@@ -33351,6 +33403,7 @@ const inlineRE = /(\?|&)inline\b/;
33351
33403
  const inlineCSSRE = /(\?|&)inline-css\b/;
33352
33404
  const usedRE = /(\?|&)used\b/;
33353
33405
  const varRE = /^var\(/i;
33406
+ const cssBundleName = 'style.css';
33354
33407
  const isCSSRequest = (request) => cssLangRE.test(request);
33355
33408
  const isDirectCSSRequest = (request) => cssLangRE.test(request) && directRequestRE.test(request);
33356
33409
  const isDirectRequest = (request) => directRequestRE.test(request);
@@ -33390,7 +33443,12 @@ function cssPlugin(config) {
33390
33443
  const ssr = (options === null || options === void 0 ? void 0 : options.ssr) === true;
33391
33444
  const urlReplacer = async (url, importer) => {
33392
33445
  if (checkPublicFile(url, config)) {
33393
- return config.base + url.slice(1);
33446
+ if (isRelativeBase(config.base)) {
33447
+ return publicFileToBuiltUrl(url, config);
33448
+ }
33449
+ else {
33450
+ return config.base + url.slice(1);
33451
+ }
33394
33452
  }
33395
33453
  const resolved = await resolveUrl(url, importer);
33396
33454
  if (resolved) {
@@ -33449,6 +33507,7 @@ function cssPlugin(config) {
33449
33507
  * Plugin applied after user plugins
33450
33508
  */
33451
33509
  function cssPostPlugin(config) {
33510
+ var _a;
33452
33511
  // styles initialization in buildStart causes a styling loss in watch
33453
33512
  const styles = new Map();
33454
33513
  let pureCssChunks;
@@ -33456,6 +33515,26 @@ function cssPostPlugin(config) {
33456
33515
  // since output formats have no effect on the generated CSS.
33457
33516
  let outputToExtractedCSSMap;
33458
33517
  let hasEmitted = false;
33518
+ const relativeBase = isRelativeBase(config.base);
33519
+ const rollupOptionsOutput = config.build.rollupOptions.output;
33520
+ const assetFileNames = (_a = (Array.isArray(rollupOptionsOutput)
33521
+ ? rollupOptionsOutput[0]
33522
+ : rollupOptionsOutput)) === null || _a === void 0 ? void 0 : _a.assetFileNames;
33523
+ const getCssAssetDirname = (cssAssetName) => {
33524
+ if (!assetFileNames) {
33525
+ return config.build.assetsDir;
33526
+ }
33527
+ else if (typeof assetFileNames === 'string') {
33528
+ return path__default.dirname(assetFileNames);
33529
+ }
33530
+ else {
33531
+ return path__default.dirname(assetFileNames({
33532
+ name: cssAssetName,
33533
+ type: 'asset',
33534
+ source: '/* vite internal call, ignore */'
33535
+ }));
33536
+ }
33537
+ };
33459
33538
  return {
33460
33539
  name: 'vite:css-post',
33461
33540
  buildStart() {
@@ -33565,28 +33644,35 @@ function cssPostPlugin(config) {
33565
33644
  if (!chunkCSS) {
33566
33645
  return null;
33567
33646
  }
33568
- // resolve asset URL placeholders to their built file URLs and perform
33569
- // minification if necessary
33570
- const processChunkCSS = async (css, { inlined, minify }) => {
33647
+ const publicAssetUrlMap = publicAssetUrlCache.get(config);
33648
+ // resolve asset URL placeholders to their built file URLs
33649
+ function resolveAssetUrlsInCss(chunkCSS, cssAssetName) {
33650
+ const cssAssetDirname = relativeBase
33651
+ ? getCssAssetDirname(cssAssetName)
33652
+ : undefined;
33571
33653
  // replace asset url references with resolved url.
33572
- const isRelativeBase = config.base === '' || config.base.startsWith('.');
33573
- css = css.replace(assetUrlRE, (_, fileHash, postfix = '') => {
33654
+ chunkCSS = chunkCSS.replace(assetUrlRE, (_, fileHash, postfix = '') => {
33574
33655
  const filename = getAssetFilename(fileHash, config) + postfix;
33575
33656
  chunk.viteMetadata.importedAssets.add(cleanUrl(filename));
33576
- if (!isRelativeBase || inlined) {
33577
- // absolute base or relative base but inlined (injected as style tag into
33578
- // index.html) use the base as-is
33579
- return config.base + filename;
33657
+ if (relativeBase) {
33658
+ // relative base + extracted CSS
33659
+ const relativePath = path__default.posix.relative(cssAssetDirname, filename);
33660
+ return relativePath.startsWith('.')
33661
+ ? relativePath
33662
+ : './' + relativePath;
33580
33663
  }
33581
33664
  else {
33582
- // relative base + extracted CSS - asset file will be in the same dir
33583
- return `./${path__default.posix.basename(filename)}`;
33665
+ // absolute base
33666
+ return config.base + filename;
33584
33667
  }
33585
33668
  });
33586
- // only external @imports and @charset should exist at this point
33587
- css = await finalizeCss(css, minify, config);
33588
- return css;
33589
- };
33669
+ // resolve public URL from CSS paths
33670
+ if (relativeBase) {
33671
+ const relativePathToPublicFromCSS = path__default.posix.relative(cssAssetDirname, '');
33672
+ chunkCSS = chunkCSS.replace(publicAssetUrlRE, (_, hash) => relativePathToPublicFromCSS + publicAssetUrlMap.get(hash));
33673
+ }
33674
+ return chunkCSS;
33675
+ }
33590
33676
  if (config.build.cssCodeSplit) {
33591
33677
  if (isPureCssChunk) {
33592
33678
  // this is a shared CSS-only chunk that is empty.
@@ -33595,24 +33681,22 @@ function cssPostPlugin(config) {
33595
33681
  if (opts.format === 'es' ||
33596
33682
  opts.format === 'cjs' ||
33597
33683
  opts.format === 'system') {
33598
- chunkCSS = await processChunkCSS(chunkCSS, {
33599
- inlined: false,
33600
- minify: true
33601
- });
33684
+ const cssAssetName = chunk.name + '.css';
33685
+ chunkCSS = resolveAssetUrlsInCss(chunkCSS, cssAssetName);
33686
+ chunkCSS = await finalizeCss(chunkCSS, true, config);
33602
33687
  // emit corresponding css file
33603
33688
  const fileHandle = this.emitFile({
33604
- name: chunk.name + '.css',
33689
+ name: cssAssetName,
33605
33690
  type: 'asset',
33606
33691
  source: chunkCSS
33607
33692
  });
33608
33693
  chunk.viteMetadata.importedCss.add(this.getFileName(fileHandle));
33609
33694
  }
33610
33695
  else if (!config.build.ssr) {
33611
- // legacy build, inline css
33612
- chunkCSS = await processChunkCSS(chunkCSS, {
33613
- inlined: true,
33614
- minify: true
33615
- });
33696
+ // legacy build and inline css
33697
+ // __VITE_ASSET__ and __VITE_PUBLIC_ASSET__ urls are processed by
33698
+ // the vite:asset plugin, don't call resolveAssetUrlsInCss here
33699
+ chunkCSS = await finalizeCss(chunkCSS, true, config);
33616
33700
  const style = `__vite_style__`;
33617
33701
  const injectCode = `var ${style} = document.createElement('style');` +
33618
33702
  `${style}.innerHTML = ${JSON.stringify(chunkCSS)};` +
@@ -33620,6 +33704,7 @@ function cssPostPlugin(config) {
33620
33704
  if (config.build.sourcemap) {
33621
33705
  const s = new MagicString(code);
33622
33706
  s.prepend(injectCode);
33707
+ // resolve public URL from CSS paths, we need to use absolute paths
33623
33708
  return {
33624
33709
  code: s.toString(),
33625
33710
  map: s.generateMap({ hires: true })
@@ -33631,11 +33716,8 @@ function cssPostPlugin(config) {
33631
33716
  }
33632
33717
  }
33633
33718
  else {
33634
- // non-split extracted CSS will be minified together
33635
- chunkCSS = await processChunkCSS(chunkCSS, {
33636
- inlined: false,
33637
- minify: false
33638
- });
33719
+ chunkCSS = resolveAssetUrlsInCss(chunkCSS, cssBundleName);
33720
+ // finalizeCss is called for the aggregated chunk in generateBundle
33639
33721
  outputToExtractedCSSMap.set(opts, (outputToExtractedCSSMap.get(opts) || '') + chunkCSS);
33640
33722
  }
33641
33723
  return null;
@@ -33684,7 +33766,7 @@ function cssPostPlugin(config) {
33684
33766
  hasEmitted = true;
33685
33767
  extractedCss = await finalizeCss(extractedCss, true, config);
33686
33768
  this.emitFile({
33687
- name: 'style.css',
33769
+ name: cssBundleName,
33688
33770
  type: 'asset',
33689
33771
  source: extractedCss
33690
33772
  });
@@ -33811,10 +33893,11 @@ async function compileCSS(id, code, config, urlReplacer, atImportResolvers, serv
33811
33893
  }));
33812
33894
  }
33813
33895
  postcssPlugins.push(UrlRewritePostcssPlugin({
33814
- replacer: urlReplacer
33896
+ replacer: urlReplacer,
33897
+ logger: config.logger
33815
33898
  }));
33816
33899
  if (isModule) {
33817
- postcssPlugins.unshift((await Promise.resolve().then(function () { return require('./dep-2d9eaf08.js'); }).then(function (n) { return n.index; })).default({
33900
+ postcssPlugins.unshift((await Promise.resolve().then(function () { return require('./dep-8db43f98.js'); }).then(function (n) { return n.index; })).default({
33818
33901
  ...modulesOptions,
33819
33902
  getJSON(cssFileName, _modules, outputFileName) {
33820
33903
  modules = _modules;
@@ -33999,12 +34082,18 @@ const UrlRewritePostcssPlugin = (opts) => {
33999
34082
  Once(root) {
34000
34083
  const promises = [];
34001
34084
  root.walkDecls((declaration) => {
34085
+ var _a;
34086
+ const importer = (_a = declaration.source) === null || _a === void 0 ? void 0 : _a.input.file;
34087
+ if (!importer) {
34088
+ opts.logger.warnOnce('\nA PostCSS plugin did not pass the `from` option to `postcss.parse`. ' +
34089
+ 'This may cause imported assets to be incorrectly transformed. ' +
34090
+ "If you've recently added a PostCSS plugin that raised this warning, " +
34091
+ 'please contact the package author to fix the issue.');
34092
+ }
34002
34093
  const isCssUrl = cssUrlRE.test(declaration.value);
34003
34094
  const isCssImageSet = cssImageSetRE.test(declaration.value);
34004
34095
  if (isCssUrl || isCssImageSet) {
34005
34096
  const replacerForDeclaration = (rawUrl) => {
34006
- var _a;
34007
- const importer = (_a = declaration.source) === null || _a === void 0 ? void 0 : _a.input.file;
34008
34097
  return opts.replacer(rawUrl, importer);
34009
34098
  };
34010
34099
  const rewriterToUse = isCssImageSet
@@ -34468,8 +34557,7 @@ function isPreProcessor(lang) {
34468
34557
  const isModernFlag = `__VITE_IS_MODERN__`;
34469
34558
  const preloadMethod = `__vitePreload`;
34470
34559
  const preloadMarker = `__VITE_PRELOAD__`;
34471
- const preloadBaseMarker = `__VITE_PRELOAD_BASE__`;
34472
- const preloadHelperId = 'vite/preload-helper';
34560
+ const preloadHelperId = '\0vite/preload-helper';
34473
34561
  const preloadMarkerWithQuote = `"${preloadMarker}"`;
34474
34562
  const dynamicImportPrefixRE = /import\s*\(/;
34475
34563
  /**
@@ -34484,14 +34572,14 @@ function detectScriptRel() {
34484
34572
  ? 'modulepreload'
34485
34573
  : 'preload';
34486
34574
  }
34487
- function preload(baseModule, deps) {
34575
+ function preload(baseModule, deps, importerUrl) {
34488
34576
  // @ts-ignore
34489
34577
  if (!__VITE_IS_MODERN__ || !deps || deps.length === 0) {
34490
34578
  return baseModule();
34491
34579
  }
34492
34580
  return Promise.all(deps.map((dep) => {
34493
34581
  // @ts-ignore
34494
- dep = `${base}${dep}`;
34582
+ dep = assetsURL(dep, importerUrl);
34495
34583
  // @ts-ignore
34496
34584
  if (dep in seen)
34497
34585
  return;
@@ -34529,10 +34617,14 @@ function buildImportAnalysisPlugin(config) {
34529
34617
  const ssr = !!config.build.ssr;
34530
34618
  const isWorker = config.isWorker;
34531
34619
  const insertPreload = !(ssr || !!config.build.lib || isWorker);
34620
+ const relativeBase = isRelativeBase(config.base);
34532
34621
  const scriptRel = config.build.polyfillModulePreload
34533
34622
  ? `'modulepreload'`
34534
34623
  : `(${detectScriptRel.toString()})()`;
34535
- const preloadCode = `const scriptRel = ${scriptRel};const seen = {};const base = '${preloadBaseMarker}';export const ${preloadMethod} = ${preload.toString()}`;
34624
+ const assetsURL = relativeBase
34625
+ ? `function(dep,importerUrl) { return new URL(dep, importerUrl).href }`
34626
+ : `function(dep) { return ${JSON.stringify(config.base)}+dep }`;
34627
+ const preloadCode = `const scriptRel = ${scriptRel};const assetsURL = ${assetsURL};const seen = {};export const ${preloadMethod} = ${preload.toString()}`;
34536
34628
  return {
34537
34629
  name: 'vite:build-import-analysis',
34538
34630
  resolveId(id) {
@@ -34542,7 +34634,7 @@ function buildImportAnalysisPlugin(config) {
34542
34634
  },
34543
34635
  load(id) {
34544
34636
  if (id === preloadHelperId) {
34545
- return preloadCode.replace(preloadBaseMarker, config.base);
34637
+ return preloadCode;
34546
34638
  }
34547
34639
  },
34548
34640
  async transform(source, importer) {
@@ -34570,7 +34662,7 @@ function buildImportAnalysisPlugin(config) {
34570
34662
  if (isDynamic && insertPreload) {
34571
34663
  needPreloadHelper = true;
34572
34664
  str().prependLeft(expStart, `${preloadMethod}(() => `);
34573
- str().appendRight(expEnd, `,${isModernFlag}?"${preloadMarker}":void 0)`);
34665
+ str().appendRight(expEnd, `,${isModernFlag}?"${preloadMarker}":void 0${relativeBase ? ',import.meta.url' : ''})`);
34574
34666
  }
34575
34667
  // Differentiate CSS imports that use the default export from those that
34576
34668
  // do not by injecting a ?used query - this allows us to avoid including
@@ -34701,12 +34793,17 @@ function buildImportAnalysisPlugin(config) {
34701
34793
  }
34702
34794
  if (markerStartPos > 0) {
34703
34795
  s.overwrite(markerStartPos, markerStartPos + preloadMarkerWithQuote.length,
34704
- // the dep list includes the main chunk, so only need to
34705
- // preload when there are actual other deps.
34796
+ // the dep list includes the main chunk, so only need to reload when there are
34797
+ // actual other deps. Don't include the assets dir if the default asset file names
34798
+ // are used, the path will be reconstructed by the import preload helper
34706
34799
  deps.size > 1 ||
34707
34800
  // main chunk is removed
34708
34801
  (hasRemovedPureCssChunk && deps.size > 0)
34709
- ? `[${[...deps].map((d) => JSON.stringify(d)).join(',')}]`
34802
+ ? `[${[...deps]
34803
+ .map((d) => JSON.stringify(relativeBase
34804
+ ? path__default.relative(path__default.dirname(file), d)
34805
+ : d))
34806
+ .join(',')}]`
34710
34807
  : `[]`, { contentOnly: true });
34711
34808
  rewroteMarkerStartPos.add(markerStartPos);
34712
34809
  }
@@ -35635,19 +35732,40 @@ async function parseImportGlob(code, importer, root, resolveId) {
35635
35732
  return e;
35636
35733
  };
35637
35734
  let ast;
35735
+ let lastTokenPos;
35638
35736
  try {
35639
35737
  ast = parseExpressionAt(code, start, {
35640
35738
  ecmaVersion: 'latest',
35641
35739
  sourceType: 'module',
35642
- ranges: true
35740
+ ranges: true,
35741
+ onToken: (token) => {
35742
+ lastTokenPos = token.end;
35743
+ }
35643
35744
  });
35644
35745
  }
35645
35746
  catch (e) {
35646
35747
  const _e = e;
35647
35748
  if (_e.message && _e.message.startsWith('Unterminated string constant'))
35648
35749
  return undefined;
35649
- throw _e;
35750
+ if (lastTokenPos == null || lastTokenPos <= start)
35751
+ throw _e;
35752
+ // tailing comma in object or array will make the parser think it's a comma operation
35753
+ // we try to parse again removing the comma
35754
+ try {
35755
+ const statement = code.slice(start, lastTokenPos).replace(/[,\s]*$/, '');
35756
+ ast = parseExpressionAt(' '.repeat(start) + statement, // to keep the ast position
35757
+ start, {
35758
+ ecmaVersion: 'latest',
35759
+ sourceType: 'module',
35760
+ ranges: true
35761
+ });
35762
+ }
35763
+ catch {
35764
+ throw _e;
35765
+ }
35650
35766
  }
35767
+ if (ast.type === 'SequenceExpression')
35768
+ ast = ast.expressions[0];
35651
35769
  if (ast.type !== 'CallExpression')
35652
35770
  throw err(`Expect CallExpression, got ${ast.type}`);
35653
35771
  if (ast.arguments.length < 1 || ast.arguments.length > 2)
@@ -37872,6 +37990,7 @@ function assetImportMetaUrlPlugin(config) {
37872
37990
  name: 'vite:asset-import-meta-url',
37873
37991
  async transform(code, id, options) {
37874
37992
  if (!(options === null || options === void 0 ? void 0 : options.ssr) &&
37993
+ id !== preloadHelperId &&
37875
37994
  code.includes('new URL') &&
37876
37995
  code.includes(`import.meta.url`)) {
37877
37996
  let s;
@@ -38012,11 +38131,11 @@ function resolveBuildOptions(raw) {
38012
38131
  // Support browserslist
38013
38132
  // "defaults and supports es6-module and supports es6-module-dynamic-import",
38014
38133
  resolved.target = [
38015
- 'es2019',
38134
+ 'es2020',
38016
38135
  'edge88',
38017
38136
  'firefox78',
38018
38137
  'chrome87',
38019
- 'safari13.1'
38138
+ 'safari13' // transpile nullish coalescing
38020
38139
  ];
38021
38140
  }
38022
38141
  else if (resolved.target === 'esnext' && resolved.minify === 'terser') {
@@ -44730,7 +44849,7 @@ async function getCertificate(cacheDir) {
44730
44849
  return content;
44731
44850
  }
44732
44851
  catch {
44733
- const content = (await Promise.resolve().then(function () { return require('./dep-dfbd0b0c.js'); })).createCertificate();
44852
+ const content = (await Promise.resolve().then(function () { return require('./dep-88b8fd2c.js'); })).createCertificate();
44734
44853
  fs$n.promises
44735
44854
  .mkdir(cacheDir, { recursive: true })
44736
44855
  .then(() => fs$n.promises.writeFile(cachePath, content))
@@ -53834,7 +53953,7 @@ const processNodeUrl = (node, s, config, htmlPath, originalUrl, moduleGraph) =>
53834
53953
  }
53835
53954
  }
53836
53955
  if (startsWithSingleSlashRE.test(url)) {
53837
- // prefix with base
53956
+ // prefix with base (dev only, base is never relative)
53838
53957
  s.overwrite(node.value.loc.start.offset, node.value.loc.end.offset, `"${config.base + url.slice(1)}"`, { contentOnly: true });
53839
53958
  }
53840
53959
  else if (url.startsWith('.') &&
@@ -53886,7 +54005,7 @@ const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl
53886
54005
  }
53887
54006
  // add HTML Proxy to Map
53888
54007
  addToHTMLProxyCache(config, proxyCacheUrl, inlineModuleIndex, { code, map });
53889
- // inline js module. convert to src="proxy"
54008
+ // inline js module. convert to src="proxy" (dev only, base is never relative)
53890
54009
  const modulePath = `${proxyModuleUrl}?html-proxy&index=${inlineModuleIndex}.${ext}`;
53891
54010
  // invalidate the module so the newly cached contents will be served
53892
54011
  const module = server === null || server === void 0 ? void 0 : server.moduleGraph.getModuleById(modulePath);
@@ -57011,6 +57130,15 @@ function emitSourcemapForWorkerEntry(ctx, config, query, chunk) {
57011
57130
  }
57012
57131
  return chunk;
57013
57132
  }
57133
+ const workerAssetUrlRE = /__VITE_WORKER_ASSET__([a-z\d]{8})__/g;
57134
+ function encodeWorkerAssetFileName(fileName, workerCache) {
57135
+ const { fileNameHash } = workerCache;
57136
+ const hash = getHash(fileName);
57137
+ if (!fileNameHash.get(hash)) {
57138
+ fileNameHash.set(hash, fileName);
57139
+ }
57140
+ return `__VITE_WORKER_ASSET__${hash}__`;
57141
+ }
57014
57142
  async function workerFileToUrl(ctx, config, id, query) {
57015
57143
  const workerMap = workerCache.get(config.mainConfig || config);
57016
57144
  let fileName = workerMap.bundle.get(id);
@@ -57024,7 +57152,9 @@ async function workerFileToUrl(ctx, config, id, query) {
57024
57152
  });
57025
57153
  workerMap.bundle.set(id, fileName);
57026
57154
  }
57027
- return config.base + fileName;
57155
+ return isRelativeBase(config.base)
57156
+ ? encodeWorkerAssetFileName(fileName, workerMap)
57157
+ : config.base + fileName;
57028
57158
  }
57029
57159
  function webWorkerPlugin(config) {
57030
57160
  const isBuild = config.command === 'build';
@@ -57037,7 +57167,8 @@ function webWorkerPlugin(config) {
57037
57167
  }
57038
57168
  workerCache.set(config, {
57039
57169
  assets: new Map(),
57040
- bundle: new Map()
57170
+ bundle: new Map(),
57171
+ fileNameHash: new Map()
57041
57172
  });
57042
57173
  },
57043
57174
  load(id) {
@@ -57062,6 +57193,7 @@ function webWorkerPlugin(config) {
57062
57193
  (query && ((_a = query.worker) !== null && _a !== void 0 ? _a : query.sharedworker) == null)) {
57063
57194
  return;
57064
57195
  }
57196
+ // stringified url or `new URL(...)`
57065
57197
  let url;
57066
57198
  if (isBuild) {
57067
57199
  if (query.inline != null) {
@@ -57096,14 +57228,42 @@ function webWorkerPlugin(config) {
57096
57228
  const workerOptions = { type: 'module' };
57097
57229
  return {
57098
57230
  code: `export default function WorkerWrapper() {
57099
- return new ${workerConstructor}(${JSON.stringify(url)}, ${JSON.stringify(workerOptions, null, 2)})
57231
+ return new ${workerConstructor}(${JSON.stringify(url)}, ${JSON.stringify(workerOptions)})
57100
57232
  }`,
57101
57233
  map: { mappings: '' } // Empty sourcemap to suppress Rollup warning
57102
57234
  };
57103
57235
  },
57104
- renderChunk(code) {
57105
- if (config.isWorker && code.includes('import.meta.url')) {
57106
- return code.replace('import.meta.url', 'self.location.href');
57236
+ renderChunk(code, chunk) {
57237
+ let s;
57238
+ const result = () => {
57239
+ return (s && {
57240
+ code: s.toString(),
57241
+ map: config.build.sourcemap ? s.generateMap({ hires: true }) : null
57242
+ });
57243
+ };
57244
+ if (code.match(workerAssetUrlRE) || code.includes('import.meta.url')) {
57245
+ let match;
57246
+ s = new MagicString(code);
57247
+ // Replace "__VITE_WORKER_ASSET__5aa0ddc0__" using relative paths
57248
+ const workerMap = workerCache.get(config.mainConfig || config);
57249
+ const { fileNameHash } = workerMap;
57250
+ while ((match = workerAssetUrlRE.exec(code))) {
57251
+ const [full, hash] = match;
57252
+ const filename = fileNameHash.get(hash);
57253
+ let outputFilepath = path__default.posix.relative(path__default.dirname(chunk.fileName), filename);
57254
+ if (!outputFilepath.startsWith('.')) {
57255
+ outputFilepath = './' + outputFilepath;
57256
+ }
57257
+ const replacement = JSON.stringify(outputFilepath).slice(1, -1);
57258
+ s.overwrite(match.index, match.index + full.length, replacement, {
57259
+ contentOnly: true
57260
+ });
57261
+ }
57262
+ // TODO: check if this should be removed
57263
+ if (config.isWorker) {
57264
+ s = s.replace('import.meta.url', 'self.location.href');
57265
+ return result();
57266
+ }
57107
57267
  }
57108
57268
  if (!isWorker) {
57109
57269
  const workerMap = workerCache.get(config);
@@ -57112,6 +57272,7 @@ function webWorkerPlugin(config) {
57112
57272
  workerMap.assets.delete(asset.fileName);
57113
57273
  });
57114
57274
  }
57275
+ return result();
57115
57276
  }
57116
57277
  };
57117
57278
  }
@@ -58747,7 +58908,7 @@ function workerImportMetaUrlPlugin(config) {
58747
58908
  }
58748
58909
  s || (s = new MagicString(code));
58749
58910
  const workerType = getWorkerType(code, cleanString, index + allExp.length);
58750
- const file = path__default.resolve(path__default.dirname(id), rawUrl.slice(1, -1));
58911
+ const file = normalizePath$3(path__default.resolve(path__default.dirname(id), rawUrl.slice(1, -1)));
58751
58912
  let url;
58752
58913
  if (isBuild) {
58753
58914
  url = await workerFileToUrl(this, config, file, query);
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var index = require('./dep-fafc4143.js');
3
+ var index = require('./dep-5cb039d6.js');
4
4
  var require$$1 = require('crypto');
5
5
  require('fs');
6
6
  require('path');
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var require$$0 = require('postcss');
4
- var index$1 = require('./dep-fafc4143.js');
4
+ var index$1 = require('./dep-5cb039d6.js');
5
5
  var path$2 = require('path');
6
6
  var require$$1 = require('crypto');
7
7
  var fs = require('fs');
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var index = require('./dep-fafc4143.js');
3
+ var index = require('./dep-5cb039d6.js');
4
4
 
5
5
  function _mergeNamespaces(n, m) {
6
6
  for (var i = 0; i < m.length; i++) {
package/dist/node/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  var perf_hooks = require('perf_hooks');
4
4
  var require$$0 = require('events');
5
- var index = require('./chunks/dep-fafc4143.js');
5
+ var index = require('./chunks/dep-5cb039d6.js');
6
6
  require('fs');
7
7
  require('path');
8
8
  require('url');
@@ -683,7 +683,7 @@ cli
683
683
  .action(async (root, options) => {
684
684
  // output structure is preserved even after bundling so require()
685
685
  // is ok here
686
- const { createServer } = await Promise.resolve().then(function () { return require('./chunks/dep-fafc4143.js'); }).then(function (n) { return n.index$1; });
686
+ const { createServer } = await Promise.resolve().then(function () { return require('./chunks/dep-5cb039d6.js'); }).then(function (n) { return n.index$1; });
687
687
  try {
688
688
  const server = await createServer({
689
689
  root,
@@ -732,7 +732,7 @@ cli
732
732
  .option('--emptyOutDir', `[boolean] force empty outDir when it's outside of root`)
733
733
  .option('-w, --watch', `[boolean] rebuilds when modules have changed on disk`)
734
734
  .action(async (root, options) => {
735
- const { build } = await Promise.resolve().then(function () { return require('./chunks/dep-fafc4143.js'); }).then(function (n) { return n.build$1; });
735
+ const { build } = await Promise.resolve().then(function () { return require('./chunks/dep-5cb039d6.js'); }).then(function (n) { return n.build$1; });
736
736
  const buildOptions = cleanOptions(options);
737
737
  try {
738
738
  await build({
@@ -755,7 +755,7 @@ cli
755
755
  .command('optimize [root]', 'pre-bundle dependencies')
756
756
  .option('--force', `[boolean] force the optimizer to ignore the cache and re-bundle`)
757
757
  .action(async (root, options) => {
758
- const { optimizeDeps } = await Promise.resolve().then(function () { return require('./chunks/dep-fafc4143.js'); }).then(function (n) { return n.index; });
758
+ const { optimizeDeps } = await Promise.resolve().then(function () { return require('./chunks/dep-5cb039d6.js'); }).then(function (n) { return n.index; });
759
759
  try {
760
760
  const config = await index.resolveConfig({
761
761
  root,
@@ -778,7 +778,7 @@ cli
778
778
  .option('--https', `[boolean] use TLS + HTTP/2`)
779
779
  .option('--open [path]', `[boolean | string] open browser on startup`)
780
780
  .action(async (root, options) => {
781
- const { preview } = await Promise.resolve().then(function () { return require('./chunks/dep-fafc4143.js'); }).then(function (n) { return n.preview$1; });
781
+ const { preview } = await Promise.resolve().then(function () { return require('./chunks/dep-5cb039d6.js'); }).then(function (n) { return n.preview$1; });
782
782
  try {
783
783
  const server = await preview({
784
784
  root,
@@ -1473,7 +1473,7 @@ export declare interface PreviewServer {
1473
1473
  /**
1474
1474
  * native Node http server instance
1475
1475
  */
1476
- httpServer: Server;
1476
+ httpServer: http.Server;
1477
1477
  /**
1478
1478
  * Print server urls
1479
1479
  */
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var index = require('./chunks/dep-fafc4143.js');
5
+ var index = require('./chunks/dep-5cb039d6.js');
6
6
  require('fs');
7
7
  require('path');
8
8
  require('url');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite",
3
- "version": "3.0.0-alpha.0",
3
+ "version": "3.0.0-alpha.1",
4
4
  "license": "MIT",
5
5
  "author": "Evan You",
6
6
  "description": "Native-ESM powered web dev build tool",