@abraca/dabra 2.93.0 → 2.96.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.
@@ -1128,6 +1128,128 @@ const Kind = {
1128
1128
  */
1129
1129
  const SERVER_ROOT_ID = "00000000-0000-0000-0000-000000000000";
1130
1130
 
1131
+ //#endregion
1132
+ //#region packages/provider/src/LifecycleGate.ts
1133
+ /** How long the app must stay hidden before we act on it. */
1134
+ const HIDE_GRACE_MS = 1e4;
1135
+ /** The browser's own visibility, or a permanently-visible stub off-DOM. */
1136
+ function defaultSource() {
1137
+ const doc = globalThis.document;
1138
+ if (!doc || typeof doc.addEventListener !== "function") return {
1139
+ get: () => "visible",
1140
+ subscribe: () => () => {}
1141
+ };
1142
+ return {
1143
+ get: () => doc.visibilityState === "hidden" ? "hidden" : "visible",
1144
+ subscribe: (onChange) => {
1145
+ doc.addEventListener("visibilitychange", onChange);
1146
+ return () => doc.removeEventListener("visibilitychange", onChange);
1147
+ }
1148
+ };
1149
+ }
1150
+ var LifecycleGate = class {
1151
+ constructor(source = defaultSource(), graceMs = HIDE_GRACE_MS) {
1152
+ this.graceMs = graceMs;
1153
+ this.unsubscribe = null;
1154
+ this.hideTimer = null;
1155
+ this._backgrounded = false;
1156
+ this.listeners = /* @__PURE__ */ new Set();
1157
+ this.source = source;
1158
+ this.unsubscribe = this.source.subscribe(() => this.onVisibilityChange());
1159
+ }
1160
+ /**
1161
+ * True when the app has been hidden for longer than the grace period.
1162
+ *
1163
+ * Deliberately NOT the same as `document.hidden`: a tab that was hidden two
1164
+ * seconds ago is still, for our purposes, in use.
1165
+ */
1166
+ get backgrounded() {
1167
+ return this._backgrounded;
1168
+ }
1169
+ /** Subscribe to background/foreground transitions. Returns an unsubscribe fn. */
1170
+ onChange(listener) {
1171
+ this.listeners.add(listener);
1172
+ return () => this.listeners.delete(listener);
1173
+ }
1174
+ /** Swap the visibility source. Used by tests to drive state deterministically. */
1175
+ setSource(source) {
1176
+ this.unsubscribe?.();
1177
+ this.source = source;
1178
+ this.unsubscribe = this.source.subscribe(() => this.onVisibilityChange());
1179
+ this.onVisibilityChange();
1180
+ }
1181
+ onVisibilityChange() {
1182
+ if (this.source.get() === "hidden") {
1183
+ if (this._backgrounded || this.hideTimer) return;
1184
+ this.hideTimer = setTimeout(() => {
1185
+ this.hideTimer = null;
1186
+ this.setBackgrounded(true);
1187
+ }, this.graceMs);
1188
+ return;
1189
+ }
1190
+ if (this.hideTimer) {
1191
+ clearTimeout(this.hideTimer);
1192
+ this.hideTimer = null;
1193
+ }
1194
+ this.setBackgrounded(false);
1195
+ }
1196
+ setBackgrounded(next) {
1197
+ if (this._backgrounded === next) return;
1198
+ this._backgrounded = next;
1199
+ for (const listener of [...this.listeners]) try {
1200
+ listener(next);
1201
+ } catch {}
1202
+ }
1203
+ destroy() {
1204
+ this.unsubscribe?.();
1205
+ this.unsubscribe = null;
1206
+ if (this.hideTimer) {
1207
+ clearTimeout(this.hideTimer);
1208
+ this.hideTimer = null;
1209
+ }
1210
+ this.listeners.clear();
1211
+ }
1212
+ };
1213
+ /**
1214
+ * The process-wide gate.
1215
+ *
1216
+ * Visibility is a property of the tab, not of any one provider or socket, so a
1217
+ * single shared instance is both correct and avoids paying for one
1218
+ * `visibilitychange` listener per document.
1219
+ */
1220
+ let shared = null;
1221
+ function getLifecycleGate() {
1222
+ if (!shared) shared = new LifecycleGate();
1223
+ return shared;
1224
+ }
1225
+ /**
1226
+ * Replace the shared gate. Tests use this to install a controllable source;
1227
+ * passing `null` restores the default browser-backed gate on next access.
1228
+ */
1229
+ function setLifecycleGate(gate) {
1230
+ if (shared && shared !== gate) shared.destroy();
1231
+ shared = gate;
1232
+ }
1233
+ /** A visibility source a test (or an embedder) can drive by hand. */
1234
+ var ManualVisibilitySource = class {
1235
+ constructor() {
1236
+ this.state = "visible";
1237
+ this.listeners = /* @__PURE__ */ new Set();
1238
+ }
1239
+ get() {
1240
+ return this.state;
1241
+ }
1242
+ subscribe(onChange) {
1243
+ this.listeners.add(onChange);
1244
+ return () => this.listeners.delete(onChange);
1245
+ }
1246
+ set(state) {
1247
+ if (this.state === state) return;
1248
+ this.state = state;
1249
+ for (const listener of [...this.listeners]) listener();
1250
+ }
1251
+ };
1252
+
1131
1253
  //#endregion
1132
1254
  //#region packages/provider/src/IncomingMessage.ts
1133
1255
  var IncomingMessage = class {
@@ -1235,8 +1357,10 @@ var AbracadabraWS = class extends EventEmitter {
1235
1357
  this.connectionAttempt = null;
1236
1358
  this.onlineListener = null;
1237
1359
  this.offlineListener = null;
1360
+ this.unsubscribeLifecycle = null;
1238
1361
  this.receivedOnOpenPayload = void 0;
1239
1362
  this.closeTries = 0;
1363
+ this.lastRefreshToken = null;
1240
1364
  this.setConfiguration(configuration);
1241
1365
  this.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill ? configuration.WebSocketPolyfill : globalThis.WebSocket;
1242
1366
  this.on("open", this.configuration.onOpen);
@@ -1253,6 +1377,9 @@ var AbracadabraWS = class extends EventEmitter {
1253
1377
  this.on("close", this.onClose.bind(this));
1254
1378
  this.on("message", this.onMessage.bind(this));
1255
1379
  this.intervals.connectionChecker = setInterval(this.checkConnection.bind(this), this.configuration.messageReconnectTimeout / 10);
1380
+ this.unsubscribeLifecycle = getLifecycleGate().onChange((backgrounded) => {
1381
+ if (!backgrounded) this.checkConnection();
1382
+ });
1256
1383
  if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
1257
1384
  this.onlineListener = this.handleOnline.bind(this);
1258
1385
  this.offlineListener = this.handleOffline.bind(this);
@@ -1436,6 +1563,7 @@ var AbracadabraWS = class extends EventEmitter {
1436
1563
  this.connectionAttempt = null;
1437
1564
  }
1438
1565
  checkConnection() {
1566
+ if (getLifecycleGate().backgrounded) return;
1439
1567
  if (this.status !== WebSocketStatus.Connected) return;
1440
1568
  if (!this.lastMessageReceived) return;
1441
1569
  if (this.configuration.messageReconnectTimeout >= getUnixTime() - this.lastMessageReceived) return;
@@ -1500,6 +1628,42 @@ var AbracadabraWS = class extends EventEmitter {
1500
1628
  if (this.webSocket?.readyState === WsReadyStates.Open) this.webSocket.send(message);
1501
1629
  else this.messageQueue.push(message);
1502
1630
  }
1631
+ /**
1632
+ * Re-arm this CONNECTION with a freshly minted JWT, in place.
1633
+ *
1634
+ * The server tracks a connection's expiry as one shared value
1635
+ * (`SyncSession`'s `jwt_exp`, an `Arc<AtomicI64>` every session on the socket
1636
+ * points at) and rejects every non-stateless frame once it passes — dropping
1637
+ * the whole socket for an ordinary session. `auth:refresh {"token":…}` moves
1638
+ * that value, and it rides `MSG_STATELESS` precisely because stateless is the
1639
+ * one frame kind an expired session may still send.
1640
+ *
1641
+ * So ONE frame, through any authenticated document, re-arms everything
1642
+ * multiplexed here. Sending it per attached provider would be N identical
1643
+ * frames on a shared socket carrying sixty documents; `lastRefreshToken` is
1644
+ * what keeps it at one.
1645
+ *
1646
+ * Verified against a live server with a 45-second token TTL, on an ORDINARY
1647
+ * (non-elevated) account, refreshing before the lapse so the socket is never
1648
+ * dropped and never re-handshaken: without the frame the socket is closed
1649
+ * past the original expiry, with it `close` never fires at all.
1650
+ *
1651
+ * Returns whether a frame actually went out. `false` means there was nobody
1652
+ * to send it through — harmless, because the next handshake carries the new
1653
+ * token anyway (see the provider's token closure).
1654
+ */
1655
+ refreshAuth(token) {
1656
+ if (!token || token === this.lastRefreshToken) return false;
1657
+ if (this.status !== WebSocketStatus.Connected) return false;
1658
+ const payload = `auth:refresh ${JSON.stringify({ token })}`;
1659
+ for (const provider of this.configuration.providerMap.values()) {
1660
+ if (!provider.isAuthenticated) continue;
1661
+ provider.sendStateless(payload);
1662
+ this.lastRefreshToken = token;
1663
+ return true;
1664
+ }
1665
+ return false;
1666
+ }
1503
1667
  onClose({ event }) {
1504
1668
  this.closeTries = 0;
1505
1669
  this.cleanupWebSocket();
@@ -1525,6 +1689,8 @@ var AbracadabraWS = class extends EventEmitter {
1525
1689
  }
1526
1690
  this.onlineListener = null;
1527
1691
  this.offlineListener = null;
1692
+ this.unsubscribeLifecycle?.();
1693
+ this.unsubscribeLifecycle = null;
1528
1694
  clearInterval(this.intervals.connectionChecker);
1529
1695
  this.stopConnectionAttempt();
1530
1696
  this.disconnect();
@@ -1751,19 +1917,21 @@ var MessageReceiver = class {
1751
1917
  provider.reportWriteRejected("server did not apply the update (permission or validation)", "validation");
1752
1918
  }
1753
1919
  applyAwarenessMessage(provider) {
1754
- if (!provider.awareness) return;
1920
+ const awareness = provider.peekAwareness();
1921
+ if (!awareness) return;
1755
1922
  const { message } = this;
1756
- applyAwarenessUpdate(provider.awareness, message.readVarUint8Array(), provider);
1923
+ applyAwarenessUpdate(awareness, message.readVarUint8Array(), provider);
1757
1924
  }
1758
1925
  applyAuthMessage(provider) {
1759
1926
  const { message } = this;
1760
1927
  readAuthMessage(message.decoder, provider.sendToken.bind(provider), provider.permissionDeniedHandler.bind(provider), provider.authenticatedHandler.bind(provider));
1761
1928
  }
1762
1929
  applyQueryAwarenessMessage(provider) {
1763
- if (!provider.awareness) return;
1930
+ const awareness = provider.peekAwareness();
1931
+ if (!awareness) return;
1764
1932
  const { message } = this;
1765
1933
  message.writeVarUint(MessageType.Awareness);
1766
- message.writeVarUint8Array(encodeAwarenessUpdate(provider.awareness, Array.from(provider.awareness.getStates().keys())));
1934
+ message.writeVarUint8Array(encodeAwarenessUpdate(awareness, Array.from(awareness.getStates().keys())));
1767
1935
  }
1768
1936
  };
1769
1937
 
@@ -2531,12 +2699,20 @@ var AbracadabraBaseProvider = class AbracadabraBaseProvider extends EventEmitter
2531
2699
  this.forwardDisconnect = (e) => this.emit("disconnect", e);
2532
2700
  this.forwardDestroy = () => this.emit("destroy");
2533
2701
  this.forwardRateLimited = () => this.emit("rateLimited");
2702
+ this._awarenessDeferred = false;
2703
+ this._awarenessExplicitlyNull = false;
2534
2704
  this.lastWriteRejection = null;
2535
2705
  this.writeRejectionCount = 0;
2536
2706
  this.setConfiguration(configuration);
2537
2707
  this.configuration.document = configuration.document ? configuration.document : new yjs.Doc();
2538
- this.configuration.awareness = configuration.awareness !== void 0 ? configuration.awareness : new Awareness(this.document);
2539
- if (this.awareness && this.awareness.getLocalState() === null) this.awareness.setLocalState({});
2708
+ if (configuration.awareness !== void 0) {
2709
+ this.configuration.awareness = configuration.awareness;
2710
+ this._awarenessExplicitlyNull = configuration.awareness === null;
2711
+ } else if (configuration.lazyAwareness) {
2712
+ this.configuration.awareness = null;
2713
+ this._awarenessDeferred = true;
2714
+ } else this.configuration.awareness = new Awareness(this.document);
2715
+ if (!this._awarenessDeferred) this._initAwareness();
2540
2716
  this.on("open", this.configuration.onOpen);
2541
2717
  this.on("reconnected", this.configuration.onReconnected);
2542
2718
  this.on("message", this.configuration.onMessage);
@@ -2552,14 +2728,7 @@ var AbracadabraBaseProvider = class AbracadabraBaseProvider extends EventEmitter
2552
2728
  this.on("authenticationFailed", this.configuration.onAuthenticationFailed);
2553
2729
  this.on("writeRejected", this.configuration.onWriteRejected);
2554
2730
  this.on("rateLimited", this.configuration.onRateLimited);
2555
- this.awareness?.on("update", () => {
2556
- this.emit("awarenessUpdate", { states: awarenessStatesToArray(this.awareness.getStates()) });
2557
- });
2558
- this.awareness?.on("change", () => {
2559
- this.emit("awarenessChange", { states: awarenessStatesToArray(this.awareness.getStates()) });
2560
- });
2561
2731
  this.document.on("update", this.boundDocumentUpdateHandler);
2562
- this.awareness?.on("update", this.boundAwarenessUpdateHandler);
2563
2732
  this.registerEventListeners();
2564
2733
  if (this.configuration.forceSyncInterval && typeof this.configuration.forceSyncInterval === "number") this.intervals.forceSync = setInterval(this.forceSync.bind(this), this.configuration.forceSyncInterval);
2565
2734
  if (this.manageSocket) this.attach();
@@ -2580,9 +2749,68 @@ var AbracadabraBaseProvider = class AbracadabraBaseProvider extends EventEmitter
2580
2749
  get isAttached() {
2581
2750
  return this._isAttached;
2582
2751
  }
2752
+ /**
2753
+ * The presence instance for this document, built on demand.
2754
+ *
2755
+ * Reading this materializes a deferred instance (see `lazyAwareness`), which
2756
+ * is why every consumer — TipTap's CollaborationCaret, presence UI, app code
2757
+ * — keeps working unchanged: touching `.awareness` is itself the signal that
2758
+ * this document needs presence.
2759
+ *
2760
+ * Provider INTERNALS must use `peekAwareness()` instead, or the lazy path
2761
+ * materializes everything it was meant to avoid.
2762
+ */
2583
2763
  get awareness() {
2764
+ if (this._awarenessExplicitlyNull) return null;
2765
+ if (this._awarenessDeferred) this._materializeAwareness();
2584
2766
  return this.configuration.awareness;
2585
2767
  }
2768
+ /**
2769
+ * The Awareness instance if one exists, without ever creating one.
2770
+ *
2771
+ * @internal Used by provider internals and `MessageReceiver`. A deferred
2772
+ * document has no local presence, so there is nothing for an inbound
2773
+ * awareness frame to be applied to and nothing to answer a peer's query with
2774
+ * — and materializing on a peer's frame would hand every idle background
2775
+ * document a heartbeat as soon as anyone else joined the space.
2776
+ */
2777
+ peekAwareness() {
2778
+ return this._awarenessDeferred ? null : this.configuration.awareness;
2779
+ }
2780
+ /**
2781
+ * Build the deferred Awareness instance and bring it fully up to date:
2782
+ * seeded, wired, published, and caught up with the peers already present.
2783
+ */
2784
+ _materializeAwareness() {
2785
+ if (!this._awarenessDeferred) return;
2786
+ this._awarenessDeferred = false;
2787
+ this.configuration.awareness = new Awareness(this.document);
2788
+ this._initAwareness();
2789
+ if (this._isAttached) {
2790
+ this.send(AwarenessMessage, {
2791
+ awareness: this.configuration.awareness,
2792
+ clients: [this.document.clientID],
2793
+ documentName: this.configuration.name
2794
+ });
2795
+ this.send(QueryAwarenessMessage, { documentName: this.configuration.name });
2796
+ }
2797
+ }
2798
+ /**
2799
+ * Seed and wire an Awareness instance. Shared by the eager constructor path
2800
+ * and the lazy materialization path so the two cannot drift.
2801
+ */
2802
+ _initAwareness() {
2803
+ const awareness = this.configuration.awareness;
2804
+ if (!awareness) return;
2805
+ if (awareness.getLocalState() === null) awareness.setLocalState({});
2806
+ awareness.on("update", () => {
2807
+ this.emit("awarenessUpdate", { states: awarenessStatesToArray(awareness.getStates()) });
2808
+ });
2809
+ awareness.on("change", () => {
2810
+ this.emit("awarenessChange", { states: awarenessStatesToArray(awareness.getStates()) });
2811
+ });
2812
+ awareness.on("update", this.boundAwarenessUpdateHandler);
2813
+ }
2586
2814
  get hasUnsyncedChanges() {
2587
2815
  return this.unsyncedChanges > 0;
2588
2816
  }
@@ -2607,7 +2835,8 @@ var AbracadabraBaseProvider = class AbracadabraBaseProvider extends EventEmitter
2607
2835
  });
2608
2836
  }
2609
2837
  pageHide() {
2610
- if (this.awareness) removeAwarenessStates(this.awareness, [this.document.clientID], "page hide");
2838
+ const awareness = this.peekAwareness();
2839
+ if (awareness) removeAwarenessStates(awareness, [this.document.clientID], "page hide");
2611
2840
  }
2612
2841
  registerEventListeners() {
2613
2842
  if (typeof window === "undefined" || !("addEventListener" in window)) return;
@@ -2645,7 +2874,7 @@ var AbracadabraBaseProvider = class AbracadabraBaseProvider extends EventEmitter
2645
2874
  if (!this.isAuthenticated) return;
2646
2875
  const changedClients = added.concat(updated).concat(removed);
2647
2876
  this.send(AwarenessMessage, {
2648
- awareness: this.awareness,
2877
+ awareness: this.peekAwareness(),
2649
2878
  clients: changedClients,
2650
2879
  documentName: this.configuration.name
2651
2880
  });
@@ -2739,12 +2968,13 @@ var AbracadabraBaseProvider = class AbracadabraBaseProvider extends EventEmitter
2739
2968
  document: this.document,
2740
2969
  documentName: this.configuration.name
2741
2970
  });
2742
- if (this.awareness && this.awareness.getLocalState() !== null) this.send(AwarenessMessage, {
2743
- awareness: this.awareness,
2971
+ const openAwareness = this.peekAwareness();
2972
+ if (openAwareness && openAwareness.getLocalState() !== null) this.send(AwarenessMessage, {
2973
+ awareness: openAwareness,
2744
2974
  clients: [this.document.clientID],
2745
2975
  documentName: this.configuration.name
2746
2976
  });
2747
- if (this.awareness) this.send(QueryAwarenessMessage, { documentName: this.configuration.name });
2977
+ if (openAwareness) this.send(QueryAwarenessMessage, { documentName: this.configuration.name });
2748
2978
  }
2749
2979
  send(message, args) {
2750
2980
  if (!this._isAttached) return;
@@ -2767,16 +2997,18 @@ var AbracadabraBaseProvider = class AbracadabraBaseProvider extends EventEmitter
2767
2997
  this.synced = false;
2768
2998
  this._hasEverAuthenticated = false;
2769
2999
  this.clearResubscribe();
2770
- if (this.awareness) removeAwarenessStates(this.awareness, Array.from(this.awareness.getStates().keys()).filter((client) => client !== this.document.clientID), this);
3000
+ const closeAwareness = this.peekAwareness();
3001
+ if (closeAwareness) removeAwarenessStates(closeAwareness, Array.from(closeAwareness.getStates().keys()).filter((client) => client !== this.document.clientID), this);
2771
3002
  }
2772
3003
  destroy() {
2773
3004
  this.emit("destroy");
2774
3005
  if (this._rpc) this._rpc.destroy();
2775
3006
  if (this.intervals.forceSync) clearInterval(this.intervals.forceSync);
2776
- if (this.awareness) {
2777
- removeAwarenessStates(this.awareness, [this.document.clientID], "provider destroy");
2778
- this.awareness.off("update", this.boundAwarenessUpdateHandler);
2779
- this.awareness.destroy();
3007
+ const ownAwareness = this.peekAwareness();
3008
+ if (ownAwareness) {
3009
+ removeAwarenessStates(ownAwareness, [this.document.clientID], "provider destroy");
3010
+ ownAwareness.off("update", this.boundAwarenessUpdateHandler);
3011
+ ownAwareness.destroy();
2780
3012
  }
2781
3013
  this.document.off("update", this.boundDocumentUpdateHandler);
2782
3014
  this.removeAllListeners();
@@ -2922,6 +3154,34 @@ function txPromise$2(store, request) {
2922
3154
  request.onerror = () => reject(request.error);
2923
3155
  });
2924
3156
  }
3157
+ /**
3158
+ * Resolve when the whole transaction commits.
3159
+ *
3160
+ * `txPromise` waits on a single request, which is the wrong unit once a
3161
+ * transaction carries a batch: the last `add` succeeding does not mean the
3162
+ * transaction committed, and reporting durability before commit is exactly the
3163
+ * lie the offline store must not tell.
3164
+ */
3165
+ function txComplete(tx) {
3166
+ return new Promise((resolve, reject) => {
3167
+ tx.oncomplete = () => resolve();
3168
+ tx.onerror = () => reject(tx.error);
3169
+ tx.onabort = () => reject(tx.error ?? /* @__PURE__ */ new Error("transaction aborted"));
3170
+ });
3171
+ }
3172
+ /**
3173
+ * How long local edits are held before being written as one transaction.
3174
+ *
3175
+ * Yjs emits one update per keystroke, and the store used to open one IndexedDB
3176
+ * transaction for each — measured at 1.02 transactions per keystroke over 200
3177
+ * keystrokes. Coalescing trades a bounded window of durability for roughly an
3178
+ * order of magnitude fewer transactions. The window is small on purpose: these
3179
+ * edits have already gone to the server on the wire (that send is NOT batched),
3180
+ * so the exposure is an offline client that dies within the window.
3181
+ */
3182
+ const WRITE_COALESCE_MS = 150;
3183
+ /** Flush early once a burst reaches this many updates, regardless of the timer. */
3184
+ const MAX_WRITE_BATCH = 128;
2925
3185
  var OfflineStore = class {
2926
3186
  /**
2927
3187
  * @param docId The document UUID.
@@ -2936,6 +3196,9 @@ var OfflineStore = class {
2936
3196
  this.db = null;
2937
3197
  this.dbPromise = null;
2938
3198
  this._destroyed = false;
3199
+ this.writeBuffer = [];
3200
+ this.writeWaiters = [];
3201
+ this.flushTimer = null;
2939
3202
  this.storeKey = serverOrigin ? `${serverOrigin}/${docId}` : docId;
2940
3203
  }
2941
3204
  getDb() {
@@ -2946,13 +3209,91 @@ var OfflineStore = class {
2946
3209
  });
2947
3210
  return this.dbPromise;
2948
3211
  }
2949
- async persistUpdate(update) {
2950
- const db = await this.getDb();
2951
- if (!db) return;
2952
- const store = db.transaction("updates", "readwrite").objectStore("updates");
2953
- await txPromise$2(store, store.add(update));
3212
+ /**
3213
+ * Queue a local update for persistence.
3214
+ *
3215
+ * The returned promise settles when the update has actually been committed,
3216
+ * not when it was queued — so `await persistUpdate(u)` still means "on disk",
3217
+ * exactly as it did when every call opened its own transaction.
3218
+ */
3219
+ persistUpdate(update) {
3220
+ if (this._destroyed || !idbAvailable$4()) return Promise.resolve();
3221
+ this.writeBuffer.push(update);
3222
+ const settled = new Promise((resolve, reject) => {
3223
+ this.writeWaiters.push({
3224
+ resolve,
3225
+ reject
3226
+ });
3227
+ });
3228
+ if (this.writeBuffer.length >= MAX_WRITE_BATCH) this.flushWrites();
3229
+ else if (this.flushTimer === null) this.flushTimer = setTimeout(() => {
3230
+ this.flushWrites();
3231
+ }, WRITE_COALESCE_MS);
3232
+ return settled;
3233
+ }
3234
+ /**
3235
+ * Commit every buffered update as ONE transaction.
3236
+ *
3237
+ * Safe to call at any time, including with an empty buffer — every read path
3238
+ * calls it first so a caller can never observe a store that is missing writes
3239
+ * still sitting in memory.
3240
+ */
3241
+ async flushWrites() {
3242
+ if (this.flushTimer !== null) {
3243
+ clearTimeout(this.flushTimer);
3244
+ this.flushTimer = null;
3245
+ }
3246
+ const batch = this.writeBuffer;
3247
+ const waiters = this.writeWaiters;
3248
+ this.writeBuffer = [];
3249
+ this.writeWaiters = [];
3250
+ if (batch.length === 0) {
3251
+ for (const w of waiters) w.resolve();
3252
+ return;
3253
+ }
3254
+ try {
3255
+ const db = await this.getDb();
3256
+ if (db) {
3257
+ const tx = db.transaction("updates", "readwrite");
3258
+ const store = tx.objectStore("updates");
3259
+ for (const update of batch) store.add(update);
3260
+ await txComplete(tx);
3261
+ }
3262
+ for (const w of waiters) w.resolve();
3263
+ } catch (err) {
3264
+ for (const w of waiters) w.reject(err);
3265
+ throw err;
3266
+ }
3267
+ }
3268
+ /**
3269
+ * Issue the buffered writes synchronously, without awaiting them.
3270
+ *
3271
+ * For teardown paths that cannot await: `pagehide` (the page may not survive
3272
+ * a microtask) and `destroy()`. IndexedDB will not close a connection until
3273
+ * its running transactions finish, so writes issued here still land.
3274
+ */
3275
+ flushWritesSync() {
3276
+ if (this.flushTimer !== null) {
3277
+ clearTimeout(this.flushTimer);
3278
+ this.flushTimer = null;
3279
+ }
3280
+ const batch = this.writeBuffer;
3281
+ const waiters = this.writeWaiters;
3282
+ this.writeBuffer = [];
3283
+ this.writeWaiters = [];
3284
+ if (batch.length === 0) {
3285
+ for (const w of waiters) w.resolve();
3286
+ return;
3287
+ }
3288
+ const db = this.db;
3289
+ if (db) try {
3290
+ const store = db.transaction("updates", "readwrite").objectStore("updates");
3291
+ for (const update of batch) store.add(update);
3292
+ } catch {}
3293
+ for (const w of waiters) w.resolve();
2954
3294
  }
2955
3295
  async getPendingUpdates() {
3296
+ await this.flushWrites().catch(() => null);
2956
3297
  const db = await this.getDb();
2957
3298
  if (!db) return [];
2958
3299
  return new Promise((resolve, reject) => {
@@ -2962,6 +3303,13 @@ var OfflineStore = class {
2962
3303
  });
2963
3304
  }
2964
3305
  async clearPendingUpdates() {
3306
+ if (this.flushTimer !== null) {
3307
+ clearTimeout(this.flushTimer);
3308
+ this.flushTimer = null;
3309
+ }
3310
+ this.writeBuffer = [];
3311
+ for (const w of this.writeWaiters) w.resolve();
3312
+ this.writeWaiters = [];
2965
3313
  const db = await this.getDb();
2966
3314
  if (!db) return;
2967
3315
  const tx = db.transaction("updates", "readwrite");
@@ -3060,6 +3408,7 @@ var OfflineStore = class {
3060
3408
  })));
3061
3409
  }
3062
3410
  destroy() {
3411
+ this.flushWritesSync();
3063
3412
  this._destroyed = true;
3064
3413
  const db = this.db;
3065
3414
  this.db = null;
@@ -3133,7 +3482,10 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3133
3482
  if (client) {
3134
3483
  const r = resolved;
3135
3484
  if (!r.url && !r.websocketProvider) r.url = client.wsUrl;
3136
- if (resolved.token === void 0 && !configuration.cryptoIdentity) resolved.token = () => client.token ?? "";
3485
+ if (resolved.token === void 0 && !configuration.cryptoIdentity) resolved.token = async () => {
3486
+ await client.ensureFreshToken().catch(() => false);
3487
+ return client.token ?? "";
3488
+ };
3137
3489
  }
3138
3490
  super(resolved);
3139
3491
  this.effectiveRole = null;
@@ -3143,6 +3495,7 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3143
3495
  this.childAccessTimes = /* @__PURE__ */ new Map();
3144
3496
  this.pinnedChildren = /* @__PURE__ */ new Set();
3145
3497
  this.transientChildren = /* @__PURE__ */ new Set();
3498
+ this.unsubscribeToken = null;
3146
3499
  this.boundHandleYSubdocsChange = this.handleYSubdocsChange.bind(this);
3147
3500
  this.hasCachedContent = false;
3148
3501
  this._client = client;
@@ -3154,10 +3507,20 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3154
3507
  this.on("subdocRegistered", configuration.onSubdocRegistered ?? (() => null));
3155
3508
  this.on("subdocLoaded", configuration.onSubdocLoaded ?? (() => null));
3156
3509
  this.document.on("subdocs", this.boundHandleYSubdocsChange);
3510
+ this.unsubscribeToken = client?.onTokenChanged?.((token) => {
3511
+ try {
3512
+ this.configuration.websocketProvider?.refreshAuth?.(token);
3513
+ } catch {}
3514
+ }) ?? null;
3157
3515
  this.on("synced", () => this.flushPendingUpdates());
3158
3516
  this.restorePermissionSnapshot();
3159
- this.ready = Promise.race([this._initFromOfflineStore(), new Promise((resolve) => setTimeout(resolve, 5e3))]).catch((err) => {
3517
+ let readyTimer = null;
3518
+ this.ready = Promise.race([this._initFromOfflineStore(), new Promise((resolve) => {
3519
+ readyTimer = setTimeout(resolve, 5e3);
3520
+ })]).catch((err) => {
3160
3521
  this.emit("error", { message: `Offline store init failed: ${err?.message ?? err}` });
3522
+ }).finally(() => {
3523
+ if (readyTimer !== null) clearTimeout(readyTimer);
3161
3524
  });
3162
3525
  }
3163
3526
  /**
@@ -3402,6 +3765,7 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3402
3765
  document: childDoc,
3403
3766
  websocketProvider: this.configuration.websocketProvider,
3404
3767
  token: this.configuration.token,
3768
+ lazyAwareness: true,
3405
3769
  subdocLoading: this.subdocLoading,
3406
3770
  disableOfflineStore: this.abracadabraConfig.disableOfflineStore,
3407
3771
  client: this._client ?? void 0,
@@ -3480,6 +3844,19 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3480
3844
  return this.childProviders;
3481
3845
  }
3482
3846
  /**
3847
+ * Land buffered offline writes before the page goes away.
3848
+ *
3849
+ * `OfflineStore` coalesces local updates into one transaction per ~150 ms
3850
+ * window (see WRITE_COALESCE_MS). That window is the only moment an edit
3851
+ * exists in memory but not on disk, and a closing tab is exactly when it
3852
+ * would be lost — so pagehide flushes it synchronously. `super.pageHide()`
3853
+ * still clears our awareness state for peers.
3854
+ */
3855
+ pageHide() {
3856
+ super.pageHide();
3857
+ this.offlineStore?.flushWritesSync();
3858
+ }
3859
+ /**
3483
3860
  * Override to persist every local update to IndexedDB before sending it
3484
3861
  * over the wire, ensuring no work is lost during connection outages.
3485
3862
  *
@@ -3527,6 +3904,7 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3527
3904
  update,
3528
3905
  documentName: this.configuration.name
3529
3906
  });
3907
+ await this.persistSnapshot();
3530
3908
  await store.clearPendingUpdates();
3531
3909
  }
3532
3910
  const pendingSubdocs = await store.getPendingSubdocs();
@@ -3558,6 +3936,8 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3558
3936
  return this.configuration.websocketProvider.status === "connected";
3559
3937
  }
3560
3938
  destroy() {
3939
+ this.unsubscribeToken?.();
3940
+ this.unsubscribeToken = null;
3561
3941
  this.document.off("subdocs", this.boundHandleYSubdocsChange);
3562
3942
  const childIds = [...this.childProviders.keys()];
3563
3943
  for (const provider of this.childProviders.values()) provider.destroy();
@@ -10800,28 +11180,70 @@ function decodeBase64UrlToString(b64url) {
10800
11180
  const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
10801
11181
  return new TextDecoder().decode(bytes);
10802
11182
  }
11183
+ /**
11184
+ * Read a JWT's `exp` / `iat` claims, in ms. `0` for anything unreadable.
11185
+ *
11186
+ * Deliberately tolerant: a token this cannot parse is treated as expiring now,
11187
+ * which costs one extra handshake and never costs a dead session.
11188
+ */
11189
+ function readJwtTimes(token) {
11190
+ if (!token) return {
11191
+ exp: 0,
11192
+ iat: 0
11193
+ };
11194
+ const payload = token.split(".")[1];
11195
+ if (!payload) return {
11196
+ exp: 0,
11197
+ iat: 0
11198
+ };
11199
+ try {
11200
+ const claims = JSON.parse(decodeBase64UrlToString(payload));
11201
+ return {
11202
+ exp: typeof claims.exp === "number" ? claims.exp * 1e3 : 0,
11203
+ iat: typeof claims.iat === "number" ? claims.iat * 1e3 : 0
11204
+ };
11205
+ } catch {
11206
+ return {
11207
+ exp: 0,
11208
+ iat: 0
11209
+ };
11210
+ }
11211
+ }
10803
11212
  var AbracadabraClient = class {
10804
11213
  constructor(config) {
10805
11214
  this.rootListInflight = /* @__PURE__ */ new Map();
10806
11215
  this.streamTokens = /* @__PURE__ */ new Map();
10807
11216
  this.streamTokenInflight = /* @__PURE__ */ new Map();
11217
+ this._renew = null;
11218
+ this._renewing = null;
11219
+ this._renewTimer = null;
11220
+ this._tokenListeners = /* @__PURE__ */ new Set();
10808
11221
  this.baseUrl = config.url.replace(/\/+$/, "");
10809
11222
  this.persistAuth = config.persistAuth ?? typeof localStorage !== "undefined";
10810
11223
  this.storageKey = config.storageKey ?? "abracadabra:auth";
10811
11224
  this._fetch = config.fetch ?? globalThis.fetch.bind(globalThis);
10812
11225
  this.cache = config.cache ?? null;
10813
11226
  this._onAuthFailed = config.onAuthFailed ?? null;
11227
+ this.renewMarginMs = config.tokenRenewMarginMs ?? 20 * 6e4;
11228
+ this.renewCheckMs = config.tokenRenewCheckMs ?? 6e4;
10814
11229
  this._token = config.token ?? this.loadPersistedToken() ?? null;
10815
11230
  }
10816
11231
  get token() {
10817
11232
  return this._token;
10818
11233
  }
10819
11234
  set token(value) {
11235
+ const changed = value !== this._token;
10820
11236
  this._token = value;
10821
11237
  this.streamTokens.clear();
10822
11238
  this.streamTokenInflight.clear();
10823
11239
  if (this.persistAuth) if (value) this.persistToken(value);
10824
11240
  else this.clearPersistedToken();
11241
+ if (changed && value) {
11242
+ this.scheduleSessionRenewal();
11243
+ for (const listener of this._tokenListeners) try {
11244
+ listener(value);
11245
+ } catch {}
11246
+ }
10825
11247
  }
10826
11248
  get isAuthenticated() {
10827
11249
  return this._token !== null;
@@ -10837,6 +11259,117 @@ var AbracadabraClient = class {
10837
11259
  return false;
10838
11260
  }
10839
11261
  }
11262
+ /** When the current token stops validating, in ms. `0` when unknown. */
11263
+ get tokenExpiresAt() {
11264
+ return readJwtTimes(this._token).exp;
11265
+ }
11266
+ /**
11267
+ * Install the way this client re-authenticates itself, or `null` to stop.
11268
+ *
11269
+ * {@link loginWithKey} installs one for you, so a key-authenticated client
11270
+ * — every Node runner, and every browser session on a crypto identity —
11271
+ * renews without its consumer doing anything. Install one by hand for a
11272
+ * password session or any other flow that can mint a fresh token.
11273
+ *
11274
+ * The function must return the new JWT; adopting it (and notifying open
11275
+ * sockets) is this client's job.
11276
+ */
11277
+ setSessionRenewer(renew) {
11278
+ this._renew = renew;
11279
+ if (renew) this.scheduleSessionRenewal();
11280
+ else this.stopSessionRenewal();
11281
+ }
11282
+ /** Whether this client knows how to re-authenticate itself. */
11283
+ get canRenewSession() {
11284
+ return this._renew !== null;
11285
+ }
11286
+ /**
11287
+ * Called whenever the session token changes — a login, a renewal, a device
11288
+ * refresh, a key revocation. Providers use this to re-arm sockets that are
11289
+ * already open. Returns an unsubscribe function.
11290
+ */
11291
+ onTokenChanged(listener) {
11292
+ this._tokenListeners.add(listener);
11293
+ return () => this._tokenListeners.delete(listener);
11294
+ }
11295
+ /**
11296
+ * Make sure the token has life left in it, re-minting if it does not.
11297
+ *
11298
+ * Cheap when the token is fresh — one subtraction — so callers need not
11299
+ * reason about when the last renewal was, and concurrent callers share one
11300
+ * handshake. Returns whether the session is believed good; `false` is not
11301
+ * fatal, and the caller's own failure is still the authority.
11302
+ */
11303
+ async ensureFreshToken(marginMs) {
11304
+ if (!this._renew) return this.isTokenValid();
11305
+ if (this._renewing) return this._renewing;
11306
+ const { exp } = readJwtTimes(this._token);
11307
+ if (exp > 0 && exp - Date.now() > this.renewMargin(marginMs)) return true;
11308
+ const mint = this._renew;
11309
+ const renew = (async () => {
11310
+ try {
11311
+ const token = await mint();
11312
+ if (token && token !== this._token) this.token = token;
11313
+ return true;
11314
+ } catch {
11315
+ return false;
11316
+ } finally {
11317
+ this._renewing = null;
11318
+ }
11319
+ })();
11320
+ this._renewing = renew;
11321
+ return renew;
11322
+ }
11323
+ /**
11324
+ * How long before `exp` this session is re-minted.
11325
+ *
11326
+ * Capped at a third of the token's own lifetime, so a server configured
11327
+ * with short-lived tokens is not re-authenticated on every check — without
11328
+ * the cap a 45-second token against a 20-minute margin would mint a new
11329
+ * session every time anything asked.
11330
+ */
11331
+ renewMargin(marginMs) {
11332
+ const { exp, iat } = readJwtTimes(this._token);
11333
+ const lifetime = exp > iat && iat > 0 ? exp - iat : Number.POSITIVE_INFINITY;
11334
+ return Math.min(marginMs ?? this.renewMarginMs, lifetime / 3);
11335
+ }
11336
+ /**
11337
+ * Arm a single timer for the moment this token needs replacing.
11338
+ *
11339
+ * Scheduled from the token's OWN expiry rather than on a fixed interval,
11340
+ * and that is not tidiness. A poll can outrun the margin: measured against
11341
+ * a server issuing 45-second tokens, a 60-second poll first fired fifteen
11342
+ * seconds AFTER the token had already lapsed — long enough for the
11343
+ * awareness heartbeat to hit an expired session and have the socket dropped
11344
+ * under it. A deadline cannot be outrun by the thing it is a deadline for.
11345
+ *
11346
+ * Re-armed on every token change, so a renewal schedules the next one.
11347
+ */
11348
+ scheduleSessionRenewal() {
11349
+ this.stopSessionRenewal();
11350
+ if (!this._renew || this.renewCheckMs <= 0) return;
11351
+ const { exp } = readJwtTimes(this._token);
11352
+ const delay = exp > 0 ? Math.max(1e3, exp - Date.now() - this.renewMargin()) : this.renewCheckMs;
11353
+ this._renewTimer = setTimeout(() => {
11354
+ this.ensureFreshToken().catch(() => false).finally(() => this.scheduleSessionRenewal());
11355
+ }, Math.min(delay, 720 * 6e4));
11356
+ this._renewTimer.unref?.();
11357
+ }
11358
+ stopSessionRenewal() {
11359
+ if (!this._renewTimer) return;
11360
+ clearTimeout(this._renewTimer);
11361
+ this._renewTimer = null;
11362
+ }
11363
+ /**
11364
+ * Stop renewing and drop every listener. Call when a client is discarded —
11365
+ * a long-lived consumer that builds one client per connection would
11366
+ * otherwise leave a timer per discarded client.
11367
+ */
11368
+ destroy() {
11369
+ this.stopSessionRenewal();
11370
+ this._renew = null;
11371
+ this._tokenListeners.clear();
11372
+ }
10840
11373
  /** Derives ws:// or wss:// URL from the http(s) base URL. */
10841
11374
  get wsUrl() {
10842
11375
  return this.baseUrl.replace(/^https:\/\//, "wss://").replace(/^http:\/\//, "ws://") + "/ws";
@@ -10899,11 +11432,13 @@ var AbracadabraClient = class {
10899
11432
  async loginWithKey(publicKey, signChallenge) {
10900
11433
  const { challenge } = await this.challenge(publicKey);
10901
11434
  const signature = await signChallenge(challenge);
10902
- return this.verify({
11435
+ const token = await this.verify({
10903
11436
  publicKey,
10904
11437
  signature,
10905
11438
  challenge
10906
11439
  });
11440
+ this.setSessionRenewer(() => this.loginWithKey(publicKey, signChallenge));
11441
+ return token;
10907
11442
  }
10908
11443
  /** Add a new Ed25519 public key to the current user (multi-device). */
10909
11444
  async addKey(opts) {
@@ -17274,10 +17809,24 @@ var BackgroundSyncManager = class extends EventEmitter {
17274
17809
  * @returns Cleanup function to stop the periodic sync.
17275
17810
  */
17276
17811
  startPeriodicSync(intervalMs = 300 * 1e3) {
17812
+ let missedWhileHidden = false;
17277
17813
  const handle = setInterval(() => {
17278
- if (!this._destroyed) this.syncAll().catch(() => null);
17814
+ if (this._destroyed) return;
17815
+ if (getLifecycleGate().backgrounded) {
17816
+ missedWhileHidden = true;
17817
+ return;
17818
+ }
17819
+ this.syncAll().catch(() => null);
17279
17820
  }, intervalMs);
17280
- return () => clearInterval(handle);
17821
+ const unsubscribe = getLifecycleGate().onChange((backgrounded) => {
17822
+ if (backgrounded || !missedWhileHidden || this._destroyed) return;
17823
+ missedWhileHidden = false;
17824
+ this.syncAll().catch(() => null);
17825
+ });
17826
+ return () => {
17827
+ clearInterval(handle);
17828
+ unsubscribe();
17829
+ };
17281
17830
  }
17282
17831
  /**
17283
17832
  * Clear all offline document data and sync state.
@@ -22286,6 +22835,340 @@ var DocumentManager = class {
22286
22835
  }
22287
22836
  };
22288
22837
 
22838
+ //#endregion
22839
+ //#region packages/provider/src/PerfCounters.ts
22840
+ let installed = false;
22841
+ let startedAt = 0;
22842
+ const liveTimers = /* @__PURE__ */ new Map();
22843
+ const groupCreated = /* @__PURE__ */ new Map();
22844
+ const groupFired = /* @__PURE__ */ new Map();
22845
+ let intervalsCreated = 0;
22846
+ let timeoutsCreated = 0;
22847
+ let timersFired = 0;
22848
+ let rafRequested = 0;
22849
+ let rafFired = 0;
22850
+ let idbTransactions = 0;
22851
+ let idbDatabasesOpened = 0;
22852
+ const idbByStore = /* @__PURE__ */ new Map();
22853
+ let framesSent = 0;
22854
+ let bytesSent = 0;
22855
+ let framesReceived = 0;
22856
+ let bytesReceived = 0;
22857
+ const sentByType = /* @__PURE__ */ new Map();
22858
+ let origSetInterval = null;
22859
+ let origClearInterval = null;
22860
+ let origSetTimeout = null;
22861
+ let origClearTimeout = null;
22862
+ let origRaf = null;
22863
+ let origIdbTransaction = null;
22864
+ let origIdbOpen = null;
22865
+ const socketRestores = [];
22866
+ /** The heartbeat every y-protocols Awareness instance starts: outdatedTimeout / 10. */
22867
+ const AWARENESS_HEARTBEAT_MS = 3e3;
22868
+ /**
22869
+ * Best-effort "who created this timer". Walks the stack past this module and
22870
+ * past the Node/browser internals, and reports the first frame that looks like
22871
+ * real code. Deliberately coarse: a file name is enough to tell an Awareness
22872
+ * heartbeat apart from a reconnect backoff, and anything finer would be noise.
22873
+ */
22874
+ function captureOrigin() {
22875
+ const stack = (/* @__PURE__ */ new Error()).stack;
22876
+ if (!stack) return "unknown";
22877
+ const lines = stack.split("\n").slice(1);
22878
+ for (const line of lines) {
22879
+ if (line.includes("PerfCounters")) continue;
22880
+ if (line.includes("node:internal")) continue;
22881
+ const nm = line.match(/node_modules\/(?:\.pnpm\/[^/]+\/node_modules\/)?(.+?):\d+:\d+/);
22882
+ if (nm?.[1]) return nm[1];
22883
+ const src = line.match(/([^/\\()]+\.(?:ts|mts|js|mjs)):\d+:\d+/);
22884
+ if (src?.[1]) return src[1];
22885
+ }
22886
+ return "unknown";
22887
+ }
22888
+ function groupKey(origin, delayMs) {
22889
+ return `${origin}@${delayMs}`;
22890
+ }
22891
+ function bump(map, key, by = 1) {
22892
+ map.set(key, (map.get(key) ?? 0) + by);
22893
+ }
22894
+ /**
22895
+ * Begin counting. Idempotent — a second call is a no-op rather than a
22896
+ * double-wrap, which would double every number and be very hard to notice.
22897
+ */
22898
+ function installPerfCounters() {
22899
+ if (installed) return;
22900
+ installed = true;
22901
+ startedAt = Date.now();
22902
+ const g = globalThis;
22903
+ origSetInterval = g.setInterval;
22904
+ origClearInterval = g.clearInterval;
22905
+ origSetTimeout = g.setTimeout;
22906
+ origClearTimeout = g.clearTimeout;
22907
+ g.setInterval = function patchedSetInterval(handler, delay, ...args) {
22908
+ const origin = captureOrigin();
22909
+ const delayMs = delay ?? 0;
22910
+ const key = groupKey(origin, delayMs);
22911
+ const wrapped = typeof handler === "function" ? (...cbArgs) => {
22912
+ timersFired++;
22913
+ bump(groupFired, key);
22914
+ return handler(...cbArgs);
22915
+ } : handler;
22916
+ const id = origSetInterval.call(g, wrapped, delay, ...args);
22917
+ intervalsCreated++;
22918
+ bump(groupCreated, key);
22919
+ liveTimers.set(id, {
22920
+ origin,
22921
+ delayMs,
22922
+ kind: "interval"
22923
+ });
22924
+ return id;
22925
+ };
22926
+ g.clearInterval = function patchedClearInterval(id) {
22927
+ liveTimers.delete(id);
22928
+ return origClearInterval.call(g, id);
22929
+ };
22930
+ g.setTimeout = function patchedSetTimeout(handler, delay, ...args) {
22931
+ const origin = captureOrigin();
22932
+ const delayMs = delay ?? 0;
22933
+ const key = groupKey(origin, delayMs);
22934
+ let id;
22935
+ const wrapped = typeof handler === "function" ? (...cbArgs) => {
22936
+ timersFired++;
22937
+ bump(groupFired, key);
22938
+ liveTimers.delete(id);
22939
+ return handler(...cbArgs);
22940
+ } : handler;
22941
+ id = origSetTimeout.call(g, wrapped, delay, ...args);
22942
+ timeoutsCreated++;
22943
+ bump(groupCreated, key);
22944
+ liveTimers.set(id, {
22945
+ origin,
22946
+ delayMs,
22947
+ kind: "timeout"
22948
+ });
22949
+ return id;
22950
+ };
22951
+ g.clearTimeout = function patchedClearTimeout(id) {
22952
+ liveTimers.delete(id);
22953
+ return origClearTimeout.call(g, id);
22954
+ };
22955
+ if (typeof g.requestAnimationFrame === "function") {
22956
+ origRaf = g.requestAnimationFrame;
22957
+ g.requestAnimationFrame = function patchedRaf(cb) {
22958
+ rafRequested++;
22959
+ return origRaf.call(g, (t) => {
22960
+ rafFired++;
22961
+ return cb(t);
22962
+ });
22963
+ };
22964
+ }
22965
+ if (typeof g.IDBDatabase === "function") {
22966
+ origIdbTransaction = g.IDBDatabase.prototype.transaction;
22967
+ g.IDBDatabase.prototype.transaction = function patchedTransaction(storeNames, ...rest) {
22968
+ idbTransactions++;
22969
+ const names = Array.isArray(storeNames) ? storeNames : [storeNames];
22970
+ for (const n of names) bump(idbByStore, String(n));
22971
+ return origIdbTransaction.call(this, storeNames, ...rest);
22972
+ };
22973
+ }
22974
+ if (g.indexedDB && typeof g.indexedDB.open === "function") {
22975
+ origIdbOpen = g.indexedDB.open.bind(g.indexedDB);
22976
+ g.indexedDB.open = function patchedOpen(...args) {
22977
+ idbDatabasesOpened++;
22978
+ return origIdbOpen(...args);
22979
+ };
22980
+ }
22981
+ }
22982
+ /** Restore every patched global. Safe to call when not installed. */
22983
+ function uninstall() {
22984
+ if (!installed) return;
22985
+ const g = globalThis;
22986
+ if (origSetInterval) g.setInterval = origSetInterval;
22987
+ if (origClearInterval) g.clearInterval = origClearInterval;
22988
+ if (origSetTimeout) g.setTimeout = origSetTimeout;
22989
+ if (origClearTimeout) g.clearTimeout = origClearTimeout;
22990
+ if (origRaf) g.requestAnimationFrame = origRaf;
22991
+ if (origIdbTransaction && typeof g.IDBDatabase === "function") g.IDBDatabase.prototype.transaction = origIdbTransaction;
22992
+ if (origIdbOpen && g.indexedDB) g.indexedDB.open = origIdbOpen;
22993
+ for (const restore of socketRestores.splice(0)) restore();
22994
+ origSetInterval = null;
22995
+ origClearInterval = null;
22996
+ origSetTimeout = null;
22997
+ origClearTimeout = null;
22998
+ origRaf = null;
22999
+ origIdbTransaction = null;
23000
+ origIdbOpen = null;
23001
+ installed = false;
23002
+ reset();
23003
+ }
23004
+ /** Zero every counter. Live-timer bookkeeping is preserved — it is a census. */
23005
+ function reset() {
23006
+ startedAt = Date.now();
23007
+ groupCreated.clear();
23008
+ groupFired.clear();
23009
+ intervalsCreated = 0;
23010
+ timeoutsCreated = 0;
23011
+ timersFired = 0;
23012
+ rafRequested = 0;
23013
+ rafFired = 0;
23014
+ idbTransactions = 0;
23015
+ idbDatabasesOpened = 0;
23016
+ idbByStore.clear();
23017
+ framesSent = 0;
23018
+ bytesSent = 0;
23019
+ framesReceived = 0;
23020
+ bytesReceived = 0;
23021
+ sentByType.clear();
23022
+ }
23023
+ /**
23024
+ * Count frames on one AbracadabraWS. Returns a restore function; the restore is
23025
+ * also run by `uninstall()`.
23026
+ *
23027
+ * Wrapping the instance (rather than a global) is deliberate: in Node the
23028
+ * provider runs on the `ws` package, so patching `globalThis.WebSocket` would
23029
+ * silently measure nothing at all.
23030
+ */
23031
+ function instrumentSocket(socket) {
23032
+ const originalSend = socket.send.bind(socket);
23033
+ socket.send = (message) => {
23034
+ framesSent++;
23035
+ const bytes = byteLength(message);
23036
+ bytesSent += bytes;
23037
+ const type = readMessageType(message);
23038
+ if (type !== null) bump(sentByType, type);
23039
+ return originalSend(message);
23040
+ };
23041
+ const onMessage = (payload) => {
23042
+ framesReceived++;
23043
+ bytesReceived += byteLength(payload?.event?.data ?? payload?.data ?? payload);
23044
+ };
23045
+ socket.on("message", onMessage);
23046
+ const restore = () => {
23047
+ socket.send = originalSend;
23048
+ try {
23049
+ socket.off("message", onMessage);
23050
+ } catch {}
23051
+ };
23052
+ socketRestores.push(restore);
23053
+ return restore;
23054
+ }
23055
+ function byteLength(value) {
23056
+ if (!value) return 0;
23057
+ if (value instanceof Uint8Array) return value.byteLength;
23058
+ if (value instanceof ArrayBuffer) return value.byteLength;
23059
+ if (typeof value === "string") return value.length;
23060
+ const encoded = value?.toUint8Array?.() ?? value?.message;
23061
+ if (encoded instanceof Uint8Array) return encoded.byteLength;
23062
+ return 0;
23063
+ }
23064
+ /**
23065
+ * The Hocuspocus V2 frame puts a varstring document name first, then the
23066
+ * message type. We only need a stable label, so report the type byte as-is
23067
+ * rather than duplicating the wire decoder here.
23068
+ */
23069
+ function readMessageType(message) {
23070
+ const encoded = message?.toUint8Array?.() ?? message?.message ?? (message instanceof Uint8Array ? message : null);
23071
+ if (!(encoded instanceof Uint8Array) || encoded.length === 0) return null;
23072
+ let offset = 0;
23073
+ let nameLen = 0;
23074
+ let shift = 0;
23075
+ while (offset < encoded.length) {
23076
+ const byte = encoded[offset++];
23077
+ nameLen |= (byte & 127) << shift;
23078
+ if ((byte & 128) === 0) break;
23079
+ shift += 7;
23080
+ }
23081
+ const typeIndex = offset + nameLen;
23082
+ if (typeIndex >= encoded.length) return null;
23083
+ return `type:${encoded[typeIndex]}`;
23084
+ }
23085
+ function snapshot() {
23086
+ const elapsedMs = Math.max(1, Date.now() - startedAt);
23087
+ const liveByKey = /* @__PURE__ */ new Map();
23088
+ let intervalsLive = 0;
23089
+ let timeoutsLive = 0;
23090
+ let awarenessLive = 0;
23091
+ for (const rec of liveTimers.values()) {
23092
+ bump(liveByKey, groupKey(rec.origin, rec.delayMs));
23093
+ if (rec.kind === "interval") {
23094
+ intervalsLive++;
23095
+ if (isAwarenessHeartbeat(rec)) awarenessLive++;
23096
+ } else timeoutsLive++;
23097
+ }
23098
+ const groups = [...new Set([
23099
+ ...groupCreated.keys(),
23100
+ ...groupFired.keys(),
23101
+ ...liveByKey.keys()
23102
+ ])].map((key) => {
23103
+ const at = key.lastIndexOf("@");
23104
+ return {
23105
+ origin: key.slice(0, at),
23106
+ delayMs: Number(key.slice(at + 1)),
23107
+ created: groupCreated.get(key) ?? 0,
23108
+ live: liveByKey.get(key) ?? 0,
23109
+ fired: groupFired.get(key) ?? 0
23110
+ };
23111
+ }).sort((a, b) => b.live - a.live || b.fired - a.fired);
23112
+ let heartbeatFires = 0;
23113
+ for (const group of groups) if (group.delayMs === AWARENESS_HEARTBEAT_MS && isAwarenessOrigin(group.origin)) heartbeatFires += group.fired;
23114
+ return {
23115
+ elapsedMs,
23116
+ timers: {
23117
+ intervalsCreated,
23118
+ intervalsLive,
23119
+ timeoutsCreated,
23120
+ timeoutsLive,
23121
+ fired: timersFired,
23122
+ firedPerSecond: Number((timersFired / elapsedMs * 1e3).toFixed(2)),
23123
+ groups
23124
+ },
23125
+ animationFrames: {
23126
+ requested: rafRequested,
23127
+ fired: rafFired
23128
+ },
23129
+ awareness: {
23130
+ liveInstances: awarenessLive,
23131
+ heartbeatFires
23132
+ },
23133
+ indexedDb: {
23134
+ transactions: idbTransactions,
23135
+ byStore: Object.fromEntries(idbByStore),
23136
+ databasesOpened: idbDatabasesOpened
23137
+ },
23138
+ sockets: {
23139
+ framesSent,
23140
+ bytesSent,
23141
+ framesReceived,
23142
+ bytesReceived,
23143
+ sentByType: Object.fromEntries(sentByType)
23144
+ }
23145
+ };
23146
+ }
23147
+ function isAwarenessOrigin(origin) {
23148
+ return origin.includes("awareness");
23149
+ }
23150
+ function isAwarenessHeartbeat(rec) {
23151
+ return rec.delayMs === AWARENESS_HEARTBEAT_MS && isAwarenessOrigin(rec.origin);
23152
+ }
23153
+ /** Field-by-field difference of two snapshots, for before/after comparisons. */
23154
+ function diff(before, after) {
23155
+ return {
23156
+ elapsedMs: after.elapsedMs - before.elapsedMs,
23157
+ timersFired: after.timers.fired - before.timers.fired,
23158
+ intervalsCreated: after.timers.intervalsCreated - before.timers.intervalsCreated,
23159
+ intervalsLive: after.timers.intervalsLive - before.timers.intervalsLive,
23160
+ awarenessLive: after.awareness.liveInstances - before.awareness.liveInstances,
23161
+ heartbeatFires: after.awareness.heartbeatFires - before.awareness.heartbeatFires,
23162
+ framesSent: after.sockets.framesSent - before.sockets.framesSent,
23163
+ bytesSent: after.sockets.bytesSent - before.sockets.bytesSent,
23164
+ idbTransactions: after.indexedDb.transactions - before.indexedDb.transactions
23165
+ };
23166
+ }
23167
+ /** Whether counting is currently active. */
23168
+ function isInstalled() {
23169
+ return installed;
23170
+ }
23171
+
22289
23172
  //#endregion
22290
23173
  exports.AbracadabraBaseProvider = AbracadabraBaseProvider;
22291
23174
  exports.AbracadabraClient = AbracadabraClient;
@@ -22322,13 +23205,16 @@ exports.FileTransferChannel = FileTransferChannel;
22322
23205
  exports.FileTransferHandle = FileTransferHandle;
22323
23206
  exports.Forbidden = Forbidden;
22324
23207
  exports.GEO_TYPE_META_SCHEMAS = GEO_TYPE_META_SCHEMAS;
23208
+ exports.HIDE_GRACE_MS = HIDE_GRACE_MS;
22325
23209
  exports.HocuspocusProvider = HocuspocusProvider;
22326
23210
  exports.HocuspocusProviderWebsocket = HocuspocusProviderWebsocket;
22327
23211
  exports.IdentityDocProvider = IdentityDocProvider;
22328
23212
  exports.KEY_EXCHANGE_CHANNEL = KEY_EXCHANGE_CHANNEL;
22329
23213
  exports.Kind = Kind;
23214
+ exports.LifecycleGate = LifecycleGate;
22330
23215
  exports.LocalStorageDeviceSessionStorage = LocalStorageDeviceSessionStorage;
22331
23216
  exports.ManualSignaling = ManualSignaling;
23217
+ exports.ManualVisibilitySource = ManualVisibilitySource;
22332
23218
  exports.MessageTooBig = MessageTooBig;
22333
23219
  exports.MessageType = MessageType;
22334
23220
  exports.MetaManager = MetaManager;
@@ -22384,6 +23270,8 @@ exports.filenameToLabel = filenameToLabel;
22384
23270
  exports.foldRecords = foldRecords;
22385
23271
  exports.forgetServerIdentity = forgetServerIdentity;
22386
23272
  exports.generateMnemonic = generateMnemonic;
23273
+ exports.getLifecycleGate = getLifecycleGate;
23274
+ exports.installPerfCounters = installPerfCounters;
22387
23275
  exports.isEncryptedContent = isEncryptedContent;
22388
23276
  exports.isPlaceholderLabel = isPlaceholderLabel;
22389
23277
  exports.isServerScopedStore = isServerScopedStore;
@@ -22402,6 +23290,10 @@ exports.normalizeRootId = normalizeRootId;
22402
23290
  exports.openSyncedProvider = openSyncedProvider;
22403
23291
  exports.parseFrontmatter = parseFrontmatter;
22404
23292
  exports.patchEntry = patchEntry;
23293
+ exports.perfCountersInstalled = isInstalled;
23294
+ exports.perfDiff = diff;
23295
+ exports.perfInstrumentSocket = instrumentSocket;
23296
+ exports.perfSnapshot = snapshot;
22405
23297
  exports.pickEntrySpace = pickEntrySpace;
22406
23298
  exports.populateYDocFromMarkdown = populateYDocFromMarkdown;
22407
23299
  exports.readAuthMessage = readAuthMessage;
@@ -22410,13 +23302,16 @@ exports.readEntries = readEntries;
22410
23302
  exports.reconcileDocCover = reconcileDocCover;
22411
23303
  exports.recordFromYAny = recordFromYAny;
22412
23304
  exports.removeServer = removeServer;
23305
+ exports.resetPerfCounters = reset;
22413
23306
  exports.resolvePageType = resolvePageType;
22414
23307
  exports.resolveServer = resolveServer;
22415
23308
  exports.saveServerRegistry = saveServerRegistry;
22416
23309
  exports.serverRegistryPath = serverRegistryPath;
22417
23310
  exports.setDefault = setDefault;
23311
+ exports.setLifecycleGate = setLifecycleGate;
22418
23312
  exports.signChallengeWithSeed = signChallengeWithSeed;
22419
23313
  exports.toPlain = toPlain;
23314
+ exports.uninstallPerfCounters = uninstall;
22420
23315
  exports.unwrapSeed = unwrapSeed;
22421
23316
  exports.validateMnemonic = validateMnemonic;
22422
23317
  exports.waitForSync = waitForSync;