@ghostlytools/cli 1.11.0 → 1.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +24 -16
  2. package/dist/assets/{api-CTqIcdu7.js → api-BM3PsXbB.js} +372 -123
  3. package/dist/assets/api-BM3PsXbB.js.map +1 -0
  4. package/dist/assets/{api-B-52sVYp.js → api-CtXgscmK.js} +2 -2
  5. package/dist/assets/{apiKit-CZq4Lq4f.js → apiKit-lCTQ0EBG.js} +17 -7
  6. package/dist/assets/apiKit-lCTQ0EBG.js.map +1 -0
  7. package/dist/assets/appFetch-BKHy5H8J.js +194 -0
  8. package/dist/assets/appFetch-BKHy5H8J.js.map +1 -0
  9. package/dist/assets/{apps-kRsY9S2S.js → apps-DO_gAZgm.js} +1 -1
  10. package/dist/assets/{apps-C_X0zgSG.js → apps-Do26w3c7.js} +44 -40
  11. package/dist/assets/apps-Do26w3c7.js.map +1 -0
  12. package/dist/assets/{arkade-_aaB7VbW.js → arkade-CZrLbz-M.js} +2 -2
  13. package/dist/assets/{arkade-_aaB7VbW.js.map → arkade-CZrLbz-M.js.map} +1 -1
  14. package/dist/assets/{backup-DBg388Ke.js → backup-D21x1f5P.js} +1 -1
  15. package/dist/assets/{backup-OTvrmk-w.js → backup-j47AzDvG.js} +84 -33
  16. package/dist/assets/backup-j47AzDvG.js.map +1 -0
  17. package/dist/assets/{bitcoind-CZchoh43.js → bitcoind-CdSmvy2y.js} +3 -3
  18. package/dist/assets/{bitcoind-CZchoh43.js.map → bitcoind-CdSmvy2y.js.map} +1 -1
  19. package/dist/assets/{bitcoindProvider-DGw3xBSa.js → bitcoindProvider-BvoRh0D5.js} +2 -2
  20. package/dist/assets/{bitcoindProvider-DGw3xBSa.js.map → bitcoindProvider-BvoRh0D5.js.map} +1 -1
  21. package/dist/assets/{buttons-DUu7hxxT.js → buttons-CiGlBVBT.js} +18 -7
  22. package/dist/assets/buttons-CiGlBVBT.js.map +1 -0
  23. package/dist/assets/buttons-D2l2bVCG.js +2 -0
  24. package/dist/assets/{childEnv-BVOQK9EA.js → childEnv-K_IzUqQx.js} +4 -3
  25. package/dist/assets/childEnv-K_IzUqQx.js.map +1 -0
  26. package/dist/assets/{client-DDpZP1R1.js → client-raIncVtF.js} +31 -3
  27. package/dist/assets/client-raIncVtF.js.map +1 -0
  28. package/dist/assets/{codec-DrryGcPT.js → codec-DcG2AeyE.js} +2 -2
  29. package/dist/assets/{codec-DrryGcPT.js.map → codec-DcG2AeyE.js.map} +1 -1
  30. package/dist/assets/endpoint-DarqblYE.js +5052 -0
  31. package/dist/assets/endpoint-DarqblYE.js.map +1 -0
  32. package/dist/assets/{envelope-Q_rMgoE9.js → envelope-Dud6lntA.js} +2 -2
  33. package/dist/assets/{envelope-Q_rMgoE9.js.map → envelope-Dud6lntA.js.map} +1 -1
  34. package/dist/assets/{fedimintSdk-CqTeMdF0.js → fedimintSdk-DRKRSw14.js} +6 -3
  35. package/dist/assets/fedimintSdk-DRKRSw14.js.map +1 -0
  36. package/dist/assets/{fixedHosts-BV5GDiTU.js → fixedHosts-CNX7QiUD.js} +3 -3
  37. package/dist/assets/{fixedHosts-BV5GDiTU.js.map → fixedHosts-CNX7QiUD.js.map} +1 -1
  38. package/dist/assets/{host-BlUzZgQL.js → host-8RskzQgB.js} +306 -84
  39. package/dist/assets/host-8RskzQgB.js.map +1 -0
  40. package/dist/assets/{hyperdhtRelay-BvI_uNZO.js → hyperdhtRelay-uAThbFub.js} +2 -2
  41. package/dist/assets/{hyperdhtRelay-BvI_uNZO.js.map → hyperdhtRelay-uAThbFub.js.map} +1 -1
  42. package/dist/assets/{irohWeb-CqPN8VPY.js → irohWeb-DGelfgDJ.js} +695 -40
  43. package/dist/assets/irohWeb-DGelfgDJ.js.map +1 -0
  44. package/dist/assets/jsonOut-POtMBS_V.js +16 -0
  45. package/dist/assets/jsonOut-POtMBS_V.js.map +1 -0
  46. package/dist/assets/{main-vQjlgEnt.js → main-BC33ooYg.js} +175 -107
  47. package/dist/assets/main-BC33ooYg.js.map +1 -0
  48. package/dist/assets/{mainline-p6HOW7sb.js → mainline-DYrjsS1t.js} +27 -8
  49. package/dist/assets/mainline-DYrjsS1t.js.map +1 -0
  50. package/dist/assets/{networkReason-DMffkiJ6.js → networkReason-n2oBs4by.js} +3 -3
  51. package/dist/assets/{networkReason-DMffkiJ6.js.map → networkReason-n2oBs4by.js.map} +1 -1
  52. package/dist/assets/{nwc-2vH18oNy.js → nwc-Do3VSlIS.js} +6 -5
  53. package/dist/assets/nwc-Do3VSlIS.js.map +1 -0
  54. package/dist/assets/{nwcProvider-DpeDy0bV.js → nwcProvider-Du5aWNIn.js} +6 -3
  55. package/dist/assets/{nwcProvider-DpeDy0bV.js.map → nwcProvider-Du5aWNIn.js.map} +1 -1
  56. package/dist/assets/{ownDid-iKz8u_fM.js → ownDid-CwwYu8s2.js} +3 -3
  57. package/dist/assets/{ownDid-iKz8u_fM.js.map → ownDid-CwwYu8s2.js.map} +1 -1
  58. package/dist/assets/{ownStatus-BlRKnM5F.js → ownStatus-D7dB4zJB.js} +4 -3
  59. package/dist/assets/{ownStatus-BlRKnM5F.js.map → ownStatus-D7dB4zJB.js.map} +1 -1
  60. package/dist/assets/{profiles-B5e0TyvS.js → profiles-NyF5FnYF.js} +82 -6
  61. package/dist/assets/profiles-NyF5FnYF.js.map +1 -0
  62. package/dist/assets/{registry-Cc_PQb3k.js → registry-C734VrO9.js} +1 -1
  63. package/dist/assets/{registry-CnFO2Pp5.js → registry-DKDInr0A.js} +75 -23
  64. package/dist/assets/registry-DKDInr0A.js.map +1 -0
  65. package/dist/assets/{resolve-DI8uAM_Y.js → resolve-3Tqh9AWQ.js} +4 -3
  66. package/dist/assets/resolve-3Tqh9AWQ.js.map +1 -0
  67. package/dist/assets/{server-DdtPxkqI.js → server-B6PQ6iae.js} +430 -868
  68. package/dist/assets/server-B6PQ6iae.js.map +1 -0
  69. package/dist/assets/{src-BnpEQqzk.js → src-ChJijTlM.js} +1139 -243
  70. package/dist/assets/src-ChJijTlM.js.map +1 -0
  71. package/dist/assets/{sshForges-cdIAraDw.js → sshForges-Brf0fslM.js} +2 -2
  72. package/dist/assets/{sshForges-cdIAraDw.js.map → sshForges-Brf0fslM.js.map} +1 -1
  73. package/dist/assets/{translate-kNopA04L.js → translate-xLme9Rdh.js} +10 -8
  74. package/dist/assets/translate-xLme9Rdh.js.map +1 -0
  75. package/dist/assets/{types-C4_KafL_.js → types-Clyb52K2.js} +2 -1
  76. package/dist/assets/types-Clyb52K2.js.map +1 -0
  77. package/dist/assets/{usdt-CDaLhEYh.js → usdt-CSU5KzTV.js} +3 -3
  78. package/dist/assets/{usdt-CDaLhEYh.js.map → usdt-CSU5KzTV.js.map} +1 -1
  79. package/dist/ghostly.mjs +1 -1
  80. package/npm-shrinkwrap.json +3592 -0
  81. package/package.json +5 -3
  82. package/dist/assets/api-CTqIcdu7.js.map +0 -1
  83. package/dist/assets/apiKit-CZq4Lq4f.js.map +0 -1
  84. package/dist/assets/apps-C_X0zgSG.js.map +0 -1
  85. package/dist/assets/backup-OTvrmk-w.js.map +0 -1
  86. package/dist/assets/buttons-4EKtQl-7.js +0 -2
  87. package/dist/assets/buttons-DUu7hxxT.js.map +0 -1
  88. package/dist/assets/childEnv-BVOQK9EA.js.map +0 -1
  89. package/dist/assets/client-DDpZP1R1.js.map +0 -1
  90. package/dist/assets/endpoint-DWHkXWVM.js +0 -419
  91. package/dist/assets/endpoint-DWHkXWVM.js.map +0 -1
  92. package/dist/assets/fedimintSdk-CqTeMdF0.js.map +0 -1
  93. package/dist/assets/host-BlUzZgQL.js.map +0 -1
  94. package/dist/assets/irohWeb-CqPN8VPY.js.map +0 -1
  95. package/dist/assets/main-vQjlgEnt.js.map +0 -1
  96. package/dist/assets/mainline-p6HOW7sb.js.map +0 -1
  97. package/dist/assets/nwc-2vH18oNy.js.map +0 -1
  98. package/dist/assets/profiles-B5e0TyvS.js.map +0 -1
  99. package/dist/assets/registry-CnFO2Pp5.js.map +0 -1
  100. package/dist/assets/resolve-DI8uAM_Y.js.map +0 -1
  101. package/dist/assets/server-DdtPxkqI.js.map +0 -1
  102. package/dist/assets/src-BnpEQqzk.js.map +0 -1
  103. package/dist/assets/translate-kNopA04L.js.map +0 -1
  104. package/dist/assets/types-C4_KafL_.js.map +0 -1
@@ -1,17 +1,18 @@
1
1
  import { n as traceJoin } from "./joinTrace-CjRDFy85.js";
2
- import { $c as contactAskerFrame, $i as emptyProofLedger, $l as OwnInviteError, $n as engineError, $o as RATCHET_CAPABILITY, $s as handoffContext, $t as ONCHAIN_PROVIDER, A as knockIdentity, Aa as DHT_MESSAGE_TTL, Ai as STATUS_CARD_CAPABILITY, Al as appRefPublisher, An as ENDPOINT, Ar as lobbyKeys, Au as turnKeys, Bc as readEnrollGrant, Bn as NO_PICTURE_METADATA, Bo as heardTime, Br as shouldBeHub, Bs as HANDOFF_OFFER, Bu as currentRelays, C as communityHasFrame, Ci as isServeId, Cr as pickMeshHubs, Cu as TURN_MAX, D as decodeGroupEntryLink, Dc as signTombstone, Di as APPS_CAPABILITY, Dl as APP_STATEMENT_LIMITS, Dr as doorHubs, Ds as contactRtcConfig, Du as signTurnPacket, Ec as setUpdateFrame, Ei as isAppVersion, Eo as STATUS_CARD_LIMITS, Er as beaconRecords, Eu as readTurnPacket, F as GroupWakeLimiter, Fa as sanitizeFileName, Fc as enrollDigits, Fi as dialDescriptors, Fl as isAppRef, Fn as parseCashuRequestPayload, Fr as pickHubs, Fs as HANDOFF_ACK, Gc as inboxRecord, Gl as canonicalJsonBytes, Gn as GhostLink, Gr as transferEnded, Gs as HANDOFF_VERIFIED, Gt as didDhtDocument, H as GroupSession, Ha as fileMessageText, Hc as verifyEnrollProof, Hl as parseImageMeta, Hn as isStrippedPicture, Ho as shownTime, Hr as FILE_LIMITS, Hs as HANDOFF_PIECE_BYTES, I as groupWakeFrame, Ia as sanitizeMime, Ic as enrollDoneFrame, Il as readAppRevocation, In as parseFedimintRequestPayload, Io as statusCardText, Ir as rankHubs, Is as HANDOFF_CANCEL, J as meshMessageRef, Ja as EDIT_RATE_WINDOW_MS, Jc as settleRequest, Jl as encodeContactLink, Jn as PAIRED_FRAME_TOO_LARGE, Jo as parseGroupCommit, Jr as STATUS_IDLE_AFTER_MS, Js as handoffAttemptAllowed, Jt as encodeDidDhtPacket, Ju as withRequestOptions, K as GROUP_EDIT_TEXT_BYTES, Ka as parseVideoMeta, Kc as newInbox, Kl as readCanonicalJson, Kn as INVITE_TAKEN, Ko as MEMBER_KEY, Kr as transferStalled, Ks as NO_ATTEMPTS, Kt as didDhtFromPublicKey, Ku as budgetRetryMs, L as groupWakes, Lc as enrollGrantFrame, Ll as readAppRevocationShape, Lr as readBeacon, Ls as HANDOFF_DONE, Lu as RelayTransport, M as mergeKnocks, Ma as DHT_FILE_CAPABILITY, Mi as CapsExchange, Ml as isAppHash, Mn as fedimintRequestPayload, Mr as mergeBeacon, Ms as HTTP_SERVICE_PROTO, Mu as turnStatedVerifier, N as readKnocks, Na as dhtFileId, Nc as enrollCancelFrame, Ni as DHT_TEXT_CAPABILITY, Nl as isAppKey, Nn as findEndpoint, No as checkStatusCard, Nr as mergeLobby, Ns as LEGACY_SERVICES, Nu as turnVerifierMark, O as encodeGroupEntryLink, Oc as verifySetUpdate, Oi as BUTTONS_CAPABILITY, Ol as appFingerprint, Or as freshHubs, Ou as signTurnRelease, Pa as formatFileSize, Pc as enrollCancelReason, Pi as capsDescriptors, Pn as isFederationId, Po as sameButtonText, Pr as newerHead, Ps as serviceIdFromName, Pu as DEFAULT_RELAYS, Qa as dhtEditId, Qc as REQUEST_LIFETIME_MS, Qi as PeerProofs, Ql as readDeviceInvite, Qn as EngineError, Qo as edgeParams, Qs as handoffCancelFrame, Qt as EVM_TEST_CHAINS, R as parseGroupWakeFrame, Rc as enrollHelloFrame, Rn as videoMetadataPatches, Ro as arrivalKey, Rr as readBeaconHead, Rs as HANDOFF_HAVE, S as GROUP_READ_NOTE_COMMUNITY, Si as APP_RANGE_LIMITS, Sl as pacer, Sr as meshHubs, Ss as RTC_CONFIG, Su as TURN_LAST_SEQUENCE, T as encodeCommunityLink, Tc as setAckFrame, Ti as chatAppId, Tl as sha256Paced, Tr as beaconKeys, Tu as nextTurnPosition, U as frameBytes, Ua as parseVoiceMeta, Uc as clearMissed, Ui as emptyIdentityLedger, Un as stripPictureMetadata, Uo as GROUP_ADMIN_OFF_ERROR, Us as HANDOFF_REQUEST, V as GROUP_READ_NOTE, Vc as readEnrollHello, Vn as PICTURE_METADATA_LIMITS, Vo as receivedTimestamp, Vr as ChatFiles, Vs as HANDOFF_PAKE, Vu as normalizeRelayUrl, Wc as endedRequests, Wl as canonicalJson, Wo as GROUP_MEMBER_CAP, Wr as sentWhole, Ws as HANDOFF_TIMINGS, Wu as traceLink, X as mentionsMember, Xa as REMOVED_TEXT, Xc as turnOff, Xl as createDeviceInvite, Xn as pairedMessageFits, Xo as rosterHas, Xr as personStatus, Xs as handoffAttemptSucceeded, Xt as signDidDhtPacket, Y as parseCommunityEdit, Ya as MAX_REMOVAL_NUMBER, Yc as takeRequest, Yi as receivedIdentityStatus, Yl as readContactLink, Yn as pairedEditFits, Yo as rosterAdmin, Yr as liveStatus, Ys as handoffAttemptFailed, Yu as PacketTooLargeError, Z as groupName, Za as RateWindow, Zc as ContactRequestError, Zi as lastSharedWithMe, Zl as deviceInviteJoinerParams, Zn as pairedMessageFrame, Zo as verifyCommitSignature, Zs as handoffBusyFrame, Zt as ETHEREUM_USDT, Zu as createRelayPayload, _ as groupTypingEpoch, _c as readHandoffHello, _d as utf8Decode, _i as parseWakeFrame, _l as appDigest, _o as replySnippet, _s as decodeControl, _t as isAtprotoDid, a as appRevocationFor, ac as handoffManifestFrames, ad as verify, ai as mayPin, al as linkRecords, an as WALLET_NETWORKS, ao as GROUP_REACTION_FRAME, b as COMMUNITY_LIMITS, bc as readHandoffVerified, bi as checkPushEndpoint, br as MESH_HUBS, bu as classifyTurnRead, c as checkAppBeforeRun, ca as HOLD_LIMITS, cc as handoffReleaseFrame, cd as hasVisible, ci as pinNumberHolds, cl as openRequest, cn as assertWholeSats, co as nextReactionNumber, cs as PRESENCE_WINDOW, cu as HANDOFF_CAPABILITY, da as isHoldUrl, dc as handoffVersions, dd as bytesEqual, di as WAKE_ONLINE_BATCH_MS, dl as requestRecords, dn as walletNetworkOf, do as reactionIsNewer, ds as presenceSeenAt, du as deviceKeyZ32, ea as validExternalKey, ec as handoffContextProof, ei as TypingSender, el as contactAskerHolds, en as PaymentPreflightError, er as engineText, es as RatchetBox, eu as createChatInvite, fa as newMailbox, fc as newHandoffId, fd as fromBase64Url, fi as WAKE_ONLINE_DELAY_MS, fl as seenEntry, fn as SPARK_NETWORKS, fo as readReaction, fs as GhostlyHttpError, fu as deviceLinkPairing, g as GroupTypingBoard, gc as readHandoffHave, gd as toZ32, gi as newWakeToken, gn as isBitcoinAddress, go as readReply, gs as LIMITS, gu as webCryptoSigner, hc as readHandoffDone, hd as toBase64Url, hi as deviceWakeRequest, hn as sparkInvoiceDetails, ho as pairedReplyAuthor, hs as webLocalFetch, hu as seedSigner, i as addedAppPermissions, ic as handoffHelloFrame, id as publicKeyFromZ32, ii as PIN_LIMITS, il as knockSlotRecords, in as USDT_PUBLIC_RPC, io as COMMUNITY_REACTION_FRAME, iu as inviteOwnership, j as knockRecords, ja as peekDhtMailbox, ji as UPGRADE_CAPABILITY, jn as cashuRequestPayload, jr as lobbyRecords, js as emptyLinkRecords, ju as turnName, k as entryParams, ki as EDIT_CAPABILITY, kl as appRef, kn as decodeBolt11, kr as hubRank, ks as parseCallSignal, ku as turnInstance, l as planAppUpdate, la as HoldKeys, lc as handoffRetryAfter, ld as sanitizeDisplayText, li as readPin, ll as readKnockSlot, ln as formatPaymentAmount, lo as queueReaction, lr as readGroupFileMeta, ls as RELAY_POLL_INTERVALS, lu as deviceEchoFrame, mc as readHandoffCancel, md as randomBytes, mi as WakeLimiter, ml as APP_BUNDLE_MAGIC, mn as sparkAddressKind, mo as wireReaction, ms as parseLocalTarget, mu as newDeviceSetSecret, n as readX401SdJwtVc, na as automaticTransport, nc as handoffDigest, nd as identityFromSeed, ni as typingActivity, nl as knockSlotIdentity, no as forwardedAgain, nr as GROUP_FILE_LIMITS, ns as ratchetSessionOf, nu as encodeInviteCode, o as appStoreDecision, oa as HOLD_CAPABILITY, oc as handoffOfferFrame, oi as nextPinNumber, ol as makeStampPaced, on as arkAddressPrefix, oo as REACTION_LIMITS, os as DHT_POLL_INTERVALS, ou as DEVICES_CAPABILITY, p as readAppStoreSteps, pa as readManifest, pc as readHandoffAck, pl as APP_BUNDLE_LIMITS, pn as SPARK_PROVIDER, po as validReactionNumber, pr as CarriedTransport, ps as formatLocalTarget, pu as devicePingFrame, q as carryMentions, qa as EDIT_BUFFER_MS, qc as planKnocks, ql as createContactLink, qn as LIVENESS_PING_MS, qo as commitHash, qs as filePartName, qt as encodeDidDhtDeactivated, qu as isDiscoveryBudgetError, r as sameX401HolderJwk, rc as handoffEphemeral, rd as identityFromSeedB64, rl as knockSlotOf, rn as TEST_USDT_FAUCET_AMOUNT, ro as readForwarded, rr as GROUP_HAVE_FRAME, rs as DirectPathWatch, ru as inviteLink, s as appUpdateDecision, sa as HOLD_DATED_BACK_MS, sc as handoffPakeFrame, sd as sanitizeAvatar, si as pinIsNewer, sl as mergeContactKnocks, sn as assertTokenUnits, so as ReactionWindow, sr as groupFileFallback, su as ENROLL_CAPABILITY, t as newX401HolderKey, ta as TRANSPORTS, tc as handoffDataFrame, td as createIdentity, tl as contactDay, tn as SEPOLIA_TEST_USDT, to as parseLinkPreview, tr as parseEngineError, ts as emptyRatchetState, tu as decodeInviteCode, u as APP_STORE_LIMITS, ua as HoldRefusedError, uc as handoffStreamKey, ud as stripHidden, ui as WAKE_CALL_INTERVAL_MS, ul as readLinkRecord, un as validatePaymentTarget, uo as reactionEmoji, us as WATCH_PEER_MS, uu as deviceEchoNonce, v as openGroupTyping, vc as readHandoffPake, vd as utf8Encode, vi as relayRequest, vl as appViewOf, vn as isPubkyKey, vo as BUTTON_ID, vr as groupSignalFrame, vs as encodeControl, vt as normalizeAtprotoHandle, vu as TURN_RAISE_READ_TIMEOUT_MS, w as decodeCommunityLink, wc as readSetUpdate, wl as readAppBundleAsync, wr as COMMUNITY_TOPOLOGY, wu as firstDeviceSetSecret, x as CommunitySession, xc as sealHandoffPiece, xi as vapidKeysMatch, xl as isAppUrl, xr as mayBeHub, xu as turnPutSummary, y as sealGroupTyping, yc as readHandoffTurnFrame, yi as wakeRequest, yr as readGroupSignal, yu as TURN_SETTLE_MS, z as GROUP_LIMITS, zc as enrollProofFrame, zn as withoutVideoMetadata, zo as claimedTime, zr as readLobby, zs as HANDOFF_HELLO } from "./src-BnpEQqzk.js";
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
- import { t as bitcoindRpc } from "./bitcoindProvider-DGw3xBSa.js";
5
- import { t as nwc } from "./nwcProvider-DpeDy0bV.js";
2
+ import { $a as MAX_REMOVAL_NUMBER, $c as takeRequest, $i as receivedIdentityStatus, $l as readContactLink, $n as pairedEditFits, $o as rosterAdmin, $r as liveStatus, $s as handoffAttemptFailed, $t as EVM_TEST_CHAINS, $u as PacketTooLargeError, A as knockIdentity, Ac as setUpdateFrame, Ai as isAppVersion, An as decodeBolt11, Ao as STATUS_CARD_LIMITS, Ar as beaconRecords, Au as readTurnPacket, Ba as sanitizeMime, Bc as enrollDoneFrame, Bl as readAppRevocation, Bo as statusCardText, Br as rankHubs, Bs as HANDOFF_CANCEL, C as communityHasFrame, Cc as readHandoffTurnFrame, Cd as utf8Encode, Ci as wakeRequest, Cr as readGroupSignal, Cu as TURN_SETTLE_MS, D as decodeGroupEntryLink, Di as isServeId, Dr as pickMeshHubs, Du as TURN_MAX, Ei as APP_RANGE_LIMITS, El as pacer, Er as meshHubs, Es as RTC_CONFIG, Eu as TURN_LAST_SEQUENCE, F as GroupWakeLimiter, Fa as peekDhtMailbox, Fi as UPGRADE_CAPABILITY, Fn as isFederationId, Fr as lobbyRecords, Fs as emptyLinkRecords, Fu as turnName, Gc as readEnrollHello, Go as receivedTimestamp, Gr as ChatFiles, Gs as HANDOFF_PAKE, Gu as normalizeRelayUrl, H as GroupSession, Hc as enrollHelloFrame, Ho as arrivalKey, Hr as readBeaconHead, Hs as HANDOFF_HAVE, I as groupWakeFrame, Ia as DHT_FILE_CAPABILITY, Ii as CapsExchange, Il as isAppHash, In as parseCashuRequestPayload, Ir as mergeBeacon, Is as HTTP_SERVICE_PROTO, Iu as turnStatedVerifier, J as carryMentions, Jc as endedRequests, Jl as canonicalJson, Jo as GROUP_MEMBER_CAP, Jr as sentWhole, Js as HANDOFF_TIMINGS, Jt as encodeDidDhtDeactivated, Ju as traceLink, Ka as fileMessageText, Kc as verifyEnrollProof, Kl as parseImageMeta, Ko as shownTime, Kr as FILE_LIMITS, Ks as HANDOFF_PIECE_BYTES, Kt as didDhtDocument, L as groupWakes, La as dhtFileId, Lc as enrollCancelFrame, Li as DHT_TEXT_CAPABILITY, Ll as isAppKey, Ln as parseFedimintRequestPayload, Lo as checkStatusCard, Lr as mergeLobby, Ls as LEGACY_SERVICES, Lu as turnVerifierMark, M as mergeKnocks, Mc as verifySetUpdate, Mi as BUTTONS_CAPABILITY, Ml as appFingerprint, Mn as cashuRequestPayload, Mr as freshHubs, Mu as signTurnRelease, N as readKnocks, Ni as EDIT_CAPABILITY, Nl as appRef, Nn as fedimintRequestPayload, Nr as hubRank, Ns as parseCallSignal, Nu as turnInstance, O as encodeGroupEntryLink, Oc as readSetUpdate, Ol as readAppBundleAsync, Or as COMMUNITY_TOPOLOGY, Ou as firstDeviceSetSecret, Pa as DHT_MESSAGE_TTL, Pi as STATUS_CARD_CAPABILITY, Pl as appRefPublisher, Pn as findEndpoint, Pr as lobbyKeys, Pu as turnKeys, Q as groupName, Qa as EDIT_RATE_WINDOW_MS, Qc as settleRequest, Ql as encodeContactLink, Qn as PAIRED_FRAME_TOO_LARGE, Qo as parseGroupCommit, Qr as STATUS_IDLE_AFTER_MS, Qs as handoffAttemptAllowed, Qt as ETHEREUM_USDT, Qu as withRequestOptions, R as parseGroupWakeFrame, Ra as formatFileSize, Rc as enrollCancelReason, Ri as capsDescriptors, Ro as sameButtonText, Rr as newerHead, Rs as serviceIdFromName, Ru as DEFAULT_RELAYS, S as GROUP_READ_NOTE_COMMUNITY, Sc as readHandoffPake, Sd as utf8Decode, Si as relayRequest, Sl as appViewOf, So as BUTTON_ID, Sr as groupSignalFrame, Ss as encodeControl, Su as TURN_RAISE_READ_TIMEOUT_MS, T as encodeCommunityLink, Tc as sealHandoffPiece, Ti as vapidKeysMatch, Tr as mayBeHub, Tu as turnPutSummary, U as frameBytes, Uc as enrollProofFrame, Uo as claimedTime, Ur as readLobby, Us as HANDOFF_HELLO, V as GROUP_READ_NOTE, Vc as enrollGrantFrame, Vl as readAppRevocationShape, Vr as readBeacon, Vs as HANDOFF_DONE, Vu as RelayTransport, W as CatchUpAnswers, Wc as readEnrollGrant, Wo as heardTime, Wr as shouldBeHub, Ws as HANDOFF_OFFER, Wu as currentRelays, X as parseCommunityEdit, Xa as parseVideoMeta, Xc as newInbox, Xl as readCanonicalJson, Xn as INVITE_TAKEN, Xo as MEMBER_KEY, Xr as transferStalled, Xs as NO_ATTEMPTS, Xu as budgetRetryMs, Y as meshMessageRef, Yc as inboxRecord, Yl as canonicalJsonBytes, Yn as GhostLink, Yr as transferEnded, Ys as HANDOFF_VERIFIED, Yt as encodeDidDhtPacket, Z as mentionsMember, Za as EDIT_BUFFER_MS, Zc as planKnocks, Zl as createContactLink, Zn as LIVENESS_PING_MS, Zo as commitHash, Zs as filePartName, Zt as signDidDhtPacket, Zu as isDiscoveryBudgetError, _ as groupTypingEpoch, _a as readManifest, _c as readHandoffAck, _d as fromBase64Url, _l as APP_BUNDLE_LIMITS, _n as isBitcoinAddress, _o as validReactionNumber, _r as CarriedTransport, _s as formatLocalTarget, _u as devicePingFrame, a as appRevocationFor, aa as TRANSPORTS, ac as handoffDataFrame, ad as createIdentity, al as contactDay, an as USDT_PUBLIC_RPC, ao as parseLinkPreview, ar as parseEngineError, as as emptyRatchetState, au as decodeInviteCode, b as COMMUNITY_LIMITS, bc as readHandoffHave, bd as toBase64Url, bi as newWakeToken, bo as readReply, bs as LIMITS, bu as webCryptoSigner, c as checkAppBeforeRun, cc as handoffHelloFrame, cd as publicKeyFromZ32, ci as PIN_LIMITS, cl as knockSlotRecords, cn as assertTokenUnits, co as COMMUNITY_REACTION_FRAME, cu as inviteOwnership, da as HOLD_DATED_BACK_MS, dc as handoffPakeFrame, dd as sanitizeAvatar, di as pinIsNewer, dl as mergeContactKnocks, dn as validatePaymentTarget, do as ReactionWindow, dr as groupFileFallback, du as ENROLL_CAPABILITY, ec as handoffAttemptSucceeded, ei as personStatus, el as turnOff, en as ONCHAIN_PROVIDER, eo as REMOVED_TEXT, er as pairedMessageFits, es as rosterHas, eu as createDeviceInvite, fa as HOLD_LIMITS, fc as handoffReleaseFrame, fi as pinNumberHolds, fl as openRequest, fn as walletNetworkOf, fo as nextReactionNumber, fs as PRESENCE_WINDOW, fu as HANDOFF_CAPABILITY, g as GroupTypingBoard, ga as newMailbox, gc as newHandoffId, gd as bytesEqual, gi as WAKE_ONLINE_DELAY_MS, gl as seenEntry, gn as sparkInvoiceDetails, go as readReaction, gs as GhostlyHttpError, gu as deviceLinkPairing, ha as isHoldUrl, hc as handoffVersions, hd as stripHidden, hi as WAKE_ONLINE_BATCH_MS, hl as requestRecords, hn as sparkAddressKind, ho as reactionIsNewer, hs as presenceSeenAt, hu as deviceKeyZ32, i as addedAppPermissions, ia as validExternalKey, ic as handoffContextProof, ii as TypingSender, il as contactAskerHolds, in as TEST_USDT_FAUCET_AMOUNT, ir as engineText, is as RatchetBox, iu as createChatInvite, j as knockRecords, jc as signTombstone, ji as APPS_CAPABILITY, jl as APP_STATEMENT_LIMITS, jn as ENDPOINT, jr as doorHubs, js as contactRtcConfig, ju as signTurnPacket, k as entryParams, kc as setAckFrame, ki as chatAppId, kl as sha256Paced, kr as beaconKeys, ku as nextTurnPosition, l as planAppUpdate, lc as handoffManifestFrames, ld as verify, li as mayPin, ll as linkRecords, ln as assertWholeSats, lo as GROUP_REACTION_FRAME, ma as HoldRefusedError, mc as handoffStreamKey, md as sanitizeDisplayText, mi as WAKE_CALL_INTERVAL_MS, ml as readLinkRecord, mn as SPARK_PROVIDER, mo as reactionEmoji, ms as WATCH_PEER_MS, mu as deviceEchoNonce, n as readX401SdJwtVc, na as PeerProofs, nc as handoffCancelFrame, nl as REQUEST_LIFETIME_MS, nn as SEPOLIA_TEST_USDT, no as dhtEditId, nr as EngineError, ns as edgeParams, nu as readDeviceInvite, o as appStoreDecision, oa as automaticTransport, oc as handoffDigest, od as identityFromSeed, oi as typingActivity, ol as knockSlotIdentity, on as WALLET_NETWORKS, oo as forwardedAgain, or as GROUP_FILE_LIMITS, os as ratchetSessionOf, ou as encodeInviteCode, p as readAppStoreSteps, pa as HoldKeys, pc as handoffRetryAfter, pd as hasVisible, pi as readPin, pl as readKnockSlot, pn as SPARK_NETWORKS, po as queueReaction, pr as readGroupFileMeta, ps as RELAY_POLL_INTERVALS, pu as deviceEchoFrame, q as GROUP_EDIT_TEXT_BYTES, qa as parseVoiceMeta, qc as clearMissed, qi as emptyIdentityLedger, qo as GROUP_ADMIN_OFF_ERROR, qs as HANDOFF_REQUEST, qt as didDhtFromPublicKey, r as sameX401HolderJwk, ra as emptyProofLedger, rc as handoffContext, rl as contactAskerFrame, rr as engineError, rs as RATCHET_CAPABILITY, ru as OwnInviteError, s as appUpdateDecision, sc as handoffEphemeral, sd as identityFromSeedB64, sl as knockSlotOf, sn as arkAddressPrefix, so as readForwarded, sr as GROUP_HAVE_FRAME, ss as DirectPathWatch, su as inviteLink, t as newX401HolderKey, ta as lastSharedWithMe, tc as handoffBusyFrame, td as createRelayPayload, tl as ContactRequestError, tn as PaymentPreflightError, to as RateWindow, tr as pairedMessageFrame, ts as verifyCommitSignature, tu as deviceInviteJoinerParams, u as APP_STORE_LIMITS, ua as HOLD_CAPABILITY, uc as handoffOfferFrame, ui as nextPinNumber, ul as makeStampPaced, un as formatPaymentAmount, uo as REACTION_LIMITS, us as DHT_POLL_INTERVALS, uu as DEVICES_CAPABILITY, v as openGroupTyping, vc as readHandoffCancel, vi as WakeLimiter, vl as APP_BUNDLE_MAGIC, vo as wireReaction, vs as parseLocalTarget, vt as isAtprotoDid, vu as newDeviceSetSecret, w as decodeCommunityLink, wc as readHandoffVerified, wi as checkPushEndpoint, wr as MESH_HUBS, wu as classifyTurnRead, x as CommunitySession, xc as readHandoffHello, xd as toZ32, xi as parseWakeFrame, xl as appDigest, xo as replySnippet, xs as decodeControl, y as sealGroupTyping, yc as readHandoffDone, yd as randomBytes, yi as deviceWakeRequest, yn as isPubkyKey, yo as pairedReplyAuthor, ys as webLocalFetch, yt as normalizeAtprotoHandle, yu as seedSigner, z as GROUP_LIMITS, za as sanitizeFileName, zc as enrollDigits, zi as dialDescriptors, zl as isAppRef, zr as pickHubs, zs as HANDOFF_ACK } from "./src-ChJijTlM.js";
3
+ import { i as SourceUnreachableError, n as PROVIDER_PLATFORMS, o as isNothingSpentError, r as SourceConfigError, t as NothingSpentError, u as redact } from "./types-Clyb52K2.js";
4
+ import { t as bitcoindRpc } from "./bitcoindProvider-BvoRh0D5.js";
5
+ import { t as nwc } from "./nwcProvider-Du5aWNIn.js";
6
6
  import { _ as openDb, a as GROUP_LIGHT_RANGE, b as transact, c as clearProfileStores, d as deleteDatabase, f as errorLine, g as newestWalletTx, h as groupLiveKey, i as FILE_INDEX, l as committed, m as groupLightKey, n as APP_STORAGE_SCOPE_INDEX, o as GROUP_LIVE_RANGE, p as fileStore, r as CARD_INDEX, s as STORES$1, t as APP_STORAGE_CHAT_INDEX, u as databaseName, v as profileOpenFailure, x as wrap, y as store } from "./idb-CEuoNsTv.js";
7
- import { a as sealSeed, c as openRow, d as sealRow, f as sealedStore, g as whenDataKeyDropped, h as sealSecret, i as newDeviceKey, l as openRows, m as openSecret, o as unsealSeed, p as hasDataKey, r as intentRepository, s as RowSeals, u as proofKey } from "./networkReason-DMffkiJ6.js";
7
+ import { a as sealSeed, c as openRow, d as sealRow, f as sealedStore, g as whenDataKeyDropped, h as sealSecret, i as newDeviceKey, l as openRows, m as openSecret, o as unsealSeed, p as hasDataKey, r as intentRepository, s as RowSeals, u as proofKey } from "./networkReason-n2oBs4by.js";
8
8
  import { c as fileSpace, f as FILE_BYTES_STEP, o as fileBytes, r as blobDigest, s as fileBytesOf, u as removeFileBytes } from "./fileBytes-BLPZq9YU.js";
9
- import { $ as iceServerProblem, A as storedSize, B as journaledPayment, C as paymentNetworksOf, D as FileAppender, E as WALLET_TYPES, F as CASHU_CARD, G as sourceKey, H as INVOICE_PACE, I as LightningCards, J as AskBackoff, K as CASHU_MINT_SOURCE, L as cardsKey, O as readStored$2, P as IdentityProofs, Q as dropBreezDatabase, R as isRecoveryPhrase, S as paymentNetwork, U as nextInvoiceAsk, V as lightningPaying, W as ProviderSources, X as breezDatabaseInUse, Y as breezDatabase, Z as breezDatabasesFor, _ as WALLET_NAMES, a as GroupFileDesk, at as networkLabel, b as createTiming, c as groupOfFile, ct as requireTurn, d as pairedWireReply, et as iceServerSetting, f as receivedPairedReply, g as paymentWireId, h as paymentAlias, i as onPublicIrohRelay, it as WrongNetworkError, j as streamStored, k as removeStored, l as storedGroupFiles, lt as setAwayWallets, m as replyTo, n as createIrohWebEndpoint, nt as ModeChanged, o as groupFileId, ot as awayFrom, p as replyRef, q as cashuMint, r as irohRelayProblem, rt as ModeGate, s as groupFileText, st as refuseAway, t as DEFAULT_IROH_RELAYS, tt as relayOnlyProblem, u as groupReply, ut as setSingleWriterGate, v as assertConfirmedReal, w as walletInstances, x as crossNetwork, y as createFailure, z as normalizePhrase } from "./irohWeb-CqPN8VPY.js";
10
- import { r as loadFedimintSdk, t as fedimintDatabase } from "./fedimintSdk-CqTeMdF0.js";
9
+ import { $ as lightningPaying, A as paymentNetworksOf, B as removeStored, C as paymentWireId, Ct as setSingleWriterGate, D as createTiming, E as createFailure, F as copyForForward, G as IdentityProofs, H as streamStored, I as forwardError, J as cardsKey, K as CASHU_CARD, L as forwardKind, N as WALLET_TYPES, O as crossNetwork, P as FORWARD_MESSAGE_GONE, Q as journaledPayment, R as FileAppender, S as paymentAlias, St as setAwayWallets, T as assertConfirmedReal, V as storedSize, X as breez, Y as BREEZ_SOURCE, Z as normalizePhrase, _ as groupReply, _t as WrongNetworkError, at as cashuMint, b as replyRef, bt as refuseAway, ct as loadBreezSdk, d as parsePayLink, dt as breezDatabasesFor, et as INVOICE_PACE, f as GroupFileDesk, ft as iceServerProblem, g as storedGroupFiles, gt as ModeGate, h as groupOfFile, ht as ModeChanged, i as onPublicIrohRelay, it as CASHU_MINT_SOURCE, j as walletInstances, k as paymentNetwork, l as groupLinkId, lt as openBreez, m as groupFileText, mt as relayOnlyProblem, n as createIrohWebEndpoint, nt as ProviderSources, o as groupPayLineId, ot as AskBackoff, p as groupFileId, pt as iceServerSetting, q as LightningCards, r as irohRelayProblem, rt as sourceKey, st as forgetBreez, t as DEFAULT_IROH_RELAYS, tt as nextInvoiceAsk, u as pairLinkId, ut as breezDatabaseInUse, v as pairedWireReply, vt as networkLabel, w as WALLET_NAMES, x as replyTo, xt as requireTurn, y as receivedPairedReply, yt as awayFrom, z as readStored$2 } from "./irohWeb-DGelfgDJ.js";
10
+ import { r as loadFedimintSdk, t as fedimintDatabase } from "./fedimintSdk-DRKRSw14.js";
11
11
  import { c as isTestMint, d as mintUrlSpelling, f as paysItsOwnInvoices, l as isWorthlessMint, n as DEFAULT_MINTS, o as fakesLightning, r as TEST_MINT, t as BITCOIN_INVOICE_ON_TESTNET, u as mintNetwork } from "./mints-j5XAOk4f.js";
12
- import { a as registeredLightningProviders, c as boundedIdentityFetch, d as testSwitch, n as setOwnDidSource, o as registeredOnchainProviders, r as onAdaptersChanged, s as reserveAdapterIds, u as testBuild } from "./ownDid-iKz8u_fM.js";
13
- import { d as chosenResolver, m as setPkarrRelaySource, r as resolveAtprotoDid, t as assertPublicServer } from "./resolve-DI8uAM_Y.js";
14
- import { n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-Q_rMgoE9.js";
12
+ import { a as registeredLightningProviders, c as boundedIdentityFetch, d as testSwitch, n as setOwnDidSource, o as registeredOnchainProviders, r as onAdaptersChanged, s as reserveAdapterIds, u as testBuild } from "./ownDid-CwwYu8s2.js";
13
+ import { d as chosenResolver, m as setPkarrRelaySource, r as resolveAtprotoDid, t as assertPublicServer } from "./resolve-3Tqh9AWQ.js";
14
+ import { a as boundedAppFetch, i as besideUrl, n as AppFetchError, o as isAppFetchUrl, r as appPasteUrl, s as isGitHubPage, t as APP_FETCH_LIMITS } from "./appFetch-BKHy5H8J.js";
15
+ import { n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-Dud6lntA.js";
15
16
  import { t as hyperdhtRelayProblem } from "./hyperdhtRelay-1wzya_0L.js";
16
17
  import { sha256 } from "@noble/hashes/sha2.js";
17
18
  import { hkdf } from "@noble/hashes/hkdf.js";
@@ -745,7 +746,7 @@ function viewNews(before, after) {
745
746
  //#endregion
746
747
  //#region ../browser/src/engine/paymentAdapters/usdtWallet.ts
747
748
  /** The Ethereum libraries, a large part of the app: loaded once a USDT wallet is made, opened or restored, not with the engine. */
748
- var loadUsdt = () => import("./usdt-CDaLhEYh.js");
749
+ var loadUsdt = () => import("./usdt-CSU5KzTV.js");
749
750
  /** Every new profile starts with this wallet: an address to receive on, nothing to set up. */
750
751
  var DEFAULT_USDT = {
751
752
  network: "ethereum",
@@ -1105,6 +1106,7 @@ var SWITCHES = [
1105
1106
  "publicProfiles",
1106
1107
  "sendTyping",
1107
1108
  "sharePresence",
1109
+ "daemonPresence",
1108
1110
  "autoDownloads",
1109
1111
  "serveFiles"
1110
1112
  ];
@@ -1233,7 +1235,7 @@ async function restoreArkDatabase(walletId, snapshot) {
1233
1235
  //#endregion
1234
1236
  //#region ../browser/src/engine/paymentAdapters/arkWallet.ts
1235
1237
  /** The Ark SDK, a large part of the app: loaded once an Ark wallet is made, opened or restored, not with the engine. */
1236
- var loadArkade = () => import("./arkade-_aaB7VbW.js");
1238
+ var loadArkade = () => import("./arkade-CZrLbz-M.js");
1237
1239
  /** How long a Testnet wallet about to make way for another waits for its server to say what it holds. */
1238
1240
  var RETIRE_READ_MS = 1e4;
1239
1241
  /** Every new profile starts with this wallet: nothing to set up before receiving. */
@@ -1681,10 +1683,10 @@ var NETWORK = {
1681
1683
  signet: "Signet",
1682
1684
  regtest: "Regtest"
1683
1685
  };
1684
- var loading$3;
1686
+ var loading$2;
1685
1687
  /** Loads the WebAssembly once, on first use: profiles that never open a Bark wallet never fetch its 7.7 MB. */
1686
1688
  function loadBarkSdk() {
1687
- return loading$3 ??= (async () => {
1689
+ return loading$2 ??= (async () => {
1688
1690
  const [bark, wasm] = await Promise.all([import("@secondts/bark/web"), import("./bark_ffi_wasm_bg-EY2uc0Bx.js")]);
1689
1691
  await bark.default({ module_or_path: wasm.default });
1690
1692
  return {
@@ -1723,7 +1725,7 @@ function loadBarkSdk() {
1723
1725
  }
1724
1726
  };
1725
1727
  })().catch((error) => {
1726
- loading$3 = void 0;
1728
+ loading$2 = void 0;
1727
1729
  throw error;
1728
1730
  });
1729
1731
  }
@@ -2543,7 +2545,7 @@ var NOTES_REFUND_SECS = 604800;
2543
2545
  var MAX_SATS = 1e7;
2544
2546
  var fedimintMode = (network) => network === "bitcoin" ? "mainnet" : "testnet";
2545
2547
  var key = (mode) => `fedimintWallet-${mode}`;
2546
- var sats$6 = (msats) => Math.floor(msats / 1e3);
2548
+ var sats$5 = (msats) => Math.floor(msats / 1e3);
2547
2549
  function assertFedimintAmount(amount) {
2548
2550
  if (!Number.isSafeInteger(amount) || amount <= 0) throw new Error("Enter an amount in sats");
2549
2551
  if (amount > MAX_SATS) throw new Error(`Amounts above ${MAX_SATS.toLocaleString("en-US")} sats are not supported`);
@@ -2566,21 +2568,21 @@ function historyEntry(federation, op) {
2566
2568
  };
2567
2569
  const invoiceSats = () => {
2568
2570
  const decoded = op.invoice ? decodeBolt11(op.invoice) : null;
2569
- return decoded?.amountMsat ? sats$6(Number(decoded.amountMsat)) : void 0;
2571
+ return decoded?.amountMsat ? sats$5(Number(decoded.amountMsat)) : void 0;
2570
2572
  };
2571
2573
  if (op.kind === "mint" && op.variant === "spend_o_o_b") {
2572
2574
  const state = text === "UserCanceledSuccess" || text === "Refunded" ? "taken-back" : text === "UserCanceledFailure" || text === "Success" ? "done" : "pending";
2573
2575
  return {
2574
2576
  ...base,
2575
2577
  kind: "notes-out",
2576
- amount: op.amountMsats !== void 0 ? sats$6(op.amountMsats) : void 0,
2578
+ amount: op.amountMsats !== void 0 ? sats$5(op.amountMsats) : void 0,
2577
2579
  state
2578
2580
  };
2579
2581
  }
2580
2582
  if (op.kind === "mint" && op.variant === "reissuance") return {
2581
2583
  ...base,
2582
2584
  kind: "notes-in",
2583
- amount: op.amountMsats !== void 0 ? sats$6(op.amountMsats) : void 0,
2585
+ amount: op.amountMsats !== void 0 ? sats$5(op.amountMsats) : void 0,
2584
2586
  state: text === "Done" ? "done" : text === "Failed" ? "failed" : "pending"
2585
2587
  };
2586
2588
  if (op.kind === "ln" && op.variant === "receive") return {
@@ -2602,7 +2604,7 @@ function historyEntry(federation, op) {
2602
2604
  if (op.kind === "wallet") return {
2603
2605
  ...base,
2604
2606
  kind: "onchain",
2605
- amount: op.amountMsats !== void 0 ? sats$6(op.amountMsats) : void 0,
2607
+ amount: op.amountMsats !== void 0 ? sats$5(op.amountMsats) : void 0,
2606
2608
  state: "pending"
2607
2609
  };
2608
2610
  }
@@ -2736,7 +2738,7 @@ var FedimintWallet = class {
2736
2738
  render() {
2737
2739
  const federations = (this.saved?.federations ?? []).map(({ database: _database, ...f }) => ({
2738
2740
  ...f,
2739
- balance: sats$6(this.balances.get(f.id) ?? 0),
2741
+ balance: sats$5(this.balances.get(f.id) ?? 0),
2740
2742
  ...this.balances.has(f.id) ? { read: true } : {},
2741
2743
  status: this.clients.has(f.id) ? "ready" : this.problems.has(f.id) ? "error" : "connecting",
2742
2744
  error: this.problems.get(f.id),
@@ -2860,7 +2862,7 @@ var FedimintWallet = class {
2860
2862
  if (!saved || !federation) throw new Error("Unknown federation");
2861
2863
  const client = this.clients.get(federationId);
2862
2864
  if (!client) throw new Error("Wait for this federation to connect: its balance must be read before leaving it");
2863
- if (sats$6(await client.balance()) > 0) throw new Error("This federation still holds your sats: spend or move them first");
2865
+ if (sats$5(await client.balance()) > 0) throw new Error("This federation still holds your sats: spend or move them first");
2864
2866
  if ((await intentRepository.list()).some((i) => i.review.method === "fedimint" && i.review.provider === federationId && [
2865
2867
  "pending",
2866
2868
  "submitted",
@@ -2868,7 +2870,7 @@ var FedimintWallet = class {
2868
2870
  ].includes(i.review.state))) throw new Error("A payment through this federation is not finished yet");
2869
2871
  const out = (await client.operations(100)).filter((op) => historyEntry(federationId, op)?.kind === "notes-out" && historyEntry(federationId, op)?.state === "pending");
2870
2872
  for (const op of out) if (await this.takeBack(federationId, op.id, 15e3) === "pending") throw new Error("Notes you sent from this federation are still being settled: try again in a moment");
2871
- if (sats$6(await client.balance()) > 0) throw new Error("Notes nobody redeemed came back to this federation: spend or move them first");
2873
+ if (sats$5(await client.balance()) > 0) throw new Error("Notes nobody redeemed came back to this federation: spend or move them first");
2872
2874
  this.unsubscribe.get(federationId)?.();
2873
2875
  this.unsubscribe.delete(federationId);
2874
2876
  this.clients.delete(federationId);
@@ -2939,7 +2941,7 @@ var FedimintWallet = class {
2939
2941
  async spendNotes(federationId, amount, ghostly = `wallet-${crypto.randomUUID()}`) {
2940
2942
  assertFedimintAmount(amount);
2941
2943
  const client = this.client(federationId);
2942
- if (sats$6(await client.balance()) < amount) throw engineError("fedimintNotEnough");
2944
+ if (sats$5(await client.balance()) < amount) throw engineError("fedimintNotEnough");
2943
2945
  const spent = await client.spend(amount * 1e3, {
2944
2946
  cancelAfterSecs: NOTES_REFUND_SECS,
2945
2947
  ghostly
@@ -2995,7 +2997,7 @@ var FedimintWallet = class {
2995
2997
  if (state !== "done") throw new Error("The federation is still redeeming these notes: they will show in the balance");
2996
2998
  return {
2997
2999
  federation: found.federation,
2998
- amount: sats$6(found.amountMsats)
3000
+ amount: sats$5(found.amountMsats)
2999
3001
  };
3000
3002
  }
3001
3003
  /** Takes notes back. `canceled`: they are ours again; `taken`: the recipient redeemed them first; `pending`: not settled yet. */
@@ -3274,102 +3276,16 @@ var FedimintAdapter = class {
3274
3276
  }
3275
3277
  };
3276
3278
  //#endregion
3277
- //#region ../browser/src/engine/paymentAdapters/providers/breezSdk.ts
3278
- var loading$2;
3279
- /** Loads the WebAssembly once, on first use: profiles that never pick Breez never fetch its 12.8 MB. */
3280
- function loadBreezSdk() {
3281
- return loading$2 ??= (async () => {
3282
- const breez = await import("./web-DwgdhfcY.js");
3283
- await breez.default();
3284
- return { async connect({ network, mnemonic, apiKey, storage }) {
3285
- const config = breez.defaultConfig(network);
3286
- if (apiKey) config.apiKey = apiKey;
3287
- return breez.connect({
3288
- config,
3289
- seed: {
3290
- type: "mnemonic",
3291
- mnemonic
3292
- },
3293
- storageDir: storage
3294
- });
3295
- } };
3296
- })().catch((error) => {
3297
- loading$2 = void 0;
3298
- throw error;
3299
- });
3300
- }
3301
- var hex$8 = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
3302
- var breezNetwork = (network) => network === "bitcoin" ? "mainnet" : "regtest";
3303
- var DISCONNECT_MS = 1e4;
3304
- /** One SDK instance per wallet storage: two over one database would each think the leaves are theirs. */
3305
- var open = /* @__PURE__ */ new Map();
3306
- /**
3307
- * Opens the Breez wallet of this seed on this network, or shares the one already open (the Spark rail and the
3308
- * Breez Lightning source of the same seed are one wallet). `release` gives this user's share back; the last one
3309
- * disconnects the SDK. `storage`: the database it opened, which `forgetBreez` deletes when the wallet is removed.
3310
- */
3311
- async function openBreez(params, sdk = loadBreezSdk, storage = breezDatabase) {
3312
- const name = await storage(params.network, params.mnemonic);
3313
- const key = `${name}|${params.apiKey ? hex$8(sha256(new TextEncoder().encode(params.apiKey))).slice(0, 8) : ""}`;
3314
- let entry = open.get(key);
3315
- if (!entry) {
3316
- const wallet = sdk().then((module) => module.connect({
3317
- network: breezNetwork(params.network),
3318
- mnemonic: params.mnemonic,
3319
- apiKey: params.apiKey,
3320
- storage: name
3321
- }));
3322
- entry = {
3323
- wallet,
3324
- refs: 0
3325
- };
3326
- open.set(key, entry);
3327
- wallet.catch(() => {
3328
- if (open.get(key) === entry) open.delete(key);
3329
- });
3330
- }
3331
- entry.refs++;
3332
- const held = entry;
3333
- let wallet;
3334
- try {
3335
- wallet = await held.wallet;
3336
- } catch (error) {
3337
- held.refs--;
3338
- throw error;
3339
- }
3340
- let released = false;
3341
- return {
3342
- wallet,
3343
- storage: name,
3344
- release: async () => {
3345
- if (released) return;
3346
- released = true;
3347
- if (--held.refs > 0) return;
3348
- if (open.get(key) === held) open.delete(key);
3349
- await Promise.race([wallet.disconnect(), new Promise((resolve) => setTimeout(resolve, DISCONNECT_MS))]);
3350
- }
3351
- };
3352
- }
3353
- /** Whether a wallet of this storage is open here (the Spark rail and a Breez card of one seed share it). */
3354
- var breezOpen = (storage) => [...open.keys()].some((key) => key.startsWith(`${storage}|`));
3355
- /**
3356
- * A wallet was removed: its Breez databases go, unless another user in this profile still has them open (a Breez
3357
- * Lightning card on the Spark wallet's own phrase). That one deletes them when it is removed in turn.
3358
- */
3359
- async function forgetBreez(storage) {
3360
- if (!breezOpen(storage)) await dropBreezDatabase(storage);
3361
- }
3362
- //#endregion
3363
3279
  //#region ../browser/src/engine/paymentAdapters/spark.ts
3364
3280
  /** Payments read to find one: newest first, bounded. */
3365
- var PAGE$1 = 100;
3366
- var PAGES$1 = 5;
3367
- var sats$5 = (value) => {
3281
+ var PAGE = 100;
3282
+ var PAGES = 5;
3283
+ var sats$4 = (value) => {
3368
3284
  const n = Number(value);
3369
3285
  if (!Number.isSafeInteger(n) || n < 0) throw new Error("Spark returned an invalid amount");
3370
3286
  return n;
3371
3287
  };
3372
- var message$5 = (error) => error instanceof Error ? error.message : typeof error === "string" ? error : "Spark refused the payment";
3288
+ var message$4 = (error) => error instanceof Error ? error.message : typeof error === "string" ? error : "Spark refused the payment";
3373
3289
  var invoiceOf = (p) => p.details?.type === "spark" ? p.details.invoiceDetails?.invoice : void 0;
3374
3290
  /** A fresh RFC 4122 v4 UUID: the SDK wants its idempotency keys in that form. */
3375
3291
  var newSparkKey = () => crypto.randomUUID();
@@ -3429,7 +3345,7 @@ var SparkAdapter = class SparkAdapter {
3429
3345
  return paymentRequest;
3430
3346
  }
3431
3347
  async balance() {
3432
- return sats$5((await this.wallet.getInfo({ ensureSynced: false })).balanceSats);
3348
+ return sats$4((await this.wallet.getInfo({ ensureSynced: false })).balanceSats);
3433
3349
  }
3434
3350
  /** Asks Spark's operators for what changed (transfers to claim, payments that completed). */
3435
3351
  async sync() {
@@ -3443,8 +3359,8 @@ var SparkAdapter = class SparkAdapter {
3443
3359
  return payments.map((p) => ({
3444
3360
  id: p.id,
3445
3361
  direction: p.paymentType === "send" ? "out" : "in",
3446
- amount: sats$5(p.amount),
3447
- fee: sats$5(p.fees),
3362
+ amount: sats$4(p.amount),
3363
+ fee: sats$4(p.fees),
3448
3364
  at: p.timestamp * 1e3,
3449
3365
  status: p.status,
3450
3366
  via: p.method === "spark" ? "spark" : p.method === "lightning" ? "lightning" : p.method === "deposit" || p.method === "withdraw" ? "onchain" : "other",
@@ -3486,7 +3402,7 @@ var SparkAdapter = class SparkAdapter {
3486
3402
  if (await this.balance() < review.amount + review.fee) throw new Error("Spark balance changed. Create a new review");
3487
3403
  if (!persist) throw new Error("Durable payment journal required");
3488
3404
  } catch (error) {
3489
- throw new PaymentPreflightError(message$5(error));
3405
+ throw new PaymentPreflightError(message$4(error));
3490
3406
  }
3491
3407
  await persist();
3492
3408
  try {
@@ -3498,7 +3414,7 @@ var SparkAdapter = class SparkAdapter {
3498
3414
  } catch (error) {
3499
3415
  const found = await this.sent(review, prepared).catch(() => void 0);
3500
3416
  if (found) return this.outcome(found);
3501
- throw new Error(/insufficient/i.test(message$5(error)) ? "Insufficient Spark balance" : "Spark payment outcome unknown");
3417
+ throw new Error(/insufficient/i.test(message$4(error)) ? "Insufficient Spark balance" : "Spark payment outcome unknown");
3502
3418
  }
3503
3419
  });
3504
3420
  }
@@ -3519,17 +3435,17 @@ var SparkAdapter = class SparkAdapter {
3519
3435
  * amount asked. Nothing the payer says is trusted. `claimed`: transfers that already paid another request.
3520
3436
  */
3521
3437
  async received(invoice, amount, since, claimed = /* @__PURE__ */ new Set()) {
3522
- for (let page = 0; page < PAGES$1; page++) {
3438
+ for (let page = 0; page < PAGES; page++) {
3523
3439
  const { payments } = await this.wallet.listPayments({
3524
3440
  typeFilter: ["receive"],
3525
3441
  fromTimestamp: Math.floor(since / 1e3) - 600,
3526
- offset: page * PAGE$1,
3527
- limit: PAGE$1,
3442
+ offset: page * PAGE,
3443
+ limit: PAGE,
3528
3444
  sortAscending: false
3529
3445
  });
3530
- const found = payments.find((p) => p.status === "completed" && invoiceOf(p) === invoice && sats$5(p.amount) >= amount && !claimed.has(p.id));
3446
+ const found = payments.find((p) => p.status === "completed" && invoiceOf(p) === invoice && sats$4(p.amount) >= amount && !claimed.has(p.id));
3531
3447
  if (found) return found.id;
3532
- if (payments.length < PAGE$1) break;
3448
+ if (payments.length < PAGE) break;
3533
3449
  }
3534
3450
  }
3535
3451
  async close() {
@@ -3557,12 +3473,12 @@ var SparkAdapter = class SparkAdapter {
3557
3473
  } else if (method.type === "sparkInvoice") {
3558
3474
  const details = method.sparkInvoiceDetails;
3559
3475
  if (details.invoice !== address || details.tokenIdentifier) throw new Error("Spark prepared a payment to another invoice");
3560
- if (details.amount !== void 0 && sats$5(details.amount) !== amount) throw new Error("The Spark invoice is for another amount");
3476
+ if (details.amount !== void 0 && sats$4(details.amount) !== amount) throw new Error("The Spark invoice is for another amount");
3561
3477
  if (details.expiryTime !== void 0 && details.expiryTime * 1e3 < Date.now()) throw new Error("The Spark invoice has expired");
3562
3478
  } else throw new Error("Spark would not pay this as a Spark transfer");
3563
- if (sats$5(quote.amount) !== amount) throw new Error("Spark prepared another amount");
3479
+ if (sats$4(quote.amount) !== amount) throw new Error("Spark prepared another amount");
3564
3480
  return {
3565
- fee: sats$5(method.fee),
3481
+ fee: sats$4(method.fee),
3566
3482
  kind: method.type === "sparkAddress" ? "address" : "invoice"
3567
3483
  };
3568
3484
  }
@@ -3581,7 +3497,7 @@ var SparkAdapter = class SparkAdapter {
3581
3497
  const { payments } = await this.wallet.listPayments({
3582
3498
  typeFilter: ["send"],
3583
3499
  fromTimestamp: Math.floor(review.createdAt / 1e3) - 600,
3584
- limit: PAGE$1,
3500
+ limit: PAGE,
3585
3501
  sortAscending: false
3586
3502
  });
3587
3503
  const mine = payments.filter((p) => invoiceOf(p) === prepared.address);
@@ -4474,278 +4390,6 @@ var BitcoinService = class {
4474
4390
  }
4475
4391
  };
4476
4392
  //#endregion
4477
- //#region ../browser/src/engine/paymentAdapters/providers/breez.ts
4478
- var BREEZ_SOURCE = "breez";
4479
- /**
4480
- * Where the Breez source is offered: Mainnet ("bitcoin", with the person's Breez API key, which the form requires
4481
- * there) and Breez and Lightspark's hosted regtest (no API key).
4482
- */
4483
- var BREEZ_NETWORKS = ["bitcoin", "regtest"];
4484
- /** WebAssembly and HTTPS only: the page, the extension's offscreen document and Tauri's WebView all run it. */
4485
- var BREEZ_PLATFORMS = [
4486
- "web",
4487
- "extension",
4488
- "desktop"
4489
- ];
4490
- var INVOICE_EXPIRY_SECS = 3600;
4491
- /** How long `payInvoice` waits for the payment to settle before answering `pending`. */
4492
- var COMPLETION_SECS = 30;
4493
- /** A fee shown to the person is paid with the same prepared payment for this long, then prepared again. */
4494
- var QUOTE_MS = 6e4;
4495
- /** Payments read to find one by its hash: newest first, bounded. */
4496
- var PAGE = 100;
4497
- var PAGES = 10;
4498
- /** Without any record of a payment, it is called failed only this long after its invoice expired. */
4499
- var LOST_AFTER_MS = 36e5;
4500
- var hex$7 = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
4501
- var sats$4 = (value) => {
4502
- const n = Number(value);
4503
- if (!Number.isSafeInteger(n) || n < 0) throw new Error("Breez returned an invalid amount");
4504
- return n;
4505
- };
4506
- var message$4 = (error) => error instanceof Error ? error.message : typeof error === "string" ? error : "Breez refused the payment";
4507
- /**
4508
- * The idempotency key of one attempt at paying one invoice: asking the SDK twice with it pays once.
4509
- * A new attempt (after one that failed) gets a new key, or the SDK would only hand back the failure.
4510
- */
4511
- function idempotencyKey(paymentHash, attempt) {
4512
- const b = sha256(new TextEncoder().encode(`ghostly-breez-pay:${paymentHash}:${attempt}`)).slice(0, 16);
4513
- b[6] = b[6] & 15 | 64;
4514
- b[8] = b[8] & 63 | 128;
4515
- const h = hex$7(b);
4516
- return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
4517
- }
4518
- /** The payment hash a Breez payment is about, when it is one (Lightning, or a Spark HTLC). */
4519
- function hashOf(payment) {
4520
- const details = payment.details;
4521
- if (details?.type === "lightning") return details.htlcDetails.paymentHash;
4522
- if (details?.type === "spark") return details.htlcDetails?.paymentHash;
4523
- }
4524
- function preimageOf(payment) {
4525
- const details = payment.details;
4526
- return details?.type === "lightning" ? details.htlcDetails.preimage : details?.type === "spark" ? details.htlcDetails?.preimage : void 0;
4527
- }
4528
- /**
4529
- * Lightning through the Breez SDK, nodeless: a self-custodial wallet on Spark whose seed Ghostly
4530
- * generated (or the person restored) and keeps sealed. Invoices are received and paid through Breez's
4531
- * and Lightspark's Spark service providers; the sats are the seed's.
4532
- *
4533
- * Nothing is reported by itself: the engine polls `invoiceStatus` and `paymentStatus`, which find a
4534
- * payment by its hash in the wallet's history.
4535
- */
4536
- var BreezLightning = class BreezLightning {
4537
- wallet;
4538
- network;
4539
- release;
4540
- storage;
4541
- capabilities = {
4542
- receive: true,
4543
- send: true,
4544
- balance: true,
4545
- lookup: true
4546
- };
4547
- /** The prepared payment behind a fee just shown: `payInvoice` pays exactly that one while it is fresh. */
4548
- quotes = /* @__PURE__ */ new Map();
4549
- closed = false;
4550
- /** `storage`: the Breez database this card opened (`breezDatabase`). */
4551
- constructor(wallet, network, release, storage) {
4552
- this.wallet = wallet;
4553
- this.network = network;
4554
- this.release = release;
4555
- this.storage = storage;
4556
- }
4557
- static async connect(params, sdk = loadBreezSdk, storage = breezDatabase) {
4558
- const opened = await openBreez(params, sdk, storage);
4559
- return new BreezLightning(opened.wallet, params.network, opened.release, opened.storage);
4560
- }
4561
- async info() {
4562
- const { balanceSats } = await this.wallet.getInfo({ ensureSynced: false });
4563
- return {
4564
- network: this.network,
4565
- balance: sats$4(balanceSats)
4566
- };
4567
- }
4568
- async createInvoice(amount, memo) {
4569
- const { paymentRequest } = await this.wallet.receivePayment({ paymentMethod: {
4570
- type: "bolt11Invoice",
4571
- description: (memo ?? "").slice(0, 100),
4572
- amountSats: amount,
4573
- expirySecs: INVOICE_EXPIRY_SECS
4574
- } });
4575
- const decoded = decodeBolt11(paymentRequest);
4576
- if (!decoded?.paymentHash || decoded.amountSat !== amount) throw new Error("Breez returned an invoice that does not match the request");
4577
- return {
4578
- invoice: decoded.invoice,
4579
- paymentHash: decoded.paymentHash,
4580
- amount,
4581
- expiresAt: decoded.expiresAt * 1e3
4582
- };
4583
- }
4584
- async invoiceStatus(invoice) {
4585
- const payment = await this.find("receive", invoice.paymentHash, invoice.invoice);
4586
- if (payment?.status === "completed") return {
4587
- state: "paid",
4588
- amount: sats$4(payment.amount)
4589
- };
4590
- if (payment?.status === "pending") return { state: "open" };
4591
- return { state: invoice.expiresAt < Date.now() ? "expired" : "open" };
4592
- }
4593
- /** Prepares the payment (nothing is sent) and keeps it for `payInvoice`: its fee is the one shown. */
4594
- async estimateFee(invoice, amount) {
4595
- const prepared = await this.prepare(invoice, amount);
4596
- this.quotes.set(decodeBolt11(invoice)?.invoice ?? invoice, {
4597
- prepared,
4598
- at: Date.now()
4599
- });
4600
- return this.feeOf(prepared);
4601
- }
4602
- async payInvoice(invoice, maxFee) {
4603
- const decoded = decodeBolt11(invoice);
4604
- if (!decoded?.paymentHash || decoded.amountSat === null) throw new NothingSpentError("That is not an invoice Breez can pay");
4605
- const hash = decoded.paymentHash, amount = decoded.amountSat, key = decoded.invoice;
4606
- let prepared, attempt;
4607
- try {
4608
- if (this.closed) throw new Error("The Breez wallet is closed");
4609
- const previous = await this.history("send", hash, decoded.invoice, decoded.createdAt);
4610
- const live = previous.find((p) => p.status !== "failed");
4611
- if (live) return this.result(live);
4612
- attempt = previous.length;
4613
- const quote = this.quotes.get(key);
4614
- this.quotes.delete(key);
4615
- prepared = quote && Date.now() - quote.at < QUOTE_MS ? quote.prepared : await this.prepare(decoded.invoice, amount);
4616
- const fee = this.feeOf(prepared);
4617
- if (fee > maxFee) throw new Error(`The Lightning fee (${fee} sats) is above your limit (${maxFee})`);
4618
- const { balanceSats } = await this.wallet.getInfo({ ensureSynced: false });
4619
- if (sats$4(balanceSats) < amount + fee) throw new Error(`Not enough sats in the Breez wallet (${sats$4(balanceSats)}; ${amount + fee} needed)`);
4620
- } catch (error) {
4621
- throw isNothingSpentError(error) ? error : new NothingSpentError(message$4(error));
4622
- }
4623
- const { payment } = await this.wallet.sendPayment({
4624
- prepareResponse: prepared,
4625
- options: {
4626
- type: "bolt11Invoice",
4627
- preferSpark: false,
4628
- completionTimeoutSecs: COMPLETION_SECS
4629
- },
4630
- idempotencyKey: idempotencyKey(hash, attempt)
4631
- });
4632
- return this.result(payment);
4633
- }
4634
- async paymentStatus(ref) {
4635
- const decoded = decodeBolt11(ref.invoice);
4636
- let payment = await this.find("send", ref.paymentHash, ref.invoice, decoded?.createdAt);
4637
- if (!payment && ref.ref) {
4638
- const byId = (await this.wallet.getPayment({ paymentId: ref.ref }).catch(() => void 0))?.payment;
4639
- if (byId && hashOf(byId) === ref.paymentHash) payment = byId;
4640
- }
4641
- if (!payment) {
4642
- await this.wallet.syncWallet({});
4643
- payment = await this.find("send", ref.paymentHash, ref.invoice, decoded?.createdAt);
4644
- }
4645
- if (!payment) return { state: (decoded ? decoded.expiresAt * 1e3 + LOST_AFTER_MS < Date.now() : false) ? "failed" : "pending" };
4646
- const state = payment.status === "completed" ? "paid" : payment.status === "failed" ? "failed" : "pending";
4647
- return {
4648
- state,
4649
- fee: state === "paid" ? sats$4(payment.fees) : void 0,
4650
- preimage: preimageOf(payment)
4651
- };
4652
- }
4653
- async close() {
4654
- if (this.closed) return;
4655
- this.closed = true;
4656
- this.quotes.clear();
4657
- await this.release();
4658
- }
4659
- /** The card is removed: closed, and its Breez databases deleted unless the Spark wallet of this phrase has them open. */
4660
- async forget() {
4661
- await this.close();
4662
- await forgetBreez(this.storage);
4663
- }
4664
- async prepare(invoice, amount) {
4665
- const prepared = await this.wallet.prepareSendPayment({ paymentRequest: {
4666
- type: "input",
4667
- input: invoice
4668
- } });
4669
- const method = prepared.paymentMethod;
4670
- if (method.type !== "bolt11Invoice") throw new Error("Breez would not pay this as a Lightning invoice");
4671
- if (method.invoiceDetails.paymentHash !== decodeBolt11(invoice)?.paymentHash || sats$4(prepared.amount) !== amount) throw new Error("Breez prepared a payment that does not match the invoice");
4672
- return prepared;
4673
- }
4674
- feeOf(prepared) {
4675
- if (prepared.paymentMethod.type !== "bolt11Invoice") throw new Error("Breez would not pay this as a Lightning invoice");
4676
- return sats$4(prepared.paymentMethod.lightningFeeSats);
4677
- }
4678
- /** `failed` is never an answer here: a payment the SDK gave up on is pending until `paymentStatus` says so. */
4679
- result(payment) {
4680
- if (payment.status === "completed") return {
4681
- state: "paid",
4682
- fee: sats$4(payment.fees),
4683
- preimage: preimageOf(payment),
4684
- ref: payment.id
4685
- };
4686
- return {
4687
- state: "pending",
4688
- ref: payment.id
4689
- };
4690
- }
4691
- async find(type, hash, invoice, createdAt) {
4692
- const found = await this.history(type, hash, invoice, createdAt);
4693
- return found.find((p) => p.status === "completed") ?? found.find((p) => p.status === "pending") ?? found[0];
4694
- }
4695
- /** This wallet's payments of this hash, newest first. Only payments since the invoice was made are read. */
4696
- async history(type, hash, invoice, createdAt = decodeBolt11(invoice)?.createdAt) {
4697
- const found = [];
4698
- for (let page = 0; page < PAGES; page++) {
4699
- const { payments } = await this.wallet.listPayments({
4700
- typeFilter: [type],
4701
- fromTimestamp: createdAt ? createdAt - 600 : void 0,
4702
- offset: page * PAGE,
4703
- limit: PAGE,
4704
- sortAscending: false
4705
- });
4706
- found.push(...payments.filter((p) => hashOf(p) === hash));
4707
- if (payments.length < PAGE) break;
4708
- }
4709
- return found;
4710
- }
4711
- };
4712
- /** The descriptor, with the SDK it loads (tests hand it a fake). */
4713
- var breezDescriptor = (sdk = loadBreezSdk) => ({
4714
- id: BREEZ_SOURCE,
4715
- label: "Breez (Spark)",
4716
- kind: "lightning",
4717
- description: "A self-custodial Lightning wallet on Spark, through the Breez SDK. Its recovery phrase is sealed on this device; you hold the sats.",
4718
- networks: BREEZ_NETWORKS,
4719
- platforms: BREEZ_PLATFORMS,
4720
- fields: [{
4721
- name: "mnemonic",
4722
- label: "Recovery phrase",
4723
- kind: "secret",
4724
- placeholder: "twelve words…",
4725
- help: "Made by Ghostly for a new wallet, or yours to restore one."
4726
- }, {
4727
- name: "apiKey",
4728
- label: "Breez API key",
4729
- kind: "secret",
4730
- optional: true,
4731
- help: "Required on Mainnet (free, from Breez). Not needed in Testnet (regtest)."
4732
- }],
4733
- experimental: true,
4734
- validate({ secrets }, mode) {
4735
- if (!isRecoveryPhrase(secrets.mnemonic ?? "")) throw new Error("That is not a valid recovery phrase");
4736
- if (mode === "mainnet" && !secrets.apiKey?.trim()) throw new Error("Breez needs an API key on Mainnet");
4737
- },
4738
- async create({ secrets }, host) {
4739
- const network = host.mode === "mainnet" ? "bitcoin" : "regtest";
4740
- return BreezLightning.connect({
4741
- network,
4742
- mnemonic: normalizePhrase(secrets.mnemonic),
4743
- apiKey: secrets.apiKey?.trim() || void 0
4744
- }, sdk);
4745
- }
4746
- });
4747
- var breez = breezDescriptor();
4748
- //#endregion
4749
4393
  //#region ../browser/src/engine/paymentAdapters/providers/bdkSdk.ts
4750
4394
  var WASM_IMPORTS = "./bitcoindevkit_bg.js";
4751
4395
  var appLoader = async () => {
@@ -9818,7 +9462,7 @@ var HostNotContacted = class extends Error {};
9818
9462
  */
9819
9463
  function fixedHostsFetch(fetch) {
9820
9464
  return async (url, options) => {
9821
- const { fixedIdentityHosts } = await import("./fixedHosts-BV5GDiTU.js");
9465
+ const { fixedIdentityHosts } = await import("./fixedHosts-CNX7QiUD.js");
9822
9466
  const host = hostOf$1(url);
9823
9467
  if (!fixedIdentityHosts().has(host) && host !== hostOf$1("https://public.api.bsky.app") && host !== hostOf$1("https://nexus.pubky.app")) throw new HostNotContacted(`Hide my IP from contacts is on: ${host}, a server your contact chose, was not contacted`);
9824
9468
  return fetch(url, options);
@@ -11011,178 +10655,6 @@ async function readPubkyProof(key, path) {
11011
10655
  }
11012
10656
  }
11013
10657
  //#endregion
11014
- //#region ../browser/src/engine/forwards.ts
11015
- /**
11016
- * Whether a message can be forwarded, and as what. Payments and payment requests (a bearer token or a request is for
11017
- * the chat it was made in), a group's history lines and its payment notes cannot; neither can a message with nothing
11018
- * in it. Identity shares and call lines are not messages here at all.
11019
- */
11020
- function forwardKind(message) {
11021
- if (message.sender !== "me" && message.sender !== "peer") return { refused: "This message cannot be forwarded" };
11022
- if (message.paymentId) return { refused: "Payments and payment requests cannot be forwarded" };
11023
- if (message.event || message.groupPay) return { refused: "This line cannot be forwarded" };
11024
- if (message.file) return "file";
11025
- return message.text.trim() ? "text" : { refused: "This message cannot be forwarded" };
11026
- }
11027
- /**
11028
- * Why a chat did not get a forward, as its result says it: never "" (a result with an error is a failure, whatever it
11029
- * says). A copy that found no room says so in the words the app knows however the storage put it: IndexedDB's
11030
- * QuotaExceededError (an empty message in Chromium), the OPFS worker's (named so), Desktop's io error (the system's English).
11031
- */
11032
- function forwardError(error) {
11033
- const message = (error instanceof Error ? error.message : String(error)).trim();
11034
- if (/^No space left on device\b/.test(message)) return `Not enough space on this device (${message})`;
11035
- const name = error?.name;
11036
- return errorLine(error).trim() || (typeof name === "string" && name ? name : "Error");
11037
- }
11038
- /** How many bytes of a stored file are actually here: all of them once it arrived. */
11039
- async function bytesHere(file) {
11040
- if (file.blob) return file.blob.size;
11041
- return await (file.bytes ? await fileBytesOf(file.bytes) : null)?.size(file.id) ?? 0;
11042
- }
11043
- /** `read` with the parts `patches` replace (zeros where a patch has no bytes). */
11044
- function patchedRead(read, patches) {
11045
- return async (offset, length) => {
11046
- const part = (await read(offset, length)).slice();
11047
- const end = offset + part.length;
11048
- for (const { start, end: until, bytes } of patches) {
11049
- if (until <= offset || start >= end) continue;
11050
- const from = Math.max(start, offset), to = Math.min(until, end);
11051
- if (bytes) part.set(bytes.subarray(from - start, to - start), from - offset);
11052
- else part.fill(0, from - offset, to - offset);
11053
- }
11054
- return part;
11055
- };
11056
- }
11057
- /**
11058
- * A received picture or video as it goes on: without its metadata (one from an app that sent it with them keeps where
11059
- * its author took it, the device, the time), as one sent from here; undefined for any other file, copied as it is. A
11060
- * picture is read whole; a video's stripped bytes are a Blob when it is kept in one, else read through the parts
11061
- * changed. Refused with `NO_PICTURE_METADATA` or `NO_VIDEO_METADATA` when its metadata cannot be removed.
11062
- */
11063
- async function withoutMetadata(source, size, file, read) {
11064
- if (file.voice || !size) return void 0;
11065
- if (file.video || !isStrippedPicture(await read(0, Math.min(PICTURE_METADATA_LIMITS.headBytes, size)), file.mime)) {
11066
- if (source.blob) return withoutVideoMetadata(source.blob, file.mime);
11067
- const readFully = async (offset, length) => {
11068
- const whole = new Uint8Array(Math.max(0, Math.min(length, size - offset)));
11069
- for (let at = 0; at < whole.length;) {
11070
- const part = await read(offset + at, whole.length - at);
11071
- if (!part.length) break;
11072
- whole.set(part, at);
11073
- at += part.length;
11074
- }
11075
- return whole;
11076
- };
11077
- const patches = await videoMetadataPatches({
11078
- size,
11079
- read: readFully
11080
- }, file.mime);
11081
- return patches && patchedRead(read, patches);
11082
- }
11083
- if (size > PICTURE_METADATA_LIMITS.maxBytes) throw new Error(NO_PICTURE_METADATA);
11084
- const whole = new Uint8Array(size);
11085
- for (let offset = 0; offset < size;) {
11086
- const part = await read(offset, Math.min(1048576, size - offset));
11087
- if (!part.length) throw new Error("The file is shorter than it says");
11088
- whole.set(part, offset);
11089
- offset += part.length;
11090
- }
11091
- return new Blob(stripPictureMetadata(whole, file.mime), { type: source.blob?.type ?? file.mime });
11092
- }
11093
- /** What a forward of a message deleted meanwhile says, whether it went before the forward or while its file was copied. */
11094
- var FORWARD_MESSAGE_GONE = "That message is not in this chat";
11095
- /**
11096
- * A copy of a file on this device, for sending in another chat under `file.id`: a small one whole, a larger one a
11097
- * step at a time, never whole in memory; a picture without its metadata, read whole, and a video without its. Refused
11098
- * while it is still arriving, or when its bytes are gone. Resolves to `file` as it goes: a stripped file's size is its
11099
- * copy's.
11100
- *
11101
- * A copy cut off because its source went meanwhile says why, as one started after would: its message deleted (here, or
11102
- * for everyone by its sender, which takes its file: `messageGone`, asked only once the copy failed) is
11103
- * `FORWARD_MESSAGE_GONE`, its record gone with the message still here is "not on this device any more". Only bytes
11104
- * missing from a source still kept whole on record stay "shorter than it says".
11105
- */
11106
- async function copyForForward(sourceId, target, messageGone) {
11107
- try {
11108
- return await copyFile(sourceId, target);
11109
- } catch (error) {
11110
- if (await messageGone?.().catch(() => false)) throw Object.assign(/* @__PURE__ */ new Error(FORWARD_MESSAGE_GONE), { cause: error });
11111
- if (!(await fileStore.get(sourceId).catch(() => ({ metadata: true })))?.metadata) throw Object.assign(/* @__PURE__ */ new Error("The file is not on this device any more"), { cause: error });
11112
- throw error;
11113
- }
11114
- }
11115
- async function copyFile(sourceId, target) {
11116
- const source = await fileStore.get(sourceId);
11117
- if (!source?.metadata) throw new Error("The file is not on this device any more");
11118
- const stored = storedSize(source);
11119
- const checked = source.wire3 ? source.wire3.state === "done" : !source.group || source.transfer?.state === "done";
11120
- if (source.direction === "in" && !checked || await bytesHere(source) !== stored) throw new Error("The file has not arrived yet");
11121
- const from = source.bytes ? await fileBytesOf(source.bytes) : null;
11122
- const read = async (offset, length) => source.blob ? new Uint8Array(await source.blob.slice(offset, offset + length).arrayBuffer()) : from.read(source.id, offset, length);
11123
- const stripped = await withoutMetadata(source, stored, target.file, read);
11124
- const blob = typeof stripped === "function" ? void 0 : stripped ?? source.blob, size = blob && stripped ? blob.size : stored;
11125
- const readCopy = typeof stripped === "function" ? stripped : read;
11126
- const known = stripped ? void 0 : source.digest;
11127
- const { linkId, wireId, timestamp } = target, file = stripped ? {
11128
- ...target.file,
11129
- size
11130
- } : target.file;
11131
- const metadata = {
11132
- name: file.name,
11133
- size: file.size,
11134
- mime: file.mime,
11135
- timestamp,
11136
- voice: file.voice,
11137
- video: file.video,
11138
- image: file.image
11139
- };
11140
- const record = {
11141
- id: file.id,
11142
- linkId,
11143
- createdAt: timestamp,
11144
- direction: "out",
11145
- wireId,
11146
- metadata,
11147
- transfer: {
11148
- state: "transferring",
11149
- transferred: 0,
11150
- size: file.size
11151
- }
11152
- };
11153
- if (size <= 16777216 && blob) {
11154
- const copy = new Blob([await blob.slice(0, size).arrayBuffer()], { type: blob.type });
11155
- const digest = known ?? (stripped ? await blobDigest(copy) : void 0);
11156
- await fileStore.put({
11157
- ...record,
11158
- blob: copy,
11159
- ...digest && { digest }
11160
- });
11161
- return file;
11162
- }
11163
- const bytes = await fileBytes();
11164
- try {
11165
- const appender = new FileAppender(bytes, file.id);
11166
- for (let offset = 0; offset < size;) {
11167
- const part = blob ? new Uint8Array(await blob.slice(offset, offset + 1048576).arrayBuffer()) : await readCopy(offset, Math.min(1048576, size - offset));
11168
- if (!part.length) throw new Error("The file is shorter than it says");
11169
- await appender.append(part);
11170
- offset += part.length;
11171
- }
11172
- await appender.close();
11173
- const digest = known ?? await bytes.digest(file.id);
11174
- await fileStore.put({
11175
- ...record,
11176
- bytes: bytes.kind,
11177
- digest
11178
- });
11179
- return file;
11180
- } catch (error) {
11181
- await bytes.remove(file.id).catch(() => {});
11182
- throw error;
11183
- }
11184
- }
11185
- //#endregion
11186
10658
  //#region ../browser/src/engine/paymentAdapters/perNetwork.ts
11187
10659
  var perNetwork = (make) => Object.fromEntries(WALLET_NETWORKS.map((network) => [network, make(network)]));
11188
10660
  /** A single one for both networks (a test, a caller that predates networks), or one per network already. */
@@ -11378,196 +10850,6 @@ var ChatTextSearch = class {
11378
10850
  return texts;
11379
10851
  }
11380
10852
  };
11381
- //#endregion
11382
- //#region ../browser/src/engine/appFetch.ts
11383
- /** The hosts phase 1 reads from. A jsDelivr URL must also name a 40-character commit (`isAppUrl`). */
11384
- var APP_FETCH_HOSTS = ["raw.githubusercontent.com", "cdn.jsdelivr.net"];
11385
- var APP_FETCH_LIMITS = {
11386
- /**
11387
- * A store index as read (WISP 1200 § Stores, Privacy): 4 MiB in phase 1, under the format's 16 MiB. Counted on the body
11388
- * as it arrives, after the browser undid any compression, since a page never sees the compressed size.
11389
- */
11390
- storeIndexBytes: 4194304,
11391
- /** A store's signature statement, `ghostly-store.sig` (canonical, at most 1 KiB). */
11392
- sigBytes: 1024,
11393
- /** `ghostly-revoke.json`: at most 4096 signed revocations. */
11394
- revocationsBytes: 16777216,
11395
- /** How long the host has to answer (the response's headers). */
11396
- timeoutMs: 3e4,
11397
- /** How long the body may go without a byte: a read still arriving is never cut by the clock alone. */
11398
- idleMs: 3e4,
11399
- /** A whole read at most: the 16 MiB cap at about 224 kbit/s. */
11400
- totalMs: 6e5
11401
- };
11402
- /** A URL this client may read an app, a store or a revocation list from. */
11403
- function isAppFetchUrl(value) {
11404
- if (!isAppUrl(value)) return false;
11405
- const url = new URL(value);
11406
- return url.port === "" && APP_FETCH_HOSTS.includes(url.hostname.toLowerCase());
11407
- }
11408
- var AppFetchError = class extends Error {
11409
- code;
11410
- status;
11411
- constructor(code, message, status) {
11412
- super(`${code}: ${message}`);
11413
- this.code = code;
11414
- this.status = status;
11415
- this.name = "AppFetchError";
11416
- }
11417
- };
11418
- function boundedAppFetch(options = {}) {
11419
- return async (url, { maxBytes, peek = false, revalidate = false, signal: stopped }) => {
11420
- if (!isAppFetchUrl(url)) throw new AppFetchError("host", "Apps are read only from raw.githubusercontent.com, or from cdn.jsdelivr.net at a commit, over HTTPS");
11421
- if (options.online && !options.online()) throw new AppFetchError("offline", "Offline");
11422
- if (stopped?.aborted) throw new AppFetchError("network", "The read was stopped");
11423
- const fetcher = options.fetcher ?? globalThis.fetch.bind(globalThis);
11424
- const controller = new AbortController();
11425
- const cut = () => {
11426
- controller.abort(new DOMException("The read took too long", "TimeoutError"));
11427
- };
11428
- const stop = () => {
11429
- controller.abort(new DOMException("The read was stopped", "AbortError"));
11430
- };
11431
- stopped?.addEventListener("abort", stop);
11432
- const total = setTimeout(cut, options.totalMs ?? APP_FETCH_LIMITS.totalMs);
11433
- let idle = setTimeout(cut, options.timeoutMs ?? APP_FETCH_LIMITS.timeoutMs);
11434
- const heard = () => {
11435
- clearTimeout(idle);
11436
- idle = setTimeout(cut, options.idleMs ?? APP_FETCH_LIMITS.idleMs);
11437
- };
11438
- const failure = (error) => stopped?.aborted ? new AppFetchError("network", "The read was stopped") : controller.signal.aborted ? new AppFetchError("slow", "That took too long on this connection") : new AppFetchError("network", error instanceof Error ? error.message : String(error));
11439
- const { signal } = controller;
11440
- let response;
11441
- try {
11442
- response = await fetcher(url, {
11443
- signal,
11444
- credentials: "omit",
11445
- referrerPolicy: "no-referrer",
11446
- cache: revalidate && !peek ? "no-cache" : "no-store",
11447
- redirect: "error",
11448
- ...peek && { headers: { range: `bytes=0-${maxBytes - 1}` } }
11449
- });
11450
- } catch (error) {
11451
- clearTimeout(total);
11452
- clearTimeout(idle);
11453
- stopped?.removeEventListener("abort", stop);
11454
- throw failure(error);
11455
- }
11456
- heard();
11457
- const parts = [];
11458
- let length = 0;
11459
- try {
11460
- if (response.url && response.url !== url && !isAppFetchUrl(response.url)) throw new AppFetchError("host", "The host sent the request elsewhere");
11461
- if (!response.ok) {
11462
- await response.body?.cancel().catch(() => {});
11463
- throw new AppFetchError("status", `The host answered ${response.status}`, response.status);
11464
- }
11465
- if (!peek && Number(response.headers.get("content-length")) > maxBytes) {
11466
- await response.body?.cancel().catch(() => {});
11467
- throw new AppFetchError("too-large", "Too large");
11468
- }
11469
- const reader = response.body?.getReader();
11470
- if (reader) {
11471
- const letGo = () => {
11472
- reader.cancel().catch(() => {});
11473
- };
11474
- signal.addEventListener("abort", letGo);
11475
- try {
11476
- for (;;) {
11477
- const { done, value } = await reader.read();
11478
- if (signal.aborted) throw failure(signal.reason);
11479
- if (done) break;
11480
- heard();
11481
- if (length + value.length > maxBytes) {
11482
- if (!peek) throw new AppFetchError("too-large", "Too large");
11483
- parts.push(value.subarray(0, maxBytes - length));
11484
- length = maxBytes;
11485
- break;
11486
- }
11487
- parts.push(value);
11488
- length += value.length;
11489
- }
11490
- } catch (error) {
11491
- if (error instanceof AppFetchError) throw error;
11492
- throw failure(error);
11493
- } finally {
11494
- signal.removeEventListener("abort", letGo);
11495
- await reader.cancel().catch(() => {});
11496
- }
11497
- }
11498
- } finally {
11499
- clearTimeout(total);
11500
- clearTimeout(idle);
11501
- stopped?.removeEventListener("abort", stop);
11502
- }
11503
- const bytes = new Uint8Array(length);
11504
- let at = 0;
11505
- for (const part of parts) {
11506
- bytes.set(part, at);
11507
- at += part.length;
11508
- }
11509
- return bytes;
11510
- };
11511
- }
11512
- var NAME = /^[A-Za-z0-9_.-]+$/;
11513
- /**
11514
- * The URL a pasted address reads `file` from (WISP 1200 § Paste a URL), or null when it is not one this client reads:
11515
- * - `https://github.com/<owner>/<repo>`, or `/tree/<ref>`: `raw.githubusercontent.com/<owner>/<repo>/<ref or HEAD>/<file>`,
11516
- * with no request to `github.com` or `api.github.com`;
11517
- * - a file as GitHub shows it, `https://github.com/<owner>/<repo>/blob/<ref>/<path>` (or `/raw/`), naming a `.ghostlyapp`
11518
- * or `.json` file: `raw.githubusercontent.com/<owner>/<repo>/<ref>/<path>`, again with no request to `github.com`;
11519
- * - a URL of the list that names a file (`….ghostlyapp`, `….json`): itself;
11520
- * - a URL of the list that names a folder: `<file>` in it.
11521
- */
11522
- function appPasteUrl(input, file) {
11523
- let url;
11524
- try {
11525
- url = new URL(input.trim());
11526
- } catch {
11527
- return null;
11528
- }
11529
- if (url.protocol !== "https:" || url.username || url.password || url.port) return null;
11530
- const host = url.hostname.toLowerCase();
11531
- if (host === "github.com" || host === "www.github.com") {
11532
- const parts = url.pathname.split("/").filter(Boolean);
11533
- if (parts.length < 2) return null;
11534
- const owner = parts[0], repo = parts[1].replace(/\.git$/, "");
11535
- if (!NAME.test(owner) || !NAME.test(repo)) return null;
11536
- let ref = "HEAD";
11537
- if (parts.length > 2) {
11538
- const rest = parts.slice(3);
11539
- if (!rest.length || !rest.every((p) => NAME.test(p) && p !== "." && p !== "..")) return null;
11540
- if (parts[2] === "blob" || parts[2] === "raw") {
11541
- if (rest.length < 2 || !/\.(ghostlyapp|json)$/.test(rest[rest.length - 1])) return null;
11542
- const raw = `https://raw.githubusercontent.com/${owner}/${repo}/${rest.join("/")}`;
11543
- return isAppFetchUrl(raw) ? raw : null;
11544
- }
11545
- if (parts[2] !== "tree") return null;
11546
- ref = rest.join("/");
11547
- }
11548
- const raw = `https://raw.githubusercontent.com/${owner}/${repo}/${ref}/${file}`;
11549
- return isAppFetchUrl(raw) ? raw : null;
11550
- }
11551
- const last = url.pathname.split("/").pop() ?? "";
11552
- const named = /\.(ghostlyapp|json)$/.test(last) ? url.href : new URL(`${url.pathname.replace(/\/?$/, "/")}${file}`, url).href;
11553
- return isAppFetchUrl(named) ? named : null;
11554
- }
11555
- /** A page of github.com (any scheme): a link `appPasteUrl` could not read is still GitHub, and is answered as such. */
11556
- function isGitHubPage(input) {
11557
- try {
11558
- const host = new URL(input.trim()).hostname.toLowerCase();
11559
- return host === "github.com" || host === "www.github.com";
11560
- } catch {
11561
- return false;
11562
- }
11563
- }
11564
- /** A file beside another (`ghostly-store.sig` beside the index, `ghostly-revoke.json` beside a bundle). */
11565
- function besideUrl(url, name) {
11566
- const target = new URL(url);
11567
- target.search = "";
11568
- target.hash = "";
11569
- return new URL(name, target).href;
11570
- }
11571
10853
  /**
11572
10854
  * The stores a new profile starts with (WISP 1200 § Stores: the default store, preloaded and removable), each a URL and
11573
10855
  * the store key it is pinned to. Preloading one makes no request; the first read comes when the person opens the Apps
@@ -11656,6 +10938,8 @@ var BUNDLES_KEPT = {
11656
10938
  min: 2,
11657
10939
  ms: 6e4
11658
10940
  };
10941
+ /** URLs the update check remembers it read whole and refused (`Apps.refusedReads`). */
10942
+ var REFUSED_READS_KEPT = 256;
11659
10943
  /** The first bytes of a bundle: magic, the manifest's length and the largest manifest. */
11660
10944
  var PEEK_BYTES = APP_BUNDLE_MAGIC.length + 4 + APP_BUNDLE_LIMITS.manifestBytes;
11661
10945
  /** What a peek reads first: the magic, the length and any usual manifest (about 1 KiB). A longer one is read to its end after. */
@@ -12079,6 +11363,12 @@ var Apps = class {
12079
11363
  */
12080
11364
  listingMisses = /* @__PURE__ */ new Map();
12081
11365
  /**
11366
+ * URLs whose whole read the update check refused (a file hash that does not hold, a bad signature, too large), with
11367
+ * the digest their peek showed then: the same peek there is not read whole again at every check, for an hour (a fixed
11368
+ * upload of the same version keeps its manifest). At most `REFUSED_READS_KEPT`, the oldest going first.
11369
+ */
11370
+ refusedReads = /* @__PURE__ */ new Map();
11371
+ /**
12082
11372
  * The index a store's own URL served at its last read when it was not taken (behind the copy the person took, at a
12083
11373
  * commit): by store key, with that URL. The same bytes there again are not checked whole at every refresh.
12084
11374
  */
@@ -12308,18 +11598,27 @@ var Apps = class {
12308
11598
  if (!app && this.ran.has(ref)) fail("not-installed", "This app is not installed");
12309
11599
  if (app) await this.stillRunnable(app, digest);
12310
11600
  }
12311
- /** Writes an app's record, keeping the revocations the record holds now (one kept since the caller read it among them). */
11601
+ /**
11602
+ * Writes an app's record, keeping the revocations the record holds now (one kept since the caller read it among them).
11603
+ * Only while the app has a record: one uninstalled since the caller read it (another tab, Uninstall while Update was
11604
+ * busy) is not put back with its data gone. False: not written.
11605
+ */
12312
11606
  async putApp(app) {
12313
11607
  const tx = (await openDb()).transaction(STORES$1.apps, "readwrite");
11608
+ let put = false;
12314
11609
  const read = tx.objectStore(STORES$1.apps).get(app.ref);
12315
11610
  read.onsuccess = () => {
12316
- tx.objectStore(STORES$1.apps).put(withRevocations(app, read.result?.revocations ?? []));
11611
+ const now = read.result;
11612
+ if (!now) return;
11613
+ tx.objectStore(STORES$1.apps).put(withRevocations(app, now.revocations ?? []));
11614
+ put = true;
12317
11615
  };
12318
11616
  try {
12319
11617
  await done(tx);
12320
11618
  } finally {
12321
11619
  this.held.delete(app.ref);
12322
11620
  }
11621
+ return put;
12323
11622
  }
12324
11623
  /**
12325
11624
  * Writes an app's record back only while it is still the record `was` (`sameRecord`), read and written in one
@@ -12327,7 +11626,9 @@ var Apps = class {
12327
11626
  * version it read over an update the person accepted meanwhile. `was` undefined: only while the app has no record.
12328
11627
  * A store removed since the caller read the stores pins nothing: it is judged at the write, as `removeStore` unpins
12329
11628
  * only the records written before it. A revocation the record gained since `was` (`keepStoreRevocations`) is kept:
12330
- * one `app` leaves out on purpose (the check's, of a version gone) was on `was` already.
11629
+ * one `app` leaves out on purpose (the check's, of a version gone) was on `was` already. So is what the person's stores
11630
+ * revoke of the versions written, as held at the write: a version fetched while a store's index revoked it was not on
11631
+ * the record `keepStoreRevocations` read.
12331
11632
  */
12332
11633
  async putAppIfUnchanged(app, was) {
12333
11634
  const stores = await this.records();
@@ -12339,6 +11640,8 @@ var Apps = class {
12339
11640
  if (!sameRecord(now, was)) return;
12340
11641
  const had = new Set((was?.revocations ?? []).map((r) => canonicalJson(r)));
12341
11642
  app = withRevocations(app, (now?.revocations ?? []).filter((r) => !had.has(canonicalJson(r))));
11643
+ const revoked = [...stores.values()].flatMap((s) => s.removed ? [] : s.index?.revoked ?? []);
11644
+ app = withRevocations(app, stopping(this.versionsOf(app), revoked));
12342
11645
  const { store: pin, ...unpinned } = app;
12343
11646
  tx.objectStore(STORES$1.apps).put(pin !== void 0 && stores.get(pin)?.removed ? unpinned : app);
12344
11647
  put = true;
@@ -13280,6 +12583,7 @@ var Apps = class {
13280
12583
  return this.view(await this.app(version.ref), stores);
13281
12584
  }
13282
12585
  const kind = wrote = await this.writeBundle(digest, bytes);
12586
+ if (this.runStatus(version, await this.heldViews(), [...installed?.revocations ?? [], ...known]).status !== "ok") continue;
13283
12587
  const next = withRevocations(this.versionRecord(installed, bundle, kind, from, fromStore), known);
13284
12588
  if (!await this.putAppIfUnchanged(next, installed)) continue;
13285
12589
  if (!installed && this.builtIn(version.ref)) await this.keepBuiltIn(version.ref);
@@ -13339,7 +12643,7 @@ var Apps = class {
13339
12643
  const read = bytes ? await readAppBundleAsync(bytes) : null;
13340
12644
  if (!read?.ok || read.bundle.digest !== pending.digest) {
13341
12645
  const { pending: _p, ...rest } = installed;
13342
- await this.putApp(rest);
12646
+ if (!await this.putApp(rest)) fail("not-installed", "This app is not installed");
13343
12647
  fail("needs-files", "The update's files are gone; it is fetched again at the next check");
13344
12648
  }
13345
12649
  const stores = await this.stores();
@@ -13354,13 +12658,13 @@ var Apps = class {
13354
12658
  if (plan.action === "refuse") fail(plan.decision, "This update can no longer be installed");
13355
12659
  const added = plan.action === "ask" ? plan.added : [];
13356
12660
  if (added.length !== pending.added.length || added.some((p) => !pending.added.includes(p))) {
13357
- await this.putApp({
12661
+ if (!await this.putApp({
13358
12662
  ...installed,
13359
12663
  pending: {
13360
12664
  ...pending,
13361
12665
  added
13362
12666
  }
13363
- });
12667
+ })) fail("not-installed", "This app is not installed");
13364
12668
  fail("permissions-changed", `This update now adds ${added.length ? added.join(", ") : "no permission"}; look at it again`);
13365
12669
  }
13366
12670
  if (shown && added.some((p) => !shown.includes(p))) fail("permissions-changed", `This update now adds ${added.join(", ")}; look at it again`);
@@ -13457,7 +12761,15 @@ var Apps = class {
13457
12761
  const revokeRead = /* @__PURE__ */ new Set();
13458
12762
  const before = await this.readRevocations(app.ref, [app.from, ...app.manifest.sources ?? []], revokeRead);
13459
12763
  app = withRevocations(app, before ?? []);
13460
- if (app.pending && this.runStatus(versionOf(app.pending.manifest, app.pending.digest), this.storeViews(stores), app.revocations).status !== "ok") {
12764
+ const kept = await this.keptRevocationsOf(app.ref);
12765
+ const judge = (version) => this.runStatus(version, this.storeViews(stores), [...app.revocations ?? [], ...kept]);
12766
+ if (app.pending && judge(versionOf(app.pending.manifest, app.pending.digest)).status !== "ok") {
12767
+ const stops = stopping([versionOf(app.pending.manifest, app.pending.digest)], [...app.revocations ?? [], ...stores.flatMap((s) => s.index?.revoked ?? [])]);
12768
+ if (stops.length) {
12769
+ const tx = (await openDb()).transaction(STORES$1.settings, "readwrite");
12770
+ keepRevocations(tx.objectStore(STORES$1.settings), app.ref, stops);
12771
+ await done(tx);
12772
+ }
13461
12773
  dropped.push(app.pending);
13462
12774
  const { pending: _p, ...rest } = app;
13463
12775
  app = rest;
@@ -13478,15 +12790,28 @@ var Apps = class {
13478
12790
  holds = peek;
13479
12791
  }
13480
12792
  const twin = holds && (holds.sequence === app.sequence || holds.sequence === app.pending?.sequence);
13481
- if (holds && !twin && this.runStatus(holds, this.storeViews(stores), app.revocations).status !== "ok") continue;
12793
+ if (holds && !twin && judge(holds).status !== "ok") continue;
13482
12794
  if (holds && twin && app.equivocation?.sequence === holds.sequence && app.equivocation.digest === holds.digest) {
13483
12795
  outcome = "equivocation";
13484
12796
  continue;
13485
12797
  }
12798
+ const refused = this.refusedReads.get(url);
12799
+ if (holds && refused?.digest === holds.digest && this.now() - refused.at < APP_CHECK_TIMINGS.freshMs) continue;
13486
12800
  let fetched;
13487
12801
  try {
13488
12802
  fetched = await this.fetchBundle(url);
13489
- } catch {
12803
+ } catch (error) {
12804
+ if (holds && (!(error instanceof AppFetchError) || error.code === "too-large")) {
12805
+ this.refusedReads.delete(url);
12806
+ this.refusedReads.set(url, {
12807
+ digest: holds.digest,
12808
+ at: this.now()
12809
+ });
12810
+ for (const old of this.refusedReads.keys()) {
12811
+ if (this.refusedReads.size <= REFUSED_READS_KEPT) break;
12812
+ this.refusedReads.delete(old);
12813
+ }
12814
+ }
13490
12815
  continue;
13491
12816
  }
13492
12817
  const { bundle, bytes } = fetched;
@@ -13523,7 +12848,8 @@ var Apps = class {
13523
12848
  }
13524
12849
  continue;
13525
12850
  }
13526
- if (this.runStatus(version, this.storeViews(stores), app.revocations).status !== "ok") continue;
12851
+ if (judge(version).status !== "ok") continue;
12852
+ if (this.runStatus(version, await this.heldViews(), app.revocations).status !== "ok") continue;
13527
12853
  if (app.pending && version.sequence < app.pending.sequence) continue;
13528
12854
  const kind = await this.writeBundle(version.digest, bytes);
13529
12855
  wrote = {
@@ -13614,14 +12940,13 @@ var Apps = class {
13614
12940
  if (held) {
13615
12941
  const kind = await this.writeBundle(app.digest, held.bytes);
13616
12942
  const now = await this.app(app.ref);
13617
- if (!now || now.digest !== app.digest) {
12943
+ if (!now || now.digest !== app.digest || now.bytes !== kind && !await this.putApp({
12944
+ ...now,
12945
+ bytes: kind
12946
+ })) {
13618
12947
  await this.removeBundle(kind, app.digest);
13619
12948
  fail("not-installed", "This app is not installed");
13620
12949
  }
13621
- if (now.bytes !== kind) await this.putApp({
13622
- ...now,
13623
- bytes: kind
13624
- });
13625
12950
  return this.runCheckOf({
13626
12951
  ...now,
13627
12952
  bytes: kind
@@ -13649,14 +12974,13 @@ var Apps = class {
13649
12974
  if (fetched.bundle.digest !== app.digest) continue;
13650
12975
  const kind = await this.writeBundle(app.digest, fetched.bytes);
13651
12976
  const now = await this.app(app.ref);
13652
- if (!now || now.digest !== app.digest) {
12977
+ if (!now || now.digest !== app.digest || now.bytes !== kind && !await this.putApp({
12978
+ ...now,
12979
+ bytes: kind
12980
+ })) {
13653
12981
  await this.removeBundle(kind, app.digest);
13654
12982
  fail("not-installed", "This app is not installed");
13655
12983
  }
13656
- if (now.bytes !== kind) await this.putApp({
13657
- ...now,
13658
- bytes: kind
13659
- });
13660
12984
  return this.runCheckOf({
13661
12985
  ...now,
13662
12986
  bytes: kind
@@ -13871,6 +13195,16 @@ var Apps = class {
13871
13195
  this.usage.set(id, used);
13872
13196
  return used;
13873
13197
  }
13198
+ /**
13199
+ * A chat removed, its rows gone (`db.deleteLink`): what this engine kept of every app's storage there goes too. A chat's
13200
+ * id comes from its invite, so the same invite joined again is the same scope: with the deleted chat's count still
13201
+ * held, its app found no keys yet every write refused as full until a restart.
13202
+ */
13203
+ forgetScope(scope) {
13204
+ const of = (id) => id.slice(id.indexOf("\0") + 1) === scope;
13205
+ for (const id of [...this.usage.keys()]) if (of(id)) this.usage.delete(id);
13206
+ for (const id of [...this.keyReads.keys()]) if (of(id)) this.keyReads.delete(id);
13207
+ }
13874
13208
  async storageGet({ ref, scope, key, digest }) {
13875
13209
  const app = await this.runningOrFail(ref, digest);
13876
13210
  const row = await wrap((await store(STORES$1.appStorage, "readonly")).get([
@@ -13933,6 +13267,7 @@ var Apps = class {
13933
13267
  });
13934
13268
  }
13935
13269
  async storageDelete({ ref, scope, key, digest }) {
13270
+ const uninstalls = this.uninstalls.get(ref);
13936
13271
  const app = await this.runningOrFail(ref, digest);
13937
13272
  const where = this.scopeOf(scope), name = this.keyOf(key);
13938
13273
  await this.serial(`${app.ref}\0${where}`, async () => {
@@ -13945,6 +13280,10 @@ var Apps = class {
13945
13280
  if (!old) return;
13946
13281
  const next = plus(used, countOf(old, -1));
13947
13282
  const writing = await store(STORES$1.appStorage, "readwrite");
13283
+ if (this.uninstalls.get(app.ref) !== uninstalls) {
13284
+ this.usage.delete(`${app.ref}\0${where}`);
13285
+ fail("not-installed", "This app is not installed");
13286
+ }
13948
13287
  writing.delete([
13949
13288
  app.ref,
13950
13289
  where,
@@ -22468,12 +21807,16 @@ function canRemove(message) {
22468
21807
  * version. A status card's update adds none either (WISP 405 · Status Cards): it replaces the card in place, and its
22469
21808
  * text is only the card's fallback, so a bot's thousands of updates keep one card and no trail of versions. Buttons
22470
21809
  * (WISP 406 · Message Buttons) are the exception: their text is the question people answer, so a new one keeps the
22471
- * version it replaces, and only a change of the buttons alone (the answer marked, closed) adds none.
21810
+ * version it replaces, and only a change of the buttons alone (the answer marked, closed) adds none. A card on a text
21811
+ * that had none (or had buttons) is not an update: the text it replaces is kept. Only the text as it came keeps the
21812
+ * message's own time: an edited one is dated after it, whatever time the edit's author gave.
22472
21813
  */
22473
21814
  function withEdit(message, edit) {
22474
21815
  const before = message.edit?.history ?? [];
22475
- const history = edit.text === message.text || edit.card && edit.card.kind !== "buttons" ? before : trimHistory([...before, {
22476
- at: message.edit?.at ?? shownTime(message),
21816
+ const sent = shownTime(message);
21817
+ const cardUpdate = !!edit.card && edit.card.kind !== "buttons" && !!message.card && message.card.kind !== "buttons";
21818
+ const history = edit.text === message.text || cardUpdate ? before : trimHistory([...before, {
21819
+ at: message.edit ? Math.max(message.edit.at, sent + 1) : sent,
22477
21820
  text: message.text
22478
21821
  }]);
22479
21822
  const next = {
@@ -22492,10 +21835,14 @@ function withEdit(message, edit) {
22492
21835
  ...edit.card && { card: edit.card }
22493
21836
  };
22494
21837
  }
21838
+ /** The first version (the text as it came) always stays; of the rest, the newest that fit. */
22495
21839
  function trimHistory(history) {
22496
- let kept = history.slice(-20);
22497
- while (kept.length > 1 && kept.reduce((sum, version) => sum + utf8Encode(version.text).length, 0) > 65536) kept = kept.slice(1);
22498
- return kept;
21840
+ if (history.length < 2) return history;
21841
+ const [first, ...rest] = history;
21842
+ let kept = rest.slice(-19);
21843
+ const bytes = (versions) => versions.reduce((sum, version) => sum + utf8Encode(version.text).length, 0);
21844
+ while (kept.length > 1 && bytes([first, ...kept]) > 65536) kept = kept.slice(1);
21845
+ return [first, ...kept];
22499
21846
  }
22500
21847
  //#endregion
22501
21848
  //#region ../browser/src/engine/outbox.ts
@@ -24065,6 +23412,11 @@ var TARGETED = /* @__PURE__ */ new Set([
24065
23412
  "usdt"
24066
23413
  ]);
24067
23414
  /**
23415
+ * Ecash sent that can still be taken back: not taken yet, or refused by the contact while the mint did not answer the
23416
+ * automatic take back (`failed`, its token kept). Its bubble offers both, and `PaymentDesk.forgetLink` keeps both.
23417
+ */
23418
+ var sentUntaken = (p) => p.kind === "payment" && p.direction === "out" && (p.state === "pending" || p.state === "failed") && !!p.token;
23419
+ /**
24068
23420
  * What the wallets of one network still wait for (see `WalletAwaitingView`): what removing one of them would lose, or
24069
23421
  * close. A request of ours counts only for the wallet it can be paid through, and only when there is one: a request a
24070
23422
  * Cashu mint and another Lightning source can both be paid through is not lost when one of them goes.
@@ -24166,7 +23518,7 @@ function walletAwaiting({ network, mints, quotes, lightningOps, lightningSource,
24166
23518
  });
24167
23519
  }
24168
23520
  for (const p of payments) {
24169
- if (p.kind !== "payment" || p.direction !== "out" || p.state !== "pending" || !p.token) continue;
23521
+ if (!sentUntaken(p)) continue;
24170
23522
  const gone = chatGone?.(p.id) ? { chatGone: true } : {};
24171
23523
  if (p.target?.method === "fedimint" || p.federation) {
24172
23524
  if (paymentNetwork(p) === network) out.push({
@@ -26663,13 +26015,16 @@ var Communities = class {
26663
26015
  * other hubs and, for taking someone new (`entries`), its entry sessions.
26664
26016
  */
26665
26017
  capacity(groupId, live, now, entries = true) {
26018
+ return Math.max(0, Math.min(COMMUNITY_TOPOLOGY.hubCapacity, this.room(groupId, live, now, entries)));
26019
+ }
26020
+ /** What the budget of connections leaves for members (`capacity` without its `hubCapacity`); no budget, no bound. */
26021
+ room(groupId, live, now, entries = true) {
26666
26022
  const room = this.host.peerRoom?.(groupId);
26667
- if (room === void 0) return COMMUNITY_TOPOLOGY.hubCapacity;
26023
+ if (room === void 0) return Infinity;
26668
26024
  const hubs = new Set(freshHubs(this.hubs(live), now).map((h) => h.key));
26669
26025
  for (const key of this.host.edges(groupId).keys()) if (!live.members.has(key)) hubs.add(key);
26670
26026
  hubs.delete(live.session.myKey);
26671
- const held = hubs.size + (entries ? this.host.entries(groupId).size : 0);
26672
- return Math.max(0, Math.min(COMMUNITY_TOPOLOGY.hubCapacity, room - held));
26027
+ return room - hubs.size - (entries ? this.host.entries(groupId).size : 0);
26673
26028
  }
26674
26029
  /** The load the beacon says: a hub with no room left says it is full, as one at `hubCapacity` does. */
26675
26030
  beaconLoad(groupId, live, now) {
@@ -27127,7 +26482,7 @@ var Communities = class {
27127
26482
  const turn = Math.floor(waited / KNOCK_SLOT_MS) % order.length, early = order.length === 1 || waited % KNOCK_SLOT_MS < KNOCK_SLOT_OPEN_MS;
27128
26483
  if (order[turn] !== s.myKey || !early || waited >= KNOCK_SLOT_MS && !stillKnocking) continue;
27129
26484
  if (live.pendingEntries.size >= MAX_PENDING_ENTRIES$1) break;
27130
- if (live.members.size >= this.capacity(groupId, live, now)) break;
26485
+ if (live.members.size >= this.capacity(groupId, live, now) && !(s.isAdmin && this.room(groupId, live, now) > live.members.size)) break;
27131
26486
  if (this.host.adminTurn && !await this.host.adminTurn(groupId, { wait: false })) break;
27132
26487
  live.pendingEntries.set(key, now);
27133
26488
  live.doorKey = link.host;
@@ -27848,6 +27203,7 @@ var MeshHubs = class {
27848
27203
  primed: false,
27849
27204
  gone: /* @__PURE__ */ new Map(),
27850
27205
  reactions: /* @__PURE__ */ new Map(),
27206
+ reactionPace: /* @__PURE__ */ new Map(),
27851
27207
  need: 0,
27852
27208
  departed: /* @__PURE__ */ new Set(),
27853
27209
  unreached: /* @__PURE__ */ new Map(),
@@ -28420,6 +27776,9 @@ var MeshHubs = class {
28420
27776
  if (!live?.hub) return;
28421
27777
  const at = `${frame.k} ${frame.id}`, held = live.reactions.get(at);
28422
27778
  if (held && held.n >= frame.n) return;
27779
+ let pace = live.reactionPace.get(frame.k);
27780
+ if (!pace) live.reactionPace.set(frame.k, pace = new ReactionWindow(REACTION_LIMITS.receive, REACTION_LIMITS.windowMs));
27781
+ if (!pace.take()) return;
28423
27782
  live.reactions.delete(at);
28424
27783
  live.reactions.set(at, frame);
28425
27784
  while (live.reactions.size > REACTIONS_KEPT) live.reactions.delete(live.reactions.keys().next().value);
@@ -29154,10 +28513,13 @@ function invitationClaims(frame) {
29154
28513
  n: Math.min(Math.max(n, 1), GROUP_MEMBER_CAP.max)
29155
28514
  };
29156
28515
  }
29157
- /** Syncs of a removed member answered with the commits it lacks, per farewell: it needs one. */
28516
+ /**
28517
+ * Syncs of a removed member answered with the commits it lacks, per farewell: it needs one. Counted per answer, however
28518
+ * many slices it goes in; a sync while one still goes out is not counted (`farewellSync`).
28519
+ */
29158
28520
  var FAREWELL_ANSWERS = 3;
29159
- /** Commits sent to a removed member that was behind when it left, at most. */
29160
- var FAREWELL_COMMITS = 64;
28521
+ /** Who an answer to a removed member's sync goes to (`Groups.farewellAnswers`): its group and its key. */
28522
+ var farewellTo = (groupId, key) => `${groupId} ${key}`;
29161
28523
  /**
29162
28524
  * The commit of epoch `e` for a removed member, with no secret: with the admin's `left` mark on a removal of someone who
29163
28525
  * left on their own, or its app says that the admin removed them (WISP 902 § Admission and departure).
@@ -30218,11 +29580,23 @@ var Groups = class {
30218
29580
  * it where the role went.
30219
29581
  */
30220
29582
  async leaveConfirmed(groupId) {
30221
- if (!this.stored.get(groupId)?.left) return;
29583
+ const group = this.stored.get(groupId), left = group?.left;
29584
+ if (!group || !left) return;
30222
29585
  if (this.holdsRole(groupId, this.sessions.get(groupId))) {
30223
29586
  if (!this.passedOnUntil.has(groupId)) this.passedOnUntil.set(groupId, this.now() + LEFT_PASSED_ON_MS);
30224
29587
  return;
30225
29588
  }
29589
+ if (this.farewellKeys(group, this.sessions.get(groupId), this.now()).length) {
29590
+ if (left.heard === void 0) {
29591
+ group.left = {
29592
+ ...left,
29593
+ heard: this.now()
29594
+ };
29595
+ await this.store.putGroup(group);
29596
+ this.reconcileEdges(groupId);
29597
+ }
29598
+ return;
29599
+ }
30226
29600
  await this.forget(groupId);
30227
29601
  }
30228
29602
  /** Tombstones the role went on from, removed already, and when they go (`leaveConfirmed`). */
@@ -30270,10 +29644,15 @@ var Groups = class {
30270
29644
  const { [key]: _gone, ...rest } = group.farewells;
30271
29645
  group.farewells = Object.keys(rest).length ? rest : void 0;
30272
29646
  }
30273
- /** The removed members this admin still waits for: not told yet, or told a moment ago (the commit is on its way). */
29647
+ /**
29648
+ * The removed members this admin still waits for: not told yet, told a moment ago (the commit is on its way), or with
29649
+ * my answer to their sync still going out a slice at a time. Also after it left the group: nobody else keeps an edge
29650
+ * to them, and the members it removed would never learn it. Never past `FAREWELL_OPEN_MS` after the edge opened.
29651
+ */
30274
29652
  farewellKeys(group, session, now) {
30275
- if (!group?.farewells || session.status !== "active") return [];
30276
- return Object.entries(group.farewells).filter(([key, f]) => !rosterHas(session.roster, key) && now - f.at <= 6048e5 && (f.told === void 0 || now - f.told < REMOVED_LINGER_MS) && (f.opened === void 0 || now - f.opened < 6e4)).map(([key]) => key);
29653
+ if (!group?.farewells || !session || session.status !== "active" && !group.left) return [];
29654
+ const answering = (key) => !!this.farewellAnswers?.busy(farewellTo(group.id, key));
29655
+ return Object.entries(group.farewells).filter(([key, f]) => !rosterHas(session.roster, key) && now - f.at <= 6048e5 && (f.told === void 0 || now - f.told < REMOVED_LINGER_MS || answering(key)) && (f.opened === void 0 || now - f.opened < 6e4)).map(([key]) => key);
30277
29656
  }
30278
29657
  /** The edges an active member keeps: what the roster (or the hubs) ask for, and those to members it removed while they were away. */
30279
29658
  edgesWanted(groupId, session, group, now) {
@@ -30372,19 +29751,65 @@ var Groups = class {
30372
29751
  farewell.told ??= this.now();
30373
29752
  this.store.putGroup(group).catch(() => {});
30374
29753
  }
30375
- /** The sync of a removed member I wait for: the commits it lacks up to the one that removed it, a few times at most. */
29754
+ /**
29755
+ * The sync of a removed member I wait for: the commits it lacks up to the one that removed it, a few times at most.
29756
+ * Every one from where it is (it takes them only one after the other), a slice at a time as a member's sync answer
29757
+ * goes (`farewellAnswers`): hundreds at once ended its session as more than its app holds waiting
29758
+ * (`SESSION_RECEIVE_PENDING`), and the next tries the same, until it was never told. A sync while my answer still
29759
+ * goes out (its app asks again every 10 s while it takes commits that bring no secret) is no new try: it adds only
29760
+ * what that answer does not hold or has not sent yet.
29761
+ */
30376
29762
  farewellSync(groupId, session, group, key, frame) {
30377
29763
  const farewell = group.farewells[key], linkId = this.host.edges(groupId).get(key);
30378
29764
  const from = frame.e;
30379
29765
  if (!linkId || frame.t !== "group-sync" || !Number.isSafeInteger(from) || from < 0 || from >= farewell.e - 1) return;
30380
- if ((farewell.answered ?? 0) >= FAREWELL_ANSWERS) return;
30381
- farewell.answered = (farewell.answered ?? 0) + 1;
30382
- try {
30383
- for (let e = Math.max(from + 1, farewell.e - FAREWELL_COMMITS); e <= farewell.e; e++) if (session.state.chain[e]) this.host.sendOnLink(linkId, farewellCommit(groupId, session, e));
30384
- } catch {}
29766
+ const answers = this.farewellOut(), to = farewellTo(groupId, key), again = answers.busy(to);
29767
+ if (!again) {
29768
+ if ((farewell.answered ?? 0) >= FAREWELL_ANSWERS) return;
29769
+ farewell.answered = (farewell.answered ?? 0) + 1;
29770
+ }
29771
+ const commits = [];
29772
+ for (let e = from + 1; e <= farewell.e; e++) if (session.state.chain[e]) commits.push(farewellCommit(groupId, session, e));
29773
+ answers.handOut(to, commits);
29774
+ if (again) return;
30385
29775
  farewell.told ??= this.now();
30386
29776
  this.store.putGroup(group).catch(() => {});
30387
29777
  }
29778
+ /**
29779
+ * Answers to removed members' syncs (`farewellSync`), per `farewellTo`, a slice at a time with two at most not handled
29780
+ * yet by the member's app, as a member's catch-up goes (`CatchUpAnswers`). One ends once its edge no longer takes a
29781
+ * frame, or the member is no longer waited for. Made at the first answer.
29782
+ */
29783
+ farewellAnswers;
29784
+ farewellOut() {
29785
+ if (this.farewellAnswers) return this.farewellAnswers;
29786
+ const edge = (to) => {
29787
+ const [groupId, key] = to.split(" ");
29788
+ return {
29789
+ groupId,
29790
+ key,
29791
+ linkId: this.host.edges(groupId).get(key)
29792
+ };
29793
+ };
29794
+ return this.farewellAnswers = new CatchUpAnswers({
29795
+ send: (to, frame) => {
29796
+ const { groupId, key, linkId } = edge(to), session = this.sessions.get(groupId);
29797
+ if (!linkId || !session || !this.stored.get(groupId)?.farewells?.[key] || rosterHas(session.roster, key)) return false;
29798
+ try {
29799
+ this.host.sendOnLink(linkId, frame);
29800
+ return true;
29801
+ } catch {
29802
+ return false;
29803
+ }
29804
+ },
29805
+ ...this.host.linkHandled && { handled: (to) => {
29806
+ const { linkId } = edge(to);
29807
+ return linkId && this.host.linkHandled ? this.host.linkHandled(linkId) : Promise.resolve(false);
29808
+ } },
29809
+ active: () => true,
29810
+ key: (frame) => frame.t === "group-commit" ? `commit:${frame.commit.e}` : void 0
29811
+ });
29812
+ }
30388
29813
  async makeAdmin(groupId, key) {
30389
29814
  if (this.isCommunity(groupId)) return this.communities.makeAdmin(groupId, key);
30390
29815
  await this.session(groupId).transferAdmin(key);
@@ -30470,6 +29895,7 @@ var Groups = class {
30470
29895
  this.hereHeard.delete(groupId);
30471
29896
  this.hereActed.delete(groupId);
30472
29897
  this.signals.forget(groupId);
29898
+ dropMarks(this.marks, groupId);
30473
29899
  this.authorOrder.forget(groupId);
30474
29900
  this.lineOrder.forget(MESSAGE_LINK(groupId));
30475
29901
  for (const linkId of [...this.host.edges(groupId).values(), ...this.host.entries(groupId).values()]) await this.host.closeEdge(linkId);
@@ -30603,6 +30029,11 @@ var Groups = class {
30603
30029
  continue;
30604
30030
  }
30605
30031
  const session = this.sessions.get(group.id);
30032
+ if (group.farewells && session) this.farewellsTick(group.id, session, now);
30033
+ if (group.left.heard !== void 0 && !group.farewells) {
30034
+ await this.forget(group.id);
30035
+ continue;
30036
+ }
30606
30037
  if (session?.status === "left" && session.admin === session.myKey && now >= (this.handOnAt.get(group.id) ?? 0)) await this.handOn(group.id);
30607
30038
  continue;
30608
30039
  }
@@ -31404,6 +30835,11 @@ var Groups = class {
31404
30835
  }
31405
30836
  if (this.isCommunity(groupId)) return this.communities.handleEdgeFrame(groupId, peerKey, frame);
31406
30837
  if (this.stored.get(groupId)?.left) {
30838
+ const tomb = this.stored.get(groupId), session = this.sessions.get(groupId);
30839
+ if (session && tomb.farewells?.[peerKey] && !rosterHas(session.roster, peerKey)) {
30840
+ if (frame && typeof frame === "object") this.farewellSync(groupId, session, tomb, peerKey, frame);
30841
+ return;
30842
+ }
31407
30843
  if (this.removesMe(groupId, peerKey, frame)) await this.leaveConfirmed(groupId);
31408
30844
  else await this.afterLeave(groupId, peerKey, frame);
31409
30845
  return;
@@ -31609,6 +31045,10 @@ var Groups = class {
31609
31045
  const left = this.stored.get(groupId)?.left;
31610
31046
  if (left) {
31611
31047
  const session = this.sessions.get(groupId), group = this.stored.get(groupId);
31048
+ if (session && group.farewells?.[peerKey] && !rosterHas(session.roster, peerKey)) {
31049
+ this.sayFarewell(groupId, session, group, peerKey, linkId);
31050
+ return;
31051
+ }
31612
31052
  if (peerKey === left.admin) try {
31613
31053
  if (session) this.sayLeave(groupId, session, group, linkId);
31614
31054
  else this.host.sendOnLink(linkId, {
@@ -32340,9 +31780,9 @@ var Groups = class {
32340
31780
  const left = group?.left;
32341
31781
  const removed = this.removedAt.get(groupId);
32342
31782
  const wanted = session?.status === "active" && group ? this.edgesWanted(groupId, session, group, this.now()) : left ? /* @__PURE__ */ new Set([
32343
- left.admin,
32344
- ...left.hubs ?? [],
32345
- ...this.holdsRole(groupId, session) && !this.hubs.large(session) ? session.others : []
31783
+ ...left.heard === void 0 ? [left.admin, ...left.hubs ?? []] : [],
31784
+ ...this.holdsRole(groupId, session) && !this.hubs.large(session) ? session.others : [],
31785
+ ...this.farewellKeys(group, session, this.now())
32346
31786
  ]) : removed !== void 0 && this.now() - removed < REMOVED_LINGER_MS ? new Set(existing.keys()) : /* @__PURE__ */ new Set();
32347
31787
  for (const [key, linkId] of existing) if (!wanted.has(key)) await this.host.closeEdge(linkId);
32348
31788
  const met = this.justMet.get(groupId);
@@ -32388,6 +31828,34 @@ var Groups = class {
32388
31828
  eventTimes = /* @__PURE__ */ new Map();
32389
31829
  };
32390
31830
  //#endregion
31831
+ //#region ../browser/src/engine/communityEdgePace.ts
31832
+ /**
31833
+ * How much slower this app looks at the Pkarr records of its connected edges in a community than a chat would, while it
31834
+ * holds `edges` edges there: up to eight, as a chat; past that, in proportion. A member holds one or two (its hubs);
31835
+ * a hub one per member it carries, and each connected read is a request of the minute the relays allow this app.
31836
+ * At the chat's pace, an admin carrying 22 members spent 22 of its 60 requests a minute on those reads alone, so it
31837
+ * had little left to bring up the edges of the members another hub's closing had cut off, who waited two to five
31838
+ * minutes (bug hunt, 2026-11-11). Now a hub's connected edges cost about 8 reads a minute however many it
31839
+ * carries, as a private group's do (`meshEdgeScale`), and the edges it is bringing up count too, so the reads slow
31840
+ * further while it takes members in. A data link that drops is noticed on its own (the edge reads fast again): a
31841
+ * connected read only notices a member's new offer while this side still thinks the link is up.
31842
+ */
31843
+ function communityEdgeScale(edges) {
31844
+ return Math.max(1, edges / 8);
31845
+ }
31846
+ /** A community edge's poll pace, read live: its connected reads follow how many edges this app holds there. */
31847
+ function communityEdgeIntervals(base, edges) {
31848
+ return {
31849
+ active: base.active,
31850
+ idle: base.idle,
31851
+ fast: base.fast,
31852
+ background: base.background,
31853
+ get connected() {
31854
+ return Math.round(base.connected * communityEdgeScale(edges()));
31855
+ }
31856
+ };
31857
+ }
31858
+ //#endregion
32391
31859
  //#region ../browser/src/engine/groupEdges.ts
32392
31860
  /**
32393
31861
  * An edge of a group as the group page shows it (WISP 902 § Mesh): open means group frames flow, which
@@ -32496,7 +31964,7 @@ var RANK = {
32496
31964
  var ID = /^[A-Za-z0-9_-]{8,64}$/;
32497
31965
  /** Notes of mine sent again to a member whose edge opens. */
32498
31966
  var RESEND = 32;
32499
- var NOTE_ID = (id) => `gpay:${id}`;
31967
+ var NOTE_ID = groupPayLineId;
32500
31968
  /** A `group-pay` frame, strictly: anything else is dropped. */
32501
31969
  function parseGroupPay(raw, groupId) {
32502
31970
  if (!raw || typeof raw !== "object") return null;
@@ -32608,7 +32076,8 @@ function mergeGroupPay(current, frame, author, members) {
32608
32076
  return JSON.stringify(next) === JSON.stringify(current) ? void 0 : next;
32609
32077
  }
32610
32078
  var federationOf = (p) => p.federation ?? p.federations?.[0];
32611
- var railOf = (p) => p.target ? p.target.method === "cashu" ? "cashu" : p.target.method : federationOf(p) ? "fedimint" : p.invoice && !p.mints?.length && !p.mint ? "lightning" : "cashu";
32079
+ /** A request's `mint` is where its invoice was paid in (a Cashu mint's Lightning, `onLightningPaid`), not how it was asked. */
32080
+ var railOf = (p) => p.target ? p.target.method === "cashu" ? "cashu" : p.target.method : federationOf(p) ? "fedimint" : p.invoice && !p.mints?.length && (p.kind === "request" || !p.mint) ? "lightning" : "cashu";
32612
32081
  /** Test money as the chat's bubble reads it (paymentIsTest): a target's chain, else the record's network, else a Fedimint federation's network, else its mints. */
32613
32082
  var testOf = (p, federationNetwork) => {
32614
32083
  if (p.target) return p.target.method === "cashu" ? p.target.network === "cashu-test" : p.target.method === "usdt" ? p.unit === "testusdt" : p.target.network !== "bitcoin";
@@ -33337,22 +32806,6 @@ function outlives(membership, edit) {
33337
32806
  return edit.rm === true && !membership.community;
33338
32807
  }
33339
32808
  //#endregion
33340
- //#region ../browser/src/shared/payLinks.ts
33341
- /**
33342
- * The desk's links to members of a community group (WISP 903 · Group Community § Payments): payments with a member
33343
- * go through the group, sealed to them, over `cpay:<group>:<member>`; a request to everyone over `cpay:<group>`.
33344
- */
33345
- var pairLinkId = (groupId, member) => `cpay:${groupId}:${member}`;
33346
- var groupLinkId = (groupId) => `cpay:${groupId}`;
33347
- /** The group and member of a community payment link, or undefined for any other link. */
33348
- function parsePayLink(linkId) {
33349
- const m = /^cpay:([A-Za-z0-9_-]{22})(?::([a-z0-9]{52}))?$/.exec(linkId);
33350
- return m ? {
33351
- groupId: m[1],
33352
- ...m[2] ? { member: m[2] } : {}
33353
- } : void 0;
33354
- }
33355
- //#endregion
33356
32809
  //#region ../browser/src/engine/communityPay.ts
33357
32810
  /**
33358
32811
  * Payments in community groups (WISP 903 · Group Community § Payments). Members have no edge to each other: what
@@ -35989,7 +35442,7 @@ var walletTx = (mint, kind, amount, fee, note) => ({
35989
35442
  /** What a failed payment left in the wallet, said to the person: all of it, or all but the fee the mint kept. */
35990
35443
  var backInWallet = (lost) => lost > 0 ? `The sats are back in your wallet, less ${lost} sat${lost === 1 ? "" : "s"} the mint kept as its fee.` : "The sats are back in your wallet.";
35991
35444
  /** A mint's own words for a refusal, as one short line: the reason at the end of `lightningRefused`. */
35992
- var mintReason = (error) => (error instanceof Error ? error.message : String(error)).replace(/\s+/g, " ").trim().slice(0, 160) || "no reason given";
35445
+ var mintReason = (error) => stripHidden((error instanceof Error ? error.message : String(error)).replace(/\s+/g, " ")).replace(/\s+/g, " ").trim().slice(0, 160) || "no reason given";
35993
35446
  /**
35994
35447
  * How long a mint gets to answer when it is only being asked something (its keys, an invoice). A mint
35995
35448
  * that is down can hold a request for minutes; the next mint should get its turn well before that.
@@ -36602,13 +36055,38 @@ var CashuWallet = class CashuWallet {
36602
36055
  if (sent) return sent;
36603
36056
  }
36604
36057
  if (room > 0) throw engineError("notEnoughForFee", { amount: room });
36058
+ const held = await this.heldBySilentSplit(candidates, amount);
36059
+ if (held) throw new SwapUnsettledError(held);
36605
36060
  throw engineError(candidates.length === 0 && preferred ? "noSharedMint" : "notEnoughSats");
36606
36061
  }
36062
+ /** An open send swap at one of `mints` whose reserved inputs, with the coins free there, would cover `amount`. */
36063
+ async heldBySilentSplit(mints, amount) {
36064
+ for (const mint of mints) {
36065
+ const open = (await this.swapsAt(mint)).filter((s) => s.kind === "send" && !s.released && !s.finished);
36066
+ if (open.length === 0) continue;
36067
+ const held = await Promise.all(open.map((s) => this.storedInputs(s)));
36068
+ const swap = open.find((_, i) => held[i].length > 0);
36069
+ if (swap && total(await this.proofsAt(mint)) + total(held.flat()) >= amount) return swap;
36070
+ }
36071
+ }
36607
36072
  async prepareReviewedCashu(mint, amount) {
36608
36073
  assertAmount(amount);
36609
36074
  if (!this.getKnownMints().includes(mint)) throw new Error("Select a configured mint");
36610
36075
  return this.locked(mint, async () => {
36611
- const preview = await (await this.wallet(mint)).ops.send(amount, asProofLike(await this.proofsAt(mint))).includeFees(true).prepare();
36076
+ const wallet = await this.wallet(mint);
36077
+ const proofs = await this.proofsAt(mint);
36078
+ const prepare = (sats) => wallet.ops.send(sats, asProofLike(proofs)).includeFees(true).prepare();
36079
+ const preview = await prepare(amount).catch(async (error) => {
36080
+ if (!/^Not enough funds available/.test(error instanceof Error ? error.message : "")) throw error;
36081
+ const fits = (sats) => prepare(sats).then(() => true, () => false);
36082
+ let low = 0, high = Math.min(amount, total(proofs) - wallet.getFeesForProofs(asProofLike(proofs)).toNumber()) - 1;
36083
+ while (low < high) {
36084
+ const middle = Math.ceil((low + high) / 2);
36085
+ if (await fits(middle)) low = middle;
36086
+ else high = middle - 1;
36087
+ }
36088
+ throw low > 0 ? engineError("notEnoughForFee", { amount: low }) : engineError("notEnoughSats");
36089
+ });
36612
36090
  return {
36613
36091
  fee: await reviewedCashuFee(preview),
36614
36092
  prepared: {
@@ -37904,8 +37382,11 @@ function parseSats(value, asset) {
37904
37382
  * wallet's `engineCode` and `values` stay on it: a host reads why by them (the CLI's `refused`, the app's words).
37905
37383
  */
37906
37384
  var NoEcashError = class extends Error {
37385
+ /** The mint took the split and has not answered: the sats it set aside come back once it does (`SwapUnsettledError`). */
37386
+ unsettled;
37907
37387
  constructor(cause) {
37908
37388
  super(cause instanceof Error ? cause.message : String(cause));
37389
+ this.unsettled = cause instanceof SwapUnsettledError;
37909
37390
  const { engineCode, values } = cause ?? {};
37910
37391
  if (engineCode !== void 0) Object.assign(this, { engineCode });
37911
37392
  if (values !== void 0) Object.assign(this, { values });
@@ -38103,6 +37584,8 @@ var RAIL_LOOK_MS = 1e4;
38103
37584
  * ago: otherwise a pace stays shut for as long as the clock went back.
38104
37585
  */
38105
37586
  var within = (now, at, ms) => at !== void 0 && at <= now && now - at < ms;
37587
+ /** What a contact reads about a request of ours closed for good (`close`), when it closes and each time their chat opens again. */
37588
+ var CLOSED_TOLD = "your contact removed the wallet it was paid to";
38106
37589
  /**
38107
37590
  * How often a wallet's own refresh asks about an open Ark request (at its server's indexer) or a contact's pending Ark
38108
37591
  * or USDT receipt (at the server or the chain) that has no answer yet (`AskBackoff`): at the wallet's pace while the
@@ -38653,6 +38136,7 @@ var PaymentDesk = class {
38653
38136
  await link.requirePaymentSupport();
38654
38137
  const lightning = !!request.invoice && link.allowsPayment("lightning");
38655
38138
  if (params.via === "lightning" && !lightning) throw new Error("This request cannot be paid over Lightning in this chat");
38139
+ let unsettled;
38656
38140
  if (params.via !== "lightning" && link.allowsPayment("cashu") && !request.federations) try {
38657
38141
  await this.sendEcash(link, {
38658
38142
  linkId: params.linkId,
@@ -38665,9 +38149,13 @@ var PaymentDesk = class {
38665
38149
  return;
38666
38150
  } catch (error) {
38667
38151
  if (!lightning || !(error instanceof NoEcashError)) throw error;
38152
+ if (error.unsettled) unsettled = error;
38668
38153
  }
38669
38154
  else if (!lightning) throw new Error("No way of paying this request is allowed in this chat");
38670
- const quote = await this.lightning[network].quote(request.invoice, params.card);
38155
+ const quote = await this.lightning[network].quote(request.invoice, params.card).catch((error) => {
38156
+ const code = error?.engineCode;
38157
+ throw unsettled && (code === "notEnoughSats" || code === "notEnoughForFee") ? unsettled : error;
38158
+ });
38671
38159
  if (quote.amount !== request.amount) throw new Error("The invoice does not match the requested amount");
38672
38160
  const feeLimit = Math.min(Math.max(10, Math.ceil(request.amount * .03)), params.maxFee ?? Infinity);
38673
38161
  if (quote.feeReserve > feeLimit) throw engineError("lightningFeeTooHigh", { fee: quote.feeReserve });
@@ -38839,6 +38327,12 @@ var PaymentDesk = class {
38839
38327
  state: "settled",
38840
38328
  token: void 0
38841
38329
  });
38330
+ else if (current.state === "failed" && current.token) await this.save({
38331
+ ...current,
38332
+ state: "settled",
38333
+ token: void 0,
38334
+ error: void 0
38335
+ });
38842
38336
  return;
38843
38337
  }
38844
38338
  }
@@ -40747,10 +40241,10 @@ var PaymentDesk = class {
40747
40241
  /**
40748
40242
  * A request of ours closed for good: the wallet it was paid through was removed. Nothing sends it again (replay,
40749
40243
  * a group edge opening), and the contact is told now when the chat is open (a request to a group: every member
40750
- * reachable), so their app stops offering to pay it. `reason`: shown here; `told`: what the contact reads. Returns
40751
- * whether it was open.
40244
+ * reachable; one away is told when their chat opens, `replay`), so their app stops offering to pay it. `reason`: shown
40245
+ * here. Returns whether it was open.
40752
40246
  */
40753
- async close(id, reason, told) {
40247
+ async close(id, reason) {
40754
40248
  const request = this.payments.get(id);
40755
40249
  if (request?.kind !== "request" || request.direction !== "out" || request.state !== "pending") return false;
40756
40250
  await this.save({
@@ -40766,7 +40260,7 @@ var PaymentDesk = class {
40766
40260
  link.sendPaymentResult({
40767
40261
  id,
40768
40262
  ok: false,
40769
- error: told,
40263
+ error: CLOSED_TOLD,
40770
40264
  closed: true
40771
40265
  });
40772
40266
  } catch {}
@@ -40785,6 +40279,12 @@ var PaymentDesk = class {
40785
40279
  id: request.id,
40786
40280
  ok: true
40787
40281
  });
40282
+ else if (request.closed) link.sendPaymentResult({
40283
+ id: request.id,
40284
+ ok: false,
40285
+ error: CLOSED_TOLD,
40286
+ closed: true
40287
+ });
40788
40288
  }
40789
40289
  for (const payment of this.payments.values()) {
40790
40290
  if (payment.linkId !== linkId || payment.direction !== "out" || this.reclaims.has(payment.id)) continue;
@@ -40795,6 +40295,15 @@ var PaymentDesk = class {
40795
40295
  });
40796
40296
  continue;
40797
40297
  }
40298
+ if (payment.kind === "request" && payment.closed) {
40299
+ link.sendPaymentResult({
40300
+ id: payment.id,
40301
+ ok: false,
40302
+ error: CLOSED_TOLD,
40303
+ closed: true
40304
+ });
40305
+ continue;
40306
+ }
40798
40307
  if (payment.target?.method === "usdt") {
40799
40308
  if (!link.supportsUsdtPayments) continue;
40800
40309
  if (payment.kind === "request" && payment.state === "pending" && payment.target.expiresAt > Date.now()) await link.sendPaymentRequest({
@@ -41904,11 +41413,13 @@ var GhostlyNode = class GhostlyNode {
41904
41413
  */
41905
41414
  openReviews = null;
41906
41415
  /**
41907
- * The pace of each submitted Cashu payment the contact has not taken: asked at 10 s while new, then twice as late up
41908
- * to 10 min (as a payee retries a redeem). At the poll's own 10 s, a contact online whose redeems fail cost the mint
41909
- * 12 checkstates a minute for each such payment, for as long as the app ran. The contact taking one says so at once.
41416
+ * The pace of each submitted payment whose outcome is still open: asked at 10 s while new, then twice as late up to
41417
+ * 10 min (as a payee retries a redeem). At the poll's own 10 s, a contact online whose redeems fail cost the mint 12
41418
+ * checkstates a minute for each such Cashu payment, and an on-chain payment waiting in the mempool its source 360
41419
+ * reads an hour (each with the Ark, Bark, Spark and USDT wallets read again), for as long as it stayed so. The
41420
+ * contact taking one says so at once.
41910
41421
  */
41911
- cashuPayAsk = new AskBackoff(1e4, 6e5);
41422
+ payAsk = new AskBackoff(1e4, 6e5);
41912
41423
  noteOpenReviews(reviews) {
41913
41424
  const open = this.openReviews ??= /* @__PURE__ */ new Set();
41914
41425
  for (const review of reviews) if (review.state === "submitted" || review.state === "unknown") open.add(review.id);
@@ -42099,6 +41610,7 @@ var GhostlyNode = class GhostlyNode {
42099
41610
  host: () => this.providerHost(network),
42100
41611
  hasMints: () => this.networkMints(network).length > 0,
42101
41612
  fetch: (...request) => (this.options.lnurlFetch ?? globalThis.fetch)(...request),
41613
+ sparkStorage: () => this.sparkWallets[network].adapter?.storage,
42102
41614
  events: {
42103
41615
  changed: () => this.walletChanged(),
42104
41616
  received: (op) => void this.desk.onLightningPaid(op),
@@ -42297,6 +41809,7 @@ var GhostlyNode = class GhostlyNode {
42297
41809
  }
42298
41810
  }),
42299
41811
  receiveFile: async (linkId, wire, bytes, digest, held) => {
41812
+ if (await this.namesMine(linkId, wire.wireId)) return "duplicate file id";
42300
41813
  const live = this.links.get(linkId);
42301
41814
  if (!live) return "unknown chat";
42302
41815
  if (live.files.wireIds.has(wire.wireId)) return "duplicate file id";
@@ -42484,10 +41997,7 @@ var GhostlyNode = class GhostlyNode {
42484
41997
  this.accepting = true;
42485
41998
  try {
42486
41999
  const { linkId } = await this.joinLink({ inviteCode: request.invite });
42487
- this.renameLink({
42488
- linkId,
42489
- label: request.name
42490
- });
42000
+ const peerNick = sanitizeDisplayText(request.name.trim().replace(/\s+/gu, " "), 48)?.replace(/ {2,}/g, " ");
42491
42001
  const message = `peer_contact_${request.key.slice(0, 32)}`;
42492
42002
  const contactAsker = {
42493
42003
  link: request.link,
@@ -42497,9 +42007,14 @@ var GhostlyNode = class GhostlyNode {
42497
42007
  const live = this.links.get(linkId);
42498
42008
  if (live) live.stored = {
42499
42009
  ...live.stored,
42010
+ peerNick,
42500
42011
  contactAsker
42501
42012
  };
42502
- await db.patchLink(linkId, { contactAsker });
42013
+ await db.patchLink(linkId, {
42014
+ peerNick,
42015
+ contactAsker
42016
+ });
42017
+ this.emitState();
42503
42018
  await this.storeMessage({
42504
42019
  linkId,
42505
42020
  id: message,
@@ -42817,7 +42332,7 @@ var GhostlyNode = class GhostlyNode {
42817
42332
  staysOnline: () => this.options.staysOnline ?? (this.options.platform === "desktop" && typeof RTCPeerConnection !== "undefined"),
42818
42333
  peerRoom: (groupId) => {
42819
42334
  const native = Object.keys(this.nativeFactories);
42820
- if (typeof RTCPeerConnection === "undefined" && native.length) {
42335
+ if (!this.contactRtc() && native.length) {
42821
42336
  let held = 0;
42822
42337
  for (const live of this.links.values()) if (live.stored.group && live.stored.group !== groupId && live.link) held++;
42823
42338
  return Math.max(0, Math.max(...native.map((key) => this.groupNativeRoom(key))) - held);
@@ -43177,7 +42692,7 @@ var GhostlyNode = class GhostlyNode {
43177
42692
  */
43178
42693
  async sentWithoutLine(payments) {
43179
42694
  const lost = /* @__PURE__ */ new Set();
43180
- const sent = payments.filter((p) => p.kind === "payment" && p.direction === "out" && p.state === "pending" && p.token);
42695
+ const sent = payments.filter(sentUntaken);
43181
42696
  if (!sent.length) return lost;
43182
42697
  let groups;
43183
42698
  const everyGroup = () => groups ??= this.groups.views().map((g) => g.id);
@@ -43378,9 +42893,9 @@ var GhostlyNode = class GhostlyNode {
43378
42893
  try {
43379
42894
  if (!this.openReviews) this.noteOpenReviews((await intentRepository.list()).map((saved) => saved.review));
43380
42895
  const open = this.openReviews;
43381
- this.cashuPayAsk.keepOnly(open);
42896
+ this.payAsk.keepOnly(open);
43382
42897
  for (const id of [...open]) {
43383
- if (!this.cashuPayAsk.due(id, Date.now())) continue;
42898
+ if (!this.payAsk.due(id, Date.now())) continue;
43384
42899
  const saved = await intentRepository.get(id), review = saved?.review;
43385
42900
  if (!review || !["submitted", "unknown"].includes(review.state)) {
43386
42901
  open.delete(id);
@@ -43391,7 +42906,10 @@ var GhostlyNode = class GhostlyNode {
43391
42906
  if (review.method === "cashu" && !prepared.abandoned && !prepared.spentElsewhere && !this.wallet.mintDue(prepared.mint, Date.now())) continue;
43392
42907
  if (review.method === "arkade" && !this.arkWallets[network].adapter || review.method === "bark" && !this.barkWallets[network].adapter || review.method === "spark" && !this.sparkWallets[network].adapter || review.method === "usdt" && !this.usdtWallets[network].adapter || review.method === "bitcoin" && !this.bitcoins[network].sources.active || review.method === "fedimint" && !this.fedimintWallets[network].federation(review.provider)) continue;
43393
42908
  const after = await this.reconcilePayment({ id: review.id }).catch(() => review);
43394
- if (review.method === "cashu" && ["submitted", "unknown"].includes(after.state)) this.cashuPayAsk.missed(id, Date.now(), Date.now() < (prepared.token ? (review.submittedAt ?? review.createdAt) + 6e4 : swapSettledAt(review, prepared)));
42909
+ if (["submitted", "unknown"].includes(after.state)) {
42910
+ const sent = review.submittedAt ?? review.createdAt;
42911
+ this.payAsk.missed(id, Date.now(), Date.now() < (review.method === "cashu" && !prepared.token ? swapSettledAt(review, prepared) : sent + 6e4));
42912
+ }
43395
42913
  }
43396
42914
  } finally {
43397
42915
  if (!this.shuttingDown) this.paymentTimer = setTimeout(() => void this.pollPaymentStatus(), 1e4);
@@ -44107,10 +43625,10 @@ var GhostlyNode = class GhostlyNode {
44107
43625
  } } : {},
44108
43626
  ...this.transport.configure && { direct: true },
44109
43627
  ...this.transport.discovery && { discovery: this.transport.discovery() },
44110
- ...typeof RTCPeerConnection === "undefined" && { webrtc: false },
43628
+ ...!this.contactRtc() && { webrtc: false },
44111
43629
  ...this.directPath.blocked && { directBlocked: true },
44112
43630
  ...this.clock.offset !== null && { clockOffMs: this.clock.offset },
44113
- ...typeof RTCPeerConnection === "undefined" && !Object.keys(this.nativeFactories).length && { groupLinks: false }
43631
+ ...!this.contactRtc() && !Object.keys(this.nativeFactories).length && { groupLinks: false }
44114
43632
  },
44115
43633
  links: [...this.links.values()].filter((live) => !live.stored.group).map((live) => this.viewOf(live)).sort((a, b) => b.createdAt - a.createdAt),
44116
43634
  services: this.services.map((s) => ({
@@ -45162,7 +44680,7 @@ var GhostlyNode = class GhostlyNode {
45162
44680
  this.wakeLimiter.reset(linkId);
45163
44681
  this.callWakeLimiter.reset(linkId);
45164
44682
  if (live.stored.wakeToken) this.rotateWake().then(() => this.emitState());
45165
- db.deleteLink(linkId);
44683
+ db.deleteLink(linkId).finally(() => this.appShelf?.forgetScope(linkId));
45166
44684
  this.desk.forgetLink(linkId);
45167
44685
  this.awaitingSoon();
45168
44686
  this.emitState();
@@ -46844,6 +46362,7 @@ var GhostlyNode = class GhostlyNode {
46844
46362
  * (its offer came first), or its message was deleted here.
46845
46363
  */
46846
46364
  async fileAnnounced(linkId, said, packet) {
46365
+ if (await this.namesMine(linkId, said.wireId)) return;
46847
46366
  const live = this.links.get(linkId);
46848
46367
  if (!live) return;
46849
46368
  const id = `peer_${said.wireId}`;
@@ -47283,7 +46802,7 @@ var GhostlyNode = class GhostlyNode {
47283
46802
  */
47284
46803
  async setGroupTransport({ groupId, transport }) {
47285
46804
  if (!this.groups.view(groupId)) throw new Error("Group not found");
47286
- const runs = transport === "webrtc/1" ? typeof RTCPeerConnection !== "undefined" : transport !== "auto" && TRANSPORTS.includes(transport) && transport in this.nativeFactories;
46805
+ const runs = transport === "webrtc/1" ? this.contactRtc() : transport !== "auto" && TRANSPORTS.includes(transport) && transport in this.nativeFactories;
47287
46806
  if (transport !== "auto" && !runs) throw new Error("Transport unavailable");
47288
46807
  if ((this.settings.groupTransports?.[groupId] ?? "auto") === transport) return;
47289
46808
  const { [groupId]: _, ...others } = this.settings.groupTransports ?? {};
@@ -48346,8 +47865,18 @@ var GhostlyNode = class GhostlyNode {
48346
47865
  ownStatusTimer;
48347
47866
  /** Per chat: when the contact's status ends, so its view is drawn again without it. */
48348
47867
  peerStatusTimers = /* @__PURE__ */ new Map();
48349
- /** WISP 401 § Presence and status: `active` at a page's word, `idle` 10 minutes after the last one (or at a page's). */
47868
+ /**
47869
+ * WISP 401 § Presence and status: `active` at a page's word, `idle` 10 minutes after the last one (or at a page's).
47870
+ * `null`: none again, as before the first word (a headless daemon whose `daemonPresence` was turned off).
47871
+ */
48350
47872
  setPresence({ presence }) {
47873
+ if (presence === null) {
47874
+ clearTimeout(this.idleTimer);
47875
+ if (this.ownPresence === void 0) return;
47876
+ this.ownPresence = void 0;
47877
+ this.sayStatus();
47878
+ return;
47879
+ }
48351
47880
  if (presence !== "active" && presence !== "idle") return;
48352
47881
  clearTimeout(this.idleTimer);
48353
47882
  if (presence === "active") this.idleTimer = setTimeout(() => this.setPresence({ presence: "idle" }), STATUS_IDLE_AFTER_MS);
@@ -48643,7 +48172,7 @@ var GhostlyNode = class GhostlyNode {
48643
48172
  /** A request of ours closes for good (its wallet was removed): never sent again, taken back from the contact's storage too. */
48644
48173
  async closeRequest(paymentId, reason) {
48645
48174
  const request = this.desk.payment(paymentId);
48646
- if (!request || !await this.desk.close(paymentId, reason, "your contact removed the wallet it was paid to")) return;
48175
+ if (!request || !await this.desk.close(paymentId, reason)) return;
48647
48176
  const message = await this.paymentMessage(request.linkId, paymentId);
48648
48177
  if (message) await this.hold.forget(request.linkId, message.id).catch(() => {});
48649
48178
  }
@@ -49531,6 +49060,10 @@ var GhostlyNode = class GhostlyNode {
49531
49060
  await db.putSettings(this.settings);
49532
49061
  this.sayStatus();
49533
49062
  }
49063
+ if (settings.daemonPresence !== void 0) {
49064
+ if (settings.daemonPresence !== true) delete this.settings.daemonPresence;
49065
+ await db.putSettings(this.settings);
49066
+ }
49534
49067
  for (const key of ["autoDownloads", "serveFiles"]) {
49535
49068
  if (settings[key] === void 0) continue;
49536
49069
  if (settings[key] !== false) delete this.settings[key];
@@ -50721,7 +50254,7 @@ var GhostlyNode = class GhostlyNode {
50721
50254
  largeFilesSupport: !entry,
50722
50255
  binaryFilesSupport: !entry,
50723
50256
  params: stored,
50724
- rtcAvailable: typeof RTCPeerConnection !== "undefined" && !this.edgeRtcOff.has(linkId) && !this.groupNativeChoice(stored),
50257
+ rtcAvailable: this.contactRtc() && !this.edgeRtcOff.has(linkId) && !this.groupNativeChoice(stored),
50725
50258
  resume: !entry && stored.edgeLive ? resumeOn : void 0,
50726
50259
  native: {
50727
50260
  peerDescriptors: stored.peerDescriptors,
@@ -50746,14 +50279,14 @@ var GhostlyNode = class GhostlyNode {
50746
50279
  },
50747
50280
  transport: live.carried ?? this.groupTransport,
50748
50281
  nick: !entry && this.quietEdge(stored) ? void 0 : this.sharedNick,
50749
- pollIntervals: entry || this.groups.isCommunityGroup(group) ? this.pollIntervals : meshEdgeIntervals(this.pollIntervals, () => this.groups.meshSize(group)),
50282
+ pollIntervals: entry ? this.pollIntervals : this.groups.isCommunityGroup(group) ? communityEdgeIntervals(this.pollIntervals, () => this.groupEdges(group).size) : meshEdgeIntervals(this.pollIntervals, () => this.groups.meshSize(group)),
50750
50283
  madeAt: stored.createdAt,
50751
50284
  autoConnect: true,
50752
50285
  ...entry ? {
50753
50286
  oneShot: true,
50754
50287
  firstPublish: stored.groupEntry === "host" ? "after-first-poll" : "at-start"
50755
50288
  } : {},
50756
- createPeerConnection: () => new RTCPeerConnection(this.contactRtcConfig()),
50289
+ createPeerConnection: () => this.contactPeerConnection(),
50757
50290
  localFetch: this.localFetch,
50758
50291
  getServices: () => [{
50759
50292
  id: "chat",
@@ -50889,7 +50422,7 @@ var GhostlyNode = class GhostlyNode {
50889
50422
  */
50890
50423
  keepsGroupNative(stored) {
50891
50424
  if (this.options.webrtcGroupLinks) return false;
50892
- return typeof RTCPeerConnection === "undefined" || this.edgeRtcOff.has(stored.id) || !!stored.peerTransports && !stored.peerTransports.includes("webrtc/1") || this.groupNativeChoice(stored) !== void 0;
50425
+ return !this.contactRtc() || this.edgeRtcOff.has(stored.id) || !!stored.peerTransports && !stored.peerTransports.includes("webrtc/1") || this.groupNativeChoice(stored) !== void 0;
50893
50426
  }
50894
50427
  /** What this device chose for the group of an edge (`setGroupTransport`); undefined on Automatic, and for an entry session. */
50895
50428
  groupChoice(stored) {
@@ -51041,7 +50574,7 @@ var GhostlyNode = class GhostlyNode {
51041
50574
  usdtPaymentsSupport: true,
51042
50575
  barkPaymentsSupport: true,
51043
50576
  params: stored,
51044
- rtcAvailable: typeof RTCPeerConnection !== "undefined",
50577
+ rtcAvailable: this.contactRtc(),
51045
50578
  callsSupport: this.options.callsSupport ?? typeof RTCPeerConnection !== "undefined",
51046
50579
  callsMissing: this.options.callsUnavailable,
51047
50580
  largeFilesSupport: true,
@@ -51148,7 +50681,7 @@ var GhostlyNode = class GhostlyNode {
51148
50681
  pollIntervals: this.pollIntervals,
51149
50682
  ...this.options.watchPeerIdleMs ? { watchPeerIdleMs: this.options.watchPeerIdleMs } : {},
51150
50683
  autoConnect: true,
51151
- createPeerConnection: () => this.chatPeer(new RTCPeerConnection(this.contactRtcConfig())),
50684
+ createPeerConnection: () => this.chatPeer(this.contactPeerConnection()),
51152
50685
  localFetch: this.localFetch,
51153
50686
  getServices: () => stored.profile ? [{
51154
50687
  id: "chat",
@@ -51533,7 +51066,19 @@ var GhostlyNode = class GhostlyNode {
51533
51066
  }
51534
51067
  /** The layer-1 transports this app can run at all: WebRTC where the page has it, then its native adapters. */
51535
51068
  transportsHere() {
51536
- return [...typeof RTCPeerConnection !== "undefined" ? ["webrtc/1"] : [], ...Object.keys(this.nativeFactories)];
51069
+ return [...this.contactRtc() ? ["webrtc/1"] : [], ...Object.keys(this.nativeFactories)];
51070
+ }
51071
+ /**
51072
+ * Whether chats and group edges run WebRTC: where the page has it, but not while Hide my IP from contacts is on where
51073
+ * that WebRTC does not keep to the relay (`webrtcIgnoresRelayOnly`, the CLI). Calls are refused there on their own.
51074
+ */
51075
+ contactRtc() {
51076
+ return typeof RTCPeerConnection !== "undefined" && !(this.options.webrtcIgnoresRelayOnly && this.settings.relayOnly === true);
51077
+ }
51078
+ /** A chat's or group edge's WebRTC connection; none (an offer is neither made nor answered) where `contactRtc` says so. */
51079
+ contactPeerConnection() {
51080
+ if (!this.contactRtc()) throw new Error("No WebRTC for contacts here");
51081
+ return new RTCPeerConnection(this.contactRtcConfig());
51537
51082
  }
51538
51083
  /** Something the capability record carries changed here: every chat publishes its record anew if it differs. */
51539
51084
  capsChanged(linkId) {
@@ -51580,7 +51125,7 @@ var GhostlyNode = class GhostlyNode {
51580
51125
  nativeFactoriesFor(relayOnly) {
51581
51126
  const relay = relayOnly || this.relaysHyperdhtNatively ? this.hyperdhtRelay : "";
51582
51127
  return {
51583
- ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-BvI_uNZO.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
51128
+ ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-uAThbFub.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
51584
51129
  ...relayOnly ? {} : this.options.nativeTransports,
51585
51130
  ...this.ownIrohRelays && !relayOnly ? { "iroh/1": (seedB64) => this.options.nativeTransports["iroh/1"](seedB64, this.settings.irohRelays?.length ? { relays: [...this.settings.irohRelays] } : {}) } : {},
51586
51131
  ...this.options.irohWeb ? { "iroh/1": (seedB64) => createIrohWebEndpoint(seedB64, {
@@ -51734,7 +51279,7 @@ var GhostlyNode = class GhostlyNode {
51734
51279
  */
51735
51280
  reachedOnlyNatively(live) {
51736
51281
  const theirs = live.stored.capsState?.peer?.transports ?? live.stored.peerTransports;
51737
- return typeof RTCPeerConnection === "undefined" || !theirs || !theirs.includes("webrtc/1") || this.directPath.blocked;
51282
+ return !this.contactRtc() || !theirs || !theirs.includes("webrtc/1") || this.directPath.blocked;
51738
51283
  }
51739
51284
  /**
51740
51285
  * When a chat or a group (for one of its edges) was last in use, for handing native listeners out least recently used
@@ -52116,7 +51661,7 @@ var GhostlyNode = class GhostlyNode {
52116
51661
  const stored = this.links.get(id)?.stored;
52117
51662
  return !!stored && !stored.group;
52118
51663
  };
52119
- const rtc = typeof RTCPeerConnection !== "undefined";
51664
+ const rtc = this.contactRtc();
52120
51665
  const rank = new Map(linkIds.filter(isChat).map((id) => {
52121
51666
  const live = this.links.get(id);
52122
51667
  const theirs = live.stored.capsState?.peer?.transports ?? live.stored.peerTransports;
@@ -52467,7 +52012,9 @@ var GhostlyNode = class GhostlyNode {
52467
52012
  if (live?.stored.deletedIds?.includes(message.id)) return false;
52468
52013
  if (message.linkId.startsWith("group:") && this.groups.isRemoved(message.linkId.slice(6), message.id)) return false;
52469
52014
  const first = live ? this.firstContactRow(live, message) : false;
52015
+ const mine = live?.stored.profile && !live.stored.group && message.sender === "peer" && !message.file && message.id.startsWith("peer_") ? this.namesMine(chat, message.id.slice(5)).catch(() => false) : false;
52470
52016
  message = await this.resolveReply(message);
52017
+ if (await mine) return false;
52471
52018
  if (first && isJoinNotice(message.text) && await first) message = {
52472
52019
  ...message,
52473
52020
  joinLine: true
@@ -52704,6 +52251,12 @@ var EngineServer = class {
52704
52251
  * call (WISP 06 § States and events). A client that goes away (a tab closed mid-call) is taken out with it.
52705
52252
  */
52706
52253
  onCall = /* @__PURE__ */ new Set();
52254
+ /**
52255
+ * The clients whose last presence word (`setPresence`) was `active`: the engine hears `idle` only once none is, so a
52256
+ * tab hidden, locked or closed does not tell the contacts the profile is idle while another tab is in use. A client
52257
+ * that goes away is taken out with it.
52258
+ */
52259
+ present = /* @__PURE__ */ new Set();
52707
52260
  /** How many history changes the engine told; per chat or group, the count at its last one (`historyMark`). */
52708
52261
  changes = 0;
52709
52262
  changedAt = /* @__PURE__ */ new Map();
@@ -52836,6 +52389,7 @@ var EngineServer = class {
52836
52389
  this.node.appsCloseAll();
52837
52390
  }
52838
52391
  if (this.onCall.delete(client)) this.node.setCallOn({ on: this.onCall.size > 0 });
52392
+ if (this.present.delete(client) && this.present.size === 0) this.node.setPresence({ presence: "idle" });
52839
52393
  }
52840
52394
  async handle(client, request) {
52841
52395
  if (request?.kind !== "request") return;
@@ -52850,12 +52404,20 @@ var EngineServer = class {
52850
52404
  else this.onCall.delete(client);
52851
52405
  params = { on: this.onCall.size > 0 };
52852
52406
  }
52407
+ let tell = true;
52408
+ if (request.method === "setPresence") {
52409
+ if (request.params?.presence === "active") this.present.add(client);
52410
+ else {
52411
+ this.present.delete(client);
52412
+ tell = this.present.size === 0;
52413
+ }
52414
+ }
52853
52415
  try {
52854
52416
  await (readsGroupHistory(request) ? Promise.race([this.ready, this.node.groupsRead]) : this.ready);
52855
52417
  const method = this.node[request.method];
52856
52418
  if (typeof method !== "function") throw new Error(`Unknown method: ${request.method}`);
52857
52419
  if (this.node.limited && !LIMITED_MODE_METHODS.has(String(request.method))) throw new Error(LIMITED_MODE_ERROR);
52858
- response.result = await method.call(this.node, params);
52420
+ if (tell) response.result = await method.call(this.node, params);
52859
52421
  } catch (error) {
52860
52422
  response.error = errorLine(error);
52861
52423
  }
@@ -53005,4 +52567,4 @@ function signalKind(signal) {
53005
52567
  //#endregion
53006
52568
  export { EngineServer };
53007
52569
 
53008
- //# sourceMappingURL=server-DdtPxkqI.js.map
52570
+ //# sourceMappingURL=server-B6PQ6iae.js.map