@ghostlytools/cli 1.11.3 → 1.12.0

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 (218) hide show
  1. package/README.md +52 -30
  2. package/SKILL.md +4 -2
  3. package/dist/assets/{api-DBlaoz8i.js → api-DLzCtePC.js} +533 -195
  4. package/dist/assets/api-DLzCtePC.js.map +1 -0
  5. package/dist/assets/{api-DgU4MZPD.js → api-DYMKyb1k.js} +2 -2
  6. package/dist/assets/{apiKit-DesObIDf.js → apiKit-CVaEzKWQ.js} +104 -21
  7. package/dist/assets/apiKit-CVaEzKWQ.js.map +1 -0
  8. package/dist/assets/appFetch-D56GsYuq.js +602 -0
  9. package/dist/assets/appFetch-D56GsYuq.js.map +1 -0
  10. package/dist/assets/apps-BPFW19Wc.js +1 -0
  11. package/dist/assets/{apps-DkMjDHML.js → apps-XnZ8VEuj.js} +66 -38
  12. package/dist/assets/apps-XnZ8VEuj.js.map +1 -0
  13. package/dist/assets/{argon2id-088uQfnH.js → argon2id-B9wFdSj6.js} +2 -3
  14. package/dist/assets/{argon2id-088uQfnH.js.map → argon2id-B9wFdSj6.js.map} +1 -1
  15. package/dist/assets/{arkade-CarKONmH.js → arkade-DryM-q5n.js} +6 -7
  16. package/dist/assets/arkade-DryM-q5n.js.map +1 -0
  17. package/dist/assets/backup-COX6j1_W.js +1 -0
  18. package/dist/assets/{backup-C0OJCJlM.js → backup-DpyvT9Z6.js} +108 -50
  19. package/dist/assets/backup-DpyvT9Z6.js.map +1 -0
  20. package/dist/assets/bark_ffi_wasm_bg-CcafsJla.js +5 -0
  21. package/dist/assets/{bark_ffi_wasm_bg-EY2uc0Bx.js.map → bark_ffi_wasm_bg-CcafsJla.js.map} +1 -1
  22. package/dist/assets/{bark_ffi_wasm_bg-Bxru_BVW.wasm → bark_ffi_wasm_bg-VNmaJsc9.wasm} +0 -0
  23. package/dist/assets/{bitcoind-CdSmvy2y.js → bitcoind-DTsrd7TF.js} +4 -5
  24. package/dist/assets/{bitcoind-CdSmvy2y.js.map → bitcoind-DTsrd7TF.js.map} +1 -1
  25. package/dist/assets/bitcoindevkit_bg-BWQHx7vd.js +5 -0
  26. package/dist/assets/{bitcoindevkit_bg-B-iLWrmX.js.map → bitcoindevkit_bg-BWQHx7vd.js.map} +1 -1
  27. package/dist/assets/bitcoindevkit_bg-DXil67yS.wasm +0 -0
  28. package/dist/assets/{blobFiles-BmsrvZc3.js → blobFiles-DDs34n0r.js} +4 -5
  29. package/dist/assets/{blobFiles-BmsrvZc3.js.map → blobFiles-DDs34n0r.js.map} +1 -1
  30. package/dist/assets/breez_sdk_spark_wasm_bg.wasm +0 -0
  31. package/dist/assets/buttons-Bq7pTXqF.js +1 -0
  32. package/dist/assets/{buttons-fZTEa_2i.js → buttons-BvWqHJeh.js} +46 -23
  33. package/dist/assets/buttons-BvWqHJeh.js.map +1 -0
  34. package/dist/assets/bytes-C1DNGY18.js +132 -0
  35. package/dist/assets/bytes-C1DNGY18.js.map +1 -0
  36. package/dist/assets/{childEnv-K_IzUqQx.js → childEnv-C-99hdbL.js} +2 -3
  37. package/dist/assets/{childEnv-K_IzUqQx.js.map → childEnv-C-99hdbL.js.map} +1 -1
  38. package/dist/assets/{client-Ibk3-e60.js → client-kGZ3ZdUW.js} +30 -13
  39. package/dist/assets/client-kGZ3ZdUW.js.map +1 -0
  40. package/dist/assets/{codec-DMpQqVSt.js → codec-B2rH1mfx.js} +2 -4
  41. package/dist/assets/{codec-DMpQqVSt.js.map → codec-B2rH1mfx.js.map} +1 -1
  42. package/dist/assets/domainProofs-BDNP1dIy.js +280 -0
  43. package/dist/assets/domainProofs-BDNP1dIy.js.map +1 -0
  44. package/dist/assets/{endpoint-DarqblYE.js → endpoint-B0vE5ojY.js} +421 -420
  45. package/dist/assets/endpoint-B0vE5ojY.js.map +1 -0
  46. package/dist/assets/engineErrors--9hfgKlK.js +150 -0
  47. package/dist/assets/engineErrors--9hfgKlK.js.map +1 -0
  48. package/dist/assets/{envelope-CvQVCGdf.js → envelope-Bi2kMqbp.js} +3 -4
  49. package/dist/assets/{envelope-CvQVCGdf.js.map → envelope-Bi2kMqbp.js.map} +1 -1
  50. package/dist/assets/{errors-Dt-ZnyOX.js → errors-DDLFO4Gf.js} +31 -5
  51. package/dist/assets/errors-DDLFO4Gf.js.map +1 -0
  52. package/dist/assets/{fedimintSdk-zV_5Qdqz.js → fedimintSdk-D-6H9Pe7.js} +4 -5
  53. package/dist/assets/{fedimintSdk-zV_5Qdqz.js.map → fedimintSdk-D-6H9Pe7.js.map} +1 -1
  54. package/dist/assets/fedimint_client_wasm_bg-Cr5xGD-w.js +5 -0
  55. package/dist/assets/{fedimint_client_wasm_bg-BtHHlFpp.js.map → fedimint_client_wasm_bg-Cr5xGD-w.js.map} +1 -1
  56. package/dist/assets/fileBytes-CCKbwqG_.js +1 -0
  57. package/dist/assets/{fileBytes-BLPZq9YU.js → fileBytes-CfvUXdSy.js} +5 -7
  58. package/dist/assets/fileBytes-CfvUXdSy.js.map +1 -0
  59. package/dist/assets/{fileBytes-B0z9A6Le.js → fileBytes-tj6-VZcB.js} +3 -4
  60. package/dist/assets/{fileBytes-B0z9A6Le.js.map → fileBytes-tj6-VZcB.js.map} +1 -1
  61. package/dist/assets/fileBytesIdb-B0zzJ6p7.js +1 -0
  62. package/dist/assets/{fileBytesIdb-Bmlrl9EO.js → fileBytesIdb-BJirUAjI.js} +4 -5
  63. package/dist/assets/{fileBytesIdb-Bmlrl9EO.js.map → fileBytesIdb-BJirUAjI.js.map} +1 -1
  64. package/dist/assets/{fileBytesOpfs-DBS0kbPT.js → fileBytesOpfs-DRUYLER4.js} +4 -5
  65. package/dist/assets/{fileBytesOpfs-DBS0kbPT.js.map → fileBytesOpfs-DRUYLER4.js.map} +1 -1
  66. package/dist/assets/{fixedHosts-6gKn8dp2.js → fixedHosts-CPSsGOI2.js} +4 -5
  67. package/dist/assets/{fixedHosts-6gKn8dp2.js.map → fixedHosts-CPSsGOI2.js.map} +1 -1
  68. package/dist/assets/{ghostly_iroh_web-BzAXJUYH.js → ghostly_iroh_web-DIj5xGmR.js} +2 -3
  69. package/dist/assets/{ghostly_iroh_web-BzAXJUYH.js.map → ghostly_iroh_web-DIj5xGmR.js.map} +1 -1
  70. package/dist/assets/{src-DjVj2ynY.js → groupMeta-DTQAJG50.js} +4879 -23799
  71. package/dist/assets/groupMeta-DTQAJG50.js.map +1 -0
  72. package/dist/assets/{host-CYlIiY3r.js → host-z0FAHP9Z.js} +750 -245
  73. package/dist/assets/host-z0FAHP9Z.js.map +1 -0
  74. package/dist/assets/{hyperdhtRelay-CdsLcAhY.js → hyperdhtRelay-CvsAfQRQ.js} +5 -6
  75. package/dist/assets/hyperdhtRelay-CvsAfQRQ.js.map +1 -0
  76. package/dist/assets/hyperdhtRelay-bjNGacf5.js +32 -0
  77. package/dist/assets/hyperdhtRelay-bjNGacf5.js.map +1 -0
  78. package/dist/assets/{idb-CEuoNsTv.js → idb-ewvbqyDI.js} +2 -3
  79. package/dist/assets/{idb-CEuoNsTv.js.map → idb-ewvbqyDI.js.map} +1 -1
  80. package/dist/assets/identityProofs-Cksc_K7_.js +940 -0
  81. package/dist/assets/identityProofs-Cksc_K7_.js.map +1 -0
  82. package/dist/assets/{irohWeb-D2IuloLL.js → irohWeb-CLBx5MIv.js} +3061 -86
  83. package/dist/assets/irohWeb-CLBx5MIv.js.map +1 -0
  84. package/dist/assets/joinTrace-CBr1jbch.js +1 -0
  85. package/dist/assets/{joinTrace-CjRDFy85.js → joinTrace-xKBe73j9.js} +2 -3
  86. package/dist/assets/{joinTrace-CjRDFy85.js.map → joinTrace-xKBe73j9.js.map} +1 -1
  87. package/dist/assets/{legacy_ciphers-JJOu0JXL.js → legacy_ciphers-BnYATjxo.js} +2 -3
  88. package/dist/assets/{legacy_ciphers-JJOu0JXL.js.map → legacy_ciphers-BnYATjxo.js.map} +1 -1
  89. package/dist/assets/linkPreview-DdMf-YAc.js +252 -0
  90. package/dist/assets/linkPreview-DdMf-YAc.js.map +1 -0
  91. package/dist/assets/{main-C0PfjKTe.js → main-CVqkvuIo.js} +536 -173
  92. package/dist/assets/main-CVqkvuIo.js.map +1 -0
  93. package/dist/assets/{mainline-Cu61qcPS.js → mainline-CVrd0C1n.js} +72 -18
  94. package/dist/assets/mainline-CVrd0C1n.js.map +1 -0
  95. package/dist/assets/mints-BcBODVVW.js +1 -0
  96. package/dist/assets/{mints-j5XAOk4f.js → mints-CMDLbMeH.js} +8 -6
  97. package/dist/assets/mints-CMDLbMeH.js.map +1 -0
  98. package/dist/assets/{nacl-fast-CDhNCYHs.js → nacl-fast-B1ThWvuM.js} +2 -3
  99. package/dist/assets/{nacl-fast-CDhNCYHs.js.map → nacl-fast-B1ThWvuM.js.map} +1 -1
  100. package/dist/assets/{networkReason-Dt7Yx_n4.js → networkReason-Be-hMghr.js} +10 -14
  101. package/dist/assets/{networkReason-Dt7Yx_n4.js.map → networkReason-Be-hMghr.js.map} +1 -1
  102. package/dist/assets/{noble_curves-DDWn5AH0.js → noble_curves-DqpNlhAU.js} +3 -4
  103. package/dist/assets/{noble_curves-DDWn5AH0.js.map → noble_curves-DqpNlhAU.js.map} +1 -1
  104. package/dist/assets/{noble_hashes-B7AZyFyS.js → noble_hashes-LFe1N2xt.js} +3 -4
  105. package/dist/assets/{noble_hashes-B7AZyFyS.js.map → noble_hashes-LFe1N2xt.js.map} +1 -1
  106. package/dist/assets/{nwc-CtZypDcv.js → nwc-DKE2FXr6.js} +5 -6
  107. package/dist/assets/{nwc-CtZypDcv.js.map → nwc-DKE2FXr6.js.map} +1 -1
  108. package/dist/assets/nwcProvider-pL2XqSbW.js +208 -0
  109. package/dist/assets/nwcProvider-pL2XqSbW.js.map +1 -0
  110. package/dist/assets/{openpgp-BBFr-zHQ.js → openpgp-LkR_Zof0.js} +14 -15
  111. package/dist/assets/{openpgp-BBFr-zHQ.js.map → openpgp-LkR_Zof0.js.map} +1 -1
  112. package/dist/assets/ownDid-DY3rYqDI.js +862 -0
  113. package/dist/assets/ownDid-DY3rYqDI.js.map +1 -0
  114. package/dist/assets/{ownStatus-D4HC6tNR.js → ownStatus-DMEhrpkd.js} +81 -19
  115. package/dist/assets/ownStatus-DMEhrpkd.js.map +1 -0
  116. package/dist/assets/pairedTransports-BKmvlKz1.js +581 -0
  117. package/dist/assets/pairedTransports-BKmvlKz1.js.map +1 -0
  118. package/dist/assets/paymentIntent-DySU3Ajm.js +349 -0
  119. package/dist/assets/paymentIntent-DySU3Ajm.js.map +1 -0
  120. package/dist/assets/pkarr-BQo4PcCg.js +367 -0
  121. package/dist/assets/pkarr-BQo4PcCg.js.map +1 -0
  122. package/dist/assets/{profiles-Ccdq6Xf6.js → profiles-BFSGqDFC.js} +30 -16
  123. package/dist/assets/profiles-BFSGqDFC.js.map +1 -0
  124. package/dist/assets/registry-B15Yg_1C.js +1 -0
  125. package/dist/assets/{registry-LvxsLJ5S.js → registry-rXgaZeNn.js} +1273 -58
  126. package/dist/assets/registry-rXgaZeNn.js.map +1 -0
  127. package/dist/assets/relay-Cjfmdec0.js +2219 -0
  128. package/dist/assets/relay-Cjfmdec0.js.map +1 -0
  129. package/dist/assets/resolve-CIc3KZMV.js +970 -0
  130. package/dist/assets/resolve-CIc3KZMV.js.map +1 -0
  131. package/dist/assets/{restoredRows-C3LcxmOw.js → restoredRows-D_WSHE7H.js} +3 -4
  132. package/dist/assets/{restoredRows-C3LcxmOw.js.map → restoredRows-D_WSHE7H.js.map} +1 -1
  133. package/dist/assets/{secretGuard-B7Hj0Kvz.js → secretGuard-B4-LlMjv.js} +75 -16
  134. package/dist/assets/{secretGuard-B7Hj0Kvz.js.map → secretGuard-B4-LlMjv.js.map} +1 -1
  135. package/dist/assets/secretGuard-BmmnEbYf.js +1 -0
  136. package/dist/assets/{server-Q3VcNqGt.js → server-CQR7NLCz.js} +10200 -625
  137. package/dist/assets/server-CQR7NLCz.js.map +1 -0
  138. package/dist/assets/{sha512-BYId-G-T.js → sha512-DST9fbWH.js} +2 -3
  139. package/dist/assets/{sha512-BYId-G-T.js.map → sha512-DST9fbWH.js.map} +1 -1
  140. package/dist/assets/sshForges-BnvwmNj-.js +539 -0
  141. package/dist/assets/sshForges-BnvwmNj-.js.map +1 -0
  142. package/dist/assets/{storage-Bya5b2Xt.js → storage-BpjdxvO2.js} +243 -34
  143. package/dist/assets/storage-BpjdxvO2.js.map +1 -0
  144. package/dist/assets/text-li76pThX.js +106 -0
  145. package/dist/assets/text-li76pThX.js.map +1 -0
  146. package/dist/assets/{translate-iQZq4TnY.js → translate-BcbSWkuq.js} +21 -26
  147. package/dist/assets/{translate-iQZq4TnY.js.map → translate-BcbSWkuq.js.map} +1 -1
  148. package/dist/assets/{tree-store-N362nuzZ.js → tree-store-CAchkO_l.js} +22 -6
  149. package/dist/assets/tree-store-CAchkO_l.js.map +1 -0
  150. package/dist/assets/{types-Clyb52K2.js → types-CdWwgvyt.js} +2 -3
  151. package/dist/assets/{types-Clyb52K2.js.map → types-CdWwgvyt.js.map} +1 -1
  152. package/dist/assets/{unbzip2-stream-B1C-JX9L.js → unbzip2-stream-BtkYGpC5.js} +2 -3
  153. package/dist/assets/{unbzip2-stream-B1C-JX9L.js.map → unbzip2-stream-BtkYGpC5.js.map} +1 -1
  154. package/dist/assets/{usdt-DnyTGdTX.js → usdt-CBJ4Q5Ji.js} +7 -7
  155. package/dist/assets/usdt-CBJ4Q5Ji.js.map +1 -0
  156. package/dist/assets/{waitNotice-Cn0WJ-He.js → waitNotice-BGM0QOS2.js} +27 -4
  157. package/dist/assets/waitNotice-BGM0QOS2.js.map +1 -0
  158. package/dist/assets/{web-DwgdhfcY.js → web-68CYFCl9.js} +314 -91
  159. package/dist/assets/web-68CYFCl9.js.map +1 -0
  160. package/dist/ghostly.mjs +3 -5
  161. package/dist/ghostly.mjs.map +1 -1
  162. package/npm-shrinkwrap.json +225 -200
  163. package/package.json +16 -16
  164. package/dist/assets/api-DBlaoz8i.js.map +0 -1
  165. package/dist/assets/apiKit-DesObIDf.js.map +0 -1
  166. package/dist/assets/appFetch-C8yZIq1e.js +0 -194
  167. package/dist/assets/appFetch-C8yZIq1e.js.map +0 -1
  168. package/dist/assets/apps-DkMjDHML.js.map +0 -1
  169. package/dist/assets/apps-rzxsjfBV.js +0 -2
  170. package/dist/assets/arkade-CarKONmH.js.map +0 -1
  171. package/dist/assets/backup-C0OJCJlM.js.map +0 -1
  172. package/dist/assets/backup-CgWU7x0T.js +0 -2
  173. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js +0 -6
  174. package/dist/assets/bitcoindProvider-BvoRh0D5.js +0 -97
  175. package/dist/assets/bitcoindProvider-BvoRh0D5.js.map +0 -1
  176. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js +0 -6
  177. package/dist/assets/bitcoindevkit_bg-CRkZTSbO.wasm +0 -0
  178. package/dist/assets/buttons-Cco0Agfa.js +0 -2
  179. package/dist/assets/buttons-fZTEa_2i.js.map +0 -1
  180. package/dist/assets/client-Ibk3-e60.js.map +0 -1
  181. package/dist/assets/endpoint-DarqblYE.js.map +0 -1
  182. package/dist/assets/errors-Dt-ZnyOX.js.map +0 -1
  183. package/dist/assets/fedimint_client_wasm_bg-BtHHlFpp.js +0 -6
  184. package/dist/assets/fileBytes-BLPZq9YU.js.map +0 -1
  185. package/dist/assets/fileBytes-BtIyoDF2.js +0 -2
  186. package/dist/assets/fileBytesIdb-D8mAK4pF.js +0 -2
  187. package/dist/assets/host-CYlIiY3r.js.map +0 -1
  188. package/dist/assets/hyperdhtRelay-1wzya_0L.js +0 -25
  189. package/dist/assets/hyperdhtRelay-1wzya_0L.js.map +0 -1
  190. package/dist/assets/hyperdhtRelay-CdsLcAhY.js.map +0 -1
  191. package/dist/assets/irohWeb-D2IuloLL.js.map +0 -1
  192. package/dist/assets/joinTrace-D-fnt2p3.js +0 -2
  193. package/dist/assets/jsonOut-POtMBS_V.js +0 -16
  194. package/dist/assets/jsonOut-POtMBS_V.js.map +0 -1
  195. package/dist/assets/main-C0PfjKTe.js.map +0 -1
  196. package/dist/assets/mainline-Cu61qcPS.js.map +0 -1
  197. package/dist/assets/mints-BaOmx517.js +0 -2
  198. package/dist/assets/mints-j5XAOk4f.js.map +0 -1
  199. package/dist/assets/nwcProvider-DYHkd0iu.js +0 -88
  200. package/dist/assets/nwcProvider-DYHkd0iu.js.map +0 -1
  201. package/dist/assets/ownDid-CJ0ta8CL.js +0 -282
  202. package/dist/assets/ownDid-CJ0ta8CL.js.map +0 -1
  203. package/dist/assets/ownStatus-D4HC6tNR.js.map +0 -1
  204. package/dist/assets/profiles-Ccdq6Xf6.js.map +0 -1
  205. package/dist/assets/registry-CE0PpQAE.js +0 -2
  206. package/dist/assets/registry-LvxsLJ5S.js.map +0 -1
  207. package/dist/assets/resolve-6kVu2DE5.js +0 -400
  208. package/dist/assets/resolve-6kVu2DE5.js.map +0 -1
  209. package/dist/assets/secretGuard-DUr6bgKc.js +0 -2
  210. package/dist/assets/server-Q3VcNqGt.js.map +0 -1
  211. package/dist/assets/src-DjVj2ynY.js.map +0 -1
  212. package/dist/assets/sshForges-DeZ9cN9Q.js +0 -261
  213. package/dist/assets/sshForges-DeZ9cN9Q.js.map +0 -1
  214. package/dist/assets/storage-Bya5b2Xt.js.map +0 -1
  215. package/dist/assets/tree-store-N362nuzZ.js.map +0 -1
  216. package/dist/assets/usdt-DnyTGdTX.js.map +0 -1
  217. package/dist/assets/waitNotice-Cn0WJ-He.js.map +0 -1
  218. package/dist/assets/web-DwgdhfcY.js.map +0 -1
@@ -1,30 +1,35 @@
1
- import { $r as STATUS_IDLE_AFTER_MS, As as buildSdpFromSignal, Es as CALL_SIGNAL_MAX_AGE_MS, Fs as parseCallSignal, Is as signalHasVideo, Ms as callSignalHeardAt, Na as ACTIVE_DHT_POLL_MS, Os as RTC_CONFIG, Ps as extractParamsFromSdp, Ta as isPublicAddress, Ti as checkPushEndpoint, Yu as setLinkTraceSink, bd as fromBase64Url, dd as setPublicKeyFastPath, ds as DAEMON_WATCH_PEER_IDLE_MS, js as callRtcConfig, ks as answersOffer } from "./src-DjVj2ynY.js";
2
- import { p as fileStore } from "./idb-CEuoNsTv.js";
3
- import { r as irohRelayProblem } from "./irohWeb-D2IuloLL.js";
4
- import { n as fedimintSdkOn } from "./fedimintSdk-zV_5Qdqz.js";
5
- import { r as asCliError, t as CliError } from "./errors-Dt-ZnyOX.js";
6
- import { A as sinceSeq, s as findChat, u as findOwnNamedChat } from "./apiKit-DesObIDf.js";
7
- import { _ as groupPayTwins, d as servedApps, f as nodeLocalFetch, g as groupMessageJson, h as groupJson, l as paymentJson, m as chatMessageJson, p as chatJson, r as callApi, u as reportAppFrames, v as resumeHolds, y as flushCardUpdates } from "./api-DBlaoz8i.js";
8
- import { C as ownProfile, E as runtimePath, S as ownFolder, T as privateFolder, b as startingPath, n as RESTORED_MARK, r as acquireLock } from "./profiles-Ccdq6Xf6.js";
9
- import { p as nativePublicKey } from "./apps-DkMjDHML.js";
10
- import { _ as frameSamples, c as greeting, d as removeDaemonSecret, g as frameBytes, h as bytesToMs, l as newDaemonSecret, m as PlaybackQueue, p as DEFAULT_RATE, u as proof, v as isCallRate, y as monotonic } from "./client-Ibk3-e60.js";
1
+ import { p as fileStore } from "./idb-ewvbqyDI.js";
2
+ import { _ as groupPayTwins, d as servedApps, f as nodeLocalFetch, g as groupMessageJson, h as groupJson, l as paymentJson, m as chatMessageJson, p as chatJson, r as callApi, u as reportAppFrames, v as resumeHolds, y as flushCardUpdates } from "./api-DLzCtePC.js";
3
+ import { N as sinceSeq, s as findChat, u as findOwnNamedChat } from "./apiKit-CVaEzKWQ.js";
4
+ import { r as asCliError, t as CliError } from "./errors-DDLFO4Gf.js";
5
+ import { C as ownFolder, D as runtimePath, E as privateFolder, n as RESTORED_MARK, r as acquireLock, w as ownProfile, x as startingPath } from "./profiles-BFSGqDFC.js";
6
+ import { _ as frameBytes, b as monotonic, d as proof, f as removeDaemonSecret, g as bytesToMs, h as PlaybackQueue, l as greeting, m as DEFAULT_RATE, u as newDaemonSecret, v as frameSamples, y as isCallRate } from "./client-kGZ3ZdUW.js";
7
+ import { Bi as callRtcConfig, Fi as CALL_SIGNAL_MAX_AGE_MS, Gi as signalHasVideo, Li as RTC_CONFIG, Ri as answersOffer, Ui as extractParamsFromSdp, Vi as callSignalHeardAt, Wi as parseCallSignal, Zt as checkPushEndpoint, bi as DAEMON_WATCH_PEER_IDLE_MS, gn as ACTIVE_DHT_POLL_MS, xt as STATUS_IDLE_AFTER_MS, zi as buildSdpFromSignal } from "./groupMeta-DTQAJG50.js";
8
+ import { d as parsePayLink, r as irohRelayProblem } from "./irohWeb-CLBx5MIv.js";
9
+ import { i as fromBase64Url } from "./bytes-C1DNGY18.js";
10
+ import { u as setLinkTraceSink } from "./relay-Cjfmdec0.js";
11
+ import { b as setPublicKeyFastPath } from "./pkarr-BQo4PcCg.js";
12
+ import { p as nativePublicKey } from "./apps-XnZ8VEuj.js";
13
+ import { n as fedimintSdkOn } from "./fedimintSdk-D-6H9Pe7.js";
14
+ import { s as isPublicAddress } from "./domainProofs-BDNP1dIy.js";
11
15
  import { createRequire } from "node:module";
12
16
  import { appendFileSync, chmodSync, closeSync, existsSync, fstatSync, fsync, fsyncSync, ftruncateSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, truncateSync, writeFileSync, writeSync } from "node:fs";
13
17
  import { open, readFile } from "node:fs/promises";
14
- import { dirname, join } from "node:path";
18
+ import { dirname, isAbsolute, join, resolve } from "node:path";
15
19
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
16
20
  import { networkInterfaces } from "node:os";
17
21
  import { Readable } from "node:stream";
18
- import { createServer, isIP } from "node:net";
22
+ import { connect, createServer, isIP } from "node:net";
19
23
  import { createInterface } from "node:readline";
24
+ import { createSocket } from "node:dgram";
20
25
  import { fileURLToPath, pathToFileURL } from "node:url";
21
26
  import { Worker } from "node:worker_threads";
22
27
  import { request } from "node:https";
23
28
  import { lookup } from "node:dns";
24
29
  import { WebSocket } from "ws";
25
- import { deserialize, serialize } from "node:v8";
26
- import { IDBFactory, IDBKeyRange, IDBTransaction } from "fake-indexeddb";
27
- //#region src/announce.ts
30
+ import { DefaultSerializer, deserialize, serialize } from "node:v8";
31
+ import { IDBFactory, IDBKeyRange as IDBKeyRange$1, IDBTransaction } from "fake-indexeddb";
32
+ // src/announce.ts
28
33
  /**
29
34
  * What the app's chat screen does by itself, done here for a profile no screen shows (apps/ui/src/hooks/useChat.ts): the side
30
35
  * that joined says "👋 <name> joined" once the chat first goes live, and the side that invited answers once. Contacts
@@ -34,7 +39,7 @@ function announceJoins(hub, node) {
34
39
  const say = (chat) => {
35
40
  if (hub.said(chat, "join")) return;
36
41
  hub.markSaid(chat, "join");
37
- const nick = node.getState().settings.nick?.trim();
42
+ const nick = node.getSettings().nick?.trim();
38
43
  node.sendMessage({
39
44
  linkId: chat,
40
45
  text: nick ? `👋 ${nick} joined` : "👋 joined"
@@ -50,33 +55,89 @@ function announceJoins(hub, node) {
50
55
  else if (event.type === "chat.joined") say(chat);
51
56
  });
52
57
  }
53
- //#endregion
54
- //#region src/calls/audioSocket.ts
58
+ // src/calls/audioSocket.ts
55
59
  /**
56
60
  * A call's audio socket (WISP 1100 § Calls): `<profile>/calls/<call>.sock`, 0600, in a folder only the owner may
57
61
  * open. When that path is too long for a Unix socket: `ghostly-calls-<hash of the profile>/<call>.sock` in the user's
58
62
  * runtime folder (`runtimePath`), a folder of the owner's, 0700, checked as such before use. A named pipe on Windows.
63
+ * With a shared folder (`callSocketDir`): `<that folder>/<call>.sock`.
59
64
  */
60
- function audioSocketPath(profileDir, callId) {
65
+ function audioSocketPath(profileDir, callId, sharedDir) {
66
+ if (sharedDir && process.platform !== "win32") return join(sharedDir, `${callId}.sock`);
61
67
  const inside = join(profileDir, "calls", `${callId}.sock`);
62
68
  if (process.platform === "win32") return `\\\\.\\pipe\\ghostly-call-${createHash("sha256").update(inside).digest("hex").slice(0, 24)}`;
63
69
  if (Buffer.byteLength(inside) <= 100) return inside;
64
70
  return runtimePath("ghostly-calls", profileDir, `${callId}.sock`);
65
71
  }
66
72
  /**
73
+ * GHOSTLY_CALL_SOCKET_DIR: a folder the machine made for its daemon's call sockets, shared with the group of another
74
+ * user that runs the program on the audio (a Ghostly OS node's assistant). Unset: the profile's own folder. Refused
75
+ * (`usage`) when it is not an absolute path, is too long for a socket's, or on Windows, whose calls are named pipes.
76
+ */
77
+ function callSocketDir(value = process.env.GHOSTLY_CALL_SOCKET_DIR) {
78
+ if (value === void 0) return void 0;
79
+ if (process.platform === "win32") throw new CliError("usage", "GHOSTLY_CALL_SOCKET_DIR is for Linux and macOS: on Windows a call's audio is a named pipe");
80
+ if (!value.trim() || !isAbsolute(value)) throw new CliError("usage", "GHOSTLY_CALL_SOCKET_DIR takes an absolute path: the folder for the calls' audio sockets");
81
+ const dir = resolve(value);
82
+ if (Buffer.byteLength(join(dir, `${"0".repeat(12)}.sock`)) > 100) throw new CliError("usage", `GHOSTLY_CALL_SOCKET_DIR is too long for a socket's path (${dir}): choose a folder of at most 82 bytes`);
83
+ return dir;
84
+ }
85
+ /**
86
+ * The shared folder (`callSocketDir`), checked before a socket goes in it: the machine made it, so it is not made here.
87
+ * Refused when it is missing, a link, someone else's, or when anyone else may write it (and so replace a socket) or
88
+ * anyone outside its group may enter it: 0750, its group the other user's (setgid, so the sockets take that group).
89
+ * Refused too on Linux when its group is not this user's own and it is not setgid: a socket there takes this user's
90
+ * group, not the folder's, and the other user's program could never open one.
91
+ */
92
+ function sharedFolder(path) {
93
+ const what = "calls will not put their audio there";
94
+ let info;
95
+ try {
96
+ info = lstatSync(path);
97
+ } catch {
98
+ throw new CliError("refused", `${path} (GHOSTLY_CALL_SOCKET_DIR) is not there: ${what}. Make it a folder of this user's, 0750 with the group that reads the audio (chmod 2750)`);
99
+ }
100
+ if (!info.isDirectory() || process.getuid && info.uid !== process.getuid()) throw new CliError("refused", `${path} (GHOSTLY_CALL_SOCKET_DIR) is not a folder of this user's: ${what}`);
101
+ if ((info.mode & 23) !== 0) throw new CliError("refused", `${path} (GHOSTLY_CALL_SOCKET_DIR) may be written by others or entered by anyone outside its group: ${what}. Run \`chmod 2750 ${path}\`, then try again`);
102
+ if (process.platform === "linux" && process.getegid && info.gid !== process.getegid() && (info.mode & 1024) === 0) throw new CliError("refused", `${path} (GHOSTLY_CALL_SOCKET_DIR) is not setgid: a call's socket there would take this user's group, not the folder's, and its group could not open it. Run \`chmod 2750 ${path}\`, then try again`);
103
+ }
104
+ /** A call's socket's name: its call id, 12 hex digits. */
105
+ var CALL_SOCKET = /^[0-9a-f]{12}\.sock$/;
106
+ /**
67
107
  * Removes the call sockets a daemon that died during a call left in this profile's folder (`audioSocketPath`; call
68
- * ids are 12 hex digits): no call outlives its daemon. A folder that is a link or someone else's is left alone.
108
+ * ids are 12 hex digits), or in the shared folder: no call outlives its daemon. A folder that is a link or someone
109
+ * else's is left alone, and so is anything else in it: the shared folder is the machine's, not Ghostly's alone. There a
110
+ * socket goes only once nobody answers on it (`removeIfDead`): two profiles' daemons may share the folder, and the
111
+ * other one's call is live.
69
112
  */
70
- function clearAudioSockets(profileDir) {
113
+ function clearAudioSockets(profileDir, sharedDir) {
71
114
  if (process.platform === "win32") return;
72
- const folder = dirname(audioSocketPath(profileDir, "0".repeat(12)));
115
+ const folder = dirname(audioSocketPath(profileDir, "0".repeat(12), sharedDir));
73
116
  try {
74
117
  const info = lstatSync(folder);
75
118
  if (!info.isDirectory() || process.getuid && info.uid !== process.getuid()) return;
76
- for (const entry of readdirSync(folder, { withFileTypes: true })) if (entry.name.endsWith(".sock") && !entry.isDirectory()) rmSync(join(folder, entry.name), { force: true });
119
+ for (const entry of readdirSync(folder, { withFileTypes: true })) {
120
+ if (!CALL_SOCKET.test(entry.name) || entry.isDirectory()) continue;
121
+ if (sharedDir && entry.isSocket()) removeIfDead(join(folder, entry.name));
122
+ else rmSync(join(folder, entry.name), { force: true });
123
+ }
77
124
  } catch {}
78
125
  }
79
126
  /**
127
+ * Removes a shared folder's call socket once a connection to it is refused: its daemon is gone. A live one is another
128
+ * daemon's call, and the connection (which sends no token) replaces nobody there and is closed at once.
129
+ */
130
+ function removeIfDead(path) {
131
+ const probe = connect(path);
132
+ probe.once("connect", () => probe.destroy());
133
+ probe.once("error", (error) => {
134
+ if (error.code !== "ECONNREFUSED") return;
135
+ try {
136
+ rmSync(path, { force: true });
137
+ } catch {}
138
+ });
139
+ }
140
+ /**
80
141
  * The socket's handlers for a call's queue: what the program writes is queued, and a program that takes the socket
81
142
  * (the first, or one that replaces the last) starts on a queue of its own (`PlaybackQueue.newWriter`): the last
82
143
  * one's leftover, half a sample included, would otherwise shift all of its audio by a byte.
@@ -101,6 +162,7 @@ function feedQueue(queue) {
101
162
  * of the machine may open and read), a connection is nobody's until it has: it hears nothing and replaces nobody, it is
102
163
  * closed when what it sent is not the token, and when `proveMs` pass without it. On an owner-only Unix socket the token
103
164
  * is optional: a connection is the program at once, and a token line it sends first is kept out of the call's audio.
165
+ * `shared`: the socket is in the shared folder (`sharedFolder`), 0660 for its group, and the token is required.
104
166
  */
105
167
  var AudioSocket = class AudioSocket {
106
168
  path;
@@ -123,8 +185,10 @@ var AudioSocket = class AudioSocket {
123
185
  this.proveMs = proveMs;
124
186
  }
125
187
  static async open(path, rate, handlers, options = {}) {
188
+ const shared = !!options.shared && process.platform !== "win32";
126
189
  if (process.platform !== "win32") {
127
- privateFolder(join(path, ".."), "calls will not put their audio there");
190
+ if (shared) sharedFolder(dirname(path));
191
+ else privateFolder(join(path, ".."), "calls will not put their audio there");
128
192
  if (existsSync(path)) rmSync(path, { force: true });
129
193
  }
130
194
  let self = null;
@@ -136,8 +200,8 @@ var AudioSocket = class AudioSocket {
136
200
  resolve();
137
201
  });
138
202
  });
139
- if (process.platform !== "win32") chmodSync(path, 384);
140
- self = new AudioSocket(path, server, rate, options.requireToken ?? process.platform === "win32", options.proveMs ?? 5e3);
203
+ if (process.platform !== "win32") chmodSync(path, shared ? 432 : 384);
204
+ self = new AudioSocket(path, server, rate, options.requireToken ?? (shared || process.platform === "win32"), options.proveMs ?? 5e3);
141
205
  return self;
142
206
  }
143
207
  get connected() {
@@ -333,8 +397,7 @@ var ReorderBuffer = class {
333
397
  }
334
398
  }
335
399
  };
336
- //#endregion
337
- //#region src/calls/audio.ts
400
+ // src/calls/audio.ts
338
401
  /** The longest stall of the sender whose frames are still sent after it (see `catchUp`). */
339
402
  var MAX_CATCH_UP_MS = 1e3;
340
403
  /**
@@ -580,8 +643,7 @@ var CallAudio = class {
580
643
  this.owed -= this.queue.skip(Math.min(this.owed, this.queue.queuedMs - this.kept));
581
644
  }
582
645
  };
583
- //#endregion
584
- //#region src/envSwitch.ts
646
+ // src/envSwitch.ts
585
647
  var OFF = /^(0|false|off|no)$/i;
586
648
  var ON = /^(1|true|on|yes)$/i;
587
649
  /**
@@ -598,8 +660,57 @@ function envSwitch(name, fallback, env = process.env) {
598
660
  if (ON.test(value.trim())) return true;
599
661
  throw new CliError("usage", `${name} takes 0 or 1 (or false/true, off/on, no/yes), not ${JSON.stringify(value)}`);
600
662
  }
601
- //#endregion
602
- //#region src/calls/media.ts
663
+ // src/runtime/rtcThreads.ts
664
+ /**
665
+ * How long no WebRTC connection is open before libdatachannel's threads are let go. For tests,
666
+ * `GHOSTLY_TEST_RTC_IDLE_MS=<ms>` sets it.
667
+ */
668
+ var RTC_IDLE_MS = Number(process.env.GHOSTLY_TEST_RTC_IDLE_MS) || 6e4;
669
+ /**
670
+ * libdatachannel's threads (usrsctp's timer, a tick every 10 ms, and a pool of a thread per core) start with the
671
+ * process's first WebRTC connection and stay for its life, every connection closed or not: a daemon whose contacts all
672
+ * went away woke about 100 times a second for good. Every connection made here (a chat's data link, a call's) is
673
+ * counted from its making to its close; once none has been open for `idleMs`, node-datachannel's `cleanup()` lets them
674
+ * go, and the next connection starts them again. `cleanup()` closes every connection there is: it runs only with none
675
+ * open, checked again once it has been loaded.
676
+ */
677
+ var RtcThreads = class {
678
+ cleanup;
679
+ idleMs;
680
+ open = 0;
681
+ timer;
682
+ constructor(cleanup, idleMs = RTC_IDLE_MS) {
683
+ this.cleanup = cleanup;
684
+ this.idleMs = idleMs;
685
+ }
686
+ /** No connection is open. */
687
+ get idle() {
688
+ return this.open === 0;
689
+ }
690
+ /** A connection made: what to call once it is closed (once; more calls do nothing). */
691
+ opened() {
692
+ this.open++;
693
+ clearTimeout(this.timer);
694
+ this.timer = void 0;
695
+ let closed = false;
696
+ return () => {
697
+ if (closed) return;
698
+ closed = true;
699
+ if (--this.open > 0) return;
700
+ this.timer = setTimeout(() => {
701
+ this.timer = void 0;
702
+ if (this.open === 0) Promise.resolve(this.cleanup()).catch(() => {});
703
+ }, this.idleMs);
704
+ this.timer.unref?.();
705
+ };
706
+ }
707
+ };
708
+ /** The process's one count: the chats' connections and the calls' share libdatachannel's threads. */
709
+ var rtcThreads = new RtcThreads(async () => {
710
+ const ndc = await import("node-datachannel");
711
+ if (rtcThreads.idle) (ndc.cleanup ?? ndc.default.cleanup)();
712
+ });
713
+ // src/calls/media.ts
603
714
  var loading = null;
604
715
  var OPUS_APPLICATION_VOIP = 2048;
605
716
  var OPUS_SET_BITRATE = 4002;
@@ -666,6 +777,8 @@ function loadCallStack() {
666
777
  } catch (error) {
667
778
  return error.message;
668
779
  }
780
+ const bind = process.env.GHOSTLY_CALL_BIND;
781
+ if (bind && !isIP(bind)) return isIP(bind.trim().replace(/^\[(.*)\]$/, "$1")) ? "Calls are off on this headless Ghostly: GHOSTLY_CALL_BIND takes an IP address of this machine without brackets or spaces, such as 127.0.0.1 or ::1" : "Calls are off on this headless Ghostly: GHOSTLY_CALL_BIND takes an IP address of this machine, such as 127.0.0.1, not a name";
669
782
  try {
670
783
  const ndc = await import("node-datachannel");
671
784
  const lib = ndc.PeerConnection ? ndc : ndc.default;
@@ -729,6 +842,29 @@ var SETTLE_MS = 150;
729
842
  * `OFFER_HOST_GATHER_MS`).
730
843
  */
731
844
  var HOST_GATHER_MS = 2e3;
845
+ /** Not echoed: the address may be one of this network's. */
846
+ var CALL_BIND_GONE = "Calls can't start: GHOSTLY_CALL_BIND is not an address of this machine now (a typo, or a network that changed). Set it to one of this machine's addresses, such as 127.0.0.1, or unset it, then restart the daemon";
847
+ /**
848
+ * Whether a socket can be bound on `address` now. On an address that is not this machine's (a typo, a network that
849
+ * changed since the daemon started), libdatachannel gathers no candidate and throws from an offer's description where
850
+ * node-datachannel catches nothing: the whole daemon aborted, every chat with it.
851
+ */
852
+ async function bindable(address) {
853
+ const socket = createSocket(isIP(address) === 6 ? "udp6" : "udp4");
854
+ try {
855
+ await new Promise((bound, failed) => {
856
+ socket.once("error", failed);
857
+ socket.bind(0, address, () => bound());
858
+ });
859
+ return true;
860
+ } catch {
861
+ return false;
862
+ } finally {
863
+ try {
864
+ socket.close();
865
+ } catch {}
866
+ }
867
+ }
732
868
  /**
733
869
  * A connection and its description, with its candidates. An early answer's (`held`) takes the contact's offer
734
870
  * without its candidates: with none, this side sends the contact no check, so nothing connects, and no audio is sent
@@ -737,11 +873,13 @@ var HOST_GATHER_MS = 2e3;
737
873
  async function openConnection(stack, options, offer, held = false) {
738
874
  const { ndc } = stack;
739
875
  const bind = process.env.GHOSTLY_CALL_BIND;
876
+ if (bind && !await bindable(bind)) throw new CliError("unavailable", CALL_BIND_GONE);
740
877
  const iceServers = callIceServers(options.iceServers);
741
878
  const pc = new ndc.PeerConnection("ghostly-call", {
742
879
  iceServers,
743
880
  ...bind ? { bindAddress: bind } : {}
744
881
  });
882
+ const released = rtcThreads.opened();
745
883
  const born = Date.now();
746
884
  const sink = options.log ?? (() => {});
747
885
  const log = (line) => sink(`+${Date.now() - born}ms ${line}`);
@@ -817,7 +955,8 @@ async function openConnection(stack, options, offer, held = false) {
817
955
  },
818
956
  closed: false,
819
957
  failed: false,
820
- onState: null
958
+ onState: null,
959
+ released
821
960
  };
822
961
  log(`candidates here: ${(local.c ?? []).join(" | ") || "none"}`);
823
962
  try {
@@ -825,7 +964,11 @@ async function openConnection(stack, options, offer, held = false) {
825
964
  } catch {}
826
965
  return conn;
827
966
  } catch (error) {
828
- pc.close();
967
+ try {
968
+ pc.close();
969
+ } finally {
970
+ released();
971
+ }
829
972
  throw error;
830
973
  }
831
974
  }
@@ -840,6 +983,7 @@ function closeConnection(conn) {
840
983
  try {
841
984
  conn.pc.close();
842
985
  } catch {}
986
+ conn.released();
843
987
  }
844
988
  /**
845
989
  * The answer's connection, made while the call rings: its description and candidates are ready when the call is
@@ -915,9 +1059,7 @@ var CallMedia = class CallMedia {
915
1059
  payloadType: conn.payloadType,
916
1060
  ssrc: conn.ssrc,
917
1061
  track: {
918
- send: (packet) => {
919
- if (track.isOpen()) track.sendMessageBinary(packet);
920
- },
1062
+ send: trackSend(track),
921
1063
  onPacket: (listener) => listeners.push(listener)
922
1064
  },
923
1065
  encoder: stack.opus(options.rate),
@@ -976,6 +1118,19 @@ function mdnsNote(signal, log) {
976
1118
  log(`${host}: an mDNS name, not resolved here: the call connects only if the contact's checks reach this side`);
977
1119
  }
978
1120
  }
1121
+ /**
1122
+ * Sends a call's packets on its track, while it is open. A track can close between `isOpen` and the send (the
1123
+ * connection failing), and libdatachannel then throws "Track is not open" from the audio's timer, where nothing catches
1124
+ * it: that frame is dropped, as one sent while the track is closed is.
1125
+ */
1126
+ function trackSend(track) {
1127
+ return (packet) => {
1128
+ if (!track.isOpen()) return;
1129
+ try {
1130
+ track.sendMessageBinary(packet);
1131
+ } catch {}
1132
+ };
1133
+ }
979
1134
  /** Whether a call's ICE servers (`callIceServers`) have a TURN server: its relay candidate is then the one waited for. */
980
1135
  function callUsesTurn(servers) {
981
1136
  return servers.some((server) => typeof server !== "string");
@@ -1010,8 +1165,7 @@ function gathering(pc, { turn = false } = {}) {
1010
1165
  });
1011
1166
  });
1012
1167
  }
1013
- //#endregion
1014
- //#region src/calls/manager.ts
1168
+ // src/calls/manager.ts
1015
1169
  /** An outgoing call rings this long, then ends as `unanswered`. */
1016
1170
  var RING_MS = 6e4;
1017
1171
  /** An answered or accepted call has this long to connect its media, then ends as `failed`. */
@@ -1055,7 +1209,8 @@ var CallManager = class {
1055
1209
  this.host = host;
1056
1210
  this.configPath = join(host.profileDir, "calls.json");
1057
1211
  this.auto = readAuto(this.configPath);
1058
- if (host.answers !== false) clearAudioSockets(host.profileDir);
1212
+ if (host.answers !== false && host.socketDir) sharedFolder(host.socketDir);
1213
+ if (host.answers !== false) clearAudioSockets(host.profileDir, host.socketDir);
1059
1214
  }
1060
1215
  get now() {
1061
1216
  return (this.host.now ?? Date.now)();
@@ -1239,7 +1394,7 @@ var CallManager = class {
1239
1394
  */
1240
1395
  prepare(call) {
1241
1396
  if (this.host.answers === false || call.ended || call.state !== "ringing") return;
1242
- const settings = this.host.engine.getState().settings;
1397
+ const settings = this.host.engine.getSettings();
1243
1398
  const iceServers = settings?.iceServers ?? [];
1244
1399
  if (settings?.relayOnly === true || callUsesTurn(callIceServers(iceServers))) return;
1245
1400
  this.stopEarly(call);
@@ -1333,6 +1488,7 @@ var CallManager = class {
1333
1488
  return this.view(call);
1334
1489
  }
1335
1490
  async answer(ref, options) {
1491
+ if (this.host.answers === false) throw new CliError("unavailable", CALLS_NEED_DAEMON);
1336
1492
  const call = this.find(ref, (c) => c.direction === "in" && c.state === "ringing");
1337
1493
  if (call.direction !== "in" || call.state !== "ringing") throw new CliError("refused", "That call is not ringing here");
1338
1494
  this.callable(call.chat);
@@ -1355,7 +1511,7 @@ var CallManager = class {
1355
1511
  v: 0
1356
1512
  });
1357
1513
  } catch (error) {
1358
- await this.end(call, "failed", true);
1514
+ await this.end(call, "failed", "unreachable");
1359
1515
  throw error;
1360
1516
  } finally {
1361
1517
  early?.close();
@@ -1382,6 +1538,7 @@ var CallManager = class {
1382
1538
  }
1383
1539
  /** Drops the audio the program queued and the call has not sent yet (barge-in). */
1384
1540
  flush(ref) {
1541
+ if (this.host.answers === false) throw new CliError("unavailable", CALLS_NEED_DAEMON);
1385
1542
  const call = this.find(ref);
1386
1543
  const flushedMs = call.queue?.flush() ?? 0;
1387
1544
  return {
@@ -1483,7 +1640,7 @@ var CallManager = class {
1483
1640
  */
1484
1641
  async attach(call, create) {
1485
1642
  const queue = call.queue = new PlaybackQueue(call.rate);
1486
- const socket = await AudioSocket.open(audioSocketPath(this.host.profileDir, call.id), call.rate, feedQueue(queue));
1643
+ const socket = await AudioSocket.open(audioSocketPath(this.host.profileDir, call.id, this.host.socketDir), call.rate, feedQueue(queue), { shared: !!this.host.socketDir });
1487
1644
  if (call.ended) {
1488
1645
  await socket.close();
1489
1646
  return;
@@ -1505,7 +1662,7 @@ var CallManager = class {
1505
1662
  rate: call.rate,
1506
1663
  queue: call.queue ?? void 0,
1507
1664
  log: (line) => process.stderr.write(`ghostly: call ${call.id}: ${line}\n`),
1508
- iceServers: this.host.engine.getState().settings?.iceServers ?? [],
1665
+ iceServers: this.host.engine.getSettings()?.iceServers ?? [],
1509
1666
  onFrame: (frame) => call.socket?.write(frame),
1510
1667
  onState: (state) => {
1511
1668
  if (call.ended || attempt !== call.attempt) return;
@@ -1519,7 +1676,7 @@ var CallManager = class {
1519
1676
  this.refused(call, "the connection failed as the answer went in");
1520
1677
  return;
1521
1678
  }
1522
- this.arm(call, MEDIA_GRACE_MS, state === "closed" ? "remote-hangup" : "failed", false);
1679
+ this.arm(call, MEDIA_GRACE_MS, state === "closed" ? "remote-hangup" : "failed", state !== "closed");
1523
1680
  }
1524
1681
  });
1525
1682
  if (call.ended || attempt !== call.attempt) {
@@ -1596,6 +1753,7 @@ var CallManager = class {
1596
1753
  }, every);
1597
1754
  call.watcher.unref?.();
1598
1755
  }
1756
+ /** `tell`: the contact is sent a hang-up; `"unreachable"`, one that says this side could not connect (`r: "u"`, WISP 601). */
1599
1757
  async end(call, reason, tell, report = true) {
1600
1758
  if (call.ended) return;
1601
1759
  call.ended = true;
@@ -1619,10 +1777,15 @@ var CallManager = class {
1619
1777
  call.early = null;
1620
1778
  const closing = call.socket?.close();
1621
1779
  if (tell) {
1622
- await this.send(call.chat, {
1780
+ const hangUp = tell === "unreachable" || reason === "failed" && call.connectedAt === null ? {
1781
+ t: "h",
1782
+ ts: this.stamp(call.chat),
1783
+ r: "u"
1784
+ } : {
1623
1785
  t: "h",
1624
1786
  ts: this.stamp(call.chat)
1625
- }).catch(() => {});
1787
+ };
1788
+ await this.send(call.chat, hangUp).catch(() => {});
1626
1789
  if (!this.stopping) {
1627
1790
  const timer = setTimeout(() => {
1628
1791
  this.clearing.delete(call.chat);
@@ -1732,7 +1895,7 @@ var CallManager = class {
1732
1895
  if (ref) {
1733
1896
  const byId = this.calls.get(ref);
1734
1897
  if (byId) return byId;
1735
- const call = this.byChat(this.chatId(ref));
1898
+ const call = this.byChat(this.chatOf(ref).id);
1736
1899
  if (!call) throw new CliError("not_found", `No call in chat ${ref}`);
1737
1900
  return call;
1738
1901
  }
@@ -1743,20 +1906,30 @@ var CallManager = class {
1743
1906
  throw new CliError("bad_request", "More than one call is on: name one (its id or its chat)", { calls: picked.map((c) => c.id) });
1744
1907
  }
1745
1908
  link(chat) {
1746
- return this.host.engine.getState().links.find((l) => l.id === chat);
1909
+ return this.host.engine.chatView(chat);
1747
1910
  }
1748
- /** A chat by id, contact key, prefix or name (the API's rules, `findChat`); a group's says it is one. */
1749
- chatId(ref) {
1911
+ /**
1912
+ * A chat by id, contact key, prefix or name (the API's rules, `findChat`); a group's says it is one. By its id (as
1913
+ * events name it, and a call's own chat), only that chat's view is built: a call placed and hung up built every chat's
1914
+ * five times, one rung and answered six, ~0.2 s of the daemon's thread at 2,000 chats.
1915
+ */
1916
+ chatOf(ref) {
1917
+ const byId = this.link(ref);
1918
+ if (byId) return byId;
1750
1919
  const { links, groups } = this.host.engine.getState();
1751
- return findChat(links, ref, groups).id;
1920
+ return findChat(links, ref, groups);
1752
1921
  }
1753
1922
  /** The chat, if a call can go in it now; else why not (the engine's reason). */
1754
1923
  callable(ref) {
1755
- const link = this.link(this.chatId(ref));
1924
+ const link = this.chatOf(ref);
1756
1925
  if (this.host.answers === false) throw new CliError("unavailable", CALLS_NEED_DAEMON);
1757
1926
  if (!link.profile) throw new CliError("unavailable", "Calls are in chats made since 0.4 (the chat session): this is a compatibility chat");
1927
+ if (link.callsUnavailable === CALLS_NEED_LIVE) {
1928
+ const shown = /^[\w.:-]+$/.test(link.label ?? "") ? link.label : link.id;
1929
+ throw new CliError("unavailable", `${CALLS_NEED_LIVE}, and your contact's app is not connected now: ghostly chat wait ${shown} --until live waits for it, then call again`, { chat: link.id });
1930
+ }
1758
1931
  if (link.callsUnavailable) throw new CliError("unavailable", link.callsUnavailable);
1759
- if (this.host.engine.getState().settings?.relayOnly === true) throw new CliError("unavailable", CALLS_OFF_RELAY_ONLY);
1932
+ if (this.host.engine.getSettings()?.relayOnly === true) throw new CliError("unavailable", CALLS_OFF_RELAY_ONLY);
1760
1933
  return link;
1761
1934
  }
1762
1935
  autoFor(chat) {
@@ -1764,6 +1937,8 @@ var CallManager = class {
1764
1937
  }
1765
1938
  };
1766
1939
  var CALLS_NEED_DAEMON = "Calls need the daemon (a call outlives this command): start it with `ghostly daemon --detach`";
1940
+ /** The engine's `callsUnavailable` for a chat with no live session (ghostlink's, or node.ts's with no link running). */
1941
+ var CALLS_NEED_LIVE = "Calls need a live connection";
1767
1942
  /**
1768
1943
  * Hide my IP from contacts (`relayOnly`, WISP 601 Relay only): libdatachannel's relay policy only keeps the other
1769
1944
  * candidates out of the signal; its ICE still checks from this machine's own sockets, and a call connected on a direct
@@ -1798,8 +1973,7 @@ function readAuto(path) {
1798
1973
  return off;
1799
1974
  }
1800
1975
  }
1801
- //#endregion
1802
- //#region src/daemonPresence.ts
1976
+ // src/daemonPresence.ts
1803
1977
  /** How often a daemon that shares its presence says `active` again: well within the engine's 10 minutes to `idle`. */
1804
1978
  var PRESENCE_EVERY_MS = STATUS_IDLE_AFTER_MS / 2;
1805
1979
  /**
@@ -1920,6 +2094,18 @@ var EventHub = class {
1920
2094
  /** `file.*` events whose message was not seen yet: they wait for it a moment (the engine stores it right after). */
1921
2095
  pendingFiles = /* @__PURE__ */ new Map();
1922
2096
  baselined = false;
2097
+ /** Whether the chats and groups are known (`perChat`, `baseline`): a change to them is an event from then on. */
2098
+ stateKnown = false;
2099
+ /**
2100
+ * How a chat or group is caught up when its history's first event comes (`perChat`): until then its notes are not
2101
+ * read. Null when the baseline took them all.
2102
+ */
2103
+ chatReads = null;
2104
+ /** Chats and groups caught up (`perChat`): their events are handled as they come. */
2105
+ caught = /* @__PURE__ */ new Set();
2106
+ /** Chats and groups being caught up, and the events of their histories that wait for it, in order. */
2107
+ behind = /* @__PURE__ */ new Map();
2108
+ catchingUp = /* @__PURE__ */ new Set();
1923
2109
  /** Chats and groups whose history the baseline did not read whole, and how to read their file rows: until a file event needs them. */
1924
2110
  unread = /* @__PURE__ */ new Map();
1925
2111
  /**
@@ -1938,8 +2124,11 @@ var EventHub = class {
1938
2124
  this.now = now;
1939
2125
  this.seenDb = seenDb;
1940
2126
  }
1941
- /** Loads the journal's last seq and the seen set; call before `sink` is attached. */
1942
- async open() {
2127
+ /**
2128
+ * Loads the journal's last seq and the seen set; call before `sink` is attached. `seen: false`: the seen set is read
2129
+ * later, whole (`loadSeen`) or as each chat needs it (`loadOwnNotes`, `perChat`).
2130
+ */
2131
+ async open({ seen = true } = {}) {
1943
2132
  const reserved = readDropped(this.journalPath + ".reserved") ?? 0;
1944
2133
  try {
1945
2134
  const dropped = readDropped(this.journalPath + ".dropped");
@@ -1982,7 +2171,27 @@ var EventHub = class {
1982
2171
  this.seq = reserved;
1983
2172
  this.markDropped(Math.max(this.dropped, reserved));
1984
2173
  }
1985
- this.db = await new Promise((resolve, reject) => {
2174
+ if (seen) await this.loadSeen();
2175
+ }
2176
+ /** Reads the whole seen set (`open` with `seen: false`); call before `baseline`. */
2177
+ async loadSeen() {
2178
+ await this.openSeen();
2179
+ await this.readNotes();
2180
+ }
2181
+ /**
2182
+ * Reads only the seen set's own notes (its marks, the transfers under way, what this side said once), for `perChat`:
2183
+ * true when that can catch the chats up one by one. Not on a first run, nor on a set without its marks, which the
2184
+ * baseline reads whole once (`loadSeen`).
2185
+ */
2186
+ async loadOwnNotes() {
2187
+ await this.openSeen();
2188
+ await this.readNotes(IDBKeyRange.bound([FORMAT], [FORMAT, []]));
2189
+ await this.readNotes(IDBKeyRange.bound([UNDERWAY], [UNDERWAY, []]));
2190
+ await this.readNotes(IDBKeyRange.bound(["said:"], ["said;"], false, true));
2191
+ return !this.firstRun && this.mentionsNoted && this.agesNoted;
2192
+ }
2193
+ async openSeen() {
2194
+ this.db ??= await new Promise((resolve, reject) => {
1986
2195
  const request = indexedDB.open(this.seenDb, 1);
1987
2196
  request.onupgradeneeded = () => {
1988
2197
  request.result.createObjectStore(SEEN);
@@ -1991,12 +2200,15 @@ var EventHub = class {
1991
2200
  request.onsuccess = () => resolve(request.result);
1992
2201
  request.onerror = () => reject(request.error);
1993
2202
  });
2203
+ }
2204
+ /** The notes in `range` (all with none) into memory. */
2205
+ async readNotes(range) {
1994
2206
  const store = this.db.transaction(SEEN).objectStore(SEEN);
1995
2207
  const all = (request) => new Promise((resolve, reject) => {
1996
2208
  request.onsuccess = () => resolve(request.result);
1997
2209
  request.onerror = () => reject(request.error);
1998
2210
  });
1999
- const [keys, values] = await Promise.all([all(store.getAllKeys()), all(store.getAll())]);
2211
+ const [keys, values] = await Promise.all([all(store.getAllKeys(range)), all(store.getAll(range))]);
2000
2212
  for (let i = 0; i < keys.length; i++) {
2001
2213
  const [chat, id] = keys[i];
2002
2214
  this.seenOf(chat).set(id, values[i]);
@@ -2019,6 +2231,7 @@ var EventHub = class {
2019
2231
  */
2020
2232
  baseline(state, histories, rest) {
2021
2233
  this.stateChanged(state);
2234
+ this.stateKnown = true;
2022
2235
  for (const [chat, messages] of histories) this.messages(chat, messages);
2023
2236
  for (const [chat, messages] of rest?.newest ?? []) {
2024
2237
  this.messages(chat, messages, []);
@@ -2038,13 +2251,73 @@ var EventHub = class {
2038
2251
  }
2039
2252
  }
2040
2253
  /**
2254
+ * The baseline one chat or group at a time, after `loadOwnNotes` said it can: the chats and groups are known now, and
2255
+ * each one's notes are read (by key range) and its history caught up as the baseline would (`reads`) when the first
2256
+ * event of its history comes; its events wait for that. A one-shot hears a few chats at most: the whole set, a note
2257
+ * per message active in the last 30 days, took a `message send` 0.07 s and 56 MB at 50,000 notes.
2258
+ */
2259
+ perChat(state, reads) {
2260
+ this.chatReads = reads;
2261
+ this.stateChanged(state);
2262
+ this.stateKnown = true;
2263
+ this.baselined = true;
2264
+ for (const id of [...state.links.map((link) => link.id), ...state.groups.map((group) => `group:${group.id}`)]) this.unread.set(id, reads.files);
2265
+ }
2266
+ /** The catch-ups still running (`perChat`): their events are told once they end. */
2267
+ async caughtUp() {
2268
+ while (this.catchingUp.size) await Promise.all(this.catchingUp);
2269
+ }
2270
+ /** An event of a history not caught up yet (`perChat`): it waits, and the first one starts the catch-up. */
2271
+ waits(message) {
2272
+ if (!this.chatReads || message.kind !== "messages" && message.kind !== "message-changes") return false;
2273
+ const chat = message.linkId;
2274
+ if (this.caught.has(chat)) return false;
2275
+ const waiting = this.behind.get(chat);
2276
+ if (waiting) {
2277
+ waiting.push(message);
2278
+ return true;
2279
+ }
2280
+ this.behind.set(chat, [message]);
2281
+ const running = this.catchUp(chat, message.kind === "messages" && !message.more).catch((error) => {
2282
+ process.stderr.write(`ghostly: event error: ${error instanceof Error ? error.stack : String(error)}\n`);
2283
+ }).then(() => {
2284
+ this.caught.add(chat);
2285
+ const events = this.behind.get(chat) ?? [];
2286
+ this.behind.delete(chat);
2287
+ if (chat.startsWith("group:") ? this.groups.has(chat.slice(6)) : this.chats.has(chat)) for (const event of events) this.sink.post(event);
2288
+ this.catchingUp.delete(running);
2289
+ });
2290
+ this.catchingUp.add(running);
2291
+ return true;
2292
+ }
2293
+ /**
2294
+ * One chat's or group's notes, and its history as the baseline takes it (`baseline`): its newest page when the history
2295
+ * is in step with them (`inStep`), else whole. `whole`: the event that waits is its whole history, which says it all.
2296
+ */
2297
+ async catchUp(chat, whole) {
2298
+ await this.readNotes(IDBKeyRange.bound([chat], [chat, []]));
2299
+ await this.readNotes(IDBKeyRange.bound([`reactions:${chat}`], [`reactions:${chat}`, []]));
2300
+ const reads = this.chatReads;
2301
+ if (whole) this.unread.delete(chat);
2302
+ else {
2303
+ const page = await reads.newest(chat);
2304
+ if (page && !page.more) this.messages(chat, page.messages);
2305
+ else if (page && this.inStep(chat, page.messages)) this.messages(chat, page.messages, []);
2306
+ else {
2307
+ this.messages(chat, await reads.whole(chat));
2308
+ this.unread.delete(chat);
2309
+ }
2310
+ }
2311
+ this.sweep([chat, `reactions:${chat}`]);
2312
+ }
2313
+ /**
2041
2314
  * Drops the notes of settled messages, and of reactions, whose last activity is older than `SEEN_KEEP_MS`: from memory
2042
2315
  * and from the store. A message of mine still on its way (or failed, which a retry sends again) keeps its note. The
2043
2316
  * 30 days count back from the newest activity the set knows when the clock reads later than it: a clock run ahead (a
2044
2317
  * wrong RTC, a VM restored with a skewed clock) would otherwise drop the notes of the recent history, which the next
2045
2318
  * start with the clock right reports again.
2046
2319
  */
2047
- sweep() {
2320
+ sweep(only) {
2048
2321
  let newest = 0;
2049
2322
  for (const [chat, known] of this.seen) {
2050
2323
  if (chat === FORMAT || chat.startsWith("said:")) continue;
@@ -2052,8 +2325,9 @@ var EventHub = class {
2052
2325
  }
2053
2326
  const cutoff = Math.min(this.now(), newest) - SEEN_KEEP_MS;
2054
2327
  let dropped = 0;
2055
- for (const [chat, known] of this.seen) {
2056
- if (chat === FORMAT || chat === UNDERWAY || chat.startsWith("said:")) continue;
2328
+ for (const chat of only ?? [...this.seen.keys()]) {
2329
+ const known = this.seen.get(chat);
2330
+ if (!known || chat === FORMAT || chat === UNDERWAY || chat.startsWith("said:")) continue;
2057
2331
  const reactions = chat.startsWith("reactions:");
2058
2332
  const gone = [];
2059
2333
  for (const [id, note] of known) {
@@ -2382,6 +2656,7 @@ var EventHub = class {
2382
2656
  return from === Infinity ? void 0 : from;
2383
2657
  }
2384
2658
  handle(message) {
2659
+ if (this.waits(message)) return;
2385
2660
  switch (message.kind) {
2386
2661
  case "state":
2387
2662
  this.stateChanged(message.state);
@@ -2407,9 +2682,11 @@ var EventHub = class {
2407
2682
  }
2408
2683
  }
2409
2684
  stateChanged(state) {
2410
- const quiet = !this.baselined;
2685
+ const quiet = !this.stateKnown;
2411
2686
  const links = new Map(state.links.map((link) => [link.id, link]));
2687
+ const last = new Map(this.state?.links.map((link) => [link.id, link]));
2412
2688
  for (const [id, link] of links) {
2689
+ if (last.get(id) === link && this.chats.has(id)) continue;
2413
2690
  const shape = chatShape(link), before = this.chats.get(id);
2414
2691
  this.chats.set(id, shape);
2415
2692
  if (quiet) continue;
@@ -2458,8 +2735,12 @@ var EventHub = class {
2458
2735
  }
2459
2736
  const removedChats = [...this.chats.keys()].filter((id) => !links.has(id));
2460
2737
  for (const id of removedChats) {
2738
+ const peer = this.chats.get(id)?.peer;
2461
2739
  this.chats.delete(id);
2462
- if (!quiet) this.emit("chat.removed", `chat.removed:${id}:${this.now()}`, { chat: id });
2740
+ if (!quiet) this.emit("chat.removed", `chat.removed:${id}:${this.now()}`, {
2741
+ chat: id,
2742
+ ...peer ? { peer } : {}
2743
+ });
2463
2744
  }
2464
2745
  const chatsGone = new Set(removedChats);
2465
2746
  this.forget(removedChats, (event) => chatsGone.has(event.chat) && event.type !== "chat.removed");
@@ -2479,8 +2760,7 @@ var EventHub = class {
2479
2760
  group: id,
2480
2761
  status: shape.status
2481
2762
  });
2482
- const joined = shape.members.filter((key) => !before.members.includes(key));
2483
- const left = before.members.filter((key) => !shape.members.includes(key));
2763
+ const { joined, left } = membersDiff(before.members, shape.members);
2484
2764
  if (joined.length || left.length) this.emit("group.members", `group.members:${id}:${this.now()}`, {
2485
2765
  group: id,
2486
2766
  joined,
@@ -2508,11 +2788,18 @@ var EventHub = class {
2508
2788
  }
2509
2789
  const groupsGone = new Set(removedGroups);
2510
2790
  this.forget(removedGroups, (event) => groupsGone.has(event.group) && event.type !== "group.removed");
2511
- for (const [id, payment] of Object.entries(state.payments ?? {})) {
2791
+ let edgeGroups;
2792
+ const groupOf = (linkId) => (edgeGroups ??= new Map(state.groups.flatMap((g) => g.members.flatMap((m) => m.edge ? [[m.edge.linkId, g.id]] : [])))).get(linkId) ?? parsePayLink(linkId)?.groupId;
2793
+ const payments = state.payments === this.state?.payments ? {} : state.payments ?? {};
2794
+ for (const [id, payment] of Object.entries(payments)) {
2512
2795
  const shape = `${payment.state}|${payment.error ?? ""}|${payment.closed ? 1 : 0}`, before = this.payments.get(id);
2513
2796
  this.payments.set(id, shape);
2514
2797
  if (quiet || before === shape) continue;
2515
- const json = paymentJson(payment);
2798
+ const group = payment.group ?? groupOf(payment.linkId);
2799
+ const json = {
2800
+ ...paymentJson(payment),
2801
+ ...group && { group }
2802
+ };
2516
2803
  if (before === void 0) this.emit("payment.created", `payment.created:${id}`, {
2517
2804
  chat: payment.linkId,
2518
2805
  payment: json
@@ -2522,22 +2809,25 @@ var EventHub = class {
2522
2809
  payment: json
2523
2810
  });
2524
2811
  }
2525
- for (const link of state.links) for (const identity of link.identities?.received ?? []) {
2526
- const key = `${link.id}:${identity.id}`, shape = identity.status, before = this.received.get(key);
2527
- this.received.set(key, shape);
2528
- if (quiet || before === shape) continue;
2529
- const id = before === void 0 ? `identity.received:${key}:${shape}` : `identity.status:${key}:${shape}:${this.now()}:${this.seq + 1}`;
2530
- this.emit(before === void 0 ? "identity.received" : "identity.status", id, {
2531
- chat: link.id,
2532
- identity: {
2533
- id: identity.id,
2534
- provider: identity.provider,
2535
- subject: identity.subject,
2536
- status: identity.status,
2537
- verified: identity.verified,
2538
- error: identity.error ?? null
2539
- }
2540
- });
2812
+ for (const link of state.links) {
2813
+ if (last.get(link.id) === link) continue;
2814
+ for (const identity of link.identities?.received ?? []) {
2815
+ const key = `${link.id}:${identity.id}`, shape = identity.status, before = this.received.get(key);
2816
+ this.received.set(key, shape);
2817
+ if (quiet || before === shape) continue;
2818
+ const id = before === void 0 ? `identity.received:${key}:${shape}` : `identity.status:${key}:${shape}:${this.now()}:${this.seq + 1}`;
2819
+ this.emit(before === void 0 ? "identity.received" : "identity.status", id, {
2820
+ chat: link.id,
2821
+ identity: {
2822
+ id: identity.id,
2823
+ provider: identity.provider,
2824
+ subject: identity.subject,
2825
+ status: identity.status,
2826
+ verified: identity.verified,
2827
+ error: identity.error ?? null
2828
+ }
2829
+ });
2830
+ }
2541
2831
  }
2542
2832
  for (const [id, transfer] of Object.entries(state.transfers ?? {})) this.transferChanged(id, transfer, state, quiet);
2543
2833
  this.state = state;
@@ -3043,7 +3333,8 @@ function chatShape(link) {
3043
3333
  typing: !!link.peerTyping,
3044
3334
  typingKind: link.peerTyping ? link.peerTypingKind ?? "typing" : "typing",
3045
3335
  typingStatus: link.peerTyping ? link.peerTypingStatus ?? null : null,
3046
- pin: link.pin ?? null
3336
+ pin: link.pin ?? null,
3337
+ peer: view.peer || null
3047
3338
  };
3048
3339
  }
3049
3340
  /** A `typing.started`'s word: the kind, and the contact's status line when it gave one (already cleaned). */
@@ -3065,6 +3356,25 @@ function groupShape(group) {
3065
3356
  };
3066
3357
  }
3067
3358
  /**
3359
+ * Who joined and who left between two of `groupShape`'s sorted member lists, in one walk of both: a state comes up to
3360
+ * every 50 ms, and a full community has 256 members, so a lookup of each key in the other list would cost each state
3361
+ * O(members²) per group though nothing changed.
3362
+ */
3363
+ function membersDiff(before, after) {
3364
+ const joined = [], left = [];
3365
+ let i = 0, j = 0;
3366
+ while (i < before.length || j < after.length) if (j >= after.length || i < before.length && before[i] < after[j]) left.push(before[i++]);
3367
+ else if (i >= before.length || after[j] < before[i]) joined.push(after[j++]);
3368
+ else {
3369
+ i++;
3370
+ j++;
3371
+ }
3372
+ return {
3373
+ joined,
3374
+ left
3375
+ };
3376
+ }
3377
+ /**
3068
3378
  * The journal's whole lines within its last `JOURNAL_MAX_BYTES`, and its size: never the whole file as one string, so
3069
3379
  * a journal grown past what a string can hold (or a trim's bound) is still read, and in bounded time. Lines `forget`
3070
3380
  * blanked are left out.
@@ -3319,8 +3629,7 @@ function journalWindow(path, lineAt = 0) {
3319
3629
  closeSync(fd);
3320
3630
  }
3321
3631
  }
3322
- //#endregion
3323
- //#region src/groupAuto.ts
3632
+ // src/groupAuto.ts
3324
3633
  var FILE = "groups.json";
3325
3634
  var GroupAutoJoin = class {
3326
3635
  host;
@@ -3458,8 +3767,7 @@ function readGrants(path) {
3458
3767
  return [];
3459
3768
  }
3460
3769
  }
3461
- //#endregion
3462
- //#region src/joinLog.ts
3770
+ // src/joinLog.ts
3463
3771
  /**
3464
3772
  * A join through a group's link, as a daemon says it in its log (stderr): the steps of the knock and of the entry
3465
3773
  * session, one short line each, from the engine's join trace (packages/browser/src/engine/joinTrace.ts). Without them a
@@ -3483,7 +3791,8 @@ var SAID = {
3483
3791
  "full.sent": "the group is full: told the joiner on the entry session",
3484
3792
  "full.received": "the group is full: knocking on until there is room",
3485
3793
  "welcome.sent": "welcome sent",
3486
- "welcome.received": "welcome received: in the group"
3794
+ "welcome.received": "welcome received: in the group",
3795
+ "join.unanswered": "nobody answered for an hour: knocks stopped (ghostly group accept knocks again)"
3487
3796
  };
3488
3797
  /** The log line for one join-trace line, or null when it is not said. */
3489
3798
  function joinLogLine(traced) {
@@ -3499,8 +3808,7 @@ function joinLogLine(traced) {
3499
3808
  const at = typeof step.t === "number" ? ` at ${new Date(step.t).toISOString()}` : "";
3500
3809
  return `ghostly: group ${step.g}: ${SAID[step.step]}${role ? ` (${role === "host" ? "letting in" : "joining"})` : ""}${at}`;
3501
3810
  }
3502
- //#endregion
3503
- //#region src/runtime/fedimint.ts
3811
+ // src/runtime/fedimint.ts
3504
3812
  /**
3505
3813
  * The Fedimint client on Node (WISP 1100 § Wallet SDKs on Node): the app's own SDK and WebAssembly, each database in
3506
3814
  * a `worker_threads` worker (fedimintWorker.mjs) and a file of the profile's `fedimint/` folder, where the browser has
@@ -3608,8 +3916,7 @@ function nodeFedimintSdk(dir) {
3608
3916
  throw error;
3609
3917
  });
3610
3918
  }
3611
- //#endregion
3612
- //#region src/runtime/fileFetch.ts
3919
+ // src/runtime/fileFetch.ts
3613
3920
  /**
3614
3921
  * `fetch` for `file:` URLs, which Node's does not do. The wallet SDKs' WebAssembly (Bark, BDK, Breez, Iroh) is loaded
3615
3922
  * the way a page loads it, `fetch(new URL("…wasm", import.meta.url))`; on Node that URL is a file beside the bundle.
@@ -3629,8 +3936,7 @@ function installFileFetch() {
3629
3936
  };
3630
3937
  globalThis.fetch = patched;
3631
3938
  }
3632
- //#endregion
3633
- //#region src/runtime/pushSend.ts
3939
+ // src/runtime/pushSend.ts
3634
3940
  /** An address as bytes (4 or 16), or null when it is not one. */
3635
3941
  function addressBytes(address) {
3636
3942
  const family = isIP(address);
@@ -3704,8 +4010,7 @@ async function nodePushSend(push, lookup = publicOnlyLookup) {
3704
4010
  req.end(push.body);
3705
4011
  });
3706
4012
  }
3707
- //#endregion
3708
- //#region src/runtime/holdFetch.ts
4013
+ // src/runtime/holdFetch.ts
3709
4014
  /**
3710
4015
  * How the CLI reads a held item or manifest (WISP 404): a GET to the address the contact chose, only
3711
4016
  * at a name whose every address is public, checked when the connection is made (so a name that changes its answer
@@ -3732,8 +4037,7 @@ function nodeHoldFetch(lookup = publicOnlyLookup) {
3732
4037
  req.end();
3733
4038
  });
3734
4039
  }
3735
- //#endregion
3736
- //#region src/runtime/irohRelay.ts
4040
+ // src/runtime/irohRelay.ts
3737
4041
  /**
3738
4042
  * Whether the CLI's Iroh may dial a contact through the relay its descriptor names (irohWeb.ts `publicRelay`): at a
3739
4043
  * public address, or at a name whose every address is public now, as a held item's is (`publicOnlyLookup`). Asked again
@@ -3787,8 +4091,7 @@ function relaySockets(scope) {
3787
4091
  } });
3788
4092
  return names;
3789
4093
  }
3790
- //#endregion
3791
- //#region src/runtime/rows.ts
4094
+ // src/runtime/rows.ts
3792
4095
  /** The warning `node:sqlite` gives as it loads (experimental on Node 22 and 23): said once for every command, it is noise. */
3793
4096
  var SQLITE_WARNING = /^SQLite is an experimental feature/;
3794
4097
  var loaded;
@@ -3851,8 +4154,7 @@ function rowRecords(rows) {
3851
4154
  return record;
3852
4155
  } };
3853
4156
  }
3854
- //#endregion
3855
- //#region src/runtime/keyBytes.ts
4157
+ // src/runtime/keyBytes.ts
3856
4158
  /**
3857
4159
  * An IndexedDB key as bytes whose order is the keys' own (W3C IndexedDB § Compare two keys: a number before a date
3858
4160
  * before a string before binary before an array; strings by UTF-16 code unit; arrays item by item, the shorter
@@ -3921,8 +4223,7 @@ function number(value, out) {
3921
4223
  out.push(negative ? ~byte & 255 : at === 0 ? byte ^ 128 : byte);
3922
4224
  }
3923
4225
  }
3924
- //#endregion
3925
- //#region src/runtime/sqlTree.ts
4226
+ // src/runtime/sqlTree.ts
3926
4227
  var buffer = (bytes) => Buffer.from(bytes, "latin1");
3927
4228
  /**
3928
4229
  * Values just read from rows.db, which nothing else holds: fake-indexeddb copies each value it hands out, and for these
@@ -4033,6 +4334,15 @@ var TreeFile = class {
4033
4334
  closeSync(fd);
4034
4335
  }
4035
4336
  }
4337
+ /**
4338
+ * rows.db written again whole (VACUUM), with nothing but its rows: `secure_delete` zeroes the cell a delete frees, not
4339
+ * the copies a page's rebalancing left in its unused space, where a text gone from every row was still found after a
4340
+ * few thousand writes. A second or two for a profile of 100,000 messages, the thread held: only when asked
4341
+ * (`message delete --purge`).
4342
+ */
4343
+ scrub() {
4344
+ this.db.exec("VACUUM");
4345
+ }
4036
4346
  /** Trees whose store or index is gone from the schema (deleted, a database removed) go, with their entries. */
4037
4347
  sweep(keep) {
4038
4348
  const ids = this.db.prepare("SELECT id FROM trees").all().map((row) => Number(row.id)).filter((id) => !keep.has(id));
@@ -4364,7 +4674,8 @@ var SqlTree = class SqlTree {
4364
4674
  /**
4365
4675
  * rows.db, owner-only (SQLite makes its WAL files with the database's mode), in WAL with NORMAL: the journal makes a
4366
4676
  * transaction durable, and `sync` runs before a snapshot takes the journal's place. With `secure_delete` SQLite zeroes
4367
- * what a delete frees: a message or chat deleted is not left readable in the file's free pages after the fold.
4677
+ * what a delete frees: a message or chat deleted is not left readable in the file's free pages after the fold (but for
4678
+ * a copy a page's rebalancing left behind, now and then: `TreeFile.scrub`).
4368
4679
  */
4369
4680
  function openTreeFile(sqlite, path, constraintError) {
4370
4681
  closeSync(openSync(path, "a", 384));
@@ -4408,8 +4719,7 @@ function holdsBlob(value, depth = 0) {
4408
4719
  for (const item of Object.values(value)) if (holdsBlob(item, depth + 1)) return true;
4409
4720
  return false;
4410
4721
  }
4411
- //#endregion
4412
- //#region src/runtime/storage.ts
4722
+ // src/runtime/storage.ts
4413
4723
  var SNAPSHOT = "snapshot.bin";
4414
4724
  var JOURNAL = "journal.bin";
4415
4725
  var ROWS = "rows.db";
@@ -4459,7 +4769,7 @@ var FOLLOWS = "__ghostly_journal__";
4459
4769
  var SEQ = "__ghostly_entry__";
4460
4770
  /** How long `close` waits for the transactions still running: one left open for good does not keep the process. */
4461
4771
  var CLOSE_WAIT_MS = 5e3;
4462
- /** Records of rows.db an export reads in one turn of the event loop: a few milliseconds' worth. */
4772
+ /** Records an export reads and serializes in one turn of the event loop, then writes: a few milliseconds' worth. */
4463
4773
  var EXPORT_PAGE = 256;
4464
4774
  /** How long a relaxed transaction's entry may wait for a sync when no other transaction brings one. */
4465
4775
  var RELAXED_SYNC_MS = 1e3;
@@ -4683,9 +4993,7 @@ async function openPersistentIndexedDb(dir, options = {}) {
4683
4993
  pending.delete(this._rollbackLog);
4684
4994
  trees?.abort(this._rollbackLog);
4685
4995
  }
4686
- const dispatched = dispatch.call(this, event);
4687
- if ((event.type === "complete" || event.type === "abort") && this._state === "finished") dropEnded(this.db._rawDatabase, this);
4688
- return dispatched;
4996
+ return dispatch.call(this, event);
4689
4997
  };
4690
4998
  const deleteDatabase = factory.deleteDatabase.bind(factory);
4691
4999
  factory.deleteDatabase = (name) => {
@@ -4782,7 +5090,7 @@ async function openPersistentIndexedDb(dir, options = {}) {
4782
5090
  tree.clear();
4783
5091
  return deleted;
4784
5092
  };
4785
- if (index) records.deleteByValue = (key) => tree.deleteByValue(key instanceof IDBKeyRange ? key : IDBKeyRange.only(key));
5093
+ if (index) records.deleteByValue = (key) => tree.deleteByValue(key instanceof IDBKeyRange$1 ? key : IDBKeyRange$1.only(key));
4786
5094
  }
4787
5095
  /** A store whose records and index entries are in rows.db already (a snapshot of format 3): its trees attached. */
4788
5096
  function attachTrees(store) {
@@ -4832,7 +5140,7 @@ async function openPersistentIndexedDb(dir, options = {}) {
4832
5140
  * `sync`: "now", synced before this returns; "shared", synced by the caller through `shareSync`; "lazy", a relaxed
4833
5141
  * transaction's entry. A sync blocks the whole process for milliseconds, and what such a transaction wrote can be
4834
5142
  * made again (the event set's note of a message it already reported): written, it outlives the process; a power cut
4835
- * may take its last second.
5143
+ * may take its last second. Its sync, a second later, runs off the thread as a shared one does.
4836
5144
  */
4837
5145
  function writeEntry(entry, sync = "now") {
4838
5146
  const lazy = sync === "lazy";
@@ -4858,11 +5166,8 @@ async function openPersistentIndexedDb(dir, options = {}) {
4858
5166
  throw error;
4859
5167
  }
4860
5168
  if (lazy) relaxed ??= setTimeout(() => {
4861
- try {
4862
- syncNow();
4863
- } catch (error) {
4864
- failed(error);
4865
- }
5169
+ relaxed = null;
5170
+ shareSync(() => {});
4866
5171
  }, RELAXED_SYNC_MS).unref();
4867
5172
  holdsRatchet ||= entry.includes(RATCHET);
4868
5173
  if (statSync(journalPath).size > COMPACT_BYTES || ratchetDue() || deleteDue()) enqueue(writeSnapshot);
@@ -4912,28 +5217,79 @@ async function openPersistentIndexedDb(dir, options = {}) {
4912
5217
  async function synced() {
4913
5218
  while (syncing) await syncing;
4914
5219
  }
4915
- async function writeSnapshot() {
5220
+ async function writeSnapshot(scrub = false) {
4916
5221
  const dirty = schemaDirty;
4917
5222
  schemaDirty = false;
4918
5223
  try {
4919
- await snapshotToDisk();
5224
+ await snapshotToDisk(scrub);
4920
5225
  } catch (error) {
4921
5226
  schemaDirty ||= dirty;
4922
5227
  throw error;
4923
5228
  }
4924
5229
  }
4925
- /**
4926
- * What is held, as a snapshot. `inline`: every value in it (format 1, `exportSnapshot`); otherwise the stores kept on
4927
- * disk say only that they are (format 3).
4928
- */
4929
- async function capture(journalName, inline) {
5230
+ /** A store's part of a snapshot, all but its records. */
5231
+ function storeMeta(store) {
5232
+ const live = [...store.rawIndexes.values()].filter((index) => !index.deleted);
5233
+ return {
5234
+ name: store.name,
5235
+ keyPath: store.keyPath,
5236
+ autoIncrement: store.autoIncrement,
5237
+ keyGenerator: store.keyGenerator?.num ?? null,
5238
+ indexes: live.map(({ name, keyPath, multiEntry, unique }) => ({
5239
+ name,
5240
+ keyPath,
5241
+ multiEntry,
5242
+ unique
5243
+ }))
5244
+ };
5245
+ }
5246
+ /** What is held, as a snapshot of format 3: the stores kept on disk say only that they are. */
5247
+ async function capture(journalName) {
4930
5248
  const snapshot = {
4931
5249
  format: 1,
4932
- ...journalName !== void 0 && { journal: journalName },
5250
+ journal: journalName,
4933
5251
  databases: []
4934
5252
  };
4935
5253
  const held = [];
4936
- const later = [];
5254
+ for (const db of raw._databases.values()) {
5255
+ if (db.name === PROBE) continue;
5256
+ const stores = [];
5257
+ for (const store of db.rawObjectStores.values()) {
5258
+ if (store.deleted) continue;
5259
+ if (disk(store)) {
5260
+ if (!onTrees(store)) toDisk(store);
5261
+ stores.push({
5262
+ ...storeMeta(store),
5263
+ records: [],
5264
+ onDisk: true
5265
+ });
5266
+ snapshot.format = 3;
5267
+ continue;
5268
+ }
5269
+ const saved = {
5270
+ ...storeMeta(store),
5271
+ records: []
5272
+ };
5273
+ for (const record of store.records.values()) saved.records.push([record.key, record.value]);
5274
+ stores.push(saved);
5275
+ held.push(saved);
5276
+ }
5277
+ snapshot.databases.push({
5278
+ name: db.name,
5279
+ version: db.version,
5280
+ stores
5281
+ });
5282
+ }
5283
+ for (const store of held) for (const record of store.records) record[1] = await blobsToDisk(record[1]);
5284
+ return snapshot;
5285
+ }
5286
+ /**
5287
+ * The whole store as a snapshot of format 1 (every value inline, `rows.db` read), written to `file` as it is read: a
5288
+ * page of records serialized and written at a time. Built whole and serialized in one turn, an export of 400,000
5289
+ * messages held the store as objects and its serialized copy at once (+340 MB) and the daemon for 390 ms.
5290
+ */
5291
+ async function exportTo(file) {
5292
+ const databases = [];
4937
5293
  let reader = null;
4938
5294
  try {
4939
5295
  for (const db of raw._databases.values()) {
@@ -4941,61 +5297,76 @@ async function openPersistentIndexedDb(dir, options = {}) {
4941
5297
  const stores = [];
4942
5298
  for (const store of db.rawObjectStores.values()) {
4943
5299
  if (store.deleted) continue;
4944
- const live = [...store.rawIndexes.values()].filter((index) => !index.deleted);
4945
- const meta = {
4946
- name: store.name,
4947
- keyPath: store.keyPath,
4948
- autoIncrement: store.autoIncrement,
4949
- keyGenerator: store.keyGenerator?.num ?? null,
4950
- indexes: live.map(({ name, keyPath, multiEntry, unique }) => ({
4951
- name,
4952
- keyPath,
4953
- multiEntry,
4954
- unique
4955
- }))
4956
- };
4957
- if (!inline && disk(store)) {
4958
- if (!onTrees(store)) toDisk(store);
5300
+ if (!onTrees(store)) {
4959
5301
  stores.push({
4960
- ...meta,
4961
- records: [],
4962
- onDisk: true
5302
+ meta: storeMeta(store),
5303
+ records: Array.from(store.records.values(), ({ key, value }) => ({
5304
+ key,
5305
+ value
5306
+ }))
4963
5307
  });
4964
- snapshot.format = 3;
4965
5308
  continue;
4966
5309
  }
4967
- const saved = {
4968
- ...meta,
4969
- records: []
4970
- };
4971
- stores.push(saved);
4972
- if (onTrees(store)) {
4973
- reader ??= openTreeReader(sqlite, rowsPath, classes.constraintError);
4974
- later.push([saved, store.records.records.at(reader)]);
4975
- } else {
4976
- for (const record of store.records.values()) saved.records.push([record.key, record.value]);
4977
- held.push(saved);
4978
- }
5310
+ reader ??= openTreeReader(sqlite, rowsPath, classes.constraintError);
5311
+ stores.push({
5312
+ meta: storeMeta(store),
5313
+ records: store.records.records.at(reader)
5314
+ });
4979
5315
  }
4980
- snapshot.databases.push({
5316
+ databases.push({
4981
5317
  name: db.name,
4982
5318
  version: db.version,
4983
5319
  stores
4984
5320
  });
4985
5321
  }
4986
- for (const store of held) for (const record of store.records) record[1] = await blobsToDisk(record[1]);
4987
- for (const [saved, tree] of later) for (const record of tree.getAllRecords()) if (saved.records.push([record.key, record.value]) % EXPORT_PAGE === 0) await new Promise((resolve) => setImmediate(resolve));
5322
+ const out = new SnapshotWriter(file);
5323
+ out.begin("o");
5324
+ out.value("format", 1);
5325
+ out.key("databases");
5326
+ out.begin("A", databases.length);
5327
+ for (const db of databases) {
5328
+ out.begin("o");
5329
+ out.value("name", db.name);
5330
+ out.value("version", db.version);
5331
+ out.key("stores");
5332
+ out.begin("A", db.stores.length);
5333
+ for (const { meta, records } of db.stores) {
5334
+ out.begin("o");
5335
+ for (const [key, value] of Object.entries(meta)) out.value(key, value);
5336
+ out.key("records");
5337
+ const count = Array.isArray(records) ? records.length : records.size();
5338
+ out.begin("A", count);
5339
+ let written = 0;
5340
+ for (const record of Array.isArray(records) ? records : records.getAllRecords()) {
5341
+ let value = Array.isArray(records) ? await blobsToDisk(record.value) : record.value;
5342
+ if (meta.name === "links" && value && typeof value === "object" && "ratchetState" in value) {
5343
+ const { ratchetState: _ratchet, ...link } = value;
5344
+ value = link;
5345
+ }
5346
+ out.item([record.key, value]);
5347
+ if (++written % EXPORT_PAGE === 0) await out.flush();
5348
+ }
5349
+ if (written !== count) throw new Error("The store changed while it was exported: try again");
5350
+ out.end("A", count);
5351
+ out.end("o", Object.keys(meta).length + 1);
5352
+ }
5353
+ out.end("A", db.stores.length);
5354
+ out.end("o", 3);
5355
+ }
5356
+ out.end("A", databases.length);
5357
+ out.end("o", 2);
5358
+ await out.flush();
4988
5359
  } finally {
4989
5360
  reader?.db.close();
4990
5361
  }
4991
- return snapshot;
4992
5362
  }
4993
- async function snapshotToDisk() {
5363
+ async function snapshotToDisk(scrub = false) {
4994
5364
  await synced();
4995
5365
  const name = randomBytes(8).toString("hex");
4996
- const snapshot = await capture(name, false);
5366
+ const snapshot = await capture(name);
4997
5367
  if (trees) {
4998
5368
  trees.apply(seq);
5369
+ if (scrub) trees.scrub();
4999
5370
  trees.sync();
5000
5371
  }
5001
5372
  const temporary = snapshotPath + ".tmp";
@@ -5061,15 +5432,15 @@ async function openPersistentIndexedDb(dir, options = {}) {
5061
5432
  }
5062
5433
  const installed = globalThis;
5063
5434
  installed.indexedDB = factory;
5064
- installed.IDBKeyRange = IDBKeyRange;
5435
+ installed.IDBKeyRange = IDBKeyRange$1;
5065
5436
  return {
5066
5437
  factory,
5067
5438
  recovered: !replayed.closed,
5068
5439
  flush: () => queue,
5069
- async compact() {
5440
+ async compact(options) {
5070
5441
  await settled();
5071
5442
  let thrown = null;
5072
- await enqueue(() => writeSnapshot().catch((error) => {
5443
+ await enqueue(() => writeSnapshot(options?.scrub).catch((error) => {
5073
5444
  thrown = { error };
5074
5445
  throw error;
5075
5446
  }));
@@ -5090,18 +5461,9 @@ async function openPersistentIndexedDb(dir, options = {}) {
5090
5461
  journalBytes,
5091
5462
  async exportSnapshot(path) {
5092
5463
  await settled();
5093
- const snapshot = await capture(void 0, true);
5094
- for (const db of snapshot.databases) for (const store of db.stores) {
5095
- if (store.name !== "links") continue;
5096
- store.records = store.records.map(([key, value]) => {
5097
- if (!value || typeof value !== "object" || !("ratchetState" in value)) return [key, value];
5098
- const { ratchetState: _ratchet, ...link } = value;
5099
- return [key, link];
5100
- });
5101
- }
5102
5464
  const file = await open(path, "w", 384);
5103
5465
  try {
5104
- await file.writeFile(serialize(snapshot));
5466
+ await exportTo(file);
5105
5467
  await file.sync();
5106
5468
  } finally {
5107
5469
  await file.close();
@@ -5113,6 +5475,109 @@ async function openPersistentIndexedDb(dir, options = {}) {
5113
5475
  function writeAll(fd, bytes) {
5114
5476
  for (let at = 0; at < bytes.length;) at += writeSync(fd, bytes, at);
5115
5477
  }
5478
+ /**
5479
+ * A value v8 would serialize whole, written in pieces: the objects and arrays around the records begun and ended here
5480
+ * by hand, as v8 itself writes them, and the records serialized a page at a time, each page's bytes to `file`. A reader
5481
+ * gets what `deserialize` of `serialize(value)` gives (the bytes differ at most by v8's alignment padding before a
5482
+ * two-byte string, which it skips): any ghostly reads it.
5483
+ *
5484
+ * A serializer keeps every object it wrote (an object met again is written as the number it had): one for the whole
5485
+ * export held every record of it, as the snapshot built whole did. Each page has its own, so a reader's numbers are not
5486
+ * its numbers, and no value it writes may meet an object twice: one that would (`meetsTwice`, rare in a store's records)
5487
+ * is written as a copy in which each meeting is an object of its own (`unshared`).
5488
+ */
5489
+ var SnapshotWriter = class {
5490
+ file;
5491
+ serializer = new DefaultSerializer();
5492
+ seen = /* @__PURE__ */ new Set();
5493
+ constructor(file) {
5494
+ this.file = file;
5495
+ this.serializer.writeHeader();
5496
+ }
5497
+ /** An object ("o") or an array ("A", of `length` items). */
5498
+ begin(tag, length) {
5499
+ this.tag(tag);
5500
+ if (length !== void 0) this.serializer.writeUint32(length);
5501
+ }
5502
+ /** An object's end, with how many properties it has; an array's, with no other property and its length. */
5503
+ end(tag, count) {
5504
+ this.tag(tag === "o" ? "{" : "$");
5505
+ if (tag === "A") this.serializer.writeUint32(0);
5506
+ this.serializer.writeUint32(count);
5507
+ }
5508
+ key(name) {
5509
+ this.serializer.writeValue(name);
5510
+ }
5511
+ value(name, value) {
5512
+ this.key(name);
5513
+ this.item(value);
5514
+ }
5515
+ /** An array's item (a record), or an object's value. */
5516
+ item(value) {
5517
+ if (meetsTwice(value, this.seen)) {
5518
+ value = unshared(value);
5519
+ if (meetsTwice(value, this.seen)) throw new Error("A record of the store could not be written to a backup");
5520
+ }
5521
+ this.serializer.writeValue(value);
5522
+ }
5523
+ /** What is serialized so far, to the file; the next page has a serializer of its own. */
5524
+ async flush() {
5525
+ const bytes = this.serializer.releaseBuffer();
5526
+ this.serializer = new DefaultSerializer();
5527
+ this.seen = /* @__PURE__ */ new Set();
5528
+ for (let at = 0; at < bytes.length;) at += (await this.file.write(bytes, at)).bytesWritten;
5529
+ }
5530
+ tag(tag) {
5531
+ this.serializer.writeRawBytes(Buffer.from(tag, "latin1"));
5532
+ }
5533
+ };
5534
+ /**
5535
+ * Whether serializing `value` meets an object twice, or one in `seen` (met before by the same serializer): within a
5536
+ * value, an object held in two places, or in itself. Every object v8 walks into is walked here (an object's or an
5537
+ * array's own enumerable properties, a Map's and a Set's entries, an error's cause); the others hold none.
5538
+ */
5539
+ function meetsTwice(value, seen) {
5540
+ if (value === null || typeof value !== "object") return false;
5541
+ if (seen.has(value)) return true;
5542
+ seen.add(value);
5543
+ if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer || value instanceof Date || value instanceof RegExp) return false;
5544
+ if (value instanceof Map) {
5545
+ for (const [k, v] of value) if (meetsTwice(k, seen) || meetsTwice(v, seen)) return true;
5546
+ return false;
5547
+ }
5548
+ if (value instanceof Set) {
5549
+ for (const item of value) if (meetsTwice(item, seen)) return true;
5550
+ return false;
5551
+ }
5552
+ if (value instanceof Error && meetsTwice(value.cause, seen)) return true;
5553
+ for (const key of Object.keys(value)) if (meetsTwice(value[key], seen)) return true;
5554
+ return false;
5555
+ }
5556
+ /**
5557
+ * `value` with each place that holds an object holding a copy of its own: what a reader of it gets is the same, but for
5558
+ * which of its parts are one object. One that holds itself has no such copy, and is refused.
5559
+ */
5560
+ function unshared(value, path = /* @__PURE__ */ new Set()) {
5561
+ if (value === null || typeof value !== "object") return value;
5562
+ if (path.has(value)) throw new Error("A record of the store holds itself: it cannot be written to a backup");
5563
+ if (Buffer.isBuffer(value)) return Buffer.from(value);
5564
+ if (value instanceof DataView) return new DataView(value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength));
5565
+ if (ArrayBuffer.isView(value)) return value.slice();
5566
+ if (value instanceof ArrayBuffer) return value.slice(0);
5567
+ if (value instanceof Date) return new Date(value);
5568
+ if (value instanceof RegExp) return new RegExp(value);
5569
+ if (value instanceof Error) return structuredClone(value);
5570
+ path.add(value);
5571
+ try {
5572
+ if (value instanceof Map) return new Map([...value].map(([k, v]) => [unshared(k, path), unshared(v, path)]));
5573
+ if (value instanceof Set) return new Set([...value].map((item) => unshared(item, path)));
5574
+ const out = Array.isArray(value) ? new Array(value.length) : {};
5575
+ for (const key of Object.keys(value)) out[key] = unshared(value[key], path);
5576
+ return out;
5577
+ } finally {
5578
+ path.delete(value);
5579
+ }
5580
+ }
5116
5581
  /** A journal entry as it is on disk: its length, then its bytes. */
5117
5582
  function framed(entry) {
5118
5583
  const header = Buffer.alloc(4);
@@ -5256,24 +5721,6 @@ function readWithoutCopy(classes) {
5256
5721
  return values;
5257
5722
  };
5258
5723
  }
5259
- /** Transactions whose last event is out, by database, and dropped from its list at the next turn: all at once. */
5260
- var ended = /* @__PURE__ */ new WeakMap();
5261
- /** A finished transaction's place in its database's list, given back: one walk of the list for all that ended in a turn. */
5262
- function dropEnded(db, transaction) {
5263
- let gone = ended.get(db);
5264
- if (gone) {
5265
- gone.add(transaction);
5266
- return;
5267
- }
5268
- ended.set(db, gone = /* @__PURE__ */ new Set([transaction]));
5269
- setImmediate(() => {
5270
- ended.delete(db);
5271
- const list = db.transactions;
5272
- let kept = 0;
5273
- for (const held of list) if (!gone.has(held)) list[kept++] = held;
5274
- list.length = kept;
5275
- });
5276
- }
5277
5724
  /** The classes whose scheduler starts every transaction it can in one pass: shared by every store opened. */
5278
5725
  var onePass = /* @__PURE__ */ new WeakSet();
5279
5726
  /**
@@ -5681,7 +6128,7 @@ function watch(store) {
5681
6128
  return change;
5682
6129
  }
5683
6130
  function keyToDisk(key) {
5684
- if (key instanceof IDBKeyRange) return { [RANGE]: {
6131
+ if (key instanceof IDBKeyRange$1) return { [RANGE]: {
5685
6132
  lower: key.lower,
5686
6133
  upper: key.upper,
5687
6134
  lowerOpen: key.lowerOpen,
@@ -5692,9 +6139,9 @@ function keyToDisk(key) {
5692
6139
  function keyFromDisk(key) {
5693
6140
  const range = key?.[RANGE];
5694
6141
  if (!range) return key;
5695
- if (range.lower === void 0) return IDBKeyRange.upperBound(range.upper, range.upperOpen);
5696
- if (range.upper === void 0) return IDBKeyRange.lowerBound(range.lower, range.lowerOpen);
5697
- return IDBKeyRange.bound(range.lower, range.upper, range.lowerOpen, range.upperOpen);
6142
+ if (range.lower === void 0) return IDBKeyRange$1.upperBound(range.upper, range.upperOpen);
6143
+ if (range.upper === void 0) return IDBKeyRange$1.lowerBound(range.lower, range.lowerOpen);
6144
+ return IDBKeyRange$1.bound(range.lower, range.upper, range.lowerOpen, range.upperOpen);
5698
6145
  }
5699
6146
  function hasBlob(value, depth = 0) {
5700
6147
  if (value instanceof Blob) return true;
@@ -5810,8 +6257,7 @@ function safe(read) {
5810
6257
  return "";
5811
6258
  }
5812
6259
  }
5813
- //#endregion
5814
- //#region src/runtime/engine.ts
6260
+ // src/runtime/engine.ts
5815
6261
  setPublicKeyFastPath(nativePublicKey);
5816
6262
  /**
5817
6263
  * The HyperDHT network: `GHOSTLY_HYPERDHT_BOOTSTRAP` ("host:port,…") replaces the public bootstrap nodes, as it does
@@ -5922,6 +6368,7 @@ async function installWebRtc() {
5922
6368
  "RTCPeerConnectionIceEvent",
5923
6369
  "RTCCertificate"
5924
6370
  ]) scope[name] ??= polyfill[name];
6371
+ countConnections(scope);
5925
6372
  refuseDataAnswers(scope);
5926
6373
  if (!publicStun()) leaveOutPublicStun(scope);
5927
6374
  return true;
@@ -5930,6 +6377,27 @@ async function installWebRtc() {
5930
6377
  return false;
5931
6378
  }
5932
6379
  }
6380
+ /** Each connection the engine makes is counted until it is closed, so libdatachannel's threads go with the last (`rtcThreads`). */
6381
+ function countConnections(scope) {
6382
+ const Base = scope.RTCPeerConnection;
6383
+ scope.RTCPeerConnection = class extends Base {
6384
+ #closed;
6385
+ constructor(config) {
6386
+ super(config);
6387
+ this.#closed = rtcThreads.opened();
6388
+ this.addEventListener("connectionstatechange", () => {
6389
+ if (this.connectionState === "closed") this.#closed();
6390
+ });
6391
+ }
6392
+ close() {
6393
+ try {
6394
+ super.close();
6395
+ } finally {
6396
+ this.#closed();
6397
+ }
6398
+ }
6399
+ };
6400
+ }
5933
6401
  /**
5934
6402
  * For tests: `GHOSTLY_TEST_REFUSE_DATA_ANSWERS=<n>` refuses one in every n answers this process applies to its offers
5935
6403
  * (the first, the n+1st, and so on), as libdatachannel 0.24.5 refuses one in its race (`ANSWER_REFUSED_REDIALS` in
@@ -6012,16 +6480,17 @@ async function startRuntime(paths, options = {}) {
6012
6480
  const dht = mainlineNetwork();
6013
6481
  const trace = process.env.GHOSTLY_LINK_TRACE;
6014
6482
  if (trace) setLinkTraceSink((line) => appendFileSync(trace, line + "\n", { mode: 384 }));
6015
- if (trace || options.logJoins) (await import("./joinTrace-D-fnt2p3.js")).setJoinTraceSink((line) => {
6483
+ if (trace || options.logJoins) (await import("./joinTrace-CBr1jbch.js")).setJoinTraceSink((line) => {
6016
6484
  if (trace) appendFileSync(trace, line + "\n", { mode: 384 });
6017
6485
  const said = options.logJoins ? joinLogLine(line) : null;
6018
6486
  if (said) process.stderr.write(said + "\n");
6019
6487
  });
6488
+ for (const name of existsSync(paths.db) ? readdirSync(paths.db) : []) if (/^backup-store-.*\.bin$/.test(name)) rmSync(join(paths.db, name), { force: true });
6020
6489
  const store = await openPersistentIndexedDb(paths.db);
6021
6490
  const restored = join(paths.dir, RESTORED_MARK);
6022
6491
  if (existsSync(restored)) {
6023
6492
  try {
6024
- const rows = await import("./restoredRows-C3LcxmOw.js");
6493
+ const rows = await import("./restoredRows-D_WSHE7H.js");
6025
6494
  await rows.markRestoredWallet();
6026
6495
  await rows.markLeftOutFiles(leftOutIn(restored));
6027
6496
  await rows.forgetRatchets();
@@ -6037,15 +6506,15 @@ async function startRuntime(paths, options = {}) {
6037
6506
  const callsUnavailable = typeof stack === "string" ? stack : null;
6038
6507
  installFileFetch();
6039
6508
  const testMints = process.env.GHOSTLY_TEST_MINTS;
6040
- if (testMints) (await import("./mints-BaOmx517.js")).declareTestMints(testMints.split(","));
6509
+ if (testMints) (await import("./mints-BcBODVVW.js")).declareTestMints(testMints.split(","));
6041
6510
  await installEventSource();
6042
6511
  await preloadWalletModules();
6043
- (await import("./ghostly_iroh_web-BzAXJUYH.js")).initSync({ module: irohWasmBytes() });
6044
- const [{ registerFileBytes }, { NodeFileBytes }] = await Promise.all([import("./fileBytes-BtIyoDF2.js"), import("./fileBytes-B0z9A6Le.js")]);
6512
+ (await import("./ghostly_iroh_web-DIj5xGmR.js")).initSync({ module: irohWasmBytes() });
6513
+ const [{ registerFileBytes }, { NodeFileBytes }] = await Promise.all([import("./fileBytes-CCKbwqG_.js"), import("./fileBytes-tj6-VZcB.js")]);
6045
6514
  registerFileBytes("native", async () => new NodeFileBytes(paths.files), true);
6046
- if (await (await import("./blobFiles-BmsrvZc3.js")).moveBlobFiles()) await store.compact();
6047
- const [{ EngineServer }, { createHyperEndpoint }] = await Promise.all([import("./server-Q3VcNqGt.js"), import("./endpoint-DarqblYE.js")]);
6048
- const mainline = dht.off ? null : new (await (import("./mainline-Cu61qcPS.js"))).Mainline({
6515
+ if (await (await import("./blobFiles-DDs34n0r.js")).moveBlobFiles()) await store.compact();
6516
+ const [{ EngineServer }, { createHyperEndpoint }] = await Promise.all([import("./server-CQR7NLCz.js"), import("./endpoint-B0vE5ojY.js")]);
6517
+ const mainline = dht.off ? null : new (await (import("./mainline-CVrd0C1n.js"))).Mainline({
6049
6518
  bootstrap: dht.bootstrap,
6050
6519
  host: dht.host
6051
6520
  });
@@ -6053,7 +6522,7 @@ async function startRuntime(paths, options = {}) {
6053
6522
  ...pinned ? { relays: pinned } : {},
6054
6523
  ...relayBudgetForTests()
6055
6524
  };
6056
- const transport = mainline || pinned ? new (await (import("./mainline-Cu61qcPS.js"))).RelaysAndDht(mainline, relayOptions, !!pinned) : null;
6525
+ const transport = mainline || pinned ? new (await (import("./mainline-CVrd0C1n.js"))).RelaysAndDht(mainline, relayOptions, !!pinned) : null;
6057
6526
  const apps = servedApps(paths.dir).length > 0;
6058
6527
  const server = new EngineServer({
6059
6528
  ...transport ? { transport } : {},
@@ -6109,8 +6578,7 @@ async function startRuntime(paths, options = {}) {
6109
6578
  })()
6110
6579
  };
6111
6580
  }
6112
- //#endregion
6113
- //#region src/host.ts
6581
+ // src/host.ts
6114
6582
  /**
6115
6583
  * The most a connection may leave unread (answers and events the daemon wrote that its client has not taken): past
6116
6584
  * it, the connection ends. A `listen` stopped with Ctrl+Z, or a client that stops reading, kept every later event in
@@ -6131,6 +6599,7 @@ var BASELINE_NEWEST = 100;
6131
6599
  */
6132
6600
  async function openHost(paths, mode, version, options = {}) {
6133
6601
  ownProfile(paths.dir);
6602
+ const socketDir = mode === "daemon" ? callSocketDir() : void 0;
6134
6603
  const locked = acquireLock(paths);
6135
6604
  const unmark = mode === "daemon" ? markStarting(paths) : () => {};
6136
6605
  const release = () => {
@@ -6157,33 +6626,63 @@ async function openHost(paths, mode, version, options = {}) {
6157
6626
  const hub = new EventHub(paths.events);
6158
6627
  let calls;
6159
6628
  try {
6160
- await hub.open();
6161
- const node = runtime.server.node;
6162
- const now = node.getState();
6163
- const mark = runtime.server.historyMark;
6164
- const histories = /* @__PURE__ */ new Map(), newest = /* @__PURE__ */ new Map();
6629
+ const { server, store } = runtime, node = server.node;
6630
+ const closed = !store.recovered;
6631
+ const oneByOne = mode === "one-shot" && closed;
6632
+ await hub.open({ seen: !oneByOne });
6633
+ const perChat = oneByOne && await hub.loadOwnNotes();
6634
+ if (oneByOne && !perChat) await hub.loadSeen();
6635
+ const kept = server.takeStartNewest();
6165
6636
  const whole = (id) => id.startsWith("group:") ? node.groupMessages({ groupId: id.slice(6) }) : node.getMessages(id);
6166
- const closed = !runtime.store.recovered;
6167
- const kept = runtime.server.takeStartNewest();
6168
- for (const id of [...now.links.map((link) => link.id), ...now.groups.map((group) => `group:${group.id}`)]) {
6169
- const page = closed && !runtime.server.historyChanged(id) ? kept.get(id) ?? await node.messagePage({
6170
- linkId: id,
6171
- limit: 100
6172
- }) : null;
6173
- if (page && !page.more) histories.set(id, page.messages);
6174
- else if (page && hub.inStep(id, page.messages)) newest.set(id, page.messages);
6175
- else histories.set(id, await whole(id));
6176
- }
6177
- hub.baseline(now, histories, {
6178
- newest,
6179
- files: (id) => node.fileMessages(id)
6180
- });
6181
- await hub.ended((id) => fileStore.get(id));
6182
- announceJoins(hub, node);
6637
+ const baseline = async () => {
6638
+ const now = node.getState();
6639
+ const mark = server.historyMark;
6640
+ const histories = /* @__PURE__ */ new Map(), newest = /* @__PURE__ */ new Map();
6641
+ for (const id of [...now.links.map((link) => link.id), ...now.groups.map((group) => `group:${group.id}`)]) {
6642
+ const page = closed && !server.historyChanged(id) ? kept.get(id) ?? await node.messagePage({
6643
+ linkId: id,
6644
+ limit: 100
6645
+ }) : null;
6646
+ if (page && !page.more) histories.set(id, page.messages);
6647
+ else if (page && hub.inStep(id, page.messages)) newest.set(id, page.messages);
6648
+ else histories.set(id, await whole(id));
6649
+ }
6650
+ hub.baseline(now, histories, {
6651
+ newest,
6652
+ files: (id) => node.fileMessages(id)
6653
+ });
6654
+ await hub.ended((id) => fileStore.get(id));
6655
+ announceJoins(hub, node);
6656
+ return {
6657
+ mark,
6658
+ ids: [...histories.keys(), ...newest.keys()]
6659
+ };
6660
+ };
6661
+ let read;
6662
+ if (perChat) {
6663
+ const now = node.getState();
6664
+ const ids = [...now.links.map((link) => link.id), ...now.groups.map((group) => `group:${group.id}`)];
6665
+ read = {
6666
+ mark: server.historyMark,
6667
+ ids
6668
+ };
6669
+ const untouched = new Set(ids.filter((id) => !server.historyChanged(id)));
6670
+ hub.perChat(now, {
6671
+ newest: async (id) => untouched.has(id) ? kept.get(id) ?? await node.messagePage({
6672
+ linkId: id,
6673
+ limit: 100
6674
+ }) : null,
6675
+ whole,
6676
+ files: (id) => node.fileMessages(id)
6677
+ });
6678
+ await hub.ended((id) => fileStore.get(id));
6679
+ announceJoins(hub, node);
6680
+ } else read = await baseline();
6183
6681
  calls = new CallManager({
6184
6682
  engine: node,
6185
6683
  emit: (type, id, fields) => hub.emit(type, id, fields),
6186
6684
  profileDir: paths.dir,
6685
+ socketDir,
6187
6686
  answers: mode === "daemon"
6188
6687
  });
6189
6688
  const manager = calls;
@@ -6196,10 +6695,7 @@ async function openHost(paths, mode, version, options = {}) {
6196
6695
  });
6197
6696
  groupAuto = joiner;
6198
6697
  hub.onState((s) => joiner.check(s));
6199
- runtime.server.attach(hub.sink, {
6200
- mark,
6201
- ids: [...histories.keys(), ...newest.keys()]
6202
- });
6698
+ server.attach(hub.sink, read);
6203
6699
  joiner.check(node.getState());
6204
6700
  if (mode === "daemon") {
6205
6701
  const said = new DaemonPresence(node);
@@ -6233,6 +6729,7 @@ async function openHost(paths, mode, version, options = {}) {
6233
6729
  });
6234
6730
  presence?.stop();
6235
6731
  runtime.server.detach(hub.sink);
6732
+ await hub.caughtUp();
6236
6733
  hub.release();
6237
6734
  await runtime.close().catch(() => {});
6238
6735
  release();
@@ -6275,8 +6772,8 @@ async function serve(host) {
6275
6772
  return {
6276
6773
  server,
6277
6774
  close: () => closing ??= new Promise((resolve) => {
6278
- removeDaemonSecret(ctx.runtime.paths.dir);
6279
6775
  server.close(() => resolve());
6776
+ removeDaemonSecret(ctx.runtime.paths.dir);
6280
6777
  stopping.abort();
6281
6778
  within(Promise.all(answering), STOP_ANSWERS_MS).then(() => {
6282
6779
  for (const socket of sockets) socket.end();
@@ -6358,6 +6855,8 @@ function connection(ctx, socket, secret, answering) {
6358
6855
  const unsubscribe = () => {
6359
6856
  for (const off of unsubscribes.splice(0)) off();
6360
6857
  };
6858
+ const gone = new AbortController();
6859
+ socket.on("close", () => gone.abort());
6361
6860
  const write = (value, replayed = false) => {
6362
6861
  if (socket.destroyed || socket.writableEnded) return;
6363
6862
  if (!replayed && socket.writableLength > limit) {
@@ -6396,6 +6895,13 @@ function connection(ctx, socket, secret, answering) {
6396
6895
  });
6397
6896
  return;
6398
6897
  }
6898
+ if (typeof request !== "object" || request === null || Array.isArray(request)) {
6899
+ write({
6900
+ id: null,
6901
+ error: new CliError("bad_request", "A request is a JSON object: {\"id\", \"method\", \"params\"}").toJSON()
6902
+ });
6903
+ return;
6904
+ }
6399
6905
  const id = typeof request.id === "number" || typeof request.id === "string" ? request.id : null;
6400
6906
  if (typeof request.method !== "string") {
6401
6907
  write({
@@ -6462,7 +6968,7 @@ function connection(ctx, socket, secret, answering) {
6462
6968
  for (const event of queued) if (event.seq > last) write({ event });
6463
6969
  return;
6464
6970
  }
6465
- const answered = callApi(ctx, request.method, request.params ?? {}).then((result) => write({
6971
+ const answered = callApi(ctx, request.method, request.params ?? {}, { gone: gone.signal }).then((result) => write({
6466
6972
  id,
6467
6973
  result: result ?? null
6468
6974
  }), (error) => write({
@@ -6473,7 +6979,6 @@ function connection(ctx, socket, secret, answering) {
6473
6979
  answered.then(() => answering.delete(answered));
6474
6980
  });
6475
6981
  }
6476
- //#endregion
6477
6982
  export { BASELINE_NEWEST, MAX_UNREAD, STOP_ANSWERS_MS, keepServing, openHost, serve };
6478
6983
 
6479
- //# sourceMappingURL=host-CYlIiY3r.js.map
6984
+ //# sourceMappingURL=host-z0FAHP9Z.js.map