@n-dream/builders-cli 0.2.2 → 0.2.3

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.
@@ -1369,11 +1369,11 @@ var require_receiver = __commonJS({
1369
1369
  * @return {(Error|RangeError)} The error
1370
1370
  * @private
1371
1371
  */
1372
- createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1372
+ createError(ErrorCtor, message2, prefix, statusCode, errorCode) {
1373
1373
  this._loop = false;
1374
1374
  this._errored = true;
1375
1375
  const err = new ErrorCtor(
1376
- prefix ? `Invalid WebSocket frame: ${message}` : message
1376
+ prefix ? `Invalid WebSocket frame: ${message2}` : message2
1377
1377
  );
1378
1378
  Error.captureStackTrace(err, this.createError);
1379
1379
  err.code = errorCode;
@@ -2039,10 +2039,10 @@ var require_event_target = __commonJS({
2039
2039
  callListener(handler, this, event);
2040
2040
  };
2041
2041
  } else if (type === "close") {
2042
- wrapper = function onClose(code, message) {
2042
+ wrapper = function onClose(code, message2) {
2043
2043
  const event = new CloseEvent("close", {
2044
2044
  code,
2045
- reason: message.toString(),
2045
+ reason: message2.toString(),
2046
2046
  wasClean: this._closeFrameReceived && this._closeFrameSent
2047
2047
  });
2048
2048
  event[kTarget] = this;
@@ -2266,10 +2266,10 @@ var require_websocket = __commonJS({
2266
2266
  "use strict";
2267
2267
  var EventEmitter = require("events");
2268
2268
  var https = require("https");
2269
- var http3 = require("http");
2270
- var net = require("net");
2269
+ var http2 = require("http");
2270
+ var net2 = require("net");
2271
2271
  var tls = require("tls");
2272
- var { randomBytes: randomBytes3, createHash } = require("crypto");
2272
+ var { randomBytes, createHash } = require("crypto");
2273
2273
  var { Duplex, Readable } = require("stream");
2274
2274
  var { URL: URL2 } = require("url");
2275
2275
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -2820,8 +2820,8 @@ var require_websocket = __commonJS({
2820
2820
  }
2821
2821
  }
2822
2822
  const defaultPort2 = isSecure ? 443 : 80;
2823
- const key = randomBytes3(16).toString("base64");
2824
- const request = isSecure ? https.request : http3.request;
2823
+ const key = randomBytes(16).toString("base64");
2824
+ const request = isSecure ? https.request : http2.request;
2825
2825
  const protocolSet = /* @__PURE__ */ new Set();
2826
2826
  let perMessageDeflate;
2827
2827
  opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
@@ -2974,29 +2974,29 @@ var require_websocket = __commonJS({
2974
2974
  const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2975
2975
  if (secWebSocketExtensions !== void 0) {
2976
2976
  if (!perMessageDeflate) {
2977
- const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
2978
- abortHandshake(websocket, socket, message);
2977
+ const message2 = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
2978
+ abortHandshake(websocket, socket, message2);
2979
2979
  return;
2980
2980
  }
2981
2981
  let extensions;
2982
2982
  try {
2983
2983
  extensions = parse(secWebSocketExtensions);
2984
2984
  } catch (err) {
2985
- const message = "Invalid Sec-WebSocket-Extensions header";
2986
- abortHandshake(websocket, socket, message);
2985
+ const message2 = "Invalid Sec-WebSocket-Extensions header";
2986
+ abortHandshake(websocket, socket, message2);
2987
2987
  return;
2988
2988
  }
2989
2989
  const extensionNames = Object.keys(extensions);
2990
2990
  if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate2.extensionName) {
2991
- const message = "Server indicated an extension that was not requested";
2992
- abortHandshake(websocket, socket, message);
2991
+ const message2 = "Server indicated an extension that was not requested";
2992
+ abortHandshake(websocket, socket, message2);
2993
2993
  return;
2994
2994
  }
2995
2995
  try {
2996
2996
  perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName]);
2997
2997
  } catch (err) {
2998
- const message = "Invalid Sec-WebSocket-Extensions header";
2999
- abortHandshake(websocket, socket, message);
2998
+ const message2 = "Invalid Sec-WebSocket-Extensions header";
2999
+ abortHandshake(websocket, socket, message2);
3000
3000
  return;
3001
3001
  }
3002
3002
  websocket._extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
@@ -3024,18 +3024,18 @@ var require_websocket = __commonJS({
3024
3024
  }
3025
3025
  function netConnect(options) {
3026
3026
  options.path = options.socketPath;
3027
- return net.connect(options);
3027
+ return net2.connect(options);
3028
3028
  }
3029
3029
  function tlsConnect(options) {
3030
3030
  options.path = void 0;
3031
3031
  if (!options.servername && options.servername !== "") {
3032
- options.servername = net.isIP(options.host) ? "" : options.host;
3032
+ options.servername = net2.isIP(options.host) ? "" : options.host;
3033
3033
  }
3034
3034
  return tls.connect(options);
3035
3035
  }
3036
- function abortHandshake(websocket, stream, message) {
3036
+ function abortHandshake(websocket, stream, message2) {
3037
3037
  websocket._readyState = WebSocket2.CLOSING;
3038
- const err = new Error(message);
3038
+ const err = new Error(message2);
3039
3039
  Error.captureStackTrace(err, abortHandshake);
3040
3040
  if (stream.setHeader) {
3041
3041
  stream[kAborted] = true;
@@ -3199,7 +3199,7 @@ var require_stream = __commonJS({
3199
3199
  objectMode: false,
3200
3200
  writableObjectMode: false
3201
3201
  });
3202
- ws.on("message", function message(msg, isBinary) {
3202
+ ws.on("message", function message2(msg, isBinary) {
3203
3203
  const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
3204
3204
  if (!duplex.push(data)) ws.pause();
3205
3205
  });
@@ -3317,7 +3317,7 @@ var require_websocket_server = __commonJS({
3317
3317
  "../../node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/websocket-server.js"(exports2, module2) {
3318
3318
  "use strict";
3319
3319
  var EventEmitter = require("events");
3320
- var http3 = require("http");
3320
+ var http2 = require("http");
3321
3321
  var { Duplex } = require("stream");
3322
3322
  var { createHash } = require("crypto");
3323
3323
  var extension2 = require_extension();
@@ -3398,8 +3398,8 @@ var require_websocket_server = __commonJS({
3398
3398
  );
3399
3399
  }
3400
3400
  if (options.port != null) {
3401
- this._server = http3.createServer((req, res) => {
3402
- const body = http3.STATUS_CODES[426];
3401
+ this._server = http2.createServer((req, res) => {
3402
+ const body = http2.STATUS_CODES[426];
3403
3403
  res.writeHead(426, {
3404
3404
  "Content-Length": body.length,
3405
3405
  "Content-Type": "text/plain"
@@ -3522,23 +3522,23 @@ var require_websocket_server = __commonJS({
3522
3522
  const upgrade = req.headers.upgrade;
3523
3523
  const version = +req.headers["sec-websocket-version"];
3524
3524
  if (req.method !== "GET") {
3525
- const message = "Invalid HTTP method";
3526
- abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
3525
+ const message2 = "Invalid HTTP method";
3526
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message2);
3527
3527
  return;
3528
3528
  }
3529
3529
  if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
3530
- const message = "Invalid Upgrade header";
3531
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3530
+ const message2 = "Invalid Upgrade header";
3531
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message2);
3532
3532
  return;
3533
3533
  }
3534
3534
  if (key === void 0 || !keyRegex.test(key)) {
3535
- const message = "Missing or invalid Sec-WebSocket-Key header";
3536
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3535
+ const message2 = "Missing or invalid Sec-WebSocket-Key header";
3536
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message2);
3537
3537
  return;
3538
3538
  }
3539
3539
  if (version !== 13 && version !== 8) {
3540
- const message = "Missing or invalid Sec-WebSocket-Version header";
3541
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
3540
+ const message2 = "Missing or invalid Sec-WebSocket-Version header";
3541
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message2, {
3542
3542
  "Sec-WebSocket-Version": "13, 8"
3543
3543
  });
3544
3544
  return;
@@ -3553,8 +3553,8 @@ var require_websocket_server = __commonJS({
3553
3553
  try {
3554
3554
  protocols = subprotocol2.parse(secWebSocketProtocol);
3555
3555
  } catch (err) {
3556
- const message = "Invalid Sec-WebSocket-Protocol header";
3557
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3556
+ const message2 = "Invalid Sec-WebSocket-Protocol header";
3557
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message2);
3558
3558
  return;
3559
3559
  }
3560
3560
  }
@@ -3573,8 +3573,8 @@ var require_websocket_server = __commonJS({
3573
3573
  extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
3574
3574
  }
3575
3575
  } catch (err) {
3576
- const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
3577
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3576
+ const message2 = "Invalid or unacceptable Sec-WebSocket-Extensions header";
3577
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message2);
3578
3578
  return;
3579
3579
  }
3580
3580
  }
@@ -3585,9 +3585,9 @@ var require_websocket_server = __commonJS({
3585
3585
  req
3586
3586
  };
3587
3587
  if (this.options.verifyClient.length === 2) {
3588
- this.options.verifyClient(info, (verified, code, message, headers) => {
3588
+ this.options.verifyClient(info, (verified, code, message2, headers) => {
3589
3589
  if (!verified) {
3590
- return abortHandshake(socket, code || 401, message, headers);
3590
+ return abortHandshake(socket, code || 401, message2, headers);
3591
3591
  }
3592
3592
  this.completeUpgrade(
3593
3593
  extensions,
@@ -3687,27 +3687,27 @@ var require_websocket_server = __commonJS({
3687
3687
  function socketOnError() {
3688
3688
  this.destroy();
3689
3689
  }
3690
- function abortHandshake(socket, code, message, headers) {
3691
- message = message || http3.STATUS_CODES[code];
3690
+ function abortHandshake(socket, code, message2, headers) {
3691
+ message2 = message2 || http2.STATUS_CODES[code];
3692
3692
  headers = {
3693
3693
  Connection: "close",
3694
3694
  "Content-Type": "text/html",
3695
- "Content-Length": Buffer.byteLength(message),
3695
+ "Content-Length": Buffer.byteLength(message2),
3696
3696
  ...headers
3697
3697
  };
3698
3698
  socket.once("finish", socket.destroy);
3699
3699
  socket.end(
3700
- `HTTP/1.1 ${code} ${http3.STATUS_CODES[code]}\r
3701
- ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
3700
+ `HTTP/1.1 ${code} ${http2.STATUS_CODES[code]}\r
3701
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message2
3702
3702
  );
3703
3703
  }
3704
- function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
3704
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message2, headers) {
3705
3705
  if (server.listenerCount("wsClientError")) {
3706
- const err = new Error(message);
3706
+ const err = new Error(message2);
3707
3707
  Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
3708
3708
  server.emit("wsClientError", err, socket, req);
3709
3709
  } else {
3710
- abortHandshake(socket, code, message, headers);
3710
+ abortHandshake(socket, code, message2, headers);
3711
3711
  }
3712
3712
  }
3713
3713
  }
@@ -4248,7 +4248,7 @@ var require_supports_color = __commonJS({
4248
4248
  return 1;
4249
4249
  }
4250
4250
  if ("CI" in env) {
4251
- if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign2) => sign2 in env) || env.CI_NAME === "codeship") {
4251
+ if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
4252
4252
  return 1;
4253
4253
  }
4254
4254
  return min;
@@ -4509,7 +4509,7 @@ var require_helpers = __commonJS({
4509
4509
  };
4510
4510
  Object.defineProperty(exports2, "__esModule", { value: true });
4511
4511
  exports2.req = exports2.json = exports2.toBuffer = void 0;
4512
- var http3 = __importStar(require("http"));
4512
+ var http2 = __importStar(require("http"));
4513
4513
  var https = __importStar(require("https"));
4514
4514
  async function toBuffer(stream) {
4515
4515
  let length = 0;
@@ -4535,7 +4535,7 @@ var require_helpers = __commonJS({
4535
4535
  exports2.json = json2;
4536
4536
  function req(url, opts = {}) {
4537
4537
  const href = typeof url === "string" ? url : url.href;
4538
- const req2 = (href.startsWith("https:") ? https : http3).request(url, opts);
4538
+ const req2 = (href.startsWith("https:") ? https : http2).request(url, opts);
4539
4539
  const promise = new Promise((resolve2, reject) => {
4540
4540
  req2.once("response", resolve2).once("error", reject).end();
4541
4541
  });
@@ -4582,12 +4582,12 @@ var require_dist = __commonJS({
4582
4582
  };
4583
4583
  Object.defineProperty(exports2, "__esModule", { value: true });
4584
4584
  exports2.Agent = void 0;
4585
- var net = __importStar(require("net"));
4586
- var http3 = __importStar(require("http"));
4585
+ var net2 = __importStar(require("net"));
4586
+ var http2 = __importStar(require("http"));
4587
4587
  var https_1 = require("https");
4588
4588
  __exportStar(require_helpers(), exports2);
4589
4589
  var INTERNAL = /* @__PURE__ */ Symbol("AgentBaseInternalState");
4590
- var Agent = class extends http3.Agent {
4590
+ var Agent = class extends http2.Agent {
4591
4591
  constructor(opts) {
4592
4592
  super(opts);
4593
4593
  this[INTERNAL] = {};
@@ -4622,7 +4622,7 @@ var require_dist = __commonJS({
4622
4622
  if (!this.sockets[name]) {
4623
4623
  this.sockets[name] = [];
4624
4624
  }
4625
- const fakeSocket = new net.Socket({ writable: false });
4625
+ const fakeSocket = new net2.Socket({ writable: false });
4626
4626
  this.sockets[name].push(fakeSocket);
4627
4627
  this.totalSocketCount++;
4628
4628
  return fakeSocket;
@@ -4659,7 +4659,7 @@ var require_dist = __commonJS({
4659
4659
  const fakeSocket = this.incrementSockets(name);
4660
4660
  Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => {
4661
4661
  this.decrementSockets(name, fakeSocket);
4662
- if (socket instanceof http3.Agent) {
4662
+ if (socket instanceof http2.Agent) {
4663
4663
  try {
4664
4664
  return socket.addRequest(req, connectOpts);
4665
4665
  } catch (err) {
@@ -4834,7 +4834,7 @@ var require_dist2 = __commonJS({
4834
4834
  };
4835
4835
  Object.defineProperty(exports2, "__esModule", { value: true });
4836
4836
  exports2.HttpsProxyAgent = void 0;
4837
- var net = __importStar(require("net"));
4837
+ var net2 = __importStar(require("net"));
4838
4838
  var tls = __importStar(require("tls"));
4839
4839
  var assert_1 = __importDefault(require("assert"));
4840
4840
  var debug_1 = __importDefault(require_src());
@@ -4843,7 +4843,7 @@ var require_dist2 = __commonJS({
4843
4843
  var parse_proxy_response_1 = require_parse_proxy_response();
4844
4844
  var debug = (0, debug_1.default)("https-proxy-agent");
4845
4845
  var setServernameFromNonIpHost = (options) => {
4846
- if (options.servername === void 0 && options.host && !net.isIP(options.host)) {
4846
+ if (options.servername === void 0 && options.host && !net2.isIP(options.host)) {
4847
4847
  return {
4848
4848
  ...options,
4849
4849
  servername: options.host
@@ -4883,10 +4883,10 @@ var require_dist2 = __commonJS({
4883
4883
  socket = tls.connect(setServernameFromNonIpHost(this.connectOpts));
4884
4884
  } else {
4885
4885
  debug("Creating `net.Socket`: %o", this.connectOpts);
4886
- socket = net.connect(this.connectOpts);
4886
+ socket = net2.connect(this.connectOpts);
4887
4887
  }
4888
4888
  const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders };
4889
- const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
4889
+ const host = net2.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
4890
4890
  let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r
4891
4891
  `;
4892
4892
  if (proxy.username || proxy.password) {
@@ -4919,7 +4919,7 @@ var require_dist2 = __commonJS({
4919
4919
  return socket;
4920
4920
  }
4921
4921
  socket.destroy();
4922
- const fakeSocket = new net.Socket({ writable: false });
4922
+ const fakeSocket = new net2.Socket({ writable: false });
4923
4923
  fakeSocket.readable = true;
4924
4924
  req.once("socket", (s) => {
4925
4925
  debug("Replaying proxy buffer for failed request");
@@ -5264,8 +5264,8 @@ var require_errors = __commonJS({
5264
5264
  "use strict";
5265
5265
  var kUndiciError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR");
5266
5266
  var UndiciError = class extends Error {
5267
- constructor(message, options) {
5268
- super(message, options);
5267
+ constructor(message2, options) {
5268
+ super(message2, options);
5269
5269
  this.name = "UndiciError";
5270
5270
  this.code = "UND_ERR";
5271
5271
  }
@@ -5278,10 +5278,10 @@ var require_errors = __commonJS({
5278
5278
  };
5279
5279
  var kConnectTimeoutError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_CONNECT_TIMEOUT");
5280
5280
  var ConnectTimeoutError = class extends UndiciError {
5281
- constructor(message) {
5282
- super(message);
5281
+ constructor(message2) {
5282
+ super(message2);
5283
5283
  this.name = "ConnectTimeoutError";
5284
- this.message = message || "Connect Timeout Error";
5284
+ this.message = message2 || "Connect Timeout Error";
5285
5285
  this.code = "UND_ERR_CONNECT_TIMEOUT";
5286
5286
  }
5287
5287
  static [Symbol.hasInstance](instance) {
@@ -5293,10 +5293,10 @@ var require_errors = __commonJS({
5293
5293
  };
5294
5294
  var kHeadersTimeoutError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_HEADERS_TIMEOUT");
5295
5295
  var HeadersTimeoutError = class extends UndiciError {
5296
- constructor(message) {
5297
- super(message);
5296
+ constructor(message2) {
5297
+ super(message2);
5298
5298
  this.name = "HeadersTimeoutError";
5299
- this.message = message || "Headers Timeout Error";
5299
+ this.message = message2 || "Headers Timeout Error";
5300
5300
  this.code = "UND_ERR_HEADERS_TIMEOUT";
5301
5301
  }
5302
5302
  static [Symbol.hasInstance](instance) {
@@ -5308,10 +5308,10 @@ var require_errors = __commonJS({
5308
5308
  };
5309
5309
  var kHeadersOverflowError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_HEADERS_OVERFLOW");
5310
5310
  var HeadersOverflowError = class extends UndiciError {
5311
- constructor(message) {
5312
- super(message);
5311
+ constructor(message2) {
5312
+ super(message2);
5313
5313
  this.name = "HeadersOverflowError";
5314
- this.message = message || "Headers Overflow Error";
5314
+ this.message = message2 || "Headers Overflow Error";
5315
5315
  this.code = "UND_ERR_HEADERS_OVERFLOW";
5316
5316
  }
5317
5317
  static [Symbol.hasInstance](instance) {
@@ -5323,10 +5323,10 @@ var require_errors = __commonJS({
5323
5323
  };
5324
5324
  var kBodyTimeoutError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_BODY_TIMEOUT");
5325
5325
  var BodyTimeoutError = class extends UndiciError {
5326
- constructor(message) {
5327
- super(message);
5326
+ constructor(message2) {
5327
+ super(message2);
5328
5328
  this.name = "BodyTimeoutError";
5329
- this.message = message || "Body Timeout Error";
5329
+ this.message = message2 || "Body Timeout Error";
5330
5330
  this.code = "UND_ERR_BODY_TIMEOUT";
5331
5331
  }
5332
5332
  static [Symbol.hasInstance](instance) {
@@ -5338,10 +5338,10 @@ var require_errors = __commonJS({
5338
5338
  };
5339
5339
  var kInvalidArgumentError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_INVALID_ARG");
5340
5340
  var InvalidArgumentError = class extends UndiciError {
5341
- constructor(message) {
5342
- super(message);
5341
+ constructor(message2) {
5342
+ super(message2);
5343
5343
  this.name = "InvalidArgumentError";
5344
- this.message = message || "Invalid Argument Error";
5344
+ this.message = message2 || "Invalid Argument Error";
5345
5345
  this.code = "UND_ERR_INVALID_ARG";
5346
5346
  }
5347
5347
  static [Symbol.hasInstance](instance) {
@@ -5353,10 +5353,10 @@ var require_errors = __commonJS({
5353
5353
  };
5354
5354
  var kInvalidReturnValueError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_INVALID_RETURN_VALUE");
5355
5355
  var InvalidReturnValueError = class extends UndiciError {
5356
- constructor(message) {
5357
- super(message);
5356
+ constructor(message2) {
5357
+ super(message2);
5358
5358
  this.name = "InvalidReturnValueError";
5359
- this.message = message || "Invalid Return Value Error";
5359
+ this.message = message2 || "Invalid Return Value Error";
5360
5360
  this.code = "UND_ERR_INVALID_RETURN_VALUE";
5361
5361
  }
5362
5362
  static [Symbol.hasInstance](instance) {
@@ -5368,10 +5368,10 @@ var require_errors = __commonJS({
5368
5368
  };
5369
5369
  var kAbortError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_ABORT");
5370
5370
  var AbortError = class extends UndiciError {
5371
- constructor(message) {
5372
- super(message);
5371
+ constructor(message2) {
5372
+ super(message2);
5373
5373
  this.name = "AbortError";
5374
- this.message = message || "The operation was aborted";
5374
+ this.message = message2 || "The operation was aborted";
5375
5375
  this.code = "UND_ERR_ABORT";
5376
5376
  }
5377
5377
  static [Symbol.hasInstance](instance) {
@@ -5383,10 +5383,10 @@ var require_errors = __commonJS({
5383
5383
  };
5384
5384
  var kRequestAbortedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_ABORTED");
5385
5385
  var RequestAbortedError = class extends AbortError {
5386
- constructor(message) {
5387
- super(message);
5386
+ constructor(message2) {
5387
+ super(message2);
5388
5388
  this.name = "AbortError";
5389
- this.message = message || "Request aborted";
5389
+ this.message = message2 || "Request aborted";
5390
5390
  this.code = "UND_ERR_ABORTED";
5391
5391
  }
5392
5392
  static [Symbol.hasInstance](instance) {
@@ -5398,10 +5398,10 @@ var require_errors = __commonJS({
5398
5398
  };
5399
5399
  var kInformationalError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_INFO");
5400
5400
  var InformationalError = class extends UndiciError {
5401
- constructor(message) {
5402
- super(message);
5401
+ constructor(message2) {
5402
+ super(message2);
5403
5403
  this.name = "InformationalError";
5404
- this.message = message || "Request information";
5404
+ this.message = message2 || "Request information";
5405
5405
  this.code = "UND_ERR_INFO";
5406
5406
  }
5407
5407
  static [Symbol.hasInstance](instance) {
@@ -5413,10 +5413,10 @@ var require_errors = __commonJS({
5413
5413
  };
5414
5414
  var kRequestContentLengthMismatchError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_REQ_CONTENT_LENGTH_MISMATCH");
5415
5415
  var RequestContentLengthMismatchError = class extends UndiciError {
5416
- constructor(message) {
5417
- super(message);
5416
+ constructor(message2) {
5417
+ super(message2);
5418
5418
  this.name = "RequestContentLengthMismatchError";
5419
- this.message = message || "Request body length does not match content-length header";
5419
+ this.message = message2 || "Request body length does not match content-length header";
5420
5420
  this.code = "UND_ERR_REQ_CONTENT_LENGTH_MISMATCH";
5421
5421
  }
5422
5422
  static [Symbol.hasInstance](instance) {
@@ -5428,10 +5428,10 @@ var require_errors = __commonJS({
5428
5428
  };
5429
5429
  var kResponseContentLengthMismatchError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_RES_CONTENT_LENGTH_MISMATCH");
5430
5430
  var ResponseContentLengthMismatchError = class extends UndiciError {
5431
- constructor(message) {
5432
- super(message);
5431
+ constructor(message2) {
5432
+ super(message2);
5433
5433
  this.name = "ResponseContentLengthMismatchError";
5434
- this.message = message || "Response body length does not match content-length header";
5434
+ this.message = message2 || "Response body length does not match content-length header";
5435
5435
  this.code = "UND_ERR_RES_CONTENT_LENGTH_MISMATCH";
5436
5436
  }
5437
5437
  static [Symbol.hasInstance](instance) {
@@ -5443,10 +5443,10 @@ var require_errors = __commonJS({
5443
5443
  };
5444
5444
  var kClientDestroyedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_DESTROYED");
5445
5445
  var ClientDestroyedError = class extends UndiciError {
5446
- constructor(message) {
5447
- super(message);
5446
+ constructor(message2) {
5447
+ super(message2);
5448
5448
  this.name = "ClientDestroyedError";
5449
- this.message = message || "The client is destroyed";
5449
+ this.message = message2 || "The client is destroyed";
5450
5450
  this.code = "UND_ERR_DESTROYED";
5451
5451
  }
5452
5452
  static [Symbol.hasInstance](instance) {
@@ -5458,10 +5458,10 @@ var require_errors = __commonJS({
5458
5458
  };
5459
5459
  var kClientClosedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_CLOSED");
5460
5460
  var ClientClosedError = class extends UndiciError {
5461
- constructor(message) {
5462
- super(message);
5461
+ constructor(message2) {
5462
+ super(message2);
5463
5463
  this.name = "ClientClosedError";
5464
- this.message = message || "The client is closed";
5464
+ this.message = message2 || "The client is closed";
5465
5465
  this.code = "UND_ERR_CLOSED";
5466
5466
  }
5467
5467
  static [Symbol.hasInstance](instance) {
@@ -5473,10 +5473,10 @@ var require_errors = __commonJS({
5473
5473
  };
5474
5474
  var kSocketError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_SOCKET");
5475
5475
  var SocketError = class extends UndiciError {
5476
- constructor(message, socket) {
5477
- super(message);
5476
+ constructor(message2, socket) {
5477
+ super(message2);
5478
5478
  this.name = "SocketError";
5479
- this.message = message || "Socket error";
5479
+ this.message = message2 || "Socket error";
5480
5480
  this.code = "UND_ERR_SOCKET";
5481
5481
  this.socket = socket;
5482
5482
  }
@@ -5489,10 +5489,10 @@ var require_errors = __commonJS({
5489
5489
  };
5490
5490
  var kNotSupportedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_NOT_SUPPORTED");
5491
5491
  var NotSupportedError = class extends UndiciError {
5492
- constructor(message) {
5493
- super(message);
5492
+ constructor(message2) {
5493
+ super(message2);
5494
5494
  this.name = "NotSupportedError";
5495
- this.message = message || "Not supported error";
5495
+ this.message = message2 || "Not supported error";
5496
5496
  this.code = "UND_ERR_NOT_SUPPORTED";
5497
5497
  }
5498
5498
  static [Symbol.hasInstance](instance) {
@@ -5504,10 +5504,10 @@ var require_errors = __commonJS({
5504
5504
  };
5505
5505
  var kBalancedPoolMissingUpstreamError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_BPL_MISSING_UPSTREAM");
5506
5506
  var BalancedPoolMissingUpstreamError = class extends UndiciError {
5507
- constructor(message) {
5508
- super(message);
5507
+ constructor(message2) {
5508
+ super(message2);
5509
5509
  this.name = "MissingUpstreamError";
5510
- this.message = message || "No upstream has been added to the BalancedPool";
5510
+ this.message = message2 || "No upstream has been added to the BalancedPool";
5511
5511
  this.code = "UND_ERR_BPL_MISSING_UPSTREAM";
5512
5512
  }
5513
5513
  static [Symbol.hasInstance](instance) {
@@ -5519,8 +5519,8 @@ var require_errors = __commonJS({
5519
5519
  };
5520
5520
  var kHTTPParserError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_HTTP_PARSER");
5521
5521
  var HTTPParserError = class extends Error {
5522
- constructor(message, code, data) {
5523
- super(message);
5522
+ constructor(message2, code, data) {
5523
+ super(message2);
5524
5524
  this.name = "HTTPParserError";
5525
5525
  this.code = code ? `HPE_${code}` : void 0;
5526
5526
  this.data = data ? data.toString() : void 0;
@@ -5534,10 +5534,10 @@ var require_errors = __commonJS({
5534
5534
  };
5535
5535
  var kResponseExceededMaxSizeError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_RES_EXCEEDED_MAX_SIZE");
5536
5536
  var ResponseExceededMaxSizeError = class extends UndiciError {
5537
- constructor(message) {
5538
- super(message);
5537
+ constructor(message2) {
5538
+ super(message2);
5539
5539
  this.name = "ResponseExceededMaxSizeError";
5540
- this.message = message || "Response content exceeded max size";
5540
+ this.message = message2 || "Response content exceeded max size";
5541
5541
  this.code = "UND_ERR_RES_EXCEEDED_MAX_SIZE";
5542
5542
  }
5543
5543
  static [Symbol.hasInstance](instance) {
@@ -5549,10 +5549,10 @@ var require_errors = __commonJS({
5549
5549
  };
5550
5550
  var kRequestRetryError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_REQ_RETRY");
5551
5551
  var RequestRetryError = class extends UndiciError {
5552
- constructor(message, code, { headers, data }) {
5553
- super(message);
5552
+ constructor(message2, code, { headers, data }) {
5553
+ super(message2);
5554
5554
  this.name = "RequestRetryError";
5555
- this.message = message || "Request retry error";
5555
+ this.message = message2 || "Request retry error";
5556
5556
  this.code = "UND_ERR_REQ_RETRY";
5557
5557
  this.statusCode = code;
5558
5558
  this.data = data;
@@ -5567,10 +5567,10 @@ var require_errors = __commonJS({
5567
5567
  };
5568
5568
  var kResponseError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_RESPONSE");
5569
5569
  var ResponseError = class extends UndiciError {
5570
- constructor(message, code, { headers, body }) {
5571
- super(message);
5570
+ constructor(message2, code, { headers, body }) {
5571
+ super(message2);
5572
5572
  this.name = "ResponseError";
5573
- this.message = message || "Response error";
5573
+ this.message = message2 || "Response error";
5574
5574
  this.code = "UND_ERR_RESPONSE";
5575
5575
  this.statusCode = code;
5576
5576
  this.body = body;
@@ -5585,10 +5585,10 @@ var require_errors = __commonJS({
5585
5585
  };
5586
5586
  var kSecureProxyConnectionError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_PRX_TLS");
5587
5587
  var SecureProxyConnectionError = class extends UndiciError {
5588
- constructor(cause, message, options = {}) {
5589
- super(message, { cause, ...options });
5588
+ constructor(cause, message2, options = {}) {
5589
+ super(message2, { cause, ...options });
5590
5590
  this.name = "SecureProxyConnectionError";
5591
- this.message = message || "Secure Proxy Connection failed";
5591
+ this.message = message2 || "Secure Proxy Connection failed";
5592
5592
  this.code = "UND_ERR_PRX_TLS";
5593
5593
  this.cause = cause;
5594
5594
  }
@@ -5601,10 +5601,10 @@ var require_errors = __commonJS({
5601
5601
  };
5602
5602
  var kMaxOriginsReachedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_MAX_ORIGINS_REACHED");
5603
5603
  var MaxOriginsReachedError = class extends UndiciError {
5604
- constructor(message) {
5605
- super(message);
5604
+ constructor(message2) {
5605
+ super(message2);
5606
5606
  this.name = "MaxOriginsReachedError";
5607
- this.message = message || "Maximum allowed origins reached";
5607
+ this.message = message2 || "Maximum allowed origins reached";
5608
5608
  this.code = "UND_ERR_MAX_ORIGINS_REACHED";
5609
5609
  }
5610
5610
  static [Symbol.hasInstance](instance) {
@@ -5615,19 +5615,19 @@ var require_errors = __commonJS({
5615
5615
  }
5616
5616
  };
5617
5617
  var Socks5ProxyError = class extends UndiciError {
5618
- constructor(message, code) {
5619
- super(message);
5618
+ constructor(message2, code) {
5619
+ super(message2);
5620
5620
  this.name = "Socks5ProxyError";
5621
- this.message = message || "SOCKS5 proxy error";
5621
+ this.message = message2 || "SOCKS5 proxy error";
5622
5622
  this.code = code || "UND_ERR_SOCKS5";
5623
5623
  }
5624
5624
  };
5625
5625
  var kMessageSizeExceededError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_WS_MESSAGE_SIZE_EXCEEDED");
5626
5626
  var MessageSizeExceededError = class extends UndiciError {
5627
- constructor(message) {
5628
- super(message);
5627
+ constructor(message2) {
5628
+ super(message2);
5629
5629
  this.name = "MessageSizeExceededError";
5630
- this.message = message || "Max decompressed message size exceeded";
5630
+ this.message = message2 || "Max decompressed message size exceeded";
5631
5631
  this.code = "UND_ERR_WS_MESSAGE_SIZE_EXCEEDED";
5632
5632
  }
5633
5633
  static [Symbol.hasInstance](instance) {
@@ -5945,7 +5945,7 @@ var require_util = __commonJS({
5945
5945
  var { kDestroyed, kBodyUsed, kListeners, kBody } = require_symbols();
5946
5946
  var { IncomingMessage } = require("node:http");
5947
5947
  var stream = require("node:stream");
5948
- var net = require("node:net");
5948
+ var net2 = require("node:net");
5949
5949
  var { stringify } = require("node:querystring");
5950
5950
  var { EventEmitter: EE } = require("node:events");
5951
5951
  var timers = require_timers();
@@ -6094,7 +6094,7 @@ var require_util = __commonJS({
6094
6094
  }
6095
6095
  assert(typeof host === "string");
6096
6096
  const servername = getHostname(host);
6097
- if (net.isIP(servername)) {
6097
+ if (net2.isIP(servername)) {
6098
6098
  return "";
6099
6099
  }
6100
6100
  return servername;
@@ -6663,14 +6663,14 @@ var require_util = __commonJS({
6663
6663
  if (socket == null) {
6664
6664
  return;
6665
6665
  }
6666
- let message = "Connect Timeout Error";
6666
+ let message2 = "Connect Timeout Error";
6667
6667
  if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) {
6668
- message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(", ")},`;
6668
+ message2 += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(", ")},`;
6669
6669
  } else {
6670
- message += ` (attempted address: ${opts.hostname}:${opts.port},`;
6670
+ message2 += ` (attempted address: ${opts.hostname}:${opts.port},`;
6671
6671
  }
6672
- message += ` timeout: ${opts.timeout}ms)`;
6673
- destroy(socket, new ConnectTimeoutError(message));
6672
+ message2 += ` timeout: ${opts.timeout}ms)`;
6673
+ destroy(socket, new ConnectTimeoutError(message2));
6674
6674
  }
6675
6675
  function getProtocolFromUrlString(urlString) {
6676
6676
  if (urlString[0] === "h" && urlString[1] === "t" && urlString[2] === "t" && urlString[3] === "p") {
@@ -7785,7 +7785,7 @@ var require_dispatcher_base = __commonJS({
7785
7785
  var require_connect = __commonJS({
7786
7786
  "../../node_modules/.pnpm/undici@7.30.1/node_modules/undici/lib/core/connect.js"(exports2, module2) {
7787
7787
  "use strict";
7788
- var net = require("node:net");
7788
+ var net2 = require("node:net");
7789
7789
  var assert = require("node:assert");
7790
7790
  var util = require_util();
7791
7791
  var { InvalidArgumentError } = require_errors();
@@ -7872,7 +7872,7 @@ var require_connect = __commonJS({
7872
7872
  } else {
7873
7873
  assert(!httpSocket, "httpSocket can only be sent on TLS update");
7874
7874
  port = port || 80;
7875
- socket = net.connect({
7875
+ socket = net2.connect({
7876
7876
  highWaterMark: 64 * 1024,
7877
7877
  // Same as nodejs fs streams.
7878
7878
  ...options,
@@ -9382,15 +9382,15 @@ var require_webidl = __commonJS({
9382
9382
  errors: {},
9383
9383
  is: {}
9384
9384
  };
9385
- webidl.errors.exception = function(message) {
9386
- return new TypeError(`${message.header}: ${message.message}`);
9385
+ webidl.errors.exception = function(message2) {
9386
+ return new TypeError(`${message2.header}: ${message2.message}`);
9387
9387
  };
9388
9388
  webidl.errors.conversionFailed = function(opts) {
9389
9389
  const plural = opts.types.length === 1 ? "" : " one of";
9390
- const message = `${opts.argument} could not be converted to${plural}: ${opts.types.join(", ")}.`;
9390
+ const message2 = `${opts.argument} could not be converted to${plural}: ${opts.types.join(", ")}.`;
9391
9391
  return webidl.errors.exception({
9392
9392
  header: opts.prefix,
9393
- message
9393
+ message: message2
9394
9394
  });
9395
9395
  };
9396
9396
  webidl.errors.invalidArgument = function(context) {
@@ -11851,12 +11851,12 @@ var require_client_h1 = __commonJS({
11851
11851
  return new ResponseContentLengthMismatchError();
11852
11852
  }
11853
11853
  const ptr = llhttp.llhttp_get_error_reason(this.ptr);
11854
- let message = "";
11854
+ let message2 = "";
11855
11855
  if (ptr) {
11856
11856
  const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0);
11857
- message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")";
11857
+ message2 = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")";
11858
11858
  }
11859
- return new HTTPParserError(message, constants.ERROR[ret], data);
11859
+ return new HTTPParserError(message2, constants.ERROR[ret], data);
11860
11860
  }
11861
11861
  destroy() {
11862
11862
  assert(currentParser === null);
@@ -12802,7 +12802,7 @@ var require_client_h2 = __commonJS({
12802
12802
  "../../node_modules/.pnpm/undici@7.30.1/node_modules/undici/lib/dispatcher/client-h2.js"(exports2, module2) {
12803
12803
  "use strict";
12804
12804
  var assert = require("node:assert");
12805
- var { pipeline: pipeline2 } = require("node:stream");
12805
+ var { pipeline } = require("node:stream");
12806
12806
  var util = require_util();
12807
12807
  var {
12808
12808
  RequestContentLengthMismatchError,
@@ -12845,11 +12845,11 @@ var require_client_h2 = __commonJS({
12845
12845
  var { channels } = require_diagnostics();
12846
12846
  var kOpenStreams = /* @__PURE__ */ Symbol("open streams");
12847
12847
  var extractBody;
12848
- var http22;
12848
+ var http2;
12849
12849
  try {
12850
- http22 = require("node:http2");
12850
+ http2 = require("node:http2");
12851
12851
  } catch {
12852
- http22 = { constants: {} };
12852
+ http2 = { constants: {} };
12853
12853
  }
12854
12854
  var {
12855
12855
  constants: {
@@ -12864,7 +12864,7 @@ var require_client_h2 = __commonJS({
12864
12864
  NGHTTP2_REFUSED_STREAM,
12865
12865
  NGHTTP2_CANCEL
12866
12866
  }
12867
- } = http22;
12867
+ } = http2;
12868
12868
  function parseH2Headers(headers) {
12869
12869
  const result = [];
12870
12870
  for (const [name, value2] of Object.entries(headers)) {
@@ -12882,7 +12882,7 @@ var require_client_h2 = __commonJS({
12882
12882
  client[kSocket] = socket;
12883
12883
  const http2InitialWindowSize = client[kHTTP2InitialWindowSize];
12884
12884
  const http2ConnectionWindowSize = client[kHTTP2ConnectionWindowSize];
12885
- const session = http22.connect(client[kUrl], {
12885
+ const session = http2.connect(client[kUrl], {
12886
12886
  createConnection: () => socket,
12887
12887
  peerMaxConcurrentStreams: client[kMaxConcurrentStreams],
12888
12888
  settings: {
@@ -13474,7 +13474,7 @@ var require_client_h2 = __commonJS({
13474
13474
  }
13475
13475
  function writeStream(abort, socket, expectsPayload, h2stream, body, client, request, contentLength) {
13476
13476
  assert(contentLength !== 0 || client[kRunning] === 0, "stream body cannot be pipelined");
13477
- const pipe = pipeline2(
13477
+ const pipe = pipeline(
13478
13478
  body,
13479
13479
  h2stream,
13480
13480
  (err) => {
@@ -13568,8 +13568,8 @@ var require_client = __commonJS({
13568
13568
  "../../node_modules/.pnpm/undici@7.30.1/node_modules/undici/lib/dispatcher/client.js"(exports2, module2) {
13569
13569
  "use strict";
13570
13570
  var assert = require("node:assert");
13571
- var net = require("node:net");
13572
- var http3 = require("node:http");
13571
+ var net2 = require("node:net");
13572
+ var http2 = require("node:http");
13573
13573
  var util = require_util();
13574
13574
  var { ClientStats } = require_stats();
13575
13575
  var { channels } = require_diagnostics();
@@ -13627,7 +13627,7 @@ var require_client = __commonJS({
13627
13627
  var connectH1 = require_client_h1();
13628
13628
  var connectH2 = require_client_h2();
13629
13629
  var kClosedResolve = /* @__PURE__ */ Symbol("kClosedResolve");
13630
- var getDefaultNodeMaxHeaderSize = http3 && http3.maxHeaderSize && Number.isInteger(http3.maxHeaderSize) && http3.maxHeaderSize > 0 ? () => http3.maxHeaderSize : () => {
13630
+ var getDefaultNodeMaxHeaderSize = http2 && http2.maxHeaderSize && Number.isInteger(http2.maxHeaderSize) && http2.maxHeaderSize > 0 ? () => http2.maxHeaderSize : () => {
13631
13631
  throw new InvalidArgumentError("http module not available or http.maxHeaderSize invalid");
13632
13632
  };
13633
13633
  var noop = () => {
@@ -13724,7 +13724,7 @@ var require_client = __commonJS({
13724
13724
  if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {
13725
13725
  throw new InvalidArgumentError("maxRequestsPerClient must be a positive number");
13726
13726
  }
13727
- if (localAddress != null && (typeof localAddress !== "string" || net.isIP(localAddress) === 0)) {
13727
+ if (localAddress != null && (typeof localAddress !== "string" || net2.isIP(localAddress) === 0)) {
13728
13728
  throw new InvalidArgumentError("localAddress must be valid string IP address");
13729
13729
  }
13730
13730
  if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {
@@ -13904,7 +13904,7 @@ var require_client = __commonJS({
13904
13904
  const idx = hostname.indexOf("]");
13905
13905
  assert(idx !== -1);
13906
13906
  const ip = hostname.substring(1, idx);
13907
- assert(net.isIPv6(ip));
13907
+ assert(net2.isIPv6(ip));
13908
13908
  hostname = ip;
13909
13909
  }
13910
13910
  client[kConnecting] = true;
@@ -14852,10 +14852,10 @@ var require_socks5_utils = __commonJS({
14852
14852
  "../../node_modules/.pnpm/undici@7.30.1/node_modules/undici/lib/core/socks5-utils.js"(exports2, module2) {
14853
14853
  "use strict";
14854
14854
  var { Buffer: Buffer2 } = require("node:buffer");
14855
- var net = require("node:net");
14855
+ var net2 = require("node:net");
14856
14856
  var { InvalidArgumentError } = require_errors();
14857
14857
  function parseAddress(address) {
14858
- if (net.isIPv4(address)) {
14858
+ if (net2.isIPv4(address)) {
14859
14859
  const parts = address.split(".").map(Number);
14860
14860
  return {
14861
14861
  type: 1,
@@ -14863,7 +14863,7 @@ var require_socks5_utils = __commonJS({
14863
14863
  buffer: Buffer2.from(parts)
14864
14864
  };
14865
14865
  }
14866
- if (net.isIPv6(address)) {
14866
+ if (net2.isIPv6(address)) {
14867
14867
  return {
14868
14868
  type: 4,
14869
14869
  // IPv6
@@ -14886,7 +14886,7 @@ var require_socks5_utils = __commonJS({
14886
14886
  if (address.includes(".")) {
14887
14887
  const lastColonIndex = address.lastIndexOf(":");
14888
14888
  const ipv4Part = address.slice(lastColonIndex + 1);
14889
- if (net.isIPv4(ipv4Part)) {
14889
+ if (net2.isIPv4(ipv4Part)) {
14890
14890
  const octets = ipv4Part.split(".").map(Number);
14891
14891
  const high = (octets[0] << 8 | octets[1]).toString(16);
14892
14892
  const low = (octets[2] << 8 | octets[3]).toString(16);
@@ -14993,8 +14993,8 @@ var require_socks5_utils = __commonJS({
14993
14993
  7: "Command not supported",
14994
14994
  8: "Address type not supported"
14995
14995
  };
14996
- const message = messages[replyCode] || `Unknown SOCKS5 error code: ${replyCode}`;
14997
- const error = new Error(message);
14996
+ const message2 = messages[replyCode] || `Unknown SOCKS5 error code: ${replyCode}`;
14997
+ const error = new Error(message2);
14998
14998
  error.code = `SOCKS5_${replyCode}`;
14999
14999
  return error;
15000
15000
  }
@@ -17388,7 +17388,7 @@ var require_api_pipeline = __commonJS({
17388
17388
  util.destroy(ret, err);
17389
17389
  }
17390
17390
  };
17391
- function pipeline2(opts, handler) {
17391
+ function pipeline(opts, handler) {
17392
17392
  try {
17393
17393
  const pipelineHandler = new PipelineHandler(opts, handler);
17394
17394
  this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler);
@@ -17397,7 +17397,7 @@ var require_api_pipeline = __commonJS({
17397
17397
  return new PassThrough().destroy(err);
17398
17398
  }
17399
17399
  }
17400
- module2.exports = pipeline2;
17400
+ module2.exports = pipeline;
17401
17401
  }
17402
17402
  });
17403
17403
 
@@ -17605,10 +17605,10 @@ var require_mock_errors = __commonJS({
17605
17605
  var { UndiciError } = require_errors();
17606
17606
  var kMockNotMatchedError = /* @__PURE__ */ Symbol.for("undici.error.UND_MOCK_ERR_MOCK_NOT_MATCHED");
17607
17607
  var MockNotMatchedError = class extends UndiciError {
17608
- constructor(message) {
17609
- super(message);
17608
+ constructor(message2) {
17609
+ super(message2);
17610
17610
  this.name = "MockNotMatchedError";
17611
- this.message = message || "The request does not match any registered mock dispatches";
17611
+ this.message = message2 || "The request does not match any registered mock dispatches";
17612
17612
  this.code = "UND_MOCK_ERR_MOCK_NOT_MATCHED";
17613
17613
  }
17614
17614
  static [Symbol.hasInstance](instance) {
@@ -18763,8 +18763,8 @@ var require_snapshot_utils = __commonJS({
18763
18763
  match: new Set(matchHeaders.map((header) => caseSensitive ? header : header.toLowerCase()))
18764
18764
  };
18765
18765
  }
18766
- var crypto2 = runtimeFeatures.has("crypto") ? require("node:crypto") : null;
18767
- var hashId = crypto2?.hash ? (value2) => crypto2.hash("sha256", value2, "base64url") : (value2) => Buffer.from(value2).toString("base64url");
18766
+ var crypto = runtimeFeatures.has("crypto") ? require("node:crypto") : null;
18767
+ var hashId = crypto?.hash ? (value2) => crypto.hash("sha256", value2, "base64url") : (value2) => Buffer.from(value2).toString("base64url");
18768
18768
  function isUndiciHeaders(headers) {
18769
18769
  return Array.isArray(headers) && (headers.length & 1) === 0;
18770
18770
  }
@@ -18839,7 +18839,7 @@ var require_snapshot_utils = __commonJS({
18839
18839
  var require_snapshot_recorder = __commonJS({
18840
18840
  "../../node_modules/.pnpm/undici@7.30.1/node_modules/undici/lib/mock/snapshot-recorder.js"(exports2, module2) {
18841
18841
  "use strict";
18842
- var { writeFile: writeFile2, readFile: readFile2, mkdir: mkdir2 } = require("node:fs/promises");
18842
+ var { writeFile, readFile, mkdir } = require("node:fs/promises");
18843
18843
  var { dirname: dirname4, resolve: resolve2 } = require("node:path");
18844
18844
  var { setTimeout: setTimeout2, clearTimeout: clearTimeout2 } = require("node:timers");
18845
18845
  var { InvalidArgumentError, UndiciError } = require_errors();
@@ -19041,7 +19041,7 @@ var require_snapshot_recorder = __commonJS({
19041
19041
  throw new InvalidArgumentError("Snapshot path is required");
19042
19042
  }
19043
19043
  try {
19044
- const data = await readFile2(resolve2(path), "utf8");
19044
+ const data = await readFile(resolve2(path), "utf8");
19045
19045
  const parsed = JSON.parse(data);
19046
19046
  if (Array.isArray(parsed)) {
19047
19047
  this.#snapshots.clear();
@@ -19071,12 +19071,12 @@ var require_snapshot_recorder = __commonJS({
19071
19071
  throw new InvalidArgumentError("Snapshot path is required");
19072
19072
  }
19073
19073
  const resolvedPath = resolve2(path);
19074
- await mkdir2(dirname4(resolvedPath), { recursive: true });
19074
+ await mkdir(dirname4(resolvedPath), { recursive: true });
19075
19075
  const data = Array.from(this.#snapshots.entries()).map(([hash, snapshot]) => ({
19076
19076
  hash,
19077
19077
  snapshot
19078
19078
  }));
19079
- await writeFile2(resolvedPath, JSON.stringify(data, null, 2), { flush: true });
19079
+ await writeFile(resolvedPath, JSON.stringify(data, null, 2), { flush: true });
19080
19080
  }
19081
19081
  /**
19082
19082
  * Clears all recorded snapshots
@@ -22674,7 +22674,7 @@ var require_decompress = __commonJS({
22674
22674
  "../../node_modules/.pnpm/undici@7.30.1/node_modules/undici/lib/interceptor/decompress.js"(exports2, module2) {
22675
22675
  "use strict";
22676
22676
  var { createInflate, createGunzip, createBrotliDecompress, createZstdDecompress } = require("node:zlib");
22677
- var { pipeline: pipeline2, Transform: TransformStream2 } = require("node:stream");
22677
+ var { pipeline, Transform: TransformStream2 } = require("node:stream");
22678
22678
  var { InvalidArgumentError, ResponseExceededMaxSizeError } = require_errors();
22679
22679
  var DecoratorHandler = require_decorator_handler();
22680
22680
  var { runtimeFeatures } = require_runtime_features();
@@ -22991,7 +22991,7 @@ var require_decompress = __commonJS({
22991
22991
  #setupMultipleDecompressors() {
22992
22992
  const lastDecompressor = this.#decompressors[this.#decompressors.length - 1];
22993
22993
  this.#setupDecompressorEvents(lastDecompressor);
22994
- pipeline2(this.#decompressors, (err) => {
22994
+ pipeline(this.#decompressors, (err) => {
22995
22995
  if (this.#terminated) {
22996
22996
  return;
22997
22997
  }
@@ -25632,10 +25632,10 @@ var require_subresource_integrity = __commonJS({
25632
25632
  var { runtimeFeatures } = require_runtime_features();
25633
25633
  var { asciiLowercase } = require_infra();
25634
25634
  var validSRIHashAlgorithmTokenSet = /* @__PURE__ */ new Map([["sha256", 0], ["sha384", 1], ["sha512", 2]]);
25635
- var crypto2;
25635
+ var crypto;
25636
25636
  if (runtimeFeatures.has("crypto")) {
25637
- crypto2 = require("node:crypto");
25638
- const cryptoHashes = crypto2.getHashes();
25637
+ crypto = require("node:crypto");
25638
+ const cryptoHashes = crypto.getHashes();
25639
25639
  if (cryptoHashes.length === 0) {
25640
25640
  validSRIHashAlgorithmTokenSet.clear();
25641
25641
  }
@@ -25723,7 +25723,7 @@ var require_subresource_integrity = __commonJS({
25723
25723
  return result;
25724
25724
  }
25725
25725
  var applyAlgorithmToBytes = (algorithm, bytes) => {
25726
- return crypto2.hash(algorithm, bytes, "base64");
25726
+ return crypto.hash(algorithm, bytes, "base64");
25727
25727
  };
25728
25728
  function caseSensitiveMatch(actualValue, expectedValue) {
25729
25729
  let actualValueLength = actualValue.length;
@@ -25821,7 +25821,7 @@ var require_fetch = __commonJS({
25821
25821
  subresourceSet
25822
25822
  } = require_constants4();
25823
25823
  var EE = require("node:events");
25824
- var { Readable, pipeline: pipeline2, finished, isErrored, isReadable } = require("node:stream");
25824
+ var { Readable, pipeline, finished, isErrored, isReadable } = require("node:stream");
25825
25825
  var { addAbortListener, bufferToLowerCasedHeaderName } = require_util();
25826
25826
  var { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require_data_url();
25827
25827
  var { getGlobalDispatcher } = require_global2();
@@ -26812,7 +26812,7 @@ var require_fetch = __commonJS({
26812
26812
  status,
26813
26813
  statusText,
26814
26814
  headersList,
26815
- body: decoders.length ? pipeline2(this.body, ...decoders, (err) => {
26815
+ body: decoders.length ? pipeline(this.body, ...decoders, (err) => {
26816
26816
  if (err) {
26817
26817
  this.onError(err);
26818
26818
  }
@@ -28711,7 +28711,7 @@ var require_connection = __commonJS({
28711
28711
  var { WebsocketFrameSend } = require_frame();
28712
28712
  var assert = require("node:assert");
28713
28713
  var { runtimeFeatures } = require_runtime_features();
28714
- var crypto2 = runtimeFeatures.has("crypto") ? require("node:crypto") : null;
28714
+ var crypto = runtimeFeatures.has("crypto") ? require("node:crypto") : null;
28715
28715
  var warningEmitted = false;
28716
28716
  function establishWebSocketConnection(url, protocols, client, handler, options) {
28717
28717
  const requestURL = url;
@@ -28731,7 +28731,7 @@ var require_connection = __commonJS({
28731
28731
  const headersList = getHeadersList(new Headers(options.headers));
28732
28732
  request.headersList = headersList;
28733
28733
  }
28734
- const keyValue = crypto2.randomBytes(16).toString("base64");
28734
+ const keyValue = crypto.randomBytes(16).toString("base64");
28735
28735
  request.headersList.append("sec-websocket-key", keyValue, true);
28736
28736
  request.headersList.append("sec-websocket-version", "13", true);
28737
28737
  for (const protocol of protocols) {
@@ -28771,7 +28771,7 @@ var require_connection = __commonJS({
28771
28771
  return;
28772
28772
  }
28773
28773
  const secWSAccept = response.headersList.get("Sec-WebSocket-Accept");
28774
- const digest = crypto2.hash("sha1", keyValue + uid, "base64");
28774
+ const digest = crypto.hash("sha1", keyValue + uid, "base64");
28775
28775
  if (secWSAccept !== digest) {
28776
28776
  failHandshake(handler, response, 1002, "Incorrect hash received in Sec-WebSocket-Accept header.");
28777
28777
  return;
@@ -29915,9 +29915,9 @@ var require_websocketerror = __commonJS({
29915
29915
  var WebSocketError = class _WebSocketError extends createInheritableDOMException() {
29916
29916
  #closeCode;
29917
29917
  #reason;
29918
- constructor(message = "", init = void 0) {
29919
- message = webidl.converters.DOMString(message, "WebSocketError", "message");
29920
- super(message, "WebSocketError");
29918
+ constructor(message2 = "", init = void 0) {
29919
+ message2 = webidl.converters.DOMString(message2, "WebSocketError", "message");
29920
+ super(message2, "WebSocketError");
29921
29921
  if (init === kConstruct) {
29922
29922
  return;
29923
29923
  } else if (init !== null) {
@@ -29943,8 +29943,8 @@ var require_websocketerror = __commonJS({
29943
29943
  * @param {number|null} code
29944
29944
  * @param {string} reason
29945
29945
  */
29946
- static createUnvalidatedWebSocketError(message, code, reason) {
29947
- const error = new _WebSocketError(message, kConstruct);
29946
+ static createUnvalidatedWebSocketError(message2, code, reason) {
29947
+ const error = new _WebSocketError(message2, kConstruct);
29948
29948
  error.#closeCode = code;
29949
29949
  error.#reason = reason;
29950
29950
  return error;
@@ -30709,7 +30709,7 @@ ${value2}`;
30709
30709
  var require_eventsource = __commonJS({
30710
30710
  "../../node_modules/.pnpm/undici@7.30.1/node_modules/undici/lib/web/eventsource/eventsource.js"(exports2, module2) {
30711
30711
  "use strict";
30712
- var { pipeline: pipeline2 } = require("node:stream");
30712
+ var { pipeline } = require("node:stream");
30713
30713
  var { fetching } = require_fetch();
30714
30714
  var { makeRequest } = require_request2();
30715
30715
  var { webidl } = require_webidl();
@@ -30869,7 +30869,7 @@ var require_eventsource = __commonJS({
30869
30869
  ));
30870
30870
  }
30871
30871
  });
30872
- pipeline2(
30872
+ pipeline(
30873
30873
  response.body.stream,
30874
30874
  eventSourceStream,
30875
30875
  (error) => {
@@ -31221,52 +31221,12 @@ ${captureLines}` : capture.stack;
31221
31221
  });
31222
31222
 
31223
31223
  // src/main.ts
31224
- var import_node_crypto2 = require("node:crypto");
31225
31224
  var import_node_fs5 = require("node:fs");
31225
+ var import_node_path5 = require("node:path");
31226
31226
 
31227
31227
  // src/client.ts
31228
31228
  var import_node_http = __toESM(require("node:http"), 1);
31229
31229
 
31230
- // ../core/src/dev-files.ts
31231
- var DEV_FILES_PATH = "/_builders/dev-files/";
31232
- var DEV_DATA_DIR_ENV = "BUILDERS_DEV_DATA_DIR";
31233
- var DEV_FILES_SECRET_ENV = "BUILDERS_DEV_FILES_SECRET";
31234
- var enc = new TextEncoder();
31235
- async function sign(secret, g) {
31236
- const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
31237
- const mac = await crypto.subtle.sign("HMAC", key, enc.encode(`${g.action}
31238
- ${g.path}
31239
- ${g.expires}
31240
- ${g.contentType}`));
31241
- return [...new Uint8Array(mac)].map((b) => b.toString(16).padStart(2, "0")).join("");
31242
- }
31243
- async function verifyDevFileLink(secret, pathAndQuery, action, now = Date.now()) {
31244
- let url;
31245
- try {
31246
- url = new URL(pathAndQuery, "http://local");
31247
- } catch {
31248
- return null;
31249
- }
31250
- if (!url.pathname.startsWith(DEV_FILES_PATH)) return null;
31251
- let path;
31252
- try {
31253
- path = url.pathname.slice(DEV_FILES_PATH.length).split("/").map(decodeURIComponent).join("/");
31254
- } catch {
31255
- return null;
31256
- }
31257
- const g = { path, action, expires: Number(url.searchParams.get("e")), contentType: url.searchParams.get("ct") ?? "" };
31258
- if (url.searchParams.get("a") !== action || !Number.isSafeInteger(g.expires) || g.expires < now || !validDevFilePath(path)) return null;
31259
- const want = await sign(secret, g);
31260
- const got = url.searchParams.get("s") ?? "";
31261
- if (got.length !== want.length) return null;
31262
- let diff = 0;
31263
- for (let i = 0; i < want.length; i++) diff |= want.charCodeAt(i) ^ got.charCodeAt(i);
31264
- return diff === 0 ? g : null;
31265
- }
31266
- function validDevFilePath(path) {
31267
- return !!path && !path.startsWith("/") && !/[\\\u0000-\u001f\u007f]/.test(path) && path.split("/").every((p) => p !== "" && p !== "." && p !== "..");
31268
- }
31269
-
31270
31230
  // ../../node_modules/.pnpm/ws@8.22.0/node_modules/ws/wrapper.mjs
31271
31231
  var import_stream = __toESM(require_stream(), 1);
31272
31232
  var import_extension = __toESM(require_extension(), 1);
@@ -31441,8 +31401,8 @@ function proxiedFetch(target, env = process.env) {
31441
31401
 
31442
31402
  // src/transport.ts
31443
31403
  var RefusedError = class extends Error {
31444
- constructor(status, message) {
31445
- super(message);
31404
+ constructor(status, message2) {
31405
+ super(message2);
31446
31406
  this.status = status;
31447
31407
  }
31448
31408
  status;
@@ -31714,7 +31674,7 @@ var TunnelClient = class {
31714
31674
  // Serves one link until it closes.
31715
31675
  serve(link, onReady) {
31716
31676
  this.link = link;
31717
- const session = new LinkSession(link, this.o.port, this.o.localHost ?? "127.0.0.1", this.o.filesPort);
31677
+ const session = new LinkSession(link, this.o.port, this.o.localHost ?? "127.0.0.1");
31718
31678
  if (this.o.onRequest) session.onRequest = this.o.onRequest;
31719
31679
  return new Promise((resolve2) => {
31720
31680
  let final = false;
@@ -31742,16 +31702,14 @@ var TunnelClient = class {
31742
31702
  }
31743
31703
  };
31744
31704
  var LinkSession = class {
31745
- constructor(link, port, localHost, filesPort) {
31705
+ constructor(link, port, localHost) {
31746
31706
  this.link = link;
31747
31707
  this.port = port;
31748
31708
  this.localHost = localHost;
31749
- this.filesPort = filesPort;
31750
31709
  }
31751
31710
  link;
31752
31711
  port;
31753
31712
  localHost;
31754
- filesPort;
31755
31713
  http = /* @__PURE__ */ new Map();
31756
31714
  ws = /* @__PURE__ */ new Map();
31757
31715
  previewOrigin = "";
@@ -31903,10 +31861,9 @@ var LinkSession = class {
31903
31861
  }
31904
31862
  const headers = this.localHeaders(head.headers);
31905
31863
  const framed = !NO_DEFAULT_FRAMING.has(head.method.toUpperCase()) || headers["content-length"] !== void 0 || headers["transfer-encoding"] !== void 0;
31906
- const files = this.filesPort !== void 0 && head.path.startsWith(DEV_FILES_PATH);
31907
31864
  const req = import_node_http.default.request({
31908
- host: files ? "127.0.0.1" : this.localHost,
31909
- port: files ? this.filesPort : this.port,
31865
+ host: this.localHost,
31866
+ port: this.port,
31910
31867
  method: head.method,
31911
31868
  path: head.path,
31912
31869
  headers,
@@ -32078,85 +32035,754 @@ function devDataDir(appDir) {
32078
32035
  return dir;
32079
32036
  }
32080
32037
 
32081
- // src/dev-files.ts
32082
- var import_node_crypto = require("node:crypto");
32038
+ // src/emulators.ts
32039
+ var import_node_child_process2 = require("node:child_process");
32083
32040
  var import_node_fs2 = require("node:fs");
32084
- var import_promises = require("node:fs/promises");
32085
- var import_node_http2 = __toESM(require("node:http"), 1);
32041
+ var import_node_net = __toESM(require("node:net"), 1);
32042
+ var import_node_os = require("node:os");
32086
32043
  var import_node_path2 = require("node:path");
32087
- var import_promises2 = require("node:stream/promises");
32088
- var MAX_UPLOAD = 100 * 1024 * 1024;
32089
- var INLINE = /^(image\/(png|jpeg|gif|webp|avif)|application\/pdf|audio\/[\w.+-]+|video\/[\w.+-]+|text\/plain)$/;
32090
- async function startDevFiles(o) {
32091
- const server = import_node_http2.default.createServer((req, res) => {
32092
- handle(req, res).catch(() => {
32093
- if (!res.headersSent) res.writeHead(500, { "content-type": "text/plain" });
32094
- res.end("The file could not be served.\n");
32044
+
32045
+ // firebase-tools/package.json
32046
+ var package_default = {
32047
+ name: "builders-firebase-tools",
32048
+ private: true,
32049
+ description: "The firebase-tools version of the dev preview emulators. builders-cli installs it with npm ci --ignore-scripts from package-lock.json.",
32050
+ dependencies: {
32051
+ "firebase-tools": "15.35.0"
32052
+ }
32053
+ };
32054
+
32055
+ // src/emulators.ts
32056
+ var FIREBASE_TOOLS_VERSION = package_default.dependencies["firebase-tools"];
32057
+ var EMULATOR_PROJECT = "demo-builders";
32058
+ var EMULATOR_BUCKET = `${EMULATOR_PROJECT}.appspot.com`;
32059
+ var EMULATORS_ERROR_ENV = "BUILDERS_EMULATORS_ERROR";
32060
+ var MIN_JAVA = 21;
32061
+ var EXPORT_EVERY_MS = 3e4;
32062
+ var EXPORT_TIMEOUT_MS = 2e4;
32063
+ var EXPORT_MS_PER_MB = 1e3;
32064
+ var EXPORT_TIMEOUT_MAX_MS = 15 * 6e4;
32065
+ var READY_TIMEOUT_MS = 18e4;
32066
+ var IMPORT_MS_PER_MB = 1e3;
32067
+ var SETUP_TIMEOUT_MS = 15 * 6e4;
32068
+ var EXPORT_FAILURES_LOG = 3;
32069
+ var STOP_EXPORT_MS = 4e3;
32070
+ var STOP_WAIT_MS = 2500;
32071
+ var FIRST_WAIT_MS2 = 1e3;
32072
+ var MAX_WAIT_MS2 = 3e4;
32073
+ var STABLE_MS2 = 6e4;
32074
+ var BAD_IMPORT_TRIES = 3;
32075
+ var HEALTH_FAILURES = 2;
32076
+ var METADATA = "firebase-export-metadata.json";
32077
+ function emulatorEnv(ports, o) {
32078
+ return {
32079
+ FIRESTORE_EMULATOR_HOST: `127.0.0.1:${ports.firestore}`,
32080
+ FIREBASE_STORAGE_EMULATOR_HOST: `127.0.0.1:${ports.storage}`,
32081
+ STORAGE_EMULATOR_HOST: `http://127.0.0.1:${ports.storage}`,
32082
+ GOOGLE_CLOUD_PROJECT: EMULATOR_PROJECT,
32083
+ GCLOUD_PROJECT: EMULATOR_PROJECT,
32084
+ ...o.storage ? { STORAGE_BUCKET: EMULATOR_BUCKET } : {}
32085
+ };
32086
+ }
32087
+ function storageOn(addOns) {
32088
+ return addOns === void 0 || addOns.split(",").includes("storage");
32089
+ }
32090
+ function javaMajor(run = () => (0, import_node_child_process2.spawnSync)("java", ["-version"], { encoding: "utf8", timeout: 2e4 })) {
32091
+ const r = run();
32092
+ if (r.error) return null;
32093
+ const m = /version "(\d+)(?:\.(\d+))?/.exec(`${r.stderr ?? ""}
32094
+ ${r.stdout ?? ""}`);
32095
+ if (!m) return null;
32096
+ const major = Number(m[1]);
32097
+ return major === 1 && m[2] ? Number(m[2]) : major;
32098
+ }
32099
+ function javaProblem(major = javaMajor()) {
32100
+ if (major !== null && major >= MIN_JAVA) return null;
32101
+ const found = major === null ? "this machine has no Java" : `this machine has Java ${major}`;
32102
+ return `The test database of this app (the Firebase emulators) needs Java ${MIN_JAVA} or later, and ${found}. Install it (for example: sudo apt-get install -y openjdk-${MIN_JAVA}-jre-headless), then run the preview command again with --restart.`;
32103
+ }
32104
+ async function freePorts() {
32105
+ const servers = [];
32106
+ const ports = [];
32107
+ try {
32108
+ while (ports.length < 5) {
32109
+ const s = import_node_net.default.createServer();
32110
+ servers.push(s);
32111
+ await new Promise((res, rej) => {
32112
+ s.once("error", rej);
32113
+ s.listen(0, "127.0.0.1", () => res());
32114
+ });
32115
+ ports.push(s.address().port);
32116
+ }
32117
+ } finally {
32118
+ await Promise.all(servers.map((s) => new Promise((r) => s.close(r))));
32119
+ }
32120
+ const [firestore, firestoreWs, storage, hub, logging] = ports;
32121
+ return { firestore, firestoreWs, storage, hub, logging };
32122
+ }
32123
+ function firebaseConfig(ports) {
32124
+ const at = (port) => ({ host: "127.0.0.1", port });
32125
+ return {
32126
+ firestore: { rules: "firestore.rules" },
32127
+ storage: { rules: "storage.rules" },
32128
+ emulators: {
32129
+ singleProjectMode: true,
32130
+ firestore: { ...at(ports.firestore), websocketPort: ports.firestoreWs },
32131
+ storage: at(ports.storage),
32132
+ hub: at(ports.hub),
32133
+ logging: at(ports.logging),
32134
+ ui: { enabled: false }
32135
+ }
32136
+ };
32137
+ }
32138
+ var FIRESTORE_RULES = `rules_version = '2';
32139
+ service cloud.firestore {
32140
+ match /databases/{database}/documents {
32141
+ match /{document=**} {
32142
+ allow read, write: if false;
32143
+ }
32144
+ }
32145
+ }
32146
+ `;
32147
+ var STORAGE_RULES = `rules_version = '2';
32148
+ service firebase.storage {
32149
+ match /b/{bucket}/o {
32150
+ match /{allPaths=**} {
32151
+ allow read, write: if false;
32152
+ }
32153
+ }
32154
+ }
32155
+ `;
32156
+ function importDir(dir) {
32157
+ for (const d of ["export", "export-old"]) if ((0, import_node_fs2.existsSync)((0, import_node_path2.join)(dir, d, METADATA))) return (0, import_node_path2.join)(dir, d);
32158
+ return null;
32159
+ }
32160
+ function swapExport(dir, tmp) {
32161
+ const cur = (0, import_node_path2.join)(dir, "export");
32162
+ const old = (0, import_node_path2.join)(dir, "export-old");
32163
+ (0, import_node_fs2.rmSync)(old, { recursive: true, force: true });
32164
+ if ((0, import_node_fs2.existsSync)(cur)) (0, import_node_fs2.renameSync)(cur, old);
32165
+ (0, import_node_fs2.renameSync)((0, import_node_path2.join)(dir, tmp), cur);
32166
+ (0, import_node_fs2.rmSync)(old, { recursive: true, force: true });
32167
+ }
32168
+ function removeTmpExports(dir) {
32169
+ try {
32170
+ for (const n of (0, import_node_fs2.readdirSync)(dir)) if (n.startsWith("export-tmp")) (0, import_node_fs2.rmSync)((0, import_node_path2.join)(dir, n), { recursive: true, force: true });
32171
+ } catch {
32172
+ }
32173
+ }
32174
+ function dirSize(path) {
32175
+ let total = 0;
32176
+ try {
32177
+ for (const e of (0, import_node_fs2.readdirSync)(path, { withFileTypes: true })) {
32178
+ const f = (0, import_node_path2.join)(path, e.name);
32179
+ total += e.isDirectory() ? dirSize(f) : (0, import_node_fs2.statSync)(f).size;
32180
+ }
32181
+ } catch {
32182
+ }
32183
+ return total;
32184
+ }
32185
+ var megabytes = (bytes) => Math.ceil(bytes / (1024 * 1024));
32186
+ var SETUP_SCRIPT = `const fs = require("fs");
32187
+ const crypto = require("crypto");
32188
+ const d = require(process.argv[1]);
32189
+ // An emulator of the user (FIRESTORE_EMULATOR_BINARY_PATH and the like:
32190
+ // localOnly) is only checked for existence and is never removed.
32191
+ function good(n) {
32192
+ const x = d.getDownloadDetails(n);
32193
+ if (x.localOnly) return fs.existsSync(x.binaryPath || x.downloadPath);
32194
+ const o = x.opts || {};
32195
+ if (!fs.existsSync(x.downloadPath)) return false;
32196
+ if (o.skipChecksumAndSize || !o.expectedSize || !o.expectedChecksum) return true;
32197
+ if (fs.statSync(x.downloadPath).size !== o.expectedSize) return false;
32198
+ return crypto.createHash("md5").update(fs.readFileSync(x.downloadPath)).digest("hex") === o.expectedChecksum;
32199
+ }
32200
+ (async () => {
32201
+ for (const n of ["firestore", "storage"]) {
32202
+ await d.downloadIfNecessary(n);
32203
+ if (good(n)) continue;
32204
+ if (d.getDownloadDetails(n).localOnly) throw new Error("The " + n + " emulator file that you set is missing.");
32205
+ console.error("The " + n + " emulator file is damaged; it downloads again.");
32206
+ fs.rmSync(d.getDownloadDetails(n).downloadPath, { force: true });
32207
+ await d.downloadIfNecessary(n);
32208
+ if (!good(n)) throw new Error("The " + n + " emulator file does not match its checksum.");
32209
+ }
32210
+ })().catch((e) => { console.error(e && e.message ? e.message : String(e)); process.exit(1); });`;
32211
+ async function setupEmulators(cmd, pre, cwd, signal) {
32212
+ const lib = (0, import_node_path2.join)((0, import_node_path2.dirname)((0, import_node_path2.dirname)(pre[0] ?? "")), "emulator", "downloadableEmulators.js");
32213
+ const result = await new Promise((res) => {
32214
+ const c = (0, import_node_child_process2.spawn)(cmd, ["-e", SETUP_SCRIPT, lib], { cwd, stdio: ["ignore", "inherit", "inherit"], env: { ...process.env, NO_UPDATE_NOTIFIER: "1" } });
32215
+ signal?.addEventListener("abort", () => c.kill("SIGKILL"), { once: true });
32216
+ const t = setTimeout(() => c.kill("SIGKILL"), SETUP_TIMEOUT_MS);
32217
+ c.once("error", (e) => {
32218
+ clearTimeout(t);
32219
+ res(e.message);
32220
+ });
32221
+ c.once("exit", (c2, sig) => {
32222
+ clearTimeout(t);
32223
+ res(sig ? `signal ${sig}` : c2 ?? -1);
32095
32224
  });
32096
32225
  });
32097
- const fail = (res, status, text) => {
32098
- res.writeHead(status, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" });
32099
- res.end(`${text}
32100
- `);
32101
- };
32102
- async function handle(req, res) {
32103
- const method = req.method ?? "GET";
32104
- const write = method === "PUT";
32105
- if (!write && method !== "GET" && method !== "HEAD") return fail(res, 405, "Method not allowed.");
32106
- const grant = await verifyDevFileLink(o.secret, req.url ?? "/", write ? "write" : "read");
32107
- if (!grant) return fail(res, 403, "This file link is not valid or has expired.");
32108
- const file = (0, import_node_path2.join)(o.dataDir, "files", grant.path);
32109
- const meta = (0, import_node_path2.join)(o.dataDir, "files-meta", `${grant.path}.json`);
32110
- if (write) {
32111
- const type2 = String(req.headers["content-type"] ?? "");
32112
- if (grant.contentType && type2 !== grant.contentType) return fail(res, 400, `Send the file with Content-Type ${grant.contentType}.`);
32113
- if (Number(req.headers["content-length"] ?? 0) > MAX_UPLOAD) return fail(res, 413, "The file is too large.");
32114
- await (0, import_promises.mkdir)((0, import_node_path2.dirname)(file), { recursive: true });
32115
- await (0, import_promises.mkdir)((0, import_node_path2.dirname)(meta), { recursive: true });
32116
- await (0, import_promises.mkdir)((0, import_node_path2.join)(o.dataDir, "uploads"), { recursive: true });
32117
- const tmp = (0, import_node_path2.join)(o.dataDir, "uploads", (0, import_node_crypto.randomBytes)(12).toString("hex"));
32118
- let size2 = 0;
32119
- req.on("data", (c) => {
32120
- size2 += c.length;
32121
- if (size2 > MAX_UPLOAD) req.destroy(new Error("too large"));
32226
+ if (result !== 0) throw new Error(`The emulator download did not work (${result}).`);
32227
+ }
32228
+ function toolsDir() {
32229
+ return (0, import_node_path2.join)(__dirname, "..", "firebase-tools");
32230
+ }
32231
+ async function firebaseCommand(log = (l) => console.error(l), signal) {
32232
+ const base = (0, import_node_path2.join)((0, import_node_os.homedir)(), ".builders", "firebase-tools", FIREBASE_TOOLS_VERSION);
32233
+ const bin = (d) => (0, import_node_path2.join)(d, "node_modules", "firebase-tools", "lib", "bin", "firebase.js");
32234
+ if (!(0, import_node_fs2.existsSync)(bin(base))) {
32235
+ const tmp = `${base}.tmp-${process.pid}`;
32236
+ (0, import_node_fs2.rmSync)(tmp, { recursive: true, force: true });
32237
+ (0, import_node_fs2.mkdirSync)(tmp, { recursive: true });
32238
+ for (const f of ["package.json", "package-lock.json"]) (0, import_node_fs2.writeFileSync)((0, import_node_path2.join)(tmp, f), (0, import_node_fs2.readFileSync)((0, import_node_path2.join)(toolsDir(), f)));
32239
+ log(`Installing firebase-tools ${FIREBASE_TOOLS_VERSION} for the test database (once per machine).`);
32240
+ const code = await new Promise((res) => {
32241
+ const c = (0, import_node_child_process2.spawn)("npm", ["ci", "--ignore-scripts", "--no-audit", "--no-fund", "--loglevel=error"], { cwd: tmp, stdio: "inherit" });
32242
+ const kill = () => c.kill("SIGKILL");
32243
+ if (signal?.aborted) kill();
32244
+ signal?.addEventListener("abort", kill, { once: true });
32245
+ c.once("error", (e) => res(e.message));
32246
+ c.once("exit", (c2) => res(c2 ?? -1));
32247
+ });
32248
+ if (code !== 0 || !(0, import_node_fs2.existsSync)(bin(tmp)) || signal?.aborted) {
32249
+ (0, import_node_fs2.rmSync)(tmp, { recursive: true, force: true });
32250
+ throw new Error(signal?.aborted ? "The install of firebase-tools was stopped." : `npm could not install firebase-tools ${FIREBASE_TOOLS_VERSION} (${code}).`);
32251
+ }
32252
+ try {
32253
+ (0, import_node_fs2.renameSync)(tmp, base);
32254
+ } catch {
32255
+ (0, import_node_fs2.rmSync)(tmp, { recursive: true, force: true });
32256
+ }
32257
+ }
32258
+ return [process.execPath, [bin(base)]];
32259
+ }
32260
+ var EMULATOR_CMD = /firebase-tools|firebase\.js|cloud-firestore-emulator|cloud-storage-rules-runtime|emulators:start/;
32261
+ function statFields(pid) {
32262
+ try {
32263
+ const stat = (0, import_node_fs2.readFileSync)(`/proc/${pid}/stat`, "utf8");
32264
+ return stat.slice(stat.lastIndexOf(")") + 2).split(" ");
32265
+ } catch {
32266
+ return null;
32267
+ }
32268
+ }
32269
+ var procTable = {
32270
+ bootId() {
32271
+ try {
32272
+ return (0, import_node_fs2.readFileSync)("/proc/sys/kernel/random/boot_id", "utf8").trim();
32273
+ } catch {
32274
+ return "";
32275
+ }
32276
+ },
32277
+ descendants(root) {
32278
+ const parent = /* @__PURE__ */ new Map();
32279
+ let names;
32280
+ try {
32281
+ names = (0, import_node_fs2.readdirSync)("/proc").filter((n) => /^\d+$/.test(n));
32282
+ } catch {
32283
+ return [];
32284
+ }
32285
+ for (const n of names) {
32286
+ const f = statFields(n);
32287
+ if (f) parent.set(Number(n), Number(f[1]));
32288
+ }
32289
+ const out = [];
32290
+ const queue = [root];
32291
+ while (queue.length) {
32292
+ const p = queue.shift();
32293
+ for (const [c, pp] of parent) {
32294
+ if (pp === p && !out.includes(c)) {
32295
+ out.push(c);
32296
+ queue.push(c);
32297
+ }
32298
+ }
32299
+ }
32300
+ return out;
32301
+ },
32302
+ startTime(pid) {
32303
+ const f = statFields(pid);
32304
+ const v = f ? Number(f[19]) : NaN;
32305
+ return Number.isFinite(v) ? v : null;
32306
+ },
32307
+ isEmulator(pid) {
32308
+ try {
32309
+ process.kill(pid, 0);
32310
+ } catch {
32311
+ return false;
32312
+ }
32313
+ try {
32314
+ return EMULATOR_CMD.test((0, import_node_fs2.readFileSync)(`/proc/${pid}/cmdline`, "utf8").replace(/\0/g, " "));
32315
+ } catch {
32316
+ return false;
32317
+ }
32318
+ },
32319
+ kill(pid, signal) {
32320
+ try {
32321
+ process.kill(pid, signal);
32322
+ } catch {
32323
+ }
32324
+ }
32325
+ };
32326
+ var isOpenTcp = (port) => new Promise((res) => {
32327
+ const s = import_node_net.default.connect(port, "127.0.0.1", () => {
32328
+ s.destroy();
32329
+ res(true);
32330
+ });
32331
+ s.once("error", () => res(false));
32332
+ s.setTimeout(1e3, () => {
32333
+ s.destroy();
32334
+ res(false);
32335
+ });
32336
+ });
32337
+ var HUB_PROBE_MS = 2500;
32338
+ var hubAnswersHttp = async (hub) => {
32339
+ try {
32340
+ const r = await fetch(`http://127.0.0.1:${hub}/emulators`, { signal: AbortSignal.timeout(HUB_PROBE_MS) });
32341
+ await r.arrayBuffer().catch(() => void 0);
32342
+ return r.ok;
32343
+ } catch {
32344
+ return false;
32345
+ }
32346
+ };
32347
+ var postJson = async (url, body, timeoutMs) => {
32348
+ try {
32349
+ const r = await fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(timeoutMs) });
32350
+ await r.arrayBuffer().catch(() => void 0);
32351
+ return r.status;
32352
+ } catch {
32353
+ return 0;
32354
+ }
32355
+ };
32356
+ var message = (e) => e instanceof Error ? e.message : String(e);
32357
+ var Emulators = class {
32358
+ constructor(o) {
32359
+ this.o = o;
32360
+ this.procs = o.procs ?? procTable;
32361
+ this.log = o.log ?? ((l) => console.error(l));
32362
+ this.clock = o.clock ?? Date.now;
32363
+ this.sleep = o.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms).unref()));
32364
+ this.isOpen = o.isOpen ?? isOpenTcp;
32365
+ this.post = o.post ?? postJson;
32366
+ this.stopRequested = new Promise((r) => this.abort.signal.addEventListener("abort", () => r(false), { once: true }));
32367
+ }
32368
+ o;
32369
+ child = null;
32370
+ stopped = false;
32371
+ isReady = false;
32372
+ timer = null;
32373
+ exporting = null;
32374
+ wake = null;
32375
+ exited = Promise.resolve();
32376
+ stopping = null;
32377
+ healthFailures = 0;
32378
+ // A test start without the import: stop it as soon as it is ready.
32379
+ probing = false;
32380
+ probeHit = false;
32381
+ readyTimeoutMs = READY_TIMEOUT_MS;
32382
+ exportFailures = 0;
32383
+ lastSaved = 0;
32384
+ lastExportBytes = 0;
32385
+ exportSeq = 0;
32386
+ // Aborted by stop(): no wait for a download or an orphan's export.
32387
+ abort = new AbortController();
32388
+ stopRequested;
32389
+ procs;
32390
+ log;
32391
+ clock;
32392
+ sleep;
32393
+ isOpen;
32394
+ post;
32395
+ readyWaiters = [];
32396
+ // The value of p, or false as soon as stop() is called.
32397
+ untilStop(p) {
32398
+ return Promise.race([p, this.stopRequested]);
32399
+ }
32400
+ get ready() {
32401
+ return this.isReady;
32402
+ }
32403
+ // Resolves true when the emulators answer, false when they stopped
32404
+ // before that or after timeoutMs.
32405
+ waitReady(timeoutMs) {
32406
+ if (this.isReady) return Promise.resolve(true);
32407
+ return new Promise((res) => {
32408
+ const t = setTimeout(() => res(false), timeoutMs);
32409
+ t.unref?.();
32410
+ this.readyWaiters.push((ok) => {
32411
+ clearTimeout(t);
32412
+ res(ok);
32122
32413
  });
32123
- await (0, import_promises2.pipeline)(req, (0, import_node_fs2.createWriteStream)(tmp));
32124
- await (0, import_promises.writeFile)(meta, JSON.stringify({ contentType: type2 }));
32125
- await (0, import_promises.rename)(tmp, file);
32126
- res.writeHead(200, { "cache-control": "no-store" });
32127
- return res.end();
32414
+ });
32415
+ }
32416
+ setReady(ok) {
32417
+ this.isReady = ok;
32418
+ const w = this.readyWaiters;
32419
+ this.readyWaiters = [];
32420
+ for (const f of w) f(ok);
32421
+ }
32422
+ get pidFile() {
32423
+ return (0, import_node_path2.join)(this.o.dir, "pids.json");
32424
+ }
32425
+ // Never throws: a missing folder (rm -rf .builders-dev) must not stop the
32426
+ // tunnel.
32427
+ writePids(pids) {
32428
+ try {
32429
+ const procs = [];
32430
+ for (const pid of new Set(pids)) {
32431
+ if (!Number.isInteger(pid) || pid <= 1) continue;
32432
+ const start = this.procs.startTime(pid);
32433
+ if (start !== null) procs.push({ pid, start });
32434
+ }
32435
+ (0, import_node_fs2.mkdirSync)(this.o.dir, { recursive: true });
32436
+ const noExport = this.probing || !this.isReady;
32437
+ const file = { boot: this.procs.bootId(), hub: this.o.ports.hub, procs, ...noExport ? { noExport: true } : {} };
32438
+ (0, import_node_fs2.writeFileSync)(this.pidFile, `${JSON.stringify(file)}
32439
+ `);
32440
+ } catch (e) {
32441
+ this.log(`The list of emulator processes could not be saved: ${message(e)}`);
32128
32442
  }
32129
- let size;
32443
+ }
32444
+ readPids() {
32130
32445
  try {
32131
- size = (await (0, import_promises.stat)(file)).size;
32446
+ const p = JSON.parse((0, import_node_fs2.readFileSync)(this.pidFile, "utf8"));
32447
+ return Array.isArray(p.procs) ? p : null;
32132
32448
  } catch {
32133
- return fail(res, 404, "No such file.");
32449
+ return null;
32134
32450
  }
32135
- let type = "";
32451
+ }
32452
+ // The processes of the pid file that still run: same boot, same start
32453
+ // time, and an emulator's command line. Another process that got the same
32454
+ // pid does not count.
32455
+ running(p) {
32456
+ if (!p || p.boot !== this.procs.bootId()) return [];
32457
+ return p.procs.filter((x) => this.procs.startTime(x.pid) === x.start && this.procs.isEmulator(x.pid)).map((x) => x.pid);
32458
+ }
32459
+ removePids() {
32460
+ (0, import_node_fs2.rmSync)(this.pidFile, { force: true });
32461
+ }
32462
+ // Saves the data of emulators that an earlier run left behind (if their
32463
+ // hub still answers) and stops them. Also removes the temporary exports
32464
+ // that firebase-tools left in config/.
32465
+ async cleanUp() {
32136
32466
  try {
32137
- type = JSON.parse(await (0, import_promises.readFile)(meta, "utf8")).contentType ?? "";
32467
+ for (const n of (0, import_node_fs2.readdirSync)((0, import_node_path2.join)(this.o.dir, "config"))) {
32468
+ if (n.startsWith("firebase-export-")) (0, import_node_fs2.rmSync)((0, import_node_path2.join)(this.o.dir, "config", n), { recursive: true, force: true });
32469
+ }
32138
32470
  } catch {
32139
32471
  }
32140
- const inline = INLINE.test(type.split(";")[0].trim().toLowerCase());
32141
- res.writeHead(200, {
32142
- "content-type": type || "application/octet-stream",
32143
- "content-length": String(size),
32144
- "cache-control": "private, no-store",
32145
- "x-content-type-options": "nosniff",
32146
- ...inline ? {} : { "content-disposition": "attachment", "content-security-policy": "sandbox; default-src 'none'" }
32472
+ removeTmpExports(this.o.dir);
32473
+ const old = this.readPids();
32474
+ const alive = this.running(old);
32475
+ if (alive.length) {
32476
+ const save = old && Number.isInteger(old.hub) && !old.noExport && await this.untilStop((this.o.hubAnswers ?? hubAnswersHttp)(old.hub));
32477
+ if (this.stopped) return;
32478
+ const saved = save && await this.untilStop(this.exportTo(old.hub, this.exportTimeoutMs(), () => this.stopped));
32479
+ if (this.stopped) return;
32480
+ if (saved) this.log("Saved the test data of emulators that were still running.");
32481
+ for (const p of alive) this.procs.kill(p, "SIGKILL");
32482
+ this.log(`Stopped ${alive.length} emulator process(es) of an earlier run.`);
32483
+ for (let i = 0; i < 20 && alive.some((p) => this.procs.isEmulator(p)); i++) await this.sleep(100);
32484
+ }
32485
+ this.removePids();
32486
+ }
32487
+ // Exports into a new export-tmp-<n>/ through the hub, then swaps that
32488
+ // folder in. With abandoned() true at the end (stop() came), it keeps
32489
+ // nothing.
32490
+ async exportTo(hub, timeoutMs, abandoned = () => false) {
32491
+ const name = `export-tmp-${this.clock()}-${++this.exportSeq}`;
32492
+ const tmp = (0, import_node_path2.join)(this.o.dir, name);
32493
+ const status = await this.post(`http://127.0.0.1:${hub}/_admin/export`, { path: tmp, initiatedBy: "builders-cli" }, timeoutMs);
32494
+ if (status !== 200 || !(0, import_node_fs2.existsSync)((0, import_node_path2.join)(tmp, METADATA)) || abandoned()) {
32495
+ (0, import_node_fs2.rmSync)(tmp, { recursive: true, force: true });
32496
+ return false;
32497
+ }
32498
+ swapExport(this.o.dir, name);
32499
+ return true;
32500
+ }
32501
+ // The time limit of a periodic export: longer for more data.
32502
+ exportTimeoutMs() {
32503
+ return Math.min(EXPORT_TIMEOUT_MS + megabytes(this.lastExportBytes) * EXPORT_MS_PER_MB, EXPORT_TIMEOUT_MAX_MS);
32504
+ }
32505
+ // Saves the test data now. One export at a time.
32506
+ exportNow(timeoutMs = this.exportTimeoutMs()) {
32507
+ if (!this.isReady) return Promise.resolve(false);
32508
+ if (this.exporting) return this.exporting;
32509
+ const p = this.exportTo(this.o.ports.hub, timeoutMs).catch((e) => {
32510
+ this.log(`The test data could not be saved: ${message(e)}`);
32511
+ return false;
32512
+ }).then((ok) => {
32513
+ if (ok) {
32514
+ this.exportFailures = 0;
32515
+ this.lastSaved = this.clock();
32516
+ this.lastExportBytes = dirSize((0, import_node_path2.join)(this.o.dir, "export"));
32517
+ } else {
32518
+ this.exportFailures++;
32519
+ this.log(`The test data could not be saved (${Math.round(timeoutMs / 1e3)} s limit); the emulators keep it in memory.`);
32520
+ if (this.exportFailures >= EXPORT_FAILURES_LOG) {
32521
+ const since = this.lastSaved ? `${Math.round((this.clock() - this.lastSaved) / 6e4)} minutes ago` : "not since the start";
32522
+ this.log(
32523
+ `The test data was not saved ${this.exportFailures} times in a row (last save: ${since}). If the dev preview stops now, the changes since then are lost. Tell the user in plain words.`
32524
+ );
32525
+ }
32526
+ }
32527
+ return ok;
32528
+ }).finally(() => {
32529
+ this.exporting = null;
32147
32530
  });
32148
- if (method === "HEAD") return res.end();
32149
- await (0, import_promises2.pipeline)((0, import_node_fs2.createReadStream)(file), res);
32531
+ this.exporting = p;
32532
+ return p;
32150
32533
  }
32151
- await new Promise((resolve2) => server.listen(0, "127.0.0.1", resolve2));
32152
- const addr = server.address();
32153
- if (!addr || typeof addr === "string") throw new Error("The file server did not start.");
32154
- return { port: addr.port, close: () => server.close() };
32155
- }
32534
+ writeConfig() {
32535
+ const cfg = (0, import_node_path2.join)(this.o.dir, "config");
32536
+ (0, import_node_fs2.mkdirSync)(cfg, { recursive: true });
32537
+ (0, import_node_fs2.writeFileSync)((0, import_node_path2.join)(cfg, "firebase.json"), `${JSON.stringify(firebaseConfig(this.o.ports), null, 2)}
32538
+ `);
32539
+ (0, import_node_fs2.writeFileSync)((0, import_node_path2.join)(cfg, "firestore.rules"), FIRESTORE_RULES);
32540
+ (0, import_node_fs2.writeFileSync)((0, import_node_path2.join)(cfg, "storage.rules"), STORAGE_RULES);
32541
+ return cfg;
32542
+ }
32543
+ args(from = importDir(this.o.dir)) {
32544
+ return [
32545
+ "emulators:start",
32546
+ "--project",
32547
+ EMULATOR_PROJECT,
32548
+ "--only",
32549
+ "firestore,storage",
32550
+ "--config",
32551
+ (0, import_node_path2.join)(this.o.dir, "config", "firebase.json"),
32552
+ ...from ? ["--import", from] : []
32553
+ ];
32554
+ }
32555
+ // Puts aside an export that the emulators could not import, so that they
32556
+ // start empty.
32557
+ putAsideImport(from) {
32558
+ const to = (0, import_node_path2.join)(this.o.dir, `export-bad-${this.clock()}`);
32559
+ try {
32560
+ (0, import_node_fs2.renameSync)(from, to);
32561
+ this.log(
32562
+ `The emulators could not load the saved test data: ${BAD_IMPORT_TRIES} starts with it failed, a start without it worked, and one more start with it failed. The old data is in ${to}. Tell the user in plain words that the test data of the dev preview starts empty.`
32563
+ );
32564
+ } catch (e) {
32565
+ this.log(`The saved test data could not be put aside: ${message(e)}`);
32566
+ }
32567
+ }
32568
+ // Runs until stop(). Starts the emulators again when they stop.
32569
+ //
32570
+ // A broken export: after BAD_IMPORT_TRIES failed starts with the import
32571
+ // (before ready), one test start without it ("probe", stopped as soon as
32572
+ // it is ready, with no export). When the probe works, one more start
32573
+ // with the import ("confirm"). Only when that fails too, the export goes
32574
+ // to export-bad-<ms>/. Any other failure (a port, the network) fails the
32575
+ // probe too, and the export stays.
32576
+ async run() {
32577
+ let delay = FIRST_WAIT_MS2;
32578
+ let badImports = 0;
32579
+ let phase = "normal";
32580
+ let setupDone = false;
32581
+ this.lastExportBytes = dirSize((0, import_node_path2.join)(this.o.dir, "export"));
32582
+ while (!this.stopped) {
32583
+ const started = this.clock();
32584
+ let how;
32585
+ let ready = false;
32586
+ let from = null;
32587
+ let ranPhase = phase;
32588
+ try {
32589
+ (0, import_node_fs2.mkdirSync)(this.o.dir, { recursive: true });
32590
+ await this.cleanUp();
32591
+ if (this.stopped) break;
32592
+ const command = await this.untilStop((this.o.command ?? ((sig) => firebaseCommand(void 0, sig)))(this.abort.signal));
32593
+ if (this.stopped || !command) break;
32594
+ const [cmd, pre] = command;
32595
+ const cwd = this.writeConfig();
32596
+ if (!setupDone) {
32597
+ await this.untilStop((this.o.setup ?? setupEmulators)(cmd, pre, cwd, this.abort.signal));
32598
+ if (this.stopped) break;
32599
+ setupDone = true;
32600
+ }
32601
+ from = importDir(this.o.dir);
32602
+ if (!from) phase = "normal";
32603
+ else if (phase === "normal" && badImports >= BAD_IMPORT_TRIES) phase = "probe";
32604
+ ranPhase = phase;
32605
+ this.probing = phase === "probe";
32606
+ this.readyTimeoutMs = (this.o.readyTimeoutMs ?? READY_TIMEOUT_MS) + (from && !this.probing ? megabytes(dirSize(from)) * IMPORT_MS_PER_MB : 0);
32607
+ const r = await this.once(cmd, [...pre, ...this.args(this.probing ? null : from)], cwd);
32608
+ how = r.how;
32609
+ ready = r.ready;
32610
+ } catch (e) {
32611
+ how = message(e);
32612
+ }
32613
+ this.probing = false;
32614
+ if (this.stopped) break;
32615
+ if (ranPhase === "probe") {
32616
+ badImports = 0;
32617
+ if (ready && await this.portsClosed()) {
32618
+ phase = "confirm";
32619
+ this.log("The emulators start without the saved test data, but not with it. They try once more with it.");
32620
+ continue;
32621
+ }
32622
+ if (ready) this.log("The ports of the test start are still in use; the saved test data stays.");
32623
+ phase = "normal";
32624
+ } else if (ranPhase === "confirm") {
32625
+ if (!ready && from) this.putAsideImport(from);
32626
+ phase = "normal";
32627
+ badImports = 0;
32628
+ } else if (ready) badImports = 0;
32629
+ else if (from) badImports++;
32630
+ if (this.clock() - started >= STABLE_MS2) delay = FIRST_WAIT_MS2;
32631
+ this.log(`The emulators stopped (${how}). They start again in ${Math.round(delay / 1e3)} s.`);
32632
+ await Promise.race([this.sleep(delay), new Promise((r) => this.wake = r)]);
32633
+ this.wake = null;
32634
+ delay = Math.min(delay * 2, MAX_WAIT_MS2);
32635
+ }
32636
+ }
32637
+ once(cmd, args, cwd) {
32638
+ const spawn2 = this.o.spawn ?? ((c, a, d) => (
32639
+ // Its own process group: a signal to the tunnel's group does not
32640
+ // reach it (a second SIGINT would stop it at once). stop() stops it.
32641
+ (0, import_node_child_process2.spawn)(c, a, { cwd: d, detached: true, stdio: ["ignore", "inherit", "inherit"], env: { ...process.env, NO_UPDATE_NOTIFIER: "1" } })
32642
+ ));
32643
+ let endExited = () => {
32644
+ };
32645
+ this.exited = new Promise((r) => endExited = r);
32646
+ return new Promise((resolve2) => {
32647
+ let child;
32648
+ try {
32649
+ child = spawn2(cmd, args, cwd);
32650
+ } catch (e) {
32651
+ endExited();
32652
+ resolve2({ how: message(e), ready: false });
32653
+ return;
32654
+ }
32655
+ this.child = child;
32656
+ this.healthFailures = 0;
32657
+ this.probeHit = false;
32658
+ if (child.pid) this.writePids([child.pid]);
32659
+ let done = false;
32660
+ let wasReady = false;
32661
+ const finish = (how) => {
32662
+ if (done) return;
32663
+ done = true;
32664
+ wasReady = wasReady || this.isReady;
32665
+ this.child = null;
32666
+ this.stopTimer();
32667
+ this.setReady(false);
32668
+ for (const p of this.running(this.readPids())) if (p !== child.pid) this.procs.kill(p, "SIGKILL");
32669
+ this.removePids();
32670
+ endExited();
32671
+ resolve2({ how, ready: wasReady || this.probeHit });
32672
+ };
32673
+ child.once("error", (e) => finish(e.message));
32674
+ child.once("exit", (code, signal) => finish(signal ? `signal ${signal}` : `code ${code}`));
32675
+ this.watchReady(child, () => done).catch((e) => this.log(`The emulators could not be watched: ${message(e)}`));
32676
+ });
32677
+ }
32678
+ // Waits until no emulator port answers (at most about 15 s).
32679
+ async portsClosed() {
32680
+ const p = this.o.ports;
32681
+ for (let i = 0; i < 60 && !this.stopped; i++) {
32682
+ let open = false;
32683
+ for (const port of [p.firestore, p.firestoreWs, p.storage, p.hub, p.logging]) if (await this.isOpen(port)) open = true;
32684
+ if (!open) return true;
32685
+ await this.sleep(250);
32686
+ }
32687
+ return false;
32688
+ }
32689
+ async portsOpen() {
32690
+ const p = this.o.ports;
32691
+ return await this.isOpen(p.firestore) && await this.isOpen(p.storage) && await this.isOpen(p.hub);
32692
+ }
32693
+ async watchReady(child, ended) {
32694
+ const deadline = this.clock() + this.readyTimeoutMs;
32695
+ for (let round = 0; !ended() && !this.stopped; round++) {
32696
+ if (round % 4 === 0) this.trackPids(child);
32697
+ if (await this.portsOpen()) {
32698
+ if (ended() || this.stopped) return;
32699
+ this.trackPids(child);
32700
+ if (this.probing) {
32701
+ this.probeHit = true;
32702
+ child.kill("SIGKILL");
32703
+ return;
32704
+ }
32705
+ this.setReady(true);
32706
+ this.trackPids(child);
32707
+ this.log("The emulators are ready (Firestore, Storage).");
32708
+ const every = this.o.exportEveryMs ?? EXPORT_EVERY_MS;
32709
+ this.timer = setInterval(() => void this.tick(child), every);
32710
+ this.timer.unref?.();
32711
+ return;
32712
+ }
32713
+ if (this.clock() > deadline) {
32714
+ this.log("The emulators did not start in time.");
32715
+ this.trackPids(child);
32716
+ child.kill("SIGKILL");
32717
+ return;
32718
+ }
32719
+ await this.sleep(250);
32720
+ }
32721
+ }
32722
+ // Every 30 s: the health check, the pids and the export. Never throws.
32723
+ async tick(child) {
32724
+ try {
32725
+ if (this.stopped || this.child !== child) return;
32726
+ if (!await this.portsOpen()) {
32727
+ if (++this.healthFailures >= HEALTH_FAILURES) {
32728
+ this.log("An emulator does not answer. The emulators start again.");
32729
+ this.trackPids(child);
32730
+ child.kill("SIGKILL");
32731
+ }
32732
+ return;
32733
+ }
32734
+ this.healthFailures = 0;
32735
+ this.trackPids(child);
32736
+ await this.exportNow();
32737
+ } catch (e) {
32738
+ this.log(`The check of the emulators failed: ${message(e)}`);
32739
+ }
32740
+ }
32741
+ trackPids(child) {
32742
+ if (!child.pid) return;
32743
+ this.writePids([child.pid, ...this.running(this.readPids()), ...this.procs.descendants(child.pid)]);
32744
+ }
32745
+ stopTimer() {
32746
+ if (this.timer) clearInterval(this.timer);
32747
+ this.timer = null;
32748
+ }
32749
+ // Saves the test data, then stops the emulators. Takes at most about
32750
+ // 7 s: the preview gives the tunnel 10 s before it kills it.
32751
+ stop() {
32752
+ this.stopping ??= this.doStop();
32753
+ return this.stopping;
32754
+ }
32755
+ async doStop() {
32756
+ this.stopped = true;
32757
+ this.abort.abort();
32758
+ this.wake?.();
32759
+ this.stopTimer();
32760
+ const child = this.child;
32761
+ if (!child) {
32762
+ this.setReady(false);
32763
+ return;
32764
+ }
32765
+ const budget = this.sleep(STOP_EXPORT_MS);
32766
+ await Promise.race([
32767
+ (async () => {
32768
+ if (this.exporting) await this.exporting;
32769
+ if (this.isReady) await this.exportNow(STOP_EXPORT_MS);
32770
+ })(),
32771
+ budget
32772
+ ]);
32773
+ this.trackPids(child);
32774
+ const pids = this.running(this.readPids());
32775
+ child.kill("SIGINT");
32776
+ const ended = await Promise.race([this.exited.then(() => true), this.sleep(this.o.stopWaitMs ?? STOP_WAIT_MS).then(() => false)]);
32777
+ if (!ended) child.kill("SIGKILL");
32778
+ for (const p of pids) if (p !== child.pid && this.procs.isEmulator(p)) this.procs.kill(p, "SIGKILL");
32779
+ this.removePids();
32780
+ }
32781
+ };
32156
32782
 
32157
32783
  // src/awake.ts
32158
32784
  var import_node_fs3 = require("node:fs");
32159
- var import_node_os = require("node:os");
32785
+ var import_node_os2 = require("node:os");
32160
32786
  var import_node_path3 = require("node:path");
32161
32787
  var DEFAULT_IDLE_MIN = 15;
32162
32788
  var DEFAULT_MAX_MIN = 25;
@@ -32235,7 +32861,7 @@ function parseAwakeArgs(rest) {
32235
32861
  i++;
32236
32862
  }
32237
32863
  const tokenFile = o["token-file"];
32238
- if (!tokenFile || !tokenFile.endsWith(".tunnel") || (0, import_node_path3.dirname)(tokenFile) !== (0, import_node_path3.join)((0, import_node_os.homedir)(), ".builders")) throw new Error("Give --token-file: the .tunnel file in ~/.builders from open_app.");
32864
+ if (!tokenFile || !tokenFile.endsWith(".tunnel") || (0, import_node_path3.dirname)(tokenFile) !== (0, import_node_path3.join)((0, import_node_os2.homedir)(), ".builders")) throw new Error("Give --token-file: the .tunnel file in ~/.builders from open_app.");
32239
32865
  const minutes = (k, d, max) => {
32240
32866
  const n = o[k] === void 0 ? d : Number(o[k]);
32241
32867
  if (!Number.isFinite(n) || n <= 0 || n > max) throw new Error(`--${k} must be more than 0 and at most ${max}.`);
@@ -32321,12 +32947,12 @@ async function awakeCommand(rest) {
32321
32947
  }
32322
32948
 
32323
32949
  // src/preview.ts
32324
- var import_node_child_process2 = require("node:child_process");
32950
+ var import_node_child_process3 = require("node:child_process");
32325
32951
  var import_node_fs4 = require("node:fs");
32326
- var import_node_os2 = require("node:os");
32952
+ var import_node_os3 = require("node:os");
32327
32953
  var import_node_path4 = require("node:path");
32328
32954
  var TOKEN_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
32329
- var CLI_VERSION = true ? "0.2.2" : "dev";
32955
+ var CLI_VERSION = true ? "0.2.3" : "dev";
32330
32956
  function olderVersion(a, b) {
32331
32957
  const parse = (v) => /^\d+\.\d+\.\d+$/.test(v) ? v.split(".").map(Number) : null;
32332
32958
  const x = parse(a);
@@ -32336,7 +32962,7 @@ function olderVersion(a, b) {
32336
32962
  for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] < y[i];
32337
32963
  return false;
32338
32964
  }
32339
- var buildersDir = () => (0, import_node_path4.join)((0, import_node_os2.homedir)(), ".builders");
32965
+ var buildersDir = () => (0, import_node_path4.join)((0, import_node_os3.homedir)(), ".builders");
32340
32966
  function value(rest, i, name) {
32341
32967
  const v = rest[i + 1];
32342
32968
  if (v === void 0) throw new Error(`--${name} needs a value.`);
@@ -32396,7 +33022,7 @@ function checkRecord(r, host, now = Date.now()) {
32396
33022
  if (r.addOns !== void 0 && !/^[a-z,-]*$/.test(r.addOns)) return "The add-ons are not valid.";
32397
33023
  return null;
32398
33024
  }
32399
- var logFile = (r) => (0, import_node_path4.join)((0, import_node_os2.tmpdir)(), `builders-${(0, import_node_path4.basename)(r.dir)}-preview.log`);
33025
+ var logFile = (r) => (0, import_node_path4.join)((0, import_node_os3.tmpdir)(), `builders-${(0, import_node_path4.basename)(r.dir)}-preview.log`);
32400
33026
  var recordFile = (r) => r.tokenFile.replace(/\.tunnel$/, ".preview.json");
32401
33027
  var pidFile2 = (r) => r.tokenFile.replace(/\.tunnel$/, ".pid");
32402
33028
  function runningPid(r) {
@@ -32440,11 +33066,11 @@ async function startPreview(r, o = {}) {
32440
33066
  }
32441
33067
  };
32442
33068
  group("SIGTERM");
32443
- for (let i = 0; i < 50 && runningPid(r); i++) await new Promise((res) => setTimeout(res, 100));
33069
+ for (let i = 0; i < 100 && runningPid(r); i++) await new Promise((res) => setTimeout(res, 100));
32444
33070
  group("SIGKILL");
32445
33071
  }
32446
33072
  const log = (0, import_node_fs4.openSync)(logFile(r), "a");
32447
- const child = (0, import_node_child_process2.spawn)(process.execPath, [o.script ?? process.argv[1], "tunnel", "--dev", "--port", String(r.port)], {
33073
+ const child = (0, import_node_child_process3.spawn)(process.execPath, [o.script ?? process.argv[1], "tunnel", "--dev", "--port", String(r.port)], {
32448
33074
  cwd: r.dir,
32449
33075
  detached: true,
32450
33076
  stdio: ["ignore", log, log],
@@ -32471,6 +33097,7 @@ async function previewCommand(rest, cwd = process.cwd()) {
32471
33097
  `, { mode: 384 });
32472
33098
  const did = await startPreview(record, { restart });
32473
33099
  console.error(did === "running" ? "The dev preview runs." : `The dev preview starts. Log: ${logFile(record)}`);
33100
+ console.error(javaProblem() ?? "The test data is in the Firebase emulators (.builders-dev/emulators/), saved every 30 s. The first start takes about 30 s.");
32474
33101
  return 0;
32475
33102
  }
32476
33103
  async function resumeCommand(rest) {
@@ -32502,7 +33129,8 @@ var USAGE = `Usage: builders-cli tunnel --port <port> [--dev] [--url <tunnel url
32502
33129
  builders-cli resume --host <tenant host>
32503
33130
  builders-cli awake --token-file <file> [--again] [--idle-minutes 15] [--max-minutes 25]
32504
33131
 
32505
- --dev also run the app's dev server (pnpm dev --port <port>) in this folder, and start it again when it stops
33132
+ --dev also run the app's dev server (pnpm dev --port <port>) in this folder, and start it again when it stops;
33133
+ with the Firestore and Storage emulators for the test data (needs Java 21)
32506
33134
 
32507
33135
  Environment:
32508
33136
  BUILDERS_TUNNEL_TOKEN_FILE a file with the tunnel token (or --token-file)
@@ -32596,32 +33224,39 @@ async function main(argv = process.argv.slice(2), env = process.env) {
32596
33224
  return o.token;
32597
33225
  }
32598
33226
  } : void 0;
32599
- let files = null;
32600
33227
  let devEnv = {};
33228
+ let emulators = null;
32601
33229
  if (o.dev) {
32602
33230
  const dataDir = devDataDir(process.cwd());
32603
- const secret = (0, import_node_crypto2.randomBytes)(32).toString("hex");
32604
- files = await startDevFiles({ dataDir, secret });
32605
- devEnv = { [DEV_DATA_DIR_ENV]: dataDir, [DEV_FILES_SECRET_ENV]: secret };
33231
+ const problem = javaProblem();
33232
+ if (problem) {
33233
+ console.error(problem);
33234
+ devEnv[EMULATORS_ERROR_ENV] = problem;
33235
+ } else {
33236
+ const ports = await freePorts();
33237
+ emulators = new Emulators({ dir: (0, import_node_path5.join)(dataDir, "emulators"), ports });
33238
+ devEnv = emulatorEnv(ports, { storage: storageOn(env.BUILDERS_DEV_ADDONS) });
33239
+ }
32606
33240
  }
32607
33241
  const client = new TunnelClient({
32608
33242
  ...o,
32609
33243
  readToken,
32610
- ...files ? { filesPort: files.port } : {},
32611
33244
  ...o.dev && file?.endsWith(".tunnel") ? { onRequest: useMarker(activityMarker(file)) } : {}
32612
33245
  });
32613
33246
  const server = o.dev ? new DevServer({ port: o.port, env: devEnv }) : null;
33247
+ const emulating = emulators?.run();
32614
33248
  const running = server?.run();
32615
33249
  const stop = () => {
32616
33250
  client.stop();
32617
33251
  server?.stop();
33252
+ void emulators?.stop();
32618
33253
  };
32619
33254
  process.on("SIGINT", stop);
32620
33255
  process.on("SIGTERM", stop);
32621
33256
  const { code } = await client.run();
32622
33257
  server?.stop();
32623
- await running;
32624
- files?.close();
33258
+ await emulators?.stop();
33259
+ await Promise.all([running, emulating]);
32625
33260
  return code;
32626
33261
  }
32627
33262