@ghostlytools/cli 1.6.1 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +36 -12
  2. package/dist/assets/{api-BpNU2LQh.js → api-CD9JbPuA.js} +99 -28
  3. package/dist/assets/api-CD9JbPuA.js.map +1 -0
  4. package/dist/assets/{api-Cx8ZCntM.js → api-CJM3R93b.js} +2 -2
  5. package/dist/assets/{apiKit-d1wi3raD.js → apiKit-BmnROpCN.js} +8 -4
  6. package/dist/assets/{apiKit-d1wi3raD.js.map → apiKit-BmnROpCN.js.map} +1 -1
  7. package/dist/assets/{apps-C-HiIRCA.js → apps-CJ2dvKSz.js} +1 -1
  8. package/dist/assets/{apps-B1QjRWqq.js → apps-DVA60Tg6.js} +34 -11
  9. package/dist/assets/apps-DVA60Tg6.js.map +1 -0
  10. package/dist/assets/{arkade-B5g4r3Ea.js → arkade-CHqwEHFd.js} +2 -2
  11. package/dist/assets/{arkade-B5g4r3Ea.js.map → arkade-CHqwEHFd.js.map} +1 -1
  12. package/dist/assets/{backup-Boqn5Y35.js → backup-B4dSNvzb.js} +5 -5
  13. package/dist/assets/{backup-Boqn5Y35.js.map → backup-B4dSNvzb.js.map} +1 -1
  14. package/dist/assets/{backup-BS9HwGyn.js → backup-C4CbTEcj.js} +1 -1
  15. package/dist/assets/{blobFiles-B6nf0gCG.js → blobFiles-Bckz9fjp.js} +2 -2
  16. package/dist/assets/{blobFiles-B6nf0gCG.js.map → blobFiles-Bckz9fjp.js.map} +1 -1
  17. package/dist/assets/buttons-BMVGYXpR.js +2 -0
  18. package/dist/assets/{buttons-Bjc51aod.js → buttons-C13rK2mH.js} +3 -3
  19. package/dist/assets/{buttons-Bjc51aod.js.map → buttons-C13rK2mH.js.map} +1 -1
  20. package/dist/assets/{daemonProof-ui8jtIw0.js → daemonProof-B41oSfon.js} +2 -2
  21. package/dist/assets/{daemonProof-ui8jtIw0.js.map → daemonProof-B41oSfon.js.map} +1 -1
  22. package/dist/assets/{envelope-DvZMFRzg.js → envelope-4TXDx3vD.js} +2 -2
  23. package/dist/assets/{envelope-DvZMFRzg.js.map → envelope-4TXDx3vD.js.map} +1 -1
  24. package/dist/assets/{fileBytes-BMEBas7S.js → fileBytes-BD0v3rRG.js} +10 -2
  25. package/dist/assets/{fileBytes-BMEBas7S.js.map → fileBytes-BD0v3rRG.js.map} +1 -1
  26. package/dist/assets/{fileBytes-CtwagJ8h.js → fileBytes-OolN5cSY.js} +1 -1
  27. package/dist/assets/{fileBytes-CFNrRfcl.js → fileBytes-_fd-2JRY.js} +2 -2
  28. package/dist/assets/{fileBytes-CFNrRfcl.js.map → fileBytes-_fd-2JRY.js.map} +1 -1
  29. package/dist/assets/fileBytesIdb-CsSQcSxD.js +2 -0
  30. package/dist/assets/{fileBytesIdb-BXAN7i-N.js → fileBytesIdb-NtA8r9EM.js} +2 -2
  31. package/dist/assets/{fileBytesIdb-BXAN7i-N.js.map → fileBytesIdb-NtA8r9EM.js.map} +1 -1
  32. package/dist/assets/{fileBytesOpfs-Do1Vpkis.js → fileBytesOpfs-B8fJwkwM.js} +3 -3
  33. package/dist/assets/{fileBytesOpfs-Do1Vpkis.js.map → fileBytesOpfs-B8fJwkwM.js.map} +1 -1
  34. package/dist/assets/{ghostly_iroh_web-BXCsSxxo.js → ghostly_iroh_web-CO0onry8.js} +33 -27
  35. package/dist/assets/ghostly_iroh_web-CO0onry8.js.map +1 -0
  36. package/dist/assets/ghostly_iroh_web_bg.wasm +0 -0
  37. package/dist/assets/{groupFiles-y4lGrOC-.js → groupFiles-ajZgZ6P8.js} +41 -25
  38. package/dist/assets/groupFiles-ajZgZ6P8.js.map +1 -0
  39. package/dist/assets/{host-DFGS8vJE.js → host-CVeNtA2_.js} +43 -20
  40. package/dist/assets/host-CVeNtA2_.js.map +1 -0
  41. package/dist/assets/{hyperdhtRelay-CZLnOc4e.js → hyperdhtRelay-CI2ISE-g.js} +2 -2
  42. package/dist/assets/{hyperdhtRelay-CZLnOc4e.js.map → hyperdhtRelay-CI2ISE-g.js.map} +1 -1
  43. package/dist/assets/{irohWeb-Y9wt8zG7.js → irohWeb-DcRJdhce.js} +3 -3
  44. package/dist/assets/{irohWeb-Y9wt8zG7.js.map → irohWeb-DcRJdhce.js.map} +1 -1
  45. package/dist/assets/{main-xgWC0qPZ.js → main-CjO0KGiF.js} +272 -79
  46. package/dist/assets/main-CjO0KGiF.js.map +1 -0
  47. package/dist/assets/{mainline-CjQ3pmvq.js → mainline-WM-WItCV.js} +27 -8
  48. package/dist/assets/mainline-WM-WItCV.js.map +1 -0
  49. package/dist/assets/{networkReason-i9wu5ZJs.js → networkReason-380j5yMs.js} +2 -2
  50. package/dist/assets/{networkReason-i9wu5ZJs.js.map → networkReason-380j5yMs.js.map} +1 -1
  51. package/dist/assets/{nwc-yO0nHt9S.js → nwc-D5dkC1xg.js} +3 -3
  52. package/dist/assets/{nwc-yO0nHt9S.js.map → nwc-D5dkC1xg.js.map} +1 -1
  53. package/dist/assets/{nwcProvider-BEg4I5Bk.js → nwcProvider-p_rMwtDv.js} +2 -2
  54. package/dist/assets/{nwcProvider-BEg4I5Bk.js.map → nwcProvider-p_rMwtDv.js.map} +1 -1
  55. package/dist/assets/{profiles-CEnZfN78.js → profiles-BFd0tpCZ.js} +91 -19
  56. package/dist/assets/profiles-BFd0tpCZ.js.map +1 -0
  57. package/dist/assets/{registry-CBDcdRPx.js → registry-BKffx4ZU.js} +1 -1
  58. package/dist/assets/{registry-DyGu5C-Z.js → registry-BfNcA6kF.js} +3 -3
  59. package/dist/assets/registry-BfNcA6kF.js.map +1 -0
  60. package/dist/assets/{resolve-CnkY--2E.js → resolve-hUsgRkmm.js} +2 -2
  61. package/dist/assets/{resolve-CnkY--2E.js.map → resolve-hUsgRkmm.js.map} +1 -1
  62. package/dist/assets/{server-CH142eWc.js → server-C3tJZFnv.js} +422 -149
  63. package/dist/assets/server-C3tJZFnv.js.map +1 -0
  64. package/dist/assets/{src-BXeGLwWV.js → src-BMHgbkli.js} +246 -62
  65. package/dist/assets/src-BMHgbkli.js.map +1 -0
  66. package/dist/assets/translate-DJUutSis.js +1067 -0
  67. package/dist/assets/translate-DJUutSis.js.map +1 -0
  68. package/dist/assets/types-C4_KafL_.js.map +1 -1
  69. package/dist/assets/{usdt-CdSNFUzO.js → usdt-glkUxsDe.js} +3 -3
  70. package/dist/assets/{usdt-CdSNFUzO.js.map → usdt-glkUxsDe.js.map} +1 -1
  71. package/dist/assets/{words-DA5feEav.js → words-DyW9b27T.js} +2 -2
  72. package/dist/assets/{words-DA5feEav.js.map → words-DyW9b27T.js.map} +1 -1
  73. package/dist/ghostly.mjs +1 -1
  74. package/package.json +1 -1
  75. package/dist/assets/api-BpNU2LQh.js.map +0 -1
  76. package/dist/assets/apps-B1QjRWqq.js.map +0 -1
  77. package/dist/assets/buttons-CugVarw3.js +0 -2
  78. package/dist/assets/fileBytesIdb-C20oXDdr.js +0 -2
  79. package/dist/assets/ghostly_iroh_web-BXCsSxxo.js.map +0 -1
  80. package/dist/assets/groupFiles-y4lGrOC-.js.map +0 -1
  81. package/dist/assets/host-DFGS8vJE.js.map +0 -1
  82. package/dist/assets/main-xgWC0qPZ.js.map +0 -1
  83. package/dist/assets/mainline-CjQ3pmvq.js.map +0 -1
  84. package/dist/assets/profiles-CEnZfN78.js.map +0 -1
  85. package/dist/assets/registry-DyGu5C-Z.js.map +0 -1
  86. package/dist/assets/server-CH142eWc.js.map +0 -1
  87. package/dist/assets/src-BXeGLwWV.js.map +0 -1
@@ -1,16 +1,16 @@
1
1
  import { n as traceJoin } from "./joinTrace-CjRDFy85.js";
2
- import { $c as createContactLink, $i as automaticTransport, $l as PacketTooLargeError, $o as HANDOFF_OFFER, $r as vapidKeysMatch, $s as readEnrollHello, A as knockRecords, Aa as GROUP_REACTION_FRAME, Al as firstDeviceSetSecret, An as findEndpoint, Ao as webLocalFetch, As as readHandoffPake, B as GROUP_READ_NOTE, Ba as pairedReplyAuthor, Bi as IdentityExchange, Bl as DEFAULT_RELAYS, Bn as EngineError, Bo as contactRtcConfig, Br as mayPin, Bs as verifySetUpdate, C as decodeCommunityLink, Ca as REMOVED_TEXT, Cc as APP_BUNDLE_LIMITS, Cr as rankHubs, Cs as handoffVersions, D as encodeGroupEntryLink, Da as forwardedAgain, Dc as appDigest, Dl as turnPutSummary, Dn as ENDPOINT, Do as GhostlyHttpError, Dr as shouldBeHub, Ds as readHandoffDone, E as decodeGroupEntryLink, Ea as parseLinkPreview, El as classifyTurnRead, En as decodeBolt11, Eo as presenceSeenAt, Er as readLobby, Es as readHandoffCancel, F as groupWakeFrame, Fa as reactionEmoji, Fc as sha256Paced, Fi as dialDescriptors, Fl as turnInstance, Fn as INVITE_TAKEN, Fo as RTC_CONFIG, Fr as TypingSender, G as GROUP_EDIT_TEXT_BYTES, Gi as newIdentityBinding, Go as HTTP_SERVICE_PROTO, Gr as WAKE_CALL_INTERVAL_MS, Gs as enrollCancelFrame, Gt as encodeDidDhtPacket, H as frameBytes, Ha as replySnippet, Hc as isAppKey, Hi as emptyIdentityLedger, Hn as engineText, Ho as parseCallSignal, Hr as pinIsNewer, Ht as didDhtDocument, I as groupWakes, Ia as reactionIsNewer, Il as turnKeys, In as LIVENESS_PING_MS, Is as readSetUpdate, J as mentionsMember, Jc as parseImageMeta, Ji as lastSharedWithMe, Jo as HANDOFF_ACK, Jr as newWakeToken, Js as enrollDoneFrame, Jt as ETHEREUM_USDT, K as carryMentions, Ki as receivedIdentityStatus, Kl as currentRelays, Ko as LEGACY_SERVICES, Kr as WakeLimiter, Ks as enrollCancelReason, L as parseGroupWakeFrame, La as readReaction, Lc as APP_STATEMENT_LIMITS, Ll as turnName, Ln as PAIRED_FRAME_TOO_LARGE, Lr as typingActivity, Ls as setAckFrame, M as readKnocks, Ma as ReactionWindow, Mc as pacer, Mi as CapsExchange, Ml as readTurnPacket, Mn as parseCashuRequestPayload, Mo as decodeControl, Mr as transferStalled, Ms as readHandoffVerified, Na as nextReactionNumber, Ni as DHT_TEXT_CAPABILITY, Nl as signTurnPacket, Nn as parseFedimintRequestPayload, No as encodeControl, Ns as sealHandoffPiece, O as entryParams, Oa as readForwarded, Oc as appViewOf, Ol as TURN_LAST_SEQUENCE, On as cashuRequestPayload, Oo as formatLocalTarget, Or as ChatFiles, Os as readHandoffHave, P as GroupWakeLimiter, Pa as queueReaction, Pc as readAppBundleAsync, Pi as capsDescriptors, Pl as signTurnRelease, Pn as GhostLink, Qc as readCanonicalJson, Qi as TRANSPORTS, Ql as withRequestOptions, Qo as HANDOFF_HELLO, Qr as checkPushEndpoint, Qs as readEnrollGrant, Qt as SEPOLIA_TEST_USDT, R as GROUP_LIMITS, Ra as validReactionNumber, Rc as appFingerprint, Ri as IDENTITY_REVOCATION_LABEL, Rl as turnStatedVerifier, Rn as pairedMessageFits, Rs as setUpdateFrame, S as communityHasFrame, Sa as MAX_REMOVAL_NUMBER, Sc as seenEntry, Sl as webCryptoSigner, So as DHT_POLL_INTERVALS, Sr as pickHubs, Ss as handoffStreamKey, Ta as dhtEditId, Tc as APP_ICON_PATH, Tl as TURN_SETTLE_MS, To as WATCH_PEER_MS, Tr as readBeaconHead, Ts as readHandoffAck, Ua as BUTTON_ID, Uc as isAppRef, Ui as identityRevocationValue, Ul as RelayTransport, Un as parseEngineError, Ur as pinNumberHolds, Ut as didDhtFromPublicKey, V as GroupSession, Va as readReply, Vc as isAppHash, Vn as engineError, Vr as nextPinNumber, Wc as readAppRevocation, Wi as identityStatement, Wn as GROUP_FILE_LIMITS, Wo as emptyLinkRecords, Wr as readPin, Wt as encodeDidDhtDeactivated, Xa as STATUS_CARD_LIMITS, Xc as canonicalJson, Xi as emptyProofLedger, Xl as budgetRetryMs, Xo as HANDOFF_DONE, Xr as relayRequest, Xs as enrollHelloFrame, Xt as ONCHAIN_PROVIDER, Y as groupName, Yi as PeerProofs, Yl as traceLink, Yn as groupFileFallback, Yo as HANDOFF_CANCEL, Yr as parseWakeFrame, Ys as enrollGrantFrame, Yt as EVM_TEST_CHAINS, Zi as validExternalKey, Zl as isDiscoveryBudgetError, Zn as readGroupFileMeta, Zo as HANDOFF_HAVE, Zr as wakeRequest, Zs as enrollProofFrame, Zt as PaymentPreflightError, _ as openGroupTyping, _c as mergeContactKnocks, _i as readManifest, _l as deviceKeyZ32, _o as rosterHas, _r as lobbyKeys, _s as handoffManifestFrames, _u as toBase64Url, a as appStoreDecision, aa as DHT_FILE_CAPABILITY, ac as planKnocks, ai as APPS_CAPABILITY, al as OwnInviteError, an as assertWholeSats, ao as arrivalKey, as as filePartName, au as createIdentity, b as CommunitySession, ba as EDIT_BUFFER_MS, bc as readLinkRecord, bl as newDeviceSetSecret, bo as DirectPathWatch, br as mergeLobby, bs as handoffReleaseFrame, bu as utf8Encode, c as planAppUpdate, ca as sanitizeFileName, cc as turnOff, ci as STATUS_CARD_CAPABILITY, cl as encodeInviteCode, cn as walletNetworkOf, co as receivedTimestamp, cr as MESH_HUBS, cs as handoffAttemptSucceeded, cu as publicKeyFromZ32, dc as contactDay, di as HOLD_DATED_BACK_MS, dn as sparkAddressKind, do as GROUP_MEMBER_CAP, dr as pickMeshHubs, ds as handoffContext, du as sanitizeAvatar, ec as verifyEnrollProof, ei as APP_RANGE_LIMITS, el as encodeContactLink, en as TEST_USDT_FAUCET_AMOUNT, es as HANDOFF_PAKE, f as readAppStoreSteps, fc as knockSlotIdentity, fi as HOLD_LIMITS, fl as DEVICES_CAPABILITY, fn as sparkInvoiceDetails, fr as COMMUNITY_TOPOLOGY, fs as handoffContextProof, fu as sanitizeDisplayText, g as groupTypingEpoch, ga as parseVoiceMeta, gc as makeStampPaced, gi as newMailbox, gl as deviceEchoNonce, go as rosterAdmin, gr as freshHubs, gs as handoffHelloFrame, gt as normalizeAtprotoHandle, gu as randomBytes, h as GroupTypingBoard, ha as fileMessageText, hc as linkRecords, hi as isHoldUrl, hl as deviceEchoFrame, hn as isPubkyKey, ho as parseGroupCommit, hr as doorHubs, hs as handoffEphemeral, ht as isAtprotoDid, i as appRevocationFor, ia as peekDhtMailbox, ic as newInbox, ii as isAppVersion, il as readDeviceInvite, in as assertTokenUnits, io as statusCardText, is as HANDOFF_VERIFIED, j as mergeKnocks, ja as REACTION_LIMITS, jc as isAppUrl, jl as nextTurnPosition, jn as isFederationId, jo as LIMITS, jr as transferEnded, js as readHandoffTurnFrame, k as knockIdentity, ka as COMMUNITY_REACTION_FRAME, kl as TURN_MAX, kn as fedimintRequestPayload, ko as parseLocalTarget, kr as FILE_LIMITS, ks as readHandoffHello, l as APP_STORE_LIMITS, la as sanitizeMime, lc as ContactRequestError, li as UPGRADE_CAPABILITY, ll as inviteLink, ln as SPARK_NETWORKS, lo as shownTime, lr as mayBeHub, ls as handoffBusyFrame, lu as verify, mc as knockSlotRecords, mi as HoldRefusedError, ml as HANDOFF_CAPABILITY, mo as commitHash, mr as beaconRecords, ms as handoffDigest, mu as fromBase64Url, n as readX401SdJwtVc, nc as endedRequests, nl as createDeviceInvite, nn as WALLET_NETWORKS, no as checkStatusCard, ns as HANDOFF_REQUEST, o as appUpdateDecision, oa as dhtFileId, oc as settleRequest, oi as BUTTONS_CAPABILITY, ol as createChatInvite, on as formatPaymentAmount, oo as claimedTime, or as groupSignalFrame, os as handoffAttemptAllowed, ou as identityFromSeed, pc as knockSlotOf, pi as HoldKeys, pl as ENROLL_CAPABILITY, pn as isBitcoinAddress, po as MEMBER_KEY, pr as beaconKeys, ps as handoffDataFrame, pu as bytesEqual, q as parseCommunityEdit, qi as revokesIdentity, ql as normalizeRelayUrl, qo as serviceIdFromName, qr as deviceWakeRequest, qs as enrollDigits, qt as signDidDhtPacket, r as sameX401HolderJwk, ra as DHT_MESSAGE_TTL, rc as inboxRecord, ri as chatAppId, rl as deviceInviteJoinerParams, rn as arkAddressPrefix, ro as sameButtonText, rs as HANDOFF_TIMINGS, s as checkAppBeforeRun, sa as formatFileSize, sc as takeRequest, si as EDIT_CAPABILITY, sl as decodeInviteCode, sn as validatePaymentTarget, so as heardTime, sr as readGroupSignal, ss as handoffAttemptFailed, su as identityFromSeedB64, t as newX401HolderKey, tc as clearMissed, ti as isServeId, tl as readContactLink, tn as USDT_PUBLIC_RPC, tr as CarriedTransport, ts as HANDOFF_PIECE_BYTES, tu as createRelayPayload, uc as REQUEST_LIFETIME_MS, ui as HOLD_CAPABILITY, ul as inviteOwnership, un as SPARK_PROVIDER, uo as GROUP_ADMIN_OFF_ERROR, ur as meshHubs, us as handoffCancelFrame, v as sealGroupTyping, vc as openRequest, vl as deviceLinkPairing, vo as verifyCommitSignature, vr as lobbyRecords, vs as handoffOfferFrame, vu as toZ32, w as encodeCommunityLink, wa as RateWindow, wc as APP_BUNDLE_MAGIC, wl as TURN_RAISE_READ_TIMEOUT_MS, wo as RELAY_POLL_INTERVALS, wr as readBeacon, ws as newHandoffId, x as GROUP_READ_NOTE_COMMUNITY, xa as EDIT_RATE_WINDOW_MS, xc as requestRecords, xl as seedSigner, xr as newerHead, xs as handoffRetryAfter, y as COMMUNITY_LIMITS, ya as parseVideoMeta, yc as readKnockSlot, yl as devicePingFrame, yo as edgeParams, yr as mergeBeacon, ys as handoffPakeFrame, yu as utf8Decode, za as wireReaction, zc as appRef, zl as turnVerifierMark, zn as pairedMessageFrame, zr as PIN_LIMITS, zs as signTombstone } from "./src-BXeGLwWV.js";
2
+ import { $c as canonicalJson, $i as automaticTransport, $l as budgetRetryMs, $o as HANDOFF_HELLO, $r as vapidKeysMatch, $s as enrollProofFrame, A as knockRecords, Aa as GROUP_REACTION_FRAME, Ac as appViewOf, Al as turnPutSummary, An as findEndpoint, Ao as parseLocalTarget, As as readHandoffHave, B as GROUP_READ_NOTE, Ba as pairedReplyAuthor, Bc as appFingerprint, Bi as IdentityExchange, Bl as turnName, Bn as EngineError, Br as mayPin, Bs as setUpdateFrame, C as decodeCommunityLink, Ca as REMOVED_TEXT, Cc as requestRecords, Cl as newDeviceSetSecret, Co as DHT_POLL_INTERVALS, Cr as rankHubs, Cs as handoffRetryAfter, Cu as utf8Encode, D as encodeGroupEntryLink, Da as forwardedAgain, Dc as APP_ICON_PATH, Dl as TURN_RAISE_READ_TIMEOUT_MS, Dn as ENDPOINT, Do as presenceSeenAt, Dr as shouldBeHub, Ds as readHandoffAck, E as decodeGroupEntryLink, Ea as parseLinkPreview, Ec as APP_BUNDLE_MAGIC, En as decodeBolt11, Eo as WATCH_PEER_MS, Er as readLobby, Es as newHandoffId, F as groupWakeFrame, Fa as reactionEmoji, Fi as dialDescriptors, Fl as readTurnPacket, Fn as INVITE_TAKEN, Fr as TypingSender, Fs as sealHandoffPiece, G as GROUP_EDIT_TEXT_BYTES, Gc as isAppRef, Gi as newIdentityBinding, Go as emptyLinkRecords, Gr as WAKE_CALL_INTERVAL_MS, Gt as encodeDidDhtPacket, H as frameBytes, Ha as replySnippet, Hi as emptyIdentityLedger, Hl as turnVerifierMark, Hn as engineText, Hr as pinIsNewer, Hs as verifySetUpdate, Ht as didDhtDocument, I as groupWakes, Ia as reactionIsNewer, Ic as readAppBundleAsync, Il as signTurnPacket, In as LIVENESS_PING_MS, Io as RTC_CONFIG, J as mentionsMember, Ji as lastSharedWithMe, Jo as serviceIdFromName, Jr as newWakeToken, Js as enrollCancelReason, Jt as ETHEREUM_USDT, K as carryMentions, Kc as readAppRevocation, Ki as receivedIdentityStatus, Kl as RelayTransport, Ko as HTTP_SERVICE_PROTO, Kr as WakeLimiter, L as parseGroupWakeFrame, La as readReaction, Lc as sha256Paced, Ll as signTurnRelease, Ln as PAIRED_FRAME_TOO_LARGE, Lr as typingActivity, M as readKnocks, Ma as ReactionWindow, Mi as CapsExchange, Ml as TURN_MAX, Mn as parseCashuRequestPayload, Mo as LIMITS, Mr as transferStalled, Ms as readHandoffPake, Na as nextReactionNumber, Nc as isAppUrl, Ni as DHT_TEXT_CAPABILITY, Nl as firstDeviceSetSecret, Nn as parseFedimintRequestPayload, No as decodeControl, Ns as readHandoffTurnFrame, O as entryParams, Oa as readForwarded, Ol as TURN_SETTLE_MS, On as cashuRequestPayload, Oo as GhostlyHttpError, Or as ChatFiles, Os as readHandoffCancel, P as GroupWakeLimiter, Pa as queueReaction, Pc as pacer, Pi as capsDescriptors, Pl as nextTurnPosition, Pn as GhostLink, Po as encodeControl, Ps as readHandoffVerified, Qi as TRANSPORTS, Ql as traceLink, Qo as HANDOFF_HAVE, Qr as checkPushEndpoint, Qs as enrollHelloFrame, Qt as SEPOLIA_TEST_USDT, R as GROUP_LIMITS, Ra as validReactionNumber, Ri as IDENTITY_REVOCATION_LABEL, Rl as turnInstance, Rn as pairedMessageFits, Rs as readSetUpdate, S as communityHasFrame, Sa as MAX_REMOVAL_NUMBER, Sc as readLinkRecord, Sl as devicePingFrame, Sr as pickHubs, Ss as handoffReleaseFrame, Su as utf8Decode, Ta as dhtEditId, Tc as APP_BUNDLE_LIMITS, Tl as webCryptoSigner, To as RELAY_POLL_INTERVALS, Tr as readBeaconHead, Ts as handoffVersions, Ua as BUTTON_ID, Uc as isAppHash, Ui as identityRevocationValue, Ul as DEFAULT_RELAYS, Un as parseEngineError, Uo as parseCallSignal, Ur as pinNumberHolds, Ut as didDhtFromPublicKey, V as GroupSession, Va as readReply, Vc as appRef, Vl as turnStatedVerifier, Vn as engineError, Vo as contactRtcConfig, Vr as nextPinNumber, Vs as signTombstone, Wc as isAppKey, Wi as identityStatement, Wn as GROUP_FILE_LIMITS, Wr as readPin, Wt as encodeDidDhtDeactivated, Xa as STATUS_CARD_LIMITS, Xi as emptyProofLedger, Xl as normalizeRelayUrl, Xo as HANDOFF_CANCEL, Xr as relayRequest, Xs as enrollDoneFrame, Xt as ONCHAIN_PROVIDER, Y as groupName, Yi as PeerProofs, Yl as currentRelays, Yn as groupFileFallback, Yo as HANDOFF_ACK, Yr as parseWakeFrame, Ys as enrollDigits, Yt as EVM_TEST_CHAINS, Zc as parseImageMeta, Zi as validExternalKey, Zn as readGroupFileMeta, Zo as HANDOFF_DONE, Zr as wakeRequest, Zs as enrollGrantFrame, Zt as PaymentPreflightError, _ as openGroupTyping, _c as linkRecords, _i as readManifest, _l as HANDOFF_CAPABILITY, _o as rosterAdmin, _r as lobbyKeys, _s as handoffEphemeral, _u as fromBase64Url, a as appStoreDecision, aa as DHT_FILE_CAPABILITY, ac as inboxRecord, ai as APPS_CAPABILITY, al as createDeviceInvite, an as assertWholeSats, ao as statusCardText, as as HANDOFF_VERIFIED, b as CommunitySession, ba as EDIT_BUFFER_MS, bc as openRequest, bl as deviceKeyZ32, bo as edgeParams, br as mergeLobby, bs as handoffOfferFrame, bu as toBase64Url, c as planAppUpdate, ca as sanitizeFileName, cc as settleRequest, ci as STATUS_CARD_CAPABILITY, cl as OwnInviteError, cn as walletNetworkOf, co as heardTime, cr as MESH_HUBS, cs as handoffAttemptAllowed, cu as createIdentity, dc as ContactRequestError, di as HOLD_DATED_BACK_MS, dl as encodeInviteCode, dn as sparkAddressKind, do as GROUP_ADMIN_OFF_ERROR, dr as pickMeshHubs, ds as handoffBusyFrame, du as publicKeyFromZ32, ec as readEnrollGrant, ei as APP_RANGE_LIMITS, en as TEST_USDT_FAUCET_AMOUNT, es as HANDOFF_OFFER, eu as isDiscoveryBudgetError, f as readAppStoreSteps, fc as REQUEST_LIFETIME_MS, fi as HOLD_LIMITS, fl as inviteLink, fn as sparkInvoiceDetails, fo as GROUP_MEMBER_CAP, fr as COMMUNITY_TOPOLOGY, fs as handoffCancelFrame, fu as verify, g as groupTypingEpoch, ga as parseVoiceMeta, gc as knockSlotRecords, gi as newMailbox, gl as ENROLL_CAPABILITY, go as parseGroupCommit, gr as freshHubs, gs as handoffDigest, gt as normalizeAtprotoHandle, gu as bytesEqual, h as GroupTypingBoard, ha as fileMessageText, hc as knockSlotOf, hi as isHoldUrl, hl as DEVICES_CAPABILITY, hn as isPubkyKey, ho as commitHash, hr as doorHubs, hs as handoffDataFrame, ht as isAtprotoDid, hu as sanitizeDisplayText, i as appRevocationFor, ia as peekDhtMailbox, ic as endedRequests, ii as isAppVersion, il as readContactLink, in as assertTokenUnits, is as HANDOFF_TIMINGS, iu as createRelayPayload, j as mergeKnocks, ja as REACTION_LIMITS, jl as TURN_LAST_SEQUENCE, jn as isFederationId, jo as webLocalFetch, jr as transferEnded, js as readHandoffHello, k as knockIdentity, ka as COMMUNITY_REACTION_FRAME, kc as appDigest, kl as classifyTurnRead, kn as fedimintRequestPayload, ko as formatLocalTarget, kr as FILE_LIMITS, ks as readHandoffDone, l as APP_STORE_LIMITS, la as sanitizeMime, lc as takeRequest, li as UPGRADE_CAPABILITY, ll as createChatInvite, ln as SPARK_NETWORKS, lo as receivedTimestamp, lr as mayBeHub, ls as handoffAttemptFailed, lu as identityFromSeed, mc as knockSlotIdentity, mi as HoldRefusedError, mo as MEMBER_KEY, mr as beaconRecords, ms as handoffContextProof, mu as sanitizeAvatar, n as readX401SdJwtVc, nc as verifyEnrollProof, nl as createContactLink, nn as WALLET_NETWORKS, no as checkStatusCard, ns as HANDOFF_PIECE_BYTES, nu as PacketTooLargeError, o as appUpdateDecision, oa as dhtFileId, oc as newInbox, oi as BUTTONS_CAPABILITY, ol as deviceInviteJoinerParams, on as formatPaymentAmount, oo as arrivalKey, or as groupSignalFrame, os as NO_ATTEMPTS, pc as contactDay, pi as HoldKeys, pl as inviteOwnership, pn as isBitcoinAddress, pr as beaconKeys, ps as handoffContext, q as parseCommunityEdit, qi as revokesIdentity, qo as LEGACY_SERVICES, qr as deviceWakeRequest, qs as enrollCancelFrame, qt as signDidDhtPacket, r as sameX401HolderJwk, ra as DHT_MESSAGE_TTL, rc as clearMissed, ri as chatAppId, rl as encodeContactLink, rn as arkAddressPrefix, ro as sameButtonText, rs as HANDOFF_REQUEST, s as checkAppBeforeRun, sa as formatFileSize, sc as planKnocks, si as EDIT_CAPABILITY, sl as readDeviceInvite, sn as validatePaymentTarget, so as claimedTime, sr as readGroupSignal, ss as filePartName, t as newX401HolderKey, tc as readEnrollHello, ti as isServeId, tl as readCanonicalJson, tn as USDT_PUBLIC_RPC, tr as CarriedTransport, ts as HANDOFF_PAKE, tu as withRequestOptions, uc as turnOff, ui as HOLD_CAPABILITY, ul as decodeInviteCode, un as SPARK_PROVIDER, uo as shownTime, ur as meshHubs, us as handoffAttemptSucceeded, uu as identityFromSeedB64, v as sealGroupTyping, vc as makeStampPaced, vl as deviceEchoFrame, vo as rosterHas, vr as lobbyRecords, vs as handoffHelloFrame, w as encodeCommunityLink, wa as RateWindow, wc as seenEntry, wl as seedSigner, wr as readBeacon, ws as handoffStreamKey, x as GROUP_READ_NOTE_COMMUNITY, xa as EDIT_RATE_WINDOW_MS, xc as readKnockSlot, xl as deviceLinkPairing, xo as DirectPathWatch, xr as newerHead, xs as handoffPakeFrame, xu as toZ32, y as COMMUNITY_LIMITS, ya as parseVideoMeta, yc as mergeContactKnocks, yl as deviceEchoNonce, yo as verifyCommitSignature, yr as mergeBeacon, ys as handoffManifestFrames, yu as randomBytes, za as wireReaction, zc as APP_STATEMENT_LIMITS, zl as turnKeys, zn as pairedMessageFrame, zr as PIN_LIMITS, zs as setAckFrame } from "./src-BMHgbkli.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-BEg4I5Bk.js";
5
+ import { t as nwc } from "./nwcProvider-p_rMwtDv.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-BlH8-O3R.js";
7
- import { a as sealSeed, i as newDeviceKey, o as unsealSeed, r as intentRepository } from "./networkReason-i9wu5ZJs.js";
8
- import { $ as setAwayWallets, A as LightningCards, B as breezDatabaseInUse, C as FileAppender, D as streamStored, E as storedSize, F as ProviderSources, G as relayOnlyProblem, H as dropBreezDatabase, I as sourceKey, J as WrongNetworkError, K as ModeChanged, L as CASHU_MINT_SOURCE, M as isRecoveryPhrase, N as normalizePhrase, P as lightningPaying, Q as requireTurn, R as cashuMint, S as WALLET_TYPES, T as removeStored, U as iceServerProblem, V as breezDatabasesFor, W as iceServerSetting, X as awayFrom, Y as networkLabel, Z as refuseAway, _ as crossNetwork, a as storedGroupFiles, b as walletInstances, c as receivedPairedReply, d as paymentAlias, et as setSingleWriterGate, f as paymentWireId, g as createTiming, h as createFailure, i as groupOfFile, j as cardsKey, k as CASHU_CARD, l as replyRef, m as assertConfirmedReal, n as groupFileId, o as groupReply, p as WALLET_NAMES, q as ModeGate, r as groupFileText, s as pairedWireReply, t as GroupFileDesk, u as replyTo, v as paymentNetwork, w as readStored$1, y as paymentNetworksOf, z as breezDatabase } from "./groupFiles-y4lGrOC-.js";
9
- import { i as fedimintDatabase, n as createIrohWebEndpoint, o as loadFedimintSdk, r as irohRelayProblem, t as DEFAULT_IROH_RELAYS } from "./irohWeb-Y9wt8zG7.js";
7
+ import { a as sealSeed, i as newDeviceKey, o as unsealSeed, r as intentRepository } from "./networkReason-380j5yMs.js";
8
+ import { $ as setAwayWallets, A as LightningCards, B as breezDatabaseInUse, C as FileAppender, D as streamStored, E as storedSize, F as ProviderSources, G as relayOnlyProblem, H as dropBreezDatabase, I as sourceKey, J as WrongNetworkError, K as ModeChanged, L as CASHU_MINT_SOURCE, M as isRecoveryPhrase, N as normalizePhrase, P as lightningPaying, Q as requireTurn, R as cashuMint, S as WALLET_TYPES, T as removeStored, U as iceServerProblem, V as breezDatabasesFor, W as iceServerSetting, X as awayFrom, Y as networkLabel, Z as refuseAway, _ as crossNetwork, a as storedGroupFiles, b as walletInstances, c as receivedPairedReply, d as paymentAlias, et as setSingleWriterGate, f as paymentWireId, g as createTiming, h as createFailure, i as groupOfFile, j as cardsKey, k as CASHU_CARD, l as replyRef, m as assertConfirmedReal, n as groupFileId, o as groupReply, p as WALLET_NAMES, q as ModeGate, r as groupFileText, s as pairedWireReply, t as GroupFileDesk, u as replyTo, v as paymentNetwork, w as readStored$1, y as paymentNetworksOf, z as breezDatabase } from "./groupFiles-ajZgZ6P8.js";
9
+ import { i as fedimintDatabase, n as createIrohWebEndpoint, o as loadFedimintSdk, r as irohRelayProblem, t as DEFAULT_IROH_RELAYS } from "./irohWeb-DcRJdhce.js";
10
10
  import { c as isTestMint, d 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-BrlY773j.js";
11
- import { _ as reserveAdapterIds, b as testBuild, f as setOwnDidSource, g as registeredOnchainProviders, h as registeredLightningProviders, l as chosenResolver, n as resolveAtprotoDid, p as onAdaptersChanged, t as assertPublicServer, v as boundedIdentityFetch, y as verifyIdentity } from "./resolve-CnkY--2E.js";
12
- import { i as fromBase64Url$1, n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-DvZMFRzg.js";
13
- import { c as fileSpace, f as FILE_BYTES_STEP, o as fileBytes, r as blobDigest, s as fileBytesOf, u as removeFileBytes } from "./fileBytes-BMEBas7S.js";
11
+ import { _ as reserveAdapterIds, b as testBuild, f as setOwnDidSource, g as registeredOnchainProviders, h as registeredLightningProviders, l as chosenResolver, n as resolveAtprotoDid, p as onAdaptersChanged, t as assertPublicServer, v as boundedIdentityFetch, y as verifyIdentity } from "./resolve-hUsgRkmm.js";
12
+ import { i as fromBase64Url$1, n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-4TXDx3vD.js";
13
+ import { c as fileSpace, f as FILE_BYTES_STEP, o as fileBytes, r as blobDigest, s as fileBytesOf, u as removeFileBytes } from "./fileBytes-BD0v3rRG.js";
14
14
  import { t as hyperdhtRelayProblem } from "./hyperdhtRelay-BT_wRxab.js";
15
15
  import { sha256 } from "@noble/hashes/sha2.js";
16
16
  import { hkdf } from "@noble/hashes/hkdf.js";
@@ -198,7 +198,7 @@ function viewNews(before, after) {
198
198
  //#endregion
199
199
  //#region ../browser/src/engine/paymentAdapters/usdtWallet.ts
200
200
  /** The Ethereum libraries, a large part of the app: loaded once a USDT wallet is made, opened or restored, not with the engine. */
201
- var loadUsdt = () => import("./usdt-CdSNFUzO.js");
201
+ var loadUsdt = () => import("./usdt-glkUxsDe.js");
202
202
  /** Every new profile starts with this wallet: an address to receive on, nothing to set up. */
203
203
  var DEFAULT_USDT = {
204
204
  network: "ethereum",
@@ -647,7 +647,7 @@ async function restoreArkDatabase(walletId, snapshot) {
647
647
  //#endregion
648
648
  //#region ../browser/src/engine/paymentAdapters/arkWallet.ts
649
649
  /** The Ark SDK, a large part of the app: loaded once an Ark wallet is made, opened or restored, not with the engine. */
650
- var loadArkade = () => import("./arkade-B5g4r3Ea.js");
650
+ var loadArkade = () => import("./arkade-CHqwEHFd.js");
651
651
  /** How long a Testnet wallet about to make way for another waits for its server to say what it holds. */
652
652
  var RETIRE_READ_MS = 1e4;
653
653
  /** Every new profile starts with this wallet: nothing to set up before receiving. */
@@ -1299,9 +1299,20 @@ var BarkAdapter = class BarkAdapter {
1299
1299
  board() {
1300
1300
  return this.serial(() => this.wallet.boardAll());
1301
1301
  }
1302
+ /**
1303
+ * Asks the Ark server what changed. One made in the last 3 s is not made again and one under way is shared, as
1304
+ * BdkOnchain.sync: the wallet's refresh and the look at the chat requests it starts right after need one.
1305
+ */
1302
1306
  sync() {
1303
- return this.outside(() => this.wallet.sync());
1307
+ if (Date.now() - this.syncedAt < 3e3) return Promise.resolve();
1308
+ return this.syncing ??= this.outside(() => this.wallet.sync()).then(() => {
1309
+ this.syncedAt = Date.now();
1310
+ }).finally(() => {
1311
+ this.syncing = void 0;
1312
+ });
1304
1313
  }
1314
+ syncedAt = 0;
1315
+ syncing;
1305
1316
  /**
1306
1317
  * How long until the first coin expires. A coin left past its expiry can be swept by the server, so the wallet
1307
1318
  * renews coins near it (maintenance); this is what the page shows so the person knows to open Ghostly in time.
@@ -1396,12 +1407,19 @@ var BarkAdapter = class BarkAdapter {
1396
1407
  * the amount asked, made after the request. Nothing the payer says is trusted.
1397
1408
  */
1398
1409
  async received(address, amount, since, claimed = /* @__PURE__ */ new Set()) {
1399
- for (const m of await this.outside(() => this.wallet.history())) {
1400
- if (m.subsystemKind !== "receive" || m.status !== "successful" || m.effectiveBalanceSats < amount || Date.parse(m.createdAt) < since - 6e4) continue;
1401
- if (!m.receivedOnAddresses.map(addressOf).includes(address)) continue;
1402
- const id = outputTxid(m) ?? `movement-${m.id}`;
1403
- if (!claimed.has(id)) return id;
1404
- }
1410
+ return (await this.receipts())(address, amount, since, claimed);
1411
+ }
1412
+ /** `received` for every open request of one look: the history is read once, not once per request. */
1413
+ async receipts() {
1414
+ const history = await this.outside(() => this.wallet.history());
1415
+ return (address, amount, since, claimed = /* @__PURE__ */ new Set()) => {
1416
+ for (const m of history) {
1417
+ if (m.subsystemKind !== "receive" || m.status !== "successful" || m.effectiveBalanceSats < amount || Date.parse(m.createdAt) < since - 6e4) continue;
1418
+ if (!m.receivedOnAddresses.map(addressOf).includes(address)) continue;
1419
+ const id = outputTxid(m) ?? `movement-${m.id}`;
1420
+ if (!claimed.has(id)) return id;
1421
+ }
1422
+ };
1405
1423
  }
1406
1424
  outcome(m) {
1407
1425
  const txid = outputTxid(m);
@@ -6836,7 +6854,7 @@ var registry;
6836
6854
  var loading$1;
6837
6855
  var listeners = /* @__PURE__ */ new Set();
6838
6856
  function loadIdentityProviders() {
6839
- return loading$1 ??= import("./registry-CBDcdRPx.js").then((m) => {
6857
+ return loading$1 ??= import("./registry-BKffx4ZU.js").then((m) => {
6840
6858
  registry = m;
6841
6859
  for (const listener of listeners) listener();
6842
6860
  return m;
@@ -15282,9 +15300,9 @@ var Enrollment = class {
15282
15300
  ...device ? { device } : {}
15283
15301
  });
15284
15302
  }
15285
- /** The person stops it, on either side. */
15286
- cancel() {
15287
- return this.fail("cancelled", "cancelled");
15303
+ /** The person stops it, on either side (`offline`: by turning the network off). */
15304
+ cancel(reason = "cancelled") {
15305
+ return this.fail(reason, "cancelled");
15288
15306
  }
15289
15307
  /** A step that throws (a crash a test asked for, a store that failed) ends it, except a crash: that leaves everything as it was. */
15290
15308
  guard(work) {
@@ -16595,29 +16613,48 @@ function verifierStands(record, latest) {
16595
16613
  return !stated || bytesEqual(stated, turnVerifierMark(record.verifier));
16596
16614
  }
16597
16615
  var sameName = (a, b) => a.normalize("NFC").trim().toLocaleLowerCase() === b.normalize("NFC").trim().toLocaleLowerCase();
16616
+ /** One try at a time on this device, whoever asks: tries sent at once would all be checked against the same count. */
16617
+ var tries = Promise.resolve();
16618
+ function oneTry(work) {
16619
+ const run = tries.catch(() => {}).then(work);
16620
+ tries = run;
16621
+ return run;
16622
+ }
16623
+ /**
16624
+ * The limits, then the lock password against the verifier the active device left, when the copy needs it. Run inside
16625
+ * `oneTry`, on the record read there. As a pull is, the try is counted before the password is checked, and taken back
16626
+ * when it is the right one. Throws `TakeoverRefusal`.
16627
+ */
16628
+ async function checkTakeoverPassword(ports, record, password) {
16629
+ const now = ports.now ?? Date.now;
16630
+ const allowed = handoffAttemptAllowed(record.takeoverAttempts, now());
16631
+ if (allowed !== "ok") throw new TakeoverRefusal(allowed, allowed === "locked-out" ? "Too many tries. Try again later." : "Too many tries on this device.", allowed === "locked-out" ? handoffRetryAfter(record.takeoverAttempts, now()) : void 0);
16632
+ if (record.copy !== "frozen" && !record.verifier) return;
16633
+ if (!record.verifier) throw new TakeoverRefusal("no-password", "This device cannot check the profile's password yet.");
16634
+ if (typeof password !== "string" || !password) throw new TakeoverRefusal("password", "Type the profile's password.");
16635
+ await ports.amend({ takeoverAttempts: handoffAttemptFailed(record.takeoverAttempts, now()) });
16636
+ if (!await ports.proves(record.verifier, password).catch(() => false)) throw new TakeoverRefusal("password", "Wrong password.");
16637
+ await ports.amend({ takeoverAttempts: record.takeoverAttempts ?? NO_ATTEMPTS });
16638
+ }
16598
16639
  /**
16599
16640
  * Checks the request and forces the takeover. Resolves to the keeper's outcome: `start` when this device is the active
16600
16641
  * one now (its record says `active`, with the raise to make before the engine starts), anything else when it is not.
16601
16642
  * Throws `TakeoverRefusal` before anything is written.
16602
16643
  */
16603
16644
  async function forceTakeover(ports, request) {
16604
- const now = ports.now ?? Date.now;
16605
- const record = await ports.read();
16606
- if (!record || record.state !== "standby" && record.state !== "superseded") throw new TakeoverRefusal("state", "Only a device on standby takes over.");
16607
- if (!record.copy) throw new TakeoverRefusal("no-copy", "This device holds no copy of the profile. Use here moves it from the active device.");
16608
- const allowed = handoffAttemptAllowed(record.takeoverAttempts, now());
16609
- if (allowed !== "ok") throw new TakeoverRefusal(allowed, allowed === "locked-out" ? "Too many tries. Try again later." : "Too many tries on this device.", allowed === "locked-out" ? handoffRetryAfter(record.takeoverAttempts, now()) : void 0);
16610
- if (record.copy === "frozen" || record.verifier) {
16611
- if (!record.verifier) throw new TakeoverRefusal("no-password", "This device cannot check the profile's password yet.");
16612
- if (typeof request.password !== "string" || !request.password) throw new TakeoverRefusal("password", "Type the profile's password.");
16613
- if (!await ports.proves(record.verifier, request.password).catch(() => false)) {
16614
- await ports.amend({ takeoverAttempts: handoffAttemptFailed(record.takeoverAttempts, now()) });
16615
- throw new TakeoverRefusal("password", "Wrong password.");
16616
- }
16617
- }
16618
- const target = takeoverTarget(record);
16619
- if (target && (typeof request.name !== "string" || !sameName(request.name, target))) throw new TakeoverRefusal("name", `Type ${target} to confirm.`);
16620
- if (record.takeoverAttempts && (record.takeoverAttempts.total > 0 || record.takeoverAttempts.recent.length)) await ports.amend({ takeoverAttempts: handoffAttemptSucceeded() });
16645
+ const { record, target } = await oneTry(async () => {
16646
+ const record = await ports.read();
16647
+ if (!record || record.state !== "standby" && record.state !== "superseded") throw new TakeoverRefusal("state", "Only a device on standby takes over.");
16648
+ if (!record.copy) throw new TakeoverRefusal("no-copy", "This device holds no copy of the profile. Use here moves it from the active device.");
16649
+ await checkTakeoverPassword(ports, record, request.password);
16650
+ const target = takeoverTarget(record);
16651
+ if (target && (typeof request.name !== "string" || !sameName(request.name, target))) throw new TakeoverRefusal("name", `Type ${target} to confirm.`);
16652
+ if (record.takeoverAttempts && (record.takeoverAttempts.total > 0 || record.takeoverAttempts.recent.length)) await ports.amend({ takeoverAttempts: handoffAttemptSucceeded() });
16653
+ return {
16654
+ record,
16655
+ target
16656
+ };
16657
+ });
16621
16658
  const keeper = await ports.keeper();
16622
16659
  if (!keeper) throw new TakeoverRefusal("offline", "Go online to take over.");
16623
16660
  const outcome = await keeper.raise({ before: (latest) => {
@@ -16637,27 +16674,22 @@ function canStartOwnSet(record) {
16637
16674
  * settles. Throws `TakeoverRefusal` before anything is written.
16638
16675
  */
16639
16676
  async function startOwnSet(ports, request) {
16640
- const now = ports.now ?? Date.now;
16641
- const record = await ports.read();
16642
- if (!record || record.state !== "moving") throw new TakeoverRefusal("state", "Only a device that waits for its devices' new secret starts a set of its own.");
16643
- if (record.ownSet) return resumeOwnSet(ports);
16644
- if (!record.copy) throw new TakeoverRefusal("no-copy", "This device holds no copy of the profile.");
16645
- if (!canStartOwnSet(record)) throw new TakeoverRefusal("state", "This device cannot start a device set of its own.");
16646
- const allowed = handoffAttemptAllowed(record.takeoverAttempts, now());
16647
- if (allowed !== "ok") throw new TakeoverRefusal(allowed, allowed === "locked-out" ? "Too many tries. Try again later." : "Too many tries on this device.", allowed === "locked-out" ? handoffRetryAfter(record.takeoverAttempts, now()) : void 0);
16648
- if (record.copy === "frozen" || record.verifier) {
16649
- if (!record.verifier) throw new TakeoverRefusal("no-password", "This device cannot check the profile's password yet.");
16650
- if (typeof request.password !== "string" || !request.password) throw new TakeoverRefusal("password", "Type the profile's password.");
16651
- if (!await ports.proves(record.verifier, request.password).catch(() => false)) {
16652
- await ports.amend({ takeoverAttempts: handoffAttemptFailed(record.takeoverAttempts, now()) });
16653
- throw new TakeoverRefusal("password", "Wrong password.");
16654
- }
16655
- }
16656
- const target = takeoverTarget(record);
16657
- const same = (a, b) => a.normalize("NFC").trim().toLocaleLowerCase() === b.normalize("NFC").trim().toLocaleLowerCase();
16658
- if (target && (typeof request.name !== "string" || !same(request.name, target))) throw new TakeoverRefusal("name", `Type ${target} to confirm.`);
16677
+ const record = await oneTry(async () => {
16678
+ const record = await ports.read();
16679
+ if (!record || record.state !== "moving") throw new TakeoverRefusal("state", "Only a device that waits for its devices' new secret starts a set of its own.");
16680
+ if (record.ownSet) return null;
16681
+ if (!record.copy) throw new TakeoverRefusal("no-copy", "This device holds no copy of the profile.");
16682
+ if (!canStartOwnSet(record)) throw new TakeoverRefusal("state", "This device cannot start a device set of its own.");
16683
+ await checkTakeoverPassword(ports, record, request.password);
16684
+ const target = takeoverTarget(record);
16685
+ const same = (a, b) => a.normalize("NFC").trim().toLocaleLowerCase() === b.normalize("NFC").trim().toLocaleLowerCase();
16686
+ if (target && (typeof request.name !== "string" || !same(request.name, target))) throw new TakeoverRefusal("name", `Type ${target} to confirm.`);
16687
+ if (!ports.network) throw new TakeoverRefusal("offline", "Go online to take over.");
16688
+ if (record.takeoverAttempts && (record.takeoverAttempts.total > 0 || record.takeoverAttempts.recent.length)) await ports.amend({ takeoverAttempts: handoffAttemptSucceeded() });
16689
+ return record;
16690
+ });
16691
+ if (!record) return resumeOwnSet(ports);
16659
16692
  if (!ports.network) throw new TakeoverRefusal("offline", "Go online to take over.");
16660
- if (record.takeoverAttempts && (record.takeoverAttempts.total > 0 || record.takeoverAttempts.recent.length)) await ports.amend({ takeoverAttempts: handoffAttemptSucceeded() });
16661
16693
  if (!record.d || record.ownSlot === void 0 || !record.deviceSet[record.ownSlot]) throw new TakeoverRefusal("state", "This device has no device set.");
16662
16694
  const keys = turnKeys(fromBase64Url(record.d));
16663
16695
  const standing = classifyTurnRead({
@@ -17335,6 +17367,7 @@ var DeviceLinks = class {
17335
17367
  agreed: false,
17336
17368
  native: false,
17337
17369
  starting: /* @__PURE__ */ new Set(),
17370
+ moved: /* @__PURE__ */ new Set(),
17338
17371
  nativeMisses: 0,
17339
17372
  waiting: /* @__PURE__ */ new Map()
17340
17373
  };
@@ -17384,6 +17417,7 @@ var DeviceLinks = class {
17384
17417
  running.handoff = false;
17385
17418
  if (!running.earlier) this.handoffLink(running.key, false);
17386
17419
  }
17420
+ if (running.moved.size) this.moveNative(running);
17387
17421
  }
17388
17422
  this.changed();
17389
17423
  },
@@ -17443,15 +17477,38 @@ var DeviceLinks = class {
17443
17477
  }
17444
17478
  /**
17445
17479
  * The native transports this app runs changed (the person set a HyperDHT relay, or other Iroh relays): every link
17446
- * that runs native endpoints starts the ones it lacks now.
17480
+ * that runs native endpoints starts the ones it lacks now. Its endpoints of the `moved` transports, on the relay the
17481
+ * person changed or removed, go first, as a chat's do: each once no session runs on it.
17447
17482
  */
17448
- nativeChanged() {
17483
+ nativeChanged(moved = []) {
17449
17484
  for (const running of this.running.values()) {
17450
17485
  if (!running.native) continue;
17451
17486
  running.nativeMisses = 0;
17452
- this.startNative(running);
17487
+ for (const transport of moved) if (running.link.availableTransports.includes(transport)) running.moved.add(transport);
17488
+ this.moveNative(running);
17453
17489
  }
17454
17490
  }
17491
+ /**
17492
+ * Lets go of the link's endpoints on an old relay that no session runs on, and starts the native transports it lacks
17493
+ * then: the new relay's, or none where the relay was removed. One carrying the session goes when the session ends.
17494
+ */
17495
+ async moveNative(running) {
17496
+ for (const transport of [...running.moved]) {
17497
+ if (!running.link.availableTransports.includes(transport)) {
17498
+ running.moved.delete(transport);
17499
+ continue;
17500
+ }
17501
+ if (!running.link.canReleaseEndpoint(transport)) continue;
17502
+ running.moved.delete(transport);
17503
+ running.starting.add(transport);
17504
+ try {
17505
+ await running.link.releaseEndpoint(transport);
17506
+ } finally {
17507
+ running.starting.delete(transport);
17508
+ }
17509
+ }
17510
+ if (!this.stopped && this.running.get(running.id) === running) this.startNative(running);
17511
+ }
17455
17512
  async receive(running, frame) {
17456
17513
  const echo = deviceEchoFrame(frame);
17457
17514
  if (echo) {
@@ -19827,8 +19884,12 @@ var FileDesk = class {
19827
19884
  chat = made;
19828
19885
  return chat;
19829
19886
  }
19830
- /** At start: the chat's unfinished and finished files/3 transfers, as they were kept. */
19831
- restore(linkId, files) {
19887
+ /**
19888
+ * At start: the chat's unfinished and finished files/3 transfers, as they were kept. One that ended before this run is
19889
+ * reported ended already (a session opening walks them all), unless it finished and `unsettled` names it: a sent file
19890
+ * whose message never got its receipt, which its next session gives.
19891
+ */
19892
+ restore(linkId, files, unsettled = /* @__PURE__ */ new Set()) {
19832
19893
  const records = [];
19833
19894
  const chat = this.chat(linkId);
19834
19895
  for (const file of files) {
@@ -19844,6 +19905,7 @@ var FileDesk = class {
19844
19905
  records.push(file.wire3);
19845
19906
  if (file.wire3.direction === "in") chat.local.set(file.wire3.id, file.id);
19846
19907
  if (!transferEnded(file.wire3)) this.restored.add(file.id);
19908
+ else if (file.wire3.state !== "done" || !unsettled.has(file.id)) this.ended.add(file.id);
19847
19909
  if (file.wire3.state === "done") continue;
19848
19910
  this.deps.transfers.set(file.id, this.view(chat, file.wire3, file.wire3.confirmed, transferStalled(file.wire3, Date.now(), this.restored.has(file.id), Date.now())));
19849
19911
  }
@@ -21075,7 +21137,11 @@ var Outbox = class {
21075
21137
  ...manual ? { resendUntil: void 0 } : {}
21076
21138
  };
21077
21139
  if (this.stopped) {
21078
- await this.queue(message, "Connection closed. Delivery is unconfirmed.");
21140
+ await this.queue({
21141
+ ...message,
21142
+ delivery: "sending",
21143
+ deliveryError: void 0
21144
+ }, "Connection closed. Delivery is unconfirmed.");
21079
21145
  return;
21080
21146
  }
21081
21147
  this.track(id, typeof this.timeoutMs === "number" ? this.timeoutMs : this.timeoutMs(message));
@@ -21275,7 +21341,7 @@ var Outbox = class {
21275
21341
  const sent = this.attempts.get(message.id) ?? 0;
21276
21342
  if (until <= now) return this.fail(message.id, `${reason} Not confirmed within ${days(this.policy.windowMs)}.`);
21277
21343
  if (sent >= this.policy.maxAttempts) return this.fail(message.id, `${reason} Sent ${sent} times without a receipt.`);
21278
- await this.store.update(message.id, "queued", reason, { resendUntil: until });
21344
+ if (message.delivery !== "queued" || message.deliveryError !== reason || message.resendUntil !== until) await this.store.update(message.id, "queued", reason, { resendUntil: until });
21279
21345
  if (!this.stopped) this.schedule(message.id);
21280
21346
  }
21281
21347
  /** The DHT path retried within its own budget until expiry: only the live link may take it from here. */
@@ -26416,6 +26482,21 @@ var ENTRY_TIMEOUT_MS = 18e4;
26416
26482
  /** A joiner refused (its app cannot follow the group) is not answered again for this long. */
26417
26483
  var REFUSED_FOR_MS = 6e5;
26418
26484
  /**
26485
+ * The removed ids with this one noted. Full, the oldest of the author who has the most goes (the one just noted's own on
26486
+ * a tie): a member's removals of messages that are not here, as many as they like, push out only their own.
26487
+ */
26488
+ function withRemovedId(ids, messageId) {
26489
+ const next = [...ids, messageId];
26490
+ if (next.length <= 500) return next;
26491
+ const authorOf = (id) => id.slice(0, Math.max(0, id.indexOf(":")));
26492
+ const counts = /* @__PURE__ */ new Map();
26493
+ for (const id of next) counts.set(authorOf(id), (counts.get(authorOf(id)) ?? 0) + 1);
26494
+ let most = authorOf(messageId);
26495
+ for (const [author, count] of counts) if (count > counts.get(most)) most = author;
26496
+ next.splice(next.findIndex((id) => authorOf(id) === most), 1);
26497
+ return next;
26498
+ }
26499
+ /**
26419
26500
  * A joiner whose entry session timed out (the relays failing, its app closed a moment) is answered again after this,
26420
26501
  * doubling with each timeout in a row up to `REFUSED_FOR_MS`: a slow network is no refusal.
26421
26502
  */
@@ -26639,6 +26720,9 @@ var Groups = class {
26639
26720
  typings;
26640
26721
  /** A member's pins taken per window in a private group (group and member key). */
26641
26722
  pinPaces = /* @__PURE__ */ new Map();
26723
+ /** Records whose removals changed and wait to be written (`saveSoon`), by group. */
26724
+ unsaved = /* @__PURE__ */ new Map();
26725
+ saveTimer;
26642
26726
  /** Edge signaling through members (WISP 902 · Group Mesh § Signaling through members). */
26643
26727
  signals;
26644
26728
  /** Files and voice messages in every group, private or community (WISP 503 · Group Files). */
@@ -26692,9 +26776,32 @@ var Groups = class {
26692
26776
  this.communities.files = this.files;
26693
26777
  }
26694
26778
  }
26695
- /** Writes what the private groups' sessions still have to save (`GROUP_LIMITS.saveWithinMs`): the app is stopping. */
26779
+ /**
26780
+ * Writes what the private groups' sessions still have to save (`GROUP_LIMITS.saveWithinMs`), and the removals taken
26781
+ * since the last save (`saveSoon`): the app is stopping.
26782
+ */
26696
26783
  async flush() {
26697
- await Promise.allSettled([...this.sessions.values()].map((session) => session.flush()));
26784
+ await Promise.allSettled([...[...this.sessions.values()].map((session) => session.flush()), this.saveUnsaved()]);
26785
+ }
26786
+ /**
26787
+ * A group's record written within `GROUP_LIMITS.saveWithinMs`, for what may change many times a second (a catch-up
26788
+ * hands back up to 256 removals): it holds the group's whole state (a community's chain and store), not worth writing each time.
26789
+ */
26790
+ saveSoon(group) {
26791
+ this.unsaved.set(group.id, group);
26792
+ this.saveTimer ??= setTimeout(() => {
26793
+ this.saveTimer = void 0;
26794
+ this.saveUnsaved().catch(() => {});
26795
+ }, GROUP_LIMITS.saveWithinMs);
26796
+ }
26797
+ async saveUnsaved() {
26798
+ if (this.saveTimer) {
26799
+ clearTimeout(this.saveTimer);
26800
+ this.saveTimer = void 0;
26801
+ }
26802
+ const due = [...this.unsaved.values()];
26803
+ this.unsaved.clear();
26804
+ for (const group of due) if (this.record(group.id) === group) await this.store.putGroup(group);
26698
26805
  }
26699
26806
  /** `asItIs`: a copy that must stay as it was stored (limited mode, WISP 06), so nothing left over is cleared from it. */
26700
26807
  async load(asItIs = false) {
@@ -27074,7 +27181,7 @@ var Groups = class {
27074
27181
  }
27075
27182
  if (this.stored.get(group.id) !== group) return;
27076
27183
  delete group.declined;
27077
- if (group.state) return this.store.putGroup(group);
27184
+ if (group.state || group.invitation) return this.store.putGroup(group);
27078
27185
  this.stored.delete(group.id);
27079
27186
  await this.store.deleteGroup(group.id);
27080
27187
  }
@@ -27230,7 +27337,7 @@ var Groups = class {
27230
27337
  at: Date.now(),
27231
27338
  admin,
27232
27339
  ...hubs.length ? { hubs } : {},
27233
- ...bye ? { bye } : {}
27340
+ bye: bye ?? session.byeFrame()
27234
27341
  };
27235
27342
  delete group.entry;
27236
27343
  this.takeBack(groupId, group);
@@ -27272,6 +27379,16 @@ var Groups = class {
27272
27379
  this.host.emit();
27273
27380
  return next;
27274
27381
  }
27382
+ /**
27383
+ * The signed leave of my old key the admin has still to hear (`StoredGroup.owedBye`): none once the old key is out of
27384
+ * the roster, or a week after the leave, and then it is dropped from the row.
27385
+ */
27386
+ owedBye(group, session, now) {
27387
+ const bye = group.owedBye;
27388
+ if (!bye || session.status === "active" && rosterHas(session.roster, bye.k) && now - bye.ts <= LEFT_KEPT_MS) return bye;
27389
+ delete group.owedBye;
27390
+ this.store.putGroup(group).catch(() => {});
27391
+ }
27275
27392
  /** The admin heard me: the tombstone of a group I left can go. */
27276
27393
  async leaveConfirmed(groupId) {
27277
27394
  if (!this.stored.get(groupId)?.left) return;
@@ -27358,23 +27475,25 @@ var Groups = class {
27358
27475
  async setRemovals(groupId, removals) {
27359
27476
  const group = this.record(groupId);
27360
27477
  if (!group) return;
27478
+ const added = removals.some((r) => !group.removals?.some((kept) => kept.id === r.id));
27361
27479
  group.removals = removals;
27362
- await this.store.putGroup(group);
27480
+ if (added) await this.store.putGroup(group);
27481
+ else this.saveSoon(group);
27363
27482
  }
27364
27483
  /** A member's message its author deleted for everyone (WISP 400 § Delete for everyone): a copy that comes again is not kept. */
27365
27484
  isRemoved(groupId, messageId) {
27366
27485
  return !!this.record(groupId)?.removedIds?.includes(messageId);
27367
27486
  }
27368
27487
  /**
27369
- * Its author deleted a message for everyone: noted so (the newest `MAX_REMOVED_IDS`, also when the message is not here
27370
- * yet, so it is taken as gone when it comes), and its file goes from this device.
27488
+ * Its author deleted a message for everyone: noted so (`MAX_REMOVED_IDS` at most, each author's newest: `withRemovedId`;
27489
+ * also when the message is not here yet, so it is taken as gone when it comes), and its file goes from this device.
27371
27490
  */
27372
27491
  async removed(groupId, messageId) {
27373
27492
  const group = this.record(groupId);
27374
27493
  if (!group) return;
27375
27494
  if (!group.removedIds?.includes(messageId)) {
27376
- group.removedIds = [...group.removedIds ?? [], messageId].slice(-500);
27377
- await this.store.putGroup(group);
27495
+ group.removedIds = withRemovedId(group.removedIds ?? [], messageId);
27496
+ this.saveSoon(group);
27378
27497
  }
27379
27498
  this.communities.session(groupId)?.forget(messageId);
27380
27499
  await this.files?.forget(groupId, messageId);
@@ -27594,6 +27713,7 @@ var Groups = class {
27594
27713
  if (existing?.invitation?.seedB64 && !existing.invitation.entry) throw new Error("You are already joining this group");
27595
27714
  if (existing?.invitation && !existing.invitation.entry) throw new Error("You have an invitation to this group. Answer it first.");
27596
27715
  if (existing?.state && !existing.left) 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.");
27716
+ const owedBye = existing?.left?.bye ?? existing?.owedBye, declined = existing?.declined;
27597
27717
  if (existing) await this.forget(link.g);
27598
27718
  const seedB64 = dialedKey(link);
27599
27719
  const linkId = await this.host.openEntry(link, "guest", seedB64, link.host);
@@ -27609,7 +27729,9 @@ var Groups = class {
27609
27729
  seedB64,
27610
27730
  pieces: [],
27611
27731
  entry: link.host
27612
- }
27732
+ },
27733
+ ...owedBye ? { owedBye } : {},
27734
+ ...declined ? { declined } : {}
27613
27735
  };
27614
27736
  this.stored.set(link.g, group);
27615
27737
  await this.store.putGroup(group);
@@ -27633,7 +27755,7 @@ var Groups = class {
27633
27755
  }
27634
27756
  if (group.declined) {
27635
27757
  await this.declineOwed(group, now);
27636
- if (!group.state) continue;
27758
+ if (!group.state && !group.invitation) continue;
27637
27759
  }
27638
27760
  if (group.invitation?.takenBack && !group.state) {
27639
27761
  if (now - group.invitation.takenBack > LEFT_KEPT_MS) await this.forget(group.id, false);
@@ -27659,6 +27781,7 @@ var Groups = class {
27659
27781
  continue;
27660
27782
  }
27661
27783
  const session = this.sessions.get(group.id);
27784
+ if (group.owedBye && session) this.owedBye(group, session, now);
27662
27785
  if (group.invited) await this.ageInvited(group, now);
27663
27786
  if (!group.entry || !session) continue;
27664
27787
  if (!session.isAdmin) {
@@ -28186,7 +28309,9 @@ var Groups = class {
28186
28309
  id: g,
28187
28310
  createdAt: group.createdAt,
28188
28311
  state: joined.state,
28189
- contacts: viaLink ? {} : { [group.invitation.admin]: linkId }
28312
+ contacts: viaLink ? {} : { [group.invitation.admin]: linkId },
28313
+ ...group.owedBye ? { owedBye: group.owedBye } : {},
28314
+ ...group.declined ? { declined: group.declined } : {}
28190
28315
  };
28191
28316
  this.stored.set(g, member);
28192
28317
  this.acceptSaid.delete(g);
@@ -28392,9 +28517,12 @@ var Groups = class {
28392
28517
  } catch {
28393
28518
  return;
28394
28519
  }
28395
- if (peerKey === session.admin) try {
28396
- for (const bye of session.byesHeld()) this.host.sendOnLink(linkId, bye);
28397
- } catch {}
28520
+ if (peerKey === session.admin) {
28521
+ const owed = this.owedBye(group, session, this.now());
28522
+ try {
28523
+ for (const bye of [...session.byesHeld(), ...owed ? [owed] : []]) this.host.sendOnLink(linkId, bye);
28524
+ } catch {}
28525
+ }
28398
28526
  const kept = this.lingering.get(groupId);
28399
28527
  if (kept?.admin === peerKey) {
28400
28528
  if (this.signals.keptEntry(groupId) === kept.linkId) setTimeout(() => {
@@ -29876,9 +30004,17 @@ var GroupEdits = class {
29876
30004
  });
29877
30005
  }
29878
30006
  }
29879
- /** A group is forgotten, or the app stops: what was known of its members' edges goes with it. */
29880
- dropResends(groupId) {
29881
- const of = (key) => groupId === void 0 || key.startsWith(`${groupId}\n`);
30007
+ /**
30008
+ * A group's roster changed: what was known of the edges of members no longer in it goes (their last edge with it,
30009
+ * which `resentOn` would keep in memory for as long as the app runs). Out of the group: all of it.
30010
+ */
30011
+ membersChanged(groupId) {
30012
+ const members = this.host.membership(groupId)?.members;
30013
+ this.dropResends(groupId, members && ((key) => !members.has(key.slice(groupId.length + 1))));
30014
+ }
30015
+ /** A group is forgotten, or the app stops: what was known of its members' edges goes with it. `gone`: those keys alone. */
30016
+ dropResends(groupId, gone) {
30017
+ const of = (key) => groupId === void 0 || key.startsWith(`${groupId}\n`) && (!gone || gone(key));
29882
30018
  for (const [key, timer] of this.resendTimers) if (of(key)) {
29883
30019
  clearTimeout(timer);
29884
30020
  this.resendTimers.delete(key);
@@ -32415,10 +32551,11 @@ var CashuWallet = class CashuWallet {
32415
32551
  static STOP_WAIT_MS = 3e4;
32416
32552
  /**
32417
32553
  * The Cashu wallet of one network: its mints, their balance, and the network's newest movements (every network's when
32418
- * none is named) with the fees they paid. Only those movements are read, however long the history is.
32554
+ * none is named) with the fees they paid. Only those movements are read, however long the history is. `read` is the
32555
+ * proofs and swaps as `readStored` read them, shared by the views of several networks.
32419
32556
  */
32420
- async view(network) {
32421
- const proofs = await this.allProofs();
32557
+ async view(network, read) {
32558
+ const { proofs, swaps: allSwaps } = read ?? await this.readStored();
32422
32559
  const mints = this.getMints(network).map((url) => ({
32423
32560
  url,
32424
32561
  name: this.names.get(url) ?? new URL(url).hostname,
@@ -32427,7 +32564,7 @@ var CashuWallet = class CashuWallet {
32427
32564
  }));
32428
32565
  const history = await newestWalletTx((mint) => !network || mintNetwork(mint) === network, HISTORY_SHOWN);
32429
32566
  const here = new Set(mints.map((m) => m.url));
32430
- const swaps = (await wrap((await store(STORES$1.swaps, "readonly")).getAll())).filter((s) => here.has(s.mint) && !s.released && !s.finished);
32567
+ const swaps = allSwaps.filter((s) => here.has(s.mint) && !s.released && !s.finished);
32431
32568
  const about = (s) => s.kind === "send" ? swapOf(s).inputs.reduce((sum, p) => sum + Number(p.amount), 0) : s.tx?.amount ?? 0;
32432
32569
  const spentAway = new Set(swaps.filter((s) => s.stuck && s.kind === "send").flatMap((s) => swapOf(s).inputs.map((p) => p.secret)));
32433
32570
  return {
@@ -32441,6 +32578,13 @@ var CashuWallet = class CashuWallet {
32441
32578
  feesPaid: history.reduce((sum, tx) => sum + tx.fee, 0)
32442
32579
  };
32443
32580
  }
32581
+ /** Every proof and swap stored, read once for the views of every network: each read is the whole store. */
32582
+ async readStored() {
32583
+ return {
32584
+ proofs: await this.allProofs(),
32585
+ swaps: await wrap((await store(STORES$1.swaps, "readonly")).getAll())
32586
+ };
32587
+ }
32444
32588
  /**
32445
32589
  * Ecash a profile restore brought back (`unchecked`) is a copy from when the backup was made. What was spent since
32446
32590
  * (by the profile it was copied from, or by this one before it was restored) still counted in the balance, for good,
@@ -32511,6 +32655,11 @@ var CashuWallet = class CashuWallet {
32511
32655
  name
32512
32656
  };
32513
32657
  }
32658
+ /** What `view(network).balance` says, from the proofs alone: no swaps, no history. */
32659
+ async balance(network) {
32660
+ const here = new Set(this.getMints(network));
32661
+ return total((await this.allProofs()).filter((p) => here.has(p.mint) && !p.reserved));
32662
+ }
32514
32663
  async balanceAt(mint) {
32515
32664
  return total((await this.allProofs()).filter((p) => p.mint === mint && !p.reserved));
32516
32665
  }
@@ -32790,6 +32939,7 @@ var CashuWallet = class CashuWallet {
32790
32939
  tx.oncomplete = () => resolve();
32791
32940
  tx.onabort = tx.onerror = () => reject(new PaymentPreflightError(engineText("reviewedSatsGone")));
32792
32941
  });
32942
+ this.events.onChange();
32793
32943
  const { keep, send } = await (await this.wallet(prepared.mint)).completeSwap(preview);
32794
32944
  return this.finishReviewedCashu(review, prepared, keep, send);
32795
32945
  });
@@ -33993,6 +34143,11 @@ var PaymentBook = class extends Map {
33993
34143
  return this.shown ??= Object.fromEntries([...this].map(([id, { token: _token, ...view }]) => [id, view]));
33994
34144
  }
33995
34145
  };
34146
+ /**
34147
+ * How often a contact's "I paid it from another wallet" makes an on-chain, Ark, Bark or Spark wallet look
34148
+ * (`receiveCheck`): no more often than the wallet's own refresh, which runs the same look.
34149
+ */
34150
+ var RAIL_LOOK_MS = 1e4;
33996
34151
  var PaymentDesk = class {
33997
34152
  wallet;
33998
34153
  host;
@@ -35263,7 +35418,8 @@ var PaymentDesk = class {
35263
35418
  /**
35264
35419
  * The contact says it paid one of our requests from another wallet: our wallet is asked now, and it alone
35265
35420
  * decides. A request already paid is said so again (the first answer may have been lost). Bounded: one
35266
- * look every 3 seconds per request.
35421
+ * look every 3 seconds per Lightning request, and one every `RAIL_LOOK_MS` per other rail: 300 frames a minute
35422
+ * about 5 Bark requests made 100 Bark server syncs and 500 history reads.
35267
35423
  */
35268
35424
  async receiveCheck(linkId, payment) {
35269
35425
  const link = this.host.getLink(linkId);
@@ -35280,8 +35436,9 @@ var PaymentDesk = class {
35280
35436
  return;
35281
35437
  }
35282
35438
  const now = Date.now();
35283
- if (now - (this.lastCheckFrom.get(request.id) ?? 0) < 3e3) return;
35284
- this.lastCheckFrom.set(request.id, now);
35439
+ const [key, every] = rail === "lightning" ? [request.id, 3e3] : [rail, RAIL_LOOK_MS];
35440
+ if (now - (this.lastCheckFrom.get(key) ?? 0) < every) return;
35441
+ this.lastCheckFrom.set(key, now);
35285
35442
  try {
35286
35443
  if (rail === "lightning") await this.lightning[paymentNetwork(request)].check?.(payment.endpoint[1].trim().toLowerCase() === request.invoice?.toLowerCase() ? request.invoice : void 0);
35287
35444
  else if (rail === "bitcoin") await this.reconcileBitcoinReceipts();
@@ -35458,13 +35615,20 @@ var PaymentDesk = class {
35458
35615
  if (!this.host.getLink(linkId)?.supportsUsdtPayments || request?.target?.method !== "usdt" || request.linkId !== linkId || request.direction !== "out" || request.kind !== "request" || payment.amount.asset !== request.unit || payment.amount.value !== String(request.amount)) return;
35459
35616
  const existing = this.payments.get(payment.id);
35460
35617
  if (existing && (existing.direction !== "in" || existing.linkId !== linkId || existing.requestId !== request.id)) return;
35618
+ if (existing) {
35619
+ if (request.state === "settled") this.host.getLink(linkId)?.sendPaymentResult({
35620
+ id: request.id,
35621
+ ok: true
35622
+ });
35623
+ return;
35624
+ }
35461
35625
  let txid;
35462
35626
  try {
35463
35627
  txid = JSON.parse(payment.endpoint[1]).txid;
35464
35628
  } catch {
35465
35629
  return;
35466
35630
  }
35467
- if (typeof txid !== "string" || !/^0x[a-fA-F0-9]{64}$/.test(txid) || existing?.state === "settled") return;
35631
+ if (typeof txid !== "string" || !/^0x[a-fA-F0-9]{64}$/.test(txid)) return;
35468
35632
  if (this.repeatedReceipt(this.host.getLink(linkId), request, payment.id)) return;
35469
35633
  txid = txid.toLowerCase();
35470
35634
  if ([...this.payments.values()].some((p) => p.txid?.toLowerCase() === txid && (p.linkId !== linkId || (p.kind === "request" ? p.id !== request.id : p.requestId !== request.id)))) return;
@@ -35624,6 +35788,13 @@ var PaymentDesk = class {
35624
35788
  if (!link?.supportsArkPayments || !request?.target || request.linkId !== linkId || request.direction !== "out" || request.kind !== "request") return;
35625
35789
  const existing = this.payments.get(payment.id);
35626
35790
  if (existing && (existing.linkId !== linkId || existing.direction !== "in" || existing.requestId !== request.id)) return;
35791
+ if (existing) {
35792
+ if (request.state === "settled") link.sendPaymentResult({
35793
+ id: request.id,
35794
+ ok: true
35795
+ });
35796
+ return;
35797
+ }
35627
35798
  if (parseSats(payment.amount.value, payment.amount.asset) !== request.amount) return;
35628
35799
  let txid;
35629
35800
  try {
@@ -35632,7 +35803,7 @@ var PaymentDesk = class {
35632
35803
  return;
35633
35804
  }
35634
35805
  if ([...this.payments.values()].some((p) => p.txid === txid && (p.linkId !== linkId || (p.kind === "request" ? p.id !== request.id : p.requestId !== request.id)))) return;
35635
- if (typeof txid !== "string" || !/^[a-f0-9]{64}$/.test(txid) || existing?.state === "settled") return;
35806
+ if (typeof txid !== "string" || !/^[a-f0-9]{64}$/.test(txid)) return;
35636
35807
  if (this.repeatedReceipt(link, request, payment.id)) return;
35637
35808
  await this.save({
35638
35809
  id: payment.id,
@@ -35786,13 +35957,18 @@ var PaymentDesk = class {
35786
35957
  try {
35787
35958
  const open = [...this.payments.values()].filter((r) => r.kind === "request" && r.direction === "out" && r.state === "pending" && r.target?.method === "bark");
35788
35959
  const bark = this.bark;
35789
- for (const wallet of new Set(open.map((r) => bark[walletNetworkOf(r.target.network)]))) await wallet.adapter?.sync().catch(() => {});
35960
+ const receipts = /* @__PURE__ */ new Map();
35961
+ for (const wallet of new Set(open.map((r) => bark[walletNetworkOf(r.target.network)]))) {
35962
+ if (!wallet.adapter) continue;
35963
+ await wallet.adapter.sync().catch(() => {});
35964
+ receipts.set(wallet.adapter, await wallet.adapter.receipts().catch(() => void 0));
35965
+ }
35790
35966
  for (const request of open) {
35791
35967
  if (request.kind !== "request" || request.direction !== "out" || request.state !== "pending" || request.target?.method !== "bark") continue;
35792
35968
  const adapter = this.bark[walletNetworkOf(request.target.network)].adapter;
35793
35969
  if (!adapter || request.target.provider !== adapter.config.provider || request.target.network !== adapter.config.network) continue;
35794
35970
  const claimed = new Set([...this.payments.values()].filter((p) => p.target?.method === "bark" && p.kind === "request" && p.txid).map((p) => p.txid));
35795
- const txid = await adapter.received(request.target.address, request.amount, request.createdAt, claimed).catch(() => void 0);
35971
+ const txid = receipts.get(adapter)?.(request.target.address, request.amount, request.createdAt, claimed);
35796
35972
  if (!txid) continue;
35797
35973
  await this.settleRequest(request, { txid });
35798
35974
  for (const payment of this.payments.values()) if (payment.kind === "payment" && payment.direction === "in" && payment.requestId === request.id && payment.state === "pending") await this.save({
@@ -37044,6 +37220,8 @@ var SPARE_INVITE_WARM_AFTER_TAKE_MS = 3e4;
37044
37220
  var STARTUP_QUIET_MS = 15e3;
37045
37221
  /** At start, how long links start in one task before the page gets the thread back (`startNow`). */
37046
37222
  var START_SLICE_MS = 10;
37223
+ /** How long the wallets' changes gather into one view of them (`walletChanged`). */
37224
+ var WALLET_CHANGE_MS = 50;
37047
37225
  var SPARE_INVITE_MAX_AGE_MS = 9e5;
37048
37226
  /** How far before this clock a warm packet is dated (`warmKey`): further than a contact's clock is ever behind. */
37049
37227
  var WARM_DATED_BACK_MS = 864e5;
@@ -37196,6 +37374,8 @@ var GhostlyNode = class GhostlyNode {
37196
37374
  get networkOn() {
37197
37375
  return !!this.settings.online && !this.limitedMode && !this.options.offline;
37198
37376
  }
37377
+ /** The chats found saved at start that this run leaves unstarted (`NodeOptions.deferChats`). */
37378
+ deferredChats = /* @__PURE__ */ new Set();
37199
37379
  transport;
37200
37380
  /** The same, for groups' requests: a relay budget keeps a chat's share from them (`CHAT_RESERVE`). */
37201
37381
  groupTransport;
@@ -37456,23 +37636,23 @@ var GhostlyNode = class GhostlyNode {
37456
37636
  * goes through the wallet of its own network, and a wallet of one network never pays for the other.
37457
37637
  */
37458
37638
  usdtWallets = perNetwork((network) => new UsdtWallet(network, (viewChanged = true) => {
37459
- if (viewChanged) this.refreshWallet();
37639
+ if (viewChanged) this.walletChanged();
37460
37640
  this.desk.reconcileUsdtReceipts().catch(() => {});
37461
37641
  }));
37462
37642
  arkWallets = perNetwork((network) => new ArkWallet(network, (viewChanged = true) => {
37463
- if (viewChanged) this.refreshWallet();
37643
+ if (viewChanged) this.walletChanged();
37464
37644
  this.desk.reconcileArkReceipts().catch(() => {});
37465
37645
  }));
37466
37646
  barkWallets = perNetwork((network) => new BarkWallet(network, (viewChanged = true) => {
37467
- if (viewChanged) this.refreshWallet();
37647
+ if (viewChanged) this.walletChanged();
37468
37648
  this.desk.reconcileBarkReceipts().catch(() => {});
37469
37649
  }));
37470
37650
  fedimintWallets = perNetwork((network) => new FedimintWallet(network, {
37471
- changed: () => void this.refreshWallet(),
37651
+ changed: () => this.walletChanged(),
37472
37652
  received: (paymentId) => void this.desk.onLightningPaid({ paymentId })
37473
37653
  }, () => (this.options.fedimintSdk ?? loadFedimintSdk)()));
37474
37654
  sparkWallets = perNetwork((network) => new SparkWallet(network, (viewChanged = true) => {
37475
- if (viewChanged) this.refreshWallet();
37655
+ if (viewChanged) this.walletChanged();
37476
37656
  this.desk.reconcileSparkReceipts().catch(() => {});
37477
37657
  }));
37478
37658
  /** What a call naming no network acts on (a caller from before wallets had their own): Mainnet. */
@@ -37558,7 +37738,7 @@ var GhostlyNode = class GhostlyNode {
37558
37738
  return this.settings.mints.filter((mint) => mintNetwork(mint) === wanted);
37559
37739
  }
37560
37740
  wallet = new CashuWallet((network) => this.networkMints(network), {
37561
- onChange: () => void this.refreshWallet(),
37741
+ onChange: () => this.walletChanged(),
37562
37742
  onQuotePaid: (quote) => void this.lightnings[mintNetwork(quote.mint)].reportInvoicePaid(quote.invoice, {
37563
37743
  paymentId: quote.paymentId,
37564
37744
  mint: quote.mint
@@ -37580,6 +37760,7 @@ var GhostlyNode = class GhostlyNode {
37580
37760
  providerHost = (network) => ({
37581
37761
  platform: this.options.platform ?? "web",
37582
37762
  cashu: this.wallet,
37763
+ cashuBalance: () => this.walletView.networks?.[network].balance,
37583
37764
  fedimint: this.fedimintWallets[network],
37584
37765
  invoke: this.options.invoke
37585
37766
  });
@@ -37593,14 +37774,14 @@ var GhostlyNode = class GhostlyNode {
37593
37774
  hasMints: () => this.networkMints(network).length > 0,
37594
37775
  fetch: (...request) => (this.options.lnurlFetch ?? globalThis.fetch)(...request),
37595
37776
  events: {
37596
- changed: () => void this.refreshWallet(),
37777
+ changed: () => this.walletChanged(),
37597
37778
  received: (op) => void this.desk.onLightningPaid(op),
37598
37779
  resolved: (op, paid) => void this.desk.onLightningResolved(op, paid)
37599
37780
  }
37600
37781
  }));
37601
37782
  /** On-chain Bitcoin of each network, through its active source: none until the person sets one up. */
37602
37783
  bitcoins = perNetwork((network) => new BitcoinService(network, () => this.providers().onchain, () => this.providerHost(network), () => {
37603
- this.refreshWallet();
37784
+ this.walletChanged();
37604
37785
  this.desk.reconcileBitcoinReceipts().catch(() => {});
37605
37786
  }));
37606
37787
  desk = new PaymentDesk(this.wallet, {
@@ -37729,16 +37910,20 @@ var GhostlyNode = class GhostlyNode {
37729
37910
  await db.updateDelivery(linkId, messageId, state, error);
37730
37911
  await this.noteHold(linkId, messageId, state, error);
37731
37912
  const message = await db.getMessage(linkId, messageId);
37732
- if (message?.file) this.transfers.set(message.file.id, state === "failed" ? {
37733
- state: "failed",
37734
- transferred: 0,
37735
- size: message.file.size,
37736
- error
37737
- } : {
37738
- state: "done",
37739
- transferred: message.file.size,
37740
- size: message.file.size
37741
- });
37913
+ if (message?.file) {
37914
+ const transfer = state === "failed" ? {
37915
+ state: "failed",
37916
+ transferred: 0,
37917
+ size: message.file.size,
37918
+ error
37919
+ } : {
37920
+ state: "done",
37921
+ transferred: message.file.size,
37922
+ size: message.file.size
37923
+ };
37924
+ this.transfers.set(message.file.id, transfer);
37925
+ await fileStore.updateTransfer(message.file.id, transfer).catch(() => {});
37926
+ }
37742
37927
  if (message && state !== "failed") this.messageFeedback("sent", message);
37743
37928
  await this.messagesChanged(linkId, [messageId]);
37744
37929
  this.emitState();
@@ -38540,12 +38725,48 @@ var GhostlyNode = class GhostlyNode {
38540
38725
  this.emitState();
38541
38726
  }).catch(() => {}), 250);
38542
38727
  }
38543
- async refreshWallet() {
38728
+ /** The wallets' view being made, and the one more run asked for while it is (see `refreshWallet`). */
38729
+ walletRefresh;
38730
+ walletRefreshAgain;
38731
+ /**
38732
+ * The wallets' view made again. Every wallet that changes asks for it: a start asked 11 times in its first seconds,
38733
+ * each run reading every Cashu proof and every payment review ever made. A run in flight may have read
38734
+ * before what the caller changed, so callers meanwhile share one more run after it: each still waits for a view made
38735
+ * after it asked.
38736
+ */
38737
+ refreshWallet() {
38738
+ if (!this.walletRefresh) {
38739
+ const run = this.walletRefresh = this.refreshWalletNow().finally(() => {
38740
+ if (this.walletRefresh === run) this.walletRefresh = void 0;
38741
+ });
38742
+ return run;
38743
+ }
38744
+ return this.walletRefreshAgain ??= this.walletRefresh.catch(() => {}).then(() => {
38745
+ this.walletRefreshAgain = void 0;
38746
+ return this.refreshWallet();
38747
+ });
38748
+ }
38749
+ /** While `startWallets` opens the wallets: what they say changed is in the view it makes once they are open. */
38750
+ walletsOpening = false;
38751
+ walletChangeTimer;
38752
+ /**
38753
+ * A wallet says what it shows changed, and nobody waits for the view: the changes said within `WALLET_CHANGE_MS`
38754
+ * make one view. Opening, the wallets and their sources say so a dozen times within 150 ms.
38755
+ */
38756
+ walletChanged() {
38757
+ if (this.walletsOpening || this.walletChangeTimer) return;
38758
+ this.walletChangeTimer = setTimeout(() => {
38759
+ this.walletChangeTimer = void 0;
38760
+ if (!this.shuttingDown) this.refreshWallet().catch(() => {});
38761
+ }, WALLET_CHANGE_MS);
38762
+ }
38763
+ async refreshWalletNow() {
38544
38764
  const networks = {};
38545
38765
  let everything = [];
38546
38766
  const awaiting = await this.readAwaiting();
38767
+ const stored = await this.wallet.readStored();
38547
38768
  for (const network of WALLET_NETWORKS) {
38548
- const view = await this.wallet.view(network);
38769
+ const view = await this.wallet.view(network, stored);
38549
38770
  everything = everything.concat(view.history);
38550
38771
  const history = view.history.filter((tx) => !tx.mint || mintNetwork(tx.mint) === network);
38551
38772
  networks[network] = {
@@ -38699,6 +38920,9 @@ var GhostlyNode = class GhostlyNode {
38699
38920
  await this.publicProfiles.load();
38700
38921
  if (!this.limitedMode) await this.startWallets();
38701
38922
  const links = await db.getLinks();
38923
+ if (this.options.deferChats) {
38924
+ for (const stored of links) if (!stored.group) this.deferredChats.add(stored.id);
38925
+ }
38702
38926
  for (const stored of links) if (stored.group) this.links.set(stored.id, newLiveLink(stored, 0, linkFilesFrom(stored.id, [], [])));
38703
38927
  for (const group of await db.getGroups()) await this.settleHistory(`group:${group.id}`);
38704
38928
  await this.groups.load(this.limitedMode);
@@ -38710,13 +38934,14 @@ var GhostlyNode = class GhostlyNode {
38710
38934
  await this.settleHistory(stored.id);
38711
38935
  const messages = await db.getMessages(stored.id);
38712
38936
  const storedFiles = await fileStore.listForLink(stored.id);
38713
- const waiting = new Set(messages.flatMap((m) => m.sender === "me" && m.delivery === "waiting" && m.file ? [m.file.id] : []));
38714
- for (const file of storedFiles) if (file.transfer && file.transfer.state !== "done" && !file.wire3 && !waiting.has(file.id)) this.transfers.set(file.id, file.transfer.state === "transferring" ? {
38937
+ const notInterrupted = new Set(messages.flatMap((m) => m.sender === "me" && m.file && (m.delivery === "waiting" || m.via === "hold" && (m.delivery === "held" || m.delivery === "delivered")) ? [m.file.id] : []));
38938
+ for (const file of storedFiles) if (file.transfer && file.transfer.state !== "done" && !file.wire3 && !notInterrupted.has(file.id)) this.transfers.set(file.id, file.transfer.state === "transferring" ? {
38715
38939
  ...file.transfer,
38716
38940
  state: "failed",
38717
38941
  error: "Transfer interrupted. Retry when connected."
38718
38942
  } : file.transfer);
38719
- this.fileDesk.restore(stored.id, storedFiles);
38943
+ const unreceipted = new Set(messages.flatMap((m) => m.sender === "me" && m.file && m.delivery !== "delivered" ? [m.file.id] : []));
38944
+ this.fileDesk.restore(stored.id, storedFiles, unreceipted);
38720
38945
  const files = linkFilesFrom(stored.id, storedFiles, messages);
38721
38946
  this.links.set(stored.id, newLiveLink(stored, messages[messages.length - 1]?.timestamp ?? 0, files));
38722
38947
  this.links.get(stored.id).waitingSends = Promise.resolve(new Set(messages.filter(waitsForLive).map((m) => m.id)));
@@ -38921,16 +39146,21 @@ var GhostlyNode = class GhostlyNode {
38921
39146
  setSingleWriterGate(() => this.singleWriterTurn());
38922
39147
  const migrated = await migrateWalletNetworks();
38923
39148
  if (migrated.moved.length || migrated.unreadable.length) console.info("[wallet] wallets moved to their network's key:", migrated.moved.map((m) => m.key).join(", ") || "none", migrated.unreadable.length ? `; left as they were: ${migrated.unreadable.join(", ")}` : "");
38924
- for (const network of WALLET_NETWORKS) {
38925
- await this.arkWallets[network].start();
38926
- await this.barkWallets[network].start();
38927
- await this.fedimintWallets[network].start();
38928
- await this.sparkWallets[network].start();
38929
- await this.usdtWallets[network].start();
38930
- await this.lightnings[network].start();
38931
- await this.bitcoins[network].start();
38932
- }
38933
- await this.desk.start();
39149
+ this.walletsOpening = true;
39150
+ try {
39151
+ for (const network of WALLET_NETWORKS) {
39152
+ await this.arkWallets[network].start();
39153
+ await this.barkWallets[network].start();
39154
+ await this.fedimintWallets[network].start();
39155
+ await this.sparkWallets[network].start();
39156
+ await this.usdtWallets[network].start();
39157
+ await this.lightnings[network].start();
39158
+ await this.bitcoins[network].start();
39159
+ }
39160
+ await this.desk.start();
39161
+ } finally {
39162
+ this.walletsOpening = false;
39163
+ }
38934
39164
  await this.refreshWallet();
38935
39165
  this.wallet.start();
38936
39166
  this.dropStaleReviews();
@@ -39169,6 +39399,7 @@ var GhostlyNode = class GhostlyNode {
39169
39399
  this.resumeTimers.clear();
39170
39400
  if (this.paymentTimer) clearTimeout(this.paymentTimer);
39171
39401
  clearTimeout(this.awaitingTimer);
39402
+ clearTimeout(this.walletChangeTimer);
39172
39403
  clearInterval(this.staleReviewTimer);
39173
39404
  if (this.spareTimer) clearTimeout(this.spareTimer);
39174
39405
  for (const timer of this.reactionTimers.values()) clearTimeout(timer);
@@ -39328,6 +39559,7 @@ var GhostlyNode = class GhostlyNode {
39328
39559
  }
39329
39560
  getState() {
39330
39561
  const groups = this.groups.views();
39562
+ const edges = this.edgesByMember();
39331
39563
  return {
39332
39564
  settings: this.settings,
39333
39565
  ...this.limitedMode && { limited: true },
@@ -39370,7 +39602,7 @@ var GhostlyNode = class GhostlyNode {
39370
39602
  ...this.reactionNotes.has(`group:${group.id}`) && { lastReaction: this.reactionNotes.get(`group:${group.id}`) },
39371
39603
  ...this.groupWakeView(group),
39372
39604
  members: group.members.map((member) => {
39373
- const edge = member.me ? void 0 : this.edgeView(group.id, member.key);
39605
+ const edge = member.me ? void 0 : this.edgeView(group.id, member.key, edges);
39374
39606
  return edge ? {
39375
39607
  ...member,
39376
39608
  edge
@@ -39416,9 +39648,25 @@ var GhostlyNode = class GhostlyNode {
39416
39648
  if (!this.groups.isCommunityGroup(groupId) || !this.membership(groupId)?.members.has(member)) return;
39417
39649
  await this.communityPay.hello(groupId, member).catch(() => {});
39418
39650
  }
39651
+ /**
39652
+ * The groups' edges by group, then member: one pass over the links per state, not one per member of every group
39653
+ * (communities' members, who have no edge, included).
39654
+ */
39655
+ edgesByMember() {
39656
+ const edges = /* @__PURE__ */ new Map();
39657
+ for (const live of this.links.values()) {
39658
+ const { group, groupPeer, groupEntry } = live.stored;
39659
+ if (!group || !groupPeer || groupEntry) continue;
39660
+ const members = edges.get(group) ?? /* @__PURE__ */ new Map();
39661
+ if (!members.has(groupPeer)) members.set(groupPeer, live);
39662
+ edges.set(group, members);
39663
+ }
39664
+ return edges;
39665
+ }
39419
39666
  /** The edge of a group toward one member, as the group page shows it: what carries it and when the member was last heard. */
39420
- edgeView(groupId, member) {
39421
- for (const live of this.links.values()) if (live.stored.group === groupId && live.stored.groupPeer === member && !live.stored.groupEntry) return edgeView(live, Date.now(), this.groupNativeWaiting.has(live.stored.id));
39667
+ edgeView(groupId, member, edges = this.edgesByMember()) {
39668
+ const live = edges.get(groupId)?.get(member);
39669
+ return live && edgeView(live, Date.now(), this.groupNativeWaiting.has(live.stored.id));
39422
39670
  }
39423
39671
  /** A chat's or a group's history, as a page gets it (`withoutFrame`). */
39424
39672
  async getMessages(linkId) {
@@ -39568,6 +39816,7 @@ var GhostlyNode = class GhostlyNode {
39568
39816
  const existing = [...this.links.values()].find((l) => l.stored.seedB64 === params.seedB64);
39569
39817
  if (existing) {
39570
39818
  if (existing.stored.profile !== params.profile) throw new Error("Invitation profile does not match the stored link");
39819
+ if (this.deferredChats.delete(existing.stored.id) && this.networkOn) this.startLink(existing.stored.id);
39571
39820
  return { linkId: await this.existingLink(existing.stored.id) };
39572
39821
  }
39573
39822
  this.refuseOwnInvite(params);
@@ -40040,6 +40289,7 @@ var GhostlyNode = class GhostlyNode {
40040
40289
  */
40041
40290
  groupMembersChanged(groupId) {
40042
40291
  this.quietOutsideEdges(groupId);
40292
+ this.groupEdits.membersChanged(groupId);
40043
40293
  const holders = this.settings.wakeHeldBy?.[groupId];
40044
40294
  if (!holders?.length) return;
40045
40295
  const members = this.membership(groupId)?.members;
@@ -40053,6 +40303,7 @@ var GhostlyNode = class GhostlyNode {
40053
40303
  */
40054
40304
  groupHistoryGone(groupId) {
40055
40305
  const linkId = `group:${groupId}`;
40306
+ this.groupEdits.forget(groupId);
40056
40307
  this.newestAt.delete(linkId);
40057
40308
  this.lateAt.delete(linkId);
40058
40309
  for (const clock of this.clockLeads.keys()) if (clock.startsWith(`${linkId} `)) this.clockLeads.delete(clock);
@@ -44176,21 +44427,25 @@ var GhostlyNode = class GhostlyNode {
44176
44427
  await db.putSettings(this.settings);
44177
44428
  this.hold.storageChanged();
44178
44429
  }
44179
- if (wasOnline && !this.networkOn) await Promise.allSettled([...this.links.values()].map(async (live) => {
44180
- live.carried?.stop();
44181
- await live.link?.stop(true);
44182
- await live.caps?.stop();
44183
- live.caps = void 0;
44184
- live.link = null;
44185
- live.status = "offline";
44186
- live.dataLink = "idle";
44187
- }));
44188
- else if (!wasOnline && this.networkOn && await this.turnBeforeOnline()) {
44430
+ if (wasOnline && !this.networkOn) {
44431
+ this.enrollment?.cancel("offline").catch(() => {});
44432
+ await Promise.allSettled([...this.links.values()].map(async (live) => {
44433
+ live.carried?.stop();
44434
+ await live.link?.stop(true);
44435
+ await live.caps?.stop();
44436
+ live.caps = void 0;
44437
+ live.link = null;
44438
+ live.status = "offline";
44439
+ live.dataLink = "idle";
44440
+ }));
44441
+ await this.stopDeviceSet();
44442
+ } else if (!wasOnline && this.networkOn && await this.turnBeforeOnline()) {
44189
44443
  await this.startLinks([...this.links.keys()]);
44190
44444
  this.hold.start();
44191
44445
  this.startGroupEntries();
44192
44446
  this.prepareSpare(STARTUP_QUIET_MS);
44193
44447
  this.did.publishNow().catch(() => {});
44448
+ if (!this.options.singleDevice && knownDeviceGate()?.state === "active") this.startDeviceSet({ justRead: true }).catch(() => {});
44194
44449
  } else if (wasOnline && this.networkOn && relayOnlyChanged) await this.restartLinksForRelayOnly();
44195
44450
  if (wasOnline && !this.networkOn) this.stopGroupEntries();
44196
44451
  if (wasOnline && !this.networkOn) await this.hold.stop();
@@ -44332,7 +44587,7 @@ var GhostlyNode = class GhostlyNode {
44332
44587
  * turn read made a moment before (the read at start, or limited mode's), which counts while it is fresh.
44333
44588
  */
44334
44589
  async startDeviceSet({ justRead = false } = {}) {
44335
- if (this.shuttingDown) return;
44590
+ if (this.shuttingDown || !this.networkOn) return;
44336
44591
  const own = await readDeviceRecord(databaseName()).catch(() => null);
44337
44592
  this.ownDeviceKey = own?.ownSlot !== void 0 ? own.deviceSet[own.ownSlot]?.key ?? null : null;
44338
44593
  if (!this.deviceLinks) {
@@ -44379,6 +44634,21 @@ var GhostlyNode = class GhostlyNode {
44379
44634
  this.watchTombstones();
44380
44635
  await this.rotateIfDue().catch(() => {});
44381
44636
  }
44637
+ /**
44638
+ * The network turned off: the links to the other devices stop as every other link does, and ask nothing more of a
44639
+ * relay or the DHT. `startDeviceSet` makes them again when it comes back, with the handoff (which resumes a stopped move).
44640
+ */
44641
+ async stopDeviceSet() {
44642
+ const links = this.deviceLinks;
44643
+ if (!links) return;
44644
+ this.deviceLinks = null;
44645
+ this.handoffGiver = null;
44646
+ if (this.activeTurnTimer) clearTimeout(this.activeTurnTimer);
44647
+ this.activeTurnTimer = null;
44648
+ this.sentTokens.clear();
44649
+ this.renewAsked.clear();
44650
+ await links.stop().catch(() => {});
44651
+ }
44382
44652
  /** How often a running active device reads the turn (WISP 06 § When a device checks: every 10 minutes, with jitter). */
44383
44653
  static ACTIVE_TURN_EVERY_MS = 6e5;
44384
44654
  static ACTIVE_TURN_JITTER_MS = 6e4;
@@ -45480,7 +45750,7 @@ var GhostlyNode = class GhostlyNode {
45480
45750
  }
45481
45751
  startLink(linkId) {
45482
45752
  const live = this.links.get(linkId);
45483
- if (!live || live.link) return;
45753
+ if (!live || live.link || this.deferredChats.has(linkId)) return;
45484
45754
  const { stored } = live;
45485
45755
  if (stored.group) return this.startEdge(linkId);
45486
45756
  if (stored.profile) live.pairing = { status: "connecting" };
@@ -46017,7 +46287,7 @@ var GhostlyNode = class GhostlyNode {
46017
46287
  nativeFactoriesFor(relayOnly) {
46018
46288
  const relay = relayOnly || this.relaysHyperdhtNatively ? this.hyperdhtRelay : "";
46019
46289
  return {
46020
- ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-CZLnOc4e.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
46290
+ ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-CI2ISE-g.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
46021
46291
  ...relayOnly ? {} : this.options.nativeTransports,
46022
46292
  ...this.ownIrohRelays && !relayOnly ? { "iroh/1": (seedB64) => this.options.nativeTransports["iroh/1"](seedB64, this.settings.irohRelays?.length ? { relays: [...this.settings.irohRelays] } : {}) } : {},
46023
46293
  ...this.options.irohWeb ? { "iroh/1": (seedB64) => createIrohWebEndpoint(seedB64, { relays: this.irohRelays }) } : {}
@@ -46034,7 +46304,7 @@ var GhostlyNode = class GhostlyNode {
46034
46304
  /** New Iroh relays: idle endpoints move now; one carrying a chat keeps its relay until that session ends. */
46035
46305
  async rehomeIroh() {
46036
46306
  if (!this.options.irohWeb && !this.ownIrohRelays) return;
46037
- this.deviceLinks?.nativeChanged();
46307
+ this.deviceLinks?.nativeChanged(["iroh/1"]);
46038
46308
  for (const [linkId, live] of this.links) {
46039
46309
  const link = live.link;
46040
46310
  if (!link?.availableTransports.includes("iroh/1") || !link.canReleaseEndpoint("iroh/1")) continue;
@@ -46078,7 +46348,7 @@ var GhostlyNode = class GhostlyNode {
46078
46348
  /** A new relay (or none): chats give up their endpoints on the old one, as soon as none of them carries a session. */
46079
46349
  async relayChanged() {
46080
46350
  if (!this.relaysHyperdht) return;
46081
- this.deviceLinks?.nativeChanged();
46351
+ this.deviceLinks?.nativeChanged(["hyperdht/1"]);
46082
46352
  for (const [linkId, live] of this.links) {
46083
46353
  const link = live.link;
46084
46354
  if (!link?.availableTransports.includes("hyperdht/1")) {
@@ -46386,7 +46656,7 @@ var GhostlyNode = class GhostlyNode {
46386
46656
  }
46387
46657
  /**
46388
46658
  * The order saved chats start in, which is the order they take native listeners in (`NATIVE_SLOTS` per transport):
46389
- * the 1:1 chats written in, or live, most recently first; group links keep their places. In the order they were
46659
+ * the 1:1 chats written in, or live, most recently first, then the group links in the order given. In the order they were
46390
46660
  * stored, an app with more paired chats than slots left a chat that was live a moment before with no listener, and a
46391
46661
  * contact with no WebRTC (the Linux Desktop) never reached it again (Omarchy, 2026-09-30: "On DHT · retrying live" for
46392
46662
  * minutes after both apps restarted). Not "live when this app last ran" first: a chat that heard its contact leave as
@@ -46395,6 +46665,10 @@ var GhostlyNode = class GhostlyNode {
46395
46665
  * On an app with WebRTC, the chats whose contact has none (its capability record lists no `webrtc/1`: a Linux Desktop,
46396
46666
  * a CLI with WebRTC off) come first, each class in that order: they reach this app over a native transport or not
46397
46667
  * live at all, while a contact with WebRTC still has it when no listener is left here.
46668
+ *
46669
+ * The chats before every group link, whatever order they come in: leaving limited mode, the network back on and
46670
+ * "Hide my IP" switched start the links in the engine's order, every private group's edges first, and with 10 mesh
46671
+ * groups of 32 the chat about to be opened waited for 310 edges to derive their keys and seal their records.
46398
46672
  */
46399
46673
  nativeStartOrder(linkIds) {
46400
46674
  const isChat = (id) => {
@@ -46418,8 +46692,7 @@ var GhostlyNode = class GhostlyNode {
46418
46692
  place,
46419
46693
  ...rank.get(id)
46420
46694
  }));
46421
- let next = 0;
46422
- return linkIds.map((id) => rank.has(id) ? chats[next++] : id);
46695
+ return [...chats, ...linkIds.filter((id) => !rank.has(id))];
46423
46696
  }
46424
46697
  /**
46425
46698
  * A chat started as "live when this app last ran" (it resumes, and knocks): if this run is not live in it within
@@ -47103,4 +47376,4 @@ function signalKind(signal) {
47103
47376
  //#endregion
47104
47377
  export { EngineServer };
47105
47378
 
47106
- //# sourceMappingURL=server-CH142eWc.js.map
47379
+ //# sourceMappingURL=server-C3tJZFnv.js.map