@unicitylabs/sphere-sdk 0.2.3 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +61 -20
- package/dist/core/index.cjs +5764 -3576
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +648 -256
- package/dist/core/index.d.ts +648 -256
- package/dist/core/index.js +5767 -3576
- package/dist/core/index.js.map +1 -1
- package/dist/impl/browser/index.cjs +2118 -185
- package/dist/impl/browser/index.cjs.map +1 -1
- package/dist/impl/browser/index.js +2118 -185
- package/dist/impl/browser/index.js.map +1 -1
- package/dist/impl/browser/ipfs.cjs +1823 -513
- package/dist/impl/browser/ipfs.cjs.map +1 -1
- package/dist/impl/browser/ipfs.js +1823 -513
- package/dist/impl/browser/ipfs.js.map +1 -1
- package/dist/impl/nodejs/index.cjs +2110 -183
- package/dist/impl/nodejs/index.cjs.map +1 -1
- package/dist/impl/nodejs/index.d.cts +86 -23
- package/dist/impl/nodejs/index.d.ts +86 -23
- package/dist/impl/nodejs/index.js +2110 -183
- package/dist/impl/nodejs/index.js.map +1 -1
- package/dist/index.cjs +5782 -3603
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +719 -105
- package/dist/index.d.ts +719 -105
- package/dist/index.js +5780 -3603
- package/dist/index.js.map +1 -1
- package/package.json +28 -6
|
@@ -1,59 +1,63 @@
|
|
|
1
|
-
//
|
|
2
|
-
var
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
/** Wallet existence flag */
|
|
18
|
-
WALLET_EXISTS: "wallet_exists",
|
|
19
|
-
/** Current active address index */
|
|
20
|
-
CURRENT_ADDRESS_INDEX: "current_address_index",
|
|
21
|
-
/** Nametag cache per address (separate from tracked addresses registry) */
|
|
22
|
-
ADDRESS_NAMETAGS: "address_nametags",
|
|
23
|
-
/** Active addresses registry (JSON: TrackedAddressesStorage) */
|
|
24
|
-
TRACKED_ADDRESSES: "tracked_addresses",
|
|
25
|
-
/** Last processed Nostr wallet event timestamp (unix seconds), keyed per pubkey */
|
|
26
|
-
LAST_WALLET_EVENT_TS: "last_wallet_event_ts"
|
|
27
|
-
};
|
|
28
|
-
var STORAGE_KEYS_ADDRESS = {
|
|
29
|
-
/** Pending transfers for this address */
|
|
30
|
-
PENDING_TRANSFERS: "pending_transfers",
|
|
31
|
-
/** Transfer outbox for this address */
|
|
32
|
-
OUTBOX: "outbox",
|
|
33
|
-
/** Conversations for this address */
|
|
34
|
-
CONVERSATIONS: "conversations",
|
|
35
|
-
/** Messages for this address */
|
|
36
|
-
MESSAGES: "messages",
|
|
37
|
-
/** Transaction history for this address */
|
|
38
|
-
TRANSACTION_HISTORY: "transaction_history"
|
|
1
|
+
// impl/shared/ipfs/ipfs-error-types.ts
|
|
2
|
+
var IpfsError = class extends Error {
|
|
3
|
+
category;
|
|
4
|
+
gateway;
|
|
5
|
+
cause;
|
|
6
|
+
constructor(message, category, gateway, cause) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = "IpfsError";
|
|
9
|
+
this.category = category;
|
|
10
|
+
this.gateway = gateway;
|
|
11
|
+
this.cause = cause;
|
|
12
|
+
}
|
|
13
|
+
/** Whether this error should trigger the circuit breaker */
|
|
14
|
+
get shouldTriggerCircuitBreaker() {
|
|
15
|
+
return this.category !== "NOT_FOUND" && this.category !== "SEQUENCE_DOWNGRADE";
|
|
16
|
+
}
|
|
39
17
|
};
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
18
|
+
function classifyFetchError(error) {
|
|
19
|
+
if (error instanceof DOMException && error.name === "AbortError") {
|
|
20
|
+
return "TIMEOUT";
|
|
21
|
+
}
|
|
22
|
+
if (error instanceof TypeError) {
|
|
23
|
+
return "NETWORK_ERROR";
|
|
24
|
+
}
|
|
25
|
+
if (error instanceof Error && error.name === "TimeoutError") {
|
|
26
|
+
return "TIMEOUT";
|
|
27
|
+
}
|
|
28
|
+
return "NETWORK_ERROR";
|
|
29
|
+
}
|
|
30
|
+
function classifyHttpStatus(status, responseBody) {
|
|
31
|
+
if (status === 404) {
|
|
32
|
+
return "NOT_FOUND";
|
|
33
|
+
}
|
|
34
|
+
if (status === 500 && responseBody) {
|
|
35
|
+
if (/routing:\s*not\s*found/i.test(responseBody)) {
|
|
36
|
+
return "NOT_FOUND";
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if (status >= 500) {
|
|
40
|
+
return "GATEWAY_ERROR";
|
|
41
|
+
}
|
|
42
|
+
if (status >= 400) {
|
|
43
|
+
return "GATEWAY_ERROR";
|
|
44
|
+
}
|
|
45
|
+
return "GATEWAY_ERROR";
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// impl/shared/ipfs/ipfs-state-persistence.ts
|
|
49
|
+
var InMemoryIpfsStatePersistence = class {
|
|
50
|
+
states = /* @__PURE__ */ new Map();
|
|
51
|
+
async load(ipnsName) {
|
|
52
|
+
return this.states.get(ipnsName) ?? null;
|
|
53
|
+
}
|
|
54
|
+
async save(ipnsName, state) {
|
|
55
|
+
this.states.set(ipnsName, { ...state });
|
|
56
|
+
}
|
|
57
|
+
async clear(ipnsName) {
|
|
58
|
+
this.states.delete(ipnsName);
|
|
59
|
+
}
|
|
43
60
|
};
|
|
44
|
-
var DEFAULT_IPFS_GATEWAYS = [
|
|
45
|
-
"https://ipfs.unicity.network",
|
|
46
|
-
"https://dweb.link",
|
|
47
|
-
"https://ipfs.io"
|
|
48
|
-
];
|
|
49
|
-
var DEFAULT_IPFS_BOOTSTRAP_PEERS = [
|
|
50
|
-
"/dns4/unicity-ipfs2.dyndns.org/tcp/4001/p2p/12D3KooWLNi5NDPPHbrfJakAQqwBqymYTTwMQXQKEWuCrJNDdmfh",
|
|
51
|
-
"/dns4/unicity-ipfs3.dyndns.org/tcp/4001/p2p/12D3KooWQ4aujVE4ShLjdusNZBdffq3TbzrwT2DuWZY9H1Gxhwn6",
|
|
52
|
-
"/dns4/unicity-ipfs4.dyndns.org/tcp/4001/p2p/12D3KooWJ1ByPfUzUrpYvgxKU8NZrR8i6PU1tUgMEbQX9Hh2DEn1",
|
|
53
|
-
"/dns4/unicity-ipfs5.dyndns.org/tcp/4001/p2p/12D3KooWB1MdZZGHN5B8TvWXntbycfe7Cjcz7n6eZ9eykZadvmDv"
|
|
54
|
-
];
|
|
55
|
-
var DEFAULT_BASE_PATH = "m/44'/0'/0'";
|
|
56
|
-
var DEFAULT_DERIVATION_PATH = `${DEFAULT_BASE_PATH}/0/0`;
|
|
57
61
|
|
|
58
62
|
// node_modules/@noble/hashes/utils.js
|
|
59
63
|
function isBytes(a) {
|
|
@@ -491,583 +495,1889 @@ var sha256 = /* @__PURE__ */ createHasher(
|
|
|
491
495
|
/* @__PURE__ */ oidNist(1)
|
|
492
496
|
);
|
|
493
497
|
|
|
494
|
-
//
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
+
// core/crypto.ts
|
|
499
|
+
import * as bip39 from "bip39";
|
|
500
|
+
import CryptoJS from "crypto-js";
|
|
501
|
+
import elliptic from "elliptic";
|
|
502
|
+
var ec = new elliptic.ec("secp256k1");
|
|
503
|
+
var CURVE_ORDER = BigInt(
|
|
504
|
+
"0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"
|
|
505
|
+
);
|
|
506
|
+
function hexToBytes(hex) {
|
|
507
|
+
const matches = hex.match(/../g);
|
|
508
|
+
if (!matches) {
|
|
509
|
+
return new Uint8Array(0);
|
|
510
|
+
}
|
|
511
|
+
return Uint8Array.from(matches.map((x) => parseInt(x, 16)));
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
// impl/shared/ipfs/ipns-key-derivation.ts
|
|
515
|
+
var IPNS_HKDF_INFO = "ipfs-storage-ed25519-v1";
|
|
498
516
|
var libp2pCryptoModule = null;
|
|
499
517
|
var libp2pPeerIdModule = null;
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
[
|
|
504
|
-
heliaModule,
|
|
505
|
-
heliaJsonModule,
|
|
506
|
-
libp2pBootstrapModule,
|
|
507
|
-
libp2pCryptoModule,
|
|
508
|
-
libp2pPeerIdModule,
|
|
509
|
-
multiformatsCidModule
|
|
510
|
-
] = await Promise.all([
|
|
511
|
-
import("helia"),
|
|
512
|
-
import("@helia/json"),
|
|
513
|
-
import("@libp2p/bootstrap"),
|
|
518
|
+
async function loadLibp2pModules() {
|
|
519
|
+
if (!libp2pCryptoModule) {
|
|
520
|
+
[libp2pCryptoModule, libp2pPeerIdModule] = await Promise.all([
|
|
514
521
|
import("@libp2p/crypto/keys"),
|
|
515
|
-
import("@libp2p/peer-id")
|
|
516
|
-
import("multiformats/cid")
|
|
522
|
+
import("@libp2p/peer-id")
|
|
517
523
|
]);
|
|
518
524
|
}
|
|
519
525
|
return {
|
|
520
|
-
createHelia: heliaModule.createHelia,
|
|
521
|
-
json: heliaJsonModule.json,
|
|
522
|
-
bootstrap: libp2pBootstrapModule.bootstrap,
|
|
523
526
|
generateKeyPairFromSeed: libp2pCryptoModule.generateKeyPairFromSeed,
|
|
524
|
-
peerIdFromPrivateKey: libp2pPeerIdModule.peerIdFromPrivateKey
|
|
525
|
-
CID: multiformatsCidModule.CID
|
|
527
|
+
peerIdFromPrivateKey: libp2pPeerIdModule.peerIdFromPrivateKey
|
|
526
528
|
};
|
|
527
529
|
}
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
bootstrapPeers: config?.bootstrapPeers ?? [...DEFAULT_IPFS_BOOTSTRAP_PEERS],
|
|
555
|
-
enableIpns: config?.enableIpns ?? true,
|
|
556
|
-
ipnsTimeout: config?.ipnsTimeout ?? 3e4,
|
|
557
|
-
fetchTimeout: config?.fetchTimeout ?? 15e3,
|
|
558
|
-
debug: config?.debug ?? false
|
|
530
|
+
function deriveEd25519KeyMaterial(privateKeyHex, info = IPNS_HKDF_INFO) {
|
|
531
|
+
const walletSecret = hexToBytes(privateKeyHex);
|
|
532
|
+
const infoBytes = new TextEncoder().encode(info);
|
|
533
|
+
return hkdf(sha256, walletSecret, void 0, infoBytes, 32);
|
|
534
|
+
}
|
|
535
|
+
async function deriveIpnsIdentity(privateKeyHex) {
|
|
536
|
+
const { generateKeyPairFromSeed, peerIdFromPrivateKey } = await loadLibp2pModules();
|
|
537
|
+
const derivedKey = deriveEd25519KeyMaterial(privateKeyHex);
|
|
538
|
+
const keyPair = await generateKeyPairFromSeed("Ed25519", derivedKey);
|
|
539
|
+
const peerId = peerIdFromPrivateKey(keyPair);
|
|
540
|
+
return {
|
|
541
|
+
keyPair,
|
|
542
|
+
ipnsName: peerId.toString()
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
// impl/shared/ipfs/ipns-record-manager.ts
|
|
547
|
+
var DEFAULT_LIFETIME_MS = 99 * 365 * 24 * 60 * 60 * 1e3;
|
|
548
|
+
var ipnsModule = null;
|
|
549
|
+
async function loadIpnsModule() {
|
|
550
|
+
if (!ipnsModule) {
|
|
551
|
+
const mod = await import("ipns");
|
|
552
|
+
ipnsModule = {
|
|
553
|
+
createIPNSRecord: mod.createIPNSRecord,
|
|
554
|
+
marshalIPNSRecord: mod.marshalIPNSRecord,
|
|
555
|
+
unmarshalIPNSRecord: mod.unmarshalIPNSRecord
|
|
559
556
|
};
|
|
560
557
|
}
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
558
|
+
return ipnsModule;
|
|
559
|
+
}
|
|
560
|
+
async function createSignedRecord(keyPair, cid, sequenceNumber, lifetimeMs = DEFAULT_LIFETIME_MS) {
|
|
561
|
+
const { createIPNSRecord, marshalIPNSRecord } = await loadIpnsModule();
|
|
562
|
+
const record = await createIPNSRecord(
|
|
563
|
+
keyPair,
|
|
564
|
+
`/ipfs/${cid}`,
|
|
565
|
+
sequenceNumber,
|
|
566
|
+
lifetimeMs
|
|
567
|
+
);
|
|
568
|
+
return marshalIPNSRecord(record);
|
|
569
|
+
}
|
|
570
|
+
async function parseRoutingApiResponse(responseText) {
|
|
571
|
+
const { unmarshalIPNSRecord } = await loadIpnsModule();
|
|
572
|
+
const lines = responseText.trim().split("\n");
|
|
573
|
+
for (const line of lines) {
|
|
574
|
+
if (!line.trim()) continue;
|
|
567
575
|
try {
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
576
|
+
const obj = JSON.parse(line);
|
|
577
|
+
if (obj.Extra) {
|
|
578
|
+
const recordData = base64ToUint8Array(obj.Extra);
|
|
579
|
+
const record = unmarshalIPNSRecord(recordData);
|
|
580
|
+
const valueBytes = typeof record.value === "string" ? new TextEncoder().encode(record.value) : record.value;
|
|
581
|
+
const valueStr = new TextDecoder().decode(valueBytes);
|
|
582
|
+
const cidMatch = valueStr.match(/\/ipfs\/([a-zA-Z0-9]+)/);
|
|
583
|
+
if (cidMatch) {
|
|
584
|
+
return {
|
|
585
|
+
cid: cidMatch[1],
|
|
586
|
+
sequence: record.sequence,
|
|
587
|
+
recordData
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
} catch {
|
|
592
|
+
continue;
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
return null;
|
|
596
|
+
}
|
|
597
|
+
function base64ToUint8Array(base64) {
|
|
598
|
+
const binary = atob(base64);
|
|
599
|
+
const bytes = new Uint8Array(binary.length);
|
|
600
|
+
for (let i = 0; i < binary.length; i++) {
|
|
601
|
+
bytes[i] = binary.charCodeAt(i);
|
|
602
|
+
}
|
|
603
|
+
return bytes;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
// impl/shared/ipfs/ipfs-cache.ts
|
|
607
|
+
var DEFAULT_IPNS_TTL_MS = 6e4;
|
|
608
|
+
var DEFAULT_FAILURE_COOLDOWN_MS = 6e4;
|
|
609
|
+
var DEFAULT_FAILURE_THRESHOLD = 3;
|
|
610
|
+
var DEFAULT_KNOWN_FRESH_WINDOW_MS = 3e4;
|
|
611
|
+
var IpfsCache = class {
|
|
612
|
+
ipnsRecords = /* @__PURE__ */ new Map();
|
|
613
|
+
content = /* @__PURE__ */ new Map();
|
|
614
|
+
gatewayFailures = /* @__PURE__ */ new Map();
|
|
615
|
+
knownFreshTimestamps = /* @__PURE__ */ new Map();
|
|
616
|
+
ipnsTtlMs;
|
|
617
|
+
failureCooldownMs;
|
|
618
|
+
failureThreshold;
|
|
619
|
+
knownFreshWindowMs;
|
|
620
|
+
constructor(config) {
|
|
621
|
+
this.ipnsTtlMs = config?.ipnsTtlMs ?? DEFAULT_IPNS_TTL_MS;
|
|
622
|
+
this.failureCooldownMs = config?.failureCooldownMs ?? DEFAULT_FAILURE_COOLDOWN_MS;
|
|
623
|
+
this.failureThreshold = config?.failureThreshold ?? DEFAULT_FAILURE_THRESHOLD;
|
|
624
|
+
this.knownFreshWindowMs = config?.knownFreshWindowMs ?? DEFAULT_KNOWN_FRESH_WINDOW_MS;
|
|
625
|
+
}
|
|
626
|
+
// ---------------------------------------------------------------------------
|
|
627
|
+
// IPNS Record Cache (60s TTL)
|
|
628
|
+
// ---------------------------------------------------------------------------
|
|
629
|
+
getIpnsRecord(ipnsName) {
|
|
630
|
+
const entry = this.ipnsRecords.get(ipnsName);
|
|
631
|
+
if (!entry) return null;
|
|
632
|
+
if (Date.now() - entry.timestamp > this.ipnsTtlMs) {
|
|
633
|
+
this.ipnsRecords.delete(ipnsName);
|
|
634
|
+
return null;
|
|
575
635
|
}
|
|
636
|
+
return entry.data;
|
|
576
637
|
}
|
|
577
638
|
/**
|
|
578
|
-
*
|
|
639
|
+
* Get cached IPNS record ignoring TTL (for known-fresh optimization).
|
|
579
640
|
*/
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
this.log("Initializing Helia with bootstrap peers...");
|
|
584
|
-
const { createHelia, json, bootstrap } = await loadHeliaModules();
|
|
585
|
-
this.helia = await createHelia({
|
|
586
|
-
libp2p: {
|
|
587
|
-
peerDiscovery: [
|
|
588
|
-
bootstrap({ list: this.config.bootstrapPeers })
|
|
589
|
-
],
|
|
590
|
-
connectionManager: {
|
|
591
|
-
maxConnections: 10
|
|
592
|
-
}
|
|
593
|
-
}
|
|
594
|
-
});
|
|
595
|
-
this.heliaJson = json(this.helia);
|
|
596
|
-
const peerId = this.helia.libp2p.peerId.toString();
|
|
597
|
-
this.log("Helia initialized, browser peer ID:", peerId.slice(0, 20) + "...");
|
|
598
|
-
setTimeout(() => {
|
|
599
|
-
const connections = this.helia?.libp2p.getConnections() || [];
|
|
600
|
-
this.log(`Active Helia connections: ${connections.length}`);
|
|
601
|
-
}, 3e3);
|
|
602
|
-
} catch (error) {
|
|
603
|
-
this.log("Helia initialization failed (will use HTTP only):", error);
|
|
604
|
-
}
|
|
641
|
+
getIpnsRecordIgnoreTtl(ipnsName) {
|
|
642
|
+
const entry = this.ipnsRecords.get(ipnsName);
|
|
643
|
+
return entry?.data ?? null;
|
|
605
644
|
}
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
this.log("Error stopping Helia:", error);
|
|
612
|
-
}
|
|
613
|
-
this.helia = null;
|
|
614
|
-
this.heliaJson = null;
|
|
615
|
-
}
|
|
616
|
-
this.status = "disconnected";
|
|
617
|
-
this.localCache = null;
|
|
618
|
-
this.ipnsKeyPair = null;
|
|
619
|
-
this.log("Disconnected from IPFS");
|
|
645
|
+
setIpnsRecord(ipnsName, result) {
|
|
646
|
+
this.ipnsRecords.set(ipnsName, {
|
|
647
|
+
data: result,
|
|
648
|
+
timestamp: Date.now()
|
|
649
|
+
});
|
|
620
650
|
}
|
|
621
|
-
|
|
622
|
-
|
|
651
|
+
invalidateIpns(ipnsName) {
|
|
652
|
+
this.ipnsRecords.delete(ipnsName);
|
|
623
653
|
}
|
|
624
|
-
|
|
625
|
-
|
|
654
|
+
// ---------------------------------------------------------------------------
|
|
655
|
+
// Content Cache (infinite TTL - content is immutable by CID)
|
|
656
|
+
// ---------------------------------------------------------------------------
|
|
657
|
+
getContent(cid) {
|
|
658
|
+
const entry = this.content.get(cid);
|
|
659
|
+
return entry?.data ?? null;
|
|
626
660
|
}
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
try {
|
|
633
|
-
const { generateKeyPairFromSeed, peerIdFromPrivateKey } = await loadHeliaModules();
|
|
634
|
-
const walletSecret = this.hexToBytes(identity.privateKey);
|
|
635
|
-
const derivedKey = hkdf(sha256, walletSecret, void 0, HKDF_INFO, 32);
|
|
636
|
-
this.ipnsKeyPair = await generateKeyPairFromSeed("Ed25519", derivedKey);
|
|
637
|
-
const peerId = peerIdFromPrivateKey(this.ipnsKeyPair);
|
|
638
|
-
this.ipnsName = peerId.toString();
|
|
639
|
-
this.log("Identity set, IPNS name:", this.ipnsName);
|
|
640
|
-
} catch {
|
|
641
|
-
this.ipnsName = identity.ipnsName ?? this.deriveIpnsNameSimple(identity.privateKey);
|
|
642
|
-
this.log("Identity set with fallback IPNS name:", this.ipnsName);
|
|
643
|
-
}
|
|
661
|
+
setContent(cid, data) {
|
|
662
|
+
this.content.set(cid, {
|
|
663
|
+
data,
|
|
664
|
+
timestamp: Date.now()
|
|
665
|
+
});
|
|
644
666
|
}
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
667
|
+
// ---------------------------------------------------------------------------
|
|
668
|
+
// Gateway Failure Tracking (Circuit Breaker)
|
|
669
|
+
// ---------------------------------------------------------------------------
|
|
670
|
+
/**
|
|
671
|
+
* Record a gateway failure. After threshold consecutive failures,
|
|
672
|
+
* the gateway enters cooldown and is considered unhealthy.
|
|
673
|
+
*/
|
|
674
|
+
recordGatewayFailure(gateway) {
|
|
675
|
+
const existing = this.gatewayFailures.get(gateway);
|
|
676
|
+
this.gatewayFailures.set(gateway, {
|
|
677
|
+
count: (existing?.count ?? 0) + 1,
|
|
678
|
+
lastFailure: Date.now()
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
/** Reset failure count for a gateway (on successful request) */
|
|
682
|
+
recordGatewaySuccess(gateway) {
|
|
683
|
+
this.gatewayFailures.delete(gateway);
|
|
684
|
+
}
|
|
685
|
+
/**
|
|
686
|
+
* Check if a gateway is currently in circuit breaker cooldown.
|
|
687
|
+
* A gateway is considered unhealthy if it has had >= threshold
|
|
688
|
+
* consecutive failures and the cooldown period hasn't elapsed.
|
|
689
|
+
*/
|
|
690
|
+
isGatewayInCooldown(gateway) {
|
|
691
|
+
const failure = this.gatewayFailures.get(gateway);
|
|
692
|
+
if (!failure) return false;
|
|
693
|
+
if (failure.count < this.failureThreshold) return false;
|
|
694
|
+
const elapsed = Date.now() - failure.lastFailure;
|
|
695
|
+
if (elapsed >= this.failureCooldownMs) {
|
|
696
|
+
this.gatewayFailures.delete(gateway);
|
|
697
|
+
return false;
|
|
648
698
|
}
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
699
|
+
return true;
|
|
700
|
+
}
|
|
701
|
+
// ---------------------------------------------------------------------------
|
|
702
|
+
// Known-Fresh Flag (FAST mode optimization)
|
|
703
|
+
// ---------------------------------------------------------------------------
|
|
704
|
+
/**
|
|
705
|
+
* Mark IPNS cache as "known-fresh" (after local publish or push notification).
|
|
706
|
+
* Within the fresh window, we can skip network resolution.
|
|
707
|
+
*/
|
|
708
|
+
markIpnsFresh(ipnsName) {
|
|
709
|
+
this.knownFreshTimestamps.set(ipnsName, Date.now());
|
|
710
|
+
}
|
|
711
|
+
/**
|
|
712
|
+
* Check if the cache is known-fresh (within the fresh window).
|
|
713
|
+
*/
|
|
714
|
+
isIpnsKnownFresh(ipnsName) {
|
|
715
|
+
const timestamp = this.knownFreshTimestamps.get(ipnsName);
|
|
716
|
+
if (!timestamp) return false;
|
|
717
|
+
if (Date.now() - timestamp > this.knownFreshWindowMs) {
|
|
718
|
+
this.knownFreshTimestamps.delete(ipnsName);
|
|
653
719
|
return false;
|
|
654
720
|
}
|
|
721
|
+
return true;
|
|
655
722
|
}
|
|
656
|
-
|
|
657
|
-
|
|
723
|
+
// ---------------------------------------------------------------------------
|
|
724
|
+
// Cache Management
|
|
725
|
+
// ---------------------------------------------------------------------------
|
|
726
|
+
clear() {
|
|
727
|
+
this.ipnsRecords.clear();
|
|
728
|
+
this.content.clear();
|
|
729
|
+
this.gatewayFailures.clear();
|
|
730
|
+
this.knownFreshTimestamps.clear();
|
|
658
731
|
}
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
732
|
+
};
|
|
733
|
+
|
|
734
|
+
// impl/shared/ipfs/ipfs-http-client.ts
|
|
735
|
+
var DEFAULT_CONNECTIVITY_TIMEOUT_MS = 5e3;
|
|
736
|
+
var DEFAULT_FETCH_TIMEOUT_MS = 15e3;
|
|
737
|
+
var DEFAULT_RESOLVE_TIMEOUT_MS = 1e4;
|
|
738
|
+
var DEFAULT_PUBLISH_TIMEOUT_MS = 3e4;
|
|
739
|
+
var DEFAULT_GATEWAY_PATH_TIMEOUT_MS = 3e3;
|
|
740
|
+
var DEFAULT_ROUTING_API_TIMEOUT_MS = 2e3;
|
|
741
|
+
var IpfsHttpClient = class {
|
|
742
|
+
gateways;
|
|
743
|
+
fetchTimeoutMs;
|
|
744
|
+
resolveTimeoutMs;
|
|
745
|
+
publishTimeoutMs;
|
|
746
|
+
connectivityTimeoutMs;
|
|
747
|
+
debug;
|
|
748
|
+
cache;
|
|
749
|
+
constructor(config, cache) {
|
|
750
|
+
this.gateways = config.gateways;
|
|
751
|
+
this.fetchTimeoutMs = config.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
|
|
752
|
+
this.resolveTimeoutMs = config.resolveTimeoutMs ?? DEFAULT_RESOLVE_TIMEOUT_MS;
|
|
753
|
+
this.publishTimeoutMs = config.publishTimeoutMs ?? DEFAULT_PUBLISH_TIMEOUT_MS;
|
|
754
|
+
this.connectivityTimeoutMs = config.connectivityTimeoutMs ?? DEFAULT_CONNECTIVITY_TIMEOUT_MS;
|
|
755
|
+
this.debug = config.debug ?? false;
|
|
756
|
+
this.cache = cache;
|
|
757
|
+
}
|
|
758
|
+
// ---------------------------------------------------------------------------
|
|
759
|
+
// Public Accessors
|
|
760
|
+
// ---------------------------------------------------------------------------
|
|
761
|
+
/**
|
|
762
|
+
* Get configured gateway URLs.
|
|
763
|
+
*/
|
|
764
|
+
getGateways() {
|
|
765
|
+
return [...this.gateways];
|
|
766
|
+
}
|
|
767
|
+
// ---------------------------------------------------------------------------
|
|
768
|
+
// Gateway Health
|
|
769
|
+
// ---------------------------------------------------------------------------
|
|
770
|
+
/**
|
|
771
|
+
* Test connectivity to a single gateway.
|
|
772
|
+
*/
|
|
773
|
+
async testConnectivity(gateway) {
|
|
774
|
+
const start = Date.now();
|
|
662
775
|
try {
|
|
663
|
-
const
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
}
|
|
670
|
-
};
|
|
671
|
-
const cid = await this.publishToGateways(dataToSave);
|
|
672
|
-
if (this.config.enableIpns && this.ipnsName) {
|
|
673
|
-
await this.publishIpns(cid);
|
|
776
|
+
const response = await this.fetchWithTimeout(
|
|
777
|
+
`${gateway}/api/v0/version`,
|
|
778
|
+
this.connectivityTimeoutMs,
|
|
779
|
+
{ method: "POST" }
|
|
780
|
+
);
|
|
781
|
+
if (!response.ok) {
|
|
782
|
+
return { gateway, healthy: false, error: `HTTP ${response.status}` };
|
|
674
783
|
}
|
|
675
|
-
this.localCache = dataToSave;
|
|
676
|
-
this.cacheTimestamp = Date.now();
|
|
677
|
-
this.lastCid = cid;
|
|
678
|
-
this.emitEvent({ type: "storage:saved", timestamp: Date.now(), data: { cid } });
|
|
679
784
|
return {
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
785
|
+
gateway,
|
|
786
|
+
healthy: true,
|
|
787
|
+
responseTimeMs: Date.now() - start
|
|
683
788
|
};
|
|
684
789
|
} catch (error) {
|
|
685
|
-
const errorMsg = error instanceof Error ? error.message : String(error);
|
|
686
|
-
this.emitEvent({ type: "storage:error", timestamp: Date.now(), error: errorMsg });
|
|
687
790
|
return {
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
791
|
+
gateway,
|
|
792
|
+
healthy: false,
|
|
793
|
+
error: error instanceof Error ? error.message : String(error)
|
|
691
794
|
};
|
|
692
795
|
}
|
|
693
796
|
}
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
797
|
+
/**
|
|
798
|
+
* Find healthy gateways from the configured list.
|
|
799
|
+
*/
|
|
800
|
+
async findHealthyGateways() {
|
|
801
|
+
const results = await Promise.allSettled(
|
|
802
|
+
this.gateways.map((gw) => this.testConnectivity(gw))
|
|
803
|
+
);
|
|
804
|
+
return results.filter((r) => r.status === "fulfilled" && r.value.healthy).map((r) => r.value.gateway);
|
|
805
|
+
}
|
|
806
|
+
/**
|
|
807
|
+
* Get gateways that are not in circuit breaker cooldown.
|
|
808
|
+
*/
|
|
809
|
+
getAvailableGateways() {
|
|
810
|
+
return this.gateways.filter((gw) => !this.cache.isGatewayInCooldown(gw));
|
|
811
|
+
}
|
|
812
|
+
// ---------------------------------------------------------------------------
|
|
813
|
+
// Content Upload
|
|
814
|
+
// ---------------------------------------------------------------------------
|
|
815
|
+
/**
|
|
816
|
+
* Upload JSON content to IPFS.
|
|
817
|
+
* Tries all gateways in parallel, returns first success.
|
|
818
|
+
*/
|
|
819
|
+
async upload(data, gateways) {
|
|
820
|
+
const targets = gateways ?? this.getAvailableGateways();
|
|
821
|
+
if (targets.length === 0) {
|
|
822
|
+
throw new IpfsError("No gateways available for upload", "NETWORK_ERROR");
|
|
823
|
+
}
|
|
824
|
+
const jsonBytes = new TextEncoder().encode(JSON.stringify(data));
|
|
825
|
+
const promises = targets.map(async (gateway) => {
|
|
826
|
+
try {
|
|
827
|
+
const formData = new FormData();
|
|
828
|
+
formData.append("file", new Blob([jsonBytes], { type: "application/json" }), "data.json");
|
|
829
|
+
const response = await this.fetchWithTimeout(
|
|
830
|
+
`${gateway}/api/v0/add?pin=true&cid-version=1`,
|
|
831
|
+
this.publishTimeoutMs,
|
|
832
|
+
{ method: "POST", body: formData }
|
|
833
|
+
);
|
|
834
|
+
if (!response.ok) {
|
|
835
|
+
throw new IpfsError(
|
|
836
|
+
`Upload failed: HTTP ${response.status}`,
|
|
837
|
+
classifyHttpStatus(response.status),
|
|
838
|
+
gateway
|
|
839
|
+
);
|
|
840
|
+
}
|
|
841
|
+
const result = await response.json();
|
|
842
|
+
this.cache.recordGatewaySuccess(gateway);
|
|
843
|
+
this.log(`Uploaded to ${gateway}: CID=${result.Hash}`);
|
|
844
|
+
return { cid: result.Hash, gateway };
|
|
845
|
+
} catch (error) {
|
|
846
|
+
if (error instanceof IpfsError && error.shouldTriggerCircuitBreaker) {
|
|
847
|
+
this.cache.recordGatewayFailure(gateway);
|
|
848
|
+
}
|
|
849
|
+
throw error;
|
|
707
850
|
}
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
851
|
+
});
|
|
852
|
+
try {
|
|
853
|
+
const result = await Promise.any(promises);
|
|
854
|
+
return { cid: result.cid };
|
|
855
|
+
} catch (error) {
|
|
856
|
+
if (error instanceof AggregateError) {
|
|
857
|
+
throw new IpfsError(
|
|
858
|
+
`Upload failed on all gateways: ${error.errors.map((e) => e.message).join("; ")}`,
|
|
859
|
+
"NETWORK_ERROR"
|
|
860
|
+
);
|
|
711
861
|
}
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
862
|
+
throw error;
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
// ---------------------------------------------------------------------------
|
|
866
|
+
// Content Fetch
|
|
867
|
+
// ---------------------------------------------------------------------------
|
|
868
|
+
/**
|
|
869
|
+
* Fetch content by CID from IPFS gateways.
|
|
870
|
+
* Checks content cache first. Races all gateways for fastest response.
|
|
871
|
+
*/
|
|
872
|
+
async fetchContent(cid, gateways) {
|
|
873
|
+
const cached = this.cache.getContent(cid);
|
|
874
|
+
if (cached) {
|
|
875
|
+
this.log(`Content cache hit for CID=${cid}`);
|
|
876
|
+
return cached;
|
|
877
|
+
}
|
|
878
|
+
const targets = gateways ?? this.getAvailableGateways();
|
|
879
|
+
if (targets.length === 0) {
|
|
880
|
+
throw new IpfsError("No gateways available for fetch", "NETWORK_ERROR");
|
|
881
|
+
}
|
|
882
|
+
const promises = targets.map(async (gateway) => {
|
|
883
|
+
try {
|
|
884
|
+
const response = await this.fetchWithTimeout(
|
|
885
|
+
`${gateway}/ipfs/${cid}`,
|
|
886
|
+
this.fetchTimeoutMs,
|
|
887
|
+
{ headers: { Accept: "application/octet-stream" } }
|
|
888
|
+
);
|
|
889
|
+
if (!response.ok) {
|
|
890
|
+
const body = await response.text().catch(() => "");
|
|
891
|
+
throw new IpfsError(
|
|
892
|
+
`Fetch failed: HTTP ${response.status}`,
|
|
893
|
+
classifyHttpStatus(response.status, body),
|
|
894
|
+
gateway
|
|
895
|
+
);
|
|
896
|
+
}
|
|
897
|
+
const data = await response.json();
|
|
898
|
+
this.cache.recordGatewaySuccess(gateway);
|
|
899
|
+
this.cache.setContent(cid, data);
|
|
900
|
+
this.log(`Fetched from ${gateway}: CID=${cid}`);
|
|
901
|
+
return data;
|
|
902
|
+
} catch (error) {
|
|
903
|
+
if (error instanceof IpfsError && error.shouldTriggerCircuitBreaker) {
|
|
904
|
+
this.cache.recordGatewayFailure(gateway);
|
|
905
|
+
}
|
|
906
|
+
throw error;
|
|
719
907
|
}
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
this.lastCid = cid;
|
|
724
|
-
this.emitEvent({ type: "storage:loaded", timestamp: Date.now() });
|
|
725
|
-
return {
|
|
726
|
-
success: true,
|
|
727
|
-
data,
|
|
728
|
-
source: "remote",
|
|
729
|
-
timestamp: Date.now()
|
|
730
|
-
};
|
|
908
|
+
});
|
|
909
|
+
try {
|
|
910
|
+
return await Promise.any(promises);
|
|
731
911
|
} catch (error) {
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
data: this.localCache,
|
|
738
|
-
source: "cache",
|
|
739
|
-
timestamp: Date.now()
|
|
740
|
-
};
|
|
912
|
+
if (error instanceof AggregateError) {
|
|
913
|
+
throw new IpfsError(
|
|
914
|
+
`Fetch failed on all gateways for CID=${cid}`,
|
|
915
|
+
"NETWORK_ERROR"
|
|
916
|
+
);
|
|
741
917
|
}
|
|
742
|
-
|
|
743
|
-
success: false,
|
|
744
|
-
error: errorMsg,
|
|
745
|
-
source: "remote",
|
|
746
|
-
timestamp: Date.now()
|
|
747
|
-
};
|
|
918
|
+
throw error;
|
|
748
919
|
}
|
|
749
920
|
}
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
921
|
+
// ---------------------------------------------------------------------------
|
|
922
|
+
// IPNS Resolution
|
|
923
|
+
// ---------------------------------------------------------------------------
|
|
924
|
+
/**
|
|
925
|
+
* Resolve IPNS via Routing API (returns record with sequence number).
|
|
926
|
+
* POST /api/v0/routing/get?arg=/ipns/{name}
|
|
927
|
+
*/
|
|
928
|
+
async resolveIpnsViaRoutingApi(gateway, ipnsName, timeoutMs = DEFAULT_ROUTING_API_TIMEOUT_MS) {
|
|
753
929
|
try {
|
|
754
|
-
const
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
conflicts: 0
|
|
765
|
-
};
|
|
930
|
+
const response = await this.fetchWithTimeout(
|
|
931
|
+
`${gateway}/api/v0/routing/get?arg=/ipns/${ipnsName}`,
|
|
932
|
+
timeoutMs,
|
|
933
|
+
{ method: "POST" }
|
|
934
|
+
);
|
|
935
|
+
if (!response.ok) {
|
|
936
|
+
const body = await response.text().catch(() => "");
|
|
937
|
+
const category = classifyHttpStatus(response.status, body);
|
|
938
|
+
if (category === "NOT_FOUND") return null;
|
|
939
|
+
throw new IpfsError(`Routing API: HTTP ${response.status}`, category, gateway);
|
|
766
940
|
}
|
|
767
|
-
const
|
|
768
|
-
await
|
|
769
|
-
|
|
941
|
+
const text = await response.text();
|
|
942
|
+
const parsed = await parseRoutingApiResponse(text);
|
|
943
|
+
if (!parsed) return null;
|
|
944
|
+
this.cache.recordGatewaySuccess(gateway);
|
|
770
945
|
return {
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
conflicts: mergeResult.conflicts
|
|
946
|
+
cid: parsed.cid,
|
|
947
|
+
sequence: parsed.sequence,
|
|
948
|
+
gateway,
|
|
949
|
+
recordData: parsed.recordData
|
|
776
950
|
};
|
|
777
951
|
} catch (error) {
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
conflicts: 0,
|
|
785
|
-
error: errorMsg
|
|
786
|
-
};
|
|
952
|
+
if (error instanceof IpfsError) throw error;
|
|
953
|
+
const category = classifyFetchError(error);
|
|
954
|
+
if (category !== "NOT_FOUND") {
|
|
955
|
+
this.cache.recordGatewayFailure(gateway);
|
|
956
|
+
}
|
|
957
|
+
return null;
|
|
787
958
|
}
|
|
788
959
|
}
|
|
789
|
-
|
|
790
|
-
|
|
960
|
+
/**
|
|
961
|
+
* Resolve IPNS via gateway path (simpler, no sequence number).
|
|
962
|
+
* GET /ipns/{name}?format=dag-json
|
|
963
|
+
*/
|
|
964
|
+
async resolveIpnsViaGatewayPath(gateway, ipnsName, timeoutMs = DEFAULT_GATEWAY_PATH_TIMEOUT_MS) {
|
|
791
965
|
try {
|
|
792
|
-
const
|
|
793
|
-
|
|
966
|
+
const response = await this.fetchWithTimeout(
|
|
967
|
+
`${gateway}/ipns/${ipnsName}`,
|
|
968
|
+
timeoutMs,
|
|
969
|
+
{ headers: { Accept: "application/json" } }
|
|
970
|
+
);
|
|
971
|
+
if (!response.ok) return null;
|
|
972
|
+
const content = await response.json();
|
|
973
|
+
const cidHeader = response.headers.get("X-Ipfs-Path");
|
|
974
|
+
if (cidHeader) {
|
|
975
|
+
const match = cidHeader.match(/\/ipfs\/([a-zA-Z0-9]+)/);
|
|
976
|
+
if (match) {
|
|
977
|
+
this.cache.recordGatewaySuccess(gateway);
|
|
978
|
+
return { cid: match[1], content };
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
return { cid: "", content };
|
|
794
982
|
} catch {
|
|
795
|
-
return
|
|
796
|
-
}
|
|
797
|
-
}
|
|
798
|
-
async clear() {
|
|
799
|
-
const emptyData = {
|
|
800
|
-
_meta: {
|
|
801
|
-
version: 0,
|
|
802
|
-
address: this.identity?.l1Address ?? "",
|
|
803
|
-
formatVersion: "2.0",
|
|
804
|
-
updatedAt: Date.now()
|
|
805
|
-
},
|
|
806
|
-
_tombstones: []
|
|
807
|
-
};
|
|
808
|
-
const result = await this.save(emptyData);
|
|
809
|
-
return result.success;
|
|
810
|
-
}
|
|
811
|
-
onEvent(callback) {
|
|
812
|
-
this.eventCallbacks.add(callback);
|
|
813
|
-
return () => this.eventCallbacks.delete(callback);
|
|
814
|
-
}
|
|
815
|
-
// ===========================================================================
|
|
816
|
-
// Private: IPFS Operations
|
|
817
|
-
// ===========================================================================
|
|
818
|
-
async testGatewayConnectivity() {
|
|
819
|
-
const gateway = this.config.gateways[0];
|
|
820
|
-
const controller = new AbortController();
|
|
821
|
-
const timeout = setTimeout(() => controller.abort(), 5e3);
|
|
822
|
-
try {
|
|
823
|
-
const response = await fetch(`${gateway}/api/v0/version`, {
|
|
824
|
-
method: "POST",
|
|
825
|
-
signal: controller.signal
|
|
826
|
-
});
|
|
827
|
-
if (!response.ok) throw new Error("Gateway not responding");
|
|
828
|
-
} finally {
|
|
829
|
-
clearTimeout(timeout);
|
|
983
|
+
return null;
|
|
830
984
|
}
|
|
831
985
|
}
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
986
|
+
/**
|
|
987
|
+
* Progressive IPNS resolution across all gateways.
|
|
988
|
+
* Queries all gateways in parallel, returns highest sequence number.
|
|
989
|
+
*/
|
|
990
|
+
async resolveIpns(ipnsName, gateways) {
|
|
991
|
+
const targets = gateways ?? this.getAvailableGateways();
|
|
992
|
+
if (targets.length === 0) {
|
|
993
|
+
return { best: null, allResults: [], respondedCount: 0, totalGateways: 0 };
|
|
838
994
|
}
|
|
839
|
-
|
|
840
|
-
|
|
995
|
+
const results = [];
|
|
996
|
+
let respondedCount = 0;
|
|
997
|
+
const promises = targets.map(async (gateway) => {
|
|
998
|
+
const result = await this.resolveIpnsViaRoutingApi(
|
|
999
|
+
gateway,
|
|
1000
|
+
ipnsName,
|
|
1001
|
+
this.resolveTimeoutMs
|
|
1002
|
+
);
|
|
1003
|
+
if (result) results.push(result);
|
|
1004
|
+
respondedCount++;
|
|
1005
|
+
return result;
|
|
1006
|
+
});
|
|
1007
|
+
await Promise.race([
|
|
1008
|
+
Promise.allSettled(promises),
|
|
1009
|
+
new Promise((resolve) => setTimeout(resolve, this.resolveTimeoutMs + 1e3))
|
|
1010
|
+
]);
|
|
1011
|
+
let best = null;
|
|
1012
|
+
for (const result of results) {
|
|
1013
|
+
if (!best || result.sequence > best.sequence) {
|
|
1014
|
+
best = result;
|
|
1015
|
+
}
|
|
841
1016
|
}
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
this.log("Published to IPFS, CID:", cid);
|
|
845
|
-
return cid;
|
|
846
|
-
} catch {
|
|
847
|
-
throw new Error("All publish attempts failed");
|
|
1017
|
+
if (best) {
|
|
1018
|
+
this.cache.setIpnsRecord(ipnsName, best);
|
|
848
1019
|
}
|
|
1020
|
+
return {
|
|
1021
|
+
best,
|
|
1022
|
+
allResults: results,
|
|
1023
|
+
respondedCount,
|
|
1024
|
+
totalGateways: targets.length
|
|
1025
|
+
};
|
|
849
1026
|
}
|
|
1027
|
+
// ---------------------------------------------------------------------------
|
|
1028
|
+
// IPNS Publishing
|
|
1029
|
+
// ---------------------------------------------------------------------------
|
|
850
1030
|
/**
|
|
851
|
-
* Publish
|
|
1031
|
+
* Publish IPNS record to a single gateway via routing API.
|
|
852
1032
|
*/
|
|
853
|
-
async
|
|
854
|
-
if (!this.heliaJson) {
|
|
855
|
-
throw new Error("Helia not initialized");
|
|
856
|
-
}
|
|
857
|
-
const cid = await this.heliaJson.add(data);
|
|
858
|
-
this.log("Published via Helia, CID:", cid.toString());
|
|
859
|
-
return cid.toString();
|
|
860
|
-
}
|
|
861
|
-
async publishToGateway(gateway, blob) {
|
|
862
|
-
const formData = new FormData();
|
|
863
|
-
formData.append("file", blob);
|
|
864
|
-
const controller = new AbortController();
|
|
865
|
-
const timeout = setTimeout(() => controller.abort(), this.config.fetchTimeout);
|
|
1033
|
+
async publishIpnsViaRoutingApi(gateway, ipnsName, marshalledRecord, timeoutMs = DEFAULT_PUBLISH_TIMEOUT_MS) {
|
|
866
1034
|
try {
|
|
867
|
-
const
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
1035
|
+
const formData = new FormData();
|
|
1036
|
+
formData.append(
|
|
1037
|
+
"file",
|
|
1038
|
+
new Blob([new Uint8Array(marshalledRecord)]),
|
|
1039
|
+
"record"
|
|
1040
|
+
);
|
|
1041
|
+
const response = await this.fetchWithTimeout(
|
|
1042
|
+
`${gateway}/api/v0/routing/put?arg=/ipns/${ipnsName}&allow-offline=true`,
|
|
1043
|
+
timeoutMs,
|
|
1044
|
+
{ method: "POST", body: formData }
|
|
1045
|
+
);
|
|
872
1046
|
if (!response.ok) {
|
|
873
|
-
|
|
1047
|
+
const errorText = await response.text().catch(() => "");
|
|
1048
|
+
throw new IpfsError(
|
|
1049
|
+
`IPNS publish: HTTP ${response.status}: ${errorText.slice(0, 100)}`,
|
|
1050
|
+
classifyHttpStatus(response.status, errorText),
|
|
1051
|
+
gateway
|
|
1052
|
+
);
|
|
874
1053
|
}
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
1054
|
+
this.cache.recordGatewaySuccess(gateway);
|
|
1055
|
+
this.log(`IPNS published to ${gateway}: ${ipnsName}`);
|
|
1056
|
+
return true;
|
|
1057
|
+
} catch (error) {
|
|
1058
|
+
if (error instanceof IpfsError && error.shouldTriggerCircuitBreaker) {
|
|
1059
|
+
this.cache.recordGatewayFailure(gateway);
|
|
1060
|
+
}
|
|
1061
|
+
this.log(`IPNS publish to ${gateway} failed: ${error}`);
|
|
1062
|
+
return false;
|
|
1063
|
+
}
|
|
880
1064
|
}
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
1065
|
+
/**
|
|
1066
|
+
* Publish IPNS record to all gateways in parallel.
|
|
1067
|
+
*/
|
|
1068
|
+
async publishIpns(ipnsName, marshalledRecord, gateways) {
|
|
1069
|
+
const targets = gateways ?? this.getAvailableGateways();
|
|
1070
|
+
if (targets.length === 0) {
|
|
1071
|
+
return { success: false, error: "No gateways available" };
|
|
1072
|
+
}
|
|
1073
|
+
const results = await Promise.allSettled(
|
|
1074
|
+
targets.map((gw) => this.publishIpnsViaRoutingApi(gw, ipnsName, marshalledRecord, this.publishTimeoutMs))
|
|
885
1075
|
);
|
|
886
|
-
|
|
887
|
-
|
|
1076
|
+
const successfulGateways = [];
|
|
1077
|
+
results.forEach((result, index) => {
|
|
1078
|
+
if (result.status === "fulfilled" && result.value) {
|
|
1079
|
+
successfulGateways.push(targets[index]);
|
|
1080
|
+
}
|
|
1081
|
+
});
|
|
1082
|
+
return {
|
|
1083
|
+
success: successfulGateways.length > 0,
|
|
1084
|
+
ipnsName,
|
|
1085
|
+
successfulGateways,
|
|
1086
|
+
error: successfulGateways.length === 0 ? "All gateways failed" : void 0
|
|
1087
|
+
};
|
|
1088
|
+
}
|
|
1089
|
+
// ---------------------------------------------------------------------------
|
|
1090
|
+
// IPNS Verification
|
|
1091
|
+
// ---------------------------------------------------------------------------
|
|
1092
|
+
/**
|
|
1093
|
+
* Verify IPNS record persistence after publishing.
|
|
1094
|
+
* Retries resolution to confirm the record was accepted.
|
|
1095
|
+
*/
|
|
1096
|
+
async verifyIpnsRecord(ipnsName, expectedSeq, expectedCid, retries = 3, delayMs = 1e3) {
|
|
1097
|
+
for (let i = 0; i < retries; i++) {
|
|
1098
|
+
if (i > 0) {
|
|
1099
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
1100
|
+
}
|
|
1101
|
+
const { best } = await this.resolveIpns(ipnsName);
|
|
1102
|
+
if (best && best.sequence >= expectedSeq && best.cid === expectedCid) {
|
|
1103
|
+
return true;
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
return false;
|
|
888
1107
|
}
|
|
889
|
-
|
|
1108
|
+
// ---------------------------------------------------------------------------
|
|
1109
|
+
// Helpers
|
|
1110
|
+
// ---------------------------------------------------------------------------
|
|
1111
|
+
async fetchWithTimeout(url, timeoutMs, options) {
|
|
890
1112
|
const controller = new AbortController();
|
|
891
|
-
const
|
|
1113
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
892
1114
|
try {
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
1115
|
+
return await fetch(url, {
|
|
1116
|
+
...options,
|
|
1117
|
+
signal: controller.signal
|
|
1118
|
+
});
|
|
1119
|
+
} finally {
|
|
1120
|
+
clearTimeout(timer);
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
log(message) {
|
|
1124
|
+
if (this.debug) {
|
|
1125
|
+
console.log(`[IPFS-HTTP] ${message}`);
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
};
|
|
1129
|
+
|
|
1130
|
+
// impl/shared/ipfs/txf-merge.ts
|
|
1131
|
+
function mergeTxfData(local, remote) {
|
|
1132
|
+
let added = 0;
|
|
1133
|
+
let removed = 0;
|
|
1134
|
+
let conflicts = 0;
|
|
1135
|
+
const localVersion = local._meta?.version ?? 0;
|
|
1136
|
+
const remoteVersion = remote._meta?.version ?? 0;
|
|
1137
|
+
const baseMeta = localVersion >= remoteVersion ? local._meta : remote._meta;
|
|
1138
|
+
const mergedMeta = {
|
|
1139
|
+
...baseMeta,
|
|
1140
|
+
version: Math.max(localVersion, remoteVersion) + 1,
|
|
1141
|
+
updatedAt: Date.now()
|
|
1142
|
+
};
|
|
1143
|
+
const mergedTombstones = mergeTombstones(
|
|
1144
|
+
local._tombstones ?? [],
|
|
1145
|
+
remote._tombstones ?? []
|
|
1146
|
+
);
|
|
1147
|
+
const tombstoneKeys = new Set(
|
|
1148
|
+
mergedTombstones.map((t) => `${t.tokenId}:${t.stateHash}`)
|
|
1149
|
+
);
|
|
1150
|
+
const localTokenKeys = getTokenKeys(local);
|
|
1151
|
+
const remoteTokenKeys = getTokenKeys(remote);
|
|
1152
|
+
const allTokenKeys = /* @__PURE__ */ new Set([...localTokenKeys, ...remoteTokenKeys]);
|
|
1153
|
+
const mergedTokens = {};
|
|
1154
|
+
for (const key of allTokenKeys) {
|
|
1155
|
+
const tokenId = key.startsWith("_") ? key.slice(1) : key;
|
|
1156
|
+
const localToken = local[key];
|
|
1157
|
+
const remoteToken = remote[key];
|
|
1158
|
+
if (isTokenTombstoned(tokenId, localToken, remoteToken, tombstoneKeys)) {
|
|
1159
|
+
if (localTokenKeys.has(key)) removed++;
|
|
1160
|
+
continue;
|
|
1161
|
+
}
|
|
1162
|
+
if (localToken && !remoteToken) {
|
|
1163
|
+
mergedTokens[key] = localToken;
|
|
1164
|
+
} else if (!localToken && remoteToken) {
|
|
1165
|
+
mergedTokens[key] = remoteToken;
|
|
1166
|
+
added++;
|
|
1167
|
+
} else if (localToken && remoteToken) {
|
|
1168
|
+
mergedTokens[key] = localToken;
|
|
1169
|
+
conflicts++;
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
const mergedOutbox = mergeArrayById(
|
|
1173
|
+
local._outbox ?? [],
|
|
1174
|
+
remote._outbox ?? [],
|
|
1175
|
+
"id"
|
|
1176
|
+
);
|
|
1177
|
+
const mergedSent = mergeArrayById(
|
|
1178
|
+
local._sent ?? [],
|
|
1179
|
+
remote._sent ?? [],
|
|
1180
|
+
"tokenId"
|
|
1181
|
+
);
|
|
1182
|
+
const mergedInvalid = mergeArrayById(
|
|
1183
|
+
local._invalid ?? [],
|
|
1184
|
+
remote._invalid ?? [],
|
|
1185
|
+
"tokenId"
|
|
1186
|
+
);
|
|
1187
|
+
const localNametags = local._nametags ?? [];
|
|
1188
|
+
const remoteNametags = remote._nametags ?? [];
|
|
1189
|
+
const mergedNametags = mergeNametagsByName(localNametags, remoteNametags);
|
|
1190
|
+
const merged = {
|
|
1191
|
+
_meta: mergedMeta,
|
|
1192
|
+
_tombstones: mergedTombstones.length > 0 ? mergedTombstones : void 0,
|
|
1193
|
+
_nametags: mergedNametags.length > 0 ? mergedNametags : void 0,
|
|
1194
|
+
_outbox: mergedOutbox.length > 0 ? mergedOutbox : void 0,
|
|
1195
|
+
_sent: mergedSent.length > 0 ? mergedSent : void 0,
|
|
1196
|
+
_invalid: mergedInvalid.length > 0 ? mergedInvalid : void 0,
|
|
1197
|
+
...mergedTokens
|
|
1198
|
+
};
|
|
1199
|
+
return { merged, added, removed, conflicts };
|
|
1200
|
+
}
|
|
1201
|
+
function mergeTombstones(local, remote) {
|
|
1202
|
+
const merged = /* @__PURE__ */ new Map();
|
|
1203
|
+
for (const tombstone of [...local, ...remote]) {
|
|
1204
|
+
const key = `${tombstone.tokenId}:${tombstone.stateHash}`;
|
|
1205
|
+
const existing = merged.get(key);
|
|
1206
|
+
if (!existing || tombstone.timestamp > existing.timestamp) {
|
|
1207
|
+
merged.set(key, tombstone);
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
return Array.from(merged.values());
|
|
1211
|
+
}
|
|
1212
|
+
function getTokenKeys(data) {
|
|
1213
|
+
const reservedKeys = /* @__PURE__ */ new Set([
|
|
1214
|
+
"_meta",
|
|
1215
|
+
"_tombstones",
|
|
1216
|
+
"_outbox",
|
|
1217
|
+
"_sent",
|
|
1218
|
+
"_invalid",
|
|
1219
|
+
"_nametag",
|
|
1220
|
+
"_nametags",
|
|
1221
|
+
"_mintOutbox",
|
|
1222
|
+
"_invalidatedNametags",
|
|
1223
|
+
"_integrity"
|
|
1224
|
+
]);
|
|
1225
|
+
const keys = /* @__PURE__ */ new Set();
|
|
1226
|
+
for (const key of Object.keys(data)) {
|
|
1227
|
+
if (reservedKeys.has(key)) continue;
|
|
1228
|
+
if (key.startsWith("archived-") || key.startsWith("_forked_")) continue;
|
|
1229
|
+
keys.add(key);
|
|
1230
|
+
}
|
|
1231
|
+
return keys;
|
|
1232
|
+
}
|
|
1233
|
+
function isTokenTombstoned(tokenId, localToken, remoteToken, tombstoneKeys) {
|
|
1234
|
+
for (const key of tombstoneKeys) {
|
|
1235
|
+
if (key.startsWith(`${tokenId}:`)) {
|
|
1236
|
+
return true;
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
void localToken;
|
|
1240
|
+
void remoteToken;
|
|
1241
|
+
return false;
|
|
1242
|
+
}
|
|
1243
|
+
function mergeNametagsByName(local, remote) {
|
|
1244
|
+
const seen = /* @__PURE__ */ new Map();
|
|
1245
|
+
for (const item of local) {
|
|
1246
|
+
if (item.name) seen.set(item.name, item);
|
|
1247
|
+
}
|
|
1248
|
+
for (const item of remote) {
|
|
1249
|
+
if (item.name && !seen.has(item.name)) {
|
|
1250
|
+
seen.set(item.name, item);
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
return Array.from(seen.values());
|
|
1254
|
+
}
|
|
1255
|
+
function mergeArrayById(local, remote, idField) {
|
|
1256
|
+
const seen = /* @__PURE__ */ new Map();
|
|
1257
|
+
for (const item of local) {
|
|
1258
|
+
const id = item[idField];
|
|
1259
|
+
if (id !== void 0) {
|
|
1260
|
+
seen.set(id, item);
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
for (const item of remote) {
|
|
1264
|
+
const id = item[idField];
|
|
1265
|
+
if (id !== void 0 && !seen.has(id)) {
|
|
1266
|
+
seen.set(id, item);
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
return Array.from(seen.values());
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
// transport/websocket.ts
|
|
1273
|
+
var WebSocketReadyState = {
|
|
1274
|
+
CONNECTING: 0,
|
|
1275
|
+
OPEN: 1,
|
|
1276
|
+
CLOSING: 2,
|
|
1277
|
+
CLOSED: 3
|
|
1278
|
+
};
|
|
1279
|
+
|
|
1280
|
+
// impl/shared/ipfs/ipns-subscription-client.ts
|
|
1281
|
+
var IpnsSubscriptionClient = class {
|
|
1282
|
+
ws = null;
|
|
1283
|
+
subscriptions = /* @__PURE__ */ new Map();
|
|
1284
|
+
reconnectTimeout = null;
|
|
1285
|
+
pingInterval = null;
|
|
1286
|
+
fallbackPollInterval = null;
|
|
1287
|
+
wsUrl;
|
|
1288
|
+
createWebSocket;
|
|
1289
|
+
pingIntervalMs;
|
|
1290
|
+
initialReconnectDelayMs;
|
|
1291
|
+
maxReconnectDelayMs;
|
|
1292
|
+
debugEnabled;
|
|
1293
|
+
reconnectAttempts = 0;
|
|
1294
|
+
isConnecting = false;
|
|
1295
|
+
connectionOpenedAt = 0;
|
|
1296
|
+
destroyed = false;
|
|
1297
|
+
/** Minimum stable connection time before resetting backoff (30 seconds) */
|
|
1298
|
+
minStableConnectionMs = 3e4;
|
|
1299
|
+
fallbackPollFn = null;
|
|
1300
|
+
fallbackPollIntervalMs = 0;
|
|
1301
|
+
constructor(config) {
|
|
1302
|
+
this.wsUrl = config.wsUrl;
|
|
1303
|
+
this.createWebSocket = config.createWebSocket;
|
|
1304
|
+
this.pingIntervalMs = config.pingIntervalMs ?? 3e4;
|
|
1305
|
+
this.initialReconnectDelayMs = config.reconnectDelayMs ?? 5e3;
|
|
1306
|
+
this.maxReconnectDelayMs = config.maxReconnectDelayMs ?? 6e4;
|
|
1307
|
+
this.debugEnabled = config.debug ?? false;
|
|
1308
|
+
}
|
|
1309
|
+
// ---------------------------------------------------------------------------
|
|
1310
|
+
// Public API
|
|
1311
|
+
// ---------------------------------------------------------------------------
|
|
1312
|
+
/**
|
|
1313
|
+
* Subscribe to IPNS updates for a specific name.
|
|
1314
|
+
* Automatically connects the WebSocket if not already connected.
|
|
1315
|
+
* If WebSocket is connecting, the name will be subscribed once connected.
|
|
1316
|
+
*/
|
|
1317
|
+
subscribe(ipnsName, callback) {
|
|
1318
|
+
if (!ipnsName || typeof ipnsName !== "string") {
|
|
1319
|
+
this.log("Invalid IPNS name for subscription");
|
|
1320
|
+
return () => {
|
|
1321
|
+
};
|
|
1322
|
+
}
|
|
1323
|
+
const isNewSubscription = !this.subscriptions.has(ipnsName);
|
|
1324
|
+
if (isNewSubscription) {
|
|
1325
|
+
this.subscriptions.set(ipnsName, /* @__PURE__ */ new Set());
|
|
1326
|
+
}
|
|
1327
|
+
this.subscriptions.get(ipnsName).add(callback);
|
|
1328
|
+
if (isNewSubscription && this.ws?.readyState === WebSocketReadyState.OPEN) {
|
|
1329
|
+
this.sendSubscribe([ipnsName]);
|
|
1330
|
+
}
|
|
1331
|
+
if (!this.ws || this.ws.readyState !== WebSocketReadyState.OPEN) {
|
|
1332
|
+
this.connect();
|
|
1333
|
+
}
|
|
1334
|
+
return () => {
|
|
1335
|
+
const callbacks = this.subscriptions.get(ipnsName);
|
|
1336
|
+
if (callbacks) {
|
|
1337
|
+
callbacks.delete(callback);
|
|
1338
|
+
if (callbacks.size === 0) {
|
|
1339
|
+
this.subscriptions.delete(ipnsName);
|
|
1340
|
+
if (this.ws?.readyState === WebSocketReadyState.OPEN) {
|
|
1341
|
+
this.sendUnsubscribe([ipnsName]);
|
|
1342
|
+
}
|
|
1343
|
+
if (this.subscriptions.size === 0) {
|
|
1344
|
+
this.disconnect();
|
|
1345
|
+
}
|
|
898
1346
|
}
|
|
899
|
-
);
|
|
900
|
-
if (!response.ok) {
|
|
901
|
-
throw new Error(`IPNS publish failed: ${response.status}`);
|
|
902
1347
|
}
|
|
903
|
-
}
|
|
904
|
-
|
|
1348
|
+
};
|
|
1349
|
+
}
|
|
1350
|
+
/**
|
|
1351
|
+
* Register a convenience update callback for all subscriptions.
|
|
1352
|
+
* Returns an unsubscribe function.
|
|
1353
|
+
*/
|
|
1354
|
+
onUpdate(callback) {
|
|
1355
|
+
if (!this.subscriptions.has("*")) {
|
|
1356
|
+
this.subscriptions.set("*", /* @__PURE__ */ new Set());
|
|
905
1357
|
}
|
|
1358
|
+
this.subscriptions.get("*").add(callback);
|
|
1359
|
+
return () => {
|
|
1360
|
+
const callbacks = this.subscriptions.get("*");
|
|
1361
|
+
if (callbacks) {
|
|
1362
|
+
callbacks.delete(callback);
|
|
1363
|
+
if (callbacks.size === 0) {
|
|
1364
|
+
this.subscriptions.delete("*");
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
};
|
|
906
1368
|
}
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
1369
|
+
/**
|
|
1370
|
+
* Set a fallback poll function to use when WebSocket is disconnected.
|
|
1371
|
+
* The poll function will be called at the specified interval while WS is down.
|
|
1372
|
+
*/
|
|
1373
|
+
setFallbackPoll(fn, intervalMs) {
|
|
1374
|
+
this.fallbackPollFn = fn;
|
|
1375
|
+
this.fallbackPollIntervalMs = intervalMs;
|
|
1376
|
+
if (!this.isConnected()) {
|
|
1377
|
+
this.startFallbackPolling();
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
/**
|
|
1381
|
+
* Connect to the WebSocket server.
|
|
1382
|
+
*/
|
|
1383
|
+
connect() {
|
|
1384
|
+
if (this.destroyed) return;
|
|
1385
|
+
if (this.ws?.readyState === WebSocketReadyState.OPEN || this.isConnecting) {
|
|
1386
|
+
return;
|
|
1387
|
+
}
|
|
1388
|
+
this.isConnecting = true;
|
|
1389
|
+
try {
|
|
1390
|
+
this.log(`Connecting to ${this.wsUrl}...`);
|
|
1391
|
+
this.ws = this.createWebSocket(this.wsUrl);
|
|
1392
|
+
this.ws.onopen = () => {
|
|
1393
|
+
this.log("WebSocket connected");
|
|
1394
|
+
this.isConnecting = false;
|
|
1395
|
+
this.connectionOpenedAt = Date.now();
|
|
1396
|
+
const names = Array.from(this.subscriptions.keys()).filter((n) => n !== "*");
|
|
1397
|
+
if (names.length > 0) {
|
|
1398
|
+
this.sendSubscribe(names);
|
|
1399
|
+
}
|
|
1400
|
+
this.startPingInterval();
|
|
1401
|
+
this.stopFallbackPolling();
|
|
1402
|
+
};
|
|
1403
|
+
this.ws.onmessage = (event) => {
|
|
1404
|
+
this.handleMessage(event.data);
|
|
1405
|
+
};
|
|
1406
|
+
this.ws.onclose = () => {
|
|
1407
|
+
const connectionDuration = this.connectionOpenedAt > 0 ? Date.now() - this.connectionOpenedAt : 0;
|
|
1408
|
+
const wasStable = connectionDuration >= this.minStableConnectionMs;
|
|
1409
|
+
this.log(`WebSocket closed (duration: ${Math.round(connectionDuration / 1e3)}s)`);
|
|
1410
|
+
this.isConnecting = false;
|
|
1411
|
+
this.connectionOpenedAt = 0;
|
|
1412
|
+
this.stopPingInterval();
|
|
1413
|
+
if (wasStable) {
|
|
1414
|
+
this.reconnectAttempts = 0;
|
|
1415
|
+
}
|
|
1416
|
+
this.startFallbackPolling();
|
|
1417
|
+
this.scheduleReconnect();
|
|
1418
|
+
};
|
|
1419
|
+
this.ws.onerror = () => {
|
|
1420
|
+
this.log("WebSocket error");
|
|
1421
|
+
this.isConnecting = false;
|
|
1422
|
+
};
|
|
1423
|
+
} catch (e) {
|
|
1424
|
+
this.log(`Failed to connect: ${e}`);
|
|
1425
|
+
this.isConnecting = false;
|
|
1426
|
+
this.startFallbackPolling();
|
|
1427
|
+
this.scheduleReconnect();
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
1430
|
+
/**
|
|
1431
|
+
* Disconnect from the WebSocket server and clean up.
|
|
1432
|
+
*/
|
|
1433
|
+
disconnect() {
|
|
1434
|
+
this.destroyed = true;
|
|
1435
|
+
if (this.reconnectTimeout) {
|
|
1436
|
+
clearTimeout(this.reconnectTimeout);
|
|
1437
|
+
this.reconnectTimeout = null;
|
|
1438
|
+
}
|
|
1439
|
+
this.stopPingInterval();
|
|
1440
|
+
this.stopFallbackPolling();
|
|
1441
|
+
if (this.ws) {
|
|
1442
|
+
this.ws.onopen = null;
|
|
1443
|
+
this.ws.onclose = null;
|
|
1444
|
+
this.ws.onerror = null;
|
|
1445
|
+
this.ws.onmessage = null;
|
|
1446
|
+
this.ws.close();
|
|
1447
|
+
this.ws = null;
|
|
1448
|
+
}
|
|
1449
|
+
this.isConnecting = false;
|
|
1450
|
+
this.reconnectAttempts = 0;
|
|
1451
|
+
}
|
|
1452
|
+
/**
|
|
1453
|
+
* Check if connected to the WebSocket server.
|
|
1454
|
+
*/
|
|
1455
|
+
isConnected() {
|
|
1456
|
+
return this.ws?.readyState === WebSocketReadyState.OPEN;
|
|
1457
|
+
}
|
|
1458
|
+
// ---------------------------------------------------------------------------
|
|
1459
|
+
// Internal: Message Handling
|
|
1460
|
+
// ---------------------------------------------------------------------------
|
|
1461
|
+
handleMessage(data) {
|
|
1462
|
+
try {
|
|
1463
|
+
const message = JSON.parse(data);
|
|
1464
|
+
switch (message.type) {
|
|
1465
|
+
case "update":
|
|
1466
|
+
if (message.name && message.sequence !== void 0) {
|
|
1467
|
+
this.notifySubscribers({
|
|
1468
|
+
type: "update",
|
|
1469
|
+
name: message.name,
|
|
1470
|
+
sequence: message.sequence,
|
|
1471
|
+
cid: message.cid ?? "",
|
|
1472
|
+
timestamp: message.timestamp || (/* @__PURE__ */ new Date()).toISOString()
|
|
1473
|
+
});
|
|
1474
|
+
}
|
|
1475
|
+
break;
|
|
1476
|
+
case "subscribed":
|
|
1477
|
+
this.log(`Subscribed to ${message.names?.length || 0} names`);
|
|
1478
|
+
break;
|
|
1479
|
+
case "unsubscribed":
|
|
1480
|
+
this.log(`Unsubscribed from ${message.names?.length || 0} names`);
|
|
1481
|
+
break;
|
|
1482
|
+
case "pong":
|
|
1483
|
+
break;
|
|
1484
|
+
case "error":
|
|
1485
|
+
this.log(`Server error: ${message.message}`);
|
|
1486
|
+
break;
|
|
1487
|
+
default:
|
|
1488
|
+
break;
|
|
913
1489
|
}
|
|
1490
|
+
} catch {
|
|
1491
|
+
this.log("Failed to parse message");
|
|
914
1492
|
}
|
|
915
|
-
return null;
|
|
916
1493
|
}
|
|
917
|
-
|
|
918
|
-
const
|
|
919
|
-
|
|
1494
|
+
notifySubscribers(update) {
|
|
1495
|
+
const callbacks = this.subscriptions.get(update.name);
|
|
1496
|
+
if (callbacks) {
|
|
1497
|
+
this.log(`Update: ${update.name.slice(0, 16)}... seq=${update.sequence}`);
|
|
1498
|
+
for (const callback of callbacks) {
|
|
1499
|
+
try {
|
|
1500
|
+
callback(update);
|
|
1501
|
+
} catch {
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
const globalCallbacks = this.subscriptions.get("*");
|
|
1506
|
+
if (globalCallbacks) {
|
|
1507
|
+
for (const callback of globalCallbacks) {
|
|
1508
|
+
try {
|
|
1509
|
+
callback(update);
|
|
1510
|
+
} catch {
|
|
1511
|
+
}
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
// ---------------------------------------------------------------------------
|
|
1516
|
+
// Internal: WebSocket Send
|
|
1517
|
+
// ---------------------------------------------------------------------------
|
|
1518
|
+
sendSubscribe(names) {
|
|
1519
|
+
if (this.ws?.readyState === WebSocketReadyState.OPEN) {
|
|
1520
|
+
this.ws.send(JSON.stringify({ action: "subscribe", names }));
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
sendUnsubscribe(names) {
|
|
1524
|
+
if (this.ws?.readyState === WebSocketReadyState.OPEN) {
|
|
1525
|
+
this.ws.send(JSON.stringify({ action: "unsubscribe", names }));
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
// ---------------------------------------------------------------------------
|
|
1529
|
+
// Internal: Reconnection
|
|
1530
|
+
// ---------------------------------------------------------------------------
|
|
1531
|
+
/**
|
|
1532
|
+
* Schedule reconnection with exponential backoff.
|
|
1533
|
+
* Sequence: 5s, 10s, 20s, 40s, 60s (capped)
|
|
1534
|
+
*/
|
|
1535
|
+
scheduleReconnect() {
|
|
1536
|
+
if (this.destroyed || this.reconnectTimeout) return;
|
|
1537
|
+
const realSubscriptions = Array.from(this.subscriptions.keys()).filter((n) => n !== "*");
|
|
1538
|
+
if (realSubscriptions.length === 0) return;
|
|
1539
|
+
this.reconnectAttempts++;
|
|
1540
|
+
const delay = Math.min(
|
|
1541
|
+
this.initialReconnectDelayMs * Math.pow(2, this.reconnectAttempts - 1),
|
|
1542
|
+
this.maxReconnectDelayMs
|
|
1543
|
+
);
|
|
1544
|
+
this.log(`Reconnecting in ${(delay / 1e3).toFixed(1)}s (attempt ${this.reconnectAttempts})...`);
|
|
1545
|
+
this.reconnectTimeout = setTimeout(() => {
|
|
1546
|
+
this.reconnectTimeout = null;
|
|
1547
|
+
this.connect();
|
|
1548
|
+
}, delay);
|
|
1549
|
+
}
|
|
1550
|
+
// ---------------------------------------------------------------------------
|
|
1551
|
+
// Internal: Keepalive
|
|
1552
|
+
// ---------------------------------------------------------------------------
|
|
1553
|
+
startPingInterval() {
|
|
1554
|
+
this.stopPingInterval();
|
|
1555
|
+
this.pingInterval = setInterval(() => {
|
|
1556
|
+
if (this.ws?.readyState === WebSocketReadyState.OPEN) {
|
|
1557
|
+
this.ws.send(JSON.stringify({ action: "ping" }));
|
|
1558
|
+
}
|
|
1559
|
+
}, this.pingIntervalMs);
|
|
1560
|
+
}
|
|
1561
|
+
stopPingInterval() {
|
|
1562
|
+
if (this.pingInterval) {
|
|
1563
|
+
clearInterval(this.pingInterval);
|
|
1564
|
+
this.pingInterval = null;
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1567
|
+
// ---------------------------------------------------------------------------
|
|
1568
|
+
// Internal: Fallback Polling
|
|
1569
|
+
// ---------------------------------------------------------------------------
|
|
1570
|
+
startFallbackPolling() {
|
|
1571
|
+
if (this.fallbackPollInterval || !this.fallbackPollFn || this.destroyed) return;
|
|
1572
|
+
this.log(`Starting fallback polling (${this.fallbackPollIntervalMs / 1e3}s interval)`);
|
|
1573
|
+
this.fallbackPollFn().catch(() => {
|
|
1574
|
+
});
|
|
1575
|
+
this.fallbackPollInterval = setInterval(() => {
|
|
1576
|
+
this.fallbackPollFn?.().catch(() => {
|
|
1577
|
+
});
|
|
1578
|
+
}, this.fallbackPollIntervalMs);
|
|
1579
|
+
}
|
|
1580
|
+
stopFallbackPolling() {
|
|
1581
|
+
if (this.fallbackPollInterval) {
|
|
1582
|
+
clearInterval(this.fallbackPollInterval);
|
|
1583
|
+
this.fallbackPollInterval = null;
|
|
1584
|
+
}
|
|
1585
|
+
}
|
|
1586
|
+
// ---------------------------------------------------------------------------
|
|
1587
|
+
// Internal: Logging
|
|
1588
|
+
// ---------------------------------------------------------------------------
|
|
1589
|
+
log(message) {
|
|
1590
|
+
if (this.debugEnabled) {
|
|
1591
|
+
console.log(`[IPNS-WS] ${message}`);
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
};
|
|
1595
|
+
|
|
1596
|
+
// impl/shared/ipfs/write-behind-buffer.ts
|
|
1597
|
+
var AsyncSerialQueue = class {
|
|
1598
|
+
tail = Promise.resolve();
|
|
1599
|
+
/** Enqueue an async operation. Returns when it completes. */
|
|
1600
|
+
enqueue(fn) {
|
|
1601
|
+
let resolve;
|
|
1602
|
+
let reject;
|
|
1603
|
+
const promise = new Promise((res, rej) => {
|
|
1604
|
+
resolve = res;
|
|
1605
|
+
reject = rej;
|
|
1606
|
+
});
|
|
1607
|
+
this.tail = this.tail.then(
|
|
1608
|
+
() => fn().then(resolve, reject),
|
|
1609
|
+
() => fn().then(resolve, reject)
|
|
1610
|
+
);
|
|
1611
|
+
return promise;
|
|
1612
|
+
}
|
|
1613
|
+
};
|
|
1614
|
+
var WriteBuffer = class {
|
|
1615
|
+
/** Full TXF data from save() calls — latest wins */
|
|
1616
|
+
txfData = null;
|
|
1617
|
+
get isEmpty() {
|
|
1618
|
+
return this.txfData === null;
|
|
1619
|
+
}
|
|
1620
|
+
clear() {
|
|
1621
|
+
this.txfData = null;
|
|
1622
|
+
}
|
|
1623
|
+
/**
|
|
1624
|
+
* Merge another buffer's contents into this one (for rollback).
|
|
1625
|
+
* Existing (newer) mutations in `this` take precedence over `other`.
|
|
1626
|
+
*/
|
|
1627
|
+
mergeFrom(other) {
|
|
1628
|
+
if (other.txfData && !this.txfData) {
|
|
1629
|
+
this.txfData = other.txfData;
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
};
|
|
1633
|
+
|
|
1634
|
+
// constants.ts
|
|
1635
|
+
var STORAGE_KEYS_GLOBAL = {
|
|
1636
|
+
/** Encrypted BIP39 mnemonic */
|
|
1637
|
+
MNEMONIC: "mnemonic",
|
|
1638
|
+
/** Encrypted master private key */
|
|
1639
|
+
MASTER_KEY: "master_key",
|
|
1640
|
+
/** BIP32 chain code */
|
|
1641
|
+
CHAIN_CODE: "chain_code",
|
|
1642
|
+
/** HD derivation path (full path like m/44'/0'/0'/0/0) */
|
|
1643
|
+
DERIVATION_PATH: "derivation_path",
|
|
1644
|
+
/** Base derivation path (like m/44'/0'/0' without chain/index) */
|
|
1645
|
+
BASE_PATH: "base_path",
|
|
1646
|
+
/** Derivation mode: bip32, wif_hmac, legacy_hmac */
|
|
1647
|
+
DERIVATION_MODE: "derivation_mode",
|
|
1648
|
+
/** Wallet source: mnemonic, file, unknown */
|
|
1649
|
+
WALLET_SOURCE: "wallet_source",
|
|
1650
|
+
/** Wallet existence flag */
|
|
1651
|
+
WALLET_EXISTS: "wallet_exists",
|
|
1652
|
+
/** Current active address index */
|
|
1653
|
+
CURRENT_ADDRESS_INDEX: "current_address_index",
|
|
1654
|
+
/** Nametag cache per address (separate from tracked addresses registry) */
|
|
1655
|
+
ADDRESS_NAMETAGS: "address_nametags",
|
|
1656
|
+
/** Active addresses registry (JSON: TrackedAddressesStorage) */
|
|
1657
|
+
TRACKED_ADDRESSES: "tracked_addresses",
|
|
1658
|
+
/** Last processed Nostr wallet event timestamp (unix seconds), keyed per pubkey */
|
|
1659
|
+
LAST_WALLET_EVENT_TS: "last_wallet_event_ts",
|
|
1660
|
+
/** Group chat: joined groups */
|
|
1661
|
+
GROUP_CHAT_GROUPS: "group_chat_groups",
|
|
1662
|
+
/** Group chat: messages */
|
|
1663
|
+
GROUP_CHAT_MESSAGES: "group_chat_messages",
|
|
1664
|
+
/** Group chat: members */
|
|
1665
|
+
GROUP_CHAT_MEMBERS: "group_chat_members",
|
|
1666
|
+
/** Group chat: processed event IDs for deduplication */
|
|
1667
|
+
GROUP_CHAT_PROCESSED_EVENTS: "group_chat_processed_events",
|
|
1668
|
+
/** Group chat: last used relay URL (stale data detection) */
|
|
1669
|
+
GROUP_CHAT_RELAY_URL: "group_chat_relay_url"
|
|
1670
|
+
};
|
|
1671
|
+
var STORAGE_KEYS_ADDRESS = {
|
|
1672
|
+
/** Pending transfers for this address */
|
|
1673
|
+
PENDING_TRANSFERS: "pending_transfers",
|
|
1674
|
+
/** Transfer outbox for this address */
|
|
1675
|
+
OUTBOX: "outbox",
|
|
1676
|
+
/** Conversations for this address */
|
|
1677
|
+
CONVERSATIONS: "conversations",
|
|
1678
|
+
/** Messages for this address */
|
|
1679
|
+
MESSAGES: "messages",
|
|
1680
|
+
/** Transaction history for this address */
|
|
1681
|
+
TRANSACTION_HISTORY: "transaction_history",
|
|
1682
|
+
/** Pending V5 finalization tokens (unconfirmed instant split tokens) */
|
|
1683
|
+
PENDING_V5_TOKENS: "pending_v5_tokens"
|
|
1684
|
+
};
|
|
1685
|
+
var STORAGE_KEYS = {
|
|
1686
|
+
...STORAGE_KEYS_GLOBAL,
|
|
1687
|
+
...STORAGE_KEYS_ADDRESS
|
|
1688
|
+
};
|
|
1689
|
+
var UNICITY_IPFS_NODES = [
|
|
1690
|
+
{
|
|
1691
|
+
host: "unicity-ipfs1.dyndns.org",
|
|
1692
|
+
peerId: "12D3KooWDKJqEMAhH4nsSSiKtK1VLcas5coUqSPZAfbWbZpxtL4u",
|
|
1693
|
+
httpPort: 9080,
|
|
1694
|
+
httpsPort: 443
|
|
1695
|
+
}
|
|
1696
|
+
];
|
|
1697
|
+
function getIpfsGatewayUrls(isSecure) {
|
|
1698
|
+
return UNICITY_IPFS_NODES.map(
|
|
1699
|
+
(node) => isSecure !== false ? `https://${node.host}` : `http://${node.host}:${node.httpPort}`
|
|
1700
|
+
);
|
|
1701
|
+
}
|
|
1702
|
+
var DEFAULT_BASE_PATH = "m/44'/0'/0'";
|
|
1703
|
+
var DEFAULT_DERIVATION_PATH = `${DEFAULT_BASE_PATH}/0/0`;
|
|
1704
|
+
|
|
1705
|
+
// impl/shared/ipfs/ipfs-storage-provider.ts
|
|
1706
|
+
var IpfsStorageProvider = class {
|
|
1707
|
+
id = "ipfs";
|
|
1708
|
+
name = "IPFS Storage";
|
|
1709
|
+
type = "p2p";
|
|
1710
|
+
status = "disconnected";
|
|
1711
|
+
identity = null;
|
|
1712
|
+
ipnsKeyPair = null;
|
|
1713
|
+
ipnsName = null;
|
|
1714
|
+
ipnsSequenceNumber = 0n;
|
|
1715
|
+
lastCid = null;
|
|
1716
|
+
lastKnownRemoteSequence = 0n;
|
|
1717
|
+
dataVersion = 0;
|
|
1718
|
+
/**
|
|
1719
|
+
* The CID currently stored on the sidecar for this IPNS name.
|
|
1720
|
+
* Used as `_meta.lastCid` in the next save to satisfy chain validation.
|
|
1721
|
+
* - null for bootstrap (first-ever save)
|
|
1722
|
+
* - set after every successful save() or load()
|
|
1723
|
+
*/
|
|
1724
|
+
remoteCid = null;
|
|
1725
|
+
cache;
|
|
1726
|
+
httpClient;
|
|
1727
|
+
statePersistence;
|
|
1728
|
+
eventCallbacks = /* @__PURE__ */ new Set();
|
|
1729
|
+
debug;
|
|
1730
|
+
ipnsLifetimeMs;
|
|
1731
|
+
/** WebSocket factory for push subscriptions */
|
|
1732
|
+
createWebSocket;
|
|
1733
|
+
/** Override WS URL */
|
|
1734
|
+
wsUrl;
|
|
1735
|
+
/** Fallback poll interval (default: 90000) */
|
|
1736
|
+
fallbackPollIntervalMs;
|
|
1737
|
+
/** IPNS subscription client for push notifications */
|
|
1738
|
+
subscriptionClient = null;
|
|
1739
|
+
/** Unsubscribe function from subscription client */
|
|
1740
|
+
subscriptionUnsubscribe = null;
|
|
1741
|
+
/** Write-behind buffer: serializes flush / sync / shutdown */
|
|
1742
|
+
flushQueue = new AsyncSerialQueue();
|
|
1743
|
+
/** Pending mutations not yet flushed to IPFS */
|
|
1744
|
+
pendingBuffer = new WriteBuffer();
|
|
1745
|
+
/** Debounce timer for background flush */
|
|
1746
|
+
flushTimer = null;
|
|
1747
|
+
/** Debounce interval in ms */
|
|
1748
|
+
flushDebounceMs;
|
|
1749
|
+
/** Set to true during shutdown to prevent new flushes */
|
|
1750
|
+
isShuttingDown = false;
|
|
1751
|
+
constructor(config, statePersistence) {
|
|
1752
|
+
const gateways = config?.gateways ?? getIpfsGatewayUrls();
|
|
1753
|
+
this.debug = config?.debug ?? false;
|
|
1754
|
+
this.ipnsLifetimeMs = config?.ipnsLifetimeMs ?? 99 * 365 * 24 * 60 * 60 * 1e3;
|
|
1755
|
+
this.flushDebounceMs = config?.flushDebounceMs ?? 2e3;
|
|
1756
|
+
this.cache = new IpfsCache({
|
|
1757
|
+
ipnsTtlMs: config?.ipnsCacheTtlMs,
|
|
1758
|
+
failureCooldownMs: config?.circuitBreakerCooldownMs,
|
|
1759
|
+
failureThreshold: config?.circuitBreakerThreshold,
|
|
1760
|
+
knownFreshWindowMs: config?.knownFreshWindowMs
|
|
1761
|
+
});
|
|
1762
|
+
this.httpClient = new IpfsHttpClient({
|
|
1763
|
+
gateways,
|
|
1764
|
+
fetchTimeoutMs: config?.fetchTimeoutMs,
|
|
1765
|
+
resolveTimeoutMs: config?.resolveTimeoutMs,
|
|
1766
|
+
publishTimeoutMs: config?.publishTimeoutMs,
|
|
1767
|
+
connectivityTimeoutMs: config?.connectivityTimeoutMs,
|
|
1768
|
+
debug: this.debug
|
|
1769
|
+
}, this.cache);
|
|
1770
|
+
this.statePersistence = statePersistence ?? new InMemoryIpfsStatePersistence();
|
|
1771
|
+
this.createWebSocket = config?.createWebSocket;
|
|
1772
|
+
this.wsUrl = config?.wsUrl;
|
|
1773
|
+
this.fallbackPollIntervalMs = config?.fallbackPollIntervalMs ?? 9e4;
|
|
1774
|
+
}
|
|
1775
|
+
// ---------------------------------------------------------------------------
|
|
1776
|
+
// BaseProvider interface
|
|
1777
|
+
// ---------------------------------------------------------------------------
|
|
1778
|
+
async connect() {
|
|
1779
|
+
await this.initialize();
|
|
1780
|
+
}
|
|
1781
|
+
async disconnect() {
|
|
1782
|
+
await this.shutdown();
|
|
1783
|
+
}
|
|
1784
|
+
isConnected() {
|
|
1785
|
+
return this.status === "connected";
|
|
1786
|
+
}
|
|
1787
|
+
getStatus() {
|
|
1788
|
+
return this.status;
|
|
1789
|
+
}
|
|
1790
|
+
// ---------------------------------------------------------------------------
|
|
1791
|
+
// Identity & Initialization
|
|
1792
|
+
// ---------------------------------------------------------------------------
|
|
1793
|
+
setIdentity(identity) {
|
|
1794
|
+
this.identity = identity;
|
|
1795
|
+
}
|
|
1796
|
+
async initialize() {
|
|
1797
|
+
if (!this.identity) {
|
|
1798
|
+
this.log("Cannot initialize: no identity set");
|
|
1799
|
+
return false;
|
|
1800
|
+
}
|
|
1801
|
+
this.status = "connecting";
|
|
1802
|
+
this.emitEvent({ type: "storage:loading", timestamp: Date.now() });
|
|
920
1803
|
try {
|
|
921
|
-
const
|
|
922
|
-
|
|
923
|
-
|
|
1804
|
+
const { keyPair, ipnsName } = await deriveIpnsIdentity(this.identity.privateKey);
|
|
1805
|
+
this.ipnsKeyPair = keyPair;
|
|
1806
|
+
this.ipnsName = ipnsName;
|
|
1807
|
+
this.log(`IPNS name derived: ${ipnsName}`);
|
|
1808
|
+
const persisted = await this.statePersistence.load(ipnsName);
|
|
1809
|
+
if (persisted) {
|
|
1810
|
+
this.ipnsSequenceNumber = BigInt(persisted.sequenceNumber);
|
|
1811
|
+
this.lastCid = persisted.lastCid;
|
|
1812
|
+
this.remoteCid = persisted.lastCid;
|
|
1813
|
+
this.dataVersion = persisted.version;
|
|
1814
|
+
this.log(`Loaded persisted state: seq=${this.ipnsSequenceNumber}, cid=${this.lastCid}`);
|
|
1815
|
+
}
|
|
1816
|
+
if (this.createWebSocket) {
|
|
1817
|
+
try {
|
|
1818
|
+
const wsUrlFinal = this.wsUrl ?? this.deriveWsUrl();
|
|
1819
|
+
if (wsUrlFinal) {
|
|
1820
|
+
this.subscriptionClient = new IpnsSubscriptionClient({
|
|
1821
|
+
wsUrl: wsUrlFinal,
|
|
1822
|
+
createWebSocket: this.createWebSocket,
|
|
1823
|
+
debug: this.debug
|
|
1824
|
+
});
|
|
1825
|
+
this.subscriptionUnsubscribe = this.subscriptionClient.subscribe(
|
|
1826
|
+
ipnsName,
|
|
1827
|
+
(update) => {
|
|
1828
|
+
this.log(`Push update: seq=${update.sequence}, cid=${update.cid}`);
|
|
1829
|
+
this.emitEvent({
|
|
1830
|
+
type: "storage:remote-updated",
|
|
1831
|
+
timestamp: Date.now(),
|
|
1832
|
+
data: { name: update.name, sequence: update.sequence, cid: update.cid }
|
|
1833
|
+
});
|
|
1834
|
+
}
|
|
1835
|
+
);
|
|
1836
|
+
this.subscriptionClient.setFallbackPoll(
|
|
1837
|
+
() => this.pollForRemoteChanges(),
|
|
1838
|
+
this.fallbackPollIntervalMs
|
|
1839
|
+
);
|
|
1840
|
+
this.subscriptionClient.connect();
|
|
1841
|
+
}
|
|
1842
|
+
} catch (wsError) {
|
|
1843
|
+
this.log(`Failed to set up IPNS subscription: ${wsError}`);
|
|
1844
|
+
}
|
|
1845
|
+
}
|
|
1846
|
+
this.httpClient.findHealthyGateways().then((healthy) => {
|
|
1847
|
+
if (healthy.length > 0) {
|
|
1848
|
+
this.log(`${healthy.length} healthy gateway(s) found`);
|
|
1849
|
+
} else {
|
|
1850
|
+
this.log("Warning: no healthy gateways found");
|
|
1851
|
+
}
|
|
1852
|
+
}).catch(() => {
|
|
924
1853
|
});
|
|
925
|
-
|
|
926
|
-
|
|
1854
|
+
this.isShuttingDown = false;
|
|
1855
|
+
this.status = "connected";
|
|
1856
|
+
this.emitEvent({ type: "storage:loaded", timestamp: Date.now() });
|
|
1857
|
+
return true;
|
|
1858
|
+
} catch (error) {
|
|
1859
|
+
this.status = "error";
|
|
1860
|
+
this.emitEvent({
|
|
1861
|
+
type: "storage:error",
|
|
1862
|
+
timestamp: Date.now(),
|
|
1863
|
+
error: error instanceof Error ? error.message : String(error)
|
|
1864
|
+
});
|
|
1865
|
+
return false;
|
|
1866
|
+
}
|
|
1867
|
+
}
|
|
1868
|
+
async shutdown() {
|
|
1869
|
+
this.isShuttingDown = true;
|
|
1870
|
+
if (this.flushTimer) {
|
|
1871
|
+
clearTimeout(this.flushTimer);
|
|
1872
|
+
this.flushTimer = null;
|
|
1873
|
+
}
|
|
1874
|
+
await this.flushQueue.enqueue(async () => {
|
|
1875
|
+
if (!this.pendingBuffer.isEmpty) {
|
|
1876
|
+
try {
|
|
1877
|
+
await this.executeFlush();
|
|
1878
|
+
} catch {
|
|
1879
|
+
this.log("Final flush on shutdown failed (data may be lost)");
|
|
1880
|
+
}
|
|
927
1881
|
}
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
1882
|
+
});
|
|
1883
|
+
if (this.subscriptionUnsubscribe) {
|
|
1884
|
+
this.subscriptionUnsubscribe();
|
|
1885
|
+
this.subscriptionUnsubscribe = null;
|
|
1886
|
+
}
|
|
1887
|
+
if (this.subscriptionClient) {
|
|
1888
|
+
this.subscriptionClient.disconnect();
|
|
1889
|
+
this.subscriptionClient = null;
|
|
932
1890
|
}
|
|
1891
|
+
this.cache.clear();
|
|
1892
|
+
this.status = "disconnected";
|
|
933
1893
|
}
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
1894
|
+
// ---------------------------------------------------------------------------
|
|
1895
|
+
// Save (non-blocking — buffers data for async flush)
|
|
1896
|
+
// ---------------------------------------------------------------------------
|
|
1897
|
+
async save(data) {
|
|
1898
|
+
if (!this.ipnsKeyPair || !this.ipnsName) {
|
|
1899
|
+
return { success: false, error: "Not initialized", timestamp: Date.now() };
|
|
938
1900
|
}
|
|
939
|
-
|
|
940
|
-
|
|
1901
|
+
this.pendingBuffer.txfData = data;
|
|
1902
|
+
this.scheduleFlush();
|
|
1903
|
+
return { success: true, timestamp: Date.now() };
|
|
1904
|
+
}
|
|
1905
|
+
// ---------------------------------------------------------------------------
|
|
1906
|
+
// Internal: Blocking save (used by sync and executeFlush)
|
|
1907
|
+
// ---------------------------------------------------------------------------
|
|
1908
|
+
/**
|
|
1909
|
+
* Perform the actual upload + IPNS publish synchronously.
|
|
1910
|
+
* Called by executeFlush() and sync() — never by public save().
|
|
1911
|
+
*/
|
|
1912
|
+
async _doSave(data) {
|
|
1913
|
+
if (!this.ipnsKeyPair || !this.ipnsName) {
|
|
1914
|
+
return { success: false, error: "Not initialized", timestamp: Date.now() };
|
|
1915
|
+
}
|
|
1916
|
+
this.emitEvent({ type: "storage:saving", timestamp: Date.now() });
|
|
1917
|
+
try {
|
|
1918
|
+
this.dataVersion++;
|
|
1919
|
+
const metaUpdate = {
|
|
1920
|
+
...data._meta,
|
|
1921
|
+
version: this.dataVersion,
|
|
1922
|
+
ipnsName: this.ipnsName,
|
|
1923
|
+
updatedAt: Date.now()
|
|
1924
|
+
};
|
|
1925
|
+
if (this.remoteCid) {
|
|
1926
|
+
metaUpdate.lastCid = this.remoteCid;
|
|
1927
|
+
}
|
|
1928
|
+
const updatedData = { ...data, _meta: metaUpdate };
|
|
1929
|
+
const { cid } = await this.httpClient.upload(updatedData);
|
|
1930
|
+
this.log(`Content uploaded: CID=${cid}`);
|
|
1931
|
+
const baseSeq = this.ipnsSequenceNumber > this.lastKnownRemoteSequence ? this.ipnsSequenceNumber : this.lastKnownRemoteSequence;
|
|
1932
|
+
const newSeq = baseSeq + 1n;
|
|
1933
|
+
const marshalledRecord = await createSignedRecord(
|
|
1934
|
+
this.ipnsKeyPair,
|
|
1935
|
+
cid,
|
|
1936
|
+
newSeq,
|
|
1937
|
+
this.ipnsLifetimeMs
|
|
1938
|
+
);
|
|
1939
|
+
const publishResult = await this.httpClient.publishIpns(
|
|
1940
|
+
this.ipnsName,
|
|
1941
|
+
marshalledRecord
|
|
1942
|
+
);
|
|
1943
|
+
if (!publishResult.success) {
|
|
1944
|
+
this.dataVersion--;
|
|
1945
|
+
this.log(`IPNS publish failed: ${publishResult.error}`);
|
|
1946
|
+
return {
|
|
1947
|
+
success: false,
|
|
1948
|
+
error: publishResult.error ?? "IPNS publish failed",
|
|
1949
|
+
timestamp: Date.now()
|
|
1950
|
+
};
|
|
1951
|
+
}
|
|
1952
|
+
this.ipnsSequenceNumber = newSeq;
|
|
1953
|
+
this.lastCid = cid;
|
|
1954
|
+
this.remoteCid = cid;
|
|
1955
|
+
this.cache.setIpnsRecord(this.ipnsName, {
|
|
1956
|
+
cid,
|
|
1957
|
+
sequence: newSeq,
|
|
1958
|
+
gateway: "local"
|
|
1959
|
+
});
|
|
1960
|
+
this.cache.setContent(cid, updatedData);
|
|
1961
|
+
this.cache.markIpnsFresh(this.ipnsName);
|
|
1962
|
+
await this.statePersistence.save(this.ipnsName, {
|
|
1963
|
+
sequenceNumber: newSeq.toString(),
|
|
1964
|
+
lastCid: cid,
|
|
1965
|
+
version: this.dataVersion
|
|
1966
|
+
});
|
|
1967
|
+
this.emitEvent({
|
|
1968
|
+
type: "storage:saved",
|
|
1969
|
+
timestamp: Date.now(),
|
|
1970
|
+
data: { cid, sequence: newSeq.toString() }
|
|
1971
|
+
});
|
|
1972
|
+
this.log(`Saved: CID=${cid}, seq=${newSeq}`);
|
|
1973
|
+
return { success: true, cid, timestamp: Date.now() };
|
|
1974
|
+
} catch (error) {
|
|
1975
|
+
this.dataVersion--;
|
|
1976
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
1977
|
+
this.emitEvent({
|
|
1978
|
+
type: "storage:error",
|
|
1979
|
+
timestamp: Date.now(),
|
|
1980
|
+
error: errorMessage
|
|
1981
|
+
});
|
|
1982
|
+
return { success: false, error: errorMessage, timestamp: Date.now() };
|
|
941
1983
|
}
|
|
942
|
-
return Promise.any(promises);
|
|
943
1984
|
}
|
|
1985
|
+
// ---------------------------------------------------------------------------
|
|
1986
|
+
// Write-behind buffer: scheduling and flushing
|
|
1987
|
+
// ---------------------------------------------------------------------------
|
|
944
1988
|
/**
|
|
945
|
-
*
|
|
1989
|
+
* Schedule a debounced background flush.
|
|
1990
|
+
* Resets the timer on each call so rapid mutations coalesce.
|
|
946
1991
|
*/
|
|
947
|
-
|
|
948
|
-
if (
|
|
949
|
-
|
|
1992
|
+
scheduleFlush() {
|
|
1993
|
+
if (this.isShuttingDown) return;
|
|
1994
|
+
if (this.flushTimer) clearTimeout(this.flushTimer);
|
|
1995
|
+
this.flushTimer = setTimeout(() => {
|
|
1996
|
+
this.flushTimer = null;
|
|
1997
|
+
this.flushQueue.enqueue(() => this.executeFlush()).catch((err) => {
|
|
1998
|
+
this.log(`Background flush failed: ${err}`);
|
|
1999
|
+
});
|
|
2000
|
+
}, this.flushDebounceMs);
|
|
2001
|
+
}
|
|
2002
|
+
/**
|
|
2003
|
+
* Execute a flush of the pending buffer to IPFS.
|
|
2004
|
+
* Runs inside AsyncSerialQueue for concurrency safety.
|
|
2005
|
+
*/
|
|
2006
|
+
async executeFlush() {
|
|
2007
|
+
if (this.pendingBuffer.isEmpty) return;
|
|
2008
|
+
const active = this.pendingBuffer;
|
|
2009
|
+
this.pendingBuffer = new WriteBuffer();
|
|
2010
|
+
try {
|
|
2011
|
+
const baseData = active.txfData ?? {
|
|
2012
|
+
_meta: { version: 0, address: this.identity?.directAddress ?? "", formatVersion: "2.0", updatedAt: 0 }
|
|
2013
|
+
};
|
|
2014
|
+
const result = await this._doSave(baseData);
|
|
2015
|
+
if (!result.success) {
|
|
2016
|
+
throw new Error(result.error ?? "Save failed");
|
|
2017
|
+
}
|
|
2018
|
+
this.log(`Flushed successfully: CID=${result.cid}`);
|
|
2019
|
+
} catch (error) {
|
|
2020
|
+
this.pendingBuffer.mergeFrom(active);
|
|
2021
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
2022
|
+
this.log(`Flush failed (will retry): ${msg}`);
|
|
2023
|
+
this.scheduleFlush();
|
|
2024
|
+
throw error;
|
|
950
2025
|
}
|
|
951
|
-
const { CID } = await loadHeliaModules();
|
|
952
|
-
const cid = CID.parse(cidString);
|
|
953
|
-
const data = await this.heliaJson.get(cid);
|
|
954
|
-
this.log("Fetched via Helia, CID:", cidString);
|
|
955
|
-
return data;
|
|
956
2026
|
}
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
2027
|
+
// ---------------------------------------------------------------------------
|
|
2028
|
+
// Load
|
|
2029
|
+
// ---------------------------------------------------------------------------
|
|
2030
|
+
async load(identifier) {
|
|
2031
|
+
if (!this.ipnsName && !identifier) {
|
|
2032
|
+
return { success: false, error: "Not initialized", source: "local", timestamp: Date.now() };
|
|
2033
|
+
}
|
|
2034
|
+
this.emitEvent({ type: "storage:loading", timestamp: Date.now() });
|
|
960
2035
|
try {
|
|
961
|
-
|
|
962
|
-
|
|
2036
|
+
if (identifier) {
|
|
2037
|
+
const data2 = await this.httpClient.fetchContent(identifier);
|
|
2038
|
+
return { success: true, data: data2, source: "remote", timestamp: Date.now() };
|
|
2039
|
+
}
|
|
2040
|
+
const ipnsName = this.ipnsName;
|
|
2041
|
+
if (this.cache.isIpnsKnownFresh(ipnsName)) {
|
|
2042
|
+
const cached = this.cache.getIpnsRecordIgnoreTtl(ipnsName);
|
|
2043
|
+
if (cached) {
|
|
2044
|
+
const content = this.cache.getContent(cached.cid);
|
|
2045
|
+
if (content) {
|
|
2046
|
+
this.log("Using known-fresh cached data");
|
|
2047
|
+
return { success: true, data: content, source: "cache", timestamp: Date.now() };
|
|
2048
|
+
}
|
|
2049
|
+
}
|
|
2050
|
+
}
|
|
2051
|
+
const cachedRecord = this.cache.getIpnsRecord(ipnsName);
|
|
2052
|
+
if (cachedRecord) {
|
|
2053
|
+
const content = this.cache.getContent(cachedRecord.cid);
|
|
2054
|
+
if (content) {
|
|
2055
|
+
this.log("IPNS cache hit");
|
|
2056
|
+
return { success: true, data: content, source: "cache", timestamp: Date.now() };
|
|
2057
|
+
}
|
|
2058
|
+
try {
|
|
2059
|
+
const data2 = await this.httpClient.fetchContent(cachedRecord.cid);
|
|
2060
|
+
return { success: true, data: data2, source: "remote", timestamp: Date.now() };
|
|
2061
|
+
} catch {
|
|
2062
|
+
}
|
|
2063
|
+
}
|
|
2064
|
+
const { best } = await this.httpClient.resolveIpns(ipnsName);
|
|
2065
|
+
if (!best) {
|
|
2066
|
+
this.log("IPNS record not found (new wallet?)");
|
|
2067
|
+
return { success: false, error: "IPNS record not found", source: "remote", timestamp: Date.now() };
|
|
2068
|
+
}
|
|
2069
|
+
if (best.sequence > this.lastKnownRemoteSequence) {
|
|
2070
|
+
this.lastKnownRemoteSequence = best.sequence;
|
|
2071
|
+
}
|
|
2072
|
+
this.remoteCid = best.cid;
|
|
2073
|
+
const data = await this.httpClient.fetchContent(best.cid);
|
|
2074
|
+
const remoteVersion = data?._meta?.version;
|
|
2075
|
+
if (typeof remoteVersion === "number" && remoteVersion > this.dataVersion) {
|
|
2076
|
+
this.dataVersion = remoteVersion;
|
|
2077
|
+
}
|
|
2078
|
+
this.emitEvent({
|
|
2079
|
+
type: "storage:loaded",
|
|
2080
|
+
timestamp: Date.now(),
|
|
2081
|
+
data: { cid: best.cid, sequence: best.sequence.toString() }
|
|
963
2082
|
});
|
|
964
|
-
|
|
965
|
-
|
|
2083
|
+
return { success: true, data, source: "remote", timestamp: Date.now() };
|
|
2084
|
+
} catch (error) {
|
|
2085
|
+
if (this.ipnsName) {
|
|
2086
|
+
const cached = this.cache.getIpnsRecordIgnoreTtl(this.ipnsName);
|
|
2087
|
+
if (cached) {
|
|
2088
|
+
const content = this.cache.getContent(cached.cid);
|
|
2089
|
+
if (content) {
|
|
2090
|
+
this.log("Network error, returning stale cache");
|
|
2091
|
+
return { success: true, data: content, source: "cache", timestamp: Date.now() };
|
|
2092
|
+
}
|
|
2093
|
+
}
|
|
966
2094
|
}
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
const existing = tombstones.get(t.tokenId);
|
|
985
|
-
if (!existing || t.timestamp > existing.timestamp) {
|
|
986
|
-
tombstones.set(t.tokenId, t);
|
|
2095
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
2096
|
+
this.emitEvent({
|
|
2097
|
+
type: "storage:error",
|
|
2098
|
+
timestamp: Date.now(),
|
|
2099
|
+
error: errorMessage
|
|
2100
|
+
});
|
|
2101
|
+
return { success: false, error: errorMessage, source: "remote", timestamp: Date.now() };
|
|
2102
|
+
}
|
|
2103
|
+
}
|
|
2104
|
+
// ---------------------------------------------------------------------------
|
|
2105
|
+
// Sync (enters serial queue to avoid concurrent IPNS conflicts)
|
|
2106
|
+
// ---------------------------------------------------------------------------
|
|
2107
|
+
async sync(localData) {
|
|
2108
|
+
return this.flushQueue.enqueue(async () => {
|
|
2109
|
+
if (this.flushTimer) {
|
|
2110
|
+
clearTimeout(this.flushTimer);
|
|
2111
|
+
this.flushTimer = null;
|
|
987
2112
|
}
|
|
2113
|
+
this.emitEvent({ type: "sync:started", timestamp: Date.now() });
|
|
2114
|
+
try {
|
|
2115
|
+
this.pendingBuffer.clear();
|
|
2116
|
+
const remoteResult = await this.load();
|
|
2117
|
+
if (!remoteResult.success || !remoteResult.data) {
|
|
2118
|
+
this.log("No remote data found, uploading local data");
|
|
2119
|
+
const saveResult2 = await this._doSave(localData);
|
|
2120
|
+
this.emitEvent({ type: "sync:completed", timestamp: Date.now() });
|
|
2121
|
+
return {
|
|
2122
|
+
success: saveResult2.success,
|
|
2123
|
+
merged: localData,
|
|
2124
|
+
added: 0,
|
|
2125
|
+
removed: 0,
|
|
2126
|
+
conflicts: 0,
|
|
2127
|
+
error: saveResult2.error
|
|
2128
|
+
};
|
|
2129
|
+
}
|
|
2130
|
+
const remoteData = remoteResult.data;
|
|
2131
|
+
const localVersion = localData._meta?.version ?? 0;
|
|
2132
|
+
const remoteVersion = remoteData._meta?.version ?? 0;
|
|
2133
|
+
if (localVersion === remoteVersion && this.lastCid) {
|
|
2134
|
+
this.log("Data is in sync (same version)");
|
|
2135
|
+
this.emitEvent({ type: "sync:completed", timestamp: Date.now() });
|
|
2136
|
+
return {
|
|
2137
|
+
success: true,
|
|
2138
|
+
merged: localData,
|
|
2139
|
+
added: 0,
|
|
2140
|
+
removed: 0,
|
|
2141
|
+
conflicts: 0
|
|
2142
|
+
};
|
|
2143
|
+
}
|
|
2144
|
+
this.log(`Merging: local v${localVersion} <-> remote v${remoteVersion}`);
|
|
2145
|
+
const { merged, added, removed, conflicts } = mergeTxfData(localData, remoteData);
|
|
2146
|
+
if (conflicts > 0) {
|
|
2147
|
+
this.emitEvent({
|
|
2148
|
+
type: "sync:conflict",
|
|
2149
|
+
timestamp: Date.now(),
|
|
2150
|
+
data: { conflicts }
|
|
2151
|
+
});
|
|
2152
|
+
}
|
|
2153
|
+
const saveResult = await this._doSave(merged);
|
|
2154
|
+
this.emitEvent({
|
|
2155
|
+
type: "sync:completed",
|
|
2156
|
+
timestamp: Date.now(),
|
|
2157
|
+
data: { added, removed, conflicts }
|
|
2158
|
+
});
|
|
2159
|
+
return {
|
|
2160
|
+
success: saveResult.success,
|
|
2161
|
+
merged,
|
|
2162
|
+
added,
|
|
2163
|
+
removed,
|
|
2164
|
+
conflicts,
|
|
2165
|
+
error: saveResult.error
|
|
2166
|
+
};
|
|
2167
|
+
} catch (error) {
|
|
2168
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
2169
|
+
this.emitEvent({
|
|
2170
|
+
type: "sync:error",
|
|
2171
|
+
timestamp: Date.now(),
|
|
2172
|
+
error: errorMessage
|
|
2173
|
+
});
|
|
2174
|
+
return {
|
|
2175
|
+
success: false,
|
|
2176
|
+
added: 0,
|
|
2177
|
+
removed: 0,
|
|
2178
|
+
conflicts: 0,
|
|
2179
|
+
error: errorMessage
|
|
2180
|
+
};
|
|
2181
|
+
}
|
|
2182
|
+
});
|
|
2183
|
+
}
|
|
2184
|
+
// ---------------------------------------------------------------------------
|
|
2185
|
+
// Private Helpers
|
|
2186
|
+
// ---------------------------------------------------------------------------
|
|
2187
|
+
// ---------------------------------------------------------------------------
|
|
2188
|
+
// Optional Methods
|
|
2189
|
+
// ---------------------------------------------------------------------------
|
|
2190
|
+
async exists() {
|
|
2191
|
+
if (!this.ipnsName) return false;
|
|
2192
|
+
const cached = this.cache.getIpnsRecord(this.ipnsName);
|
|
2193
|
+
if (cached) return true;
|
|
2194
|
+
const { best } = await this.httpClient.resolveIpns(this.ipnsName);
|
|
2195
|
+
return best !== null;
|
|
2196
|
+
}
|
|
2197
|
+
async clear() {
|
|
2198
|
+
if (!this.ipnsKeyPair || !this.ipnsName) return false;
|
|
2199
|
+
this.pendingBuffer.clear();
|
|
2200
|
+
if (this.flushTimer) {
|
|
2201
|
+
clearTimeout(this.flushTimer);
|
|
2202
|
+
this.flushTimer = null;
|
|
988
2203
|
}
|
|
989
|
-
const
|
|
2204
|
+
const emptyData = {
|
|
990
2205
|
_meta: {
|
|
991
|
-
|
|
992
|
-
|
|
2206
|
+
version: 0,
|
|
2207
|
+
address: this.identity?.directAddress ?? "",
|
|
2208
|
+
ipnsName: this.ipnsName,
|
|
2209
|
+
formatVersion: "2.0",
|
|
993
2210
|
updatedAt: Date.now()
|
|
994
|
-
},
|
|
995
|
-
_tombstones: Array.from(tombstones.values())
|
|
996
|
-
};
|
|
997
|
-
let added = 0;
|
|
998
|
-
let conflicts = 0;
|
|
999
|
-
const processedKeys = /* @__PURE__ */ new Set();
|
|
1000
|
-
for (const key of Object.keys(local)) {
|
|
1001
|
-
if (!key.startsWith("_") || key === "_meta" || key === "_tombstones") continue;
|
|
1002
|
-
processedKeys.add(key);
|
|
1003
|
-
const tokenId = key.slice(1);
|
|
1004
|
-
if (tombstones.has(tokenId)) continue;
|
|
1005
|
-
const localToken = local[key];
|
|
1006
|
-
const remoteToken = remote[key];
|
|
1007
|
-
if (remoteToken) {
|
|
1008
|
-
conflicts++;
|
|
1009
|
-
merged[key] = localToken;
|
|
1010
|
-
} else {
|
|
1011
|
-
merged[key] = localToken;
|
|
1012
2211
|
}
|
|
2212
|
+
};
|
|
2213
|
+
const result = await this._doSave(emptyData);
|
|
2214
|
+
if (result.success) {
|
|
2215
|
+
this.cache.clear();
|
|
2216
|
+
await this.statePersistence.clear(this.ipnsName);
|
|
1013
2217
|
}
|
|
1014
|
-
|
|
1015
|
-
if (!key.startsWith("_") || key === "_meta" || key === "_tombstones") continue;
|
|
1016
|
-
if (processedKeys.has(key)) continue;
|
|
1017
|
-
const tokenId = key.slice(1);
|
|
1018
|
-
if (tombstones.has(tokenId)) continue;
|
|
1019
|
-
merged[key] = remote[key];
|
|
1020
|
-
added++;
|
|
1021
|
-
}
|
|
1022
|
-
return { merged, added, removed: 0, conflicts };
|
|
2218
|
+
return result.success;
|
|
1023
2219
|
}
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
2220
|
+
onEvent(callback) {
|
|
2221
|
+
this.eventCallbacks.add(callback);
|
|
2222
|
+
return () => {
|
|
2223
|
+
this.eventCallbacks.delete(callback);
|
|
2224
|
+
};
|
|
2225
|
+
}
|
|
2226
|
+
// ---------------------------------------------------------------------------
|
|
2227
|
+
// Public Accessors
|
|
2228
|
+
// ---------------------------------------------------------------------------
|
|
2229
|
+
getIpnsName() {
|
|
2230
|
+
return this.ipnsName;
|
|
2231
|
+
}
|
|
2232
|
+
getLastCid() {
|
|
2233
|
+
return this.lastCid;
|
|
2234
|
+
}
|
|
2235
|
+
getSequenceNumber() {
|
|
2236
|
+
return this.ipnsSequenceNumber;
|
|
2237
|
+
}
|
|
2238
|
+
getDataVersion() {
|
|
2239
|
+
return this.dataVersion;
|
|
2240
|
+
}
|
|
2241
|
+
getRemoteCid() {
|
|
2242
|
+
return this.remoteCid;
|
|
2243
|
+
}
|
|
2244
|
+
// ---------------------------------------------------------------------------
|
|
2245
|
+
// Testing helper: wait for pending flush to complete
|
|
2246
|
+
// ---------------------------------------------------------------------------
|
|
2247
|
+
/**
|
|
2248
|
+
* Wait for the pending flush timer to fire and the flush operation to
|
|
2249
|
+
* complete. Useful in tests to await background writes.
|
|
2250
|
+
* Returns immediately if no flush is pending.
|
|
2251
|
+
*/
|
|
2252
|
+
async waitForFlush() {
|
|
2253
|
+
if (this.flushTimer) {
|
|
2254
|
+
clearTimeout(this.flushTimer);
|
|
2255
|
+
this.flushTimer = null;
|
|
2256
|
+
await this.flushQueue.enqueue(() => this.executeFlush()).catch(() => {
|
|
2257
|
+
});
|
|
2258
|
+
} else if (!this.pendingBuffer.isEmpty) {
|
|
2259
|
+
await this.flushQueue.enqueue(() => this.executeFlush()).catch(() => {
|
|
2260
|
+
});
|
|
2261
|
+
} else {
|
|
2262
|
+
await this.flushQueue.enqueue(async () => {
|
|
2263
|
+
});
|
|
1033
2264
|
}
|
|
1034
2265
|
}
|
|
2266
|
+
// ---------------------------------------------------------------------------
|
|
2267
|
+
// Internal: Push Subscription Helpers
|
|
2268
|
+
// ---------------------------------------------------------------------------
|
|
1035
2269
|
/**
|
|
1036
|
-
*
|
|
2270
|
+
* Derive WebSocket URL from the first configured gateway.
|
|
2271
|
+
* Converts https://host → wss://host/ws/ipns
|
|
1037
2272
|
*/
|
|
1038
|
-
|
|
1039
|
-
|
|
2273
|
+
deriveWsUrl() {
|
|
2274
|
+
const gateways = this.httpClient.getGateways();
|
|
2275
|
+
if (gateways.length === 0) return null;
|
|
2276
|
+
const gateway = gateways[0];
|
|
2277
|
+
const wsProtocol = gateway.startsWith("https://") ? "wss://" : "ws://";
|
|
2278
|
+
const host = gateway.replace(/^https?:\/\//, "");
|
|
2279
|
+
return `${wsProtocol}${host}/ws/ipns`;
|
|
1040
2280
|
}
|
|
1041
2281
|
/**
|
|
1042
|
-
*
|
|
2282
|
+
* Poll for remote IPNS changes (fallback when WS is unavailable).
|
|
2283
|
+
* Compares remote sequence number with last known and emits event if changed.
|
|
1043
2284
|
*/
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
2285
|
+
async pollForRemoteChanges() {
|
|
2286
|
+
if (!this.ipnsName) return;
|
|
2287
|
+
try {
|
|
2288
|
+
const { best } = await this.httpClient.resolveIpns(this.ipnsName);
|
|
2289
|
+
if (best && best.sequence > this.lastKnownRemoteSequence) {
|
|
2290
|
+
this.log(`Poll detected remote change: seq=${best.sequence} (was ${this.lastKnownRemoteSequence})`);
|
|
2291
|
+
this.lastKnownRemoteSequence = best.sequence;
|
|
2292
|
+
this.emitEvent({
|
|
2293
|
+
type: "storage:remote-updated",
|
|
2294
|
+
timestamp: Date.now(),
|
|
2295
|
+
data: { name: this.ipnsName, sequence: Number(best.sequence), cid: best.cid }
|
|
2296
|
+
});
|
|
2297
|
+
}
|
|
2298
|
+
} catch {
|
|
1048
2299
|
}
|
|
1049
|
-
return bytes;
|
|
1050
2300
|
}
|
|
2301
|
+
// ---------------------------------------------------------------------------
|
|
2302
|
+
// Internal
|
|
2303
|
+
// ---------------------------------------------------------------------------
|
|
1051
2304
|
emitEvent(event) {
|
|
1052
2305
|
for (const callback of this.eventCallbacks) {
|
|
1053
2306
|
try {
|
|
1054
2307
|
callback(event);
|
|
1055
|
-
} catch
|
|
1056
|
-
console.error("[IpfsStorageProvider] Event callback error:", error);
|
|
2308
|
+
} catch {
|
|
1057
2309
|
}
|
|
1058
2310
|
}
|
|
1059
2311
|
}
|
|
1060
|
-
log(
|
|
1061
|
-
if (this.
|
|
1062
|
-
console.log(
|
|
2312
|
+
log(message) {
|
|
2313
|
+
if (this.debug) {
|
|
2314
|
+
console.log(`[IPFS-Storage] ${message}`);
|
|
1063
2315
|
}
|
|
1064
2316
|
}
|
|
1065
2317
|
};
|
|
1066
|
-
|
|
1067
|
-
|
|
2318
|
+
|
|
2319
|
+
// impl/browser/ipfs/browser-ipfs-state-persistence.ts
|
|
2320
|
+
var KEY_PREFIX = "sphere_ipfs_";
|
|
2321
|
+
function seqKey(ipnsName) {
|
|
2322
|
+
return `${KEY_PREFIX}seq_${ipnsName}`;
|
|
2323
|
+
}
|
|
2324
|
+
function cidKey(ipnsName) {
|
|
2325
|
+
return `${KEY_PREFIX}cid_${ipnsName}`;
|
|
2326
|
+
}
|
|
2327
|
+
function verKey(ipnsName) {
|
|
2328
|
+
return `${KEY_PREFIX}ver_${ipnsName}`;
|
|
2329
|
+
}
|
|
2330
|
+
var BrowserIpfsStatePersistence = class {
|
|
2331
|
+
async load(ipnsName) {
|
|
2332
|
+
try {
|
|
2333
|
+
const seq = localStorage.getItem(seqKey(ipnsName));
|
|
2334
|
+
if (!seq) return null;
|
|
2335
|
+
return {
|
|
2336
|
+
sequenceNumber: seq,
|
|
2337
|
+
lastCid: localStorage.getItem(cidKey(ipnsName)),
|
|
2338
|
+
version: parseInt(localStorage.getItem(verKey(ipnsName)) ?? "0", 10)
|
|
2339
|
+
};
|
|
2340
|
+
} catch {
|
|
2341
|
+
return null;
|
|
2342
|
+
}
|
|
2343
|
+
}
|
|
2344
|
+
async save(ipnsName, state) {
|
|
2345
|
+
try {
|
|
2346
|
+
localStorage.setItem(seqKey(ipnsName), state.sequenceNumber);
|
|
2347
|
+
if (state.lastCid) {
|
|
2348
|
+
localStorage.setItem(cidKey(ipnsName), state.lastCid);
|
|
2349
|
+
} else {
|
|
2350
|
+
localStorage.removeItem(cidKey(ipnsName));
|
|
2351
|
+
}
|
|
2352
|
+
localStorage.setItem(verKey(ipnsName), String(state.version));
|
|
2353
|
+
} catch {
|
|
2354
|
+
}
|
|
2355
|
+
}
|
|
2356
|
+
async clear(ipnsName) {
|
|
2357
|
+
try {
|
|
2358
|
+
localStorage.removeItem(seqKey(ipnsName));
|
|
2359
|
+
localStorage.removeItem(cidKey(ipnsName));
|
|
2360
|
+
localStorage.removeItem(verKey(ipnsName));
|
|
2361
|
+
} catch {
|
|
2362
|
+
}
|
|
2363
|
+
}
|
|
2364
|
+
};
|
|
2365
|
+
|
|
2366
|
+
// impl/browser/ipfs/index.ts
|
|
2367
|
+
function createBrowserWebSocket(url) {
|
|
2368
|
+
return new WebSocket(url);
|
|
2369
|
+
}
|
|
2370
|
+
function createBrowserIpfsStorageProvider(config) {
|
|
2371
|
+
return new IpfsStorageProvider(
|
|
2372
|
+
{ ...config, createWebSocket: config?.createWebSocket ?? createBrowserWebSocket },
|
|
2373
|
+
new BrowserIpfsStatePersistence()
|
|
2374
|
+
);
|
|
1068
2375
|
}
|
|
2376
|
+
var createIpfsStorageProvider = createBrowserIpfsStorageProvider;
|
|
1069
2377
|
export {
|
|
2378
|
+
BrowserIpfsStatePersistence,
|
|
1070
2379
|
IpfsStorageProvider,
|
|
2380
|
+
createBrowserIpfsStorageProvider,
|
|
1071
2381
|
createIpfsStorageProvider
|
|
1072
2382
|
};
|
|
1073
2383
|
/*! Bundled license information:
|