@ghostlytools/cli 1.7.3 → 1.7.4

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 (97) hide show
  1. package/README.md +18 -13
  2. package/SKILL.md +5 -3
  3. package/dist/assets/{api-B42F9ytB.js → api-Chhvpwok.js} +2 -2
  4. package/dist/assets/{api-tf-wAAnB.js → api-D3i2hwy0.js} +142 -84
  5. package/dist/assets/api-D3i2hwy0.js.map +1 -0
  6. package/dist/assets/{apiKit-DJb9hulp.js → apiKit-BtsHrnoo.js} +30 -7
  7. package/dist/assets/apiKit-BtsHrnoo.js.map +1 -0
  8. package/dist/assets/{apps-BfoDISRg.js → apps-BFJTqvAt.js} +1 -1
  9. package/dist/assets/{apps-DIrWmLgL.js → apps-BHl97rHs.js} +10 -8
  10. package/dist/assets/apps-BHl97rHs.js.map +1 -0
  11. package/dist/assets/{arkade-CJAhhgPQ.js → arkade-BFE8KkEE.js} +2 -2
  12. package/dist/assets/{arkade-CJAhhgPQ.js.map → arkade-BFE8KkEE.js.map} +1 -1
  13. package/dist/assets/{backup-BkUeeduy.js → backup-Bbsr6nDi.js} +1 -1
  14. package/dist/assets/{backup-Bko-AAm0.js → backup-CxACdtQX.js} +7 -7
  15. package/dist/assets/{backup-Bko-AAm0.js.map → backup-CxACdtQX.js.map} +1 -1
  16. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -1
  17. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
  18. package/dist/assets/{blobFiles-Bckz9fjp.js → blobFiles-DOQDRdDI.js} +3 -3
  19. package/dist/assets/{blobFiles-Bckz9fjp.js.map → blobFiles-DOQDRdDI.js.map} +1 -1
  20. package/dist/assets/{buttons-DeA6Yddq.js → buttons-CieBtXEO.js} +4 -4
  21. package/dist/assets/{buttons-DeA6Yddq.js.map → buttons-CieBtXEO.js.map} +1 -1
  22. package/dist/assets/buttons-YtAj3R_E.js +2 -0
  23. package/dist/assets/{daemonProof-Bp9lJDxf.js → daemonProof-QmtwDj-N.js} +2 -2
  24. package/dist/assets/{daemonProof-Bp9lJDxf.js.map → daemonProof-QmtwDj-N.js.map} +1 -1
  25. package/dist/assets/{envelope-Cz5fc7BM.js → envelope-DYiGwzq_.js} +2 -2
  26. package/dist/assets/{envelope-Cz5fc7BM.js.map → envelope-DYiGwzq_.js.map} +1 -1
  27. package/dist/assets/{errors-mnjSQlbX.js → errors-QUGP-jIF.js} +2 -2
  28. package/dist/assets/errors-QUGP-jIF.js.map +1 -0
  29. package/dist/assets/{fileBytes-OolN5cSY.js → fileBytes-BPDKufla.js} +1 -1
  30. package/dist/assets/{fileBytes-BD0v3rRG.js → fileBytes-DNgrRL0R.js} +3 -3
  31. package/dist/assets/{fileBytes-BD0v3rRG.js.map → fileBytes-DNgrRL0R.js.map} +1 -1
  32. package/dist/assets/{fileBytes-_fd-2JRY.js → fileBytes-Q3ehcEr8.js} +2 -2
  33. package/dist/assets/{fileBytes-_fd-2JRY.js.map → fileBytes-Q3ehcEr8.js.map} +1 -1
  34. package/dist/assets/fileBytesIdb-DZcESfTt.js +2 -0
  35. package/dist/assets/{fileBytesIdb-NtA8r9EM.js → fileBytesIdb-Dm1EyEbT.js} +3 -3
  36. package/dist/assets/{fileBytesIdb-NtA8r9EM.js.map → fileBytesIdb-Dm1EyEbT.js.map} +1 -1
  37. package/dist/assets/{fileBytesOpfs-B8fJwkwM.js → fileBytesOpfs-ZGD21c4Q.js} +3 -3
  38. package/dist/assets/{fileBytesOpfs-B8fJwkwM.js.map → fileBytesOpfs-ZGD21c4Q.js.map} +1 -1
  39. package/dist/assets/{groupFiles-BlZRBWpt.js → groupFiles-CBJIEvCE.js} +22 -10
  40. package/dist/assets/groupFiles-CBJIEvCE.js.map +1 -0
  41. package/dist/assets/{host-BX0DmKW6.js → host-Va-r_KJz.js} +54 -16
  42. package/dist/assets/host-Va-r_KJz.js.map +1 -0
  43. package/dist/assets/{hyperdhtRelay-DitYDnXx.js → hyperdhtRelay-B2uK9tJv.js} +2 -2
  44. package/dist/assets/{hyperdhtRelay-DitYDnXx.js.map → hyperdhtRelay-B2uK9tJv.js.map} +1 -1
  45. package/dist/assets/{idb-BlH8-O3R.js → idb-BkOJES5_.js} +5 -3
  46. package/dist/assets/idb-BkOJES5_.js.map +1 -0
  47. package/dist/assets/{irohWeb-R3bcd34h.js → irohWeb-DxeEgQ-W.js} +2 -2
  48. package/dist/assets/{irohWeb-R3bcd34h.js.map → irohWeb-DxeEgQ-W.js.map} +1 -1
  49. package/dist/assets/{main-6QOSvQ8b.js → main-BX4oPWCJ.js} +362 -110
  50. package/dist/assets/main-BX4oPWCJ.js.map +1 -0
  51. package/dist/assets/{mainline-BfwezHWi.js → mainline-IfWQOB-J.js} +39 -12
  52. package/dist/assets/mainline-IfWQOB-J.js.map +1 -0
  53. package/dist/assets/{networkReason-Ba9415nn.js → networkReason-N2vAaoth.js} +3 -3
  54. package/dist/assets/{networkReason-Ba9415nn.js.map → networkReason-N2vAaoth.js.map} +1 -1
  55. package/dist/assets/{nwc-ovXSN2M2.js → nwc-CzyCtNK2.js} +3 -3
  56. package/dist/assets/{nwc-ovXSN2M2.js.map → nwc-CzyCtNK2.js.map} +1 -1
  57. package/dist/assets/{nwcProvider-BzZbfFP3.js → nwcProvider-DjWmEn3j.js} +2 -2
  58. package/dist/assets/{nwcProvider-BzZbfFP3.js.map → nwcProvider-DjWmEn3j.js.map} +1 -1
  59. package/dist/assets/{profiles-C6XWqre5.js → profiles-DcCeOi7J.js} +104 -10
  60. package/dist/assets/profiles-DcCeOi7J.js.map +1 -0
  61. package/dist/assets/{registry-CFtlhWCI.js → registry-BmS02J5h.js} +1 -1
  62. package/dist/assets/{registry-B0Uv9yL6.js → registry-CeW8XEQc.js} +45 -14
  63. package/dist/assets/registry-CeW8XEQc.js.map +1 -0
  64. package/dist/assets/{resolve-BzFG4WDU.js → resolve-BvHkAhDH.js} +66 -29
  65. package/dist/assets/resolve-BvHkAhDH.js.map +1 -0
  66. package/dist/assets/{restoredRows-Fv-MuY45.js → restoredRows-mTTp3XNs.js} +2 -2
  67. package/dist/assets/{restoredRows-Fv-MuY45.js.map → restoredRows-mTTp3XNs.js.map} +1 -1
  68. package/dist/assets/{server-BGCuHbmQ.js → server-BUcJo4vz.js} +779 -239
  69. package/dist/assets/server-BUcJo4vz.js.map +1 -0
  70. package/dist/assets/{src-DWw2hUE5.js → src-BB5-5P3s.js} +540 -159
  71. package/dist/assets/src-BB5-5P3s.js.map +1 -0
  72. package/dist/assets/{translate-DObb-1tq.js → translate-2WyaRVCr.js} +11 -9
  73. package/dist/assets/translate-2WyaRVCr.js.map +1 -0
  74. package/dist/assets/{usdt-Bkva90Vo.js → usdt-BLazHiaP.js} +3 -3
  75. package/dist/assets/{usdt-Bkva90Vo.js.map → usdt-BLazHiaP.js.map} +1 -1
  76. package/dist/assets/{words-odSAoasK.js → words-BaumxjXe.js} +3 -3
  77. package/dist/assets/words-BaumxjXe.js.map +1 -0
  78. package/dist/ghostly.mjs +1 -1
  79. package/package.json +1 -1
  80. package/dist/assets/api-tf-wAAnB.js.map +0 -1
  81. package/dist/assets/apiKit-DJb9hulp.js.map +0 -1
  82. package/dist/assets/apps-DIrWmLgL.js.map +0 -1
  83. package/dist/assets/buttons-Be7u0V5g.js +0 -2
  84. package/dist/assets/errors-mnjSQlbX.js.map +0 -1
  85. package/dist/assets/fileBytesIdb-CsSQcSxD.js +0 -2
  86. package/dist/assets/groupFiles-BlZRBWpt.js.map +0 -1
  87. package/dist/assets/host-BX0DmKW6.js.map +0 -1
  88. package/dist/assets/idb-BlH8-O3R.js.map +0 -1
  89. package/dist/assets/main-6QOSvQ8b.js.map +0 -1
  90. package/dist/assets/mainline-BfwezHWi.js.map +0 -1
  91. package/dist/assets/profiles-C6XWqre5.js.map +0 -1
  92. package/dist/assets/registry-B0Uv9yL6.js.map +0 -1
  93. package/dist/assets/resolve-BzFG4WDU.js.map +0 -1
  94. package/dist/assets/server-BGCuHbmQ.js.map +0 -1
  95. package/dist/assets/src-DWw2hUE5.js.map +0 -1
  96. package/dist/assets/translate-DObb-1tq.js.map +0 -1
  97. package/dist/assets/words-odSAoasK.js.map +0 -1
@@ -1,16 +1,16 @@
1
1
  import { n as traceJoin } from "./joinTrace-CjRDFy85.js";
2
- import { $i as automaticTransport, $l as traceLink, $o as HANDOFF_HAVE, $r as vapidKeysMatch, $s as enrollHelloFrame, A as knockRecords, Aa as GROUP_REACTION_FRAME, Ac as appDigest, Al as classifyTurnRead, An as findEndpoint, Ao as formatLocalTarget, As as readHandoffDone, B as GROUP_READ_NOTE, Ba as pairedReplyAuthor, Bc as APP_STATEMENT_LIMITS, Bl as turnKeys, Bn as EngineError, Br as mayPin, Bs as setAckFrame, C as decodeCommunityLink, Ca as REMOVED_TEXT, Cc as readLinkRecord, Cl as devicePingFrame, Cr as rankHubs, Cs as handoffReleaseFrame, Cu as utf8Decode, D as encodeGroupEntryLink, Da as forwardedAgain, Dc as APP_BUNDLE_MAGIC, Dn as ENDPOINT, Do as WATCH_PEER_MS, Dr as shouldBeHub, Ds as newHandoffId, E as decodeGroupEntryLink, Ea as parseLinkPreview, Ec as APP_BUNDLE_LIMITS, El as webCryptoSigner, En as decodeBolt11, Eo as RELAY_POLL_INTERVALS, Er as readLobby, Es as handoffVersions, F as groupWakeFrame, Fa as reactionEmoji, Fc as pacer, Fi as dialDescriptors, Fl as nextTurnPosition, Fn as INVITE_TAKEN, Fo as encodeControl, Fr as TypingSender, Fs as readHandoffVerified, G as GROUP_EDIT_TEXT_BYTES, Gc as isAppKey, Gr as WAKE_CALL_INTERVAL_MS, Gt as encodeDidDhtPacket, H as frameBytes, Ha as replySnippet, Hc as appRef, Hi as emptyIdentityLedger, Hl as turnStatedVerifier, Hn as engineText, Ho as contactRtcConfig, Hr as pinIsNewer, Hs as signTombstone, Ht as didDhtDocument, I as groupWakes, Ia as reactionIsNewer, Il as readTurnPacket, In as LIVENESS_PING_MS, Is as sealHandoffPiece, J as mentionsMember, Ji as lastSharedWithMe, Jo as LEGACY_SERVICES, Jr as newWakeToken, Js as enrollCancelFrame, Jt as ETHEREUM_USDT, K as carryMentions, Kc as isAppRef, Ki as receivedIdentityStatus, Ko as emptyLinkRecords, Kr as WakeLimiter, L as parseGroupWakeFrame, La as readReaction, Lc as readAppBundleAsync, Ll as signTurnPacket, Ln as PAIRED_FRAME_TOO_LARGE, Lo as RTC_CONFIG, Lr as typingActivity, M as readKnocks, Ma as ReactionWindow, Mi as CapsExchange, Ml as TURN_LAST_SEQUENCE, Mn as parseCashuRequestPayload, Mo as webLocalFetch, Mr as transferStalled, Ms as readHandoffHello, Na as nextReactionNumber, Ni as DHT_TEXT_CAPABILITY, Nl as TURN_MAX, Nn as parseFedimintRequestPayload, No as LIMITS, Ns as readHandoffPake, O as entryParams, Oa as readForwarded, Oc as APP_ICON_PATH, Ol as TURN_RAISE_READ_TIMEOUT_MS, On as cashuRequestPayload, Oo as presenceSeenAt, Or as ChatFiles, Os as readHandoffAck, P as GroupWakeLimiter, Pa as queueReaction, Pc as isAppUrl, Pi as capsDescriptors, Pl as firstDeviceSetSecret, Pn as GhostLink, Po as decodeControl, Ps as readHandoffTurnFrame, Qc as parseImageMeta, Qi as TRANSPORTS, Qo as HANDOFF_DONE, Qr as checkPushEndpoint, Qs as enrollGrantFrame, Qt as SEPOLIA_TEST_USDT, R as GROUP_LIMITS, Ra as validReactionNumber, Rc as sha256Paced, Rl as signTurnRelease, Rn as pairedMessageFits, S as communityHasFrame, Sa as MAX_REMOVAL_NUMBER, Sc as readKnockSlot, Sl as deviceLinkPairing, So as DirectPathWatch, Sr as pickHubs, Ss as handoffPakeFrame, Su as toZ32, Ta as dhtEditId, Tc as seenEntry, Tl as seedSigner, Tr as readBeaconHead, Ts as handoffStreamKey, Ua as BUTTON_ID, Ul as turnVerifierMark, Un as parseEngineError, Ur as pinNumberHolds, Us as verifySetUpdate, Ut as didDhtFromPublicKey, V as GroupSession, Va as readReply, Vc as appFingerprint, Vl as turnName, Vn as engineError, Vr as nextPinNumber, Vs as setUpdateFrame, Wc as isAppHash, Wl as DEFAULT_RELAYS, Wn as GROUP_FILE_LIMITS, Wo as parseCallSignal, Wr as readPin, Wt as encodeDidDhtDeactivated, Xi as emptyProofLedger, Xl as currentRelays, Xo as HANDOFF_ACK, Xr as relayRequest, Xs as enrollDigits, Xt as ONCHAIN_PROVIDER, Y as groupName, Yi as PeerProofs, Yn as groupFileFallback, Yo as serviceIdFromName, Yr as parseWakeFrame, Ys as enrollCancelReason, Yt as EVM_TEST_CHAINS, Za as STATUS_CARD_LIMITS, Zi as validExternalKey, Zl as normalizeRelayUrl, Zn as readGroupFileMeta, Zo as HANDOFF_CANCEL, Zr as wakeRequest, Zs as enrollDoneFrame, Zt as PaymentPreflightError, _ as openGroupTyping, _c as knockSlotRecords, _i as readManifest, _l as ENROLL_CAPABILITY, _o as parseGroupCommit, _r as lobbyKeys, _s as handoffDigest, _u as bytesEqual, a as appStoreDecision, aa as DHT_FILE_CAPABILITY, ac as endedRequests, ai as APPS_CAPABILITY, al as readContactLink, an as assertWholeSats, as as HANDOFF_TIMINGS, au as createRelayPayload, b as CommunitySession, ba as EDIT_BUFFER_MS, bc as mergeContactKnocks, bl as deviceEchoNonce, bo as verifyCommitSignature, br as mergeLobby, bs as handoffManifestFrames, bu as randomBytes, c as planAppUpdate, ca as sanitizeFileName, cc as planKnocks, ci as STATUS_CARD_CAPABILITY, cl as readDeviceInvite, cn as walletNetworkOf, co as claimedTime, cr as MESH_HUBS, cs as filePartName, dc as turnOff, di as HOLD_DATED_BACK_MS, dl as decodeInviteCode, dn as sparkAddressKind, do as shownTime, dr as pickMeshHubs, ds as handoffAttemptSucceeded, du as identityFromSeedB64, ec as enrollProofFrame, ei as APP_RANGE_LIMITS, el as canonicalJson, en as TEST_USDT_FAUCET_AMOUNT, es as HANDOFF_HELLO, eu as budgetRetryMs, f as readAppStoreSteps, fc as ContactRequestError, fi as HOLD_LIMITS, fl as encodeInviteCode, fn as sparkInvoiceDetails, fo as GROUP_ADMIN_OFF_ERROR, fr as COMMUNITY_TOPOLOGY, fs as handoffBusyFrame, fu as publicKeyFromZ32, g as groupTypingEpoch, ga as parseVoiceMeta, gc as knockSlotOf, gi as newMailbox, gl as DEVICES_CAPABILITY, go as commitHash, gr as freshHubs, gs as handoffDataFrame, gt as normalizeAtprotoHandle, gu as sanitizeDisplayText, h as GroupTypingBoard, ha as fileMessageText, hc as knockSlotIdentity, hi as isHoldUrl, hn as isPubkyKey, ho as MEMBER_KEY, hr as doorHubs, hs as handoffContextProof, ht as isAtprotoDid, hu as sanitizeAvatar, i as appRevocationFor, ia as peekDhtMailbox, ic as clearMissed, ii as isAppVersion, il as encodeContactLink, in as assertTokenUnits, io as sameButtonText, is as HANDOFF_REQUEST, j as mergeKnocks, ja as REACTION_LIMITS, jc as appViewOf, jl as turnPutSummary, jn as isFederationId, jo as parseLocalTarget, jr as transferEnded, js as readHandoffHave, k as knockIdentity, ka as COMMUNITY_REACTION_FRAME, kl as TURN_SETTLE_MS, kn as fedimintRequestPayload, ko as GhostlyHttpError, kr as FILE_LIMITS, ks as readHandoffCancel, l as APP_STORE_LIMITS, la as sanitizeMime, lc as settleRequest, li as UPGRADE_CAPABILITY, ll as OwnInviteError, ln as SPARK_NETWORKS, lo as heardTime, lr as mayBeHub, ls as handoffAttemptAllowed, lu as createIdentity, mc as contactDay, mi as HoldRefusedError, ml as inviteOwnership, mr as beaconRecords, ms as handoffContext, n as readX401SdJwtVc, nc as readEnrollHello, nl as readCanonicalJson, nn as WALLET_NETWORKS, ns as HANDOFF_PAKE, nu as withRequestOptions, o as appUpdateDecision, oa as dhtFileId, oc as inboxRecord, oi as BUTTONS_CAPABILITY, ol as createDeviceInvite, on as formatPaymentAmount, oo as statusCardText, or as groupSignalFrame, os as HANDOFF_VERIFIED, pc as REQUEST_LIFETIME_MS, pi as HoldKeys, pl as inviteLink, pn as isBitcoinAddress, po as GROUP_MEMBER_CAP, pr as beaconKeys, ps as handoffCancelFrame, pu as verify, q as parseCommunityEdit, qc as readAppRevocation, ql as RelayTransport, qo as HTTP_SERVICE_PROTO, qr as deviceWakeRequest, qt as signDidDhtPacket, r as sameX401HolderJwk, ra as DHT_MESSAGE_TTL, rc as verifyEnrollProof, ri as chatAppId, rl as createContactLink, rn as arkAddressPrefix, ro as checkStatusCard, rs as HANDOFF_PIECE_BYTES, ru as PacketTooLargeError, s as checkAppBeforeRun, sa as formatFileSize, sc as newInbox, si as EDIT_CAPABILITY, sl as deviceInviteJoinerParams, sn as validatePaymentTarget, so as arrivalKey, sr as readGroupSignal, ss as NO_ATTEMPTS, t as newX401HolderKey, tc as readEnrollGrant, ti as isServeId, tn as USDT_PUBLIC_RPC, tr as CarriedTransport, ts as HANDOFF_OFFER, tu as isDiscoveryBudgetError, uc as takeRequest, ui as HOLD_CAPABILITY, ul as createChatInvite, un as SPARK_PROVIDER, uo as receivedTimestamp, ur as meshHubs, us as handoffAttemptFailed, uu as identityFromSeed, v as sealGroupTyping, vc as linkRecords, vl as HANDOFF_CAPABILITY, vo as rosterAdmin, vr as lobbyRecords, vs as handoffEphemeral, vu as fromBase64Url, w as encodeCommunityLink, wa as RateWindow, wc as requestRecords, wl as newDeviceSetSecret, wo as DHT_POLL_INTERVALS, wr as readBeacon, ws as handoffRetryAfter, wu as utf8Encode, x as GROUP_READ_NOTE_COMMUNITY, xa as EDIT_RATE_WINDOW_MS, xc as openRequest, xl as deviceKeyZ32, xo as edgeParams, xr as newerHead, xs as handoffOfferFrame, xu as toBase64Url, y as COMMUNITY_LIMITS, ya as parseVideoMeta, yc as makeStampPaced, yl as deviceEchoFrame, yo as rosterHas, yr as mergeBeacon, ys as handoffHelloFrame, za as wireReaction, zl as turnInstance, zn as pairedMessageFrame, zr as PIN_LIMITS, zs as readSetUpdate } from "./src-DWw2hUE5.js";
2
+ import { $i as TRANSPORTS, $l as currentRelays, $o as HANDOFF_ACK, $r as checkPushEndpoint, $s as enrollDigits, $t as SEPOLIA_TEST_USDT, A as knockIdentity, Aa as forwardedAgain, Ac as APP_BUNDLE_MAGIC, An as fedimintRequestPayload, Ao as WATCH_PEER_MS, Ar as FILE_LIMITS, As as newHandoffId, Ba as readReaction, Bc as readAppBundleAsync, Bl as signTurnPacket, Bn as pairedMessageFrame, Bo as RTC_CONFIG, Br as PIN_LIMITS, C as communityHasFrame, Ca as MAX_REMOVAL_NUMBER, Cc as mergeContactKnocks, Cl as deviceEchoNonce, Co as verifyCommitSignature, Cr as pickHubs, Cs as handoffManifestFrames, Cu as randomBytes, D as decodeGroupEntryLink, Dc as requestRecords, Dl as newDeviceSetSecret, Dn as decodeBolt11, Do as DHT_POLL_INTERVALS, Dr as readLobby, Ds as handoffRetryAfter, Du as utf8Encode, Ea as dhtEditId, Ec as readLinkRecord, El as devicePingFrame, Er as readBeaconHead, Es as handoffReleaseFrame, Eu as utf8Decode, F as GroupWakeLimiter, Fa as ReactionWindow, Fi as capsDescriptors, Fl as TURN_LAST_SEQUENCE, Fn as GhostLink, Fo as webLocalFetch, Fs as readHandoffHello, Ga as replySnippet, Gc as appRef, Gl as turnStatedVerifier, Gn as GROUP_FILE_LIMITS, Go as contactRtcConfig, Gr as readPin, Gs as signTombstone, Gt as encodeDidDhtDeactivated, H as GroupSession, Ha as wireReaction, Hl as turnInstance, Hn as engineError, Hr as nextPinNumber, Hs as readSetUpdate, I as groupWakeFrame, Ia as nextReactionNumber, Ii as dialDescriptors, Il as TURN_MAX, In as INVITE_TAKEN, Io as LIMITS, Ir as TypingSender, Is as readHandoffPake, J as parseCommunityEdit, Jc as isAppKey, Jr as deviceWakeRequest, Jt as signDidDhtPacket, K as GROUP_EDIT_TEXT_BYTES, Ka as BUTTON_ID, Kl as turnVerifierMark, Kr as WAKE_CALL_INTERVAL_MS, Ks as verifySetUpdate, Kt as encodeDidDhtPacket, L as groupWakes, La as queueReaction, Lc as isAppUrl, Ll as firstDeviceSetSecret, Ln as LIVENESS_PING_MS, Lo as decodeControl, Ls as readHandoffTurnFrame, M as mergeKnocks, Ma as COMMUNITY_REACTION_FRAME, Ml as TURN_SETTLE_MS, Mn as isFederationId, Mo as GhostlyHttpError, Mr as transferEnded, Ms as readHandoffCancel, N as readKnocks, Na as GROUP_REACTION_FRAME, Nc as appDigest, Ni as CapsExchange, Nl as classifyTurnRead, Nn as parseCashuRequestPayload, No as formatLocalTarget, Nr as transferStalled, Ns as readHandoffDone, O as encodeGroupEntryLink, Oc as seenEntry, Ol as seedSigner, On as ENDPOINT, Or as shouldBeHub, Os as handoffStreamKey, Pa as REACTION_LIMITS, Pc as appViewOf, Pi as DHT_TEXT_CAPABILITY, Pl as turnPutSummary, Pn as parseFedimintRequestPayload, Po as parseLocalTarget, Ps as readHandoffHave, Qi as validExternalKey, Qn as readGroupFileMeta, Qo as serviceIdFromName, Qr as wakeRequest, Qs as enrollCancelReason, Qt as PaymentPreflightError, R as parseGroupWakeFrame, Ra as reactionEmoji, Rc as pacer, Rl as nextTurnPosition, Rn as PAIRED_FRAME_TOO_LARGE, Ro as encodeControl, Rr as typingActivity, Rs as readHandoffVerified, S as GROUP_READ_NOTE_COMMUNITY, Sa as EDIT_RATE_WINDOW_MS, Sc as makeStampPaced, Sl as deviceEchoFrame, So as rosterHas, Sr as newerHead, Ss as handoffHelloFrame, T as encodeCommunityLink, Ta as RateWindow, Tc as readKnockSlot, Tl as deviceLinkPairing, To as DirectPathWatch, Tr as readBeacon, Ts as handoffPakeFrame, Tu as toZ32, U as frameBytes, Ua as pairedReplyAuthor, Uc as APP_STATEMENT_LIMITS, Ui as emptyIdentityLedger, Ul as turnKeys, Un as engineText, Ur as pinIsNewer, Us as setAckFrame, Ut as didDhtDocument, V as GROUP_READ_NOTE, Va as validReactionNumber, Vc as sha256Paced, Vl as signTurnRelease, Vn as EngineError, Vr as mayPin, Wa as readReply, Wc as appFingerprint, Wl as turnName, Wn as parseEngineError, Wr as pinNumberHolds, Ws as setUpdateFrame, Wt as didDhtFromPublicKey, X as groupName, Xc as readAppRevocation, Xi as PeerProofs, Xl as RelayTransport, Xn as groupFileFallback, Xo as HTTP_SERVICE_PROTO, Xr as parseWakeFrame, Xt as EVM_TEST_CHAINS, Y as mentionsMember, Yc as isAppRef, Yi as lastSharedWithMe, Yo as emptyLinkRecords, Yr as newWakeToken, Yt as ETHEREUM_USDT, Zi as emptyProofLedger, Zo as LEGACY_SERVICES, Zr as relayRequest, Zs as enrollCancelFrame, Zt as ONCHAIN_PROVIDER, _ as groupTypingEpoch, _a as parseVoiceMeta, _c as contactDay, _i as newMailbox, _l as inviteOwnership, _r as freshHubs, _s as handoffContext, _t as normalizeAtprotoHandle, a as appRevocationFor, aa as peekDhtMailbox, ac as readEnrollHello, ai as isAppVersion, al as readCanonicalJson, an as assertTokenUnits, as as HANDOFF_PAKE, au as withRequestOptions, b as COMMUNITY_LIMITS, ba as parseVideoMeta, bc as knockSlotRecords, bl as ENROLL_CAPABILITY, bo as parseGroupCommit, br as mergeBeacon, bs as handoffDigest, bu as bytesEqual, c as checkAppBeforeRun, ca as formatFileSize, cc as endedRequests, ci as EDIT_CAPABILITY, cl as readContactLink, cn as validatePaymentTarget, cr as readGroupSignal, cs as HANDOFF_TIMINGS, cu as createRelayPayload, dc as planKnocks, di as HOLD_CAPABILITY, dl as readDeviceInvite, dn as SPARK_PROVIDER, do as claimedTime, dr as meshHubs, ds as filePartName, ea as automaticTransport, ec as enrollDoneFrame, ei as vapidKeysMatch, eo as STATUS_CARD_LIMITS, es as HANDOFF_CANCEL, eu as normalizeRelayUrl, fc as settleRequest, fi as HOLD_DATED_BACK_MS, fl as OwnInviteError, fn as sparkAddressKind, fo as heardTime, fr as pickMeshHubs, fs as handoffAttemptAllowed, fu as createIdentity, g as GroupTypingBoard, ga as fileMessageText, gc as REQUEST_LIFETIME_MS, gi as isHoldUrl, gl as inviteLink, gn as isPubkyKey, go as GROUP_MEMBER_CAP, gr as doorHubs, gs as handoffCancelFrame, gt as isAtprotoDid, gu as verify, hc as ContactRequestError, hi as HoldRefusedError, hl as encodeInviteCode, ho as GROUP_ADMIN_OFF_ERROR, hr as beaconRecords, hs as handoffBusyFrame, hu as publicKeyFromZ32, i as addedAppPermissions, ia as DHT_MESSAGE_TTL, ic as readEnrollGrant, ii as chatAppId, in as arkAddressPrefix, is as HANDOFF_OFFER, iu as isDiscoveryBudgetError, j as knockRecords, ja as readForwarded, jc as APP_ICON_PATH, jl as TURN_RAISE_READ_TIMEOUT_MS, jn as findEndpoint, jo as presenceSeenAt, js as readHandoffAck, k as entryParams, ka as parseLinkPreview, kc as APP_BUNDLE_LIMITS, kl as webCryptoSigner, kn as cashuRequestPayload, ko as RELAY_POLL_INTERVALS, kr as ChatFiles, ks as handoffVersions, l as planAppUpdate, la as sanitizeFileName, lc as inboxRecord, li as STATUS_CARD_CAPABILITY, ll as createDeviceInvite, ln as walletNetworkOf, lo as statusCardText, lr as MESH_HUBS, ls as HANDOFF_VERIFIED, mc as turnOff, mi as HoldKeys, ml as decodeInviteCode, mn as isBitcoinAddress, mo as shownTime, mr as beaconKeys, ms as handoffAttemptSucceeded, mu as identityFromSeedB64, n as readX401SdJwtVc, nc as enrollHelloFrame, ni as isServeId, nn as USDT_PUBLIC_RPC, nr as CarriedTransport, ns as HANDOFF_HAVE, nu as traceLink, o as appStoreDecision, oa as DHT_FILE_CAPABILITY, oc as verifyEnrollProof, oi as APPS_CAPABILITY, ol as createContactLink, on as assertWholeSats, oo as checkStatusCard, os as HANDOFF_PIECE_BYTES, ou as PacketTooLargeError, p as readAppStoreSteps, pc as takeRequest, pi as HOLD_LIMITS, pl as createChatInvite, pn as sparkInvoiceDetails, po as receivedTimestamp, pr as COMMUNITY_TOPOLOGY, ps as handoffAttemptFailed, pu as identityFromSeed, q as carryMentions, qc as isAppHash, qi as receivedIdentityStatus, ql as DEFAULT_RELAYS, qo as parseCallSignal, qr as WakeLimiter, r as sameX401HolderJwk, rc as enrollProofFrame, rl as canonicalJson, rn as WALLET_NETWORKS, rs as HANDOFF_HELLO, ru as budgetRetryMs, s as appUpdateDecision, sa as dhtFileId, sc as clearMissed, si as BUTTONS_CAPABILITY, sl as encodeContactLink, sn as formatPaymentAmount, so as sameButtonText, sr as groupSignalFrame, ss as HANDOFF_REQUEST, t as newX401HolderKey, tc as enrollGrantFrame, ti as APP_RANGE_LIMITS, tl as parseImageMeta, tn as TEST_USDT_FAUCET_AMOUNT, ts as HANDOFF_DONE, u as APP_STORE_LIMITS, ua as sanitizeMime, uc as newInbox, ui as UPGRADE_CAPABILITY, ul as deviceInviteJoinerParams, un as SPARK_NETWORKS, uo as arrivalKey, ur as mayBeHub, us as NO_ATTEMPTS, v as openGroupTyping, vc as knockSlotIdentity, vi as readManifest, vo as MEMBER_KEY, vr as lobbyKeys, vs as handoffContextProof, vu as sanitizeAvatar, w as decodeCommunityLink, wa as REMOVED_TEXT, wc as openRequest, wl as deviceKeyZ32, wo as edgeParams, wr as rankHubs, ws as handoffOfferFrame, wu as toBase64Url, x as CommunitySession, xa as EDIT_BUFFER_MS, xc as linkRecords, xl as HANDOFF_CAPABILITY, xo as rosterAdmin, xr as mergeLobby, xs as handoffEphemeral, xu as fromBase64Url, y as sealGroupTyping, yc as knockSlotOf, yl as DEVICES_CAPABILITY, yo as commitHash, yr as lobbyRecords, ys as handoffDataFrame, yu as sanitizeDisplayText, z as GROUP_LIMITS, za as reactionIsNewer, zl as readTurnPacket, zn as pairedMessageFits, zs as sealHandoffPiece } from "./src-BB5-5P3s.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-BzZbfFP3.js";
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-Ba9415nn.js";
8
- import { $ as WrongNetworkError, A as IdentityProofs, B as ProviderSources, C as FileAppender, D as streamStored, E as storedSize, F as LightningCards, G as breezDatabaseInUse, H as CASHU_MINT_SOURCE, I as cardsKey, J as iceServerProblem, K as breezDatabasesFor, L as isRecoveryPhrase, M as sealSecret, N as whenDataKeyDropped, P as CASHU_CARD, Q as ModeGate, R as normalizePhrase, S as WALLET_TYPES, T as removeStored, U as cashuMint, V as sourceKey, W as breezDatabase, X as relayOnlyProblem, Y as iceServerSetting, Z as ModeChanged, _ as crossNetwork, a as storedGroupFiles, at as setSingleWriterGate, b as walletInstances, c as receivedPairedReply, d as paymentAlias, et as networkLabel, f as paymentWireId, g as createTiming, h as createFailure, i as groupOfFile, it as setAwayWallets, j as openSecret, l as replyRef, m as assertConfirmedReal, n as groupFileId, nt as refuseAway, o as groupReply, p as WALLET_NAMES, q as dropBreezDatabase, r as groupFileText, rt as requireTurn, s as pairedWireReply, t as GroupFileDesk, tt as awayFrom, u as replyTo, v as paymentNetwork, w as readStored$1, y as paymentNetworksOf, z as lightningPaying } from "./groupFiles-BlZRBWpt.js";
9
- import { i as fedimintDatabase, n as createIrohWebEndpoint, o as loadFedimintSdk, r as irohRelayProblem, t as DEFAULT_IROH_RELAYS } from "./irohWeb-R3bcd34h.js";
5
+ import { t as nwc } from "./nwcProvider-DjWmEn3j.js";
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-BkOJES5_.js";
7
+ import { a as sealSeed, i as newDeviceKey, o as unsealSeed, r as intentRepository } from "./networkReason-N2vAaoth.js";
8
+ import { $ as WrongNetworkError, A as IdentityProofs, B as ProviderSources, C as FileAppender, D as streamStored, E as storedSize, F as LightningCards, G as breezDatabaseInUse, H as CASHU_MINT_SOURCE, I as cardsKey, J as iceServerProblem, K as breezDatabasesFor, L as isRecoveryPhrase, M as sealSecret, N as whenDataKeyDropped, P as CASHU_CARD, Q as ModeGate, R as normalizePhrase, S as WALLET_TYPES, T as removeStored, U as cashuMint, V as sourceKey, W as breezDatabase, X as relayOnlyProblem, Y as iceServerSetting, Z as ModeChanged, _ as crossNetwork, a as storedGroupFiles, at as setSingleWriterGate, b as walletInstances, c as receivedPairedReply, d as paymentAlias, et as networkLabel, f as paymentWireId, g as createTiming, h as createFailure, i as groupOfFile, it as setAwayWallets, j as openSecret, l as replyRef, m as assertConfirmedReal, n as groupFileId, nt as refuseAway, o as groupReply, p as WALLET_NAMES, q as dropBreezDatabase, r as groupFileText, rt as requireTurn, s as pairedWireReply, t as GroupFileDesk, tt as awayFrom, u as replyTo, v as paymentNetwork, w as readStored$1, y as paymentNetworksOf, z as lightningPaying } from "./groupFiles-CBJIEvCE.js";
9
+ import { i as fedimintDatabase, n as createIrohWebEndpoint, o as loadFedimintSdk, r as irohRelayProblem, t as DEFAULT_IROH_RELAYS } from "./irohWeb-DxeEgQ-W.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 } from "./resolve-BzFG4WDU.js";
12
- import { n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-Cz5fc7BM.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";
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 } from "./resolve-BvHkAhDH.js";
12
+ import { n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-DYiGwzq_.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-DNgrRL0R.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-Bkva90Vo.js");
201
+ var loadUsdt = () => import("./usdt-BLazHiaP.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-CJAhhgPQ.js");
650
+ var loadArkade = () => import("./arkade-BFE8KkEE.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. */
@@ -3553,6 +3553,16 @@ var SWAP_SETTLED_MS = 12e4;
3553
3553
  function swapSettledAt(review, prepared) {
3554
3554
  return Math.max((review.submittedAt ?? review.createdAt) + CASHU_REQUEST_TIMEOUT_MS + SWAP_SETTLED_MS, (prepared.attemptEndedAt ?? 0) + SWAP_SETTLED_MS);
3555
3555
  }
3556
+ /**
3557
+ * The mint answered, and refused. cashu-ts turns a refusal of a keyset the mint retired or does not know (codes
3558
+ * 12xxx) into a `StaleKeysetError` once it has reloaded the mint's keysets: the mint's refusal all the same, with it
3559
+ * as its cause. By name, as cashu-ts's own `isMintOperationError`, so it needs no import of the library.
3560
+ */
3561
+ function mintRefused(error) {
3562
+ if (!(error instanceof Error)) return false;
3563
+ if (error.name === "StaleKeysetError") return mintRefused(error.cause);
3564
+ return error.name === "MintOperationError" && "code" in error;
3565
+ }
3556
3566
  var NEVER_REACHED_MINT = "The payment never reached the mint: nothing was sent, and the sats are back in your wallet. You can pay again.";
3557
3567
  var CashuAdapter = class {
3558
3568
  wallet;
@@ -3575,7 +3585,10 @@ var CashuAdapter = class {
3575
3585
  token = await this.wallet.executeReviewedCashu(review, prepared);
3576
3586
  } catch (error) {
3577
3587
  prepared.attemptEndedAt = Date.now();
3578
- if (persist && (await import("@cashu/cashu-ts")).isMintOperationError(error) && await this.wallet.reviewedCashuSpentElsewhere(prepared).catch(() => false)) return this.spentElsewhere(prepared, persist);
3588
+ if (persist && mintRefused(error)) {
3589
+ if (await this.wallet.reviewedCashuSpentElsewhere(prepared).catch(() => false)) return this.spentElsewhere(prepared, persist);
3590
+ if (await this.wallet.reviewedCashuNeverSwapped(prepared).catch(() => false)) return this.abandon(prepared, persist);
3591
+ }
3579
3592
  throw error;
3580
3593
  }
3581
3594
  await persist?.();
@@ -6945,6 +6958,12 @@ var ProfileDid = class {
6945
6958
  inFlight = null;
6946
6959
  again = false;
6947
6960
  unlisten;
6961
+ /** The last `samePacket` answer. */
6962
+ compared;
6963
+ /** "Clear all data" ended the DID: a publish still on its way saves nothing, or the cleared record comes back. */
6964
+ ended = false;
6965
+ /** The newest sequence number signed here, so the `deactivated` packet goes past one still on its way. */
6966
+ signedSeq = 0;
6948
6967
  constructor(host) {
6949
6968
  this.host = host;
6950
6969
  }
@@ -6994,15 +7013,16 @@ var ProfileDid = class {
6994
7013
  view() {
6995
7014
  if (!this.stored) return void 0;
6996
7015
  const published = this.stored.published;
7016
+ const alsoKnownAs = this.alsoKnownAs(this.listed());
6997
7017
  return {
6998
7018
  id: this.id,
6999
7019
  listed: this.listed(),
7000
- alsoKnownAs: this.alsoKnownAs(this.listed()),
7020
+ alsoKnownAs,
7001
7021
  ...published ? { published: {
7002
7022
  at: published.at,
7003
7023
  versionId: String(published.seq)
7004
7024
  } } : {},
7005
- upToDate: !!published && this.samePacket(published.payload),
7025
+ upToDate: !!published && this.samePacket(published.payload, alsoKnownAs),
7006
7026
  ...this.error ? { error: this.error } : {}
7007
7027
  };
7008
7028
  }
@@ -7064,7 +7084,7 @@ var ProfileDid = class {
7064
7084
  }, ms);
7065
7085
  }
7066
7086
  async publish() {
7067
- if (!this.stored || !this.host.online()) return;
7087
+ if (!this.stored || this.ended || !this.host.online()) return;
7068
7088
  const previous = this.stored.published;
7069
7089
  try {
7070
7090
  const packet = encodeDidDhtPacket(this.document());
@@ -7077,7 +7097,9 @@ var ProfileDid = class {
7077
7097
  seq = Math.max(Math.floor(Date.now() / 1e3), (previous?.seq ?? 0) + 1);
7078
7098
  payload = signDidDhtPacket(identityFromSeed(await this.unsealed()), packet, seq);
7079
7099
  }
7100
+ this.signedSeq = Math.max(this.signedSeq, seq);
7080
7101
  await this.host.publish(toZ32(this.publicKey()), payload);
7102
+ if (this.ended) return;
7081
7103
  this.error = void 0;
7082
7104
  await this.save({
7083
7105
  ...this.stored,
@@ -7093,14 +7115,15 @@ var ProfileDid = class {
7093
7115
  this.host.emit();
7094
7116
  }
7095
7117
  /**
7096
- * "Clear all data": the DID ends. When a document was ever published, a newer packet reading `deactivated` replaces
7118
+ * "Clear all data": the DID ends. When a document was ever published (or is on its way), a newer packet reading `deactivated` replaces
7097
7119
  * it, so resolvers say the DID is gone instead of showing the old document until it expires. Stops publishing first.
7098
7120
  */
7099
7121
  async deactivate() {
7122
+ this.ended = true;
7100
7123
  this.stop();
7101
7124
  const previous = this.stored?.published;
7102
- if (!this.stored || !previous) return;
7103
- const seq = Math.max(Math.floor(Date.now() / 1e3), previous.seq + 1);
7125
+ if (!this.stored || !previous && this.signedSeq === 0) return;
7126
+ const seq = Math.max(Math.floor(Date.now() / 1e3), (previous?.seq ?? 0) + 1, this.signedSeq + 1);
7104
7127
  const identity = identityFromSeed(fromBase64Url(await openSecret(this.stored.seed, SEED_AT)));
7105
7128
  await this.host.publish(toZ32(this.publicKey()), signDidDhtPacket(identity, encodeDidDhtDeactivated(this.publicKey()), seq));
7106
7129
  }
@@ -7108,6 +7131,7 @@ var ProfileDid = class {
7108
7131
  return this.stored?.listed ?? [];
7109
7132
  }
7110
7133
  alsoKnownAs(ids) {
7134
+ if (ids.length === 0) return [];
7111
7135
  const listable = this.host.listable();
7112
7136
  return [...new Set(ids.map((id) => listable.get(id)).filter((uri) => !!uri))];
7113
7137
  }
@@ -7115,13 +7139,23 @@ var ProfileDid = class {
7115
7139
  if (!this.stored) throw new Error("The profile's DID is not loaded yet");
7116
7140
  return fromBase64Url(this.stored.publicKey);
7117
7141
  }
7118
- /** Whether `payload` carries the document as it is now. Never throws: the engine's state is built from it. */
7119
- samePacket(payload) {
7142
+ /**
7143
+ * Whether `payload` carries the document as it is now. Never throws: the engine's state is built from it. Every state
7144
+ * asks, and the document follows from the key and its URIs alone, so it is encoded again only when those URIs or `payload` change.
7145
+ */
7146
+ samePacket(payload, alsoKnownAs = this.alsoKnownAs(this.listed())) {
7147
+ const uris = alsoKnownAs.join(" ");
7148
+ if (this.compared?.payload === payload && this.compared.uris === uris) return this.compared.same;
7149
+ let same = false;
7120
7150
  try {
7121
- return bytesEqual(fromBase64Url(payload).subarray(HEADER), encodeDidDhtPacket(this.document()));
7122
- } catch {
7123
- return false;
7124
- }
7151
+ same = bytesEqual(fromBase64Url(payload).subarray(HEADER), encodeDidDhtPacket(didDhtDocument(this.publicKey(), { alsoKnownAs })));
7152
+ } catch {}
7153
+ this.compared = {
7154
+ payload,
7155
+ uris,
7156
+ same
7157
+ };
7158
+ return same;
7125
7159
  }
7126
7160
  /**
7127
7161
  * A copy of the DID key's seed, for the first device-set secret of the profile (WISP 06 § Terms: `D0` comes from
@@ -7136,6 +7170,7 @@ var ProfileDid = class {
7136
7170
  return this.seed;
7137
7171
  }
7138
7172
  async save(next) {
7173
+ if (this.ended) return;
7139
7174
  await committed((await store(STORES$1.settings, "readwrite")).put(next, KEY$1));
7140
7175
  this.stored = next;
7141
7176
  }
@@ -8501,6 +8536,8 @@ var NostrSocial = class {
8501
8536
  loadingOwn = /* @__PURE__ */ new Set();
8502
8537
  errors = /* @__PURE__ */ new Map();
8503
8538
  drafts = /* @__PURE__ */ new Map();
8539
+ hints = /* @__PURE__ */ new WeakMap();
8540
+ shownNotes = /* @__PURE__ */ new WeakMap();
8504
8541
  constructor(host) {
8505
8542
  this.host = host;
8506
8543
  }
@@ -8607,6 +8644,7 @@ var NostrSocial = class {
8607
8644
  if (subjects.length === 0) return void 0;
8608
8645
  const cache = this.host.readContacts(linkId) ?? {};
8609
8646
  const myKeys = this.host.ownSubjects();
8647
+ const muteLists = myKeys.map((s) => this.own[s]?.mute?.list).filter((m) => !!m);
8610
8648
  return subjects.map((subject) => {
8611
8649
  const c = cache[subject];
8612
8650
  const view = {
@@ -8632,34 +8670,9 @@ var NostrSocial = class {
8632
8670
  key: k,
8633
8671
  follows: this.own[k]?.follows
8634
8672
  })).find((x) => x.follows);
8635
- if (mine?.follows) {
8636
- const h = followHints(c.follows.follows, mine.follows.follows, myKeys, subject);
8637
- view.follows.hints = {
8638
- followsYou: h.followsYou,
8639
- youFollow: h.youFollow,
8640
- mutual: h.mutual.length,
8641
- myKey: mine.key,
8642
- myFollowsAt: mine.follows.fetchedAt
8643
- };
8644
- }
8645
- }
8646
- if (c?.notes) {
8647
- const authorMuted = this.muteLists().some((m) => m.pubkeys.includes(subject));
8648
- const shown = authorMuted ? [] : c.notes.notes.filter((n) => !this.muted(n, subject));
8649
- view.notes = {
8650
- fetchedAt: c.notes.fetchedAt,
8651
- relays: c.notes.relays,
8652
- notes: shown.map((n) => ({
8653
- id: n.id,
8654
- createdAt: n.createdAt,
8655
- content: n.content,
8656
- reply: n.reply
8657
- })),
8658
- more: !c.notes.exhausted,
8659
- hidden: c.notes.notes.length - shown.length,
8660
- authorMuted
8661
- };
8673
+ if (mine?.follows) view.follows.hints = this.hintsOf(c.follows, mine.follows, mine.key, myKeys, subject);
8662
8674
  }
8675
+ if (c?.notes) view.notes = this.notesOf(c.notes, muteLists, subject);
8663
8676
  const loading = this.loading.get(`${linkId}:${subject}`);
8664
8677
  if (loading) view.loading = loading;
8665
8678
  const error = this.errors.get(`${linkId}:${subject}`);
@@ -8667,6 +8680,54 @@ var NostrSocial = class {
8667
8680
  return view;
8668
8681
  });
8669
8682
  }
8683
+ /** How a contact's follows meet the person's. Every state asks; a list that changes is a new object. */
8684
+ hintsOf(theirs, mine, myKey, myKeys, subject) {
8685
+ const keys = myKeys.join(" ");
8686
+ const kept = this.hints.get(theirs);
8687
+ if (kept?.mine === mine && kept.myKey === myKey && kept.keys === keys && kept.subject === subject) return kept.hints;
8688
+ const h = followHints(theirs.follows, mine.follows, myKeys, subject);
8689
+ const hints = {
8690
+ followsYou: h.followsYou,
8691
+ youFollow: h.youFollow,
8692
+ mutual: h.mutual.length,
8693
+ myKey,
8694
+ myFollowsAt: mine.fetchedAt
8695
+ };
8696
+ this.hints.set(theirs, {
8697
+ mine,
8698
+ myKey,
8699
+ keys,
8700
+ subject,
8701
+ hints
8702
+ });
8703
+ return hints;
8704
+ }
8705
+ /** A contact's posts as shown, past the person's mute lists. Every state asks; a list that changes is a new object. */
8706
+ notesOf(notes, lists, subject) {
8707
+ const kept = this.shownNotes.get(notes);
8708
+ if (kept && kept.subject === subject && kept.lists.length === lists.length && kept.lists.every((list, i) => list === lists[i])) return kept.view;
8709
+ const authorMuted = lists.some((m) => m.pubkeys.includes(subject));
8710
+ const shown = authorMuted ? [] : notes.notes.filter((n) => !lists.some((m) => !!mutedBecause(n, subject, m)));
8711
+ const view = {
8712
+ fetchedAt: notes.fetchedAt,
8713
+ relays: notes.relays,
8714
+ notes: shown.map((n) => ({
8715
+ id: n.id,
8716
+ createdAt: n.createdAt,
8717
+ content: n.content,
8718
+ reply: n.reply
8719
+ })),
8720
+ more: !notes.exhausted,
8721
+ hidden: notes.notes.length - shown.length,
8722
+ authorMuted
8723
+ };
8724
+ this.shownNotes.set(notes, {
8725
+ lists,
8726
+ subject,
8727
+ view
8728
+ });
8729
+ return view;
8730
+ }
8670
8731
  requireOnline() {
8671
8732
  if (!this.host.online()) throw new Error("Offline: turn the network on first");
8672
8733
  }
@@ -10844,6 +10905,29 @@ function markBuiltIns(settings, change) {
10844
10905
  settings.put(marks, BUILT_IN_APPS_KEY);
10845
10906
  };
10846
10907
  }
10908
+ /**
10909
+ * The key, in `STORES.settings`, of the digests of the bundles this profile may hold in file storage (one of
10910
+ * `PROFILE_SETTINGS_KEYS`): each one is noted before its bytes are written. File storage lists no files, and a bundle is
10911
+ * written or removed in a step of its own beside its app's record: a page gone between the two leaves one no record
10912
+ * names, which the next start finds here and removes.
10913
+ */
10914
+ var APP_BUNDLES_KEY = "appBundles";
10915
+ /** The digests as kept, read with nothing taken on trust. */
10916
+ function bundleDigests(kept) {
10917
+ return Array.isArray(kept) ? kept.filter((d) => typeof d === "string" && isAppHash(d)) : [];
10918
+ }
10919
+ /** Changes the digests noted (`APP_BUNDLES_KEY`), read and written in one transaction. */
10920
+ async function noteBundles(change) {
10921
+ const tx = (await openDb()).transaction(STORES$1.settings, "readwrite");
10922
+ const settings = tx.objectStore(STORES$1.settings);
10923
+ const read = settings.get(APP_BUNDLES_KEY);
10924
+ read.onsuccess = () => {
10925
+ const noted = new Set(bundleDigests(read.result));
10926
+ change(noted);
10927
+ settings.put([...noted], APP_BUNDLES_KEY);
10928
+ };
10929
+ await done(tx);
10930
+ }
10847
10931
  var builtInRef = (app) => appRef(app.publisher, app.name);
10848
10932
  /**
10849
10933
  * The entries of the built-in list this profile is offered (WISP 1200 § Built-in apps): each reference once, not
@@ -10884,6 +10968,27 @@ function withRevocations(app, read) {
10884
10968
  revocations: [...merged.values()]
10885
10969
  } : app;
10886
10970
  }
10971
+ /** Of these revocations, the ones that stop one of these versions. */
10972
+ function stopping(versions, revocations) {
10973
+ return revocations.filter((r) => versions.some((v) => appRevocationFor(v, [r])));
10974
+ }
10975
+ /**
10976
+ * What installing `version` over `installed` does, for the install screen and for Install alike: the update rule, and an
10977
+ * equivocation for another bundle at the number of the update waiting (two different versions of that number exist).
10978
+ */
10979
+ function installDecision(installed, version) {
10980
+ if (!installed) return "new";
10981
+ if (installed.pending && installed.pending.sequence === version.sequence && installed.pending.digest !== version.digest) return "equivocation";
10982
+ return appUpdateDecision(installed, version);
10983
+ }
10984
+ /**
10985
+ * Whether `now` is still the record `was`: the same install, version, waiting update, files and mark. A store pinned or
10986
+ * unpinned meanwhile is not a change here: the update check unpins on its own (`removeStore`).
10987
+ */
10988
+ function sameRecord(now, was) {
10989
+ if (!was) return !now;
10990
+ return !!now && now.installedAt === was.installedAt && now.digest === was.digest && now.pending?.digest === was.pending?.digest && now.bytes === was.bytes && now.equivocation?.digest === was.equivocation?.digest;
10991
+ }
10887
10992
  /** Rows of one app (`[ref]`), or of one app in one scope (`[ref, scope]`), in `STORES.appStorage`, counter rows included. */
10888
10993
  var rowsOf = (...prefix) => IDBKeyRange.bound(prefix, [...prefix, []]);
10889
10994
  /** The app's own rows of one scope: its counter row left out. */
@@ -11004,6 +11109,10 @@ var Apps = class {
11004
11109
  }
11005
11110
  };
11006
11111
  stopped = false;
11112
+ /** Bundles written by this engine (`writeBundle`), by digest: one whose record is not written yet is not swept (`sweepBundles`). */
11113
+ written = /* @__PURE__ */ new Set();
11114
+ /** The sweep of `start` while it runs: a bundle written meanwhile waits for it. */
11115
+ sweeping = null;
11007
11116
  constructor(host) {
11008
11117
  this.host = host;
11009
11118
  }
@@ -11013,10 +11122,14 @@ var Apps = class {
11013
11122
  nowS() {
11014
11123
  return Math.floor(this.now() / 1e3);
11015
11124
  }
11016
- /** Preloads the default stores (no request), then checks for updates soon after start and every 24 hours. */
11125
+ /**
11126
+ * Preloads the default stores (no request) and removes the bundles no record names (`sweepBundles`), then checks for
11127
+ * updates soon after start and every 24 hours.
11128
+ */
11017
11129
  async start() {
11018
11130
  this.stopped = false;
11019
11131
  await this.seedDefaults();
11132
+ await (this.sweeping = this.sweepBundles().catch(() => {}));
11020
11133
  this.schedule(APP_CHECK_TIMINGS.afterStartMs, true);
11021
11134
  }
11022
11135
  stop() {
@@ -11161,6 +11274,14 @@ var Apps = class {
11161
11274
  digest
11162
11275
  };
11163
11276
  }
11277
+ /** The versions of an app a revocation it keeps may stop: the installed one, the one waiting, one started here before an update (it may still run). */
11278
+ versionsOf(app) {
11279
+ return [
11280
+ app,
11281
+ ...app.pending ? [versionOf(app.pending.manifest, app.pending.digest)] : [],
11282
+ ...this.startedBefore(app)
11283
+ ];
11284
+ }
11164
11285
  /** The versions started here that are not the installed one any more. */
11165
11286
  startedBefore(app) {
11166
11287
  return [...this.started.get(app.ref) ?? []].filter(([digest]) => digest !== app.digest).map(([digest, sequence]) => ({
@@ -11191,15 +11312,16 @@ var Apps = class {
11191
11312
  }
11192
11313
  }
11193
11314
  /**
11194
- * Writes an app's record back only while that install is still there (the same `installedAt`), read and written in
11195
- * one transaction: an app uninstalled (or installed again) while the update check was reading is not put back.
11315
+ * Writes an app's record back only while it is still the record `was` (`sameRecord`), read and written in one
11316
+ * transaction: an app uninstalled (or installed again) while the update check was reading is not put back, nor is the
11317
+ * version it read over an update the person accepted meanwhile. `was` undefined: only while the app has no record.
11196
11318
  */
11197
- async putAppIfInstalled(app, installedAt) {
11319
+ async putAppIfUnchanged(app, was) {
11198
11320
  const tx = (await openDb()).transaction(STORES$1.apps, "readwrite");
11199
11321
  let put = false;
11200
11322
  const read = tx.objectStore(STORES$1.apps).get(app.ref);
11201
11323
  read.onsuccess = () => {
11202
- if (read.result?.installedAt !== installedAt) return;
11324
+ if (!sameRecord(read.result, was)) return;
11203
11325
  tx.objectStore(STORES$1.apps).put(app);
11204
11326
  put = true;
11205
11327
  };
@@ -11239,8 +11361,22 @@ var Apps = class {
11239
11361
  });
11240
11362
  await written;
11241
11363
  }
11242
- putStore(record) {
11243
- return this.writeStores((records) => records.put(record), (held) => held.set(record.key, record));
11364
+ async putStore(record) {
11365
+ await this.writeStores((records) => records.put(record), (held) => held.set(record.key, record));
11366
+ await this.keepStoreRevocations(record);
11367
+ }
11368
+ /**
11369
+ * Keeps on each installed app the revocations a store's index carries of its versions: a client keeps every
11370
+ * revocation it verified (WISP 1200 § Publisher keys), so the store's next index without it, or the store removed,
11371
+ * does not let that version run again.
11372
+ */
11373
+ async keepStoreRevocations(record) {
11374
+ const revoked = record.index?.revoked ?? [];
11375
+ if (!revoked.length) return;
11376
+ for (const app of await this.installed()) {
11377
+ const next = withRevocations(app, stopping(this.versionsOf(app), revoked));
11378
+ if ((next.revocations?.length ?? 0) > (app.revocations?.length ?? 0)) await this.putAppIfUnchanged(next, app);
11379
+ }
11244
11380
  }
11245
11381
  /** The stores' views, made once and again after a store is written here: an app's every storage call and chat frame checks them. */
11246
11382
  heldViews() {
@@ -11283,11 +11419,14 @@ var Apps = class {
11283
11419
  * failure is `storage`, with the browser's own words after it for the logs, and leaves no piece behind.
11284
11420
  */
11285
11421
  async writeBundle(digest, bytes) {
11422
+ this.written.add(digest);
11286
11423
  const id = bundleId(digest);
11287
11424
  const expected = toBase64Url(await sha256Paced(bytes));
11288
11425
  let files;
11289
11426
  let stored;
11290
11427
  try {
11428
+ await this.sweeping;
11429
+ await noteBundles((noted) => noted.add(digest));
11291
11430
  files = await fileBytes();
11292
11431
  const size = await files.size(id);
11293
11432
  if (size === bytes.length && await files.digest(id) === expected) return files.kind;
@@ -11338,6 +11477,29 @@ var Apps = class {
11338
11477
  const app = await this.app(ref);
11339
11478
  if (app?.digest !== digest && app?.pending?.digest !== digest) await this.removeBundle(kind, digest);
11340
11479
  }
11480
+ /**
11481
+ * Removes the bundles noted (`APP_BUNDLES_KEY`) that no record names, as its version or the one waiting: what an
11482
+ * install, update, accept or uninstall cut short left. One written by this engine is left (its record may be on its
11483
+ * way); the next start sees it. The digests the records name are noted too, for the day they stop naming them.
11484
+ */
11485
+ async sweepBundles() {
11486
+ const tx = (await openDb()).transaction([STORES$1.apps, STORES$1.settings], "readonly");
11487
+ const [apps, kept] = await Promise.all([wrap(tx.objectStore(STORES$1.apps).getAll()), wrap(tx.objectStore(STORES$1.settings).get(APP_BUNDLES_KEY))]);
11488
+ const named = new Set(apps.flatMap((a) => a.pending ? [a.digest, a.pending.digest] : [a.digest]));
11489
+ const kinds = new Set(apps.flatMap((a) => a.pending ? [a.bytes, a.pending.bytes] : [a.bytes]));
11490
+ const current = await fileBytes().catch(() => null);
11491
+ if (current) kinds.add(current.kind);
11492
+ const gone = /* @__PURE__ */ new Set();
11493
+ for (const digest of bundleDigests(kept)) {
11494
+ if (named.has(digest) || this.written.has(digest)) continue;
11495
+ for (const kind of kinds) await this.removeBundle(kind, digest);
11496
+ gone.add(digest);
11497
+ }
11498
+ await noteBundles((noted) => {
11499
+ for (const digest of named) noted.add(digest);
11500
+ for (const digest of gone) noted.delete(digest);
11501
+ });
11502
+ }
11341
11503
  /** The installed bundle read back and checked again before it runs (WISP 1200 § Signatures: "again before it runs one"). */
11342
11504
  verifiedBundle(app, running) {
11343
11505
  if (running) this.runUsed.set(app.digest, this.now());
@@ -11654,6 +11816,7 @@ var Apps = class {
11654
11816
  async removeStore({ key }) {
11655
11817
  const held = await this.storeRecord(key);
11656
11818
  if (!held) return;
11819
+ await this.keepStoreRevocations(held);
11657
11820
  const seen = held.index ? {
11658
11821
  sequence: held.index.sequence,
11659
11822
  digest: held.digest ?? ""
@@ -11678,21 +11841,21 @@ var Apps = class {
11678
11841
  if (key !== void 0 && !stores.length) fail("no-store", "No such store");
11679
11842
  const out = [];
11680
11843
  for (const s of stores) {
11681
- let next;
11844
+ let read;
11682
11845
  try {
11683
- const read = await this.readStoreAt(s.url, s.key, s);
11684
- next = read.ok ? this.withIndex(s, read.store.index, read.store.digest) : {
11685
- ...s,
11686
- problem: read.reason
11687
- };
11846
+ read = await this.readStoreAt(s.url, s.key, s);
11688
11847
  } catch (error) {
11689
- next = {
11690
- ...s,
11691
- problem: error instanceof AppFetchError ? error.code : "network"
11848
+ read = {
11849
+ ok: false,
11850
+ reason: error instanceof AppFetchError ? error.code : "network"
11692
11851
  };
11693
11852
  }
11694
11853
  const now = await this.storeRecord(s.key);
11695
11854
  if (!now || now.removed) continue;
11855
+ const next = read.ok ? this.withIndex(now, read.store.index, read.store.digest) : {
11856
+ ...now,
11857
+ problem: read.reason
11858
+ };
11696
11859
  if (now === s && next.index === s.index && next.digest === s.digest && next.problem === s.problem && next.equivocation === s.equivocation) (await this.records()).set(s.key, next);
11697
11860
  else await this.putStore(next);
11698
11861
  out.push(this.summary(next));
@@ -11784,7 +11947,7 @@ var Apps = class {
11784
11947
  const { manifest, digest } = bundle;
11785
11948
  const version = versionOf(manifest, digest);
11786
11949
  const [installed, stores] = await Promise.all([this.app(version.ref), this.stores()]);
11787
- const decision = installed ? appUpdateDecision(installed, version) : "new";
11950
+ const decision = installDecision(installed, version);
11788
11951
  const install = decision === "other-app" ? "new" : decision;
11789
11952
  const asks = install === "new" ? [...manifest.permissions] : install === "update" ? manifest.permissions.filter((p) => !installed.permissions.includes(p)) : [];
11790
11953
  const listedBy = this.listedBy(version.ref, stores);
@@ -11819,47 +11982,54 @@ var Apps = class {
11819
11982
  const { manifest } = bundle;
11820
11983
  if (!Array.isArray(grant) || !manifest.permissions.every((p) => grant.includes(p))) fail("permissions", "Every permission the app asks for must be granted");
11821
11984
  const version = versionOf(manifest, digest);
11822
- const [installed, stores] = await Promise.all([this.app(version.ref), this.stores()]);
11823
- const run = this.runStatus(version, this.storeViews(stores), installed?.revocations);
11824
- if (run.status === "revoked") fail("revoked", "Its publisher revoked this version");
11825
- if (run.status === "removed") fail("removed", `Removed by ${run.by[0].name}: ${run.by[0].reason}`);
11826
- const pendingClash = installed?.pending && installed.pending.sequence === version.sequence && installed.pending.digest !== digest;
11827
- const decision = installed ? pendingClash ? "equivocation" : appUpdateDecision(installed, version) : "new";
11828
- if (decision === "rollback") fail("rollback", "A newer version of this app is installed");
11829
- if (decision === "equivocation") {
11830
- await this.putApp({
11831
- ...installed,
11832
- equivocation: {
11833
- sequence: version.sequence,
11834
- digest,
11835
- at: this.now()
11985
+ let wrote;
11986
+ try {
11987
+ for (;;) {
11988
+ const [installed, stores] = await Promise.all([this.app(version.ref), this.stores()]);
11989
+ const run = this.runStatus(version, this.storeViews(stores), installed?.revocations);
11990
+ if (run.status === "revoked") fail("revoked", "Its publisher revoked this version");
11991
+ if (run.status === "removed") fail("removed", `Removed by ${run.by[0].name}: ${run.by[0].reason}`);
11992
+ const decision = installDecision(installed, version);
11993
+ if (decision === "rollback") fail("rollback", "A newer version of this app is installed");
11994
+ if (decision === "equivocation") {
11995
+ if (!await this.putAppIfUnchanged({
11996
+ ...installed,
11997
+ equivocation: {
11998
+ sequence: version.sequence,
11999
+ digest,
12000
+ at: this.now()
12001
+ }
12002
+ }, installed)) continue;
12003
+ fail("equivocation", `Two different versions ${version.sequence} exist. Ghostly kept the one you have.`);
11836
12004
  }
11837
- });
11838
- fail("equivocation", `Two different versions ${version.sequence} exist. Ghostly kept the one you have.`);
11839
- }
11840
- if (decision === "same" && installed) {
11841
- const files = await this.hasBundle(installed.bytes, digest) ? null : await this.writeBundle(digest, bytes);
11842
- const pin = fromStore !== void 0 && installed.store !== fromStore;
11843
- if (files || pin) {
11844
- const { pending, ...rest } = installed;
11845
- if (pin && pending) await this.removeBundle(pending.bytes, pending.digest);
11846
- await this.putApp({
11847
- ...pin ? rest : installed,
11848
- ...files && { bytes: files },
11849
- ...pin && { store: fromStore }
11850
- });
12005
+ if (decision === "same" && installed) {
12006
+ const files = await this.hasBundle(installed.bytes, digest) ? null : wrote = await this.writeBundle(digest, bytes);
12007
+ const pin = fromStore !== void 0 && installed.store !== fromStore;
12008
+ if (files || pin) {
12009
+ const { pending, ...rest } = installed;
12010
+ if (!await this.putAppIfUnchanged({
12011
+ ...pin ? rest : installed,
12012
+ ...files && { bytes: files },
12013
+ ...pin && { store: fromStore }
12014
+ }, installed)) continue;
12015
+ if (pin && pending) await this.removeBundle(pending.bytes, pending.digest);
12016
+ }
12017
+ this.staged.delete(digest);
12018
+ return this.view(await this.app(version.ref), stores);
12019
+ }
12020
+ const kind = wrote = await this.writeBundle(digest, bytes);
12021
+ const next = this.versionRecord(installed, bundle, kind, from, fromStore);
12022
+ if (!await this.putAppIfUnchanged(next, installed)) continue;
12023
+ if (!installed && this.builtIn(version.ref)) await this.keepBuiltIn(version.ref);
12024
+ if (installed && installed.digest !== digest) await this.removeBundle(installed.bytes, installed.digest);
12025
+ if (installed?.pending && next.pending?.digest !== installed.pending.digest && installed.pending.digest !== digest) await this.removeBundle(installed.pending.bytes, installed.pending.digest);
12026
+ this.staged.delete(digest);
12027
+ return this.view(next, stores);
11851
12028
  }
11852
- this.staged.delete(digest);
11853
- return this.view(await this.app(version.ref), stores);
11854
- }
11855
- const kind = await this.writeBundle(digest, bytes);
11856
- const next = this.versionRecord(installed, bundle, kind, from, fromStore);
11857
- await this.putApp(next);
11858
- if (!installed && this.builtIn(version.ref)) await this.keepBuiltIn(version.ref);
11859
- if (installed && installed.digest !== digest) await this.removeBundle(installed.bytes, installed.digest);
11860
- if (installed?.pending && next.pending?.digest !== installed.pending.digest && installed.pending.digest !== digest) await this.removeBundle(installed.pending.bytes, installed.pending.digest);
11861
- this.staged.delete(digest);
11862
- return this.view(next, stores);
12029
+ } catch (error) {
12030
+ if (wrote) await this.removeUnusedBundle(version.ref, wrote, digest);
12031
+ throw error;
12032
+ }
11863
12033
  }
11864
12034
  /**
11865
12035
  * The record of a version installed now, keeping what the app had (its revocations, a newer version waiting). `store`
@@ -11869,7 +12039,11 @@ var Apps = class {
11869
12039
  versionRecord(installed, bundle, kind, from, store) {
11870
12040
  const { manifest, digest } = bundle;
11871
12041
  const now = this.now();
11872
- const keepPending = installed?.pending && installed.pending.sequence > manifest.sequence && installed.store === store ? installed.pending : void 0;
12042
+ const kept = installed?.pending && installed.pending.sequence > manifest.sequence && installed.store === store ? installed.pending : void 0;
12043
+ const keepPending = kept && {
12044
+ ...kept,
12045
+ added: addedAppPermissions(manifest.permissions, kept.manifest.permissions)
12046
+ };
11873
12047
  return {
11874
12048
  ref: appRef(manifest.publisher, manifest.name),
11875
12049
  publisher: manifest.publisher,
@@ -11910,9 +12084,25 @@ var Apps = class {
11910
12084
  permissions: read.bundle.manifest.permissions
11911
12085
  });
11912
12086
  if (plan.action === "refuse") fail(plan.decision, "This update can no longer be installed");
12087
+ const added = plan.action === "ask" ? plan.added : [];
12088
+ if (added.length !== pending.added.length || added.some((p) => !pending.added.includes(p))) {
12089
+ await this.putApp({
12090
+ ...installed,
12091
+ pending: {
12092
+ ...pending,
12093
+ added
12094
+ }
12095
+ });
12096
+ fail("permissions-changed", `This update now adds ${added.length ? added.join(", ") : "no permission"}; look at it again`);
12097
+ }
11913
12098
  const { pending: _p, ...without } = installed;
11914
12099
  const next = this.versionRecord(without, read.bundle, pending.bytes, pending.from, installed.store);
11915
- await this.putApp(next);
12100
+ if (!await this.putAppIfUnchanged(next, installed)) {
12101
+ const now = await this.app(ref);
12102
+ if (!now) fail("not-installed", "This app is not installed");
12103
+ if (now.digest === pending.digest) return this.view(now, await this.stores());
12104
+ fail("no-update", "This update can no longer be installed");
12105
+ }
11916
12106
  await this.removeBundle(installed.bytes, installed.digest);
11917
12107
  return this.view(next, stores);
11918
12108
  }
@@ -11948,15 +12138,17 @@ var Apps = class {
11948
12138
  if (!await this.hasBundle(listed.bytes, listed.digest)) await this.fetchFiles({ ref: listed.ref }).catch(() => {});
11949
12139
  const first = await this.app(listed.ref);
11950
12140
  if (!first) continue;
12141
+ let stored = first;
11951
12142
  let app = first;
11952
12143
  let outcome = "none";
11953
12144
  let wrote;
12145
+ const dropped = [];
11954
12146
  if (app.store !== void 0 && !stores.some((s) => s.key === app.store)) {
11955
12147
  const { store: _s, ...unpinned } = app;
11956
12148
  app = unpinned;
11957
12149
  }
11958
12150
  if (app.store !== void 0 && app.pending && stores.find((s) => s.key === app.store)?.index && this.pinnedListing(app, stores)?.digest !== app.pending.digest) {
11959
- await this.removeBundle(app.pending.bytes, app.pending.digest);
12151
+ dropped.push(app.pending);
11960
12152
  const { pending: _p, ...rest } = app;
11961
12153
  app = rest;
11962
12154
  }
@@ -11974,6 +12166,7 @@ var Apps = class {
11974
12166
  const missed = `${s.key} ${app.ref} ${url}`;
11975
12167
  if (candidates.has(url) || s.digest !== void 0 && this.listingMisses.get(missed) === seen) continue;
11976
12168
  candidates.set(url, {
12169
+ sequence: listing.sequence,
11977
12170
  ...pinned !== void 0 && { digest: listing.digest },
11978
12171
  peek: true,
11979
12172
  ...s.digest !== void 0 && { miss: [missed, seen] }
@@ -11984,13 +12177,21 @@ var Apps = class {
11984
12177
  if (candidates.has(url)) continue;
11985
12178
  try {
11986
12179
  const peek = await this.peekAt(url);
11987
- if (peek && newer(peek)) candidates.set(url, { holds: peek });
12180
+ if (peek && newer(peek)) candidates.set(url, {
12181
+ sequence: peek.sequence,
12182
+ holds: peek
12183
+ });
11988
12184
  } catch {}
11989
12185
  }
11990
12186
  const revokeRead = /* @__PURE__ */ new Set();
11991
12187
  const before = await this.readRevocations(app.ref, [app.from, ...app.manifest.sources ?? []], revokeRead);
11992
12188
  app = withRevocations(app, before ?? []);
11993
- for (const [url, want] of candidates) {
12189
+ if (app.pending && this.runStatus(versionOf(app.pending.manifest, app.pending.digest), this.storeViews(stores), app.revocations).status !== "ok") {
12190
+ await this.removeBundle(app.pending.bytes, app.pending.digest);
12191
+ const { pending: _p, ...rest } = app;
12192
+ app = rest;
12193
+ }
12194
+ for (const [url, want] of [...candidates].sort(([, a], [, b]) => b.sequence - a.sequence)) {
11994
12195
  let holds = want.holds;
11995
12196
  if (want.peek) {
11996
12197
  let peek;
@@ -12059,13 +12260,13 @@ var Apps = class {
12059
12260
  const next = this.versionRecord(app, bundle, kind, url, app.store);
12060
12261
  const passed = old.pending && old.pending.sequence <= version.sequence ? old.pending : void 0;
12061
12262
  if (passed) delete next.pending;
12062
- if (!await this.putAppIfInstalled(next, first.installedAt)) break;
12063
- app = next;
12263
+ if (!await this.putAppIfUnchanged(next, stored)) break;
12264
+ app = stored = next;
12064
12265
  if (passed) await this.removeBundle(passed.bytes, passed.digest);
12065
12266
  await this.removeBundle(old.bytes, old.digest);
12066
12267
  outcome = "updated";
12067
12268
  } else {
12068
- if (app.pending) await this.removeBundle(app.pending.bytes, app.pending.digest);
12269
+ if (app.pending) dropped.push(app.pending);
12069
12270
  app = {
12070
12271
  ...app,
12071
12272
  pending: {
@@ -12084,13 +12285,14 @@ var Apps = class {
12084
12285
  }
12085
12286
  const after = await this.readRevocations(app.ref, [app.from, ...app.manifest.sources ?? []], revokeRead);
12086
12287
  const revocations = before || after ? [...before ?? [], ...after ?? []] : null;
12087
- const versions = [
12088
- app,
12089
- ...app.pending ? [versionOf(app.pending.manifest, app.pending.digest)] : [],
12090
- ...this.startedBefore(app)
12091
- ];
12092
- const stays = (app.revocations ?? []).filter((r) => !revocations || versions.some((v) => appRevocationFor(v, [r])));
12093
- const merged = new Map([...stays, ...revocations ?? []].map((r) => [canonicalJson(r), r]));
12288
+ const versions = this.versionsOf(app);
12289
+ const stays = revocations ? stopping(versions, app.revocations ?? []) : app.revocations ?? [];
12290
+ const carried = stopping(versions, stores.flatMap((s) => s.index?.revoked ?? []));
12291
+ const merged = new Map([
12292
+ ...stays,
12293
+ ...revocations ?? [],
12294
+ ...carried
12295
+ ].map((r) => [canonicalJson(r), r]));
12094
12296
  if ((await this.app(app.ref))?.store === void 0 && app.store !== void 0) {
12095
12297
  const { store: _s, ...unpinned } = app;
12096
12298
  app = unpinned;
@@ -12100,10 +12302,9 @@ var Apps = class {
12100
12302
  ...merged.size && { revocations: [...merged.values()] },
12101
12303
  checkedAt: this.now()
12102
12304
  };
12103
- if (!await this.putAppIfInstalled(app, first.installedAt)) {
12104
- if (wrote) await this.removeUnusedBundle(app.ref, wrote.bytes, wrote.digest);
12105
- continue;
12106
- }
12305
+ const put = await this.putAppIfUnchanged(app, stored);
12306
+ for (const files of [...dropped, ...!put && wrote ? [wrote] : []]) await this.removeUnusedBundle(app.ref, files.bytes, files.digest);
12307
+ if (!put) continue;
12107
12308
  out.push({
12108
12309
  ref: app.ref,
12109
12310
  outcome,
@@ -12748,6 +12949,12 @@ function isPush(value) {
12748
12949
  }
12749
12950
  return true;
12750
12951
  }
12952
+ /** One earlier device set as a record keeps it, and as a handoff's part `devices` carries it. */
12953
+ function isEarlierSet(value) {
12954
+ const set = value;
12955
+ if (!set || typeof set !== "object" || !bytes(set.d) || !bytes(set.tombstone) || !text(set.setUpdate) || !Array.isArray(set.pending) || !set.pending.every(bytes)) return false;
12956
+ return set.pending.length <= 4 && (set.foreign === void 0 || set.foreign === true) && optional(set.removed, bytes);
12957
+ }
12751
12958
  /** Why a stored record cannot be trusted. The gate then starts nothing (see `gate.ts`). */
12752
12959
  var DeviceRecordError = class extends Error {
12753
12960
  constructor(what) {
@@ -12786,7 +12993,7 @@ function parseDeviceRecord(value) {
12786
12993
  ]) if (!optional(r[field], bytes)) return bad(field);
12787
12994
  if (!optional(r.signingKey, (v) => DEVICE_SIGNING_KEY_KINDS.includes(v))) return bad("signingKey");
12788
12995
  if (r.network !== void 0 && !isNetwork(r.network)) return bad("network");
12789
- if (!optional(r.forks, (v) => Array.isArray(v) && v.length <= 8 && v.every((name) => text(name) && /^ghostly(_[A-Za-z0-9_-]{1,64})?$/.test(name)))) return bad("forks");
12996
+ if (!optional(r.forks, (v) => Array.isArray(v) && v.every((name) => text(name) && /^ghostly(_[A-Za-z0-9_-]{1,64})?$/.test(name)))) return bad("forks");
12790
12997
  if (!optional(r.breezDatabases, (v) => Array.isArray(v) && v.length <= 8 && v.every((name) => text(name) && /^ghostly-breez-/.test(name)))) return bad("breezDatabases");
12791
12998
  if (!optional(r.releasedTurn, (v) => count(v, 2 ** 32 - 1))) return bad("releasedTurn");
12792
12999
  if (!optional(r.seenSequence, (v) => count(v, Number.MAX_SAFE_INTEGER))) return bad("seenSequence");
@@ -12841,10 +13048,7 @@ function parseDeviceRecord(value) {
12841
13048
  if (!raise || typeof raise !== "object" || !bytes(raise.id) || raise.why !== "takeover" && raise.why !== "restore" || !count(raise.takeovers, 2 ** 32 - 1) || !count(raise.at, Number.MAX_SAFE_INTEGER)) return bad("raise");
12842
13049
  }
12843
13050
  if (!Array.isArray(r.earlierSets) || r.earlierSets.length > 8) return bad("the earlier device sets");
12844
- for (const set of r.earlierSets) {
12845
- if (!set || !bytes(set.d) || !bytes(set.tombstone) || !text(set.setUpdate) || !Array.isArray(set.pending) || !set.pending.every(bytes)) return bad("an earlier device set");
12846
- if (set.pending.length > 4 || set.foreign !== void 0 && set.foreign !== true) return bad("an earlier device set");
12847
- }
13051
+ if (!r.earlierSets.every(isEarlierSet)) return bad("an earlier device set");
12848
13052
  if (r.setNotice !== void 0) {
12849
13053
  const n = r.setNotice;
12850
13054
  if (!n || typeof n !== "object" || !texts(n.names, 4) || !count(n.at, Number.MAX_SAFE_INTEGER) || n.seen !== void 0 && n.seen !== true) return bad("setNotice");
@@ -13329,11 +13533,14 @@ async function enrollDevice(profile, state, patch = {}) {
13329
13533
  async function moveDevice(profile, to, patch = {}) {
13330
13534
  return change(profile, (current) => transition(current, profile, to, patch));
13331
13535
  }
13332
- /** Fields of the record changed, its state kept. There must be a record. */
13536
+ /**
13537
+ * Fields of the record changed, its state kept. There must be a record. A function makes the patch from the record
13538
+ * read inside this write, so a write that landed since the caller's own read is not written over (null: no change).
13539
+ */
13333
13540
  async function amendDevice(profile, patch) {
13334
13541
  return change(profile, (current) => {
13335
13542
  if (!current) throw new Error("This profile has no device set");
13336
- return amend(current, patch);
13543
+ return amend(current, (typeof patch === "function" ? patch(current) : patch) ?? {});
13337
13544
  });
13338
13545
  }
13339
13546
  /** One writer at a time in this page; across pages and documents, the Web Lock below and the check inside `swap`. */
@@ -14882,6 +15089,8 @@ var EnrollInviter = class extends Enrollment {
14882
15089
  seen = false;
14883
15090
  /** The person answered the digits: one answer is taken, before the record is read or written for it. */
14884
15091
  answered = false;
15092
+ /** When the code's ten minutes end, in ms. */
15093
+ expiresAt = 0;
14885
15094
  constructor(options) {
14886
15095
  super(options, {
14887
15096
  role: "inviter",
@@ -14951,6 +15160,7 @@ var EnrollInviter = class extends Enrollment {
14951
15160
  });
14952
15161
  }
14953
15162
  });
15163
+ this.expiresAt = side.invite.expires * 1e3;
14954
15164
  this.timer(Math.max(0, side.invite.expires * 1e3 - this.now()), () => {
14955
15165
  if (this.view.step === "waiting" || this.view.step === "confirm") this.fail("expired", "expired");
14956
15166
  });
@@ -14964,6 +15174,10 @@ var EnrollInviter = class extends Enrollment {
14964
15174
  return;
14965
15175
  }
14966
15176
  if (frame.t === "enroll-hello" && this.view.step === "waiting" && this.session && !this.joiner) {
15177
+ if (this.now() >= this.expiresAt) {
15178
+ await this.fail("expired", "expired");
15179
+ return;
15180
+ }
14967
15181
  const hello = readEnrollHello(frame, this.session.hash, this.key.publicKey, this.session.peerKey);
14968
15182
  if (!hello) {
14969
15183
  await this.fail("proof", "failed");
@@ -14998,6 +15212,10 @@ var EnrollInviter = class extends Enrollment {
14998
15212
  async confirm(match) {
14999
15213
  if (this.over || this.answered || this.view.step !== "confirm" || !this.joiner) throw new Error("There are no digits to confirm");
15000
15214
  this.answered = true;
15215
+ if (this.now() >= this.expiresAt) {
15216
+ await this.fail("expired", "expired", this.joiner.name);
15217
+ return this.view;
15218
+ }
15001
15219
  if (!match) {
15002
15220
  await this.fail("digits", "digits", this.joiner.name);
15003
15221
  return this.view;
@@ -15959,9 +16177,16 @@ async function planSetMove(record, signer, options = {}) {
15959
16177
  const was = JSON.parse(set.setUpdate);
15960
16178
  if (typeof was.rec === "string") oldRec = fromBase64Url(was.rec);
15961
16179
  } catch {}
15962
- const setUpdate = pending.length ? JSON.stringify(await setUpdateFrame(turnKeys(fromBase64Url(set.d)).address, {
16180
+ const setKeys = turnKeys(fromBase64Url(set.d)), tombBytes = fromBase64Url(set.tombstone);
16181
+ const oldTomb = readTurnPacket(setKeys, tombBytes);
16182
+ const kept = oldTomb.kind === "valid" ? turnSlots.map((slot, i) => {
16183
+ const was = oldTomb.record.slots[i];
16184
+ return slot && was && bytesEqual(was.key, slot.key) ? slot : null;
16185
+ }) : turnSlots;
16186
+ const setUpdate = pending.length ? JSON.stringify(await setUpdateFrame(setKeys.address, {
15963
16187
  ...update,
15964
- tomb: fromBase64Url(set.tombstone),
16188
+ set: kept,
16189
+ tomb: tombBytes,
15965
16190
  ...oldRec ? { rec: oldRec } : {}
15966
16191
  }, signer)) : set.setUpdate;
15967
16192
  earlier.push({
@@ -15974,7 +16199,8 @@ async function planSetMove(record, signer, options = {}) {
15974
16199
  d: record.d,
15975
16200
  tombstone: toBase64Url(tomb),
15976
16201
  setUpdate: JSON.stringify(frame),
15977
- pending: staying(slots.flatMap((slot) => slot ? [slot.key] : []))
16202
+ pending: staying(slots.flatMap((slot) => slot ? [slot.key] : [])),
16203
+ ...removed ? { removed: removed.key } : {}
15978
16204
  });
15979
16205
  return {
15980
16206
  removed,
@@ -17002,11 +17228,7 @@ var DeviceLinks = class {
17002
17228
  },
17003
17229
  onAnswersRefused: () => this.withoutRtc(running),
17004
17230
  onPresence: (presence) => {
17005
- if (!presence.online || running.rtcOff || running.rtcWait || running.link.isDataLinkOpen) return;
17006
- running.rtcWait = setTimeout(() => {
17007
- running.rtcWait = void 0;
17008
- if (!running.link.isDataLinkOpen) this.withoutRtc(running);
17009
- }, Math.min(DEVICE_RTC_MS * 2 ** (this.rtcBacks.get(running.id) ?? 0), DEVICE_RTC_MAX_MS));
17231
+ if (presence.online) this.waitForRtc(running);
17010
17232
  },
17011
17233
  onPacketTransports: (transports) => {
17012
17234
  if (!running.native && !transports.includes("webrtc/1")) this.startNative(running);
@@ -17311,9 +17533,8 @@ var DeviceLinks = class {
17311
17533
  }
17312
17534
  /** `key` holds the set under `d` (or the current one): its pending frame is done, and the old link goes. */
17313
17535
  async acked(key, d) {
17314
- const patch = acknowledged(await this.record(), key, d);
17315
- if (!patch) return;
17316
- await amendDevice(this.options.profile, patch);
17536
+ if (!acknowledged(await this.record(), key, d)) return;
17537
+ await amendDevice(this.options.profile, (current) => acknowledged(current, key, d));
17317
17538
  await this.refresh();
17318
17539
  this.changed();
17319
17540
  }
@@ -17401,9 +17622,13 @@ var DeviceLinks = class {
17401
17622
  * its own for it as for a Linux Desktop, and the two meet over Iroh's relay. Only with no session open, and only
17402
17623
  * where this app has a native transport to go on with.
17403
17624
  */
17404
- withoutRtc(running) {
17625
+ withoutRtc(running, waited = false) {
17405
17626
  if (this.stopped || running.rtcOff || running.native || !this.createPeerConnection || running.link.isDataLinkOpen) return;
17406
17627
  if (!Object.values(this.nativeFactories()).some(Boolean)) return;
17628
+ if (!waited && this.rtcBacks.get(running.id)) {
17629
+ this.waitForRtc(running);
17630
+ return;
17631
+ }
17407
17632
  const run = this.queue.catch(() => {}).then(async () => {
17408
17633
  if (this.stopped || this.running.get(running.id) !== running || running.link.isDataLinkOpen) return;
17409
17634
  this.running.delete(running.id);
@@ -17421,6 +17646,14 @@ var DeviceLinks = class {
17421
17646
  });
17422
17647
  this.queue = run;
17423
17648
  }
17649
+ /** `withoutRtc` once `DEVICE_RTC_MS` passed with no session open, twice as long for each time it went back (`rtcBacks`). */
17650
+ waitForRtc(running) {
17651
+ if (running.rtcOff || running.rtcWait || running.link.isDataLinkOpen) return;
17652
+ running.rtcWait = setTimeout(() => {
17653
+ running.rtcWait = void 0;
17654
+ if (!running.link.isDataLinkOpen) this.withoutRtc(running, true);
17655
+ }, Math.min(DEVICE_RTC_MS * 2 ** (this.rtcBacks.get(running.id) ?? 0), DEVICE_RTC_MAX_MS));
17656
+ }
17424
17657
  /**
17425
17658
  * The link that went on without WebRTC (`withoutRtc`) started none of its native transports: an Iroh relay neither
17426
17659
  * device reaches, and no HyperDHT relay. With nothing to go through it starts again with WebRTC, which may connect
@@ -17775,6 +18008,12 @@ var reportOf = (busy) => busy === null ? null : typeof busy === "string" ? { why
17775
18008
  var wireWhy = (report) => report.why === "call" ? "call" : "handoff";
17776
18009
  var name = (record, key) => record.deviceSet.find((slot) => slot?.key === key)?.name ?? "";
17777
18010
  var slotOf = (record, key) => record.deviceSet.findIndex((slot) => slot?.key === key);
18011
+ /**
18012
+ * The counts of the devices still in the set: a removed device cannot pull (`onRequest` refuses it), and one added again
18013
+ * has a new key, so the list stays within the set's size instead of growing to the record's cap of 16 and refusing every
18014
+ * write after it.
18015
+ */
18016
+ var setAttempts = (record, attempts) => Object.fromEntries(Object.entries(attempts ?? {}).filter(([key]) => slotOf(record, key) >= 0));
17778
18017
  /** One session of a handoff with the other device: its own X25519 key, the other's hello, and the stream key. */
17779
18018
  var Session = class {
17780
18019
  transcript;
@@ -17803,6 +18042,15 @@ function idsOf(files) {
17803
18042
  for (const list of Object.values(ids)) list.sort();
17804
18043
  return ids;
17805
18044
  }
18045
+ /**
18046
+ * The part `devices` (WISP 06 § What moves): the earlier device sets of the giver's record, so the device that takes
18047
+ * the turn puts their tombstones and delivers their frames. None when the record holds none: a profile that never
18048
+ * removed a device moves as it did before the part.
18049
+ */
18050
+ var DEVICES_PART = "devices";
18051
+ function devicesBytes(record) {
18052
+ return record?.earlierSets.length ? new TextEncoder().encode(JSON.stringify({ earlierSets: record.earlierSets })) : null;
18053
+ }
17806
18054
  /** Files over the taker's limit stay behind for later (WISP 06 § User experience, "Bring large files later"). */
17807
18055
  var isLater = (file, later) => !!later && later > 0 && file.size > later;
17808
18056
  /**
@@ -18242,7 +18490,7 @@ var HandoffGiver = class {
18242
18490
  const allowed = handoffAttemptAllowed(record.handoffAttempts?.[from], this.now());
18243
18491
  if (allowed !== "ok") return busy(allowed, allowed === "refused" ? 0 : handoffRetryAfter(record.handoffAttempts?.[from], this.now()));
18244
18492
  await this.ports.records.amend({ handoffAttempts: {
18245
- ...record.handoffAttempts,
18493
+ ...setAttempts(record, record.handoffAttempts),
18246
18494
  [from]: handoffAttemptFailed(record.handoffAttempts?.[from], this.now())
18247
18495
  } });
18248
18496
  this.begin(from, request.id, record);
@@ -18300,10 +18548,9 @@ var HandoffGiver = class {
18300
18548
  throw error;
18301
18549
  }
18302
18550
  const record = await this.ports.records.read();
18303
- await this.ports.records.amend({ handoffAttempts: {
18304
- ...record?.handoffAttempts,
18305
- [from]: handoffAttemptSucceeded()
18306
- } });
18551
+ const attempts = record ? setAttempts(record, record.handoffAttempts) : {};
18552
+ delete attempts[from];
18553
+ await this.ports.records.amend({ handoffAttempts: attempts });
18307
18554
  this.authorized(session, key);
18308
18555
  }
18309
18556
  wrongPassword(from) {
@@ -18371,12 +18618,13 @@ var HandoffGiver = class {
18371
18618
  });
18372
18619
  const parts = [...send];
18373
18620
  if (pass === 2) {
18374
- this.bundleMade ??= this.ports.source.bundle().then((bytes) => ({
18621
+ this.bundleMade ??= Promise.all([this.ports.source.bundle(), this.ports.records.read()]).then(([bytes, record]) => ({
18375
18622
  bytes,
18376
- digest: toBase64Url(sha256(bytes))
18623
+ digest: toBase64Url(sha256(bytes)),
18624
+ devices: devicesBytes(record)
18377
18625
  }));
18378
18626
  const made = this.bundleMade;
18379
- const { bytes: bundle, digest } = await made.catch((error) => {
18627
+ const { bytes: bundle, digest, devices } = await made.catch((error) => {
18380
18628
  if (this.bundleMade === made) this.bundleMade = null;
18381
18629
  throw error;
18382
18630
  });
@@ -18395,6 +18643,19 @@ var HandoffGiver = class {
18395
18643
  bundle.length,
18396
18644
  digest
18397
18645
  ];
18646
+ this.devicesPart = devices && [
18647
+ DEVICES_PART,
18648
+ devices.length,
18649
+ toBase64Url(sha256(devices))
18650
+ ];
18651
+ if (this.devicesPart) {
18652
+ parts.push(this.devicesPart);
18653
+ out.push({
18654
+ name: DEVICES_PART,
18655
+ size: devices.length,
18656
+ read: async (offset, length) => devices.subarray(offset, offset + length)
18657
+ });
18658
+ }
18398
18659
  }
18399
18660
  this.planned = {
18400
18661
  total: parts.reduce((sum, part) => sum + part[1], 0),
@@ -18427,6 +18688,7 @@ var HandoffGiver = class {
18427
18688
  else this.arm(HANDOFF_TIMINGS.verifiedMs, () => this.backToActive());
18428
18689
  }
18429
18690
  bundlePart = null;
18691
+ devicesPart = null;
18430
18692
  bundleMade = null;
18431
18693
  paused = false;
18432
18694
  stallTimer;
@@ -18469,7 +18731,11 @@ var HandoffGiver = class {
18469
18731
  const h = readHandoffVerified(frame, this.ports.turnAddress, this.turn + 1, fromBase64Url(from));
18470
18732
  if (!h) return;
18471
18733
  const later = new Set(this.laterParts.map((part) => part[2]));
18472
- const parts = [...fileParts(this.allFiles.filter((file) => !later.has(file.sha256))), this.bundlePart];
18734
+ const parts = [
18735
+ ...fileParts(this.allFiles.filter((file) => !later.has(file.sha256))),
18736
+ this.bundlePart,
18737
+ ...this.devicesPart ? [this.devicesPart] : []
18738
+ ];
18473
18739
  const expected = handoffDigest(this.turn + 1, this.ports.ownKey, fromBase64Url(from), parts);
18474
18740
  if (toBase64Url(expected) !== toBase64Url(h)) {
18475
18741
  this.out(handoffCancelFrame("damaged"));
@@ -22097,6 +22363,29 @@ var db = {
22097
22363
  }
22098
22364
  },
22099
22365
  /**
22366
+ * The oldest `limit` messages of a chat after `after` (and before `before`, when given), oldest first, and whether
22367
+ * newer ones remain in that window. Reads those rows only: a bot that reads what came since its last message costs
22368
+ * a page, where reading the whole history and cutting it cost 94 ms of the daemon's time a call at 7,000 messages.
22369
+ */
22370
+ async getMessagePageAfter(linkId, { limit, before, after }) {
22371
+ const upper = before?.timestamp ?? Infinity;
22372
+ if (after.timestamp > upper || after.timestamp === upper && (after.id === void 0 || before?.id === void 0)) return {
22373
+ messages: [],
22374
+ more: false
22375
+ };
22376
+ const range = IDBKeyRange.bound([linkId, after.timestamp], [linkId, upper], after.id === void 0, !!before && before.id === void 0);
22377
+ const kept = (m) => !(after.id !== void 0 && m.timestamp === after.timestamp && m.id <= after.id) && !(before?.id !== void 0 && m.timestamp === before.timestamp && m.id >= before.id);
22378
+ for (let want = limit + 1;;) {
22379
+ const oldest = await wrap((await store(STORES$1.messages, "readonly")).index("byLinkTime").getAll(range, want));
22380
+ const page = oldest.filter(kept);
22381
+ if (page.length > limit || oldest.length < want) return {
22382
+ messages: page.slice(0, limit),
22383
+ more: page.length > limit
22384
+ };
22385
+ want += oldest.length - page.length;
22386
+ }
22387
+ },
22388
+ /**
22100
22389
  * Every message of this profile that carries a task, a routine or a usage card, from every chat and group, oldest first (time,
22101
22390
  * then id). Reads the card index only (`CARD_INDEX`): no chat's history is read, however long. The index follows the
22102
22391
  * rows, so an edit's card, a deleted message and a deleted chat or group are in step with no bookkeeping.
@@ -23094,6 +23383,8 @@ var COMMUNITY_TIMINGS = {
23094
23383
  newcomerMs: 3e4
23095
23384
  };
23096
23385
  var KNOCK_BELL = 0;
23386
+ /** What `CommunitySession.join` says of a welcome whose entry is not the link's: the link was replaced since. */
23387
+ var LINK_REPLACED = "This link was replaced or turned off";
23097
23388
  var knockRecord = (link, n) => ({
23098
23389
  g: `${link.g}.${n}`,
23099
23390
  host: link.host
@@ -23427,6 +23718,7 @@ var Communities = class {
23427
23718
  /** How far a join through the link got, as the joiner's app knows it. */
23428
23719
  joinStage(group) {
23429
23720
  const joining = group.joining;
23721
+ if (joining.replaced) return "replaced";
23430
23722
  if (joining.inviter) return "admitted";
23431
23723
  if (this.host.linkReady(joining.linkId, 2) || this.host.linkSeen?.(joining.linkId)) return "answered";
23432
23724
  return this.knocked.has(group.id) ? "knocked" : "knocking";
@@ -23749,7 +24041,7 @@ var Communities = class {
23749
24041
  };
23750
24042
  for (const group of [...this.stored.values()]) {
23751
24043
  const live = this.live.get(group.id);
23752
- if (group.joining && (this.knocking(group, live) || group.joining.check) && !this.gaveUp.has(group.id)) {
24044
+ if (group.joining && (this.knocking(group, live) || group.joining.check) && !this.gaveUp.has(group.id) && !group.joining.replaced) {
23753
24045
  const knocking = this.knocking(group, live), waited = now - group.joining.since;
23754
24046
  const answered = this.host.linkReady(group.joining.linkId, 2) || !!this.host.linkSeen?.(group.joining.linkId);
23755
24047
  const since = this.knockingSince.get(group.id);
@@ -23805,6 +24097,10 @@ var Communities = class {
23805
24097
  live.lingering.delete(linkId);
23806
24098
  if ([...this.host.entries(groupId).values()].includes(linkId)) await this.host.closeEdge(linkId);
23807
24099
  }
24100
+ if (live.doorKey && live.doorKey !== s.entryKey) {
24101
+ live.doorKey = void 0;
24102
+ await this.closeEntries(groupId);
24103
+ }
23808
24104
  const alone = live.hub && !freshHubs(this.hubs(live), now).some((h) => h.key !== me);
23809
24105
  if ((live.beaconFailedAt ? now - live.beaconFailedAt >= BEACON_RETRY_MS : now - live.lastBeaconRead >= this.beaconEvery(groupId, live, alone)) || live.lastBeaconRead === 0) await this.readBeacon(groupId, live, now);
23810
24106
  if (!live.beaconKnown) {
@@ -24523,6 +24819,7 @@ var Communities = class {
24523
24819
  if (live.members.size >= this.capacity(groupId, live, now)) break;
24524
24820
  if (this.host.adminTurn && !await this.host.adminTurn(groupId, { wait: false })) break;
24525
24821
  live.pendingEntries.set(key, now);
24822
+ live.doorKey = link.host;
24526
24823
  traceJoin(groupId, "knock.seen", {
24527
24824
  age: now - ts,
24528
24825
  turn
@@ -24677,6 +24974,7 @@ var Communities = class {
24677
24974
  const live = this.live.get(g);
24678
24975
  const peer = [...this.host.entries(g)].find(([, id]) => id === linkId)?.[0];
24679
24976
  if (!live || !peer || frame.key !== peer || !live.pendingEntries.has(peer)) return;
24977
+ if (live.doorKey !== live.session.entryKey) return;
24680
24978
  let welcome;
24681
24979
  try {
24682
24980
  welcome = rosterHas(live.session.roster, peer) ? await live.session.rewelcome(peer) : await live.session.admit(peer, this.now());
@@ -24716,6 +25014,23 @@ var Communities = class {
24716
25014
  g,
24717
25015
  host: joining.host
24718
25016
  }, joining.pieces, frame, joining.seedB64);
25017
+ if ("error" in joined && joined.error === LINK_REPLACED && !joining.check) {
25018
+ joining.replaced = true;
25019
+ joining.inviter = "";
25020
+ joining.pieces = [];
25021
+ if (this.knocked.has(g)) this.unknock({
25022
+ g,
25023
+ host: joining.host
25024
+ }, this.knockAt.get(g) ?? KNOCK_BELL, joining.seedB64).catch(() => {});
25025
+ this.knocked.delete(g);
25026
+ this.knockAt.delete(g);
25027
+ countWaitingJoin(this.host, g, this.now(), false);
25028
+ traceJoin(g, "join.replaced");
25029
+ await this.store.putGroup(group);
25030
+ await this.host.closeEdge(linkId);
25031
+ this.host.emit();
25032
+ return;
25033
+ }
24719
25034
  if ("error" in joined) {
24720
25035
  joining.pieces = [];
24721
25036
  return;
@@ -28083,7 +28398,7 @@ var Groups = class {
28083
28398
  if (!viaLink) await this.sessions.get(g).setNick(group.invitation.admin, this.host.contactName(linkId));
28084
28399
  const session = this.sessions.get(g);
28085
28400
  for (const [key, nick] of Object.entries(group.formerNames ?? {})) if (!session.state.nicks[key]) await session.setNick(key, nick);
28086
- await this.event(g, "joined", `You joined. ${GROUP_READ_NOTE}`, Date.now(), joined.state.chain.length - 1);
28401
+ await this.event(g, "joined", group.invitation.genesis ? "You joined again" : `You joined. ${GROUP_READ_NOTE}`, Date.now(), joined.state.chain.length - 1);
28087
28402
  if (viaLink) traceJoin(g, "welcome.received");
28088
28403
  if (viaLink) {
28089
28404
  this.lastKnock.delete(g);
@@ -28907,13 +29222,17 @@ var Groups = class {
28907
29222
  for (const [key] of after) if (!rosterHas(before, key) && key !== session.myKey) await this.event(groupId, "joined", `${name(key)} joined`, when, top.e, key);
28908
29223
  const gone = before.filter(([key]) => !rosterHas(after, key)).map(([key]) => key);
28909
29224
  this.hubs.removed(groupId, gone, this.now());
28910
- const left = (key) => {
28911
- const chain = session.state.chain;
28912
- for (let e = chain.length - 1; e > 0; e--) if (chain[e].k === "remove" && chain[e].s === key) return !!session.state.leftMarks?.[e];
28913
- return false;
29225
+ const chain = session.state.chain;
29226
+ const removal = (key) => {
29227
+ for (let e = chain.length - 1; e > 0; e--) if (chain[e].k === "remove" && chain[e].s === key) return e;
29228
+ return -1;
28914
29229
  };
28915
- for (const key of gone) if (left(key)) await this.event(groupId, "left", `${name(key)} left`, when, top.e, key);
28916
- else await this.event(groupId, "gone", `${name(key)} is no longer a member`, when, top.e, key);
29230
+ for (const key of gone) {
29231
+ const e = removal(key), by = e > 0 && chain[e].by !== key ? chain[e].by : void 0;
29232
+ if (e > 0 && session.state.leftMarks?.[e]) await this.event(groupId, "left", `${name(key)} left`, when, top.e, key);
29233
+ else if (by) await this.event(groupId, "gone", `${name(by)} removed ${name(key)}`, when, top.e, key, by);
29234
+ else await this.event(groupId, "gone", `${name(key)} is no longer a member`, when, top.e, key);
29235
+ }
28917
29236
  if (top.k === "role") await this.event(groupId, "admin", `${name(top.s)} ${top.s === session.myKey ? "are" : "is"} now the admin`, when, top.e, top.s);
28918
29237
  if (top.k === "rotate") await this.event(groupId, "rotated", "Keys rotated: a fresh epoch", when, top.e);
28919
29238
  }
@@ -28966,7 +29285,7 @@ var Groups = class {
28966
29285
  }
28967
29286
  /** `member`: whom it is about, so the apps can name them as they are known now, not as they were then. */
28968
29287
  /** A line in the group's history; lines at the same time (two members gone in one change) get distinct ones, see `eventTime`. */
28969
- async event(groupId, event, text, timestamp, epoch, member) {
29288
+ async event(groupId, event, text, timestamp, epoch, member, by) {
28970
29289
  timestamp = eventTime(this.eventTimes, groupId, timestamp);
28971
29290
  const id = `event:${epoch}:${event}:${timestamp}`;
28972
29291
  this.lineOrder.placing(MESSAGE_LINK(groupId), {
@@ -28980,6 +29299,7 @@ var Groups = class {
28980
29299
  sender: "peer",
28981
29300
  event,
28982
29301
  member,
29302
+ ...by && { by },
28983
29303
  timestamp,
28984
29304
  via: "datalink"
28985
29305
  }) !== false);
@@ -29581,13 +29901,14 @@ var GroupEdits = class {
29581
29901
  }
29582
29902
  /**
29583
29903
  * An edit from a member, authenticated as `sender` by the group. Believed only while the sender is in the group (a
29584
- * removed member's edits are dropped) and only of the sender's own message; the highest number wins. One of a message
29904
+ * removed member's edits are dropped) and only of the sender's own message; the highest number wins. In a private
29905
+ * group a removal stands once its author is out too (`outlives`): the group took it under the epoch rules. One of a message
29585
29906
  * not here yet waits a minute for it. Past `EDIT_RECEIVE_LIMIT` a window from one member, the rest wait for the next
29586
29907
  * window (`hold`): a catch-up hands back every edit of an author at once, and one dropped is never handed again.
29587
29908
  */
29588
29909
  async receive(groupId, sender, edit) {
29589
29910
  const membership = this.host.membership(groupId);
29590
- if (!membership?.members.has(sender) || sender === membership.me || !edit.id.startsWith(`${sender}:`)) return "dropped";
29911
+ if (!membership || !(membership.members.has(sender) || outlives(membership, edit)) || sender === membership.me || !edit.id.startsWith(`${sender}:`)) return "dropped";
29591
29912
  const key = `${groupId}\n${sender}`;
29592
29913
  let pace = this.receivePace.get(key);
29593
29914
  if (!pace) this.receivePace.set(key, pace = new RateWindow(30, EDIT_RATE_WINDOW_MS, this.now));
@@ -29631,10 +29952,14 @@ var GroupEdits = class {
29631
29952
  if (this.stopped || !group || !waiting || !pace) return;
29632
29953
  for (const [id, edit] of [...waiting]) {
29633
29954
  const membership = this.host.membership(groupId);
29634
- if (!membership?.members.has(sender)) {
29955
+ if (!membership) {
29635
29956
  waiting.clear();
29636
29957
  break;
29637
29958
  }
29959
+ if (!membership.members.has(sender) && !outlives(membership, edit)) {
29960
+ waiting.delete(id);
29961
+ continue;
29962
+ }
29638
29963
  if (!pace.take()) break;
29639
29964
  if (waiting.get(id) !== edit) continue;
29640
29965
  waiting.delete(id);
@@ -29808,6 +30133,14 @@ var GroupEdits = class {
29808
30133
  else this.held.delete(groupId);
29809
30134
  }
29810
30135
  };
30136
+ /**
30137
+ * A private group's removal (WISP 902 § Edits): it stands once its author left or was removed, since it only takes
30138
+ * away what the author wrote while in. The group's session checked it (signed by the author, for an epoch the author
30139
+ * and I were both in, handed on by a member). A community's member out of it edits nothing at all.
30140
+ */
30141
+ function outlives(membership, edit) {
30142
+ return edit.rm === true && !membership.community;
30143
+ }
29811
30144
  //#endregion
29812
30145
  //#region ../browser/src/shared/payLinks.ts
29813
30146
  /**
@@ -32127,6 +32460,26 @@ var S3Store = class {
32127
32460
  }
32128
32461
  };
32129
32462
  //#endregion
32463
+ //#region ../browser/src/shared/refusals.ts
32464
+ /** The English line for `notice`, stored as the row's `text`. */
32465
+ function refusedText(notice) {
32466
+ return `Could not receive ${notice.method === "fedimint" ? "Fedimint ecash" : notice.amount === void 0 ? "a payment" : `${notice.amount.toLocaleString("en-US")} ${notice.network === "testnet" ? "test sats" : "sats"}`}: ${notice.reason}`;
32467
+ }
32468
+ /** The row the engine stores for a refusal: the values, and their English as the text. */
32469
+ function refusedRow(notice) {
32470
+ const values = {
32471
+ type: "paymentRefused",
32472
+ ...notice.amount !== void 0 && { amount: notice.amount },
32473
+ ...notice.network && { network: notice.network },
32474
+ ...notice.method && { method: notice.method },
32475
+ reason: notice.reason
32476
+ };
32477
+ return {
32478
+ text: refusedText(values),
32479
+ notice: values
32480
+ };
32481
+ }
32482
+ //#endregion
32130
32483
  //#region ../browser/src/engine/wallet.ts
32131
32484
  /**
32132
32485
  * The peer's Cashu wallet. Ecash is custodial: the mint holds the sats and the
@@ -32184,6 +32537,8 @@ var SwapUnsettledError = class extends Error {
32184
32537
  };
32185
32538
  /** When a swap with no answer can no longer reach the mint: a request's longest life, and a margin after its last try. */
32186
32539
  var swapOverdueAt = (swap) => Math.max(swap.createdAt + CASHU_REQUEST_TIMEOUT_MS + SWAP_SETTLED_MS, (swap.attemptEndedAt ?? Number.POSITIVE_INFINITY) + SWAP_SETTLED_MS);
32540
+ /** When a melt with no answer can no longer reach the mint: its one request is sent right after it is written down. */
32541
+ var meltOverdueAt = (melt) => melt.createdAt + CASHU_REQUEST_TIMEOUT_MS + SWAP_SETTLED_MS;
32187
32542
  var swapOf = (swap) => swap.swap;
32188
32543
  function normalizeMintUrl(input) {
32189
32544
  let url;
@@ -32547,7 +32902,7 @@ var CashuWallet = class CashuWallet {
32547
32902
  const quote = await wrap((await store(STORES$1.quotes, "readonly")).get(id));
32548
32903
  if (!quote || quote.issuedUnclaimed || quote.held) return null;
32549
32904
  const wallet = await this.wallet(quote.mint);
32550
- const { OutputData, isMintOperationError } = await loadCashu();
32905
+ const { OutputData } = await loadCashu();
32551
32906
  const answer = await wallet.checkMintQuoteBolt11(quote.quote);
32552
32907
  const { state } = answer;
32553
32908
  if (state === "UNPAID") {
@@ -32580,7 +32935,7 @@ var CashuWallet = class CashuWallet {
32580
32935
  try {
32581
32936
  proofs = await wallet.completeMint(preview);
32582
32937
  } catch (error) {
32583
- if (saved && isMintOperationError(error) && (await wallet.checkMintQuoteBolt11(quote.quote).catch(() => null))?.state === "PAID") {
32938
+ if (mintRefused(error) && (await wallet.checkMintQuoteBolt11(quote.quote).catch(() => null))?.state === "PAID") {
32584
32939
  const { outputs: _refused, ...fresh } = written;
32585
32940
  await committed((await store(STORES$1.quotes, "readwrite")).put(fresh));
32586
32941
  }
@@ -33069,11 +33424,11 @@ var CashuWallet = class CashuWallet {
33069
33424
  * `pollSwaps` settles it. Runs under the mint's lock.
33070
33425
  */
33071
33426
  async completeSwap(swap) {
33072
- const { deserializeSwapPreview, isMintOperationError } = await loadCashu();
33427
+ const { deserializeSwapPreview } = await loadCashu();
33073
33428
  try {
33074
33429
  return await (await this.wallet(swap.mint)).completeSwap(deserializeSwapPreview(swapOf(swap)));
33075
33430
  } catch (error) {
33076
- const refused = isMintOperationError(error) && swap.attemptEndedAt === void 0;
33431
+ const refused = mintRefused(error) && swap.attemptEndedAt === void 0;
33077
33432
  const ended = {
33078
33433
  ...swap,
33079
33434
  attemptEndedAt: Date.now()
@@ -33325,7 +33680,7 @@ var CashuWallet = class CashuWallet {
33325
33680
  if (stuck === 1) this.events.onChange();
33326
33681
  later(wait);
33327
33682
  } else if (outcome.idle && swap.kind === "receive" && !swap.released) {
33328
- const { deserializeSwapPreview, isMintOperationError } = await loadCashu();
33683
+ const { deserializeSwapPreview } = await loadCashu();
33329
33684
  try {
33330
33685
  const { keep } = await (await this.wallet(mint)).completeSwap(deserializeSwapPreview(swapOf(swap)));
33331
33686
  if (await this.finishSwap(swap, keep, [], true)) {
@@ -33340,7 +33695,7 @@ var CashuWallet = class CashuWallet {
33340
33695
  attemptEndedAt: Date.now()
33341
33696
  };
33342
33697
  await committed((await store(STORES$1.swaps, "readwrite")).put(swap));
33343
- const refusal = isMintOperationError(error) ? await this.swapOutcome(swap, true).catch(() => void 0) : void 0;
33698
+ const refusal = mintRefused(error) ? await this.swapOutcome(swap, true).catch(() => void 0) : void 0;
33344
33699
  if (refusal?.state === "done") {
33345
33700
  if (await this.finishSwap(swap, refusal.keep, refusal.send, true)) {
33346
33701
  const told = await this.tellSwap(swap, true);
@@ -33451,7 +33806,7 @@ var CashuWallet = class CashuWallet {
33451
33806
  }
33452
33807
  async melt(quoteId, mint, note, paymentId) {
33453
33808
  const wallet = await this.wallet(mint);
33454
- const { MeltChangeError, OutputData, isMintOperationError } = await loadCashu();
33809
+ const { MeltChangeError, OutputData } = await loadCashu();
33455
33810
  const quote = await wallet.checkMeltQuoteBolt11(quoteId);
33456
33811
  if ((await wrap((await store(STORES$1.melts, "readonly")).getAll())).some((m) => m.quote === quote.quote || m.request === quote.request)) throw new Error("This invoice is already being paid");
33457
33812
  const shown = this.shownQuotes.get(quoteId);
@@ -33495,8 +33850,8 @@ var CashuWallet = class CashuWallet {
33495
33850
  try {
33496
33851
  result = await wallet.completeMelt(preview);
33497
33852
  } catch (error) {
33498
- if (!isMintOperationError(error) && !(error instanceof MeltChangeError)) return "pending";
33499
- const outcome = await this.settleMelt(melt).catch(() => "pending");
33853
+ if (!mintRefused(error) && !(error instanceof MeltChangeError)) return "pending";
33854
+ const outcome = await this.settleMelt(melt, true).catch(() => "pending");
33500
33855
  if (outcome === "unpaid") {
33501
33856
  const lost = this.takeFailedFee(melt.quote);
33502
33857
  if (this.spentAway.delete(melt.quote)) throw Object.assign(engineError("ecashAlreadySpent"), { cause: error });
@@ -33509,7 +33864,7 @@ var CashuWallet = class CashuWallet {
33509
33864
  await this.finishMelt(melt, result.change);
33510
33865
  return "paid";
33511
33866
  }
33512
- return this.settleMelt(melt).catch(() => "pending");
33867
+ return this.settleMelt(melt, true).catch(() => "pending");
33513
33868
  }
33514
33869
  /**
33515
33870
  * Whether a Lightning payment of this invoice is written down as in flight. A melt is written before the mint sees
@@ -33541,9 +33896,10 @@ var CashuWallet = class CashuWallet {
33541
33896
  /**
33542
33897
  * Asks the mint where a recorded melt stands and books the answer. Paid: the reserved proofs are gone and
33543
33898
  * the change is ours. Unpaid: what the mint says is unspent is spendable again. Pending: nothing moves.
33544
- * Throws when the mint cannot be asked, and the melt stays as it is.
33899
+ * Throws when the mint cannot be asked, and the melt stays as it is. `answered`: the mint answered the melt request
33900
+ * itself, so it has acted on it; without that, an unpaid quote may only mean the request has not landed yet.
33545
33901
  */
33546
- async settleMelt(melt) {
33902
+ async settleMelt(melt, answered = false) {
33547
33903
  const wallet = await this.wallet(melt.mint);
33548
33904
  const { Amount, OutputData } = await loadCashu();
33549
33905
  const quote = await wallet.checkMeltQuoteBolt11(melt.quote);
@@ -33562,6 +33918,7 @@ var CashuWallet = class CashuWallet {
33562
33918
  return "paid";
33563
33919
  }
33564
33920
  if (quote.state === "PENDING") return "pending";
33921
+ if (!answered && Date.now() < meltOverdueAt(melt)) return "pending";
33565
33922
  const inputs = await this.reservedProofs(melt);
33566
33923
  const states = inputs.length > 0 ? await wallet.checkProofsStates(inputs) : [];
33567
33924
  if (states.some((s) => s.state === "PENDING")) return "pending";
@@ -33616,20 +33973,26 @@ var CashuWallet = class CashuWallet {
33616
33973
  */
33617
33974
  async forget(mints, acceptLoss = false) {
33618
33975
  const at = new Set(mints);
33619
- if ((await wrap((await store(STORES$1.melts, "readonly")).getAll())).some((m) => at.has(m.mint))) throw new Error("A Lightning payment from this wallet is still in flight: wait for it to settle, then remove the wallet.");
33976
+ const inFlight = async () => {
33977
+ if ((await wrap((await store(STORES$1.melts, "readonly")).getAll())).some((m) => at.has(m.mint))) throw new Error("A Lightning payment from this wallet is still in flight: wait for it to settle, then remove the wallet.");
33978
+ };
33979
+ await inFlight();
33620
33980
  await this.pollSwaps(mints).catch(() => {});
33621
- if ((await wrap((await store(STORES$1.swaps, "readonly")).getAll())).filter((s) => at.has(s.mint) && !s.released).length > 0 && !acceptLoss) throw new Error("An exchange of ecash with this wallet's mint is not finished yet: wait for the mint to answer, or confirm that what it would bring is lost to remove the wallet.");
33622
- const proofs = (await this.allProofs()).filter((p) => at.has(p.mint));
33623
- const quotes = (await wrap((await store(STORES$1.quotes, "readonly")).getAll())).filter((q) => at.has(q.mint));
33624
- const swaps = (await wrap((await store(STORES$1.swaps, "readonly")).getAll())).filter((s) => at.has(s.mint));
33625
- await transact([
33626
- STORES$1.proofs,
33627
- STORES$1.quotes,
33628
- STORES$1.swaps
33629
- ], (stores) => {
33630
- for (const p of proofs) stores[STORES$1.proofs].delete(p.secret);
33631
- for (const q of quotes) stores[STORES$1.quotes].delete(q.quote);
33632
- for (const s of swaps) stores[STORES$1.swaps].delete(s.id);
33981
+ await this.lockedAll(mints, async () => {
33982
+ await inFlight();
33983
+ if ((await wrap((await store(STORES$1.swaps, "readonly")).getAll())).filter((s) => at.has(s.mint) && !s.released).length > 0 && !acceptLoss) throw new Error("An exchange of ecash with this wallet's mint is not finished yet: wait for the mint to answer, or confirm that what it would bring is lost to remove the wallet.");
33984
+ const proofs = (await this.allProofs()).filter((p) => at.has(p.mint));
33985
+ const quotes = (await wrap((await store(STORES$1.quotes, "readonly")).getAll())).filter((q) => at.has(q.mint));
33986
+ const swaps = (await wrap((await store(STORES$1.swaps, "readonly")).getAll())).filter((s) => at.has(s.mint));
33987
+ await transact([
33988
+ STORES$1.proofs,
33989
+ STORES$1.quotes,
33990
+ STORES$1.swaps
33991
+ ], (stores) => {
33992
+ for (const p of proofs) stores[STORES$1.proofs].delete(p.secret);
33993
+ for (const q of quotes) stores[STORES$1.quotes].delete(q.quote);
33994
+ for (const s of swaps) stores[STORES$1.swaps].delete(s.id);
33995
+ });
33633
33996
  });
33634
33997
  for (const mint of mints) {
33635
33998
  this.wallets.delete(mint);
@@ -33691,6 +34054,10 @@ var CashuWallet = class CashuWallet {
33691
34054
  this.locks.set(mint, next.catch(() => {}));
33692
34055
  return next;
33693
34056
  }
34057
+ /** `task` under the locks of every one of `mints`, taken in one order (no other task holds two, so none waits on this one). */
34058
+ lockedAll(mints, task) {
34059
+ return [...new Set(mints)].sort().reduceRight((inner, mint) => () => this.locked(mint, inner), task)();
34060
+ }
33694
34061
  async allProofs() {
33695
34062
  return wrap((await store(STORES$1.proofs, "readonly")).getAll());
33696
34063
  }
@@ -33740,8 +34107,18 @@ function parseSats(value, asset) {
33740
34107
  if (asset !== UNIT || !/^[1-9]\d{0,8}$/.test(value)) return null;
33741
34108
  return Number(value);
33742
34109
  }
33743
- /** Paying in ecash failed before any token existed, so nothing reached the contact and Lightning is safe to try. */
33744
- var NoEcashError = class extends Error {};
34110
+ /**
34111
+ * Paying in ecash failed before any token existed, so nothing reached the contact and Lightning is safe to try. The
34112
+ * wallet's `engineCode` and `values` stay on it: a host reads why by them (the CLI's `refused`, the app's words).
34113
+ */
34114
+ var NoEcashError = class extends Error {
34115
+ constructor(cause) {
34116
+ super(cause instanceof Error ? cause.message : String(cause));
34117
+ const { engineCode, values } = cause ?? {};
34118
+ if (engineCode !== void 0) Object.assign(this, { engineCode });
34119
+ if (values !== void 0) Object.assign(this, { values });
34120
+ }
34121
+ };
33745
34122
  var arkSats = (network) => network === "bitcoin" ? "sats" : "test sats";
33746
34123
  /** The English line kept with a payment message (the CLI and older apps show it): test sats say so. */
33747
34124
  var satsOn = (network) => network === "testnet" ? "test sats" : "sats";
@@ -34962,11 +35339,17 @@ var PaymentDesk = class {
34962
35339
  });
34963
35340
  const sats = parseSats(payment.amount.value, payment.amount.asset);
34964
35341
  const spent = error instanceof EngineError && error.engineCode === "ecashAlreadySpent";
35342
+ const network = inspected?.kind === "token" ? mintNetwork(inspected.mint) : void 0;
35343
+ const line = refusedRow({
35344
+ amount: sats ?? void 0,
35345
+ network,
35346
+ reason
35347
+ });
34965
35348
  try {
34966
35349
  await this.host.storeMessage({
34967
35350
  linkId,
34968
35351
  id: spent ? `peer_spent_${digestHex(token).slice(0, 32)}` : `peer_${payment.timestamp}_refused`,
34969
- text: `Could not receive ${sats === null ? "a payment" : `${sats.toLocaleString()} sats`}: ${reason}`,
35352
+ ...line,
34970
35353
  sender: "peer",
34971
35354
  timestamp: payment.timestamp,
34972
35355
  via: "datalink"
@@ -35033,11 +35416,16 @@ var PaymentDesk = class {
35033
35416
  ok: false,
35034
35417
  error: reason
35035
35418
  });
35419
+ const line = refusedRow({
35420
+ amount: record.amount,
35421
+ network: record.mint ? mintNetwork(record.mint) : void 0,
35422
+ reason
35423
+ });
35036
35424
  try {
35037
35425
  await this.host.storeMessage({
35038
35426
  linkId: record.linkId,
35039
35427
  id: `peer_${record.createdAt}_refused`,
35040
- text: `Could not receive ${record.amount.toLocaleString()} sats: ${reason}`,
35428
+ ...line,
35041
35429
  sender: "peer",
35042
35430
  timestamp: record.createdAt,
35043
35431
  via: "datalink"
@@ -35973,17 +36361,23 @@ var PaymentDesk = class {
35973
36361
  });
35974
36362
  return;
35975
36363
  }
35976
- const refuse = async (reason) => {
36364
+ const refuse = async (reason, network) => {
35977
36365
  link?.sendPaymentResult({
35978
36366
  id: payment.id,
35979
36367
  ok: false,
35980
36368
  error: reason
35981
36369
  });
36370
+ const line = refusedRow({
36371
+ amount: parseSats(payment.amount.value, payment.amount.asset) ?? void 0,
36372
+ network,
36373
+ method: "fedimint",
36374
+ reason
36375
+ });
35982
36376
  try {
35983
36377
  await this.host.storeMessage({
35984
36378
  linkId,
35985
36379
  id: `peer_${payment.timestamp}_refused`,
35986
- text: `Could not receive Fedimint ecash: ${reason}`,
36380
+ ...line,
35987
36381
  sender: "peer",
35988
36382
  timestamp: payment.timestamp,
35989
36383
  via: "datalink"
@@ -36019,7 +36413,7 @@ var PaymentDesk = class {
36019
36413
  }
36020
36414
  const network = this.fedimintOf(found.federation)?.federation(found.federation)?.network;
36021
36415
  if (network && !this.accepts(linkId, "fedimint", walletNetworkOf(network))) {
36022
- await refuse(`${networkLabel(walletNetworkOf(network))} Fedimint is off in this chat`);
36416
+ await refuse(`${networkLabel(walletNetworkOf(network))} Fedimint is off in this chat`, walletNetworkOf(network));
36023
36417
  return;
36024
36418
  }
36025
36419
  const digest = fedimintNotesDigest(notes);
@@ -36096,11 +36490,17 @@ var PaymentDesk = class {
36096
36490
  ok: false,
36097
36491
  error: "These notes were already redeemed"
36098
36492
  });
36493
+ const line = refusedRow({
36494
+ amount: payment.amount,
36495
+ network: payment.network,
36496
+ method: "fedimint",
36497
+ reason: "These notes were already redeemed"
36498
+ });
36099
36499
  try {
36100
36500
  await this.host.storeMessage({
36101
36501
  linkId: payment.linkId,
36102
36502
  id: `peer_${payment.createdAt}_refused`,
36103
- text: "Could not receive Fedimint ecash: These notes were already redeemed",
36503
+ ...line,
36104
36504
  sender: "peer",
36105
36505
  timestamp: payment.createdAt,
36106
36506
  via: "datalink"
@@ -36294,7 +36694,7 @@ var PaymentDesk = class {
36294
36694
  paidFrom = created.mint;
36295
36695
  this.payments.set(id, record(created.token, created.mint));
36296
36696
  } catch (error) {
36297
- throw new NoEcashError(error instanceof Error ? error.message : String(error));
36697
+ throw new NoEcashError(error);
36298
36698
  }
36299
36699
  this.host.onChange();
36300
36700
  await this.host.storeMessage({
@@ -36865,7 +37265,11 @@ var WalletSetup = class {
36865
37265
  };
36866
37266
  //#endregion
36867
37267
  //#region ../browser/src/engine/node.ts
36868
- /** How long a chat waits before listening again after its HyperDHT relay went away. */
37268
+ /**
37269
+ * How long a chat waits, on average, before listening again after its HyperDHT relay went away. Each app draws its own
37270
+ * wait within half of it either side: a relay that restarts closes every app's socket at once, and with one fixed wait
37271
+ * they all came back in the same instant, more listens than its one HyperDHT node sends out in time.
37272
+ */
36869
37273
  var RELAY_RETRY_MS = 3e4;
36870
37274
  /** Native listeners an app may hold per transport (the Desktop's Rust Iroh allows eight, `paired_transport.rs`). */
36871
37275
  var NATIVE_SLOTS = 8;
@@ -36910,6 +37314,8 @@ var DEFAULT_SETTINGS = {
36910
37314
  mints: [],
36911
37315
  mintsInitialized: false
36912
37316
  };
37317
+ /** A link's `removedRefs` with `ref`, the newest `MAX_DELETED_IDS`. */
37318
+ var withRemovedRef = (refs, ref) => [...(refs ?? []).filter((r) => r !== ref), ref].slice(-500);
36913
37319
  /**
36914
37320
  * A card that went on the DHT floor or into a hold goes again live (`restoreCards`) only for the newest this many
36915
37321
  * messages of a chat, sent within this long: an old chat's cards are not worth a burst of edits.
@@ -37207,6 +37613,7 @@ var GhostlyNode = class GhostlyNode {
37207
37613
  const key = type + ":" + id;
37208
37614
  if (this.feedbackIds.has(key)) return;
37209
37615
  this.feedbackIds.add(key);
37616
+ if (this.feedbackIds.size > 4096) this.feedbackIds.delete(this.feedbackIds.values().next().value);
37210
37617
  this.events.onAttention?.({
37211
37618
  type,
37212
37619
  id: key,
@@ -39466,6 +39873,10 @@ var GhostlyNode = class GhostlyNode {
39466
39873
  const message = await db.getMessage(linkId, id);
39467
39874
  return message && withoutFrame(message);
39468
39875
  }
39876
+ /**
39877
+ * A page of a chat's or a group's history: the newest `limit` (before `before`), or with `after` the oldest `limit`
39878
+ * after it (and before `before`). Each bound is a time or a message's place; only the page's rows are read.
39879
+ */
39469
39880
  async messagePage(asked) {
39470
39881
  const page = await this.storedPage(asked);
39471
39882
  return {
@@ -39473,23 +39884,29 @@ var GhostlyNode = class GhostlyNode {
39473
39884
  messages: page.messages.map(withoutFrame)
39474
39885
  };
39475
39886
  }
39476
- async storedPage({ linkId, limit = 50, before }) {
39887
+ async storedPage({ linkId, limit = 50, before, after }) {
39477
39888
  if (!Number.isSafeInteger(limit) || limit < 1) throw new Error("limit: a whole number of messages, at least 1");
39478
- if (before === void 0) return db.getMessagePage(linkId, { limit });
39479
- if (typeof before === "number") {
39480
- if (Number.isNaN(before)) throw new Error("before: a time or a message id");
39481
- return db.getMessagePage(linkId, {
39482
- limit,
39483
- before: { timestamp: before }
39484
- });
39485
- }
39486
- const from = await db.getMessage(linkId, before);
39487
- if (!from) throw new Error(`No message ${before}`);
39488
- return db.getMessagePage(linkId, {
39889
+ const end = before === void 0 ? void 0 : await this.pagePlace(linkId, before, "before");
39890
+ if (after === void 0) return db.getMessagePage(linkId, {
39891
+ limit,
39892
+ before: end
39893
+ });
39894
+ return db.getMessagePageAfter(linkId, {
39489
39895
  limit,
39490
- before: from
39896
+ before: end,
39897
+ after: await this.pagePlace(linkId, after, "after")
39491
39898
  });
39492
39899
  }
39900
+ /** A page's bound: a time, or the place of a message of the chat. */
39901
+ async pagePlace(linkId, bound, side) {
39902
+ if (typeof bound === "number") {
39903
+ if (Number.isNaN(bound)) throw new Error(`${side}: a time or a message id`);
39904
+ return { timestamp: bound };
39905
+ }
39906
+ const from = await db.getMessage(linkId, bound);
39907
+ if (!from) throw new Error(`No message ${bound}`);
39908
+ return from;
39909
+ }
39493
39910
  /** Saves a message on this device, or unsaves it (`engine/saved.ts`): nothing is sent. */
39494
39911
  saveMessage(params) {
39495
39912
  return this.saved.save(params);
@@ -40599,6 +41016,27 @@ var GhostlyNode = class GhostlyNode {
40599
41016
  break;
40600
41017
  }
40601
41018
  }
41019
+ if (!original && group && this.groups.isRemoved(message.linkId.slice(6), reply.id)) return {
41020
+ ...message,
41021
+ replyTo: {
41022
+ ...reply,
41023
+ snippet: "",
41024
+ messageId: reply.id
41025
+ }
41026
+ };
41027
+ const live = group ? void 0 : this.links.get(message.linkId)?.stored;
41028
+ if (!original && live?.removedRefs?.includes(reply.id)) {
41029
+ const row = [`peer_${reply.id}`, `me_${reply.id}`].find((id) => live.deletedIds?.includes(id));
41030
+ return {
41031
+ ...message,
41032
+ replyTo: {
41033
+ ...reply,
41034
+ snippet: "",
41035
+ messageId: row ?? reply.id,
41036
+ from: reply.from ?? (row?.startsWith("peer_") ? "peer" : "me")
41037
+ }
41038
+ };
41039
+ }
40602
41040
  if (!original && !group) {
40603
41041
  history = await db.getMessages(message.linkId);
40604
41042
  original = history.find((m) => m.id !== message.id && replyRef(m) === reply.id);
@@ -40763,17 +41201,28 @@ var GhostlyNode = class GhostlyNode {
40763
41201
  const live = this.links.get(linkId);
40764
41202
  if (!live?.stored.profile || live.stored.group) return false;
40765
41203
  const id = `peer_${edit.id}`;
41204
+ const ref = edit.rm && !await this.namesMine(linkId, edit.id);
40766
41205
  if (live.stored.deletedIds?.includes(id)) {
40767
- if (edit.rm) this.quoteSweeps.add(linkId, id, replyRef({
40768
- id,
40769
- linkId
40770
- }));
41206
+ if (ref) {
41207
+ this.quoteSweeps.add(linkId, id, replyRef({
41208
+ id,
41209
+ linkId
41210
+ }));
41211
+ if (!live.stored.removedRefs?.includes(edit.id)) {
41212
+ live.stored = {
41213
+ ...live.stored,
41214
+ removedRefs: withRemovedRef(live.stored.removedRefs, edit.id)
41215
+ };
41216
+ await this.writeDeletions(linkId, { removedRefs: live.stored.removedRefs });
41217
+ this.emitState();
41218
+ }
41219
+ }
40771
41220
  return true;
40772
41221
  }
40773
41222
  if (edit.rm) {
40774
41223
  const message = await db.getMessage(linkId, id);
40775
- if (!message && PAYMENT_LINE_ID.test(edit.id)) return true;
40776
- if (!message || canRemove(message)) await this.forgetMessage(linkId, id, true);
41224
+ if (PAYMENT_LINE_ID.test(edit.id)) return true;
41225
+ if (!message || canRemove(message)) await this.forgetMessage(linkId, id, ref && (message ?? true));
40777
41226
  return true;
40778
41227
  }
40779
41228
  const message = await db.getMessage(linkId, id);
@@ -41355,7 +41804,7 @@ var GhostlyNode = class GhostlyNode {
41355
41804
  const out = `${linkId}-out-`;
41356
41805
  const wireId = message.wireId ?? (message.file?.id.startsWith(out) ? message.file.id.slice(out.length) : void 0);
41357
41806
  if (!wireId || message.delivery === "waiting") {
41358
- await this.forgetMessage(linkId, messageId, true);
41807
+ await this.forgetMessage(linkId, messageId, message);
41359
41808
  return { error: null };
41360
41809
  }
41361
41810
  const removal = {
@@ -41370,7 +41819,7 @@ var GhostlyNode = class GhostlyNode {
41370
41819
  removals: withRemoval(live.stored.removals, removal)
41371
41820
  };
41372
41821
  const written = this.writeDeletions(linkId, { removals: live.stored.removals });
41373
- const forgot = this.forgetMessage(linkId, messageId, true);
41822
+ const forgot = this.forgetMessage(linkId, messageId, message);
41374
41823
  await written;
41375
41824
  await forgot;
41376
41825
  const edits = this.editsFor(linkId);
@@ -41417,19 +41866,35 @@ var GhostlyNode = class GhostlyNode {
41417
41866
  });
41418
41867
  return entry.done;
41419
41868
  }
41869
+ /** Whether a 1:1 chat's wire id names a message of mine: here, deleted here, removed, or a file or payment of mine. */
41870
+ async namesMine(linkId, wireId) {
41871
+ const stored = this.links.get(linkId)?.stored, row = `me_${wireId}`;
41872
+ if (stored?.deletedIds?.includes(row) || stored?.removals?.some((r) => r.id === row || r.wireId === wireId)) return true;
41873
+ for (const id of [row, ...await this.rowsNamed(linkId, wireId)]) if ((await db.getMessage(linkId, id))?.sender === "me") return true;
41874
+ return false;
41875
+ }
41420
41876
  /**
41421
41877
  * Forgets one message of a chat on this device, the bytes of its file and any transfer of it, and keeps its id so a
41422
41878
  * copy that comes again is not stored: a delete here, or the contact's own removal (WISP 400 § Delete for everyone),
41423
- * also of a message not here yet. `removed`: deleted for everyone, so the replies here that quote it lose its line too.
41879
+ * also of a message not here yet. `removed`: deleted for everyone (its row, when the caller read it), so the replies
41880
+ * here that quote it lose its line too, and a pin of it goes (`removedRefs`).
41424
41881
  */
41425
41882
  async forgetMessage(linkId, messageId, removed = false) {
41426
41883
  const live = this.links.get(linkId);
41427
41884
  if (!live) return;
41885
+ const ref = removed ? replyRef(removed === true ? {
41886
+ id: messageId,
41887
+ linkId
41888
+ } : removed) : void 0;
41428
41889
  live.stored = {
41429
41890
  ...live.stored,
41430
- deletedIds: [...live.stored.deletedIds ?? [], messageId].slice(-500)
41891
+ deletedIds: [...live.stored.deletedIds ?? [], messageId].slice(-500),
41892
+ ...ref && { removedRefs: withRemovedRef(live.stored.removedRefs, ref) }
41431
41893
  };
41432
- this.writeDeletions(linkId, { deletedIds: live.stored.deletedIds }).catch(() => {});
41894
+ this.writeDeletions(linkId, {
41895
+ deletedIds: live.stored.deletedIds,
41896
+ ...ref && { removedRefs: live.stored.removedRefs }
41897
+ }).catch(() => {});
41433
41898
  this.hold.forget(linkId, messageId).catch(() => {});
41434
41899
  const message = await db.getMessage(linkId, messageId);
41435
41900
  if (message?.paymentId && message.delivery === "waiting") await this.desk.withdraw(message.paymentId).catch(() => {});
@@ -41467,7 +41932,12 @@ var GhostlyNode = class GhostlyNode {
41467
41932
  async forgetQuotes(linkId, removed) {
41468
41933
  const byRef = /* @__PURE__ */ new Map();
41469
41934
  for (const [id, ref] of removed) if (ref !== void 0) byRef.set(ref, id);
41470
- const quoted = (reply) => !reply ? void 0 : reply.messageId !== void 0 && removed.has(reply.messageId) ? reply.messageId : byRef.get(reply.id);
41935
+ const side = (id) => id.startsWith("peer_") ? "peer" : id.startsWith("me_") ? "me" : void 0;
41936
+ const byReference = (reply) => {
41937
+ const id = byRef.get(reply.id);
41938
+ return id === void 0 || !reply.from || !side(id) || side(id) === reply.from ? id : void 0;
41939
+ };
41940
+ const quoted = (reply) => !reply ? void 0 : reply.messageId !== void 0 && removed.has(reply.messageId) ? reply.messageId : byReference(reply);
41471
41941
  const ids = (await db.getMessages(linkId)).filter((m) => {
41472
41942
  const id = quoted(m.replyTo);
41473
41943
  return id !== void 0 && (m.replyTo.snippet || m.replyTo.messageId !== id);
@@ -42873,17 +43343,32 @@ var GhostlyNode = class GhostlyNode {
42873
43343
  async appOpen({ linkId, ref, version, digest }) {
42874
43344
  const { live, app } = this.appChat(linkId, ref);
42875
43345
  if (!isAppVersion(version)) throw new Error("Not an app version");
43346
+ const turn = this.appTurn(linkId, app);
42876
43347
  await this.appChatRunnable(ref, digest);
43348
+ if (this.appTurns.get(`${linkId} ${app}`) !== turn) return { app };
42877
43349
  const open = live.appsOpen ??= /* @__PURE__ */ new Map();
42878
43350
  if (live.link) live.link.openApp(app, version);
42879
43351
  else open.set(app, version);
42880
43352
  return { app };
42881
43353
  }
43354
+ /** The last open or close of each app in each chat, by chat and chat app id: an open still reading the store is not the last. */
43355
+ appTurns = /* @__PURE__ */ new Map();
43356
+ nextAppTurn = 0;
43357
+ appTurn(linkId, app) {
43358
+ const turn = ++this.nextAppTurn;
43359
+ this.appTurns.set(`${linkId} ${app}`, turn);
43360
+ return turn;
43361
+ }
43362
+ /** Closes `app` in a chat, and any open of it still on its way. */
43363
+ appCloseIn(linkId, live, app) {
43364
+ this.appTurn(linkId, app);
43365
+ if (live.link) live.link.closeApp(app);
43366
+ else live.appsOpen?.delete(app);
43367
+ }
42882
43368
  /** This side closed an app in a paired chat: `close` goes now when the session is live. */
42883
43369
  appClose({ linkId, ref }) {
42884
43370
  const { live, app } = this.appChat(linkId, ref);
42885
- if (live.link) live.link.closeApp(app);
42886
- else live.appsOpen?.delete(app);
43371
+ this.appCloseIn(linkId, live, app);
42887
43372
  }
42888
43373
  /** One data frame of an app open on both sides, on the live session only; nothing is kept to send later. */
42889
43374
  async appSend({ linkId, ref, data, digest }) {
@@ -42970,17 +43455,15 @@ var GhostlyNode = class GhostlyNode {
42970
43455
  }
42971
43456
  /** Every page went away: no app runs here any more, so each open one is closed (`close` goes where it can). */
42972
43457
  appsCloseAll() {
42973
- for (const live of this.links.values()) for (const app of [...live.appsOpen?.keys() ?? []]) if (live.link) live.link.closeApp(app);
42974
- else live.appsOpen?.delete(app);
43458
+ for (const [linkId, live] of this.links) for (const app of [...live.appsOpen?.keys() ?? []]) this.appCloseIn(linkId, live, app);
43459
+ for (const key of this.appTurns.keys()) this.appTurns.set(key, ++this.nextAppTurn);
42975
43460
  }
42976
43461
  /** An app that went (uninstalled) is closed in every chat it was open in, as `appClose` does. */
42977
43462
  appsCloseOf(ref) {
42978
43463
  for (const [linkId, live] of this.links) {
42979
43464
  if (!live.appsOpen?.size) continue;
42980
43465
  const { app } = this.appChat(linkId, ref);
42981
- if (!live.appsOpen.has(app)) continue;
42982
- if (live.link) live.link.closeApp(app);
42983
- else live.appsOpen.delete(app);
43466
+ if (live.appsOpen.has(app)) this.appCloseIn(linkId, live, app);
42984
43467
  }
42985
43468
  }
42986
43469
  /** Keeps a pin of a 1:1 chat when it is newer than the chat's; `out`: mine, to say until the contact confirms it. */
@@ -43022,6 +43505,29 @@ var GhostlyNode = class GhostlyNode {
43022
43505
  };
43023
43506
  await db.patchLink(linkId, { pinOut: void 0 });
43024
43507
  }
43508
+ /**
43509
+ * A 1:1 chat's pin that came before its message (pinned while I was away: the pin goes as the session opens, ahead of
43510
+ * what waited) names its row once the row is here. Only the rows that changed are read, and only while such a pin stands.
43511
+ */
43512
+ async pinnedRowCame(linkId, ids) {
43513
+ const live = this.links.get(linkId), pin = live?.stored.pin;
43514
+ if (!live || live.stored.group || !pin?.id || pin.messageId) return;
43515
+ for (const id of new Set(ids)) {
43516
+ const row = await db.getMessage(linkId, id);
43517
+ if (!row || replyRef(row) !== pin.id) continue;
43518
+ if (live.stored.pin !== pin) return;
43519
+ live.stored = {
43520
+ ...live.stored,
43521
+ pin: {
43522
+ ...pin,
43523
+ messageId: row.id
43524
+ }
43525
+ };
43526
+ await db.patchLink(linkId, { pin: live.stored.pin });
43527
+ this.emitState();
43528
+ return;
43529
+ }
43530
+ }
43025
43531
  /** A pin that came, as it is kept: who pinned, and its row when it is here. */
43026
43532
  async pinCame(chat, by, pin) {
43027
43533
  const row = await pinnedRow(this.pinsHost, chat, pin.id);
@@ -44444,6 +44950,7 @@ var GhostlyNode = class GhostlyNode {
44444
44950
  }
44445
44951
  this.watchActiveTurn();
44446
44952
  this.watchTombstones();
44953
+ await this.finishRemovals().catch(() => {});
44447
44954
  await this.rotateIfDue().catch(() => {});
44448
44955
  }
44449
44956
  /**
@@ -44544,6 +45051,12 @@ var GhostlyNode = class GhostlyNode {
44544
45051
  async moveDeviceSet(remove) {
44545
45052
  this.setMoveAllowed();
44546
45053
  if (this.settingMove) throw new Error("remove-busy: The device set is already changing.");
45054
+ const record = remove === void 0 ? null : await readDeviceRecord(databaseName()).catch(() => null);
45055
+ if (record?.state === "active" && record.earlierSets.some((set) => set.removed === remove) && !record.deviceSet.some((slot) => slot?.key === remove)) {
45056
+ await this.finishRemovals().catch(() => {});
45057
+ this.watchTombstones();
45058
+ return this.deviceSet();
45059
+ }
44547
45060
  const work = (async () => {
44548
45061
  const ports = await this.setMovePorts();
44549
45062
  if (!ports) throw new Error("remove-state: This device cannot sign for its device set.");
@@ -44555,7 +45068,7 @@ var GhostlyNode = class GhostlyNode {
44555
45068
  } finally {
44556
45069
  this.settingMove = null;
44557
45070
  }
44558
- if (remove !== void 0) await this.afterDeviceRemoved(remove).catch(() => {});
45071
+ if (remove !== void 0) await this.finishRemovals().catch(() => {});
44559
45072
  if (this.handoffGiver) {
44560
45073
  this.deviceLinks?.setHandoff(null);
44561
45074
  this.handoffGiver = null;
@@ -44590,6 +45103,28 @@ var GhostlyNode = class GhostlyNode {
44590
45103
  }
44591
45104
  }
44592
45105
  /**
45106
+ * What each removal left in the profile (`afterDeviceRemoved`), for every earlier set that still names the device it
45107
+ * removed: after the move, and at start for one a reload, a crash or a stop cut short after its write. The name is
45108
+ * dropped once its device's leftovers are cleared.
45109
+ */
45110
+ async finishRemovals() {
45111
+ const profile = databaseName();
45112
+ const record = await readDeviceRecord(profile);
45113
+ if (record?.state !== "active") return;
45114
+ const done = /* @__PURE__ */ new Set();
45115
+ for (const set of record.earlierSets) {
45116
+ if (set.removed === void 0 || done.has(set.removed)) continue;
45117
+ if (await this.afterDeviceRemoved(set.removed).then(() => true, () => false)) done.add(set.removed);
45118
+ }
45119
+ if (!done.size) return;
45120
+ const now = await readDeviceRecord(profile);
45121
+ if (now?.state !== "active") return;
45122
+ await amendDevice(profile, { earlierSets: now.earlierSets.map(({ removed, ...set }) => removed === void 0 || done.has(removed) ? set : {
45123
+ ...set,
45124
+ removed
45125
+ }) });
45126
+ }
45127
+ /**
44593
45128
  * Remove: the device with this signing key can no longer take the profile (WISP 06 § Removing a device). The set
44594
45129
  * moves to a new secret, which the other devices get over their old links; the removed one gets nothing, and reads
44595
45130
  * its removal from the tombstone. Only the active device removes.
@@ -44664,7 +45199,7 @@ var GhostlyNode = class GhostlyNode {
44664
45199
  await this.startDeviceSet();
44665
45200
  },
44666
45201
  onChange: (view) => {
44667
- if (view.step === "failed") setTimeout(() => void this.rotateIfDue().catch(() => {}), 0);
45202
+ if (view.step === "failed" || view.step === "done") setTimeout(() => void this.rotateIfDue().catch(() => {}), 0);
44668
45203
  }
44669
45204
  });
44670
45205
  this.enrollment = inviter;
@@ -46099,7 +46634,7 @@ var GhostlyNode = class GhostlyNode {
46099
46634
  nativeFactoriesFor(relayOnly) {
46100
46635
  const relay = relayOnly || this.relaysHyperdhtNatively ? this.hyperdhtRelay : "";
46101
46636
  return {
46102
- ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-DitYDnXx.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
46637
+ ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-B2uK9tJv.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
46103
46638
  ...relayOnly ? {} : this.options.nativeTransports,
46104
46639
  ...this.ownIrohRelays && !relayOnly ? { "iroh/1": (seedB64) => this.options.nativeTransports["iroh/1"](seedB64, this.settings.irohRelays?.length ? { relays: [...this.settings.irohRelays] } : {}) } : {},
46105
46640
  ...this.options.irohWeb ? { "iroh/1": (seedB64) => createIrohWebEndpoint(seedB64, { relays: this.irohRelays }) } : {}
@@ -46155,7 +46690,7 @@ var GhostlyNode = class GhostlyNode {
46155
46690
  this.relayRetry = setTimeout(() => {
46156
46691
  this.relayRetry = null;
46157
46692
  for (const [linkId, live] of this.links) if (live.link && live.stored.profile && (!live.stored.group || this.keepsGroupNative(live.stored)) && live.stored.deliveryMode !== "dht" && !live.link.availableTransports.includes("hyperdht/1") && this.keepsNativeEndpoints(linkId, live.stored)) this.ensureNativeEndpoints(linkId);
46158
- }, RELAY_RETRY_MS);
46693
+ }, RELAY_RETRY_MS / 2 + Math.random() * RELAY_RETRY_MS);
46159
46694
  }
46160
46695
  /** A new relay (or none): chats give up their endpoints on the old one, as soon as none of them carries a session. */
46161
46696
  async relayChanged() {
@@ -46599,6 +47134,7 @@ var GhostlyNode = class GhostlyNode {
46599
47134
  */
46600
47135
  async messagesChanged(linkId, ids) {
46601
47136
  this.chatSearch.changed(linkId);
47137
+ await this.pinnedRowCame(linkId, ids);
46602
47138
  const reacted = this.reactionNotes.get(linkId);
46603
47139
  if (reacted?.message && ids.includes(reacted.message)) {
46604
47140
  const row = await db.getMessage(linkId, reacted.message);
@@ -46807,7 +47343,11 @@ var GhostlyNode = class GhostlyNode {
46807
47343
  ...stored.wakeMuted && { wakeMuted: true }
46808
47344
  },
46809
47345
  ...this.reactionNotes.has(stored.id) && { lastReaction: this.reactionNotes.get(stored.id) },
46810
- ...stored.pin && { pin: pinView(stored.pin) },
47346
+ ...stored.pin && { pin: pinView(stored.pin.id && stored.removedRefs?.includes(stored.pin.id) ? {
47347
+ ...stored.pin,
47348
+ id: "",
47349
+ messageId: void 0
47350
+ } : stored.pin) },
46811
47351
  participationKey: participationKeyOf(live),
46812
47352
  peerParticipationKey: stored.pairedPeerKey,
46813
47353
  publicProfiles: void 0,
@@ -47207,4 +47747,4 @@ function signalKind(signal) {
47207
47747
  //#endregion
47208
47748
  export { EngineServer };
47209
47749
 
47210
- //# sourceMappingURL=server-BGCuHbmQ.js.map
47750
+ //# sourceMappingURL=server-BUcJo4vz.js.map