vite 5.2.7 → 5.2.9

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.
@@ -7559,21 +7559,29 @@ class MagicString {
7559
7559
  if (searchValue.global) {
7560
7560
  const matches = matchAll(searchValue, this.original);
7561
7561
  matches.forEach((match) => {
7562
- if (match.index != null)
7562
+ if (match.index != null) {
7563
+ const replacement = getReplacement(match, this.original);
7564
+ if (replacement !== match[0]) {
7565
+ this.overwrite(
7566
+ match.index,
7567
+ match.index + match[0].length,
7568
+ replacement
7569
+ );
7570
+ }
7571
+ }
7572
+ });
7573
+ } else {
7574
+ const match = this.original.match(searchValue);
7575
+ if (match && match.index != null) {
7576
+ const replacement = getReplacement(match, this.original);
7577
+ if (replacement !== match[0]) {
7563
7578
  this.overwrite(
7564
7579
  match.index,
7565
7580
  match.index + match[0].length,
7566
- getReplacement(match, this.original),
7581
+ replacement
7567
7582
  );
7568
- });
7569
- } else {
7570
- const match = this.original.match(searchValue);
7571
- if (match && match.index != null)
7572
- this.overwrite(
7573
- match.index,
7574
- match.index + match[0].length,
7575
- getReplacement(match, this.original),
7576
- );
7583
+ }
7584
+ }
7577
7585
  }
7578
7586
  return this;
7579
7587
  }
@@ -7605,7 +7613,9 @@ class MagicString {
7605
7613
  index !== -1;
7606
7614
  index = original.indexOf(string, index + stringLength)
7607
7615
  ) {
7608
- this.overwrite(index, index + stringLength, replacement);
7616
+ const previous = original.slice(index, index + stringLength);
7617
+ if (previous !== replacement)
7618
+ this.overwrite(index, index + stringLength, replacement);
7609
7619
  }
7610
7620
 
7611
7621
  return this;
@@ -9998,7 +10008,7 @@ function makeUrl(scheme, user, host, port, path, query, hash) {
9998
10008
  type: 7 /* Absolute */,
9999
10009
  };
10000
10010
  }
10001
- function parseUrl$2(input) {
10011
+ function parseUrl$3(input) {
10002
10012
  if (isSchemeRelativeUrl(input)) {
10003
10013
  const url = parseAbsoluteUrl('http:' + input);
10004
10014
  url.scheme = '';
@@ -10112,10 +10122,10 @@ function normalizePath$4(url, type) {
10112
10122
  function resolve$2(input, base) {
10113
10123
  if (!input && !base)
10114
10124
  return '';
10115
- const url = parseUrl$2(input);
10125
+ const url = parseUrl$3(input);
10116
10126
  let inputType = url.type;
10117
10127
  if (base && inputType !== 7 /* Absolute */) {
10118
- const baseUrl = parseUrl$2(base);
10128
+ const baseUrl = parseUrl$3(base);
10119
10129
  const baseType = baseUrl.type;
10120
10130
  switch (inputType) {
10121
10131
  case 1 /* Empty */:
@@ -10354,6 +10364,14 @@ class TraceMap {
10354
10364
  function cast$2(map) {
10355
10365
  return map;
10356
10366
  }
10367
+ /**
10368
+ * Returns the encoded (VLQ string) form of the SourceMap's mappings field.
10369
+ */
10370
+ function encodedMappings(map) {
10371
+ var _a;
10372
+ var _b;
10373
+ return ((_a = (_b = cast$2(map))._encoded) !== null && _a !== void 0 ? _a : (_b._encoded = encode$1(cast$2(map)._decoded)));
10374
+ }
10357
10375
  /**
10358
10376
  * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
10359
10377
  */
@@ -10402,6 +10420,32 @@ function originalPositionFor$1(map, needle) {
10402
10420
  const { names, resolvedSources } = map;
10403
10421
  return OMapping(resolvedSources[segment[SOURCES_INDEX$1]], segment[SOURCE_LINE$1] + 1, segment[SOURCE_COLUMN$1], segment.length === 5 ? names[segment[NAMES_INDEX$1]] : null);
10404
10422
  }
10423
+ /**
10424
+ * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects
10425
+ * a sourcemap, or to JSON.stringify.
10426
+ */
10427
+ function decodedMap(map) {
10428
+ return clone(map, decodedMappings(map));
10429
+ }
10430
+ /**
10431
+ * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects
10432
+ * a sourcemap, or to JSON.stringify.
10433
+ */
10434
+ function encodedMap(map) {
10435
+ return clone(map, encodedMappings(map));
10436
+ }
10437
+ function clone(map, mappings) {
10438
+ return {
10439
+ version: map.version,
10440
+ file: map.file,
10441
+ names: map.names,
10442
+ sourceRoot: map.sourceRoot,
10443
+ sources: map.sources,
10444
+ sourcesContent: map.sourcesContent,
10445
+ mappings,
10446
+ ignoreList: map.ignoreList || map.x_google_ignoreList,
10447
+ };
10448
+ }
10405
10449
  function OMapping(source, line, column, name) {
10406
10450
  return { source, line, column, name };
10407
10451
  }
@@ -19258,10 +19302,10 @@ var string$2 = {};
19258
19302
 
19259
19303
  Object.defineProperty(string$2, "__esModule", { value: true });
19260
19304
  string$2.isEmpty = string$2.isString = void 0;
19261
- function isString(input) {
19305
+ function isString$1(input) {
19262
19306
  return typeof input === 'string';
19263
19307
  }
19264
- string$2.isString = isString;
19308
+ string$2.isString = isString$1;
19265
19309
  function isEmpty$1(input) {
19266
19310
  return input === '';
19267
19311
  }
@@ -29291,7 +29335,7 @@ var postcssrc = /*@__PURE__*/getDefaultExportFromCjs(src$1);
29291
29335
 
29292
29336
  // Copyright 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Simon Lydell
29293
29337
  // License: MIT.
29294
- var Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace;
29338
+ var HashbangComment, Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace;
29295
29339
  RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:[^\]\\\n\r\u2028\u2029]+|\\.)*\]|[^\/\\\n\r\u2028\u2029]+|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/yu;
29296
29340
  Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y;
29297
29341
  Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]+|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/yu;
@@ -29302,6 +29346,7 @@ WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/yu;
29302
29346
  LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y;
29303
29347
  MultiLineComment = /\/\*(?:[^*]+|\*(?!\/))*(\*\/)?/y;
29304
29348
  SingleLineComment = /\/\/.*/y;
29349
+ HashbangComment = /^#!.*/;
29305
29350
  JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y;
29306
29351
  JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/yu;
29307
29352
  JSXString = /(['"])(?:[^'"]+|(?!\1)['"])*(\1)?/y;
@@ -29322,6 +29367,13 @@ var jsTokens_1 = function*(input, {jsx = false} = {}) {
29322
29367
  braces = [];
29323
29368
  parenNesting = 0;
29324
29369
  postfixIncDec = false;
29370
+ if (match = HashbangComment.exec(input)) {
29371
+ yield ({
29372
+ type: "HashbangComment",
29373
+ value: match[0]
29374
+ });
29375
+ lastIndex = match[0].length;
29376
+ }
29325
29377
  while (lastIndex < length) {
29326
29378
  mode = stack[stack.length - 1];
29327
29379
  switch (mode.tag) {
@@ -29697,6 +29749,10 @@ function stripLiteralJsTokens(code, options) {
29697
29749
  continue;
29698
29750
  }
29699
29751
  if (token.type === "StringLiteral") {
29752
+ if (!token.closed) {
29753
+ result += token.value;
29754
+ continue;
29755
+ }
29700
29756
  const body = token.value.slice(1, -1);
29701
29757
  if (filter(body)) {
29702
29758
  result += token.value[0] + FILL.repeat(body.length) + token.value[token.value.length - 1];
@@ -31185,7 +31241,10 @@ function injectNonceAttributeTagHook(config) {
31185
31241
  (node.nodeName === 'link' &&
31186
31242
  node.attrs.some((attr) => attr.name === 'rel' &&
31187
31243
  parseRelAttr(attr.value).some((a) => processRelType.has(a))))) {
31188
- s.appendRight(node.sourceCodeLocation.startTag.endOffset - 1, ` nonce="${nonce}"`);
31244
+ // if the closing of the start tag includes a `/`, the offset should be 2 so the nonce
31245
+ // is appended prior to the `/`
31246
+ const appendOffset = html[node.sourceCodeLocation.startTag.endOffset - 2] === '/' ? 2 : 1;
31247
+ s.appendRight(node.sourceCodeLocation.startTag.endOffset - appendOffset, ` nonce="${nonce}"`);
31189
31248
  }
31190
31249
  });
31191
31250
  return s.toString();
@@ -31873,6 +31932,7 @@ function cssPostPlugin(config) {
31873
31932
  for (const file in bundle) {
31874
31933
  const chunk = bundle[file];
31875
31934
  if (chunk.type === 'chunk') {
31935
+ let chunkImportsPureCssChunk = false;
31876
31936
  // remove pure css chunk from other chunk's imports,
31877
31937
  // and also register the emitted CSS files under the importer
31878
31938
  // chunks instead.
@@ -31881,11 +31941,14 @@ function cssPostPlugin(config) {
31881
31941
  const { importedCss, importedAssets } = bundle[file].viteMetadata;
31882
31942
  importedCss.forEach((file) => chunk.viteMetadata.importedCss.add(file));
31883
31943
  importedAssets.forEach((file) => chunk.viteMetadata.importedAssets.add(file));
31944
+ chunkImportsPureCssChunk = true;
31884
31945
  return false;
31885
31946
  }
31886
31947
  return true;
31887
31948
  });
31888
- chunk.code = replaceEmptyChunk(chunk.code);
31949
+ if (chunkImportsPureCssChunk) {
31950
+ chunk.code = replaceEmptyChunk(chunk.code);
31951
+ }
31889
31952
  }
31890
31953
  }
31891
31954
  const removedPureCssFiles = removedPureCssFilesCache.get(config);
@@ -32293,8 +32356,8 @@ function createCachedImport(imp) {
32293
32356
  return cached;
32294
32357
  };
32295
32358
  }
32296
- const importPostcssImport = createCachedImport(() => import('./dep-C1QONNHf.js').then(function (n) { return n.i; }));
32297
- const importPostcssModules = createCachedImport(() => import('./dep-ThQVBShq.js').then(function (n) { return n.i; }));
32359
+ const importPostcssImport = createCachedImport(() => import('./dep-DHU7GEFN.js').then(function (n) { return n.i; }));
32360
+ const importPostcssModules = createCachedImport(() => import('./dep-DbzVZKyq.js').then(function (n) { return n.i; }));
32298
32361
  const importPostcss = createCachedImport(() => import('postcss'));
32299
32362
  const preprocessorWorkerControllerCache = new WeakMap();
32300
32363
  let alwaysFakeWorkerWorkerControllerCache;
@@ -33190,12 +33253,13 @@ async function compileLightningCSS(id, src, config, urlReplacer) {
33190
33253
  switch (dep.type) {
33191
33254
  case 'url':
33192
33255
  if (skipUrlReplacer(dep.url)) {
33193
- css = css.replace(dep.placeholder, dep.url);
33256
+ css = css.replace(dep.placeholder, () => dep.url);
33194
33257
  break;
33195
33258
  }
33196
33259
  deps.add(dep.url);
33197
33260
  if (urlReplacer) {
33198
- css = css.replace(dep.placeholder, await urlReplacer(dep.url, id));
33261
+ const replaceUrl = await urlReplacer(dep.url, id);
33262
+ css = css.replace(dep.placeholder, () => replaceUrl);
33199
33263
  }
33200
33264
  break;
33201
33265
  default:
@@ -42286,7 +42350,7 @@ var debug$e = srcExports('finalhandler');
42286
42350
  var encodeUrl = encodeurl;
42287
42351
  var escapeHtml = escapeHtml_1;
42288
42352
  var onFinished = onFinishedExports;
42289
- var parseUrl$1 = parseurlExports;
42353
+ var parseUrl$2 = parseurlExports;
42290
42354
  var statuses = statuses$1;
42291
42355
  var unpipe = unpipe_1;
42292
42356
 
@@ -42490,7 +42554,7 @@ function getErrorStatusCode (err) {
42490
42554
 
42491
42555
  function getResourceName (req) {
42492
42556
  try {
42493
- return parseUrl$1.original(req).pathname
42557
+ return parseUrl$2.original(req).pathname
42494
42558
  } catch (e) {
42495
42559
  return 'resource'
42496
42560
  }
@@ -42649,7 +42713,7 @@ var EventEmitter$3 = require$$0$5.EventEmitter;
42649
42713
  var finalhandler = finalhandler_1;
42650
42714
  var http$4 = require$$1;
42651
42715
  var merge = utilsMergeExports;
42652
- var parseUrl = parseurlExports;
42716
+ var parseUrl$1 = parseurlExports;
42653
42717
 
42654
42718
  /**
42655
42719
  * Module exports.
@@ -42784,7 +42848,7 @@ proto.handle = function handle(req, res, out) {
42784
42848
  }
42785
42849
 
42786
42850
  // route data
42787
- var path = parseUrl(req).pathname || '/';
42851
+ var path = parseUrl$1(req).pathname || '/';
42788
42852
  var route = layer.route;
42789
42853
 
42790
42854
  // skip this layer if the route doesn't match
@@ -49063,6 +49127,23 @@ async function replaceDefine(code, id, define, config) {
49063
49127
  sourcefile: id,
49064
49128
  sourcemap: config.command === 'build' ? !!config.build.sourcemap : true,
49065
49129
  });
49130
+ // remove esbuild's <define:...> source entries
49131
+ // since they would confuse source map remapping/collapsing which expects a single source
49132
+ if (result.map.includes('<define:')) {
49133
+ const originalMap = new TraceMap(result.map);
49134
+ if (originalMap.sources.length >= 2) {
49135
+ const sourceIndex = originalMap.sources.indexOf(id);
49136
+ const decoded = decodedMap(originalMap);
49137
+ decoded.sources = [id];
49138
+ decoded.mappings = decoded.mappings.map((segments) => segments.filter((segment) => {
49139
+ // modify and filter
49140
+ const index = segment[1];
49141
+ segment[1] = 0;
49142
+ return index === sourceIndex;
49143
+ }));
49144
+ result.map = JSON.stringify(encodedMap(new TraceMap(decoded)));
49145
+ }
49146
+ }
49066
49147
  for (const marker in replacementMarkers) {
49067
49148
  result.code = result.code.replaceAll(marker, replacementMarkers[marker]);
49068
49149
  }
@@ -51428,12 +51509,10 @@ function esbuildScanPlugin(config, container, depImports, missing, entries) {
51428
51509
  // Avoid matching the content of the comment
51429
51510
  raw = raw.replace(commentRE, '<!---->');
51430
51511
  const isHtml = p.endsWith('.html');
51431
- scriptRE.lastIndex = 0;
51432
51512
  let js = '';
51433
51513
  let scriptId = 0;
51434
- let match;
51435
- while ((match = scriptRE.exec(raw))) {
51436
- const [, openTag, content] = match;
51514
+ const matches = raw.matchAll(scriptRE);
51515
+ for (const [, openTag, content] of matches) {
51437
51516
  const typeMatch = openTag.match(typeRE);
51438
51517
  const type = typeMatch && (typeMatch[1] || typeMatch[2] || typeMatch[3]);
51439
51518
  const langMatch = openTag.match(langRE);
@@ -52565,9 +52644,13 @@ function runOptimizeDeps(resolvedConfig, depsInfo, ssr) {
52565
52644
  // No need to wait, we can clean up in the background because temp folders
52566
52645
  // are unique per run
52567
52646
  debug$7?.(colors$1.green(`removing cache dir ${processingCacheDir}`));
52568
- fsp.rm(processingCacheDir, { recursive: true, force: true }).catch(() => {
52647
+ try {
52648
+ // When exiting the process, `fsp.rm` may not take effect, so we use `fs.rmSync`
52649
+ fs$l.rmSync(processingCacheDir, { recursive: true, force: true });
52650
+ }
52651
+ catch (error) {
52569
52652
  // Ignore errors
52570
- });
52653
+ }
52571
52654
  }
52572
52655
  };
52573
52656
  const successfulResult = {
@@ -54644,7 +54727,7 @@ function walk(root, { onIdentifier, onImportMeta, onDynamicImport }) {
54644
54727
  identifiers.push([node, parentStack.slice(0)]);
54645
54728
  }
54646
54729
  }
54647
- else if (isFunction(node)) {
54730
+ else if (isFunction$1(node)) {
54648
54731
  // If it is a function declaration, it could be shadowing an import
54649
54732
  // Add its name to the scope so it won't get replaced
54650
54733
  if (node.type === 'FunctionDeclaration') {
@@ -54724,7 +54807,7 @@ function isRefIdentifier(id, parent, parentStack) {
54724
54807
  parent.id === id)) {
54725
54808
  return false;
54726
54809
  }
54727
- if (isFunction(parent)) {
54810
+ if (isFunction$1(parent)) {
54728
54811
  // function declaration/expression id
54729
54812
  if (parent.id === id) {
54730
54813
  return false;
@@ -54769,7 +54852,7 @@ function isRefIdentifier(id, parent, parentStack) {
54769
54852
  const isStaticProperty = (node) => node && node.type === 'Property' && !node.computed;
54770
54853
  const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
54771
54854
  const functionNodeTypeRE = /Function(?:Expression|Declaration)$|Method$/;
54772
- function isFunction(node) {
54855
+ function isFunction$1(node) {
54773
54856
  return functionNodeTypeRE.test(node.type);
54774
54857
  }
54775
54858
  const blockNodeTypeRE = /^BlockStatement$|^For(?:In|Of)?Statement$/;
@@ -54777,7 +54860,7 @@ function isBlock(node) {
54777
54860
  return blockNodeTypeRE.test(node.type);
54778
54861
  }
54779
54862
  function findParentScope(parentStack, isVar = false) {
54780
- return parentStack.find(isVar ? isFunction : isBlock);
54863
+ return parentStack.find(isVar ? isFunction$1 : isBlock);
54781
54864
  }
54782
54865
  function isInDestructuringAssignment(parent, parentStack) {
54783
54866
  if (parent &&
@@ -62050,6 +62133,30 @@ var Writable = require$$0$7.Writable;
62050
62133
  var assert = require$$5;
62051
62134
  var debug$5 = debug_1;
62052
62135
 
62136
+ // Whether to use the native URL object or the legacy url module
62137
+ var useNativeURL = false;
62138
+ try {
62139
+ assert(new URL$1());
62140
+ }
62141
+ catch (error) {
62142
+ useNativeURL = error.code === "ERR_INVALID_URL";
62143
+ }
62144
+
62145
+ // URL fields to preserve in copy operations
62146
+ var preservedUrlFields = [
62147
+ "auth",
62148
+ "host",
62149
+ "hostname",
62150
+ "href",
62151
+ "path",
62152
+ "pathname",
62153
+ "port",
62154
+ "protocol",
62155
+ "query",
62156
+ "search",
62157
+ "hash",
62158
+ ];
62159
+
62053
62160
  // Create handlers that pass events from native requests
62054
62161
  var events = ["abort", "aborted", "connect", "error", "socket", "timeout"];
62055
62162
  var eventHandlers = Object.create(null);
@@ -62060,13 +62167,19 @@ events.forEach(function (event) {
62060
62167
  });
62061
62168
 
62062
62169
  // Error types with codes
62170
+ var InvalidUrlError = createErrorType(
62171
+ "ERR_INVALID_URL",
62172
+ "Invalid URL",
62173
+ TypeError
62174
+ );
62063
62175
  var RedirectionError = createErrorType(
62064
62176
  "ERR_FR_REDIRECTION_FAILURE",
62065
62177
  "Redirected request failed"
62066
62178
  );
62067
62179
  var TooManyRedirectsError = createErrorType(
62068
62180
  "ERR_FR_TOO_MANY_REDIRECTS",
62069
- "Maximum number of redirects exceeded"
62181
+ "Maximum number of redirects exceeded",
62182
+ RedirectionError
62070
62183
  );
62071
62184
  var MaxBodyLengthExceededError = createErrorType(
62072
62185
  "ERR_FR_MAX_BODY_LENGTH_EXCEEDED",
@@ -62077,6 +62190,9 @@ var WriteAfterEndError = createErrorType(
62077
62190
  "write after end"
62078
62191
  );
62079
62192
 
62193
+ // istanbul ignore next
62194
+ var destroy = Writable.prototype.destroy || noop;
62195
+
62080
62196
  // An HTTP(S) request that can be redirected
62081
62197
  function RedirectableRequest(options, responseCallback) {
62082
62198
  // Initialize the request
@@ -62098,7 +62214,13 @@ function RedirectableRequest(options, responseCallback) {
62098
62214
  // React to responses of native requests
62099
62215
  var self = this;
62100
62216
  this._onNativeResponse = function (response) {
62101
- self._processResponse(response);
62217
+ try {
62218
+ self._processResponse(response);
62219
+ }
62220
+ catch (cause) {
62221
+ self.emit("error", cause instanceof RedirectionError ?
62222
+ cause : new RedirectionError({ cause: cause }));
62223
+ }
62102
62224
  };
62103
62225
 
62104
62226
  // Perform the first request
@@ -62107,10 +62229,17 @@ function RedirectableRequest(options, responseCallback) {
62107
62229
  RedirectableRequest.prototype = Object.create(Writable.prototype);
62108
62230
 
62109
62231
  RedirectableRequest.prototype.abort = function () {
62110
- abortRequest(this._currentRequest);
62232
+ destroyRequest(this._currentRequest);
62233
+ this._currentRequest.abort();
62111
62234
  this.emit("abort");
62112
62235
  };
62113
62236
 
62237
+ RedirectableRequest.prototype.destroy = function (error) {
62238
+ destroyRequest(this._currentRequest, error);
62239
+ destroy.call(this, error);
62240
+ return this;
62241
+ };
62242
+
62114
62243
  // Writes buffered data to the current native request
62115
62244
  RedirectableRequest.prototype.write = function (data, encoding, callback) {
62116
62245
  // Writing is not allowed if end has been called
@@ -62119,10 +62248,10 @@ RedirectableRequest.prototype.write = function (data, encoding, callback) {
62119
62248
  }
62120
62249
 
62121
62250
  // Validate input and shift parameters if necessary
62122
- if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) {
62251
+ if (!isString(data) && !isBuffer(data)) {
62123
62252
  throw new TypeError("data should be a string, Buffer or Uint8Array");
62124
62253
  }
62125
- if (typeof encoding === "function") {
62254
+ if (isFunction(encoding)) {
62126
62255
  callback = encoding;
62127
62256
  encoding = null;
62128
62257
  }
@@ -62151,11 +62280,11 @@ RedirectableRequest.prototype.write = function (data, encoding, callback) {
62151
62280
  // Ends the current native request
62152
62281
  RedirectableRequest.prototype.end = function (data, encoding, callback) {
62153
62282
  // Shift parameters if necessary
62154
- if (typeof data === "function") {
62283
+ if (isFunction(data)) {
62155
62284
  callback = data;
62156
62285
  data = encoding = null;
62157
62286
  }
62158
- else if (typeof encoding === "function") {
62287
+ else if (isFunction(encoding)) {
62159
62288
  callback = encoding;
62160
62289
  encoding = null;
62161
62290
  }
@@ -62223,6 +62352,7 @@ RedirectableRequest.prototype.setTimeout = function (msecs, callback) {
62223
62352
  self.removeListener("abort", clearTimer);
62224
62353
  self.removeListener("error", clearTimer);
62225
62354
  self.removeListener("response", clearTimer);
62355
+ self.removeListener("close", clearTimer);
62226
62356
  if (callback) {
62227
62357
  self.removeListener("timeout", callback);
62228
62358
  }
@@ -62249,6 +62379,7 @@ RedirectableRequest.prototype.setTimeout = function (msecs, callback) {
62249
62379
  this.on("abort", clearTimer);
62250
62380
  this.on("error", clearTimer);
62251
62381
  this.on("response", clearTimer);
62382
+ this.on("close", clearTimer);
62252
62383
 
62253
62384
  return this;
62254
62385
  };
@@ -62307,8 +62438,7 @@ RedirectableRequest.prototype._performRequest = function () {
62307
62438
  var protocol = this._options.protocol;
62308
62439
  var nativeProtocol = this._options.nativeProtocols[protocol];
62309
62440
  if (!nativeProtocol) {
62310
- this.emit("error", new TypeError("Unsupported protocol " + protocol));
62311
- return;
62441
+ throw new TypeError("Unsupported protocol " + protocol);
62312
62442
  }
62313
62443
 
62314
62444
  // If specified, use the agent corresponding to the protocol
@@ -62318,21 +62448,26 @@ RedirectableRequest.prototype._performRequest = function () {
62318
62448
  this._options.agent = this._options.agents[scheme];
62319
62449
  }
62320
62450
 
62321
- // Create the native request
62451
+ // Create the native request and set up its event handlers
62322
62452
  var request = this._currentRequest =
62323
62453
  nativeProtocol.request(this._options, this._onNativeResponse);
62324
- this._currentUrl = url.format(this._options);
62325
-
62326
- // Set up event handlers
62327
62454
  request._redirectable = this;
62328
- for (var e = 0; e < events.length; e++) {
62329
- request.on(events[e], eventHandlers[events[e]]);
62455
+ for (var event of events) {
62456
+ request.on(event, eventHandlers[event]);
62330
62457
  }
62331
62458
 
62459
+ // RFC7230§5.3.1: When making a request directly to an origin server, […]
62460
+ // a client MUST send only the absolute path […] as the request-target.
62461
+ this._currentUrl = /^\//.test(this._options.path) ?
62462
+ url.format(this._options) :
62463
+ // When making a request to a proxy, […]
62464
+ // a client MUST send the target URI in absolute-form […].
62465
+ this._options.path;
62466
+
62332
62467
  // End a redirected request
62333
62468
  // (The first request must be ended explicitly with RedirectableRequest#end)
62334
62469
  if (this._isRedirect) {
62335
- // Write the request entity and end.
62470
+ // Write the request entity and end
62336
62471
  var i = 0;
62337
62472
  var self = this;
62338
62473
  var buffers = this._requestBodyBuffers;
@@ -62395,15 +62530,14 @@ RedirectableRequest.prototype._processResponse = function (response) {
62395
62530
  }
62396
62531
 
62397
62532
  // The response is a redirect, so abort the current request
62398
- abortRequest(this._currentRequest);
62533
+ destroyRequest(this._currentRequest);
62399
62534
  // Discard the remainder of the response to avoid waiting for data
62400
62535
  response.destroy();
62401
62536
 
62402
62537
  // RFC7231§6.4: A client SHOULD detect and intervene
62403
62538
  // in cyclical redirections (i.e., "infinite" redirection loops).
62404
62539
  if (++this._redirectCount > this._options.maxRedirects) {
62405
- this.emit("error", new TooManyRedirectsError());
62406
- return;
62540
+ throw new TooManyRedirectsError();
62407
62541
  }
62408
62542
 
62409
62543
  // Store the request headers if applicable
@@ -62437,38 +62571,28 @@ RedirectableRequest.prototype._processResponse = function (response) {
62437
62571
  var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);
62438
62572
 
62439
62573
  // If the redirect is relative, carry over the host of the last request
62440
- var currentUrlParts = url.parse(this._currentUrl);
62574
+ var currentUrlParts = parseUrl(this._currentUrl);
62441
62575
  var currentHost = currentHostHeader || currentUrlParts.host;
62442
62576
  var currentUrl = /^\w+:/.test(location) ? this._currentUrl :
62443
62577
  url.format(Object.assign(currentUrlParts, { host: currentHost }));
62444
62578
 
62445
- // Determine the URL of the redirection
62446
- var redirectUrl;
62447
- try {
62448
- redirectUrl = url.resolve(currentUrl, location);
62449
- }
62450
- catch (cause) {
62451
- this.emit("error", new RedirectionError(cause));
62452
- return;
62453
- }
62454
-
62455
62579
  // Create the redirected request
62456
- debug$5("redirecting to", redirectUrl);
62580
+ var redirectUrl = resolveUrl(location, currentUrl);
62581
+ debug$5("redirecting to", redirectUrl.href);
62457
62582
  this._isRedirect = true;
62458
- var redirectUrlParts = url.parse(redirectUrl);
62459
- Object.assign(this._options, redirectUrlParts);
62583
+ spreadUrlObject(redirectUrl, this._options);
62460
62584
 
62461
62585
  // Drop confidential headers when redirecting to a less secure protocol
62462
62586
  // or to a different domain that is not a superdomain
62463
- if (redirectUrlParts.protocol !== currentUrlParts.protocol &&
62464
- redirectUrlParts.protocol !== "https:" ||
62465
- redirectUrlParts.host !== currentHost &&
62466
- !isSubdomain(redirectUrlParts.host, currentHost)) {
62467
- removeMatchingHeaders(/^(?:authorization|cookie)$/i, this._options.headers);
62587
+ if (redirectUrl.protocol !== currentUrlParts.protocol &&
62588
+ redirectUrl.protocol !== "https:" ||
62589
+ redirectUrl.host !== currentHost &&
62590
+ !isSubdomain(redirectUrl.host, currentHost)) {
62591
+ removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers);
62468
62592
  }
62469
62593
 
62470
62594
  // Evaluate the beforeRedirect callback
62471
- if (typeof beforeRedirect === "function") {
62595
+ if (isFunction(beforeRedirect)) {
62472
62596
  var responseDetails = {
62473
62597
  headers: response.headers,
62474
62598
  statusCode: statusCode,
@@ -62478,23 +62602,12 @@ RedirectableRequest.prototype._processResponse = function (response) {
62478
62602
  method: method,
62479
62603
  headers: requestHeaders,
62480
62604
  };
62481
- try {
62482
- beforeRedirect(this._options, responseDetails, requestDetails);
62483
- }
62484
- catch (err) {
62485
- this.emit("error", err);
62486
- return;
62487
- }
62605
+ beforeRedirect(this._options, responseDetails, requestDetails);
62488
62606
  this._sanitizeOptions(this._options);
62489
62607
  }
62490
62608
 
62491
62609
  // Perform the redirected request
62492
- try {
62493
- this._performRequest();
62494
- }
62495
- catch (cause) {
62496
- this.emit("error", new RedirectionError(cause));
62497
- }
62610
+ this._performRequest();
62498
62611
  };
62499
62612
 
62500
62613
  // Wraps the key/value object of protocols with redirect functionality
@@ -62514,26 +62627,19 @@ function wrap(protocols) {
62514
62627
 
62515
62628
  // Executes a request, following redirects
62516
62629
  function request(input, options, callback) {
62517
- // Parse parameters
62518
- if (typeof input === "string") {
62519
- var urlStr = input;
62520
- try {
62521
- input = urlToOptions(new URL$1(urlStr));
62522
- }
62523
- catch (err) {
62524
- /* istanbul ignore next */
62525
- input = url.parse(urlStr);
62526
- }
62630
+ // Parse parameters, ensuring that input is an object
62631
+ if (isURL(input)) {
62632
+ input = spreadUrlObject(input);
62527
62633
  }
62528
- else if (URL$1 && (input instanceof URL$1)) {
62529
- input = urlToOptions(input);
62634
+ else if (isString(input)) {
62635
+ input = spreadUrlObject(parseUrl(input));
62530
62636
  }
62531
62637
  else {
62532
62638
  callback = options;
62533
- options = input;
62639
+ options = validateUrl(input);
62534
62640
  input = { protocol: protocol };
62535
62641
  }
62536
- if (typeof options === "function") {
62642
+ if (isFunction(options)) {
62537
62643
  callback = options;
62538
62644
  options = null;
62539
62645
  }
@@ -62544,6 +62650,9 @@ function wrap(protocols) {
62544
62650
  maxBodyLength: exports.maxBodyLength,
62545
62651
  }, input, options);
62546
62652
  options.nativeProtocols = nativeProtocols;
62653
+ if (!isString(options.host) && !isString(options.hostname)) {
62654
+ options.hostname = "::1";
62655
+ }
62547
62656
 
62548
62657
  assert.equal(options.protocol, protocol, "protocol mismatch");
62549
62658
  debug$5("options", options);
@@ -62566,27 +62675,57 @@ function wrap(protocols) {
62566
62675
  return exports;
62567
62676
  }
62568
62677
 
62569
- /* istanbul ignore next */
62570
62678
  function noop() { /* empty */ }
62571
62679
 
62572
- // from https://github.com/nodejs/node/blob/master/lib/internal/url.js
62573
- function urlToOptions(urlObject) {
62574
- var options = {
62575
- protocol: urlObject.protocol,
62576
- hostname: urlObject.hostname.startsWith("[") ?
62577
- /* istanbul ignore next */
62578
- urlObject.hostname.slice(1, -1) :
62579
- urlObject.hostname,
62580
- hash: urlObject.hash,
62581
- search: urlObject.search,
62582
- pathname: urlObject.pathname,
62583
- path: urlObject.pathname + urlObject.search,
62584
- href: urlObject.href,
62585
- };
62586
- if (urlObject.port !== "") {
62587
- options.port = Number(urlObject.port);
62680
+ function parseUrl(input) {
62681
+ var parsed;
62682
+ /* istanbul ignore else */
62683
+ if (useNativeURL) {
62684
+ parsed = new URL$1(input);
62685
+ }
62686
+ else {
62687
+ // Ensure the URL is valid and absolute
62688
+ parsed = validateUrl(url.parse(input));
62689
+ if (!isString(parsed.protocol)) {
62690
+ throw new InvalidUrlError({ input });
62691
+ }
62692
+ }
62693
+ return parsed;
62694
+ }
62695
+
62696
+ function resolveUrl(relative, base) {
62697
+ /* istanbul ignore next */
62698
+ return useNativeURL ? new URL$1(relative, base) : parseUrl(url.resolve(base, relative));
62699
+ }
62700
+
62701
+ function validateUrl(input) {
62702
+ if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) {
62703
+ throw new InvalidUrlError({ input: input.href || input });
62588
62704
  }
62589
- return options;
62705
+ if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) {
62706
+ throw new InvalidUrlError({ input: input.href || input });
62707
+ }
62708
+ return input;
62709
+ }
62710
+
62711
+ function spreadUrlObject(urlObject, target) {
62712
+ var spread = target || {};
62713
+ for (var key of preservedUrlFields) {
62714
+ spread[key] = urlObject[key];
62715
+ }
62716
+
62717
+ // Fix IPv6 hostname
62718
+ if (spread.hostname.startsWith("[")) {
62719
+ spread.hostname = spread.hostname.slice(1, -1);
62720
+ }
62721
+ // Ensure port is a number
62722
+ if (spread.port !== "") {
62723
+ spread.port = Number(spread.port);
62724
+ }
62725
+ // Concatenate path
62726
+ spread.path = spread.search ? spread.pathname + spread.search : spread.pathname;
62727
+
62728
+ return spread;
62590
62729
  }
62591
62730
 
62592
62731
  function removeMatchingHeaders(regex, headers) {
@@ -62601,37 +62740,60 @@ function removeMatchingHeaders(regex, headers) {
62601
62740
  undefined : String(lastValue).trim();
62602
62741
  }
62603
62742
 
62604
- function createErrorType(code, defaultMessage) {
62605
- function CustomError(cause) {
62743
+ function createErrorType(code, message, baseClass) {
62744
+ // Create constructor
62745
+ function CustomError(properties) {
62606
62746
  Error.captureStackTrace(this, this.constructor);
62607
- if (!cause) {
62608
- this.message = defaultMessage;
62609
- }
62610
- else {
62611
- this.message = defaultMessage + ": " + cause.message;
62612
- this.cause = cause;
62613
- }
62747
+ Object.assign(this, properties || {});
62748
+ this.code = code;
62749
+ this.message = this.cause ? message + ": " + this.cause.message : message;
62614
62750
  }
62615
- CustomError.prototype = new Error();
62616
- CustomError.prototype.constructor = CustomError;
62617
- CustomError.prototype.name = "Error [" + code + "]";
62618
- CustomError.prototype.code = code;
62751
+
62752
+ // Attach constructor and set default properties
62753
+ CustomError.prototype = new (baseClass || Error)();
62754
+ Object.defineProperties(CustomError.prototype, {
62755
+ constructor: {
62756
+ value: CustomError,
62757
+ enumerable: false,
62758
+ },
62759
+ name: {
62760
+ value: "Error [" + code + "]",
62761
+ enumerable: false,
62762
+ },
62763
+ });
62619
62764
  return CustomError;
62620
62765
  }
62621
62766
 
62622
- function abortRequest(request) {
62623
- for (var e = 0; e < events.length; e++) {
62624
- request.removeListener(events[e], eventHandlers[events[e]]);
62767
+ function destroyRequest(request, error) {
62768
+ for (var event of events) {
62769
+ request.removeListener(event, eventHandlers[event]);
62625
62770
  }
62626
62771
  request.on("error", noop);
62627
- request.abort();
62772
+ request.destroy(error);
62628
62773
  }
62629
62774
 
62630
62775
  function isSubdomain(subdomain, domain) {
62631
- const dot = subdomain.length - domain.length - 1;
62776
+ assert(isString(subdomain) && isString(domain));
62777
+ var dot = subdomain.length - domain.length - 1;
62632
62778
  return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
62633
62779
  }
62634
62780
 
62781
+ function isString(value) {
62782
+ return typeof value === "string" || value instanceof String;
62783
+ }
62784
+
62785
+ function isFunction(value) {
62786
+ return typeof value === "function";
62787
+ }
62788
+
62789
+ function isBuffer(value) {
62790
+ return typeof value === "object" && ("length" in value);
62791
+ }
62792
+
62793
+ function isURL(value) {
62794
+ return URL$1 && value instanceof URL$1;
62795
+ }
62796
+
62635
62797
  // Exports
62636
62798
  followRedirects$1.exports = wrap({ http: http$1, https: https$1 });
62637
62799
  followRedirects$1.exports.wrap = wrap;
@@ -64055,6 +64217,13 @@ class ModuleNode {
64055
64217
  ssrModule = null;
64056
64218
  ssrError = null;
64057
64219
  lastHMRTimestamp = 0;
64220
+ /**
64221
+ * `import.meta.hot.invalidate` is called by the client.
64222
+ * If there's multiple clients, multiple `invalidate` request is received.
64223
+ * This property is used to dedupe those request to avoid multiple updates happening.
64224
+ * @internal
64225
+ */
64226
+ lastHMRInvalidationReceived = false;
64058
64227
  lastInvalidationTimestamp = 0;
64059
64228
  /**
64060
64229
  * If the module only needs to update its imports timestamp (e.g. within an HMR chain),
@@ -64179,6 +64348,7 @@ class ModuleGraph {
64179
64348
  seen.add(mod);
64180
64349
  if (isHmr) {
64181
64350
  mod.lastHMRTimestamp = timestamp;
64351
+ mod.lastHMRInvalidationReceived = false;
64182
64352
  }
64183
64353
  else {
64184
64354
  // Save the timestamp for this invalidation, so we can avoid caching the result of possible already started
@@ -64802,7 +64972,11 @@ async function _createServer(inlineConfig = {}, options) {
64802
64972
  });
64803
64973
  hot.on('vite:invalidate', async ({ path, message }) => {
64804
64974
  const mod = moduleGraph.urlToModuleMap.get(path);
64805
- if (mod && mod.isSelfAccepting && mod.lastHMRTimestamp > 0) {
64975
+ if (mod &&
64976
+ mod.isSelfAccepting &&
64977
+ mod.lastHMRTimestamp > 0 &&
64978
+ !mod.lastHMRInvalidationReceived) {
64979
+ mod.lastHMRInvalidationReceived = true;
64806
64980
  config.logger.info(colors$1.yellow(`hmr invalidate `) +
64807
64981
  colors$1.dim(path) +
64808
64982
  (message ? ` ${message}` : ''), { timestamp: true });
@@ -65488,6 +65662,7 @@ function handlePrunedModules(mods, { hot }) {
65488
65662
  const t = Date.now();
65489
65663
  mods.forEach((mod) => {
65490
65664
  mod.lastHMRTimestamp = t;
65665
+ mod.lastHMRInvalidationReceived = false;
65491
65666
  debugHmr?.(`[dispose] ${colors$1.dim(mod.file)}`);
65492
65667
  });
65493
65668
  hot.send({
@@ -66800,13 +66975,7 @@ function buildImportAnalysisPlugin(config) {
66800
66975
  const fileDepsCode = `[${fileDeps
66801
66976
  .map((fileDep) => fileDep.runtime ? fileDep.url : JSON.stringify(fileDep.url))
66802
66977
  .join(',')}]`;
66803
- const mapDepsCode = `\
66804
- function __vite__mapDeps(indexes) {
66805
- if (!__vite__mapDeps.viteFileDeps) {
66806
- __vite__mapDeps.viteFileDeps = ${fileDepsCode}
66807
- }
66808
- return indexes.map((i) => __vite__mapDeps.viteFileDeps[i])
66809
- }\n`;
66978
+ const mapDepsCode = `const __vite__fileDeps=${fileDepsCode},__vite__mapDeps=i=>i.map(i=>__vite__fileDeps[i]);\n`;
66810
66979
  // inject extra code at the top or next line of hashbang
66811
66980
  if (code.startsWith('#!')) {
66812
66981
  s.prependLeft(code.indexOf('\n') + 1, mapDepsCode);