@dabble/patches 0.3.2 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/algorithms/client/makeChange.d.ts +2 -3
- package/dist/algorithms/client/makeChange.js +1 -1
- package/dist/algorithms/server/getSnapshotAtRevision.d.ts +1 -1
- package/dist/algorithms/server/getStateAtRevision.d.ts +1 -1
- package/dist/algorithms/server/handleOfflineSessionsAndBatches.d.ts +1 -1
- package/dist/client/InMemoryStore.js +1 -3
- package/dist/client/IndexedDBStore.js +345 -342
- package/dist/client/Patches.js +156 -156
- package/dist/client/PatchesDoc.d.ts +4 -5
- package/dist/client/PatchesDoc.js +16 -13
- package/dist/client/PatchesHistoryClient.js +12 -8
- package/dist/json-patch/JSONPatch.js +2 -0
- package/dist/json-patch/createJSONPatch.d.ts +15 -18
- package/dist/json-patch/createJSONPatch.js +18 -20
- package/dist/json-patch/pathProxy.d.ts +22 -0
- package/dist/json-patch/pathProxy.js +50 -0
- package/dist/json-patch/utils/getType.d.ts +1 -1
- package/dist/net/PatchesSync.js +307 -303
- package/dist/net/error.js +1 -0
- package/dist/net/protocol/JSONRPCClient.js +4 -3
- package/dist/net/protocol/JSONRPCServer.js +6 -8
- package/dist/net/webrtc/WebRTCAwareness.js +12 -7
- package/dist/net/webrtc/WebRTCTransport.d.ts +1 -1
- package/dist/net/webrtc/WebRTCTransport.js +27 -21
- package/dist/net/websocket/PatchesWebSocket.js +7 -2
- package/dist/net/websocket/RPCServer.js +5 -0
- package/dist/net/websocket/SignalingService.js +1 -3
- package/dist/net/websocket/WebSocketServer.js +2 -0
- package/dist/net/websocket/WebSocketTransport.js +21 -19
- package/dist/net/websocket/onlineState.js +2 -2
- package/dist/server/PatchesBranchManager.js +2 -0
- package/dist/server/PatchesHistoryManager.js +2 -0
- package/dist/server/PatchesServer.d.ts +2 -2
- package/dist/server/PatchesServer.js +7 -5
- package/dist/types.d.ts +15 -6
- package/dist/types.js +1 -1
- package/package.json +3 -2
- package/dist/json-patch/patchProxy.d.ts +0 -42
- package/dist/json-patch/patchProxy.js +0 -126
package/dist/net/PatchesSync.js
CHANGED
|
@@ -45,345 +45,349 @@ import { onlineState } from './websocket/onlineState.js';
|
|
|
45
45
|
* the Patches instance and the server.
|
|
46
46
|
*/
|
|
47
47
|
let PatchesSync = (() => {
|
|
48
|
-
var _a;
|
|
49
48
|
let _instanceExtraInitializers = [];
|
|
50
49
|
let _syncDoc_decorators;
|
|
51
50
|
let __receiveCommittedChanges_decorators;
|
|
52
|
-
return
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
51
|
+
return class PatchesSync {
|
|
52
|
+
static {
|
|
53
|
+
const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
|
|
54
|
+
_syncDoc_decorators = [blockable];
|
|
55
|
+
__receiveCommittedChanges_decorators = [blockable];
|
|
56
|
+
__esDecorate(this, null, _syncDoc_decorators, { kind: "method", name: "syncDoc", static: false, private: false, access: { has: obj => "syncDoc" in obj, get: obj => obj.syncDoc }, metadata: _metadata }, null, _instanceExtraInitializers);
|
|
57
|
+
__esDecorate(this, null, __receiveCommittedChanges_decorators, { kind: "method", name: "_receiveCommittedChanges", static: false, private: false, access: { has: obj => "_receiveCommittedChanges" in obj, get: obj => obj._receiveCommittedChanges }, metadata: _metadata }, null, _instanceExtraInitializers);
|
|
58
|
+
if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
|
|
59
|
+
}
|
|
60
|
+
options = __runInitializers(this, _instanceExtraInitializers);
|
|
61
|
+
ws;
|
|
62
|
+
patches;
|
|
63
|
+
store;
|
|
64
|
+
maxPayloadBytes;
|
|
65
|
+
trackedDocs;
|
|
66
|
+
_state = { online: false, connected: false, syncing: null };
|
|
67
|
+
/**
|
|
68
|
+
* Signal emitted when the sync state changes.
|
|
69
|
+
*/
|
|
70
|
+
onStateChange = signal();
|
|
71
|
+
/**
|
|
72
|
+
* Signal emitted when an error occurs.
|
|
73
|
+
*/
|
|
74
|
+
onError = signal();
|
|
75
|
+
constructor(patches, url, options) {
|
|
76
|
+
this.options = options;
|
|
77
|
+
this.patches = patches;
|
|
78
|
+
this.store = patches.store;
|
|
79
|
+
this.maxPayloadBytes = patches.docOptions?.maxPayloadBytes;
|
|
80
|
+
this.ws = new PatchesWebSocket(url, options?.websocket);
|
|
81
|
+
this._state.online = onlineState.isOnline;
|
|
82
|
+
this.trackedDocs = new Set(patches.trackedDocs);
|
|
83
|
+
// --- Event Listeners ---
|
|
84
|
+
onlineState.onOnlineChange(online => this.updateState({ online }));
|
|
85
|
+
this.ws.onStateChange(this._handleConnectionChange.bind(this));
|
|
86
|
+
this.ws.onChangesCommitted(this._receiveCommittedChanges.bind(this));
|
|
87
|
+
// Listen to Patches for tracking changes
|
|
88
|
+
patches.onTrackDocs(this._handleDocsTracked.bind(this));
|
|
89
|
+
patches.onUntrackDocs(this._handleDocsUntracked.bind(this));
|
|
90
|
+
patches.onDeleteDoc(this._handleDocDeleted.bind(this));
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Gets the current sync state.
|
|
94
|
+
*/
|
|
95
|
+
get state() {
|
|
96
|
+
return this._state;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Updates the sync state.
|
|
100
|
+
* @param update - The partial state to update.
|
|
101
|
+
*/
|
|
102
|
+
updateState(update) {
|
|
103
|
+
const newState = { ...this._state, ...update };
|
|
104
|
+
if (!isEqual(this._state, newState)) {
|
|
105
|
+
this._state = newState;
|
|
106
|
+
this.onStateChange.emit(this._state);
|
|
95
107
|
}
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
catch (err) {
|
|
104
|
-
console.error('PatchesSync connection failed:', err);
|
|
105
|
-
this.updateState({ connected: false, syncing: err instanceof Error ? err : new Error(String(err)) });
|
|
106
|
-
this.onError.emit(err);
|
|
107
|
-
throw err;
|
|
108
|
-
}
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Connects to the WebSocket server and starts syncing if online. If not online, it will wait for online state.
|
|
111
|
+
*/
|
|
112
|
+
async connect() {
|
|
113
|
+
try {
|
|
114
|
+
await this.ws.connect();
|
|
109
115
|
}
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
this.updateState({ connected: false, syncing: null });
|
|
116
|
+
catch (err) {
|
|
117
|
+
console.error('PatchesSync connection failed:', err);
|
|
118
|
+
this.updateState({ connected: false, syncing: err instanceof Error ? err : new Error(String(err)) });
|
|
119
|
+
this.onError.emit(err);
|
|
120
|
+
throw err;
|
|
116
121
|
}
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Disconnects from the WebSocket server and stops syncing.
|
|
125
|
+
*/
|
|
126
|
+
disconnect() {
|
|
127
|
+
this.ws.disconnect();
|
|
128
|
+
this.updateState({ connected: false, syncing: null });
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Syncs all known docs when initially connected.
|
|
132
|
+
*/
|
|
133
|
+
async syncAllKnownDocs() {
|
|
134
|
+
if (!this.state.connected)
|
|
135
|
+
return;
|
|
136
|
+
this.updateState({ syncing: 'updating' });
|
|
137
|
+
try {
|
|
138
|
+
const tracked = await this.store.listDocs(true); // Include deleted docs
|
|
139
|
+
const activeDocs = tracked.filter(t => !t.deleted);
|
|
140
|
+
const deletedDocs = tracked.filter(t => t.deleted);
|
|
141
|
+
const activeDocIds = activeDocs.map((t) => t.docId);
|
|
142
|
+
// Ensure tracked set reflects only active docs for subscription purposes
|
|
143
|
+
this.trackedDocs = new Set(activeDocIds);
|
|
144
|
+
// Subscribe to active docs
|
|
145
|
+
if (activeDocIds.length > 0) {
|
|
146
|
+
try {
|
|
147
|
+
const subscribeIds = this.options?.subscribeFilter?.(activeDocIds) || activeDocIds;
|
|
148
|
+
if (subscribeIds.length) {
|
|
149
|
+
await this.ws.subscribe(subscribeIds);
|
|
142
150
|
}
|
|
143
151
|
}
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
try {
|
|
149
|
-
console.info(`Attempting server delete for tombstoned doc: ${docId}`);
|
|
150
|
-
await this.ws.deleteDoc(docId);
|
|
151
|
-
// If server delete succeeds, remove tombstone and all data locally
|
|
152
|
-
await this.store.confirmDeleteDoc(docId);
|
|
153
|
-
console.info(`Successfully deleted and untracked doc: ${docId}`);
|
|
154
|
-
}
|
|
155
|
-
catch (err) {
|
|
156
|
-
// If server delete fails (e.g., offline, already deleted), keep tombstone for retry
|
|
157
|
-
console.warn(`Server delete failed for ${docId}, keeping tombstone:`, err);
|
|
158
|
-
this.onError.emit(err, { docId });
|
|
159
|
-
}
|
|
160
|
-
});
|
|
161
|
-
// Wait for all sync and delete operations
|
|
162
|
-
await Promise.all([...activeSyncPromises, ...deletePromises]);
|
|
163
|
-
this.updateState({ syncing: null });
|
|
164
|
-
}
|
|
165
|
-
catch (error) {
|
|
166
|
-
console.error('Error during global sync:', error);
|
|
167
|
-
this.updateState({ syncing: error instanceof Error ? error : new Error(String(error)) });
|
|
168
|
-
this.onError.emit(error);
|
|
152
|
+
catch (err) {
|
|
153
|
+
console.warn('Error subscribing to active docs during sync:', err);
|
|
154
|
+
this.onError.emit(err);
|
|
155
|
+
}
|
|
169
156
|
}
|
|
157
|
+
// Sync each active doc
|
|
158
|
+
const activeSyncPromises = activeDocIds.map((id) => this.syncDoc(id));
|
|
159
|
+
// Attempt to delete docs marked with tombstones
|
|
160
|
+
const deletePromises = deletedDocs.map(async ({ docId }) => {
|
|
161
|
+
try {
|
|
162
|
+
console.info(`Attempting server delete for tombstoned doc: ${docId}`);
|
|
163
|
+
await this.ws.deleteDoc(docId);
|
|
164
|
+
// If server delete succeeds, remove tombstone and all data locally
|
|
165
|
+
await this.store.confirmDeleteDoc(docId);
|
|
166
|
+
console.info(`Successfully deleted and untracked doc: ${docId}`);
|
|
167
|
+
}
|
|
168
|
+
catch (err) {
|
|
169
|
+
// If server delete fails (e.g., offline, already deleted), keep tombstone for retry
|
|
170
|
+
console.warn(`Server delete failed for ${docId}, keeping tombstone:`, err);
|
|
171
|
+
this.onError.emit(err, { docId });
|
|
172
|
+
}
|
|
173
|
+
});
|
|
174
|
+
// Wait for all sync and delete operations
|
|
175
|
+
await Promise.all([...activeSyncPromises, ...deletePromises]);
|
|
176
|
+
this.updateState({ syncing: null });
|
|
170
177
|
}
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
178
|
+
catch (error) {
|
|
179
|
+
console.error('Error during global sync:', error);
|
|
180
|
+
this.updateState({ syncing: error instanceof Error ? error : new Error(String(error)) });
|
|
181
|
+
this.onError.emit(error);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Syncs a single document.
|
|
186
|
+
* @param docId The ID of the document to sync.
|
|
187
|
+
*/
|
|
188
|
+
async syncDoc(docId) {
|
|
189
|
+
if (!this.state.connected)
|
|
190
|
+
return;
|
|
191
|
+
const doc = this.patches.getOpenDoc(docId);
|
|
192
|
+
if (doc) {
|
|
193
|
+
doc.updateSyncing('updating');
|
|
194
|
+
}
|
|
195
|
+
try {
|
|
196
|
+
const pending = await this.store.getPendingChanges(docId);
|
|
197
|
+
if (pending.length > 0) {
|
|
198
|
+
await this.flushDoc(docId); // flushDoc handles setting flushing state
|
|
181
199
|
}
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
if (committedRev) {
|
|
191
|
-
const serverChanges = await this.ws.getChangesSince(docId, committedRev);
|
|
192
|
-
if (serverChanges.length > 0) {
|
|
193
|
-
// Apply server changes with proper rebasing
|
|
194
|
-
await this._applyServerChangesToDoc(docId, serverChanges);
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
else {
|
|
198
|
-
const snapshot = await this.ws.getDoc(docId);
|
|
199
|
-
await this.store.saveDoc(docId, snapshot);
|
|
200
|
+
else {
|
|
201
|
+
// No pending, just check for server changes
|
|
202
|
+
const [committedRev] = await this.store.getLastRevs(docId);
|
|
203
|
+
if (committedRev) {
|
|
204
|
+
const serverChanges = await this.ws.getChangesSince(docId, committedRev);
|
|
205
|
+
if (serverChanges.length > 0) {
|
|
206
|
+
// Apply server changes with proper rebasing
|
|
207
|
+
await this._applyServerChangesToDoc(docId, serverChanges);
|
|
200
208
|
}
|
|
201
209
|
}
|
|
202
|
-
|
|
203
|
-
|
|
210
|
+
else {
|
|
211
|
+
const snapshot = await this.ws.getDoc(docId);
|
|
212
|
+
await this.store.saveDoc(docId, snapshot);
|
|
204
213
|
}
|
|
205
214
|
}
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
this.onError.emit(err, { docId });
|
|
209
|
-
if (doc) {
|
|
210
|
-
doc.updateSyncing(err instanceof Error ? err : new Error(String(err)));
|
|
211
|
-
}
|
|
215
|
+
if (doc) {
|
|
216
|
+
doc.updateSyncing(null);
|
|
212
217
|
}
|
|
213
218
|
}
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
if (!this.trackedDocs.has(docId)) {
|
|
220
|
-
throw new Error(`Document ${docId} is not tracked`);
|
|
219
|
+
catch (err) {
|
|
220
|
+
console.error(`Error syncing doc ${docId}:`, err);
|
|
221
|
+
this.onError.emit(err, { docId });
|
|
222
|
+
if (doc) {
|
|
223
|
+
doc.updateSyncing(err instanceof Error ? err : new Error(String(err)));
|
|
221
224
|
}
|
|
222
|
-
|
|
223
|
-
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Flushes a document to the server.
|
|
229
|
+
* @param docId The ID of the document to flush.
|
|
230
|
+
*/
|
|
231
|
+
async flushDoc(docId) {
|
|
232
|
+
if (!this.trackedDocs.has(docId)) {
|
|
233
|
+
throw new Error(`Document ${docId} is not tracked`);
|
|
234
|
+
}
|
|
235
|
+
if (!this.state.connected) {
|
|
236
|
+
throw new Error('Not connected to server');
|
|
237
|
+
}
|
|
238
|
+
try {
|
|
239
|
+
// Get changes from store or memory
|
|
240
|
+
let pending = await this.store.getPendingChanges(docId);
|
|
241
|
+
if (!pending.length) {
|
|
242
|
+
return; // Nothing to flush
|
|
224
243
|
}
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
return; // Nothing to flush
|
|
230
|
-
}
|
|
231
|
-
const batches = breakIntoBatches(pending, this.maxPayloadBytes);
|
|
232
|
-
for (const batch of batches) {
|
|
233
|
-
if (!this.state.connected) {
|
|
234
|
-
throw new Error('Disconnected during flush');
|
|
235
|
-
}
|
|
236
|
-
const range = [batch[0].rev, batch[batch.length - 1].rev];
|
|
237
|
-
const committed = await this.ws.commitChanges(docId, batch);
|
|
238
|
-
// Apply the committed changes using the sync algorithm (already saved to store)
|
|
239
|
-
await this._applyServerChangesToDoc(docId, committed, range);
|
|
240
|
-
// Fetch remaining pending for next batch or check completion
|
|
241
|
-
pending = await this.store.getPendingChanges(docId);
|
|
244
|
+
const batches = breakIntoBatches(pending, this.maxPayloadBytes);
|
|
245
|
+
for (const batch of batches) {
|
|
246
|
+
if (!this.state.connected) {
|
|
247
|
+
throw new Error('Disconnected during flush');
|
|
242
248
|
}
|
|
249
|
+
const range = [batch[0].rev, batch[batch.length - 1].rev];
|
|
250
|
+
const committed = await this.ws.commitChanges(docId, batch);
|
|
251
|
+
// Apply the committed changes using the sync algorithm (already saved to store)
|
|
252
|
+
await this._applyServerChangesToDoc(docId, committed, range);
|
|
253
|
+
// Fetch remaining pending for next batch or check completion
|
|
254
|
+
pending = await this.store.getPendingChanges(docId);
|
|
243
255
|
}
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
256
|
+
}
|
|
257
|
+
catch (err) {
|
|
258
|
+
console.error(`Flush failed for doc ${docId}:`, err);
|
|
259
|
+
this.onError.emit(err, { docId });
|
|
260
|
+
throw err; // Re-throw so caller (like syncAll) knows it failed
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Receives committed changes from the server and applies them to the document. This is a blockable function, so it
|
|
265
|
+
* is separate from applyServerChangesToDoc, which is called by other blockable functions. Ensuring this is blockable
|
|
266
|
+
* ensures that while a doc is sending changes to the server, it isn't receiving changes from the server which could
|
|
267
|
+
* cause a race condition.
|
|
268
|
+
*/
|
|
269
|
+
async _receiveCommittedChanges(docId, serverChanges) {
|
|
270
|
+
try {
|
|
271
|
+
await this._applyServerChangesToDoc(docId, serverChanges);
|
|
272
|
+
}
|
|
273
|
+
catch (err) {
|
|
274
|
+
this.onError.emit(err, { docId });
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Applies server changes to a document using the centralized sync algorithm.
|
|
279
|
+
* This ensures consistent OT behavior regardless of whether the doc is open in memory.
|
|
280
|
+
*/
|
|
281
|
+
async _applyServerChangesToDoc(docId, serverChanges, sentPendingRange) {
|
|
282
|
+
// 1. Get current document snapshot from store
|
|
283
|
+
const currentSnapshot = await this.store.getDoc(docId);
|
|
284
|
+
if (!currentSnapshot) {
|
|
285
|
+
console.warn(`Cannot apply server changes to non-existent doc: ${docId}`);
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
const doc = this.patches.getOpenDoc(docId);
|
|
289
|
+
if (doc) {
|
|
290
|
+
// Ensure we have all the changes, stored and in-memory (newly created but not yet persisted)
|
|
291
|
+
const inMemoryPendingChanges = doc?.getPendingChanges();
|
|
292
|
+
const latestRev = currentSnapshot.changes[currentSnapshot.changes.length - 1]?.rev || currentSnapshot.rev;
|
|
293
|
+
const newChanges = inMemoryPendingChanges.filter(change => change.rev > latestRev);
|
|
294
|
+
currentSnapshot.changes.push(...newChanges);
|
|
295
|
+
}
|
|
296
|
+
// 2. Use the pure algorithm to calculate the new state
|
|
297
|
+
const { state, rev, changes: rebasedPendingChanges } = applyCommittedChanges(currentSnapshot, serverChanges);
|
|
298
|
+
// 3. If the doc is open in memory, update it with the new state
|
|
299
|
+
if (doc) {
|
|
300
|
+
if (doc.committedRev === serverChanges[0].rev - 1) {
|
|
301
|
+
// We can update the doc's snapshot
|
|
302
|
+
doc.applyCommittedChanges(serverChanges, rebasedPendingChanges);
|
|
303
|
+
}
|
|
304
|
+
else {
|
|
305
|
+
// We have to do a full state update
|
|
306
|
+
doc.import({ state, rev, changes: rebasedPendingChanges });
|
|
248
307
|
}
|
|
249
308
|
}
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
309
|
+
// 4. Save changes to store (if not already saved)
|
|
310
|
+
await Promise.all([
|
|
311
|
+
this.store.saveCommittedChanges(docId, serverChanges, sentPendingRange),
|
|
312
|
+
this.store.replacePendingChanges(docId, rebasedPendingChanges),
|
|
313
|
+
]);
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Initiates the deletion process for a document both locally and on the server.
|
|
317
|
+
* This now delegates the local tombstone marking to Patches.
|
|
318
|
+
*/
|
|
319
|
+
async _handleDocDeleted(docId) {
|
|
320
|
+
// Attempt server delete if online
|
|
321
|
+
if (this.state.connected) {
|
|
257
322
|
try {
|
|
258
|
-
await this.
|
|
323
|
+
await this.ws.deleteDoc(docId);
|
|
324
|
+
await this.store.confirmDeleteDoc(docId);
|
|
259
325
|
}
|
|
260
326
|
catch (err) {
|
|
327
|
+
console.error(`Server delete failed for doc ${docId}, will retry on reconnect/resync.`, err);
|
|
261
328
|
this.onError.emit(err, { docId });
|
|
329
|
+
throw err;
|
|
262
330
|
}
|
|
263
331
|
}
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
* This ensures consistent OT behavior regardless of whether the doc is open in memory.
|
|
267
|
-
*/
|
|
268
|
-
async _applyServerChangesToDoc(docId, serverChanges, sentPendingRange) {
|
|
269
|
-
// 1. Get current document snapshot from store
|
|
270
|
-
const currentSnapshot = await this.store.getDoc(docId);
|
|
271
|
-
if (!currentSnapshot) {
|
|
272
|
-
console.warn(`Cannot apply server changes to non-existent doc: ${docId}`);
|
|
273
|
-
return;
|
|
274
|
-
}
|
|
275
|
-
const doc = this.patches.getOpenDoc(docId);
|
|
276
|
-
if (doc) {
|
|
277
|
-
// Ensure we have all the changes, stored and in-memory (newly created but not yet persisted)
|
|
278
|
-
const inMemoryPendingChanges = doc?.getPendingChanges();
|
|
279
|
-
const latestRev = currentSnapshot.changes[currentSnapshot.changes.length - 1]?.rev || currentSnapshot.rev;
|
|
280
|
-
const newChanges = inMemoryPendingChanges.filter(change => change.rev > latestRev);
|
|
281
|
-
currentSnapshot.changes.push(...newChanges);
|
|
282
|
-
}
|
|
283
|
-
// 2. Use the pure algorithm to calculate the new state
|
|
284
|
-
const { state, rev, changes: rebasedPendingChanges } = applyCommittedChanges(currentSnapshot, serverChanges);
|
|
285
|
-
// 3. If the doc is open in memory, update it with the new state
|
|
286
|
-
if (doc) {
|
|
287
|
-
if (doc.committedRev === serverChanges[0].rev - 1) {
|
|
288
|
-
// We can update the doc's snapshot
|
|
289
|
-
doc.applyCommittedChanges(serverChanges, rebasedPendingChanges);
|
|
290
|
-
}
|
|
291
|
-
else {
|
|
292
|
-
// We have to do a full state update
|
|
293
|
-
doc.import({ state, rev, changes: rebasedPendingChanges });
|
|
294
|
-
}
|
|
295
|
-
}
|
|
296
|
-
// 4. Save changes to store (if not already saved)
|
|
297
|
-
await Promise.all([
|
|
298
|
-
this.store.saveCommittedChanges(docId, serverChanges, sentPendingRange),
|
|
299
|
-
this.store.replacePendingChanges(docId, rebasedPendingChanges),
|
|
300
|
-
]);
|
|
332
|
+
else {
|
|
333
|
+
console.warn(`Offline: Server delete for doc ${docId} deferred.`);
|
|
301
334
|
}
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
}
|
|
318
|
-
}
|
|
319
|
-
else {
|
|
320
|
-
console.warn(`Offline: Server delete for doc ${docId} deferred.`);
|
|
321
|
-
}
|
|
335
|
+
}
|
|
336
|
+
_handleConnectionChange(connectionState) {
|
|
337
|
+
const isConnected = connectionState === 'connected';
|
|
338
|
+
const isConnecting = connectionState === 'connecting';
|
|
339
|
+
// Preserve syncing state if moving from connecting -> connected
|
|
340
|
+
// Reset syncing if disconnected or errored
|
|
341
|
+
const newSyncingState = isConnected
|
|
342
|
+
? this._state.syncing // Preserve
|
|
343
|
+
: isConnecting
|
|
344
|
+
? this._state.syncing // Preserve during connecting phase too
|
|
345
|
+
: null; // Reset
|
|
346
|
+
this.updateState({ connected: isConnected, syncing: newSyncingState });
|
|
347
|
+
if (isConnected) {
|
|
348
|
+
// Sync everything on connect/reconnect
|
|
349
|
+
void this.syncAllKnownDocs();
|
|
322
350
|
}
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
if (isConnected) {
|
|
335
|
-
// Sync everything on connect/reconnect
|
|
336
|
-
void this.syncAllKnownDocs();
|
|
337
|
-
}
|
|
351
|
+
}
|
|
352
|
+
async _handleDocsTracked(docIds) {
|
|
353
|
+
const newIds = docIds.filter(id => !this.trackedDocs.has(id));
|
|
354
|
+
if (!newIds.length)
|
|
355
|
+
return;
|
|
356
|
+
newIds.forEach(id => this.trackedDocs.add(id));
|
|
357
|
+
let subscribeIds = newIds;
|
|
358
|
+
// If a subscribe filter is provided, filter out docs that are already tracked
|
|
359
|
+
if (this.options?.subscribeFilter) {
|
|
360
|
+
const alreadyTracked = this.options.subscribeFilter([...this.trackedDocs]);
|
|
361
|
+
subscribeIds = subscribeIds.filter(id => !alreadyTracked.includes(id));
|
|
338
362
|
}
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
newIds.forEach(id => this.trackedDocs.add(id));
|
|
344
|
-
let subscribeIds = newIds;
|
|
345
|
-
// If a subscribe filter is provided, filter out docs that are already tracked
|
|
346
|
-
if (this.options?.subscribeFilter) {
|
|
347
|
-
const alreadyTracked = this.options.subscribeFilter([...this.trackedDocs]);
|
|
348
|
-
subscribeIds = subscribeIds.filter(id => !alreadyTracked.includes(id));
|
|
349
|
-
}
|
|
350
|
-
if (this.state.connected) {
|
|
351
|
-
try {
|
|
352
|
-
if (subscribeIds.length) {
|
|
353
|
-
await this.ws.subscribe(subscribeIds);
|
|
354
|
-
}
|
|
355
|
-
// Trigger sync for newly tracked docs immediately
|
|
356
|
-
await Promise.all(newIds.map(id => this.syncDoc(id)));
|
|
357
|
-
}
|
|
358
|
-
catch (err) {
|
|
359
|
-
console.warn(`Failed to subscribe/sync newly tracked docs: ${newIds.join(', ')}`, err);
|
|
360
|
-
this.onError.emit(err);
|
|
363
|
+
if (this.state.connected) {
|
|
364
|
+
try {
|
|
365
|
+
if (subscribeIds.length) {
|
|
366
|
+
await this.ws.subscribe(subscribeIds);
|
|
361
367
|
}
|
|
368
|
+
// Trigger sync for newly tracked docs immediately
|
|
369
|
+
await Promise.all(newIds.map(id => this.syncDoc(id)));
|
|
370
|
+
}
|
|
371
|
+
catch (err) {
|
|
372
|
+
console.warn(`Failed to subscribe/sync newly tracked docs: ${newIds.join(', ')}`, err);
|
|
373
|
+
this.onError.emit(err);
|
|
362
374
|
}
|
|
363
375
|
}
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
}
|
|
376
|
+
}
|
|
377
|
+
async _handleDocsUntracked(docIds) {
|
|
378
|
+
const existingIds = docIds.filter(id => this.trackedDocs.has(id));
|
|
379
|
+
if (!existingIds.length)
|
|
380
|
+
return;
|
|
381
|
+
existingIds.forEach(id => this.trackedDocs.delete(id));
|
|
382
|
+
if (this.state.connected) {
|
|
383
|
+
try {
|
|
384
|
+
await this.ws.unsubscribe(existingIds);
|
|
385
|
+
}
|
|
386
|
+
catch (err) {
|
|
387
|
+
console.warn(`Failed to unsubscribe docs: ${existingIds.join(', ')}`, err);
|
|
376
388
|
}
|
|
377
389
|
}
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
|
|
381
|
-
_syncDoc_decorators = [blockable];
|
|
382
|
-
__receiveCommittedChanges_decorators = [blockable];
|
|
383
|
-
__esDecorate(_a, null, _syncDoc_decorators, { kind: "method", name: "syncDoc", static: false, private: false, access: { has: obj => "syncDoc" in obj, get: obj => obj.syncDoc }, metadata: _metadata }, null, _instanceExtraInitializers);
|
|
384
|
-
__esDecorate(_a, null, __receiveCommittedChanges_decorators, { kind: "method", name: "_receiveCommittedChanges", static: false, private: false, access: { has: obj => "_receiveCommittedChanges" in obj, get: obj => obj._receiveCommittedChanges }, metadata: _metadata }, null, _instanceExtraInitializers);
|
|
385
|
-
if (_metadata) Object.defineProperty(_a, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
|
|
386
|
-
})(),
|
|
387
|
-
_a;
|
|
390
|
+
}
|
|
391
|
+
};
|
|
388
392
|
})();
|
|
389
393
|
export { PatchesSync };
|