@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.
Files changed (151) hide show
  1. package/dist/abracadabra-provider.cjs +6673 -6543
  2. package/dist/abracadabra-provider.cjs.map +1 -1
  3. package/dist/esm/AbracadabraBaseProvider.js +558 -0
  4. package/dist/esm/AbracadabraBaseProvider.js.map +1 -0
  5. package/dist/esm/AbracadabraClient.js +1424 -0
  6. package/dist/esm/AbracadabraClient.js.map +1 -0
  7. package/dist/esm/AbracadabraProvider.js +547 -0
  8. package/dist/esm/AbracadabraProvider.js.map +1 -0
  9. package/dist/esm/AbracadabraWS.js +398 -0
  10. package/dist/esm/AbracadabraWS.js.map +1 -0
  11. package/dist/esm/BackgroundSyncManager.js +571 -0
  12. package/dist/esm/BackgroundSyncManager.js.map +1 -0
  13. package/dist/esm/BackgroundSyncPersistence.js +62 -0
  14. package/dist/esm/BackgroundSyncPersistence.js.map +1 -0
  15. package/dist/esm/ChatClient.js +176 -0
  16. package/dist/esm/ChatClient.js.map +1 -0
  17. package/dist/esm/CloseEvents.js +45 -0
  18. package/dist/esm/CloseEvents.js.map +1 -0
  19. package/dist/esm/ContentManager.js +153 -0
  20. package/dist/esm/ContentManager.js.map +1 -0
  21. package/dist/esm/CoverReconcile.js +124 -0
  22. package/dist/esm/CoverReconcile.js.map +1 -0
  23. package/dist/esm/CryptoIdentityKeystore.js +580 -0
  24. package/dist/esm/CryptoIdentityKeystore.js.map +1 -0
  25. package/dist/esm/DeviceRegistrationService.js +158 -0
  26. package/dist/esm/DeviceRegistrationService.js.map +1 -0
  27. package/dist/esm/DocConverters.js +1300 -0
  28. package/dist/esm/DocConverters.js.map +1 -0
  29. package/dist/esm/DocKeyManager.js +145 -0
  30. package/dist/esm/DocKeyManager.js.map +1 -0
  31. package/dist/esm/DocTypes.js +792 -0
  32. package/dist/esm/DocTypes.js.map +1 -0
  33. package/dist/esm/DocUtils.js +180 -0
  34. package/dist/esm/DocUtils.js.map +1 -0
  35. package/dist/esm/DocumentCache.js +131 -0
  36. package/dist/esm/DocumentCache.js.map +1 -0
  37. package/dist/esm/DocumentManager.js +240 -0
  38. package/dist/esm/DocumentManager.js.map +1 -0
  39. package/dist/esm/E2EAbracadabraProvider.js +273 -0
  40. package/dist/esm/E2EAbracadabraProvider.js.map +1 -0
  41. package/dist/esm/E2EOfflineStore.js +53 -0
  42. package/dist/esm/E2EOfflineStore.js.map +1 -0
  43. package/dist/esm/EncryptedChatClient.js +156 -0
  44. package/dist/esm/EncryptedChatClient.js.map +1 -0
  45. package/dist/esm/EncryptedY.js +115 -0
  46. package/dist/esm/EncryptedY.js.map +1 -0
  47. package/dist/esm/EventEmitter.js +40 -0
  48. package/dist/esm/EventEmitter.js.map +1 -0
  49. package/dist/esm/FileBlobStore.js +410 -0
  50. package/dist/esm/FileBlobStore.js.map +1 -0
  51. package/dist/esm/IdentityDoc.js +413 -0
  52. package/dist/esm/IdentityDoc.js.map +1 -0
  53. package/dist/esm/IncomingMessage.js +39 -0
  54. package/dist/esm/IncomingMessage.js.map +1 -0
  55. package/dist/esm/LifecycleGate.js +124 -0
  56. package/dist/esm/LifecycleGate.js.map +1 -0
  57. package/dist/esm/MessageReceiver.js +86 -0
  58. package/dist/esm/MessageReceiver.js.map +1 -0
  59. package/dist/esm/MessageSender.js +19 -0
  60. package/dist/esm/MessageSender.js.map +1 -0
  61. package/dist/esm/MetaManager.js +112 -0
  62. package/dist/esm/MetaManager.js.map +1 -0
  63. package/dist/esm/MnemonicKeyDerivation.js +137 -0
  64. package/dist/esm/MnemonicKeyDerivation.js.map +1 -0
  65. package/dist/esm/NodeConnect.js +63 -0
  66. package/dist/esm/NodeConnect.js.map +1 -0
  67. package/dist/esm/NodeIdentity.js +212 -0
  68. package/dist/esm/NodeIdentity.js.map +1 -0
  69. package/dist/esm/NotificationsClient.js +136 -0
  70. package/dist/esm/NotificationsClient.js.map +1 -0
  71. package/dist/esm/OfflineStore.js +291 -0
  72. package/dist/esm/OfflineStore.js.map +1 -0
  73. package/dist/esm/OutgoingMessage.js +18 -0
  74. package/dist/esm/OutgoingMessage.js.map +1 -0
  75. package/dist/esm/OutgoingMessages/AuthenticationMessage.js +24 -0
  76. package/dist/esm/OutgoingMessages/AuthenticationMessage.js.map +1 -0
  77. package/dist/esm/OutgoingMessages/AwarenessMessage.js +28 -0
  78. package/dist/esm/OutgoingMessages/AwarenessMessage.js.map +1 -0
  79. package/dist/esm/OutgoingMessages/CloseMessage.js +21 -0
  80. package/dist/esm/OutgoingMessages/CloseMessage.js.map +1 -0
  81. package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js +21 -0
  82. package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js.map +1 -0
  83. package/dist/esm/OutgoingMessages/StatelessMessage.js +22 -0
  84. package/dist/esm/OutgoingMessages/StatelessMessage.js.map +1 -0
  85. package/dist/esm/OutgoingMessages/SubdocMessage.js +34 -0
  86. package/dist/esm/OutgoingMessages/SubdocMessage.js.map +1 -0
  87. package/dist/esm/OutgoingMessages/SyncStepOneMessage.js +24 -0
  88. package/dist/esm/OutgoingMessages/SyncStepOneMessage.js.map +1 -0
  89. package/dist/esm/OutgoingMessages/UpdateMessage.js +23 -0
  90. package/dist/esm/OutgoingMessages/UpdateMessage.js.map +1 -0
  91. package/dist/esm/PerfCounters.js +336 -0
  92. package/dist/esm/PerfCounters.js.map +1 -0
  93. package/dist/esm/QueryClient.js +117 -0
  94. package/dist/esm/QueryClient.js.map +1 -0
  95. package/dist/esm/RpcClient.js +456 -0
  96. package/dist/esm/RpcClient.js.map +1 -0
  97. package/dist/esm/SchemaTypes.js +38 -0
  98. package/dist/esm/SchemaTypes.js.map +1 -0
  99. package/dist/esm/SearchIndex.js +167 -0
  100. package/dist/esm/SearchIndex.js.map +1 -0
  101. package/dist/esm/ServerRegistry.js +139 -0
  102. package/dist/esm/ServerRegistry.js.map +1 -0
  103. package/dist/esm/ServerReset.js +170 -0
  104. package/dist/esm/ServerReset.js.map +1 -0
  105. package/dist/esm/TokenManager.js +236 -0
  106. package/dist/esm/TokenManager.js.map +1 -0
  107. package/dist/esm/TreeManager.js +655 -0
  108. package/dist/esm/TreeManager.js.map +1 -0
  109. package/dist/esm/TreeTimestamps.js +61 -0
  110. package/dist/esm/TreeTimestamps.js.map +1 -0
  111. package/dist/esm/auth.js +43 -0
  112. package/dist/esm/auth.js.map +1 -0
  113. package/dist/esm/awarenessStatesToArray.js +13 -0
  114. package/dist/esm/awarenessStatesToArray.js.map +1 -0
  115. package/dist/esm/docIds.js +53 -0
  116. package/dist/esm/docIds.js.map +1 -0
  117. package/dist/esm/encryptedContent.js +21 -0
  118. package/dist/esm/encryptedContent.js.map +1 -0
  119. package/dist/esm/index.js +61 -0
  120. package/dist/esm/messageRecord.js +64 -0
  121. package/dist/esm/messageRecord.js.map +1 -0
  122. package/dist/esm/sync/BroadcastChannelSync.js +160 -0
  123. package/dist/esm/sync/BroadcastChannelSync.js.map +1 -0
  124. package/dist/esm/types.js +54 -0
  125. package/dist/esm/types.js.map +1 -0
  126. package/dist/esm/webrtc/AbracadabraWebRTC.js +483 -0
  127. package/dist/esm/webrtc/AbracadabraWebRTC.js.map +1 -0
  128. package/dist/esm/webrtc/DataChannelRouter.js +124 -0
  129. package/dist/esm/webrtc/DataChannelRouter.js.map +1 -0
  130. package/dist/esm/webrtc/DevicePairingChannel.js +335 -0
  131. package/dist/esm/webrtc/DevicePairingChannel.js.map +1 -0
  132. package/dist/esm/webrtc/E2EEChannel.js +137 -0
  133. package/dist/esm/webrtc/E2EEChannel.js.map +1 -0
  134. package/dist/esm/webrtc/FileTransferChannel.js +250 -0
  135. package/dist/esm/webrtc/FileTransferChannel.js.map +1 -0
  136. package/dist/esm/webrtc/ManualSignaling.js +161 -0
  137. package/dist/esm/webrtc/ManualSignaling.js.map +1 -0
  138. package/dist/esm/webrtc/PeerConnection.js +96 -0
  139. package/dist/esm/webrtc/PeerConnection.js.map +1 -0
  140. package/dist/esm/webrtc/SignalingSocket.js +274 -0
  141. package/dist/esm/webrtc/SignalingSocket.js.map +1 -0
  142. package/dist/esm/webrtc/YjsDataChannel.js +135 -0
  143. package/dist/esm/webrtc/YjsDataChannel.js.map +1 -0
  144. package/dist/esm/webrtc/types.js +29 -0
  145. package/dist/esm/webrtc/types.js.map +1 -0
  146. package/dist/esm/x25519Convert.js +69 -0
  147. package/dist/esm/x25519Convert.js.map +1 -0
  148. package/dist/index.d.ts +26 -11
  149. package/package.json +6 -4
  150. package/dist/abracadabra-provider.esm.js +0 -14860
  151. package/dist/abracadabra-provider.esm.js.map +0 -1
@@ -0,0 +1,558 @@
1
+ import { awarenessStatesToArray } from "./awarenessStatesToArray.js";
2
+ import EventEmitter from "./EventEmitter.js";
3
+ import { WebSocketStatus } from "./types.js";
4
+ import { getLifecycleGate } from "./LifecycleGate.js";
5
+ import { IncomingMessage } from "./IncomingMessage.js";
6
+ import { AbracadabraWS } from "./AbracadabraWS.js";
7
+ import { MessageReceiver } from "./MessageReceiver.js";
8
+ import { MessageSender } from "./MessageSender.js";
9
+ import { AuthenticationMessage } from "./OutgoingMessages/AuthenticationMessage.js";
10
+ import { AwarenessMessage } from "./OutgoingMessages/AwarenessMessage.js";
11
+ import { StatelessMessage } from "./OutgoingMessages/StatelessMessage.js";
12
+ import { RpcClient } from "./RpcClient.js";
13
+ import { QueryClient } from "./QueryClient.js";
14
+ import { QueryAwarenessMessage } from "./OutgoingMessages/QueryAwarenessMessage.js";
15
+ import { SyncStepOneMessage } from "./OutgoingMessages/SyncStepOneMessage.js";
16
+ import { UpdateMessage } from "./OutgoingMessages/UpdateMessage.js";
17
+ import { Awareness, removeAwarenessStates } from "y-protocols/awareness";
18
+ import * as Y from "yjs";
19
+
20
+ //#region packages/provider/src/AbracadabraBaseProvider.ts
21
+ var AwarenessError = class extends Error {
22
+ constructor(..._args) {
23
+ super(..._args);
24
+ this.code = 1001;
25
+ }
26
+ };
27
+ var AbracadabraBaseProvider = class AbracadabraBaseProvider extends EventEmitter {
28
+ /** Current WebSocket connection status. */
29
+ get connectionStatus() {
30
+ return this.configuration.websocketProvider.status;
31
+ }
32
+ static {
33
+ this.MAX_RESUBSCRIBE_ATTEMPTS = 6;
34
+ }
35
+ get rpc() {
36
+ if (!this._rpc) this._rpc = new RpcClient(this);
37
+ return this._rpc;
38
+ }
39
+ getQueryClient() {
40
+ if (!this._queryClient) this._queryClient = new QueryClient(this);
41
+ return this._queryClient;
42
+ }
43
+ /**
44
+ * Open a live query subscription. Mirrors the v1 REST shape
45
+ * (`POST /docs/query`) but pushes deltas as the server-side
46
+ * projection drifts under the predicate.
47
+ */
48
+ subscribeQuery(spec, handlers = {}) {
49
+ return this.getQueryClient().subscribeQuery(spec, handlers);
50
+ }
51
+ constructor(configuration) {
52
+ super();
53
+ this.configuration = {
54
+ name: "",
55
+ document: void 0,
56
+ awareness: void 0,
57
+ token: null,
58
+ forceSyncInterval: false,
59
+ onAuthenticated: () => null,
60
+ onAuthenticationFailed: () => null,
61
+ onWriteRejected: () => null,
62
+ onRateLimited: () => null,
63
+ onOpen: () => null,
64
+ onReconnected: () => null,
65
+ onConnect: () => null,
66
+ onMessage: () => null,
67
+ onOutgoingMessage: () => null,
68
+ onSynced: () => null,
69
+ onStatus: () => null,
70
+ onDisconnect: () => null,
71
+ onClose: () => null,
72
+ onDestroy: () => null,
73
+ onAwarenessUpdate: () => null,
74
+ onAwarenessChange: () => null,
75
+ onStateless: () => null,
76
+ onServerError: () => null,
77
+ onUnsyncedChanges: () => null
78
+ };
79
+ this.isSynced = false;
80
+ this.unsyncedChanges = 0;
81
+ this.isAuthenticated = false;
82
+ this._hasEverAuthenticated = false;
83
+ this._hasOpenedBefore = false;
84
+ this.authorizedScope = void 0;
85
+ this.manageSocket = false;
86
+ this._isAttached = false;
87
+ this._resubscribeAttempts = 0;
88
+ this._resubscribeTimer = null;
89
+ this.intervals = { forceSync: null };
90
+ this.missedForceSync = false;
91
+ this.unsubscribeForceSyncLifecycle = null;
92
+ this.boundDocumentUpdateHandler = this.documentUpdateHandler.bind(this);
93
+ this.boundAwarenessUpdateHandler = this.awarenessUpdateHandler.bind(this);
94
+ this.boundPageHide = this.pageHide.bind(this);
95
+ this.boundOnOpen = this.onOpen.bind(this);
96
+ this.boundOnClose = this.onClose.bind(this);
97
+ this.forwardConnect = () => this.emit("connect");
98
+ this.forwardStatus = (e) => this.emit("status", e);
99
+ this.forwardClose = (e) => this.emit("close", e);
100
+ this.forwardDisconnect = (e) => this.emit("disconnect", e);
101
+ this.forwardDestroy = () => this.emit("destroy");
102
+ this.forwardRateLimited = () => this.emit("rateLimited");
103
+ this._awarenessDeferred = false;
104
+ this._awarenessExplicitlyNull = false;
105
+ this.lastWriteRejection = null;
106
+ this.writeRejectionCount = 0;
107
+ this.setConfiguration(configuration);
108
+ this.configuration.document = configuration.document ? configuration.document : new Y.Doc();
109
+ if (configuration.awareness !== void 0) {
110
+ this.configuration.awareness = configuration.awareness;
111
+ this._awarenessExplicitlyNull = configuration.awareness === null;
112
+ } else if (configuration.lazyAwareness) {
113
+ this.configuration.awareness = null;
114
+ this._awarenessDeferred = true;
115
+ } else this.configuration.awareness = new Awareness(this.document);
116
+ if (!this._awarenessDeferred) this._initAwareness();
117
+ this.on("open", this.configuration.onOpen);
118
+ this.on("reconnected", this.configuration.onReconnected);
119
+ this.on("message", this.configuration.onMessage);
120
+ this.on("outgoingMessage", this.configuration.onOutgoingMessage);
121
+ this.on("synced", this.configuration.onSynced);
122
+ this.on("destroy", this.configuration.onDestroy);
123
+ if (configuration.onAwarenessUpdate) this.on("awarenessUpdate", configuration.onAwarenessUpdate);
124
+ if (configuration.onAwarenessChange) this.on("awarenessChange", configuration.onAwarenessChange);
125
+ this.on("stateless", this.configuration.onStateless);
126
+ this.on("serverError", this.configuration.onServerError);
127
+ this.on("unsyncedChanges", this.configuration.onUnsyncedChanges);
128
+ this.on("authenticated", this.configuration.onAuthenticated);
129
+ this.on("authenticationFailed", this.configuration.onAuthenticationFailed);
130
+ this.on("writeRejected", this.configuration.onWriteRejected);
131
+ this.on("rateLimited", this.configuration.onRateLimited);
132
+ this.document.on("update", this.boundDocumentUpdateHandler);
133
+ this.registerEventListeners();
134
+ if (this.configuration.forceSyncInterval && typeof this.configuration.forceSyncInterval === "number") {
135
+ this.intervals.forceSync = setInterval(() => {
136
+ if (getLifecycleGate().backgrounded) {
137
+ this.missedForceSync = true;
138
+ return;
139
+ }
140
+ this.forceSync();
141
+ }, this.configuration.forceSyncInterval);
142
+ this.unsubscribeForceSyncLifecycle = getLifecycleGate().onChange((backgrounded) => {
143
+ if (backgrounded || !this.missedForceSync) return;
144
+ this.missedForceSync = false;
145
+ this.forceSync();
146
+ });
147
+ }
148
+ if (this.manageSocket) this.attach();
149
+ }
150
+ setConfiguration(configuration = {}) {
151
+ if (!configuration.websocketProvider) {
152
+ this.manageSocket = true;
153
+ this.configuration.websocketProvider = new AbracadabraWS(configuration);
154
+ }
155
+ this.configuration = {
156
+ ...this.configuration,
157
+ ...configuration
158
+ };
159
+ }
160
+ get document() {
161
+ return this.configuration.document;
162
+ }
163
+ get isAttached() {
164
+ return this._isAttached;
165
+ }
166
+ /**
167
+ * The presence instance for this document, built on demand.
168
+ *
169
+ * Reading this materializes a deferred instance (see `lazyAwareness`), which
170
+ * is why every consumer — TipTap's CollaborationCaret, presence UI, app code
171
+ * — keeps working unchanged: touching `.awareness` is itself the signal that
172
+ * this document needs presence.
173
+ *
174
+ * Provider INTERNALS must use `peekAwareness()` instead, or the lazy path
175
+ * materializes everything it was meant to avoid.
176
+ */
177
+ get awareness() {
178
+ if (this._awarenessExplicitlyNull) return null;
179
+ if (this._awarenessDeferred) this._materializeAwareness();
180
+ return this.configuration.awareness;
181
+ }
182
+ /**
183
+ * The Awareness instance if one exists, without ever creating one.
184
+ *
185
+ * @internal Used by provider internals and `MessageReceiver`. A deferred
186
+ * document has no local presence, so there is nothing for an inbound
187
+ * awareness frame to be applied to and nothing to answer a peer's query with
188
+ * — and materializing on a peer's frame would hand every idle background
189
+ * document a heartbeat as soon as anyone else joined the space.
190
+ */
191
+ peekAwareness() {
192
+ return this._awarenessDeferred ? null : this.configuration.awareness;
193
+ }
194
+ /**
195
+ * Build the deferred Awareness instance and bring it fully up to date:
196
+ * seeded, wired, published, and caught up with the peers already present.
197
+ */
198
+ _materializeAwareness() {
199
+ if (!this._awarenessDeferred) return;
200
+ this._awarenessDeferred = false;
201
+ this.configuration.awareness = new Awareness(this.document);
202
+ this._initAwareness();
203
+ if (this._isAttached) {
204
+ this.send(AwarenessMessage, {
205
+ awareness: this.configuration.awareness,
206
+ clients: [this.document.clientID],
207
+ documentName: this.configuration.name
208
+ });
209
+ this.send(QueryAwarenessMessage, { documentName: this.configuration.name });
210
+ }
211
+ }
212
+ /**
213
+ * Seed and wire an Awareness instance. Shared by the eager constructor path
214
+ * and the lazy materialization path so the two cannot drift.
215
+ */
216
+ _initAwareness() {
217
+ const awareness = this.configuration.awareness;
218
+ if (!awareness) return;
219
+ if (awareness.getLocalState() === null) awareness.setLocalState({});
220
+ awareness.on("update", () => {
221
+ if (!this.callbacks.awarenessUpdate?.length) return;
222
+ this.emit("awarenessUpdate", { states: awarenessStatesToArray(awareness.getStates()) });
223
+ });
224
+ awareness.on("change", () => {
225
+ if (!this.callbacks.awarenessChange?.length) return;
226
+ this.emit("awarenessChange", { states: awarenessStatesToArray(awareness.getStates()) });
227
+ });
228
+ awareness.on("update", this.boundAwarenessUpdateHandler);
229
+ }
230
+ get hasUnsyncedChanges() {
231
+ return this.unsyncedChanges > 0;
232
+ }
233
+ resetUnsyncedChanges() {
234
+ this.unsyncedChanges = 0;
235
+ this.emit("unsyncedChanges", { number: this.unsyncedChanges });
236
+ }
237
+ incrementUnsyncedChanges() {
238
+ this.unsyncedChanges += 1;
239
+ this.emit("unsyncedChanges", { number: this.unsyncedChanges });
240
+ }
241
+ decrementUnsyncedChanges() {
242
+ if (this.unsyncedChanges > 0) this.unsyncedChanges -= 1;
243
+ if (this.unsyncedChanges === 0) this.synced = true;
244
+ this.emit("unsyncedChanges", { number: this.unsyncedChanges });
245
+ }
246
+ forceSync() {
247
+ this.resetUnsyncedChanges();
248
+ this.send(SyncStepOneMessage, {
249
+ document: this.document,
250
+ documentName: this.configuration.name
251
+ });
252
+ }
253
+ pageHide() {
254
+ const awareness = this.peekAwareness();
255
+ if (awareness) removeAwarenessStates(awareness, [this.document.clientID], "page hide");
256
+ }
257
+ registerEventListeners() {
258
+ if (typeof window === "undefined" || !("addEventListener" in window)) return;
259
+ window.addEventListener("pagehide", this.boundPageHide);
260
+ }
261
+ sendStateless(payload) {
262
+ this.send(StatelessMessage, {
263
+ documentName: this.configuration.name,
264
+ payload
265
+ });
266
+ }
267
+ async sendToken() {
268
+ let token;
269
+ try {
270
+ token = await this.getToken();
271
+ } catch (error) {
272
+ this.permissionDeniedHandler(`Failed to get token during sendToken(): ${error}`);
273
+ return;
274
+ }
275
+ this.send(AuthenticationMessage, {
276
+ token: token ?? "",
277
+ documentName: this.configuration.name
278
+ });
279
+ }
280
+ documentUpdateHandler(update, origin) {
281
+ if (origin === this) return;
282
+ if (!this.isAuthenticated) return;
283
+ this.incrementUnsyncedChanges();
284
+ this.send(UpdateMessage, {
285
+ update,
286
+ documentName: this.configuration.name
287
+ });
288
+ }
289
+ awarenessUpdateHandler({ added, updated, removed }, origin) {
290
+ if (!this.isAuthenticated) return;
291
+ if (origin === this) return;
292
+ const changedClients = added.concat(updated).concat(removed);
293
+ this.send(AwarenessMessage, {
294
+ awareness: this.peekAwareness(),
295
+ clients: changedClients,
296
+ documentName: this.configuration.name
297
+ });
298
+ }
299
+ /**
300
+ * Indicates whether a first handshake with the server has been established
301
+ *
302
+ * Note: this does not mean all updates from the client have been persisted to the backend. For this,
303
+ * use `hasUnsyncedChanges`.
304
+ */
305
+ get synced() {
306
+ return this.isSynced;
307
+ }
308
+ set synced(state) {
309
+ if (this.isSynced === state) return;
310
+ this.isSynced = state;
311
+ if (state) queueMicrotask(() => {
312
+ if (this.isSynced) this.emit("synced", { state });
313
+ });
314
+ }
315
+ receiveStateless(payload) {
316
+ if (!payload.includes("\"error\"")) {
317
+ this.emit("stateless", { payload });
318
+ return;
319
+ }
320
+ try {
321
+ const parsed = JSON.parse(payload);
322
+ if (parsed?.type === "error" && parsed.source && parsed.code) {
323
+ const { source, code, message, meta } = parsed;
324
+ console.warn(`[Abracadabra] Server error: ${source} (${code}) — ${message}`, meta ?? "");
325
+ this.emit("serverError", {
326
+ source,
327
+ code,
328
+ message: message ?? "",
329
+ meta
330
+ });
331
+ return;
332
+ }
333
+ } catch {}
334
+ this.emit("stateless", { payload });
335
+ }
336
+ async connect() {
337
+ if (this.manageSocket) return this.configuration.websocketProvider.connect();
338
+ console.warn("AbracadabraBaseProvider::connect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.");
339
+ }
340
+ disconnect() {
341
+ if (this.manageSocket) return this.configuration.websocketProvider.disconnect();
342
+ console.warn("AbracadabraBaseProvider::disconnect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.");
343
+ }
344
+ /**
345
+ * Force the underlying socket to drop and reconnect on the SAME Y.Doc.
346
+ *
347
+ * Unlike destroying and re-creating the provider, the document is never
348
+ * replaced — so every `observe`/`observeDeep` listener attached to it (and
349
+ * its subdocs) keeps firing once the socket comes back. This also revives a
350
+ * socket that a permanent permission-denial gave up on (see
351
+ * {@link permissionDeniedHandler}). Pair it with a freshly-minted token (the
352
+ * `token` callback is re-invoked on every reconnect) when healing a drop that
353
+ * was caused by an expired JWT.
354
+ *
355
+ * Every provider multiplexed onto this socket is marked unsynced so a
356
+ * subsequent `waitForSync` actually waits for the post-reconnect handshake
357
+ * instead of short-circuiting on the stale `isSynced` flag.
358
+ *
359
+ * No-op (with a warning) for a provider on a shared, externally-managed
360
+ * socket — reconnect the owning `websocketProvider` directly in that case.
361
+ */
362
+ reconnect() {
363
+ if (!this.manageSocket) {
364
+ console.warn("AbracadabraBaseProvider::reconnect() — this provider shares an externally-managed socket; call reconnect() on the websocketProvider instead.");
365
+ return;
366
+ }
367
+ for (const provider of this.configuration.websocketProvider.configuration.providerMap.values()) {
368
+ provider.synced = false;
369
+ provider.isAuthenticated = false;
370
+ }
371
+ return this.configuration.websocketProvider.reconnect();
372
+ }
373
+ async onOpen(event) {
374
+ const isReopen = this._hasOpenedBefore;
375
+ this._hasOpenedBefore = true;
376
+ this.isAuthenticated = false;
377
+ this.emit("open", { event });
378
+ if (isReopen) this.emit("reconnected", { event });
379
+ await this.sendToken();
380
+ this.startSync();
381
+ }
382
+ async getToken() {
383
+ if (typeof this.configuration.token === "function") return await this.configuration.token();
384
+ return this.configuration.token;
385
+ }
386
+ startSync() {
387
+ this.resetUnsyncedChanges();
388
+ this.send(SyncStepOneMessage, {
389
+ document: this.document,
390
+ documentName: this.configuration.name
391
+ });
392
+ const openAwareness = this.peekAwareness();
393
+ if (openAwareness && openAwareness.getLocalState() !== null) this.send(AwarenessMessage, {
394
+ awareness: openAwareness,
395
+ clients: [this.document.clientID],
396
+ documentName: this.configuration.name
397
+ });
398
+ if (openAwareness) this.send(QueryAwarenessMessage, { documentName: this.configuration.name });
399
+ }
400
+ send(message, args) {
401
+ if (!this._isAttached) return;
402
+ const messageSender = new MessageSender(message, args);
403
+ this.emit("outgoingMessage", { message: messageSender.message });
404
+ messageSender.send(this.configuration.websocketProvider);
405
+ }
406
+ onMessage(event) {
407
+ const message = new IncomingMessage(event.data);
408
+ const documentName = message.readVarString();
409
+ message.writeVarString(documentName);
410
+ this.emit("message", {
411
+ event,
412
+ message: new IncomingMessage(event.data)
413
+ });
414
+ new MessageReceiver(message).apply(this, true);
415
+ }
416
+ onClose() {
417
+ this.isAuthenticated = false;
418
+ this.synced = false;
419
+ this._hasEverAuthenticated = false;
420
+ this.clearResubscribe();
421
+ const closeAwareness = this.peekAwareness();
422
+ if (closeAwareness) removeAwarenessStates(closeAwareness, Array.from(closeAwareness.getStates().keys()).filter((client) => client !== this.document.clientID), this);
423
+ }
424
+ destroy() {
425
+ this.emit("destroy");
426
+ if (this._rpc) this._rpc.destroy();
427
+ if (this.unsubscribeForceSyncLifecycle) {
428
+ this.unsubscribeForceSyncLifecycle();
429
+ this.unsubscribeForceSyncLifecycle = null;
430
+ }
431
+ if (this.intervals.forceSync) clearInterval(this.intervals.forceSync);
432
+ const ownAwareness = this.peekAwareness();
433
+ if (ownAwareness) {
434
+ removeAwarenessStates(ownAwareness, [this.document.clientID], "provider destroy");
435
+ ownAwareness.off("update", this.boundAwarenessUpdateHandler);
436
+ ownAwareness.destroy();
437
+ }
438
+ this.document.off("update", this.boundDocumentUpdateHandler);
439
+ this.removeAllListeners();
440
+ this.detach();
441
+ if (this.manageSocket) this.configuration.websocketProvider.destroy();
442
+ if (typeof window === "undefined" || !("removeEventListener" in window)) return;
443
+ window.removeEventListener("pagehide", this.boundPageHide);
444
+ }
445
+ detach() {
446
+ this.configuration.websocketProvider.off("connect", this.configuration.onConnect);
447
+ this.configuration.websocketProvider.off("connect", this.forwardConnect);
448
+ this.configuration.websocketProvider.off("status", this.forwardStatus);
449
+ this.configuration.websocketProvider.off("status", this.configuration.onStatus);
450
+ this.configuration.websocketProvider.off("open", this.boundOnOpen);
451
+ this.configuration.websocketProvider.off("close", this.boundOnClose);
452
+ this.configuration.websocketProvider.off("close", this.configuration.onClose);
453
+ this.configuration.websocketProvider.off("close", this.forwardClose);
454
+ this.configuration.websocketProvider.off("disconnect", this.configuration.onDisconnect);
455
+ this.configuration.websocketProvider.off("disconnect", this.forwardDisconnect);
456
+ this.configuration.websocketProvider.off("destroy", this.configuration.onDestroy);
457
+ this.configuration.websocketProvider.off("destroy", this.forwardDestroy);
458
+ this.configuration.websocketProvider.off("rateLimited", this.forwardRateLimited);
459
+ this.configuration.websocketProvider.detach(this);
460
+ this._isAttached = false;
461
+ this.clearResubscribe();
462
+ }
463
+ attach() {
464
+ if (this._isAttached) return;
465
+ this.configuration.websocketProvider.on("connect", this.configuration.onConnect);
466
+ this.configuration.websocketProvider.on("connect", this.forwardConnect);
467
+ this.configuration.websocketProvider.on("status", this.configuration.onStatus);
468
+ this.configuration.websocketProvider.on("status", this.forwardStatus);
469
+ this.configuration.websocketProvider.on("open", this.boundOnOpen);
470
+ this.configuration.websocketProvider.on("close", this.boundOnClose);
471
+ this.configuration.websocketProvider.on("close", this.configuration.onClose);
472
+ this.configuration.websocketProvider.on("close", this.forwardClose);
473
+ this.configuration.websocketProvider.on("disconnect", this.configuration.onDisconnect);
474
+ this.configuration.websocketProvider.on("disconnect", this.forwardDisconnect);
475
+ this.configuration.websocketProvider.on("destroy", this.configuration.onDestroy);
476
+ this.configuration.websocketProvider.on("destroy", this.forwardDestroy);
477
+ this.configuration.websocketProvider.on("rateLimited", this.forwardRateLimited);
478
+ this._isAttached = true;
479
+ this.configuration.websocketProvider.attach(this);
480
+ }
481
+ permissionDeniedHandler(reason) {
482
+ if (this._hasEverAuthenticated && this.isSynced) this.reportWriteRejected(reason, "permission");
483
+ this.emit("authenticationFailed", { reason });
484
+ this.isAuthenticated = false;
485
+ if (this.manageSocket && !this._hasEverAuthenticated) try {
486
+ this.configuration.websocketProvider.disconnect();
487
+ } catch {}
488
+ if (!this.manageSocket && !this.isSynced && this._isAttached && this._resubscribeAttempts < AbracadabraBaseProvider.MAX_RESUBSCRIBE_ATTEMPTS && AbracadabraBaseProvider.isTransientSubscribeDenial(reason)) this.scheduleResubscribe();
489
+ }
490
+ /**
491
+ * Record and announce a server-refused local change.
492
+ *
493
+ * Called from both nack paths: the permission-denied auth frame and
494
+ * `SyncStatus(applied=0)`. Deliberately does NOT touch the unsynced counter
495
+ * — the update stays queued so a retry can land it once the cause is fixed.
496
+ */
497
+ reportWriteRejected(reason, kind) {
498
+ const data = {
499
+ documentName: this.configuration.name,
500
+ reason,
501
+ kind
502
+ };
503
+ this.lastWriteRejection = data;
504
+ this.writeRejectionCount += 1;
505
+ this.emit("writeRejected", data);
506
+ }
507
+ /**
508
+ * Whether a permission-denied reason reflects a *transient* server condition
509
+ * a retry can clear (a freshly-created doc not yet visible on this replica, or
510
+ * a dropped subscribe-ordering) rather than a permanent authorization failure.
511
+ */
512
+ static isTransientSubscribeDenial(reason) {
513
+ const r = reason.toLowerCase();
514
+ return r.includes("not found") || r.includes("not subscribed");
515
+ }
516
+ /**
517
+ * Schedule one backed-off replay of the initial subscribe handshake. A single
518
+ * timer is in flight at a time; each denial that slips past the guard above
519
+ * arms the next attempt until {@link MAX_RESUBSCRIBE_ATTEMPTS} is reached.
520
+ */
521
+ scheduleResubscribe() {
522
+ if (this._resubscribeTimer) return;
523
+ const attempt = this._resubscribeAttempts++;
524
+ const delay = Math.min(4e3, 250 * 2 ** attempt);
525
+ this._resubscribeTimer = setTimeout(() => {
526
+ this._resubscribeTimer = null;
527
+ if (!this._isAttached || this.isSynced || this.connectionStatus !== WebSocketStatus.Connected) return;
528
+ this.sendToken().then(() => {
529
+ if (this._isAttached && !this.isAuthenticated) this.startSync();
530
+ }).catch(() => {});
531
+ }, delay);
532
+ }
533
+ /** Cancel any pending resubscribe and reset the attempt budget. */
534
+ clearResubscribe() {
535
+ if (this._resubscribeTimer) {
536
+ clearTimeout(this._resubscribeTimer);
537
+ this._resubscribeTimer = null;
538
+ }
539
+ this._resubscribeAttempts = 0;
540
+ }
541
+ authenticatedHandler(scope) {
542
+ this.isAuthenticated = true;
543
+ this._hasEverAuthenticated = true;
544
+ this.authorizedScope = scope;
545
+ this.clearResubscribe();
546
+ this.emit("authenticated", { scope });
547
+ }
548
+ setAwarenessField(key, value) {
549
+ if (!this.awareness) throw new AwarenessError(`Cannot set awareness field "${key}" to ${JSON.stringify(value)}. You have disabled Awareness for this provider by explicitly passing awareness: null in the provider configuration.`);
550
+ this.awareness.setLocalStateField(key, value);
551
+ }
552
+ };
553
+ /** @deprecated Use AbracadabraBaseProvider */
554
+ const HocuspocusProvider = AbracadabraBaseProvider;
555
+
556
+ //#endregion
557
+ export { AbracadabraBaseProvider, AwarenessError, HocuspocusProvider };
558
+ //# sourceMappingURL=AbracadabraBaseProvider.js.map