@ghostlytools/cli 1.13.0 → 1.13.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -10
- package/dist/assets/api-DV52o7A8.js +3 -0
- package/dist/assets/{api-CjOaoG-v.js → api-O57SNJcb.js} +495 -99
- package/dist/assets/api-O57SNJcb.js.map +1 -0
- package/dist/assets/{apiKit-BAGvlQtm.js → apiKit-CPTFJHA7.js} +40 -8
- package/dist/assets/{apiKit-BAGvlQtm.js.map → apiKit-CPTFJHA7.js.map} +1 -1
- package/dist/assets/{appFetch-BwJd-kNq.js → appFetch-Ca9DNQQ2.js} +2 -2
- package/dist/assets/{appFetch-BwJd-kNq.js.map → appFetch-Ca9DNQQ2.js.map} +1 -1
- package/dist/assets/{apps-Cuk45sz5.js → apps-gXpGFPiv.js} +16 -14
- package/dist/assets/apps-gXpGFPiv.js.map +1 -0
- package/dist/assets/{apps-DjY095Af.js → apps-uZTu5FlR.js} +1 -1
- package/dist/assets/{arkade-DryM-q5n.js → arkade-B6UNf5HI.js} +2 -2
- package/dist/assets/{arkade-DryM-q5n.js.map → arkade-B6UNf5HI.js.map} +1 -1
- package/dist/assets/{backup-DekVCDWv.js → backup-CxH3auHB.js} +9 -7
- package/dist/assets/backup-CxH3auHB.js.map +1 -0
- package/dist/assets/{backup-B56sQqoQ.js → backup-Di2U6QVH.js} +1 -1
- package/dist/assets/bark_ffi_wasm_bg-CcafsJla.js.map +1 -1
- package/dist/assets/{bitcoind-B2bbVSzh.js → bitcoind-BpZn3bRN.js} +2 -2
- package/dist/assets/{bitcoind-B2bbVSzh.js.map → bitcoind-BpZn3bRN.js.map} +1 -1
- package/dist/assets/bitcoindevkit_bg-BWQHx7vd.js.map +1 -1
- package/dist/assets/{buttons-BGxzOtrq.js → buttons-D4udKEvT.js} +8 -8
- package/dist/assets/buttons-D4udKEvT.js.map +1 -0
- package/dist/assets/buttons-YTYEqvGC.js +1 -0
- package/dist/assets/{client-DcQAfc3h.js → client-DGx7E8b3.js} +3 -3
- package/dist/assets/{client-DcQAfc3h.js.map → client-DGx7E8b3.js.map} +1 -1
- package/dist/assets/{domainProofs-BDNP1dIy.js → domainProofs-b3Y1Gj9g.js} +6 -2
- package/dist/assets/{domainProofs-BDNP1dIy.js.map → domainProofs-b3Y1Gj9g.js.map} +1 -1
- package/dist/assets/{engineErrors--9hfgKlK.js → engineErrors-wWlLy54D.js} +11 -3
- package/dist/assets/engineErrors-wWlLy54D.js.map +1 -0
- package/dist/assets/{errors-DDLFO4Gf.js → errors-JVJsO8Iu.js} +18 -2
- package/dist/assets/errors-JVJsO8Iu.js.map +1 -0
- package/dist/assets/{fixedHosts-C3hBliM9.js → fixedHosts-CODN2pTL.js} +3 -3
- package/dist/assets/{fixedHosts-C3hBliM9.js.map → fixedHosts-CODN2pTL.js.map} +1 -1
- package/dist/assets/{ghostly_iroh_web-DIj5xGmR.js → ghostly_iroh_web-9VOwZcJQ.js} +30 -35
- package/dist/assets/ghostly_iroh_web-9VOwZcJQ.js.map +1 -0
- package/dist/assets/ghostly_iroh_web_bg.wasm +0 -0
- package/dist/assets/{groupMeta-goASqzOt.js → groupMeta-CeZpqVVC.js} +174 -37
- package/dist/assets/groupMeta-CeZpqVVC.js.map +1 -0
- package/dist/assets/{host-C2WRKj3g.js → host-CRA7h5A2.js} +270 -64
- package/dist/assets/host-CRA7h5A2.js.map +1 -0
- package/dist/assets/{hyperdhtRelay-DLUiwfnt.js → hyperdhtRelay-B34Zhz4P.js} +2 -2
- package/dist/assets/{hyperdhtRelay-DLUiwfnt.js.map → hyperdhtRelay-B34Zhz4P.js.map} +1 -1
- package/dist/assets/{hyperdhtRelay-bjNGacf5.js → hyperdhtRelay-DDwU5b4P.js} +2 -2
- package/dist/assets/{hyperdhtRelay-bjNGacf5.js.map → hyperdhtRelay-DDwU5b4P.js.map} +1 -1
- package/dist/assets/{identityProofs-Cksc_K7_.js → identityProofs-B8zCp5_0.js} +140 -27
- package/dist/assets/identityProofs-B8zCp5_0.js.map +1 -0
- package/dist/assets/{irohWeb-NfthOL98.js → irohWeb-mnOi2Jp7.js} +10838 -4837
- package/dist/assets/irohWeb-mnOi2Jp7.js.map +1 -0
- package/dist/assets/{linkPreview-DdMf-YAc.js → linkPreview-5kHmKUTN.js} +20 -8
- package/dist/assets/linkPreview-5kHmKUTN.js.map +1 -0
- package/dist/assets/{main-Dh7fePd8.js → main-Chc871HV.js} +119 -81
- package/dist/assets/main-Chc871HV.js.map +1 -0
- package/dist/assets/{mainline-DY95WbuK.js → mainline-CDUXtV-I.js} +2 -2
- package/dist/assets/{mainline-DY95WbuK.js.map → mainline-CDUXtV-I.js.map} +1 -1
- package/dist/assets/{networkReason-Be-hMghr.js → networkReason-DYlPZS5M.js} +2 -2
- package/dist/assets/{networkReason-Be-hMghr.js.map → networkReason-DYlPZS5M.js.map} +1 -1
- package/dist/assets/{ownDid-BErplN7N.js → ownDid-BOuSlDv-.js} +10 -6
- package/dist/assets/ownDid-BOuSlDv-.js.map +1 -0
- package/dist/assets/{ownStatus-ClrFjd7h.js → ownStatus-CLA1VPkL.js} +6 -6
- package/dist/assets/{ownStatus-ClrFjd7h.js.map → ownStatus-CLA1VPkL.js.map} +1 -1
- package/dist/assets/{pairedTransports-BKmvlKz1.js → pairedTransports-DAzupLYo.js} +23 -17
- package/dist/assets/pairedTransports-DAzupLYo.js.map +1 -0
- package/dist/assets/{paymentIntent-DySU3Ajm.js → paymentIntent-Cr3uZa_0.js} +2 -2
- package/dist/assets/{paymentIntent-DySU3Ajm.js.map → paymentIntent-Cr3uZa_0.js.map} +1 -1
- package/dist/assets/{profiles-B8xO8-oj.js → profiles-BH1bH9aE.js} +3 -3
- package/dist/assets/{profiles-B8xO8-oj.js.map → profiles-BH1bH9aE.js.map} +1 -1
- package/dist/assets/{registry--Rg2YvOH.js → registry-DAq16T-V.js} +1 -1
- package/dist/assets/{registry-CU8PevhI.js → registry-DP_-RA-v.js} +11 -7
- package/dist/assets/registry-DP_-RA-v.js.map +1 -0
- package/dist/assets/{relay-CHWg5hpZ.js → relay-gJTOYQJZ.js} +93 -7
- package/dist/assets/relay-gJTOYQJZ.js.map +1 -0
- package/dist/assets/{resolve-B1upovPM.js → resolve-B1eQ4dVQ.js} +10 -5
- package/dist/assets/resolve-B1eQ4dVQ.js.map +1 -0
- package/dist/assets/secretGuard-Bh11MPdI.js +1 -0
- package/dist/assets/{secretGuard-BrATm_gl.js → secretGuard-oz_3hBfW.js} +19 -2
- package/dist/assets/{secretGuard-BrATm_gl.js.map → secretGuard-oz_3hBfW.js.map} +1 -1
- package/dist/assets/{server-Dgxx_DaN.js → server-Bd2ofxc1.js} +1283 -6628
- package/dist/assets/server-Bd2ofxc1.js.map +1 -0
- package/dist/assets/{sshForges-BnvwmNj-.js → sshForges-As7dbGXM.js} +2 -2
- package/dist/assets/{sshForges-BnvwmNj-.js.map → sshForges-As7dbGXM.js.map} +1 -1
- package/dist/assets/{translate-BcbSWkuq.js → translate-DnuQMfj0.js} +22 -11
- package/dist/assets/translate-DnuQMfj0.js.map +1 -0
- package/dist/assets/{usdt-CBJ4Q5Ji.js → usdt-DLmtf8F9.js} +4 -4
- package/dist/assets/{usdt-CBJ4Q5Ji.js.map → usdt-DLmtf8F9.js.map} +1 -1
- package/dist/assets/{waitNotice-ylU3XwjO.js → waitNotice-BHuMofaH.js} +57 -3
- package/dist/assets/waitNotice-BHuMofaH.js.map +1 -0
- package/dist/ghostly.mjs +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/assets/api-CVtg7MpI.js +0 -3
- package/dist/assets/api-CjOaoG-v.js.map +0 -1
- package/dist/assets/apps-Cuk45sz5.js.map +0 -1
- package/dist/assets/backup-DekVCDWv.js.map +0 -1
- package/dist/assets/buttons-BGxzOtrq.js.map +0 -1
- package/dist/assets/buttons-CsN2WJOf.js +0 -1
- package/dist/assets/engineErrors--9hfgKlK.js.map +0 -1
- package/dist/assets/errors-DDLFO4Gf.js.map +0 -1
- package/dist/assets/ghostly_iroh_web-DIj5xGmR.js.map +0 -1
- package/dist/assets/groupMeta-goASqzOt.js.map +0 -1
- package/dist/assets/host-C2WRKj3g.js.map +0 -1
- package/dist/assets/identityProofs-Cksc_K7_.js.map +0 -1
- package/dist/assets/irohWeb-NfthOL98.js.map +0 -1
- package/dist/assets/linkPreview-DdMf-YAc.js.map +0 -1
- package/dist/assets/main-Dh7fePd8.js.map +0 -1
- package/dist/assets/ownDid-BErplN7N.js.map +0 -1
- package/dist/assets/pairedTransports-BKmvlKz1.js.map +0 -1
- package/dist/assets/registry-CU8PevhI.js.map +0 -1
- package/dist/assets/relay-CHWg5hpZ.js.map +0 -1
- package/dist/assets/resolve-B1upovPM.js.map +0 -1
- package/dist/assets/secretGuard-Bm6nci0I.js +0 -1
- package/dist/assets/server-Dgxx_DaN.js.map +0 -1
- package/dist/assets/translate-BcbSWkuq.js.map +0 -1
- package/dist/assets/waitNotice-ylU3XwjO.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"irohWeb-mnOi2Jp7.js","names":["STRIPPED_TYPES","u32be","u32le","text","check","boxes","ZEROS","u32be","text","check","within","u32le","hex","PREFIX","seenKey","hex","loading","hex","sats","openSecret","sealSecret"],"sources":["../../../core/src/pictureMetadata.ts","../../../core/src/videoMetadata.ts","../../../core/src/audioMetadata.ts","../../../core/src/lnurl.ts","../../../core/src/groupMentions.ts","../../../core/src/groupEdits.ts","../../../core/src/catchUp.ts","../../../core/src/groupEntry.ts","../../../core/src/groupCommunity.ts","../../../browser/src/engine/paymentAdapters/away.ts","../../../browser/src/engine/paymentAdapters/modeGate.ts","../../../browser/src/shared/ice.ts","../../../browser/src/engine/paymentAdapters/providers/breezDatabases.ts","../../../browser/src/engine/paymentAdapters/providers/breezSdk.ts","../../../browser/src/engine/paymentAdapters/cashu.ts","../../../browser/src/engine/askBackoff.ts","../../../browser/src/engine/paymentAdapters/providers/cashuMint.ts","../../../browser/src/engine/paymentAdapters/providers/sources.ts","../../../browser/src/engine/invoicePace.ts","../../../browser/src/engine/paymentAdapters/providers/lightningService.ts","../../../browser/src/engine/paymentAdapters/providers/recoveryPhrase.ts","../../../browser/src/engine/paymentAdapters/providers/breez.ts","../../../browser/src/engine/paymentAdapters/providers/lightningCards.ts","../../../browser/src/proofs/load.ts","../../../browser/src/engine/identities.ts","../../../browser/src/shared/storedFiles.ts","../../../browser/src/engine/forwards.ts","../../../browser/src/shared/types.ts","../../../browser/src/engine/paymentAdapters/walletInstances.ts","../../../browser/src/shared/paymentIds.ts","../../../browser/src/shared/replies.ts","../../../browser/src/engine/groupFiles.ts","../../../browser/src/shared/payLinks.ts","../../../browser/src/shared/groupPayNotes.ts","../../../browser/src/engine/wallet.ts","../../../browser/src/platform/irohWeb.ts"],"sourcesContent":["/**\n * What a picture leaves with. A photo's file says more than its pixels: its Exif and XMP hold where it was taken, the\n * device, the time, often a thumbnail of the uncropped original. The sender removes them before the file is stored and\n * its digest computed, so what the contact (or anyone in a community) receives is the picture alone: JPEG, PNG, WebP\n * and HEIF (HEIC, AVIF), without decoding or re-encoding a pixel.\n *\n * Fail-closed: a file that is one of these pictures, by its bytes or by its type, and whose metadata cannot be removed\n * (truncated, malformed, a part this does not know) is refused with `NO_PICTURE_METADATA`, never sent as it was. So is\n * a JPEG XL or a JPEG 2000 in its boxes (their Exif, XMP and GeoJP2 boxes are not removed here). Any other file goes\n * as it is.\n */\nimport { exifOrientation } from \"./image\";\n\nexport const PICTURE_METADATA_LIMITS = {\n /** The largest picture read whole to remove its metadata: past this it is refused. */\n maxBytes: 256 * 1024 * 1024,\n /** Bytes read first to tell a picture from another file. */\n headBytes: 64,\n} as const;\n\n/** Why a picture is refused: its metadata could not be removed, so it does not go at all. */\nexport const NO_PICTURE_METADATA = \"This picture cannot be sent: Ghostly could not remove the details saved in it, like where it was taken\";\n\n/** The types of the pictures stripped here: a file of one of them whose bytes are not that picture is refused. */\nconst STRIPPED_TYPES = new Set([\n \"image/jpeg\", \"image/jpg\", \"image/pjpeg\", \"image/png\", \"image/apng\", \"image/webp\",\n \"image/heic\", \"image/heif\", \"image/heic-sequence\", \"image/heif-sequence\", \"image/avif\", \"image/gif\", \"image/tiff\", \"image/tiff-fx\",\n]);\n\n/** HEIF brands (HEIC, AVIF, the generic `mif1`): an MP4 video's `ftyp` names none of them. */\nconst HEIF_BRANDS = new Set([\"heic\", \"heix\", \"heim\", \"heis\", \"hevc\", \"hevx\", \"mif1\", \"mif2\", \"msf1\", \"avif\", \"avis\"]);\n\ntype Kind = \"jpeg\" | \"png\" | \"webp\" | \"heif\" | \"gif\" | \"tiff\" | \"boxes\";\n\n/** The signature box a JPEG XL (`JXL `) or a JPEG 2000 (`jP `) in boxes starts with. */\nconst SIGNATURE_BOXES = new Set([\"JXL \", \"jP \"]);\n\nconst u16be = (b: Uint8Array, at: number) => (b[at]! << 8) | b[at + 1]!;\nconst u32be = (b: Uint8Array, at: number) => ((b[at]! << 24) >>> 0) + (b[at + 1]! << 16) + (b[at + 2]! << 8) + b[at + 3]!;\nconst u32le = (b: Uint8Array, at: number) => (b[at]! | (b[at + 1]! << 8) | (b[at + 2]! << 16) | (b[at + 3]! << 24)) >>> 0;\nconst text = (b: Uint8Array, at: number, length: number) => String.fromCharCode(...b.subarray(at, at + length));\nconst starts = (b: Uint8Array, at: number, prefix: string) => at + prefix.length <= b.length && text(b, at, prefix.length) === prefix;\n\n/** A picture this strips, by its first bytes. */\nfunction kindOf(b: Uint8Array): Kind | undefined {\n if (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return \"jpeg\";\n if (b.length >= 8 && b[0] === 0x89 && starts(b, 1, \"PNG\\r\\n\\x1a\\n\")) return \"png\";\n if (b.length >= 12 && starts(b, 0, \"RIFF\") && starts(b, 8, \"WEBP\")) return \"webp\";\n if (starts(b, 0, \"GIF87a\") || starts(b, 0, \"GIF89a\")) return \"gif\";\n // TIFF, and BigTIFF (refused): camera raw files (DNG, CR2, NEF, ARW) are TIFF too.\n if (starts(b, 0, \"II*\\0\") || starts(b, 0, \"MM\\0*\") || starts(b, 0, \"II+\\0\") || starts(b, 0, \"MM\\0+\")) return \"tiff\";\n if (b.length >= 12 && u32be(b, 0) === 12 && SIGNATURE_BOXES.has(text(b, 4, 4)) && u32be(b, 8) === 0x0d0a870a) return \"boxes\";\n if (b.length >= 16 && starts(b, 4, \"ftyp\")) {\n const end = Math.min(b.length, u32be(b, 0));\n for (let at = 8; at + 4 <= end; at += 4) if (at !== 12 && HEIF_BRANDS.has(text(b, at, 4))) return \"heif\";\n }\n return undefined;\n}\n\n/** Refuses the picture where its bytes are not what this expects. */\nfunction check(ok: boolean): asserts ok {\n if (!ok) throw new Error(NO_PICTURE_METADATA);\n}\n\n// JPEG: the segments that draw the picture stay (frames, tables, scans, restart intervals, JFIF without its thumbnail,\n// the ICC profile, Adobe's colour transform) and the camera's Orientation, alone in an Exif of its own; every other\n// APPn (Exif, XMP, IPTC, MPF), comments, and whatever follows the image's end (a gain map, a motion photo's video) go.\n// As Android's Camera strips its photos (CameraPhoto.kt).\n\n/** SOFn markers: every frame type but DHT (C4), JPG (C8) and DAC (CC). */\nconst JPEG_FRAME = new Set([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf]);\n\nfunction jpegKeeps(marker: number, b: Uint8Array, payload: number): boolean {\n if ((marker >= 0xc0 && marker <= 0xcf) || (marker >= 0xda && marker <= 0xdf)) return true;\n if (marker === 0xe0) return starts(b, payload, \"JFIF\\0\");\n if (marker === 0xe2) return starts(b, payload, \"ICC_PROFILE\\0\");\n if (marker === 0xee) return starts(b, payload, \"Adobe\");\n return false;\n}\n\n/** An Exif (its TIFF), big-endian, whose IFD0 holds `orientation` alone: all a picture keeps of its Exif. */\nconst orientationTiff = (orientation: number) => Uint8Array.of(\n 0x4d, 0x4d, 0, 42, 0, 0, 0, 8, 0, 1, 0x01, 0x12, 0, 3, 0, 0, 0, 1, 0, orientation, 0, 0, 0, 0, 0, 0,\n);\n\n/** An APP1 Exif whose IFD0 holds `orientation` alone. */\nconst orientationOnly = (orientation: number) => Uint8Array.of(0xff, 0xe1, 0, 34, 0x45, 0x78, 0x69, 0x66, 0, 0, ...orientationTiff(orientation));\n\nfunction stripJpeg(b: Uint8Array): Uint8Array[] {\n const parts = [b.subarray(0, 2)];\n let at = 2, framed = false, scanned = false, exif = false;\n for (;;) {\n check(at < b.length && b[at] === 0xff);\n while (at < b.length && b[at] === 0xff) at++;\n check(at < b.length);\n const marker = b[at++]!;\n if (marker === 0xd9) {\n check(framed && scanned);\n parts.push(Uint8Array.of(0xff, 0xd9));\n return parts;\n }\n // TEM and restarts stand alone.\n if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) { parts.push(Uint8Array.of(0xff, marker)); continue; }\n check(marker !== 0x00 && marker !== 0xd8 && at + 2 <= b.length);\n const length = u16be(b, at);\n check(length >= 2 && at + length <= b.length);\n if (marker === 0xe0 && length > 16 && starts(b, at + 2, \"JFIF\\0\")) {\n // JFIF's header without its thumbnail: no thumbnail's width and height, and no pixels after them.\n parts.push(Uint8Array.of(0xff, 0xe0, 0, 16, ...b.subarray(at + 2, at + 14), 0, 0));\n } else if (jpegKeeps(marker, b, at + 2)) {\n parts.push(Uint8Array.of(0xff, marker), b.subarray(at, at + length));\n if (JPEG_FRAME.has(marker)) framed = true;\n } else if (marker === 0xe1 && !scanned && !exif && starts(b, at + 2, \"Exif\\0\\0\")) {\n exif = true;\n const orientation = exifOrientation(b, at + 8, at + length);\n if (orientation >= 2) parts.push(orientationOnly(orientation));\n }\n at += length;\n if (marker !== 0xda) continue;\n check(framed);\n scanned = true;\n // The scan's image data, where FF 00 is a data byte and FF D0 to D7 a restart, up to the marker that ends it.\n let end = at;\n for (;;) {\n end = b.indexOf(0xff, end);\n check(end >= 0);\n let next = end + 1;\n while (next < b.length && b[next] === 0xff) next++;\n check(next < b.length);\n if (b[next] !== 0x00 && !(b[next]! >= 0xd0 && b[next]! <= 0xd7)) break;\n end = next + 1;\n }\n parts.push(b.subarray(at, end));\n at = end;\n }\n}\n\n// PNG: the critical chunks and the ancillary ones that change how it is drawn (transparency, colour, animation)\n// stay, and the camera's Orientation, alone in an eXIf of its own before the image data; text (tEXt, iTXt, zTXt), the\n// rest of the Exif, tIME and every other chunk go, and anything after IEND.\n\nconst PNG_CRITICAL = new Set([\"IHDR\", \"PLTE\", \"IDAT\", \"IEND\"]);\nconst PNG_DRAWS = new Set([\"tRNS\", \"gAMA\", \"cHRM\", \"sRGB\", \"iCCP\", \"sBIT\", \"bKGD\", \"pHYs\", \"cICP\", \"mDCV\", \"cLLI\", \"acTL\", \"fcTL\", \"fdAT\"]);\n\nconst CRC_TABLE = Array.from({ length: 256 }, (_, n) => {\n for (let k = 0; k < 8; k++) n = n & 1 ? 0xedb88320 ^ (n >>> 1) : n >>> 1;\n return n >>> 0;\n});\n\n/** A PNG chunk: its length, type, data and the CRC of its type and data. */\nfunction pngChunk(type: string, data: Uint8Array): Uint8Array {\n const out = new Uint8Array(12 + data.length), view = new DataView(out.buffer);\n view.setUint32(0, data.length);\n for (let i = 0; i < 4; i++) out[4 + i] = type.charCodeAt(i);\n out.set(data, 8);\n let crc = ~0;\n for (const byte of out.subarray(4, 8 + data.length)) crc = CRC_TABLE[(crc ^ byte) & 0xff]! ^ (crc >>> 8);\n view.setUint32(8 + data.length, ~crc >>> 0);\n return out;\n}\n\nfunction stripPng(b: Uint8Array): Uint8Array[] {\n const parts = [b.subarray(0, 8)];\n let at = 8, exif = false, imaged = false;\n for (;;) {\n check(at + 12 <= b.length);\n const length = u32be(b, at), type = text(b, at + 4, 4);\n check(at + 12 + length <= b.length && (at > 8 || type === \"IHDR\"));\n // A critical chunk this does not know (its first letter upper case) may hold anything a decoder needs.\n const critical = (b[at + 4]! & 0x20) === 0;\n check(!critical || PNG_CRITICAL.has(type));\n if (critical || PNG_DRAWS.has(type)) parts.push(b.subarray(at, at + 12 + length));\n else if (type === \"eXIf\" && !exif && !imaged) {\n // The first one, read before the image data as browsers do; its Orientation alone, where it was.\n exif = true;\n const orientation = exifOrientation(b, at + 8, at + 8 + length);\n if (orientation >= 2) parts.push(pngChunk(\"eXIf\", orientationTiff(orientation)));\n }\n if (type === \"IDAT\") imaged = true;\n at += 12 + length;\n if (type === \"IEND\") return parts;\n }\n}\n\n// WebP: the image, its alpha, animation and ICC profile stay, and the camera's Orientation, alone in an EXIF of its\n// own; XMP, the rest of the Exif and unknown chunks go, and VP8X says it has an EXIF only when one is left.\n\nconst WEBP_KEEPS = new Set([\"VP8 \", \"VP8L\", \"VP8X\", \"ALPH\", \"ANIM\", \"ANMF\", \"ICCP\"]);\n\nfunction stripWebp(b: Uint8Array): Uint8Array[] {\n check(b.length >= 20);\n const riffEnd = 8 + u32le(b, 4);\n check(riffEnd <= b.length && riffEnd % 2 === 0);\n const parts: Uint8Array[] = [];\n let at = 12, size = 4, drawn = false, exif = false, vp8x: Uint8Array | undefined;\n while (at < riffEnd) {\n check(at + 8 <= riffEnd);\n const type = text(b, at, 4), length = u32le(b, at + 4), end = at + 8 + length + (length & 1);\n check(end <= riffEnd && (at > 12 || type === \"VP8 \" || type === \"VP8L\" || type === \"VP8X\"));\n let chunk: Uint8Array | undefined;\n if (WEBP_KEEPS.has(type)) {\n chunk = b.subarray(at, end);\n if (type === \"VP8X\") {\n check(length >= 10);\n // Its flags: EXIF (0x08) and XMP (0x04) are gone, until an Orientation is kept.\n chunk = vp8x = chunk.slice();\n chunk[8] = chunk[8]! & ~0x0c;\n }\n if (type === \"VP8 \" || type === \"VP8L\" || type === \"ANMF\") drawn = true;\n } else if (type === \"EXIF\" && !exif && vp8x) {\n // The first one, in an extended WebP (a simple one has none); some writers put JPEG's \"Exif\\0\\0\" before its TIFF.\n exif = true;\n const tiff = starts(b, at + 8, \"Exif\\0\\0\") ? at + 14 : at + 8;\n const orientation = exifOrientation(b, tiff, at + 8 + length);\n if (orientation >= 2) {\n const data = orientationTiff(orientation);\n chunk = new Uint8Array(8 + data.length);\n chunk.set([0x45, 0x58, 0x49, 0x46, data.length]);\n chunk.set(data, 8);\n vp8x[8] = vp8x[8]! | 0x08;\n }\n }\n if (chunk) {\n parts.push(chunk);\n size += chunk.length;\n }\n at = end;\n }\n check(drawn);\n const header = new Uint8Array(12);\n header.set(b.subarray(0, 12));\n new DataView(header.buffer).setUint32(4, size, true);\n return [header, ...parts];\n}\n\n// HEIF (HEIC, AVIF): its Exif and XMP are items of the `meta` box whose bytes sit elsewhere in the file. They are\n// overwritten with zeros where they are, so no offset in the file moves, and so are the bodies of `free` and `skip`\n// boxes (an editor's leftovers), their headers kept. The item properties (`iprp`'s `ipco`) that say what the picture\n// is about rather than how it is drawn are zeroed the same way: they stay where they are, as `ipma` points at them by\n// position. A part this does not know, at the top, in `meta` or among the properties (a video track, an XML box, a\n// `uuid` box, camera parameters), or a picture's bytes inside a `free` or `skip` box, refuses the picture.\n\nconst HEIF_TOP = new Set([\"ftyp\", \"meta\", \"mdat\", \"free\", \"skip\"]);\nconst HEIF_META = new Set([\"hdlr\", \"dinf\", \"pitm\", \"iloc\", \"iinf\", \"iref\", \"iprp\", \"idat\", \"grpl\", \"free\", \"skip\"]);\n/** Items that hold metadata: Exif, and XMP (or any other document) as a MIME item. */\nconst HEIF_METADATA_ITEMS = new Set([\"Exif\", \"mime\", \"uri \"]);\n/**\n * Item properties that only draw the picture: the codec's configuration (HEVC, AV1, AVC, VVC, JPEG, JPEG 2000,\n * uncompressed and its components, layered HEVC with its operating points and layers), the size (`ispe`), the bits\n * per channel (`pixi`), colour (`colr`, its light levels and display volumes `clli`, `mdcv`, `cclv`, `amve`), geometry\n * (`irot`, `imir`, `clap`, `pasp`, `rloc`, `iscl`), what an auxiliary image is (`auxC`: alpha, depth, a gain map), and\n * AV1's operating point and layers (`a1op`, `a1lx`).\n */\nconst HEIF_DRAWS = new Set([\n \"hvcC\", \"av1C\", \"avcC\", \"vvcC\", \"jpgC\", \"j2kH\", \"uncC\", \"cmpd\", \"lhvC\", \"oinf\", \"tols\", \"lsel\",\n \"ispe\", \"pixi\", \"colr\", \"clli\", \"mdcv\", \"cclv\", \"amve\", \"irot\", \"imir\", \"clap\", \"pasp\", \"rloc\", \"iscl\", \"auxC\", \"a1op\", \"a1lx\",\n]);\n/** Item properties about the picture: its user description (name, description, tags), accessibility text, creation and modification times, TAI clock and timestamp; and `free`, `skip`. */\nconst HEIF_ABOUT = new Set([\"udes\", \"altt\", \"crtt\", \"mdft\", \"taic\", \"itai\", \"free\", \"skip\"]);\n\ninterface Box { type: string; start: number; body: number; end: number }\n\nfunction boxes(b: Uint8Array, start: number, end: number): Box[] {\n const found: Box[] = [];\n for (let at = start; at < end;) {\n check(at + 8 <= end);\n let size = u32be(b, at), body = at + 8;\n const type = text(b, at + 4, 4);\n if (size === 1) {\n check(at + 16 <= end);\n size = u32be(b, at + 8) * 2 ** 32 + u32be(b, at + 12);\n body = at + 16;\n } else if (size === 0) size = end - at;\n if (type === \"uuid\") body += 16;\n check(size >= body - at && at + size <= end);\n found.push({ type, start: at, body, end: at + size });\n at += size;\n }\n return found;\n}\n\nfunction stripHeif(b: Uint8Array): Uint8Array[] {\n const top = boxes(b, 0, b.length);\n check(top[0]?.type === \"ftyp\" && top.every((box) => HEIF_TOP.has(box.type)));\n const metas = top.filter((box) => box.type === \"meta\");\n check(metas.length === 1);\n const meta = metas[0]!;\n // A FullBox: version and flags first.\n const children = boxes(b, meta.body + 4, meta.end);\n check(children.every((box) => HEIF_META.has(box.type)));\n const one = (type: string) => {\n const of = children.filter((box) => box.type === type);\n check(of.length <= 1);\n return of[0];\n };\n const iinf = one(\"iinf\"), iloc = one(\"iloc\"), idat = one(\"idat\");\n check(!!iinf && !!iloc);\n\n // The metadata items, by id.\n const metadata = new Set<number>();\n const infeVersion = b[iinf.body]!;\n const entries = boxes(b, iinf.body + 4 + (infeVersion === 0 ? 2 : 4), iinf.end);\n for (const infe of entries) {\n check(infe.type === \"infe\" && infe.body + 4 <= infe.end);\n const version = b[infe.body]!;\n // Versions 0 and 1 have no item type: this cannot tell what they hold.\n check(version === 2 || version === 3);\n let at = infe.body + 4;\n const id = version === 2 ? u16be(b, at) : u32be(b, at);\n at += version === 2 ? 2 : 4;\n check(at + 6 <= infe.end);\n if (HEIF_METADATA_ITEMS.has(text(b, at + 2, 4))) metadata.add(id);\n }\n\n // The item properties: one `ipco`, and the `ipma` that associate them with items.\n const iprp = one(\"iprp\"), properties: Box[] = [];\n if (iprp) {\n const held = boxes(b, iprp.body, iprp.end);\n const ipco = held.filter((box) => box.type === \"ipco\");\n check(ipco.length === 1 && held.every((box) => box.type === \"ipco\" || box.type === \"ipma\"));\n properties.push(...boxes(b, ipco[0]!.body, ipco[0]!.end));\n check(properties.every((box) => HEIF_DRAWS.has(box.type) || HEIF_ABOUT.has(box.type)));\n }\n\n /** `free` and `skip` boxes, at the top and in `meta`, and the properties about the picture: their bodies go as zeros. */\n const space = [\n ...[...top, ...children].filter((box) => box.type === \"free\" || box.type === \"skip\"),\n ...properties.filter((box) => HEIF_ABOUT.has(box.type)),\n ];\n\n // Where their bytes are (iloc), overwritten in a copy.\n const out = b.slice();\n const version = b[iloc.body]!;\n check(version <= 2);\n let at = iloc.body + 4;\n /** The next field of `size` bytes (0, 2, 4 or 8), big-endian. */\n const read = (size: number): number => {\n check(at + size <= iloc.end);\n const value = size === 0 ? 0 : size === 2 ? u16be(b, at) : size === 4 ? u32be(b, at) : size === 8 ? u32be(b, at) * 2 ** 32 + u32be(b, at + 4) : NaN;\n check(Number.isSafeInteger(value));\n at += size;\n return value;\n };\n const read2 = () => read(2);\n check(at + 2 <= iloc.end);\n const offsetSize = b[at]! >> 4, lengthSize = b[at]! & 15, baseSize = b[at + 1]! >> 4, indexSize = version > 0 ? b[at + 1]! & 15 : 0;\n check([offsetSize, lengthSize, baseSize, indexSize].every((size) => size === 0 || size === 4 || size === 8));\n at += 2;\n const count = read(version < 2 ? 2 : 4);\n for (let i = 0; i < count; i++) {\n const id = version < 2 ? read2() : read(4);\n const method = version > 0 ? read2() & 15 : 0;\n const reference = read2();\n const base = read(baseSize);\n const extents = read2();\n for (let e = 0; e < extents; e++) {\n if (indexSize) read(indexSize);\n const offset = read(offsetSize), length = read(lengthSize);\n if (!metadata.has(id)) {\n // The picture's bytes (to the file's end for a length of 0) are in no space zeroed below.\n const start = base + offset, end = length ? start + length : b.length;\n check(reference !== 0 || method !== 0 || !space.some((box) => start < box.end && end > box.body));\n continue;\n }\n // Its bytes in this file (0) or in `idat` (1): a length of 0 (to the end) or another file, refused.\n check(reference === 0 && length > 0 && (method === 0 || (method === 1 && !!idat)));\n const start = (method === 1 ? idat!.body : 0) + base + offset, limit = method === 1 ? idat!.end : b.length;\n check(start + length <= limit);\n out.fill(0, start, start + length);\n }\n }\n for (const box of space) out.fill(0, box.body, box.end);\n return [out];\n}\n\n// GIF: the frames, their colour tables and timing (graphic control, plain text), the animation's loop (NETSCAPE2.0,\n// ANIMEXTS1.0) and its ICC profile stay byte for byte; comments, XMP and every other application extension go, and\n// whatever follows its end.\n\nconst GIF_APPS_KEPT = new Set([\"NETSCAPE2.0\", \"ANIMEXTS1.0\", \"ICCRGBG1012\"]);\n\nfunction stripGif(b: Uint8Array): Uint8Array[] {\n check(b.length >= 13);\n /** A colour table's bytes, from the flags that say it is there and its size. */\n const table = (flags: number) => (flags & 0x80 ? 3 << ((flags & 7) + 1) : 0);\n /** The end of the data sub-blocks at `at`, past their empty block. */\n const blocks = (at: number) => {\n for (;;) {\n check(at < b.length);\n const length = b[at]!;\n at += 1 + length;\n if (!length) return at;\n }\n };\n let at = 13 + table(b[10]!), framed = false;\n check(at <= b.length);\n const parts = [b.subarray(0, at)];\n for (;;) {\n check(at < b.length);\n const introducer = b[at]!;\n if (introducer === 0x3b) {\n check(framed);\n parts.push(Uint8Array.of(0x3b));\n return parts;\n }\n if (introducer === 0x2c) {\n // Image descriptor, its local colour table, the LZW code size, the image data.\n check(at + 10 <= b.length);\n const data = at + 10 + table(b[at + 9]!);\n check(data < b.length);\n const end = blocks(data + 1);\n parts.push(b.subarray(at, end));\n framed = true;\n at = end;\n continue;\n }\n check(introducer === 0x21 && at + 2 < b.length);\n const label = b[at + 1]!, end = blocks(at + 2);\n const app = label === 0xff && b[at + 2] === 11 && GIF_APPS_KEPT.has(text(b, at + 3, 11));\n if (label === 0xf9 || label === 0x01 || app) parts.push(b.subarray(at, end));\n else check(label === 0xfe || label === 0xff);\n at = end;\n }\n}\n\n// TIFF: what draws it stays where it is (size, strips or tiles, colour, Orientation, ICC profile); its text tags (Make,\n// Model, DateTime, Artist, Software, its description), XMP, IPTC and Photoshop's resources are overwritten with zeros\n// where they are, the Exif and GPS IFDs zeroed and their pointers taken out of the IFD that holds them (its other\n// entries move up in place), so no offset in the file moves. A tag this does not\n// know, sub-images, JPEG-compressed data (whose own segments could hold an Exif) or a maker note refuses the picture:\n// so camera raw files (DNG, CR2, NEF, ARW), and BigTIFF, are refused.\n\nconst TIFF_DRAWS = new Set([\n 254, 255, 256, 257, 258, 259, 262, 263, 264, 265, 266, 273, 274, 277, 278, 279, 280, 281, 282, 283, 284, 286, 287, 290,\n 291, 292, 293, 296, 297, 301, 317, 318, 319, 320, 321, 322, 323, 324, 325, 332, 334, 336, 338, 339, 340, 341, 529, 530,\n 531, 532, 0x8773,\n]);\n/** Text and documents about the picture: DocumentName to HostComputer, InkNames, XMP, Copyright, IPTC, Photoshop, Windows' XP tags, PrintIM. */\nconst TIFF_METADATA = new Set([269, 270, 271, 272, 285, 305, 306, 315, 316, 333, 700, 0x8298, 0x83bb, 0x8649, 0x4746, 0x4749, 0x9c9b, 0x9c9c, 0x9c9d, 0x9c9e, 0x9c9f, 0xc4a5]);\n/** The IFDs of Exif, GPS and interoperability, emptied whole. */\nconst TIFF_METADATA_IFDS = new Set([0x8769, 0x8825, 0xa005]);\n/** Compression without JPEG: none, CCITT, LZW, Deflate, PackBits. */\nconst TIFF_COMPRESSION = new Set([1, 2, 3, 4, 5, 8, 32773, 32946]);\n/** Bytes per value of each field type. */\nconst TIFF_TYPE_BYTES = [0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 4];\n\nfunction stripTiff(b: Uint8Array): Uint8Array[] {\n const little = b[0] === 0x49;\n const u16 = (at: number) => { check(at + 2 <= b.length); return little ? b[at]! | (b[at + 1]! << 8) : u16be(b, at); };\n const u32 = (at: number) => { check(at + 4 <= b.length); return little ? u32le(b, at) : u32be(b, at); };\n check(b.length >= 8 && u16(2) === 42);\n const out = b.slice(), seen = new Set<number>();\n /** An IFD's entries: tag, type, the value's first byte (in the entry or where it points) and its bytes. */\n const entries = (ifd: number) => {\n check(ifd >= 8 && !seen.has(ifd) && seen.size < 1024);\n seen.add(ifd);\n const count = u16(ifd), next = ifd + 2 + count * 12;\n u32(next);\n return {\n next,\n list: Array.from({ length: count }, (_, i) => {\n const at = ifd + 2 + i * 12, tag = u16(at), type = u16(at + 2);\n check(type >= 1 && type < TIFF_TYPE_BYTES.length);\n const bytes = TIFF_TYPE_BYTES[type]! * u32(at + 4);\n const value = bytes <= 4 ? at + 8 : u32(at + 8);\n check(Number.isSafeInteger(bytes) && value + bytes <= b.length);\n return { at, tag, type, value, bytes };\n }),\n };\n };\n /** An Exif, GPS or interoperability IFD: every value zeroed, then the IFD itself, so it holds no entry. */\n const empty = (ifd: number) => {\n const { next, list } = entries(ifd);\n for (const entry of list) {\n check(entry.tag !== 0x927c);\n if (TIFF_METADATA_IFDS.has(entry.tag)) empty(u32(entry.value));\n out.fill(0, entry.value, entry.value + entry.bytes);\n }\n out.fill(0, ifd, next + 4);\n };\n for (let ifd = u32(4); ifd;) {\n const { next, list } = entries(ifd);\n // The entries kept move up over the pointers to the emptied IFDs: libtiff refuses an IFD without an entry.\n let kept = 0;\n for (const { at, tag, value, bytes } of list) {\n if (tag === 259) check(TIFF_COMPRESSION.has(u16(value)));\n if (TIFF_METADATA_IFDS.has(tag)) {\n empty(u32(value));\n continue;\n }\n if (TIFF_METADATA.has(tag)) out.fill(0, value, value + bytes);\n else check(TIFF_DRAWS.has(tag));\n out.copyWithin(ifd + 2 + kept++ * 12, at, at + 12);\n }\n check(kept > 0);\n const end = ifd + 2 + kept * 12;\n out.set(little ? [kept & 0xff, kept >> 8] : [kept >> 8, kept & 0xff], ifd);\n out.set(b.subarray(next, next + 4), end);\n out.fill(0, end + 4, next + 4);\n ifd = u32(next);\n }\n return [out];\n}\n\n/** A JPEG XL or a JPEG 2000 in boxes: refused. */\nfunction refuse(): never {\n throw new Error(NO_PICTURE_METADATA);\n}\n\nconst STRIP: Record<Kind, (b: Uint8Array) => Uint8Array[]> = { jpeg: stripJpeg, png: stripPng, webp: stripWebp, heif: stripHeif, gif: stripGif, tiff: stripTiff, boxes: refuse };\n\n/**\n * A picture's bytes without its metadata, as parts to put in a Blob; undefined when the file is not a picture this\n * strips (by its bytes and its type), so it goes as it is. Throws `NO_PICTURE_METADATA` when it is one but its\n * metadata cannot be removed.\n */\nexport function stripPictureMetadata(bytes: Uint8Array, mime: string): Uint8Array[] | undefined {\n const kind = kindOf(bytes);\n if (!kind) {\n if (STRIPPED_TYPES.has(mime.split(\";\")[0]!.trim().toLowerCase())) throw new Error(NO_PICTURE_METADATA);\n return undefined;\n }\n return STRIP[kind](bytes);\n}\n\n/**\n * Whether a file is a picture whose metadata goes before it is sent, by its first `PICTURE_METADATA_LIMITS.headBytes`\n * bytes or by its type: then it is read whole and stripped (`stripPictureMetadata`), else it goes as it is.\n */\nexport function isStrippedPicture(head: Uint8Array, mime: string): boolean {\n return !!kindOf(head) || STRIPPED_TYPES.has(mime.split(\";\")[0]!.trim().toLowerCase());\n}\n\n/**\n * `source` as it is sent: without its metadata when it is a picture (`stripPictureMetadata`), or undefined when it is\n * not one and goes as it is. Only its first bytes are read for any other file. Throws `NO_PICTURE_METADATA` for a\n * picture that cannot be stripped or is past `PICTURE_METADATA_LIMITS.maxBytes`; an error reading `source` as it is.\n */\nexport async function withoutPictureMetadata(source: Blob, mime: string): Promise<Blob | undefined> {\n const head = new Uint8Array(await source.slice(0, PICTURE_METADATA_LIMITS.headBytes).arrayBuffer());\n if (!isStrippedPicture(head, mime)) return undefined;\n if (source.size > PICTURE_METADATA_LIMITS.maxBytes) throw new Error(NO_PICTURE_METADATA);\n const parts = stripPictureMetadata(new Uint8Array(await source.arrayBuffer()), mime);\n return parts && new Blob(parts as BlobPart[], { type: mime });\n}\n","/**\n * What a video leaves with. An MP4 or QuickTime file says more than its frames: its `udta` and `meta` boxes hold where\n * it was recorded (`©xyz`, `com.apple.quicktime.location.ISO6709`), the device, often its software; a timed metadata\n * track (an iPhone's location and motion, a GoPro's GPS) holds them sample by sample, a caption track (a drone's, a\n * dashcam's) a line of them each second; the movie's, each track's and\n * each track's media header (`mvhd`, `tkhd`, `mdhd`) say when it was recorded, to the second, and a camera's timecode\n * track the time of day. The sender removes them before the file is stored and its digest computed, without decoding\n * or re-encoding a frame: each such box becomes a `free` box of the same size, zeroed, the headers' creation and\n * modification times are zeroed (0 is \"unknown\"), the space already left in it (`free`, `skip`, `wide`: what an edit in\n * place left behind, a recorder's GPS log) is zeroed after its header, so are the names of its handlers and of the\n * compressor that made its frames, and each metadata, timecode and caption track's samples are zeroed where they are, so no\n * offset in the file moves and it plays as it did. Only the boxes' headers, `moov` and `moof` are read; the\n * media goes untouched.\n *\n * Fail-closed: a file that is an MP4 or QuickTime video, by its bytes or by its type, and whose metadata cannot be\n * removed (truncated, malformed, a part of its movie this does not know) is refused with `NO_VIDEO_METADATA`, never sent as it was.\n * A picture (HEIF is pictureMetadata.ts's) and any other file go as they are; so does a file without a video track (an\n * M4A) here: audioMetadata.ts strips it.\n *\n * An AVI (a dashcam's, an older camera's) goes without what its header and its `INFO` list say: each chunk but the\n * ones its frames and sound are made of (`avih`, `strh`, `strf`, `indx`, `vprp`, `dmlh`) becomes `JUNK`, zeroed (a\n * stream's name `strn` and data `strd`, `IDIT`'s date, a camera's `LIST ncdt`), and the chunks of a stream that is\n * neither pictures nor sound (a GPS or subtitle text stream) are zeroed in `movi`, so no offset moves. An ASF (WMV,\n * WMA), an FLV and an MPEG transport stream are refused with `NO_VIDEO_METADATA` (a WMA, typed as audio, with\n * `NO_AUDIO_METADATA`): their titles, places and dates are not removed here.\n */\nimport { isStrippedPicture } from \"./pictureMetadata\";\n\nexport const VIDEO_METADATA_LIMITS = {\n /** The largest `moov` or `moof` read whole, and the most bytes of a metadata track's chunk: past this the video is refused. */\n maxBoxBytes: 64 * 1024 * 1024,\n /** The most top-level boxes walked (a fragmented MP4 has two per fragment). */\n maxBoxes: 100_000,\n /** The most chunks of an AVI walked (one per frame and per piece of sound). */\n maxChunks: 4_000_000,\n /** Bytes read first to tell a video from another file. */\n headBytes: 64,\n /** Bytes read at once for a box's header or a small box, so the next headers and `moof`s are read with it. */\n readAhead: 64 * 1024,\n /** The most a walk going on from its window reads at once (an Ogg's pages, a live WebM's blocks: the whole file). */\n readAheadMax: 4 * 1024 * 1024,\n /** The most bytes between two parts replaced that are read and sent with them as one part of the stripped video. */\n joinGap: 64 * 1024,\n /** The most bytes of such a part. */\n joinedBytes: 4 * 1024 * 1024,\n} as const;\n\n/** Why a video is refused: its metadata could not be removed, so it does not go at all. */\nexport const NO_VIDEO_METADATA = \"This video cannot be sent: Ghostly could not remove the details saved in it, like where it was recorded\";\n\n/** The types of the videos stripped here: a file of one of them whose bytes are not one is refused. */\nconst STRIPPED_TYPES = new Set([\"video/mp4\", \"video/quicktime\", \"video/x-m4v\", \"video/3gpp\", \"video/3gpp2\"]);\n\n/**\n * The first box of an MP4 (`ftyp`), of a QuickTime file written without one, or of one a tool or a preview was put\n * before (`uuid`, `pnot`): a file that starts with one is a movie, refused when it is not one.\n */\nconst FIRST_BOXES = new Set([\"ftyp\", \"moov\", \"mdat\", \"wide\", \"free\", \"skip\", \"uuid\", \"pnot\", \"PICT\"]);\n\n/** Boxes that hold metadata wherever they are: emptied into `free`. */\nconst METADATA = new Set([\"udta\", \"meta\", \"uuid\"]);\n/**\n * Space left in a file (padding, or an old `moov` or `udta` an edit in place left behind), and what a recorder puts\n * there (a dashcam's GPS log, a thumbnail): kept where it is, its body zeroed.\n */\nconst SPACE = new Set([\"free\", \"skip\", \"wide\"]);\n/**\n * At the top: what makes the movie, kept (`moov` and `moof` looked into). Any other box is emptied, unless the movie's\n * samples are in it: the ones known at a movie's top (a preview picture, an event message, the wall-clock time a\n * fragment was made, `prft`) and a device's own (Samsung's `sefd`, a GPS track's `gps0`) alike.\n */\nconst TOP_KEEPS = new Set([\"ftyp\", \"styp\", \"moov\", \"mdat\", \"moof\", \"mfra\", \"sidx\", \"ssix\", \"pdin\", ...SPACE]);\n/** The boxes emptied that are known at a movie's top: a file that starts with one is read as boxes. */\nconst TOP_EMPTIED = new Set([...METADATA, \"pnot\", \"PICT\", \"emsg\", \"Xtra\", \"prft\"]);\nconst MOOV_KEEPS = new Set([\"mvhd\", \"trak\", \"mvex\", \"iods\", \"ctab\", ...SPACE]);\nconst TRAK_KEEPS = new Set([\"tkhd\", \"edts\", \"mdia\", \"tref\", \"tapt\", \"load\", \"txas\", \"matt\", ...SPACE]);\n/** Boxes looked into below a track (and in a fragment) for the metadata boxes in them. */\nconst CONTAINERS = new Set([\"mdia\", \"minf\", \"dinf\", \"stbl\", \"edts\", \"mvex\", \"traf\"]);\n/** Track handlers kept as they are: picture, sound, timecode, hints. `meta` tracks have their samples zeroed, `tmcd` ones and `CAPTIONS` too. */\nconst HANDLERS = new Set([\"vide\", \"soun\", \"tmcd\", \"hint\", \"auxv\", \"pict\", \"sdsm\", \"odsm\", \"subp\"]);\n/**\n * Text, subtitle and caption tracks: what a recorder writes there is a log (a drone's or a dashcam's GPS, home point,\n * date and time each second), so their samples are zeroed, in `moov`'s tables and in fragments alike; they show nothing.\n */\nconst CAPTIONS = new Set([\"text\", \"sbtl\", \"subt\", \"clcp\"]);\n/** The handlers whose sample descriptions are a visual one's, a compressor's name in each. */\nconst VISUAL = new Set([\"vide\", \"auxv\", \"pict\"]);\n\n/** 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. */\nconst ZEROS = new Blob([new Uint8Array(1024 * 1024)]);\n\nconst u32be = (b: Uint8Array, at: number) => ((b[at]! << 24) >>> 0) + (b[at + 1]! << 16) + (b[at + 2]! << 8) + b[at + 3]!;\nconst text = (b: Uint8Array, at: number, length: number) => String.fromCharCode(...b.subarray(at, at + length));\n\n/** Refuses the video where its bytes are not what this expects. */\nfunction check(ok: boolean): asserts ok {\n if (!ok) throw new Error(NO_VIDEO_METADATA);\n}\n\ninterface Box { type: string; start: number; body: number; end: number }\n\n/** A box's header at `at` of `b` (`base` its offset in the file), up to `end` (a size of 0 runs to it). */\nfunction header(b: Uint8Array, at: number, end: number, base = 0): Box {\n check(at + 8 <= b.length);\n let size = u32be(b, at), body = at + 8;\n const type = text(b, at + 4, 4);\n if (size === 1) {\n check(at + 16 <= b.length);\n size = u32be(b, at + 8) * 2 ** 32 + u32be(b, at + 12);\n body = at + 16;\n } else if (size === 0) size = end - (base + at);\n if (type === \"uuid\") body += 16;\n check(Number.isSafeInteger(size) && size >= body - at && base + at + size <= end);\n return { type, start: base + at, body: base + body, end: base + at + size };\n}\n\nfunction boxes(b: Uint8Array, start: number, end: number): Box[] {\n const found: Box[] = [];\n for (let at = start; at < end;) {\n check(at + 8 <= end);\n const box = header(b.subarray(0, end), at, end);\n found.push(box);\n at = box.end;\n }\n return found;\n}\n\n/** A box made `free` where it is: its size kept, everything after its size zeroed. */\nfunction empty(b: Uint8Array, box: Box): void {\n b.set([0x66, 0x72, 0x65, 0x65], box.start + 4);\n b.fill(0, box.start + (u32be(b, box.start) === 1 ? 16 : 8), box.end);\n}\n\n/**\n * Every metadata box in a container's children (and in theirs, for the containers below a track) emptied, every\n * free space's body zeroed, and every handler's name (an `hdlr`'s after its 24 bytes of fields: \"Core Media Video\",\n * an encoder's or an app's) zeroed in place, its type kept.\n */\nfunction emptyWithin(b: Uint8Array, start: number, end: number): void {\n for (const box of boxes(b, start, end)) {\n if (METADATA.has(box.type)) empty(b, box);\n else if (SPACE.has(box.type)) b.fill(0, box.body, box.end);\n else if (box.type === \"hdlr\") b.fill(0, Math.min(box.body + 24, box.end), box.end);\n else if (CONTAINERS.has(box.type)) emptyWithin(b, box.body, box.end);\n }\n}\n\n/**\n * A visual track's sample descriptions with the name of the compressor that made them zeroed (32 bytes at 42 of each\n * entry's body, MP4's `compressorname` and QuickTime's alike: an encoder's version, a camera's).\n */\nfunction zeroCompressorNames(b: Uint8Array, stbl: Box): void {\n const stsd = child(b, stbl, \"stsd\");\n check(!!stsd && stsd.body + 8 <= stsd.end);\n for (const entry of boxes(b, stsd.body + 8, stsd.end)) {\n check(entry.body + 74 <= entry.end);\n b.fill(0, entry.body + 42, entry.body + 74);\n }\n}\n\n/** A `mvhd`, `tkhd` or `mdhd` with its creation and modification times zeroed: 32 bits each in version 0, 64 in 1. */\nfunction zeroTimes(b: Uint8Array, box: Box): void {\n const version = b[box.body]!, bytes = version === 1 ? 16 : 8;\n check(version <= 1 && box.body + 4 + bytes <= box.end);\n b.fill(0, box.body + 4, box.body + 4 + bytes);\n}\n\nconst child = (b: Uint8Array, parent: Box | undefined, type: string): Box | undefined => {\n if (!parent) return undefined;\n const of = boxes(b, parent.body, parent.end).filter((box) => box.type === type);\n check(of.length <= 1);\n return of[0];\n};\n\n/** A sample table's chunks, from its `stco` or `co64`: how many, and where each starts in the file. */\nfunction chunkOffsets(b: Uint8Array, stbl: Box): { chunks: number; offsetOf: (i: number) => number } {\n const stco = child(b, stbl, \"stco\"), co64 = child(b, stbl, \"co64\");\n check(!!stco !== !!co64);\n const offsets = (stco ?? co64)!;\n check(offsets.body + 8 <= offsets.end);\n const chunks = u32be(b, offsets.body + 4);\n check(offsets.body + 8 + chunks * (co64 ? 8 : 4) <= offsets.end);\n const offsetOf = (i: number) => co64 ? u32be(b, co64.body + 8 + i * 8) * 2 ** 32 + u32be(b, co64.body + 12 + i * 8) : u32be(b, stco!.body + 8 + i * 4);\n return { chunks, offsetOf };\n}\n\n/** The byte ranges of a track's samples in the file, one per chunk, from its sample table. */\nfunction sampleRanges(b: Uint8Array, stbl: Box): [number, number][] {\n const stsz = child(b, stbl, \"stsz\"), stz2 = child(b, stbl, \"stz2\"), stsc = child(b, stbl, \"stsc\");\n check(!!stsc && !!stsz !== !!stz2);\n const need = (box: Box, at: number, bytes: number) => check(at + bytes <= box.end);\n\n // Each sample's size.\n const sizeTable = (stsz ?? stz2)!;\n need(sizeTable, sizeTable.body, 12);\n const count = u32be(b, sizeTable.body + 8);\n let sizeOf: (i: number) => number;\n /** Samples of one size: a chunk's length is counted, not added up a sample at a time. */\n let uniform = 0;\n if (stsz) {\n uniform = u32be(b, stsz.body + 4);\n if (!uniform) need(stsz, stsz.body + 12, count * 4);\n sizeOf = (i) => u32be(b, stsz.body + 12 + i * 4);\n } else {\n const field = b[stz2!.body + 7]!;\n check(field === 4 || field === 8 || field === 16);\n need(stz2!, stz2!.body + 12, Math.ceil((count * field) / 8));\n const at = stz2!.body + 12;\n sizeOf = field === 16 ? (i) => (b[at + i * 2]! << 8) | b[at + i * 2 + 1]!\n : field === 8 ? (i) => b[at + i]!\n : (i) => (i & 1 ? b[at + (i >> 1)]! & 15 : b[at + (i >> 1)]! >> 4);\n }\n\n // Each chunk's offset.\n const { chunks, offsetOf } = chunkOffsets(b, stbl);\n\n // How many samples each chunk holds.\n need(stsc, stsc.body, 8);\n const runs = u32be(b, stsc.body + 4);\n need(stsc, stsc.body + 8, runs * 12);\n const ranges: [number, number][] = [];\n let sample = 0;\n for (let run = 0; run < runs; run++) {\n const first = u32be(b, stsc.body + 8 + run * 12), perChunk = u32be(b, stsc.body + 12 + run * 12);\n const last = run + 1 < runs ? u32be(b, stsc.body + 8 + (run + 1) * 12) : chunks + 1;\n check(first >= 1 && last > first && last <= chunks + 1);\n for (let chunk = first; chunk < last; chunk++) {\n const start = offsetOf(chunk - 1);\n check(sample + perChunk <= count);\n let length = uniform * perChunk;\n if (!uniform) for (let i = 0; i < perChunk; i++) length += sizeOf(sample + i);\n sample += perChunk;\n check(Number.isSafeInteger(start) && length <= VIDEO_METADATA_LIMITS.maxBoxBytes);\n if (length) ranges.push([start, start + length]);\n }\n }\n check(sample === count);\n return ranges;\n}\n\n/** Each track's default sample size in fragments, from `moov`'s `mvex/trex` boxes, by track ID. */\nfunction defaultSampleSizes(moov: Uint8Array): Map<number, number> {\n const sizes = new Map<number, number>();\n const mvex = child(moov, header(moov, 0, moov.length), \"mvex\");\n for (const trex of mvex ? boxes(moov, mvex.body, mvex.end) : []) {\n if (trex.type !== \"trex\") continue;\n check(trex.body + 24 <= trex.end);\n sizes.set(u32be(moov, trex.body + 4), u32be(moov, trex.body + 16));\n }\n return sizes;\n}\n\n/**\n * The byte ranges of a fragment's samples in the file, one per track run (`trun`), from its `moof` read whole (`at` its\n * offset in the file): each run starts at its data offset from its track fragment's base (`tfhd`'s base data offset,\n * else the `moof`'s start for the first track fragment or one that says so, else where the previous one's data ended),\n * or where the previous run ended; its length is its samples' sizes, its own or `tfhd`'s or `trex`'s default. Each\n * with its track's ID.\n */\nfunction fragmentRanges(b: Uint8Array, at: number, sizes: Map<number, number>): [number, number, number][] {\n const ranges: [number, number, number][] = [];\n let previous = at;\n for (const traf of boxes(b, header(b, 0, b.length).body, b.length)) {\n if (traf.type !== \"traf\") continue;\n const tfhd = child(b, traf, \"tfhd\");\n check(!!tfhd && tfhd.body + 8 <= tfhd.end);\n const flags = u32be(b, tfhd.body) & 0xffffff;\n let field = tfhd.body + 8, base = flags & 0x20000 ? at : previous;\n if (flags & 0x1) {\n check(field + 8 <= tfhd.end);\n base = u32be(b, field) * 2 ** 32 + u32be(b, field + 4);\n field += 8;\n }\n if (flags & 0x2) field += 4;\n if (flags & 0x8) field += 4;\n const track = u32be(b, tfhd.body + 4);\n let size = sizes.get(track);\n if (flags & 0x10) {\n check(field + 4 <= tfhd.end);\n size = u32be(b, field);\n }\n let next = base;\n for (const trun of boxes(b, traf.body, traf.end)) {\n if (trun.type !== \"trun\") continue;\n check(trun.body + 8 <= trun.end);\n const runFlags = u32be(b, trun.body) & 0xffffff, count = u32be(b, trun.body + 4);\n let field = trun.body + 8;\n if (runFlags & 0x1) {\n check(field + 4 <= trun.end);\n next = base + (u32be(b, field) | 0);\n field += 4;\n }\n if (runFlags & 0x4) field += 4;\n const stride = [0x100, 0x200, 0x400, 0x800].filter((flag) => runFlags & flag).length * 4;\n check(field + count * stride <= trun.end);\n let length = 0;\n if (runFlags & 0x200) {\n const sizeAt = field + (runFlags & 0x100 ? 4 : 0);\n for (let i = 0; i < count; i++) length += u32be(b, sizeAt + i * stride);\n } else if (count) {\n check(size !== undefined);\n length = count * size;\n }\n check(Number.isSafeInteger(next) && Number.isSafeInteger(next + length));\n if (length) ranges.push([next, next + length, track]);\n next += length;\n }\n previous = next;\n }\n return ranges;\n}\n\n/** Whether every data reference of a track is this file (a self-contained `url ` or `alis`). */\nfunction selfContained(b: Uint8Array, minf: Box): boolean {\n const dref = child(b, child(b, minf, \"dinf\"), \"dref\");\n if (!dref) return false;\n return boxes(b, dref.body + 8, dref.end).every((entry) => entry.body + 4 <= entry.end && (b[entry.body + 3]! & 1) === 1);\n}\n\n/**\n * `moov` with its metadata boxes emptied and its headers' times zeroed, read whole: whether it has a video track, the\n * byte ranges of its metadata, timecode and caption tracks' samples (zeroed by the caller where they are), whether it\n * has a metadata or timecode track, every track's sample table, and the IDs of its caption tracks (their samples in\n * fragments zeroed too).\n */\nfunction stripMoov(b: Uint8Array): { video: boolean; fragmented: boolean; metadata: boolean; zeroed: [number, number][]; tables: Box[]; captions: Set<number> } {\n let video = false, fragmented = false, metadata = false;\n const zeroed: [number, number][] = [], tables: Box[] = [], captions = new Set<number>();\n for (const box of boxes(b, header(b, 0, b.length).body, b.length)) {\n if (METADATA.has(box.type)) { empty(b, box); continue; }\n check(MOOV_KEEPS.has(box.type));\n if (SPACE.has(box.type)) b.fill(0, box.body, box.end);\n if (box.type === \"mvhd\") zeroTimes(b, box);\n if (box.type === \"mvex\") { fragmented = true; emptyWithin(b, box.body, box.end); }\n if (box.type !== \"trak\") continue;\n let mdia: Box | undefined, tkhd: Box | undefined;\n for (const part of boxes(b, box.body, box.end)) {\n if (METADATA.has(part.type)) { empty(b, part); continue; }\n check(TRAK_KEEPS.has(part.type));\n if (part.type === \"tkhd\") { check(!tkhd); tkhd = part; zeroTimes(b, part); }\n if (part.type === \"mdia\") { check(!mdia); mdia = part; }\n }\n check(!!mdia);\n const hdlr = child(b, mdia, \"hdlr\"), minf = child(b, mdia, \"minf\"), mdhd = child(b, mdia, \"mdhd\");\n check(!!hdlr && !!minf && hdlr.body + 12 <= hdlr.end);\n if (mdhd) zeroTimes(b, mdhd);\n const handler = text(b, hdlr.body + 8, 4);\n const stbl = child(b, minf, \"stbl\");\n check(!!stbl);\n tables.push(stbl);\n if (handler === \"meta\") {\n check(selfContained(b, minf));\n // The track itself, not its table in `moov`: a fragmented movie's tables are empty, its samples in fragments.\n metadata = true;\n for (const range of sampleRanges(b, stbl)) zeroed.push(range);\n } else if (handler === \"tmcd\" && selfContained(b, minf)) {\n // A camera's timecode starts at the time of day it recorded: it starts at 0 instead.\n metadata = true;\n for (const range of sampleRanges(b, stbl)) zeroed.push(range);\n } else if (CAPTIONS.has(handler)) {\n check(selfContained(b, minf) && !!tkhd);\n // Its ID (after the times, 32 or 64 bits each), for its samples in fragments.\n const id = tkhd.body + 4 + (b[tkhd.body] === 1 ? 16 : 8);\n check(id + 4 <= tkhd.end);\n captions.add(u32be(b, id));\n for (const range of sampleRanges(b, stbl)) zeroed.push(range);\n } else check(HANDLERS.has(handler));\n if (handler === \"vide\") video = true;\n if (VISUAL.has(handler)) zeroCompressorNames(b, stbl);\n emptyWithin(b, box.body, box.end);\n }\n return { video, fragmented, metadata, zeroed, tables, captions };\n}\n\n/** A video as it is read: its size, and `length` of its bytes from `offset` (fewer only at its end). */\nexport interface VideoSource {\n size: number;\n read(offset: number, length: number): Promise<Uint8Array>;\n}\n\n/**\n * Whether `start` to `end` of the file meets one of `ranges` (in file order, apart): the first one that ends past\n * `start` is the only one that can, found by halves, so a fragment per range is not checked against every other.\n */\nfunction meets(ranges: [number, number][], start: number, end: number): boolean {\n let low = 0, high = ranges.length;\n while (low < high) {\n const middle = (low + high) >>> 1;\n if (ranges[middle]![1] > start) high = middle;\n else low = middle + 1;\n }\n return low < ranges.length && ranges[low]![0] < end;\n}\n\n/**\n * Whether `start` to `end` of the file is within one of `boxes` (in file order, apart): the first one that ends at or\n * past `end` is the only one that can hold it, found by halves, so a caption run per fragment is not checked against\n * every fragment's `mdat`.\n */\nfunction within(boxes: Box[], start: number, end: number): boolean {\n let low = 0, high = boxes.length;\n while (low < high) {\n const middle = (low + high) >>> 1;\n if (boxes[middle]!.end >= end) high = middle;\n else low = middle + 1;\n }\n return low < boxes.length && start >= boxes[low]!.body;\n}\n\n/**\n * `source` read a window at a time: a read that fits in `readAhead` bytes reads that many from where it starts, and\n * the reads after it within them (the next boxes' headers, a fragment's `moof`) are served from it, as copies (they\n * are changed in place). A Blob's read costs most for being one (in Chromium ~0.3 ms, and ~0.9 ms per MiB), so a\n * fragment costs one, not three.\n *\n * A walk that goes on from its window (an Ogg's pages, a live WebM's blocks: headers less than a window apart, through\n * the whole file) reads twice as much each time, up to `readAheadMax`, so it makes a few large reads, not one per\n * 64 KiB. One that jumps farther (over a fragment's samples) or back reads `readAhead` again.\n */\nexport function readingAhead(source: VideoSource): VideoSource {\n let start = 0, window: Uint8Array = new Uint8Array(0), ahead = VIDEO_METADATA_LIMITS.readAhead;\n return {\n size: source.size,\n async read(offset, length) {\n const end = start + window.length;\n if (offset < start || (offset + length > end && end < source.size)) {\n // Going on: forward, past less than a window (a page's or a block's body skipped).\n const goesOn = window.length > 0 && offset >= start && offset - end < ahead;\n ahead = goesOn ? Math.min(ahead * 2, VIDEO_METADATA_LIMITS.readAheadMax) : VIDEO_METADATA_LIMITS.readAhead;\n if (length > ahead) return source.read(offset, length);\n start = offset;\n window = await source.read(offset, ahead);\n }\n return window.slice(offset - start, offset - start + length);\n },\n };\n}\n\n/** A part of a video replaced as it is sent, `start` to `end` of the file: by `bytes`, or by zeros. */\nexport interface VideoPatch { start: number; end: number; bytes?: Uint8Array }\n\n/** A whole box's header in the file at `at`, read from it; undefined where none fits (bytes after the last box). */\nasync function headerAt(source: VideoSource, at: number): Promise<Box | undefined> {\n const head = await source.read(at, 16);\n try {\n return header(head, 0, source.size, at);\n } catch {\n return undefined;\n }\n}\n\n/** A box read whole, within the limit. */\nasync function whole(source: VideoSource, box: Box): Promise<Uint8Array> {\n check(box.end - box.start <= VIDEO_METADATA_LIMITS.maxBoxBytes);\n const bytes = await source.read(box.start, box.end - box.start);\n check(bytes.length === box.end - box.start);\n return bytes;\n}\n\n// AVI: RIFF chunks.\n\nconst u32le = (b: Uint8Array, at: number) => (b[at]! | (b[at + 1]! << 8) | (b[at + 2]! << 16) | (b[at + 3]! << 24)) >>> 0;\nconst JUNK = Uint8Array.from(\"JUNK\", (c) => c.charCodeAt(0));\n/** The chunks of an AVI's header its frames and sound are read with, kept; any other becomes `JUNK`. */\nconst AVI_HEADER_KEEPS = new Set([\"avih\", \"strh\", \"strf\", \"indx\", \"vprp\", \"dmlh\"]);\n/** The lists of an AVI's header looked into. */\nconst AVI_HEADER_LISTS = new Set([\"hdrl\", \"strl\", \"odml\"]);\n/** The streams whose chunks in `movi` are kept: pictures and sound. */\nconst AVI_STREAMS = new Set([\"vids\", \"auds\"]);\n/** A frame's or a piece of sound's chunk in `movi`: its stream's number, then what it is. */\nconst AVI_DATA = /^\\d\\d(dc|db|wb|pc)$/;\n\ninterface Chunk { id: string; type: string; start: number; body: number; end: number; next: number }\n\n/** An AVI: `RIFF` `AVI `, then any `RIFF` `AVIX` (an OpenDML one past 1 GiB). */\nconst isAvi = (head: Uint8Array) => head.length >= 12 && text(head, 0, 4) === \"RIFF\" && text(head, 8, 4) === \"AVI \";\n\n/** An AVI without what its header and `INFO` say, nor its text and data streams' chunks; the patches in file order. */\nasync function avi(source: VideoSource): Promise<VideoPatch[]> {\n const patches: VideoPatch[] = [], size = source.size;\n /** Whether each stream, in order, is kept (pictures or sound). */\n const streams: boolean[] = [];\n let chunks = 0;\n const chunkAt = async (at: number, end: number): Promise<Chunk> => {\n check(++chunks <= VIDEO_METADATA_LIMITS.maxChunks && at + 8 <= end);\n const head = await source.read(at, 12);\n check(head.length >= 8);\n const id = text(head, 0, 4), length = u32le(head, 4), list = id === \"LIST\" || id === \"RIFF\";\n check(!list || (length >= 4 && head.length >= 12));\n return { id, type: list ? text(head, 8, 4) : \"\", start: at, body: at + (list ? 12 : 8), end: at + 8 + length, next: at + 8 + length + (length & 1) };\n };\n /** Zeros from `start` to `end`; a chunk made `JUNK` (`junk`) has its id replaced too. */\n const zero = (start: number, end: number) => { if (end > start) patches.push({ start, end }); };\n const junk = (chunk: Chunk, end = chunk.end) => {\n if (chunk.id !== \"JUNK\") patches.push({ start: chunk.start, end: chunk.start + 4, bytes: JUNK });\n zero(chunk.start + 8, end);\n };\n const header = async (start: number, end: number): Promise<void> => {\n for (let at = start; at < end; ) {\n const chunk = await chunkAt(at, end);\n check(chunk.end <= end);\n if (chunk.id === \"LIST\" && AVI_HEADER_LISTS.has(chunk.type)) await header(chunk.body, chunk.end);\n else if (chunk.id === \"strh\") {\n check(chunk.end - chunk.body >= 4);\n streams.push(AVI_STREAMS.has(text(await source.read(chunk.body, 4), 0, 4)));\n } else if (chunk.id === \"JUNK\") zero(chunk.body, chunk.end);\n else if (!AVI_HEADER_KEEPS.has(chunk.id)) junk(chunk);\n at = Math.min(chunk.next, end);\n }\n };\n // A recording cut short (power lost in a dashcam): its lists and last chunk run past the end of the file.\n const movi = async (start: number, end: number): Promise<void> => {\n let at = start;\n for (; at + 8 <= end; ) {\n const chunk = await chunkAt(at, end), until = Math.min(chunk.end, end);\n if (chunk.id === \"LIST\" && chunk.type === \"rec \") await movi(chunk.body, until);\n else if (chunk.id.startsWith(\"ix\") || (AVI_DATA.test(chunk.id) && streams[Number(chunk.id.slice(0, 2))])) { /* kept */ }\n else if (/^\\d\\d/.test(chunk.id)) zero(chunk.body, until);\n else junk(chunk, until);\n at = Math.min(chunk.next, end);\n }\n zero(at, end);\n };\n let at = 0;\n for (let first = true; at + 12 <= size; first = false) {\n const head = await source.read(at, 12);\n if (text(head, 0, 4) !== \"RIFF\" || text(head, 8, 4) !== (first ? \"AVI \" : \"AVIX\")) break;\n const form = await chunkAt(at, size), end = Math.min(form.end, size);\n for (let inner = form.body; inner + 8 <= end; ) {\n const chunk = await chunkAt(inner, end);\n if (first && chunk.id === \"LIST\" && chunk.type === \"hdrl\") {\n check(!streams.length && chunk.end <= end);\n await header(chunk.body, chunk.end);\n } else if (chunk.id === \"LIST\" && chunk.type === \"movi\") {\n check(streams.length > 0);\n await movi(chunk.body, Math.min(chunk.end, end));\n } else if (chunk.id === \"JUNK\") zero(chunk.body, Math.min(chunk.end, end));\n else if (chunk.id !== \"idx1\") junk(chunk, Math.min(chunk.end, end));\n inner = Math.min(chunk.next, end);\n }\n at = Math.min(form.next, size);\n }\n // Bytes after the last RIFF (a recorder's trailer) are no part of the movie: zeros.\n zero(at, size);\n return patches;\n}\n\n/** An ASF (WMV, WMA): its header object's GUID. */\nconst ASF = [0x30, 0x26, 0xb2, 0x75, 0x8e, 0x66, 0xcf, 0x11, 0xa6, 0xd9, 0x00, 0xaa, 0x00, 0x62, 0xce, 0x6c];\nexport const isAsf = (head: Uint8Array) => head.length >= 16 && ASF.every((byte, i) => head[i] === byte);\n\n/** A video whose metadata is not removed here, so it is refused: an ASF, an FLV, an MPEG transport stream (`.ts`, `.m2ts`). */\nasync function refused(source: VideoSource, head: Uint8Array): Promise<boolean> {\n if (isAsf(head) || (head.length >= 4 && text(head, 0, 3) === \"FLV\" && head[3] === 1)) return true;\n // Three packets in a row, 188 bytes apart (192 in a camcorder's M2TS, after each one's time): a sync byte, and an\n // adaptation field control that is not the reserved 0.\n const packetAt = (b: Uint8Array, at: number) => b[at] === 0x47 && (b[at + 3]! & 0x30) !== 0;\n for (const [packet, offset] of [[188, 0], [192, 4]] as const) {\n if (!packetAt(head, offset) || source.size < offset + 2 * packet + 4) continue;\n const next = await source.read(offset + packet, packet + 4);\n if (packetAt(next, 0) && packetAt(next, packet)) return true;\n }\n return false;\n}\n\n/**\n * What a file is by its first box: a movie (`FIRST_BOXES`), a file of boxes that is one when it holds a `moov` (any\n * other box found at the top of a movie: a stream's segment holds none), or another file. An HEIF picture is\n * pictureMetadata.ts's.\n */\nfunction containerOf(head: Uint8Array, mime: string): \"movie\" | \"boxes\" | undefined {\n const first = head.length >= 8 ? text(head, 4, 4) : \"\";\n if (isStrippedPicture(head, mime)) return undefined;\n if (FIRST_BOXES.has(first)) return \"movie\";\n return TOP_KEEPS.has(first) || TOP_EMPTIED.has(first) ? \"boxes\" : undefined;\n}\n\n/**\n * `source` as it is sent: an MP4 or QuickTime video without its metadata, made of `source`'s own bytes but for the\n * boxes and samples zeroed; undefined when it goes as it is (not one of these videos, a file without a video track).\n * Throws `NO_VIDEO_METADATA` for a video whose metadata cannot be removed; an error reading `source` as it is.\n */\nexport async function withoutVideoMetadata(source: Blob, mime: string): Promise<Blob | undefined> {\n const patches = await videoMetadataPatches({ size: source.size, read: async (offset, length) => new Uint8Array(await source.slice(offset, offset + length).arrayBuffer()) }, mime);\n if (!patches) return undefined;\n const parts: BlobPart[] = [];\n let at = 0;\n for (let i = 0; i < patches.length;) {\n const patch = patches[i]!;\n // Parts replaced close together (a fragmented video's `moof`s, the frames between them) are read with the bytes\n // between them and go as one part: Chromium slices a File and builds a Blob a part at a time, so a part per\n // fragment held the page for seconds before the file was even in the chat.\n let last = i;\n while (last + 1 < patches.length && patches[last + 1]!.start - patches[last]!.end <= VIDEO_METADATA_LIMITS.joinGap\n && patches[last + 1]!.end - patch.start <= VIDEO_METADATA_LIMITS.joinedBytes) last++;\n if (patch.start > at) parts.push(source.slice(at, patch.start));\n if (last > i) {\n const joined = new Uint8Array(await source.slice(patch.start, patches[last]!.end).arrayBuffer());\n for (const { start, end, bytes } of patches.slice(i, last + 1)) {\n if (bytes) joined.set(bytes, start - patch.start);\n else joined.fill(0, start - patch.start, end - patch.start);\n }\n parts.push(joined as BlobPart);\n } else if (patch.bytes) parts.push(patch.bytes as BlobPart);\n else for (let left = patch.end - patch.start; left > 0; left -= ZEROS.size) parts.push(ZEROS.slice(0, Math.min(left, ZEROS.size)));\n at = patches[last]!.end;\n i = last + 1;\n }\n if (at < source.size) parts.push(source.slice(at));\n return new Blob(parts, { type: mime });\n}\n\n/**\n * What `withoutVideoMetadata` changes in a video read from `source` (one not held in a Blob: a file kept in storage):\n * the parts replaced, in order and apart, the rest of its bytes going as they are; undefined when it goes as it is.\n * Throws `NO_VIDEO_METADATA` as it does. With `audio`, a movie without a video track (an M4A) is stripped too.\n */\nexport async function videoMetadataPatches(file: VideoSource, mime: string, audio = false): Promise<VideoPatch[] | undefined> {\n const source = readingAhead(file);\n const head = await source.read(0, VIDEO_METADATA_LIMITS.headBytes);\n if (isAvi(head)) {\n const patches = await avi(source);\n return patches.length ? patches : undefined;\n }\n // A WMA typed as audio is audioMetadata.ts's to refuse.\n if (!(isAsf(head) && mime.toLowerCase().startsWith(\"audio/\"))) check(!await refused(source, head));\n const typed = STRIPPED_TYPES.has(mime.split(\";\")[0]!.trim().toLowerCase());\n const container = containerOf(head, mime);\n if (!container) {\n if (typed && !isStrippedPicture(head, mime)) throw new Error(NO_VIDEO_METADATA);\n return undefined;\n }\n\n /** What replaces the file's bytes, by where it starts: a box rewritten, or zeros (no `bytes`). */\n const patches: VideoPatch[] = [];\n\n // The top-level boxes, by their headers alone.\n const top: Box[] = [];\n /** What goes as zeros at the top, in file order: the boxes emptied, the space's bodies, and the bytes after the last box. */\n const dropped: [number, number][] = [];\n let trailer = false;\n for (let at = 0; at < source.size;) {\n check(top.length < VIDEO_METADATA_LIMITS.maxBoxes);\n const box = await headerAt(source, at);\n // Bytes after the last whole box (a recorder's zeros, a phone's trailer) are no box: they go as zeros.\n if (!box || (top.length && box.type === \"\\0\\0\\0\\0\")) {\n patches.push({ start: at, end: source.size });\n dropped.push([at, source.size]);\n // A box of zeros to the end was let through before as it is; bytes that are no box were not.\n trailer = !box || box.end !== source.size;\n break;\n }\n top.push(box);\n if (SPACE.has(box.type)) dropped.push([box.body, box.end]);\n else if (!TOP_KEEPS.has(box.type)) dropped.push([box.start, box.end]);\n at = box.end;\n }\n const moovs = top.filter((box) => box.type === \"moov\");\n // A stream's segment goes as it is; boxes that are not all known ones, or bytes that are no box, are refused.\n if (!moovs.length && container === \"boxes\" && !typed) {\n check(!trailer && top.every((box) => TOP_KEEPS.has(box.type) || TOP_EMPTIED.has(box.type)));\n return undefined;\n }\n check(moovs.length === 1);\n\n const moov = await whole(source, moovs[0]!);\n const { video, fragmented, metadata, zeroed, tables, captions } = stripMoov(moov);\n if (!video && !typed && !audio) return undefined;\n patches.push({ start: moovs[0]!.start, end: moovs[0]!.end, bytes: moov });\n\n // No sample is where zeros go.\n if (dropped.length) for (const stbl of tables) {\n const { chunks, offsetOf } = chunkOffsets(moov, stbl);\n for (let i = 0; i < chunks; i++) {\n const offset = offsetOf(i);\n check(!meets(dropped, offset, offset + 1));\n }\n }\n\n // A metadata or timecode track's samples in fragments are not looked for: such a video is refused.\n check(!fragmented || !metadata);\n const sizes = (dropped.length || captions.size) && fragmented ? defaultSampleSizes(moov) : undefined;\n for (const box of top) {\n if (box.type === \"moof\") {\n const moof = await whole(source, box);\n // No fragment's sample is where zeros go either; a caption track's samples are zeroed.\n if (dropped.length || captions.size) {\n for (const [start, end, track] of fragmentRanges(moof, box.start, sizes ?? new Map())) {\n check(!meets(dropped, start, end));\n if (captions.has(track)) zeroed.push([start, end]);\n }\n }\n emptyWithin(moof, box.body - box.start, moof.length);\n patches.push({ start: box.start, end: box.end, bytes: moof });\n } else if (SPACE.has(box.type)) {\n // Its header kept, its body zeros.\n if (box.body < box.end) patches.push({ start: box.body, end: box.end });\n } else if (!TOP_KEEPS.has(box.type)) {\n // Its header made `free`, its body zeros.\n const head = await source.read(box.start, box.body - box.start);\n empty(head, { type: box.type, start: 0, body: head.length, end: head.length });\n patches.push({ start: box.start, end: box.body, bytes: head }, { start: box.body, end: box.end });\n }\n }\n\n // The metadata, timecode and caption samples, each within a `mdat`: zeros where they were, ranges that touch made one.\n const mdats = top.filter((box) => box.type === \"mdat\");\n const merged: [number, number][] = [];\n for (const [start, end] of zeroed.sort((a, b) => a[0] - b[0])) {\n check(within(mdats, start, end));\n const last = merged[merged.length - 1];\n if (last && start <= last[1]) last[1] = Math.max(last[1], end);\n else merged.push([start, end]);\n }\n for (const [start, end] of merged) patches.push({ start, end });\n\n let at = 0;\n for (const patch of patches.sort((a, b) => a.start - b.start)) {\n check(patch.start >= at);\n at = patch.end;\n }\n return patches;\n}\n","/**\n * What an audio file leaves with. A recording made in another app, or a song a tagger went through, says more than its\n * sound: a title or a file name that is where it was recorded (a phone's recorder names it after the place), a comment,\n * a location tag, a picture, the date. The sender removes them before the file is stored and its digest computed, as\n * pictures' and videos' are (pictureMetadata.ts, videoMetadata.ts), without decoding or re-encoding a sample, and the\n * file keeps its size, so no offset in it moves and it plays as it did:\n *\n * - MP4 audio (M4A, a voice note recorded in MP4): videoMetadata.ts's box walk, its `udta` and `meta` emptied.\n * - MP3 and AAC: an ID3v2 tag at the start becomes an empty one (its frames zeros: padding), one at the end (with its\n * footer), an APEv2 tag's items, a Lyrics3v2 tag and an ID3v1 tag's fields become zeros. One typed as MP3 or AAC\n * whose first bytes are neither (junk before its first frame) still has the tags at its end emptied.\n * - FLAC: every metadata block but its stream info and seek table (a Vorbis comment, a picture, a cue sheet, an\n * application's) becomes padding, zeroed.\n * - Ogg Opus, Vorbis, Speex and Theora: the comment header keeps its vendor (the encoder's name) and has no comment,\n * the bytes after it zeros. FLAC in Ogg: its metadata blocks as a FLAC's. Each page changed has its checksum made again.\n * - WAV (RIFF, RF64 or BW64): every chunk but its format, data and the ones of the sound itself (`fact`, `cue `,\n * `smpl`, `inst`, an RF64's `ds64`) becomes `JUNK`, zeroed (an INFO list, an `id3 ` chunk, a broadcast `bext` with\n * its date and originator, iXML, XMP).\n * - AIFF and AIFF-C: every chunk but its sound's (`COMM`, `SSND`, `FVER`, `MARK`, `INST`, `AESD`, `chan`) becomes\n * `JUNK`, zeroed (NAME, AUTH, ANNO, `(c) `, COMT, an `ID3 ` chunk, an app's `APPL`).\n * - CAF: every chunk but its sound's (`desc`, `data`, `pakt`, `kuki`, `chan`, `peak`, `ovvw`) becomes `free`, zeroed\n * (its `info` strings, a marker's names in `strg`, `edct` comments, `uuid` chunks).\n * - WavPack: its APEv2 and ID3v1 tags at the end as an MP3's, and the source file's header and trailer each block may\n * keep for a lossless restore (a WAV's INFO list, an AIFF's NAME) made a sub-block that says nothing, zeroed.\n * - TTA, Monkey's Audio, Musepack (SV7 and SV8) and OptimFROG: their tags at the end (and an ID3v2 before them) as an MP3's.\n * - DSF: the ID3v2 tag its header points at emptied as an MP3's; any other byte after its sound, zeros.\n * - DSDIFF: every chunk but its sound's (`FVER`, `PROP`, `DSD `, `DST `, `DSTI`) becomes `JUNK`, zeroed (COMT, DIIN\n * with its artist and title, MANF, an `ID3 ` chunk), and any byte after its form.\n * - MIDI: the text of its meta events (a copyright, a track's name, lyrics, markers) and a sequencer's own data become\n * zeros, their lengths kept; its notes and SysEx as they are.\n * - Sun AU: its annotation, zeros.\n * - WebM and Matroska, audio or video: `Tags`, `Attachments`, `Chapters`, the title, the date, the file names and each\n * track's name become `Void` elements (and the SeekHead's entries for them); the muxer's and the writing app's names\n * are zeroed. A Vorbis, Theora or FLAC track's CodecPrivate (its Ogg headers or its FLAC metadata blocks) has its\n * comments emptied as an Ogg's or a FLAC's. Clusters, cues and other track settings are kept as they are.\n *\n * Fail-closed: a file that is one of these by its bytes and whose tags cannot be removed (truncated, malformed) is\n * refused with `NO_AUDIO_METADATA`, never sent as it was. So is a WMA (ASF): its title, place and date are not removed\n * here. Any other file goes as it is (other audio formats too).\n */\nimport { baseMime } from \"./voice\";\nimport { NO_VIDEO_METADATA, isAsf, readingAhead, videoMetadataPatches, type VideoPatch, type VideoSource } from \"./videoMetadata\";\n\nexport const AUDIO_METADATA_LIMITS = {\n /** The largest header, element or tag read whole (an Ogg comment header with a picture in it): past this the file is refused. */\n maxReadBytes: 64 * 1024 * 1024,\n /** The most pages, chunks, blocks or elements walked. */\n maxParts: 1_000_000,\n /** Bytes read first to tell an audio file from another file. */\n headBytes: 64,\n} as const;\n\n/** Why an audio file is refused: its tags could not be removed, so it does not go at all. */\nexport const NO_AUDIO_METADATA = \"This audio cannot be sent: Ghostly could not remove the details saved in it, like where it was recorded\";\n\n/** 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. */\nconst ZEROS = new Blob([new Uint8Array(1024 * 1024)]);\n\nconst text = (b: Uint8Array, at: number, length: number) => String.fromCharCode(...b.subarray(at, at + length));\nconst u32le = (b: Uint8Array, at: number) => (b[at]! | (b[at + 1]! << 8) | (b[at + 2]! << 16) | (b[at + 3]! << 24)) >>> 0;\nconst u32be = (b: Uint8Array, at: number) => ((b[at]! << 24) >>> 0) + (b[at + 1]! << 16) + (b[at + 2]! << 8) + b[at + 3]!;\nconst syncsafe = (b: Uint8Array, at: number) => (b[at]! << 21) | (b[at + 1]! << 14) | (b[at + 2]! << 7) | b[at + 3]!;\nconst latin = (s: string) => Uint8Array.from(s, (c) => c.charCodeAt(0));\n\n/** Refuses the file where its bytes are not what this expects. */\nfunction check(ok: boolean): asserts ok {\n if (!ok) throw new Error(NO_AUDIO_METADATA);\n}\n\n/** The file read as patches are made: `length` of its bytes from `offset`, all of them or refused. */\ntype Read = (offset: number, length: number) => Promise<Uint8Array>;\n\nfunction exactly(source: VideoSource): Read {\n return async (offset, length) => {\n check(offset >= 0 && length >= 0 && length <= AUDIO_METADATA_LIMITS.maxReadBytes && offset + length <= source.size);\n const bytes = await source.read(offset, length);\n check(bytes.length === length);\n return bytes;\n };\n}\n\n/** Counts the parts walked, so a file of millions of tiny ones is refused rather than walked forever. */\nfunction counter(): () => void {\n let parts = 0;\n return () => check(++parts <= AUDIO_METADATA_LIMITS.maxParts);\n}\n\n// ID3, APE, Lyrics3: MP3's and AAC's tags.\n\n/** An ID3v2 header at `at` of `b`: its version 2 to 4 and its size four 7-bit bytes, or none. */\nconst isId3 = (b: Uint8Array, at = 0) => b.length >= at + 10 && text(b, at, 3) === \"ID3\" && b[at + 3]! >= 2 && b[at + 3]! <= 4 && b[at + 4] !== 0xff\n && [6, 7, 8, 9].every((i) => b[at + i]! < 0x80);\n\n/**\n * The ID3v2 tag whose header is `head`, at `at`: made an empty one where it is, its frames (and an extended header)\n * zeros, which is its padding, its flags but the footer's cleared. Returns where it ends.\n */\nasync function emptyId3(read: Read, size: number, at: number, head: Uint8Array, patches: VideoPatch[]): Promise<number> {\n const body = syncsafe(head, 6), footer = head[3] === 4 && head[5]! & 0x10 ? 10 : 0, end = at + 10 + body + footer;\n check(end <= size);\n const flags = Uint8Array.of(footer ? 0x10 : 0);\n patches.push({ start: at + 5, end: at + 6, bytes: flags });\n if (body) patches.push({ start: at + 10, end: at + 10 + body });\n if (footer) {\n check(text(await read(at + 10 + body, 3), 0, 3) === \"3DI\");\n patches.push({ start: at + 10 + body + 5, end: at + 10 + body + 6, bytes: flags });\n }\n return end;\n}\n\n/**\n * The tags at the end of an MP3 or AAC file (after `start`): an ID3v1 (and its extended part), then any of an APEv2\n * tag, a Lyrics3v2 tag and an ID3v2 tag with a footer, in any order. Each found is emptied where it is.\n */\nasync function trailingTags(read: Read, size: number, start: number, patches: VideoPatch[]): Promise<void> {\n let end = size;\n if (end - 128 >= start && text(await read(end - 128, 3), 0, 3) === \"TAG\") {\n // Its fields zeros, its genre none.\n patches.push({ start: end - 125, end: end - 1 }, { start: end - 1, end, bytes: Uint8Array.of(0xff) });\n end -= 128;\n if (end - 227 >= start && text(await read(end - 227, 4), 0, 4) === \"TAG+\") {\n patches.push({ start: end - 223, end });\n end -= 227;\n }\n }\n const count = counter();\n for (;;) {\n count();\n if (end - 32 >= start) {\n const footer = await read(end - 32, 32);\n if (text(footer, 0, 8) === \"APETAGEX\") {\n // Its size counts its items and footer; a header before them says so in its flags.\n const length = u32le(footer, 12), header = footer[23]! & 0x80 ? 32 : 0, tagStart = end - length - header;\n check(length >= 32 && tagStart >= start);\n if (header) {\n check(text(await read(tagStart, 8), 0, 8) === \"APETAGEX\");\n patches.push({ start: tagStart + 16, end: tagStart + 20 });\n }\n if (length > 32) patches.push({ start: tagStart + header, end: end - 32 });\n patches.push({ start: end - 16, end: end - 12 });\n end = tagStart;\n continue;\n }\n }\n if (end - 15 >= start) {\n const footer = await read(end - 15, 15);\n if (text(footer, 6, 9) === \"LYRICS200\") {\n const length = /^\\d{6}$/.test(text(footer, 0, 6)) ? Number(text(footer, 0, 6)) : -1, tagStart = end - 15 - length;\n check(length >= 11 && tagStart >= start && text(await read(tagStart, 11), 0, 11) === \"LYRICSBEGIN\");\n if (length > 11) patches.push({ start: tagStart + 11, end: end - 15 });\n end = tagStart;\n continue;\n }\n }\n if (end - 10 >= start) {\n const footer = await read(end - 10, 10);\n if (text(footer, 0, 3) === \"3DI\") {\n check([6, 7, 8, 9].every((i) => footer[i]! < 0x80));\n const tagStart = end - 20 - syncsafe(footer, 6);\n check(tagStart >= start);\n const head = await read(tagStart, 10);\n check(isId3(head));\n check(await emptyId3(read, size, tagStart, head, patches) === end);\n end = tagStart;\n continue;\n }\n }\n return;\n }\n}\n\n/** The types an MP3 or AAC file is sent as: one whose first bytes are no frame still has its tags at the end read. */\nconst MPEG_AUDIO = new Set([\"audio/mpeg\", \"audio/mp3\", \"audio/mpeg3\", \"audio/x-mpeg\", \"audio/x-mp3\", \"audio/aac\", \"audio/x-aac\", \"audio/aacp\"]);\n\n/** An MPEG audio frame's or an ADTS header's first bytes: 11 bits set, a version and a layer that are some. */\nconst isFrame = (b: Uint8Array, at: number) => b.length >= at + 2 && b[at] === 0xff && (b[at + 1]! & 0xe0) === 0xe0 && (b[at + 1]! & 0x18) !== 0x08;\n\n// FLAC.\n\nconst FLAC_KEEPS = new Set([0 /* STREAMINFO */, 3 /* SEEKTABLE */]);\n\n/** A FLAC's metadata blocks from `at` (its `fLaC`): all but its stream info and seek table become padding, zeroed. */\nasync function flac(read: Read, size: number, at: number, patches: VideoPatch[]): Promise<number> {\n const count = counter();\n for (at += 4; ;) {\n count();\n const head = await read(at, 4);\n const last = head[0]! & 0x80, type = head[0]! & 0x7f, end = at + 4 + ((head[1]! << 16) | (head[2]! << 8) | head[3]!);\n check(type !== 127 && end <= size);\n if (!FLAC_KEEPS.has(type)) {\n if (type !== 1) patches.push({ start: at, end: at + 1, bytes: Uint8Array.of(last | 1) });\n if (end > at + 4) patches.push({ start: at + 4, end });\n }\n at = end;\n if (last) return at;\n }\n}\n\n// Ogg.\n\nconst OGG_CRC = (() => {\n const table = new Uint32Array(256);\n for (let i = 0; i < 256; i++) {\n let crc = i << 24;\n for (let bit = 0; bit < 8; bit++) crc = crc & 0x80000000 ? (crc << 1) ^ 0x04c11db7 : crc << 1;\n table[i] = crc >>> 0;\n }\n return table;\n})();\n\n/** Ogg's page checksum, over the page with its checksum's four bytes zeroed. */\nfunction oggCrc(page: Uint8Array): number {\n let crc = 0;\n for (let i = 0; i < page.length; i++) crc = ((crc << 8) ^ OGG_CRC[((crc >>> 24) ^ (i >= 22 && i < 26 ? 0 : page[i]!)) & 0xff]!) >>> 0;\n return crc;\n}\n\n/**\n * A comment header with no comment: its magic and vendor kept, its count 0 (and Vorbis's framing bit set), the rest\n * zeros: padding after the comments, which Opus says may be there and Vorbis's, Speex's and Theora's readers do not read.\n */\nfunction noComments(packet: Uint8Array, comments: string, framing: boolean): Uint8Array {\n const magic = comments.length;\n check(text(packet, 0, magic) === comments && packet.length >= magic + 4);\n const count = magic + 4 + u32le(packet, magic);\n check(count + 4 + (framing ? 1 : 0) <= packet.length);\n const out = new Uint8Array(packet.length);\n out.set(packet.subarray(0, count));\n if (framing) out[count + 4] = 1;\n return out;\n}\n\n/** A FLAC metadata block that is a whole packet (FLAC in Ogg): kept, or made padding as `flac` makes it. */\nfunction noFlacBlock(packet: Uint8Array): Uint8Array {\n check(packet.length >= 4 && packet.length === 4 + ((packet[1]! << 16) | (packet[2]! << 8) | packet[3]!) && (packet[0]! & 0x7f) !== 127);\n const type = packet[0]! & 0x7f;\n if (FLAC_KEEPS.has(type)) return packet;\n const out = new Uint8Array(packet.length);\n out[0] = type === 1 ? packet[0]! : (packet[0]! & 0x80) | 1;\n return out;\n}\n\n/**\n * A codec's headers after its first packet, known by that packet's first bytes: `tagged` says whether one that may\n * hold tags follows (its first packet given, then each header after it), `empty` makes one without them, its length\n * kept.\n */\ninterface OggCodec { head: string; tagged: (packet: Uint8Array, index: number) => boolean; empty: (packet: Uint8Array) => Uint8Array }\n/** A codec whose second packet is its comment header: its magic, and whether a framing bit follows its comments (Vorbis). */\nconst commentHeader = (head: string, comments: string, framing: boolean): OggCodec => ({ head, tagged: (_, index) => index === 0, empty: (packet) => noComments(packet, comments, framing) });\n\nconst OGG_CODECS: OggCodec[] = [\n commentHeader(\"OpusHead\", \"OpusTags\", false),\n commentHeader(\"\\x01vorbis\", \"\\x03vorbis\", true),\n commentHeader(\"Speex \", \"\", false),\n commentHeader(\"\\x80theora\", \"\\x81theora\", false),\n // FLAC: its first packet holds the stream info's block, each header after it one metadata block, the last flagged.\n {\n head: \"\\x7fFLAC\",\n tagged: (packet, index) => {\n if (index) return !(packet[0]! & 0x80);\n check(packet.length >= 17 && text(packet, 9, 4) === \"fLaC\");\n return !(packet[13]! & 0x80);\n },\n empty: noFlacBlock,\n },\n];\n\n/**\n * An Ogg file's pages walked: each logical stream's comment header (a chained file has one per link) made one with no\n * comment where it is, across the pages it spans, and those pages' checksums made again.\n */\nasync function ogg(read: Read, size: number, patches: VideoPatch[]): Promise<void> {\n /**\n * A logical stream: its packets so far, the parts of the one being read (with the page each is on), its codec (null:\n * one not known), and whether a header that may hold tags is still to come.\n */\n interface Stream { packet: number; ranges: [number, number, number][]; codec?: OggCodec | null; tagged: boolean }\n const streams = new Map<number, Stream>();\n /** The bytes put in the pages changed, by where each page starts: by where they go in the file. */\n const pages = new Map<number, [number, Uint8Array][]>();\n const packetOf = async (ranges: [number, number, number][]) => {\n const length = ranges.reduce((sum, [start, end]) => sum + end - start, 0);\n check(length <= AUDIO_METADATA_LIMITS.maxReadBytes);\n const packet = new Uint8Array(length);\n let at = 0;\n for (const [start, end] of ranges) { packet.set(await read(start, end - start), at); at += end - start; }\n return packet;\n };\n const count = counter();\n for (let at = 0; at < size;) {\n count();\n const head = await read(at, 27);\n check(text(head, 0, 4) === \"OggS\" && head[4] === 0);\n const lacing = await read(at + 27, head[26]!);\n const end = at + 27 + lacing.length + lacing.reduce((sum, l) => sum + l, 0);\n check(end <= size);\n const serial = u32le(head, 14);\n if (head[5]! & 2) streams.set(serial, { packet: 0, ranges: [], tagged: true });\n const stream = streams.get(serial);\n check(!!stream);\n let offset = at + 27 + lacing.length;\n for (const length of lacing) {\n if (stream.tagged) stream.ranges.push([offset, offset + length, at]);\n offset += length;\n if (length === 255) continue;\n // A packet ends.\n if (stream.packet === 0) {\n const first = await packetOf(stream.ranges);\n stream.codec = OGG_CODECS.find((codec) => text(first, 0, codec.head.length) === codec.head) ?? null;\n stream.tagged = !!stream.codec?.tagged(first, 0);\n } else if (stream.tagged && stream.codec) {\n const packet = await packetOf(stream.ranges), emptied = stream.codec.empty(packet);\n stream.tagged = stream.codec.tagged(packet, stream.packet);\n let from = 0;\n for (const [start, until, page] of stream.ranges) {\n if (!pages.has(page)) pages.set(page, []);\n pages.get(page)!.push([start, emptied.subarray(from, from + until - start)]);\n from += until - start;\n }\n }\n stream.packet++;\n stream.ranges = [];\n }\n at = end;\n }\n // A stream cut before its headers with tags ended would go with them.\n for (const stream of streams.values()) check(!stream.tagged);\n for (const [start, changes] of pages) {\n const head = await read(start, 27), lacing = await read(start + 27, head[26]!);\n const end = start + 27 + lacing.length + lacing.reduce((sum, l) => sum + l, 0);\n const page = (await read(start, end - start)).slice();\n for (const [where, bytes] of changes) page.set(bytes, where - start);\n const crc = oggCrc(page);\n page.set([crc & 0xff, (crc >>> 8) & 0xff, (crc >>> 16) & 0xff, crc >>> 24], 22);\n patches.push({ start, end, bytes: page });\n }\n}\n\n// WAV.\n\n/** The chunks a WAV's sound is made of, kept; any other becomes `JUNK`. */\nconst WAV_KEEPS = new Set([\"fmt \", \"data\", \"fact\", \"cue \", \"smpl\", \"inst\"]);\nconst WAV_SPACE = new Set([\"JUNK\", \"junk\", \"PAD \", \"FLLR\"]);\n\n/** A WAV's chunks from its `WAVE`; an RF64 or BW64 one (`rf64`) has its `ds64` first, which says `data`'s size when its own is all ones. */\nasync function wav(read: Read, size: number, rf64: boolean, patches: VideoPatch[]): Promise<void> {\n let dataSize: number | undefined;\n if (rf64) {\n const ds64 = await read(12, 8 + 16);\n check(text(ds64, 0, 4) === \"ds64\" && u32le(ds64, 4) >= 28);\n dataSize = u32le(ds64, 16) + u32le(ds64, 20) * 2 ** 32;\n }\n const count = counter();\n for (let at = 12; at + 8 <= size;) {\n count();\n const head = await read(at, 8);\n const id = text(head, 0, 4), length = id === \"data\" && dataSize !== undefined && u32le(head, 4) === 0xffffffff ? dataSize : u32le(head, 4);\n let end = at + 8 + length + (length % 2);\n // Sound that runs to the end: a recorder's that never wrote its size (0, or all ones), or one cut short.\n if (id === \"data\") end = length ? Math.min(end, size) : size;\n else check(at + 8 + length <= size);\n if (!WAV_KEEPS.has(id) && !(rf64 && at === 12)) {\n if (!WAV_SPACE.has(id)) patches.push({ start: at, end: at + 4, bytes: latin(\"JUNK\") });\n if (length) patches.push({ start: at + 8, end: at + 8 + length });\n }\n at = Math.min(end, size);\n }\n}\n\n// AIFF, CAF, WavPack, Sun AU.\n\n/** The chunks an AIFF's or AIFF-C's sound is made of, kept; any other becomes `JUNK`. */\nconst AIFF_KEEPS = new Set([\"COMM\", \"SSND\", \"FVER\", \"MARK\", \"INST\", \"AESD\", \"chan\"]);\n\n/** An AIFF's chunks from its form type: big-endian sizes, each padded to an even length. */\nasync function aiff(read: Read, size: number, patches: VideoPatch[]): Promise<void> {\n const count = counter();\n for (let at = 12; at + 8 <= size;) {\n count();\n const head = await read(at, 8);\n const id = text(head, 0, 4), length = u32be(head, 4);\n let end = at + 8 + length + (length % 2);\n // Sound that runs to the end: a recorder's that never wrote its size, or one cut short.\n if (id === \"SSND\") end = length ? Math.min(end, size) : size;\n else check(at + 8 + length <= size);\n if (!AIFF_KEEPS.has(id)) {\n if (id !== \"JUNK\") patches.push({ start: at, end: at + 4, bytes: latin(\"JUNK\") });\n if (length) patches.push({ start: at + 8, end: at + 8 + length });\n }\n at = Math.min(end, size);\n }\n}\n\n/** The chunks a CAF's sound is made of, kept; any other becomes `free`. */\nconst CAF_KEEPS = new Set([\"desc\", \"data\", \"pakt\", \"kuki\", \"chan\", \"peak\", \"ovvw\"]);\n\n/** A CAF's chunks after its 8-byte header: big-endian 64-bit sizes, `data`'s -1 when it runs to the end. */\nasync function caf(read: Read, size: number, patches: VideoPatch[]): Promise<void> {\n const count = counter();\n for (let at = 8; at + 12 <= size;) {\n count();\n const head = await read(at, 12);\n const id = text(head, 0, 4), high = u32be(head, 4), length = high * 2 ** 32 + u32be(head, 8);\n const toEnd = id === \"data\" && high === 0xffffffff && u32be(head, 8) === 0xffffffff;\n check(toEnd || (Number.isSafeInteger(length) && at + 12 + length <= size));\n const end = toEnd ? size : at + 12 + length;\n if (!CAF_KEEPS.has(id)) {\n if (id !== \"free\") patches.push({ start: at, end: at + 4, bytes: latin(\"free\") });\n if (end > at + 12) patches.push({ start: at + 12, end });\n }\n at = end;\n }\n}\n\n/** A WavPack sub-block's own id (its flags apart): the source file's header and trailer, a WAV's or another's. */\nconst WAVPACK_SOURCE = new Set([0x21 /* RIFF header */, 0x22 /* RIFF trailer */, 0x23 /* other header */, 0x24 /* other trailer */]);\n\n/** A WavPack's blocks from `at`, their source file's header and trailer emptied; returns where they end (its tags). */\nasync function wavpack(read: Read, size: number, at: number, patches: VideoPatch[]): Promise<number> {\n const count = counter();\n while (at + 32 <= size && text(await read(at, 4), 0, 4) === \"wvpk\") {\n count();\n const end = at + 8 + u32le(await read(at + 4, 4), 0);\n check(end >= at + 32 && end <= size);\n for (let sub = at + 32; sub < end;) {\n count();\n const head = await read(sub, Math.min(4, end - sub));\n // Its size in 16-bit words: one byte, or three for a large one.\n const large = (head[0]! & 0x80) !== 0, body = sub + (large ? 4 : 2);\n check(body <= end);\n const length = (large ? head[1]! | (head[2]! << 8) | (head[3]! << 16) : head[1]!) * 2;\n check(body + length <= end);\n // An optional sub-block of no id (its flags kept), its body zeros: a decoder skips it, and makes a header of its own.\n if (WAVPACK_SOURCE.has(head[0]! & 0x3f)) {\n patches.push({ start: sub, end: sub + 1, bytes: Uint8Array.of((head[0]! & 0xc0) | 0x20) });\n if (length) patches.push({ start: body, end: body + length });\n }\n sub = body + length;\n }\n at = end;\n }\n return at;\n}\n\n/** A 64-bit size at `at` of `b`, little- or big-endian: one past what a file can hold is refused. */\nfunction u64(b: Uint8Array, at: number, little: boolean): number {\n const n = little ? u32le(b, at) + u32le(b, at + 4) * 2 ** 32 : u32be(b, at) * 2 ** 32 + u32be(b, at + 4);\n check(Number.isSafeInteger(n));\n return n;\n}\n\n/**\n * A DSF: its `DSD `, `fmt ` and `data` chunks kept, the ID3v2 tag its header's metadata pointer names emptied where it\n * is, and any byte after its data that is not that tag zeroed.\n */\nasync function dsf(read: Read, size: number, patches: VideoPatch[]): Promise<void> {\n const head = await read(0, 28);\n check(u64(head, 4, true) === 28);\n const fmt = await read(28, 12);\n check(text(fmt, 0, 4) === \"fmt \");\n const dataAt = 28 + u64(fmt, 4, true);\n const data = await read(dataAt, 12);\n check(text(data, 0, 4) === \"data\");\n let end = dataAt + u64(data, 4, true);\n check(end <= size);\n const pointer = u64(head, 20, true);\n if (pointer) {\n check(pointer >= end);\n const tag = await read(pointer, 10);\n check(isId3(tag));\n if (pointer > end) patches.push({ start: end, end: pointer });\n end = await emptyId3(read, size, pointer, tag, patches);\n }\n if (end < size) patches.push({ start: end, end: size });\n}\n\n/** The chunks a DSDIFF's sound is made of, kept; any other (COMT, DIIN with its artist and title, MANF, an `ID3 `) becomes `JUNK`, zeroed. */\nconst DSDIFF_KEEPS = new Set([\"FVER\", \"PROP\", \"DSD \", \"DST \", \"DSTI\"]);\n\n/** A DSDIFF's chunks within its `FRM8`: big-endian 64-bit sizes, each padded to an even length; any byte after the form zeroed. */\nasync function dsdiff(read: Read, size: number, patches: VideoPatch[]): Promise<void> {\n const formEnd = 12 + u64(await read(4, 8), 0, false);\n check(formEnd >= 16 && formEnd <= size);\n const count = counter();\n for (let at = 16; at < formEnd;) {\n count();\n const head = await read(at, 12);\n const id = text(head, 0, 4), length = u64(head, 4, false), end = at + 12 + length;\n check(end <= formEnd);\n if (!DSDIFF_KEEPS.has(id)) {\n patches.push({ start: at, end: at + 4, bytes: latin(\"JUNK\") });\n if (length) patches.push({ start: at + 12, end });\n }\n at = Math.min(end + (length % 2), formEnd);\n }\n if (formEnd < size) patches.push({ start: formEnd, end: size });\n}\n\n/** The meta events whose data is text (a text, a copyright, a track's or an instrument's name, a lyric, a marker, a cue point, a program's or a device's name) or a sequencer's own. */\nconst MIDI_TEXT = new Set([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x7f]);\n\n/**\n * A Standard MIDI File's chunks: each track's events walked, the data of its text meta events zeroed (their lengths\n * kept, so every delta time and event stays where it was), any byte after its end of track zeroed; a chunk that is\n * neither a header nor a track zeroed.\n */\nasync function midi(read: Read, size: number, patches: VideoPatch[]): Promise<void> {\n const count = counter();\n let at = 0;\n for (; at + 8 <= size;) {\n count();\n const head = await read(at, 8);\n const id = text(head, 0, 4), start = at + 8, end = start + u32be(head, 4);\n check(end <= size);\n if (id === \"MTrk\") {\n const b = await read(start, end - start);\n let i = 0, running = 0;\n const varlen = () => {\n let value = 0;\n for (let n = 0; ; n++) {\n check(i < b.length && n < 4);\n const byte = b[i++]!;\n value = value * 128 + (byte & 0x7f);\n if (!(byte & 0x80)) return value;\n }\n };\n while (i < b.length) {\n count();\n varlen();\n check(i < b.length);\n const status = b[i]!;\n if (status === 0xff || status === 0xf0 || status === 0xf7) {\n // A meta event or a SysEx: its length says where it ends; either ends running status.\n const type = status === 0xff ? b[++i] : undefined;\n i++;\n const length = varlen();\n check(i + length <= b.length);\n if (type !== undefined && MIDI_TEXT.has(type) && length) patches.push({ start: start + i, end: start + i + length });\n i += length;\n running = 0;\n if (type === 0x2f) {\n if (i < b.length) patches.push({ start: start + i, end });\n break;\n }\n } else {\n // A channel event, its status byte left out when it is the one before (running status).\n if (status & 0x80) { running = status; i++; }\n check(running >= 0x80 && running < 0xf0);\n i += (running & 0xe0) === 0xc0 ? 1 : 2;\n check(i <= b.length);\n }\n }\n } else if (id !== \"MThd\" && end > start) patches.push({ start, end });\n at = end;\n }\n if (at < size) patches.push({ start: at, end: size });\n}\n\n/** A Sun AU's annotation: from its 24-byte header to its sound. */\nasync function au(read: Read, size: number, patches: VideoPatch[]): Promise<void> {\n const offset = u32be(await read(4, 4), 0);\n check(offset >= 24 && offset <= size);\n if (offset > 24) patches.push({ start: 24, end: offset });\n}\n\n// WebM and Matroska.\n\nconst EBML_HEADER = 0x1a45dfa3, SEGMENT = 0x18538067, CLUSTER = 0x1f43b675, VOID = 0xec, CRC32 = 0xbf;\nconst SEEK_HEAD = 0x114d9b74, INFO = 0x1549a966, TRACKS = 0x1654ae6b, CUES = 0x1c53bb6b;\n/** What a segment's sound and pictures are made of, kept; any other top-level element (Tags, Attachments, Chapters) becomes Void. */\nconst SEGMENT_KEEPS = new Set([SEEK_HEAD, INFO, TRACKS, CLUSTER, CUES]);\n/** What a cluster holds: one of unknown size ends where an element that is none of these starts. */\nconst CLUSTER_CHILDREN = new Set([0xe7, 0x5854, 0xa7, 0xab, 0xa3, 0xa0, 0xaf, VOID, CRC32]);\n/** 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. */\nconst INFO_KEEPS = new Set([0x2ad7b1, 0x4489, 0x73a4, 0x4444, 0x3cb923, 0x3eb923, 0x6924]);\nconst INFO_ZEROED = new Set([0x4d80, 0x5741]);\nconst TRACK_ENTRY = 0xae, TRACK_NAME = 0x536e, CODEC_ID = 0x86, CODEC_PRIVATE = 0x63a2, SEEK = 0x4dbb, SEEK_ID = 0x53ab;\n/** The codecs whose CodecPrivate is their Ogg headers Xiph-laced: the second a comment header, its magic, and whether a framing bit follows its comments. */\nconst XIPH_PRIVATE = new Map<string, [string, boolean]>([[\"A_VORBIS\", [\"\\x03vorbis\", true]], [\"V_THEORA\", [\"\\x81theora\", false]]]);\n\ninterface Element { id: number; start: number; body: number; end: number; unknown: boolean }\n\n/** The element whose header is at `at` of `b` (`base` its offset in the file); one of unknown size ends at `limit`. */\nfunction element(b: Uint8Array, at: number, limit: number, base = 0): Element {\n check(at < b.length);\n const idLength = Math.clz32(b[at]!) - 23;\n check(idLength >= 1 && idLength <= 4 && at + idLength < b.length);\n let id = 0;\n for (let i = 0; i < idLength; i++) id = id * 256 + b[at + i]!;\n const sizeAt = at + idLength, sizeLength = Math.clz32(b[sizeAt]!) - 23;\n check(sizeLength >= 1 && sizeLength <= 8 && sizeAt + sizeLength <= b.length);\n let size = b[sizeAt]! & (0xff >> sizeLength), ones = size === 0xff >> sizeLength;\n for (let i = 1; i < sizeLength; i++) {\n size = size * 256 + b[sizeAt + i]!;\n ones &&= b[sizeAt + i] === 0xff;\n }\n const body = base + sizeAt + sizeLength;\n return { id, start: base + at, body, end: ones ? limit : body + size, unknown: ones };\n}\n\n/** An element's header read from the file at `at`. */\nasync function elementAt(source: VideoSource, at: number, limit: number): Promise<Element> {\n return element(await source.read(at, 12), 0, limit, at);\n}\n\n/** A Void element `length` bytes long: its ID, its size in as many bytes as it takes to fill it, the rest zeros. */\nfunction voidHeader(length: number): Uint8Array {\n for (let sizeLength = 1; sizeLength <= 8; sizeLength++) {\n const body = length - 1 - sizeLength;\n if (body < 0 || body >= 2 ** (7 * sizeLength) - 1) continue;\n const header = new Uint8Array(1 + sizeLength);\n header[0] = VOID;\n for (let i = sizeLength, rest = body; i >= 1; i--, rest = Math.floor(rest / 256)) header[i] = rest % 256;\n header[1]! |= 0x80 >> (sizeLength - 1);\n return header;\n }\n check(false);\n}\n\n/** `el` of `b` (read whole, `el`'s offsets in it) made Void where it is. */\nfunction voidIn(b: Uint8Array, el: Element): void {\n const header = voidHeader(el.end - el.start);\n b.fill(0, el.start, el.end);\n b.set(header, el.start);\n}\n\n/** The children of `parent` (in `b`, read whole) as elements, each within it. */\nfunction childrenOf(b: Uint8Array, parent: Element): Element[] {\n const found: Element[] = [];\n for (let at = parent.body; at < parent.end;) {\n const child = element(b.subarray(0, parent.end), at, parent.end);\n check(!child.unknown && child.end <= parent.end);\n found.push(child);\n at = child.end;\n }\n return found;\n}\n\n/**\n * A track's CodecPrivate (`b`, changed in it) by its codec: a Vorbis or Theora track's headers (their count less one,\n * each size but the last's in Xiph lacing, them) with a comment header that has no comment, its sizes kept; a FLAC\n * track's `fLaC` and metadata blocks as a FLAC's, any byte after the last zeroed. Another codec's is kept as it is.\n */\nasync function noPrivateTags(b: Uint8Array, codec: string): Promise<void> {\n const xiph = XIPH_PRIVATE.get(codec);\n if (xiph) {\n check(b.length >= 1 && b[0] === 2);\n let at = 1;\n const sizes: number[] = [];\n while (sizes.length < 2) {\n let size = 0;\n for (let byte = 255; byte === 255; size += byte) {\n check(at < b.length);\n byte = b[at++]!;\n }\n sizes.push(size);\n }\n const start = at + sizes[0]!, end = start + sizes[1]!;\n check(end <= b.length);\n b.set(noComments(b.subarray(start, end), ...xiph), start);\n } else if (codec === \"A_FLAC\") {\n check(b.length >= 4 && text(b, 0, 4) === \"fLaC\");\n const patches: VideoPatch[] = [];\n const end = await flac(async (offset, length) => {\n check(offset >= 0 && length >= 0 && offset + length <= b.length);\n return b.subarray(offset, offset + length);\n }, b.length, 0, patches);\n for (const patch of patches) {\n if (patch.bytes) b.set(patch.bytes, patch.start);\n else b.fill(0, patch.start, patch.end);\n }\n b.fill(0, end);\n }\n}\n\n/**\n * A top-level element of a segment read whole and changed in it: Info without its title, date and file names (its\n * muxer's and writing app's names zeroed), Tracks without their names and the comments in their CodecPrivate, a\n * SeekHead without the entries for what became Void. A CRC-32 in them, wrong once they changed, becomes Void too.\n */\nasync function stripTopLevel(b: Uint8Array): Promise<void> {\n const top = element(b, 0, b.length);\n check(!top.unknown && top.end === b.length);\n for (const child of childrenOf(b, top)) {\n if (child.id === CRC32) voidIn(b, child);\n else if (top.id === INFO) {\n if (INFO_ZEROED.has(child.id)) b.fill(0, child.body, child.end);\n else if (!INFO_KEEPS.has(child.id) && child.id !== VOID) voidIn(b, child);\n } else if (top.id === TRACKS && child.id === TRACK_ENTRY) {\n const parts = childrenOf(b, child), ids = parts.filter((part) => part.id === CODEC_ID);\n // A CodecID null-padded is the same; two would leave which one a player reads unknown.\n check(ids.length <= 1);\n const codec = ids[0] ? text(b, ids[0].body, ids[0].end - ids[0].body).replace(/\\0+$/, \"\") : \"\";\n for (const part of parts) {\n if (part.id === TRACK_NAME || part.id === CRC32) voidIn(b, part);\n else if (part.id === CODEC_PRIVATE) await noPrivateTags(b.subarray(part.body, part.end), codec);\n }\n } else if (top.id === SEEK_HEAD && child.id === SEEK) {\n const target = childrenOf(b, child).find((part) => part.id === SEEK_ID);\n let id = 0;\n if (target) for (let i = target.body; i < target.end; i++) id = id * 256 + b[i]!;\n if (!SEGMENT_KEEPS.has(id)) voidIn(b, child);\n }\n if (child.id === VOID) b.fill(0, child.body, child.end);\n }\n}\n\n/** Where a cluster of unknown size ends: at the first element that is not a cluster's, or the segment's end. */\nasync function clusterEnd(source: VideoSource, at: number, limit: number, count: () => void): Promise<number> {\n for (;;) {\n count();\n if (at >= limit) return limit;\n const child = await elementAt(source, at, limit);\n if (!CLUSTER_CHILDREN.has(child.id)) return at;\n check(!child.unknown);\n // A recording cut short ends in the middle of a block: the rest is sound.\n if (child.end >= limit) return limit;\n at = child.end;\n }\n}\n\nasync function matroska(source: VideoSource, read: Read, patches: VideoPatch[]): Promise<void> {\n const count = counter();\n const toVoid = (el: Element) => {\n const header = voidHeader(el.end - el.start);\n patches.push({ start: el.start, end: el.start + header.length, bytes: header });\n if (el.end > el.start + header.length) patches.push({ start: el.start + header.length, end: el.end });\n };\n for (let at = 0; at < source.size;) {\n count();\n const top = await elementAt(source, at, source.size);\n check(top.end <= source.size);\n if (top.id === EBML_HEADER) check(!top.unknown);\n else if (top.id === VOID) { if (top.end > top.body) patches.push({ start: top.body, end: top.end }); }\n else if (top.id !== SEGMENT) { check(!top.unknown); toVoid(top); }\n else for (let in_ = top.body; in_ < top.end;) {\n count();\n const el = await elementAt(source, in_, top.end);\n if (el.id === CLUSTER) {\n in_ = el.unknown ? await clusterEnd(source, el.body, top.end, count) : Math.min(el.end, top.end);\n continue;\n }\n check(!el.unknown && el.end <= top.end);\n if (el.id === INFO || el.id === TRACKS || el.id === SEEK_HEAD) {\n const bytes = (await read(el.start, el.end - el.start)).slice();\n await stripTopLevel(bytes);\n patches.push({ start: el.start, end: el.end, bytes });\n } else if (el.id === VOID) {\n if (el.end > el.body) patches.push({ start: el.body, end: el.end });\n } else if (!SEGMENT_KEEPS.has(el.id)) toVoid(el);\n in_ = el.end;\n }\n at = top.end;\n }\n}\n\n/**\n * What `withoutAudioMetadata` changes in an audio file read from `source` (one not held in a Blob: a file kept in\n * storage): the parts replaced, in order and apart, the rest of its bytes going as they are; undefined when it goes as\n * it is. Throws `NO_AUDIO_METADATA` for one whose tags cannot be removed; an error reading `source` as it is.\n */\nexport async function audioMetadataPatches(file: VideoSource, mime: string): Promise<VideoPatch[] | undefined> {\n const source = readingAhead(file), read = exactly(source), size = source.size;\n const head = await source.read(0, Math.min(AUDIO_METADATA_LIMITS.headBytes, size));\n const patches: VideoPatch[] = [];\n if (head.length >= 8 && text(head, 4, 4) === \"ftyp\") {\n try {\n return await videoMetadataPatches(file, mime, true);\n } catch (error) {\n if (error instanceof Error && error.message === NO_VIDEO_METADATA) throw Object.assign(new Error(NO_AUDIO_METADATA), { cause: error });\n throw error;\n }\n } else if (text(head, 0, 4) === \"OggS\") await ogg(read, size, patches);\n else if (head.length >= 12 && [\"RIFF\", \"RF64\", \"BW64\"].includes(text(head, 0, 4)) && text(head, 8, 4) === \"WAVE\") await wav(read, size, text(head, 0, 4) !== \"RIFF\", patches);\n else if (text(head, 0, 4) === \"\\x1a\\x45\\xdf\\xa3\") await matroska(source, read, patches);\n else if (head.length >= 12 && text(head, 0, 4) === \"FORM\" && [\"AIFF\", \"AIFC\"].includes(text(head, 8, 4))) await aiff(read, size, patches);\n else if (head.length >= 8 && text(head, 0, 4) === \"caff\") await caf(read, size, patches);\n else if (head.length >= 24 && text(head, 0, 4) === \".snd\") await au(read, size, patches);\n else if (text(head, 0, 4) === \"wvpk\") await trailingTags(read, size, await wavpack(read, size, 0, patches), patches);\n else if (text(head, 0, 4) === \"TTA1\" || [\"MAC \", \"MPCK\", \"OFR \"].includes(text(head, 0, 4)) || text(head, 0, 3) === \"MP+\") await trailingTags(read, size, 0, patches);\n else if (text(head, 0, 4) === \"DSD \") await dsf(read, size, patches);\n else if (head.length >= 16 && text(head, 0, 4) === \"FRM8\" && text(head, 12, 4) === \"DSD \") await dsdiff(read, size, patches);\n else if (head.length >= 14 && text(head, 0, 4) === \"MThd\") await midi(read, size, patches);\n else if (isAsf(head)) check(false);\n else if (text(head, 0, 4) === \"fLaC\") await trailingTags(read, size, await flac(read, size, 0, patches), patches);\n else if (isId3(head) || isFrame(head, 0)) {\n // ID3v2 tags before the sound (one after another, as some taggers leave them), then a FLAC's or a WavPack's blocks, or MPEG frames.\n let at = 0;\n const count = counter();\n for (let next = head; isId3(next); next = at + 10 <= size ? await read(at, 10) : new Uint8Array(0)) {\n count();\n at = await emptyId3(read, size, at, next, patches);\n }\n if (at + 4 <= size && text(await read(at, 4), 0, 4) === \"fLaC\") at = await flac(read, size, at, patches);\n else if (at + 4 <= size && text(await read(at, 4), 0, 4) === \"wvpk\") at = await wavpack(read, size, at, patches);\n await trailingTags(read, size, at, patches);\n } else if (MPEG_AUDIO.has(baseMime(mime))) {\n // An MP3 or AAC that starts with neither (junk before its first frame, a stream cut): a player finds its frames past\n // the junk and reads the tags at its end.\n await trailingTags(read, size, 0, patches);\n } else return undefined;\n if (!patches.length) return undefined;\n patches.sort((a, b) => a.start - b.start);\n for (let i = 1; i < patches.length; i++) check(patches[i]!.start >= patches[i - 1]!.end);\n return patches;\n}\n\n/**\n * `source` as it is sent: an audio file without its tags, made of `source`'s own bytes but for the parts emptied;\n * undefined when it goes as it is (not one of these, or one with nothing to remove). Throws `NO_AUDIO_METADATA` for\n * one whose tags cannot be removed; an error reading `source` as it is.\n */\nexport async function withoutAudioMetadata(source: Blob, mime: string): Promise<Blob | undefined> {\n const patches = await audioMetadataPatches({ size: source.size, read: async (offset, length) => new Uint8Array(await source.slice(offset, offset + length).arrayBuffer()) }, mime);\n if (!patches) return undefined;\n const parts: BlobPart[] = [];\n let at = 0;\n for (const patch of patches) {\n if (patch.start > at) parts.push(source.slice(at, patch.start));\n if (patch.bytes) parts.push(patch.bytes as BlobPart);\n else for (let left = patch.end - patch.start; left > 0; left -= ZEROS.size) parts.push(ZEROS.slice(0, Math.min(left, ZEROS.size)));\n at = patch.end;\n }\n if (at < source.size) parts.push(source.slice(at));\n return new Blob(parts, { type: mime });\n}\n","import { engineError } from \"./engineErrors\";\nimport { bech32 } from \"@scure/base\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { decodeBolt11, type Bolt11Invoice } from \"./bolt11\";\nimport { underLocalSuffix } from \"./localNames\";\nimport { stripHidden } from \"./text\";\n\n/**\n * Paying a Lightning address or an LNURL: the payer's side of\n * [LUD-16](https://github.com/lnurl/luds/blob/luds/16.md) (`name@domain`),\n * [LUD-06](https://github.com/lnurl/luds/blob/luds/06.md) (`payRequest`),\n * [LUD-01](https://github.com/lnurl/luds/blob/luds/01.md) (`lnurl1…` bech32),\n * [LUD-17](https://github.com/lnurl/luds/blob/luds/17.md) (`lnurlp://`),\n * [LUD-12](https://github.com/lnurl/luds/blob/luds/12.md) (a comment) and\n * [LUD-09](https://github.com/lnurl/luds/blob/luds/09.md) (a success message).\n *\n * Resolving reveals the request to the service's domain (it is an HTTPS fetch), so the domain is part of\n * what a person is shown before anything is fetched. Everything the service answers is checked: the\n * amounts it allows, the invoice it returns (its amount, and that it commits to the metadata the person\n * saw), and how much of it is read at all. Paying then goes through the active Lightning source like any\n * other invoice. Receiving on a Lightning address needs a server the person runs; it is not here.\n */\n\nexport interface LightningDestination {\n kind: \"address\" | \"lnurl\";\n /** What was pasted, normalised: a lower-cased `name@domain`, or the `lnurl…` / `lnurlp://…` text. */\n text: string;\n /** Where the pay request is fetched from. */\n url: string;\n /** The host that learns about the request. */\n domain: string;\n /** LUD-16: the part before the `@`. */\n name?: string;\n}\n\nexport interface LnurlSuccessAction {\n tag: \"message\" | \"url\";\n message?: string;\n description?: string;\n url?: string;\n}\n\n/** A service's `payRequest`, checked. Amounts in `minSendable`/`maxSendable` are millisats, `minSat`/`maxSat` whole sats. */\nexport interface LnurlPayParams {\n destination: LightningDestination;\n callback: string;\n /** The host the invoice is asked from, when it is not the one that answered. */\n callbackDomain: string;\n minSendable: number;\n maxSendable: number;\n minSat: number;\n maxSat: number;\n /** The metadata string as the service sent it: what the invoice must commit to. */\n metadata: string;\n /** sha256 of `metadata`, hex: the invoice's `h` tag when it has one. */\n descriptionHash: string;\n /** The `text/plain` entry: what the payment is for, as the service says. */\n description: string;\n /** The `text/identifier` or `text/email` entry, when the service names an address. */\n identifier?: string;\n /** LUD-12: how long a comment may be; 0 when none is taken. */\n commentAllowed: number;\n}\n\nexport interface LnurlFetchOptions {\n fetch?: typeof fetch;\n signal?: AbortSignal;\n timeoutMs?: number;\n maxBytes?: number;\n}\n\nexport const LNURL_LIMITS = { timeoutMs: 15_000, maxBytes: 64 * 1024, maxRedirects: 5, maxUrlLength: 2048, maxMetadataLength: 8 * 1024, maxComment: 2000 } as const;\n\nconst ADDRESS = /^([a-z0-9._+-]{1,64})@([a-z0-9-]+(?:\\.[a-z0-9-]+)*(?::\\d{1,5})?)$/i;\nconst LNURL_BECH32 = /^lnurl1[02-9ac-hj-np-z]{6,}$/i;\n/** A Lightning address or LNURL inside free text: `lightning:` and `⚡` prefixes are tolerated. */\nexport const LIGHTNING_DESTINATION_PATTERN = /(?:lightning:|lnurlp:\\/\\/|lnurl1|[a-z0-9._+-]{1,64}@[a-z0-9-]+(?:\\.[a-z0-9-]+)+)/i;\n\nconst REDIRECTS = [301, 302, 303, 307, 308];\n\n/**\n * A host that is not on the public internet, as far as its name tells: this machine, a single label, a name under a\n * local suffix (`localNames.ts`), private and reserved IP addresses. (What a public name resolves to is checked where\n * the client resolves names itself, as Ghostly Desktop and the CLI do, for every request.)\n */\nfunction isLocalHost(hostname: string): boolean {\n const host = hostname.toLowerCase().replace(/\\.+$/, \"\").replace(/^\\[|\\]$/g, \"\");\n if (!host.includes(\".\") && !host.includes(\":\")) return true;\n if (underLocalSuffix(host)) return true;\n const v4 = /^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(host);\n if (v4) {\n const [a, b] = [Number(v4[1]), Number(v4[2])];\n return a === 0 || a === 10 || a === 127 || a >= 224 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b < 32)\n || (a === 192 && b === 168) || (a === 100 && b >= 64 && b < 128) || (a === 198 && (b === 18 || b === 19)) || (a === 192 && b === 0);\n }\n // Any IPv6 literal but a global unicast one (2000::/3: a first group of four digits, as `2::` is `0002::`), none\n // that embeds an IPv4 address (dotted, 6to4 2002::/16, Teredo 2001::/32: `new URL()` writes them all in hex), and\n // no documentation one (2001:db8::/32). Kept the same as apps/ui/src/lib/localHost.ts.\n if (host.includes(\":\")) {\n return !/^[23][0-9a-f]{3}:/.test(host) || host.includes(\".\") || host.startsWith(\"2002:\") || /^2001:(0{0,4}|0{0,3}db8):/.test(host);\n }\n return false;\n}\n\nconst isLoopback = (hostname: string) => [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(hostname);\n\n/** HTTPS, or plain HTTP only for a hidden service or a test server on this machine; never credentials. */\nfunction acceptUrl(text: string): URL {\n if (text.length > LNURL_LIMITS.maxUrlLength) throw new Error(\"That LNURL is too long\");\n let url: URL;\n try { url = new URL(text); } catch { throw new Error(\"That LNURL does not point to a valid address\"); }\n const plainAllowed = url.hostname.endsWith(\".onion\") || isLoopback(url.hostname);\n if (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && plainAllowed)) throw new Error(\"Lightning addresses and LNURLs must use HTTPS\");\n if (url.username || url.password) throw new Error(\"That LNURL carries credentials, which is not allowed\");\n return url;\n}\n\n/** Reads what was pasted as a Lightning address or an LNURL; null when it is neither. Throws when it is one, but a bad one. */\nexport function parseLightningDestination(input: string): LightningDestination | null {\n const text = input.trim().replace(/^(lightning:|⚡\\s*)/i, \"\").trim();\n if (!text) return null;\n if (LNURL_BECH32.test(text)) {\n let decoded: { prefix: string; words: number[] };\n try { decoded = bech32.decode(text.toLowerCase() as `${string}1${string}`, LNURL_LIMITS.maxUrlLength); }\n catch { throw new Error(\"That LNURL is not valid\"); }\n const url = acceptUrl(new TextDecoder().decode(bech32.fromWords(decoded.words)));\n return { kind: \"lnurl\", text: text.toLowerCase(), url: url.href, domain: url.host };\n }\n if (/^lnurlp:\\/\\//i.test(text)) {\n const bare = text.slice(\"lnurlp://\".length);\n const host = bare.split(/[/?#]/)[0].toLowerCase();\n const scheme = host.endsWith(\".onion\") || isLoopback(host.replace(/:\\d+$/, \"\")) ? \"http\" : \"https\";\n const url = acceptUrl(`${scheme}://${bare}`);\n return { kind: \"lnurl\", text: `lnurlp://${bare}`, url: url.href, domain: url.host };\n }\n const address = ADDRESS.exec(text);\n if (!address) return null;\n const name = address[1].toLowerCase(), domain = address[2].toLowerCase();\n const hostname = domain.replace(/:\\d+$/, \"\");\n if (!hostname.includes(\".\") && !isLoopback(hostname)) return null;\n const scheme = hostname.endsWith(\".onion\") || isLoopback(hostname) ? \"http\" : \"https\";\n const url = acceptUrl(`${scheme}://${domain}/.well-known/lnurlp/${name}`);\n return { kind: \"address\", text: `${name}@${domain}`, url: url.href, domain: url.host, name };\n}\n\n/** The first Lightning address or LNURL in a message, with whatever else the message says. */\nexport function findLightningDestination(text: string): { destination: LightningDestination; rest: string } | null {\n const match = LIGHTNING_DESTINATION_PATTERN.exec(text);\n if (!match) return null;\n // Take the whole token the match starts in: an lnurl runs to the next space, an address stops at its domain.\n const start = match.index, end = text.slice(start).search(/\\s|$/);\n // The sentence's closing punctuation stays out, taken off one by one: `/[…]+$/` retries from every character of a\n // long run that does not reach the end, which is quadratic.\n let stop = start + end;\n while (stop > start && \"),.;:!?\".includes(text[stop - 1])) stop--;\n const token = text.slice(start, stop);\n let destination: LightningDestination | null;\n try { destination = parseLightningDestination(token); } catch { return null; }\n if (!destination) return null;\n return { destination, rest: (text.slice(0, start) + text.slice(start + token.length)).trim() };\n}\n\nconst hex = (bytes: Uint8Array) => Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n/** A server's own words on one line, bounded, with no character that hides text or reorders what follows it. */\nconst reason = (value: unknown) => (typeof value === \"string\" ? stripHidden(value.replace(/\\s+/g, \" \")).slice(0, 200) : \"\");\nconst isRecord = (value: unknown): value is Record<string, unknown> => !!value && typeof value === \"object\" && !Array.isArray(value);\n\nasync function readBounded(response: Response, maxBytes: number): Promise<string> {\n const reader = response.body?.getReader?.();\n if (!reader) {\n const text = await response.text();\n if (text.length > maxBytes) throw new Error(\"The server's answer is too large\");\n return text;\n }\n const chunks: Uint8Array[] = [];\n let size = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > maxBytes) { await reader.cancel().catch(() => {}); throw new Error(\"The server's answer is too large\"); }\n chunks.push(value);\n }\n const all = new Uint8Array(size);\n let at = 0;\n for (const chunk of chunks) { all.set(chunk, at); at += chunk.byteLength; }\n return new TextDecoder().decode(all);\n}\n\n/** One GET to an LNURL service (and to each checked redirect of it): bounded in time and size, no credentials, no referrer, and the answer must be JSON. */\nexport async function fetchLnurlJson(url: string, options: LnurlFetchOptions = {}): Promise<unknown> {\n const target = acceptUrl(url);\n // The rule a redirect has: this machine or the local network is never asked, but for a test server on this machine.\n if (!isLoopback(target.hostname) && isLocalHost(target.hostname)) throw new Error(`${target.host} is a local address`);\n const doFetch = options.fetch ?? globalThis.fetch;\n if (!doFetch) throw new Error(\"No way to reach the network here\");\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(new Error(\"The server took too long to answer\")), options.timeoutMs ?? LNURL_LIMITS.timeoutMs);\n const onAbort = () => controller.abort(options.signal?.reason);\n options.signal?.addEventListener(\"abort\", onAbort, { once: true });\n try {\n let response: Response;\n // Redirects are followed here, one by one: each is checked before anything is sent to it.\n for (let at = target, hops = 0; ; hops++) {\n try {\n response = await doFetch(at.href, { signal: controller.signal, headers: { accept: \"application/json\" }, credentials: \"omit\", referrerPolicy: \"no-referrer\", redirect: \"manual\" });\n } catch {\n if (controller.signal.aborted) throw controller.signal.reason instanceof Error ? controller.signal.reason : new Error(\"The request was cancelled\");\n throw engineError(\"lnurlUnreachable\", { host: target.host });\n }\n // A fetcher that followed one after all: where it landed is still checked.\n if (response.url) acceptUrl(response.url);\n // A browser's `fetch` does not say where a redirect leads (an opaque answer: no status, no `Location`), so a page\n // cannot check it: refused here. A host that can read each hop passes its own `fetch` (Ghostly Desktop, from Rust).\n if (response.type === \"opaqueredirect\") throw new Error(`${target.host} redirects to another address, which cannot be checked here`);\n const location = REDIRECTS.includes(response.status) ? response.headers.get(\"location\") : null;\n if (!location) break;\n await response.body?.cancel().catch(() => {});\n if (hops >= LNURL_LIMITS.maxRedirects) throw new Error(`${target.host} redirects too many times`);\n let next: URL;\n try { next = new URL(location, at); } catch { throw new Error(`${target.host} redirects to an invalid address`); }\n next = acceptUrl(next.href);\n // Another host only over HTTPS and at a public address: never plain HTTP (a hidden service, this machine), this\n // machine or the local network as a way in from the host that was asked.\n if (next.host !== at.host) {\n if (next.protocol !== \"https:\") throw new Error(\"Lightning addresses and LNURLs must use HTTPS\");\n if (isLocalHost(next.hostname)) throw new Error(`${target.host} redirects to a local address`);\n }\n at = next;\n }\n const text = await readBounded(response, options.maxBytes ?? LNURL_LIMITS.maxBytes);\n let body: unknown;\n try { body = JSON.parse(text); } catch { throw new Error(`${target.host} did not answer with JSON${response.ok ? \"\" : ` (HTTP ${response.status})`}`); }\n if (isRecord(body) && body.status === \"ERROR\") throw new Error(`${target.host} refused: ${reason(body.reason) || \"no reason given\"}`);\n if (!response.ok) throw new Error(`${target.host} answered HTTP ${response.status}`);\n return body;\n } finally {\n clearTimeout(timer);\n options.signal?.removeEventListener(\"abort\", onAbort);\n }\n}\n\n/** Checks a service's `payRequest` answer (LUD-06), and reads what a person needs to see of it. */\nexport function parsePayParams(body: unknown, destination: LightningDestination): LnurlPayParams {\n if (!isRecord(body)) throw new Error(`${destination.domain} did not answer with a pay request`);\n if (body.tag !== \"payRequest\") throw new Error(`${destination.domain} answered with something other than a pay request${typeof body.tag === \"string\" ? ` (${reason(body.tag)})` : \"\"}`);\n if (typeof body.callback !== \"string\") throw new Error(\"The pay request has no callback\");\n const callback = acceptUrl(body.callback);\n // The same rule as a redirect: another host only over HTTPS and at a public address.\n if (callback.host !== new URL(destination.url).host) {\n if (callback.protocol !== \"https:\") throw new Error(\"Lightning addresses and LNURLs must use HTTPS\");\n if (isLocalHost(callback.hostname)) throw new Error(`${destination.domain} asks for the invoice at a local address`);\n }\n const { minSendable, maxSendable, metadata, commentAllowed } = body;\n if (!Number.isSafeInteger(minSendable) || !Number.isSafeInteger(maxSendable) || (minSendable as number) <= 0 || (maxSendable as number) < (minSendable as number)) throw new Error(\"The pay request has invalid amount limits\");\n const minSat = Math.ceil((minSendable as number) / 1000), maxSat = Math.floor((maxSendable as number) / 1000);\n if (minSat > maxSat) throw new Error(\"The pay request only takes fractions of a sat, which cannot be paid here\");\n if (typeof metadata !== \"string\" || metadata.length > LNURL_LIMITS.maxMetadataLength) throw new Error(\"The pay request has no usable metadata\");\n let entries: unknown;\n try { entries = JSON.parse(metadata); } catch { throw new Error(\"The pay request's metadata is not JSON\"); }\n if (!Array.isArray(entries) || !entries.every((e) => Array.isArray(e) && typeof e[0] === \"string\")) throw new Error(\"The pay request's metadata is malformed\");\n const entry = (type: string) => (entries as unknown[][]).find((e) => e[0] === type)?.[1];\n const description = entry(\"text/plain\");\n if (typeof description !== \"string\") throw new Error(\"The pay request says nothing about what it is for (no text/plain metadata)\");\n const identifier = [entry(\"text/identifier\"), entry(\"text/email\")].find((v): v is string => typeof v === \"string\")?.toLowerCase();\n if (destination.kind === \"address\" && identifier && identifier !== destination.text) throw new Error(`${destination.domain} answered for ${identifier}, not ${destination.text}`);\n const comment = Number.isSafeInteger(commentAllowed) && (commentAllowed as number) > 0 ? Math.min(commentAllowed as number, LNURL_LIMITS.maxComment) : 0;\n return {\n destination, callback: callback.href, callbackDomain: callback.host,\n minSendable: minSendable as number, maxSendable: maxSendable as number, minSat, maxSat,\n metadata, descriptionHash: hex(sha256(new TextEncoder().encode(metadata))), description: stripHidden(description.replace(/\\s+/g, \" \")).slice(0, 280), identifier, commentAllowed: comment,\n };\n}\n\n/** Where to ask for the invoice of `amountSat` (and a comment, LUD-12). Throws when the amount or comment is not allowed. */\nexport function invoiceCallbackUrl(params: LnurlPayParams, amountSat: number, comment?: string): string {\n if (!Number.isSafeInteger(amountSat) || amountSat <= 0) throw new Error(\"Enter a whole number of sats\");\n if (amountSat < params.minSat || amountSat > params.maxSat) throw params.minSat === params.maxSat ? engineError(\"lnurlExactly\", { domain: params.destination.domain, amount: params.minSat.toLocaleString() }) : engineError(\"lnurlRange\", { domain: params.destination.domain, min: params.minSat.toLocaleString(), max: params.maxSat.toLocaleString() });\n const url = new URL(params.callback);\n url.searchParams.set(\"amount\", String(amountSat * 1000));\n const text = comment?.trim();\n if (text) {\n if (!params.commentAllowed) throw new Error(`${params.destination.domain} does not take a comment`);\n if (text.length > params.commentAllowed) throw new Error(`The comment can be at most ${params.commentAllowed} characters`);\n url.searchParams.set(\"comment\", text);\n }\n return url.href;\n}\n\n/**\n * A success action's link: HTTPS, bounded, no user part (\"https://www.paypal.com@evil.example\" opens evil.example),\n * and on the callback's own host (LUD-09), so a service cannot hand out a link to somewhere else.\n */\nfunction successUrl(text: string, host: string): boolean {\n if (!/^https:\\/\\//i.test(text) || text.length > LNURL_LIMITS.maxUrlLength) return false;\n try { const url = new URL(text); return !url.username && !url.password && url.host === host; } catch { return false; }\n}\n\n/**\n * Checks the invoice a service answered with (LUD-06): the amount asked, a payment hash, not expired, and\n * a commitment to the metadata the person was shown: the `h` tag is its sha256, or the invoice carries the\n * metadata itself as its description (the same commitment, unhashed).\n */\nexport function parseInvoiceCallback(body: unknown, params: LnurlPayParams, amountSat: number): { invoice: Bolt11Invoice; successAction?: LnurlSuccessAction } {\n if (!isRecord(body) || typeof body.pr !== \"string\") throw new Error(`${params.callbackDomain} did not answer with an invoice`);\n const invoice = decodeBolt11(body.pr);\n if (!invoice) throw new Error(`${params.callbackDomain} answered with an invoice that does not decode`);\n // Its amounts in en-US, whatever the language of the process (a browser's worker): the app matches this English (errorText.ts).\n if (invoice.amountMsat !== BigInt(amountSat) * 1000n) throw new Error(`The invoice asks for ${invoice.amountSat === null ? \"any amount\" : `${invoice.amountSat.toLocaleString(\"en-US\")} sats`}, not the ${amountSat.toLocaleString(\"en-US\")} sats you chose`);\n if (!invoice.paymentHash) throw new Error(\"The invoice has no payment hash\");\n if (invoice.descriptionHash !== params.descriptionHash && invoice.description !== params.metadata) throw new Error(\"The invoice does not commit to what the service said the payment is for\");\n if (invoice.expiresAt * 1000 < Date.now()) throw new Error(\"The invoice the service answered with has already expired\");\n let successAction: LnurlSuccessAction | undefined;\n const action = body.successAction;\n if (isRecord(action)) {\n if (action.tag === \"message\" && typeof action.message === \"string\") successAction = { tag: \"message\", message: reason(action.message) };\n else if (action.tag === \"url\" && typeof action.url === \"string\" && successUrl(action.url, params.callbackDomain)) successAction = { tag: \"url\", description: reason(action.description), url: action.url };\n }\n return { invoice, successAction };\n}\n\n/** Fetches and checks what a Lightning address or LNURL asks for. The service's domain learns of it. */\nexport async function resolveLightningDestination(text: string, options: LnurlFetchOptions = {}): Promise<LnurlPayParams> {\n const destination = parseLightningDestination(text);\n if (!destination) throw new Error(\"That is not a Lightning address or an LNURL\");\n return parsePayParams(await fetchLnurlJson(destination.url, options), destination);\n}\n\n/** Asks the service for an invoice of `amountSat`, and checks it before it is handed to any wallet. */\nexport async function requestLnurlInvoice(params: LnurlPayParams, amountSat: number, comment: string | undefined, options: LnurlFetchOptions = {}): Promise<{ invoice: Bolt11Invoice; successAction?: LnurlSuccessAction }> {\n return parseInvoiceCallback(await fetchLnurlJson(invoiceCallbackUrl(params, amountSat, comment), options), params, amountSat);\n}\n","import { MEMBER_KEY } from \"./groupCommits\";\nimport { utf8Encode } from \"./bytes\";\n\n/*\n * Mentions in a group message (WISP 902 Group Mesh § Mentions, Group Community § Mentions): which members a\n * message names, bound to their member keys rather than to the names they go by, since names can collide and\n * change. The text keeps a readable \"@Name\" at each place, so an app without mentions shows the message as it\n * was typed; the list says which member each place is.\n */\n\n/** A place in the text that names a member: `k` their member key (\"*\": everyone), `o`/`l` in Unicode code points. */\nexport interface GroupMention { k: string; o: number; l: number }\n\n/** Everyone in the group (a private group's admin only; never in a community). */\nexport const MENTION_EVERYONE = \"*\";\n\nexport const MENTION_LIMITS = {\n /** Mentions in one message. A longer list is refused whole. */\n count: 16,\n /** Code points of one mention in the text, its \"@\" included. */\n chars: 65,\n} as const;\n\n// eslint-disable-next-line no-control-regex\nconst NOT_IN_A_NAME = /[\\u0000-\\u001f\\u007f-\\u009f\\u061c\\u200e\\u200f\\u2028\\u2029\\u202a-\\u202e\\u2066-\\u2069]/;\nconst isInt = (v: unknown): v is number => Number.isSafeInteger(v) && (v as number) >= 0;\n\n/**\n * The mentions of a message as a receiver (or the sender) takes them: at most `count` of them, each naming a\n * member key (or everyone, when `everyone` allows it), at a place of the text that starts with \"@\" and holds no\n * line break or control character, in order and not overlapping. An entry that is none of that is dropped; a list\n * longer than the bound is dropped whole.\n */\nexport function validMentions(raw: unknown, text: string, everyone: boolean): GroupMention[] {\n if (!Array.isArray(raw) || raw.length > MENTION_LIMITS.count) return [];\n const points = Array.from(text);\n const kept: GroupMention[] = [];\n for (const entry of raw) {\n if (!entry || typeof entry !== \"object\") continue;\n const { k, o, l } = entry as Record<string, unknown>;\n if (typeof k !== \"string\" || !(MEMBER_KEY.test(k) || (everyone && k === MENTION_EVERYONE))) continue;\n if (!isInt(o) || !isInt(l) || l < 2 || l > MENTION_LIMITS.chars || o + l > points.length || points[o] !== \"@\") continue;\n // A name has no line break, control or direction character: a mention holding one is not a name.\n if (NOT_IN_A_NAME.test(points.slice(o, o + l).join(\"\"))) continue;\n kept.push({ k, o, l });\n }\n kept.sort((a, b) => a.o - b.o);\n return kept.filter((m, i) => i === 0 || m.o >= kept[i - 1].o + kept[i - 1].l);\n}\n\n/** Whether a message's mentions name this member (by key, or everyone). */\nexport function mentionsMember(mentions: readonly GroupMention[] | undefined, key: string): boolean {\n return !!mentions?.some(m => m.k === key || m.k === MENTION_EVERYONE);\n}\n\n/** The bytes a list of mentions adds to a message, as JSON: counted against the text's bound. */\nexport function mentionsBytes(mentions: readonly GroupMention[]): number {\n return mentions.length ? utf8Encode(JSON.stringify(mentions)).length : 0;\n}\n\n/** Only the wire fields, in a fixed order (what the sender seals). */\nexport const wireMentions = (mentions: readonly GroupMention[]): GroupMention[] => mentions.map(({ k, o, l }) => ({ k, o, l }));\n","import { utf8Encode } from \"./bytes\";\nimport { MEMBER_KEY } from \"./groupCommits\";\nimport { MENTION_LIMITS, validMentions, type GroupMention } from \"./groupMentions\";\nimport { validEditNumber, validRemovalNumber } from \"./pairedEdits\";\nimport { cardEditNumber, readStatusCard, type StatusCard } from \"./statusCards\";\n\n/**\n * Editing a sent text in a group (WISP 902 § Edits, both profiles). As in a 1:1 chat (WISP 401 § Edits), the author says\n * the whole new text of one of its own messages with an edit number of its own per message, and the highest number\n * wins whatever order edits arrive in. A group has no receipts: the author says an edit to every member it can, and\n * again later (a private group: when an edge opens; a community: its members catch up from each other).\n *\n * - A private group (`group-mesh/1`) sends a `group-edit` frame of its own over each edge, sealed under the key of the\n * epoch the message was sent in and signed by its author (`GroupSession.sendEdit`).\n * - A community (`group-community/1`) sends an application frame through the group, sealed and signed like any payload,\n * so every hub carries it and a member who was away gets it with the catch-up:\n *\n * { \"x\": { \"t\": \"edit\", \"id\": <message id>, \"v\": 3, \"ts\": 1790000000000, \"text\": \"Done: 12 of 12\", \"m\"?: [mentions], \"sc\"?: {card} } }\n *\n * `sc` is the status card of this version (WISP 405 · Status Cards); an edit with one may be numbered up to\n * `STATUS_CARD_LIMITS.edits`, one without only up to `MAX_EDITS_PER_MESSAGE`.\n *\n * A removal (WISP 400 § Delete for everyone) is an edit with `rm: true` and a fallback text, nothing else beside it,\n * numbered up to `MAX_REMOVAL_NUMBER`: in a mesh group's box as `{ \"text\", \"rm\": true }`, in a community's frame beside\n * `text`. A `rm` other than `true` is no edit.\n *\n * Older apps drop both: a mesh session ignores a `t` it does not know, a community app the `x` frames it does not know.\n */\n\nexport const GROUP_EDIT_FRAME = \"group-edit\";\nexport const COMMUNITY_EDIT_FRAME = \"edit\";\n\n/** One edit of a group message: the message's id in the group, its edit number, when it was made, the whole new text, its mentions. */\nexport interface GroupEdit {\n id: string;\n /** The edit number, 1 for the first edit (`MAX_EDITS_PER_MESSAGE` at most). */\n e: number;\n ts: number;\n /** The whole new text. */\n m: string;\n /** Places of the new text that name members. */\n k?: GroupMention[];\n /** The status card of this version (WISP 405 · Status Cards). */\n sc?: StatusCard;\n /** The author deleted the message for everyone: `m` is only a fallback. */\n rm?: true;\n}\n\n/** An edit as a group hands it to the engine: `sender` is the member it is authenticated as. */\nexport interface GroupIncomingEdit extends GroupEdit { sender: string }\n\n/** The text bound of a group edit, as a message's: 16 KiB of UTF-8. */\nexport const GROUP_EDIT_TEXT_BYTES = 16 * 1024;\n\nconst MESH_ID = /^([a-km-uw-z13-9]{52}):(\\d{1,9}):(\\d{1,9})$/;\nconst COMMUNITY_ID = /^([a-km-uw-z13-9]{52}):(\\d{1,9}):([0-9a-f]{16}):(\\d{1,9})$/;\n\n/** A private group's message id (`<sender>:<epoch>:<seq>`), split; null when it is not one. */\nexport function meshMessageRef(id: string): { s: string; e: number; n: number } | null {\n const match = MESH_ID.exec(id);\n if (!match || !MEMBER_KEY.test(match[1])) return null;\n return { s: match[1], e: Number(match[2]), n: Number(match[3]) };\n}\n\n/** Whose message a community's id names (`<sender>:<epoch>:<commit>:<seq>`); null when it is not one. */\nexport function communityMessageAuthor(id: string): string | null {\n const match = COMMUNITY_ID.exec(id);\n return match && MEMBER_KEY.test(match[1]) ? match[1] : null;\n}\n\n/** A text an edit may carry: trimmed, not empty, within the bound. */\nexport function validEditText(text: unknown): text is string {\n return typeof text === \"string\" && !!text && text === text.trim() && utf8Encode(text).length <= GROUP_EDIT_TEXT_BYTES;\n}\n\n/** The `x` frame a community edit travels as. */\nexport function communityEditFrame(edit: GroupEdit): Record<string, unknown> {\n if (edit.rm) return { t: COMMUNITY_EDIT_FRAME, id: edit.id, v: edit.e, ts: edit.ts, text: edit.m, rm: true };\n return { t: COMMUNITY_EDIT_FRAME, id: edit.id, v: edit.e, ts: edit.ts, text: edit.m, ...(edit.k?.length ? { m: edit.k } : {}), ...(edit.sc ? { sc: edit.sc } : {}) };\n}\n\n/**\n * The edit a community `x` frame says, from `sender` (whom the group authenticated it as), or null when it is not a\n * valid edit of one of the sender's own messages. Mentions that do not hold are left out, never the edit; a community\n * names no one as everyone.\n */\nexport function parseCommunityEdit(frame: Record<string, unknown>, sender: string): GroupEdit | null {\n if (frame?.t !== COMMUNITY_EDIT_FRAME) return null;\n const { id, v, ts, text, rm } = frame;\n if (rm !== undefined && rm !== true) return null;\n if (typeof id !== \"string\" || communityMessageAuthor(id) !== sender || typeof v !== \"number\" || !(rm ? validRemovalNumber(v) : cardEditNumber(v))) return null;\n if (typeof ts !== \"number\" || !Number.isSafeInteger(ts) || ts <= 0 || !validEditText(text)) return null;\n if (rm) return { id, e: v, ts, m: text, rm };\n const sc = frame.sc === undefined ? undefined : readStatusCard(frame.sc);\n if (!validEditNumber(v) && !sc) return null;\n const k = validMentions(frame.m, text, false);\n return { id, e: v, ts, m: text, ...(k.length ? { k } : {}), ...(sc ? { sc } : {}) };\n}\n\n/**\n * The mentions of an edited text: the places the message named that are still there, found by their words (the text\n * around them may have changed, or their order), and those `added` while editing. Where two overlap, `added` wins.\n */\nexport function carryMentions(before: { text: string; mentions?: readonly GroupMention[] }, after: string, added: readonly GroupMention[], everyone: boolean): GroupMention[] {\n const was = Array.from(before.text), now = Array.from(after);\n const overlaps = (a: GroupMention, b: GroupMention) => a.o < b.o + b.l && b.o < a.o + a.l;\n const carried: GroupMention[] = [];\n for (const m of [...(before.mentions ?? [])].sort((a, b) => a.o - b.o)) {\n const words = was.slice(m.o, m.o + m.l);\n // The first place with its words that no mention carried already holds: \"@Bob … @Bob\" keeps both, in either order.\n for (let at = indexOf(now, words, 0); at >= 0; at = indexOf(now, words, at + 1)) {\n const place = { k: m.k, o: at, l: m.l };\n if (carried.some(c => overlaps(c, place))) continue;\n carried.push(place);\n break;\n }\n }\n const fresh = validMentions(added.map(({ k, o, l }) => ({ k, o, l })), after, everyone);\n const all = [...fresh, ...carried.filter(m => !fresh.some(a => overlaps(a, m)))].sort((a, b) => a.o - b.o);\n return validMentions(all.slice(0, MENTION_LIMITS.count), after, everyone);\n}\n\nfunction indexOf(points: readonly string[], words: readonly string[], from: number): number {\n if (!words.length) return -1;\n outer: for (let i = from; i + words.length <= points.length; i++) {\n for (let j = 0; j < words.length; j++) if (points[i + j] !== words[j]) continue outer;\n return i;\n }\n return -1;\n}\n","/**\n * Frames of one catch-up answer in a slice, two slices at most not handled yet by the member's app: the next goes once\n * it handled the one before the last. An app holds 64 frames waiting at most before 2026-10-07 (more ends the session),\n * and a member back in a busy group was handed over a hundred at once (a private group's answer, WISP 902; a\n * community's, WISP 903: 258 from a full store).\n */\nexport const CATCH_UP_SLICE = 16;\n/** Between two slices, when the member's app cannot say it handled one (`handled` resolves `false`). */\nexport const CATCH_UP_PAUSE_MS = 500;\n\n/** What `CatchUpHooks.handled` says: handled, cannot tell (`false`), or not handled yet within its wait (`\"late\"`). */\nexport type CatchUpHandled = boolean | \"late\";\n\nexport interface CatchUpHooks<F> {\n /** One frame to the member: `false` when its edge did not take it, which ends the answer. */\n send(to: string, frame: F): boolean | void;\n /**\n * Resolves once the member's app handled every frame sent to it so far (it answers a ping in the order frames come),\n * or `false` when it cannot tell: the answer then waits `CATCH_UP_PAUSE_MS` between slices. `\"late\"`: the member's app\n * answers pings but has not handled them yet (a phone with a long history), and the answer asks again rather than\n * sending more. Absent: an answer goes all at once, as before 2026-10-07.\n */\n handled?(to: string): Promise<CatchUpHandled>;\n /** Whether the group still answers: an answer stops when it no longer does. */\n active(): boolean;\n /**\n * What names a frame that a newer answer leaves out while it is on its way (`handled` not resolved yet), or undefined\n * for one that always goes. Absent: a newer answer has every frame of its own.\n */\n key?(frame: F): string | undefined;\n}\n\n/**\n * Catch-up answers, a slice at a time (`CATCH_UP_SLICE`), with two slices at most not handled yet by the member's app\n * (`hooks.handled`): the next once it handled the one before the last, so the slices follow each other without a round\n * trip between them. All at once, a member back in a busy group was handed over a hundred frames on one session, and an\n * app that holds 64 waiting ended that session mid catch-up (\"Session receive limit exceeded\", 2026-10-07). The frames\n * and their order are what they were: only when they go changes.\n */\nexport class CatchUpAnswers<F> {\n /** Answers still going out, per member: what is left of each. */\n private going = new Map<string, F[]>();\n /**\n * Per member, the frames sent (`hooks.key`) whose `handled` has not resolved yet: still waiting in its app, which asks\n * again every 10 s while it handles 1 or 2 a second, and each answer sent the same ones again (200 missed went 1,009\n * times). Left out of a newer answer until handled; one handled and still missing (lost) goes in the next.\n */\n private onTheirWay = new Map<string, Set<string>>();\n\n constructor(private readonly hooks: CatchUpHooks<F>) {}\n\n /**\n * The first two slices go now, the rest without holding the group's other frames back. A newer answer to the same\n * member goes after what is left of the last, without the frames still queued there (the same objects: a store's, or\n * the same `key`) nor those still on their way (`onTheirWay`); it took their place before, and left out what the member's `have`\n * said it held: a live frame of an author raises it above that author's frames still queued, which were lost for\n * good. A frame the edge did not take ends the answer (the member asks again when its edge opens).\n */\n handOut(to: string, frames: F[]): void {\n const handled = this.hooks.handled;\n if (!handled) { for (const frame of frames) this.hooks.send(to, frame); return; }\n const sent = this.onTheirWay.get(to), key = this.hooks.key;\n if (sent?.size && key) frames = frames.filter(frame => { const k = key(frame); return k === undefined || !sent.has(k); });\n const going = this.going.get(to);\n if (going) {\n // By `key` too: a community's commits and secrets are new objects in each answer.\n const queued = new Set(going), queuedKeys = new Set(key ? going.map(key) : []);\n const isQueued = (frame: F) => { const k = key?.(frame); return queued.has(frame) || (k !== undefined && queuedKeys.has(k)); };\n going.push(...frames.filter(frame => !isQueued(frame)));\n return;\n }\n const rest = [...frames], told: Promise<CatchUpHandled>[] = [];\n const ask = () => handled(to).catch(() => false as const);\n // Late, from an app that answers pings: still handling, so it is asked again until it has (a pause there let a\n // member at 600 ms a frame hold 134 waiting, past the 64 an app before 2026-10-07 takes).\n const settled = async () => {\n let answer = await ask();\n while (answer === \"late\" && this.hooks.active()) answer = await ask();\n return answer;\n };\n const next = () => {\n const slice = this.sendSlice(to, rest);\n if (!slice) return false;\n // After the last slice, asked only to know when its frames are no longer on their way.\n const keys = key ? slice.map(key).filter((k): k is string => k !== undefined) : [];\n if (!rest.length && !keys.length) return true;\n const done = settled();\n if (keys.length) this.track(to, keys, done);\n if (rest.length) told.push(done);\n return true;\n };\n if (!next() || !next() || !rest.length) return;\n this.going.set(to, rest);\n void (async () => {\n try {\n while (rest.length) {\n const answer = await told.shift()!;\n if (!answer) await new Promise(resolve => setTimeout(resolve, CATCH_UP_PAUSE_MS));\n if (!this.hooks.active() || !next()) break;\n }\n } finally { this.going.delete(to); }\n })();\n }\n\n /** Whether an answer to `to` still has frames to send, or sent ones its app has not said it handled yet (`hooks.handled`). */\n busy(to: string): boolean { return this.going.has(to) || !!this.onTheirWay.get(to)?.size; }\n\n /** The next slice of `rest` to `to`, as sent: undefined, and nothing left, when the edge did not take one. */\n private sendSlice(to: string, rest: F[]): F[] | undefined {\n const slice = rest.splice(0, CATCH_UP_SLICE);\n for (const frame of slice) if (this.hooks.send(to, frame) === false) { rest.length = 0; return undefined; }\n return slice;\n }\n\n /** A slice's frames (`keys`) are on their way to `to` until `done`: its app handled them, or cannot say (`false`). */\n private track(to: string, keys: string[], done: Promise<CatchUpHandled>): void {\n let sent = this.onTheirWay.get(to);\n if (!sent) this.onTheirWay.set(to, (sent = new Set()));\n for (const k of keys) sent.add(k);\n void done.then(() => {\n for (const k of keys) sent.delete(k);\n if (!sent.size && this.onTheirWay.get(to) === sent) this.onTheirWay.delete(to);\n });\n }\n}\n","import { xchacha20poly1305 } from \"@noble/ciphers/chacha.js\";\nimport { hkdf } from \"@noble/hashes/hkdf.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { concatBytes, fromBase64Url, randomBytes, toBase64Url, utf8Decode, utf8Encode } from \"./bytes\";\nimport { edgeParams } from \"./groupCrypto\";\nimport { GROUP_ID, MEMBER_KEY } from \"./groupCommits\";\nimport { identityFromSeed, publicKeyFromZ32, type Identity } from \"./identity\";\nimport { trimEndOf, unwrapPasted } from \"./text\";\nimport type { LinkParams } from \"./invite\";\nimport type { GhostRecord } from \"./pkarr\";\n\n/**\n * A group's public entry link (`group-entry/1`, WISP 902 § Entry link): one\n * address the admin can hand to anyone, so people who are not their contacts\n * can join, without a contact chat and without saying who they are.\n *\n * The link names the group and an **entry key** of the admin's, made for the\n * link and nothing else. From those two, everyone holding the link derives\n * the same **knock identity**: a Pkarr key whose seed is known to every\n * holder, where a joiner leaves its fresh member key. The admin's app reads\n * it; for every knock it opens an **entry session**, a paired link derived like\n * a group edge from the entry key and the joiner's member key and pinned to\n * both, and runs the ordinary admission over it (invite, accept, welcome).\n * The joiner's trust anchor is the entry key the link named: whoever holds\n * its seed is the admin who must admit it.\n *\n * A link is a bearer capability. Anyone who has it can join while it is on;\n * the admin turns it off, or replaces it, and the old one stops working.\n */\nexport const GROUP_ENTRY_PROFILE = \"group-entry/1\" as const;\nconst PREFIX = \"group1\";\n/** A knock older than this is not answered: the joiner republishes while it waits. */\nexport const KNOCK_TTL_MS = 3 * 60_000;\n/** Knocks a record keeps: joiners share one Pkarr packet, so it holds the latest few. */\nexport const MAX_KNOCKS = 6;\nconst KNOCK_LABEL = \"_knock\";\nconst NONCE_LENGTH = 24;\n\nexport interface GroupEntryLink {\n /** The group id. */\n g: string;\n /** The admin's entry key (z-base-32 Ed25519), made for this link. */\n host: string;\n}\n\nexport interface Knock {\n /** The joiner's member key for this group. */\n key: string;\n /** When the joiner last said it is waiting (ms). */\n ts: number;\n}\n\nconst info = (label: string) => utf8Encode(`ghostly-group-entry/1 ${label}`);\n\n/** `group1/<group id>/<entry key>` */\nexport function encodeGroupEntryLink(link: GroupEntryLink): string {\n return `${PREFIX}/${link.g}/${link.host}`;\n}\n\n/** Where the link opens the web app: its join route. */\nexport function groupEntryUrl(origin: string, link: GroupEntryLink): string {\n return `${trimEndOf(origin, \"/\")}/#/join/${encodeGroupEntryLink(link)}`;\n}\n\n/**\n * A pasted link, a `/join/…` path or the bare code; null when it is none of them. Copied with the words around it\n * (\"Join our group: <https://…/join/group1/…>.\"), it is read as the token in it (`unwrapPasted`).\n */\nexport function decodeGroupEntryLink(input: string): GroupEntryLink | null {\n return readGroupEntryLink(input) ?? readGroupEntryLink(unwrapPasted(input));\n}\n\nfunction readGroupEntryLink(input: string): GroupEntryLink | null {\n const clean = input.trim().replace(/^.*#/, \"\").replace(/^.*?\\/join\\//, \"\").replace(/^\\/+/, \"\");\n const parts = clean.split(\"/\");\n if (parts.length !== 3 || parts[0] !== PREFIX) return null;\n const [, g, host] = parts;\n if (!GROUP_ID.test(g) || !MEMBER_KEY.test(host)) return null;\n try { publicKeyFromZ32(host); } catch { return null; }\n return { g, host };\n}\n\nfunction knockMaterial(link: GroupEntryLink, label: string): Uint8Array {\n return hkdf(sha256, publicKeyFromZ32(link.host), utf8Encode(link.g), info(label), 32);\n}\n\n/** The Pkarr identity every holder of the link can publish knocks under. */\nexport function knockIdentity(link: GroupEntryLink): Identity {\n return identityFromSeed(knockMaterial(link, \"knock seed\"));\n}\n\n/**\n * The knocks under the knock identity, sealed with a key from the link: a\n * relay sees an opaque value on a key it cannot tie to the group.\n */\nexport function knockRecords(link: GroupEntryLink, knocks: Knock[]): GhostRecord[] {\n const nonce = randomBytes(NONCE_LENGTH);\n const body = utf8Encode(JSON.stringify(knocks.slice(-MAX_KNOCKS).map(k => [k.key, k.ts])));\n const box = xchacha20poly1305(knockMaterial(link, \"knock key\"), nonce, utf8Encode(link.g)).encrypt(body);\n return [{ label: KNOCK_LABEL, value: toBase64Url(concatBytes(nonce, box)) }];\n}\n\n/** Knocks that open with the link's key and are well formed; anything else is nobody. */\nexport function readKnocks(link: GroupEntryLink, records: GhostRecord[]): Knock[] {\n const value = records.find(r => r.label === KNOCK_LABEL)?.value;\n if (!value || value.length > 900) return [];\n try {\n const bytes = fromBase64Url(value);\n const body = xchacha20poly1305(knockMaterial(link, \"knock key\"), bytes.slice(0, NONCE_LENGTH), utf8Encode(link.g)).decrypt(bytes.slice(NONCE_LENGTH));\n const parsed: unknown = JSON.parse(utf8Decode(body));\n if (!Array.isArray(parsed)) return [];\n return parsed.slice(0, MAX_KNOCKS).flatMap(entry => Array.isArray(entry) && typeof entry[0] === \"string\" && MEMBER_KEY.test(entry[0]) && Number.isSafeInteger(entry[1])\n ? [{ key: entry[0], ts: entry[1] as number }] : []);\n } catch { return []; }\n}\n\n/** The knocks to publish: mine refreshed, others' still fresh, newest last, at most `MAX_KNOCKS`. */\nexport function mergeKnocks(existing: Knock[], mine: Knock, now = Date.now()): Knock[] {\n const fresh = existing.filter(k => k.key !== mine.key && now - k.ts < KNOCK_TTL_MS && k.ts <= now + 60_000);\n return [...fresh.sort((a, b) => a.ts - b.ts).slice(-(MAX_KNOCKS - 1)), mine];\n}\n\n/**\n * The entry session between the admin's entry key and a joiner's member key:\n * the same derivation as a group edge, under a salt of its own, so it can\n * never be confused with an edge of the same group.\n */\nexport function entryParams(link: GroupEntryLink, mySeed: Uint8Array, myZ32: string, peerZ32: string): LinkParams {\n return edgeParams(`entry/${link.g}`, mySeed, myZ32, peerZ32);\n}\n","import { hkdf } from \"@noble/hashes/hkdf.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { pacer } from \"./appBundle\";\nimport { concatBytes, fromBase64Url, isZ32Key, randomBytes, toBase64Url, utf8Decode, utf8Encode } from \"./bytes\";\nimport { identityFromSeedB64, publicKeyFromZ32, sign, verify } from \"./identity\";\nimport { sanitizeNick, unwrapPasted } from \"./text\";\nimport {\n confirmationMatches, confirmationTag, decryptText, encryptText, epochKeys, groupCallKey, newEpochSecret, openPair, openSecret, sealPair, sealSecret, sha256Hex,\n type SealedSecret,\n} from \"./groupCrypto\";\nimport { engineError } from \"./engineErrors\";\nimport { GROUP_ADMIN_OFF_ERROR, GROUP_ID, OWN_FRAME_LIMIT, MEMBER_KEY, SAID_AGAIN, rememberAlone, rosterAdmin, rosterHas, sortRoster, type GroupRole, type Roster } from \"./groupCommits\";\nimport { mentionsBytes, validMentions, wireMentions, type GroupMention } from \"./groupMentions\";\nimport { groupReplyAuthor, readReply, wireReply, type WireReply } from \"./replies\";\nimport { readForwarded } from \"./forwards\";\nimport { cardEditNumber, readStatusCard, statusCardBytes, type StatusCard } from \"./statusCards\";\nimport { readGroupFileMeta, type GroupFileMeta } from \"./groupFiles\";\nimport { communityEditFrame, communityMessageAuthor, validEditText } from \"./groupEdits\";\nimport { RateWindow, validEditNumber, validRemovalNumber } from \"./pairedEdits\";\nimport { CATCH_UP_PAUSE_MS, CATCH_UP_SLICE, CatchUpAnswers, type CatchUpHandled } from \"./catchUp\";\nimport {\n encodeGroupMetaBody, groupDisplayName, groupMetaBody, groupMetaChange, groupMetaNewer, groupMetaPicture, groupMetaToHand, keepPastGroupMeta, nextGroupMetaRevision, groupMetaTag, groupName, openGroupMeta, parseGroupMetaFrame, parseGroupMetaTag, signGroupMeta, verifyGroupMetaSignature, wrapGroupMeta,\n type GroupMeta, type GroupMetaBody, type GroupMetaChange, type GroupMetaFrame, type GroupMetaStatement,\n} from \"./groupMeta\";\n\n/**\n * `group-community/1` (WISP 903 · Group Community): a group whose link is the way in, for hundreds\n * of members, where the admin need not be online for anyone to join.\n *\n * What differs from `group-mesh/1`:\n * - any member may commit `add` (admission) and `leave` (on the leaver's signed request); the admin\n * keeps `remove`, `role`, `rotate` and `link`;\n * - a commit carries the hash of the roster after it, not the roster, and members replay the chain;\n * - `add`, `role` and `link` derive the next epoch's secret from the previous one and the commit, so\n * only a newcomer is sent it; `leave`, `remove` and `rotate` get a fresh secret sealed to everyone;\n * - concurrent commits are a race with a deterministic winner, not a fork: the branch that keeps the\n * admin's changes (remove, role, rotate, link) since the common parent, then the longest, then the\n * lowest hash of the first commit after the common parent. The admin of the tip signing changes on\n * two branches (after the same commit or not) is still a fork and halts the group; a former admin\n * doing so on a branch from before its hand-over is refused, as a stale branch;\n * - messages name the commit of their epoch, so messages under a commit that lost stay readable;\n * every member keeps recent frames from everyone and re-sends them to whoever was away.\n *\n * Transport-agnostic, like `GroupSession`: frames go out through the hooks and come in through\n * `handle(from, frame)`, where `from` is the member key of the edge the frame arrived on (which\n * may be a hub relaying someone else's frame: everything relayed is signed by its author).\n */\nexport const COMMUNITY_PROFILE = \"group-community/1\" as const;\n\nexport const COMMUNITY_LIMITS = {\n members: 256,\n chain: 2048,\n textBytes: 16 * 1024,\n /**\n * An application frame the group carries (`x`: a payment note, a request to the group) or one member's\n * payload for another (`p`: a payment between the two), as JSON. Room for a Cashu token of many proofs,\n * sealed twice (to the member, then to the epoch) within a frame.\n */\n appBytes: 8 * 1024,\n /** Frames from everyone kept for whoever was away. */\n store: 256,\n /**\n * Application frames that say state rather than news (the admin's pin): the newest of each kind, kept past the\n * store (`CommunitySessionHooks.lasting`). A few kinds at most.\n */\n lasting: 8,\n storeBytes: 1024 * 1024,\n /** Epoch secrets kept (by commit), main branch and losing ones together. */\n secrets: 96,\n /** How far back a competing branch may start; older ones are refused and their authors commit again. */\n window: 64,\n /** Commits known off the main branch. */\n side: 512,\n /**\n * Of those, the branches one member's commit ends (its newest), and the commits it signed: a handful of races, and\n * one full run of its admissions (`memberAdmissions`, with the leaves among them). The admin's are not counted.\n */\n sideTips: 8,\n sideCommits: 64,\n /** Commits waiting for their parent. */\n pendingCommits: 64,\n /** Epoch secrets waiting for their commit. */\n pendingSecrets: 32,\n /** How long a commit waits for its parent, or a secret for its commit: many catch-ups; after it, a catch-up brings both again. */\n pendingMs: 120_000,\n waiting: 64,\n waitingBytes: 1024 * 1024,\n /**\n * Of those, the ones signed by a key no commit I know names (a newcomer whose admission has not come yet, or a key\n * anyone can make up): the newest only, they push out nobody else's, and they make no catch-up hurry.\n */\n waitingStrangers: 8,\n replay: 256,\n /** Commits in one welcome or chain piece. */\n chainPiece: 100,\n /** Admissions members other than the admin may commit in a row while the admin is away (`memberAdmissions`). */\n memberAdmissions: 32,\n /** Commits back in which a leave of a key a member let in counts against `memberAdmissions`, the admin there or not. */\n memberLeaves: 256,\n pendingLeaves: 64,\n /** Leaves whose mark (`group-left`) is kept, and the epochs one names. */\n leftMarks: 64,\n /**\n * Syncs of one member answered in `syncWindowMs`: each answer may carry the chain's tail, secrets and the whole\n * store. A member catching up asks every five seconds at most, and every member syncs every thirty; one asking more\n * waits for the window.\n */\n syncAnswers: 16,\n syncWindowMs: 60_000,\n /**\n * Messages of one member taken per `messageWindowMs`, and the bytes of their sealed bodies, past what one catch-up\n * answer holds (a whole store, and the lasting frames): anyone with the link is a member, and each message taken is a\n * row in every member's app and a frame each hub passes on. The rest are not taken now and come again in a catch-up\n * (`MessagePace`).\n */\n messagesPerAuthor: 30,\n messageBytesPerAuthor: 128 * 1024,\n messageWindowMs: 10_000,\n /**\n * Frames of one catch-up answer in a slice (`CommunitySessionHooks.handled`), two slices at most not handled yet by\n * the member's app: a member back after the store filled was handed 258 at once, and an app holds 64 waiting at most\n * before 2026-10-07 (more ends the session). As a private group's (`GROUP_LIMITS.catchUpSlice`).\n */\n catchUpSlice: CATCH_UP_SLICE,\n /** Between two slices, when the member's app cannot say it handled one (`handled` resolves `false`). */\n catchUpPauseMs: CATCH_UP_PAUSE_MS,\n /**\n * A message a member handed on with its live mark (`lv`, WISP 903 § Relaying) is live here only when the time it says\n * is at most this long before my clock: the mark is that member's word, and past this it would make a catch-up ring.\n */\n liveMarkMs: 10 * 60_000,\n} as const;\n\n/**\n * After I send a member my sync: how long what comes over its edge may be its answer (a catch-up, never `live`). Each\n * frame of the answer keeps it open, since it goes a slice at a time. As a private group's.\n */\nconst ANSWER_WINDOW_MS = 5_000;\n\n/**\n * After the admin role moved to me: how long I still take the statement of the admin I took it from (WISP 903\n * § Metadata), one that was on its way while the commit reached me first. Past it, condition 4 holds as for anyone.\n */\nexport const COMMUNITY_TAKEOVER_META_MS = 10 * 60_000;\n\n/** What every member should know about who can read what, and what the link does, in the words the apps show. */\nexport const GROUP_READ_NOTE_COMMUNITY = `Anyone with the group's link can join, and any member can let people in. Everyone in the group can read everything sent while they are a member; someone removed cannot read what comes after, someone who joins later cannot read what came before. Members who were away get the last ${COMMUNITY_LIMITS.store} messages from whoever is there when they return.`;\n\n/** A community group's link: `group2/<group id>/<entry key>` (web: `#/join/group2/…`). */\nexport function encodeCommunityLink(link: { g: string; host: string }): string { return `group2/${link.g}/${link.host}`; }\n/** A pasted link, a `/join/…` path or the bare code (or one in words: `unwrapPasted`); null when it is not a community group's link. */\nexport function decodeCommunityLink(input: string): { g: string; host: string } | null {\n return readCommunityLink(input) ?? readCommunityLink(unwrapPasted(input));\n}\n\nfunction readCommunityLink(input: string): { g: string; host: string } | null {\n const clean = input.trim().replace(/^.*#/, \"\").replace(/^.*?\\/join\\//, \"\").replace(/^\\/+/, \"\");\n const parts = clean.split(\"/\");\n if (parts.length !== 3 || parts[0] !== \"group2\" || !GROUP_ID.test(parts[1]) || !MEMBER_KEY.test(parts[2])) return null;\n try { publicKeyFromZ32(parts[2]); return { g: parts[1], host: parts[2] }; } catch { return null; }\n}\n\nexport type CommunityKind = \"create\" | \"add\" | \"leave\" | \"remove\" | \"role\" | \"rotate\" | \"link\";\nconst KINDS: CommunityKind[] = [\"create\", \"add\", \"leave\", \"remove\", \"role\", \"rotate\", \"link\"];\n/** Kinds whose epoch secret is fresh: they take someone out, or start or re-key the group. */\nconst FRESH: ReadonlySet<CommunityKind> = new Set([\"create\", \"leave\", \"remove\", \"rotate\"]);\n/**\n * Commits that make the membership history longer and the group no smaller. A committer signs one only while the\n * history keeps room for everyone else to get out after it: two commits a member (a leave or a remove is one, and a\n * leaving admin hands the role over first). The history is never compacted, and one that filled with people in it\n * took no leave, remove or handover any more. Its own rule: a history up to `COMMUNITY_LIMITS.chain` verifies as before.\n * A member takes in such a commit from someone else only when it keeps that room too (`receiveCommit`): an app that\n * does not keep it could otherwise fill the history for everyone.\n */\nconst GROWS: ReadonlySet<CommunityKind> = new Set([\"add\", \"rotate\", \"link\"]);\n/** Whether a history whose last commit is at `epoch`, with `roster` in it, still has room for everyone else to get out. */\nconst keepsRoom = (epoch: number, roster: Roster) => epoch + 1 + 2 * (roster.length - 1) <= COMMUNITY_LIMITS.chain;\n/**\n * Kinds only the admin commits. They are final: a branch that drops one never replaces the branch\n * that has it, however long, so no member can undo a removal, a hand-over, a rotation or a link change\n * by outgrowing it with admissions.\n */\nconst ADMIN_ONLY: ReadonlySet<CommunityKind> = new Set([\"remove\", \"role\", \"rotate\", \"link\"]);\n\n/**\n * The admissions signed by members other than `admin` on a branch (`before`: its commits, newest first) since the admin\n * last let someone in, rotated, changed the link or handed the role on, or since the group began. A removal or a leave\n * the admin commits does not count as the admin being there: its app commits leaves by itself, and a removal while\n * the admin clears keys let in would otherwise make room for as many more each time. An admission is a member's\n * right, and costs nothing: a key nobody holds is as good as anyone's, so without a bound one member could fill the\n * group to its cap in seconds. `COMMUNITY_LIMITS.memberAdmissions` in a row, then the admin's turn.\n * A leave among the last `COMMUNITY_LIMITS.memberLeaves` commits that ends an admission a member other than the admin\n * signed counts as one more, whether or not the admin was there since: the key leaves the roster as it was, and a\n * member that lets in keys it made up and commits their own leaves would otherwise fill the history with two commits\n * for each one the admin lets in at the door.\n */\nexport function memberAdmissions(admin: string | undefined, before: Iterable<CommunityCommit>): number {\n let n = 0, run = true, seen = 0;\n const leavers = new Set<string>();\n for (const c of before) {\n if (run && (c.k === \"create\" || c.k === \"role\" || (c.by === admin && c.k !== \"remove\" && c.k !== \"leave\"))) run = false;\n if (run && c.k === \"add\") n++;\n const recent = ++seen <= COMMUNITY_LIMITS.memberLeaves;\n if (c.k === \"add\" && c.s && leavers.delete(c.s) && c.by !== admin) n++;\n if (recent && c.k === \"leave\" && c.s) leavers.add(c.s);\n if (!run && !recent && !leavers.size) break;\n }\n return n;\n}\nconst MEMBER_ADMISSIONS_ERROR = \"Members can let no one else in until the admin does\";\n\nexport interface CommunityCommit {\n v: 2;\n g: string;\n e: number;\n /** Hash of the parent commit; empty for the genesis. */\n p: string;\n k: CommunityKind;\n /** SHA-256 (hex) of the canonical roster after this commit. */\n m: string;\n by: string;\n s?: string;\n /** Entry key (`create`, `link`); empty in a `link` turns the link off. */\n x?: string;\n /** Genesis nonce: the group id derives from it and the creator. */\n n?: string;\n /** The leaver's signature, in a `leave`. */\n ls?: string;\n /**\n * The leaver's signature over the admission the leave ends (`leaveStatement3`), in a `leave`. Outside the hash and\n * the committer's signature, which an app from before computes without it: it stands by the leaver's key alone.\n */\n ls3?: string;\n ts: number;\n c: string;\n sig: string;\n}\n\nconst HASH = /^[a-f0-9]{64}$/;\nconst TAG = /^[A-Za-z0-9_-]{43}$/;\nconst SIG = /^[A-Za-z0-9_-]{86}$/;\nconst NONCE = /^[A-Za-z0-9_-]{22}$/;\nconst B64 = /^[A-Za-z0-9_-]*$/;\n\nconst tuple = (c: Omit<CommunityCommit, \"sig\">, tag = c.c) =>\n JSON.stringify([2, c.g, c.e, c.p, c.k, c.m, c.by, c.s ?? \"\", c.x ?? \"\", c.n ?? \"\", c.ls ?? \"\", c.ts, tag]);\nexport function communityCommitHash(c: Omit<CommunityCommit, \"sig\">): string { return sha256Hex(utf8Encode(tuple(c))); }\nexport function communityUntaggedHash(c: Omit<CommunityCommit, \"sig\" | \"c\">): string { return sha256Hex(utf8Encode(tuple({ ...c, c: \"\" }, \"\"))); }\nexport const shortHash = (hash: string) => hash.slice(0, 16);\nexport function rosterHash(roster: Roster): string { return sha256Hex(utf8Encode(JSON.stringify(roster))); }\n\n/** The id of a community group: from its creator and a nonce, so no other genesis can claim it. */\nexport function communityGroupId(creator: string, nonce: string): string {\n return toBase64Url(sha256(concatBytes(utf8Encode(\"ghostly-group-community/1 id\"), publicKeyFromZ32(creator), fromBase64Url(nonce))).slice(0, 16));\n}\n\nexport const leaveStatement = (g: string, s: string) => utf8Encode(JSON.stringify([\"ghostly-group/2 leave\", g, s]));\n/** What the member who committed a leave (`h`) had heard of the leaver then: `e:h16` → its highest number there. */\nexport const leftStatement = (g: string, h: string, hi: Record<string, number>) =>\n utf8Encode(JSON.stringify([\"ghostly-group/2 left\", g, h, Object.entries(hi).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))]));\nconst LEFT_EPOCH = /^\\d{1,15}:[a-f0-9]{16}$/;\n/** A leave of one admission: `h` is the hash of the commit that last put `s` in the roster (its `add`, or the `create` it signed). */\nexport const leaveStatement3 = (g: string, s: string, h: string) => utf8Encode(JSON.stringify([\"ghostly-group/3 leave\", g, s, h]));\n\n/**\n * Whether a leave holds after `before` (the commits before it, newest first): its `ls3` names the commit that last\n * admitted the leaver, or, from an app that signs no such statement, no earlier leave carries its `ls`. `ls` says the\n * same for every admission of a member, so by itself it ends one admission only.\n */\nexport function leaveStands(leave: Pick<CommunityCommit, \"g\" | \"s\" | \"ls\" | \"ls3\">, before: Iterable<CommunityCommit>): boolean {\n if (!leave.s || !leave.ls) return false;\n let admitted = false;\n for (const c of before) {\n if (!admitted && ((c.k === \"add\" && c.s === leave.s) || (c.k === \"create\" && c.by === leave.s))) {\n admitted = true;\n if (leave.ls3 && SIG.test(leave.ls3) && verify(fromBase64Url(leave.ls3), leaveStatement3(leave.g, leave.s, communityCommitHash(c)), publicKeyFromZ32(leave.s))) return true;\n }\n if (c.k === \"leave\" && c.ls === leave.ls) return false;\n }\n return true;\n}\n\n/** The secret of an epoch that adds, re-roles or re-links: from the previous one and the commit. */\nexport function derivedSecret(previous: Uint8Array, untaggedHash: string): Uint8Array {\n return hkdf(sha256, previous, utf8Encode(untaggedHash), utf8Encode(\"ghostly-group/2 derived\"), 32);\n}\n\nfunction parseCommit(raw: unknown): CommunityCommit | null {\n if (!raw || typeof raw !== \"object\") return null;\n const c = raw as Record<string, unknown>;\n const key = (v: unknown) => typeof v === \"string\" && MEMBER_KEY.test(v);\n if (c.v !== 2 || typeof c.g !== \"string\" || !GROUP_ID.test(c.g) || !Number.isSafeInteger(c.e) || (c.e as number) < 0 ||\n typeof c.p !== \"string\" || (c.p !== \"\" && !HASH.test(c.p)) || !KINDS.includes(c.k as CommunityKind) ||\n typeof c.m !== \"string\" || !HASH.test(c.m) || !key(c.by) || (c.s !== undefined && !key(c.s)) ||\n (c.x !== undefined && !(c.x === \"\" || key(c.x))) || (c.n !== undefined && (typeof c.n !== \"string\" || !NONCE.test(c.n))) ||\n (c.ls !== undefined && (typeof c.ls !== \"string\" || !SIG.test(c.ls))) ||\n !Number.isSafeInteger(c.ts) || (c.ts as number) <= 0 || typeof c.c !== \"string\" || !TAG.test(c.c) || typeof c.sig !== \"string\" || !SIG.test(c.sig)) return null;\n const out: CommunityCommit = { v: 2, g: c.g, e: c.e as number, p: c.p, k: c.k as CommunityKind, m: c.m, by: c.by as string, ts: c.ts as number, c: c.c, sig: c.sig };\n if (c.s !== undefined) out.s = c.s as string;\n if (c.x !== undefined) out.x = c.x as string;\n if (c.n !== undefined) out.n = c.n as string;\n if (c.ls !== undefined) out.ls = c.ls as string;\n // Not under the commit's hash or signature: one that is not a leave's, or not a signature, is as if absent.\n if (out.k === \"leave\" && typeof c.ls3 === \"string\" && SIG.test(c.ls3)) out.ls3 = c.ls3;\n return out;\n}\n\n/**\n * The roster a commit of this kind makes of the previous one; null when it is not allowed. `trusted`: the commit was\n * verified when it was accepted (a replay of the stored main branch), so a leave's statement is not checked again.\n */\nexport function communityRoster(previous: Roster | null, c: Pick<CommunityCommit, \"k\" | \"by\" | \"s\" | \"x\" | \"n\" | \"ls\" | \"g\">, trusted = false): Roster | null {\n if (c.k === \"create\") return previous === null && !c.s && !!c.x && !!c.n ? [[c.by, \"admin\"]] : null;\n if (!previous || !rosterHas(previous, c.by)) return null;\n const admin = rosterAdmin(previous);\n switch (c.k) {\n case \"add\":\n if (!c.s || c.x !== undefined || rosterHas(previous, c.s) || previous.length >= COMMUNITY_LIMITS.members) return null;\n return sortRoster([...previous, [c.s, \"member\"]]);\n case \"leave\":\n if (!c.s || c.s === c.by || c.s === admin || !rosterHas(previous, c.s) || !c.ls) return null;\n if (!trusted && !verify(fromBase64Url(c.ls), leaveStatement(c.g, c.s), publicKeyFromZ32(c.s))) return null;\n return previous.filter(([k]) => k !== c.s);\n case \"remove\":\n if (c.by !== admin || !c.s || c.s === c.by || !rosterHas(previous, c.s)) return null;\n return previous.filter(([k]) => k !== c.s);\n case \"role\":\n if (c.by !== admin || !c.s || c.s === c.by || !rosterHas(previous, c.s)) return null;\n return previous.map(([k]) => [k, k === c.s ? \"admin\" : \"member\"] as [string, GroupRole]);\n case \"rotate\":\n return c.by === admin && !c.s && c.x === undefined ? previous : null;\n case \"link\":\n return c.by === admin && !c.s && c.x !== undefined ? previous : null;\n default:\n return null;\n }\n}\n\n/**\n * One commit against its parent (null for a genesis) and the parent's roster: shape, id, link,\n * authority, roster arithmetic, roster hash and signature. The confirmation tag is checked once\n * the secret is known (a derived kind's on arrival, by a member holding the parent's: `receiveCommit`). `before`: the commits before it on its branch, newest first; given, a `leave` is held to the\n * admission it ends (`leaveStands`). A member gives it for every commit it takes in after its own admission; the chain\n * of a welcome is not held to it (`verifyCommunityChain`).\n */\nexport function verifyCommunityCommit(raw: unknown, parent: CommunityCommit | null, parentRoster: Roster | null, groupId?: string, before?: Iterable<CommunityCommit>): { commit: CommunityCommit; roster: Roster } | { error: string } {\n const commit = parseCommit(raw);\n if (!commit) return { error: \"Malformed membership commit\" };\n if (groupId && commit.g !== groupId) return { error: \"Commit for another group\" };\n if (parent) {\n if (commit.g !== parent.g) return { error: \"Commit for another group\" };\n if (commit.e !== parent.e + 1) return { error: \"Commit out of sequence\" };\n if (commit.e >= COMMUNITY_LIMITS.chain) return { error: \"Membership chain too long\" };\n if (commit.p !== communityCommitHash(parent)) return { error: \"Commit does not follow its parent\" };\n } else {\n if (commit.e !== 0 || commit.p !== \"\" || commit.k !== \"create\") return { error: \"The chain does not start with the creation of the group\" };\n if (communityGroupId(commit.by, commit.n ?? \"\") !== commit.g) return { error: \"The group id is not this genesis's\" };\n }\n if (commit.k !== \"create\" && commit.n !== undefined) return { error: \"Malformed membership commit\" };\n if (commit.k !== \"leave\" && commit.ls !== undefined) return { error: \"Malformed membership commit\" };\n const roster = communityRoster(parent ? parentRoster : null, commit);\n if (!roster) return { error: \"Unauthorized or inconsistent membership change\" };\n if (commit.k === \"leave\" && before && !leaveStands(commit, before)) return { error: \"This leave is not for the member's current admission\" };\n if (rosterHash(roster) !== commit.m) return { error: \"The roster hash does not match the change\" };\n if (!verify(fromBase64Url(commit.sig), utf8Encode(tuple(commit)), publicKeyFromZ32(commit.by))) return { error: \"Membership commit signature is invalid\" };\n return { commit, roster };\n}\n\n/**\n * A whole chain from its genesis; the rosters after each commit and the entry key at the end. What a newcomer is\n * handed: a `leave` in it is not held to the admission it ends, since a chain from before 2026-10-10 may hold a\n * member's second leave under the one statement there was, and no newcomer could enter that group again.\n */\nexport function verifyCommunityChain(raw: unknown, groupId?: string): VerifiedChain | { error: string } {\n const check = checkChain(raw, groupId);\n for (;;) { const step = check.next(); if (step.done) return step.value; }\n}\n\n/**\n * `verifyCommunityChain` for a client whose engine shares its page's thread: the same checks, letting the thread go every\n * `CHAIN_SLICE_MS` of them. One commit's signature takes ~2.6 ms in JavaScript on a desktop CPU, several times that on a\n * phone, so a history near `COMMUNITY_LIMITS.chain` checked at once was an app that drew nothing for 5 s and more.\n */\nexport async function verifyCommunityChainPaced(raw: unknown, groupId?: string): Promise<VerifiedChain | { error: string }> {\n const check = checkChain(raw, groupId), pause = pacer(CHAIN_SLICE_MS);\n for (;;) { const step = check.next(); if (step.done) return step.value; await pause(); }\n}\n\n/** `verifyCommunityChainPaced` checks commits for this long at most before it lets the thread go. */\nconst CHAIN_SLICE_MS = 5;\n/** A fresh epoch's secret is sealed to members for this long at most before the thread goes (`CommunitySession.commit`). */\nconst SEAL_SLICE_MS = 5;\n\ntype VerifiedChain = { chain: CommunityCommit[]; roster: Roster; entry: string; rosters: Roster[] };\n\n/** The chain's checks, one commit per step. */\nfunction* checkChain(raw: unknown, groupId?: string): Generator<void, VerifiedChain | { error: string }> {\n if (!Array.isArray(raw) || raw.length === 0 || raw.length > COMMUNITY_LIMITS.chain) return { error: \"Malformed membership chain\" };\n const chain: CommunityCommit[] = [], rosters: Roster[] = [];\n let entry = \"\";\n for (const entryRaw of raw) {\n const result = verifyCommunityCommit(entryRaw, chain[chain.length - 1] ?? null, rosters[rosters.length - 1] ?? null, groupId);\n if (\"error\" in result) return result;\n chain.push(result.commit); rosters.push(result.roster);\n if (result.commit.x !== undefined) entry = result.commit.x;\n yield;\n }\n return { chain, roster: rosters[rosters.length - 1], entry, rosters };\n}\n\n// -- frames ---------------------------------------------------------------------------------------\n\nexport interface CommunityMessageFrame { t: \"group-msg\"; v: 2; g: string; e: number; h: string; s: string; n: number; ts: number; nn: string; c: string; sig: string }\nexport interface CommunityCommitFrame { t: \"group-commit\"; v: 2; g: string; commit: CommunityCommit }\n/** An epoch secret sealed to one member (`to`): relayed by hubs to whoever holds that member's edge. */\nexport interface CommunitySecretFrame { t: \"group-secret\"; v: 2; g: string; to: string; h: string; s: SealedSecret }\nexport interface CommunitySecretsFrame { t: \"group-secrets\"; v: 2; g: string; secrets: { h: string; s: SealedSecret }[] }\n/** `loc`: hashes of my branch at 1, 2, 4, 8… commits back from my tip, so whoever is on another branch finds where we part. */\nexport interface CommunitySyncFrame { t: \"group-sync\"; v: 2; g: string; e: number; h: string; loc?: string[]; have: Record<string, Record<string, number>>; secrets: string[]; mt?: string }\nexport interface CommunityLeaveFrame { t: \"group-leave\"; v: 2; g: string; s: string; ls: string; ls3?: string }\n/**\n * The mark of a leave (`h`, the commit's full hash), signed by the member who committed it: how far it had heard the\n * leaver in each epoch. What the leaver wrote past it is not taken (WISP 903 § Leaving and removal).\n */\nexport interface CommunityLeftFrame { t: \"group-left\"; v: 2; g: string; h: string; hi: Record<string, number>; sig: string }\n/** The seed of the link's current entry key, sealed to one member: after a `link` commit, or at a sync. */\nexport interface CommunityEntryFrame { t: \"group-entry\"; v: 2; g: string; to: string; x: string; s: SealedSecret }\nexport interface CommunityInviteFrame { t: \"group-invite\"; v: 2; g: string; name: string; admin: string; e: number; n: number }\nexport interface CommunityChainFrame { t: \"group-chain\"; v: 2; g: string; commits: CommunityCommit[] }\nexport interface CommunityWelcomeFrame {\n t: \"group-welcome\"; v: 2; g: string; name: string; commits: CommunityCommit[];\n secrets: { h: string; s: SealedSecret }[]; rv: SealedSecret; entry: SealedSecret;\n}\nexport type CommunityFrame = CommunityMessageFrame | CommunityCommitFrame | CommunitySecretFrame | CommunitySecretsFrame | CommunitySyncFrame | CommunityLeaveFrame | CommunityLeftFrame | CommunityEntryFrame | GroupMetaFrame;\n\nexport type CommunityStatus = \"active\" | \"left\" | \"removed\" | \"forked\" | \"lost\";\n\nexport interface CommunityState {\n id: string;\n name: string;\n profile: typeof COMMUNITY_PROFILE;\n seedB64: string;\n createdAt: number;\n /** The branch followed, from the genesis. */\n chain: CommunityCommit[];\n /** Commits known off it, within the window: losing branches, or a better one being assembled. */\n side: CommunityCommit[];\n /** Commit hash (full) → epoch secret (base64url). */\n secrets: Record<string, string>;\n /** The group's link: its entry key and seed (every member holds the seed); empty key when off. */\n entry: { key: string; seedB64: string };\n /** Rendezvous secret: the beacon and lobbies derive from it. */\n rv: string;\n status: CommunityStatus;\n statusReason?: string;\n /** My next sequence number under the commit `seqH` (full hash). */\n seq: number;\n seqH: string;\n /**\n * Sender → `e:h16` → highest seen and the window below it. `gap`: the lowest number missing below it, how many syncs\n * asked for it and when the last did (`haveOf`); `floor`: what is missing at or below it is given up.\n */\n seen: Record<string, Record<string, { high: number; window: number[]; gap?: [number, number, number]; floor?: number }>>;\n nicks: Record<string, string>;\n /** Recent frames from everyone (mine included), oldest first. */\n store: CommunityMessageFrame[];\n /**\n * Kind → the newest application frame of that kind that says the group's state (`CommunitySessionHooks.lasting`),\n * kept when the store rolls past it, and handed with a catch-up to a member who lacks it. Absent in older states.\n */\n lasting?: Record<string, CommunityMessageFrame>;\n /**\n * Frames of mine no edge took when I said them (none was up), as `e:h16:n`, oldest first: the first member I reach\n * may have joined after I sealed them, and carries them all the same (see `receiveSync`). Absent in older states.\n */\n unheard?: string[];\n /**\n * Frames of mine no edge took when I said them, kept until they were looked at for saying again under a newer\n * commit (`resealBehind`), as `e:h16:n`, oldest first. Unlike `unheard`, handing one on does not take it out.\n * Absent in older states.\n */\n alone?: string[];\n /**\n * My texts saved here (counter, frame in `store`) whose message row may not be stored or whose frame may not have gone\n * yet, as `e:h16:n`, oldest first: an app killed in between stores and says them when it opens again (`resume`), so the\n * number is never given to another text. Absent in older states.\n */\n unsaid?: string[];\n /** Leave requests waiting for a member to commit them. */\n pendingLeaves: { s: string; ls: string; ls3?: string }[];\n /** Leave commit (full hash) → its mark, as its committer signed it (`group-left`), oldest first. Absent in older states. */\n left?: Record<string, { hi: Record<string, number>; sig: string }>;\n /** The group's metadata (its picture), as the admin last signed it and I accepted it. */\n meta?: GroupMeta;\n /** A few statements I held before `meta`, oldest first, for a member back from away (`keepPastGroupMeta`). Absent in older states. */\n metaPast?: GroupMeta[];\n}\n\n/**\n * `frame`: the frame the message came in, as it is kept to hand on to a member who missed it (without a live mark). An\n * app may keep it with the message it stores.\n * `live`: it came as it was written (revision 2026-11-03): straight from its author over the author's own edge, not in\n * the author's answer to my sync and not one that waited for a commit or a secret; or handed on at once by the member\n * at the other end of the edge, whose live mark names itself (`lv`), the time it says at most `liveMarkMs` before my\n * clock. How long it took then says how far the author's clock is from mine.\n */\nexport interface CommunityIncomingMessage { id: string; sender: string; epoch: number; seq: number; timestamp: number; text: string; mentions?: GroupMention[]; reply?: WireReply; forwarded?: number; card?: StatusCard; file?: GroupFileMeta; frame?: CommunityMessageFrame; live?: true }\n/**\n * What an application sends through the group rather than as text: `frame` for everyone in the epoch (the group\n * reads it, as it reads text), or, in `pair`, a payload only `to` can open. Delivered once, like a message: the\n * frame identity (sender, epoch, commit, sequence) deduplicates it across hubs and catch-ups.\n */\nexport interface CommunityIncomingApp { id: string; sender: string; epoch: number; timestamp: number; frame: Record<string, unknown> }\nexport interface CommunityIncomingPair { id: string; sender: string; epoch: number; timestamp: number; payload: Record<string, unknown> }\n\nexport interface CommunitySessionHooks {\n save(state: CommunityState): Promise<void>;\n /** To everyone this member has an edge to (hubs relay it on). Returns how many edges took it; nothing when the host does not say. */\n broadcast(frame: CommunityFrame): number | void;\n /** To the member at the other end of an edge, if there is one: `false` when the edge did not take it. */\n direct(to: string, frame: CommunityFrame): boolean | void;\n /** To one member, wherever they are: over their edge if I have it, else to the hubs with `to`. */\n addressed(to: string, frame: CommunitySecretFrame | CommunityEntryFrame): void;\n /** `true`: the app stored the message's `frame` with it, durably, so the saved state need not carry that frame. */\n message(message: CommunityIncomingMessage): Promise<boolean | void> | boolean | void;\n /** A frame the app holds with its message (`id`) is no longer kept to hand on: newer ones took its place, or I am out. */\n forgetFrame?(id: string): void;\n /**\n * Whether an application frame (mine or a member's) says the group's state rather than news, and of which kind: the\n * newest frame of each kind is kept past the store and handed with every catch-up to a member who lacks it, however\n * much was said since (a pin, which travels once: a member away past 256 frames never got it, agents#1095).\n * Undefined for anything else. Asked once the frame is read, before the `app` hook.\n */\n lasting?(message: CommunityIncomingApp): string | undefined;\n /**\n * Whether an application frame (mine or a member's) is only a hint (a `group-have`, WISP 503): relayed live like any\n * frame, but never kept, so it takes no place among those a member back from away gets.\n */\n fleeting?(frame: Record<string, unknown>): boolean;\n /** An application frame for the group (see `sendApp`). */\n app?(message: CommunityIncomingApp): Promise<void> | void;\n /** A payload another member sealed to me (see `sendPair`). Payloads to others are carried, never opened. */\n pair?(message: CommunityIncomingPair): Promise<void> | void;\n changed(): void;\n /**\n * The group's name or picture changed (set, replaced or removed), by `by`, in a statement signed at `at`. `by` is\n * undefined when the signer may only have signed again what an admin before them set (`metaAuthor`).\n */\n metaChanged?(by: string | undefined, change: GroupMetaChange, at: number): void;\n /** A frame that waited here (a commit ahead of its parent) and is now placed: a hub passes it on. */\n relay?(frame: CommunityFrame): void;\n /** The engine's clock, for how often a member is asked for what I lack (defaults to Date.now). */\n clock?(): number;\n /**\n * The lowest sequence number this member sends at, under any head (WISP 06 § Raised counters): 0 for a profile that\n * never took over or was never restored. A copy started from older state sends above every number the copy it\n * replaced may have used, so the other members do not drop its frames as already seen. The beacon packs the number\n * in 32 bits, so a floor stays well under 2^32.\n */\n seqFloor?(): number;\n /**\n * Whether this device may sign commits for the group (WISP 06 § Forced takeover): false after a forced takeover or a\n * restore, until the person turns on \"Manage groups from this device\" there. Then no commit is signed: no admission\n * at the door, no leave committed for another member, no admin change. Absent: true.\n */\n adminWork?(): boolean;\n /**\n * Whether a fresh turn read says this device is the active one (WISP 06 § When a device checks), asked before every\n * commit: two devices that both think they are active would each commit after one parent. No: the commit is refused\n * (`groupTurnUnconfirmed`), and leave requests wait for the next try. Absent: yes.\n */\n adminTurn?(): Promise<boolean>;\n /**\n * Resolves once the member's app handled every frame sent to it so far (it answers a ping in the order frames come),\n * or `false` when it cannot tell (no session, or an app that answers no ping): a catch-up answer then waits\n * `COMMUNITY_LIMITS.catchUpPauseMs` between slices; `\"late\"` when it answers pings but has not handled them yet, and\n * the answer asks again. Absent: an answer goes all at once, as before 2026-10-07.\n */\n handled?(to: string): Promise<CatchUpHandled>;\n /**\n * Whether message `id` was deleted for everyone (WISP 400 § Delete for everyone), by its author or here: a frame of it\n * that comes (a catch-up, a hub passing it on) is not taken, kept or passed on. Absent: none is.\n */\n removed?(id: string): boolean;\n}\n\nconst MAX_TEXT_BOX = Math.ceil((COMMUNITY_LIMITS.textBytes + 256 + 16) * 4 / 3) + 4;\nconst secretAad = (g: string, h: string, member: string) => JSON.stringify([\"ghostly-group/2 secret\", g, h, member]);\nconst rvAad = (g: string, member: string) => JSON.stringify([\"ghostly-group/2 rendezvous\", g, member]);\nconst entryAad = (g: string, member: string) => JSON.stringify([\"ghostly-group/2 entry\", g, member]);\nconst messageAad = (f: Pick<CommunityMessageFrame, \"g\" | \"e\" | \"h\" | \"s\" | \"n\" | \"ts\">) => JSON.stringify([f.g, f.e, f.h, f.s, f.n, f.ts]);\n/** A pair payload is bound to the frame that carries it, and to whom it is for. */\nconst pairAad = (f: Pick<CommunityMessageFrame, \"g\" | \"e\" | \"h\" | \"s\" | \"n\" | \"ts\">, to: string) => JSON.stringify([\"ghostly-group/2 pair\", f.g, f.e, f.h, f.s, f.n, f.ts, to]);\nconst isObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === \"object\" && !Array.isArray(v);\nconst messageSigned = (f: Omit<CommunityMessageFrame, \"sig\" | \"t\" | \"v\">) => utf8Encode(JSON.stringify([\"ghostly-group/2 msg\", f.g, f.e, f.h, f.s, f.n, f.ts, f.nn, f.c]));\nexport const communityMessageId = (sender: string, epoch: number, h: string, seq: number) => `${sender}:${epoch}:${h}:${seq}`;\nconst seenKey = (e: number, h: string) => `${e}:${h}`;\n\n/**\n * One member's messages taken: a whole catch-up answer at once (`MESSAGE_BURST`), then\n * `COMMUNITY_LIMITS.messagesPerAuthor` and `messageBytesPerAuthor` per `messageWindowMs`. One not taken is not marked\n * seen, so a catch-up hands it again; until it is taken, those after it under the same commit (`seenKey`) are not taken\n * either: a later one taken would say I have everything up to it (`syncFrame`'s `have`) and the one before would never\n * be handed again. A place that moves no more for `COMMUNITY_LIMITS.pendingMs` (no catch-up holds it any longer) is let go.\n */\nconst MESSAGE_BURST = { frames: COMMUNITY_LIMITS.store + COMMUNITY_LIMITS.lasting, bytes: COMMUNITY_LIMITS.storeBytes + COMMUNITY_LIMITS.lasting * COMMUNITY_LIMITS.textBytes * 2 };\nclass MessagePace {\n private frames: number = MESSAGE_BURST.frames;\n private bytes: number = MESSAGE_BURST.bytes;\n private at: number | undefined;\n private held = new Map<string, { low: number; top: number; at: number }>();\n\n take(key: string, n: number, bytes: number, now: number): boolean {\n let held = this.held.get(key);\n if (held && now - held.at >= COMMUNITY_LIMITS.pendingMs) { this.held.delete(key); held = undefined; }\n if (held && n > held.low) { held.top = Math.max(held.top, n); return false; }\n const elapsed = Math.max(0, now - (this.at ?? now)) / COMMUNITY_LIMITS.messageWindowMs;\n this.at = now;\n this.frames = Math.min(MESSAGE_BURST.frames, this.frames + elapsed * COMMUNITY_LIMITS.messagesPerAuthor);\n this.bytes = Math.min(MESSAGE_BURST.bytes, this.bytes + elapsed * COMMUNITY_LIMITS.messageBytesPerAuthor);\n if (this.frames < 1 || this.bytes < bytes) {\n if (held) held.low = n;\n else this.held.set(key, { low: n, top: n, at: now });\n return false;\n }\n this.frames -= 1; this.bytes -= bytes;\n if (held && n === held.low) {\n if (held.top > n) { held.low = n + 1; held.at = now; }\n else this.held.delete(key);\n }\n return true;\n }\n}\n/** One of a member's frames, among its own. */\nconst frameKey = (f: { e: number; h: string; n: number }) => `${f.e}:${f.h}:${f.n}`;\n/** A frame among everyone's: each member counts its own `n`, so `frameKey` alone tells only one member's frames apart. */\nconst storeKey = (f: { s: string; e: number; h: string; n: number }) => `${f.s}:${frameKey(f)}`;\n/** Frames of mine remembered as not heard by anyone yet. */\nconst UNHEARD_KEPT = 64;\n/** A new link's entry seed is sealed to members for this long at most before the thread goes (`replaceLink`). */\nconst ENTRY_SLICE_MS = 5;\n/**\n * Where a frame said again under a newer commit was first said (`o`, WISP 903 § Messages and catch-up): its commit's\n * epoch and short hash and its number there. Never the frame's own place, nor a later epoch than its own.\n */\nfunction readOriginal(o: unknown, frame: { e: number; h: string }): { e: number; h: string; n: number } | null {\n if (!o || typeof o !== \"object\" || Array.isArray(o)) return null;\n const { e, h, n } = o as Record<string, unknown>;\n if (!Number.isSafeInteger(e) || (e as number) < 0 || (e as number) > frame.e || typeof h !== \"string\" || !/^[a-f0-9]{16}$/.test(h) || !Number.isSafeInteger(n) || (n as number) < 0) return null;\n if (e === frame.e && h === frame.h) return null;\n return { e: e as number, h, n: n as number };\n}\n/** Syncs that ask for a sender's missing frame, at least `GAP_ASK_MS` apart, before it is given up (`haveOf`). */\nconst GAP_ASKS = 3;\nconst GAP_ASK_MS = 5_000;\n/** Whether a frame, by its identity, is one this state took already (or is too old to be taken again). */\nfunction seenIn(seen: CommunityState[\"seen\"], f: { s: string; e: number; h: string; n: number }): boolean {\n const entry = seen[f.s]?.[seenKey(f.e, f.h)];\n if (!entry || f.n > entry.high) return false;\n if (f.n <= entry.high - COMMUNITY_LIMITS.replay) return true;\n return f.n === entry.high || entry.window.includes(f.n);\n}\n/**\n * Whether a stored community state holds the frame a beacon's head names (WISP 903 § Head), read without running\n * the group: its own frame, one it took, or one of an epoch so far behind its own that it would not be taken now.\n */\nexport function communityHasFrame(state: Pick<CommunityState, \"seen\" | \"seedB64\" | \"chain\">, f: { s: string; e: number; h: string; n: number }): boolean {\n if (f.s === identityFromSeedB64(state.seedB64).pubKeyZ32) return true;\n const epoch = state.chain.length ? state.chain[state.chain.length - 1].e : 0;\n if (f.e < epoch - COMMUNITY_LIMITS.window) return true;\n return seenIn(state.seen, f);\n}\n\nfunction isSealed(v: unknown): v is SealedSecret {\n return !!v && typeof v === \"object\" && [\"e\", \"n\", \"c\"].every(k => typeof (v as Record<string, unknown>)[k] === \"string\" && B64.test((v as Record<string, string>)[k]) && (v as Record<string, string>)[k].length <= 128);\n}\nconst COMMIT_HASH = /^[0-9a-f]{64}$/;\n/**\n * A `group-secret` or `group-entry` frame a hub routes for another member, rebuilt from its known fields when each has\n * its real shape: what a hub remembers and hands on is no bigger than a real one. Null for anything else.\n */\nexport function routedCommunityFrame(raw: Record<string, unknown>): CommunitySecretFrame | CommunityEntryFrame | null {\n const { t, v, g, to, s } = raw;\n if (v !== 2 || typeof g !== \"string\" || !GROUP_ID.test(g) || !MEMBER_KEY.test(to) || !isSealed(s)) return null;\n const sealed = { e: s.e, n: s.n, c: s.c };\n if (t === \"group-secret\" && typeof raw.h === \"string\" && COMMIT_HASH.test(raw.h)) return { t, v, g, to, h: raw.h, s: sealed };\n if (t === \"group-entry\" && isZ32Key(raw.x)) return { t, v, g, to, x: raw.x, s: sealed };\n return null;\n}\n/** A welcome's shape and the whole chain it and the pieces before it carry, not yet checked (`CommunitySession.join`). */\nfunction readWelcome(link: { g: string }, pieces: unknown[], welcome: unknown): { welcome: Record<string, unknown>; commits: unknown[] } | { error: string } {\n if (!welcome || typeof welcome !== \"object\") return { error: \"Malformed welcome\" };\n const w = welcome as Record<string, unknown>;\n if (w.t !== \"group-welcome\" || w.v !== 2 || w.g !== link.g || !Array.isArray(w.commits) || !Array.isArray(w.secrets) || !isSealed(w.rv) || !isSealed(w.entry)) return { error: \"Malformed welcome\" };\n const commits = [...pieces.flatMap(p => (p && typeof p === \"object\" && Array.isArray((p as CommunityChainFrame).commits)) ? (p as CommunityChainFrame).commits : []), ...w.commits];\n if (commits.length > COMMUNITY_LIMITS.chain) return { error: \"Membership chain too long\" };\n return { welcome: w, commits };\n}\n/** A pair payload's box: an ephemeral key, a nonce and a ciphertext of at most `appBytes` sealed. */\nconst MAX_PAIR_BOX = Math.ceil((COMMUNITY_LIMITS.appBytes + 16) * 4 / 3) + 4;\nfunction isPairBox(v: Record<string, unknown>): v is Record<string, unknown> & SealedSecret & { to: string } {\n return typeof v.to === \"string\" && MEMBER_KEY.test(v.to) && typeof v.e === \"string\" && v.e.length === 43 && B64.test(v.e) &&\n typeof v.n === \"string\" && v.n.length === 32 && B64.test(v.n) && typeof v.c === \"string\" && v.c.length <= MAX_PAIR_BOX && B64.test(v.c);\n}\nfunction isMessageFrame(v: unknown): v is CommunityMessageFrame {\n if (!v || typeof v !== \"object\") return false;\n const f = v as Record<string, unknown>;\n return f.t === \"group-msg\" && f.v === 2 && typeof f.g === \"string\" && GROUP_ID.test(f.g) && Number.isSafeInteger(f.e) && (f.e as number) >= 0 &&\n typeof f.h === \"string\" && /^[a-f0-9]{16}$/.test(f.h) && typeof f.s === \"string\" && MEMBER_KEY.test(f.s) && Number.isSafeInteger(f.n) && (f.n as number) >= 0 &&\n Number.isSafeInteger(f.ts) && (f.ts as number) > 0 && typeof f.nn === \"string\" && f.nn.length === 32 && B64.test(f.nn) &&\n typeof f.c === \"string\" && f.c.length <= MAX_TEXT_BOX && B64.test(f.c) && typeof f.sig === \"string\" && f.sig.length === 86 && B64.test(f.sig);\n}\n/** A message frame's own fields alone: whatever else came beside them is outside its author's signature, so no member's word, and is neither kept nor handed on. */\nfunction messageFields(f: CommunityMessageFrame): CommunityMessageFrame {\n const { t, v, g, e, h, s, n, ts, nn, c, sig } = f;\n return { t, v, g, e, h, s, n, ts, nn, c, sig };\n}\n\n/**\n * One member's view of a community group: the branch it follows and the ones it knows, the\n * secrets it holds, what it has seen, and the recent frames it keeps for others.\n */\nexport class CommunitySession {\n readonly state: CommunityState;\n private readonly identity;\n /** Commit hash → commit, for everything known (main and side). */\n private known = new Map<string, CommunityCommit>();\n /** Commit hash → roster after it, for the window of the main branch and the side commits. */\n private rosters = new Map<string, Roster>();\n /**\n * Who was in the roster after each main-branch commit, from one replay of the branch: key → the places where it came in\n * and went out, in turn (an open last span while it is in). `through` commits are counted, the last one `top`.\n */\n private spans = { through: 0, top: \"\", roster: null as Roster | null, byKey: new Map<string, number[]>() };\n private mainIndex = new Map<string, number>();\n private pendingCommits = new Map<string, { from: string; commit: CommunityCommit; at: number }>();\n private pendingSecrets = new Map<string, { sealed: SealedSecret; at: number }>();\n private waiting: { from: string; frame: CommunityMessageFrame; stranger: boolean }[] = [];\n private waitingBytes = 0;\n private asked = new Map<string, number>();\n /** Per member: until when what comes over its edge may be its answer to my sync (`ANSWER_WINDOW_MS`). In memory only. */\n private readonly answering = new Map<string, number>();\n /**\n * Per member asked: what my sync said I have (`have`), the highest number its answer handed per author and commit\n * (`top`), and whether anything of the answer came (`heard`). Once the answer is over (`settleGaps`), what it did\n * not fill below those is nobody's to hand (a hint, never kept; a frame out of every store). In memory only.\n */\n private readonly answerOf = new Map<string, { have: Record<string, Record<string, number>>; top: Record<string, Record<string, number>>; heard: boolean }>();\n /** Author → `e:h16` → the number up to which a gap is gone (`settleGaps`), not on its way: `missing` leaves it out. In memory only. */\n private readonly gapsGone: Record<string, Record<string, number>> = {};\n /** The message frames given to `handle` that came live here (`CommunityIncomingMessage.live`): `passOn` marks them. */\n private readonly cameLive = new WeakSet<object>();\n /** Syncs answered per member, a few a minute (`COMMUNITY_LIMITS.syncAnswers`). In memory only. */\n private syncsAnswered = new Map<string, RateWindow>();\n /** Messages taken per author, a few a second (`MessagePace`). In memory only. */\n private messagePace = new Map<string, MessagePace>();\n /** The entry seed sealed to each member, for the seed it seals (`entryFrame`): every sync answer carries it. In memory only. */\n private sealedEntries = new Map<string, { seedB64: string; frame: CommunityEntryFrame }>();\n /** Catch-up answers still going out, a slice at a time (`receiveSync`). */\n private readonly answers: CatchUpAnswers<CommunityFrame>;\n private queue = Promise.resolve();\n /** When the commit I follow last changed (`adopt`), by `hooks.clock`. */\n private chainMovedAt = 0;\n /** My frames said again in this run (`e:h16:n`) → the id of the message they first were. In memory only. */\n private resealedFrom = new Map<string, string>();\n private saveTimer: ReturnType<typeof setTimeout> | undefined;\n /** 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. */\n private pendingMeta: { admin?: WaitingMeta; other?: WaitingMeta } = {};\n /** The admin as of the last `metaFollowsChain`. In memory only. */\n private adminSeen: string | undefined;\n /**\n * After the admin role moved to me (`metaFollowsChain`): whom from, until when I take their statement, and the last\n * one of theirs I signed again (what I held then, until one of theirs comes). `vouched`: the latest of theirs another\n * member's sync said it holds; `held`: the latest of theirs no other member has shown it holds yet. In memory only.\n */\n private takeover: { from: string; until: number; base: GroupMeta | undefined; vouched?: { e: number; r: number }; held?: { from: string; raw: unknown; s: GroupMetaStatement } } | undefined;\n /** The store's frames the app holds with their messages (`storeKey` → message id): in memory here, not in what is saved. */\n private readonly onRows = new Map<string, string>();\n /** The oldest epoch whose seen marks are kept, as of the last `pruneSeen`. In memory only. */\n private seenFrom = -1;\n /** The secret of the epoch I left in (`leave`), for `followAfterLeave`. In memory only. */\n private leftSecret: { h: string; s: string } | undefined;\n /** After my leave, still taking commits and secrets (`followAfterLeave`). In memory only. */\n private following = false;\n\n /** `rows`: the frames the app holds with the messages it stored (`CommunityIncomingMessage.frame`). They join the store. */\n constructor(state: CommunityState, private readonly hooks: CommunitySessionHooks, rows: readonly { id: string; frame: CommunityMessageFrame }[] = []) {\n this.state = state;\n this.identity = identityFromSeedB64(state.seedB64);\n // Out of the group, its store is empty (`out`): a row that kept its frame through a stop gives it up.\n if (state.status === \"left\" || state.status === \"removed\") for (const row of rows) hooks.forgetFrame?.(row.id);\n else this.takeRows(rows);\n this.answers = new CatchUpAnswers({\n send: (to, frame) => hooks.direct(to, frame),\n ...(hooks.handled && { handled: (to: string) => hooks.handled!(to) }),\n active: () => this.state.status === \"active\",\n // A member whose app handles 1 or 2 frames a second asks again while the last answer still waits there: without\n // a key, what was on its way went again (29-104 of 200 messages; 610 commit frames for 318 commits).\n key: frame => frame.t === \"group-msg\" ? communityMessageId(frame.s, frame.e, frame.h, frame.n)\n : frame.t === \"group-commit\" ? `commit:${communityCommitHash(frame.commit)}`\n : frame.t === \"group-secret\" ? `secret:${frame.h}` : undefined,\n });\n this.rebuild();\n this.pruneSeen();\n // A reply to a message deleted for everyone while this device ran an app from before `unquote`.\n if (hooks.removed && this.unquote(id => hooks.removed!(id))) this.persistSoon();\n this.adminSeen = this.admin;\n // A branch kept under the older rule (longest first) may be the better one now: it keeps an admin change mine dropped.\n if ((state.status === \"active\" || state.status === \"lost\") && this.bestBranch().tip !== this.topHash) void this.serialize(() => this.chooseBranch());\n }\n\n // -- creation and joining ----------------------------------------------------------------------\n\n static create(name: string, now = Date.now()): CommunityState {\n const me = identityFromSeedB64(toBase64Url(randomBytes(32)));\n const entry = identityFromSeedB64(toBase64Url(randomBytes(32)));\n const n = toBase64Url(randomBytes(16));\n const g = communityGroupId(me.pubKeyZ32, n);\n const secret = newEpochSecret();\n const roster: Roster = [[me.pubKeyZ32, \"admin\"]];\n const draft: Omit<CommunityCommit, \"sig\" | \"c\"> = { v: 2, g, e: 0, p: \"\", k: \"create\", m: rosterHash(roster), by: me.pubKeyZ32, x: entry.pubKeyZ32, n, ts: now };\n const commit = signCommunity({ ...draft, c: confirmationTag(epochKeys(secret, g, 0).confirm, communityUntaggedHash(draft)) }, me.seed);\n const h = communityCommitHash(commit);\n return { id: g, name: sanitizeNick(name) ?? \"Group\", profile: COMMUNITY_PROFILE, seedB64: me.seedB64, createdAt: now, chain: [commit], side: [],\n secrets: { [h]: toBase64Url(secret) }, entry: { key: entry.pubKeyZ32, seedB64: entry.seedB64 }, rv: toBase64Url(randomBytes(32)),\n status: \"active\", seq: 0, seqH: h, seen: {}, nicks: {}, store: [], pendingLeaves: [] };\n }\n\n /**\n * Joining from a welcome over the link's entry session: the whole chain verifies from its\n * genesis (which produces the group id), the link's entry key is the chain's current one, the\n * chain admits me in an `add` (signed by a member, as the chain rules require), and the secrets,\n * rendezvous secret and entry seed open and confirm. Who sent the welcome does not matter: the\n * entry session is pinned to the link's entry key, which only members hold, and a welcome whose\n * add was made by another member (the first one to answer me went away) is as good.\n */\n static join(link: { g: string; host: string }, pieces: unknown[], welcome: unknown, seedB64: string, now = Date.now()): { state: CommunityState } | { error: string } {\n const read = readWelcome(link, pieces, welcome);\n if (\"error\" in read) return read;\n return CommunitySession.joinVerified(link, read.welcome, verifyCommunityChain(read.commits, link.g), seedB64, now);\n }\n\n /** `join`, its chain checked a slice at a time (`verifyCommunityChainPaced`): what an app sharing its page's thread calls. */\n static async joinPaced(link: { g: string; host: string }, pieces: unknown[], welcome: unknown, seedB64: string, now = Date.now()): Promise<{ state: CommunityState } | { error: string }> {\n const read = readWelcome(link, pieces, welcome);\n if (\"error\" in read) return read;\n return CommunitySession.joinVerified(link, read.welcome, await verifyCommunityChainPaced(read.commits, link.g), seedB64, now);\n }\n\n private static joinVerified(link: { g: string; host: string }, w: Record<string, unknown>, verified: VerifiedChain | { error: string }, seedB64: string, now: number): { state: CommunityState } | { error: string } {\n if (\"error\" in verified) return verified;\n const { chain, roster, entry } = verified;\n const me = identityFromSeedB64(seedB64);\n if (!rosterHas(roster, me.pubKeyZ32)) return { error: \"The welcome does not admit this member key\" };\n if (entry !== link.host) return { error: \"This link was replaced or turned off\" };\n let admitted = -1;\n for (let i = chain.length - 1; i >= 0; i--) if (chain[i].k === \"add\" && chain[i].s === me.pubKeyZ32) { admitted = i; break; }\n if (admitted < 0) return { error: \"The welcome does not admit this member key\" };\n const secrets: Record<string, string> = {};\n const byHash = new Map(chain.map((c, i) => [communityCommitHash(c), i]));\n for (const entryRaw of w.secrets as unknown[]) {\n const { h, s } = (entryRaw ?? {}) as { h?: unknown; s?: unknown };\n if (typeof h !== \"string\" || !isSealed(s)) continue;\n const i = byHash.get(h);\n if (i === undefined || i < admitted) continue;\n const secret = openSecret(me.seed, me.pubKeyZ32, s, secretAad(link.g, h, me.pubKeyZ32));\n if (secret && confirmationMatches(epochKeys(secret, link.g, chain[i].e).confirm, communityUntaggedHash(chain[i]), chain[i].c)) secrets[h] = toBase64Url(secret);\n }\n // Later derived epochs follow from the admitting one.\n for (let i = admitted + 1; i < chain.length; i++) {\n const h = communityCommitHash(chain[i]), before = secrets[communityCommitHash(chain[i - 1])];\n if (!secrets[h] && before && !FRESH.has(chain[i].k)) secrets[h] = toBase64Url(derivedSecret(fromBase64Url(before), communityUntaggedHash(chain[i])));\n }\n const top = communityCommitHash(chain[chain.length - 1]);\n if (!secrets[top]) return { error: \"The welcome carries no usable secret for the current epoch\" };\n const rv = openSecret(me.seed, me.pubKeyZ32, w.rv as SealedSecret, rvAad(link.g, me.pubKeyZ32));\n const entrySeed = openSecret(me.seed, me.pubKeyZ32, w.entry as SealedSecret, entryAad(link.g, me.pubKeyZ32));\n if (!rv || !entrySeed || identityFromSeedB64(toBase64Url(entrySeed)).pubKeyZ32 !== entry) return { error: \"The welcome's keys do not open\" };\n return { state: { id: link.g, name: groupName(w.name) ?? \"Group\", profile: COMMUNITY_PROFILE, seedB64, createdAt: now,\n chain, side: [], secrets, entry: { key: entry, seedB64: toBase64Url(entrySeed) }, rv: toBase64Url(rv), status: \"active\", seq: 0, seqH: top,\n seen: {}, nicks: {}, store: [], pendingLeaves: [] } };\n }\n\n // -- views ---------------------------------------------------------------------------------------\n\n get id(): string { return this.state.id; }\n /** The name the admin gave the group, else the one it had when I got in (WISP 903 § Metadata). */\n get name(): string { return groupDisplayName(this.state.meta, this.state.name); }\n get myKey(): string { return this.identity.pubKeyZ32; }\n get top(): CommunityCommit { return this.state.chain[this.state.chain.length - 1]; }\n /**\n * The top commit's hash: a view reads it for each member (its roster, what each member's lines are missing), and\n * hashing it every time cost tens of milliseconds per state in big communities.\n */\n get topHash(): string { return this.hashOf(this.top); }\n /**\n * A commit's hash, kept for the commit it was taken from (a commit never changes once made): every sync frame, sync\n * answer and commit hashed the whole window again, about a tenth of the load test's CPU at 64 and 128 members.\n */\n private hashOf(c: CommunityCommit): string {\n let h = this.hashes.get(c);\n if (h === undefined) this.hashes.set(c, h = communityCommitHash(c));\n return h;\n }\n private readonly hashes = new WeakMap<CommunityCommit, string>();\n get epoch(): number { return this.top.e; }\n get roster(): Roster { return this.rosters.get(this.topHash)!; }\n get admin(): string | undefined { return rosterAdmin(this.roster); }\n get isAdmin(): boolean { return this.admin === this.myKey && this.state.status === \"active\"; }\n get status(): CommunityStatus { return this.state.status; }\n get others(): string[] { return this.roster.map(([k]) => k).filter(k => k !== this.myKey); }\n get isMember(): boolean { return this.state.status === \"active\" && rosterHas(this.roster, this.myKey); }\n get canSend(): boolean { return this.isMember && !!this.state.secrets[this.topHash]; }\n /** The call key of the newest epoch (WISP 602), or null until its secret arrives or once I am out. */\n callKey(): { epoch: number; key: Uint8Array } | null {\n const secret = this.isMember && this.state.secrets[this.topHash];\n return secret ? { epoch: this.epoch, key: groupCallKey(fromBase64Url(secret), this.id, this.epoch) } : null;\n }\n /** The entry key of the group's link, or \"\" when it is off. */\n get entryKey(): string { return this.state.entry.key; }\n /**\n * The entry key of the link my admission that lost was let in by (the one its branch named), where I ask again: a\n * link replaced since keeps me out as it does anyone. `entryKey` once that admission is no longer held.\n */\n get lostEntryKey(): string {\n const side = this.state.side;\n for (let i = side.length - 1; i >= 0; i--) if (side[i].k === \"add\" && side[i].s === this.myKey) {\n for (const c of this.ancestry(side[i].p)) if (c.x !== undefined) return c.x;\n return \"\";\n }\n return this.entryKey;\n }\n role(key: string): GroupRole | undefined { return this.roster.find(([k]) => k === key)?.[1]; }\n /** The group's picture, if it has one. */\n get picture(): string | undefined { return groupMetaPicture(this.state.meta); }\n /** The node that forwards the group's calls, while the statement I keep names one that holds (WISP 602). */\n get call(): { sfu: string; e2ee?: 1 } | undefined { return groupMetaBody(this.state.meta).call; }\n /**\n * Members of any epoch in the window: whom a frame may come from. A side commit's roster counts only while its branch\n * could still win (`mayWin`): one let in only on a branch that lost is not in the roster anyone sees, and the main\n * branch past where they part, a later link among it, is not its business (`lostAt`).\n */\n isRecentMember(key: string): boolean {\n let side = false;\n for (const [h, roster] of this.rosters) if (rosterHas(roster, key)) { if (this.mainIndex.has(h)) return true; side = true; }\n return side && [...this.mayWin()].some(h => rosterHas(this.rosters.get(h) ?? [], key));\n }\n /**\n * The side commits whose branch could still win: it does not drop an admin change the main branch holds (one that\n * does never wins, see `better`), and it parts within the window. Kept until the tip or the side moves.\n */\n private mayWin(): Set<string> {\n const side = this.state.side, at = `${this.topHash}:${side.length}:${side.length ? this.hashOf(side[side.length - 1]) : \"\"}`;\n if (this.winning?.at === at) return this.winning.set;\n const counts = this.adminCounts(), main = this.branch(this.topHash)!, set = new Set<string>();\n for (const c of side) {\n const h = this.hashOf(c), branch = this.rosters.has(h) ? this.branch(h) : null;\n if (!branch || !branch.path.length) continue;\n const { parent, admin } = this.parting(branch, main, counts);\n if (!(admin[1] && !admin[0]) && parent >= this.epoch - COMMUNITY_LIMITS.window) set.add(h);\n }\n this.winning = { at, set };\n return set;\n }\n private winning: { at: string; set: Set<string> } | undefined;\n /**\n * For a key that is no recent member, let in on a branch that lost: the main-branch index it parts from, and that of\n * the commit that makes it lose (the latest over its branches). Undefined for anyone else.\n */\n private lostAt(key: string): { fork: number; end: number } | undefined {\n const side = this.state.side, parents = new Set(side.map(c => c.p)), counts = this.adminCounts();\n let lost: { fork: number; end: number } | undefined;\n for (const c of side) {\n const h = this.hashOf(c);\n if (parents.has(h)) continue;\n const branch = this.branch(h);\n if (!branch || !branch.path.some(x => rosterHas(this.rosters.get(x) ?? [], key))) continue;\n for (let j = branch.fork + 1; j < this.state.chain.length; j++) {\n if (this.better(branch, this.branch(this.hashOf(this.state.chain[j]))!, counts)) continue;\n lost = { fork: Math.min(lost?.fork ?? j, branch.fork), end: Math.max(lost?.end ?? j, j) };\n break;\n }\n }\n return lost;\n }\n /**\n * Whether `key` could read message `messageId` (`<s>:<e>:<h>:<n>`) and still can: a member of the roster it was sealed\n * for, and of the roster now. A holder serves a group file only to such a member (WISP 503 § Asking).\n */\n couldRead(key: string, messageId: string): boolean {\n const [, e, h] = messageId.split(\":\");\n if (h === undefined || !rosterHas(this.roster, key)) return false;\n const found = this.commitByShort(Number(e), h);\n if (found) return rosterHas(this.rosterAt(found.hash) ?? [], key);\n // A commit of the main branch older than the window: its secret is gone, not the rule (its roster is replayed).\n const i = this.state.chain.length - 1 - (this.epoch - Number(e));\n const commit = Number.isSafeInteger(i) && i >= 0 ? this.state.chain[i] : undefined;\n const hash = commit && this.hashOf(commit);\n return !!hash && hash.startsWith(h) && this.wasInAt(key, i);\n }\n /**\n * Whether `key` was in the roster after the main branch's commit `i`. The branch is replayed once, as `rebuild` does (its\n * leaves were checked when they were taken), and only further as it grows: again from the start only once it changed.\n */\n private wasInAt(key: string, i: number): boolean {\n let s = this.spans;\n if (s.through > 0 && this.mainIndex.get(s.top) !== s.through - 1) s = this.spans = { through: 0, top: \"\", roster: null, byKey: new Map() };\n if (s.through <= i) {\n for (; s.through <= i; s.through++) {\n const before = new Set((s.roster ?? []).map(([k]) => k));\n s.roster = s.through === 0 || s.roster ? communityRoster(s.roster, this.state.chain[s.through], true) : null;\n const after = new Set((s.roster ?? []).map(([k]) => k));\n for (const k of after) if (!before.has(k)) s.byKey.set(k, [...s.byKey.get(k) ?? [], s.through]);\n for (const k of before) if (!after.has(k)) s.byKey.get(k)!.push(s.through);\n }\n s.top = this.hashOf(this.state.chain[s.through - 1]);\n }\n const at = s.byKey.get(key) ?? [];\n for (let j = 0; j < at.length; j += 2) if (at[j] <= i && (j + 1 >= at.length || i < at[j + 1])) return true;\n return false;\n }\n /** Someone the chain took out (removed or left) and who is not back in. */\n wasRemoved(key: string): boolean { return this.outIndex(key) >= 0; }\n /** When the chain took them out (the commit's time, by its signer's clock), if it did and they are not back in. */\n outAt(key: string): number | undefined { const i = this.outIndex(key); return i < 0 ? undefined : this.state.chain[i].ts; }\n private outIndex(key: string): number {\n if (rosterHas(this.roster, key)) return -1;\n for (let i = this.state.chain.length - 1; i >= 0; i--) { const c = this.state.chain[i]; if ((c.k === \"remove\" || c.k === \"leave\") && c.s === key) return i; }\n return -1;\n }\n /**\n * Whether a frame of someone the chain took out is still heard. A member removed is heard no more, even for an epoch\n * it was in. What one who left wrote while in the group is taken and handed on, its goodbye included, up to what the\n * member who committed the leave had heard of it then (its `group-left` mark), never past it: the leaver still holds\n * those epochs' secrets, and anything it signs later is not heard (WISP 903 § Leaving and removal). No mark here\n * (one not come yet, or a committer's app before it) and nothing of it is heard. A key let in only on a branch that\n * lost is heard no more either, as one removed, once this member knows it lost.\n */\n private heardAfterOut(f: { s: string; e: number; h: string; n: number }): boolean {\n const i = this.outIndex(f.s);\n // Let in only on a branch that lost: in no roster anyone sees (`isRecentMember`), and heard no more, as one removed,\n // whatever epoch of its branch it signs for (WISP 903 § A key no commit names).\n if (i < 0) return rosterHas(this.roster, f.s) || this.isRecentMember(f.s) || !this.lostAt(f.s);\n const commit = this.state.chain[i];\n if (commit.k !== \"leave\") return false;\n const high = this.state.left?.[this.hashOf(commit)]?.hi[seenKey(f.e, f.h)];\n return high !== undefined && f.n <= high;\n }\n /** The mark of a leave on my branch, as a frame to hand on (see `heardAfterOut`). */\n private leftFrame(key: string): CommunityLeftFrame | undefined {\n const i = this.outIndex(key);\n if (i < 0 || this.state.chain[i].k !== \"leave\") return undefined;\n const h = this.hashOf(this.state.chain[i]), mark = this.state.left?.[h];\n return mark && { t: \"group-left\", v: 2, g: this.id, h, hi: mark.hi, sig: mark.sig };\n }\n private keepLeft(h: string, mark: { hi: Record<string, number>; sig: string }): void {\n const left = { ...(this.state.left ?? {}) };\n delete left[h];\n left[h] = mark;\n const keys = Object.keys(left);\n for (const old of keys.slice(0, Math.max(0, keys.length - COMMUNITY_LIMITS.leftMarks))) delete left[old];\n this.state.left = left;\n }\n /**\n * A leave's mark, from the member who committed it: kept when it is that member's, for a leave I hold. The first one\n * taken stays: its committer signs one, and another for the same leave, each a new signature, would be handed on to\n * every member and saved again each time, or say after the fact that the leaver's earlier lines were never heard.\n */\n private receiveLeft(frame: Record<string, unknown>): boolean {\n const { h, hi, sig } = frame;\n if (typeof h !== \"string\" || !HASH.test(h) || typeof sig !== \"string\" || !SIG.test(sig) || !isObject(hi)) return false;\n const entries = Object.entries(hi);\n if (entries.length > COMMUNITY_LIMITS.leftMarks || entries.some(([k, n]) => !LEFT_EPOCH.test(k) || !Number.isSafeInteger(n) || (n as number) < 0)) return false;\n const commit = this.known.get(h);\n if (!commit || commit.k !== \"leave\" || this.state.left?.[h]) return false;\n const marks = hi as Record<string, number>;\n if (!verify(fromBase64Url(sig), leftStatement(this.id, h, marks), publicKeyFromZ32(commit.by))) return false;\n this.keepLeft(h, { hi: marks, sig });\n this.persistSoon();\n return true;\n }\n /**\n * What someone the chain took out is told when it comes back (WISP 903 § Leaving and removal): the commits from where\n * it says it is (`sync`: its tip, or its locator) up to the one that took it out, and nothing after. Later commits\n * are not its business (a `link` commit names the new entry key); no secret, no stored frame, no seed goes with them.\n * Empty when it is a member, was never one, or already holds that commit.\n */\n farewell(key: string, sync: { h?: unknown; loc?: unknown }): CommunityCommitFrame[] {\n if (!this.isMember) return [];\n const chain = this.state.chain, out = this.outIndex(key);\n if (out < 0) return [];\n let start: number;\n if (typeof sync.h === \"string\" && this.mainIndex.has(sync.h)) start = this.mainIndex.get(sync.h)! + 1;\n else {\n const path = typeof sync.h === \"string\" && this.known.has(sync.h) ? this.pathToMain(sync.h) : null;\n const common = (Array.isArray(sync.loc) ? sync.loc : []).find(x => typeof x === \"string\" && this.mainIndex.has(x)) as string | undefined;\n start = path ? this.mainIndex.get(this.known.get(path[0])!.p)! + 1 : common !== undefined ? this.mainIndex.get(common)! + 1 : Math.max(0, out + 1 - COMMUNITY_LIMITS.side);\n }\n return chain.slice(start, out + 1).map(commit => ({ t: \"group-commit\" as const, v: 2 as const, g: this.id, commit }));\n }\n /**\n * How many of a member's messages under the current commit are known to be missing: on their way, not gone (a\n * finished answer did not fill it, `settleGaps`; or syncs gave it up, `haveOf`). A hint spends its author's number\n * and is never kept (WISP 903), so a member who was away counted it missing until the commit changed.\n */\n missing(sender: string): number {\n // Only the answers now over: the members view asks once per member, and `settleGaps`'s prune walks every author\n // (the engine's tick runs it).\n this.settleAnswers();\n const key = seenKey(this.epoch, shortHash(this.topHash));\n const entry = this.state.seen[sender]?.[key];\n if (!entry) return 0;\n const lowest = Math.max(0, entry.high - COMMUNITY_LIMITS.replay + 1, (entry.floor ?? -1) + 1, (this.gapsGone[sender]?.[key] ?? -1) + 1);\n return Math.max(0, entry.high - lowest + 1 - (1 + entry.window.filter(n => n >= lowest).length));\n }\n\n /**\n * Gaps that the answers now over did not fill count as gone: an answer hands every frame its member holds above what\n * my sync said I have, so a number below my mark then, or below the highest it handed, that is still not here is\n * held by nobody. Returns whether some became gone (the members view changes). A sync nobody answered settles nothing.\n */\n settleGaps(): boolean {\n const changed = this.settleAnswers();\n // Only for authors and commits still seen: the rest is pruned with them.\n for (const [sender, byKey] of Object.entries(this.gapsGone)) {\n for (const key of Object.keys(byKey)) if (!this.state.seen[sender]?.[key]) delete byKey[key];\n if (!Object.keys(byKey).length) delete this.gapsGone[sender];\n }\n return changed;\n }\n\n /** The gaps of the answers now over (`settleGaps`), without the prune. */\n private settleAnswers(): boolean {\n if (!this.answerOf.size) return false;\n const now = this.hooks.clock?.() ?? Date.now();\n let changed = false;\n for (const [from, answer] of this.answerOf) {\n if ((this.answering.get(from) ?? 0) > now) continue;\n this.answerOf.delete(from);\n if (!answer.heard) continue;\n for (const marks of [answer.have, answer.top]) for (const [sender, byKey] of Object.entries(marks)) for (const [key, upTo] of Object.entries(byKey)) {\n if (!this.state.seen[sender]?.[key] || upTo <= (this.gapsGone[sender]?.[key] ?? -1)) continue;\n (this.gapsGone[sender] ??= {})[key] = upTo;\n changed = true;\n }\n }\n return changed;\n }\n\n // -- the tree of commits -------------------------------------------------------------------------\n\n /**\n * Replays the main branch (rosters kept for its window) and places the side commits. The main branch was verified\n * commit by commit when it was accepted: its signatures are not checked again.\n */\n private rebuild(): void {\n this.known.clear(); this.rosters.clear(); this.mainIndex.clear();\n let roster: Roster | null = null;\n const keepFrom = Math.max(0, this.state.chain.length - 1 - COMMUNITY_LIMITS.window);\n this.state.chain.forEach((commit, i) => {\n roster = communityRoster(roster, commit, true);\n if (!roster) throw new Error(\"Stored membership chain does not replay\");\n const h = this.hashOf(commit);\n this.known.set(h, commit); this.mainIndex.set(h, i);\n if (i >= keepFrom) this.rosters.set(h, roster);\n });\n for (const commit of this.state.side) this.placeSide(commit);\n }\n\n private placeSide(commit: CommunityCommit): boolean {\n const parent = this.known.get(commit.p), parentRoster = parent ? this.rosterAt(commit.p) : undefined;\n if (!parentRoster || !parent) return false;\n const result = verifyCommunityCommit(commit, parent, parentRoster, this.id, this.ancestry(commit.p));\n if (\"error\" in result) return false;\n const h = this.hashOf(result.commit);\n this.known.set(h, result.commit); this.rosters.set(h, result.roster);\n return true;\n }\n\n /** The commit `h` and those before it on its branch, newest first. */\n private *ancestry(h: string): Generator<CommunityCommit> {\n for (let c = this.known.get(h); c; c = this.known.get(c.p)) yield c;\n }\n\n private rosterOf(h: string): Roster | undefined { return this.rosterAt(h); }\n /** The roster after a commit: cached for the window and the side, replayed for an older commit of the main branch. */\n private rosterAt(h: string): Roster | undefined {\n const cached = this.rosters.get(h);\n if (cached) return cached;\n const i = this.mainIndex.get(h);\n if (i === undefined) return undefined;\n let roster: Roster | null = null;\n for (let j = 0; j <= i; j++) roster = communityRoster(roster, this.state.chain[j], true);\n if (roster) this.rosters.set(h, roster);\n return roster ?? undefined;\n }\n commitByShort(e: number, h16: string): { commit: CommunityCommit; hash: string } | undefined {\n const i = this.state.chain.length - 1 - (this.epoch - e);\n const candidates = [...(i >= 0 && i < this.state.chain.length ? [this.state.chain[i]] : []), ...this.state.side.filter(c => c.e === e)];\n for (const commit of candidates) {\n const hash = this.hashOf(commit);\n if (hash.startsWith(h16) && this.rosters.has(hash)) return { commit, hash };\n }\n return undefined;\n }\n\n /** The commits from `hash` back to the main branch (exclusive), oldest first; null when it does not reach it. */\n private pathToMain(hash: string): string[] | null {\n const path: string[] = [];\n let h = hash;\n while (!this.mainIndex.has(h)) {\n const c = this.known.get(h);\n if (!c) return null;\n path.unshift(h);\n h = c.p;\n }\n return path;\n }\n\n /** A branch: its tip, the main-branch index it leaves from, and its commits off the main branch (oldest first). */\n private branch(tip: string): Branch | null {\n if (this.mainIndex.has(tip)) return { tip, fork: this.mainIndex.get(tip)!, path: [] };\n const path = this.pathToMain(tip);\n return path ? { tip, fork: this.mainIndex.get(this.known.get(path[0])!.p)!, path } : null;\n }\n\n /** How many admin changes the main branch holds up to each index. */\n private adminCounts(): number[] {\n const counts: number[] = [];\n this.state.chain.forEach((c, i) => counts.push((i ? counts[i - 1] : 0) + (ADMIN_ONLY.has(c.k) ? 1 : 0)));\n return counts;\n }\n\n /** What each of two branches holds after their common parent: whether it has an admin change, its first commit, and its hand-overs. */\n private parting(a: Branch, b: Branch, counts: number[]): { parent: number; admin: [boolean, boolean]; first: [string, string]; roles: [string[], string[]] } {\n const m = Math.min(a.fork, b.fork);\n // Off the same main commit, the side paths may share their start too.\n let shared = 0;\n if (a.fork === b.fork) while (shared < a.path.length && shared < b.path.length && a.path[shared] === b.path[shared]) shared++;\n const parent = shared ? this.known.get(a.path[shared - 1])!.e : this.state.chain[m].e;\n const side = (x: Branch) => {\n const path = x.path.slice(shared);\n const admin = counts[x.fork] - counts[m] > 0 || path.some(h => ADMIN_ONLY.has(this.known.get(h)!.k));\n const first = x.fork > m ? this.hashOf(this.state.chain[m + 1]) : path[0] ?? \"\";\n // Its hand-overs: admin changes, so none on a side without one.\n const roles = !admin ? [] : [\n ...this.state.chain.slice(m + 1, x.fork + 1).filter(c => c.k === \"role\").map(c => this.hashOf(c)),\n ...path.filter(h => this.known.get(h)!.k === \"role\"),\n ];\n return { admin, first, roles };\n };\n const sa = side(a), sb = side(b);\n return { parent, admin: [sa.admin, sb.admin], first: [sa.first, sb.first], roles: [sa.roles, sb.roles] };\n }\n\n /**\n * Whether a hand-over (`h`, a `role`) went to a member whose leave of that admission I know on a branch that does not\n * hold the hand-over: signed on a view from before the leave, it would leave the role with someone gone for good (a\n * leave never names the admin). Not when that member signed a commit after the hand-over: it took the role while still\n * in, so its leave came later, and a branch from before the hand-over must not undo what it and later admins did.\n */\n private handedToLeaver(h: string): boolean {\n const role = this.known.get(h)!, at = this.mainIndex.get(h), fork = this.branch(h)?.fork;\n if (fork === undefined || this.signedAfter(h, role.s)) return false;\n // The main branch past a side hand-over's fork, and the side: commits before it are its own history.\n const others = [...(at === undefined ? this.state.chain.slice(fork + 1) : []), ...this.state.side];\n return others.some(c => {\n if (c.k !== \"leave\" || c.s !== role.s) return false;\n // Not one after the hand-over (the role went on, then that member left).\n const b = this.branch(this.hashOf(c));\n if (!b || (at !== undefined ? b.fork >= at : b.path.includes(h))) return false;\n return leaveStands(c, this.ancestry(role.p));\n });\n }\n\n /** Whether `key` signed a commit I know that comes after `h` (on the main branch past it, or on a side branch through it). */\n private signedAfter(h: string, key: string | undefined): boolean {\n const at = this.mainIndex.get(h);\n if (!key) return false;\n if (at !== undefined && this.state.chain.slice(at + 1).some(c => c.by === key)) return true;\n return this.state.side.some(c => {\n if (c.by !== key) return false;\n const b = this.branch(this.hashOf(c));\n return !!b && (at !== undefined ? b.fork >= at : b.path.includes(h));\n });\n }\n\n /**\n * Is branch `a` better than branch `b`? After their common parent: first, the one that does not hand the\n * role to a member who left (`handedToLeaver`); then the one that keeps an admin change, however short\n * and however far back it parts; then one I can read over one whose tip lists me and whose secret I lack;\n * then the longer; then, parting within the window, the lower hash of the first commit. Both holding admin changes means the admin signed two histories: `b` stays (a fresh one\n * halts the group, see `receiveCommit`).\n */\n private better(a: Branch, b: Branch, counts: number[]): boolean {\n if (a.tip === b.tip) return false;\n const { parent, admin, first, roles } = this.parting(a, b, counts);\n // A hand-over on a view from before the new admin's leave: that branch loses, or the group keeps an admin who is gone.\n const toLeaver = roles.map(r => r.some(h => this.handedToLeaver(h)));\n if (toLeaver[0] !== toLeaver[1]) return toLeaver[1];\n if (admin[0] !== admin[1]) return admin[0];\n if (admin[0]) return false;\n // A fresh secret (a member's leave) can be checked only once it comes: one that never comes, or does not confirm\n // the tag, opens an epoch nobody else holds, and followed it would leave the whole group unable to send. Such a\n // branch waits here until its secret comes (`takeSecret`), and is followed then.\n const wa = this.awaitsSecret(a.tip), wb = this.awaitsSecret(b.tip);\n if (wa !== wb) return wb;\n const ea = this.known.get(a.tip)!.e, eb = this.known.get(b.tip)!.e;\n if (ea !== eb) return ea > eb;\n if (parent < this.epoch - COMMUNITY_LIMITS.window) return false;\n return first[0] < first[1];\n }\n\n /** A commit whose roster lists me and whose secret I do not hold (yet). */\n private awaitsSecret(h: string): boolean {\n return !this.state.secrets[h] && rosterHas(this.rosterAt(h) ?? [], this.myKey);\n }\n\n /**\n * Takes in a commit (from a frame or from me): placed in the tree if it verifies against its\n * parent, a fork if the admin signed another commit after the same parent, and then the best\n * branch is followed. Returns whether it was new.\n */\n private async receiveCommit(from: string, raw: unknown): Promise<boolean> {\n if (!raw || typeof raw !== \"object\") return false;\n const p = (raw as { p?: unknown }).p, e = (raw as { e?: unknown }).e;\n if (typeof p !== \"string\" || !Number.isSafeInteger(e)) return false;\n const parent = this.known.get(p), parentRoster = parent ? this.rosterAt(p) : undefined;\n if (!parent || !parentRoster) {\n // Its parent is not here yet. Nothing says whether it follows one, so only its shape and its signature can be\n // checked: signed, I ask for what comes before; signed by someone who is or was the admin, it is also kept for a\n // while, the oldest giving its place. A member's is not kept (the catch-up brings it after its parent): anything\n // a member signs would take every place and keep me asking.\n const commit = parseCommit(raw);\n if (!commit || commit.g !== this.id || !verify(fromBase64Url(commit.sig), utf8Encode(tuple(commit)), publicKeyFromZ32(commit.by))) return false;\n if (this.wasAdmin(commit.by)) {\n const now = this.hooks.clock?.() ?? Date.now(), key = p + \":\" + String(e);\n this.dropStale(this.pendingCommits, now);\n this.pendingCommits.delete(key);\n if (this.pendingCommits.size >= COMMUNITY_LIMITS.pendingCommits) this.pendingCommits.delete(this.pendingCommits.keys().next().value!);\n this.pendingCommits.set(key, { from, commit, at: now });\n }\n this.ask(from);\n return false;\n }\n // One I hold already (a second hub's copy, a catch-up answer) is dropped before its signatures are checked: its hash\n // leaves the signature out, so a copy whose signature does not hold is dropped all the same.\n const parsed = parseCommit(raw);\n if (!parsed || this.known.has(communityCommitHash(parsed))) return false;\n const result = verifyCommunityCommit(raw, parent, parentRoster, this.id, this.ancestry(p));\n if (\"error\" in result) return false;\n // A derived epoch's tag, checked here when I hold its parent's secret, as a welcome's is: one that does not match\n // opens an epoch nobody can derive, its signer included, and followed it would leave the whole group unable to send.\n const previous = this.state.secrets[p];\n if (previous && !FRESH.has(result.commit.k)) {\n const untagged = communityUntaggedHash(result.commit);\n if (!confirmationMatches(epochKeys(derivedSecret(fromBase64Url(previous), untagged), this.id, result.commit.e).confirm, untagged, result.commit.c)) return false;\n }\n if (GROWS.has(result.commit.k) && !keepsRoom(result.commit.e, result.roster)) return false;\n // As the room above: a member that takes in admissions past the bound would let any one member fill the group.\n const parentAdmin = rosterAdmin(parentRoster);\n if (result.commit.k === \"add\" && result.commit.by !== parentAdmin && memberAdmissions(parentAdmin, this.ancestry(p)) >= COMMUNITY_LIMITS.memberAdmissions) return false;\n const commit = result.commit, h = this.hashOf(commit);\n // Two commits by the admin after the same commit: equivocation. By one my branch moved past (it handed the role\n // on, then maybe left or was removed), its other commit is a branch that drops that hand-over and never wins: it\n // is refused, not kept or passed on, and the group goes on. Only the admin of my tip halts the group.\n const admin = rosterAdmin(parentRoster);\n if (commit.by === admin) {\n for (const [other, c] of this.known) if (other !== h && c.p === commit.p && c.by === admin) {\n if (admin !== this.admin) return false;\n this.known.set(h, commit); this.rosters.set(h, result.roster);\n await this.fork(`The admin signed two different changes after epoch ${parent.e}`);\n return true;\n }\n }\n this.known.set(h, commit); this.rosters.set(h, result.roster);\n const branch = this.branch(h);\n if (branch && branch.path.length) {\n const { admin } = this.parting(branch, this.branch(this.topHash)!, this.adminCounts());\n // The admin's change on a branch parting from one that holds another admin change: two histories. From a former\n // admin (my branch holds its hand-over), refused as above; from the admin of my tip, the group halts.\n if (ADMIN_ONLY.has(commit.k) && admin[1]) {\n // A hand-over to a member who left never wins either (`better`): the admin went on without it, not a second history.\n if (commit.by !== this.admin || (commit.k === \"role\" && this.handedToLeaver(h))) { this.known.delete(h); this.rosters.delete(h); return false; }\n await this.fork(`The admin signed changes on two branches after epoch ${this.state.chain[branch.fork].e}`);\n return true;\n }\n // A branch that drops an admin change never wins: from someone the main branch took out, it is not kept or passed on.\n if (admin[1] && !admin[0] && !rosterHas(this.roster, commit.by)) { this.known.delete(h); this.rosters.delete(h); return false; }\n }\n if (!this.mainIndex.has(h)) this.state.side.push(commit);\n this.takeDerived(h);\n const sealed = this.pendingSecrets.get(h);\n if (sealed) { this.pendingSecrets.delete(h); this.takeSecret(h, sealed.sealed); }\n await this.chooseBranch();\n // Anything that was waiting for this one; hubs relay those too.\n for (const [key, pending] of [...this.pendingCommits]) if (key.startsWith(h + \":\")) {\n this.pendingCommits.delete(key);\n if (await this.receiveCommit(pending.from, pending.commit)) this.hooks.relay?.({ t: \"group-commit\", v: 2, g: this.id, commit: pending.commit });\n }\n return true;\n }\n\n /** Is, or was on the branch I follow, the admin (and was not taken out since). */\n private wasAdmin(key: string): boolean {\n if (this.wasRemoved(key)) return false;\n return this.admin === key || this.state.chain.some((c, i) => i === 0 ? c.by === key : c.k === \"role\" && c.s === key);\n }\n\n /** What waited longer than `pendingMs` goes (the oldest first: a Map keeps the order they came in). */\n private dropStale(pending: Map<string, { at: number }>, now: number): void {\n for (const [key, { at }] of pending) { if (now - at < COMMUNITY_LIMITS.pendingMs) break; pending.delete(key); }\n }\n\n /**\n * Follows the best branch among the known tips (see `better`); reorganizes the main branch when it\n * changed. A branch that keeps the admin's changes, or a longer one, wins however far back it parts\n * (a member away through a race must end up where everyone is); a branch of the same length only\n * within the window.\n */\n private async chooseBranch(): Promise<void> {\n const status = this.state.status;\n const best = this.bestBranch();\n if (best.tip !== this.topHash) await this.adopt(best.tip);\n if (this.state.status === \"lost\" && rosterHas(this.roster, this.myKey)) { this.state.status = \"active\"; delete this.state.statusReason; }\n this.followEntry();\n this.pruneSide();\n // A held request goes once the branch I follow takes its member out (its leave or a removal), as committing it drops\n // it on a hub: a member who never commits kept up to 64 for members long gone, and handed them on in every sync answer.\n // One a lost fork drops is held again from the dropped commit (`holdDroppedLeaves`).\n this.state.pendingLeaves = this.state.pendingLeaves.filter(r => rosterHas(this.roster, r.s));\n // Saved at once only when my place in the group changed (removed, left, lost, back in); otherwise within a second, as\n // messages are. Each commit of a catch-up saved the whole state: 1,000 commits were 1,051 whole-record writes, 241 MB\n // of journal on the CLI store (agents#1767). A save lost to a crash is asked again at the next sync: the commits are on\n // every hub.\n if (this.state.status !== status) await this.persist(); else this.persistSoon();\n this.hooks.changed();\n await this.replayWaiting();\n await this.renewLasting();\n }\n\n private bestBranch(): Branch {\n const counts = this.adminCounts();\n let best = this.branch(this.topHash)!;\n const parents = new Set(this.state.side.map(c => c.p));\n for (const c of this.state.side) {\n const h = this.hashOf(c);\n // Only tips: a commit's children keep what it has and are longer.\n if (this.mainIndex.has(h) || parents.has(h)) continue;\n const branch = this.branch(h);\n if (branch && this.better(branch, best, counts)) best = branch;\n }\n return best;\n }\n\n private async adopt(tip: string): Promise<void> {\n this.chainMovedAt = this.hooks.clock?.() ?? Date.now();\n const path = this.pathToMain(tip)!;\n const ancestor = this.mainIndex.get(this.known.get(path[0])!.p)!;\n const dropped = this.state.chain.splice(ancestor + 1);\n for (const c of dropped) { const h = this.hashOf(c); this.mainIndex.delete(h); this.state.side.push(c); }\n for (const h of path) {\n const c = this.known.get(h)!;\n this.state.side = this.state.side.filter(x => this.hashOf(x) !== h);\n this.mainIndex.set(h, this.state.chain.length);\n this.state.chain.push(c);\n this.takeDerived(h);\n }\n this.holdDroppedLeaves(dropped);\n const lostMine = !rosterHas(this.roster, this.myKey);\n if (lostMine && this.state.status === \"active\") {\n const out = [...path].reverse().map(h => this.known.get(h)!).find(c => (c.k === \"remove\" || c.k === \"leave\") && c.s === this.myKey);\n if (out) this.out(out.k === \"remove\" ? \"removed\" : \"left\", out.k === \"remove\" ? \"You were removed from this group\" : \"You left this group\");\n else { this.state.status = \"lost\"; this.state.statusReason = \"Two members let people in at the same moment and yours did not count. Asking to be let in again…\"; }\n }\n }\n\n /**\n * A leave the branch I left behind had committed, whose member the main branch still lists (an admin-only commit\n * signed on a stale view won the fork): its request is held again, so the next hub commits it on top. The hub that\n * committed it kept no copy and the leaver's app forgot the group, so nobody would say it again (agents#2285).\n */\n private holdDroppedLeaves(dropped: CommunityCommit[]): void {\n let held = this.state.pendingLeaves;\n for (const c of dropped) {\n if (c.k !== \"leave\" || !c.s || !c.ls || c.s === this.myKey || !rosterHas(this.roster, c.s)) continue;\n const request = { s: c.s, ls: c.ls, ...(c.ls3 ? { ls3: c.ls3 } : {}) };\n // Not one the main branch committed already (this admission's), and the one naming the admission takes the place.\n if (!leaveStands({ g: this.id, ...request }, this.ancestry(this.topHash))) continue;\n const other = held.find(r => r.s === c.s && leaveStands({ g: this.id, ...r }, this.ancestry(this.topHash)));\n if (other && (other.ls3 || !request.ls3)) continue;\n held = [...held.filter(r => r.s !== c.s), request].slice(-COMMUNITY_LIMITS.pendingLeaves);\n }\n this.state.pendingLeaves = held;\n }\n\n /** The entry key is the one the main branch names; its seed comes with a `group-entry` from whoever holds it. */\n private followEntry(): void {\n const key = this.currentEntryKey();\n if (key !== this.state.entry.key) this.state.entry = { key, seedB64: \"\" };\n }\n\n /**\n * Side commits stay up to a bound, the most recent ones (a longer branch being assembled included), and a member's\n * newest only: past `sideTips` of the branches it ends or `sideCommits` of its commits, its oldest branch goes, from\n * the tip down, so nothing kept loses its parent. Each is weighed at every commit taken and saved with the group, so\n * what one member signs off the main branch costs every member a bounded amount. What it signs last is kept, so a\n * branch it grows still comes in commit by commit (one let go comes again from where it parts in a catch-up).\n */\n private pruneSide(): void {\n const admin = this.admin, hash = (c: CommunityCommit) => this.hashOf(c);\n let side = this.state.side.slice(-COMMUNITY_LIMITS.side);\n for (;;) {\n const held = new Set(side.map(hash)), parents = new Set(side.map(c => c.p)), drop = new Set<CommunityCommit>();\n const signed = new Map<string, number>(), tips = new Map<string, number>(), oldest = new Map<string, CommunityCommit>(), cut = new Set<string>();\n for (const c of side) signed.set(c.by, (signed.get(c.by) ?? 0) + 1);\n // Newest first: a member's newest branches are those kept.\n for (let i = side.length - 1; i >= 0; i--) {\n const c = side[i];\n if (!held.has(c.p) && !this.mainIndex.has(c.p)) { drop.add(c); continue; }\n if (parents.has(hash(c))) continue;\n const n = (tips.get(c.by) ?? 0) + 1;\n tips.set(c.by, n);\n if (c.by !== admin && n > COMMUNITY_LIMITS.sideTips) { drop.add(c); cut.add(c.by); } else oldest.set(c.by, c);\n }\n for (const [by, n] of signed) if (by !== admin && n > COMMUNITY_LIMITS.sideCommits && !cut.has(by) && oldest.has(by)) drop.add(oldest.get(by)!);\n if (!drop.size) break;\n side = side.filter(c => !drop.has(c));\n }\n this.state.side = side;\n const keep = new Set(side.map(hash));\n for (const [h, c] of [...this.known]) {\n if (this.mainIndex.has(h)) { if (this.mainIndex.get(h)! < this.state.chain.length - 1 - COMMUNITY_LIMITS.window) this.rosters.delete(h); continue; }\n if (!keep.has(h)) { this.known.delete(h); this.rosters.delete(h); void c; }\n }\n this.pruneSecrets();\n this.pruneSeen();\n }\n\n /**\n * Seen marks of epochs older than the window go, every sender's, once the branch I follow moves past them: as\n * `markSeen` drops the sender's it marks. Before, only that sender's went, so a member who left or went quiet kept\n * an entry for every epoch it wrote in, and its window of numbers, for the life of the group (agents#2904). Those\n * within the window stay, a leaver's too: what it wrote before its leave is still taken up to its mark there.\n */\n private pruneSeen(): void {\n const from = this.epoch - COMMUNITY_LIMITS.window;\n if (from === this.seenFrom) return;\n this.seenFrom = from;\n for (const [sender, bySender] of Object.entries(this.state.seen)) {\n for (const key of Object.keys(bySender)) if (Number(key.split(\":\")[0]) < from) delete bySender[key];\n if (!Object.keys(bySender).length) delete this.state.seen[sender];\n }\n }\n\n /**\n * Those of the main branch's window always stay, the current epoch's included; side commits, however many are\n * kept, only get what is left of the bound, the most recent first.\n */\n private pruneSecrets(): void {\n const keep = new Set(this.state.chain.slice(-COMMUNITY_LIMITS.window - 1).map(c => this.hashOf(c)));\n let room = COMMUNITY_LIMITS.secrets - [...keep].filter(h => this.state.secrets[h]).length;\n for (let i = this.state.side.length - 1; i >= 0 && room > 0; i--) {\n const h = this.hashOf(this.state.side[i]);\n if (this.state.secrets[h] && !keep.has(h)) { keep.add(h); room--; }\n }\n for (const h of Object.keys(this.state.secrets)) if (!keep.has(h)) delete this.state.secrets[h];\n }\n\n /** The epoch of the commit on the main branch that took `key` out (`outIndex`), while it is out. */\n private outEpoch(key: string): number | undefined { const i = this.outIndex(key); return i < 0 ? undefined : this.state.chain[i].e; }\n\n /**\n * 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.\n * A member stops being one at the commit that takes it out: a side branch from before it may list it still, at that\n * epoch or later, and that epoch's secret and every later one never reach it.\n */\n private readsAt(h: string, key: string, out = this.outEpoch(key)): boolean {\n const c = this.known.get(h);\n return !!c && rosterHas(this.rosterAt(h) ?? [], key) && (out === undefined || c.e < out);\n }\n\n /** A derived epoch's secret, from its parent's, when that is held. */\n private takeDerived(h: string): void {\n const c = this.known.get(h);\n if (!c || this.state.secrets[h] || FRESH.has(c.k)) return;\n const parent = this.state.secrets[c.p];\n if (!parent || !this.readsAt(h, this.myKey)) return;\n const secret = derivedSecret(fromBase64Url(parent), communityUntaggedHash(c));\n if (confirmationMatches(epochKeys(secret, this.id, c.e).confirm, communityUntaggedHash(c), c.c)) {\n this.state.secrets[h] = toBase64Url(secret);\n // …and the derived ones after it, on any branch.\n for (const [child, cc] of this.known) if (cc.p === h) this.takeDerived(child);\n }\n }\n\n /** A sealed secret for a known commit I read (`readsAt`): kept only when it confirms. */\n private takeSecret(h: string, sealed: unknown): boolean {\n const c = this.known.get(h);\n if (!c) {\n // Its commit is not here yet, so nothing says it is one: kept for a while, the oldest giving its place.\n if (!HASH.test(h) || !isSealed(sealed)) return false;\n const now = this.hooks.clock?.() ?? Date.now();\n this.dropStale(this.pendingSecrets, now);\n this.pendingSecrets.delete(h);\n if (this.pendingSecrets.size >= COMMUNITY_LIMITS.pendingSecrets) this.pendingSecrets.delete(this.pendingSecrets.keys().next().value!);\n this.pendingSecrets.set(h, { sealed, at: now });\n return false;\n }\n if (this.state.secrets[h] || !isSealed(sealed) || !this.readsAt(h, this.myKey)) return false;\n const secret = openSecret(this.identity.seed, this.myKey, sealed, secretAad(this.id, h, this.myKey));\n if (!secret || !confirmationMatches(epochKeys(secret, this.id, c.e).confirm, communityUntaggedHash(c), c.c)) return false;\n this.state.secrets[h] = toBase64Url(secret);\n for (const [child, cc] of this.known) if (cc.p === h) this.takeDerived(child);\n return true;\n }\n\n // -- what a member does --------------------------------------------------------------------------\n\n private serialize<T>(run: () => Promise<T>): Promise<T> {\n const operation = this.queue.then(run);\n this.queue = operation.then(() => {}, () => {});\n return operation;\n }\n private persist(): Promise<void> {\n if (this.saveTimer) { clearTimeout(this.saveTimer); this.saveTimer = undefined; }\n return this.hooks.save(this.toSave());\n }\n /** The state as it is saved: a copy, without the frames the app holds with their messages (`onRows`). */\n private toSave(): CommunityState {\n const { store, ...rest } = this.state;\n return structuredClone({ ...rest, store: store.filter(f => !this.onRows.has(storeKey(f))) });\n }\n /**\n * A save within a second, for what may happen many times a second (every message received, in a\n * group of hundreds): the state holds the chain and the store, and is not worth writing each time.\n */\n private persistSoon(): void {\n if (this.saveTimer) return;\n this.saveTimer = setTimeout(() => { this.saveTimer = undefined; void this.hooks.save(this.toSave()); }, 1000);\n }\n /** Writes what is waiting to be saved now (before a restart, in tests). */\n async flush(): Promise<void> { if (this.saveTimer) await this.persist(); }\n private requireMember(): void { if (!this.isMember) throw new Error(this.state.statusReason ?? \"You are not in this group\"); }\n /** Whether this device may sign commits for the group now (`CommunitySessionHooks.adminWork`). */\n get adminWork(): boolean { return this.hooks.adminWork?.() !== false; }\n private requireAdmin(): void { this.requireMember(); if (!this.isAdmin) throw new Error(\"Only the admin can do that\"); }\n\n /** `alongside`: what else the commit changes in the state, saved in the same write (only once the commit is signed). */\n private async commit(kind: CommunityKind, fields: { s?: string; x?: string; ls?: string; ls3?: string }, now: number, alongside?: () => void): Promise<{ commit: CommunityCommit; hash: string; secret: Uint8Array }> {\n if (!this.adminWork) throw new Error(GROUP_ADMIN_OFF_ERROR);\n if (this.hooks.adminTurn && !(await this.hooks.adminTurn())) throw engineError(\"groupTurnUnconfirmed\");\n if (this.state.chain.length >= COMMUNITY_LIMITS.chain) throw new Error(\"This group has reached its membership history limit. Create a new group.\");\n const parent = this.top, parentHash = this.topHash;\n const draftBase = { v: 2 as const, g: this.id, e: parent.e + 1, p: parentHash, k: kind, by: this.myKey, ...fields, ts: now };\n const roster = communityRoster(this.roster, draftBase);\n if (!roster || (kind === \"leave\" && !leaveStands(draftBase, this.ancestry(parentHash)))) throw new Error(\"This change is not allowed\");\n if (GROWS.has(kind) && !keepsRoom(draftBase.e, roster)) throw new Error(\"This group has reached its membership history limit. Create a new group.\");\n if (kind === \"add\" && !this.isAdmin && memberAdmissions(this.admin, this.ancestry(parentHash)) >= COMMUNITY_LIMITS.memberAdmissions) throw new Error(MEMBER_ADMISSIONS_ERROR);\n const draft: Omit<CommunityCommit, \"sig\" | \"c\"> = { ...draftBase, m: rosterHash(roster) };\n const untagged = communityUntaggedHash(draft);\n let secret: Uint8Array;\n if (FRESH.has(kind)) secret = newEpochSecret();\n else {\n const previous = this.state.secrets[parentHash];\n if (!previous) throw new Error(\"This epoch's key has not arrived yet. Wait for a member to catch you up.\");\n secret = derivedSecret(fromBase64Url(previous), untagged);\n }\n const commit = signCommunity({ ...draft, c: confirmationTag(epochKeys(secret, this.id, draft.e).confirm, untagged) }, this.identity.seed);\n const hash = this.hashOf(commit);\n this.known.set(hash, commit); this.rosters.set(hash, roster);\n this.mainIndex.set(hash, this.state.chain.length);\n this.state.chain.push(commit);\n this.state.secrets[hash] = toBase64Url(secret);\n this.state.seq = 0; this.state.seqH = hash;\n this.pruneSide();\n alongside?.();\n await this.persist();\n this.hooks.broadcast({ t: \"group-commit\", v: 2, g: this.id, commit });\n // A key respelled in its last character could be pinned and added by a build before `MEMBER_KEY` was canonical, and\n // the roster that holds it is in every member's chain: `sealSecret` would throw on it, past the persist and the\n // broadcast above, so it gets no secret instead. One agreement a member, ~1 ms in JavaScript: sealed a slice at a time,\n // so a page sharing the thread draws meanwhile (250 members held it 230 ms a commit, a hub's 40 held leaves 8.6 s).\n if (FRESH.has(kind)) {\n const pause = pacer(SEAL_SLICE_MS);\n for (const [key] of roster) if (key !== this.myKey && isZ32Key(key)) {\n this.hooks.addressed(key, { t: \"group-secret\", v: 2, g: this.id, to: key, h: hash, s: sealSecret(key, secret, secretAad(this.id, hash, key)) });\n await pause();\n }\n }\n this.hooks.changed();\n await this.renewLasting();\n return { commit, hash, secret };\n }\n\n /** What an entry session sends a joiner first. */\n inviteFrame(): CommunityInviteFrame {\n this.requireMember();\n return { t: \"group-invite\", v: 2, g: this.id, name: this.name, admin: this.myKey, e: this.epoch, n: this.roster.length };\n }\n\n /** Admits a joiner who knocked with the link: an `add`, then the welcome for them (in pieces). */\n admit(memberKey: string, now = Date.now()): Promise<(CommunityChainFrame | CommunityWelcomeFrame)[]> {\n return this.serialize(async () => {\n this.requireMember();\n if (!MEMBER_KEY.test(memberKey) || memberKey === this.myKey) throw new Error(\"Invalid member key\");\n if (rosterHas(this.roster, memberKey)) throw new Error(\"Already a member\");\n if (this.roster.length >= COMMUNITY_LIMITS.members) throw new Error(`The group is full (${COMMUNITY_LIMITS.members} members)`);\n const { hash } = await this.commit(\"add\", { s: memberKey }, now);\n return this.welcomeFor(memberKey, hash);\n });\n }\n\n /**\n * A welcome for someone already in the roster who knocks again: their admission reached the\n * roster but its welcome never reached them. Nothing is committed; what they get is sealed to their key.\n */\n rewelcome(memberKey: string): Promise<(CommunityChainFrame | CommunityWelcomeFrame)[]> {\n return this.serialize(async () => {\n this.requireMember();\n if (!rosterHas(this.roster, memberKey) || memberKey === this.myKey || !isZ32Key(memberKey)) throw new Error(\"Not a member\");\n for (let i = this.state.chain.length - 1; i >= 0; i--) {\n const c = this.state.chain[i];\n if (c.k === \"add\" && c.s === memberKey) return this.welcomeFor(memberKey, this.hashOf(c));\n }\n throw new Error(\"Not a member\");\n });\n }\n\n /** The chain, the secrets from the admitting commit on, the rendezvous secret and the entry seed, for one newcomer. */\n private welcomeFor(memberKey: string, admittedAt: string): (CommunityChainFrame | CommunityWelcomeFrame)[] {\n const chain = this.state.chain, from = this.mainIndex.get(admittedAt)!;\n const secrets = chain.slice(from).map(c => this.hashOf(c)).filter(h => this.state.secrets[h])\n .map(h => ({ h, s: sealSecret(memberKey, fromBase64Url(this.state.secrets[h]), secretAad(this.id, h, memberKey)) }));\n const piece = COMMUNITY_LIMITS.chainPiece, frames: (CommunityChainFrame | CommunityWelcomeFrame)[] = [];\n for (let i = 0; i < chain.length - piece; i += piece) frames.push({ t: \"group-chain\", v: 2, g: this.id, commits: chain.slice(i, i + piece) });\n const tail = chain.length % piece || piece;\n frames.push({ t: \"group-welcome\", v: 2, g: this.id, name: this.name, commits: chain.slice(chain.length - tail), secrets,\n rv: sealSecret(memberKey, fromBase64Url(this.state.rv), rvAad(this.id, memberKey)),\n entry: sealSecret(memberKey, fromBase64Url(this.state.entry.seedB64), entryAad(this.id, memberKey)) });\n return frames;\n }\n\n /**\n * Takes a member out, and with it everyone it let in who is still in, and whom those let in in turn\n * (`admittedThrough`): keys a member let in cost it nothing, and one by one they were the admin's to clear. A\n * `remove` commit each, as before (an app from before follows them), one at a time, so what arrives meanwhile is\n * heard, and an admission signed meanwhile by one of them is taken out too (`memberAdmissions` bounds them, as a\n * removal is not the admin letting anyone in). A member already out still has those it let in cleared.\n */\n async remove(memberKey: string, now = Date.now()): Promise<void> {\n for (let first = true; ; first = false) {\n const done = await this.serialize(async () => {\n this.requireAdmin();\n if (memberKey === this.myKey) throw new Error(\"Not a member\");\n const next = rosterHas(this.roster, memberKey) ? memberKey : this.admittedThrough(memberKey)[0];\n if (next === undefined) { if (first) throw new Error(\"Not a member\"); return true; }\n await this.commit(\"remove\", { s: next }, now);\n // The admin before me, removed: what they sign is no longer taken (`takesOver`).\n if (next === this.takeover?.from) this.takeover = undefined;\n return false;\n });\n if (done) return;\n }\n }\n\n /**\n * The members still in whose admission, on the main branch, `root` signed, or one of them did, and so on: in the\n * order they were let in. An admission signed by whoever was the admin then is the admin's, not counted: removing\n * a former admin does not take out everyone it let in. Never the admin nor me.\n */\n private admittedThrough(root: string): string[] {\n const by = new Map<string, string>();\n let admin = \"\";\n for (const c of this.state.chain) {\n if (c.k === \"create\") admin = c.by;\n else if (c.k === \"role\" && c.s) admin = c.s;\n else if (c.k === \"add\" && c.s) { by.delete(c.s); if (c.by !== admin) by.set(c.s, c.by); }\n }\n const through = new Set([root]);\n for (let grew = true; grew;) {\n grew = false;\n for (const [key, signer] of by) if (!through.has(key) && through.has(signer)) { through.add(key); grew = true; }\n }\n return [...by.keys()].filter(key => key !== root && through.has(key) && key !== this.myKey && key !== this.admin && rosterHas(this.roster, key));\n }\n transferAdmin(memberKey: string, now = Date.now()): Promise<void> {\n return this.serialize(async () => {\n this.requireAdmin();\n if (!rosterHas(this.roster, memberKey) || memberKey === this.myKey) throw new Error(\"Not a member\");\n // A member whose signed leave I hold has gone: the role would stay with nobody (a leave never names the admin).\n if (this.state.pendingLeaves.some(r => r.s === memberKey && leaveStands({ g: this.id, ...r }, this.ancestry(this.topHash)))) throw new Error(\"This member has left the group. Make someone else the admin.\");\n await this.commit(\"role\", { s: memberKey }, now);\n });\n }\n rotate(now = Date.now()): Promise<void> { return this.serialize(async () => { this.requireAdmin(); await this.commit(\"rotate\", {}, now); }); }\n\n /** A new entry key (the old link reaches nobody), or none (`off`): a `link` commit every member follows. */\n replaceLink(off = false, now = Date.now()): Promise<string> {\n return this.serialize(async () => {\n this.requireAdmin();\n const entry = off ? null : identityFromSeedB64(toBase64Url(randomBytes(32)));\n // The new key is saved with the commit naming it: one write of the state (the chain, the secrets), not two.\n await this.commit(\"link\", { x: entry?.pubKeyZ32 ?? \"\" }, now, () => { this.state.entry = { key: entry?.pubKeyZ32 ?? \"\", seedB64: entry?.seedB64 ?? \"\" }; });\n // Every member can answer the new link: its seed, sealed to each. One agreement a member, ~1 ms in JavaScript: sealed\n // a slice at a time, so a page sharing the thread draws meanwhile (250 members held it 230 ms).\n if (entry) {\n const pause = pacer(ENTRY_SLICE_MS);\n for (const key of this.others) {\n const frame = this.entryFrame(key);\n if (frame) this.hooks.addressed(key, frame);\n await pause();\n }\n }\n this.hooks.changed();\n return this.state.entry.key;\n });\n }\n\n /**\n * Leaves: a signed request any other member commits, and my secrets go now. The admin must\n * hand over the role first (the engine does it for a leaving admin). `follow`: commits and secrets are still taken\n * after (`followAfterLeave`).\n */\n leave(follow = false): Promise<CommunityLeaveFrame | null> {\n return this.serialize(async () => {\n if (this.state.status !== \"active\") return null;\n if (this.isAdmin && this.others.length) throw new Error(\"Make someone else the admin before leaving\");\n const frame: CommunityLeaveFrame = { t: \"group-leave\", v: 2, g: this.id, s: this.myKey, ls: toBase64Url(sign(leaveStatement(this.id, this.myKey), this.identity.seed)) };\n // The admission this leave ends: an app from before reads `ls` alone, which says the same at every admission.\n for (const c of this.ancestry(this.topHash)) if ((c.k === \"add\" && c.s === this.myKey) || (c.k === \"create\" && c.by === this.myKey)) {\n frame.ls3 = toBase64Url(sign(leaveStatement3(this.id, this.myKey, this.hashOf(c)), this.identity.seed));\n break;\n }\n this.hooks.broadcast(frame);\n const tip = this.state.secrets[this.topHash];\n this.leftSecret = tip ? { h: this.topHash, s: tip } : undefined;\n this.out(\"left\", \"You left this group\");\n this.following = follow;\n await this.persist();\n this.hooks.changed();\n return frame;\n });\n }\n\n /**\n * After I left with `follow` (WISP 903 § Leaving, \"A role that reaches a leave\"): commits and secrets are taken still,\n * as a member whose admission lost takes them, so a hand-over that crossed my leave reaches me (`handOnAfterLeave`).\n * Once the app has forgotten the group (nothing is saved any more), the secret of the epoch I left in comes back, in\n * memory only, for the epochs derived from it. Nothing else is heard.\n */\n followAfterLeave(): Promise<void> {\n return this.serialize(async () => {\n if (!this.following || this.state.status !== \"left\") return;\n const kept = this.leftSecret;\n if (!kept) return;\n this.state.secrets[kept.h] = kept.s;\n for (const [child, c] of this.known) if (c.p === kept.h) this.takeDerived(child);\n });\n }\n\n /**\n * After I left, a chain that names me the admin (a hand-over that crossed my leave): the role goes on to\n * `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\n * the signer of the newest `role` on my branch, whatever members committed on top since: an admission there would\n * otherwise steer the role to whoever let someone in. True when it went; false while the secret of my tip has not\n * come (it is tried again).\n */\n handOnAfterLeave(pick: (by: string) => string | undefined, now = Date.now()): Promise<boolean> {\n return this.serialize(async () => {\n if (!this.following || this.state.status !== \"left\" || this.admin !== this.myKey || !this.state.secrets[this.topHash]) return false;\n const next = pick([...this.state.chain].reverse().find(c => c.k === \"role\" || c.k === \"create\")!.by);\n if (!next || next === this.myKey || !rosterHas(this.roster, next)) return false;\n await this.commit(\"role\", { s: next }, now);\n return true;\n });\n }\n\n /**\n * 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\n * missing): the engine asks my edges for it (`catchUp`) while I follow, so the role can go on. Only what I still read\n * comes back (`readsAt`): epochs before the commit that takes me out, never that one's nor any later.\n */\n get leftWaitsForSecret(): boolean {\n return this.following && this.state.status === \"left\" && this.admin === this.myKey && !this.state.secrets[this.topHash];\n }\n\n /** Commits the leave requests I hold whose members are still in: the engine calls this on hubs. */\n commitPendingLeaves(now = Date.now()): Promise<number> {\n return this.serialize(async () => {\n // Admin work off on this device: the requests wait for a member who commits them, or for the person to turn it on.\n if (!this.isMember || !this.adminWork) return 0;\n // Not confirmed as the active device: the requests wait, untouched, for the next try (or another hub).\n if (this.state.pendingLeaves.length && this.hooks.adminTurn && !(await this.hooks.adminTurn())) return 0;\n let done = 0;\n // A hand-over that crossed the new admin's leave (its request is here, and never committed): the member who handed\n // it the role, leaving too, stays in until the role goes on. Its app follows the chain after it left, and may be the\n // only edge the new admin's app has to hand the role on over (WISP 903 § Leaving, \"A role that reaches a leave\").\n // The admin's request is kept, not committed: once its app hands the role on, it is a member's.\n const handedBy = this.state.pendingLeaves.some(r => r.s === this.admin) ? [...this.state.chain].reverse().find(c => c.k === \"role\")?.by : undefined;\n for (const request of [...this.state.pendingLeaves]) {\n if ((request.s === handedBy || request.s === this.admin) && request.s !== this.myKey && rosterHas(this.roster, request.s)) continue;\n if (!rosterHas(this.roster, request.s) || request.s === this.myKey || request.s === this.admin) { this.state.pendingLeaves = this.state.pendingLeaves.filter(r => r !== request); continue; }\n try { const { hash } = await this.commit(\"leave\", { s: request.s, ls: request.ls, ...(request.ls3 ? { ls3: request.ls3 } : {}) }, now); this.markLeft(hash, request.s); done++; } catch { /* not allowed right now */ }\n this.state.pendingLeaves = this.state.pendingLeaves.filter(r => r !== request);\n }\n if (done) await this.persist();\n return done;\n });\n }\n\n /**\n * Signs and says how far I had heard a member whose leave I just committed (`group-left`): per epoch, up to the first\n * number of my window of it I never heard, so a copy of the leaver's state cannot sign one later into the gap. A gap\n * at the window's bottom (a jump past it, or a counter raised by a restore) leaves the epoch out: nothing of it then.\n */\n private markLeft(h: string, leaver: string): void {\n const hi: Record<string, number> = {};\n const heard = Object.entries(this.state.seen[leaver] ?? {}).filter(([k]) => LEFT_EPOCH.test(k)).slice(-COMMUNITY_LIMITS.leftMarks);\n for (const [k, entry] of heard) {\n const bottom = Math.max(0, entry.high - COMMUNITY_LIMITS.replay + 1);\n let n = bottom;\n while (n < entry.high && entry.window.includes(n)) n++;\n const top = n === entry.high ? n : n - 1;\n if (top >= bottom) hi[k] = top;\n }\n const sig = toBase64Url(sign(leftStatement(this.id, h, hi), this.identity.seed));\n this.keepLeft(h, { hi, sig });\n this.hooks.broadcast({ t: \"group-left\", v: 2, g: this.id, h, hi, sig });\n }\n\n private out(status: CommunityStatus, reason: string): void {\n this.state.status = status;\n this.state.statusReason = reason;\n this.state.secrets = {};\n this.state.store = [];\n delete this.state.unsaid;\n for (const id of this.onRows.values()) this.hooks.forgetFrame?.(id);\n this.onRows.clear();\n delete this.state.lasting;\n this.state.entry = { key: this.state.entry.key, seedB64: \"\" };\n this.waiting = []; this.waitingBytes = 0; this.pendingCommits.clear(); this.pendingSecrets.clear();\n }\n\n /**\n * `mentions`: places of the text that name members, sealed with it (`m`). Never everyone in a community. They\n * count against the text's 16 KiB, so the box stays within what older apps accept. `reply`: the message it\n * answers (`r`), counted the same way. `forwarded`: a forwarded text's hop count (`fw`, WISP 903 § Forwards). `card`:\n * a status card, checked by the caller (`sc`, WISP 405 · Status Cards), counted the same way; the text is its fallback.\n * `file`: a file or voice message the text announces (`fl`, WISP 503 · Group Files), counted the same way; the text is\n * its caption, or the line an older app shows.\n */\n sendText(text: string, nick?: string, now = Date.now(), mentions: readonly GroupMention[] = [], reply?: WireReply, forwarded?: number, card?: StatusCard, file?: GroupFileMeta): Promise<{ id: string } | { error: string }> {\n return this.serialize(async () => {\n if (!this.isMember) return { error: this.state.statusReason ?? \"You are not in this group\" };\n const trimmed = text.trim();\n if (!trimmed) return { error: \"Nothing to send\" };\n const described = file === undefined ? undefined : readGroupFileMeta(file);\n if (file !== undefined && !described) return { error: \"That file cannot go to a group\" };\n const named = validMentions(wireMentions(mentions), trimmed, false);\n const answers = reply && readReply(wireReply(reply), groupReplyAuthor);\n const replyBytes = answers ? utf8Encode(JSON.stringify(answers)).length : 0;\n const fileBytes = described ? utf8Encode(JSON.stringify(described)).length + 8 : 0;\n const hops = readForwarded(forwarded);\n if (utf8Encode(trimmed).length + mentionsBytes(named) + replyBytes + fileBytes + (hops ? 16 : 0) + (card ? statusCardBytes(card) + 8 : 0) > COMMUNITY_LIMITS.textBytes) return { error: \"Message exceeds 16 KiB\" };\n // A text an app killed mid-send left saved but not stored or said goes first, in its place.\n await this.sayUnsaid();\n const sent = await this.sendPayload(() => ({ text: trimmed, ...(named.length ? { m: named } : {}), ...(answers ? { r: answers } : {}), ...(hops ? { fw: hops } : {}), ...(card ? { sc: card } : {}), ...(described ? { fl: described } : {}) }), nick, now);\n if (\"error\" in sent) return sent;\n // The counter and the frame are saved before the row is stored: an app killed after the row but before the save\n // gave the next text this same id, and the members held one text or the other under it, or dropped the next as\n // seen. Until the row is stored and the frame said, the number is `unsaid`, and an app opened again does both (`resume`).\n const key = frameKey(sent.frame);\n this.state.unsaid = [...(this.state.unsaid ?? []), key];\n this.markUnheard(sent.frame);\n const unsend = async () => {\n this.state.store = this.state.store.filter(f => f !== sent.frame);\n this.state.unsaid = (this.state.unsaid ?? []).filter(k => k !== key);\n this.state.unheard = (this.state.unheard ?? []).filter(k => k !== key);\n await this.persist().catch(() => {});\n };\n try { await this.persist(); } catch (error) { await unsend(); throw error; }\n let onRow: boolean | void;\n try {\n onRow = await this.hooks.message({ id: sent.id, sender: this.myKey, epoch: sent.frame.e, seq: sent.frame.n, timestamp: now, text: trimmed, ...(named.length ? { mentions: named } : {}), ...(answers ? { reply: answers } : {}), ...(hops ? { forwarded: hops } : {}), ...(card ? { card } : {}), ...(described ? { file: described } : {}), frame: sent.frame });\n } catch (error) {\n // Never said, so not sent. A row the app stored before it failed brings its frame, and a counter above it, back\n // when the app opens again (`takeRows`).\n await unsend();\n throw error;\n }\n if (onRow === true) this.onRows.set(storeKey(sent.frame), sent.id);\n this.state.unsaid = (this.state.unsaid ?? []).filter(k => k !== key);\n // Said once more after a kill before this save: members take a frame they hold as already seen.\n await this.say(sent.frame, true);\n return { id: sent.id };\n });\n }\n\n /**\n * An application frame to everyone in the group (a note about a payment, a request anyone may pay): sealed to\n * the epoch like text, signed, kept and caught up like text, and handed to the other members' `app` hook\n * instead of their history. A fleeting one (`CommunitySessionHooks.fleeting`) is only said to those up now.\n */\n sendApp(frame: Record<string, unknown>, nick?: string, now = Date.now()): Promise<{ id: string } | { error: string }> {\n return this.serialize(async () => {\n if (!this.isMember) return { error: this.state.statusReason ?? \"You are not in this group\" };\n if (!isObject(frame) || utf8Encode(JSON.stringify(frame)).length > COMMUNITY_LIMITS.appBytes) return { error: \"Too large for the group\" };\n const fleeting = this.hooks.fleeting?.(frame) === true;\n const sent = await this.sendPayload(() => ({ x: frame }), nick, now, !fleeting);\n if (\"error\" in sent) return sent;\n if (fleeting) {\n // Its sequence number is spent: saved before it goes, so it is never sealed twice.\n await this.persist();\n this.hooks.broadcast(sent.frame);\n return { id: sent.id };\n }\n this.keepLasting({ id: sent.id, sender: this.myKey, epoch: sent.frame.e, timestamp: sent.frame.ts, frame }, sent.frame);\n await this.say(sent.frame);\n return { id: sent.id };\n });\n }\n\n /**\n * An application frame that says the group's state (`CommunitySessionHooks.lasting`) in place of the one of its\n * kind kept now, unless that one is newer (by the author's time, then its epoch, so one said again under a newer\n * commit takes the first's place, then the frame's identity, so every member keeps the same one).\n */\n private keepLasting(message: CommunityIncomingApp, frame: CommunityMessageFrame): void {\n const kind = this.hooks.lasting?.(message);\n if (typeof kind !== \"string\" || !kind) return;\n const kept = { ...this.state.lasting };\n const now = kept[kind];\n if (now && (now.ts > frame.ts || (now.ts === frame.ts && (now.e > frame.e || (now.e === frame.e && frameKey(now) >= frameKey(frame)))))) return;\n if (!now && Object.keys(kept).length >= COMMUNITY_LIMITS.lasting) return;\n kept[kind] = frame;\n this.state.lasting = kept;\n }\n\n /**\n * An edit of one of my messages (WISP 903 · Group Community § Edits): an application frame like `sendApp`'s, sealed\n * to the current epoch, but with a text's room rather than an application frame's, since it carries a whole text.\n * The nick is left out when the text leaves no room for it.\n */\n sendEdit(edit: { id: string; v: number; ts: number; text: string; mentions?: readonly GroupMention[]; card?: StatusCard; remove?: boolean }, nick?: string, now = Date.now()): Promise<{ id: string } | { error: string }> {\n return this.serialize(async () => {\n if (!this.isMember) return { error: this.state.statusReason ?? \"You are not in this group\" };\n if (communityMessageAuthor(edit.id) !== this.myKey) return { error: \"Only your own messages can be edited\" };\n if (!(edit.remove ? validRemovalNumber(edit.v) : edit.card ? cardEditNumber(edit.v) : validEditNumber(edit.v))) return { error: \"This message was edited too many times\" };\n const text = edit.text.trim();\n if (!validEditText(text)) return { error: text ? \"Message exceeds 16 KiB\" : \"An edit cannot be empty\" };\n const named = edit.remove ? [] : validMentions(wireMentions(edit.mentions ?? []), text, false);\n // A removal (WISP 400 § Delete for everyone) carries its fallback text alone.\n const frame = communityEditFrame({ id: edit.id, e: edit.v, ts: edit.ts, m: text, k: named, ...(edit.card && !edit.remove && { sc: edit.card }), ...(edit.remove && { rm: true as const }) });\n // What a message's box holds (`isMessageFrame`): the text's bound and a little more.\n const room = COMMUNITY_LIMITS.textBytes + 256, clean = sanitizeNick(nick);\n const size = (withNick: boolean) => utf8Encode(JSON.stringify(withNick && clean ? { x: frame, nick: clean } : { x: frame })).length;\n if (size(false) > room) return { error: \"Too long to edit in this group\" };\n const sent = await this.sendPayload(() => ({ x: frame }), size(true) <= room ? nick : undefined, now);\n if (\"error\" in sent) return sent;\n await this.say(sent.frame);\n return { id: sent.id };\n });\n }\n\n /**\n * A payload for one member only (`to`), carried by the group like any frame: every hub relays it and every\n * member keeps it for whoever was away, but only `to` can open it, and only I can have made it (see\n * `sealPair`). The group learns that I sent `to` something, and when; not what.\n */\n sendPair(to: string, payload: Record<string, unknown>, nick?: string, now = Date.now()): Promise<{ id: string } | { error: string }> {\n return this.serialize(async () => {\n if (!this.isMember) return { error: this.state.statusReason ?? \"You are not in this group\" };\n if (to === this.myKey || !rosterHas(this.roster, to)) return { error: \"Not a member of this group\" };\n if (!isObject(payload)) return { error: \"Nothing to send\" };\n const plain = utf8Encode(JSON.stringify(payload));\n if (plain.length > COMMUNITY_LIMITS.appBytes) return { error: \"Too large for the group\" };\n const sent = await this.sendPayload(header => ({ p: { to, ...sealPair(this.identity.seed, this.myKey, to, plain, pairAad(header, to)) } }), nick, now);\n if (\"error\" in sent) return sent;\n await this.say(sent.frame);\n return { id: sent.id };\n });\n }\n\n /** Seals, signs and keeps a frame under the current epoch (the caller holds the queue, persists and broadcasts). */\n private async sendPayload(body: (header: Pick<CommunityMessageFrame, \"g\" | \"e\" | \"h\" | \"s\" | \"n\" | \"ts\">) => Record<string, unknown>, nick: string | undefined, now: number, kept = true): Promise<{ id: string; frame: CommunityMessageFrame } | { error: string }> {\n const h = this.topHash, secret = this.state.secrets[h];\n if (!secret) return { error: \"This epoch's key has not arrived yet. Wait for a member to catch you up.\" };\n if (this.state.seqH !== h) { this.state.seq = 0; this.state.seqH = h; }\n // Every head starts at the floor, not at 0, and a floor raised under a running head counts at once.\n const floor = this.hooks.seqFloor?.() ?? 0;\n const n = Math.max(this.state.seq, Number.isSafeInteger(floor) && floor > 0 ? floor : 0);\n this.state.seq = n + 1;\n const header = { g: this.id, e: this.epoch, h: shortHash(h), s: this.myKey, n, ts: now };\n const clean = sanitizeNick(nick);\n const payload = JSON.stringify(clean ? { ...body(header), nick: clean } : body(header));\n const { n: nn, c } = encryptText(epochKeys(fromBase64Url(secret), this.id, this.epoch).message, messageAad(header), payload);\n const unsigned = { ...header, nn, c };\n const frame: CommunityMessageFrame = { t: \"group-msg\", v: 2, ...unsigned, sig: toBase64Url(sign(messageSigned(unsigned), this.identity.seed)) };\n this.markSeen(frame);\n if (kept) this.keep(frame);\n return { id: communityMessageId(this.myKey, header.e, header.h, n), frame };\n }\n\n /**\n * Saves, then says my frame on every edge. One no edge took (none is up: I just joined, or my app just opened) is\n * remembered until a member it was written for is handed it: I may be behind on the chain without knowing, and the\n * first member I reach may be one let in since, who cannot read it but can carry it (`receiveSync`). `saved`: the\n * caller marked it unheard and saved it (`sendText`).\n */\n private async say(frame: CommunityMessageFrame, saved = false): Promise<void> {\n const inStore = new Set(this.state.store.filter(f => f.s === this.myKey).map(frameKey));\n if (!saved) {\n this.markUnheard(frame);\n await this.persist();\n }\n if (this.hooks.broadcast(frame) === 0) {\n // Said alone: I may be behind on the chain without knowing (`resealBehind`).\n this.state.alone = rememberAlone(this.state.alone, frameKey(frame), key => inStore.has(key));\n this.persistSoon();\n return;\n }\n this.state.unheard = (this.state.unheard ?? []).filter(key => key !== frameKey(frame));\n this.persistSoon();\n }\n /** My frame in `unheard`, before it is said: the frames of mine the store no longer holds leave it. */\n private markUnheard(frame: CommunityMessageFrame): void {\n const inStore = new Set(this.state.store.filter(f => f.s === this.myKey).map(frameKey));\n this.state.unheard = [...(this.state.unheard ?? []).filter(key => inStore.has(key) && key !== frameKey(frame)), frameKey(frame)].slice(-UNHEARD_KEPT);\n }\n\n /**\n * Stores and says what an app killed mid-send left `unsaid`: its counter and frame were saved, its row or its sending\n * may not have happened. A row stored already is not stored twice (the app's store takes one row per id), a frame\n * that went already is taken by the members as one they hold. The engine calls this on each tick; a send does first.\n */\n resume(): Promise<void> {\n if (!this.state.unsaid?.length) return Promise.resolve();\n return this.serialize(() => this.sayUnsaid());\n }\n\n private async sayUnsaid(): Promise<void> {\n for (const key of [...this.state.unsaid ?? []]) {\n const frame = this.isMember ? this.state.store.find(f => f.s === this.myKey && frameKey(f) === key) : undefined;\n const row = frame && this.ownRow(frame);\n // Stored before it leaves the list: a store that fails keeps it there, for the next tick.\n if (frame && row) {\n let onRow: boolean | void;\n try { onRow = await this.hooks.message(row); } catch { return; }\n if (onRow === true) this.onRows.set(storeKey(frame), row.id);\n }\n this.state.unsaid = (this.state.unsaid ?? []).filter(k => k !== key);\n if (frame && row) await this.say(frame); else await this.persist();\n }\n }\n\n /** The row of one of my own texts, as `sendText` stored it, opened from its frame; none for anything else, or one deleted for everyone. */\n private ownRow(f: CommunityMessageFrame): CommunityIncomingMessage | undefined {\n const found = this.commitByShort(f.e, f.h), secret = found && this.state.secrets[found.hash];\n const plain = secret ? decryptText(epochKeys(fromBase64Url(secret), this.id, f.e).message, messageAad(f), f.nn, f.c) : null;\n let parsed: unknown = null;\n try { parsed = plain === null ? null : JSON.parse(plain); } catch { /* not a payload */ }\n if (!isObject(parsed) || typeof parsed.text !== \"string\" || parsed.o !== undefined) return undefined;\n const id = communityMessageId(this.myKey, f.e, f.h, f.n);\n if (this.hooks.removed?.(id)) return undefined;\n const text = parsed.text, mentions = validMentions(parsed.m, text, false), reply = parsed.r === undefined ? undefined : readReply(parsed.r, groupReplyAuthor);\n const forwarded = readForwarded(parsed.fw), card = parsed.sc === undefined ? undefined : readStatusCard(parsed.sc), file = parsed.fl === undefined ? undefined : readGroupFileMeta(parsed.fl) ?? undefined;\n return { id, sender: this.myKey, epoch: f.e, seq: f.n, timestamp: f.ts, text, ...(mentions.length ? { mentions } : {}), ...(reply ? { reply } : {}),\n ...(forwarded ? { forwarded } : {}), ...(card ? { card } : {}), ...(file ? { file } : {}), frame: f };\n }\n\n /**\n * Message `id` was deleted for everyone (WISP 400 § Delete for everyone), by its author or here: its frame goes from\n * the store, so no catch-up hands it to a member who was away (they get the removal, which stays). A frame said again\n * (`reseal`) carries the first one's place inside: its author's are opened to tell.\n */\n forget(id: string): void {\n const author = id.slice(0, id.indexOf(\":\"));\n const kept = this.state.store.filter(f => f.s !== author || this.storedId(f) !== id);\n const dropped = kept.length !== this.state.store.length;\n if (dropped) {\n const left = new Set(kept.map(storeKey));\n for (const f of this.state.store) if (!left.has(storeKey(f))) this.onRows.delete(storeKey(f));\n this.state.store = kept;\n }\n if (this.unquote(quoted => quoted === id) || dropped) this.persistSoon();\n }\n\n /**\n * The frames whose reply quotes a message deleted for everyone (`gone`): the line of it (`r.s`) is sealed with them,\n * and opens with the epoch secret this profile keeps. Mine is sealed again with an empty line, in its place, time and\n * reply, and signed again: a member who holds the first drops it as seen, one who missed it gets the reply without\n * the line. A member's I cannot sign again: it goes, and its author hands it on. Either way the row that held the\n * first gives it up; mine is saved with the state from then on.\n */\n private unquote(gone: (id: string) => boolean): boolean {\n let changed = false;\n const store: CommunityMessageFrame[] = [];\n for (const f of this.state.store) {\n const key = this.messageKey(f);\n const plain = key ? decryptText(key, messageAad(f), f.nn, f.c) : null;\n let parsed: unknown = null;\n try { parsed = plain === null ? null : JSON.parse(plain); } catch { /* not a payload */ }\n const r = isObject(parsed) ? parsed.r : undefined;\n if (!isObject(r) || typeof r.i !== \"string\" || r.s === \"\" || !gone(r.i)) { store.push(f); continue; }\n changed = true;\n const row = this.onRows.get(storeKey(f));\n if (row !== undefined) { this.onRows.delete(storeKey(f)); this.hooks.forgetFrame?.(row); }\n if (f.s !== this.myKey) continue;\n const { n: nn, c } = encryptText(key!, messageAad(f), JSON.stringify({ ...(parsed as Record<string, unknown>), r: { ...r, s: \"\" } }));\n const unsigned = { g: f.g, e: f.e, h: f.h, s: f.s, n: f.n, ts: f.ts, nn, c };\n store.push({ t: \"group-msg\", v: 2, ...unsigned, sig: toBase64Url(sign(messageSigned(unsigned), this.identity.seed)) });\n }\n if (changed) this.state.store = store;\n return changed;\n }\n\n /** The key a stored frame is sealed with, when I hold its epoch's secret. */\n private messageKey(f: CommunityMessageFrame): Uint8Array | undefined {\n const found = this.commitByShort(f.e, f.h), secret = found && this.state.secrets[found.hash];\n return secret ? epochKeys(fromBase64Url(secret), this.id, f.e).message : undefined;\n }\n\n /** The id of the message a stored frame is, by its first place when it was said again (and I can open it). */\n private storedId(f: CommunityMessageFrame): string {\n const found = this.commitByShort(f.e, f.h), secret = found && this.state.secrets[found.hash];\n const plain = secret ? decryptText(epochKeys(fromBase64Url(secret), this.id, f.e).message, messageAad(f), f.nn, f.c) : null;\n let parsed: unknown = null;\n try { parsed = plain === null ? null : JSON.parse(plain); } catch { /* not a payload: its own place */ }\n const original = isObject(parsed) && parsed.o !== undefined ? readOriginal(parsed.o, f) : null;\n return original ? communityMessageId(f.s, original.e, original.h, original.n) : communityMessageId(f.s, f.e, f.h, f.n);\n }\n\n private keep(frame: CommunityMessageFrame): void {\n // Taken again after a save that was lost (`persistSoon`): its row, and so the store, has it already.\n if (this.onRows.has(storeKey(frame))) return;\n this.state.store.push(frame);\n this.trimStore();\n }\n private trimStore(): void {\n let bytes = this.state.store.reduce((sum, f) => sum + f.c.length, 0);\n while (this.state.store.length > COMMUNITY_LIMITS.store || bytes > COMMUNITY_LIMITS.storeBytes) {\n const oldest = this.state.store.shift()!;\n bytes -= oldest.c.length;\n const row = this.onRows.get(storeKey(oldest));\n if (row === undefined) continue;\n this.onRows.delete(storeKey(oldest));\n this.hooks.forgetFrame?.(row);\n }\n }\n /** The frames the app's rows hold, into the store: oldest first by when they were written, with what the record kept from before. */\n private takeRows(rows: readonly { id: string; frame: CommunityMessageFrame }[]): void {\n if (!rows.length) return;\n const inRecord = new Map(this.state.store.map(f => [storeKey(f), f]));\n for (const { id, frame } of rows) {\n // My counter goes above a row of mine an older app stored before it was killed mid-send, its counter unsaved.\n if (frame.s === this.myKey && frame.h === shortHash(this.state.seqH) && frame.n >= this.state.seq && frame.n < OWN_FRAME_LIMIT) this.state.seq = frame.n + 1;\n // Mine sealed again since (`unquote`), the app stopped before the row gave the first up: the record's stands.\n const recorded = inRecord.get(storeKey(frame));\n if (recorded && frame.s === this.myKey && recorded.sig !== frame.sig) { this.hooks.forgetFrame?.(id); continue; }\n this.onRows.set(storeKey(frame), id);\n if (!recorded) this.state.store.push(messageFields(frame));\n }\n this.state.store.sort((a, b) => a.ts - b.ts);\n this.trimStore();\n }\n\n /**\n * My frames sealed under a commit I took for the newest while I was behind (no edge was up, and others were let in\n * meanwhile): the members let in before I said them could never open them. Once the chain I follow (and its secret)\n * says so, each is said again under the current commit, with the same content and time and `o` naming the first, so\n * those who read the first do not show it twice and everyone keeps one id for it (replies, edits, reactions). Once\n * per frame, when the chain has settled. A payload for one member is sealed to its first frame and cannot be said\n * again: it stays as it was. The engine calls `reseal` now and then.\n */\n reseal(): Promise<void> {\n if (!this.state.alone?.length) return Promise.resolve();\n return this.serialize(async () => {\n const now = this.hooks.clock?.() ?? Date.now();\n if (this.needsCatchUp || now - this.chainMovedAt < SAID_AGAIN.settledMs) return;\n await this.resealBehind();\n });\n }\n\n private async resealBehind(): Promise<void> {\n if (!this.isMember || !this.state.alone?.length || !this.state.secrets[this.topHash]) return;\n const alone = new Set(this.state.alone);\n // When each member now in was let in (its last admission), by the admitting member's clock: before my frame, by\n // mine, it was in the group when I said it. (Someone let in after it is not handed what came before.)\n const admitted = new Map<string, number>();\n for (const c of this.state.chain) if (c.k === \"add\" && c.s) admitted.set(c.s, c.ts);\n const looked: string[] = [];\n for (const f of [...this.state.store]) {\n if (f.s !== this.myKey || !alone.has(frameKey(f))) continue;\n const found = this.commitByShort(f.e, f.h);\n // Still the newest I know: nothing says yet whether I was behind.\n if (!found || found.hash === this.topHash || !this.mainIndex.has(found.hash)) continue;\n looked.push(frameKey(f));\n const then = this.rosterAt(found.hash), secret = this.state.secrets[found.hash];\n if (!then || !secret) continue;\n const since = this.roster.filter(([key]) => !rosterHas(then, key)).map(([key]) => admitted.get(key) ?? Infinity);\n // Only for members let in before I said it, and never sealed where one let in after could open it: the current\n // commit is the one sealing it, so one such member there means it stays as it was.\n if (!since.some(ts => ts <= f.ts) || since.some(ts => ts > f.ts)) continue;\n const plain = decryptText(epochKeys(fromBase64Url(secret), this.id, f.e).message, messageAad(f), f.nn, f.c);\n let parsed: unknown = null;\n try { parsed = plain === null ? null : JSON.parse(plain); } catch { /* not a payload to say again */ }\n if (!isObject(parsed) || isObject(parsed.p)) continue;\n // Said again once already (I was behind twice): it still names the very first.\n const o = readOriginal(parsed.o, f) ?? { e: f.e, h: f.h, n: f.n };\n const { nick, o: _first, ...body } = parsed;\n void _first;\n const name = typeof nick === \"string\" ? nick : undefined;\n const fits = (withNick: boolean) => Math.ceil((utf8Encode(JSON.stringify({ ...body, o, ...(withNick && name ? { nick: name } : {}) })).length + 16) * 4 / 3) + 4 <= MAX_TEXT_BOX;\n if (!fits(false)) continue;\n const sent = await this.sendPayload(() => ({ ...body, o }), fits(true) ? name : undefined, f.ts);\n if (\"error\" in sent) continue;\n this.resealedFrom.set(frameKey(sent.frame), communityMessageId(this.myKey, o.e, o.h, o.n));\n await this.say(sent.frame);\n }\n if (!looked.length) return;\n // Looked at once each; one said again that reached nobody is in the list again, by its own key.\n this.state.alone = (this.state.alone ?? []).filter(key => !looked.includes(key));\n this.persistSoon();\n }\n\n /**\n * My lasting frames (`keepLasting`), said again under the current commit once theirs is half the window behind: past\n * the window no member finds that commit or holds its secret, and a member back from away after more commits than\n * that was never handed the group's state. With the same content and time and `o` naming the first, as\n * `resealBehind` says one, so it stays one message, and in the place of the one kept, everywhere.\n */\n private async renewLasting(): Promise<void> {\n if (!this.isMember || !this.state.secrets[this.topHash]) return;\n for (const [kind, f] of Object.entries(this.state.lasting ?? {})) {\n if (f.s !== this.myKey || this.epoch - f.e < COMMUNITY_LIMITS.window / 2) continue;\n const found = this.commitByShort(f.e, f.h), secret = found && this.state.secrets[found.hash];\n if (!secret) continue;\n const plain = decryptText(epochKeys(fromBase64Url(secret), this.id, f.e).message, messageAad(f), f.nn, f.c);\n let parsed: unknown = null;\n try { parsed = plain === null ? null : JSON.parse(plain); } catch { /* not a payload to say again */ }\n if (!isObject(parsed) || !isObject(parsed.x)) continue;\n const o = readOriginal(parsed.o, f) ?? { e: f.e, h: f.h, n: f.n };\n const id = communityMessageId(this.myKey, o.e, o.h, o.n);\n // Still the group's state, said by me (an admin's pin, while I am the admin).\n if (this.hooks.lasting?.({ id, sender: this.myKey, epoch: this.epoch, timestamp: f.ts, frame: parsed.x }) !== kind) continue;\n const { nick, o: _first, ...body } = parsed;\n void _first;\n const name = typeof nick === \"string\" ? nick : undefined;\n const fits = (withNick: boolean) => Math.ceil((utf8Encode(JSON.stringify({ ...body, o, ...(withNick && name ? { nick: name } : {}) })).length + 16) * 4 / 3) + 4 <= MAX_TEXT_BOX;\n if (!fits(false)) continue;\n const sent = await this.sendPayload(() => ({ ...body, o }), fits(true) ? name : undefined, f.ts);\n if (\"error\" in sent) continue;\n this.resealedFrom.set(frameKey(sent.frame), id);\n this.keepLasting({ id, sender: this.myKey, epoch: sent.frame.e, timestamp: f.ts, frame: parsed.x }, sent.frame);\n await this.say(sent.frame);\n }\n }\n\n /** Whether a lasting frame kept here is `f`'s author's, said at its time, and is the message `id` (the first's, said again). */\n private keepsLasting(f: CommunityMessageFrame, id: string): boolean {\n return Object.values(this.state.lasting ?? {}).some(kept => {\n if (kept.s !== f.s || kept.ts !== f.ts || frameKey(kept) === frameKey(f)) return false;\n const found = this.commitByShort(kept.e, kept.h), secret = found && this.state.secrets[found.hash];\n const plain = secret ? decryptText(epochKeys(fromBase64Url(secret), this.id, kept.e).message, messageAad(kept), kept.nn, kept.c) : null;\n let parsed: unknown;\n try { parsed = plain === null ? null : JSON.parse(plain); } catch { return false; }\n if (!isObject(parsed)) return false;\n const o = readOriginal(parsed.o, kept) ?? kept;\n return communityMessageId(kept.s, o.e, o.h, o.n) === id;\n });\n }\n\n /** The message a frame of mine is: the first one's id for a frame said again (`resealBehind`), else its own. */\n messageIdOf(f: { s: string; e: number; h: string; n: number }): string {\n return (f.s === this.myKey && this.resealedFrom.get(frameKey(f))) || communityMessageId(f.s, f.e, f.h, f.n);\n }\n\n /**\n * Where I am and what I have, for the member at the other end of an edge that just opened. `to`: that member, now\n * asked: my answer to its own sync asks nothing more for a while. A second sync went, and its answer took the place of\n * what was left of the first from its start: a member back after 256 messages was handed 288 (2026-10-14).\n */\n syncFrame(to?: string): CommunitySyncFrame {\n if (to) { const now = this.hooks.clock?.() ?? Date.now(); this.asked.set(to, now); this.answering.set(to, now + ANSWER_WINDOW_MS); }\n const have: Record<string, Record<string, number>> = {};\n const recent = new Set(this.state.store.map(f => seenKey(f.e, f.h)));\n const now = this.hooks.clock?.() ?? Date.now();\n for (const [sender, byKey] of Object.entries(this.state.seen)) for (const [key, entry] of Object.entries(byKey)) {\n if (!recent.has(key)) continue;\n (have[sender] ??= {})[key] = this.haveOf(entry, now);\n }\n // The lasting frames I hold too: once their epoch has no frame left in the store, every answer handed me the pin\n // again, dropped as a duplicate (2026-10-16).\n for (const f of Object.values(this.state.lasting ?? {})) {\n const key = seenKey(f.e, f.h);\n (have[f.s] ??= {})[key] ??= Math.max(f.n, this.state.seen[f.s]?.[key]?.high ?? -1);\n }\n if (to) {\n const open = this.answerOf.get(to);\n this.answerOf.set(to, { have: Object.fromEntries(Object.entries(have).map(([sender, byKey]) => [sender, { ...byKey }])), top: open?.top ?? {}, heard: open?.heard ?? false });\n }\n const secrets = this.state.chain.slice(-COMMUNITY_LIMITS.window - 1).map(c => this.hashOf(c)).filter(h => this.state.secrets[h]).map(shortHash);\n const loc: string[] = [];\n for (let back = 1; back < this.state.chain.length && loc.length < 12; back *= 2) loc.push(this.hashOf(this.state.chain[this.state.chain.length - 1 - back]));\n return { t: \"group-sync\", v: 2, g: this.id, e: this.epoch, h: this.topHash, loc, have, secrets, mt: groupMetaTag(this.state.meta) };\n }\n\n // -- frames from others --------------------------------------------------------------------------\n\n /**\n * A frame from the edge of member `from` (the author, or a hub relaying it). Returns whether it\n * was new and valid, so a hub knows to relay it on.\n */\n handle(from: string, raw: unknown): Promise<boolean> {\n return this.serialize(async () => {\n if (!raw || typeof raw !== \"object\") return false;\n const frame = raw as Record<string, unknown>;\n if (frame.g !== this.id || frame.v !== 2) return false;\n // A frame of an answer to my sync keeps it open: the answer goes a slice at a time.\n const now = this.hooks.clock?.() ?? Date.now();\n if ((this.answering.get(from) ?? 0) > now) {\n this.answering.set(from, now + ANSWER_WINDOW_MS);\n const answer = this.answerOf.get(from);\n if (answer) answer.heard = true;\n }\n // A member who lost its admission still hears commits: the next one may take it in. One that left, while it\n // follows its chain (`followAfterLeave`): the next one may hand it the role.\n 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;\n switch (frame.t) {\n case \"group-msg\": return this.receiveMessage(from, raw);\n case \"group-commit\": return this.receiveCommit(from, frame.commit);\n case \"group-secret\": {\n if (frame.to !== this.myKey || typeof frame.h !== \"string\") return false;\n const took = this.takeSecret(frame.h, frame.s);\n if (took) await this.tookSecrets();\n return took;\n }\n case \"group-secrets\": {\n if (!Array.isArray(frame.secrets) || frame.secrets.length > COMMUNITY_LIMITS.secrets) return false;\n let took = false;\n for (const entry of frame.secrets as { h?: unknown; s?: unknown }[]) if (entry && typeof entry.h === \"string\") took = this.takeSecret(entry.h, entry.s) || took;\n if (took) await this.tookSecrets();\n return false;\n }\n case \"group-sync\": await this.receiveSync(from, frame as unknown as CommunitySyncFrame); return false;\n case \"group-meta\": return this.receiveMeta(from, raw);\n case \"group-leave\": return this.receiveLeave(frame);\n case \"group-left\": return this.receiveLeft(frame);\n case \"group-entry\": {\n if (frame.to !== this.myKey || !isSealed(frame.s) || frame.x !== this.currentEntryKey()) return false;\n // Every sync answer carries it: the seed of that key, held already, is not opened again (a key has one seed).\n if (this.state.entry.key === frame.x && this.state.entry.seedB64) return false;\n const seed = openSecret(this.identity.seed, this.myKey, frame.s, entryAad(this.id, this.myKey));\n return !!seed && this.takeEntrySeed(toBase64Url(seed));\n }\n default: return false;\n }\n });\n }\n\n /** After a secret came that confirms: a branch that waited for it may be the one to follow now (see `better`). */\n private async tookSecrets(): Promise<void> {\n if (this.bestBranch().tip !== this.topHash) { await this.chooseBranch(); return; }\n // Within a second, as a commit (agents#1767): a catch-up hands one per epoch.\n this.persistSoon(); this.hooks.changed(); await this.replayWaiting();\n }\n\n /**\n * The member a leave frame is from, when that member signed it and is in this admission (as `receiveLeave` checks);\n * else undefined. For an app that left and follows the chain (`followAfterLeave`): it holds no requests, and a leave\n * it counts takes that member out of whom a role that reached it goes on to.\n */\n signedLeave(frame: Record<string, unknown>): string | undefined {\n const s = frame.s, ls = frame.ls;\n if (typeof s !== \"string\" || !MEMBER_KEY.test(s) || typeof ls !== \"string\" || !SIG.test(ls) || !rosterHas(this.roster, s)) return undefined;\n const ls3 = typeof frame.ls3 === \"string\" && SIG.test(frame.ls3) ? frame.ls3 : undefined;\n if (!verify(fromBase64Url(ls), leaveStatement(this.id, s), publicKeyFromZ32(s))) return undefined;\n return leaveStands({ g: this.id, s, ls, ls3 }, this.ancestry(this.topHash)) ? s : undefined;\n }\n\n private receiveLeave(frame: Record<string, unknown>): boolean {\n const s = frame.s, ls = frame.ls;\n if (typeof s !== \"string\" || !MEMBER_KEY.test(s) || typeof ls !== \"string\" || !SIG.test(ls) || !rosterHas(this.roster, s)) return false;\n const ls3 = typeof frame.ls3 === \"string\" && SIG.test(frame.ls3) ? frame.ls3 : undefined;\n // One request a member; the one that names the admission takes the place of one that does not (a hub from before passes on `ls` alone).\n let held = this.state.pendingLeaves.find(r => r.s === s);\n // A request kept from an earlier admission of this member (someone else committed it) is not one for this admission.\n if (held && !leaveStands({ g: this.id, ...held }, this.ancestry(this.topHash))) { this.state.pendingLeaves = this.state.pendingLeaves.filter(r => r !== held); held = undefined; }\n if (held && (held.ls3 || !ls3)) return false;\n if (!verify(fromBase64Url(ls), leaveStatement(this.id, s), publicKeyFromZ32(s))) return false;\n if (!leaveStands({ g: this.id, s, ls, ls3 }, this.ancestry(this.topHash))) return false;\n this.state.pendingLeaves = [...this.state.pendingLeaves.filter(r => r !== held), { s, ls, ...(ls3 ? { ls3 } : {}) }].slice(-COMMUNITY_LIMITS.pendingLeaves);\n this.persistSoon();\n return true;\n }\n\n /**\n * What a hub hands on of a frame it took (`handle` said it was new): as it came, without the live mark of whoever\n * handed it to me, and with mine when it came live here (WISP 903 § Relaying, revision 2026-11-03). Hand it on at\n * once: the mark says it is passed on as it came.\n */\n passOn(frame: object): object {\n if (!isMessageFrame(frame)) return frame;\n const fields = messageFields(frame);\n return this.cameLive.has(frame) ? { ...fields, lv: this.myKey } : fields;\n }\n\n /** `waited`: it waited for a commit or a secret (`replayWaiting`), so it is not live. */\n private async receiveMessage(from: string, input: unknown, waited = false): Promise<boolean> {\n if (!isMessageFrame(input)) return false;\n // The live mark is the hop's, never the frame's: it is not kept, stored or handed on as it came.\n const mark = (input as { lv?: unknown }).lv;\n const raw = messageFields(input);\n if (raw.s === this.myKey) { this.ownFrame(raw); return false; }\n const now = this.hooks.clock?.() ?? Date.now();\n // Straight from its author, outside its answer to my sync; or handed on at once by the member at the other end,\n // whose mark names itself, and not so old that the mark would make a catch-up ring.\n const live = !waited && (raw.s === from ? (this.answering.get(from) ?? 0) <= now\n : mark === from && rosterHas(this.roster, from) && now - raw.ts <= COMMUNITY_LIMITS.liveMarkMs);\n if (live) this.cameLive.add(input);\n // One I took already (from a second hub, or in a catch-up answer) is dropped before its signature is checked: it\n // would be dropped below whether the signature holds or not.\n if (this.isDuplicate(raw)) { this.handedInAnswer(from, raw, now); return false; }\n // Signed by its author before anything else, so a frame no member wrote takes no member's place among those waiting\n // (`park`).\n if (!verify(fromBase64Url(raw.sig), messageSigned(raw), publicKeyFromZ32(raw.s))) return false;\n // Someone removed is heard no more, even for an epoch it was in (whose secret it still holds); one who left, for\n // what it wrote before its leave only (and for the epochs it was in: the roster check below).\n if (!this.heardAfterOut(raw)) return false;\n const found = this.commitByShort(raw.e, raw.h);\n if (!found) { this.park(from, raw); return false; }\n const roster = this.rosterOf(found.hash)!;\n // Not from a member of that epoch: nothing to read, nothing to relay.\n if (!rosterHas(roster, raw.s)) return false;\n // At its author's pace, once it is known to be theirs: past it, neither kept nor passed on (it comes again in a catch-up).\n let pace = this.messagePace.get(raw.s);\n if (!pace) this.messagePace.set(raw.s, pace = new MessagePace());\n if (!pace.take(seenKey(raw.e, raw.h), raw.n, raw.c.length, this.hooks.clock?.() ?? Date.now())) return false;\n this.handedInAnswer(from, raw, now);\n // From before I was let in: nothing for me to read, but its author may have reached nobody else yet (it wrote\n // before it heard of me, with no edge up, and I am its hub). Kept and passed on like any frame, never opened, so\n // the members it was written for get it; the store hands it to those only.\n if (!rosterHas(roster, this.myKey)) {\n this.markSeen(raw);\n this.keep(raw);\n this.persistSoon();\n return true;\n }\n const secret = this.state.secrets[found.hash];\n if (!secret) { this.park(from, raw); return true; }\n const payload = decryptText(epochKeys(fromBase64Url(secret), this.id, raw.e).message, messageAad(raw), raw.nn, raw.c);\n if (payload === null) return false;\n let parsed: { text?: unknown; nick?: unknown; x?: unknown; p?: unknown; m?: unknown; r?: unknown; fw?: unknown; sc?: unknown; fl?: unknown; o?: unknown };\n try { parsed = JSON.parse(payload) as typeof parsed; } catch { return false; }\n if (!isObject(parsed)) return false;\n // Said again under a newer commit (its author was behind): the message it first was, by that one's identity. Taken\n // already (I could read the first one): kept and passed on for those who could not, not shown twice.\n const original = parsed.o === undefined ? null : readOriginal(parsed.o, raw);\n if (parsed.o !== undefined && !original) return false;\n const first = original ? { s: raw.s, ...original } : raw;\n // (A first one I only carried, let in after it was sealed, was never shown here: this one is.)\n const firstAt = original && this.commitByShort(original.e, original.h);\n const readFirst = !!firstAt && rosterHas(this.rosterOf(firstAt.hash) ?? [], this.myKey);\n const id = communityMessageId(raw.s, first.e, first.h, first.n);\n // Deleted for everyone (`hooks.removed`): it stays gone here, and is neither kept nor passed on.\n if (this.hooks.removed?.(id)) { this.markSeen(raw); this.persistSoon(); return false; }\n // Or the group's state said again once more (`renewLasting`), its first past the window: the one kept here names it.\n if (original && ((readFirst && this.isDuplicate(first)) || this.keepsLasting(raw, id))) {\n // Kept in the first's place, so it outlives the first's commit.\n if (isObject(parsed.x)) this.keepLasting({ id, sender: raw.s, epoch: raw.e, timestamp: raw.ts, frame: parsed.x }, raw);\n this.markSeen(raw); this.keep(raw); this.persistSoon(); return true;\n }\n const text = typeof parsed.text === \"string\" ? parsed.text.slice(0, COMMUNITY_LIMITS.textBytes) : undefined;\n // Exactly one of: text, an application frame for the group, a payload for one member.\n if ([text !== undefined, isObject(parsed.x), isObject(parsed.p)].filter(Boolean).length !== 1) return false;\n const nick = typeof parsed.nick === \"string\" ? sanitizeNick(parsed.nick) : undefined;\n if (nick && this.state.nicks[raw.s] !== nick) { this.state.nicks[raw.s] = nick; this.hooks.changed(); }\n let onRow: boolean | void = false, fleeting = false;\n if (text !== undefined) {\n const mentions = validMentions(parsed.m, text, false);\n // A reply that does not hold is left out, never the text.\n const reply = parsed.r === undefined ? undefined : readReply(parsed.r, groupReplyAuthor);\n const forwarded = readForwarded(parsed.fw);\n // A card that does not hold is left out: the text, its fallback, shows.\n const card = parsed.sc === undefined ? undefined : readStatusCard(parsed.sc);\n // A file that does not hold is left out too (WISP 503): the text, its caption or fallback line, shows.\n const file = parsed.fl === undefined ? undefined : readGroupFileMeta(parsed.fl) ?? undefined;\n onRow = await this.hooks.message({ id, sender: raw.s, epoch: raw.e, seq: raw.n, timestamp: raw.ts, text, ...(mentions.length ? { mentions } : {}), ...(reply ? { reply } : {}), ...(forwarded ? { forwarded } : {}), ...(card ? { card } : {}), ...(file ? { file } : {}), frame: raw, ...(live ? { live: true as const } : {}) });\n }\n else if (isObject(parsed.x)) {\n const app = { id, sender: raw.s, epoch: raw.e, timestamp: raw.ts, frame: parsed.x };\n fleeting = this.hooks.fleeting?.(parsed.x) === true;\n if (!fleeting) this.keepLasting(app, raw);\n await this.hooks.app?.(app);\n }\n else {\n // Someone else's is carried and kept for them, never opened; mine opens only if its sender sealed it to me here.\n const box = parsed.p as Record<string, unknown>;\n if (!isPairBox(box)) return false;\n if (box.to === this.myKey) {\n const plain = openPair(this.identity.seed, this.myKey, raw.s, box, pairAad(raw, this.myKey));\n let opened: unknown = null;\n try { opened = plain && plain.length <= COMMUNITY_LIMITS.appBytes ? JSON.parse(utf8Decode(plain)) : null; } catch { /* not JSON: dropped */ }\n if (isObject(opened)) await this.hooks.pair?.({ id, sender: raw.s, epoch: raw.e, timestamp: raw.ts, payload: opened });\n }\n }\n this.markSeen(raw);\n // The first one, should it come too (from a member who carried it): a duplicate. Only under a commit I know: a\n // place naming none would be a new entry in `seen` per frame, never pruned before the window passes it.\n if (original && firstAt) this.markSeen({ ...raw, ...original });\n // A hint (`hooks.fleeting`) is passed on, never kept.\n if (!fleeting) this.keep(raw);\n if (onRow === true) this.onRows.set(storeKey(raw), id);\n // The message itself is stored already; what changed here (seen, store) is saved in a batch.\n this.persistSoon();\n return true;\n }\n\n /**\n * A frame signed with my own key that I did not send here: another copy of this profile sent it (a restored backup, a\n * device that took over while this one was away, WISP 06). It is not shown, as before; but my counter goes above it\n * under this head, so what I send next is not dropped by the others as already seen.\n */\n private ownFrame(raw: CommunityMessageFrame): void {\n const top = this.topHash;\n if (raw.h !== shortHash(top)) return;\n const current = this.state.seqH === top ? this.state.seq : 0;\n // A number past every floor a copy may have (`OWN_FRAME_LIMIT`) is not taken: the counter must fit in 32 bits.\n if (raw.n < current || raw.n >= OWN_FRAME_LIMIT) return;\n try { if (!verify(fromBase64Url(raw.sig), messageSigned(raw), publicKeyFromZ32(raw.s))) return; } catch { return; }\n this.state.seq = raw.n + 1; this.state.seqH = top;\n this.persistSoon();\n }\n private isDuplicate(f: { s: string; e: number; h: string; n: number }): boolean { return seenIn(this.state.seen, f); }\n /**\n * What a sync says I have of a sender under a commit: below the lowest number missing, not the highest seen. A live\n * frame raises the highest above that sender's frames still coming in a catch-up answer, and when the rest of the\n * answer never came (my app closed or my edge dropped, or the hub's app closed), every later sync said I had them:\n * they were lost for good (2026-10-18). A gap asked for by `GAP_ASKS` syncs at least `GAP_ASK_MS` apart that none\n * filled (the stores rolled past it, a leaver's frames) is given up: each answer hands what is stored above it again.\n */\n private haveOf(entry: CommunityState[\"seen\"][string][string], now: number): number {\n const got = new Set(entry.window);\n let gap = -1;\n for (let n = Math.max(0, entry.high - COMMUNITY_LIMITS.replay + 1, (entry.floor ?? -1) + 1); n < entry.high; n++) if (!got.has(n)) { gap = n; break; }\n if (gap < 0) { if (entry.gap) { delete entry.gap; this.persistSoon(); } return entry.high; }\n const [asked, times, at] = entry.gap ?? [-1, 0, 0];\n if (asked === gap && now - at < GAP_ASK_MS) return gap - 1;\n this.persistSoon();\n if (asked === gap && times >= GAP_ASKS) { delete entry.gap; entry.floor = entry.high; return entry.high; }\n entry.gap = [gap, asked === gap ? times + 1 : 1, now];\n return gap - 1;\n }\n /** A frame (known to be its author's) from a member whose answer to my sync is open: the highest it handed (`settleGaps`). */\n private handedInAnswer(from: string, f: { s: string; e: number; h: string; n: number }, now: number): void {\n const answer = (this.answering.get(from) ?? 0) > now ? this.answerOf.get(from) : undefined;\n if (!answer) return;\n const byKey = (answer.top[f.s] ??= {}), key = seenKey(f.e, f.h);\n byKey[key] = Math.max(f.n, byKey[key] ?? -1);\n }\n private markSeen(f: CommunityMessageFrame): void {\n const bySender = (this.state.seen[f.s] ??= {});\n const entry = (bySender[seenKey(f.e, f.h)] ??= { high: -1, window: [] });\n if (f.n > entry.high) { if (entry.high >= 0) entry.window.push(entry.high); entry.high = f.n; }\n else entry.window.push(f.n);\n entry.window = entry.window.filter(n => n > entry.high - COMMUNITY_LIMITS.replay);\n for (const key of Object.keys(bySender)) if (Number(key.split(\":\")[0]) < this.epoch - COMMUNITY_LIMITS.window) delete bySender[key];\n if (!Object.keys(bySender).length) delete this.state.seen[f.s];\n }\n\n private park(from: string, frame: CommunityMessageFrame): void {\n if (frame.e > this.epoch + COMMUNITY_LIMITS.window) return;\n if (this.waiting.some(w => w.frame.s === frame.s && w.frame.e === frame.e && w.frame.h === frame.h && w.frame.n === frame.n)) return;\n // Its signature says only that its key wrote it, and anyone can make a key: one no commit I know names waits among\n // `waitingStrangers` only (`COMMUNITY_LIMITS`), and goes before any member's.\n const stranger = !rosterHas(this.roster, frame.s) && !this.isRecentMember(frame.s);\n this.waiting.push({ from, frame, stranger });\n this.waitingBytes += frame.c.length;\n for (;;) {\n const strangers = this.waiting.filter(w => w.stranger).length;\n if (strangers <= COMMUNITY_LIMITS.waitingStrangers && this.waiting.length <= COMMUNITY_LIMITS.waiting && this.waitingBytes <= COMMUNITY_LIMITS.waitingBytes) break;\n this.waitingBytes -= this.waiting.splice(strangers ? this.waiting.findIndex(w => w.stranger) : 0, 1)[0].frame.c.length;\n }\n this.ask(from);\n }\n\n /** Something is missing here: the current epoch's secret, or the epoch of a member's frames waiting. */\n get needsCatchUp(): boolean {\n if (!this.isMember) return false;\n this.dropStale(this.pendingCommits, this.hooks.clock?.() ?? Date.now());\n return !this.state.secrets[this.topHash] || this.waiting.some(w => !w.stranger) || this.pendingCommits.size > 0;\n }\n /** Asks a member I have an edge to for what I lack (the engine calls it now and then while `needsCatchUp`). */\n catchUp(to: string): void { this.ask(to); }\n\n private ask(from: string): void {\n const sync = this.question(from);\n if (sync) this.hooks.direct(from, sync);\n }\n /** My sync for a member, unless I asked it a moment ago. */\n private question(from: string): CommunitySyncFrame | null {\n const now = this.hooks.clock?.() ?? Date.now();\n if (now - (this.asked.get(from) ?? 0) < 5_000) return null;\n return this.syncFrame(from);\n }\n\n private async replayWaiting(): Promise<void> {\n await this.metaFollowsChain();\n const ready = this.waiting.filter(w => { const found = this.commitByShort(w.frame.e, w.frame.h); return !!found && !!this.state.secrets[found.hash]; });\n if (!ready.length) return;\n this.waiting = this.waiting.filter(w => !ready.includes(w));\n this.waitingBytes = this.waiting.reduce((sum, w) => sum + w.frame.c.length, 0);\n for (const { from, frame } of ready) await this.receiveMessage(from, frame, true);\n }\n\n private async receiveSync(from: string, frame: CommunitySyncFrame): Promise<void> {\n // Nothing is sealed to a key that is not canonical (see `commit`).\n if (!isZ32Key(from) || !Number.isSafeInteger(frame.e) || typeof frame.h !== \"string\") return;\n const recent = this.isRecentMember(from), lost = recent ? undefined : this.lostAt(from);\n if (!recent && !lost) return;\n let answered = this.syncsAnswered.get(from);\n if (!answered) this.syncsAnswered.set(from, answered = new RateWindow(COMMUNITY_LIMITS.syncAnswers, COMMUNITY_LIMITS.syncWindowMs, () => this.hooks.clock?.() ?? Date.now()));\n if (!answered.take()) return;\n if (recent) await this.vouch(from, frame.mt);\n // Let in only on a branch that lost: the commits from where it parts up to the one that makes it lose, and nothing\n // else (no secret, no frame, no later link), as `farewell` tells one taken out. Its app then knows to ask again.\n // A new link's commit is never among them: its `x` is the link. When it is what makes the branch lose, the answer\n // stops before it, and the key is not told it lost.\n if (lost) {\n const at = this.mainIndex.get(frame.h);\n let commits = this.state.chain.slice(at !== undefined ? at + 1 : lost.fork + 1, lost.end + 1);\n const link = commits.findIndex(c => c.k === \"link\" && !!c.x);\n if (link >= 0) commits = commits.slice(0, link);\n if (commits.length) this.answers.handOut(from, commits.map(commit => ({ t: \"group-commit\" as const, v: 2 as const, g: this.id, commit })));\n return;\n }\n // The answer, in this order, goes out a slice at a time (`CatchUpAnswers`): a member back after the store filled\n // was handed 258 frames at once, and an app before 2026-10-07 ends a session holding 64 waiting.\n const answer: CommunityFrame[] = [];\n const ask = () => { const sync = this.question(from); if (sync) answer.push(sync); };\n const theirs = this.known.get(frame.h);\n let start: number;\n if (theirs && this.mainIndex.has(frame.h)) start = this.mainIndex.get(frame.h)! + 1;\n else if (theirs) {\n // On a branch I did not follow: mine from where they part.\n const path = this.pathToMain(frame.h);\n start = path ? this.mainIndex.get(this.known.get(path[0])!.p)! + 1 : this.state.chain.length;\n } else {\n // Unknown to me: they may be ahead, or on a branch I never saw. From where our branches part (their\n // locator says), or my recent commits; my sync makes them send theirs.\n const common = (Array.isArray(frame.loc) ? frame.loc : []).find(x => typeof x === \"string\" && this.mainIndex.has(x));\n start = common !== undefined ? this.mainIndex.get(common)! + 1 : Math.max(0, this.state.chain.length - COMMUNITY_LIMITS.side);\n ask();\n }\n // Nothing of the epoch that took them out or later, on any branch (`readsAt`).\n const out = this.outEpoch(from);\n for (let i = start; i < this.state.chain.length; i++) {\n const commit = this.state.chain[i], h = this.hashOf(commit);\n answer.push({ t: \"group-commit\", v: 2, g: this.id, commit });\n const secret = this.state.secrets[h];\n if (secret && this.readsAt(h, from, out) && FRESH.has(commit.k))\n answer.push({ t: \"group-secret\", v: 2, g: this.id, to: from, h, s: sealSecret(from, fromBase64Url(secret), secretAad(this.id, h, from)) });\n }\n // Secrets of the window they were in and lack (derived ones included: they may lack the parent).\n const held = new Set(Array.isArray(frame.secrets) ? frame.secrets.filter(x => typeof x === \"string\") : []);\n const secrets = this.state.chain.slice(-COMMUNITY_LIMITS.window - 1).map(c => this.hashOf(c))\n .filter(h => this.state.secrets[h] && !held.has(shortHash(h)) && this.readsAt(h, from, out))\n .map(h => ({ h, s: sealSecret(from, fromBase64Url(this.state.secrets[h]), secretAad(this.id, h, from)) }));\n if (secrets.length) answer.push({ t: \"group-secrets\", v: 2, g: this.id, secrets: secrets.slice(-COMMUNITY_LIMITS.secrets) });\n // What was said while they were away, by anyone, for epochs they were in.\n const have = frame.have && typeof frame.have === \"object\" ? frame.have as Record<string, Record<string, unknown>> : {};\n // A frame sealed on a branch I do not follow (two members committed one leave apart, each with a fresh secret,\n // and that branch lost) goes with that branch's commits and secret: the commits above are my branch's only, and a\n // member who was never on the other one could not place the frame, and kept it waiting for good (2026-10-02).\n const handed = new Set<string>();\n // Mine that no edge took when I said them go to a member let in since too: it cannot read them, and carries them\n // to the members they were written for (a hub passes them on). Anyone else's it could not read stays here.\n const unheard = new Set(this.state.unheard ?? []);\n const marked = new Set<string>();\n // The group's picture or name, when theirs is older (after the commits and secrets above, which it may need), each\n // statement they missed before the first message written after it: they place its line where it comes, as they do\n // each message.\n const metas = this.metaFor(from, frame.mt);\n // The group's state said once (the admin's pin) and since rolled out of the store: before the store's frames, as\n // older than all of them, under the same checks (agents#1095).\n // By author too (`storeKey`): another member's frame of the same number is not this one.\n const inStore = new Set(this.state.store.map(storeKey));\n const lasting = Object.values(this.state.lasting ?? {}).filter(f => !inStore.has(storeKey(f))).sort((a, b) => a.ts - b.ts);\n for (const stored of [...lasting, ...this.state.store]) {\n if (stored.s === from) continue;\n // What they have first: the checks below hash commits for every stored frame, and a member up to date has them\n // all; a hub answered each 30 s sync in ~4 ms (2026-10-08).\n const high = have[stored.s]?.[seenKey(stored.e, stored.h)];\n if (Number.isSafeInteger(high) && (high as number) >= stored.n) continue;\n // Deleted for everyone and still here (a removal taken by an app that kept the frame, before `forget`): their removal goes, not it.\n if (this.hooks.removed?.(communityMessageId(stored.s, stored.e, stored.h, stored.n))) continue;\n if (!this.heardAfterOut(stored)) continue;\n const found = this.commitByShort(stored.e, stored.h);\n if (!found) continue;\n const reads = this.readsAt(found.hash, from, out), mine = stored.s === this.myKey && unheard.has(frameKey(stored));\n if (!reads && !(mine && rosterHas(this.roster, from))) continue;\n if (!this.mainIndex.has(found.hash)) this.handSide(from, found.hash, handed, answer, out);\n // A leaver's frame goes after its leave's mark, without which it is not taken.\n if (!rosterHas(this.roster, stored.s) && !marked.has(stored.s)) { marked.add(stored.s); const left = this.leftFrame(stored.s); if (left) answer.push(left); }\n while (metas.length && metas[0].ts < stored.ts) answer.push(metas.shift()!.frame);\n answer.push(stored);\n // Handed to a member it was written for: heard.\n if (mine && reads) unheard.delete(frameKey(stored));\n }\n if (unheard.size !== (this.state.unheard?.length ?? 0)) { this.state.unheard = [...unheard]; this.persistSoon(); }\n // The link's seed, so they can answer it too.\n if (rosterHas(this.roster, from)) { const entry = this.entryFrame(from); if (entry) answer.push(entry); }\n // Pending leaves travel too, so whoever commits next can: those of members still in (a receiver drops the others).\n for (const request of this.state.pendingLeaves) if (rosterHas(this.roster, request.s)) answer.push({ t: \"group-leave\", v: 2, g: this.id, ...request });\n // Or here, those after every message.\n answer.push(...metas.map(m => m.frame));\n // And where I am, so they can hand me what I lack (asked once in a while, not in a loop).\n ask();\n this.answers.handOut(from, answer);\n }\n\n /** 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`. */\n private handSide(to: string, tip: string, handed: Set<string>, answer: CommunityFrame[], out = this.outEpoch(to)): void {\n for (const h of this.pathToMain(tip) ?? []) {\n if (handed.has(h)) continue;\n handed.add(h);\n answer.push({ t: \"group-commit\", v: 2, g: this.id, commit: this.known.get(h)! });\n const secret = this.state.secrets[h];\n if (secret && this.readsAt(h, to, out)) answer.push({ t: \"group-secret\", v: 2, g: this.id, to, h, s: sealSecret(to, fromBase64Url(secret), secretAad(this.id, h, to)) });\n }\n }\n\n /** The current entry seed sealed to a member, when I hold it: sealed once per seed, not on every sync answer. */\n private entryFrame(to: string): CommunityEntryFrame | null {\n const { key, seedB64 } = this.state.entry;\n if (!key || !seedB64 || !isZ32Key(to)) return null;\n const sealed = this.sealedEntries.get(to);\n if (sealed?.seedB64 === seedB64 && sealed.frame.x === key) return { ...sealed.frame };\n const frame: CommunityEntryFrame = { t: \"group-entry\", v: 2, g: this.id, to, x: key, s: sealSecret(to, fromBase64Url(seedB64), entryAad(this.id, to)) };\n this.sealedEntries.set(to, { seedB64, frame });\n return { ...frame };\n }\n\n /** A newer entry seed, from a member who holds it (see `replaceLink`): only the one the chain names. */\n takeEntrySeed(seedB64: string): boolean {\n try {\n if (!this.isMember || identityFromSeedB64(seedB64).pubKeyZ32 !== this.currentEntryKey() || this.state.entry.seedB64 === seedB64) return false;\n } catch { return false; }\n this.state.entry = { key: this.currentEntryKey(), seedB64 };\n void this.persist();\n this.hooks.changed();\n return true;\n }\n /** The entry key the main branch names now. */\n currentEntryKey(): string {\n for (let i = this.state.chain.length - 1; i >= 0; i--) if (this.state.chain[i].x !== undefined) return this.state.chain[i].x!;\n return \"\";\n }\n\n setNick(key: string, nick: string | undefined): Promise<void> {\n return this.serialize(async () => {\n const clean = sanitizeNick(nick);\n if ((this.state.nicks[key] ?? undefined) === clean) return;\n if (clean) this.state.nicks[key] = clean; else delete this.state.nicks[key];\n await this.persist();\n this.hooks.changed();\n });\n }\n\n // -- metadata (WISP 903 § Metadata) ------------------------------------------------------------\n\n /** Sets (or, with null, removes) the group's picture: only the admin, signed under the current commit. */\n setPicture(picture: string | null, now = Date.now()): Promise<void> {\n return this.serialize(async () => {\n this.requireMember();\n if (!this.isAdmin) throw new Error(\"Only the admin can change the group's picture\");\n await this.publishMeta(encodeGroupMetaBody({ ...groupMetaBody(this.state.meta), pic: picture ?? undefined }), now);\n });\n }\n\n /** Renames the group: only the admin, signed under the current commit, beside the picture. */\n rename(name: string, now = Date.now()): Promise<void> {\n return this.serialize(async () => {\n this.requireMember();\n if (!this.isAdmin) throw new Error(\"Only the admin can rename the group\");\n const body = encodeGroupMetaBody({ ...groupMetaBody(this.state.meta), name });\n if (body !== this.state.meta?.body) await this.publishMeta(body, now);\n });\n }\n\n /**\n * Names (or, with null, removes) the node that forwards the group's calls (WISP 602): only the admin, beside the name\n * and picture. `e2ee` turns sealed call media on or off (§ End-to-end encryption); left out, the group keeps what it\n * had, so naming the node again does not turn it off.\n */\n setCall(sfu: string | null, e2ee?: boolean, now = Date.now()): Promise<void> {\n return this.serialize(async () => {\n this.requireMember();\n if (!this.isAdmin) throw new Error(\"Only the admin can set the group's call node\");\n const before = groupMetaBody(this.state.meta);\n const sealed = e2ee ?? before.call?.e2ee === 1;\n const body = encodeGroupMetaBody({ ...before, call: sfu === null ? undefined : sealed ? { sfu, e2ee: 1 } : { sfu } });\n if (body !== this.state.meta?.body) await this.publishMeta(body, now);\n });\n }\n\n /**\n * Signs a body under my current commit, keeps it and sends it to everyone (hubs relay it). Inside `serialize`. Like a\n * commit, only with admin work on and a good turn read (WISP 06 § Forced takeover): refused otherwise, or, `quiet`,\n * not made. Its revision is never under the floor (WISP 06 § Raised counters).\n * `taken`: a former admin's statement signed again (`signAgainTaken`): the line credits them, and the one held is not\n * kept to hand on when it was no change (an older statement signed again).\n */\n private async publishMeta(body: string, now: number, quiet = false, taken?: { by: string; replaces: boolean }): Promise<void> {\n const refused = !this.adminWork ? new Error(GROUP_ADMIN_OFF_ERROR)\n : this.hooks.adminTurn && !(await this.hooks.adminTurn()) ? engineError(\"groupTurnUnconfirmed\") : undefined;\n if (refused) { if (quiet) return; throw refused; }\n const before = this.state.meta;\n const meta = signGroupMeta({ g: this.id, e: this.epoch, h: this.topHash, r: nextGroupMetaRevision(before, this.epoch, this.hooks.seqFloor?.()), ts: now }, body, this.identity.seed, this.myKey);\n this.state.meta = meta;\n if (!taken?.replaces) this.state.metaPast = keepPastGroupMeta(this.state.metaPast, before, meta);\n await this.persist();\n const frame = this.metaFrame(meta);\n if (frame) this.hooks.broadcast(frame);\n const change = groupMetaChange(before, meta, this.state.name);\n if (change) this.hooks.metaChanged?.(taken?.by ?? this.myKey, change, meta.ts);\n this.hooks.changed();\n }\n\n /** A statement sealed under my current epoch, when I hold its secret. */\n private metaFrame(meta: GroupMeta): GroupMetaFrame | null {\n const secret = this.state.secrets[this.topHash];\n return secret ? wrapGroupMeta(meta, this.topHash, epochKeys(fromBase64Url(secret), this.id, this.epoch).message, true) : null;\n }\n\n /**\n * The statements a member whose sync says it holds an older one (or none) missed, oldest first (`groupMetaToHand`);\n * none for an app that says nothing.\n */\n private metaFor(to: string, theirTag: unknown): { ts: number; frame: GroupMetaFrame }[] {\n const meta = this.state.meta, theirs = parseGroupMetaTag(theirTag);\n if (!meta || theirs === null || !this.isMember || !rosterHas(this.roster, to) || !this.state.secrets[this.topHash]) return [];\n return groupMetaToHand(this.state.metaPast, meta, theirs, m => rosterHas(this.rosterAt(m.h) ?? [], to))\n .map(m => ({ ts: m.ts, frame: this.metaFrame(m)! }));\n }\n\n /**\n * A metadata statement (from its author's edge or a hub's): kept when it is newer than mine, its\n * commit is on my main branch, its signer was the admin after that commit and is the admin now,\n * its signature holds, and it opens under the epoch it names into metadata Ghostly shows. Returns\n * whether it was new, so a hub relays it. One naming what I do not have yet waits for the chain. Just after the admin\n * role moved to me, the former admin's is signed again as mine (`takesOver`).\n */\n private async receiveMeta(from: string, raw: unknown): Promise<boolean> {\n const frame = parseGroupMetaFrame(raw);\n if (!frame || frame.statement.g !== this.id || typeof frame.k !== \"string\" || !this.isRecentMember(from)) return false;\n const s = frame.statement, taking = this.takesOver(s);\n if (!taking && !groupMetaNewer(s, this.state.meta)) return false;\n const at = this.mainIndex.get(s.h);\n if (at === undefined) {\n if (s.e >= this.epoch - COMMUNITY_LIMITS.window) this.waitMeta(from, raw, s);\n return false;\n }\n if (at !== s.e || rosterAdmin(this.rosterAt(s.h) ?? []) !== s.by || (!taking && this.admin !== s.by) || !verifyGroupMetaSignature(s)) return false;\n // The epoch it is sealed under: a commit I know and hold the secret of, or one that may still come.\n const secret = this.state.secrets[frame.k], sealedUnder = this.known.get(frame.k);\n if (!secret || !sealedUnder) { this.waitMeta(from, raw, s); return false; }\n const opened = openGroupMeta(frame, epochKeys(fromBase64Url(secret), this.id, sealedUnder.e).message);\n if (!opened) return false;\n if (taking) {\n if (this.vouches(from, s)) await this.signAgainTaken(opened.meta, opened.body);\n else this.holdTaken(from, raw, s);\n return false;\n }\n const before = this.state.meta;\n this.state.meta = opened.meta;\n this.state.metaPast = keepPastGroupMeta(this.state.metaPast, before, opened.meta);\n await this.persist();\n // What the group looked like when I got in is no change: the first statement I take, signed under a commit before\n // mine, makes no line, nor does a new admin's signing again the name the welcome gave me.\n const change = !before && !rosterHas(this.rosterAt(s.h) ?? [], this.myKey) ? null : groupMetaChange(before, opened.meta, this.state.name);\n if (change) this.hooks.metaChanged?.(this.metaAuthor(before, s, at), change, opened.meta.ts);\n this.hooks.changed();\n return true;\n }\n\n /**\n * Whether I take a statement though its signer is no longer the admin (WISP 903 § Metadata): I am the admin since\n * moments ago, they were the admin before me, and it is later than the one of theirs I signed again. A member who had\n * not synced when the role moved to them signed again what they held (or nothing), and the statement on its way would\n * be refused for good: a rename of theirs, or a member back from away, would then lose the group's call node.\n */\n private takesOver(s: GroupMetaStatement): boolean {\n const t = this.takeover;\n return !!t && this.isAdmin && s.by === t.from && (this.hooks.clock?.() ?? Date.now()) <= t.until && groupMetaNewer(s, t.base);\n }\n\n /**\n * Whether a statement I would take (`takesOver`) was on its way when the role moved, as far as I can tell: a member\n * other than its signer handed it to me (a hub's relay included), or said in a sync it holds that one or a later one\n * under the same commit. The former admin alone could sign new ones after the hand-over, each taken for the whole group.\n */\n private vouches(from: string, s: GroupMetaStatement): boolean {\n const v = this.takeover?.vouched;\n return from !== s.by || (!!v && v.e === s.e && v.r >= s.r);\n }\n\n /** The former admin's statement nobody else has shown it holds: the latest is kept until a sync does (`vouch`). */\n private holdTaken(from: string, raw: unknown, s: GroupMetaStatement): void {\n const t = this.takeover!;\n if (!t.held || groupMetaNewer(s, t.held.s)) t.held = { from, raw, s };\n }\n\n /**\n * A member's sync names the statement it holds: one signed under a commit of the admin before me, by another member\n * than them, vouches for theirs up to it, and the one held is taken if it now is.\n */\n private async vouch(from: string, tag: unknown): Promise<void> {\n const t = this.takeover, v = parseGroupMetaTag(tag), commit = v ? this.state.chain[v.e] : undefined;\n if (!t || !v || !commit || from === t.from || rosterAdmin(this.rosterAt(this.hashOf(commit)) ?? []) !== t.from) return;\n if (t.vouched && !groupMetaNewer(v, t.vouched)) return;\n t.vouched = v;\n const held = t.held;\n if (held && this.vouches(held.from, held.s)) { t.held = undefined; await this.receiveMeta(held.from, held.raw); }\n }\n\n /**\n * The former admin's statement, taken (`takesOver`): signed again as mine, each field I changed since keeping my\n * value. Dated as theirs, and credited to them, when I changed nothing; what I held was then no change to hand on.\n */\n private async signAgainTaken(meta: GroupMeta, theirs: GroupMetaBody): Promise<void> {\n const t = this.takeover!, base = groupMetaBody(t.base), mine = groupMetaBody(this.state.meta);\n t.base = meta;\n const pick = <K extends keyof GroupMetaBody>(k: K) => JSON.stringify(mine[k]) === JSON.stringify(base[k]) ? theirs[k] : mine[k];\n const body = encodeGroupMetaBody({ name: pick(\"name\"), pic: pick(\"pic\"), hubs: pick(\"hubs\"), call: pick(\"call\") });\n if (body === this.state.meta?.body) return;\n const changed = encodeGroupMetaBody(mine) !== encodeGroupMetaBody(base);\n await this.publishMeta(body, changed ? this.hooks.clock?.() ?? Date.now() : meta.ts, true, { by: meta.by, replaces: !changed });\n }\n\n /**\n * A statement that waits for the chain: only one its signer signed, so an altered copy cannot push out the one\n * waiting. The admin I know has a place of their own, which another member's statement cannot take, and in each\n * place only a later statement takes the one waiting.\n */\n private waitMeta(from: string, raw: unknown, s: GroupMetaStatement): void {\n if (!verifyGroupMetaSignature(s)) return;\n const place = s.by === this.admin ? \"admin\" : \"other\", waiting = this.pendingMeta[place];\n if (!waiting || groupMetaNewer(s, waiting.s)) this.pendingMeta[place] = { from, frame: raw, s };\n this.ask(from);\n }\n\n /**\n * Who made the change a statement brings me (`at`: its commit's place on my main branch): its signer, when they were\n * the admin all along since the statement I held (or, with none, since I got in). A new admin signs again what the\n * last one set (`metaFollowsChain`): to a member that missed that, it is no change of theirs it can tell apart. With\n * none held, theirs is one dated after the commit that made them the admin: what they sign again keeps its date.\n */\n private metaAuthor(before: GroupMeta | undefined, s: GroupMetaStatement, at: number): string | undefined {\n const from = before ? this.mainIndex.get(before.h) : undefined;\n let roster = before && from !== undefined ? this.rosterAt(before.h) ?? null : null, counted = from !== undefined, moved: number | undefined;\n for (let i = from ?? 0; i <= at; i++) {\n if (i !== from) roster = communityRoster(roster, this.state.chain[i]);\n if (!roster) return undefined;\n counted ||= rosterHas(roster, this.myKey);\n if (counted && rosterAdmin(roster) !== s.by) { if (before) return undefined; moved = i + 1; }\n }\n return moved === undefined || s.ts > this.state.chain[moved].ts ? s.by : undefined;\n }\n\n /**\n * After the chain or my secrets moved: the waiting statement, and, if I became the admin, or my statement's commit\n * went with a branch that lost a fork, the name and picture signed again as mine under the main branch.\n */\n private async metaFollowsChain(): Promise<void> {\n if (this.admin !== this.adminSeen) {\n // The role moved to me: what the admin before me signed may still be on its way (`takesOver`).\n const from = this.adminSeen;\n this.takeover = this.isAdmin && from && from !== this.myKey\n ? { from, until: (this.hooks.clock?.() ?? Date.now()) + COMMUNITY_TAKEOVER_META_MS, base: this.state.meta } : undefined;\n this.adminSeen = this.admin;\n }\n const { admin, other } = this.pendingMeta;\n this.pendingMeta = {};\n for (const pending of [admin, other]) if (pending && await this.receiveMeta(pending.from, pending.frame)) this.hooks.relay?.(pending.frame as GroupMetaFrame);\n // Joiners accept only the current admin's statement: a new admin signs the picture again. One under a commit off\n // the main branch reaches no one (each waits for a chain that never comes): its admin signs it again too. Dated\n // when it was set: a member holding nothing tells it from a new admin's change by that (`metaAuthor`).\n const meta = this.state.meta;\n if (this.isAdmin && meta && (meta.by !== this.myKey || !this.mainIndex.has(meta.h))) await this.publishMeta(meta.body, meta.ts, true);\n }\n\n private async fork(reason: string): Promise<void> {\n if (this.state.status !== \"active\") return;\n this.state.status = \"forked\";\n this.state.statusReason = `${reason}. Membership changes are halted; the admin must re-form the group.`;\n await this.persist();\n this.hooks.changed();\n }\n}\n\ninterface Branch { tip: string; fork: number; path: string[] }\n/** A metadata frame waiting for the chain, with its statement, whose signature holds. */\ninterface WaitingMeta { from: string; frame: unknown; s: GroupMetaStatement }\n\nexport function signCommunity(commit: Omit<CommunityCommit, \"sig\">, seed: Uint8Array): CommunityCommit {\n return { ...commit, sig: toBase64Url(sign(utf8Encode(tuple(commit)), seed)) };\n}\n\n","import { engineText } from \"@ghostly/core\";\n\n/*\n * Wallets at home on another device (WISP 06 § Wallets that stay home): their database lives there, and no other\n * device opens them. The engine says which, by wallet id (`<type>:<network>`, `lightning:<network>:<card>`), before\n * any wallet opens; each wallet asks here before it opens its SDK, so no path that opens one (a start, a retry, a\n * restore, an unlock) opens a wallet that is away.\n */\n\nlet away = new Map<string, string>();\n\n/** The wallets away from this device, by wallet id, with the name of their home device (\"\" when it has none here). */\nexport function setAwayWallets(next: ReadonlyMap<string, string>): void {\n away = new Map(next);\n}\n\n/** The home device's name of a wallet away from this device, or undefined when it is here. */\nexport function awayFrom(id: string): string | undefined {\n return away.get(id);\n}\n\n/** A wallet that cannot be used here: it is at home on another device. */\nexport class WalletAwayError extends Error {\n constructor(wallet: string, device: string) {\n super(device ? engineText(\"walletAway\", { wallet, device }) : engineText(\"walletAwayUnnamed\", { wallet }));\n this.name = \"WalletAwayError\";\n }\n}\n\n/**\n * Whether a single-writer wallet (Ark, Bark, Spark and the Breez source, Fedimint) may open its SDK now: the engine\n * says, from a good turn read under 60 seconds old (WISP 06 § Wallets). Every open asks, the retries of each wallet\n * included, so a device replaced while it was offline does not reopen one on a retry.\n */\nlet turnGate: () => Promise<boolean> = async () => true;\nexport function setSingleWriterGate(gate: (() => Promise<boolean>) | null): void {\n turnGate = gate ?? (async () => true);\n}\n\n/** Throws (the wallet tries again later, as it does when its server does not answer) without a fresh good turn read. */\nexport async function requireTurn(): Promise<void> {\n if (!(await turnGate().catch(() => false))) throw new Error(\"Checking which device is active\");\n}\n\n/** Throws when the wallet `id` is at home on another device. */\nexport function refuseAway(id: string, wallet: string): void {\n const device = awayFrom(id);\n if (device !== undefined) throw new WalletAwayError(wallet, device);\n}\n","import type { WalletNetwork } from \"@ghostly/core\";\nimport type { WalletMode } from \"../../shared/mints\";\n\n/** A wallet of the mode being left stopped opening: the switch goes ahead without waiting for its network. */\nexport class ModeChanged extends Error {\n constructor() { super(\"The wallets switched mode\"); this.name = \"ModeChanged\"; }\n}\n\nexport const networkLabel = (network: WalletNetwork) => network === \"mainnet\" ? \"Mainnet\" : \"Testnet\";\n\n/**\n * What was asked of one network's wallet belongs to the other network's (a backup, a chain): nothing was changed.\n * `network` is where it belongs, so the engine can hand it to that wallet instead.\n */\nexport class WrongNetworkError extends Error {\n constructor(readonly network: WalletNetwork, message: string) { super(message); this.name = \"WrongNetworkError\"; }\n}\n\n/**\n * Opening a wallet waits on its network (an Ark server, an RPC), which can take minutes or never answer.\n * A mode switch must not wait behind that: `within` gives up on the wait as soon as the mode changes, and\n * whatever still arrives afterwards is handed to `dispose`. Nothing is saved before that wait ends, so\n * giving up leaves the profile as it was. Every wait on the network inside a wallet's queue goes through it,\n * reading a balance too, or the switch, queued behind it, waits anyway.\n */\nexport class ModeGate {\n constructor(private target: WalletMode = \"mainnet\") {}\n private controller = new AbortController();\n /** The mode its owner works in, once it says so: a wait that starts while a switch away from it is queued ends at once. */\n private current?: WalletMode;\n\n /** A switch to `mode` was asked for: waits for a wallet of another mode end now. */\n switching(mode: WalletMode) {\n if (this.target === mode) return;\n this.target = mode;\n this.controller.abort();\n this.controller = new AbortController();\n }\n\n /** The owner's switch to `mode` is applied (its queue reached it): waits are for this mode again. */\n entered(mode: WalletMode) { this.current = mode; }\n\n /**\n * A creation took too long: the waits under way end now, and so does every wait that starts until `resume`\n * (a creation still sealing its seed has not reached its server yet, and must not wait there either).\n */\n interrupt() { this.cut = true; this.controller.abort(); this.controller = new AbortController(); }\n resume() { this.cut = false; }\n private cut = false;\n\n /** The wallet stopped: every wait ends now, and any later one at once. */\n close() { this.closed = true; this.controller.abort(); }\n private closed = false;\n\n within<T>(work: Promise<T>, dispose?: (value: T) => unknown): Promise<T> {\n const signal = this.controller.signal;\n return new Promise<T>((resolve, reject) => {\n const give = () => { reject(new ModeChanged()); void work.then((value) => dispose?.(value), () => {}); };\n if (this.closed || this.cut || (this.current && this.current !== this.target)) return give();\n signal.addEventListener(\"abort\", give, { once: true });\n work.then(\n (value) => { signal.removeEventListener(\"abort\", give); if (!signal.aborted) resolve(value); },\n (error) => { signal.removeEventListener(\"abort\", give); if (!signal.aborted) reject(error); },\n );\n });\n }\n}\n","import type { IceServerSetting } from \"./types\";\n\n/**\n * What is wrong with a TURN/STUN server, or null. Browsers refuse to create any WebRTC connection when\n * one server in the list is malformed, so a bad entry here would silently cut off calls and files.\n */\nexport function iceServerProblem(server: IceServerSetting): string | null {\n // A setting from outside the form (the CLI, `ghostly engine`, an import) may have no urls at all: before, a TypeError.\n if (typeof server?.urls !== \"string\") return \"Each ICE server needs urls: one address, or several comma-separated (turn:host:port)\";\n if ([server.username, server.credential].some((value) => value !== undefined && typeof value !== \"string\")) return \"A TURN server's username and credential are texts\";\n const urls = server.urls.split(/[\\s,]+/).filter(Boolean);\n if (!urls.length) return \"Enter the TURN server address\";\n for (const url of urls) {\n if (!/^(stun|turns?):[^\\s/?#]+(\\?transport=(udp|tcp))?$/i.test(url)) return `“${url}” is not a TURN or STUN address (turn:host:port)`;\n if (/^turns?:/i.test(url) && (!server.username?.trim() || !server.credential?.trim())) return \"A TURN server needs its username and credential\";\n }\n return null;\n}\n\n/**\n * Why \"Hide my IP from contacts\" (`relayOnly`) cannot be on with these ICE servers, or null: it needs a TURN server\n * with its username and credential, which every connection to a contact then goes through. Without one there is no\n * way to reach a contact that hides this device's address, and the mode never falls back to a direct path.\n */\nexport function relayOnlyProblem(servers: readonly IceServerSetting[] | undefined): string | null {\n const turn = (servers ?? []).some((server) => !iceServerProblem(server) && server.urls.split(/[\\s,]+/).some((url) => /^turns?:/i.test(url)));\n return turn ? null : \"Add a TURN server first\";\n}\n\n/**\n * A server as WebRTC writes it (`urls` a list, as every TURN guide does) in this setting's own form: the addresses\n * comma-separated. Anything else is left as it is, for `iceServerProblem` to say what is wrong.\n */\nexport function iceServerSetting(server: IceServerSetting): IceServerSetting {\n const urls: unknown = server?.urls;\n if (!Array.isArray(urls) || !urls.every((url) => typeof url === \"string\")) return server;\n return { ...server, urls: urls.join(\", \") };\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { databaseName } from \"../../../shared/idb\";\n\n/**\n * Where the Breez SDK keeps a wallet on this device, and which profile it belongs to.\n *\n * The SDK keeps its IndexedDB databases under one storage name (`breezDatabaseFiles`). That name is one per **profile,\n * network and seed**: the Spark rail and a Breez Lightning card of the same phrase in one profile are one SDK instance\n * over one database (`openBreez`), two phrases are two wallets, and a profile restored as a copy on the same device\n * starts from the phrase with a database of its own. Two SDK instances over one database would each think the leaves\n * are theirs.\n *\n * Before this, the name came from the network and the seed only, so every profile of the origin holding that phrase\n * opened the same database. Such a database is kept, under its old name, for **one** profile: the first to open the\n * phrase on this device after the change claims it in a small database of the device (`ghostly-breez`), outside every\n * profile database (a backup copies a profile's database whole, so a mark in it would be the copy's too). Any other\n * profile gets a new name. The same register lists every name a profile uses, so deleting a profile deletes its Breez\n * databases without opening its sealed phrases.\n */\nexport type BreezDatabaseNetwork = \"mainnet\" | \"regtest\";\nconst netOf = (network: string): BreezDatabaseNetwork => (network === \"bitcoin\" || network === \"mainnet\" ? \"mainnet\" : \"regtest\");\nconst hex = (bytes: Uint8Array) => Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\nconst digest = (text: string) => hex(sha256(new TextEncoder().encode(text))).slice(0, 16);\n\n/** What a Breez database name looks like, old or new: nothing about the seed or the profile shows in it. */\nexport const BREEZ_DATABASE = /^ghostly-breez-(mainnet|regtest)-[0-9a-f]{16}$/;\n\n/** The name every profile of the origin used for this phrase before databases were per profile. */\nexport const breezLegacyName = (network: string, mnemonic: string) => `ghostly-breez-${netOf(network)}-${digest(`ghostly-breez:${netOf(network)}:${mnemonic}`)}`;\n\n/** The name of this phrase's Breez database in one profile (`space`: the profile's peer database, WISP 04). */\nexport const breezDatabaseName = (network: string, mnemonic: string, space: string = databaseName()) =>\n `ghostly-breez-${netOf(network)}-${digest(`ghostly-breez:${space}:${netOf(network)}:${mnemonic}`)}`;\n\n/**\n * The databases the SDK keeps under one storage name. SDK 0.26 roots them there: `<name>/<network>/<identity>` and\n * `<name>/<network>/<identity>-tree`, the identity read from the seed inside the SDK. Older builds kept `<name>`\n * itself. A browser without `indexedDB.databases()` cannot list them: only the bare names are known there.\n */\nexport async function breezDatabaseFiles(name: string): Promise<string[]> {\n const files = [name, `${name}-tree`];\n if (typeof indexedDB.databases !== \"function\") return files;\n const under = (await indexedDB.databases()).map((d) => d.name ?? \"\").filter((file) => file.startsWith(`${name}/`));\n return [...new Set([...files, ...under])];\n}\n\ninterface Entry { name: string; space: string; network: BreezDatabaseNetwork; legacy?: true }\nconst REGISTER = \"ghostly-breez\", STORE = \"databases\";\n\nconst request = <T>(r: IDBRequest<T>) => new Promise<T>((resolve, reject) => { r.onsuccess = () => resolve(r.result); r.onerror = () => reject(r.error); });\nfunction openRegister(): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const open = indexedDB.open(REGISTER, 1);\n open.onupgradeneeded = () => { if (!open.result.objectStoreNames.contains(STORE)) open.result.createObjectStore(STORE); };\n open.onsuccess = () => resolve(open.result);\n open.onerror = () => reject(open.error);\n open.onblocked = () => reject(new Error(\"The Breez register is blocked\"));\n });\n}\nasync function withRegister<T>(mode: IDBTransactionMode, run: (store: IDBObjectStore) => Promise<T> | T): Promise<T> {\n const db = await openRegister();\n try {\n const tx = db.transaction(STORE, mode);\n const done = new Promise<void>((resolve, reject) => { tx.oncomplete = () => resolve(); tx.onerror = tx.onabort = () => reject(tx.error); });\n const result = await run(tx.objectStore(STORE));\n await done;\n return result;\n } finally { db.close(); }\n}\n\n/**\n * Whether the SDK keeps a wallet under this storage name on this device (`breezDatabaseFiles`). A browser that cannot\n * list databases is answered yes: the first profile then takes the old name whether or not it is there, which is\n * safe, since only one profile ever has it.\n */\nasync function exists(name: string): Promise<boolean> {\n if (typeof indexedDB.databases !== \"function\") return true;\n return (await indexedDB.databases()).some((d) => d.name === name || !!d.name?.startsWith(`${name}/`));\n}\n\n/**\n * The Breez database this profile opens for this phrase: the old shared one when this profile owns it (or is the\n * first to claim it), else the profile's own. Noted in the register either way. A device whose IndexedDB cannot be\n * read gets the profile's own name: never a database another profile may use.\n */\nexport async function breezDatabase(network: string, mnemonic: string, space: string = databaseName()): Promise<string> {\n const fresh = breezDatabaseName(network, mnemonic, space);\n if (typeof indexedDB === \"undefined\") return fresh;\n const legacy = breezLegacyName(network, mnemonic);\n try {\n const legacyHere = await exists(legacy);\n return await withRegister(\"readwrite\", async (store) => {\n // Both reads and the write in one transaction: two profiles opening at once cannot both claim the old one.\n const [owner, own] = await Promise.all([request(store.get(legacy)) as Promise<Entry | undefined>, request(store.get(fresh)) as Promise<Entry | undefined>]);\n if (owner?.space === space) return legacy;\n if (!own && !owner && legacyHere) { store.put({ name: legacy, space, network: netOf(network), legacy: true } satisfies Entry, legacy); return legacy; }\n if (!own) store.put({ name: fresh, space, network: netOf(network) } satisfies Entry, fresh);\n return fresh;\n });\n } catch { return fresh; }\n}\n\n/** The names this profile has noted for this phrase (nothing is claimed): what removing the wallet deletes. */\nexport async function breezDatabasesFor(network: string, mnemonic: string, space: string = databaseName()): Promise<string[]> {\n const names = [breezLegacyName(network, mnemonic), breezDatabaseName(network, mnemonic, space)];\n return (await breezDatabasesOf(space)).filter((name) => names.includes(name));\n}\n\n/**\n * The name this profile uses for this phrase, read without claiming anything: the one it noted (`breezDatabase`), else\n * the profile's own name. What a handoff deletes and compares (WISP 06 § Wallets): never the old shared database of\n * another profile that has not opened the phrase since the change.\n */\nexport async function breezDatabaseInUse(network: string, mnemonic: string, space: string = databaseName()): Promise<string> {\n return (await breezDatabasesFor(network, mnemonic, space))[0] ?? breezDatabaseName(network, mnemonic, space);\n}\n\n/** Every Breez database name noted for a profile of this device. */\nexport async function breezDatabasesOf(space: string): Promise<string[]> {\n if (typeof indexedDB === \"undefined\") return [];\n try { return ((await withRegister(\"readonly\", (store) => request(store.getAll()))) as Entry[]).filter((e) => e?.space === space && BREEZ_DATABASE.test(e.name)).map((e) => e.name); }\n catch { return []; }\n}\n\nconst deleteDatabase = (name: string) => new Promise<void>((resolve) => {\n try { const r = indexedDB.deleteDatabase(name); r.onsuccess = r.onerror = r.onblocked = () => resolve(); } catch { resolve(); }\n});\n\nconst deleteStrictly = (name: string) => new Promise<void>((resolve, reject) => {\n const r = indexedDB.deleteDatabase(name);\n r.onsuccess = () => resolve();\n r.onerror = () => reject(r.error ?? new Error(`${name} was not deleted`));\n r.onblocked = () => reject(new Error(`${name} is still open`));\n});\n\n/**\n * Deletes one Breez wallet's databases (all the SDK keeps under the name) and its note in the register. Anything else\n * is refused. `strict` (a handoff, WISP 06 § Wallets): a delete that is blocked or fails rejects and the note stays,\n * so the caller tries again.\n */\nexport async function dropBreezDatabase(name: string, options: { strict?: boolean } = {}): Promise<void> {\n if (!BREEZ_DATABASE.test(name) || typeof indexedDB === \"undefined\") return;\n for (const file of await breezDatabaseFiles(name).catch(() => [name, `${name}-tree`])) await (options.strict ? deleteStrictly(file) : deleteDatabase(file));\n await withRegister(\"readwrite\", (store) => { store.delete(name); }).catch(() => {});\n}\n\n/** Deletes every Breez database a profile used on this device (the profile is being deleted). */\nexport async function dropBreezDatabasesOf(space: string): Promise<void> {\n for (const name of await breezDatabasesOf(space)) await dropBreezDatabase(name);\n}\n","import type { BreezSdk } from \"@breeztech/breez-sdk-spark/web\";\nimport { breezDatabase, dropBreezDatabase } from \"./breezDatabases\";\n\n/**\n * The part of the Breez SDK (nodeless, on Spark: `@breeztech/breez-sdk-spark`, WebAssembly) the Breez\n * Lightning source uses, behind an interface small enough to fake in tests. The SDK keeps its wallet in\n * IndexedDB and reaches the Spark operators and the Breez services over HTTPS, so the same build runs\n * in the web app, the extension's offscreen document and Desktop's WebView.\n */\nexport type BreezNetwork = \"mainnet\" | \"regtest\";\n/** Ghostly's own name for the two networks: `bitcoin` (Mainnet, real sats) or `regtest` (Breez's test network). */\nexport type BreezChain = \"bitcoin\" | \"regtest\";\nexport type BreezWallet = Pick<BreezSdk, \"getInfo\" | \"receivePayment\" | \"prepareSendPayment\" | \"sendPayment\" | \"getPayment\" | \"listPayments\" | \"syncWallet\" | \"disconnect\">;\n\nexport interface BreezConnect {\n network: BreezNetwork;\n mnemonic: string;\n /** Breez's API key. Mainnet needs one; regtest works without. */\n apiKey?: string;\n /** Where the SDK keeps this wallet: an IndexedDB name in a browser, a directory in Node. */\n storage: string;\n}\n\nexport interface BreezSdkModule {\n connect(params: BreezConnect): Promise<BreezWallet>;\n}\n\nlet loading: Promise<BreezSdkModule> | undefined;\n\n/** Loads the WebAssembly once, on first use: profiles that never pick Breez never fetch its 12.8 MB. */\nexport function loadBreezSdk(): Promise<BreezSdkModule> {\n return loading ??= (async () => {\n const breez = await import(\"@breeztech/breez-sdk-spark/web\");\n // Loads the module and installs the SDK's IndexedDB storage.\n await breez.default();\n const sdk: BreezSdkModule = {\n async connect({ network, mnemonic, apiKey, storage }) {\n const config = breez.defaultConfig(network);\n if (apiKey) config.apiKey = apiKey;\n return breez.connect({ config, seed: { type: \"mnemonic\", mnemonic }, storageDir: storage });\n },\n };\n return sdk;\n })().catch((error) => { loading = undefined; throw error; });\n}\n\nexport const breezNetwork = (network: string): BreezNetwork => (network === \"bitcoin\" ? \"mainnet\" : \"regtest\");\n\n/**\n * The wallet's own storage: one per profile, network and seed (`breezDatabases.ts`), named without revealing anything\n * about either. The Spark rail and the Breez Lightning source name it the same way, so in one profile one seed is one\n * wallet whichever opens it. `breezDatabase` is the one helper that gives the name a profile actually uses.\n */\nexport { breezDatabase, breezDatabaseName, dropBreezDatabase } from \"./breezDatabases\";\n/** Names the storage of a seed on a network in this profile. */\nexport type BreezStorageName = (network: string, mnemonic: string) => string | Promise<string>;\n\nconst DISCONNECT_MS = 10_000;\n/** One SDK instance per wallet storage: two over one database would each think the leaves are theirs. */\nconst open = new Map<string, { wallet: Promise<BreezWallet>; refs: number }>();\n\n/**\n * Opens the Breez wallet of this seed on this network, or shares the one already open (the Spark rail and the\n * Breez Lightning source of the same seed are one wallet, even when they carry different API keys: the instance\n * open keeps the key it opened with). `release` gives this user's share back; the last one disconnects the SDK.\n * `storage`: the database it opened, which `forgetBreez` deletes when the wallet is removed.\n */\nexport async function openBreez(\n params: { network: string; mnemonic: string; apiKey?: string },\n sdk: () => Promise<BreezSdkModule> = loadBreezSdk,\n storage: BreezStorageName = breezDatabase,\n): Promise<{ wallet: BreezWallet; release: () => Promise<void>; storage: string }> {\n const name = await storage(params.network, params.mnemonic);\n let entry = open.get(name);\n if (!entry) {\n const wallet = sdk().then((module) => module.connect({ network: breezNetwork(params.network), mnemonic: params.mnemonic, apiKey: params.apiKey, storage: name }));\n entry = { wallet, refs: 0 };\n open.set(name, entry);\n wallet.catch(() => { if (open.get(name) === entry) open.delete(name); });\n }\n entry.refs++;\n const held = entry;\n let wallet: BreezWallet;\n try { wallet = await held.wallet; }\n catch (error) { held.refs--; throw error; }\n let released = false;\n return {\n wallet,\n storage: name,\n release: async () => {\n if (released) return;\n released = true;\n if (--held.refs > 0) return;\n if (open.get(name) === held) open.delete(name);\n await Promise.race([wallet.disconnect(), new Promise((resolve) => setTimeout(resolve, DISCONNECT_MS))]);\n },\n };\n}\n\n/** Whether a wallet of this storage is open here (the Spark rail and a Breez card of one seed share it). */\nexport const breezOpen = (storage: string) => open.has(storage);\n\n/**\n * A wallet was removed: its Breez databases go, unless another user in this profile still has them open (a Breez\n * Lightning card on the Spark wallet's own phrase). That one deletes them when it is removed in turn.\n */\nexport async function forgetBreez(storage: string): Promise<void> {\n if (!breezOpen(storage)) await dropBreezDatabase(storage);\n}\n","import { engineError, engineText, type PaymentAdapter, type PaymentReview, type PaymentTarget } from '@ghostly/core';\nimport { mintNetwork } from '../../shared/mints';\nimport type { CashuWallet, CashuPrepared } from '../wallet';\n\n/**\n * How long one request of a swap to a mint may last, and one asking where a swap stands (NUT-09 restore, NUT-07 states):\n * its retries (NUT-19) included, under one deadline (`boundSwapRequests`). A mint that takes the connection and never\n * answers is given up on within it, and the payment says so, instead of after cashu-ts' 5 min. Retries run inside the\n * same approval, and reconcile waits for it (the coordinator runs one operation per payment at a time).\n */\nexport const CASHU_REQUEST_TIMEOUT_MS=30_000;\n/**\n * How long a melt's request may last, its retries (NUT-19) included under one deadline (`boundMintRequests`): cashu-ts's\n * default `requestTimeout` (5 min) for one try.\n */\nexport const MELT_REQUEST_TIMEOUT_MS=300_000;\n/** The margin past that for a mint slow to act on a swap it did receive. */\nexport const SWAP_SETTLED_MS=120_000;\n/**\n * When a swap whose outcome is unknown can no longer reach the mint: a request's longest life after the approval\n * (`submittedAt`, saved when it was claimed), and the margin after the attempt ended (`attemptEndedAt`), both saved.\n */\nexport function swapSettledAt(review:PaymentReview,prepared:CashuPrepared):number{\n return Math.max((review.submittedAt ?? review.createdAt)+CASHU_REQUEST_TIMEOUT_MS+SWAP_SETTLED_MS,(prepared.attemptEndedAt ?? 0)+SWAP_SETTLED_MS);\n}\n/**\n * The mint answered, and refused. cashu-ts turns a refusal of a keyset the mint retired or does not know (codes\n * 12xxx) into a `StaleKeysetError` once it has reloaded the mint's keysets: the mint's refusal all the same, with it\n * as its cause. By name, as cashu-ts's own `isMintOperationError`, so it needs no import of the library.\n */\nexport function mintRefused(error:unknown):boolean{\n if(!(error instanceof Error))return false;\n if(error.name==='StaleKeysetError')return mintRefused((error as {cause?:unknown}).cause);\n return error.name==='MintOperationError' && 'code' in error;\n}\n/**\n * The mint refused outputs for their keyset: one it retired, or does not know, since they were made. No request with\n * those outputs is ever signed; new ones on the keyset it signs with now can be. cashu-ts says it in its own English,\n * which is never shown to a person.\n */\n/**\n * The mint failed, and said nothing of the request: a server error (5xx, \"internal error\"), or no answer at all (a\n * closed connection, cashu-ts's `NetworkError`). Unlike a refusal, it may work later. By name, as `mintRefused`.\n */\nexport function mintFailed(error:unknown):boolean{\n if(!(error instanceof Error))return false;\n const status=(error as {status?:unknown}).status;\n return error.name==='NetworkError' || (error.name==='HttpResponseError' && typeof status==='number' && status>=500);\n}\nexport function keysetRefused(error:unknown):boolean{\n return error instanceof Error && error.name==='StaleKeysetError' && mintRefused(error);\n}\nexport const NEVER_REACHED_MINT=\"The payment never reached the mint: nothing was sent, and the sats are back in your wallet. You can pay again.\";\n\n/**\n * A Take it back of the payment under way, if one is (`PaymentDesk.takingBack`): settles once it is over, with the\n * payment's state then.\n */\nexport type TakingBack=(paymentId:string)=>Promise<string|undefined>|undefined;\n\nexport class CashuAdapter implements PaymentAdapter<CashuPrepared> {\n readonly method='cashu' as const;\n constructor(private wallet:CashuWallet,private publish:(review:PaymentReview,token:string)=>Promise<void>,private takingBack:TakingBack=()=>undefined){}\n async prepare(target:PaymentTarget,amount:number,feeCap:number){\n // A test mint (the public ones, or one on this machine) pays in test sats, named cashu-test; any other in sats.\n if(target.method!=='cashu' || target.network!==(mintNetwork(target.provider)==='testnet'?'cashu-test':'bitcoin'))throw new Error('Cashu mint/network mismatch');\n const result=await this.wallet.prepareReviewedCashu(target.provider,amount);\n if(result.fee>feeCap)throw engineError('cashuFeeAboveLimit');\n return result;\n }\n async execute(review:PaymentReview,prepared:CashuPrepared,persist?:()=>Promise<void>){\n if(!review.linkId)throw new Error('Cashu requires an authenticated chat recipient');\n let token:string;\n try { token=await this.wallet.executeReviewedCashu(review,prepared); }\n catch(error){\n // Saved with the intent when the coordinator records the unknown outcome: the swap may still reach the mint for a while.\n prepared.attemptEndedAt=Date.now();\n if(persist && mintRefused(error)){\n // A refusal, and the mint says why: the ecash it was to spend was spent somewhere else. The payment ends here.\n if(await this.wallet.reviewedCashuSpentElsewhere(prepared).catch(()=>false))return this.spentElsewhere(prepared,persist);\n // A refusal of the only request made for it (outputs on a keyset the mint retired since): no request of it is on\n // its way, so the mint's word that it never happened ends it now, not once reconcile may ask.\n if(await this.wallet.reviewedCashuNeverSwapped(prepared).catch(()=>false))return this.abandon(prepared,persist);\n }\n throw error;\n }\n await persist?.();\n await this.publish(review,token);\n return await this.outcome(review,prepared) ?? {settled:false};\n }\n /**\n * What the mint and this wallet know of a payment whose token went out: paid once the mint reads its ecash spent,\n * unless this wallet is the one that spent it, taking the payment back. Asked in that order: ecash taken back while\n * the mint was being asked reads spent too. Undefined while the contact has not taken it.\n * A Take it back of it under way when the mint is asked, or started while it answers, is waited for: its swap makes\n * the ecash read spent before the ecash is back here. Ended with the ecash back, the payment was taken back; ended\n * with the mint saying the contact had it first, it is paid; ended any other way, this round's spent read proves\n * nothing, and the next round asks again (nothing is sent meanwhile). One whose answer from the mint was lost is still\n * under way while its redeem is written down: asked before whether the ecash is back, which is stored as it ends.\n */\n private async outcome(review:PaymentReview,prepared:CashuPrepared){\n const before=this.takingBack(review.id);\n const spent=await this.wallet.reviewedCashuSpent(prepared);\n const reclaim=this.takingBack(review.id) ?? before;\n const ended=await reclaim;\n const unsettled=await this.wallet.cashuTakingBack(review.id);\n const back=await this.takenBack(review.id);\n if(back)return back;\n if(unsettled || (reclaim && ended!=='settled'))return {settled:false};\n return spent?{settled:true}:undefined;\n }\n /** Taken back, waiting for a Take it back under way first: the payment then ends failed, its sats back here. */\n private async takenBack(id:string){\n await this.takingBack(id);\n return await this.wallet.reviewedCashuTakenBack(id)?{settled:false,failed:true,error:engineText('paymentTakenBack')}:undefined;\n }\n /** `persist` saves the intent as it is: required, since the abandon path must be durable before it releases anything. */\n async reconcile(review:PaymentReview,prepared:CashuPrepared,persist:()=>Promise<void>){\n if(prepared.abandoned)return this.abandon(prepared,persist);\n if(prepared.spentElsewhere)return this.spentElsewhere(prepared,persist);\n // Asked once a round: the contact taking a token it just got says so (`onReviewedPaymentResult`), and the next round asks.\n const known=await this.outcome(review,prepared);\n if(known)return known;\n const token=prepared.token ?? await this.wallet.recoverReviewedCashu(review,prepared);\n if(token){\n await this.publish(review,token); // Repeat the same token, never mint a replacement.\n // Sending it can wait on the chat for a while (a restart dials the contact): Take it back may have ended it meanwhile.\n const back=await this.takenBack(review.id);\n if(back)return back;\n }\n // No token: the swap may never have reached the mint (it was unreachable when approved). Only the mint can say so,\n // and only once no request of it can still be on its way: then the payment failed and its inputs come back.\n if(!token && Date.now()>=swapSettledAt(review,prepared) && await this.wallet.reviewedCashuNeverSwapped(prepared))return this.abandon(prepared,persist);\n // No token, and the mint answers that it signed none of the outputs while an input reads spent: something else\n // spent this ecash (the profile in use on another device, its ecash redeemed from a copy). This swap can never\n // happen, whenever it is asked about.\n if(!token && await this.wallet.reviewedCashuSpentElsewhere(prepared))return this.spentElsewhere(prepared,persist);\n return {settled:false};\n }\n /**\n * The mint proved this swap never happened. Marked for good first (a reload repeats only this), then its reserved\n * inputs are released. Nothing sends the saved swap again: approve claims pending reviews only, and reconcile asks.\n */\n /**\n * The ecash this payment was to spend is spent, and not by this payment. Marked for good first, then the wallet lets\n * go of what the mint reads spent, frees the rest, and asks the mint about its other ecash there.\n */\n private async spentElsewhere(prepared:CashuPrepared,persist:()=>Promise<void>){\n prepared.spentElsewhere=true;\n await persist();\n await this.wallet.dropReviewedCashu(prepared);\n return {settled:false,failed:true,error:engineText('reviewedEcashSpent')};\n }\n private async abandon(prepared:CashuPrepared,persist:()=>Promise<void>){\n prepared.abandoned=true;\n await persist();\n await this.wallet.releaseReviewedCashu(prepared);\n return {settled:false,failed:true,error:NEVER_REACHED_MINT};\n }\n}\n","/**\n * A growing wait with a cap, for whatever a wallet asks about again until it gets an answer: a Cashu melt or swap whose\n * mint does not answer or keeps it pending, restored ecash at a mint that cannot say what is spent, a Lightning card's\n * payment its source keeps pending or cannot be reached about. Asked at a fixed pace, each of these knocked on a dead\n * mint or source every 15 to 60 s for as long as the app ran.\n *\n * Each key is asked at `firstMs` while it is `fast` (a request may still land, the payment is new), then twice as late\n * after every ask with no answer, up to `capMs`. The pace lives in memory: an app start asks at once, and so does a\n * caller that knows something changed (it `forget`s the key, or asks whatever the pace says).\n */\nexport class AskBackoff<K = string> {\n private readonly paces = new Map<K, { at: number; wait: number }>();\n\n constructor(private readonly firstMs: number, private readonly capMs: number) {}\n\n /** Whether `key` may be asked now: never asked in this run, or its time came. */\n due(key: K, now: number): boolean {\n const pace = this.paces.get(key);\n return !pace || now >= pace.at;\n }\n\n /** When `key` is asked next; `now` if it never was in this run. */\n at(key: K, now: number): number {\n return this.paces.get(key)?.at ?? now;\n }\n\n /**\n * `key` was asked and gave no answer (unreachable, an error, still pending). The next ask waits `firstMs` while\n * `fast`, else twice the last wait, up to `capMs`. Returns that wait.\n */\n missed(key: K, now: number, fast = false): number {\n const last = this.paces.get(key)?.wait;\n const wait = fast || last === undefined ? this.firstMs : Math.min(last * 2, this.capMs);\n this.paces.set(key, { at: now + wait, wait });\n return wait;\n }\n\n /** `key` answered, or is gone: its next ask is due at once. */\n forget(key: K): void {\n this.paces.delete(key);\n }\n\n /** Forgets every key but these (the ones still open). */\n keepOnly(keys: ReadonlySet<K>): void {\n for (const key of this.paces.keys()) if (!keys.has(key)) this.paces.delete(key);\n }\n}\n","import { decodeBolt11, engineError } from \"@ghostly/core\";\nimport type { WalletMode } from \"../../../shared/mints\";\nimport type { CashuWallet } from \"../../wallet\";\nimport type { LightningInvoice, LightningPaymentRef, LightningProvider, LightningProviderDescriptor } from \"./lightning\";\nimport { NothingSpentError, PROVIDER_PLATFORMS } from \"./types\";\n\nexport const CASHU_MINT_SOURCE = \"cashu-mint\";\n\ninterface MintRef { mint: string; quote: string }\nconst parseRef = (ref: string | undefined): MintRef => {\n const parsed = JSON.parse(ref ?? \"null\") as MintRef | null;\n if (!parsed?.mint || !parsed.quote) throw new Error(\"Unknown Cashu quote\");\n return parsed;\n};\n\n/**\n * Lightning through the Cashu mints: invoices are mint quotes that turn into ecash once paid, and\n * invoices are paid by melting ecash. The default source, and what Lightning was before sources.\n *\n * The Cashu wallet already polls its quotes and pending melts, mints and books them and says so\n * (`onQuotePaid`, `onMeltResolved`): the engine forwards those, and never polls this source itself.\n */\nexport class CashuMintLightning implements LightningProvider {\n readonly capabilities = { receive: true, send: true, balance: true, lookup: true };\n readonly settlesItself = true;\n /** The melt quote shown to the person is the one paid: quoting again could change the fee. */\n private readonly quotes = new Map<string, { quote: string; mint: string; amount: number; feeReserve: number }>();\n\n /** `lastBalance`: the balance in the engine's last wallet view, once there is one (see `ProviderHost.cashuBalance`). */\n constructor(private readonly wallet: CashuWallet, private readonly mode: WalletMode, private readonly lastBalance?: () => number | undefined) {}\n\n async info() {\n // Test mints issue invoices for worthless sats (often with a mainnet prefix): the mode says which it is.\n // The balance is the wallets' view's, made again whenever the wallet changes: read for itself, it was a whole read\n // of the proofs, the swaps and the history, as each card opened and every 15 s.\n return { network: this.mode === \"mainnet\" ? \"bitcoin\" as const : \"testnet\" as const, balance: this.lastBalance?.() ?? await this.wallet.balance(this.mode) };\n }\n\n async createInvoice(amount: number): Promise<LightningInvoice> {\n const quote = await this.wallet.receiveLightning(amount, undefined, this.mode);\n const decoded = decodeBolt11(quote.invoice);\n if (!decoded?.paymentHash) throw new Error(\"The mint returned an invoice that cannot be read\");\n return { invoice: quote.invoice, paymentHash: decoded.paymentHash, amount, expiresAt: quote.expiresAt ?? decoded.expiresAt * 1000, ref: JSON.stringify({ mint: quote.mint, quote: quote.quote }) };\n }\n\n async invoiceStatus(invoice: LightningInvoice) {\n const { mint, quote } = parseRef(invoice.ref);\n // A test mint's invoice reads paid by itself: until a payer says it paid, it is open (see CashuWallet.vouch).\n const state = await this.wallet.isHeld(quote) ? \"UNPAID\" : await this.wallet.mintQuoteState(mint, quote);\n if (state === \"PAID\" || state === \"ISSUED\") return { state: \"paid\" as const, amount: invoice.amount };\n return { state: invoice.expiresAt < Date.now() ? \"expired\" as const : \"open\" as const };\n }\n\n /** A real melt quote: its fee reserve is what paying may cost at most. It is kept for `payInvoice`. */\n async estimateFee(invoice: string) {\n const quote = await this.wallet.quoteInvoice(invoice, this.mode);\n this.quotes.set(invoice.trim().toLowerCase(), quote);\n return quote.feeReserve;\n }\n\n /** The quote behind a fee just shown, when there is one: `payQuote` pays exactly that. */\n quoteFor(invoice: string) {\n return this.quotes.get(invoice.trim().toLowerCase());\n }\n\n /** The melt quote `payInvoice` pays, when its fee was shown first: what the mint is asked about later. */\n paymentRef(invoice: string) {\n const quote = this.quotes.get(invoice.trim().toLowerCase());\n return quote ? JSON.stringify({ mint: quote.mint, quote: quote.quote } satisfies MintRef) : undefined;\n }\n\n /**\n * A payment the app was cut off from (the tab closed while it was being paid). A melt written down is the wallet's\n * to settle and report. With none, the mint's word on the quote decides: paid, or never melted (the melt is written\n * down before the mint is handed anything, so an unpaid quote with no melt spent nothing).\n */\n async interruptedPayment(payment: LightningPaymentRef) {\n if (await this.wallet.meltInFlight(payment.invoice)) return \"pending\" as const;\n if (!payment.ref) return \"unknown\" as const;\n const { mint, quote } = parseRef(payment.ref);\n const state = await this.wallet.meltQuoteState(mint, quote);\n // Asked again: a melt written while the mint was being asked is the wallet's to settle.\n if (await this.wallet.meltInFlight(payment.invoice)) return \"pending\" as const;\n return state === \"PAID\" ? \"paid\" as const : state === \"PENDING\" ? \"pending\" as const : \"failed\" as const;\n }\n\n async payInvoice(invoice: string, maxFee: number, note?: string) {\n const key = invoice.trim().toLowerCase();\n let quote = this.quotes.get(key);\n // Nothing reaches the mint's melt before `payQuote`, and it throws only when the sats did not leave.\n try {\n quote ??= await this.wallet.quoteInvoice(invoice, this.mode);\n if (quote.feeReserve > maxFee) throw engineError(\"lightningFeeTooHigh\", { fee: quote.feeReserve });\n } catch (error) {\n throw new NothingSpentError(error instanceof Error ? error.message : String(error));\n }\n this.quotes.delete(key);\n const ref = JSON.stringify({ mint: quote.mint, quote: quote.quote });\n let paid: boolean;\n try { paid = await this.wallet.payQuote(quote.quote, quote.mint, note); }\n catch (error) { throw new NothingSpentError(error instanceof Error ? error.message : String(error)); }\n return paid ? { state: \"paid\" as const, ref } : { state: \"pending\" as const, ref };\n }\n\n async paymentStatus(payment: LightningPaymentRef) {\n const { mint, quote } = parseRef(payment.ref);\n const state = await this.wallet.meltQuoteState(mint, quote);\n return { state: state === \"PAID\" ? \"paid\" as const : state === \"PENDING\" ? \"pending\" as const : \"failed\" as const };\n }\n\n async close() { this.quotes.clear(); }\n}\n\nexport const cashuMint: LightningProviderDescriptor = {\n id: CASHU_MINT_SOURCE,\n label: \"Cashu mints\",\n kind: \"lightning\",\n description: \"Invoices are paid into, and paid from, your Cashu balance. The mints hold the sats.\",\n networks: [\"bitcoin\", \"testnet\"],\n platforms: PROVIDER_PLATFORMS,\n fields: [],\n custodial: true,\n async create(_settings, host) { return new CashuMintLightning(host.cashu as CashuWallet, host.mode, host.cashuBalance); },\n};\n","import { STORES, store, transact, wrap } from \"../../../shared/idb\";\nimport type { WalletMode } from \"../../../shared/mints\";\nimport { ModeChanged, ModeGate } from \"../modeGate\";\nimport { newDeviceKey, sealSeed, unsealSeed, type EncryptedSeed } from \"../persistence\";\nimport { requireTurn } from \"../away\";\nimport { AskBackoff } from \"../../askBackoff\";\nimport { describeProvider, networkMode, offeredIn, redact, sourceProblem, type ProviderDescriptor, type ProviderDescriptorView, type ProviderHost, type ProviderKind, type ProviderNetwork, type ProviderSettings, type SourceProblem } from \"./types\";\n\n/**\n * What is stored for a source, under `<kind>Source-<mode>` (or `<kind>Source-<mode>-<key>`, one Lightning card of\n * several) in the settings store: never in the Settings object (which the UI sees), and its secrets sealed with a\n * device key, like the Ark and USDT seeds.\n */\ninterface StoredSource {\n providerId: string;\n config: Record<string, string>;\n secrets?: EncryptedSeed;\n deviceKey?: string;\n savedAt: number;\n}\n\n/** The last balance a source read, under `<kind>SourceSeen-<mode>`: shown while it reconnects after a restart. */\ninterface SeenBalance { providerId: string; balance?: number; unconfirmed?: number; at: number }\n\nexport interface SourceView {\n mode: WalletMode;\n /** Absent: no source (on-chain has none until one is chosen). */\n providerId?: string;\n label?: string;\n /** The built-in default of this kind (the Cashu mints for Lightning). */\n isDefault?: boolean;\n custodial?: boolean;\n /** The non-secret settings, as saved. */\n config?: Record<string, string>;\n /** The names of the secret fields that are saved. Their values never leave the engine. */\n secrets?: string[];\n status: \"none\" | \"connecting\" | \"ready\" | \"error\";\n network?: ProviderNetwork;\n alias?: string;\n /** Spendable sats, when the source says. */\n balance?: number;\n /** What the source holds was read once since it connected (or it says it shows none): until then `balance` says nothing. */\n read?: true;\n /** On-chain: sats in the mempool. */\n unconfirmed?: number;\n /**\n * The balance shown is the last one read (at this time), not a fresh one: the source is not connected.\n * Absent once it reads again.\n */\n balanceAt?: number;\n /**\n * While `connecting` after a failed attempt, why it failed (it is being tried again by itself); while\n * `error`, why the source is unavailable.\n */\n error?: string;\n /** What kind of failure `error` is: no answer (tried again by itself), a setting to change, or other. */\n problem?: SourceProblem;\n /** Attempts that failed in a row, and when the next one starts (it also starts on Retry, or on waking). */\n failures?: number;\n retryAt?: number;\n /** The providers that can be picked here (this platform, this mode), in registry order. */\n offered: ProviderDescriptorView[];\n}\n\ninterface Connectable { info(): Promise<{ network: ProviderNetwork; alias?: string }>; close(): Promise<void> }\n\nexport interface SourcesOptions<P> {\n kind: ProviderKind;\n /** The network this source belongs to: Mainnet and Testnet each have their own, both connected at once. */\n network: WalletMode;\n descriptors: () => readonly ProviderDescriptor<P>[];\n /** Read each time a source connects. */\n host: () => Omit<ProviderHost, \"mode\" | \"signal\">;\n changed: () => void;\n /** Used while nothing is stored for the mode. */\n defaultId?: string;\n /** One of several sources of this kind and mode (a Lightning card): its own storage keys. Absent: the mode's one. */\n key?: string;\n /** Asked before the source of a mode changes: a refusal (money in flight through it) stops the change. */\n refuseReplacing?: (providerId: string, mode: WalletMode) => Promise<string | undefined>;\n /**\n * Balance and the like, read after connecting and then every `refreshMs` while it answers; a read with no answer\n * is tried again twice as late each time, up to `REFRESH_SLOW_MS`.\n */\n refresh?: (provider: P) => Promise<Partial<Pick<SourceView, \"balance\" | \"unconfirmed\">>>;\n refreshMs?: number;\n /** How long to wait before the next attempt after `failures` failed ones (tests shorten it). */\n backoff?: (failures: number) => number;\n}\n\n/** Where a source is stored: the mode's one, or one of several (`key`). */\nexport const sourceKey = (kind: ProviderKind, mode: WalletMode, key?: string) => `${kind}Source-${mode}${key ? `-${key}` : \"\"}`;\nconst seenKey = (kind: ProviderKind, mode: WalletMode, key?: string) => `${kind}SourceSeen-${mode}${key ? `-${key}` : \"\"}`;\n\n/**\n * A source that does not answer is tried again by itself: 2 s, 4 s, 8 s… up to 5 minutes, ±20 % so\n * that many apps coming back online do not knock at once.\n */\nexport const RETRY_MAX_MS = 5 * 60_000;\nexport function retryDelay(failures: number, random = Math.random): number {\n const base = Math.min(RETRY_MAX_MS, 2_000 * 2 ** Math.max(0, failures - 1));\n return Math.round(base * (0.8 + 0.4 * random()));\n}\n/**\n * \"Unavailable\" only once it has failed this many times in a row for at least this long: a slow server at\n * start-up is \"Connecting…\". A wrong setting is unavailable at once (waiting does not fix it).\n */\nexport const SUSTAINED_FAILURES = 3;\nexport const SUSTAINED_MS = 30_000;\n/**\n * A connected source whose balance read gets no answer (its node went off, the relay is down) is read again twice as\n * late after each failed read, from `refreshMs` up to this (`AskBackoff`, as a Lightning card's pending payment): at\n * the fixed 15 s it was 240 failed requests an hour, for good. A read that answers, waking up and Retry read at once\n * and go back to `refreshMs`.\n */\nexport const REFRESH_SLOW_MS = 30 * 60_000;\nconst REFRESH_MS = 15_000;\n\n/**\n * Gives up on a connection when its signal aborts (a change of settings interrupts an attempt), even if the\n * provider does not listen to it; what still arrives afterwards is closed.\n */\nfunction abortable<P extends Connectable>(work: Promise<P>, signal: AbortSignal): Promise<P> {\n return new Promise<P>((resolve, reject) => {\n const give = () => { reject(new Error(\"The connection attempt was interrupted\")); void work.then((p) => p.close().catch(() => {}), () => {}); };\n if (signal.aborted) return give();\n signal.addEventListener(\"abort\", give, { once: true });\n work.then(\n (value) => { signal.removeEventListener(\"abort\", give); if (!signal.aborted) resolve(value); },\n (error) => { signal.removeEventListener(\"abort\", give); if (!signal.aborted) reject(error); },\n );\n });\n}\n\n/**\n * The active source of one kind (Lightning, on-chain) of one network: Mainnet and Testnet each have their\n * own, both connected at once. Every change is serialized.\n */\nexport class ProviderSources<P extends Connectable> {\n private readonly mode: WalletMode;\n private stored?: StoredSource;\n private descriptor?: ProviderDescriptor<P>;\n private provider?: P;\n /** The connected source's secrets, only to blank them out of error messages. */\n private secrets: Record<string, string> = {};\n private controller = new AbortController();\n private readonly gate = new ModeGate();\n private queue: Promise<unknown> = Promise.resolve();\n private connecting?: Promise<void>;\n private timer?: ReturnType<typeof setTimeout>;\n private retry?: ReturnType<typeof setTimeout>;\n /** Failed attempts in a row, and since when: what makes a failure sustained. */\n private failures = 0;\n private failingSince?: number;\n private seen?: SeenBalance;\n private stopped = false;\n /** When the balance is read next, while reads get no answer (one key: this source). */\n private readonly reads: AskBackoff<\"balance\">;\n /** Balance reads under way, and whether another call to the source got its answer meanwhile (`answered`). */\n private reading = 0;\n private answeredMeanwhile = false;\n /** An answer to another call already brought a read since the last read that answered: the next ones wait their turn. */\n private answerRead = false;\n /** The balance changed while a read was under way (`balanceChanged`): it may say the old one, so one more follows it. */\n private changedMeanwhile = false;\n view: SourceView = { mode: \"mainnet\", status: \"none\", offered: [] };\n\n constructor(private readonly options: SourcesOptions<P>) {\n this.mode = options.network; this.view = { mode: options.network, status: \"none\", offered: [] };\n const every = options.refreshMs ?? REFRESH_MS;\n this.reads = new AskBackoff(every, Math.max(every, REFRESH_SLOW_MS));\n }\n\n private serial<T>(run: () => Promise<T>): Promise<T> { const next = this.queue.then(run, run); this.queue = next.catch(() => {}); return next; }\n private find(id: string) { return this.options.descriptors().find((d) => d.id === id); }\n private offered() { return this.options.descriptors().filter((d) => offeredIn(d, this.options.host().platform, this.mode)).map((d) => describeProvider(d as ProviderDescriptor<unknown>)); }\n private async load(mode: WalletMode) {\n const settings = await store(STORES.settings, \"readonly\");\n const [stored, seen] = await Promise.all([wrap<StoredSource | undefined>(settings.get(sourceKey(this.options.kind, mode, this.options.key))), wrap<SeenBalance | undefined>(settings.get(seenKey(this.options.kind, mode, this.options.key)))]);\n this.stored = stored; this.seen = seen;\n this.failures = 0; this.failingSince = undefined;\n }\n\n /** The source of the mode (stored, else the default), not connected yet: with the last balance it read. */\n private idle(): SourceView {\n const id = this.stored?.providerId ?? this.options.defaultId;\n const descriptor = id ? this.find(id) : undefined;\n const seen = id && this.seen?.providerId === id ? this.seen : undefined;\n return {\n mode: this.mode, offered: this.offered(), providerId: id, label: descriptor?.label ?? id, custodial: descriptor?.custodial,\n isDefault: !!id && id === this.options.defaultId, config: this.stored?.config,\n secrets: descriptor?.fields.filter((f) => f.kind === \"secret\" && this.stored?.secrets).map((f) => f.name),\n status: !id ? \"none\" : descriptor ? \"connecting\" : \"error\",\n error: id && !descriptor ? `${id} is not available in this version of Ghostly` : undefined,\n ...(seen ? { balance: seen.balance, unconfirmed: seen.unconfirmed, balanceAt: seen.at } : {}),\n };\n }\n\n async start() { await this.load(this.mode); this.view = this.idle(); }\n\n /**\n * One saved secret of the source (a handoff asks whether an LND card pins its certificate, and a Breez phrase), or\n * undefined. A connected source reads the secrets it connected with, as `holds` does; one that is not unseals them.\n */\n async secret(name: string): Promise<string | undefined> {\n const stored = this.stored;\n if (!stored?.secrets) return undefined;\n const secrets = (this.provider ? this.secrets : JSON.parse(await unsealSeed(stored.secrets, stored.deviceKey ?? \"\"))) as Record<string, unknown>;\n const value = secrets[name];\n return typeof value === \"string\" && value ? value : undefined;\n }\n\n /** The list of providers changed (a plugin registered): the picker is told, nothing reconnects. */\n refreshOffered() { this.view = { ...this.view, offered: this.offered() }; this.options.changed(); }\n\n /**\n * Connects the mode's source in the background, and keeps trying while it cannot be reached: \"Connecting…\"\n * (with the last balance it read) until the failure is sustained, then \"Unavailable\", still retrying with\n * backoff. `eager` (Retry, waking up): shows \"Connecting…\" again while it tries.\n */\n ensureReady(eager = false): Promise<void> {\n return this.connecting ??= this.serial(() => this.connect(eager)).finally(() => { this.connecting = undefined; });\n }\n\n /**\n * Retry, now: the wait before the next attempt is skipped (a connected source reads its balance now, whatever\n * the wait its failed reads earned). Resolves when the attempt ends.\n */\n retryNow(): Promise<void> {\n if (this.stopped) return Promise.resolve();\n if (this.provider) { this.reads.forget(\"balance\"); return this.refresh(); }\n clearTimeout(this.retry);\n return this.ensureReady(true);\n }\n\n /**\n * The app is back (in front, online, the computer woke): a source that is not connected is tried now, and\n * a connected one reads its balance now.\n */\n wake() {\n if (this.stopped) return;\n if (this.provider) { this.reads.forget(\"balance\"); void this.refresh(); return; }\n if (this.failures && !this.connecting) void this.retryNow();\n }\n\n /**\n * The connected source answered another call (a payment, a fee estimate, an invoice made or looked up): it is back.\n * While its balance reads get no answer, the balance is read now rather than when the wait they earned ends; a\n * read that answers forgets that wait, as any does. A read already under way is left to say it (if it gets no\n * answer, the next one is `refreshMs` later). Once per stretch of failed reads, and one that fails keeps doubling\n * the wait: a source that answers everything but its balance keeps the slow pace. A source whose reads answer:\n * nothing changes.\n */\n answered(provider: P) {\n if (this.stopped || provider !== this.provider || !this.options.refresh || !this.view.error || this.answerRead) return;\n this.answerRead = true;\n if (this.reading) { this.answeredMeanwhile = true; return; }\n void this.refresh();\n }\n\n /**\n * What the connected source holds changed (a payment through it went through, an invoice of ours was seen paid): its\n * balance is read now, failed reads or not, instead of on its timer: the card, the wallet's total and the Send\n * picker would show the balance from before it for up to `refreshMs`. A read already under way may have started\n * before: one more comes right after it, never two at once. It is also the one read an answer brings (`answered`).\n */\n balanceChanged(provider: P) {\n if (this.stopped || provider !== this.provider || !this.options.refresh) return;\n this.answerRead = true;\n if (this.reading) { this.changedMeanwhile = true; return; }\n void this.refresh();\n }\n\n private async connect(eager = false) {\n clearTimeout(this.retry);\n if (this.stopped || this.provider) return;\n const id = this.stored?.providerId ?? this.options.defaultId;\n const descriptor = id ? this.find(id) : undefined;\n if (!id || !descriptor) { this.view = this.idle(); this.options.changed(); return; }\n if (eager && this.view.status === \"error\") { this.view = { ...this.view, status: \"connecting\", retryAt: undefined }; this.options.changed(); }\n const signal = this.controller.signal;\n let secrets: Record<string, string> = {};\n try {\n if (this.stored?.secrets) secrets = JSON.parse(await unsealSeed(this.stored.secrets, this.stored.deviceKey ?? \"\")) as Record<string, string>;\n const { provider, network, alias } = await this.open(descriptor, { config: this.stored?.config ?? {}, secrets });\n this.descriptor = descriptor; this.provider = provider; this.secrets = secrets;\n this.failures = 0; this.failingSince = undefined;\n this.view = { ...this.idle(), status: \"ready\", network, alias };\n this.options.changed();\n void this.refresh();\n } catch (error) {\n // Stopped, another mode, or interrupted by a change of settings: whoever did it connects next.\n if (this.stopped || error instanceof ModeChanged || signal.aborted) return;\n const now = Date.now();\n this.failures++;\n this.failingSince ??= now;\n const problem = sourceProblem(error);\n const sustained = problem === \"config\" || (this.failures >= SUSTAINED_FAILURES && now - this.failingSince >= SUSTAINED_MS);\n const delay = (this.options.backoff ?? retryDelay)(this.failures);\n this.view = { ...this.idle(), status: sustained ? \"error\" : \"connecting\", error: `Could not connect to ${descriptor.label}: ${redact(error, secrets)}`, problem, failures: this.failures, retryAt: now + delay };\n this.options.changed();\n this.retry = setTimeout(() => void this.ensureReady(), delay);\n }\n }\n\n /** Creates a provider and checks it is on a network of this mode before anything uses it. */\n private async open(descriptor: ProviderDescriptor<P>, settings: ProviderSettings, controller = this.controller) {\n // The Breez source shares its database with the Spark wallet of its phrase: one writer, after a fresh turn read.\n if (descriptor.id === \"breez\") await requireTurn();\n const signal = controller.signal;\n const provider = await this.gate.within(abortable(descriptor.create(settings, { ...this.options.host(), mode: this.mode, signal }), signal), (p) => p.close());\n try {\n const { network, alias } = await this.gate.within(provider.info());\n if (!descriptor.networks.includes(network)) throw new Error(`it runs on ${network}, which ${descriptor.label} does not support here`);\n if (networkMode(network) !== this.mode) throw new Error(this.mode === \"mainnet\" ? `it runs on ${network}, a test network: set it up as a Testnet wallet instead` : \"it runs on Bitcoin, real money: set it up as a Mainnet wallet instead\");\n return { provider, network, alias };\n } catch (error) { await provider.close().catch(() => {}); throw error; }\n }\n\n /**\n * Makes `providerId` this mode's source, with the values typed in its form. It is connected and its\n * network checked first; only then are its settings saved (secrets sealed) and the old source closed.\n */\n set(providerId: string, values: Record<string, string>): Promise<void> {\n const interrupted = this.interrupt();\n return this.afterChange(interrupted, this.serial(async () => {\n const { descriptor, settings } = this.settingsOf(providerId, values);\n await this.guard();\n await this.apply(descriptor, settings, false);\n }));\n }\n\n /** The form's values as a source's settings, checked: its secrets apart. Throws what to fix. */\n settingsOf(providerId: string, values: Record<string, string>): { descriptor: ProviderDescriptor<P>; settings: ProviderSettings } {\n const descriptor = this.find(providerId);\n if (!descriptor || !offeredIn(descriptor, this.options.host().platform, this.mode)) throw new Error(\"That source is not available here\");\n const settings: ProviderSettings = { config: {}, secrets: {} };\n for (const field of descriptor.fields) {\n const value = (values[field.name] ?? \"\").trim();\n if (!value && !field.optional) throw new Error(`Enter ${field.label.toLowerCase()}`);\n if (field.kind === \"select\" && value && !field.options?.some((o) => o.value === value)) throw new Error(`Choose ${field.label.toLowerCase()}`);\n if (value) (field.kind === \"secret\" ? settings.secrets : settings.config)[field.name] = value;\n }\n descriptor.validate?.(settings, this.mode);\n return { descriptor, settings };\n }\n\n /**\n * Whether the saved source is this provider reaching the same wallet (the same wallet added twice): the provider's\n * `wallet` says which one (an NWC URI spelled another way, or another app connection to it, is the same), else these\n * very settings. A connected source compares the secrets it connected with; one that is not unseals them here (a\n * 600,000-iteration key: once per card of the kind, each new card took 320 ms more). They never leave.\n */\n async holds(providerId: string, settings: ProviderSettings): Promise<boolean> {\n const stored = this.stored;\n if (!stored || stored.providerId !== providerId) return false;\n const connected = this.provider ? this.secrets : undefined;\n const unseal = async () => connected ?? (stored.secrets ? JSON.parse(await unsealSeed(stored.secrets, stored.deviceKey ?? \"\")) as Record<string, string> : {});\n const wallet = this.find(providerId)?.wallet;\n if (wallet) {\n const secrets = await unseal();\n try { return wallet({ config: stored.config, secrets }) === wallet(settings); } catch { return false; }\n }\n const same = (a: Record<string, string>, b: Record<string, string>) => {\n const keys = Object.keys(a).sort();\n return JSON.stringify(keys) === JSON.stringify(Object.keys(b).sort()) && keys.every((k) => a[k] === b[k]);\n };\n return same(stored.config, settings.config) && same(await unseal(), settings.secrets);\n }\n\n /**\n * Changes the `changeable` fields (a server address) of this mode's saved source, keeping its sealed\n * secrets and whose money it is: the wallet stays, only where it reads the chain changes. Connected and\n * checked first, like `set`; a refusal leaves the saved source as it was.\n */\n reconfigure(values: Record<string, string>): Promise<void> {\n const interrupted = this.interrupt();\n return this.afterChange(interrupted, this.serial(async () => {\n const stored = this.stored;\n const descriptor = stored ? this.find(stored.providerId) : undefined;\n if (!stored || !descriptor) throw new Error(\"There is no saved source to change\");\n const changeable = descriptor.fields.filter((f) => f.changeable);\n if (!changeable.length) throw new Error(`${descriptor.label} has no server to change`);\n const config = { ...stored.config };\n for (const field of changeable) {\n if (!(field.name in values)) continue;\n const value = (values[field.name] ?? \"\").trim();\n if (!value && !field.optional) throw new Error(`Enter ${field.label.toLowerCase()}`);\n if (value) config[field.name] = value; else delete config[field.name];\n }\n const secrets = stored.secrets ? JSON.parse(await unsealSeed(stored.secrets, stored.deviceKey ?? \"\")) as Record<string, string> : {};\n const settings: ProviderSettings = { config, secrets };\n descriptor.validate?.(settings, this.mode);\n await this.apply(descriptor, settings, true);\n }));\n }\n\n /** A change refused after interrupting an attempt: the saved source goes on connecting as before. */\n private afterChange(interrupted: boolean, change: Promise<void>): Promise<void> {\n return change.finally(() => { if (interrupted && !this.provider && !this.stopped) void this.ensureReady(); });\n }\n\n /**\n * A connection attempt under way (or waiting to try again) gives way to a change of settings, instead of\n * holding it for its time-out. Says whether there was one.\n */\n private interrupt(): boolean {\n if (this.provider || (!this.connecting && !this.failures)) return false;\n clearTimeout(this.retry);\n this.controller.abort(); this.controller = new AbortController();\n return true;\n }\n\n /** Connects `settings`, then saves them and replaces the current source. `same`: the same wallet, reconfigured. */\n private async apply(descriptor: ProviderDescriptor<P>, settings: ProviderSettings, same: boolean) {\n const providerId = descriptor.id;\n let opened: Awaited<ReturnType<typeof this.open>>;\n // Its own signal: closing the source it replaces aborts that one's, not this one's.\n const controller = new AbortController();\n try { opened = await this.open(descriptor, settings, controller); }\n catch (error) { throw error instanceof ModeChanged ? error : new Error(`Could not connect to ${descriptor.label}: ${redact(error, settings.secrets)}`); }\n const deviceKey = newDeviceKey();\n const stored: StoredSource = { providerId, config: settings.config, savedAt: Date.now(),\n ...(Object.keys(settings.secrets).length ? { secrets: await sealSeed(JSON.stringify(settings.secrets), deviceKey), deviceKey } : {}) };\n // The default with nothing to configure is what an empty mode already uses: nothing to store.\n const plain = providerId === this.options.defaultId && !Object.keys(settings.config).length && !stored.secrets;\n // Another wallet's last balance is not this one's.\n if (!same) this.seen = undefined;\n try {\n await transact([STORES.settings], (s) => {\n if (plain) s[STORES.settings].delete(sourceKey(this.options.kind, this.mode, this.options.key)); else s[STORES.settings].put(stored, sourceKey(this.options.kind, this.mode, this.options.key));\n if (!same) s[STORES.settings].delete(seenKey(this.options.kind, this.mode, this.options.key));\n });\n }\n catch (error) { await opened.provider.close().catch(() => {}); throw error; }\n await this.disconnect();\n this.controller = controller;\n this.failures = 0; this.failingSince = undefined;\n this.stored = plain ? undefined : stored; this.descriptor = descriptor; this.provider = opened.provider; this.secrets = settings.secrets;\n this.view = { ...this.idle(), status: \"ready\", network: opened.network, alias: opened.alias };\n this.options.changed();\n void this.refresh();\n }\n\n /** Forgets this mode's source (and its sealed secrets): the default, if there is one, takes over. */\n clear(): Promise<void> {\n this.interrupt();\n return this.serial(async () => {\n await this.guard();\n await transact([STORES.settings], (s) => { s[STORES.settings].delete(sourceKey(this.options.kind, this.mode, this.options.key)); s[STORES.settings].delete(seenKey(this.options.kind, this.mode, this.options.key)); });\n await this.disconnect(true);\n this.stored = undefined; this.seen = undefined;\n this.failures = 0; this.failingSince = undefined;\n this.view = this.idle(); this.options.changed();\n }).then(() => this.ensureReady());\n }\n\n /**\n * Forgets this source for good (its card is removed): its settings, sealed secrets and last balance go, it is\n * closed, and nothing takes over. Refused while a payment through it has not ended.\n */\n forget(): Promise<void> {\n this.interrupt();\n return this.serial(async () => {\n await this.guard();\n await transact([STORES.settings], (s) => { s[STORES.settings].delete(sourceKey(this.options.kind, this.mode, this.options.key)); s[STORES.settings].delete(seenKey(this.options.kind, this.mode, this.options.key)); });\n this.stopped = true;\n this.gate.close();\n await this.disconnect(true);\n this.stored = undefined; this.seen = undefined;\n this.view = { mode: this.mode, status: \"none\", offered: [] };\n });\n }\n\n private async guard() {\n const current = this.stored?.providerId ?? this.options.defaultId;\n const refusal = current ? await this.options.refuseReplacing?.(current, this.mode) : undefined;\n if (refusal) throw new Error(refusal);\n }\n\n /** The connected source, waiting for a connection under way. Throws when there is none. */\n async use(): Promise<{ provider: P; descriptor: ProviderDescriptor<P> }> {\n if (!this.provider) await this.ensureReady();\n if (!this.provider || !this.descriptor) throw new Error(this.view.status === \"none\" ? `No ${this.options.kind === \"onchain\" ? \"Bitcoin\" : \"Lightning\"} source is set up` : this.view.error ?? \"The source is still connecting\");\n return { provider: this.provider, descriptor: this.descriptor };\n }\n\n /** A change waiting on its connection gives up now (a creation that took too long); nothing is saved. */\n cutShort() { this.gate.interrupt(); }\n resume() { this.gate.resume(); }\n\n /** The connected source's id, when one is connected right now. */\n get activeId(): string | undefined { return this.provider ? this.descriptor?.id : undefined; }\n get active(): P | undefined { return this.provider; }\n\n async refresh() {\n clearTimeout(this.timer);\n const provider = this.provider;\n if (!provider) return;\n // A kind of source with nothing to read shows no balance: what it shows is read.\n if (!this.options.refresh) { if (!this.view.read) { this.view = { ...this.view, read: true }; this.options.changed(); } return; }\n const before = this.view;\n let wait = this.options.refreshMs ?? REFRESH_MS;\n this.reading++;\n try {\n const details = await this.options.refresh(provider);\n if (provider !== this.provider) return;\n this.view = { ...this.view, ...details, read: true, balanceAt: undefined, error: undefined };\n this.remember(details);\n this.reads.forget(\"balance\");\n this.answerRead = false;\n } catch (error) {\n if (provider !== this.provider) return;\n // Its error stays shown until a read answers.\n this.view = { ...this.view, error: `Could not read the balance: ${redact(error, this.secrets)}` };\n wait = this.reads.missed(\"balance\", Date.now());\n // The source answered another call while this read was under way (it may have started before the source was\n // back): the next read comes soon, once, and the wait goes on doubling from where it was.\n if (this.answeredMeanwhile) wait = this.options.refreshMs ?? REFRESH_MS;\n } finally {\n this.reading--;\n if (!this.reading) this.answeredMeanwhile = false;\n }\n // A read that says what the view already did (the same balance, or none) changes nothing: every 15 s it made a\n // whole wallet view and engine state, with no wallet at all.\n const after = this.view as unknown as Record<string, unknown>, was = before as unknown as Record<string, unknown>;\n if (Object.keys({ ...was, ...after }).some(key => was[key] !== after[key])) this.options.changed();\n if (!this.provider) return;\n clearTimeout(this.timer);\n // The balance changed while this read was under way: it may have said the old one.\n if (this.changedMeanwhile && !this.reading) { this.changedMeanwhile = false; void this.refresh(); return; }\n this.timer = setTimeout(() => void this.refresh(), wait);\n }\n\n /** Keeps the balance read, for the next start: written only when it changed. */\n private remember({ balance, unconfirmed }: Partial<Pick<SourceView, \"balance\" | \"unconfirmed\">>) {\n const providerId = this.descriptor?.id;\n // The default (the Cashu mints) connects without a network: nothing to show meanwhile.\n if (!providerId || providerId === this.options.defaultId || (balance === undefined && unconfirmed === undefined)) return;\n const was = this.seen;\n if (was?.providerId === providerId && was.balance === balance && was.unconfirmed === unconfirmed) return;\n const seen: SeenBalance = { providerId, balance, unconfirmed, at: Date.now() }, key = seenKey(this.options.kind, this.mode, this.options.key);\n this.seen = seen;\n void transact([STORES.settings], (s) => { s[STORES.settings].put(seen, key); }).catch(() => {});\n }\n\n /** `forget`: the source is removed, so what it keeps on this device goes too (a provider's own `forget`). */\n private async disconnect(forget = false) {\n clearTimeout(this.timer); clearTimeout(this.retry); this.reads.forget(\"balance\"); this.answerRead = false; this.changedMeanwhile = false;\n this.controller.abort(); this.controller = new AbortController();\n const provider = this.provider as (P & { forget?: () => Promise<void> }) | undefined;\n this.provider = undefined; this.descriptor = undefined; this.secrets = {};\n await (forget && provider?.forget ? provider.forget() : provider?.close())?.catch(() => {});\n }\n\n /** Shutting down: nothing reconnects afterwards. */\n async stop() { this.stopped = true; this.gate.close(); await this.serial(() => this.disconnect()); }\n}\n","/**\n * How often an open invoice of ours is asked about, at its Cashu mint or at a Lightning card's source (agents#2447).\n * Someone pays an invoice soon after it is shown, or not at all: it is asked about every few seconds at first, then\n * less and less. Asked every 4 s for the hour a mint or a node keeps it open, an invoice nobody paid cost about 900\n * requests (on NWC each one signed, encrypted and carried by the wallet's relay); on this pace it costs about 100.\n *\n * Whoever knows a payment may have happened asks at once, whatever the pace: a payer's \"I paid\" (`vouch`), the\n * request's check, a wallet about to be removed. The screen showing an invoice keeps it `watched`, at the fast pace.\n */\nexport const INVOICE_PACE = {\n /** While the invoice is new, or watched: a payment shows within seconds. */\n fastMs: 4_000,\n fastForMs: 2 * 60_000,\n /** Then, until it is this old. */\n midMs: 15_000,\n midForMs: 5 * 60_000,\n /** From then on, until it expires. */\n slowMs: 60_000,\n /** How long one word from the screen keeps an invoice watched: the screen says it again while it shows it. */\n watchMs: 90_000,\n /** A quote or an invoice goes only this long after its expiry, once its mint or source says it is unpaid. */\n expiryGraceMs: 60_000,\n /**\n * A mint or a Lightning card's source that does not answer about an invoice, or answers with an error, is asked again\n * after this, then twice as late each time up to `missedCapMs` (`AskBackoff`): the pace above never looked at whether\n * it answered, and a dead mint or node was asked every minute (every 4 s about a paid invoice) for good.\n */\n missedMs: 30_000,\n missedCapMs: 30 * 60_000,\n /** Due this close to now counts as due: a timer may fire a moment before the clock reads its time. */\n dueSlackMs: 250,\n} as const;\n\nexport interface PacedInvoice {\n createdAt: number;\n /** Null: an invoice that does not expire. */\n expiresAt: number | null;\n /** Until when the screen shows it (`watch`). */\n watchedUntil?: number;\n /**\n * The chat request it is the invoice of was closed (withdrawn, closed, or paid some other way): nobody is meant to\n * pay it any more. It is asked about once more after it expired, so money that came all the same is claimed, and\n * the quote goes.\n */\n closed?: boolean;\n /** The money is there and only its claim is left (a paid quote not minted yet): asked at the fast pace. */\n paid?: boolean;\n}\n\n/** When the invoice is next asked about. `asked`: when it was last, in this run; never, it is due now. */\nexport function nextInvoiceAsk(invoice: PacedInvoice, asked: number | undefined, now: number): number {\n const { fastMs, fastForMs, midMs, midForMs, slowMs, expiryGraceMs } = INVOICE_PACE;\n const fast = invoice.paid || (invoice.watchedUntil ?? 0) > now;\n if (invoice.closed && !fast) {\n if (invoice.expiresAt !== null) return Math.max(asked === undefined ? now : asked + slowMs, invoice.expiresAt + expiryGraceMs + 1);\n return asked === undefined ? now : asked + slowMs;\n }\n if (asked === undefined) return now;\n const age = now - invoice.createdAt;\n return asked + (fast || age < fastForMs ? fastMs : age < midForMs ? midMs : slowMs);\n}\n","import { decodeBolt11, engineError, requestLnurlInvoice, resolveLightningDestination, type LnurlPayParams, type LnurlSuccessAction } from \"@ghostly/core\";\nimport { STORES, store, transact, wrap } from \"../../../shared/idb\";\nimport { BITCOIN_INVOICE_ON_TESTNET, type WalletMode } from \"../../../shared/mints\";\nimport { CASHU_MINT_SOURCE, CashuMintLightning } from \"./cashuMint\";\nimport type { LightningInvoice, LightningProvider, LightningProviderDescriptor } from \"./lightning\";\nimport { ProviderSources, type SourceView } from \"./sources\";\nimport { isNothingSpentError, redact, type ProviderHost } from \"./types\";\nimport { AskBackoff } from \"../../askBackoff\";\nimport { INVOICE_PACE, nextInvoiceAsk } from \"../../invoicePace\";\n\n/**\n * One Lightning operation, journaled under `lightningOp-<direction>-<payment hash>` in the settings store\n * BEFORE the provider is asked to spend: after a crash or a lost answer it is only ever reconciled (asked\n * about), never paid again. Incoming invoices are journaled too, so whoever paid a chat request is told\n * once the source sees it paid.\n */\nexport interface LightningOp {\n direction: \"in\" | \"out\";\n providerId: string;\n mode: WalletMode;\n paymentHash: string;\n invoice: string;\n amount: number;\n /** The chat payment request this pays, or is the invoice of. */\n paymentId?: string;\n note?: string;\n ref?: string;\n expiresAt: number;\n createdAt: number;\n /** The source books and reports this itself (the Cashu wallet): the engine does not poll it. */\n selfSettled?: boolean;\n /**\n * The Lightning card it went through (see `lightningCards.ts`). Absent on operations journaled before a network could\n * have several cards: those belong to the card that took over the network's one source (`legacyCard`).\n */\n card?: string;\n /** in: open → paid | expired. out: sending → paid | pending | failed | unknown (a lost answer). */\n state: \"open\" | \"paid\" | \"expired\" | \"sending\" | \"pending\" | \"failed\" | \"unknown\";\n maxFee?: number;\n fee?: number;\n error?: string;\n settledAt?: number;\n}\nexport type LightningOpView = Omit<LightningOp, \"ref\" | \"note\" | \"selfSettled\">;\n\n/** Options of one Lightning card's service. Without `card`, it is the network's only one (tests, older callers). */\nexport interface LightningServiceOptions {\n fetch?: typeof fetch;\n /** The card this service is: its operations carry the id, and it reads only its own. */\n card?: string;\n /** Where its source is stored: `lightningSource-<network>-<key>`; absent, the network's one key. */\n key?: string;\n /** Whether a journaled operation is this card's. Default: one carrying its id, or one carrying none. */\n owns?: (op: LightningOp) => boolean;\n}\nexport interface LightningView extends SourceView {\n capabilities?: LightningProvider[\"capabilities\"];\n /** This mode's latest operations, newest first. */\n recent: LightningOpView[];\n}\n/** `mint`: the Cashu mint that will pay, when the source is the mints; otherwise the source's id. */\nexport interface LightningQuote { quote: string; mint: string; amount: number; feeReserve: number; source: string }\n/** What a person sees of a resolved Lightning address or LNURL before choosing an amount. Amounts are whole sats. */\nexport interface LnurlView {\n id: string;\n kind: \"address\" | \"lnurl\";\n /** The address or LNURL, as normalised. */\n text: string;\n /** The host that learned of the request. */\n domain: string;\n /** The host the invoice is asked from, when it is another. */\n callbackDomain: string;\n minSat: number;\n maxSat: number;\n /** What the service says the payment is for. */\n description: string;\n /** How long a comment may be (LUD-12); 0 when none is taken. */\n commentAllowed: number;\n}\n/** Who an event is about. `mint`: the Cashu mint it went through, when it did. `invoice`: what it paid or was paid. */\nexport interface LightningEventOp { paymentId?: string; providerId: string; mint?: string; invoice?: string }\n\nexport interface LightningEvents {\n changed(): void;\n /** One of our invoices was paid. `paymentId`: the chat request it belongs to. */\n received(op: LightningEventOp): void;\n /** A payment left pending or unknown ended, one way or the other. */\n resolved(op: LightningEventOp, paid: boolean): void;\n /**\n * Whether the chat request an invoice of ours belongs to was closed (withdrawn, closed, or paid some other way): the\n * source is then asked about it only once more, after it expired (`nextInvoiceAsk`).\n */\n requestClosed?(paymentId: string): boolean;\n}\n\nconst PREFIX = \"lightningOp-\";\nconst opKey = (direction: LightningOp[\"direction\"], hash: string) => `${PREFIX}${direction}-${hash}`;\nconst RANGE = () => IDBKeyRange.bound(PREFIX, `${PREFIX}\\uffff`);\n/** Every Lightning operation journaled, of every network and card. */\n/** Lightning payments whose call to the source has not returned, on any card of this page (WISP 06 § Payments in flight). */\nlet paying = 0;\nexport const lightningPaying = (): number => paying;\n\n/**\n * The journal as last read, for the database it was read from, while nothing wrote it since (`journalVersion`, moved\n * by `LightningService.put`, its one writer). A start read the whole journal 38 times, 8 of them one after another\n * before the chat list could show: with 5,000 past payments the list showed 0.25 s later (0.5-0.75 s at 4x CPU), and\n * a CLI daemon took 0.5 s and 125 MB more to start (agents#1687). Reads in flight together share one.\n */\nlet journal: { db: IDBDatabase; version: number; ops: Promise<LightningOp[]> } | undefined;\nlet journalVersion = 0;\nconst journalWritten = () => { journalVersion++; journal = undefined; };\n/** The journal was written outside `LightningService.put` (a test seeding or clearing the store): read it again. */\nexport const lightningJournalWritten = (): void => journalWritten();\n\n/** Every Lightning operation journaled, as copies: a caller may change what it got. */\nexport async function readLightningJournal(): Promise<LightningOp[]> {\n const settings = await store(STORES.settings, \"readonly\"), db = settings.transaction.db;\n let read = journal;\n if (!read || read.db !== db || read.version !== journalVersion) {\n const ops = wrap<LightningOp[]>(settings.getAll(RANGE()));\n const made = read = { db, version: journalVersion, ops };\n journal = made;\n ops.catch(() => { if (journal === made) journal = undefined; });\n }\n return (await read.ops).map((op) => ({ ...op }));\n}\n\n/**\n * What the journal says of the payments of one chat request (`DeskLightning.interrupted`): \"pending\" while one has not\n * ended (sending, pending, unknown: its card settles it and says so), \"paid\" once one went through, undefined when\n * none left the wallet (none journaled, or only failed ones).\n */\nexport async function journaledPayment(paymentId: string): Promise<\"pending\" | \"paid\" | undefined> {\n const ops = (await readLightningJournal()).filter((op) => op.direction === \"out\" && op.paymentId === paymentId);\n if (ops.some((op) => op.state === \"sending\" || op.state === \"pending\" || op.state === \"unknown\")) return \"pending\";\n return ops.some((op) => op.state === \"paid\") ? \"paid\" : undefined;\n}\n/** A payment whose answer was lost is asked about this often while it is new (OUT_FAST_FOR_MS)... */\nconst OUT_POLL_MS = 15_000;\nconst OUT_FAST_FOR_MS = 5 * 60_000;\n/** ...then, while its source keeps it pending or cannot be reached, twice as late each time up to this. */\nconst OUT_SLOW_POLL_MS = 1_800_000;\nconst RECENT = 20;\n/** Resolved Lightning addresses are kept this long for the amount to be chosen; this many at most. */\nconst LNURL_TTL_MS = 10 * 60_000;\nconst LNURL_KEPT = 20;\n/** A source that cannot tell its fee beforehand gets this ceiling, the same one chat requests are paid under. */\nexport const defaultFeeCap = (amount: number) => Math.max(10, Math.ceil(amount * 0.03));\n\n/**\n * Lightning of one network: its Lightning card, the invoice a chat request on that network carries and paying a\n * contact's invoice on it all come here, and go to this network's active source. The engine has one per network.\n */\nexport class LightningService {\n readonly sources: ProviderSources<LightningProvider>;\n private readonly quotes = new Map<string, { providerId: string; provider: LightningProvider; invoice: string; amount: number; maxFee: number; paymentHash: string }>();\n private readonly mode: WalletMode;\n private timer?: ReturnType<typeof setTimeout>;\n /** When `timer` fires: a pass that would fire later leaves it as it is. */\n private timerAt = 0;\n /** Per open invoice of ours (payment hash): when the source was last asked about it, in this run. */\n private readonly asked = new Map<string, number>();\n /** Per invoice the screen shows (payment hash): until when (`watch`). */\n private readonly watched = new Map<string, number>();\n /**\n * Per open invoice whose source did not answer about it, or answered with an error (payment hash): as Cashu quotes',\n * on top of its own pace. Asked every minute for good, one invoice cost 60 lookups an hour at a dead node, 20 cost 1,200.\n */\n private readonly invoiceAsk = new AskBackoff(INVOICE_PACE.missedMs, INVOICE_PACE.missedCapMs);\n /** When an open invoice in `recent` next reads as expired (`shownExpiredAt`): the view is read again then. */\n private recentTurns = Infinity;\n /** Per outgoing payment left pending or unknown (payment hash): when its source is asked next, in this run. */\n private readonly outAsk = new AskBackoff(OUT_POLL_MS, OUT_SLOW_POLL_MS);\n private passes: Promise<void> = Promise.resolve();\n private stopped = false;\n private recent: LightningOpView[] = [];\n /** Operations written in this run (`put`): a reconcile pass that wrote one is news, recent or not. */\n private writes = 0;\n /** Lightning addresses and LNURLs resolved, until an amount is chosen for them. */\n private readonly lnurls = new Map<string, { params: LnurlPayParams; at: number }>();\n\n constructor(readonly network: WalletMode, descriptors: () => readonly LightningProviderDescriptor[], host: () => Omit<ProviderHost, \"mode\" | \"signal\">, private readonly events: LightningEvents, defaultId?: string, private readonly options: LightningServiceOptions = {}) {\n this.mode = network;\n this.sources = new ProviderSources<LightningProvider>({\n kind: \"lightning\", network, descriptors, host, defaultId, key: options.key,\n changed: () => { this.schedule(0); events.changed(); },\n refuseReplacing: (providerId, mode) => this.refusal(providerId, mode),\n refresh: async (provider) => (provider.capabilities.balance ? { balance: (await provider.info()).balance } : {}),\n });\n }\n\n /** The card this service is, when the network has several. */\n get card(): string | undefined { return this.options.card; }\n /** Whether a journaled operation went through this card (and this network). */\n owns(op: LightningOp): boolean {\n if (op.mode !== this.mode) return false;\n return this.options.owns ? this.options.owns(op) : op.card === undefined || op.card === this.options.card;\n }\n\n get view(): LightningView {\n return { ...this.sources.view, capabilities: this.sources.active?.capabilities, recent: this.recent };\n }\n\n async start() { await this.sources.start(); await this.loadRecent(); }\n ensureReady() { return this.sources.ensureReady(); }\n async stop() { this.stopped = true; clearTimeout(this.timer); this.timer = undefined; await this.sources.stop(); }\n refreshOffered() { this.sources.refreshOffered(); }\n\n // -- receiving -----------------------------------------------------------------\n\n async createInvoice(amount: number, context: { memo?: string; paymentId?: string } = {}): Promise<LightningInvoice & { source: string }> {\n const { provider, descriptor } = await this.sources.use();\n if (!provider.capabilities.receive) throw new Error(`${descriptor.label} cannot create invoices`);\n // Receiving needs looking up, as paying does: an invoice the source cannot be asked about would never be seen\n // paid nor expire, and its chat request would wait for good. A source that reports its own (the mints) is told.\n if (!provider.capabilities.lookup && !provider.settlesItself) throw new Error(`${descriptor.label} cannot look up its invoices, so a payment to it would never be seen: receive with another Lightning card, or connect it with invoice lookup allowed`);\n const created = await provider.createInvoice(amount, context.memo ?? \"Ghostly\");\n this.sources.answered(provider);\n const decoded = decodeBolt11(created.invoice);\n // What goes to a contact must be the invoice we asked for: this amount, this hash, the right chain.\n if (!decoded || decoded.amountSat !== amount || (decoded.paymentHash && decoded.paymentHash !== created.paymentHash) || created.amount !== amount) throw new Error(`${descriptor.label} returned an invoice that does not match the request`);\n this.checkNetwork(decoded.network);\n await this.put({ direction: \"in\", providerId: descriptor.id, mode: this.mode, ...this.cardField(), paymentHash: created.paymentHash, invoice: created.invoice, amount, paymentId: context.paymentId, ref: created.ref, expiresAt: created.expiresAt, createdAt: Date.now(), selfSettled: !!provider.settlesItself, state: \"open\" });\n // Nobody paid it yet: it is first asked about after the fast pace's gap.\n this.asked.set(created.paymentHash, Date.now());\n this.schedule(INVOICE_PACE.fastMs);\n return { ...created, source: descriptor.id };\n }\n\n /**\n * The screen shows this invoice of ours (Receive): the source is asked about it at the fast pace for\n * `INVOICE_PACE.watchMs`, and now if it was not just asked. Returns whether it is an open invoice of this card's.\n */\n async watch(invoice: string): Promise<boolean> {\n const hash = decodeBolt11(invoice)?.paymentHash;\n const op = hash ? await this.get(\"in\", hash) : undefined;\n if (!op || !this.owns(op) || op.state !== \"open\") return false;\n this.watched.set(op.paymentHash, Date.now() + INVOICE_PACE.watchMs);\n // Its source may be back: the screen asks whatever wait its silence earned.\n this.invoiceAsk.forget(op.paymentHash);\n this.schedule(0);\n return true;\n }\n\n /**\n * A payer says it paid this invoice of ours: the source is asked about it now, and at the fast pace for\n * `INVOICE_PACE.watchMs`. The other open invoices keep their pace. Returns whether it is an open invoice of this card's.\n */\n async check(invoice: string): Promise<boolean> {\n const hash = decodeBolt11(invoice)?.paymentHash;\n const op = hash ? await this.get(\"in\", hash) : undefined;\n if (!op || !this.owns(op) || op.state !== \"open\") return false;\n this.watched.set(op.paymentHash, Date.now() + INVOICE_PACE.watchMs);\n this.invoiceAsk.forget(op.paymentHash);\n await this.reconcile(false, op.paymentHash);\n return true;\n }\n\n /** The Cashu wallet minted the ecash of one of its invoices (it polls its own quotes). */\n async reportInvoicePaid(invoice: string, context: { paymentId?: string; mint?: string } = {}) {\n const hash = decodeBolt11(invoice)?.paymentHash;\n const op = hash ? await this.get(\"in\", hash) : undefined;\n if (op && op.state !== \"paid\") await this.put({ ...op, state: \"paid\", settledAt: Date.now() });\n // Quotes made before sources carry their chat request themselves.\n this.events.received({ paymentId: op?.paymentId ?? context.paymentId, providerId: op?.providerId ?? CASHU_MINT_SOURCE, mint: context.mint });\n await this.loadRecent(); this.events.changed();\n }\n\n // -- Lightning addresses and LNURLs (LUD-16, LUD-06) -----------------------------\n\n /**\n * Fetches what a Lightning address or LNURL asks for, and keeps it until an amount is chosen. The\n * service's domain learns of the request: the caller says so before asking.\n */\n async resolveDestination(text: string): Promise<LnurlView> {\n const params = await resolveLightningDestination(text, { fetch: this.options.fetch });\n const now = Date.now();\n for (const [id, entry] of this.lnurls) if (entry.at + LNURL_TTL_MS < now) this.lnurls.delete(id);\n while (this.lnurls.size >= LNURL_KEPT) this.lnurls.delete(this.lnurls.keys().next().value!);\n const id = crypto.randomUUID();\n this.lnurls.set(id, { params, at: now });\n const { destination, callbackDomain, minSat, maxSat, description, commentAllowed } = params;\n return { id, kind: destination.kind, text: destination.text, domain: destination.domain, callbackDomain, minSat, maxSat, description, commentAllowed };\n }\n\n /**\n * The invoice for `amountSat` from a resolved destination: checked (the amount, a commitment to what\n * was shown, not expired, a network of this mode) before it is quoted and paid like any other invoice.\n */\n async destinationInvoice(id: string, amountSat: number, comment?: string): Promise<{ invoice: string; successAction?: LnurlSuccessAction; note: string }> {\n const entry = this.lnurls.get(id);\n if (!entry || entry.at + LNURL_TTL_MS < Date.now()) { this.lnurls.delete(id); throw new Error(\"That address was resolved too long ago: check it again\"); }\n const { invoice, successAction } = await requestLnurlInvoice(entry.params, amountSat, comment, { fetch: this.options.fetch });\n this.checkNetwork(invoice.network);\n return { invoice: invoice.invoice, successAction, note: entry.params.destination.text };\n }\n\n /** Whether this card resolved that address (the invoice is asked where it was resolved). */\n hasDestination(id: string) { return this.lnurls.has(id); }\n\n // -- paying --------------------------------------------------------------------\n\n /** What paying this invoice costs at most, from the active source. Nothing is spent. */\n async quote(text: string): Promise<LightningQuote> {\n const decoded = decodeBolt11(text);\n if (!decoded) throw new Error(\"That is not a Lightning invoice\");\n if (decoded.amountSat === null) throw new Error(\"Invoices without an amount are not supported\");\n if (!decoded.paymentHash) throw new Error(\"That invoice has no payment hash\");\n if (decoded.expiresAt * 1000 < Date.now()) throw engineError(\"invoiceExpired\");\n this.checkNetwork(decoded.network);\n const { provider, descriptor } = await this.sources.use();\n // A Bitcoin invoice on Testnet: only the mints can tell test sats from real ones (`fakesLightning`, checked when\n // they quote it). Any other Testnet source that pays one is a real node, and would pay it with real money.\n if (this.mode === \"testnet\" && decoded.network === \"bitcoin\" && !(provider instanceof CashuMintLightning)) throw new Error(BITCOIN_INVOICE_ON_TESTNET);\n if (!provider.capabilities.send) throw new Error(`${descriptor.label} cannot pay invoices`);\n const maxFee = provider.estimateFee ? await provider.estimateFee(decoded.invoice, decoded.amountSat) : defaultFeeCap(decoded.amountSat);\n if (provider.estimateFee) this.sources.answered(provider);\n if (!Number.isSafeInteger(maxFee) || maxFee < 0) throw new Error(`${descriptor.label} returned an invalid fee`);\n const id = crypto.randomUUID();\n this.quotes.set(id, { providerId: descriptor.id, provider, invoice: decoded.invoice, amount: decoded.amountSat, maxFee, paymentHash: decoded.paymentHash });\n const mint = provider instanceof CashuMintLightning ? provider.quoteFor(decoded.invoice)?.mint : undefined;\n return { quote: id, mint: mint ?? descriptor.id, amount: decoded.amountSat, feeReserve: maxFee, source: descriptor.id };\n }\n\n hasQuote(id: string) { return this.quotes.has(id); }\n\n /**\n * Pays a quote. True once paid; false while in flight or unknown (reconciled in the background, never\n * paid again). Throws only when nothing left the wallet.\n */\n async pay(quoteId: string, context: { note?: string; paymentId?: string } = {}): Promise<boolean> {\n const quote = this.quotes.get(quoteId);\n if (!quote) throw new Error(\"This quote is no longer valid: check the invoice again\");\n if (this.sources.active !== quote.provider) { this.quotes.delete(quoteId); throw new Error(\"The Lightning source changed: check the invoice again\"); }\n this.quotes.delete(quoteId);\n const existing = await this.get(\"out\", quote.paymentHash);\n if (existing && existing.state !== \"failed\") throw new Error(existing.state === \"paid\" ? \"This invoice is already paid\" : \"This invoice is already being paid\");\n let op: LightningOp = { direction: \"out\", providerId: quote.providerId, mode: this.mode, ...this.cardField(), paymentHash: quote.paymentHash, invoice: quote.invoice, amount: quote.amount, paymentId: context.paymentId, note: context.note?.slice(0, 140), expiresAt: 0, createdAt: Date.now(), selfSettled: !!quote.provider.settlesItself, state: \"sending\", maxFee: quote.maxFee, ref: quote.provider.paymentRef?.(quote.invoice) };\n // Written down before the provider sees it: from here on the sats may be gone.\n await this.put(op);\n paying += 1;\n try {\n const result = await quote.provider.payInvoice(quote.invoice, quote.maxFee, context.note);\n // The source answered: a card that could not read its balance reads it now; one paid reads it now anyway (it changed).\n if (result.state === \"paid\") this.sources.balanceChanged(quote.provider); else this.sources.answered(quote.provider);\n op = result.state === \"paid\" ? { ...op, state: \"paid\", fee: result.fee, ref: result.ref ?? op.ref, settledAt: Date.now() } : { ...op, state: \"pending\", ref: result.ref ?? op.ref };\n } catch (error) {\n if (isNothingSpentError(error)) { await this.put({ ...op, state: \"failed\", error: redact(error) }); await this.showRecent(); throw error; }\n // A source that cannot look payments up never settles this by itself: say so rather than \"being checked\".\n op = { ...op, state: \"unknown\", error: quote.provider.capabilities.lookup ? \"No answer from the source. It is being checked; nothing is paid again.\" : \"No answer from the source, and it cannot be asked: check this payment in the wallet itself. It is never paid again.\" };\n } finally { paying -= 1; }\n await this.put(op);\n await this.showRecent();\n if (op.state !== \"paid\") this.schedule(OUT_POLL_MS);\n return op.state === \"paid\";\n }\n\n /**\n * A payment ended (paid, refused, or left to be checked): the recent list says so now. It was read again only by a\n * later pass, which a balance that changed brought: one refused right after a paid one kept the paid one first. A\n * read that fails leaves it to the next pass: the payment's own outcome is what the caller hears.\n */\n private async showRecent() { if (await this.loadRecent().catch(() => false)) this.events.changed(); }\n\n /** The Cashu wallet settled a melt it had left pending. */\n async reportPaymentResolved(invoice: string, paid: boolean, context: { paymentId?: string; mint?: string } = {}) {\n const hash = decodeBolt11(invoice)?.paymentHash;\n const op = hash ? await this.get(\"out\", hash) : undefined;\n if (op) await this.put({ ...op, state: paid ? \"paid\" : \"failed\", settledAt: Date.now() });\n this.events.resolved({ paymentId: op?.paymentId ?? context.paymentId, providerId: op?.providerId ?? CASHU_MINT_SOURCE, mint: context.mint, invoice }, paid);\n await this.loadRecent(); this.events.changed();\n }\n\n // -- reconciling ---------------------------------------------------------------\n\n /**\n * Asks the active source about everything of its that is open, pending or unknown. One pass at a time. `paced`: an\n * open invoice only when its pace says so (`nextInvoiceAsk`, and not before the wait its source's silence earned,\n * `invoiceAsk`), and a payment left pending or unknown only when its own does (`outAsk`); otherwise every one now.\n * Once one open invoice got no answer in a pass, the others due in it wait as that one does, unasked. `only`: the\n * open invoice with this payment hash alone (a payer says it paid it, `check`).\n */\n reconcile(paced = false, only?: string): Promise<void> {\n const pass = this.passes.then(() => this.reconcileOnce(paced, only));\n this.passes = pass.catch(() => {});\n return pass;\n }\n\n private async reconcileOnce(paced: boolean, only?: string): Promise<void> {\n if (this.stopped) return;\n let again = 0;\n const later = (ms: number) => { again = again ? Math.min(again, ms) : ms; };\n /** An outgoing payment asked with no answer (pending, or the source unreachable): asked less and less often. */\n const missed = (op: LightningOp) => later(this.outAsk.missed(op.paymentHash, Date.now(), Date.now() < op.createdAt + OUT_FAST_FOR_MS));\n /** Whether a paced pass leaves this outgoing payment for later. */\n const notYet = (op: LightningOp) => {\n if (!paced || this.outAsk.due(op.paymentHash, Date.now())) return false;\n later(Math.max(0, this.outAsk.at(op.paymentHash, Date.now()) - Date.now()));\n return true;\n };\n /** When the next open invoice is due. */\n let invoiceDue = Infinity;\n /** An open invoice got no answer in this pass: the source is taken as down until the next one. */\n let down = false;\n /** An open invoice of ours got no answer: asked again later, and later each time (on top of its own pace). */\n const unanswered = (op: LightningOp) => {\n this.invoiceAsk.missed(op.paymentHash, Date.now());\n invoiceDue = Math.min(invoiceDue, this.nextAsk(op, Date.now()));\n };\n const writes = this.writes;\n try {\n const provider = this.sources.active, providerId = this.sources.activeId;\n const ops = await this.list();\n // What this run knows of invoices that are no longer open goes with them.\n const open = new Set(ops.filter((op) => op.direction === \"in\" && op.state === \"open\").map((op) => op.paymentHash));\n for (const pace of [this.asked, this.watched]) for (const hash of pace.keys()) if (!open.has(hash)) pace.delete(hash);\n this.invoiceAsk.keepOnly(open);\n this.outAsk.keepOnly(new Set(ops.filter((op) => op.direction === \"out\" && [\"pending\", \"unknown\"].includes(op.state)).map((op) => op.paymentHash)));\n for (const op of ops) {\n if (!this.owns(op) || (only !== undefined && (op.direction !== \"in\" || op.paymentHash !== only))) continue;\n if (op.selfSettled) {\n // The source settles and reports its own. One cut off before its answer was written (`recover`) it may\n // never have heard of, and would never report: the source is asked what became of it.\n if (op.direction !== \"out\" || op.state !== \"unknown\") continue;\n // No source connected yet: asked again. Another source's waits until its own is active again.\n if (!provider) { later(OUT_POLL_MS); continue; }\n if (op.providerId !== providerId || !provider.interruptedPayment || notYet(op)) continue;\n try {\n const outcome = await provider.interruptedPayment({ invoice: op.invoice, paymentHash: op.paymentHash, ref: op.ref });\n this.sources.answered(provider);\n if (outcome === \"pending\") missed(op);\n if (outcome !== \"paid\" && outcome !== \"failed\") continue;\n this.outAsk.forget(op.paymentHash);\n // Written only over the state that was asked about: the source's own report wins.\n if ((await this.get(\"out\", op.paymentHash))?.state !== \"unknown\") continue;\n await this.put({ ...op, state: outcome, error: outcome === \"failed\" ? \"The payment did not go through\" : undefined, settledAt: Date.now() });\n if (outcome === \"paid\") this.sources.balanceChanged(provider);\n this.events.resolved(op, outcome === \"paid\");\n } catch { missed(op); }\n continue;\n }\n // `sending` is a spend under way in this process: its own answer decides. One left by a crash is\n // made `unknown` by `recover` at the next start, and only then asked about.\n const waiting = op.direction === \"in\" ? op.state === \"open\" : [\"pending\", \"unknown\"].includes(op.state);\n if (!waiting) continue;\n // Another source's operation waits until that source is active again: only it can answer.\n if (!provider || op.providerId !== providerId || !provider.capabilities.lookup) continue;\n if (op.direction === \"in\") {\n const due = this.nextAsk(op, Date.now());\n if (paced && due > Date.now() + INVOICE_PACE.dueSlackMs) { invoiceDue = Math.min(invoiceDue, due); continue; }\n this.asked.set(op.paymentHash, Date.now());\n // Its source did not answer about another invoice just now: this one waits as that one does.\n if (down) { unanswered(op); continue; }\n } else if (notYet(op)) continue;\n try {\n const unchanged = async () => (await this.get(op.direction, op.paymentHash))?.state === op.state;\n if (op.direction === \"in\") {\n const status = await provider.invoiceStatus({ invoice: op.invoice, paymentHash: op.paymentHash, amount: op.amount, expiresAt: op.expiresAt, ref: op.ref });\n this.invoiceAsk.forget(op.paymentHash);\n this.sources.answered(provider);\n if (!(await unchanged())) continue;\n if (status.state === \"paid\") { await this.put({ ...op, state: \"paid\", settledAt: Date.now() }); this.sources.balanceChanged(provider); this.events.received(op); }\n else if (status.state === \"expired\" || op.expiresAt + INVOICE_PACE.expiryGraceMs < Date.now()) await this.put({ ...op, state: \"expired\" });\n else invoiceDue = Math.min(invoiceDue, this.nextAsk(op, Date.now()));\n } else {\n const status = await provider.paymentStatus({ invoice: op.invoice, paymentHash: op.paymentHash, ref: op.ref });\n this.sources.answered(provider);\n if (status.state === \"pending\") { missed(op); continue; }\n this.outAsk.forget(op.paymentHash);\n // Written only over the state that was asked about: anything newer wins.\n if (!(await unchanged())) continue;\n await this.put({ ...op, state: status.state, fee: status.fee ?? op.fee, error: status.state === \"failed\" ? \"The payment did not go through\" : undefined, settledAt: Date.now() });\n if (status.state === \"paid\") this.sources.balanceChanged(provider);\n this.events.resolved(op, status.state === \"paid\");\n }\n } catch {\n // The source cannot be asked right now: ask again later (later each time for an invoice), nothing changes.\n if (op.direction === \"in\") { down = true; unanswered(op); }\n else missed(op);\n }\n }\n } finally {\n // Only a pass that settled something, or whose recent list reads otherwise, is news to the wallet view.\n if (await this.loadRecent() || this.writes !== writes) this.events.changed();\n const wait = Math.min(again || Infinity, invoiceDue - Date.now(), this.recentTurns - Date.now());\n if (wait < Infinity) this.schedule(Math.max(0, wait));\n }\n }\n\n /** When the source is next asked about this open invoice of ours: at its pace, and not before the wait its silence earned. */\n private nextAsk(op: LightningOp, now: number): number {\n return Math.max(this.invoiceAsk.at(op.paymentHash, 0), nextInvoiceAsk({\n createdAt: op.createdAt,\n expiresAt: op.expiresAt,\n watchedUntil: this.watched.get(op.paymentHash),\n closed: !!op.paymentId && !!this.events.requestClosed?.(op.paymentId),\n }, this.asked.get(op.paymentHash), now));\n }\n\n /** The next pass in `ms`, unless one is due sooner. It asks only what is due (`reconcile(true)`). */\n private schedule(ms: number) {\n if (this.stopped) return;\n const at = Date.now() + ms;\n if (this.timer && this.timerAt <= at) return;\n clearTimeout(this.timer);\n this.timerAt = at;\n this.timer = setTimeout(() => { this.timer = undefined; void this.reconcile(true); }, ms);\n }\n\n /** Changing the source is refused while a payment through it has not ended: only it can say how. */\n private async refusal(providerId: string, mode: WalletMode) {\n const open = (await this.list()).filter((op) => op.direction === \"out\" && !op.selfSettled && op.providerId === providerId && op.mode === mode && this.owns(op) && [\"sending\", \"pending\", \"unknown\"].includes(op.state));\n return open.length ? `A Lightning payment through this source has not ended yet (${open.length}). Wait for it before changing the source.` : undefined;\n }\n\n private cardField(): Pick<LightningOp, \"card\"> { return this.options.card === undefined ? {} : { card: this.options.card }; }\n\n /** A Mainnet source refuses an invoice on a test chain. The reverse (test mints use lnbc) is `quote`'s to refuse. */\n private checkNetwork(network: string) {\n if (this.mode === \"mainnet\" && network !== \"bitcoin\") throw new Error(`That invoice is for ${network}, a test network: pay it from a Testnet wallet`);\n }\n\n private async get(direction: LightningOp[\"direction\"], hash: string) { return wrap<LightningOp | undefined>((await store(STORES.settings, \"readonly\")).get(opKey(direction, hash))); }\n private async put(op: LightningOp) {\n this.writes++;\n // Before and after: a read started while this writes may or may not see it, so it is not kept.\n journalWritten();\n try { await transact([STORES.settings], (s) => { s[STORES.settings].put(op, opKey(op.direction, op.paymentHash)); }); }\n finally { journalWritten(); }\n }\n list(): Promise<LightningOp[]> { return readLightningJournal(); }\n\n /** Crash recovery: a spend journaled as `sending` never got its answer written, so its outcome is unknown. */\n async recover() {\n for (const op of await this.list()) if (op.direction === \"out\" && op.state === \"sending\" && this.owns(op)) await this.put({ ...op, state: \"unknown\", error: \"Interrupted. It is being checked; nothing is paid again.\" });\n this.schedule(0);\n }\n\n /** True when the recent list reads otherwise than before. */\n private async loadRecent(): Promise<boolean> {\n const was = this.recent, now = Date.now();\n const ops = (await this.list()).filter((op) => this.owns(op)).sort((a, b) => b.createdAt - a.createdAt).slice(0, RECENT);\n this.recentTurns = Math.min(Infinity, ...ops.map((op) => shownExpiredAt(op)).filter((at) => at > now));\n this.recent = ops.map((op) => {\n const { ref: _ref, note: _note, selfSettled: _self, ...view } = op;\n return shownExpiredAt(op) <= now ? { ...view, state: \"expired\" as const } : view;\n });\n return JSON.stringify(was) !== JSON.stringify(this.recent);\n }\n}\n\n/**\n * When an open invoice of ours that this engine asks about reads as expired, though no answer said so: past its expiry\n * and the grace a source's own \"expired\" gets. Its source may not answer for hours (a node that is off, an NWC relay\n * gone), and \"waiting for payment\" on an invoice nobody can pay any more is wrong. The journal keeps it open, and it is\n * still asked about (`invoiceAsk`), so a late \"paid\" counts. Infinity: shown as it is stored.\n */\nfunction shownExpiredAt(op: LightningOp): number {\n return op.direction === \"in\" && op.state === \"open\" && !op.selfSettled && op.expiresAt > 0 ? op.expiresAt + INVOICE_PACE.expiryGraceMs + 1 : Infinity;\n}\n","import { generateMnemonic, validateMnemonic } from \"@scure/bip39\";\nimport { wordlist } from \"@scure/bip39/wordlists/english.js\";\n\n/**\n * Recovery phrases (BIP 39, English) for providers whose wallet Ghostly makes: the form generates one for\n * a new wallet and checks one typed to restore. Small on purpose, so a form can use it without loading\n * the provider.\n */\nexport const newRecoveryPhrase = () => generateMnemonic(wordlist);\n/** A phrase as BIP 39 wants it, however it was typed or pasted. */\nexport const normalizePhrase = (text = \"\") => text.trim().toLowerCase().split(/\\s+/).join(\" \");\nexport const isRecoveryPhrase = (text: string) => validateMnemonic(normalizePhrase(text), wordlist);\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { decodeBolt11 } from \"@ghostly/core\";\nimport type { Payment, PaymentType, PrepareSendPaymentResponse } from \"@breeztech/breez-sdk-spark/web\";\nimport { breezDatabase, breezDatabaseName, forgetBreez, loadBreezSdk, openBreez, type BreezSdkModule, type BreezStorageName, type BreezWallet } from \"./breezSdk\";\nimport { isRecoveryPhrase, normalizePhrase } from \"./recoveryPhrase\";\nimport type { InvoiceStatus, LightningInvoice, LightningPayResult, LightningPaymentRef, LightningPaymentStatus, LightningProvider, LightningProviderDescriptor } from \"./lightning\";\nimport { isNothingSpentError, NothingSpentError, type ProviderNetwork, type ProviderPlatform } from \"./types\";\n\nexport const BREEZ_SOURCE = \"breez\";\n/**\n * Where the Breez source is offered: Mainnet (\"bitcoin\", with the person's Breez API key, which the form requires\n * there) and Breez and Lightspark's hosted regtest (no API key).\n */\nexport const BREEZ_NETWORKS: readonly ProviderNetwork[] = [\"bitcoin\", \"regtest\"];\n/** WebAssembly and HTTPS only: the page, the extension's offscreen document and Tauri's WebView all run it. */\nexport const BREEZ_PLATFORMS: readonly ProviderPlatform[] = [\"web\", \"extension\", \"desktop\"];\n\nconst INVOICE_EXPIRY_SECS = 3600;\n/** How long `payInvoice` waits for the payment to settle before answering `pending`. */\nconst COMPLETION_SECS = 30;\n/** A fee shown to the person is paid with the same prepared payment for this long, then prepared again. */\nconst QUOTE_MS = 60_000;\n/** Payments read to find one by its hash: newest first, bounded. */\nconst PAGE = 100, PAGES = 10;\n/** Without any record of a payment, it is called failed only this long after its invoice expired. */\nconst LOST_AFTER_MS = 3600_000;\n\nconst hex = (bytes: Uint8Array) => Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\nconst sats = (value: bigint | number) => { const n = Number(value); if (!Number.isSafeInteger(n) || n < 0) throw new Error(\"Breez returned an invalid amount\"); return n; };\nconst message = (error: unknown) => (error instanceof Error ? error.message : typeof error === \"string\" ? error : \"Breez refused the payment\");\n\nexport { breezDatabase, breezDatabaseName };\n\n/**\n * The idempotency key of one attempt at paying one invoice: asking the SDK twice with it pays once.\n * A new attempt (after one that failed) gets a new key, or the SDK would only hand back the failure.\n */\nexport function idempotencyKey(paymentHash: string, attempt: number): string {\n const b = sha256(new TextEncoder().encode(`ghostly-breez-pay:${paymentHash}:${attempt}`)).slice(0, 16);\n b[6] = (b[6] & 0x0f) | 0x40; b[8] = (b[8] & 0x3f) | 0x80;\n const h = hex(b);\n return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;\n}\n\n/** The payment hash a Breez payment is about, when it is one (Lightning, or a Spark HTLC). */\nfunction hashOf(payment: Payment): string | undefined {\n const details = payment.details;\n if (details?.type === \"lightning\") return details.htlcDetails.paymentHash;\n if (details?.type === \"spark\") return details.htlcDetails?.paymentHash;\n return undefined;\n}\nfunction preimageOf(payment: Payment): string | undefined {\n const details = payment.details;\n return details?.type === \"lightning\" ? details.htlcDetails.preimage : details?.type === \"spark\" ? details.htlcDetails?.preimage : undefined;\n}\n\n/**\n * Lightning through the Breez SDK, nodeless: a self-custodial wallet on Spark whose seed Ghostly\n * generated (or the person restored) and keeps sealed. Invoices are received and paid through Breez's\n * and Lightspark's Spark service providers; the sats are the seed's.\n *\n * Nothing is reported by itself: the engine polls `invoiceStatus` and `paymentStatus`, which find a\n * payment by its hash in the wallet's history.\n */\nexport class BreezLightning implements LightningProvider {\n readonly capabilities = { receive: true, send: true, balance: true, lookup: true };\n /** The prepared payment behind a fee just shown: `payInvoice` pays exactly that one while it is fresh. */\n private readonly quotes = new Map<string, { prepared: PrepareSendPaymentResponse; at: number }>();\n private closed = false;\n\n /** `storage`: the Breez database this card opened (`breezDatabase`). */\n private constructor(private readonly wallet: BreezWallet, private readonly network: ProviderNetwork, private readonly release: () => Promise<void>, readonly storage: string) {}\n\n static async connect(params: { network: ProviderNetwork; mnemonic: string; apiKey?: string }, sdk: () => Promise<BreezSdkModule> = loadBreezSdk, storage: BreezStorageName = breezDatabase): Promise<BreezLightning> {\n const opened = await openBreez(params, sdk, storage);\n return new BreezLightning(opened.wallet, params.network, opened.release, opened.storage);\n }\n\n async info() {\n const { balanceSats } = await this.wallet.getInfo({ ensureSynced: false });\n return { network: this.network, balance: sats(balanceSats) };\n }\n\n async createInvoice(amount: number, memo?: string): Promise<LightningInvoice> {\n const { paymentRequest } = await this.wallet.receivePayment({ paymentMethod: { type: \"bolt11Invoice\", description: (memo ?? \"\").slice(0, 100), amountSats: amount, expirySecs: INVOICE_EXPIRY_SECS } });\n const decoded = decodeBolt11(paymentRequest);\n if (!decoded?.paymentHash || decoded.amountSat !== amount) throw new Error(\"Breez returned an invoice that does not match the request\");\n return { invoice: decoded.invoice, paymentHash: decoded.paymentHash, amount, expiresAt: decoded.expiresAt * 1000 };\n }\n\n async invoiceStatus(invoice: LightningInvoice): Promise<InvoiceStatus> {\n const payment = await this.find(\"receive\", invoice.paymentHash, invoice.invoice);\n if (payment?.status === \"completed\") return { state: \"paid\", amount: sats(payment.amount) };\n // A payment on its way in (claim under way) is still open, even past the invoice's expiry.\n if (payment?.status === \"pending\") return { state: \"open\" };\n return { state: invoice.expiresAt < Date.now() ? \"expired\" : \"open\" };\n }\n\n /** Prepares the payment (nothing is sent) and keeps it for `payInvoice`: its fee is the one shown. */\n async estimateFee(invoice: string, amount: number) {\n const prepared = await this.prepare(invoice, amount);\n this.quotes.set(decodeBolt11(invoice)?.invoice ?? invoice, { prepared, at: Date.now() });\n return this.feeOf(prepared);\n }\n\n async payInvoice(invoice: string, maxFee: number): Promise<LightningPayResult> {\n const decoded = decodeBolt11(invoice);\n if (!decoded?.paymentHash || decoded.amountSat === null) throw new NothingSpentError(\"That is not an invoice Breez can pay\");\n const hash = decoded.paymentHash, amount = decoded.amountSat, key = decoded.invoice;\n let prepared: PrepareSendPaymentResponse, attempt: number;\n // Everything up to `sendPayment` only reads and prepares: when it fails, nothing left the wallet.\n try {\n if (this.closed) throw new Error(\"The Breez wallet is closed\");\n // Already paid, or on its way, from this wallet: answer that, never pay it again.\n const previous = await this.history(\"send\", hash, decoded.invoice, decoded.createdAt);\n const live = previous.find((p) => p.status !== \"failed\");\n if (live) return this.result(live);\n attempt = previous.length;\n const quote = this.quotes.get(key);\n this.quotes.delete(key);\n prepared = quote && Date.now() - quote.at < QUOTE_MS ? quote.prepared : await this.prepare(decoded.invoice, amount);\n const fee = this.feeOf(prepared);\n if (fee > maxFee) throw new Error(`The Lightning fee (${fee} sats) is above your limit (${maxFee})`);\n const { balanceSats } = await this.wallet.getInfo({ ensureSynced: false });\n if (sats(balanceSats) < amount + fee) throw new Error(`Not enough sats in the Breez wallet (${sats(balanceSats)}; ${amount + fee} needed)`);\n } catch (error) {\n throw isNothingSpentError(error) ? error : new NothingSpentError(message(error));\n }\n // From here on the sats may be gone: any throw is an unknown outcome, reconciled by the payment hash.\n const { payment } = await this.wallet.sendPayment({ prepareResponse: prepared, options: { type: \"bolt11Invoice\", preferSpark: false, completionTimeoutSecs: COMPLETION_SECS }, idempotencyKey: idempotencyKey(hash, attempt) });\n return this.result(payment);\n }\n\n async paymentStatus(ref: LightningPaymentRef): Promise<LightningPaymentStatus> {\n const decoded = decodeBolt11(ref.invoice);\n // By the hash first: of every attempt at this invoice, the one that went furthest answers.\n let payment = await this.find(\"send\", ref.paymentHash, ref.invoice, decoded?.createdAt);\n if (!payment && ref.ref) {\n const byId = (await this.wallet.getPayment({ paymentId: ref.ref }).catch(() => undefined))?.payment;\n if (byId && hashOf(byId) === ref.paymentHash) payment = byId;\n }\n if (!payment) {\n // Not in the history: ask the operators, then look again.\n await this.wallet.syncWallet({});\n payment = await this.find(\"send\", ref.paymentHash, ref.invoice, decoded?.createdAt);\n }\n if (!payment) {\n // No record at all, long after the invoice could be paid: it never left. Until then, it may still show up.\n const expired = decoded ? decoded.expiresAt * 1000 + LOST_AFTER_MS < Date.now() : false;\n return { state: expired ? \"failed\" : \"pending\" };\n }\n const state = payment.status === \"completed\" ? \"paid\" : payment.status === \"failed\" ? \"failed\" : \"pending\";\n return { state, fee: state === \"paid\" ? sats(payment.fees) : undefined, preimage: preimageOf(payment) };\n }\n\n async close() {\n if (this.closed) return;\n this.closed = true; this.quotes.clear();\n await this.release();\n }\n\n /** The card is removed: closed, and its Breez databases deleted unless the Spark wallet of this phrase has them open. */\n async forget() {\n await this.close();\n await forgetBreez(this.storage);\n }\n\n private async prepare(invoice: string, amount: number) {\n const prepared = await this.wallet.prepareSendPayment({ paymentRequest: { type: \"input\", input: invoice } });\n const method = prepared.paymentMethod;\n // What will be paid must be this invoice, for this amount, over Lightning.\n if (method.type !== \"bolt11Invoice\") throw new Error(\"Breez would not pay this as a Lightning invoice\");\n if (method.invoiceDetails.paymentHash !== decodeBolt11(invoice)?.paymentHash || sats(prepared.amount) !== amount) throw new Error(\"Breez prepared a payment that does not match the invoice\");\n return prepared;\n }\n\n private feeOf(prepared: PrepareSendPaymentResponse) {\n if (prepared.paymentMethod.type !== \"bolt11Invoice\") throw new Error(\"Breez would not pay this as a Lightning invoice\");\n return sats(prepared.paymentMethod.lightningFeeSats);\n }\n\n /** `failed` is never an answer here: a payment the SDK gave up on is pending until `paymentStatus` says so. */\n private result(payment: Payment): LightningPayResult {\n if (payment.status === \"completed\") return { state: \"paid\", fee: sats(payment.fees), preimage: preimageOf(payment), ref: payment.id };\n return { state: \"pending\", ref: payment.id };\n }\n\n private async find(type: PaymentType, hash: string, invoice: string, createdAt?: number) {\n const found = await this.history(type, hash, invoice, createdAt);\n return found.find((p) => p.status === \"completed\") ?? found.find((p) => p.status === \"pending\") ?? found[0];\n }\n\n /** This wallet's payments of this hash, newest first. Only payments since the invoice was made are read. */\n private async history(type: PaymentType, hash: string, invoice: string, createdAt = decodeBolt11(invoice)?.createdAt): Promise<Payment[]> {\n const found: Payment[] = [];\n for (let page = 0; page < PAGES; page++) {\n const { payments } = await this.wallet.listPayments({ typeFilter: [type], fromTimestamp: createdAt ? createdAt - 600 : undefined, offset: page * PAGE, limit: PAGE, sortAscending: false });\n found.push(...payments.filter((p) => hashOf(p) === hash));\n if (payments.length < PAGE) break;\n }\n return found;\n }\n}\n\n/** The descriptor, with the SDK it loads (tests hand it a fake). */\nexport const breezDescriptor = (sdk: () => Promise<BreezSdkModule> = loadBreezSdk): LightningProviderDescriptor => ({\n id: BREEZ_SOURCE,\n label: \"Breez (Spark)\",\n kind: \"lightning\",\n description: \"A self-custodial Lightning wallet on Spark, through the Breez SDK. Its recovery phrase is sealed on this device; you hold the sats.\",\n networks: BREEZ_NETWORKS,\n platforms: BREEZ_PLATFORMS,\n fields: [\n { name: \"mnemonic\", label: \"Recovery phrase\", kind: \"secret\", placeholder: \"twelve words…\", help: \"Made by Ghostly for a new wallet, or yours to restore one.\" },\n { name: \"apiKey\", label: \"Breez API key\", kind: \"secret\", optional: true, help: \"Required on Mainnet (free, from Breez). Not needed in Testnet (regtest).\" },\n ],\n experimental: true,\n validate({ secrets }, mode) {\n if (!isRecoveryPhrase(secrets.mnemonic ?? \"\")) throw new Error(\"That is not a valid recovery phrase\");\n if (mode === \"mainnet\" && !secrets.apiKey?.trim()) throw new Error(\"Breez needs an API key on Mainnet\");\n },\n async create({ secrets }, host) {\n const network: ProviderNetwork = host.mode === \"mainnet\" ? \"bitcoin\" : \"regtest\";\n return BreezLightning.connect({ network, mnemonic: normalizePhrase(secrets.mnemonic), apiKey: secrets.apiKey?.trim() || undefined }, sdk);\n },\n});\n\nexport const breez = breezDescriptor();\n","import { dropLoneJoiners, hasVisible, stripHidden } from \"@ghostly/core\";\nimport { STORES, transact } from \"../../../shared/idb\";\nimport type { WalletMode } from \"../../../shared/mints\";\nimport { CASHU_MINT_SOURCE } from \"./cashuMint\";\nimport type { LightningProviderDescriptor } from \"./lightning\";\nimport { LightningService, readLightningJournal, type LightningEvents, type LightningOp, type LightningView } from \"./lightningService\";\nimport { sourceKey } from \"./sources\";\nimport { awayFrom } from \"../away\";\nimport { breezDatabaseInUse } from \"./breezDatabases\";\nimport { BreezLightning } from \"./breez\";\nimport { nwc, nwcWalletName } from \"./nwcProvider\";\nimport { normalizePhrase } from \"./recoveryPhrase\";\nimport type { ProviderHost } from \"./types\";\n\n/**\n * One Lightning card of a network, as stored under `lightningCards-<network>`. Its source (and the source's sealed\n * secrets) is stored apart, under `lightningSource-<network>-<key>`: the card that took over a network's one source\n * (`LEGACY_CARD`) has no key and keeps reading `lightningSource-<network>`, where that source always was.\n */\nexport interface StoredLightningCard {\n id: string;\n name: string;\n providerId: string;\n /** Where its source is stored. Absent: the network's one key (the card made from it). */\n key?: string;\n createdAt: number;\n}\ninterface StoredLightningCards {\n cards: StoredLightningCard[];\n /** The card a chat request's invoice and Receive come from, unless another is picked. */\n receive: string;\n}\n\n/** A Lightning card as the pages see it: its source's view, its name, and whether it is the one receiving. */\nexport interface LightningCardView extends LightningView {\n card: string;\n name: string;\n /** The network's default for receiving: chat requests and Receive use it unless another card is picked. */\n receive: boolean;\n /**\n * `spark`: this card is the network's Spark wallet itself (a Breez card that opened the Spark wallet's own Breez\n * database: same phrase, same profile), so its balance is that wallet's, whatever each of the two last read.\n */\n sameWalletAs?: \"spark\";\n}\n\n/** The card of Lightning through the Cashu mints: at most one per network, shown while the network has mints. */\nexport const CASHU_CARD = \"cashu\";\n/** The card made from the one source a network had before it could have several. */\nexport const LEGACY_CARD = \"main\";\nexport const cardsKey = (network: WalletMode) => `lightningCards-${network}`;\nconst NAME_MAX = 32;\n\n/** Short source names for a card's default name (\"Alby Hub (NWC)\"): the form's label otherwise. */\nconst SHORT: Record<string, string> = { nwc: \"NWC\", lnd: \"LND\", \"core-lightning\": \"Core Lightning\", breez: \"Breez\", [CASHU_MINT_SOURCE]: \"Cashu\", fedimint: \"Fedimint\", webln: \"WebLN\" };\n\n/**\n * The cards of a network, made the first time this version opens it from what an older one kept: the network's one\n * source (`lightningSource-<network>`) becomes a card reading that same key, so no secret moves and nothing asks\n * again; with no source saved, the network used the Cashu mints, and that is its card. Either becomes the default for\n * receiving. Read and written in one transaction; a second run finds the cards and changes nothing. Never reads a\n * secret: the source's record names its provider next to its sealed secrets.\n */\nexport async function loadLightningCards(network: WalletMode, label: (providerId: string) => string, now = Date.now()): Promise<StoredLightningCards> {\n let result: StoredLightningCards | undefined;\n await transact([STORES.settings], (stores) => {\n const settings = stores[STORES.settings];\n const saved = settings.get(cardsKey(network));\n saved.onsuccess = () => {\n const found = saved.result as StoredLightningCards | undefined;\n if (found?.cards?.length) { result = found; return; }\n const legacy = settings.get(sourceKey(\"lightning\", network));\n legacy.onsuccess = () => {\n const providerId = (legacy.result as { providerId?: unknown } | undefined)?.providerId;\n const card: StoredLightningCard = typeof providerId === \"string\" && providerId && providerId !== CASHU_MINT_SOURCE\n ? { id: LEGACY_CARD, name: shortName(providerId, label), providerId, createdAt: now }\n : cashuCard(now);\n result = { cards: [card], receive: card.id };\n settings.put(result, cardsKey(network));\n };\n };\n });\n return result!;\n}\n\nconst cashuCard = (now: number): StoredLightningCard => ({ id: CASHU_CARD, name: SHORT[CASHU_MINT_SOURCE], providerId: CASHU_MINT_SOURCE, key: CASHU_CARD, createdAt: now });\nconst shortName = (providerId: string, label: (providerId: string) => string) => SHORT[providerId] ?? label(providerId);\n\n/** At most this many characters of the wallet's own name go into a new card's name. */\nconst ALIAS_IN_NAME = 20;\n\n/**\n * A new card's name: the wallet's own name, then its source's short name (\"Alby Hub (NWC)\"), or the short name alone.\n * An NWC wallet's name leaves out \"via <relay host>\" (the card's subtitle shows it). A longer name is cut where a word\n * ends, with \"…\", never in the middle of a word.\n */\nexport function defaultCardName(providerId: string, alias: string | undefined, short: string): string {\n const own = cleanName(alias && providerId === nwc.id ? nwcWalletName(alias) : alias ?? \"\");\n return own ? `${cutAtWord(own, ALIAS_IN_NAME)} (${short})` : short;\n}\n\n/**\n * A card's name as shown: no invisible or direction-changing character (one from the wallet's service could make a\n * name read like another card's, or reorder the source's name after it), white space collapsed; \"\" with nothing visible.\n */\nfunction cleanName(name: string): string {\n const clean = dropLoneJoiners(stripHidden(name.replace(/\\s+/g, \" \"))).replace(/\\s+/g, \" \").trim();\n return hasVisible(clean) ? clean : \"\";\n}\n\n/** What two names that read alike share: a name stored before `cleanName` may still hold what it drops. */\nconst nameKey = (name: string) => cleanName(name).toLowerCase();\n\n/** `text` in at most `max` UTF-16 units (the unit `rename` counts), cut after a whole word with \"…\" when longer. */\nfunction cutAtWord(text: string, max: number): string {\n if (text.length <= max) return text;\n let head = text.slice(0, max - 1);\n if (/[\\uD800-\\uDBFF]$/.test(head)) head = head.slice(0, -1);\n // A head that ends right before a space is whole words already; otherwise drop the word it cut, unless it is the only one.\n const space = text[head.length] === \" \" ? head.length : head.lastIndexOf(\" \");\n const kept = (space > 0 ? head.slice(0, space) : head).replace(/[\\s,;:·–—-]+$/u, \"\");\n return `${kept || head}…`;\n}\n\nexport interface LightningCardsHost {\n descriptors: () => readonly LightningProviderDescriptor[];\n host: () => Omit<ProviderHost, \"mode\" | \"signal\">;\n events: LightningEvents;\n /** Whether the network has Cashu mints: the Cashu card shows only then. */\n hasMints: () => boolean;\n fetch?: typeof fetch;\n /** The Breez database the network's Spark wallet has open, when it is open (`SparkAdapter.storage`). */\n sparkStorage?: () => string | undefined;\n}\n\n/**\n * The Lightning cards of one network, each with its own source, balance and journal: \"Alby Hub (NWC)\", \"Home LND\",\n * the Cashu mints. A payment goes through the card picked for it; a chat request's invoice and Receive come from the\n * default for receiving unless another is picked. Adding, removing and renaming are serialized.\n */\nexport class LightningCards {\n private stored: StoredLightningCards = { cards: [], receive: CASHU_CARD };\n private readonly services = new Map<string, LightningService>();\n private queue: Promise<unknown> = Promise.resolve();\n /** A card being added: a creation that takes too long cuts its connection short. */\n private adding?: LightningService;\n private stopped = false;\n\n constructor(readonly network: WalletMode, private readonly options: LightningCardsHost) {}\n\n private serial<T>(run: () => Promise<T>): Promise<T> { const next = this.queue.then(run, run); this.queue = next.catch(() => {}); return next; }\n private label = (providerId: string) => this.options.descriptors().find((d) => d.id === providerId)?.label ?? providerId;\n\n private make(card: StoredLightningCard): LightningService {\n return new LightningService(this.network, this.options.descriptors, this.options.host, this.options.events,\n card.providerId === CASHU_MINT_SOURCE ? CASHU_MINT_SOURCE : undefined,\n { fetch: this.options.fetch, card: card.id, key: card.key, owns: (op) => this.owner(op) === card.id });\n }\n\n private starting?: Promise<void>;\n /** Opens the cards (once: a use before the engine started opens them too). */\n start(): Promise<void> { return this.starting ??= this.open(); }\n private async open() {\n this.stored = await loadLightningCards(this.network, this.label);\n for (const card of this.stored.cards) {\n const service = this.make(card);\n this.services.set(card.id, service);\n await service.start();\n }\n }\n\n /**\n * The card an operation went through. One journaled before cards: the Cashu card's when the mints made it, else the\n * card made from the network's one source (none, when that source was replaced before cards: nobody shows it).\n */\n owner(op: LightningOp): string {\n if (op.card !== undefined) return op.card;\n return op.providerId === CASHU_MINT_SOURCE ? CASHU_CARD : LEGACY_CARD;\n }\n\n /** The cards a person sees: the Cashu card only while the network has mints. In the order they were added. */\n private shown(): StoredLightningCard[] { return this.stored.cards.filter((c) => c.id !== CASHU_CARD || this.options.hasMints()); }\n\n /**\n * The default for receiving, or the first card shown here when that one is not (the Cashu card of a network with no\n * mints): a card at home on another device cannot receive here.\n */\n get receivingId(): string {\n const shown = this.shown();\n return shown.find((c) => c.id === this.stored.receive)?.id ?? shown.find((c) => this.isHere(c.id))?.id ?? shown[0]?.id ?? this.stored.receive;\n }\n get receiving(): LightningService { return this.services.get(this.receivingId) ?? [...this.services.values()][0]; }\n\n /** A card by its id; without one, the default for receiving. Throws when it is gone. */\n card(id?: string): LightningService {\n if (id === undefined) { if (!this.services.size) throw new Error(\"Lightning is not open yet\"); return this.receiving; }\n const service = this.services.get(id);\n if (!service) throw new Error(\"That Lightning card is gone: pick another\");\n return service;\n }\n has(id: string) { return this.services.has(id); }\n all(): LightningService[] { return [...this.services.values()]; }\n\n views(): LightningCardView[] {\n const receive = this.receivingId;\n return this.shown().filter((card) => this.services.has(card.id)).map((card) => this.cardView(card, card.id === receive));\n }\n /** The default for receiving's view: what a caller from before cards reads as the network's Lightning. None before start. */\n get view(): LightningCardView | undefined {\n const card = this.stored.cards.find((c) => c.id === this.receivingId) ?? this.stored.cards[0];\n return card && this.services.has(card.id) ? this.cardView(card, true) : undefined;\n }\n private cardView(card: StoredLightningCard, receive: boolean): LightningCardView {\n const service = this.services.get(card.id)!;\n return { ...service.view, card: card.id, name: card.name, receive, ...(this.isSpark(service) ? { sameWalletAs: \"spark\" as const } : {}) };\n }\n /** The card opened the Breez database the network's Spark wallet has open: one wallet behind both cards. */\n private isSpark(service: LightningService): boolean {\n const spark = this.options.sparkStorage?.(), active = service.sources.active;\n return !!spark && active instanceof BreezLightning && active.storage === spark;\n }\n\n /** The card holding this quote (each card quotes through its own source). */\n withQuote(quote: string): LightningService | undefined { return this.all().find((s) => s.hasQuote(quote)); }\n\n /**\n * Adds a card with `providerId` and the values of its form: connected and checked first, like any source; only then\n * saved. Nothing is saved when it fails. The same wallet twice (same source, same settings) is refused. A card of the\n * person's own takes receiving over from the mints' card (what a source chosen before cards did); next to another\n * card of their own, the default stays.\n */\n add(providerId: string, values: Record<string, string>): Promise<string> {\n return this.serial(async () => {\n if (providerId === CASHU_MINT_SOURCE) {\n if (this.services.has(CASHU_CARD)) throw new Error(\"Lightning through your Cashu mints is already a card\");\n if (!this.options.hasMints()) throw new Error(\"Create a Cashu wallet first: this card pays and receives through its mints\");\n const card = cashuCard(Date.now());\n const service = this.make(card);\n await service.start();\n await this.save({ ...this.stored, cards: [...this.stored.cards, card] }, card.id);\n this.services.set(card.id, service);\n void service.ensureReady();\n return card.id;\n }\n const id = `ln-${[...crypto.getRandomValues(new Uint8Array(4))].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\")}`;\n const card: StoredLightningCard = { id, name: \"\", providerId, key: id, createdAt: Date.now() };\n const service = this.make(card);\n const same = await this.findSame(providerId, values);\n if (same) throw new Error(`That wallet is already your card “${this.stored.cards.find((c) => c.id === same)?.name}”`);\n await service.start();\n this.adding = service;\n try { await service.sources.set(providerId, values); }\n catch (error) { await service.stop(); throw error; }\n finally { this.adding = undefined; }\n card.name = this.freeName(defaultCardName(providerId, service.view.alias, shortName(providerId, this.label)));\n const receive = this.receivingId === CASHU_CARD ? id : this.stored.receive;\n // The mints' card of a network with no mints is not shown and holds nothing: a card of the person's own takes its\n // place, as the one source did before cards (a Cashu wallet made later does not bring it back).\n const hidden = this.services.has(CASHU_CARD) && !this.options.hasMints();\n const cards = [...this.stored.cards.filter((c) => !hidden || c.id !== CASHU_CARD), card];\n try { await this.save({ cards, receive }, card.id); }\n catch (error) { await service.sources.forget().catch(() => {}); await service.stop(); throw error; }\n this.services.set(id, service);\n if (hidden) { const gone = this.services.get(CASHU_CARD)!; this.services.delete(CASHU_CARD); await gone.stop(); }\n return id;\n });\n }\n\n /** The card that is already this wallet (the same source with the same settings), if one is. Throws what to fix in the form. */\n async findSame(providerId: string, values: Record<string, string>): Promise<string | undefined> {\n const { settings } = this.receiving.sources.settingsOf(providerId, values);\n for (const [id, service] of this.services) if (await service.sources.holds(providerId, settings)) return id;\n return undefined;\n }\n\n /** A name no other card of the network has: \"LND\", then \"LND 2\". */\n private freeName(name: string): string {\n const taken = new Set(this.stored.cards.map((c) => nameKey(c.name)));\n if (!taken.has(nameKey(name))) return name;\n for (let n = 2; ; n++) if (!taken.has(nameKey(`${name} ${n}`))) return `${name} ${n}`;\n }\n\n /**\n * Removes a card: its source and sealed secrets go (refused while a payment through it has not ended). The default\n * for receiving moves to the first card of the person's own left on this device (one at home on another device\n * cannot receive here), else the mints' card. A network left with no card gets the Cashu card back, as before cards.\n */\n remove(id: string): Promise<void> {\n return this.serial(async () => {\n const service = this.services.get(id);\n if (!service) throw new Error(\"That Lightning card is gone\");\n await service.sources.forget();\n await service.stop();\n this.services.delete(id);\n let cards = this.stored.cards.filter((c) => c.id !== id);\n let added: LightningService | undefined;\n if (!cards.length) {\n const card = cashuCard(Date.now());\n cards = [card];\n added = this.make(card);\n this.services.set(card.id, added);\n await added.start();\n }\n const shown = cards.filter((c) => c.id !== CASHU_CARD || this.options.hasMints());\n const next = shown.find((c) => c.id !== CASHU_CARD && this.isHere(c.id)) ?? shown.find((c) => c.id === CASHU_CARD) ?? shown[0] ?? cards[0];\n const receive = this.stored.receive === id || !cards.some((c) => c.id === this.stored.receive) ? next.id : this.stored.receive;\n await this.save({ cards, receive });\n if (added) void added.ensureReady();\n });\n }\n\n /** Makes a card the network's default for receiving. */\n setReceive(id: string): Promise<void> {\n return this.serial(async () => {\n if (!this.shown().some((c) => c.id === id)) throw new Error(\"That Lightning card is gone\");\n await this.save({ ...this.stored, receive: id });\n });\n }\n\n /** Renames a card: 1 to 32 characters, unique on its network. */\n rename(id: string, name: string): Promise<void> {\n return this.serial(async () => {\n const clean = cleanName(name);\n if (!clean) throw new Error(\"Enter a name\");\n if (clean.length > NAME_MAX) throw new Error(`At most ${NAME_MAX} characters`);\n if (!this.services.has(id)) throw new Error(\"That Lightning card is gone\");\n if (this.stored.cards.some((c) => c.id !== id && nameKey(c.name) === nameKey(clean))) throw new Error(\"Another card has that name\");\n await this.save({ ...this.stored, cards: this.stored.cards.map((c) => (c.id === id ? { ...c, name: clean } : c)) });\n });\n }\n\n private async save(next: StoredLightningCards, receiveIfNone?: string) {\n const shown = next.cards.filter((c) => c.id !== CASHU_CARD || this.options.hasMints());\n // A first card shown takes the receiving over from one that is not (the Cashu card of a network with no mints).\n const receive = receiveIfNone && !shown.some((c) => c.id === next.receive) ? receiveIfNone : next.receive;\n const stored = { cards: next.cards, receive };\n await transact([STORES.settings], (s) => { s[STORES.settings].put(stored, cardsKey(this.network)); });\n this.stored = stored;\n this.options.events.changed();\n }\n\n // -- the Cashu wallet reports what its mints settled -------------------------------\n\n private async ownerOf(direction: LightningOp[\"direction\"], invoice: string): Promise<LightningService> {\n const op = (await readLightningJournal()).find((o) => o.direction === direction && o.invoice === invoice && o.mode === this.network);\n const owner = op ? this.owner(op) : CASHU_CARD;\n return (owner && this.services.get(owner)) || this.services.get(CASHU_CARD) || this.receiving;\n }\n async reportInvoicePaid(invoice: string, context: { paymentId?: string; mint?: string } = {}) { await (await this.ownerOf(\"in\", invoice)).reportInvoicePaid(invoice, context); }\n async reportPaymentResolved(invoice: string, paid: boolean, context: { paymentId?: string; mint?: string } = {}) { await (await this.ownerOf(\"out\", invoice)).reportPaymentResolved(invoice, paid, context); }\n\n // -- Lightning addresses: resolved by one card, and the invoice asked by that same one --------\n\n resolveDestination(text: string) { return this.receiving.resolveDestination(text); }\n destinationInvoice(id: string, amountSat: number, comment?: string) { return (this.all().find((s) => s.hasDestination(id)) ?? this.receiving).destinationInvoice(id, amountSat, comment); }\n\n // -- every card at once -----------------------------------------------------------\n\n list() { return readLightningJournal(); }\n /**\n * What a handoff needs to know of the cards (WISP 06 § Wallets), from their sealed settings: the LND cards that pin a\n * certificate, and each Breez card's database on this device, by wallet id.\n */\n async handoffFacts(): Promise<{ pinned: string[]; breez: Map<string, string> }> {\n const pinned: string[] = [], breez = new Map<string, string>();\n for (const [id, service] of this.services) {\n const wallet = `lightning:${this.network}:${id}`, providerId = service.view.providerId;\n if (providerId === \"lnd\" && await service.sources.secret(\"certificate\")) pinned.push(wallet);\n if (providerId === \"breez\") {\n const mnemonic = await service.sources.secret(\"mnemonic\");\n if (mnemonic) breez.set(wallet, await breezDatabaseInUse(this.network === \"mainnet\" ? \"bitcoin\" : \"regtest\", normalizePhrase(mnemonic)));\n }\n }\n return { pinned, breez };\n }\n\n /** The cards whose source is opened on this device: not one at home on another device (WISP 06 § Wallets that stay home). */\n private here(): LightningService[] { return [...this.services].filter(([id]) => this.isHere(id)).map(([, s]) => s); }\n private isHere(id: string): boolean { return awayFrom(`lightning:${this.network}:${id}`) === undefined; }\n async reconcile() { await Promise.all(this.here().map((s) => s.reconcile())); }\n /** The screen shows this invoice of ours: the card that made it asks about it at the fast pace a while longer. */\n async watch(invoice: string): Promise<boolean> { return (await Promise.all(this.here().map((s) => s.watch(invoice)))).some(Boolean); }\n /** A payer says it paid this invoice of ours: the card that made it asks its source about it now, and about nothing else. */\n async check(invoice: string): Promise<boolean> { return (await Promise.all(this.here().map((s) => s.check(invoice)))).some(Boolean); }\n async recover() { for (const s of this.here()) await s.recover(); }\n async ensureReady() { await Promise.all(this.here().map((s) => s.ensureReady())); }\n refreshOffered() { for (const s of this.all()) s.refreshOffered(); }\n wake() { for (const s of this.all()) s.sources.wake(); }\n cutShort() { this.adding?.sources.cutShort(); }\n resume() { this.adding?.sources.resume(); }\n async stop() { this.stopped = true; for (const s of this.all()) await s.stop(); }\n get isStopped() { return this.stopped; }\n}\n","import type { IdentityProofProvider } from \"./contract\";\n\ntype Registry = typeof import(\"./registry\");\n\n/**\n * The identity proof providers, loaded on first need and not with the app: they and their libraries (OpenPGP, the\n * Bitcoin signer, the DID, AT Protocol and OpenID Connect checks) are a large part of the code, and the first screen\n * draws none of it. The engine loads them with the profile's proofs; the UI once it draws something about identities.\n */\nlet registry: Registry | undefined;\nlet loading: Promise<Registry> | undefined;\nconst listeners = new Set<() => void>();\n\nexport function loadIdentityProviders(): Promise<Registry> {\n return loading ??= import(\"./registry\").then(m => {\n registry = m;\n for (const listener of listeners) listener();\n return m;\n }, error => { loading = undefined; throw error; });\n}\n\n/** Whether they are loaded: before, `loadedIdentityProviders` is empty. */\nexport const identityProvidersLoaded = (): boolean => !!registry;\n\n/** The providers (built in, from plugins, the test ones when asked for), once loaded; none before. */\nexport const loadedIdentityProviders = (): readonly IdentityProofProvider[] => registry?.identityProviders() ?? [];\n\n/** Whether `provider` is built into Ghostly (its words are in the app's locales), not a plugin's or a test one. */\nexport const builtInIdentityProvider = (provider: IdentityProofProvider): boolean => !!registry?.IDENTITY_PROVIDERS.includes(provider);\n\n/** Called once they are loaded. Returns the unsubscribe. */\nexport function onIdentityProvidersLoaded(listener: () => void): () => void {\n listeners.add(listener);\n return () => { listeners.delete(listener); };\n}\n","import {\n budgetRetryMs, emptyIdentityLedger, fromBase64Url, isDiscoveryBudgetError, identityRevocationValue, identityStatement, IdentityCheckUnavailable, IdentityExchange, IDENTITY_CHALLENGE_WINDOW, IDENTITY_MAX_VALIDITY, IDENTITY_REVOCATION_LABEL, isIdentityBinding, newIdentityBinding,\n identityRefusal, receivedIdentityStatus, revokesIdentity, toBase64Url,\n boundIdentityDisplay, type IdentityBinding, type IdentityLedger, type IdentityScope, type ReceivedIdentity, type IdentityStatement, type LocalIdentityProof, type SharedIdentity, type VerifiedIdentity,\n} from \"@ghostly/core\";\nimport { STORES, store, transact, wrap } from \"../shared/idb\";\nimport { openSecret, sealSecret, whenDataKeyDropped, type SealedSecret } from \"./dataKey\";\nimport type { IdentityFetch, IdentityProofProvider } from \"../proofs/contract\";\nimport { loadedIdentityProviders, loadIdentityProviders } from \"../proofs/load\";\nimport { boundedIdentityFetch, verifyIdentity } from \"../proofs/verify\";\nimport type { IdentityProofView, LinkIdentitiesView, PublicProfileView } from \"../shared/types\";\n\n/** A proof key's seed, sealed like the wallet seeds (`dataKey.ts`). It never leaves the profile. */\nexport type SealedProofKey = SealedSecret;\n/** Where a proof key's seed belongs: by proof id, so it still opens once the proof moved to the revocations. */\nconst proofKeyAt = (id: string) => ({ store: STORES.settings, key: id, field: \"identityProof.seed\" });\n\n/** A proof of this profile, as stored. */\nexport interface StoredIdentityProof {\n binding: IdentityBinding;\n evidence: unknown;\n seed: SealedProofKey;\n verified: VerifiedIdentity;\n createdAt: number;\n /** Shared in a chat at least once: removing it then revokes it, even once that chat (and its ledger) is deleted. */\n shared?: true;\n}\n\n/** A removed proof whose revocation is republished, under its proof key, until the proof would have expired. */\ninterface Revocation { id: string; key: string; seed: SealedProofKey; revokedAt: number; expiresAt: number }\n\n/** What the engine gives the identity module about a chat. */\nexport interface IdentityLinkHost {\n /** Paired chats only; undefined for others. */\n ledger(linkId: string): IdentityLedger | undefined;\n updateLedger(linkId: string, change: (ledger: IdentityLedger) => IdentityLedger): Promise<IdentityLedger>;\n /** The authenticated channel, when both sides offer identity proofs and it is open. */\n channel(linkId: string): { scope(): IdentityScope; send(frame: object): void } | undefined;\n /** Both participation keys of the chat, for the status of what the contact shared. */\n keys(linkId: string): { mine?: string; theirs?: string };\n linkIds(): string[];\n online(): boolean;\n /** How a proof is read from the addresses it names. Default: `fetch`. */\n fetcher?: typeof fetch;\n /** How the profile's own Pkarr relays are read for a did:dht (`boundedIdentityFetch`). Default: `fetcher`. */\n relayFetcher?: typeof fetch;\n /** Settings → Hide my IP from contacts: a contact's proof is then checked only on hosts this app names (`fixedIdentityHosts`). */\n relayOnly?(): boolean;\n emit(): void;\n /** One chat's view is to be built again: a contact's proof it shows expired, or its re-check fell due, by the time alone. */\n redraw?(linkId: string): void;\n /** The public profile kept for an identity (PUBLIC-PROFILES.md), shown only while its proof is current and verified. */\n publicProfile?(provider: string, subject: string): PublicProfileView | undefined;\n /** Pkarr (the Ghost DHT or its relays): publish records under a key, read a key's latest records. */\n publish(seed: Uint8Array, records: { label: string; value: string }[]): Promise<void>;\n resolve(key: string): Promise<{ label: string; value: string }[] | null>;\n}\n\nconst KEY = \"identityProofs\";\nconst REVOCATIONS = \"identityRevocations\";\n/** When the contacts' proofs were last looked up for a revocation (ms), so a reload does not look them all up again. */\nconst REVOCATIONS_CHECKED_AT = \"identityRevocationsCheckedAt\";\n/** The lookup under way: when it began (ms) and the proofs it already looked up (`linkId|id`), so one cut short goes on from the rest. */\nconst REVOCATIONS_ROUND = \"identityRevocationsRound\";\ninterface LookupRound { startedAt: number; done: string[] }\n/** Relays and the DHT forget a record within hours: republish revocations this often while the app runs. */\nconst REPUBLISH_MS = 60 * 60_000;\n/** The longest a timer waits; a redraw further off waits again from there. */\nconst MAX_TIMER_MS = 2 ** 31 - 1;\n/**\n * A revocation is kept (with its sealed seed) this long past its expiry by this device's clock, which may be the one that\n * is wrong: the contacts decide expiry by theirs. Only a clock ahead by more than the longest a proof may last (400 days)\n * drops one still standing for them. Republished only until its expiry, as before; a few hundred bytes each.\n */\nconst REVOCATION_KEPT_PAST_EXPIRY = IDENTITY_MAX_VALIDITY;\n/** How often the contacts' proofs are looked up for a revocation (and once shortly after start). */\nconst REVOCATION_CHECK_MS = 12 * 60 * 60_000;\n/** A lookup that could not run (offline, no relay answered) is tried again after this, doubled each time, up to the 12 h. */\nconst REVOCATION_RETRY_MS = 5 * 60_000;\n/** A proof's lookup the relays' budget held back is read again when it frees, at most this many times; then the lookup stops there and goes on from it at its next try. */\nconst BUDGET_TRIES = 5;\n/**\n * The 12 h lookup reads one proof key this often: 20 a minute, under half the relays' background share (44 a minute over\n * the three default relays), which the profile's DID, contact link and public profiles read through too.\n */\nconst REVOCATION_READ_GAP_MS = 3_000;\n/**\n * The lookup under way (`REVOCATIONS_ROUND`) is written at most this often, or once this many proofs were read since\n * (the reads of that time), and when it ends cut short or the engine stops: a restart after a crash reads again at most\n * those. Written after every read, it cost n writes of 1 to n entries: 45 MB a lookup for 900 proofs.\n */\nconst ROUND_SAVE_MS = 60_000;\nconst ROUND_SAVE_READS = ROUND_SAVE_MS / REVOCATION_READ_GAP_MS;\n/**\n * After a contact withdraws a proof, how long to wait before each lookup for its revocation (WISP 300: removing a proof withdraws it from\n * every chat and revokes it). The notice goes out before the revocation is published, so not at once; each try backs\n * off, and the first that finds it stops the rest. The 12 h check covers it after that.\n */\nexport const WITHDRAWN_REVOCATION_TRIES_MS = [20_000, 60_000, 180_000] as const;\n/**\n * A contact's proof whose provider asks for re-checks is checked again on its own (the provider's check, as \"Check\n * again\" runs it) this long after its last check, or the provider's own interval when longer: a domain record or a\n * listed key that is gone then stops reading verified.\n */\nexport const AUTO_RECHECK_AFTER_S = 86_400;\n/**\n * Due proofs are looked for this often (the first time a few minutes after the start). Each time checks enough of them\n * to clear the ones due within `AUTO_RECHECK_SPREAD_TICKS` times (at least `AUTO_RECHECK_BATCH`), one every\n * `AUTO_RECHECK_GAP_MS` at most, so every proof is checked about a day after its last check however many contacts.\n */\nconst AUTO_RECHECK_TICK_MS = 15 * 60_000;\nconst AUTO_RECHECK_FIRST_MS = 3 * 60_000;\nconst AUTO_RECHECK_BATCH = 3;\nconst AUTO_RECHECK_SPREAD_TICKS = 4;\nconst AUTO_RECHECK_GAP_MS = 4_000;\n/** The checks of one time fit before the next: 150 every 15 minutes, 14,400 a day. */\nconst AUTO_RECHECK_MAX_BATCH = Math.floor(AUTO_RECHECK_TICK_MS * 2 / 3 / AUTO_RECHECK_GAP_MS);\n/** A check that could not reach the server leaves the proof as it was and is tried again after this, doubling, at most a day. */\nconst AUTO_RECHECK_BACKOFF_MS = 2 * 60 * 60_000;\n/** A proof begun and not completed is dropped this long after, or when a fifth one begins (the CLI says the same). */\nexport const IDENTITY_DRAFT_TTL_MS = 30 * 60_000;\nexport const IDENTITY_MAX_DRAFTS = 4;\nconst MAX_PROOFS = 32;\nconst now = () => Math.floor(Date.now() / 1000);\n\n/**\n * A share of mine as every reader gets it (the app, the CLI, `getState`): its reason only in words this app writes\n * (identityRefusal), else none. A ledger kept from before that check holds the contact's own words there.\n */\nconst ownRefusal = (s: SharedIdentity): SharedIdentity => {\n if (s.error === undefined || identityRefusal(s.error) !== undefined) return s;\n const { error: _contactWords, ...rest } = s;\n return rest;\n};\n\n/**\n * Identity proofs, engine side: the profile's own proofs (made once, on the Identities page) and, per\n * chat, the `IdentityExchange` that shares them with that contact and checks what the contact shares.\n * Providers come from the registry; their `verify` runs here, through the shared checks.\n */\nexport class IdentityProofs {\n private proofs: StoredIdentityProof[] = [];\n private revocations: Revocation[] = [];\n private revocationsCheckedAt = 0;\n /** Revocation lookups in a row that could not run: the next waits `REVOCATION_RETRY_MS` doubled this many times less one. */\n private lookupsMissed = 0;\n /** The lookup under way, if one was cut short (`REVOCATIONS_ROUND`). */\n private round: LookupRound | undefined;\n /** When `round` was last written (ms), and how many proofs it gained since: `noteRound`. */\n private roundSavedAt = 0;\n private roundUnsaved = 0;\n /**\n * How the last Pkarr read of each contact's proof went (`revoked`), by proof id: answered, could not run (offline, no\n * relay answered), or held back by the relays' budget, which takes reads again in this many ms.\n */\n private reads = new Map<string, \"answered\" | \"failed\" | number>();\n /** When each contact's proof was last read for a revocation this run (ms), by proof id: the 12 h lookup reads the longest unread first. */\n private lastRead = new Map<string, number>();\n private lookupTimer: ReturnType<typeof setTimeout> | undefined;\n private looking = false;\n /** Counted at each `stop`: a 12 h lookup under way ends there. */\n private stops = 0;\n /** Ends the 12 h lookup's wait (between two reads, or for the budget) at once: `stop`. */\n private wakeLookup: (() => void) | undefined;\n /** Ends the automatic re-check's wait between two checks at once: `stop`. */\n private wakeRecheck: (() => void) | undefined;\n /** Revocations not published because the app was offline: published when the network comes back (`networkBack`). */\n private unpublished = new Set<string>();\n private running = false;\n /** \"Clear all data\" (`revokeAll`): a revocation lookup or a proof's save still on its way writes nothing. */\n private ended = false;\n /** Unsealed proof-key seeds, by proof id, for this run only. */\n private seeds = new Map<string, Uint8Array>();\n private timers: ReturnType<typeof setTimeout>[] = [];\n private unlisten: (() => void) | undefined;\n private drafts = new Map<string, { binding: IdentityBinding; seed: Uint8Array; at: number }>();\n private exchanges = new Map<string, IdentityExchange>();\n private saving: Promise<void> = Promise.resolve();\n private errors = new Map<string, string>();\n /** Chats whose current connection already got the hello: \"ready\" is reported more than once per connection. */\n private greeted = new Set<string>();\n /** Automatic re-checks that could not reach the server, by chat and proof: how many in a row, and when to try again (ms). */\n private recheckBackoff = new Map<string, { failures: number; until: number }>();\n /** When the automatic re-check asked each provider with a `recheck.perHour` (ms), this last hour, by provider id. */\n private recheckedAt = new Map<string, number[]>();\n /** Each chat's next change of its view by the time alone (s), and the timer that has it built again then: `linkView`. */\n private redrawTimers = new Map<string, { at: number; timer: ReturnType<typeof setTimeout> }>();\n private readonly fetch: ReturnType<typeof boundedIdentityFetch>;\n\n constructor(private host: IdentityLinkHost, private providers: () => readonly IdentityProofProvider[] = loadedIdentityProviders) {\n this.fetch = boundedIdentityFetch({ online: host.online, ...(host.fetcher && { fetcher: host.fetcher }), ...(host.relayFetcher && { relayFetcher: host.relayFetcher }) });\n }\n\n /** The profile's proofs, and the providers that check and show them: loaded here, not with the app. */\n async load(): Promise<void> {\n const providers = loadIdentityProviders();\n const settings = await store(STORES.settings, \"readonly\");\n [this.proofs, this.revocations, this.revocationsCheckedAt, this.round] = await Promise.all([\n wrap<StoredIdentityProof[] | undefined>(settings.get(KEY)).then(v => v ?? []),\n wrap<Revocation[] | undefined>(settings.get(REVOCATIONS)).then(v => v ?? []),\n wrap<number | undefined>(settings.get(REVOCATIONS_CHECKED_AT)).then(v => typeof v === \"number\" ? v : 0),\n wrap<LookupRound | undefined>(settings.get(REVOCATIONS_ROUND)).then(v => typeof v?.startedAt === \"number\" && Array.isArray(v.done) ? v : undefined),\n ]);\n await providers;\n }\n /** Background work: republish revocations, look up the contacts' proofs for revocations. */\n start(): void {\n this.running = true;\n // A round under way at `stop` plans no next one: `stop` cleared the timers before it ended.\n const stops = this.stops;\n const every = (ms: number, first: number, work: () => Promise<void>) => {\n const tick = () => { void work().catch(() => {}).finally(() => { if (this.stops === stops) this.timers.push(setTimeout(tick, ms)); }); };\n this.timers.push(setTimeout(tick, first));\n };\n every(REPUBLISH_MS, 5_000, () => this.republish());\n // 60 s after the start, unless the last lookup (from an earlier run) was less than 12 h ago: then when those are up.\n // A clock set back since then waits 12 h at most.\n const due = Math.min(REVOCATION_CHECK_MS, this.revocationsCheckedAt + REVOCATION_CHECK_MS - Date.now());\n this.lookUpIn(Math.max(60_000, due));\n every(AUTO_RECHECK_TICK_MS, AUTO_RECHECK_FIRST_MS, () => this.recheckDue());\n // A contact's request whose challenge ended unanswered, with no request after it, leaves the timeline within a window.\n every(IDENTITY_CHALLENGE_WINDOW * 1000, IDENTITY_CHALLENGE_WINDOW * 1000, () => this.expireChallenges());\n this.unlisten ??= whenDataKeyDropped(() => this.forgetSeeds());\n }\n /** The network is back: a revocation lookup that could not run, and a revocation not published offline, go now. */\n networkBack(): void {\n if (!this.running || this.ended) return;\n if (this.lookupsMissed > 0) this.lookUpIn(0);\n for (const r of this.revocations) if (this.unpublished.has(r.id) && r.expiresAt > now()) void this.publishRevocation(r).catch(() => {});\n }\n private lookUpIn(ms: number): void {\n if (this.lookupTimer) clearTimeout(this.lookupTimer);\n const timer = this.lookupTimer = setTimeout(() => {\n this.timers = this.timers.filter(t => t !== timer);\n this.lookupTimer = undefined;\n void this.lookUp();\n }, ms);\n this.timers.push(timer);\n }\n /** A lookup done waits 12 h for the next; one that could not run is tried again sooner, backing off. */\n private async lookUp(): Promise<void> {\n // One still on its way plans the next itself.\n if (this.looking) return;\n this.looking = true;\n const done = await this.checkRevocations().catch(() => false);\n this.looking = false;\n if (!this.running) return;\n this.lookupsMissed = done ? 0 : this.lookupsMissed + 1;\n this.lookUpIn(done ? REVOCATION_CHECK_MS : Math.min(REVOCATION_CHECK_MS, REVOCATION_RETRY_MS * 2 ** (this.lookupsMissed - 1)));\n }\n stop(): void {\n this.running = false;\n this.stops++;\n for (const t of this.timers) clearTimeout(t);\n this.timers = [];\n for (const { timer } of this.redrawTimers.values()) clearTimeout(timer);\n this.redrawTimers.clear();\n // Every chat's exchange ends as if its link closed: no pacing timer outlives the engine, and a start after this\n // greets each chat again when its link is ready.\n for (const x of this.exchanges.values()) x.stop();\n this.greeted.clear();\n this.lookupTimer = undefined;\n // The lookup under way ends here: what it read since its last write is kept for the next start.\n this.saveRound();\n this.wakeLookup?.();\n this.wakeRecheck?.();\n this.unlisten?.();\n this.unlisten = undefined;\n this.forgetSeeds();\n }\n private forgetSeeds(): void {\n for (const seed of this.seeds.values()) seed.fill(0);\n this.seeds.clear();\n }\n /**\n * Every change of the proofs and revocations, one after the other, each made on what the one before stored: two at\n * once (two proofs completed, a proof removed while another completes) both from the same list lost one of them.\n */\n private save(change: (proofs: StoredIdentityProof[], revocations: Revocation[]) => [StoredIdentityProof[], Revocation[]]): Promise<void> {\n const run = this.saving.then(async () => {\n // \"Clear all data\" came while a check or a removal was on its way: the list in memory is the cleared profile's.\n if (this.ended) throw new Error(\"This profile's data was cleared\");\n const [proofs, revocations] = change(this.proofs, this.revocations);\n await transact([STORES.settings], stores => { stores[STORES.settings].put(proofs, KEY); stores[STORES.settings].put(revocations, REVOCATIONS); });\n this.proofs = proofs;\n this.revocations = revocations;\n this.host.emit();\n });\n this.saving = run.catch(() => {});\n return run;\n }\n private async seedOf(id: string, sealed: SealedProofKey): Promise<Uint8Array> {\n let seed = this.seeds.get(id);\n if (!seed) { seed = fromBase64Url(await openSecret(sealed, proofKeyAt(id))); this.seeds.set(id, seed); }\n return seed;\n }\n\n private ctx(fetch: IdentityFetch = this.fetch) { return { now: now(), signal: AbortSignal.timeout(30_000), fetch }; }\n /** The person's own proof, before it is saved: on whatever servers it names, their own. */\n private verify = (statement: IdentityStatement, evidence: unknown) => verifyIdentity(this.providers(), statement, evidence, this.ctx());\n /**\n * A contact's proof. With Hide my IP on, a host its evidence names (a did:web or domain's web server, an AT Protocol\n * server, a Pubky homeserver) is not contacted, since it would learn this device's IP address: the check fails as one\n * that could not run, and the contact is told only that.\n */\n private verifyContact = async (statement: IdentityStatement, evidence: unknown) => {\n let refused: string | undefined;\n let fetch = this.fetch;\n if (this.host.relayOnly?.()) {\n const { fixedIdentityHosts } = await import(\"../proofs/fixedHosts\");\n const fixed = fixedIdentityHosts();\n fetch = async (url, options) => {\n const host = new URL(url).host;\n if (!fixed.has(host)) { refused ??= host; throw new IdentityCheckUnavailable(`${host} was not contacted`); }\n return this.fetch(url, options);\n };\n }\n const ctx = this.ctx(fetch);\n try {\n return await verifyIdentity(this.providers(), statement, evidence, ctx);\n } catch (e) {\n // A provider words a failed fetch its own way (\"could not be reached\"): this says why it was not tried.\n if (refused) throw new IdentityCheckUnavailable(`Hide my IP from contacts is on: ${refused}, a server your contact chose, was not contacted`);\n // Out of time (servers that hang): the check could not run, which says nothing of the proof.\n if (ctx.signal.aborted && !(e instanceof IdentityCheckUnavailable)) throw new IdentityCheckUnavailable(e instanceof Error ? e.message : String(e));\n throw e;\n }\n };\n /**\n * The exchange reads a lookup that failed as \"not revoked\": noted here (`reads`), so the 12 h lookup looks that proof\n * up again. One the relays' budget held back is kept apart: the lookup waits for the budget and reads it again.\n */\n private revoked = async (statement: IdentityStatement): Promise<boolean> => {\n if (!this.host.online()) { this.reads.set(statement.id, \"failed\"); return false; }\n const records = await this.host.resolve(statement.binding.key).catch((e: unknown) => {\n this.reads.set(statement.id, isDiscoveryBudgetError(e) ? budgetRetryMs(e, 1_000, 60_000) : \"failed\");\n throw e;\n });\n this.reads.set(statement.id, \"answered\");\n this.lastRead.set(statement.id, Date.now());\n return !!records && revokesIdentity(records, statement.id);\n };\n\n private async local(id: string): Promise<LocalIdentityProof | undefined> {\n const p = this.proofs.find(x => identityStatement(x.binding).id === id);\n return p && { statement: identityStatement(p.binding), evidence: p.evidence, seed: await this.seedOf(id, p.seed), account: p.verified.subject };\n }\n\n // -- the profile's proofs --------------------------------------------------------------------\n\n /** Step 1 of adding a proof: a fresh proof key and the statement the external identity must sign. */\n begin({ provider, subject, validityDays }: { provider: string; subject: string; validityDays?: number }): { draftId: string; binding: IdentityBinding } {\n const p = this.providers().find(x => x.id === provider);\n if (!p) throw new Error(\"Unknown kind of identity\");\n const days = validityDays ?? p.validity.defaultDays;\n if (!Number.isInteger(days) || days < 1 || days > p.validity.maxDays) throw new Error(`Choose between 1 and ${p.validity.maxDays} days`);\n const canonical = p.subject.normalize(subject);\n for (const [id, d] of this.drafts) if (Date.now() - d.at > IDENTITY_DRAFT_TTL_MS) { d.seed.fill(0); this.drafts.delete(id); }\n while (this.drafts.size >= IDENTITY_MAX_DRAFTS) { const [id, d] = this.drafts.entries().next().value!; d.seed.fill(0); this.drafts.delete(id); }\n const { binding, seed } = newIdentityBinding({ provider, subject: canonical, validitySeconds: days * 86_400 });\n const draftId = toBase64Url(crypto.getRandomValues(new Uint8Array(16)));\n this.drafts.set(draftId, { binding, seed, at: Date.now() });\n return { draftId, binding };\n }\n\n /** Step 2: the evidence. Verified here, exactly as a contact will, before anything is saved. */\n async complete({ draftId, evidence }: { draftId: string; evidence: unknown }): Promise<IdentityProofView> {\n const draft = this.drafts.get(draftId);\n if (!draft) throw new Error(\"This proof was started too long ago. Start again.\");\n const statement = identityStatement(draft.binding);\n const verified = await this.verify(statement, JSON.parse(JSON.stringify(evidence ?? null)));\n // Cancelled (or dropped) while it was checked: nothing to save, and its seed is zeroed.\n if (this.drafts.get(draftId) !== draft) throw new Error(\"This proof was started too long ago. Start again.\");\n if (this.proofs.length >= MAX_PROOFS) throw new Error(\"Remove an identity first\");\n this.drafts.delete(draftId);\n const stored: StoredIdentityProof = { binding: draft.binding, evidence, seed: await sealSecret(toBase64Url(draft.seed), proofKeyAt(statement.id)), verified, createdAt: Date.now() };\n this.seeds.set(statement.id, draft.seed);\n await this.save((proofs, revocations) => {\n if (proofs.length >= MAX_PROOFS) throw new Error(\"Remove an identity first\");\n return [[...proofs, stored], revocations];\n });\n return this.viewOf(stored);\n }\n\n cancel({ draftId }: { draftId: string }): void {\n this.drafts.get(draftId)?.seed.fill(0);\n this.drafts.delete(draftId);\n }\n\n /**\n * Removes a proof from the profile: withdrawn from every chat it was shared in (each contact is told now\n * or when it next connects), and revoked for good, by a record its proof key publishes on Pkarr and this\n * app republishes until the proof would have expired, for contacts it never reconnects to.\n */\n async remove({ id }: { id: string }): Promise<void> {\n const proof = this.proofs.find(p => identityStatement(p.binding).id === id);\n if (!proof) return;\n for (const linkId of this.host.linkIds()) {\n const shared = this.host.ledger(linkId)?.shared.find(s => s.id === id);\n if (shared && shared.status !== \"withdrawn\") await this.exchange(linkId)?.withdraw(id, !!this.host.channel(linkId));\n }\n const revocation: Revocation = { id, key: proof.binding.key, seed: proof.seed, revokedAt: now(), expiresAt: Math.min(proof.binding.expiresAt, proof.verified.expiresAt ?? Infinity) };\n // Kept whatever this clock says: the contacts decide expiry by theirs.\n const wasShared = this.everShared(proof);\n await this.save((proofs, revocations) => proofs.some(p => identityStatement(p.binding).id === id)\n ? [proofs.filter(p => identityStatement(p.binding).id !== id), wasShared ? [...revocations, revocation] : revocations]\n : [proofs, revocations]);\n if (wasShared) void this.publishRevocation(revocation).catch(() => {});\n else { this.seeds.get(id)?.fill(0); this.seeds.delete(id); }\n }\n\n /**\n * \"Clear all data\": every proof that was ever shared, and every removed one still being revoked, gets its revocation\n * record published once more, all at once. Nothing will republish them after the clear, so this is a last word for\n * contacts who check; proofs posted elsewhere (a Bluesky record, a Pubky file, a DNS record) are the person's to delete.\n */\n async revokeAll(): Promise<void> {\n this.ended = true;\n this.stop();\n const at = now();\n const last: Revocation[] = [\n ...this.revocations,\n ...this.proofs.filter(p => this.everShared(p)).map(p => ({\n id: identityStatement(p.binding).id, key: p.binding.key, seed: p.seed, revokedAt: at, expiresAt: Math.min(p.binding.expiresAt, p.verified.expiresAt ?? Infinity),\n })),\n ];\n await Promise.allSettled(last.map(r => this.publishRevocation(r)));\n this.stop();\n }\n\n /** Marked when shared; the chats' ledgers still count for a proof shared before the mark was kept. */\n private everShared(p: StoredIdentityProof): boolean {\n const id = identityStatement(p.binding).id;\n return !!p.shared || this.host.linkIds().some(l => this.host.ledger(l)?.shared.some(s => s.id === id));\n }\n\n private async publishRevocation(r: Revocation): Promise<void> {\n if (!this.host.online()) { this.unpublished.add(r.id); return; }\n this.unpublished.delete(r.id);\n await this.host.publish(await this.seedOf(r.id, r.seed), [{ label: IDENTITY_REVOCATION_LABEL, value: identityRevocationValue(r.id, r.revokedAt) }]);\n }\n private async republish(): Promise<void> {\n const kept = (r: Revocation) => r.expiresAt + REVOCATION_KEPT_PAST_EXPIRY > now();\n if (!this.revocations.every(kept)) {\n for (const r of this.revocations) if (!kept(r)) { this.seeds.get(r.id)?.fill(0); this.seeds.delete(r.id); }\n await this.save((proofs, revocations) => [proofs, revocations.filter(kept)]);\n }\n for (const r of this.revocations.filter(r => r.expiresAt > now())) {\n if (!this.running) return;\n await this.publishRevocation(r).catch(() => {});\n }\n }\n /**\n * Looks up the contacts' proofs for a revocation (the Pkarr record only, not the provider): the ones standing, and the\n * ones withdrawn, which a removal also revokes. Not a proof already revoked, nor one past its expiry: its owner\n * publishes the revocation only until then. True when every lookup was answered: only then is its time noted.\n *\n * Each proof answered is noted in the lookup under way (`round`, kept across a restart): one cut short (a read that\n * failed, the relays' budget still held after its tries, the network gone, the app stopped) goes on later from the\n * proofs still to look up. Started again from the first, a few keys no relay answered cost every proof's read again.\n * It is written about once a minute (`ROUND_SAVE_MS`) and whenever the lookup ends without completing.\n *\n * One read every `REVOCATION_READ_GAP_MS`, the longest unread first: read back to back, the lookup took the relays'\n * whole background share for a minute, and every read past it was held back.\n */\n async checkRevocations(): Promise<boolean> {\n if (!this.host.online()) return false;\n // A lookup begun 12 h ago (or after the clock was set back) is not gone on with: every proof is due again.\n const at = Date.now();\n if (!this.round || at - this.round.startedAt >= REVOCATION_CHECK_MS || this.round.startedAt > at) this.round = { startedAt: at, done: [] };\n const round = this.round, done = new Set(round.done);\n this.roundSavedAt = at;\n this.roundUnsaved = 0;\n const todo = this.host.linkIds().flatMap(linkId => (this.host.ledger(linkId)?.received ?? [])\n .filter(r => this.revocable(r) && !done.has(`${linkId}|${r.id}`)).map(r => ({ linkId, id: r.id })))\n .sort((a, b) => (this.lastRead.get(a.id) ?? 0) - (this.lastRead.get(b.id) ?? 0));\n let missed = false, wait = 0, complete = false;\n const stops = this.stops;\n try {\n for (const { linkId, id } of todo) {\n // The relays hold background reads past their minute's share: this one waits for it and goes again, as nobody\n // waits on the lookup. Still held after its tries, the relays are busy: the rest wait for the next try.\n for (let tries = 0; ; tries++) {\n if (wait > 0 && !await this.lookupPause(wait)) return false;\n if (this.ended || this.stops !== stops) return false;\n // The network went: the rest wait for it (`networkBack`), not each one counted a failed read.\n if (!this.host.online()) return false;\n this.reads.delete(id);\n await this.exchange(linkId)?.recheck(id, { revocationOnly: true }).catch(() => {});\n const read = this.reads.get(id);\n wait = typeof read === \"number\" ? read : REVOCATION_READ_GAP_MS;\n if (read === \"failed\") { missed = true; break; }\n if (typeof read !== \"number\") { round.done.push(`${linkId}|${id}`); this.noteRound(round); break; }\n if (tries >= BUDGET_TRIES) return false;\n }\n }\n complete = !missed;\n } finally {\n this.reads.clear();\n // Cut short (stopped, offline, a read failed or held back, an error): what was read since the last write is kept.\n if (!complete) this.saveRound(round);\n }\n // \"Clear all data\" came meanwhile: the profile it was for is gone, and its time must not land in the cleared one.\n if (this.ended || missed) return false;\n this.revocationsCheckedAt = Date.now();\n if (this.round === round) this.round = undefined;\n await transact([STORES.settings], stores => {\n stores[STORES.settings].put(this.revocationsCheckedAt, REVOCATIONS_CHECKED_AT);\n stores[STORES.settings].delete(REVOCATIONS_ROUND);\n });\n return true;\n }\n /** A proof read in the lookup under way: written a minute after the last write, or once `ROUND_SAVE_READS` wait (a clock set back writes too). */\n private noteRound(round: LookupRound): void {\n this.roundUnsaved++;\n const since = Date.now() - this.roundSavedAt;\n if (this.roundUnsaved >= ROUND_SAVE_READS || since >= ROUND_SAVE_MS || since < 0) this.saveRound(round);\n }\n /** Not waited on: the writes keep their order, so the lookup's end (which deletes it) lands after. Nothing new since the last write: nothing written. */\n private saveRound(round: LookupRound | undefined = this.round): void {\n if (!round || this.roundUnsaved === 0 || this.ended || this.round !== round) return;\n this.roundUnsaved = 0;\n this.roundSavedAt = Date.now();\n void transact([STORES.settings], stores => { stores[STORES.settings].put({ ...round, done: [...round.done] }, REVOCATIONS_ROUND); }).catch(() => {});\n }\n /**\n * The contacts' proofs due for an automatic re-check (`AUTO_RECHECK_AFTER_S`), the longest unchecked first, as many\n * at a time as keep up with them (`AUTO_RECHECK_SPREAD_TICKS`), one after the other a few seconds apart, and no more\n * an hour of a provider's than its `recheck.perHour`. A proof whose\n * record or key is gone shows unconfirmed with the reason, as after \"Check again\"; one whose server could not be reached (or a network that went away meanwhile) is left as it was and backs off.\n */\n async recheckDue(): Promise<void> {\n if (!this.host.online()) return;\n const t = now(), at = Date.now();\n const due: { linkId: string; r: ReceivedIdentity }[] = [];\n for (const linkId of this.host.linkIds()) {\n for (const r of this.host.ledger(linkId)?.received ?? []) {\n const after = this.providers().find(p => p.id === r.binding.provider)?.recheck?.afterSeconds;\n if (after === undefined || (r.status !== \"verified\" && r.status !== \"unconfirmed\") || !this.revocable(r)) continue;\n // A check made while the clock ran ahead is due now, not at that future date.\n if ((r.checkedAt <= t && t - r.checkedAt < Math.max(after, AUTO_RECHECK_AFTER_S)) || (this.recheckBackoff.get(`${linkId}|${r.id}`)?.until ?? 0) > at) continue;\n due.push({ linkId, r });\n }\n }\n let batch = Math.min(AUTO_RECHECK_MAX_BATCH, Math.max(AUTO_RECHECK_BATCH, Math.ceil(due.length / AUTO_RECHECK_SPREAD_TICKS)));\n let first = true;\n for (const { linkId, r } of due.sort((a, b) => a.r.checkedAt - b.r.checkedAt)) {\n if (batch === 0) return;\n // A provider whose server limits lookups per IP: past its hour's share, its proofs wait for a later time.\n const perHour = this.providers().find(p => p.id === r.binding.provider)?.recheck?.perHour;\n const recent = perHour === undefined ? undefined : (this.recheckedAt.get(r.binding.provider) ?? []).filter(t => t > Date.now() - 3_600_000 && t <= Date.now());\n if (recent && recent.length >= perHour!) continue;\n batch--;\n if (!first && !await this.recheckPause(AUTO_RECHECK_GAP_MS)) return;\n first = false;\n if (this.ended || !this.running || !this.host.online()) return;\n if (recent) this.recheckedAt.set(r.binding.provider, [...recent, Date.now()]);\n const key = `${linkId}|${r.id}`;\n try {\n await this.exchange(linkId)?.recheck(r.id, { keepUnavailable: true });\n this.recheckBackoff.delete(key);\n } catch {\n const failures = (this.recheckBackoff.get(key)?.failures ?? 0) + 1;\n this.recheckBackoff.set(key, { failures, until: Date.now() + Math.min(AUTO_RECHECK_BACKOFF_MS * 2 ** (failures - 1), AUTO_RECHECK_AFTER_S * 1000) });\n }\n }\n }\n /** The automatic re-check's wait between two checks: false when `stop` ended it. */\n private recheckPause(ms: number): Promise<boolean> {\n return new Promise(resolve => {\n const timer = setTimeout(() => { this.timers = this.timers.filter(t => t !== timer); this.wakeRecheck = undefined; resolve(true); }, ms);\n this.timers.push(timer);\n this.wakeRecheck = () => { clearTimeout(timer); this.wakeRecheck = undefined; resolve(false); };\n });\n }\n /** Every chat's challenges whose window ended unanswered, and their verifying lines (`IdentityExchange.expire`). */\n async expireChallenges(): Promise<void> {\n for (const linkId of this.host.linkIds()) {\n if (this.ended || !this.running) return;\n if (this.host.ledger(linkId)?.challenges.length) await this.exchange(linkId)?.expire().catch(() => {});\n }\n }\n /** The 12 h lookup's wait between two reads, or for the budget: false when `stop` ended it. */\n private lookupPause(ms: number): Promise<boolean> {\n return new Promise(resolve => {\n const timer = setTimeout(() => { this.timers = this.timers.filter(t => t !== timer); this.wakeLookup = undefined; resolve(true); }, ms);\n this.timers.push(timer);\n this.wakeLookup = () => { clearTimeout(timer); this.wakeLookup = undefined; resolve(false); };\n });\n }\n private revocable(r: ReceivedIdentity): boolean {\n return r.status !== \"revoked\" && Math.min(r.binding.expiresAt, r.verified.expiresAt ?? Infinity) > now();\n }\n /** A proof the contact just withdrew: looked up for its revocation a few times (`WITHDRAWN_REVOCATION_TRIES_MS`). */\n private afterWithdrawal(linkId: string, id: string, tries: readonly number[] = WITHDRAWN_REVOCATION_TRIES_MS): void {\n const [wait, ...rest] = tries;\n if (wait === undefined) return;\n const timer = setTimeout(() => {\n this.timers = this.timers.filter(t => t !== timer);\n const r = this.host.ledger(linkId)?.received.find(x => x.id === id);\n if (!r || r.status !== \"withdrawn\" || !this.revocable(r)) return;\n void (async () => {\n const next = this.host.online() ? await this.exchange(linkId)?.recheck(id, { revocationOnly: true }).catch(() => undefined) : undefined;\n if (next?.status !== \"revoked\") this.afterWithdrawal(linkId, id, rest);\n })();\n }, wait);\n this.timers.push(timer);\n }\n\n /** Every engine state builds these: each chat's ledger is read once for all the proofs, not once per proof. */\n views(): IdentityProofView[] {\n const sharedWith = this.sharedWith();\n return this.proofs.map(p => this.viewOf(p, sharedWith));\n }\n /** The subjects of the profile's own proofs of one provider, without building their views (no chat's ledger is read). */\n subjects(provider: string): string[] {\n return this.proofs.filter(p => p.binding.provider === provider).map(p => p.binding.subject);\n }\n /** By proof id, the chats it is shared in (not withdrawn, nor rejected by the contact). */\n private sharedWith(): Map<string, number> {\n const counts = new Map<string, number>();\n for (const l of this.host.linkIds()) {\n const ids = new Set<string>();\n for (const s of this.host.ledger(l)?.shared ?? []) if (s.status !== \"withdrawn\" && s.status !== \"withdrawal-pending\" && s.status !== \"rejected\") ids.add(s.id);\n for (const id of ids) counts.set(id, (counts.get(id) ?? 0) + 1);\n }\n return counts;\n }\n private viewOf(p: StoredIdentityProof, shared = this.sharedWith()): IdentityProofView {\n const id = identityStatement(p.binding).id;\n const sharedWith = shared.get(id) ?? 0;\n const publicUri = this.publicUri(p);\n const expiresAt = Math.min(p.binding.expiresAt, p.verified.expiresAt ?? Infinity);\n const publicProfile = expiresAt > now() ? this.host.publicProfile?.(p.binding.provider, p.verified.subject) : undefined;\n return { id, provider: p.binding.provider, subject: p.binding.subject, key: p.binding.key, verified: p.verified,\n issuedAt: p.binding.issuedAt, expiresAt, createdAt: p.createdAt, sharedWith, evidence: p.evidence,\n ...(publicUri ? { publicUri } : {}), ...(publicProfile ? { publicProfile } : {}) };\n }\n\n /** What the profile's public DID would list for this identity: the provider's URI for the verified subject, if well formed. */\n private publicUri(p: StoredIdentityProof): string | undefined {\n try {\n const uri = this.providers().find(x => x.id === p.binding.provider)?.publicUri?.(p.verified.subject);\n return uri && /^[A-Za-z][A-Za-z0-9+.-]*:[^\\s,;]+$/.test(uri) ? uri : undefined;\n } catch {\n return undefined;\n }\n }\n\n // -- per chat ----------------------------------------------------------------------------------\n\n private exchange(linkId: string): IdentityExchange | undefined {\n if (!this.host.ledger(linkId)) return undefined;\n let x = this.exchanges.get(linkId);\n if (!x) {\n x = new IdentityExchange({\n scope: () => { const c = this.host.channel(linkId); if (!c) throw new Error(\"Connect to this contact first\"); return c.scope(); },\n send: frame => { const c = this.host.channel(linkId); if (!c) throw new Error(\"Connect to this contact first\"); c.send(frame); },\n storage: {\n read: () => this.host.ledger(linkId) ?? emptyIdentityLedger(),\n update: async change => { await this.host.updateLedger(linkId, change); this.host.emit(); },\n },\n providers: () => this.providers().map(p => p.id),\n localProof: id => this.local(id),\n verify: this.verifyContact,\n revoked: this.revoked,\n onError: error => { this.errors.set(linkId, error); this.host.emit(); },\n });\n this.exchanges.set(linkId, x);\n }\n return x;\n }\n\n async share({ linkId, id }: { linkId: string; id: string }): Promise<void> {\n const x = this.exchange(linkId);\n if (!x) throw new Error(\"Identities can be shared in paired chats only\");\n const p = this.proofs.find(q => identityStatement(q.binding).id === id);\n if (!p) throw new Error(\"That identity is no longer in your profile\");\n if (Math.min(p.binding.expiresAt, p.verified.expiresAt ?? Infinity) <= now())\n throw new Error(\"This identity has expired. Make a new proof in your profile.\");\n this.errors.delete(linkId);\n // Noted before it can leave the device: the chat's ledger goes if the chat is deleted, the contact's copy does not.\n if (!p.shared) await this.save((proofs, revocations) => [proofs.map(q => identityStatement(q.binding).id === id ? { ...q, shared: true as const } : q), revocations]);\n await x.share(id, !!this.host.channel(linkId));\n }\n async withdraw({ linkId, id }: { linkId: string; id: string }): Promise<void> {\n await this.exchange(linkId)?.withdraw(id, !!this.host.channel(linkId));\n }\n /** The contact's proof, checked again: its revocation record, then the provider's own check. */\n async recheck({ linkId, id }: { linkId: string; id: string }): Promise<void> {\n if (!this.host.online()) throw new Error(\"Offline: turn the network on to check again\");\n await this.exchange(linkId)?.recheck(id);\n }\n /** Only on the person's request: the provider's public name/picture for a verified identity. */\n async lookupDisplay({ linkId, id }: { linkId: string; id: string }): Promise<void> {\n if (!this.host.online()) throw new Error(\"Offline: turn the network on first\");\n const r = this.host.ledger(linkId)?.received.find(x => x.id === id);\n const provider = r && this.providers().find(p => p.id === r.binding.provider);\n if (!r || !provider?.lookupDisplay) throw new Error(\"No public profile for this identity\");\n const found = await provider.lookupDisplay(r.verified.subject, { signal: AbortSignal.timeout(15_000) });\n if (!found) throw new Error(\"No public profile found\");\n // Held to the rule a proof's own display is (no hidden or direction-changing characters in its name).\n const display = boundIdentityDisplay(found);\n await this.host.updateLedger(linkId, l => ({ ...l, received: l.received.map(x => x.id === id && x.verified.subject === r.verified.subject ? { ...x, display } : x) }));\n this.host.emit();\n }\n\n async frame(linkId: string, frame: Record<string, unknown>): Promise<void> {\n const x = this.exchange(linkId);\n if (!x) return;\n // A proof withdrawn now, or one whose check ends after its owner withdrew it (`idp-present`), gets its revocation lookups.\n const id = frame.t === \"idp-withdraw\" && typeof frame.id === \"string\" ? frame.id\n : frame.t === \"idp-present\" && isIdentityBinding(frame.binding) ? identityStatement(frame.binding).id : undefined;\n const withdrawn = () => !!id && !!this.host.ledger(linkId)?.received.some(r => r.id === id && r.status === \"withdrawn\");\n // A withdraw that marks a presentation still in its check withdrawn (`challenge.withdrawn`) counts too: the\n // record kept from an earlier withdraw already reads withdrawn, and that check's own frame read it so on arrival.\n const checking = () => frame.t === \"idp-withdraw\" && !!this.host.ledger(linkId)?.challenges.some(c => c.id === id && !c.withdrawn);\n const before = withdrawn() && !checking();\n const handled = x.receive(frame).then(() => { if (id && !before && withdrawn()) this.afterWithdrawal(linkId, id); });\n // A presentation's check waits on a host the contact chose (up to 30 s): it is not waited for here, so the\n // contact's texts, pings and other frames go on meanwhile. Its outcome is written and sent when it ends.\n if (frame.t === \"idp-present\") void handled.catch(() => {});\n else await handled;\n }\n ready(linkId: string): void {\n if (this.greeted.has(linkId) || !this.host.channel(linkId)) return;\n try { this.exchange(linkId)?.ready(); this.greeted.add(linkId); } catch { /* the channel closed again */ }\n }\n closed(linkId: string): void {\n this.greeted.delete(linkId);\n this.exchanges.get(linkId)?.stop();\n }\n forget(linkId: string): void {\n this.greeted.delete(linkId);\n this.exchanges.get(linkId)?.stop();\n this.exchanges.delete(linkId);\n this.errors.delete(linkId);\n this.redrawAt(linkId, undefined);\n }\n\n /** Has the chat's view built again at `at` (s): nothing stored changes when a proof expires, so nothing else would. */\n private redrawAt(linkId: string, at: number | undefined): void {\n const armed = this.redrawTimers.get(linkId);\n if (armed?.at === at) return;\n if (armed) clearTimeout(armed.timer);\n this.redrawTimers.delete(linkId);\n if (at === undefined || !this.host.redraw) return;\n const timer = setTimeout(() => {\n this.redrawTimers.delete(linkId);\n if (at * 1000 > Date.now()) this.redrawAt(linkId, at);\n else this.host.redraw?.(linkId);\n }, Math.min(at * 1000 - Date.now(), MAX_TIMER_MS));\n this.redrawTimers.set(linkId, { at, timer });\n }\n\n linkView(linkId: string, supported: boolean): LinkIdentitiesView | undefined {\n const ledger = this.host.ledger(linkId);\n if (!ledger) return undefined;\n const { mine, theirs } = this.host.keys(linkId);\n const t = now();\n // The soonest a proof shown expires or its re-check falls due: the view is built again then.\n let next = Infinity;\n const view: LinkIdentitiesView = {\n support: supported,\n contactProviders: supported ? this.exchanges.get(linkId)?.contactProviders?.slice() : undefined,\n shared: ledger.shared.map(ownRefusal),\n received: ledger.received.map(r => {\n const provider = this.providers().find(p => p.id === r.binding.provider);\n const status = receivedIdentityStatus(r, theirs, mine, t);\n const ends = Math.min(r.binding.expiresAt, r.verified.expiresAt ?? Infinity);\n if ((status === \"verified\" || status === \"unconfirmed\") && ends > t) next = Math.min(next, ends);\n const due = provider?.recheck && r.checkedAt <= t ? r.checkedAt + provider.recheck.afterSeconds : Infinity;\n if (due > t) next = Math.min(next, due);\n const publicProfile = status === \"verified\" ? this.host.publicProfile?.(r.binding.provider, r.verified.subject) : undefined;\n // A check stored while this device's clock ran ahead reads as done now, not at that future date.\n return { id: r.id, provider: r.binding.provider, subject: r.verified.subject, verified: r.verified, display: r.display,\n status, verifiedAt: Math.min(r.verifiedAt, t), checkedAt: Math.min(r.checkedAt, t),\n expiresAt: Math.min(r.binding.expiresAt, r.verified.expiresAt ?? Infinity), error: r.error,\n recheckDue: !!provider?.recheck && (r.checkedAt > t || t - r.checkedAt >= provider.recheck.afterSeconds),\n ...(publicProfile ? { publicProfile } : {}) };\n }),\n error: this.errors.get(linkId),\n };\n this.redrawAt(linkId, next === Infinity ? undefined : next);\n return view;\n }\n}\n","import { FILE_BYTES_STEP, fileBytesOf, type FileBytes } from \"./fileBytes\";\nimport { fileStore, type StoredFile } from \"./idb\";\nimport type { FileTransferView } from \"./types\";\n\n/** The bytes a file holds: its metadata says, and a file stored before that says it with its Blob. */\nexport function storedSize(file: StoredFile): number {\n return file.metadata?.size ?? file.blob?.size ?? 0;\n}\n\n/**\n * A group's file (WISP 503) that is not here, read from its record: when the engine shows no transfer for it, it waits\n * for its person's Download. The engine keeps no view of such a file in the states it builds (one for every file a\n * group ever had would go into each of them), so the app's bubble and the CLI read it here. Null for any other file.\n */\nexport function waitingGroupFile(file: StoredFile | undefined): FileTransferView | null {\n if (!file?.group || file.direction !== \"in\" || file.transfer?.state !== \"transferring\") return null;\n return { state: \"transferring\", stage: \"asking\", transferred: 0, size: file.metadata?.size ?? file.transfer.size, direction: \"in\" };\n}\n\nasync function backend(file: StoredFile): Promise<FileBytes | null> {\n return file.bytes ? fileBytesOf(file.bytes) : null;\n}\n\n/** The file as a Blob backed by storage, or null where it cannot be had as one (see `FileBytes.blob`). */\nexport async function storedBlob(file: StoredFile, type: string): Promise<Blob | null> {\n if (file.blob) return file.blob.slice(0, file.blob.size, type);\n return (await backend(file))?.blob(file.id, type) ?? null;\n}\n\n/** At most `length` bytes from `offset`. */\nexport async function readStored(file: StoredFile, offset: number, length: number): Promise<Uint8Array> {\n if (file.blob) return new Uint8Array(await file.blob.slice(offset, offset + length).arrayBuffer());\n const bytes = await backend(file);\n if (!bytes) throw new Error(\"The file is gone\");\n return bytes.read(file.id, offset, length);\n}\n\n/** The file, a step at a time, from `offset`. */\nexport async function* streamStored(file: StoredFile, offset = 0): AsyncGenerator<Uint8Array> {\n const size = storedSize(file);\n while (offset < size) {\n const part = await readStored(file, offset, Math.min(FILE_BYTES_STEP, size - offset));\n if (!part.length) throw new Error(\"The file is shorter than it says\");\n offset += part.length;\n yield part;\n }\n}\n\n/** A file's record and its bytes, wherever they are. */\nexport async function removeStored(id: string): Promise<void> {\n const file = await fileStore.get(id);\n await fileStore.delete(id);\n if (file?.bytes) await (await backend(file))?.remove(id);\n}\n\n/** Writes are gathered to this size before they go to storage: a chunk from the wire is 16 KiB. */\nconst GATHER = 256 * 1024;\n\n/**\n * Writes one file in order, gathering small writes into larger ones. `written` counts what was handed over,\n * gathered or not; `flush` makes all of it durable. Its calls run one after another: a close while a flush still\n * writes the gathered part (a holder gone, then the transfer cancelled) would write that part a second time.\n *\n * The gathering buffer is made at the first small write and let go at a flush or close: a file waiting (paused,\n * its session gone) holds none. Made with every appender, a contact's 256 small files offered and then paused held\n * 64 MiB until a restart.\n */\nexport class FileAppender {\n private buffer: Uint8Array | null = null;\n private buffered = 0;\n private stored: number;\n private turn: Promise<unknown> = Promise.resolve();\n\n constructor(readonly bytes: FileBytes, readonly id: string, offset = 0) { this.stored = offset; }\n\n get written(): number { return this.stored + this.buffered; }\n\n append(chunk: Uint8Array): Promise<void> {\n return this.inTurn(async () => {\n if (this.buffered + chunk.length > GATHER) await this.drain();\n if (chunk.length >= GATHER) {\n await this.bytes.append(this.id, this.stored, chunk);\n this.stored += chunk.length;\n return;\n }\n this.buffer ??= new Uint8Array(GATHER);\n this.buffer.set(chunk, this.buffered);\n this.buffered += chunk.length;\n });\n }\n\n flush(): Promise<void> {\n return this.inTurn(async () => {\n await this.drain();\n this.buffer = null;\n await this.bytes.flush(this.id);\n });\n }\n\n close(): Promise<void> {\n return this.inTurn(async () => {\n await this.drain();\n this.buffer = null;\n await this.bytes.close(this.id);\n });\n }\n\n private inTurn(work: () => Promise<void>): Promise<void> {\n const done = this.turn.then(work);\n this.turn = done.catch(() => {});\n return done;\n }\n\n private async drain(): Promise<void> {\n if (!this.buffered || !this.buffer) return;\n const part = this.buffer.slice(0, this.buffered);\n await this.bytes.append(this.id, this.stored, part);\n this.stored += part.length;\n this.buffered = 0;\n }\n}\n","import { NO_PICTURE_METADATA, PICTURE_METADATA_LIMITS, audioMetadataPatches, isStrippedPicture, stripPictureMetadata, videoMetadataPatches, withoutAudioMetadata, withoutVideoMetadata, type VideoPatch } from \"@ghostly/core\";\nimport { FileAppender, storedSize } from \"../shared/storedFiles\";\nimport { SMALL_FILE_BYTES, blobDigest, fileBytes, fileBytesOf } from \"../shared/fileBytes\";\nimport { errorLine, fileStore, type StoredFile } from \"../shared/idb\";\nimport type { MessageFile, StoredMessage } from \"../shared/types\";\n\n/*\n * Forwarding (WISP 400 § Forwards): messages of one chat sent on to others, each as a new message of mine that says\n * only how many times it has been forwarded. A text goes as it was written (its Markdown source, its link preview); a\n * file goes from the bytes already on this device, copied for the new chat, never fetched again.\n */\n\n/** At most this many chats at once, as WhatsApp does: forwarding is for a few people, not a broadcast. */\nexport const FORWARD_TARGETS = 5;\n/** At most this many messages at once. */\nexport const FORWARD_MESSAGES = 30;\n\n/** What each chat forwarded to got: the new messages' ids, in order, and the first problem, if any. */\n/**\n * What one chat or group got of a forward: the new messages (`messageIds`), the forwarded ones they came from\n * (`sent`, their ids in the chat forwarded from) and the first problem. A chat that got part of it is sent only the\n * rest the next time (agents#1082).\n */\nexport interface ForwardResult { to: string; messageIds: string[]; sent: string[]; error: string | null }\n\n/**\n * Whether a message can be forwarded, and as what. Payments and payment requests (a bearer token or a request is for\n * the chat it was made in), a group's history lines and its payment notes cannot; neither can a message with nothing\n * in it. Identity shares and call lines are not messages here at all.\n */\nexport function forwardKind(message: StoredMessage): \"text\" | \"file\" | { refused: string } {\n if (message.sender !== \"me\" && message.sender !== \"peer\") return { refused: \"This message cannot be forwarded\" };\n if (message.paymentId) return { refused: \"Payments and payment requests cannot be forwarded\" };\n if (message.event || message.groupPay) return { refused: \"This line cannot be forwarded\" };\n if (message.file) return \"file\";\n return message.text.trim() ? \"text\" : { refused: \"This message cannot be forwarded\" };\n}\n\n/**\n * Why a chat did not get a forward, as its result says it: never \"\" (a result with an error is a failure, whatever it\n * says). A copy that found no room says so in the words the app knows however the storage put it: IndexedDB's\n * QuotaExceededError (an empty message in Chromium), the OPFS worker's (named so), Desktop's io error (the system's English).\n */\nexport function forwardError(error: unknown): string {\n const message = (error instanceof Error ? error.message : String(error)).trim();\n if (/^No space left on device\\b/.test(message)) return `Not enough space on this device (${message})`;\n const name = (error as { name?: unknown } | null)?.name;\n return errorLine(error).trim() || (typeof name === \"string\" && name ? name : \"Error\");\n}\n\n/** How many bytes of a stored file are actually here: all of them once it arrived. */\nasync function bytesHere(file: StoredFile): Promise<number> {\n if (file.blob) return file.blob.size;\n const bytes = file.bytes ? await fileBytesOf(file.bytes) : null;\n return (await bytes?.size(file.id)) ?? 0;\n}\n\ntype Read = (offset: number, length: number) => Promise<Uint8Array>;\n\n/** `read` with the parts `patches` replace (zeros where a patch has no bytes). */\nfunction patchedRead(read: Read, patches: VideoPatch[]): Read {\n return async (offset, length) => {\n const part = (await read(offset, length)).slice();\n const end = offset + part.length;\n for (const { start, end: until, bytes } of patches) {\n if (until <= offset || start >= end) continue;\n const from = Math.max(start, offset), to = Math.min(until, end);\n if (bytes) part.set(bytes.subarray(from - start, to - start), from - offset);\n else part.fill(0, from - offset, to - offset);\n }\n return part;\n };\n}\n\n/**\n * A received picture, video, audio file or voice note as it goes on: without its metadata (one from an app that sent\n * it with them keeps where its author took it, the device, the time, an audio file's tags), as one sent from here;\n * undefined for any other file, copied as it is. A picture is read whole; a video's or an audio file's stripped bytes\n * are a Blob when it is kept in one, else read through the parts changed. Refused with `NO_PICTURE_METADATA`,\n * `NO_VIDEO_METADATA` or `NO_AUDIO_METADATA` when its metadata cannot be removed.\n */\nasync function withoutMetadata(source: StoredFile, size: number, file: MessageFile, read: Read): Promise<Blob | Read | undefined> {\n if (!size) return undefined;\n if (file.video || file.voice || !isStrippedPicture(await read(0, Math.min(PICTURE_METADATA_LIMITS.headBytes, size)), file.mime)) {\n if (source.blob) return await withoutVideoMetadata(source.blob, file.mime) ?? await withoutAudioMetadata(source.blob, file.mime);\n // A whole box at a time: a storage's read can return fewer bytes than asked before the end.\n const readFully: Read = async (offset, length) => {\n const whole = new Uint8Array(Math.max(0, Math.min(length, size - offset)));\n for (let at = 0; at < whole.length;) {\n const part = await read(offset + at, whole.length - at);\n if (!part.length) break;\n whole.set(part, at);\n at += part.length;\n }\n return whole;\n };\n const patches = await videoMetadataPatches({ size, read: readFully }, file.mime) ?? await audioMetadataPatches({ size, read: readFully }, file.mime);\n return patches && patchedRead(read, patches);\n }\n if (size > PICTURE_METADATA_LIMITS.maxBytes) throw new Error(NO_PICTURE_METADATA);\n const whole = new Uint8Array(size);\n for (let offset = 0; offset < size;) {\n const part = await read(offset, Math.min(1024 * 1024, size - offset));\n if (!part.length) throw new Error(\"The file is shorter than it says\");\n whole.set(part, offset);\n offset += part.length;\n }\n return new Blob(stripPictureMetadata(whole, file.mime) as BlobPart[], { type: source.blob?.type ?? file.mime });\n}\n\n/** What a forward of a message deleted meanwhile says, whether it went before the forward or while its file was copied. */\nexport const FORWARD_MESSAGE_GONE = \"That message is not in this chat\";\n\ntype ForwardTarget = { linkId: string; wireId: string; timestamp: number; file: MessageFile };\n\n/**\n * A copy of a file on this device, for sending in another chat under `file.id`: a small one whole, a larger one a\n * step at a time, never whole in memory; a picture without its metadata, read whole, and a video or an audio file\n * without its. Refused while it is still arriving, or when its bytes are gone. Resolves to `file` as it goes: a\n * stripped file's size is its copy's.\n *\n * A copy cut off because its source went meanwhile says why, as one started after would: its message deleted (here, or\n * for everyone by its sender, which takes its file: `messageGone`, asked only once the copy failed) is\n * `FORWARD_MESSAGE_GONE`, its record gone with the message still here is \"not on this device any more\". Only bytes\n * missing from a source still kept whole on record stay \"shorter than it says\".\n */\nexport async function copyForForward(sourceId: string, target: ForwardTarget, messageGone?: () => Promise<boolean>): Promise<MessageFile> {\n try {\n return await copyFile(sourceId, target);\n } catch (error) {\n if (await messageGone?.().catch(() => false)) throw Object.assign(new Error(FORWARD_MESSAGE_GONE), { cause: error });\n if (!(await fileStore.get(sourceId).catch(() => ({ metadata: true })))?.metadata) throw Object.assign(new Error(\"The file is not on this device any more\"), { cause: error });\n throw error;\n }\n}\n\nasync function copyFile(sourceId: string, target: ForwardTarget): Promise<MessageFile> {\n const source = await fileStore.get(sourceId);\n if (!source?.metadata) throw new Error(\"The file is not on this device any more\");\n const stored = storedSize(source);\n // One arriving with files/3, or a group's, is whole only once its digest checked out (a group's desk says so once it\n // did: a holder can leave bytes of the whole size that are not the author's); any other is whole when all its bytes are here.\n const checked = source.wire3 ? source.wire3.state === \"done\" : !source.group || source.transfer?.state === \"done\";\n if (source.direction === \"in\" && !checked || await bytesHere(source) !== stored)\n throw new Error(\"The file has not arrived yet\");\n const from = source.bytes ? await fileBytesOf(source.bytes) : null;\n const read: Read = async (offset, length) => source.blob ? new Uint8Array(await source.blob.slice(offset, offset + length).arrayBuffer()) : from!.read(source.id, offset, length);\n // The bytes it is copied from, and their digest: the stripped copy's, computed on what is sent, never the original's.\n const stripped = await withoutMetadata(source, stored, target.file, read);\n const blob = typeof stripped === \"function\" ? undefined : stripped ?? source.blob, size = blob && stripped ? blob.size : stored;\n const readCopy = typeof stripped === \"function\" ? stripped : read;\n const known = stripped ? undefined : source.digest;\n const { linkId, wireId, timestamp } = target, file = stripped ? { ...target.file, size } : target.file;\n const metadata = { name: file.name, size: file.size, mime: file.mime, timestamp, voice: file.voice, video: file.video, image: file.image };\n const record = { id: file.id, linkId, createdAt: timestamp, direction: \"out\" as const, wireId, metadata, transfer: { state: \"transferring\" as const, transferred: 0, size: file.size } };\n if (size <= SMALL_FILE_BYTES && blob) {\n // Its bytes in a Blob of its own: WebKit keeps a stored Blob as one file, and a slice of the original would share it,\n // gone for both once either record is deleted (see `fileStore`).\n const copy = new Blob([await blob.slice(0, size).arrayBuffer()], { type: blob.type });\n const digest = known ?? (stripped ? await blobDigest(copy) : undefined);\n await fileStore.put({ ...record, blob: copy, ...(digest && { digest }) });\n return file;\n }\n const bytes = await fileBytes();\n try {\n const appender = new FileAppender(bytes, file.id);\n for (let offset = 0; offset < size;) {\n const part = blob ? new Uint8Array(await blob.slice(offset, offset + 1024 * 1024).arrayBuffer()) : await readCopy(offset, Math.min(1024 * 1024, size - offset));\n if (!part.length) throw new Error(\"The file is shorter than it says\");\n await appender.append(part);\n offset += part.length;\n }\n await appender.close();\n // The same bytes, so the same digest: read back only when the original never had one written down (or was stripped).\n const digest = known ?? await bytes.digest(file.id);\n await fileStore.put({ ...record, bytes: bytes.kind, digest });\n return file;\n } catch (error) {\n await bytes.remove(file.id).catch(() => {});\n throw error;\n }\n}\n","import type { CommunityMessageFrame, DiscoveryStatus, GroupEditFrame, GroupMention, GroupMessageFrame, ImageMeta, LinkPreview, PairingProgress, PaymentMethodName, PersonStatus, Presence, RoutineCard, StatusCard, TaskCard, TypingKind, UsageCard, VideoMeta, VoiceMeta, WirePin, WireReaction } from \"@ghostly/core\";\nimport type { UsdtWalletView } from \"../engine/paymentAdapters/usdtWallet\";\nimport type { ArkWalletView } from \"../engine/paymentAdapters/arkWallet\";\nimport type { BarkWalletView } from \"../engine/paymentAdapters/barkWallet\";\nimport type { FedimintWalletView } from \"../engine/paymentAdapters/fedimintWallet\";\nimport type { SparkWalletView } from \"../engine/paymentAdapters/sparkWallet\";\nimport type { LightningView } from \"../engine/paymentAdapters/providers/lightningService\";\nimport type { LightningCardView } from \"../engine/paymentAdapters/providers/lightningCards\";\nimport type { BitcoinView } from \"../engine/paymentAdapters/providers/bitcoinService\";\nimport type { Removal } from \"../engine/removals\";\nimport type { PaymentReview, PaymentTarget, VapidKeys, WakeTarget, WalletNetwork } from \"@ghostly/core\";\nimport type { ProviderDescriptorView } from \"../engine/paymentAdapters/providers/types\";\nimport type { CapsState, DeliveryMode, DhtDeliveryState, DhtDeliveryView, HoldKind, RatchetState } from \"@ghostly/core\";\nimport type { S3Config } from \"../backup/s3\";\nimport type { BackupReminders } from \"./backupReminder\";\nimport type { TransportCause, TransportEntry, TransportEvent } from \"../engine/transportLog\";\nimport type { PublicProfile, ProfileChoice } from '../profiles/public';\nimport type { NostrContactCache, NostrContactView, NostrSocialSettings, NostrSocialState } from \"../nostr/types\";\nimport type { ProofLedger, ProofAdapter } from \"@ghostly/core\";\nimport type { IdentityDisplay, IdentityLedger, IdentityStatus, IdentityTimelineEntry, SharedIdentity, VerifiedIdentity } from \"@ghostly/core\";\nimport type { DataLinkState, LinkStatus, LiveAttempt, ServiceAd, PairingState, NativeTransport, PairedTransport, TransportDescriptors, TransportWait } from \"@ghostly/core\";\nimport type { CommunityState, GroupByeFrame, GroupCommit, GroupRole, GroupState, GroupStatus } from \"@ghostly/core\";\n\n/** A reaction to a message not here yet (WISP 401 § Reactions), from `by`, waiting for it until `until`. */\nexport interface WaitingReaction { by: string; reaction: WireReaction; until: number }\n\n/** A link as stored in IndexedDB. Same fields Desktop keeps in its ChatSession. */\nexport interface StoredLink {\n /**\n * Paired 1:1 chats: how to wake the contact's closed web app, as it shared it (`wake/1`, WISP 401 § Wake-up push).\n * Absent until it does, and again once it stops sharing or its push service says the subscription is gone.\n */\n peerWake?: WakeTarget;\n /** Paired 1:1 chats: this side's token for this chat in its own wake-ups; a new one whenever the subscription changes. */\n wakeToken?: string;\n /** Paired 1:1 chats: muted here, so the contact is told to forget this side's subscription until it is unmuted. */\n wakeMuted?: boolean;\n /** Paired 1:1 chats: when this side last told the contact it came online (an online wake-up), for the 30-minute limit. */\n onlineWokeAt?: number;\n deliveryMode?: DeliveryMode;\n dhtDeliveryState?: DhtDeliveryState;\n /**\n * Paired 1:1 chats: the ratchet of the DHT floor and held items (WISP 4xx). State of this device only: never in a\n * backup or a handoff (`profileBackup.ts`), and dropped by a forced takeover (`raisedLink`).\n */\n ratchetState?: RatchetState;\n /** This side's layer-0 capability record and the contact's last good one (WISP 03). */\n capsState?: CapsState;\n publicProfiles?: PublicProfile[];\n profileChoice?: ProfileChoice;\n peerProofs?: ProofLedger;\n /** Identity proofs shared in this chat, both ways (WISP 300). */\n identities?: IdentityLedger;\n /** The contact's Nostr profile, follows and notes, cached under their proven key, loaded only on request. */\n nostrSocial?: Record<string, NostrContactCache>;\n profile?: \"paired-chat/1\";\n participationSeed?: string;\n transportSeeds?: Partial<Record<NativeTransport, string>>;\n peerDescriptors?: TransportDescriptors;\n peerTransports?: PairedTransport[];\n peerFallback?: boolean;\n /** Absent: no choice for this chat, the app's rule applies (\"Automatic\"). */\n preferredTransport?: PairedTransport;\n transportFallback?: boolean;\n /** The chat's connection story, newest last (see engine/transportLog.ts). Local only. */\n transportLog?: TransportEntry[];\n /** Every connection event, for the connection panel, newest last (see engine/transportLog.ts). Local only. */\n transportHistory?: TransportEvent[];\n pairedPeerKey?: string;\n /** The inviter's participation key, from a `ghostly1` code (the joiner's side): the only key that may be pinned. */\n peerParticipationKeyZ32?: string;\n /** Absent only in old releases, where first pin required an explicit code comparison. */\n peerTrust?: { version: 1; verifiedKey?: string; verifiedAt?: number };\n requireSignedSignals?: boolean;\n id: string;\n seedB64: string;\n peerPubKeyZ32: string;\n encKeyB64: string;\n createdAt: number;\n label?: string;\n /**\n * The name the contact asked to be shown by, as they last said it. `\"\"` means a paired contact said they\n * have none (removed, or not shared); absent means nothing was heard yet.\n */\n peerNick?: string;\n /** The contact's profile picture, as they last sent it (checked, small JPEG data URL). */\n peerAvatar?: string;\n /** Present on the side that created the link, until the peer shows up. */\n inviteCode?: string;\n /**\n * A chat started by accepting a contact request (WISP 8xx § Accept), until its requester's app proves it holds the\n * request's asker key `key` (asked through `link`): the request's text, row `message`, shows as not confirmed till then.\n */\n contactAsker?: { link: string; key: string; message: string };\n /**\n * Messages deleted on this device, by id, so a republished one is not stored again: 500 at most, my deletions never\n * pushing out the contact's ids nor theirs mine (`withDeletedId`).\n */\n deletedIds?: string[];\n /**\n * 1:1 chats: the contact has had a row here in the words of the chat's joined line (a contact request's note aside),\n * so no later row of theirs is that line (`StoredMessage.joinLine`). Absent on a chat stored before it was kept: set\n * as the engine starts.\n */\n peerSpoke?: true;\n /** My messages I deleted for everyone, their removal on its way to the contact (`engine/removals.ts`). */\n removals?: Removal[];\n /**\n * The ids both sides know (`replyRef`) of the messages deleted for everyone, mine or the contact's, here or not, the\n * newest 500: a pin naming one shows as unpinned, the pin kept as it came and marked (`StoredPin.removed`), so no\n * later trimming brings it back (WISP 400 § Delete for everyone).\n */\n removedRefs?: string[];\n /**\n * Files of mine whose offer went on the DHT floor (WISP 403 § Files) and that were deleted here before they went live,\n * by wire id: the next session that carries files/3 says each is cancelled (`pf-abort`), so the contact's bubble does too.\n */\n withdrawnFiles?: string[];\n /** This side's reactions the contact has not confirmed yet (WISP 401 § Reactions), in the order of their numbers. */\n reactionsOut?: WireReaction[];\n /** The contact's reactions to messages not here yet, confirmed to them: kept here until their message lands or their wait ends. */\n reactionsWaiting?: WaitingReaction[];\n /** The chat's pinned message (WISP 400 § Pinned message): the latest pin, either side's; `id` \"\" once unpinned. */\n pin?: StoredPin;\n /** This side's pin the contact has not confirmed yet (WISP 401 § Pinned message): said on each live session until it does. */\n pinOut?: WirePin;\n /** Ways of paying this device allows in this chat. Absent or true: allowed. */\n paymentMethods?: Partial<Record<PaymentMethodName, boolean>>;\n /**\n * For a way of paying, the networks this chat accepts it on (its cards on the Accept side). Absent for a method:\n * every network. A request, a payment or an ask of a network off here is refused, and the contact is told.\n */\n paymentNetworks?: Partial<Record<PaymentMethodName, WalletNetwork[]>>;\n /** Store-and-forward for this contact (WISP 404, `hold/1`). Absent: off, as for every chat from before it. */\n hold?: HoldState;\n /** An edge of a private group (WISP 900): the group, and the member at the other end. Not a chat. */\n group?: string;\n groupPeer?: string;\n /**\n * Not an edge but an entry session of the group's link (`group-entry/1`): `host` on the admin's\n * side, toward a joiner's member key; `guest` on the joiner's, toward the link's entry key.\n */\n groupEntry?: \"host\" | \"guest\";\n /**\n * An edge whose session is up: set when it opens, cleared when it drops while this app runs (not when the app quits).\n * Still set when the app starts, it was live when the app last ran, and is dialled at once (`resume`). Local only.\n */\n edgeLive?: boolean;\n /** When that session opened: a member's offer from before it is not answered after a restart (`resumeFloor`). Local only. */\n edgeLiveSince?: number;\n}\n\n/** What happened to a group's membership, as a line in its history. */\nexport type GroupEvent = \"created\" | \"joined\" | \"gone\" | \"admin\" | \"rotated\" | \"removed\" | \"left\" | \"forked\" | \"picture\" | \"renamed\";\n\n/** A private group as stored: an invitation not yet answered, or a group I am (or was) in. */\n/** Another group under the id of one held (`StoredGroup.others`): a contact's invitation, or a group link opened. */\nexport type OtherGroup = { at: number; linkId: string; name: string; admin: string; e: number; n: number } | { at: number; link: string };\n\nexport interface StoredGroup {\n id: string;\n createdAt: number;\n /** Pending (or accepted, awaiting the welcome) invitation, on the invitee's side. */\n invitation?: {\n name: string;\n /** The inviter's member key, learned over the contact chat: the admin who must have admitted me. */\n admin: string;\n /** The contact chat it came over. */\n linkId: string;\n e: number;\n n: number;\n /** My member seed, once accepted. */\n seedB64?: string;\n /** Chain pieces that precede the welcome of a long chain. */\n pieces: { t: \"group-chain\"; g: string; commits: GroupCommit[] }[];\n /** Joining through the group's link: its entry key, the admin's side of `linkId` (an entry session, not a contact chat). */\n entry?: string;\n /**\n * Removed and invited again over a contact chat: the hash of the genesis of the chain I held. The id alone names no\n * group (anyone may sign a genesis under it): only a welcome whose chain starts there joins the history I kept.\n */\n genesis?: string;\n /**\n * Taken back by who sent it (`group-decline` over its chat), and when: kept a week so the list says so where the\n * invitation was, instead of it going with no word. Nothing is accepted or owed for it; another invitation replaces it.\n */\n takenBack?: number;\n };\n /**\n * On the admin's side: contact chats invited and not answered yet, and when. Kept so that an accept after my app\n * started again still lets them in.\n */\n invited?: Record<string, number>;\n /**\n * Members' messages their authors deleted for everyone (WISP 400 § Delete for everyone), by id, `MAX_REMOVED_IDS` at\n * most, each author's newest (`withRemovedId`): a copy that comes again (a catch-up, a member handing it on) is not stored again.\n */\n removedIds?: string[];\n /** My messages I deleted for everyone, their removal said to the members and again to an edge that opens (`engine/removals.ts`). */\n removals?: Removal[];\n /** On the admin's side: the group's link is on, with this entry key seed (`group-entry/1`). */\n entry?: { seedB64: string; createdAt: number };\n state?: GroupState;\n /** Member key → the contact chat that invited them (or me): the path for courtesy notices. */\n contacts?: Record<string, string>;\n /**\n * Members whose apps said (`paired-groups` version 3, on their edge or the link that admitted them) that they take\n * rosters past eight: an admin grows the group past eight only when every other member is here (WISP 902 § Bounds).\n */\n large?: string[];\n /**\n * On the admin's side: members I let in over a contact chat or the group's link whose edge has not come up with me\n * yet, so whose app may never have had the group's keys (its welcome lost on the way). A `group-decline` from that\n * chat takes such a member out again, and one that knocks on the link again gets its welcome again; one seen on an\n * edge once is a member, whatever its chat says after.\n */\n unseen?: string[];\n /**\n * Removed, then invited again over a contact chat: the names my app knew members by (member key → name). The history\n * stays while the invitation waits, and still names who wrote it; once in again, the names of members who are gone\n * since go on naming what they wrote.\n */\n formerNames?: Record<string, string>;\n /** Removed, then invited again: the removed group as it was, which a Decline puts back (with the history it kept). */\n previous?: StoredGroup;\n /**\n * Other groups that came under this id while it was held: an invitation over a contact chat from someone outside the\n * group held, or a link opened. A private group's id names no genesis (anyone who knows it may sign one under it), so\n * which of them is the real one is the person's to say: each is kept beside the group held until they pick\n * (`Groups.keepGroup`, `Groups.switchGroup`), and an inviter turned down hears a decline.\n */\n others?: OtherGroup[];\n /**\n * Past 16 members, with hubs (WISP 902 · Group Mesh § Hubs): the hubs I kept edges with (as a hub, the other hubs),\n * where my edges go when the app starts again, before the beacon is read.\n */\n hubs?: string[];\n /** Members whose edge came up without `paired-groups` version 4: their apps take no hubs, so hubs keep edges with them. */\n legacy?: string[];\n /**\n * I left: the group is gone from the list and its history from the device. What is kept is the\n * edge to the admin, until the admin's commit removing me arrives or `at` is a week old, so\n * a leave said while the admin was away still reaches it. With hubs, the edges to my hubs too, which carry my\n * signed leave (`bye`) to the admin. `bye` is kept without hubs too: opening the group's link again takes it along\n * (`owedBye`). An admin that leaves keeps its `farewells` here too, and the edges to them: `heard`, when the admin my\n * leave went to took it, and the tombstone stays for those farewells alone.\n */\n left?: { at: number; admin: string; hubs?: string[]; bye?: GroupByeFrame; heard?: number };\n /**\n * Left while the admin was away, then back by the group's link before it heard the leave: the signed leave of my old\n * key, said to the admin on my new key's edge, so it takes the old key out (it was in every roster twice for good,\n * agents#1652). Dropped once the old key is out of the roster, or a week after the leave.\n */\n owedBye?: GroupByeFrame;\n /**\n * I declined an invitation while its inviter's chat (`linkId`) was down: the answer is said when that chat is up, or\n * dropped once `at` is a week old. Alone when nothing else of the group is kept; beside `state` when the invitation\n * was to a group I was removed from, which stays; beside a join by the group's link opened after the decline (its\n * `invitation`, then its `state`), which stays too.\n */\n declined?: { at: number; linkId: string };\n /**\n * On the admin's side: members I removed while they could not be told (their edge was down, and no contact chat\n * carried the notice), by member key. `e`: the epoch of the commit that removed them; `at`: when. The edge to each\n * stays until it opens and that commit goes over it (`told`, the first time), or `at` is a week old: a member removed\n * while its app was closed otherwise never learns it, since every member closes the edge to someone out of the\n * roster. `opened`: when the edge's connection first opened; it closes a while after, told or not.\n */\n farewells?: Record<string, { at: number; e: number; told?: number; answered?: number; opened?: number }>;\n /** The group's pinned message (WISP 400 § Pinned message): the latest pin; `id` \"\" once unpinned. */\n pin?: StoredPin;\n /**\n * When the latest message of another member (`peer`) and the latest one that names me (`mention`) reached this\n * device, where that is later than the message's own time (`cameAt`): what makes the group unread survives a restart.\n */\n came?: { peer?: number; mention?: number };\n /**\n * Where `state.seq` was raised to when `state` was last written whole (`engine/groupRows.ts`), in epoch `e`: the numbers\n * below `n` are this app's to send at, and the group's small row (`GroupLive`) says how far it went. An app from before\n * reads `state` alone and sends from `n` on, above everything said here. A `state.seq` other than `n` is one such an app\n * wrote since.\n */\n seqReserved?: { e: number; n: number };\n /** A community group (`group-community/1`) I am in: its session state. Mesh groups use `state`. */\n community?: CommunityState;\n /**\n * Joining a community group through its link (`group2/…`), or again after my admission lost a\n * race: my member seed, the entry session, and what arrived of the welcome. `opened`: the entry key of the link a\n * member checking it still is opened, when that is not the door it asks (where it knocks once it learns it is out).\n */\n joining?: { g: string; host: string; seedB64: string; linkId: string; name: string; inviter: string; invitedAt?: number; pieces: unknown[]; since: number; check?: boolean; opened?: string; replaced?: boolean };\n}\n\n/**\n * What a message sent or received changes of a private group's state, in a row of its own (settings store,\n * `groupLiveKey`): written alone at each message, while the group's record (its chain, its secrets) is written only when\n * they change (`engine/groupRows.ts`). `top`: the signature of the last commit of the chain it goes with.\n */\nexport interface GroupLive {\n top: string;\n state: Pick<GroupState, \"seq\" | \"seqEpoch\" | \"seen\" | \"sent\" | \"alone\" | \"provisional\" | \"nicks\" | \"unsaid\">;\n came?: StoredGroup[\"came\"];\n}\n\n/**\n * What a pin, a deletion for everyone, a change of hubs or a member's edit changes of a private group's record, in a\n * row of its own (settings store, `groupLightKey`), apart from `GroupLive` so that a message does not write them too:\n * there while the record is behind on them, deleted each time the record is written whole (`engine/groupRows.ts`).\n * `hubs`: the record's (`StoredGroup.hubs`); absent in a row from before it was kept here, where the record's count.\n * `large`: the members noted in `StoredGroup.large` since the record was written, which the record's are added to.\n * `relayEdits`: the state's (`GroupState.relayEdits`); absent in rows from before it was kept here, whose record holds\n * them. `of`: what the record held of them when the row was written (a hash); a record that holds something else now\n * was written by an app from before since, and counts. Absent in rows from before it.\n */\nexport interface GroupLight { pin?: StoredPin; removedIds: string[]; removals: Removal[]; hubs?: string[]; large?: string[]; relayEdits?: GroupEditFrame[]; of?: string }\n\nexport interface GroupMemberView {\n key: string;\n role: GroupRole;\n me: boolean;\n nick?: string;\n /** The pairwise edge to this member is open, or a hub I am connected to reaches them (always true for me). */\n online: boolean;\n /** Reached through a hub, not an edge of mine (WISP 902 · Group Mesh § Hubs). */\n viaHub?: boolean;\n /** A hub of the group now (listed in its beacon), and what the admin said: pinned as a hub, or never one. */\n hub?: boolean;\n hubRole?: \"pin\" | \"exclude\";\n /** Messages of the current epoch known to be missing from this member. */\n missing: number;\n /** The pairwise edge to this member as the engine sees it: absent for me, and until the edge exists. */\n edge?: GroupEdgeView;\n}\n\n/** One edge of a group's mesh (WISP 902): a paired link toward one member, which carries the group to and from them. */\nexport interface GroupEdgeView {\n linkId: string;\n /**\n * `open`: frames flow (the member is reachable). `connecting`: the member answered and the channel is being set up.\n * `waiting`: nothing heard from the member's app yet. `error`: the last attempt failed (`error` says why).\n */\n state: \"open\" | \"connecting\" | \"waiting\" | \"error\";\n /** The transport carrying the edge while it is open: WebRTC, or Iroh or HyperDHT where one side has none. */\n transport?: PairedTransport;\n /**\n * Waiting because this device has no free native slot for it (a member reached over Iroh or HyperDHT, and the\n * device's native listeners held by chats and other group links): it is tried again as one frees up.\n */\n noSlot?: true;\n /**\n * When this device last heard from the member on this edge, in ms (0: never). While the edge is open, as of when it\n * opened (or of the member's latest packet read): the member is heard all along, and it stays the same from one state\n * to the next.\n */\n lastSeenAt: number;\n /** The engine's own words for why the last attempt failed (English, for logs and details); `cause` sums it up. */\n error?: string;\n /**\n * What `error` comes down to, for a short status: `relays`, its packets could not go out or be read (the Pkarr relays\n * failed); `session`, a connection opened and dropped in a way that says nothing about the member (it is dialled\n * again); `other`, anything else (a refused key, no common transport...).\n */\n cause?: GroupEdgeCause;\n /**\n * Down after it was live (in this run, or when the app last ran), for nothing the app can't get past: the app dials it\n * again by itself, at WISP 100's background pace, while the member is seen.\n */\n reconnecting?: true;\n /** When this side dials again by itself, in ms: set while it is the side that dials and its wait between attempts runs. */\n retryAt?: number;\n /** Automatic dials since the edge was last live or its wait started over, the one under way included. */\n attempt?: number;\n}\n\nexport type GroupEdgeCause = \"relays\" | \"session\" | \"other\";\n\n/**\n * How far a join through a group's link got, as the joiner can know it: the knock is being left,\n * it is there for the admin's app to read, that app opened the entry session, it let me in. Or a member's app\n * answered that there is no room yet (`group-full`, WISP 902 § A full group): `full`, or `blocked` while the group\n * waits for every member's app to take more than eight; the joiner goes on knocking. Or the welcome said the link was\n * replaced or turned off since it was shared (`replaced`): the knocking stops, and only the current link gets in.\n */\nexport type GroupJoinStage = \"knocking\" | \"knocked\" | \"answered\" | \"admitted\" | \"full\" | \"blocked\" | \"replaced\";\n\nexport interface GroupView {\n id: string;\n name: string;\n createdAt: number;\n /** Which kind of group: a private mesh of up to 32 (`group-mesh/1`) or a community (`group-community/1`). */\n profile: \"mesh\" | \"community\";\n /** Absent while it is only an invitation. */\n status?: GroupStatus | \"lost\";\n statusReason?: string;\n epoch?: number;\n myKey?: string;\n isAdmin: boolean;\n /**\n * Admin work is off for this group on this device (WISP 06 § Forced takeover): no commit is signed and no door duty\n * taken until the person turns on \"Manage groups from this device\" (`setGroupManage`).\n */\n adminOff?: true;\n members: GroupMemberView[];\n /** On the invitee's side, until the welcome arrives. */\n /**\n * `waiting`: joining a community through its link, how many others were knocking with me when I last knocked.\n * `othersKnocked`: joining a private group through its link, others knocked in its record lately (`KNOCK_REFRESH_MS`):\n * the admin's app may be busy letting them in, its relay budget spent, so the wait is not a sign it is closed.\n * `since`: joining a community through its link, when the knock started (a group kept here, knocking to get back in,\n * was created long before).\n * `admittedAt`: joining a community through its link, at stage `admitted`, when a member's app let me in. A welcome\n * lost there, and the link replaced before I knock again, is never said again: nobody reads the old link's knocks.\n * `full`: with stage `full` or `blocked`, the members the group has and the most it holds, as the answer said.\n * `unanswered`: accepted over a contact chat, said again as often as it is, and the inviter's app answered nothing\n * while that chat was up: the answer is offered again. Through a link (`viaLink`): nobody answered it for an hour of\n * this run (`JOIN_GIVE_UP_MS`), so the knocks stopped; accepting knocks again.\n * `takenBack`: who sent it took it back (the group is gone from its app, or the admin role from it): nothing to answer.\n * `kept`: an invitation to a group this device was in (removed, or left): that group and its history are kept under it,\n * and come back if it is declined.\n */\n invitation?: { linkId: string; contact: string; admin: string; members: number; accepted: boolean; unanswered?: boolean; takenBack?: boolean; kept?: boolean; viaLink?: boolean; stage?: GroupJoinStage; waiting?: number; othersKnocked?: boolean; since?: number; admittedAt?: number; full?: { n: number; max: number } };\n /**\n * Other groups that came under this one's id (a contact's invitation, or a link opened) while it was here: kept beside\n * it until the person picks the real one (`keepGroup`, `switchGroup` with the other's `linkId` or `link`).\n */\n others?: ({ linkId: string; contact: string; name: string; members: number } | { link: string })[];\n /** The group's link while it is on (`group1/<id>/<entry key>`); only the admin who made it sees it. */\n entryLink?: string;\n /**\n * The admin's link of a private group lets nobody in: knocks under it keep coming from keys whose app never answers,\n * and they hold the places a joiner is answered in. A new link (`enableGroupLink` with `reset`) ends it.\n */\n entryJammed?: true;\n /** Contacts (by chat id) invited by me and not yet in. */\n invited: string[];\n /** Contact chats that are members, by chat id → member key. */\n memberLinks: Record<string, string>;\n lastMessageAt: number;\n /** When the latest message from another member arrived (what makes the group unread; mine and membership lines do not); absent for none. */\n lastPeerMessageAt?: number;\n /** When the latest message that names me arrived; absent for none. */\n lastMentionAt?: number;\n /** The latest reaction in the group, for the chat list. */\n lastReaction?: ReactionNote;\n /** The group's pin (WISP 400 § Pinned message): `id` \"\" once unpinned; absent when nothing was ever pinned. */\n pin?: PinView;\n canSend: boolean;\n /** The group's picture (a JPEG data URL the engine checked), set by its admin; absent for none. */\n picture?: string;\n /**\n * The node that forwards a community group's calls, as its admin's statement names it (WISP 602); absent for none.\n * `e2ee: 1` when the group asks for sealed call media (WISP 602 § End-to-end encryption): an app that cannot seal\n * does not join.\n */\n call?: { sfu: string; e2ee?: 1 };\n /**\n * A private group past 16 members that runs on hubs (WISP 902 · Group Mesh § Hubs): `hub` when I am one. Absent for\n * the full mesh.\n */\n hubs?: { hub: boolean };\n /** Community groups: how this device is connected (a hub for others, or through hubs). */\n community?: {\n hub: boolean; hubs: number; connected: number;\n /**\n * Admin only: this many joiners lately were let in to an entry session that never came up on their side, enough that\n * the knocks may not be real people and real ones may not get in. A new link (`enableLink` with `reset`) ends it.\n */\n unansweredKnocks?: number;\n };\n /** Private groups: the members typing now, in the order they started (WISP 902 · Group Mesh § Typing). Never stored. */\n typing?: GroupTypingView[];\n /** Private groups: this side's wake-up tokens, one per member it shared its subscription with (the push worker's table). */\n wakeTokens?: string[];\n /** Private groups: its members were told not to wake this side while the group is muted (`setWakeMuted`). */\n wakeMuted?: boolean;\n /**\n * The names of authors no longer in the roster (removed, left, or back with a new member key), by\n * member key, so their earlier messages still say who wrote them. Absent when there are none.\n */\n formerNames?: Record<string, string>;\n}\n\n/** A member typing in a group: `kind` when it is not plain typing, and a bot's status line, sanitized as in a 1:1 chat. */\nexport interface GroupTypingView { key: string; kind?: Exclude<TypingKind, \"typing\">; status?: string }\n\n/** One item held in this device's storage for the contact, or on its way there. */\nexport interface HeldEntry {\n seq: number;\n /** The id on the wire: the text's wire id, the file's wire id or the payment id. */\n id: string;\n /** The chat message this item is, for its delivery state. */\n messageId: string;\n kind: Exclude<HoldKind, \"manifest\">;\n /** What to rebuild the bundle from: the file's local id or the payment id; text is on the message. */\n ref?: string;\n /** The object's name in storage, chosen before the first upload and kept across retries. */\n name: string;\n bytes: number;\n ts: number;\n expires: number;\n state: \"queued\" | \"held\" | \"failed\";\n error?: string;\n /**\n * The chat's ratchet session it was last sealed in (WISP 4xx), when ratcheted: once the ratchet seals in another one (the\n * contact moved to another device or restored), it is sealed again there. Absent: plain, or sealed by an older build.\n */\n sid?: string;\n}\n\n/** Everything store-and-forward keeps per chat: the switch, what the contact said, sequences and the outbox. */\nexport interface HoldState {\n /** This device offers `hold/1` in this chat: it accepts held items, and holds items for the contact when it can. */\n enabled: boolean;\n /** The contact's app accepts held items, as it last said (handshake or session). */\n peerAllows?: boolean;\n /** This device's mailbox folder for the contact in its storage, chosen once. */\n mailbox?: string;\n /** Sequence of the last item held for the contact. */\n outSeq: number;\n /** Highest sequence received from the contact and stored. */\n inSeq: number;\n /** Highest sequence the contact said it received of what was held for it. */\n peerAck: number;\n /** This device's pointer revision, and the contact's last seen one. */\n pointerRev: number;\n peerPointerRev: number;\n /** When the manifest and its addresses were last signed (they live seven days). */\n manifestSignedAt?: number;\n outbox: HeldEntry[];\n /** Items from the contact refused on the way in (changed, oversized, not for this chat). */\n refused: number;\n /** Their sequences, the last 32, told to the contact on this device's pointer. */\n refusedSeqs?: number[];\n /** Ways of paying the contact allowed at the last session, for requests held while it is away. */\n peerPaymentMethods?: PaymentMethodName[];\n}\n\n/** A file attached to a message. The bytes live in the `files` store under `id`. */\nexport interface MessageFile {\n id: string;\n name: string;\n size: number;\n mime: string;\n /** A voice message: its length and the shape of its sound. */\n voice?: VoiceMeta;\n /** A video: its length, size and a small first frame, when the sender sent them. */\n video?: VideoMeta;\n /** A picture: its size as it is shown, when the sender sent it. */\n image?: ImageMeta;\n}\n\nexport interface FileTransferView {\n state: \"transferring\" | \"done\" | \"failed\";\n transferred: number;\n size: number;\n error?: string;\n /**\n * files/3 (WISP 501 rev 0.3), while `transferring`: where it stands when it is not moving. `waiting`: no live\n * connection (it goes on by itself); `asking`: the receiver's person has not decided (on the receiving side,\n * this person); `queued`: accepted, waiting its turn; `paused`; `verifying`: every byte there, checking the digest.\n */\n stage?: \"preparing\" | \"waiting\" | \"asking\" | \"queued\" | \"paused\" | \"verifying\";\n /** files/3: the transfer can be paused, resumed and cancelled from here. */\n direction?: \"in\" | \"out\";\n pausedBy?: \"me\" | \"peer\";\n /** Bytes per second lately, while moving. */\n rate?: number;\n /** Receiving, `asking`: bytes this device can still take for files, when it says. */\n room?: number | null;\n /** Failed but the sender can offer it again (files/3). */\n retry?: boolean; /**\n * files/3, unfinished and not moving for a while (or not since the app started): the sender can send it again\n * (`resend`), the receiver ask for it again (`request`). Either goes on from what the receiver holds.\n */\n stalled?: boolean;\n /**\n * A group file (WISP 503) waiting, `waiting`: why. `nobody`: nobody this device is connected to has it; `author`: only\n * its author holds it, a member this device has no edge with (a private group on hubs: it comes once a hub holds it);\n * `busy`: its holders answered busy; `damaged`: what came failed the author's digest (`stalled`: its person can ask again).\n */\n wait?: \"nobody\" | \"author\" | \"busy\" | \"day\" | \"damaged\";\n /** The same, in a few words (\"Nobody you are connected to has this file yet\"). */\n note?: string;\n}\n\n/** Ecash held by this peer. One row per proof; `reserved` while an operation is using it. */\nexport interface StoredProof {\n mint: string;\n id: string;\n amount: number;\n secret: string;\n C: string;\n dleq?: unknown;\n /** Handed to the mint for a Lightning payment that has not settled: not spendable, not yet gone. */\n reserved?: boolean;\n /**\n * Brought back by a profile restore: a copy of ecash as it was when the backup was made, which the profile it was\n * copied from (or this one, before the backup was restored) may have spent since. The mint is asked once, and a\n * proof it reads spent is dropped (see `CashuWallet.checkRestored`).\n */\n unchecked?: boolean;\n}\n\n/** A Lightning payment the mint has not settled yet. Its proofs stay in the wallet, reserved, until it does. */\nexport interface PendingMelt {\n /** The melt quote id. */\n quote: string;\n mint: string;\n /** The invoice, so it is not paid a second time while this one is in flight. */\n request: string;\n /** What the invoice pays. */\n amount: number;\n /** The reserved proofs handed to the mint. */\n secrets: string[];\n /** Everything that left the balance for this payment: the proofs above plus any swap fee. */\n outlay: number;\n /** NUT-08 blank outputs (`OutputData.serialize`), to unblind the fee change once the mint returns it. */\n outputs: unknown[];\n note?: string;\n /** Set when the invoice pays a contact's payment request. */\n paymentId?: string;\n createdAt: number;\n /** Came with a restored copy of the profile: its change is as old as the copy, and is checked like the copy's ecash. */\n restored?: boolean;\n}\n\n/**\n * A swap at a mint, written down before the mint is asked, with everything that finishes it: the mint signs the\n * outputs of `swap` and nothing else, so its signatures can be asked for again (NUT-09) for as long as this is kept.\n * Deleted in the transaction that stores what the swap brought, or once the mint says it never happened.\n */\nexport interface PendingSwap {\n id: string;\n mint: string;\n /** `receive`: a token redeemed into this wallet. `send`: this wallet's ecash split, for a token or a Lightning payment. */\n kind: \"receive\" | \"send\";\n /** cashu-ts' `SerializedSwapPreview`: the inputs and the blinded outputs with their secrets. As secret as the ecash itself. */\n swap: unknown;\n createdAt: number;\n /** When the request to the mint ended with no answer. The mint may still act on it for a moment after that. */\n attemptEndedAt?: number;\n /**\n * The inputs were given back (the swap was overdue with nothing signed), and it holds nothing any more. Still asked\n * about for a while: a request that reached the mint late is recovered from what is written here.\n */\n released?: boolean;\n /** What it brought is stored; only the chat of its payment is still to be told (the app closed in between). */\n finished?: boolean;\n /**\n * Its inputs read spent at a mint that cannot say what it signed (no NUT-09): how many times that was the answer.\n * Kept, since the outputs are the only way back to that ecash, and asked about less and less often (`askAt`).\n */\n stuck?: number;\n /** Not asked about before this time. */\n askAt?: number;\n /** Came with a restored copy of the profile: what it brings is as old as the copy, and is checked like the copy's ecash. */\n restored?: boolean;\n /** `receive`: the token being redeemed. Redeeming it again while this is kept finishes this swap, and makes no other. */\n token?: string;\n /** `receive`: the history line of the ecash, written with it. */\n tx?: WalletTx;\n /** `receive`: the payment record written with the ecash (a contact's payment received, or one of ours taken back). */\n payment?: StoredPayment;\n}\n\n/** A Lightning invoice the mint issued for us; paid invoices turn into ecash. */\nexport interface StoredQuote {\n quote: string;\n mint: string;\n amount: number;\n invoice: string;\n createdAt: number;\n expiresAt: number | null;\n /** Set when the invoice belongs to a payment request sent to a peer. */\n paymentId?: string;\n /**\n * The mint says it issued this quote's ecash, but the wallet never stored it. Kept, not polled: it is the\n * only record of sats the user paid for.\n */\n issuedUnclaimed?: boolean;\n /** The mint said this invoice is paid, and its ecash is not claimed yet (the claim is tried again every round). */\n paid?: boolean;\n /**\n * The mint marks its invoices paid by itself (a test mint, `paysItsOwnInvoices`): its \"paid\" says nothing about a\n * payer. Not polled, never minted by itself: a payer saying it paid (`CashuWallet.vouch`) lets it be minted.\n */\n held?: boolean;\n /** Asked for on purpose, as test coins from a test mint (\"Get test coins\"): minted as soon as the mint says paid. */\n testCoins?: boolean;\n /**\n * The blinded outputs the mint is asked to sign for this invoice (`OutputData.serialize`), written down before it\n * is asked: the ecash it issues is for these, and its signatures for them can be asked for again (NUT-09).\n */\n outputs?: unknown[];\n /** Came with a restored copy of the profile: its ecash is as old as the copy, and is checked like the copy's ecash. */\n restored?: boolean;\n}\n\nexport type PaymentState =\n | \"pending\" // sent, no word from the peer yet / request waiting to be paid\n | \"settled\"\n | \"failed\"\n | \"reclaimed\"; // the peer never took the ecash and it is back in the wallet\n\n/** A payment or payment request in a chat, by id. */\nexport interface StoredPayment {\n /** A request made because the contact asked to pay (its `pay-ask` id), or, on the payer's side, the ask it answers. */\n ask?: string;\n target?: PaymentTarget;\n txid?: string;\n id: string;\n linkId: string;\n kind: \"payment\" | \"request\";\n direction: \"in\" | \"out\";\n amount: number;\n unit: string;\n memo?: string;\n state: PaymentState;\n error?: string;\n createdAt: number;\n mint?: string;\n /** Outgoing ecash, kept until the peer confirms so it can be reclaimed. */\n token?: string;\n /** Requests: how the payer can pay. */\n invoice?: string;\n mints?: string[];\n /**\n * Real money or test coins: only a wallet of this network pays a request, or made a payment. Absent on records\n * from before wallets had their own network: its target, mints or invoice say (see `paymentNetwork`).\n */\n network?: WalletNetwork;\n /** Fedimint requests: the federations the payee takes ecash of (their ids). */\n federations?: string[];\n /** Fedimint payments: the federation of the notes, and the client operation that spent (or redeems) them. */\n federation?: string;\n fedimintOp?: string;\n /** Incoming Fedimint payments: a digest of the notes, kept after they are redeemed or refused, so the same notes sent again under another id are answered from it. */\n notesDigest?: string;\n requestId?: string;\n /** Requests we pay: a Lightning payment is in flight at the mint, so paying again would pay twice. */\n lightningPending?: boolean;\n /** Requests we pay: this device paid it over Lightning (the payee's wallet cannot say who paid an invoice). */\n paidHere?: boolean;\n /**\n * Requests we pay: the payee said it is paid (its `pay-res` ok), so its wallet has seen the money and our receipts\n * for it (on-chain, Ark, Bark, Spark, USDT) are not said again when the chat reconnects. Absent: not heard yet, or a\n * record from before this was kept (see `PaymentDesk.receiptOwed`).\n */\n payeeConfirmed?: boolean;\n /**\n * A request to a whole group (WISP 902 § Payments): the group's id. Its `linkId` is `group:<id>`, it went to\n * every member over their edges, and the first member whose payment settles it pays it; later ones are refused.\n */\n group?: string;\n /**\n * A request closed by the one who made it (their wallet for it was removed): it can no longer be paid, and a\n * payment still made to what it named is lost. Set on both sides, with `state` \"failed\".\n */\n closed?: boolean;\n}\n\n/** What pages see of a payment: everything but the token. */\nexport type PaymentView = Omit<StoredPayment, \"token\">;\n\nexport interface MintView {\n url: string;\n name: string;\n balance: number;\n /** Null until the mint answered once. */\n info: MintInfoView | null;\n /** What it still waits for (see `mintAwaiting`), when it does: removing it asks about these first. */\n awaiting?: WalletAwaitingView[];\n}\n\n/** What a mint says about itself and what it charges. */\n/** What a pasted piece of ecash says about itself. Mirrors `CashuInspection` in the UI's platform contract. */\nexport type CashuInspection =\n | { kind: \"token\"; amount: number; unit: string; mint: string; memo?: string; accepted: boolean }\n | { kind: \"request\"; amount: number | null; unit: string; mints: string[]; description?: string };\n\nexport interface MintInfoView {\n version?: string;\n motd?: string;\n /**\n * Fee for spending ecash, in sats per thousand proofs (NUT-02). A swap,\n * a redeem or a Lightning payment spends a handful of proofs and is charged\n * the sum, rounded up. 0 means spending ecash is free.\n */\n inputFeePpk: number;\n /** Lightning in and out: allowed amounts in sats, null when the mint sets no bound. */\n receive: { min: number | null; max: number | null } | null;\n send: { min: number | null; max: number | null } | null;\n}\n\nexport type WalletTxKind =\n | \"lightning-in\"\n | \"lightning-out\"\n | \"ecash-in\" // from a contact, or a pasted token\n | \"ecash-out\"\n | \"reclaimed\"\n | \"fee\"; // a Lightning payment failed, and the mint kept its fee for preparing it (`amount` 0)\n\n/** One movement of the wallet. `fee` is exact: what left the balance beyond `amount`, or what a redeem cost. */\nexport interface WalletTx {\n id: string;\n timestamp: number;\n mint: string;\n kind: WalletTxKind;\n /** Sats that moved, always positive; the kind gives the direction. */\n amount: number;\n fee: number;\n note?: string;\n /** `lightning-in`: the mint quote of the invoice paid, so the invoice on screen knows it is the one. Absent on older records. */\n quote?: string;\n}\n\n/** The kinds of wallet a profile can have: each is one card of the deck, on one network. */\nexport type WalletType = \"cashu\" | \"lightning\" | \"arkade\" | \"bark\" | \"spark\" | \"bitcoin\" | \"fedimint\" | \"usdt\";\nexport const WALLET_TYPES: readonly WalletType[] = [\"cashu\", \"lightning\", \"arkade\", \"bark\", \"spark\", \"bitcoin\", \"fedimint\", \"usdt\"];\n\n/** One network's wallets, whole: what `WalletView` shows of the network in use, for either network. */\nexport interface NetworkWalletsView {\n ark?: ArkWalletView;\n bark?: BarkWalletView;\n fedimint?: FedimintWalletView;\n spark?: SparkWalletView;\n usdt?: UsdtWalletView;\n /** The network's default Lightning card for receiving (what a caller from before cards reads as its Lightning). */\n lightning?: LightningView;\n /** Every Lightning card of the network, in the order they were added: each its own source, balance and history. */\n lightnings?: LightningCardView[];\n bitcoin?: BitcoinView;\n /** This network's Cashu mints (test mints and mints on this machine are Testnet's). */\n mints: MintView[];\n balance: number;\n /** Cashu: sats held for a payment or a swap the mints have not settled yet. Not in `balance`, and not gone. */\n setAside?: number;\n /** Cashu: swaps at these mints that are not finished yet, and the sats in them. Removing the wallet names them. */\n openSwaps?: number;\n swapsAmount?: number;\n /** Cashu: sats in swaps whose inputs read spent at a mint that cannot say what it gave for them. Not in `setAside`. */\n unconfirmed?: number;\n /** This network's history, newest first. */\n history: WalletTx[];\n feesPaid: number;\n /** What this network's wallets still wait for: removing one reads it (see `walletRemoval`). Always set by the engine. */\n awaiting?: WalletAwaitingView[];\n}\n\n/**\n * Something one wallet still waits for. `request`: a request of ours still open in a chat that only this wallet can\n * be paid through; `invoice`: an invoice of its own, not paid and not expired; `paid`: an invoice the mint says is\n * paid whose ecash is not claimed yet; `unclaimed`: ecash the mint says it issued for an invoice of ours that this\n * wallet never received; `sent`: ecash sent from it that the contact has not taken yet. Removing the wallet loses\n * what is paid to the first four; `sent` Cashu comes back once its mint is added again.\n */\nexport interface WalletAwaitingView {\n /** The wallet it goes through (Lightning through the Cashu mints is the Cashu wallet's). */\n type: WalletType;\n /** `swap`: sats in an exchange with a Cashu mint that the mint has not settled yet (`PendingSwap`). */\n kind: \"request\" | \"invoice\" | \"paid\" | \"unclaimed\" | \"sent\" | \"swap\";\n /** In the wallet's base unit: sats, or the token's smallest unit for USDT. */\n amount: number;\n /** The chat payment it belongs to, when it does. */\n paymentId?: string;\n /** Lightning: the card it goes through. */\n card?: string;\n /**\n * `sent`: its bubble, with the chat's Take it back, is in no chat that can be opened: the chat it went in was deleted\n * since (or joined again by the same invite, without its old history), or its group is gone. The Wallet page offers\n * it instead. A group member who left, whose edge closed, leaves the bubble in the group: not this.\n */\n chatGone?: true;\n}\n\n/**\n * A wallet the profile has: one type on one network, one of each but Lightning, which a network can have several\n * cards of. `id` is `<type>:<network>`, and `lightning:<network>:<card>` for a Lightning card. Its seed and secrets\n * stay in the engine; `config` holds only what can be shown (a server, a source).\n */\nexport interface WalletInstanceView {\n id: string;\n type: WalletType;\n network: WalletNetwork;\n config: Record<string, string>;\n /** Lightning: the card's id on its network, its name, and whether it is the network's default for receiving. */\n card?: string;\n name?: string;\n receive?: boolean;\n /**\n * At home on another device (WISP 06 § Wallets that stay home): that device's name (\"\" when this device does not know\n * it), and when its coins expire (Ark, Bark). It is never opened here, and takes no payment here.\n */\n home?: { device: string; expiresAt?: number };\n}\n\n/**\n * What New can make: one type on one network. `available` false: `reason` says why (Mainnet not validated yet,\n * one already there). `needs`: the one thing it asks for, when it cannot be made in one click.\n */\nexport interface WalletOffer {\n type: WalletType;\n network: WalletNetwork;\n available: boolean;\n reason?: string;\n /** Already made: its card is in the deck. */\n exists?: boolean;\n /** A network can have several of it (Lightning): New adds one more, whatever `exists` says. */\n several?: boolean;\n needs?: \"invite\" | \"provider\" | \"apiKey\";\n /** Lightning and on-chain: the sources that can be picked on this network. */\n providers?: ProviderDescriptorView[];\n}\n\n/** What New asks the engine to make (see `walletCreate`). */\nexport interface WalletCreate {\n type: WalletType;\n network: WalletNetwork;\n /** Lightning and on-chain: the source, and the values of its form (blank ones take the network's default). */\n providerId?: string;\n values?: Record<string, string>;\n /** Fedimint: the federation's invite code. */\n invite?: string;\n /** Spark on Mainnet: the person's Breez API key. */\n apiKey?: string;\n}\n\n/** What Remove asks the engine to take away (see `walletRemove`). */\nexport interface WalletRemove {\n type: WalletType;\n network: WalletNetwork;\n /** Lightning: the card to remove; absent, the network's default for receiving. */\n card?: string;\n /** The person confirmed that what it holds on this device becomes unreachable without its backup. */\n acceptLoss?: boolean;\n}\n\n/** \"Get test coins\" on a Testnet wallet: which one asks its faucet. */\nexport interface WalletTestCoins {\n type: WalletType;\n network: WalletNetwork;\n /** Lightning: the card asking (only the Cashu mints' card has a faucet); absent, the default one. */\n card?: string;\n}\n\n/** What the faucet gave: `amount` in the wallet's own unit (\"test sats\", \"TEST-USDT\"). */\nexport interface TestCoinsResult {\n amount: number;\n unit: string;\n /** Asked, and on its way (a transaction the chain has not confirmed): it shows up in a few seconds. */\n pending?: boolean;\n}\n\n/**\n * The first-run wallet setup of a new profile: the Mainnet kinds still to make, and why the last try at each failed.\n * Kept in the settings. Absent on a profile from before it, which is never set up by itself.\n */\nexport interface WalletSetupRecord {\n /** Kinds not made yet, tried again at each start. A kind with no Mainnet wallet here yet (on-chain) waits quietly. */\n left: WalletType[];\n /** Why the last try failed, per kind still left. */\n failed?: Partial<Record<WalletType, string>>;\n}\n\n/** What the Wallet page shows of the first-run setup: whether it runs now, and each kind it could not make. */\nexport interface WalletSetupView {\n running: boolean;\n failed: { type: WalletType; network: WalletNetwork; reason: string }[];\n}\n\nexport interface WalletView {\n /** The first-run setup, while it runs or has a kind it could not make; absent otherwise. */\n setup?: WalletSetupView;\n /** Both networks' wallets, open side by side. The flat fields below are Mainnet's, for a caller naming no network. */\n networks?: Record<WalletNetwork, NetworkWalletsView>;\n /** The wallets this profile has, in the deck's order. */\n wallets?: WalletInstanceView[];\n /** What New can make on each network. */\n offers?: WalletOffer[];\n ark?: ArkWalletView;\n /** Second's Ark (Bark): a different Ark server from `ark`, not interchangeable with it. */\n bark?: BarkWalletView;\n /** Federations joined with an invite code, and their ecash. */\n fedimint?: FedimintWalletView;\n /** Spark, wallet to wallet (the Breez SDK's Spark wallet; it can also be the Breez Lightning source). */\n spark?: SparkWalletView;\n usdt?: UsdtWalletView;\n /** The Lightning source of this mode (the Cashu mints by default) and its latest operations. */\n lightning?: LightningView;\n lightnings?: LightningCardView[];\n /** The on-chain Bitcoin source of this mode, if one is set up. */\n bitcoin?: BitcoinView;\n intents?: PaymentReview[];\n mints: MintView[];\n balance: number;\n /** Cashu: see `NetworkWalletsView`. */\n setAside?: number;\n openSwaps?: number;\n swapsAmount?: number;\n unconfirmed?: number;\n /** Newest first. */\n history: WalletTx[];\n feesPaid: number;\n /** Each Mainnet wallet's backup reminder, by wallet id: the page works out which asks now (`backupDue`). */\n backupReminders?: BackupReminders;\n}\n\nexport interface StoredMessage {\n wireId?: string;\n /**\n * `held`: in this device's storage, waiting for the contact to come back (WISP 404).\n * `queued`: unconfirmed, and sent again by itself under the same id once the chat can carry it.\n * `waiting`: not sent yet; it goes by itself when the chat can carry it (live, or the DHT text before it\n * confirmed), and can be cancelled meanwhile (\"Sends when live\", WISP 400).\n */\n delivery?: \"sending\" | \"sent\" | \"queued\" | \"waiting\" | \"held\" | \"delivered\" | \"failed\";\n deliveryError?: string;\n /** Until when a `queued` message is sent again by itself; after that it waits for Retry. */\n resendUntil?: number;\n /**\n * A file of mine that waits for the live link, said on the DHT floor meanwhile (WISP 403 § Files): `sent` its offer\n * went, `seen` the contact's app took it (its bubble is in place there), `unfit` it cannot go there (it waits as before).\n */\n fileOnFloor?: \"sent\" | \"seen\" | \"unfit\";\n linkId: string;\n id: string;\n text: string;\n sender: \"me\" | \"peer\";\n /**\n * The row's place in its history, which is sorted by it (WISP 400, requirement 10). Mine: when I sent it. Received:\n * when it was first stored on this device (`arrivalKey`), never the sender's clock, so a conversation reads in the\n * order things happened here. A row received before `sentAt` existed keeps the sender's time it was stored under.\n */\n timestamp: number;\n /** Received: when the sender says it sent it, by its own clock. Shown (`shownTime`), never sorted by. */\n sentAt?: number;\n /** `hold`: through the sender's storage while the other side was away (WISP 404). */\n via: \"pkarr\" | \"datalink\" | \"hold\";\n nick?: string;\n file?: MessageFile;\n paymentId?: string;\n /**\n * The text a contact request carried, while its requester's app has not proven in the chat that it sent it (WISP 8xx\n * § Accept): whoever made the chat's invite may not be who asked.\n */\n unconfirmed?: true;\n /** Group messages: the member key of the sender. */\n member?: string;\n /** Group history lines that are not messages. */\n event?: GroupEvent;\n /**\n * A line of a group's history: when it was first stored on this device. Its `timestamp` keeps its commit's moment\n * (`placed`), which can be long before it came here (a member back after a month). Absent on lines stored before it.\n */\n heardAt?: number;\n /** A private group's removal line (`gone`): the member key of the admin who removed `member`. */\n by?: string;\n /** Group history: a payment between members, as the group knows it (WISP 902 § Payments). */\n groupPay?: GroupPayNote;\n /** Group messages: the places of the text that name members, by member key (WISP 902 § Mentions). */\n mentions?: GroupMention[];\n /** A group message someone else sent that names me (or everyone). */\n mentioned?: true;\n /**\n * A private group's message from another member, or a community's from anyone: the frame it came in (sealed, signed\n * by its author), kept on the group's newest rows to hand on to members who were away (`GROUP_LIMITS.relay`,\n * `COMMUNITY_LIMITS.store`). The engine's own: a row goes to a page without it (`withoutFrame`).\n */\n frame?: GroupMessageFrame | CommunityMessageFrame;\n /** How this message travelled, as the engine saw it go or come (the message's details view). */\n details?: MessageDetails;\n /** A link preview that came with the text (WISP 401 § Link previews): made by the sender's app, never fetched here. */\n preview?: LinkPreview;\n /** The message this one answers (WISP 400 § Replies). */\n replyTo?: MessageReply;\n /**\n * Reactions to it (WISP 400 § Reactions), one per person: `me`, `peer` (a 1:1 chat's contact) or a group member's\n * key. One taken back stays with an empty emoji, so an older reaction arriving late does not bring it back.\n */\n reactions?: Record<string, MessageReaction>;\n /** A text edited after it was sent (WISP 400 § Edits): `text` is the latest version. */\n edit?: MessageEdit;\n /**\n * A forwarded text or file (WISP 400 § Forwards): how many times it has been forwarded, this hop included. Only the\n * count: never who wrote it first, nor where it came from.\n */\n forwarded?: number;\n /**\n * A bot's status card (WISP 405 · Status Cards): a task or a routine shown instead of `text`, which is its fallback.\n * It belongs to the version it came with: an edit brings its own, or leaves the message a text.\n */\n card?: StatusCard;\n /** Only on the row a removal of mine reads as to the edit queues (`engine/removals.ts`): never stored, never shown. */\n removed?: true;\n /**\n * A reply that presses a button of this side's own message (WISP 406 · Message Buttons), as the author's engine took\n * it: set only when the button was open for this person. What `button.pressed` reports.\n */\n press?: MessagePress;\n /**\n * A card of mine (WISP 405 · Status Cards, WISP 406 · Message Buttons) whose text went on the DHT floor or into a hold,\n * which carry text alone: `due` until the card goes again live, as an edit of the card alone; `sent` once it did, or\n * once it was given up (too old).\n */\n cardRestore?: \"due\" | \"sent\";\n /** What `cardRestore` was named before it covered every kind of card (buttons only): read for rows kept since. */\n buttonsRestore?: \"due\" | \"sent\";\n /**\n * A line this app wrote in the chat itself, never the contact's words: the app says it in its own language from these\n * values (`paymentRefusal` in `shared/refusals.ts`), and `text` keeps its English for the CLI and older apps.\n */\n notice?: ChatNotice;\n /**\n * A 1:1 chat's \"👋 <name> joined\" line, drawn as the app's own line: set only on the contact's first row of the chat\n * in those words (`peerSpoke` on its link), whatever they wrote before it. Decided once, as the row is stored, so it never moves to\n * another row as history loads or rows go. Any other row in those words is an ordinary message.\n */\n joinLine?: true;\n}\n\n/**\n * A payment of the contact's this app refused, or could not take in: how much they said they sent, on which\n * network when it is known (`testnet`: test sats), `fedimint` for Fedimint notes (Cashu otherwise), and the reason in\n * the English the contact was told, which the app reads back into its own language.\n */\nexport interface PaymentRefusedNotice {\n type: \"paymentRefused\";\n amount?: number;\n network?: WalletNetwork;\n method?: \"fedimint\";\n reason: string;\n}\n\n/** The lines an app writes in a chat on its own (`StoredMessage.notice`). */\nexport type ChatNotice = PaymentRefusedNotice;\n\n/**\n * A message that carries a task, a routine or a usage card, as the Tasks board and the chat list read it across every\n * chat and group (`statusCardIndex`): where it is (`linkId`: a chat's id, or `group:<id>`), its message, who sent it (`member`: a group\n * member's key, absent for my own), when it was sent and when its last edit was made. Nothing else of the message.\n */\nexport interface CardIndexRow {\n linkId: string;\n id: string;\n card: TaskCard | RoutineCard | UsageCard;\n sender: \"me\" | \"peer\";\n member?: string;\n timestamp: number;\n editedAt?: number;\n}\n\n/**\n * A message saved on this device (`savedMessages`): when it was saved and its row as it is now (an edit shows its latest\n * version). Kept for the profile here only, never sent.\n */\nexport interface SavedMessage { savedAt: number; message: StoredMessage }\n\n/** A page of a chat's history, oldest first, and whether older messages remain (`messagePage`). */\nexport interface MessagePage { messages: StoredMessage[]; more: boolean }\n\n/**\n * A chat's pin as kept (WISP 400 § Pinned message): the message's id both sides know (`id`, \"\" unpinned), the pinner's\n * number (the highest wins), who pinned (`me`, `peer`, or a member's key) and when it came here. `messageId`: the row\n * here, when it was here then. A private group's keeps the pinner's signature (`k`, `sig`), to pass it on. `removed`: a\n * 1:1 chat's, its message deleted for everyone: shown as unpinned for good, the pin kept as it came.\n */\nexport interface StoredPin extends WirePin { by: string; at: number; messageId?: string; k?: string; sig?: string; removed?: true }\n\n/** A chat's pin, as the pages and the CLI see it. `id`: the id both sides know the message by (\"\" once unpinned); `messageId`: the row here. */\nexport interface PinView { id: string; by: string; at: number; messageId?: string }\n\n/** One person's reaction to a message: the emoji (\"\" once taken back), their number (the highest wins), when it came. */\nexport interface MessageReaction { e: string; n: number; at: number }\n\n/** The latest reaction in a chat, as the chat list says it: \"Ana reacted ❤️ to \"…\"\". */\nexport interface ReactionNote {\n at: number;\n /** Who reacted: `me`, `peer`, or a group member's key. */\n by: string;\n emoji: string;\n /** A line of the message it went to: an app card's never with its bundle's link (`withoutAppLink`). */\n snippet: string;\n /** The message was mine. */\n mine: boolean;\n /** The message's id here: an edit of it changes `snippet`. */\n message?: string;\n /**\n * A group's note: what the message is where its text is only an English fallback, so the chat list (which holds no\n * group's rows) says it in the reader's language: a voice message's or a video's length (milliseconds), an app card's\n * name. Absent for any other message, on a 1:1 chat's (the list reads its row), and on notes made before it.\n */\n kind?: ReactionNoteKind;\n}\n\n/** `ReactionNote.kind`: a voice message, a video, or an app card (WISP 405 § An app) by its ref, title and version. */\nexport type ReactionNoteKind = { voice: number } | { video: number } | { app: { ref: string; title: string; version?: string } };\n\n/** How a message was edited (WISP 400 § Edits). */\nexport interface MessageEdit {\n /** The edit shown: its number (1 for the first; the highest one wins) and when its author made it. */\n seq: number;\n at: number;\n /**\n * A contact's or a member's edit: when this device took it. Their `at` is their clock's (never later than this), and\n * can be long before it came. Absent on mine, made here at `at`, and on edits stored before it.\n */\n heardAt?: number;\n /** Earlier versions, oldest first (the newest `EDIT_HISTORY_KEEP`): when each was written, and its text. */\n history: MessageVersion[];\n /** Mine: the contact has not confirmed this edit yet. It goes by itself once the chat is live and both sides offer edit/1. */\n pending?: true;\n /**\n * Mine: the engine's own edit that sends a question's buttons again, the text unchanged (WISP 406 · Message Buttons),\n * never one a person or a bot made. The bot's event stream reports none for it; a later edit makes a new one without it.\n */\n restore?: true;\n}\n\nexport interface MessageVersion { at: number; text: string }\n\n/**\n * The message a reply answers, as kept with the reply (WISP 400 § Replies). What the replier's app saw of it goes\n * with the reply; the receiver keeps its own view of the original when it has it (`messageId`), and the line and the\n * author then come from there, not from the wire.\n */\n/** A button press on this side's message (WISP 406 · Message Buttons). */\nexport interface MessagePress {\n /** The message with the buttons, its id here. */\n messageId: string;\n button: string;\n label: string;\n /** Named by its label or id in the text, not by the reply (the DHT floor, or an app without buttons). */\n inferred?: true;\n}\n\nexport interface MessageReply {\n /** The original's id in this chat as both sides know it: a paired chat's wire, file or payment id; a group message id. */\n id: string;\n /** A line of the original, plain and short (`replySnippet`); empty when only its id came (over the DHT). */\n snippet: string;\n /** Who wrote the original; absent when nothing says (only its id came, and it is not here). */\n from?: \"me\" | \"peer\";\n /** A group's original: its author's member key. */\n member?: string;\n /** A button press (WISP 406 · Message Buttons): the original's button this reply presses, its text the label. */\n button?: string;\n /**\n * The original here, when it was found in this chat as the reply was kept (always, for a reply sent here). Without\n * it the line is only what the replier's app said: shown, but marked as not checked.\n */\n messageId?: string;\n}\n\n/**\n * The way a message went, as the engine saw it at that moment: a live transport, the DHT floor (a paired chat's\n * `dht-text/1` envelope), the sender's storage (`hold/1`), or a chat from before pairing (`legacy-*`).\n */\nexport type MessagePath = PairedTransport | \"dht\" | \"hold\" | \"legacy-datalink\" | \"legacy-dht\";\n\n/** One send of a message: when, over what, and how it ended. */\nexport interface MessageSend {\n at: number;\n path: MessagePath;\n /** The live session crossed a relay (WISP 100, \"Relayed\"); the relays' hosts. */\n relayed?: boolean;\n relays?: string[];\n /** The round trip measured on the session at the time. */\n rttMs?: number;\n /** Absent while the send is under way. */\n result?: \"sent\" | \"failed\";\n error?: string;\n}\n\n/**\n * What the engine remembers about one message's travels, for its details view (WISP 400 § Message details): facts\n * as they were when the message went or came, that nothing else keeps. Kept on the message row, bounded by\n * `MESSAGE_DETAILS_MAX_BYTES`. Never a key, a seed or anything else that opens the chat.\n */\nexport interface MessageDetails {\n /** Sends of this message, oldest first: the first and the last ones (`MESSAGE_DETAILS_MAX_SENDS`). */\n sends?: MessageSend[];\n /** Sends there were in all, when more than `sends` keeps. */\n attempts?: number;\n /** A received message: when it came and over what. */\n received?: Omit<MessageSend, \"result\" | \"error\">;\n /** The last successful send was handed to the transport. */\n sentAt?: number;\n /** The contact's receipt came (the message is `delivered`). */\n receiptAt?: number;\n /** Stored for an away contact, sealed for them. */\n heldAt?: number;\n /** A file: its last byte arrived here, or the contact confirmed it. */\n completedAt?: number;\n /** The frame the message travelled in. `wireBytes`: as sent on the channel (a JSON frame, a sealed record, a bundle). */\n wire?: { frame: string; protocol: string; plaintextBytes?: number; wireBytes?: number; chunks?: number; chunkBytes?: number };\n /** The DHT floor: the envelope's sequence and times, the sealed packet's size and nonce, the record read. */\n dht?: { seq?: number; issued?: number; expires?: number; packetBytes?: number; nonce?: string; recordKey?: string; records?: string[] };\n /** Store-and-forward: the item's sequence in the mailbox, its sealed size and expiry. */\n hold?: { seq?: number; bytes?: number; expires?: number; mailbox?: string };\n}\n\n/** A details record larger than this (as JSON) is trimmed: its oldest sends go first. */\nexport const MESSAGE_DETAILS_MAX_BYTES = 2048;\n/** Sends kept on a record: the first, and the last ones. */\nexport const MESSAGE_DETAILS_MAX_SENDS = 6;\n\n/** What the details view is made of: the row, its record, and what the engine knows around it right now. */\nexport interface MessageDetailsView {\n message: Pick<StoredMessage, \"id\" | \"wireId\" | \"linkId\" | \"sender\" | \"timestamp\" | \"sentAt\" | \"via\" | \"delivery\" | \"deliveryError\" | \"resendUntil\" | \"member\" | \"nick\"> & {\n kind: \"text\" | \"file\" | \"voice\" | \"payment\" | \"event\" | \"note\";\n /** UTF-8 bytes of the text. */\n textBytes: number;\n };\n details?: MessageDetails;\n /** The chat the message is in. Keys are the public participation keys (z-base-32), never a seed. */\n link?: {\n id: string;\n profile?: \"paired-chat/1\";\n deliveryMode?: DeliveryMode;\n /** Our own participation key on this link. */\n myKey: string;\n /** The contact's, as pinned; absent before the first contact. */\n peerKey?: string;\n /** The pinned key was compared by the two people (WISP 401 § verification). */\n verified: boolean;\n /** The session carrying the chat right now, if any. */\n transportNow?: PairedTransport;\n relayedNow?: boolean;\n rttNowMs?: number;\n };\n /** The file the message carries (files/2, files/3 or a held item), as stored. */\n file?: {\n id: string; name: string; size: number; mime: string;\n /** SHA-256 of the bytes, hex, once known (the sender's own, or checked on arrival). */\n digest?: string;\n protocol?: \"files/2\" | \"files/3\" | \"hold/1\";\n state?: string;\n stage?: string;\n transferred?: number;\n /** Why a transfer that ended without the file did. */\n error?: string;\n /** files/3: bytes confirmed durably, where a restart resumes. */\n confirmed?: number;\n /** files/3: when the offer was made. */\n since?: number;\n consented?: boolean;\n /** Where the bytes are kept on this device. */\n storage?: string;\n voice?: { duration: number; peaks: number };\n };\n /** The payment or request the message stands for: everything but the money itself. */\n payment?: {\n id: string; kind: \"payment\" | \"request\"; direction: \"in\" | \"out\"; amount: number; unit: string; state: PaymentState;\n method?: string; network?: string; provider?: string; asset?: string; mint?: string; txid?: string; ask?: string;\n createdAt: number; error?: string; memo?: string; group?: string;\n /** SHA-256 of the invoice, hex, when there is one (the invoice itself carries the amount and a payment hash). */\n invoiceDigest?: string;\n lightningPending?: boolean; paidHere?: boolean;\n };\n /** A group message: which group, and the member key of the sender when it is not this device. */\n group?: { id: string; member?: string; profile?: string };\n}\n\n/** The ways of paying a group note can name. */\nexport type GroupPayRail = \"cashu\" | \"lightning\" | \"arkade\" | \"bark\" | \"bitcoin\" | \"spark\" | \"usdt\" | \"fedimint\";\n\n/**\n * A payment between two members as the whole group sees it (WISP 902 § Payments): who pays whom, how much, over\n * what, and how it stands. No money and nothing to pay with: that travels only on the edge between the two.\n */\nexport interface GroupPayNote {\n id: string;\n /** `request`: a member asks to be paid; `payment`: a member sends without a request. */\n kind: \"request\" | \"payment\";\n /** Who pays: a member key, or `*` for a request any member may pay once. */\n from: string;\n /** Who is paid. */\n to: string;\n /** In the unit's smallest denomination (sats, token base units). */\n amount: string;\n unit: string;\n decimals: number;\n rail: GroupPayRail;\n /** Test money (test mints, test networks): worth nothing. */\n test?: boolean;\n memo?: string;\n /** The request answers the payer's own ask (Ark, Bark, on-chain, USDT): the payer started it. */\n ask?: boolean;\n createdAt: number;\n /** `sent`: the payer says it paid, the payee has not confirmed. `closed`: failed, refused or taken back. */\n state: \"open\" | \"sent\" | \"paid\" | \"closed\";\n /** Who paid it: the payee's word, or, when its wallet cannot tell (an invoice), the only member who said so. */\n by?: string;\n /** Members who said they paid it. */\n claims?: string[];\n /** The last note this device said about it, sent again when an edge opens. */\n mine?: GroupPayFrame;\n /**\n * Known only from another member's word (a payer's claim, a payee's \"paid\"): the member it is about (the payee of a\n * request, the payer of a payment) has not described it. Kept on this device only, never in the group's history,\n * until that member's own note arrives: nothing is shown as a member's that the member never said.\n */\n undescribed?: true;\n}\n\n/** `group-pay` on an edge (WISP 902 § Payments). Old apps drop it. */\nexport interface GroupPayFrame {\n t: \"group-pay\";\n g: string;\n id: string;\n k: \"req\" | \"pay\";\n f: string;\n to: string;\n v: string;\n u: string;\n d: number;\n r: GroupPayRail;\n x?: 1;\n m?: string;\n a?: 1;\n ts: number;\n st: GroupPayNote[\"state\"];\n by?: string;\n}\n\n/** A local web application the user chose to share. */\nexport interface StoredService {\n id: string;\n name: string;\n /** Normalized loopback URL, e.g. `http://localhost:3400` */\n target: string;\n enabled: boolean;\n createdAt: number;\n /**\n * The contacts allowed to reach this service, by participation key. Absent or\n * empty means nobody: a service is granted per contact, never to everyone at\n * once, and a service from before this existed starts closed rather than\n * keeping an exposure its owner never chose.\n */\n sharedWith?: string[];\n}\n\nexport interface IceServerSetting {\n urls: string;\n username?: string;\n credential?: string;\n}\n\nexport interface Settings {\n online: boolean;\n nick: string;\n /** This profile's picture, shown to paired contacts: a small square JPEG data URL. */\n avatar?: string;\n /**\n * Whether contacts are told this profile's name and picture (WISP 401 § name and picture). Absent means\n * yes; off, every chat and group member is told there is none, and the join notice names nobody.\n */\n shareProfile?: boolean;\n /** The Pkarr relays. Browsers read and write through them; the Desktop writes to them (so browser contacts see its packets). */\n relays: string[];\n /**\n * Where the DHT is reached directly (the Desktop): whether reads may use the relays too, \"Also use Pkarr relays\"\n * in Settings, Network. Absent means no: reads go to the DHT alone.\n */\n readRelays?: boolean;\n /** Extra ICE servers (typically TURN) on top of the built-in STUN set. */\n iceServers: IceServerSetting[];\n /**\n * \"Hide my IP from contacts\" (WISP 100 § Relay only): every WebRTC connection to a contact (calls, chat links,\n * group edges) goes through the TURN server in `iceServers` alone, with no STUN server. On only with a TURN server\n * (`relayOnlyProblem`). The Desktop offers contacts neither its own Iroh nor its own HyperDHT (HyperDHT goes through\n * `hyperdhtRelay`, as in a browser); its own devices keep them. Absent means off.\n */\n relayOnly?: boolean;\n /**\n * The Iroh relays a browser build homes on (WISP 102, relay only): a page cannot send UDP, so every Iroh\n * packet goes through one. Absent or empty means the defaults (n0's public relays, as the desktop app's).\n */\n irohRelays?: string[];\n /**\n * The HyperDHT relay (wss://) this browser reaches the HyperDHT through, so paired chats can use HyperDHT\n * (WISP 103) beside WebRTC. Empty: none. Absent means the default (shared/hyperdhtRelay.ts). The Desktop\n * runs HyperDHT itself and ignores it, except toward contacts while `relayOnly` is on.\n */\n hyperdhtRelay?: string;\n /** Cashu mints this peer holds ecash at and accepts ecash from. The first is where invoices are created. */\n mints: string[];\n /** False until the default mints were put in place once; after that the list is the user's. */\n mintsInitialized: boolean;\n /** The Nostr social layer: relays, automatic profile loading, publication. Absent means the defaults, everything off. */\n nostr?: NostrSocialSettings;\n /**\n * Identity cards show the public profile (picture, name, bio, counts) of a verified identity, read from its\n * network's public host when the card is on screen (PUBLIC-PROFILES.md). Absent means on; off drops what was kept.\n */\n publicProfiles?: boolean;\n /**\n * Whether paired contacts are told when this profile is typing (WISP 401 § Typing). Absent means yes; off,\n * nothing is said, and a contact's typing is still shown.\n */\n sendTyping?: boolean;\n /**\n * Whether paired contacts see when this profile is online (WISP 401 § Presence and status, \"Share when I'm online\").\n * Absent means yes; off, no presence is said (a set status still is), and a contact's is still shown.\n */\n sharePresence?: boolean;\n /**\n * Whether a headless daemon running this profile (the CLI's `settings set daemonPresence true`) says it is active\n * while it runs, as a page does on input. Absent means no: kept only while on. The apps never read it.\n */\n daemonPresence?: boolean;\n /**\n * The status this profile set (availability, emoji, text, until when), said to every paired contact whose app offers\n * `status/1`. Set and cleared through `setOwnStatus`/`clearOwnStatus`, never a settings patch; this device's own.\n */\n ownStatus?: PersonStatus;\n /**\n * Whether files are downloaded without asking where the rules allow it (WISP 503: a group's voice messages, and its\n * files up to 8 MiB within 256 MiB a group). Absent means on; off, each waits for a Download.\n */\n autoDownloads?: boolean;\n /**\n * Whether this device sends the group files it keeps to members who ask (WISP 503 § Serving limits). Absent means\n * on; off, it answers that it is busy and does not say it holds them.\n */\n serveFiles?: boolean;\n /**\n * Where items are held for away contacts (WISP 404): the profile's S3 storage and its random space\n * (WISP 1000/1002), as set up under Profile → Backups. Kept here for the peer, which may run outside the\n * page; never copied into a backup.\n */\n holdStorage?: { s3: S3Config; space: string } | null;\n /** The first-run wallet setup (see `WalletSetupRecord`). Only the engine writes it: a settings patch cannot. */\n walletSetup?: WalletSetupRecord;\n /**\n * This profile's push subscription (the installed web app, WISP 401 § Wake-up push): shared with each paired\n * contact whose app offers `wake/1`, so it can wake this app while it is closed. Absent: not woken.\n */\n wake?: WakeSubscription;\n /**\n * A contact who held `wake` can no longer be told to forget it (its chat was deleted, or muted: a contact may ignore\n * `w: null`). The app replaces the subscription (a new endpoint and VAPID key pair, new tokens for the others) and\n * `setWakeSubscription` clears this. Set by the engine only.\n */\n wakeRotate?: boolean;\n /**\n * False: contacts are not asked for an online notice when they come online while this app is closed (WISP 401 §\n * Wake-up push, revision 2026-10-27). Absent: they are (the default). Only through `setWakeOnline`.\n */\n wakeOnline?: false;\n /**\n * Private groups muted here (WISP 902 · Group Mesh § Wake-up push): their members are told to forget this profile's\n * subscription, as a muted chat's contact is. Only through `setWakeMuted` with the group's `group:<id>`.\n */\n wakeMutedGroups?: string[];\n /**\n * Groups whose links this device put on one transport (WISP 902 § Transports), by group id; a group not here is on\n * Automatic. This device's own: nothing of it goes to the members but each edge's `_tr`. Only through `setGroupTransport`.\n */\n groupTransports?: Record<string, PairedTransport>;\n /**\n * Private groups → members that were given a token on an edge a group on hubs later dropped: they still hold the\n * subscription with no edge to close, so their leaving the group (or this profile leaving it, or muting it) replaces\n * it. Cleared with every new subscription. Set by the engine only.\n */\n wakeHeldBy?: Record<string, string[]>;\n /**\n * In a profile on several devices (WISP 06 § Push and the phone): devices asked for a new subscription over their\n * device link, by signing key, with the endpoint they are to replace. A device that shares another endpoint (or none)\n * has done it. Set by the engine only.\n */\n wakeRenew?: Record<string, string>;\n /**\n * A push relay (https) this app hands a finished wake-up to when it may not post to the contact's push service\n * itself (a browser page: the services answer without CORS). Empty or absent: none; nobody runs one by default.\n */\n pushRelay?: string;\n /** The backup reminder of each Mainnet wallet (see `shared/backupReminder`). Only the engine writes it: a settings patch cannot. */\n backupReminders?: BackupReminders;\n}\n\n/** A browser push subscription and the VAPID key pair it was made with. */\nexport interface WakeSubscription {\n endpoint: string;\n p256dh: string;\n auth: string;\n vapid: VapidKeys;\n /**\n * In a profile on several devices (WISP 06 § Push and the phone): the signing key of the device whose subscription\n * this is. It moves with the profile, so a device with none of its own (a desktop) goes on giving contacts the\n * phone's. Set by the engine only; absent in a profile on one device, and for a subscription made before.\n */\n device?: string;\n}\n\n/**\n * What `updateSettings` takes: any settings, and of the Nostr ones only those that change. The rest of the\n * Nostr settings stay as stored, so a switch flipped from a page that has not seen the last save yet does not\n * put back what that save replaced.\n */\nexport type SettingsPatch = Partial<Omit<Settings, \"nostr\">> & { nostr?: Partial<NostrSocialSettings> };\n\n/** What pages see of store-and-forward in one chat. */\nexport interface LinkHoldView {\n /** The switch of this chat on this device. */\n enabled: boolean;\n /** The contact's app accepts held items, as it last said; undefined until it said anything. */\n peerAllows?: boolean;\n /** This device has storage to hold items in (Profile → Backups → S3 storage). */\n storage: boolean;\n /** Items can be held for the contact right now: switch on, contact allows it, storage set up, contact pinned. */\n canHold: boolean;\n /** Items held for the contact and not yet picked up. */\n outstanding: number;\n bytes: number;\n maxBytes: number;\n maxItems: number;\n ttlMs: number;\n /** Items from the contact refused on the way in. */\n refused: number;\n /** The last problem holding or picking up, for people. */\n error?: string;\n}\n\n/** A proof of this profile (Identities). */\nexport interface IdentityProofView {\n id: string;\n provider: string;\n subject: string;\n /** The proof key the statement authorizes. */\n key: string;\n verified: VerifiedIdentity;\n issuedAt: number;\n /** Seconds: the earlier of the statement's and the evidence's expiry. */\n expiresAt: number;\n createdAt: number;\n /** Chats it is currently shared in (or queued for). */\n sharedWith: number;\n /** The identity as a URI the profile's public DID can list (`alsoKnownAs`); absent when it has none. */\n publicUri?: string;\n /** What the provider checked (public: contacts receive it too). Removal uses it to take down a published proof. */\n evidence?: unknown;\n /** The identity's public profile on its network, once asked for (PUBLIC-PROFILES.md); absent while not asked or turned off. */\n publicProfile?: PublicProfileView;\n}\n\n/**\n * An identity's public profile, as its network publishes it (docs/wisps/PUBLIC-PROFILES.md): self-described by the\n * account, never part of the proof. Only for an identity with a current verified proof, with Settings → Load public\n * profiles on; kept on this device and asked again after a day.\n */\nexport interface PublicProfileView {\n /** False when the network has no profile for this identity (or none was read yet). */\n found: boolean;\n name?: string;\n /** How the network writes the account: \"@alice.bsky.social\", a Nostr `name`. */\n handle?: string;\n /** A short bio, plain text. */\n about?: string;\n /** The website the account names: an https address, shown as a plain link. */\n website?: string;\n /** A sanitized `data:image/jpeg;base64,…` URL, never a remote one. */\n avatar?: string;\n /** The profile names a picture that is not shown: which rule refused it, in words (\"it is a GIF; …\"). */\n avatarMiss?: string;\n followers?: number;\n following?: number;\n /** The hosts it was read from, which saw this device's IP address: \"nexus.pubky.app\". */\n hosts: string[];\n /** Seconds; 0 when it was never read. */\n fetchedAt: number;\n loading?: boolean;\n /** The last attempt failed (a copy read before, if any, is still shown). */\n error?: string;\n}\n\n/**\n * A verified identity's recent posts (docs/wisps/PUBLIC-PROFILES.md, \"Posts and follows\"): `loadPublicPosts`, asked\n * when its card is chosen in a contact's identities panel. Plain text, bounded, never markup.\n */\nexport interface PublicPostView {\n id: string;\n /** Seconds. */\n createdAt: number;\n text: string;\n /** Opens the post in its network's app or site. */\n url?: string;\n reply?: boolean;\n /** Its pictures, loaded only on a tap (`loadPublicPostImage` with the index here). `host`: who is asked. */\n images: { host?: string; alt?: string }[];\n}\n\nexport interface PublicPostsView {\n posts: PublicPostView[];\n /** More can be asked for (`more: true`). */\n more: boolean;\n /** The hosts asked, which saw this device's IP address. */\n hosts: string[];\n /** Seconds. */\n fetchedAt: number;\n /** Notes the person's own Nostr mute list hides. */\n hidden?: number;\n /** The identity's profile in its network's app or site. */\n profileUrl?: string;\n}\n\n/**\n * Who a verified identity follows and who follows it, only as far as it touches people the reader knows: the reader's\n * own identities and the identities contacts shared. Computed on this device from lists read from the same hosts as\n * the profile; the lists themselves are never shown or stored.\n */\nexport interface PublicGraphView {\n /** False when there was nobody to compare with (no identity of the reader's, no contact, on this network): nothing was read. */\n compared: boolean;\n /** Its follow list names one of the reader's identities. */\n followsYou: boolean;\n /** One of the reader's identities follows it (their followers list, or the reader's own follow list). */\n youFollow: boolean;\n /** Contacts whose shared identity it follows (`follows`) or who follow it (`followedBy`). */\n contacts: { linkId: string; follows: boolean; followedBy: boolean }[];\n /** A list was longer than this app reads: someone may be missing, never added. */\n partial?: boolean;\n hosts: string[];\n /** Seconds; 0 when nothing was read. */\n fetchedAt: number;\n}\n\n/** A post's picture, on the reader's tap: a re-encoded `data:image/jpeg` URL, or why there is none. */\nexport interface PublicPostImageView { src?: string; miss?: string; hosts: string[]; width?: number; height?: number }\n\n/** The profile's did:dht (WISP 310-did-dht): its own key, public to everyone, never tied to a chat. */\n/** A request in Requests (WISP 8xx): what the asker said. The name is what it typed, unverified. */\nexport interface ContactRequestView {\n /** The asker key. */\n id: string;\n name: string;\n text: string;\n receivedAt: number;\n /** When it ends unanswered. */\n expires: number;\n}\n\n/** A request this profile sent through someone's contact link (WISP 8xx), shown on the chat made for it. */\nexport interface ContactAskView {\n chatId: string;\n /**\n * `sending`, `knocking`: on its way. `seen`: it arrived; the owner accepts it or nothing is said. `off`: the link was\n * turned off. `ended`: no answer in seven days.\n */\n state: \"sending\" | \"knocking\" | \"seen\" | \"off\" | \"ended\";\n expires: number;\n}\n\n/** The profile's contact link (WISP 8xx): what the owner shows and shares. */\nexport interface ContactLinkView {\n /** `ghostly1r…` */\n code: string;\n /** `https://ghostly.tools/#ghostly1r…` */\n link: string;\n createdAt: number;\n /** `busy`: too many requests wait; new ones are counted, not read. */\n state: \"open\" | \"busy\";\n /** Requests waiting in Requests. */\n waiting: number;\n /** How many people tried while the link was busy, since the owner last looked; never their names. */\n missed: number;\n /** When the link record last went out. */\n publishedAt?: number;\n /** Why the last publish failed. */\n error?: string;\n}\n\nexport interface ProfileDidView {\n /** `did:dht:…` */\n id: string;\n /** Identity proof ids the person listed as public, in order (some may not be publishable right now). */\n listed: string[];\n /** What the document says the subject is also known as: the listed identities that are verified and current. */\n alsoKnownAs: string[];\n /** The last packet put on Pkarr: when, and its version (the BEP44 sequence number). */\n published?: { at: number; versionId: string };\n /** The document out there is the current one. */\n upToDate: boolean;\n /** Why the last publish failed. */\n error?: string;\n}\n\n/** A contact's proof, as this app checked it. */\nexport interface ReceivedIdentityView {\n id: string;\n provider: string;\n subject: string;\n verified: VerifiedIdentity;\n /** A public name/picture looked up on request. */\n display?: IdentityDisplay;\n status: IdentityStatus;\n verifiedAt: number;\n checkedAt: number;\n expiresAt: number;\n error?: string;\n /** The provider's checks can go stale and the last one is old enough to repeat. */\n recheckDue: boolean;\n /** Its public profile, while the proof is verified and current (PUBLIC-PROFILES.md). */\n publicProfile?: PublicProfileView;\n}\n\nexport interface LinkIdentitiesView {\n /** Both sides offer identity proofs and the channel is open now. */\n support: boolean;\n /** Providers the contact's app said it can verify. */\n contactProviders?: string[];\n shared: SharedIdentity[];\n received: ReceivedIdentityView[];\n error?: string;\n}\n\nexport interface LinkView {\n /** Identity proofs in this chat; absent for chats that are not paired. */\n identities?: LinkIdentitiesView;\n /** The contact's Nostr data, one entry per key they proved in this chat. */\n nostr?: NostrContactView[];\n discoveryError?: string;\n publicProfiles?: PublicProfile[];\n profileChoice?: ProfileChoice;\n peerProofs?: Pick<ProofLedger, \"local\" | \"remote\">;\n peerProofSupport?: boolean;\n peerProofAdapters?: ProofAdapter[];\n participationKey?: string;\n peerParticipationKey?: string;\n proofError?: string;\n profile?: \"paired-chat/1\";\n pairing?: PairingState;\n /**\n * How far this chat's first pairing got (`@ghostly/core` `PairingProgress`): from the invite being\n * published to `live`. Absent for chats paired before this app start, DHT-only invites and legacy chats.\n */\n pairingProgress?: PairingProgress;\n peerVerified?: boolean;\n /**\n * `methods`: ways of paying both sides allow in this chat right now. `calls` / `services`: both sides offer\n * `calls/1` / `services/1` on the open session (paired chats only; they need a live connection).\n */\n capabilities?: {\n files: boolean; payments: boolean; methods?: Record<PaymentMethodName, boolean>; calls?: boolean; services?: boolean; largeFiles?: boolean;\n /**\n * The networks the contact has a wallet on, per way of paying, as it said on the open session. Absent: it said\n * none (an older app): any network may meet. A way of paying it has no wallet of is not in the map (one it has\n * but turned off here lists no network). A card is offered only where its network is in its list.\n */\n networks?: Partial<Record<PaymentMethodName, readonly WalletNetwork[]>>;\n };\n /** files/3 live in this chat: bytes the contact's device said it can still take for files, when it said. */\n peerFileRoom?: number | null;\n /** Ways of paying this device allows in this chat. */\n paymentMethods?: Record<PaymentMethodName, boolean>;\n /** For each way of paying, the networks this chat accepts it on. */\n paymentNetworks?: Partial<Record<PaymentMethodName, readonly WalletNetwork[]>>;\n /** Both sides announced private groups on the open session: this contact can be invited. */\n groups?: boolean;\n /** Paired chats: what each side offers after the handshake (`paired-capabilities`); `peer` is null until it says. */\n sessionOffers?: { mine: string[]; peer: string[] | null };\n /** Paired chats: why a call cannot be placed right now, or null when it can. */\n callsUnavailable?: string | null;\n /** Paired 1:1 chats: the contact is typing now (`typing/1` on the live session). Absent otherwise. Never stored. */\n peerTyping?: boolean;\n /**\n * Paired 1:1 chats: the contact is online and shares it (`status/1`): active or idle. Absent otherwise; ends with the\n * session. Never stored.\n */\n peerPresence?: Presence;\n /** Paired 1:1 chats: the status the contact set, while it lasts (heard on a live session, kept until the engine stops). */\n peerStatus?: PersonStatus;\n /** Paired 1:1 chats: this side's wake-up token for this chat (the push worker's table), when it shared its subscription. */\n wakeToken?: string;\n /** Paired 1:1 chats: the contact was told not to wake this side while the chat is muted (`setWakeMuted`). */\n wakeMuted?: boolean;\n /** Paired 1:1 chats: the contact shared how to wake its closed app, so a message sent while it is away wakes it. */\n peerWakes?: boolean;\n /** While `peerTyping`: what the contact is doing when it is not plain typing (recording a voice note, thinking). */\n peerTypingKind?: Exclude<TypingKind, \"typing\">;\n /** While `peerTyping`: the contact's (a bot's) status line, sanitized: one line, at most 40 characters, no links. */\n peerTypingStatus?: string;\n availableTransports?: PairedTransport[];\n /**\n * Every transport this app runs for the chat, started or not: DHT only releases the native ones, and an app with no\n * WebRTC (the Linux Desktop) then has none started, yet can still leave DHT only for any of these.\n */\n runnableTransports?: PairedTransport[];\n /** Transports a session with this contact would cross a relay on (a browser's HyperDHT or Iroh): a fallback, and shown as relayed. */\n relayedTransports?: PairedTransport[];\n deliveryMode?: DeliveryMode;\n dhtDelivery?: DhtDeliveryView;\n canSendText?: boolean;\n /** `hold`: the contact is away and what is sent now waits in this device's storage for it. */\n textDelivery?: \"stream\" | \"dht\" | \"hold\" | \"unavailable\";\n hold?: LinkHoldView;\n transportErrors?: Partial<Record<PairedTransport, string>>;\n preferredTransport?: PairedTransport;\n transportFallback?: boolean;\n /** No transport chosen for this chat: the app's rule applies. */\n transportAutomatic?: boolean;\n /** What the contact's app can use on this link, as it last said (a session, or its capability record); unknown before either. */\n peerTransports?: PairedTransport[];\n /**\n * The transport this chat is set to reach and is not on yet, and why (WISP 100, \"A chosen transport not reached\n * yet\"): waited for, never a failure. Absent when the chat is on it, or nothing limits where it goes.\n */\n transportWait?: TransportWait;\n /**\n * The last attempt to go live that did not, as this side saw it (WISP 100, \"Why a chat is not live\"): what it tried\n * and why each did not connect, whether this side dialled or answered, and when it dials again. Absent while live.\n */\n liveAttempt?: LiveAttempt;\n /** Which side dials this chat to go live (the other answers): paired chats. */\n liveDialer?: \"you\" | \"contact\";\n /** Round trip on the live session, once measured. */\n transportRttMs?: number;\n /**\n * The live session goes through relays, never directly (WISP 100, \"Relayed\"): a browser's Iroh. The relays'\n * hosts, this app's first. They see who talks to whom and when, not what is said.\n */\n transportRelayed?: { relays: string[] };\n /** While live: since when the current transport carries the chat, and why it was chosen (see engine/transportLog.ts). */\n transportLive?: { since: number; cause?: TransportCause };\n /** The chat's connection story, newest last; only for the chat on screen (`setActiveLink`). */\n transportLog?: TransportEntry[];\n /** Every connection event of the chat on screen, for its connection panel, newest last. */\n transportHistory?: TransportEvent[];\n /** Identities shared in this chat, both ways, as its timeline shows them, newest last; only for the chat on screen. Local only. */\n identityTimeline?: IdentityTimelineEntry[];\n /** When the contact last shared an identity here (milliseconds): the chat list's preview and order. Paired chats. */\n identitySharedAt?: number;\n /** The latest reaction in this chat, for the chat list; paired chats. */\n lastReaction?: ReactionNote;\n /** The chat's pin (WISP 400 § Pinned message): `id` \"\" once unpinned; absent when nothing was ever pinned. */\n pin?: PinView;\n id: string;\n myPubKeyZ32: string;\n peerPubKeyZ32: string;\n label?: string;\n /**\n * The name the contact asked to be shown by, as they last said it. `\"\"` means a paired contact said they\n * have none (removed, or not shared); absent means nothing was heard yet.\n */\n peerNick?: string;\n /** The contact's profile picture, as they last sent it (checked, small JPEG data URL). */\n peerAvatar?: string;\n inviteCode?: string;\n createdAt: number;\n status: LinkStatus;\n dataLink: DataLinkState;\n peerOnline: boolean;\n peerLastSeenAt: number;\n /** `null` when the peer does not advertise (offline, or a legacy client). */\n peerServices: ServiceAd[] | null;\n lastMessageAt: number;\n /** Newest of my messages the peer acknowledged through Pkarr. */\n peerAck: number;\n lastSyncAt: number;\n poll: { polling: boolean; nextAt: number; interval: number };\n}\n\nexport interface ServiceView extends StoredService {\n /** Requests served since the engine started. */\n requests: number;\n}\n\n/** A push relay's answer that was not a push service's status (`EngineState.pushRelayRefused`). */\nexport interface PushRelayRefused {\n /** The relay address it came from. */\n url: string;\n /** When, in ms. */\n at: number;\n /** The relay's HTTP status. */\n http: number;\n /** The relay's own error text, when it gave one. */\n text?: string;\n}\n\nexport interface EngineState {\n settings: Settings;\n /**\n * Limited mode (WISP 06 § When a device checks): the device could not read which device is active and was started\n * anyway. The profile is offline whatever `settings.online` says, and no wallet is open. Absent otherwise.\n */\n limited?: true;\n /**\n * Why limited mode is on, when it is a restored copy (WISP 06 § A backup restored where a device set exists): `checking`,\n * the turn is read every 30 seconds to learn whether another device runs the profile; `removed`, the read found the\n * device set moved after a removal, and only the person can start the copy as a profile of its own.\n */\n restoreCheck?: \"checking\" | \"removed\";\n /**\n * Limited mode only while the active device's read at start is out (WISP 06 § When a device checks): the profile shows\n * as it is, nothing goes out, and nobody is asked anything until the read answers. Absent otherwise.\n */\n startCheck?: true;\n /**\n * Whose push subscription `settings.wake` is, in a profile on several devices (WISP 06 § Push and the phone): `here`,\n * this device's own; `away`, another device's, given to contacts because this device has none of its own (the page\n * neither replaces nor turns off what is not its own). Absent in a profile on one device, or when nobody said.\n */\n wakeOwner?: \"here\" | \"away\";\n /**\n * The push relay set in `settings.pushRelay` answered the last wake-up it was handed, but not as a push relay: a web\n * page, JSON without the push service's status, or its own refusal (`text`, its `{ error }` on one line, cut). Kept\n * in memory until it forwards one; absent otherwise, and where the host posts wake-ups itself (Desktop, CLI).\n */\n pushRelayRefused?: PushRelayRefused;\n transport: {\n protocol: string; relays: string[];\n /** Present where Iroh runs in the browser (web app, extension): the relays it uses and the defaults. */\n iroh?: { relays: string[]; defaults: string[] };\n /** This client reaches the Mainline DHT itself (the Desktop): relays are for writes, and reads only when chosen. */\n direct?: boolean;\n /** How reads go and how each relay is doing, for the connection panel's Details. */\n discovery?: DiscoveryStatus;\n /** False where this client has no WebRTC (Ghostly Desktop on Linux: WebKitGTK has none). Absent where it has. */\n webrtc?: false;\n /**\n * This device's own WebRTC attempts say direct connections do not get through its network (a VPN, a firewall, a\n * carrier's NAT: `DirectPathWatch` in packages/core). Chats still go live through relays. Absent otherwise.\n */\n directBlocked?: true;\n /**\n * This device's clock seems to be off: this clock minus what the relays and several contacts say, in ms (positive\n * when it is ahead). From several sources agreeing, never one contact (`ClockWatch` in packages/core). Absent otherwise.\n */\n clockOffMs?: number;\n /**\n * False where a group's links have no transport at all here: no WebRTC and no native transport (WISP 902 §\n * Transports), so no member of a group can be reached from it. Absent where they have one (the Linux Desktop runs\n * Iroh and HyperDHT).\n */\n groupLinks?: false;\n };\n links: LinkView[];\n services: ServiceView[];\n /** Transfers since the peer started, by file id. */\n transfers: Record<string, FileTransferView>;\n /**\n * The kept transfers are back in `transfers`. False for the first moments after a start: a file with no transfer\n * yet may still be moving, not finished.\n */\n transfersRestored?: boolean;\n /**\n * The kept groups are in `groups`. Unset while the peer starts: until then a group missing from the list may only not\n * be loaded yet, not gone (the app forgets a gone group's draft and read mark only between two states that have it).\n */\n groupsLoaded?: true;\n wallet: WalletView;\n payments: Record<string, PaymentView>;\n /** This profile's identity proofs. */\n identityProofs: IdentityProofView[];\n /** This profile's public DID. Absent until the engine has loaded it. */\n did?: ProfileDidView;\n /** This profile's contact link, when it has one. */\n contactLink?: ContactLinkView;\n /** The requests its contact link took, newest first. */\n contactRequests?: ContactRequestView[];\n /** The requests this profile sent through others' contact links. */\n contactAsks?: ContactAskView[];\n /** The Nostr social layer: the person's own keys' data and the effective settings. */\n nostr: NostrSocialState;\n /** Private groups and pending invitations (WISP 900). */\n groups: GroupView[];\n /** The links of groups' edges: not chats, but payments with a member travel on them. */\n edges?: LinkView[];\n}\n","import { WALLET_NETWORKS, decodeBolt11, engineText, walletNetworkOf, type PaymentMethodName, type PaymentNetworks, type WalletNetwork } from \"@ghostly/core\";\nimport { mintNetwork } from \"../../shared/mints\";\nimport { WALLET_TYPES, type NetworkWalletsView, type StoredPayment, type WalletInstanceView, type WalletType } from \"../../shared/types\";\nimport { CASHU_MINT_SOURCE } from \"./providers/cashuMint\";\nimport { CASHU_CARD, LEGACY_CARD } from \"./providers/lightningCards\";\nimport { networkLabel } from \"./modeGate\";\nimport { networkReason } from \"./networkReason\";\n\nexport const WALLET_NAMES: Record<WalletType, string> = {\n cashu: \"Cashu\", lightning: \"Lightning\", arkade: \"Ark\", bark: \"Bark\", spark: \"Spark\", bitcoin: \"Bitcoin\", fedimint: \"Fedimint\", usdt: \"USDT\",\n};\n\n/** How long a one-click creation waits on its server before it gives up, saving nothing (tests shorten it). */\nexport const createTiming = { timeoutMs: 60_000 };\n\n/**\n * The wallets a profile has, read from both networks' views: one per type and network, in the deck's order, and one\n * per Lightning card. A wallet exists once it holds something to open (a seed, a source, a mint); Lightning through\n * the Cashu mints comes with that network's Cashu wallet.\n */\nexport function walletInstances(networks: Record<WalletNetwork, NetworkWalletsView>): WalletInstanceView[] {\n const list: WalletInstanceView[] = [];\n for (const type of WALLET_TYPES) for (const network of WALLET_NETWORKS) {\n if (type === \"lightning\") { list.push(...lightningInstances(network, networks[network])); continue; }\n const config = instanceConfig(type, networks[network]);\n if (config) list.push({ id: `${type}:${network}`, type, network, config });\n }\n return list;\n}\n\n/** A network's Lightning cards (a view from before cards: its one source, as one card). */\nfunction lightningInstances(network: WalletNetwork, view: NetworkWalletsView): WalletInstanceView[] {\n const cards = view.lightnings ?? (view.lightning ? [{ ...view.lightning, card: view.lightning.providerId === CASHU_MINT_SOURCE || !view.lightning.providerId ? CASHU_CARD : LEGACY_CARD, name: \"\", receive: true }] : []);\n return cards.flatMap((ln) => {\n if (!ln.providerId || (ln.providerId === CASHU_MINT_SOURCE && !view.mints.length)) return [];\n return [{ id: `lightning:${network}:${ln.card}`, type: \"lightning\" as const, network, config: { providerId: ln.providerId, label: ln.label ?? \"\" }, card: ln.card, name: ln.name || ln.label || \"Lightning\", receive: ln.receive }];\n });\n}\n\nfunction instanceConfig(type: WalletType, view: NetworkWalletsView): Record<string, string> | undefined {\n const text = (value: unknown) => typeof value === \"string\" ? value : \"\";\n switch (type) {\n case \"cashu\": return view.mints.length ? { mint: view.mints[0].url, mints: String(view.mints.length) } : undefined;\n case \"lightning\": return undefined;\n case \"arkade\": return view.ark?.configured ? { chain: text(view.ark.network), provider: text(view.ark.provider) } : undefined;\n case \"bark\": return view.bark?.configured ? { chain: text(view.bark.network), provider: text(view.bark.provider) } : undefined;\n case \"spark\": return view.spark?.configured ? { chain: text(view.spark.network) } : undefined;\n case \"bitcoin\": return view.bitcoin?.providerId ? { providerId: view.bitcoin.providerId, label: text(view.bitcoin.label) } : undefined;\n case \"fedimint\": return view.fedimint?.federations.length ? { federations: String(view.fedimint.federations.length) } : undefined;\n case \"usdt\": return view.usdt?.configured ? { chain: text(view.usdt.network), provider: text(view.usdt.provider) } : undefined;\n }\n}\n\n/** For each way of paying, the networks this profile has a wallet on: what every chat tells its contact. */\nexport function paymentNetworksOf(wallets: readonly WalletInstanceView[]): PaymentNetworks {\n const networks: PaymentNetworks = {};\n for (const wallet of wallets) {\n const method = wallet.type as PaymentMethodName;\n networks[method] = [...new Set([...(networks[method] ?? []), wallet.network])];\n }\n return networks;\n}\n\n/**\n * The network of a payment or a request: written on it since wallets have their own, else read from what it\n * carries (a target's chain, a mint, an invoice's chain). A test mint's invoice looks like a Bitcoin one; its\n * mints say Testnet.\n */\nexport function paymentNetwork(payment: Pick<StoredPayment, \"network\" | \"target\" | \"mints\" | \"mint\" | \"invoice\">): WalletNetwork {\n if (payment.network) return payment.network;\n if (payment.target) return payment.target.method === \"cashu\" ? mintNetwork(payment.target.provider) : walletNetworkOf(payment.target.network);\n const mint = payment.mints?.[0] ?? payment.mint;\n if (mint) return mintNetwork(mint);\n const decoded = payment.invoice ? decodeBolt11(payment.invoice) : null;\n return decoded && decoded.network !== \"bitcoin\" ? \"testnet\" : \"mainnet\";\n}\n\n/** The refusal when a card of one network would pay for the other: test coins and real money never meet. */\nexport const crossNetwork = (card: WalletNetwork, asked: WalletNetwork) =>\n card === asked ? `This is a ${networkLabel(asked)} payment (${asked === \"mainnet\" ? \"real money\" : \"test coins\"}): a ${networkLabel(card)} wallet never pays it. Use a ${networkLabel(asked)} wallet.`\n : engineText(asked === \"mainnet\" ? \"mainnetPaymentOnTestnet\" : \"testnetPaymentOnMainnet\");\n\n/**\n * Real money goes out only once the person confirmed it as real money (\"Send real money\"), whatever screen asked:\n * a spend RPC on Mainnet without `confirmedReal` is refused before anything is spent. Test coins need no second step.\n */\nexport function assertConfirmedReal(network: WalletNetwork, confirmedReal: unknown): void {\n if (network === \"mainnet\" && confirmedReal !== true) throw new Error(REAL_MONEY_UNCONFIRMED);\n}\nexport const REAL_MONEY_UNCONFIRMED = engineText(\"realMoneyUnconfirmed\");\n\n/** One clear message for a creation that failed: nothing was saved, and trying again is safe. */\nexport function createFailure(label: string, error: unknown): string {\n const reason = (networkReason(error) ?? (error instanceof Error ? error.message : String(error))).replace(/\\.$/, \"\");\n return `Could not create the ${label} wallet: ${reason}. Nothing was saved; try again.`;\n}\n","/**\n * Payment ids are chosen by whoever sends them, and every member of a group sees the requests the others make to the\n * group. So a contact's request is kept under the id it came with, unless a record of another chat already holds that\n * id: then under `<id>.<chat>`. A `.` is never in a payment id on the wire (8 to 64 of `A-Z a-z 0-9 _ -`), so no\n * contact can name another's record, and two contacts' requests never share one.\n */\nexport const paymentAlias = (wireId: string, linkId: string): string => `${wireId}.${linkId}`;\n\n/** The id a payment record goes by on the wire, which is also the one its chat and its group's notes know it by. */\nexport const paymentWireId = (key: string): string => key.split(\".\", 1)[0];\n","import { replySnippet, type WireReply } from \"@ghostly/core\";\nimport { paymentWireId } from \"./paymentIds\";\nimport type { MessageReply, StoredMessage } from \"./types\";\n\n/*\n * Replies (WISP 400 § Replies) as the engine and the UI both need them: which id a message goes by on both sides of\n * its chat, and a reply as it is kept and as it goes on the wire.\n */\n\n/** A paired chat's text (`me_`/`peer_` + its 22-character wire id), or a held file (`peer_` + its 16-character one). */\nconst PAIRED_ROW = /^(?:me|peer)_([A-Za-z0-9_-]{22}|[A-Za-z0-9_-]{16})$/;\nconst WIRE_ID = /^[A-Za-z0-9_-]{8,64}$/;\nconst GROUP_LINK = \"group:\";\n\n/** The parts of a message, as the engine or the UI keeps it, that say which id both sides know it by. */\nexport interface ReplyTarget {\n id: string;\n linkId?: string;\n wireId?: string;\n paymentId?: string;\n file?: { id: string };\n event?: unknown;\n groupPay?: unknown;\n /** Set by the UI from the engine's row (`replyRef`), for what the UI's own copy no longer says. */\n ref?: string;\n}\n\n/**\n * The id a message of a chat goes by on both sides, which a reply names; none for what only this side has (a notice,\n * a group payment line, a refused payment). A paired chat: the text's wire id, a payment's id, a file's wire id. A\n * group: the message id, which is the same for every member.\n */\nexport function replyRef(message: ReplyTarget, group = message.linkId?.startsWith(GROUP_LINK) ?? false): string | undefined {\n if (message.ref) return message.ref;\n if (group) return message.paymentId || message.event || message.groupPay || !message.id.includes(\":\") ? undefined : message.id;\n if (message.paymentId) return paymentWireId(message.paymentId);\n if (message.wireId && WIRE_ID.test(message.wireId)) return message.wireId;\n const out = message.file?.id.match(/-out-([A-Za-z0-9_-]{8,64})$/);\n if (out) return out[1];\n const row = message.id.match(PAIRED_ROW);\n return row && !/^\\d+$/.test(row[1]) ? row[1] : undefined;\n}\n\n/** A reply to `original` as this side keeps it: always found, since it is here. The engine's row, or the UI's copy. */\nexport function replyTo(original: Pick<StoredMessage, \"id\" | \"text\" | \"member\"> & { sender: string }, ref: string): MessageReply {\n return { id: ref, snippet: replySnippet(original.text), from: original.sender === \"me\" ? \"me\" : \"peer\",\n ...(original.member && { member: original.member }), messageId: original.id };\n}\n\n/**\n * A reply as it goes on a paired chat's wire, from the side that sends it (`f`: who wrote the original, from the\n * sender's side). For a group, `f` is the author's member key, which the reply keeps.\n */\nexport function pairedWireReply(reply: MessageReply, sender: \"me\" | \"peer\" = \"me\"): WireReply {\n return { i: reply.id, s: reply.snippet, f: reply.from === sender ? \"sender\" : \"recipient\", ...(reply.button && { b: reply.button }) };\n}\n\n/** A paired chat's reply as it arrived (`f` from the sender's side), as this side keeps it. */\nexport function receivedPairedReply(reply: WireReply | { i: string }): MessageReply {\n if (!(\"f\" in reply)) return { id: reply.i, snippet: \"\" };\n return { id: reply.i, snippet: reply.s, from: reply.f === \"sender\" ? \"peer\" : \"me\", ...(reply.b && { button: reply.b }) };\n}\n\n/** A group's reply as it arrived or was sent (`f` the author's member key), as this member keeps it. */\nexport function groupReply(reply: WireReply, myKey: string): MessageReply {\n return { id: reply.i, snippet: reply.s, from: reply.f === myKey ? \"me\" : \"peer\", member: reply.f, ...(reply.b && { button: reply.b }) };\n}\n","import {\n ChatFiles,\n FileUplink,\n GROUP_FILE_LIMITS,\n GROUP_HAVE_FRAME,\n GROUP_WANT_FRAME,\n GROUP_WANT_NO_FRAME,\n RateWindow,\n fetchesByItself,\n fileMessageText,\n groupFileFallback,\n isGroupMessageId,\n meshMessageRef,\n randomBytes,\n readGroupHave,\n readGroupWant,\n readGroupWantNo,\n toBase64Url,\n transferEnded,\n type FileInfo,\n type FileTransferRecord,\n type GroupFileMeta,\n type GroupWantRefusal,\n type IncomingTarget,\n type OfferDecision,\n type OutgoingSource,\n} from \"@ghostly/core\";\nimport { fileBytes, fileBytesOf } from \"../shared/fileBytes\";\nimport { fileStore, type StoredFile } from \"../shared/idb\";\nimport { FileAppender, readStored, removeStored } from \"../shared/storedFiles\";\nimport type { FileTransferView, MessageFile } from \"../shared/types\";\n\n/*\n * Files and voice messages in groups (WISP 503 · Group Files), the engine's side. A file is announced as a group message\n * carrying its description (`fl`); each member's app then fetches the bytes from a member that holds them, over\n * `files/3` on the edge between the two (`ChatFiles`, WISP 501): it sends `group-want`, the holder offers the file with\n * `gm` naming the message, and what arrives is checked against the author's digest. Whoever stored it holds it, and says\n * so (`group-have`), so a member away during the announcement gets it later from whoever is there.\n */\n\n/** A group file's local id: its group's and a random part, never anything a member sends. */\nexport const groupFileId = (groupId: string, direction: \"in\" | \"out\", random = toBase64Url(randomBytes(12))) => `group-${groupId}-${direction}-${random}`;\n/** The group a local file id names, among `groupIds`. */\nexport const groupOfFile = (fileId: string, groupIds: Iterable<string>): string | undefined =>\n [...groupIds].find(g => fileId.startsWith(`group-${g}-in-`) || fileId.startsWith(`group-${g}-out-`));\n\n/** What a file's message says: its caption, or (when the author wrote none) the file itself, not the line older apps show. */\nexport const groupFileText = (text: string, meta: GroupFileMeta): string => text === groupFileFallback(meta) ? fileMessageText(meta) : text;\n\n/** Where a group's files are kept: the profile's file store and file storage (`storedGroupFiles`), or a test's memory. */\nexport interface GroupFileStore {\n /** The records of a group's files (`linkId` `group:<id>`). */\n list(groupId: string): Promise<StoredFile[]>;\n /** Every group a stored file is of, whether or not this device still has the group. */\n groups(): Promise<string[]>;\n get(id: string): Promise<StoredFile | undefined>;\n put(file: StoredFile): Promise<void>;\n patch(id: string, fields: Pick<StoredFile, \"transfer\" | \"group\">): Promise<void>;\n /** The record and its bytes. */\n remove(id: string): Promise<void>;\n /**\n * Writes a file in order: from its first byte (whatever was there goes), or with `resume` after what an earlier\n * transfer stored (the writer's `offset`).\n */\n write(id: string, resume?: boolean): Promise<GroupFileWriter>;\n /** At most `length` bytes of a kept file from `offset`. */\n read(file: StoredFile, offset: number, length: number): Promise<Uint8Array>;\n /** Bytes this device can still take for files, or null when the platform does not say. */\n room(): Promise<number | null>;\n}\n\nexport interface GroupFileWriter {\n /** Where it writes from: the bytes already stored. */\n offset: number;\n append(bytes: Uint8Array): Promise<void>;\n flush(): Promise<void>;\n /** SHA-256 of what was stored, read back from storage, base64url. */\n digest(): Promise<string>;\n /** Done writing for now: what is stored stays. */\n close(): Promise<void>;\n discard(): Promise<void>;\n}\n\n/** The profile's files store and file storage, as a 1:1 chat's files use them. */\nexport const storedGroupFiles: GroupFileStore = {\n list: groupId => fileStore.listForLink(`group:${groupId}`),\n groups: () => fileStore.groupIds(),\n get: id => fileStore.get(id),\n put: file => fileStore.put(file),\n patch: (id, fields) => fileStore.patch(id, fields),\n remove: id => removeStored(id),\n async write(id, resume = false) {\n const stored = await fileStore.get(id);\n const bytes = (stored?.bytes && await fileBytesOf(stored.bytes)) || await fileBytes();\n const size = await bytes.size(id);\n const offset = resume && size !== null ? size : 0;\n if (size !== null && size !== offset) await bytes.truncate(id, offset);\n if (stored && stored.bytes !== bytes.kind) await fileStore.patch(id, { bytes: bytes.kind });\n const appender = new FileAppender(bytes, id, offset);\n return {\n offset,\n append: chunk => appender.append(chunk),\n flush: () => appender.flush(),\n digest: async () => { await appender.close(); return bytes.digest(id); },\n close: () => appender.close(),\n discard: async () => { await appender.close().catch(() => {}); await bytes.remove(id); },\n };\n },\n read: (file, offset, length) => readStored(file, offset, length),\n room: async () => (await fileBytes()).room(),\n};\n\n/** What the engine gives the group files: where they are kept, their views, the profile's settings, an edge's files/3. */\nexport interface GroupFilesHost {\n store: GroupFileStore;\n transfers: Map<string, FileTransferView>;\n /** The file's view goes in the next state the engine sends, and then away: the file's record says the rest. */\n brief(fileId: string): void;\n settings(): { autoDownloads: boolean; serveFiles: boolean };\n /** A files/3 frame on an edge's open session; false when it could not go. */\n sendFiles(linkId: string, frame: Record<string, unknown>): boolean;\n /** A file's bytes on an edge, in the form its session agreed (`GhostLink.sendFileData`, files/4). Absent: `pf-data` frames. */\n sendData?(linkId: string, id: string, offset: number, data: Uint8Array): boolean;\n /** Resolves once the edge's session can take another data frame. */\n writable?(linkId: string): Promise<void> | undefined;\n}\n\n/** Me in a group I am active in, and who could read one of its messages. */\nexport interface GroupFileMembership {\n me: string;\n community: boolean;\n /**\n * A private group laid out on hubs (WISP 902 § Hubs): a member that is not a hub has edges with its hubs only, so the\n * other members' files reach it only once a hub holds them.\n */\n onHubs?: boolean;\n inRoster(key: string): boolean;\n /**\n * In the roster now, and in the roster of the message's epoch or of one its author said it again under: `arrived`, the\n * one it reached this device under (WISP 503 § Asking).\n */\n couldRead(key: string, messageId: string, arrived?: number): boolean;\n}\n\nexport interface GroupFileDeps extends GroupFilesHost {\n /** A group frame on an edge; false when it could not go. */\n send(linkId: string, frame: Record<string, unknown>): boolean;\n /** Member key → edge link id, for the group's edges. */\n edges(groupId: string): Map<string, string>;\n /** The edge is up, and the app at its other end announced group files (`GROUP_VERSION_FILES`). */\n ready(linkId: string): boolean;\n membership(groupId: string): GroupFileMembership | undefined;\n /**\n * Why this device is out of the group for good (removed, its history forked), or undefined while it is in it: no\n * holder serves it any more, so its files not here stop coming and say so.\n */\n out?(groupId: string): string | undefined;\n /** An application frame to everyone in a community. */\n sendApp(groupId: string, frame: Record<string, unknown>): Promise<void>;\n /** A row changed: the pages get a state. `delayMs`: how long it may wait (the engine's own wait when not given). */\n changed(delayMs?: number): void;\n now(): number;\n}\n\n/**\n * Time gone by, on the monotonic clock: a transfer's pace and how long it held its place, which a device clock set\n * ahead or back (`deps.now()`, the wall clock) would cut short or stretch. Stored times and the day stay on the wall clock.\n */\nconst elapsed = (): number => performance.now();\n\n/** A group file this device knows of: one it announced, or one a member announced. */\ninterface Kept {\n id: string;\n groupId: string;\n message: string;\n author: string;\n /**\n * The epoch its announcement reached this device under, when later than the message's own (said again by its author,\n * who was behind): its roster could read it too (`couldRead`).\n */\n arrived?: number;\n meta: GroupFileMeta;\n /** I announced it: my copy is its first. */\n mine: boolean;\n /** Fetched without asking: it counts toward the group's automatic limit. */\n auto: boolean;\n /** Its person asked for it (Download). */\n asked: boolean;\n /** Its person paused it: what came stays, and it reads paused after a restart too, until Resume. */\n paused?: boolean;\n /** Every byte is here, checked against the author's digest: this device holds it. */\n held: boolean;\n /** Members said to hold it (`group-have`), or that offered it, newest first. The author is asked whether or not it is here. */\n holders: string[];\n /** A discard of what an earlier transfer stored, which the next one waits for. */\n idle?: Promise<void>;\n /** Its transfer's write under way to storage, which a Leave waits for before it deletes the file (`drop`). */\n writing?: Promise<unknown>;\n /** Bytes a transfer stored here that the next one goes on from, shown while it waits for a holder. */\n stored?: number;\n /** The transfer (its id on the edge) its person cancelled: what it stored is deleted, not kept for the next one. */\n dropped?: string;\n /**\n * The bytes kept from an earlier holder did not check out with the next one's tail: who served the bad part is not\n * known, so the next transfer starts from 0 (`fresh`) and the holder whose tail failed is not counted as damaged\n * (`unclear`, read once by `transferChanged`).\n */\n fresh?: boolean;\n unclear?: boolean;\n /**\n * The holder every byte stored here came from, in this run (none once two holders' bytes are mixed): its tail failing\n * the check is its own bytes failing, so it counts as damaged, however many transfers it split them into.\n */\n storedBy?: string;\n /**\n * Holders whose bytes failed the author's digest: not asked again for it, whatever the round, until its person asks\n * for it again (Download). Once every holder known is here, it is fetched no more (`DAMAGED`).\n */\n damaged: Set<string>;\n /**\n * Holders whose tail failed the check on bytes an earlier holder stored (`unclear`): whose bytes were bad is not known,\n * so each is asked last, never left for mid-way (`leaveSlow`), and serves only from 0: its own bytes failing then\n * count as damaged. Until its person asks for it again (Download).\n */\n suspect?: Set<string>;\n /** The holder its last transfer was left with (it stalled, or its person paused it): asked last, not first, next time. */\n left?: string;\n}\n\n/** A file being asked for: of one holder at a time. */\ninterface Want {\n /** The holder asked now and the edge it was asked on; none while nobody reachable has it. */\n holder?: string;\n linkId?: string;\n at: number;\n /**\n * When this round began: once `wantWaitMs` went by and nobody is asked, a new round asks every holder again, the one\n * left too. Asks that find nobody, or a member that says it holds the file and answers `gone`, do not put it off.\n */\n round: number;\n /** Holders asked in this round that had nothing to give: the next ask goes to another. */\n tried: Set<string>;\n /**\n * The holder's transfer, once it offered: its id on the edge, and the bytes stored when it last moved by\n * `wantMoveBytes` and when, on the monotonic clock (-1 until its first change: a resumed transfer starts at what was\n * stored before).\n */\n wire?: string;\n moved: number;\n movedAt: number;\n /** When the holder offered (on the monotonic clock), and the bytes stored here then: its pace is what moved since. */\n offeredAt?: number;\n offeredBytes?: number;\n /**\n * Holders that answered `busy` in this round and said since, while another served it, that they hold the file (a place\n * of theirs freed): one it may leave for, as for a known holder, when that one is slow (`leaveSlow`).\n */\n free?: Set<string>;\n /**\n * The holders known when the holder offered: one it may leave for when that one is slow (`leaveSlow`). Not one that\n * came to hold the file since: the members waiting take its places at once.\n */\n knownAtOffer?: Set<string>;\n /** What the last holder asked in this round answered, when it was not the file: shown while the want waits. */\n why?: \"busy\" | \"day\" | \"damaged\";\n /**\n * Holders that answered `busy` in this round: one of them in reach tells this device when its place frees (its\n * `group-have`), so members never heard of as holders are not asked meanwhile.\n */\n busy?: Set<string>;\n}\n\n/** One edge's files/3, both ways. */\ninterface Edge {\n linkId: string;\n groupId: string;\n peer: string;\n files: ChatFiles;\n /** Transfers this side serves on the edge (their wire id) → the local file. */\n serving: Map<string, string>;\n /**\n * Of each transfer served: the bytes the asker confirmed, when that last moved, and when it was offered; once accepted,\n * what was confirmed at a mark at least `servePaceMs` old (`mark`, the first at the offer) and at the next (`next`),\n * as [bytes, when]. Its times are on the monotonic clock.\n */\n servedMoved: Map<string, { confirmed: number; at: number; from: number; mark?: [number, number]; next?: [number, number] }>;\n /** Files this side served its member that lost their place for their pace (`makeRoom`): not again. */\n paced: Set<string>;\n /** Transfers this side takes on the edge (the holder's wire id) → the local file. */\n taking: Map<string, string>;\n /** Transfers that ended on the edge, oldest first: the last `ENDED_KEPT` keep their record, the rest are forgotten. */\n ended: [\"in\" | \"out\", string][];\n /** Message ids to say in the next `group-have`, and the frames of it that went lately (`haveFrames` in `haveWindowMs`). */\n have: Set<string>;\n haveSent: RateWindow;\n /** Its member's `group-have` frames taken lately: no more than `haveFramesTaken` in `haveWindowMs`, twice what it may send; past that, dropped. */\n haveTaken: RateWindow;\n /**\n * Wants sent on the edge lately (`wantFrames` in `wantWindowMs`), and whether one waited for that window to free; and\n * its member's taken lately (`wantFramesTaken`, twice that): past that, dropped before anything is looked up.\n */\n wantSent: RateWindow;\n wantPaced?: boolean;\n wantTaken: RateWindow;\n /**\n * Message ids its member asked for while this device served all it serves at once, and when: said in a `group-have`\n * once a slot frees.\n */\n busy: Map<string, number>;\n /** Message ids its member said it does not hold (`gone`): not asked of it again until it says it does, or the edge's session closes or opens. */\n gone: Set<string>;\n}\n\n/**\n * Ended transfers an edge keeps the record of. A late frame for one of them is still answered as files/3 says (an abort\n * to an asker going on with a transfer cancelled here); older ones are forgotten, so an edge's records stay few\n * however many transfers it has seen.\n */\nconst ENDED_KEPT = 8;\n\n/** Why a want waits, as the person reads it (the app shows its own words for each `wait`). */\nconst WAITING_NOTES = {\n nobody: \"Nobody you are connected to has this file yet\",\n author: \"Nobody you are connected to has this file yet, and its sender is not one of them\",\n busy: \"Its holders are busy; asking again soon\",\n day: \"Its holders have shared all they can today; it comes when another member has it, or tomorrow\",\n damaged: \"It arrived damaged; ask again\",\n} as const;\n/** Why a want stopped: every holder served bytes that are not the author's file. */\nconst DAMAGED = \"Every copy of this file arrived damaged and was deleted. Ask for it again later.\";\n/** Why a want stopped, or a Download was refused: this device has no room for the file. */\nconst NO_ROOM = \"Not enough space on this device for this file\";\n\nexport class GroupFileDesk {\n private readonly kept = new Map<string, Kept>();\n /** `<group>\\n<message id>` → local id. */\n private readonly byMessage = new Map<string, string>();\n private readonly wants = new Map<string, Want>();\n /**\n * The want last asked on each edge (by link id), and its file: whether a file is asked of an edge's member is read here,\n * not by going through every want each time (`askedOf`). An entry the want has moved on from is dropped when read.\n */\n private readonly askedOn = new Map<string, { id: string; want: Want }>();\n private readonly edgesById = new Map<string, Edge>();\n /**\n * My files about to be announced, by `<group>\\n<digest>`, in the order they were handed over: the message that\n * announces one takes the first one's local id. A list, not one id: the same bytes sent twice at once (two picks, two\n * CLI sends) are two files, each its own message's. A group's sends are announced one after another in the order they\n * were made, so the first waiting is this message's (agents#3772).\n */\n private readonly own = new Map<string, { fileId: string; meta: GroupFileMeta }[]>();\n /** Announcements sent per group, and taken per member of a group (WISP 503 § Rules for both, Pace). */\n private readonly sentPace = new Map<string, RateWindow>();\n private readonly sentTaken = new Map<string, RateWindow>();\n private readonly takenPace = new Map<string, RateWindow>();\n /** `<group>\\n<message id>` a `group-have` named before its message came → its holders, newest first. */\n private readonly ahead = new Map<string, string[]>();\n /** A community's ids for its next `group-have`, and when one last went. */\n private readonly communityHave = new Map<string, { ids: Set<string>; at: number }>();\n /** Bytes served today, and the day (UTC days since the epoch). */\n private served = { day: 0, bytes: 0 };\n\n /**\n * The uplink every edge's files leave this device by: the floor of their windows is shared out among those sending.\n * Each with 64 KiB of its own, serving one file to three members at 1 Mbit/s held everything else this device said\n * 1-2 s behind them (agents#1569).\n */\n private readonly uplink = new FileUplink();\n\n constructor(private readonly deps: GroupFileDeps) {}\n\n // -- what the groups hand over -------------------------------------------------------------------------------\n\n /**\n * At start: each group's files as they were kept. One fetched by itself, or asked for, and not here yet is asked for\n * again; with automatic downloads off, one chosen by itself before waits for a Download instead.\n */\n async load(groupIds: string[]): Promise<void> {\n for (const groupId of groupIds) {\n for (const file of await this.deps.store.list(groupId).catch(() => [])) {\n if (!file.group || !file.metadata || !file.digest || this.kept.has(file.id)) continue;\n const { name, size, mime, voice, video, image } = file.metadata;\n const kept: Kept = { id: file.id, groupId, message: file.group.message, author: file.group.author, ...(file.group.arrived !== undefined && { arrived: file.group.arrived }),\n meta: { name, size, mime, d: file.digest, ...(voice && { voice }), ...(video && { video }), ...(image && { image }) },\n mine: file.direction === \"out\", auto: !!file.group.auto, asked: !!file.group.asked, held: file.transfer?.state === \"done\", holders: [], damaged: new Set() };\n this.add(kept);\n // All here: it shows no transfer (a file with none reads as finished; its record says done). A view for each\n // would go into every state the engine builds, so each state would cost more with every file the groups ever had.\n if (kept.held) continue;\n // Every holder served it damaged: it waits for its person to ask again, not fetched again by itself.\n if (file.transfer?.state === \"failed\") this.show(kept, { state: \"failed\", transferred: 0, size, direction: \"in\", retry: !this.deps.out?.(groupId), error: file.transfer.error ?? DAMAGED });\n // Paused by its person: still paused, with the bytes that came (what the next transfer goes on from).\n else if (file.group.paused) {\n kept.paused = true;\n kept.stored = await this.keptBytes(kept.id);\n this.show(kept, { state: \"transferring\", stage: \"paused\", pausedBy: \"me\", transferred: kept.stored, size, direction: \"in\" });\n }\n else if (kept.asked || (kept.auto && this.deps.settings().autoDownloads)) this.wants.set(kept.id, this.newWant());\n else if (kept.auto) await this.stop(kept, false);\n // Waiting for a Download: no transfer either. Its record says it is not here (`waitingGroupFile`).\n }\n }\n for (const [id] of this.wants) this.ask(this.kept.get(id)!);\n this.deps.changed();\n }\n\n /**\n * At start, once every group was read: the files of a group this device no longer has (`groupIds` are the groups it\n * has, a tombstone or a join under way among them) go, with their bytes. A group left before Leave took its files\n * left them behind, where nothing lists them.\n */\n async sweep(groupIds: string[]): Promise<void> {\n const here = new Set(groupIds);\n for (const groupId of await this.deps.store.groups().catch(() => [])) {\n if (here.has(groupId)) continue;\n for (const file of await this.deps.store.list(groupId).catch(() => [])) await this.deps.store.remove(file.id).catch(() => {});\n }\n }\n\n /**\n * The person stops a file that is coming, or that this device would fetch (Cancel, Decline): nobody is asked for it\n * any more, the transfer under way ends, what came of it is deleted, and it waits for a Download. Paused (`keep`),\n * what came stays, and Resume (`download`) goes on from there.\n */\n async halt(fileId: string, keep = false): Promise<void> {\n const kept = this.kept.get(fileId);\n if (!kept) throw new Error(\"No such file\");\n // Only a file that is coming pauses: one waiting for a Download has nothing to go on with.\n if (keep && !this.wants.has(fileId)) return;\n await this.stop(kept, keep);\n }\n\n /**\n * Its author deleted the message for everyone (WISP 400 § Delete for everyone): its file stops coming, nobody is\n * asked for it, and what came of it goes from this device.\n */\n async forget(groupId: string, messageId: string): Promise<void> {\n const key = `${groupId}\\n${messageId}`, kept = this.kept.get(this.byMessage.get(key) ?? \"\");\n if (!kept) return;\n await this.stop(kept, false).catch(() => {});\n this.kept.delete(kept.id);\n this.byMessage.delete(key);\n this.wants.delete(kept.id);\n this.deps.transfers.delete(kept.id);\n await kept.writing?.catch(() => {});\n await this.deps.store.remove(kept.id).catch(() => {});\n this.deps.changed();\n }\n\n /** Automatic downloads were turned off: files chosen by themselves and not here yet stop coming, and wait for a Download. */\n async autoDownloadsOff(): Promise<void> {\n for (const kept of [...this.kept.values()]) if (kept.auto && !kept.asked && this.wants.has(kept.id)) await this.stop(kept, false);\n }\n\n private async stop(kept: Kept, keep: boolean): Promise<void> {\n if (kept.held || kept.mine) return;\n const want = this.wants.get(kept.id);\n // Gone first: the transfer's end below asks nobody else (`transferChanged`), and a late offer is refused.\n this.wants.delete(kept.id);\n // Paused on a holder's transfer: Resume asks the others first.\n if (want?.wire && want.holder) kept.left = want.holder;\n const edge = want?.wire && want.linkId ? this.edgesById.get(want.linkId) : undefined;\n const record = edge?.files.get(\"in\", want!.wire!);\n const { size } = kept.meta;\n // One every holder served damaged waits for a Download as any other: its record no longer says it failed.\n const failed = !keep && this.deps.transfers.get(kept.id)?.state === \"failed\";\n if (!keep) { kept.stored = 0; kept.fresh = true; }\n if (edge && record && !transferEnded(record)) {\n // The transfer's own writer deletes what it stored (`openTarget`), or keeps it when paused.\n if (!keep) kept.dropped = record.id;\n edge.files.cancel(\"in\", record.id);\n edge.taking.delete(record.id);\n } else if (!keep) {\n // No transfer under way: what an earlier one stored goes, before the next one writes.\n kept.idle = (kept.idle ?? Promise.resolve()).then(() => this.deps.store.write(kept.id)).then(writer => writer.discard()).catch(() => {});\n }\n if (keep) this.show(kept, { state: \"transferring\", stage: \"paused\", pausedBy: \"me\", transferred: kept.stored ?? 0, size, direction: \"in\" });\n else this.waiting(kept);\n // Not fetched by itself any more, nor asked for: it stays stopped (or paused) after a restart, and counts toward no limit.\n const wasPaused = !!kept.paused;\n kept.paused = keep;\n if (kept.auto || kept.asked || wasPaused !== keep || failed) {\n kept.auto = kept.asked = false;\n await this.deps.store.patch(kept.id, { group: this.groupField(kept), ...(failed && { transfer: { state: \"transferring\", transferred: 0, size } }) }).catch(() => {});\n }\n }\n\n /**\n * An error when this group took as many announcements of mine as it takes in a minute, or as its members take from\n * one member in `announceWindowMs` (past that they would not fetch the file by themselves); null when one may go now.\n */\n mayAnnounce(groupId: string): string | null {\n const wait = Math.max(...this.sentPaces(groupId).map(pace => pace.wait()));\n if (!wait) return null;\n const minutes = Math.ceil(wait / 60_000);\n return `You sent many files to this group just now. Wait ${minutes > 1 ? `${minutes} minutes` : \"a minute\"}.`;\n }\n\n /** My file, stored under `fileId` with the author's digest, is about to be announced in the group: its message takes it. */\n outgoing(groupId: string, fileId: string, meta: GroupFileMeta): void {\n const key = `${groupId}\\n${meta.d}`;\n this.own.set(key, [...this.own.get(key) ?? [], { fileId, meta }]);\n }\n /**\n * The announcement did not go: the file is not this group's after all. `meta` is the one handed to `outgoing`, which\n * tells it from another send of the same bytes still on its way (its caller deletes this one's local id).\n */\n notSent(groupId: string, meta: GroupFileMeta): void {\n const key = `${groupId}\\n${meta.d}`, waiting = this.own.get(key) ?? [];\n const at = waiting.findIndex(entry => entry.meta === meta);\n const left = waiting.filter((_, i) => i !== (at < 0 ? 0 : at));\n if (left.length) this.own.set(key, left); else this.own.delete(key);\n }\n\n /**\n * The local id of my file a message of mine announces, taken from those waiting: the first whose record is still\n * here. One whose send failed past its caller's notice (its record deleted) is passed over, not given to this message.\n */\n private async takeOwn(groupId: string, digest: string): Promise<string | undefined> {\n const key = `${groupId}\\n${digest}`;\n for (let waiting = this.own.get(key); waiting?.length; waiting = this.own.get(key)) {\n const [{ fileId }, ...rest] = waiting;\n if (rest.length) this.own.set(key, rest); else this.own.delete(key);\n if (await this.deps.store.get(fileId).then(record => !!record, () => true)) return fileId;\n }\n return undefined;\n }\n\n /**\n * A message of the group announces a file (mine, or a member's): the file its row shows. A member's is kept here\n * unfetched, and fetched now when it is one this device takes by itself and the member announced no more than the\n * group fetches that way. The same message again (a catch-up, a whole copy) is the same file.\n */\n async announced(groupId: string, m: { id: string; sender: string; epoch?: number; file: GroupFileMeta }, me: string): Promise<MessageFile | undefined> {\n const known = this.byMessage.get(`${groupId}\\n${m.id}`);\n if (known) { this.arrivedAgain(groupId, m.id, m.epoch); return messageFile(this.kept.get(known)!); }\n // Only a send of mine waits on the store here: any other message is known at once (below), before a copy of it comes.\n const ownId = m.sender === me && this.own.has(`${groupId}\\n${m.file.d}`) ? await this.takeOwn(groupId, m.file.d) : undefined;\n if (ownId) {\n for (const pace of this.sentPaces(groupId)) pace.take();\n const kept: Kept = { id: ownId, groupId, message: m.id, author: me, meta: m.file, mine: true, auto: false, asked: false, held: true, holders: [], damaged: new Set() };\n this.add(kept);\n const transfer = { state: \"done\" as const, transferred: m.file.size, size: m.file.size };\n await this.deps.store.patch(ownId, { group: { message: m.id, author: me }, transfer }).catch(() => {});\n this.finished(kept, \"out\");\n this.queueHave(kept);\n return messageFile(kept);\n }\n // More from one member than a group fetches by itself: past it, the file is kept and waits for a Download (WISP 503,\n // Pace). Counted as they come, so a catch-up of files sent over hours is one burst: none of them is lost to it.\n const paced = this.pace(this.takenPace, `${groupId}\\n${m.sender}`, GROUP_FILE_LIMITS.announceTaken, GROUP_FILE_LIMITS.announceWindowMs).take();\n const id = groupFileId(groupId, \"in\");\n // No room here for it: it waits for a Download, which says so, rather than be asked for and refused here.\n const auto = paced && this.deps.settings().autoDownloads && fetchesByItself(m.file, this.keptAutomatically(groupId)) && await this.hasRoom(m.file.size);\n const holders = this.ahead.get(`${groupId}\\n${m.id}`) ?? [];\n this.ahead.delete(`${groupId}\\n${m.id}`);\n const arrived = laterEpoch(m.id, m.epoch);\n const kept: Kept = { id, groupId, message: m.id, author: m.sender, ...(arrived !== undefined && { arrived }), meta: m.file, mine: false, auto, asked: false, held: false, holders, damaged: new Set() };\n const { name, size, mime, voice, video, image } = m.file;\n // Known at once: the same message coming again meanwhile (another copy of it) is this file.\n this.add(kept);\n // No bytes yet: where they go is decided when they come (`GroupFileStore.write`).\n await this.deps.store.put({ id, linkId: `group:${groupId}`, direction: \"in\", digest: m.file.d, createdAt: this.deps.now(),\n metadata: { name, size, mime, timestamp: this.deps.now(), voice, video, image },\n transfer: { state: \"transferring\", transferred: 0, size }, group: { message: m.id, author: m.sender, ...(arrived !== undefined && { arrived }), ...(auto && { auto: true }) } });\n if (auto) { this.wants.set(id, this.newWant()); this.ask(kept); }\n else this.waiting(kept);\n return messageFile(kept);\n }\n\n /**\n * A message whose file is known here reached this device again, said again by its author under a later epoch (it was\n * behind): that epoch's members could read it too, and are served it.\n */\n arrivedAgain(groupId: string, messageId: string, epoch: number | undefined): void {\n const kept = this.kept.get(this.byMessage.get(`${groupId}\\n${messageId}`) ?? \"\");\n const arrived = laterEpoch(messageId, epoch);\n if (!kept || arrived === undefined || arrived <= (kept.arrived ?? -1)) return;\n kept.arrived = arrived;\n this.deps.store.patch(kept.id, { group: this.groupField(kept) }).catch(() => {});\n }\n\n /** The person asks for a file this device did not fetch by itself (Download), or for one that stopped coming. */\n async download(fileId: string): Promise<void> {\n const kept = this.kept.get(fileId);\n if (!kept) throw new Error(\"No such file\");\n if (kept.held) return;\n const out = this.deps.out?.(kept.groupId);\n if (out) throw new Error(out);\n if (!await this.hasRoom(kept.meta.size)) throw new Error(NO_ROOM);\n if (!kept.asked || kept.paused) {\n kept.asked = true; kept.paused = false;\n await this.deps.store.patch(kept.id, { group: this.groupField(kept) }).catch(() => {});\n }\n // Asked again: every holder is worth asking again, one that served it damaged too.\n kept.damaged.clear();\n kept.suspect = undefined;\n if (this.deps.transfers.get(kept.id)?.state === \"failed\") {\n await this.deps.store.patch(kept.id, { transfer: { state: \"transferring\", transferred: 0, size: kept.meta.size } }).catch(() => {});\n }\n const want = this.wants.get(kept.id);\n if (!want) this.wants.set(kept.id, this.newWant());\n else if (!want.wire) { want.tried.clear(); want.why = want.busy = undefined; want.round = this.deps.now(); }\n this.ask(kept);\n }\n\n /** The group is gone from this device: its files go too. */\n async drop(groupId: string): Promise<void> {\n for (const kept of [...this.kept.values()].filter(k => k.groupId === groupId)) {\n this.kept.delete(kept.id);\n this.byMessage.delete(`${groupId}\\n${kept.message}`);\n this.wants.delete(kept.id);\n this.deps.transfers.delete(kept.id);\n // A write under way goes first; after it, the file's transfer writes nothing more (`openTarget`).\n await kept.writing?.catch(() => {});\n await this.deps.store.remove(kept.id).catch(() => {});\n }\n for (const [linkId, edge] of this.edgesById) if (edge.groupId === groupId) { edge.files.detach(); this.edgesById.delete(linkId); }\n for (const key of [...this.ahead.keys()]) if (key.startsWith(`${groupId}\\n`)) this.ahead.delete(key);\n this.communityHave.delete(groupId);\n this.deps.changed();\n }\n\n // -- edges ---------------------------------------------------------------------------------------------------\n\n /** An edge's files/3 session opened (both sides agreed it) or closed. */\n session(groupId: string, peer: string, linkId: string, open: boolean): void {\n const edge = this.edge(groupId, peer, linkId);\n if (open) edge.files.attach(); else edge.files.detach();\n // Another session, or none: its member may have fetched since what it did not hold, and is asked again.\n edge.gone.clear();\n if (open) this.retry(groupId);\n }\n\n /** An edge came up and both sides said where they are: what this device holds goes to it, and wants waiting for a holder go. */\n edgeReady(groupId: string, peer: string, linkId: string): void {\n if (!this.deps.ready(linkId)) return;\n const edge = this.edge(groupId, peer, linkId);\n if (this.deps.settings().serveFiles) {\n const held = [...this.kept.values()].filter(k => k.groupId === groupId && k.held).map(k => k.message).slice(-GROUP_FILE_LIMITS.haveIds);\n if (held.length) this.sendHave(edge, held);\n }\n this.retry(groupId);\n }\n\n /** A `group-want`, `group-want-no` or `group-have` on an edge, from the member it is pinned to. */\n async frame(groupId: string, peer: string, linkId: string, frame: Record<string, unknown>): Promise<void> {\n if (frame.t === GROUP_WANT_FRAME) {\n const want = readGroupWant(frame, groupId);\n const edge = want && this.edge(groupId, peer, linkId);\n if (edge && edge.wantTaken.take()) await this.serve(edge, want.id);\n } else if (frame.t === GROUP_WANT_NO_FRAME) {\n const no = readGroupWantNo(frame, groupId);\n if (no) this.refused(groupId, peer, linkId, no.id, no.why);\n } else if (frame.t === GROUP_HAVE_FRAME) {\n const ids = readGroupHave(frame, groupId);\n // Each one makes its member worth asking again: taken at about the pace it may send them, not much faster.\n if (ids && this.edge(groupId, peer, linkId).haveTaken.take()) this.heard(groupId, peer, ids);\n }\n }\n\n /** A community's `group-have`, an application frame its signer sent the group. */\n communityApp(groupId: string, sender: string, frame: Record<string, unknown>): void {\n const ids = readGroupHave(frame);\n if (ids) this.heard(groupId, sender, ids);\n }\n\n /**\n * A files/3 frame on an edge. An offer is taken only for a file this device asked that member for (`gm` naming the\n * message): nobody can push a file into another's storage. What it brings belongs to the group's message, not to the\n * edge as a chat.\n */\n filesFrame(groupId: string, peer: string, linkId: string, frame: Record<string, unknown>): Promise<void> {\n const edge = this.edge(groupId, peer, linkId);\n if (frame.t === \"pf-offer\" && typeof frame.id === \"string\" && /^[A-Za-z0-9_-]{8,64}$/.test(frame.id) && !edge.taking.has(frame.id)) {\n const kept = isGroupMessageId(frame.gm) ? this.kept.get(this.byMessage.get(`${groupId}\\n${frame.gm}`) ?? \"\") : undefined;\n const want = kept && this.wants.get(kept.id);\n if (!kept || kept.held || !want || want.linkId !== linkId || want.wire) {\n this.deps.sendFiles(linkId, { t: \"pf-refuse\", id: frame.id, why: \"invalid\" });\n return Promise.resolve();\n }\n edge.taking.set(frame.id, kept.id);\n // It offers the file: it holds it, whether or not it ever said so.\n kept.holders = newestHolder(peer, kept.holders);\n want.wire = frame.id;\n want.why = undefined;\n want.moved = -1;\n want.movedAt = want.offeredAt = elapsed();\n want.offeredBytes = kept.stored ?? 0;\n want.free = undefined;\n want.knownAtOffer = new Set(kept.holders);\n }\n return edge.files.handle(frame);\n }\n\n /** Wants that waited too long for an offer, or for bytes, go to the next holder; `group-have`s gathered go. */\n tick(): void {\n const now = this.deps.now();\n for (const [id, want] of this.wants) {\n const kept = this.kept.get(id);\n if (!kept) { this.wants.delete(id); continue; }\n if (this.leaveSlow(kept, want) || this.leaveGone(kept, want)) continue;\n if ((want.wire ? elapsed() - want.movedAt : now - (want.holder ? want.at : want.round)) < GROUP_FILE_LIMITS.wantWaitMs) continue;\n if (want.wire) {\n // A holder that stalls, or sends too little to count (`wantMoveBytes`), is left: the transfer ends here, and the\n // next holder is asked (`transferChanged`).\n kept.left = want.holder;\n const edge = want.linkId ? this.edgesById.get(want.linkId) : undefined;\n if (edge?.files.get(\"in\", want.wire) && !transferEnded(edge.files.get(\"in\", want.wire)!)) { edge.files.cancel(\"in\", want.wire); continue; }\n want.wire = undefined;\n }\n if (want.holder) want.tried.add(want.holder);\n // Everyone asked in turn: a new round, as holders come and go.\n else { want.tried.clear(); want.why = want.busy = undefined; want.round = now; }\n this.ask(kept);\n }\n this.letGo();\n this.makeRoomForWaiting();\n // Wants that waited for an edge's window: asked now that it freed.\n const freed = new Set<string>();\n for (const edge of this.edgesById.values()) if (edge.wantPaced && !this.paced(edge.linkId)) { edge.wantPaced = false; freed.add(edge.groupId); }\n for (const groupId of freed) this.retry(groupId);\n for (const edge of this.edgesById.values()) {\n if (edge.have.size && this.deps.ready(edge.linkId)) this.sendHave(edge, [...edge.have]);\n }\n for (const [groupId, have] of this.communityHave) {\n if (!have.ids.size || now - have.at < GROUP_FILE_LIMITS.communityHaveEveryMs) continue;\n const ids = [...have.ids].slice(-GROUP_FILE_LIMITS.haveIds);\n have.ids.clear();\n have.at = now;\n void this.deps.sendApp(groupId, { t: GROUP_HAVE_FRAME, ids }).catch(() => {});\n }\n }\n\n // -- asking --------------------------------------------------------------------------------------------------\n\n private newWant(): Want { return { at: this.deps.now(), round: this.deps.now(), tried: new Set(), moved: 0, movedAt: 0 }; }\n\n /**\n * Wants of this group that wait for a holder: asked now (an edge came up or freed, or a member said it holds\n * something). One queued behind an edge's file is asked only while an edge of the group is free to take it, and free\n * for it (`freeFor`): once every edge has a file asked of it, or the free ones are of members it already asked, it would\n * only queue again. So a file that ends asks the few wants it frees an edge for, not every want waiting (a member back\n * from away with hundreds of files to fetch asked each of them once per file, more so with a member in the group that\n * holds none of them, or serves none).\n * `freed`, the edge a file ended or was refused on: a want waiting with nobody to ask is asked again only when that is\n * its author's edge, whose turn it may wait for (`waitForKnown`). A free edge does nothing else for it: one up and\n * live to a member it could ask would have queued it, not left it waiting. What may (an edge up, a session open, a\n * member saying it holds the file, a new round) asks it then.\n */\n private retry(groupId: string, freed?: string): void {\n let free: [string, string][] | undefined;\n const peer = freed === undefined ? undefined : this.edgesById.get(freed)?.peer;\n for (const [id, want] of this.wants) {\n const kept = this.kept.get(id);\n if (kept?.groupId !== groupId || want.holder) continue;\n const stage = this.deps.transfers.get(id)?.stage;\n if (freed !== undefined && stage === \"waiting\" && kept.author !== peer) continue;\n if (stage === \"queued\" && !this.freeFor(kept, want, free ??= this.freeEdges(groupId))) continue;\n this.ask(kept);\n // That ask may have taken a free edge.\n free = undefined;\n }\n }\n\n /** The group's edges that are up, with files/3 live and no file asked of their member: a want could be asked on them. */\n private freeEdges(groupId: string): [string, string][] {\n return [...this.deps.edges(groupId)].filter(([, linkId]) => this.deps.ready(linkId) && this.edgesById.get(linkId)?.files.live && !this.askedOf(linkId) && !this.paced(linkId));\n }\n\n /** This device sent as many wants on the edge as its window takes (`wantFrames`). */\n private paced(linkId: string): boolean {\n return !!this.edgesById.get(linkId)?.wantSent.wait();\n }\n\n /** One of these free edges (member key, link id) is one `ask` would ask this want on: asked now, it would not only queue again. */\n private freeFor(kept: Kept, want: Want, free: [string, string][]): boolean {\n if (!free.length) return false;\n const membership = this.deps.membership(kept.groupId);\n if (!membership) return false;\n const known = this.knownHolders(kept, membership);\n // As in `ask`: the others only while no known holder is worth waiting for.\n const others = !this.waitForKnown(kept, want, known, this.deps.edges(kept.groupId));\n return free.some(([key, linkId]) => this.mayAsk(kept, want, key, linkId)\n && (known.includes(key) || (others && key !== membership.me && membership.couldRead(key, kept.message, kept.arrived))));\n }\n\n /** The members known to hold the file (its author first), in the group's roster, but this device. */\n private knownHolders(kept: Kept, membership: GroupFileMembership | undefined): string[] {\n return [kept.author, ...kept.holders.filter(key => key !== kept.author)]\n .filter(key => membership && key !== membership.me && membership.inRoster(key));\n }\n\n /**\n * The author, its edge up, that answered busy or whose edge another file of this device's is asked of, serves when its\n * place frees: the others are asked only when it is not worth waiting for (out of reach), as after a restart here.\n * Only the author holds them back: any member can say it holds files, and one that answers busy, or serves the file\n * asked of it slowly, would keep every file it named here from coming while the author is away. Its busy only skips\n * it for the round.\n */\n private waitForKnown(kept: Kept, want: Want, known: string[], edges: Map<string, string>): boolean {\n if (!known.includes(kept.author)) return false;\n const linkId = edges.get(kept.author) ?? \"\";\n return this.deps.ready(linkId) && (!!want.busy?.has(kept.author) || this.askedOf(linkId, want) || this.paced(linkId));\n }\n\n /** The want may ask this member in this round: not asked yet, it did not serve it damaged, and did not say it is gone. */\n private mayAsk(kept: Kept, want: Want, key: string, linkId: string | undefined): boolean {\n return !want.tried.has(key) && !kept.damaged.has(key) && !this.edgesById.get(linkId ?? \"\")?.gone.has(kept.message);\n }\n\n /**\n * Asks the next holder for a file: the author first while its edge is up, then the holders whose edge is up, then every\n * other member whose edge is up and that could read its message. Who holds what is heard, not kept: a holder names few\n * of its files to an edge that opens, and none it was told of is known after a restart here, so a member in reach is\n * asked whether or not it said so (one that does not hold it answers `gone`, and is not asked again). Only over an\n * edge this device has. (A private group past 16 members, or a community, reaches a holder it has no edge with\n * over a file session of the two members, WISP 503 § The file session; that session is not built yet, so such a\n * holder is not asked, and the file waits for one that is reachable: `author` when that is its author alone.)\n */\n private ask(kept: Kept): void {\n const want = this.wants.get(kept.id);\n if (!want || kept.held || want.wire) return;\n // Out of the group: it would wait for good on holders that serve this device no more. What came of it goes.\n const out = this.deps.out?.(kept.groupId);\n if (out) { void this.stop(kept, false).then(() => this.stopFailed(kept, out, false)); return; }\n const membership = this.deps.membership(kept.groupId);\n const edges = this.deps.edges(kept.groupId);\n const known = this.knownHolders(kept, membership);\n // Every holder known served it damaged: asking again would fetch the same bytes, all of them, round after round.\n if (known.length && known.every(key => kept.damaged.has(key))) { this.stopFailed(kept); return; }\n const others = this.waitForKnown(kept, want, known, edges) ? [] : [...edges.keys()].filter(key => !known.includes(key) && membership && key !== membership.me && membership.couldRead(key, kept.message, kept.arrived));\n const order = [...known, ...others].filter(key => this.mayAsk(kept, want, key, edges.get(key)));\n // The holder last left for this file is asked once the others were.\n if (kept.left && order.includes(kept.left)) order.push(...order.splice(order.indexOf(kept.left), 1));\n // Then those whose tail failed on another's bytes: asked, they serve from 0, and what came here before goes.\n for (const key of order.filter(key => kept.suspect?.has(key))) order.push(...order.splice(order.indexOf(key), 1));\n let behind = false;\n for (const key of order) {\n const linkId = edges.get(key);\n if (!linkId || !this.deps.ready(linkId) || !this.edgesById.get(linkId)?.files.live) continue;\n // A holder serves this device one file at a time (WISP 503 § Serving limits): asked now, it would answer `busy`.\n // This one waits its turn, and is asked when the file before it ends (`transferChanged`).\n if (this.askedOf(linkId, want)) { behind = true; continue; }\n // Its wants go at their pace (§ Bounds): past it, this one waits its turn too, asked once the window frees (`tick`).\n if (this.paced(linkId)) { this.edgesById.get(linkId)!.wantPaced = true; behind = true; continue; }\n // Asked of it before the frame goes: its answer is this want's, however soon it comes.\n Object.assign(want, { holder: key, linkId, at: this.deps.now() });\n this.askedOn.set(linkId, { id: kept.id, want });\n this.edgesById.get(linkId)!.wantSent.take();\n if (!this.deps.send(linkId, { t: GROUP_WANT_FRAME, g: kept.groupId, id: kept.message })) { want.tried.add(key); continue; }\n if (want.holder === key) this.show(kept, { state: \"transferring\", stage: \"queued\", transferred: kept.stored ?? 0, size: kept.meta.size, direction: \"in\" });\n return;\n }\n Object.assign(want, { holder: undefined, linkId: undefined, at: this.deps.now() });\n if (behind) { this.show(kept, { state: \"transferring\", stage: \"queued\", transferred: kept.stored ?? 0, size: kept.meta.size, direction: \"in\" }); return; }\n // Why it waits: a holder busy, bytes that came damaged (its person can ask again), or nobody in reach has it. On\n // hubs, a file only its author is known to hold, the author with no edge here, comes only once a hub holds it: said\n // so, rather than blamed on who is online.\n const outOfReach = !!membership?.onHubs && known.includes(kept.author) && known.every(key => !edges.has(key));\n const wait = want.why ?? (outOfReach ? \"author\" : \"nobody\");\n this.show(kept, { state: \"transferring\", stage: \"waiting\", transferred: kept.stored ?? 0, size: kept.meta.size, direction: \"in\",\n wait, note: WAITING_NOTES[wait], ...(wait === \"damaged\" && { stalled: true }) });\n }\n\n /**\n * Another file is asked of, or coming from, the member at the other end of this edge. A want gets its edge only in\n * `ask`, which notes it in `askedOn`, and one edge has one want at a time: the want noted there is it, while it still\n * waits and is still on that edge.\n */\n private askedOf(linkId: string, except?: Want): boolean {\n const on = this.askedOn.get(linkId);\n if (!on || on.want === except) return false;\n if (on.want.linkId === linkId && this.wants.get(on.id) === on.want) return true;\n this.askedOn.delete(linkId);\n return false;\n }\n\n /**\n * The holder serving this want is slow (served `slowAfterMs`, and at its pace more than `wantWaitMs` to go) and another\n * holder is free to ask, one known when it offered (`want.knownAtOffer`) or one that answered it busy and said since that\n * a place freed (`want.free`): the transfer ends here, what came stays, and the next holder is asked\n * (`transferChanged`), so a phone's slow upload does not keep a member the author or a fast holder could serve. (The\n * newest holder heard is asked first, whatever its pace: a phone that finished after a fast member is the one taken.)\n */\n private leaveSlow(kept: Kept, want: Want): boolean {\n if (!want.wire || want.offeredAt === undefined) return false;\n const edge = want.linkId ? this.edgesById.get(want.linkId) : undefined;\n const record = edge?.files.get(\"in\", want.wire);\n if (!edge || !record || transferEnded(record) || record.state === \"verifying\") return false;\n const served = elapsed() - want.offeredAt;\n if (served < GROUP_FILE_LIMITS.slowAfterMs) return false;\n const stored = Math.max(want.moved, kept.stored ?? 0, want.offeredBytes ?? 0), pace = (stored - (want.offeredBytes ?? 0)) / served;\n if (pace > 0 && (kept.meta.size - stored) / pace <= GROUP_FILE_LIMITS.wantWaitMs) return false;\n const edges = this.deps.edges(kept.groupId);\n const known = this.knownHolders(kept, this.deps.membership(kept.groupId)).filter(key => want.knownAtOffer?.has(key));\n const candidates = new Set([...known, ...want.free ?? []]);\n const other = [...candidates].some(key => {\n const linkId = edges.get(key);\n return !!linkId && key !== want.holder && !kept.suspect?.has(key) && this.mayAsk(kept, want, key, linkId) && this.deps.ready(linkId)\n && !!this.edgesById.get(linkId)?.files.live && !this.askedOf(linkId, want);\n });\n if (!other) return false;\n want.free = undefined;\n edge.files.cancel(\"in\", want.wire);\n return true;\n }\n\n /**\n * The holder serving this want is gone (its edge's file session closed: its app went away mid-way) and another holder\n * may be asked now: the transfer ends here, what came stays, and that one is asked (`transferChanged`), not once\n * `wantWaitMs` went by with nothing moving. With nobody else in reach it waits, and goes on if the holder comes back.\n */\n private leaveGone(kept: Kept, want: Want): boolean {\n const edge = want.wire && want.linkId ? this.edgesById.get(want.linkId) : undefined;\n const record = edge?.files.get(\"in\", want.wire!);\n if (!edge || edge.files.live || !record || transferEnded(record) || record.state === \"verifying\") return false;\n if (!this.freeFor(kept, want, this.freeEdges(kept.groupId))) return false;\n kept.left = want.holder;\n edge.files.cancel(\"in\", want.wire!);\n return true;\n }\n\n /**\n * No holder serves the author's bytes (`DAMAGED`), or this device has no room for them (`NO_ROOM`): the want stops,\n * and stays stopped after a restart, until Download. Out of the group (`retry` false), Download says why instead.\n */\n private stopFailed(kept: Kept, error = DAMAGED, retry = true): void {\n this.wants.delete(kept.id);\n const { size } = kept.meta;\n void this.deps.store.patch(kept.id, { transfer: { state: \"failed\", transferred: 0, size, error } }).catch(() => {});\n this.show(kept, { state: \"failed\", transferred: 0, size, direction: \"in\", retry, error });\n }\n\n /** A holder's no: the next one is asked. One that deleted the file is no holder any more. */\n private refused(groupId: string, peer: string, linkId: string, messageId: string, why: GroupWantRefusal): void {\n const kept = this.kept.get(this.byMessage.get(`${groupId}\\n${messageId}`) ?? \"\");\n const want = kept && this.wants.get(kept.id);\n if (!kept || !want || want.linkId !== linkId || want.wire) return;\n if (why === \"gone\") {\n kept.holders = kept.holders.filter(key => key !== peer);\n this.edgesById.get(linkId)?.gone.add(messageId);\n }\n // Its day spent (agents#1672): said as such, not as \"asking again soon\", which held for up to a day.\n if (why === \"busy\" || why === \"day\") { want.why = why; (want.busy ??= new Set()).add(peer); }\n want.tried.add(peer);\n want.holder = want.linkId = undefined;\n this.ask(kept);\n // The edge is free for a file waiting its turn there.\n this.retry(groupId, linkId);\n }\n\n /** A member says it holds these files: remembered as a holder of each (newest first), and asked when a want waits. */\n private heard(groupId: string, from: string, ids: string[]): void {\n const membership = this.deps.membership(groupId);\n if (!membership || from === membership.me || !membership.inRoster(from)) return;\n const newest = (holders: string[]) => newestHolder(from, holders);\n const edge = this.edgesById.get(this.deps.edges(groupId).get(from) ?? \"\");\n // Its edge, while free: a want queued behind other edges' files is asked again only if it can be asked there.\n let free: [string, string][] | undefined;\n for (const message of ids) {\n const key = `${groupId}\\n${message}`, kept = this.kept.get(this.byMessage.get(key) ?? \"\");\n if (!kept) {\n // Its message has not come yet (it is on its way in a catch-up): who holds it is kept for when it does.\n this.ahead.set(key, newest(this.ahead.get(key) ?? []));\n if (this.ahead.size > GROUP_FILE_LIMITS.heardAhead) this.ahead.delete(this.ahead.keys().next().value!);\n continue;\n }\n if (kept.mine) continue;\n kept.holders = newest(kept.holders);\n edge?.gone.delete(message);\n const want = this.wants.get(kept.id);\n if (!want) continue;\n want.tried.delete(from);\n // Free for it only when it says so after answering it busy: its places freed. Any other `group-have` says it holds\n // the file, not that a place is free (one that just fetched it says so to every edge, whose waiting members take\n // its places at once): left for, it would answer busy, and the transfer left would be lost for nothing.\n if (want.wire && from !== want.holder && want.busy?.has(from)) (want.free ??= new Set()).add(from);\n want.busy?.delete(from);\n if (want.holder) continue;\n if (this.deps.transfers.get(kept.id)?.stage === \"queued\" && !this.freeFor(kept, want, free ??= this.freeEdges(groupId).filter(([key]) => key === from))) continue;\n this.ask(kept);\n free = undefined;\n }\n }\n\n // -- serving -------------------------------------------------------------------------------------------------\n\n /** A member asks for a file: offered over files/3 on its edge, or a `group-want-no` saying why not. */\n private async serve(edge: Edge, messageId: string): Promise<void> {\n const kept = this.kept.get(this.byMessage.get(`${edge.groupId}\\n${messageId}`) ?? \"\");\n const here = !!kept?.held && !!(await this.deps.store.get(kept.id).catch(() => undefined));\n // Decided and offered in one step: two wants at once never both find the last free place.\n const why = this.mayServe(edge, messageId, here ? kept : undefined, kept?.arrived);\n if (why || !kept) { this.deps.send(edge.linkId, { t: GROUP_WANT_NO_FRAME, g: edge.groupId, id: messageId, why: why ?? \"gone\" }); return; }\n const wire = toBase64Url(randomBytes(12));\n edge.serving.set(wire, kept.id);\n const at = elapsed();\n edge.servedMoved.set(wire, { confirmed: 0, at, from: at });\n const { name, mime, size, voice, video, image } = kept.meta;\n const file: FileInfo = { id: wire, name, mime, size, timestamp: this.deps.now(), ...(voice && { voice }), ...(video && { video }), ...(image && { image }) };\n edge.files.offer(file, kept.meta.d);\n }\n\n /**\n * Why this device does not serve a file now, or null when it does (WISP 503 § Asking, Serving limits): `refused` to\n * someone who could not read the announcement, `gone` when it is not here (`kept` undefined), `busy` when serving is\n * off or full, `day` when this device served its bytes for the day (`serveBytesPerDay`).\n */\n private mayServe(edge: Edge, messageId: string, kept: Kept | undefined, arrived: number | undefined): GroupWantRefusal | null {\n const membership = this.deps.membership(edge.groupId);\n if (!membership || !membership.couldRead(edge.peer, messageId, arrived)) return \"refused\";\n if (!kept) return \"gone\";\n if (!this.deps.settings().serveFiles || !edge.files.live) return \"busy\";\n this.letGo();\n const active = this.servingNow();\n // One place per member, whatever it confirms. One that has all its bytes, lately, waits only for the member's word\n // that its check passed, which may come after this want: that one alone is not its place.\n const theirs = active.filter(a => a.peer === edge.peer);\n const placed = theirs.length > 1 || theirs.some(a => a.sending || elapsed() - a.since >= GROUP_FILE_LIMITS.doneWaitMs);\n // All places taken: a member holding none gets the one held longest past `servePlaceMs`, or the slowest, if there is one.\n const full = active.length >= GROUP_FILE_LIMITS.serveAtOnce;\n const room = full && !placed ? this.roomFor() : undefined;\n if (full && !room) { edge.busy.set(messageId, this.deps.now()); return \"busy\"; }\n if (placed) return \"busy\";\n const today = Math.floor(this.deps.now() / 86_400_000);\n if (this.served.day !== today) this.served = { day: today, bytes: 0 };\n // The transfer ended for this member counts what it sent instead of its share: ended only when the day has room.\n const reserved = active.reduce((sum, a) => sum + a.size, 0) - (room ? room.size - room.sent : 0);\n if (this.served.bytes + reserved + kept.meta.size > GROUP_FILE_LIMITS.serveBytesPerDay) return \"day\";\n if (room) this.cut(room);\n return null;\n }\n\n /**\n * The served transfer to end for a member that holds no place (undefined when none is): the one that has held its place\n * longest, once past `servePaceMs`; else the slowest of those under way for `servePaceMs` with more left to go at their\n * pace than they have been served (and than `servePaceMs`), each member's file once (its asker goes on from what it\n * stored, from the next holder or this one, and the members on fast links do not wait for the slow ones that asked\n * first). With its share of the day (as in `servingNow`) and what it sent.\n */\n private roomFor(): { edge: Edge; wire: string; size: number; sent: number; paced: boolean } | undefined {\n const now = elapsed();\n let oldest: { edge: Edge; wire: string; from: number } | undefined;\n let slowest: { edge: Edge; wire: string; pace: number } | undefined;\n for (const edge of this.edgesById.values()) for (const [wire, id] of edge.serving) {\n const record = edge.files.get(\"out\", wire), moved = edge.servedMoved.get(wire), from = moved?.from ?? now;\n if (!record || transferEnded(record)) continue;\n if (now - from >= GROUP_FILE_LIMITS.servePlaceMs && (!oldest || from < oldest.from)) oldest = { edge, wire, from };\n if (!moved?.mark || now - moved.mark[1] < GROUP_FILE_LIMITS.servePaceMs || edge.paced.has(id) || record.confirmed >= record.file.size) continue;\n const pace = (record.confirmed - moved.mark[0]) / (now - moved.mark[1]);\n if (pace > 0 && (record.file.size - record.confirmed) / pace <= Math.max(GROUP_FILE_LIMITS.servePaceMs, now - from)) continue;\n if (!slowest || pace < slowest.pace) slowest = { edge, wire, pace };\n }\n const cut = oldest ?? slowest;\n if (!cut) return undefined;\n const sent = cut.edge.files.sent(cut.wire);\n return { edge: cut.edge, wire: cut.wire, size: Math.max(cut.edge.files.get(\"out\", cut.wire)!.file.size, sent), sent, paced: !oldest };\n }\n\n /** Ends the served transfer `roomFor` chose; one ended for its pace is not served its member again. */\n private cut(room: { edge: Edge; wire: string; paced: boolean }): void {\n if (room.paced) room.edge.paced.add(room.edge.serving.get(room.wire)!);\n room.edge.files.cancel(\"out\", room.wire);\n }\n\n /** Ends a served transfer for a member that holds no place (`roomFor`): false when none is. */\n private makeRoom(): boolean {\n const room = this.roomFor();\n if (room) this.cut(room);\n return !!room;\n }\n\n /**\n * A member turned away as busy within `wantWaitMs`, holding no place, waits for the holder's word that a place freed:\n * it is made one as when it asks (`makeRoom`), and hears so.\n */\n private makeRoomForWaiting(): void {\n if (!this.deps.settings().serveFiles) return;\n const active = this.servingNow(), now = this.deps.now();\n if (active.length < GROUP_FILE_LIMITS.serveAtOnce) return;\n const waits = [...this.edgesById.values()].some(edge => edge.files.live && !active.some(a => a.peer === edge.peer)\n && [...edge.busy.values()].some(at => now - at < GROUP_FILE_LIMITS.wantWaitMs));\n if (waits) this.makeRoom();\n }\n\n /**\n * Transfers served now, all groups together: to whom, what each takes of the day (its size, or what it sent when that\n * is more), whether bytes are still to go, and since when it has not gone further.\n */\n private servingNow(): { peer: string; size: number; sending: boolean; since: number }[] {\n const active: { peer: string; size: number; sending: boolean; since: number }[] = [];\n for (const edge of this.edgesById.values()) for (const wire of edge.serving.keys()) {\n const record = edge.files.get(\"out\", wire);\n if (record && !transferEnded(record)) {\n active.push({ peer: edge.peer, size: Math.max(record.file.size, edge.files.sent(wire)), sending: record.confirmed < record.file.size,\n since: edge.servedMoved.get(wire)?.at ?? elapsed() });\n }\n }\n return active;\n }\n\n /**\n * An asker has a served transfer send parts again (WISP 503 § Serving limits): every byte sent counts toward the day,\n * so it goes on only while the day has room for it.\n */\n private mayResend(): boolean {\n const today = Math.floor(this.deps.now() / 86_400_000);\n if (this.served.day !== today) this.served = { day: today, bytes: 0 };\n return this.served.bytes + this.servingNow().reduce((sum, a) => sum + a.size, 0) < GROUP_FILE_LIMITS.serveBytesPerDay;\n }\n\n /**\n * Served transfers that no longer count end, their places free for others (WISP 503 § Serving limits): the asker's\n * session closed, it is not in the roster any more, it has not had `serveMoveBytes` more confirmed (or the rest of\n * its file) for `wantWaitMs` (the asker has moved on by then), or it has all its bytes and the member's next want has\n * overtaken its word for `doneWaitMs`.\n */\n private letGo(): void {\n const now = elapsed();\n const theirs = new Map<string, number>();\n for (const a of this.servingNow()) theirs.set(a.peer, (theirs.get(a.peer) ?? 0) + 1);\n for (const edge of this.edgesById.values()) for (const wire of [...edge.serving.keys()]) {\n const record = edge.files.get(\"out\", wire);\n if (!record || transferEnded(record)) continue;\n let moved = edge.servedMoved.get(wire);\n if (!moved) edge.servedMoved.set(wire, (moved = { confirmed: record.confirmed, at: now, from: now }));\n const gone = !edge.files.live || !this.deps.membership(edge.groupId)?.inRoster(edge.peer);\n const overtaken = record.confirmed === record.file.size && theirs.get(edge.peer)! > 1 && now - moved.at >= GROUP_FILE_LIMITS.doneWaitMs;\n if (gone || overtaken || now - moved.at >= GROUP_FILE_LIMITS.wantWaitMs) {\n edge.files.cancel(\"out\", wire);\n theirs.set(edge.peer, theirs.get(edge.peer)! - 1);\n continue;\n }\n // Its pace (`makeRoom`): a new mark each `servePaceMs`.\n if (moved.next && now - moved.next[1] >= GROUP_FILE_LIMITS.servePaceMs) { moved.mark = moved.next; moved.next = [record.confirmed, now]; }\n }\n }\n\n /**\n * Says on an edge which files this device holds, as many frames as the edge takes now (`haveFrames` in\n * `haveWindowMs`); the ids past that, and those of a frame that could not go, wait for the next tick with room.\n */\n private sendHave(edge: Edge, ids: string[]): void {\n for (const id of ids) edge.have.add(id);\n for (let i = 0; i < ids.length; i += GROUP_FILE_LIMITS.haveIds) {\n const frame = ids.slice(i, i + GROUP_FILE_LIMITS.haveIds);\n if (edge.haveSent.wait() || !this.deps.send(edge.linkId, { t: GROUP_HAVE_FRAME, g: edge.groupId, ids: frame })) return;\n edge.haveSent.take();\n for (const id of frame) edge.have.delete(id);\n }\n }\n\n /**\n * This device holds a new file: the group hears it with the next `group-have`, which gathers what there is to say\n * until the next tick.\n */\n private queueHave(kept: Kept): void {\n if (!this.deps.settings().serveFiles) return;\n if (this.deps.membership(kept.groupId)?.community) {\n let have = this.communityHave.get(kept.groupId);\n if (!have) this.communityHave.set(kept.groupId, (have = { ids: new Set(), at: 0 }));\n have.ids.add(kept.message);\n return;\n }\n for (const [key, linkId] of this.deps.edges(kept.groupId)) this.edge(kept.groupId, key, linkId).have.add(kept.message);\n }\n\n // -- files/3 on an edge --------------------------------------------------------------------------------------\n\n private edge(groupId: string, peer: string, linkId: string): Edge {\n const known = this.edgesById.get(linkId);\n if (known) return known;\n const edge: Edge = { linkId, groupId, peer, files: undefined as unknown as ChatFiles, serving: new Map(), servedMoved: new Map(), taking: new Map(), ended: [], have: new Set(),\n haveSent: new RateWindow(GROUP_FILE_LIMITS.haveFrames, GROUP_FILE_LIMITS.haveWindowMs, () => this.deps.now()),\n haveTaken: new RateWindow(GROUP_FILE_LIMITS.haveFramesTaken, GROUP_FILE_LIMITS.haveWindowMs, () => this.deps.now()),\n wantSent: new RateWindow(GROUP_FILE_LIMITS.wantFrames, GROUP_FILE_LIMITS.wantWindowMs, () => this.deps.now()),\n wantTaken: new RateWindow(GROUP_FILE_LIMITS.wantFramesTaken, GROUP_FILE_LIMITS.wantWindowMs, () => this.deps.now()), busy: new Map(), gone: new Set(), paced: new Set() };\n edge.files = new ChatFiles({\n uplink: this.uplink,\n // An offer names the group message it serves (`gm`), which a 1:1 chat never carries.\n send: frame => {\n const kept = frame.t === \"pf-offer\" ? this.kept.get(edge.serving.get(frame.id as string) ?? \"\") : undefined;\n return this.deps.sendFiles(linkId, kept ? { ...frame, gm: kept.message } : frame);\n },\n decide: file => this.decide(edge, file),\n openTarget: record => this.openTarget(edge, record),\n openSource: record => this.openSource(edge, record),\n changed: (record, transferred) => this.transferChanged(edge, record, transferred),\n room: () => this.deps.store.room(),\n ...(this.deps.sendData && { sendData: (id: string, offset: number, data: Uint8Array) => this.deps.sendData!(linkId, id, offset, data) }),\n writable: () => this.deps.writable?.(linkId),\n resend: record => !edge.serving.has(record.id) || this.mayResend(),\n });\n this.edgesById.set(linkId, edge);\n return edge;\n }\n\n /**\n * An offer that answers my want (`filesFrame` checked that): taken, unless it is not the file announced or there is no\n * room. With no room, every holder's offer would be refused the same: the want stops and says so, until Download.\n */\n private async decide(edge: Edge, file: FileInfo): Promise<OfferDecision> {\n const kept = this.kept.get(edge.taking.get(file.id) ?? \"\"), want = kept && this.wants.get(kept.id);\n if (!kept || kept.held || want?.linkId !== edge.linkId || want.wire !== file.id || file.size !== kept.meta.size) return { refuse: \"invalid\" };\n const room = await this.deps.store.room().catch(() => null);\n if (room === null || file.size <= room) return \"accept\"; // A refused offer makes no transfer here, so nothing else ends the want.\n edge.taking.delete(file.id);\n if (this.wants.get(kept.id) === want && want.wire === file.id) {\n this.stopFailed(kept, NO_ROOM);\n this.retry(kept.groupId, edge.linkId);\n }\n return { refuse: \"no-room\", room };\n }\n\n /** This device has room for a file of this size, or does not say. */\n private async hasRoom(size: number): Promise<boolean> {\n const room = await this.deps.store.room().catch(() => null);\n return room === null || size <= room;\n }\n\n private async openTarget(edge: Edge, record: FileTransferRecord): Promise<IncomingTarget> {\n const kept = this.kept.get(edge.taking.get(record.id) ?? \"\");\n if (!kept) throw new Error(\"No such file\");\n // What an earlier holder's transfer stored stays, and this one goes on from there (WISP 503: the asker accepts from\n // the offset it stored): every holder serves the author's bytes, and the whole file is checked at the end.\n await kept.idle;\n const writer = await this.deps.store.write(kept.id, !kept.fresh && !kept.suspect?.has(edge.peer));\n kept.fresh = false;\n const resumed = writer.offset > 0;\n if (!resumed) kept.storedBy = edge.peer;\n else if (kept.storedBy !== edge.peer) kept.storedBy = undefined;\n let damaged = false;\n // Its group was left (`drop`): what the transfer still has to write (its checkpoint as the edge closes) is deleted,\n // not stored as a file nothing knows of.\n const gone = () => this.kept.get(kept.id) !== kept;\n const write = async <T>(op: () => Promise<T>): Promise<T> => {\n if (gone()) { await writer.discard(); throw new Error(\"No such file\"); }\n return await (kept.writing = op());\n };\n return {\n offset: writer.offset,\n append: bytes => write(() => writer.append(bytes)),\n flush: () => write(() => writer.flush()),\n // Against the author's digest, read back from storage, not the holder's word: a holder can withhold a file, never\n // serve another one.\n verify: async () => {\n damaged = (await write(() => writer.digest())) !== kept.meta.d;\n const want = this.wants.get(kept.id);\n if (damaged && want) want.why = \"damaged\";\n return !damaged;\n },\n // Only damaged bytes go, and those of a file its person cancelled. Left with a holder that stalled or stopped, what\n // came is kept for the next holder.\n discard: () => {\n // Whole from this holder and damaged: its bytes are not the author's, and it is not asked for them again.\n if (damaged) {\n kept.stored = 0;\n if (resumed && kept.storedBy !== edge.peer) {\n kept.fresh = kept.unclear = true;\n (kept.suspect ??= new Set()).add(edge.peer);\n } else kept.damaged.add(edge.peer);\n kept.storedBy = undefined;\n }\n return (kept.idle = (damaged || kept.dropped === record.id || gone() ? writer.discard() : writer.close()).catch(() => {}));\n },\n };\n }\n\n private async openSource(edge: Edge, record: FileTransferRecord): Promise<OutgoingSource> {\n const kept = this.kept.get(edge.serving.get(record.id) ?? \"\");\n const stored = kept && await this.deps.store.get(kept.id);\n if (!kept || !stored) throw new Error(\"The file is gone\");\n return { read: (offset, length) => this.deps.store.read(stored, offset, length), digest: async () => kept.meta.d };\n }\n\n /** A transfer on the edge ended: its record stays among the last `ENDED_KEPT`, and the oldest past that is forgotten. */\n private transferOver(edge: Edge, record: FileTransferRecord): void {\n if (edge.ended.some(([direction, id]) => direction === record.direction && id === record.id)) return;\n edge.ended.push([record.direction, record.id]);\n while (edge.ended.length > ENDED_KEPT) edge.files.forget(...edge.ended.shift()!);\n }\n\n private transferChanged(edge: Edge, record: FileTransferRecord, transferred: number): void {\n if (transferEnded(record)) this.transferOver(edge, record);\n if (record.direction === \"out\") {\n // Only bytes confirmed for the first time are progress, and only `serveMoveBytes` of them (or the rest of the\n // file): one accepted back and forth stays where it was, and a byte now and then does not keep a place.\n const moved = edge.servedMoved.get(record.id);\n // Its pace is measured from the offer, from the bytes the asker had (where it accepted from).\n if (moved && !moved.mark && record.state === \"active\") moved.mark = moved.next = [record.confirmed, moved.from];\n if (moved && record.confirmed > moved.confirmed && (record.confirmed - moved.confirmed >= GROUP_FILE_LIMITS.serveMoveBytes || record.confirmed === record.file.size)) {\n edge.servedMoved.set(record.id, { ...moved, confirmed: record.confirmed, at: elapsed() });\n }\n if (transferEnded(record) && edge.serving.has(record.id)) {\n // What was sent to a member counts toward the day's serving, done or not, and whatever it confirmed.\n const today = Math.floor(this.deps.now() / 86_400_000);\n if (this.served.day !== today) this.served = { day: today, bytes: 0 };\n this.served.bytes += edge.files.sent(record.id);\n edge.serving.delete(record.id);\n edge.servedMoved.delete(record.id);\n // A slot is free: those turned away as busy hear this device holds their file (with the next `group-have`), and\n // ask it again rather than wait out their round.\n const serving = this.deps.settings().serveFiles;\n for (const other of this.edgesById.values()) {\n if (serving) for (const id of other.busy.keys()) other.have.add(id);\n other.busy.clear();\n }\n }\n return;\n }\n const kept = this.kept.get(edge.taking.get(record.id) ?? \"\"), want = kept && this.wants.get(kept.id);\n // A transfer this device moved on from (the holder stalled, then went on) changes nothing.\n if (!kept || !want || want.wire !== record.id || want.linkId !== edge.linkId) return;\n // Moving: `wantMoveBytes` more since it last moved (or the rest of the file), not any byte.\n if (want.moved < 0) want.moved = transferred;\n else if (transferred - want.moved >= Math.min(GROUP_FILE_LIMITS.wantMoveBytes, kept.meta.size - want.moved)) { want.moved = transferred; want.movedAt = elapsed(); }\n if (record.state !== \"failed\" && record.state !== \"declined\" && record.state !== \"cancelled\") kept.stored = transferred;\n const { size } = kept.meta;\n switch (record.state) {\n case \"done\": {\n kept.held = true;\n this.wants.delete(kept.id);\n edge.taking.delete(record.id);\n void this.deps.store.patch(kept.id, { transfer: { state: \"done\", transferred: size, size } }).catch(() => {});\n this.finished(kept, \"in\");\n this.queueHave(kept);\n // The holder is free for the next file this device waits for.\n this.retry(kept.groupId, edge.linkId);\n return;\n }\n case \"failed\": case \"declined\": case \"cancelled\":\n // Damaged (refused, its bytes deleted), stopped by the holder or left here: the next holder is asked.\n edge.taking.delete(record.id);\n // A resumed file that failed its check may owe its bad bytes to the earlier holder: this one is asked again, from 0.\n if (want.holder && !kept.unclear) want.tried.add(want.holder);\n kept.unclear = false;\n Object.assign(want, { wire: undefined, holder: undefined, linkId: undefined, moved: 0 });\n this.ask(kept);\n this.retry(kept.groupId, edge.linkId);\n return;\n case \"verifying\":\n this.show(kept, { state: \"transferring\", stage: \"verifying\", transferred, size, direction: \"in\" });\n return;\n default:\n // Progress waits 250 ms for its state, as a 1:1 file's does (`FileDesk`): within 50 ms of each part, a 64 MiB\n // file sent the pages 77 states, where the same file in a 1:1 chat sent 18.\n this.show(kept, { state: \"transferring\", transferred, size, direction: \"in\" }, 250);\n }\n }\n\n // -- bookkeeping ---------------------------------------------------------------------------------------------\n\n private add(kept: Kept): void {\n this.kept.set(kept.id, kept);\n this.byMessage.set(`${kept.groupId}\\n${kept.message}`, kept.id);\n }\n\n /** Bytes this device fetched by itself from the group and keeps (or is fetching): what `autoBytesPerGroup` bounds. */\n private keptAutomatically(groupId: string): number {\n let sum = 0;\n for (const kept of this.kept.values()) if (kept.groupId === groupId && kept.auto && !kept.mine) sum += kept.meta.size;\n return sum;\n }\n\n private groupField(kept: Kept): NonNullable<StoredFile[\"group\"]> {\n return { message: kept.message, author: kept.author, ...(kept.arrived !== undefined && { arrived: kept.arrived }), ...(kept.auto && { auto: true }), ...(kept.asked && { asked: true }), ...(kept.paused && { paused: true }) };\n }\n\n /** The bytes of a file kept here from transfers that did not finish. */\n private async keptBytes(id: string): Promise<number> {\n const writer = await this.deps.store.write(id, true).catch(() => undefined);\n if (!writer) return 0;\n await writer.close().catch(() => {});\n return writer.offset;\n }\n\n private pace(windows: Map<string, RateWindow>, key: string, limit: number, ms: number): RateWindow {\n let window = windows.get(key);\n if (!window) windows.set(key, (window = new RateWindow(limit, ms, () => this.deps.now())));\n return window;\n }\n\n /** My announcements in a group, in a minute and in the window the members count them over. */\n private sentPaces(groupId: string): RateWindow[] {\n return [this.pace(this.sentPace, groupId, GROUP_FILE_LIMITS.announcePerMinute, 60_000),\n this.pace(this.sentTaken, groupId, GROUP_FILE_LIMITS.announceTaken, GROUP_FILE_LIMITS.announceWindowMs)];\n }\n\n /**\n * The file waits for its person's Download: said in one state (the CLI's `file.offered`), then left to its record,\n * which says it is not here (`waitingGroupFile`). A view kept for each such file would go into every state the engine\n * builds, so each would cost more with every file the groups ever had.\n */\n private waiting(kept: Kept): void {\n this.show(kept, { state: \"transferring\", stage: \"asking\", transferred: 0, size: kept.meta.size, direction: \"in\" });\n this.deps.brief(kept.id);\n }\n\n /**\n * All here: said in one state (the CLI's `file.done`), then left to its record, which says it is done. A view kept for\n * each file fetched or sent would go into every state the engine builds until the next start.\n */\n private finished(kept: Kept, direction: \"in\" | \"out\"): void {\n this.show(kept, { state: \"done\", transferred: kept.meta.size, size: kept.meta.size, direction });\n this.deps.brief(kept.id);\n }\n\n /** A file's row shows `view`; the engine hears of it only when that is not what the row shows already. */\n private show(kept: Kept, view: FileTransferView, delayMs?: number): void {\n if (sameView(this.deps.transfers.get(kept.id), view)) return;\n this.deps.transfers.set(kept.id, view);\n this.deps.changed(delayMs);\n }\n}\n\n/** Two views of a transfer that say the same: their fields are all plain values. */\nfunction sameView(a: FileTransferView | undefined, b: FileTransferView): boolean {\n if (!a) return false;\n const keys = new Set([...Object.keys(a), ...Object.keys(b)] as (keyof FileTransferView)[]);\n for (const key of keys) if (a[key] !== b[key]) return false;\n return true;\n}\n\n/** A file's holders with `key` the newest of them, the `holders` newest kept. */\nconst newestHolder = (key: string, holders: string[]): string[] => [key, ...holders.filter(other => other !== key)].slice(0, GROUP_FILE_LIMITS.holders);\n\n/** The epoch a private group's message reached this device under, when later than its own (said again); else none. */\nfunction laterEpoch(messageId: string, epoch: number | undefined): number | undefined {\n const ref = meshMessageRef(messageId);\n return ref && epoch !== undefined && epoch > ref.e ? epoch : undefined;\n}\n\nfunction messageFile(kept: Kept): MessageFile {\n const { name, size, mime, voice, video, image } = kept.meta;\n return { id: kept.id, name, size, mime, ...(voice && { voice }), ...(video && { video }), ...(image && { image }) };\n}\n","/**\n * The desk's links to members of a community group (WISP 903 · Group Community § Payments): payments with a member\n * go through the group, sealed to them, over `cpay:<group>:<member>`; a request to everyone over `cpay:<group>`.\n */\nexport const pairLinkId = (groupId: string, member: string) => `cpay:${groupId}:${member}`;\nexport const groupLinkId = (groupId: string) => `cpay:${groupId}`;\n/** The group and member of a community payment link, or undefined for any other link. */\nexport function parsePayLink(linkId: string): { groupId: string; member?: string } | undefined {\n const m = /^cpay:([A-Za-z0-9_-]{22})(?::([a-z0-9]{52}))?$/.exec(linkId);\n return m ? { groupId: m[1], ...(m[2] ? { member: m[2] } : {}) } : undefined;\n}\n","import { parsePayLink } from \"./payLinks\";\nimport { paymentWireId } from \"./paymentIds\";\nimport type { GroupPayNote, GroupView, PaymentView, StoredMessage } from \"./types\";\n\n/** The id of a group payment note's line in the group's history (WISP 902 § Payments). */\nexport const groupPayLineId = (noteId: string): string => `gpay:${noteId}`;\n\ntype PaymentOf = (Pick<PaymentView, \"kind\" | \"requestId\"> & Partial<Pick<PaymentView, \"linkId\">>) | undefined;\ntype PaymentRow = Pick<StoredMessage, \"paymentId\" | \"sender\" | \"member\">;\n\n/** The group note a payment of this device is part of: a request's own, or the request a payment answers (by its id on the wire). */\nexport function groupPayNoteId(paymentId: string, payment: PaymentOf): string {\n return paymentWireId(payment?.kind === \"payment\" && payment.requestId ? payment.requestId : paymentId);\n}\n\n/**\n * The note that captions a payment bubble: the one about that bubble's own payment, which the member who started it\n * says (the payee of a request, the payer of a payment), never a note of another member that reuses its id.\n */\nexport function groupPayCaption(message: PaymentRow, payment: PaymentOf, noteOf: (id: string) => GroupPayNote | undefined, myKey: string | undefined): GroupPayNote | undefined {\n if (!message.paymentId) return undefined;\n // Said once, under the request (or the payment) itself: not again under a payment that answers it.\n if (payment?.kind === \"payment\" && payment.requestId) return undefined;\n const note = noteOf(groupPayNoteId(message.paymentId, payment));\n const starter = message.sender === \"me\" ? myKey : message.member;\n return note && starter && (note.kind === \"request\" ? note.to : note.from) === starter ? note : undefined;\n}\n\n/** The member at the other end of a group's payment link: a mesh member's edge, or a community member's link. */\nexport function groupMemberOfLink(group: Pick<GroupView, \"members\"> | undefined, linkId: string): string | undefined {\n return group?.members.find(m => !m.me && m.edge?.linkId === linkId)?.key ?? parsePayLink(linkId)?.member;\n}\n\n/**\n * The note a payment bubble of this device says again (its own caption, or a payment answering it), by the note's id:\n * the group page draws the bubble and leaves that note's own line out, so the same payment shows once. Undefined for\n * a bubble no note of the group is about. A payment answers the note of the request it pays only when that note is a\n * request between the same two members (`memberOf`: the member at the other end of a link of mine): a request's id is\n * its sender's to choose, so it can be the id of another member's note.\n */\nexport function groupPayTwin(message: PaymentRow, payment: PaymentOf, noteOf: (id: string) => GroupPayNote | undefined, myKey: string | undefined,\n memberOf: (linkId: string) => string | undefined = () => undefined): string | undefined {\n if (!message.paymentId) return undefined;\n if (groupPayCaption(message, payment, noteOf, myKey)) return groupPayNoteId(message.paymentId, payment);\n if (payment?.kind !== \"payment\" || !payment.requestId) return undefined;\n const note = noteOf(groupPayNoteId(message.paymentId, payment));\n const member = message.sender === \"me\" ? payment.linkId && memberOf(payment.linkId) : message.member;\n const [payer, payee] = message.sender === \"me\" ? [myKey, member] : [member, myKey];\n if (note?.kind !== \"request\" || !payer || !payee || note.to !== payee || (note.from !== payer && note.from !== \"*\")) return undefined;\n return note.id;\n}\n","import type {\n GetInfoResponse,\n MeltPreview,\n MeltProofsResponse,\n MeltQuoteBolt11Response,\n NetworkError as CashuNetworkError,\n OutputData,\n Proof,\n ProofLike,\n RequestFn,\n RequestOptions,\n SerializedOutputData,\n SerializedSwapPreview,\n SwapPreview,\n Wallet,\n} from \"@cashu/cashu-ts\";\nimport { STORES, newestWalletTx, openDb, store, transact, wrap, committed } from \"../shared/idb\";\nimport { openRow, openRows, proofKey, RowSeals, sealRow, sealedStore } from \"./sealedRows\";\nimport { hasDataKey } from \"./dataKey\";\nimport { LIMITS, PaymentPreflightError, decodeBolt11, ecashUnitError, engineError, engineText, stripHidden, type PaymentReview, type WalletNetwork } from \"@ghostly/core\";\nimport { CASHU_REQUEST_TIMEOUT_MS, MELT_REQUEST_TIMEOUT_MS, SWAP_SETTLED_MS, keysetRefused, mintFailed, mintRefused } from \"./paymentAdapters/cashu\";\nimport { AskBackoff } from \"./askBackoff\";\nimport { INVOICE_PACE, nextInvoiceAsk } from \"./invoicePace\";\nimport { BITCOIN_INVOICE_ON_TESTNET, fakesLightning, isTestMint, mintNetwork, mintUrlSpelling, paysItsOwnInvoices } from \"../shared/mints\";\nimport type {\n CashuInspection,\n MintInfoView,\n MintView,\n PendingMelt,\n PendingSwap,\n StoredPayment,\n StoredProof,\n StoredQuote,\n WalletTx,\n WalletTxKind,\n WalletView,\n} from \"../shared/types\";\n\n/**\n * The peer's Cashu wallet. Ecash is custodial: the mint holds the sats and the\n * proofs in IndexedDB are the claim on them. The user picks the mints; ecash\n * from any other mint is refused, because accepting a token means trusting\n * whoever issued it.\n *\n * Secrets are random, so there is no seed to restore from yet. `exportTokens`\n * is the backup, and balances are meant to stay pocket-money sized.\n *\n * Every swap is written down before the mint is asked (`PendingSwap`, or the payment intent of a reviewed payment),\n * with its blinded outputs and their secrets: the mint signs those outputs and no others, and its signatures can be\n * asked for again (NUT-09) at any time.\n */\nconst UNIT = \"sat\";\n/**\n * cdk-mintd 0.17 writes NUT-05's `amountless` beside the method, not under its `options` as 0.18 does, and cashu-ts reads\n * `options` only: such a mint would be taken for one that refuses an invoice with no amount, and never sent the amount.\n */\nconst saysAmountlessBeside = (method: object): boolean => (method as { amountless?: unknown }).amountless === true;\nfunction amountlessUnderOptions(info: GetInfoResponse): GetInfoResponse {\n const moved = info.nuts[5].methods.map((method) => (saysAmountlessBeside(method) ? { ...method, options: { ...method.options, amountless: true } } : method));\n return { ...info, nuts: { ...info.nuts, 5: { ...info.nuts[5], methods: moved } } };\n}\n/**\n * An invoice from the mint, with `label` as its description when the mint says it takes one. NUT-04's `description` is\n * optional: cashu-ts refuses to ask a mint that leaves it out for an invoice with one, and the label is only a label.\n */\nconst mintInvoice = (wallet: Wallet, amount: number, label: string) =>\n wallet.createMintQuoteBolt11(amount, wallet.getMintInfo().supportsNut04Description?.(\"bolt11\", UNIT) === false ? undefined : label);\n/** A Lightning payment can stay in flight for minutes or hours; the mint is asked again this often. */\nconst MELT_POLL_MS = 30_000;\n/** Once its request can no longer land, a payment still pending is asked twice as late each time, up to this. */\nconst MELT_SLOW_POLL_MS = 1_800_000;\nconst MAX_AMOUNT = 1_000_000;\n/** How long \"Get test coins\" waits for the test mint to mark its invoice paid before saying the coins come later. */\nconst TEST_COINS_WAIT_MS = 30_000;\nconst HISTORY_SHOWN = 100;\n/** How long before a mint that could not say which restored ecash is spent is asked again. */\nconst RESTORED_POLL_MS = 60_000;\n/** Asked twice as late each time it still cannot say, up to this. */\nconst RESTORED_SLOW_POLL_MS = 1_800_000;\n/** How long before a mint that could not say where a swap stands is asked again. */\nconst SWAP_POLL_MS = 30_000;\n/** The same, for a swap that holds nothing any more or whose mint cannot give signatures back: asked now and then. */\nconst SWAP_SLOW_POLL_MS = 600_000;\n/** How long a swap whose inputs were given back is still asked about, in case the mint made it after all. */\nconst SWAP_WATCH_MS = 3_600_000;\n/** How many proofs of tokens refused as spent are remembered. */\nconst SPENT_KEPT = 1_000;\n/** The most coins `sendCoins` makes for one token. */\nconst MAX_SEND_COINS = 64;\n/** `abandoned`: the mint proved the swap never happened (`reviewedCashuNeverSwapped`); it is never sent again. */\n/**\n * `attemptEndedAt`: when the approval's swap failed with no answer. `abandoned`: the mint proved the swap never\n * happened (`reviewedCashuNeverSwapped`); it is never sent again.\n */\nexport interface CashuPrepared {mint:string;swap:SerializedSwapPreview;token?:string;attemptEndedAt?:number;abandoned?:boolean;\n /** The mint answered that it signed none of the outputs while an input read spent: something else spent that ecash. */\n spentElsewhere?:boolean}\n\n/**\n * Cashu's library (174 KiB) loads with the wallet's first use of a mint or a token, not with the app's start. A mint's\n * redirect is refused on every request, not only on those with a body as the library does: `normalizeMintUrl` alone\n * says where the wallet's requests go.\n */\nconst loadCashu = () => import(\"@cashu/cashu-ts\").then((cashu) => {\n cashu.setGlobalRequestOptions({ redirect: \"error\" });\n return cashu;\n});\n\n// SDK 4.x preview.fees covers input swap fees, despite its declaration saying\n// it includes the recipient fee. includeFees(true) also tops up send outputs.\n// Derive everything leaving this wallet beyond the requested amount instead.\nasync function reviewedCashuFee(preview: SwapPreview): Promise<number> {\n const { Amount } = await loadCashu();\n const inputs = preview.inputs.reduce((sum, proof) => sum + Amount.from(proof.amount).toNumber(), 0);\n const change = (preview.keepOutputs ?? []).reduce((sum, output) => sum + Amount.from(output.blindedMessage.amount).toNumber(), 0);\n const fee = inputs - change - preview.amount.toNumber();\n if (!Number.isSafeInteger(fee) || fee < 0) throw new Error(\"Invalid Cashu prepared fee\");\n return fee;\n}\n\n/**\n * The mint was asked for a swap and has not answered. The swap is written down: the wallet asks the mint where it\n * stands until it knows, then stores what it brought or frees what it held. Nothing is known to have failed.\n */\nexport class SwapUnsettledError extends Error {\n constructor(readonly swap: PendingSwap, readonly cause?: unknown) {\n const host = new URL(swap.mint).host;\n super(swap.kind === \"receive\"\n ? `${host} has not answered yet. The ecash is added to your wallet as soon as it does.`\n : `${host} has not answered yet. The payment was not made. The sats set aside for it return to your wallet a few minutes after the mint answers.`);\n this.name = \"SwapUnsettledError\";\n }\n}\n\n/**\n * A redeem the mint refused again after its outputs were made anew on its keyset: the wallet's own words for it, as a\n * contact is told when the mint never made a redeem (`PaymentDesk.onSwapSettled`). The token stays unspent.\n */\nconst MINT_DID_NOT_CONFIRM = \"The mint did not confirm the ecash\";\n\n/**\n * Where a written-down swap stands at its mint. `never`: the mint signed none of its outputs. `gone`: the inputs it\n * reads spent all the same. `final`: nothing can change that (a refusal, or inputs spent by something else); without\n * it the swap is only overdue, and stays watched after its inputs are given back. `open`: not known yet; `slow`, a\n * mint that cannot give signatures back; `idle`, a mint that answers and has done nothing with it so far; `pending`,\n * inputs the mint reads pending.\n */\ntype SwapOutcome =\n | { state: \"done\"; keep: Proof[]; send: Proof[] }\n | { state: \"never\"; gone: Set<string>; final: boolean }\n | { state: \"open\"; slow?: boolean; idle?: boolean; pending?: boolean };\n\n/** How many of the times melts and swaps wrote down a wallet keeps on the monotonic clock (`CashuWallet.passed`). */\nconst WRITTEN_KEPT = 1_000;\n\nconst swapOf = (swap: PendingSwap) => swap.swap as SerializedSwapPreview;\n\nexport function normalizeMintUrl(input: string): string {\n let url: URL;\n try {\n url = new URL(input.trim());\n } catch {\n throw engineError(\"invalidMintUrl\");\n }\n const local = url.hostname === \"localhost\" || url.hostname === \"127.0.0.1\";\n if (url.protocol !== \"https:\" && !(local && url.protocol === \"http:\")) throw engineError(\"mintNotHttps\");\n return mintUrlSpelling(url.href);\n}\n\nexport function assertAmount(amount: number): void {\n if (!Number.isSafeInteger(amount) || amount <= 0) throw new Error(\"Enter an amount in sats\");\n // Written the English way whatever the browser's own (errorText.ts reads the amount back to say it in the app's language).\n if (amount > MAX_AMOUNT) throw new Error(`Amounts above ${MAX_AMOUNT.toLocaleString(\"en-US\")} sats are not supported`);\n}\n\n/** Stored proofs are plain objects (amounts as numbers), which is what the library calls ProofLike. */\nconst asProofLike = (proofs: StoredProof[]) => proofs as unknown as ProofLike[];\n\nconst total = (proofs: { amount: number }[]) => proofs.reduce((sum, p) => sum + p.amount, 0);\n\nconst sats = (proofs: Proof[]) => total(proofs.map((p) => ({ amount: p.amount.toNumber() })));\n\n/**\n * Whether `split` can take `amount` out of `proofs`, as it does: coins that add up exactly with the fee their receiver\n * pays to redeem them, or a swap whose inputs also pay the mint's fee for taking them in. Asks nothing of the mint.\n */\n/** Whether exact coins go as one token a payment frame carries: a wallet of many small coins can add up in hundreds. */\nconst inOneFrame = (encode: typeof import(\"@cashu/cashu-ts\").getEncodedToken, mint: string) => (send: Proof[]) =>\n encode({ mint, proofs: send, unit: UNIT }).length <= LIMITS.maxPaymentEndpointChars;\n\n/**\n * The coins a swap makes to send `amount` with the fee their receiver pays to redeem them: the fewest sats whose coins,\n * less that fee, are exactly `amount`. cashu-ts' includeFees adds coins for the fee that can be worth more than it, and\n * the contact is credited more than was sent. Undefined at a mint that charges nothing for coins, or when no such\n * coins are found up to what cashu-ts would make: its own choice is used then.\n */\nfunction sendCoins(wallet: Wallet, amount: number): number[] | undefined {\n const included = wallet.getFeesToInclude(amount).toNumber();\n if (included === 0) return undefined;\n const keyset = wallet.getKeyset();\n const fee = (coins: number) => wallet.getFeesForKeyset(coins, keyset.id).toNumber();\n const sizes = Object.keys(keyset.keys).map(Number).filter((size) => size > 0).sort((a, b) => b - a);\n const coinsOf = (value: number, among = sizes) => {\n const coins: number[] = [];\n for (const size of among) while (value >= size) { coins.push(size); value -= size; }\n return value === 0 ? coins : undefined;\n };\n for (let value = amount; value <= amount + included; value++) {\n let coins = coinsOf(value);\n // Fewer coins than the sats over `amount` pay for: the largest coin split in smaller ones until they do, if ever.\n while (coins && coins.length <= MAX_SEND_COINS && fee(coins.length) < value - amount) {\n const [largest, ...rest] = coins;\n const parts = coinsOf(largest, sizes.filter((size) => size < largest));\n coins = parts && [...parts, ...rest].sort((a, b) => b - a);\n }\n if (coins && coins.length <= MAX_SEND_COINS && fee(coins.length) === value - amount) return coins;\n }\n return undefined;\n}\n\nfunction fitsAt(wallet: Wallet, proofs: StoredProof[], amount: number): boolean {\n return outlayAt(wallet, proofs, amount) !== undefined;\n}\n\n/**\n * The sats `split` takes out of the wallet for `amount`, the mint's fees for the coins it takes in included, as `fitsAt`\n * works it out: undefined when it cannot. `inOneFrame`: whether exact coins fit in one token, as `split` asks of them.\n */\nfunction outlayAt(wallet: Wallet, proofs: StoredProof[], amount: number, inOneFrame = (_send: Proof[]) => true): number | undefined {\n try {\n const { send } = wallet.sendOffline(amount, asProofLike(proofs), { includeFees: true, exactMatch: true });\n if (send.length > 0 && sats(send) === amount + wallet.getFeesForProofs(send).toNumber() && inOneFrame(send)) return sats(send);\n } catch {\n // no exact coins: a swap makes them\n }\n try {\n const coins = sendCoins(wallet, amount);\n const outputs = coins ? coins.reduce((sum, coin) => sum + coin, 0) : amount + wallet.getFeesToInclude(amount).toNumber();\n const { send } = wallet.selectProofsToSend(asProofLike(proofs), outputs, true);\n const taken = outputs + wallet.getFeesForProofs(send).toNumber();\n return send.length > 0 && sats(send) >= taken ? taken : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The most `fitsAt` takes out of `proofs` with `extra` on top (a Lightning fee reserve): 0 when nothing fits. */\nfunction roomAt(wallet: Wallet, proofs: StoredProof[], extra = 0): number {\n // Every coin as it is, less what the mint charges to take them all in: nothing sends more.\n const most = total(proofs) - wallet.getFeesForProofs(asProofLike(proofs)).toNumber() - extra;\n if (most <= 0 || fitsAt(wallet, proofs, most + extra)) return Math.max(0, most);\n let low = 0;\n let high = most - 1;\n while (low < high) {\n const middle = Math.ceil((low + high) / 2);\n if (fitsAt(wallet, proofs, middle + extra)) low = middle;\n else high = middle - 1;\n }\n return low;\n}\n\nconst MINT_QUOTE_MISMATCH = \"The mint quoted another amount than this invoice's. Nothing was paid.\";\n/** A melt quote that is not for this invoice (`invoice` lower case, as `decodeBolt11` gives it) and its amount. */\nconst quoteMismatch = (quote: MeltQuoteBolt11Response, invoice: string, amount: number) =>\n quote.request.trim().toLowerCase().replace(/^lightning:/, \"\") !== invoice || quote.amount.toNumber() !== amount;\n\nconst toStored = (mint: string, p: Proof, reserved?: boolean): StoredProof => ({\n mint,\n id: p.id,\n amount: p.amount.toNumber(),\n secret: p.secret,\n C: p.C,\n dleq: p.dleq,\n ...(reserved ? { reserved } : {}),\n});\n\n/** The note of the ecash \"Get test coins\" brought (the engine plays its own sound for it). */\nexport const TEST_COINS_NOTE = \"Test coins from the test mint\";\nconst swapId = () => `swap-${Date.now()}-${crypto.randomUUID().slice(0, 8)}`;\nconst walletTx = (mint: string, kind: WalletTxKind, amount: number, fee: number, note?: string): WalletTx => ({\n id: `${Date.now()}-${crypto.randomUUID().slice(0, 8)}`,\n timestamp: Date.now(),\n mint,\n kind,\n amount,\n fee: Math.max(0, fee),\n note: note?.slice(0, 140),\n});\n\n/** Where a Lightning payment stands, once the mint has been asked. */\ntype MeltOutcome = \"paid\" | \"pending\" | \"unpaid\";\n\n/** What a failed payment left in the wallet, said to the person: all of it, or all but the fee the mint kept. */\nconst backInWallet = (lost: number) => lost > 0\n ? `The sats are back in your wallet, less ${lost} sat${lost === 1 ? \"\" : \"s\"} the mint kept as its fee.`\n : \"The sats are back in your wallet.\";\n\n/** A mint's own words for a refusal, as one short line: the reason at the end of `lightningRefused`. */\nconst mintReason = (error: unknown) =>\n stripHidden((error instanceof Error ? error.message : String(error)).replace(/\\s+/g, \" \")).replace(/\\s+/g, \" \").trim().slice(0, 160) || \"no reason given\";\n\n/** Every proof and swap stored, as `CashuWallet.readStored` read them. */\nexport interface StoredCashu { proofs: StoredProof[]; swaps: PendingSwap[] }\n\nexport interface WalletEvents {\n onChange(): void;\n /** Ecash arrived from the public test mint, which this wallet did not have yet. */\n onTestMintNeeded(mint: string): Promise<void>;\n /** An invoice of ours was paid and its ecash is in the wallet. */\n onQuotePaid(quote: StoredQuote): void;\n /** A Lightning payment the mint had left pending settled, one way or the other. */\n onMeltResolved(melt: PendingMelt, paid: boolean): void;\n /**\n * A swap the mint had not answered is settled, after the call that made it was over: `done`, what it brought is in\n * the wallet with its records; otherwise the mint never made it, and what it held is free again.\n */\n onSwapSettled?(swap: PendingSwap, done: boolean): void | Promise<void>;\n /**\n * Whether the chat request an invoice of ours belongs to (`StoredQuote.paymentId`) was closed: withdrawn, closed, or\n * paid some other way. Its invoice is then asked about only once more, after it expired (`nextInvoiceAsk`).\n */\n requestClosed?(paymentId: string): boolean;\n}\n\n/**\n * How long a mint gets to answer when it is only being asked something (its keys, an invoice). A mint\n * that is down can hold a request for minutes; the next mint should get its turn well before that.\n */\nexport const MINT_TIMEOUT_MS = 12_000;\n\nfunction within<T>(ms: number, work: Promise<T>, mint: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const late = new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(`${new URL(mint).host} did not answer`)), ms); });\n return Promise.race([work, late]).finally(() => clearTimeout(timer));\n}\n\n/** A swap's request, and those that ask a mint where a swap stands (NUT-09 restore, NUT-07 states). */\nconst SWAP_REQUESTS = [\"/v1/swap\", \"/v1/restore\", \"/v1/checkstate\"];\n/** A Lightning payment's request (`completeMelt`): `meltOverdue` holds its coins until it can no longer land. */\nconst MELT_REQUEST = \"/v1/melt/bolt11\";\n/**\n * What `settleQuote` asks under the mint's lock once an invoice is paid: where the quote stands, and its ecash. Its\n * outputs are written down first, so a request cut short is asked again next round (NUT-09 once issued).\n */\nconst MINT_REQUEST = \"/v1/mint/bolt11\";\nconst MINT_QUOTE_STATE = /\\/v1\\/mint\\/quote\\/bolt11\\/[^/]+$/;\n/**\n * What `melt` and `settleMelt` ask under the mint's lock: where a Lightning payment's quote stands, and the keysets its\n * change may be on. Nothing is paid on a read: one cut short is asked again (`melt` before it pays, `pollMelts` after).\n */\nconst MELT_QUOTE_STATE = /\\/v1\\/melt\\/quote\\/bolt11\\/[^/]+$/;\nconst KEYSET_REQUESTS = /\\/v1\\/(keysets|keys(\\/[^/]+)?)$/;\n\n/** How long a request to this path may last, its retries included; undefined: cashu-ts' defaults. */\nfunction requestLimit(pathname: string): number | undefined {\n if (SWAP_REQUESTS.some((path) => pathname.endsWith(path))) return CASHU_REQUEST_TIMEOUT_MS;\n if (pathname.endsWith(MINT_REQUEST) || MINT_QUOTE_STATE.test(pathname)) return CASHU_REQUEST_TIMEOUT_MS;\n if (MELT_QUOTE_STATE.test(pathname) || KEYSET_REQUESTS.test(pathname)) return CASHU_REQUEST_TIMEOUT_MS;\n if (pathname.endsWith(MELT_REQUEST)) return MELT_REQUEST_TIMEOUT_MS;\n return undefined;\n}\n\n/**\n * Each of `SWAP_REQUESTS`, a paid invoice's (`MINT_REQUEST`, `MINT_QUOTE_STATE`) and a melt's reads (`MELT_QUOTE_STATE`,\n * `KEYSET_REQUESTS`) ends within\n * `CASHU_REQUEST_TIMEOUT_MS`, and a melt's within `MELT_REQUEST_TIMEOUT_MS`, retries\n * included. cashu-ts' `requestTimeout` is per try, and NUT-19 tries a cached endpoint again after a timeout, each try\n * with a timeout of its own, for as long as the mint's `ttl` (endless when it gives none): one deadline for the whole\n * request ends them all, and a caller's abort is never retried. Past it the request failed with no answer\n * (`NetworkError`), as a try that timed out does. Every other request keeps cashu-ts' defaults. cashu-ts takes no\n * options per call of a swap or a melt: its mint client's request function is wrapped.\n */\nfunction boundMintRequests(wallet: Wallet, NetworkError: typeof CashuNetworkError): void {\n const client = wallet.mint as unknown as { _request: RequestFn };\n const request = client._request;\n client._request = async <T,>(options: RequestOptions): Promise<T> => {\n const url = new URL(options.endpoint);\n const limit = requestLimit(url.pathname);\n if (limit === undefined) return request<T>(options);\n const deadline = new AbortController();\n const timer = setTimeout(() => deadline.abort(), limit);\n options.signal?.addEventListener(\"abort\", () => deadline.abort(), { once: true });\n try {\n return await request<T>({ ...options, requestTimeout: limit, signal: deadline.signal });\n } catch (error) {\n if (deadline.signal.aborted && !options.signal?.aborted) throw new NetworkError(`${url.host} did not answer within ${limit / 1_000} s`, { cause: error });\n throw error;\n } finally {\n clearTimeout(timer);\n }\n };\n}\n\n/**\n * How long a mint that could not be loaded stays so for the payment poll's reads, then twice as long after each failed\n * load up to `MINT_FAILED_CAP_MS`: the payments of one round at a gone mint share its failure, instead of each loading\n * it again (three requests each), and so do payments made at different times, whose own backoffs are out of step.\n */\nexport const MINT_FAILED_MS = 5_000;\nexport const MINT_FAILED_CAP_MS = 600_000;\n\nexport class CashuWallet {\n private readonly wallets = new Map<string, Promise<Wallet>>();\n /** The mints whose load in `wallets` failed: the payment poll's reads try them again at `mintAsk`'s pace. */\n private readonly failedLoads = new Set<string>();\n private readonly mintAsk = new AskBackoff(MINT_FAILED_MS, MINT_FAILED_CAP_MS);\n private readonly names = new Map<string, string>();\n private readonly infos = new Map<string, MintInfoView>();\n private readonly locks = new Map<string, Promise<unknown>>();\n private quoteTimer: ReturnType<typeof setTimeout> | null = null;\n /** When `quoteTimer` fires: a round that would fire later leaves it as it is. */\n private quoteTimerAt = 0;\n /** Per open quote: when its mint was last asked about it, in this run (`nextInvoiceAsk`). */\n private readonly quoteAsked = new Map<string, number>();\n /** Per quote the screen shows: until when (`watch`). */\n private readonly quoteWatched = new Map<string, number>();\n /** Per open quote whose mint did not answer, or answered with an error: as `meltAsk`, on top of its own pace. */\n private readonly quoteAsk = new AskBackoff(INVOICE_PACE.missedMs, INVOICE_PACE.missedCapMs);\n private meltTimer: ReturnType<typeof setTimeout> | null = null;\n /** Per pending melt: when it is asked about next and the wait before that, in this run (a restart asks at once). */\n private readonly meltAsk = new AskBackoff(MELT_POLL_MS, MELT_SLOW_POLL_MS);\n private restoredTimer: ReturnType<typeof setTimeout> | null = null;\n private swapTimer: ReturnType<typeof setTimeout> | null = null;\n private swapTimerAt = 0;\n /** Per open swap whose mint did not answer past its overdue time: as `meltAsk`, in this run (a restart asks at once). */\n private readonly swapAsk = new AskBackoff(SWAP_POLL_MS, SWAP_SLOW_POLL_MS);\n /** Per mint that could not say which restored ecash is spent, or holds some pending: as `meltAsk`. */\n private readonly restoredAsk = new AskBackoff(RESTORED_POLL_MS, RESTORED_SLOW_POLL_MS);\n /** Per melt quote that ended unpaid: the sats the mint kept all the same (the fee of the split before the melt). */\n private readonly failedFees = new Map<string, number>();\n /** Melt quotes that ended unpaid with proofs the mint read spent: ecash spent somewhere else, said as such. */\n private readonly spentAway = new Set<string>();\n /**\n * Proofs of tokens the mint read spent by something else (`mint secret`), the newest SPENT_KEPT: spent stays spent,\n * so the same token sent again, under any id or encoding, is refused without asking the mint again.\n */\n private readonly spentTokens = new Set<string>();\n /** Per melt quote shown to the person: the invoice, its amount and the most it was said to cost in fees\n * (the mint's reserve and the coins' own fees). Only these are paid, for no more. */\n private readonly shownQuotes = new Map<string, { request: string; amount: number; feeReserve: number }>();\n /**\n * Per time a melt or swap wrote down (`createdAt`, `attemptEndedAt`): where it stands on the monotonic clock. Whether a\n * request of it can still reach the mint is measured from there (`passed`): read by the wall clock, a clock stepped an\n * hour forward booked a melt whose answer was lost unpaid within seconds, its sats back, and then the mint paid it.\n */\n private readonly writtenAt = new Map<number, number>();\n\n /**\n * `getMints`: the mints of one network (the engine's default when none is named), primary first: balances,\n * invoices, payments of that network's Cashu wallet. `getKnownMints`: every mint the user added, whatever its\n * network: ecash from any of them is taken in, and counts in its own network's wallet.\n */\n constructor(\n private readonly getMints: (network?: WalletNetwork) => string[],\n private readonly events: WalletEvents,\n private readonly getKnownMints: () => string[] = getMints,\n ) {}\n\n /** Stopped with the engine: no poll runs or is scheduled again (WISP 06: the check after a handoff's stop is final). */\n private stopped = false;\n\n start(): void {\n this.stopped = false;\n void this.pollQuotes();\n void this.pollMelts();\n void this.checkRestored();\n void this.pollSwaps();\n // Names, fees and limits for the UI; a mint that is down simply stays without them.\n for (const mint of this.getKnownMints()) void this.checkMint(mint).then(() => this.events.onChange(), () => {});\n }\n\n /**\n * Stops every poll and timer, and waits for what runs inside a per-mint lock to end: a swap there must end, not be cut.\n * Nothing is written by this wallet after it resolves.\n */\n async stop(): Promise<void> {\n this.stopped = true;\n for (const timer of [this.quoteTimer, this.meltTimer, this.restoredTimer, this.swapTimer]) if (timer) clearTimeout(timer);\n this.quoteTimer = this.meltTimer = this.restoredTimer = this.swapTimer = null;\n // Bounded: a mint that never answers does not hold a closing app forever (the handoff's check after the stop then\n // sees a swap still going through and refuses).\n let timer: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([Promise.all([...this.locks.values()].map((lock) => lock.catch(() => {}))), new Promise((resolve) => { timer = setTimeout(resolve, CashuWallet.STOP_WAIT_MS); })]);\n clearTimeout(timer);\n }\n /** How long `stop` waits for a swap in a per-mint lock. */\n static STOP_WAIT_MS = 30_000;\n\n /** The wall-clock time a melt or swap writes down, its place on the monotonic clock kept for `passed`. */\n private stamp(): number {\n const now = Date.now();\n this.keepWritten(now, performance.now());\n return now;\n }\n\n private keepWritten(at: number, monotonic: number): void {\n this.writtenAt.set(at, monotonic);\n if (this.writtenAt.size > WRITTEN_KEPT) this.writtenAt.delete(this.writtenAt.keys().next().value!);\n }\n\n /**\n * How long really passed since `at`, a time a melt or swap wrote down, while this wallet ran. One written by an earlier\n * run counts by the wall clock up to the first time this run asks, never below nothing: written by a clock ahead of\n * this one, its window starts again rather than waiting for the clock to get there.\n */\n private passed(at: number): number {\n let since = this.writtenAt.get(at);\n if (since === undefined) this.keepWritten(at, since = performance.now() - Math.max(0, Date.now() - at));\n return performance.now() - since;\n }\n\n /** Whether no request of this melt can reach the mint any more: its one request is sent right after it is written down. */\n private meltOverdue(melt: PendingMelt): boolean {\n return this.passed(melt.createdAt) >= MELT_REQUEST_TIMEOUT_MS + SWAP_SETTLED_MS;\n }\n\n /** Whether no request of this swap can reach the mint any more: a request's longest life, and a margin after its last try. */\n private swapOverdue(swap: PendingSwap): boolean {\n return swap.attemptEndedAt !== undefined && this.passed(swap.createdAt) >= CASHU_REQUEST_TIMEOUT_MS + SWAP_SETTLED_MS\n && this.passed(swap.attemptEndedAt) >= SWAP_SETTLED_MS;\n }\n\n /** Whether a swap is past the hour it is watched for (`SWAP_WATCH_MS`). */\n private pastWatch(swap: PendingSwap): boolean {\n return this.passed(swap.createdAt) >= SWAP_WATCH_MS;\n }\n\n /**\n * The Cashu wallet of one network: its mints, their balance, and the network's newest movements (every network's when\n * none is named) with the fees they paid. Only those movements are read, however long the history is. `read` is the\n * proofs and swaps as `readStored` read them, shared by the views of several networks.\n */\n async view(network?: WalletNetwork, read?: StoredCashu): Promise<WalletView> {\n const { proofs, swaps: allSwaps } = read ?? await this.readStored();\n const mints: MintView[] = this.getMints(network).map((url) => ({\n url,\n name: this.names.get(url) ?? new URL(url).hostname,\n balance: total(proofs.filter((p) => p.mint === url && !p.reserved)),\n info: this.infos.get(url) ?? null,\n }));\n const history = await this.history(network, HISTORY_SHOWN);\n const here = new Set(mints.map((m) => m.url));\n const swaps = allSwaps.filter((s) => here.has(s.mint) && !s.released && !s.finished);\n // What a swap is about: the proofs it spends, or what a redeem would bring.\n const about = (s: PendingSwap) => s.kind === \"send\" ? swapOf(s).inputs.reduce((sum, p) => sum + Number(p.amount), 0) : s.tx?.amount ?? 0;\n // Inputs that read spent at a mint that cannot say what it gave for them are not \"set aside\": they may not return.\n const spentAway = new Set(swaps.filter((s) => s.stuck && s.kind === \"send\").flatMap((s) => swapOf(s).inputs.map((p) => p.secret)));\n return {\n mints,\n balance: total(mints.map((m) => ({ amount: m.balance }))),\n // Held for a payment or a swap the mint has not settled: not spendable now, and not gone.\n setAside: total(proofs.filter((p) => here.has(p.mint) && p.reserved && !spentAway.has(p.secret))),\n openSwaps: swaps.length,\n swapsAmount: total(swaps.map((s) => ({ amount: about(s) }))),\n unconfirmed: total(swaps.filter((s) => s.stuck).map((s) => ({ amount: about(s) }))),\n history,\n feesPaid: history.reduce((sum, tx) => sum + tx.fee, 0),\n };\n }\n\n /** A network's `count` newest movements, newest first (every network's when none is named): only those are read. */\n history(network: WalletNetwork | undefined, count: number): Promise<WalletTx[]> {\n return newestWalletTx<WalletTx>((mint) => !network || mintNetwork(mint) === network, count);\n }\n\n /** Every proof and swap stored, read once for the views of every network: each read is the whole store. */\n async readStored(): Promise<StoredCashu> {\n const proofs = await this.allProofs();\n return { proofs, swaps: await this.readSwaps() };\n }\n\n /**\n * Ecash a profile restore brought back (`unchecked`) is a copy from when the backup was made. What was spent since\n * (by the profile it was copied from, or by this one before it was restored) still counted in the balance, for good,\n * and every payment that picked one of those proofs failed with the mint's \"Token already spent\". Each mint is asked\n * once which of them it still reads unspent: a spent proof is dropped, an unspent one is checked for good, and one\n * the mint holds pending, or a mint that cannot be asked, is asked again later: after RESTORED_POLL_MS, then twice\n * as late each time up to RESTORED_SLOW_POLL_MS (`restoredAsk`). `paced`: only the mints whose time came (the timer);\n * a start or a restore asks every one now.\n */\n private async checkRestored(paced = false): Promise<void> {\n if (this.restoredTimer) clearTimeout(this.restoredTimer);\n this.restoredTimer = null;\n if (this.stopped) return;\n const waiting = (p: StoredProof) => !!p.unchecked && !p.reserved;\n let changed = false, next = Infinity;\n const mints = new Set((await this.allProofs()).filter(waiting).map((p) => p.mint));\n this.restoredAsk.keepOnly(mints);\n for (const mint of mints) {\n if (paced && !this.restoredAsk.due(mint, Date.now())) { next = Math.min(next, this.restoredAsk.at(mint, Date.now())); continue; }\n let again = false;\n try {\n await this.locked(mint, async () => {\n const proofs = (await this.allProofs()).filter((p) => p.mint === mint && waiting(p));\n if (!proofs.length) return;\n const states = await (await this.wallet(mint)).checkProofsStates(proofs);\n if (states.length !== proofs.length) throw new Error(\"The mint answered for another number of proofs\");\n await this.sealedTransact([STORES.proofs], { [STORES.proofs]: proofs }, (stores) => {\n proofs.forEach((proof, i) => {\n const state = states[i]?.state;\n if (state === \"SPENT\") stores[STORES.proofs].delete(proof.secret);\n else if (state === \"UNSPENT\") { const { unchecked: _checked, ...kept } = proof; stores[STORES.proofs].put(kept satisfies StoredProof); }\n else again = true;\n });\n });\n changed = true;\n });\n } catch {\n again = true;\n }\n if (again) next = Math.min(next, Date.now() + this.restoredAsk.missed(mint, Date.now()));\n else this.restoredAsk.forget(mint);\n }\n if (changed) this.events.onChange();\n if (next < Infinity && !this.stopped) this.restoredTimer = setTimeout(() => void this.checkRestored(true), Math.max(0, next - Date.now()));\n }\n\n /** Talks to the mint before it is added: a typo should not become a place to keep money. */\n async checkMint(url: string): Promise<{ url: string; name: string }> {\n const normalized = normalizeMintUrl(url);\n let wallet: Wallet;\n try { wallet = await this.wallet(normalized); }\n catch (error) {\n // \"Failed to fetch\" says nothing to a person: say which place did not answer, and what it should be.\n throw Object.assign(engineError(\"mintUnreachable\", { host: new URL(normalized).host }), { cause: error });\n }\n const info = wallet.getMintInfo();\n // The mint's own words, without the characters that hide text or reorder it, so its name reads as what it is.\n const name = (typeof info.name === \"string\" ? stripHidden(info.name).replace(/\\s+/g, \" \").trim().slice(0, 80) : \"\") || new URL(normalized).hostname;\n this.names.set(normalized, name);\n\n const bounds = (nut: 4 | 5) => {\n const method = info.isSupported(nut).params.find((m) => m.method === \"bolt11\" && m.unit === UNIT);\n const toNumber = (v: unknown) => (v === null || v === undefined ? null : Number(v));\n return method ? { min: toNumber(method.min_amount), max: toNumber(method.max_amount) } : null;\n };\n const active = wallet.keyChain.getKeysets().filter((k) => k.isActive);\n this.infos.set(normalized, {\n version: info.version || undefined,\n motd: typeof info.motd === \"string\" ? stripHidden(info.motd).trim().slice(0, 200) || undefined : undefined,\n inputFeePpk: active.length > 0 ? Math.min(...active.map((k) => k.fee)) : 0,\n receive: bounds(4),\n send: bounds(5),\n });\n return { url: normalized, name };\n }\n\n /** What `view(network).balance` says, from the proofs alone: no swaps, no history. */\n async balance(network?: WalletNetwork): Promise<number> {\n const here = new Set(this.getMints(network));\n return total((await this.allProofs()).filter((p) => here.has(p.mint) && !p.reserved));\n }\n\n async balanceAt(mint: string): Promise<number> {\n return total((await this.allProofs()).filter((p) => p.mint === mint && !p.reserved));\n }\n\n // -- Lightning in ----------------------------------------------------------\n\n async receiveLightning(amount: number, paymentId?: string, network?: WalletNetwork): Promise<StoredQuote> {\n assertAmount(amount);\n // The primary mint comes first; if it is down the next one takes the invoice.\n let created: { mint: string; response: Awaited<ReturnType<Wallet[\"createMintQuoteBolt11\"]>> } | null = null;\n let lastError: unknown = new Error(\"No mint configured\");\n for (const candidate of this.getMints(network)) {\n try {\n created = { mint: candidate, response: await within(MINT_TIMEOUT_MS, mintInvoice(await this.wallet(candidate), amount, \"Ghostly\"), candidate) };\n break;\n } catch (error) {\n // A mint that failed (\"internal error\", a closed connection) is named, with what to do; its words kept last.\n lastError = mintFailed(error) ? Object.assign(engineError(\"mintFailedInvoice\", { host: new URL(candidate).host, reason: mintReason(error) }), { cause: error }) : error;\n }\n }\n if (!created) {\n if ((lastError as { engineCode?: unknown } | null)?.engineCode === \"mintFailedInvoice\") throw lastError;\n throw new Error(`No mint could create an invoice: ${lastError instanceof Error ? lastError.message : lastError}`);\n }\n const { mint, response } = created;\n const quote: StoredQuote = {\n quote: response.quote,\n mint,\n amount,\n invoice: response.request,\n createdAt: Date.now(),\n expiresAt: response.expiry ? response.expiry * 1000 : null,\n paymentId,\n // A test mint says \"paid\" to every invoice: that is not someone paying this one.\n ...(paysItsOwnInvoices(mint) ? { held: true } : {}),\n };\n await this.putQuote(quote);\n // Nobody paid it yet: it is first asked about after the fast pace's gap.\n this.quoteAsked.set(quote.quote, Date.now());\n void this.pollQuotes();\n return quote;\n }\n\n /**\n * The screen shows this invoice of ours (Receive): it is asked about at the fast pace for `INVOICE_PACE.watchMs`, and\n * now if it was not just asked. The screen says it again while it shows it. Returns whether it is one of ours here.\n */\n async watch(invoice: string): Promise<boolean> {\n const wanted = invoice.trim().toLowerCase();\n const quote = (await this.quotes()).find((q) => q.invoice.toLowerCase() === wanted);\n if (!quote) return false;\n this.quoteWatched.set(quote.quote, Date.now() + INVOICE_PACE.watchMs);\n // Its mint may be back: the screen asks whatever wait its silence earned.\n this.quoteAsk.forget(quote.quote);\n await this.pollQuotes();\n return true;\n }\n\n /**\n * A payer says it paid this invoice of ours (a contact's app, once its payment went through). A held quote (a test\n * mint's, which reads paid by itself) is minted from now on; on any other mint the mint's own answer decides, as\n * always. Returns whether the invoice is one of ours. `said` false: the payer spoke of another invoice, so this one is\n * only asked about, and a held one stays held. Only this invoice is asked about now: the others keep their pace.\n */\n async vouch(invoice: string, said = true): Promise<boolean> {\n const wanted = invoice.trim().toLowerCase();\n let quote = (await this.quotes()).find((q) => q.invoice.toLowerCase() === wanted);\n if (!quote) return false;\n if (quote.held && said) {\n quote = { ...quote, held: undefined } satisfies StoredQuote;\n await this.putQuote(quote);\n }\n // The payment may take a moment to settle at the mint: the invoice is asked about at the fast pace meanwhile.\n this.quoteWatched.set(quote.quote, Date.now() + INVOICE_PACE.watchMs);\n if (!(await this.settleQuotes([quote])).length && !quote.held && !quote.issuedUnclaimed) this.scheduleQuotes(this.nextAsk(quote, Date.now()));\n return true;\n }\n\n /** True while an invoice of ours waits for a payer's word (see `vouch`): whatever its mint says, it is not paid. */\n async isHeld(quote: string): Promise<boolean> {\n return !!(await wrap<StoredQuote | undefined>((await store(STORES.quotes, \"readonly\")).get(quote)))?.held;\n }\n\n /**\n * \"Get test coins\": a test mint pays its own invoices, so an invoice asked of it on purpose is its faucet. Only a\n * mint that does (`paysItsOwnInvoices`), never real money. Waits a little for the mint to say paid, then mints;\n * a mint slower than that has its quote minted by the regular poll.\n */\n async testCoins(amount: number, network: WalletNetwork = \"testnet\"): Promise<{ mint: string; amount: number }> {\n assertAmount(amount);\n const mint = this.getMints(network).find(paysItsOwnInvoices);\n if (!mint) throw new Error(\"This wallet has no test mint to ask for test coins\");\n let response: Awaited<ReturnType<typeof mintInvoice>>;\n try {\n response = await within(MINT_TIMEOUT_MS, mintInvoice(await this.wallet(mint), amount, \"Ghostly test coins\"), mint);\n } catch (error) {\n // A test mint that failed (\"internal error\", a closed connection) is named, with what to do; its words kept last.\n throw mintFailed(error) ? Object.assign(engineError(\"mintFailedFaucet\", { host: new URL(mint).host, reason: mintReason(error) }), { cause: error }) : error;\n }\n const quote: StoredQuote = {\n quote: response.quote,\n mint,\n amount,\n invoice: response.request,\n createdAt: Date.now(),\n expiresAt: response.expiry ? response.expiry * 1000 : null,\n testCoins: true,\n };\n await this.putQuote(quote);\n const deadline = Date.now() + TEST_COINS_WAIT_MS;\n for (;;) {\n const minted = await this.locked(mint, () => this.settleQuote(quote.quote));\n if (minted) {\n this.events.onChange();\n return { mint, amount };\n }\n if (Date.now() > deadline) {\n void this.pollQuotes();\n throw new Error(`${new URL(mint).host} has not paid its test coins yet: they show up here once it does`);\n }\n await new Promise((resolve) => setTimeout(resolve, 1_000));\n }\n }\n\n /**\n * Asks the mints about the open invoices now, without waiting for the next round. `mints`: only the invoices at\n * these mints (one network's wallet, before it is removed), claiming what is paid; the regular round is left alone.\n */\n async checkQuotes(mints?: readonly string[]): Promise<void> {\n if (!mints) return this.pollQuotes(true);\n const at = new Set(mints);\n await this.settleQuotes((await this.quotes()).filter((q) => at.has(q.mint)));\n }\n\n /** Every invoice of ours the mints have not settled yet, held, paid-unclaimed and issued-unclaimed ones included. */\n async quotes(): Promise<StoredQuote[]> {\n return openRows(STORES.quotes, await wrap<StoredQuote[]>((await store(STORES.quotes, \"readonly\")).getAll()));\n }\n\n /** Sealed before its transaction opens, when the profile is encrypted: a paid quote's outputs can be minted from. */\n private async putQuote(quote: StoredQuote): Promise<void> {\n const row = await sealRow(STORES.quotes, quote);\n await committed((await store(STORES.quotes, \"readwrite\")).put(row));\n }\n\n /**\n * Invoices are paid by someone else, somewhere else; all we can do is ask the mint. A quote is the only\n * claim on the sats paid to it, so it is dropped only once the mint says it is unpaid and it has expired.\n * Each quote is asked about at its own pace (`nextInvoiceAsk`): often while it is new or on screen, then less.\n * `now`: every open quote is asked about, whatever its pace (someone says it was paid). The store is read once.\n */\n private async pollQuotes(now = false): Promise<void> {\n if (this.quoteTimer) clearTimeout(this.quoteTimer);\n this.quoteTimer = null;\n if (this.stopped) return;\n const quotes = await this.quotes();\n const gone = new Set<string>();\n\n // A held quote is not asked about: its mint's \"paid\" means nothing. It only goes once it has expired.\n for (const held of quotes.filter((q) => q.held && q.expiresAt && q.expiresAt + INVOICE_PACE.expiryGraceMs < Date.now())) {\n await committed((await store(STORES.quotes, \"readwrite\")).delete(held.quote));\n gone.add(held.quote);\n }\n // What this run knows of quotes that are no longer stored goes with them.\n const stored = new Set(quotes.map((q) => q.quote));\n for (const pace of [this.quoteAsked, this.quoteWatched]) for (const id of pace.keys()) if (!stored.has(id)) pace.delete(id);\n this.quoteAsk.keepOnly(stored);\n\n const open = quotes.filter((q) => !q.issuedUnclaimed && !q.held);\n const at = Date.now();\n for (const settled of await this.settleQuotes(open.filter((q) => now || this.nextAsk(q, at) <= at + INVOICE_PACE.dueSlackMs))) gone.add(settled);\n\n const next = open.filter((q) => !gone.has(q.quote)).map((q) => this.nextAsk(q, Date.now()));\n if (next.length) this.scheduleQuotes(Math.min(...next));\n }\n\n /** When the mint is next asked about this quote: at its pace, and not before the wait its mint's silence earned. */\n private nextAsk(quote: StoredQuote, now: number): number {\n return Math.max(this.quoteAsk.at(quote.quote, 0), nextInvoiceAsk({\n createdAt: quote.createdAt,\n expiresAt: quote.expiresAt,\n watchedUntil: this.quoteWatched.get(quote.quote),\n closed: !!quote.paymentId && !!this.events.requestClosed?.(quote.paymentId),\n paid: !!quote.paid,\n }, this.quoteAsked.get(quote.quote), now));\n }\n\n /** The next round at `at`, unless one is due sooner. */\n private scheduleQuotes(at: number): void {\n if (this.stopped) return;\n if (this.quoteTimer && this.quoteTimerAt <= at) return;\n if (this.quoteTimer) clearTimeout(this.quoteTimer);\n this.quoteTimerAt = at;\n this.quoteTimer = setTimeout(() => { this.quoteTimer = null; void this.pollQuotes(); }, Math.max(0, at - Date.now()));\n }\n\n /**\n * Asks the mints about these quotes. Returns the ones minted. A quote whose mint does not answer, or answers with an\n * error, waits longer each time (`quoteAsk`); a mint that could not be loaded is not loaded again in this call for its\n * other quotes, which wait as that one does. The load runs outside the mint's lock, so a failed one does not hold it.\n */\n private async settleQuotes(quotes: readonly StoredQuote[]): Promise<string[]> {\n const minted: string[] = [];\n const down = new Set<string>();\n for (const { quote, mint } of quotes.filter((q) => !q.issuedUnclaimed && !q.held)) {\n this.quoteAsked.set(quote, Date.now());\n // Its mint could not be loaded for another quote just now: this one waits as that one does.\n if (down.has(mint)) { this.quoteAsk.missed(quote, Date.now()); continue; }\n try {\n try { await this.wallet(mint); }\n catch (error) { down.add(mint); throw error; }\n const paid = await this.locked(mint, () => this.settleQuote(quote));\n this.quoteAsk.forget(quote);\n if (paid) {\n minted.push(quote);\n // Test coins are no invoice anyone else knows of.\n if (!paid.testCoins) this.events.onQuotePaid(paid);\n this.events.onChange();\n }\n } catch {\n // The mint did not answer, or answered with an error: asked again later, and later each time.\n this.quoteAsk.missed(quote, Date.now());\n }\n }\n return minted;\n }\n\n /** Runs under the mint's lock, so two rounds never mint one quote twice. Returns the quote once its ecash is in. */\n private async settleQuote(id: string): Promise<StoredQuote | null> {\n // Another round may have settled it while this one waited for the lock.\n const quote = await openRow(STORES.quotes, await wrap<StoredQuote | undefined>((await store(STORES.quotes, \"readonly\")).get(id)));\n if (!quote || quote.issuedUnclaimed || quote.held) return null;\n const wallet = await this.wallet(quote.mint);\n const { OutputData } = await loadCashu();\n const answer = await wallet.checkMintQuoteBolt11(quote.quote);\n const { state } = answer;\n\n if (state === \"UNPAID\") {\n if (quote.expiresAt && quote.expiresAt + 60_000 < Date.now()) {\n await committed((await store(STORES.quotes, \"readwrite\")).delete(quote.quote));\n }\n return null;\n }\n const saved = (quote.outputs as SerializedOutputData[] | undefined)?.map((o) => OutputData.deserialize(o));\n if (state === \"ISSUED\") {\n // Issued for outputs that were written down here: the mint still has its signatures for them (NUT-09).\n // A mint that cannot be asked, or answers with an error, is asked again next round: the quote stays as it is.\n const issued = saved?.length ? await this.signedOutputs(wallet, saved) : undefined;\n if (Array.isArray(issued)) return this.storeMinted(quote, issued);\n // The ecash is stored in the same transaction that drops the quote, so a quote still here was never\n // credited to this wallet. It is the only trace of those sats: keep it, stop asking.\n console.warn(`[wallet] ${quote.mint} issued quote ${quote.quote} (${quote.amount} sats) but this wallet holds no ecash for it`);\n await this.putQuote({ ...quote, issuedUnclaimed: true } satisfies StoredQuote);\n return null;\n }\n\n // Paid: money arrived, and until it is minted this quote is the only claim on it. Written down, so a wallet\n // about to be removed can say so (walletRemoval) while the mint is slow to hand the ecash over.\n // The outputs the mint is asked to sign are written down with it, and asked for again as they are: whichever\n // request the mint acts on, what it issues is for these, and can be asked for again.\n const preview = await wallet.prepareMint(\"bolt11\", quote.amount, { ...answer, quote: quote.quote });\n // These quotes are not locked to a key (NUT-20), so no signature over the outputs has to be made again.\n if (saved) preview.outputData = saved;\n const written: StoredQuote = { ...quote, paid: true, outputs: saved ? quote.outputs : preview.outputData.map((o) => OutputData.serialize(o as OutputData)) };\n if (!quote.paid || !saved) await this.putQuote(written);\n let proofs: Proof[];\n try {\n proofs = await wallet.completeMint(preview);\n } catch (error) {\n // Outputs the mint refuses while the quote is still only paid (on a keyset it retired since) would be refused\n // every round: the next one makes new ones. Nothing was issued for these.\n if (mintRefused(error) &&(await wallet.checkMintQuoteBolt11(quote.quote).catch(() => null))?.state === \"PAID\") {\n const { outputs: _refused, ...fresh } = written;\n await this.putQuote(fresh satisfies StoredQuote);\n }\n throw error;\n }\n return this.storeMinted(quote, proofs);\n }\n\n /** The ecash of a paid invoice goes in with its history line, in the transaction that drops the quote. */\n private async storeMinted(quote: StoredQuote, proofs: Proof[]): Promise<StoredQuote> {\n const minted = sats(proofs);\n const tx: WalletTx = { ...walletTx(quote.mint, \"lightning-in\", minted, quote.amount - minted, quote.paymentId ? \"Request paid over Lightning\" : quote.testCoins ? TEST_COINS_NOTE : undefined), quote: quote.quote };\n await this.sealedTransact([STORES.proofs, STORES.walletTx, STORES.quotes], { [STORES.proofs]: proofs }, (stores) => {\n // From a restored copy, the profile it came from may have minted this invoice and spent its ecash since.\n for (const p of proofs) stores[STORES.proofs].put({ ...toStored(quote.mint, p), ...(quote.restored ? { unchecked: true } : {}) } satisfies StoredProof);\n stores[STORES.walletTx].put(tx);\n stores[STORES.quotes].delete(quote.quote);\n });\n if (quote.restored) void this.checkRestored();\n return quote;\n }\n\n /** Where one of our invoices stands at its mint. Only a question: ecash is minted by the poll above. */\n async mintQuoteState(mint: string, quote: string): Promise<string> {\n return String((await (await this.wallet(mint)).checkMintQuoteBolt11(quote)).state);\n }\n\n /** Where one of our Lightning payments stands at its mint. Only a question: `pollMelts` books the answer. */\n async meltQuoteState(mint: string, quote: string): Promise<string> {\n return String((await (await this.wallet(mint)).checkMeltQuoteBolt11(quote)).state);\n }\n\n // -- ecash out and in --------------------------------------------------------\n\n /**\n * Takes `amount` out of the wallet as a token, from the first of `preferred`\n * (or of the user's mints) that holds enough. The receiver's redeem fee is\n * included, so they are credited the full amount.\n *\n * `outbox` turns the token into the record that keeps it (a chat payment). It is written in the same\n * transaction that takes the inputs out of the wallet, so the ecash never lives only in memory.\n */\n async createToken(\n amount: number,\n preferred?: string[],\n note?: string,\n outbox?: (token: string, mint: string) => StoredPayment,\n network?: WalletNetwork,\n ): Promise<{ token: string; mint: string }> {\n assertAmount(amount);\n // A send without mints comes from this network's mints. A request names its mints, but a contact may name a\n // real mint on a Testnet request: only mints of the network asked for are ever spent from.\n const mine = preferred ? this.getKnownMints() : this.getMints(network);\n const candidates = (preferred ? preferred.map(mintUrlSpelling).filter((m) => mine.includes(m)) : mine)\n .filter((m) => !network || mintNetwork(m) === network);\n /** The most a mint that holds the amount could send with its fees on top. */\n let room = 0;\n /** The coins held at `mint` when they send the amount. */\n const fitting = async (mint: string): Promise<StoredProof[] | undefined> => {\n const proofs = await this.proofsAt(mint);\n if (total(proofs) < amount) return undefined;\n // At a mint that charges for each coin it takes in, the amount held may not cover its fees: the next mint may.\n const wallet = await this.wallet(mint);\n if (fitsAt(wallet, proofs, amount)) return proofs;\n room = Math.max(room, roomAt(wallet, proofs));\n return undefined;\n };\n for (const mint of candidates) {\n if (!(await fitting(mint))) continue;\n const sent = await this.locked(mint, async () => {\n // Asked again in the mint's turn: another payment may have taken these coins since.\n const proofs = await fitting(mint);\n if (!proofs) return undefined;\n const { inputs, keep, send, swap } = await this.split(mint, amount, proofs);\n const token = (await loadCashu()).getEncodedToken({ mint, proofs: send, unit: UNIT });\n // Everything that left the balance beyond the amount: the swap's fee and the redeem fee prepaid for the receiver.\n const spent = total(inputs) - sats(keep);\n const tx = walletTx(mint, \"ecash-out\", amount, spent - amount, note);\n const kept = outbox?.(token, mint);\n await this.sealedTransact([STORES.proofs, STORES.walletTx, STORES.swaps, ...(kept ? [STORES.payments] : [])], { [STORES.proofs]: keep, [STORES.payments]: kept ? [kept] : [] }, (stores) => {\n this.queueReplace(stores[STORES.proofs], mint, inputs, keep);\n stores[STORES.walletTx].put(tx);\n if (swap) stores[STORES.swaps].delete(swap.id);\n if (kept) stores[STORES.payments].put(kept);\n });\n this.events.onChange();\n return { token, mint };\n });\n if (sent) return sent;\n }\n if (room > 0) throw engineError(\"notEnoughForFee\", { amount: room });\n // The sats are there, only set aside by a split the mint has not answered: said as the first attempt said it.\n const held = await this.heldBySilentSplit(candidates, amount);\n if (held) throw new SwapUnsettledError(held);\n throw engineError(candidates.length === 0 && preferred ? \"noSharedMint\" : \"notEnoughSats\");\n }\n\n /** An open send swap at one of `mints` whose reserved inputs, with the coins free there, would cover `amount`. */\n private async heldBySilentSplit(mints: string[], amount: number): Promise<PendingSwap | undefined> {\n for (const mint of mints) {\n const open = (await this.swapsAt(mint)).filter((s) => s.kind === \"send\" && !s.released && !s.finished);\n if (open.length === 0) continue;\n const held = await Promise.all(open.map((s) => this.storedInputs(s)));\n const swap = open.find((_, i) => held[i].length > 0);\n if (swap && total(await this.proofsAt(mint)) + total(held.flat()) >= amount) return swap;\n }\n return undefined;\n }\n\n async prepareReviewedCashu(mint:string,amount:number):Promise<{fee:number;prepared:CashuPrepared}> {\n assertAmount(amount);\n if(!this.getKnownMints().includes(mint))throw new Error(\"Select a configured mint\");\n return this.locked(mint,async()=>{\n const wallet=await this.wallet(mint);\n const proofs=await this.proofsAt(mint);\n const prepare=(sats:number)=>wallet.ops.send(sats,asProofLike(proofs)).includeFees(true).prepare();\n const preview=await prepare(amount).catch(async(error:unknown)=>{\n // Coins that cannot cover the amount and its fees are refused in cashu-ts' own English words: said as a send\n // says it instead, with how much fits. Its coins are not split's, so `roomAt` would claim more than fits here.\n if(!/^Not enough funds available/.test(error instanceof Error?error.message:\"\"))throw error;\n const fits=(sats:number)=>prepare(sats).then(()=>true,()=>false);\n // Below the amount asked, and at most what every coin brings in past its fee (all of it, at a mint that charges none).\n let low=0,high=Math.min(amount-1,total(proofs)-wallet.getFeesForProofs(asProofLike(proofs)).toNumber());\n while(low<high){\n const middle=Math.ceil((low+high)/2);\n if(await fits(middle))low=middle;\n else high=middle-1;\n }\n throw low>0?engineError(\"notEnoughForFee\",{amount:low}):engineError(\"notEnoughSats\");\n });\n return {fee:await reviewedCashuFee(preview),prepared:{mint,swap:(await loadCashu()).serializeSwapPreview(preview)}};\n });\n }\n\n /** Reserve before the mint call. A timeout keeps these inputs reserved for read-only recovery. */\n async executeReviewedCashu(review:PaymentReview,prepared:CashuPrepared):Promise<string> {\n return this.locked(prepared.mint,async()=>{\n const preview=(await loadCashu()).deserializeSwapPreview(prepared.swap);\n // Refused before the mint is asked: nothing was sent, and the review fails for good (the request can be paid again).\n if(prepared.mint!==review.provider || preview.amount.toNumber()!==review.amount || await reviewedCashuFee(preview)!==review.fee)throw new PaymentPreflightError(\"Cashu preview does not match review\");\n const seals=new RowSeals(),tx=(await openDb()).transaction(STORES.proofs,\"readwrite\");\n await new Promise<void>((resolve,reject)=>{\n const proofs=sealedStore(tx.objectStore(STORES.proofs),seals);\n for(const input of preview.inputs){\n const request=proofs.get(input.secret);\n request.onsuccess=()=>{\n const proof:StoredProof|undefined=request.result;\n if(!proof || proof.reserved || proof.mint!==prepared.mint || proof.C!==input.C || proof.amount!==input.amount.toNumber()){tx.abort();return;}\n proofs.put({...proof,reserved:true});\n };\n }\n tx.oncomplete=()=>resolve();tx.onabort=tx.onerror=()=>reject(new PaymentPreflightError(engineText(\"reviewedSatsGone\")));\n });\n // The inputs leave the balance for \"set aside\" now: a mint that never answers would leave the view made before.\n this.events.onChange();\n const wallet=await this.wallet(prepared.mint);\n const {keep,send}=await wallet.completeSwap(preview);\n return this.finishReviewedCashu(review,prepared,keep,send);\n });\n }\n\n /** NUT-09 retrieves signatures for the exact saved outputs; it never creates another swap. */\n async recoverReviewedCashu(review:PaymentReview,prepared:CashuPrepared):Promise<string|undefined> {\n const stored=await openRow(STORES.payments,await wrap<StoredPayment|undefined>((await store(STORES.payments,\"readonly\")).get(review.id)));\n if(stored?.token)return stored.token;\n const wallet=await this.wallet(prepared.mint,true);\n const {OutputData}=await loadCashu();\n const keep=(prepared.swap.keepOutputs??[]).map(OutputData.deserialize);\n const send=(prepared.swap.sendOutputs??[]).map(OutputData.deserialize);\n const outputs=[...keep,...send];\n const restored=await this.restoreOutputs(wallet,outputs);\n if(!Array.isArray(restored))return undefined;\n return this.finishReviewedCashu(review,prepared,restored.slice(0,keep.length),restored.slice(keep.length));\n }\n\n /**\n * What the mint says of outputs that were written down before it was asked to sign them: the proofs they stand for\n * when it signed them all, `none` when it answered that it signed none, and undefined when it has no way of saying\n * (it does not restore, NUT-09, by its own info). Only an answer counts: a mint that cannot be reached, answers with\n * an error or answers for some of the outputs throws, and is asked again later.\n */\n private async signedOutputs(wallet: Wallet, outputs: OutputData[]): Promise<Proof[] | \"none\" | undefined> {\n if (!wallet.getMintInfo().isSupported(9).supported) return undefined;\n const restored = await this.restoreOutputs(wallet, outputs);\n if (restored === \"some\") throw new Error(\"The mint answered for some of the outputs\");\n return restored;\n }\n\n /**\n * The mint's signatures for these exact outputs (NUT-09), as the proofs they stand for: all of them, `none`, or\n * `some` (an answer that does not cover every output). It only reads what the mint already signed: nothing is\n * swapped again.\n */\n private async restoreOutputs(wallet:Wallet,outputs:OutputData[]):Promise<Proof[]|\"none\"|\"some\"> {\n const recovered=await wallet.mint.restore({outputs:outputs.map(o=>o.blindedMessage)});\n if(recovered.outputs.length===0 && recovered.signatures.length===0)return \"none\";\n if(recovered.outputs.length!==outputs.length || recovered.signatures.length!==outputs.length)return \"some\";\n const keys=(await wallet.mint.getKeys()).keysets;\n const {Amount}=await loadCashu();\n const restored:Proof[]=[];\n for(const output of outputs){\n const index=recovered.outputs.findIndex(o=>o.B_===output.blindedMessage.B_);\n const signature=recovered.signatures[index];\n const key=signature && keys.find(k=>k.id===signature.id);\n if(!signature || !key || signature.id!==output.blindedMessage.id || Amount.from(signature.amount).toString()!==Amount.from(output.blindedMessage.amount).toString())throw new Error(\"Mint restore does not match reviewed outputs\");\n restored.push(output.toProof(signature,key));\n }\n return restored;\n }\n\n private async finishReviewedCashu(review:PaymentReview,prepared:CashuPrepared,keep:Proof[],send:Proof[]):Promise<string> {\n const {getEncodedToken,deserializeSwapPreview}=await loadCashu();\n const token=getEncodedToken({mint:prepared.mint,proofs:send,unit:UNIT});\n const preview=deserializeSwapPreview(prepared.swap);\n const record:StoredPayment={id:review.id,linkId:review.linkId!,kind:\"payment\",direction:\"out\",amount:review.amount,unit:UNIT,memo:review.memo,state:\"pending\",createdAt:review.createdAt,mint:prepared.mint,token,requestId:review.requestId,target:review};\n await this.sealedTransact([STORES.proofs,STORES.payments,STORES.walletTx], {[STORES.proofs]:keep,[STORES.payments]:[record]}, stores=>{\n this.queueReplace(stores[STORES.proofs],prepared.mint,preview.inputs.map(p=>toStored(prepared.mint,p)),keep);\n stores[STORES.payments].put(record);\n stores[STORES.walletTx].put({...walletTx(prepared.mint,\"ecash-out\",review.amount,review.fee),id:review.id});\n });\n prepared.token=token;this.events.onChange();return token;\n }\n\n /**\n * Proof from the mint that a reviewed swap never happened: every input it would spend reads UNSPENT (not PENDING,\n * not SPENT), and the mint signed none of its outputs. Read-only: it asks, and never sends the swap.\n */\n async reviewedCashuNeverSwapped(prepared:CashuPrepared):Promise<boolean> {\n const {OutputData,deserializeSwapPreview}=await loadCashu();\n const preview=deserializeSwapPreview(prepared.swap);\n if(!preview.inputs.length)return false;\n const wallet=await this.wallet(prepared.mint,true);\n const states=await wallet.checkProofsStates(preview.inputs.map(p=>({secret:p.secret,id:p.id})));\n if(states.length!==preview.inputs.length || !states.every(s=>s.state===\"UNSPENT\"))return false;\n const outputs=[...(prepared.swap.keepOutputs??[]),...(prepared.swap.sendOutputs??[])].map(OutputData.deserialize);\n const restored=await wallet.mint.restore({outputs:outputs.map(o=>o.blindedMessage)});\n return restored.signatures.length===0 && restored.outputs.length===0;\n }\n\n /**\n * Whether a reviewed swap can never happen because its ecash was spent by something else: the mint answers that it\n * signed none of its outputs (a successful NUT-09 answer, asked before and after), and reads an input spent, none\n * pending. Read-only. A mint that does not restore cannot say, and the answer is no.\n */\n async reviewedCashuSpentElsewhere(prepared:CashuPrepared):Promise<boolean> {\n const {OutputData,deserializeSwapPreview}=await loadCashu();\n const preview=deserializeSwapPreview(prepared.swap);\n if(!preview.inputs.length)return false;\n const wallet=await this.wallet(prepared.mint,true);\n const outputs=[...(prepared.swap.keepOutputs??[]),...(prepared.swap.sendOutputs??[])].map(OutputData.deserialize);\n if(await this.signedOutputs(wallet,outputs)!==\"none\")return false;\n const states=await wallet.checkProofsStates(preview.inputs.map(p=>({secret:p.secret,id:p.id})));\n if(states.length!==preview.inputs.length || states.some(s=>s.state===\"PENDING\") || !states.some(s=>s.state===\"SPENT\"))return false;\n return await this.signedOutputs(wallet,outputs)===\"none\";\n }\n\n /**\n * Ends a reviewed swap whose ecash was spent elsewhere: the inputs the mint reads spent leave the wallet, the others\n * are free again, and the rest of the wallet's ecash at that mint is checked the same way. Idempotent.\n */\n async dropReviewedCashu(prepared:CashuPrepared):Promise<void> {\n const preview=(await loadCashu()).deserializeSwapPreview(prepared.swap);\n await this.locked(prepared.mint,async()=>{\n const states=await (await this.wallet(prepared.mint)).checkProofsStates(preview.inputs.map(p=>({secret:p.secret,id:p.id})));\n if(states.length!==preview.inputs.length)throw new Error(\"The mint answered for another number of proofs\");\n const spent=new Set(preview.inputs.filter((_,i)=>states[i]?.state===\"SPENT\").map(p=>p.secret));\n await this.sealedTransact([STORES.proofs], {}, stores=>{\n const proofs=stores[STORES.proofs];\n for(const input of preview.inputs){\n const request=proofs.get(input.secret);\n request.onsuccess=()=>{\n const proof:StoredProof|undefined=request.result;\n if(!proof || !proof.reserved || proof.mint!==prepared.mint || proof.C!==input.C)return;\n if(spent.has(input.secret)){proofs.delete(input.secret);return;}\n const {reserved:_released,...free}=proof;\n proofs.put(free);\n };\n }\n });\n });\n await this.recheck(prepared.mint);\n this.events.onChange();\n }\n\n /**\n * A proof of this wallet read spent when nothing here spent it: its ecash is in use somewhere else too. Every other\n * free proof at that mint is asked about once (`checkRestored`), so the balance becomes what the mint still holds\n * instead of one payment after another finding out.\n */\n private async recheck(mint:string):Promise<void> {\n const free=(await this.allProofs()).filter(p=>p.mint===mint && !p.reserved && !p.unchecked);\n if(free.length>0)await this.sealedTransact([STORES.proofs], {[STORES.proofs]:free}, stores=>{ for(const p of free)stores[STORES.proofs].put({...p,unchecked:true} satisfies StoredProof); });\n await this.checkRestored();\n }\n\n /** Gives back the inputs a reviewed swap reserved, once the mint proved it never happened. Idempotent. */\n async releaseReviewedCashu(prepared:CashuPrepared):Promise<void> {\n const preview=(await loadCashu()).deserializeSwapPreview(prepared.swap);\n await this.locked(prepared.mint,async()=>{\n await this.sealedTransact([STORES.proofs], {}, stores=>{\n const proofs=stores[STORES.proofs];\n for(const input of preview.inputs){\n const request=proofs.get(input.secret);\n request.onsuccess=()=>{\n const proof:StoredProof|undefined=request.result;\n if(!proof || !proof.reserved || proof.mint!==prepared.mint || proof.C!==input.C)return;\n const {reserved:_released,...free}=proof;\n proofs.put(free);\n };\n }\n });\n });\n this.events.onChange();\n }\n\n /**\n * Whether the ecash of a reviewed payment came back to this wallet (Take it back, or a refusal). Its proofs then read\n * SPENT at the mint because this wallet redeemed them, not the contact.\n */\n async reviewedCashuTakenBack(id:string):Promise<boolean> {\n return (await wrap<StoredPayment|undefined>((await store(STORES.payments,\"readonly\")).get(id)))?.state===\"reclaimed\";\n }\n\n /**\n * Whether a Take it back of this payment of ours is still written down: its redeem reached the mint, whose answer was\n * lost (`SwapUnsettledError`), and `pollSwaps` settles it. Its ecash reads SPENT meanwhile, by this wallet.\n */\n async cashuTakingBack(id:string):Promise<boolean> {\n return (await this.readSwaps()).some((s)=>s.kind===\"receive\" && !s.released && s.payment?.id===id && s.payment.direction===\"out\");\n }\n\n async reviewedCashuSpent(prepared:CashuPrepared):Promise<boolean> {\n const outputs=(prepared.swap.sendOutputs??[]).map((await loadCashu()).OutputData.deserialize);\n const states=await (await this.wallet(prepared.mint,true)).checkProofsStates(outputs.map(o=>({secret:new TextDecoder().decode(o.secret),id:o.blindedMessage.id})));\n return states.length>0 && states.length===outputs.length && states.every(s=>s.state===\"SPENT\");\n }\n\n /** Reads a token or a payment request without contacting a mint. Nothing here moves money. */\n async inspect(text: string): Promise<CashuInspection | null> {\n const value = text.trim();\n if (!/^(cashu|creq)[AB]/i.test(value)) return null;\n const { decodePaymentRequest, getTokenMetadata } = await loadCashu();\n try {\n if (/^cashu[AB]/i.test(value)) {\n const metadata = getTokenMetadata(value);\n const mint = mintUrlSpelling(metadata.mint);\n return {\n kind: \"token\",\n amount: metadata.amount.toNumber(),\n unit: metadata.unit,\n mint,\n memo: metadata.memo || undefined,\n // Only sat ecash is redeemed here, whatever mint it is from.\n accepted: metadata.unit === UNIT && (this.getKnownMints().includes(mint) || isTestMint(mint)),\n };\n }\n if (/^creq[AB]/i.test(value)) {\n const request = decodePaymentRequest(value);\n return {\n kind: \"request\",\n amount: request.amount === undefined ? null : request.amount.toNumber(),\n unit: request.unit ?? UNIT,\n mints: (request.mints ?? []).map(mintUrlSpelling),\n description: request.description || undefined,\n };\n }\n } catch {\n // not ecash after all\n }\n return null;\n }\n\n /**\n * Redeems a token into fresh proofs of our own. Until this succeeds the sender could still spend it.\n * Test-mint ecash the user pastes adds the test mint; ecash a contact sends in a payment never adds a mint.\n */\n async receiveToken(\n token: string,\n kind: WalletTxKind = \"ecash-in\",\n note?: string,\n { addTestMint = true, payment }: { addTestMint?: boolean; payment?: (amount: number, mint: string) => StoredPayment } = {},\n ): Promise<{ amount: number; mint: string; fee: number }> {\n let mint: string;\n let faceValue: number;\n let unit: string;\n const { getTokenMetadata, serializeSwapPreview } = await loadCashu();\n try {\n const metadata = getTokenMetadata(token);\n unit = metadata.unit;\n // In this wallet's spelling of its mints. The library redeems the token at the same mint in any spelling.\n mint = mintUrlSpelling(metadata.mint);\n faceValue = metadata.amount.toNumber();\n } catch {\n throw new Error(\"That is not a valid ecash token\");\n }\n // A token of another unit is still a token: said as such (its unit named only when it looks like one).\n if (unit !== UNIT) throw ecashUnitError(unit);\n // A mint is a custodian and only the user picks those. The test mint holds nothing of value.\n if (addTestMint && !this.getKnownMints().includes(mint) && isTestMint(mint)) await this.events.onTestMintNeeded(mint);\n // The words name the host only (a contact reads them in a payment's result); `mint` is the whole URL, which a host\n // can offer to add (the CLI's `wallet add-mint`).\n if (!this.getKnownMints().includes(mint)) throw Object.assign(new Error(`Ecash from ${new URL(mint).hostname} is not accepted`), { mint });\n\n return this.locked(mint, async () => {\n // A sender that prepaid the redeem fee put it on top of the amount; what the mint kept is the fee either way.\n const records = (credited: number) => ({ tx: walletTx(mint, kind, credited, Math.max(0, faceValue - credited), note), ...(payment ? { payment: payment(credited, mint) } : {}) });\n // A redeem of this very token that is still written down is finished as it was made: never a second swap for it.\n const written = (await this.swapsAt(mint)).filter((s) => s.kind === \"receive\");\n let swap = written.find((s) => s.token === token);\n // Written down for another payment (another id, another chat) or for none: that payment's, never finished for this one.\n const own = payment?.(0, mint);\n const sameRecord = (a?: StoredPayment, b?: StoredPayment) => a?.id === b?.id && a?.linkId === b?.linkId && a?.direction === b?.direction;\n if (swap && !sameRecord(swap.payment, own)) throw engineError(\"ecashBeingReceived\");\n // Already in the wallet, with only its chat still to be told: nothing to redeem again.\n if (swap?.finished) return { amount: swap.tx?.amount ?? 0, mint, fee: swap.tx?.fee ?? 0 };\n if (!swap) {\n const preview = await (await this.wallet(mint)).prepareSwapToReceive(token);\n if (preview.inputs.some((p) => this.spentTokens.has(`${mint} ${p.secret}`))) throw engineError(\"ecashAlreadySpent\");\n // The same coins in another token (another memo): one coin is one redeem, never another swap counted again.\n const redeeming = new Set(written.flatMap((s) => (swapOf(s).inputs ?? []).map((p) => p.secret)));\n if (preview.inputs.some((p) => redeeming.has(p.secret))) throw engineError(\"ecashBeingReceived\");\n // A mint whose fee to take the token in is all of it would spend the coin and give nothing back: refused before the\n // mint is asked, so the token stays unspent and its sender can still take it back.\n if (preview.amount.toNumber() <= 0) throw engineError(\"ecashFeeTakesAll\", { amount: String(faceValue) });\n // The outputs are for what is left after the mint's fee, so the records are known before the mint is asked.\n swap = { id: swapId(), mint, kind: \"receive\", swap: serializeSwapPreview(preview), createdAt: this.stamp(), token, ...records(preview.amount.toNumber()) };\n await this.putSwap(swap);\n } else if (payment && !this.swapAsk.due(swap.id, Date.now())) {\n // A contact's payment sent already, and the mint did not take it: asked again at the wallet's own pace\n // (`pollSwaps`), not each time its payer sends the same token again.\n throw new SwapUnsettledError(swap);\n }\n const sent = swap;\n const { keep } = await this.completeSwap(sent).catch((error: unknown) => {\n if (error instanceof SwapUnsettledError) this.swapAsk.missed(sent.id, Date.now());\n throw error;\n });\n const credited = sats(keep);\n // What the mint signed is what is credited.\n if (swap.tx && credited !== swap.tx.amount) swap = { ...swap, ...records(credited), tx: { ...records(credited).tx, id: swap.tx.id, timestamp: swap.tx.timestamp } };\n await this.finishSwap(swap, keep, [], false);\n this.events.onChange();\n // `fee`: what the mint kept of the token's face value for taking it in.\n return { amount: credited, mint, fee: Math.max(0, faceValue - credited) };\n });\n }\n\n // -- swaps: written down, then finished ------------------------------------------\n\n /**\n * Splits `amount`, with the fee its receiver will pay to redeem it, out of `proofs`. Coins that add up exactly need\n * no mint, as long as their token fits in a payment frame: a wallet of many small coins can add up exactly in\n * hundreds of them, a token the contact's app drops unread. Otherwise it is a swap, which sends a few coins: written\n * down, with its inputs reserved, before the mint is asked. The caller stores the result in one transaction: `inputs`\n * out, `keep` in, `send` where it goes, and `swap` deleted. Runs under the mint's lock.\n */\n private async split(mint: string, amount: number, proofs: StoredProof[]): Promise<{ inputs: StoredProof[]; keep: Proof[]; send: Proof[]; swap?: PendingSwap }> {\n const wallet = await this.wallet(mint);\n const { getEncodedToken, serializeSwapPreview } = await loadCashu();\n const among =(chosen: { secret: string }[]) => { const secrets = new Set(chosen.map((p) => p.secret)); return proofs.filter((p) => secrets.has(p.secret)); };\n try {\n const { send } = wallet.sendOffline(amount, asProofLike(proofs), { includeFees: true, exactMatch: true });\n if (send.length > 0 && sats(send) === amount + wallet.getFeesForProofs(send).toNumber() && inOneFrame(getEncodedToken, mint)(send)) return { inputs: among(send), keep: [], send };\n } catch {\n // no exact coins: the mint makes them\n }\n const coins = sendCoins(wallet, amount);\n const preview = coins\n ? await wallet.prepareSwapToSend(coins.reduce((sum, coin) => sum + coin, 0), asProofLike(proofs), {}, { send: { type: \"random\", denominations: coins } })\n : await wallet.prepareSwapToSend(amount, asProofLike(proofs), { includeFees: true });\n const swap: PendingSwap = { id: swapId(), mint, kind: \"send\", swap: serializeSwapPreview(preview), createdAt: this.stamp() };\n const inputs = among(preview.inputs);\n // Written down before the mint sees the proofs: from here on they may be spent, and only these outputs replace them.\n await this.sealedTransact([STORES.proofs, STORES.swaps], { [STORES.proofs]: inputs, [STORES.swaps]: [swap] }, (stores) => {\n for (const p of inputs) stores[STORES.proofs].put({ ...p, reserved: true } satisfies StoredProof);\n stores[STORES.swaps].put(swap);\n });\n const { keep, send } = await this.completeSwap(swap);\n return { inputs, keep, send, swap };\n }\n\n /**\n * Sends a written-down swap to the mint: always the saved one, so a second try asks for the same outputs. When the\n * answer is missed the mint is asked what it did, and its word decides: the outputs it signed are the result, as the\n * answer would have been; a swap it says it never made is undone and the failure is thrown; and for as long as the\n * swap stays written down nothing is known to have failed, whatever the mint's words were (`SwapUnsettledError`):\n * `pollSwaps` settles it. A redeem refused for the keyset of its outputs is made again on the mint's keyset now and\n * sent once more (`renewedReceive`); `renew` false: it already was. Runs under the mint's lock.\n */\n private async completeSwap(swap: PendingSwap, renew = true): Promise<{ keep: Proof[]; send: Proof[] }> {\n const { deserializeSwapPreview } = await loadCashu();\n try {\n // The saved preview carries only the swap's own outputs: what comes back is exactly what the mint signed.\n return await (await this.wallet(swap.mint)).completeSwap(deserializeSwapPreview(swapOf(swap)));\n } catch (error) {\n const renewed = renew ? await this.renewedReceive(swap, error).catch(() => undefined) : undefined;\n if (renewed) return this.completeSwap(renewed, false);\n // A refusal of the first request ever made for this swap: no other request of it can be on its way.\n const refused = mintRefused(error) && swap.attemptEndedAt === undefined;\n const ended: PendingSwap = { ...swap, attemptEndedAt: this.stamp() };\n await this.putSwap(ended).catch(() => {});\n const outcome = await this.swapOutcome(ended, refused).catch((): SwapOutcome => ({ state: \"open\" }));\n if (outcome.state === \"done\") return outcome;\n if (outcome.state === \"never\" && outcome.final) {\n await this.dropSwap(ended, outcome.gone);\n if (swap.kind === \"receive\") this.rememberSpent(swap.mint, outcome.gone);\n // Said as what it is: the mint's own words for it vary from mint to mint, and cashu-ts' for a keyset are its own.\n if (outcome.gone.size > 0) throw Object.assign(engineError(\"ecashAlreadySpent\"), { cause: error });\n throw swap.kind === \"receive\" && keysetRefused(error) ? Object.assign(new Error(MINT_DID_NOT_CONFIRM), { cause: error }) : error;\n }\n this.swapsAgainIn(SWAP_POLL_MS);\n // What it holds and that it is open show at once.\n this.events.onChange();\n throw new SwapUnsettledError(ended, error);\n }\n }\n\n /**\n * A redeem the mint refused for the keyset of its outputs (one it retired, or does not know, since they were made):\n * no request with those outputs is ever signed. While the mint reads every coin of its token unspent, nothing of it\n * happened, and it is written down again with new outputs on the keyset the mint signs with now (cashu-ts reloaded\n * the mint's keysets with the refusal), as `settleQuote` does for an invoice. Undefined when it is not that case.\n * Only asks: the caller sends it. Runs under the mint's lock.\n */\n private async renewedReceive(swap: PendingSwap, error: unknown): Promise<PendingSwap | undefined> {\n if (swap.kind !== \"receive\" || swap.released || !keysetRefused(error)) return undefined;\n // The keysets could not be reloaded with the refusal: loaded anew, so the new outputs are on the mint's keyset now.\n if ((error as { repaired?: boolean }).repaired === false) this.wallets.delete(swap.mint);\n const wallet = await this.wallet(swap.mint);\n const { deserializeSwapPreview, serializeSwapPreview } = await loadCashu();\n const { inputs } = deserializeSwapPreview(swapOf(swap));\n const states = await wallet.checkProofsStates(inputs.map((p) => ({ secret: p.secret, id: p.id })));\n if (states.length !== inputs.length || states.some((s) => s.state !== \"UNSPENT\")) return undefined;\n // The same coins, so the same fee: what was written down to credit stays right.\n const preview = await wallet.prepareSwapToReceive(swap.token ?? inputs);\n const { attemptEndedAt: _ended, askAt: _ask, stuck: _stuck, ...rest } = swap;\n // Written down before the mint is asked, in place of the outputs it refused: the only request of these is the next.\n const renewed: PendingSwap = { ...rest, swap: serializeSwapPreview(preview) };\n await this.putSwap(renewed);\n return renewed;\n }\n\n /**\n * Sends a redeem `renewedReceive` wrote down again, after the call that made it was over (`pollSwaps`): stored and its\n * chat told as any redeem settled late; let go by `completeSwap` on the mint's word (spent, refused once more), and\n * its chat told that; still written down with no answer, asked about again.\n */\n private async sendRenewed(swap: PendingSwap, later: (ms: number) => void): Promise<void> {\n try {\n const { keep } = await this.completeSwap(swap, false);\n if (await this.finishSwap(swap, keep, [], true)) {\n const told = await this.tellSwap(swap, true);\n if (swap.payment && told) await committed((await store(STORES.swaps, \"readwrite\")).delete(swap.id));\n else if (swap.payment) later(SWAP_POLL_MS);\n this.events.onChange();\n }\n } catch {\n if ((await this.swapsAt(swap.mint)).some((s) => s.id === swap.id)) { later(SWAP_POLL_MS); return; }\n await this.tellSwap(swap, false);\n this.events.onChange();\n }\n }\n\n /**\n * Asks the mint where a written-down swap stands. It only asks: nothing is sent again, nothing is stored.\n * `refused`: the mint refused the only request ever made for this swap, so no request of it is still on its way.\n * Throws when the mint cannot be asked, or answers with an error: only its answers count.\n */\n private async swapOutcome(swap: PendingSwap, refused = false): Promise<SwapOutcome> {\n const wallet = await this.wallet(swap.mint);\n const { OutputData } = await loadCashu();\n const saved = swapOf(swap);\n const keep =(saved.keepOutputs ?? []).map(OutputData.deserialize);\n const send = (saved.sendOutputs ?? []).map(OutputData.deserialize);\n const signed = async () => {\n const proofs = await this.signedOutputs(wallet, [...keep, ...send]);\n return Array.isArray(proofs) ? { state: \"done\" as const, keep: proofs.slice(0, keep.length), send: proofs.slice(keep.length) } : proofs;\n };\n const first = await signed();\n if (first && first !== \"none\") return first;\n const states = await wallet.checkProofsStates(saved.inputs.map((p) => ({ secret: p.secret, id: p.id })));\n if (states.length !== saved.inputs.length) throw new Error(\"The mint answered for another number of proofs\");\n if (states.some((s) => s.state === \"PENDING\")) {\n // A redeem's inputs are its sender's, held by a payment of theirs: refused, this redeem can never reach the mint.\n if (swap.kind === \"receive\" && refused) return { state: \"never\", gone: new Set(), final: true };\n return { state: \"open\", pending: true };\n }\n const gone = new Set(saved.inputs.filter((_, i) => states[i]?.state === \"SPENT\").map((p) => p.secret));\n if (gone.size > 0) {\n // Asked once more: the swap may have gone through between the two questions.\n const second = await signed();\n if (second && second !== \"none\") return second;\n // The mint answered that it signed none of these outputs: something else spent the inputs.\n if (second === \"none\" || refused) return { state: \"never\", gone, final: true };\n // Spent, and the mint cannot say by what: this swap may have done it. It stays written down.\n return { state: \"open\", slow: true };\n }\n // Unspent and unsigned: it never happened. For good after a refusal; otherwise once no request can still arrive.\n if (refused) return { state: \"never\", gone, final: true };\n if (this.swapOverdue(swap)) return { state: \"never\", gone, final: false };\n return { state: \"open\", idle: !!first };\n }\n\n /**\n * Stores what a swap brought, in one transaction that reads the swap first: a swap still written down was never\n * stored, and one stored is never stored again, whoever else works on this database. A redeem brings its ecash with\n * its history line and its payment record. A split finished here was not finished by its caller (the payment it was\n * for is over): everything it made is the wallet's. `late`: after the call that made it was over; a swap with a\n * payment then stays, marked `finished`, until the chat has been told (`tellSwap`). Returns whether it stored.\n */\n private async finishSwap(swap: PendingSwap, keep: Proof[], send: Proof[], late: boolean): Promise<boolean> {\n // A redeem's inputs were never the wallet's: only a split looks its own up.\n const inputs = (await this.proofsOf(swap.kind === \"send\" ? swapOf(swap).inputs.map((p) => p.secret) : [])).filter((p) => p.mint === swap.mint);\n const lost = swap.kind === \"send\" ? swapOf(swap).inputs.reduce((sum, p) => sum + Number(p.amount), 0) - sats(keep) - sats(send) : 0;\n let stored = false;\n await this.sealedTransact([STORES.proofs, STORES.swaps, STORES.walletTx, ...(swap.payment ? [STORES.payments] : [])], { [STORES.proofs]: [...keep, ...send], [STORES.payments]: swap.payment ? [swap.payment] : [] }, (stores) => {\n const current = stores[STORES.swaps].get(swap.id);\n current.onsuccess = () => {\n const kept: PendingSwap | undefined = current.result;\n if (!kept || kept.finished) return;\n stored = true;\n for (const p of inputs) stores[STORES.proofs].delete(p.secret);\n // From a restored copy, what the swap made is as old as the copy: the mint is asked which of it is unspent.\n for (const p of [...keep, ...send]) stores[STORES.proofs].put({ ...toStored(swap.mint, p), ...(swap.restored ? { unchecked: true } : {}) } satisfies StoredProof);\n if (swap.tx) stores[STORES.walletTx].put(swap.tx);\n // What the mint kept for a split whose payment was never made. In the history, never silent.\n if (lost > 0) stores[STORES.walletTx].put({ ...walletTx(swap.mint, \"fee\", 0, lost, \"A payment was not sent\"), id: swap.id });\n if (swap.payment) stores[STORES.payments].put(swap.payment);\n if (late && swap.payment) stores[STORES.swaps].put({ ...kept, finished: true } satisfies PendingSwap);\n else stores[STORES.swaps].delete(swap.id);\n };\n });\n if (stored && swap.restored) void this.checkRestored();\n return stored;\n }\n\n /**\n * The mint never made this swap. The inputs it held are free again, less any the mint reads spent. `watch`: it is\n * only overdue, so it stays written down, marked `released`, and is asked about for a while longer: should the mint\n * have made it after all, what it made is still recovered.\n */\n private async dropSwap(swap: PendingSwap, gone: Set<string>, watch = false): Promise<void> {\n const inputs = swap.kind === \"send\" && !swap.released ? await this.storedInputs(swap) : [];\n if (gone.size > 0 && inputs.length > 0) console.warn(`[wallet] ${gone.size} proofs of a swap at ${swap.mint} that never happened are spent`);\n await this.sealedTransact([STORES.proofs, STORES.swaps], { [STORES.proofs]: inputs, [STORES.swaps]: [swap] }, (stores) => {\n for (const p of inputs) {\n if (gone.has(p.secret)) stores[STORES.proofs].delete(p.secret);\n else { const { reserved: _released, ...free } = p; stores[STORES.proofs].put(free satisfies StoredProof); }\n }\n if (watch) stores[STORES.swaps].put({ ...swap, released: true } satisfies PendingSwap);\n else stores[STORES.swaps].delete(swap.id);\n });\n // Ecash of this wallet spent by something else: the rest of what it holds at that mint is asked about too.\n if (gone.size > 0 && inputs.length > 0) void this.recheck(swap.mint).catch(() => {});\n }\n\n private rememberSpent(mint: string, secrets: Set<string>): void {\n for (const secret of secrets) {\n const key = `${mint} ${secret}`;\n this.spentTokens.delete(key);\n this.spentTokens.add(key);\n }\n for (const oldest of this.spentTokens) {\n if (this.spentTokens.size <= SPENT_KEPT) break;\n this.spentTokens.delete(oldest);\n }\n }\n\n /** The proofs a split reserved, as they are stored now. */\n private async storedInputs(swap: PendingSwap): Promise<StoredProof[]> {\n return (await this.proofsOf(swapOf(swap).inputs.map((p) => p.secret))).filter((p) => p.mint === swap.mint && p.reserved);\n }\n\n private async swapsAt(mint: string): Promise<PendingSwap[]> {\n return (await this.readSwaps()).filter((s) => s.mint === mint);\n }\n\n /** Says what became of a swap to whoever follows it (the chat its payment is in), and waits for it to be taken in. */\n private async tellSwap(swap: PendingSwap, done: boolean): Promise<boolean> {\n try { await this.events.onSwapSettled?.(swap, done); return true; } catch { return false; }\n }\n\n private swapsAgainIn(ms: number): void {\n if (this.stopped) return;\n if (this.swapTimer && this.swapTimerAt <= Date.now() + ms) return;\n if (this.swapTimer) clearTimeout(this.swapTimer);\n this.swapTimerAt = Date.now() + ms;\n this.swapTimer = setTimeout(() => void this.pollSwaps(), ms);\n }\n\n /**\n * Swaps still written down: the app closed while the mint was being asked, or the mint did not answer. Each mint is\n * asked where its own stand, one swap at a time under its lock. A swap it made is stored as its answer would have been; one it says it\n * never made is undone; one that is only overdue gives its inputs back and stays watched; one it cannot speak for\n * is asked about again. `mints`: only these mints', once, now.\n */\n /** Asks these mints about their open swaps now (before a wallet's removal is shown or refused). */\n settleSwaps(mints: readonly string[]): Promise<void> {\n return this.pollSwaps(mints);\n }\n\n /**\n * A contact's ecash for this request of ours is being redeemed: written down, and the mint has not said how it ended,\n * or it has and its chat was not told yet. Released: the mint never made it in time, and the ecash went back. Stuck\n * past its watch hour (spent, and a mint that cannot say by what): kept to be asked about, but no longer expected to\n * pay the request, which another member may pay.\n */\n async redeemingFor(requestId: string): Promise<boolean> {\n const open = await this.readSwaps();\n return open.some((s) => s.kind === \"receive\" && !s.released && s.payment?.requestId === requestId\n && !(s.stuck && this.pastWatch(s)));\n }\n\n private async pollSwaps(mints?: readonly string[]): Promise<void> {\n if (!mints) {\n if (this.swapTimer) clearTimeout(this.swapTimer);\n this.swapTimer = null;\n if (this.stopped) return;\n }\n const open = (await this.readSwaps()).filter((s) => !mints || mints.includes(s.mint));\n if (!mints) this.swapAsk.keepOnly(new Set(open.map((s) => s.id)));\n let again = 0;\n const later = (ms: number) => { again = again ? Math.min(again, ms) : ms; };\n // One swap at a time under its mint's lock, read again inside it: the user's own payments there go in between.\n for (const { id, mint } of open) {\n // A mint that has not answered for a while is asked less and less often; a wallet's removal asks it now.\n if (!mints && !this.swapAsk.due(id, Date.now())) { later(this.swapAsk.at(id, Date.now()) - Date.now()); continue; }\n await this.locked(mint, async () => {\n let swap = await openRow(STORES.swaps, await wrap<PendingSwap | undefined>((await store(STORES.swaps, \"readonly\")).get(id)));\n if (!swap) return;\n try {\n // Stored already, and the app closed before its chat was told: told now.\n // It goes only once the chat took it in: until then it is told again, every round and at every start.\n if (swap.finished) {\n if (await this.tellSwap(swap, true)) await committed((await store(STORES.swaps, \"readwrite\")).delete(swap.id));\n else later(SWAP_POLL_MS);\n return;\n }\n // Asked many times already with no way of knowing: asked again only when its time comes.\n if (swap.askAt && Date.now() < swap.askAt && !mints) { later(swap.askAt - Date.now()); return; }\n // Found written down with no answer on record: whatever sent it is gone. The mint gets time to finish.\n if (swap.attemptEndedAt === undefined) {\n swap = { ...swap, attemptEndedAt: this.stamp() };\n await this.putSwap(swap);\n }\n let outcome = await this.swapOutcome(swap);\n // A redeem whose token the mint reads unspent, with nothing signed, never happened however long the app was\n // closed, and still can: sent again below, never let go while the token is good (only the mint's word ends it).\n if (outcome.state === \"never\" && !outcome.final && swap.kind === \"receive\" && !swap.released) outcome = { state: \"open\", idle: true };\n // The mint answered. A redeem sent again below keeps its pace until the mint takes it: a mint that reads the\n // token but never takes the swap is not sent it every 30 s for as long as the token is good.\n if (!(outcome.state === \"open\" && outcome.idle && swap.kind === \"receive\" && !swap.released)) this.swapAsk.forget(id);\n if (outcome.state === \"open\") {\n // Its inputs went back, and an hour on the mint still cannot say more: nothing of it is held here.\n if (swap.released && this.pastWatch(swap)) { await this.dropSwap(swap, new Set()); return; }\n if (outcome.slow) {\n // No way of knowing what the mint signed: kept, and asked about less and less often.\n const stuck = (swap.stuck ?? 0) + 1;\n const wait = stuck <= 6 ? SWAP_SLOW_POLL_MS : stuck <= 30 ? 3_600_000 : 86_400_000;\n await this.putSwap({ ...swap, stuck, askAt: Date.now() + wait } satisfies PendingSwap);\n if (stuck === 1) this.events.onChange();\n later(wait);\n } else if (outcome.idle && swap.kind === \"receive\" && !swap.released) {\n // The mint answers, and has done nothing with this redeem: it is sent again as it was written down.\n // Whichever request the mint acts on signs the same outputs.\n const { deserializeSwapPreview } = await loadCashu();\n try {\n const { keep } = await (await this.wallet(mint)).completeSwap(deserializeSwapPreview(swapOf(swap)));\n this.swapAsk.forget(id);\n if (await this.finishSwap(swap, keep, [], true)) {\n const told = await this.tellSwap(swap, true);\n if (swap.payment && told) await committed((await store(STORES.swaps, \"readwrite\")).delete(swap.id));\n else if (swap.payment) later(SWAP_POLL_MS);\n this.events.onChange();\n }\n } catch (error) {\n // Refused for the keyset of its outputs, the token unspent: made again on the mint's keyset now.\n const renewed = await this.renewedReceive(swap, error).catch(() => undefined);\n if (renewed) { await this.sendRenewed(renewed, later); return; }\n swap = { ...swap, attemptEndedAt: this.stamp() };\n await this.putSwap(swap);\n // Refused: the mint's word on it, asked once more, ends it. Anything else is tried again.\n const refusal = mintRefused(error) ?await this.swapOutcome(swap, true).catch(() => undefined) : undefined;\n if (refusal?.state === \"done\") {\n if (await this.finishSwap(swap, refusal.keep, refusal.send, true)) {\n const told = await this.tellSwap(swap, true);\n if (swap.payment && told) await committed((await store(STORES.swaps, \"readwrite\")).delete(swap.id));\n }\n this.events.onChange();\n } else if (refusal?.state === \"never\") {\n await this.dropSwap(swap, refusal.gone);\n await this.tellSwap(swap, false);\n this.events.onChange();\n }\n // Not taken, and the mint did not refuse it: from 30 s, twice as late each time (each send moves when\n // it is overdue, so that cannot pace it).\n else later(this.swapAsk.missed(id, Date.now()));\n }\n } else if (outcome.pending && swap.kind === \"receive\" && !swap.released && this.swapOverdue(swap)) {\n // No request of it can reach the mint any more, and its sender's ecash is still held by a payment of\n // theirs: asked now and then, and let go after its hour.\n if (!this.pastWatch(swap)) {\n await this.putSwap({ ...swap, askAt: Date.now() + SWAP_SLOW_POLL_MS } satisfies PendingSwap);\n later(SWAP_SLOW_POLL_MS);\n } else {\n await this.dropSwap(swap, new Set());\n await this.tellSwap(swap, false);\n this.events.onChange();\n }\n } else later(swap.released ? SWAP_SLOW_POLL_MS : SWAP_POLL_MS);\n return;\n }\n if (outcome.state === \"done\") {\n if (await this.finishSwap(swap, outcome.keep, outcome.send, true)) {\n const told = await this.tellSwap(swap, true);\n // One with a payment stays, marked finished, until its chat took it in.\n if (swap.payment && told) await committed((await store(STORES.swaps, \"readwrite\")).delete(swap.id));\n else if (swap.payment) later(SWAP_POLL_MS);\n }\n } else if (swap.released) {\n // Its inputs went back long ago. Watched until they are spent by something else, or for an hour.\n if (outcome.final || this.pastWatch(swap)) await this.dropSwap(swap, outcome.gone);\n else later(SWAP_SLOW_POLL_MS);\n return;\n } else {\n await this.dropSwap(swap, outcome.gone, !outcome.final);\n await this.tellSwap(swap, false);\n if (!outcome.final) later(SWAP_SLOW_POLL_MS);\n }\n this.events.onChange();\n } catch {\n // Mint unreachable, or its answer was an error: asked again on the next round. One that holds nothing\n // any more is not asked about past its hour.\n if (swap.released && this.pastWatch(swap)) await this.dropSwap(swap, new Set()).catch(() => {});\n else if (swap.released) later(SWAP_SLOW_POLL_MS);\n else {\n // Every 30 s while a request may still reach the mint, then less and less often, as melts are.\n later(this.swapAsk.missed(id, Date.now(), !this.swapOverdue(swap)));\n }\n }\n }).catch(() => { later(SWAP_POLL_MS); });\n }\n if (again && !mints) this.swapsAgainIn(again);\n }\n\n // -- Lightning out -----------------------------------------------------------\n\n /**\n * What paying this invoice would cost, from the first mint that can afford it. `chosen`: the sats the person typed for\n * an invoice with no amount, the only way one is paid (WISP 203); only a mint that says it takes one is asked.\n */\n async quoteInvoice(invoice: string, network?: WalletNetwork, chosen?: number): Promise<{ quote: string; mint: string; amount: number; feeReserve: number }> {\n let lastError: unknown = new Error(\"Add a mint in Settings first\");\n let mints = this.getMints(network);\n /** The most any mint asked could pay with its fee on top: a Max comes down to it. */\n let room = 0;\n const decoded = decodeBolt11(invoice);\n if (!decoded) throw new Error(\"That is not an invoice this wallet can pay\");\n if (decoded.amountSat === null && chosen === undefined) throw new Error(\"Invoices without an amount are not supported\");\n // An invoice that names its amount is paid for that amount, whatever is asked.\n if (decoded.amountSat !== null && chosen !== undefined) throw new Error(MINT_QUOTE_MISMATCH);\n if (chosen !== undefined) assertAmount(chosen);\n const expected = decoded.amountSat ?? chosen!;\n // A Bitcoin invoice may be real money: test sats pay one only through a mint whose Lightning is known to be fake.\n if (decoded.network === \"bitcoin\" && mints.some((mint) => mintNetwork(mint) === \"testnet\")) {\n mints = mints.filter((mint) => mintNetwork(mint) === \"mainnet\" || fakesLightning(mint));\n if (!mints.length) throw new Error(BITCOIN_INVOICE_ON_TESTNET);\n }\n if (chosen !== undefined && mints.length) lastError = engineError(\"mintsNoAnyAmount\");\n /** The failure of a mint that holds enough for the invoice: said over a later mint's \"Not enough sats\". */\n let failedHolding: unknown;\n for (const mint of mints) {\n try {\n const wallet = await this.wallet(mint);\n // cashu-ts leaves the amount out of the request for a mint that does not say it takes one: never asked here.\n if (chosen !== undefined && !wallet.getMintInfo().supportsAmountless(\"bolt11\", UNIT)) continue;\n const quote = chosen === undefined ? await wallet.createMeltQuoteBolt11(invoice.trim()) : await wallet.createMeltQuoteBolt11(invoice.trim(), chosen * 1000);\n const amount = quote.amount.toNumber();\n const feeReserve = quote.fee_reserve.toNumber();\n // The amount shown is the invoice's, or the one chosen: a quote for another invoice or amount is never paid.\n if (quoteMismatch(quote, decoded.invoice, expected)) throw new Error(MINT_QUOTE_MISMATCH);\n // The coins the melt spends are paid for too, at a mint that charges for each coin it takes in.\n const proofs = await this.proofsAt(mint);\n const outlay = outlayAt(wallet, proofs, amount + feeReserve, inOneFrame((await loadCashu()).getEncodedToken, mint));\n if (outlay === undefined) {\n room = Math.max(room, roomAt(wallet, proofs, feeReserve));\n lastError = room > 0 ? engineError(\"notEnoughForFee\", { amount: room }) : engineError(\"notEnoughSats\");\n continue;\n }\n // The most it can cost: the reserve, and what the split before the melt and the melt itself pay for their coins.\n const fee = outlay - amount;\n this.shownQuotes.set(quote.quote, { request: decoded.invoice, amount, feeReserve: fee });\n return { quote: quote.quote, mint, amount, feeReserve: fee };\n } catch (error) {\n // A mint that failed (\"internal error\", a closed connection) is named, with what to do; its words kept last.\n lastError = mintFailed(error) ? Object.assign(engineError(\"mintFailedQuote\", { host: new URL(mint).host, reason: mintReason(error) }), { cause: error }) : error;\n if (failedHolding === undefined && total(await this.proofsAt(mint)) >= expected) failedHolding = lastError;\n }\n }\n const said = failedHolding ?? lastError;\n throw said instanceof Error ? said : new Error(String(said));\n }\n\n /**\n * Pays a melt quote. True once paid; false while the mint holds the payment pending, in which case its\n * proofs stay reserved and the wallet keeps asking until the mint settles it (`onMeltResolved`).\n * Throws only when the sats never left the wallet or are known to be back in it, or when the split before the payment\n * has no answer yet (`SwapUnsettledError`): the payment was not made, and the split is settled by `pollSwaps`.\n */\n async payQuote(quoteId: string, mint: string, note?: string, paymentId?: string): Promise<boolean> {\n try {\n const outcome = await this.locked(mint, () => this.melt(quoteId, mint, note, paymentId));\n if (outcome === \"unpaid\") throw new Error(`The Lightning payment did not go through. ${backInWallet(this.takeFailedFee(quoteId))}`);\n if (outcome === \"pending\") void this.pollMelts();\n return outcome === \"paid\";\n } finally {\n this.events.onChange();\n }\n }\n\n private async melt(quoteId: string, mint: string, note?: string, paymentId?: string): Promise<MeltOutcome> {\n const wallet = await this.wallet(mint);\n const { MeltChangeError, OutputData, getEncodedToken } = await loadCashu();\n const quote = await wallet.checkMeltQuoteBolt11(quoteId);\n const inFlight = await this.readMelts();\n if (inFlight.some((m) => m.quote === quote.quote || m.request === quote.request)) throw new Error(\"This invoice is already being paid\");\n // Read again from the mint: it must still be the invoice and amount shown, for no more fee than shown, the coins'\n // own fees included, out of the coins held now.\n const shown = this.shownQuotes.get(quoteId);\n const needed = quote.amount.toNumber() + quote.fee_reserve.toNumber();\n const proofs = await this.proofsAt(mint);\n const outlay = outlayAt(wallet, proofs, needed, inOneFrame(getEncodedToken, mint));\n if (!shown || quote.quote !== quoteId || quoteMismatch(quote, shown.request, shown.amount) || (outlay ?? needed) > shown.amount + shown.feeReserve) {\n throw new Error(MINT_QUOTE_MISMATCH);\n }\n // Coins another payment took since the quote was shown: said as the quote would have said it.\n if (outlay === undefined) {\n const room = roomAt(wallet, proofs, quote.fee_reserve.toNumber());\n throw room > 0 ? engineError(\"notEnoughForFee\", { amount: room }) : engineError(\"notEnoughSats\");\n }\n const { inputs, keep, send, swap } = await this.split(mint, needed, proofs);\n let preview: MeltPreview<MeltQuoteBolt11Response>;\n try {\n preview = await wallet.prepareMelt(\"bolt11\", quote, send);\n } catch (error) {\n // Nothing reached the melt: what the swap returned is all spendable.\n await this.sealedTransact([STORES.proofs, STORES.swaps], { [STORES.proofs]: [...keep, ...send] }, (stores) => {\n this.queueReplace(stores[STORES.proofs], mint, inputs, [...keep, ...send]);\n if (swap) stores[STORES.swaps].delete(swap.id);\n });\n throw error;\n }\n\n const melt: PendingMelt = {\n quote: quote.quote,\n mint,\n request: quote.request,\n amount: quote.amount.toNumber(),\n secrets: send.map((p) => p.secret),\n outlay: total(inputs) - sats(keep),\n outputs: preview.outputData.map((o) => OutputData.serialize(o)),\n note: note?.slice(0, 140),\n paymentId,\n createdAt: this.stamp(),\n };\n // Written down before the mint sees the proofs: from here on they may be spent, or come back.\n await this.sealedTransact([STORES.proofs, STORES.melts, STORES.swaps], { [STORES.proofs]: [...keep, ...send], [STORES.melts]: [melt] }, (stores) => {\n this.queueReplace(stores[STORES.proofs], mint, inputs, keep);\n for (const p of send) stores[STORES.proofs].put(toStored(mint, p, true));\n stores[STORES.melts].put(melt);\n if (swap) stores[STORES.swaps].delete(swap.id);\n });\n this.shownQuotes.delete(quoteId);\n // Not paid: the review that showed it is still the invoice and amount shown, and Pay on it again pays (the refusal\n // says it is safe to try again), checked against the mint's quote as the first time.\n const unpaid = () => { this.shownQuotes.set(quoteId, shown); };\n\n let result: MeltProofsResponse<MeltQuoteBolt11Response>;\n try {\n result = await wallet.completeMelt(preview);\n } catch (error) {\n // A dropped connection or a gateway timeout says nothing: the payment may still be going through.\n if (!mintRefused(error) && !(error instanceof MeltChangeError)) return \"pending\";\n // The mint answered (a refusal), or took the proofs and only the change failed: its word decides.\n const outcome = await this.settleMelt(melt, true).catch((): MeltOutcome => \"pending\");\n if (outcome === \"unpaid\") {\n unpaid();\n const lost = this.takeFailedFee(melt.quote);\n // Its ecash was spent somewhere else: said in plain words, whatever the mint's own were.\n if (this.spentAway.delete(melt.quote)) throw Object.assign(engineError(\"ecashAlreadySpent\"), { cause: error });\n // The mint's refusal (\"Invoice already paid\") stays what the person reads, with what it cost them.\n if (lost > 0) throw Object.assign(new Error(`${error instanceof Error ? error.message : String(error)} ${backInWallet(lost)}`), { cause: error });\n // Refused, the quote unpaid and every proof back unspent: nothing left the wallet. Said in the app's words, the\n // mint's own kept as the reason (and in the text, where \"already paid\" is read: InvoiceBubble.tsx).\n throw Object.assign(engineError(\"lightningRefused\", { reason: mintReason(error) }), { cause: error });\n }\n return outcome;\n }\n if (result.quote.state === \"PAID\") {\n await this.finishMelt(melt, result.change);\n return \"paid\";\n }\n const outcome = await this.settleMelt(melt, true).catch((): MeltOutcome => \"pending\");\n if (outcome === \"unpaid\") unpaid();\n return outcome;\n }\n\n /**\n * Whether a Lightning payment of this invoice is written down as in flight. A melt is written before the mint sees\n * its proofs, and `pollMelts` settles and reports it: an invoice with none never reached the mint's melt, or is done.\n */\n async meltInFlight(invoice: string): Promise<boolean> {\n const melts = await this.readMelts();\n return melts.some((m) => m.request === invoice);\n }\n\n /**\n * Lightning payments left pending, asked about again until the mint settles each one: every MELT_POLL_MS while its\n * request may still land, then each at its own pace, twice as late every time up to MELT_SLOW_POLL_MS.\n */\n private async pollMelts(): Promise<void> {\n if (this.meltTimer) clearTimeout(this.meltTimer);\n this.meltTimer = null;\n if (this.stopped) return;\n const melts = await this.readMelts();\n // Mints that could not be loaded, or did not answer a melt's read, in this round: their other melts wait for the next.\n const down = new Set<string>();\n // Each mint's melts in turn (its lock serializes them anyway), the mints side by side: one that does not answer\n // holds only its own melts, not those of the mints after it.\n const byMint = new Map<string, PendingMelt[]>();\n for (const melt of melts) {\n const atMint = byMint.get(melt.mint);\n if (atMint) atMint.push(melt);\n else byMint.set(melt.mint, [melt]);\n }\n await Promise.allSettled([...byMint.values()].map(async (atMint) => {\n for (const melt of atMint) await this.pollMelt(melt, down);\n }));\n\n const remaining = new Set((await this.readMelts()).map((m) => m.quote));\n this.meltAsk.keepOnly(remaining);\n if (remaining.size === 0 || this.stopped) return;\n // A melt written down since this round began has no pace yet: it is asked at once.\n const next = Math.min(...[...remaining].map((quote) => this.meltAsk.at(quote, 0)));\n if (this.meltTimer) clearTimeout(this.meltTimer);\n this.meltTimer = setTimeout(() => void this.pollMelts(), Math.max(0, next - Date.now()));\n }\n\n /** One pending melt of a `pollMelts` round, if it is due: asked under its mint's lock, unless its mint is `down`. */\n private async pollMelt(melt: PendingMelt, down: Set<string>): Promise<void> {\n if (!this.meltAsk.due(melt.quote, Date.now())) return;\n try {\n // Its mint could not be loaded, or did not answer, for another melt just now: this one waits as that one does.\n if (down.has(melt.mint)) throw new Error(\"mint down\");\n try { await this.wallet(melt.mint); }\n catch (error) { down.add(melt.mint); throw error; }\n const outcome = await this.locked(melt.mint, async () => {\n // It may have been settled while this waited for the lock.\n const current = await openRow(STORES.melts, await wrap<PendingMelt | undefined>((await store(STORES.melts, \"readonly\")).get(melt.quote)));\n return current ? this.settleMelt(current) : null;\n });\n if (outcome === \"paid\" || outcome === \"unpaid\") {\n this.takeFailedFee(melt.quote);\n this.spentAway.delete(melt.quote);\n this.events.onMeltResolved(melt, outcome === \"paid\");\n this.events.onChange();\n }\n } catch (error) {\n // No answer at all (its read timed out, or the connection failed): each of the mint's other melts would wait as\n // long again, so they are asked next round. An answer, even a refusal or a server error, says the mint is there.\n if (error instanceof Error && error.name === \"NetworkError\") down.add(melt.mint);\n }\n this.meltAsk.missed(melt.quote, Date.now(), !this.meltOverdue(melt));\n }\n\n /**\n * Asks the mint where a recorded melt stands and books the answer. Paid: the reserved proofs are gone and\n * the change is ours. Unpaid: what the mint says is unspent is spendable again. Pending: nothing moves.\n * Throws when the mint cannot be asked, and the melt stays as it is. `answered`: the mint answered the melt request\n * itself, so it has acted on it; without that, an unpaid quote may only mean the request has not landed yet.\n */\n private async settleMelt(melt: PendingMelt, answered = false): Promise<MeltOutcome> {\n const wallet = await this.wallet(melt.mint);\n const { Amount, OutputData } = await loadCashu();\n const quote = await wallet.checkMeltQuoteBolt11(melt.quote);\n if (quote.state === \"PAID\") {\n const signatures = (quote.change ?? []).filter((sig) => !Amount.from(sig.amount).isZero());\n let change: Proof[] = [];\n if (signatures.length > 0) {\n // The change may be on a keyset rotated in while the payment was pending. Fetching it can fail, and is retried.\n await wallet.ensureOperableKeysets(signatures.map((sig) => sig.id));\n try {\n change = wallet.createMeltChangeProofs(\n (melt.outputs as SerializedOutputData[]).map((o) => OutputData.deserialize(o)),\n signatures,\n );\n } catch (error) {\n // This would fail the same way every time, and the payment itself went through.\n console.warn(`[wallet] the fee change of melt ${melt.quote} could not be unblinded`, error);\n }\n }\n await this.finishMelt(melt, change);\n return \"paid\";\n }\n if (quote.state === \"PENDING\") return \"pending\";\n // UNPAID with no answer to the request: it may still reach the mint and be paid with these very proofs. Held\n // until no request of this melt can land any more.\n if (!answered && !this.meltOverdue(melt)) return \"pending\";\n\n // UNPAID: the payment failed, or never started. The mint says which proofs are still unspent.\n const inputs = await this.reservedProofs(melt);\n const states = inputs.length > 0 ? await wallet.checkProofsStates(inputs) : [];\n if (states.some((s) => s.state === \"PENDING\")) return \"pending\";\n const spent = new Set(inputs.filter((_, i) => states[i]?.state === \"SPENT\").map((p) => p.secret));\n if (spent.size > 0) console.warn(`[wallet] melt ${melt.quote} is unpaid, yet ${spent.size} of its proofs are spent`);\n // What left the balance for this payment and does not come back: the fee of the split that made its exact proofs\n // (the mint keeps it whether the payment goes or not). In the history, never silent. A proof that reads spent when\n // the payment never happened was spent by something else: it leaves the wallet, and is no fee of this payment.\n const lost = melt.outlay - inputs.reduce((sum, p) => sum + p.amount, 0);\n await this.sealedTransact([STORES.proofs, STORES.melts, ...(lost > 0 ? [STORES.walletTx] : [])], { [STORES.proofs]: inputs }, (stores) => {\n for (const p of inputs) {\n if (spent.has(p.secret)) stores[STORES.proofs].delete(p.secret);\n else stores[STORES.proofs].put({ ...p, reserved: false } satisfies StoredProof);\n }\n stores[STORES.melts].delete(melt.quote);\n if (lost > 0) stores[STORES.walletTx].put(walletTx(melt.mint, \"fee\", 0, lost, melt.note ? `Payment failed: ${melt.note}` : \"A Lightning payment failed\"));\n });\n if (lost > 0) this.failedFees.set(melt.quote, lost);\n if (spent.size > 0) { this.spentAway.add(melt.quote); void this.recheck(melt.mint).catch(() => {}); }\n return \"unpaid\";\n }\n\n /** The fee a failed melt cost, once: for the words that say it failed. */\n private takeFailedFee(quote: string): number {\n const lost = this.failedFees.get(quote) ?? 0;\n this.failedFees.delete(quote);\n return lost;\n }\n\n /** The invoice is paid: the reserved proofs are spent, the change is ours, and the payment goes in the history. */\n private async finishMelt(melt: PendingMelt, change: Proof[]): Promise<void> {\n // The reserve is an upper bound; the mint returns what the route did not cost as change.\n const tx = walletTx(melt.mint, \"lightning-out\", melt.amount, melt.outlay - sats(change) - melt.amount, melt.note);\n await this.sealedTransact([STORES.proofs, STORES.melts, STORES.walletTx], { [STORES.proofs]: change }, (stores) => {\n for (const secret of melt.secrets) stores[STORES.proofs].delete(secret);\n // From a restored copy, the profile it came from may have settled this payment and spent its change since.\n for (const p of change) stores[STORES.proofs].put({ ...toStored(melt.mint, p), ...(melt.restored ? { unchecked: true } : {}) } satisfies StoredProof);\n stores[STORES.melts].delete(melt.quote);\n stores[STORES.walletTx].put(tx);\n });\n if (melt.restored && change.length > 0) void this.checkRestored();\n }\n\n /**\n * The person removes the Cashu wallet of a network (the engine checked what it holds and what it still waits for,\n * claimed what was already paid, and the person confirmed the rest): the ecash held at its mints, reserved or not,\n * and every invoice of theirs are deleted. A Lightning payment still in flight from one of them is not cut off: the\n * removal is refused until it settles.\n */\n async forget(mints: readonly string[], acceptLoss = false): Promise<void> {\n const at = new Set(mints);\n const inFlight = async () => {\n const melts = await this.readMelts();\n if (melts.some((m) => at.has(m.mint))) throw new Error(\"A Lightning payment from this wallet is still in flight: wait for it to settle, then remove the wallet.\");\n };\n await inFlight();\n // A swap still written down may hold ecash of these mints. They are asked once more, and a swap they cannot\n // settle now is not cut off: the removal is refused until it is. One that holds nothing any more goes with the rest.\n await this.pollSwaps(mints).catch(() => {});\n // Checked again and deleted under every one of these mints' locks: a payment or a send that was splitting its ecash\n // meanwhile (no payment written down yet) ends its turn first, and one that went on to the mint refuses the removal\n // instead of losing its reserved ecash.\n await this.lockedAll(mints, async () => {\n await inFlight();\n const open = (await this.readSwaps()).filter((s) => at.has(s.mint) && !s.released);\n // One that may never settle (its mint is gone, or cannot say what it signed) goes only when the person, shown\n // what it is about, agreed to let it go.\n if (open.length > 0 && !acceptLoss) throw new Error(\"An exchange of ecash with this wallet's mint is not finished yet: wait for the mint to answer, or confirm that what it would bring is lost to remove the wallet.\");\n const proofs = (await this.allProofs()).filter((p) => at.has(p.mint));\n const quotes = (await wrap<StoredQuote[]>((await store(STORES.quotes, \"readonly\")).getAll())).filter((q) => at.has(q.mint));\n const swaps = (await this.readSwaps()).filter((s) => at.has(s.mint));\n await this.sealedTransact([STORES.proofs, STORES.quotes, STORES.swaps], {}, (stores) => {\n for (const p of proofs) stores[STORES.proofs].delete(p.secret);\n for (const q of quotes) stores[STORES.quotes].delete(q.quote);\n for (const s of swaps) stores[STORES.swaps].delete(s.id);\n });\n });\n for (const mint of mints) { this.wallets.delete(mint); this.names.delete(mint); this.infos.delete(mint); }\n }\n\n private async reservedProofs(melt: PendingMelt): Promise<StoredProof[]> {\n return this.proofsOf(melt.secrets);\n }\n\n /** Everything held, as one token per mint; `mints`: only these mints' (one network's wallet). */\n async exportTokens(mints?: readonly string[]): Promise<{ mint: string; token: string; amount: number }[]> {\n const out: { mint: string; token: string; amount: number }[] = [];\n for (const mint of new Set((await this.allProofs()).map((p) => p.mint))) {\n if (mints && !mints.includes(mint)) continue;\n const proofs = await this.proofsAt(mint);\n if (proofs.length === 0) continue;\n out.push({\n mint,\n amount: total(proofs),\n token: (await loadCashu()).getEncodedToken({ mint, proofs: proofs as unknown as Proof[], unit: UNIT }),\n });\n }\n return out;\n }\n\n /** Whether the payment poll's reads at this mint may ask it now: its last load did not fail, or its next try came. */\n mintDue(mint: string, now: number): boolean {\n return !this.failedLoads.has(mint) || this.mintAsk.due(mint, now);\n }\n\n // -- storage -----------------------------------------------------------------\n\n /**\n * A mint's loaded wallet. A failed load is tried again by the next caller, unless that one takes `recentFailure`\n * (a payment's reads in the poll): a failed load is its answer too until the mint's next try (`mintAsk`).\n */\n private wallet(mint: string, recentFailure = false): Promise<Wallet> {\n let wallet = this.wallets.get(mint);\n if (this.failedLoads.has(mint) && !(recentFailure && !this.mintAsk.due(mint, Date.now()))) wallet = undefined;\n if (!wallet) {\n const loading = (async () => {\n const cashu = await loadCashu();\n const instance = new cashu.Wallet(mint, { unit: UNIT });\n boundMintRequests(instance, cashu.NetworkError);\n await within(MINT_TIMEOUT_MS, instance.loadMint(), mint);\n const info = instance.getMintInfo();\n if (info.isSupported(5).params.some(saysAmountlessBeside)) instance.loadMintFromCache(amountlessUnderOptions(info.cache), instance.keyChain.cache);\n return instance;\n })();\n wallet = loading;\n this.failedLoads.delete(mint);\n this.wallets.set(mint, loading);\n loading.then(() => this.mintAsk.forget(mint), () => {\n if (this.wallets.get(mint) !== loading) return;\n this.failedLoads.add(mint);\n this.mintAsk.missed(mint, Date.now());\n });\n }\n return wallet;\n }\n\n /** One operation per mint at a time: two swaps must never pick the same proofs. */\n /** Tasks inside a per-mint lock, running or waiting their turn: a swap there must end, not be cut (WISP 06 § Wallets). */\n private lockedTasks = 0;\n get swapping(): boolean { return this.lockedTasks > 0; }\n\n private locked<T>(mint: string, task: () => Promise<T>): Promise<T> {\n const previous = this.locks.get(mint) ?? Promise.resolve();\n this.lockedTasks += 1;\n const next = previous.then(task, task);\n void next.then(() => { this.lockedTasks -= 1; }, () => { this.lockedTasks -= 1; });\n this.locks.set(\n mint,\n next.catch(() => {}),\n );\n return next;\n }\n\n /** `task` under the locks of every one of `mints`, taken in one order (no other task holds two, so none waits on this one). */\n private lockedAll<T>(mints: readonly string[], task: () => Promise<T>): Promise<T> {\n return [...new Set(mints)].sort().reduceRight<() => Promise<T>>((inner, mint) => () => this.locked(mint, inner), task)();\n }\n\n private async allProofs(): Promise<StoredProof[]> {\n return openRows(STORES.proofs, await wrap<StoredProof[]>((await store(STORES.proofs, \"readonly\")).getAll()));\n }\n\n /**\n * The stored proofs of these secrets, each read by its key: a swap's inputs cost what the swap holds, not the wallet.\n * With the data key, a proof is under the hash of its secret, or under the secret itself until the migration reseals it.\n */\n private async proofsOf(secrets: Iterable<string>): Promise<StoredProof[]> {\n const wanted = [...new Set(secrets)];\n if (wanted.length === 0) return [];\n const proofs = await store(STORES.proofs, \"readonly\");\n const sealed = hasDataKey();\n const found = await Promise.all(wanted.map(async (secret) => {\n const [hashed, plain] = await Promise.all([sealed ? wrap<StoredProof | undefined>(proofs.get(proofKey(secret))) : undefined, wrap<StoredProof | undefined>(proofs.get(secret))]);\n return hashed ?? plain;\n }));\n return openRows(STORES.proofs, found.filter((p): p is StoredProof => p !== undefined));\n }\n\n private async readSwaps(): Promise<PendingSwap[]> {\n return openRows(STORES.swaps, await wrap<PendingSwap[]>((await store(STORES.swaps, \"readonly\")).getAll()));\n }\n\n private async readMelts(): Promise<PendingMelt[]> {\n return openRows(STORES.melts, await wrap<PendingMelt[]>((await store(STORES.melts, \"readonly\")).getAll()));\n }\n\n /** Sealed before its transaction opens (one that waits for WebCrypto commits early), when the profile is encrypted. */\n private async putSwap(swap: PendingSwap): Promise<void> {\n const row = await sealRow(STORES.swaps, swap);\n await committed((await store(STORES.swaps, \"readwrite\")).put(row));\n }\n\n /**\n * `transact`, with the wallet's secrets sealed as they are written when the profile is encrypted (WISP 04): `rows`,\n * the proofs, swaps, melts and payments the work may put, are sealed before the transaction opens, and the work finds\n * a proof by its secret. Without the data key, `transact` itself.\n */\n private async sealedTransact(names: string[], rows: Partial<Record<string, readonly object[]>>, work: (stores: Record<string, IDBObjectStore>) => void): Promise<void> {\n const seals = new RowSeals();\n for (const [name, list] of Object.entries(rows)) await seals.prepare(name, list ?? []);\n return transact(names, (stores) => work(seals.on ? Object.fromEntries(names.map((name) => [name, sealedStore(stores[name], seals)])) : stores));\n }\n\n private async proofsAt(mint: string): Promise<StoredProof[]> {\n return (await this.allProofs()).filter((p) => p.mint === mint && !p.reserved);\n }\n\n /** After a swap: the inputs are spent, `keep` is what came back to us. Queued in the caller's transaction: all or nothing. */\n private queueReplace(proofStore: IDBObjectStore, mint: string, inputs: StoredProof[], keep: Proof[]): void {\n const kept = new Set(keep.map((p) => p.secret));\n for (const p of inputs) if (!kept.has(p.secret)) proofStore.delete(p.secret);\n for (const p of keep) proofStore.put(toStored(mint, p));\n }\n}\n","import { dialableIrohRelay, fromBase64Url, irohDescriptor, irohRelayUrl, relayUrl, relayUrlTooLong, type BoundChannel, type FrameChannel, type NativeBinding, type NativeEndpoint } from \"@ghostly/core\";\n\n/**\n * Iroh (WISP 102) in a browser: the same QUIC/TLS session and binding as the\n * Desktop's native Iroh, but relay only. A page cannot send UDP, so every\n * packet goes through an Iroh relay over a WebSocket; the relay sees who talks\n * to whom and when, never the frames.\n *\n * The wasm (about 1 MB gzip) loads on the first chat that starts an endpoint,\n * never on the app's first load.\n */\n\n/**\n * n0's public relays, the same ones the Desktop's Iroh homes on by default, then Ghostly's own (`iroh-relay` behind a\n * Cloudflare tunnel) as one more fallback. Iroh homes on the one with the lowest latency it measures, not the first.\n * Iroh itself names n0's with the trailing dot of a full domain name (`use1-1.relay.n0.iroh.link.`), and compares relay\n * URLs as text; here they have none, because WebKit opens no host name that ends in a dot. `BROWSER_SPELLING` is what\n * keeps the two one relay. Ghostly's stays plain everywhere: the tunnel in front of it answers the dotted name with 404.\n * At most `MAX_IROH_RELAYS`, the wasm's own limit.\n */\nexport const DEFAULT_IROH_RELAYS = [\n \"https://use1-1.relay.n0.iroh.link/\",\n \"https://euc1-1.relay.n0.iroh.link/\",\n \"https://aps1-1.relay.n0.iroh.link/\",\n \"https://usw1-1.relay.n0.iroh.link/\",\n \"https://iroh.miguelmedeiros.dev/\",\n] as const;\n\n/** The most relays an endpoint homes on: the wasm refuses more (`native/transports/iroh-web`), as does the Desktop. */\nexport const MAX_IROH_RELAYS = 5;\n\n/**\n * Whether one of these relays is n0's public ones (`*.iroh.link`, either spelling): those refused six of sixteen\n * listeners started at once, so an app that may home on one keeps the listener count they took.\n */\nexport function onPublicIrohRelay(relays: readonly string[]): boolean {\n return relays.some(relay => { try { return /(^|\\.)iroh\\.link\\.?$/.test(new URL(relay).hostname); } catch { return false; } });\n}\n\n/**\n * The spelling of every relay URL handed to the wasm Iroh (`irohRelayUrl`): the relays it homes on and a contact's\n * relay before a dial. One spelling, so a contact on this endpoint's relay is reached over the connection already\n * open to it; without the dot, so Safari can open it (a Desktop's record names its relay with the dot).\n */\nconst BROWSER_SPELLING = \"plain\";\n\n/**\n * Why a relay URL cannot be used, or null. TLS, except on this machine (a local `iroh-relay --dev`): a page\n * may not open plain WebSockets elsewhere, and the relay's operator would see traffic metadata in the clear.\n */\nexport function irohRelayProblem(value: string): string | null {\n let url: URL;\n try { url = new URL(value); } catch { return `Not a relay address: ${value}`; }\n const local = [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname);\n if (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && local)) return `Use an https:// relay address: ${value}`;\n if (url.username || url.password || url.search || url.hash) return `Not a relay address: ${value}`;\n // Nor one a contact would drop with the whole descriptor (`relayUrl`: past 120 characters, a loopback path past 100),\n // leaving this profile unreached over Iroh without a word. Checked as Iroh names it: parsed, in its longer spelling.\n // One refused for its length alone is a relay address all the same: what to do is said instead.\n const named = new URL(irohRelayUrl(value)).href;\n if (value.length > 256 || !relayUrl(named)) return relayUrlTooLong(named) ? `Use a shorter relay address: ${value}` : `Not a relay address: ${value}`;\n return null;\n}\n\n/** A browser endpoint's descriptor: no direct addresses, only its relay. */\nexport interface IrohWebDescriptor { id: string; relay: string | null; addresses: string[] }\n\ninterface WasmConn {\n binding(): NativeBinding;\n send(text: string): Promise<void>;\n recv(): Promise<string | undefined>;\n rtt(): number;\n close(): void;\n free(): void;\n}\ninterface WasmNode {\n address(): IrohWebDescriptor;\n connect(descriptor: unknown, timeoutMs: number): Promise<WasmConn>;\n accept(): Promise<WasmConn | undefined>;\n close(): Promise<void>;\n free(): void;\n}\nexport interface IrohWasm {\n IrohNode: { start(seed: Uint8Array, relays: string[], onlineMs: number): Promise<WasmNode> };\n}\n\nlet loaded: Promise<IrohWasm> | null = null;\n/** Loads the wasm once per page. Tests pass their own `load` (Node reads the file). */\nexport function loadIrohWasm(): Promise<IrohWasm> {\n loaded ??= import(\"@ghostly/iroh-web\").then(async module => {\n await module.default();\n return module as unknown as IrohWasm;\n }).catch(error => { loaded = null; throw error; });\n return loaded;\n}\n\nexport interface IrohWebOptions {\n /** Relay URLs, first preferred. Default: n0's public relays. */\n relays?: readonly string[];\n /** How long to wait for the first relay to answer. */\n onlineMs?: number;\n connectMs?: number;\n load?: () => Promise<IrohWasm>;\n /**\n * Dial only through one of `relays` (Hide my IP from contacts, WISP 100 § Relay only): the wasm reaches a peer through\n * the relay its descriptor names, and a contact who runs that relay would see this profile's address there.\n */\n ownRelaysOnly?: boolean;\n /**\n * Whether a contact's relay is at a public address, or at a name whose every address is public now: asked before each\n * dial through a relay that is not one of `relays`, where the host has a resolver (the CLI's `nodePublicRelay`). A page\n * has none; a contact's relay is held there to what its URL says (`dialableIrohRelay`).\n */\n publicRelay?: (relay: string) => Promise<boolean>;\n}\n\nconst SEND_BUDGET = 120 * 1024;\nconst MAX_FRAME = 60 * 1024;\n/** How often an endpoint reads which relay it is homed on (`createIrohWebEndpoint`). */\nconst HOME_CHECK_MS = 5_000;\n\n/** One paired channel over one QUIC stream. Sends are queued in order. */\nclass IrohWebChannel implements FrameChannel {\n private reader: FrameChannel[\"onMessage\"] = null;\n private buffered: string[] = [];\n private queue = Promise.resolve();\n private closed = false;\n bufferedAmount = 0;\n readonly sendBudget = SEND_BUDGET;\n onClose: FrameChannel[\"onClose\"] = null;\n constructor(private conn: WasmConn, private forget: () => void) { void this.read(); }\n get onMessage() { return this.reader; }\n set onMessage(reader: FrameChannel[\"onMessage\"]) {\n this.reader = reader;\n if (reader) for (const text of this.buffered.splice(0)) reader(text);\n }\n private async read() {\n try {\n for (;;) {\n const text = await this.conn.recv();\n if (text === undefined || this.closed) break;\n if (this.reader) this.reader(text);\n else if (this.buffered.length < 64) this.buffered.push(text);\n else break;\n }\n } catch { /* A broken stream ends the channel. */ }\n this.close();\n }\n send(data: string | Uint8Array) {\n if (typeof data !== \"string\" || this.closed || !data.length || data.length > MAX_FRAME || this.bufferedAmount + data.length > SEND_BUDGET)\n throw new Error(\"Iroh channel is closed or its send budget is full\");\n this.bufferedAmount += data.length;\n this.queue = this.queue.then(() => this.closed ? undefined : this.conn.send(data))\n .catch(() => this.close()).finally(() => { this.bufferedAmount -= data.length; });\n }\n drained() { return this.queue; }\n get rttMs() { const rtt = this.conn.rtt(); return rtt >= 0 ? rtt : undefined; }\n close() {\n if (this.closed) return;\n this.closed = true; this.buffered = [];\n try { this.conn.close(); } catch { /* Already gone. */ }\n this.forget();\n this.onClose?.();\n }\n}\n\n/**\n * Where the endpoint that measures a relay list for the others is homed, per wasm loader and list. Each endpoint on a\n * list keeps measuring every relay in it (a `GET /ping` to each, about 1.3 a minute), and all the endpoints in one app\n * share one network, so one measures for all: the others start on its home relay alone, which is also the one their\n * descriptor names, and move when it moves (`HOME_CHECK_MS`). On its home alone, an endpoint never leaves that relay by\n * itself: when it went down, 5 of 6 such listeners stayed out of reach until it came back (local relays, 90 s), while\n * the one measuring was homed elsewhere within 45 s. Dialling a contact on another relay still works; only the measuring\n * is skipped.\n */\ninterface Homing {\n /** Settles with the measuring endpoint's first home, or null when it failed to start. */\n found: Promise<string | null>;\n /** Its home now, as the list spells it, once found. */\n home: string | null;\n /** The endpoint measuring, or null once it closed: the next to start or to look takes it on. */\n measurer: object | null;\n}\nconst homes = new WeakMap<object, Map<string, Homing>>();\n\n/** The list's spelling of a relay the wasm names. */\nfunction listed(relays: readonly string[], relay: string | null | undefined): string | null {\n if (!relay) return null;\n try { return relays.find(own => new URL(own).href === new URL(relay).href) ?? null; } catch { return null; }\n}\n\n/**\n * Starts a node on the home relay the measuring endpoint is on, or on every relay when none measures, it has no home\n * or that one fails; then this one measures for the list (`whole`).\n */\nasync function startNode(wasm: IrohWasm, homesOfList: Map<string, Homing>, me: object, seed: Uint8Array, relays: string[], onlineMs: number): Promise<{ node: WasmNode; whole: boolean }> {\n const key = relays.join(\" \");\n const homing = relays.length > 1 ? homesOfList.get(key) : undefined;\n if (homing?.measurer) await homing.found;\n if (homing?.measurer && homing.home) {\n try { return { node: await wasm.IrohNode.start(seed, [homing.home], onlineMs), whole: false }; } catch {\n // That relay stopped answering: measure again, from the next endpoint on.\n if (homesOfList.get(key) === homing) homesOfList.delete(key);\n }\n }\n let settle = (_home: string | null) => {};\n const mine: Homing | null = relays.length > 1 && !homesOfList.get(key)?.measurer\n ? { found: new Promise<string | null>(resolve => { settle = resolve; }), home: null, measurer: me } : null;\n if (mine) homesOfList.set(key, mine);\n try {\n const node = await wasm.IrohNode.start(seed, relays, onlineMs);\n if (mine) settle(mine.home = listed(relays, node.address().relay));\n return { node, whole: true };\n } catch (error) {\n if (mine && homesOfList.get(key) === mine) homesOfList.delete(key);\n settle(null);\n throw error;\n }\n}\n\n/** Whether a descriptor (in `BROWSER_SPELLING`) names one of these relays, whichever way its URL is written. */\nfunction onOwnRelay(descriptor: unknown, relays: readonly string[]): boolean {\n const relay = (descriptor as { relay?: unknown } | null | undefined)?.relay;\n if (typeof relay !== \"string\") return false;\n try { return relays.some(own => new URL(own).href === new URL(relay).href); } catch { return false; }\n}\n\n/** A NativeEndpoint for `iroh/1`, as the Desktop's is, for one chat's transport seed. */\nexport async function createIrohWebEndpoint(seedB64: string, options: IrohWebOptions = {}): Promise<NativeEndpoint> {\n const seed = fromBase64Url(seedB64);\n if (seed.length !== 32) throw new Error(\"Invalid transport seed\");\n // Either spelling of a relay (with or without the trailing dot) homes on it under the one a browser opens.\n const relays = [...new Set((options.relays?.length ? options.relays : DEFAULT_IROH_RELAYS).map(relay => irohRelayUrl(relay, BROWSER_SPELLING)))];\n const load = options.load ?? loadIrohWasm;\n const wasm = await load();\n let homesOfList = homes.get(load);\n if (!homesOfList) homes.set(load, homesOfList = new Map());\n const onlineMs = options.onlineMs ?? 10_000;\n const key = relays.join(\" \");\n const me = {};\n let { node, whole } = await startNode(wasm, homesOfList, me, seed, relays, onlineMs);\n const channels = new Set<IrohWebChannel>();\n let stopped = false;\n /** A node being replaced by one on another relay list (`move`): the old one's end is not the relay going away. */\n let moving = false;\n let handler: NativeEndpoint[\"onConnection\"] = null;\n const early: BoundChannel[] = [];\n const bind = (conn: WasmConn): BoundChannel => {\n const channel: IrohWebChannel = new IrohWebChannel(conn, () => channels.delete(channel));\n channels.add(channel);\n return { channel, binding: conn.binding() };\n };\n const endpoint: NativeEndpoint = {\n transport: \"iroh/1\",\n // Relay only: the rank puts it after every direct path (WISP 100, \"Relayed\").\n descriptor: { ...node.address(), relayed: true },\n onDescriptor: null,\n get onConnection() { return handler; },\n set onConnection(value) { handler = value; if (value) for (const bound of early.splice(0)) value(bound); },\n async connect(descriptor) {\n if (stopped) throw new Error(\"Iroh endpoint is stopped\");\n if (!dialableIrohRelay((descriptor as { relay?: unknown } | null)?.relay, relays)) throw new Error(\"The contact's Iroh relay is not one this device dials\");\n const dialled = irohDescriptor(descriptor, BROWSER_SPELLING);\n if (options.ownRelaysOnly && !onOwnRelay(dialled, relays)) throw new Error(\"The contact is not on one of this profile's Iroh relays\");\n const relay = (dialled as { relay?: unknown } | null)?.relay;\n if (options.publicRelay && typeof relay === \"string\" && !onOwnRelay(dialled, relays) && !await options.publicRelay(relay))\n throw new Error(\"The contact's Iroh relay is not one this device dials\");\n if (stopped) throw new Error(\"Iroh endpoint is stopped\");\n const conn = await node.connect(dialled, options.connectMs ?? 20_000);\n if (stopped) { conn.close(); throw new Error(\"Iroh endpoint is stopped\"); }\n return bind(conn);\n },\n async close() {\n if (stopped) return;\n stopped = true;\n clearInterval(watching);\n const homing = homesOfList.get(key);\n if (homing?.measurer === me) homing.measurer = null;\n for (const channel of [...channels]) channel.close();\n for (const bound of early.splice(0)) bound.channel.close();\n await node.close().catch(() => {});\n },\n };\n /** Replaces the node with one on `list` (the whole list if that fails), same seed: same endpoint id. */\n const move = async (list: string[]): Promise<void> => {\n moving = true;\n // Taking on the measuring: the others wait for its home, as for a first endpoint's (`startNode`).\n let settle = (_home: string | null) => {};\n const mine: Homing | null = list === relays && !homesOfList.get(key)?.measurer\n ? { found: new Promise<string | null>(resolve => { settle = resolve; }), home: null, measurer: me } : null;\n if (mine) homesOfList.set(key, mine);\n try {\n await node.close().catch(() => {});\n let fresh: WasmNode | undefined;\n for (const tried of list.length < relays.length ? [list, relays] : [relays]) {\n if (stopped) return;\n try { fresh = await wasm.IrohNode.start(seed, tried, onlineMs); whole = tried === relays; break; } catch { /* The next list, or none. */ }\n }\n if (fresh && stopped) { await fresh.close().catch(() => {}); return; }\n if (!fresh) { if (!stopped) { endpoint.onUnavailable?.(); await endpoint.close(); } return; }\n node = fresh;\n serve(fresh);\n if (mine) settle(mine.home = listed(relays, fresh.address().relay));\n moving = false;\n look();\n } finally {\n moving = false;\n if (mine && !mine.home) {\n if (homesOfList.get(key) === mine) homesOfList.delete(key);\n settle(null);\n }\n }\n };\n // Iroh moves its home to another of the relays when the one it homed on goes away or another answers faster, and a\n // contact reaches it only through the relay its record names (the one left: no answer, every time). The wasm says\n // nothing when it moves, so its address is read again (`HOME_CHECK_MS`) and a new home is published, as the\n // Desktop's own Iroh does (`onDescriptor`). Between two homes it has none: the last stays published.\n const look = () => {\n let now: IrohWebDescriptor;\n try { now = node.address(); } catch { return; }\n if (stopped || moving) return;\n const homing = homesOfList.get(key);\n if (now.relay && now.relay !== (endpoint.descriptor as IrohWebDescriptor).relay) {\n endpoint.descriptor = { ...now, relayed: true };\n endpoint.onDescriptor?.();\n if (homing?.measurer === me) homing.home = listed(relays, now.relay) ?? homing.home;\n }\n // One on the measured home alone follows it, or measures once nobody does; only with no channel open, which the\n // new node would end (a channel on a relay that went away ends by itself).\n if (whole || relays.length < 2 || channels.size) return;\n if (!homing?.measurer) void move(relays);\n else if (homing.home && now.relay && listed(relays, now.relay) !== homing.home) void move([homing.home]);\n };\n const watching = setInterval(look, HOME_CHECK_MS);\n const serve = (current: WasmNode) => void (async () => {\n while (!stopped && current === node) {\n let conn: WasmConn | undefined;\n try { conn = await current.accept(); } catch { break; }\n if (!conn) break;\n if (stopped || current !== node) { conn.close(); break; }\n const bound = bind(conn);\n const accept = endpoint.onConnection;\n if (accept) accept(bound); else if (early.length < 4) early.push(bound); else bound.channel.close();\n }\n // The relay went away for good (or the endpoint was closed): stop offering Iroh.\n if (!stopped && current === node && !moving) { endpoint.onUnavailable?.(); await endpoint.close(); }\n })();\n serve(node);\n return endpoint;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,IAAa,0BAA0B;;CAErC,UAAU;;CAEV,WAAW;AACb;;AAGA,IAAa,sBAAsB;;AAGnC,IAAMA,mCAAiB,IAAI,IAAI;CAC7B;CAAc;CAAa;CAAe;CAAa;CAAc;CACrE;CAAc;CAAc;CAAuB;CAAuB;CAAc;CAAa;CAAc;AACrH,CAAC;;AAGD,IAAM,8BAAc,IAAI,IAAI;CAAC;CAAQ;CAAQ;CAAQ;CAAQ;CAAQ;CAAQ;CAAQ;CAAQ;CAAQ;CAAQ;AAAM,CAAC;;AAKpH,IAAM,kCAAkB,IAAI,IAAI,CAAC,QAAQ,MAAM,CAAC;AAEhD,IAAM,SAAS,GAAe,OAAgB,EAAE,O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