vite 4.4.8 → 5.0.0-beta.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.
@@ -11901,15 +11901,17 @@ function testCaseInsensitiveFS() {
11901
11901
  }
11902
11902
  return fs$l.existsSync(CLIENT_ENTRY.replace('client.mjs', 'cLiEnT.mjs'));
11903
11903
  }
11904
- function isUrl(path) {
11905
- try {
11906
- new URL$3(path);
11907
- return true;
11908
- }
11909
- catch {
11910
- return false;
11911
- }
11912
- }
11904
+ const urlCanParse = URL$3.canParse ??
11905
+ // URL.canParse is supported from Node.js 18.17.0+, 20.0.0+
11906
+ ((path, base) => {
11907
+ try {
11908
+ new URL$3(path, base);
11909
+ return true;
11910
+ }
11911
+ catch {
11912
+ return false;
11913
+ }
11914
+ });
11913
11915
  const isCaseInsensitiveFS = testCaseInsensitiveFS();
11914
11916
  const isWindows$4 = os$4.platform() === 'win32';
11915
11917
  const VOLUME_RE = /^[A-Z]:/i;
@@ -12172,7 +12174,7 @@ function emptyDir(dir, skip) {
12172
12174
  if (path$o.dirname(file) !== '.') {
12173
12175
  const matched = file.match(splitFirstDirRE);
12174
12176
  if (matched) {
12175
- nested ?? (nested = new Map());
12177
+ nested ??= new Map();
12176
12178
  const [, nestedDir, skipPath] = matched;
12177
12179
  let nestedSkip = nested.get(nestedDir);
12178
12180
  if (!nestedSkip) {
@@ -12299,7 +12301,7 @@ const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
12299
12301
  const imageSetUrlRE = /^(?:[\w\-]+\(.*?\)|'.*?'|".*?"|\S*)/;
12300
12302
  function reduceSrcset(ret) {
12301
12303
  return ret.reduce((prev, { url, descriptor }, index) => {
12302
- descriptor ?? (descriptor = '');
12304
+ descriptor ??= '';
12303
12305
  return (prev +=
12304
12306
  url + ` ${descriptor}${index === ret.length - 1 ? '' : ', '}`);
12305
12307
  }, '');
@@ -12984,21 +12986,23 @@ function buildReporterPlugin(config) {
12984
12986
  chunkCount = 0;
12985
12987
  compressedCount = 0;
12986
12988
  },
12987
- renderChunk(code, chunk) {
12988
- for (const id of chunk.moduleIds) {
12989
- const module = this.getModuleInfo(id);
12990
- if (!module)
12991
- continue;
12992
- // When a dynamic importer shares a chunk with the imported module,
12993
- // warn that the dynamic imported module will not be moved to another chunk (#12850).
12994
- if (module.importers.length && module.dynamicImporters.length) {
12995
- // Filter out the intersection of dynamic importers and sibling modules in
12996
- // the same chunk. The intersecting dynamic importers' dynamic import is not
12997
- // expected to work. Note we're only detecting the direct ineffective
12998
- // dynamic import here.
12999
- const detectedIneffectiveDynamicImport = module.dynamicImporters.some((id) => !isInNodeModules(id) && chunk.moduleIds.includes(id));
13000
- if (detectedIneffectiveDynamicImport) {
13001
- this.warn(`\n(!) ${module.id} is dynamically imported by ${module.dynamicImporters.join(', ')} but also statically imported by ${module.importers.join(', ')}, dynamic import will not move module into another chunk.\n`);
12989
+ renderChunk(code, chunk, options) {
12990
+ if (!options.inlineDynamicImports) {
12991
+ for (const id of chunk.moduleIds) {
12992
+ const module = this.getModuleInfo(id);
12993
+ if (!module)
12994
+ continue;
12995
+ // When a dynamic importer shares a chunk with the imported module,
12996
+ // warn that the dynamic imported module will not be moved to another chunk (#12850).
12997
+ if (module.importers.length && module.dynamicImporters.length) {
12998
+ // Filter out the intersection of dynamic importers and sibling modules in
12999
+ // the same chunk. The intersecting dynamic importers' dynamic import is not
13000
+ // expected to work. Note we're only detecting the direct ineffective
13001
+ // dynamic import here.
13002
+ const detectedIneffectiveDynamicImport = module.dynamicImporters.some((id) => !isInNodeModules(id) && chunk.moduleIds.includes(id));
13003
+ if (detectedIneffectiveDynamicImport) {
13004
+ this.warn(`\n(!) ${module.id} is dynamically imported by ${module.dynamicImporters.join(', ')} but also statically imported by ${module.importers.join(', ')}, dynamic import will not move module into another chunk.\n`);
13005
+ }
13002
13006
  }
13003
13007
  }
13004
13008
  }
@@ -13110,7 +13114,7 @@ function buildReporterPlugin(config) {
13110
13114
  config.build.minify &&
13111
13115
  !config.build.lib &&
13112
13116
  !config.build.ssr) {
13113
- config.logger.warn(colors$1.yellow(`\n(!) Some chunks are larger than ${chunkLimit} kBs after minification. Consider:\n` +
13117
+ config.logger.warn(colors$1.yellow(`\n(!) Some chunks are larger than ${chunkLimit} kB after minification. Consider:\n` +
13114
13118
  `- Using dynamic import() to code-split the application\n` +
13115
13119
  `- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/configuration-options/#output-manualchunks\n` +
13116
13120
  `- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.`));
@@ -14351,7 +14355,7 @@ function terserPlugin(config) {
14351
14355
  return null;
14352
14356
  }
14353
14357
  // Lazy load worker.
14354
- worker || (worker = makeWorker());
14358
+ worker ||= makeWorker();
14355
14359
  const terserPath = loadTerserPath(config.root);
14356
14360
  const res = await worker.run(terserPath, code, {
14357
14361
  safari10: true,
@@ -16070,7 +16074,7 @@ function renderAssetUrlInJS(ctx, config, chunk, opts, code) {
16070
16074
  // In both cases, the wrapping should already be fine
16071
16075
  assetUrlRE.lastIndex = 0;
16072
16076
  while ((match = assetUrlRE.exec(code))) {
16073
- s || (s = new MagicString(code));
16077
+ s ||= new MagicString(code);
16074
16078
  const [full, referenceId, postfix = ''] = match;
16075
16079
  const file = ctx.getFileName(referenceId);
16076
16080
  chunk.viteMetadata.importedAssets.add(cleanUrl(file));
@@ -16085,7 +16089,7 @@ function renderAssetUrlInJS(ctx, config, chunk, opts, code) {
16085
16089
  const publicAssetUrlMap = publicAssetUrlCache.get(config);
16086
16090
  publicAssetUrlRE.lastIndex = 0;
16087
16091
  while ((match = publicAssetUrlRE.exec(code))) {
16088
- s || (s = new MagicString(code));
16092
+ s ||= new MagicString(code);
16089
16093
  const [full, hash] = match;
16090
16094
  const publicUrl = publicAssetUrlMap.get(hash).slice(1);
16091
16095
  const replacement = toOutputFilePathInJS(publicUrl, 'public', chunk.fileName, 'js', config, toRelativeRuntime);
@@ -16096,6 +16100,9 @@ function renderAssetUrlInJS(ctx, config, chunk, opts, code) {
16096
16100
  }
16097
16101
  return s;
16098
16102
  }
16103
+ // During build, if we don't use a virtual file for public assets, rollup will
16104
+ // watch for these ids resulting in watching the root of the file system in Windows,
16105
+ const viteBuildPublicIdPrefix = '\0vite:asset:public';
16099
16106
  /**
16100
16107
  * Also supports loading plain strings with import text from './foo.txt?raw'
16101
16108
  */
@@ -16115,10 +16122,15 @@ function assetPlugin(config) {
16115
16122
  // will fail to resolve in the main resolver. handle them here.
16116
16123
  const publicFile = checkPublicFile(id, config);
16117
16124
  if (publicFile) {
16118
- return id;
16125
+ return config.command === 'build'
16126
+ ? `${viteBuildPublicIdPrefix}${id}`
16127
+ : id;
16119
16128
  }
16120
16129
  },
16121
16130
  async load(id) {
16131
+ if (id.startsWith(viteBuildPublicIdPrefix)) {
16132
+ id = id.slice(viteBuildPublicIdPrefix.length);
16133
+ }
16122
16134
  if (id[0] === '\0') {
16123
16135
  // Rollup convention, this id should be handled by the
16124
16136
  // plugin that marked it with \0
@@ -16196,7 +16208,7 @@ async function fileToUrl(id, config, ctx) {
16196
16208
  function fileToDevUrl(id, config) {
16197
16209
  let rtn;
16198
16210
  if (checkPublicFile(id, config)) {
16199
- // in public dir, keep the url as-is
16211
+ // in public dir during dev, keep the url as-is
16200
16212
  rtn = id;
16201
16213
  }
16202
16214
  else if (id.startsWith(config.root)) {
@@ -21300,6 +21312,8 @@ var settings = {};
21300
21312
  if (this.stats) {
21301
21313
  this.objectMode = true;
21302
21314
  }
21315
+ // Remove the cast to the array in the next major (#404).
21316
+ this.ignore = [].concat(this.ignore);
21303
21317
  }
21304
21318
  _getValue(option, value) {
21305
21319
  return option === undefined ? value : option;
@@ -27431,7 +27445,7 @@ function encodeQueryItem(key, value) {
27431
27445
  return `${encodeQueryKey(key)}=${encodeQueryValue(value)}`;
27432
27446
  }
27433
27447
  function stringifyQuery(query) {
27434
- return Object.keys(query).filter((k) => query[k] !== void 0).map((k) => encodeQueryItem(k, query[k])).join("&");
27448
+ return Object.keys(query).filter((k) => query[k] !== void 0).map((k) => encodeQueryItem(k, query[k])).filter(Boolean).join("&");
27435
27449
  }
27436
27450
 
27437
27451
  new Set(builtinModules);
@@ -28648,7 +28662,7 @@ function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache
28648
28662
  }
28649
28663
  }
28650
28664
  }
28651
- entryPoint || (entryPoint = data.main);
28665
+ entryPoint ||= data.main;
28652
28666
  // try default entry when entry is not define
28653
28667
  // https://nodejs.org/api/modules.html#all-together
28654
28668
  const entryPoints = entryPoint
@@ -36627,47 +36641,77 @@ var src$1 = rc;
36627
36641
 
36628
36642
  var postcssrc = /*@__PURE__*/getDefaultExportFromCjs(src$1);
36629
36643
 
36630
- function stripLiteralAcorn(code) {
36631
- const FILL = " ";
36644
+ function _stripLiteralAcorn(code, options) {
36645
+ const FILL = options?.fillChar ?? " ";
36646
+ const FILL_COMMENT = " ";
36632
36647
  let result = "";
36633
- function fulfill(index) {
36648
+ const filter = options?.filter ?? (() => true);
36649
+ function fillupTo(index) {
36634
36650
  if (index > result.length)
36635
- result += code.slice(result.length, index).replace(/[^\n]/g, FILL);
36651
+ result += code.slice(result.length, index).replace(/[^\n]/g, FILL_COMMENT);
36636
36652
  }
36637
- const tokens = tokenizer(code, {
36653
+ const tokens = [];
36654
+ const pasers = tokenizer(code, {
36638
36655
  ecmaVersion: "latest",
36639
36656
  sourceType: "module",
36640
36657
  allowHashBang: true,
36641
36658
  allowAwaitOutsideFunction: true,
36642
36659
  allowImportExportEverywhere: true
36643
36660
  });
36644
- const inter = tokens[Symbol.iterator]();
36645
- while (true) {
36646
- const { done, value: token } = inter.next();
36647
- if (done)
36648
- break;
36649
- fulfill(token.start);
36650
- if (token.type.label === "string")
36651
- result += code[token.start] + FILL.repeat(token.end - token.start - 2) + code[token.end - 1];
36652
- else if (token.type.label === "template")
36653
- result += FILL.repeat(token.end - token.start);
36654
- else
36661
+ const iter = pasers[Symbol.iterator]();
36662
+ let error;
36663
+ try {
36664
+ while (true) {
36665
+ const { done, value: token } = iter.next();
36666
+ if (done)
36667
+ break;
36668
+ tokens.push(token);
36669
+ fillupTo(token.start);
36670
+ if (token.type.label === "string") {
36671
+ const body = code.slice(token.start + 1, token.end - 1);
36672
+ if (filter(body)) {
36673
+ result += code[token.start] + FILL.repeat(token.end - token.start - 2) + code[token.end - 1];
36674
+ continue;
36675
+ }
36676
+ } else if (token.type.label === "template") {
36677
+ const body = code.slice(token.start, token.end);
36678
+ if (filter(body)) {
36679
+ result += FILL.repeat(token.end - token.start);
36680
+ continue;
36681
+ }
36682
+ } else if (token.type.label === "regexp") {
36683
+ const body = code.slice(token.start, token.end);
36684
+ if (filter(body)) {
36685
+ result += body.replace(/\/(.*)\/(\w?)$/g, (_, $1, $2) => `/${FILL.repeat($1.length)}/${$2}`);
36686
+ continue;
36687
+ }
36688
+ }
36655
36689
  result += code.slice(token.start, token.end);
36690
+ }
36691
+ fillupTo(code.length);
36692
+ } catch (e) {
36693
+ error = e;
36656
36694
  }
36657
- fulfill(code.length);
36658
- return result;
36695
+ return {
36696
+ error,
36697
+ result,
36698
+ tokens
36699
+ };
36659
36700
  }
36660
36701
 
36661
36702
  const multilineCommentsRE = /\/\*([^*\/])*?\*\//gms;
36662
36703
  const singlelineCommentsRE = /(?:^|\n|\r)\s*\/\/.*(?:\r|\n|$)/gm;
36663
- const templateLiteralRE = /\$\{(\s*(?:(?!\$\{).|\n|\r)*?\s*)\}/g;
36704
+ const templateLiteralRE = /\$\{(\s*(?:|{.*}|(?!\$\{).|\n|\r)*?\s*)\}/g;
36664
36705
  const quotesRE = [
36665
36706
  /(["'`])((?:\\\1|(?!\1)|.|\r)*?)\1/gm,
36666
36707
  /([`])((?:\\\1|(?!\1)|.|\n|\r)*?)\1/gm
36667
36708
  // multi-line strings (i.e. template literals only)
36668
36709
  ];
36669
- function stripLiteralRegex(code) {
36670
- code = code.replace(multilineCommentsRE, (s) => " ".repeat(s.length)).replace(singlelineCommentsRE, (s) => " ".repeat(s.length));
36710
+ function stripLiteralRegex(code, options) {
36711
+ const FILL_COMMENT = " ";
36712
+ const FILL = options?.fillChar ?? " ";
36713
+ const filter = options?.filter ?? (() => true);
36714
+ code = code.replace(multilineCommentsRE, (s) => filter(s) ? FILL_COMMENT.repeat(s.length) : s).replace(singlelineCommentsRE, (s) => filter(s) ? FILL_COMMENT.repeat(s.length) : s);
36671
36715
  let expanded = code;
36672
36716
  for (let i = 0; i < 16; i++) {
36673
36717
  const before = expanded;
@@ -36677,19 +36721,32 @@ function stripLiteralRegex(code) {
36677
36721
  }
36678
36722
  quotesRE.forEach((re) => {
36679
36723
  expanded = expanded.replace(re, (s, quote, body, index) => {
36680
- code = code.slice(0, index + 1) + " ".repeat(s.length - 2) + code.slice(index + s.length - 1);
36681
- return quote + " ".repeat(s.length - 2) + quote;
36724
+ if (!filter(s.slice(1, -1)))
36725
+ return s;
36726
+ code = code.slice(0, index + 1) + FILL.repeat(s.length - 2) + code.slice(index + s.length - 1);
36727
+ return quote + FILL.repeat(s.length - 2) + quote;
36682
36728
  });
36683
36729
  });
36684
36730
  return code;
36685
36731
  }
36686
36732
 
36687
- function stripLiteral(code) {
36688
- try {
36689
- return stripLiteralAcorn(code);
36690
- } catch (e) {
36691
- return stripLiteralRegex(code);
36733
+ function stripLiteral(code, options) {
36734
+ return stripLiteralDetailed(code, options).result;
36735
+ }
36736
+ function stripLiteralDetailed(code, options) {
36737
+ const acorn = _stripLiteralAcorn(code, options);
36738
+ if (!acorn.error) {
36739
+ return {
36740
+ mode: "acorn",
36741
+ result: acorn.result,
36742
+ acorn
36743
+ };
36692
36744
  }
36745
+ return {
36746
+ mode: "regex",
36747
+ result: stripLiteralRegex(acorn.result + code.slice(acorn.result.length), options),
36748
+ acorn
36749
+ };
36693
36750
  }
36694
36751
 
36695
36752
  var main$1 = {exports: {}};
@@ -37514,9 +37571,9 @@ function buildHtmlPlugin(config) {
37514
37571
  js += `\nimport "${id}?html-proxy&index=${inlineModuleIndex}.js"`;
37515
37572
  shouldRemove = true;
37516
37573
  }
37517
- everyScriptIsAsync && (everyScriptIsAsync = isAsync);
37518
- someScriptsAreAsync || (someScriptsAreAsync = isAsync);
37519
- someScriptsAreDefer || (someScriptsAreDefer = !isAsync);
37574
+ everyScriptIsAsync &&= isAsync;
37575
+ someScriptsAreAsync ||= isAsync;
37576
+ someScriptsAreDefer ||= !isAsync;
37520
37577
  }
37521
37578
  else if (url && !isPublicFile) {
37522
37579
  if (!isExcludedUrl(url)) {
@@ -37817,7 +37874,7 @@ function buildHtmlPlugin(config) {
37817
37874
  let s;
37818
37875
  inlineCSSRE$1.lastIndex = 0;
37819
37876
  while ((match = inlineCSSRE$1.exec(result))) {
37820
- s || (s = new MagicString(result));
37877
+ s ||= new MagicString(result);
37821
37878
  const { 0: full, 1: scopedName } = match;
37822
37879
  const cssTransformedCode = htmlProxyResult.get(scopedName);
37823
37880
  s.update(match.index, match.index + full.length, cssTransformedCode);
@@ -37837,7 +37894,7 @@ function buildHtmlPlugin(config) {
37837
37894
  });
37838
37895
  result = result.replace(publicAssetUrlRE, (_, fileHash) => {
37839
37896
  const publicAssetPath = toOutputPublicAssetFilePath(getPublicAssetFilename(fileHash, config));
37840
- return isUrl(publicAssetPath)
37897
+ return urlCanParse(publicAssetPath)
37841
37898
  ? publicAssetPath
37842
37899
  : normalizePath$3(publicAssetPath);
37843
37900
  });
@@ -38379,7 +38436,7 @@ function cssPostPlugin(config) {
38379
38436
  else {
38380
38437
  let content = css;
38381
38438
  if (config.build.cssMinify) {
38382
- content = await minifyCSS(content, config);
38439
+ content = await minifyCSS(content, config, true);
38383
38440
  }
38384
38441
  code = `export default ${JSON.stringify(content)}`;
38385
38442
  }
@@ -38459,9 +38516,10 @@ function cssPostPlugin(config) {
38459
38516
  pureCssChunks.add(chunk);
38460
38517
  }
38461
38518
  if (opts.format === 'es' || opts.format === 'cjs') {
38462
- const cssAssetName = chunk.facadeModuleId
38463
- ? normalizePath$3(path$o.relative(config.root, chunk.facadeModuleId))
38464
- : chunk.name;
38519
+ const isEntry = chunk.isEntry && isPureCssChunk;
38520
+ const cssAssetName = normalizePath$3(!isEntry && chunk.facadeModuleId
38521
+ ? path$o.relative(config.root, chunk.facadeModuleId)
38522
+ : chunk.name);
38465
38523
  const lang = path$o.extname(cssAssetName).slice(1);
38466
38524
  const cssFileName = ensureFileExt(cssAssetName, '.css');
38467
38525
  chunkCSS = resolveAssetUrlsInCss(chunkCSS, cssAssetName);
@@ -38485,7 +38543,6 @@ function cssPostPlugin(config) {
38485
38543
  source: chunkCSS,
38486
38544
  });
38487
38545
  const originalName = isPreProcessor(lang) ? cssAssetName : cssFileName;
38488
- const isEntry = chunk.isEntry && isPureCssChunk;
38489
38546
  generatedAssets
38490
38547
  .get(config)
38491
38548
  .set(referenceId, { originalName, isEntry });
@@ -38558,19 +38615,12 @@ function cssPostPlugin(config) {
38558
38615
  // remove empty css chunks and their imports
38559
38616
  if (pureCssChunks.size) {
38560
38617
  // map each pure css chunk (rendered chunk) to it's corresponding bundle
38561
- // chunk. we check that by comparing the `moduleIds` as they have different
38562
- // filenames (rendered chunk has the !~{XXX}~ placeholder)
38563
- const pureCssChunkNames = [];
38564
- for (const pureCssChunk of pureCssChunks) {
38565
- for (const key in bundle) {
38566
- const bundleChunk = bundle[key];
38567
- if (bundleChunk.type === 'chunk' &&
38568
- arrayEqual(bundleChunk.moduleIds, pureCssChunk.moduleIds)) {
38569
- pureCssChunkNames.push(key);
38570
- break;
38571
- }
38572
- }
38573
- }
38618
+ // chunk. we check that by `preliminaryFileName` as they have different
38619
+ // `filename`s (rendered chunk has the !~{XXX}~ placeholder)
38620
+ const prelimaryNameToChunkMap = Object.fromEntries(Object.values(bundle)
38621
+ .filter((chunk) => chunk.type === 'chunk')
38622
+ .map((chunk) => [chunk.preliminaryFileName, chunk.fileName]));
38623
+ const pureCssChunkNames = [...pureCssChunks].map((pureCssChunk) => prelimaryNameToChunkMap[pureCssChunk.fileName]);
38574
38624
  const emptyChunkFiles = pureCssChunkNames
38575
38625
  .map((file) => path$o.basename(file))
38576
38626
  .join('|')
@@ -38912,8 +38962,8 @@ function createCachedImport(imp) {
38912
38962
  return cached;
38913
38963
  };
38914
38964
  }
38915
- const importPostcssImport = createCachedImport(() => import('./dep-d502c17d.js').then(function (n) { return n.i; }));
38916
- const importPostcssModules = createCachedImport(() => import('./dep-def3b363.js').then(function (n) { return n.i; }));
38965
+ const importPostcssImport = createCachedImport(() => import('./dep-1d1f72b4.js').then(function (n) { return n.i; }));
38966
+ const importPostcssModules = createCachedImport(() => import('./dep-3d0847ee.js').then(function (n) { return n.i; }));
38917
38967
  const importPostcss = createCachedImport(() => import('postcss'));
38918
38968
  /**
38919
38969
  * @experimental
@@ -38956,7 +39006,7 @@ async function finalizeCss(css, minify, config) {
38956
39006
  css = await hoistAtRules(css);
38957
39007
  }
38958
39008
  if (minify && config.build.cssMinify) {
38959
- css = await minifyCSS(css, config);
39009
+ css = await minifyCSS(css, config, false);
38960
39010
  }
38961
39011
  return css;
38962
39012
  }
@@ -39117,7 +39167,10 @@ async function doImportCSSReplace(rawUrl, matched, replacer) {
39117
39167
  }
39118
39168
  return `@import ${wrap}${await replacer(rawUrl)}${wrap}`;
39119
39169
  }
39120
- async function minifyCSS(css, config) {
39170
+ async function minifyCSS(css, config, inlined) {
39171
+ // We want inlined CSS to not end with a linebreak, while ensuring that
39172
+ // regular CSS assets do end with a linebreak.
39173
+ // See https://github.com/vitejs/vite/pull/13893#issuecomment-1678628198
39121
39174
  if (config.build.cssMinify === 'lightningcss') {
39122
39175
  const { code, warnings } = (await importLightningCSS()).transform({
39123
39176
  ...config.css?.lightningcss,
@@ -39132,7 +39185,8 @@ async function minifyCSS(css, config) {
39132
39185
  .map((w) => w.message)
39133
39186
  .join('\n')}`));
39134
39187
  }
39135
- return code.toString();
39188
+ // LightningCSS output does not return a linebreak at the end
39189
+ return code.toString() + (inlined ? '' : '\n');
39136
39190
  }
39137
39191
  try {
39138
39192
  const { code, warnings } = await transform$1(css, {
@@ -39144,7 +39198,8 @@ async function minifyCSS(css, config) {
39144
39198
  const msgs = await formatMessages(warnings, { kind: 'warning' });
39145
39199
  config.logger.warn(colors$1.yellow(`warnings when minifying css:\n${msgs.join('\n')}`));
39146
39200
  }
39147
- return code;
39201
+ // esbuild output does return a linebreak at the end
39202
+ return inlined ? code.trimEnd() : code;
39148
39203
  }
39149
39204
  catch (e) {
39150
39205
  if (e.errors) {
@@ -39435,6 +39490,9 @@ let ViteLessManager;
39435
39490
  function createViteLessPlugin(less, rootFile, alias, resolvers) {
39436
39491
  if (!ViteLessManager) {
39437
39492
  ViteLessManager = class ViteManager extends less.FileManager {
39493
+ resolvers;
39494
+ rootFile;
39495
+ alias;
39438
39496
  constructor(rootFile, resolvers, alias) {
39439
39497
  super();
39440
39498
  this.rootFile = rootFile;
@@ -39571,11 +39629,13 @@ async function compileLightningCSS(id, src, config, urlReplacer) {
39571
39629
  ? (await importLightningCSS()).transformStyleAttribute({
39572
39630
  filename,
39573
39631
  code: Buffer.from(src),
39574
- targets: config.css?.lightningcss?.targets,
39575
39632
  minify: config.isProduction && !!config.build.cssMinify,
39633
+ targets: config.css?.lightningcss?.targets,
39576
39634
  analyzeDependencies: true,
39635
+ visitor: config.css?.lightningcss?.visitor,
39577
39636
  })
39578
39637
  : await (await importLightningCSS()).bundleAsync({
39638
+ ...config.css?.lightningcss,
39579
39639
  filename,
39580
39640
  resolver: {
39581
39641
  read(filePath) {
@@ -39601,14 +39661,12 @@ async function compileLightningCSS(id, src, config, urlReplacer) {
39601
39661
  return id;
39602
39662
  },
39603
39663
  },
39604
- targets: config.css?.lightningcss?.targets,
39605
39664
  minify: config.isProduction && !!config.build.cssMinify,
39606
39665
  sourceMap: config.css?.devSourcemap,
39607
39666
  analyzeDependencies: true,
39608
39667
  cssModules: cssModuleRE.test(id)
39609
39668
  ? config.css?.lightningcss?.cssModules ?? true
39610
39669
  : undefined,
39611
- drafts: config.css?.lightningcss?.drafts,
39612
39670
  });
39613
39671
  let css = res.code.toString();
39614
39672
  for (const dep of res.dependencies) {
@@ -40737,8 +40795,11 @@ function getAffectedGlobModules(file, server) {
40737
40795
  for (const [id, allGlobs] of server._importGlobMap) {
40738
40796
  // (glob1 || glob2) && !glob3 && !glob4...
40739
40797
  if (allGlobs.some(({ affirmed, negated }) => (!affirmed.length || affirmed.some((glob) => isMatch$1(file, glob))) &&
40740
- (!negated.length || negated.every((glob) => isMatch$1(file, glob)))))
40741
- modules.push(...(server.moduleGraph.getModulesByFile(id) || []));
40798
+ (!negated.length || negated.every((glob) => isMatch$1(file, glob))))) {
40799
+ const mod = server.moduleGraph.getModuleById(id);
40800
+ if (mod)
40801
+ modules.push(mod);
40802
+ }
40742
40803
  }
40743
40804
  modules.forEach((i) => {
40744
40805
  if (i?.file)
@@ -40775,7 +40836,7 @@ function importGlobPlugin(config) {
40775
40836
  },
40776
40837
  };
40777
40838
  }
40778
- const importGlobRE = /\bimport\.meta\.(glob|globEager|globEagerDefault)(?:<\w+>)?\s*\(/g;
40839
+ const importGlobRE = /\bimport\.meta\.glob(?:<\w+>)?\s*\(/g;
40779
40840
  const knownOptions = {
40780
40841
  as: ['string'],
40781
40842
  eager: ['boolean'],
@@ -40840,7 +40901,6 @@ async function parseImportGlob(code, importer, root, resolveId) {
40840
40901
  }
40841
40902
  const matches = Array.from(cleanCode.matchAll(importGlobRE));
40842
40903
  const tasks = matches.map(async (match, index) => {
40843
- const type = match[1];
40844
40904
  const start = match.index;
40845
40905
  const err = (msg) => {
40846
40906
  const e = new Error(`Invalid glob import syntax: ${msg}`);
@@ -40926,13 +40986,11 @@ async function parseImportGlob(code, importer, root, resolveId) {
40926
40986
  const globsResolved = await Promise.all(globs.map((glob) => toAbsoluteGlob(glob, root, importer, resolveId)));
40927
40987
  const isRelative = globs.every((i) => '.!'.includes(i[0]));
40928
40988
  return {
40929
- match,
40930
40989
  index,
40931
40990
  globs,
40932
40991
  globsResolved,
40933
40992
  isRelative,
40934
40993
  options,
40935
- type,
40936
40994
  start,
40937
40995
  end,
40938
40996
  };
@@ -40959,15 +41017,6 @@ async function transformGlobImport(code, id, root, resolveId, isProduction, rest
40959
41017
  const dir = isVirtual ? undefined : dirname(id);
40960
41018
  const matches = await parseImportGlob(code, isVirtual ? undefined : id, root, resolveId);
40961
41019
  const matchedFiles = new Set();
40962
- // TODO: backwards compatibility
40963
- matches.forEach((i) => {
40964
- if (i.type === 'globEager')
40965
- i.options.eager = true;
40966
- if (i.type === 'globEagerDefault') {
40967
- i.options.eager = true;
40968
- i.options.import = 'default';
40969
- }
40970
- });
40971
41020
  if (!matches.length)
40972
41021
  return null;
40973
41022
  const s = new MagicString(code);
@@ -41026,7 +41075,7 @@ async function transformGlobImport(code, id, root, resolveId, isProduction, rest
41026
41075
  }
41027
41076
  importPath = `${importPath}${importQuery}`;
41028
41077
  const isCSS = !query && isCSSRequest(file) && !isModuleCSSRequest(file);
41029
- includesCSS || (includesCSS = isCSS);
41078
+ includesCSS ||= isCSS;
41030
41079
  const importKey = options.import && options.import !== '*'
41031
41080
  ? options.import
41032
41081
  : undefined;
@@ -42231,11 +42280,12 @@ function clientInjectionsPlugin(config) {
42231
42280
  const timeout = hmrConfig?.timeout || 30000;
42232
42281
  const overlay = hmrConfig?.overlay !== false;
42233
42282
  const isHmrServerSpecified = !!hmrConfig?.server;
42283
+ const hmrConfigName = path$o.basename(config.configFile || 'vite.config.js');
42234
42284
  // hmr.clientPort -> hmr.port
42235
42285
  // -> (24678 if middleware mode and HMR server is not specified) -> new URL(import.meta.url).port
42236
42286
  let port = hmrConfig?.clientPort || hmrConfig?.port || null;
42237
42287
  if (config.server.middlewareMode && !isHmrServerSpecified) {
42238
- port || (port = 24678);
42288
+ port ||= 24678;
42239
42289
  }
42240
42290
  let directTarget = hmrConfig?.host || resolvedServerHostname;
42241
42291
  directTarget += `:${hmrConfig?.port || resolvedServerPort}`;
@@ -42256,6 +42306,7 @@ function clientInjectionsPlugin(config) {
42256
42306
  const hmrBaseReplacement = escapeReplacement(hmrBase);
42257
42307
  const hmrTimeoutReplacement = escapeReplacement(timeout);
42258
42308
  const hmrEnableOverlayReplacement = escapeReplacement(overlay);
42309
+ const hmrConfigNameReplacement = escapeReplacement(hmrConfigName);
42259
42310
  injectConfigValues = (code) => {
42260
42311
  return code
42261
42312
  .replace(`__MODE__`, modeReplacement)
@@ -42268,7 +42319,8 @@ function clientInjectionsPlugin(config) {
42268
42319
  .replace(`__HMR_DIRECT_TARGET__`, hmrDirectTargetReplacement)
42269
42320
  .replace(`__HMR_BASE__`, hmrBaseReplacement)
42270
42321
  .replace(`__HMR_TIMEOUT__`, hmrTimeoutReplacement)
42271
- .replace(`__HMR_ENABLE_OVERLAY__`, hmrEnableOverlayReplacement);
42322
+ .replace(`__HMR_ENABLE_OVERLAY__`, hmrEnableOverlayReplacement)
42323
+ .replace(`__HMR_CONFIG_NAME__`, hmrConfigNameReplacement);
42272
42324
  };
42273
42325
  },
42274
42326
  transform(code, id, options) {
@@ -42580,7 +42632,7 @@ function webWorkerPlugin(config) {
42580
42632
  ? 'module'
42581
42633
  : 'classic'
42582
42634
  : 'module';
42583
- const workerOptions = workerType === 'classic' ? '' : ',{type: "module"}';
42635
+ const workerTypeOption = workerType === 'classic' ? undefined : 'module';
42584
42636
  if (isBuild) {
42585
42637
  getDepsOptimizer(config, ssr)?.registerWorkersSource(id);
42586
42638
  if (query.inline != null) {
@@ -42591,21 +42643,33 @@ function webWorkerPlugin(config) {
42591
42643
  workerConstructor === 'Worker'
42592
42644
  ? `${encodedJs}
42593
42645
  const blob = typeof window !== "undefined" && window.Blob && new Blob([atob(encodedJs)], { type: "text/javascript;charset=utf-8" });
42594
- export default function WorkerWrapper() {
42646
+ export default function WorkerWrapper(options) {
42595
42647
  let objURL;
42596
42648
  try {
42597
42649
  objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob);
42598
42650
  if (!objURL) throw ''
42599
- return new ${workerConstructor}(objURL)
42651
+ return new ${workerConstructor}(objURL, { name: options?.name })
42600
42652
  } catch(e) {
42601
- return new ${workerConstructor}("data:application/javascript;base64," + encodedJs${workerOptions});
42653
+ return new ${workerConstructor}(
42654
+ "data:application/javascript;base64," + encodedJs,
42655
+ {
42656
+ ${workerTypeOption ? `type: "${workerTypeOption}",` : ''}
42657
+ name: options?.name
42658
+ }
42659
+ );
42602
42660
  } finally {
42603
42661
  objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);
42604
42662
  }
42605
42663
  }`
42606
42664
  : `${encodedJs}
42607
- export default function WorkerWrapper() {
42608
- return new ${workerConstructor}("data:application/javascript;base64," + encodedJs${workerOptions});
42665
+ export default function WorkerWrapper(options) {
42666
+ return new ${workerConstructor}(
42667
+ "data:application/javascript;base64," + encodedJs,
42668
+ {
42669
+ ${workerTypeOption ? `type: "${workerTypeOption}",` : ''}
42670
+ name: options?.name
42671
+ }
42672
+ );
42609
42673
  }
42610
42674
  `;
42611
42675
  return {
@@ -42630,8 +42694,14 @@ function webWorkerPlugin(config) {
42630
42694
  };
42631
42695
  }
42632
42696
  return {
42633
- code: `export default function WorkerWrapper() {
42634
- return new ${workerConstructor}(${JSON.stringify(url)}${workerOptions})
42697
+ code: `export default function WorkerWrapper(options) {
42698
+ return new ${workerConstructor}(
42699
+ ${JSON.stringify(url)},
42700
+ {
42701
+ ${workerTypeOption ? `type: "${workerTypeOption}",` : ''}
42702
+ name: options?.name
42703
+ }
42704
+ );
42635
42705
  }`,
42636
42706
  map: { mappings: '' }, // Empty sourcemap to suppress Rollup warning
42637
42707
  };
@@ -42912,7 +42982,6 @@ function definePlugin(config) {
42912
42982
  };
42913
42983
  }
42914
42984
 
42915
- const ignoreFlagRE = /\/\*\s*@vite-ignore\s*\*\//;
42916
42985
  function err(e, pos) {
42917
42986
  const error = new Error(e);
42918
42987
  error.pos = pos;
@@ -42949,7 +43018,7 @@ function getWorkerType(raw, clean, i) {
42949
43018
  const workerOptString = raw
42950
43019
  .substring(commaIndex + 1, endIndex)
42951
43020
  .replace(/\}[\s\S]*,/g, '}'); // strip trailing comma for parsing
42952
- const hasViteIgnore = ignoreFlagRE.test(workerOptString);
43021
+ const hasViteIgnore = hasViteIgnoreRE.test(workerOptString);
42953
43022
  if (hasViteIgnore) {
42954
43023
  return 'ignore';
42955
43024
  }
@@ -42999,7 +43068,7 @@ function workerImportMetaUrlPlugin(config) {
42999
43068
  if (rawUrl[0] === '`' && rawUrl.includes('${')) {
43000
43069
  this.error(`\`new URL(url, import.meta.url)\` is not supported in dynamic template string.`, urlIndex);
43001
43070
  }
43002
- s || (s = new MagicString(code));
43071
+ s ||= new MagicString(code);
43003
43072
  const workerType = getWorkerType(code, cleanString, index + allExp.length);
43004
43073
  const url = rawUrl.slice(1, -1);
43005
43074
  let file;
@@ -43008,15 +43077,16 @@ function workerImportMetaUrlPlugin(config) {
43008
43077
  file = tryFsResolve(file, fsResolveOptions) ?? file;
43009
43078
  }
43010
43079
  else {
43011
- workerResolver ?? (workerResolver = config.createResolver({
43080
+ workerResolver ??= config.createResolver({
43012
43081
  extensions: [],
43013
43082
  tryIndex: false,
43014
43083
  preferRelative: true,
43015
- }));
43084
+ });
43016
43085
  file = await workerResolver(url, id);
43017
- file ?? (file = url[0] === '/'
43018
- ? slash$1(path$o.join(config.publicDir, url))
43019
- : slash$1(path$o.resolve(path$o.dirname(id), url)));
43086
+ file ??=
43087
+ url[0] === '/'
43088
+ ? slash$1(path$o.join(config.publicDir, url))
43089
+ : slash$1(path$o.resolve(path$o.dirname(id), url));
43020
43090
  }
43021
43091
  let builtUrl;
43022
43092
  if (isBuild) {
@@ -43120,16 +43190,17 @@ function assetImportMetaUrlPlugin(config) {
43120
43190
  file = tryFsResolve(file, fsResolveOptions) ?? file;
43121
43191
  }
43122
43192
  else {
43123
- assetResolver ?? (assetResolver = config.createResolver({
43193
+ assetResolver ??= config.createResolver({
43124
43194
  extensions: [],
43125
43195
  mainFields: [],
43126
43196
  tryIndex: false,
43127
43197
  preferRelative: true,
43128
- }));
43198
+ });
43129
43199
  file = await assetResolver(url, id);
43130
- file ?? (file = url[0] === '/'
43131
- ? slash$1(path$o.join(config.publicDir, url))
43132
- : slash$1(path$o.resolve(path$o.dirname(id), url)));
43200
+ file ??=
43201
+ url[0] === '/'
43202
+ ? slash$1(path$o.join(config.publicDir, url))
43203
+ : slash$1(path$o.resolve(path$o.dirname(id), url));
43133
43204
  }
43134
43205
  // Get final asset URL. If the file does not exist,
43135
43206
  // we fall back to the initial URL and let it resolve in runtime
@@ -43468,7 +43539,10 @@ function dynamicImportVarsPlugin(config) {
43468
43539
  if (dynamicIndex === -1 || source[start] !== '`') {
43469
43540
  continue;
43470
43541
  }
43471
- s || (s = new MagicString(source));
43542
+ if (hasViteIgnoreRE.test(source.slice(expStart, expEnd))) {
43543
+ continue;
43544
+ }
43545
+ s ||= new MagicString(source);
43472
43546
  let result;
43473
43547
  try {
43474
43548
  // When import string is using backticks, es-module-lexer `end` captures
@@ -43846,15 +43920,15 @@ async function createPluginContainer(config, moduleGraph, watcher) {
43846
43920
  // active plugin in that pipeline can be tracked in a concurrency-safe manner.
43847
43921
  // using a class to make creating new contexts more efficient
43848
43922
  class Context {
43923
+ meta = minimalContext.meta;
43924
+ ssr = false;
43925
+ _scan = false;
43926
+ _activePlugin;
43927
+ _activeId = null;
43928
+ _activeCode = null;
43929
+ _resolveSkips;
43930
+ _addedImports = null;
43849
43931
  constructor(initialPlugin) {
43850
- this.meta = minimalContext.meta;
43851
- this.ssr = false;
43852
- this._scan = false;
43853
- this._activeId = null;
43854
- this._activeCode = null;
43855
- this._addedImports = null;
43856
- this.debug = noop$3;
43857
- this.info = noop$3;
43858
43932
  this._activePlugin = initialPlugin || null;
43859
43933
  }
43860
43934
  parse(code, opts = {}) {
@@ -43939,6 +44013,8 @@ async function createPluginContainer(config, moduleGraph, watcher) {
43939
44013
  // the the error middleware.
43940
44014
  throw formatError(e, position, this);
43941
44015
  }
44016
+ debug = noop$3;
44017
+ info = noop$3;
43942
44018
  }
43943
44019
  function formatError(e, position, ctx) {
43944
44020
  const err = (typeof e === 'string' ? new Error(e) : e);
@@ -43999,7 +44075,7 @@ async function createPluginContainer(config, moduleGraph, watcher) {
43999
44075
  typeof err.loc?.line === 'number' &&
44000
44076
  typeof err.loc?.column === 'number') {
44001
44077
  const rawSourceMap = ctx._getCombinedSourcemap();
44002
- if (rawSourceMap) {
44078
+ if (rawSourceMap && 'version' in rawSourceMap) {
44003
44079
  const traced = new TraceMap(rawSourceMap);
44004
44080
  const { source, line, column } = originalPositionFor$1(traced, {
44005
44081
  line: Number(err.loc.line),
@@ -44036,11 +44112,13 @@ async function createPluginContainer(config, moduleGraph, watcher) {
44036
44112
  return err;
44037
44113
  }
44038
44114
  class TransformContext extends Context {
44115
+ filename;
44116
+ originalCode;
44117
+ originalSourcemap = null;
44118
+ sourcemapChain = [];
44119
+ combinedMap = null;
44039
44120
  constructor(filename, code, inMap) {
44040
44121
  super();
44041
- this.originalSourcemap = null;
44042
- this.sourcemapChain = [];
44043
- this.combinedMap = null;
44044
44122
  this.filename = filename;
44045
44123
  this.originalCode = code;
44046
44124
  if (inMap) {
@@ -44051,7 +44129,7 @@ async function createPluginContainer(config, moduleGraph, watcher) {
44051
44129
  this.sourcemapChain.push(inMap);
44052
44130
  }
44053
44131
  }
44054
- _getCombinedSourcemap(createIfNull = false) {
44132
+ _getCombinedSourcemap() {
44055
44133
  if (debugSourcemapCombine &&
44056
44134
  debugSourcemapCombineFilter &&
44057
44135
  this.filename.includes(debugSourcemapCombineFilter)) {
@@ -44061,13 +44139,24 @@ async function createPluginContainer(config, moduleGraph, watcher) {
44061
44139
  debugSourcemapCombine('----------');
44062
44140
  }
44063
44141
  let combinedMap = this.combinedMap;
44142
+ // { mappings: '' }
44143
+ if (combinedMap &&
44144
+ !('version' in combinedMap) &&
44145
+ combinedMap.mappings === '') {
44146
+ this.sourcemapChain.length = 0;
44147
+ return combinedMap;
44148
+ }
44064
44149
  for (let m of this.sourcemapChain) {
44065
44150
  if (typeof m === 'string')
44066
44151
  m = JSON.parse(m);
44067
44152
  if (!('version' in m)) {
44153
+ // { mappings: '' }
44154
+ if (m.mappings === '') {
44155
+ combinedMap = { mappings: '' };
44156
+ break;
44157
+ }
44068
44158
  // empty, nullified source map
44069
- combinedMap = this.combinedMap = null;
44070
- this.sourcemapChain.length = 0;
44159
+ combinedMap = null;
44071
44160
  break;
44072
44161
  }
44073
44162
  if (!combinedMap) {
@@ -44080,15 +44169,6 @@ async function createPluginContainer(config, moduleGraph, watcher) {
44080
44169
  ]);
44081
44170
  }
44082
44171
  }
44083
- if (!combinedMap) {
44084
- return createIfNull
44085
- ? new MagicString(this.originalCode).generateMap({
44086
- includeContent: true,
44087
- hires: 'boundary',
44088
- source: cleanUrl(this.filename),
44089
- })
44090
- : null;
44091
- }
44092
44172
  if (combinedMap !== this.combinedMap) {
44093
44173
  this.combinedMap = combinedMap;
44094
44174
  this.sourcemapChain.length = 0;
@@ -44096,7 +44176,15 @@ async function createPluginContainer(config, moduleGraph, watcher) {
44096
44176
  return this.combinedMap;
44097
44177
  }
44098
44178
  getCombinedSourcemap() {
44099
- return this._getCombinedSourcemap(true);
44179
+ const map = this._getCombinedSourcemap();
44180
+ if (!map || (!('version' in map) && map.mappings === '')) {
44181
+ return new MagicString(this.originalCode).generateMap({
44182
+ includeContent: true,
44183
+ hires: 'boundary',
44184
+ source: cleanUrl(this.filename),
44185
+ });
44186
+ }
44187
+ return map;
44100
44188
  }
44101
44189
  }
44102
44190
  let closed = false;
@@ -46009,7 +46097,11 @@ function newDepOptimizationProcessing() {
46009
46097
  }
46010
46098
  // Convert to { id: src }
46011
46099
  function depsFromOptimizedDepInfo(depsInfo) {
46012
- return Object.fromEntries(Object.entries(depsInfo).map((d) => [d[0], d[1].src]));
46100
+ const obj = {};
46101
+ for (const key in depsInfo) {
46102
+ obj[key] = depsInfo[key].src;
46103
+ }
46104
+ return obj;
46013
46105
  }
46014
46106
  function getOptimizedDepPath(id, config, ssr) {
46015
46107
  return normalizePath$3(path$o.resolve(getDepsCacheDir(config, ssr), flattenId(id) + '.js'));
@@ -46287,7 +46379,7 @@ function findOptimizedDepInfoInRecord(dependenciesInfo, callbackFn) {
46287
46379
  async function optimizedDepNeedsInterop(metadata, file, config, ssr) {
46288
46380
  const depInfo = optimizedDepInfoFromFile(metadata, file);
46289
46381
  if (depInfo?.src && depInfo.needsInterop === undefined) {
46290
- depInfo.exportsData ?? (depInfo.exportsData = extractExportsData(depInfo.src, config, ssr));
46382
+ depInfo.exportsData ??= extractExportsData(depInfo.src, config, ssr);
46291
46383
  depInfo.needsInterop = needsInterop(config, ssr, depInfo.id, await depInfo.exportsData);
46292
46384
  }
46293
46385
  return depInfo?.needsInterop;
@@ -46498,7 +46590,7 @@ function buildImportAnalysisPlugin(config) {
46498
46590
  ? // If `experimental.renderBuiltUrl` or `build.modulePreload.resolveDependencies` are used
46499
46591
  // the dependencies are already resolved. To avoid the need for `new URL(dep, import.meta.url)`
46500
46592
  // a helper `__vitePreloadRelativeDep` is used to resolve from relative paths which can be minimized.
46501
- `function(dep, importerUrl) { return dep.startsWith('.') ? new URL(dep, importerUrl).href : dep }`
46593
+ `function(dep, importerUrl) { return dep[0] === '.' ? new URL(dep, importerUrl).href : dep }`
46502
46594
  : optimizeModulePreloadRelativePaths
46503
46595
  ? // If there isn't custom resolvers affecting the deps list, deps in the list are relative
46504
46596
  // to the current chunk and are resolved to absolute URL by the __vitePreload helper itself.
@@ -46897,7 +46989,7 @@ function ssrManifestPlugin(config) {
46897
46989
  if (chunk.code.includes(preloadMethod)) {
46898
46990
  // generate css deps map
46899
46991
  const code = chunk.code;
46900
- let imports;
46992
+ let imports = [];
46901
46993
  try {
46902
46994
  imports = parse$e(code)[0].filter((i) => i.n && i.d > -1);
46903
46995
  }
@@ -47165,11 +47257,18 @@ function send$2(req, res, content, type, options) {
47165
47257
  }
47166
47258
  }
47167
47259
  // inject source map reference
47168
- if (map && map.mappings) {
47260
+ if (map && 'version' in map && map.mappings) {
47169
47261
  if (type === 'js' || type === 'css') {
47170
47262
  content = getCodeWithSourcemap(type, content.toString(), map);
47171
47263
  }
47172
47264
  }
47265
+ else {
47266
+ if (type === 'js' && (!map || map.mappings !== '')) {
47267
+ const urlWithoutTimestamp = removeTimestampQuery(req.url);
47268
+ const ms = new MagicString(content.toString());
47269
+ content = getCodeWithSourcemap(type, content.toString(), ms.generateMap({ source: urlWithoutTimestamp, hires: 'boundary' }));
47270
+ }
47271
+ }
47173
47272
  res.statusCode = 200;
47174
47273
  res.end(content);
47175
47274
  return;
@@ -47838,7 +47937,6 @@ async function build(inlineConfig = {}) {
47838
47937
  await initDepsOptimizer(config);
47839
47938
  }
47840
47939
  const rollupOptions = {
47841
- context: 'globalThis',
47842
47940
  preserveEntrySignatures: ssr
47843
47941
  ? 'allow-extension'
47844
47942
  : libOptions
@@ -48035,7 +48133,7 @@ function resolveLibFilename(libOptions, format, entryName, root, extension, pack
48035
48133
  : entryName);
48036
48134
  if (!name)
48037
48135
  throw new Error('Name in package.json is required if option "build.lib.fileName" is not provided.');
48038
- extension ?? (extension = resolveOutputJsExtension(format, packageJson?.type));
48136
+ extension ??= resolveOutputJsExtension(format, packageJson?.type);
48039
48137
  if (format === 'cjs' || format === 'es') {
48040
48138
  return `${name}.${extension}`;
48041
48139
  }
@@ -54894,7 +54992,7 @@ async function loadAndTransform(id, url, server, options, timestamp, mod, resolv
54894
54992
  if (server._restartPromise && !ssr)
54895
54993
  throwClosedServerError();
54896
54994
  // ensure module in graph after successful load
54897
- mod ?? (mod = await moduleGraph._ensureEntryFromUrl(url, ssr, undefined, resolved));
54995
+ mod ??= await moduleGraph._ensureEntryFromUrl(url, ssr, undefined, resolved);
54898
54996
  ensureWatchedFile(watcher, mod.file, root);
54899
54997
  // transform
54900
54998
  const transformStart = debugTransform ? performance.now() : 0;
@@ -54913,22 +55011,31 @@ async function loadAndTransform(id, url, server, options, timestamp, mod, resolv
54913
55011
  code = transformResult.code;
54914
55012
  map = transformResult.map;
54915
55013
  }
54916
- if (map && mod.file) {
54917
- map = (typeof map === 'string' ? JSON.parse(map) : map);
54918
- if (map.mappings) {
54919
- await injectSourcesContent(map, mod.file, logger);
55014
+ let normalizedMap;
55015
+ if (typeof map === 'string') {
55016
+ normalizedMap = JSON.parse(map);
55017
+ }
55018
+ else if (map) {
55019
+ normalizedMap = map;
55020
+ }
55021
+ else {
55022
+ normalizedMap = null;
55023
+ }
55024
+ if (normalizedMap && 'version' in normalizedMap && mod.file) {
55025
+ if (normalizedMap.mappings) {
55026
+ await injectSourcesContent(normalizedMap, mod.file, logger);
54920
55027
  }
54921
55028
  const sourcemapPath = `${mod.file}.map`;
54922
- applySourcemapIgnoreList(map, sourcemapPath, config.server.sourcemapIgnoreList, logger);
55029
+ applySourcemapIgnoreList(normalizedMap, sourcemapPath, config.server.sourcemapIgnoreList, logger);
54923
55030
  if (path$o.isAbsolute(mod.file)) {
54924
- for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
54925
- const sourcePath = map.sources[sourcesIndex];
55031
+ for (let sourcesIndex = 0; sourcesIndex < normalizedMap.sources.length; ++sourcesIndex) {
55032
+ const sourcePath = normalizedMap.sources[sourcesIndex];
54926
55033
  if (sourcePath) {
54927
55034
  // Rewrite sources to relative paths to give debuggers the chance
54928
55035
  // to resolve and display them in a meaningful way (rather than
54929
55036
  // with absolute paths).
54930
55037
  if (path$o.isAbsolute(sourcePath)) {
54931
- map.sources[sourcesIndex] = path$o.relative(path$o.dirname(mod.file), sourcePath);
55038
+ normalizedMap.sources[sourcesIndex] = path$o.relative(path$o.dirname(mod.file), sourcePath);
54932
55039
  }
54933
55040
  }
54934
55041
  }
@@ -54937,12 +55044,12 @@ async function loadAndTransform(id, url, server, options, timestamp, mod, resolv
54937
55044
  if (server._restartPromise && !ssr)
54938
55045
  throwClosedServerError();
54939
55046
  const result = ssr && !server.config.experimental.skipSsrTransform
54940
- ? await server.ssrTransform(code, map, url, originalCode)
54941
- : {
55047
+ ? await server.ssrTransform(code, normalizedMap, url, originalCode)
55048
+ : ({
54942
55049
  code,
54943
- map,
55050
+ map: normalizedMap,
54944
55051
  etag: getEtag(code, { weak: true }),
54945
- };
55052
+ });
54946
55053
  // Only cache the result if the module wasn't invalidated while it was
54947
55054
  // being processed, so it is re-processed next time if it is stale
54948
55055
  if (timestamp > mod.lastInvalidationTimestamp) {
@@ -55451,7 +55558,10 @@ async function ssrTransformScript(code, inMap, url, originalCode) {
55451
55558
  },
55452
55559
  });
55453
55560
  let map = s.generateMap({ hires: 'boundary' });
55454
- if (inMap && inMap.mappings && inMap.sources.length > 0) {
55561
+ if (inMap &&
55562
+ inMap.mappings &&
55563
+ 'sources' in inMap &&
55564
+ inMap.sources.length > 0) {
55455
55565
  map = combineSourcemaps(url, [
55456
55566
  {
55457
55567
  ...map,
@@ -55909,7 +56019,7 @@ async function instantiateModule(url, server, context = { global }, urlStack = [
55909
56019
  }
55910
56020
  }
55911
56021
  let sourceMapSuffix = '';
55912
- if (result.map) {
56022
+ if (result.map && 'version' in result.map) {
55913
56023
  const moduleSourceMap = Object.assign({}, result.map, {
55914
56024
  // currently we need to offset the line
55915
56025
  // https://github.com/nodejs/node/issues/43047#issuecomment-1180632750
@@ -57260,8 +57370,13 @@ const BASE_PREVIEW_SHORTCUTS = [
57260
57370
  key: 'o',
57261
57371
  description: 'open in browser',
57262
57372
  action(server) {
57263
- const url = server.resolvedUrls.local[0] ?? server.resolvedUrls.network[0];
57264
- openBrowser(url, true, server.config.logger);
57373
+ const url = server.resolvedUrls?.local[0] ?? server.resolvedUrls?.network[0];
57374
+ if (url) {
57375
+ openBrowser(url, true, server.config.logger);
57376
+ }
57377
+ else {
57378
+ server.config.logger.warn('No URL available to open in browser');
57379
+ }
57265
57380
  },
57266
57381
  },
57267
57382
  {
@@ -61643,6 +61758,7 @@ function createWebSocketServer(server, config, httpsOptions) {
61643
61758
  // TODO: the main server port may not have been chosen yet as it may use the next available
61644
61759
  const portsAreCompatible = !hmrPort || hmrPort === config.server.port;
61645
61760
  const wsServer = hmrServer || (portsAreCompatible && server);
61761
+ let hmrServerWsListener;
61646
61762
  const customListeners = new Map();
61647
61763
  const clientsMap = new WeakMap();
61648
61764
  const port = hmrPort || 24678;
@@ -61654,14 +61770,15 @@ function createWebSocketServer(server, config, httpsOptions) {
61654
61770
  hmrBase = path$o.posix.join(hmrBase, hmrPath);
61655
61771
  }
61656
61772
  wss = new WebSocketServerRaw({ noServer: true });
61657
- wsServer.on('upgrade', (req, socket, head) => {
61773
+ hmrServerWsListener = (req, socket, head) => {
61658
61774
  if (req.headers['sec-websocket-protocol'] === HMR_HEADER &&
61659
61775
  req.url === hmrBase) {
61660
61776
  wss.handleUpgrade(req, socket, head, (ws) => {
61661
61777
  wss.emit('connection', ws, req);
61662
61778
  });
61663
61779
  }
61664
- });
61780
+ };
61781
+ wsServer.on('upgrade', hmrServerWsListener);
61665
61782
  }
61666
61783
  else {
61667
61784
  // http server request handler keeps the same with
@@ -61803,6 +61920,11 @@ function createWebSocketServer(server, config, httpsOptions) {
61803
61920
  });
61804
61921
  },
61805
61922
  close() {
61923
+ // should remove listener if hmr.server is set
61924
+ // otherwise the old listener swallows all WebSocket connections
61925
+ if (hmrServerWsListener && wsServer) {
61926
+ wsServer.off('upgrade', hmrServerWsListener);
61927
+ }
61806
61928
  return new Promise((resolve, reject) => {
61807
61929
  wss.clients.forEach((client) => {
61808
61930
  client.terminate();
@@ -64149,9 +64271,10 @@ var history = /*@__PURE__*/getDefaultExportFromCjs(libExports);
64149
64271
 
64150
64272
  function htmlFallbackMiddleware(root, spaFallback) {
64151
64273
  const historyHtmlFallbackMiddleware = history({
64274
+ disableDotRule: true,
64152
64275
  logger: createDebugger('vite:html-fallback'),
64153
- // support /dir/ without explicit index.html
64154
64276
  rewrites: [
64277
+ // support /dir/ without explicit index.html
64155
64278
  {
64156
64279
  from: /\/$/,
64157
64280
  to({ parsedUrl, request }) {
@@ -64162,6 +64285,13 @@ function htmlFallbackMiddleware(root, spaFallback) {
64162
64285
  return spaFallback ? `/index.html` : request.url;
64163
64286
  },
64164
64287
  },
64288
+ // don't rewrite paths ending with .html
64289
+ {
64290
+ from: /\.html$/,
64291
+ to({ request }) {
64292
+ return request.url;
64293
+ },
64294
+ },
64165
64295
  ],
64166
64296
  });
64167
64297
  // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
@@ -64521,7 +64651,7 @@ const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl
64521
64651
  const result = await server.pluginContainer.transform(code, mod.id);
64522
64652
  let content = '';
64523
64653
  if (result) {
64524
- if (result.map) {
64654
+ if (result.map && 'version' in result.map) {
64525
64655
  if (result.map.mappings) {
64526
64656
  await injectSourcesContent(result.map, proxyModulePath, config.logger);
64527
64657
  }
@@ -64605,27 +64735,35 @@ function timeMiddleware(root) {
64605
64735
  }
64606
64736
 
64607
64737
  class ModuleNode {
64738
+ /**
64739
+ * Public served url path, starts with /
64740
+ */
64741
+ url;
64742
+ /**
64743
+ * Resolved file system path + query
64744
+ */
64745
+ id = null;
64746
+ file = null;
64747
+ type;
64748
+ info;
64749
+ meta;
64750
+ importers = new Set();
64751
+ clientImportedModules = new Set();
64752
+ ssrImportedModules = new Set();
64753
+ acceptedHmrDeps = new Set();
64754
+ acceptedHmrExports = null;
64755
+ importedBindings = null;
64756
+ isSelfAccepting;
64757
+ transformResult = null;
64758
+ ssrTransformResult = null;
64759
+ ssrModule = null;
64760
+ ssrError = null;
64761
+ lastHMRTimestamp = 0;
64762
+ lastInvalidationTimestamp = 0;
64608
64763
  /**
64609
64764
  * @param setIsSelfAccepting - set `false` to set `isSelfAccepting` later. e.g. #7870
64610
64765
  */
64611
64766
  constructor(url, setIsSelfAccepting = true) {
64612
- /**
64613
- * Resolved file system path + query
64614
- */
64615
- this.id = null;
64616
- this.file = null;
64617
- this.importers = new Set();
64618
- this.clientImportedModules = new Set();
64619
- this.ssrImportedModules = new Set();
64620
- this.acceptedHmrDeps = new Set();
64621
- this.acceptedHmrExports = null;
64622
- this.importedBindings = null;
64623
- this.transformResult = null;
64624
- this.ssrTransformResult = null;
64625
- this.ssrModule = null;
64626
- this.ssrError = null;
64627
- this.lastHMRTimestamp = 0;
64628
- this.lastInvalidationTimestamp = 0;
64629
64767
  this.url = url;
64630
64768
  this.type = isDirectCSSRequest(url) ? 'css' : 'js';
64631
64769
  if (setIsSelfAccepting) {
@@ -64641,21 +64779,22 @@ class ModuleNode {
64641
64779
  }
64642
64780
  }
64643
64781
  class ModuleGraph {
64782
+ resolveId;
64783
+ urlToModuleMap = new Map();
64784
+ idToModuleMap = new Map();
64785
+ // a single file may corresponds to multiple modules with different queries
64786
+ fileToModulesMap = new Map();
64787
+ safeModulesPath = new Set();
64788
+ /**
64789
+ * @internal
64790
+ */
64791
+ _unresolvedUrlToModuleMap = new Map();
64792
+ /**
64793
+ * @internal
64794
+ */
64795
+ _ssrUnresolvedUrlToModuleMap = new Map();
64644
64796
  constructor(resolveId) {
64645
64797
  this.resolveId = resolveId;
64646
- this.urlToModuleMap = new Map();
64647
- this.idToModuleMap = new Map();
64648
- // a single file may corresponds to multiple modules with different queries
64649
- this.fileToModulesMap = new Map();
64650
- this.safeModulesPath = new Set();
64651
- /**
64652
- * @internal
64653
- */
64654
- this._unresolvedUrlToModuleMap = new Map();
64655
- /**
64656
- * @internal
64657
- */
64658
- this._ssrUnresolvedUrlToModuleMap = new Map();
64659
64798
  }
64660
64799
  async getModuleByUrl(rawUrl, ssr) {
64661
64800
  // Quick path, if we already have a module for this rawUrl (even without extension)
@@ -65588,7 +65727,7 @@ var preview$1 = {
65588
65727
  };
65589
65728
 
65590
65729
  function resolveSSROptions(ssr, preserveSymlinks, buildSsrCjsExternalHeuristics) {
65591
- ssr ?? (ssr = {});
65730
+ ssr ??= {};
65592
65731
  const optimizeDeps = ssr.optimizeDeps ?? {};
65593
65732
  const format = buildSsrCjsExternalHeuristics ? 'cjs' : 'esm';
65594
65733
  const target = 'node';
@@ -65672,7 +65811,7 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development',
65672
65811
  optimizeDeps: { disabled: false },
65673
65812
  ssr: { optimizeDeps: { disabled: false } },
65674
65813
  });
65675
- config.build ?? (config.build = {});
65814
+ config.build ??= {};
65676
65815
  config.build.commonjsOptions = { include: [] };
65677
65816
  }
65678
65817
  // Define logger
@@ -66062,7 +66201,7 @@ async function bundleConfigFile(fileName, isESM) {
66062
66201
  entryPoints: [fileName],
66063
66202
  outfile: 'out.js',
66064
66203
  write: false,
66065
- target: ['node14.18', 'node16'],
66204
+ target: ['node18'],
66066
66205
  platform: 'node',
66067
66206
  bundle: true,
66068
66207
  format: isESM ? 'esm' : 'cjs',