vite 6.0.0-alpha.0 → 6.0.0-alpha.2

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
  }
@@ -19261,10 +19305,10 @@ var string$2 = {};
19261
19305
 
19262
19306
  Object.defineProperty(string$2, "__esModule", { value: true });
19263
19307
  string$2.isEmpty = string$2.isString = void 0;
19264
- function isString(input) {
19308
+ function isString$1(input) {
19265
19309
  return typeof input === 'string';
19266
19310
  }
19267
- string$2.isString = isString;
19311
+ string$2.isString = isString$1;
19268
19312
  function isEmpty$1(input) {
19269
19313
  return input === '';
19270
19314
  }
@@ -39082,7 +39126,7 @@ var debug$d = srcExports('finalhandler');
39082
39126
  var encodeUrl = encodeurl;
39083
39127
  var escapeHtml = escapeHtml_1;
39084
39128
  var onFinished = onFinishedExports;
39085
- var parseUrl$1 = parseurlExports;
39129
+ var parseUrl$2 = parseurlExports;
39086
39130
  var statuses = statuses$1;
39087
39131
  var unpipe = unpipe_1;
39088
39132
 
@@ -39286,7 +39330,7 @@ function getErrorStatusCode (err) {
39286
39330
 
39287
39331
  function getResourceName (req) {
39288
39332
  try {
39289
- return parseUrl$1.original(req).pathname
39333
+ return parseUrl$2.original(req).pathname
39290
39334
  } catch (e) {
39291
39335
  return 'resource'
39292
39336
  }
@@ -39445,7 +39489,7 @@ var EventEmitter$3 = require$$0$5.EventEmitter;
39445
39489
  var finalhandler = finalhandler_1;
39446
39490
  var http$4 = require$$1;
39447
39491
  var merge = utilsMergeExports;
39448
- var parseUrl = parseurlExports;
39492
+ var parseUrl$1 = parseurlExports;
39449
39493
 
39450
39494
  /**
39451
39495
  * Module exports.
@@ -39580,7 +39624,7 @@ proto.handle = function handle(req, res, out) {
39580
39624
  }
39581
39625
 
39582
39626
  // route data
39583
- var path = parseUrl(req).pathname || '/';
39627
+ var path = parseUrl$1(req).pathname || '/';
39584
39628
  var route = layer.route;
39585
39629
 
39586
39630
  // skip this layer if the route doesn't match
@@ -44522,7 +44566,7 @@ function walk(root, { onIdentifier, onImportMeta, onDynamicImport }) {
44522
44566
  identifiers.push([node, parentStack.slice(0)]);
44523
44567
  }
44524
44568
  }
44525
- else if (isFunction(node)) {
44569
+ else if (isFunction$1(node)) {
44526
44570
  // If it is a function declaration, it could be shadowing an import
44527
44571
  // Add its name to the scope so it won't get replaced
44528
44572
  if (node.type === 'FunctionDeclaration') {
@@ -44602,7 +44646,7 @@ function isRefIdentifier(id, parent, parentStack) {
44602
44646
  parent.id === id)) {
44603
44647
  return false;
44604
44648
  }
44605
- if (isFunction(parent)) {
44649
+ if (isFunction$1(parent)) {
44606
44650
  // function declaration/expression id
44607
44651
  if (parent.id === id) {
44608
44652
  return false;
@@ -44647,7 +44691,7 @@ function isRefIdentifier(id, parent, parentStack) {
44647
44691
  const isStaticProperty = (node) => node && node.type === 'Property' && !node.computed;
44648
44692
  const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
44649
44693
  const functionNodeTypeRE = /Function(?:Expression|Declaration)$|Method$/;
44650
- function isFunction(node) {
44694
+ function isFunction$1(node) {
44651
44695
  return functionNodeTypeRE.test(node.type);
44652
44696
  }
44653
44697
  const blockNodeTypeRE = /^BlockStatement$|^For(?:In|Of)?Statement$/;
@@ -44655,7 +44699,7 @@ function isBlock(node) {
44655
44699
  return blockNodeTypeRE.test(node.type);
44656
44700
  }
44657
44701
  function findParentScope(parentStack, isVar = false) {
44658
- return parentStack.find(isVar ? isFunction : isBlock);
44702
+ return parentStack.find(isVar ? isFunction$1 : isBlock);
44659
44703
  }
44660
44704
  function isInDestructuringAssignment(parent, parentStack) {
44661
44705
  if (parent &&
@@ -44768,7 +44812,8 @@ async function ssrLoadModule(url, server, context = { global }, urlStack = [], f
44768
44812
  return modulePromise;
44769
44813
  }
44770
44814
  async function instantiateModule(url, server, context = { global }, urlStack = [], fixStacktrace) {
44771
- const moduleGraph = server.environments.ssr.moduleGraph;
44815
+ const environment = server.environments.ssr;
44816
+ const moduleGraph = environment.moduleGraph;
44772
44817
  const mod = await moduleGraph.ensureEntryFromUrl(url);
44773
44818
  if (mod.ssrError) {
44774
44819
  throw mod.ssrError;
@@ -44776,7 +44821,7 @@ async function instantiateModule(url, server, context = { global }, urlStack = [
44776
44821
  if (mod.ssrModule) {
44777
44822
  return mod.ssrModule;
44778
44823
  }
44779
- const result = mod.transformResult || (await server.environments.ssr.transformRequest(url));
44824
+ const result = mod.transformResult || (await environment.transformRequest(url));
44780
44825
  if (!result) {
44781
44826
  // TODO more info? is this even necessary?
44782
44827
  throw new Error(`failed to load module for ssr: ${url}`);
@@ -44798,8 +44843,8 @@ async function instantiateModule(url, server, context = { global }, urlStack = [
44798
44843
  };
44799
44844
  urlStack = urlStack.concat(url);
44800
44845
  const isCircular = (url) => urlStack.includes(url);
44801
- const { isProduction, resolve: { dedupe, preserveSymlinks }, root, ssr, } = server.config;
44802
- const externalConditions = ssr.resolve?.externalConditions || [];
44846
+ const { isProduction, root } = server.config;
44847
+ const { externalConditions, dedupe, preserveSymlinks } = environment.options.resolve;
44803
44848
  const resolveOptions = {
44804
44849
  mainFields: ['main'],
44805
44850
  conditions: [],
@@ -44813,7 +44858,6 @@ async function instantiateModule(url, server, context = { global }, urlStack = [
44813
44858
  isBuild: false,
44814
44859
  isProduction,
44815
44860
  root,
44816
- ssrConfig: ssr,
44817
44861
  legacyProxySsrExternalModules: server.config.legacy?.proxySsrExternalModules,
44818
44862
  packageCache: server.config.packageCache,
44819
44863
  };
@@ -51849,6 +51893,30 @@ var Writable = require$$0$7.Writable;
51849
51893
  var assert = require$$5;
51850
51894
  var debug$a = debug_1;
51851
51895
 
51896
+ // Whether to use the native URL object or the legacy url module
51897
+ var useNativeURL = false;
51898
+ try {
51899
+ assert(new URL$1());
51900
+ }
51901
+ catch (error) {
51902
+ useNativeURL = error.code === "ERR_INVALID_URL";
51903
+ }
51904
+
51905
+ // URL fields to preserve in copy operations
51906
+ var preservedUrlFields = [
51907
+ "auth",
51908
+ "host",
51909
+ "hostname",
51910
+ "href",
51911
+ "path",
51912
+ "pathname",
51913
+ "port",
51914
+ "protocol",
51915
+ "query",
51916
+ "search",
51917
+ "hash",
51918
+ ];
51919
+
51852
51920
  // Create handlers that pass events from native requests
51853
51921
  var events = ["abort", "aborted", "connect", "error", "socket", "timeout"];
51854
51922
  var eventHandlers = Object.create(null);
@@ -51859,13 +51927,19 @@ events.forEach(function (event) {
51859
51927
  });
51860
51928
 
51861
51929
  // Error types with codes
51930
+ var InvalidUrlError = createErrorType(
51931
+ "ERR_INVALID_URL",
51932
+ "Invalid URL",
51933
+ TypeError
51934
+ );
51862
51935
  var RedirectionError = createErrorType(
51863
51936
  "ERR_FR_REDIRECTION_FAILURE",
51864
51937
  "Redirected request failed"
51865
51938
  );
51866
51939
  var TooManyRedirectsError = createErrorType(
51867
51940
  "ERR_FR_TOO_MANY_REDIRECTS",
51868
- "Maximum number of redirects exceeded"
51941
+ "Maximum number of redirects exceeded",
51942
+ RedirectionError
51869
51943
  );
51870
51944
  var MaxBodyLengthExceededError = createErrorType(
51871
51945
  "ERR_FR_MAX_BODY_LENGTH_EXCEEDED",
@@ -51876,6 +51950,9 @@ var WriteAfterEndError = createErrorType(
51876
51950
  "write after end"
51877
51951
  );
51878
51952
 
51953
+ // istanbul ignore next
51954
+ var destroy = Writable.prototype.destroy || noop$2;
51955
+
51879
51956
  // An HTTP(S) request that can be redirected
51880
51957
  function RedirectableRequest(options, responseCallback) {
51881
51958
  // Initialize the request
@@ -51897,7 +51974,13 @@ function RedirectableRequest(options, responseCallback) {
51897
51974
  // React to responses of native requests
51898
51975
  var self = this;
51899
51976
  this._onNativeResponse = function (response) {
51900
- self._processResponse(response);
51977
+ try {
51978
+ self._processResponse(response);
51979
+ }
51980
+ catch (cause) {
51981
+ self.emit("error", cause instanceof RedirectionError ?
51982
+ cause : new RedirectionError({ cause: cause }));
51983
+ }
51901
51984
  };
51902
51985
 
51903
51986
  // Perform the first request
@@ -51906,10 +51989,17 @@ function RedirectableRequest(options, responseCallback) {
51906
51989
  RedirectableRequest.prototype = Object.create(Writable.prototype);
51907
51990
 
51908
51991
  RedirectableRequest.prototype.abort = function () {
51909
- abortRequest(this._currentRequest);
51992
+ destroyRequest(this._currentRequest);
51993
+ this._currentRequest.abort();
51910
51994
  this.emit("abort");
51911
51995
  };
51912
51996
 
51997
+ RedirectableRequest.prototype.destroy = function (error) {
51998
+ destroyRequest(this._currentRequest, error);
51999
+ destroy.call(this, error);
52000
+ return this;
52001
+ };
52002
+
51913
52003
  // Writes buffered data to the current native request
51914
52004
  RedirectableRequest.prototype.write = function (data, encoding, callback) {
51915
52005
  // Writing is not allowed if end has been called
@@ -51918,10 +52008,10 @@ RedirectableRequest.prototype.write = function (data, encoding, callback) {
51918
52008
  }
51919
52009
 
51920
52010
  // Validate input and shift parameters if necessary
51921
- if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) {
52011
+ if (!isString(data) && !isBuffer(data)) {
51922
52012
  throw new TypeError("data should be a string, Buffer or Uint8Array");
51923
52013
  }
51924
- if (typeof encoding === "function") {
52014
+ if (isFunction(encoding)) {
51925
52015
  callback = encoding;
51926
52016
  encoding = null;
51927
52017
  }
@@ -51950,11 +52040,11 @@ RedirectableRequest.prototype.write = function (data, encoding, callback) {
51950
52040
  // Ends the current native request
51951
52041
  RedirectableRequest.prototype.end = function (data, encoding, callback) {
51952
52042
  // Shift parameters if necessary
51953
- if (typeof data === "function") {
52043
+ if (isFunction(data)) {
51954
52044
  callback = data;
51955
52045
  data = encoding = null;
51956
52046
  }
51957
- else if (typeof encoding === "function") {
52047
+ else if (isFunction(encoding)) {
51958
52048
  callback = encoding;
51959
52049
  encoding = null;
51960
52050
  }
@@ -52022,6 +52112,7 @@ RedirectableRequest.prototype.setTimeout = function (msecs, callback) {
52022
52112
  self.removeListener("abort", clearTimer);
52023
52113
  self.removeListener("error", clearTimer);
52024
52114
  self.removeListener("response", clearTimer);
52115
+ self.removeListener("close", clearTimer);
52025
52116
  if (callback) {
52026
52117
  self.removeListener("timeout", callback);
52027
52118
  }
@@ -52048,6 +52139,7 @@ RedirectableRequest.prototype.setTimeout = function (msecs, callback) {
52048
52139
  this.on("abort", clearTimer);
52049
52140
  this.on("error", clearTimer);
52050
52141
  this.on("response", clearTimer);
52142
+ this.on("close", clearTimer);
52051
52143
 
52052
52144
  return this;
52053
52145
  };
@@ -52106,8 +52198,7 @@ RedirectableRequest.prototype._performRequest = function () {
52106
52198
  var protocol = this._options.protocol;
52107
52199
  var nativeProtocol = this._options.nativeProtocols[protocol];
52108
52200
  if (!nativeProtocol) {
52109
- this.emit("error", new TypeError("Unsupported protocol " + protocol));
52110
- return;
52201
+ throw new TypeError("Unsupported protocol " + protocol);
52111
52202
  }
52112
52203
 
52113
52204
  // If specified, use the agent corresponding to the protocol
@@ -52117,21 +52208,26 @@ RedirectableRequest.prototype._performRequest = function () {
52117
52208
  this._options.agent = this._options.agents[scheme];
52118
52209
  }
52119
52210
 
52120
- // Create the native request
52211
+ // Create the native request and set up its event handlers
52121
52212
  var request = this._currentRequest =
52122
52213
  nativeProtocol.request(this._options, this._onNativeResponse);
52123
- this._currentUrl = url.format(this._options);
52124
-
52125
- // Set up event handlers
52126
52214
  request._redirectable = this;
52127
- for (var e = 0; e < events.length; e++) {
52128
- request.on(events[e], eventHandlers[events[e]]);
52215
+ for (var event of events) {
52216
+ request.on(event, eventHandlers[event]);
52129
52217
  }
52130
52218
 
52219
+ // RFC7230§5.3.1: When making a request directly to an origin server, […]
52220
+ // a client MUST send only the absolute path […] as the request-target.
52221
+ this._currentUrl = /^\//.test(this._options.path) ?
52222
+ url.format(this._options) :
52223
+ // When making a request to a proxy, […]
52224
+ // a client MUST send the target URI in absolute-form […].
52225
+ this._options.path;
52226
+
52131
52227
  // End a redirected request
52132
52228
  // (The first request must be ended explicitly with RedirectableRequest#end)
52133
52229
  if (this._isRedirect) {
52134
- // Write the request entity and end.
52230
+ // Write the request entity and end
52135
52231
  var i = 0;
52136
52232
  var self = this;
52137
52233
  var buffers = this._requestBodyBuffers;
@@ -52194,15 +52290,14 @@ RedirectableRequest.prototype._processResponse = function (response) {
52194
52290
  }
52195
52291
 
52196
52292
  // The response is a redirect, so abort the current request
52197
- abortRequest(this._currentRequest);
52293
+ destroyRequest(this._currentRequest);
52198
52294
  // Discard the remainder of the response to avoid waiting for data
52199
52295
  response.destroy();
52200
52296
 
52201
52297
  // RFC7231§6.4: A client SHOULD detect and intervene
52202
52298
  // in cyclical redirections (i.e., "infinite" redirection loops).
52203
52299
  if (++this._redirectCount > this._options.maxRedirects) {
52204
- this.emit("error", new TooManyRedirectsError());
52205
- return;
52300
+ throw new TooManyRedirectsError();
52206
52301
  }
52207
52302
 
52208
52303
  // Store the request headers if applicable
@@ -52236,38 +52331,28 @@ RedirectableRequest.prototype._processResponse = function (response) {
52236
52331
  var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);
52237
52332
 
52238
52333
  // If the redirect is relative, carry over the host of the last request
52239
- var currentUrlParts = url.parse(this._currentUrl);
52334
+ var currentUrlParts = parseUrl(this._currentUrl);
52240
52335
  var currentHost = currentHostHeader || currentUrlParts.host;
52241
52336
  var currentUrl = /^\w+:/.test(location) ? this._currentUrl :
52242
52337
  url.format(Object.assign(currentUrlParts, { host: currentHost }));
52243
52338
 
52244
- // Determine the URL of the redirection
52245
- var redirectUrl;
52246
- try {
52247
- redirectUrl = url.resolve(currentUrl, location);
52248
- }
52249
- catch (cause) {
52250
- this.emit("error", new RedirectionError(cause));
52251
- return;
52252
- }
52253
-
52254
52339
  // Create the redirected request
52255
- debug$a("redirecting to", redirectUrl);
52340
+ var redirectUrl = resolveUrl(location, currentUrl);
52341
+ debug$a("redirecting to", redirectUrl.href);
52256
52342
  this._isRedirect = true;
52257
- var redirectUrlParts = url.parse(redirectUrl);
52258
- Object.assign(this._options, redirectUrlParts);
52343
+ spreadUrlObject(redirectUrl, this._options);
52259
52344
 
52260
52345
  // Drop confidential headers when redirecting to a less secure protocol
52261
52346
  // or to a different domain that is not a superdomain
52262
- if (redirectUrlParts.protocol !== currentUrlParts.protocol &&
52263
- redirectUrlParts.protocol !== "https:" ||
52264
- redirectUrlParts.host !== currentHost &&
52265
- !isSubdomain(redirectUrlParts.host, currentHost)) {
52266
- removeMatchingHeaders(/^(?:authorization|cookie)$/i, this._options.headers);
52347
+ if (redirectUrl.protocol !== currentUrlParts.protocol &&
52348
+ redirectUrl.protocol !== "https:" ||
52349
+ redirectUrl.host !== currentHost &&
52350
+ !isSubdomain(redirectUrl.host, currentHost)) {
52351
+ removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers);
52267
52352
  }
52268
52353
 
52269
52354
  // Evaluate the beforeRedirect callback
52270
- if (typeof beforeRedirect === "function") {
52355
+ if (isFunction(beforeRedirect)) {
52271
52356
  var responseDetails = {
52272
52357
  headers: response.headers,
52273
52358
  statusCode: statusCode,
@@ -52277,23 +52362,12 @@ RedirectableRequest.prototype._processResponse = function (response) {
52277
52362
  method: method,
52278
52363
  headers: requestHeaders,
52279
52364
  };
52280
- try {
52281
- beforeRedirect(this._options, responseDetails, requestDetails);
52282
- }
52283
- catch (err) {
52284
- this.emit("error", err);
52285
- return;
52286
- }
52365
+ beforeRedirect(this._options, responseDetails, requestDetails);
52287
52366
  this._sanitizeOptions(this._options);
52288
52367
  }
52289
52368
 
52290
52369
  // Perform the redirected request
52291
- try {
52292
- this._performRequest();
52293
- }
52294
- catch (cause) {
52295
- this.emit("error", new RedirectionError(cause));
52296
- }
52370
+ this._performRequest();
52297
52371
  };
52298
52372
 
52299
52373
  // Wraps the key/value object of protocols with redirect functionality
@@ -52313,26 +52387,19 @@ function wrap(protocols) {
52313
52387
 
52314
52388
  // Executes a request, following redirects
52315
52389
  function request(input, options, callback) {
52316
- // Parse parameters
52317
- if (typeof input === "string") {
52318
- var urlStr = input;
52319
- try {
52320
- input = urlToOptions(new URL$1(urlStr));
52321
- }
52322
- catch (err) {
52323
- /* istanbul ignore next */
52324
- input = url.parse(urlStr);
52325
- }
52390
+ // Parse parameters, ensuring that input is an object
52391
+ if (isURL(input)) {
52392
+ input = spreadUrlObject(input);
52326
52393
  }
52327
- else if (URL$1 && (input instanceof URL$1)) {
52328
- input = urlToOptions(input);
52394
+ else if (isString(input)) {
52395
+ input = spreadUrlObject(parseUrl(input));
52329
52396
  }
52330
52397
  else {
52331
52398
  callback = options;
52332
- options = input;
52399
+ options = validateUrl(input);
52333
52400
  input = { protocol: protocol };
52334
52401
  }
52335
- if (typeof options === "function") {
52402
+ if (isFunction(options)) {
52336
52403
  callback = options;
52337
52404
  options = null;
52338
52405
  }
@@ -52343,6 +52410,9 @@ function wrap(protocols) {
52343
52410
  maxBodyLength: exports.maxBodyLength,
52344
52411
  }, input, options);
52345
52412
  options.nativeProtocols = nativeProtocols;
52413
+ if (!isString(options.host) && !isString(options.hostname)) {
52414
+ options.hostname = "::1";
52415
+ }
52346
52416
 
52347
52417
  assert.equal(options.protocol, protocol, "protocol mismatch");
52348
52418
  debug$a("options", options);
@@ -52365,27 +52435,57 @@ function wrap(protocols) {
52365
52435
  return exports;
52366
52436
  }
52367
52437
 
52368
- /* istanbul ignore next */
52369
52438
  function noop$2() { /* empty */ }
52370
52439
 
52371
- // from https://github.com/nodejs/node/blob/master/lib/internal/url.js
52372
- function urlToOptions(urlObject) {
52373
- var options = {
52374
- protocol: urlObject.protocol,
52375
- hostname: urlObject.hostname.startsWith("[") ?
52376
- /* istanbul ignore next */
52377
- urlObject.hostname.slice(1, -1) :
52378
- urlObject.hostname,
52379
- hash: urlObject.hash,
52380
- search: urlObject.search,
52381
- pathname: urlObject.pathname,
52382
- path: urlObject.pathname + urlObject.search,
52383
- href: urlObject.href,
52384
- };
52385
- if (urlObject.port !== "") {
52386
- options.port = Number(urlObject.port);
52440
+ function parseUrl(input) {
52441
+ var parsed;
52442
+ /* istanbul ignore else */
52443
+ if (useNativeURL) {
52444
+ parsed = new URL$1(input);
52445
+ }
52446
+ else {
52447
+ // Ensure the URL is valid and absolute
52448
+ parsed = validateUrl(url.parse(input));
52449
+ if (!isString(parsed.protocol)) {
52450
+ throw new InvalidUrlError({ input });
52451
+ }
52387
52452
  }
52388
- return options;
52453
+ return parsed;
52454
+ }
52455
+
52456
+ function resolveUrl(relative, base) {
52457
+ /* istanbul ignore next */
52458
+ return useNativeURL ? new URL$1(relative, base) : parseUrl(url.resolve(base, relative));
52459
+ }
52460
+
52461
+ function validateUrl(input) {
52462
+ if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) {
52463
+ throw new InvalidUrlError({ input: input.href || input });
52464
+ }
52465
+ if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) {
52466
+ throw new InvalidUrlError({ input: input.href || input });
52467
+ }
52468
+ return input;
52469
+ }
52470
+
52471
+ function spreadUrlObject(urlObject, target) {
52472
+ var spread = target || {};
52473
+ for (var key of preservedUrlFields) {
52474
+ spread[key] = urlObject[key];
52475
+ }
52476
+
52477
+ // Fix IPv6 hostname
52478
+ if (spread.hostname.startsWith("[")) {
52479
+ spread.hostname = spread.hostname.slice(1, -1);
52480
+ }
52481
+ // Ensure port is a number
52482
+ if (spread.port !== "") {
52483
+ spread.port = Number(spread.port);
52484
+ }
52485
+ // Concatenate path
52486
+ spread.path = spread.search ? spread.pathname + spread.search : spread.pathname;
52487
+
52488
+ return spread;
52389
52489
  }
52390
52490
 
52391
52491
  function removeMatchingHeaders(regex, headers) {
@@ -52400,37 +52500,60 @@ function removeMatchingHeaders(regex, headers) {
52400
52500
  undefined : String(lastValue).trim();
52401
52501
  }
52402
52502
 
52403
- function createErrorType(code, defaultMessage) {
52404
- function CustomError(cause) {
52503
+ function createErrorType(code, message, baseClass) {
52504
+ // Create constructor
52505
+ function CustomError(properties) {
52405
52506
  Error.captureStackTrace(this, this.constructor);
52406
- if (!cause) {
52407
- this.message = defaultMessage;
52408
- }
52409
- else {
52410
- this.message = defaultMessage + ": " + cause.message;
52411
- this.cause = cause;
52412
- }
52507
+ Object.assign(this, properties || {});
52508
+ this.code = code;
52509
+ this.message = this.cause ? message + ": " + this.cause.message : message;
52413
52510
  }
52414
- CustomError.prototype = new Error();
52415
- CustomError.prototype.constructor = CustomError;
52416
- CustomError.prototype.name = "Error [" + code + "]";
52417
- CustomError.prototype.code = code;
52511
+
52512
+ // Attach constructor and set default properties
52513
+ CustomError.prototype = new (baseClass || Error)();
52514
+ Object.defineProperties(CustomError.prototype, {
52515
+ constructor: {
52516
+ value: CustomError,
52517
+ enumerable: false,
52518
+ },
52519
+ name: {
52520
+ value: "Error [" + code + "]",
52521
+ enumerable: false,
52522
+ },
52523
+ });
52418
52524
  return CustomError;
52419
52525
  }
52420
52526
 
52421
- function abortRequest(request) {
52422
- for (var e = 0; e < events.length; e++) {
52423
- request.removeListener(events[e], eventHandlers[events[e]]);
52527
+ function destroyRequest(request, error) {
52528
+ for (var event of events) {
52529
+ request.removeListener(event, eventHandlers[event]);
52424
52530
  }
52425
52531
  request.on("error", noop$2);
52426
- request.abort();
52532
+ request.destroy(error);
52427
52533
  }
52428
52534
 
52429
52535
  function isSubdomain(subdomain, domain) {
52430
- const dot = subdomain.length - domain.length - 1;
52536
+ assert(isString(subdomain) && isString(domain));
52537
+ var dot = subdomain.length - domain.length - 1;
52431
52538
  return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
52432
52539
  }
52433
52540
 
52541
+ function isString(value) {
52542
+ return typeof value === "string" || value instanceof String;
52543
+ }
52544
+
52545
+ function isFunction(value) {
52546
+ return typeof value === "function";
52547
+ }
52548
+
52549
+ function isBuffer(value) {
52550
+ return typeof value === "object" && ("length" in value);
52551
+ }
52552
+
52553
+ function isURL(value) {
52554
+ return URL$1 && value instanceof URL$1;
52555
+ }
52556
+
52434
52557
  // Exports
52435
52558
  followRedirects$1.exports = wrap({ http: http$1, https: https$1 });
52436
52559
  followRedirects$1.exports.wrap = wrap;
@@ -53877,7 +54000,7 @@ function transformRequest(url, server, options = {}, environment) {
53877
54000
  // Backward compatibility
53878
54001
  options = { ...options, ssr: environment.name !== 'client' };
53879
54002
  }
53880
- if (server._restartPromise && !options.ssr)
54003
+ if (server._restartPromise && environment?.options.dev.recoverable)
53881
54004
  throwClosedServerError();
53882
54005
  // We could have a cache per environment instead of the global _pendingRequests
53883
54006
  const cacheKey = `${options.html ? 'html:' : ''}${environment.name}:${url}`;
@@ -54019,7 +54142,8 @@ async function loadAndTransform(environment, id, url, server, options, timestamp
54019
54142
  // as string
54020
54143
  // only try the fallback if access is allowed, skip for out of root url
54021
54144
  // like /service-worker.js or /api/users
54022
- if (options.ssr || isFileServingAllowed(file, server)) {
54145
+ if (environment.options.nodeCompatible ||
54146
+ isFileServingAllowed(file, server)) {
54023
54147
  try {
54024
54148
  code = await fsp.readFile(file, 'utf-8');
54025
54149
  debugLoad?.(`${timeFrom(loadStart)} [fs] ${prettyUrl}`);
@@ -54078,7 +54202,7 @@ async function loadAndTransform(environment, id, url, server, options, timestamp
54078
54202
  err.code = isPublicFile ? ERR_LOAD_PUBLIC_URL : ERR_LOAD_URL;
54079
54203
  throw err;
54080
54204
  }
54081
- if (server._restartPromise && !ssr)
54205
+ if (server._restartPromise && environment.options.dev.recoverable)
54082
54206
  throwClosedServerError();
54083
54207
  // ensure module in graph after successful load
54084
54208
  mod ??= await moduleGraph._ensureEntryFromUrl(url, undefined, resolved);
@@ -54132,7 +54256,7 @@ async function loadAndTransform(environment, id, url, server, options, timestamp
54132
54256
  }
54133
54257
  }
54134
54258
  }
54135
- if (server._restartPromise && !ssr)
54259
+ if (server._restartPromise && environment.options.dev.recoverable)
54136
54260
  throwClosedServerError();
54137
54261
  const result = ssr && !server.config.experimental.skipSsrTransform
54138
54262
  ? await server.ssrTransform(code, normalizedMap, url, originalCode)
@@ -54220,7 +54344,7 @@ async function handleModuleSoftInvalidation(environment, mod, timestamp, server)
54220
54344
 
54221
54345
  // Copyright 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Simon Lydell
54222
54346
  // License: MIT.
54223
- var Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace;
54347
+ var HashbangComment, Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace;
54224
54348
  RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:[^\]\\\n\r\u2028\u2029]+|\\.)*\]|[^\/\\\n\r\u2028\u2029]+|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/yu;
54225
54349
  Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y;
54226
54350
  Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]+|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/yu;
@@ -54231,6 +54355,7 @@ WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/yu;
54231
54355
  LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y;
54232
54356
  MultiLineComment = /\/\*(?:[^*]+|\*(?!\/))*(\*\/)?/y;
54233
54357
  SingleLineComment = /\/\/.*/y;
54358
+ HashbangComment = /^#!.*/;
54234
54359
  JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y;
54235
54360
  JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/yu;
54236
54361
  JSXString = /(['"])(?:[^'"]+|(?!\1)['"])*(\1)?/y;
@@ -54251,6 +54376,13 @@ var jsTokens_1 = function*(input, {jsx = false} = {}) {
54251
54376
  braces = [];
54252
54377
  parenNesting = 0;
54253
54378
  postfixIncDec = false;
54379
+ if (match = HashbangComment.exec(input)) {
54380
+ yield ({
54381
+ type: "HashbangComment",
54382
+ value: match[0]
54383
+ });
54384
+ lastIndex = match[0].length;
54385
+ }
54254
54386
  while (lastIndex < length) {
54255
54387
  mode = stack[stack.length - 1];
54256
54388
  switch (mode.tag) {
@@ -54626,6 +54758,10 @@ function stripLiteralJsTokens(code, options) {
54626
54758
  continue;
54627
54759
  }
54628
54760
  if (token.type === "StringLiteral") {
54761
+ if (!token.closed) {
54762
+ result += token.value;
54763
+ continue;
54764
+ }
54629
54765
  const body = token.value.slice(1, -1);
54630
54766
  if (filter(body)) {
54631
54767
  result += token.value[0] + FILL.repeat(body.length) + token.value[token.value.length - 1];
@@ -55523,7 +55659,10 @@ function injectNonceAttributeTagHook(config) {
55523
55659
  (node.nodeName === 'link' &&
55524
55660
  node.attrs.some((attr) => attr.name === 'rel' &&
55525
55661
  parseRelAttr(attr.value).some((a) => processRelType.has(a))))) {
55526
- s.appendRight(node.sourceCodeLocation.startTag.endOffset - 1, ` nonce="${nonce}"`);
55662
+ // if the closing of the start tag includes a `/`, the offset should be 2 so the nonce
55663
+ // is appended prior to the `/`
55664
+ const appendOffset = html[node.sourceCodeLocation.startTag.endOffset - 2] === '/' ? 2 : 1;
55665
+ s.appendRight(node.sourceCodeLocation.startTag.endOffset - appendOffset, ` nonce="${nonce}"`);
55527
55666
  }
55528
55667
  });
55529
55668
  return s.toString();
@@ -56836,8 +56975,8 @@ async function fetchModule(environment, url, importer, options = {}) {
56836
56975
  return { externalize: url, type: 'network' };
56837
56976
  }
56838
56977
  if (url[0] !== '.' && url[0] !== '/') {
56839
- const { isProduction, resolve: { dedupe, preserveSymlinks }, root, ssr, } = environment.config;
56840
- const externalConditions = ssr.resolve?.externalConditions || [];
56978
+ const { isProduction, root } = environment.config;
56979
+ const { externalConditions, dedupe, preserveSymlinks } = environment.options.resolve;
56841
56980
  const resolveOptions = {
56842
56981
  mainFields: ['main'],
56843
56982
  conditions: [],
@@ -56851,7 +56990,6 @@ async function fetchModule(environment, url, importer, options = {}) {
56851
56990
  isBuild: false,
56852
56991
  isProduction,
56853
56992
  root,
56854
- ssrConfig: ssr,
56855
56993
  packageCache: environment.config.packageCache,
56856
56994
  };
56857
56995
  const resolved = tryNodeResolve(url, importer, {
@@ -58203,20 +58341,20 @@ async function _createServer(inlineConfig = {}, options) {
58203
58341
  // Create Environments
58204
58342
  const client_createEnvironment = config.environments.client?.dev?.createEnvironment ??
58205
58343
  ((server, name) => new DevEnvironment(server, name, { hot: ws }));
58206
- environments.client = client_createEnvironment(server, 'client');
58344
+ environments.client = await client_createEnvironment(server, 'client');
58207
58345
  const ssr_createEnvironment = config.environments.ssr?.dev?.createEnvironment ??
58208
58346
  ((server, name) => createNodeDevEnvironment(server, name, { hot: ssrHotChannel }));
58209
- environments.ssr = ssr_createEnvironment(server, 'ssr');
58210
- Object.entries(config.environments).forEach(([name, EnvironmentOptions]) => {
58347
+ environments.ssr = await ssr_createEnvironment(server, 'ssr');
58348
+ for (const [name, EnvironmentOptions] of Object.entries(config.environments)) {
58211
58349
  // TODO: move client and ssr inside the loop?
58212
58350
  if (name !== 'client' && name !== 'ssr') {
58213
58351
  const createEnvironment = EnvironmentOptions.dev?.createEnvironment ??
58214
58352
  ((server, name) => new DevEnvironment(server, name, {
58215
58353
  hot: ws, // TODO: what should we use here?
58216
58354
  }));
58217
- environments[name] = createEnvironment(server, name);
58355
+ environments[name] = await createEnvironment(server, name);
58218
58356
  }
58219
- });
58357
+ }
58220
58358
  if (!middlewareMode) {
58221
58359
  exitProcess = async () => {
58222
58360
  try {
@@ -59334,8 +59472,8 @@ function createIsConfiguredAsExternal(environment) {
59334
59472
  isProduction: false,
59335
59473
  isBuild: true,
59336
59474
  conditions: targetConditions,
59337
- webCompatible: config.ssr.target === 'webworker',
59338
- nodeCompatible: true,
59475
+ webCompatible: options.webCompatible,
59476
+ nodeCompatible: options.nodeCompatible,
59339
59477
  };
59340
59478
  const isExternalizable = (id, importer, configuredAsExternal) => {
59341
59479
  if (!bareImportRE.test(id) || id.includes('\0')) {
@@ -59449,8 +59587,13 @@ function definePlugin(config) {
59449
59587
  userDefineEnv[key.slice(16)] = config.define[key];
59450
59588
  }
59451
59589
  }
59452
- function generatePattern(ssr) {
59453
- const replaceProcessEnv = !ssr || config.ssr?.target === 'webworker';
59590
+ function generatePattern(environment) {
59591
+ // This is equivalent to the old `!ssr || config.ssr?.target === 'webworker'`
59592
+ // TODO: We shouldn't keep options.nodeCompatible and options.webCompatible
59593
+ // This is a place where using `!options.nodeCompatible` fails and it is confusing why
59594
+ // Do we need a per-environment replaceProcessEnv option?
59595
+ // Is it useful to have define be configured per-environment?
59596
+ const replaceProcessEnv = environment.options.webCompatible;
59454
59597
  const define = {
59455
59598
  ...(replaceProcessEnv ? processEnv : {}),
59456
59599
  ...importMetaKeys,
@@ -59458,6 +59601,10 @@ function definePlugin(config) {
59458
59601
  ...importMetaFallbackKeys,
59459
59602
  };
59460
59603
  // Additional define fixes based on `ssr` value
59604
+ // Backward compatibility. Any non client environment will get import.meta.env.SSR = true
59605
+ // TODO: Check if we should only do this for the SSR environment and how to abstract
59606
+ // maybe we need import.meta.env.environmentName ?
59607
+ const ssr = environment.name !== 'client';
59461
59608
  if ('import.meta.env.SSR' in define) {
59462
59609
  define['import.meta.env.SSR'] = ssr + '';
59463
59610
  }
@@ -59481,13 +59628,23 @@ function definePlugin(config) {
59481
59628
  : null;
59482
59629
  return [define, pattern];
59483
59630
  }
59484
- const defaultPattern = generatePattern(false);
59485
- const ssrPattern = generatePattern(true);
59631
+ const patternsCache = new WeakMap();
59632
+ function getPattern(environment) {
59633
+ let pattern = patternsCache.get(environment);
59634
+ if (!pattern) {
59635
+ pattern = generatePattern(environment);
59636
+ patternsCache.set(environment, pattern);
59637
+ }
59638
+ return pattern;
59639
+ }
59486
59640
  return {
59487
59641
  name: 'vite:define',
59488
- async transform(code, id, options) {
59489
- const ssr = options?.ssr === true;
59490
- if (!ssr && !isBuild) {
59642
+ async transform(code, id) {
59643
+ const { environment } = this;
59644
+ if (!environment) {
59645
+ return;
59646
+ }
59647
+ if (environment.name === 'client' && !isBuild) {
59491
59648
  // for dev we inject actual global defines in the vite client to
59492
59649
  // avoid the transform cost. see the `clientInjection` and
59493
59650
  // `importAnalysis` plugin.
@@ -59501,7 +59658,7 @@ function definePlugin(config) {
59501
59658
  config.assetsInclude(id)) {
59502
59659
  return;
59503
59660
  }
59504
- const [define, pattern] = ssr ? ssrPattern : defaultPattern;
59661
+ const [define, pattern] = getPattern(environment);
59505
59662
  if (!pattern)
59506
59663
  return;
59507
59664
  // Check if our code needs any replacements before running esbuild
@@ -59534,6 +59691,23 @@ async function replaceDefine(code, id, define, config) {
59534
59691
  sourcefile: id,
59535
59692
  sourcemap: config.command === 'build' ? !!config.build.sourcemap : true,
59536
59693
  });
59694
+ // remove esbuild's <define:...> source entries
59695
+ // since they would confuse source map remapping/collapsing which expects a single source
59696
+ if (result.map.includes('<define:')) {
59697
+ const originalMap = new TraceMap(result.map);
59698
+ if (originalMap.sources.length >= 2) {
59699
+ const sourceIndex = originalMap.sources.indexOf(id);
59700
+ const decoded = decodedMap(originalMap);
59701
+ decoded.sources = [id];
59702
+ decoded.mappings = decoded.mappings.map((segments) => segments.filter((segment) => {
59703
+ // modify and filter
59704
+ const index = segment[1];
59705
+ segment[1] = 0;
59706
+ return index === sourceIndex;
59707
+ }));
59708
+ result.map = JSON.stringify(encodedMap(new TraceMap(decoded)));
59709
+ }
59710
+ }
59537
59711
  for (const marker in replacementMarkers) {
59538
59712
  result.code = result.code.replaceAll(marker, replacementMarkers[marker]);
59539
59713
  }
@@ -59989,6 +60163,7 @@ function preAliasPlugin(config) {
59989
60163
  },
59990
60164
  };
59991
60165
  }
60166
+ // TODO: environment?
59992
60167
  function optimizeAliasReplacementForSSR(id, optimizeDeps) {
59993
60168
  if (optimizeDeps.include?.includes(id)) {
59994
60169
  return true;
@@ -60959,7 +61134,6 @@ function workerImportMetaUrlPlugin(config) {
60959
61134
  isProduction: config.isProduction,
60960
61135
  isBuild: config.command === 'build',
60961
61136
  packageCache: config.packageCache,
60962
- ssrConfig: config.ssr,
60963
61137
  asSrc: true,
60964
61138
  };
60965
61139
  return {
@@ -60969,9 +61143,12 @@ function workerImportMetaUrlPlugin(config) {
60969
61143
  return true;
60970
61144
  }
60971
61145
  },
60972
- async transform(code, id, options) {
61146
+ async transform(code, id) {
60973
61147
  const { environment } = this;
60974
- if (environment && !options?.ssr && isIncludeWorkerImportMetaUrl(code)) {
61148
+ // TODO: environment, same as with assetImportMetaUrlPlugin
61149
+ if (environment &&
61150
+ environment.name === 'client' &&
61151
+ isIncludeWorkerImportMetaUrl(code)) {
60975
61152
  let s;
60976
61153
  const cleanString = stripLiteral(code);
60977
61154
  const workerImportMetaUrlRE = /\bnew\s+(?:Worker|SharedWorker)\s*\(\s*(new\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*\))/dg;
@@ -61050,7 +61227,6 @@ function assetImportMetaUrlPlugin(config) {
61050
61227
  isProduction: config.isProduction,
61051
61228
  isBuild: config.command === 'build',
61052
61229
  packageCache: config.packageCache,
61053
- ssrConfig: config.ssr,
61054
61230
  asSrc: true,
61055
61231
  };
61056
61232
  return {
@@ -61058,7 +61234,8 @@ function assetImportMetaUrlPlugin(config) {
61058
61234
  async transform(code, id, options) {
61059
61235
  const { environment } = this;
61060
61236
  if (environment &&
61061
- !options?.ssr &&
61237
+ // TODO: Should this be done only for the client or for any webCompatible environment?
61238
+ environment.name === 'client' &&
61062
61239
  id !== preloadHelperId &&
61063
61240
  id !== CLIENT_ENTRY &&
61064
61241
  code.includes('new URL') &&
@@ -62239,7 +62416,6 @@ async function resolvePlugins(config, prePlugins, normalPlugins, postPlugins) {
62239
62416
  isProduction: config.isProduction,
62240
62417
  isBuild,
62241
62418
  packageCache: config.packageCache,
62242
- ssrConfig: config.ssr,
62243
62419
  asSrc: true,
62244
62420
  fsUtils: getFsUtils(config),
62245
62421
  optimizeDeps: true,
@@ -62813,7 +62989,7 @@ async function createPluginContainer(config, watcher, environments) {
62813
62989
  let id = null;
62814
62990
  const partial = {};
62815
62991
  for (const plugin of getSortedPlugins('resolveId')) {
62816
- if (closed && !ssr)
62992
+ if (closed && environment?.options.dev.recoverable)
62817
62993
  throwClosedServerError();
62818
62994
  if (!plugin.resolveId)
62819
62995
  continue;
@@ -62864,7 +63040,7 @@ async function createPluginContainer(config, watcher, environments) {
62864
63040
  ctx.ssr = !!ssr;
62865
63041
  ctx.environment = environment;
62866
63042
  for (const plugin of getSortedPlugins('load')) {
62867
- if (closed && !ssr)
63043
+ if (closed && environment?.options.dev.recoverable)
62868
63044
  throwClosedServerError();
62869
63045
  if (!plugin.load)
62870
63046
  continue;
@@ -62889,7 +63065,7 @@ async function createPluginContainer(config, watcher, environments) {
62889
63065
  ctx.ssr = !!ssr;
62890
63066
  ctx.environment = environment;
62891
63067
  for (const plugin of getSortedPlugins('transform')) {
62892
- if (closed && !ssr)
63068
+ if (closed && environment?.options.dev.recoverable)
62893
63069
  throwClosedServerError();
62894
63070
  if (!plugin.transform)
62895
63071
  continue;
@@ -63494,7 +63670,6 @@ function createOptimizeDepsIncludeResolver(environment) {
63494
63670
  asSrc: false,
63495
63671
  scan: true,
63496
63672
  ssrOptimizeCheck: environment.name !== 'client',
63497
- ssrConfig: config.ssr,
63498
63673
  packageCache: new Map(),
63499
63674
  });
63500
63675
  return async (id) => {
@@ -63802,9 +63977,13 @@ function runOptimizeDeps(environment, depsInfo) {
63802
63977
  // No need to wait, we can clean up in the background because temp folders
63803
63978
  // are unique per run
63804
63979
  debug$2?.(colors$1.green(`removing cache dir ${processingCacheDir}`));
63805
- fsp.rm(processingCacheDir, { recursive: true, force: true }).catch(() => {
63980
+ try {
63981
+ // When exiting the process, `fsp.rm` may not take effect, so we use `fs.rmSync`
63982
+ fs$l.rmSync(processingCacheDir, { recursive: true, force: true });
63983
+ }
63984
+ catch (error) {
63806
63985
  // Ignore errors
63807
- });
63986
+ }
63808
63987
  }
63809
63988
  };
63810
63989
  const successfulResult = {
@@ -63983,8 +64162,7 @@ async function prepareEsbuildOptimizerRun(environment, depsInfo, processingCache
63983
64162
  const define = {
63984
64163
  'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || config.mode),
63985
64164
  };
63986
- const ssr = environment.name !== 'client'; // TODO:depsOptimizer
63987
- const platform = ssr && config.ssr?.target !== 'webworker' ? 'node' : 'browser';
64165
+ const platform = environment.options.webCompatible ? 'browser' : 'node';
63988
64166
  const external = [...(optimizeDeps?.exclude ?? [])];
63989
64167
  const plugins = [...pluginsFromConfig];
63990
64168
  if (external.length) {
@@ -65572,7 +65750,7 @@ function cssPostPlugin(config) {
65572
65750
  if (isDirectCSSRequest(id)) {
65573
65751
  return null;
65574
65752
  }
65575
- // server only
65753
+ // server only, TODO: environment
65576
65754
  if (options?.ssr) {
65577
65755
  return modulesCode || `export default ${JSON.stringify(css)}`;
65578
65756
  }
@@ -65830,6 +66008,7 @@ function cssPostPlugin(config) {
65830
66008
  for (const file in bundle) {
65831
66009
  const chunk = bundle[file];
65832
66010
  if (chunk.type === 'chunk') {
66011
+ let chunkImportsPureCssChunk = false;
65833
66012
  // remove pure css chunk from other chunk's imports,
65834
66013
  // and also register the emitted CSS files under the importer
65835
66014
  // chunks instead.
@@ -65838,11 +66017,14 @@ function cssPostPlugin(config) {
65838
66017
  const { importedCss, importedAssets } = bundle[file].viteMetadata;
65839
66018
  importedCss.forEach((file) => chunk.viteMetadata.importedCss.add(file));
65840
66019
  importedAssets.forEach((file) => chunk.viteMetadata.importedAssets.add(file));
66020
+ chunkImportsPureCssChunk = true;
65841
66021
  return false;
65842
66022
  }
65843
66023
  return true;
65844
66024
  });
65845
- chunk.code = replaceEmptyChunk(chunk.code);
66025
+ if (chunkImportsPureCssChunk) {
66026
+ chunk.code = replaceEmptyChunk(chunk.code);
66027
+ }
65846
66028
  }
65847
66029
  }
65848
66030
  const removedPureCssFiles = removedPureCssFilesCache.get(config);
@@ -66245,8 +66427,8 @@ function createCachedImport(imp) {
66245
66427
  return cached;
66246
66428
  };
66247
66429
  }
66248
- const importPostcssImport = createCachedImport(() => import('./dep-DUc_OVe8.js').then(function (n) { return n.i; }));
66249
- const importPostcssModules = createCachedImport(() => import('./dep-b2YSXG5U.js').then(function (n) { return n.i; }));
66430
+ const importPostcssImport = createCachedImport(() => import('./dep-DK04Q0H9.js').then(function (n) { return n.i; }));
66431
+ const importPostcssModules = createCachedImport(() => import('./dep-DKZVy3_n.js').then(function (n) { return n.i; }));
66250
66432
  const importPostcss = createCachedImport(() => import('postcss'));
66251
66433
  const preprocessorWorkerControllerCache = new WeakMap();
66252
66434
  let alwaysFakeWorkerWorkerControllerCache;
@@ -67635,13 +67817,7 @@ function buildImportAnalysisPlugin(config) {
67635
67817
  const fileDepsCode = `[${fileDeps
67636
67818
  .map((fileDep) => fileDep.runtime ? fileDep.url : JSON.stringify(fileDep.url))
67637
67819
  .join(',')}]`;
67638
- const mapDepsCode = `\
67639
- function __vite__mapDeps(indexes) {
67640
- if (!__vite__mapDeps.viteFileDeps) {
67641
- __vite__mapDeps.viteFileDeps = ${fileDepsCode}
67642
- }
67643
- return indexes.map((i) => __vite__mapDeps.viteFileDeps[i])
67644
- }\n`;
67820
+ const mapDepsCode = `const __vite__fileDeps=${fileDepsCode},__vite__mapDeps=i=>i.map(i=>__vite__fileDeps[i]);\n`;
67645
67821
  // inject extra code at the top or next line of hashbang
67646
67822
  if (code.startsWith('#!')) {
67647
67823
  s.prependLeft(code.indexOf('\n') + 1, mapDepsCode);
@@ -67817,37 +67993,39 @@ function completeSystemWrapPlugin() {
67817
67993
  };
67818
67994
  }
67819
67995
 
67820
- function resolveBuildOptions(raw, logger, root, environmentName) {
67996
+ function resolveBuildOptions(raw, logger, root) {
67997
+ const libMode = raw.lib ?? false;
67998
+ const buildOptions = resolveBuildEnvironmentOptions(raw, logger, root, undefined, libMode);
67999
+ return { ...buildOptions, lib: libMode };
68000
+ }
68001
+ function resolveBuildEnvironmentOptions(raw, logger, root, environmentName, libMode = false) {
67821
68002
  const deprecatedPolyfillModulePreload = raw?.polyfillModulePreload;
67822
- if (raw) {
67823
- const { polyfillModulePreload, ...rest } = raw;
67824
- raw = rest;
67825
- if (deprecatedPolyfillModulePreload !== undefined) {
67826
- logger.warn('polyfillModulePreload is deprecated. Use modulePreload.polyfill instead.');
67827
- }
67828
- if (deprecatedPolyfillModulePreload === false &&
67829
- raw.modulePreload === undefined) {
67830
- raw.modulePreload = { polyfill: false };
67831
- }
68003
+ const { polyfillModulePreload, ...rest } = raw;
68004
+ raw = rest;
68005
+ if (deprecatedPolyfillModulePreload !== undefined) {
68006
+ logger.warn('polyfillModulePreload is deprecated. Use modulePreload.polyfill instead.');
68007
+ }
68008
+ if (deprecatedPolyfillModulePreload === false &&
68009
+ raw.modulePreload === undefined) {
68010
+ raw.modulePreload = { polyfill: false };
67832
68011
  }
67833
- const modulePreload = raw?.modulePreload;
68012
+ const modulePreload = raw.modulePreload;
67834
68013
  const defaultModulePreload = {
67835
68014
  polyfill: true,
67836
68015
  };
67837
- const defaultBuildOptions = {
68016
+ const defaultBuildEnvironmentOptions = {
67838
68017
  outDir: 'dist',
67839
68018
  assetsDir: 'assets',
67840
68019
  assetsInlineLimit: DEFAULT_ASSETS_INLINE_LIMIT,
67841
- cssCodeSplit: !raw?.lib,
68020
+ cssCodeSplit: !libMode,
67842
68021
  sourcemap: false,
67843
68022
  rollupOptions: {},
67844
- minify: raw?.ssr ? false : 'esbuild',
68023
+ minify: raw.ssr ? false : 'esbuild',
67845
68024
  terserOptions: {},
67846
68025
  write: true,
67847
68026
  emptyOutDir: null,
67848
68027
  copyPublicDir: true,
67849
68028
  manifest: false,
67850
- lib: false,
67851
68029
  ssr: false,
67852
68030
  ssrManifest: false,
67853
68031
  ssrEmitAssets: false,
@@ -67856,23 +68034,23 @@ function resolveBuildOptions(raw, logger, root, environmentName) {
67856
68034
  chunkSizeWarningLimit: 500,
67857
68035
  watch: null,
67858
68036
  };
67859
- const userBuildOptions = raw
67860
- ? mergeConfig(defaultBuildOptions, raw)
67861
- : defaultBuildOptions;
68037
+ const userBuildEnvironmentOptions = raw
68038
+ ? mergeConfig(defaultBuildEnvironmentOptions, raw)
68039
+ : defaultBuildEnvironmentOptions;
67862
68040
  // @ts-expect-error Fallback options instead of merging
67863
68041
  const resolved = {
67864
68042
  target: 'modules',
67865
68043
  cssTarget: false,
67866
- ...userBuildOptions,
68044
+ ...userBuildEnvironmentOptions,
67867
68045
  commonjsOptions: {
67868
68046
  include: [/node_modules/],
67869
68047
  extensions: ['.js', '.cjs'],
67870
- ...userBuildOptions.commonjsOptions,
68048
+ ...userBuildEnvironmentOptions.commonjsOptions,
67871
68049
  },
67872
68050
  dynamicImportVarsOptions: {
67873
68051
  warnOnError: true,
67874
68052
  exclude: [/node_modules/],
67875
- ...userBuildOptions.dynamicImportVarsOptions,
68053
+ ...userBuildEnvironmentOptions.dynamicImportVarsOptions,
67876
68054
  },
67877
68055
  // Resolve to false | object
67878
68056
  modulePreload: modulePreload === false
@@ -67950,17 +68128,27 @@ async function resolveBuildPlugins(config) {
67950
68128
  */
67951
68129
  async function build(inlineConfig = {}) {
67952
68130
  const builder = await createViteBuilder({}, { ...inlineConfig, plugins: () => inlineConfig.plugins ?? [] });
67953
- const ssr = !!builder.config.build.ssr;
67954
- const environment = builder.environments[ssr ? 'ssr' : 'client'];
67955
- return builder.build(environment);
68131
+ if (builder.config.build.lib) {
68132
+ // TODO: temporal workaround. Should we support `libraries: Record<string, LibraryOptions & EnvironmentOptions>`
68133
+ // to build multiple libraries and be able to target different environments (for example for a Svelte components
68134
+ // library generating both client and SSR builds)?
68135
+ return buildEnvironment(builder.config, builder.environments.client, builder.config.build.lib);
68136
+ }
68137
+ else {
68138
+ const ssr = !!builder.config.build.ssr;
68139
+ const environment = builder.environments[ssr ? 'ssr' : 'client'];
68140
+ return builder.build(environment);
68141
+ }
67956
68142
  }
67957
68143
  function resolveConfigToBuild(inlineConfig = {}) {
67958
68144
  return resolveConfig(inlineConfig, 'build', 'production', 'production');
67959
68145
  }
67960
- async function buildEnvironment(config, environment) {
68146
+ /**
68147
+ * Build an App environment, or a App library (if librayOptions is provided)
68148
+ **/
68149
+ async function buildEnvironment(config, environment, libOptions = false) {
67961
68150
  const options = config.build;
67962
68151
  const ssr = environment.name !== 'client';
67963
- const libOptions = options.lib;
67964
68152
  config.logger.info(colors$1.cyan(`vite v${VERSION} ${colors$1.green(`building ${ssr ? `SSR bundle ` : ``}for ${config.mode}...`)}`));
67965
68153
  const resolve = (p) => path$o.resolve(config.root, p);
67966
68154
  const input = libOptions
@@ -68043,16 +68231,8 @@ async function buildEnvironment(config, environment) {
68043
68231
  config.logger.warnOnce(colors$1.yellow(`Vite does not support "rollupOptions.output.sourcemap". ` +
68044
68232
  `Please use "build.sourcemap" instead.`));
68045
68233
  }
68046
- /**
68047
- * if (ssr.target === 'webworker') {
68048
- * build.rollupOptions.entryFileNames = '[name].js'
68049
- * build.rollupOptions.inlineDynamicImports = (typeof input === 'string' || Object.keys(input).length === 1))
68050
- * }
68051
- */
68052
- const ssrNodeBuild = ssr && config.ssr.target === 'node';
68053
- const ssrWorkerBuild = ssr && config.ssr.target === 'webworker';
68054
68234
  const format = output.format || 'es';
68055
- const jsExt = ssrNodeBuild || libOptions
68235
+ const jsExt = !environment.options.webCompatible || libOptions
68056
68236
  ? resolveOutputJsExtension(format, findNearestPackageData(config.root, config.packageCache)?.data
68057
68237
  .type)
68058
68238
  : 'js';
@@ -68081,7 +68261,11 @@ async function buildEnvironment(config, environment) {
68081
68261
  : path$o.posix.join(options.assetsDir, `[name]-[hash].[ext]`),
68082
68262
  inlineDynamicImports: output.format === 'umd' ||
68083
68263
  output.format === 'iife' ||
68084
- (ssrWorkerBuild &&
68264
+ // TODO: We need an abstraction for non-client environments?
68265
+ // We should remove the explicit 'client' hcek here.
68266
+ // Or maybe `inlineDynamicImports` should be an environment option?
68267
+ (environment.name !== 'client' &&
68268
+ environment.options.webCompatible &&
68085
68269
  (typeof input === 'string' || Object.keys(input).length === 1)),
68086
68270
  ...output,
68087
68271
  };
@@ -68591,7 +68775,7 @@ async function createViteBuilder(builderOptions = {}, defaultBuilderInlineConfig
68591
68775
  // plugins are built to handle multiple environments concurrently).
68592
68776
  const environmentConfig = await resolveConfig(environmentOptions);
68593
68777
  const environmentBuilder = { ...builder, config: environmentConfig };
68594
- const environment = createEnvironment(environmentBuilder, name);
68778
+ const environment = await createEnvironment(environmentBuilder, name);
68595
68779
  environments[name] = environment;
68596
68780
  }
68597
68781
  return builder;
@@ -68606,6 +68790,7 @@ var build$1 = {
68606
68790
  createViteBuilder: createViteBuilder,
68607
68791
  injectEnvironmentToHooks: injectEnvironmentToHooks,
68608
68792
  onRollupWarning: onRollupWarning,
68793
+ resolveBuildEnvironmentOptions: resolveBuildEnvironmentOptions,
68609
68794
  resolveBuildOptions: resolveBuildOptions,
68610
68795
  resolveBuildOutputs: resolveBuildOutputs,
68611
68796
  resolveBuildPlugins: resolveBuildPlugins,
@@ -68753,7 +68938,8 @@ function resolvePreviewOptions(preview, server) {
68753
68938
  */
68754
68939
  async function preview(inlineConfig = {}) {
68755
68940
  const config = await resolveConfig(inlineConfig, 'serve', 'production', 'production', true);
68756
- const distDir = path$o.resolve(config.root, config.build.outDir);
68941
+ const clientOutDir = config.environments.client.build.outDir ?? config.build.outDir;
68942
+ const distDir = path$o.resolve(config.root, clientOutDir);
68757
68943
  if (!fs$l.existsSync(distDir) &&
68758
68944
  // error if no plugins implement `configurePreviewServer`
68759
68945
  config.plugins.every((plugin) => !plugin.configurePreviewServer) &&
@@ -68761,7 +68947,7 @@ async function preview(inlineConfig = {}) {
68761
68947
  // and affect file serving
68762
68948
  process.argv[1]?.endsWith(path$o.normalize('bin/vite.js')) &&
68763
68949
  process.argv[2] === 'preview') {
68764
- throw new Error(`The directory "${config.build.outDir}" does not exist. Did you build your project?`);
68950
+ throw new Error(`The directory "${clientOutDir}" does not exist. Did you build your project?`);
68765
68951
  }
68766
68952
  const app = connect$1();
68767
68953
  const httpServer = await resolveHttpServer(config.preview, app, await resolveHttpsConfig(config.preview?.https));
@@ -68885,7 +69071,7 @@ const promisifiedRealpath = promisify$4(fs$l.realpath);
68885
69071
  function defineConfig(config) {
68886
69072
  return config;
68887
69073
  }
68888
- function resolveDevOptions(dev, preserverSymlinks) {
69074
+ function resolveDevEnvironmentOptions(dev, preserverSymlinks, environmentName) {
68889
69075
  return {
68890
69076
  sourcemap: dev?.sourcemap ?? { js: true },
68891
69077
  sourcemapIgnoreList: dev?.sourcemapIgnoreList === false
@@ -68897,6 +69083,7 @@ function resolveDevOptions(dev, preserverSymlinks) {
68897
69083
  },
68898
69084
  optimizeDeps: resolveOptimizeDepsConfig(dev?.optimizeDeps, preserverSymlinks),
68899
69085
  createEnvironment: dev?.createEnvironment,
69086
+ recoverable: dev?.recoverable ?? environmentName === 'client',
68900
69087
  };
68901
69088
  }
68902
69089
  function resolveEnvironmentOptions(config, resolvedRoot, logger, environmentName) {
@@ -68905,8 +69092,8 @@ function resolveEnvironmentOptions(config, resolvedRoot, logger, environmentName
68905
69092
  resolve,
68906
69093
  nodeCompatible: config.nodeCompatible ?? environmentName !== 'client',
68907
69094
  webCompatible: config.webCompatible ?? environmentName === 'client',
68908
- dev: resolveDevOptions(config.dev, resolve.preserveSymlinks),
68909
- build: resolveBuildOptions(config.build, logger, resolvedRoot, environmentName),
69095
+ dev: resolveDevEnvironmentOptions(config.dev, resolve.preserveSymlinks, environmentName),
69096
+ build: resolveBuildEnvironmentOptions(config.build ?? {}, logger, resolvedRoot, environmentName),
68910
69097
  };
68911
69098
  }
68912
69099
  function getDefaultEnvironmentOptions(config) {
@@ -69119,8 +69306,9 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development',
69119
69306
  ...patchedOptimizeDeps.esbuildOptions,
69120
69307
  },
69121
69308
  };
69122
- const resolvedDevOptions = resolveDevOptions(config.dev, resolvedDefaultEnvironmentResolve.preserveSymlinks);
69123
- const resolvedBuildOptions = resolveBuildOptions(config.build, logger, resolvedRoot, undefined);
69309
+ // TODO: Deprecate and remove resolve, dev and build options at the root level of the resolved config
69310
+ const resolvedDevEnvironmentOptions = resolveDevEnvironmentOptions(config.dev, resolvedDefaultEnvironmentResolve.preserveSymlinks, undefined);
69311
+ const resolvedBuildOptions = resolveBuildOptions(config.build ?? {}, logger, resolvedRoot);
69124
69312
  // Backward compatibility: merge config.environments.ssr back into config.ssr
69125
69313
  // so ecosystem SSR plugins continue to work if only environments.ssr is configured
69126
69314
  const patchedConfigSsr = {
@@ -69275,10 +69463,11 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development',
69275
69463
  },
69276
69464
  // Backward compatibility, users should use environment.config.dev.optimizeDeps
69277
69465
  optimizeDeps: backwardCompatibleOptimizeDeps,
69466
+ ssr,
69467
+ // TODO: deprecate and later remove from ResolvedConfig?
69278
69468
  resolve: resolvedDefaultEnvironmentResolve,
69279
- dev: resolvedDevOptions,
69469
+ dev: resolvedDevEnvironmentOptions,
69280
69470
  build: resolvedBuildOptions,
69281
- ssr,
69282
69471
  environments: resolvedEnvironments,
69283
69472
  getSortedPlugins: undefined,
69284
69473
  getSortedPluginHooks: undefined,
@@ -69352,13 +69541,6 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development',
69352
69541
  },
69353
69542
  });
69354
69543
  // validate config
69355
- if (config.build?.terserOptions &&
69356
- config.build.minify &&
69357
- config.build.minify !== 'terser') {
69358
- logger.warn(colors$1.yellow(`build.terserOptions is specified but build.minify is not set to use Terser. ` +
69359
- `Note Vite now defaults to use esbuild for minification. If you still ` +
69360
- `prefer Terser, set build.minify to "terser".`));
69361
- }
69362
69544
  // Check if all assetFileNames have the same reference.
69363
69545
  // If not, display a warn for user.
69364
69546
  const outputOption = config.build?.rollupOptions?.output ?? [];