@abraca/dabra 2.101.0 → 2.103.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/dist/abracadabra-provider.cjs +6673 -6543
- package/dist/abracadabra-provider.cjs.map +1 -1
- package/dist/esm/AbracadabraBaseProvider.js +558 -0
- package/dist/esm/AbracadabraBaseProvider.js.map +1 -0
- package/dist/esm/AbracadabraClient.js +1424 -0
- package/dist/esm/AbracadabraClient.js.map +1 -0
- package/dist/esm/AbracadabraProvider.js +547 -0
- package/dist/esm/AbracadabraProvider.js.map +1 -0
- package/dist/esm/AbracadabraWS.js +398 -0
- package/dist/esm/AbracadabraWS.js.map +1 -0
- package/dist/esm/BackgroundSyncManager.js +571 -0
- package/dist/esm/BackgroundSyncManager.js.map +1 -0
- package/dist/esm/BackgroundSyncPersistence.js +62 -0
- package/dist/esm/BackgroundSyncPersistence.js.map +1 -0
- package/dist/esm/ChatClient.js +176 -0
- package/dist/esm/ChatClient.js.map +1 -0
- package/dist/esm/CloseEvents.js +45 -0
- package/dist/esm/CloseEvents.js.map +1 -0
- package/dist/esm/ContentManager.js +153 -0
- package/dist/esm/ContentManager.js.map +1 -0
- package/dist/esm/CoverReconcile.js +124 -0
- package/dist/esm/CoverReconcile.js.map +1 -0
- package/dist/esm/CryptoIdentityKeystore.js +580 -0
- package/dist/esm/CryptoIdentityKeystore.js.map +1 -0
- package/dist/esm/DeviceRegistrationService.js +158 -0
- package/dist/esm/DeviceRegistrationService.js.map +1 -0
- package/dist/esm/DocConverters.js +1300 -0
- package/dist/esm/DocConverters.js.map +1 -0
- package/dist/esm/DocKeyManager.js +145 -0
- package/dist/esm/DocKeyManager.js.map +1 -0
- package/dist/esm/DocTypes.js +792 -0
- package/dist/esm/DocTypes.js.map +1 -0
- package/dist/esm/DocUtils.js +180 -0
- package/dist/esm/DocUtils.js.map +1 -0
- package/dist/esm/DocumentCache.js +131 -0
- package/dist/esm/DocumentCache.js.map +1 -0
- package/dist/esm/DocumentManager.js +240 -0
- package/dist/esm/DocumentManager.js.map +1 -0
- package/dist/esm/E2EAbracadabraProvider.js +273 -0
- package/dist/esm/E2EAbracadabraProvider.js.map +1 -0
- package/dist/esm/E2EOfflineStore.js +53 -0
- package/dist/esm/E2EOfflineStore.js.map +1 -0
- package/dist/esm/EncryptedChatClient.js +156 -0
- package/dist/esm/EncryptedChatClient.js.map +1 -0
- package/dist/esm/EncryptedY.js +115 -0
- package/dist/esm/EncryptedY.js.map +1 -0
- package/dist/esm/EventEmitter.js +40 -0
- package/dist/esm/EventEmitter.js.map +1 -0
- package/dist/esm/FileBlobStore.js +410 -0
- package/dist/esm/FileBlobStore.js.map +1 -0
- package/dist/esm/IdentityDoc.js +413 -0
- package/dist/esm/IdentityDoc.js.map +1 -0
- package/dist/esm/IncomingMessage.js +39 -0
- package/dist/esm/IncomingMessage.js.map +1 -0
- package/dist/esm/LifecycleGate.js +124 -0
- package/dist/esm/LifecycleGate.js.map +1 -0
- package/dist/esm/MessageReceiver.js +86 -0
- package/dist/esm/MessageReceiver.js.map +1 -0
- package/dist/esm/MessageSender.js +19 -0
- package/dist/esm/MessageSender.js.map +1 -0
- package/dist/esm/MetaManager.js +112 -0
- package/dist/esm/MetaManager.js.map +1 -0
- package/dist/esm/MnemonicKeyDerivation.js +137 -0
- package/dist/esm/MnemonicKeyDerivation.js.map +1 -0
- package/dist/esm/NodeConnect.js +63 -0
- package/dist/esm/NodeConnect.js.map +1 -0
- package/dist/esm/NodeIdentity.js +212 -0
- package/dist/esm/NodeIdentity.js.map +1 -0
- package/dist/esm/NotificationsClient.js +136 -0
- package/dist/esm/NotificationsClient.js.map +1 -0
- package/dist/esm/OfflineStore.js +291 -0
- package/dist/esm/OfflineStore.js.map +1 -0
- package/dist/esm/OutgoingMessage.js +18 -0
- package/dist/esm/OutgoingMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/AuthenticationMessage.js +24 -0
- package/dist/esm/OutgoingMessages/AuthenticationMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/AwarenessMessage.js +28 -0
- package/dist/esm/OutgoingMessages/AwarenessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/CloseMessage.js +21 -0
- package/dist/esm/OutgoingMessages/CloseMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js +21 -0
- package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/StatelessMessage.js +22 -0
- package/dist/esm/OutgoingMessages/StatelessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/SubdocMessage.js +34 -0
- package/dist/esm/OutgoingMessages/SubdocMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/SyncStepOneMessage.js +24 -0
- package/dist/esm/OutgoingMessages/SyncStepOneMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/UpdateMessage.js +23 -0
- package/dist/esm/OutgoingMessages/UpdateMessage.js.map +1 -0
- package/dist/esm/PerfCounters.js +336 -0
- package/dist/esm/PerfCounters.js.map +1 -0
- package/dist/esm/QueryClient.js +117 -0
- package/dist/esm/QueryClient.js.map +1 -0
- package/dist/esm/RpcClient.js +456 -0
- package/dist/esm/RpcClient.js.map +1 -0
- package/dist/esm/SchemaTypes.js +38 -0
- package/dist/esm/SchemaTypes.js.map +1 -0
- package/dist/esm/SearchIndex.js +167 -0
- package/dist/esm/SearchIndex.js.map +1 -0
- package/dist/esm/ServerRegistry.js +139 -0
- package/dist/esm/ServerRegistry.js.map +1 -0
- package/dist/esm/ServerReset.js +170 -0
- package/dist/esm/ServerReset.js.map +1 -0
- package/dist/esm/TokenManager.js +236 -0
- package/dist/esm/TokenManager.js.map +1 -0
- package/dist/esm/TreeManager.js +655 -0
- package/dist/esm/TreeManager.js.map +1 -0
- package/dist/esm/TreeTimestamps.js +61 -0
- package/dist/esm/TreeTimestamps.js.map +1 -0
- package/dist/esm/auth.js +43 -0
- package/dist/esm/auth.js.map +1 -0
- package/dist/esm/awarenessStatesToArray.js +13 -0
- package/dist/esm/awarenessStatesToArray.js.map +1 -0
- package/dist/esm/docIds.js +53 -0
- package/dist/esm/docIds.js.map +1 -0
- package/dist/esm/encryptedContent.js +21 -0
- package/dist/esm/encryptedContent.js.map +1 -0
- package/dist/esm/index.js +61 -0
- package/dist/esm/messageRecord.js +64 -0
- package/dist/esm/messageRecord.js.map +1 -0
- package/dist/esm/sync/BroadcastChannelSync.js +160 -0
- package/dist/esm/sync/BroadcastChannelSync.js.map +1 -0
- package/dist/esm/types.js +54 -0
- package/dist/esm/types.js.map +1 -0
- package/dist/esm/webrtc/AbracadabraWebRTC.js +483 -0
- package/dist/esm/webrtc/AbracadabraWebRTC.js.map +1 -0
- package/dist/esm/webrtc/DataChannelRouter.js +124 -0
- package/dist/esm/webrtc/DataChannelRouter.js.map +1 -0
- package/dist/esm/webrtc/DevicePairingChannel.js +335 -0
- package/dist/esm/webrtc/DevicePairingChannel.js.map +1 -0
- package/dist/esm/webrtc/E2EEChannel.js +137 -0
- package/dist/esm/webrtc/E2EEChannel.js.map +1 -0
- package/dist/esm/webrtc/FileTransferChannel.js +250 -0
- package/dist/esm/webrtc/FileTransferChannel.js.map +1 -0
- package/dist/esm/webrtc/ManualSignaling.js +161 -0
- package/dist/esm/webrtc/ManualSignaling.js.map +1 -0
- package/dist/esm/webrtc/PeerConnection.js +96 -0
- package/dist/esm/webrtc/PeerConnection.js.map +1 -0
- package/dist/esm/webrtc/SignalingSocket.js +274 -0
- package/dist/esm/webrtc/SignalingSocket.js.map +1 -0
- package/dist/esm/webrtc/YjsDataChannel.js +135 -0
- package/dist/esm/webrtc/YjsDataChannel.js.map +1 -0
- package/dist/esm/webrtc/types.js +29 -0
- package/dist/esm/webrtc/types.js.map +1 -0
- package/dist/esm/x25519Convert.js +69 -0
- package/dist/esm/x25519Convert.js.map +1 -0
- package/dist/index.d.ts +26 -11
- package/package.json +6 -4
- package/dist/abracadabra-provider.esm.js +0 -14860
- package/dist/abracadabra-provider.esm.js.map +0 -1
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
//#region packages/provider/src/SearchIndex.ts
|
|
2
|
+
const DB_VERSION = 1;
|
|
3
|
+
function idbAvailable() {
|
|
4
|
+
return typeof globalThis !== "undefined" && "indexedDB" in globalThis;
|
|
5
|
+
}
|
|
6
|
+
function openDb(origin) {
|
|
7
|
+
return new Promise((resolve, reject) => {
|
|
8
|
+
const req = globalThis.indexedDB.open(`abracadabra:search:${origin}`, DB_VERSION);
|
|
9
|
+
req.onupgradeneeded = (event) => {
|
|
10
|
+
const db = event.target.result;
|
|
11
|
+
if (!db.objectStoreNames.contains("postings")) db.createObjectStore("postings");
|
|
12
|
+
if (!db.objectStoreNames.contains("doc_trigrams")) db.createObjectStore("doc_trigrams");
|
|
13
|
+
};
|
|
14
|
+
req.onsuccess = () => resolve(req.result);
|
|
15
|
+
req.onerror = () => reject(req.error);
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
/** Extract the set of trigrams for a piece of text. */
|
|
19
|
+
function extractTrigrams(text) {
|
|
20
|
+
const trigrams = /* @__PURE__ */ new Set();
|
|
21
|
+
const padded = ` ${text.toLowerCase()} `;
|
|
22
|
+
for (let i = 0; i <= padded.length - 3; i++) trigrams.add(padded.slice(i, i + 3));
|
|
23
|
+
return trigrams;
|
|
24
|
+
}
|
|
25
|
+
/** Merge trigrams from multiple texts into a single set. */
|
|
26
|
+
function extractAllTrigrams(texts) {
|
|
27
|
+
const result = /* @__PURE__ */ new Set();
|
|
28
|
+
for (const t of texts) for (const trigram of extractTrigrams(t)) result.add(trigram);
|
|
29
|
+
return result;
|
|
30
|
+
}
|
|
31
|
+
var SearchIndex = class {
|
|
32
|
+
constructor(serverOrigin) {
|
|
33
|
+
this.dbPromise = null;
|
|
34
|
+
this.db = null;
|
|
35
|
+
this.origin = serverOrigin;
|
|
36
|
+
}
|
|
37
|
+
getDb() {
|
|
38
|
+
if (!idbAvailable()) return Promise.resolve(null);
|
|
39
|
+
if (!this.dbPromise) this.dbPromise = openDb(this.origin).catch(() => null).then((db) => {
|
|
40
|
+
this.db = db;
|
|
41
|
+
return db;
|
|
42
|
+
});
|
|
43
|
+
return this.dbPromise;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Replace the index for docId with the given texts.
|
|
47
|
+
* Old trigram associations are removed before new ones are added.
|
|
48
|
+
*/
|
|
49
|
+
async index(docId, texts) {
|
|
50
|
+
const db = await this.getDb();
|
|
51
|
+
if (!db) return;
|
|
52
|
+
const newTrigrams = extractAllTrigrams(texts);
|
|
53
|
+
return new Promise((resolve, reject) => {
|
|
54
|
+
const tx = db.transaction(["postings", "doc_trigrams"], "readwrite");
|
|
55
|
+
tx.oncomplete = () => resolve();
|
|
56
|
+
tx.onerror = () => reject(tx.error);
|
|
57
|
+
const postings = tx.objectStore("postings");
|
|
58
|
+
const docTrigramsStore = tx.objectStore("doc_trigrams");
|
|
59
|
+
const oldReq = docTrigramsStore.get(docId);
|
|
60
|
+
oldReq.onsuccess = () => {
|
|
61
|
+
const oldTrigrams = oldReq.result ?? [];
|
|
62
|
+
let pending = oldTrigrams.length + newTrigrams.size + 1;
|
|
63
|
+
function done() {
|
|
64
|
+
pending--;
|
|
65
|
+
}
|
|
66
|
+
for (const trigram of oldTrigrams) {
|
|
67
|
+
const req = postings.get(trigram);
|
|
68
|
+
req.onsuccess = () => {
|
|
69
|
+
const updated = (req.result ?? []).filter((id) => id !== docId);
|
|
70
|
+
if (updated.length === 0) postings.delete(trigram);
|
|
71
|
+
else postings.put(updated, trigram);
|
|
72
|
+
done();
|
|
73
|
+
};
|
|
74
|
+
req.onerror = done;
|
|
75
|
+
}
|
|
76
|
+
for (const trigram of newTrigrams) {
|
|
77
|
+
const req = postings.get(trigram);
|
|
78
|
+
req.onsuccess = () => {
|
|
79
|
+
const list = req.result ?? [];
|
|
80
|
+
if (!list.includes(docId)) list.push(docId);
|
|
81
|
+
postings.put(list, trigram);
|
|
82
|
+
done();
|
|
83
|
+
};
|
|
84
|
+
req.onerror = done;
|
|
85
|
+
}
|
|
86
|
+
const writeReq = docTrigramsStore.put([...newTrigrams], docId);
|
|
87
|
+
writeReq.onsuccess = done;
|
|
88
|
+
writeReq.onerror = done;
|
|
89
|
+
};
|
|
90
|
+
oldReq.onerror = () => reject(oldReq.error);
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
/** Remove all indexed content for a document. */
|
|
94
|
+
async remove(docId) {
|
|
95
|
+
const db = await this.getDb();
|
|
96
|
+
if (!db) return;
|
|
97
|
+
return new Promise((resolve, reject) => {
|
|
98
|
+
const tx = db.transaction(["postings", "doc_trigrams"], "readwrite");
|
|
99
|
+
tx.oncomplete = () => resolve();
|
|
100
|
+
tx.onerror = () => reject(tx.error);
|
|
101
|
+
const postings = tx.objectStore("postings");
|
|
102
|
+
const docTrigramsStore = tx.objectStore("doc_trigrams");
|
|
103
|
+
const oldReq = docTrigramsStore.get(docId);
|
|
104
|
+
oldReq.onsuccess = () => {
|
|
105
|
+
const oldTrigrams = oldReq.result ?? [];
|
|
106
|
+
for (const trigram of oldTrigrams) {
|
|
107
|
+
const req = postings.get(trigram);
|
|
108
|
+
req.onsuccess = () => {
|
|
109
|
+
const updated = (req.result ?? []).filter((id) => id !== docId);
|
|
110
|
+
if (updated.length === 0) postings.delete(trigram);
|
|
111
|
+
else postings.put(updated, trigram);
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
docTrigramsStore.delete(docId);
|
|
115
|
+
};
|
|
116
|
+
oldReq.onerror = () => reject(oldReq.error);
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Search for documents matching the query.
|
|
121
|
+
* Returns results sorted by score (matching trigram count) descending.
|
|
122
|
+
*/
|
|
123
|
+
async search(query, limit = 20) {
|
|
124
|
+
const db = await this.getDb();
|
|
125
|
+
if (!db) return [];
|
|
126
|
+
const queryTrigrams = [...extractTrigrams(query)];
|
|
127
|
+
if (queryTrigrams.length === 0) return [];
|
|
128
|
+
const maxScoreEntries = limit * 10;
|
|
129
|
+
return new Promise((resolve, reject) => {
|
|
130
|
+
const tx = db.transaction("postings", "readonly");
|
|
131
|
+
const postings = tx.objectStore("postings");
|
|
132
|
+
const scores = /* @__PURE__ */ new Map();
|
|
133
|
+
let remaining = queryTrigrams.length;
|
|
134
|
+
for (const trigram of queryTrigrams) {
|
|
135
|
+
const req = postings.get(trigram);
|
|
136
|
+
req.onsuccess = () => {
|
|
137
|
+
const docIds = req.result ?? [];
|
|
138
|
+
for (const docId of docIds) {
|
|
139
|
+
scores.set(docId, (scores.get(docId) ?? 0) + 1);
|
|
140
|
+
if (scores.size >= maxScoreEntries) break;
|
|
141
|
+
}
|
|
142
|
+
remaining--;
|
|
143
|
+
if (remaining === 0) resolve([...scores.entries()].map(([docId, score]) => ({
|
|
144
|
+
docId,
|
|
145
|
+
score
|
|
146
|
+
})).sort((a, b) => b.score - a.score).slice(0, limit));
|
|
147
|
+
};
|
|
148
|
+
req.onerror = () => {
|
|
149
|
+
remaining--;
|
|
150
|
+
if (remaining === 0) resolve([...scores.entries()].map(([docId, score]) => ({
|
|
151
|
+
docId,
|
|
152
|
+
score
|
|
153
|
+
})).sort((a, b) => b.score - a.score).slice(0, limit));
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
tx.onerror = () => reject(tx.error);
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
destroy() {
|
|
160
|
+
this.db?.close();
|
|
161
|
+
this.db = null;
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
//#endregion
|
|
166
|
+
export { SearchIndex };
|
|
167
|
+
//# sourceMappingURL=SearchIndex.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SearchIndex.js","names":[],"sources":["../../src/SearchIndex.ts"],"sourcesContent":["/**\n * IndexedDB-backed trigram full-text search index.\n *\n * Generic: caller passes (docId, texts[]) — works for Y.Doc text content,\n * file names, document titles, or any other text. No Y.js coupling.\n *\n * Algorithm: trigram inverted index.\n * - Each document is decomposed into overlapping 3-character windows.\n * - The \"postings\" store maps trigram → [docId, ...].\n * - The \"doc_trigrams\" store maps docId → [trigram, ...] for efficient removal.\n * - search() scores by number of query trigrams that match.\n *\n * IDB transactions that touch multiple stores use the callback-only pattern\n * (not async/await inside a transaction) to avoid the transaction auto-commit\n * issue across microtask boundaries.\n */\n\nimport type { SearchResult } from \"./types.ts\";\n\nconst DB_VERSION = 1;\n\nfunction idbAvailable(): boolean {\n\treturn typeof globalThis !== \"undefined\" && \"indexedDB\" in globalThis;\n}\n\nfunction openDb(origin: string): Promise<IDBDatabase> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst req = globalThis.indexedDB.open(`abracadabra:search:${origin}`, DB_VERSION);\n\n\t\treq.onupgradeneeded = (event) => {\n\t\t\tconst db = (event.target as IDBOpenDBRequest).result;\n\t\t\tif (!db.objectStoreNames.contains(\"postings\")) {\n\t\t\t\tdb.createObjectStore(\"postings\");\n\t\t\t}\n\t\t\tif (!db.objectStoreNames.contains(\"doc_trigrams\")) {\n\t\t\t\tdb.createObjectStore(\"doc_trigrams\");\n\t\t\t}\n\t\t};\n\n\t\treq.onsuccess = () => resolve(req.result);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\n/** Extract the set of trigrams for a piece of text. */\nfunction extractTrigrams(text: string): Set<string> {\n\tconst trigrams = new Set<string>();\n\tconst padded = ` ${text.toLowerCase()} `;\n\tfor (let i = 0; i <= padded.length - 3; i++) {\n\t\ttrigrams.add(padded.slice(i, i + 3));\n\t}\n\treturn trigrams;\n}\n\n/** Merge trigrams from multiple texts into a single set. */\nfunction extractAllTrigrams(texts: string[]): Set<string> {\n\tconst result = new Set<string>();\n\tfor (const t of texts) {\n\t\tfor (const trigram of extractTrigrams(t)) {\n\t\t\tresult.add(trigram);\n\t\t}\n\t}\n\treturn result;\n}\n\nexport class SearchIndex {\n\tprivate readonly origin: string;\n\tprivate dbPromise: Promise<IDBDatabase | null> | null = null;\n\tprivate db: IDBDatabase | null = null;\n\n\tconstructor(serverOrigin: string) {\n\t\tthis.origin = serverOrigin;\n\t}\n\n\tprivate getDb(): Promise<IDBDatabase | null> {\n\t\tif (!idbAvailable()) return Promise.resolve(null);\n\t\tif (!this.dbPromise) {\n\t\t\tthis.dbPromise = openDb(this.origin)\n\t\t\t\t.catch(() => null)\n\t\t\t\t.then((db) => {\n\t\t\t\t\tthis.db = db;\n\t\t\t\t\treturn db;\n\t\t\t\t});\n\t\t}\n\t\treturn this.dbPromise;\n\t}\n\n\t/**\n\t * Replace the index for docId with the given texts.\n\t * Old trigram associations are removed before new ones are added.\n\t */\n\tasync index(docId: string, texts: string[]): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\n\t\tconst newTrigrams = extractAllTrigrams(texts);\n\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tconst tx = db.transaction([\"postings\", \"doc_trigrams\"], \"readwrite\");\n\t\t\ttx.oncomplete = () => resolve();\n\t\t\ttx.onerror = () => reject(tx.error);\n\n\t\t\tconst postings = tx.objectStore(\"postings\");\n\t\t\tconst docTrigramsStore = tx.objectStore(\"doc_trigrams\");\n\n\t\t\t// Step 1: read old trigrams for this doc\n\t\t\tconst oldReq = docTrigramsStore.get(docId);\n\t\t\toldReq.onsuccess = () => {\n\t\t\t\tconst oldTrigrams: string[] = oldReq.result ?? [];\n\t\t\t\tlet pending = oldTrigrams.length + newTrigrams.size + 1; // +1 for doc_trigrams write\n\n\t\t\t\tfunction done() {\n\t\t\t\t\tpending--;\n\t\t\t\t\t// tx.oncomplete fires naturally once all requests settle\n\t\t\t\t}\n\n\t\t\t\t// Step 2: remove docId from each old trigram's posting list\n\t\t\t\tfor (const trigram of oldTrigrams) {\n\t\t\t\t\tconst req = postings.get(trigram);\n\t\t\t\t\treq.onsuccess = () => {\n\t\t\t\t\t\tconst list: string[] = req.result ?? [];\n\t\t\t\t\t\tconst updated = list.filter((id) => id !== docId);\n\t\t\t\t\t\tif (updated.length === 0) {\n\t\t\t\t\t\t\tpostings.delete(trigram);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpostings.put(updated, trigram);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdone();\n\t\t\t\t\t};\n\t\t\t\t\treq.onerror = done;\n\t\t\t\t}\n\n\t\t\t\t// Step 3: add docId to each new trigram's posting list\n\t\t\t\tfor (const trigram of newTrigrams) {\n\t\t\t\t\tconst req = postings.get(trigram);\n\t\t\t\t\treq.onsuccess = () => {\n\t\t\t\t\t\tconst list: string[] = req.result ?? [];\n\t\t\t\t\t\tif (!list.includes(docId)) {\n\t\t\t\t\t\t\tlist.push(docId);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpostings.put(list, trigram);\n\t\t\t\t\t\tdone();\n\t\t\t\t\t};\n\t\t\t\t\treq.onerror = done;\n\t\t\t\t}\n\n\t\t\t\t// Step 4: save new trigram set for this doc\n\t\t\t\tconst writeReq = docTrigramsStore.put([...newTrigrams], docId);\n\t\t\t\twriteReq.onsuccess = done;\n\t\t\t\twriteReq.onerror = done;\n\t\t\t};\n\t\t\toldReq.onerror = () => reject(oldReq.error);\n\t\t});\n\t}\n\n\t/** Remove all indexed content for a document. */\n\tasync remove(docId: string): Promise<void> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return;\n\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tconst tx = db.transaction([\"postings\", \"doc_trigrams\"], \"readwrite\");\n\t\t\ttx.oncomplete = () => resolve();\n\t\t\ttx.onerror = () => reject(tx.error);\n\n\t\t\tconst postings = tx.objectStore(\"postings\");\n\t\t\tconst docTrigramsStore = tx.objectStore(\"doc_trigrams\");\n\n\t\t\tconst oldReq = docTrigramsStore.get(docId);\n\t\t\toldReq.onsuccess = () => {\n\t\t\t\tconst oldTrigrams: string[] = oldReq.result ?? [];\n\n\t\t\t\tfor (const trigram of oldTrigrams) {\n\t\t\t\t\tconst req = postings.get(trigram);\n\t\t\t\t\treq.onsuccess = () => {\n\t\t\t\t\t\tconst list: string[] = req.result ?? [];\n\t\t\t\t\t\tconst updated = list.filter((id) => id !== docId);\n\t\t\t\t\t\tif (updated.length === 0) {\n\t\t\t\t\t\t\tpostings.delete(trigram);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpostings.put(updated, trigram);\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tdocTrigramsStore.delete(docId);\n\t\t\t};\n\t\t\toldReq.onerror = () => reject(oldReq.error);\n\t\t});\n\t}\n\n\t/**\n\t * Search for documents matching the query.\n\t * Returns results sorted by score (matching trigram count) descending.\n\t */\n\tasync search(query: string, limit = 20): Promise<SearchResult[]> {\n\t\tconst db = await this.getDb();\n\t\tif (!db) return [];\n\n\t\tconst queryTrigrams = [...extractTrigrams(query)];\n\t\tif (queryTrigrams.length === 0) return [];\n\n\t\tconst maxScoreEntries = limit * 10;\n\n\t\treturn new Promise<SearchResult[]>((resolve, reject) => {\n\t\t\tconst tx = db.transaction(\"postings\", \"readonly\");\n\t\t\tconst postings = tx.objectStore(\"postings\");\n\t\t\tconst scores = new Map<string, number>();\n\t\t\tlet remaining = queryTrigrams.length;\n\n\t\t\tfor (const trigram of queryTrigrams) {\n\t\t\t\tconst req = postings.get(trigram);\n\t\t\t\treq.onsuccess = () => {\n\t\t\t\t\tconst docIds: string[] = req.result ?? [];\n\t\t\t\t\tfor (const docId of docIds) {\n\t\t\t\t\t\tscores.set(docId, (scores.get(docId) ?? 0) + 1);\n\t\t\t\t\t\tif (scores.size >= maxScoreEntries) break;\n\t\t\t\t\t}\n\t\t\t\t\tremaining--;\n\t\t\t\t\tif (remaining === 0) {\n\t\t\t\t\t\tconst results: SearchResult[] = [...scores.entries()]\n\t\t\t\t\t\t\t.map(([docId, score]) => ({ docId, score }))\n\t\t\t\t\t\t\t.sort((a, b) => b.score - a.score)\n\t\t\t\t\t\t\t.slice(0, limit);\n\t\t\t\t\t\tresolve(results);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\treq.onerror = () => {\n\t\t\t\t\tremaining--;\n\t\t\t\t\tif (remaining === 0) {\n\t\t\t\t\t\tconst results: SearchResult[] = [...scores.entries()]\n\t\t\t\t\t\t\t.map(([docId, score]) => ({ docId, score }))\n\t\t\t\t\t\t\t.sort((a, b) => b.score - a.score)\n\t\t\t\t\t\t\t.slice(0, limit);\n\t\t\t\t\t\tresolve(results);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\n\t\t\ttx.onerror = () => reject(tx.error);\n\t\t});\n\t}\n\n\t// ── Lifecycle ─────────────────────────────────────────────────────────────\n\n\tdestroy(): void {\n\t\tthis.db?.close();\n\t\tthis.db = null;\n\t}\n}\n"],"mappings":";AAmBA,MAAM,aAAa;AAEnB,SAAS,eAAwB;AAChC,QAAO,OAAO,eAAe,eAAe,eAAe;;AAG5D,SAAS,OAAO,QAAsC;AACrD,QAAO,IAAI,SAAS,SAAS,WAAW;EACvC,MAAM,MAAM,WAAW,UAAU,KAAK,sBAAsB,UAAU,WAAW;AAEjF,MAAI,mBAAmB,UAAU;GAChC,MAAM,KAAM,MAAM,OAA4B;AAC9C,OAAI,CAAC,GAAG,iBAAiB,SAAS,WAAW,CAC5C,IAAG,kBAAkB,WAAW;AAEjC,OAAI,CAAC,GAAG,iBAAiB,SAAS,eAAe,CAChD,IAAG,kBAAkB,eAAe;;AAItC,MAAI,kBAAkB,QAAQ,IAAI,OAAO;AACzC,MAAI,gBAAgB,OAAO,IAAI,MAAM;GACpC;;;AAIH,SAAS,gBAAgB,MAA2B;CACnD,MAAM,2BAAW,IAAI,KAAa;CAClC,MAAM,SAAS,IAAI,KAAK,aAAa,CAAC;AACtC,MAAK,IAAI,IAAI,GAAG,KAAK,OAAO,SAAS,GAAG,IACvC,UAAS,IAAI,OAAO,MAAM,GAAG,IAAI,EAAE,CAAC;AAErC,QAAO;;;AAIR,SAAS,mBAAmB,OAA8B;CAC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_FILE` env, else `~/.abracadabra/servers.json`. */
|
|
3
|
+
async function serverRegistryPath(override) {
|
|
4
|
+
const { homedir } = await import("node:os");
|
|
5
|
+
const { join } = await import("node:path");
|
|
6
|
+
return override ?? process.env.ABRA_SERVERS_FILE ?? join(homedir(), ".abracadabra", "servers.json");
|
|
7
|
+
}
|
|
8
|
+
/** Default per-server key-file path: `~/.abracadabra/keys/<alias>.key`. */
|
|
9
|
+
async function defaultKeyFileFor(alias) {
|
|
10
|
+
const { homedir } = await import("node:os");
|
|
11
|
+
const { join } = await import("node:path");
|
|
12
|
+
const safe = alias.replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
13
|
+
return join(homedir(), ".abracadabra", "keys", `${safe}.key`);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Load the registry from disk. A missing file yields an empty registry (never
|
|
17
|
+
* throws on absence). A malformed file throws so the caller can surface it.
|
|
18
|
+
*/
|
|
19
|
+
async function loadServerRegistry(path) {
|
|
20
|
+
const { existsSync } = await import("node:fs");
|
|
21
|
+
const { readFile } = await import("node:fs/promises");
|
|
22
|
+
const file = await serverRegistryPath(path);
|
|
23
|
+
if (!existsSync(file)) return { servers: {} };
|
|
24
|
+
const raw = await readFile(file, "utf8");
|
|
25
|
+
if (!raw.trim()) return { servers: {} };
|
|
26
|
+
let parsed;
|
|
27
|
+
try {
|
|
28
|
+
parsed = JSON.parse(raw);
|
|
29
|
+
} catch (err) {
|
|
30
|
+
throw new Error(`Malformed server registry at ${file}: ${err.message}`);
|
|
31
|
+
}
|
|
32
|
+
const reg = parsed;
|
|
33
|
+
return {
|
|
34
|
+
defaultAlias: reg.defaultAlias,
|
|
35
|
+
servers: reg.servers ?? {}
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/** Persist the registry, creating `~/.abracadabra/` with `0o700` if needed. */
|
|
39
|
+
async function saveServerRegistry(reg, path) {
|
|
40
|
+
const { existsSync } = await import("node:fs");
|
|
41
|
+
const { writeFile, mkdir } = await import("node:fs/promises");
|
|
42
|
+
const { dirname } = await import("node:path");
|
|
43
|
+
const file = await serverRegistryPath(path);
|
|
44
|
+
const dir = dirname(file);
|
|
45
|
+
if (!existsSync(dir)) await mkdir(dir, {
|
|
46
|
+
recursive: true,
|
|
47
|
+
mode: 448
|
|
48
|
+
});
|
|
49
|
+
await writeFile(file, `${JSON.stringify(reg, null, 2)}\n`, { mode: 384 });
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Resolve `aliasOrUrl` against the registry.
|
|
53
|
+
*
|
|
54
|
+
* - A known alias → its stored profile.
|
|
55
|
+
* - A bare URL (starts with `http://` / `https://`) → an ephemeral profile with
|
|
56
|
+
* a derived alias (the URL host) and a default per-host key file. This is NOT
|
|
57
|
+
* persisted; the caller decides whether to `addServer` it.
|
|
58
|
+
* - Anything else → `null` (unknown alias).
|
|
59
|
+
*/
|
|
60
|
+
async function resolveServer(reg, aliasOrUrl) {
|
|
61
|
+
const direct = reg.servers[aliasOrUrl];
|
|
62
|
+
if (direct) return direct;
|
|
63
|
+
if (/^https?:\/\//i.test(aliasOrUrl)) {
|
|
64
|
+
let alias = aliasOrUrl;
|
|
65
|
+
try {
|
|
66
|
+
alias = new URL(aliasOrUrl).host || aliasOrUrl;
|
|
67
|
+
} catch {}
|
|
68
|
+
return {
|
|
69
|
+
alias,
|
|
70
|
+
url: aliasOrUrl.replace(/\/+$/, ""),
|
|
71
|
+
keyFile: await defaultKeyFileFor(alias)
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
/** Add or replace a profile. The first server added becomes the default. */
|
|
77
|
+
function addServer(reg, profile) {
|
|
78
|
+
const servers = {
|
|
79
|
+
...reg.servers,
|
|
80
|
+
[profile.alias]: profile
|
|
81
|
+
};
|
|
82
|
+
return {
|
|
83
|
+
defaultAlias: reg.defaultAlias && reg.servers[reg.defaultAlias] ? reg.defaultAlias : profile.alias,
|
|
84
|
+
servers
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/** Remove a profile by alias. Clears `defaultAlias` if it pointed at it. */
|
|
88
|
+
function removeServer(reg, alias) {
|
|
89
|
+
if (!reg.servers[alias]) return reg;
|
|
90
|
+
const servers = { ...reg.servers };
|
|
91
|
+
delete servers[alias];
|
|
92
|
+
let defaultAlias = reg.defaultAlias;
|
|
93
|
+
if (defaultAlias === alias) defaultAlias = Object.keys(servers)[0];
|
|
94
|
+
return {
|
|
95
|
+
defaultAlias,
|
|
96
|
+
servers
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/** Mark `alias` as the default. Throws if the alias is unknown. */
|
|
100
|
+
function setDefault(reg, alias) {
|
|
101
|
+
if (!reg.servers[alias]) throw new Error(`Unknown server alias: ${alias}`);
|
|
102
|
+
return {
|
|
103
|
+
...reg,
|
|
104
|
+
defaultAlias: alias
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Seed a `default` profile from a legacy single-key setup when the registry is
|
|
109
|
+
* empty. Existing MCP/CLI users keep `~/.abracadabra/{agent,cli}.key` and an
|
|
110
|
+
* `ABRA_URL`; without this they'd lose their identity the first time the
|
|
111
|
+
* registry takes over. Returns the (possibly unchanged) registry; the caller
|
|
112
|
+
* persists if `migrated` is true.
|
|
113
|
+
*
|
|
114
|
+
* @param url the legacy `ABRA_URL` (no migration without it).
|
|
115
|
+
* @param legacyKeyFile path to the legacy key (e.g. `~/.abracadabra/agent.key`).
|
|
116
|
+
*/
|
|
117
|
+
async function migrateLegacyDefault(reg, url, legacyKeyFile) {
|
|
118
|
+
if (!url || Object.keys(reg.servers).length > 0) return {
|
|
119
|
+
registry: reg,
|
|
120
|
+
migrated: false
|
|
121
|
+
};
|
|
122
|
+
const { existsSync } = await import("node:fs");
|
|
123
|
+
if (!existsSync(legacyKeyFile)) return {
|
|
124
|
+
registry: reg,
|
|
125
|
+
migrated: false
|
|
126
|
+
};
|
|
127
|
+
return {
|
|
128
|
+
registry: addServer(reg, {
|
|
129
|
+
alias: "default",
|
|
130
|
+
url: url.replace(/\/+$/, ""),
|
|
131
|
+
keyFile: legacyKeyFile
|
|
132
|
+
}),
|
|
133
|
+
migrated: true
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
//#endregion
|
|
138
|
+
export { addServer, defaultKeyFileFor, loadServerRegistry, migrateLegacyDefault, removeServer, resolveServer, saveServerRegistry, serverRegistryPath, setDefault };
|
|
139
|
+
//# sourceMappingURL=ServerRegistry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ServerRegistry.js","names":[],"sources":["../../src/ServerRegistry.ts"],"sourcesContent":["/**\n * ServerRegistry — a tiny on-disk registry of Abracadabra servers shared by the\n * Node-side consumers (`@abraca/mcp`, `@abraca/cli`).\n *\n * Historically each daemon read a single `ABRA_URL` and a single key file, so it\n * could only ever talk to one server. The registry lets a user remember several\n * servers by alias, keep a per-server identity (key file), and switch between\n * them — both from the CLI (`server add/use/login`) and from a running MCP agent\n * (`connect_server`/`switch_server`).\n *\n * Format: JSON at `~/.abracadabra/servers.json` (override with `ABRA_SERVERS_FILE`):\n *\n * {\n * \"defaultAlias\": \"coop\",\n * \"servers\": {\n * \"coop\": { \"alias\": \"coop\", \"url\": \"https://coop.cou.sh\",\n * \"keyFile\": \"/home/me/.abracadabra/keys/coop.key\" }\n * }\n * }\n *\n * Node-only: filesystem access is via dynamic `import(\"node:…\")`, so importing\n * this module from a browser bundle is safe — only *calling* the load/save\n * helpers requires Node.\n */\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\n/** A single remembered server. */\nexport interface ServerProfile {\n\t/** Short, unique handle used on the CLI / in MCP tools. */\n\talias: string;\n\t/** Base URL, e.g. `https://coop.cou.sh`. */\n\turl: string;\n\t/** Path to this server's Ed25519 key file (per-server identity). */\n\tkeyFile: string;\n\t/** Display name presented to the server (presence / registration). */\n\tdisplayName?: string;\n\t/** Presence color (HSL string). */\n\tcolor?: string;\n\t/** Invite/registration token, when the server is invite-only. */\n\tinviteCode?: string;\n}\n\n/** The whole registry: a map of profiles plus which alias is the default. */\nexport interface ServerRegistry {\n\t/** Alias used when no `--server` / `connect_server` target is given. */\n\tdefaultAlias?: string;\n\tservers: Record<string, ServerProfile>;\n}\n\n// ── Paths ──────────────────────────────────────────────────────────────────\n\n/** Resolve the registry path: `ABRA_SERVERS_FILE` env, else `~/.abracadabra/servers.json`. */\nexport async function serverRegistryPath(override?: string): Promise<string> {\n\tconst { homedir } = await import(\"node:os\");\n\tconst { join } = await import(\"node:path\");\n\treturn (\n\t\toverride ??\n\t\tprocess.env.ABRA_SERVERS_FILE ??\n\t\tjoin(homedir(), \".abracadabra\", \"servers.json\")\n\t);\n}\n\n/** Default per-server key-file path: `~/.abracadabra/keys/<alias>.key`. */\nexport async function defaultKeyFileFor(alias: string): Promise<string> {\n\tconst { homedir } = await import(\"node:os\");\n\tconst { join } = await import(\"node:path\");\n\tconst safe = alias.replace(/[^a-zA-Z0-9._-]/g, \"_\");\n\treturn join(homedir(), \".abracadabra\", \"keys\", `${safe}.key`);\n}\n\n// ── Load / save ────────────────────────────────────────────────────────────\n\n/**\n * Load the registry from disk. A missing file yields an empty registry (never\n * throws on absence). A malformed file throws so the caller can surface it.\n */\nexport async function loadServerRegistry(\n\tpath?: string,\n): Promise<ServerRegistry> {\n\tconst { existsSync } = await import(\"node:fs\");\n\tconst { readFile } = await import(\"node:fs/promises\");\n\tconst file = await serverRegistryPath(path);\n\n\tif (!existsSync(file)) return { servers: {} };\n\n\tconst raw = await readFile(file, \"utf8\");\n\tif (!raw.trim()) return { servers: {} };\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch (err) {\n\t\tthrow new Error(\n\t\t\t`Malformed server registry at ${file}: ${(err as Error).message}`,\n\t\t);\n\t}\n\tconst reg = parsed as Partial<ServerRegistry>;\n\treturn {\n\t\tdefaultAlias: reg.defaultAlias,\n\t\tservers: reg.servers ?? {},\n\t};\n}\n\n/** Persist the registry, creating `~/.abracadabra/` with `0o700` if needed. */\nexport async function saveServerRegistry(\n\treg: ServerRegistry,\n\tpath?: string,\n): Promise<void> {\n\tconst { existsSync } = await import(\"node:fs\");\n\tconst { writeFile, mkdir } = await import(\"node:fs/promises\");\n\tconst { dirname } = await import(\"node:path\");\n\tconst file = await serverRegistryPath(path);\n\tconst dir = dirname(file);\n\tif (!existsSync(dir)) await mkdir(dir, { recursive: true, mode: 0o700 });\n\tawait writeFile(file, `${JSON.stringify(reg, null, 2)}\\n`, { mode: 0o600 });\n}\n\n// ── Resolution ─────────────────────────────────────────────────────────────\n\n/**\n * Resolve `aliasOrUrl` against the registry.\n *\n * - A known alias → its stored profile.\n * - A bare URL (starts with `http://` / `https://`) → an ephemeral profile with\n * a derived alias (the URL host) and a default per-host key file. This is NOT\n * persisted; the caller decides whether to `addServer` it.\n * - Anything else → `null` (unknown alias).\n */\nexport async function resolveServer(\n\treg: ServerRegistry,\n\taliasOrUrl: string,\n): Promise<ServerProfile | null> {\n\tconst direct = reg.servers[aliasOrUrl];\n\tif (direct) return direct;\n\n\tif (/^https?:\\/\\//i.test(aliasOrUrl)) {\n\t\tlet alias = aliasOrUrl;\n\t\ttry {\n\t\t\talias = new URL(aliasOrUrl).host || aliasOrUrl;\n\t\t} catch {\n\t\t\t/* keep the raw string as the alias */\n\t\t}\n\t\treturn {\n\t\t\talias,\n\t\t\turl: aliasOrUrl.replace(/\\/+$/, \"\"),\n\t\t\tkeyFile: await defaultKeyFileFor(alias),\n\t\t};\n\t}\n\n\treturn null;\n}\n\n// ── Mutators (return a new registry; caller persists) ────────────────────────\n\n/** Add or replace a profile. The first server added becomes the default. */\nexport function addServer(\n\treg: ServerRegistry,\n\tprofile: ServerProfile,\n): ServerRegistry {\n\tconst servers = { ...reg.servers, [profile.alias]: profile };\n\tconst defaultAlias =\n\t\treg.defaultAlias && reg.servers[reg.defaultAlias]\n\t\t\t? reg.defaultAlias\n\t\t\t: profile.alias;\n\treturn { defaultAlias, servers };\n}\n\n/** Remove a profile by alias. Clears `defaultAlias` if it pointed at it. */\nexport function removeServer(\n\treg: ServerRegistry,\n\talias: string,\n): ServerRegistry {\n\tif (!reg.servers[alias]) return reg;\n\tconst servers = { ...reg.servers };\n\tdelete servers[alias];\n\tlet defaultAlias = reg.defaultAlias;\n\tif (defaultAlias === alias) {\n\t\tdefaultAlias = Object.keys(servers)[0];\n\t}\n\treturn { defaultAlias, servers };\n}\n\n/** Mark `alias` as the default. Throws if the alias is unknown. */\nexport function setDefault(reg: ServerRegistry, alias: string): ServerRegistry {\n\tif (!reg.servers[alias]) {\n\t\tthrow new Error(`Unknown server alias: ${alias}`);\n\t}\n\treturn { ...reg, defaultAlias: alias };\n}\n\n// ── Migration ────────────────────────────────────────────────────────────────\n\n/**\n * Seed a `default` profile from a legacy single-key setup when the registry is\n * empty. Existing MCP/CLI users keep `~/.abracadabra/{agent,cli}.key` and an\n * `ABRA_URL`; without this they'd lose their identity the first time the\n * registry takes over. Returns the (possibly unchanged) registry; the caller\n * persists if `migrated` is true.\n *\n * @param url the legacy `ABRA_URL` (no migration without it).\n * @param legacyKeyFile path to the legacy key (e.g. `~/.abracadabra/agent.key`).\n */\nexport async function migrateLegacyDefault(\n\treg: ServerRegistry,\n\turl: string | undefined,\n\tlegacyKeyFile: string,\n): Promise<{ registry: ServerRegistry; migrated: boolean }> {\n\tif (!url || Object.keys(reg.servers).length > 0) {\n\t\treturn { registry: reg, migrated: false };\n\t}\n\tconst { existsSync } = await import(\"node:fs\");\n\tif (!existsSync(legacyKeyFile)) return { registry: reg, migrated: false };\n\n\tconst profile: ServerProfile = {\n\t\talias: \"default\",\n\t\turl: url.replace(/\\/+$/, \"\"),\n\t\tkeyFile: legacyKeyFile,\n\t};\n\treturn { registry: addServer(reg, profile), migrated: true };\n}\n"],"mappings":";;AAqDA,eAAsB,mBAAmB,UAAoC;CAC5E,MAAM,EAAE,YAAY,MAAM,OAAO;CACjC,M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U,KALE;GAC9B,OAAO;GACP,KAAK,IAAI,QAAQ,QAAQ,GAAG;GAC5B,SAAS;GACT,CACyC;EAAE,UAAU;EAAM"}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
//#region packages/provider/src/ServerReset.ts
|
|
2
|
+
/**
|
|
3
|
+
* Detect that a server's database has been REPLACED, and drop this browser's
|
|
4
|
+
* caches for it before anything re-pushes them.
|
|
5
|
+
*
|
|
6
|
+
* ## The bug
|
|
7
|
+
*
|
|
8
|
+
* Deleting a backend's database does not give you a clean server. Every browser
|
|
9
|
+
* that was connected still holds that space's CRDT state in IndexedDB, and on
|
|
10
|
+
* reconnect it re-pushes the old tree into the fresh one. A seeder then adds its
|
|
11
|
+
* own on top and you get every page twice — `/about` AND `/about-1`. Repeat the
|
|
12
|
+
* cycle and it MULTIPLIES: `-2`, `-3`, `-4`.
|
|
13
|
+
*
|
|
14
|
+
* This is inherent to a CRDT and cannot be fixed downstream. A deleted database
|
|
15
|
+
* is not a tombstone; it is a peer that lost its memory, and the client is the
|
|
16
|
+
* one holding the newer state. No idempotency guard can see it — by the time one
|
|
17
|
+
* runs, the re-pushed tree looks exactly like real content.
|
|
18
|
+
*
|
|
19
|
+
* It is not a development-only annoyance. The expensive case is a production
|
|
20
|
+
* restore from backup, where the peers re-pushing stale trees are visitors who
|
|
21
|
+
* will never read a release note.
|
|
22
|
+
*
|
|
23
|
+
* ## Why the server can be believed
|
|
24
|
+
*
|
|
25
|
+
* The server mints a `server_id` and persists it beside its database. It
|
|
26
|
+
* survives restarts and changes when, and only when, that database is replaced.
|
|
27
|
+
* So it states outright what a CRDT cannot work out for itself: *the peer you
|
|
28
|
+
* are syncing with is not the one you have been talking to.*
|
|
29
|
+
*
|
|
30
|
+
* ## What gets dropped
|
|
31
|
+
*
|
|
32
|
+
* Everything this SDK scopes to a server, which is more than the document
|
|
33
|
+
* caches:
|
|
34
|
+
*
|
|
35
|
+
* | store | written by |
|
|
36
|
+
* |---|---|
|
|
37
|
+
* | `abracadabra:<host>/<docId>` | {@link OfflineStore} |
|
|
38
|
+
* | `abracadabra:meta-cache:<host>` | `DocumentCache` |
|
|
39
|
+
* | `abracadabra:files:<host>` | `FileBlobStore` |
|
|
40
|
+
* | `abracadabra:bgsync:<host>` | `BackgroundSyncPersistence` |
|
|
41
|
+
* | `abracadabra:search:<host>` | `SearchIndex` |
|
|
42
|
+
*
|
|
43
|
+
* One ANCHORED rule covers all five shapes, so nothing here has to stay in step
|
|
44
|
+
* with how each store builds its key. Anchored rather than a substring test on
|
|
45
|
+
* purpose — see {@link isServerScopedStore}, where the naive version would have
|
|
46
|
+
* cleared a different server's caches.
|
|
47
|
+
*
|
|
48
|
+
* `abracadabra:identity` is deliberately NOT dropped. It is this browser's
|
|
49
|
+
* keypair across every server it talks to; clearing it would sign the user out
|
|
50
|
+
* of all of them because one of them was reinstalled.
|
|
51
|
+
*/
|
|
52
|
+
/** Where the last-seen id for a host is remembered. */
|
|
53
|
+
const STORAGE_PREFIX = "abracadabra:server-id:";
|
|
54
|
+
/**
|
|
55
|
+
* Stores that belong to no particular server and must survive a reset.
|
|
56
|
+
*
|
|
57
|
+
* `abracadabra:identity` is this browser's keypair for EVERY server it talks to,
|
|
58
|
+
* so dropping it because one server was reinstalled would sign the user out of
|
|
59
|
+
* all of them. Listed explicitly rather than relying on the anchored match, so
|
|
60
|
+
* that a future store named after a host cannot take it by accident.
|
|
61
|
+
*/
|
|
62
|
+
const GLOBAL_STORES = new Set(["abracadabra:identity", "abracadabra:softkey"]);
|
|
63
|
+
function storageAvailable() {
|
|
64
|
+
try {
|
|
65
|
+
return typeof globalThis !== "undefined" && "localStorage" in globalThis && "indexedDB" in globalThis;
|
|
66
|
+
} catch {
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Does this database belong to the given server?
|
|
72
|
+
*
|
|
73
|
+
* The match is ANCHORED, and it has to be. A plain `name.includes(host)` looks
|
|
74
|
+
* right and is wrong in a way that destroys data: `other.example.com:3011`
|
|
75
|
+
* contains `example.com:3011`, so clearing one server's caches would delete a
|
|
76
|
+
* DIFFERENT server's — the exact "too broad" failure this guard exists to avoid.
|
|
77
|
+
* A unit test covers that pair.
|
|
78
|
+
*
|
|
79
|
+
* Three anchored shapes are needed, because the stores are NOT consistently
|
|
80
|
+
* scoped and pretending otherwise silently misses some:
|
|
81
|
+
*
|
|
82
|
+
* - `<host>/…` — {@link OfflineStore}, keyed `<host>/<docId>`
|
|
83
|
+
* - `…:<host>` — a namespaced store handed a bare host
|
|
84
|
+
* - `…://<host>` — a namespaced store handed a full URL. Real, not hypothetical:
|
|
85
|
+
* `@abraca/nuxt` passes `serverUrl` to `FileBlobStore`, so the database is
|
|
86
|
+
* named `abracadabra:files:http://example.com:3011`. Measured in a live
|
|
87
|
+
* browser; a rule written only for the first two shapes left it behind, which
|
|
88
|
+
* is a whole file cache surviving a wipe.
|
|
89
|
+
*/
|
|
90
|
+
function isServerScopedStore(name, host) {
|
|
91
|
+
if (!name.startsWith("abracadabra:")) return false;
|
|
92
|
+
if (GLOBAL_STORES.has(name)) return false;
|
|
93
|
+
const rest = name.slice(12);
|
|
94
|
+
return rest === host || rest.startsWith(`${host}/`) || rest.endsWith(`:${host}`) || rest.endsWith(`://${host}`);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Compare the server's identity against the one this browser last saw, and drop
|
|
98
|
+
* every cache belonging to it if the database has been replaced.
|
|
99
|
+
*
|
|
100
|
+
* **Call this before opening any provider.** Once a provider holds an IndexedDB
|
|
101
|
+
* handle, `deleteDatabase` blocks instead of deleting and the stale tree is
|
|
102
|
+
* already queued for re-push — the deletion completes later, having achieved
|
|
103
|
+
* nothing. Any store in that position comes back in `blocked`.
|
|
104
|
+
*
|
|
105
|
+
* Conservative by design:
|
|
106
|
+
*
|
|
107
|
+
* - the FIRST time a host is seen, the id is recorded and nothing is deleted —
|
|
108
|
+
* a new visitor must not have caches cleared for having no history;
|
|
109
|
+
* - a browser with no `indexedDB`/`localStorage` is a no-op;
|
|
110
|
+
* - it never throws. Failing to tidy a cache must not stop an app from starting.
|
|
111
|
+
*
|
|
112
|
+
* @param host The server's `host` (`example.com:3011`) — the same value
|
|
113
|
+
* providers scope their stores by. Not the full origin: the
|
|
114
|
+
* scheme is not part of a server's cache identity here.
|
|
115
|
+
* @param serverId `server_id` from `GET /info`.
|
|
116
|
+
*/
|
|
117
|
+
async function dropCachesIfServerReplaced(host, serverId) {
|
|
118
|
+
if (!storageAvailable() || !host || !serverId) return null;
|
|
119
|
+
const key = STORAGE_PREFIX + host;
|
|
120
|
+
let previousServerId = null;
|
|
121
|
+
try {
|
|
122
|
+
previousServerId = globalThis.localStorage.getItem(key);
|
|
123
|
+
} catch {
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
if (previousServerId === null) {
|
|
127
|
+
try {
|
|
128
|
+
globalThis.localStorage.setItem(key, serverId);
|
|
129
|
+
} catch {}
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
if (previousServerId === serverId) return null;
|
|
133
|
+
const cleared = [];
|
|
134
|
+
const blocked = [];
|
|
135
|
+
try {
|
|
136
|
+
const doomed = (await globalThis.indexedDB.databases?.() ?? []).map((d) => d.name).filter((n) => !!n && isServerScopedStore(n, host));
|
|
137
|
+
await Promise.all(doomed.map((name) => new Promise((resolve) => {
|
|
138
|
+
const request = globalThis.indexedDB.deleteDatabase(name);
|
|
139
|
+
request.onsuccess = () => {
|
|
140
|
+
cleared.push(name);
|
|
141
|
+
resolve();
|
|
142
|
+
};
|
|
143
|
+
request.onerror = () => resolve();
|
|
144
|
+
request.onblocked = () => {
|
|
145
|
+
blocked.push(name);
|
|
146
|
+
resolve();
|
|
147
|
+
};
|
|
148
|
+
})));
|
|
149
|
+
} catch {}
|
|
150
|
+
try {
|
|
151
|
+
globalThis.localStorage.setItem(key, serverId);
|
|
152
|
+
} catch {}
|
|
153
|
+
return {
|
|
154
|
+
previousServerId,
|
|
155
|
+
serverId,
|
|
156
|
+
cleared,
|
|
157
|
+
blocked
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
/** Forget what we know about a host, so the next check treats it as new. */
|
|
161
|
+
function forgetServerIdentity(host) {
|
|
162
|
+
if (!storageAvailable() || !host) return;
|
|
163
|
+
try {
|
|
164
|
+
globalThis.localStorage.removeItem(STORAGE_PREFIX + host);
|
|
165
|
+
} catch {}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
//#endregion
|
|
169
|
+
export { dropCachesIfServerReplaced, forgetServerIdentity, isServerScopedStore };
|
|
170
|
+
//# sourceMappingURL=ServerReset.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ServerReset.js","names":[],"sources":["../../src/ServerReset.ts"],"sourcesContent":["/**\n * Detect that a server's database has been REPLACED, and drop this browser's\n * caches for it before anything re-pushes them.\n *\n * ## The bug\n *\n * Deleting a backend's database does not give you a clean server. Every browser\n * that was connected still holds that space's CRDT state in IndexedDB, and on\n * reconnect it re-pushes the old tree into the fresh one. A seeder then adds its\n * own on top and you get every page twice — `/about` AND `/about-1`. Repeat the\n * cycle and it MULTIPLIES: `-2`, `-3`, `-4`.\n *\n * This is inherent to a CRDT and cannot be fixed downstream. A deleted database\n * is not a tombstone; it is a peer that lost its memory, and the client is the\n * one holding the newer state. No idempotency guard can see it — by the time one\n * runs, the re-pushed tree looks exactly like real content.\n *\n * It is not a development-only annoyance. The expensive case is a production\n * restore from backup, where the peers re-pushing stale trees are visitors who\n * will never read a release note.\n *\n * ## Why the server can be believed\n *\n * The server mints a `server_id` and persists it beside its database. It\n * survives restarts and changes when, and only when, that database is replaced.\n * So it states outright what a CRDT cannot work out for itself: *the peer you\n * are syncing with is not the one you have been talking to.*\n *\n * ## What gets dropped\n *\n * Everything this SDK scopes to a server, which is more than the document\n * caches:\n *\n * | store | written by |\n * |---|---|\n * | `abracadabra:<host>/<docId>` | {@link OfflineStore} |\n * | `abracadabra:meta-cache:<host>` | `DocumentCache` |\n * | `abracadabra:files:<host>` | `FileBlobStore` |\n * | `abracadabra:bgsync:<host>` | `BackgroundSyncPersistence` |\n * | `abracadabra:search:<host>` | `SearchIndex` |\n *\n * One ANCHORED rule covers all five shapes, so nothing here has to stay in step\n * with how each store builds its key. Anchored rather than a substring test on\n * purpose — see {@link isServerScopedStore}, where the naive version would have\n * cleared a different server's caches.\n *\n * `abracadabra:identity` is deliberately NOT dropped. It is this browser's\n * keypair across every server it talks to; clearing it would sign the user out\n * of all of them because one of them was reinstalled.\n */\n\n/** Where the last-seen id for a host is remembered. */\nconst STORAGE_PREFIX = \"abracadabra:server-id:\";\n\n/**\n * Stores that belong to no particular server and must survive a reset.\n *\n * `abracadabra:identity` is this browser's keypair for EVERY server it talks to,\n * so dropping it because one server was reinstalled would sign the user out of\n * all of them. Listed explicitly rather than relying on the anchored match, so\n * that a future store named after a host cannot take it by accident.\n */\nconst GLOBAL_STORES = new Set([\"abracadabra:identity\", \"abracadabra:softkey\"]);\n\nexport interface ServerResetOutcome {\n\t/** The id previously seen for this host, if any. */\n\tpreviousServerId: string | null;\n\t/** The id the server reports now. */\n\tserverId: string;\n\t/** Databases deleted because they belonged to the replaced server. */\n\tcleared: string[];\n\t/**\n\t * Databases whose deletion was BLOCKED by an open connection.\n\t *\n\t * This is a failure, not a warning to swallow: the stale state is still in\n\t * the tab and will be re-pushed. It happens when a provider opened the store\n\t * before this ran, which means the guard was called too late. Callers should\n\t * surface it rather than assume a clean result.\n\t */\n\tblocked: string[];\n}\n\nfunction storageAvailable(): boolean {\n\ttry {\n\t\treturn (\n\t\t\ttypeof globalThis !== \"undefined\" &&\n\t\t\t\"localStorage\" in globalThis &&\n\t\t\t\"indexedDB\" in globalThis\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Does this database belong to the given server?\n *\n * The match is ANCHORED, and it has to be. A plain `name.includes(host)` looks\n * right and is wrong in a way that destroys data: `other.example.com:3011`\n * contains `example.com:3011`, so clearing one server's caches would delete a\n * DIFFERENT server's — the exact \"too broad\" failure this guard exists to avoid.\n * A unit test covers that pair.\n *\n * Three anchored shapes are needed, because the stores are NOT consistently\n * scoped and pretending otherwise silently misses some:\n *\n * - `<host>/…` — {@link OfflineStore}, keyed `<host>/<docId>`\n * - `…:<host>` — a namespaced store handed a bare host\n * - `…://<host>` — a namespaced store handed a full URL. Real, not hypothetical:\n * `@abraca/nuxt` passes `serverUrl` to `FileBlobStore`, so the database is\n * named `abracadabra:files:http://example.com:3011`. Measured in a live\n * browser; a rule written only for the first two shapes left it behind, which\n * is a whole file cache surviving a wipe.\n */\nexport function isServerScopedStore(name: string, host: string): boolean {\n\tif (!name.startsWith(\"abracadabra:\")) return false;\n\tif (GLOBAL_STORES.has(name)) return false;\n\tconst rest = name.slice(\"abracadabra:\".length);\n\treturn (\n\t\trest === host ||\n\t\trest.startsWith(`${host}/`) ||\n\t\trest.endsWith(`:${host}`) ||\n\t\trest.endsWith(`://${host}`)\n\t);\n}\n\n/**\n * Compare the server's identity against the one this browser last saw, and drop\n * every cache belonging to it if the database has been replaced.\n *\n * **Call this before opening any provider.** Once a provider holds an IndexedDB\n * handle, `deleteDatabase` blocks instead of deleting and the stale tree is\n * already queued for re-push — the deletion completes later, having achieved\n * nothing. Any store in that position comes back in `blocked`.\n *\n * Conservative by design:\n *\n * - the FIRST time a host is seen, the id is recorded and nothing is deleted —\n * a new visitor must not have caches cleared for having no history;\n * - a browser with no `indexedDB`/`localStorage` is a no-op;\n * - it never throws. Failing to tidy a cache must not stop an app from starting.\n *\n * @param host The server's `host` (`example.com:3011`) — the same value\n * providers scope their stores by. Not the full origin: the\n * scheme is not part of a server's cache identity here.\n * @param serverId `server_id` from `GET /info`.\n */\nexport async function dropCachesIfServerReplaced(\n\thost: string,\n\tserverId: string,\n): Promise<ServerResetOutcome | null> {\n\tif (!storageAvailable() || !host || !serverId) return null;\n\n\tconst key = STORAGE_PREFIX + host;\n\tlet previousServerId: string | null = null;\n\ttry {\n\t\tpreviousServerId = globalThis.localStorage.getItem(key);\n\t} catch {\n\t\treturn null;\n\t}\n\n\t// First sighting, or the same server we have always been talking to.\n\tif (previousServerId === null) {\n\t\ttry {\n\t\t\tglobalThis.localStorage.setItem(key, serverId);\n\t\t} catch {\n\t\t\t/* private mode, quota — not worth failing over */\n\t\t}\n\t\treturn null;\n\t}\n\tif (previousServerId === serverId) return null;\n\n\tconst cleared: string[] = [];\n\tconst blocked: string[] = [];\n\ttry {\n\t\tconst databases = (await globalThis.indexedDB.databases?.()) ?? [];\n\t\tconst doomed = databases\n\t\t\t.map((d) => d.name)\n\t\t\t.filter((n): n is string => !!n && isServerScopedStore(n, host));\n\n\t\tawait Promise.all(\n\t\t\tdoomed.map(\n\t\t\t\t(name) =>\n\t\t\t\t\tnew Promise<void>((resolve) => {\n\t\t\t\t\t\tconst request = globalThis.indexedDB.deleteDatabase(name);\n\t\t\t\t\t\trequest.onsuccess = () => {\n\t\t\t\t\t\t\tcleared.push(name);\n\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t};\n\t\t\t\t\t\trequest.onerror = () => resolve();\n\t\t\t\t\t\t// Still open somewhere. The delete stays pending and the stale\n\t\t\t\t\t\t// state is still live in this tab — report it, do not hang the\n\t\t\t\t\t\t// page waiting for a handle we do not own.\n\t\t\t\t\t\trequest.onblocked = () => {\n\t\t\t\t\t\t\tblocked.push(name);\n\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t};\n\t\t\t\t\t}),\n\t\t\t),\n\t\t);\n\t} catch {\n\t\t/* enumeration unsupported or denied — nothing safely deletable */\n\t}\n\n\ttry {\n\t\tglobalThis.localStorage.setItem(key, serverId);\n\t} catch {\n\t\t/* see above */\n\t}\n\n\treturn { previousServerId, serverId, cleared, blocked };\n}\n\n/** Forget what we know about a host, so the next check treats it as new. */\nexport function forgetServerIdentity(host: string): void {\n\tif (!storageAvailable() || !host) return;\n\ttry {\n\t\tglobalThis.localStorage.removeItem(STORAG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