@ghostlytools/cli 1.10.0 → 1.10.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.
Files changed (104) hide show
  1. package/README.md +19 -17
  2. package/SKILL.md +5 -4
  3. package/dist/assets/api-DcE4KylM.js +3 -0
  4. package/dist/assets/{api-BF_KwecF.js → api-EUGHGnRz.js} +108 -49
  5. package/dist/assets/api-EUGHGnRz.js.map +1 -0
  6. package/dist/assets/{apiKit-Du1u2l4x.js → apiKit-CJVp_crp.js} +85 -22
  7. package/dist/assets/apiKit-CJVp_crp.js.map +1 -0
  8. package/dist/assets/{apps-Bti9fDoW.js → apps-C-KbyLCa.js} +1 -1
  9. package/dist/assets/{apps-DwPfp54I.js → apps-C54T_MOT.js} +33 -12
  10. package/dist/assets/apps-C54T_MOT.js.map +1 -0
  11. package/dist/assets/{arkade-DOWpA2Kr.js → arkade-BmxJTa65.js} +2 -2
  12. package/dist/assets/{arkade-DOWpA2Kr.js.map → arkade-BmxJTa65.js.map} +1 -1
  13. package/dist/assets/{backup-DZ_Q1eSu.js → backup-BxSH5BZG.js} +7 -6
  14. package/dist/assets/{backup-DZ_Q1eSu.js.map → backup-BxSH5BZG.js.map} +1 -1
  15. package/dist/assets/{backup-CeRckyl2.js → backup-C0Plp-DF.js} +1 -1
  16. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -1
  17. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
  18. package/dist/assets/{buttons-BxIThdg9.js → buttons-B-ZJYdo0.js} +6 -6
  19. package/dist/assets/{buttons-BxIThdg9.js.map → buttons-B-ZJYdo0.js.map} +1 -1
  20. package/dist/assets/buttons-DA3wZfG0.js +2 -0
  21. package/dist/assets/childEnv-BVOQK9EA.js +21 -0
  22. package/dist/assets/childEnv-BVOQK9EA.js.map +1 -0
  23. package/dist/assets/{client-D5E1RQYB.js → client-CDa87uYD.js} +3 -3
  24. package/dist/assets/{client-D5E1RQYB.js.map → client-CDa87uYD.js.map} +1 -1
  25. package/dist/assets/codec-D45W1L8n.js +13 -0
  26. package/dist/assets/codec-D45W1L8n.js.map +1 -0
  27. package/dist/assets/{envelope-CugS9qwQ.js → envelope-C3yFCQa-.js} +3 -12
  28. package/dist/assets/envelope-C3yFCQa-.js.map +1 -0
  29. package/dist/assets/{errors-R4S2SAEM.js → errors-Dt-ZnyOX.js} +3 -1
  30. package/dist/assets/errors-Dt-ZnyOX.js.map +1 -0
  31. package/dist/assets/{fixedHosts-B4E4VrYE.js → fixedHosts-C6nCHjOa.js} +4 -4
  32. package/dist/assets/{fixedHosts-B4E4VrYE.js.map → fixedHosts-C6nCHjOa.js.map} +1 -1
  33. package/dist/assets/{groupFiles-NonOYBKN.js → groupFiles-DYopNE57.js} +217 -178
  34. package/dist/assets/groupFiles-DYopNE57.js.map +1 -0
  35. package/dist/assets/{host-DvcVt5YI.js → host-G5seUwaI.js} +241 -87
  36. package/dist/assets/host-G5seUwaI.js.map +1 -0
  37. package/dist/assets/{hyperdhtRelay-Ce42sR8x.js → hyperdhtRelay-B_uHjg_r.js} +28 -20
  38. package/dist/assets/hyperdhtRelay-B_uHjg_r.js.map +1 -0
  39. package/dist/assets/{irohWeb-C9ChbD-c.js → irohWeb-C-2oslSU.js} +120 -38
  40. package/dist/assets/irohWeb-C-2oslSU.js.map +1 -0
  41. package/dist/assets/{main-4qE381KM.js → main-Dk--nD7X.js} +92 -48
  42. package/dist/assets/main-Dk--nD7X.js.map +1 -0
  43. package/dist/assets/{mainline-DOwZDHVy.js → mainline-HPlVrl8R.js} +5 -5
  44. package/dist/assets/mainline-HPlVrl8R.js.map +1 -0
  45. package/dist/assets/networkReason-CfpO9ayz.js +474 -0
  46. package/dist/assets/networkReason-CfpO9ayz.js.map +1 -0
  47. package/dist/assets/{nwc-CHLWFV1R.js → nwc-BY7BPttn.js} +3 -3
  48. package/dist/assets/{nwc-CHLWFV1R.js.map → nwc-BY7BPttn.js.map} +1 -1
  49. package/dist/assets/{nwcProvider-BlkPOJen.js → nwcProvider-CfpbNUf7.js} +2 -2
  50. package/dist/assets/{nwcProvider-BlkPOJen.js.map → nwcProvider-CfpbNUf7.js.map} +1 -1
  51. package/dist/assets/{ownDid-yXtY_1B5.js → ownDid-DJFZM2cV.js} +2 -2
  52. package/dist/assets/{ownDid-yXtY_1B5.js.map → ownDid-DJFZM2cV.js.map} +1 -1
  53. package/dist/assets/{profiles-vbXHs0Mq.js → profiles-DKmZGXp6.js} +22 -9
  54. package/dist/assets/profiles-DKmZGXp6.js.map +1 -0
  55. package/dist/assets/{registry-chCD0KWS.js → registry-BUm4cAzV.js} +60 -19
  56. package/dist/assets/registry-BUm4cAzV.js.map +1 -0
  57. package/dist/assets/{registry-BN9r2pR4.js → registry-CAzrtV0_.js} +1 -1
  58. package/dist/assets/{resolve-Dtzogt2W.js → resolve-CDD4X68j.js} +5 -3
  59. package/dist/assets/resolve-CDD4X68j.js.map +1 -0
  60. package/dist/assets/{restoredRows-CRYwIx3g.js → restoredRows-YhlbokEE.js} +4 -2
  61. package/dist/assets/restoredRows-YhlbokEE.js.map +1 -0
  62. package/dist/assets/{secretGuard-CSVNxXVW.js → secretGuard-B7Hj0Kvz.js} +2 -2
  63. package/dist/assets/{secretGuard-CSVNxXVW.js.map → secretGuard-B7Hj0Kvz.js.map} +1 -1
  64. package/dist/assets/secretGuard-DUr6bgKc.js +2 -0
  65. package/dist/assets/{server-BZnsm5X5.js → server-DcOsgYDU.js} +1046 -573
  66. package/dist/assets/server-DcOsgYDU.js.map +1 -0
  67. package/dist/assets/{src-DZagapGt.js → src-D31D1_oY.js} +2360 -1673
  68. package/dist/assets/src-D31D1_oY.js.map +1 -0
  69. package/dist/assets/{sshForges-BkTgy5rx.js → sshForges-DerRwMf3.js} +2 -2
  70. package/dist/assets/{sshForges-BkTgy5rx.js.map → sshForges-DerRwMf3.js.map} +1 -1
  71. package/dist/assets/{translate-B9SMd6uf.js → translate-C-sj0VJe.js} +12 -8
  72. package/dist/assets/{translate-B9SMd6uf.js.map → translate-C-sj0VJe.js.map} +1 -1
  73. package/dist/assets/{usdt-BU4ezonh.js → usdt-DwHqp625.js} +3 -3
  74. package/dist/assets/{usdt-BU4ezonh.js.map → usdt-DwHqp625.js.map} +1 -1
  75. package/dist/assets/{waitNotice-B8D8WhbE.js → waitNotice-D52RWbV4.js} +38 -4
  76. package/dist/assets/waitNotice-D52RWbV4.js.map +1 -0
  77. package/dist/assets/{words-jYy7lTcb.js → words-Db9WgatT.js} +3 -3
  78. package/dist/assets/words-Db9WgatT.js.map +1 -0
  79. package/dist/ghostly.mjs +1 -1
  80. package/package.json +1 -1
  81. package/dist/assets/api-BF_KwecF.js.map +0 -1
  82. package/dist/assets/api-DdrA86Ur.js +0 -3
  83. package/dist/assets/apiKit-Du1u2l4x.js.map +0 -1
  84. package/dist/assets/apps-DwPfp54I.js.map +0 -1
  85. package/dist/assets/buttons-D9QBHS9Y.js +0 -2
  86. package/dist/assets/envelope-CugS9qwQ.js.map +0 -1
  87. package/dist/assets/errors-R4S2SAEM.js.map +0 -1
  88. package/dist/assets/groupFiles-NonOYBKN.js.map +0 -1
  89. package/dist/assets/host-DvcVt5YI.js.map +0 -1
  90. package/dist/assets/hyperdhtRelay-Ce42sR8x.js.map +0 -1
  91. package/dist/assets/irohWeb-C9ChbD-c.js.map +0 -1
  92. package/dist/assets/main-4qE381KM.js.map +0 -1
  93. package/dist/assets/mainline-DOwZDHVy.js.map +0 -1
  94. package/dist/assets/networkReason-MInk1Y63.js +0 -154
  95. package/dist/assets/networkReason-MInk1Y63.js.map +0 -1
  96. package/dist/assets/profiles-vbXHs0Mq.js.map +0 -1
  97. package/dist/assets/registry-chCD0KWS.js.map +0 -1
  98. package/dist/assets/resolve-Dtzogt2W.js.map +0 -1
  99. package/dist/assets/restoredRows-CRYwIx3g.js.map +0 -1
  100. package/dist/assets/secretGuard-Q2BKq0q0.js +0 -2
  101. package/dist/assets/server-BZnsm5X5.js.map +0 -1
  102. package/dist/assets/src-DZagapGt.js.map +0 -1
  103. package/dist/assets/waitNotice-B8D8WhbE.js.map +0 -1
  104. package/dist/assets/words-jYy7lTcb.js.map +0 -1
@@ -1,17 +1,17 @@
1
1
  import { n as traceJoin } from "./joinTrace-CjRDFy85.js";
2
- import { $a as wireReaction, $c as appViewOf, $i as emptyIdentityLedger, $l as TURN_SETTLE_MS, $n as parseEngineError, $o as LIMITS, $r as pinIsNewer, $s as readHandoffPake, $t as PaymentPreflightError, A as knockIdentity, Ac as takeRequest, Al as createDeviceInvite, An as cashuRequestPayload, Ao as MEMBER_KEY, Ar as mergeLobby, As as handoffAttemptFailed, Ba as parseLinkPreview, Bc as linkRecords, Bl as DEVICES_CAPABILITY, Bn as PICTURE_METADATA_LIMITS, Bo as ratchetSessionOf, Bs as handoffManifestFrames, Bu as sanitizeDisplayText, C as communityHasFrame, Cc as verifyEnrollProof, Ci as HOLD_LIMITS, Co as claimedTime, Cr as beaconKeys, Cs as HANDOFF_PIECE_BYTES, Cu as traceLink, D as decodeGroupEntryLink, Da as fileMessageText, Dc as newInbox, Di as newMailbox, Dl as createContactLink, Do as GROUP_ADMIN_OFF_ERROR, Dr as lobbyKeys, Ds as NO_ATTEMPTS, Du as PacketTooLargeError, Ec as inboxRecord, Ei as isHoldUrl, El as readCanonicalJson, Eo as shownTime, Er as freshHubs, Es as HANDOFF_VERIFIED, Eu as withRequestOptions, F as GroupWakeLimiter, Fa as REMOVED_TEXT, Fc as contactAskerHolds, Fl as decodeInviteCode, Fn as parseFedimintRequestPayload, Fo as verifyCommitSignature, Fr as readBeaconHead, Fs as handoffContextProof, Fu as identityFromSeedB64, Ga as REACTION_LIMITS, Gc as readLinkRecord, Gi as capsDescriptors, Gl as deviceKeyZ32, Gn as INVITE_TAKEN, Go as PRESENCE_WINDOW, Gs as handoffStreamKey, Gt as didDhtFromPublicKey, Gu as toBase64Url, H as GroupSession, Ha as readForwarded, Hc as mergeContactKnocks, Hl as HANDOFF_CAPABILITY, Hn as stripPictureMetadata, Hr as transferEnded, Hs as handoffPakeFrame, Hu as fromBase64Url, I as groupWakeFrame, Ia as RateWindow, Ic as contactDay, Il as encodeInviteCode, Io as edgeParams, Ir as readLobby, Is as handoffDataFrame, Iu as publicKeyFromZ32, Ja as queueReaction, Jc as APP_BUNDLE_LIMITS, Jl as newDeviceSetSecret, Jn as pairedMessageFits, Jo as presenceSeenAt, Jr as typingActivity, Js as readHandoffAck, Ju as utf8Encode, K as GROUP_EDIT_TEXT_BYTES, Ka as ReactionWindow, Kc as requestRecords, Ki as dialDescriptors, Kl as deviceLinkPairing, Kn as LIVENESS_PING_MS, Ko as RELAY_POLL_INTERVALS, Kr as TypingSender, Ks as handoffVersions, Kt as encodeDidDhtDeactivated, Ku as toZ32, L as groupWakes, La as dhtEditId, Lc as knockSlotIdentity, Ll as inviteLink, Ln as videoMetadataPatches, Lo as RATCHET_CAPABILITY, Lr as shouldBeHub, Ls as handoffDigest, Lu as verify, M as mergeKnocks, Ma as EDIT_BUFFER_MS, Mc as ContactRequestError, Ml as readDeviceInvite, Mn as findEndpoint, Mo as parseGroupCommit, Mr as pickHubs, Ms as handoffBusyFrame, N as readKnocks, Na as EDIT_RATE_WINDOW_MS, Nc as REQUEST_LIFETIME_MS, Nl as OwnInviteError, Nn as isFederationId, No as rosterAdmin, Nr as rankHubs, Ns as handoffCancelFrame, Nu as createIdentity, O as encodeGroupEntryLink, Oa as parseVoiceMeta, Oc as planKnocks, Oi as readManifest, Ol as encodeContactLink, On as decodeBolt11, Oo as GROUP_MEMBER_CAP, Or as lobbyRecords, Os as filePartName, Pa as MAX_REMOVAL_NUMBER, Pc as contactAskerFrame, Pl as createChatInvite, Pn as parseCashuRequestPayload, Po as rosterHas, Pr as readBeacon, Ps as handoffContext, Pu as identityFromSeed, Qa as validReactionNumber, Qc as appDigest, Ql as TURN_RAISE_READ_TIMEOUT_MS, Qn as engineText, Qo as webLocalFetch, Qr as nextPinNumber, Qs as readHandoffHello, Qt as ONCHAIN_PROVIDER, R as parseGroupWakeFrame, Rc as knockSlotOf, Rl as inviteOwnership, Rn as withoutVideoMetadata, Ro as RatchetBox, Rr as ChatFiles, Rs as handoffEphemeral, S as GROUP_READ_NOTE_COMMUNITY, Sc as readEnrollHello, Si as HOLD_DATED_BACK_MS, Sl as parseImageMeta, So as arrivalKey, Sr as COMMUNITY_TOPOLOGY, Ss as HANDOFF_PAKE, T as encodeCommunityLink, Tc as endedRequests, Ti as HoldRefusedError, To as receivedTimestamp, Tr as doorHubs, Ts as HANDOFF_TIMINGS, Tu as isDiscoveryBudgetError, U as frameBytes, Ua as COMMUNITY_REACTION_FRAME, Uc as openRequest, Ui as CapsExchange, Ul as deviceEchoFrame, Uo as DHT_POLL_INTERVALS, Ur as transferStalled, Us as handoffReleaseFrame, V as GROUP_READ_NOTE, Va as forwardedAgain, Vc as makeStampPaced, Vl as ENROLL_CAPABILITY, Vn as isStrippedPicture, Vo as DirectPathWatch, Vr as sentWhole, Vs as handoffOfferFrame, Vu as bytesEqual, Wa as GROUP_REACTION_FRAME, Wc as readKnockSlot, Wi as DHT_TEXT_CAPABILITY, Wl as deviceEchoNonce, Wn as GhostLink, Ws as handoffRetryAfter, Wt as didDhtDocument, Wu as randomBytes, X as mentionsMember, Xa as reactionIsNewer, Xc as APP_ICON_PATH, Xl as webCryptoSigner, Xn as EngineError, Xo as formatLocalTarget, Xr as PIN_LIMITS, Xs as readHandoffDone, Xt as ETHEREUM_USDT, Y as parseCommunityEdit, Ya as reactionEmoji, Yc as APP_BUNDLE_MAGIC, Yl as seedSigner, Yn as pairedMessageFrame, Yo as GhostlyHttpError, Ys as readHandoffCancel, Yt as signDidDhtPacket, Z as groupName, Za as readReaction, Zn as engineError, Zo as parseLocalTarget, Zr as mayPin, Zs as readHandoffHave, Zt as EVM_TEST_CHAINS, _ as groupTypingEpoch, _a as DHT_FILE_CAPABILITY, _c as enrollDoneFrame, _i as BUTTONS_CAPABILITY, _l as readAppRevocationShape, _n as isPubkyKey, _r as readGroupSignal, _s as HANDOFF_CANCEL, _t as isAtprotoDid, _u as RelayTransport, a as appRevocationFor, ac as readSetUpdate, ai as newWakeToken, al as readAppBundleAsync, an as arkAddressPrefix, ar as groupFileFallback, au as nextTurnPosition, b as COMMUNITY_LIMITS, ba as sanitizeFileName, bc as enrollProofFrame, bi as UPGRADE_CAPABILITY, br as meshHubs, bs as HANDOFF_HELLO, bu as currentRelays, c as checkAppBeforeRun, ca as emptyProofLedger, cc as signTombstone, ci as wakeRequest, cl as APP_STATEMENT_LIMITS, cn as formatPaymentAmount, cs as contactRtcConfig, cu as signTurnRelease, da as automaticTransport, di as APP_RANGE_LIMITS, dl as appRefPublisher, dn as SPARK_NETWORKS, do as STATUS_CARD_LIMITS, dr as CarriedTransport, du as turnName, ec as readHandoffTurnFrame, ei as pinNumberHolds, en as SEPOLIA_TEST_USDT, eo as pairedReplyAuthor, er as GROUP_FILE_LIMITS, es as decodeControl, eu as classifyTurnRead, fi as isServeId, fn as SPARK_PROVIDER, fs as emptyLinkRecords, fu as turnStatedVerifier, g as GroupTypingBoard, ga as peekDhtMailbox, gc as enrollDigits, gi as APPS_CAPABILITY, gl as readAppRevocation, gr as groupSignalFrame, gs as HANDOFF_ACK, ha as DHT_MESSAGE_TTL, hc as enrollCancelReason, hi as isAppVersion, hl as isAppRef, hn as isBitcoinAddress, hs as serviceIdFromName, i as addedAppPermissions, ia as receivedIdentityStatus, ii as deviceWakeRequest, in as WALLET_NETWORKS, iu as firstDeviceSetSecret, j as knockRecords, ja as parseVideoMeta, jc as turnOff, jl as deviceInviteJoinerParams, jn as fedimintRequestPayload, jo as commitHash, jr as newerHead, js as handoffAttemptSucceeded, k as entryParams, kc as settleRequest, kl as readContactLink, kn as ENDPOINT, kr as mergeBeacon, ks as handoffAttemptAllowed, ku as createRelayPayload, l as planAppUpdate, la as validExternalKey, lc as verifySetUpdate, li as checkPushEndpoint, ll as appFingerprint, ln as validatePaymentTarget, lu as turnInstance, mc as enrollCancelFrame, mi as chatAppId, ml as isAppKey, mn as sparkInvoiceDetails, ms as LEGACY_SERVICES, mu as DEFAULT_RELAYS, n as readX401SdJwtVc, nc as sealHandoffPiece, ni as WAKE_CALL_INTERVAL_MS, nl as isAppUrl, nn as TEST_USDT_FAUCET_AMOUNT, no as replySnippet, nu as TURN_LAST_SEQUENCE, o as appStoreDecision, oa as lastSharedWithMe, oc as setAckFrame, oi as parseWakeFrame, ol as sha256Paced, on as assertTokenUnits, ou as readTurnPacket, p as readAppStoreSteps, pl as isAppHash, pn as sparkAddressKind, ps as HTTP_SERVICE_PROTO, pu as turnVerifierMark, q as carryMentions, qa as nextReactionNumber, qc as seenEntry, ql as devicePingFrame, qn as PAIRED_FRAME_TOO_LARGE, qo as WATCH_PEER_MS, qs as newHandoffId, qt as encodeDidDhtPacket, qu as utf8Decode, r as sameX401HolderJwk, ri as WakeLimiter, rl as pacer, rn as USDT_PUBLIC_RPC, ro as BUTTON_ID, rs as RTC_CONFIG, ru as TURN_MAX, s as appUpdateDecision, sa as PeerProofs, sc as setUpdateFrame, si as relayRequest, sn as assertWholeSats, sr as readGroupFileMeta, su as signTurnPacket, t as newX401HolderKey, tc as readHandoffVerified, ti as readPin, to as readReply, tr as GROUP_HAVE_FRAME, ts as encodeControl, tu as turnPutSummary, u as APP_STORE_LIMITS, ua as TRANSPORTS, ui as vapidKeysMatch, ul as appRef, un as walletNetworkOf, us as parseCallSignal, uu as turnKeys, v as openGroupTyping, va as dhtFileId, vc as enrollGrantFrame, vi as EDIT_CAPABILITY, vo as checkStatusCard, vr as MESH_HUBS, vs as HANDOFF_DONE, vt as normalizeAtprotoHandle, w as decodeCommunityLink, wc as clearMissed, wi as HoldKeys, wl as canonicalJson, wo as heardTime, wr as beaconRecords, ws as HANDOFF_REQUEST, wu as budgetRetryMs, x as CommunitySession, xa as sanitizeMime, xc as readEnrollGrant, xi as HOLD_CAPABILITY, xo as statusCardText, xr as pickMeshHubs, xs as HANDOFF_OFFER, xu as normalizeRelayUrl, y as sealGroupTyping, ya as formatFileSize, yc as enrollHelloFrame, yi as STATUS_CARD_CAPABILITY, yo as sameButtonText, yr as mayBeHub, ys as HANDOFF_HAVE, z as GROUP_LIMITS, zc as knockSlotRecords, zn as NO_PICTURE_METADATA, zo as emptyRatchetState, zr as FILE_LIMITS, zs as handoffHelloFrame, zu as sanitizeAvatar } from "./src-DZagapGt.js";
2
+ import { $a as reactionEmoji, $c as requestRecords, $i as HoldKeys, $l as deviceLinkPairing, $n as engineError, $o as presenceSeenAt, $r as PIN_LIMITS, $s as handoffVersions, $t as ONCHAIN_PROVIDER, A as knockIdentity, Ac as verifyEnrollProof, An as ENDPOINT, Ao as shownTime, Ar as lobbyKeys, As as HANDOFF_PIECE_BYTES, Ba as RateWindow, Bc as REQUEST_LIFETIME_MS, Bl as OwnInviteError, Bn as NO_PICTURE_METADATA, Bo as edgeParams, Br as shouldBeHub, Bs as handoffCancelFrame, C as communityHasFrame, Ca as formatFileSize, Cc as enrollDigits, Ci as UPGRADE_CAPABILITY, Cl as readAppRevocation, Co as sameButtonText, Cr as pickMeshHubs, Cs as HANDOFF_ACK, D as decodeGroupEntryLink, Dc as enrollProofFrame, Di as dialDescriptors, Do as claimedTime, Dr as doorHubs, Ds as HANDOFF_HELLO, Du as currentRelays, Ec as enrollHelloFrame, Ei as capsDescriptors, Eo as arrivalKey, Er as beaconRecords, Es as HANDOFF_HAVE, F as GroupWakeLimiter, Fa as parseVideoMeta, Fc as planKnocks, Fl as encodeContactLink, Fn as parseCashuRequestPayload, Fo as commitHash, Fr as pickHubs, Fs as filePartName, Fu as PacketTooLargeError, Ga as forwardedAgain, Gc as knockSlotOf, Gi as TRANSPORTS, Gl as inviteOwnership, Gn as GhostLink, Go as DirectPathWatch, Gr as transferEnded, Gs as handoffEphemeral, Gt as didDhtDocument, Gu as verify, H as GroupSession, Hc as contactAskerHolds, Hi as PeerProofs, Hl as decodeInviteCode, Hn as isStrippedPicture, Ho as RatchetBox, Hr as FILE_LIMITS, Hs as handoffContextProof, Hu as identityFromSeed, I as groupWakeFrame, Ia as EDIT_BUFFER_MS, Ic as settleRequest, Il as readContactLink, In as parseFedimintRequestPayload, Io as parseGroupCommit, Ir as rankHubs, Is as handoffAttemptAllowed, J as meshMessageRef, Ja as GROUP_REACTION_FRAME, Jc as makeStampPaced, Jl as ENROLL_CAPABILITY, Jn as PAIRED_FRAME_TOO_LARGE, Jo as DHT_POLL_INTERVALS, Js as handoffOfferFrame, Jt as encodeDidDhtPacket, Ju as hasVisible, K as GROUP_EDIT_TEXT_BYTES, Ka as readForwarded, Kc as knockSlotRecords, Ki as automaticTransport, Kn as INVITE_TAKEN, Kr as transferStalled, Ks as handoffHelloFrame, Kt as didDhtFromPublicKey, L as groupWakes, La as EDIT_RATE_WINDOW_MS, Lc as takeRequest, Ll as createDeviceInvite, Lo as rosterAdmin, Lr as readBeacon, Ls as handoffAttemptFailed, Lu as createRelayPayload, M as mergeKnocks, Ma as parseVoiceMeta, Mc as endedRequests, Mn as fedimintRequestPayload, Mo as GROUP_MEMBER_CAP, Mr as mergeBeacon, Ms as HANDOFF_TIMINGS, Mu as budgetRetryMs, N as readKnocks, Nc as inboxRecord, Nl as readCanonicalJson, Nn as findEndpoint, Nr as mergeLobby, Ns as HANDOFF_VERIFIED, Nu as isDiscoveryBudgetError, O as encodeGroupEntryLink, Oc as readEnrollGrant, Oo as heardTime, Or as freshHubs, Os as HANDOFF_OFFER, Ou as normalizeRelayUrl, Pc as newInbox, Pi as emptyIdentityLedger, Pl as createContactLink, Pn as isFederationId, Po as MEMBER_KEY, Pr as newerHead, Ps as NO_ATTEMPTS, Pu as withRequestOptions, Qa as queueReaction, Qc as readLinkRecord, Qi as HOLD_LIMITS, Ql as deviceKeyZ32, Qn as EngineError, Qo as WATCH_PEER_MS, Qs as handoffStreamKey, Qt as EVM_TEST_CHAINS, Qu as fromBase64Url, R as parseGroupWakeFrame, Ra as MAX_REMOVAL_NUMBER, Rc as turnOff, Rl as deviceInviteJoinerParams, Rn as videoMetadataPatches, Ro as rosterHas, Rr as readBeaconHead, Rs as handoffAttemptSucceeded, S as GROUP_READ_NOTE_COMMUNITY, Sa as dhtFileId, Sc as enrollCancelReason, Si as STATUS_CARD_CAPABILITY, Sl as isAppRef, So as checkStatusCard, Sr as meshHubs, Ss as serviceIdFromName, T as encodeCommunityLink, Ta as sanitizeMime, Tc as enrollGrantFrame, Ti as DHT_TEXT_CAPABILITY, To as statusCardText, Tr as beaconKeys, Ts as HANDOFF_DONE, U as frameBytes, Uc as contactDay, Ui as emptyProofLedger, Ul as encodeInviteCode, Un as stripPictureMetadata, Uo as emptyRatchetState, Us as handoffDataFrame, Uu as identityFromSeedB64, V as GROUP_READ_NOTE, Va as dhtEditId, Vc as contactAskerFrame, Vi as lastSharedWithMe, Vl as createChatInvite, Vn as PICTURE_METADATA_LIMITS, Vo as RATCHET_CAPABILITY, Vr as ChatFiles, Vs as handoffContext, Vu as createIdentity, Wa as parseLinkPreview, Wc as knockSlotIdentity, Wi as validExternalKey, Wl as inviteLink, Wo as ratchetSessionOf, Wr as sentWhole, Ws as handoffDigest, Wu as publicKeyFromZ32, X as mentionsMember, Xa as ReactionWindow, Xc as openRequest, Xi as HOLD_CAPABILITY, Xl as deviceEchoFrame, Xn as pairedMessageFits, Xo as PRESENCE_WINDOW, Xs as handoffReleaseFrame, Xt as signDidDhtPacket, Xu as stripHidden, Y as parseCommunityEdit, Ya as REACTION_LIMITS, Yc as mergeContactKnocks, Yl as HANDOFF_CAPABILITY, Yn as pairedEditFits, Yr as TypingSender, Ys as handoffPakeFrame, Yu as sanitizeDisplayText, Z as groupName, Za as nextReactionNumber, Zc as readKnockSlot, Zi as HOLD_DATED_BACK_MS, Zl as deviceEchoNonce, Zn as pairedMessageFrame, Zo as RELAY_POLL_INTERVALS, Zr as typingActivity, Zs as handoffRetryAfter, Zt as ETHEREUM_USDT, Zu as bytesEqual, _ as groupTypingEpoch, _i as chatAppId, _l as appRef, _s as parseCallSignal, _t as isAtprotoDid, _u as turnKeys, a as appRevocationFor, ac as readHandoffHello, ai as WAKE_CALL_INTERVAL_MS, al as appDigest, an as WALLET_NETWORKS, ao as readReply, as as decodeControl, au as TURN_RAISE_READ_TIMEOUT_MS, b as COMMUNITY_LIMITS, ba as peekDhtMailbox, bi as BUTTONS_CAPABILITY, bl as isAppHash, br as MESH_HUBS, bs as HTTP_SERVICE_PROTO, bu as turnVerifierMark, c as checkAppBeforeRun, cc as readHandoffVerified, ci as newWakeToken, cn as assertWholeSats, cu as turnPutSummary, di as wakeRequest, dn as walletNetworkOf, du as firstDeviceSetSecret, ea as HoldRefusedError, ec as newHandoffId, ed as randomBytes, ei as mayPin, el as seenEntry, en as PaymentPreflightError, eo as reactionIsNewer, er as engineText, es as GhostlyHttpError, eu as devicePingFrame, fc as readSetUpdate, fi as checkPushEndpoint, fl as readAppBundleAsync, fn as SPARK_NETWORKS, fu as nextTurnPosition, g as GroupTypingBoard, gc as verifySetUpdate, gl as appFingerprint, gn as isBitcoinAddress, gu as turnInstance, hc as signTombstone, hi as isServeId, hl as APP_STATEMENT_LIMITS, hn as sparkInvoiceDetails, ho as STATUS_CARD_LIMITS, hs as contactRtcConfig, hu as signTurnRelease, i as addedAppPermissions, ic as readHandoffHave, id as utf8Encode, ii as readPin, in as USDT_PUBLIC_RPC, io as pairedReplyAuthor, is as LIMITS, j as knockRecords, ja as fileMessageText, jc as clearMissed, jl as canonicalJson, jn as cashuRequestPayload, jo as GROUP_ADMIN_OFF_ERROR, jr as lobbyRecords, js as HANDOFF_REQUEST, ju as traceLink, k as entryParams, kc as readEnrollHello, kl as parseImageMeta, kn as decodeBolt11, ko as receivedTimestamp, kr as hubRank, ks as HANDOFF_PAKE, l as planAppUpdate, lc as sealHandoffPiece, li as parseWakeFrame, ll as isAppUrl, ln as formatPaymentAmount, lr as readGroupFileMeta, lu as TURN_LAST_SEQUENCE, mc as setUpdateFrame, mi as APP_RANGE_LIMITS, mn as sparkAddressKind, mu as signTurnPacket, n as readX401SdJwtVc, na as newMailbox, nc as readHandoffCancel, nd as toZ32, ni as pinIsNewer, nl as APP_BUNDLE_MAGIC, no as validReactionNumber, nr as GROUP_FILE_LIMITS, ns as parseLocalTarget, nu as seedSigner, o as appStoreDecision, oc as readHandoffPake, oi as WakeLimiter, ol as appViewOf, on as arkAddressPrefix, oo as replySnippet, os as encodeControl, ou as TURN_SETTLE_MS, p as readAppStoreSteps, pc as setAckFrame, pi as vapidKeysMatch, pl as sha256Paced, pn as SPARK_PROVIDER, pr as CarriedTransport, pu as readTurnPacket, q as carryMentions, qa as COMMUNITY_REACTION_FRAME, qc as linkRecords, ql as DEVICES_CAPABILITY, qn as LIVENESS_PING_MS, qs as handoffManifestFrames, qt as encodeDidDhtDeactivated, qu as sanitizeAvatar, r as sameX401HolderJwk, ra as readManifest, rc as readHandoffDone, rd as utf8Decode, ri as pinNumberHolds, rn as TEST_USDT_FAUCET_AMOUNT, ro as wireReaction, rr as GROUP_HAVE_FRAME, rs as webLocalFetch, ru as webCryptoSigner, s as appUpdateDecision, sc as readHandoffTurnFrame, si as deviceWakeRequest, sn as assertTokenUnits, so as BUTTON_ID, sr as groupFileFallback, su as classifyTurnRead, t as newX401HolderKey, ta as isHoldUrl, tc as readHandoffAck, td as toBase64Url, ti as nextPinNumber, tl as APP_BUNDLE_LIMITS, tn as SEPOLIA_TEST_USDT, to as readReaction, tr as parseEngineError, ts as formatLocalTarget, tu as newDeviceSetSecret, u as APP_STORE_LIMITS, ui as relayRequest, ul as pacer, un as validatePaymentTarget, us as RTC_CONFIG, uu as TURN_MAX, v as openGroupTyping, vi as isAppVersion, vl as appRefPublisher, vn as isPubkyKey, vr as groupSignalFrame, vt as normalizeAtprotoHandle, vu as turnName, w as decodeCommunityLink, wa as sanitizeFileName, wc as enrollDoneFrame, wi as CapsExchange, wl as readAppRevocationShape, wr as COMMUNITY_TOPOLOGY, ws as HANDOFF_CANCEL, wu as RelayTransport, x as CommunitySession, xa as DHT_FILE_CAPABILITY, xc as enrollCancelFrame, xi as EDIT_CAPABILITY, xl as isAppKey, xr as mayBeHub, xs as LEGACY_SERVICES, xu as DEFAULT_RELAYS, y as sealGroupTyping, ya as DHT_MESSAGE_TTL, yi as APPS_CAPABILITY, yr as readGroupSignal, ys as emptyLinkRecords, yu as turnStatedVerifier, z as GROUP_LIMITS, za as REMOVED_TEXT, zc as ContactRequestError, zi as receivedIdentityStatus, zl as readDeviceInvite, zn as withoutVideoMetadata, zo as verifyCommitSignature, zr as readLobby, zs as handoffBusyFrame } from "./src-D31D1_oY.js";
3
3
  import { i as SourceUnreachableError, n as PROVIDER_PLATFORMS, o as isNothingSpentError, r as SourceConfigError, t as NothingSpentError, u as redact } from "./types-C4_KafL_.js";
4
4
  import { t as bitcoindRpc } from "./bitcoindProvider-DGw3xBSa.js";
5
- import { t as nwc } from "./nwcProvider-BlkPOJen.js";
5
+ import { t as nwc } from "./nwcProvider-CfpbNUf7.js";
6
6
  import { a as clearProfileStores, c as deleteDatabase, d as newestWalletTx, f as openDb, g as wrap, h as transact, i as STORES$1, l as errorLine, m as store, n as APP_STORAGE_SCOPE_INDEX, o as committed, p as profileOpenFailure, r as CARD_INDEX, s as databaseName, t as APP_STORAGE_CHAT_INDEX, u as fileStore } from "./idb-BHsAqENE.js";
7
- import { a as sealSeed, i as newDeviceKey, o as unsealSeed, r as intentRepository } from "./networkReason-MInk1Y63.js";
8
- import { $ as breezDatabasesFor, A as IdentityProofs, B as cardsKey, C as FileAppender, D as streamStored, E as storedSize, F as takesUnsealed, G as INVOICE_PACE, H as normalizePhrase, I as whenDataKeyDropped, J as sourceKey, K as nextInvoiceAsk, L as isSealedField, M as openSecret, N as sealPlace, P as sealSecret, Q as breezDatabaseInUse, R as CASHU_CARD, S as WALLET_TYPES, T as removeStored, U as journaledPayment, V as isRecoveryPhrase, W as lightningPaying, X as cashuMint, Y as CASHU_MINT_SOURCE, Z as breezDatabase, _ as crossNetwork, a as storedGroupFiles, at as ModeGate, b as walletInstances, c as receivedPairedReply, ct as awayFrom, d as paymentAlias, dt as setAwayWallets, et as dropBreezDatabase, f as paymentWireId, ft as setSingleWriterGate, g as createTiming, h as createFailure, i as groupOfFile, it as ModeChanged, j as hasDataKey, l as replyRef, lt as refuseAway, m as assertConfirmedReal, n as groupFileId, nt as iceServerSetting, o as groupReply, ot as WrongNetworkError, p as WALLET_NAMES, q as ProviderSources, r as groupFileText, rt as relayOnlyProblem, s as pairedWireReply, st as networkLabel, t as GroupFileDesk, tt as iceServerProblem, u as replyTo, ut as requireTurn, v as paymentNetwork, w as readStored$1, y as paymentNetworksOf, z as LightningCards } from "./groupFiles-NonOYBKN.js";
9
- import { a as fedimintDatabase, i as onPublicIrohRelay, n as createIrohWebEndpoint, r as irohRelayProblem, s as loadFedimintSdk, t as DEFAULT_IROH_RELAYS } from "./irohWeb-C9ChbD-c.js";
7
+ import { a as sealSeed, c as openRow, d as sealedStore, f as openSecret, i as newDeviceKey, l as openRows, m as whenDataKeyDropped, o as unsealSeed, p as sealSecret, r as intentRepository, s as RowSeals, u as sealRow } from "./networkReason-CfpO9ayz.js";
8
+ import { $ as ModeGate, A as IdentityProofs, B as AskBackoff, C as FileAppender, D as streamStored, E as storedSize, F as normalizePhrase, G as breezDatabase, H as sourceKey, I as journaledPayment, J as dropBreezDatabase, K as breezDatabaseInUse, L as lightningPaying, M as LightningCards, N as cardsKey, P as isRecoveryPhrase, Q as ModeChanged, R as INVOICE_PACE, S as WALLET_TYPES, T as removeStored, U as CASHU_MINT_SOURCE, V as ProviderSources, W as cashuMint, X as iceServerSetting, Y as iceServerProblem, Z as relayOnlyProblem, _ as crossNetwork, a as storedGroupFiles, at as setAwayWallets, b as walletInstances, c as receivedPairedReply, d as paymentAlias, et as WrongNetworkError, f as paymentWireId, g as createTiming, h as createFailure, i as groupOfFile, it as requireTurn, j as CASHU_CARD, l as replyRef, m as assertConfirmedReal, n as groupFileId, nt as awayFrom, o as groupReply, ot as setSingleWriterGate, p as WALLET_NAMES, q as breezDatabasesFor, r as groupFileText, rt as refuseAway, s as pairedWireReply, t as GroupFileDesk, tt as networkLabel, u as replyTo, v as paymentNetwork, w as readStored$2, y as paymentNetworksOf, z as nextInvoiceAsk } from "./groupFiles-DYopNE57.js";
9
+ import { a as fedimintDatabase, i as onPublicIrohRelay, n as createIrohWebEndpoint, r as irohRelayProblem, s as loadFedimintSdk, t as DEFAULT_IROH_RELAYS } from "./irohWeb-C-2oslSU.js";
10
10
  import { c as isTestMint, d as mintUrlSpelling, f as paysItsOwnInvoices, l as isWorthlessMint, n as DEFAULT_MINTS, o as fakesLightning, r as TEST_MINT, t as BITCOIN_INVOICE_ON_TESTNET, u as mintNetwork } from "./mints-j5XAOk4f.js";
11
- import { a as registeredLightningProviders, c as boundedIdentityFetch, d as testSwitch, n as setOwnDidSource, o as registeredOnchainProviders, r as onAdaptersChanged, s as reserveAdapterIds, u as testBuild } from "./ownDid-yXtY_1B5.js";
12
- import { n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-CugS9qwQ.js";
13
- import { d as chosenResolver, r as resolveAtprotoDid, t as assertPublicServer } from "./resolve-Dtzogt2W.js";
11
+ import { a as registeredLightningProviders, c as boundedIdentityFetch, d as testSwitch, n as setOwnDidSource, o as registeredOnchainProviders, r as onAdaptersChanged, s as reserveAdapterIds, u as testBuild } from "./ownDid-DJFZM2cV.js";
12
+ import { d as chosenResolver, r as resolveAtprotoDid, t as assertPublicServer } from "./resolve-CDD4X68j.js";
14
13
  import { c as fileSpace, f as FILE_BYTES_STEP, o as fileBytes, r as blobDigest, s as fileBytesOf, u as removeFileBytes } from "./fileBytes-DjBYYyXT.js";
14
+ import { n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-C3yFCQa-.js";
15
15
  import { t as hyperdhtRelayProblem } from "./hyperdhtRelay-1wzya_0L.js";
16
16
  import { sha256 } from "@noble/hashes/sha2.js";
17
17
  import { hkdf } from "@noble/hashes/hkdf.js";
@@ -199,7 +199,7 @@ function viewNews(before, after) {
199
199
  //#endregion
200
200
  //#region ../browser/src/engine/paymentAdapters/usdtWallet.ts
201
201
  /** The Ethereum libraries, a large part of the app: loaded once a USDT wallet is made, opened or restored, not with the engine. */
202
- var loadUsdt = () => import("./usdt-BU4ezonh.js");
202
+ var loadUsdt = () => import("./usdt-DwHqp625.js");
203
203
  /** Every new profile starts with this wallet: an address to receive on, nothing to set up. */
204
204
  var DEFAULT_USDT = {
205
205
  network: "ethereum",
@@ -686,7 +686,7 @@ async function restoreArkDatabase(walletId, snapshot) {
686
686
  //#endregion
687
687
  //#region ../browser/src/engine/paymentAdapters/arkWallet.ts
688
688
  /** The Ark SDK, a large part of the app: loaded once an Ark wallet is made, opened or restored, not with the engine. */
689
- var loadArkade = () => import("./arkade-DOWpA2Kr.js");
689
+ var loadArkade = () => import("./arkade-BmxJTa65.js");
690
690
  /** How long a Testnet wallet about to make way for another waits for its server to say what it holds. */
691
691
  var RETIRE_READ_MS = 1e4;
692
692
  /** Every new profile starts with this wallet: nothing to set up before receiving. */
@@ -2414,15 +2414,25 @@ var FedimintWallet = class {
2414
2414
  }
2415
2415
  return null;
2416
2416
  }
2417
- /** Redeems notes into the federation that issued them. `done` once the ecash is ours; `failed` when they were spent. */
2417
+ /**
2418
+ * Redeems notes into the federation that issued them. `done` once the ecash is ours; `failed` when they were spent.
2419
+ * `error`: the redeem was asked for, but the client could not say how it stands (its operation is kept, to ask again).
2420
+ */
2418
2421
  async redeemNotes(federationId, notes, ghostly, waitMs = 6e4) {
2419
2422
  const client = this.client(federationId);
2420
2423
  const operationId = await client.redeem(notes.trim(), ghostly);
2421
- const state = await client.redeemState(operationId, waitMs);
2424
+ const { state, error } = await client.redeemState(operationId, waitMs).then((state) => ({
2425
+ state,
2426
+ error: void 0
2427
+ }), (e) => ({
2428
+ state: void 0,
2429
+ error: e instanceof Error ? e.message : String(e)
2430
+ }));
2422
2431
  this.refresh();
2423
2432
  return {
2424
2433
  operationId,
2425
- state
2434
+ state,
2435
+ error
2426
2436
  };
2427
2437
  }
2428
2438
  async redeemState(federationId, operationId, waitMs) {
@@ -2432,7 +2442,8 @@ var FedimintWallet = class {
2432
2442
  async receiveNotes(notes) {
2433
2443
  const found = await this.inspectNotes(notes);
2434
2444
  if (!found) throw new Error(this.clients.size ? "These notes are not from a federation you joined in this wallet" : "Join the federation these notes are from first");
2435
- const { state } = await this.redeemNotes(found.federation, notes, `wallet-${crypto.randomUUID()}`);
2445
+ const { state, error } = await this.redeemNotes(found.federation, notes, `wallet-${crypto.randomUUID()}`);
2446
+ if (error !== void 0) throw engineError("fedimintRedeemUnheard");
2436
2447
  if (state === "failed") throw new Error("These notes were already redeemed by someone");
2437
2448
  if (state !== "done") throw new Error("The federation is still redeeming these notes: they will show in the balance");
2438
2449
  return {
@@ -3602,6 +3613,14 @@ function mintRefused(error) {
3602
3613
  if (error.name === "StaleKeysetError") return mintRefused(error.cause);
3603
3614
  return error.name === "MintOperationError" && "code" in error;
3604
3615
  }
3616
+ /**
3617
+ * The mint refused outputs for their keyset: one it retired, or does not know, since they were made. No request with
3618
+ * those outputs is ever signed; new ones on the keyset it signs with now can be. cashu-ts says it in its own English,
3619
+ * which is never shown to a person.
3620
+ */
3621
+ function keysetRefused(error) {
3622
+ return error instanceof Error && error.name === "StaleKeysetError" && mintRefused(error);
3623
+ }
3605
3624
  var NEVER_REACHED_MINT = "The payment never reached the mint: nothing was sent, and the sats are back in your wallet. You can pay again.";
3606
3625
  var CashuAdapter = class {
3607
3626
  wallet;
@@ -6497,7 +6516,7 @@ function fakeInvoice(amount, paymentHash, memo = "", expirySeconds = 3600) {
6497
6516
  }
6498
6517
  /** A valid regtest P2WPKH address of nobody's. */
6499
6518
  var fakeAddress = () => bech32.encode("bcrt", [0, ...bech32.toWords(random$1(20))]);
6500
- var FIELDS$1 = [
6519
+ var FIELDS = [
6501
6520
  {
6502
6521
  name: "alias",
6503
6522
  label: "Name",
@@ -6725,7 +6744,7 @@ var fakeLightning = {
6725
6744
  description: "In-memory regtest node for tests. Holds nothing.",
6726
6745
  networks: ["regtest"],
6727
6746
  platforms: ["web", "desktop"],
6728
- fields: FIELDS$1,
6747
+ fields: FIELDS,
6729
6748
  experimental: true,
6730
6749
  validate,
6731
6750
  async create(settings) {
@@ -6739,7 +6758,7 @@ var fakeOnchain = {
6739
6758
  description: "In-memory regtest wallet for tests. Holds nothing.",
6740
6759
  networks: ["regtest"],
6741
6760
  platforms: ["web", "desktop"],
6742
- fields: FIELDS$1,
6761
+ fields: FIELDS,
6743
6762
  experimental: true,
6744
6763
  validate,
6745
6764
  async create(settings) {
@@ -7270,7 +7289,7 @@ var ContactLinks = class {
7270
7289
  */
7271
7290
  shown() {
7272
7291
  this.shownAt = Date.now();
7273
- this.schedulePoll(0);
7292
+ this.schedulePoll(this.pollDue());
7274
7293
  }
7275
7294
  /** Whether a link key is one of this profile's, current or turned off. */
7276
7295
  owns(linkKeyZ32) {
@@ -7308,9 +7327,19 @@ var ContactLinks = class {
7308
7327
  decline(id) {
7309
7328
  return this.serial(() => this.settle(id));
7310
7329
  }
7311
- /** Reads the knock slots once and takes what is new into Requests. */
7330
+ /**
7331
+ * Reads the knock slots once and takes what is new into Requests. Never faster than the link's fastest pace: within
7332
+ * `POLL_SHOWN_MS` of the last read, what that read took is the answer.
7333
+ */
7312
7334
  poll() {
7313
- return this.serial(() => this.take());
7335
+ return this.serial(async () => {
7336
+ if (this.pollDue() === 0) await this.take();
7337
+ });
7338
+ }
7339
+ /** How long until the knock slots may be read again. */
7340
+ pollDue() {
7341
+ const since = Date.now() - (this.stored.current?.polled ?? -Infinity);
7342
+ return since >= 0 && since < 15e3 ? POLL_SHOWN_MS - since : 0;
7314
7343
  }
7315
7344
  /** Undefined while the profile has no link. */
7316
7345
  view() {
@@ -7440,7 +7469,8 @@ var ContactLinks = class {
7440
7469
  current: {
7441
7470
  ...latest,
7442
7471
  inbox,
7443
- requests
7472
+ requests,
7473
+ polled: now
7444
7474
  }
7445
7475
  });
7446
7476
  this.host.emit();
@@ -7789,7 +7819,8 @@ var ContactAsks = class {
7789
7819
  };
7790
7820
  function profileName(value) {
7791
7821
  if (typeof value !== "string" || value.length > 256) return;
7792
- return value.replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, "").trim().slice(0, 64) || void 0;
7822
+ const name = stripHidden(value).trim().slice(0, 64);
7823
+ return name && hasVisible(name) ? name : void 0;
7793
7824
  }
7794
7825
  var IMAGE_HOSTS = /* @__PURE__ */ new Set([
7795
7826
  "nostr.build",
@@ -8336,14 +8367,17 @@ var HEX64$1 = /^[a-f0-9]{64}$/;
8336
8367
  var UNSAFE = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f‪-‮⁦-⁩]/g;
8337
8368
  /** Longest string looked at before it is cut: a relay's frame is capped at 64 KiB anyway. */
8338
8369
  var MAX_TEXT_INPUT = 65536;
8339
- /** Plain text: no controls (newlines kept when `multiline`), no bidi overrides, trimmed, capped. */
8370
+ /**
8371
+ * Plain text: no controls (newlines kept when `multiline`), no bidi overrides, trimmed, capped. One line (a name, a
8372
+ * word) is held to core's rule for display text (`stripHidden`): no line or paragraph separator and no invisible or
8373
+ * direction-changing character either, and something visible or nothing.
8374
+ */
8340
8375
  function plainText(value, max, multiline = false) {
8341
8376
  if (typeof value !== "string" || value.length > MAX_TEXT_INPUT) return;
8342
- let text = value.replace(UNSAFE, "");
8343
- if (!multiline) text = text.replace(/[\r\n\t]+/g, " ");
8377
+ let text = multiline ? value.replace(UNSAFE, "") : stripHidden(value.replace(/[\r\n\t]+/g, " "));
8344
8378
  text = text.trim();
8345
8379
  if (text.length > max) text = text.slice(0, max);
8346
- return text || void 0;
8380
+ return text && (multiline || hasVisible(text)) ? text : void 0;
8347
8381
  }
8348
8382
  /** An https URL for a website or a picture, or nothing: never javascript:, data:, or a host with credentials. */
8349
8383
  function httpsUrl(value, max = 512) {
@@ -9200,7 +9234,7 @@ var HostNotContacted = class extends Error {};
9200
9234
  */
9201
9235
  function fixedHostsFetch(fetch) {
9202
9236
  return async (url, options) => {
9203
- const { fixedIdentityHosts } = await import("./fixedHosts-B4E4VrYE.js");
9237
+ const { fixedIdentityHosts } = await import("./fixedHosts-C6nCHjOa.js");
9204
9238
  const host = hostOf$1(url);
9205
9239
  if (!fixedIdentityHosts().has(host) && host !== hostOf$1("https://public.api.bsky.app") && host !== hostOf$1("https://nexus.pubky.app")) throw new HostNotContacted(`Hide my IP from contacts is on: ${host}, a server your contact chose, was not contacted`);
9206
9240
  return fetch(url, options);
@@ -9405,7 +9439,7 @@ var PUBLIC_PROFILE_READERS = {
9405
9439
  var KEY = "publicProfiles";
9406
9440
  /** Unused entries are dropped this often, so an expired proof's profile does not wait for the next change. */
9407
9441
  var PRUNE_MS = 6e5;
9408
- var keyOf$2 = (s) => `${s.provider}\n${s.subject}`;
9442
+ var keyOf$1 = (s) => `${s.provider}\n${s.subject}`;
9409
9443
  /**
9410
9444
  * The fetch an identity's public data is read with: a contact's, while Hide my IP from contacts is on, reaches only
9411
9445
  * hosts this app names, so a server the contact chose (their AT Protocol server) never learns this device's IP address.
@@ -9472,7 +9506,7 @@ var PublicProfiles = class {
9472
9506
  /** What a card shows for this identity; undefined with the setting off, for a provider without profiles, or never asked. */
9473
9507
  view(s) {
9474
9508
  if (!this.host.enabled() || !this.readers[s.provider]) return void 0;
9475
- const key = keyOf$2(s);
9509
+ const key = keyOf$1(s);
9476
9510
  const c = this.cache[key];
9477
9511
  const loading = this.inflight.has(key);
9478
9512
  const error = this.errors.get(key);
@@ -9505,7 +9539,7 @@ var PublicProfiles = class {
9505
9539
  async request(s) {
9506
9540
  const reader = this.readers[s.provider];
9507
9541
  if (!reader || !this.host.enabled() || !this.host.online() || !this.isEligible(s)) return;
9508
- const key = keyOf$2(s);
9542
+ const key = keyOf$1(s);
9509
9543
  const existing = this.inflight.get(key);
9510
9544
  if (existing) return existing;
9511
9545
  const c = this.cache[key];
@@ -9521,7 +9555,7 @@ var PublicProfiles = class {
9521
9555
  return task;
9522
9556
  }
9523
9557
  async ask(s, reader) {
9524
- const key = keyOf$2(s);
9558
+ const key = keyOf$1(s);
9525
9559
  const checkedAt = this.now;
9526
9560
  try {
9527
9561
  const data = await reader.read(s.subject, {
@@ -9570,7 +9604,7 @@ var PublicProfiles = class {
9570
9604
  /** Drops every profile whose identity is no longer eligible (expired, removed, withdrawn, revoked). */
9571
9605
  async prune() {
9572
9606
  if (!this.started) return;
9573
- const keep = new Set(this.host.eligible().map(keyOf$2));
9607
+ const keep = new Set(this.host.eligible().map(keyOf$1));
9574
9608
  const drop = Object.keys(this.cache).filter((k) => !keep.has(k));
9575
9609
  if (!drop.length) return;
9576
9610
  for (const k of drop) {
@@ -10097,7 +10131,7 @@ async function readPostImage(source, ctx) {
10097
10131
  var MAX_IMAGES_KEPT = 16;
10098
10132
  /** One ask, all its pages and hosts included. */
10099
10133
  var ASK_TIMEOUT_MS = 2e4;
10100
- var keyOf$1 = (s) => `${s.provider}\n${s.subject}`;
10134
+ var keyOf = (s) => `${s.provider}\n${s.subject}`;
10101
10135
  /**
10102
10136
  * A contact's verified identity's recent posts and follows, engine side (PUBLIC-PROFILES.md, "Posts and follows"):
10103
10137
  * asked one identity at a time when the reader chooses its card, only for a current, verified proof, only with Load
@@ -10196,7 +10230,7 @@ var PublicActivity = class {
10196
10230
  /** The identity's recent posts: the kept page when fresh, else asked; `more` adds the next page. */
10197
10231
  async loadPosts(s) {
10198
10232
  if (!this.allowed(s)) return null;
10199
- const key = keyOf$1(s);
10233
+ const key = keyOf(s);
10200
10234
  const kept = this.posts.get(key);
10201
10235
  if (kept) kept.used = Date.now();
10202
10236
  const fresh = kept && this.now - kept.fetchedAt < 600;
@@ -10251,7 +10285,7 @@ var PublicActivity = class {
10251
10285
  fetchedAt: 0
10252
10286
  };
10253
10287
  const following = new Set(g.following), followers = new Set(g.followers ?? []);
10254
- const theirList = (subject) => this.graphs.get(keyOf$1({
10288
+ const theirList = (subject) => this.graphs.get(keyOf({
10255
10289
  provider: s.provider,
10256
10290
  subject
10257
10291
  }));
@@ -10289,7 +10323,7 @@ var PublicActivity = class {
10289
10323
  */
10290
10324
  async loadGraph(s) {
10291
10325
  if (!this.allowed(s)) return null;
10292
- const key = keyOf$1(s);
10326
+ const key = keyOf(s);
10293
10327
  const { own, contacts } = this.known(s);
10294
10328
  const kept = this.graphs.get(key);
10295
10329
  if (kept) kept.used = Date.now();
@@ -10320,10 +10354,10 @@ var PublicActivity = class {
10320
10354
  /** One picture of a post already loaded, on the reader's tap; the source comes from the kept post, never the page. */
10321
10355
  async loadImage(s) {
10322
10356
  if (!this.allowed(s)) throw new Error("Public profiles are off, or this identity is no longer verified");
10323
- const post = this.posts.get(keyOf$1(s))?.posts.find((p) => p.id === s.postId);
10357
+ const post = this.posts.get(keyOf(s))?.posts.find((p) => p.id === s.postId);
10324
10358
  const image = Number.isSafeInteger(s.index) ? post?.images[s.index] : void 0;
10325
10359
  if (!image) throw new Error("That picture is no longer here: load the posts again");
10326
- const key = `${keyOf$1(s)}\n${s.postId}\n${s.index}`;
10360
+ const key = `${keyOf(s)}\n${s.postId}\n${s.index}`;
10327
10361
  const kept = this.images.get(key);
10328
10362
  if (kept) {
10329
10363
  kept.used = Date.now();
@@ -10354,7 +10388,7 @@ var PublicActivity = class {
10354
10388
  }
10355
10389
  /** Drops what belongs to identities that are no longer eligible (expired, removed, withdrawn, revoked). */
10356
10390
  prune() {
10357
- const keep = new Set(this.host.eligible().map(keyOf$1));
10391
+ const keep = new Set(this.host.eligible().map(keyOf));
10358
10392
  const owner = (k) => k.split("\n").slice(0, 2).join("\n");
10359
10393
  for (const map of [
10360
10394
  this.posts,
@@ -11168,30 +11202,30 @@ var REVOCATIONS_KEPT = {
11168
11202
  all: 1024
11169
11203
  };
11170
11204
  /**
11171
- * The revocations as kept, by reference, in the order they were last added to: read with nothing taken on trust but
11172
- * their signatures (checked before they were kept), so an entry that is not one of that app's publisher is none.
11205
+ * The revocations as kept, by reference, in the order they were last added to (`all`), and those of `ref` (`mine`), read
11206
+ * with nothing taken on trust but their signatures (checked before they were kept), so an entry that is not one of that
11207
+ * app's publisher is none. The other apps' lists are left as kept, unread: each is read when its own app asks (a
11208
+ * revocation's read is about 0.15 ms, and the 1024 kept at most held the page's thread 160 ms at every install screen).
11173
11209
  */
11174
- function keptRevocations(kept) {
11175
- const out = /* @__PURE__ */ new Map();
11176
- if (!Array.isArray(kept)) return out;
11177
- for (const entry of kept) {
11178
- if (!Array.isArray(entry) || !isAppRef(entry[0]) || !Array.isArray(entry[1])) continue;
11179
- const ref = entry[0];
11180
- const list = entry[1].flatMap((r) => {
11210
+ function keptRevocations(kept, ref) {
11211
+ const all = /* @__PURE__ */ new Map();
11212
+ if (Array.isArray(kept)) {
11213
+ for (const entry of kept) if (Array.isArray(entry) && isAppRef(entry[0]) && Array.isArray(entry[1]) && entry[1].length) all.set(entry[0], entry[1]);
11214
+ }
11215
+ return {
11216
+ mine: (all.get(ref) ?? []).flatMap((r) => {
11181
11217
  const read = readAppRevocationShape(r);
11182
11218
  return read.ok && read.revocation.statement.app === ref && read.revocation.signature.key === appRefPublisher(ref) ? [read.revocation] : [];
11183
- });
11184
- if (list.length) out.set(ref, list);
11185
- }
11186
- return out;
11219
+ }),
11220
+ all
11221
+ };
11187
11222
  }
11188
11223
  /** Queues, on the settings store of an open transaction, these revocations of `ref` kept with the others (each once). */
11189
11224
  function keepRevocations(settings, ref, add) {
11190
11225
  if (!add.length) return;
11191
11226
  const read = settings.get(APP_REVOCATIONS_KEY);
11192
11227
  read.onsuccess = () => {
11193
- const kept = keptRevocations(read.result);
11194
- const before = kept.get(ref) ?? [];
11228
+ const { mine: before, all: kept } = keptRevocations(read.result, ref);
11195
11229
  const merged = new Map(before.map((r) => [canonicalJson(r), r]));
11196
11230
  for (const r of add) if (r.statement.app === ref) merged.set(canonicalJson(r), r);
11197
11231
  if (merged.size === before.length) return;
@@ -11348,6 +11382,17 @@ function peekAppManifest(bytes) {
11348
11382
  return null;
11349
11383
  }
11350
11384
  }
11385
+ /** `length` bytes of a stored file from `at`, or null where it ends before them. */
11386
+ async function readStored$1(files, id, at, length) {
11387
+ const out = new Uint8Array(length);
11388
+ for (let done = 0; done < length;) {
11389
+ const part = await files.read(id, at + done, Math.min(FILE_BYTES_STEP, length - done));
11390
+ if (!part.length) return null;
11391
+ out.set(part, done);
11392
+ done += part.length;
11393
+ }
11394
+ return out;
11395
+ }
11351
11396
  /** Where a bundle's manifest ends, from its first bytes, or null when they are not a bundle's or name a manifest too long. */
11352
11397
  function peekManifestEnd(bytes) {
11353
11398
  const magic = utf8Encode(APP_BUNDLE_MAGIC);
@@ -11371,6 +11416,8 @@ var Apps = class {
11371
11416
  * page, in a chat's cards and in the composer's Apps is read without the whole bundle again.
11372
11417
  */
11373
11418
  icons = /* @__PURE__ */ new Map();
11419
+ /** Reads of an icon from its stored bundle under way, by digest: cards of one app drawn at once share one read. */
11420
+ iconReads = /* @__PURE__ */ new Map();
11374
11421
  /** What each `ref\0scope` holds, read once from its counter row and kept in step by the writes here. */
11375
11422
  usage = /* @__PURE__ */ new Map();
11376
11423
  queues = /* @__PURE__ */ new Map();
@@ -11437,6 +11484,11 @@ var Apps = class {
11437
11484
  nowS() {
11438
11485
  return Math.floor(this.now() / 1e3);
11439
11486
  }
11487
+ /** Checked less than `ms` ago. A mark ahead of the clock (the clock went back since) is not recent: it would stay so until the clock caught up. */
11488
+ checkedWithin(at, ms) {
11489
+ const age = at === void 0 ? -1 : this.now() - at;
11490
+ return age >= 0 && age < ms;
11491
+ }
11440
11492
  /**
11441
11493
  * Preloads the default stores (no request) and removes the bundles no record names (`sweepBundles`), then checks for
11442
11494
  * updates soon after start and every 24 hours.
@@ -11467,7 +11519,7 @@ var Apps = class {
11467
11519
  if (this.stopped) return;
11468
11520
  if (this.host.online()) {
11469
11521
  const apps = await this.installed();
11470
- const fresh = atStart && apps.length > 0 && apps.every((a) => a.checkedAt !== void 0 && this.now() - a.checkedAt < APP_CHECK_TIMINGS.freshMs);
11522
+ const fresh = atStart && apps.length > 0 && apps.every((a) => this.checkedWithin(a.checkedAt, APP_CHECK_TIMINGS.freshMs));
11471
11523
  if (apps.length && !fresh) await this.checkUpdates().catch(() => {});
11472
11524
  }
11473
11525
  if (!this.stopped) this.schedule(APP_CHECK_TIMINGS.everyMs);
@@ -11519,7 +11571,7 @@ var Apps = class {
11519
11571
  }
11520
11572
  /** The revocations of this app this profile verified and keeps (`APP_REVOCATIONS_KEY`), installed or not. */
11521
11573
  async keptRevocationsOf(ref) {
11522
- return keptRevocations(await wrap((await store(STORES$1.settings, "readonly")).get("appRevocations"))).get(ref) ?? [];
11574
+ return keptRevocations(await wrap((await store(STORES$1.settings, "readonly")).get(APP_REVOCATIONS_KEY)), ref).mine;
11523
11575
  }
11524
11576
  /**
11525
11577
  * The built-in apps this profile is offered (WISP 1200 § Built-in apps): shown with the installed ones, with nothing
@@ -11852,6 +11904,52 @@ var Apps = class {
11852
11904
  return reading;
11853
11905
  }
11854
11906
  /**
11907
+ * The installed bundle's `icon.png`, or null for none, read alone from where it lies in the stored bundle: an icon drawn
11908
+ * after a start reads and hashes its own bytes, not the whole bundle (up to 16 MiB, for every row of the Apps page at
11909
+ * once). What makes its bytes safe: the stored manifest's bytes must hash to the digest the record holds (where the
11910
+ * whole bundle, its signature and its icon were checked at install), and the icon's bytes to the SHA-256 that manifest
11911
+ * lists for it. The statement between them is not checked: a wrong length only moves where the icon is read from, and
11912
+ * those bytes fail the hash.
11913
+ */
11914
+ storedIcon(app) {
11915
+ const under = this.iconReads.get(app.digest);
11916
+ if (under) return under;
11917
+ const reading = (async () => {
11918
+ const files = await fileBytesOf(app.bytes);
11919
+ const id = bundleId(app.digest);
11920
+ const size = files ? await files.size(id) : null;
11921
+ if (!files || size === null) fail("needs-files", "This app's files are not on this device yet");
11922
+ const damaged = () => fail("damaged", "This app's stored files do not match what was installed");
11923
+ const first = await files.read(id, 0, Math.min(size, PEEK_FIRST_BYTES));
11924
+ const end = peekManifestEnd(first);
11925
+ if (end === null || end + 4 > size) damaged();
11926
+ const head = end + 4 <= first.length ? first : await readStored$1(files, id, 0, end + 4) ?? damaged();
11927
+ const manifestBytes = head.subarray(APP_BUNDLE_MAGIC.length + 4, end);
11928
+ if (appDigest(manifestBytes) !== app.digest) damaged();
11929
+ const manifest = JSON.parse(utf8Decode(manifestBytes));
11930
+ let at = end + 4 + new DataView(head.buffer, head.byteOffset, head.byteLength).getUint32(end);
11931
+ let listed;
11932
+ for (const f of manifest.files) {
11933
+ if (f.path === "icon.png") {
11934
+ listed = f;
11935
+ break;
11936
+ }
11937
+ at += f.size;
11938
+ }
11939
+ let icon = null;
11940
+ if (listed) {
11941
+ icon = at + listed.size <= size ? await readStored$1(files, id, at, listed.size) : null;
11942
+ if (!icon || toBase64Url(await sha256Paced(icon)) !== listed.sha256) damaged();
11943
+ }
11944
+ this.icons.set(app.digest, icon);
11945
+ return icon;
11946
+ })().finally(() => {
11947
+ this.iconReads.delete(app.digest);
11948
+ });
11949
+ this.iconReads.set(app.digest, reading);
11950
+ return reading;
11951
+ }
11952
+ /**
11855
11953
  * Apps running at once do not push each other's bundle out, which every `file` read would then read and check again
11856
11954
  * whole; one closed (or only drawn as an icon) goes once two newer ones are kept, at the next bundle read or hit.
11857
11955
  */
@@ -12022,7 +12120,8 @@ var Apps = class {
12022
12120
  sequence: s.equivocation.sequence,
12023
12121
  at: s.equivocation.at
12024
12122
  } },
12025
- ...s.problem && { problem: s.problem }
12123
+ ...s.problem && { problem: s.problem },
12124
+ ...s.problemStatus !== void 0 && { problemStatus: s.problemStatus }
12026
12125
  };
12027
12126
  }
12028
12127
  async listStores() {
@@ -12158,7 +12257,7 @@ var Apps = class {
12158
12257
  sequence: index.sequence,
12159
12258
  digest
12160
12259
  });
12161
- const { problem: _problem, ...rest } = record;
12260
+ const { problem: _problem, problemStatus: _status, ...rest } = record;
12162
12261
  switch (decision) {
12163
12262
  case "new":
12164
12263
  case "update": {
@@ -12245,16 +12344,18 @@ var Apps = class {
12245
12344
  const { read, copy } = await reads[i];
12246
12345
  const now = await this.storeRecord(s.key);
12247
12346
  if (!now || now.removed) continue;
12347
+ const { problemStatus: _status, ...unread } = now;
12248
12348
  let next = read.ok ? this.withIndex(now, read.store.index, read.store.digest) : {
12249
- ...now,
12250
- problem: read.reason
12349
+ ...unread,
12350
+ problem: read.reason,
12351
+ ..."status" in read && read.status !== void 0 && { problemStatus: read.status }
12251
12352
  };
12252
12353
  const fromCopy = copy?.ok ? this.withIndex(now, copy.store.index, copy.store.digest) : null;
12253
12354
  if (next.copyUrl !== void 0 && !next.problem) {
12254
12355
  const { copyUrl: _c, ...own } = next;
12255
12356
  next = own;
12256
12357
  } else if (fromCopy && fromCopy.problem !== "rollback" && next.problem !== "equivocation") next = fromCopy;
12257
- if (now === s && next.index === s.index && next.digest === s.digest && next.problem === s.problem && next.equivocation === s.equivocation && next.copyUrl === s.copyUrl) (await this.records()).set(s.key, next);
12358
+ if (now === s && next.index === s.index && next.digest === s.digest && next.problem === s.problem && next.equivocation === s.equivocation && next.problemStatus === s.problemStatus && next.copyUrl === s.copyUrl) (await this.records()).set(s.key, next);
12258
12359
  else await this.putStore(next);
12259
12360
  out.push(this.summary(next));
12260
12361
  }
@@ -12276,9 +12377,13 @@ var Apps = class {
12276
12377
  try {
12277
12378
  read = await this.readStoreAt(s.url, s.key, s, lastBehind);
12278
12379
  } catch (error) {
12279
- read = {
12380
+ read = error instanceof AppFetchError ? {
12381
+ ok: false,
12382
+ reason: error.code,
12383
+ ...error.status !== void 0 && { status: error.status }
12384
+ } : {
12280
12385
  ok: false,
12281
- reason: error instanceof AppFetchError ? error.code : "network"
12386
+ reason: "network"
12282
12387
  };
12283
12388
  }
12284
12389
  const behind = !read.ok || !!this.withIndex(s, read.store.index, read.store.digest).problem;
@@ -12378,6 +12483,10 @@ var Apps = class {
12378
12483
  await done(tx);
12379
12484
  }
12380
12485
  const revocations = [...await this.keptRevocationsOf(version.ref), ...read];
12486
+ const [installed, stores] = await Promise.all([this.app(version.ref), this.stores()]);
12487
+ const decision = installDecision(installed, version);
12488
+ const install = decision === "other-app" ? "new" : decision;
12489
+ const asks = install === "new" ? [...manifest.permissions] : install === "update" ? manifest.permissions.filter((p) => !installed.permissions.includes(p)) : [];
12381
12490
  for (const [d, s] of this.staged) if (this.now() - s.at > STAGED.ms) this.staged.delete(d);
12382
12491
  this.staged.delete(digest);
12383
12492
  while (this.staged.size >= STAGED.max) this.staged.delete(this.staged.keys().next().value);
@@ -12387,13 +12496,10 @@ var Apps = class {
12387
12496
  from,
12388
12497
  ...fromStore !== void 0 && { store: fromStore },
12389
12498
  revocations,
12499
+ asks,
12390
12500
  at: this.now()
12391
12501
  });
12392
12502
  if (!this.sweep) this.sweepStaged();
12393
- const [installed, stores] = await Promise.all([this.app(version.ref), this.stores()]);
12394
- const decision = installDecision(installed, version);
12395
- const install = decision === "other-app" ? "new" : decision;
12396
- const asks = install === "new" ? [...manifest.permissions] : install === "update" ? manifest.permissions.filter((p) => !installed.permissions.includes(p)) : [];
12397
12503
  const listedBy = this.listedBy(version.ref, stores);
12398
12504
  return {
12399
12505
  digest,
@@ -12414,9 +12520,11 @@ var Apps = class {
12414
12520
  /**
12415
12521
  * Installs the bundle `preview` fetched, once the person pressed Install: `grant` must hold every permission it asks
12416
12522
  * for (WISP 1200 § Permissions: none is granted by a store or a contact). A revoked or removed version is not
12417
- * installed; neither is a rollback, nor another bundle under an installed `sequence` (marked on the app).
12523
+ * installed; neither is a rollback, nor another bundle under an installed `sequence` (marked on the app). `asks` is
12524
+ * what the person's screen listed (`AppPreview.asks`; the last screen of this bundle when not given): what this install
12525
+ * adds to the record it writes over must be among it, else the screen is shown again first.
12418
12526
  */
12419
- async install({ digest, grant }) {
12527
+ async install({ digest, grant, asks }) {
12420
12528
  const staged = this.staged.get(digest);
12421
12529
  if (!staged || this.now() - staged.at > STAGED.ms) {
12422
12530
  this.staged.delete(digest);
@@ -12425,6 +12533,8 @@ var Apps = class {
12425
12533
  const { bundle, bytes, from, store: fromStore, revocations } = staged;
12426
12534
  const { manifest } = bundle;
12427
12535
  if (!Array.isArray(grant) || !manifest.permissions.every((p) => grant.includes(p))) fail("permissions", "Every permission the app asks for must be granted");
12536
+ const shown = asks ?? staged.asks;
12537
+ if (!Array.isArray(shown)) fail("permissions", "The permissions shown must be a list");
12428
12538
  const version = versionOf(manifest, digest);
12429
12539
  let wrote;
12430
12540
  try {
@@ -12454,6 +12564,8 @@ var Apps = class {
12454
12564
  }, installed)) continue;
12455
12565
  fail("equivocation", `Two different versions ${version.sequence} exist. Ghostly kept the one you have.`);
12456
12566
  }
12567
+ const added = installed ? addedAppPermissions(installed.permissions, manifest.permissions) : [...manifest.permissions];
12568
+ if (added.some((p) => !shown.includes(p))) fail("permissions-changed", `This install now asks for ${added.join(", ")}; look at it again`);
12457
12569
  if (decision === "same" && installed) {
12458
12570
  const files = await this.hasBundle(installed.bytes, digest) ? null : wrote = await this.writeBundle(digest, bytes);
12459
12571
  const pin = fromStore !== void 0 && installed.store !== fromStore;
@@ -12662,6 +12774,10 @@ var Apps = class {
12662
12774
  }
12663
12775
  const twin = holds && (holds.sequence === app.sequence || holds.sequence === app.pending?.sequence);
12664
12776
  if (holds && !twin && this.runStatus(holds, this.storeViews(stores), app.revocations).status !== "ok") continue;
12777
+ if (holds && twin && app.equivocation?.sequence === holds.sequence && app.equivocation.digest === holds.digest) {
12778
+ outcome = "equivocation";
12779
+ continue;
12780
+ }
12665
12781
  let fetched;
12666
12782
  try {
12667
12783
  fetched = await this.fetchBundle(url);
@@ -12757,7 +12873,7 @@ var Apps = class {
12757
12873
  ...merged.size && { revocations: [...merged.values()] },
12758
12874
  checkedAt: this.now()
12759
12875
  };
12760
- const put = stored.checkedAt !== void 0 && this.now() - stored.checkedAt < APP_CHECK_TIMINGS.freshMs / 2 && sameExceptChecked(app, stored) ? sameRecord(current, stored) : await this.putAppIfUnchanged(app, stored);
12876
+ const put = this.checkedWithin(stored.checkedAt, APP_CHECK_TIMINGS.freshMs / 2) && sameExceptChecked(app, stored) ? sameRecord(current, stored) : await this.putAppIfUnchanged(app, stored);
12761
12877
  for (const files of [...dropped, ...!put && wrote ? [wrote] : []]) await this.removeUnusedBundle(app.ref, files.bytes, files.digest);
12762
12878
  if (!put) return null;
12763
12879
  return {
@@ -12901,10 +13017,12 @@ var Apps = class {
12901
13017
  async file({ ref, path, digest }) {
12902
13018
  const app = path === "icon.png" ? await this.installedOrFail(ref) : await this.runningOrFail(ref, digest);
12903
13019
  if (path !== "icon.png" && digest !== void 0 && digest !== app.digest) fail("no-file", "No such file in this app");
12904
- const icon = path === "icon.png" ? this.icons.get(app.digest) : void 0;
12905
- if (icon) return icon.slice();
12906
- if (icon === null) fail("no-file", "No such file in this app");
12907
- const bundle = await this.verifiedBundle(app, path !== APP_ICON_PATH);
13020
+ if (path === "icon.png") {
13021
+ const icon = this.icons.has(app.digest) ? this.icons.get(app.digest) : await this.storedIcon(app);
13022
+ if (!icon) fail("no-file", "No such file in this app");
13023
+ return icon.slice();
13024
+ }
13025
+ const bundle = await this.verifiedBundle(app, true);
12908
13026
  if (typeof path !== "string" || !bundle.files.has(path)) fail("no-file", "No such file in this app");
12909
13027
  return bundle.files.get(path).slice();
12910
13028
  }
@@ -14136,7 +14254,8 @@ function turnRow(state, atStart) {
14136
14254
  if (state === "active") return atStart ? "active-start" : "active-running";
14137
14255
  return state;
14138
14256
  }
14139
- var tombstone = (facts) => facts.listed ? "moving" : "removed";
14257
+ /** Only a tombstone the device it believes signed ends a device that it does not list; any other leaves it waiting. */
14258
+ var tombstone = (facts) => facts.listed || facts.believed === false ? "moving" : "removed";
14140
14259
  var STAY = {
14141
14260
  do: "stay",
14142
14261
  offers: []
@@ -14297,7 +14416,7 @@ function cell(row, column, facts) {
14297
14416
  break;
14298
14417
  case "moving":
14299
14418
  switch (column) {
14300
- case "tombstone": return facts.listed ? {
14419
+ case "tombstone": return tombstone(facts) === "moving" ? {
14301
14420
  do: "stay",
14302
14421
  offers: [],
14303
14422
  awaits: "set-update"
@@ -14651,11 +14770,11 @@ function checkSetUpdate(record, frame, now) {
14651
14770
  const read = readTurnPacket(oldKeys, update.tomb);
14652
14771
  if (read.kind !== "valid" || !read.record.tombstone) return refuse("tombstone");
14653
14772
  const tomb = read.record;
14654
- if (!tomb.slots.some((slot) => !!slot && toBase64Url(slot.key) === own)) return refuse("removed");
14655
14773
  if (!verifySetUpdate(update, oldKeys.address)) return refuse("signature");
14656
14774
  const by = toBase64Url(update.by);
14657
14775
  const active = believed(record, oldKeys, by, update.rec);
14658
- if (!active || by !== active) return refuse("signer", true);
14776
+ if (!listedIn(tomb, own)) return active && by === active ? refuse("removed") : refuse("signer");
14777
+ if (!active || by !== active) return refuse("signer", record.activeSlot !== record.ownSlot);
14659
14778
  if (!listedIn(tomb, active)) return refuse("unlisted", true);
14660
14779
  if (record.tombstone) {
14661
14780
  const kept = readTurnPacket(oldKeys, fromBase64Url(record.tombstone));
@@ -14761,6 +14880,18 @@ function latestKnown(read, stored) {
14761
14880
  if (!news) return stored;
14762
14881
  return !stored || news.sequence >= stored.sequence ? news : stored;
14763
14882
  }
14883
+ /**
14884
+ * Whether a tombstone was signed by the device this one believes active: the one its record names (itself, on the
14885
+ * active device), or the other device of a handoff under way (the one it releases the turn to, or takes it from). Any
14886
+ * slot's key and `D` make a valid tombstone, so a stolen standby or a removed device can sign one too; only the believed
14887
+ * device's ends this device (WISP 06 § Removing a device).
14888
+ */
14889
+ function tombstoneBelieved(record, tombstone) {
14890
+ const author = tombstone.slots[tombstone.author];
14891
+ if (!author) return false;
14892
+ const key = toBase64Url(author.key);
14893
+ return key === (record.activeSlot === void 0 ? void 0 : record.deviceSet[record.activeSlot]?.key) || key === record.handoff?.release?.to || key === record.handoff?.peer;
14894
+ }
14764
14895
  /** The record's slots as the device state keeps them. */
14765
14896
  function deviceSetOf(record) {
14766
14897
  return record.slots.map((slot) => slot && {
@@ -15178,8 +15309,12 @@ var TurnKeeper = class {
15178
15309
  continue;
15179
15310
  }
15180
15311
  let outcome;
15312
+ const facts = read.result === "tombstone" && read.record ? {
15313
+ ...read,
15314
+ believed: tombstoneBelieved(held.record, read.record)
15315
+ } : read;
15181
15316
  try {
15182
- outcome = await this.carryOut(held, row, turnAction(row, read, behind), read);
15317
+ outcome = await this.carryOut(held, row, turnAction(row, facts, behind), read);
15183
15318
  } catch (error) {
15184
15319
  if (error instanceof TurnClosedError) return this.exhausted(held, row, read);
15185
15320
  if (!(error instanceof TurnStaleReadError)) throw error;
@@ -15251,7 +15386,9 @@ var TurnKeeper = class {
15251
15386
  const won = !!takeover && state === "active";
15252
15387
  const takeovers = held.record.takeovers + 1;
15253
15388
  const was = held.record.state;
15254
- const copy = state === "active" ? { copy: void 0 } : state === "superseded" && (was === "active" || was === "releasing") ? { copy: "frozen" } : {};
15389
+ const ran = was === "active" || was === "releasing";
15390
+ const foreign = state === "moving" && read.result === "tombstone" && !!read.record && !tombstoneBelieved(held.record, read.record);
15391
+ const copy = state === "active" ? { copy: void 0 } : (state === "superseded" || foreign) && ran ? { copy: "frozen" } : {};
15255
15392
  const listed = read.record?.slots[held.ownSlot];
15256
15393
  const replacedBy = state === "superseded" && read.result === "other" && read.record && !!listed && toBase64Url(listed.key) === toBase64Url(held.ownKey) ? {
15257
15394
  activeSlot: read.record.active,
@@ -15259,7 +15396,7 @@ var TurnKeeper = class {
15259
15396
  } : {};
15260
15397
  const tombstoned = state === "moving" && read.result === "tombstone" && read.record && read.payload ? {
15261
15398
  tombstone: toBase64Url(read.payload),
15262
- ...storedActiveListed(held.record, read.record) ? {} : { reenroll: true }
15399
+ ...storedActiveListed(held.record, read.record) || foreign && ran ? {} : { reenroll: true }
15263
15400
  } : {};
15264
15401
  const stopped = won && held.record.handoff?.peer ? held.record.deviceSet.find((slot) => slot?.key === held.record.handoff.peer) : void 0;
15265
15402
  held.record = await this.store.move(this.options.profile, state, {
@@ -16536,7 +16673,8 @@ function wakeOwnerOf(current, self) {
16536
16673
  }
16537
16674
  /**
16538
16675
  * Posts a push: the host's way (Desktop and the CLI post it themselves), or `fetch`, then the person's push relay when
16539
- * a page may not post it (the push services answer without CORS). Answers the push service's HTTP status.
16676
+ * a page may not post it (the push services answer without CORS). Answers the push service's HTTP status; throws when
16677
+ * the relay does not answer with it.
16540
16678
  */
16541
16679
  async function postPush(request, options) {
16542
16680
  if (options.pushSend) return options.pushSend(request);
@@ -16562,8 +16700,9 @@ async function postPush(request, options) {
16562
16700
  signal: AbortSignal.timeout(15e3),
16563
16701
  ...quiet
16564
16702
  });
16565
- const answer = await response.json().catch(() => null);
16566
- return typeof answer?.status === "number" ? answer.status : response.status;
16703
+ const answer = response.ok ? await response.json().catch(() => null) : null;
16704
+ if (typeof answer?.status !== "number") throw Object.assign(/* @__PURE__ */ new Error(`The push relay did not forward it (HTTP ${response.status})`), { cause: error });
16705
+ return answer.status;
16567
16706
  }
16568
16707
  }
16569
16708
  /** One device wake-up per device per `DEVICE_WAKE_INTERVAL_MS`. */
@@ -16960,6 +17099,13 @@ async function forceTakeover(ports, request) {
16960
17099
  }
16961
17100
  //#endregion
16962
17101
  //#region ../browser/src/devices/ownSet.ts
17102
+ /**
17103
+ * Whether another valid tombstone that does not list this device ends it here. A device that was the active one
17104
+ * believes no other device, so another slot's tombstone (a stolen device's, which needs only `D` and a slot's key)
17105
+ * leaves it `moving`, and it may try again. Any other device yields: that is how two `moving` devices of one remover
17106
+ * settle which of them goes on.
17107
+ */
17108
+ var yieldsTo = (record) => record.activeSlot !== record.ownSlot;
16963
17109
  /** Whether this device may offer it: `moving`, a copy here, and a remover it still believes (not one it can only be added back from). */
16964
17110
  function canStartOwnSet(record) {
16965
17111
  return !!record && record.state === "moving" && !!record.copy && !record.reenroll;
@@ -16993,7 +17139,7 @@ async function startOwnSet(ports, request) {
16993
17139
  stored: null
16994
17140
  }, await ports.network.turnRead(keys.identity.pubKeyZ32));
16995
17141
  if (!standing.good) return "wait";
16996
- if (standing.result === "tombstone" && !standing.listed) {
17142
+ if (standing.result === "tombstone" && !standing.listed && yieldsTo(record)) {
16997
17143
  await ports.move("removed", {});
16998
17144
  return "removed";
16999
17145
  }
@@ -17100,7 +17246,7 @@ async function resumeOwnSet(ports) {
17100
17246
  await won(ports, record, plan, now());
17101
17247
  return "start";
17102
17248
  }
17103
- if (!read.listed) {
17249
+ if (!read.listed && yieldsTo(record)) {
17104
17250
  await ports.move("removed", { ownSet: void 0 });
17105
17251
  return "removed";
17106
17252
  }
@@ -17476,6 +17622,8 @@ var NATIVE_RETRY_MS$1 = 1e4;
17476
17622
  var NATIVE_RETRY_MAX_MS = 12e4;
17477
17623
  /** The other device is there and no session opened over WebRTC in this long: the link goes on without it (`withoutRtc`). */
17478
17624
  var DEVICE_RTC_MS = 2e4;
17625
+ /** The other device is there and no session opened over a link's native endpoints in this long: it starts again with WebRTC (`withRtc`). */
17626
+ var DEVICE_NATIVE_MS = 6e4;
17479
17627
  /** The longest that wait grows to, for a link that went back to WebRTC again and again (`withRtc`). */
17480
17628
  var DEVICE_RTC_MAX_MS = 3e5;
17481
17629
  /** How often a standby reads the turn while its screen shows (WISP 06 § When a device checks), and the jitter on it. */
@@ -17747,6 +17895,7 @@ var DeviceLinks = class {
17747
17895
  clearTimeout(running.rtcWait);
17748
17896
  running.rtcWait = void 0;
17749
17897
  }
17898
+ if (state === "open") running.rtcDue = false;
17750
17899
  if (state !== "open") {
17751
17900
  if (running.agreed && !running.earlier && this.running.get(running.id) === running) this.linkLost().catch(() => {});
17752
17901
  running.agreed = false;
@@ -17769,7 +17918,12 @@ var DeviceLinks = class {
17769
17918
  if (presence.online) this.waitForRtc(running);
17770
17919
  },
17771
17920
  onPacketTransports: (transports) => {
17772
- if (!running.native && !transports.includes("webrtc/1")) this.startNative(running);
17921
+ running.peerRtcOff = !transports.includes("webrtc/1");
17922
+ if (!running.native && running.peerRtcOff) this.startNative(running);
17923
+ },
17924
+ onPacketTransportsUnsaid: (unsaid) => {
17925
+ running.peerUnsaid = unsaid;
17926
+ if (unsaid && running.rtcDue) this.withRtc(running);
17773
17927
  },
17774
17928
  onTransportsChanged: () => {
17775
17929
  if (running.native && this.missingNative(running).length) this.retryNative(running);
@@ -17794,6 +17948,10 @@ var DeviceLinks = class {
17794
17948
  * and a transport that does not start is tried again (`retryNative`), as a chat's listeners are.
17795
17949
  */
17796
17950
  startNative(running) {
17951
+ if (!running.native && running.rtcWait) {
17952
+ clearTimeout(running.rtcWait);
17953
+ running.rtcWait = void 0;
17954
+ }
17797
17955
  running.native = true;
17798
17956
  const factories = this.nativeFactories();
17799
17957
  for (const transport of this.missingNative(running)) {
@@ -18229,22 +18387,41 @@ var DeviceLinks = class {
18229
18387
  });
18230
18388
  this.queue = run;
18231
18389
  }
18232
- /** `withoutRtc` once `DEVICE_RTC_MS` passed with no session open, twice as long for each time it went back (`rtcBacks`). */
18390
+ /**
18391
+ * `withoutRtc` once `DEVICE_RTC_MS` passed with no session open, twice as long for each time it went back (`rtcBacks`).
18392
+ * A link that runs its native endpoints (`native`) waits `DEVICE_NATIVE_MS` so instead, then goes back to WebRTC
18393
+ * (`withRtc`): one device's endpoint may start where the other's never does, so nothing opens over them.
18394
+ * Not while the other device's packet still says it has no WebRTC, where this link did not go without it itself:
18395
+ * WebRTC connects nothing there, and each round only made new endpoints the other device had to read of before it
18396
+ * could dial. It goes back once that packet says nothing (`rtcDue`): a page whose own link went back to WebRTC.
18397
+ */
18233
18398
  waitForRtc(running) {
18234
- if (running.rtcOff || running.rtcWait || running.link.isDataLinkOpen) return;
18399
+ if (running.rtcOff && !running.native || running.rtcWait || running.rtcDue || running.link.isDataLinkOpen) return;
18400
+ const wait = (running.native ? DEVICE_NATIVE_MS : DEVICE_RTC_MS) * 2 ** (this.rtcBacks.get(running.id) ?? 0);
18235
18401
  running.rtcWait = setTimeout(() => {
18236
18402
  running.rtcWait = void 0;
18237
- if (!running.link.isDataLinkOpen) this.withoutRtc(running, true);
18238
- }, Math.min(DEVICE_RTC_MS * 2 ** (this.rtcBacks.get(running.id) ?? 0), DEVICE_RTC_MAX_MS));
18403
+ if (running.link.isDataLinkOpen) return;
18404
+ if (this.peerWithoutRtc(running)) running.rtcDue = true;
18405
+ else if (running.native) this.withRtc(running);
18406
+ else this.withoutRtc(running, true);
18407
+ }, Math.min(wait, DEVICE_RTC_MAX_MS));
18408
+ }
18409
+ /** A link that runs native for the other device, whose packet still says it has no WebRTC. */
18410
+ peerWithoutRtc(running) {
18411
+ return running.native && !running.rtcOff && !!running.peerRtcOff && !running.peerUnsaid;
18239
18412
  }
18240
18413
  /**
18241
18414
  * The link that went on without WebRTC (`withoutRtc`) started none of its native transports: an Iroh relay neither
18242
18415
  * device reaches, and no HyperDHT relay. With nothing to go through it starts again with WebRTC, which may connect
18243
18416
  * now, or only after `DEVICE_RTC_MS` (a device that just reloaded dials at its own pace). The wait before it goes
18244
18417
  * without WebRTC again doubles each time (`rtcBacks`), so a native transport that comes back is still tried.
18418
+ * The same where its native transports started and no session opened over them by `DEVICE_NATIVE_MS` while the other
18419
+ * device is there (its own endpoint never started, or is on another Iroh relay), and on the other device's link
18420
+ * that runs native for it: the new link forgets the transports the other device's packet said, which a device link
18421
+ * keeps although the packet no longer says any (the other device went back to WebRTC), and offers WebRTC again.
18245
18422
  */
18246
18423
  withRtc(running) {
18247
- if (this.stopped || !running.rtcOff || running.link.isDataLinkOpen || this.running.get(running.id) !== running) return;
18424
+ if (this.stopped || !this.createPeerConnection || !running.native || running.link.isDataLinkOpen || this.running.get(running.id) !== running) return;
18248
18425
  this.rtcBacks.set(running.id, (this.rtcBacks.get(running.id) ?? 0) + 1);
18249
18426
  const run = this.queue.catch(() => {}).then(async () => {
18250
18427
  if (this.stopped || this.running.get(running.id) !== running || running.link.isDataLinkOpen) return;
@@ -18590,13 +18767,13 @@ var reportOf = (busy) => busy === null ? null : typeof busy === "string" ? { why
18590
18767
  */
18591
18768
  var wireWhy = (report) => report.why === "call" ? "call" : "handoff";
18592
18769
  var name = (record, key) => record.deviceSet.find((slot) => slot?.key === key)?.name ?? "";
18593
- var slotOf$1 = (record, key) => record.deviceSet.findIndex((slot) => slot?.key === key);
18770
+ var slotOf = (record, key) => record.deviceSet.findIndex((slot) => slot?.key === key);
18594
18771
  /**
18595
18772
  * The counts of the devices still in the set: a removed device cannot pull (`onRequest` refuses it), and one added again
18596
18773
  * has a new key, so the list stays within the set's size instead of growing to the record's cap of 16 and refusing every
18597
18774
  * write after it.
18598
18775
  */
18599
- var setAttempts = (record, attempts) => Object.fromEntries(Object.entries(attempts ?? {}).filter(([key]) => slotOf$1(record, key) >= 0));
18776
+ var setAttempts = (record, attempts) => Object.fromEntries(Object.entries(attempts ?? {}).filter(([key]) => slotOf(record, key) >= 0));
18600
18777
  /** One session of a handoff with the other device: its own X25519 key, the other's hello, and the stream key. */
18601
18778
  var Session = class {
18602
18779
  transcript;
@@ -18873,7 +19050,7 @@ var HandoffGiver = class {
18873
19050
  if (this.phase !== "idle" && this.phase !== "failed") throw new Error("handoff-busy: Another move is in progress.");
18874
19051
  const record = await this.ports.records.read();
18875
19052
  if (!record || record.state !== "active") throw new Error("handoff-refused: Only the active device moves the profile.");
18876
- if (slotOf$1(record, key) < 0) throw new Error("handoff-refused: That device is not one of this profile's.");
19053
+ if (slotOf(record, key) < 0) throw new Error("handoff-refused: That device is not one of this profile's.");
18877
19054
  const busy = reportOf(await this.ports.busy(this.takerFacts(key)));
18878
19055
  if (busy) throw new Error(`handoff-${busy.why}:${busy.wallet ? `${busy.wallet}:` : ""} This device cannot move the profile now.`);
18879
19056
  if (!this.ports.links.live(key)) {
@@ -19068,7 +19245,7 @@ var HandoffGiver = class {
19068
19245
  if (this.phase !== "idle" && this.phase !== "failed") busy("handoff");
19069
19246
  return;
19070
19247
  }
19071
- if (slotOf$1(record, from) < 0) return busy("refused", 0);
19248
+ if (slotOf(record, from) < 0) return busy("refused", 0);
19072
19249
  const pushed = this.phase === "offered" && from === this.peer && request.id === this.id;
19073
19250
  if (this.phase !== "idle" && this.phase !== "failed" && !pushed) return busy("handoff");
19074
19251
  const session = this.sessionFor(from);
@@ -19344,7 +19521,7 @@ var HandoffGiver = class {
19344
19521
  }
19345
19522
  const record = await this.ports.records.read();
19346
19523
  if (!record || record.state !== "releasing") return;
19347
- const fromSlot = record.ownSlot, toSlot = slotOf$1(record, from);
19524
+ const fromSlot = record.ownSlot, toSlot = slotOf(record, from);
19348
19525
  if (toSlot < 0) return;
19349
19526
  const signed = await signTurnRelease(this.ports.turnAddress, this.turn + 1, fromSlot, toSlot, fromBase64Url(from), h, (bytes) => this.ports.sign(bytes));
19350
19527
  const release = {
@@ -20443,6 +20620,8 @@ var ANNOUNCED_FOR_MS = 6048e5;
20443
20620
  var floorRefusal = (why) => why === "no-room" ? "No room on this device for this file" : why === "too-many" ? "Too many files are waiting here" : "It was refused here";
20444
20621
  /** Progress is written to the database at most this often; every change of state is written at once. */
20445
20622
  var SAVE_EVERY_MS = 2e3;
20623
+ /** A transfer's state the database refused is written again this often, until it goes (`FileDesk.save`). */
20624
+ var REWRITE_AFTER_MS = 5e3;
20446
20625
  /** The views of finished transfers the states carry, the newest (`FileDesk.finished`). */
20447
20626
  var DONE_VIEWS_KEPT = 16;
20448
20627
  /**
@@ -20475,6 +20654,7 @@ var FileDesk = class {
20475
20654
  saving: Promise.resolve(),
20476
20655
  lastSaved: /* @__PURE__ */ new Map(),
20477
20656
  unsaved: /* @__PURE__ */ new Map(),
20657
+ refused: /* @__PURE__ */ new Map(),
20478
20658
  files: void 0
20479
20659
  };
20480
20660
  made.files = new ChatFiles({
@@ -20726,6 +20906,7 @@ var FileDesk = class {
20726
20906
  chat.files.forget(out ? "out" : "in", wireId);
20727
20907
  clearTimeout(chat.unsaved.get(fileId)?.timer);
20728
20908
  chat.unsaved.delete(fileId);
20909
+ chat.refused.delete(fileId);
20729
20910
  if (!out) {
20730
20911
  chat.local.delete(wireId);
20731
20912
  chat.announced.delete(wireId);
@@ -20742,17 +20923,26 @@ var FileDesk = class {
20742
20923
  for (const [wireId, said] of [...chat.announced]) if (now - said.at > ANNOUNCED_FOR_MS) this.withdrawn(chat, wireId, "It did not come within a week");
20743
20924
  }
20744
20925
  }
20745
- /** The chat went away: its transfers stop here. */
20926
+ /**
20927
+ * The chat went away: its transfers stop here. An unfinished one ends on the contact's side too, as deleting its
20928
+ * message does, on the session while it is still up: one never told stayed under way there for good, its part kept.
20929
+ * Called before the chat's link goes, so what is said still finds it. True when an end was said on the session.
20930
+ */
20746
20931
  drop(linkId) {
20747
20932
  const chat = this.chats.get(linkId);
20933
+ const records = chat?.files.records().sort((a, b) => Number(b.state === "queued") - Number(a.state === "queued")) ?? [];
20934
+ const said = !!chat?.files.live && records.some((record) => !transferEnded(record));
20935
+ for (const record of records) chat.files.forget(record.direction, record.id);
20748
20936
  chat?.files.detach();
20749
20937
  for (const { timer } of chat?.unsaved.values() ?? []) clearTimeout(timer);
20938
+ clearTimeout(chat?.rewrite);
20750
20939
  this.chats.delete(linkId);
20751
20940
  for (const id of [
20752
20941
  ...this.moved.keys(),
20753
20942
  ...this.restored,
20754
20943
  ...this.stallChecks.keys()
20755
20944
  ]) if (id.startsWith(`${linkId}-`)) this.unwatch(id);
20945
+ return said;
20756
20946
  }
20757
20947
  /** Stops tracking whether a transfer is stuck. */
20758
20948
  unwatch(id) {
@@ -20768,8 +20958,9 @@ var FileDesk = class {
20768
20958
  async decide(linkId, file, again = false) {
20769
20959
  const used = this.deps.wireIds(linkId);
20770
20960
  const said = this.chats.get(linkId)?.announced.has(file.id) ?? false;
20771
- if (!used || !again && !said && used.has(file.id)) return { refuse: "invalid" };
20961
+ if (!used) return { refuse: "invalid" };
20772
20962
  if (this.deps.deleted(linkId, `peer_${file.id}`)) return { refuse: "declined" };
20963
+ if (!again && !said && used.has(file.id)) return { refuse: "invalid" };
20773
20964
  if (!again && !said && await this.deps.messageExists?.(linkId, `peer_${file.id}`)) return { refuse: "invalid" };
20774
20965
  const room = await (await fileBytes()).room().catch(() => null);
20775
20966
  if (room !== null && file.size > room) return {
@@ -20821,7 +21012,7 @@ var FileDesk = class {
20821
21012
  const stored = await fileStore.get(id);
20822
21013
  if (!stored) throw new Error("The file is gone");
20823
21014
  return {
20824
- read: (offset, length) => readStored$1(stored, offset, length),
21015
+ read: (offset, length) => readStored$2(stored, offset, length),
20825
21016
  digest: async () => {
20826
21017
  if (stored.digest) return stored.digest;
20827
21018
  const digest = stored.blob ? await blobDigest(stored.blob) : await (await fileBytesOf(stored.bytes)).digest(id);
@@ -20952,7 +21143,12 @@ var FileDesk = class {
20952
21143
  if (record.state === "done" && record.direction === "in") this.deps.wireIds(linkId)?.add(record.id);
20953
21144
  this.deps.changed(progress ? 250 : 50);
20954
21145
  }
20955
- /** Writes a transfer's record and the view of it, after the chat's writes before it; what was held back goes with it. */
21146
+ /**
21147
+ * Writes a transfer's record and the view of it, after the chat's writes before it; what was held back goes with it.
21148
+ * One the database refuses (a full disk) is kept and written again, with the chat's next write and every few seconds,
21149
+ * until it goes: dropped, a received file that failed for want of room read "under way" after a restart, then
21150
+ * "Cancelled by the sender".
21151
+ */
20956
21152
  save(chat, id, record) {
20957
21153
  const held = chat.unsaved.get(id);
20958
21154
  if (held) {
@@ -20962,7 +21158,7 @@ var FileDesk = class {
20962
21158
  if (transferEnded(record)) chat.lastSaved.delete(id);
20963
21159
  else chat.lastSaved.set(id, Date.now());
20964
21160
  const transfer = this.deps.transfers.get(id);
20965
- chat.saving = chat.saving.then(() => fileStore.patch(id, {
21161
+ const change = {
20966
21162
  wire3: record,
20967
21163
  ...transfer && { transfer: {
20968
21164
  state: transfer.state,
@@ -20970,7 +21166,27 @@ var FileDesk = class {
20970
21166
  size: transfer.size,
20971
21167
  error: transfer.error
20972
21168
  } }
20973
- })).catch(() => {});
21169
+ };
21170
+ chat.saving = chat.saving.then(() => {
21171
+ chat.refused.delete(id);
21172
+ chat.refused.set(id, change);
21173
+ return this.writeRefused(chat);
21174
+ }).catch(() => this.rewriteLater(chat));
21175
+ }
21176
+ /** Writes what is waiting in `refused`, oldest first; it stops at the first the database refuses. */
21177
+ async writeRefused(chat) {
21178
+ for (const [id, change] of [...chat.refused]) {
21179
+ await fileStore.patch(id, change);
21180
+ chat.refused.delete(id);
21181
+ }
21182
+ }
21183
+ rewriteLater(chat) {
21184
+ if (chat.rewrite || !chat.refused.size) return;
21185
+ chat.rewrite = setTimeout(() => {
21186
+ chat.rewrite = void 0;
21187
+ chat.saving = chat.saving.then(() => this.writeRefused(chat)).catch(() => this.rewriteLater(chat));
21188
+ }, REWRITE_AFTER_MS);
21189
+ chat.rewrite.unref?.();
20974
21190
  }
20975
21191
  show(linkId, chat, record, transferred, progress = false) {
20976
21192
  const id = record.direction === "out" ? outgoingFileId(linkId, record.id) : chat.local.get(record.id);
@@ -22842,201 +23058,6 @@ function faucetError(error) {
22842
23058
  return /* @__PURE__ */ new Error(`The faucet did not pay: ${message}`);
22843
23059
  }
22844
23060
  //#endregion
22845
- //#region ../browser/src/engine/sealedRows.ts
22846
- /**
22847
- * Phase 1 of the encrypted profile (WISP 04, What is encrypted): the fields of the peer database that let someone act
22848
- * as the person or spend, by store, as paths into the row. With the data key set they are written sealed (version 2,
22849
- * bound to the store, the row's key and the path) and opened as they are read; without it, rows are written and read
22850
- * as they always were. A field is sealed as its JSON, so an object (transport seeds, epoch secrets) is one field.
22851
- */
22852
- var FIELDS = {
22853
- [STORES$1.links]: [
22854
- "seedB64",
22855
- "encKeyB64",
22856
- "participationSeed",
22857
- "transportSeeds",
22858
- "inviteCode",
22859
- "pairedPeerKey",
22860
- "peerTrust.verifiedKey",
22861
- "ratchetState"
22862
- ],
22863
- [STORES$1.groups]: [
22864
- "invitation.seedB64",
22865
- "entry.seedB64",
22866
- "joining.seedB64",
22867
- "state.seedB64",
22868
- "state.secrets",
22869
- "community.seedB64",
22870
- "community.secrets",
22871
- "community.entry.seedB64",
22872
- "community.rv"
22873
- ],
22874
- [STORES$1.swaps]: ["swap", "token"],
22875
- [STORES$1.melts]: ["secrets", "outputs"]
22876
- };
22877
- /** A group removed and invited again keeps the group it was (`previous`), with secrets of its own. */
22878
- var NESTED = { [STORES$1.groups]: "previous" };
22879
- /**
22880
- * A proof's secret is its row's key (`keyPath: "secret"`), and a sealed value can't be one: a sealed proof is kept under
22881
- * this hash of its secret, the secret itself sealed beside it. The hash, not the secret, can be found again inside a
22882
- * transaction, where WebCrypto can't be waited for.
22883
- */
22884
- var proofKey = (secret) => bytesToHex(sha256(utf8ToBytes(`ghostly-proof/1\n${secret}`)));
22885
- var SEALED_SECRET = "sealedSecret";
22886
- var keyOf = (store, row) => String(store === STORES$1.melts ? row.quote : row.id);
22887
- function read(row, path) {
22888
- return path.split(".").reduce((at, part) => at && typeof at === "object" ? at[part] : void 0, row);
22889
- }
22890
- /** The row with `value` at `path`, copied along the way: the caller's row is never changed. */
22891
- function written(row, [part, ...rest], value) {
22892
- return {
22893
- ...row,
22894
- [part]: rest.length ? written(row[part], rest, value) : value
22895
- };
22896
- }
22897
- /** Every phase 1 value of a row that is there, with its path. */
22898
- function places(store, row, prefix = "") {
22899
- const found = (FIELDS[store] ?? []).map((path) => ({
22900
- path: prefix + path,
22901
- value: read(row, path)
22902
- })).filter(({ value }) => value !== void 0);
22903
- const nested = NESTED[store] && row[NESTED[store]];
22904
- return nested && typeof nested === "object" ? [...found, ...places(store, nested, `${prefix}${NESTED[store]}.`)] : found;
22905
- }
22906
- function sealWith(store, value, seal) {
22907
- const row = value;
22908
- if (store === STORES$1.proofs) {
22909
- if (row[SEALED_SECRET] !== void 0) return value;
22910
- const secret = String(row.secret), key = proofKey(secret);
22911
- return {
22912
- ...row,
22913
- secret: key,
22914
- [SEALED_SECRET]: seal(JSON.stringify(secret), {
22915
- store,
22916
- key,
22917
- field: "secret"
22918
- })
22919
- };
22920
- }
22921
- const key = keyOf(store, row);
22922
- let out = row;
22923
- for (const { path, value: at } of places(store, row)) if (!isSealedField(at)) out = written(out, path.split("."), seal(JSON.stringify(at), {
22924
- store,
22925
- key,
22926
- field: path
22927
- }));
22928
- return out;
22929
- }
22930
- var slotOf = (json, at) => [
22931
- at.store,
22932
- at.key,
22933
- at.field,
22934
- json
22935
- ].join("\n");
22936
- /**
22937
- * Seals made ahead of a transaction, for `row` to use inside it: IndexedDB commits a transaction that waits for
22938
- * anything else, WebCrypto included. Whether rows are sealed is fixed when this is made, so a key dropped meanwhile
22939
- * makes a write fail, never go out in the clear.
22940
- */
22941
- var RowSeals = class RowSeals {
22942
- /** Seals are made one batch after another, so writes that seal first are saved in the order they were asked for. */
22943
- static turn = Promise.resolve();
22944
- on = hasDataKey();
22945
- ready = /* @__PURE__ */ new Map();
22946
- /** What these rows (or the proofs of these secrets) hold, sealed now. */
22947
- async prepare(store, rows) {
22948
- if (!this.on) return this;
22949
- const wanted = /* @__PURE__ */ new Map();
22950
- for (const row of rows) sealWith(store, row, (json, at) => {
22951
- wanted.set(slotOf(json, at), [json, at]);
22952
- return {
22953
- v: 2,
22954
- iv: "",
22955
- ct: ""
22956
- };
22957
- });
22958
- const sealing = RowSeals.turn.then(async () => {
22959
- for (const [slot, [json, at]] of wanted) if (!this.ready.has(slot)) this.ready.set(slot, await sealPlace(json, at));
22960
- });
22961
- RowSeals.turn = sealing.catch(() => {});
22962
- await sealing;
22963
- return this;
22964
- }
22965
- /** The row as it is written. Throws for a value not prepared: its transaction aborts, and nothing goes out in the clear. */
22966
- row(store, row) {
22967
- if (!this.on) return row;
22968
- return sealWith(store, row, (json, at) => {
22969
- const sealed = this.ready.get(slotOf(json, at));
22970
- if (!sealed) throw new Error("A secret was not sealed before it was saved");
22971
- return sealed;
22972
- });
22973
- }
22974
- };
22975
- async function sealRow(store, row) {
22976
- return (await new RowSeals().prepare(store, [row])).row(store, row);
22977
- }
22978
- /**
22979
- * The store as a transaction's work sees it: what it puts is sealed from `seals`, and a proof is found by its secret.
22980
- * Without the data key, the store itself.
22981
- */
22982
- function sealedStore(store, seals) {
22983
- if (!seals.on) return store;
22984
- const proofs = store.name === STORES$1.proofs;
22985
- return new Proxy(store, { get(target, name) {
22986
- if (name === "put") return (row, ...key) => target.put(seals.row(target.name, row), ...key);
22987
- if (proofs && name === "delete") return (secret) => {
22988
- target.delete(secret);
22989
- return target.delete(proofKey(secret));
22990
- };
22991
- if (proofs && name === "get") return (secret) => target.get(proofKey(secret));
22992
- const value = Reflect.get(target, name, target);
22993
- return typeof value === "function" ? value.bind(target) : value;
22994
- } });
22995
- }
22996
- function unsealed() {
22997
- if (!takesUnsealed()) throw new Error("A secret of this profile was not sealed with its key");
22998
- }
22999
- /** The row as the engine uses it: every sealed value opened, where it was. */
23000
- async function openRow(store, value) {
23001
- if (!hasDataKey() || !value) return value;
23002
- const row = value;
23003
- if (store === STORES$1.proofs) {
23004
- const sealed = row[SEALED_SECRET];
23005
- if (sealed === void 0) {
23006
- unsealed();
23007
- return value;
23008
- }
23009
- const key = String(row.secret), secret = JSON.parse(await openSecret(sealed, {
23010
- store,
23011
- key,
23012
- field: "secret"
23013
- }));
23014
- if (proofKey(secret) !== key) throw new Error("A sealed field could not be opened: it was changed, or it belongs to another record");
23015
- const { [SEALED_SECRET]: _sealed, ...rest } = row;
23016
- return {
23017
- ...rest,
23018
- secret
23019
- };
23020
- }
23021
- const key = keyOf(store, row);
23022
- let out = row;
23023
- for (const { path, value: at } of places(store, row)) {
23024
- if (!isSealedField(at)) {
23025
- unsealed();
23026
- continue;
23027
- }
23028
- out = written(out, path.split("."), JSON.parse(await openSecret(at, {
23029
- store,
23030
- key,
23031
- field: path
23032
- })));
23033
- }
23034
- return out;
23035
- }
23036
- function openRows(store, rows) {
23037
- return hasDataKey() ? Promise.all(rows.map((row) => openRow(store, row))) : Promise.resolve(rows);
23038
- }
23039
- //#endregion
23040
23061
  //#region ../browser/src/engine/db.ts
23041
23062
  /**
23042
23063
  * The newest `count` rows of an index range, newest first: one descending read where IndexedDB has it (the options
@@ -23879,10 +23900,22 @@ function pinView(pin) {
23879
23900
  }
23880
23901
  /**
23881
23902
  * Whether a private group's pin was made by someone no longer in its roster (`inRoster`): it goes when they do, so a
23882
- * member removed leaves nothing of theirs at the top of the chat.
23903
+ * member removed leaves nothing of theirs at the top of the chat. Their unpin shows nothing already: it stays.
23883
23904
  */
23884
23905
  function pinOfFormerMember(pin, inRoster) {
23885
- return !!pin && pin.by !== "me" && !inRoster(pin.by);
23906
+ return !!pin?.id && pin.by !== "me" && !inRoster(pin.by);
23907
+ }
23908
+ /**
23909
+ * What a former member's pin is dropped to: an unpin at its number, so only a pin numbered past it shows. Dropped to
23910
+ * none, an older pin a member kept while away (and says again when its edges open) would come back.
23911
+ */
23912
+ function droppedPin(pin, now = Date.now()) {
23913
+ return {
23914
+ id: "",
23915
+ n: pin.n,
23916
+ by: pin.by,
23917
+ at: now
23918
+ };
23886
23919
  }
23887
23920
  /** Whether I may pin in this group now: the rule (`mayPin`) with my key and its admin's. */
23888
23921
  function mayPinIn(group) {
@@ -23890,7 +23923,8 @@ function mayPinIn(group) {
23890
23923
  }
23891
23924
  /**
23892
23925
  * The row a pin names, when it is here: the row of that id (a group's), or of `peer_`/`me_` and that id, or one the host
23893
- * knows that id names (a file of mine, a payment), each read alone; else any other of a chat's.
23926
+ * knows that id names (a file of mine, a payment), each read alone; else any other of a chat's, from the rows the host
23927
+ * knows by another id (`unkeyed`) or, without those, the whole chat.
23894
23928
  */
23895
23929
  async function pinnedRow(host, chat, id) {
23896
23930
  if (!id) return void 0;
@@ -23905,6 +23939,11 @@ async function pinnedRow(host, chat, id) {
23905
23939
  if (row && replyRef(row, group) === id) return row;
23906
23940
  }
23907
23941
  if (group) return void 0;
23942
+ const unkeyed = host.unkeyed?.(chat);
23943
+ if (unkeyed) {
23944
+ const rowId = (await unkeyed).get(id), row = rowId === void 0 ? void 0 : await host.message(chat, rowId);
23945
+ return row && replyRef(row, false) === id ? row : void 0;
23946
+ }
23908
23947
  }
23909
23948
  return reactionTarget(await host.messages(chat), id, group);
23910
23949
  }
@@ -24603,10 +24642,10 @@ var Communities = class {
24603
24642
  markedBy(groupId) {
24604
24643
  return this.marks.by.get(groupId);
24605
24644
  }
24606
- /** A message deleted for everyone left this device: the marks it set go back (`unmark` in groups.ts). */
24607
- async unmark(groupId, removed) {
24645
+ /** A message deleted for everyone left this device: the marks it set go back (`unmark` in groups.ts); `mentionOnly`, its "@" alone. */
24646
+ async unmark(groupId, removed, mentionOnly = false) {
24608
24647
  const group = this.stored.get(groupId);
24609
- if (await unmark(this.marks, group, groupId, () => this.store.getMessages(MESSAGE_LINK$1(groupId)), removed) && group) await this.store.putGroup(group);
24648
+ if (await unmark(this.marks, group, groupId, () => this.store.getMessages(MESSAGE_LINK$1(groupId)), removed, mentionOnly) && group) await this.store.putGroup(group);
24610
24649
  }
24611
24650
  views() {
24612
24651
  return [...this.stored.values()].flatMap((group) => this.viewOf(group));
@@ -24743,13 +24782,14 @@ var Communities = class {
24743
24782
  if (s.entryKey) await this.startJoining(door ? link : {
24744
24783
  g: link.g,
24745
24784
  host: s.entryKey
24746
- }, s.state.seedB64, this.now(), true);
24785
+ }, s.state.seedB64, this.now(), true, door ? void 0 : link.host);
24747
24786
  return link.g;
24748
24787
  }
24749
24788
  if (s.status === "removed" || s.status === "lost") {
24750
- await this.startJoining(link, door ? s.state.seedB64 : dialedKey(link), this.now());
24789
+ await this.startJoining(link, this.rejoinSeed(s, link), this.now());
24751
24790
  return link.g;
24752
24791
  }
24792
+ throw new Error("You are out of this group and its history is still here. Delete it from this device to join with a link.");
24753
24793
  }
24754
24794
  if (existing) await this.forget(link.g);
24755
24795
  await this.startJoining(link, dialedKey(link), this.now());
@@ -24766,8 +24806,37 @@ var Communities = class {
24766
24806
  keptWhileKnocking(live) {
24767
24807
  return live?.session.status === "removed";
24768
24808
  }
24769
- /** `check`: a member, as far as this device knows, asking the door whether it still is (`joinByLink`). */
24770
- async startJoining(link, seedB64, since, check = false) {
24809
+ /** Someone out of the group knocks with the member key it had at the door it knows, else with a fresh one, as any joiner. */
24810
+ rejoinSeed(s, link) {
24811
+ return s.entryKey === link.host ? s.state.seedB64 : dialedKey(link);
24812
+ }
24813
+ /** The newest link this device knows of a group it knocks at: the one opened, over the door a member's check asks. */
24814
+ knockLink(joining) {
24815
+ return {
24816
+ g: joining.g,
24817
+ host: joining.opened ?? joining.host
24818
+ };
24819
+ }
24820
+ /**
24821
+ * A member asking the door it knows whether it still is, told meanwhile that it is out (removed while its app was
24822
+ * closed, the link replaced): no check any more but a knock, at the link that was opened, as any joiner's. Left a
24823
+ * check, it knocked for an hour at a door nobody reads, and Try again knocked there too.
24824
+ */
24825
+ async checkTurnedKnock(group, s, now) {
24826
+ const joining = group.joining, link = this.knockLink(joining);
24827
+ if (link.host !== joining.host) {
24828
+ await this.startJoining(link, this.rejoinSeed(s, link), now);
24829
+ return true;
24830
+ }
24831
+ delete joining.check;
24832
+ await this.store.putGroup(group);
24833
+ return false;
24834
+ }
24835
+ /**
24836
+ * `check`: a member, as far as this device knows, asking the door whether it still is (`joinByLink`); `opened`, the
24837
+ * entry key of the link it opened when that is not the door.
24838
+ */
24839
+ async startJoining(link, seedB64, since, check = false, opened) {
24771
24840
  this.lastKnock.delete(link.g);
24772
24841
  this.knocked.delete(link.g);
24773
24842
  this.knockAt.delete(link.g);
@@ -24792,7 +24861,8 @@ var Communities = class {
24792
24861
  inviter: "",
24793
24862
  pieces: [],
24794
24863
  since,
24795
- ...check && { check: true }
24864
+ ...check && { check: true },
24865
+ ...check && opened && { opened }
24796
24866
  };
24797
24867
  this.stored.set(link.g, group);
24798
24868
  await this.store.putGroup(group);
@@ -24812,6 +24882,24 @@ var Communities = class {
24812
24882
  this.host.emit();
24813
24883
  this.knock(group, now).catch(() => {});
24814
24884
  }
24885
+ /** The link a joiner knocks at was replaced (or turned off): it is told so and stops, until it opens the current link. */
24886
+ async linkReplaced(group) {
24887
+ const joining = group.joining, g = group.id;
24888
+ joining.replaced = true;
24889
+ joining.inviter = "";
24890
+ joining.pieces = [];
24891
+ if (this.knocked.has(g)) this.unknock({
24892
+ g,
24893
+ host: joining.host
24894
+ }, this.knockAt.get(g) ?? KNOCK_BELL, joining.seedB64).catch(() => {});
24895
+ this.knocked.delete(g);
24896
+ this.knockAt.delete(g);
24897
+ countWaitingJoin(this.host, g, this.now(), false);
24898
+ traceJoin(g, "join.replaced");
24899
+ await this.store.putGroup(group);
24900
+ await this.host.closeEdge(joining.linkId);
24901
+ this.host.emit();
24902
+ }
24815
24903
  /** The joiner's side of the link's entry session, opened again where it is gone (the same key, so the same session). */
24816
24904
  async reopenEntry(joining) {
24817
24905
  if ([...this.host.entries(joining.g).values()].includes(joining.linkId)) return;
@@ -25035,6 +25123,7 @@ var Communities = class {
25035
25123
  };
25036
25124
  for (const group of [...this.stored.values()]) {
25037
25125
  const live = this.live.get(group.id);
25126
+ if (group.joining?.check && live && live.session.status !== "active" && await this.checkTurnedKnock(group, live.session, now)) continue;
25038
25127
  if (group.joining && (this.knocking(group, live) || group.joining.check) && !this.gaveUp.has(group.id) && !group.joining.replaced) {
25039
25128
  const knocking = this.knocking(group, live), waited = now - group.joining.since;
25040
25129
  const answered = this.host.linkReady(group.joining.linkId, 2) || !!this.host.linkSeen?.(group.joining.linkId);
@@ -25062,10 +25151,12 @@ var Communities = class {
25062
25151
  await this.publishBeacon(group.id, live, now, false).catch(() => {});
25063
25152
  }
25064
25153
  await this.closeEntries(group.id);
25154
+ const lostAt = live.session.lostEntryKey;
25065
25155
  await this.startJoining({
25066
25156
  g: group.id,
25067
- host: live.session.lostEntryKey
25157
+ host: lostAt
25068
25158
  }, live.session.state.seedB64, now);
25159
+ if (lostAt !== live.session.entryKey) await this.linkReplaced(group);
25069
25160
  continue;
25070
25161
  }
25071
25162
  if (live.session.status !== "active") {
@@ -25282,6 +25373,7 @@ var Communities = class {
25282
25373
  const ready = [...this.host.edges(groupId)].filter(([key, id]) => this.host.linkReady(id, 2) && !s.wasRemoved(key)).map(([key]) => key);
25283
25374
  for (const key of ready.slice(0, 3)) s.catchUp(key);
25284
25375
  }
25376
+ await s.resume().catch(() => {});
25285
25377
  await s.reseal().catch(() => {});
25286
25378
  await this.reconcile(groupId, live, now);
25287
25379
  }
@@ -26105,20 +26197,7 @@ var Communities = class {
26105
26197
  }, joining.pieces, frame, joining.seedB64);
26106
26198
  if (this.stored.get(g) !== group || group.joining !== joining || joining.linkId !== linkId || joining.inviter !== inviter) return;
26107
26199
  if ("error" in joined && joined.error === LINK_REPLACED && !joining.check) {
26108
- joining.replaced = true;
26109
- joining.inviter = "";
26110
- joining.pieces = [];
26111
- if (this.knocked.has(g)) this.unknock({
26112
- g,
26113
- host: joining.host
26114
- }, this.knockAt.get(g) ?? KNOCK_BELL, joining.seedB64).catch(() => {});
26115
- this.knocked.delete(g);
26116
- this.knockAt.delete(g);
26117
- countWaitingJoin(this.host, g, this.now(), false);
26118
- traceJoin(g, "join.replaced");
26119
- await this.store.putGroup(group);
26120
- await this.host.closeEdge(linkId);
26121
- this.host.emit();
26200
+ await this.linkReplaced(group);
26122
26201
  return;
26123
26202
  }
26124
26203
  if ("error" in joined) {
@@ -26469,7 +26548,8 @@ var MESH_HUB_TIMINGS = {
26469
26548
  firstReadMs: 3e4,
26470
26549
  graceMs: 18e4,
26471
26550
  keepMetMs: 12e4,
26472
- reachEveryMs: 5e3
26551
+ reachEveryMs: 5e3,
26552
+ standInAfterMs: 3e4
26473
26553
  };
26474
26554
  /** A hub says whom it reaches this often even when nothing changed: members that cannot read the beacon learn it is one. */
26475
26555
  var REACH_AGAIN_MS = 6e4;
@@ -26498,6 +26578,33 @@ var STEP_UP_MARGIN = 2;
26498
26578
  var STEP_UP_DELAY_MS = 6e4;
26499
26579
  /** The longest a write of my entry waits for the budget it was told of: within an entry's freshness (90 s). */
26500
26580
  var PUBLISH_WAIT_MAX_MS = 3e4;
26581
+ /** Members that keep an edge for a member no hub reaches (WISP 902 · Group Mesh § Hubs, Stand-ins). */
26582
+ var STAND_INS = MESH_HUBS.hubsPerMember;
26583
+ /**
26584
+ * Who stands in for whom (WISP 902 · Group Mesh § Hubs, Stand-ins): the members nobody reaches, in key order, each get
26585
+ * the first `STAND_INS` of `standing` by rendezvous rank for their key (`hubRank`, as hubs are ranked) that do not stand
26586
+ * in for `STAND_IN_MAX` members already. Every member reads the same roster and the same `u`, so each works out the
26587
+ * same answer on its own. Keyed by stand-in, the members it keeps an edge for.
26588
+ */
26589
+ function standInDuty(lost, standing) {
26590
+ const duty = /* @__PURE__ */ new Map();
26591
+ for (const subject of [...new Set(lost)].sort()) {
26592
+ const rank = new Map(standing.map((key) => [key, hubRank(subject, key)]));
26593
+ const order = [...rank.keys()].filter((key) => key !== subject).sort((a, b) => {
26594
+ const ra = rank.get(a), rb = rank.get(b);
26595
+ return ra < rb ? 1 : ra > rb ? -1 : 0;
26596
+ });
26597
+ let taken = 0;
26598
+ for (const key of order) {
26599
+ if (taken === STAND_INS) break;
26600
+ const mine = duty.get(key) ?? [];
26601
+ if (mine.length >= 4) continue;
26602
+ duty.set(key, [...mine, subject]);
26603
+ taken++;
26604
+ }
26605
+ }
26606
+ return duty;
26607
+ }
26501
26608
  /**
26502
26609
  * The hubs of the private groups this device is in (WISP 902 · Group Mesh § Hubs): whether a group runs on hubs, who
26503
26610
  * they are (the community's sealed beacon and lobbies, under the epoch's rendezvous secret), whether I am one, which
@@ -26572,7 +26679,13 @@ var MeshHubs = class {
26572
26679
  gone: /* @__PURE__ */ new Map(),
26573
26680
  reactions: /* @__PURE__ */ new Map(),
26574
26681
  need: 0,
26575
- departed: /* @__PURE__ */ new Set()
26682
+ departed: /* @__PURE__ */ new Set(),
26683
+ unreached: /* @__PURE__ */ new Map(),
26684
+ reachNone: /* @__PURE__ */ new Map(),
26685
+ standFor: {
26686
+ at: "",
26687
+ mine: []
26688
+ }
26576
26689
  });
26577
26690
  }
26578
26691
  return live;
@@ -26636,8 +26749,9 @@ var MeshHubs = class {
26636
26749
  return meshHubs(live.beacon, session.myKey, session.hubPolicy, (key) => rosterHas(session.roster, key), now).filter((h) => !live.departed.has(h.key));
26637
26750
  }
26638
26751
  /**
26639
- * A member said on its own edge that it leaves: if it was a hub, it is none from now on, rather than until the beacon
26640
- * forgets it and its grace runs out (the commit that takes it out may have no other way here). True when a hub went.
26752
+ * A member said that it leaves, on its own edge or in a signed bye a hub passed on: if it was a hub, it is none from now
26753
+ * on, rather than until the beacon forgets it and its grace runs out (the commit that takes it out may have no other way
26754
+ * here), and it stands in for nobody. True when a hub went.
26641
26755
  */
26642
26756
  departs(groupId, key) {
26643
26757
  const live = this.live.get(groupId);
@@ -26646,6 +26760,7 @@ var MeshHubs = class {
26646
26760
  const was = live.seenHubs.delete(key) || live.myHubs.includes(key) || live.beacon.some((h) => h.key === key);
26647
26761
  live.reach.delete(key);
26648
26762
  live.reachLegacy.delete(key);
26763
+ live.reachNone.delete(key);
26649
26764
  live.claimed.delete(key);
26650
26765
  live.hubsUp.delete(key);
26651
26766
  live.myHubs = live.myHubs.filter((k) => k !== key);
@@ -26710,6 +26825,7 @@ var MeshHubs = class {
26710
26825
  return !!id && this.host.linkReady(id);
26711
26826
  });
26712
26827
  if (admin && (legacy.includes(admin) || !hubUp)) out.add(admin);
26828
+ for (const key of this.standIns(groupId, session, live, hubs, legacy)) out.add(key);
26713
26829
  }
26714
26830
  if (session.isAdmin) for (const key of legacy) out.add(key);
26715
26831
  }
@@ -26722,6 +26838,61 @@ var MeshHubs = class {
26722
26838
  return out;
26723
26839
  }
26724
26840
  /**
26841
+ * The members I keep an edge for as one of their stand-ins (WISP 902 · Group Mesh § Hubs, Stand-ins): those the hubs of
26842
+ * my beacon reading, on edges that are up, say nobody reaches (`u`), when `standInDuty` gives them to me: at most
26843
+ * `STAND_IN_MAX`, among the first `STAND_INS` by rendezvous rank for their key of the members that are reached and no
26844
+ * hubs (nor apps without hubs). A member back behind the chain whose hubs all left or closed while it was away reads a
26845
+ * beacon no hub writes any more and dials every member it knows; those keep their hubs' edges only, and the hub it has
26846
+ * not heard of yet opens an edge it does not open, not knowing it. An edge needs both sides: nobody ever opened the
26847
+ * other (agents#2491). Its stand-ins do; it catches up over them (the commits, the secrets) and finds its hubs. Only
26848
+ * hubs can say who nobody reaches: a hub's reach is the members that picked it, and hubs hear each other's.
26849
+ */
26850
+ standIns(groupId, session, live, hubs, legacy) {
26851
+ const edges = this.host.edges(groupId), me = session.myKey, none = /* @__PURE__ */ new Set();
26852
+ for (const hub of hubs) {
26853
+ const id = edges.get(hub), said = live.reachNone.get(hub);
26854
+ if (said && id && this.host.linkReady(id)) for (const key of said) none.add(key);
26855
+ }
26856
+ if (!none.size || none.has(me)) return [];
26857
+ const lost = [...none].filter((key) => rosterHas(session.roster, key) && !legacy.includes(key)).sort();
26858
+ const standing = session.roster.map(([key]) => key).filter((key) => !none.has(key) && !hubs.includes(key) && !legacy.includes(key) && !live.departed.has(key));
26859
+ const at = `${lost.join(",")}|${standing.join(",")}`;
26860
+ if (live.standFor.at !== at) live.standFor = {
26861
+ at,
26862
+ mine: lost.length ? standInDuty(lost, standing).get(me) ?? [] : []
26863
+ };
26864
+ return live.standFor.mine;
26865
+ }
26866
+ /**
26867
+ * As a hub: the members that neither I (on an edge that is up) nor any hub I hear from (its `group-reach`, on its edge
26868
+ * with me) has reached for `standInAfterMs`, but apps without hubs (the admin keeps their edges): what I say in `u`.
26869
+ */
26870
+ nobodyReaches(groupId, session, live, up, now) {
26871
+ const edges = this.host.edges(groupId), hubs = this.hubs(groupId, session, now);
26872
+ const reached = /* @__PURE__ */ new Set([
26873
+ ...up,
26874
+ ...hubs,
26875
+ session.myKey
26876
+ ]);
26877
+ for (const hub of hubs) {
26878
+ const id = edges.get(hub), keys = live.reach.get(hub);
26879
+ if (keys && id && this.host.linkReady(id)) for (const key of keys) reached.add(key);
26880
+ }
26881
+ const legacy = new Set(this.legacyOf(groupId)), out = [];
26882
+ for (const [key] of session.roster) {
26883
+ if (reached.has(key) || legacy.has(key) || live.departed.has(key)) {
26884
+ live.unreached.delete(key);
26885
+ continue;
26886
+ }
26887
+ const since = live.unreached.get(key) ?? now;
26888
+ live.unreached.set(key, since);
26889
+ if (now - since >= this.timings.standInAfterMs) out.push(key);
26890
+ }
26891
+ for (const key of live.unreached.keys()) if (!rosterHas(session.roster, key)) live.unreached.delete(key);
26892
+ const since = (key) => live.unreached.get(key);
26893
+ return out.sort((a, b) => since(b) - since(a) || (a < b ? -1 : 1)).slice(0, 16).sort();
26894
+ }
26895
+ /**
26725
26896
  * The members whose apps take no hubs: those whose own edge here said so (`edgeReady`, kept in `group`), and those a
26726
26897
  * hub of the beacon I still count on says so of its own edges, unless their own edge here said otherwise.
26727
26898
  */
@@ -26789,10 +26960,12 @@ var MeshHubs = class {
26789
26960
  live.hubSince = now;
26790
26961
  live.myHubs = [];
26791
26962
  live.need = session.others.length;
26963
+ live.unreached.clear();
26792
26964
  await this.publish(groupId, session, live, now, true).catch(() => {});
26793
26965
  } else if (live.hub && (!may || !fits || this.full(live, session, now))) {
26794
26966
  live.hub = false;
26795
26967
  live.members.clear();
26968
+ live.unreached.clear();
26796
26969
  if (!may || !fits) await this.publish(groupId, session, live, now, false).catch(() => {});
26797
26970
  } else if (live.hub && now - live.lastTry >= 5e3 && now >= live.publishAfter && (now - live.lastWrite >= this.timings.beaconEveryMs || !live.beacon.some((h) => h.key === me))) await this.publish(groupId, session, live, now, true).catch(() => {});
26798
26971
  if (live.hub) {
@@ -27011,7 +27184,8 @@ var MeshHubs = class {
27011
27184
  sayReach(groupId, session, live, now, only) {
27012
27185
  const edges = this.host.edges(groupId);
27013
27186
  const up = [...edges].filter(([key, id]) => rosterHas(session.roster, key) && this.host.linkReady(id)).map(([key]) => key).sort();
27014
- const said = up.join(",");
27187
+ const none = this.nobodyReaches(groupId, session, live, up, now);
27188
+ const said = `${up.join(",")}|${none.join(",")}`;
27015
27189
  if (!only && (said === live.sentReach && now - live.lastReach < REACH_AGAIN_MS || now - live.lastReach < this.timings.reachEveryMs)) return;
27016
27190
  if (!only) {
27017
27191
  live.sentReach = said;
@@ -27022,7 +27196,8 @@ var MeshHubs = class {
27022
27196
  t: "group-reach",
27023
27197
  g: groupId,
27024
27198
  k: up,
27025
- ...legacy.length ? { l: legacy } : {}
27199
+ ...legacy.length ? { l: legacy } : {},
27200
+ ...none.length ? { u: none } : {}
27026
27201
  };
27027
27202
  for (const [key, id] of edges) {
27028
27203
  if (only && key !== only || !rosterHas(session.roster, key) || !this.host.linkReady(id)) continue;
@@ -27108,6 +27283,9 @@ var MeshHubs = class {
27108
27283
  }
27109
27284
  live.reach.set(from, reach);
27110
27285
  live.seenHubs.set(from, now);
27286
+ const none = Array.isArray(frame.u) && frame.u.length <= Math.min(16, session.roster.length) ? frame.u.filter((key) => typeof key === "string" && key !== session.myKey && !reach.has(key) && rosterHas(session.roster, key)) : [];
27287
+ if (none.length) live.reachNone.set(from, new Set(none));
27288
+ else live.reachNone.delete(from);
27111
27289
  if (!Array.isArray(frame.l) || frame.l.length > session.roster.length) {
27112
27290
  live.reachLegacy.delete(from);
27113
27291
  return;
@@ -27130,7 +27308,8 @@ var MeshHubs = class {
27130
27308
  }
27131
27309
  /**
27132
27310
  * As a hub, what the session took for the first time goes on to every other edge that is up: not back where it came
27133
- * from, nor to its author. Everyone else takes it as a frame handed on (WISP 902 § Catch-up).
27311
+ * from, nor to its author. Everyone else takes it as a frame handed on (WISP 902 § Catch-up); a member, a commit with
27312
+ * the epoch's secret sealed for it when I hold it (`GroupSession.handOnTo`), so it can write at once.
27134
27313
  */
27135
27314
  passOn(groupId, session, from, frames) {
27136
27315
  if (!this.live.get(groupId)?.hub || !frames.length) return 0;
@@ -27142,7 +27321,7 @@ var MeshHubs = class {
27142
27321
  for (const frame of frames) {
27143
27322
  if (authorOf(frame) === key || !member && (frame.t !== "group-commit" || frame.commit.e > until)) continue;
27144
27323
  try {
27145
- this.host.sendOnLink(id, frame);
27324
+ this.host.sendOnLink(id, member ? session.handOnTo(key, frame) : frame);
27146
27325
  sent++;
27147
27326
  } catch {
27148
27327
  break;
@@ -27631,23 +27810,21 @@ function newestMarked(history) {
27631
27810
  * chat): the marks it moved go back to the newest line still kept, as `load` reads them, and the record's `came` it
27632
27811
  * raised goes too. A mark a newer line moved stays, and the history is read only when the message moved one
27633
27812
  * (`markedBy`): removals go at the pace of edits. `history`: the group's rows, with it gone. True when `came` changed
27634
- * (the record is to be saved).
27813
+ * (the record is to be saved). `mentionOnly`: an edit took my mention out of it: the message is still there, so only
27814
+ * the "@" goes back.
27635
27815
  */
27636
- async function unmark(marks, group, groupId, history, removed) {
27816
+ async function unmark(marks, group, groupId, history, removed, mentionOnly = false) {
27637
27817
  const by = marks.by.get(groupId);
27638
- if (!by || ![
27639
- by.last,
27640
- by.peer,
27641
- by.mention
27642
- ].includes(removed.id)) return false;
27818
+ const last = !mentionOnly && by?.last === removed.id, peer = !mentionOnly && by?.peer === removed.id, mention = by?.mention === removed.id;
27819
+ if (!by || !(last || peer || mention)) return false;
27643
27820
  const newest = newestMarked((await history()).filter((m) => m.id !== removed.id));
27644
27821
  const back = (map, row) => {
27645
27822
  if (row) map.set(groupId, row.timestamp);
27646
27823
  else map.delete(groupId);
27647
27824
  };
27648
27825
  let came = false;
27649
- if (by.last === removed.id) back(marks.lastMessageAt, newest.last);
27650
- if (by.peer === removed.id) {
27826
+ if (last) back(marks.lastMessageAt, newest.last);
27827
+ if (peer) {
27651
27828
  back(marks.lastPeerMessageAt, newest.peer);
27652
27829
  if (group?.came?.peer !== void 0) {
27653
27830
  group.came = {
@@ -27657,7 +27834,7 @@ async function unmark(marks, group, groupId, history, removed) {
27657
27834
  came = true;
27658
27835
  }
27659
27836
  }
27660
- if (by.mention === removed.id) {
27837
+ if (mention) {
27661
27838
  back(marks.lastMentionAt, newest.mention);
27662
27839
  if (group?.came?.mention !== void 0) {
27663
27840
  group.came = {
@@ -27668,9 +27845,9 @@ async function unmark(marks, group, groupId, history, removed) {
27668
27845
  }
27669
27846
  }
27670
27847
  marks.by.set(groupId, {
27671
- last: by.last === removed.id ? newest.last?.id : by.last,
27672
- peer: by.peer === removed.id ? newest.peer?.id : by.peer,
27673
- mention: by.mention === removed.id ? newest.mention?.id : by.mention
27848
+ last: last ? newest.last?.id : by.last,
27849
+ peer: peer ? newest.peer?.id : by.peer,
27850
+ mention: mention ? newest.mention?.id : by.mention
27674
27851
  });
27675
27852
  return came;
27676
27853
  }
@@ -27760,6 +27937,8 @@ var LEFT_KEPT_MS = 6048e5;
27760
27937
  var LEFT_HAND_ON_MS = 1e3;
27761
27938
  /** The commits of my chain since my leave said to the admin my leave follows, before the leave (it may lack them). */
27762
27939
  var LEFT_COMMITS = 16;
27940
+ /** How long a tombstone the role went on from stays after the commit removing it, for the leaves that followed the role to it. */
27941
+ var LEFT_PASSED_ON_MS = 12e4;
27763
27942
  /** Admin side: how long a contact invited over its chat is waited for. After, it holds no place and may be invited again. */
27764
27943
  var INVITED_KEPT_MS = LEFT_KEPT_MS;
27765
27944
  /**
@@ -28040,6 +28219,7 @@ var Groups = class {
28040
28219
  edges: (groupId) => host.edges(groupId),
28041
28220
  ready: (linkId) => host.linkReady(linkId, 6),
28042
28221
  membership: (groupId) => this.fileMembership(groupId),
28222
+ out: (groupId) => this.fileOut(groupId),
28043
28223
  sendApp: (groupId, frame) => this.communities.sendApp(groupId, frame),
28044
28224
  changed: () => host.emit(),
28045
28225
  now: () => this.now()
@@ -28091,6 +28271,7 @@ var Groups = class {
28091
28271
  bytes: frameBytes(m.frame)
28092
28272
  })));
28093
28273
  if (group.state) this.attach(group.state, framed.map((m) => m.frame));
28274
+ this.ownRows(group.id, history);
28094
28275
  if (group.invited) this.invited.set(group.id, new Set(Object.keys(group.invited)));
28095
28276
  loadMarks(this.marks, group, history);
28096
28277
  this.host.loaded?.(group.id, history);
@@ -28247,6 +28428,19 @@ var Groups = class {
28247
28428
  return this.communities.has(groupId);
28248
28429
  }
28249
28430
  /**
28431
+ * A private group's roster in admission order, its admin and my key: what the edge each member keeps while the group
28432
+ * is not on screen is computed from (`keptMeshPeer`, WISP 902 § Transports). Undefined for a community or no session.
28433
+ */
28434
+ meshOrder(groupId) {
28435
+ const session = this.sessions.get(groupId);
28436
+ if (!session || this.isCommunity(groupId)) return void 0;
28437
+ return {
28438
+ order: session.admissionOrder,
28439
+ admin: session.admin,
28440
+ me: session.myKey
28441
+ };
28442
+ }
28443
+ /**
28250
28444
  * What paces a private group's edges (`meshEdgeIntervals`), as a roster of that many members would: the roster in a
28251
28445
  * full mesh, the edges this member keeps (and one) with hubs. 0 for no group.
28252
28446
  */
@@ -28634,6 +28828,12 @@ var Groups = class {
28634
28828
  couldRead: (key, messageId, ts) => session.couldRead(key, messageId, ts)
28635
28829
  };
28636
28830
  }
28831
+ /** Why this device is out of the group for good, as `fileCheck` says it; undefined while it is in it, or not loaded. */
28832
+ fileOut(groupId) {
28833
+ const session = this.isCommunity(groupId) ? this.communities.session(groupId) : this.sessions.get(groupId);
28834
+ if (!session || session.status === "active") return void 0;
28835
+ return session.state.statusReason ?? "You are no longer in this group";
28836
+ }
28637
28837
  /**
28638
28838
  * This side is typing in a private group (with what it is doing), or stopped (WISP 902 · Group Mesh § Typing).
28639
28839
  * Nothing for a community: it does not carry typing yet.
@@ -28776,11 +28976,21 @@ var Groups = class {
28776
28976
  delete group.owedBye;
28777
28977
  this.store.putGroup(group).catch(() => {});
28778
28978
  }
28779
- /** The admin heard me: the tombstone of a group I left can go. */
28979
+ /**
28980
+ * The admin heard me: the tombstone of a group I left can go. One the role went on from stays `LEFT_PASSED_ON_MS`
28981
+ * more (`holdsRole`): a member whose leave followed the role to me may not have reached me yet, and only I can tell
28982
+ * it where the role went.
28983
+ */
28780
28984
  async leaveConfirmed(groupId) {
28781
28985
  if (!this.stored.get(groupId)?.left) return;
28986
+ if (this.holdsRole(groupId, this.sessions.get(groupId))) {
28987
+ if (!this.passedOnUntil.has(groupId)) this.passedOnUntil.set(groupId, this.now() + LEFT_PASSED_ON_MS);
28988
+ return;
28989
+ }
28782
28990
  await this.forget(groupId);
28783
28991
  }
28992
+ /** Tombstones the role went on from, removed already, and when they go (`leaveConfirmed`). */
28993
+ passedOnUntil = /* @__PURE__ */ new Map();
28784
28994
  async remove(groupId, key) {
28785
28995
  if (this.isCommunity(groupId)) return this.communities.remove(groupId, key);
28786
28996
  const session = this.session(groupId), group = this.stored.get(groupId);
@@ -28894,10 +29104,11 @@ var Groups = class {
28894
29104
  const by = (this.isCommunity(groupId) ? this.communities.markedBy(groupId) : this.marks.by.get(groupId)) ?? {};
28895
29105
  return by.last === messageId || by.peer === messageId || by.mention === messageId;
28896
29106
  }
28897
- async unmark(groupId, removed) {
28898
- if (this.isCommunity(groupId)) return this.communities.unmark(groupId, removed);
29107
+ /** `mentionOnly`: an edit took my mention out of the message, which stays: its "@" alone goes back. */
29108
+ async unmark(groupId, removed, mentionOnly = false) {
29109
+ if (this.isCommunity(groupId)) return this.communities.unmark(groupId, removed, mentionOnly);
28899
29110
  const group = this.stored.get(groupId);
28900
- if (await unmark(this.marks, group, groupId, () => this.store.getMessages(MESSAGE_LINK(groupId)), removed) && group) await this.store.putGroup(group);
29111
+ if (await unmark(this.marks, group, groupId, () => this.store.getMessages(MESSAGE_LINK(groupId)), removed, mentionOnly) && group) await this.store.putGroup(group);
28901
29112
  }
28902
29113
  /** The connection of an edge opened. One kept to tell a removed member closes a while after, whatever its app says or does not say. */
28903
29114
  edgeOpen(groupId, peerKey) {
@@ -28985,6 +29196,7 @@ var Groups = class {
28985
29196
  this.stored.delete(groupId);
28986
29197
  this.leavesHeard.delete(groupId);
28987
29198
  this.handOnAt.delete(groupId);
29199
+ this.passedOnUntil.delete(groupId);
28988
29200
  this.takeBack(groupId);
28989
29201
  this.acceptSaid.delete(groupId);
28990
29202
  this.entryHosts.delete(groupId);
@@ -29148,7 +29360,7 @@ var Groups = class {
29148
29360
  const quiet = [];
29149
29361
  for (const group of [...this.stored.values()]) {
29150
29362
  if (group.left) {
29151
- if (now - group.left.at > LEFT_KEPT_MS) {
29363
+ if (now - group.left.at > LEFT_KEPT_MS || now >= (this.passedOnUntil.get(group.id) ?? Infinity)) {
29152
29364
  await this.forget(group.id);
29153
29365
  continue;
29154
29366
  }
@@ -29921,6 +30133,7 @@ var Groups = class {
29921
30133
  return;
29922
30134
  }
29923
30135
  const taken = await session.handle(peerKey, frame);
30136
+ for (const f of taken) if (f.t === "group-bye" && f.k !== peerKey && this.hubs.departs(groupId, f.k)) this.host.emit();
29924
30137
  const askedAt = this.askedAt(groupId, peerKey);
29925
30138
  if (taken.some((f) => f.t === "group-msg" && f.ts < askedAt)) {
29926
30139
  let handed = this.lastHanded.get(groupId);
@@ -29971,12 +30184,20 @@ var Groups = class {
29971
30184
  */
29972
30185
  async afterLeave(groupId, from, raw) {
29973
30186
  const group = this.stored.get(groupId), left = group?.left, session = this.sessions.get(groupId);
29974
- if (!group || !left || !session || from !== left.admin && !left.hubs?.includes(from) || !raw || typeof raw !== "object") return;
30187
+ if (!group || !left || !session || !raw || typeof raw !== "object") return;
29975
30188
  const t = raw.t;
30189
+ const holding = t === "group-leave" && this.holdsRole(groupId, session) && rosterHas(session.roster, from);
30190
+ if (from !== left.admin && !left.hubs?.includes(from) && !holding) return;
29976
30191
  if (t === "group-leave" && from !== session.myKey) {
29977
30192
  let heard = this.leavesHeard.get(groupId);
29978
30193
  if (!heard) this.leavesHeard.set(groupId, heard = /* @__PURE__ */ new Set());
29979
30194
  heard.add(from);
30195
+ if (holding && session.admin !== session.myKey) {
30196
+ const edge = this.host.edges(groupId).get(from);
30197
+ if (edge) try {
30198
+ this.sayCommitsSinceLeave(groupId, session, group, edge);
30199
+ } catch {}
30200
+ }
29980
30201
  return;
29981
30202
  }
29982
30203
  if (t !== "group-commit") return;
@@ -29984,10 +30205,23 @@ var Groups = class {
29984
30205
  if (session.status !== "left" || !await session.followAfterLeave(raw)) return;
29985
30206
  if (session.admin === session.myKey) {
29986
30207
  this.handOnAt.set(groupId, this.now() + LEFT_HAND_ON_MS);
30208
+ this.reconcileEdges(groupId);
29987
30209
  return;
29988
30210
  }
29989
30211
  await this.leaveFollows(groupId);
29990
30212
  }
30213
+ /**
30214
+ * A tombstone the role reached, until it goes: it keeps edges to every member, as an admin does (past the size where
30215
+ * hubs start, the ones to its hubs: they carry leaves and commits), so the leaves that follow the role reach it, and
30216
+ * its `role` commit handing it on reaches them (a member whose leave the role passed by has no other way to hear where
30217
+ * it went). Also when the role reached my leave while it was under way, and went on in the same step: a `role` commit
30218
+ * of mine past the epoch my leave was signed in.
30219
+ */
30220
+ holdsRole(groupId, session) {
30221
+ if (session?.status !== "left") return false;
30222
+ const since = this.stored.get(groupId)?.left?.bye?.e ?? session.epoch - 1;
30223
+ return session.admin === session.myKey || session.state.chain.some((c) => c.k === "role" && c.by === session.myKey && c.e > since);
30224
+ }
29991
30225
  /** My tombstone's chain moved: my leave goes to the admin it names now, over our edge when it is up (and when it opens). */
29992
30226
  async leaveFollows(groupId) {
29993
30227
  const group = this.stored.get(groupId), left = group?.left, session = this.sessions.get(groupId);
@@ -30018,13 +30252,17 @@ var Groups = class {
30018
30252
  * role came to it from a leaver, whose edge with it is the only one up), then the leave.
30019
30253
  */
30020
30254
  sayLeave(groupId, session, group, linkId) {
30021
- const since = group.left?.bye?.e ?? session.epoch;
30022
- for (let e = Math.max(since + 1, session.epoch - LEFT_COMMITS + 1); e <= session.epoch; e++) this.host.sendOnLink(linkId, farewellCommit(groupId, session, e));
30255
+ this.sayCommitsSinceLeave(groupId, session, group, linkId);
30023
30256
  this.host.sendOnLink(linkId, {
30024
30257
  t: "group-leave",
30025
30258
  g: groupId
30026
30259
  });
30027
30260
  }
30261
+ /** The commits of my chain since I left (at most `LEFT_COMMITS`), without a secret. */
30262
+ sayCommitsSinceLeave(groupId, session, group, linkId) {
30263
+ const since = group.left?.bye?.e ?? session.epoch;
30264
+ for (let e = Math.max(since + 1, session.epoch - LEFT_COMMITS + 1); e <= session.epoch; e++) this.host.sendOnLink(linkId, farewellCommit(groupId, session, e));
30265
+ }
30028
30266
  /** A tombstone the role reached: it goes on (`nextAdmin`), and my leave with it. */
30029
30267
  async handOn(groupId) {
30030
30268
  const session = this.sessions.get(groupId);
@@ -30519,6 +30757,7 @@ var Groups = class {
30519
30757
  for (const [groupId, session] of this.sessions) {
30520
30758
  if (session.status !== "active" || this.stored.get(groupId)?.left) continue;
30521
30759
  session.reseal().catch(() => {});
30760
+ session.resume().catch(() => {});
30522
30761
  session.sayName().catch(() => {});
30523
30762
  this.farewellsTick(groupId, session, now);
30524
30763
  this.heldSyncs(groupId, session, now);
@@ -30597,6 +30836,20 @@ var Groups = class {
30597
30836
  if (!session) throw new Error("Group not found");
30598
30837
  return session;
30599
30838
  }
30839
+ /** Tells a group's session the numbers its own rows hold (`GroupSession.ownRows`). */
30840
+ ownRows(groupId, history) {
30841
+ const session = this.sessions.get(groupId);
30842
+ if (!session) return;
30843
+ const rows = [];
30844
+ for (const m of history) {
30845
+ const ref = m.sender === "me" ? meshMessageRef(m.id) : null;
30846
+ if (ref && ref.s === session.myKey) rows.push({
30847
+ epoch: ref.e,
30848
+ seq: ref.n
30849
+ });
30850
+ }
30851
+ session.ownRows(rows);
30852
+ }
30600
30853
  /** `frames`: what the group's rows hold to hand on, oldest first (none yet for a group just made, joined or given back). */
30601
30854
  attach(state, frames = []) {
30602
30855
  const session = new GroupSession(state, {
@@ -30746,8 +30999,8 @@ var Groups = class {
30746
30999
  if (top.k === "rotate") await this.event(groupId, "rotated", "Keys rotated: a fresh epoch", when, top.e);
30747
31000
  }
30748
31001
  const group = this.stored.get(groupId);
30749
- if (session.status === "active" && group && pinOfFormerMember(group.pin, (key) => rosterHas(after, key))) {
30750
- group.pin = void 0;
31002
+ if (session.status === "active" && group?.pin && pinOfFormerMember(group.pin, (key) => rosterHas(after, key))) {
31003
+ group.pin = droppedPin(group.pin, this.now());
30751
31004
  await this.store.putGroup(group);
30752
31005
  }
30753
31006
  this.reconcileEdges(groupId);
@@ -30771,7 +31024,11 @@ var Groups = class {
30771
31024
  const existing = this.host.edges(groupId);
30772
31025
  const left = group?.left;
30773
31026
  const removed = this.removedAt.get(groupId);
30774
- const wanted = session?.status === "active" && group ? this.edgesWanted(groupId, session, group, this.now()) : left ? /* @__PURE__ */ new Set([left.admin, ...left.hubs ?? []]) : removed !== void 0 && this.now() - removed < REMOVED_LINGER_MS ? new Set(existing.keys()) : /* @__PURE__ */ new Set();
31027
+ const wanted = session?.status === "active" && group ? this.edgesWanted(groupId, session, group, this.now()) : left ? /* @__PURE__ */ new Set([
31028
+ left.admin,
31029
+ ...left.hubs ?? [],
31030
+ ...this.holdsRole(groupId, session) && !this.hubs.large(session) ? session.others : []
31031
+ ]) : removed !== void 0 && this.now() - removed < REMOVED_LINGER_MS ? new Set(existing.keys()) : /* @__PURE__ */ new Set();
30775
31032
  for (const [key, linkId] of existing) if (!wanted.has(key)) await this.host.closeEdge(linkId);
30776
31033
  const met = this.justMet.get(groupId);
30777
31034
  if (session) {
@@ -30853,6 +31110,29 @@ function edgeView(live, now = Date.now(), noSlot = false) {
30853
31110
  };
30854
31111
  }
30855
31112
  /**
31113
+ * The member whose edge a member of a private group keeps while the group is not on screen (WISP 902 § Transports,
31114
+ * revision 2026-11-04), from the roster in admission order (`GroupSession.admissionOrder`, the creator first): the
31115
+ * member admitted just before it, which it knows from its welcome. The first member keeps the edge to the second,
31116
+ * which keeps the same one: the one member every later member knows from its welcome, so the roster it learns there
31117
+ * reaches everyone (a member's edge to the newest would bring nothing: the newest knew it all, and nobody knows it
31118
+ * yet). The newest keeps the edge to the admin, which admitted it and so knows it at once (to the first member where
31119
+ * the admin is the newest); the admin answers it as one a member keeps (`chosenByPeer`). So the edges kept make a tree
31120
+ * over the whole roster (connected, N - 1 edges, each member on two of them at most, the admin on three where it is
31121
+ * not the first), both ends compute the same one from the same roster, and a join or a leave changes what two
31122
+ * members keep at most. Undefined when `me` is not in it or nobody else is.
31123
+ */
31124
+ function keptMeshPeer(order, admin, me) {
31125
+ const at = order.indexOf(me), last = order.length - 1;
31126
+ if (at < 0 || last < 1) return void 0;
31127
+ if (at === 0) return order[1];
31128
+ if (at < last) return order[at - 1];
31129
+ return admin !== void 0 && admin !== me && order.includes(admin) ? admin : order[0];
31130
+ }
31131
+ /** The members whose kept edge (`keptMeshPeer`) is the one to `me`: the edges this member answers by the rule. */
31132
+ function meshPeersKeeping(order, admin, me) {
31133
+ return order.filter((key) => key !== me && keptMeshPeer(order, admin, key) === me);
31134
+ }
31135
+ /**
30856
31136
  * A pairing error the session ends with when nothing is wrong with the member: an attempt dialled again. Their
30857
31137
  * English is `PairedSession`'s and `GhostLink`'s (packages/core).
30858
31138
  */
@@ -31337,9 +31617,10 @@ var GroupEdits = class {
31337
31617
  const message = typeof messageId === "string" ? await this.find(chat, messageId) : void 0;
31338
31618
  if (!message || message.removed || message.sender !== "me" || !GROUP_MESSAGE_ID.test(message.id)) return refuse("Only your own messages can be deleted for everyone");
31339
31619
  if (!canRemove(message)) return refuse("A payment, a request or a notice cannot be deleted for everyone");
31620
+ const e = removalNumber(message.edit?.seq);
31340
31621
  await this.host.removeMine(chat, message, {
31341
31622
  id: message.id,
31342
- e: removalNumber(message.edit?.seq),
31623
+ e,
31343
31624
  at: this.now(),
31344
31625
  pending: true
31345
31626
  });
@@ -31347,7 +31628,8 @@ var GroupEdits = class {
31347
31628
  await this.flush(groupId).catch(() => {});
31348
31629
  return {
31349
31630
  error: null,
31350
- messageId
31631
+ messageId,
31632
+ e
31351
31633
  };
31352
31634
  }
31353
31635
  /** What an edit or a removal in a group I am not in is refused with: the group's reason, as a message or a reaction is. */
@@ -31537,8 +31819,10 @@ var GroupEdits = class {
31537
31819
  const takes = (m) => takesPeerEdit(m, edit.m) && m.member === sender;
31538
31820
  if (!takes(message)) return "dropped";
31539
31821
  if ((message.edit?.seq ?? 0) >= edit.e) return "stale";
31540
- if (!await this.host.patch(chat, message.id, (current) => {
31822
+ let wasMentioned = false;
31823
+ const updated = await this.host.patch(chat, message.id, (current) => {
31541
31824
  if (!takes(current) || (current.edit?.seq ?? 0) >= edit.e) return null;
31825
+ wasMentioned = !!current.mentioned;
31542
31826
  const next = withEdit(current, {
31543
31827
  seq: edit.e,
31544
31828
  at: heardTime(edit.ts),
@@ -31552,7 +31836,9 @@ var GroupEdits = class {
31552
31836
  mentions: edit.k?.length ? edit.k : void 0,
31553
31837
  mentioned: mentionsMember(edit.k, me) ? true : void 0
31554
31838
  };
31555
- })) return "stale";
31839
+ });
31840
+ if (!updated) return "stale";
31841
+ if (wasMentioned && !updated.mentioned) await this.host.unmentioned?.(chat, updated);
31556
31842
  await this.host.changed(chat, message.id);
31557
31843
  return "applied";
31558
31844
  }
@@ -33821,7 +34107,7 @@ var ProfilePeek = class {
33821
34107
  state: link.dhtDeliveryState,
33822
34108
  transport: readOnly,
33823
34109
  background: true,
33824
- ratchet: link.ratchetState
34110
+ ratchet: link.ratchetState ?? emptyRatchetState()
33825
34111
  });
33826
34112
  let held = 0;
33827
34113
  if (holdable(link)) {
@@ -34143,6 +34429,8 @@ var TEST_COINS_WAIT_MS = 3e4;
34143
34429
  var HISTORY_SHOWN = 100;
34144
34430
  /** How long before a mint that could not say which restored ecash is spent is asked again. */
34145
34431
  var RESTORED_POLL_MS = 6e4;
34432
+ /** Asked twice as late each time it still cannot say, up to this. */
34433
+ var RESTORED_SLOW_POLL_MS = 18e5;
34146
34434
  /** How long before a mint that could not say where a swap stands is asked again. */
34147
34435
  var SWAP_POLL_MS = 3e4;
34148
34436
  /** The same, for a swap that holds nothing any more or whose mint cannot give signatures back: asked now and then. */
@@ -34153,8 +34441,15 @@ var SWAP_WATCH_MS = 36e5;
34153
34441
  var SPENT_KEPT = 1e3;
34154
34442
  /** The most coins `sendCoins` makes for one token. */
34155
34443
  var MAX_SEND_COINS = 64;
34156
- /** Cashu's library (174 KiB) loads with the wallet's first use of a mint or a token, not with the app's start. */
34157
- var loadCashu = () => import("@cashu/cashu-ts");
34444
+ /**
34445
+ * 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
34446
+ * redirect is refused on every request, not only on those with a body as the library does: `normalizeMintUrl` alone
34447
+ * says where the wallet's requests go.
34448
+ */
34449
+ var loadCashu = () => import("@cashu/cashu-ts").then((cashu) => {
34450
+ cashu.setGlobalRequestOptions({ redirect: "error" });
34451
+ return cashu;
34452
+ });
34158
34453
  async function reviewedCashuFee(preview) {
34159
34454
  const { Amount } = await loadCashu();
34160
34455
  const fee = preview.inputs.reduce((sum, proof) => sum + Amount.from(proof.amount).toNumber(), 0) - (preview.keepOutputs ?? []).reduce((sum, output) => sum + Amount.from(output.blindedMessage.amount).toNumber(), 0) - preview.amount.toNumber();
@@ -34176,6 +34471,11 @@ var SwapUnsettledError = class extends Error {
34176
34471
  this.name = "SwapUnsettledError";
34177
34472
  }
34178
34473
  };
34474
+ /**
34475
+ * A redeem the mint refused again after its outputs were made anew on its keyset: the wallet's own words for it, as a
34476
+ * contact is told when the mint never made a redeem (`PaymentDesk.onSwapSettled`). The token stays unspent.
34477
+ */
34478
+ var MINT_DID_NOT_CONFIRM = "The mint did not confirm the ecash";
34179
34479
  /** When a swap with no answer can no longer reach the mint: a request's longest life, and a margin after its last try. */
34180
34480
  var swapOverdueAt = (swap) => Math.max(swap.createdAt + CASHU_REQUEST_TIMEOUT_MS + SWAP_SETTLED_MS, (swap.attemptEndedAt ?? Number.POSITIVE_INFINITY) + SWAP_SETTLED_MS);
34181
34481
  /** When a melt with no answer can no longer reach the mint: its one request is sent right after it is written down. */
@@ -34335,10 +34635,14 @@ var CashuWallet = class CashuWallet {
34335
34635
  quoteWatched = /* @__PURE__ */ new Map();
34336
34636
  meltTimer = null;
34337
34637
  /** Per pending melt: when it is asked about next and the wait before that, in this run (a restart asks at once). */
34338
- meltAsk = /* @__PURE__ */ new Map();
34638
+ meltAsk = new AskBackoff(MELT_POLL_MS, MELT_SLOW_POLL_MS);
34339
34639
  restoredTimer = null;
34340
34640
  swapTimer = null;
34341
34641
  swapTimerAt = 0;
34642
+ /** Per open swap whose mint did not answer past its overdue time: as `meltAsk`, in this run (a restart asks at once). */
34643
+ swapAsk = new AskBackoff(SWAP_POLL_MS, SWAP_SLOW_POLL_MS);
34644
+ /** Per mint that could not say which restored ecash is spent, or holds some pending: as `meltAsk`. */
34645
+ restoredAsk = new AskBackoff(RESTORED_POLL_MS, RESTORED_SLOW_POLL_MS);
34342
34646
  /** Per melt quote that ended unpaid: the sats the mint kept all the same (the fee of the split before the melt). */
34343
34647
  failedFees = /* @__PURE__ */ new Map();
34344
34648
  /** Melt quotes that ended unpaid with proofs the mint read spent: ecash spent somewhere else, said as such. */
@@ -34433,37 +34737,50 @@ var CashuWallet = class CashuWallet {
34433
34737
  * (by the profile it was copied from, or by this one before it was restored) still counted in the balance, for good,
34434
34738
  * and every payment that picked one of those proofs failed with the mint's "Token already spent". Each mint is asked
34435
34739
  * once which of them it still reads unspent: a spent proof is dropped, an unspent one is checked for good, and one
34436
- * the mint holds pending, or a mint that cannot be asked, is asked again later.
34740
+ * the mint holds pending, or a mint that cannot be asked, is asked again later: after RESTORED_POLL_MS, then twice
34741
+ * as late each time up to RESTORED_SLOW_POLL_MS (`restoredAsk`). `paced`: only the mints whose time came (the timer);
34742
+ * a start or a restore asks every one now.
34437
34743
  */
34438
- async checkRestored() {
34744
+ async checkRestored(paced = false) {
34439
34745
  if (this.restoredTimer) clearTimeout(this.restoredTimer);
34440
34746
  this.restoredTimer = null;
34441
34747
  if (this.stopped) return;
34442
34748
  const waiting = (p) => !!p.unchecked && !p.reserved;
34443
- let again = false, changed = false;
34444
- for (const mint of new Set((await this.allProofs()).filter(waiting).map((p) => p.mint))) try {
34445
- await this.locked(mint, async () => {
34446
- const proofs = (await this.allProofs()).filter((p) => p.mint === mint && waiting(p));
34447
- if (!proofs.length) return;
34448
- const states = await (await this.wallet(mint)).checkProofsStates(proofs);
34449
- if (states.length !== proofs.length) throw new Error("The mint answered for another number of proofs");
34450
- await this.sealedTransact([STORES$1.proofs], { [STORES$1.proofs]: proofs }, (stores) => {
34451
- proofs.forEach((proof, i) => {
34452
- const state = states[i]?.state;
34453
- if (state === "SPENT") stores[STORES$1.proofs].delete(proof.secret);
34454
- else if (state === "UNSPENT") {
34455
- const { unchecked: _checked, ...kept } = proof;
34456
- stores[STORES$1.proofs].put(kept);
34457
- } else again = true;
34749
+ let changed = false, next = Infinity;
34750
+ const mints = new Set((await this.allProofs()).filter(waiting).map((p) => p.mint));
34751
+ this.restoredAsk.keepOnly(mints);
34752
+ for (const mint of mints) {
34753
+ if (paced && !this.restoredAsk.due(mint, Date.now())) {
34754
+ next = Math.min(next, this.restoredAsk.at(mint, Date.now()));
34755
+ continue;
34756
+ }
34757
+ let again = false;
34758
+ try {
34759
+ await this.locked(mint, async () => {
34760
+ const proofs = (await this.allProofs()).filter((p) => p.mint === mint && waiting(p));
34761
+ if (!proofs.length) return;
34762
+ const states = await (await this.wallet(mint)).checkProofsStates(proofs);
34763
+ if (states.length !== proofs.length) throw new Error("The mint answered for another number of proofs");
34764
+ await this.sealedTransact([STORES$1.proofs], { [STORES$1.proofs]: proofs }, (stores) => {
34765
+ proofs.forEach((proof, i) => {
34766
+ const state = states[i]?.state;
34767
+ if (state === "SPENT") stores[STORES$1.proofs].delete(proof.secret);
34768
+ else if (state === "UNSPENT") {
34769
+ const { unchecked: _checked, ...kept } = proof;
34770
+ stores[STORES$1.proofs].put(kept);
34771
+ } else again = true;
34772
+ });
34458
34773
  });
34774
+ changed = true;
34459
34775
  });
34460
- changed = true;
34461
- });
34462
- } catch {
34463
- again = true;
34776
+ } catch {
34777
+ again = true;
34778
+ }
34779
+ if (again) next = Math.min(next, Date.now() + this.restoredAsk.missed(mint, Date.now()));
34780
+ else this.restoredAsk.forget(mint);
34464
34781
  }
34465
34782
  if (changed) this.events.onChange();
34466
- if (again && !this.stopped) this.restoredTimer = setTimeout(() => void this.checkRestored(), RESTORED_POLL_MS);
34783
+ if (next < Infinity && !this.stopped) this.restoredTimer = setTimeout(() => void this.checkRestored(true), Math.max(0, next - Date.now()));
34467
34784
  }
34468
34785
  /** Talks to the mint before it is added: a typo should not become a place to keep money. */
34469
34786
  async checkMint(url) {
@@ -34531,7 +34848,7 @@ var CashuWallet = class CashuWallet {
34531
34848
  paymentId,
34532
34849
  ...paysItsOwnInvoices(mint) ? { held: true } : {}
34533
34850
  };
34534
- await committed((await store(STORES$1.quotes, "readwrite")).put(quote));
34851
+ await this.putQuote(quote);
34535
34852
  this.quoteAsked.set(quote.quote, Date.now());
34536
34853
  this.pollQuotes();
34537
34854
  return quote;
@@ -34556,14 +34873,14 @@ var CashuWallet = class CashuWallet {
34556
34873
  */
34557
34874
  async vouch(invoice, said = true) {
34558
34875
  const wanted = invoice.trim().toLowerCase();
34559
- let quote = (await wrap((await store(STORES$1.quotes, "readonly")).getAll())).find((q) => q.invoice.toLowerCase() === wanted);
34876
+ let quote = (await this.quotes()).find((q) => q.invoice.toLowerCase() === wanted);
34560
34877
  if (!quote) return false;
34561
34878
  if (quote.held && said) {
34562
34879
  quote = {
34563
34880
  ...quote,
34564
34881
  held: void 0
34565
34882
  };
34566
- await committed((await store(STORES$1.quotes, "readwrite")).put(quote));
34883
+ await this.putQuote(quote);
34567
34884
  }
34568
34885
  this.quoteWatched.set(quote.quote, Date.now() + INVOICE_PACE.watchMs);
34569
34886
  if (!(await this.settleQuotes([quote])).length && !quote.held && !quote.issuedUnclaimed) this.scheduleQuotes(this.nextAsk(quote, Date.now()));
@@ -34592,7 +34909,7 @@ var CashuWallet = class CashuWallet {
34592
34909
  expiresAt: response.expiry ? response.expiry * 1e3 : null,
34593
34910
  testCoins: true
34594
34911
  };
34595
- await committed((await store(STORES$1.quotes, "readwrite")).put(quote));
34912
+ await this.putQuote(quote);
34596
34913
  const deadline = Date.now() + TEST_COINS_WAIT_MS;
34597
34914
  for (;;) {
34598
34915
  if (await this.locked(mint, () => this.settleQuote(quote.quote))) {
@@ -34620,7 +34937,12 @@ var CashuWallet = class CashuWallet {
34620
34937
  }
34621
34938
  /** Every invoice of ours the mints have not settled yet, held, paid-unclaimed and issued-unclaimed ones included. */
34622
34939
  async quotes() {
34623
- return wrap((await store(STORES$1.quotes, "readonly")).getAll());
34940
+ return openRows(STORES$1.quotes, await wrap((await store(STORES$1.quotes, "readonly")).getAll()));
34941
+ }
34942
+ /** Sealed before its transaction opens, when the profile is encrypted: a paid quote's outputs can be minted from. */
34943
+ async putQuote(quote) {
34944
+ const row = await sealRow(STORES$1.quotes, quote);
34945
+ await committed((await store(STORES$1.quotes, "readwrite")).put(row));
34624
34946
  }
34625
34947
  /**
34626
34948
  * Invoices are paid by someone else, somewhere else; all we can do is ask the mint. A quote is the only
@@ -34685,7 +35007,7 @@ var CashuWallet = class CashuWallet {
34685
35007
  }
34686
35008
  /** Runs under the mint's lock, so two rounds never mint one quote twice. Returns the quote once its ecash is in. */
34687
35009
  async settleQuote(id) {
34688
- const quote = await wrap((await store(STORES$1.quotes, "readonly")).get(id));
35010
+ const quote = await openRow(STORES$1.quotes, await wrap((await store(STORES$1.quotes, "readonly")).get(id)));
34689
35011
  if (!quote || quote.issuedUnclaimed || quote.held) return null;
34690
35012
  const wallet = await this.wallet(quote.mint);
34691
35013
  const { OutputData } = await loadCashu();
@@ -34700,10 +35022,10 @@ var CashuWallet = class CashuWallet {
34700
35022
  const issued = saved?.length ? await this.signedOutputs(wallet, saved) : void 0;
34701
35023
  if (Array.isArray(issued)) return this.storeMinted(quote, issued);
34702
35024
  console.warn(`[wallet] ${quote.mint} issued quote ${quote.quote} (${quote.amount} sats) but this wallet holds no ecash for it`);
34703
- await committed((await store(STORES$1.quotes, "readwrite")).put({
35025
+ await this.putQuote({
34704
35026
  ...quote,
34705
35027
  issuedUnclaimed: true
34706
- }));
35028
+ });
34707
35029
  return null;
34708
35030
  }
34709
35031
  const preview = await wallet.prepareMint("bolt11", quote.amount, {
@@ -34716,14 +35038,14 @@ var CashuWallet = class CashuWallet {
34716
35038
  paid: true,
34717
35039
  outputs: saved ? quote.outputs : preview.outputData.map((o) => OutputData.serialize(o))
34718
35040
  };
34719
- if (!quote.paid || !saved) await committed((await store(STORES$1.quotes, "readwrite")).put(written));
35041
+ if (!quote.paid || !saved) await this.putQuote(written);
34720
35042
  let proofs;
34721
35043
  try {
34722
35044
  proofs = await wallet.completeMint(preview);
34723
35045
  } catch (error) {
34724
35046
  if (mintRefused(error) && (await wallet.checkMintQuoteBolt11(quote.quote).catch(() => null))?.state === "PAID") {
34725
35047
  const { outputs: _refused, ...fresh } = written;
34726
- await committed((await store(STORES$1.quotes, "readwrite")).put(fresh));
35048
+ await this.putQuote(fresh);
34727
35049
  }
34728
35050
  throw error;
34729
35051
  }
@@ -34741,10 +35063,14 @@ var CashuWallet = class CashuWallet {
34741
35063
  STORES$1.walletTx,
34742
35064
  STORES$1.quotes
34743
35065
  ], { [STORES$1.proofs]: proofs }, (stores) => {
34744
- for (const p of proofs) stores[STORES$1.proofs].put(toStored(quote.mint, p));
35066
+ for (const p of proofs) stores[STORES$1.proofs].put({
35067
+ ...toStored(quote.mint, p),
35068
+ ...quote.restored ? { unchecked: true } : {}
35069
+ });
34745
35070
  stores[STORES$1.walletTx].put(tx);
34746
35071
  stores[STORES$1.quotes].delete(quote.quote);
34747
35072
  });
35073
+ if (quote.restored) this.checkRestored();
34748
35074
  return quote;
34749
35075
  }
34750
35076
  /** Where one of our invoices stands at its mint. Only a question: ecash is minted by the poll above. */
@@ -34796,7 +35122,10 @@ var CashuWallet = class CashuWallet {
34796
35122
  STORES$1.walletTx,
34797
35123
  STORES$1.swaps,
34798
35124
  ...kept ? [STORES$1.payments] : []
34799
- ], { [STORES$1.proofs]: keep }, (stores) => {
35125
+ ], {
35126
+ [STORES$1.proofs]: keep,
35127
+ [STORES$1.payments]: kept ? [kept] : []
35128
+ }, (stores) => {
34800
35129
  this.queueReplace(stores[STORES$1.proofs], mint, inputs, keep);
34801
35130
  stores[STORES$1.walletTx].put(tx);
34802
35131
  if (swap) stores[STORES$1.swaps].delete(swap.id);
@@ -34859,7 +35188,7 @@ var CashuWallet = class CashuWallet {
34859
35188
  }
34860
35189
  /** NUT-09 retrieves signatures for the exact saved outputs; it never creates another swap. */
34861
35190
  async recoverReviewedCashu(review, prepared) {
34862
- const stored = await wrap((await store(STORES$1.payments, "readonly")).get(review.id));
35191
+ const stored = await openRow(STORES$1.payments, await wrap((await store(STORES$1.payments, "readonly")).get(review.id)));
34863
35192
  if (stored?.token) return stored.token;
34864
35193
  const wallet = await this.wallet(prepared.mint);
34865
35194
  const { OutputData } = await loadCashu();
@@ -34930,7 +35259,10 @@ var CashuWallet = class CashuWallet {
34930
35259
  STORES$1.proofs,
34931
35260
  STORES$1.payments,
34932
35261
  STORES$1.walletTx
34933
- ], { [STORES$1.proofs]: keep }, (stores) => {
35262
+ ], {
35263
+ [STORES$1.proofs]: keep,
35264
+ [STORES$1.payments]: [record]
35265
+ }, (stores) => {
34934
35266
  this.queueReplace(stores[STORES$1.proofs], prepared.mint, preview.inputs.map((p) => toStored(prepared.mint, p)), keep);
34935
35267
  stores[STORES$1.payments].put(record);
34936
35268
  stores[STORES$1.walletTx].put({
@@ -35225,13 +35557,16 @@ var CashuWallet = class CashuWallet {
35225
35557
  * answer is missed the mint is asked what it did, and its word decides: the outputs it signed are the result, as the
35226
35558
  * answer would have been; a swap it says it never made is undone and the failure is thrown; and for as long as the
35227
35559
  * swap stays written down nothing is known to have failed, whatever the mint's words were (`SwapUnsettledError`):
35228
- * `pollSwaps` settles it. Runs under the mint's lock.
35560
+ * `pollSwaps` settles it. A redeem refused for the keyset of its outputs is made again on the mint's keyset now and
35561
+ * sent once more (`renewedReceive`); `renew` false: it already was. Runs under the mint's lock.
35229
35562
  */
35230
- async completeSwap(swap) {
35563
+ async completeSwap(swap, renew = true) {
35231
35564
  const { deserializeSwapPreview } = await loadCashu();
35232
35565
  try {
35233
35566
  return await (await this.wallet(swap.mint)).completeSwap(deserializeSwapPreview(swapOf(swap)));
35234
35567
  } catch (error) {
35568
+ const renewed = renew ? await this.renewedReceive(swap, error).catch(() => void 0) : void 0;
35569
+ if (renewed) return this.completeSwap(renewed, false);
35235
35570
  const refused = mintRefused(error) && swap.attemptEndedAt === void 0;
35236
35571
  const ended = {
35237
35572
  ...swap,
@@ -35243,7 +35578,8 @@ var CashuWallet = class CashuWallet {
35243
35578
  if (outcome.state === "never" && outcome.final) {
35244
35579
  await this.dropSwap(ended, outcome.gone);
35245
35580
  if (swap.kind === "receive") this.rememberSpent(swap.mint, outcome.gone);
35246
- throw outcome.gone.size > 0 ? Object.assign(engineError("ecashAlreadySpent"), { cause: error }) : error;
35581
+ if (outcome.gone.size > 0) throw Object.assign(engineError("ecashAlreadySpent"), { cause: error });
35582
+ throw swap.kind === "receive" && keysetRefused(error) ? Object.assign(/* @__PURE__ */ new Error(MINT_DID_NOT_CONFIRM), { cause: error }) : error;
35247
35583
  }
35248
35584
  this.swapsAgainIn(SWAP_POLL_MS);
35249
35585
  this.events.onChange();
@@ -35251,6 +35587,56 @@ var CashuWallet = class CashuWallet {
35251
35587
  }
35252
35588
  }
35253
35589
  /**
35590
+ * A redeem the mint refused for the keyset of its outputs (one it retired, or does not know, since they were made):
35591
+ * no request with those outputs is ever signed. While the mint reads every coin of its token unspent, nothing of it
35592
+ * happened, and it is written down again with new outputs on the keyset the mint signs with now (cashu-ts reloaded
35593
+ * the mint's keysets with the refusal), as `settleQuote` does for an invoice. Undefined when it is not that case.
35594
+ * Only asks: the caller sends it. Runs under the mint's lock.
35595
+ */
35596
+ async renewedReceive(swap, error) {
35597
+ if (swap.kind !== "receive" || swap.released || !keysetRefused(error)) return void 0;
35598
+ if (error.repaired === false) this.wallets.delete(swap.mint);
35599
+ const wallet = await this.wallet(swap.mint);
35600
+ const { deserializeSwapPreview, serializeSwapPreview } = await loadCashu();
35601
+ const { inputs } = deserializeSwapPreview(swapOf(swap));
35602
+ const states = await wallet.checkProofsStates(inputs.map((p) => ({
35603
+ secret: p.secret,
35604
+ id: p.id
35605
+ })));
35606
+ if (states.length !== inputs.length || states.some((s) => s.state !== "UNSPENT")) return void 0;
35607
+ const preview = await wallet.prepareSwapToReceive(swap.token ?? inputs);
35608
+ const { attemptEndedAt: _ended, askAt: _ask, stuck: _stuck, ...rest } = swap;
35609
+ const renewed = {
35610
+ ...rest,
35611
+ swap: serializeSwapPreview(preview)
35612
+ };
35613
+ await this.putSwap(renewed);
35614
+ return renewed;
35615
+ }
35616
+ /**
35617
+ * Sends a redeem `renewedReceive` wrote down again, after the call that made it was over (`pollSwaps`): stored and its
35618
+ * chat told as any redeem settled late; let go by `completeSwap` on the mint's word (spent, refused once more), and
35619
+ * its chat told that; still written down with no answer, asked about again.
35620
+ */
35621
+ async sendRenewed(swap, later) {
35622
+ try {
35623
+ const { keep } = await this.completeSwap(swap, false);
35624
+ if (await this.finishSwap(swap, keep, [], true)) {
35625
+ const told = await this.tellSwap(swap, true);
35626
+ if (swap.payment && told) await committed((await store(STORES$1.swaps, "readwrite")).delete(swap.id));
35627
+ else if (swap.payment) later(SWAP_POLL_MS);
35628
+ this.events.onChange();
35629
+ }
35630
+ } catch {
35631
+ if ((await this.swapsAt(swap.mint)).some((s) => s.id === swap.id)) {
35632
+ later(SWAP_POLL_MS);
35633
+ return;
35634
+ }
35635
+ await this.tellSwap(swap, false);
35636
+ this.events.onChange();
35637
+ }
35638
+ }
35639
+ /**
35254
35640
  * Asks the mint where a written-down swap stands. It only asks: nothing is sent again, nothing is stored.
35255
35641
  * `refused`: the mint refused the only request ever made for this swap, so no request of it is still on its way.
35256
35642
  * Throws when the mint cannot be asked, or answers with an error: only its answers count.
@@ -35333,7 +35719,10 @@ var CashuWallet = class CashuWallet {
35333
35719
  STORES$1.swaps,
35334
35720
  STORES$1.walletTx,
35335
35721
  ...swap.payment ? [STORES$1.payments] : []
35336
- ], { [STORES$1.proofs]: [...keep, ...send] }, (stores) => {
35722
+ ], {
35723
+ [STORES$1.proofs]: [...keep, ...send],
35724
+ [STORES$1.payments]: swap.payment ? [swap.payment] : []
35725
+ }, (stores) => {
35337
35726
  const current = stores[STORES$1.swaps].get(swap.id);
35338
35727
  current.onsuccess = () => {
35339
35728
  const kept = current.result;
@@ -35446,113 +35835,131 @@ var CashuWallet = class CashuWallet {
35446
35835
  if (this.stopped) return;
35447
35836
  }
35448
35837
  const open = (await this.readSwaps()).filter((s) => !mints || mints.includes(s.mint));
35838
+ if (!mints) this.swapAsk.keepOnly(new Set(open.map((s) => s.id)));
35449
35839
  let again = 0;
35450
35840
  const later = (ms) => {
35451
35841
  again = again ? Math.min(again, ms) : ms;
35452
35842
  };
35453
- for (const { id, mint } of open) await this.locked(mint, async () => {
35454
- let swap = await openRow(STORES$1.swaps, await wrap((await store(STORES$1.swaps, "readonly")).get(id)));
35455
- if (!swap) return;
35456
- try {
35457
- if (swap.finished) {
35458
- if (await this.tellSwap(swap, true)) await committed((await store(STORES$1.swaps, "readwrite")).delete(swap.id));
35459
- else later(SWAP_POLL_MS);
35460
- return;
35461
- }
35462
- if (swap.askAt && Date.now() < swap.askAt && !mints) {
35463
- later(swap.askAt - Date.now());
35464
- return;
35465
- }
35466
- if (swap.attemptEndedAt === void 0) {
35467
- swap = {
35468
- ...swap,
35469
- attemptEndedAt: Date.now()
35470
- };
35471
- await this.putSwap(swap);
35472
- }
35473
- const outcome = await this.swapOutcome(swap);
35474
- if (outcome.state === "open") {
35475
- if (swap.released && Date.now() >= swap.createdAt + SWAP_WATCH_MS) {
35476
- await this.dropSwap(swap, /* @__PURE__ */ new Set());
35843
+ for (const { id, mint } of open) {
35844
+ if (!mints && !this.swapAsk.due(id, Date.now())) {
35845
+ later(this.swapAsk.at(id, Date.now()) - Date.now());
35846
+ continue;
35847
+ }
35848
+ await this.locked(mint, async () => {
35849
+ let swap = await openRow(STORES$1.swaps, await wrap((await store(STORES$1.swaps, "readonly")).get(id)));
35850
+ if (!swap) return;
35851
+ try {
35852
+ if (swap.finished) {
35853
+ if (await this.tellSwap(swap, true)) await committed((await store(STORES$1.swaps, "readwrite")).delete(swap.id));
35854
+ else later(SWAP_POLL_MS);
35477
35855
  return;
35478
35856
  }
35479
- if (outcome.slow) {
35480
- const stuck = (swap.stuck ?? 0) + 1;
35481
- const wait = stuck <= 6 ? SWAP_SLOW_POLL_MS : stuck <= 30 ? 36e5 : 864e5;
35482
- await this.putSwap({
35857
+ if (swap.askAt && Date.now() < swap.askAt && !mints) {
35858
+ later(swap.askAt - Date.now());
35859
+ return;
35860
+ }
35861
+ if (swap.attemptEndedAt === void 0) {
35862
+ swap = {
35483
35863
  ...swap,
35484
- stuck,
35485
- askAt: Date.now() + wait
35486
- });
35487
- if (stuck === 1) this.events.onChange();
35488
- later(wait);
35489
- } else if (outcome.idle && swap.kind === "receive" && !swap.released) {
35490
- const { deserializeSwapPreview } = await loadCashu();
35491
- try {
35492
- const { keep } = await (await this.wallet(mint)).completeSwap(deserializeSwapPreview(swapOf(swap)));
35493
- if (await this.finishSwap(swap, keep, [], true)) {
35494
- const told = await this.tellSwap(swap, true);
35495
- if (swap.payment && told) await committed((await store(STORES$1.swaps, "readwrite")).delete(swap.id));
35496
- else if (swap.payment) later(SWAP_POLL_MS);
35497
- this.events.onChange();
35498
- }
35499
- } catch (error) {
35500
- swap = {
35864
+ attemptEndedAt: Date.now()
35865
+ };
35866
+ await this.putSwap(swap);
35867
+ }
35868
+ let outcome = await this.swapOutcome(swap);
35869
+ this.swapAsk.forget(id);
35870
+ if (outcome.state === "never" && !outcome.final && swap.kind === "receive" && !swap.released) outcome = {
35871
+ state: "open",
35872
+ idle: true
35873
+ };
35874
+ if (outcome.state === "open") {
35875
+ if (swap.released && Date.now() >= swap.createdAt + SWAP_WATCH_MS) {
35876
+ await this.dropSwap(swap, /* @__PURE__ */ new Set());
35877
+ return;
35878
+ }
35879
+ if (outcome.slow) {
35880
+ const stuck = (swap.stuck ?? 0) + 1;
35881
+ const wait = stuck <= 6 ? SWAP_SLOW_POLL_MS : stuck <= 30 ? 36e5 : 864e5;
35882
+ await this.putSwap({
35501
35883
  ...swap,
35502
- attemptEndedAt: Date.now()
35503
- };
35504
- await this.putSwap(swap);
35505
- const refusal = mintRefused(error) ? await this.swapOutcome(swap, true).catch(() => void 0) : void 0;
35506
- if (refusal?.state === "done") {
35507
- if (await this.finishSwap(swap, refusal.keep, refusal.send, true)) {
35884
+ stuck,
35885
+ askAt: Date.now() + wait
35886
+ });
35887
+ if (stuck === 1) this.events.onChange();
35888
+ later(wait);
35889
+ } else if (outcome.idle && swap.kind === "receive" && !swap.released) {
35890
+ const { deserializeSwapPreview } = await loadCashu();
35891
+ try {
35892
+ const { keep } = await (await this.wallet(mint)).completeSwap(deserializeSwapPreview(swapOf(swap)));
35893
+ if (await this.finishSwap(swap, keep, [], true)) {
35508
35894
  const told = await this.tellSwap(swap, true);
35509
35895
  if (swap.payment && told) await committed((await store(STORES$1.swaps, "readwrite")).delete(swap.id));
35896
+ else if (swap.payment) later(SWAP_POLL_MS);
35897
+ this.events.onChange();
35510
35898
  }
35511
- this.events.onChange();
35512
- } else if (refusal?.state === "never") {
35513
- await this.dropSwap(swap, refusal.gone);
35899
+ } catch (error) {
35900
+ const renewed = await this.renewedReceive(swap, error).catch(() => void 0);
35901
+ if (renewed) {
35902
+ await this.sendRenewed(renewed, later);
35903
+ return;
35904
+ }
35905
+ swap = {
35906
+ ...swap,
35907
+ attemptEndedAt: Date.now()
35908
+ };
35909
+ await this.putSwap(swap);
35910
+ const refusal = mintRefused(error) ? await this.swapOutcome(swap, true).catch(() => void 0) : void 0;
35911
+ if (refusal?.state === "done") {
35912
+ if (await this.finishSwap(swap, refusal.keep, refusal.send, true)) {
35913
+ const told = await this.tellSwap(swap, true);
35914
+ if (swap.payment && told) await committed((await store(STORES$1.swaps, "readwrite")).delete(swap.id));
35915
+ }
35916
+ this.events.onChange();
35917
+ } else if (refusal?.state === "never") {
35918
+ await this.dropSwap(swap, refusal.gone);
35919
+ await this.tellSwap(swap, false);
35920
+ this.events.onChange();
35921
+ } else later(SWAP_POLL_MS);
35922
+ }
35923
+ } else if (outcome.pending && swap.kind === "receive" && !swap.released && Date.now() >= swapOverdueAt(swap)) {
35924
+ if (Date.now() < swap.createdAt + SWAP_WATCH_MS) {
35925
+ await this.putSwap({
35926
+ ...swap,
35927
+ askAt: Date.now() + SWAP_SLOW_POLL_MS
35928
+ });
35929
+ later(SWAP_SLOW_POLL_MS);
35930
+ } else {
35931
+ await this.dropSwap(swap, /* @__PURE__ */ new Set());
35514
35932
  await this.tellSwap(swap, false);
35515
35933
  this.events.onChange();
35516
- } else later(SWAP_POLL_MS);
35517
- }
35518
- } else if (outcome.pending && swap.kind === "receive" && !swap.released && Date.now() >= swapOverdueAt(swap)) {
35519
- if (Date.now() < swap.createdAt + SWAP_WATCH_MS) {
35520
- await this.putSwap({
35521
- ...swap,
35522
- askAt: Date.now() + SWAP_SLOW_POLL_MS
35523
- });
35524
- later(SWAP_SLOW_POLL_MS);
35525
- } else {
35526
- await this.dropSwap(swap, /* @__PURE__ */ new Set());
35527
- await this.tellSwap(swap, false);
35528
- this.events.onChange();
35934
+ }
35935
+ } else later(swap.released ? SWAP_SLOW_POLL_MS : SWAP_POLL_MS);
35936
+ return;
35937
+ }
35938
+ if (outcome.state === "done") {
35939
+ if (await this.finishSwap(swap, outcome.keep, outcome.send, true)) {
35940
+ const told = await this.tellSwap(swap, true);
35941
+ if (swap.payment && told) await committed((await store(STORES$1.swaps, "readwrite")).delete(swap.id));
35942
+ else if (swap.payment) later(SWAP_POLL_MS);
35529
35943
  }
35530
- } else later(swap.released ? SWAP_SLOW_POLL_MS : SWAP_POLL_MS);
35531
- return;
35532
- }
35533
- if (outcome.state === "done") {
35534
- if (await this.finishSwap(swap, outcome.keep, outcome.send, true)) {
35535
- const told = await this.tellSwap(swap, true);
35536
- if (swap.payment && told) await committed((await store(STORES$1.swaps, "readwrite")).delete(swap.id));
35537
- else if (swap.payment) later(SWAP_POLL_MS);
35944
+ } else if (swap.released) {
35945
+ if (outcome.final || Date.now() >= swap.createdAt + SWAP_WATCH_MS) await this.dropSwap(swap, outcome.gone);
35946
+ else later(SWAP_SLOW_POLL_MS);
35947
+ return;
35948
+ } else {
35949
+ await this.dropSwap(swap, outcome.gone, !outcome.final);
35950
+ await this.tellSwap(swap, false);
35951
+ if (!outcome.final) later(SWAP_SLOW_POLL_MS);
35538
35952
  }
35539
- } else if (swap.released) {
35540
- if (outcome.final || Date.now() >= swap.createdAt + SWAP_WATCH_MS) await this.dropSwap(swap, outcome.gone);
35541
- else later(SWAP_SLOW_POLL_MS);
35542
- return;
35543
- } else {
35544
- await this.dropSwap(swap, outcome.gone, !outcome.final);
35545
- await this.tellSwap(swap, false);
35546
- if (!outcome.final) later(SWAP_SLOW_POLL_MS);
35953
+ this.events.onChange();
35954
+ } catch {
35955
+ if (swap.released && Date.now() >= swap.createdAt + SWAP_WATCH_MS) await this.dropSwap(swap, /* @__PURE__ */ new Set()).catch(() => {});
35956
+ else if (swap.released) later(SWAP_SLOW_POLL_MS);
35957
+ else later(this.swapAsk.missed(id, Date.now(), Date.now() < swapOverdueAt(swap)));
35547
35958
  }
35548
- this.events.onChange();
35549
- } catch {
35550
- if (swap.released && Date.now() >= swap.createdAt + SWAP_WATCH_MS) await this.dropSwap(swap, /* @__PURE__ */ new Set()).catch(() => {});
35551
- else later(swap.released ? SWAP_SLOW_POLL_MS : SWAP_POLL_MS);
35552
- }
35553
- }).catch(() => {
35554
- later(SWAP_POLL_MS);
35555
- });
35959
+ }).catch(() => {
35960
+ later(SWAP_POLL_MS);
35961
+ });
35962
+ }
35556
35963
  if (again && !mints) this.swapsAgainIn(again);
35557
35964
  }
35558
35965
  /**
@@ -35710,8 +36117,7 @@ var CashuWallet = class CashuWallet {
35710
36117
  if (this.stopped) return;
35711
36118
  const melts = await this.readMelts();
35712
36119
  for (const melt of melts) {
35713
- const pace = this.meltAsk.get(melt.quote);
35714
- if (pace && Date.now() < pace.at) continue;
36120
+ if (!this.meltAsk.due(melt.quote, Date.now())) continue;
35715
36121
  try {
35716
36122
  const outcome = await this.locked(melt.mint, async () => {
35717
36123
  const current = await openRow(STORES$1.melts, await wrap((await store(STORES$1.melts, "readonly")).get(melt.quote)));
@@ -35724,16 +36130,12 @@ var CashuWallet = class CashuWallet {
35724
36130
  this.events.onChange();
35725
36131
  }
35726
36132
  } catch {}
35727
- const wait = Date.now() < meltOverdueAt(melt) ? MELT_POLL_MS : Math.min((pace?.wait ?? MELT_POLL_MS) * 2, MELT_SLOW_POLL_MS);
35728
- this.meltAsk.set(melt.quote, {
35729
- at: Date.now() + wait,
35730
- wait
35731
- });
36133
+ this.meltAsk.missed(melt.quote, Date.now(), Date.now() < meltOverdueAt(melt));
35732
36134
  }
35733
36135
  const remaining = new Set((await this.readMelts()).map((m) => m.quote));
35734
- for (const quote of this.meltAsk.keys()) if (!remaining.has(quote)) this.meltAsk.delete(quote);
36136
+ this.meltAsk.keepOnly(remaining);
35735
36137
  if (remaining.size === 0 || this.stopped) return;
35736
- const next = Math.min(...[...remaining].map((quote) => this.meltAsk.get(quote)?.at ?? 0));
36138
+ const next = Math.min(...[...remaining].map((quote) => this.meltAsk.at(quote, 0)));
35737
36139
  if (this.meltTimer) clearTimeout(this.meltTimer);
35738
36140
  this.meltTimer = setTimeout(() => void this.pollMelts(), Math.max(0, next - Date.now()));
35739
36141
  }
@@ -35804,10 +36206,14 @@ var CashuWallet = class CashuWallet {
35804
36206
  STORES$1.walletTx
35805
36207
  ], { [STORES$1.proofs]: change }, (stores) => {
35806
36208
  for (const secret of melt.secrets) stores[STORES$1.proofs].delete(secret);
35807
- for (const p of change) stores[STORES$1.proofs].put(toStored(melt.mint, p));
36209
+ for (const p of change) stores[STORES$1.proofs].put({
36210
+ ...toStored(melt.mint, p),
36211
+ ...melt.restored ? { unchecked: true } : {}
36212
+ });
35808
36213
  stores[STORES$1.melts].delete(melt.quote);
35809
36214
  stores[STORES$1.walletTx].put(tx);
35810
36215
  });
36216
+ if (melt.restored && change.length > 0) this.checkRestored();
35811
36217
  }
35812
36218
  /**
35813
36219
  * The person removes the Cashu wallet of a network (the engine checked what it holds and what it still waits for,
@@ -35920,8 +36326,8 @@ var CashuWallet = class CashuWallet {
35920
36326
  }
35921
36327
  /**
35922
36328
  * `transact`, with the wallet's secrets sealed as they are written when the profile is encrypted (WISP 04): `rows`,
35923
- * the proofs, swaps and melts the work may put, are sealed before the transaction opens, and the work finds a proof
35924
- * by its secret. Without the data key, `transact` itself.
36329
+ * the proofs, swaps, melts and payments the work may put, are sealed before the transaction opens, and the work finds
36330
+ * a proof by its secret. Without the data key, `transact` itself.
35925
36331
  */
35926
36332
  async sealedTransact(names, rows, work) {
35927
36333
  const seals = new RowSeals();
@@ -35989,6 +36395,16 @@ var NoEcashError = class extends Error {
35989
36395
  var arkSats = (network) => network === "bitcoin" ? "sats" : "test sats";
35990
36396
  /** The English line kept with a payment message (the CLI and older apps show it): test sats say so. */
35991
36397
  var satsOn = (network) => network === "testnet" ? "test sats" : "sats";
36398
+ /** The sender's chat line of ecash sent in a chat, from its record: one id, whether written as it goes or on a later start. */
36399
+ var ecashLine = (payment) => ({
36400
+ linkId: payment.linkId,
36401
+ id: `me_${payment.createdAt}`,
36402
+ text: `⚡ ${payment.amount.toLocaleString()} ${satsOn(paymentNetwork(payment))}`,
36403
+ sender: "me",
36404
+ timestamp: payment.createdAt,
36405
+ via: "datalink",
36406
+ paymentId: payment.id
36407
+ });
35992
36408
  var ENDPOINT_OF = {
35993
36409
  arkade: ENDPOINT.arkade,
35994
36410
  bark: ENDPOINT.bark,
@@ -36226,7 +36642,7 @@ var PaymentDesk = class {
36226
36642
  return federation && this.fedimint ? distinct(this.fedimint).find((w) => w.federation(federation)) : void 0;
36227
36643
  }
36228
36644
  async start() {
36229
- const stored = await wrap((await store(STORES$1.payments, "readonly")).getAll());
36645
+ const stored = await openRows(STORES$1.payments, await wrap((await store(STORES$1.payments, "readonly")).getAll()));
36230
36646
  for (const payment of stored) this.payments.set(payment.id, payment);
36231
36647
  for (const payment of stored) if (payment.kind === "request" && payment.direction === "in" && payment.lightningPending) await this.settleInterrupted(payment);
36232
36648
  const claims = await wrap((await store(STORES$1.settings, "readonly")).get(INVOICE_CLAIMS_KEY));
@@ -37824,7 +38240,7 @@ var PaymentDesk = class {
37824
38240
  if (!review.linkId || review.method !== "cashu") throw new Error("Cashu chat recipient missing");
37825
38241
  const link = this.requireLink(review.linkId);
37826
38242
  await link.requirePaymentSupport();
37827
- const existing = await wrap((await store(STORES$1.payments, "readonly")).get(review.id));
38243
+ const existing = await openRow(STORES$1.payments, await wrap((await store(STORES$1.payments, "readonly")).get(review.id)));
37828
38244
  if (!existing || existing.linkId !== review.linkId || existing.requestId !== review.requestId) throw new Error("Cashu outbox does not match the reviewed payment");
37829
38245
  this.payments.set(existing.id, existing);
37830
38246
  this.host.onChange();
@@ -37851,7 +38267,7 @@ var PaymentDesk = class {
37851
38267
  }
37852
38268
  async confirmReviewedCashu(review) {
37853
38269
  if (review.method !== "cashu" || review.state !== "settled") return;
37854
- const payment = this.payments.get(review.id) ?? await wrap((await store(STORES$1.payments, "readonly")).get(review.id));
38270
+ const payment = this.payments.get(review.id) ?? await openRow(STORES$1.payments, await wrap((await store(STORES$1.payments, "readonly")).get(review.id)));
37855
38271
  if (!payment || payment.linkId !== review.linkId || payment.state === "reclaimed") return;
37856
38272
  await this.save({
37857
38273
  ...payment,
@@ -38429,7 +38845,8 @@ var PaymentDesk = class {
38429
38845
  const redeemed = await fedimint.redeemNotes(payment.federation, payment.token, payment.id);
38430
38846
  await this.save({
38431
38847
  ...this.current(payment),
38432
- fedimintOp: redeemed.operationId
38848
+ fedimintOp: redeemed.operationId,
38849
+ ...redeemed.error !== void 0 ? { error: redeemed.error } : {}
38433
38850
  });
38434
38851
  state = redeemed.state;
38435
38852
  }
@@ -38660,26 +39077,16 @@ var PaymentDesk = class {
38660
39077
  requestId: params.requestId,
38661
39078
  network: mintNetwork(mint)
38662
39079
  });
38663
- let token;
38664
- let paidFrom;
39080
+ let sent;
38665
39081
  try {
38666
39082
  const created = await this.wallet.createToken(params.amount, params.mints, memo, record, params.network);
38667
- token = created.token;
38668
- paidFrom = created.mint;
38669
- this.payments.set(id, record(created.token, created.mint));
39083
+ sent = record(created.token, created.mint);
39084
+ this.payments.set(id, sent);
38670
39085
  } catch (error) {
38671
39086
  throw new NoEcashError(error);
38672
39087
  }
38673
39088
  this.host.onChange();
38674
- await this.host.storeMessage({
38675
- linkId: params.linkId,
38676
- id: `me_${params.timestamp}`,
38677
- text: `⚡ ${params.amount.toLocaleString()} ${satsOn(mintNetwork(paidFrom))}`,
38678
- sender: "me",
38679
- timestamp: params.timestamp,
38680
- via: "datalink",
38681
- paymentId: id
38682
- });
39089
+ await this.host.storeMessage(ecashLine(sent));
38683
39090
  try {
38684
39091
  await this.sendTo(link, {
38685
39092
  id,
@@ -38690,7 +39097,7 @@ var PaymentDesk = class {
38690
39097
  asset: UNIT
38691
39098
  },
38692
39099
  memo,
38693
- endpoint: [ENDPOINT.cashu, token]
39100
+ endpoint: [ENDPOINT.cashu, sent.token]
38694
39101
  });
38695
39102
  } catch (error) {
38696
39103
  await this.reclaim(id).catch(() => {});
@@ -38759,13 +39166,20 @@ var PaymentDesk = class {
38759
39166
  if (group) for (const request of this.payments.values()) {
38760
39167
  if (request.group !== group || request.kind !== "request" || request.direction !== "out") continue;
38761
39168
  if (request.state === "pending") await this.sendGroupRequest(linkId, request);
38762
- else if (request.state === "settled") link.sendPaymentResult({
39169
+ else if (request.state === "settled" && Date.now() - request.createdAt < 6048e5) link.sendPaymentResult({
38763
39170
  id: request.id,
38764
39171
  ok: true
38765
39172
  });
38766
39173
  }
38767
39174
  for (const payment of this.payments.values()) {
38768
39175
  if (payment.linkId !== linkId || payment.direction !== "out" || this.reclaims.has(payment.id)) continue;
39176
+ if (payment.kind === "request" && payment.state === "settled" && !payment.group && Date.now() - payment.createdAt < 6048e5) {
39177
+ link.sendPaymentResult({
39178
+ id: payment.id,
39179
+ ok: true
39180
+ });
39181
+ continue;
39182
+ }
38769
39183
  if (payment.target?.method === "usdt") {
38770
39184
  if (!link.supportsUsdtPayments) continue;
38771
39185
  if (payment.kind === "request" && payment.state === "pending" && payment.target.expiresAt > Date.now()) await link.sendPaymentRequest({
@@ -38907,26 +39321,21 @@ var PaymentDesk = class {
38907
39321
  });
38908
39322
  continue;
38909
39323
  }
38910
- if (payment.kind === "request" && payment.state === "settled" && payment.invoice && !payment.group && Date.now() - payment.createdAt < 6048e5) {
38911
- link.sendPaymentResult({
39324
+ if (payment.state !== "pending") continue;
39325
+ if (payment.kind === "payment" && payment.token) {
39326
+ await this.host.storeMessage(ecashLine(payment));
39327
+ await this.sendTo(link, {
38912
39328
  id: payment.id,
38913
- ok: true
39329
+ timestamp: payment.createdAt,
39330
+ requestId: payment.requestId,
39331
+ amount: {
39332
+ value: String(payment.amount),
39333
+ asset: UNIT
39334
+ },
39335
+ memo: payment.memo,
39336
+ endpoint: [ENDPOINT.cashu, payment.token]
38914
39337
  });
38915
- continue;
38916
- }
38917
- if (payment.state !== "pending") continue;
38918
- if (payment.kind === "payment" && payment.token) await this.sendTo(link, {
38919
- id: payment.id,
38920
- timestamp: payment.createdAt,
38921
- requestId: payment.requestId,
38922
- amount: {
38923
- value: String(payment.amount),
38924
- asset: UNIT
38925
- },
38926
- memo: payment.memo,
38927
- endpoint: [ENDPOINT.cashu, payment.token]
38928
- });
38929
- else if (payment.kind === "request" && (payment.invoice || payment.mints?.length)) await link.sendPaymentRequest({
39338
+ } else if (payment.kind === "request" && (payment.invoice || payment.mints?.length)) await link.sendPaymentRequest({
38930
39339
  id: payment.id,
38931
39340
  timestamp: payment.createdAt,
38932
39341
  amount: {
@@ -38966,7 +39375,8 @@ var PaymentDesk = class {
38966
39375
  }
38967
39376
  async save(payment) {
38968
39377
  this.payments.set(payment.id, payment);
38969
- await committed((await store(STORES$1.payments, "readwrite")).put(payment));
39378
+ const row = await sealRow(STORES$1.payments, payment);
39379
+ await committed((await store(STORES$1.payments, "readwrite")).put(row));
38970
39380
  this.host.onChange();
38971
39381
  }
38972
39382
  /**
@@ -39386,6 +39796,10 @@ var CARD_RESTORE_EVERY_MS = 3e4;
39386
39796
  var RTT_SAVE_MS = 3e5;
39387
39797
  /** A reaction said on the live session and not confirmed is said again after this long. */
39388
39798
  var REACTION_RESEND_MS = 3e4;
39799
+ /** How long a deleted chat's session stays up once the ends of its moving files are said, so they get there (as a yield's goodbye). */
39800
+ var FILES_END_MS = 300;
39801
+ /** A chat's reactions shown on the chat list before the one shown now, kept to show again when that one is taken back. */
39802
+ var REACTION_NOTES_KEPT = 8;
39389
39803
  /** When the contact's newest message over the DHT in these was sent (`LiveLink.pkarrSeenAt`). */
39390
39804
  var pkarrSeenAt = (messages) => messages.reduce((max, m) => m.sender === "peer" && m.via === "pkarr" ? Math.max(max, m.sentAt ?? m.timestamp) : max, 0);
39391
39805
  /** A file or a payment request of mine that waits for the chat to be live (a text that waits is its outbox's). */
@@ -40206,7 +40620,7 @@ var GhostlyNode = class GhostlyNode {
40206
40620
  const stored = await fileStore.get(fileId);
40207
40621
  if (!stored?.metadata) return null;
40208
40622
  return {
40209
- bytes: await readStored$1(stored, 0, storedSize(stored)),
40623
+ bytes: await readStored$2(stored, 0, storedSize(stored)),
40210
40624
  name: stored.metadata.name,
40211
40625
  size: stored.metadata.size,
40212
40626
  mime: stored.metadata.mime,
@@ -40530,7 +40944,7 @@ var GhostlyNode = class GhostlyNode {
40530
40944
  settings: () => this.settings.nostr,
40531
40945
  online: () => this.networkOn,
40532
40946
  emit: () => this.emitState(),
40533
- ownSubjects: () => this.identities.views().filter((p) => p.provider === "nostr").map((p) => p.subject),
40947
+ ownSubjects: () => this.identities.subjects("nostr"),
40534
40948
  contactSubjects: (linkId) => {
40535
40949
  const live = this.links.get(linkId), stored = live?.stored;
40536
40950
  if (!stored?.profile || !stored.identities) return [];
@@ -40631,6 +41045,13 @@ var GhostlyNode = class GhostlyNode {
40631
41045
  reactionNotes = /* @__PURE__ */ new Map();
40632
41046
  /** Each chat's notes shown before the one shown now, oldest first, the latest `REACTION_NOTES_KEPT` of this run. */
40633
41047
  reactionNotesBefore = /* @__PURE__ */ new Map();
41048
+ /**
41049
+ * Chats whose history had no reaction standing when last read whole, none of this run's notes having left
41050
+ * `reactionNotesBefore` since: every reaction that stands there is among those notes, so the history has nothing older
41051
+ * to say. A contact flipping the chat's only reaction on and off read it whole at each take-back, 90 ms at 20,000
41052
+ * messages on the CLI's store, up to 15 times per 10 s that the reaction window takes.
41053
+ */
41054
+ reactionNotesWhole = /* @__PURE__ */ new Set();
40634
41055
  reactionsSent = /* @__PURE__ */ new Map();
40635
41056
  reactionPace = /* @__PURE__ */ new Map();
40636
41057
  reactionTimers = /* @__PURE__ */ new Map();
@@ -40660,7 +41081,11 @@ var GhostlyNode = class GhostlyNode {
40660
41081
  pinsHost = {
40661
41082
  messages: (chat) => db.getMessages(chat),
40662
41083
  message: (chat, id) => db.getMessage(chat, id),
40663
- rows: (chat, id) => this.rowsNamed(chat, id)
41084
+ rows: (chat, id) => this.rowsNamed(chat, id),
41085
+ unkeyed: (chat) => {
41086
+ const live = this.links.get(chat);
41087
+ return live && !live.stored.group ? this.unkeyedRowsOf(live) : void 0;
41088
+ }
40664
41089
  };
40665
41090
  reactions = new Reactions({
40666
41091
  messages: (chat) => db.getMessages(chat),
@@ -40670,7 +41095,11 @@ var GhostlyNode = class GhostlyNode {
40670
41095
  changed: async (chat, id, note) => {
40671
41096
  const shown = this.reactionNotes.get(chat);
40672
41097
  if (note) {
40673
- if (shown && (shown.message !== note.message || shown.by !== note.by)) this.reactionNotesBefore.set(chat, [...this.reactionNotesBefore.get(chat) ?? [], shown].slice(-8));
41098
+ if (shown && (shown.message !== note.message || shown.by !== note.by)) {
41099
+ const before = [...this.reactionNotesBefore.get(chat) ?? [], shown];
41100
+ if (before.length > REACTION_NOTES_KEPT) this.reactionNotesWhole.delete(chat);
41101
+ this.reactionNotesBefore.set(chat, before.slice(-8));
41102
+ }
40674
41103
  this.reactionNotes.set(chat, note);
40675
41104
  } else if (shown?.message === id) {
40676
41105
  const before = await this.reactionNoteNow(chat, shown);
@@ -40696,7 +41125,8 @@ var GhostlyNode = class GhostlyNode {
40696
41125
  });
40697
41126
  /**
40698
41127
  * The chat list's reaction once one to its message was taken back: the same one if it still stands, else the latest
40699
- * shown before it that does, each read from its own row. Only past those is the whole history read for an older one.
41128
+ * shown before it that does, each read from its own row. Only past those is the whole history read for an older one,
41129
+ * and not when it had none (`reactionNotesWhole`).
40700
41130
  */
40701
41131
  async reactionNoteNow(chat, shown) {
40702
41132
  const before = this.reactionNotesBefore.get(chat) ?? [];
@@ -40705,7 +41135,15 @@ var GhostlyNode = class GhostlyNode {
40705
41135
  const standing = row && noteIfStanding(note, row);
40706
41136
  if (standing) return standing;
40707
41137
  }
40708
- return latestReaction(await db.getMessages(chat));
41138
+ if (this.reactionNotesWhole.has(chat)) return void 0;
41139
+ return this.noteFromHistory(chat, await db.getMessages(chat));
41140
+ }
41141
+ /** The chat's latest reaction in its whole history, read now; none there marks the chat `reactionNotesWhole`. */
41142
+ noteFromHistory(chat, history) {
41143
+ const note = latestReaction(history);
41144
+ if (note) this.reactionNotesWhole.delete(chat);
41145
+ else this.reactionNotesWhole.add(chat);
41146
+ return note;
40709
41147
  }
40710
41148
  /** Private groups (WISP 900): sessions, admission on contact chats, and the pairwise edges that carry them. */
40711
41149
  groups = new Groups({
@@ -40721,7 +41159,7 @@ var GhostlyNode = class GhostlyNode {
40721
41159
  linkWaiting: (linkId) => this.links.get(linkId)?.link?.framesWaiting() ?? 0,
40722
41160
  linkOpen: (linkId) => !!this.links.get(linkId)?.link?.isDataLinkOpen,
40723
41161
  loaded: (groupId, history) => {
40724
- const note = latestReaction(history);
41162
+ const note = this.noteFromHistory(`group:${groupId}`, history);
40725
41163
  if (note) this.reactionNotes.set(`group:${groupId}`, note);
40726
41164
  },
40727
41165
  myNick: () => this.sharedNick,
@@ -40871,6 +41309,10 @@ var GhostlyNode = class GhostlyNode {
40871
41309
  await this.groups.setRemovals(groupId, withRemoval(this.groups.removals(groupId), removal));
40872
41310
  await this.forgetGroupMessage(chat, message.id, message);
40873
41311
  },
41312
+ unmentioned: async (chat, row) => {
41313
+ await this.groups.unmark(chat.slice(6), row, true);
41314
+ this.emitState();
41315
+ },
40874
41316
  edge: (groupId, member) => {
40875
41317
  const link = this.links.get(this.memberEdges(groupId).get(member) ?? "")?.link;
40876
41318
  return link?.supportsGroupVersion(1) ? link : void 0;
@@ -41311,7 +41753,7 @@ var GhostlyNode = class GhostlyNode {
41311
41753
  this.links.get(stored.id).cardsDue = Promise.resolve(new Set(messages.filter(cardDue).map((m) => m.id)));
41312
41754
  this.links.get(stored.id).pkarrSeenAt = pkarrSeenAt(messages);
41313
41755
  for (const message of messages.slice(-20)) this.clockSample(message);
41314
- const note = latestReaction(messages);
41756
+ const note = this.noteFromHistory(stored.id, messages);
41315
41757
  if (note) this.reactionNotes.set(stored.id, note);
41316
41758
  if (stored.reactionsWaiting?.length) await this.reactions.restore(stored.id, stored.reactionsWaiting, messages);
41317
41759
  if (stored.profile) await this.outboxFor(stored.id).recover(messages);
@@ -42722,6 +43164,7 @@ var GhostlyNode = class GhostlyNode {
42722
43164
  this.placedAt.delete(linkId);
42723
43165
  this.reactionNotes.delete(linkId);
42724
43166
  this.reactionNotesBefore.delete(linkId);
43167
+ this.reactionNotesWhole.delete(linkId);
42725
43168
  this.events.onMessages(linkId, []);
42726
43169
  }
42727
43170
  async setGroupWakeMuted(groupId, muted) {
@@ -42876,13 +43319,14 @@ var GhostlyNode = class GhostlyNode {
42876
43319
  this.quoteSweeps.forget(linkId);
42877
43320
  this.editBuffer.forget(linkId);
42878
43321
  live.carried?.stop();
43322
+ const filesEnded = this.fileDesk.drop(linkId);
42879
43323
  this.links.delete(linkId);
42880
- live.link?.stop(true);
43324
+ if (filesEnded) setTimeout(() => void live.link?.stop(true), FILES_END_MS);
43325
+ else live.link?.stop(true);
42881
43326
  live.caps?.stop();
42882
43327
  this.identities.forget(linkId);
42883
43328
  this.nostrSocial.forgetLink(linkId);
42884
43329
  this.hold.forgetLink(linkId);
42885
- this.fileDesk.drop(linkId);
42886
43330
  this.contactAsks.forgetChat(linkId).catch(() => {});
42887
43331
  this.wakeLimiter.reset(linkId);
42888
43332
  this.callWakeLimiter.reset(linkId);
@@ -43394,6 +43838,13 @@ var GhostlyNode = class GhostlyNode {
43394
43838
  };
43395
43839
  const seq = (message.edit?.seq ?? 0) + 1, most = card ? STATUS_CARD_LIMITS.edits : 100;
43396
43840
  if (seq > most) return refuse(`This message was edited ${most} times, the most one takes.`);
43841
+ if (!pairedEditFits({
43842
+ id: "A".repeat(22),
43843
+ e: seq,
43844
+ ts: Date.now(),
43845
+ m: text,
43846
+ ...card && { sc: card }
43847
+ })) return refuse(PAIRED_FRAME_TOO_LARGE);
43397
43848
  const edited = withEdit(message, {
43398
43849
  seq,
43399
43850
  at: Date.now(),
@@ -44034,7 +44485,8 @@ var GhostlyNode = class GhostlyNode {
44034
44485
  /**
44035
44486
  * Deletes a message of mine for everyone (WISP 400 § Delete for everyone): it goes from this device at once, as a delete
44036
44487
  * here does, and its removal goes to the contact as the message's last edit, said again until confirmed, live only.
44037
- * One that never left is only deleted. Never a payment, a request or a notice. A group's goes through `GroupEdits`.
44488
+ * One that never left is only deleted. Never a payment, a request or a notice. A group's goes through `GroupEdits`;
44489
+ * its `e` is the removal's edit number, for `groupTaken`.
44038
44490
  */
44039
44491
  async removeMessage({ linkId, messageId }) {
44040
44492
  const refuse = (error) => ({
@@ -48526,6 +48978,14 @@ var GhostlyNode = class GhostlyNode {
48526
48978
  await pause();
48527
48979
  }
48528
48980
  }
48981
+ /**
48982
+ * Starts a chat this run left unstarted (`NodeOptions.deferChats`): the one a one-shot names, once the command has
48983
+ * found it. Any other chat, or one already started, is left as it is.
48984
+ */
48985
+ startDeferredChat(linkId) {
48986
+ if (!this.deferredChats.delete(linkId)) return;
48987
+ if (this.networkOn && !this.shuttingDown) this.startLink(linkId);
48988
+ }
48529
48989
  startLink(linkId) {
48530
48990
  const live = this.links.get(linkId);
48531
48991
  if (!live || live.link || this.deferredChats.has(linkId)) return;
@@ -48655,6 +49115,7 @@ var GhostlyNode = class GhostlyNode {
48655
49115
  avatar: this.sharedAvatar,
48656
49116
  lastSeenTimestamp,
48657
49117
  pollIntervals: this.pollIntervals,
49118
+ ...this.options.watchPeerIdleMs ? { watchPeerIdleMs: this.options.watchPeerIdleMs } : {},
48658
49119
  autoConnect: true,
48659
49120
  createPeerConnection: () => this.chatPeer(new RTCPeerConnection(this.contactRtcConfig())),
48660
49121
  localFetch: this.localFetch,
@@ -48904,7 +49365,7 @@ var GhostlyNode = class GhostlyNode {
48904
49365
  if (supported) this.flushReactions(linkId);
48905
49366
  },
48906
49367
  onPin: async (pin) => {
48907
- await this.keepLinkPin(linkId, await this.pinCame(linkId, "peer", pin));
49368
+ if (pinIsNewer(this.links.get(linkId)?.stored.pin, pin)) await this.keepLinkPin(linkId, await this.pinCame(linkId, "peer", pin));
48908
49369
  return true;
48909
49370
  },
48910
49371
  onPinReceipt: (n) => this.pinReceipt(linkId, n),
@@ -48931,7 +49392,7 @@ var GhostlyNode = class GhostlyNode {
48931
49392
  onFileRoom: async () => (await fileBytes()).room(),
48932
49393
  onFileProgress: (id, transferred, direction) => this.fileProgress(this.localFileId(linkId, id, direction), transferred),
48933
49394
  onFileComplete: (id, direction) => this.fileSettled(this.localFileId(linkId, id, direction, { failed: false }), void 0, linkId),
48934
- onFilesFrame: (frame) => this.fileDesk.handle(linkId, frame),
49395
+ onFilesFrame: (frame) => this.links.get(linkId) !== live ? Promise.resolve() : this.fileDesk.handle(linkId, frame),
48935
49396
  onFilesSession: (open) => {
48936
49397
  if (this.links.get(linkId) !== live) return;
48937
49398
  this.fileDesk.session(linkId, open);
@@ -49080,7 +49541,7 @@ var GhostlyNode = class GhostlyNode {
49080
49541
  nativeFactoriesFor(relayOnly) {
49081
49542
  const relay = relayOnly || this.relaysHyperdhtNatively ? this.hyperdhtRelay : "";
49082
49543
  return {
49083
- ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-Ce42sR8x.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
49544
+ ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-B_uHjg_r.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
49084
49545
  ...relayOnly ? {} : this.options.nativeTransports,
49085
49546
  ...this.ownIrohRelays && !relayOnly ? { "iroh/1": (seedB64) => this.options.nativeTransports["iroh/1"](seedB64, this.settings.irohRelays?.length ? { relays: [...this.settings.irohRelays] } : {}) } : {},
49086
49547
  ...this.options.irohWeb ? { "iroh/1": (seedB64) => createIrohWebEndpoint(seedB64, { relays: this.irohRelays }) } : {}
@@ -49243,21 +49704,32 @@ var GhostlyNode = class GhostlyNode {
49243
49704
  }
49244
49705
  /**
49245
49706
  * A group's edges that run native transports (`keepsGroupNative`), the one it keeps while it is not on screen first
49246
- * (WISP 902 § Transports): to a hub, then the admin, then one the member keeps itself (`chosenByPeer`), then one that
49247
- * holds a listener already (so the one it keeps does not change hands each time another member is heard), then the
49248
- * member seen last. One passed over lately (`groupAnchorsAnswered`: its member never answered) comes after all of
49707
+ * (WISP 902 § Transports): to a hub, then, in a private group, the one the rule gives this member (`keptMeshPeer`:
49708
+ * spread over the members, not every member's to the admin), or in a community the admin; then one the member keeps
49709
+ * itself (`chosenByPeer`), then, in a private group, one whose member keeps it by the rule, then the admin, then one
49710
+ * that holds a listener already (so the one it keeps does not change hands each time another member is heard), then
49711
+ * the member seen last. One passed over lately (`groupAnchorsAnswered`: its member never answered) comes after all of
49249
49712
  * them. The mesh's catch-up brings the group's messages through any member.
49250
49713
  */
49251
49714
  groupEdgesByRank(groupId, view) {
49252
49715
  const native = Object.keys(this.nativeFactories), now = Date.now();
49716
+ const mesh = this.groups.meshOrder(groupId);
49717
+ const kept = mesh && keptMeshPeer(mesh.order, mesh.admin, mesh.me), keeping = new Set(mesh ? meshPeersKeeping(mesh.order, mesh.admin, mesh.me) : []);
49253
49718
  const lead = new Map(view?.members.filter((member) => !member.me && (member.hub || member.role === "admin")).map((member) => [member.key, member.hub ? 2 : 1]));
49254
- const rank = (live) => [
49255
- Number(!this.anchorPassed(live, now)),
49256
- lead.get(live.stored.groupPeer) ?? 0,
49257
- Number(this.chosenByPeer(live)),
49258
- Number(native.some((t) => live.link.availableTransports.includes(t))),
49259
- live.link.groupsSupport ? now : Math.max(presenceSeenAt(live.presence), live.lastSyncAt)
49260
- ];
49719
+ const leads = (peer) => mesh && lead.get(peer) === 1 ? 0 : lead.get(peer) ?? 0;
49720
+ const rank = (live) => {
49721
+ const peer = live.stored.groupPeer;
49722
+ return [
49723
+ Number(!this.anchorPassed(live, now)),
49724
+ leads(peer),
49725
+ Number(peer === kept),
49726
+ Number(this.chosenByPeer(live)),
49727
+ Number(keeping.has(peer)),
49728
+ Number(!!mesh && lead.get(peer) === 1),
49729
+ Number(native.some((t) => live.link.availableTransports.includes(t))),
49730
+ live.link.groupsSupport ? now : Math.max(presenceSeenAt(live.presence), live.lastSyncAt)
49731
+ ];
49732
+ };
49261
49733
  const edges = [...this.links.values()].filter((live) => live.stored.group === groupId && !live.stored.groupEntry && live.link && this.keepsGroupNative(live.stored));
49262
49734
  const ranks = new Map(edges.map((live) => [live, rank(live)]));
49263
49735
  return edges.sort((a, b) => {
@@ -49305,7 +49777,7 @@ var GhostlyNode = class GhostlyNode {
49305
49777
  * Every few seconds, each group not on screen whose edges run native transports: the one edge it keeps has a
49306
49778
  * listener (or waits for one, `groupNativeWaiting`), and when its member has not answered it in
49307
49779
  * `GROUP_ANCHOR_ANSWER_MS` (it is there with no listener for it: all its own taken), the group keeps the next
49308
- * one instead (hub, then admin, then the member heard from last), whose member answers the edge it keeps
49780
+ * one instead (in `groupEdgesByRank`'s order), whose member answers the edge it keeps
49309
49781
  * (`chosenByPeer`). Not while any edge of the group is live: the group is reachable through it. Every other one passed
49310
49782
  * over lately too: the one it keeps stays, without its listener going back and forth.
49311
49783
  */
@@ -49491,7 +49963,8 @@ var GhostlyNode = class GhostlyNode {
49491
49963
  if (group) return "no-slot";
49492
49964
  throw new Error("All native connection slots are in use. This chat takes one once a chat live over one has been quiet for 2 minutes. Disconnect a native connection in another chat to free one now.");
49493
49965
  }
49494
- if (group && (entry || extra(live)) && (full || groups >= this.groupNativeSlots(key) || !entry && !anchorOf(live.stored.group)?.link?.availableTransports.includes(key))) return "no-slot";
49966
+ if (group && extra(live) && (full || groups >= this.groupNativeSlots(key) || !anchorOf(live.stored.group)?.link?.availableTransports.includes(key))) return "no-slot";
49967
+ if (entry && full && !owners.some((other) => extra(other) && other.link?.canReleaseEndpoint(key))) return "no-slot";
49495
49968
  if (full || !group && owners.length - groups >= this.chatNativeSlots(key)) {
49496
49969
  const paired = !group && live.pairedAt !== void 0 && now - live.pairedAt < 6e5 ? live.pairedAt : void 0;
49497
49970
  const taking = group || this.activeLinkId === linkId || inUse || paired !== void 0;
@@ -50446,4 +50919,4 @@ function signalKind(signal) {
50446
50919
  //#endregion
50447
50920
  export { EngineServer };
50448
50921
 
50449
- //# sourceMappingURL=server-BZnsm5X5.js.map
50922
+ //# sourceMappingURL=server-DcOsgYDU.js.map