@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 +1 @@
1
- {"version":3,"file":"blobFiles-BmsrvZc3.js","names":[],"sources":["../../src/runtime/blobFiles.ts"],"sourcesContent":["import { fileBytes } from \"@ghostly/browser/shared/fileBytes\";\nimport { fileStore } from \"@ghostly/browser/shared/idb\";\n\n/** Files moved at once: their Blobs are in memory already, and each one is read and written a step at a time. */\nconst AT_ONCE = 4;\n\n/**\n * Files a profile took before every received file went to file storage (held files, hold/1, up to 1.3.0): their bytes\n * are a Blob in their record, which the store keeps in memory and writes whole into `snapshot.bin` (100 MB for 24\n * pictures), read back at every start and one-shot. Each one goes to the profile's files folder, then its record says so\n * and drops the Blob. Called before the engine starts; a file that fails stays as it was, and goes at the next start.\n * Resolves to how many moved: the caller folds the store's journal into a small snapshot then.\n */\nexport async function moveBlobFiles(): Promise<number> {\n const ids = await fileStore.blobIds();\n if (!ids.length) return 0;\n const storage = await fileBytes();\n let moved = 0;\n const move = async (id: string) => {\n const file = await fileStore.get(id);\n // Its size is read off its metadata once the Blob is gone (`storedSize`): one without stays as it is.\n if (!file?.blob || file.metadata?.size !== file.blob.size) return;\n try {\n await storage.stage(id, file.blob);\n if (await fileStore.movedToBytes(id, storage.kind)) moved++;\n else await storage.remove(id);\n } catch {\n await storage.remove(id).catch(() => {});\n }\n };\n for (let i = 0; i < ids.length; i += AT_ONCE) await Promise.all(ids.slice(i, i + AT_ONCE).map(move));\n return moved;\n}\n"],"mappings":";;;;AAIA,IAAM,UAAU;;;;;;;;AAShB,eAAsB,gBAAiC;CACrD,MAAM,MAAM,MAAM,UAAU,QAAQ;CACpC,IAAI,CAAC,IAAI,QAAQ,OAAO;CACxB,MAAM,UAAU,MAAM,UAAU;CAChC,IAAI,QAAQ;CACZ,MAAM,OAAO,OAAO,OAAe;EACjC,MAAM,OAAO,MAAM,UAAU,IAAI,EAAE;EAEnC,IAAI,CAAC,MAAM,QAAQ,KAAK,UAAU,SAAS,KAAK,KAAK,MAAM;EAC3D,IAAI;GACF,MAAM,QAAQ,MAAM,IAAI,KAAK,IAAI;GACjC,IAAI,MAAM,UAAU,aAAa,IAAI,QAAQ,IAAI,GAAG;QAC/C,MAAM,QAAQ,OAAO,EAAE;EAC9B,QAAQ;GACN,MAAM,QAAQ,OAAO,EAAE,CAAC,CAAC,YAAY,CAAC,CAAC;EACzC;CACF;CACA,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK,SAAS,MAAM,QAAQ,IAAI,IAAI,MAAM,GAAG,IAAI,OAAO,CAAC,CAAC,IAAI,IAAI,CAAC;CACnG,OAAO;AACT"}
1
+ {"version":3,"file":"blobFiles-DDs34n0r.js","names":[],"sources":["../../src/runtime/blobFiles.ts"],"sourcesContent":["import { fileBytes } from \"@ghostly/browser/shared/fileBytes\";\nimport { fileStore } from \"@ghostly/browser/shared/idb\";\n\n/** Files moved at once: their Blobs are in memory already, and each one is read and written a step at a time. */\nconst AT_ONCE = 4;\n\n/**\n * Files a profile took before every received file went to file storage (held files, hold/1, up to 1.3.0): their bytes\n * are a Blob in their record, which the store keeps in memory and writes whole into `snapshot.bin` (100 MB for 24\n * pictures), read back at every start and one-shot. Each one goes to the profile's files folder, then its record says so\n * and drops the Blob. Called before the engine starts; a file that fails stays as it was, and goes at the next start.\n * Resolves to how many moved: the caller folds the store's journal into a small snapshot then.\n */\nexport async function moveBlobFiles(): Promise<number> {\n const ids = await fileStore.blobIds();\n if (!ids.length) return 0;\n const storage = await fileBytes();\n let moved = 0;\n const move = async (id: string) => {\n const file = await fileStore.get(id);\n // Its size is read off its metadata once the Blob is gone (`storedSize`): one without stays as it is.\n if (!file?.blob || file.metadata?.size !== file.blob.size) return;\n try {\n await storage.stage(id, file.blob);\n if (await fileStore.movedToBytes(id, storage.kind)) moved++;\n else await storage.remove(id);\n } catch {\n await storage.remove(id).catch(() => {});\n }\n };\n for (let i = 0; i < ids.length; i += AT_ONCE) await Promise.all(ids.slice(i, i + AT_ONCE).map(move));\n return moved;\n}\n"],"mappings":";;;;AAIA,IAAM,UAAU;;;;;;;;AAShB,eAAsB,gBAAiC;CACrD,MAAM,MAAM,MAAM,UAAU,QAAQ;CACpC,IAAI,CAAC,IAAI,QAAQ,OAAO;CACxB,MAAM,UAAU,MAAM,UAAU;CAChC,IAAI,QAAQ;CACZ,MAAM,OAAO,OAAO,OAAe;EACjC,MAAM,OAAO,MAAM,UAAU,IAAI,EAAE;EAEnC,IAAI,CAAC,MAAM,QAAQ,KAAK,UAAU,SAAS,KAAK,KAAK,MAAM;EAC3D,IAAI;GACF,MAAM,QAAQ,MAAM,IAAI,KAAK,IAAI;GACjC,IAAI,MAAM,UAAU,aAAa,IAAI,QAAQ,IAAI,GAAG;QAC/C,MAAM,QAAQ,OAAO,EAAE;EAC9B,QAAQ;GACN,MAAM,QAAQ,OAAO,EAAE,CAAC,CAAC,YAAY,CAAC,CAAC;EACzC;CACF;CACA,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK,SAAS,MAAM,QAAQ,IAAI,IAAI,MAAM,GAAG,IAAI,OAAO,CAAC,CAAC,IAAI,IAAI,CAAC;CACnG,OAAO;AACT"}
@@ -0,0 +1 @@
1
+ export { r as buttonsOf } from "./buttons-BvWqHJeh.js";
@@ -1,9 +1,10 @@
1
- import { Cd as toBase64Url, Io as buttonLabelClash, Mo as STATUS_CARD_LIMITS, Ni as BUTTONS_CAPABILITY, Sd as randomBytes, Ss as LIMITS, To as BUTTON_STYLES, zo as checkStatusCard } from "./src-DjVj2ynY.js";
2
- import { n as secretWords, r as findSecret } from "./secretGuard-B7Hj0Kvz.js";
3
- import { t as CliError } from "./errors-Dt-ZnyOX.js";
4
- import { C as nobodyJoinedChat, D as oneShotWaits, E as oneOf, N as state, P as str, T as num, _ as messageOf, r as chatOrGroup, t as bool, w as node, x as noMessage } from "./apiKit-DesObIDf.js";
5
- import { n as goesOn$1 } from "./waitNotice-Cn0WJ-He.js";
6
- //#region src/waits.ts
1
+ import { an as BUTTONS_CAPABILITY, br as buttonLabelClash, gr as STATUS_CARD_LIMITS, ji as LIMITS, lr as BUTTON_STYLES, wr as checkStatusCard } from "./groupMeta-DTQAJG50.js";
2
+ import { l as toBase64Url, s as randomBytes } from "./bytes-C1DNGY18.js";
3
+ import { D as oneOf, E as num, L as str, O as oneShotWaits, S as noMessage, T as node, d as groupById, r as chatOrGroup, t as bool, v as messageOf, w as nobodyJoinedChat } from "./apiKit-CVaEzKWQ.js";
4
+ import { t as CliError } from "./errors-DDLFO4Gf.js";
5
+ import { n as secretWords, r as findSecret } from "./secretGuard-B4-LlMjv.js";
6
+ import { n as goesOn$1 } from "./waitNotice-BGM0QOS2.js";
7
+ // src/waits.ts
7
8
  var DELIVERY_RANK = {
8
9
  sending: 0,
9
10
  waiting: 1,
@@ -59,24 +60,46 @@ async function waitForRemoval(ctx, chat, messageId, ms) {
59
60
  await new Promise((resolve) => setTimeout(resolve, 250));
60
61
  }
61
62
  }
63
+ /** How long `purgeMessage` waits for the engine to take the message's row out: it does so in a few milliseconds. */
64
+ var PURGE_WAIT_MS = 5e3;
65
+ /**
66
+ * `message delete --purge`: once the message's row is gone (the engine takes it out on later turns, its files first),
67
+ * the replies that quote it lose its line (a delete here leaves it in their rows, one for everyone to a sweep within
68
+ * 10 s), then the store's journal is folded into a fresh snapshot now, not within the hour of the fold that comes by
69
+ * itself: what the message said leaves rows.db, `db/journal.bin` and rows.db's WAL before the command answers. For a
70
+ * secret pasted into a chat; every delete folding would rewrite the snapshot each time. `message`: its row, read
71
+ * before the delete.
72
+ */
73
+ async function purgeMessage(ctx, message) {
74
+ const { linkId: chat, id: messageId } = message;
75
+ const until = performance.now() + PURGE_WAIT_MS;
76
+ let gone = !await node(ctx).getMessage(chat, messageId);
77
+ while (!gone && performance.now() < until) {
78
+ await new Promise((resolve) => setTimeout(resolve, 20));
79
+ gone = !await node(ctx).getMessage(chat, messageId);
80
+ }
81
+ if (gone) await node(ctx).forgetQuotesOf(message);
82
+ await ctx.runtime.store.compact({ scrub: true });
83
+ if (!gone) throw new CliError("timeout", `Timed out after ${PURGE_WAIT_MS / 1e3} s: the message is deleted, but what it said may stay in the profile's store until its next fold (within the hour)`, {
84
+ messageId,
85
+ deleted: messageId
86
+ });
87
+ }
62
88
  /**
63
89
  * A private group with no member but me (they all left, or nobody accepted an invitation yet): what I send there now
64
90
  * reaches nobody, not even a member who joins later (a joiner reads nothing from before). A community's roster may not
65
91
  * list every member yet, so only a private group counts.
66
92
  */
67
- var nobodyElseIn = (ctx, groupId) => {
68
- const group = state(ctx).groups?.find((g) => g.id === groupId);
69
- return group?.profile === "mesh" && !group.members.some((m) => !m.me);
70
- };
93
+ var nobodyElseIn = (ctx, groupId) => alone(groupIn(ctx, groupId));
94
+ /** A group as the engine shows it, built alone: `getState()` builds a view of every chat, once per poll. */
95
+ var groupIn = (ctx, groupId) => groupById(ctx, groupId);
96
+ var alone = (group) => group?.profile === "mesh" && !group.members.some((m) => !m.me);
71
97
  /**
72
98
  * Why I am no longer in a group (removed, say), or null while I am. A member removed while away learns it only after
73
99
  * it is back, so what it sent in between is never taken, and from then on nothing goes. A community's `lost` is not
74
100
  * out: it asks to be let in again by itself.
75
101
  */
76
- var outOf = (ctx, groupId) => {
77
- const group = state(ctx).groups?.find((g) => g.id === groupId);
78
- return group?.status && group.status !== "active" && group.status !== "lost" ? group.statusReason ?? "You are not in this group" : null;
79
- };
102
+ var outOf = (group) => group?.status && group.status !== "active" && group.status !== "lost" ? group.statusReason ?? "You are not in this group" : null;
80
103
  /**
81
104
  * Waits until an edge took my group message, or its edit number `edit`, or my reaction to it numbered `reaction`, or my
82
105
  * pin numbered `pin` (WISP 902: a group has no receipts, so this is as far as the author sees): a member's edge in a
@@ -94,8 +117,10 @@ async function waitForGroupFrame(ctx, groupId, messageId, edit, ms) {
94
117
  messageId,
95
118
  ...which
96
119
  });
97
- if (taken > 0 || nobodyElseIn(ctx, groupId)) return taken;
98
- const out = outOf(ctx, groupId);
120
+ if (taken > 0) return taken;
121
+ const group = groupIn(ctx, groupId);
122
+ if (alone(group)) return taken;
123
+ const out = outOf(group);
99
124
  if (out) throw new CliError("refused", `${out}: no member took it, and it no longer goes`, {
100
125
  messageId,
101
126
  ..."edit" in which ? { edits: which.edit } : which
@@ -181,8 +206,7 @@ async function waitForDelivery(ctx, chat, messageId, target, ms) {
181
206
  }
182
207
  });
183
208
  }
184
- //#endregion
185
- //#region src/textSize.ts
209
+ // src/textSize.ts
186
210
  /**
187
211
  * A text past what a chat or a group carries (16 KiB of UTF-8, as the engine counts it: trimmed) is refused before the
188
212
  * secret guard reads it and before the engine is asked, with its size and the bound, as `send` and `edit` refuse it.
@@ -194,8 +218,7 @@ function checkTextSize(text) {
194
218
  max: LIMITS.maxChatMessageBytes
195
219
  });
196
220
  }
197
- //#endregion
198
- //#region src/buttons.ts
221
+ // src/buttons.ts
199
222
  /**
200
223
  * `--button id:Label` (again for each, 1 to 6), `--style id=primary|neutral|danger`, `--once` and `--id`, as the
201
224
  * method's parameters: `buttons` and `buttonsId`. Nothing when no `--button` is given. The label may hold colons: the
@@ -287,6 +310,7 @@ async function updateButtons(ctx, params) {
287
310
  const close = bool(params, "close");
288
311
  const newText = str(params, "text");
289
312
  if (chosen === void 0 && !close && newText === void 0) throw new CliError("bad_request", "Nothing to update: give chosen, close or text");
313
+ if (newText !== void 0 && !newText.trim()) throw new CliError("bad_request", "The new text is blank: give the question's new words, or leave text out to keep them");
290
314
  if (newText !== void 0) checkTextSize(newText);
291
315
  if (newText !== void 0 && !bool(params, "force")) {
292
316
  const secret = findSecret(newText);
@@ -397,7 +421,6 @@ var BUTTON_METHODS = {
397
421
  /** WISP 406 · Message Buttons: the answer chosen on a question of mine, its buttons closed, or its text changed. */
398
422
  "button.update": updateButtons
399
423
  };
400
- //#endregion
401
- export { checkTextSize as a, waitForConfirmed as c, waitForMessage as d, waitForRemoval as f, pressable as i, waitForEdit as l, buttonsCard as n, goesOn as o, buttonsOf as r, nobodyElseIn as s, BUTTON_METHODS as t, waitForGroupFrame as u };
424
+ export { checkTextSize as a, outOf as c, waitForEdit as d, waitForGroupFrame as f, pressable as i, purgeMessage as l, waitForRemoval as m, buttonsCard as n, goesOn as o, waitForMessage as p, buttonsOf as r, nobodyElseIn as s, BUTTON_METHODS as t, waitForConfirmed as u };
402
425
 
403
- //# sourceMappingURL=buttons-fZTEa_2i.js.map
426
+ //# sourceMappingURL=buttons-BvWqHJeh.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buttons-BvWqHJeh.js","names":["goesOnIn"],"sources":["../../src/waits.ts","../../src/textSize.ts","../../src/buttons.ts"],"sourcesContent":["import type { GroupView, StoredMessage } from \"@ghostly/browser/shared/types\";\nimport { groupById, noMessage, nobodyJoinedChat, node, type ApiContext } from \"./apiKit\";\nimport { CliError } from \"./errors\";\nimport type { GhostlyEvent } from \"./events\";\nimport { goesOn as goesOnIn } from \"./waitNotice\";\n\n/*\n * Waiting on what a command sent (WISP 1100): a message's delivery, an edit's confirmation, a group frame taken by an\n * edge. Shared by the chat, group and status card methods. A deadline counts on `performance.now()`: on `Date.now()`\n * a wall clock set back while a wait ran (NTP, a person fixing the time) stretched it by as much, past the client's\n * own deadline, which told the bot to restart a sound daemon.\n */\n\nconst DELIVERY_RANK: Record<string, number> = { sending: 0, waiting: 1, queued: 1, held: 2, sent: 2, delivered: 3 };\n\n/**\n * What a timed-out wait says of what happens next: a daemon goes on, a one-shot's profile closes now. A one-shot's\n * `edit` and `group edit` said \"while this profile is online\" too, as it was about to leave. Ctrl-C says the same.\n * On a chat nobody joined yet nothing goes before they do: it said \"goes with this profile's next command\".\n */\nexport const goesOn = (ctx: ApiContext, chat?: string) => chat !== undefined && nobodyJoinedChat(ctx, chat)\n ? `goes once the contact joins this chat (nobody has yet)${ctx.mode === \"one-shot\" ? \" while this profile is online (`ghostly daemon --detach`)\" : \"\"}`\n : ctx.mode === \"daemon\" && stopped(ctx) ? \"goes by itself once this profile is online again\" : goesOnIn(ctx.mode);\n\n/**\n * A daemon that stops (`ApiContext.stopping`) ends every wait still open at once, with what it knows, as a timeout:\n * what was asked is done and goes on by itself. Its connections ended under the waits before, and the command failed\n * as `unavailable` \"The daemon went away\" with no `messageId`: a bot that sent again sent the message twice.\n */\nconst stopped = (ctx: ApiContext) => ctx.stopping?.aborted === true;\n\n/** How a wait that ends short of its aim begins: its time ran out, or the daemon stopped under it. */\nconst ended = (ctx: ApiContext, ms: number) => stopped(ctx) ? \"The daemon stopped before the wait ended\" : `Timed out after ${Math.round(ms / 1000)} s`;\n\n/** A timed-out wait's details, and `reason: \"daemon-stopped\"` when the daemon's stop ended it. */\nconst known = (ctx: ApiContext, details: Record<string, unknown>) => stopped(ctx) ? { ...details, reason: \"daemon-stopped\" } : details;\n\n/** Waits until the contact confirmed the latest edit of one of my messages (it is no longer pending). */\nexport async function waitForEdit(ctx: ApiContext, chat: string, messageId: string, ms: number): Promise<StoredMessage> {\n const until = performance.now() + ms;\n for (;;) {\n const message = await node(ctx).getMessage(chat, messageId);\n if (!message) throw noMessage(messageId, { group: false, ref: chat });\n if (!message.edit?.pending) return message;\n if (performance.now() >= until || stopped(ctx)) throw new CliError(\"timeout\", `${ended(ctx, ms)}: the contact has not confirmed the edit yet (it needs a live chat and a contact's app that shows edits). It ${goesOn(ctx, chat)}`, known(ctx, { messageId, edits: message.edit.seq }));\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n}\n\n/** Waits until the contact confirmed my removal of a message, which is already gone here. */\nexport async function waitForRemoval(ctx: ApiContext, chat: string, messageId: string, ms: number): Promise<void> {\n const until = performance.now() + ms;\n while (node(ctx).removalPending({ linkId: chat, messageId })) {\n if (performance.now() >= until || stopped(ctx)) throw new CliError(\"timeout\", `${ended(ctx, ms)}: the message is gone here and the contact has not confirmed yet. Its removal ${goesOn(ctx, chat)}`, known(ctx, { messageId }));\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n}\n\n/** How long `purgeMessage` waits for the engine to take the message's row out: it does so in a few milliseconds. */\nconst PURGE_WAIT_MS = 5_000;\n\n/**\n * `message delete --purge`: once the message's row is gone (the engine takes it out on later turns, its files first),\n * the replies that quote it lose its line (a delete here leaves it in their rows, one for everyone to a sweep within\n * 10 s), then the store's journal is folded into a fresh snapshot now, not within the hour of the fold that comes by\n * itself: what the message said leaves rows.db, `db/journal.bin` and rows.db's WAL before the command answers. For a\n * secret pasted into a chat; every delete folding would rewrite the snapshot each time. `message`: its row, read\n * before the delete.\n */\nexport async function purgeMessage(ctx: ApiContext, message: StoredMessage): Promise<void> {\n const { linkId: chat, id: messageId } = message;\n const until = performance.now() + PURGE_WAIT_MS;\n let gone = !(await node(ctx).getMessage(chat, messageId));\n while (!gone && performance.now() < until) {\n await new Promise((resolve) => setTimeout(resolve, 20));\n gone = !(await node(ctx).getMessage(chat, messageId));\n }\n if (gone) await node(ctx).forgetQuotesOf(message);\n await ctx.runtime.store.compact({ scrub: true });\n if (!gone) throw new CliError(\"timeout\", `Timed out after ${PURGE_WAIT_MS / 1000} s: the message is deleted, but what it said may stay in the profile's store until its next fold (within the hour)`, { messageId, deleted: messageId });\n}\n\n/**\n * A private group with no member but me (they all left, or nobody accepted an invitation yet): what I send there now\n * reaches nobody, not even a member who joins later (a joiner reads nothing from before). A community's roster may not\n * list every member yet, so only a private group counts.\n */\nexport const nobodyElseIn = (ctx: ApiContext, groupId: string): boolean => alone(groupIn(ctx, groupId));\n\n/** A group as the engine shows it, built alone: `getState()` builds a view of every chat, once per poll. */\nconst groupIn = (ctx: ApiContext, groupId: string): GroupView | undefined => groupById(ctx, groupId);\n\nconst alone = (group: GroupView | undefined): boolean => group?.profile === \"mesh\" && !group.members.some((m) => !m.me);\n\n/**\n * Why I am no longer in a group (removed, say), or null while I am. A member removed while away learns it only after\n * it is back, so what it sent in between is never taken, and from then on nothing goes. A community's `lost` is not\n * out: it asks to be let in again by itself.\n */\nexport const outOf = (group: GroupView | undefined): string | null =>\n group?.status && group.status !== \"active\" && group.status !== \"lost\" ? group.statusReason ?? \"You are not in this group\" : null;\n\n/**\n * Waits until an edge took my group message, or its edit number `edit`, or my reaction to it numbered `reaction`, or my\n * pin numbered `pin` (WISP 902: a group has no receipts, so this is as far as the author sees): a member's edge in a\n * private group, an edge to one of my hubs in a community. In a private group with nobody else in it, 0 at once: no\n * edge will ever take it, and the wait sat its whole time, then said \"it goes when one opens\" and exited 4, which a\n * bot retries, sending it again each time. Refused as soon as I learn I am out of the group: it sat its whole time\n * there too and said the same, though nothing goes any more.\n */\nexport async function waitForGroupFrame(ctx: ApiContext, groupId: string, messageId: string, edit: number | { reaction: number } | { pin: number } | undefined, ms: number): Promise<number> {\n const until = performance.now() + ms;\n const which = typeof edit === \"object\" ? edit : edit ? { edit } : {};\n for (;;) {\n const taken = node(ctx).groupTaken({ groupId, messageId, ...which });\n if (taken > 0) return taken;\n const group = groupIn(ctx, groupId);\n if (alone(group)) return taken;\n const out = outOf(group);\n if (out) throw new CliError(\"refused\", `${out}: no member took it, and it no longer goes`, { messageId, ...(\"edit\" in which ? { edits: which.edit } : which) });\n if (performance.now() >= until || stopped(ctx)) throw new CliError(\"timeout\", `${ended(ctx, ms)}: no member's edge took it yet (it stays in the group and goes when one opens). It ${goesOn(ctx)}`, known(ctx, { messageId, ...(\"edit\" in which ? { edits: which.edit } : which) }));\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n}\n\n/**\n * A one-shot whose text went over the live link waits this long for its receipt before it leaves (`waitForMessage`).\n * Left at `sent`, the engine stopping took the text for unconfirmed, the next start sent it again on the DHT, and that\n * copy took the chat's one DHT text awaiting a receipt: a script's next one-shot send waited 30 s behind it, every 5-8\n * messages, and the last text showed \"Connection closed before receipt\" though the contact had it (agents#1640).\n */\nexport const ONE_SHOT_RECEIPT_MS = 2_000;\n\n/**\n * Waits until the contact confirmed my reaction or pin in a 1:1 chat (WISP 401): until `pending` no longer finds it in\n * what the contact has not confirmed (`chatUnconfirmed`). It goes on the live session, a reaction also on the DHT\n * envelopes; one not confirmed in time is kept and said again.\n */\nexport async function waitForConfirmed(ctx: ApiContext, chat: string, what: \"reaction\" | \"pin\", pending: (left: { reactions: number[]; pin: number | null }) => boolean, ms: number): Promise<void> {\n const until = performance.now() + ms;\n while (pending(node(ctx).chatUnconfirmed({ linkId: chat }))) {\n if (performance.now() >= until || stopped(ctx)) throw new CliError(\"timeout\", `${ended(ctx, ms)}: the contact has not confirmed the ${what} yet. It is kept here and ${goesOn(ctx, chat)}`, known(ctx, { chat }));\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n}\n\n/**\n * Waits until a message of mine reached `target` (`sent`: on its way to the contact; `delivered`: acknowledged). A\n * one-shot's text sent over the live link waits a moment more for its receipt (`ONE_SHOT_RECEIPT_MS`).\n */\nexport async function waitForMessage(ctx: ApiContext, chat: string, messageId: string, target: \"sent\" | \"delivered\", ms: number): Promise<StoredMessage> {\n const reached = await waitForDelivery(ctx, chat, messageId, target, ms);\n if (ctx.mode !== \"one-shot\" || target !== \"sent\" || reached.delivery !== \"sent\" || reached.via !== \"datalink\") return reached;\n return waitForDelivery(ctx, chat, messageId, \"delivered\", ONE_SHOT_RECEIPT_MS).catch(async () => (await node(ctx).getMessage(chat, messageId)) ?? reached);\n}\n\nasync function waitForDelivery(ctx: ApiContext, chat: string, messageId: string, target: \"sent\" | \"delivered\", ms: number): Promise<StoredMessage> {\n const want = DELIVERY_RANK[target];\n const look = (message: StoredMessage | undefined) => {\n if (!message) return undefined;\n const delivery = message.delivery ?? \"sent\";\n if (delivery === \"failed\") throw new CliError(\"engine\", message.deliveryError ?? \"The message could not be sent\", { messageId, delivery });\n return (DELIVERY_RANK[delivery] ?? 0) >= want ? message : undefined;\n };\n return new Promise<StoredMessage>((resolve, reject) => {\n let settled = false;\n const finish = (error: unknown, message?: StoredMessage) => {\n if (settled) return;\n settled = true; clearTimeout(timer); off(); ctx.stopping?.removeEventListener(\"abort\", giveUp);\n if (error) reject(error); else resolve(message!);\n };\n const check = (last = false) => void node(ctx).getMessage(chat, messageId).then((message) => {\n try {\n const done = look(message);\n if (done) finish(null, done);\n else if (last) finish(new CliError(\"timeout\", `${ended(ctx, ms)}: the message is ${message?.delivery ?? \"not sent yet\"} and ${goesOn(ctx, chat)}`, known(ctx, { messageId, delivery: message?.delivery ?? null })));\n } catch (error) { finish(error); }\n }, finish);\n const giveUp = () => check(true);\n const timer = setTimeout(giveUp, ms);\n // Any event naming the message: a message first seen already delivered comes as `message.sent`, never as\n // `message.delivery`. Listening before the first read leaves no gap for a change to slip through.\n const off = ctx.hub.onEvent((event: GhostlyEvent) => {\n if (event.chat === chat && (event.messageId === messageId || (event.message as { id?: string } | undefined)?.id === messageId)) check();\n });\n if (stopped(ctx)) giveUp();\n else { ctx.stopping?.addEventListener(\"abort\", giveUp, { once: true }); check(); }\n });\n}\n","import { LIMITS } from \"@ghostly/core\";\nimport { CliError } from \"./errors\";\n\n/**\n * A text past what a chat or a group carries (16 KiB of UTF-8, as the engine counts it: trimmed) is refused before the\n * secret guard reads it and before the engine is asked, with its size and the bound, as `send` and `edit` refuse it.\n */\nexport function checkTextSize(text: string): void {\n const bytes = new TextEncoder().encode(text.trim()).length;\n if (bytes > LIMITS.maxChatMessageBytes) throw new CliError(\"bad_request\", `Message exceeds ${LIMITS.maxChatMessageBytes} UTF-8 bytes (${bytes}): shorten it, or send it as a file`, { bytes, max: LIMITS.maxChatMessageBytes });\n}\n","import { BUTTONS_CAPABILITY, BUTTON_STYLES, STATUS_CARD_LIMITS, buttonLabelClash, checkStatusCard, randomBytes, toBase64Url, type ButtonsCard } from \"@ghostly/core\";\nimport type { LinkView, StoredMessage } from \"@ghostly/browser/shared/types\";\nimport type { Parsed } from \"./args\";\nimport { bool, chatOrGroup, messageOf, noMessage, node, num, oneOf, oneShotWaits, str, type Method, type Params, type RefPlace } from \"./apiKit\";\nimport { CliError } from \"./errors\";\nimport { findSecret, secretWords } from \"./secretGuard\";\nimport { checkTextSize } from \"./textSize\";\nimport { waitForEdit, waitForGroupFrame, waitForMessage } from \"./waits\";\n\n/*\n * Message buttons (WISP 406 · Message Buttons), the bot's side: a message whose text is the question, with up to six\n * buttons under it (`send --button yes:Yes`). A press comes back as a reply whose text is the button's label; the\n * engine marks it (`press`) and `listen` says `button.pressed`. `button update` then shows the answer (`chosen`) and\n * closes the buttons, by editing the message with the same buttons.\n */\n\n/**\n * `--button id:Label` (again for each, 1 to 6), `--style id=primary|neutral|danger`, `--once` and `--id`, as the\n * method's parameters: `buttons` and `buttonsId`. Nothing when no `--button` is given. The label may hold colons: the\n * id ends at the first one. An id given twice, two labels that read the same (ignoring case and spaces at the ends), a\n * label that is another button's id, or a style not listed are a usage error here, before the profile opens; other\n * bounds (ids, labels, how many) are the card's, checked when it is sent.\n */\nexport function buttonsOf(options: Parsed[\"options\"]): { buttons: Record<string, unknown>[]; buttonsId?: string } | undefined {\n const given = Array.isArray(options.button) ? options.button as string[] : [];\n if (!given.length) {\n for (const flag of [\"style\", \"once\", \"id\"] as const)\n if (options[flag] !== undefined) throw new CliError(\"usage\", `--${flag} goes with --button id:Label`);\n return undefined;\n }\n const buttons: Record<string, unknown>[] = given.map((value) => {\n const colon = value.indexOf(\":\");\n if (colon < 1 || colon === value.length - 1) throw new CliError(\"usage\", `--button takes id:Label, like yes:Yes, not ${JSON.stringify(value)}`);\n return { id: value.slice(0, colon), label: value.slice(colon + 1).trim() };\n });\n const twice = buttons.findIndex((button, at) => buttons.findIndex((other) => other.id === button.id) !== at);\n if (twice !== -1) throw new CliError(\"usage\", `--button ${JSON.stringify(given[twice])} repeats the id ${JSON.stringify(buttons[twice].id)}: each button takes its own`);\n // Two buttons a typed answer could not tell apart: the same label, or a label that is another's id (ignoring case).\n const clash = buttonLabelClash(buttons);\n if (clash) {\n const [at, other] = [JSON.stringify(given[clash.at]), JSON.stringify(given[clash.with])];\n throw new CliError(\"usage\", clash.kind === \"label\"\n ? `--button ${at} repeats the label of --button ${other} (ignoring case and spaces): a typed answer could not tell them apart`\n : `--button ${at} has a label that is the id of --button ${other}: a typed answer could not tell them apart`);\n }\n for (const value of Array.isArray(options.style) ? options.style as string[] : []) {\n const eq = value.indexOf(\"=\");\n const button = eq > 0 ? buttons.find((b) => b.id === value.slice(0, eq)) : undefined;\n if (!button) throw new CliError(\"usage\", `--style takes id=primary|neutral|danger for one of the buttons, not ${JSON.stringify(value)}`);\n const style = value.slice(eq + 1);\n if (!(BUTTON_STYLES as readonly string[]).includes(style)) throw new CliError(\"usage\", `--style ${JSON.stringify(value)}: a button's style is ${BUTTON_STYLES.join(\", \")}`);\n button.style = style;\n }\n if (options.once === true) for (const button of buttons) button.once = true;\n return { buttons, ...(options.id !== undefined && { buttonsId: String(options.id) }) };\n}\n\n/** A buttons card checked by the sender's rule, or a `bad_request` that says what is wrong. */\nfunction checked(card: Record<string, unknown>): ButtonsCard {\n const result = checkStatusCard(card);\n if (\"error\" in result) throw new CliError(\"bad_request\", `Buttons: ${result.error}`, { card });\n return result.card as ButtonsCard;\n}\n\n/**\n * The card a send's `buttons` (and `buttonsId`) make, or undefined when it names none. `buttons` is a list of\n * `{id, label, style?, once?}`; the id of the question is made up (`ask-…`) unless given.\n */\nexport function buttonsCard(params: Params): ButtonsCard | undefined {\n const buttons = params.buttons;\n if (buttons === undefined || buttons === null) {\n if (params.buttonsId !== undefined) throw new CliError(\"bad_request\", \"buttonsId goes with buttons\");\n return undefined;\n }\n if (!Array.isArray(buttons)) throw new CliError(\"bad_request\", \"buttons must be a list of {id, label, style?, once?}\");\n const id = str(params, \"buttonsId\") ?? `ask-${toBase64Url(randomBytes(6))}`;\n return checked({ kind: \"buttons\", id, buttons });\n}\n\n/** Whether a 1:1 contact's app shows and presses buttons: null until its app said what it offers. */\nexport function pressable(link: LinkView): boolean | null {\n const peer = link.sessionOffers?.peer;\n return peer ? peer.includes(BUTTONS_CAPABILITY) : null;\n}\n\n/** The message of mine with buttons that `button update` names, by its id here (or the id both sides know). */\nfunction buttonsMessage(message: StoredMessage | undefined, ref: string, place: RefPlace): StoredMessage & { card: ButtonsCard } {\n if (!message) throw noMessage(ref, place, { whose: \"of yours\" });\n if (message.card?.kind !== \"buttons\") throw new CliError(\"bad_request\", \"That message has no buttons: send one with send --button id:Label\");\n return message as StoredMessage & { card: ButtonsCard };\n}\n\n/**\n * `button update`: the answer shown on a question's buttons (`chosen`), the buttons closed (`close`), or a new text\n * (`text`), by editing the message with the same buttons. What is not given stays as it was.\n */\nasync function updateButtons(ctx: Parameters<Method>[0], params: Params): Promise<Record<string, unknown>> {\n const target = chatOrGroup(ctx, str(params, \"chat\", true));\n const ref = str(params, \"message\", true);\n const chosen = str(params, \"chosen\");\n const close = bool(params, \"close\");\n const newText = str(params, \"text\");\n if (chosen === undefined && !close && newText === undefined) throw new CliError(\"bad_request\", \"Nothing to update: give chosen, close or text\");\n // The engine fills a card's blank text with its fallback line (\"Reply: Yes / No\"): the question's words were lost.\n if (newText !== undefined && !newText.trim()) throw new CliError(\"bad_request\", \"The new text is blank: give the question's new words, or leave text out to keep them\");\n // A new text is a message like any other: the same size check and guard as `send` and `edit`.\n if (newText !== undefined) checkTextSize(newText);\n if (newText !== undefined && !bool(params, \"force\")) {\n const secret = findSecret(newText);\n if (secret) throw new CliError(\"confirm\", `The text looks like ${secretWords(secret)}; update with --force if you mean to`, { kind: secret.kind });\n }\n const message = buttonsMessage(await messageOf(ctx, target.linkId, ref, (m) => m.sender === \"me\"), ref, { group: target.group, ref: str(params, \"chat\", true) });\n if ((message.edit?.seq ?? 0) >= STATUS_CARD_LIMITS.edits)\n throw new CliError(\"refused\", `This message took ${STATUS_CARD_LIMITS.edits} updates, the most one takes: ask again with a new send`, { messageId: message.id, edits: message.edit!.seq });\n const before = message.card;\n // Said here, with the buttons it has, as a press says it (not_found, exit 3): the card's own check names only the field.\n if (chosen !== undefined && !before.buttons.some((b) => b.id === chosen))\n throw new CliError(\"not_found\", `That message has no button ${JSON.stringify(chosen)}; its buttons: ${before.buttons.map((b) => b.id).join(\", \")}`, { card: before });\n const card = checked({ ...before, ...(chosen !== undefined && { chosen }), ...((close || before.closed) && { closed: true }) });\n const text = newText ?? message.text;\n const wait = oneOf(params, \"wait\", target.group ? [\"none\", \"sent\"] as const : [\"none\", \"confirmed\"] as const, \"none\");\n const ms = num(params, \"timeout\", 30, { min: 1, max: 3600 }) * 1000;\n const result = await node(ctx).editMessage({ linkId: target.linkId, messageId: message.id, text, card });\n if (result.error) throw new CliError(result.refused ? \"refused\" : \"unavailable\", result.error);\n let edited = await node(ctx).getMessage(target.linkId, message.id);\n if (wait === \"confirmed\" && edited?.edit?.pending) edited = await waitForEdit(ctx, target.linkId, message.id, ms);\n const edges = wait === \"sent\" && edited?.edit ? await waitForGroupFrame(ctx, target.id, message.id, edited.edit.seq, ms) : undefined;\n return {\n [target.group ? \"group\" : \"chat\"]: target.id, buttons: card.id, messageId: message.id, card, edits: edited?.edit?.seq ?? 0,\n ...(target.group ? { ...(edges !== undefined && { edges }) } : { confirmed: !!edited && !edited.edit?.pending }),\n };\n}\n\n/**\n * `button press`: the other side of a question, as the app's tap: a press on a button of someone else's message, by\n * its id here (or the id both sides know). The engine sends a reply whose text is the button's label, and refuses what\n * an app would: a button the message does not have, closed buttons, a second answer past `once`, a second press\n * within a second. A one-shot in a chat waits until the press went out, as `send` does.\n */\nasync function pressButton(ctx: Parameters<Method>[0], params: Params): Promise<Record<string, unknown>> {\n const target = chatOrGroup(ctx, str(params, \"chat\", true));\n const ref = str(params, \"message\", true);\n const buttonId = str(params, \"button\", true);\n const where = target.group ? \"group\" : \"chat\";\n const message = await messageOf(ctx, target.linkId, ref, (m) => m.sender !== \"me\");\n if (!message) throw noMessage(ref, { group: target.group, ref: str(params, \"chat\", true) }, { whose: \"from someone else\" });\n if (message.card?.kind !== \"buttons\") throw new CliError(\"bad_request\", \"That message has no buttons\");\n const button = message.card.buttons.find((b) => b.id === buttonId);\n if (!button) throw new CliError(\"not_found\", `That message has no button ${JSON.stringify(buttonId)}; its buttons: ${message.card.buttons.map((b) => b.id).join(\", \")}`);\n const wait = target.group\n ? oneOf(params, \"wait\", [\"none\", \"sent\"] as const, \"none\")\n : oneOf(params, \"wait\", [\"none\", \"sent\", \"delivered\"] as const, oneShotWaits(ctx, target.linkId) ? \"sent\" : \"none\");\n const ms = num(params, \"timeout\", 30, { min: 1, max: 3600 }) * 1000;\n const result = await node(ctx).pressButton({ linkId: target.linkId, messageId: message.id, buttonId });\n if (result.error) throw new CliError(result.refused ? \"refused\" : \"unavailable\", result.error, result.paced ? { paced: true } : undefined);\n const replyId = result.messageId ?? null;\n const answer = { [where]: target.id, messageId: message.id, button: button.id, label: button.label, replyId };\n if (!replyId) return answer;\n if (target.group) {\n const edges = wait === \"sent\" ? await waitForGroupFrame(ctx, target.id, replyId, undefined, ms) : node(ctx).groupTaken({ groupId: target.id, messageId: replyId });\n return { ...answer, edges };\n }\n const reply = wait === \"none\" ? await node(ctx).getMessage(target.linkId, replyId) : await waitForMessage(ctx, target.linkId, replyId, wait, ms);\n return { ...answer, delivery: reply?.delivery ?? null };\n}\n\nexport const BUTTON_METHODS: Record<string, Method> = {\n /** WISP 406 · Message Buttons: a press on a button of someone else's message, as the app's tap. */\n \"button.press\": pressButton,\n /** WISP 406 · Message Buttons: the answer chosen on a question of mine, its buttons closed, or its text changed. */\n \"button.update\": updateButtons,\n};\n"],"mappings":";;;;;;;AAaA,IAAM,gBAAwC;CAAE,SAAS;CAAG,SAAS;CAAG,QAAQ;CAAG,MAAM;CAAG,MAAM;CAAG,WAAW;AAAE;;;;;;AAOlH,IAAa,UAAU,KAAiB,SAAkB,SAAS,KAAA,KAAa,iBAAiB,KAAK,IAAI,IACtG,yDAAyD,IAAI,SAAS,aAAa,8DAA8D,OACjJ,IAAI,SAAS,YAAY,QAAQ,GAAG,IAAI,qDAAqDA,SAAS,IAAI,IAAI;;;;;;AAOlH,IAAM,WAAW,QAAoB,IAAI,UAAU,YAAY;;AAG/D,IAAM,SAAS,KAAiB,OAAe,QAAQ,GAAG,IAAI,6CAA6C,mBAAmB,KAAK,MAAM,KAAK,GAAI,EAAE;;AAGpJ,IAAM,SAAS,KAAiB,YAAqC,QAAQ,GAAG,IAAI;CAAE,GAAG;CAAS,QAAQ;AAAiB,IAAI;;AAG/H,eAAsB,YAAY,KAAiB,MAAc,WAAmB,IAAoC;CACtH,MAAM,QAAQ,YAAY,IAAI,IAAI;CAClC,SAAS;EACP,MAAM,UAAU,MAAM,KAAK,GAAG,CAAC,CAAC,WAAW,MAAM,SAAS;EAC1D,IAAI,CAAC,SAAS,MAAM,UAAU,WAAW;GAAE,OAAO;GAAO,KAAK;EAAK,CAAC;EACpE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AM,KAAK,GAAG,CAAC,CAAC,YAAY;EAAE,QAAQ,OAAO;EAAQ,WAAW,QAAQ;EAAI;CAAS,CAAC;CACrG,IAAI,OAAO,OAAO,MAAM,IAAI,SAAS,OAAO,UAAU,YAAY,eAAe,OAAO,OAAO,OAAO,QAAQ,EAAE,OAAO,KAAK,IAAI,KAAA,CAAS;CACzI,MAAM,UAAU,OAAO,aAAa;CACpC,MAAM,SAAS;GAAG,QAAQ,OAAO;EAAI,WAAW,QAAQ;EAAI,QAAQ,OAAO;EAAI,OAAO,OAAO;EAAO;CAAQ;CAC5G,IAAI,CAAC,SAAS,OAAO;CACrB,IAAI,OAAO,OAAO;EAChB,MAAM,QAAQ,SAAS,SAAS,MAAM,kBAAkB,KAAK,OAAO,IAAI,SAAS,KAAA,GAAW,EAAE,IAAI,KAAK,GAAG,CAAC,CAAC,WAAW;GAAE,SAAS,OAAO;GAAI,WAAW;EAAQ,CAAC;EACjK,OAAO;GAAE,GAAG;GAAQ;EAAM;CAC5B;CACA,MAAM,QAAQ,SAAS,SAAS,MAAM,KAAK,GAAG,CAAC,CAAC,WAAW,OAAO,QAAQ,OAAO,IAAI,MAAM,eAAe,KAAK,OAAO,QAAQ,SAAS,MAAM,EAAE;CAC/I,OAAO;EAAE,GAAG;EAAQ,UAAU,OAAO,YAAY;CAAK;AACxD;AAEA,IAAa,iBAAyC;;CAEpD,gBAAgB;;CAEhB,iBAAiB;AACnB"}
@@ -0,0 +1,132 @@
1
+ // ../core/src/bytes.ts
2
+ var textEncoder = new TextEncoder();
3
+ var textDecoder = new TextDecoder("utf-8", { fatal: true });
4
+ function utf8Encode(str) {
5
+ return textEncoder.encode(str);
6
+ }
7
+ function utf8Decode(bytes) {
8
+ return textDecoder.decode(bytes);
9
+ }
10
+ function concatBytes(...parts) {
11
+ let length = 0;
12
+ for (const p of parts) length += p.length;
13
+ const out = new Uint8Array(length);
14
+ let offset = 0;
15
+ for (const p of parts) {
16
+ out.set(p, offset);
17
+ offset += p.length;
18
+ }
19
+ return out;
20
+ }
21
+ function bytesEqual(a, b) {
22
+ if (a.length !== b.length) return false;
23
+ let diff = 0;
24
+ for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
25
+ return diff === 0;
26
+ }
27
+ /** `Uint8Array.prototype.toBase64` (Node 25+, Chrome 140+, Firefox 133+, Safari 18.2+): ~200x the JS below. */
28
+ var nativeToBase64 = Uint8Array.prototype.toBase64;
29
+ var tableOf = (chars) => Uint8Array.from(chars, (c) => c.charCodeAt(0));
30
+ var BASE64_TABLE = tableOf("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
31
+ var BASE64URL_TABLE = tableOf("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");
32
+ /**
33
+ * Base64 where the runtime has no native encoder (Node 22 and 24, older WebViews): the characters go into bytes and
34
+ * become one string at the end. Every file chunk is encoded (files/3 `pf-data`), so this is on a transfer's path.
35
+ */
36
+ function encodeBase64(bytes, table, pad) {
37
+ const out = new Uint8Array(Math.ceil(bytes.length / 3) * 4);
38
+ let o = 0, i = 0;
39
+ for (; i + 2 < bytes.length; i += 3) {
40
+ const n = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
41
+ out[o++] = table[n >>> 18];
42
+ out[o++] = table[n >>> 12 & 63];
43
+ out[o++] = table[n >>> 6 & 63];
44
+ out[o++] = table[n & 63];
45
+ }
46
+ const rest = bytes.length - i;
47
+ if (rest) {
48
+ const n = bytes[i] << 16 | (rest === 2 ? bytes[i + 1] << 8 : 0);
49
+ out[o++] = table[n >>> 18];
50
+ out[o++] = table[n >>> 12 & 63];
51
+ if (rest === 2) out[o++] = table[n >>> 6 & 63];
52
+ else if (pad) out[o++] = 61;
53
+ if (pad) out[o++] = 61;
54
+ }
55
+ return textDecoder.decode(out.subarray(0, o));
56
+ }
57
+ function toBase64(bytes) {
58
+ return nativeToBase64 ? nativeToBase64.call(bytes) : encodeBase64(bytes, BASE64_TABLE, true);
59
+ }
60
+ function fromBase64(str) {
61
+ const binary = atob(str);
62
+ const bytes = new Uint8Array(binary.length);
63
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
64
+ return bytes;
65
+ }
66
+ function toBase64Url(bytes) {
67
+ return nativeToBase64 ? nativeToBase64.call(bytes, {
68
+ alphabet: "base64url",
69
+ omitPadding: true
70
+ }) : encodeBase64(bytes, BASE64URL_TABLE, false);
71
+ }
72
+ function fromBase64Url(str) {
73
+ let b = str.replace(/-/g, "+").replace(/_/g, "/");
74
+ while (b.length % 4) b += "=";
75
+ return fromBase64(b);
76
+ }
77
+ var Z32_ALPHABET = "ybndrfg8ejkmcpqxot1uwisza345h769";
78
+ function toZ32(bytes) {
79
+ let out = "";
80
+ let bits = 0;
81
+ let value = 0;
82
+ for (const byte of bytes) {
83
+ value = value << 8 | byte;
84
+ bits += 8;
85
+ while (bits >= 5) {
86
+ out += Z32_ALPHABET[value >>> bits - 5 & 31];
87
+ bits -= 5;
88
+ }
89
+ value &= (1 << bits) - 1;
90
+ }
91
+ if (bits > 0) out += Z32_ALPHABET[value << 5 - bits & 31];
92
+ return out;
93
+ }
94
+ function fromZ32(str) {
95
+ const out = new Uint8Array(Math.floor(str.length * 5 / 8));
96
+ let bits = 0;
97
+ let value = 0;
98
+ let index = 0;
99
+ for (const char of str) {
100
+ const v = Z32_ALPHABET.indexOf(char);
101
+ if (v < 0) throw new Error(`Invalid z-base-32 character: ${char}`);
102
+ value = value << 5 | v;
103
+ bits += 5;
104
+ if (bits >= 8) {
105
+ out[index++] = value >>> bits - 8 & 255;
106
+ bits -= 8;
107
+ }
108
+ value &= (1 << bits) - 1;
109
+ }
110
+ return out;
111
+ }
112
+ /**
113
+ * A 32-byte key written as the one z-base-32 spelling `toZ32` produces: 52 characters that decode to 32 bytes and
114
+ * encode back to the same string. The last character carries four zero padding bits, so each key has exactly one
115
+ * spelling and keys may be compared as strings (WISP 02). Any other spelling is not a key here.
116
+ */
117
+ function isZ32Key(value) {
118
+ if (typeof value !== "string" || value.length !== 52) return false;
119
+ try {
120
+ return toZ32(fromZ32(value)) === value;
121
+ } catch {
122
+ return false;
123
+ }
124
+ }
125
+ function randomBytes(length) {
126
+ const bytes = new Uint8Array(length);
127
+ crypto.getRandomValues(bytes);
128
+ return bytes;
129
+ }
130
+ export { fromZ32 as a, toBase64 as c, utf8Decode as d, utf8Encode as f, fromBase64Url as i, toBase64Url as l, concatBytes as n, isZ32Key as o, fromBase64 as r, randomBytes as s, bytesEqual as t, toZ32 as u };
131
+
132
+ //# sourceMappingURL=bytes-C1DNGY18.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bytes-C1DNGY18.js","names":[],"sources":["../../../core/src/bytes.ts"],"sourcesContent":["const textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder(\"utf-8\", { fatal: true });\n\nexport function utf8Encode(str: string): Uint8Array {\n return textEncoder.encode(str);\n}\n\nexport function utf8Decode(bytes: Uint8Array): string {\n return textDecoder.decode(bytes);\n}\n\nexport function concatBytes(...parts: Uint8Array[]): Uint8Array {\n let length = 0;\n for (const p of parts) length += p.length;\n const out = new Uint8Array(length);\n let offset = 0;\n for (const p of parts) {\n out.set(p, offset);\n offset += p.length;\n }\n return out;\n}\n\nexport function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\ntype NativeToBase64 = (this: Uint8Array, options?: { alphabet?: \"base64\" | \"base64url\"; omitPadding?: boolean }) => string;\n/** `Uint8Array.prototype.toBase64` (Node 25+, Chrome 140+, Firefox 133+, Safari 18.2+): ~200x the JS below. */\nconst nativeToBase64 = (Uint8Array.prototype as { toBase64?: NativeToBase64 }).toBase64;\n\nconst tableOf = (chars: string) => Uint8Array.from(chars, (c) => c.charCodeAt(0));\nconst BASE64_TABLE = tableOf(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\");\nconst BASE64URL_TABLE = tableOf(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\");\n\n/**\n * Base64 where the runtime has no native encoder (Node 22 and 24, older WebViews): the characters go into bytes and\n * become one string at the end. Every file chunk is encoded (files/3 `pf-data`), so this is on a transfer's path.\n */\nfunction encodeBase64(bytes: Uint8Array, table: Uint8Array, pad: boolean): string {\n const out = new Uint8Array(Math.ceil(bytes.length / 3) * 4);\n let o = 0, i = 0;\n for (; i + 2 < bytes.length; i += 3) {\n const n = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n out[o++] = table[n >>> 18];\n out[o++] = table[(n >>> 12) & 63];\n out[o++] = table[(n >>> 6) & 63];\n out[o++] = table[n & 63];\n }\n const rest = bytes.length - i;\n if (rest) {\n const n = (bytes[i] << 16) | (rest === 2 ? bytes[i + 1] << 8 : 0);\n out[o++] = table[n >>> 18];\n out[o++] = table[(n >>> 12) & 63];\n if (rest === 2) out[o++] = table[(n >>> 6) & 63];\n else if (pad) out[o++] = 61; // \"=\"\n if (pad) out[o++] = 61;\n }\n return textDecoder.decode(out.subarray(0, o));\n}\n\nexport function toBase64(bytes: Uint8Array): string {\n return nativeToBase64 ? nativeToBase64.call(bytes) : encodeBase64(bytes, BASE64_TABLE, true);\n}\n\nexport function fromBase64(str: string): Uint8Array {\n const binary = atob(str);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\nexport function toBase64Url(bytes: Uint8Array): string {\n return nativeToBase64 ? nativeToBase64.call(bytes, { alphabet: \"base64url\", omitPadding: true }) : encodeBase64(bytes, BASE64URL_TABLE, false);\n}\n\nexport function fromBase64Url(str: string): Uint8Array {\n let b = str.replace(/-/g, \"+\").replace(/_/g, \"/\");\n while (b.length % 4) b += \"=\";\n return fromBase64(b);\n}\n\nconst Z32_ALPHABET = \"ybndrfg8ejkmcpqxot1uwisza345h769\";\n\nexport function toZ32(bytes: Uint8Array): string {\n let out = \"\";\n let bits = 0;\n let value = 0;\n for (const byte of bytes) {\n value = (value << 8) | byte;\n bits += 8;\n while (bits >= 5) {\n out += Z32_ALPHABET[(value >>> (bits - 5)) & 31];\n bits -= 5;\n }\n value &= (1 << bits) - 1;\n }\n if (bits > 0) out += Z32_ALPHABET[(value << (5 - bits)) & 31];\n return out;\n}\n\nexport function fromZ32(str: string): Uint8Array {\n const out = new Uint8Array(Math.floor((str.length * 5) / 8));\n let bits = 0;\n let value = 0;\n let index = 0;\n for (const char of str) {\n const v = Z32_ALPHABET.indexOf(char);\n if (v < 0) throw new Error(`Invalid z-base-32 character: ${char}`);\n value = (value << 5) | v;\n bits += 5;\n if (bits >= 8) {\n out[index++] = (value >>> (bits - 8)) & 0xff;\n bits -= 8;\n }\n value &= (1 << bits) - 1;\n }\n return out;\n}\n\n/**\n * A 32-byte key written as the one z-base-32 spelling `toZ32` produces: 52 characters that decode to 32 bytes and\n * encode back to the same string. The last character carries four zero padding bits, so each key has exactly one\n * spelling and keys may be compared as strings (WISP 02). Any other spelling is not a key here.\n */\nexport function isZ32Key(value: unknown): value is string {\n if (typeof value !== \"string\" || value.length !== 52) return false;\n try { return toZ32(fromZ32(value)) === value; } catch { return false; }\n}\n\nexport function randomBytes(length: number): Uint8Array {\n const bytes = new Uint8Array(length);\n crypto.getRandomValues(bytes);\n return bytes;\n}\n"],"mappings":";AAAA,IAAM,cAAc,IAAI,YAAY;AACpC,IAAM,cAAc,IAAI,YAAY,SAAS,EAAE,OAAO,KAAK,CAAC;AAE5D,SAAgB,WAAW,KAAyB;CAClD,OAAO,YAAY,OAAO,GAAG;AAC/B;AAEA,SAAgB,WAAW,OAA2B;CACpD,OAAO,YAAY,OAAO,KAAK;AACjC;AAEA,SAAgB,YAAY,GAAG,OAAiC;CAC9D,IAAI,SAAS;CACb,KAAK,MAAM,KAA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AAM,QAAQ,KAAK;EACtB,MAAM,IAAI,aAAa,QAAQ,IAAI;EACnC,IAAI,IAAI,GAAG,MAAM,IAAI,MAAM,gCAAgC,MAAM;EACjE,QAAS,SAAS,IAAK;EACvB,QAAQ;EACR,IAAI,QAAQ,GAAG;GACb,IAAI,WAAY,UAAW,OAAO,IAAM;GACxC,QAAQ;EACV;EACA,UAAU,KAAK,QAAQ;CACzB;CACA,OAAO;AACT;;;;;;AAOA,SAAgB,SAAS,OAAiC;CACxD,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,IAAI,OAAO;CAC7D,IAAI;EAAE,OAAO,MAAM,QAAQ,KAAK,CAAC,MAAM;CAAO,QAAQ;EAAE,OAAO;CAAO;AACxE;AAEA,SAAgB,YAAY,QAA4B;CACtD,MAAM,QAAQ,IAAI,WAAW,MAAM;CACnC,OAAO,gBAAgB,KAAK;CAC5B,OAAO;AACT"}
@@ -1,4 +1,4 @@
1
- //#region src/childEnv.ts
1
+ // src/childEnv.ts
2
2
  /**
3
3
  * Environment variables only the command that reads them needs: the backup passphrase is read by a one-shot
4
4
  * `profile backup`/`profile restore` and sent as a call parameter, so no other process (the daemon, a hook, ffmpeg,
@@ -16,7 +16,6 @@ function childEnv(env = process.env) {
16
16
  function dropSecretEnv(env = process.env) {
17
17
  for (const name of SECRET_ENV) delete env[name];
18
18
  }
19
- //#endregion
20
19
  export { dropSecretEnv as n, childEnv as t };
21
20
 
22
- //# sourceMappingURL=childEnv-K_IzUqQx.js.map
21
+ //# sourceMappingURL=childEnv-C-99hdbL.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"childEnv-K_IzUqQx.js","names":[],"sources":["../../src/childEnv.ts"],"sourcesContent":["/**\n * Environment variables only the command that reads them needs: the backup passphrase is read by a one-shot\n * `profile backup`/`profile restore` and sent as a call parameter, so no other process (the daemon, a hook, ffmpeg,\n * the translator, `ps`, `xattr`) ever needs it; `listen` reads its webhook's URL (a bridge's token in it) once, at the\n * start, and a hook it runs never needs it. The one list every child's environment is cleaned with.\n */\nexport const SECRET_ENV = [\"GHOSTLY_BACKUP_PASSPHRASE\", \"GHOSTLY_WEBHOOK\"] as const;\n\n/** `env` less the secrets in `SECRET_ENV`: what a process this one starts gets. */\nexport function childEnv(env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {\n const rest = { ...env };\n for (const name of SECRET_ENV) delete rest[name];\n return rest;\n}\n\n/** Removes the secrets in `SECRET_ENV` from this process's own environment (the daemon, which never reads them). */\nexport function dropSecretEnv(env: NodeJS.ProcessEnv = process.env): void {\n for (const name of SECRET_ENV) delete env[name];\n}\n"],"mappings":";;;;;;;AAMA,IAAa,aAAa,CAAC,6BAA6B,iBAAiB;;AAGzE,SAAgB,SAAS,MAAyB,QAAQ,KAAwB;CAChF,MAAM,OAAO,EAAE,GAAG,IAAI;CACtB,KAAK,MAAM,QAAQ,YAAY,OAAO,KAAK;CAC3C,OAAO;AACT;;AAGA,SAAgB,cAAc,MAAyB,QAAQ,KAAW;CACxE,KAAK,MAAM,QAAQ,YAAY,OAAO,IAAI;AAC5C"}
1
+ {"version":3,"file":"childEnv-C-99hdbL.js","names":[],"sources":["../../src/childEnv.ts"],"sourcesContent":["/**\n * Environment variables only the command that reads them needs: the backup passphrase is read by a one-shot\n * `profile backup`/`profile restore` and sent as a call parameter, so no other process (the daemon, a hook, ffmpeg,\n * the translator, `ps`, `xattr`) ever needs it; `listen` reads its webhook's URL (a bridge's token in it) once, at the\n * start, and a hook it runs never needs it. The one list every child's environment is cleaned with.\n */\nexport const SECRET_ENV = [\"GHOSTLY_BACKUP_PASSPHRASE\", \"GHOSTLY_WEBHOOK\"] as const;\n\n/** `env` less the secrets in `SECRET_ENV`: what a process this one starts gets. */\nexport function childEnv(env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {\n const rest = { ...env };\n for (const name of SECRET_ENV) delete rest[name];\n return rest;\n}\n\n/** Removes the secrets in `SECRET_ENV` from this process's own environment (the daemon, which never reads them). */\nexport function dropSecretEnv(env: NodeJS.ProcessEnv = process.env): void {\n for (const name of SECRET_ENV) delete env[name];\n}\n"],"mappings":";;;;;;;AAMA,IAAa,aAAa,CAAC,6BAA6B,iBAAiB;;AAGzE,SAAgB,SAAS,MAAyB,QAAQ,KAAwB;CAChF,MAAM,OAAO,EAAE,GAAG,IAAI;CACtB,KAAK,MAAM,QAAQ,YAAY,OAAO,KAAK;CAC3C,OAAO;AACT;;AAGA,SAAgB,cAAc,MAAyB,QAAQ,KAAW;CACxE,KAAK,MAAM,QAAQ,YAAY,OAAO,IAAI;AAC5C"}
@@ -1,5 +1,5 @@
1
- import { t as CliError } from "./errors-Dt-ZnyOX.js";
2
- import { m as lockPath, w as ownSocket } from "./profiles-Ccdq6Xf6.js";
1
+ import { t as CliError } from "./errors-DDLFO4Gf.js";
2
+ import { T as ownSocket, h as lockPath } from "./profiles-BFSGqDFC.js";
3
3
  import { closeSync, lstatSync, openSync, readFileSync, rmSync, writeSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
@@ -141,8 +141,7 @@ var PlaybackQueue = class {
141
141
  return out;
142
142
  }
143
143
  };
144
- //#endregion
145
- //#region src/daemonProof.ts
144
+ // src/daemonProof.ts
146
145
  /**
147
146
  * How a client knows the process on the profile's socket is the profile's daemon (WISP 1100 § Local control API).
148
147
  * On Windows the socket is a named pipe whose name follows from the profile's path, and any account of the machine
@@ -260,8 +259,7 @@ function provesDaemon(secret, nonce, answer) {
260
259
  if (typeof given !== "string" || !/^[0-9a-f]{64}$/.test(given)) return false;
261
260
  return timingSafeEqual(Buffer.from(given, "hex"), Buffer.from(proof(secret, "daemon", nonce), "hex"));
262
261
  }
263
- //#endregion
264
- //#region src/client.ts
262
+ // src/client.ts
265
263
  /** The id of the hello on every connection: a string, so it is never one of the calls' numbers. */
266
264
  var HELLO_ID = "hello";
267
265
  /**
@@ -274,9 +272,29 @@ var HELLO_ID = "hello";
274
272
  var GREETING_MS = 2e3;
275
273
  /** The longest request line the daemon reads (WISP 1100 § Framing): it cuts the connection on a longer one. */
276
274
  var MAX_LINE = 16777216;
277
- /** The refusal of a listener that did not prove it is the profile's daemon (`isNotTheDaemon` tells it apart). */
278
- function notTheDaemon(socket) {
279
- return new CliError("refused", `What answers on ${socket} did not prove it is this profile's daemon, so nothing was sent to it. A daemon of an older release cannot: \`ghostly daemon restart\` starts this one's`, { reason: "not-the-daemon" });
275
+ /**
276
+ * The refusal of a listener that did not prove it is the profile's daemon (`isNotTheDaemon` tells it apart). With nobody
277
+ * holding the profile it is no daemon of any release, and no restart moves it: the answer pointed at `daemon restart`,
278
+ * which answered the same, and a start said a daemon ran. What listens there has to stop, or its file go. `held`: whether
279
+ * a process holds the profile, as the caller knows it (`lockOwner`); read here as a greeting's proof reads it otherwise.
280
+ */
281
+ function notTheDaemon(address, held = profileHeld(address.dir)) {
282
+ if (!held) return new CliError("refused", `Something that is not this profile's daemon listens on ${address.socket}, and no ghostly process holds the profile: nothing was sent to it. Stop the program that listens there, or remove that file, then start the daemon with ghostly daemon --detach`, {
283
+ reason: "not-the-daemon",
284
+ socket: address.socket
285
+ });
286
+ return new CliError("refused", `What answers on ${address.socket} did not prove it is this profile's daemon, so nothing was sent to it. A daemon of an older release cannot: \`ghostly daemon restart\` starts this one's`, { reason: "not-the-daemon" });
287
+ }
288
+ /** Whether a live process of this user's is in the profile's lock (`daemonProof.ts` reads it the same way). */
289
+ function profileHeld(dir) {
290
+ try {
291
+ const pid = Number(readFileSync(lockPath(dir), "utf8").trim());
292
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
293
+ process.kill(pid, 0);
294
+ return true;
295
+ } catch {
296
+ return false;
297
+ }
280
298
  }
281
299
  /** The failures of calls whose connection ended unanswered (`endedUnanswered`), not answers the daemon gave. */
282
300
  var unanswered = /* @__PURE__ */ new WeakSet();
@@ -429,7 +447,7 @@ var DaemonClient = class {
429
447
  }
430
448
  /** `secretGone`: the daemon's secret was not there to check against, as when it stops (`endedUnanswered`). */
431
449
  refuse(secretGone = false) {
432
- this.refusal = notTheDaemon(this.address.socket);
450
+ this.refusal = notTheDaemon(this.address);
433
451
  if (secretGone) unanswered.add(this.refusal);
434
452
  this.settle.reject(this.refusal);
435
453
  this.socket.destroy();
@@ -546,7 +564,6 @@ function connectDaemon(address, timeoutMs = 2e3, { greetingMs = GREETING_MS } =
546
564
  });
547
565
  });
548
566
  }
549
- //#endregion
550
- export { frameSamples as _, endedUnsent as a, greeting as c, removeDaemonSecret as d, CALL_RATES as f, frameBytes as g, bytesToMs as h, endedUnanswered as i, newDaemonSecret as l, PlaybackQueue as m, MAX_LINE as n, isNotTheDaemon as o, DEFAULT_RATE as p, connectDaemon as r, HELLO as s, DaemonClient as t, proof as u, isCallRate as v, monotonic as y };
567
+ export { frameBytes as _, endedUnsent as a, monotonic as b, HELLO as c, proof as d, removeDaemonSecret as f, bytesToMs as g, PlaybackQueue as h, endedUnanswered as i, greeting as l, DEFAULT_RATE as m, MAX_LINE as n, isNotTheDaemon as o, CALL_RATES as p, connectDaemon as r, notTheDaemon as s, DaemonClient as t, newDaemonSecret as u, frameSamples as v, isCallRate as y };
551
568
 
552
- //# sourceMappingURL=client-Ibk3-e60.js.map
569
+ //# sourceMappingURL=client-kGZ3ZdUW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-kGZ3ZdUW.js","names":[],"sources":["../../src/calls/pcm.ts","../../src/daemonProof.ts","../../src/client.ts"],"sourcesContent":["/**\n * The audio a call hands to an outside program, and takes from it (WISP 1100 § Calls): raw PCM, signed 16-bit\n * little-endian, mono, at the call's rate, in frames of 20 ms. Opus runs at every one of these rates itself, so\n * nothing is resampled.\n */\nexport const FRAME_MS = 20;\nexport const CALL_RATES = [8000, 12000, 16000, 24000, 48000] as const;\nexport type CallRate = (typeof CALL_RATES)[number];\nexport const DEFAULT_RATE: CallRate = 48000;\n\nexport const frameSamples = (rate: CallRate): number => (rate * FRAME_MS) / 1000;\nexport const frameBytes = (rate: CallRate): number => frameSamples(rate) * 2;\nexport const bytesToMs = (rate: CallRate, bytes: number): number => Math.round((bytes / 2 / rate) * 1000);\n\nexport function isCallRate(value: unknown): value is CallRate {\n return CALL_RATES.includes(value as CallRate);\n}\n\n/** The most a program may queue ahead of the call: five minutes of speech. What goes past it is dropped. */\nexport const MAX_QUEUE_MS = 5 * 60_000;\n\n/**\n * A partial frame waits this long for the rest of it before it is played padded with silence: a program writing at\n * real time, a little late, is not cut into gaps; a program that stopped mid-frame is still heard to its end.\n */\nexport const PARTIAL_WAIT_MS = 60;\n\n/**\n * The call's own clock, in ms: monotonic, so the device's clock set back or ahead mid-call (a phone or a VM fixing its\n * time) moves the time of day, not the audio. On `Date.now()`, a clock set back held the next frame for as long as the\n * jump, and one set ahead read as that long without a packet from the contact.\n */\nexport const monotonic = (): number => performance.now();\n\n/**\n * What the program wrote, waiting to be sent: taken one 20 ms frame per tick, silence when there is nothing, and\n * dropped whole by a flush (barge-in). The program may write any amount at any time, faster than real time too.\n */\nexport class PlaybackQueue {\n private chunks: Buffer[] = [];\n private head = 0;\n private length = 0;\n private lastPush = 0;\n /** Half a sample was dropped (a flush, a full queue): the program's next byte is its other half, dropped too. */\n private owed = false;\n private readonly frame: number;\n private readonly max: number;\n private readonly silence: Buffer;\n /** Bytes dropped because the queue was full, since the start. */\n dropped = 0;\n\n constructor(readonly rate: CallRate, private readonly now: () => number = monotonic, maxMs = MAX_QUEUE_MS) {\n this.frame = frameBytes(rate);\n // Whole samples only: an odd byte waits for its other half.\n this.max = Math.floor((rate * maxMs) / 1000) * 2;\n this.silence = Buffer.alloc(this.frame);\n }\n\n /** Adds what the program wrote. Returns the bytes it could not keep (the queue was full). */\n push(chunk: Buffer): number {\n if (!chunk.length) return 0;\n this.lastPush = this.now();\n if (this.owed) {\n this.owed = false;\n chunk = chunk.subarray(1);\n }\n const room = this.max - this.length;\n const kept = chunk.length <= room ? chunk : chunk.subarray(0, Math.max(0, room));\n const lost = chunk.length - kept.length;\n this.dropped += lost;\n // The queue ends on a whole sample here, so an odd number lost ends on half of one.\n if (lost % 2) this.owed = true;\n if (kept.length) { this.chunks.push(Buffer.from(kept)); this.length += kept.length; }\n return lost;\n }\n\n /** Queued audio, in milliseconds (whole frames and a partial one). */\n get queuedMs(): number {\n return bytesToMs(this.rate, this.length - (this.length % 2));\n }\n\n /** One frame to send now, and whether it is the program's audio or silence. */\n next(): { frame: Buffer; silent: boolean } {\n if (this.length >= this.frame) return { frame: this.take(this.frame), silent: false };\n const whole = this.length - (this.length % 2);\n if (whole > 0 && this.now() - this.lastPush >= PARTIAL_WAIT_MS) {\n const frame = Buffer.alloc(this.frame);\n this.take(whole).copy(frame);\n return { frame, silent: false };\n }\n return { frame: this.silence, silent: true };\n }\n\n /** Drops everything queued; returns how much, in milliseconds. */\n flush(): number {\n const ms = this.queuedMs;\n // Half a sample queued: its other half is the program's next byte.\n if (this.length % 2) this.owed = true;\n this.chunks = [];\n this.head = 0;\n this.length = 0;\n return ms;\n }\n\n /** Drops up to that much from the front, in whole frames (audio whose time went by); returns how much, in milliseconds. */\n skip(ms: number): number {\n const frames = Math.min(Math.floor(ms / FRAME_MS), Math.floor(this.length / this.frame));\n if (frames > 0) this.take(frames * this.frame);\n return Math.max(0, frames) * FRAME_MS;\n }\n\n /**\n * Another program writes from now on (it replaced the last one on the call's socket): what the last one left is\n * dropped, half a sample included, so the new one starts on a whole sample and is heard at once. Returns how much\n * was dropped, in milliseconds.\n */\n newWriter(): number {\n const ms = this.queuedMs;\n this.chunks = [];\n this.head = 0;\n this.length = 0;\n // A flush that cut the last program's half sample owes nothing to the next program: it starts on a whole sample.\n this.owed = false;\n return ms;\n }\n\n private take(bytes: number): Buffer {\n const out = Buffer.allocUnsafe(bytes);\n let filled = 0;\n while (filled < bytes) {\n const chunk = this.chunks[0];\n const n = Math.min(bytes - filled, chunk.length - this.head);\n chunk.copy(out, filled, this.head, this.head + n);\n filled += n;\n this.head += n;\n if (this.head === chunk.length) { this.chunks.shift(); this.head = 0; }\n }\n this.length -= bytes;\n return out;\n }\n}\n","import { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { closeSync, lstatSync, openSync, readFileSync, rmSync, writeSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { lockPath } from \"./profiles\";\n\n/**\n * How a client knows the process on the profile's socket is the profile's daemon (WISP 1100 § Local control API).\n * On Windows the socket is a named pipe whose name follows from the profile's path, and any account of the machine\n * may open that name first; the pipe itself has no owner a client can check. So the daemon writes a fresh random\n * secret in the profile's owner-only folder at every start, and the client sends nothing but a `daemon.hello` with a\n * nonce of its own until the answer proves, over that nonce, that its sender read the secret. Same on every platform.\n *\n * Before even the hello, the daemon speaks first: a greeting that proves, with the same secret, its pid (the\n * profile's lock holder) and the time. The client writes nothing at all until the greeting checks out. A process\n * holding `SeImpersonatePrivilege` that opened the pipe's name first can impersonate the client from the first\n * message it reads (Node's pipe client sets no security quality of service, so the level is SecurityImpersonation),\n * and Windows refuses to impersonate a pipe's client until data has been read from it (ERROR_CANNOT_IMPERSONATE):\n * a client that writes nothing to it cannot be impersonated.\n */\nexport const HELLO = \"daemon.hello\";\n\n/**\n * How far a greeting's time may be from the client's clock (the same machine's): a greeting is no fresh challenge, so\n * one copied from a daemon that has since died could otherwise stand in for it as long as its secret file is left.\n */\nexport const GREETING_WINDOW_MS = 10_000;\n\nexport interface Greeting { pid: number; at: number; proof: string }\n\nexport function daemonSecretPath(dir: string): string {\n return join(dir, \"daemon.secret\");\n}\n\n/** HMAC-SHA256 over the role's domain and the nonce, hex: a daemon's proof is never a client's, nor one for another nonce. */\nexport function proof(secret: Buffer, role: \"daemon\" | \"client\" | \"greeting\", nonce: string): string {\n return createHmac(\"sha256\", secret).update(`ghostly-${role}:${nonce}`).digest(\"hex\");\n}\n\nexport function newNonce(): string {\n return randomBytes(16).toString(\"hex\");\n}\n\n/**\n * The daemon's: a new secret, 32 random bytes as hex, made 0600 (`wx`, so a file or link put there in the meantime is\n * an error, not something written through). The one a daemon before it left is removed first: whoever could have\n * read that one learns nothing about this one.\n */\nexport function newDaemonSecret(dir: string): Buffer {\n const file = daemonSecretPath(dir);\n rmSync(file, { force: true });\n const secret = randomBytes(32);\n const fd = openSync(file, \"wx\", 0o600);\n try { writeSync(fd, secret.toString(\"hex\") + \"\\n\"); } finally { closeSync(fd); }\n return secret;\n}\n\n/** The daemon's, when it stops: a greeting copied from it proves nothing once it is gone. */\nexport function removeDaemonSecret(dir: string): void {\n rmSync(daemonSecretPath(dir), { force: true });\n}\n\n/** The daemon's first line on every connection, before it has read anything. */\nexport function greeting(secret: Buffer, pid = process.pid, at = Date.now()): { greeting: Greeting } {\n return { greeting: { pid, at, proof: proof(secret, \"greeting\", `${pid}:${at}`) } };\n}\n\n/**\n * Whether `message` (the first line the client read) is the profile's daemon's greeting: proved with the secret, made\n * within `GREETING_WINDOW_MS` of `now`, by the process that holds the profile's lock, alive and one this user may\n * signal (`process.kill(pid, 0)`: EPERM on Unix for another user's; on Windows libuv opens the process to terminate\n * it, which another account's process normally denies). A greeting copied from a daemon that died fails on its pid,\n * unless a process this user may signal took that pid within the window.\n */\nexport function provesGreeting(secret: Buffer, dir: string, message: unknown, now = Date.now()): boolean {\n const given = (message as { greeting?: Partial<Greeting> } | null)?.greeting;\n if (!given || !Number.isSafeInteger(given.pid) || (given.pid as number) <= 0 || !Number.isSafeInteger(given.at)) return false;\n if (typeof given.proof !== \"string\" || !/^[0-9a-f]{64}$/.test(given.proof)) return false;\n const { pid, at } = given as Greeting;\n if (Math.abs(now - at) > GREETING_WINDOW_MS) return false;\n if (!timingSafeEqual(Buffer.from(given.proof, \"hex\"), Buffer.from(proof(secret, \"greeting\", `${pid}:${at}`), \"hex\"))) return false;\n return holdsProfile(dir, pid);\n}\n\n/**\n * Whether a daemon of this release holds the profile: its secret is there (an older release's never writes one, and a\n * daemon removes its own when it stops) and the lock's holder is alive and this user's. One whose greeting is late is\n * busy (its event loop held by one long task), not something else on its socket: the client waits for it.\n */\nexport function daemonOfThisRelease(dir: string): boolean {\n if (!readDaemonSecret(dir)) return false;\n let pid: number;\n try { pid = Number(readFileSync(lockPath(dir), \"utf8\").trim()); } catch { return false; }\n return Number.isSafeInteger(pid) && pid > 0 && holdsProfile(dir, pid);\n}\n\nfunction holdsProfile(dir: string, pid: number): boolean {\n try {\n if (readFileSync(lockPath(dir), \"utf8\").trim() !== String(pid)) return false;\n process.kill(pid, 0);\n return true;\n } catch { return false; }\n}\n\n/**\n * The client's: the secret the profile's daemon wrote, or null when there is none, or it is not a file of this user's\n * alone (a link, another user's file, one others may read): then it proves nothing. On Windows the file has the\n * folder's ACL (owner-only in the user's home); Node can check no more than that it is a plain file.\n */\nexport function readDaemonSecret(dir: string): Buffer | null {\n const file = daemonSecretPath(dir);\n try {\n const info = lstatSync(file);\n if (!info.isFile()) return null;\n if (process.platform !== \"win32\" && ((process.getuid && info.uid !== process.getuid()) || (info.mode & 0o077) !== 0)) return null;\n const text = readFileSync(file, \"utf8\").trim();\n return /^[0-9a-f]{64}$/.test(text) ? Buffer.from(text, \"hex\") : null;\n } catch { return null; }\n}\n\n/** Whether `answer` (the result of a `daemon.hello` with `nonce`) is the daemon's proof over it, in constant time. */\nexport function provesDaemon(secret: Buffer, nonce: string, answer: unknown): boolean {\n const given = (answer as { proof?: unknown } | null)?.proof;\n if (typeof given !== \"string\" || !/^[0-9a-f]{64}$/.test(given)) return false;\n return timingSafeEqual(Buffer.from(given, \"hex\"), Buffer.from(proof(secret, \"daemon\", nonce), \"hex\"));\n}\n","import { readFileSync } from \"node:fs\";\nimport { connect, type Socket } from \"node:net\";\nimport { createInterface } from \"node:readline\";\nimport { CliError, type ErrorCode } from \"./errors\";\nimport type { GhostlyEvent } from \"./events\";\nimport { daemonOfThisRelease, HELLO, newNonce, provesDaemon, provesGreeting, readDaemonSecret } from \"./daemonProof\";\nimport { ownSocket } from \"./privateFolder\";\nimport { lockPath } from \"./profiles\";\n\n/** The id of the hello on every connection: a string, so it is never one of the calls' numbers. */\nconst HELLO_ID = \"hello\";\n\n/**\n * How long a client waits for the daemon's greeting before it asks who holds the profile: a daemon greets as it\n * accepts the connection, and one of an older release (before the greeting) never does. A daemon of this release\n * holding the profile (`daemonOfThisRelease`) is busy and is waited for, under each call's own deadline; anything\n * else is refused then. It used to refuse every late greeting, after 10 s: a daemon busy that long on one task (an\n * outbox backlog, 14 to 29 s) had every command and `listen` refused as an older release's, to be restarted.\n */\nexport const GREETING_MS = 2_000;\n\n/** The longest request line the daemon reads (WISP 1100 § Framing): it cuts the connection on a longer one. */\nexport const MAX_LINE = 16 * 1024 * 1024;\n\n/** What a client needs of a profile to reach its daemon: the socket, and the folder the daemon's secret is in. */\nexport interface DaemonAddress { socket: string; dir: string }\n\n/**\n * The refusal of a listener that did not prove it is the profile's daemon (`isNotTheDaemon` tells it apart). With nobody\n * holding the profile it is no daemon of any release, and no restart moves it: the answer pointed at `daemon restart`,\n * which answered the same, and a start said a daemon ran. What listens there has to stop, or its file go. `held`: whether\n * a process holds the profile, as the caller knows it (`lockOwner`); read here as a greeting's proof reads it otherwise.\n */\nexport function notTheDaemon(address: DaemonAddress, held = profileHeld(address.dir)): CliError {\n if (!held) {\n return new CliError(\"refused\", `Something that is not this profile's daemon listens on ${address.socket}, and no ghostly process holds the profile: nothing was sent to it. Stop the program that listens there, or remove that file, then start the daemon with ghostly daemon --detach`, { reason: \"not-the-daemon\", socket: address.socket });\n }\n return new CliError(\"refused\", `What answers on ${address.socket} did not prove it is this profile's daemon, so nothing was sent to it. A daemon of an older release cannot: \\`ghostly daemon restart\\` starts this one's`, { reason: \"not-the-daemon\" });\n}\n\n/** Whether a live process of this user's is in the profile's lock (`daemonProof.ts` reads it the same way). */\nfunction profileHeld(dir: string): boolean {\n try {\n const pid = Number(readFileSync(lockPath(dir), \"utf8\").trim());\n if (!Number.isSafeInteger(pid) || pid <= 0) return false;\n process.kill(pid, 0);\n return true;\n } catch { return false; }\n}\n\n/** The failures of calls whose connection ended unanswered (`endedUnanswered`), not answers the daemon gave. */\nconst unanswered = new WeakSet<CliError>();\n\n/**\n * A call the daemon read and never answered, because it stopped (a restart, a crash): what was asked may be done, so\n * it is no plain failure a bot tries again (a send went twice). A daemon that stops answers its waits first (`serve`);\n * this is for the calls it could not.\n */\nfunction stoppedUnanswered(method: string): CliError {\n const error = new CliError(\"timeout\", `The daemon stopped before it answered ${method}, which may be done: check (\\`ghostly chat history\\` for a message) before you try again`, { method, reason: \"daemon-stopped\" });\n unanswered.add(error);\n return error;\n}\n\n/**\n * A call whose connection ended before the daemon read it, or before it proved itself: nothing was done. `leaving`: this\n * client ended it (a deadline, Ctrl-C), so it is no daemon that stopped under the call.\n */\nfunction wentAway(leaving: boolean): CliError {\n const error = new CliError(\"unavailable\", \"The daemon went away\");\n if (!leaving) unanswered.add(error);\n return error;\n}\n\n/**\n * Whether a call failed because its connection ended unanswered (the daemon stopped, restarted or crashed under it),\n * not because the daemon answered it with an error. A read that did can be asked again: it changed nothing. So may one\n * refused because the daemon's secret was gone when its greeting or its hello's answer came: a daemon that stops removes\n * it first, and the greeting it wrote just before is read after. Nothing but the hello was written to it, and a listener\n * that never proves itself is refused again on the new connection.\n */\nexport function endedUnanswered(error: unknown): boolean {\n return error instanceof CliError && unanswered.has(error);\n}\n\n/**\n * Whether a call ended unanswered before it was written (`endedUnanswered`, and not a call the daemon read: those are\n * `daemon-stopped`): nothing reached the daemon, so the call may go to the daemon that runs next, whatever it does.\n */\nexport function endedUnsent(error: unknown): boolean {\n return endedUnanswered(error) && (error as CliError).details?.reason !== \"daemon-stopped\";\n}\n\nexport function isNotTheDaemon(error: unknown): boolean {\n return error instanceof CliError && error.code === \"refused\" && error.details?.reason === \"not-the-daemon\";\n}\n\n/**\n * A connection to a profile's daemon over its socket (WISP 1100 § Local control API). `null` from `connectDaemon`\n * means no daemon answers there: a one-shot command runs the profile itself.\n *\n * The client writes nothing on it until the daemon's greeting, its first line, proves the other end read the\n * profile's daemon secret and holds the profile's lock (`provesGreeting`): a listener that cannot prove it has read\n * nothing from this client, so it cannot impersonate it either (`daemonProof.ts`). Then the first line written is a\n * `daemon.hello`, and no call is written until its answer proves the same over the client's own nonce. Until then\n * every call waits, under its own deadline, and a listener that does not prove both gets every call refused\n * (`refused`, `isNotTheDaemon`). Nothing it writes before that is read either.\n */\nexport class DaemonClient {\n private nextId = 1;\n /** `written`: the call is on the socket, so the daemon may have acted on it. */\n private readonly pending = new Map<number, { method: string; written: boolean; resolve: (value: unknown) => void; reject: (error: Error) => void }>();\n /** This client closed the connection: what was still unanswered is its own doing, not a daemon that stopped. */\n private leaving = false;\n private eventListener: ((event: GhostlyEvent) => void) | null = null;\n private closedListener: (() => void) | null = null;\n /** While paused: the events of the chunk already read, given to the listener on resume. */\n private held: GhostlyEvent[] | null = null;\n private greeted = false;\n private verified = false;\n private refusal: CliError | null = null;\n private readonly ready: Promise<void>;\n private settle!: { resolve: () => void; reject: (error: CliError) => void };\n\n constructor(private readonly socket: Socket, private readonly address: DaemonAddress, greetingMs = GREETING_MS) {\n this.ready = new Promise<void>((resolve, reject) => { this.settle = { resolve, reject }; });\n this.ready.catch(() => {});\n const nonce = newNonce();\n // Nothing is written until the greeting either way: a busy daemon only keeps the calls waiting.\n const waitedTooLong = setTimeout(() => { if (!this.greeted && !this.refusal && !daemonOfThisRelease(this.address.dir)) this.refuse(); }, greetingMs);\n waitedTooLong.unref?.();\n const lines = createInterface({ input: socket, crlfDelay: Infinity });\n // readline passes on its input's errors: a daemon that went away with this client's lines unread (ECONNRESET) ended\n // the command on an unhandled 'error' instead of the close below (unavailable).\n lines.on(\"error\", () => {});\n lines.on(\"line\", (line) => {\n let message: { id?: number | string; result?: unknown; error?: { code: ErrorCode; message: string; details?: Record<string, unknown> }; event?: GhostlyEvent };\n // A first line that is not even JSON is no greeting: refused as one that does not prove itself.\n try { message = JSON.parse(line); } catch { if (!this.greeted && !this.refusal) this.refuse(); return; }\n if (this.refusal) return;\n if (!this.greeted) {\n clearTimeout(waitedTooLong);\n // The secret is read once a listener spoke: the daemon wrote it before it listened.\n const secret = readDaemonSecret(this.address.dir);\n if (!secret || !provesGreeting(secret, this.address.dir, message)) { this.refuse(!secret); return; }\n this.greeted = true;\n // A client closed before the greeting came (a start's readiness probe) has nothing to say.\n if (socket.writableEnded || socket.destroyed) return;\n socket.write(JSON.stringify({ id: HELLO_ID, method: HELLO, params: { nonce } }) + \"\\n\");\n return;\n }\n if (!this.verified) {\n if (message?.id !== HELLO_ID) return;\n // The secret is read once a listener answered: the daemon wrote it before it listened.\n const secret = readDaemonSecret(this.address.dir);\n if (!message.error && secret && provesDaemon(secret, nonce, message.result)) { this.verified = true; this.settle.resolve(); return; }\n this.refuse(!secret);\n return;\n }\n if (message.event) { if (this.held) this.held.push(message.event); else this.eventListener?.(message.event); return; }\n const waiting = typeof message.id === \"number\" ? this.pending.get(message.id) : undefined;\n if (!waiting) return;\n this.pending.delete(message.id as number);\n if (message.error) waiting.reject(new CliError(message.error.code, message.error.message, message.error.details));\n else waiting.resolve(message.result);\n });\n socket.on(\"close\", () => {\n clearTimeout(waitedTooLong);\n const why = this.refusal ?? wentAway(this.leaving);\n if (!this.verified) this.settle.reject(why);\n for (const waiting of this.pending.values()) waiting.reject(waiting.written && !this.refusal && !this.leaving ? stoppedUnanswered(waiting.method) : why);\n this.pending.clear();\n this.closedListener?.();\n });\n socket.on(\"error\", () => {});\n }\n\n /** `secretGone`: the daemon's secret was not there to check against, as when it stops (`endedUnanswered`). */\n private refuse(secretGone = false): void {\n this.refusal = notTheDaemon(this.address);\n if (secretGone) unanswered.add(this.refusal);\n this.settle.reject(this.refusal);\n this.socket.destroy();\n }\n\n /**\n * `timeoutMs`: give up (code `timeout`, exit 4) when the daemon has not answered by then; without it the call waits\n * for as long as the connection holds. A call that timed out closes the connection: its answer, if one ever comes,\n * is of no use, and the process leaves once nothing else keeps it (not every caller reaches `exit`).\n *\n * A call whose line is longer than `MAX_LINE` is refused here, never written: the daemon cut the connection on it,\n * and the command answered \"The daemon went away\" (`unavailable`, read as try later) while the daemon ran on.\n */\n call(method: string, params: unknown = {}, { timeoutMs }: { timeoutMs?: number } = {}): Promise<unknown> {\n if (this.socket.destroyed) return Promise.reject(this.refusal ?? wentAway(this.leaving));\n const id = this.nextId++;\n const line = JSON.stringify({ id, method, params }) + \"\\n\";\n const bytes = Buffer.byteLength(line);\n if (bytes > MAX_LINE) return Promise.reject(new CliError(\"bad_request\", `${method} came to ${(bytes / 1024 / 1024).toFixed(1)} MiB as JSON, more than a daemon reads in one request (16 MiB): nothing was sent (a long text goes as a file: ghostly file send <chat|group> <path>)`));\n return new Promise((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n if (timeoutMs !== undefined) {\n timer = setTimeout(() => {\n if (!this.pending.delete(id)) return;\n reject(new CliError(\"timeout\", `The daemon did not answer ${method} in ${timeoutMs / 1000} s: \\`ghostly daemon restart\\` starts a fresh one`, { method }));\n this.destroy();\n }, timeoutMs);\n timer.unref?.();\n }\n const settle = {\n method, written: false,\n resolve: (value: unknown) => { if (timer) clearTimeout(timer); resolve(value); },\n reject: (error: Error) => { if (timer) clearTimeout(timer); reject(error); },\n };\n this.pending.set(id, settle);\n // Written once the daemon proved itself, in the order the calls were made; a refusal ends each instead.\n this.ready.then(\n () => {\n if (!this.pending.has(id) || this.socket.destroyed) return;\n this.socket.write(line);\n settle.written = true;\n },\n (error: CliError) => { if (this.pending.delete(id)) settle.reject(error); },\n );\n });\n }\n\n /** Events after `since` (replayed from the journal), then every new one, until the connection closes. */\n async subscribe(since: number | undefined, listener: (event: GhostlyEvent) => void, onClosed?: () => void): Promise<{ lastSeq: number }> {\n this.eventListener = listener;\n this.closedListener = onClosed ?? null;\n return this.call(\"events.subscribe\", since === undefined ? {} : { since }) as Promise<{ lastSeq: number }>;\n }\n\n /**\n * Stops reading: what the daemon sends waits in the connection (and past its bound the daemon ends it), and no\n * event reaches the listener until `resume`.\n */\n pause(): void {\n if (this.held) return;\n this.held = [];\n this.socket.pause();\n }\n\n /** Gives the listener the events held, then reads again; a listener that pauses again keeps the rest held. */\n resume(): void {\n const held = this.held;\n if (!held) return;\n this.held = null;\n for (let i = 0; i < held.length; i++) {\n this.eventListener?.(held[i]);\n if (this.held) { (this.held as GhostlyEvent[]).unshift(...held.slice(i + 1)); return; }\n }\n this.socket.resume();\n }\n\n close(): void {\n this.leaving = true;\n this.socket.end();\n }\n\n /** Closes at once: what the daemon still sends is not read. */\n destroy(): void {\n this.leaving = true;\n this.socket.destroy();\n }\n}\n\n/**\n * `timeoutMs` bounds the connect only; `greetingMs`, the wait for the daemon's greeting (above). The client it gives\n * has written nothing yet; whether the listener is the daemon is known at the first call.\n */\nexport function connectDaemon(address: DaemonAddress, timeoutMs = 2_000, { greetingMs = GREETING_MS }: { greetingMs?: number } = {}): Promise<DaemonClient | null> {\n const path = address.socket;\n // Someone else's socket (or a link) where the daemon's should be is no daemon of this profile's.\n if (!ownSocket(path)) return Promise.resolve(null);\n return new Promise((resolve) => {\n const socket = connect(path);\n const timer = setTimeout(() => { socket.destroy(); resolve(null); }, timeoutMs);\n socket.once(\"connect\", () => { clearTimeout(timer); resolve(new DaemonClient(socket, address, greetingMs)); });\n socket.once(\"error\", () => { clearTimeout(timer); resolve(null); });\n });\n}\n"],"mappings":";;;;;;;AAMA,IAAa,aAAa;CAAC;CAAM;CAAO;CAAO;CAAO;AAAK;AAE3D,IAAa,eAAyB;AAEtC,IAAa,gBAAgB,SAA4B,OAAA,KAAmB;AAC5E,IAAa,cAAc,SAA2B,aAAa,IAAI,IAAI;AAC3E,IAAa,aAAa,MAAgB,UAA0B,KAAK,MAAO,QAAQ,IAAI,OAAQ,GAAI;AAExG,SAAgB,WAAW,OAAmC;CAC5D,OAAO,WAAW,SAAS,KAAiB;AAC9C;;AAGA,IAAa,eAAe;;;;;;AAa5B,IAAa,kBAA0B,YAAY,IAAI;;;;;AAMvD,IAAa,gBAAb,MAA2B;CAaJ;CAAiC;CAZtD,SAA2B,CAAC;CAC5B,OAAe;CACf,SAA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 -1,5 +1,4 @@
1
- import "./src-DjVj2ynY.js";
2
- //#region ../browser/src/backup/codec.ts
1
+ // ../browser/src/backup/codec.ts
3
2
  function fromBase64Url(text) {
4
3
  if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("Invalid base64url");
5
4
  const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - text.length % 4) % 4));
@@ -7,7 +6,6 @@ function fromBase64Url(text) {
7
6
  for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
8
7
  return bytes;
9
8
  }
10
- //#endregion
11
9
  export { fromBase64Url as t };
12
10
 
13
- //# sourceMappingURL=codec-DMpQqVSt.js.map
11
+ //# sourceMappingURL=codec-B2rH1mfx.js.map