vite 3.0.1 → 3.0.4

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.
@@ -11754,7 +11754,7 @@ const dataUrlRE = /^\s*data:/i;
11754
11754
  const isDataUrl = (url) => dataUrlRE.test(url);
11755
11755
  const virtualModuleRE = /^virtual-module:.*/;
11756
11756
  const virtualModulePrefix = 'virtual-module:';
11757
- const knownJsSrcRE = /\.((j|t)sx?|mjs|vue|marko|svelte|astro)($|\?)/;
11757
+ const knownJsSrcRE = /\.((j|t)sx?|m[jt]s|vue|marko|svelte|astro)($|\?)/;
11758
11758
  const isJSRequest = (url) => {
11759
11759
  url = cleanUrl(url);
11760
11760
  if (knownJsSrcRE.test(url)) {
@@ -12318,6 +12318,9 @@ function gracefulRemoveDir(dir, cb) {
12318
12318
  function emptyCssComments(raw) {
12319
12319
  return raw.replace(multilineCommentsRE$1, (s) => ' '.repeat(s.length));
12320
12320
  }
12321
+ function removeComments(raw) {
12322
+ return raw.replace(multilineCommentsRE$1, '').replace(singlelineCommentsRE$1, '');
12323
+ }
12321
12324
  function mergeConfigRecursively(defaults, overrides, rootPath) {
12322
12325
  const merged = { ...defaults };
12323
12326
  for (const key in overrides) {
@@ -13244,12 +13247,15 @@ async function transformWithEsbuild(code, filename, options, inMap) {
13244
13247
  if (ext === 'cjs' || ext === 'mjs') {
13245
13248
  loader = 'js';
13246
13249
  }
13250
+ else if (ext === 'cts' || ext === 'mts') {
13251
+ loader = 'ts';
13252
+ }
13247
13253
  else {
13248
13254
  loader = ext;
13249
13255
  }
13250
13256
  }
13251
13257
  let tsconfigRaw = options?.tsconfigRaw;
13252
- // if options provide tsconfigraw in string, it takes highest precedence
13258
+ // if options provide tsconfigRaw in string, it takes highest precedence
13253
13259
  if (typeof tsconfigRaw !== 'string') {
13254
13260
  // these fields would affect the compilation result
13255
13261
  // https://esbuild.github.io/content-types/#tsconfig-json
@@ -13329,7 +13335,7 @@ async function transformWithEsbuild(code, filename, options, inMap) {
13329
13335
  }
13330
13336
  }
13331
13337
  function esbuildPlugin(options = {}) {
13332
- const filter = createFilter(options.include || /\.(tsx?|jsx)$/, options.exclude || /\.js$/);
13338
+ const filter = createFilter(options.include || /\.(m?ts|[jt]sx)$/, options.exclude || /\.js$/);
13333
13339
  // Remove optimization options for dev as we only need to transpile them,
13334
13340
  // and for build as the final optimization is in `buildEsbuildPlugin`
13335
13341
  const transformOptions = {
@@ -13563,7 +13569,7 @@ function reloadOnTsconfigChange(changedFile) {
13563
13569
  if (path$n.basename(changedFile) === 'tsconfig.json' ||
13564
13570
  (changedFile.endsWith('.json') &&
13565
13571
  tsconfckParseOptions?.cache?.has(changedFile))) {
13566
- server.config.logger.info(`changed tsconfig file detected: ${changedFile} - Clearing cache and forcing full-reload to ensure typescript is compiled with updated config values.`, { clear: server.config.clearScreen, timestamp: true });
13572
+ server.config.logger.info(`changed tsconfig file detected: ${changedFile} - Clearing cache and forcing full-reload to ensure TypeScript is compiled with updated config values.`, { clear: server.config.clearScreen, timestamp: true });
13567
13573
  // clear module graph to remove code compiled with outdated config
13568
13574
  server.moduleGraph.invalidateAll();
13569
13575
  // reset tsconfck so that recompile works with up2date configs
@@ -27478,10 +27484,10 @@ function getLineInfo(input, offset) {
27478
27484
  var defaultOptions = {
27479
27485
  // `ecmaVersion` indicates the ECMAScript version to parse. Must be
27480
27486
  // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
27481
- // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the
27482
- // latest version the library supports). This influences support
27483
- // for strict mode, the set of reserved words, and support for
27484
- // new syntax features.
27487
+ // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"`
27488
+ // (the latest version the library supports). This influences
27489
+ // support for strict mode, the set of reserved words, and support
27490
+ // for new syntax features.
27485
27491
  ecmaVersion: null,
27486
27492
  // `sourceType` indicates the mode the code should be parsed in.
27487
27493
  // Can be either `"script"` or `"module"`. This influences global
@@ -27515,8 +27521,9 @@ var defaultOptions = {
27515
27521
  // When enabled, super identifiers are not constrained to
27516
27522
  // appearing in methods and do not raise an error when they appear elsewhere.
27517
27523
  allowSuperOutsideMethod: null,
27518
- // When enabled, hashbang directive in the beginning of file
27519
- // is allowed and treated as a line comment.
27524
+ // When enabled, hashbang directive in the beginning of file is
27525
+ // allowed and treated as a line comment. Enabled by default when
27526
+ // `ecmaVersion` >= 2023.
27520
27527
  allowHashBang: false,
27521
27528
  // When `locations` is on, `loc` properties holding objects with
27522
27529
  // `start` and `end` properties in `{line, column}` form (with
@@ -27591,6 +27598,9 @@ function getOptions(opts) {
27591
27598
  if (options.allowReserved == null)
27592
27599
  { options.allowReserved = options.ecmaVersion < 5; }
27593
27600
 
27601
+ if (opts.allowHashBang == null)
27602
+ { options.allowHashBang = options.ecmaVersion >= 14; }
27603
+
27594
27604
  if (isArray(options.onToken)) {
27595
27605
  var tokens = options.onToken;
27596
27606
  options.onToken = function (token) { return tokens.push(token); };
@@ -27921,7 +27931,7 @@ pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
27921
27931
  if (refDestructuringErrors.trailingComma > -1)
27922
27932
  { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
27923
27933
  var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
27924
- if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
27934
+ if (parens > -1) { this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); }
27925
27935
  };
27926
27936
 
27927
27937
  pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
@@ -29017,6 +29027,7 @@ pp$8.adaptDirectivePrologue = function(statements) {
29017
29027
  };
29018
29028
  pp$8.isDirectiveCandidate = function(statement) {
29019
29029
  return (
29030
+ this.options.ecmaVersion >= 5 &&
29020
29031
  statement.type === "ExpressionStatement" &&
29021
29032
  statement.expression.type === "Literal" &&
29022
29033
  typeof statement.expression.value === "string" &&
@@ -29427,7 +29438,8 @@ pp$6.updateContext = function(prevType) {
29427
29438
  { this.exprAllowed = type.beforeExpr; }
29428
29439
  };
29429
29440
 
29430
- // Used to handle egde case when token context could not be inferred correctly in tokenize phase
29441
+ // Used to handle egde cases when token context could not be inferred correctly during tokenization phase
29442
+
29431
29443
  pp$6.overrideContext = function(tokenCtx) {
29432
29444
  if (this.curContext() !== tokenCtx) {
29433
29445
  this.context[this.context.length - 1] = tokenCtx;
@@ -30243,15 +30255,6 @@ pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
30243
30255
  }
30244
30256
  return this.finishNode(prop, "RestElement")
30245
30257
  }
30246
- // To disallow parenthesized identifier via `this.toAssignable()`.
30247
- if (this.type === types$1.parenL && refDestructuringErrors) {
30248
- if (refDestructuringErrors.parenthesizedAssign < 0) {
30249
- refDestructuringErrors.parenthesizedAssign = this.start;
30250
- }
30251
- if (refDestructuringErrors.parenthesizedBind < 0) {
30252
- refDestructuringErrors.parenthesizedBind = this.start;
30253
- }
30254
- }
30255
30258
  // Parse argument.
30256
30259
  prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
30257
30260
  // To disallow trailing comma via `this.toAssignable()`.
@@ -32681,7 +32684,7 @@ pp.readWord = function() {
32681
32684
 
32682
32685
  // Acorn is a tiny, fast JavaScript parser written in JavaScript.
32683
32686
 
32684
- var version = "8.7.1";
32687
+ var version = "8.8.0";
32685
32688
 
32686
32689
  Parser.acorn = {
32687
32690
  Parser: Parser,
@@ -33300,11 +33303,6 @@ function assetPlugin(config) {
33300
33303
  renderChunk(code, chunk) {
33301
33304
  let match;
33302
33305
  let s;
33303
- const toRelative = (filename, importer) => {
33304
- return {
33305
- runtime: `new URL(${JSON.stringify(path$n.posix.relative(path$n.dirname(importer), filename))},import.meta.url).href`
33306
- };
33307
- };
33308
33306
  // Urls added with JS using e.g.
33309
33307
  // imgElement.src = "__VITE_ASSET__5aa0ddc0__" are using quotes
33310
33308
  // Urls added in CSS that is imported in JS end up like
@@ -33318,7 +33316,7 @@ function assetPlugin(config) {
33318
33316
  const file = getAssetFilename(hash, config) || this.getFileName(hash);
33319
33317
  chunk.viteMetadata.importedAssets.add(cleanUrl(file));
33320
33318
  const filename = file + postfix;
33321
- const replacement = toOutputFilePathInString(filename, 'asset', chunk.fileName, 'js', config, toRelative);
33319
+ const replacement = toOutputFilePathInString(filename, 'asset', chunk.fileName, 'js', config);
33322
33320
  const replacementString = typeof replacement === 'string'
33323
33321
  ? JSON.stringify(replacement).slice(1, -1)
33324
33322
  : `"+${replacement.runtime}+"`;
@@ -33332,7 +33330,7 @@ function assetPlugin(config) {
33332
33330
  s = s || (s = new MagicString(code));
33333
33331
  const [full, hash] = match;
33334
33332
  const publicUrl = publicAssetUrlMap.get(hash).slice(1);
33335
- const replacement = toOutputFilePathInString(publicUrl, 'public', chunk.fileName, 'js', config, toRelative);
33333
+ const replacement = toOutputFilePathInString(publicUrl, 'public', chunk.fileName, 'js', config);
33336
33334
  const replacementString = typeof replacement === 'string'
33337
33335
  ? JSON.stringify(replacement).slice(1, -1)
33338
33336
  : `"+${replacement.runtime}+"`;
@@ -33407,6 +33405,9 @@ function fileToDevUrl(id, config) {
33407
33405
  function getAssetFilename(hash, config) {
33408
33406
  return assetHashToFilenameMap.get(config)?.get(hash);
33409
33407
  }
33408
+ function getPublicAssetFilename(hash, config) {
33409
+ return publicAssetUrlCache.get(config)?.get(hash);
33410
+ }
33410
33411
  function resolveAssetFileNames(config) {
33411
33412
  const output = config.build?.rollupOptions?.output;
33412
33413
  const defaultAssetFileNames = path$n.posix.join(config.build.assetsDir, '[name].[hash][extname]');
@@ -34095,7 +34096,7 @@ function tryResolveFile(file, postfix, options, tryIndex, targetWeb, tryPrefix,
34095
34096
  }
34096
34097
  }
34097
34098
  const idToPkgMap = new Map();
34098
- function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr, externalize) {
34099
+ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr, externalize, allowLinkedExternal = true) {
34099
34100
  const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options;
34100
34101
  ssr ?? (ssr = false);
34101
34102
  // split id by last '>' for nested selected packages, for example:
@@ -34179,13 +34180,17 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr, ex
34179
34180
  if (!externalize) {
34180
34181
  return resolved;
34181
34182
  }
34183
+ // dont external symlink packages
34184
+ if (!allowLinkedExternal && !resolved.id.includes('node_modules')) {
34185
+ return resolved;
34186
+ }
34182
34187
  const resolvedExt = path$n.extname(resolved.id);
34183
34188
  let resolvedId = id;
34184
34189
  if (isDeepImport) {
34185
34190
  // check ext before externalizing - only externalize
34186
34191
  // extension-less imports and explicit .js imports
34187
34192
  if (resolvedExt && !resolved.id.match(/(.js|.mjs|.cjs)$/)) {
34188
- return;
34193
+ return resolved;
34189
34194
  }
34190
34195
  if (!pkg?.data.exports && path$n.extname(id) !== resolvedExt) {
34191
34196
  resolvedId += resolvedExt;
@@ -34537,6 +34542,8 @@ const externalTypes = [
34537
34542
  'stylus',
34538
34543
  'pcss',
34539
34544
  'postcss',
34545
+ // wasm
34546
+ 'wasm',
34540
34547
  // known SFC types
34541
34548
  'vue',
34542
34549
  'svelte',
@@ -35383,10 +35390,6 @@ function importGlobPlugin(config) {
35383
35390
  if (server) {
35384
35391
  const allGlobs = result.matches.map((i) => i.globsResolved);
35385
35392
  server._importGlobMap.set(id, allGlobs);
35386
- result.files.forEach((file) => {
35387
- // update watcher
35388
- server.watcher.add(dirname(file));
35389
- });
35390
35393
  }
35391
35394
  return transformStableResult(result.s, id, config);
35392
35395
  }
@@ -35454,6 +35457,10 @@ async function parseImportGlob(code, importer, root, resolveId) {
35454
35457
  }
35455
35458
  if (ast.type === 'SequenceExpression')
35456
35459
  ast = ast.expressions[0];
35460
+ // immediate property access, call expression is nested
35461
+ // import.meta.glob(...)['prop']
35462
+ if (ast.type === 'MemberExpression')
35463
+ ast = ast.object;
35457
35464
  if (ast.type !== 'CallExpression')
35458
35465
  throw err(`Expect CallExpression, got ${ast.type}`);
35459
35466
  if (ast.arguments.length < 1 || ast.arguments.length > 2)
@@ -35461,24 +35468,31 @@ async function parseImportGlob(code, importer, root, resolveId) {
35461
35468
  const arg1 = ast.arguments[0];
35462
35469
  const arg2 = ast.arguments[1];
35463
35470
  const globs = [];
35464
- if (arg1.type === 'ArrayExpression') {
35465
- for (const element of arg1.elements) {
35466
- if (!element)
35467
- continue;
35468
- if (element.type !== 'Literal')
35469
- throw err('Could only use literals');
35471
+ const validateLiteral = (element) => {
35472
+ if (!element)
35473
+ return;
35474
+ if (element.type === 'Literal') {
35470
35475
  if (typeof element.value !== 'string')
35471
35476
  throw err(`Expected glob to be a string, but got "${typeof element.value}"`);
35472
35477
  globs.push(element.value);
35473
35478
  }
35474
- }
35475
- else if (arg1.type === 'Literal') {
35476
- if (typeof arg1.value !== 'string')
35477
- throw err(`Expected glob to be a string, but got "${typeof arg1.value}"`);
35478
- globs.push(arg1.value);
35479
+ else if (element.type === 'TemplateLiteral') {
35480
+ if (element.expressions.length !== 0) {
35481
+ throw err(`Expected glob to be a string, but got dynamic template literal`);
35482
+ }
35483
+ globs.push(element.quasis[0].value.raw);
35484
+ }
35485
+ else {
35486
+ throw err('Could only use literals');
35487
+ }
35488
+ };
35489
+ if (arg1.type === 'ArrayExpression') {
35490
+ for (const element of arg1.elements) {
35491
+ validateLiteral(element);
35492
+ }
35479
35493
  }
35480
35494
  else {
35481
- throw err('Could only use literals');
35495
+ validateLiteral(arg1);
35482
35496
  }
35483
35497
  // arg2
35484
35498
  const options = {};
@@ -35985,14 +35999,18 @@ function esbuildScanPlugin(config, container, depImports, missing, entries) {
35985
35999
  build.onResolve({
35986
36000
  // avoid matching windows volume
35987
36001
  filter: /^[\w@][^:]/
35988
- }, async ({ path: id, importer }) => {
36002
+ }, async ({ path: id, importer, pluginData }) => {
35989
36003
  if (moduleListContains(exclude, id)) {
35990
36004
  return externalUnlessEntry({ path: id });
35991
36005
  }
35992
36006
  if (depImports[id]) {
35993
36007
  return externalUnlessEntry({ path: id });
35994
36008
  }
35995
- const resolved = await resolve(id, importer);
36009
+ const resolved = await resolve(id, importer, {
36010
+ custom: {
36011
+ depScan: { loader: pluginData?.htmlType?.loader }
36012
+ }
36013
+ });
35996
36014
  if (resolved) {
35997
36015
  if (shouldExternalizeDep(resolved, id)) {
35998
36016
  return externalUnlessEntry({ path: id });
@@ -36025,9 +36043,9 @@ function esbuildScanPlugin(config, container, depImports, missing, entries) {
36025
36043
  // should be faster than doing it in the catch-all via js
36026
36044
  // they are done after the bare import resolve because a package name
36027
36045
  // may end with these extensions
36028
- // css & json
36046
+ // css & json & wasm
36029
36047
  build.onResolve({
36030
- filter: /\.(css|less|sass|scss|styl|stylus|pcss|postcss|json)$/
36048
+ filter: /\.(css|less|sass|scss|styl|stylus|pcss|postcss|json|wasm)$/
36031
36049
  }, externalUnlessEntry);
36032
36050
  // known asset types
36033
36051
  build.onResolve({
@@ -36137,7 +36155,7 @@ function getDepsOptimizer(config, ssr) {
36137
36155
  }
36138
36156
  async function initDepsOptimizer(config, server) {
36139
36157
  // Non Dev SSR Optimizer
36140
- const ssr = !!config.build.ssr;
36158
+ const ssr = config.command === 'build' && !!config.build.ssr;
36141
36159
  if (!getDepsOptimizer(config, ssr)) {
36142
36160
  await createDepsOptimizer(config, server);
36143
36161
  }
@@ -36168,7 +36186,7 @@ async function initDevSsrDepsOptimizer(config, server) {
36168
36186
  async function createDepsOptimizer(config, server) {
36169
36187
  const { logger } = config;
36170
36188
  const isBuild = config.command === 'build';
36171
- const ssr = !!config.build.ssr; // safe as Dev SSR don't use this optimizer
36189
+ const ssr = isBuild && !!config.build.ssr; // safe as Dev SSR don't use this optimizer
36172
36190
  const sessionTimestamp = Date.now().toString();
36173
36191
  const cachedMetadata = loadCachedDepOptimizationMetadata(config, ssr);
36174
36192
  let handle;
@@ -36271,11 +36289,11 @@ async function createDepsOptimizer(config, server) {
36271
36289
  // promises are going to be resolved once a rerun is committed
36272
36290
  depOptimizationProcessingQueue.push(depOptimizationProcessing);
36273
36291
  // Create a new promise for the next rerun, discovered missing
36274
- // dependencies will be asigned this promise from this point
36292
+ // dependencies will be assigned this promise from this point
36275
36293
  depOptimizationProcessing = newDepOptimizationProcessing();
36276
36294
  }
36277
36295
  async function optimizeNewDeps() {
36278
- // a succesful completion of the optimizeDeps rerun will end up
36296
+ // a successful completion of the optimizeDeps rerun will end up
36279
36297
  // creating new bundled version of all current and discovered deps
36280
36298
  // in the cache dir and a new metadata info object assigned
36281
36299
  // to _metadata. A fullReload is only issued if the previous bundled
@@ -36384,7 +36402,7 @@ async function createDepsOptimizer(config, server) {
36384
36402
  else {
36385
36403
  if (newDepsDiscovered) {
36386
36404
  // There are newly discovered deps, and another rerun is about to be
36387
- // excecuted. Avoid the current full reload discarding this rerun result
36405
+ // executed. Avoid the current full reload discarding this rerun result
36388
36406
  // We don't resolve the processing promise, as they will be resolved
36389
36407
  // once a rerun is committed
36390
36408
  processingResult.cancel();
@@ -36481,7 +36499,7 @@ async function createDepsOptimizer(config, server) {
36481
36499
  src: resolved,
36482
36500
  // Assing a browserHash to this missing dependency that is unique to
36483
36501
  // the current state of known + missing deps. If its optimizeDeps run
36484
- // doesn't alter the bundled files of previous known dependendencies,
36502
+ // doesn't alter the bundled files of previous known dependencies,
36485
36503
  // we don't need a full reload and this browserHash will be kept
36486
36504
  browserHash: getDiscoveredBrowserHash(metadata.hash, depsFromOptimizedDepInfo(metadata.optimized), depsFromOptimizedDepInfo(metadata.discovered)),
36487
36505
  // loading of this pre-bundled dep needs to await for its processing
@@ -36684,7 +36702,7 @@ const jsMapExtensionRE = /\.js\.map$/i;
36684
36702
  */
36685
36703
  async function optimizeDeps(config, force = config.optimizeDeps.force, asCommand = false) {
36686
36704
  const log = asCommand ? config.logger.info : debug$a;
36687
- const ssr = !!config.build.ssr;
36705
+ const ssr = config.command === 'build' && !!config.build.ssr;
36688
36706
  const cachedMetadata = loadCachedDepOptimizationMetadata(config, ssr, force, asCommand);
36689
36707
  if (cachedMetadata) {
36690
36708
  return cachedMetadata;
@@ -36819,7 +36837,8 @@ function depsLogString(qualifiedIds) {
36819
36837
  * Internally, Vite uses this function to prepare a optimizeDeps run. When Vite starts, we can get
36820
36838
  * the metadata and start the server without waiting for the optimizeDeps processing to be completed
36821
36839
  */
36822
- async function runOptimizeDeps(resolvedConfig, depsInfo, ssr = !!resolvedConfig.build.ssr) {
36840
+ async function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.command === 'build' &&
36841
+ !!resolvedConfig.build.ssr) {
36823
36842
  const isBuild = resolvedConfig.command === 'build';
36824
36843
  const config = {
36825
36844
  ...resolvedConfig,
@@ -37045,7 +37064,7 @@ function newDepOptimizationProcessing() {
37045
37064
  function depsFromOptimizedDepInfo(depsInfo) {
37046
37065
  return Object.fromEntries(Object.entries(depsInfo).map((d) => [d[0], d[1].src]));
37047
37066
  }
37048
- function getOptimizedDepPath(id, config, ssr = !!config.build.ssr) {
37067
+ function getOptimizedDepPath(id, config, ssr) {
37049
37068
  return normalizePath$3(path$n.resolve(getDepsCacheDir(config, ssr), flattenId(id) + '.js'));
37050
37069
  }
37051
37070
  function getDepsCacheSuffix(config, ssr) {
@@ -37232,7 +37251,7 @@ function needsInterop(config, ssr, id, exportsData, output) {
37232
37251
  return true;
37233
37252
  }
37234
37253
  if (output) {
37235
- // if a peer dependency used require() on a ESM dependency, esbuild turns the
37254
+ // if a peer dependency used require() on an ESM dependency, esbuild turns the
37236
37255
  // ESM dependency's entry chunk into a single default export... detect
37237
37256
  // such cases by checking exports mismatch, and force interop.
37238
37257
  const generatedExports = output.exports;
@@ -37975,22 +37994,55 @@ function shouldExternalizeForSSR(id, config) {
37975
37994
  return isSsrExternal(id);
37976
37995
  }
37977
37996
  function createIsConfiguredAsSsrExternal(config) {
37978
- const { ssr } = config;
37997
+ const { ssr, root } = config;
37979
37998
  const noExternal = ssr?.noExternal;
37980
37999
  const noExternalFilter = noExternal !== 'undefined' &&
37981
38000
  typeof noExternal !== 'boolean' &&
37982
38001
  createFilter(undefined, noExternal, { resolve: false });
38002
+ const resolveOptions = {
38003
+ root,
38004
+ preserveSymlinks: config.resolve.preserveSymlinks,
38005
+ isProduction: false,
38006
+ isBuild: true
38007
+ };
38008
+ const isExternalizable = (id, configuredAsExternal) => {
38009
+ if (!bareImportRE.test(id) || id.includes('\0')) {
38010
+ return false;
38011
+ }
38012
+ try {
38013
+ return !!tryNodeResolve(id, undefined, resolveOptions, ssr?.target === 'webworker', undefined, true,
38014
+ // try to externalize, will return undefined or an object without
38015
+ // a external flag if it isn't externalizable
38016
+ true,
38017
+ // Allow linked packages to be externalized if they are explicitly
38018
+ // configured as external
38019
+ !!configuredAsExternal)?.external;
38020
+ }
38021
+ catch (e) {
38022
+ // may be an invalid import that's resolved by a plugin
38023
+ return false;
38024
+ }
38025
+ };
37983
38026
  // Returns true if it is configured as external, false if it is filtered
37984
38027
  // by noExternal and undefined if it isn't affected by the explicit config
37985
38028
  return (id) => {
37986
38029
  const { ssr } = config;
37987
38030
  if (ssr) {
38031
+ if (
38032
+ // If this id is defined as external, force it as external
38033
+ // Note that individual package entries are allowed in ssr.external
38034
+ ssr.external?.includes(id)) {
38035
+ return true;
38036
+ }
37988
38037
  const pkgName = getNpmPackageName(id);
37989
38038
  if (!pkgName) {
37990
- return undefined;
38039
+ return isExternalizable(id);
37991
38040
  }
37992
- if (ssr.external?.includes(pkgName)) {
37993
- return true;
38041
+ if (
38042
+ // A package name in ssr.external externalizes every
38043
+ // externalizable package entry
38044
+ ssr.external?.includes(pkgName)) {
38045
+ return isExternalizable(id, true);
37994
38046
  }
37995
38047
  if (typeof noExternal === 'boolean') {
37996
38048
  return !noExternal;
@@ -37999,34 +38051,19 @@ function createIsConfiguredAsSsrExternal(config) {
37999
38051
  return false;
38000
38052
  }
38001
38053
  }
38002
- return undefined;
38054
+ return isExternalizable(id);
38003
38055
  };
38004
38056
  }
38005
38057
  function createIsSsrExternal(config) {
38006
38058
  const processedIds = new Map();
38007
- const { ssr, root } = config;
38008
38059
  const isConfiguredAsExternal = createIsConfiguredAsSsrExternal(config);
38009
- const resolveOptions = {
38010
- root,
38011
- preserveSymlinks: config.resolve.preserveSymlinks,
38012
- isProduction: false,
38013
- isBuild: true
38014
- };
38015
- const isValidPackageEntry = (id) => {
38016
- if (!bareImportRE.test(id) || id.includes('\0')) {
38017
- return false;
38018
- }
38019
- return !!tryNodeResolve(id, undefined, resolveOptions, ssr?.target === 'webworker', undefined, true, true // try to externalize, will return undefined if not possible
38020
- );
38021
- };
38022
38060
  return (id) => {
38023
38061
  if (processedIds.has(id)) {
38024
38062
  return processedIds.get(id);
38025
38063
  }
38026
38064
  let external = false;
38027
38065
  if (!id.startsWith('.') && !path$n.isAbsolute(id)) {
38028
- external =
38029
- isBuiltin(id) || (isConfiguredAsExternal(id) ?? isValidPackageEntry(id));
38066
+ external = isBuiltin(id) || isConfiguredAsExternal(id);
38030
38067
  }
38031
38068
  processedIds.set(id, external);
38032
38069
  return external;
@@ -39500,32 +39537,36 @@ function serveStaticMiddleware(dir, server) {
39500
39537
  isInternalRequest(req.url)) {
39501
39538
  return next();
39502
39539
  }
39503
- const url = decodeURIComponent(req.url);
39540
+ const url = new URL(req.url, 'http://example.com');
39541
+ const pathname = decodeURIComponent(url.pathname);
39504
39542
  // apply aliases to static requests as well
39505
- let redirected;
39543
+ let redirectedPathname;
39506
39544
  for (const { find, replacement } of server.config.resolve.alias) {
39507
- const matches = typeof find === 'string' ? url.startsWith(find) : find.test(url);
39545
+ const matches = typeof find === 'string'
39546
+ ? pathname.startsWith(find)
39547
+ : find.test(pathname);
39508
39548
  if (matches) {
39509
- redirected = url.replace(find, replacement);
39549
+ redirectedPathname = pathname.replace(find, replacement);
39510
39550
  break;
39511
39551
  }
39512
39552
  }
39513
- if (redirected) {
39553
+ if (redirectedPathname) {
39514
39554
  // dir is pre-normalized to posix style
39515
- if (redirected.startsWith(dir)) {
39516
- redirected = redirected.slice(dir.length);
39555
+ if (redirectedPathname.startsWith(dir)) {
39556
+ redirectedPathname = redirectedPathname.slice(dir.length);
39517
39557
  }
39518
39558
  }
39519
- const resolvedUrl = redirected || url;
39520
- let fileUrl = path$n.resolve(dir, resolvedUrl.replace(/^\//, ''));
39521
- if (resolvedUrl.endsWith('/') && !fileUrl.endsWith('/')) {
39559
+ const resolvedPathname = redirectedPathname || pathname;
39560
+ let fileUrl = path$n.resolve(dir, resolvedPathname.replace(/^\//, ''));
39561
+ if (resolvedPathname.endsWith('/') && !fileUrl.endsWith('/')) {
39522
39562
  fileUrl = fileUrl + '/';
39523
39563
  }
39524
39564
  if (!ensureServingAccess(fileUrl, server, res, next)) {
39525
39565
  return;
39526
39566
  }
39527
- if (redirected) {
39528
- req.url = encodeURIComponent(redirected);
39567
+ if (redirectedPathname) {
39568
+ url.pathname = encodeURIComponent(redirectedPathname);
39569
+ req.url = url.href.slice(url.origin.length);
39529
39570
  }
39530
39571
  serve(req, res, next);
39531
39572
  };
@@ -39534,20 +39575,22 @@ function serveRawFsMiddleware(server) {
39534
39575
  const serveFromRoot = sirv('/', sirvOptions(server.config.server.headers));
39535
39576
  // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
39536
39577
  return function viteServeRawFsMiddleware(req, res, next) {
39537
- let url = decodeURIComponent(req.url);
39578
+ const url = new URL(req.url, 'http://example.com');
39538
39579
  // In some cases (e.g. linked monorepos) files outside of root will
39539
39580
  // reference assets that are also out of served root. In such cases
39540
39581
  // the paths are rewritten to `/@fs/` prefixed paths and must be served by
39541
39582
  // searching based from fs root.
39542
- if (url.startsWith(FS_PREFIX)) {
39583
+ if (url.pathname.startsWith(FS_PREFIX)) {
39584
+ const pathname = decodeURIComponent(url.pathname);
39543
39585
  // restrict files outside of `fs.allow`
39544
- if (!ensureServingAccess(slash$1(path$n.resolve(fsPathFromId(url))), server, res, next)) {
39586
+ if (!ensureServingAccess(slash$1(path$n.resolve(fsPathFromId(pathname))), server, res, next)) {
39545
39587
  return;
39546
39588
  }
39547
- url = url.slice(FS_PREFIX.length);
39589
+ let newPathname = pathname.slice(FS_PREFIX.length);
39548
39590
  if (isWindows$4)
39549
- url = url.replace(/^[A-Z]:/i, '');
39550
- req.url = encodeURIComponent(url);
39591
+ newPathname = newPathname.replace(/^[A-Z]:/i, '');
39592
+ url.pathname = encodeURIComponent(newPathname);
39593
+ req.url = url.href.slice(url.origin.length);
39551
39594
  serveFromRoot(req, res, next);
39552
39595
  }
39553
39596
  else {
@@ -39577,7 +39620,7 @@ function ensureServingAccess(url, server, res, next) {
39577
39620
  const hintMessage = `
39578
39621
  ${server.config.server.fs.allow.map((i) => `- ${i}`).join('\n')}
39579
39622
 
39580
- Refer to docs https://vitejs.dev/config/#server-fs-allow for configurations and more details.`;
39623
+ Refer to docs https://vitejs.dev/config/server-options.html#server-fs-allow for configurations and more details.`;
39581
39624
  server.config.logger.error(urlMessage);
39582
39625
  server.config.logger.warnOnce(hintMessage + '\n');
39583
39626
  res.statusCode = 403;
@@ -40990,7 +41033,7 @@ function polyfill() {
40990
41033
  }
40991
41034
  }
40992
41035
 
40993
- const htmlProxyRE$1 = /\?html-proxy=?[&inline\-css]*&index=(\d+)\.(js|css)$/;
41036
+ const htmlProxyRE$1 = /\?html-proxy=?(?:&inline-css)?&index=(\d+)\.(js|css)$/;
40994
41037
  const inlineCSSRE$1 = /__VITE_INLINE_CSS__([a-z\d]{8}_\d+)__/g;
40995
41038
  // Do not allow preceding '.', but do allow preceding '...' for spread operations
40996
41039
  const inlineImportRE = /(?<!(?<!\.\.)\.)\bimport\s*\(("([^"]|(?<=\\)")*"|'([^']|(?<=\\)')*')\)/g;
@@ -41056,7 +41099,7 @@ const assetAttrsConfig = {
41056
41099
  const isAsyncScriptMap = new WeakMap();
41057
41100
  async function traverseHtml(html, filePath, visitor) {
41058
41101
  // lazy load compiler
41059
- const { parse, transform } = await import('./dep-7d66befd.js').then(function (n) { return n.c; });
41102
+ const { parse, transform } = await import('./dep-f135d593.js').then(function (n) { return n.c; });
41060
41103
  // @vue/compiler-core doesn't like lowercase doctypes
41061
41104
  html = html.replace(/<!doctype\s/i, '<!DOCTYPE ');
41062
41105
  try {
@@ -41218,7 +41261,10 @@ function buildHtmlPlugin(config) {
41218
41261
  // assetsUrl may be encodeURI
41219
41262
  const url = decodeURI(p.value.content);
41220
41263
  if (!isExcludedUrl(url)) {
41221
- if (node.tag === 'link' && isCSSRequest(url)) {
41264
+ if (node.tag === 'link' &&
41265
+ isCSSRequest(url) &&
41266
+ // should not be converted if following attributes are present (#6748)
41267
+ !node.props.some((p) => p.name === 'media' || p.name === 'disabled')) {
41222
41268
  // CSS references, convert to import
41223
41269
  const importExpression = `\nimport ${JSON.stringify(url)}`;
41224
41270
  styleUrls.push({
@@ -41402,14 +41448,16 @@ function buildHtmlPlugin(config) {
41402
41448
  for (const [id, html] of processedHtml) {
41403
41449
  const relativeUrlPath = path$n.posix.relative(config.root, id);
41404
41450
  const assetsBase = getBaseInHTML(relativeUrlPath, config);
41405
- const toOutputAssetFilePath = (filename) => {
41451
+ const toOutputFilePath = (filename, type) => {
41406
41452
  if (isExternalUrl(filename)) {
41407
41453
  return filename;
41408
41454
  }
41409
41455
  else {
41410
- return toOutputFilePathInHtml(filename, 'asset', relativeUrlPath, 'html', config, (filename, importer) => assetsBase + filename);
41456
+ return toOutputFilePathInHtml(filename, type, relativeUrlPath, 'html', config, (filename, importer) => assetsBase + filename);
41411
41457
  }
41412
41458
  };
41459
+ const toOutputAssetFilePath = (filename) => toOutputFilePath(filename, 'asset');
41460
+ const toOutputPublicAssetFilePath = (filename) => toOutputFilePath(filename, 'public');
41413
41461
  const isAsync = isAsyncScriptMap.get(config).get(id);
41414
41462
  let result = html;
41415
41463
  // find corresponding entry chunk
@@ -41474,6 +41522,9 @@ function buildHtmlPlugin(config) {
41474
41522
  result = result.replace(assetUrlRE, (_, fileHash, postfix = '') => {
41475
41523
  return (toOutputAssetFilePath(getAssetFilename(fileHash, config)) + postfix);
41476
41524
  });
41525
+ result = result.replace(publicAssetUrlRE, (_, fileHash) => {
41526
+ return normalizePath$3(toOutputPublicAssetFilePath(getPublicAssetFilename(fileHash, config)));
41527
+ });
41477
41528
  if (chunk && canInlineEntry) {
41478
41529
  // all imports from entry have been inlined to html, prevent rollup from outputting it
41479
41530
  delete bundle[chunk.fileName];
@@ -41956,7 +42007,7 @@ function cssPostPlugin(config) {
41956
42007
  return chunkCSS;
41957
42008
  }
41958
42009
  function ensureFileExt(name, ext) {
41959
- return path$n.format({ ...path$n.parse(name), base: undefined, ext });
42010
+ return normalizePath$3(path$n.format({ ...path$n.parse(name), base: undefined, ext }));
41960
42011
  }
41961
42012
  if (config.build.cssCodeSplit) {
41962
42013
  if (isPureCssChunk) {
@@ -42186,7 +42237,7 @@ async function compileCSS(id, code, config, urlReplacer, atImportResolvers, serv
42186
42237
  logger: config.logger
42187
42238
  }));
42188
42239
  if (isModule) {
42189
- postcssPlugins.unshift((await import('./dep-adbb28b2.js').then(function (n) { return n.i; })).default({
42240
+ postcssPlugins.unshift((await import('./dep-3811dadb.js').then(function (n) { return n.i; })).default({
42190
42241
  ...modulesOptions,
42191
42242
  getJSON(cssFileName, _modules, outputFileName) {
42192
42243
  modules = _modules;
@@ -42497,17 +42548,23 @@ async function minifyCSS(css, config) {
42497
42548
  }
42498
42549
  }
42499
42550
  function resolveEsbuildMinifyOptions(options) {
42551
+ const base = {
42552
+ logLevel: options.logLevel,
42553
+ logLimit: options.logLimit,
42554
+ logOverride: options.logOverride
42555
+ };
42500
42556
  if (options.minifyIdentifiers != null ||
42501
42557
  options.minifySyntax != null ||
42502
42558
  options.minifyWhitespace != null) {
42503
42559
  return {
42560
+ ...base,
42504
42561
  minifyIdentifiers: options.minifyIdentifiers ?? true,
42505
42562
  minifySyntax: options.minifySyntax ?? true,
42506
42563
  minifyWhitespace: options.minifyWhitespace ?? true
42507
42564
  };
42508
42565
  }
42509
42566
  else {
42510
- return { minify: true };
42567
+ return { ...base, minify: true };
42511
42568
  }
42512
42569
  }
42513
42570
  async function hoistAtRules(css) {
@@ -43116,7 +43173,7 @@ function assetImportMetaUrlPlugin(config) {
43116
43173
  // target so we use the global location here. It can be
43117
43174
  // window.location or self.location in case it is used in a Web Worker.
43118
43175
  // @see https://developer.mozilla.org/en-US/docs/Web/API/Window/self
43119
- s.overwrite(index, index + exp.length, `new URL((import.meta.glob(${pattern}, { eager: true, import: 'default' }))[${rawUrl}], self.location)`, { contentOnly: true });
43176
+ s.overwrite(index, index + exp.length, `new URL((import.meta.glob(${pattern}, { eager: true, import: 'default', as: 'url' }))[${rawUrl}], self.location)`, { contentOnly: true });
43120
43177
  continue;
43121
43178
  }
43122
43179
  }
@@ -43361,10 +43418,11 @@ async function doBuild(inlineConfig = {}) {
43361
43418
  `This is deprecated and will override all Vite.js default output options. ` +
43362
43419
  `Please use "rollupOptions.output" instead.`);
43363
43420
  }
43364
- const ssrWorkerBuild = ssr && config.ssr?.target !== 'webworker';
43365
- const cjsSsrBuild = ssr && config.ssr?.format === 'cjs';
43421
+ const ssrNodeBuild = ssr && config.ssr.target === 'node';
43422
+ const ssrWorkerBuild = ssr && config.ssr.target === 'webworker';
43423
+ const cjsSsrBuild = ssr && config.ssr.format === 'cjs';
43366
43424
  const format = output.format || (cjsSsrBuild ? 'cjs' : 'es');
43367
- const jsExt = ssrWorkerBuild || libOptions
43425
+ const jsExt = ssrNodeBuild || libOptions
43368
43426
  ? resolveOutputJsExtension(format, getPkgJson(config.root)?.type)
43369
43427
  : 'js';
43370
43428
  return {
@@ -43649,7 +43707,7 @@ function wrapSsrTransform(fn) {
43649
43707
  function injectSsrFlag(options) {
43650
43708
  return { ...(options ?? {}), ssr: true };
43651
43709
  }
43652
- function toOutputFilePathInString(filename, type, hostId, hostType, config, toRelative) {
43710
+ function toOutputFilePathInString(filename, type, hostId, hostType, config, toRelative = toImportMetaURLBasedRelativePath) {
43653
43711
  const { renderBuiltUrl } = config.experimental;
43654
43712
  let relative = config.base === '' || config.base === './';
43655
43713
  if (renderBuiltUrl) {
@@ -43676,6 +43734,11 @@ function toOutputFilePathInString(filename, type, hostId, hostType, config, toRe
43676
43734
  }
43677
43735
  return config.base + filename;
43678
43736
  }
43737
+ function toImportMetaURLBasedRelativePath(filename, importer) {
43738
+ return {
43739
+ runtime: `new URL(${JSON.stringify(path$n.posix.relative(path$n.dirname(importer), filename))},import.meta.url).href`
43740
+ };
43741
+ }
43679
43742
  function toOutputFilePathWithoutRuntime(filename, type, hostId, hostType, config, toRelative) {
43680
43743
  const { renderBuiltUrl } = config.experimental;
43681
43744
  let relative = config.base === '' || config.base === './';
@@ -50276,7 +50339,8 @@ async function instantiateModule(url, server, context = { global }, urlStack = [
50276
50339
  if (dep[0] !== '.' && dep[0] !== '/') {
50277
50340
  return nodeImport(dep, mod.file, resolveOptions);
50278
50341
  }
50279
- dep = unwrapId(dep);
50342
+ // convert to rollup URL because `pendingImports`, `moduleGraph.urlToModuleMap` requires that
50343
+ dep = unwrapId(dep).replace(NULL_BYTE_PLACEHOLDER, '\0');
50280
50344
  if (!isCircular(dep) && !pendingImports.get(dep)?.some(isCircular)) {
50281
50345
  pendingDeps.push(dep);
50282
50346
  if (pendingDeps.length === 1) {
@@ -50318,7 +50382,7 @@ async function instantiateModule(url, server, context = { global }, urlStack = [
50318
50382
  try {
50319
50383
  // eslint-disable-next-line @typescript-eslint/no-empty-function
50320
50384
  const AsyncFunction = async function () { }.constructor;
50321
- const initModule = new AsyncFunction(`global`, ssrModuleExportsKey, ssrImportMetaKey, ssrImportKey, ssrDynamicImportKey, ssrExportAllKey, result.code + `\n//# sourceURL=${mod.url}`);
50385
+ const initModule = new AsyncFunction(`global`, ssrModuleExportsKey, ssrImportMetaKey, ssrImportKey, ssrDynamicImportKey, ssrExportAllKey, '"use strict";' + result.code + `\n//# sourceURL=${mod.url}`);
50322
50386
  await initModule(context.global, ssrModule, ssrImportMeta, ssrImport, ssrDynamicImport, ssrExportAll);
50323
50387
  }
50324
50388
  catch (e) {
@@ -50399,7 +50463,7 @@ async function nodeImport(id, importer, resolveOptions) {
50399
50463
  }
50400
50464
  // rollup-style default import interop for cjs
50401
50465
  function proxyESM(mod) {
50402
- // This is the only sensible option when the exports object is a primitve
50466
+ // This is the only sensible option when the exports object is a primitive
50403
50467
  if (isPrimitive(mod))
50404
50468
  return { default: mod };
50405
50469
  let defaultExport = 'default' in mod ? mod.default : mod;
@@ -53520,11 +53584,11 @@ function initAsClient(websocket, address, protocols, options) {
53520
53584
  ? parsedUrl.hostname.slice(1, -1)
53521
53585
  : parsedUrl.hostname;
53522
53586
  opts.headers = {
53587
+ ...opts.headers,
53523
53588
  'Sec-WebSocket-Version': opts.protocolVersion,
53524
53589
  'Sec-WebSocket-Key': key,
53525
53590
  Connection: 'Upgrade',
53526
- Upgrade: 'websocket',
53527
- ...opts.headers
53591
+ Upgrade: 'websocket'
53528
53592
  };
53529
53593
  opts.path = parsedUrl.pathname + parsedUrl.search;
53530
53594
  opts.timeout = opts.handshakeTimeout;
@@ -53578,8 +53642,11 @@ function initAsClient(websocket, address, protocols, options) {
53578
53642
 
53579
53643
  if (opts.followRedirects) {
53580
53644
  if (websocket._redirects === 0) {
53645
+ websocket._originalUnixSocket = isUnixSocket;
53581
53646
  websocket._originalSecure = isSecure;
53582
- websocket._originalHost = parsedUrl.host;
53647
+ websocket._originalHostOrSocketPath = isUnixSocket
53648
+ ? opts.socketPath
53649
+ : parsedUrl.host;
53583
53650
 
53584
53651
  const headers = options && options.headers;
53585
53652
 
@@ -53595,7 +53662,13 @@ function initAsClient(websocket, address, protocols, options) {
53595
53662
  }
53596
53663
  }
53597
53664
  } else if (websocket.listenerCount('redirect') === 0) {
53598
- const isSameHost = parsedUrl.host === websocket._originalHost;
53665
+ const isSameHost = isUnixSocket
53666
+ ? websocket._originalUnixSocket
53667
+ ? opts.socketPath === websocket._originalHostOrSocketPath
53668
+ : false
53669
+ : websocket._originalUnixSocket
53670
+ ? false
53671
+ : parsedUrl.host === websocket._originalHostOrSocketPath;
53599
53672
 
53600
53673
  if (!isSameHost || (websocket._originalSecure && !isSecure)) {
53601
53674
  //
@@ -56970,7 +57043,7 @@ function proxyMiddleware(httpServer, options, config) {
56970
57043
  timestamp: true,
56971
57044
  error: err
56972
57045
  });
56973
- if (!res.writableEnded) {
57046
+ if (!res.headersSent && !res.writableEnded) {
56974
57047
  res
56975
57048
  .writeHead(500, {
56976
57049
  'Content-Type': 'text/plain'
@@ -57389,9 +57462,9 @@ function transformMiddleware(server) {
57389
57462
  }
57390
57463
  // We don't need to log an error in this case, the request
57391
57464
  // is outdated because new dependencies were discovered and
57392
- // the new pre-bundle dependendencies have changed.
57465
+ // the new pre-bundle dependencies have changed.
57393
57466
  // A full-page reload has been issued, and these old requests
57394
- // can't be properly fullfilled. This isn't an unexpected
57467
+ // can't be properly fulfilled. This isn't an unexpected
57395
57468
  // error but a normal part of the missing deps discovery flow
57396
57469
  return;
57397
57470
  }
@@ -57766,10 +57839,14 @@ class ModuleGraph {
57766
57839
  url = removeImportQuery(removeTimestampQuery(url));
57767
57840
  const resolved = await this.resolveId(url, !!ssr);
57768
57841
  const resolvedId = resolved?.id || url;
57769
- const ext = extname$1(cleanUrl(resolvedId));
57770
- const { pathname, search, hash } = parse$k(url);
57771
- if (ext && !pathname.endsWith(ext)) {
57772
- url = pathname + ext + (search || '') + (hash || '');
57842
+ if (url !== resolvedId &&
57843
+ !url.includes('\0') &&
57844
+ !url.startsWith(`virtual:`)) {
57845
+ const ext = extname$1(cleanUrl(resolvedId));
57846
+ const { pathname, search, hash } = new URL(url, 'relative://');
57847
+ if (ext && !pathname.endsWith(ext)) {
57848
+ url = pathname + ext + search + hash;
57849
+ }
57773
57850
  }
57774
57851
  return [url, resolvedId, resolved?.meta];
57775
57852
  }
@@ -59810,14 +59887,6 @@ function emitSourcemapForWorkerEntry(config, query, chunk) {
59810
59887
  }
59811
59888
  return chunk;
59812
59889
  }
59813
- // TODO:base review why we aren't using import.meta.url here
59814
- function toStaticRelativePath(filename, importer) {
59815
- let outputFilepath = path$n.posix.relative(path$n.dirname(importer), filename);
59816
- if (!outputFilepath.startsWith('.')) {
59817
- outputFilepath = './' + outputFilepath;
59818
- }
59819
- return outputFilepath;
59820
- }
59821
59890
  const workerAssetUrlRE = /__VITE_WORKER_ASSET__([a-z\d]{8})__/g;
59822
59891
  function encodeWorkerAssetFileName(fileName, workerCache) {
59823
59892
  const { fileNameHash } = workerCache;
@@ -59973,7 +60042,7 @@ function webWorkerPlugin(config) {
59973
60042
  while ((match = workerAssetUrlRE.exec(code))) {
59974
60043
  const [full, hash] = match;
59975
60044
  const filename = fileNameHash.get(hash);
59976
- const replacement = toOutputFilePathInString(filename, 'asset', chunk.fileName, 'js', config, toStaticRelativePath);
60045
+ const replacement = toOutputFilePathInString(filename, 'asset', chunk.fileName, 'js', config);
59977
60046
  const replacementString = typeof replacement === 'string'
59978
60047
  ? JSON.stringify(replacement).slice(1, -1)
59979
60048
  : `"+${replacement.runtime}+"`;
@@ -61921,7 +61990,13 @@ function dynamicImportVarsPlugin(config) {
61921
61990
  s || (s = new MagicString(source));
61922
61991
  let result;
61923
61992
  try {
61924
- result = await transformDynamicImport(source.slice(start, end), importer, resolve);
61993
+ // When import string is using backticks, es-module-lexer `end` captures
61994
+ // until the closing parenthesis, instead of the closing backtick.
61995
+ // There may be inline comments between the backtick and the closing
61996
+ // parenthesis, so we manually remove them for now.
61997
+ // See https://github.com/guybedford/es-module-lexer/issues/118
61998
+ const importSource = removeComments(source.slice(start, end)).trim();
61999
+ result = await transformDynamicImport(importSource, importer, resolve);
61925
62000
  }
61926
62001
  catch (error) {
61927
62002
  if (warnOnError) {
@@ -61998,7 +62073,7 @@ async function resolvePlugins(config, prePlugins, normalPlugins, postPlugins) {
61998
62073
  wasmFallbackPlugin(),
61999
62074
  definePlugin(config),
62000
62075
  cssPostPlugin(config),
62001
- config.build.ssr ? ssrRequireHookPlugin(config) : null,
62076
+ isBuild && config.build.ssr ? ssrRequireHookPlugin(config) : null,
62002
62077
  isBuild && buildHtmlPlugin(config),
62003
62078
  workerImportMetaUrlPlugin(config),
62004
62079
  ...buildPlugins.pre,
@@ -62335,6 +62410,23 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62335
62410
  // user config may provide an alternative mode. But --mode has a higher priority
62336
62411
  mode = inlineConfig.mode || config.mode || mode;
62337
62412
  configEnv.mode = mode;
62413
+ // Some plugins that aren't intended to work in the bundling of workers (doing post-processing at build time for example).
62414
+ // And Plugins may also have cached that could be corrupted by being used in these extra rollup calls.
62415
+ // So we need to separate the worker plugin from the plugin that vite needs to run.
62416
+ const rawWorkerUserPlugins = (await asyncFlatten(config.worker?.plugins || [])).filter((p) => {
62417
+ if (!p) {
62418
+ return false;
62419
+ }
62420
+ else if (!p.apply) {
62421
+ return true;
62422
+ }
62423
+ else if (typeof p.apply === 'function') {
62424
+ return p.apply({ ...config, mode }, configEnv);
62425
+ }
62426
+ else {
62427
+ return p.apply === command;
62428
+ }
62429
+ });
62338
62430
  // resolve plugins
62339
62431
  const rawUserPlugins = (await asyncFlatten(config.plugins || [])).filter((p) => {
62340
62432
  if (!p) {
@@ -62351,12 +62443,6 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62351
62443
  }
62352
62444
  });
62353
62445
  const [prePlugins, normalPlugins, postPlugins] = sortUserPlugins(rawUserPlugins);
62354
- // resolve worker
62355
- const resolvedWorkerOptions = {
62356
- format: config.worker?.format || 'iife',
62357
- plugins: [],
62358
- rollupOptions: config.worker?.rollupOptions || {}
62359
- };
62360
62446
  // run config hooks
62361
62447
  const userPlugins = [...prePlugins, ...normalPlugins, ...postPlugins];
62362
62448
  for (const p of userPlugins) {
@@ -62475,8 +62561,29 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62475
62561
  const middlewareMode = config?.server?.middlewareMode;
62476
62562
  const optimizeDeps = config.optimizeDeps || {};
62477
62563
  const BASE_URL = resolvedBase;
62478
- const resolved = {
62479
- ...config,
62564
+ // resolve worker
62565
+ let workerConfig = mergeConfig({}, config);
62566
+ const [workerPrePlugins, workerNormalPlugins, workerPostPlugins] = sortUserPlugins(rawWorkerUserPlugins);
62567
+ // run config hooks
62568
+ const workerUserPlugins = [
62569
+ ...workerPrePlugins,
62570
+ ...workerNormalPlugins,
62571
+ ...workerPostPlugins
62572
+ ];
62573
+ for (const p of workerUserPlugins) {
62574
+ if (p.config) {
62575
+ const res = await p.config(workerConfig, configEnv);
62576
+ if (res) {
62577
+ workerConfig = mergeConfig(workerConfig, res);
62578
+ }
62579
+ }
62580
+ }
62581
+ const resolvedWorkerOptions = {
62582
+ format: workerConfig.worker?.format || 'iife',
62583
+ plugins: [],
62584
+ rollupOptions: workerConfig.worker?.rollupOptions || {}
62585
+ };
62586
+ const resolvedConfig = {
62480
62587
  configFile: configFile ? normalizePath$3(configFile) : undefined,
62481
62588
  configFileDependencies: configFileDependencies.map((name) => normalizePath$3(path$n.resolve(name))),
62482
62589
  inlineConfig,
@@ -62524,6 +62631,23 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62524
62631
  ...config.experimental
62525
62632
  }
62526
62633
  };
62634
+ const resolved = {
62635
+ ...config,
62636
+ ...resolvedConfig
62637
+ };
62638
+ resolved.plugins = await resolvePlugins(resolved, prePlugins, normalPlugins, postPlugins);
62639
+ const workerResolved = {
62640
+ ...workerConfig,
62641
+ ...resolvedConfig,
62642
+ isWorker: true,
62643
+ mainConfig: resolved
62644
+ };
62645
+ resolvedConfig.worker.plugins = await resolvePlugins(workerResolved, workerPrePlugins, workerNormalPlugins, workerPostPlugins);
62646
+ // call configResolved hooks
62647
+ await Promise.all(userPlugins
62648
+ .map((p) => p.configResolved?.(resolved))
62649
+ .concat(resolvedConfig.worker.plugins.map((p) => p.configResolved?.(workerResolved))));
62650
+ // validate config
62527
62651
  if (middlewareMode === 'ssr') {
62528
62652
  logger.warn(picocolors.exports.yellow(`Setting server.middlewareMode to 'ssr' is deprecated, set server.middlewareMode to \`true\`${config.appType === 'custom' ? '' : ` and appType to 'custom'`} instead`));
62529
62653
  }
@@ -62536,21 +62660,6 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development')
62536
62660
  resolved.optimizeDeps.force = true;
62537
62661
  logger.warn(picocolors.exports.yellow(`server.force is deprecated, use optimizeDeps.force instead`));
62538
62662
  }
62539
- // Some plugins that aren't intended to work in the bundling of workers (doing post-processing at build time for example).
62540
- // And Plugins may also have cached that could be corrupted by being used in these extra rollup calls.
62541
- // So we need to separate the worker plugin from the plugin that vite needs to run.
62542
- const [workerPrePlugins, workerNormalPlugins, workerPostPlugins] = sortUserPlugins(config.worker?.plugins);
62543
- const workerResolved = {
62544
- ...resolved,
62545
- isWorker: true,
62546
- mainConfig: resolved
62547
- };
62548
- resolved.worker.plugins = await resolvePlugins(workerResolved, workerPrePlugins, workerNormalPlugins, workerPostPlugins);
62549
- // call configResolved worker plugins hooks
62550
- await Promise.all(resolved.worker.plugins.map((p) => p.configResolved?.(workerResolved)));
62551
- resolved.plugins = await resolvePlugins(resolved, prePlugins, normalPlugins, postPlugins);
62552
- // call configResolved hooks
62553
- await Promise.all(userPlugins.map((p) => p.configResolved?.(resolved)));
62554
62663
  if (process.env.DEBUG) {
62555
62664
  debug(`using resolved config: %O`, {
62556
62665
  ...resolved,
@@ -62776,13 +62885,15 @@ async function loadConfigFromBundledFile(fileName, bundledCode, isESM) {
62776
62885
  // with --experimental-loader themselves, we have to do a hack here:
62777
62886
  // write it to disk, load it with native Node ESM, then delete the file.
62778
62887
  if (isESM) {
62779
- const fileUrl = pathToFileURL(fileName);
62780
- fs$l.writeFileSync(fileName + '.mjs', bundledCode);
62888
+ const fileBase = `${fileName}.timestamp-${Date.now()}`;
62889
+ const fileNameTmp = `${fileBase}.mjs`;
62890
+ const fileUrl = `${pathToFileURL(fileBase)}.mjs`;
62891
+ fs$l.writeFileSync(fileNameTmp, bundledCode);
62781
62892
  try {
62782
- return (await dynamicImport(`${fileUrl}.mjs?t=${Date.now()}`)).default;
62893
+ return (await dynamicImport(fileUrl)).default;
62783
62894
  }
62784
62895
  finally {
62785
- fs$l.unlinkSync(fileName + '.mjs');
62896
+ fs$l.unlinkSync(fileNameTmp);
62786
62897
  }
62787
62898
  }
62788
62899
  // for cjs, we can register a custom loader via `_require.extensions`