@ghostlytools/cli 1.10.6 → 1.11.1

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.
Files changed (111) hide show
  1. package/README.md +27 -22
  2. package/SKILL.md +8 -5
  3. package/dist/assets/api-D89ubgas.js +3 -0
  4. package/dist/assets/{api-DppWqAP3.js → api-DL0Uazf6.js} +543 -204
  5. package/dist/assets/api-DL0Uazf6.js.map +1 -0
  6. package/dist/assets/{apiKit-DFIho4Ev.js → apiKit-D78MXTrk.js} +97 -13
  7. package/dist/assets/apiKit-D78MXTrk.js.map +1 -0
  8. package/dist/assets/{apps-yBnbEtfV.js → apps--pAqmfgQ.js} +16 -4
  9. package/dist/assets/apps--pAqmfgQ.js.map +1 -0
  10. package/dist/assets/{apps-1MkGMH8m.js → apps-BlSl1nGn.js} +1 -1
  11. package/dist/assets/{arkade-bFAS6imn.js → arkade-DxB-MR43.js} +2 -2
  12. package/dist/assets/{arkade-bFAS6imn.js.map → arkade-DxB-MR43.js.map} +1 -1
  13. package/dist/assets/{backup-vj4J7M3e.js → backup-B3JJd75o.js} +35 -7
  14. package/dist/assets/backup-B3JJd75o.js.map +1 -0
  15. package/dist/assets/{backup-ejIX59o7.js → backup-T7gFpU80.js} +1 -1
  16. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -1
  17. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
  18. package/dist/assets/{blobFiles-XZ9PEXYy.js → blobFiles-BmsrvZc3.js} +3 -3
  19. package/dist/assets/{blobFiles-XZ9PEXYy.js.map → blobFiles-BmsrvZc3.js.map} +1 -1
  20. package/dist/assets/{buttons-BoDMx3Ky.js → buttons-C1VbDihe.js} +61 -30
  21. package/dist/assets/buttons-C1VbDihe.js.map +1 -0
  22. package/dist/assets/buttons-DwWuK_uN.js +2 -0
  23. package/dist/assets/{client-BQArefYa.js → client-CGLuWFRV.js} +55 -10
  24. package/dist/assets/client-CGLuWFRV.js.map +1 -0
  25. package/dist/assets/{codec-_MwTUz5E.js → codec-YGJDr7uH.js} +2 -2
  26. package/dist/assets/{codec-_MwTUz5E.js.map → codec-YGJDr7uH.js.map} +1 -1
  27. package/dist/assets/{envelope-CeZBNGX-.js → envelope-Dwq8EN8x.js} +2 -2
  28. package/dist/assets/{envelope-CeZBNGX-.js.map → envelope-Dwq8EN8x.js.map} +1 -1
  29. package/dist/assets/{irohWeb-C_Wnw7Q9.js → fedimintSdk-CqTeMdF0.js} +2 -354
  30. package/dist/assets/fedimintSdk-CqTeMdF0.js.map +1 -0
  31. package/dist/assets/{fileBytes-DqnfKIkj.js → fileBytes-B0z9A6Le.js} +2 -2
  32. package/dist/assets/{fileBytes-DqnfKIkj.js.map → fileBytes-B0z9A6Le.js.map} +1 -1
  33. package/dist/assets/{fileBytes-BABGEF13.js → fileBytes-BLPZq9YU.js} +3 -3
  34. package/dist/assets/{fileBytes-BABGEF13.js.map → fileBytes-BLPZq9YU.js.map} +1 -1
  35. package/dist/assets/{fileBytes-CQQK2uOh.js → fileBytes-BtIyoDF2.js} +1 -1
  36. package/dist/assets/{fileBytesIdb-DrXmDUSy.js → fileBytesIdb-Bmlrl9EO.js} +3 -3
  37. package/dist/assets/{fileBytesIdb-DrXmDUSy.js.map → fileBytesIdb-Bmlrl9EO.js.map} +1 -1
  38. package/dist/assets/fileBytesIdb-D8mAK4pF.js +2 -0
  39. package/dist/assets/{fileBytesOpfs-udKCzcLe.js → fileBytesOpfs-DBS0kbPT.js} +3 -3
  40. package/dist/assets/{fileBytesOpfs-udKCzcLe.js.map → fileBytesOpfs-DBS0kbPT.js.map} +1 -1
  41. package/dist/assets/{fixedHosts-B_2Rvyja.js → fixedHosts-CINXidpd.js} +3 -3
  42. package/dist/assets/{fixedHosts-B_2Rvyja.js.map → fixedHosts-CINXidpd.js.map} +1 -1
  43. package/dist/assets/{host-DFLzzKNr.js → host-CGlHkiQv.js} +336 -84
  44. package/dist/assets/host-CGlHkiQv.js.map +1 -0
  45. package/dist/assets/{hyperdhtRelay-CV6qMrom.js → hyperdhtRelay-Bj5jJT5w.js} +2 -2
  46. package/dist/assets/{hyperdhtRelay-CV6qMrom.js.map → hyperdhtRelay-Bj5jJT5w.js.map} +1 -1
  47. package/dist/assets/{idb-BHsAqENE.js → idb-CEuoNsTv.js} +16 -5
  48. package/dist/assets/idb-CEuoNsTv.js.map +1 -0
  49. package/dist/assets/{groupFiles-D-ZUUHrx.js → irohWeb-CYn0uB_A.js} +471 -18
  50. package/dist/assets/irohWeb-CYn0uB_A.js.map +1 -0
  51. package/dist/assets/{main-DxRwajM_.js → main-CgLW_Gyx.js} +409 -126
  52. package/dist/assets/main-CgLW_Gyx.js.map +1 -0
  53. package/dist/assets/{mainline-Bx184Ixg.js → mainline-B0h8RchD.js} +2 -2
  54. package/dist/assets/{mainline-Bx184Ixg.js.map → mainline-B0h8RchD.js.map} +1 -1
  55. package/dist/assets/{networkReason-BlQhTbXk.js → networkReason-BBosp2KG.js} +4 -4
  56. package/dist/assets/{networkReason-BlQhTbXk.js.map → networkReason-BBosp2KG.js.map} +1 -1
  57. package/dist/assets/{nwc-B3-PHX0L.js → nwc-SSNS1aJ-.js} +4 -4
  58. package/dist/assets/nwc-SSNS1aJ-.js.map +1 -0
  59. package/dist/assets/{nwcProvider-BeQBPB2q.js → nwcProvider-BXqJmM98.js} +11 -3
  60. package/dist/assets/nwcProvider-BXqJmM98.js.map +1 -0
  61. package/dist/assets/{ownDid-DAzW-Urb.js → ownDid--DtH_Jdi.js} +2 -2
  62. package/dist/assets/{ownDid-DAzW-Urb.js.map → ownDid--DtH_Jdi.js.map} +1 -1
  63. package/dist/assets/{words-BvdNuw_v.js → ownStatus-CQPGjCUR.js} +56 -4
  64. package/dist/assets/ownStatus-CQPGjCUR.js.map +1 -0
  65. package/dist/assets/{profiles-Bg43mRXu.js → profiles-4UQ1Hsds.js} +22 -12
  66. package/dist/assets/profiles-4UQ1Hsds.js.map +1 -0
  67. package/dist/assets/{registry-CAk2-5BQ.js → registry-B6BXKv6Q.js} +1 -1
  68. package/dist/assets/{registry-BDnsZJBi.js → registry-BKCFTEYp.js} +123 -99
  69. package/dist/assets/registry-BKCFTEYp.js.map +1 -0
  70. package/dist/assets/{resolve-UAfshn6j.js → resolve-MFeFljsN.js} +2 -2
  71. package/dist/assets/{resolve-UAfshn6j.js.map → resolve-MFeFljsN.js.map} +1 -1
  72. package/dist/assets/{restoredRows-YhlbokEE.js → restoredRows-C3LcxmOw.js} +4 -4
  73. package/dist/assets/{restoredRows-YhlbokEE.js.map → restoredRows-C3LcxmOw.js.map} +1 -1
  74. package/dist/assets/{server-DYdR0_Fj.js → server-rHKhnog1.js} +2100 -685
  75. package/dist/assets/server-rHKhnog1.js.map +1 -0
  76. package/dist/assets/{src-BTRPAi5X.js → src-BzsyAvPf.js} +1604 -305
  77. package/dist/assets/src-BzsyAvPf.js.map +1 -0
  78. package/dist/assets/{sshForges-KtHK5x1x.js → sshForges-qITn-RoV.js} +2 -2
  79. package/dist/assets/{sshForges-KtHK5x1x.js.map → sshForges-qITn-RoV.js.map} +1 -1
  80. package/dist/assets/{translate-CYuygrvA.js → translate-Bkr_iDgp.js} +9 -7
  81. package/dist/assets/translate-Bkr_iDgp.js.map +1 -0
  82. package/dist/assets/{usdt-Dw9IENe_.js → usdt-Bp7T2iqt.js} +3 -3
  83. package/dist/assets/{usdt-Dw9IENe_.js.map → usdt-Bp7T2iqt.js.map} +1 -1
  84. package/dist/assets/{waitNotice-Ce3YCinu.js → waitNotice-Cn0WJ-He.js} +3 -1
  85. package/dist/assets/waitNotice-Cn0WJ-He.js.map +1 -0
  86. package/dist/ghostly.mjs +1 -1
  87. package/examples/claude-code-agent.sh +5 -0
  88. package/package.json +2 -2
  89. package/dist/assets/api-DppWqAP3.js.map +0 -1
  90. package/dist/assets/api-K-i5MrP-.js +0 -3
  91. package/dist/assets/apiKit-DFIho4Ev.js.map +0 -1
  92. package/dist/assets/apps-yBnbEtfV.js.map +0 -1
  93. package/dist/assets/backup-vj4J7M3e.js.map +0 -1
  94. package/dist/assets/buttons-BoDMx3Ky.js.map +0 -1
  95. package/dist/assets/buttons-DG1CKgAI.js +0 -2
  96. package/dist/assets/client-BQArefYa.js.map +0 -1
  97. package/dist/assets/fileBytesIdb-BtXATa7j.js +0 -2
  98. package/dist/assets/groupFiles-D-ZUUHrx.js.map +0 -1
  99. package/dist/assets/host-DFLzzKNr.js.map +0 -1
  100. package/dist/assets/idb-BHsAqENE.js.map +0 -1
  101. package/dist/assets/irohWeb-C_Wnw7Q9.js.map +0 -1
  102. package/dist/assets/main-DxRwajM_.js.map +0 -1
  103. package/dist/assets/nwc-B3-PHX0L.js.map +0 -1
  104. package/dist/assets/nwcProvider-BeQBPB2q.js.map +0 -1
  105. package/dist/assets/profiles-Bg43mRXu.js.map +0 -1
  106. package/dist/assets/registry-BDnsZJBi.js.map +0 -1
  107. package/dist/assets/server-DYdR0_Fj.js.map +0 -1
  108. package/dist/assets/src-BTRPAi5X.js.map +0 -1
  109. package/dist/assets/translate-CYuygrvA.js.map +0 -1
  110. package/dist/assets/waitNotice-Ce3YCinu.js.map +0 -1
  111. package/dist/assets/words-BvdNuw_v.js.map +0 -1
@@ -4746,12 +4746,12 @@ function findAppForbiddenKey(value) {
4746
4746
  var MAX_CLIENTS = 16;
4747
4747
  var SEMVER$1 = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
4748
4748
  var HOST = /^>=(0|[1-9]\d*)\.(0|[1-9]\d*)(\.(0|[1-9]\d*))?$/;
4749
- var SEGMENT$1 = /^[A-Za-z0-9._-]+$/;
4749
+ var SEGMENT$2 = /^[A-Za-z0-9._-]+$/;
4750
4750
  var codePoints = (s) => [...s].length;
4751
4751
  /** Text of several lines: no control character but the line feed. */
4752
4752
  var isText$2 = (v, max) => typeof v === "string" && codePoints(v) <= max && !/[^\P{Cc}\n]/u.test(v);
4753
4753
  var isSafeCount = (v, min) => typeof v === "number" && Number.isSafeInteger(v) && v >= min;
4754
- var isObject$5 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4754
+ var isObject$6 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4755
4755
  /**
4756
4756
  * An https URL as WISP 1200 takes one anywhere: at most 512 characters, no user or password, and on jsDelivr only
4757
4757
  * `https://cdn.jsdelivr.net/gh/<owner>/<repo>@<40-hex commit>/...`, since a branch, a tag, a range or `latest` is
@@ -4818,7 +4818,7 @@ function isAppLicense(value) {
4818
4818
  /** A path of a bundle: relative, `/`-separated, `[A-Za-z0-9._-]` per segment, no `.` or `..`, at most 128 bytes. */
4819
4819
  function isAppPath(value) {
4820
4820
  if (typeof value !== "string" || value.length < 1 || value.length > APP_BUNDLE_LIMITS.pathBytes) return false;
4821
- return value.split("/").every((s) => SEGMENT$1.test(s) && s !== "." && s !== "..");
4821
+ return value.split("/").every((s) => SEGMENT$2.test(s) && s !== "." && s !== "..");
4822
4822
  }
4823
4823
  var bad = (field, detail = `${field} is not valid`) => ({
4824
4824
  ok: false,
@@ -4830,7 +4830,7 @@ var bad = (field, detail = `${field} is not valid`) => ({
4830
4830
  * ignored unless `strict` (`AppManifestOptions`).
4831
4831
  */
4832
4832
  function checkAppManifest(value, options = {}) {
4833
- if (!isObject$5(value)) return bad("manifest", "The manifest is not an object");
4833
+ if (!isObject$6(value)) return bad("manifest", "The manifest is not an object");
4834
4834
  if (value.ghostlyApp !== void 0 && value.ghostlyApp !== 1) return {
4835
4835
  ok: false,
4836
4836
  reason: "unsupported-format",
@@ -4873,7 +4873,7 @@ function checkAppManifest(value, options = {}) {
4873
4873
  if (!Array.isArray(permissions) || new Set(permissions).size !== permissions.length || !permissions.every((p) => APP_PERMISSIONS.includes(p))) return bad("permissions");
4874
4874
  if (m.view !== void 0 && !APP_VIEWS.includes(m.view)) return bad("view", `view is "chat" or "full"`);
4875
4875
  const runtime = m.runtime;
4876
- if (!isObject$5(runtime)) return bad("runtime");
4876
+ if (!isObject$6(runtime)) return bad("runtime");
4877
4877
  for (const key of Object.keys(runtime)) {
4878
4878
  if (key === "host" || key === "clients") continue;
4879
4879
  if (options.strict) return {
@@ -4908,7 +4908,7 @@ function checkAppManifest(value, options = {}) {
4908
4908
  let previous = "";
4909
4909
  let screenshots = 0;
4910
4910
  for (const f of files) {
4911
- if (!isObject$5(f) || Object.keys(f).length !== 3 || !isAppPath(f.path) || !isSafeCount(f.size, 0) || !isAppHash(f.sha256)) return isObject$5(f) && typeof f.path === "string" && !isAppPath(f.path) ? {
4911
+ if (!isObject$6(f) || Object.keys(f).length !== 3 || !isAppPath(f.path) || !isSafeCount(f.size, 0) || !isAppHash(f.sha256)) return isObject$6(f) && typeof f.path === "string" && !isAppPath(f.path) ? {
4912
4912
  ok: false,
4913
4913
  reason: "bad-path",
4914
4914
  detail: f.path
@@ -4944,7 +4944,7 @@ function checkAppManifest(value, options = {}) {
4944
4944
  };
4945
4945
  }
4946
4946
  const entry = m.entry;
4947
- if (typeof entry !== "string" || !entry.endsWith(".html") || !files.some((f) => isObject$5(f) && f.path === entry)) return {
4947
+ if (typeof entry !== "string" || !entry.endsWith(".html") || !files.some((f) => isObject$6(f) && f.path === entry)) return {
4948
4948
  ok: false,
4949
4949
  reason: "bad-entry",
4950
4950
  detail: "The entry is not an .html file of the bundle"
@@ -6738,7 +6738,7 @@ function extractParamsFromSdp(sdp, { maxCandidates = 2, loopback = false, relayO
6738
6738
  if (currentMedia === "a" && opus === null && /^opus/i.test(rtpmap[2])) opus = pt;
6739
6739
  if (currentMedia === "v" && vp8 === null && /^VP8/i.test(rtpmap[2])) vp8 = pt;
6740
6740
  }
6741
- if (line.startsWith("a=candidate:")) candidates.push(line.substring(12));
6741
+ if (line.startsWith("a=candidate:") && line.split(" ")[1] === "1") candidates.push(line.substring(12));
6742
6742
  if (line.startsWith("a=ssrc:")) {
6743
6743
  const ssrcMatch = line.match(/^a=ssrc:(\d+)/);
6744
6744
  if (ssrcMatch) {
@@ -8405,6 +8405,8 @@ var LinkSession = class {
8405
8405
  upkeepOnly = false;
8406
8406
  /** The last write this link asked for was a background one (`retryDelay`). */
8407
8407
  wroteInBackground = false;
8408
+ /** The records built for a packet that did not go out, and what they say: a try again of the same reuses them (`publishOnce`). */
8409
+ unsent = null;
8408
8410
  pollTimer = null;
8409
8411
  heartbeatTimer = null;
8410
8412
  lastActivity = Date.now();
@@ -8859,7 +8861,7 @@ var LinkSession = class {
8859
8861
  this.wroteInBackground = options?.background === true;
8860
8862
  const held = this.transport.publishHeld?.(this.identity.pubKeyZ32, options);
8861
8863
  if (held) throw held;
8862
- const built = buildLinkRecords(this.identity.pubKeyZ32, {
8864
+ const state = {
8863
8865
  messages: this.sentBuffer,
8864
8866
  ackTimestamp: this.myAck,
8865
8867
  nick: this.nick,
@@ -8867,9 +8869,16 @@ var LinkSession = class {
8867
8869
  rtcSignal,
8868
8870
  services: advertise ? this.getServices() : void 0,
8869
8871
  transports: advertise ? this.transports : null
8870
- }, this.encKey);
8872
+ };
8873
+ const says = JSON.stringify(state);
8874
+ const built = this.unsent?.says === says ? this.unsent.built : buildLinkRecords(this.identity.pubKeyZ32, state, this.encKey);
8875
+ this.unsent = {
8876
+ says,
8877
+ built
8878
+ };
8871
8879
  keptMessages = built.keptMessages;
8872
8880
  await this.transport.publish(this.identity, built.records, options);
8881
+ this.unsent = null;
8873
8882
  } catch (error) {
8874
8883
  const ms = Date.now() - started, waiting = isDiscoveryBudgetError(error);
8875
8884
  traceLink(this.identity.pubKeyZ32, "publish", {
@@ -9004,7 +9013,7 @@ var LinkSession = class {
9004
9013
  receivedNew = true;
9005
9014
  if (fresh.length > 0) this.events.onMessages?.(fresh, batch);
9006
9015
  }
9007
- if (read && batch.packetTimestamp > this.peerPacketAt) this.peerPacketAt = batch.packetTimestamp;
9016
+ if (read && batch.packetTimestamp > this.peerPacketAt) this.peerPacketAt = Math.min(batch.packetTimestamp, Date.now() + PKARR_FUTURE_SKEW_MS);
9008
9017
  const seenAt = batch.packetTimestamp === wasSeen ? presenceSeenAt(this.presence) : Math.max(readBefore, Math.min(batch.packetTimestamp, Date.now()));
9009
9018
  const online = batch.services !== null && Date.now() - seenAt < 6e5;
9010
9019
  this.presence = {
@@ -10621,8 +10630,8 @@ var sameButtonText = (a, b) => a.trim().toLowerCase() === b.trim().toLowerCase()
10621
10630
  * them (one line, cleaned). `at` is the button that clashes, `with` the one it clashes with.
10622
10631
  */
10623
10632
  function buttonLabelClash(buttons) {
10624
- const labels = buttons.map((button) => isObject$4(button) ? cardLine(button.label, Infinity) : void 0);
10625
- const ids = buttons.map((button) => isObject$4(button) && typeof button.id === "string" ? button.id : void 0);
10633
+ const labels = buttons.map((button) => isObject$5(button) ? cardLine(button.label, Infinity) : void 0);
10634
+ const ids = buttons.map((button) => isObject$5(button) && typeof button.id === "string" ? button.id : void 0);
10626
10635
  for (const [at, label] of labels.entries()) {
10627
10636
  if (!label) continue;
10628
10637
  const twin = labels.findIndex((other, i) => i < at && !!other && sameButtonText(other, label));
@@ -10645,7 +10654,7 @@ function appCardId(ref) {
10645
10654
  }
10646
10655
  /** An app card's `sequence`: a whole number from 0 to 2^53 - 1. */
10647
10656
  var appSequence = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
10648
- var isObject$4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10657
+ var isObject$5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10649
10658
  /** One line of display text: runs of space (line breaks included) become one space, then the display rules for names. */
10650
10659
  function cardLine(value, max) {
10651
10660
  if (typeof value !== "string") return void 0;
@@ -10686,7 +10695,7 @@ function readLinks(raw) {
10686
10695
  if (!Array.isArray(raw)) return [];
10687
10696
  const links = [];
10688
10697
  for (const entry of raw.slice(0, STATUS_CARD_LIMITS.links)) {
10689
- if (!isObject$4(entry)) continue;
10698
+ if (!isObject$5(entry)) continue;
10690
10699
  const url = cardUrl(entry.url);
10691
10700
  if (!url) continue;
10692
10701
  const label = cardLine(entry.label, STATUS_CARD_LIMITS.linkLabel);
@@ -10709,7 +10718,7 @@ function readTags(raw) {
10709
10718
  return tags;
10710
10719
  }
10711
10720
  function readRun(raw, now) {
10712
- if (!isObject$4(raw)) return void 0;
10721
+ if (!isObject$5(raw)) return void 0;
10713
10722
  const at = time(raw.at, now + MESSAGE_CLOCK_SKEW_MS), result = oneOf(RUN_RESULTS, raw.result);
10714
10723
  if (!at || !result) return void 0;
10715
10724
  const summary = cardLine(raw.summary, STATUS_CARD_LIMITS.line);
@@ -10734,7 +10743,7 @@ function readUsage(raw, id, now) {
10734
10743
  const resetsAt = ahead(raw.resetsAt, now), updatedAt = time(raw.updatedAt, now + MESSAGE_CLOCK_SKEW_MS);
10735
10744
  const windows = [];
10736
10745
  if (Array.isArray(raw.windows)) for (const entry of raw.windows.slice(0, STATUS_CARD_LIMITS.usageWindows)) {
10737
- if (!isObject$4(entry)) continue;
10746
+ if (!isObject$5(entry)) continue;
10738
10747
  const name = cardLine(entry.window, STATUS_CARD_LIMITS.usageWindow), share = percent(entry.left);
10739
10748
  if (!name || share === void 0) continue;
10740
10749
  const at = ahead(entry.resetsAt, now);
@@ -10780,7 +10789,7 @@ function statusCardBytes(card) {
10780
10789
  * routine's next run up to a year ahead). The message is always kept: without a card it shows its text.
10781
10790
  */
10782
10791
  function readStatusCard(raw, now = Date.now()) {
10783
- if (!isObject$4(raw) || statusCardBytes(raw) > STATUS_CARD_LIMITS.bytes) return void 0;
10792
+ if (!isObject$5(raw) || statusCardBytes(raw) > STATUS_CARD_LIMITS.bytes) return void 0;
10784
10793
  const id = typeof raw.id === "string" && ID$4.test(raw.id) ? raw.id : void 0;
10785
10794
  if (!id) return void 0;
10786
10795
  if (raw.kind === "app") {
@@ -10819,7 +10828,7 @@ function readStatusCard(raw, now = Date.now()) {
10819
10828
  if (done === void 0 || total === void 0 || done > total) done = total = void 0;
10820
10829
  const step = cardLine(raw.step, STATUS_CARD_LIMITS.line), branch = cardLine(raw.branch, STATUS_CARD_LIMITS.branch);
10821
10830
  let pr;
10822
- if (isObject$4(raw.pr)) {
10831
+ if (isObject$5(raw.pr)) {
10823
10832
  const url = cardUrl(raw.pr.url);
10824
10833
  if (url) {
10825
10834
  const number = count(raw.pr.number, 1), additions = count(raw.pr.additions), deletions = count(raw.pr.deletions), files = count(raw.pr.files);
@@ -10837,7 +10846,7 @@ function readStatusCard(raw, now = Date.now()) {
10837
10846
  }
10838
10847
  const items = [];
10839
10848
  if (Array.isArray(raw.items)) for (const entry of raw.items.slice(0, STATUS_CARD_LIMITS.items)) {
10840
- if (!isObject$4(entry)) continue;
10849
+ if (!isObject$5(entry)) continue;
10841
10850
  const text = cardLine(entry.text, STATUS_CARD_LIMITS.line);
10842
10851
  if (text) items.push({
10843
10852
  text,
@@ -10896,7 +10905,7 @@ function readStatusCard(raw, now = Date.now()) {
10896
10905
  if (!Array.isArray(raw.buttons)) return void 0;
10897
10906
  const buttons = [], seen = /* @__PURE__ */ new Set();
10898
10907
  for (const entry of raw.buttons.slice(0, STATUS_CARD_LIMITS.buttons)) {
10899
- if (!isObject$4(entry) || typeof entry.id !== "string" || !BUTTON_ID.test(entry.id) || seen.has(entry.id)) continue;
10908
+ if (!isObject$5(entry) || typeof entry.id !== "string" || !BUTTON_ID.test(entry.id) || seen.has(entry.id)) continue;
10900
10909
  const label = cardLine(entry.label, STATUS_CARD_LIMITS.buttonLabel);
10901
10910
  if (!label) continue;
10902
10911
  seen.add(entry.id);
@@ -10925,7 +10934,7 @@ function readStatusCard(raw, now = Date.now()) {
10925
10934
  * at once and nothing it said is lost on the way. Line breaks and invisible characters are cleaned, as a reader would.
10926
10935
  */
10927
10936
  function checkStatusCard(raw, now = Date.now()) {
10928
- if (!isObject$4(raw)) return { error: "A card is an object" };
10937
+ if (!isObject$5(raw)) return { error: "A card is an object" };
10929
10938
  const bytes = statusCardBytes(raw);
10930
10939
  if (bytes > STATUS_CARD_LIMITS.bytes) return { error: `The card takes ${bytes} bytes; at most ${STATUS_CARD_LIMITS.bytes}` };
10931
10940
  if (raw.kind !== "task" && raw.kind !== "routine" && raw.kind !== "buttons" && raw.kind !== "app" && raw.kind !== "usage" && raw.kind !== "removed") return { error: "kind is task, routine, buttons, app, usage or removed" };
@@ -10942,7 +10951,7 @@ function checkStatusCard(raw, now = Date.now()) {
10942
10951
  if (raw.links !== void 0) {
10943
10952
  if (!Array.isArray(raw.links) || raw.links.length > STATUS_CARD_LIMITS.links) errors.push(`links is a list of at most ${STATUS_CARD_LIMITS.links}`);
10944
10953
  else for (const [i, link] of raw.links.entries()) {
10945
- if (!isObject$4(link)) {
10954
+ if (!isObject$5(link)) {
10946
10955
  errors.push(`links[${i}] is an object`);
10947
10956
  continue;
10948
10957
  }
@@ -10969,7 +10978,7 @@ function checkStatusCard(raw, now = Date.now()) {
10969
10978
  if (raw.windows !== void 0) {
10970
10979
  if (!Array.isArray(raw.windows) || raw.windows.length > STATUS_CARD_LIMITS.usageWindows) errors.push(`windows is a list of at most ${STATUS_CARD_LIMITS.usageWindows}`);
10971
10980
  else for (const [i, entry] of raw.windows.entries()) {
10972
- if (!isObject$4(entry)) {
10981
+ if (!isObject$5(entry)) {
10973
10982
  errors.push(`windows[${i}] is an object`);
10974
10983
  continue;
10975
10984
  }
@@ -10992,7 +11001,7 @@ function checkStatusCard(raw, now = Date.now()) {
10992
11001
  else {
10993
11002
  const ids = /* @__PURE__ */ new Set();
10994
11003
  for (const [i, button] of raw.buttons.entries()) {
10995
- if (!isObject$4(button)) {
11004
+ if (!isObject$5(button)) {
10996
11005
  errors.push(`buttons[${i}] is an object`);
10997
11006
  continue;
10998
11007
  }
@@ -11019,7 +11028,7 @@ function checkStatusCard(raw, now = Date.now()) {
11019
11028
  }
11020
11029
  errors.push(line("step", raw.step, STATUS_CARD_LIMITS.line), line("branch", raw.branch, STATUS_CARD_LIMITS.branch));
11021
11030
  if (raw.pr !== void 0) {
11022
- if (!isObject$4(raw.pr)) errors.push("pr is an object");
11031
+ if (!isObject$5(raw.pr)) errors.push("pr is an object");
11023
11032
  else {
11024
11033
  errors.push(url("pr.url", raw.pr.url), whole("pr.number", raw.pr.number, 1), whole("pr.additions", raw.pr.additions), whole("pr.deletions", raw.pr.deletions), whole("pr.files", raw.pr.files));
11025
11034
  if (raw.pr.state !== void 0 && !oneOf(PR_STATES, raw.pr.state)) errors.push(`pr.state is one of ${PR_STATES.join(", ")}`);
@@ -11051,7 +11060,7 @@ function checkStatusCard(raw, now = Date.now()) {
11051
11060
  if (raw.items !== void 0) {
11052
11061
  if (!Array.isArray(raw.items) || raw.items.length > STATUS_CARD_LIMITS.items) errors.push(`items is a list of at most ${STATUS_CARD_LIMITS.items}`);
11053
11062
  else for (const [i, item] of raw.items.entries()) {
11054
- if (!isObject$4(item)) {
11063
+ if (!isObject$5(item)) {
11055
11064
  errors.push(`items[${i}] is an object`);
11056
11065
  continue;
11057
11066
  }
@@ -11065,7 +11074,7 @@ function checkStatusCard(raw, now = Date.now()) {
11065
11074
  if (raw.cron !== void 0 && !(typeof raw.cron === "string" && CRON_LINE.test(raw.cron.trim()))) errors.push(`cron is a cron line of at most ${STATUS_CARD_LIMITS.cron} characters`);
11066
11075
  if (raw.nextRunAt !== void 0 && !(typeof raw.nextRunAt === "number" && Number.isSafeInteger(raw.nextRunAt) && raw.nextRunAt > 0 && raw.nextRunAt <= now + STATUS_CARD_LIMITS.nextRunMs)) errors.push("nextRunAt is a time in milliseconds, within a year");
11067
11076
  const run = (field, value) => {
11068
- if (!isObject$4(value)) return errors.push(`${field} is an object`);
11077
+ if (!isObject$5(value)) return errors.push(`${field} is an object`);
11069
11078
  if (!(typeof value.at === "number" && Number.isSafeInteger(value.at) && value.at > 0 && value.at <= now + 3e5)) errors.push(`${field}.at is a time in milliseconds, not in the future`);
11070
11079
  if (!oneOf(RUN_RESULTS, value.result)) errors.push(`${field}.result is one of ${RUN_RESULTS.join(", ")}`);
11071
11080
  errors.push(line(`${field}.summary`, value.summary, STATUS_CARD_LIMITS.line));
@@ -11191,14 +11200,41 @@ var REPLY_ID = /^[A-Za-z0-9_:.-]{1,128}$/;
11191
11200
  var PAIRED_REPLY_AUTHORS = ["sender", "recipient"];
11192
11201
  /** A picture sent inline has no line worth quoting. */
11193
11202
  var INLINE_PICTURE = /^data:image\//i;
11194
- /**
11195
- * A line of a message to quote: plain text on one line (line breaks and runs of spaces become one space), without
11196
- * control, invisible or direction characters (WISP 400, as for names), at most `REPLY_LIMITS.snippet` code points,
11197
- * the last of them an ellipsis when it was cut.
11203
+ /** What a spoiler reads as in a line of it: nothing of what it hides (the chat list's `SPOILER_PLAIN` in apps/ui). */
11204
+ var SPOILER_COVER = "▒▒▒";
11205
+ var PIPES = /\|{2,}/gu;
11206
+ var SPACE$1 = /\s/u;
11207
+ var PUNCT = /[\p{P}\p{S}]/u;
11208
+ /**
11209
+ * A line of text with its spoilers (`||hidden||`, WISP 400 § Formatting) as `SPOILER_COVER`. The bubble's parser
11210
+ * (apps/ui lib/parse) is not here, so this covers at least what it hides: from the first `||` on the line that may
11211
+ * open one to the last that may close one, by the parser's word-edge rules without its exceptions. Two spoilers on a
11212
+ * line read as one, with the words between them. `open`: the line goes on past this text, so a spoiler opened on it
11213
+ * runs to its end.
11214
+ */
11215
+ function coverSpoilers(line, open) {
11216
+ let start = -1, end = -1;
11217
+ for (const run of line.matchAll(PIPES)) {
11218
+ const at = run.index, after = line[at + run[0].length], before = line[at - 1];
11219
+ const long = run[0].length > 2;
11220
+ if (start < 0) {
11221
+ if (long || after !== void 0 && !SPACE$1.test(after) && (before === void 0 || SPACE$1.test(before) || PUNCT.test(before))) start = at;
11222
+ } else if (long || before !== void 0 && !SPACE$1.test(before) && (after === void 0 || SPACE$1.test(after) || PUNCT.test(after))) end = at + run[0].length;
11223
+ }
11224
+ if (start < 0) return line;
11225
+ if (open) return line.slice(0, start) + SPOILER_COVER;
11226
+ return end < 0 ? line : line.slice(0, start) + SPOILER_COVER + line.slice(end);
11227
+ }
11228
+ /**
11229
+ * A line of a message to quote: plain text on one line (line breaks and runs of spaces become one space), its
11230
+ * spoilers covered, without control, invisible or direction characters (WISP 400, as for names), at most
11231
+ * `REPLY_LIMITS.snippet` code points, the last of them an ellipsis when it was cut.
11198
11232
  */
11199
11233
  function replySnippet(text) {
11200
11234
  if (INLINE_PICTURE.test(text.trimStart())) return "🖼️ Picture";
11201
- const clean = sanitizeDisplayText(text.slice(0, REPLY_LIMITS.raw * 2).replace(/\s+/gu, " "), REPLY_LIMITS.snippet + 1) ?? "";
11235
+ const head = text.slice(0, REPLY_LIMITS.raw * 2);
11236
+ const lines = head.split("\n");
11237
+ const clean = sanitizeDisplayText(lines.map((line, i) => coverSpoilers(line, head.length < text.length && i === lines.length - 1)).join("\n").replace(/\s+/gu, " "), REPLY_LIMITS.snippet + 1) ?? "";
11202
11238
  const points = [...clean];
11203
11239
  return points.length > REPLY_LIMITS.snippet ? `${points.slice(0, REPLY_LIMITS.snippet - 1).join("").trimEnd()}…` : clean;
11204
11240
  }
@@ -12256,11 +12292,23 @@ var MAX_ATTEMPTS = 8;
12256
12292
  * nothing; one the budget turned away is not used again, as it may have gone out on the DHT (the CLI puts there too).
12257
12293
  */
12258
12294
  var SEQUENCE_BLOCK = 64;
12295
+ /** The longest the relays' request budget holds publications back (`budgetUntil`). */
12296
+ var BUDGET_HOLD_MAX_MS = 6e4;
12297
+ /** The longest wait `backoff` gives. */
12298
+ var BACKOFF_MAX_MS = 6e4;
12259
12299
  /** The wait before publication attempt `attempts + 1` of a text, or of a receipt the contact still asks for. */
12260
- var backoff = (attempts) => Math.min(6e4, 4e3 * 2 ** attempts);
12300
+ var backoff = (attempts) => Math.min(BACKOFF_MAX_MS, 4e3 * 2 ** attempts);
12261
12301
  /**
12262
- * The contact's mailbox is read this often while this side is DHT-only (a contact that chose it is read at the chat's
12263
- * pace: `ACTIVE_DHT_POLL_MS` open, or on a daemon, `peerDhtPollMs`), and otherwise…
12302
+ * A time this side set by its clock, at most `ms` after the moment it was set, read back `now`. One further ahead was set
12303
+ * before the device clock went back (an NTP step, a clock that ran ahead set right): it counts from now, not for as long
12304
+ * as the clock went back, as `relay.ts` counts its budget times. One already past (the clock set forward) stays past:
12305
+ * what it timed ends early, never late.
12306
+ */
12307
+ var bounded = (at, now, ms = 0) => Math.min(at, now + ms);
12308
+ /**
12309
+ * The contact's mailbox is read this often while this side is DHT-only, unless that contact is away with nothing of
12310
+ * ours waiting on it (`dhtOnlyIdle`; a contact that chose it is read at the chat's pace: `ACTIVE_DHT_POLL_MS` open,
12311
+ * or on a daemon, `peerDhtPollMs`), and otherwise…
12264
12312
  */
12265
12313
  var DHT_POLL_MS = 4e3;
12266
12314
  var STREAM_POLL_MS = 3e4;
@@ -12762,6 +12810,41 @@ var DhtDelivery = class DhtDelivery {
12762
12810
  if (active && !this.live) this.tick();
12763
12811
  else this.schedule();
12764
12812
  }
12813
+ /**
12814
+ * The device clock now, with every time this side set by it kept no further ahead than it is ever set (`bounded`).
12815
+ * The outbox times a text's receipt on a timer, which a step of the clock does not move; these times are judged by
12816
+ * the clock. Taken as they were, a clock set back an hour (or one an hour ahead set right) while a text awaited its
12817
+ * receipt held every later text of the chat for that hour though the outbox showed the text failed at five minutes,
12818
+ * the text was not published again meanwhile and the chat read every 4 s; and a contact away counted as there, its
12819
+ * mailbox read every 4 s for most of the hour (bug hunt, 2026-11-08). Kept so in memory; the next save writes them.
12820
+ */
12821
+ clock() {
12822
+ const now = Date.now(), { pending, receipt } = this.state;
12823
+ if (pending && (pending.expires > now + 3e5 || pending.next > now + BACKOFF_MAX_MS)) this.state = {
12824
+ ...this.state,
12825
+ pending: {
12826
+ ...pending,
12827
+ expires: bounded(pending.expires, now, DHT_MESSAGE_TTL),
12828
+ next: bounded(pending.next, now, BACKOFF_MAX_MS)
12829
+ }
12830
+ };
12831
+ if (receipt && (receipt.expires > now + 3e5 || (receipt.next ?? 0) > now + BACKOFF_MAX_MS)) this.state = {
12832
+ ...this.state,
12833
+ receipt: {
12834
+ ...receipt,
12835
+ expires: bounded(receipt.expires, now, DHT_MESSAGE_TTL),
12836
+ ...receipt.next !== void 0 && { next: bounded(receipt.next, now, BACKOFF_MAX_MS) }
12837
+ }
12838
+ };
12839
+ this.peerNewAt = bounded(this.peerNewAt, now);
12840
+ this.lastPublish = bounded(this.lastPublish, now);
12841
+ this.networkBackAt = bounded(this.networkBackAt, now);
12842
+ this.pinnedProbeAt = bounded(this.pinnedProbeAt, now);
12843
+ this.controlDue = bounded(this.controlDue, now, Math.max(24e4, UNUSED_INVITE_UPKEEP_MS, this.options.firstControlAfterMs ?? 0));
12844
+ this.budgetUntil = bounded(this.budgetUntil, now, BUDGET_HOLD_MAX_MS);
12845
+ this.leavingUntil = bounded(this.leavingUntil, now, LEAVING_DHT_FAST_MS);
12846
+ return now;
12847
+ }
12765
12848
  validate(text, timestamp, id, reply, edit) {
12766
12849
  if (this.options.peerAcceptsText?.() === false) return DHT_TEXT_REFUSED;
12767
12850
  if (this.forwardSecrecy === "stopped") return DHT_RATCHET_STOPPED;
@@ -12769,7 +12852,7 @@ var DhtDelivery = class DhtDelivery {
12769
12852
  if (edit !== void 0 && (reply !== void 0 || !ID$2.test(edit[0]) || !validEditNumber(edit[1]))) return "Invalid message.";
12770
12853
  if (utf8Encode(text).length > 256) return DHT_TEXT_TOO_LONG;
12771
12854
  if (/cashu[AB][A-Za-z0-9_-]+/i.test(text)) return "Payment tokens cannot be sent through DHT delivery.";
12772
- const now = Date.now(), pending = this.state.pending;
12855
+ const now = this.clock(), pending = this.state.pending;
12773
12856
  if (pending && pending.expires > now && pending.message[0] !== id) return "One DHT text can await a receipt at a time. Wait for its receipt or expiry before sending another.";
12774
12857
  if (pending?.message[0] === id && pending.expires > now && pending.attempts >= MAX_ATTEMPTS) return "DHT retry budget exhausted. Wait for expiry before retrying this message.";
12775
12858
  const next = pending?.message[0] === id && pending.expires > now ? pending : {
@@ -12955,8 +13038,8 @@ var DhtDelivery = class DhtDelivery {
12955
13038
  }
12956
13039
  /** The id of what awaits its receipt on the floor now, if anything does. */
12957
13040
  get pendingId() {
12958
- const pending = this.state.pending;
12959
- return pending && pending.expires > Date.now() && pending.attempts < MAX_ATTEMPTS ? pending.message[0] : void 0;
13041
+ const now = this.clock(), pending = this.state.pending;
13042
+ return pending && pending.expires > now && pending.attempts < MAX_ATTEMPTS ? pending.message[0] : void 0;
12960
13043
  }
12961
13044
  /**
12962
13045
  * This side's capability record has a new revision (WISP 03): an envelope names it now. Otherwise the contact
@@ -12967,7 +13050,7 @@ var DhtDelivery = class DhtDelivery {
12967
13050
  await this.serialize(async () => {
12968
13051
  const rev = this.options.capsRev?.();
12969
13052
  if (rev === void 0 || rev === this.namedRev) return;
12970
- const wait = this.lastPublish + 4e3 - Date.now();
13053
+ const wait = this.lastPublish + 4e3 - this.clock();
12971
13054
  if (wait > 0) {
12972
13055
  this.announceTimer ??= setTimeout(() => {
12973
13056
  this.announceTimer = null;
@@ -13062,7 +13145,7 @@ var DhtDelivery = class DhtDelivery {
13062
13145
  };
13063
13146
  }
13064
13147
  async publish(force = false) {
13065
- const now = Date.now();
13148
+ const now = this.clock();
13066
13149
  if (!this.running || !force && (now - this.lastPublish < 4e3 || now < this.budgetUntil)) return;
13067
13150
  const pending = this.state.pending && this.state.pending.expires > now && this.state.pending.attempts < MAX_ATTEMPTS ? this.state.pending : void 0;
13068
13151
  const receipt = this.state.receipt && this.state.receipt.expires > now && this.state.receipt.attempts < MAX_ATTEMPTS ? this.state.receipt : void 0;
@@ -13141,7 +13224,7 @@ var DhtDelivery = class DhtDelivery {
13141
13224
  * receipt as they were before, and no publication before then (`budgetUntil`) but a forced one.
13142
13225
  */
13143
13226
  async heldBack(error, now, before, pending, receipt) {
13144
- const at = now + budgetRetryMs(error, 1e3, 6e4);
13227
+ const at = now + budgetRetryMs(error, 1e3, BUDGET_HOLD_MAX_MS);
13145
13228
  this.budgetUntil = at;
13146
13229
  this.lastPublish = before.lastPublish;
13147
13230
  this.controlDue = Math.min(before.controlDue, at);
@@ -13528,15 +13611,29 @@ var DhtDelivery = class DhtDelivery {
13528
13611
  if (this.options.pollMs) return this.options.pollMs;
13529
13612
  const taken = this.takenInviteWait();
13530
13613
  if (taken !== void 0) return taken;
13531
- const now = Date.now();
13614
+ const now = this.clock();
13532
13615
  const unused = this.running ? this.unusedInviteAge(now) : void 0;
13533
13616
  const readers = countUnusedInvite(this.options.transport, this, unused !== void 0 && !this.active && now >= this.fastUntil);
13534
13617
  if (unused !== void 0 && !this.active && now >= this.fastUntil) return unusedInviteWait(unused, this.mode === "dht" ? DHT_POLL_MS : STREAM_POLL_MS, readers);
13535
- if (this.mode === "dht" || this.state.peerMode === "dht" && now < this.leavingUntil || now < this.fastUntil) return DHT_POLL_MS;
13618
+ if (this.mode === "dht" && !this.dhtOnlyIdle(now) || this.state.peerMode === "dht" && now < this.leavingUntil || now < this.fastUntil) return DHT_POLL_MS;
13536
13619
  if (this.live) return LIVE_POLL_MS;
13537
13620
  if (this.state.pending && this.state.pending.expires > now) return DHT_POLL_MS;
13538
13621
  if (this.active) return ACTIVE_DHT_POLL_MS;
13539
- return this.state.peerMode === "dht" && this.options.peerDhtPollMs ? Math.min(this.options.peerDhtPollMs, STREAM_POLL_MS) : STREAM_POLL_MS;
13622
+ const there = now - this.peerNewAt < PRESENCE_WINDOW;
13623
+ return this.state.peerMode === "dht" && this.options.peerDhtPollMs && there ? Math.min(this.options.peerDhtPollMs, STREAM_POLL_MS) : STREAM_POLL_MS;
13624
+ }
13625
+ /**
13626
+ * This side is DHT only, and nothing waits on the contact's mailbox: the contact, pinned, is away (nothing new of its
13627
+ * own in `PRESENCE_WINDOW`; it puts a keep-alive every four minutes while there), no text of ours awaits its receipt,
13628
+ * and the chat is not on screen. Its mailbox is then read at the background pace, as background reads, not every 4 s:
13629
+ * a daemon with 50 such chats looked each contact up on the Mainline DHT every ~3 s, 1,081 lookups a minute for as
13630
+ * long as it ran, since its relays' budget held those reads and a held read nobody marked background goes to the DHT.
13631
+ * The contact's next envelope (its first on coming back, or a text) is read at the next of those reads, and the
13632
+ * 4 s pace is back from there. Just started, a contact there is read so until its next envelope too.
13633
+ */
13634
+ dhtOnlyIdle(now) {
13635
+ if (this.active || !this.options.credentials.peerKey || now - this.peerNewAt < 6e5) return false;
13636
+ return !(this.state.pending && this.state.pending.expires > now);
13540
13637
  }
13541
13638
  /**
13542
13639
  * How long ago this side's invite was made (or joined), while nobody used it (or its inviter never answered,
@@ -13562,7 +13659,7 @@ var DhtDelivery = class DhtDelivery {
13562
13659
  schedule() {
13563
13660
  if (!this.running || this.ticking) return;
13564
13661
  if (this.timer) clearTimeout(this.timer);
13565
- const held = this.budgetUntil - Date.now();
13662
+ const held = this.budgetUntil - this.clock();
13566
13663
  const due = this.reactionsDue || this.resealDue && !this.errors.publish ? Math.max(0, this.lastPublish + 4e3 - Date.now(), held) : Infinity;
13567
13664
  const readHeld = this.readHeldUntil > 0 ? Math.max(1e3, this.readHeldUntil - Date.now()) : Infinity;
13568
13665
  this.timer = setTimeout(() => void this.tick(), Math.min(held > 0 ? Math.min(this.pollMs, held) : this.pollMs, due, readHeld));
@@ -14656,17 +14753,28 @@ function relayedTransports(local, remote) {
14656
14753
  /** Symmetric rank sum; the fixed order breaks ties deterministically. Neither
14657
14754
  * a remote list nor a preference can add an unavailable local adapter. A
14658
14755
  * relayed transport ranks after every direct one: it is where a failed direct
14659
- * path goes, never ahead of one that works. */
14756
+ * path goes, never ahead of one that works. Iroh through its relay is the
14757
+ * exception (WISP 100, revision 2026-11-08): it comes back almost at once after
14758
+ * the app was away, and a browser's Iroh is never anything else. */
14660
14759
  function rankTransports(local, remote, relayed = []) {
14661
- const penalty = (t) => relayed.includes(t) ? 1 : 0;
14760
+ const penalty = (t) => t !== "iroh/1" && relayed.includes(t) ? 1 : 0;
14662
14761
  return TRANSPORTS.filter((t) => local.includes(t) && remote.includes(t)).sort((a, b) => penalty(a) - penalty(b) || local.indexOf(a) + remote.indexOf(a) - (local.indexOf(b) + remote.indexOf(b)) || TRANSPORTS.indexOf(a) - TRANSPORTS.indexOf(b));
14663
14762
  }
14664
14763
  /**
14665
- * What a chat prefers when nobody chose (Automatic): WebRTC where the app has it, else the first transport it has
14666
- * (a Linux Desktop: WebKitGTK has no WebRTC). With nothing at all, WebRTC, which the offer then leaves out.
14764
+ * What a chat prefers when nobody chose (Automatic): Iroh where the app has it, then WebRTC, then HyperDHT (WISP 100,
14765
+ * revision 2026-11-08). Every app puts Iroh first, so the rank sum of two apps that both run it puts it first on both
14766
+ * sides. With nothing at all, WebRTC, which the offer then leaves out.
14767
+ * With Fallback off the chat may use only that one transport, and nothing moves it off a relayed Iroh then: WebRTC
14768
+ * where the app has it, else the first transport it has (a Linux Desktop: WebKitGTK has no WebRTC), as before.
14667
14769
  */
14668
- function automaticTransport(available) {
14669
- return available.includes("webrtc/1") ? "webrtc/1" : TRANSPORTS.find((t) => available.includes(t)) ?? "webrtc/1";
14770
+ var AUTOMATIC_ORDER = [
14771
+ "iroh/1",
14772
+ "webrtc/1",
14773
+ "hyperdht/1"
14774
+ ];
14775
+ function automaticTransport(available, fallback = true) {
14776
+ if (!fallback) return available.includes("webrtc/1") ? "webrtc/1" : TRANSPORTS.find((t) => available.includes(t)) ?? "webrtc/1";
14777
+ return AUTOMATIC_ORDER.find((t) => available.includes(t)) ?? "webrtc/1";
14670
14778
  }
14671
14779
  function transportOrder(available, preferred, fallback) {
14672
14780
  const rest = TRANSPORTS.filter((t) => available.includes(t) && t !== preferred);
@@ -14674,6 +14782,8 @@ function transportOrder(available, preferred, fallback) {
14674
14782
  }
14675
14783
  var POLICY_RECEIVE_WINDOW_MS = 6e4;
14676
14784
  var allowedTransports = (policy) => transportOrder(policy.available, policy.preferred, policy.fallback);
14785
+ /** The first ranked transport that is not relayed. */
14786
+ var directFirst = (ranked, relayed) => ranked.find((t) => !relayed.includes(t));
14677
14787
  function parsePolicy(raw) {
14678
14788
  if (!raw || typeof raw !== "object") return null;
14679
14789
  const p = raw;
@@ -14751,7 +14861,7 @@ var TransportSwitch = class {
14751
14861
  if (!this.context || !this.remote) return void 0;
14752
14862
  const local = this.local(), remote = this.remote, winner = this.winner(local, remote);
14753
14863
  return {
14754
- transport: this.choices(local, remote)[0] ?? winner.preferred,
14864
+ transport: (this.isUpgrade(local, remote) ? this.actual : void 0) ?? this.choices(local, remote)[0] ?? winner.preferred,
14755
14865
  ...winner.intent > 0 ? { by: winner === local ? "you" : "contact" } : {}
14756
14866
  };
14757
14867
  }
@@ -14945,12 +15055,17 @@ var TransportSwitch = class {
14945
15055
  const ranked = rankTransports(allowedTransports(local), allowedTransports(remote), relayed);
14946
15056
  if (!ranked.length) return [];
14947
15057
  const winner = this.winner(local, remote);
14948
- const target = this.upgrading(winner, ranked, relayed) ? ranked[0] : winner.intent === 0 && this.actual && ranked.includes(this.actual) ? this.actual : ranked.includes(winner.preferred) ? winner.preferred : ranked[0];
15058
+ const target = this.upgrading(winner, ranked, relayed) ? directFirst(ranked, relayed) : winner.intent === 0 && this.actual && ranked.includes(this.actual) ? this.actual : ranked.includes(winner.preferred) ? winner.preferred : ranked[0];
14949
15059
  return [target, ...local.fallback && remote.fallback ? ranked.filter((t) => t !== target) : []];
14950
15060
  }
14951
- /** Nobody chose, the session is on a relayed transport, a direct one ranks first, and both sides move (`upgrade/1`). */
15061
+ /**
15062
+ * Nobody chose, the session is on a relayed transport, a direct one is ranked, and both sides move (`upgrade/1`). The
15063
+ * first direct one, not the first ranked: Iroh through its relay ranks first so that a chat comes back over it at once
15064
+ * (WISP 100, revision 2026-11-08), and the session then moves to the direct path, which carries files many times faster.
15065
+ */
14952
15066
  upgrading(winner, ranked, relayed) {
14953
- return winner.intent === 0 && !!this.actual && relayed.includes(this.actual) && ranked.includes(this.actual) && ranked[0] !== this.actual && !relayed.includes(ranked[0]) && !!this.options.upgrade?.();
15067
+ const direct = directFirst(ranked, relayed);
15068
+ return winner.intent === 0 && !!this.actual && relayed.includes(this.actual) && ranked.includes(this.actual) && !!direct && direct !== this.actual && !!this.options.upgrade?.();
14954
15069
  }
14955
15070
  isUpgrade(local, remote) {
14956
15071
  const relayed = relayedTransports(local.descriptors, remote.descriptors);
@@ -15644,7 +15759,8 @@ function applyIdentityEvent(timeline, event, at) {
15644
15759
  reason: event.reason
15645
15760
  });
15646
15761
  break;
15647
- case "unsent": if (last?.kind === "shared" && last.state === "verifying") out.splice(i, 1);
15762
+ case "unsent":
15763
+ case "unanswered": if (last?.kind === "shared" && last.state === "verifying") out.splice(i, 1);
15648
15764
  }
15649
15765
  return out.length > 100 ? out.slice(-100) : out;
15650
15766
  }
@@ -15679,6 +15795,8 @@ var IDENTITY_MAX_VALIDITY = 3456e4;
15679
15795
  var IDENTITY_MAX_EVIDENCE = 16384;
15680
15796
  /** Unanswered challenges a verifier keeps per conversation. */
15681
15797
  var MAX_CHALLENGES = 8;
15798
+ /** A challenge still open at `now` (seconds): a presentation for it is still taken. */
15799
+ var liveAt = (c, now) => c.issuedAt > now - 300;
15682
15800
  var IDENTITY_FRAME_WINDOW_MS = 6e4;
15683
15801
  var IDENTITY_PROVIDER_ID = /^[a-z][a-z0-9-]{0,31}$/;
15684
15802
  /** Printable ASCII without spaces, so the statement can be built but never needs parsing. */
@@ -15953,6 +16071,28 @@ var IdentityExchange = class {
15953
16071
  this.requested.clear();
15954
16072
  this.peerProviders = void 0;
15955
16073
  }
16074
+ /**
16075
+ * The challenges whose window ended unanswered go, and with them their requests' lines still verifying: a contact
16076
+ * whose app closed, or whose proof left its profile, before it presented tells this side nothing, and its line read
16077
+ * "verifying" for good. No write when none ended.
16078
+ */
16079
+ async expire() {
16080
+ const now = this.now();
16081
+ if (!this.options.storage.read().challenges.some((c) => !liveAt(c, now))) return;
16082
+ await this.options.storage.update((l) => this.withoutExpired(l, now));
16083
+ }
16084
+ withoutExpired(l, now) {
16085
+ const live = l.challenges.filter((c) => liveAt(c, now));
16086
+ if (live.length === l.challenges.length) return l;
16087
+ return [...new Set(l.challenges.filter((c) => c.id !== void 0 && !liveAt(c, now) && !live.some((x) => x.id === c.id)).map((c) => c.id))].reduce((out, proof) => this.log(out, {
16088
+ type: "unanswered",
16089
+ side: "theirs",
16090
+ proof
16091
+ }), {
16092
+ ...l,
16093
+ challenges: live
16094
+ });
16095
+ }
15956
16096
  /** Share a proof of this profile with this contact: now if connected, else when it next is. */
15957
16097
  async share(id, connected) {
15958
16098
  const local = await this.options.localProof(id);
@@ -16209,17 +16349,16 @@ var IdentityExchange = class {
16209
16349
  id
16210
16350
  };
16211
16351
  await this.options.storage.update((l) => {
16212
- const live = l.challenges.filter((c) => c.issuedAt > now - 300);
16213
- if (live.length >= MAX_CHALLENGES) throw new Error("Too many identity challenges");
16214
- return this.log({
16352
+ if (l.challenges.filter((c) => liveAt(c, now)).length >= MAX_CHALLENGES) throw new Error("Too many identity challenges");
16353
+ return this.withoutExpired(this.log({
16215
16354
  ...l,
16216
- challenges: [...live, challenge]
16355
+ challenges: [...l.challenges, challenge]
16217
16356
  }, {
16218
16357
  type: "shared",
16219
16358
  side: "theirs",
16220
16359
  proof: id,
16221
16360
  provider
16222
- });
16361
+ }), now);
16223
16362
  });
16224
16363
  this.send({
16225
16364
  t: "idp-challenge",
@@ -16286,7 +16425,7 @@ var IdentityExchange = class {
16286
16425
  const id = statement.id;
16287
16426
  const scope = this.incomingScope();
16288
16427
  const now = this.now();
16289
- const challengeOf = (l) => l.challenges.find((c) => c.nonce === nonce && c.issuedAt === issuedAt && c.provider === binding.provider && c.issuedAt > now - 300);
16428
+ const challengeOf = (l) => l.challenges.find((c) => c.nonce === nonce && c.issuedAt === issuedAt && c.provider === binding.provider && liveAt(c, now));
16290
16429
  const known = (l) => !!challengeOf(l);
16291
16430
  if (!known(this.options.storage.read())) throw new Error("Unknown or reused identity challenge");
16292
16431
  let verified;
@@ -17489,6 +17628,11 @@ var FILES_CAPABILITY = "files/3";
17489
17628
  var FILES_BINARY_CAPABILITY = "files/4";
17490
17629
  /** The typing indicator: `paired-typing` frames on this session, 1:1 chats only (WISP 401 § Typing, `pairedTyping.ts`). */
17491
17630
  var TYPING_CAPABILITY = "typing/1";
17631
+ /**
17632
+ * Presence and a set status: `paired-status` frames on this session, 1:1 chats only (WISP 401 § Presence and status,
17633
+ * `pairedStatus.ts`).
17634
+ */
17635
+ var STATUS_CAPABILITY = "status/1";
17492
17636
  /** Reactions to messages: `paired-reaction` frames on this session, 1:1 chats only (WISP 401 § Reactions, `reactions.ts`). */
17493
17637
  var REACTIONS_CAPABILITY = "react/1";
17494
17638
  /** Editing sent texts: `paired-edit` frames on this session, 1:1 chats only (WISP 401 § Edits, `pairedEdits.ts`). */
@@ -17533,6 +17677,7 @@ var KNOWN_SESSION_CAPABILITIES = [
17533
17677
  FILES_CAPABILITY,
17534
17678
  FILES_BINARY_CAPABILITY,
17535
17679
  TYPING_CAPABILITY,
17680
+ STATUS_CAPABILITY,
17536
17681
  REACTIONS_CAPABILITY,
17537
17682
  EDIT_CAPABILITY,
17538
17683
  WAKE_SESSION_CAPABILITY,
@@ -17937,7 +18082,7 @@ var APP_RANGE_LIMITS = {
17937
18082
  bytesPerSecond: 33554432
17938
18083
  };
17939
18084
  /**
17940
- * What an `ar-err` says. `not-served`: no serve of that id on this session (never given, or ended); `changed` and
18085
+ * What an `ar-err` says. `not-served`: no serve of that id (never given, or ended); `changed` and
17941
18086
  * `gone`: the file under it, as `files.read` says them; `busy`: past the requests the server takes in flight. A
17942
18087
  * later version may add one: an asker reads a code it does not know as a failure.
17943
18088
  */
@@ -18122,12 +18267,13 @@ function decodeAppRangeData(message) {
18122
18267
  var slot = (app, request) => `${app}:${request}`;
18123
18268
  /**
18124
18269
  * The read lane of one chat, both ways (WISP 1200 § A read lane to the contact). As the side that serves it keeps the
18125
- * serve ids it gave out on this session and answers the contact's `ar-get` for those only, at most
18270
+ * serve ids it gave out and answers the contact's `ar-get` for those only, at most
18126
18271
  * `APP_RANGE_LIMITS.inFlight` per app and `bytesPerSecond` asked in all (`busy` past either); the bytes themselves
18127
18272
  * are read and sent by the session, which calls `finish` or `fail` for each task. As the side that asks it sends at
18128
18273
  * most `inFlight` requests per app, keeps
18129
- * the rest waiting, and puts each answer back together, in order, from the offset asked. Serves and requests last one
18130
- * session: `reset` ends them all, `closeApp` those of one app; a task still being read counts until it is settled.
18274
+ * the rest waiting, and puts each answer back together, in order, from the offset asked. Requests last one session
18275
+ * (`suspend` ends them); serves last until the app closes on either side (`closeApp`) or the session ends for good
18276
+ * (`reset`, which ends both). A task still being read counts until it is settled.
18131
18277
  */
18132
18278
  var AppRanges = class {
18133
18279
  send;
@@ -18158,8 +18304,8 @@ var AppRanges = class {
18158
18304
  this.now = now;
18159
18305
  }
18160
18306
  /**
18161
- * Lets the contact's `app` read `file` on this session: the serve id to tell it. A file the app serves already answers
18162
- * the id it has, so an app that serves again on each play holds one serve per file, not one per call.
18307
+ * Lets the contact's `app` read `file` until the app closes: the serve id to tell it. A file the app serves already
18308
+ * answers the id it has, so an app that serves again on each play holds one serve per file, not one per call.
18163
18309
  */
18164
18310
  serve(app, file) {
18165
18311
  if (!isChatAppId(app)) throw new Error("Not a chat app id");
@@ -18179,7 +18325,7 @@ var AppRanges = class {
18179
18325
  for (const task of this.serving.values()) if (task.serve === serveId) this.drop(task, true);
18180
18326
  return true;
18181
18327
  }
18182
- /** The serve ids `app` has given out on this session (what the panel's "Sharing with" line shows). */
18328
+ /** The serve ids `app` has given out and not ended (what the panel's "Sharing with" line shows). */
18183
18329
  servesOf(app) {
18184
18330
  return [...this.serves].filter(([, serve]) => serve.app === app).map(([id]) => id);
18185
18331
  }
@@ -18314,6 +18460,28 @@ var AppRanges = class {
18314
18460
  */
18315
18461
  closeApp(app, error = "peer-closed", stopped = false) {
18316
18462
  for (const [id, serve] of this.serves) if (serve.app === app) this.serves.delete(id);
18463
+ for (const key of [...this.sizes.keys()]) if (key.startsWith(`${app} `)) this.sizes.delete(key);
18464
+ this.endRequests(app, error, stopped);
18465
+ }
18466
+ /** The session ended: no serve id lasts into the next, and every request fails with `offline`. Tasks still being read keep their places into the next. */
18467
+ reset() {
18468
+ this.sizes.clear();
18469
+ for (const app of new Set([...this.serves.values()].map((serve) => serve.app))) this.closeApp(app, "offline");
18470
+ this.suspend();
18471
+ }
18472
+ /**
18473
+ * The session changed (a resume, a re-dial, a transport switch) and the apps are held across it: every request fails
18474
+ * with `offline`, and the serve ids stay, for the next session, until the app closes on either side.
18475
+ */
18476
+ suspend() {
18477
+ const apps = new Set([...this.serving.values(), ...this.draining].map((task) => task.app).concat([...this.waiting.keys()], [...this.asking.values()].map((ask) => ask.app)));
18478
+ for (const app of apps) this.endRequests(app, "offline");
18479
+ }
18480
+ /**
18481
+ * What `app` was sending stops and what it asked fails with `error`. A task this side is still reading keeps its place
18482
+ * until it is settled; only `stopped` (this side's app closed) frees them now.
18483
+ */
18484
+ endRequests(app, error, stopped = false) {
18317
18485
  for (const task of this.serving.values()) if (task.app === app) this.drop(task, !stopped);
18318
18486
  if (stopped) {
18319
18487
  for (const task of this.draining) if (task.app === app) this.draining.delete(task);
@@ -18321,13 +18489,6 @@ var AppRanges = class {
18321
18489
  for (const ask of this.waiting.get(app) ?? []) ask.reject(new Error(error));
18322
18490
  this.waiting.delete(app);
18323
18491
  for (const ask of this.asking.values()) if (ask.app === app) this.settle(ask, error);
18324
- for (const key of [...this.sizes.keys()]) if (key.startsWith(`${app} `)) this.sizes.delete(key);
18325
- }
18326
- /** The session ended: no serve id lasts into the next, and every request fails with `offline`. Tasks still being read keep their places into the next. */
18327
- reset() {
18328
- this.sizes.clear();
18329
- const apps = new Set([...this.serves.values()].map((serve) => serve.app).concat([...this.serving.values(), ...this.draining].map((task) => task.app), [...this.waiting.keys()], [...this.asking.values()].map((ask) => ask.app)));
18330
- for (const app of apps) this.closeApp(app, "offline");
18331
18492
  }
18332
18493
  /** Stops `task` and frees its request number; `draining` keeps it counted until it is settled. */
18333
18494
  drop(task, draining = false) {
@@ -18498,6 +18659,12 @@ function pushRequest(target, keys, payload, options) {
18498
18659
  var WAKE_FRAME = "paired-wake";
18499
18660
  /** At most one wake-up per contact in this long. A burst of messages is one push. */
18500
18661
  var WAKE_INTERVAL_MS = 3e5;
18662
+ /**
18663
+ * A wake-up that did not reach the push service (no network, the push relay did not forward it, the push service
18664
+ * answered 429 or 5xx) is not the contact's wake-up: the next one may go this long after it, not 5 minutes. Never a
18665
+ * retry of that one; only a pause, so a relay that is refusing is not asked again on every message.
18666
+ */
18667
+ var WAKE_RETRY_MS = 3e4;
18501
18668
  /** A wake-up that has not reached the phone within this is no use: the push service may drop it. */
18502
18669
  var WAKE_TTL_SECONDS = 3600;
18503
18670
  /** The VAPID subject push services ask for: who to contact about abuse. The project, never a person. */
@@ -18515,7 +18682,8 @@ function wakeFrame(target) {
18515
18682
  a: target.auth,
18516
18683
  vp: target.vapid.publicKey,
18517
18684
  vk: target.vapid.privateKey,
18518
- k: target.token
18685
+ k: target.token,
18686
+ ...target.online && { o: 1 }
18519
18687
  }
18520
18688
  };
18521
18689
  }
@@ -18530,7 +18698,7 @@ function parseWakeFrame(frame) {
18530
18698
  if (frame.w === null) return null;
18531
18699
  const w = frame.w;
18532
18700
  if (!w || typeof w !== "object") return void 0;
18533
- const { e, p, a, vp, vk, k } = w;
18701
+ const { e, p, a, vp, vk, k, o } = w;
18534
18702
  if (typeof e !== "string" || ![
18535
18703
  p,
18536
18704
  a,
@@ -18550,22 +18718,26 @@ function parseWakeFrame(frame) {
18550
18718
  publicKey: vp,
18551
18719
  privateKey: vk
18552
18720
  },
18553
- token: k
18721
+ token: k,
18722
+ ...o === 1 && { online: true }
18554
18723
  };
18555
18724
  if (!vapidKeysMatch(target.vapid)) return void 0;
18556
18725
  return target;
18557
18726
  }
18727
+ /** At most one online notice per contact in this long, whatever the message wake-ups do. Kept across restarts. */
18728
+ var WAKE_ONLINE_INTERVAL_MS = 18e5;
18729
+ /** How long after this side comes online it waits for the chat to go live before it says so: a live contact needs no push. */
18730
+ var WAKE_ONLINE_DELAY_MS = 3e4;
18731
+ var WAKE_ONLINE_BATCH_MS = 6e4;
18558
18732
  /** At most one call wake-up per contact in this long: a caller who tries again at once is not a new push. */
18559
18733
  var WAKE_CALL_INTERVAL_MS = 3e4;
18560
- /** The wake-up's plaintext: the contact's token for this chat, and whether it is for a call. Nothing else. */
18734
+ /** The wake-up's plaintext: the contact's token for this chat, and whether it is for a call or an online notice. Nothing else. */
18561
18735
  function wakePayload(token, kind = "message") {
18562
- return utf8Encode(JSON.stringify(kind === "call" ? {
18736
+ return utf8Encode(JSON.stringify({
18563
18737
  wake: 1,
18564
18738
  k: token,
18565
- c: 1
18566
- } : {
18567
- wake: 1,
18568
- k: token
18739
+ ...kind === "call" && { c: 1 },
18740
+ ...kind === "online" && { o: 1 }
18569
18741
  }));
18570
18742
  }
18571
18743
  /**
@@ -18588,7 +18760,7 @@ function deviceWakeRequest(target, now = Date.now()) {
18588
18760
  function wakeRequest(target, now = Date.now(), kind = "message") {
18589
18761
  return pushRequest(target, target.vapid, wakePayload(target.token, kind), {
18590
18762
  subject: WAKE_SUBJECT,
18591
- ttlSeconds: kind === "call" ? 60 : WAKE_TTL_SECONDS,
18763
+ ttlSeconds: kind === "call" ? 60 : kind === "online" ? 300 : WAKE_TTL_SECONDS,
18592
18764
  now
18593
18765
  });
18594
18766
  }
@@ -18606,6 +18778,14 @@ var WakeLimiter = class {
18606
18778
  this.last.set(contact, now);
18607
18779
  return true;
18608
18780
  }
18781
+ /**
18782
+ * The wake-up taken at `takenAt` did not reach the push service: it does not count, and the next may go
18783
+ * `retryMs` from now. Nothing changes when another was taken since, or the count started over.
18784
+ */
18785
+ missed(contact, takenAt, retryMs = WAKE_RETRY_MS, now = Date.now()) {
18786
+ if (this.last.get(contact) !== takenAt) return;
18787
+ this.last.set(contact, now - this.interval + Math.min(retryMs, this.interval));
18788
+ }
18609
18789
  /** The contact answered (it is live again): the next time it is away, it may be woken at once. */
18610
18790
  reset(contact) {
18611
18791
  this.last.delete(contact);
@@ -18759,8 +18939,12 @@ var LINK_OR_MARKUP = /[a-z][a-z0-9+.-]*:\/\/|\bwww\.|\b(?:mailto|javascript|data
18759
18939
  * holds a link or markup (it is plain text, never a way to put a link on the contact's screen).
18760
18940
  */
18761
18941
  function sanitizeTypingStatus(value) {
18942
+ return plainStatusLine(value, 40);
18943
+ }
18944
+ /** A contact's line of plain text by the typing status's rules, at most `max` characters (a set status uses it too). */
18945
+ function plainStatusLine(value, max) {
18762
18946
  if (typeof value !== "string") return void 0;
18763
- const clean = sanitizeDisplayText(value.slice(0, 160).replace(/\s+/g, " "), 40);
18947
+ const clean = sanitizeDisplayText(value.slice(0, 4 * max).replace(/\s+/g, " "), max);
18764
18948
  if (!clean || LINK_OR_MARKUP.test(clean)) return void 0;
18765
18949
  return clean;
18766
18950
  }
@@ -18939,6 +19123,187 @@ var TypingReceiver = class {
18939
19123
  }
18940
19124
  };
18941
19125
  //#endregion
19126
+ //#region ../core/src/pairedStatus.ts
19127
+ /**
19128
+ * Presence and a set status in a 1:1 chat (WISP 401 § Presence and status): whether the person is there, and a status
19129
+ * they set (Slack-like), said to the contact on the live session only.
19130
+ *
19131
+ * {"t":"paired-status","p":"active"}
19132
+ * {"t":"paired-status","p":"idle","s":{"a":"busy","e":"🍕","m":"At lunch","u":1762603600000}}
19133
+ * {"t":"paired-status"}
19134
+ *
19135
+ * It needs `status/1` in `paired-capabilities` on both sides. Each frame is the whole state and replaces the one before.
19136
+ * Like typing, it is presence, not a message: no message id (older apps drop it), never stored, held or put on the DHT.
19137
+ * `p` is absent when the person does not share when they are online; `s` is absent when they set no status.
19138
+ */
19139
+ var STATUS_FRAME = "paired-status";
19140
+ /** What a person can say they are: `dnd` is Do not disturb. */
19141
+ var STATUS_AVAILABILITIES = [
19142
+ "available",
19143
+ "busy",
19144
+ "away",
19145
+ "dnd"
19146
+ ];
19147
+ /** Whether the person uses the app now (`active`) or not for a while (`idle`). */
19148
+ var PRESENCES = ["active", "idle"];
19149
+ /** No input in the app for this long: the person is idle. */
19150
+ var STATUS_IDLE_AFTER_MS = 6e5;
19151
+ /** The sender says at most one frame per this; a change in between goes when it ends, the latest state only. */
19152
+ var STATUS_SEND_INTERVAL_MS = 5e3;
19153
+ var isObject$4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
19154
+ var validUntil = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
19155
+ var availabilityOf = (value) => STATUS_AVAILABILITIES.includes(value) ? value : "available";
19156
+ var presenceOf = (value) => PRESENCES.includes(value) ? value : "active";
19157
+ /** A status text as it may be shown: one line, no invisible characters, no link or markup, at most 60 characters. */
19158
+ function sanitizeStatusText(value) {
19159
+ return plainStatusLine(value, 60);
19160
+ }
19161
+ /** A status with each field checked; undefined when nothing is left of it. An unknown availability reads as available. */
19162
+ function personStatus(raw) {
19163
+ if (!isObject$4(raw)) return void 0;
19164
+ const status = {};
19165
+ if (raw.availability !== void 0) status.availability = availabilityOf(raw.availability);
19166
+ const emoji = reactionEmoji(raw.emoji);
19167
+ if (emoji) status.emoji = emoji;
19168
+ const text = sanitizeStatusText(raw.text);
19169
+ if (text) status.text = text;
19170
+ if (validUntil(raw.until)) status.until = raw.until;
19171
+ return Object.keys(status).length ? status : void 0;
19172
+ }
19173
+ /** The status while it lasts: undefined once its `until` is past by this clock. */
19174
+ function liveStatus(status, now = Date.now()) {
19175
+ return status && (status.until === void 0 || status.until > now) ? status : void 0;
19176
+ }
19177
+ /** A state with its fields checked. */
19178
+ function statusState(raw) {
19179
+ const state = {};
19180
+ if (raw.presence !== void 0) state.presence = presenceOf(raw.presence);
19181
+ const status = personStatus(raw.status);
19182
+ if (status) state.status = status;
19183
+ return state;
19184
+ }
19185
+ function statusFrame(state) {
19186
+ const frame = { t: STATUS_FRAME };
19187
+ const clean = statusState(state);
19188
+ if (clean.presence) frame.p = clean.presence;
19189
+ const status = clean.status;
19190
+ if (status) {
19191
+ const wire = {};
19192
+ if (status.availability) wire.a = status.availability;
19193
+ if (status.emoji) wire.e = status.emoji;
19194
+ if (status.text) wire.m = status.text;
19195
+ if (status.until !== void 0) wire.u = status.until;
19196
+ frame.s = wire;
19197
+ }
19198
+ return frame;
19199
+ }
19200
+ /**
19201
+ * The state a `paired-status` frame says, or null when it is malformed (then the reader keeps what it had): `s` not an
19202
+ * object, or `p` or `s.a` present and not a string. A field that does not hold (an emoji that is not one, a text with a
19203
+ * link, a bad `u`) is left out, not the frame.
19204
+ */
19205
+ function parseStatusFrame(frame) {
19206
+ if (frame?.t !== "paired-status") return null;
19207
+ if (frame.p !== void 0 && typeof frame.p !== "string") return null;
19208
+ if (frame.s !== void 0 && !isObject$4(frame.s)) return null;
19209
+ const s = frame.s;
19210
+ if (s?.a !== void 0 && typeof s.a !== "string") return null;
19211
+ return statusState({
19212
+ ...frame.p !== void 0 ? { presence: frame.p } : {},
19213
+ ...s ? { status: {
19214
+ availability: s.a,
19215
+ emoji: s.e,
19216
+ text: s.m,
19217
+ until: s.u
19218
+ } } : {}
19219
+ });
19220
+ }
19221
+ var sameStatus = (a, b) => a?.availability === b?.availability && a?.emoji === b?.emoji && a?.text === b?.text && a?.until === b?.until;
19222
+ /** Two states say the same. */
19223
+ var sameStatusState = (a, b) => a.presence === b.presence && sameStatus(a.status, b.status);
19224
+ /**
19225
+ * This side's word: what it says, and when. One per chat. A new session owes the whole state (`reset`); a change owes
19226
+ * it again. Frames go at most one per `STATUS_SEND_INTERVAL_MS`, across sessions, so the reader's window always has room.
19227
+ */
19228
+ var StatusSender = class {
19229
+ now;
19230
+ state = {};
19231
+ owed = true;
19232
+ sentAt = -Infinity;
19233
+ constructor(now = () => Date.now()) {
19234
+ this.now = now;
19235
+ }
19236
+ /** What this side says now. */
19237
+ get current() {
19238
+ return this.state;
19239
+ }
19240
+ /** This side's presence or status changed: owed again when it says something new. */
19241
+ set(state) {
19242
+ const clean = statusState(state);
19243
+ if (sameStatusState(clean, this.state)) return;
19244
+ this.state = clean;
19245
+ this.owed = true;
19246
+ }
19247
+ /**
19248
+ * On a session that agreed `status/1`: the frame to send now; or how long to wait before asking again (the interval
19249
+ * has not passed); or null when nothing is owed.
19250
+ */
19251
+ take() {
19252
+ if (!this.owed) return null;
19253
+ const now = this.now(), wait = this.sentAt + STATUS_SEND_INTERVAL_MS - now;
19254
+ if (wait > 0 && now >= this.sentAt) return { wait };
19255
+ this.owed = false;
19256
+ this.sentAt = now;
19257
+ return { frame: statusFrame(this.state) };
19258
+ }
19259
+ /** The session ended: the next one is owed the whole state. */
19260
+ reset() {
19261
+ this.owed = true;
19262
+ }
19263
+ };
19264
+ /**
19265
+ * The contact's word, with a rate limit. Presence ends with the session (`endSession`); the status stays until a new
19266
+ * frame replaces it or its `until` passes (read through `peer`). `onChange` hears changes only.
19267
+ */
19268
+ var StatusReceiver = class {
19269
+ onChange;
19270
+ now;
19271
+ state = {};
19272
+ recent = [];
19273
+ constructor(onChange, now = () => Date.now()) {
19274
+ this.onChange = onChange;
19275
+ this.now = now;
19276
+ }
19277
+ /** What the contact says now, a status past its `until` left out. */
19278
+ get peer() {
19279
+ const status = liveStatus(this.state.status, this.now());
19280
+ return {
19281
+ ...this.state.presence ? { presence: this.state.presence } : {},
19282
+ ...status ? { status } : {}
19283
+ };
19284
+ }
19285
+ /** A `paired-status` frame from the contact. False when it was dropped: malformed, or over the rate limit. */
19286
+ receive(frame) {
19287
+ const now = this.now();
19288
+ this.recent = this.recent.filter((at) => at <= now && now - at < 6e4);
19289
+ if (this.recent.length >= 15) return false;
19290
+ this.recent.push(now);
19291
+ const state = parseStatusFrame(frame);
19292
+ if (!state) return false;
19293
+ this.set(state);
19294
+ return true;
19295
+ }
19296
+ /** The session ended: the contact is not online any more; its status stands. */
19297
+ endSession() {
19298
+ if (this.state.presence) this.set(this.state.status ? { status: this.state.status } : {});
19299
+ }
19300
+ set(state) {
19301
+ if (sameStatusState(state, this.state)) return;
19302
+ this.state = state;
19303
+ this.onChange(this.peer);
19304
+ }
19305
+ };
19306
+ //#endregion
18942
19307
  //#region ../core/src/chatFiles.ts
18943
19308
  /**
18944
19309
  * files/3 (WISP 501, revision 0.3): files of any size in a chat, offered before they are sent, sent with
@@ -20596,6 +20961,7 @@ var ChatFiles = class {
20596
20961
  * contact this session authenticated. Nothing about a call is ever published on the DHT.
20597
20962
  */
20598
20963
  var PAIRED_CALL_FRAME = "paired-call";
20964
+ var CALL_RATE_WINDOW_MS = 6e4;
20599
20965
  /**
20600
20966
  * The signal a `paired-call` frame carries, or null when it is not a well-formed one. It came on a live session, now:
20601
20967
  * that is when it was heard (`heardCallSignal`), whatever time its sender's clock gave it.
@@ -21145,6 +21511,8 @@ var CarriedTransport = class {
21145
21511
  hooks;
21146
21512
  /** My last packet while the edge is down: what a member that just became reachable is handed. */
21147
21513
  mine = null;
21514
+ /** The records `mine` holds, as members last took them, and when. */
21515
+ handed = null;
21148
21516
  lastTimestamp = 0n;
21149
21517
  /** The date each packet `stamp` signed carries: the relays' transport takes it rather than check the signature again. */
21150
21518
  dated = /* @__PURE__ */ new WeakMap();
@@ -21215,6 +21583,8 @@ var CarriedTransport = class {
21215
21583
  throw held;
21216
21584
  }
21217
21585
  }
21586
+ const said = JSON.stringify(records);
21587
+ if (this.mine && this.handed?.said === said && Date.now() - this.handed.at < 3e4) return this.toRelays(identity, records, this.mine, options);
21218
21588
  const payload = this.newest = this.stamp(identity, records);
21219
21589
  this.mine = payload;
21220
21590
  let carried = {
@@ -21224,6 +21594,10 @@ var CarriedTransport = class {
21224
21594
  try {
21225
21595
  carried = this.hooks.carry(payload);
21226
21596
  } catch {}
21597
+ this.handed = carried.taken ? {
21598
+ said,
21599
+ at: Date.now()
21600
+ } : null;
21227
21601
  const proven = Date.now() - this.heardAt < SIGNAL_PROVEN_MS;
21228
21602
  if (!carried.taken || this.quiet || !(carried.sure || proven)) return this.toRelays(identity, records, payload, options);
21229
21603
  let end;
@@ -21385,6 +21759,7 @@ var CarriedTransport = class {
21385
21759
  if (this.unsigned) {
21386
21760
  const { identity, records } = this.unsigned;
21387
21761
  this.unsigned = null;
21762
+ this.handed = null;
21388
21763
  this.mine = this.newest = this.stamp(identity, records);
21389
21764
  }
21390
21765
  return this.mine;
@@ -21781,6 +22156,8 @@ var ENGINE_ERRORS = {
21781
22156
  ecashOtherUnit: "This ecash is in {unit}: only sat ecash can be redeemed here",
21782
22157
  reviewedEcashSpent: "The ecash for this payment was already spent somewhere else. Nothing was sent, and your balance now shows what the mint still holds.",
21783
22158
  reviewedSatsGone: "The sats this payment was reviewed with went to another payment. Nothing was sent: review it again.",
22159
+ mintFailedQuote: "{host} could not take this payment right now, and no sats left your wallet: try again later. The mint said: {reason}",
22160
+ mintFailedFaucet: "{host} could not give test coins right now: try again later. The mint said: {reason}",
21784
22161
  lightningFeeTooHigh: "The Lightning fee ({fee} sats) is too high",
21785
22162
  lightningRefused: "The mint refused this Lightning payment, and no sats left your wallet: it is safe to try again. The mint said: {reason}",
21786
22163
  invoiceExpired: "That invoice has expired",
@@ -22002,6 +22379,15 @@ var LIVENESS_PING_MS = 15e3;
22002
22379
  */
22003
22380
  var SWITCH_RETIRE_MS = 3e3;
22004
22381
  /**
22382
+ * A move's native dial that found no announce of the contact (HyperDHT's PEER_NOT_FOUND) is made again this long after,
22383
+ * for as long as the move lasts: the contact is live (its policy came over the open session), and its endpoint is not
22384
+ * announced while a channel is live: a move back to HyperDHT within ~5 s of leaving it, before the session left behind
22385
+ * had retired (`SWITCH_RETIRE_MS`) and the endpoint was announced again, found nobody. The move gave up at once and the
22386
+ * chat waited the 20 s retry (20.0-20.1 s in 3 of 3 cycles on two CLI daemons, a 2 s gap between moves).
22387
+ */
22388
+ var SWITCH_FIND_RETRY_MS = 1e3;
22389
+ var RTC_SIGNAL_RATE_WINDOW_MS = 6e4;
22390
+ /**
22005
22391
  * Frames that keep a session going rather than say something of the two people's: what the contact sent last outside
22006
22392
  * these is when the chat was last in use (`canYieldEndpoint`). Every other frame (a text, a receipt, typing, a
22007
22393
  * reaction, an edit, a file, a call, a payment) is use; what this side sends is answered with one of them.
@@ -22285,6 +22671,11 @@ var GhostLink = class {
22285
22671
  /** Typing on this session (`typing/1`): when to say `start` again, and the contact's word with its timeout. */
22286
22672
  typingSender = new TypingSender();
22287
22673
  typingReceiver = new TypingReceiver((typing, activity) => this.options.events?.onPeerTyping?.(typing, activity));
22674
+ /** Presence and status on this session (`status/1`): this side's word (kept across sessions) and the contact's. */
22675
+ statusSender = new StatusSender();
22676
+ statusReceiver = new StatusReceiver((state) => this.options.events?.onPeerStatus?.(state));
22677
+ /** A status frame waiting for the send interval to pass. */
22678
+ statusTimer = null;
22288
22679
  /** Mini-apps on this session (`apps/1`): this side's open apps (kept across sessions), the peer's, the limits. */
22289
22680
  apps;
22290
22681
  /** The read lane on this session (`app-ranges/1`): what this side serves and what it asked; none of it outlives the session. */
@@ -22299,6 +22690,10 @@ var GhostLink = class {
22299
22690
  pinsReceived = new ReactionWindow(PIN_LIMITS.receive, PIN_LIMITS.windowMs);
22300
22691
  /** Edit frames the contact may send per window; the rest go unconfirmed and come again. */
22301
22692
  editsReceived = new RateWindow(30, EDIT_RATE_WINDOW_MS);
22693
+ /** Call signals the contact may send per window; the rest are dropped. */
22694
+ callsReceived = new RateWindow(150, CALL_RATE_WINDOW_MS);
22695
+ /** WebRTC signals the contact may send on the session (`paired-rtc`) per window; the rest are dropped. */
22696
+ rtcSignalsReceived = new RateWindow(60, RTC_SIGNAL_RATE_WINDOW_MS);
22302
22697
  wakeReceived = new RateWindow(6, 6e4);
22303
22698
  /** Said once a session by the requester's app: a few a minute at most. */
22304
22699
  askerReceived = new RateWindow(4, 6e4);
@@ -22845,7 +23240,7 @@ var GhostLink = class {
22845
23240
  key: this.myPubKeyZ32,
22846
23241
  peerKey: options.params.peerPubKeyZ32,
22847
23242
  policy: () => ({
22848
- preferred: this.preferred,
23243
+ preferred: this.ownPreferred,
22849
23244
  fallback: this.fallback,
22850
23245
  available: this.availableTransports,
22851
23246
  descriptors: Object.fromEntries([...this.endpoints].map(([transport, endpoint]) => [transport, endpoint.descriptor]))
@@ -23540,7 +23935,7 @@ var GhostLink = class {
23540
23935
  return wanted && wanted.transport !== state.transport ? wanted : void 0;
23541
23936
  }
23542
23937
  if (!this.fallback) return {
23543
- transport: this.preferred,
23938
+ transport: this.ownPreferred,
23544
23939
  ...this.automatic ? {} : { by: "you" }
23545
23940
  };
23546
23941
  return this.choiceApart;
@@ -23643,8 +24038,15 @@ var GhostLink = class {
23643
24038
  get availableTransports() {
23644
24039
  return [...this.options.rtcAvailable !== false ? ["webrtc/1"] : [], ...this.endpoints.keys()];
23645
24040
  }
24041
+ /**
24042
+ * The transport this side's policy names: on Automatic, the app's rule for what runs now (Iroh once its endpoint is
24043
+ * up, with Fallback on; with it off, WebRTC where there is one, so an endpoint coming up moves nothing).
24044
+ */
24045
+ get ownPreferred() {
24046
+ return this.automatic ? automaticTransport(this.availableTransports, this.fallback) : this.preferred;
24047
+ }
23646
24048
  transportOffer() {
23647
- return transportOrder(this.availableTransports, this.preferred, this.fallback);
24049
+ return transportOrder(this.availableTransports, this.ownPreferred, this.fallback);
23648
24050
  }
23649
24051
  registerEndpoint(endpoint) {
23650
24052
  if (this.stopped || this.deliveryMode === "dht" || this.quietForTaken || !this.options.params.profile) {
@@ -24046,8 +24448,9 @@ var GhostLink = class {
24046
24448
  const relayed = relayedTransports(this.localDescriptors(), this.peerDescriptors);
24047
24449
  const remembered = this.peerTransports && rankTransports(local, this.peerFallback ? this.peerTransports : this.peerTransports.slice(0, 1), relayed);
24048
24450
  const ranked = remembered?.length ? remembered : this.peerTransports ? rankTransports(local, this.peerTransports, relayed) : local.filter((t) => t === "webrtc/1");
24049
- const chosen = this.switcher.chosenTarget ?? this.choiceApart?.transport ?? this.resuming;
24050
24451
  const resume = this.resuming === "webrtc/1", woke = resume && this.resumingWoke;
24452
+ if (this.automatic && this.resuming === "webrtc/1" && ranked.includes("iroh/1") && ranked.indexOf("iroh/1") < ranked.indexOf("webrtc/1")) this.resuming = "iroh/1";
24453
+ const chosen = this.switcher.chosenTarget ?? this.choiceApart?.transport ?? this.resuming;
24051
24454
  if (chosen && chosen === this.resuming && ranked.includes(chosen)) {
24052
24455
  this.resuming = void 0;
24053
24456
  this.resumingWoke = false;
@@ -25155,6 +25558,7 @@ var GhostLink = class {
25155
25558
  if (this.options.largeFilesSupport) offered.push(FILES_CAPABILITY);
25156
25559
  if (this.options.largeFilesSupport && this.options.binaryFilesSupport && this.channel?.binary) offered.push(FILES_BINARY_CAPABILITY);
25157
25560
  if (this.options.typingSupport) offered.push(TYPING_CAPABILITY);
25561
+ if (this.options.statusSupport) offered.push(STATUS_CAPABILITY);
25158
25562
  if (this.options.reactionsSupport) offered.push(REACTIONS_CAPABILITY);
25159
25563
  if (this.options.editSupport) offered.push(EDIT_CAPABILITY);
25160
25564
  if (this.options.wakeSupport) offered.push(WAKE_SESSION_CAPABILITY);
@@ -25233,6 +25637,48 @@ var GhostLink = class {
25233
25637
  get peerTypingActivity() {
25234
25638
  return this.typingReceiver.peerActivity;
25235
25639
  }
25640
+ /** Both sides offer `status/1` on the open session: presence and a set status can be said and shown. */
25641
+ get supportsStatus() {
25642
+ return !!this.options.params.profile && this.isDataLinkOpen && this.sessionCapabilities.agreed("status/1");
25643
+ }
25644
+ /** What the contact says of itself: presence while this session is live and it shares it, a status while it lasts. */
25645
+ get peerStatus() {
25646
+ return this.statusReceiver.peer;
25647
+ }
25648
+ /**
25649
+ * This side's presence and status (the whole state: `presence` left out when the person does not share it). Said on
25650
+ * the live session once both sides offer `status/1`, at most one frame per few seconds; kept for every next session.
25651
+ */
25652
+ setStatus(state) {
25653
+ this.statusSender.set(state);
25654
+ this.flushStatus();
25655
+ }
25656
+ flushStatus() {
25657
+ if (this.statusTimer || !this.channel || !this.supportsStatus) return;
25658
+ const next = this.statusSender.take();
25659
+ if (!next) return;
25660
+ if ("wait" in next) {
25661
+ this.statusTimer = setTimeout(() => {
25662
+ this.statusTimer = null;
25663
+ this.flushStatus();
25664
+ }, next.wait);
25665
+ return;
25666
+ }
25667
+ try {
25668
+ this.channel.send(JSON.stringify(next.frame));
25669
+ } catch {
25670
+ this.statusSender.reset();
25671
+ }
25672
+ }
25673
+ /** The session ended: the contact is not online here any more, and the next session is owed this side's whole state. */
25674
+ endStatusSession() {
25675
+ if (this.statusTimer) {
25676
+ clearTimeout(this.statusTimer);
25677
+ this.statusTimer = null;
25678
+ }
25679
+ this.statusSender.reset();
25680
+ this.statusReceiver.endSession();
25681
+ }
25236
25682
  /** Both sides offer `wake/1` on the open session: push subscriptions can be shared (WISP 401 § Wake-up push). */
25237
25683
  get supportsWake() {
25238
25684
  return !!this.options.params.profile && this.isDataLinkOpen && this.sessionCapabilities.agreed("wake/1");
@@ -25449,8 +25895,8 @@ var GhostLink = class {
25449
25895
  return this.supportsAppRanges && this.apps.peerOpen.has(app) ? null : "peer-closed";
25450
25896
  }
25451
25897
  /**
25452
- * Lets the contact's `app` read `file` (what this side's app calls it) for as long as both have the app open on this
25453
- * session: the serve id to tell it, or why not.
25898
+ * Lets the contact's `app` read `file` (what this side's app calls it) for as long as both have the app open, across
25899
+ * a session change the apps are held across: the serve id to tell it, or why not.
25454
25900
  */
25455
25901
  serveAppFile(app, file) {
25456
25902
  const error = this.appRangesRefusal(app);
@@ -25460,7 +25906,7 @@ var GhostLink = class {
25460
25906
  unserveAppFile(serve) {
25461
25907
  return this.appRanges.unserve(serve);
25462
25908
  }
25463
- /** The serve ids `app` has given out on this session. */
25909
+ /** The serve ids `app` has given out and not ended. */
25464
25910
  appServes(app) {
25465
25911
  return this.appRanges.servesOf(app);
25466
25912
  }
@@ -25548,7 +25994,7 @@ var GhostLink = class {
25548
25994
  * gives what it held its own grace: a later one's apps do not close at an earlier one's time.
25549
25995
  */
25550
25996
  appsSuspended() {
25551
- this.appRanges.reset();
25997
+ this.appRanges.suspend();
25552
25998
  this.apps.sessionSuspended(this.options.appResumeGraceMs ?? 1e4);
25553
25999
  this.armAppsGrace();
25554
26000
  }
@@ -25562,7 +26008,10 @@ var GhostLink = class {
25562
26008
  if (until === void 0) return;
25563
26009
  this.appsGrace = setTimeout(() => {
25564
26010
  this.appsGrace = null;
25565
- for (const event of this.apps.heldExpired()) this.options.events?.onAppFrame?.(event);
26011
+ for (const event of this.apps.heldExpired()) {
26012
+ if ("o" in event && event.o === "close") this.appRanges.closeApp(event.app, "offline");
26013
+ this.options.events?.onAppFrame?.(event);
26014
+ }
25566
26015
  this.armAppsGrace();
25567
26016
  }, Math.max(0, until - Date.now()));
25568
26017
  }
@@ -25713,6 +26162,10 @@ var GhostLink = class {
25713
26162
  this.typingReceiver.clear();
25714
26163
  } else this.resumeTyping();
25715
26164
  }
26165
+ if (changed.includes("status/1")) {
26166
+ if (this.supportsStatus) this.flushStatus();
26167
+ else this.endStatusSession();
26168
+ }
25716
26169
  if (changed.includes("react/1")) this.options.events?.onReactionsSupport?.(this.supportsReactions);
25717
26170
  if (changed.includes("edit/1")) this.options.events?.onEditSupport?.(this.supportsEdits);
25718
26171
  if (changed.includes("pin/1")) this.options.events?.onPinSupport?.(this.supportsPins);
@@ -25817,10 +26270,10 @@ var GhostLink = class {
25817
26270
  }
25818
26271
  try {
25819
26272
  await new Promise((resolve, reject) => {
25820
- let active = true;
26273
+ let active = true, notFound;
25821
26274
  const timer = setTimeout(() => {
25822
26275
  active = false;
25823
- reject(/* @__PURE__ */ new Error(`${transport} did not connect in time`));
26276
+ reject(notFound ?? /* @__PURE__ */ new Error(`${transport} did not connect in time`));
25824
26277
  }, 8e3);
25825
26278
  const done = {
25826
26279
  resolve: () => {
@@ -25848,17 +26301,26 @@ var GhostLink = class {
25848
26301
  return;
25849
26302
  }
25850
26303
  const turn = (this.switchDials.get(transport) ?? Promise.resolve()).then(async () => {
25851
- if (!active || epoch !== this.candidateEpoch || this.switcher.pending !== plan) return;
25852
- this.switcher.dialing(plan);
25853
- try {
25854
- const { channel, binding } = await endpoint.connect(descriptor);
25855
- if (!active || epoch !== this.candidateEpoch || this.switcher.pending !== plan) {
25856
- channel.close();
26304
+ for (;;) {
26305
+ if (!active || epoch !== this.candidateEpoch || this.switcher.pending !== plan) return;
26306
+ this.switcher.dialing(plan);
26307
+ try {
26308
+ const { channel, binding } = await endpoint.connect(descriptor);
26309
+ if (!active || epoch !== this.candidateEpoch || this.switcher.pending !== plan) {
26310
+ channel.close();
26311
+ return;
26312
+ }
26313
+ this.attachCandidate(channel, binding, plan).then(done.resolve, done.reject);
25857
26314
  return;
26315
+ } catch (error) {
26316
+ const failure = error instanceof Error ? error : new Error(String(error));
26317
+ if (!/^PEER_NOT_FOUND\b/.test(failure.message)) {
26318
+ done.reject(failure);
26319
+ return;
26320
+ }
26321
+ notFound = failure;
26322
+ await new Promise((resolve) => setTimeout(resolve, SWITCH_FIND_RETRY_MS));
25858
26323
  }
25859
- this.attachCandidate(channel, binding, plan).then(done.resolve, done.reject);
25860
- } catch (error) {
25861
- done.reject(error instanceof Error ? error : new Error(String(error)));
25862
26324
  }
25863
26325
  });
25864
26326
  this.switchDials.set(transport, turn);
@@ -26242,6 +26704,7 @@ var GhostLink = class {
26242
26704
  this.leaveHangUp();
26243
26705
  this.typingSender.reset();
26244
26706
  this.typingReceiver.clear();
26707
+ this.endStatusSession();
26245
26708
  this.appsSuspended();
26246
26709
  this.pairedHttp?.close();
26247
26710
  this.pairedHttp = new PairedHttp(channel, this.options.getHostedHttpService, this.options.localFetch, this.bodiesOn(channel));
@@ -26336,6 +26799,7 @@ var GhostLink = class {
26336
26799
  if (!frame || typeof frame !== "object") return;
26337
26800
  if (paired.peerTransportSwitchSupport && this.switcher.handle(frame)) return;
26338
26801
  if (frame.t === "paired-rtc") {
26802
+ if (!this.rtcSignalsReceived.take()) return;
26339
26803
  if (this.switcher.pending?.choices.includes("webrtc/1") && typeof frame.signal === "string") {
26340
26804
  const credentials = this.options.pairing.credentials;
26341
26805
  const signal = verifyPairedSignal(frame.signal, this.options.params.peerPubKeyZ32, this.myPubKeyZ32, credentials.peerKey, true);
@@ -26437,6 +26901,10 @@ var GhostLink = class {
26437
26901
  if (keys && this.askerReceived.take()) this.options.events?.onContactAsker?.(frame, keys);
26438
26902
  return;
26439
26903
  }
26904
+ if (frame?.t === "paired-status") {
26905
+ if (this.supportsStatus) this.statusReceiver.receive(frame);
26906
+ return;
26907
+ }
26440
26908
  if (frame?.t === "paired-typing") {
26441
26909
  if (this.supportsTyping) this.typingReceiver.receive(frame);
26442
26910
  return;
@@ -26495,7 +26963,8 @@ var GhostLink = class {
26495
26963
  return;
26496
26964
  }
26497
26965
  if (frame?.t === "paired-call") {
26498
- const signal = this.supportsCalls ? parsePairedCallFrame(frame) : null;
26966
+ if (!this.supportsCalls || !this.callsReceived.take()) return;
26967
+ const signal = parsePairedCallFrame(frame);
26499
26968
  if (signal && this.pairedCalls.heard(signal)) this.options.events?.onCallSignal?.(signal);
26500
26969
  return;
26501
26970
  }
@@ -27035,6 +27504,7 @@ var GhostLink = class {
27035
27504
  this.sessionCapabilities.reset();
27036
27505
  this.typingSender.reset();
27037
27506
  this.typingReceiver.clear();
27507
+ this.endStatusSession();
27038
27508
  this.appsSuspended();
27039
27509
  this.emitFilesSession();
27040
27510
  this.peerGroupsWereOn = false;
@@ -27190,9 +27660,9 @@ var HEIF_BRANDS = /* @__PURE__ */ new Set([
27190
27660
  ]);
27191
27661
  var u16be = (b, at) => b[at] << 8 | b[at + 1];
27192
27662
  var u32be$1 = (b, at) => (b[at] << 24 >>> 0) + (b[at + 1] << 16) + (b[at + 2] << 8) + b[at + 3];
27193
- var u32le = (b, at) => (b[at] | b[at + 1] << 8 | b[at + 2] << 16 | b[at + 3] << 24) >>> 0;
27194
- var text$1 = (b, at, length) => String.fromCharCode(...b.subarray(at, at + length));
27195
- var starts = (b, at, prefix) => at + prefix.length <= b.length && text$1(b, at, prefix.length) === prefix;
27663
+ var u32le$1 = (b, at) => (b[at] | b[at + 1] << 8 | b[at + 2] << 16 | b[at + 3] << 24) >>> 0;
27664
+ var text$2 = (b, at, length) => String.fromCharCode(...b.subarray(at, at + length));
27665
+ var starts = (b, at, prefix) => at + prefix.length <= b.length && text$2(b, at, prefix.length) === prefix;
27196
27666
  /** A picture this strips, by its first bytes. */
27197
27667
  function kindOf(b) {
27198
27668
  if (b.length >= 3 && b[0] === 255 && b[1] === 216 && b[2] === 255) return "jpeg";
@@ -27202,11 +27672,11 @@ function kindOf(b) {
27202
27672
  if (starts(b, 0, "II*\0") || starts(b, 0, "MM\0*") || starts(b, 0, "II+\0") || starts(b, 0, "MM\0+")) return "tiff";
27203
27673
  if (b.length >= 16 && starts(b, 4, "ftyp")) {
27204
27674
  const end = Math.min(b.length, u32be$1(b, 0));
27205
- for (let at = 8; at + 4 <= end; at += 4) if (at !== 12 && HEIF_BRANDS.has(text$1(b, at, 4))) return "heif";
27675
+ for (let at = 8; at + 4 <= end; at += 4) if (at !== 12 && HEIF_BRANDS.has(text$2(b, at, 4))) return "heif";
27206
27676
  }
27207
27677
  }
27208
27678
  /** Refuses the picture where its bytes are not what this expects. */
27209
- function check$1(ok) {
27679
+ function check$2(ok) {
27210
27680
  if (!ok) throw new Error(NO_PICTURE_METADATA);
27211
27681
  }
27212
27682
  /** SOFn markers: every frame type but DHT (C4), JPG (C8) and DAC (CC). */
@@ -27240,12 +27710,12 @@ function stripJpeg(b) {
27240
27710
  const parts = [b.subarray(0, 2)];
27241
27711
  let at = 2, framed = false, scanned = false, exif = false;
27242
27712
  for (;;) {
27243
- check$1(at < b.length && b[at] === 255);
27713
+ check$2(at < b.length && b[at] === 255);
27244
27714
  while (at < b.length && b[at] === 255) at++;
27245
- check$1(at < b.length);
27715
+ check$2(at < b.length);
27246
27716
  const marker = b[at++];
27247
27717
  if (marker === 217) {
27248
- check$1(framed && scanned);
27718
+ check$2(framed && scanned);
27249
27719
  parts.push(Uint8Array.of(255, 217));
27250
27720
  return parts;
27251
27721
  }
@@ -27253,9 +27723,9 @@ function stripJpeg(b) {
27253
27723
  parts.push(Uint8Array.of(255, marker));
27254
27724
  continue;
27255
27725
  }
27256
- check$1(marker !== 0 && marker !== 216 && at + 2 <= b.length);
27726
+ check$2(marker !== 0 && marker !== 216 && at + 2 <= b.length);
27257
27727
  const length = u16be(b, at);
27258
- check$1(length >= 2 && at + length <= b.length);
27728
+ check$2(length >= 2 && at + length <= b.length);
27259
27729
  if (marker === 224 && length > 16 && starts(b, at + 2, "JFIF\0")) parts.push(Uint8Array.of(255, 224, 0, 16, ...b.subarray(at + 2, at + 14), 0, 0));
27260
27730
  else if (jpegKeeps(marker, b, at + 2)) {
27261
27731
  parts.push(Uint8Array.of(255, marker), b.subarray(at, at + length));
@@ -27267,15 +27737,15 @@ function stripJpeg(b) {
27267
27737
  }
27268
27738
  at += length;
27269
27739
  if (marker !== 218) continue;
27270
- check$1(framed);
27740
+ check$2(framed);
27271
27741
  scanned = true;
27272
27742
  let end = at;
27273
27743
  for (;;) {
27274
27744
  end = b.indexOf(255, end);
27275
- check$1(end >= 0);
27745
+ check$2(end >= 0);
27276
27746
  let next = end + 1;
27277
27747
  while (next < b.length && b[next] === 255) next++;
27278
- check$1(next < b.length);
27748
+ check$2(next < b.length);
27279
27749
  if (b[next] !== 0 && !(b[next] >= 208 && b[next] <= 215)) break;
27280
27750
  end = next + 1;
27281
27751
  }
@@ -27324,11 +27794,11 @@ function stripPng(b) {
27324
27794
  const parts = [b.subarray(0, 8)];
27325
27795
  let at = 8, exif = false, imaged = false;
27326
27796
  for (;;) {
27327
- check$1(at + 12 <= b.length);
27328
- const length = u32be$1(b, at), type = text$1(b, at + 4, 4);
27329
- check$1(at + 12 + length <= b.length && (at > 8 || type === "IHDR"));
27797
+ check$2(at + 12 <= b.length);
27798
+ const length = u32be$1(b, at), type = text$2(b, at + 4, 4);
27799
+ check$2(at + 12 + length <= b.length && (at > 8 || type === "IHDR"));
27330
27800
  const critical = (b[at + 4] & 32) === 0;
27331
- check$1(!critical || PNG_CRITICAL.has(type));
27801
+ check$2(!critical || PNG_CRITICAL.has(type));
27332
27802
  if (critical || PNG_DRAWS.has(type)) parts.push(b.subarray(at, at + 12 + length));
27333
27803
  else if (type === "eXIf" && !exif && !imaged) {
27334
27804
  exif = true;
@@ -27350,20 +27820,20 @@ var WEBP_KEEPS = /* @__PURE__ */ new Set([
27350
27820
  "ICCP"
27351
27821
  ]);
27352
27822
  function stripWebp(b) {
27353
- check$1(b.length >= 20);
27354
- const riffEnd = 8 + u32le(b, 4);
27355
- check$1(riffEnd <= b.length && riffEnd % 2 === 0);
27823
+ check$2(b.length >= 20);
27824
+ const riffEnd = 8 + u32le$1(b, 4);
27825
+ check$2(riffEnd <= b.length && riffEnd % 2 === 0);
27356
27826
  const parts = [];
27357
27827
  let at = 12, size = 4, drawn = false, exif = false, vp8x;
27358
27828
  while (at < riffEnd) {
27359
- check$1(at + 8 <= riffEnd);
27360
- const type = text$1(b, at, 4), length = u32le(b, at + 4), end = at + 8 + length + (length & 1);
27361
- check$1(end <= riffEnd && (at > 12 || type === "VP8 " || type === "VP8L" || type === "VP8X"));
27829
+ check$2(at + 8 <= riffEnd);
27830
+ const type = text$2(b, at, 4), length = u32le$1(b, at + 4), end = at + 8 + length + (length & 1);
27831
+ check$2(end <= riffEnd && (at > 12 || type === "VP8 " || type === "VP8L" || type === "VP8X"));
27362
27832
  let chunk;
27363
27833
  if (WEBP_KEEPS.has(type)) {
27364
27834
  chunk = b.subarray(at, end);
27365
27835
  if (type === "VP8X") {
27366
- check$1(length >= 10);
27836
+ check$2(length >= 10);
27367
27837
  chunk = vp8x = chunk.slice();
27368
27838
  chunk[8] = chunk[8] & -13;
27369
27839
  }
@@ -27391,7 +27861,7 @@ function stripWebp(b) {
27391
27861
  }
27392
27862
  at = end;
27393
27863
  }
27394
- check$1(drawn);
27864
+ check$2(drawn);
27395
27865
  const header = /* @__PURE__ */ new Uint8Array(12);
27396
27866
  header.set(b.subarray(0, 12));
27397
27867
  new DataView(header.buffer).setUint32(4, size, true);
@@ -27474,16 +27944,16 @@ var HEIF_ABOUT = /* @__PURE__ */ new Set([
27474
27944
  function boxes$1(b, start, end) {
27475
27945
  const found = [];
27476
27946
  for (let at = start; at < end;) {
27477
- check$1(at + 8 <= end);
27947
+ check$2(at + 8 <= end);
27478
27948
  let size = u32be$1(b, at), body = at + 8;
27479
- const type = text$1(b, at + 4, 4);
27949
+ const type = text$2(b, at + 4, 4);
27480
27950
  if (size === 1) {
27481
- check$1(at + 16 <= end);
27951
+ check$2(at + 16 <= end);
27482
27952
  size = u32be$1(b, at + 8) * 2 ** 32 + u32be$1(b, at + 12);
27483
27953
  body = at + 16;
27484
27954
  } else if (size === 0) size = end - at;
27485
27955
  if (type === "uuid") body += 16;
27486
- check$1(size >= body - at && at + size <= end);
27956
+ check$2(size >= body - at && at + size <= end);
27487
27957
  found.push({
27488
27958
  type,
27489
27959
  start: at,
@@ -27496,58 +27966,58 @@ function boxes$1(b, start, end) {
27496
27966
  }
27497
27967
  function stripHeif(b) {
27498
27968
  const top = boxes$1(b, 0, b.length);
27499
- check$1(top[0]?.type === "ftyp" && top.every((box) => HEIF_TOP.has(box.type)));
27969
+ check$2(top[0]?.type === "ftyp" && top.every((box) => HEIF_TOP.has(box.type)));
27500
27970
  const metas = top.filter((box) => box.type === "meta");
27501
- check$1(metas.length === 1);
27971
+ check$2(metas.length === 1);
27502
27972
  const meta = metas[0];
27503
27973
  const children = boxes$1(b, meta.body + 4, meta.end);
27504
- check$1(children.every((box) => HEIF_META.has(box.type)));
27974
+ check$2(children.every((box) => HEIF_META.has(box.type)));
27505
27975
  const one = (type) => {
27506
27976
  const of = children.filter((box) => box.type === type);
27507
- check$1(of.length <= 1);
27977
+ check$2(of.length <= 1);
27508
27978
  return of[0];
27509
27979
  };
27510
27980
  const iinf = one("iinf"), iloc = one("iloc"), idat = one("idat");
27511
- check$1(!!iinf && !!iloc);
27981
+ check$2(!!iinf && !!iloc);
27512
27982
  const metadata = /* @__PURE__ */ new Set();
27513
27983
  const infeVersion = b[iinf.body];
27514
27984
  const entries = boxes$1(b, iinf.body + 4 + (infeVersion === 0 ? 2 : 4), iinf.end);
27515
27985
  for (const infe of entries) {
27516
- check$1(infe.type === "infe" && infe.body + 4 <= infe.end);
27986
+ check$2(infe.type === "infe" && infe.body + 4 <= infe.end);
27517
27987
  const version = b[infe.body];
27518
- check$1(version === 2 || version === 3);
27988
+ check$2(version === 2 || version === 3);
27519
27989
  let at = infe.body + 4;
27520
27990
  const id = version === 2 ? u16be(b, at) : u32be$1(b, at);
27521
27991
  at += version === 2 ? 2 : 4;
27522
- check$1(at + 6 <= infe.end);
27523
- if (HEIF_METADATA_ITEMS.has(text$1(b, at + 2, 4))) metadata.add(id);
27992
+ check$2(at + 6 <= infe.end);
27993
+ if (HEIF_METADATA_ITEMS.has(text$2(b, at + 2, 4))) metadata.add(id);
27524
27994
  }
27525
27995
  const iprp = one("iprp"), properties = [];
27526
27996
  if (iprp) {
27527
27997
  const held = boxes$1(b, iprp.body, iprp.end);
27528
27998
  const ipco = held.filter((box) => box.type === "ipco");
27529
- check$1(ipco.length === 1 && held.every((box) => box.type === "ipco" || box.type === "ipma"));
27999
+ check$2(ipco.length === 1 && held.every((box) => box.type === "ipco" || box.type === "ipma"));
27530
28000
  properties.push(...boxes$1(b, ipco[0].body, ipco[0].end));
27531
- check$1(properties.every((box) => HEIF_DRAWS.has(box.type) || HEIF_ABOUT.has(box.type)));
28001
+ check$2(properties.every((box) => HEIF_DRAWS.has(box.type) || HEIF_ABOUT.has(box.type)));
27532
28002
  }
27533
28003
  /** `free` and `skip` boxes, at the top and in `meta`, and the properties about the picture: their bodies go as zeros. */
27534
28004
  const space = [...[...top, ...children].filter((box) => box.type === "free" || box.type === "skip"), ...properties.filter((box) => HEIF_ABOUT.has(box.type))];
27535
28005
  const out = b.slice();
27536
28006
  const version = b[iloc.body];
27537
- check$1(version <= 2);
28007
+ check$2(version <= 2);
27538
28008
  let at = iloc.body + 4;
27539
28009
  /** The next field of `size` bytes (0, 2, 4 or 8), big-endian. */
27540
28010
  const read = (size) => {
27541
- check$1(at + size <= iloc.end);
28011
+ check$2(at + size <= iloc.end);
27542
28012
  const value = size === 0 ? 0 : size === 2 ? u16be(b, at) : size === 4 ? u32be$1(b, at) : size === 8 ? u32be$1(b, at) * 2 ** 32 + u32be$1(b, at + 4) : NaN;
27543
- check$1(Number.isSafeInteger(value));
28013
+ check$2(Number.isSafeInteger(value));
27544
28014
  at += size;
27545
28015
  return value;
27546
28016
  };
27547
28017
  const read2 = () => read(2);
27548
- check$1(at + 2 <= iloc.end);
28018
+ check$2(at + 2 <= iloc.end);
27549
28019
  const offsetSize = b[at] >> 4, lengthSize = b[at] & 15, baseSize = b[at + 1] >> 4, indexSize = version > 0 ? b[at + 1] & 15 : 0;
27550
- check$1([
28020
+ check$2([
27551
28021
  offsetSize,
27552
28022
  lengthSize,
27553
28023
  baseSize,
@@ -27566,12 +28036,12 @@ function stripHeif(b) {
27566
28036
  const offset = read(offsetSize), length = read(lengthSize);
27567
28037
  if (!metadata.has(id)) {
27568
28038
  const start = base + offset, end = length ? start + length : b.length;
27569
- check$1(reference !== 0 || method !== 0 || !space.some((box) => start < box.end && end > box.body));
28039
+ check$2(reference !== 0 || method !== 0 || !space.some((box) => start < box.end && end > box.body));
27570
28040
  continue;
27571
28041
  }
27572
- check$1(reference === 0 && length > 0 && (method === 0 || method === 1 && !!idat));
28042
+ check$2(reference === 0 && length > 0 && (method === 0 || method === 1 && !!idat));
27573
28043
  const start = (method === 1 ? idat.body : 0) + base + offset, limit = method === 1 ? idat.end : b.length;
27574
- check$1(start + length <= limit);
28044
+ check$2(start + length <= limit);
27575
28045
  out.fill(0, start, start + length);
27576
28046
  }
27577
28047
  }
@@ -27584,44 +28054,44 @@ var GIF_APPS_KEPT = /* @__PURE__ */ new Set([
27584
28054
  "ICCRGBG1012"
27585
28055
  ]);
27586
28056
  function stripGif(b) {
27587
- check$1(b.length >= 13);
28057
+ check$2(b.length >= 13);
27588
28058
  /** A colour table's bytes, from the flags that say it is there and its size. */
27589
28059
  const table = (flags) => flags & 128 ? 3 << (flags & 7) + 1 : 0;
27590
28060
  /** The end of the data sub-blocks at `at`, past their empty block. */
27591
28061
  const blocks = (at) => {
27592
28062
  for (;;) {
27593
- check$1(at < b.length);
28063
+ check$2(at < b.length);
27594
28064
  const length = b[at];
27595
28065
  at += 1 + length;
27596
28066
  if (!length) return at;
27597
28067
  }
27598
28068
  };
27599
28069
  let at = 13 + table(b[10]), framed = false;
27600
- check$1(at <= b.length);
28070
+ check$2(at <= b.length);
27601
28071
  const parts = [b.subarray(0, at)];
27602
28072
  for (;;) {
27603
- check$1(at < b.length);
28073
+ check$2(at < b.length);
27604
28074
  const introducer = b[at];
27605
28075
  if (introducer === 59) {
27606
- check$1(framed);
28076
+ check$2(framed);
27607
28077
  parts.push(Uint8Array.of(59));
27608
28078
  return parts;
27609
28079
  }
27610
28080
  if (introducer === 44) {
27611
- check$1(at + 10 <= b.length);
28081
+ check$2(at + 10 <= b.length);
27612
28082
  const data = at + 10 + table(b[at + 9]);
27613
- check$1(data < b.length);
28083
+ check$2(data < b.length);
27614
28084
  const end = blocks(data + 1);
27615
28085
  parts.push(b.subarray(at, end));
27616
28086
  framed = true;
27617
28087
  at = end;
27618
28088
  continue;
27619
28089
  }
27620
- check$1(introducer === 33 && at + 2 < b.length);
28090
+ check$2(introducer === 33 && at + 2 < b.length);
27621
28091
  const label = b[at + 1], end = blocks(at + 2);
27622
- const app = label === 255 && b[at + 2] === 11 && GIF_APPS_KEPT.has(text$1(b, at + 3, 11));
28092
+ const app = label === 255 && b[at + 2] === 11 && GIF_APPS_KEPT.has(text$2(b, at + 3, 11));
27623
28093
  if (label === 249 || label === 1 || app) parts.push(b.subarray(at, end));
27624
- else check$1(label === 254 || label === 255);
28094
+ else check$2(label === 254 || label === 255);
27625
28095
  at = end;
27626
28096
  }
27627
28097
  }
@@ -27740,18 +28210,18 @@ var TIFF_TYPE_BYTES = [
27740
28210
  function stripTiff(b) {
27741
28211
  const little = b[0] === 73;
27742
28212
  const u16 = (at) => {
27743
- check$1(at + 2 <= b.length);
28213
+ check$2(at + 2 <= b.length);
27744
28214
  return little ? b[at] | b[at + 1] << 8 : u16be(b, at);
27745
28215
  };
27746
28216
  const u32 = (at) => {
27747
- check$1(at + 4 <= b.length);
27748
- return little ? u32le(b, at) : u32be$1(b, at);
28217
+ check$2(at + 4 <= b.length);
28218
+ return little ? u32le$1(b, at) : u32be$1(b, at);
27749
28219
  };
27750
- check$1(b.length >= 8 && u16(2) === 42);
28220
+ check$2(b.length >= 8 && u16(2) === 42);
27751
28221
  const out = b.slice(), seen = /* @__PURE__ */ new Set();
27752
28222
  /** An IFD's entries: tag, type, the value's first byte (in the entry or where it points) and its bytes. */
27753
28223
  const entries = (ifd) => {
27754
- check$1(ifd >= 8 && !seen.has(ifd) && seen.size < 1024);
28224
+ check$2(ifd >= 8 && !seen.has(ifd) && seen.size < 1024);
27755
28225
  seen.add(ifd);
27756
28226
  const count = u16(ifd), next = ifd + 2 + count * 12;
27757
28227
  u32(next);
@@ -27759,10 +28229,10 @@ function stripTiff(b) {
27759
28229
  next,
27760
28230
  list: Array.from({ length: count }, (_, i) => {
27761
28231
  const at = ifd + 2 + i * 12, tag = u16(at), type = u16(at + 2);
27762
- check$1(type >= 1 && type < TIFF_TYPE_BYTES.length);
28232
+ check$2(type >= 1 && type < TIFF_TYPE_BYTES.length);
27763
28233
  const bytes = TIFF_TYPE_BYTES[type] * u32(at + 4);
27764
28234
  const value = bytes <= 4 ? at + 8 : u32(at + 8);
27765
- check$1(Number.isSafeInteger(bytes) && value + bytes <= b.length);
28235
+ check$2(Number.isSafeInteger(bytes) && value + bytes <= b.length);
27766
28236
  return {
27767
28237
  at,
27768
28238
  tag,
@@ -27777,7 +28247,7 @@ function stripTiff(b) {
27777
28247
  const empty = (ifd) => {
27778
28248
  const { next, list } = entries(ifd);
27779
28249
  for (const entry of list) {
27780
- check$1(entry.tag !== 37500);
28250
+ check$2(entry.tag !== 37500);
27781
28251
  if (TIFF_METADATA_IFDS.has(entry.tag)) empty(u32(entry.value));
27782
28252
  out.fill(0, entry.value, entry.value + entry.bytes);
27783
28253
  }
@@ -27787,16 +28257,16 @@ function stripTiff(b) {
27787
28257
  const { next, list } = entries(ifd);
27788
28258
  let kept = 0;
27789
28259
  for (const { at, tag, value, bytes } of list) {
27790
- if (tag === 259) check$1(TIFF_COMPRESSION.has(u16(value)));
28260
+ if (tag === 259) check$2(TIFF_COMPRESSION.has(u16(value)));
27791
28261
  if (TIFF_METADATA_IFDS.has(tag)) {
27792
28262
  empty(u32(value));
27793
28263
  continue;
27794
28264
  }
27795
28265
  if (TIFF_METADATA.has(tag)) out.fill(0, value, value + bytes);
27796
- else check$1(TIFF_DRAWS.has(tag));
28266
+ else check$2(TIFF_DRAWS.has(tag));
27797
28267
  out.copyWithin(ifd + 2 + kept++ * 12, at, at + 12);
27798
28268
  }
27799
- check$1(kept > 0);
28269
+ check$2(kept > 0);
27800
28270
  const end = ifd + 2 + kept * 12;
27801
28271
  out.set(little ? [kept & 255, kept >> 8] : [kept >> 8, kept & 255], ifd);
27802
28272
  out.set(b.subarray(next, next + 4), end);
@@ -27862,7 +28332,8 @@ async function withoutPictureMetadata(source, mime) {
27862
28332
  *
27863
28333
  * Fail-closed: a file that is an MP4 or QuickTime video, by its bytes or by its type, and whose metadata cannot be
27864
28334
  * removed (truncated, malformed, a part of its movie this does not know) is refused with `NO_VIDEO_METADATA`, never sent as it was.
27865
- * A picture (HEIF is pictureMetadata.ts's), a file without a video track (an M4A) and any other file go as they are.
28335
+ * A picture (HEIF is pictureMetadata.ts's) and any other file go as they are; so does a file without a video track (an
28336
+ * M4A) here: audioMetadata.ts strips it.
27866
28337
  */
27867
28338
  var VIDEO_METADATA_LIMITS = {
27868
28339
  /** The largest `moov` or `moof` read whole, and the most bytes of a metadata track's chunk: past this the video is refused. */
@@ -27997,26 +28468,26 @@ var VISUAL = /* @__PURE__ */ new Set([
27997
28468
  "auxv",
27998
28469
  "pict"
27999
28470
  ]);
28000
- /** Zeros put in a Blob a part at a time. */
28001
- var ZEROS = /* @__PURE__ */ new Uint8Array(1048576);
28471
+ /** Zeros put in a Blob a slice at a time: a Blob's Blob parts are not copied, so a zeroed range of any size holds no more. */
28472
+ var ZEROS$1 = new Blob([/* @__PURE__ */ new Uint8Array(1048576)]);
28002
28473
  var u32be = (b, at) => (b[at] << 24 >>> 0) + (b[at + 1] << 16) + (b[at + 2] << 8) + b[at + 3];
28003
- var text = (b, at, length) => String.fromCharCode(...b.subarray(at, at + length));
28474
+ var text$1 = (b, at, length) => String.fromCharCode(...b.subarray(at, at + length));
28004
28475
  /** Refuses the video where its bytes are not what this expects. */
28005
- function check(ok) {
28476
+ function check$1(ok) {
28006
28477
  if (!ok) throw new Error(NO_VIDEO_METADATA);
28007
28478
  }
28008
28479
  /** A box's header at `at` of `b` (`base` its offset in the file), up to `end` (a size of 0 runs to it). */
28009
28480
  function header(b, at, end, base = 0) {
28010
- check(at + 8 <= b.length);
28481
+ check$1(at + 8 <= b.length);
28011
28482
  let size = u32be(b, at), body = at + 8;
28012
- const type = text(b, at + 4, 4);
28483
+ const type = text$1(b, at + 4, 4);
28013
28484
  if (size === 1) {
28014
- check(at + 16 <= b.length);
28485
+ check$1(at + 16 <= b.length);
28015
28486
  size = u32be(b, at + 8) * 2 ** 32 + u32be(b, at + 12);
28016
28487
  body = at + 16;
28017
28488
  } else if (size === 0) size = end - (base + at);
28018
28489
  if (type === "uuid") body += 16;
28019
- check(Number.isSafeInteger(size) && size >= body - at && base + at + size <= end);
28490
+ check$1(Number.isSafeInteger(size) && size >= body - at && base + at + size <= end);
28020
28491
  return {
28021
28492
  type,
28022
28493
  start: base + at,
@@ -28027,7 +28498,7 @@ function header(b, at, end, base = 0) {
28027
28498
  function boxes(b, start, end) {
28028
28499
  const found = [];
28029
28500
  for (let at = start; at < end;) {
28030
- check(at + 8 <= end);
28501
+ check$1(at + 8 <= end);
28031
28502
  const box = header(b.subarray(0, end), at, end);
28032
28503
  found.push(box);
28033
28504
  at = box.end;
@@ -28061,32 +28532,32 @@ function emptyWithin(b, start, end) {
28061
28532
  */
28062
28533
  function zeroCompressorNames(b, stbl) {
28063
28534
  const stsd = child(b, stbl, "stsd");
28064
- check(!!stsd && stsd.body + 8 <= stsd.end);
28535
+ check$1(!!stsd && stsd.body + 8 <= stsd.end);
28065
28536
  for (const entry of boxes(b, stsd.body + 8, stsd.end)) {
28066
- check(entry.body + 74 <= entry.end);
28537
+ check$1(entry.body + 74 <= entry.end);
28067
28538
  b.fill(0, entry.body + 42, entry.body + 74);
28068
28539
  }
28069
28540
  }
28070
28541
  /** A `mvhd`, `tkhd` or `mdhd` with its creation and modification times zeroed: 32 bits each in version 0, 64 in 1. */
28071
28542
  function zeroTimes(b, box) {
28072
28543
  const version = b[box.body], bytes = version === 1 ? 16 : 8;
28073
- check(version <= 1 && box.body + 4 + bytes <= box.end);
28544
+ check$1(version <= 1 && box.body + 4 + bytes <= box.end);
28074
28545
  b.fill(0, box.body + 4, box.body + 4 + bytes);
28075
28546
  }
28076
28547
  var child = (b, parent, type) => {
28077
28548
  if (!parent) return void 0;
28078
28549
  const of = boxes(b, parent.body, parent.end).filter((box) => box.type === type);
28079
- check(of.length <= 1);
28550
+ check$1(of.length <= 1);
28080
28551
  return of[0];
28081
28552
  };
28082
28553
  /** A sample table's chunks, from its `stco` or `co64`: how many, and where each starts in the file. */
28083
28554
  function chunkOffsets(b, stbl) {
28084
28555
  const stco = child(b, stbl, "stco"), co64 = child(b, stbl, "co64");
28085
- check(!!stco !== !!co64);
28556
+ check$1(!!stco !== !!co64);
28086
28557
  const offsets = stco ?? co64;
28087
- check(offsets.body + 8 <= offsets.end);
28558
+ check$1(offsets.body + 8 <= offsets.end);
28088
28559
  const chunks = u32be(b, offsets.body + 4);
28089
- check(offsets.body + 8 + chunks * (co64 ? 8 : 4) <= offsets.end);
28560
+ check$1(offsets.body + 8 + chunks * (co64 ? 8 : 4) <= offsets.end);
28090
28561
  const offsetOf = (i) => co64 ? u32be(b, co64.body + 8 + i * 8) * 2 ** 32 + u32be(b, co64.body + 12 + i * 8) : u32be(b, stco.body + 8 + i * 4);
28091
28562
  return {
28092
28563
  chunks,
@@ -28096,8 +28567,8 @@ function chunkOffsets(b, stbl) {
28096
28567
  /** The byte ranges of a track's samples in the file, one per chunk, from its sample table. */
28097
28568
  function sampleRanges(b, stbl) {
28098
28569
  const stsz = child(b, stbl, "stsz"), stz2 = child(b, stbl, "stz2"), stsc = child(b, stbl, "stsc");
28099
- check(!!stsc && !!stsz !== !!stz2);
28100
- const need = (box, at, bytes) => check(at + bytes <= box.end);
28570
+ check$1(!!stsc && !!stsz !== !!stz2);
28571
+ const need = (box, at, bytes) => check$1(at + bytes <= box.end);
28101
28572
  const sizeTable = stsz ?? stz2;
28102
28573
  need(sizeTable, sizeTable.body, 12);
28103
28574
  const count = u32be(b, sizeTable.body + 8);
@@ -28110,7 +28581,7 @@ function sampleRanges(b, stbl) {
28110
28581
  sizeOf = (i) => u32be(b, stsz.body + 12 + i * 4);
28111
28582
  } else {
28112
28583
  const field = b[stz2.body + 7];
28113
- check(field === 4 || field === 8 || field === 16);
28584
+ check$1(field === 4 || field === 8 || field === 16);
28114
28585
  need(stz2, stz2.body + 12, Math.ceil(count * field / 8));
28115
28586
  const at = stz2.body + 12;
28116
28587
  sizeOf = field === 16 ? (i) => b[at + i * 2] << 8 | b[at + i * 2 + 1] : field === 8 ? (i) => b[at + i] : (i) => i & 1 ? b[at + (i >> 1)] & 15 : b[at + (i >> 1)] >> 4;
@@ -28124,18 +28595,18 @@ function sampleRanges(b, stbl) {
28124
28595
  for (let run = 0; run < runs; run++) {
28125
28596
  const first = u32be(b, stsc.body + 8 + run * 12), perChunk = u32be(b, stsc.body + 12 + run * 12);
28126
28597
  const last = run + 1 < runs ? u32be(b, stsc.body + 8 + (run + 1) * 12) : chunks + 1;
28127
- check(first >= 1 && last > first && last <= chunks + 1);
28598
+ check$1(first >= 1 && last > first && last <= chunks + 1);
28128
28599
  for (let chunk = first; chunk < last; chunk++) {
28129
28600
  const start = offsetOf(chunk - 1);
28130
- check(sample + perChunk <= count);
28601
+ check$1(sample + perChunk <= count);
28131
28602
  let length = uniform * perChunk;
28132
28603
  if (!uniform) for (let i = 0; i < perChunk; i++) length += sizeOf(sample + i);
28133
28604
  sample += perChunk;
28134
- check(Number.isSafeInteger(start) && length <= VIDEO_METADATA_LIMITS.maxBoxBytes);
28605
+ check$1(Number.isSafeInteger(start) && length <= VIDEO_METADATA_LIMITS.maxBoxBytes);
28135
28606
  if (length) ranges.push([start, start + length]);
28136
28607
  }
28137
28608
  }
28138
- check(sample === count);
28609
+ check$1(sample === count);
28139
28610
  return ranges;
28140
28611
  }
28141
28612
  /** Each track's default sample size in fragments, from `moov`'s `mvex/trex` boxes, by track ID. */
@@ -28144,7 +28615,7 @@ function defaultSampleSizes(moov) {
28144
28615
  const mvex = child(moov, header(moov, 0, moov.length), "mvex");
28145
28616
  for (const trex of mvex ? boxes(moov, mvex.body, mvex.end) : []) {
28146
28617
  if (trex.type !== "trex") continue;
28147
- check(trex.body + 24 <= trex.end);
28618
+ check$1(trex.body + 24 <= trex.end);
28148
28619
  sizes.set(u32be(moov, trex.body + 4), u32be(moov, trex.body + 16));
28149
28620
  }
28150
28621
  return sizes;
@@ -28162,11 +28633,11 @@ function fragmentRanges(b, at, sizes) {
28162
28633
  for (const traf of boxes(b, header(b, 0, b.length).body, b.length)) {
28163
28634
  if (traf.type !== "traf") continue;
28164
28635
  const tfhd = child(b, traf, "tfhd");
28165
- check(!!tfhd && tfhd.body + 8 <= tfhd.end);
28636
+ check$1(!!tfhd && tfhd.body + 8 <= tfhd.end);
28166
28637
  const flags = u32be(b, tfhd.body) & 16777215;
28167
28638
  let field = tfhd.body + 8, base = flags & 131072 ? at : previous;
28168
28639
  if (flags & 1) {
28169
- check(field + 8 <= tfhd.end);
28640
+ check$1(field + 8 <= tfhd.end);
28170
28641
  base = u32be(b, field) * 2 ** 32 + u32be(b, field + 4);
28171
28642
  field += 8;
28172
28643
  }
@@ -28175,17 +28646,17 @@ function fragmentRanges(b, at, sizes) {
28175
28646
  const track = u32be(b, tfhd.body + 4);
28176
28647
  let size = sizes.get(track);
28177
28648
  if (flags & 16) {
28178
- check(field + 4 <= tfhd.end);
28649
+ check$1(field + 4 <= tfhd.end);
28179
28650
  size = u32be(b, field);
28180
28651
  }
28181
28652
  let next = base;
28182
28653
  for (const trun of boxes(b, traf.body, traf.end)) {
28183
28654
  if (trun.type !== "trun") continue;
28184
- check(trun.body + 8 <= trun.end);
28655
+ check$1(trun.body + 8 <= trun.end);
28185
28656
  const runFlags = u32be(b, trun.body) & 16777215, count = u32be(b, trun.body + 4);
28186
28657
  let field = trun.body + 8;
28187
28658
  if (runFlags & 1) {
28188
- check(field + 4 <= trun.end);
28659
+ check$1(field + 4 <= trun.end);
28189
28660
  next = base + (u32be(b, field) | 0);
28190
28661
  field += 4;
28191
28662
  }
@@ -28196,16 +28667,16 @@ function fragmentRanges(b, at, sizes) {
28196
28667
  1024,
28197
28668
  2048
28198
28669
  ].filter((flag) => runFlags & flag).length * 4;
28199
- check(field + count * stride <= trun.end);
28670
+ check$1(field + count * stride <= trun.end);
28200
28671
  let length = 0;
28201
28672
  if (runFlags & 512) {
28202
28673
  const sizeAt = field + (runFlags & 256 ? 4 : 0);
28203
28674
  for (let i = 0; i < count; i++) length += u32be(b, sizeAt + i * stride);
28204
28675
  } else if (count) {
28205
- check(size !== void 0);
28676
+ check$1(size !== void 0);
28206
28677
  length = count * size;
28207
28678
  }
28208
- check(Number.isSafeInteger(next) && Number.isSafeInteger(next + length));
28679
+ check$1(Number.isSafeInteger(next) && Number.isSafeInteger(next + length));
28209
28680
  if (length) ranges.push([
28210
28681
  next,
28211
28682
  next + length,
@@ -28237,7 +28708,7 @@ function stripMoov(b) {
28237
28708
  empty(b, box);
28238
28709
  continue;
28239
28710
  }
28240
- check(MOOV_KEEPS.has(box.type));
28711
+ check$1(MOOV_KEEPS.has(box.type));
28241
28712
  if (SPACE.has(box.type)) b.fill(0, box.body, box.end);
28242
28713
  if (box.type === "mvhd") zeroTimes(b, box);
28243
28714
  if (box.type === "mvex") {
@@ -28251,39 +28722,39 @@ function stripMoov(b) {
28251
28722
  empty(b, part);
28252
28723
  continue;
28253
28724
  }
28254
- check(TRAK_KEEPS.has(part.type));
28725
+ check$1(TRAK_KEEPS.has(part.type));
28255
28726
  if (part.type === "tkhd") {
28256
- check(!tkhd);
28727
+ check$1(!tkhd);
28257
28728
  tkhd = part;
28258
28729
  zeroTimes(b, part);
28259
28730
  }
28260
28731
  if (part.type === "mdia") {
28261
- check(!mdia);
28732
+ check$1(!mdia);
28262
28733
  mdia = part;
28263
28734
  }
28264
28735
  }
28265
- check(!!mdia);
28736
+ check$1(!!mdia);
28266
28737
  const hdlr = child(b, mdia, "hdlr"), minf = child(b, mdia, "minf"), mdhd = child(b, mdia, "mdhd");
28267
- check(!!hdlr && !!minf && hdlr.body + 12 <= hdlr.end);
28738
+ check$1(!!hdlr && !!minf && hdlr.body + 12 <= hdlr.end);
28268
28739
  if (mdhd) zeroTimes(b, mdhd);
28269
- const handler = text(b, hdlr.body + 8, 4);
28740
+ const handler = text$1(b, hdlr.body + 8, 4);
28270
28741
  const stbl = child(b, minf, "stbl");
28271
- check(!!stbl);
28742
+ check$1(!!stbl);
28272
28743
  tables.push(stbl);
28273
28744
  if (handler === "meta") {
28274
- check(selfContained(b, minf));
28745
+ check$1(selfContained(b, minf));
28275
28746
  metadata = true;
28276
28747
  for (const range of sampleRanges(b, stbl)) zeroed.push(range);
28277
28748
  } else if (handler === "tmcd" && selfContained(b, minf)) {
28278
28749
  metadata = true;
28279
28750
  for (const range of sampleRanges(b, stbl)) zeroed.push(range);
28280
28751
  } else if (CAPTIONS.has(handler)) {
28281
- check(selfContained(b, minf) && !!tkhd);
28752
+ check$1(selfContained(b, minf) && !!tkhd);
28282
28753
  const id = tkhd.body + 4 + (b[tkhd.body] === 1 ? 16 : 8);
28283
- check(id + 4 <= tkhd.end);
28754
+ check$1(id + 4 <= tkhd.end);
28284
28755
  captions.add(u32be(b, id));
28285
28756
  for (const range of sampleRanges(b, stbl)) zeroed.push(range);
28286
- } else check(HANDLERS.has(handler));
28757
+ } else check$1(HANDLERS.has(handler));
28287
28758
  if (handler === "vide") video = true;
28288
28759
  if (VISUAL.has(handler)) zeroCompressorNames(b, stbl);
28289
28760
  emptyWithin(b, box.body, box.end);
@@ -28341,9 +28812,9 @@ async function headerAt(source, at) {
28341
28812
  }
28342
28813
  /** A box read whole, within the limit. */
28343
28814
  async function whole(source, box) {
28344
- check(box.end - box.start <= VIDEO_METADATA_LIMITS.maxBoxBytes);
28815
+ check$1(box.end - box.start <= VIDEO_METADATA_LIMITS.maxBoxBytes);
28345
28816
  const bytes = await source.read(box.start, box.end - box.start);
28346
- check(bytes.length === box.end - box.start);
28817
+ check$1(bytes.length === box.end - box.start);
28347
28818
  return bytes;
28348
28819
  }
28349
28820
  /**
@@ -28352,7 +28823,7 @@ async function whole(source, box) {
28352
28823
  * pictureMetadata.ts's.
28353
28824
  */
28354
28825
  function containerOf(head, mime) {
28355
- const first = head.length >= 8 ? text(head, 4, 4) : "";
28826
+ const first = head.length >= 8 ? text$1(head, 4, 4) : "";
28356
28827
  if (isStrippedPicture(head, mime)) return void 0;
28357
28828
  if (FIRST_BOXES.has(first)) return "movie";
28358
28829
  return TOP_KEEPS.has(first) || TOP_EMPTIED.has(first) ? "boxes" : void 0;
@@ -28373,7 +28844,7 @@ async function withoutVideoMetadata(source, mime) {
28373
28844
  for (const patch of patches) {
28374
28845
  if (patch.start > at) parts.push(source.slice(at, patch.start));
28375
28846
  if (patch.bytes) parts.push(patch.bytes);
28376
- else for (let left = patch.end - patch.start; left > 0; left -= ZEROS.length) parts.push(ZEROS.subarray(0, Math.min(left, ZEROS.length)));
28847
+ else for (let left = patch.end - patch.start; left > 0; left -= ZEROS$1.size) parts.push(ZEROS$1.slice(0, Math.min(left, ZEROS$1.size)));
28377
28848
  at = patch.end;
28378
28849
  }
28379
28850
  if (at < source.size) parts.push(source.slice(at));
@@ -28382,9 +28853,9 @@ async function withoutVideoMetadata(source, mime) {
28382
28853
  /**
28383
28854
  * What `withoutVideoMetadata` changes in a video read from `source` (one not held in a Blob: a file kept in storage):
28384
28855
  * the parts replaced, in order and apart, the rest of its bytes going as they are; undefined when it goes as it is.
28385
- * Throws `NO_VIDEO_METADATA` as it does.
28856
+ * Throws `NO_VIDEO_METADATA` as it does. With `audio`, a movie without a video track (an M4A) is stripped too.
28386
28857
  */
28387
- async function videoMetadataPatches(file, mime) {
28858
+ async function videoMetadataPatches(file, mime, audio = false) {
28388
28859
  const source = readingAhead(file);
28389
28860
  const head = await source.read(0, VIDEO_METADATA_LIMITS.headBytes);
28390
28861
  const typed = STRIPPED_TYPES.has(mime.split(";")[0].trim().toLowerCase());
@@ -28400,7 +28871,7 @@ async function videoMetadataPatches(file, mime) {
28400
28871
  const dropped = [];
28401
28872
  let trailer = false;
28402
28873
  for (let at = 0; at < source.size;) {
28403
- check(top.length < VIDEO_METADATA_LIMITS.maxBoxes);
28874
+ check$1(top.length < VIDEO_METADATA_LIMITS.maxBoxes);
28404
28875
  const box = await headerAt(source, at);
28405
28876
  if (!box || top.length && box.type === "\0\0\0\0") {
28406
28877
  patches.push({
@@ -28418,13 +28889,13 @@ async function videoMetadataPatches(file, mime) {
28418
28889
  }
28419
28890
  const moovs = top.filter((box) => box.type === "moov");
28420
28891
  if (!moovs.length && container === "boxes" && !typed) {
28421
- check(!trailer && top.every((box) => TOP_KEEPS.has(box.type) || TOP_EMPTIED.has(box.type)));
28892
+ check$1(!trailer && top.every((box) => TOP_KEEPS.has(box.type) || TOP_EMPTIED.has(box.type)));
28422
28893
  return;
28423
28894
  }
28424
- check(moovs.length === 1);
28895
+ check$1(moovs.length === 1);
28425
28896
  const moov = await whole(source, moovs[0]);
28426
28897
  const { video, fragmented, metadata, zeroed, tables, captions } = stripMoov(moov);
28427
- if (!video && !typed) return void 0;
28898
+ if (!video && !typed && !audio) return void 0;
28428
28899
  patches.push({
28429
28900
  start: moovs[0].start,
28430
28901
  end: moovs[0].end,
@@ -28434,15 +28905,15 @@ async function videoMetadataPatches(file, mime) {
28434
28905
  const { chunks, offsetOf } = chunkOffsets(moov, stbl);
28435
28906
  for (let i = 0; i < chunks; i++) {
28436
28907
  const offset = offsetOf(i);
28437
- check(!meets(dropped, offset, offset + 1));
28908
+ check$1(!meets(dropped, offset, offset + 1));
28438
28909
  }
28439
28910
  }
28440
- check(!fragmented || !metadata);
28911
+ check$1(!fragmented || !metadata);
28441
28912
  const sizes = (dropped.length || captions.size) && fragmented ? defaultSampleSizes(moov) : void 0;
28442
28913
  for (const box of top) if (box.type === "moof") {
28443
28914
  const moof = await whole(source, box);
28444
28915
  if (dropped.length || captions.size) for (const [start, end, track] of fragmentRanges(moof, box.start, sizes ?? /* @__PURE__ */ new Map())) {
28445
- check(!meets(dropped, start, end));
28916
+ check$1(!meets(dropped, start, end));
28446
28917
  if (captions.has(track)) zeroed.push([start, end]);
28447
28918
  }
28448
28919
  emptyWithin(moof, box.body - box.start, moof.length);
@@ -28476,7 +28947,7 @@ async function videoMetadataPatches(file, mime) {
28476
28947
  const mdats = top.filter((box) => box.type === "mdat");
28477
28948
  const merged = [];
28478
28949
  for (const [start, end] of zeroed.sort((a, b) => a[0] - b[0])) {
28479
- check(mdats.some((mdat) => start >= mdat.body && end <= mdat.end));
28950
+ check$1(mdats.some((mdat) => start >= mdat.body && end <= mdat.end));
28480
28951
  const last = merged[merged.length - 1];
28481
28952
  if (last && start <= last[1]) last[1] = Math.max(last[1], end);
28482
28953
  else merged.push([start, end]);
@@ -28487,12 +28958,629 @@ async function videoMetadataPatches(file, mime) {
28487
28958
  });
28488
28959
  let at = 0;
28489
28960
  for (const patch of patches.sort((a, b) => a.start - b.start)) {
28490
- check(patch.start >= at);
28961
+ check$1(patch.start >= at);
28491
28962
  at = patch.end;
28492
28963
  }
28493
28964
  return patches;
28494
28965
  }
28495
28966
  //#endregion
28967
+ //#region ../core/src/audioMetadata.ts
28968
+ /**
28969
+ * What an audio file leaves with. A recording made in another app, or a song a tagger went through, says more than its
28970
+ * sound: a title or a file name that is where it was recorded (a phone's recorder names it after the place), a comment,
28971
+ * a location tag, a picture, the date. The sender removes them before the file is stored and its digest computed, as
28972
+ * pictures' and videos' are (pictureMetadata.ts, videoMetadata.ts), without decoding or re-encoding a sample, and the
28973
+ * file keeps its size, so no offset in it moves and it plays as it did:
28974
+ *
28975
+ * - MP4 audio (M4A, a voice note recorded in MP4): videoMetadata.ts's box walk, its `udta` and `meta` emptied.
28976
+ * - MP3 and AAC: an ID3v2 tag at the start becomes an empty one (its frames zeros: padding), one at the end (with its
28977
+ * footer), an APEv2 tag's items, a Lyrics3v2 tag and an ID3v1 tag's fields become zeros.
28978
+ * - FLAC: every metadata block but its stream info and seek table (a Vorbis comment, a picture, a cue sheet, an
28979
+ * application's) becomes padding, zeroed.
28980
+ * - Ogg Opus, Vorbis and Speex: the comment header keeps its vendor (the encoder's name) and has no comment, the bytes
28981
+ * after it zeros; each page it changed has its checksum made again.
28982
+ * - WAV: every chunk but its format, data and the ones of the sound itself (`fact`, `cue `, `smpl`, `inst`) becomes
28983
+ * `JUNK`, zeroed (an INFO list, an `id3 ` chunk, a broadcast `bext` with its date and originator, XMP).
28984
+ * - WebM and Matroska, audio or video: `Tags`, `Attachments`, `Chapters`, the title, the date, the file names and each
28985
+ * track's name become `Void` elements (and the SeekHead's entries for them); the muxer's and the writing app's names
28986
+ * are zeroed. Clusters, cues and track settings are kept as they are.
28987
+ *
28988
+ * Fail-closed: a file that is one of these by its bytes and whose tags cannot be removed (truncated, malformed) is
28989
+ * refused with `NO_AUDIO_METADATA`, never sent as it was. Any other file goes as it is (other audio formats too).
28990
+ */
28991
+ var AUDIO_METADATA_LIMITS = {
28992
+ /** The largest header, element or tag read whole (an Ogg comment header with a picture in it): past this the file is refused. */
28993
+ maxReadBytes: 67108864,
28994
+ /** The most pages, chunks, blocks or elements walked. */
28995
+ maxParts: 1e6,
28996
+ /** Bytes read first to tell an audio file from another file. */
28997
+ headBytes: 64
28998
+ };
28999
+ /** Why an audio file is refused: its tags could not be removed, so it does not go at all. */
29000
+ var NO_AUDIO_METADATA = "This audio cannot be sent: Ghostly could not remove the details saved in it, like where it was recorded";
29001
+ /** Zeros put in a Blob a slice at a time: a Blob's Blob parts are not copied, so a zeroed range of any size holds no more. */
29002
+ var ZEROS = new Blob([/* @__PURE__ */ new Uint8Array(1048576)]);
29003
+ var text = (b, at, length) => String.fromCharCode(...b.subarray(at, at + length));
29004
+ var u32le = (b, at) => (b[at] | b[at + 1] << 8 | b[at + 2] << 16 | b[at + 3] << 24) >>> 0;
29005
+ var syncsafe = (b, at) => b[at] << 21 | b[at + 1] << 14 | b[at + 2] << 7 | b[at + 3];
29006
+ var latin = (s) => Uint8Array.from(s, (c) => c.charCodeAt(0));
29007
+ /** Refuses the file where its bytes are not what this expects. */
29008
+ function check(ok) {
29009
+ if (!ok) throw new Error(NO_AUDIO_METADATA);
29010
+ }
29011
+ function exactly(source) {
29012
+ return async (offset, length) => {
29013
+ check(offset >= 0 && length >= 0 && length <= AUDIO_METADATA_LIMITS.maxReadBytes && offset + length <= source.size);
29014
+ const bytes = await source.read(offset, length);
29015
+ check(bytes.length === length);
29016
+ return bytes;
29017
+ };
29018
+ }
29019
+ /** Counts the parts walked, so a file of millions of tiny ones is refused rather than walked forever. */
29020
+ function counter() {
29021
+ let parts = 0;
29022
+ return () => check(++parts <= AUDIO_METADATA_LIMITS.maxParts);
29023
+ }
29024
+ /** An ID3v2 header at `at` of `b`: its version 2 to 4 and its size four 7-bit bytes, or none. */
29025
+ var isId3 = (b, at = 0) => b.length >= at + 10 && text(b, at, 3) === "ID3" && b[at + 3] >= 2 && b[at + 3] <= 4 && b[at + 4] !== 255 && [
29026
+ 6,
29027
+ 7,
29028
+ 8,
29029
+ 9
29030
+ ].every((i) => b[at + i] < 128);
29031
+ /**
29032
+ * The ID3v2 tag whose header is `head`, at `at`: made an empty one where it is, its frames (and an extended header)
29033
+ * zeros, which is its padding, its flags but the footer's cleared. Returns where it ends.
29034
+ */
29035
+ async function emptyId3(read, size, at, head, patches) {
29036
+ const body = syncsafe(head, 6), footer = head[3] === 4 && head[5] & 16 ? 10 : 0, end = at + 10 + body + footer;
29037
+ check(end <= size);
29038
+ const flags = Uint8Array.of(footer ? 16 : 0);
29039
+ patches.push({
29040
+ start: at + 5,
29041
+ end: at + 6,
29042
+ bytes: flags
29043
+ });
29044
+ if (body) patches.push({
29045
+ start: at + 10,
29046
+ end: at + 10 + body
29047
+ });
29048
+ if (footer) {
29049
+ check(text(await read(at + 10 + body, 3), 0, 3) === "3DI");
29050
+ patches.push({
29051
+ start: at + 10 + body + 5,
29052
+ end: at + 10 + body + 6,
29053
+ bytes: flags
29054
+ });
29055
+ }
29056
+ return end;
29057
+ }
29058
+ /**
29059
+ * The tags at the end of an MP3 or AAC file (after `start`): an ID3v1 (and its extended part), then any of an APEv2
29060
+ * tag, a Lyrics3v2 tag and an ID3v2 tag with a footer, in any order. Each found is emptied where it is.
29061
+ */
29062
+ async function trailingTags(read, size, start, patches) {
29063
+ let end = size;
29064
+ if (end - 128 >= start && text(await read(end - 128, 3), 0, 3) === "TAG") {
29065
+ patches.push({
29066
+ start: end - 125,
29067
+ end: end - 1
29068
+ }, {
29069
+ start: end - 1,
29070
+ end,
29071
+ bytes: Uint8Array.of(255)
29072
+ });
29073
+ end -= 128;
29074
+ if (end - 227 >= start && text(await read(end - 227, 4), 0, 4) === "TAG+") {
29075
+ patches.push({
29076
+ start: end - 223,
29077
+ end
29078
+ });
29079
+ end -= 227;
29080
+ }
29081
+ }
29082
+ const count = counter();
29083
+ for (;;) {
29084
+ count();
29085
+ if (end - 32 >= start) {
29086
+ const footer = await read(end - 32, 32);
29087
+ if (text(footer, 0, 8) === "APETAGEX") {
29088
+ const length = u32le(footer, 12), header = footer[23] & 128 ? 32 : 0, tagStart = end - length - header;
29089
+ check(length >= 32 && tagStart >= start);
29090
+ if (header) {
29091
+ check(text(await read(tagStart, 8), 0, 8) === "APETAGEX");
29092
+ patches.push({
29093
+ start: tagStart + 16,
29094
+ end: tagStart + 20
29095
+ });
29096
+ }
29097
+ if (length > 32) patches.push({
29098
+ start: tagStart + header,
29099
+ end: end - 32
29100
+ });
29101
+ patches.push({
29102
+ start: end - 16,
29103
+ end: end - 12
29104
+ });
29105
+ end = tagStart;
29106
+ continue;
29107
+ }
29108
+ }
29109
+ if (end - 15 >= start) {
29110
+ const footer = await read(end - 15, 15);
29111
+ if (text(footer, 6, 9) === "LYRICS200") {
29112
+ const length = /^\d{6}$/.test(text(footer, 0, 6)) ? Number(text(footer, 0, 6)) : -1, tagStart = end - 15 - length;
29113
+ check(length >= 11 && tagStart >= start && text(await read(tagStart, 11), 0, 11) === "LYRICSBEGIN");
29114
+ if (length > 11) patches.push({
29115
+ start: tagStart + 11,
29116
+ end: end - 15
29117
+ });
29118
+ end = tagStart;
29119
+ continue;
29120
+ }
29121
+ }
29122
+ if (end - 10 >= start) {
29123
+ const footer = await read(end - 10, 10);
29124
+ if (text(footer, 0, 3) === "3DI") {
29125
+ check([
29126
+ 6,
29127
+ 7,
29128
+ 8,
29129
+ 9
29130
+ ].every((i) => footer[i] < 128));
29131
+ const tagStart = end - 20 - syncsafe(footer, 6);
29132
+ check(tagStart >= start);
29133
+ const head = await read(tagStart, 10);
29134
+ check(isId3(head));
29135
+ check(await emptyId3(read, size, tagStart, head, patches) === end);
29136
+ end = tagStart;
29137
+ continue;
29138
+ }
29139
+ }
29140
+ return;
29141
+ }
29142
+ }
29143
+ /** An MPEG audio frame's or an ADTS header's first bytes: 11 bits set, a version and a layer that are some. */
29144
+ var isFrame = (b, at) => b.length >= at + 2 && b[at] === 255 && (b[at + 1] & 224) === 224 && (b[at + 1] & 24) !== 8;
29145
+ var FLAC_KEEPS = /* @__PURE__ */ new Set([0, 3]);
29146
+ /** A FLAC's metadata blocks from `at` (its `fLaC`): all but its stream info and seek table become padding, zeroed. */
29147
+ async function flac(read, size, at, patches) {
29148
+ const count = counter();
29149
+ for (at += 4;;) {
29150
+ count();
29151
+ const head = await read(at, 4);
29152
+ const last = head[0] & 128, type = head[0] & 127, end = at + 4 + (head[1] << 16 | head[2] << 8 | head[3]);
29153
+ check(type !== 127 && end <= size);
29154
+ if (!FLAC_KEEPS.has(type)) {
29155
+ if (type !== 1) patches.push({
29156
+ start: at,
29157
+ end: at + 1,
29158
+ bytes: Uint8Array.of(last | 1)
29159
+ });
29160
+ if (end > at + 4) patches.push({
29161
+ start: at + 4,
29162
+ end
29163
+ });
29164
+ }
29165
+ at = end;
29166
+ if (last) return at;
29167
+ }
29168
+ }
29169
+ var OGG_CRC = (() => {
29170
+ const table = /* @__PURE__ */ new Uint32Array(256);
29171
+ for (let i = 0; i < 256; i++) {
29172
+ let crc = i << 24;
29173
+ for (let bit = 0; bit < 8; bit++) crc = crc & 2147483648 ? crc << 1 ^ 79764919 : crc << 1;
29174
+ table[i] = crc >>> 0;
29175
+ }
29176
+ return table;
29177
+ })();
29178
+ /** Ogg's page checksum, over the page with its checksum's four bytes zeroed. */
29179
+ function oggCrc(page) {
29180
+ let crc = 0;
29181
+ for (let i = 0; i < page.length; i++) crc = (crc << 8 ^ OGG_CRC[(crc >>> 24 ^ (i >= 22 && i < 26 ? 0 : page[i])) & 255]) >>> 0;
29182
+ return crc;
29183
+ }
29184
+ /**
29185
+ * How a codec's comment header (its second packet) is laid out: its magic's length, and whether a framing bit
29186
+ * follows its comments (Vorbis). Known by the first bytes of its first packet.
29187
+ */
29188
+ var OGG_CODECS = [
29189
+ {
29190
+ head: "OpusHead",
29191
+ comments: "OpusTags",
29192
+ framing: false
29193
+ },
29194
+ {
29195
+ head: "vorbis",
29196
+ comments: "vorbis",
29197
+ framing: true
29198
+ },
29199
+ {
29200
+ head: "Speex ",
29201
+ comments: "",
29202
+ framing: false
29203
+ }
29204
+ ];
29205
+ /**
29206
+ * A comment header with no comment: its magic and vendor kept, its count 0 (and Vorbis's framing bit set), the rest
29207
+ * zeros: padding after the comments, which Opus says may be there and Vorbis's and Speex's readers do not read.
29208
+ */
29209
+ function noComments(packet, codec) {
29210
+ const magic = codec.comments.length;
29211
+ check(text(packet, 0, magic) === codec.comments && packet.length >= magic + 4);
29212
+ const count = magic + 4 + u32le(packet, magic);
29213
+ check(count + 4 + (codec.framing ? 1 : 0) <= packet.length);
29214
+ const out = new Uint8Array(packet.length);
29215
+ out.set(packet.subarray(0, count));
29216
+ if (codec.framing) out[count + 4] = 1;
29217
+ return out;
29218
+ }
29219
+ /**
29220
+ * An Ogg file's pages walked: each logical stream's comment header (a chained file has one per link) made one with no
29221
+ * comment where it is, across the pages it spans, and those pages' checksums made again.
29222
+ */
29223
+ async function ogg(read, size, patches) {
29224
+ const streams = /* @__PURE__ */ new Map();
29225
+ /** The bytes put in the pages changed, by where each page starts: by where they go in the file. */
29226
+ const pages = /* @__PURE__ */ new Map();
29227
+ const packetOf = async (ranges) => {
29228
+ const length = ranges.reduce((sum, [start, end]) => sum + end - start, 0);
29229
+ check(length <= AUDIO_METADATA_LIMITS.maxReadBytes);
29230
+ const packet = new Uint8Array(length);
29231
+ let at = 0;
29232
+ for (const [start, end] of ranges) {
29233
+ packet.set(await read(start, end - start), at);
29234
+ at += end - start;
29235
+ }
29236
+ return packet;
29237
+ };
29238
+ const count = counter();
29239
+ for (let at = 0; at < size;) {
29240
+ count();
29241
+ const head = await read(at, 27);
29242
+ check(text(head, 0, 4) === "OggS" && head[4] === 0);
29243
+ const lacing = await read(at + 27, head[26]);
29244
+ const end = at + 27 + lacing.length + lacing.reduce((sum, l) => sum + l, 0);
29245
+ check(end <= size);
29246
+ const serial = u32le(head, 14);
29247
+ if (head[5] & 2) streams.set(serial, {
29248
+ packet: 0,
29249
+ ranges: []
29250
+ });
29251
+ const stream = streams.get(serial);
29252
+ check(!!stream);
29253
+ let offset = at + 27 + lacing.length;
29254
+ for (const length of lacing) {
29255
+ if (stream.packet <= 1 && stream.codec !== null) stream.ranges.push([
29256
+ offset,
29257
+ offset + length,
29258
+ at
29259
+ ]);
29260
+ offset += length;
29261
+ if (length === 255) continue;
29262
+ if (stream.packet === 0) {
29263
+ const first = await packetOf(stream.ranges);
29264
+ stream.codec = OGG_CODECS.find((codec) => text(first, 0, codec.head.length) === codec.head) ?? null;
29265
+ } else if (stream.packet === 1 && stream.codec) {
29266
+ const emptied = noComments(await packetOf(stream.ranges), stream.codec);
29267
+ let from = 0;
29268
+ for (const [start, until, page] of stream.ranges) {
29269
+ if (!pages.has(page)) pages.set(page, []);
29270
+ pages.get(page).push([start, emptied.subarray(from, from + until - start)]);
29271
+ from += until - start;
29272
+ }
29273
+ }
29274
+ stream.packet++;
29275
+ stream.ranges = [];
29276
+ }
29277
+ at = end;
29278
+ }
29279
+ for (const stream of streams.values()) check(stream.codec === null || stream.packet > 1);
29280
+ for (const [start, changes] of pages) {
29281
+ const head = await read(start, 27), lacing = await read(start + 27, head[26]);
29282
+ const end = start + 27 + lacing.length + lacing.reduce((sum, l) => sum + l, 0);
29283
+ const page = (await read(start, end - start)).slice();
29284
+ for (const [where, bytes] of changes) page.set(bytes, where - start);
29285
+ const crc = oggCrc(page);
29286
+ page.set([
29287
+ crc & 255,
29288
+ crc >>> 8 & 255,
29289
+ crc >>> 16 & 255,
29290
+ crc >>> 24
29291
+ ], 22);
29292
+ patches.push({
29293
+ start,
29294
+ end,
29295
+ bytes: page
29296
+ });
29297
+ }
29298
+ }
29299
+ /** The chunks a WAV's sound is made of, kept; any other becomes `JUNK`. */
29300
+ var WAV_KEEPS = /* @__PURE__ */ new Set([
29301
+ "fmt ",
29302
+ "data",
29303
+ "fact",
29304
+ "cue ",
29305
+ "smpl",
29306
+ "inst"
29307
+ ]);
29308
+ var WAV_SPACE = /* @__PURE__ */ new Set([
29309
+ "JUNK",
29310
+ "junk",
29311
+ "PAD ",
29312
+ "FLLR"
29313
+ ]);
29314
+ async function wav(read, size, patches) {
29315
+ const count = counter();
29316
+ for (let at = 12; at + 8 <= size;) {
29317
+ count();
29318
+ const head = await read(at, 8);
29319
+ const id = text(head, 0, 4), length = u32le(head, 4);
29320
+ let end = at + 8 + length + (length & 1);
29321
+ if (id === "data") end = length ? Math.min(end, size) : size;
29322
+ else check(at + 8 + length <= size);
29323
+ if (!WAV_KEEPS.has(id)) {
29324
+ if (!WAV_SPACE.has(id)) patches.push({
29325
+ start: at,
29326
+ end: at + 4,
29327
+ bytes: latin("JUNK")
29328
+ });
29329
+ if (length) patches.push({
29330
+ start: at + 8,
29331
+ end: at + 8 + length
29332
+ });
29333
+ }
29334
+ at = Math.min(end, size);
29335
+ }
29336
+ }
29337
+ var EBML_HEADER = 440786851;
29338
+ var SEGMENT$1 = 408125543;
29339
+ var CLUSTER = 524531317;
29340
+ var VOID = 236;
29341
+ var CRC32 = 191;
29342
+ var SEEK_HEAD = 290298740;
29343
+ var INFO = 357149030;
29344
+ var TRACKS = 374648427;
29345
+ /** What a segment's sound and pictures are made of, kept; any other top-level element (Tags, Attachments, Chapters) becomes Void. */
29346
+ var SEGMENT_KEEPS = /* @__PURE__ */ new Set([
29347
+ SEEK_HEAD,
29348
+ INFO,
29349
+ TRACKS,
29350
+ CLUSTER,
29351
+ 475249515
29352
+ ]);
29353
+ /** What a cluster holds: one of unknown size ends where an element that is none of these starts. */
29354
+ var CLUSTER_CHILDREN = /* @__PURE__ */ new Set([
29355
+ 231,
29356
+ 22612,
29357
+ 167,
29358
+ 171,
29359
+ 163,
29360
+ 160,
29361
+ 175,
29362
+ VOID,
29363
+ CRC32
29364
+ ]);
29365
+ /** What Info keeps: the timing, the segment's IDs; the muxer's and writing app's names, zeroed. Any other (a title, a date, file names) becomes Void. */
29366
+ var INFO_KEEPS = /* @__PURE__ */ new Set([
29367
+ 2807729,
29368
+ 17545,
29369
+ 29604,
29370
+ 17476,
29371
+ 3979555,
29372
+ 4110627,
29373
+ 26916
29374
+ ]);
29375
+ var INFO_ZEROED = /* @__PURE__ */ new Set([19840, 22337]);
29376
+ var TRACK_ENTRY = 174;
29377
+ var TRACK_NAME = 21358;
29378
+ var SEEK = 19899;
29379
+ var SEEK_ID = 21419;
29380
+ /** The element whose header is at `at` of `b` (`base` its offset in the file); one of unknown size ends at `limit`. */
29381
+ function element(b, at, limit, base = 0) {
29382
+ check(at < b.length);
29383
+ const idLength = Math.clz32(b[at]) - 23;
29384
+ check(idLength >= 1 && idLength <= 4 && at + idLength < b.length);
29385
+ let id = 0;
29386
+ for (let i = 0; i < idLength; i++) id = id * 256 + b[at + i];
29387
+ const sizeAt = at + idLength, sizeLength = Math.clz32(b[sizeAt]) - 23;
29388
+ check(sizeLength >= 1 && sizeLength <= 8 && sizeAt + sizeLength <= b.length);
29389
+ let size = b[sizeAt] & 255 >> sizeLength, ones = size === 255 >> sizeLength;
29390
+ for (let i = 1; i < sizeLength; i++) {
29391
+ size = size * 256 + b[sizeAt + i];
29392
+ ones &&= b[sizeAt + i] === 255;
29393
+ }
29394
+ const body = base + sizeAt + sizeLength;
29395
+ return {
29396
+ id,
29397
+ start: base + at,
29398
+ body,
29399
+ end: ones ? limit : body + size,
29400
+ unknown: ones
29401
+ };
29402
+ }
29403
+ /** An element's header read from the file at `at`. */
29404
+ async function elementAt(source, at, limit) {
29405
+ return element(await source.read(at, 12), 0, limit, at);
29406
+ }
29407
+ /** A Void element `length` bytes long: its ID, its size in as many bytes as it takes to fill it, the rest zeros. */
29408
+ function voidHeader(length) {
29409
+ for (let sizeLength = 1; sizeLength <= 8; sizeLength++) {
29410
+ const body = length - 1 - sizeLength;
29411
+ if (body < 0 || body >= 2 ** (7 * sizeLength) - 1) continue;
29412
+ const header = new Uint8Array(1 + sizeLength);
29413
+ header[0] = VOID;
29414
+ for (let i = sizeLength, rest = body; i >= 1; i--, rest = Math.floor(rest / 256)) header[i] = rest % 256;
29415
+ header[1] |= 128 >> sizeLength - 1;
29416
+ return header;
29417
+ }
29418
+ check(false);
29419
+ }
29420
+ /** `el` of `b` (read whole, `el`'s offsets in it) made Void where it is. */
29421
+ function voidIn(b, el) {
29422
+ const header = voidHeader(el.end - el.start);
29423
+ b.fill(0, el.start, el.end);
29424
+ b.set(header, el.start);
29425
+ }
29426
+ /** The children of `parent` (in `b`, read whole) as elements, each within it. */
29427
+ function childrenOf(b, parent) {
29428
+ const found = [];
29429
+ for (let at = parent.body; at < parent.end;) {
29430
+ const child = element(b.subarray(0, parent.end), at, parent.end);
29431
+ check(!child.unknown && child.end <= parent.end);
29432
+ found.push(child);
29433
+ at = child.end;
29434
+ }
29435
+ return found;
29436
+ }
29437
+ /**
29438
+ * A top-level element of a segment read whole and changed in it: Info without its title, date and file names (its
29439
+ * muxer's and writing app's names zeroed), Tracks without their names, a SeekHead without the entries for what
29440
+ * became Void. A CRC-32 in them, wrong once they changed, becomes Void too.
29441
+ */
29442
+ function stripTopLevel(b) {
29443
+ const top = element(b, 0, b.length);
29444
+ check(!top.unknown && top.end === b.length);
29445
+ for (const child of childrenOf(b, top)) {
29446
+ if (child.id === CRC32) voidIn(b, child);
29447
+ else if (top.id === INFO) {
29448
+ if (INFO_ZEROED.has(child.id)) b.fill(0, child.body, child.end);
29449
+ else if (!INFO_KEEPS.has(child.id) && child.id !== VOID) voidIn(b, child);
29450
+ } else if (top.id === TRACKS && child.id === TRACK_ENTRY) {
29451
+ for (const part of childrenOf(b, child)) if (part.id === TRACK_NAME || part.id === CRC32) voidIn(b, part);
29452
+ } else if (top.id === SEEK_HEAD && child.id === SEEK) {
29453
+ const target = childrenOf(b, child).find((part) => part.id === SEEK_ID);
29454
+ let id = 0;
29455
+ if (target) for (let i = target.body; i < target.end; i++) id = id * 256 + b[i];
29456
+ if (!SEGMENT_KEEPS.has(id)) voidIn(b, child);
29457
+ }
29458
+ if (child.id === VOID) b.fill(0, child.body, child.end);
29459
+ }
29460
+ }
29461
+ /** Where a cluster of unknown size ends: at the first element that is not a cluster's, or the segment's end. */
29462
+ async function clusterEnd(source, at, limit, count) {
29463
+ for (;;) {
29464
+ count();
29465
+ if (at >= limit) return limit;
29466
+ const child = await elementAt(source, at, limit);
29467
+ if (!CLUSTER_CHILDREN.has(child.id)) return at;
29468
+ check(!child.unknown);
29469
+ if (child.end >= limit) return limit;
29470
+ at = child.end;
29471
+ }
29472
+ }
29473
+ async function matroska(source, read, patches) {
29474
+ const count = counter();
29475
+ const toVoid = (el) => {
29476
+ const header = voidHeader(el.end - el.start);
29477
+ patches.push({
29478
+ start: el.start,
29479
+ end: el.start + header.length,
29480
+ bytes: header
29481
+ });
29482
+ if (el.end > el.start + header.length) patches.push({
29483
+ start: el.start + header.length,
29484
+ end: el.end
29485
+ });
29486
+ };
29487
+ for (let at = 0; at < source.size;) {
29488
+ count();
29489
+ const top = await elementAt(source, at, source.size);
29490
+ check(top.end <= source.size);
29491
+ if (top.id === EBML_HEADER) check(!top.unknown);
29492
+ else if (top.id === VOID) {
29493
+ if (top.end > top.body) patches.push({
29494
+ start: top.body,
29495
+ end: top.end
29496
+ });
29497
+ } else if (top.id !== SEGMENT$1) {
29498
+ check(!top.unknown);
29499
+ toVoid(top);
29500
+ } else for (let in_ = top.body; in_ < top.end;) {
29501
+ count();
29502
+ const el = await elementAt(source, in_, top.end);
29503
+ if (el.id === CLUSTER) {
29504
+ in_ = el.unknown ? await clusterEnd(source, el.body, top.end, count) : Math.min(el.end, top.end);
29505
+ continue;
29506
+ }
29507
+ check(!el.unknown && el.end <= top.end);
29508
+ if (el.id === INFO || el.id === TRACKS || el.id === SEEK_HEAD) {
29509
+ const bytes = (await read(el.start, el.end - el.start)).slice();
29510
+ stripTopLevel(bytes);
29511
+ patches.push({
29512
+ start: el.start,
29513
+ end: el.end,
29514
+ bytes
29515
+ });
29516
+ } else if (el.id === VOID) {
29517
+ if (el.end > el.body) patches.push({
29518
+ start: el.body,
29519
+ end: el.end
29520
+ });
29521
+ } else if (!SEGMENT_KEEPS.has(el.id)) toVoid(el);
29522
+ in_ = el.end;
29523
+ }
29524
+ at = top.end;
29525
+ }
29526
+ }
29527
+ /**
29528
+ * What `withoutAudioMetadata` changes in an audio file read from `source` (one not held in a Blob: a file kept in
29529
+ * storage): the parts replaced, in order and apart, the rest of its bytes going as they are; undefined when it goes as
29530
+ * it is. Throws `NO_AUDIO_METADATA` for one whose tags cannot be removed; an error reading `source` as it is.
29531
+ */
29532
+ async function audioMetadataPatches(file, mime) {
29533
+ const source = readingAhead(file), read = exactly(source), size = source.size;
29534
+ const head = await source.read(0, Math.min(AUDIO_METADATA_LIMITS.headBytes, size));
29535
+ const patches = [];
29536
+ if (head.length >= 8 && text(head, 4, 4) === "ftyp") try {
29537
+ return await videoMetadataPatches(file, mime, true);
29538
+ } catch (error) {
29539
+ if (error instanceof Error && error.message === "This video cannot be sent: Ghostly could not remove the details saved in it, like where it was recorded") throw Object.assign(/* @__PURE__ */ new Error(NO_AUDIO_METADATA), { cause: error });
29540
+ throw error;
29541
+ }
29542
+ else if (text(head, 0, 4) === "OggS") await ogg(read, size, patches);
29543
+ else if (head.length >= 12 && text(head, 0, 4) === "RIFF" && text(head, 8, 4) === "WAVE") await wav(read, size, patches);
29544
+ else if (text(head, 0, 4) === "Eߣ") await matroska(source, read, patches);
29545
+ else if (text(head, 0, 4) === "fLaC") await trailingTags(read, size, await flac(read, size, 0, patches), patches);
29546
+ else if (isId3(head) || isFrame(head, 0)) {
29547
+ let at = 0;
29548
+ const count = counter();
29549
+ for (let next = head; isId3(next); next = at + 10 <= size ? await read(at, 10) : /* @__PURE__ */ new Uint8Array(0)) {
29550
+ count();
29551
+ at = await emptyId3(read, size, at, next, patches);
29552
+ }
29553
+ if (at + 4 <= size && text(await read(at, 4), 0, 4) === "fLaC") at = await flac(read, size, at, patches);
29554
+ await trailingTags(read, size, at, patches);
29555
+ } else return void 0;
29556
+ if (!patches.length) return void 0;
29557
+ patches.sort((a, b) => a.start - b.start);
29558
+ for (let i = 1; i < patches.length; i++) check(patches[i].start >= patches[i - 1].end);
29559
+ return patches;
29560
+ }
29561
+ /**
29562
+ * `source` as it is sent: an audio file without its tags, made of `source`'s own bytes but for the parts emptied;
29563
+ * undefined when it goes as it is (not one of these, or one with nothing to remove). Throws `NO_AUDIO_METADATA` for
29564
+ * one whose tags cannot be removed; an error reading `source` as it is.
29565
+ */
29566
+ async function withoutAudioMetadata(source, mime) {
29567
+ const patches = await audioMetadataPatches({
29568
+ size: source.size,
29569
+ read: async (offset, length) => new Uint8Array(await source.slice(offset, offset + length).arrayBuffer())
29570
+ }, mime);
29571
+ if (!patches) return void 0;
29572
+ const parts = [];
29573
+ let at = 0;
29574
+ for (const patch of patches) {
29575
+ if (patch.start > at) parts.push(source.slice(at, patch.start));
29576
+ if (patch.bytes) parts.push(patch.bytes);
29577
+ else for (let left = patch.end - patch.start; left > 0; left -= ZEROS.size) parts.push(ZEROS.slice(0, Math.min(left, ZEROS.size)));
29578
+ at = patch.end;
29579
+ }
29580
+ if (at < source.size) parts.push(source.slice(at));
29581
+ return new Blob(parts, { type: mime });
29582
+ }
29583
+ //#endregion
28496
29584
  //#region ../core/src/payments.ts
28497
29585
  /**
28498
29586
  * Payments between two linked peers. Ghostly does not move money itself: it
@@ -32045,13 +33133,19 @@ function openGroupMeta(frame, messageKey) {
32045
33133
  const body = decryptText(messageKey, boxAad(frame.statement.g, frame.k, frame.statement.d), frame.nn, frame.c);
32046
33134
  if (body === null || sha256Hex(utf8Encode(body)) !== frame.statement.d) return null;
32047
33135
  const parsed = parseGroupMetaBody(body);
32048
- return parsed ? {
32049
- meta: {
32050
- ...frame.statement,
32051
- body
32052
- },
32053
- body: parsed
32054
- } : null;
33136
+ if (!parsed) return null;
33137
+ const meta = {
33138
+ ...frame.statement,
33139
+ body
33140
+ };
33141
+ parsedBodies.set(meta, {
33142
+ body,
33143
+ parsed
33144
+ });
33145
+ return {
33146
+ meta,
33147
+ body: copyBody(parsed)
33148
+ };
32055
33149
  }
32056
33150
  /** Is `a` later than `b`: signed under a later commit, or a higher revision under the same one. */
32057
33151
  function groupMetaNewer(a, b) {
@@ -32094,13 +33188,40 @@ function parseGroupMetaTag(tag) {
32094
33188
  r
32095
33189
  };
32096
33190
  }
33191
+ /**
33192
+ * Each kept statement's body as `parseGroupMetaBody` reads it, worked out once per statement: the sessions' `name` and
33193
+ * `picture` read it on every engine state, and checking a picture (`sanitizeAvatar`) costs ~0.2 ms at 40 KB. Keyed by
33194
+ * the statement object, so an entry goes with the statement it was made for; the body it was made from is kept beside
33195
+ * it, and a statement whose body was swapped in place is read again.
33196
+ */
33197
+ var parsedBodies = /* @__PURE__ */ new WeakMap();
33198
+ function parsedBody(meta) {
33199
+ const hit = parsedBodies.get(meta);
33200
+ if (hit && hit.body === meta.body) return hit.parsed;
33201
+ const parsed = parseGroupMetaBody(meta.body);
33202
+ parsedBodies.set(meta, {
33203
+ body: meta.body,
33204
+ parsed
33205
+ });
33206
+ return parsed;
33207
+ }
33208
+ /** A body the caller may change without changing the one kept for its statement. */
33209
+ function copyBody(parsed) {
33210
+ const copy = { ...parsed };
33211
+ if (parsed.hubs) copy.hubs = {
33212
+ pin: [...parsed.hubs.pin],
33213
+ no: [...parsed.hubs.no]
33214
+ };
33215
+ return copy;
33216
+ }
32097
33217
  /** What a kept statement's body says, `{}` for none. */
32098
33218
  function groupMetaBody(meta) {
32099
- return meta && parseGroupMetaBody(meta.body) || {};
33219
+ const parsed = meta && parsedBody(meta);
33220
+ return parsed ? copyBody(parsed) : {};
32100
33221
  }
32101
33222
  /** The picture a kept statement's body names, if it is one Ghostly shows. */
32102
33223
  function groupMetaPicture(meta) {
32103
- return groupMetaBody(meta).pic;
33224
+ return (meta && parsedBody(meta))?.pic;
32104
33225
  }
32105
33226
  /**
32106
33227
  * The name members see: the one the admin's statement gives, else the name the group had when this member got in
@@ -32108,7 +33229,7 @@ function groupMetaPicture(meta) {
32108
33229
  * names show, and what a member shows until the statement reaches them.
32109
33230
  */
32110
33231
  function groupDisplayName(meta, first) {
32111
- return groupMetaBody(meta).name ?? first;
33232
+ return (meta && parsedBody(meta))?.name ?? first;
32112
33233
  }
32113
33234
  /**
32114
33235
  * The name and picture that differ between two statements; null when neither does (hubs alone, or the same body signed
@@ -32932,8 +34053,8 @@ var GroupSession = class {
32932
34053
  messagePace = /* @__PURE__ */ new Map();
32933
34054
  editPace = /* @__PURE__ */ new Map();
32934
34055
  queue = Promise.resolve();
32935
- /** One metadata frame that names a commit or an epoch I do not have yet: tried again when the chain moves. */
32936
- pendingMeta;
34056
+ /** Metadata frames that name a commit or an epoch I do not have yet, one signed by the admin and one by anyone else (`waitMeta`): tried again when the chain moves. */
34057
+ pendingMeta = {};
32937
34058
  /** While `handle` runs: the frames it took that a hub passes on (`handle`'s result). */
32938
34059
  passOn = null;
32939
34060
  /** The frames kept to hand on that the app holds with its messages, oldest first; undefined when the state holds them all. */
@@ -32945,6 +34066,12 @@ var GroupSession = class {
32945
34066
  * them is not handed them again at every sync. In memory only.
32946
34067
  */
32947
34068
  leaversHanded = /* @__PURE__ */ new Map();
34069
+ /**
34070
+ * The kept edits each hub I count on was handed that it cannot read (`editKey`): of epochs from before it was let in,
34071
+ * for it to carry to the members of those epochs. Each goes to a hub once while my app runs, not at every sync of its
34072
+ * own. In memory only.
34073
+ */
34074
+ carriedHanded = /* @__PURE__ */ new Map();
32948
34075
  /** Syncs answered per member, a few a minute (`GROUP_LIMITS.syncAnswers`). In memory only. */
32949
34076
  syncsAnswered = /* @__PURE__ */ new Map();
32950
34077
  /**
@@ -32991,7 +34118,12 @@ var GroupSession = class {
32991
34118
  const handed = this.leaversHanded.get(to) ?? /* @__PURE__ */ new Set();
32992
34119
  this.leaversHanded.set(to, handed.add(editKey(frame)));
32993
34120
  }
32994
- return hooks.send(to, frame);
34121
+ const took = hooks.send(to, frame);
34122
+ if (took !== false && frame.t === "group-edit" && !rosterHas(this.state.chain[frame.e]?.m ?? [], to)) {
34123
+ const carried = this.carriedHanded.get(to) ?? /* @__PURE__ */ new Set();
34124
+ this.carriedHanded.set(to, carried.add(editKey(frame)));
34125
+ }
34126
+ return took;
32995
34127
  },
32996
34128
  ...hooks.handled && { handled: (to) => hooks.handled(to) },
32997
34129
  active: () => this.state.status === "active",
@@ -34865,8 +35997,14 @@ var GroupSession = class {
34865
35997
  answer.push(f);
34866
35998
  }
34867
35999
  const readable = (f) => !!this.state.chain[f.e] && rosterHas(this.state.chain[f.e].m, from);
36000
+ const carrier = !!this.hooks.carriers?.().includes(from), carried = this.carriedHanded.get(from);
36001
+ if (carried) {
36002
+ const held = new Set((this.state.relayEdits ?? []).map(editKey));
36003
+ for (const key of carried) if (!held.has(key)) carried.delete(key);
36004
+ }
36005
+ const owed = (f) => readable(f) || carrier && !!this.state.chain[f.e] && !carried?.has(editKey(f));
34868
36006
  for (const author of asked) {
34869
- const edits = (this.state.relayEdits ?? []).filter((f) => f.s === author && readable(f));
36007
+ const edits = (this.state.relayEdits ?? []).filter((f) => f.s === author && owed(f));
34870
36008
  answer.push(...edits.slice(-GROUP_LIMITS.handOnEdits));
34871
36009
  }
34872
36010
  const handed = this.leaversHanded.get(from);
@@ -35000,22 +36138,14 @@ var GroupSession = class {
35000
36138
  const s = frame.statement;
35001
36139
  if (!groupMetaNewer(s, this.state.meta)) return;
35002
36140
  if (s.e > this.epoch || frame.k > this.epoch) {
35003
- this.pendingMeta = {
35004
- from,
35005
- frame: raw
35006
- };
35007
- this.ask(from);
36141
+ this.waitMeta(from, raw, s);
35008
36142
  return;
35009
36143
  }
35010
36144
  const commit = this.state.chain[s.e];
35011
36145
  if (commitHash(commit) !== s.h || rosterAdmin(commit.m) !== s.by || this.admin !== s.by || !verifyGroupMetaSignature(s)) return;
35012
36146
  const secret = this.secret(frame.k);
35013
36147
  if (!secret) {
35014
- this.pendingMeta = {
35015
- from,
35016
- frame: raw
35017
- };
35018
- this.ask(from);
36148
+ this.waitMeta(from, raw, s);
35019
36149
  return;
35020
36150
  }
35021
36151
  const opened = openGroupMeta(frame, epochKeys(secret, this.id, frame.k).message);
@@ -35036,6 +36166,21 @@ var GroupSession = class {
35036
36166
  });
35037
36167
  }
35038
36168
  /**
36169
+ * A statement that waits for the chain: only one its signer signed, so an altered copy cannot push out the one
36170
+ * waiting. The admin I know has a place of their own, which another member's statement cannot take, and in each
36171
+ * place only a later statement takes the one waiting.
36172
+ */
36173
+ waitMeta(from, raw, s) {
36174
+ if (!verifyGroupMetaSignature(s)) return;
36175
+ const place = s.by === this.admin ? "admin" : "other", waiting = this.pendingMeta[place];
36176
+ if (!waiting || groupMetaNewer(s, waiting.s)) this.pendingMeta[place] = {
36177
+ from,
36178
+ frame: raw,
36179
+ s
36180
+ };
36181
+ this.ask(from);
36182
+ }
36183
+ /**
35039
36184
  * Who made the change a statement brings me: its signer, when they were the admin all along since the statement I
35040
36185
  * held (or, with none, since I got in). A new admin signs again what the last one set (`metaFollowsChain`): to a
35041
36186
  * member that missed that, it is no change of theirs it can tell apart, so nobody is named. With none held, theirs is
@@ -35052,9 +36197,9 @@ var GroupSession = class {
35052
36197
  }
35053
36198
  /** After the chain or my secrets moved: the waiting statement, and, if I became the admin, the name and picture signed again as mine. */
35054
36199
  async metaFollowsChain() {
35055
- const pending = this.pendingMeta;
35056
- this.pendingMeta = void 0;
35057
- if (pending) await this.receiveMeta(pending.from, pending.frame);
36200
+ const { admin, other } = this.pendingMeta;
36201
+ this.pendingMeta = {};
36202
+ for (const pending of [admin, other]) if (pending) await this.receiveMeta(pending.from, pending.frame);
35058
36203
  if (this.isAdmin && this.state.meta && this.state.meta.by !== this.myKey) await this.publishMeta(this.state.meta.body, this.state.meta.ts, true);
35059
36204
  }
35060
36205
  async fork(reason) {
@@ -35839,6 +36984,14 @@ var CommunitySession = class CommunitySession {
35839
36984
  asked = /* @__PURE__ */ new Map();
35840
36985
  /** Per member: until when what comes over its edge may be its answer to my sync (`ANSWER_WINDOW_MS`). In memory only. */
35841
36986
  answering = /* @__PURE__ */ new Map();
36987
+ /**
36988
+ * Per member asked: what my sync said I have (`have`), the highest number its answer handed per author and commit
36989
+ * (`top`), and whether anything of the answer came (`heard`). Once the answer is over (`settleGaps`), what it did
36990
+ * not fill below those is nobody's to hand (a hint, never kept; a frame out of every store). In memory only.
36991
+ */
36992
+ answerOf = /* @__PURE__ */ new Map();
36993
+ /** Author → `e:h16` → the number up to which a gap is gone (`settleGaps`), not on its way: `missing` leaves it out. In memory only. */
36994
+ gapsGone = {};
35842
36995
  /** The message frames given to `handle` that came live here (`CommunityIncomingMessage.live`): `passOn` marks them. */
35843
36996
  cameLive = /* @__PURE__ */ new WeakSet();
35844
36997
  /** Syncs answered per member, a few a minute (`COMMUNITY_LIMITS.syncAnswers`). In memory only. */
@@ -35855,12 +37008,16 @@ var CommunitySession = class CommunitySession {
35855
37008
  /** My frames said again in this run (`e:h16:n`) → the id of the message they first were. In memory only. */
35856
37009
  resealedFrom = /* @__PURE__ */ new Map();
35857
37010
  saveTimer;
35858
- /** One metadata frame naming a commit or a secret I do not have yet: tried again when the chain or my secrets move. */
35859
- pendingMeta;
37011
+ /** Metadata frames naming a commit or a secret I do not have yet, one signed by the admin and one by anyone else (`waitMeta`): tried again when the chain or my secrets move. */
37012
+ pendingMeta = {};
35860
37013
  /** The store's frames the app holds with their messages (`storeKey` → message id): in memory here, not in what is saved. */
35861
37014
  onRows = /* @__PURE__ */ new Map();
35862
37015
  /** The oldest epoch whose seen marks are kept, as of the last `pruneSeen`. In memory only. */
35863
37016
  seenFrom = -1;
37017
+ /** The secret of the epoch I left in (`leave`), for `followAfterLeave`. In memory only. */
37018
+ leftSecret;
37019
+ /** After my leave, still taking commits and secrets (`followAfterLeave`). In memory only. */
37020
+ following = false;
35864
37021
  /** `rows`: the frames the app holds with the messages it stored (`CommunityIncomingMessage.frame`). They join the store. */
35865
37022
  constructor(state, hooks, rows = []) {
35866
37023
  this.hooks = hooks;
@@ -36267,13 +37424,50 @@ var CommunitySession = class CommunitySession {
36267
37424
  commit
36268
37425
  }));
36269
37426
  }
37427
+ /**
37428
+ * How many of a member's messages under the current commit are known to be missing: on their way, not gone (a
37429
+ * finished answer did not fill it, `settleGaps`; or syncs gave it up, `haveOf`). A hint spends its author's number
37430
+ * and is never kept (WISP 903), so a member who was away counted it missing until the commit changed.
37431
+ */
36270
37432
  missing(sender) {
36271
- const entry = this.state.seen[sender]?.[seenKey(this.epoch, shortHash(this.topHash))];
37433
+ this.settleAnswers();
37434
+ const key = seenKey(this.epoch, shortHash(this.topHash));
37435
+ const entry = this.state.seen[sender]?.[key];
36272
37436
  if (!entry) return 0;
36273
- const lowest = Math.max(0, entry.high - COMMUNITY_LIMITS.replay + 1);
37437
+ const lowest = Math.max(0, entry.high - COMMUNITY_LIMITS.replay + 1, (entry.floor ?? -1) + 1, (this.gapsGone[sender]?.[key] ?? -1) + 1);
36274
37438
  return Math.max(0, entry.high - lowest + 1 - (1 + entry.window.filter((n) => n >= lowest).length));
36275
37439
  }
36276
37440
  /**
37441
+ * Gaps that the answers now over did not fill count as gone: an answer hands every frame its member holds above what
37442
+ * my sync said I have, so a number below my mark then, or below the highest it handed, that is still not here is
37443
+ * held by nobody. Returns whether some became gone (the members view changes). A sync nobody answered settles nothing.
37444
+ */
37445
+ settleGaps() {
37446
+ const changed = this.settleAnswers();
37447
+ for (const [sender, byKey] of Object.entries(this.gapsGone)) {
37448
+ for (const key of Object.keys(byKey)) if (!this.state.seen[sender]?.[key]) delete byKey[key];
37449
+ if (!Object.keys(byKey).length) delete this.gapsGone[sender];
37450
+ }
37451
+ return changed;
37452
+ }
37453
+ /** The gaps of the answers now over (`settleGaps`), without the prune. */
37454
+ settleAnswers() {
37455
+ if (!this.answerOf.size) return false;
37456
+ const now = this.hooks.clock?.() ?? Date.now();
37457
+ let changed = false;
37458
+ for (const [from, answer] of this.answerOf) {
37459
+ if ((this.answering.get(from) ?? 0) > now) continue;
37460
+ this.answerOf.delete(from);
37461
+ if (!answer.heard) continue;
37462
+ for (const marks of [answer.have, answer.top]) for (const [sender, byKey] of Object.entries(marks)) for (const [key, upTo] of Object.entries(byKey)) {
37463
+ if (!this.state.seen[sender]?.[key] || upTo <= (this.gapsGone[sender]?.[key] ?? -1)) continue;
37464
+ (this.gapsGone[sender] ??= {})[key] = upTo;
37465
+ changed = true;
37466
+ }
37467
+ }
37468
+ return changed;
37469
+ }
37470
+ /**
36277
37471
  * Replays the main branch (rosters kept for its window) and places the side commits. The main branch was verified
36278
37472
  * commit by commit when it was accepted: its signatures are not checked again.
36279
37473
  */
@@ -36720,19 +37914,33 @@ var CommunitySession = class CommunitySession {
36720
37914
  }
36721
37915
  for (const h of Object.keys(this.state.secrets)) if (!keep.has(h)) delete this.state.secrets[h];
36722
37916
  }
37917
+ /** The epoch of the commit on the main branch that took `key` out (`outIndex`), while it is out. */
37918
+ outEpoch(key) {
37919
+ const i = this.outIndex(key);
37920
+ return i < 0 ? void 0 : this.state.chain[i].e;
37921
+ }
37922
+ /**
37923
+ * Whether `key` reads commit `h`, so its secret may be sealed to it or taken by it: in its roster, and not out by then.
37924
+ * A member stops being one at the commit that takes it out: a side branch from before it may list it still, at that
37925
+ * epoch or later, and that epoch's secret and every later one never reach it.
37926
+ */
37927
+ readsAt(h, key, out = this.outEpoch(key)) {
37928
+ const c = this.known.get(h);
37929
+ return !!c && rosterHas(this.rosterAt(h) ?? [], key) && (out === void 0 || c.e < out);
37930
+ }
36723
37931
  /** A derived epoch's secret, from its parent's, when that is held. */
36724
37932
  takeDerived(h) {
36725
37933
  const c = this.known.get(h);
36726
37934
  if (!c || this.state.secrets[h] || FRESH.has(c.k)) return;
36727
37935
  const parent = this.state.secrets[c.p];
36728
- if (!parent || !rosterHas(this.rosterAt(h) ?? [], this.myKey)) return;
37936
+ if (!parent || !this.readsAt(h, this.myKey)) return;
36729
37937
  const secret = derivedSecret(fromBase64Url(parent), communityUntaggedHash(c));
36730
37938
  if (confirmationMatches(epochKeys(secret, this.id, c.e).confirm, communityUntaggedHash(c), c.c)) {
36731
37939
  this.state.secrets[h] = toBase64Url(secret);
36732
37940
  for (const [child, cc] of this.known) if (cc.p === h) this.takeDerived(child);
36733
37941
  }
36734
37942
  }
36735
- /** A sealed secret for a known commit I am in the roster of: kept only when it confirms. */
37943
+ /** A sealed secret for a known commit I read (`readsAt`): kept only when it confirms. */
36736
37944
  takeSecret(h, sealed) {
36737
37945
  const c = this.known.get(h);
36738
37946
  if (!c) {
@@ -36747,7 +37955,7 @@ var CommunitySession = class CommunitySession {
36747
37955
  });
36748
37956
  return false;
36749
37957
  }
36750
- if (this.state.secrets[h] || !isSealed(sealed) || !rosterHas(this.rosterAt(h) ?? [], this.myKey)) return false;
37958
+ if (this.state.secrets[h] || !isSealed(sealed) || !this.readsAt(h, this.myKey)) return false;
36751
37959
  const secret = openSecret(this.identity.seed, this.myKey, sealed, secretAad(this.id, h, this.myKey));
36752
37960
  if (!secret || !confirmationMatches(epochKeys(secret, this.id, c.e).confirm, communityUntaggedHash(c), c.c)) return false;
36753
37961
  this.state.secrets[h] = toBase64Url(secret);
@@ -37027,9 +38235,10 @@ var CommunitySession = class CommunitySession {
37027
38235
  }
37028
38236
  /**
37029
38237
  * Leaves: a signed request any other member commits, and my secrets go now. The admin must
37030
- * hand over the role first (the engine does it for a leaving admin).
38238
+ * hand over the role first (the engine does it for a leaving admin). `follow`: commits and secrets are still taken
38239
+ * after (`followAfterLeave`).
37031
38240
  */
37032
- leave() {
38241
+ leave(follow = false) {
37033
38242
  return this.serialize(async () => {
37034
38243
  if (this.state.status !== "active") return null;
37035
38244
  if (this.isAdmin && this.others.length) throw new Error("Make someone else the admin before leaving");
@@ -37045,19 +38254,66 @@ var CommunitySession = class CommunitySession {
37045
38254
  break;
37046
38255
  }
37047
38256
  this.hooks.broadcast(frame);
38257
+ const tip = this.state.secrets[this.topHash];
38258
+ this.leftSecret = tip ? {
38259
+ h: this.topHash,
38260
+ s: tip
38261
+ } : void 0;
37048
38262
  this.out("left", "You left this group");
38263
+ this.following = follow;
37049
38264
  await this.persist();
37050
38265
  this.hooks.changed();
37051
38266
  return frame;
37052
38267
  });
37053
38268
  }
38269
+ /**
38270
+ * After I left with `follow` (WISP 903 § Leaving, "A role that reaches a leave"): commits and secrets are taken still,
38271
+ * as a member whose admission lost takes them, so a hand-over that crossed my leave reaches me (`handOnAfterLeave`).
38272
+ * Once the app has forgotten the group (nothing is saved any more), the secret of the epoch I left in comes back, in
38273
+ * memory only, for the epochs derived from it. Nothing else is heard.
38274
+ */
38275
+ followAfterLeave() {
38276
+ return this.serialize(async () => {
38277
+ if (!this.following || this.state.status !== "left") return;
38278
+ const kept = this.leftSecret;
38279
+ if (!kept) return;
38280
+ this.state.secrets[kept.h] = kept.s;
38281
+ for (const [child, c] of this.known) if (c.p === kept.h) this.takeDerived(child);
38282
+ });
38283
+ }
38284
+ /**
38285
+ * After I left, a chain that names me the admin (a hand-over that crossed my leave): the role goes on to
38286
+ * `pick(<the member who handed it to me>)` with a `role` commit of mine, as an admin's leave hands it. Who handed it is
38287
+ * the signer of the newest `role` on my branch, whatever members committed on top since: an admission there would
38288
+ * otherwise steer the role to whoever let someone in. True when it went; false while the secret of my tip has not
38289
+ * come (it is tried again).
38290
+ */
38291
+ handOnAfterLeave(pick, now = Date.now()) {
38292
+ return this.serialize(async () => {
38293
+ if (!this.following || this.state.status !== "left" || this.admin !== this.myKey || !this.state.secrets[this.topHash]) return false;
38294
+ const next = pick([...this.state.chain].reverse().find((c) => c.k === "role" || c.k === "create").by);
38295
+ if (!next || next === this.myKey || !rosterHas(this.roster, next)) return false;
38296
+ await this.commit("role", { s: next }, now);
38297
+ return true;
38298
+ });
38299
+ }
38300
+ /**
38301
+ * After I left, a chain that names me the admin whose tip's secret has not come (the fresh one of a commit below went
38302
+ * missing): the engine asks my edges for it (`catchUp`) while I follow, so the role can go on. Only what I still read
38303
+ * comes back (`readsAt`): epochs before the commit that takes me out, never that one's nor any later.
38304
+ */
38305
+ get leftWaitsForSecret() {
38306
+ return this.following && this.state.status === "left" && this.admin === this.myKey && !this.state.secrets[this.topHash];
38307
+ }
37054
38308
  /** Commits the leave requests I hold whose members are still in: the engine calls this on hubs. */
37055
38309
  commitPendingLeaves(now = Date.now()) {
37056
38310
  return this.serialize(async () => {
37057
38311
  if (!this.isMember || !this.adminWork) return 0;
37058
38312
  if (this.state.pendingLeaves.length && this.hooks.adminTurn && !await this.hooks.adminTurn()) return 0;
37059
38313
  let done = 0;
38314
+ const handedBy = this.state.pendingLeaves.some((r) => r.s === this.admin) ? [...this.state.chain].reverse().find((c) => c.k === "role")?.by : void 0;
37060
38315
  for (const request of [...this.state.pendingLeaves]) {
38316
+ if ((request.s === handedBy || request.s === this.admin) && request.s !== this.myKey && rosterHas(this.roster, request.s)) continue;
37061
38317
  if (!rosterHas(this.roster, request.s) || request.s === this.myKey || request.s === this.admin) {
37062
38318
  this.state.pendingLeaves = this.state.pendingLeaves.filter((r) => r !== request);
37063
38319
  continue;
@@ -37630,6 +38886,14 @@ var CommunitySession = class CommunitySession {
37630
38886
  const key = seenKey(f.e, f.h);
37631
38887
  (have[f.s] ??= {})[key] ??= Math.max(f.n, this.state.seen[f.s]?.[key]?.high ?? -1);
37632
38888
  }
38889
+ if (to) {
38890
+ const open = this.answerOf.get(to);
38891
+ this.answerOf.set(to, {
38892
+ have: Object.fromEntries(Object.entries(have).map(([sender, byKey]) => [sender, { ...byKey }])),
38893
+ top: open?.top ?? {},
38894
+ heard: open?.heard ?? false
38895
+ });
38896
+ }
37633
38897
  const secrets = this.state.chain.slice(-COMMUNITY_LIMITS.window - 1).map((c) => communityCommitHash(c)).filter((h) => this.state.secrets[h]).map(shortHash);
37634
38898
  const loc = [];
37635
38899
  for (let back = 1; back < this.state.chain.length && loc.length < 12; back *= 2) loc.push(communityCommitHash(this.state.chain[this.state.chain.length - 1 - back]));
@@ -37655,8 +38919,12 @@ var CommunitySession = class CommunitySession {
37655
38919
  const frame = raw;
37656
38920
  if (frame.g !== this.id || frame.v !== 2) return false;
37657
38921
  const now = this.hooks.clock?.() ?? Date.now();
37658
- if ((this.answering.get(from) ?? 0) > now) this.answering.set(from, now + ANSWER_WINDOW_MS);
37659
- if (this.state.status !== "active" && !(this.state.status === "lost" && (frame.t === "group-commit" || frame.t === "group-secret" || frame.t === "group-secrets"))) return false;
38922
+ if ((this.answering.get(from) ?? 0) > now) {
38923
+ this.answering.set(from, now + ANSWER_WINDOW_MS);
38924
+ const answer = this.answerOf.get(from);
38925
+ if (answer) answer.heard = true;
38926
+ }
38927
+ if (this.state.status !== "active" && !((this.state.status === "lost" || this.following) && (frame.t === "group-commit" || frame.t === "group-secret" || frame.t === "group-secrets"))) return false;
37660
38928
  switch (frame.t) {
37661
38929
  case "group-msg": return this.receiveMessage(from, raw);
37662
38930
  case "group-commit": return this.receiveCommit(from, frame.commit);
@@ -37699,6 +38967,23 @@ var CommunitySession = class CommunitySession {
37699
38967
  this.hooks.changed();
37700
38968
  await this.replayWaiting();
37701
38969
  }
38970
+ /**
38971
+ * The member a leave frame is from, when that member signed it and is in this admission (as `receiveLeave` checks);
38972
+ * else undefined. For an app that left and follows the chain (`followAfterLeave`): it holds no requests, and a leave
38973
+ * it counts takes that member out of whom a role that reached it goes on to.
38974
+ */
38975
+ signedLeave(frame) {
38976
+ const s = frame.s, ls = frame.ls;
38977
+ if (typeof s !== "string" || !MEMBER_KEY.test(s) || typeof ls !== "string" || !SIG.test(ls) || !rosterHas(this.roster, s)) return void 0;
38978
+ const ls3 = typeof frame.ls3 === "string" && SIG.test(frame.ls3) ? frame.ls3 : void 0;
38979
+ if (!verify(fromBase64Url(ls), leaveStatement(this.id, s), publicKeyFromZ32(s))) return void 0;
38980
+ return leaveStands({
38981
+ g: this.id,
38982
+ s,
38983
+ ls,
38984
+ ls3
38985
+ }, this.ancestry(this.topHash)) ? s : void 0;
38986
+ }
37702
38987
  receiveLeave(frame) {
37703
38988
  const s = frame.s, ls = frame.ls;
37704
38989
  if (typeof s !== "string" || !MEMBER_KEY.test(s) || typeof ls !== "string" || !SIG.test(ls) || !rosterHas(this.roster, s)) return false;
@@ -37752,7 +39037,10 @@ var CommunitySession = class CommunitySession {
37752
39037
  const now = this.hooks.clock?.() ?? Date.now();
37753
39038
  const live = !waited && (raw.s === from ? (this.answering.get(from) ?? 0) <= now : mark === from && rosterHas(this.roster, from) && now - raw.ts <= COMMUNITY_LIMITS.liveMarkMs);
37754
39039
  if (live) this.cameLive.add(input);
37755
- if (this.isDuplicate(raw)) return false;
39040
+ if (this.isDuplicate(raw)) {
39041
+ this.handedInAnswer(from, raw, now);
39042
+ return false;
39043
+ }
37756
39044
  if (!verify(fromBase64Url(raw.sig), messageSigned(raw), publicKeyFromZ32(raw.s))) return false;
37757
39045
  if (!this.heardAfterOut(raw)) return false;
37758
39046
  const found = this.commitByShort(raw.e, raw.h);
@@ -37765,6 +39053,7 @@ var CommunitySession = class CommunitySession {
37765
39053
  let pace = this.messagePace.get(raw.s);
37766
39054
  if (!pace) this.messagePace.set(raw.s, pace = new MessagePace());
37767
39055
  if (!pace.take(seenKey(raw.e, raw.h), raw.n, raw.c.length, this.hooks.clock?.() ?? Date.now())) return false;
39056
+ this.handedInAnswer(from, raw, now);
37768
39057
  if (!rosterHas(roster, this.myKey)) {
37769
39058
  this.markSeen(raw);
37770
39059
  this.keep(raw);
@@ -37946,6 +39235,13 @@ var CommunitySession = class CommunitySession {
37946
39235
  ];
37947
39236
  return gap - 1;
37948
39237
  }
39238
+ /** A frame (known to be its author's) from a member whose answer to my sync is open: the highest it handed (`settleGaps`). */
39239
+ handedInAnswer(from, f, now) {
39240
+ const answer = (this.answering.get(from) ?? 0) > now ? this.answerOf.get(from) : void 0;
39241
+ if (!answer) return;
39242
+ const byKey = answer.top[f.s] ??= {}, key = seenKey(f.e, f.h);
39243
+ byKey[key] = Math.max(f.n, byKey[key] ?? -1);
39244
+ }
37949
39245
  markSeen(f) {
37950
39246
  const bySender = this.state.seen[f.s] ??= {};
37951
39247
  const entry = bySender[seenKey(f.e, f.h)] ??= {
@@ -37993,11 +39289,8 @@ var CommunitySession = class CommunitySession {
37993
39289
  }
37994
39290
  /** My sync for a member, unless I asked it a moment ago. */
37995
39291
  question(from) {
37996
- const now = this.hooks.clock?.() ?? Date.now();
37997
- if (now - (this.asked.get(from) ?? 0) < 5e3) return null;
37998
- this.asked.set(from, now);
37999
- this.answering.set(from, now + ANSWER_WINDOW_MS);
38000
- return this.syncFrame();
39292
+ if ((this.hooks.clock?.() ?? Date.now()) - (this.asked.get(from) ?? 0) < 5e3) return null;
39293
+ return this.syncFrame(from);
38001
39294
  }
38002
39295
  async replayWaiting() {
38003
39296
  await this.metaFollowsChain();
@@ -38046,6 +39339,7 @@ var CommunitySession = class CommunitySession {
38046
39339
  start = common !== void 0 ? this.mainIndex.get(common) + 1 : Math.max(0, this.state.chain.length - COMMUNITY_LIMITS.side);
38047
39340
  ask();
38048
39341
  }
39342
+ const out = this.outEpoch(from);
38049
39343
  for (let i = start; i < this.state.chain.length; i++) {
38050
39344
  const commit = this.state.chain[i], h = communityCommitHash(commit);
38051
39345
  answer.push({
@@ -38055,7 +39349,7 @@ var CommunitySession = class CommunitySession {
38055
39349
  commit
38056
39350
  });
38057
39351
  const secret = this.state.secrets[h];
38058
- if (secret && rosterHas(this.rosterAt(h) ?? [], from) && FRESH.has(commit.k)) answer.push({
39352
+ if (secret && this.readsAt(h, from, out) && FRESH.has(commit.k)) answer.push({
38059
39353
  t: "group-secret",
38060
39354
  v: 2,
38061
39355
  g: this.id,
@@ -38065,7 +39359,7 @@ var CommunitySession = class CommunitySession {
38065
39359
  });
38066
39360
  }
38067
39361
  const held = new Set(Array.isArray(frame.secrets) ? frame.secrets.filter((x) => typeof x === "string") : []);
38068
- const secrets = this.state.chain.slice(-COMMUNITY_LIMITS.window - 1).map((c) => communityCommitHash(c)).filter((h) => this.state.secrets[h] && !held.has(shortHash(h)) && rosterHas(this.rosterAt(h) ?? [], from)).map((h) => ({
39362
+ const secrets = this.state.chain.slice(-COMMUNITY_LIMITS.window - 1).map((c) => communityCommitHash(c)).filter((h) => this.state.secrets[h] && !held.has(shortHash(h)) && this.readsAt(h, from, out)).map((h) => ({
38069
39363
  h,
38070
39364
  s: sealSecret(from, fromBase64Url(this.state.secrets[h]), secretAad(this.id, h, from))
38071
39365
  }));
@@ -38090,9 +39384,9 @@ var CommunitySession = class CommunitySession {
38090
39384
  if (!this.heardAfterOut(stored)) continue;
38091
39385
  const found = this.commitByShort(stored.e, stored.h);
38092
39386
  if (!found) continue;
38093
- const reads = rosterHas(this.rosterAt(found.hash) ?? [], from), mine = stored.s === this.myKey && unheard.has(frameKey(stored));
39387
+ const reads = this.readsAt(found.hash, from, out), mine = stored.s === this.myKey && unheard.has(frameKey(stored));
38094
39388
  if (!reads && !(mine && rosterHas(this.roster, from))) continue;
38095
- if (!this.mainIndex.has(found.hash)) this.handSide(from, found.hash, handed, answer);
39389
+ if (!this.mainIndex.has(found.hash)) this.handSide(from, found.hash, handed, answer, out);
38096
39390
  if (!rosterHas(this.roster, stored.s) && !marked.has(stored.s)) {
38097
39391
  marked.add(stored.s);
38098
39392
  const left = this.leftFrame(stored.s);
@@ -38121,7 +39415,7 @@ var CommunitySession = class CommunitySession {
38121
39415
  this.answers.handOut(from, answer);
38122
39416
  }
38123
39417
  /** The commits of a branch I do not follow, from where it leaves mine, and the secrets I hold of those `to` was in, onto `answer`. */
38124
- handSide(to, tip, handed, answer) {
39418
+ handSide(to, tip, handed, answer, out = this.outEpoch(to)) {
38125
39419
  for (const h of this.pathToMain(tip) ?? []) {
38126
39420
  if (handed.has(h)) continue;
38127
39421
  handed.add(h);
@@ -38132,7 +39426,7 @@ var CommunitySession = class CommunitySession {
38132
39426
  commit: this.known.get(h)
38133
39427
  });
38134
39428
  const secret = this.state.secrets[h];
38135
- if (secret && rosterHas(this.rosterAt(h) ?? [], to)) answer.push({
39429
+ if (secret && this.readsAt(h, to, out)) answer.push({
38136
39430
  t: "group-secret",
38137
39431
  v: 2,
38138
39432
  g: this.id,
@@ -38273,23 +39567,13 @@ var CommunitySession = class CommunitySession {
38273
39567
  if (!groupMetaNewer(s, this.state.meta)) return false;
38274
39568
  const at = this.mainIndex.get(s.h);
38275
39569
  if (at === void 0) {
38276
- if (s.e >= this.epoch - COMMUNITY_LIMITS.window) {
38277
- this.pendingMeta = {
38278
- from,
38279
- frame: raw
38280
- };
38281
- this.ask(from);
38282
- }
39570
+ if (s.e >= this.epoch - COMMUNITY_LIMITS.window) this.waitMeta(from, raw, s);
38283
39571
  return false;
38284
39572
  }
38285
39573
  if (at !== s.e || rosterAdmin(this.rosterAt(s.h) ?? []) !== s.by || this.admin !== s.by || !verifyGroupMetaSignature(s)) return false;
38286
39574
  const secret = this.state.secrets[frame.k], sealedUnder = this.known.get(frame.k);
38287
39575
  if (!secret || !sealedUnder) {
38288
- this.pendingMeta = {
38289
- from,
38290
- frame: raw
38291
- };
38292
- this.ask(from);
39576
+ this.waitMeta(from, raw, s);
38293
39577
  return false;
38294
39578
  }
38295
39579
  const opened = openGroupMeta(frame, epochKeys(fromBase64Url(secret), this.id, sealedUnder.e).message);
@@ -38304,6 +39588,21 @@ var CommunitySession = class CommunitySession {
38304
39588
  return true;
38305
39589
  }
38306
39590
  /**
39591
+ * A statement that waits for the chain: only one its signer signed, so an altered copy cannot push out the one
39592
+ * waiting. The admin I know has a place of their own, which another member's statement cannot take, and in each
39593
+ * place only a later statement takes the one waiting.
39594
+ */
39595
+ waitMeta(from, raw, s) {
39596
+ if (!verifyGroupMetaSignature(s)) return;
39597
+ const place = s.by === this.admin ? "admin" : "other", waiting = this.pendingMeta[place];
39598
+ if (!waiting || groupMetaNewer(s, waiting.s)) this.pendingMeta[place] = {
39599
+ from,
39600
+ frame: raw,
39601
+ s
39602
+ };
39603
+ this.ask(from);
39604
+ }
39605
+ /**
38307
39606
  * Who made the change a statement brings me (`at`: its commit's place on my main branch): its signer, when they were
38308
39607
  * the admin all along since the statement I held (or, with none, since I got in). A new admin signs again what the
38309
39608
  * last one set (`metaFollowsChain`): to a member that missed that, it is no change of theirs it can tell apart. With
@@ -38328,9 +39627,9 @@ var CommunitySession = class CommunitySession {
38328
39627
  * went with a branch that lost a fork, the name and picture signed again as mine under the main branch.
38329
39628
  */
38330
39629
  async metaFollowsChain() {
38331
- const pending = this.pendingMeta;
38332
- this.pendingMeta = void 0;
38333
- if (pending && await this.receiveMeta(pending.from, pending.frame)) this.hooks.relay?.(pending.frame);
39630
+ const { admin, other } = this.pendingMeta;
39631
+ this.pendingMeta = {};
39632
+ for (const pending of [admin, other]) if (pending && await this.receiveMeta(pending.from, pending.frame)) this.hooks.relay?.(pending.frame);
38334
39633
  const meta = this.state.meta;
38335
39634
  if (this.isAdmin && meta && (meta.by !== this.myKey || !this.mainIndex.has(meta.h))) await this.publishMeta(meta.body, meta.ts, true);
38336
39635
  }
@@ -39002,6 +40301,6 @@ function readX401SdJwtVc(text) {
39002
40301
  };
39003
40302
  }
39004
40303
  //#endregion
39005
- export { SSHSIG_NAMESPACE as $, ReactionWindow as $a, openRequest as $c, HOLD_DATED_BACK_MS as $i, deviceEchoFrame as $l, engineError as $n, PRESENCE_WINDOW as $o, PIN_LIMITS as $r, handoffReleaseFrame as $s, ONCHAIN_PROVIDER as $t, sanitizeDisplayText as $u, knockIdentity as A, VOICE_LIMITS as Aa, enrollProofFrame as Ac, IDENTITY_REVOCATION_LABEL as Ai, signAppObject as Al, ENDPOINT as An, claimedTime as Ao, lobbyKeys as Ar, HANDOFF_HELLO as As, didJwsAlg as At, currentRelays as Au, GROUP_REACTED_FRAME as B, EDIT_RATE_WINDOW_MS as Ba, takeRequest as Bc, newIdentityBinding as Bi, createDeviceInvite as Bl, NO_PICTURE_METADATA as Bn, rosterAdmin as Bo, shouldBeHub as Br, handoffAttemptFailed as Bs, parseDidSignaturePaste as Bt, RELAY_PAYLOAD_MAX_BYTES as Bu, communityHasFrame as C, peekDhtMailbox as Ca, ENROLL_PROOF as Cc, UPGRADE_CAPABILITY as Ci, isAppHash as Cl, pubkyProofFile as Cn, cardLine as Co, pickMeshHubs as Cr, HTTP_SERVICE_PROTO as Cs, DID_DOCUMENT_MAX_BYTES as Ct, turnVerifierMark as Cu, decodeGroupEntryLink as D, sanitizeFileName as Da, enrollDoneFrame as Dc, dialDescriptors as Di, readAppRevocationShape as Dl, requestLnurlInvoice as Dn, statusCardBytes as Do, doorHubs as Dr, HANDOFF_CANCEL as Ds, checkDidJws as Dt, RelayTransport as Du, KNOCK_TTL_MS as E, formatFileSize as Ea, enrollDigits as Ec, capsDescriptors as Ei, readAppRevocation as El, pubkyHomeserverOf as En, sameButtonText as Eo, beaconRecords as Er, HANDOFF_ACK as Es, DidError as Et, HEDGE_MS as Eu, GroupWakeLimiter as F, parseVoiceMeta as Fa, endedRequests as Fc, emptyIdentityLedger as Fi, canonicalJsonBytes as Fl, parseCashuRequestPayload as Fn, GROUP_MEMBER_CAP as Fo, pickHubs as Fr, HANDOFF_TIMINGS as Fs, didWebFileUrl as Ft, DiscoveryBudgetError as Fu, GROUP_EDIT_FRAME as G, LINK_TRAILING as Ga, contactAskerHolds as Gc, emptyProofLedger as Gi, decodeInviteCode as Gl, GhostLink as Gn, RatchetBox as Go, transferEnded as Gr, handoffContextProof as Gs, didDhtDocument as Gt, createIdentity as Gu, GroupSession as H, REMOVED_TEXT as Ha, ContactRequestError as Hc, revokesIdentity as Hi, readDeviceInvite as Hl, isStrippedPicture as Hn, verifyCommitSignature as Ho, FILE_LIMITS as Hr, handoffBusyFrame as Hs, staticDidDocument as Ht, newerPacket as Hu, groupWakeFrame as I, voiceDownloadName as Ia, inboxRecord as Ic, identityRefusal as Ii, readCanonicalJson as Il, parseFedimintRequestPayload as In, MAX_GROUP_CHAIN as Io, rankHubs as Ir, HANDOFF_VERIFIED as Is, didWebHost as It, budgetRetryMs as Iu, meshMessageRef as J, forwardedAgain as Ja, knockSlotOf as Jc, automaticTransport as Ji, inviteOwnership as Jl, PAIRED_FRAME_TOO_LARGE as Jn, DirectPathWatch as Jo, TYPING_REFRESH_MS as Jr, handoffEphemeral as Js, encodeDidDhtPacket as Jt, publicKeyFromZ32 as Ju, GROUP_EDIT_TEXT_BYTES as K, linkStop as Ka, contactDay as Kc, validExternalKey as Ki, encodeInviteCode as Kl, INVITE_TAKEN as Kn, emptyRatchetState as Ko, transferStalled as Kr, handoffDataFrame as Ks, didDhtFromPublicKey as Kt, identityFromSeed as Ku, groupWakes as L, voiceLevel as La, newInbox as Lc, identityRevocationValue as Li, createContactLink as Ll, NO_VIDEO_METADATA as Ln, MEMBER_KEY as Lo, readBeacon as Lr, NO_ATTEMPTS as Ls, normalizeDid as Lt, isDiscoveryBudgetError as Lu, mergeKnocks as M, baseMime as Ma, readEnrollHello as Mc, IdentityExchange as Mi, parseImageMeta as Ml, fedimintRequestPayload as Mn, receivedTimestamp as Mo, mergeBeacon as Mr, HANDOFF_PAKE as Ms, didWebDocumentUrl as Mt, relayUrlProblem as Mu, readKnocks as N, downsamplePeaks as Na, verifyEnrollProof as Nc, boundIdentityDisplay as Ni, readImageMeta as Nl, findEndpoint as Nn, shownTime as No, mergeLobby as Nr, HANDOFF_PIECE_BYTES as Ns, didWebFile as Nt, setLinkTraceSink as Nu, encodeGroupEntryLink as O, sanitizeMime as Oa, enrollGrantFrame as Oc, IDENTITY_MAX_EVIDENCE as Oi, readAppRevocations as Ol, resolveLightningDestination as On, statusCardText as Oo, freshHubs as Or, HANDOFF_DONE as Os, checkDidSignature as Ot, RelaysFailedError as Ou, GROUP_WAKE_FRAME as P, fileMessageText as Pa, clearMissed as Pc, boundVerifiedIdentity as Pi, canonicalJson as Pl, isFederationId as Pn, GROUP_ADMIN_OFF_ERROR as Po, newerHead as Pr, HANDOFF_REQUEST as Ps, didWebFileNames as Pt, traceLink as Pu, SSHSIG_MAX_ARMOR as Q, REACTION_LIMITS as Qa, mergeContactKnocks as Qc, HOLD_CAPABILITY as Qi, HANDOFF_CAPABILITY as Ql, EngineError as Qn, EXPECT_PEER_MS as Qo, GROUP_PIN_FRAME as Qr, handoffPakeFrame as Qs, EVM_TEST_CHAINS as Qt, hasVisible as Qu, parseGroupWakeFrame as R, parseVideoMeta as Ra, planKnocks as Rc, identityStatement as Ri, encodeContactLink as Rl, videoMetadataPatches as Rn, commitHash as Ro, readBeaconHead as Rr, filePartName as Rs, parseDid as Rt, withRequestOptions as Ru, GROUP_READ_NOTE_COMMUNITY as S, DHT_MESSAGE_TTL as Sa, ENROLL_HELLO as Sc, STATUS_CARD_CAPABILITY as Si, checkAppRevokeStatement as Sl, pubkyProofCapability as Sn, buttonLabelClash as So, meshHubs as Sr, emptyLinkRecords as Ss, verifyAtprotoRecordProof as St, turnStatedVerifier as Su, encodeCommunityLink as T, dhtFileId as Ta, enrollCancelReason as Tc, DHT_TEXT_CAPABILITY as Ti, isAppRef as Tl, homeserverWebEndpoint as Tn, checkStatusCard as To, beaconKeys as Tr, serviceIdFromName as Ts, DID_JWS_MAX_LENGTH as Tt, HEDGE_MISSING_MS as Tu, frameBytes as U, RateWindow as Ua, REQUEST_LIFETIME_MS as Uc, lastSharedWithMe as Ui, OwnInviteError as Ul, stripPictureMetadata as Un, edgeParams as Uo, FileUplink as Ur, handoffCancelFrame as Us, strictBase64Url as Ut, openRelayPayload as Uu, GROUP_READ_NOTE as V, MAX_REMOVAL_NUMBER as Va, turnOff as Vc, receivedIdentityStatus as Vi, deviceInviteJoinerParams as Vl, PICTURE_METADATA_LIMITS as Vn, rosterHas as Vo, ChatFiles as Vr, handoffAttemptSucceeded as Vs, signingKeys as Vt, createRelayPayload as Vu, COMMUNITY_EDIT_FRAME as W, dhtEditId as Wa, contactAskerFrame as Wc, PeerProofs as Wi, createChatInvite as Wl, withoutPictureMetadata as Wn, RATCHET_CAPABILITY as Wo, sentWhole as Wr, handoffContext as Ws, DidDhtError as Wt, parseRelayPayload as Wu, mentionsMember as X, COMMUNITY_REACTION_FRAME as Xa, linkRecords as Xc, irohDescriptor as Xi, DEVICES_CAPABILITY as Xl, pairedMessageFits as Xn, DAEMON_WATCH_PEER_IDLE_MS as Xo, sanitizeTypingStatus as Xr, handoffManifestFrames as Xs, signDidDhtPacket as Xt, MAX_AVATAR_LENGTH as Xu, parseCommunityEdit as Y, readForwarded as Ya, knockSlotRecords as Yc, dialableIrohRelay as Yi, ownInviteRefusal as Yl, pairedEditFits as Yn, AWAITING_PEER_MS as Yo, TypingSender as Yr, handoffHelloFrame as Ys, resolveDidDht as Yt, verify as Yu, groupName as Z, GROUP_REACTION_FRAME as Za, makeStampPaced as Zc, irohRelayUrl as Zi, ENROLL_CAPABILITY as Zl, pairedMessageFrame as Zn, DHT_POLL_INTERVALS as Zo, typingActivity as Zr, handoffOfferFrame as Zs, ETHEREUM_USDT as Zt, sanitizeAvatar as Zu, groupTypingEpoch as _, recordsName as _a, setUpdateFrame as _c, chatAppId as _i, APP_PREFIXES as _l, PUBKY_PROOF_MAX_BYTES as _n, RUN_RESULTS as _o, SIGNAL_REPLY_MS as _r, callSignalHeardAt as _s, isAtprotoDid as _t, signTurnPacket as _u, appRevocationFor as a, readManifest as aa, readHandoffCancel as ac, toBase64Url as ad, WAKE_CALL_INTERVAL_MS as ai, APP_BUNDLE_MAGIC as al, WALLET_NETWORKS as an, validReactionNumber as ao, GROUP_WANT_NO_FRAME as ar, parseLocalTarget as as, verifySshSignature as at, seedSigner as au, COMMUNITY_LIMITS as b, ACTIVE_DHT_POLL_MS as ba, ENROLL_DONE as bc, BUTTONS_CAPABILITY as bi, appRef as bl, newPubkyProofFolder as bn, appCardId as bo, MESH_HUBS as br, parseCallSignal as bs, shortAtprotoDid as bt, turnKeys as bu, checkAppBeforeRun as c, dnsProofName as ca, readHandoffHello as cc, utf8Encode as cd, newWakeToken as ci, appDigest as cl, assertWholeSats as cn, readReply as co, isGroupMessageId as cr, decodeControl as cs, decodeAnyBitcoinAddress as ct, TURN_RAISE_READ_TIMEOUT_MS as cu, checkAppStoreIndex as d, encodeDnsQuery as da, readHandoffVerified as dc, wakeRequest as di, checkAppManifest as dl, walletNetworkOf as dn, BUTTON_STYLES as do, readGroupWant as dr, CALL_SIGNAL_MAX_AGE_MS as ds, ATPROTO_PROOF_COLLECTION as dt, turnPutSummary as du, HOLD_LIMITS as ea, handoffRetryAfter as ec, stripHidden as ed, mayPin as ei, readKnockSlot as el, PaymentPreflightError as en, nextReactionNumber as eo, engineText as er, RELAY_POLL_INTERVALS as es, SshSigError as et, deviceEchoNonce as eu, readAppStore as f, isPublicAddress as fa, sealHandoffPiece as fc, checkPushEndpoint as fi, isAppUrl as fl, SPARK_NETWORKS as fn, CRON_LINE as fo, readGroupWantNo as fr, QUICK_REDIAL_MS as fs, ATPROTO_PROOF_SCOPE as ft, TURN_LAST_SEQUENCE as fu, GroupTypingBoard as g, recordsFromWellKnown as ga, setAckFrame as gc, APP_DATA_MAX_BYTES as gi, sha256Paced as gl, isBitcoinAddress as gn, ROUTINE_STATES as go, SIGNAL_HOLD_MS as gr, callRtcConfig as gs, checkAtprotoProofRecord as gt, readTurnPacket as gu, GROUP_TYPING_FRAME as h, recordsFromTxt as ha, readSetUpdate as hc, isServeId as hi, readAppBundleAsync as hl, sparkInvoiceDetails as hn, PR_STATES as ho, SIGNAL_FRESH_MS as hr, buildSdpFromSignal as hs, atprotoProofRkey as ht, nextTurnPosition as hu, addedAppPermissions as i, newMailbox as ia, readHandoffAck as ic, randomBytes as id, readPin as ii, APP_BUNDLE_LIMITS as il, USDT_PUBLIC_RPC as in, readReaction as io, GROUP_WANT_FRAME as ir, formatLocalTarget as is, sshSignCommand as it, newDeviceSetSecret as iu, knockRecords as j, VOICE_METER as ja, readEnrollGrant as jc, IdentityCheckUnavailable as ji, signAppRevocation as jl, cashuRequestPayload as jn, heardTime as jo, lobbyRecords as jr, HANDOFF_OFFER as js, didSignedMessages as jt, normalizeRelayUrl as ju, entryParams as k, PLAYABLE_AUDIO as ka, enrollHelloFrame as kc, IDENTITY_MAX_VALIDITY as ki, setAppSignatureFastPath as kl, decodeBolt11 as kn, arrivalKey as ko, hubRank as kr, HANDOFF_HAVE as ks, didGhostlyServiceEntry as kt, SLOW_MS as ku, planAppUpdate as l, domainTxtRecord as la, readHandoffPake as lc, parseWakeFrame as li, appViewOf as ll, formatPaymentAmount as ln, replySnippet as lo, readGroupFileMeta as lr, encodeControl as ls, ATPROTO_DECLARED_SCOPE as lt, TURN_SETTLE_MS as lu, signAppStore as m, normalizeDomain as ma, SET_UPDATE as mc, APP_RANGE_LIMITS as mi, readAppBundle as ml, sparkAddressKind as mn, PR_CHECKS as mo, GROUP_SIGNAL_FRAME as mr, answersOffer as ms, atprotoProofRecord as mt, firstDeviceSetSecret as mu, readX401SdJwtVc as n, HoldRefusedError as na, handoffVersions as nc, fromBase64Url as nd, pinIsNewer as ni, requestRecords as nl, SEPOLIA_TEST_USDT_FAUCET as nn, reactionEmoji as no, GROUP_FILE_LIMITS as nr, presenceSeenAt as ns, parseSshSignature as nt, deviceLinkPairing as nu, appStoreDecision as o, DOMAIN_FILE_MAX_BYTES as oa, readHandoffDone as oc, toZ32 as od, WakeLimiter as oi, APP_ICON_PATH as ol, arkAddressPrefix as on, wireReaction as oo, fetchesByItself as or, webLocalFetch as os, verifyBitcoinMessage as ot, webCryptoSigner as ou, readAppStoreSteps as p, nip05RootKey as pa, SET_ACK as pc, vapidKeysMatch as pi, pacer as pl, SPARK_PROVIDER as pn, ITEM_STATES as po, CarriedTransport as pr, RTC_CONFIG as ps, atprotoDidMethod as pt, TURN_MAX as pu, carryMentions as q, parseLinkPreview as qa, knockSlotIdentity as qc, TRANSPORTS as qi, inviteLink as ql, LIVENESS_PING_MS as qn, ratchetSessionOf as qo, TYPING_KINDS as qr, handoffDigest as qs, encodeDidDhtDeactivated as qt, identityFromSeedB64 as qu, sameX401HolderJwk as r, isHoldUrl as ra, newHandoffId as rc, isZ32Key as rd, pinNumberHolds as ri, seenEntry as rl, TEST_USDT_FAUCET_AMOUNT as rn, reactionIsNewer as ro, GROUP_HAVE_FRAME as rr, GhostlyHttpError as rs, sameSshKey as rt, devicePingFrame as ru, appUpdateDecision as s, decodeDnsResponse as sa, readHandoffHave as sc, utf8Decode as sd, deviceWakeRequest as si, APP_PERMISSIONS as sl, assertTokenUnits as sn, pairedReplyAuthor as so, groupFileFallback as sr, LIMITS as ss, BitcoinAddressError as st, TURN_PUT_WINDOW_MS as su, newX401HolderKey as t, HoldKeys as ta, handoffStreamKey as tc, bytesEqual as td, nextPinNumber as ti, readLinkRecord as tl, SEPOLIA_TEST_USDT as tn, queueReaction as to, parseEngineError as tr, WATCH_PEER_MS as ts, parseSshPublicKey as tt, deviceKeyZ32 as tu, APP_STORE_LIMITS as u, domainWellKnownFile as ua, readHandoffTurnFrame as uc, relayRequest as ui, assembleAppBundle as ul, validatePaymentTarget as un, BUTTON_ID as uo, readGroupHave as ur, BURST_RING_MS as us, ATPROTO_FULL_SCOPE as ut, classifyTurnRead as uu, openGroupTyping as v, txtValue as va, signTombstone as vc, isAppVersion as vi, APP_STATEMENT_LIMITS as vl, isPubkyKey as vn, STATUS_CARD_LIMITS as vo, groupSignalFrame as vr, contactRtcConfig as vs, normalizeAtprotoHandle as vt, signTurnRelease as vu, decodeCommunityLink as w, DHT_FILE_CAPABILITY as wa, enrollCancelFrame as wc, CapsExchange as wi, isAppKey as wl, pubkyProofPath as wn, cardUrl as wo, COMMUNITY_TOPOLOGY as wr, LEGACY_SERVICES as ws, DID_FILE_MAX_BYTES as wt, DEFAULT_RELAYS as wu, CommunitySession as x, DHT_FILE_TOO_LARGE as xa, ENROLL_GRANT as xc, EDIT_CAPABILITY as xi, appRefPublisher as xl, normalizePubkyKey as xn, appCardUrl as xo, mayBeHub as xr, signalHasVideo as xs, AtprotoProofError as xt, turnName as xu, sealGroupTyping as y, wellKnownUrl as ya, verifySetUpdate as yc, APPS_CAPABILITY as yi, appFingerprint as yl, isPubkyProofFolder as yn, TASK_STATUSES as yo, readGroupSignal as yr, extractParamsFromSdp as ys, parseAtprotoDidDocument as yt, turnInstance as yu, GROUP_LIMITS as z, EDIT_BUFFER_MS as za, settleRequest as zc, isIdentityBinding as zi, readContactLink as zl, withoutVideoMetadata as zn, parseGroupCommit as zo, readLobby as zr, handoffAttemptAllowed as zs, parseDidDocument as zt, PacketTooLargeError as zu };
40304
+ export { SSHSIG_NAMESPACE as $, REMOVED_TEXT as $a, turnOff as $c, revokesIdentity as $i, createDeviceInvite as $l, pairedMessageFits as $n, rosterHas as $o, personStatus as $r, handoffAttemptSucceeded as $s, ONCHAIN_PROVIDER as $t, RELAY_PAYLOAD_MAX_BYTES as $u, knockIdentity as A, wellKnownUrl as Aa, signTombstone as Ac, APPS_CAPABILITY as Ai, APP_STATEMENT_LIMITS as Al, ENDPOINT as An, TASK_STATUSES as Ao, doorHubs as Ar, contactRtcConfig as As, didJwsAlg as At, signTurnPacket as Au, GROUP_REACTED_FRAME as B, PLAYABLE_AUDIO as Ba, enrollGrantFrame as Bc, IDENTITY_MAX_VALIDITY as Bi, readAppRevocationShape as Bl, NO_VIDEO_METADATA as Bn, MESSAGE_CLOCK_SKEW_MS as Bo, readBeacon as Br, HANDOFF_DONE as Bs, parseDidSignaturePaste as Bt, RelayTransport as Bu, communityHasFrame as C, isPublicAddress as Ca, readHandoffVerified as Cc, checkPushEndpoint as Ci, checkAppManifest as Cl, pubkyProofFile as Cn, CRON_LINE as Co, MESH_HUBS as Cr, CALL_SIGNAL_MAX_AGE_MS as Cs, DID_DOCUMENT_MAX_BYTES as Ct, classifyTurnRead as Cu, decodeGroupEntryLink as D, recordsFromWellKnown as Da, readSetUpdate as Dc, APP_DATA_MAX_BYTES as Di, readAppBundleAsync as Dl, requestLnurlInvoice as Dn, ROUTINE_STATES as Do, COMMUNITY_TOPOLOGY as Dr, buildSdpFromSignal as Ds, checkDidJws as Dt, firstDeviceSetSecret as Du, KNOCK_TTL_MS as E, recordsFromTxt as Ea, SET_UPDATE as Ec, isServeId as Ei, readAppBundle as El, pubkyHomeserverOf as En, PR_STATES as Eo, pickMeshHubs as Er, answersOffer as Es, DidError as Et, TURN_MAX as Eu, GroupWakeLimiter as F, DHT_FILE_CAPABILITY as Fa, ENROLL_PROOF as Fc, CapsExchange as Fi, isAppHash as Fl, parseCashuRequestPayload as Fn, cardUrl as Fo, mergeBeacon as Fr, HTTP_SERVICE_PROTO as Fs, didWebFileUrl as Ft, turnStatedVerifier as Fu, GROUP_EDIT_FRAME as G, fileMessageText as Ga, verifyEnrollProof as Gc, boundVerifiedIdentity as Gi, parseImageMeta as Gl, isStrippedPicture as Gn, shownTime as Go, FILE_LIMITS as Gr, HANDOFF_PIECE_BYTES as Gs, didDhtDocument as Gt, relayUrlProblem as Gu, GroupSession as H, VOICE_METER as Ha, enrollProofFrame as Hc, IdentityCheckUnavailable as Hi, setAppSignatureFastPath as Hl, withoutVideoMetadata as Hn, claimedTime as Ho, readLobby as Hr, HANDOFF_HELLO as Hs, staticDidDocument as Ht, SLOW_MS as Hu, groupWakeFrame as I, dhtFileId as Ia, enrollCancelFrame as Ic, DHT_TEXT_CAPABILITY as Ii, isAppKey as Il, parseFedimintRequestPayload as In, checkStatusCard as Io, mergeLobby as Ir, LEGACY_SERVICES as Is, didWebHost as It, turnVerifierMark as Iu, meshMessageRef as J, voiceLevel as Ja, inboxRecord as Jc, identityRevocationValue as Ji, canonicalJsonBytes as Jl, GhostLink as Jn, MAX_GROUP_CHAIN as Jo, transferEnded as Jr, HANDOFF_VERIFIED as Js, encodeDidDhtPacket as Jt, DiscoveryBudgetError as Ju, GROUP_EDIT_TEXT_BYTES as K, parseVoiceMeta as Ka, clearMissed as Kc, emptyIdentityLedger as Ki, readImageMeta as Kl, stripPictureMetadata as Kn, GROUP_ADMIN_OFF_ERROR as Ko, FileUplink as Kr, HANDOFF_REQUEST as Ks, didDhtFromPublicKey as Kt, setLinkTraceSink as Ku, groupWakes as L, formatFileSize as La, enrollCancelReason as Lc, capsDescriptors as Li, isAppLine as Ll, NO_AUDIO_METADATA as Ln, sameButtonText as Lo, newerHead as Lr, serviceIdFromName as Ls, normalizeDid as Lt, DEFAULT_RELAYS as Lu, mergeKnocks as M, DHT_FILE_TOO_LARGE as Ma, ENROLL_DONE as Mc, EDIT_CAPABILITY as Mi, appRef as Ml, fedimintRequestPayload as Mn, appCardUrl as Mo, hubRank as Mr, parseCallSignal as Ms, didWebDocumentUrl as Mt, turnInstance as Mu, readKnocks as N, DHT_MESSAGE_TTL as Na, ENROLL_GRANT as Nc, STATUS_CARD_CAPABILITY as Ni, appRefPublisher as Nl, findEndpoint as Nn, buttonLabelClash as No, lobbyKeys as Nr, signalHasVideo as Ns, didWebFile as Nt, turnKeys as Nu, encodeGroupEntryLink as O, recordsName as Oa, setAckFrame as Oc, chatAppId as Oi, sha256Paced as Ol, resolveLightningDestination as On, RUN_RESULTS as Oo, beaconKeys as Or, callRtcConfig as Os, checkDidSignature as Ot, nextTurnPosition as Ou, GROUP_WAKE_FRAME as P, peekDhtMailbox as Pa, ENROLL_HELLO as Pc, UPGRADE_CAPABILITY as Pi, checkAppRevokeStatement as Pl, isFederationId as Pn, cardLine as Po, lobbyRecords as Pr, emptyLinkRecords as Ps, didWebFileNames as Pt, turnName as Pu, SSHSIG_MAX_ARMOR as Q, MAX_REMOVAL_NUMBER as Qa, takeRequest as Qc, receivedIdentityStatus as Qi, readContactLink as Ql, pairedEditFits as Qn, rosterAdmin as Qo, liveStatus as Qr, handoffAttemptFailed as Qs, EVM_TEST_CHAINS as Qt, PacketTooLargeError as Qu, parseGroupWakeFrame as R, sanitizeFileName as Ra, enrollDigits as Rc, dialDescriptors as Ri, isAppRef as Rl, audioMetadataPatches as Rn, statusCardBytes as Ro, pickHubs as Rr, HANDOFF_ACK as Rs, parseDid as Rt, HEDGE_MISSING_MS as Ru, GROUP_READ_NOTE_COMMUNITY as S, encodeDnsQuery as Sa, readHandoffTurnFrame as Sc, wakeRequest as Si, assembleAppBundle as Sl, pubkyProofCapability as Sn, BUTTON_STYLES as So, readGroupSignal as Sr, BURST_RING_MS as Ss, verifyAtprotoRecordProof as St, TURN_SETTLE_MS as Su, encodeCommunityLink as T, normalizeDomain as Ta, SET_ACK as Tc, APP_RANGE_LIMITS as Ti, pacer as Tl, homeserverWebEndpoint as Tn, PR_CHECKS as To, meshHubs as Tr, RTC_CONFIG as Ts, DID_JWS_MAX_LENGTH as Tt, TURN_LAST_SEQUENCE as Tu, frameBytes as U, baseMime as Ua, readEnrollGrant as Uc, IdentityExchange as Ui, signAppObject as Ul, NO_PICTURE_METADATA as Un, heardTime as Uo, shouldBeHub as Ur, HANDOFF_OFFER as Us, strictBase64Url as Ut, currentRelays as Uu, GROUP_READ_NOTE as V, VOICE_LIMITS as Va, enrollHelloFrame as Vc, IDENTITY_REVOCATION_LABEL as Vi, readAppRevocations as Vl, videoMetadataPatches as Vn, arrivalKey as Vo, readBeaconHead as Vr, HANDOFF_HAVE as Vs, signingKeys as Vt, RelaysFailedError as Vu, COMMUNITY_EDIT_FRAME as W, downsamplePeaks as Wa, readEnrollHello as Wc, boundIdentityDisplay as Wi, signAppRevocation as Wl, PICTURE_METADATA_LIMITS as Wn, receivedTimestamp as Wo, ChatFiles as Wr, HANDOFF_PAKE as Ws, DidDhtError as Wt, normalizeRelayUrl as Wu, mentionsMember as X, EDIT_BUFFER_MS as Xa, planKnocks as Xc, isIdentityBinding as Xi, createContactLink as Xl, LIVENESS_PING_MS as Xn, commitHash as Xo, STATUS_AVAILABILITIES as Xr, filePartName as Xs, signDidDhtPacket as Xt, isDiscoveryBudgetError as Xu, parseCommunityEdit as Y, parseVideoMeta as Ya, newInbox as Yc, identityStatement as Yi, readCanonicalJson as Yl, INVITE_TAKEN as Yn, MEMBER_KEY as Yo, transferStalled as Yr, NO_ATTEMPTS as Ys, resolveDidDht as Yt, budgetRetryMs as Yu, groupName as Z, EDIT_RATE_WINDOW_MS as Za, settleRequest as Zc, newIdentityBinding as Zi, encodeContactLink as Zl, PAIRED_FRAME_TOO_LARGE as Zn, parseGroupCommit as Zo, STATUS_IDLE_AFTER_MS as Zr, handoffAttemptAllowed as Zs, ETHEREUM_USDT as Zt, withRequestOptions as Zu, groupTypingEpoch as _, DOMAIN_FILE_MAX_BYTES as _a, readHandoffCancel as _c, randomBytes as _d, WakeLimiter as _i, APP_BUNDLE_MAGIC as _l, PUBKY_PROOF_MAX_BYTES as _n, wireReaction as _o, GROUP_SIGNAL_FRAME as _r, parseLocalTarget as _s, isAtprotoDid as _t, newDeviceSetSecret as _u, appRevocationFor as a, automaticTransport as aa, handoffDigest as ac, identityFromSeed as ad, typingActivity as ai, knockSlotIdentity as al, WALLET_NETWORKS as an, forwardedAgain as ao, GROUP_FILE_LIMITS as ar, ratchetSessionOf as as, verifySshSignature as at, encodeInviteCode as au, COMMUNITY_LIMITS as b, domainTxtRecord as ba, readHandoffHello as bc, utf8Decode as bd, parseWakeFrame as bi, appDigest as bl, newPubkyProofFolder as bn, replySnippet as bo, SIGNAL_REPLY_MS as br, decodeControl as bs, shortAtprotoDid as bt, TURN_PUT_WINDOW_MS as bu, checkAppBeforeRun as c, irohRelayUrl as ca, handoffManifestFrames as cc, verify as cd, mayPin as ci, linkRecords as cl, assertWholeSats as cn, GROUP_REACTION_FRAME as co, GROUP_WANT_NO_FRAME as cr, DAEMON_WATCH_PEER_IDLE_MS as cs, decodeAnyBitcoinAddress as ct, ownInviteRefusal as cu, checkAppStoreIndex as d, HOLD_LIMITS as da, handoffReleaseFrame as dc, hasVisible as dd, pinNumberHolds as di, openRequest as dl, walletNetworkOf as dn, nextReactionNumber as do, isGroupMessageId as dr, PRESENCE_WINDOW as ds, ATPROTO_PROOF_COLLECTION as dt, HANDOFF_CAPABILITY as du, lastSharedWithMe as ea, handoffBusyFrame as ec, createRelayPayload as ed, sanitizeStatusText as ei, ContactRequestError as el, PaymentPreflightError as en, RateWindow as eo, pairedMessageFrame as er, verifyCommitSignature as es, SshSigError as et, deviceInviteJoinerParams as eu, readAppStore as f, HoldKeys as fa, handoffRetryAfter as fc, sanitizeDisplayText as fd, readPin as fi, readKnockSlot as fl, SPARK_NETWORKS as fn, queueReaction as fo, readGroupFileMeta as fr, RELAY_POLL_INTERVALS as fs, ATPROTO_PROOF_SCOPE as ft, deviceEchoFrame as fu, GroupTypingBoard as g, readManifest as ga, readHandoffAck as gc, isZ32Key as gd, WAKE_ONLINE_INTERVAL_MS as gi, APP_BUNDLE_LIMITS as gl, isBitcoinAddress as gn, validReactionNumber as go, CarriedTransport as gr, formatLocalTarget as gs, checkAtprotoProofRecord as gt, devicePingFrame as gu, GROUP_TYPING_FRAME as h, newMailbox as ha, newHandoffId as hc, fromBase64Url as hd, WAKE_ONLINE_DELAY_MS as hi, seenEntry as hl, sparkInvoiceDetails as hn, readReaction as ho, readGroupWantNo as hr, GhostlyHttpError as hs, atprotoProofRkey as ht, deviceLinkPairing as hu, addedAppPermissions as i, TRANSPORTS as ia, handoffDataFrame as ic, createIdentity as id, sanitizeTypingStatus as ii, contactDay as il, USDT_PUBLIC_RPC as in, parseLinkPreview as io, parseEngineError as ir, emptyRatchetState as is, sshSignCommand as it, decodeInviteCode as iu, knockRecords as j, ACTIVE_DHT_POLL_MS as ja, verifySetUpdate as jc, BUTTONS_CAPABILITY as ji, appFingerprint as jl, cashuRequestPayload as jn, appCardId as jo, freshHubs as jr, extractParamsFromSdp as js, didSignedMessages as jt, signTurnRelease as ju, entryParams as k, txtValue as ka, setUpdateFrame as kc, isAppVersion as ki, APP_PREFIXES as kl, decodeBolt11 as kn, STATUS_CARD_LIMITS as ko, beaconRecords as kr, callSignalHeardAt as ks, didGhostlyServiceEntry as kt, readTurnPacket as ku, planAppUpdate as l, HOLD_CAPABILITY as la, handoffOfferFrame as lc, MAX_AVATAR_LENGTH as ld, nextPinNumber as li, makeStampPaced as ll, formatPaymentAmount as ln, REACTION_LIMITS as lo, fetchesByItself as lr, DHT_POLL_INTERVALS as ls, ATPROTO_DECLARED_SCOPE as lt, DEVICES_CAPABILITY as lu, signAppStore as m, isHoldUrl as ma, handoffVersions as mc, bytesEqual as md, WAKE_ONLINE_BATCH_MS as mi, requestRecords as ml, sparkAddressKind as mn, reactionIsNewer as mo, readGroupWant as mr, presenceSeenAt as ms, atprotoProofRecord as mt, deviceKeyZ32 as mu, readX401SdJwtVc as n, emptyProofLedger as na, handoffContext as nc, openRelayPayload as nd, TYPING_REFRESH_MS as ni, contactAskerFrame as nl, SEPOLIA_TEST_USDT_FAUCET as nn, LINK_TRAILING as no, engineError as nr, RATCHET_CAPABILITY as ns, parseSshSignature as nt, OwnInviteError as nu, appStoreDecision as o, dialableIrohRelay as oa, handoffEphemeral as oc, identityFromSeedB64 as od, GROUP_PIN_FRAME as oi, knockSlotOf as ol, arkAddressPrefix as on, readForwarded as oo, GROUP_HAVE_FRAME as or, DirectPathWatch as os, verifyBitcoinMessage as ot, inviteLink as ou, readAppStoreSteps as p, HoldRefusedError as pa, handoffStreamKey as pc, stripHidden as pd, WAKE_CALL_INTERVAL_MS as pi, readLinkRecord as pl, SPARK_PROVIDER as pn, reactionEmoji as po, readGroupHave as pr, WATCH_PEER_MS as ps, atprotoDidMethod as pt, deviceEchoNonce as pu, carryMentions as q, voiceDownloadName as qa, endedRequests as qc, identityRefusal as qi, canonicalJson as ql, withoutPictureMetadata as qn, GROUP_MEMBER_CAP as qo, sentWhole as qr, HANDOFF_TIMINGS as qs, encodeDidDhtDeactivated as qt, traceLink as qu, sameX401HolderJwk as r, validExternalKey as ra, handoffContextProof as rc, parseRelayPayload as rd, TypingSender as ri, contactAskerHolds as rl, TEST_USDT_FAUCET_AMOUNT as rn, linkStop as ro, engineText as rr, RatchetBox as rs, sameSshKey as rt, createChatInvite as ru, appUpdateDecision as s, irohDescriptor as sa, handoffHelloFrame as sc, publicKeyFromZ32 as sd, PIN_LIMITS as si, knockSlotRecords as sl, assertTokenUnits as sn, COMMUNITY_REACTION_FRAME as so, GROUP_WANT_FRAME as sr, AWAITING_PEER_MS as ss, BitcoinAddressError as st, inviteOwnership as su, newX401HolderKey as t, PeerProofs as ta, handoffCancelFrame as tc, newerPacket as td, TYPING_KINDS as ti, REQUEST_LIFETIME_MS as tl, SEPOLIA_TEST_USDT as tn, dhtEditId as to, EngineError as tr, edgeParams as ts, parseSshPublicKey as tt, readDeviceInvite as tu, APP_STORE_LIMITS as u, HOLD_DATED_BACK_MS as ua, handoffPakeFrame as uc, sanitizeAvatar as ud, pinIsNewer as ui, mergeContactKnocks as ul, validatePaymentTarget as un, ReactionWindow as uo, groupFileFallback as ur, EXPECT_PEER_MS as us, ATPROTO_FULL_SCOPE as ut, ENROLL_CAPABILITY as uu, openGroupTyping as v, decodeDnsResponse as va, readHandoffDone as vc, toBase64Url as vd, deviceWakeRequest as vi, APP_ICON_PATH as vl, isPubkyKey as vn, pairedReplyAuthor as vo, SIGNAL_FRESH_MS as vr, webLocalFetch as vs, normalizeAtprotoHandle as vt, seedSigner as vu, decodeCommunityLink as w, nip05RootKey as wa, sealHandoffPiece as wc, vapidKeysMatch as wi, isAppUrl as wl, pubkyProofPath as wn, ITEM_STATES as wo, mayBeHub as wr, QUICK_REDIAL_MS as ws, DID_FILE_MAX_BYTES as wt, turnPutSummary as wu, CommunitySession as x, domainWellKnownFile as xa, readHandoffPake as xc, utf8Encode as xd, relayRequest as xi, appViewOf as xl, normalizePubkyKey as xn, BUTTON_ID as xo, groupSignalFrame as xr, encodeControl as xs, AtprotoProofError as xt, TURN_RAISE_READ_TIMEOUT_MS as xu, sealGroupTyping as y, dnsProofName as ya, readHandoffHave as yc, toZ32 as yd, newWakeToken as yi, APP_PERMISSIONS as yl, isPubkyProofFolder as yn, readReply as yo, SIGNAL_HOLD_MS as yr, LIMITS as ys, parseAtprotoDidDocument as yt, webCryptoSigner as yu, GROUP_LIMITS as z, sanitizeMime as za, enrollDoneFrame as zc, IDENTITY_MAX_EVIDENCE as zi, readAppRevocation as zl, withoutAudioMetadata as zn, statusCardText as zo, rankHubs as zr, HANDOFF_CANCEL as zs, parseDidDocument as zt, HEDGE_MS as zu };
39006
40305
 
39007
- //# sourceMappingURL=src-BTRPAi5X.js.map
40306
+ //# sourceMappingURL=src-BzsyAvPf.js.map