@abraca/dabra 2.102.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,571 @@
|
|
|
1
|
+
import EventEmitter from "./EventEmitter.js";
|
|
2
|
+
import { getLifecycleGate } from "./LifecycleGate.js";
|
|
3
|
+
import { OfflineStore } from "./OfflineStore.js";
|
|
4
|
+
import { E2EAbracadabraProvider } from "./E2EAbracadabraProvider.js";
|
|
5
|
+
import { BackgroundSyncPersistence } from "./BackgroundSyncPersistence.js";
|
|
6
|
+
import * as Y from "yjs";
|
|
7
|
+
|
|
8
|
+
//#region packages/provider/src/BackgroundSyncManager.ts
|
|
9
|
+
/**
|
|
10
|
+
* BackgroundSyncManager
|
|
11
|
+
*
|
|
12
|
+
* Proactively syncs all documents in the root tree map to IndexedDB so they
|
|
13
|
+
* are available offline even if the user has never opened them directly.
|
|
14
|
+
*
|
|
15
|
+
* Key behaviours:
|
|
16
|
+
* - Priority queue: sorted by updatedAt desc → never-synced first → errored last
|
|
17
|
+
* - Concurrency: semaphore (default 2 parallel WS connections)
|
|
18
|
+
* - Provider selection: non-E2E via rootProvider.loadChild(); E2E via
|
|
19
|
+
* E2EAbracadabraProvider directly when docKeyManager + keystore are present
|
|
20
|
+
* - File pre-caching: after sync, walks the Y.Doc for file refs and warms
|
|
21
|
+
* the FileBlobStore cache (opt-in via prefetchFiles, default true)
|
|
22
|
+
* - Cover images: at start of syncAll(), pre-caches all cover upload IDs
|
|
23
|
+
* from the root tree map immediately (fire-and-forget)
|
|
24
|
+
* - Periodic sync: startPeriodicSync() returns a cleanup function
|
|
25
|
+
*
|
|
26
|
+
* Note: This is in-page only (no Service Worker). The existing
|
|
27
|
+
* flushPendingUpdates() handles offline → reconnect for open docs.
|
|
28
|
+
*/
|
|
29
|
+
/**
|
|
30
|
+
* Simple semaphore for capping concurrency.
|
|
31
|
+
*/
|
|
32
|
+
var Semaphore = class {
|
|
33
|
+
constructor(limit) {
|
|
34
|
+
this.queue = [];
|
|
35
|
+
this.slots = limit;
|
|
36
|
+
}
|
|
37
|
+
acquire() {
|
|
38
|
+
if (this.slots > 0) {
|
|
39
|
+
this.slots--;
|
|
40
|
+
return Promise.resolve();
|
|
41
|
+
}
|
|
42
|
+
return new Promise((resolve) => this.queue.push(resolve));
|
|
43
|
+
}
|
|
44
|
+
release() {
|
|
45
|
+
const next = this.queue.shift();
|
|
46
|
+
if (next) next();
|
|
47
|
+
else this.slots++;
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Server-accepted doc-id format. The Rust server's `DocId::from_string`
|
|
52
|
+
* is a strict UUID parse; any other string returns 422. Stale entries in
|
|
53
|
+
* the doc-tree map (legacy slug ids from earlier demos, manual experiments)
|
|
54
|
+
* would otherwise emit one 422 per `syncAll()` forever — see the warn
|
|
55
|
+
* below in `_buildQueue`.
|
|
56
|
+
*/
|
|
57
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
58
|
+
function isValidDocId(id) {
|
|
59
|
+
return UUID_RE.test(id);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Consecutive transient failures before a doc is promoted from the calm
|
|
63
|
+
* `retrying` status to a genuine `error`. Keeps a single timeout/network blip
|
|
64
|
+
* from flashing a red error badge — the doc only "counts" as broken once it
|
|
65
|
+
* has failed this many passes in a row.
|
|
66
|
+
*/
|
|
67
|
+
const FAILURE_THRESHOLD = 3;
|
|
68
|
+
/** Delay before a one-shot follow-up retry of stragglers after `syncAll()`. */
|
|
69
|
+
const STRAGGLER_RETRY_DELAY_MS = 6e4;
|
|
70
|
+
/**
|
|
71
|
+
* Decide whether a sync failure is permanent (the server will never accept
|
|
72
|
+
* this doc — deleted, forbidden, or an unparseable id) or merely transient
|
|
73
|
+
* (timeout, dropped socket, momentary 5xx). Permanent failures are parked as
|
|
74
|
+
* `unavailable` and never retried; transient ones go through `retrying`.
|
|
75
|
+
*
|
|
76
|
+
* Best-effort: inspects a numeric `status`/`code` if the thrown value carries
|
|
77
|
+
* one, otherwise falls back to message keywords. Defaults to transient so we
|
|
78
|
+
* never give up on a doc we're unsure about.
|
|
79
|
+
*/
|
|
80
|
+
function isPermanentSyncError(err) {
|
|
81
|
+
const status = typeof err === "object" && err !== null ? Number(err.status ?? err.statusCode ?? err.code) : NaN;
|
|
82
|
+
if (status === 403 || status === 404 || status === 410 || status === 422) return true;
|
|
83
|
+
const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
|
|
84
|
+
return /\b(403|404|410|422)\b/.test(msg) || msg.includes("forbidden") || msg.includes("not found") || msg.includes("does not exist") || msg.includes("unprocessable");
|
|
85
|
+
}
|
|
86
|
+
var BackgroundSyncManager = class extends EventEmitter {
|
|
87
|
+
constructor(rootProvider, client, fileBlobStore, opts) {
|
|
88
|
+
super();
|
|
89
|
+
this.syncStates = /* @__PURE__ */ new Map();
|
|
90
|
+
this._warnedInvalidIds = /* @__PURE__ */ new Set();
|
|
91
|
+
this._destroyed = false;
|
|
92
|
+
this._initPromise = null;
|
|
93
|
+
this._stragglerTimer = null;
|
|
94
|
+
this.rootProvider = rootProvider;
|
|
95
|
+
this.client = client;
|
|
96
|
+
this.fileBlobStore = fileBlobStore ?? null;
|
|
97
|
+
this.opts = {
|
|
98
|
+
concurrency: opts?.concurrency ?? 2,
|
|
99
|
+
syncTimeout: opts?.syncTimeout ?? 3e4,
|
|
100
|
+
prefetchFiles: opts?.prefetchFiles ?? true,
|
|
101
|
+
throttleMs: opts?.throttleMs ?? 200,
|
|
102
|
+
maxRetries: opts?.maxRetries ?? 2
|
|
103
|
+
};
|
|
104
|
+
let serverOrigin = "default";
|
|
105
|
+
try {
|
|
106
|
+
serverOrigin = new URL(client.baseUrl ?? "").host;
|
|
107
|
+
} catch {}
|
|
108
|
+
this.persistence = new BackgroundSyncPersistence(serverOrigin);
|
|
109
|
+
this.semaphore = new Semaphore(this.opts.concurrency);
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Load persisted sync states from IndexedDB into the in-memory map.
|
|
113
|
+
* Called automatically by syncAll() / syncDoc(); safe to call concurrently.
|
|
114
|
+
*/
|
|
115
|
+
async init() {
|
|
116
|
+
if (!this._initPromise) this._initPromise = this._loadPersistedStates();
|
|
117
|
+
return this._initPromise;
|
|
118
|
+
}
|
|
119
|
+
async _loadPersistedStates() {
|
|
120
|
+
try {
|
|
121
|
+
const states = await this.persistence.getAllStates();
|
|
122
|
+
for (const state of states) this.syncStates.set(state.docId, state);
|
|
123
|
+
} catch {}
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Re-read persisted sync states from IndexedDB, merging in any docs not
|
|
127
|
+
* already tracked in memory. Unlike `init()` this is **not** cached behind
|
|
128
|
+
* `_initPromise` — every call hits IDB afresh.
|
|
129
|
+
*
|
|
130
|
+
* Why this exists: `init()` only ever loads IDB once. If a manager was
|
|
131
|
+
* created while IDB was empty/mid-population (or a UI singleton was left
|
|
132
|
+
* pointing at a manager whose in-memory map is stale after a connection
|
|
133
|
+
* swap), the only thing that recovered the real counts was a full page
|
|
134
|
+
* reload (which spins up a brand-new manager → fresh `_loadPersistedStates`).
|
|
135
|
+
* Calling this re-hydrates from the same source a reload reads, so the
|
|
136
|
+
* offline-sync panel can self-heal from a spurious "0/0" without a reload.
|
|
137
|
+
*
|
|
138
|
+
* Merge-only by design: an in-memory entry (possibly a fresher in-flight
|
|
139
|
+
* `syncing`/`synced`) is never clobbered by the persisted copy; we only add
|
|
140
|
+
* docs IDB knows about that memory doesn't.
|
|
141
|
+
*/
|
|
142
|
+
async reloadPersistedStates() {
|
|
143
|
+
try {
|
|
144
|
+
const states = await this.persistence.getAllStates();
|
|
145
|
+
for (const state of states) if (!this.syncStates.has(state.docId)) this.syncStates.set(state.docId, state);
|
|
146
|
+
} catch {}
|
|
147
|
+
}
|
|
148
|
+
/** Sync all documents in the root tree. */
|
|
149
|
+
async syncAll() {
|
|
150
|
+
if (this._destroyed) return;
|
|
151
|
+
await this.init();
|
|
152
|
+
const treeMap = this.rootProvider.document.getMap("doc-tree");
|
|
153
|
+
const entries = Array.from(treeMap.entries());
|
|
154
|
+
if (entries.length === 0) return;
|
|
155
|
+
const updatedAtMap = /* @__PURE__ */ new Map();
|
|
156
|
+
for (const [docId, v] of entries) updatedAtMap.set(docId, v?.updatedAt ?? v?.createdAt ?? 0);
|
|
157
|
+
this._prefetchCovers(entries).catch(() => null);
|
|
158
|
+
const queue = this._buildQueue(entries);
|
|
159
|
+
const failed = [];
|
|
160
|
+
let idx = 0;
|
|
161
|
+
const next = async () => {
|
|
162
|
+
while (idx < queue.length) {
|
|
163
|
+
if (this._destroyed) return;
|
|
164
|
+
const docId = queue[idx++];
|
|
165
|
+
const updatedAt = updatedAtMap.get(docId) ?? 0;
|
|
166
|
+
if (!await this._syncWithSemaphore(docId, updatedAt)) failed.push(docId);
|
|
167
|
+
if (this.opts.throttleMs > 0 && idx < queue.length) await new Promise((r) => setTimeout(r, this.opts.throttleMs));
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
const workers = Array.from({ length: this.opts.concurrency }, () => next());
|
|
171
|
+
await Promise.all(workers);
|
|
172
|
+
for (let retry = 0; retry < this.opts.maxRetries && failed.length > 0; retry++) {
|
|
173
|
+
if (this._destroyed) return;
|
|
174
|
+
const batch = failed.splice(0, failed.length);
|
|
175
|
+
const backoff = 2e3 * 2 ** retry;
|
|
176
|
+
await new Promise((r) => setTimeout(r, backoff));
|
|
177
|
+
idx = 0;
|
|
178
|
+
const retryQueue = batch;
|
|
179
|
+
const retryNext = async () => {
|
|
180
|
+
while (idx < retryQueue.length) {
|
|
181
|
+
if (this._destroyed) return;
|
|
182
|
+
const docId = retryQueue[idx++];
|
|
183
|
+
const updatedAt = updatedAtMap.get(docId) ?? 0;
|
|
184
|
+
if (!await this._syncWithSemaphore(docId, updatedAt)) failed.push(docId);
|
|
185
|
+
if (this.opts.throttleMs > 0 && idx < retryQueue.length) await new Promise((r) => setTimeout(r, this.opts.throttleMs));
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
const retryWorkers = Array.from({ length: this.opts.concurrency }, () => retryNext());
|
|
189
|
+
await Promise.all(retryWorkers);
|
|
190
|
+
}
|
|
191
|
+
if (failed.length > 0) this._scheduleStragglerRetry(failed.slice());
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Schedule a single delayed retry of the given docs. Replaces any pending
|
|
195
|
+
* straggler timer so repeated `syncAll()` calls don't stack timers.
|
|
196
|
+
*/
|
|
197
|
+
_scheduleStragglerRetry(docIds) {
|
|
198
|
+
if (this._destroyed || docIds.length === 0) return;
|
|
199
|
+
if (this._stragglerTimer) clearTimeout(this._stragglerTimer);
|
|
200
|
+
this._stragglerTimer = setTimeout(() => {
|
|
201
|
+
this._stragglerTimer = null;
|
|
202
|
+
if (this._destroyed) return;
|
|
203
|
+
(async () => {
|
|
204
|
+
const treeMap = this.rootProvider.document.getMap("doc-tree");
|
|
205
|
+
for (const docId of docIds) {
|
|
206
|
+
if (this._destroyed) return;
|
|
207
|
+
const entry = treeMap.get(docId);
|
|
208
|
+
const updatedAt = entry?.updatedAt ?? entry?.createdAt ?? 0;
|
|
209
|
+
await this._syncWithSemaphore(docId, updatedAt);
|
|
210
|
+
}
|
|
211
|
+
})();
|
|
212
|
+
}, STRAGGLER_RETRY_DELAY_MS);
|
|
213
|
+
}
|
|
214
|
+
/** Sync a single document by ID. */
|
|
215
|
+
async syncDoc(docId) {
|
|
216
|
+
await this.init();
|
|
217
|
+
const state = await this._doSyncDoc(docId);
|
|
218
|
+
this.syncStates.set(docId, state);
|
|
219
|
+
await this.persistence.setState(state).catch(() => null);
|
|
220
|
+
this.emit("stateChanged", {
|
|
221
|
+
docId,
|
|
222
|
+
state
|
|
223
|
+
});
|
|
224
|
+
return state;
|
|
225
|
+
}
|
|
226
|
+
/** Return a snapshot of all known sync states. */
|
|
227
|
+
getSyncStatus() {
|
|
228
|
+
return new Map(this.syncStates);
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Start periodic background sync.
|
|
232
|
+
* @param intervalMs Interval between sync runs. Default: 5 minutes.
|
|
233
|
+
* @returns Cleanup function to stop the periodic sync.
|
|
234
|
+
*/
|
|
235
|
+
startPeriodicSync(intervalMs = 300 * 1e3) {
|
|
236
|
+
let missedWhileHidden = false;
|
|
237
|
+
const handle = setInterval(() => {
|
|
238
|
+
if (this._destroyed) return;
|
|
239
|
+
if (getLifecycleGate().backgrounded) {
|
|
240
|
+
missedWhileHidden = true;
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
this.syncAll().catch(() => null);
|
|
244
|
+
}, intervalMs);
|
|
245
|
+
const unsubscribe = getLifecycleGate().onChange((backgrounded) => {
|
|
246
|
+
if (backgrounded || !missedWhileHidden || this._destroyed) return;
|
|
247
|
+
missedWhileHidden = false;
|
|
248
|
+
this.syncAll().catch(() => null);
|
|
249
|
+
});
|
|
250
|
+
return () => {
|
|
251
|
+
clearInterval(handle);
|
|
252
|
+
unsubscribe();
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Clear all offline document data and sync state.
|
|
257
|
+
* Opens each document's OfflineStore and clears its contents, then
|
|
258
|
+
* resets the background sync persistence. After calling this, all
|
|
259
|
+
* documents will need to be re-synced.
|
|
260
|
+
*/
|
|
261
|
+
async clearAllSyncedData() {
|
|
262
|
+
const docIds = new Set(this.syncStates.keys());
|
|
263
|
+
const treeMap = this.rootProvider.document.getMap("doc-tree");
|
|
264
|
+
for (const docId of treeMap.keys()) docIds.add(docId);
|
|
265
|
+
let serverOrigin;
|
|
266
|
+
try {
|
|
267
|
+
serverOrigin = new URL(this.client.baseUrl ?? "").host;
|
|
268
|
+
} catch {}
|
|
269
|
+
const clearPromises = Array.from(docIds).map(async (docId) => {
|
|
270
|
+
try {
|
|
271
|
+
const store = new OfflineStore(docId, serverOrigin);
|
|
272
|
+
await store.clearAll();
|
|
273
|
+
store.destroy();
|
|
274
|
+
} catch {}
|
|
275
|
+
});
|
|
276
|
+
await Promise.all(clearPromises);
|
|
277
|
+
for (const docId of docIds) await this.persistence.deleteState(docId).catch(() => null);
|
|
278
|
+
this.syncStates.clear();
|
|
279
|
+
this._initPromise = null;
|
|
280
|
+
}
|
|
281
|
+
destroy() {
|
|
282
|
+
this._destroyed = true;
|
|
283
|
+
if (this._stragglerTimer) {
|
|
284
|
+
clearTimeout(this._stragglerTimer);
|
|
285
|
+
this._stragglerTimer = null;
|
|
286
|
+
}
|
|
287
|
+
this.removeAllListeners();
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Build a priority-sorted list of doc IDs:
|
|
291
|
+
* 1. Never-synced docs first (lastSynced === null, status !== "error")
|
|
292
|
+
* 2. Synced docs sorted by updatedAt desc (most-recently-edited first)
|
|
293
|
+
* 3. Errored docs last
|
|
294
|
+
*/
|
|
295
|
+
_buildQueue(entries) {
|
|
296
|
+
const filtered = [];
|
|
297
|
+
for (const entry of entries) {
|
|
298
|
+
const [docId] = entry;
|
|
299
|
+
if (isValidDocId(docId)) {
|
|
300
|
+
filtered.push(entry);
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
if (!this._warnedInvalidIds.has(docId)) {
|
|
304
|
+
this._warnedInvalidIds.add(docId);
|
|
305
|
+
console.warn(`[BackgroundSyncManager] skipping non-UUID doc id "${docId}" in doc-tree — server would reject it (422). Likely a stale entry from an earlier seeder; remove it from the tree to silence this.`);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
const items = [];
|
|
309
|
+
for (const [docId, v] of filtered) {
|
|
310
|
+
const state = this.syncStates.get(docId);
|
|
311
|
+
if (state?.status === "unavailable") continue;
|
|
312
|
+
const updatedAt = v?.updatedAt ?? v?.createdAt ?? 0;
|
|
313
|
+
let priority;
|
|
314
|
+
if (!state || state.status === "pending") priority = Number.MAX_SAFE_INTEGER - updatedAt;
|
|
315
|
+
else if (state.status === "error" || state.status === "retrying") priority = -1;
|
|
316
|
+
else priority = updatedAt;
|
|
317
|
+
items.push({
|
|
318
|
+
docId,
|
|
319
|
+
priority
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
items.sort((a, b) => b.priority - a.priority);
|
|
323
|
+
return items.map((i) => i.docId);
|
|
324
|
+
}
|
|
325
|
+
/** Returns true on success (or skip), false on error. */
|
|
326
|
+
async _syncWithSemaphore(docId, updatedAt) {
|
|
327
|
+
if (this._destroyed) return true;
|
|
328
|
+
const existing = this.syncStates.get(docId);
|
|
329
|
+
if (existing && existing.status === "unavailable") {
|
|
330
|
+
this.emit("stateChanged", {
|
|
331
|
+
docId,
|
|
332
|
+
state: existing
|
|
333
|
+
});
|
|
334
|
+
return true;
|
|
335
|
+
}
|
|
336
|
+
if (existing && existing.status === "synced" && existing.lastSynced !== null && existing.lastSynced + 200 >= updatedAt) {
|
|
337
|
+
this.emit("stateChanged", {
|
|
338
|
+
docId,
|
|
339
|
+
state: existing
|
|
340
|
+
});
|
|
341
|
+
return true;
|
|
342
|
+
}
|
|
343
|
+
await this.semaphore.acquire();
|
|
344
|
+
try {
|
|
345
|
+
const state = await this._doSyncDoc(docId);
|
|
346
|
+
this.syncStates.set(docId, state);
|
|
347
|
+
await this.persistence.setState(state).catch(() => null);
|
|
348
|
+
this.emit("stateChanged", {
|
|
349
|
+
docId,
|
|
350
|
+
state
|
|
351
|
+
});
|
|
352
|
+
return state.status !== "error" && state.status !== "retrying";
|
|
353
|
+
} finally {
|
|
354
|
+
this.semaphore.release();
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
async _doSyncDoc(docId) {
|
|
358
|
+
if (!isValidDocId(docId)) return {
|
|
359
|
+
docId,
|
|
360
|
+
status: "unavailable",
|
|
361
|
+
lastSynced: this.syncStates.get(docId)?.lastSynced ?? null,
|
|
362
|
+
error: "Invalid document id (not a UUID)",
|
|
363
|
+
consecutiveFailures: 0,
|
|
364
|
+
isE2E: false
|
|
365
|
+
};
|
|
366
|
+
const syncing = {
|
|
367
|
+
docId,
|
|
368
|
+
status: "syncing",
|
|
369
|
+
lastSynced: this.syncStates.get(docId)?.lastSynced ?? null,
|
|
370
|
+
isE2E: false
|
|
371
|
+
};
|
|
372
|
+
this.syncStates.set(docId, syncing);
|
|
373
|
+
this.emit("stateChanged", {
|
|
374
|
+
docId,
|
|
375
|
+
state: syncing
|
|
376
|
+
});
|
|
377
|
+
let isE2E = false;
|
|
378
|
+
try {
|
|
379
|
+
try {
|
|
380
|
+
isE2E = (await this.client.getDocEncryption(docId)).mode === "e2e";
|
|
381
|
+
} catch {}
|
|
382
|
+
if (isE2E) return await this._syncE2EDoc(docId);
|
|
383
|
+
else return await this._syncNonE2EDoc(docId);
|
|
384
|
+
} catch (err) {
|
|
385
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
386
|
+
const prev = this.syncStates.get(docId);
|
|
387
|
+
const lastSynced = prev?.lastSynced ?? null;
|
|
388
|
+
if (isPermanentSyncError(err)) return {
|
|
389
|
+
docId,
|
|
390
|
+
status: "unavailable",
|
|
391
|
+
lastSynced,
|
|
392
|
+
error,
|
|
393
|
+
consecutiveFailures: 0,
|
|
394
|
+
isE2E
|
|
395
|
+
};
|
|
396
|
+
const consecutiveFailures = (prev?.consecutiveFailures ?? 0) + 1;
|
|
397
|
+
return {
|
|
398
|
+
docId,
|
|
399
|
+
status: consecutiveFailures >= FAILURE_THRESHOLD ? "error" : "retrying",
|
|
400
|
+
lastSynced,
|
|
401
|
+
error,
|
|
402
|
+
consecutiveFailures,
|
|
403
|
+
isE2E
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
async _syncNonE2EDoc(docId) {
|
|
408
|
+
const treeMap = this.rootProvider.document.getMap("doc-tree");
|
|
409
|
+
const alreadyCached = this.rootProvider.children.has(docId);
|
|
410
|
+
if (!alreadyCached) {
|
|
411
|
+
if ((this.rootProvider.configuration?.websocketProvider?.configuration?.providerMap)?.has(docId)) return {
|
|
412
|
+
docId,
|
|
413
|
+
status: "synced",
|
|
414
|
+
lastSynced: Date.now(),
|
|
415
|
+
consecutiveFailures: 0,
|
|
416
|
+
isE2E: false
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
const childProvider = await this.rootProvider.loadChild(docId, { evictable: false });
|
|
420
|
+
try {
|
|
421
|
+
await childProvider.ready;
|
|
422
|
+
await this._waitForSynced(childProvider);
|
|
423
|
+
if (typeof childProvider.persistSnapshot === "function") await childProvider.persistSnapshot();
|
|
424
|
+
{
|
|
425
|
+
const treeEntry = treeMap.get(docId);
|
|
426
|
+
this.emit("docSynced", {
|
|
427
|
+
docId,
|
|
428
|
+
document: childProvider.document,
|
|
429
|
+
label: treeEntry?.label ?? "",
|
|
430
|
+
meta: treeEntry?.meta
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
if (this.opts.prefetchFiles && this.fileBlobStore) this._prefetchDocFiles(docId, childProvider.document).catch(() => null);
|
|
434
|
+
const treeEntry = treeMap.get(docId);
|
|
435
|
+
const treeUpdatedAt = treeEntry?.updatedAt ?? treeEntry?.createdAt ?? 0;
|
|
436
|
+
return {
|
|
437
|
+
docId,
|
|
438
|
+
status: "synced",
|
|
439
|
+
lastSynced: Math.max(Date.now(), treeUpdatedAt),
|
|
440
|
+
consecutiveFailures: 0,
|
|
441
|
+
isE2E: false
|
|
442
|
+
};
|
|
443
|
+
} finally {
|
|
444
|
+
if (!alreadyCached) {
|
|
445
|
+
if (typeof this.rootProvider.isChildTransient === "function" ? this.rootProvider.isChildTransient(docId) : true) this.rootProvider.unloadChild(docId);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
async _syncE2EDoc(docId) {
|
|
450
|
+
const treeMap = this.rootProvider.document.getMap("doc-tree");
|
|
451
|
+
const docKeyManager = this.rootProvider.abracadabraConfig?.docKeyManager;
|
|
452
|
+
const keystore = this.rootProvider.abracadabraConfig?.keystore;
|
|
453
|
+
if (!docKeyManager || !keystore) return {
|
|
454
|
+
docId,
|
|
455
|
+
status: "skipped",
|
|
456
|
+
lastSynced: null,
|
|
457
|
+
consecutiveFailures: 0,
|
|
458
|
+
isE2E: true
|
|
459
|
+
};
|
|
460
|
+
const childDoc = new Y.Doc({ guid: docId });
|
|
461
|
+
const childProvider = new E2EAbracadabraProvider({
|
|
462
|
+
name: docId,
|
|
463
|
+
document: childDoc,
|
|
464
|
+
client: this.client,
|
|
465
|
+
docKeyManager,
|
|
466
|
+
keystore
|
|
467
|
+
});
|
|
468
|
+
try {
|
|
469
|
+
await childProvider.ready;
|
|
470
|
+
await this._waitForSynced(childProvider);
|
|
471
|
+
{
|
|
472
|
+
const treeEntry = treeMap.get(docId);
|
|
473
|
+
this.emit("docSynced", {
|
|
474
|
+
docId,
|
|
475
|
+
document: childDoc,
|
|
476
|
+
label: treeEntry?.label ?? "",
|
|
477
|
+
meta: treeEntry?.meta
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
if (this.opts.prefetchFiles && this.fileBlobStore) this._prefetchDocFiles(docId, childDoc).catch(() => null);
|
|
481
|
+
const treeEntry = treeMap.get(docId);
|
|
482
|
+
const treeUpdatedAt = treeEntry?.updatedAt ?? treeEntry?.createdAt ?? 0;
|
|
483
|
+
return {
|
|
484
|
+
docId,
|
|
485
|
+
status: "synced",
|
|
486
|
+
lastSynced: Math.max(Date.now(), treeUpdatedAt),
|
|
487
|
+
consecutiveFailures: 0,
|
|
488
|
+
isE2E: true
|
|
489
|
+
};
|
|
490
|
+
} finally {
|
|
491
|
+
childProvider.destroy();
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* Wait for a provider to emit the "synced" event (with state=true),
|
|
496
|
+
* timing out after opts.syncTimeout ms.
|
|
497
|
+
*/
|
|
498
|
+
_waitForSynced(provider) {
|
|
499
|
+
if (provider.synced === true) return Promise.resolve();
|
|
500
|
+
return new Promise((resolve, reject) => {
|
|
501
|
+
const timer = setTimeout(() => {
|
|
502
|
+
provider.off("synced", onSynced);
|
|
503
|
+
reject(/* @__PURE__ */ new Error(`Sync timeout after ${this.opts.syncTimeout}ms`));
|
|
504
|
+
}, this.opts.syncTimeout);
|
|
505
|
+
function onSynced(state) {
|
|
506
|
+
if (typeof state === "boolean" ? state : state?.state ?? state) {
|
|
507
|
+
clearTimeout(timer);
|
|
508
|
+
provider.off("synced", onSynced);
|
|
509
|
+
resolve();
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
provider.on("synced", onSynced);
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* Pre-cache all cover images referenced in the root tree map.
|
|
517
|
+
*/
|
|
518
|
+
async _prefetchCovers(entries) {
|
|
519
|
+
if (!this.fileBlobStore) return;
|
|
520
|
+
for (const [docId, v] of entries) {
|
|
521
|
+
const coverUploadId = v?.meta?.coverUploadId;
|
|
522
|
+
if (coverUploadId) this.fileBlobStore.getBlobUrl(docId, coverUploadId).catch(() => null);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* Pre-cache file blobs referenced in a synced Y.Doc.
|
|
527
|
+
* Walks:
|
|
528
|
+
* - ydoc.getXmlFragment('default') for `fileBlock` nodes (TipTap)
|
|
529
|
+
* - ydoc.getMap('doc-tree') for meta.coverUploadId entries
|
|
530
|
+
*/
|
|
531
|
+
async _prefetchDocFiles(docId, ydoc) {
|
|
532
|
+
if (!this.fileBlobStore) return;
|
|
533
|
+
const refs = this._extractFileRefs(ydoc);
|
|
534
|
+
for (const { refDocId, uploadId } of refs) this.fileBlobStore.getBlobUrl(refDocId ?? docId, uploadId).catch(() => null);
|
|
535
|
+
}
|
|
536
|
+
_extractFileRefs(ydoc) {
|
|
537
|
+
const refs = [];
|
|
538
|
+
try {
|
|
539
|
+
const fragment = ydoc.getXmlFragment("default");
|
|
540
|
+
this._walkXml(fragment, refs);
|
|
541
|
+
} catch {}
|
|
542
|
+
try {
|
|
543
|
+
const treeMap = ydoc.getMap("doc-tree");
|
|
544
|
+
for (const [id, v] of treeMap.entries()) {
|
|
545
|
+
const coverUploadId = v?.meta?.coverUploadId;
|
|
546
|
+
if (coverUploadId) refs.push({
|
|
547
|
+
refDocId: id,
|
|
548
|
+
uploadId: coverUploadId
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
} catch {}
|
|
552
|
+
return refs;
|
|
553
|
+
}
|
|
554
|
+
_walkXml(node, refs) {
|
|
555
|
+
for (const child of node.toArray()) if (child instanceof Y.XmlElement) {
|
|
556
|
+
if (child.nodeName === "fileBlock") {
|
|
557
|
+
const uploadId = child.getAttribute("uploadId");
|
|
558
|
+
const refDocId = child.getAttribute("docId") ?? null;
|
|
559
|
+
if (uploadId) refs.push({
|
|
560
|
+
refDocId,
|
|
561
|
+
uploadId
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
this._walkXml(child, refs);
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
};
|
|
568
|
+
|
|
569
|
+
//#endregion
|
|
570
|
+
export { BackgroundSyncManager };
|
|
571
|
+
//# sourceMappingURL=BackgroundSyncManager.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BackgroundSyncManager.js","names":[],"sources":["../../src/BackgroundSyncManager.ts"],"sourcesContent":["/**\n * BackgroundSyncManager\n *\n * Proactively syncs all documents in the root tree map to IndexedDB so they\n * are available offline even if the user has never opened them directly.\n *\n * Key behaviours:\n * - Priority queue: sorted by updatedAt desc → never-synced first → errored last\n * - Concurrency: semaphore (default 2 parallel WS connections)\n * - Provider selection: non-E2E via rootProvider.loadChild(); E2E via\n * E2EAbracadabraProvider directly when docKeyManager + keystore are present\n * - File pre-caching: after sync, walks the Y.Doc for file refs and warms\n * the FileBlobStore cache (opt-in via prefetchFiles, default true)\n * - Cover images: at start of syncAll(), pre-caches all cover upload IDs\n * from the root tree map immediately (fire-and-forget)\n * - Periodic sync: startPeriodicSync() returns a cleanup function\n *\n * Note: This is in-page only (no Service Worker). The existing\n * flushPendingUpdates() handles offline → reconnect for open docs.\n */\n\nimport * as Y from \"yjs\";\nimport type { AbracadabraProvider } from \"./AbracadabraProvider.ts\";\nimport type { AbracadabraClient } from \"./AbracadabraClient.ts\";\nimport type { FileBlobStore } from \"./FileBlobStore.ts\";\nimport {\n\tBackgroundSyncPersistence,\n\ttype DocSyncState,\n} from \"./BackgroundSyncPersistence.ts\";\nimport { OfflineStore } from \"./OfflineStore.ts\";\nimport EventEmitter from \"./EventEmitter.ts\";\nimport { E2EAbracadabraProvider } from \"./E2EAbracadabraProvider.ts\";\nimport { getLifecycleGate } from \"./LifecycleGate.ts\";\n\nexport interface BackgroundSyncManagerOptions {\n\t/** Max parallel WS connections for background sync. Default: 2. */\n\tconcurrency?: number;\n\t/** Timeout (ms) waiting for a provider to sync. Default: 30 000. */\n\tsyncTimeout?: number;\n\t/** Pre-cache file blobs after syncing a doc. Default: true. */\n\tprefetchFiles?: boolean;\n\t/** Delay (ms) between starting each doc sync to avoid server pressure. Default: 200. */\n\tthrottleMs?: number;\n\t/** Max retries for failed docs within a single syncAll() run. Default: 2. */\n\tmaxRetries?: number;\n}\n\n/**\n * Simple semaphore for capping concurrency.\n */\nclass Semaphore {\n\tprivate slots: number;\n\tprivate queue: Array<() => void> = [];\n\n\tconstructor(limit: number) {\n\t\tthis.slots = limit;\n\t}\n\n\tacquire(): Promise<void> {\n\t\tif (this.slots > 0) {\n\t\t\tthis.slots--;\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\treturn new Promise((resolve) => this.queue.push(resolve));\n\t}\n\n\trelease(): void {\n\t\tconst next = this.queue.shift();\n\t\tif (next) {\n\t\t\tnext();\n\t\t} else {\n\t\t\tthis.slots++;\n\t\t}\n\t}\n}\n\n/**\n * Server-accepted doc-id format. The Rust server's `DocId::from_string`\n * is a strict UUID parse; any other string returns 422. Stale entries in\n * the doc-tree map (legacy slug ids from earlier demos, manual experiments)\n * would otherwise emit one 422 per `syncAll()` forever — see the warn\n * below in `_buildQueue`.\n */\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nfunction isValidDocId(id: string): boolean {\n\treturn UUID_RE.test(id);\n}\n\n/**\n * Consecutive transient failures before a doc is promoted from the calm\n * `retrying` status to a genuine `error`. Keeps a single timeout/network blip\n * from flashing a red error badge — the doc only \"counts\" as broken once it\n * has failed this many passes in a row.\n */\nconst FAILURE_THRESHOLD = 3;\n\n/** Delay before a one-shot follow-up retry of stragglers after `syncAll()`. */\nconst STRAGGLER_RETRY_DELAY_MS = 60_000;\n\n/**\n * Decide whether a sync failure is permanent (the server will never accept\n * this doc — deleted, forbidden, or an unparseable id) or merely transient\n * (timeout, dropped socket, momentary 5xx). Permanent failures are parked as\n * `unavailable` and never retried; transient ones go through `retrying`.\n *\n * Best-effort: inspects a numeric `status`/`code` if the thrown value carries\n * one, otherwise falls back to message keywords. Defaults to transient so we\n * never give up on a doc we're unsure about.\n */\nfunction isPermanentSyncError(err: unknown): boolean {\n\tconst status =\n\t\ttypeof err === \"object\" && err !== null\n\t\t\t? Number(\n\t\t\t\t\t(err as { status?: unknown; statusCode?: unknown; code?: unknown })\n\t\t\t\t\t\t.status ??\n\t\t\t\t\t\t(err as { statusCode?: unknown }).statusCode ??\n\t\t\t\t\t\t(err as { code?: unknown }).code,\n\t\t\t\t)\n\t\t\t: NaN;\n\tif (status === 403 || status === 404 || status === 410 || status === 422) {\n\t\treturn true;\n\t}\n\tconst msg = (err instanceof Error ? err.message : String(err)).toLowerCase();\n\treturn (\n\t\t/\\b(403|404|410|422)\\b/.test(msg) ||\n\t\tmsg.includes(\"forbidden\") ||\n\t\tmsg.includes(\"not found\") ||\n\t\tmsg.includes(\"does not exist\") ||\n\t\tmsg.includes(\"unprocessable\")\n\t);\n}\n\nexport class BackgroundSyncManager extends EventEmitter {\n\tprivate readonly rootProvider: AbracadabraProvider;\n\tprivate readonly client: AbracadabraClient;\n\tprivate readonly fileBlobStore: FileBlobStore | null;\n\tprivate readonly opts: Required<BackgroundSyncManagerOptions>;\n\n\tprivate readonly persistence: BackgroundSyncPersistence;\n\tprivate readonly semaphore: Semaphore;\n\tprivate readonly syncStates = new Map<string, DocSyncState>();\n\t/** Doc ids we've already warned about; keeps the log to one line per id. */\n\tprivate readonly _warnedInvalidIds = new Set<string>();\n\n\tprivate _destroyed = false;\n\tprivate _initPromise: Promise<void> | null = null;\n\t/** One-shot timer for the post-syncAll straggler retry pass. */\n\tprivate _stragglerTimer: ReturnType<typeof setTimeout> | null = null;\n\n\tconstructor(\n\t\trootProvider: AbracadabraProvider,\n\t\tclient: AbracadabraClient,\n\t\tfileBlobStore?: FileBlobStore | null,\n\t\topts?: BackgroundSyncManagerOptions,\n\t) {\n\t\tsuper();\n\t\tthis.rootProvider = rootProvider;\n\t\tthis.client = client;\n\t\tthis.fileBlobStore = fileBlobStore ?? null;\n\t\tthis.opts = {\n\t\t\tconcurrency: opts?.concurrency ?? 2,\n\t\t\tsyncTimeout: opts?.syncTimeout ?? 30_000,\n\t\t\tprefetchFiles: opts?.prefetchFiles ?? true,\n\t\t\tthrottleMs: opts?.throttleMs ?? 200,\n\t\t\tmaxRetries: opts?.maxRetries ?? 2,\n\t\t};\n\n\t\t// Derive server origin from client URL for IDB namespacing.\n\t\t// `host` (not `hostname`): port-scoped so same-host servers on\n\t\t// different ports don't share a namespace.\n\t\tlet serverOrigin = \"default\";\n\t\ttry {\n\t\t\tserverOrigin = new URL((client as any).baseUrl ?? \"\").host;\n\t\t} catch {}\n\n\t\tthis.persistence = new BackgroundSyncPersistence(serverOrigin);\n\t\tthis.semaphore = new Semaphore(this.opts.concurrency);\n\t}\n\n\t// ── Public API ────────────────────────────────────────────────────────────\n\n\t/**\n\t * Load persisted sync states from IndexedDB into the in-memory map.\n\t * Called automatically by syncAll() / syncDoc(); safe to call concurrently.\n\t */\n\tasync init(): Promise<void> {\n\t\tif (!this._initPromise) {\n\t\t\tthis._initPromise = this._loadPersistedStates();\n\t\t}\n\t\treturn this._initPromise;\n\t}\n\n\tprivate async _loadPersistedStates(): Promise<void> {\n\t\ttry {\n\t\t\tconst states = await this.persistence.getAllStates();\n\t\t\tfor (const state of states) {\n\t\t\t\tthis.syncStates.set(state.docId, state);\n\t\t\t}\n\t\t} catch {\n\t\t\t// IDB unavailable — proceed with empty map (full sync fallback)\n\t\t}\n\t}\n\n\t/**\n\t * Re-read persisted sync states from IndexedDB, merging in any docs not\n\t * already tracked in memory. Unlike `init()` this is **not** cached behind\n\t * `_initPromise` — every call hits IDB afresh.\n\t *\n\t * Why this exists: `init()` only ever loads IDB once. If a manager was\n\t * created while IDB was empty/mid-population (or a UI singleton was left\n\t * pointing at a manager whose in-memory map is stale after a connection\n\t * swap), the only thing that recovered the real counts was a full page\n\t * reload (which spins up a brand-new manager → fresh `_loadPersistedStates`).\n\t * Calling this re-hydrates from the same source a reload reads, so the\n\t * offline-sync panel can self-heal from a spurious \"0/0\" without a reload.\n\t *\n\t * Merge-only by design: an in-memory entry (possibly a fresher in-flight\n\t * `syncing`/`synced`) is never clobbered by the persisted copy; we only add\n\t * docs IDB knows about that memory doesn't.\n\t */\n\tasync reloadPersistedStates(): Promise<void> {\n\t\ttry {\n\t\t\tconst states = await this.persistence.getAllStates();\n\t\t\tfor (const state of states) {\n\t\t\t\tif (!this.syncStates.has(state.docId)) {\n\t\t\t\t\tthis.syncStates.set(state.docId, state);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// IDB unavailable — keep whatever is already in memory.\n\t\t}\n\t}\n\n\t/** Sync all documents in the root tree. */\n\tasync syncAll(): Promise<void> {\n\t\tif (this._destroyed) return;\n\n\t\tawait this.init();\n\n\t\tconst treeMap = this.rootProvider.document.getMap(\"doc-tree\") as Y.Map<any>;\n\t\tconst entries = Array.from(treeMap.entries()) as Array<[string, any]>;\n\n\t\tif (entries.length === 0) return;\n\n\t\t// Build updatedAt lookup for skip-unchanged logic\n\t\tconst updatedAtMap = new Map<string, number>();\n\t\tfor (const [docId, v] of entries) {\n\t\t\tupdatedAtMap.set(docId, v?.updatedAt ?? v?.createdAt ?? 0);\n\t\t}\n\n\t\t// Pre-cache cover images immediately (fire-and-forget)\n\t\tthis._prefetchCovers(entries).catch(() => null);\n\n\t\t// Build the priority queue\n\t\tconst queue = this._buildQueue(entries);\n\n\t\t// Sync all docs with throttling: stagger starts to avoid server pressure.\n\t\t// We use a feeding loop instead of Promise.all(queue.map(...)) so that\n\t\t// each new doc start is spaced by throttleMs.\n\t\tconst failed: string[] = [];\n\t\tlet idx = 0;\n\t\tconst next = async (): Promise<void> => {\n\t\t\twhile (idx < queue.length) {\n\t\t\t\tif (this._destroyed) return;\n\t\t\t\tconst docId = queue[idx++]!;\n\t\t\t\tconst updatedAt = updatedAtMap.get(docId) ?? 0;\n\t\t\t\tconst ok = await this._syncWithSemaphore(docId, updatedAt);\n\t\t\t\tif (!ok) failed.push(docId);\n\t\t\t\t// Throttle between starts\n\t\t\t\tif (this.opts.throttleMs > 0 && idx < queue.length) {\n\t\t\t\t\tawait new Promise((r) => setTimeout(r, this.opts.throttleMs));\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\t// Launch `concurrency` parallel workers feeding from the shared index.\n\t\tconst workers = Array.from({ length: this.opts.concurrency }, () => next());\n\t\tawait Promise.all(workers);\n\n\t\t// Retry failed docs with increasing backoff.\n\t\tfor (let retry = 0; retry < this.opts.maxRetries && failed.length > 0; retry++) {\n\t\t\tif (this._destroyed) return;\n\t\t\tconst batch = failed.splice(0, failed.length);\n\t\t\t// Backoff: 2s, 4s, 8s...\n\t\t\tconst backoff = 2000 * 2 ** retry;\n\t\t\tawait new Promise((r) => setTimeout(r, backoff));\n\n\t\t\tidx = 0;\n\t\t\tconst retryQueue = batch;\n\t\t\tconst retryNext = async (): Promise<void> => {\n\t\t\t\twhile (idx < retryQueue.length) {\n\t\t\t\t\tif (this._destroyed) return;\n\t\t\t\t\tconst docId = retryQueue[idx++]!;\n\t\t\t\t\tconst updatedAt = updatedAtMap.get(docId) ?? 0;\n\t\t\t\t\tconst ok = await this._syncWithSemaphore(docId, updatedAt);\n\t\t\t\t\tif (!ok) failed.push(docId);\n\t\t\t\t\tif (this.opts.throttleMs > 0 && idx < retryQueue.length) {\n\t\t\t\t\t\tawait new Promise((r) => setTimeout(r, this.opts.throttleMs));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst retryWorkers = Array.from({ length: this.opts.concurrency }, () => retryNext());\n\t\t\tawait Promise.all(retryWorkers);\n\t\t}\n\n\t\t// Any docs still failing after the in-run retries are \"stragglers\" — the\n\t\t// usual 1-2 slow docs that just needed a moment. Rather than make the\n\t\t// user stare at them until the next periodic pass (which can be far off),\n\t\t// schedule one quiet follow-up attempt while the connection is still warm.\n\t\tif (failed.length > 0) {\n\t\t\tthis._scheduleStragglerRetry(failed.slice());\n\t\t}\n\t}\n\n\t/**\n\t * Schedule a single delayed retry of the given docs. Replaces any pending\n\t * straggler timer so repeated `syncAll()` calls don't stack timers.\n\t */\n\tprivate _scheduleStragglerRetry(docIds: string[]): void {\n\t\tif (this._destroyed || docIds.length === 0) return;\n\t\tif (this._stragglerTimer) clearTimeout(this._stragglerTimer);\n\t\tthis._stragglerTimer = setTimeout(() => {\n\t\t\tthis._stragglerTimer = null;\n\t\t\tif (this._destroyed) return;\n\t\t\tvoid (async () => {\n\t\t\t\tconst treeMap = this.rootProvider.document.getMap(\n\t\t\t\t\t\"doc-tree\",\n\t\t\t\t) as Y.Map<any>;\n\t\t\t\tfor (const docId of docIds) {\n\t\t\t\t\tif (this._destroyed) return;\n\t\t\t\t\tconst entry = treeMap.get(docId);\n\t\t\t\t\tconst updatedAt = entry?.updatedAt ?? entry?.createdAt ?? 0;\n\t\t\t\t\tawait this._syncWithSemaphore(docId, updatedAt);\n\t\t\t\t}\n\t\t\t})();\n\t\t}, STRAGGLER_RETRY_DELAY_MS);\n\t}\n\n\t/** Sync a single document by ID. */\n\tasync syncDoc(docId: string): Promise<DocSyncState> {\n\t\tawait this.init();\n\t\tconst state = await this._doSyncDoc(docId);\n\t\tthis.syncStates.set(docId, state);\n\t\tawait this.persistence.setState(state).catch(() => null);\n\t\tthis.emit(\"stateChanged\", { docId, state });\n\t\treturn state;\n\t}\n\n\t/** Return a snapshot of all known sync states. */\n\tgetSyncStatus(): Map<string, DocSyncState> {\n\t\treturn new Map(this.syncStates);\n\t}\n\n\t/**\n\t * Start periodic background sync.\n\t * @param intervalMs Interval between sync runs. Default: 5 minutes.\n\t * @returns Cleanup function to stop the periodic sync.\n\t */\n\tstartPeriodicSync(intervalMs = 5 * 60 * 1000): () => void {\n\t\tlet missedWhileHidden = false;\n\n\t\tconst handle = setInterval(() => {\n\t\t\tif (this._destroyed) return;\n\n\t\t\t// A full-tree pass is the single most expensive thing this client\n\t\t\t// does on its own initiative: every document in the space gets an\n\t\t\t// encryption lookup, a provider, a sync wait, a document encode, an\n\t\t\t// IndexedDB write and a blob prefetch. Running that on a phone in\n\t\t\t// someone's pocket, on cellular, every five minutes, for a UI nobody\n\t\t\t// is looking at, is the worst trade in the codebase. Defer it; the\n\t\t\t// data is still there when they come back.\n\t\t\tif (getLifecycleGate().backgrounded) {\n\t\t\t\tmissedWhileHidden = true;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.syncAll().catch(() => null);\n\t\t}, intervalMs);\n\n\t\t// Catch up on return, but only if a run was actually skipped — coming\n\t\t// back to a foreground app must not trigger a redundant full-tree pass\n\t\t// on top of the one the interval is about to do anyway.\n\t\tconst unsubscribe = getLifecycleGate().onChange((backgrounded) => {\n\t\t\tif (backgrounded || !missedWhileHidden || this._destroyed) return;\n\t\t\tmissedWhileHidden = false;\n\t\t\tthis.syncAll().catch(() => null);\n\t\t});\n\n\t\treturn () => {\n\t\t\tclearInterval(handle);\n\t\t\tunsubscribe();\n\t\t};\n\t}\n\n\t/**\n\t * Clear all offline document data and sync state.\n\t * Opens each document's OfflineStore and clears its contents, then\n\t * resets the background sync persistence. After calling this, all\n\t * documents will need to be re-synced.\n\t */\n\tasync clearAllSyncedData(): Promise<void> {\n\t\t// Collect doc IDs from both in-memory state and the tree\n\t\tconst docIds = new Set<string>(this.syncStates.keys());\n\t\tconst treeMap = this.rootProvider.document.getMap(\"doc-tree\") as Y.Map<any>;\n\t\tfor (const docId of treeMap.keys()) {\n\t\t\tdocIds.add(docId);\n\t\t}\n\n\t\t// Derive server origin the same way the provider does (`host`, port-scoped)\n\t\tlet serverOrigin: string | undefined;\n\t\ttry {\n\t\t\tserverOrigin = new URL((this.client as any).baseUrl ?? \"\").host;\n\t\t} catch {}\n\n\t\t// Clear each document's offline store contents\n\t\tconst clearPromises = Array.from(docIds).map(async (docId) => {\n\t\t\ttry {\n\t\t\t\tconst store = new OfflineStore(docId, serverOrigin);\n\t\t\t\tawait store.clearAll();\n\t\t\t\tstore.destroy();\n\t\t\t} catch {\n\t\t\t\t// Ignore per-doc failures\n\t\t\t}\n\t\t});\n\t\tawait Promise.all(clearPromises);\n\n\t\t// Clear background sync persistence\n\t\tfor (const docId of docIds) {\n\t\t\tawait this.persistence.deleteState(docId).catch(() => null);\n\t\t}\n\n\t\t// Reset in-memory state\n\t\tthis.syncStates.clear();\n\t\tthis._initPromise = null;\n\t}\n\n\tdestroy(): void {\n\t\tthis._destroyed = true;\n\t\tif (this._stragglerTimer) {\n\t\t\tclearTimeout(this._stragglerTimer);\n\t\t\tthis._stragglerTimer = null;\n\t\t}\n\t\tthis.removeAllListeners();\n\t}\n\n\t// ── Internal ──────────────────────────────────────────────────────────────\n\n\t/**\n\t * Build a priority-sorted list of doc IDs:\n\t * 1. Never-synced docs first (lastSynced === null, status !== \"error\")\n\t * 2. Synced docs sorted by updatedAt desc (most-recently-edited first)\n\t * 3. Errored docs last\n\t */\n\tprivate _buildQueue(entries: Array<[string, any]>): string[] {\n\t\ttype Sortable = { docId: string; priority: number };\n\n\t\t// Drop ids the server can't parse (non-UUID). One-time warn per id\n\t\t// so the operator can chase down where the stale entry is, but no\n\t\t// log storm on every sync run.\n\t\tconst filtered: Array<[string, any]> = [];\n\t\tfor (const entry of entries) {\n\t\t\tconst [docId] = entry;\n\t\t\tif (isValidDocId(docId)) {\n\t\t\t\tfiltered.push(entry);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!this._warnedInvalidIds.has(docId)) {\n\t\t\t\tthis._warnedInvalidIds.add(docId);\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[BackgroundSyncManager] skipping non-UUID doc id \"${docId}\" in doc-tree — server would reject it (422). Likely a stale entry from an earlier seeder; remove it from the tree to silence this.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst items: Sortable[] = [];\n\t\tfor (const [docId, v] of filtered) {\n\t\t\tconst state = this.syncStates.get(docId);\n\n\t\t\t// Permanently unavailable docs are never queued — the server would\n\t\t\t// just reject them again. They stay parked until a resync clears them.\n\t\t\tif (state?.status === \"unavailable\") continue;\n\n\t\t\tconst updatedAt: number = v?.updatedAt ?? v?.createdAt ?? 0;\n\n\t\t\tlet priority: number;\n\t\t\tif (!state || state.status === \"pending\") {\n\t\t\t\t// Never synced — high priority (large number so it sorts first when DESC)\n\t\t\t\tpriority = Number.MAX_SAFE_INTEGER - updatedAt;\n\t\t\t} else if (state.status === \"error\" || state.status === \"retrying\") {\n\t\t\t\t// Failing — lowest priority (large negative offset)\n\t\t\t\tpriority = -1;\n\t\t\t} else {\n\t\t\t\t// Synced — sort by updatedAt desc (most recent = highest priority)\n\t\t\t\tpriority = updatedAt;\n\t\t\t}\n\t\t\titems.push({ docId, priority });\n\t\t}\n\n\t\t// Sort descending by priority\n\t\titems.sort((a, b) => b.priority - a.priority);\n\t\treturn items.map((i) => i.docId);\n\t}\n\n\t/** Returns true on success (or skip), false on error. */\n\tprivate async _syncWithSemaphore(\n\t\tdocId: string,\n\t\tupdatedAt: number,\n\t): Promise<boolean> {\n\t\tif (this._destroyed) return true;\n\n\t\tconst existing = this.syncStates.get(docId);\n\n\t\t// Permanently unavailable (deleted/forbidden) — don't keep hammering a\n\t\t// doc the server will never accept. Re-emit so the UI keeps the state.\n\t\tif (existing && existing.status === \"unavailable\") {\n\t\t\tthis.emit(\"stateChanged\", { docId, state: existing });\n\t\t\treturn true;\n\t\t}\n\n\t\t// Skip if already synced and doc hasn't changed since last sync.\n\t\t// The 200ms grace margin handles edge cases where the updatedAt\n\t\t// observer writes a timestamp milliseconds after lastSynced was recorded.\n\t\tif (\n\t\t\texisting &&\n\t\t\texisting.status === \"synced\" &&\n\t\t\texisting.lastSynced !== null &&\n\t\t\texisting.lastSynced + 200 >= updatedAt\n\t\t) {\n\t\t\tthis.emit(\"stateChanged\", { docId, state: existing });\n\t\t\treturn true;\n\t\t}\n\n\t\tawait this.semaphore.acquire();\n\t\ttry {\n\t\t\tconst state = await this._doSyncDoc(docId);\n\t\t\tthis.syncStates.set(docId, state);\n\t\t\tawait this.persistence.setState(state).catch(() => null);\n\t\t\tthis.emit(\"stateChanged\", { docId, state });\n\t\t\t// `retrying` and `error` are both failures that warrant another pass;\n\t\t\t// `unavailable` is permanent so we report it as done (no retry).\n\t\t\treturn state.status !== \"error\" && state.status !== \"retrying\";\n\t\t} finally {\n\t\t\tthis.semaphore.release();\n\t\t}\n\t}\n\n\tprivate async _doSyncDoc(docId: string): Promise<DocSyncState> {\n\t\t// Non-UUID ids the server can't parse (422) are permanently unsyncable —\n\t\t// park them as `unavailable` rather than churning through retries.\n\t\tif (!isValidDocId(docId)) {\n\t\t\treturn {\n\t\t\t\tdocId,\n\t\t\t\tstatus: \"unavailable\",\n\t\t\t\tlastSynced: this.syncStates.get(docId)?.lastSynced ?? null,\n\t\t\t\terror: \"Invalid document id (not a UUID)\",\n\t\t\t\tconsecutiveFailures: 0,\n\t\t\t\tisE2E: false,\n\t\t\t};\n\t\t}\n\n\t\t// Mark as syncing\n\t\tconst syncing: DocSyncState = {\n\t\t\tdocId,\n\t\t\tstatus: \"syncing\",\n\t\t\tlastSynced: this.syncStates.get(docId)?.lastSynced ?? null,\n\t\t\tisE2E: false,\n\t\t};\n\t\tthis.syncStates.set(docId, syncing);\n\t\tthis.emit(\"stateChanged\", { docId, state: syncing });\n\n\t\tlet isE2E = false;\n\t\ttry {\n\t\t\t// Check encryption type\n\t\t\ttry {\n\t\t\t\tconst enc = await this.client.getDocEncryption(docId);\n\t\t\t\tisE2E = enc.mode === \"e2e\";\n\t\t\t} catch {\n\t\t\t\t// If we can't check, treat as non-E2E\n\t\t\t}\n\n\t\t\tif (isE2E) {\n\t\t\t\treturn await this._syncE2EDoc(docId);\n\t\t\t} else {\n\t\t\t\treturn await this._syncNonE2EDoc(docId);\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tconst error = err instanceof Error ? err.message : String(err);\n\t\t\tconst prev = this.syncStates.get(docId);\n\t\t\tconst lastSynced = prev?.lastSynced ?? null;\n\n\t\t\t// Permanent failure (deleted / forbidden / unparseable) — park it as\n\t\t\t// `unavailable` so we stop retrying and never surface it as an error.\n\t\t\tif (isPermanentSyncError(err)) {\n\t\t\t\treturn {\n\t\t\t\t\tdocId,\n\t\t\t\t\tstatus: \"unavailable\",\n\t\t\t\t\tlastSynced,\n\t\t\t\t\terror,\n\t\t\t\t\tconsecutiveFailures: 0,\n\t\t\t\t\tisE2E,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Transient failure — escalate to a genuine `error` only once it has\n\t\t\t// recurred past the threshold; otherwise keep it calm as `retrying`.\n\t\t\tconst consecutiveFailures = (prev?.consecutiveFailures ?? 0) + 1;\n\t\t\treturn {\n\t\t\t\tdocId,\n\t\t\t\tstatus:\n\t\t\t\t\tconsecutiveFailures >= FAILURE_THRESHOLD ? \"error\" : \"retrying\",\n\t\t\t\tlastSynced,\n\t\t\t\terror,\n\t\t\t\tconsecutiveFailures,\n\t\t\t\tisE2E,\n\t\t\t};\n\t\t}\n\t}\n\n\tprivate async _syncNonE2EDoc(docId: string): Promise<DocSyncState> {\n\t\tconst treeMap = this.rootProvider.document.getMap(\"doc-tree\") as Y.Map<any>;\n\n\t\t// Check if the provider already exists (user is viewing it) before loading.\n\t\tconst alreadyCached = this.rootProvider.children.has(docId);\n\n\t\t// Another provider (e.g. a nested renderer) may have already loaded\n\t\t// this doc through a different parent. The shared WS providerMap\n\t\t// tracks all attached providers; if one exists, the doc is already\n\t\t// syncing — skip to avoid creating a duplicate.\n\t\tif (!alreadyCached) {\n\t\t\tconst wsProviderMap = (this.rootProvider as any).configuration\n\t\t\t\t?.websocketProvider?.configuration?.providerMap as\n\t\t\t\t| Map<string, unknown>\n\t\t\t\t| undefined;\n\t\t\tif (wsProviderMap?.has(docId)) {\n\t\t\t\treturn {\n\t\t\t\t\tdocId,\n\t\t\t\t\tstatus: \"synced\",\n\t\t\t\t\tlastSynced: Date.now(),\n\t\t\t\t\tconsecutiveFailures: 0,\n\t\t\t\t\tisE2E: false,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\t// Load transiently: a background-sync child must neither count toward\n\t\t// the parent's LRU budget nor evict the user's open docs, and it must\n\t\t// not be evicted out from under its own in-flight sync. We clean it up\n\t\t// explicitly in `finally`.\n\t\tconst childProvider = await this.rootProvider.loadChild(docId, {\n\t\t\tevictable: false,\n\t\t});\n\n\t\ttry {\n\t\t\t// Wait for ready (offline snapshot loaded) then synced (server sync done)\n\t\t\tawait childProvider.ready;\n\t\t\tawait this._waitForSynced(childProvider);\n\n\t\t\t// Force the offline snapshot to disk BEFORE the `finally` below\n\t\t\t// unloads (and therefore destroys) this provider. The provider's own\n\t\t\t// \"synced\" handler also writes one, but that runs concurrently and\n\t\t\t// loses the race often enough that most background-synced documents\n\t\t\t// ended up with an empty offline cache — which is also why the\n\t\t\t// client-side search/backlink index had almost nothing to walk.\n\t\t\t// \"Synced\" must mean \"on disk\", or this manager is lying.\n\t\t\tif (typeof (childProvider as any).persistSnapshot === \"function\") {\n\t\t\t\tawait (childProvider as any).persistSnapshot();\n\t\t\t}\n\n\t\t\t// Emit docSynced while the child is still loaded so listeners can\n\t\t\t// extract data (search text, file refs) without opening a new IDB.\n\t\t\t{\n\t\t\t\tconst treeEntry = treeMap.get(docId);\n\t\t\t\tthis.emit(\"docSynced\", {\n\t\t\t\t\tdocId,\n\t\t\t\t\tdocument: childProvider.document,\n\t\t\t\t\tlabel: treeEntry?.label ?? \"\",\n\t\t\t\t\tmeta: treeEntry?.meta,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Prefetch file blobs\n\t\t\tif (this.opts.prefetchFiles && this.fileBlobStore) {\n\t\t\t\tthis._prefetchDocFiles(docId, childProvider.document).catch(() => null);\n\t\t\t}\n\n\t\t\t// Use the tree's updatedAt so lastSynced >= updatedAt, preventing\n\t\t\t// the observer's timestamp write from triggering a spurious re-sync.\n\t\t\tconst treeEntry = treeMap.get(docId);\n\t\t\tconst treeUpdatedAt = treeEntry?.updatedAt ?? treeEntry?.createdAt ?? 0;\n\t\t\treturn {\n\t\t\t\tdocId,\n\t\t\t\tstatus: \"synced\",\n\t\t\t\tlastSynced: Math.max(Date.now(), treeUpdatedAt),\n\t\t\t\tconsecutiveFailures: 0,\n\t\t\t\tisE2E: false,\n\t\t\t};\n\t\t} finally {\n\t\t\t// Release the provider only if we created it solely for background\n\t\t\t// sync. Two cases keep it alive:\n\t\t\t// - `alreadyCached`: it was loaded before we started — the UI owns it.\n\t\t\t// - the user OPENED it mid-sync: `loadChild` (default evictable)\n\t\t\t// promoted it out of transient, so it's no longer ours. Destroying\n\t\t\t// it here would detach the provider under a doc they're viewing,\n\t\t\t// leaving it stuck on a blue/\"retrying\" indicator until reload.\n\t\t\t// `isChildTransient` is a newer provider API; fall back to the old\n\t\t\t// unconditional unload if the parent predates it.\n\t\t\tif (!alreadyCached) {\n\t\t\t\tconst stillOurs =\n\t\t\t\t\ttypeof (this.rootProvider as any).isChildTransient === \"function\"\n\t\t\t\t\t\t? (this.rootProvider as any).isChildTransient(docId)\n\t\t\t\t\t\t: true;\n\t\t\t\tif (stillOurs) this.rootProvider.unloadChild(docId);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async _syncE2EDoc(docId: string): Promise<DocSyncState> {\n\t\tconst treeMap = this.rootProvider.document.getMap(\"doc-tree\") as Y.Map<any>;\n\n\t\t// Attempt E2E sync only when docKeyManager and keystore are available\n\t\tconst docKeyManager = (this.rootProvider as any).abracadabraConfig\n\t\t\t?.docKeyManager;\n\t\tconst keystore = (this.rootProvider as any).abracadabraConfig?.keystore;\n\n\t\tif (!docKeyManager || !keystore) {\n\t\t\t// No key management configured — skip silently\n\t\t\treturn {\n\t\t\t\tdocId,\n\t\t\t\tstatus: \"skipped\",\n\t\t\t\tlastSynced: null,\n\t\t\t\tconsecutiveFailures: 0,\n\t\t\t\tisE2E: true,\n\t\t\t};\n\t\t}\n\n\t\tconst childDoc = new Y.Doc({ guid: docId });\n\t\tconst childProvider = new E2EAbracadabraProvider({\n\t\t\tname: docId,\n\t\t\tdocument: childDoc,\n\t\t\tclient: this.client,\n\t\t\tdocKeyManager,\n\t\t\tkeystore,\n\t\t});\n\n\t\ttry {\n\t\t\tawait childProvider.ready;\n\t\t\tawait this._waitForSynced(childProvider);\n\n\t\t\t// Emit docSynced while the child is still alive so listeners can\n\t\t\t// extract data without opening a new IDB connection.\n\t\t\t{\n\t\t\t\tconst treeEntry = treeMap.get(docId);\n\t\t\t\tthis.emit(\"docSynced\", {\n\t\t\t\t\tdocId,\n\t\t\t\t\tdocument: childDoc,\n\t\t\t\t\tlabel: treeEntry?.label ?? \"\",\n\t\t\t\t\tmeta: treeEntry?.meta,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (this.opts.prefetchFiles && this.fileBlobStore) {\n\t\t\t\tthis._prefetchDocFiles(docId, childDoc).catch(() => null);\n\t\t\t}\n\n\t\t\t// Use the tree's updatedAt so lastSynced >= updatedAt, preventing\n\t\t\t// the observer's timestamp write from triggering a spurious re-sync.\n\t\t\tconst treeEntry = treeMap.get(docId);\n\t\t\tconst treeUpdatedAt = treeEntry?.updatedAt ?? treeEntry?.createdAt ?? 0;\n\t\t\treturn {\n\t\t\t\tdocId,\n\t\t\t\tstatus: \"synced\",\n\t\t\t\tlastSynced: Math.max(Date.now(), treeUpdatedAt),\n\t\t\t\tconsecutiveFailures: 0,\n\t\t\t\tisE2E: true,\n\t\t\t};\n\t\t} finally {\n\t\t\tchildProvider.destroy();\n\t\t}\n\t}\n\n\t/**\n\t * Wait for a provider to emit the \"synced\" event (with state=true),\n\t * timing out after opts.syncTimeout ms.\n\t */\n\tprivate _waitForSynced(provider: any): Promise<void> {\n\t\t// If already synced, resolve immediately\n\t\tif (provider.synced === true) return Promise.resolve();\n\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tprovider.off(\"synced\", onSynced);\n\t\t\t\treject(new Error(`Sync timeout after ${this.opts.syncTimeout}ms`));\n\t\t\t}, this.opts.syncTimeout);\n\n\t\t\tfunction onSynced(state: boolean | { state: boolean }) {\n\t\t\t\t// Hocuspocus passes `{ state }` or a boolean directly\n\t\t\t\tconst synced =\n\t\t\t\t\ttypeof state === \"boolean\" ? state : (state as any)?.state ?? state;\n\t\t\t\tif (synced) {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tprovider.off(\"synced\", onSynced);\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprovider.on(\"synced\", onSynced);\n\t\t});\n\t}\n\n\t/**\n\t * Pre-cache all cover images referenced in the root tree map.\n\t */\n\tprivate async _prefetchCovers(entries: Array<[string, any]>): Promise<void> {\n\t\tif (!this.fileBlobStore) return;\n\t\tfor (const [docId, v] of entries) {\n\t\t\tconst coverUploadId = v?.meta?.coverUploadId;\n\t\t\tif (coverUploadId) {\n\t\t\t\tthis.fileBlobStore.getBlobUrl(docId, coverUploadId).catch(() => null);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Pre-cache file blobs referenced in a synced Y.Doc.\n\t * Walks:\n\t * - ydoc.getXmlFragment('default') for `fileBlock` nodes (TipTap)\n\t * - ydoc.getMap('doc-tree') for meta.coverUploadId entries\n\t */\n\tprivate async _prefetchDocFiles(\n\t\tdocId: string,\n\t\tydoc: Y.Doc,\n\t): Promise<void> {\n\t\tif (!this.fileBlobStore) return;\n\n\t\tconst refs = this._extractFileRefs(ydoc);\n\t\tfor (const { refDocId, uploadId } of refs) {\n\t\t\tthis.fileBlobStore\n\t\t\t\t.getBlobUrl(refDocId ?? docId, uploadId)\n\t\t\t\t.catch(() => null);\n\t\t}\n\t}\n\n\tprivate _extractFileRefs(\n\t\tydoc: Y.Doc,\n\t): Array<{ refDocId: string | null; uploadId: string }> {\n\t\tconst refs: Array<{ refDocId: string | null; uploadId: string }> = [];\n\n\t\t// Walk XML fragment for fileBlock nodes\n\t\ttry {\n\t\t\tconst fragment = ydoc.getXmlFragment(\"default\");\n\t\t\tthis._walkXml(fragment, refs);\n\t\t} catch {}\n\n\t\t// Walk doc-tree meta for cover upload IDs\n\t\ttry {\n\t\t\tconst treeMap = ydoc.getMap(\"doc-tree\") as Y.Map<any>;\n\t\t\tfor (const [id, v] of treeMap.entries()) {\n\t\t\t\tconst coverUploadId = v?.meta?.coverUploadId;\n\t\t\t\tif (coverUploadId) {\n\t\t\t\t\trefs.push({ refDocId: id, uploadId: coverUploadId });\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {}\n\n\t\treturn refs;\n\t}\n\n\tprivate _walkXml(\n\t\tnode: Y.XmlFragment | Y.XmlElement,\n\t\trefs: Array<{ refDocId: string | null; uploadId: string }>,\n\t): void {\n\t\tfor (const child of node.toArray()) {\n\t\t\tif (child instanceof Y.XmlElement) {\n\t\t\t\tif (child.nodeName === \"fileBlock\") {\n\t\t\t\t\tconst uploadId = child.getAttribute(\"uploadId\");\n\t\t\t\t\tconst refDocId = child.getAttribute(\"docId\") ?? null;\n\t\t\t\t\tif (uploadId) refs.push({ refDocId, uploadId });\n\t\t\t\t}\n\t\t\t\tthis._walkXml(child, refs);\n\t\t\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