@ghostlytools/cli 1.11.4 → 1.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -14
- package/dist/assets/{api-MYc6QNRs.js → api-BwEgbvvK.js} +395 -131
- package/dist/assets/api-BwEgbvvK.js.map +1 -0
- package/dist/assets/{api-BwyFq4lA.js → api-jRUXnBdX.js} +2 -2
- package/dist/assets/{apiKit-CfsNx9ZR.js → apiKit-BlsNk-Cx.js} +48 -11
- package/dist/assets/apiKit-BlsNk-Cx.js.map +1 -0
- package/dist/assets/appFetch-CW9fJPHh.js +602 -0
- package/dist/assets/appFetch-CW9fJPHh.js.map +1 -0
- package/dist/assets/apps-BcG4u6SM.js +1 -0
- package/dist/assets/{apps-h12II1us.js → apps-CL8TXHhu.js} +20 -14
- package/dist/assets/apps-CL8TXHhu.js.map +1 -0
- package/dist/assets/{argon2id-088uQfnH.js → argon2id-B9wFdSj6.js} +2 -3
- package/dist/assets/{argon2id-088uQfnH.js.map → argon2id-B9wFdSj6.js.map} +1 -1
- package/dist/assets/{arkade-Bw_4PZRG.js → arkade-DryM-q5n.js} +6 -7
- package/dist/assets/arkade-DryM-q5n.js.map +1 -0
- package/dist/assets/{backup-Chvy79SN.js → backup-BA41EDvh.js} +110 -26
- package/dist/assets/backup-BA41EDvh.js.map +1 -0
- package/dist/assets/backup-xZfV-ytw.js +1 -0
- package/dist/assets/bark_ffi_wasm_bg-CcafsJla.js +5 -0
- package/dist/assets/bark_ffi_wasm_bg-CcafsJla.js.map +1 -0
- package/dist/assets/{bark_ffi_wasm_bg-Bxru_BVW.wasm → bark_ffi_wasm_bg-VNmaJsc9.wasm} +0 -0
- package/dist/assets/{bitcoind-CdSmvy2y.js → bitcoind-Dh7n9amb.js} +4 -5
- package/dist/assets/{bitcoind-CdSmvy2y.js.map → bitcoind-Dh7n9amb.js.map} +1 -1
- package/dist/assets/bitcoindevkit_bg-BWQHx7vd.js +5 -0
- package/dist/assets/bitcoindevkit_bg-BWQHx7vd.js.map +1 -0
- package/dist/assets/bitcoindevkit_bg-DXil67yS.wasm +0 -0
- package/dist/assets/{blobFiles-BmsrvZc3.js → blobFiles-DDs34n0r.js} +4 -5
- package/dist/assets/{blobFiles-BmsrvZc3.js.map → blobFiles-DDs34n0r.js.map} +1 -1
- package/dist/assets/breez_sdk_spark_wasm_bg.wasm +0 -0
- package/dist/assets/buttons-CsGdQNnR.js +1 -0
- package/dist/assets/{buttons-BgoExb4E.js → buttons-SH1tNRh7.js} +45 -23
- package/dist/assets/buttons-SH1tNRh7.js.map +1 -0
- package/dist/assets/bytes-C1DNGY18.js +132 -0
- package/dist/assets/bytes-C1DNGY18.js.map +1 -0
- package/dist/assets/{childEnv-K_IzUqQx.js → childEnv-C-99hdbL.js} +2 -3
- package/dist/assets/{childEnv-K_IzUqQx.js.map → childEnv-C-99hdbL.js.map} +1 -1
- package/dist/assets/{client-DY8tZZWi.js → client-DGS-atRu.js} +5 -8
- package/dist/assets/{client-DY8tZZWi.js.map → client-DGS-atRu.js.map} +1 -1
- package/dist/assets/{codec-BnMg-Grj.js → codec-B2rH1mfx.js} +2 -4
- package/dist/assets/{codec-BnMg-Grj.js.map → codec-B2rH1mfx.js.map} +1 -1
- package/dist/assets/domainProofs-BDNP1dIy.js +280 -0
- package/dist/assets/domainProofs-BDNP1dIy.js.map +1 -0
- package/dist/assets/{endpoint-DarqblYE.js → endpoint-Cvu-taMs.js} +462 -424
- package/dist/assets/endpoint-Cvu-taMs.js.map +1 -0
- package/dist/assets/engineErrors--9hfgKlK.js +150 -0
- package/dist/assets/engineErrors--9hfgKlK.js.map +1 -0
- package/dist/assets/{envelope-CdV7vHVZ.js → envelope-Bi2kMqbp.js} +3 -4
- package/dist/assets/{envelope-CdV7vHVZ.js.map → envelope-Bi2kMqbp.js.map} +1 -1
- package/dist/assets/{errors-CAh6GLJZ.js → errors-DDLFO4Gf.js} +5 -4
- package/dist/assets/errors-DDLFO4Gf.js.map +1 -0
- package/dist/assets/{fedimintSdk-CPFfVK-G.js → fedimintSdk-D-6H9Pe7.js} +4 -5
- package/dist/assets/{fedimintSdk-CPFfVK-G.js.map → fedimintSdk-D-6H9Pe7.js.map} +1 -1
- package/dist/assets/fedimint_client_wasm_bg-Cr5xGD-w.js +5 -0
- package/dist/assets/{fedimint_client_wasm_bg-BtHHlFpp.js.map → fedimint_client_wasm_bg-Cr5xGD-w.js.map} +1 -1
- package/dist/assets/fileBytes-CCKbwqG_.js +1 -0
- package/dist/assets/{fileBytes-BLPZq9YU.js → fileBytes-CfvUXdSy.js} +5 -7
- package/dist/assets/fileBytes-CfvUXdSy.js.map +1 -0
- package/dist/assets/{fileBytes-B0z9A6Le.js → fileBytes-tj6-VZcB.js} +3 -4
- package/dist/assets/{fileBytes-B0z9A6Le.js.map → fileBytes-tj6-VZcB.js.map} +1 -1
- package/dist/assets/fileBytesIdb-B0zzJ6p7.js +1 -0
- package/dist/assets/{fileBytesIdb-Bmlrl9EO.js → fileBytesIdb-BJirUAjI.js} +4 -5
- package/dist/assets/{fileBytesIdb-Bmlrl9EO.js.map → fileBytesIdb-BJirUAjI.js.map} +1 -1
- package/dist/assets/{fileBytesOpfs-DBS0kbPT.js → fileBytesOpfs-DRUYLER4.js} +4 -5
- package/dist/assets/{fileBytesOpfs-DBS0kbPT.js.map → fileBytesOpfs-DRUYLER4.js.map} +1 -1
- package/dist/assets/{fixedHosts-CbgqrIKs.js → fixedHosts-CPSsGOI2.js} +4 -5
- package/dist/assets/{fixedHosts-CbgqrIKs.js.map → fixedHosts-CPSsGOI2.js.map} +1 -1
- package/dist/assets/{ghostly_iroh_web-BzAXJUYH.js → ghostly_iroh_web-DIj5xGmR.js} +2 -3
- package/dist/assets/{ghostly_iroh_web-BzAXJUYH.js.map → ghostly_iroh_web-DIj5xGmR.js.map} +1 -1
- package/dist/assets/{src-DJe-OYxd.js → groupMeta-DxuJzko_.js} +6009 -25536
- package/dist/assets/groupMeta-DxuJzko_.js.map +1 -0
- package/dist/assets/{host-C0NMNQLl.js → host-BxM-HMr0.js} +262 -134
- package/dist/assets/host-BxM-HMr0.js.map +1 -0
- package/dist/assets/{hyperdhtRelay-Dz7pvcBA.js → hyperdhtRelay-DLUiwfnt.js} +36 -9
- package/dist/assets/hyperdhtRelay-DLUiwfnt.js.map +1 -0
- package/dist/assets/hyperdhtRelay-bjNGacf5.js +32 -0
- package/dist/assets/hyperdhtRelay-bjNGacf5.js.map +1 -0
- package/dist/assets/{idb-CEuoNsTv.js → idb-ewvbqyDI.js} +2 -3
- package/dist/assets/{idb-CEuoNsTv.js.map → idb-ewvbqyDI.js.map} +1 -1
- package/dist/assets/identityProofs-Cksc_K7_.js +940 -0
- package/dist/assets/identityProofs-Cksc_K7_.js.map +1 -0
- package/dist/assets/{irohWeb-caAj4Dms.js → irohWeb-CbnGtUo6.js} +3231 -87
- package/dist/assets/irohWeb-CbnGtUo6.js.map +1 -0
- package/dist/assets/joinTrace-CBr1jbch.js +1 -0
- package/dist/assets/{joinTrace-CjRDFy85.js → joinTrace-xKBe73j9.js} +2 -3
- package/dist/assets/{joinTrace-CjRDFy85.js.map → joinTrace-xKBe73j9.js.map} +1 -1
- package/dist/assets/{legacy_ciphers-JJOu0JXL.js → legacy_ciphers-BnYATjxo.js} +2 -3
- package/dist/assets/{legacy_ciphers-JJOu0JXL.js.map → legacy_ciphers-BnYATjxo.js.map} +1 -1
- package/dist/assets/linkPreview-DdMf-YAc.js +252 -0
- package/dist/assets/linkPreview-DdMf-YAc.js.map +1 -0
- package/dist/assets/{main-C6t5zrD5.js → main-CwTaepxR.js} +296 -122
- package/dist/assets/main-CwTaepxR.js.map +1 -0
- package/dist/assets/{mainline-DCuGUSZF.js → mainline-CVrd0C1n.js} +72 -18
- package/dist/assets/mainline-CVrd0C1n.js.map +1 -0
- package/dist/assets/mints-BcBODVVW.js +1 -0
- package/dist/assets/{mints-j5XAOk4f.js → mints-CMDLbMeH.js} +8 -6
- package/dist/assets/mints-CMDLbMeH.js.map +1 -0
- package/dist/assets/{nacl-fast-CDhNCYHs.js → nacl-fast-B1ThWvuM.js} +2 -3
- package/dist/assets/{nacl-fast-CDhNCYHs.js.map → nacl-fast-B1ThWvuM.js.map} +1 -1
- package/dist/assets/{networkReason-BbQW1Xpc.js → networkReason-Be-hMghr.js} +10 -14
- package/dist/assets/{networkReason-BbQW1Xpc.js.map → networkReason-Be-hMghr.js.map} +1 -1
- package/dist/assets/{noble_curves-DDWn5AH0.js → noble_curves-DqpNlhAU.js} +3 -4
- package/dist/assets/{noble_curves-DDWn5AH0.js.map → noble_curves-DqpNlhAU.js.map} +1 -1
- package/dist/assets/{noble_hashes-B7AZyFyS.js → noble_hashes-LFe1N2xt.js} +3 -4
- package/dist/assets/{noble_hashes-B7AZyFyS.js.map → noble_hashes-LFe1N2xt.js.map} +1 -1
- package/dist/assets/{nwc-CSDRMZ0e.js → nwc-DKE2FXr6.js} +5 -6
- package/dist/assets/{nwc-CSDRMZ0e.js.map → nwc-DKE2FXr6.js.map} +1 -1
- package/dist/assets/nwcProvider-pL2XqSbW.js +208 -0
- package/dist/assets/nwcProvider-pL2XqSbW.js.map +1 -0
- package/dist/assets/{openpgp-BBFr-zHQ.js → openpgp-LkR_Zof0.js} +14 -15
- package/dist/assets/{openpgp-BBFr-zHQ.js.map → openpgp-LkR_Zof0.js.map} +1 -1
- package/dist/assets/ownDid-DY3rYqDI.js +862 -0
- package/dist/assets/ownDid-DY3rYqDI.js.map +1 -0
- package/dist/assets/{ownStatus-BoTf5WqQ.js → ownStatus-DtzIllg2.js} +70 -20
- package/dist/assets/ownStatus-DtzIllg2.js.map +1 -0
- package/dist/assets/pairedTransports-BKmvlKz1.js +581 -0
- package/dist/assets/pairedTransports-BKmvlKz1.js.map +1 -0
- package/dist/assets/paymentIntent-DySU3Ajm.js +349 -0
- package/dist/assets/paymentIntent-DySU3Ajm.js.map +1 -0
- package/dist/assets/pkarr-BQo4PcCg.js +367 -0
- package/dist/assets/pkarr-BQo4PcCg.js.map +1 -0
- package/dist/assets/{profiles-DszHjEJi.js → profiles-BOYGlmu2.js} +9 -10
- package/dist/assets/profiles-BOYGlmu2.js.map +1 -0
- package/dist/assets/registry-4W1LGlCF.js +1 -0
- package/dist/assets/{registry-Da-r6eC3.js → registry-Bep4umOM.js} +1296 -80
- package/dist/assets/registry-Bep4umOM.js.map +1 -0
- package/dist/assets/relay-Cjfmdec0.js +2219 -0
- package/dist/assets/relay-Cjfmdec0.js.map +1 -0
- package/dist/assets/resolve-CIc3KZMV.js +970 -0
- package/dist/assets/resolve-CIc3KZMV.js.map +1 -0
- package/dist/assets/{restoredRows-C3LcxmOw.js → restoredRows-D_WSHE7H.js} +3 -4
- package/dist/assets/{restoredRows-C3LcxmOw.js.map → restoredRows-D_WSHE7H.js.map} +1 -1
- package/dist/assets/secretGuard-Bm6nci0I.js +1 -0
- package/dist/assets/{secretGuard-CsVHDdYk.js → secretGuard-BrATm_gl.js} +43 -22
- package/dist/assets/{secretGuard-CsVHDdYk.js.map → secretGuard-BrATm_gl.js.map} +1 -1
- package/dist/assets/{server-C1jZZ61O.js → server-D4gf-LnD.js} +9797 -479
- package/dist/assets/server-D4gf-LnD.js.map +1 -0
- package/dist/assets/{sha512-BYId-G-T.js → sha512-DST9fbWH.js} +2 -3
- package/dist/assets/{sha512-BYId-G-T.js.map → sha512-DST9fbWH.js.map} +1 -1
- package/dist/assets/sshForges-BnvwmNj-.js +539 -0
- package/dist/assets/sshForges-BnvwmNj-.js.map +1 -0
- package/dist/assets/{storage-Bya5b2Xt.js → storage-BpjdxvO2.js} +243 -34
- package/dist/assets/storage-BpjdxvO2.js.map +1 -0
- package/dist/assets/text-li76pThX.js +106 -0
- package/dist/assets/text-li76pThX.js.map +1 -0
- package/dist/assets/{translate-CUuC5szR.js → translate-BcbSWkuq.js} +21 -26
- package/dist/assets/{translate-CUuC5szR.js.map → translate-BcbSWkuq.js.map} +1 -1
- package/dist/assets/{tree-store-N362nuzZ.js → tree-store-CAchkO_l.js} +22 -6
- package/dist/assets/tree-store-CAchkO_l.js.map +1 -0
- package/dist/assets/{types-Clyb52K2.js → types-CdWwgvyt.js} +2 -3
- package/dist/assets/{types-Clyb52K2.js.map → types-CdWwgvyt.js.map} +1 -1
- package/dist/assets/{unbzip2-stream-B1C-JX9L.js → unbzip2-stream-BtkYGpC5.js} +2 -3
- package/dist/assets/{unbzip2-stream-B1C-JX9L.js.map → unbzip2-stream-BtkYGpC5.js.map} +1 -1
- package/dist/assets/{usdt-DI51znt-.js → usdt-CBJ4Q5Ji.js} +7 -7
- package/dist/assets/usdt-CBJ4Q5Ji.js.map +1 -0
- package/dist/assets/{waitNotice-Cn0WJ-He.js → waitNotice-DQvZgz2T.js} +27 -4
- package/dist/assets/waitNotice-DQvZgz2T.js.map +1 -0
- package/dist/assets/{web-DwgdhfcY.js → web-68CYFCl9.js} +314 -91
- package/dist/assets/web-68CYFCl9.js.map +1 -0
- package/dist/ghostly.mjs +3 -5
- package/dist/ghostly.mjs.map +1 -1
- package/npm-shrinkwrap.json +225 -200
- package/package.json +16 -16
- package/dist/assets/api-MYc6QNRs.js.map +0 -1
- package/dist/assets/apiKit-CfsNx9ZR.js.map +0 -1
- package/dist/assets/appFetch-DVYZOZFw.js +0 -194
- package/dist/assets/appFetch-DVYZOZFw.js.map +0 -1
- package/dist/assets/apps-Dbw2Hcko.js +0 -2
- package/dist/assets/apps-h12II1us.js.map +0 -1
- package/dist/assets/arkade-Bw_4PZRG.js.map +0 -1
- package/dist/assets/backup-CdEzTq5C.js +0 -2
- package/dist/assets/backup-Chvy79SN.js.map +0 -1
- package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js +0 -6
- package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +0 -1
- package/dist/assets/bitcoindProvider-BvoRh0D5.js +0 -97
- package/dist/assets/bitcoindProvider-BvoRh0D5.js.map +0 -1
- package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js +0 -6
- package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +0 -1
- package/dist/assets/bitcoindevkit_bg-CRkZTSbO.wasm +0 -0
- package/dist/assets/buttons-BgoExb4E.js.map +0 -1
- package/dist/assets/buttons-DK2aAGat.js +0 -2
- package/dist/assets/endpoint-DarqblYE.js.map +0 -1
- package/dist/assets/errors-CAh6GLJZ.js.map +0 -1
- package/dist/assets/fedimint_client_wasm_bg-BtHHlFpp.js +0 -6
- package/dist/assets/fileBytes-BLPZq9YU.js.map +0 -1
- package/dist/assets/fileBytes-BtIyoDF2.js +0 -2
- package/dist/assets/fileBytesIdb-D8mAK4pF.js +0 -2
- package/dist/assets/host-C0NMNQLl.js.map +0 -1
- package/dist/assets/hyperdhtRelay-1wzya_0L.js +0 -25
- package/dist/assets/hyperdhtRelay-1wzya_0L.js.map +0 -1
- package/dist/assets/hyperdhtRelay-Dz7pvcBA.js.map +0 -1
- package/dist/assets/irohWeb-caAj4Dms.js.map +0 -1
- package/dist/assets/joinTrace-D-fnt2p3.js +0 -2
- package/dist/assets/jsonOut-POtMBS_V.js +0 -16
- package/dist/assets/jsonOut-POtMBS_V.js.map +0 -1
- package/dist/assets/main-C6t5zrD5.js.map +0 -1
- package/dist/assets/mainline-DCuGUSZF.js.map +0 -1
- package/dist/assets/mints-BaOmx517.js +0 -2
- package/dist/assets/mints-j5XAOk4f.js.map +0 -1
- package/dist/assets/nwcProvider-PE0wli8n.js +0 -88
- package/dist/assets/nwcProvider-PE0wli8n.js.map +0 -1
- package/dist/assets/ownDid-C1R5Kd8q.js +0 -282
- package/dist/assets/ownDid-C1R5Kd8q.js.map +0 -1
- package/dist/assets/ownStatus-BoTf5WqQ.js.map +0 -1
- package/dist/assets/profiles-DszHjEJi.js.map +0 -1
- package/dist/assets/registry-Da-r6eC3.js.map +0 -1
- package/dist/assets/registry-zUZBSHYv.js +0 -2
- package/dist/assets/resolve-tUzh4lHh.js +0 -400
- package/dist/assets/resolve-tUzh4lHh.js.map +0 -1
- package/dist/assets/secretGuard-DCb1I0_B.js +0 -2
- package/dist/assets/server-C1jZZ61O.js.map +0 -1
- package/dist/assets/src-DJe-OYxd.js.map +0 -1
- package/dist/assets/sshForges-C9zTO72R.js +0 -261
- package/dist/assets/sshForges-C9zTO72R.js.map +0 -1
- package/dist/assets/storage-Bya5b2Xt.js.map +0 -1
- package/dist/assets/tree-store-N362nuzZ.js.map +0 -1
- package/dist/assets/usdt-DI51znt-.js.map +0 -1
- package/dist/assets/waitNotice-Cn0WJ-He.js.map +0 -1
- package/dist/assets/web-DwgdhfcY.js.map +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as hyperdhtRelayProblem } from "./hyperdhtRelay-
|
|
1
|
+
import { i as fromBase64Url } from "./bytes-C1DNGY18.js";
|
|
2
|
+
import { n as hyperdhtRelayUrl, t as hyperdhtRelayProblem } from "./hyperdhtRelay-bjNGacf5.js";
|
|
3
3
|
import { ed25519 } from "@noble/curves/ed25519.js";
|
|
4
|
-
|
|
4
|
+
// ../browser/src/platform/hyperdhtRelay.ts
|
|
5
5
|
/**
|
|
6
6
|
* HyperDHT (WISP 103) for a browser, through a dht-relay: a server that runs the UDP half of HyperDHT and
|
|
7
7
|
* talks to the browser over one WebSocket. It runs non-custodial: the browser keeps its keys, runs the
|
|
@@ -24,6 +24,11 @@ var RELAY_OPEN_MS = 1e4;
|
|
|
24
24
|
var LISTEN_MS = 2e4;
|
|
25
25
|
var MAX_CHANNELS = 2;
|
|
26
26
|
/**
|
|
27
|
+
* Streams dialled in that have not sent the preface yet. They hold none of the MAX_CHANNELS: a new one past this many
|
|
28
|
+
* drops the oldest of them, so streams that stall can never keep the contact's out.
|
|
29
|
+
*/
|
|
30
|
+
var MAX_UNPREFACED = 4;
|
|
31
|
+
/**
|
|
27
32
|
* How the relay client is always made: never custodial. dht-relay's default is custodial, which sends every
|
|
28
33
|
* secret key to the relay so it can run the handshake and the stream itself. Nothing here takes this from
|
|
29
34
|
* settings or options; test/hyperdhtRelay.test.ts fails if a secret key ever reaches the relay's wire.
|
|
@@ -190,14 +195,23 @@ function writeFrame(socket, payload, binary = false) {
|
|
|
190
195
|
* Waits for the peer's preface on an authenticated stream (sending ours as soon as the handshake is
|
|
191
196
|
* done), then hands the channel over with the binding the stream itself gives. A frame of the wrong size,
|
|
192
197
|
* bytes that are not UTF-8 or another protocol close the stream.
|
|
198
|
+
*
|
|
199
|
+
* `dialledIn`: the stream was dialled in, and takes one of its MAX_CHANNELS only once its preface came. This side's own
|
|
200
|
+
* dials are not counted: one always goes out.
|
|
193
201
|
*/
|
|
194
|
-
function attach(socket, channels) {
|
|
195
|
-
if (
|
|
202
|
+
function attach(socket, channels, dialledIn) {
|
|
203
|
+
if (dialledIn && dialledIn.live.size >= MAX_CHANNELS) {
|
|
196
204
|
socket.destroy();
|
|
197
205
|
return Promise.reject(/* @__PURE__ */ new Error("Native connection limit reached"));
|
|
198
206
|
}
|
|
207
|
+
if (dialledIn && dialledIn.unprefaced.size >= MAX_UNPREFACED) {
|
|
208
|
+
const [oldest] = dialledIn.unprefaced;
|
|
209
|
+
dialledIn.unprefaced.delete(oldest);
|
|
210
|
+
oldest.close();
|
|
211
|
+
}
|
|
199
212
|
const channel = new RelayedChannel(socket);
|
|
200
213
|
channels.add(channel);
|
|
214
|
+
dialledIn?.unprefaced.add(channel);
|
|
201
215
|
return new Promise((resolve, reject) => {
|
|
202
216
|
let buffer = /* @__PURE__ */ new Uint8Array(0);
|
|
203
217
|
let prefaced = false;
|
|
@@ -210,6 +224,8 @@ function attach(socket, channels) {
|
|
|
210
224
|
socket.on("close", () => {
|
|
211
225
|
clearTimeout(timer);
|
|
212
226
|
channels.delete(channel);
|
|
227
|
+
dialledIn?.live.delete(channel);
|
|
228
|
+
dialledIn?.unprefaced.delete(channel);
|
|
213
229
|
reject(/* @__PURE__ */ new Error("Native channel closed"));
|
|
214
230
|
channel.closedByPeer();
|
|
215
231
|
});
|
|
@@ -264,6 +280,14 @@ function attach(socket, channels) {
|
|
|
264
280
|
}
|
|
265
281
|
prefaced = true;
|
|
266
282
|
clearTimeout(timer);
|
|
283
|
+
if (dialledIn) {
|
|
284
|
+
dialledIn.unprefaced.delete(channel);
|
|
285
|
+
if (dialledIn.live.size >= MAX_CHANNELS) {
|
|
286
|
+
fail(/* @__PURE__ */ new Error("Native connection limit reached"));
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
dialledIn.live.add(channel);
|
|
290
|
+
}
|
|
267
291
|
resolve({
|
|
268
292
|
channel,
|
|
269
293
|
binding: {
|
|
@@ -298,6 +322,10 @@ async function createRelayedHyperEndpoint(seedB64, url, options = {}) {
|
|
|
298
322
|
const keyPair = hyperKeyPair(fromBase64Url(seedB64));
|
|
299
323
|
const client = await relayClient(url, options.createSocket ?? ((address) => new WebSocket(address)));
|
|
300
324
|
const channels = /* @__PURE__ */ new Set();
|
|
325
|
+
const dialledIn = {
|
|
326
|
+
live: /* @__PURE__ */ new Set(),
|
|
327
|
+
unprefaced: /* @__PURE__ */ new Set()
|
|
328
|
+
};
|
|
301
329
|
let stopped = false;
|
|
302
330
|
let handler = null;
|
|
303
331
|
const waiting = [];
|
|
@@ -312,7 +340,7 @@ async function createRelayedHyperEndpoint(seedB64, url, options = {}) {
|
|
|
312
340
|
} };
|
|
313
341
|
client.endpoints.add(member);
|
|
314
342
|
const server = client.node.createServer({}, (socket) => {
|
|
315
|
-
attach(socket, channels).then((bound) => {
|
|
343
|
+
attach(socket, channels, dialledIn).then((bound) => {
|
|
316
344
|
if (stopped) bound.channel.close();
|
|
317
345
|
else if (handler) handler(bound);
|
|
318
346
|
else if (waiting.length < MAX_CHANNELS) waiting.push(bound);
|
|
@@ -348,7 +376,7 @@ async function createRelayedHyperEndpoint(seedB64, url, options = {}) {
|
|
|
348
376
|
descriptor: {
|
|
349
377
|
publicKey: hex(keyPair.publicKey),
|
|
350
378
|
relayed: true,
|
|
351
|
-
relay: url
|
|
379
|
+
relay: hyperdhtRelayUrl(url)
|
|
352
380
|
},
|
|
353
381
|
onDescriptor: null,
|
|
354
382
|
onUnavailable: null,
|
|
@@ -374,7 +402,6 @@ async function createRelayedHyperEndpoint(seedB64, url, options = {}) {
|
|
|
374
402
|
};
|
|
375
403
|
return endpoint;
|
|
376
404
|
}
|
|
377
|
-
//#endregion
|
|
378
405
|
export { createRelayedHyperEndpoint };
|
|
379
406
|
|
|
380
|
-
//# sourceMappingURL=hyperdhtRelay-
|
|
407
|
+
//# sourceMappingURL=hyperdhtRelay-DLUiwfnt.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hyperdhtRelay-DLUiwfnt.js","names":[],"sources":["../../../browser/src/platform/hyperdhtRelay.ts"],"sourcesContent":["import { ed25519 } from \"@noble/curves/ed25519.js\";\nimport { fromBase64Url, type BoundChannel, type FrameChannel, type NativeEndpoint } from \"@ghostly/core\";\nimport { hyperdhtRelayProblem, hyperdhtRelayUrl } from \"../shared/hyperdhtRelay\";\n\nexport { hyperdhtRelayProblem as relayUrlProblem };\n\n/**\n * HyperDHT (WISP 103) for a browser, through a dht-relay: a server that runs the UDP half of HyperDHT and\n * talks to the browser over one WebSocket. It runs non-custodial: the browser keeps its keys, runs the\n * Noise handshake and the encrypted stream itself, and the relay moves handshake messages and ciphertext.\n * The binding (the handshake hash and both keys) is computed here, at the endpoint, as the Desktop does.\n *\n * What the relay sees: this browser's address, the HyperDHT keys it listens on and dials, and when and how\n * much it sends. Not the frames, not the keys' secrets, not the handshake hash.\n *\n * The wire is the Desktop's (native/transports/hyperdht/endpoint.mjs): the same preface, u32 length-prefixed\n * UTF-8 frames of at most 60 KiB, so a browser and a Desktop talk HyperDHT to each other.\n */\n\nconst PREFACE = \"ghostly/paired-chat/1\";\nconst MAX_FRAME = 60 * 1024;\n/** The top bit of a frame's length word: the frame is a binary message, not UTF-8 text (WISP 103). */\nconst BINARY = 0x80000000;\nconst SEND_BUDGET = 120 * 1024;\nconst HANDSHAKE_MS = 20_000;\nconst RELAY_OPEN_MS = 10_000;\nconst LISTEN_MS = 20_000;\nconst MAX_CHANNELS = 2;\n/**\n * Streams dialled in that have not sent the preface yet. They hold none of the MAX_CHANNELS: a new one past this many\n * drops the oldest of them, so streams that stall can never keep the contact's out.\n */\nconst MAX_UNPREFACED = 4;\n/** The places of the streams dialled in: those whose preface came, and those still waiting for it (oldest first). */\ninterface DialledIn { live: Set<RelayedChannel>; unprefaced: Set<RelayedChannel> }\n/**\n * How the relay client is always made: never custodial. dht-relay's default is custodial, which sends every\n * secret key to the relay so it can run the handshake and the stream itself. Nothing here takes this from\n * settings or options; test/hyperdhtRelay.test.ts fails if a secret key ever reaches the relay's wire.\n */\nconst NON_CUSTODIAL = Object.freeze({ custodial: false as const });\n\n/**\n * The descriptor a browser's HyperDHT endpoint gives out: its key, that it is reached only through a relay, and\n * which one (the connection panel names its host; a Desktop dialling it ignores both).\n */\nexport interface RelayedHyperDescriptor { publicKey: string; relayed: true; relay: string }\n\n/** The parts of dht-relay and its streams this adapter uses. */\ninterface SecretSocket {\n handshakeHash: Uint8Array | null;\n publicKey: Uint8Array;\n remotePublicKey: Uint8Array;\n opened?: Promise<boolean>;\n destroyed?: boolean;\n write(data: Uint8Array): boolean;\n destroy(error?: Error): void;\n on(event: string, listener: (...args: never[]) => void): unknown;\n once(event: string, listener: (...args: never[]) => void): unknown;\n off(event: string, listener: (...args: never[]) => void): unknown;\n}\ninterface RelayedServer {\n listen(keyPair: KeyPair): Promise<void>;\n /** Where the relay's node listens for it, as the relay said; port 0 when the relay refused the listen. */\n address(): { port: number } | null;\n close(): Promise<void>;\n once(event: \"close\", listener: () => void): unknown;\n}\ninterface RelayedNode {\n ready(): Promise<void>;\n connect(remotePublicKey: Uint8Array, options: { keyPair: KeyPair }): SecretSocket;\n createServer(options: object, onconnection: (socket: SecretSocket) => void): RelayedServer;\n destroy(): Promise<void>;\n}\ninterface KeyPair { publicKey: Uint8Array; secretKey: Uint8Array }\n\nconst hex = (bytes: Uint8Array) => Array.from(bytes, b => b.toString(16).padStart(2, \"0\")).join(\"\");\nconst fromHex = (text: string) => Uint8Array.from(text.match(/../g)!, byte => parseInt(byte, 16));\n\n/** HyperDHT's key pair for a seed: libsodium's layout (the seed, then the public key). */\nexport function hyperKeyPair(seed: Uint8Array): KeyPair {\n if (seed.length !== 32) throw new Error(\"Invalid HyperDHT seed\");\n const publicKey = ed25519.getPublicKey(seed);\n const secretKey = new Uint8Array(64);\n secretKey.set(seed); secretKey.set(publicKey, 32);\n return { publicKey, secretKey };\n}\n\n/**\n * One WebSocket per relay for the whole app, shared by every chat's endpoint (each listens on its own\n * key). It closes when the last endpoint does. When the relay goes away, every endpoint on it says it is\n * unavailable, and the next one to start opens a new connection.\n */\ninterface RelayClient {\n node: RelayedNode;\n endpoints: Set<{ unavailable(): void }>;\n gone: boolean;\n}\nconst clients = new Map<string, Promise<RelayClient>>();\n\nasync function relayClient(url: string, createSocket: (url: string) => WebSocket): Promise<RelayClient> {\n const existing = clients.get(url);\n if (existing) {\n const client = await existing.catch(() => null);\n if (client && !client.gone) return client;\n if (clients.get(url) === existing) clients.delete(url);\n }\n const opening = (async () => {\n const [{ default: RelayedDHT }, { default: WebSocketStream }] = await Promise.all([\n // @ts-expect-error dht-relay ships no types: RelayedNode and SecretSocket above describe what this uses.\n import(\"@hyperswarm/dht-relay\"),\n // @ts-expect-error The same package's WebSocket stream, untyped too.\n import(\"@hyperswarm/dht-relay/ws\"),\n ]);\n const socket = createSocket(url);\n socket.binaryType = \"arraybuffer\";\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => { socket.close(); reject(new Error(\"The HyperDHT relay did not answer\")); }, RELAY_OPEN_MS);\n socket.addEventListener(\"open\", () => { clearTimeout(timer); resolve(); }, { once: true });\n socket.addEventListener(\"error\", () => { clearTimeout(timer); reject(new Error(\"Could not reach the HyperDHT relay\")); }, { once: true });\n socket.addEventListener(\"close\", () => { clearTimeout(timer); reject(new Error(\"The HyperDHT relay closed the connection\")); }, { once: true });\n });\n // Non-custodial: the relay is told public keys only, never a secret key (dht-relay's default sends them).\n // The node's own key is never used to listen or dial: a random one says nothing about this app.\n const node = new RelayedDHT(new WebSocketStream(true, socket), { ...NON_CUSTODIAL, keyPair: hyperKeyPair(crypto.getRandomValues(new Uint8Array(32))) }) as RelayedNode;\n const client: RelayClient = { node, endpoints: new Set(), gone: false };\n socket.addEventListener(\"close\", () => {\n client.gone = true;\n if (clients.get(url) === opening) clients.delete(url);\n for (const endpoint of [...client.endpoints]) endpoint.unavailable();\n });\n return client;\n })();\n clients.set(url, opening);\n opening.catch(() => { if (clients.get(url) === opening) clients.delete(url); });\n return opening;\n}\n\n/**\n * dht-relay 0.4.3's server waits for the relay connection to close (to close itself) and never stops waiting once it has\n * closed, so every listener ever opened on the connection, closed or refused, stayed in memory with its chat's endpoint\n * until the connection went. The relay forgets its own side the same way (infra/services/hyperdht-relay `Servers`).\n */\nfunction forgetServer(server: RelayedServer): void {\n const internal = server as unknown as { _protocol?: { _stream?: { off(event: string, listener: () => void): unknown } }; _onStreamClose?: () => void };\n if (internal._onStreamClose) internal._protocol?._stream?.off(\"close\", internal._onStreamClose);\n}\n\nfunction release(url: string, client: RelayClient, endpoint: { unavailable(): void }): void {\n client.endpoints.delete(endpoint);\n if (client.endpoints.size || client.gone) return;\n client.gone = true;\n void clients.get(url)?.then(current => { if (current === client) clients.delete(url); }).catch(() => {});\n void client.node.destroy().catch(() => {});\n}\n\n/** One authenticated stream as a frame channel, with a bounded queue before the session installs its reader. */\nclass RelayedChannel implements FrameChannel {\n private reader: FrameChannel[\"onMessage\"] = null;\n private buffered: (string | Uint8Array)[] = [];\n private closed = false;\n private pendingBytes = 0;\n /** It carries binary messages (WISP 100 § Text and binary messages), as the Desktop's own HyperDHT does. */\n readonly binary = true;\n onClose: FrameChannel[\"onClose\"] = null;\n constructor(private readonly socket: SecretSocket) {\n socket.on(\"drain\", () => { this.pendingBytes = 0; });\n }\n get bufferedAmount(): number { return this.pendingBytes; }\n readonly sendBudget = SEND_BUDGET;\n get onMessage() { return this.reader; }\n set onMessage(reader: FrameChannel[\"onMessage\"]) {\n this.reader = reader;\n if (reader) for (const text of this.buffered.splice(0)) reader(text);\n }\n receive(text: string | Uint8Array): boolean {\n if (this.closed) return true;\n if (this.reader) this.reader(text);\n else if (this.buffered.length < 64) this.buffered.push(text);\n else return false;\n return true;\n }\n send(data: string | Uint8Array): void {\n if (this.closed || !data.length) throw new Error(\"Native channel is closed or exceeds its frame budget\");\n const binary = typeof data !== \"string\";\n const payload = binary ? data : new TextEncoder().encode(data);\n if (payload.length > MAX_FRAME || this.pendingBytes + payload.length > SEND_BUDGET) throw new Error(\"Native channel is closed or exceeds its frame budget\");\n // The stream takes every write; past its high-water mark it says so until it drains.\n if (!writeFrame(this.socket, payload, binary) || this.pendingBytes) this.pendingBytes += payload.length + 4;\n }\n drained(): Promise<void> {\n if (!this.pendingBytes) return Promise.resolve();\n return new Promise((resolve, reject) => {\n const done = () => { this.socket.off(\"close\", gone); resolve(); };\n const gone = () => { this.socket.off(\"drain\", done); reject(new Error(\"Native channel closed\")); };\n this.socket.once(\"drain\", done); this.socket.once(\"close\", gone);\n });\n }\n closedByPeer(): void {\n if (this.closed) return;\n this.closed = true; this.buffered = [];\n this.onClose?.();\n }\n close(): void {\n if (this.closed) return;\n this.socket.destroy();\n this.closedByPeer();\n }\n}\n\nfunction writeFrame(socket: SecretSocket, payload: Uint8Array, binary = false): boolean {\n const frame = new Uint8Array(4 + payload.length);\n new DataView(frame.buffer).setUint32(0, (binary ? BINARY : 0) + payload.length);\n frame.set(payload, 4);\n return socket.write(frame);\n}\n\n/**\n * Waits for the peer's preface on an authenticated stream (sending ours as soon as the handshake is\n * done), then hands the channel over with the binding the stream itself gives. A frame of the wrong size,\n * bytes that are not UTF-8 or another protocol close the stream.\n *\n * `dialledIn`: the stream was dialled in, and takes one of its MAX_CHANNELS only once its preface came. This side's own\n * dials are not counted: one always goes out.\n */\nfunction attach(socket: SecretSocket, channels: Set<RelayedChannel>, dialledIn?: DialledIn): Promise<BoundChannel> {\n if (dialledIn && dialledIn.live.size >= MAX_CHANNELS) { socket.destroy(); return Promise.reject(new Error(\"Native connection limit reached\")); }\n if (dialledIn && dialledIn.unprefaced.size >= MAX_UNPREFACED) {\n const [oldest] = dialledIn.unprefaced;\n dialledIn.unprefaced.delete(oldest); oldest.close();\n }\n const channel = new RelayedChannel(socket);\n channels.add(channel); dialledIn?.unprefaced.add(channel);\n return new Promise<BoundChannel>((resolve, reject) => {\n let buffer = new Uint8Array(0);\n let prefaced = false;\n const decoder = new TextDecoder(\"utf-8\", { fatal: true });\n const timer = setTimeout(() => socket.destroy(new Error(\"HyperDHT handshake timed out\")), HANDSHAKE_MS);\n const fail = (error: Error) => { socket.destroy(error); };\n socket.on(\"error\", (error: Error) => reject(error));\n socket.on(\"close\", () => {\n clearTimeout(timer); channels.delete(channel); dialledIn?.live.delete(channel); dialledIn?.unprefaced.delete(channel);\n reject(new Error(\"Native channel closed\"));\n channel.closedByPeer();\n });\n const opened = () => {\n if (socket.handshakeHash?.length !== 64 || socket.publicKey?.length !== 32 || socket.remotePublicKey?.length !== 32) {\n fail(new Error(\"Noise session binding unavailable\")); return;\n }\n writeFrame(socket, new TextEncoder().encode(PREFACE));\n };\n if (socket.opened) void socket.opened.then(ok => { if (ok) opened(); else reject(new Error(\"Noise handshake failed\")); });\n else socket.once(\"open\", opened);\n socket.on(\"data\", (chunk: Uint8Array) => {\n // Frames are read by offset and only the partial one left is kept (a copy, once per chunk), as on the\n // Desktop: copying the rest of the buffer per frame made a burst of tiny frames cost quadratic time.\n let joined = chunk;\n if (buffer.length) {\n joined = new Uint8Array(buffer.length + chunk.length);\n joined.set(buffer); joined.set(chunk, buffer.length);\n }\n let offset = 0;\n while (joined.length - offset >= 4) {\n const word = new DataView(joined.buffer, joined.byteOffset + offset, 4).getUint32(0);\n const binary = word >= BINARY, length = word % BINARY;\n // A binary frame before the preface is another protocol.\n if (length === 0 || length > MAX_FRAME || (binary && !prefaced)) { fail(new Error(\"Invalid frame length\")); return; }\n if (joined.length - offset < 4 + length) break;\n const payload = joined.subarray(offset + 4, offset + 4 + length);\n offset += 4 + length;\n if (binary) {\n if (!channel.receive(new Uint8Array(payload))) { fail(new Error(\"Receive queue exceeded\")); return; }\n continue;\n }\n let text: string;\n try { text = decoder.decode(payload); }\n catch { fail(new Error(\"Invalid UTF-8 frame\")); return; }\n if (!prefaced) {\n if (text !== PREFACE) { fail(new Error(\"Unexpected application protocol\")); return; }\n prefaced = true; clearTimeout(timer);\n if (dialledIn) {\n dialledIn.unprefaced.delete(channel);\n if (dialledIn.live.size >= MAX_CHANNELS) { fail(new Error(\"Native connection limit reached\")); return; }\n dialledIn.live.add(channel);\n }\n resolve({ channel, binding: { transport: \"hyperdht/1\", context: hex(socket.handshakeHash!),\n identities: [hex(socket.publicKey), hex(socket.remotePublicKey)].sort() as [string, string] } });\n } else if (!channel.receive(text)) { fail(new Error(\"Receive queue exceeded\")); return; }\n }\n buffer = new Uint8Array(joined.subarray(offset));\n });\n });\n}\n\nexport interface RelayedHyperOptions {\n /** How to open the WebSocket (tests pass Node's `ws`). Default: the browser's. */\n createSocket?: (url: string) => WebSocket;\n}\n\n/**\n * A chat's HyperDHT endpoint through the relay at `url`: it listens on the key of `seedB64` (the chat's\n * own transport seed, as on the Desktop) and dials a contact's descriptor. Fails, and so is not offered,\n * when the relay cannot be reached or does not let it listen.\n *\n * dht-relay 0.4.3 has no message for a refused listen (the relay's node refuses a key it already listens on, for\n * another client or an old connection of this one), and its client drops a `closed` for a server that has not had\n * `listening`. So the relay answers a refusal with `listening` at no address (port 0), then `closed`: that fails here\n * at once. A relay that answers nothing leaves the listen to LISTEN_MS. A server the relay closes later says the\n * endpoint is unavailable, as when the whole connection goes.\n */\nexport async function createRelayedHyperEndpoint(seedB64: string, url: string, options: RelayedHyperOptions = {}): Promise<NativeEndpoint> {\n const problem = hyperdhtRelayProblem(url);\n if (problem) throw new Error(problem);\n const keyPair = hyperKeyPair(fromBase64Url(seedB64));\n const client = await relayClient(url, options.createSocket ?? (address => new WebSocket(address)));\n const channels = new Set<RelayedChannel>();\n const dialledIn: DialledIn = { live: new Set(), unprefaced: new Set() };\n let stopped = false;\n let handler: NativeEndpoint[\"onConnection\"] = null;\n const waiting: BoundChannel[] = [];\n let endpoint: NativeEndpoint | null = null;\n // Fails the listen below when the relay connection closes while it waits.\n let relayClosed: (() => void) | null = null;\n const member = {\n unavailable() {\n if (client.gone) relayClosed?.();\n if (stopped) return;\n stopped = true;\n for (const channel of channels) channel.close();\n endpoint?.onUnavailable?.();\n },\n };\n client.endpoints.add(member);\n const server = client.node.createServer({}, socket => {\n void attach(socket, channels, dialledIn).then(bound => {\n if (stopped) bound.channel.close();\n else if (handler) handler(bound);\n else if (waiting.length < MAX_CHANNELS) waiting.push(bound);\n else bound.channel.close();\n }).catch(() => {});\n });\n let serverClosed = false;\n server.once(\"close\", () => { serverClosed = true; forgetServer(server); member.unavailable(); });\n // Neither wait outlasts the listen: one on `client.closed` stayed there, holding this endpoint, closed or refused, for as\n // long as the relay connection stayed open.\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n server.listen(keyPair),\n new Promise((_, reject) => {\n relayClosed = () => reject(new Error(\"The HyperDHT relay closed the connection\"));\n if (client.gone) relayClosed();\n timer = setTimeout(() => reject(new Error(\"The HyperDHT relay did not let this chat listen\")), LISTEN_MS);\n }),\n ]);\n if (client.gone) throw new Error(\"The HyperDHT relay closed the connection\");\n if (serverClosed || !server.address()?.port) throw new Error(\"The HyperDHT relay did not let this chat listen\");\n } catch (error) {\n stopped = true;\n void server.close().catch(() => {});\n release(url, client, member);\n throw error;\n } finally {\n clearTimeout(timer);\n relayClosed = null;\n }\n const descriptor: RelayedHyperDescriptor = { publicKey: hex(keyPair.publicKey), relayed: true, relay: hyperdhtRelayUrl(url) };\n endpoint = {\n transport: \"hyperdht/1\", descriptor, onDescriptor: null, onUnavailable: null,\n get onConnection() { return handler; },\n set onConnection(value) { handler = value; if (value) for (const bound of waiting.splice(0)) value(bound); },\n async connect(address) {\n const publicKey = (address as { publicKey?: unknown } | null)?.publicKey;\n if (stopped || typeof publicKey !== \"string\" || !/^[a-f0-9]{64}$/.test(publicKey)) throw new Error(\"Invalid HyperDHT endpoint\");\n return attach(client.node.connect(fromHex(publicKey), { keyPair }), channels);\n },\n async close() {\n stopped = true;\n for (const channel of channels) channel.close();\n waiting.length = 0;\n await server.close().catch(() => {});\n release(url, client, member);\n },\n };\n return endpoint;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAmBA,IAAM,UAAU;AAChB,IAAM,YAAY;;AAElB,IAAM,SAAS;AACf,IAAM,cAAc;AACpB,IAAM,eAAe;AACrB,IAAM,gBAAgB;AACtB,IAAM,YAAY;AAClB,IAAM,eAAe;;;;;AAKrB,IAAM,iBAAiB;;;;;;AAQvB,IAAM,gBAAgB,OAAO,OAAO,EAAE,WAAW,MAAe,CAAC;AAoCjE,IAAM,OAAO,UAAsB,MAAM,KAAK,QAAO,MAAK,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;AAClG,IAAM,WAAW,SAAiB,WAAW,KAAK,KAAK,MAAM,KAAK,IAAI,SAAQ,SAAS,MAAM,EAAE,CAAC;;AAGhG,SAAgB,aAAa,MAA2B;CACtD,IAAI,KAAK,WAAW,IAAI,MAAM,IAAI,MAAM,uBAAuB;CAC/D,MAAM,YAAY,QAAQ,aAAa,IAAI;CAC3C,MAAM,4BAAY,IAAI,WAAW,EAAE;CACnC,UAAU,IAAI,IAAI;CAAG,UAAU,IAAI,WAAW,EAAE;CAChD,OAAO;EAAE;EAAW;CAAU;AAChC;AAYA,IAAM,0BAAU,IAAI,IAAkC;AAEtD,eAAe,YAAY,KAAa,cAAgE;CACtG,MAAM,WAAW,QAAQ,IAAI,GAAG;CAChC,IAAI,UAAU;EACZ,MAAM,SAAS,MAAM,SAAS,YAAY,IAAI;EAC9C,IAAI,U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Q,CAAC,GAAG,QAAQ;EAC9E;EACA,MAAM,QAAQ;GACZ,UAAU;GACV,KAAK,MAAM,WAAW,UAAU,QAAQ,MAAM;GAC9C,QAAQ,SAAS;GACjB,MAAM,OAAO,MAAM,CAAC,CAAC,YAAY,CAAC,CAAC;GACnC,QAAQ,KAAK,QAAQ,MAAM;EAC7B;CACF;CACA,OAAO;AACT"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { d as relayUrlTooLong, u as relayUrl } from "./pairedTransports-BKmvlKz1.js";
|
|
2
|
+
// ../browser/src/shared/hyperdhtRelay.ts
|
|
3
|
+
/**
|
|
4
|
+
* Only `wss://`, or `ws://` to this machine (a relay for tests or development). Nothing but the server's address, as
|
|
5
|
+
* an Iroh relay (irohWeb.ts `irohRelayProblem`): the endpoint names this URL as its descriptor's relay, which every
|
|
6
|
+
* contact is told, so a login, a password, a query or a fragment in it would go to them all.
|
|
7
|
+
*/
|
|
8
|
+
function hyperdhtRelayProblem(url) {
|
|
9
|
+
let parsed;
|
|
10
|
+
try {
|
|
11
|
+
parsed = new URL(url);
|
|
12
|
+
} catch {
|
|
13
|
+
return "Enter a relay address (wss://…)";
|
|
14
|
+
}
|
|
15
|
+
if (parsed.protocol !== "wss:" && !(parsed.protocol === "ws:" && [
|
|
16
|
+
"127.0.0.1",
|
|
17
|
+
"localhost",
|
|
18
|
+
"[::1]"
|
|
19
|
+
].includes(parsed.hostname))) return "Use a wss:// relay address";
|
|
20
|
+
if (parsed.username || parsed.password || /[?#]/.test(url)) return `Not a relay address: ${url}`;
|
|
21
|
+
const named = hyperdhtRelayUrl(url);
|
|
22
|
+
if (url.length > 256 || !relayUrl(named)) return relayUrlTooLong(named) ? `Use a shorter relay address: ${url}` : `Not a relay address: ${url}`;
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The relay as the endpoint names it to contacts: its scheme in lower case, as `relayUrl` reads it (`WSS://relay.example`
|
|
27
|
+
* pasted is wss://relay.example), the rest as typed.
|
|
28
|
+
*/
|
|
29
|
+
var hyperdhtRelayUrl = (url) => url.replace(/^[a-z]+:/i, (scheme) => scheme.toLowerCase());
|
|
30
|
+
export { hyperdhtRelayUrl as n, hyperdhtRelayProblem as t };
|
|
31
|
+
|
|
32
|
+
//# sourceMappingURL=hyperdhtRelay-bjNGacf5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hyperdhtRelay-bjNGacf5.js","names":[],"sources":["../../../browser/src/shared/hyperdhtRelay.ts"],"sourcesContent":["import { relayUrl, relayUrlTooLong } from \"@ghostly/core\";\n\n/**\n * The HyperDHT relay a browser reaches the HyperDHT through (WISP 103, browser profile). Empty: none, so a\n * browser offers no HyperDHT. Nobody runs a public one for Ghostly yet; this becomes Ghostly's own relay\n * once it is deployed.\n */\nexport const DEFAULT_HYPERDHT_RELAY = \"\";\n\n/**\n * Only `wss://`, or `ws://` to this machine (a relay for tests or development). Nothing but the server's address, as\n * an Iroh relay (irohWeb.ts `irohRelayProblem`): the endpoint names this URL as its descriptor's relay, which every\n * contact is told, so a login, a password, a query or a fragment in it would go to them all.\n */\nexport function hyperdhtRelayProblem(url: string): string | null {\n let parsed: URL;\n try { parsed = new URL(url); } catch { return \"Enter a relay address (wss://…)\"; }\n if (parsed.protocol !== \"wss:\" && !(parsed.protocol === \"ws:\" && [\"127.0.0.1\", \"localhost\", \"[::1]\"].includes(parsed.hostname))) return \"Use a wss:// relay address\";\n if (parsed.username || parsed.password || /[?#]/.test(url)) return `Not a relay address: ${url}`;\n // Nor one a contact would drop with the whole descriptor (`relayUrl`: a space in it, past 126 characters, a capital in\n // `localhost`), leaving the relay unused for reaching this browser without a word. One refused for its length alone\n // is a relay address all the same: what to do is said instead.\n const named = hyperdhtRelayUrl(url);\n if (url.length > 256 || !relayUrl(named)) return relayUrlTooLong(named) ? `Use a shorter relay address: ${url}` : `Not a relay address: ${url}`;\n return null;\n}\n\n/**\n * The relay as the endpoint names it to contacts: its scheme in lower case, as `relayUrl` reads it (`WSS://relay.example`\n * pasted is wss://relay.example), the rest as typed.\n */\nexport const hyperdhtRelayUrl = (url: string): string => url.replace(/^[a-z]+:/i, scheme => scheme.toLowerCase());\n"],"mappings":";;;;;;;AAcA,SAAgB,qBAAqB,KAA4B;CAC/D,IAAI;CACJ,IAAI;EAAE,SAAS,IAAI,IAAI,GAAG;CAAG,QAAQ;EAAE,OAAO;CAAmC;CACjF,IAAI,OAAO,aAAa,UAAU,EAAE,OAAO,aAAa,SAAS;EAAC;EAAa;EAAa;CAAO,CAAC,CAAC,SAAS,OAAO,QAAQ,IAAI,OAAO;CACxI,IAAI,OAAO,YAAY,OAAO,YAAY,OAAO,KAAK,GAAG,GAAG,OAAO,wBAAwB;CAI3F,MAAM,QAAQ,iBAAiB,GAAG;CAClC,IAAI,IAAI,SAAS,OAAO,CAAC,SAAS,KAAK,GAAG,OAAO,gBAAgB,KAAK,IAAI,gCAAgC,QAAQ,wBAAwB;CAC1I,OAAO;AACT;;;;;AAMA,IAAa,oBAAoB,QAAwB,IAAI,QAAQ,cAAa,WAAU,OAAO,YAAY,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// ../browser/src/shared/idb.ts
|
|
2
2
|
/**
|
|
3
3
|
* The extension's one IndexedDB database. The peer (offscreen document) and
|
|
4
4
|
* the pages share an origin, so both open it: that is also how file contents
|
|
@@ -556,7 +556,6 @@ var fileStore = {
|
|
|
556
556
|
await Promise.all(keys.flatMap((key) => [committed(files.delete(key)), committed(state.delete(key))]));
|
|
557
557
|
}
|
|
558
558
|
};
|
|
559
|
-
//#endregion
|
|
560
559
|
export { openDb as _, GROUP_LIGHT_RANGE as a, transact as b, clearProfileStores as c, deleteDatabase as d, errorLine as f, newestWalletTx as g, groupLiveKey as h, FILE_INDEX as i, committed as l, groupLightKey as m, APP_STORAGE_SCOPE_INDEX as n, GROUP_LIVE_RANGE as o, fileStore as p, CARD_INDEX as r, STORES as s, APP_STORAGE_CHAT_INDEX as t, databaseName as u, profileOpenFailure as v, wrap as x, store as y };
|
|
561
560
|
|
|
562
|
-
//# sourceMappingURL=idb-
|
|
561
|
+
//# sourceMappingURL=idb-ewvbqyDI.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"idb-CEuoNsTv.js","names":[],"sources":["../../../browser/src/shared/idb.ts"],"sourcesContent":["/**\n * The extension's one IndexedDB database. The peer (offscreen document) and\n * the pages share an origin, so both open it: that is also how file contents\n * move between them without squeezing through runtime messages.\n */\nlet dbName = \"ghostly\";\n\n/** Before first use: keeps profiles that share a browser storage area apart (Desktop's GHOSTLY_PROFILE). */\nexport function setDatabaseName(name: string): void {\n dbName = name;\n}\n/** The peer database this page uses: its profile's (WISP 04). */\nexport function databaseName(): string {\n return dbName;\n}\n/** The schema this build reads and writes. A database stored at a higher one is a newer build's: it is never opened. */\nexport const DB_VERSION = 16;\n\n/**\n * Why the profile's database did not open. `newer`: a newer Ghostly stored it (IndexedDB never opens a database below\n * its stored version). `blocked`: another window still holds it open at an older version. `full`: no storage space.\n * `denied`: the browser gives this page no storage (a private window, storage blocked for the site). `failed`:\n * anything else, a damaged database included (browsers do not tell that one apart).\n */\nexport type ProfileOpenReason = \"newer\" | \"blocked\" | \"full\" | \"denied\" | \"failed\";\n\n/** What the pages are told (a plain object: it crosses the extension's port), and what a bot reads in `details`. */\nexport interface ProfileOpenFailure {\n reason: ProfileOpenReason;\n /** The schema version this build reads (`DB_VERSION`). */\n supportedVersion: number;\n /** The version the database is stored at, when it could be read (`newer`). */\n storedVersion?: number;\n /** What the browser said, in its own words. */\n detail?: string;\n}\n\n/** The profile's database did not open. Nothing was changed, and nothing is ever deleted or reset because of it. */\nexport class ProfileOpenError extends Error {\n constructor(readonly failure: ProfileOpenFailure) {\n super(profileOpenMessage(failure));\n this.name = \"ProfileOpenError\";\n }\n}\n\n/** The failure in plain English, for logs, the CLI and anything that shows an engine error as it came. */\nexport function profileOpenMessage(failure: ProfileOpenFailure): string {\n const could = \"Ghostly could not open this profile's data\";\n switch (failure.reason) {\n case \"newer\":\n return `This profile was last used by a newer version of Ghostly (its data is version ${failure.storedVersion ?? \"above \" + failure.supportedVersion}, this version reads up to ${failure.supportedVersion}). Update Ghostly to open it.`;\n case \"blocked\": return `${could}: another Ghostly window or tab still has it open with an older version. Close it and try again.`;\n case \"full\": return `${could}: this device is out of storage space. Free some space and try again.`;\n case \"denied\": return `${could}: storage is not allowed here (a private window, or storage blocked for this site).`;\n default: return `${could}${failure.detail ? `: ${failure.detail}` : \"\"}`;\n }\n}\n\n/** What the start of the engine failed with, as the failure the pages show: a database that did not open, or anything else. */\nexport function profileOpenFailure(error: unknown): ProfileOpenFailure {\n if (error instanceof ProfileOpenError) return error.failure;\n // The database opened but a first write found no room (Chromium aborts the transaction with an empty message).\n const quota = quotaError(error);\n if (quota) return failureOf(quota);\n const detail = error instanceof Error ? error.message : String(error);\n return { reason: \"failed\", supportedVersion: DB_VERSION, ...(detail ? { detail } : {}) };\n}\n\n/**\n * A failed call as the client hears it (engine/server.ts): the error's message. Only the message travels, so a storage\n * write the browser refused for want of space (Chromium's QuotaExceededError has an empty message) says so, its name\n * kept for the ⓘ.\n */\nexport function errorLine(error: unknown): string {\n if ((error as { name?: unknown } | null)?.name === \"QuotaExceededError\") {\n const message = error instanceof Error ? error.message.trim() : \"\";\n return `Not enough space on this device (QuotaExceededError${message ? `: ${message}` : \"\"})`;\n }\n return error instanceof Error ? error.message : String(error);\n}\n\n/** The no-room error's names: the standard one and Firefox's (its legacy code, 22, is read as well). */\nconst QUOTA_NAMES: ReadonlySet<unknown> = new Set([\"QuotaExceededError\", \"NS_ERROR_DOM_QUOTA_REACHED\"]);\n\n/**\n * The no-room error behind `error`, as thrown or wrapped: a transaction's abort (`error`, an event's `target.error`)\n * or an Error's `cause`. Undefined when it is not one.\n */\nfunction quotaError(error: unknown, depth = 0): { name?: unknown; message?: unknown } | undefined {\n if (!error || typeof error !== \"object\" || depth > 3) return undefined;\n const e = error as { name?: unknown; code?: unknown; error?: unknown; target?: { error?: unknown } | null; cause?: unknown };\n if (QUOTA_NAMES.has(e.name) || (typeof DOMException !== \"undefined\" && error instanceof DOMException && e.code === 22)) return e;\n return quotaError(e.error, depth + 1) ?? quotaError(e.target?.error, depth + 1) ?? quotaError(e.cause, depth + 1);\n}\n\n/**\n * `blockedMs`: how long an open that another window blocks may wait for that window to let go before it is said to be\n * blocked. `silentMs`: how long an open may go without any answer from the browser (no success, error, blocked or\n * upgrade) before it is said to have failed. An upgrade that started has its answer and may take as long as it needs.\n */\nexport const OPEN_TIMINGS = { blockedMs: 10_000, silentMs: 30_000 };\n\nfunction failureOf(error: unknown): ProfileOpenFailure {\n const name = (error as { name?: unknown } | null)?.name;\n const message = (error as { message?: unknown } | null)?.message;\n const detail = [typeof name === \"string\" ? name : \"\", typeof message === \"string\" ? message : \"\"].filter(Boolean).join(\": \");\n const reason: ProfileOpenReason = name === \"VersionError\" ? \"newer\"\n : quotaError(error) ? \"full\"\n // Firefox's private windows of old, storage blocked for the site, or no IndexedDB at all.\n : name === \"BlockedError\" ? \"blocked\"\n : name === \"SecurityError\" || name === \"InvalidStateError\" || name === \"ReferenceError\" || name === \"TypeError\" ? \"denied\"\n : \"failed\";\n return { reason, supportedVersion: DB_VERSION, ...(detail ? { detail } : {}) };\n}\n\n/**\n * The version a database is stored at, read without changing it: an open that names no version opens what is there.\n * Only for a database known to exist (an open without a version would make a missing one).\n */\nfunction storedVersion(name: string): Promise<number | undefined> {\n return new Promise((resolve) => {\n try {\n const request = indexedDB.open(name);\n // It did not exist after all: leave nothing behind.\n request.onupgradeneeded = () => { try { request.transaction?.abort(); } catch { /* already over */ } };\n request.onsuccess = () => { const { version } = request.result; request.result.close(); resolve(version); };\n request.onerror = request.onblocked = () => resolve(undefined);\n } catch { resolve(undefined); }\n });\n}\n/** The messages store's index of card messages (`card.kind`): what `db.getCardMessages` reads. */\nexport const CARD_INDEX = \"byCardKind\";\n/** The messages store's index of the messages that carry a file, by chat (`linkId`, `file.id`): what `db.getFileMessages` reads. */\nexport const FILE_INDEX = \"byLinkFile\";\n/** The wallet history's index by (mint, time): what `newestWalletTx` reads. */\nexport const WALLET_TX_INDEX = \"byMintTime\";\n\nexport const STORES = {\n links: \"links\",\n messages: \"messages\",\n services: \"services\",\n settings: \"settings\",\n files: \"files\",\n proofs: \"proofs\",\n payments: \"payments\",\n quotes: \"quotes\",\n walletTx: \"walletTx\",\n melts: \"melts\",\n /** Swaps at a mint that have not finished (`PendingSwap`): what gets their outputs back when an answer is missed. */\n swaps: \"swaps\",\n intents: \"paymentIntents\",\n /** Private groups (WISP 900): membership chain, epoch secrets and my own recent messages, by group id. */\n groups: \"groups\",\n /** Files kept in 1 MiB pieces where the platform has no file system for them (see `fileBytesIdb.ts`). */\n fileChunks: \"fileChunks\",\n /**\n * What changes about a stored file after it is stored, by file id. A `files` record is written once and never\n * again: WebKit loses the Blob of a record written back with the Blob it read (see `fileStore`).\n */\n fileState: \"fileState\",\n /** Installed mini-apps (WISP 1200 § Updates and rollback), by app reference: `InstalledApp` (`engine/apps.ts`). */\n apps: \"apps\",\n /** The app stores the person added, by store key: `AddedAppStore`. A store is its key; its URL is kept on the record. */\n appStores: \"appStores\",\n /** Each installed app's own storage, by (app reference, scope, key): `AppStorageRow`. Scope: a chat's link id, or `alone`. */\n appStorage: \"appStorage\",\n} as const;\n\n/** The app storage store's index by (app reference, scope): one scope's rows, for its 5 MiB cap and its keys. */\nexport const APP_STORAGE_SCOPE_INDEX = \"byAppScope\";\n/** The app storage store's index by scope: every app's rows of one chat, which go with the chat. */\nexport const APP_STORAGE_CHAT_INDEX = \"byScope\";\n\n/**\n * A file's contents. Metadata travels with the chat message; this is only the bytes: in `blob` for a file\n * small enough to hold whole, or in the platform's file storage (`bytes`, see `fileBytes.ts`) under the same id.\n * Ids are `<link id>-out-<random>` for files we send and `<link id>-in-<random>` for\n * files we receive, both chosen here. Files stored before that are `<link id>-<wire id>`\n * without `direction` and are still read under their old id.\n */\nexport interface StoredFile {\n id: string;\n linkId: string;\n blob?: Blob;\n /** Where the bytes are when there is no `blob`. */\n bytes?: import(\"./fileBytes\").FileBytesKind;\n createdAt: number;\n direction?: \"in\" | \"out\";\n /** The id the file had on the data link. */\n wireId?: string;\n digest?: string;\n metadata?: { name: string; size: number; mime: string; timestamp: number; voice?: import(\"@ghostly/core\").VoiceMeta; video?: import(\"@ghostly/core\").VideoMeta; image?: import(\"@ghostly/core\").ImageMeta };\n transfer?: { state: \"transferring\" | \"done\" | \"failed\"; transferred: number; size: number; error?: string };\n /** files/3: the transfer's own record (`@ghostly/core` `FileTransferRecord`), kept so it resumes after a restart. */\n wire3?: import(\"@ghostly/core\").FileTransferRecord;\n /** Its bytes were left out of the light backup this profile was restored from (WISP 05 § Light backups). */\n leftOut?: boolean;\n /**\n * A file the contact said on the DHT floor (WISP 403 § Files), by its wire id: its bubble waits for its offer on the\n * live session, and no byte is here yet. Gone once the offer came (`wireId` and `wire3` then).\n */\n announced?: string;\n /**\n * A file of a group (WISP 503), its `linkId` `group:<id>`: the message that announced it and its author, whether this\n * device fetched it without asking (it counts toward the group's automatic limit), and whether its person asked for it.\n * `digest` is the author's, which the bytes are checked against.\n */\n /**\n * A group's file (WISP 503): its message, author and, when its announcement reached this device said again under a\n * later epoch than the message's own, that epoch (`arrived`). A `ts` on records from before is not read.\n */\n group?: { message: string; author: string; arrived?: number; auto?: boolean; asked?: boolean; paused?: boolean };\n}\n\n/** The fields of a stored file that change after it is stored: kept in `STORES.fileState`, read over the record's own. */\ntype FileStateFields = Partial<Pick<StoredFile, \"bytes\" | \"digest\" | \"transfer\" | \"wire3\" | \"group\" | \"leftOut\">>;\ntype FileState = { id: string } & FileStateFields;\n\nlet dbPromise: Promise<IDBDatabase> | null = null;\n\nexport function openDb(): Promise<IDBDatabase> {\n dbPromise ??= new Promise((resolve, reject) => {\n let settled = false;\n let blocked: ReturnType<typeof setTimeout> | undefined;\n // A browser fault (WebKit had one on a first page load): an open that never answers, which left the app looking\n // alive with an engine that never started. Without an answer in time it is said as a failure, and Try again reloads.\n const silent = setTimeout(() => fail({ name: \"TimeoutError\", message: `the browser did not answer in ${Math.round(OPEN_TIMINGS.silentMs / 1000)} s` }), OPEN_TIMINGS.silentMs);\n // Said once, as what it is (`ProfileOpenError`): the engine does not start, and the pages show why.\n const fail = (error: unknown) => {\n if (settled) return;\n settled = true;\n clearTimeout(blocked);\n clearTimeout(silent);\n const failure = failureOf(error);\n if (failure.reason !== \"newer\") { reject(new ProfileOpenError(failure)); return; }\n void storedVersion(dbName).then((version) => reject(new ProfileOpenError({ ...failure, ...(version !== undefined ? { storedVersion: version } : {}) })));\n };\n let request: IDBOpenDBRequest;\n try {\n request = indexedDB.open(dbName, DB_VERSION);\n } catch (error) {\n fail(error);\n return;\n }\n request.onupgradeneeded = () => {\n clearTimeout(silent);\n const db = request.result;\n const has = (name: string) => db.objectStoreNames.contains(name);\n if (!has(STORES.links)) db.createObjectStore(STORES.links, { keyPath: \"id\" });\n if (!has(STORES.services)) db.createObjectStore(STORES.services, { keyPath: \"id\" });\n if (!has(STORES.settings)) db.createObjectStore(STORES.settings);\n if (!has(STORES.messages)) {\n db.createObjectStore(STORES.messages, { keyPath: [\"linkId\", \"id\"] }).createIndex(\"byLink\", \"linkId\");\n }\n if (!has(STORES.proofs)) db.createObjectStore(STORES.proofs, { keyPath: \"secret\" });\n if (!has(STORES.payments)) db.createObjectStore(STORES.payments, { keyPath: \"id\" });\n if (!has(STORES.quotes)) db.createObjectStore(STORES.quotes, { keyPath: \"quote\" });\n if (!has(STORES.walletTx)) db.createObjectStore(STORES.walletTx, { keyPath: \"id\" });\n // v5: Lightning payments the mint has not settled yet, and the proofs they hold.\n if (!has(STORES.melts)) db.createObjectStore(STORES.melts, { keyPath: \"quote\" });\n if (!has(STORES.intents)) db.createObjectStore(STORES.intents, { keyPath: \"review.id\" });\n if (!has(STORES.files)) {\n db.createObjectStore(STORES.files, { keyPath: \"id\" }).createIndex(\"byLink\", \"linkId\");\n }\n // v7: private groups.\n if (!has(STORES.groups)) db.createObjectStore(STORES.groups, { keyPath: \"id\" });\n // v8: files in pieces, for platforms without the origin-private file system.\n if (!has(STORES.fileChunks)) db.createObjectStore(STORES.fileChunks, { keyPath: [\"id\", \"index\"] });\n // v9: what changes about a stored file, apart from its record (see `fileStore`).\n if (!has(STORES.fileState)) db.createObjectStore(STORES.fileState, { keyPath: \"id\" });\n // v10: a chat's messages in time order, so its latest page is read without the rest.\n const messages = request.transaction!.objectStore(STORES.messages);\n if (!messages.indexNames.contains(\"byLinkTime\")) messages.createIndex(\"byLinkTime\", [\"linkId\", \"timestamp\"]);\n // v11: the messages that carry a status card, by the card's kind, across every chat and group (the Tasks board).\n // A message without a card has no such key and is not in it, so the index is as small as the cards are few.\n if (!messages.indexNames.contains(CARD_INDEX)) messages.createIndex(CARD_INDEX, \"card.kind\");\n // v12: swaps at a mint, written down before the mint is asked.\n if (!has(STORES.swaps)) db.createObjectStore(STORES.swaps, { keyPath: \"id\" });\n // v13: no change of the schema. A build from here can hold a frozen copy of a profile on a standby device (WISP 06\n // § Compatibility and rollout): the step keeps an older build (1.0.3 reads 12) from opening and starting one.\n // v14: mini-apps (WISP 1200): the installed apps, the stores added and each app's storage per scope. Empty until the\n // apps feature is on; the bundles themselves are in file storage under `app-<digest>`, outside every store here.\n if (!has(STORES.apps)) db.createObjectStore(STORES.apps, { keyPath: \"ref\" });\n if (!has(STORES.appStores)) db.createObjectStore(STORES.appStores, { keyPath: \"key\" });\n if (!has(STORES.appStorage)) {\n const storage = db.createObjectStore(STORES.appStorage, { keyPath: [\"ref\", \"scope\", \"key\"] });\n storage.createIndex(APP_STORAGE_SCOPE_INDEX, [\"ref\", \"scope\"]);\n storage.createIndex(APP_STORAGE_CHAT_INDEX, \"scope\");\n }\n // v15: the wallet history by mint and time, so a refresh reads each network's newest movements without the rest.\n const walletTx = request.transaction!.objectStore(STORES.walletTx);\n if (!walletTx.indexNames.contains(WALLET_TX_INDEX)) walletTx.createIndex(WALLET_TX_INDEX, [\"mint\", \"timestamp\"]);\n // v16: the messages that carry a file, by chat or group, so a chat's files are read without its texts (`file list`).\n // A message without a file has no such key and is not in it.\n if (!messages.indexNames.contains(FILE_INDEX)) messages.createIndex(FILE_INDEX, [\"linkId\", \"file.id\"]);\n };\n request.onsuccess = () => {\n // Opened after it was said to be blocked: nobody uses this connection, and it must not block the next open.\n if (settled) { request.result.close(); return; }\n settled = true;\n clearTimeout(blocked);\n clearTimeout(silent);\n // Let the other context upgrade the schema instead of blocking it.\n request.result.onversionchange = () => {\n request.result.close();\n dbPromise = null;\n };\n resolve(request.result);\n };\n // The event's default aborts nothing here, but an unhandled one is logged as an uncaught error in some browsers.\n request.onerror = (event) => { event.preventDefault?.(); fail(request.error); };\n // Another window holds the database at an older version and has not let go (ours do, on `versionchange`). The\n // open stays pending for as long as that lasts: before, the engine waited with it, silently and for good.\n request.onblocked = () => {\n clearTimeout(silent);\n blocked ??= setTimeout(() => fail({ name: \"BlockedError\", message: \"another connection holds an older version open\" }), OPEN_TIMINGS.blockedMs);\n };\n });\n return dbPromise;\n}\n\n/** The stores \"Clear all data\" empties: chats and their keys, messages, files, shared services, groups, mini-apps and their data. */\nexport const PROFILE_STORES = [STORES.links, STORES.messages, STORES.files, STORES.fileState, STORES.fileChunks, STORES.services, STORES.groups, STORES.apps, STORES.appStores, STORES.appStorage] as const;\n\n/**\n * Records of the settings store that belong to the profile, not to a wallet: its DID and its key, its identity proofs\n * with their keys and revocations and when the contacts' were last looked up for one (and which, of a lookup under way), its own Nostr data, the public profiles it read, the built-in mini-apps it removed\n * (`BUILT_IN_APPS_KEY` of `engine/apps.ts`), the digests of the mini-app bundles it may hold (`APP_BUNDLES_KEY`) and the mini-app revocations it verified (`APP_REVOCATIONS_KEY`), its x401 credentials and their keys (`engine/x401.ts`), its contact links\n * (`engine/contactLinks.ts`), the requests it sent through others' (`engine/contactAsks.ts`) and its saved messages\n * (`engine/saved.ts`). A list of what goes\n * rather than of what stays, on purpose: every other record of that store is a wallet's (seeds, configuration, pending\n * operations), and a wallet record a newer version adds must never be deleted by mistake.\n */\nexport const PROFILE_SETTINGS_KEYS = [\"profileDid\", \"identityProofs\", \"identityRevocations\", \"identityRevocationsCheckedAt\", \"identityRevocationsRound\", \"nostrSocial\", \"publicProfiles\", \"appBuiltIns\", \"appBundles\", \"appRevocations\", \"x401Credentials\", \"contactLinks\", \"contactAsks\", \"savedMessages\"] as const;\n\n/** A private group's small row in the settings store (`GroupLive`, `engine/groupRows.ts`): the profile's too. */\nexport const groupLiveKey = (groupId: string): string => `groupLive:${groupId}`;\nexport const GROUP_LIVE_RANGE = (): IDBKeyRange => IDBKeyRange.bound(groupLiveKey(\"\"), `${groupLiveKey(\"\")}`);\n/** A private group's pin and deletions for everyone, while its record is behind on them (`GroupLight`): the profile's too. */\nexport const groupLightKey = (groupId: string): string => `groupLight:${groupId}`;\nexport const GROUP_LIGHT_RANGE = (): IDBKeyRange => IDBKeyRange.bound(groupLightKey(\"\"), `${groupLightKey(\"\")}`);\n\n/**\n * The fields of the peer's `settings` record that are a wallet's, kept by \"Clear all data\": the mint list, the first-run\n * wallet setup and the backup reminders. Everything else in it is the profile's (name, picture, network settings,\n * storage credentials for held items, the push subscription and who holds it) and goes.\n */\nexport const WALLET_SETTINGS_FIELDS = [\"mints\", \"mintsInitialized\", \"walletSetup\", \"backupReminders\"] as const;\n\n/**\n * \"Clear all data\" (WISP 04): everything of the profile in its peer database except its wallets. The chats' stores are\n * emptied, the profile's records of the settings store are deleted and the `settings` record keeps only its wallet\n * fields. The wallets (proofs, payments, quotes, history, payment journal, wallet records) stay: ecash is money, and\n * nothing else holds a copy of it. The caller stops the peer first, or it may write back what was just deleted.\n */\nexport async function clearProfileStores(): Promise<void> {\n if (typeof indexedDB === \"undefined\") return;\n const db = await openDb();\n const names = [...PROFILE_STORES, STORES.settings].filter((name) => db.objectStoreNames.contains(name));\n const tx = db.transaction(names, \"readwrite\");\n for (const name of names) if (name !== STORES.settings) tx.objectStore(name).clear();\n if (names.includes(STORES.settings)) {\n const settings = tx.objectStore(STORES.settings);\n for (const key of PROFILE_SETTINGS_KEYS) settings.delete(key);\n settings.delete(GROUP_LIVE_RANGE());\n settings.delete(GROUP_LIGHT_RANGE());\n const read = settings.get(\"settings\");\n read.onsuccess = () => {\n const record = read.result as Record<string, unknown> | undefined;\n if (!record || typeof record !== \"object\") return;\n const kept = Object.fromEntries(WALLET_SETTINGS_FIELDS.filter((field) => field in record).map((field) => [field, record[field]]));\n settings.put(kept, \"settings\");\n };\n }\n await new Promise<void>((resolve, reject) => {\n tx.oncomplete = () => resolve();\n tx.onerror = tx.onabort = () => reject(tx.error);\n });\n}\n\n/** Deletes a database of the origin by name (an SDK's own), as far as the browser lets it: blocked or failed, it gives up quietly. */\nexport function deleteDatabase(name: string): Promise<void> {\n return new Promise<void>((resolve) => {\n try { const request = indexedDB.deleteDatabase(name); request.onsuccess = request.onerror = request.onblocked = () => resolve(); } catch { resolve(); }\n });\n}\n\n/** A read. A write goes through `committed`: its request's success does not mean the browser kept it. */\nexport function wrap<T>(request: IDBRequest<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n}\n\n/** What a write the device had no room for says (Chromium's own QuotaExceededError has no message). */\nexport const NO_ROOM_TO_SAVE = \"This device has no room left to save this\";\n\n/**\n * A write, settled when its transaction is: kept once it commits, refused when it aborts. On a device out of storage\n * Chromium fires the request's success and then aborts the transaction with QuotaExceededError, so a write awaited on\n * its request alone reads as saved and is gone. The last request of its transaction: the transaction ends before this\n * settles. Several in one transaction settle together.\n */\nexport function committed<T>(request: IDBRequest<T>): Promise<T> {\n const tx = request.transaction!;\n return new Promise((resolve, reject) => {\n tx.addEventListener(\"complete\", () => resolve(request.result));\n tx.addEventListener(\"abort\", () => {\n const error = tx.error ?? request.error;\n reject(error?.name === \"QuotaExceededError\" ? Object.assign(new Error(NO_ROOM_TO_SAVE), { name: \"QuotaExceededError\", cause: error })\n : error ?? new Error(\"The write was not saved\"));\n });\n });\n}\n\nexport async function store(name: string, mode: IDBTransactionMode): Promise<IDBObjectStore> {\n return (await openDb()).transaction(name, mode).objectStore(name);\n}\n\n/**\n * Several writes across stores in one transaction: they all land, or none does.\n * `work` only queues requests; the promise settles when the transaction does.\n */\nexport async function transact(names: string[], work: (stores: Record<string, IDBObjectStore>) => void): Promise<void> {\n const tx = (await openDb()).transaction(names, \"readwrite\");\n const done = new Promise<void>((resolve, reject) => {\n tx.oncomplete = () => resolve();\n tx.onabort = () => reject(tx.error ?? new Error(\"The wallet could not save\"));\n tx.onerror = () => reject(tx.error ?? new Error(\"The wallet could not save\"));\n });\n try {\n work(Object.fromEntries(names.map((name) => [name, tx.objectStore(name)])));\n } catch (error) {\n tx.abort();\n await done.catch(() => {});\n throw error;\n }\n return done;\n}\n\n/**\n * The `count` newest wallet movements of the mints `wanted` picks, newest first. Read backwards on the history index, a\n * mint at a time: a mint not wanted, or one whose `count` newest are read, is stepped over at once. What it reads grows\n * with the number of mints, never with the history's length.\n */\nexport async function newestWalletTx<T extends { timestamp: number }>(wanted: (mint: string) => boolean, count: number): Promise<T[]> {\n const index = (await store(STORES.walletTx, \"readonly\")).index(WALLET_TX_INDEX);\n const rows: T[] = [];\n await new Promise<void>((resolve, reject) => {\n let mint: string | undefined, taken = 0;\n const read = (below: IDBKeyRange | null) => {\n const request = index.openCursor(below, \"prev\");\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const cursor = request.result;\n if (!cursor) { resolve(); return; }\n const [at] = cursor.key as [string, number];\n if (at !== mint) { mint = at; taken = 0; }\n // A new cursor below every key of this mint starts at the next mint's newest movement. Not `continue(key)`:\n // fake-indexeddb (the CLI's and Desktop-headless' IndexedDB) walks every key that skips.\n if (taken >= count || !wanted(at)) { read(IDBKeyRange.upperBound([at, -Infinity], true)); return; }\n rows.push(cursor.value as T);\n taken++;\n cursor.continue();\n };\n };\n read(null);\n });\n return rows.sort((a, b) => b.timestamp - a.timestamp).slice(0, count);\n}\n\n/** A stored file as it stands: its record, with what changed since it was stored read over it. */\nfunction withState(file: StoredFile, state: FileState | undefined): StoredFile {\n if (!state) return file;\n const { id: _id, ...fields } = state;\n return { ...file, ...fields };\n}\n\n/**\n * The files store. A record is written once, by `put`, and never written back: what changes later (`patch`,\n * `updateTransfer`) goes to `STORES.fileState` and is read over it. WebKit (Safari, the macOS app) keeps a stored\n * Blob as a file the record points to, and a record written back with the Blob it read can lose that file: from\n * then on every read of it fails with \"The object can not be found here.\" For the same reason a Blob read from\n * here is never put here again, under any id (a forward copies the bytes into a Blob of its own).\n */\nexport const fileStore = {\n /** Stores a file anew: whatever changed about an earlier file under this id is forgotten. */\n async put(file: StoredFile): Promise<void> {\n await transact([STORES.files, STORES.fileState], stores => {\n stores[STORES.files].put(file);\n stores[STORES.fileState].delete(file.id);\n });\n },\n async updateTransfer(id: string, transfer: NonNullable<StoredFile[\"transfer\"]>): Promise<void> {\n await fileStore.patch(id, { transfer });\n },\n /** Changes some fields of a stored file (never its record, see above); nothing happens to one that was deleted. */\n async patch(id: string, fields: FileStateFields): Promise<void> {\n await transact([STORES.files, STORES.fileState], stores => {\n const exists = stores[STORES.files].getKey(id);\n exists.onsuccess = () => {\n if (exists.result === undefined) return;\n const state = stores[STORES.fileState].get(id);\n state.onsuccess = () => { stores[STORES.fileState].put({ ...(state.result as FileState | undefined), ...fields, id } satisfies FileState); };\n };\n });\n },\n async get(id: string): Promise<StoredFile | undefined> {\n const tx = (await openDb()).transaction([STORES.files, STORES.fileState], \"readonly\");\n const [file, state] = await Promise.all([\n wrap<StoredFile | undefined>(tx.objectStore(STORES.files).get(id)),\n wrap<FileState | undefined>(tx.objectStore(STORES.fileState).get(id)),\n ]);\n return file && withState(file, state);\n },\n /**\n * A link's files in two requests: what changed about them is read as one range, from the least of their ids to the\n * greatest. A link's file ids share its prefix (`<link>-in-`, `group-<id>-out-`…), so the range holds little else, and\n * whatever else it holds is not theirs. A read per file was 16,000 requests at every start with 200 files per chat\n * and 300 per group (50 chats, 20 groups).\n */\n async listForLink(linkId: string): Promise<StoredFile[]> {\n const tx = (await openDb()).transaction([STORES.files, STORES.fileState], \"readonly\");\n const files = await wrap<StoredFile[]>(tx.objectStore(STORES.files).index(\"byLink\").getAll(linkId));\n if (!files.length) return files;\n // Strings sort by UTF-16 code unit, as IndexedDB orders its keys.\n const ids = files.map(file => file.id).sort();\n const states = new Map((await wrap<FileState[]>(tx.objectStore(STORES.fileState).getAll(IDBKeyRange.bound(ids[0], ids[ids.length - 1])))).map(state => [state.id, state]));\n return files.map(file => withState(file, states.get(file.id)));\n },\n /** The id of every group a stored file is of (`linkId` `group:<id>`), read off the index: no record is loaded. */\n async groupIds(): Promise<string[]> {\n const index = (await store(STORES.files, \"readonly\")).index(\"byLink\"), ids: string[] = [];\n await new Promise<void>((resolve, reject) => {\n const request = index.openKeyCursor(IDBKeyRange.bound(\"group:\", \"group:\\uffff\"), \"nextunique\");\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const cursor = request.result;\n if (!cursor) return resolve();\n ids.push(String(cursor.key).slice(\"group:\".length));\n cursor.continue();\n };\n });\n return ids;\n },\n /** The id of every stored file whose bytes are a Blob in its record. */\n async blobIds(): Promise<string[]> {\n const files = await store(STORES.files, \"readonly\"), ids: string[] = [];\n await new Promise<void>((resolve, reject) => {\n const request = files.openCursor();\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const cursor = request.result;\n if (!cursor) return resolve();\n if ((cursor.value as StoredFile).blob) ids.push(String(cursor.key));\n cursor.continue();\n };\n });\n return ids;\n },\n /**\n * A file whose Blob was copied to file storage (`kind`, under its id): its record without the Blob from now on. Written\n * back without the Blob it read, so not what WebKit loses (see above); what changed about it since (`fileState`) stays.\n * False when the record is gone or holds no Blob any more: the copy is the caller's to remove.\n */\n async movedToBytes(id: string, kind: NonNullable<StoredFile[\"bytes\"]>): Promise<boolean> {\n let moved = false;\n await transact([STORES.files], stores => {\n const read = stores[STORES.files].get(id);\n read.onsuccess = () => {\n const record = read.result as StoredFile | undefined;\n if (!record?.blob) return;\n const { blob: _blob, ...rest } = record;\n stores[STORES.files].put({ ...rest, bytes: kind } satisfies StoredFile);\n moved = true;\n };\n });\n return moved;\n },\n async delete(id: string): Promise<void> {\n await transact([STORES.files, STORES.fileState], stores => {\n stores[STORES.files].delete(id);\n stores[STORES.fileState].delete(id);\n });\n },\n async deleteForLink(linkId: string): Promise<void> {\n const tx = (await openDb()).transaction([STORES.files, STORES.fileState], \"readwrite\");\n const files = tx.objectStore(STORES.files), state = tx.objectStore(STORES.fileState);\n const keys = await wrap(files.index(\"byLink\").getAllKeys(linkId));\n await Promise.all(keys.flatMap((key) => [committed(files.delete(key)), committed(state.delete(key))]));\n },\n};\n"],"mappings":";;;;;;AAKA,IAAI,SAAS;;AAOb,SAAgB,eAAuB;CACrC,OAAO;AACT;;AAwBA,IAAa,mBAAb,cAAsC,MAAM;CACrB;CAArB,YAAY,SAAsC;EAChD,MAAM,mBAAmB,OAAO,CAAC;EADd,KAAA,UAAA;EAEnB,KAAK,OAAO;CACd;AACF;;AAGA,SAAgB,mBAAmB,SAAqC;CACtE,MAAM,QAAQ;CACd,QAAQ,QAAQ,QAAhB;EACE,KAAK,SACH,OAAO,iFAAiF,QAAQ,iBAAiB,WAAW,QAAQ,iBAAiB,6BAA6B,QAAQ,iBAAiB;EAC7M,KAAK,WAAW,OAAO,GAAG,MAAM;EAChC,KAAK,QAAQ,OAAO,GAAG,MAAM;EAC7B,KAAK,UAAU,OAAO,GAAG,MAAM;EAC/B,SAAS,OAAO,GAAG,QAAQ,QAAQ,SAAS,KAAK,QAAQ,WAAW;CACtE;AACF;;AAGA,SAAgB,mBAAmB,OAAoC;CACrE,IAAI,iBAAiB,kBAAkB,OAAO,MAAM;CAEpD,MAAM,QAAQ,WAAW,KAAK;CAC9B,IAAI,OAAO,OAAO,UAAU,KAAK;CACjC,MAAM,S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KAAK,IAAG,WAAU;GACvC,MAAM,OAAO,OAAO,OAAO,MAAM,CAAC,IAAI,EAAE;GACxC,KAAK,kBAAkB;IACrB,MAAM,SAAS,KAAK;IACpB,IAAI,CAAC,QAAQ,MAAM;IACnB,MAAM,EAAE,MAAM,OAAO,GAAG,SAAS;IACjC,OAAO,OAAO,MAAM,CAAC,IAAI;KAAE,GAAG;KAAM,OAAO;IAAK,CAAsB;IACtE,QAAQ;GACV;EACF,CAAC;EACD,OAAO;CACT;CACA,MAAM,OAAO,IAA2B;EACtC,MAAM,SAAS,CAAC,OAAO,OAAO,OAAO,SAAS,IAAG,WAAU;GACzD,OAAO,OAAO,MAAM,CAAC,OAAO,EAAE;GAC9B,OAAO,OAAO,UAAU,CAAC,OAAO,EAAE;EACpC,CAAC;CACH;CACA,MAAM,cAAc,QAA+B;EACjD,MAAM,MAAM,MAAM,OAAO,EAAA,CAAG,YAAY,CAAC,OAAO,OAAO,OAAO,SAAS,GAAG,WAAW;EACrF,MAAM,QAAQ,GAAG,YAAY,OAAO,KAAK,GAAG,QAAQ,GAAG,YAAY,OAAO,SAAS;EACnF,MAAM,OAAO,MAAM,KAAK,MAAM,MAAM,QAAQ,CAAC,CAAC,WAAW,MAAM,CAAC;EAChE,MAAM,QAAQ,IAAI,KAAK,SAAS,QAAQ,CAAC,UAAU,MAAM,OAAO,GAAG,CAAC,GAAG,UAAU,MAAM,OAAO,GAAG,CAAC,CAAC,CAAC,CAAC;CACvG;AACF"}
|
|
1
|
+
{"version":3,"file":"idb-ewvbqyDI.js","names":[],"sources":["../../../browser/src/shared/idb.ts"],"sourcesContent":["/**\n * The extension's one IndexedDB database. The peer (offscreen document) and\n * the pages share an origin, so both open it: that is also how file contents\n * move between them without squeezing through runtime messages.\n */\nlet dbName = \"ghostly\";\n\n/** Before first use: keeps profiles that share a browser storage area apart (Desktop's GHOSTLY_PROFILE). */\nexport function setDatabaseName(name: string): void {\n dbName = name;\n}\n/** The peer database this page uses: its profile's (WISP 04). */\nexport function databaseName(): string {\n return dbName;\n}\n/** The schema this build reads and writes. A database stored at a higher one is a newer build's: it is never opened. */\nexport const DB_VERSION = 16;\n\n/**\n * Why the profile's database did not open. `newer`: a newer Ghostly stored it (IndexedDB never opens a database below\n * its stored version). `blocked`: another window still holds it open at an older version. `full`: no storage space.\n * `denied`: the browser gives this page no storage (a private window, storage blocked for the site). `failed`:\n * anything else, a damaged database included (browsers do not tell that one apart).\n */\nexport type ProfileOpenReason = \"newer\" | \"blocked\" | \"full\" | \"denied\" | \"failed\";\n\n/** What the pages are told (a plain object: it crosses the extension's port), and what a bot reads in `details`. */\nexport interface ProfileOpenFailure {\n reason: ProfileOpenReason;\n /** The schema version this build reads (`DB_VERSION`). */\n supportedVersion: number;\n /** The version the database is stored at, when it could be read (`newer`). */\n storedVersion?: number;\n /** What the browser said, in its own words. */\n detail?: string;\n}\n\n/** The profile's database did not open. Nothing was changed, and nothing is ever deleted or reset because of it. */\nexport class ProfileOpenError extends Error {\n constructor(readonly failure: ProfileOpenFailure) {\n super(profileOpenMessage(failure));\n this.name = \"ProfileOpenError\";\n }\n}\n\n/** The failure in plain English, for logs, the CLI and anything that shows an engine error as it came. */\nexport function profileOpenMessage(failure: ProfileOpenFailure): string {\n const could = \"Ghostly could not open this profile's data\";\n switch (failure.reason) {\n case \"newer\":\n return `This profile was last used by a newer version of Ghostly (its data is version ${failure.storedVersion ?? \"above \" + failure.supportedVersion}, this version reads up to ${failure.supportedVersion}). Update Ghostly to open it.`;\n case \"blocked\": return `${could}: another Ghostly window or tab still has it open with an older version. Close it and try again.`;\n case \"full\": return `${could}: this device is out of storage space. Free some space and try again.`;\n case \"denied\": return `${could}: storage is not allowed here (a private window, or storage blocked for this site).`;\n default: return `${could}${failure.detail ? `: ${failure.detail}` : \"\"}`;\n }\n}\n\n/** What the start of the engine failed with, as the failure the pages show: a database that did not open, or anything else. */\nexport function profileOpenFailure(error: unknown): ProfileOpenFailure {\n if (error instanceof ProfileOpenError) return error.failure;\n // The database opened but a first write found no room (Chromium aborts the transaction with an empty message).\n const quota = quotaError(error);\n if (quota) return failureOf(quota);\n const detail = error instanceof Error ? error.message : String(error);\n return { reason: \"failed\", supportedVersion: DB_VERSION, ...(detail ? { detail } : {}) };\n}\n\n/**\n * A failed call as the client hears it (engine/server.ts): the error's message. Only the message travels, so a storage\n * write the browser refused for want of space (Chromium's QuotaExceededError has an empty message) says so, its name\n * kept for the ⓘ.\n */\nexport function errorLine(error: unknown): string {\n if ((error as { name?: unknown } | null)?.name === \"QuotaExceededError\") {\n const message = error instanceof Error ? error.message.trim() : \"\";\n return `Not enough space on this device (QuotaExceededError${message ? `: ${message}` : \"\"})`;\n }\n return error instanceof Error ? error.message : String(error);\n}\n\n/** The no-room error's names: the standard one and Firefox's (its legacy code, 22, is read as well). */\nconst QUOTA_NAMES: ReadonlySet<unknown> = new Set([\"QuotaExceededError\", \"NS_ERROR_DOM_QUOTA_REACHED\"]);\n\n/**\n * The no-room error behind `error`, as thrown or wrapped: a transaction's abort (`error`, an event's `target.error`)\n * or an Error's `cause`. Undefined when it is not one.\n */\nfunction quotaError(error: unknown, depth = 0): { name?: unknown; message?: unknown } | undefined {\n if (!error || typeof error !== \"object\" || depth > 3) return undefined;\n const e = error as { name?: unknown; code?: unknown; error?: unknown; target?: { error?: unknown } | null; cause?: unknown };\n if (QUOTA_NAMES.has(e.name) || (typeof DOMException !== \"undefined\" && error instanceof DOMException && e.code === 22)) return e;\n return quotaError(e.error, depth + 1) ?? quotaError(e.target?.error, depth + 1) ?? quotaError(e.cause, depth + 1);\n}\n\n/**\n * `blockedMs`: how long an open that another window blocks may wait for that window to let go before it is said to be\n * blocked. `silentMs`: how long an open may go without any answer from the browser (no success, error, blocked or\n * upgrade) before it is said to have failed. An upgrade that started has its answer and may take as long as it needs.\n */\nexport const OPEN_TIMINGS = { blockedMs: 10_000, silentMs: 30_000 };\n\nfunction failureOf(error: unknown): ProfileOpenFailure {\n const name = (error as { name?: unknown } | null)?.name;\n const message = (error as { message?: unknown } | null)?.message;\n const detail = [typeof name === \"string\" ? name : \"\", typeof message === \"string\" ? message : \"\"].filter(Boolean).join(\": \");\n const reason: ProfileOpenReason = name === \"VersionError\" ? \"newer\"\n : quotaError(error) ? \"full\"\n // Firefox's private windows of old, storage blocked for the site, or no IndexedDB at all.\n : name === \"BlockedError\" ? \"blocked\"\n : name === \"SecurityError\" || name === \"InvalidStateError\" || name === \"ReferenceError\" || name === \"TypeError\" ? \"denied\"\n : \"failed\";\n return { reason, supportedVersion: DB_VERSION, ...(detail ? { detail } : {}) };\n}\n\n/**\n * The version a database is stored at, read without changing it: an open that names no version opens what is there.\n * Only for a database known to exist (an open without a version would make a missing one).\n */\nfunction storedVersion(name: string): Promise<number | undefined> {\n return new Promise((resolve) => {\n try {\n const request = indexedDB.open(name);\n // It did not exist after all: leave nothing behind.\n request.onupgradeneeded = () => { try { request.transaction?.abort(); } catch { /* already over */ } };\n request.onsuccess = () => { const { version } = request.result; request.result.close(); resolve(version); };\n request.onerror = request.onblocked = () => resolve(undefined);\n } catch { resolve(undefined); }\n });\n}\n/** The messages store's index of card messages (`card.kind`): what `db.getCardMessages` reads. */\nexport const CARD_INDEX = \"byCardKind\";\n/** The messages store's index of the messages that carry a file, by chat (`linkId`, `file.id`): what `db.getFileMessages` reads. */\nexport const FILE_INDEX = \"byLinkFile\";\n/** The wallet history's index by (mint, time): what `newestWalletTx` reads. */\nexport const WALLET_TX_INDEX = \"byMintTime\";\n\nexport const STORES = {\n links: \"links\",\n messages: \"messages\",\n services: \"services\",\n settings: \"settings\",\n files: \"files\",\n proofs: \"proofs\",\n payments: \"payments\",\n quotes: \"quotes\",\n walletTx: \"walletTx\",\n melts: \"melts\",\n /** Swaps at a mint that have not finished (`PendingSwap`): what gets their outputs back when an answer is missed. */\n swaps: \"swaps\",\n intents: \"paymentIntents\",\n /** Private groups (WISP 900): membership chain, epoch secrets and my own recent messages, by group id. */\n groups: \"groups\",\n /** Files kept in 1 MiB pieces where the platform has no file system for them (see `fileBytesIdb.ts`). */\n fileChunks: \"fileChunks\",\n /**\n * What changes about a stored file after it is stored, by file id. A `files` record is written once and never\n * again: WebKit loses the Blob of a record written back with the Blob it read (see `fileStore`).\n */\n fileState: \"fileState\",\n /** Installed mini-apps (WISP 1200 § Updates and rollback), by app reference: `InstalledApp` (`engine/apps.ts`). */\n apps: \"apps\",\n /** The app stores the person added, by store key: `AddedAppStore`. A store is its key; its URL is kept on the record. */\n appStores: \"appStores\",\n /** Each installed app's own storage, by (app reference, scope, key): `AppStorageRow`. Scope: a chat's link id, or `alone`. */\n appStorage: \"appStorage\",\n} as const;\n\n/** The app storage store's index by (app reference, scope): one scope's rows, for its 5 MiB cap and its keys. */\nexport const APP_STORAGE_SCOPE_INDEX = \"byAppScope\";\n/** The app storage store's index by scope: every app's rows of one chat, which go with the chat. */\nexport const APP_STORAGE_CHAT_INDEX = \"byScope\";\n\n/**\n * A file's contents. Metadata travels with the chat message; this is only the bytes: in `blob` for a file\n * small enough to hold whole, or in the platform's file storage (`bytes`, see `fileBytes.ts`) under the same id.\n * Ids are `<link id>-out-<random>` for files we send and `<link id>-in-<random>` for\n * files we receive, both chosen here. Files stored before that are `<link id>-<wire id>`\n * without `direction` and are still read under their old id.\n */\nexport interface StoredFile {\n id: string;\n linkId: string;\n blob?: Blob;\n /** Where the bytes are when there is no `blob`. */\n bytes?: import(\"./fileBytes\").FileBytesKind;\n createdAt: number;\n direction?: \"in\" | \"out\";\n /** The id the file had on the data link. */\n wireId?: string;\n digest?: string;\n metadata?: { name: string; size: number; mime: string; timestamp: number; voice?: import(\"@ghostly/core\").VoiceMeta; video?: import(\"@ghostly/core\").VideoMeta; image?: import(\"@ghostly/core\").ImageMeta };\n transfer?: { state: \"transferring\" | \"done\" | \"failed\"; transferred: number; size: number; error?: string };\n /** files/3: the transfer's own record (`@ghostly/core` `FileTransferRecord`), kept so it resumes after a restart. */\n wire3?: import(\"@ghostly/core\").FileTransferRecord;\n /** Its bytes were left out of the light backup this profile was restored from (WISP 05 § Light backups). */\n leftOut?: boolean;\n /**\n * A file the contact said on the DHT floor (WISP 403 § Files), by its wire id: its bubble waits for its offer on the\n * live session, and no byte is here yet. Gone once the offer came (`wireId` and `wire3` then).\n */\n announced?: string;\n /**\n * A file of a group (WISP 503), its `linkId` `group:<id>`: the message that announced it and its author, whether this\n * device fetched it without asking (it counts toward the group's automatic limit), and whether its person asked for it.\n * `digest` is the author's, which the bytes are checked against.\n */\n /**\n * A group's file (WISP 503): its message, author and, when its announcement reached this device said again under a\n * later epoch than the message's own, that epoch (`arrived`). A `ts` on records from before is not read.\n */\n group?: { message: string; author: string; arrived?: number; auto?: boolean; asked?: boolean; paused?: boolean };\n}\n\n/** The fields of a stored file that change after it is stored: kept in `STORES.fileState`, read over the record's own. */\ntype FileStateFields = Partial<Pick<StoredFile, \"bytes\" | \"digest\" | \"transfer\" | \"wire3\" | \"group\" | \"leftOut\">>;\ntype FileState = { id: string } & FileStateFields;\n\nlet dbPromise: Promise<IDBDatabase> | null = null;\n\nexport function openDb(): Promise<IDBDatabase> {\n dbPromise ??= new Promise((resolve, reject) => {\n let settled = false;\n let blocked: ReturnType<typeof setTimeout> | undefined;\n // A browser fault (WebKit had one on a first page load): an open that never answers, which left the app looking\n // alive with an engine that never started. Without an answer in time it is said as a failure, and Try again reloads.\n const silent = setTimeout(() => fail({ name: \"TimeoutError\", message: `the browser did not answer in ${Math.round(OPEN_TIMINGS.silentMs / 1000)} s` }), OPEN_TIMINGS.silentMs);\n // Said once, as what it is (`ProfileOpenError`): the engine does not start, and the pages show why.\n const fail = (error: unknown) => {\n if (settled) return;\n settled = true;\n clearTimeout(blocked);\n clearTimeout(silent);\n const failure = failureOf(error);\n if (failure.reason !== \"newer\") { reject(new ProfileOpenError(failure)); return; }\n void storedVersion(dbName).then((version) => reject(new ProfileOpenError({ ...failure, ...(version !== undefined ? { storedVersion: version } : {}) })));\n };\n let request: IDBOpenDBRequest;\n try {\n request = indexedDB.open(dbName, DB_VERSION);\n } catch (error) {\n fail(error);\n return;\n }\n request.onupgradeneeded = () => {\n clearTimeout(silent);\n const db = request.result;\n const has = (name: string) => db.objectStoreNames.contains(name);\n if (!has(STORES.links)) db.createObjectStore(STORES.links, { keyPath: \"id\" });\n if (!has(STORES.services)) db.createObjectStore(STORES.services, { keyPath: \"id\" });\n if (!has(STORES.settings)) db.createObjectStore(STORES.settings);\n if (!has(STORES.messages)) {\n db.createObjectStore(STORES.messages, { keyPath: [\"linkId\", \"id\"] }).createIndex(\"byLink\", \"linkId\");\n }\n if (!has(STORES.proofs)) db.createObjectStore(STORES.proofs, { keyPath: \"secret\" });\n if (!has(STORES.payments)) db.createObjectStore(STORES.payments, { keyPath: \"id\" });\n if (!has(STORES.quotes)) db.createObjectStore(STORES.quotes, { keyPath: \"quote\" });\n if (!has(STORES.walletTx)) db.createObjectStore(STORES.walletTx, { keyPath: \"id\" });\n // v5: Lightning payments the mint has not settled yet, and the proofs they hold.\n if (!has(STORES.melts)) db.createObjectStore(STORES.melts, { keyPath: \"quote\" });\n if (!has(STORES.intents)) db.createObjectStore(STORES.intents, { keyPath: \"review.id\" });\n if (!has(STORES.files)) {\n db.createObjectStore(STORES.files, { keyPath: \"id\" }).createIndex(\"byLink\", \"linkId\");\n }\n // v7: private groups.\n if (!has(STORES.groups)) db.createObjectStore(STORES.groups, { keyPath: \"id\" });\n // v8: files in pieces, for platforms without the origin-private file system.\n if (!has(STORES.fileChunks)) db.createObjectStore(STORES.fileChunks, { keyPath: [\"id\", \"index\"] });\n // v9: what changes about a stored file, apart from its record (see `fileStore`).\n if (!has(STORES.fileState)) db.createObjectStore(STORES.fileState, { keyPath: \"id\" });\n // v10: a chat's messages in time order, so its latest page is read without the rest.\n const messages = request.transaction!.objectStore(STORES.messages);\n if (!messages.indexNames.contains(\"byLinkTime\")) messages.createIndex(\"byLinkTime\", [\"linkId\", \"timestamp\"]);\n // v11: the messages that carry a status card, by the card's kind, across every chat and group (the Tasks board).\n // A message without a card has no such key and is not in it, so the index is as small as the cards are few.\n if (!messages.indexNames.contains(CARD_INDEX)) messages.createIndex(CARD_INDEX, \"card.kind\");\n // v12: swaps at a mint, written down before the mint is asked.\n if (!has(STORES.swaps)) db.createObjectStore(STORES.swaps, { keyPath: \"id\" });\n // v13: no change of the schema. A build from here can hold a frozen copy of a profile on a standby device (WISP 06\n // § Compatibility and rollout): the step keeps an older build (1.0.3 reads 12) from opening and starting one.\n // v14: mini-apps (WISP 1200): the installed apps, the stores added and each app's storage per scope. Empty until the\n // apps feature is on; the bundles themselves are in file storage under `app-<digest>`, outside every store here.\n if (!has(STORES.apps)) db.createObjectStore(STORES.apps, { keyPath: \"ref\" });\n if (!has(STORES.appStores)) db.createObjectStore(STORES.appStores, { keyPath: \"key\" });\n if (!has(STORES.appStorage)) {\n const storage = db.createObjectStore(STORES.appStorage, { keyPath: [\"ref\", \"scope\", \"key\"] });\n storage.createIndex(APP_STORAGE_SCOPE_INDEX, [\"ref\", \"scope\"]);\n storage.createIndex(APP_STORAGE_CHAT_INDEX, \"scope\");\n }\n // v15: the wallet history by mint and time, so a refresh reads each network's newest movements without the rest.\n const walletTx = request.transaction!.objectStore(STORES.walletTx);\n if (!walletTx.indexNames.contains(WALLET_TX_INDEX)) walletTx.createIndex(WALLET_TX_INDEX, [\"mint\", \"timestamp\"]);\n // v16: the messages that carry a file, by chat or group, so a chat's files are read without its texts (`file list`).\n // A message without a file has no such key and is not in it.\n if (!messages.indexNames.contains(FILE_INDEX)) messages.createIndex(FILE_INDEX, [\"linkId\", \"file.id\"]);\n };\n request.onsuccess = () => {\n // Opened after it was said to be blocked: nobody uses this connection, and it must not block the next open.\n if (settled) { request.result.close(); return; }\n settled = true;\n clearTimeout(blocked);\n clearTimeout(silent);\n // Let the other context upgrade the schema instead of blocking it.\n request.result.onversionchange = () => {\n request.result.close();\n dbPromise = null;\n };\n resolve(request.result);\n };\n // The event's default aborts nothing here, but an unhandled one is logged as an uncaught error in some browsers.\n request.onerror = (event) => { event.preventDefault?.(); fail(request.error); };\n // Another window holds the database at an older version and has not let go (ours do, on `versionchange`). The\n // open stays pending for as long as that lasts: before, the engine waited with it, silently and for good.\n request.onblocked = () => {\n clearTimeout(silent);\n blocked ??= setTimeout(() => fail({ name: \"BlockedError\", message: \"another connection holds an older version open\" }), OPEN_TIMINGS.blockedMs);\n };\n });\n return dbPromise;\n}\n\n/** The stores \"Clear all data\" empties: chats and their keys, messages, files, shared services, groups, mini-apps and their data. */\nexport const PROFILE_STORES = [STORES.links, STORES.messages, STORES.files, STORES.fileState, STORES.fileChunks, STORES.services, STORES.groups, STORES.apps, STORES.appStores, STORES.appStorage] as const;\n\n/**\n * Records of the settings store that belong to the profile, not to a wallet: its DID and its key, its identity proofs\n * with their keys and revocations and when the contacts' were last looked up for one (and which, of a lookup under way), its own Nostr data, the public profiles it read, the built-in mini-apps it removed\n * (`BUILT_IN_APPS_KEY` of `engine/apps.ts`), the digests of the mini-app bundles it may hold (`APP_BUNDLES_KEY`) and the mini-app revocations it verified (`APP_REVOCATIONS_KEY`), its x401 credentials and their keys (`engine/x401.ts`), its contact links\n * (`engine/contactLinks.ts`), the requests it sent through others' (`engine/contactAsks.ts`) and its saved messages\n * (`engine/saved.ts`). A list of what goes\n * rather than of what stays, on purpose: every other record of that store is a wallet's (seeds, configuration, pending\n * operations), and a wallet record a newer version adds must never be deleted by mistake.\n */\nexport const PROFILE_SETTINGS_KEYS = [\"profileDid\", \"identityProofs\", \"identityRevocations\", \"identityRevocationsCheckedAt\", \"identityRevocationsRound\", \"nostrSocial\", \"publicProfiles\", \"appBuiltIns\", \"appBundles\", \"appRevocations\", \"x401Credentials\", \"contactLinks\", \"contactAsks\", \"savedMessages\"] as const;\n\n/** A private group's small row in the settings store (`GroupLive`, `engine/groupRows.ts`): the profile's too. */\nexport const groupLiveKey = (groupId: string): string => `groupLive:${groupId}`;\nexport const GROUP_LIVE_RANGE = (): IDBKeyRange => IDBKeyRange.bound(groupLiveKey(\"\"), `${groupLiveKey(\"\")}`);\n/** A private group's pin and deletions for everyone, while its record is behind on them (`GroupLight`): the profile's too. */\nexport const groupLightKey = (groupId: string): string => `groupLight:${groupId}`;\nexport const GROUP_LIGHT_RANGE = (): IDBKeyRange => IDBKeyRange.bound(groupLightKey(\"\"), `${groupLightKey(\"\")}`);\n\n/**\n * The fields of the peer's `settings` record that are a wallet's, kept by \"Clear all data\": the mint list, the first-run\n * wallet setup and the backup reminders. Everything else in it is the profile's (name, picture, network settings,\n * storage credentials for held items, the push subscription and who holds it) and goes.\n */\nexport const WALLET_SETTINGS_FIELDS = [\"mints\", \"mintsInitialized\", \"walletSetup\", \"backupReminders\"] as const;\n\n/**\n * \"Clear all data\" (WISP 04): everything of the profile in its peer database except its wallets. The chats' stores are\n * emptied, the profile's records of the settings store are deleted and the `settings` record keeps only its wallet\n * fields. The wallets (proofs, payments, quotes, history, payment journal, wallet records) stay: ecash is money, and\n * nothing else holds a copy of it. The caller stops the peer first, or it may write back what was just deleted.\n */\nexport async function clearProfileStores(): Promise<void> {\n if (typeof indexedDB === \"undefined\") return;\n const db = await openDb();\n const names = [...PROFILE_STORES, STORES.settings].filter((name) => db.objectStoreNames.contains(name));\n const tx = db.transaction(names, \"readwrite\");\n for (const name of names) if (name !== STORES.settings) tx.objectStore(name).clear();\n if (names.includes(STORES.settings)) {\n const settings = tx.objectStore(STORES.settings);\n for (const key of PROFILE_SETTINGS_KEYS) settings.delete(key);\n settings.delete(GROUP_LIVE_RANGE());\n settings.delete(GROUP_LIGHT_RANGE());\n const read = settings.get(\"settings\");\n read.onsuccess = () => {\n const record = read.result as Record<string, unknown> | undefined;\n if (!record || typeof record !== \"object\") return;\n const kept = Object.fromEntries(WALLET_SETTINGS_FIELDS.filter((field) => field in record).map((field) => [field, record[field]]));\n settings.put(kept, \"settings\");\n };\n }\n await new Promise<void>((resolve, reject) => {\n tx.oncomplete = () => resolve();\n tx.onerror = tx.onabort = () => reject(tx.error);\n });\n}\n\n/** Deletes a database of the origin by name (an SDK's own), as far as the browser lets it: blocked or failed, it gives up quietly. */\nexport function deleteDatabase(name: string): Promise<void> {\n return new Promise<void>((resolve) => {\n try { const request = indexedDB.deleteDatabase(name); request.onsuccess = request.onerror = request.onblocked = () => resolve(); } catch { resolve(); }\n });\n}\n\n/** A read. A write goes through `committed`: its request's success does not mean the browser kept it. */\nexport function wrap<T>(request: IDBRequest<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n}\n\n/** What a write the device had no room for says (Chromium's own QuotaExceededError has no message). */\nexport const NO_ROOM_TO_SAVE = \"This device has no room left to save this\";\n\n/**\n * A write, settled when its transaction is: kept once it commits, refused when it aborts. On a device out of storage\n * Chromium fires the request's success and then aborts the transaction with QuotaExceededError, so a write awaited on\n * its request alone reads as saved and is gone. The last request of its transaction: the transaction ends before this\n * settles. Several in one transaction settle together.\n */\nexport function committed<T>(request: IDBRequest<T>): Promise<T> {\n const tx = request.transaction!;\n return new Promise((resolve, reject) => {\n tx.addEventListener(\"complete\", () => resolve(request.result));\n tx.addEventListener(\"abort\", () => {\n const error = tx.error ?? request.error;\n reject(error?.name === \"QuotaExceededError\" ? Object.assign(new Error(NO_ROOM_TO_SAVE), { name: \"QuotaExceededError\", cause: error })\n : error ?? new Error(\"The write was not saved\"));\n });\n });\n}\n\nexport async function store(name: string, mode: IDBTransactionMode): Promise<IDBObjectStore> {\n return (await openDb()).transaction(name, mode).objectStore(name);\n}\n\n/**\n * Several writes across stores in one transaction: they all land, or none does.\n * `work` only queues requests; the promise settles when the transaction does.\n */\nexport async function transact(names: string[], work: (stores: Record<string, IDBObjectStore>) => void): Promise<void> {\n const tx = (await openDb()).transaction(names, \"readwrite\");\n const done = new Promise<void>((resolve, reject) => {\n tx.oncomplete = () => resolve();\n tx.onabort = () => reject(tx.error ?? new Error(\"The wallet could not save\"));\n tx.onerror = () => reject(tx.error ?? new Error(\"The wallet could not save\"));\n });\n try {\n work(Object.fromEntries(names.map((name) => [name, tx.objectStore(name)])));\n } catch (error) {\n tx.abort();\n await done.catch(() => {});\n throw error;\n }\n return done;\n}\n\n/**\n * The `count` newest wallet movements of the mints `wanted` picks, newest first. Read backwards on the history index, a\n * mint at a time: a mint not wanted, or one whose `count` newest are read, is stepped over at once. What it reads grows\n * with the number of mints, never with the history's length.\n */\nexport async function newestWalletTx<T extends { timestamp: number }>(wanted: (mint: string) => boolean, count: number): Promise<T[]> {\n const index = (await store(STORES.walletTx, \"readonly\")).index(WALLET_TX_INDEX);\n const rows: T[] = [];\n await new Promise<void>((resolve, reject) => {\n let mint: string | undefined, taken = 0;\n const read = (below: IDBKeyRange | null) => {\n const request = index.openCursor(below, \"prev\");\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const cursor = request.result;\n if (!cursor) { resolve(); return; }\n const [at] = cursor.key as [string, number];\n if (at !== mint) { mint = at; taken = 0; }\n // A new cursor below every key of this mint starts at the next mint's newest movement. Not `continue(key)`:\n // fake-indexeddb (the CLI's and Desktop-headless' IndexedDB) walks every key that skips.\n if (taken >= count || !wanted(at)) { read(IDBKeyRange.upperBound([at, -Infinity], true)); return; }\n rows.push(cursor.value as T);\n taken++;\n cursor.continue();\n };\n };\n read(null);\n });\n return rows.sort((a, b) => b.timestamp - a.timestamp).slice(0, count);\n}\n\n/** A stored file as it stands: its record, with what changed since it was stored read over it. */\nfunction withState(file: StoredFile, state: FileState | undefined): StoredFile {\n if (!state) return file;\n const { id: _id, ...fields } = state;\n return { ...file, ...fields };\n}\n\n/**\n * The files store. A record is written once, by `put`, and never written back: what changes later (`patch`,\n * `updateTransfer`) goes to `STORES.fileState` and is read over it. WebKit (Safari, the macOS app) keeps a stored\n * Blob as a file the record points to, and a record written back with the Blob it read can lose that file: from\n * then on every read of it fails with \"The object can not be found here.\" For the same reason a Blob read from\n * here is never put here again, under any id (a forward copies the bytes into a Blob of its own).\n */\nexport const fileStore = {\n /** Stores a file anew: whatever changed about an earlier file under this id is forgotten. */\n async put(file: StoredFile): Promise<void> {\n await transact([STORES.files, STORES.fileState], stores => {\n stores[STORES.files].put(file);\n stores[STORES.fileState].delete(file.id);\n });\n },\n async updateTransfer(id: string, transfer: NonNullable<StoredFile[\"transfer\"]>): Promise<void> {\n await fileStore.patch(id, { transfer });\n },\n /** Changes some fields of a stored file (never its record, see above); nothing happens to one that was deleted. */\n async patch(id: string, fields: FileStateFields): Promise<void> {\n await transact([STORES.files, STORES.fileState], stores => {\n const exists = stores[STORES.files].getKey(id);\n exists.onsuccess = () => {\n if (exists.result === undefined) return;\n const state = stores[STORES.fileState].get(id);\n state.onsuccess = () => { stores[STORES.fileState].put({ ...(state.result as FileState | undefined), ...fields, id } satisfies FileState); };\n };\n });\n },\n async get(id: string): Promise<StoredFile | undefined> {\n const tx = (await openDb()).transaction([STORES.files, STORES.fileState], \"readonly\");\n const [file, state] = await Promise.all([\n wrap<StoredFile | undefined>(tx.objectStore(STORES.files).get(id)),\n wrap<FileState | undefined>(tx.objectStore(STORES.fileState).get(id)),\n ]);\n return file && withState(file, state);\n },\n /**\n * A link's files in two requests: what changed about them is read as one range, from the least of their ids to the\n * greatest. A link's file ids share its prefix (`<link>-in-`, `group-<id>-out-`…), so the range holds little else, and\n * whatever else it holds is not theirs. A read per file was 16,000 requests at every start with 200 files per chat\n * and 300 per group (50 chats, 20 groups).\n */\n async listForLink(linkId: string): Promise<StoredFile[]> {\n const tx = (await openDb()).transaction([STORES.files, STORES.fileState], \"readonly\");\n const files = await wrap<StoredFile[]>(tx.objectStore(STORES.files).index(\"byLink\").getAll(linkId));\n if (!files.length) return files;\n // Strings sort by UTF-16 code unit, as IndexedDB orders its keys.\n const ids = files.map(file => file.id).sort();\n const states = new Map((await wrap<FileState[]>(tx.objectStore(STORES.fileState).getAll(IDBKeyRange.bound(ids[0], ids[ids.length - 1])))).map(state => [state.id, state]));\n return files.map(file => withState(file, states.get(file.id)));\n },\n /** The id of every group a stored file is of (`linkId` `group:<id>`), read off the index: no record is loaded. */\n async groupIds(): Promise<string[]> {\n const index = (await store(STORES.files, \"readonly\")).index(\"byLink\"), ids: string[] = [];\n await new Promise<void>((resolve, reject) => {\n const request = index.openKeyCursor(IDBKeyRange.bound(\"group:\", \"group:\\uffff\"), \"nextunique\");\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const cursor = request.result;\n if (!cursor) return resolve();\n ids.push(String(cursor.key).slice(\"group:\".length));\n cursor.continue();\n };\n });\n return ids;\n },\n /** The id of every stored file whose bytes are a Blob in its record. */\n async blobIds(): Promise<string[]> {\n const files = await store(STORES.files, \"readonly\"), ids: string[] = [];\n await new Promise<void>((resolve, reject) => {\n const request = files.openCursor();\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const cursor = request.result;\n if (!cursor) return resolve();\n if ((cursor.value as StoredFile).blob) ids.push(String(cursor.key));\n cursor.continue();\n };\n });\n return ids;\n },\n /**\n * A file whose Blob was copied to file storage (`kind`, under its id): its record without the Blob from now on. Written\n * back without the Blob it read, so not what WebKit loses (see above); what changed about it since (`fileState`) stays.\n * False when the record is gone or holds no Blob any more: the copy is the caller's to remove.\n */\n async movedToBytes(id: string, kind: NonNullable<StoredFile[\"bytes\"]>): Promise<boolean> {\n let moved = false;\n await transact([STORES.files], stores => {\n const read = stores[STORES.files].get(id);\n read.onsuccess = () => {\n const record = read.result as StoredFile | undefined;\n if (!record?.blob) return;\n const { blob: _blob, ...rest } = record;\n stores[STORES.files].put({ ...rest, bytes: kind } satisfies StoredFile);\n moved = true;\n };\n });\n return moved;\n },\n async delete(id: string): Promise<void> {\n await transact([STORES.files, STORES.fileState], stores => {\n stores[STORES.files].delete(id);\n stores[STORES.fileState].delete(id);\n });\n },\n async deleteForLink(linkId: string): Promise<void> {\n const tx = (await openDb()).transaction([STORES.files, STORES.fileState], \"readwrite\");\n const files = tx.objectStore(STORES.files), state = tx.objectStore(STORES.fileState);\n const keys = await wrap(files.index(\"byLink\").getAllKeys(linkId));\n await Promise.all(keys.flatMap((key) => [committed(files.delete(key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