@hot-updater/firebase 1.0.0-rc.0 → 1.0.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19,7 +19,7 @@ import { finished } from "node:stream/promises";
19
19
  import { Duplex, PassThrough, Readable, Transform, Writable, getDefaultHighWaterMark } from "node:stream";
20
20
  import { Buffer as Buffer$1 } from "node:buffer";
21
21
  import { applicationDefault, cert, deleteApp, getApp, getApps, initializeApp } from "firebase-admin/app";
22
- import { createDatabasePlugin, isDatabaseMetadataObject } from "@hot-updater/plugin-core";
22
+ import { compareInsightsText, createDatabasePlugin, isDatabaseMetadataObject } from "@hot-updater/plugin-core";
23
23
  import { createDatabasePluginAdapter } from "@hot-updater/plugin-core/internal";
24
24
  import { getFirestore } from "firebase-admin/firestore";
25
25
  import fs$1 from "fs/promises";
@@ -31,7 +31,7 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
31
31
  var __getOwnPropNames = Object.getOwnPropertyNames;
32
32
  var __getProtoOf = Object.getPrototypeOf;
33
33
  var __hasOwnProp = Object.prototype.hasOwnProperty;
34
- var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
34
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
35
35
  var __copyProps = (to, from, except, desc) => {
36
36
  if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
37
37
  key = keys[i];
@@ -42,11 +42,11 @@ var __copyProps = (to, from, except, desc) => {
42
42
  }
43
43
  return to;
44
44
  };
45
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
45
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
46
46
  value: mod,
47
47
  enumerable: true
48
48
  }) : target, mod));
49
- var __require = /* @__PURE__ */ createRequire(import.meta.url);
49
+ var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
50
50
  //#endregion
51
51
  //#region ../../node_modules/.pnpm/es-toolkit@1.47.0/node_modules/es-toolkit/dist/_internal/compareValues.mjs
52
52
  function compareValues(a, b, order) {
@@ -651,7 +651,8 @@ const parseTemplate = ({ templates, expressions, tokens, index, template }) => {
651
651
  const newTokens = concatTokens(tokens, nextTokens, leadingWhitespaces);
652
652
  if (index === expressions.length) return newTokens;
653
653
  const expression = expressions[index];
654
- return concatTokens(newTokens, Array.isArray(expression) ? expression.map((expression) => parseExpression(expression)) : [parseExpression(expression)], trailingWhitespaces);
654
+ const expressionTokens = Array.isArray(expression) ? expression.map((expression) => parseExpression(expression)) : [parseExpression(expression)];
655
+ return concatTokens(newTokens, expressionTokens, trailingWhitespaces);
655
656
  };
656
657
  const splitByWhitespaces = (template, rawTemplate) => {
657
658
  if (rawTemplate.length === 0) return {
@@ -684,7 +685,7 @@ const splitByWhitespaces = (template, rawTemplate) => {
684
685
  trailingWhitespaces
685
686
  };
686
687
  };
687
- const DELIMITERS = new Set([
688
+ const DELIMITERS = /* @__PURE__ */ new Set([
688
689
  " ",
689
690
  " ",
690
691
  "\r",
@@ -736,7 +737,8 @@ const normalizeFdSpecificOptions = (options) => {
736
737
  };
737
738
  const normalizeFdSpecificOption = (options, optionName) => {
738
739
  const optionBaseArray = Array.from({ length: getStdioLength(options) + 1 });
739
- return addDefaultValue$1(normalizeFdSpecificValue(options[optionName], optionBaseArray, optionName), optionName);
740
+ const optionArray = normalizeFdSpecificValue(options[optionName], optionBaseArray, optionName);
741
+ return addDefaultValue$1(optionArray, optionName);
740
742
  };
741
743
  const getStdioLength = ({ stdio }) => Array.isArray(stdio) ? Math.max(stdio.length, STANDARD_STREAMS_ALIASES.length) : STANDARD_STREAMS_ALIASES.length;
742
744
  const normalizeFdSpecificValue = (optionValue, optionArray, optionName) => isPlainObject(optionValue) ? normalizeOptionObject(optionValue, optionArray, optionName) : optionArray.fill(optionValue);
@@ -769,7 +771,7 @@ const addDefaultValue$1 = (optionArray, optionName) => optionArray.map((optionVa
769
771
  const DEFAULT_OPTIONS = {
770
772
  lines: false,
771
773
  buffer: true,
772
- maxBuffer: 1e3 * 1e3 * 100,
774
+ maxBuffer: 1e8,
773
775
  verbose: debuglog("execa").enabled ? "full" : "none",
774
776
  stripFinalNewline: true
775
777
  };
@@ -817,7 +819,7 @@ const escapeControlCharacter = (character) => {
817
819
  };
818
820
  const getSpecialCharRegExp = () => {
819
821
  try {
820
- return /* @__PURE__ */ new RegExp("\\p{Separator}|\\p{Other}", "gu");
822
+ return new RegExp("\\p{Separator}|\\p{Other}", "gu");
821
823
  } catch {
822
824
  return /[\s\u0000-\u001F\u007F-\u009F\u00AD]/g;
823
825
  }
@@ -1237,11 +1239,13 @@ const appendNewline = (printedLine) => printedLine.endsWith("\n") ? printedLine
1237
1239
  //#endregion
1238
1240
  //#region ../../node_modules/.pnpm/execa@9.5.2/node_modules/execa/lib/verbose/log.js
1239
1241
  const verboseLog = ({ type, verboseMessage, fdNumber, verboseInfo, result }) => {
1240
- const finalLines = applyVerboseOnLines(getPrintedLines(verboseMessage, getVerboseObject({
1242
+ const verboseObject = getVerboseObject({
1241
1243
  type,
1242
1244
  result,
1243
1245
  verboseInfo
1244
- })), verboseInfo, fdNumber);
1246
+ });
1247
+ const printedLines = getPrintedLines(verboseMessage, verboseObject);
1248
+ const finalLines = applyVerboseOnLines(printedLines, verboseInfo, fdNumber);
1245
1249
  if (finalLines !== "") console.warn(finalLines.slice(0, -1));
1246
1250
  };
1247
1251
  const getVerboseObject = ({ type, result, verboseInfo: { escapedCommand, commandId, rawOptions: { piped = false, ...options } } }) => ({
@@ -1264,7 +1268,8 @@ const getPrintedLine = (verboseObject) => {
1264
1268
  };
1265
1269
  };
1266
1270
  const serializeVerboseMessage = (message) => {
1267
- return escapeLines(typeof message === "string" ? message : inspect(message)).replaceAll(" ", " ".repeat(TAB_SIZE));
1271
+ const messageString = typeof message === "string" ? message : inspect(message);
1272
+ return escapeLines(messageString).replaceAll(" ", " ".repeat(TAB_SIZE));
1268
1273
  };
1269
1274
  const TAB_SIZE = 2;
1270
1275
  //#endregion
@@ -1309,7 +1314,8 @@ const getDurationMs = (startTime) => Number(hrtime.bigint() - startTime) / 1e6;
1309
1314
  const handleCommand = (filePath, rawArguments, rawOptions) => {
1310
1315
  const startTime = getStartTime();
1311
1316
  const { command, escapedCommand } = joinCommand(filePath, rawArguments);
1312
- const verboseInfo = getVerboseInfo(normalizeFdSpecificOption(rawOptions, "verbose"), escapedCommand, { ...rawOptions });
1317
+ const verbose = normalizeFdSpecificOption(rawOptions, "verbose");
1318
+ const verboseInfo = getVerboseInfo(verbose, escapedCommand, { ...rawOptions });
1313
1319
  logCommand(escapedCommand, verboseInfo);
1314
1320
  return {
1315
1321
  command,
@@ -1430,7 +1436,8 @@ var require_which = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1430
1436
  const getNotFoundError = (cmd) => Object.assign(/* @__PURE__ */ new Error(`not found: ${cmd}`), { code: "ENOENT" });
1431
1437
  const getPathInfo = (cmd, opt) => {
1432
1438
  const colon = opt.colon || COLON;
1433
- const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [""] : [...isWindows ? [process.cwd()] : [], ...(opt.path || process.env.PATH || "").split(colon)];
1439
+ const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [""] : [...isWindows ? [process.cwd()] : [], ...(opt.path || process.env.PATH ||
1440
+ /* istanbul ignore next: very unusual */ "").split(colon)];
1434
1441
  const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
1435
1442
  const pathExt = isWindows ? pathExtExe.split(colon) : [""];
1436
1443
  if (isWindows) {
@@ -1455,14 +1462,17 @@ var require_which = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1455
1462
  const ppRaw = pathEnv[i];
1456
1463
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
1457
1464
  const pCmd = path$4.join(pathPart, cmd);
1458
- resolve(subStep(!pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd, i, 0));
1465
+ const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
1466
+ resolve(subStep(p, i, 0));
1459
1467
  });
1460
1468
  const subStep = (p, i, ii) => new Promise((resolve, reject) => {
1461
1469
  if (ii === pathExt.length) return resolve(step(i + 1));
1462
1470
  const ext = pathExt[ii];
1463
1471
  isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
1464
- if (!er && is) if (opt.all) found.push(p + ext);
1465
- else return resolve(p + ext);
1472
+ if (!er && is) {
1473
+ if (opt.all) found.push(p + ext);
1474
+ else return resolve(p + ext);
1475
+ }
1466
1476
  return resolve(subStep(p, i, ii + 1));
1467
1477
  });
1468
1478
  });
@@ -1480,8 +1490,10 @@ var require_which = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1480
1490
  for (let j = 0; j < pathExt.length; j++) {
1481
1491
  const cur = p + pathExt[j];
1482
1492
  try {
1483
- if (isexe.sync(cur, { pathExt: pathExtExe })) if (opt.all) found.push(cur);
1484
- else return cur;
1493
+ if (isexe.sync(cur, { pathExt: pathExtExe })) {
1494
+ if (opt.all) found.push(cur);
1495
+ else return cur;
1496
+ }
1485
1497
  } catch (ex) {}
1486
1498
  }
1487
1499
  }
@@ -2172,7 +2184,7 @@ const normalizeForceKillAfterDelay = (forceKillAfterDelay) => {
2172
2184
  if (!Number.isFinite(forceKillAfterDelay) || forceKillAfterDelay < 0) throw new TypeError(`Expected the \`forceKillAfterDelay\` option to be a non-negative integer, got \`${forceKillAfterDelay}\` (${typeof forceKillAfterDelay})`);
2173
2185
  return forceKillAfterDelay;
2174
2186
  };
2175
- const DEFAULT_FORCE_KILL_TIMEOUT = 1e3 * 5;
2187
+ const DEFAULT_FORCE_KILL_TIMEOUT = 5e3;
2176
2188
  const subprocessKill = ({ kill, options: { forceKillAfterDelay, killSignal }, onInternalError, context, controller }, signalOrError, errorArgument) => {
2177
2189
  const { signal, error } = parseKillArguments(signalOrError, errorArgument, killSignal);
2178
2190
  emitKillError(error, onInternalError);
@@ -2274,7 +2286,7 @@ const handleSerializationError = ({ error, methodName, isSubprocess, message })
2274
2286
  if (isSerializationError(error)) throw new Error(`${getMethodName(methodName, isSubprocess)}'s argument type is invalid: the message cannot be serialized: ${String(message)}.`, { cause: error });
2275
2287
  };
2276
2288
  const isSerializationError = ({ code, message }) => SERIALIZATION_ERROR_CODES.has(code) || SERIALIZATION_ERROR_MESSAGES.some((serializationErrorMessage) => message.includes(serializationErrorMessage));
2277
- const SERIALIZATION_ERROR_CODES = new Set(["ERR_MISSING_ARGS", "ERR_INVALID_ARG_TYPE"]);
2289
+ const SERIALIZATION_ERROR_CODES = /* @__PURE__ */ new Set(["ERR_MISSING_ARGS", "ERR_INVALID_ARG_TYPE"]);
2278
2290
  const SERIALIZATION_ERROR_MESSAGES = [
2279
2291
  "could not be cloned",
2280
2292
  "circular structure",
@@ -2484,7 +2496,8 @@ const isConnected = (anyProcess) => {
2484
2496
  //#region ../../node_modules/.pnpm/execa@9.5.2/node_modules/execa/lib/ipc/strict.js
2485
2497
  const handleSendStrict = ({ anyProcess, channel, isSubprocess, message, strict }) => {
2486
2498
  if (!strict) return message;
2487
- const hasListeners = hasMessageListeners(anyProcess, getIpcEmitter(anyProcess, channel, isSubprocess));
2499
+ const ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess);
2500
+ const hasListeners = hasMessageListeners(anyProcess, ipcEmitter);
2488
2501
  return {
2489
2502
  id: count++,
2490
2503
  type: REQUEST_TYPE,
@@ -2716,7 +2729,8 @@ const throwOnGracefulCancel = ({ subprocess, cancelSignal, gracefulCancel, force
2716
2729
  })] : [];
2717
2730
  const sendOnAbort = async ({ subprocess, cancelSignal, forceKillAfterDelay, context, controller: { signal } }) => {
2718
2731
  await onAbortedSignal(cancelSignal, signal);
2719
- await sendAbort(subprocess, getReason(cancelSignal));
2732
+ const reason = getReason(cancelSignal);
2733
+ await sendAbort(subprocess, reason);
2720
2734
  killOnTimeout({
2721
2735
  kill: subprocess.kill,
2722
2736
  forceKillAfterDelay,
@@ -2828,8 +2842,8 @@ Please rename it to ${serializeEncoding(correctEncoding)}.`);
2828
2842
  throw new TypeError(`Invalid option \`encoding: ${serializeEncoding(encoding)}\`.
2829
2843
  Please rename it to one of: ${correctEncodings}.`);
2830
2844
  };
2831
- const TEXT_ENCODINGS = new Set(["utf8", "utf16le"]);
2832
- const BINARY_ENCODINGS = new Set([
2845
+ const TEXT_ENCODINGS = /* @__PURE__ */ new Set(["utf8", "utf16le"]);
2846
+ const BINARY_ENCODINGS = /* @__PURE__ */ new Set([
2833
2847
  "buffer",
2834
2848
  "hex",
2835
2849
  "base64",
@@ -2837,7 +2851,7 @@ const BINARY_ENCODINGS = new Set([
2837
2851
  "latin1",
2838
2852
  "ascii"
2839
2853
  ]);
2840
- const ENCODINGS = new Set([...TEXT_ENCODINGS, ...BINARY_ENCODINGS]);
2854
+ const ENCODINGS = /* @__PURE__ */ new Set([...TEXT_ENCODINGS, ...BINARY_ENCODINGS]);
2841
2855
  const getCorrectEncoding = (encoding) => {
2842
2856
  if (encoding === null) return "buffer";
2843
2857
  if (typeof encoding !== "string") return;
@@ -2884,7 +2898,8 @@ const normalizeOptions = (filePath, rawArguments, rawOptions) => {
2884
2898
  rawOptions.cwd = normalizeCwd(rawOptions.cwd);
2885
2899
  const [processedFile, processedArguments, processedOptions] = handleNodeOption(filePath, rawArguments, rawOptions);
2886
2900
  const { command: file, args: commandArguments, options: initialOptions } = import_cross_spawn.default._parse(processedFile, processedArguments, processedOptions);
2887
- const options = addDefaultOptions(normalizeFdSpecificOptions(initialOptions));
2901
+ const fdOptions = normalizeFdSpecificOptions(initialOptions);
2902
+ const options = addDefaultOptions(fdOptions);
2888
2903
  validateTimeout(options);
2889
2904
  validateEncoding(options);
2890
2905
  validateIpcInputOption(options);
@@ -3085,14 +3100,17 @@ const getStreamContents$1 = async (stream, { init, convertChunk, getSize, trunca
3085
3100
  const state = init();
3086
3101
  state.length = 0;
3087
3102
  try {
3088
- for await (const chunk of asyncIterable) appendChunk({
3089
- convertedChunk: convertChunk[getChunkType(chunk)](chunk, state),
3090
- state,
3091
- getSize,
3092
- truncateChunk,
3093
- addChunk,
3094
- maxBuffer
3095
- });
3103
+ for await (const chunk of asyncIterable) {
3104
+ const convertedChunk = convertChunk[getChunkType(chunk)](chunk, state);
3105
+ appendChunk({
3106
+ convertedChunk,
3107
+ state,
3108
+ getSize,
3109
+ truncateChunk,
3110
+ addChunk,
3111
+ maxBuffer
3112
+ });
3113
+ }
3096
3114
  appendFinalChunk({
3097
3115
  state,
3098
3116
  convertChunk,
@@ -3378,7 +3396,8 @@ const getErrorPrefix = ({ originalError, timedOut, timeout, isMaxBuffer, maxBuff
3378
3396
  const getForcefulSuffix = (isForcefullyTerminated, forceKillAfterDelay) => isForcefullyTerminated ? ` and was forcefully terminated after ${forceKillAfterDelay} milliseconds` : "";
3379
3397
  const getOriginalMessage = (originalError, cwd) => {
3380
3398
  if (originalError instanceof DiscardedError) return;
3381
- const escapedOriginalMessage = escapeLines(fixCwdError(isExecaError(originalError) ? originalError.originalMessage : String(originalError?.message ?? originalError), cwd));
3399
+ const originalMessage = isExecaError(originalError) ? originalError.originalMessage : String(originalError?.message ?? originalError);
3400
+ const escapedOriginalMessage = escapeLines(fixCwdError(originalMessage, cwd));
3382
3401
  return escapedOriginalMessage === "" ? void 0 : escapedOriginalMessage;
3383
3402
  };
3384
3403
  const serializeIpcMessage = (ipcMessage) => typeof ipcMessage === "string" ? ipcMessage : inspect(ipcMessage);
@@ -3589,26 +3608,28 @@ function prettyMilliseconds(milliseconds, options) {
3589
3608
  add(Number(parsed.hours), "hour", "h");
3590
3609
  }
3591
3610
  add(Number(parsed.minutes), "minute", "m");
3592
- if (!options.hideSeconds) if (options.separateMilliseconds || options.formatSubMilliseconds || !options.colonNotation && milliseconds < 1e3 && !options.subSecondsAsDecimals) {
3593
- const seconds = Number(parsed.seconds);
3594
- const milliseconds = Number(parsed.milliseconds);
3595
- const microseconds = Number(parsed.microseconds);
3596
- const nanoseconds = Number(parsed.nanoseconds);
3597
- add(seconds, "second", "s");
3598
- if (options.formatSubMilliseconds) {
3599
- add(milliseconds, "millisecond", "ms");
3600
- add(microseconds, "microsecond", "µs");
3601
- add(nanoseconds, "nanosecond", "ns");
3611
+ if (!options.hideSeconds) {
3612
+ if (options.separateMilliseconds || options.formatSubMilliseconds || !options.colonNotation && milliseconds < 1e3 && !options.subSecondsAsDecimals) {
3613
+ const seconds = Number(parsed.seconds);
3614
+ const milliseconds = Number(parsed.milliseconds);
3615
+ const microseconds = Number(parsed.microseconds);
3616
+ const nanoseconds = Number(parsed.nanoseconds);
3617
+ add(seconds, "second", "s");
3618
+ if (options.formatSubMilliseconds) {
3619
+ add(milliseconds, "millisecond", "ms");
3620
+ add(microseconds, "microsecond", "µs");
3621
+ add(nanoseconds, "nanosecond", "ns");
3622
+ } else {
3623
+ const millisecondsAndBelow = milliseconds + microseconds / 1e3 + nanoseconds / 1e6;
3624
+ const millisecondsDecimalDigits = typeof options.millisecondsDecimalDigits === "number" ? options.millisecondsDecimalDigits : 0;
3625
+ const millisecondsString = millisecondsDecimalDigits ? millisecondsAndBelow.toFixed(millisecondsDecimalDigits) : millisecondsAndBelow >= 1 ? Math.round(millisecondsAndBelow) : Math.ceil(millisecondsAndBelow);
3626
+ add(Number.parseFloat(millisecondsString), "millisecond", "ms", millisecondsString);
3627
+ }
3602
3628
  } else {
3603
- const millisecondsAndBelow = milliseconds + microseconds / 1e3 + nanoseconds / 1e6;
3604
- const millisecondsDecimalDigits = typeof options.millisecondsDecimalDigits === "number" ? options.millisecondsDecimalDigits : 0;
3605
- const millisecondsString = millisecondsDecimalDigits ? millisecondsAndBelow.toFixed(millisecondsDecimalDigits) : millisecondsAndBelow >= 1 ? Math.round(millisecondsAndBelow) : Math.ceil(millisecondsAndBelow);
3606
- add(Number.parseFloat(millisecondsString), "millisecond", "ms", millisecondsString);
3629
+ const secondsFixed = floorDecimals((isBigInt ? Number(milliseconds % ONE_DAY_IN_MILLISECONDS) : milliseconds) / 1e3 % 60, typeof options.secondsDecimalDigits === "number" ? options.secondsDecimalDigits : 1);
3630
+ const secondsString = options.keepDecimalsOnWholeSeconds ? secondsFixed : secondsFixed.replace(/\.0+$/, "");
3631
+ add(Number.parseFloat(secondsString), "second", "s", secondsString);
3607
3632
  }
3608
- } else {
3609
- const secondsFixed = floorDecimals((isBigInt ? Number(milliseconds % ONE_DAY_IN_MILLISECONDS) : milliseconds) / 1e3 % 60, typeof options.secondsDecimalDigits === "number" ? options.secondsDecimalDigits : 1);
3610
- const secondsString = options.keepDecimalsOnWholeSeconds ? secondsFixed : secondsFixed.replace(/\.0+$/, "");
3611
- add(Number.parseFloat(secondsString), "second", "s", secondsString);
3612
3633
  }
3613
3634
  if (result.length === 0) return sign + "0" + (options.verbose ? " milliseconds" : "ms");
3614
3635
  const separator = options.colonNotation ? ":" : " ";
@@ -3633,9 +3654,10 @@ const logResult = (result, verboseInfo) => {
3633
3654
  logDuration(result, verboseInfo);
3634
3655
  };
3635
3656
  const logDuration = (result, verboseInfo) => {
3657
+ const verboseMessage = `(done in ${prettyMilliseconds(result.durationMs)})`;
3636
3658
  verboseLog({
3637
3659
  type: "duration",
3638
- verboseMessage: `(done in ${prettyMilliseconds(result.durationMs)})`,
3660
+ verboseMessage,
3639
3661
  verboseInfo,
3640
3662
  result
3641
3663
  });
@@ -3703,10 +3725,10 @@ const isTransformOptions = (value) => isPlainObject(value) && (value.transform !
3703
3725
  const isUrl = (value) => Object.prototype.toString.call(value) === "[object URL]";
3704
3726
  const isRegularUrl = (value) => isUrl(value) && value.protocol !== "file:";
3705
3727
  const isFilePathObject = (value) => isPlainObject(value) && Object.keys(value).length > 0 && Object.keys(value).every((key) => FILE_PATH_KEYS.has(key)) && isFilePathString(value.file);
3706
- const FILE_PATH_KEYS = new Set(["file", "append"]);
3728
+ const FILE_PATH_KEYS = /* @__PURE__ */ new Set(["file", "append"]);
3707
3729
  const isFilePathString = (file) => typeof file === "string";
3708
3730
  const isUnknownStdioString = (type, value) => type === "native" && typeof value === "string" && !KNOWN_STDIO_STRINGS.has(value);
3709
- const KNOWN_STDIO_STRINGS = new Set([
3731
+ const KNOWN_STDIO_STRINGS = /* @__PURE__ */ new Set([
3710
3732
  "ipc",
3711
3733
  "ignore",
3712
3734
  "inherit",
@@ -3720,24 +3742,24 @@ const isTransformStream = (value) => isReadableStream(value?.readable) && isWrit
3720
3742
  const isAsyncIterableObject = (value) => isObject(value) && typeof value[Symbol.asyncIterator] === "function";
3721
3743
  const isIterableObject = (value) => isObject(value) && typeof value[Symbol.iterator] === "function";
3722
3744
  const isObject = (value) => typeof value === "object" && value !== null;
3723
- const TRANSFORM_TYPES = new Set([
3745
+ const TRANSFORM_TYPES = /* @__PURE__ */ new Set([
3724
3746
  "generator",
3725
3747
  "asyncGenerator",
3726
3748
  "duplex",
3727
3749
  "webTransform"
3728
3750
  ]);
3729
- const FILE_TYPES = new Set([
3751
+ const FILE_TYPES = /* @__PURE__ */ new Set([
3730
3752
  "fileUrl",
3731
3753
  "filePath",
3732
3754
  "fileNumber"
3733
3755
  ]);
3734
- const SPECIAL_DUPLICATE_TYPES_SYNC = new Set(["fileUrl", "filePath"]);
3735
- const SPECIAL_DUPLICATE_TYPES = new Set([
3756
+ const SPECIAL_DUPLICATE_TYPES_SYNC = /* @__PURE__ */ new Set(["fileUrl", "filePath"]);
3757
+ const SPECIAL_DUPLICATE_TYPES = /* @__PURE__ */ new Set([
3736
3758
  ...SPECIAL_DUPLICATE_TYPES_SYNC,
3737
3759
  "webStream",
3738
3760
  "nodeStream"
3739
3761
  ]);
3740
- const FORBID_DUPLICATE_TYPES = new Set(["webTransform", "duplex"]);
3762
+ const FORBID_DUPLICATE_TYPES = /* @__PURE__ */ new Set(["webTransform", "duplex"]);
3741
3763
  const TYPE_TO_MESSAGE = {
3742
3764
  generator: "a generator",
3743
3765
  asyncGenerator: "an async generator",
@@ -4070,7 +4092,8 @@ const validateDuplicateStreamSync = ({ otherStdioItems, type, value, optionName,
4070
4092
  const getDuplicateStreamInstance = ({ otherStdioItems, type, value, optionName, direction }) => {
4071
4093
  const duplicateStdioItems = otherStdioItems.filter((stdioItem) => hasSameValue(stdioItem, value));
4072
4094
  if (duplicateStdioItems.length === 0) return;
4073
- throwOnDuplicateStream(duplicateStdioItems.find((stdioItem) => stdioItem.direction !== direction), optionName, type);
4095
+ const differentStdioItem = duplicateStdioItems.find((stdioItem) => stdioItem.direction !== direction);
4096
+ throwOnDuplicateStream(differentStdioItem, optionName, type);
4074
4097
  return direction === "output" ? duplicateStdioItems[0].stream : void 0;
4075
4098
  };
4076
4099
  const hasSameValue = ({ type, value }, secondValue) => {
@@ -4079,7 +4102,8 @@ const hasSameValue = ({ type, value }, secondValue) => {
4079
4102
  return value === secondValue;
4080
4103
  };
4081
4104
  const validateDuplicateTransform = ({ otherStdioItems, type, value, optionName }) => {
4082
- throwOnDuplicateStream(otherStdioItems.find(({ value: { transform } }) => transform === value.transform), optionName, type);
4105
+ const duplicateStdioItem = otherStdioItems.find(({ value: { transform } }) => transform === value.transform);
4106
+ throwOnDuplicateStream(duplicateStdioItem, optionName, type);
4083
4107
  };
4084
4108
  const throwOnDuplicateStream = (stdioItem, optionName, type) => {
4085
4109
  if (stdioItem !== void 0) throw new TypeError(`The \`${stdioItem.optionName}\` and \`${optionName}\` options must not target ${TYPE_TO_MESSAGE[type]} that is the same.`);
@@ -4087,13 +4111,14 @@ const throwOnDuplicateStream = (stdioItem, optionName, type) => {
4087
4111
  //#endregion
4088
4112
  //#region ../../node_modules/.pnpm/execa@9.5.2/node_modules/execa/lib/stdio/handle.js
4089
4113
  const handleStdio = (addProperties, options, verboseInfo, isSync) => {
4114
+ const initialFileDescriptors = normalizeStdioOption(options, verboseInfo, isSync).map((stdioOption, fdNumber) => getFileDescriptor({
4115
+ stdioOption,
4116
+ fdNumber,
4117
+ options,
4118
+ isSync
4119
+ }));
4090
4120
  const fileDescriptors = getFinalFileDescriptors({
4091
- initialFileDescriptors: normalizeStdioOption(options, verboseInfo, isSync).map((stdioOption, fdNumber) => getFileDescriptor({
4092
- stdioOption,
4093
- fdNumber,
4094
- options,
4095
- isSync
4096
- })),
4121
+ initialFileDescriptors,
4097
4122
  addProperties,
4098
4123
  options,
4099
4124
  isSync
@@ -4110,13 +4135,14 @@ const getFileDescriptor = ({ stdioOption, fdNumber, options, isSync }) => {
4110
4135
  optionName
4111
4136
  });
4112
4137
  const direction = getStreamDirection(initialStdioItems, fdNumber, optionName);
4113
- const normalizedStdioItems = normalizeTransforms(initialStdioItems.map((stdioItem) => handleNativeStream({
4138
+ const stdioItems = initialStdioItems.map((stdioItem) => handleNativeStream({
4114
4139
  stdioItem,
4115
4140
  isStdioArray,
4116
4141
  fdNumber,
4117
4142
  direction,
4118
4143
  isSync
4119
- })), optionName, direction, options);
4144
+ }));
4145
+ const normalizedStdioItems = normalizeTransforms(stdioItems, optionName, direction, options);
4120
4146
  const objectMode = getFdObjectMode(normalizedStdioItems, direction);
4121
4147
  validateFileObjectMode(normalizedStdioItems, objectMode);
4122
4148
  return {
@@ -4126,7 +4152,8 @@ const getFileDescriptor = ({ stdioOption, fdNumber, options, isSync }) => {
4126
4152
  };
4127
4153
  };
4128
4154
  const initializeStdioItems = ({ stdioOption, fdNumber, options, optionName }) => {
4129
- const stdioItems = filterDuplicates([...(Array.isArray(stdioOption) ? stdioOption : [stdioOption]).map((value) => initializeStdioItem(value, optionName)), ...handleInputOptions(options, fdNumber)]);
4155
+ const initialStdioItems = [...(Array.isArray(stdioOption) ? stdioOption : [stdioOption]).map((value) => initializeStdioItem(value, optionName)), ...handleInputOptions(options, fdNumber)];
4156
+ const stdioItems = filterDuplicates(initialStdioItems);
4130
4157
  const isStdioArray = stdioItems.length > 1;
4131
4158
  validateStdioArray(stdioItems, isStdioArray, optionName);
4132
4159
  validateStreams(stdioItems);
@@ -4145,7 +4172,7 @@ const validateStdioArray = (stdioItems, isStdioArray, optionName) => {
4145
4172
  if (!isStdioArray) return;
4146
4173
  for (const { value, optionName } of stdioItems) if (INVALID_STDIO_ARRAY_OPTIONS.has(value)) throw new Error(`The \`${optionName}\` option must not include \`${value}\`.`);
4147
4174
  };
4148
- const INVALID_STDIO_ARRAY_OPTIONS = new Set(["ignore", "ipc"]);
4175
+ const INVALID_STDIO_ARRAY_OPTIONS = /* @__PURE__ */ new Set(["ignore", "ipc"]);
4149
4176
  const validateStreams = (stdioItems) => {
4150
4177
  for (const stdioItem of stdioItems) validateFileStdio(stdioItem);
4151
4178
  };
@@ -4474,7 +4501,10 @@ const generatorToStream = ({ value, value: { transform, final, writableObjectMod
4474
4501
  const runGeneratorsSync = (chunks, stdioItems, encoding, isInput) => {
4475
4502
  const generators = stdioItems.filter(({ type }) => type === "generator");
4476
4503
  const reversedGenerators = isInput ? generators.reverse() : generators;
4477
- for (const { value, optionName } of reversedGenerators) chunks = runTransformSync(addInternalGenerators(value, encoding, optionName), chunks);
4504
+ for (const { value, optionName } of reversedGenerators) {
4505
+ const generators = addInternalGenerators(value, encoding, optionName);
4506
+ chunks = runTransformSync(generators, chunks);
4507
+ }
4478
4508
  return chunks;
4479
4509
  };
4480
4510
  const addInternalGenerators = ({ transform, final, binary, writableObjectMode, readableObjectMode, preserveNewlines }, encoding, optionName) => {
@@ -4510,7 +4540,8 @@ const addInputOptionSync = (fileDescriptors, fdNumber, options) => {
4510
4540
  const [{ type, optionName }] = allStdioItems;
4511
4541
  throw new TypeError(`Only the \`stdin\` option, not \`${optionName}\`, can be ${TYPE_TO_MESSAGE[type]} with synchronous methods.`);
4512
4542
  }
4513
- options.input = joinToUint8Array(allStdioItems.map(({ contents }) => contents).map((contents) => applySingleInputGeneratorsSync(contents, stdioItems)));
4543
+ const transformedContents = allStdioItems.map(({ contents }) => contents).map((contents) => applySingleInputGeneratorsSync(contents, stdioItems));
4544
+ options.input = joinToUint8Array(transformedContents);
4514
4545
  };
4515
4546
  const applySingleInputGeneratorsSync = (contents, stdioItems) => {
4516
4547
  const newContents = runGeneratorsSync(contents, stdioItems, "utf8", true);
@@ -4525,7 +4556,7 @@ const validateSerializable = (newContents) => {
4525
4556
  //#region ../../node_modules/.pnpm/execa@9.5.2/node_modules/execa/lib/verbose/output.js
4526
4557
  const shouldLogOutput = ({ stdioItems, encoding, verboseInfo, fdNumber }) => fdNumber !== "all" && isFullVerbose(verboseInfo, fdNumber) && !BINARY_ENCODINGS.has(encoding) && fdUsesVerbose(fdNumber) && (stdioItems.some(({ type, value }) => type === "native" && PIPED_STDIO_VALUES.has(value)) || stdioItems.every(({ type }) => TRANSFORM_TYPES.has(type)));
4527
4558
  const fdUsesVerbose = (fdNumber) => fdNumber === 1 || fdNumber === 2;
4528
- const PIPED_STDIO_VALUES = new Set(["pipe", "overlapped"]);
4559
+ const PIPED_STDIO_VALUES = /* @__PURE__ */ new Set(["pipe", "overlapped"]);
4529
4560
  const logLines = async (linesIterable, stream, fdNumber, verboseInfo) => {
4530
4561
  for await (const line of linesIterable) if (!isPipingStream(stream)) logLine(line, fdNumber, verboseInfo);
4531
4562
  };
@@ -4534,9 +4565,10 @@ const logLinesSync = (linesArray, fdNumber, verboseInfo) => {
4534
4565
  };
4535
4566
  const isPipingStream = (stream) => stream._readableState.pipes.length > 0;
4536
4567
  const logLine = (line, fdNumber, verboseInfo) => {
4568
+ const verboseMessage = serializeVerboseMessage(line);
4537
4569
  verboseLog({
4538
4570
  type: "output",
4539
- verboseMessage: serializeVerboseMessage(line),
4571
+ verboseMessage,
4540
4572
  fdNumber,
4541
4573
  verboseInfo
4542
4574
  });
@@ -4562,10 +4594,12 @@ const transformOutputSync = ({ fileDescriptors, syncResult: { output }, options,
4562
4594
  };
4563
4595
  const transformOutputResultSync = ({ result, fileDescriptors, fdNumber, state, outputFiles, isMaxBuffer, verboseInfo }, { buffer, encoding, lines, stripFinalNewline, maxBuffer }) => {
4564
4596
  if (result === null) return;
4565
- const uint8ArrayResult = bufferToUint8Array(truncateMaxBufferSync(result, isMaxBuffer, maxBuffer));
4597
+ const truncatedResult = truncateMaxBufferSync(result, isMaxBuffer, maxBuffer);
4598
+ const uint8ArrayResult = bufferToUint8Array(truncatedResult);
4566
4599
  const { stdioItems, objectMode } = fileDescriptors[fdNumber];
4600
+ const chunks = runOutputGeneratorsSync([uint8ArrayResult], stdioItems, encoding, state);
4567
4601
  const { serializedResult, finalResult = serializedResult } = serializeChunks({
4568
- chunks: runOutputGeneratorsSync([uint8ArrayResult], stdioItems, encoding, state),
4602
+ chunks,
4569
4603
  objectMode,
4570
4604
  encoding,
4571
4605
  lines,
@@ -4689,7 +4723,7 @@ const getResultError = (error, exitCode, signal) => {
4689
4723
  //#region ../../node_modules/.pnpm/execa@9.5.2/node_modules/execa/lib/methods/main-sync.js
4690
4724
  const execaCoreSync = (rawFile, rawArguments, rawOptions) => {
4691
4725
  const { file, commandArguments, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors } = handleSyncArguments(rawFile, rawArguments, rawOptions);
4692
- return handleResult(spawnSubprocessSync({
4726
+ const result = spawnSubprocessSync({
4693
4727
  file,
4694
4728
  commandArguments,
4695
4729
  options,
@@ -4698,11 +4732,13 @@ const execaCoreSync = (rawFile, rawArguments, rawOptions) => {
4698
4732
  verboseInfo,
4699
4733
  fileDescriptors,
4700
4734
  startTime
4701
- }), verboseInfo, options);
4735
+ });
4736
+ return handleResult(result, verboseInfo, options);
4702
4737
  };
4703
4738
  const handleSyncArguments = (rawFile, rawArguments, rawOptions) => {
4704
4739
  const { command, escapedCommand, startTime, verboseInfo } = handleCommand(rawFile, rawArguments, rawOptions);
4705
- const { file, commandArguments, options } = normalizeOptions(rawFile, rawArguments, normalizeSyncOptions(rawOptions));
4740
+ const syncOptions = normalizeSyncOptions(rawOptions);
4741
+ const { file, commandArguments, options } = normalizeOptions(rawFile, rawArguments, syncOptions);
4706
4742
  validateSyncOptions(options);
4707
4743
  return {
4708
4744
  file,
@@ -4747,14 +4783,16 @@ const spawnSubprocessSync = ({ file, commandArguments, options, command, escaped
4747
4783
  isMaxBuffer,
4748
4784
  verboseInfo
4749
4785
  });
4786
+ const stdio = output.map((stdioOutput, fdNumber) => stripNewline(stdioOutput, options, fdNumber));
4787
+ const all = stripNewline(getAllSync(output, options), options, "all");
4750
4788
  return getSyncResult({
4751
4789
  error,
4752
4790
  exitCode,
4753
4791
  signal,
4754
4792
  timedOut,
4755
4793
  isMaxBuffer,
4756
- stdio: output.map((stdioOutput, fdNumber) => stripNewline(stdioOutput, options, fdNumber)),
4757
- all: stripNewline(getAllSync(output, options), options, "all"),
4794
+ stdio,
4795
+ all,
4758
4796
  options,
4759
4797
  command,
4760
4798
  escapedCommand,
@@ -4764,7 +4802,8 @@ const spawnSubprocessSync = ({ file, commandArguments, options, command, escaped
4764
4802
  const runSubprocessSync = ({ file, commandArguments, options, command, escapedCommand, fileDescriptors, startTime }) => {
4765
4803
  try {
4766
4804
  addInputOptionsSync(fileDescriptors, options);
4767
- return spawnSync(file, commandArguments, normalizeSpawnSyncOptions(options));
4805
+ const normalizedOptions = normalizeSpawnSyncOptions(options);
4806
+ return spawnSync(file, commandArguments, normalizedOptions);
4768
4807
  } catch (error) {
4769
4808
  return makeEarlyError({
4770
4809
  error,
@@ -4978,17 +5017,18 @@ const handleEarlyError = ({ error, command, escapedCommand, fileDescriptors, opt
4978
5017
  writable,
4979
5018
  duplex
4980
5019
  });
5020
+ const earlyError = makeEarlyError({
5021
+ error,
5022
+ command,
5023
+ escapedCommand,
5024
+ fileDescriptors,
5025
+ options,
5026
+ startTime,
5027
+ isSync: false
5028
+ });
4981
5029
  return {
4982
5030
  subprocess,
4983
- promise: handleDummyPromise(makeEarlyError({
4984
- error,
4985
- command,
4986
- escapedCommand,
4987
- fileDescriptors,
4988
- options,
4989
- startTime,
4990
- isSync: false
4991
- }), verboseInfo, options)
5031
+ promise: handleDummyPromise(earlyError, verboseInfo, options)
4992
5032
  };
4993
5033
  };
4994
5034
  const createDummyStreams = (subprocess, fileDescriptors) => {
@@ -5172,8 +5212,10 @@ const endWhenStreamsDone = async ({ passThroughStream, stream, streams, ended, a
5172
5212
  controller.abort();
5173
5213
  updateMaxListeners(passThroughStream, -PASSTHROUGH_LISTENERS_PER_STREAM);
5174
5214
  }
5175
- if (streams.size > 0 && streams.size === ended.size + aborted.size) if (ended.size === 0 && aborted.size > 0) abortStream(passThroughStream);
5176
- else endStream(passThroughStream);
5215
+ if (streams.size > 0 && streams.size === ended.size + aborted.size) {
5216
+ if (ended.size === 0 && aborted.size > 0) abortStream(passThroughStream);
5217
+ else endStream(passThroughStream);
5218
+ }
5177
5219
  };
5178
5220
  const afterMergedStreamFinished = async (onFinished, stream, { signal }) => {
5179
5221
  try {
@@ -5279,7 +5321,10 @@ const pipeOutputAsync = (subprocess, fileDescriptors, controller) => {
5279
5321
  controller
5280
5322
  });
5281
5323
  }
5282
- for (const [outputStream, inputStreams] of pipeGroups.entries()) pipeStreams(inputStreams.length === 1 ? inputStreams[0] : mergeStreams(inputStreams), outputStream);
5324
+ for (const [outputStream, inputStreams] of pipeGroups.entries()) {
5325
+ const inputStream = inputStreams.length === 1 ? inputStreams[0] : mergeStreams(inputStreams);
5326
+ pipeStreams(inputStream, outputStream);
5327
+ }
5283
5328
  };
5284
5329
  const pipeTransform = (subprocess, stream, direction, fdNumber) => {
5285
5330
  if (direction === "output") pipeStreams(subprocess.stdio[fdNumber], stream);
@@ -5768,12 +5813,13 @@ const stopReadingOnStreamEnd = async (onStreamEnd, controller, stream) => {
5768
5813
  }
5769
5814
  };
5770
5815
  const iterateOnStream = ({ stream, controller, binary, shouldEncode, encoding, shouldSplit, preserveNewlines }) => {
5816
+ const onStdoutChunk = on(stream, "data", {
5817
+ signal: controller.signal,
5818
+ highWaterMark: HIGH_WATER_MARK,
5819
+ highWatermark: HIGH_WATER_MARK
5820
+ });
5771
5821
  return iterateOnData({
5772
- onStdoutChunk: on(stream, "data", {
5773
- signal: controller.signal,
5774
- highWaterMark: HIGH_WATER_MARK,
5775
- highWatermark: HIGH_WATER_MARK
5776
- }),
5822
+ onStdoutChunk,
5777
5823
  controller,
5778
5824
  binary,
5779
5825
  shouldEncode,
@@ -5817,12 +5863,13 @@ const getStreamOutput = async ({ stream, onStreamEnd, fdNumber, encoding, buffer
5817
5863
  await Promise.all([resumeStream(stream), logPromise]);
5818
5864
  return;
5819
5865
  }
5866
+ const stripFinalNewlineValue = getStripFinalNewline(stripFinalNewline, fdNumber);
5820
5867
  const iterable = iterateForResult({
5821
5868
  stream,
5822
5869
  onStreamEnd,
5823
5870
  lines,
5824
5871
  encoding,
5825
- stripFinalNewline: getStripFinalNewline(stripFinalNewline, fdNumber),
5872
+ stripFinalNewline: stripFinalNewlineValue,
5826
5873
  allMixed
5827
5874
  });
5828
5875
  const [output] = await Promise.all([getStreamContents({
@@ -5842,14 +5889,15 @@ const logOutputAsync = async ({ stream, onStreamEnd, fdNumber, encoding, allMixe
5842
5889
  verboseInfo,
5843
5890
  fdNumber
5844
5891
  })) return;
5845
- await logLines(iterateForResult({
5892
+ const linesIterable = iterateForResult({
5846
5893
  stream,
5847
5894
  onStreamEnd,
5848
5895
  lines: true,
5849
5896
  encoding,
5850
5897
  stripFinalNewline: true,
5851
5898
  allMixed
5852
- }), stream, fdNumber, verboseInfo);
5899
+ });
5900
+ await logLines(linesIterable, stream, fdNumber, verboseInfo);
5853
5901
  };
5854
5902
  const resumeStream = async (stream) => {
5855
5903
  await setImmediate();
@@ -5995,9 +6043,10 @@ const getAllMixed = ({ all, stdout, stderr }) => all && stdout && stderr && stdo
5995
6043
  //#region ../../node_modules/.pnpm/execa@9.5.2/node_modules/execa/lib/verbose/ipc.js
5996
6044
  const shouldLogIpc = (verboseInfo) => isFullVerbose(verboseInfo, "ipc");
5997
6045
  const logIpcOutput = (message, verboseInfo) => {
6046
+ const verboseMessage = serializeVerboseMessage(message);
5998
6047
  verboseLog({
5999
6048
  type: "ipc",
6000
- verboseMessage: serializeVerboseMessage(message),
6049
+ verboseMessage,
6001
6050
  fdNumber: "ipc",
6002
6051
  verboseInfo
6003
6052
  });
@@ -6393,14 +6442,15 @@ const onDuplexDestroy = async ({ subprocessStdout, subprocessStdin, subprocess,
6393
6442
  const createIterable = (subprocess, encoding, { from, binary: binaryOption = false, preserveNewlines = false } = {}) => {
6394
6443
  const binary = binaryOption || BINARY_ENCODINGS.has(encoding);
6395
6444
  const subprocessStdout = getFromStream(subprocess, from);
6396
- return iterateOnStdoutData(iterateOnSubprocessStream({
6445
+ const onStdoutData = iterateOnSubprocessStream({
6397
6446
  subprocessStdout,
6398
6447
  subprocess,
6399
6448
  binary,
6400
6449
  shouldEncode: true,
6401
6450
  encoding,
6402
6451
  preserveNewlines
6403
- }), subprocessStdout, subprocess);
6452
+ });
6453
+ return iterateOnStdoutData(onStdoutData, subprocessStdout, subprocess);
6404
6454
  };
6405
6455
  const iterateOnStdoutData = async function* (onStdoutData, subprocessStdout, subprocess) {
6406
6456
  try {
@@ -6560,19 +6610,22 @@ const handlePromise = async ({ subprocess, options, startTime, verboseInfo, file
6560
6610
  });
6561
6611
  controller.abort();
6562
6612
  onInternalError.resolve();
6563
- return handleResult(getAsyncResult({
6613
+ const stdio = stdioResults.map((stdioResult, fdNumber) => stripNewline(stdioResult, options, fdNumber));
6614
+ const all = stripNewline(allResult, options, "all");
6615
+ const result = getAsyncResult({
6564
6616
  errorInfo,
6565
6617
  exitCode,
6566
6618
  signal,
6567
- stdio: stdioResults.map((stdioResult, fdNumber) => stripNewline(stdioResult, options, fdNumber)),
6568
- all: stripNewline(allResult, options, "all"),
6619
+ stdio,
6620
+ all,
6569
6621
  ipcOutput,
6570
6622
  context,
6571
6623
  options,
6572
6624
  command,
6573
6625
  escapedCommand,
6574
6626
  startTime
6575
- }), verboseInfo, options);
6627
+ });
6628
+ return handleResult(result, verboseInfo, options);
6576
6629
  };
6577
6630
  const getAsyncResult = ({ errorInfo, exitCode, signal, stdio, all, ipcOutput, context, options, command, escapedCommand, startTime }) => "error" in errorInfo ? makeError({
6578
6631
  error: errorInfo.error,
@@ -6616,7 +6669,7 @@ const mergeOption = (optionName, boundOptionValue, optionValue) => {
6616
6669
  };
6617
6670
  return optionValue;
6618
6671
  };
6619
- const DEEP_OPTIONS = new Set(["env", ...FD_SPECIFIC_OPTIONS]);
6672
+ const DEEP_OPTIONS = /* @__PURE__ */ new Set(["env", ...FD_SPECIFIC_OPTIONS]);
6620
6673
  //#endregion
6621
6674
  //#region ../../node_modules/.pnpm/execa@9.5.2/node_modules/execa/lib/methods/create.js
6622
6675
  const createExeca = (mapArguments, boundOptions, deepOptions, setBoundExeca) => {
@@ -6643,7 +6696,8 @@ const callBoundExeca = ({ mapArguments, deepOptions = {}, boundOptions = {}, set
6643
6696
  return isSync ? execaCoreSync(file, commandArguments, options) : execaCoreAsync(file, commandArguments, options, createNested);
6644
6697
  };
6645
6698
  const parseArguments = ({ mapArguments, firstArgument, nextArguments, deepOptions, boundOptions }) => {
6646
- const [initialFile, initialArguments, initialOptions] = normalizeParameters(...isTemplateString(firstArgument) ? parseTemplates(firstArgument, nextArguments) : [firstArgument, ...nextArguments]);
6699
+ const callArguments = isTemplateString(firstArgument) ? parseTemplates(firstArgument, nextArguments) : [firstArgument, ...nextArguments];
6700
+ const [initialFile, initialArguments, initialOptions] = normalizeParameters(...callArguments);
6647
6701
  const mergedOptions = mergeOptions(mergeOptions(deepOptions, boundOptions), initialOptions);
6648
6702
  const { file = initialFile, commandArguments = initialArguments, options = mergedOptions, isSync = false } = mapArguments({
6649
6703
  file: initialFile,
@@ -6714,6 +6768,7 @@ const { sendMessage, getOneMessage, getEachMessage, getCancelSignal } = getIpcEx
6714
6768
  //#endregion
6715
6769
  //#region src/firebaseDatabaseParserShared.ts
6716
6770
  var FirebaseDatabaseDataError = class extends Error {
6771
+ source;
6717
6772
  name = "FirebaseDatabaseDataError";
6718
6773
  constructor(source) {
6719
6774
  super(`Invalid Firebase database data at "${source}".`);
@@ -6825,6 +6880,24 @@ const parseFirebaseBundleEventRow = (value, source) => {
6825
6880
  received_at_ms: number(property(input, "received_at_ms"), source)
6826
6881
  };
6827
6882
  };
6883
+ const parseFirebaseInsightsInstallationRow = (value, source) => {
6884
+ const input = record(value, source);
6885
+ const type = string(property(input, "type"), source);
6886
+ if (type !== "UPDATE_APPLIED" && type !== "RECOVERED" && type !== "RELEASE_ADOPTED" && type !== "UNCHANGED") throw new FirebaseDatabaseDataError(source);
6887
+ return {
6888
+ id: string(property(input, "id"), source),
6889
+ type,
6890
+ install_id: string(property(input, "install_id"), source),
6891
+ user_id: nullableString(property(input, "user_id"), source),
6892
+ username: nullableString(property(input, "username"), source),
6893
+ to_bundle_id: string(property(input, "to_bundle_id"), source),
6894
+ platform: platform$1(property(input, "platform"), source),
6895
+ app_version: string(property(input, "app_version"), source),
6896
+ channel: string(property(input, "channel"), source),
6897
+ cohort: string(property(input, "cohort"), source),
6898
+ received_at_ms: number(property(input, "received_at_ms"), source)
6899
+ };
6900
+ };
6828
6901
  const parseFirebaseApiKeyRow = (value, source) => {
6829
6902
  const input = record(value, source);
6830
6903
  const role = string(property(input, "role"), source);
@@ -6905,13 +6978,15 @@ const matchesCondition = (row, condition) => {
6905
6978
  switch (condition.operator ?? "eq") {
6906
6979
  case "eq": {
6907
6980
  if (typeof expected !== "string") return actual === expected;
6908
- const comparison = normalizeStringComparison(actual, expected, "mode" in condition ? condition.mode : void 0);
6981
+ const mode = "mode" in condition ? condition.mode : void 0;
6982
+ const comparison = normalizeStringComparison(actual, expected, mode);
6909
6983
  return comparison !== null && comparison[0] === comparison[1];
6910
6984
  }
6911
6985
  case "ne": {
6912
6986
  if (actual === null || actual === void 0) return false;
6913
6987
  if (typeof expected !== "string") return actual !== expected;
6914
- const comparison = normalizeStringComparison(actual, expected, "mode" in condition ? condition.mode : void 0);
6988
+ const mode = "mode" in condition ? condition.mode : void 0;
6989
+ const comparison = normalizeStringComparison(actual, expected, mode);
6915
6990
  return comparison === null || comparison[0] !== comparison[1];
6916
6991
  }
6917
6992
  case "gt":
@@ -6936,17 +7011,20 @@ const matchesCondition = (row, condition) => {
6936
7011
  }
6937
7012
  case "contains": {
6938
7013
  if (typeof expected !== "string") return false;
6939
- const comparison = normalizeStringComparison(actual, expected, "mode" in condition ? condition.mode : void 0);
7014
+ const mode = "mode" in condition ? condition.mode : void 0;
7015
+ const comparison = normalizeStringComparison(actual, expected, mode);
6940
7016
  return comparison?.[0].includes(comparison[1]) ?? false;
6941
7017
  }
6942
7018
  case "starts_with": {
6943
7019
  if (typeof expected !== "string") return false;
6944
- const comparison = normalizeStringComparison(actual, expected, "mode" in condition ? condition.mode : void 0);
7020
+ const mode = "mode" in condition ? condition.mode : void 0;
7021
+ const comparison = normalizeStringComparison(actual, expected, mode);
6945
7022
  return comparison?.[0].startsWith(comparison[1]) ?? false;
6946
7023
  }
6947
7024
  case "ends_with": {
6948
7025
  if (typeof expected !== "string") return false;
6949
- const comparison = normalizeStringComparison(actual, expected, "mode" in condition ? condition.mode : void 0);
7026
+ const mode = "mode" in condition ? condition.mode : void 0;
7027
+ const comparison = normalizeStringComparison(actual, expected, mode);
6950
7028
  return comparison?.[0].endsWith(comparison[1]) ?? false;
6951
7029
  }
6952
7030
  }
@@ -6991,6 +7069,7 @@ const queryFirebaseDatabaseRows = (rows, input) => {
6991
7069
  //#endregion
6992
7070
  //#region src/firebaseDatabaseState.ts
6993
7071
  var FirebaseDatabaseConstraintError = class extends Error {
7072
+ constraint;
6994
7073
  name = "FirebaseDatabaseConstraintError";
6995
7074
  constructor(constraint) {
6996
7075
  super(`Firebase database constraint failed: ${constraint}`);
@@ -7001,6 +7080,7 @@ const cloneFirebaseDatabaseSnapshot = (snapshot) => ({
7001
7080
  bundles: new Map(snapshot.bundles),
7002
7081
  bundlePatches: new Map(snapshot.bundlePatches),
7003
7082
  bundleEvents: new Map(snapshot.bundleEvents),
7083
+ bundleInstallations: new Map(snapshot.bundleInstallations),
7004
7084
  channels: new Map(snapshot.channels),
7005
7085
  apiKeys: new Map(snapshot.apiKeys),
7006
7086
  releaseCatalogs: new Map(snapshot.releaseCatalogs),
@@ -7030,6 +7110,13 @@ const createFirebaseDatabaseState = (snapshot) => ({
7030
7110
  requireUnique(snapshot.bundleEvents, input.data.id, input.model);
7031
7111
  snapshot.bundleEvents.set(input.data.id, input.data);
7032
7112
  return input.data;
7113
+ case "bundle_installations": {
7114
+ const current = snapshot.bundleInstallations.get(input.data.install_id);
7115
+ if (current && input.onConflict === "ignore") return current;
7116
+ if (current) throw new FirebaseDatabaseConstraintError("bundle_installations.install_id.unique");
7117
+ snapshot.bundleInstallations.set(input.data.install_id, input.data);
7118
+ return input.data;
7119
+ }
7033
7120
  case "releases":
7034
7121
  requireUnique(snapshot.releases, input.data.id, input.model);
7035
7122
  if (!snapshot.channels.has(input.data.channel_id)) throw new FirebaseDatabaseConstraintError("releases.channel_id.foreign-key");
@@ -7059,6 +7146,16 @@ const createFirebaseDatabaseState = (snapshot) => ({
7059
7146
  }
7060
7147
  },
7061
7148
  async update(input) {
7149
+ if (input.model === "bundle_installations") {
7150
+ const current = [...snapshot.bundleInstallations.values()].find((row) => matchesFirebaseDatabaseWhere(row, input.where));
7151
+ if (!current) return null;
7152
+ const updated = {
7153
+ ...current,
7154
+ ...input.update
7155
+ };
7156
+ snapshot.bundleInstallations.set(current.install_id, updated);
7157
+ return updated;
7158
+ }
7062
7159
  if (input.model === "api_keys") {
7063
7160
  const current = [...snapshot.apiKeys.values()].find((row) => matchesFirebaseDatabaseWhere(row, input.where));
7064
7161
  if (!current) return null;
@@ -7120,6 +7217,8 @@ const createFirebaseDatabaseState = (snapshot) => ({
7120
7217
  case "bundles": return distinctCount([...snapshot.bundles.values()].filter((row) => matchesFirebaseDatabaseWhere(row, input.where)), input.distinct);
7121
7218
  case "bundle_patches": return distinctCount([...snapshot.bundlePatches.values()].filter((row) => matchesFirebaseDatabaseWhere(row, input.where)), input.distinct);
7122
7219
  case "releases": return distinctCount([...snapshot.releases.values()].filter((row) => matchesFirebaseDatabaseWhere(row, input.where)), input.distinct);
7220
+ case "bundle_installations": return distinctCount([...snapshot.bundleInstallations.values()].filter((row) => matchesFirebaseDatabaseWhere(row, input.where)), input.distinct);
7221
+ case "bundle_events": return distinctCount([...snapshot.bundleEvents.values()].filter((row) => matchesFirebaseDatabaseWhere(row, input.where)), input.distinct);
7123
7222
  }
7124
7223
  },
7125
7224
  async findOne(input) {
@@ -7130,6 +7229,7 @@ const createFirebaseDatabaseState = (snapshot) => ({
7130
7229
  case "bundle_patches": return [...snapshot.bundlePatches.values()].find((row) => matchesFirebaseDatabaseWhere(row, input.where)) ?? null;
7131
7230
  case "releases": return [...snapshot.releases.values()].find((row) => matchesFirebaseDatabaseWhere(row, input.where)) ?? null;
7132
7231
  case "release_catalogs": return [...snapshot.releaseCatalogs.values()].find((row) => matchesFirebaseDatabaseWhere(row, input.where)) ?? null;
7232
+ case "bundle_installations": return [...snapshot.bundleInstallations.values()].find((row) => matchesFirebaseDatabaseWhere(row, input.where)) ?? null;
7133
7233
  }
7134
7234
  },
7135
7235
  async findMany(input) {
@@ -7137,6 +7237,7 @@ const createFirebaseDatabaseState = (snapshot) => ({
7137
7237
  case "bundles": return queryFirebaseDatabaseRows([...snapshot.bundles.values()], input);
7138
7238
  case "bundle_patches": return queryFirebaseDatabaseRows([...snapshot.bundlePatches.values()], input);
7139
7239
  case "bundle_events": return queryFirebaseDatabaseRows([...snapshot.bundleEvents.values()], input);
7240
+ case "bundle_installations": return queryFirebaseDatabaseRows([...snapshot.bundleInstallations.values()], input);
7140
7241
  case "channels": return queryFirebaseDatabaseRows([...snapshot.channels.values()], input);
7141
7242
  case "api_keys": return queryFirebaseDatabaseRows([...snapshot.apiKeys.values()], input);
7142
7243
  case "releases": return queryFirebaseDatabaseRows([...snapshot.releases.values()], input);
@@ -7150,6 +7251,7 @@ const FIREBASE_V1_FUNCTION_NAME = "hot-updater-v1";
7150
7251
  const FIREBASE_V1_COLLECTION_NAMES = {
7151
7252
  apiKeys: "hot_updater_v1_api_keys",
7152
7253
  bundleEvents: "hot_updater_v1_bundle_events",
7254
+ bundleInstallations: "hot_updater_v1_bundle_installations",
7153
7255
  bundlePatches: "hot_updater_v1_bundle_patches",
7154
7256
  bundles: "hot_updater_v1_bundles",
7155
7257
  channels: "hot_updater_v1_channels",
@@ -7160,6 +7262,7 @@ const FIREBASE_V1_COLLECTION_NAMES = {
7160
7262
  //#endregion
7161
7263
  //#region src/firebaseDatabasePersistence.ts
7162
7264
  var FirebaseDatabaseAdapterVersionError = class extends Error {
7265
+ version;
7163
7266
  name = "FirebaseDatabaseAdapterVersionError";
7164
7267
  constructor(version) {
7165
7268
  super(`Unsupported Firebase database adapter version: ${String(version)}`);
@@ -7170,6 +7273,7 @@ const createFirebaseDatabaseCollections = (db) => ({
7170
7273
  bundles: db.collection(FIREBASE_V1_COLLECTION_NAMES.bundles),
7171
7274
  bundlePatches: db.collection(FIREBASE_V1_COLLECTION_NAMES.bundlePatches),
7172
7275
  bundleEvents: db.collection(FIREBASE_V1_COLLECTION_NAMES.bundleEvents),
7276
+ bundleInstallations: db.collection(FIREBASE_V1_COLLECTION_NAMES.bundleInstallations),
7173
7277
  channels: db.collection(FIREBASE_V1_COLLECTION_NAMES.channels),
7174
7278
  apiKeys: db.collection(FIREBASE_V1_COLLECTION_NAMES.apiKeys),
7175
7279
  releaseCatalogs: db.collection(FIREBASE_V1_COLLECTION_NAMES.releaseCatalogs),
@@ -7178,14 +7282,15 @@ const createFirebaseDatabaseCollections = (db) => ({
7178
7282
  });
7179
7283
  const firebaseChannelDocumentId = (name) => `name_${Buffer.from(name, "utf8").toString("base64url")}`;
7180
7284
  const firebaseChannelIdDocumentId = (id) => `channel_id_${Buffer.from(id, "utf8").toString("base64url")}`;
7285
+ const firebaseInstallationDocumentId = (id) => `install_${Buffer.from(id, "utf8").toString("base64url")}`;
7181
7286
  const requireFirebaseDocumentKey = (model, documentId, row) => {
7182
- if (documentId !== ("id" in row ? row.id : row.scope_key)) throw new FirebaseDatabaseConstraintError(`${model}.id.document-key`);
7287
+ if (documentId !== (model === "bundle_installations" ? firebaseInstallationDocumentId(row.install_id) : "id" in row ? row.id : row.scope_key)) throw new FirebaseDatabaseConstraintError(`${model}.id.document-key`);
7183
7288
  return row;
7184
7289
  };
7185
7290
  const documentMap = (model, documents) => {
7186
7291
  const rows = /* @__PURE__ */ new Map();
7187
7292
  for (const { row } of documents) {
7188
- const key = "id" in row ? row.id : row.scope_key;
7293
+ const key = model === "bundle_installations" ? row.install_id : "id" in row ? row.id : row.scope_key;
7189
7294
  if (rows.has(key)) throw new FirebaseDatabaseConstraintError(`${model}.id.unique`);
7190
7295
  rows.set(key, row);
7191
7296
  }
@@ -7200,10 +7305,6 @@ const patchMap = (snapshot) => documentMap("bundle_patches", snapshot.docs.map((
7200
7305
  document,
7201
7306
  row: parseFirebasePatchRow(document.data(), `bundle_patches/${document.id}`)
7202
7307
  })));
7203
- const eventMap = (snapshot) => documentMap("bundle_events", snapshot.docs.map((document) => ({
7204
- document,
7205
- row: parseFirebaseBundleEventRow(document.data(), `bundle_events/${document.id}`)
7206
- })));
7207
7308
  const channelMap = (snapshot) => {
7208
7309
  const rows = /* @__PURE__ */ new Map();
7209
7310
  const names = /* @__PURE__ */ new Set();
@@ -7234,18 +7335,18 @@ const toSnapshot = (documents) => {
7234
7335
  return {
7235
7336
  bundles: bundleMap(documents[0]),
7236
7337
  bundlePatches: patchMap(documents[1]),
7237
- bundleEvents: eventMap(documents[2]),
7238
- channels: channelMap(documents[3]),
7239
- apiKeys: apiKeyMap(documents[4]),
7240
- releases: releaseMap(documents[5]),
7241
- releaseCatalogs: releaseCatalogMap(documents[6])
7338
+ bundleEvents: /* @__PURE__ */ new Map(),
7339
+ bundleInstallations: /* @__PURE__ */ new Map(),
7340
+ channels: channelMap(documents[2]),
7341
+ apiKeys: apiKeyMap(documents[3]),
7342
+ releases: releaseMap(documents[4]),
7343
+ releaseCatalogs: releaseCatalogMap(documents[5])
7242
7344
  };
7243
7345
  };
7244
7346
  const loadFirebaseDatabaseSnapshot = async (collections) => {
7245
- const [bundles, patches, events, channels, apiKeys, releases, releaseCatalogs] = await Promise.all([
7347
+ const [bundles, patches, channels, apiKeys, releases, releaseCatalogs] = await Promise.all([
7246
7348
  collections.bundles.get(),
7247
7349
  collections.bundlePatches.get(),
7248
- collections.bundleEvents.get(),
7249
7350
  collections.channels.get(),
7250
7351
  collections.apiKeys.get(),
7251
7352
  collections.releases.get(),
@@ -7254,7 +7355,6 @@ const loadFirebaseDatabaseSnapshot = async (collections) => {
7254
7355
  return toSnapshot([
7255
7356
  bundles,
7256
7357
  patches,
7257
- events,
7258
7358
  channels,
7259
7359
  apiKeys,
7260
7360
  releases,
@@ -7262,10 +7362,9 @@ const loadFirebaseDatabaseSnapshot = async (collections) => {
7262
7362
  ]);
7263
7363
  };
7264
7364
  const loadFirebaseTransactionSnapshot = async (transaction, collections) => {
7265
- const [bundles, patches, events, channels, apiKeys, releases, releaseCatalogs] = await Promise.all([
7365
+ const [bundles, patches, channels, apiKeys, releases, releaseCatalogs] = await Promise.all([
7266
7366
  transaction.get(collections.bundles),
7267
7367
  transaction.get(collections.bundlePatches),
7268
- transaction.get(collections.bundleEvents),
7269
7368
  transaction.get(collections.channels),
7270
7369
  transaction.get(collections.apiKeys),
7271
7370
  transaction.get(collections.releases),
@@ -7274,7 +7373,6 @@ const loadFirebaseTransactionSnapshot = async (transaction, collections) => {
7274
7373
  return toSnapshot([
7275
7374
  bundles,
7276
7375
  patches,
7277
- events,
7278
7376
  channels,
7279
7377
  apiKeys,
7280
7378
  releases,
@@ -7300,13 +7398,6 @@ const persistFirebaseDatabaseSnapshot = ({ transaction, collections, before, aft
7300
7398
  after: after.bundlePatches,
7301
7399
  documentId: (row) => row.id
7302
7400
  });
7303
- persistCollection({
7304
- transaction,
7305
- collection: collections.bundleEvents,
7306
- before: before.bundleEvents,
7307
- after: after.bundleEvents,
7308
- documentId: (row) => row.id
7309
- });
7310
7401
  persistCollection({
7311
7402
  transaction,
7312
7403
  collection: collections.channels,
@@ -7338,7 +7429,7 @@ const persistFirebaseDatabaseSnapshot = ({ transaction, collections, before, aft
7338
7429
  documentId: (row) => row.scope_key
7339
7430
  });
7340
7431
  };
7341
- const migrateFirebaseDatabase = async (_db, collections) => {
7432
+ const migrateFirebaseDatabase = async (collections) => {
7342
7433
  const versionDocument = collections.settings.doc("database_adapter_version");
7343
7434
  const version = await versionDocument.get();
7344
7435
  const adapterVersion = version.data()?.version;
@@ -7349,7 +7440,9 @@ const migrateFirebaseDatabase = async (_db, collections) => {
7349
7440
  collections.bundlePatches.limit(1).get(),
7350
7441
  collections.channels.limit(1).get(),
7351
7442
  collections.releases.limit(1).get(),
7352
- collections.releaseCatalogs.limit(1).get()
7443
+ collections.releaseCatalogs.limit(1).get(),
7444
+ collections.bundleInstallations.limit(1).get(),
7445
+ collections.bundleEvents.limit(1).get()
7353
7446
  ])).some((snapshot) => !snapshot.empty)) throw new FirebaseDatabaseAdapterVersionError("v0");
7354
7447
  try {
7355
7448
  await versionDocument.create({ version: 4 });
@@ -7364,13 +7457,40 @@ const exactId = (input) => {
7364
7457
  const [condition] = input.where;
7365
7458
  return condition.field === "id" && (condition.operator === void 0 || condition.operator === "eq") && typeof condition.value === "string" ? condition.value : void 0;
7366
7459
  };
7460
+ const exactInstallId = (input) => {
7461
+ const condition = input.where?.find(({ field, operator }) => field === "install_id" && (operator === void 0 || operator === "eq"));
7462
+ return typeof condition?.value === "string" ? condition.value : void 0;
7463
+ };
7464
+ const firestoreOperator = (operator) => {
7465
+ switch (operator ?? "eq") {
7466
+ case "eq": return "==";
7467
+ case "ne": return "!=";
7468
+ case "gt": return ">";
7469
+ case "gte": return ">=";
7470
+ case "lt": return "<";
7471
+ case "lte": return "<=";
7472
+ case "in": return "in";
7473
+ case "not_in": return "not-in";
7474
+ default: return;
7475
+ }
7476
+ };
7477
+ const applyFirebaseWhere = (initial, where) => {
7478
+ let query = initial;
7479
+ for (const condition of where) {
7480
+ const operator = firestoreOperator(condition.operator);
7481
+ if (condition.connector === "OR" || operator === void 0) throw new FirebaseDatabaseConstraintError("query.unsupported");
7482
+ query = query.where(condition.field, operator, condition.value);
7483
+ }
7484
+ return query;
7485
+ };
7367
7486
  const firebaseDatabase = (config) => {
7368
- const adapter = createDatabasePluginAdapter("firebaseDatabase", (() => {
7369
- const db = getFirestore(getApps().length ? getApp() : initializeApp(config));
7487
+ const implementation = (() => {
7488
+ const app = getApps().length ? getApp() : initializeApp(config);
7489
+ const db = getFirestore(app);
7370
7490
  const collections = createFirebaseDatabaseCollections(db);
7371
7491
  let migration;
7372
7492
  const ensureMigrated = () => {
7373
- migration ??= migrateFirebaseDatabase(db, collections).catch((error) => {
7493
+ migration ??= migrateFirebaseDatabase(collections).catch((error) => {
7374
7494
  migration = void 0;
7375
7495
  throw error;
7376
7496
  });
@@ -7393,14 +7513,74 @@ const firebaseDatabase = (config) => {
7393
7513
  };
7394
7514
  const read = async (operation) => {
7395
7515
  await ensureMigrated();
7396
- return operation(createFirebaseDatabaseState(await loadFirebaseDatabaseSnapshot(collections)));
7516
+ const snapshot = await loadFirebaseDatabaseSnapshot(collections);
7517
+ return operation(createFirebaseDatabaseState(snapshot));
7397
7518
  };
7398
7519
  return {
7399
- create: (input) => mutate((database) => database.create(input)),
7400
- update: (input) => mutate((database) => database.update(input)),
7520
+ recordInsights: async ({ event, installation }) => {
7521
+ await ensureMigrated();
7522
+ await db.runTransaction(async (transaction) => {
7523
+ const eventReference = collections.bundleEvents.doc(event.id);
7524
+ const installationReference = collections.bundleInstallations.doc(firebaseInstallationDocumentId(installation.install_id));
7525
+ const [storedEvent, storedInstallation] = await transaction.getAll(eventReference, installationReference);
7526
+ if (storedEvent.exists) return;
7527
+ const current = storedInstallation.exists ? requireFirebaseDocumentKey("bundle_installations", storedInstallation.id, parseFirebaseInsightsInstallationRow(storedInstallation.data(), `bundle_installations/${storedInstallation.id}`)) : null;
7528
+ transaction.create(eventReference, event);
7529
+ if (current === null || installation.received_at_ms > current.received_at_ms || installation.received_at_ms === current.received_at_ms && compareInsightsText(installation.id, current.id) > 0) transaction.set(installationReference, installation);
7530
+ });
7531
+ },
7532
+ create: async (input) => {
7533
+ if (input.model !== "bundle_events" && input.model !== "bundle_installations") return mutate((database) => database.create(input));
7534
+ await ensureMigrated();
7535
+ return db.runTransaction(async (transaction) => {
7536
+ const collection = input.model === "bundle_events" ? collections.bundleEvents : collections.bundleInstallations;
7537
+ const documentId = input.model === "bundle_events" ? input.data.id : firebaseInstallationDocumentId(input.data.install_id);
7538
+ const reference = collection.doc(documentId);
7539
+ const document = await transaction.get(reference);
7540
+ if (document.exists) {
7541
+ const row = input.model === "bundle_events" ? requireFirebaseDocumentKey("bundle_events", document.id, parseFirebaseBundleEventRow(document.data(), `bundle_events/${document.id}`)) : requireFirebaseDocumentKey("bundle_installations", document.id, parseFirebaseInsightsInstallationRow(document.data(), `bundle_installations/${document.id}`));
7542
+ if (input.onConflict === "ignore") return row;
7543
+ throw new FirebaseDatabaseConstraintError(`${input.model}.id.unique`);
7544
+ }
7545
+ transaction.create(reference, input.data);
7546
+ return input.data;
7547
+ });
7548
+ },
7549
+ update: async (input) => {
7550
+ if (input.model !== "bundle_installations") return mutate((database) => database.update(input));
7551
+ const installId = exactInstallId(input);
7552
+ if (installId === void 0) return mutate((database) => database.update(input));
7553
+ await ensureMigrated();
7554
+ return db.runTransaction(async (transaction) => {
7555
+ const reference = collections.bundleInstallations.doc(firebaseInstallationDocumentId(installId));
7556
+ const document = await transaction.get(reference);
7557
+ if (!document.exists) return null;
7558
+ const current = requireFirebaseDocumentKey("bundle_installations", document.id, parseFirebaseInsightsInstallationRow(document.data(), `bundle_installations/${document.id}`));
7559
+ if (!matchesFirebaseDatabaseWhere(current, input.where)) return null;
7560
+ const updated = {
7561
+ ...current,
7562
+ ...input.update
7563
+ };
7564
+ transaction.set(reference, updated, { merge: true });
7565
+ return updated;
7566
+ });
7567
+ },
7401
7568
  delete: (input) => mutate((database) => database.delete(input)),
7402
- count: (input) => read((database) => database.count(input)),
7569
+ count: async (input) => {
7570
+ if (input.model !== "bundle_installations" && input.model !== "bundle_events") return read((database) => database.count(input));
7571
+ await ensureMigrated();
7572
+ let query = applyFirebaseWhere(input.model === "bundle_events" ? collections.bundleEvents : collections.bundleInstallations, input.where ?? []);
7573
+ if (input.model === "bundle_events") query = query.orderBy("received_at_ms", "desc").orderBy("id", "desc");
7574
+ return (await query.count().get()).data().count;
7575
+ },
7403
7576
  findOne: async (input) => {
7577
+ if (input.model === "bundle_installations") {
7578
+ const installId = exactInstallId(input);
7579
+ if (installId === void 0) return read((database) => database.findOne(input));
7580
+ await ensureMigrated();
7581
+ const document = await collections.bundleInstallations.doc(firebaseInstallationDocumentId(installId)).get();
7582
+ return document.exists ? requireFirebaseDocumentKey("bundle_installations", document.id, parseFirebaseInsightsInstallationRow(document.data(), `bundle_installations/${document.id}`)) : null;
7583
+ }
7404
7584
  const id = exactId(input);
7405
7585
  if (id === void 0) return read((database) => database.findOne(input));
7406
7586
  await ensureMigrated();
@@ -7421,9 +7601,21 @@ const firebaseDatabase = (config) => {
7421
7601
  }
7422
7602
  },
7423
7603
  findMany: async (input) => {
7424
- if (input.model !== "channels") return read((database) => database.findMany(input));
7425
- await ensureMigrated();
7426
- return queryFirebaseDatabaseRows(await loadFirebaseChannels(collections), input);
7604
+ if (input.model === "bundle_events" || input.model === "bundle_installations") {
7605
+ await ensureMigrated();
7606
+ const collection = input.model === "bundle_events" ? collections.bundleEvents : collections.bundleInstallations;
7607
+ let query = applyFirebaseWhere(collection, input.where ?? []);
7608
+ for (const order of input.orderBy ?? []) {
7609
+ if (order.nulls !== void 0) throw new FirebaseDatabaseConstraintError("query.unsupported");
7610
+ query = query.orderBy(order.field, order.direction);
7611
+ }
7612
+ return (await query.offset(input.offset).limit(input.limit).get()).docs.map((document) => input.model === "bundle_events" ? requireFirebaseDocumentKey("bundle_events", document.id, parseFirebaseBundleEventRow(document.data(), `bundle_events/${document.id}`)) : requireFirebaseDocumentKey("bundle_installations", document.id, parseFirebaseInsightsInstallationRow(document.data(), `bundle_installations/${document.id}`)));
7613
+ }
7614
+ if (input.model === "channels") {
7615
+ await ensureMigrated();
7616
+ return queryFirebaseDatabaseRows(await loadFirebaseChannels(collections), input);
7617
+ }
7618
+ return read((database) => database.findMany(input));
7427
7619
  },
7428
7620
  insertChannel: async (input) => {
7429
7621
  await ensureMigrated();
@@ -7475,7 +7667,8 @@ const firebaseDatabase = (config) => {
7475
7667
  },
7476
7668
  transaction: (callback) => mutate(callback)
7477
7669
  };
7478
- })());
7670
+ })();
7671
+ const adapter = createDatabasePluginAdapter("firebaseDatabase", implementation);
7479
7672
  return createDatabasePlugin({
7480
7673
  name: "firebaseDatabase",
7481
7674
  models: adapter.models,
@@ -7543,8 +7736,9 @@ const resolveFirebaseInfrastructureState = ({ adapterVersion, hasData }) => {
7543
7736
  return "fresh";
7544
7737
  };
7545
7738
  const assertFirebaseInfrastructureCanInitialize = async ({ applicationCredentials, projectId }) => {
7739
+ const credential = applicationCredentials ? cert(JSON.parse(await fs$1.readFile(applicationCredentials, "utf8"))) : applicationDefault();
7546
7740
  const app = initializeApp({
7547
- credential: applicationCredentials ? cert(JSON.parse(await fs$1.readFile(applicationCredentials, "utf8"))) : applicationDefault(),
7741
+ credential,
7548
7742
  projectId
7549
7743
  }, `hot-updater-init-${projectId}-${Date.now()}`);
7550
7744
  try {
@@ -7803,10 +7997,11 @@ const getConfigScaffold = (build) => {
7803
7997
  // Example: GOOGLE_APPLICATION_CREDENTIALS=./firebase-adminsdk-credentials.json
7804
7998
  const credential = applicationDefault();`.trim()
7805
7999
  }];
7806
- return createHotUpdaterConfigScaffoldFromBuilder(new ConfigBuilder().setBuildType(build).setStorage(storageConfig).setDatabase(databaseConfig).addImport({
8000
+ const builder = new ConfigBuilder().setBuildType(build).setStorage(storageConfig).setDatabase(databaseConfig).addImport({
7807
8001
  pkg: "firebase-admin/app",
7808
8002
  named: ["applicationDefault"]
7809
- }).setIntermediateCode(helperStatements.map((statement) => statement.code.trim()).join("\n\n")), { helperStatements });
8003
+ }).setIntermediateCode(helperStatements.map((statement) => statement.code.trim()).join("\n\n"));
8004
+ return createHotUpdaterConfigScaffoldFromBuilder(builder, { helperStatements });
7810
8005
  };
7811
8006
  const setEnv = async ({ applicationCredentials, projectId, storageBucket, build, region }) => {
7812
8007
  await makeEnv({
@@ -7969,6 +8164,10 @@ const initFirebaseUser = async (cwd, preferredProjectId, nonInteractive = false,
7969
8164
  "--format=json"
7970
8165
  ], {
7971
8166
  env: selectedProjectCliEnv,
8167
+ /**
8168
+ * API [firestore.googleapis.com] not enabled on project [xxx]. Would you
8169
+ like to enable and retry (this will take a few minutes)? (y/N)?
8170
+ */
7972
8171
  input: "N\n"
7973
8172
  });
7974
8173
  if (JSON.parse(databases.stdout).length === 0) {
@@ -8255,7 +8454,8 @@ const runInit = async ({ build, envFile }) => {
8255
8454
  p.log.step(link("https://cloud.google.com/sdk/docs/install"));
8256
8455
  process.exit(1);
8257
8456
  }
8258
- const { tmpDir, removeTmpDir, functionsDir } = await prepareFirebaseTemplate(path.dirname(path.dirname(__require.resolve("@hot-updater/firebase/functions"))));
8457
+ const firebaseRootDir = path.dirname(path.dirname(__require.resolve("@hot-updater/firebase/functions")));
8458
+ const { tmpDir, removeTmpDir, functionsDir } = await prepareFirebaseTemplate(firebaseRootDir);
8259
8459
  const functionsIndexPath = path.join(functionsDir, "index.cjs");
8260
8460
  const runtimePackageInfo = await syncFunctionsPackageJson(functionsDir);
8261
8461
  const initializeVariable = await initFirebaseUser(tmpDir, savedInputs.projectId, nonInteractive, cliEnv, async (projectId) => {
@@ -8287,13 +8487,14 @@ const runInit = async ({ build, envFile }) => {
8287
8487
  projectId: initializeVariable.projectId,
8288
8488
  region: currentRegion
8289
8489
  };
8490
+ const persistCredentialInputs = await confirmInitInputPersistence({
8491
+ existingEnv: managedEnv,
8492
+ inputs: resolvedInputs,
8493
+ nonInteractive,
8494
+ provider: initProvider
8495
+ });
8290
8496
  const persistedInputs = getInitProviderEnvVars({
8291
- includeConsentInputs: await confirmInitInputPersistence({
8292
- existingEnv: managedEnv,
8293
- inputs: resolvedInputs,
8294
- nonInteractive,
8295
- provider: initProvider
8296
- }),
8497
+ includeConsentInputs: persistCredentialInputs,
8297
8498
  inputs: resolvedInputs,
8298
8499
  provider: initProvider
8299
8500
  });