@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.
@@ -1098,6 +1098,128 @@ const Kind = {
1098
1098
  */
1099
1099
  const SERVER_ROOT_ID = "00000000-0000-0000-0000-000000000000";
1100
1100
 
1101
+ //#endregion
1102
+ //#region packages/provider/src/LifecycleGate.ts
1103
+ /** How long the app must stay hidden before we act on it. */
1104
+ const HIDE_GRACE_MS = 1e4;
1105
+ /** The browser's own visibility, or a permanently-visible stub off-DOM. */
1106
+ function defaultSource() {
1107
+ const doc = globalThis.document;
1108
+ if (!doc || typeof doc.addEventListener !== "function") return {
1109
+ get: () => "visible",
1110
+ subscribe: () => () => {}
1111
+ };
1112
+ return {
1113
+ get: () => doc.visibilityState === "hidden" ? "hidden" : "visible",
1114
+ subscribe: (onChange) => {
1115
+ doc.addEventListener("visibilitychange", onChange);
1116
+ return () => doc.removeEventListener("visibilitychange", onChange);
1117
+ }
1118
+ };
1119
+ }
1120
+ var LifecycleGate = class {
1121
+ constructor(source = defaultSource(), graceMs = HIDE_GRACE_MS) {
1122
+ this.graceMs = graceMs;
1123
+ this.unsubscribe = null;
1124
+ this.hideTimer = null;
1125
+ this._backgrounded = false;
1126
+ this.listeners = /* @__PURE__ */ new Set();
1127
+ this.source = source;
1128
+ this.unsubscribe = this.source.subscribe(() => this.onVisibilityChange());
1129
+ }
1130
+ /**
1131
+ * True when the app has been hidden for longer than the grace period.
1132
+ *
1133
+ * Deliberately NOT the same as `document.hidden`: a tab that was hidden two
1134
+ * seconds ago is still, for our purposes, in use.
1135
+ */
1136
+ get backgrounded() {
1137
+ return this._backgrounded;
1138
+ }
1139
+ /** Subscribe to background/foreground transitions. Returns an unsubscribe fn. */
1140
+ onChange(listener) {
1141
+ this.listeners.add(listener);
1142
+ return () => this.listeners.delete(listener);
1143
+ }
1144
+ /** Swap the visibility source. Used by tests to drive state deterministically. */
1145
+ setSource(source) {
1146
+ this.unsubscribe?.();
1147
+ this.source = source;
1148
+ this.unsubscribe = this.source.subscribe(() => this.onVisibilityChange());
1149
+ this.onVisibilityChange();
1150
+ }
1151
+ onVisibilityChange() {
1152
+ if (this.source.get() === "hidden") {
1153
+ if (this._backgrounded || this.hideTimer) return;
1154
+ this.hideTimer = setTimeout(() => {
1155
+ this.hideTimer = null;
1156
+ this.setBackgrounded(true);
1157
+ }, this.graceMs);
1158
+ return;
1159
+ }
1160
+ if (this.hideTimer) {
1161
+ clearTimeout(this.hideTimer);
1162
+ this.hideTimer = null;
1163
+ }
1164
+ this.setBackgrounded(false);
1165
+ }
1166
+ setBackgrounded(next) {
1167
+ if (this._backgrounded === next) return;
1168
+ this._backgrounded = next;
1169
+ for (const listener of [...this.listeners]) try {
1170
+ listener(next);
1171
+ } catch {}
1172
+ }
1173
+ destroy() {
1174
+ this.unsubscribe?.();
1175
+ this.unsubscribe = null;
1176
+ if (this.hideTimer) {
1177
+ clearTimeout(this.hideTimer);
1178
+ this.hideTimer = null;
1179
+ }
1180
+ this.listeners.clear();
1181
+ }
1182
+ };
1183
+ /**
1184
+ * The process-wide gate.
1185
+ *
1186
+ * Visibility is a property of the tab, not of any one provider or socket, so a
1187
+ * single shared instance is both correct and avoids paying for one
1188
+ * `visibilitychange` listener per document.
1189
+ */
1190
+ let shared = null;
1191
+ function getLifecycleGate() {
1192
+ if (!shared) shared = new LifecycleGate();
1193
+ return shared;
1194
+ }
1195
+ /**
1196
+ * Replace the shared gate. Tests use this to install a controllable source;
1197
+ * passing `null` restores the default browser-backed gate on next access.
1198
+ */
1199
+ function setLifecycleGate(gate) {
1200
+ if (shared && shared !== gate) shared.destroy();
1201
+ shared = gate;
1202
+ }
1203
+ /** A visibility source a test (or an embedder) can drive by hand. */
1204
+ var ManualVisibilitySource = class {
1205
+ constructor() {
1206
+ this.state = "visible";
1207
+ this.listeners = /* @__PURE__ */ new Set();
1208
+ }
1209
+ get() {
1210
+ return this.state;
1211
+ }
1212
+ subscribe(onChange) {
1213
+ this.listeners.add(onChange);
1214
+ return () => this.listeners.delete(onChange);
1215
+ }
1216
+ set(state) {
1217
+ if (this.state === state) return;
1218
+ this.state = state;
1219
+ for (const listener of [...this.listeners]) listener();
1220
+ }
1221
+ };
1222
+
1101
1223
  //#endregion
1102
1224
  //#region packages/provider/src/IncomingMessage.ts
1103
1225
  var IncomingMessage = class {
@@ -1205,8 +1327,10 @@ var AbracadabraWS = class extends EventEmitter {
1205
1327
  this.connectionAttempt = null;
1206
1328
  this.onlineListener = null;
1207
1329
  this.offlineListener = null;
1330
+ this.unsubscribeLifecycle = null;
1208
1331
  this.receivedOnOpenPayload = void 0;
1209
1332
  this.closeTries = 0;
1333
+ this.lastRefreshToken = null;
1210
1334
  this.setConfiguration(configuration);
1211
1335
  this.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill ? configuration.WebSocketPolyfill : globalThis.WebSocket;
1212
1336
  this.on("open", this.configuration.onOpen);
@@ -1223,6 +1347,9 @@ var AbracadabraWS = class extends EventEmitter {
1223
1347
  this.on("close", this.onClose.bind(this));
1224
1348
  this.on("message", this.onMessage.bind(this));
1225
1349
  this.intervals.connectionChecker = setInterval(this.checkConnection.bind(this), this.configuration.messageReconnectTimeout / 10);
1350
+ this.unsubscribeLifecycle = getLifecycleGate().onChange((backgrounded) => {
1351
+ if (!backgrounded) this.checkConnection();
1352
+ });
1226
1353
  if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
1227
1354
  this.onlineListener = this.handleOnline.bind(this);
1228
1355
  this.offlineListener = this.handleOffline.bind(this);
@@ -1406,6 +1533,7 @@ var AbracadabraWS = class extends EventEmitter {
1406
1533
  this.connectionAttempt = null;
1407
1534
  }
1408
1535
  checkConnection() {
1536
+ if (getLifecycleGate().backgrounded) return;
1409
1537
  if (this.status !== WebSocketStatus.Connected) return;
1410
1538
  if (!this.lastMessageReceived) return;
1411
1539
  if (this.configuration.messageReconnectTimeout >= getUnixTime() - this.lastMessageReceived) return;
@@ -1470,6 +1598,42 @@ var AbracadabraWS = class extends EventEmitter {
1470
1598
  if (this.webSocket?.readyState === WsReadyStates.Open) this.webSocket.send(message);
1471
1599
  else this.messageQueue.push(message);
1472
1600
  }
1601
+ /**
1602
+ * Re-arm this CONNECTION with a freshly minted JWT, in place.
1603
+ *
1604
+ * The server tracks a connection's expiry as one shared value
1605
+ * (`SyncSession`'s `jwt_exp`, an `Arc<AtomicI64>` every session on the socket
1606
+ * points at) and rejects every non-stateless frame once it passes — dropping
1607
+ * the whole socket for an ordinary session. `auth:refresh {"token":…}` moves
1608
+ * that value, and it rides `MSG_STATELESS` precisely because stateless is the
1609
+ * one frame kind an expired session may still send.
1610
+ *
1611
+ * So ONE frame, through any authenticated document, re-arms everything
1612
+ * multiplexed here. Sending it per attached provider would be N identical
1613
+ * frames on a shared socket carrying sixty documents; `lastRefreshToken` is
1614
+ * what keeps it at one.
1615
+ *
1616
+ * Verified against a live server with a 45-second token TTL, on an ORDINARY
1617
+ * (non-elevated) account, refreshing before the lapse so the socket is never
1618
+ * dropped and never re-handshaken: without the frame the socket is closed
1619
+ * past the original expiry, with it `close` never fires at all.
1620
+ *
1621
+ * Returns whether a frame actually went out. `false` means there was nobody
1622
+ * to send it through — harmless, because the next handshake carries the new
1623
+ * token anyway (see the provider's token closure).
1624
+ */
1625
+ refreshAuth(token) {
1626
+ if (!token || token === this.lastRefreshToken) return false;
1627
+ if (this.status !== WebSocketStatus.Connected) return false;
1628
+ const payload = `auth:refresh ${JSON.stringify({ token })}`;
1629
+ for (const provider of this.configuration.providerMap.values()) {
1630
+ if (!provider.isAuthenticated) continue;
1631
+ provider.sendStateless(payload);
1632
+ this.lastRefreshToken = token;
1633
+ return true;
1634
+ }
1635
+ return false;
1636
+ }
1473
1637
  onClose({ event }) {
1474
1638
  this.closeTries = 0;
1475
1639
  this.cleanupWebSocket();
@@ -1495,6 +1659,8 @@ var AbracadabraWS = class extends EventEmitter {
1495
1659
  }
1496
1660
  this.onlineListener = null;
1497
1661
  this.offlineListener = null;
1662
+ this.unsubscribeLifecycle?.();
1663
+ this.unsubscribeLifecycle = null;
1498
1664
  clearInterval(this.intervals.connectionChecker);
1499
1665
  this.stopConnectionAttempt();
1500
1666
  this.disconnect();
@@ -1721,19 +1887,21 @@ var MessageReceiver = class {
1721
1887
  provider.reportWriteRejected("server did not apply the update (permission or validation)", "validation");
1722
1888
  }
1723
1889
  applyAwarenessMessage(provider) {
1724
- if (!provider.awareness) return;
1890
+ const awareness = provider.peekAwareness();
1891
+ if (!awareness) return;
1725
1892
  const { message } = this;
1726
- applyAwarenessUpdate(provider.awareness, message.readVarUint8Array(), provider);
1893
+ applyAwarenessUpdate(awareness, message.readVarUint8Array(), provider);
1727
1894
  }
1728
1895
  applyAuthMessage(provider) {
1729
1896
  const { message } = this;
1730
1897
  readAuthMessage(message.decoder, provider.sendToken.bind(provider), provider.permissionDeniedHandler.bind(provider), provider.authenticatedHandler.bind(provider));
1731
1898
  }
1732
1899
  applyQueryAwarenessMessage(provider) {
1733
- if (!provider.awareness) return;
1900
+ const awareness = provider.peekAwareness();
1901
+ if (!awareness) return;
1734
1902
  const { message } = this;
1735
1903
  message.writeVarUint(MessageType.Awareness);
1736
- message.writeVarUint8Array(encodeAwarenessUpdate(provider.awareness, Array.from(provider.awareness.getStates().keys())));
1904
+ message.writeVarUint8Array(encodeAwarenessUpdate(awareness, Array.from(awareness.getStates().keys())));
1737
1905
  }
1738
1906
  };
1739
1907
 
@@ -2501,12 +2669,20 @@ var AbracadabraBaseProvider = class AbracadabraBaseProvider extends EventEmitter
2501
2669
  this.forwardDisconnect = (e) => this.emit("disconnect", e);
2502
2670
  this.forwardDestroy = () => this.emit("destroy");
2503
2671
  this.forwardRateLimited = () => this.emit("rateLimited");
2672
+ this._awarenessDeferred = false;
2673
+ this._awarenessExplicitlyNull = false;
2504
2674
  this.lastWriteRejection = null;
2505
2675
  this.writeRejectionCount = 0;
2506
2676
  this.setConfiguration(configuration);
2507
2677
  this.configuration.document = configuration.document ? configuration.document : new Y.Doc();
2508
- this.configuration.awareness = configuration.awareness !== void 0 ? configuration.awareness : new Awareness(this.document);
2509
- if (this.awareness && this.awareness.getLocalState() === null) this.awareness.setLocalState({});
2678
+ if (configuration.awareness !== void 0) {
2679
+ this.configuration.awareness = configuration.awareness;
2680
+ this._awarenessExplicitlyNull = configuration.awareness === null;
2681
+ } else if (configuration.lazyAwareness) {
2682
+ this.configuration.awareness = null;
2683
+ this._awarenessDeferred = true;
2684
+ } else this.configuration.awareness = new Awareness(this.document);
2685
+ if (!this._awarenessDeferred) this._initAwareness();
2510
2686
  this.on("open", this.configuration.onOpen);
2511
2687
  this.on("reconnected", this.configuration.onReconnected);
2512
2688
  this.on("message", this.configuration.onMessage);
@@ -2522,14 +2698,7 @@ var AbracadabraBaseProvider = class AbracadabraBaseProvider extends EventEmitter
2522
2698
  this.on("authenticationFailed", this.configuration.onAuthenticationFailed);
2523
2699
  this.on("writeRejected", this.configuration.onWriteRejected);
2524
2700
  this.on("rateLimited", this.configuration.onRateLimited);
2525
- this.awareness?.on("update", () => {
2526
- this.emit("awarenessUpdate", { states: awarenessStatesToArray(this.awareness.getStates()) });
2527
- });
2528
- this.awareness?.on("change", () => {
2529
- this.emit("awarenessChange", { states: awarenessStatesToArray(this.awareness.getStates()) });
2530
- });
2531
2701
  this.document.on("update", this.boundDocumentUpdateHandler);
2532
- this.awareness?.on("update", this.boundAwarenessUpdateHandler);
2533
2702
  this.registerEventListeners();
2534
2703
  if (this.configuration.forceSyncInterval && typeof this.configuration.forceSyncInterval === "number") this.intervals.forceSync = setInterval(this.forceSync.bind(this), this.configuration.forceSyncInterval);
2535
2704
  if (this.manageSocket) this.attach();
@@ -2550,9 +2719,68 @@ var AbracadabraBaseProvider = class AbracadabraBaseProvider extends EventEmitter
2550
2719
  get isAttached() {
2551
2720
  return this._isAttached;
2552
2721
  }
2722
+ /**
2723
+ * The presence instance for this document, built on demand.
2724
+ *
2725
+ * Reading this materializes a deferred instance (see `lazyAwareness`), which
2726
+ * is why every consumer — TipTap's CollaborationCaret, presence UI, app code
2727
+ * — keeps working unchanged: touching `.awareness` is itself the signal that
2728
+ * this document needs presence.
2729
+ *
2730
+ * Provider INTERNALS must use `peekAwareness()` instead, or the lazy path
2731
+ * materializes everything it was meant to avoid.
2732
+ */
2553
2733
  get awareness() {
2734
+ if (this._awarenessExplicitlyNull) return null;
2735
+ if (this._awarenessDeferred) this._materializeAwareness();
2554
2736
  return this.configuration.awareness;
2555
2737
  }
2738
+ /**
2739
+ * The Awareness instance if one exists, without ever creating one.
2740
+ *
2741
+ * @internal Used by provider internals and `MessageReceiver`. A deferred
2742
+ * document has no local presence, so there is nothing for an inbound
2743
+ * awareness frame to be applied to and nothing to answer a peer's query with
2744
+ * — and materializing on a peer's frame would hand every idle background
2745
+ * document a heartbeat as soon as anyone else joined the space.
2746
+ */
2747
+ peekAwareness() {
2748
+ return this._awarenessDeferred ? null : this.configuration.awareness;
2749
+ }
2750
+ /**
2751
+ * Build the deferred Awareness instance and bring it fully up to date:
2752
+ * seeded, wired, published, and caught up with the peers already present.
2753
+ */
2754
+ _materializeAwareness() {
2755
+ if (!this._awarenessDeferred) return;
2756
+ this._awarenessDeferred = false;
2757
+ this.configuration.awareness = new Awareness(this.document);
2758
+ this._initAwareness();
2759
+ if (this._isAttached) {
2760
+ this.send(AwarenessMessage, {
2761
+ awareness: this.configuration.awareness,
2762
+ clients: [this.document.clientID],
2763
+ documentName: this.configuration.name
2764
+ });
2765
+ this.send(QueryAwarenessMessage, { documentName: this.configuration.name });
2766
+ }
2767
+ }
2768
+ /**
2769
+ * Seed and wire an Awareness instance. Shared by the eager constructor path
2770
+ * and the lazy materialization path so the two cannot drift.
2771
+ */
2772
+ _initAwareness() {
2773
+ const awareness = this.configuration.awareness;
2774
+ if (!awareness) return;
2775
+ if (awareness.getLocalState() === null) awareness.setLocalState({});
2776
+ awareness.on("update", () => {
2777
+ this.emit("awarenessUpdate", { states: awarenessStatesToArray(awareness.getStates()) });
2778
+ });
2779
+ awareness.on("change", () => {
2780
+ this.emit("awarenessChange", { states: awarenessStatesToArray(awareness.getStates()) });
2781
+ });
2782
+ awareness.on("update", this.boundAwarenessUpdateHandler);
2783
+ }
2556
2784
  get hasUnsyncedChanges() {
2557
2785
  return this.unsyncedChanges > 0;
2558
2786
  }
@@ -2577,7 +2805,8 @@ var AbracadabraBaseProvider = class AbracadabraBaseProvider extends EventEmitter
2577
2805
  });
2578
2806
  }
2579
2807
  pageHide() {
2580
- if (this.awareness) removeAwarenessStates(this.awareness, [this.document.clientID], "page hide");
2808
+ const awareness = this.peekAwareness();
2809
+ if (awareness) removeAwarenessStates(awareness, [this.document.clientID], "page hide");
2581
2810
  }
2582
2811
  registerEventListeners() {
2583
2812
  if (typeof window === "undefined" || !("addEventListener" in window)) return;
@@ -2615,7 +2844,7 @@ var AbracadabraBaseProvider = class AbracadabraBaseProvider extends EventEmitter
2615
2844
  if (!this.isAuthenticated) return;
2616
2845
  const changedClients = added.concat(updated).concat(removed);
2617
2846
  this.send(AwarenessMessage, {
2618
- awareness: this.awareness,
2847
+ awareness: this.peekAwareness(),
2619
2848
  clients: changedClients,
2620
2849
  documentName: this.configuration.name
2621
2850
  });
@@ -2709,12 +2938,13 @@ var AbracadabraBaseProvider = class AbracadabraBaseProvider extends EventEmitter
2709
2938
  document: this.document,
2710
2939
  documentName: this.configuration.name
2711
2940
  });
2712
- if (this.awareness && this.awareness.getLocalState() !== null) this.send(AwarenessMessage, {
2713
- awareness: this.awareness,
2941
+ const openAwareness = this.peekAwareness();
2942
+ if (openAwareness && openAwareness.getLocalState() !== null) this.send(AwarenessMessage, {
2943
+ awareness: openAwareness,
2714
2944
  clients: [this.document.clientID],
2715
2945
  documentName: this.configuration.name
2716
2946
  });
2717
- if (this.awareness) this.send(QueryAwarenessMessage, { documentName: this.configuration.name });
2947
+ if (openAwareness) this.send(QueryAwarenessMessage, { documentName: this.configuration.name });
2718
2948
  }
2719
2949
  send(message, args) {
2720
2950
  if (!this._isAttached) return;
@@ -2737,16 +2967,18 @@ var AbracadabraBaseProvider = class AbracadabraBaseProvider extends EventEmitter
2737
2967
  this.synced = false;
2738
2968
  this._hasEverAuthenticated = false;
2739
2969
  this.clearResubscribe();
2740
- if (this.awareness) removeAwarenessStates(this.awareness, Array.from(this.awareness.getStates().keys()).filter((client) => client !== this.document.clientID), this);
2970
+ const closeAwareness = this.peekAwareness();
2971
+ if (closeAwareness) removeAwarenessStates(closeAwareness, Array.from(closeAwareness.getStates().keys()).filter((client) => client !== this.document.clientID), this);
2741
2972
  }
2742
2973
  destroy() {
2743
2974
  this.emit("destroy");
2744
2975
  if (this._rpc) this._rpc.destroy();
2745
2976
  if (this.intervals.forceSync) clearInterval(this.intervals.forceSync);
2746
- if (this.awareness) {
2747
- removeAwarenessStates(this.awareness, [this.document.clientID], "provider destroy");
2748
- this.awareness.off("update", this.boundAwarenessUpdateHandler);
2749
- this.awareness.destroy();
2977
+ const ownAwareness = this.peekAwareness();
2978
+ if (ownAwareness) {
2979
+ removeAwarenessStates(ownAwareness, [this.document.clientID], "provider destroy");
2980
+ ownAwareness.off("update", this.boundAwarenessUpdateHandler);
2981
+ ownAwareness.destroy();
2750
2982
  }
2751
2983
  this.document.off("update", this.boundDocumentUpdateHandler);
2752
2984
  this.removeAllListeners();
@@ -2892,6 +3124,34 @@ function txPromise$2(store, request) {
2892
3124
  request.onerror = () => reject(request.error);
2893
3125
  });
2894
3126
  }
3127
+ /**
3128
+ * Resolve when the whole transaction commits.
3129
+ *
3130
+ * `txPromise` waits on a single request, which is the wrong unit once a
3131
+ * transaction carries a batch: the last `add` succeeding does not mean the
3132
+ * transaction committed, and reporting durability before commit is exactly the
3133
+ * lie the offline store must not tell.
3134
+ */
3135
+ function txComplete(tx) {
3136
+ return new Promise((resolve, reject) => {
3137
+ tx.oncomplete = () => resolve();
3138
+ tx.onerror = () => reject(tx.error);
3139
+ tx.onabort = () => reject(tx.error ?? /* @__PURE__ */ new Error("transaction aborted"));
3140
+ });
3141
+ }
3142
+ /**
3143
+ * How long local edits are held before being written as one transaction.
3144
+ *
3145
+ * Yjs emits one update per keystroke, and the store used to open one IndexedDB
3146
+ * transaction for each — measured at 1.02 transactions per keystroke over 200
3147
+ * keystrokes. Coalescing trades a bounded window of durability for roughly an
3148
+ * order of magnitude fewer transactions. The window is small on purpose: these
3149
+ * edits have already gone to the server on the wire (that send is NOT batched),
3150
+ * so the exposure is an offline client that dies within the window.
3151
+ */
3152
+ const WRITE_COALESCE_MS = 150;
3153
+ /** Flush early once a burst reaches this many updates, regardless of the timer. */
3154
+ const MAX_WRITE_BATCH = 128;
2895
3155
  var OfflineStore = class {
2896
3156
  /**
2897
3157
  * @param docId The document UUID.
@@ -2906,6 +3166,9 @@ var OfflineStore = class {
2906
3166
  this.db = null;
2907
3167
  this.dbPromise = null;
2908
3168
  this._destroyed = false;
3169
+ this.writeBuffer = [];
3170
+ this.writeWaiters = [];
3171
+ this.flushTimer = null;
2909
3172
  this.storeKey = serverOrigin ? `${serverOrigin}/${docId}` : docId;
2910
3173
  }
2911
3174
  getDb() {
@@ -2916,13 +3179,91 @@ var OfflineStore = class {
2916
3179
  });
2917
3180
  return this.dbPromise;
2918
3181
  }
2919
- async persistUpdate(update) {
2920
- const db = await this.getDb();
2921
- if (!db) return;
2922
- const store = db.transaction("updates", "readwrite").objectStore("updates");
2923
- await txPromise$2(store, store.add(update));
3182
+ /**
3183
+ * Queue a local update for persistence.
3184
+ *
3185
+ * The returned promise settles when the update has actually been committed,
3186
+ * not when it was queued — so `await persistUpdate(u)` still means "on disk",
3187
+ * exactly as it did when every call opened its own transaction.
3188
+ */
3189
+ persistUpdate(update) {
3190
+ if (this._destroyed || !idbAvailable$4()) return Promise.resolve();
3191
+ this.writeBuffer.push(update);
3192
+ const settled = new Promise((resolve, reject) => {
3193
+ this.writeWaiters.push({
3194
+ resolve,
3195
+ reject
3196
+ });
3197
+ });
3198
+ if (this.writeBuffer.length >= MAX_WRITE_BATCH) this.flushWrites();
3199
+ else if (this.flushTimer === null) this.flushTimer = setTimeout(() => {
3200
+ this.flushWrites();
3201
+ }, WRITE_COALESCE_MS);
3202
+ return settled;
3203
+ }
3204
+ /**
3205
+ * Commit every buffered update as ONE transaction.
3206
+ *
3207
+ * Safe to call at any time, including with an empty buffer — every read path
3208
+ * calls it first so a caller can never observe a store that is missing writes
3209
+ * still sitting in memory.
3210
+ */
3211
+ async flushWrites() {
3212
+ if (this.flushTimer !== null) {
3213
+ clearTimeout(this.flushTimer);
3214
+ this.flushTimer = null;
3215
+ }
3216
+ const batch = this.writeBuffer;
3217
+ const waiters = this.writeWaiters;
3218
+ this.writeBuffer = [];
3219
+ this.writeWaiters = [];
3220
+ if (batch.length === 0) {
3221
+ for (const w of waiters) w.resolve();
3222
+ return;
3223
+ }
3224
+ try {
3225
+ const db = await this.getDb();
3226
+ if (db) {
3227
+ const tx = db.transaction("updates", "readwrite");
3228
+ const store = tx.objectStore("updates");
3229
+ for (const update of batch) store.add(update);
3230
+ await txComplete(tx);
3231
+ }
3232
+ for (const w of waiters) w.resolve();
3233
+ } catch (err) {
3234
+ for (const w of waiters) w.reject(err);
3235
+ throw err;
3236
+ }
3237
+ }
3238
+ /**
3239
+ * Issue the buffered writes synchronously, without awaiting them.
3240
+ *
3241
+ * For teardown paths that cannot await: `pagehide` (the page may not survive
3242
+ * a microtask) and `destroy()`. IndexedDB will not close a connection until
3243
+ * its running transactions finish, so writes issued here still land.
3244
+ */
3245
+ flushWritesSync() {
3246
+ if (this.flushTimer !== null) {
3247
+ clearTimeout(this.flushTimer);
3248
+ this.flushTimer = null;
3249
+ }
3250
+ const batch = this.writeBuffer;
3251
+ const waiters = this.writeWaiters;
3252
+ this.writeBuffer = [];
3253
+ this.writeWaiters = [];
3254
+ if (batch.length === 0) {
3255
+ for (const w of waiters) w.resolve();
3256
+ return;
3257
+ }
3258
+ const db = this.db;
3259
+ if (db) try {
3260
+ const store = db.transaction("updates", "readwrite").objectStore("updates");
3261
+ for (const update of batch) store.add(update);
3262
+ } catch {}
3263
+ for (const w of waiters) w.resolve();
2924
3264
  }
2925
3265
  async getPendingUpdates() {
3266
+ await this.flushWrites().catch(() => null);
2926
3267
  const db = await this.getDb();
2927
3268
  if (!db) return [];
2928
3269
  return new Promise((resolve, reject) => {
@@ -2932,6 +3273,13 @@ var OfflineStore = class {
2932
3273
  });
2933
3274
  }
2934
3275
  async clearPendingUpdates() {
3276
+ if (this.flushTimer !== null) {
3277
+ clearTimeout(this.flushTimer);
3278
+ this.flushTimer = null;
3279
+ }
3280
+ this.writeBuffer = [];
3281
+ for (const w of this.writeWaiters) w.resolve();
3282
+ this.writeWaiters = [];
2935
3283
  const db = await this.getDb();
2936
3284
  if (!db) return;
2937
3285
  const tx = db.transaction("updates", "readwrite");
@@ -3030,6 +3378,7 @@ var OfflineStore = class {
3030
3378
  })));
3031
3379
  }
3032
3380
  destroy() {
3381
+ this.flushWritesSync();
3033
3382
  this._destroyed = true;
3034
3383
  const db = this.db;
3035
3384
  this.db = null;
@@ -3103,7 +3452,10 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3103
3452
  if (client) {
3104
3453
  const r = resolved;
3105
3454
  if (!r.url && !r.websocketProvider) r.url = client.wsUrl;
3106
- if (resolved.token === void 0 && !configuration.cryptoIdentity) resolved.token = () => client.token ?? "";
3455
+ if (resolved.token === void 0 && !configuration.cryptoIdentity) resolved.token = async () => {
3456
+ await client.ensureFreshToken().catch(() => false);
3457
+ return client.token ?? "";
3458
+ };
3107
3459
  }
3108
3460
  super(resolved);
3109
3461
  this.effectiveRole = null;
@@ -3113,6 +3465,7 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3113
3465
  this.childAccessTimes = /* @__PURE__ */ new Map();
3114
3466
  this.pinnedChildren = /* @__PURE__ */ new Set();
3115
3467
  this.transientChildren = /* @__PURE__ */ new Set();
3468
+ this.unsubscribeToken = null;
3116
3469
  this.boundHandleYSubdocsChange = this.handleYSubdocsChange.bind(this);
3117
3470
  this.hasCachedContent = false;
3118
3471
  this._client = client;
@@ -3124,10 +3477,20 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3124
3477
  this.on("subdocRegistered", configuration.onSubdocRegistered ?? (() => null));
3125
3478
  this.on("subdocLoaded", configuration.onSubdocLoaded ?? (() => null));
3126
3479
  this.document.on("subdocs", this.boundHandleYSubdocsChange);
3480
+ this.unsubscribeToken = client?.onTokenChanged?.((token) => {
3481
+ try {
3482
+ this.configuration.websocketProvider?.refreshAuth?.(token);
3483
+ } catch {}
3484
+ }) ?? null;
3127
3485
  this.on("synced", () => this.flushPendingUpdates());
3128
3486
  this.restorePermissionSnapshot();
3129
- this.ready = Promise.race([this._initFromOfflineStore(), new Promise((resolve) => setTimeout(resolve, 5e3))]).catch((err) => {
3487
+ let readyTimer = null;
3488
+ this.ready = Promise.race([this._initFromOfflineStore(), new Promise((resolve) => {
3489
+ readyTimer = setTimeout(resolve, 5e3);
3490
+ })]).catch((err) => {
3130
3491
  this.emit("error", { message: `Offline store init failed: ${err?.message ?? err}` });
3492
+ }).finally(() => {
3493
+ if (readyTimer !== null) clearTimeout(readyTimer);
3131
3494
  });
3132
3495
  }
3133
3496
  /**
@@ -3372,6 +3735,7 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3372
3735
  document: childDoc,
3373
3736
  websocketProvider: this.configuration.websocketProvider,
3374
3737
  token: this.configuration.token,
3738
+ lazyAwareness: true,
3375
3739
  subdocLoading: this.subdocLoading,
3376
3740
  disableOfflineStore: this.abracadabraConfig.disableOfflineStore,
3377
3741
  client: this._client ?? void 0,
@@ -3450,6 +3814,19 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3450
3814
  return this.childProviders;
3451
3815
  }
3452
3816
  /**
3817
+ * Land buffered offline writes before the page goes away.
3818
+ *
3819
+ * `OfflineStore` coalesces local updates into one transaction per ~150 ms
3820
+ * window (see WRITE_COALESCE_MS). That window is the only moment an edit
3821
+ * exists in memory but not on disk, and a closing tab is exactly when it
3822
+ * would be lost — so pagehide flushes it synchronously. `super.pageHide()`
3823
+ * still clears our awareness state for peers.
3824
+ */
3825
+ pageHide() {
3826
+ super.pageHide();
3827
+ this.offlineStore?.flushWritesSync();
3828
+ }
3829
+ /**
3453
3830
  * Override to persist every local update to IndexedDB before sending it
3454
3831
  * over the wire, ensuring no work is lost during connection outages.
3455
3832
  *
@@ -3497,6 +3874,7 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3497
3874
  update,
3498
3875
  documentName: this.configuration.name
3499
3876
  });
3877
+ await this.persistSnapshot();
3500
3878
  await store.clearPendingUpdates();
3501
3879
  }
3502
3880
  const pendingSubdocs = await store.getPendingSubdocs();
@@ -3528,6 +3906,8 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3528
3906
  return this.configuration.websocketProvider.status === "connected";
3529
3907
  }
3530
3908
  destroy() {
3909
+ this.unsubscribeToken?.();
3910
+ this.unsubscribeToken = null;
3531
3911
  this.document.off("subdocs", this.boundHandleYSubdocsChange);
3532
3912
  const childIds = [...this.childProviders.keys()];
3533
3913
  for (const provider of this.childProviders.values()) provider.destroy();
@@ -10770,28 +11150,70 @@ function decodeBase64UrlToString(b64url) {
10770
11150
  const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
10771
11151
  return new TextDecoder().decode(bytes);
10772
11152
  }
11153
+ /**
11154
+ * Read a JWT's `exp` / `iat` claims, in ms. `0` for anything unreadable.
11155
+ *
11156
+ * Deliberately tolerant: a token this cannot parse is treated as expiring now,
11157
+ * which costs one extra handshake and never costs a dead session.
11158
+ */
11159
+ function readJwtTimes(token) {
11160
+ if (!token) return {
11161
+ exp: 0,
11162
+ iat: 0
11163
+ };
11164
+ const payload = token.split(".")[1];
11165
+ if (!payload) return {
11166
+ exp: 0,
11167
+ iat: 0
11168
+ };
11169
+ try {
11170
+ const claims = JSON.parse(decodeBase64UrlToString(payload));
11171
+ return {
11172
+ exp: typeof claims.exp === "number" ? claims.exp * 1e3 : 0,
11173
+ iat: typeof claims.iat === "number" ? claims.iat * 1e3 : 0
11174
+ };
11175
+ } catch {
11176
+ return {
11177
+ exp: 0,
11178
+ iat: 0
11179
+ };
11180
+ }
11181
+ }
10773
11182
  var AbracadabraClient = class {
10774
11183
  constructor(config) {
10775
11184
  this.rootListInflight = /* @__PURE__ */ new Map();
10776
11185
  this.streamTokens = /* @__PURE__ */ new Map();
10777
11186
  this.streamTokenInflight = /* @__PURE__ */ new Map();
11187
+ this._renew = null;
11188
+ this._renewing = null;
11189
+ this._renewTimer = null;
11190
+ this._tokenListeners = /* @__PURE__ */ new Set();
10778
11191
  this.baseUrl = config.url.replace(/\/+$/, "");
10779
11192
  this.persistAuth = config.persistAuth ?? typeof localStorage !== "undefined";
10780
11193
  this.storageKey = config.storageKey ?? "abracadabra:auth";
10781
11194
  this._fetch = config.fetch ?? globalThis.fetch.bind(globalThis);
10782
11195
  this.cache = config.cache ?? null;
10783
11196
  this._onAuthFailed = config.onAuthFailed ?? null;
11197
+ this.renewMarginMs = config.tokenRenewMarginMs ?? 20 * 6e4;
11198
+ this.renewCheckMs = config.tokenRenewCheckMs ?? 6e4;
10784
11199
  this._token = config.token ?? this.loadPersistedToken() ?? null;
10785
11200
  }
10786
11201
  get token() {
10787
11202
  return this._token;
10788
11203
  }
10789
11204
  set token(value) {
11205
+ const changed = value !== this._token;
10790
11206
  this._token = value;
10791
11207
  this.streamTokens.clear();
10792
11208
  this.streamTokenInflight.clear();
10793
11209
  if (this.persistAuth) if (value) this.persistToken(value);
10794
11210
  else this.clearPersistedToken();
11211
+ if (changed && value) {
11212
+ this.scheduleSessionRenewal();
11213
+ for (const listener of this._tokenListeners) try {
11214
+ listener(value);
11215
+ } catch {}
11216
+ }
10795
11217
  }
10796
11218
  get isAuthenticated() {
10797
11219
  return this._token !== null;
@@ -10807,6 +11229,117 @@ var AbracadabraClient = class {
10807
11229
  return false;
10808
11230
  }
10809
11231
  }
11232
+ /** When the current token stops validating, in ms. `0` when unknown. */
11233
+ get tokenExpiresAt() {
11234
+ return readJwtTimes(this._token).exp;
11235
+ }
11236
+ /**
11237
+ * Install the way this client re-authenticates itself, or `null` to stop.
11238
+ *
11239
+ * {@link loginWithKey} installs one for you, so a key-authenticated client
11240
+ * — every Node runner, and every browser session on a crypto identity —
11241
+ * renews without its consumer doing anything. Install one by hand for a
11242
+ * password session or any other flow that can mint a fresh token.
11243
+ *
11244
+ * The function must return the new JWT; adopting it (and notifying open
11245
+ * sockets) is this client's job.
11246
+ */
11247
+ setSessionRenewer(renew) {
11248
+ this._renew = renew;
11249
+ if (renew) this.scheduleSessionRenewal();
11250
+ else this.stopSessionRenewal();
11251
+ }
11252
+ /** Whether this client knows how to re-authenticate itself. */
11253
+ get canRenewSession() {
11254
+ return this._renew !== null;
11255
+ }
11256
+ /**
11257
+ * Called whenever the session token changes — a login, a renewal, a device
11258
+ * refresh, a key revocation. Providers use this to re-arm sockets that are
11259
+ * already open. Returns an unsubscribe function.
11260
+ */
11261
+ onTokenChanged(listener) {
11262
+ this._tokenListeners.add(listener);
11263
+ return () => this._tokenListeners.delete(listener);
11264
+ }
11265
+ /**
11266
+ * Make sure the token has life left in it, re-minting if it does not.
11267
+ *
11268
+ * Cheap when the token is fresh — one subtraction — so callers need not
11269
+ * reason about when the last renewal was, and concurrent callers share one
11270
+ * handshake. Returns whether the session is believed good; `false` is not
11271
+ * fatal, and the caller's own failure is still the authority.
11272
+ */
11273
+ async ensureFreshToken(marginMs) {
11274
+ if (!this._renew) return this.isTokenValid();
11275
+ if (this._renewing) return this._renewing;
11276
+ const { exp } = readJwtTimes(this._token);
11277
+ if (exp > 0 && exp - Date.now() > this.renewMargin(marginMs)) return true;
11278
+ const mint = this._renew;
11279
+ const renew = (async () => {
11280
+ try {
11281
+ const token = await mint();
11282
+ if (token && token !== this._token) this.token = token;
11283
+ return true;
11284
+ } catch {
11285
+ return false;
11286
+ } finally {
11287
+ this._renewing = null;
11288
+ }
11289
+ })();
11290
+ this._renewing = renew;
11291
+ return renew;
11292
+ }
11293
+ /**
11294
+ * How long before `exp` this session is re-minted.
11295
+ *
11296
+ * Capped at a third of the token's own lifetime, so a server configured
11297
+ * with short-lived tokens is not re-authenticated on every check — without
11298
+ * the cap a 45-second token against a 20-minute margin would mint a new
11299
+ * session every time anything asked.
11300
+ */
11301
+ renewMargin(marginMs) {
11302
+ const { exp, iat } = readJwtTimes(this._token);
11303
+ const lifetime = exp > iat && iat > 0 ? exp - iat : Number.POSITIVE_INFINITY;
11304
+ return Math.min(marginMs ?? this.renewMarginMs, lifetime / 3);
11305
+ }
11306
+ /**
11307
+ * Arm a single timer for the moment this token needs replacing.
11308
+ *
11309
+ * Scheduled from the token's OWN expiry rather than on a fixed interval,
11310
+ * and that is not tidiness. A poll can outrun the margin: measured against
11311
+ * a server issuing 45-second tokens, a 60-second poll first fired fifteen
11312
+ * seconds AFTER the token had already lapsed — long enough for the
11313
+ * awareness heartbeat to hit an expired session and have the socket dropped
11314
+ * under it. A deadline cannot be outrun by the thing it is a deadline for.
11315
+ *
11316
+ * Re-armed on every token change, so a renewal schedules the next one.
11317
+ */
11318
+ scheduleSessionRenewal() {
11319
+ this.stopSessionRenewal();
11320
+ if (!this._renew || this.renewCheckMs <= 0) return;
11321
+ const { exp } = readJwtTimes(this._token);
11322
+ const delay = exp > 0 ? Math.max(1e3, exp - Date.now() - this.renewMargin()) : this.renewCheckMs;
11323
+ this._renewTimer = setTimeout(() => {
11324
+ this.ensureFreshToken().catch(() => false).finally(() => this.scheduleSessionRenewal());
11325
+ }, Math.min(delay, 720 * 6e4));
11326
+ this._renewTimer.unref?.();
11327
+ }
11328
+ stopSessionRenewal() {
11329
+ if (!this._renewTimer) return;
11330
+ clearTimeout(this._renewTimer);
11331
+ this._renewTimer = null;
11332
+ }
11333
+ /**
11334
+ * Stop renewing and drop every listener. Call when a client is discarded —
11335
+ * a long-lived consumer that builds one client per connection would
11336
+ * otherwise leave a timer per discarded client.
11337
+ */
11338
+ destroy() {
11339
+ this.stopSessionRenewal();
11340
+ this._renew = null;
11341
+ this._tokenListeners.clear();
11342
+ }
10810
11343
  /** Derives ws:// or wss:// URL from the http(s) base URL. */
10811
11344
  get wsUrl() {
10812
11345
  return this.baseUrl.replace(/^https:\/\//, "wss://").replace(/^http:\/\//, "ws://") + "/ws";
@@ -10869,11 +11402,13 @@ var AbracadabraClient = class {
10869
11402
  async loginWithKey(publicKey, signChallenge) {
10870
11403
  const { challenge } = await this.challenge(publicKey);
10871
11404
  const signature = await signChallenge(challenge);
10872
- return this.verify({
11405
+ const token = await this.verify({
10873
11406
  publicKey,
10874
11407
  signature,
10875
11408
  challenge
10876
11409
  });
11410
+ this.setSessionRenewer(() => this.loginWithKey(publicKey, signChallenge));
11411
+ return token;
10877
11412
  }
10878
11413
  /** Add a new Ed25519 public key to the current user (multi-device). */
10879
11414
  async addKey(opts) {
@@ -17221,10 +17756,24 @@ var BackgroundSyncManager = class extends EventEmitter {
17221
17756
  * @returns Cleanup function to stop the periodic sync.
17222
17757
  */
17223
17758
  startPeriodicSync(intervalMs = 300 * 1e3) {
17759
+ let missedWhileHidden = false;
17224
17760
  const handle = setInterval(() => {
17225
- if (!this._destroyed) this.syncAll().catch(() => null);
17761
+ if (this._destroyed) return;
17762
+ if (getLifecycleGate().backgrounded) {
17763
+ missedWhileHidden = true;
17764
+ return;
17765
+ }
17766
+ this.syncAll().catch(() => null);
17226
17767
  }, intervalMs);
17227
- return () => clearInterval(handle);
17768
+ const unsubscribe = getLifecycleGate().onChange((backgrounded) => {
17769
+ if (backgrounded || !missedWhileHidden || this._destroyed) return;
17770
+ missedWhileHidden = false;
17771
+ this.syncAll().catch(() => null);
17772
+ });
17773
+ return () => {
17774
+ clearInterval(handle);
17775
+ unsubscribe();
17776
+ };
17228
17777
  }
17229
17778
  /**
17230
17779
  * Clear all offline document data and sync state.
@@ -22229,5 +22778,339 @@ var DocumentManager = class {
22229
22778
  };
22230
22779
 
22231
22780
  //#endregion
22232
- export { AbracadabraBaseProvider, AbracadabraClient, AbracadabraProvider, AbracadabraWS, AbracadabraWebRTC, AuthMessageType, AwarenessError, BackgroundSyncManager, BackgroundSyncPersistence, BroadcastChannelSync, CHANNEL_NAMES, ChannelKeyResolver, ChatClient, ConnectionTimeout, ContentManager, CryptoIdentityKeystore, DEFAULT_FILE_CHUNK_SIZE, DEFAULT_ICE_SERVERS, DataChannelRouter, DevicePairingChannel, DeviceRegistrationService, DocKeyManager, DocumentCache, DocumentManager, E2EAbracadabraProvider, E2EEChannel, E2EOfflineStore, EncryptedChatClient, EncryptedYMap, EncryptedYText, FileBlobStore, FileTransferChannel, FileTransferHandle, Forbidden, GEO_TYPE_META_SCHEMAS, HocuspocusProvider, HocuspocusProviderWebsocket, IdentityDocProvider, KEY_EXCHANGE_CHANNEL, Kind, LocalStorageDeviceSessionStorage, ManualSignaling, MessageTooBig, MessageType, MetaManager, MetaValidationError, NotificationsClient, OfflineStore, PAGE_TYPES, PeerConnection, QUERY_PREFIX, QueryClient, QueryError, RPC_PREFIX, ResetConnection, RpcClient, RpcError, SERVER_ROOT_ID, SearchIndex, SignalingSocket, SubdocMessage, TYPE_ALIASES, TokenManager, TreeManager, TypedDocTypeMismatchError, Unauthorized, WebSocketStatus, WsReadyStates, YjsDataChannel, addServer, attachUpdatedAtObserver, awarenessStatesToArray, wordlist as bip39Wordlist, buildBlockquoteElement, buildBlocksFromMarkdown, buildBulletListElement, buildCodeBlockElement, buildHeadingElement, buildHorizontalRuleElement, buildOrderedListElement, buildParagraphElement, buildTaskListElement, collectMediaFileBlocks, decryptChatContent, decryptField, defaultKeyFileFor, deriveDmDocId, deriveIdentityDocId, deriveSeedWrappingKey, deterministicKeypair, dropCachesIfServerReplaced, encryptChatContent, encryptField, filenameToLabel, foldRecords, forgetServerIdentity, generateMnemonic, isEncryptedContent, isPlaceholderLabel, isServerScopedStore, loadOrCreateKeyFile, loadServerRegistry, loginOrRegisterWithKey, loginOrRegisterWithPolicy, makeChallengeSigner, makeEncryptedYMap, makeEncryptedYText, makeEntryMap, migrateLegacyDefault, mnemonicToEd25519Seed, mnemonicToKeyPair, normalizeRootId, openSyncedProvider, parseFrontmatter, patchEntry, pickEntrySpace, populateYDocFromMarkdown, readAuthMessage, readBlocksFromFragment, readEntries, reconcileDocCover, recordFromYAny, removeServer, resolvePageType, resolveServer, saveServerRegistry, serverRegistryPath, setDefault, signChallengeWithSeed, toPlain, unwrapSeed, validateMnemonic, waitForSync, withTimeout, wrapSeed, writeAuthenticated, writeAuthentication, writePermissionDenied, writeTokenSyncRequest, yjsToMarkdown };
22781
+ //#region packages/provider/src/PerfCounters.ts
22782
+ let installed = false;
22783
+ let startedAt = 0;
22784
+ const liveTimers = /* @__PURE__ */ new Map();
22785
+ const groupCreated = /* @__PURE__ */ new Map();
22786
+ const groupFired = /* @__PURE__ */ new Map();
22787
+ let intervalsCreated = 0;
22788
+ let timeoutsCreated = 0;
22789
+ let timersFired = 0;
22790
+ let rafRequested = 0;
22791
+ let rafFired = 0;
22792
+ let idbTransactions = 0;
22793
+ let idbDatabasesOpened = 0;
22794
+ const idbByStore = /* @__PURE__ */ new Map();
22795
+ let framesSent = 0;
22796
+ let bytesSent = 0;
22797
+ let framesReceived = 0;
22798
+ let bytesReceived = 0;
22799
+ const sentByType = /* @__PURE__ */ new Map();
22800
+ let origSetInterval = null;
22801
+ let origClearInterval = null;
22802
+ let origSetTimeout = null;
22803
+ let origClearTimeout = null;
22804
+ let origRaf = null;
22805
+ let origIdbTransaction = null;
22806
+ let origIdbOpen = null;
22807
+ const socketRestores = [];
22808
+ /** The heartbeat every y-protocols Awareness instance starts: outdatedTimeout / 10. */
22809
+ const AWARENESS_HEARTBEAT_MS = 3e3;
22810
+ /**
22811
+ * Best-effort "who created this timer". Walks the stack past this module and
22812
+ * past the Node/browser internals, and reports the first frame that looks like
22813
+ * real code. Deliberately coarse: a file name is enough to tell an Awareness
22814
+ * heartbeat apart from a reconnect backoff, and anything finer would be noise.
22815
+ */
22816
+ function captureOrigin() {
22817
+ const stack = (/* @__PURE__ */ new Error()).stack;
22818
+ if (!stack) return "unknown";
22819
+ const lines = stack.split("\n").slice(1);
22820
+ for (const line of lines) {
22821
+ if (line.includes("PerfCounters")) continue;
22822
+ if (line.includes("node:internal")) continue;
22823
+ const nm = line.match(/node_modules\/(?:\.pnpm\/[^/]+\/node_modules\/)?(.+?):\d+:\d+/);
22824
+ if (nm?.[1]) return nm[1];
22825
+ const src = line.match(/([^/\\()]+\.(?:ts|mts|js|mjs)):\d+:\d+/);
22826
+ if (src?.[1]) return src[1];
22827
+ }
22828
+ return "unknown";
22829
+ }
22830
+ function groupKey(origin, delayMs) {
22831
+ return `${origin}@${delayMs}`;
22832
+ }
22833
+ function bump(map, key, by = 1) {
22834
+ map.set(key, (map.get(key) ?? 0) + by);
22835
+ }
22836
+ /**
22837
+ * Begin counting. Idempotent — a second call is a no-op rather than a
22838
+ * double-wrap, which would double every number and be very hard to notice.
22839
+ */
22840
+ function installPerfCounters() {
22841
+ if (installed) return;
22842
+ installed = true;
22843
+ startedAt = Date.now();
22844
+ const g = globalThis;
22845
+ origSetInterval = g.setInterval;
22846
+ origClearInterval = g.clearInterval;
22847
+ origSetTimeout = g.setTimeout;
22848
+ origClearTimeout = g.clearTimeout;
22849
+ g.setInterval = function patchedSetInterval(handler, delay, ...args) {
22850
+ const origin = captureOrigin();
22851
+ const delayMs = delay ?? 0;
22852
+ const key = groupKey(origin, delayMs);
22853
+ const wrapped = typeof handler === "function" ? (...cbArgs) => {
22854
+ timersFired++;
22855
+ bump(groupFired, key);
22856
+ return handler(...cbArgs);
22857
+ } : handler;
22858
+ const id = origSetInterval.call(g, wrapped, delay, ...args);
22859
+ intervalsCreated++;
22860
+ bump(groupCreated, key);
22861
+ liveTimers.set(id, {
22862
+ origin,
22863
+ delayMs,
22864
+ kind: "interval"
22865
+ });
22866
+ return id;
22867
+ };
22868
+ g.clearInterval = function patchedClearInterval(id) {
22869
+ liveTimers.delete(id);
22870
+ return origClearInterval.call(g, id);
22871
+ };
22872
+ g.setTimeout = function patchedSetTimeout(handler, delay, ...args) {
22873
+ const origin = captureOrigin();
22874
+ const delayMs = delay ?? 0;
22875
+ const key = groupKey(origin, delayMs);
22876
+ let id;
22877
+ const wrapped = typeof handler === "function" ? (...cbArgs) => {
22878
+ timersFired++;
22879
+ bump(groupFired, key);
22880
+ liveTimers.delete(id);
22881
+ return handler(...cbArgs);
22882
+ } : handler;
22883
+ id = origSetTimeout.call(g, wrapped, delay, ...args);
22884
+ timeoutsCreated++;
22885
+ bump(groupCreated, key);
22886
+ liveTimers.set(id, {
22887
+ origin,
22888
+ delayMs,
22889
+ kind: "timeout"
22890
+ });
22891
+ return id;
22892
+ };
22893
+ g.clearTimeout = function patchedClearTimeout(id) {
22894
+ liveTimers.delete(id);
22895
+ return origClearTimeout.call(g, id);
22896
+ };
22897
+ if (typeof g.requestAnimationFrame === "function") {
22898
+ origRaf = g.requestAnimationFrame;
22899
+ g.requestAnimationFrame = function patchedRaf(cb) {
22900
+ rafRequested++;
22901
+ return origRaf.call(g, (t) => {
22902
+ rafFired++;
22903
+ return cb(t);
22904
+ });
22905
+ };
22906
+ }
22907
+ if (typeof g.IDBDatabase === "function") {
22908
+ origIdbTransaction = g.IDBDatabase.prototype.transaction;
22909
+ g.IDBDatabase.prototype.transaction = function patchedTransaction(storeNames, ...rest) {
22910
+ idbTransactions++;
22911
+ const names = Array.isArray(storeNames) ? storeNames : [storeNames];
22912
+ for (const n of names) bump(idbByStore, String(n));
22913
+ return origIdbTransaction.call(this, storeNames, ...rest);
22914
+ };
22915
+ }
22916
+ if (g.indexedDB && typeof g.indexedDB.open === "function") {
22917
+ origIdbOpen = g.indexedDB.open.bind(g.indexedDB);
22918
+ g.indexedDB.open = function patchedOpen(...args) {
22919
+ idbDatabasesOpened++;
22920
+ return origIdbOpen(...args);
22921
+ };
22922
+ }
22923
+ }
22924
+ /** Restore every patched global. Safe to call when not installed. */
22925
+ function uninstall() {
22926
+ if (!installed) return;
22927
+ const g = globalThis;
22928
+ if (origSetInterval) g.setInterval = origSetInterval;
22929
+ if (origClearInterval) g.clearInterval = origClearInterval;
22930
+ if (origSetTimeout) g.setTimeout = origSetTimeout;
22931
+ if (origClearTimeout) g.clearTimeout = origClearTimeout;
22932
+ if (origRaf) g.requestAnimationFrame = origRaf;
22933
+ if (origIdbTransaction && typeof g.IDBDatabase === "function") g.IDBDatabase.prototype.transaction = origIdbTransaction;
22934
+ if (origIdbOpen && g.indexedDB) g.indexedDB.open = origIdbOpen;
22935
+ for (const restore of socketRestores.splice(0)) restore();
22936
+ origSetInterval = null;
22937
+ origClearInterval = null;
22938
+ origSetTimeout = null;
22939
+ origClearTimeout = null;
22940
+ origRaf = null;
22941
+ origIdbTransaction = null;
22942
+ origIdbOpen = null;
22943
+ installed = false;
22944
+ reset();
22945
+ }
22946
+ /** Zero every counter. Live-timer bookkeeping is preserved — it is a census. */
22947
+ function reset() {
22948
+ startedAt = Date.now();
22949
+ groupCreated.clear();
22950
+ groupFired.clear();
22951
+ intervalsCreated = 0;
22952
+ timeoutsCreated = 0;
22953
+ timersFired = 0;
22954
+ rafRequested = 0;
22955
+ rafFired = 0;
22956
+ idbTransactions = 0;
22957
+ idbDatabasesOpened = 0;
22958
+ idbByStore.clear();
22959
+ framesSent = 0;
22960
+ bytesSent = 0;
22961
+ framesReceived = 0;
22962
+ bytesReceived = 0;
22963
+ sentByType.clear();
22964
+ }
22965
+ /**
22966
+ * Count frames on one AbracadabraWS. Returns a restore function; the restore is
22967
+ * also run by `uninstall()`.
22968
+ *
22969
+ * Wrapping the instance (rather than a global) is deliberate: in Node the
22970
+ * provider runs on the `ws` package, so patching `globalThis.WebSocket` would
22971
+ * silently measure nothing at all.
22972
+ */
22973
+ function instrumentSocket(socket) {
22974
+ const originalSend = socket.send.bind(socket);
22975
+ socket.send = (message) => {
22976
+ framesSent++;
22977
+ const bytes = byteLength(message);
22978
+ bytesSent += bytes;
22979
+ const type = readMessageType(message);
22980
+ if (type !== null) bump(sentByType, type);
22981
+ return originalSend(message);
22982
+ };
22983
+ const onMessage = (payload) => {
22984
+ framesReceived++;
22985
+ bytesReceived += byteLength(payload?.event?.data ?? payload?.data ?? payload);
22986
+ };
22987
+ socket.on("message", onMessage);
22988
+ const restore = () => {
22989
+ socket.send = originalSend;
22990
+ try {
22991
+ socket.off("message", onMessage);
22992
+ } catch {}
22993
+ };
22994
+ socketRestores.push(restore);
22995
+ return restore;
22996
+ }
22997
+ function byteLength(value) {
22998
+ if (!value) return 0;
22999
+ if (value instanceof Uint8Array) return value.byteLength;
23000
+ if (value instanceof ArrayBuffer) return value.byteLength;
23001
+ if (typeof value === "string") return value.length;
23002
+ const encoded = value?.toUint8Array?.() ?? value?.message;
23003
+ if (encoded instanceof Uint8Array) return encoded.byteLength;
23004
+ return 0;
23005
+ }
23006
+ /**
23007
+ * The Hocuspocus V2 frame puts a varstring document name first, then the
23008
+ * message type. We only need a stable label, so report the type byte as-is
23009
+ * rather than duplicating the wire decoder here.
23010
+ */
23011
+ function readMessageType(message) {
23012
+ const encoded = message?.toUint8Array?.() ?? message?.message ?? (message instanceof Uint8Array ? message : null);
23013
+ if (!(encoded instanceof Uint8Array) || encoded.length === 0) return null;
23014
+ let offset = 0;
23015
+ let nameLen = 0;
23016
+ let shift = 0;
23017
+ while (offset < encoded.length) {
23018
+ const byte = encoded[offset++];
23019
+ nameLen |= (byte & 127) << shift;
23020
+ if ((byte & 128) === 0) break;
23021
+ shift += 7;
23022
+ }
23023
+ const typeIndex = offset + nameLen;
23024
+ if (typeIndex >= encoded.length) return null;
23025
+ return `type:${encoded[typeIndex]}`;
23026
+ }
23027
+ function snapshot() {
23028
+ const elapsedMs = Math.max(1, Date.now() - startedAt);
23029
+ const liveByKey = /* @__PURE__ */ new Map();
23030
+ let intervalsLive = 0;
23031
+ let timeoutsLive = 0;
23032
+ let awarenessLive = 0;
23033
+ for (const rec of liveTimers.values()) {
23034
+ bump(liveByKey, groupKey(rec.origin, rec.delayMs));
23035
+ if (rec.kind === "interval") {
23036
+ intervalsLive++;
23037
+ if (isAwarenessHeartbeat(rec)) awarenessLive++;
23038
+ } else timeoutsLive++;
23039
+ }
23040
+ const groups = [...new Set([
23041
+ ...groupCreated.keys(),
23042
+ ...groupFired.keys(),
23043
+ ...liveByKey.keys()
23044
+ ])].map((key) => {
23045
+ const at = key.lastIndexOf("@");
23046
+ return {
23047
+ origin: key.slice(0, at),
23048
+ delayMs: Number(key.slice(at + 1)),
23049
+ created: groupCreated.get(key) ?? 0,
23050
+ live: liveByKey.get(key) ?? 0,
23051
+ fired: groupFired.get(key) ?? 0
23052
+ };
23053
+ }).sort((a, b) => b.live - a.live || b.fired - a.fired);
23054
+ let heartbeatFires = 0;
23055
+ for (const group of groups) if (group.delayMs === AWARENESS_HEARTBEAT_MS && isAwarenessOrigin(group.origin)) heartbeatFires += group.fired;
23056
+ return {
23057
+ elapsedMs,
23058
+ timers: {
23059
+ intervalsCreated,
23060
+ intervalsLive,
23061
+ timeoutsCreated,
23062
+ timeoutsLive,
23063
+ fired: timersFired,
23064
+ firedPerSecond: Number((timersFired / elapsedMs * 1e3).toFixed(2)),
23065
+ groups
23066
+ },
23067
+ animationFrames: {
23068
+ requested: rafRequested,
23069
+ fired: rafFired
23070
+ },
23071
+ awareness: {
23072
+ liveInstances: awarenessLive,
23073
+ heartbeatFires
23074
+ },
23075
+ indexedDb: {
23076
+ transactions: idbTransactions,
23077
+ byStore: Object.fromEntries(idbByStore),
23078
+ databasesOpened: idbDatabasesOpened
23079
+ },
23080
+ sockets: {
23081
+ framesSent,
23082
+ bytesSent,
23083
+ framesReceived,
23084
+ bytesReceived,
23085
+ sentByType: Object.fromEntries(sentByType)
23086
+ }
23087
+ };
23088
+ }
23089
+ function isAwarenessOrigin(origin) {
23090
+ return origin.includes("awareness");
23091
+ }
23092
+ function isAwarenessHeartbeat(rec) {
23093
+ return rec.delayMs === AWARENESS_HEARTBEAT_MS && isAwarenessOrigin(rec.origin);
23094
+ }
23095
+ /** Field-by-field difference of two snapshots, for before/after comparisons. */
23096
+ function diff(before, after) {
23097
+ return {
23098
+ elapsedMs: after.elapsedMs - before.elapsedMs,
23099
+ timersFired: after.timers.fired - before.timers.fired,
23100
+ intervalsCreated: after.timers.intervalsCreated - before.timers.intervalsCreated,
23101
+ intervalsLive: after.timers.intervalsLive - before.timers.intervalsLive,
23102
+ awarenessLive: after.awareness.liveInstances - before.awareness.liveInstances,
23103
+ heartbeatFires: after.awareness.heartbeatFires - before.awareness.heartbeatFires,
23104
+ framesSent: after.sockets.framesSent - before.sockets.framesSent,
23105
+ bytesSent: after.sockets.bytesSent - before.sockets.bytesSent,
23106
+ idbTransactions: after.indexedDb.transactions - before.indexedDb.transactions
23107
+ };
23108
+ }
23109
+ /** Whether counting is currently active. */
23110
+ function isInstalled() {
23111
+ return installed;
23112
+ }
23113
+
23114
+ //#endregion
23115
+ export { AbracadabraBaseProvider, AbracadabraClient, AbracadabraProvider, AbracadabraWS, AbracadabraWebRTC, AuthMessageType, AwarenessError, BackgroundSyncManager, BackgroundSyncPersistence, BroadcastChannelSync, CHANNEL_NAMES, ChannelKeyResolver, ChatClient, ConnectionTimeout, ContentManager, CryptoIdentityKeystore, DEFAULT_FILE_CHUNK_SIZE, DEFAULT_ICE_SERVERS, DataChannelRouter, DevicePairingChannel, DeviceRegistrationService, DocKeyManager, DocumentCache, DocumentManager, E2EAbracadabraProvider, E2EEChannel, E2EOfflineStore, EncryptedChatClient, EncryptedYMap, EncryptedYText, FileBlobStore, FileTransferChannel, FileTransferHandle, Forbidden, GEO_TYPE_META_SCHEMAS, HIDE_GRACE_MS, HocuspocusProvider, HocuspocusProviderWebsocket, IdentityDocProvider, KEY_EXCHANGE_CHANNEL, Kind, LifecycleGate, LocalStorageDeviceSessionStorage, ManualSignaling, ManualVisibilitySource, MessageTooBig, MessageType, MetaManager, MetaValidationError, NotificationsClient, OfflineStore, PAGE_TYPES, PeerConnection, QUERY_PREFIX, QueryClient, QueryError, RPC_PREFIX, ResetConnection, RpcClient, RpcError, SERVER_ROOT_ID, SearchIndex, SignalingSocket, SubdocMessage, TYPE_ALIASES, TokenManager, TreeManager, TypedDocTypeMismatchError, Unauthorized, WebSocketStatus, WsReadyStates, YjsDataChannel, addServer, attachUpdatedAtObserver, awarenessStatesToArray, wordlist as bip39Wordlist, buildBlockquoteElement, buildBlocksFromMarkdown, buildBulletListElement, buildCodeBlockElement, buildHeadingElement, buildHorizontalRuleElement, buildOrderedListElement, buildParagraphElement, buildTaskListElement, collectMediaFileBlocks, decryptChatContent, decryptField, defaultKeyFileFor, deriveDmDocId, deriveIdentityDocId, deriveSeedWrappingKey, deterministicKeypair, dropCachesIfServerReplaced, encryptChatContent, encryptField, filenameToLabel, foldRecords, forgetServerIdentity, generateMnemonic, getLifecycleGate, installPerfCounters, isEncryptedContent, isPlaceholderLabel, isServerScopedStore, loadOrCreateKeyFile, loadServerRegistry, loginOrRegisterWithKey, loginOrRegisterWithPolicy, makeChallengeSigner, makeEncryptedYMap, makeEncryptedYText, makeEntryMap, migrateLegacyDefault, mnemonicToEd25519Seed, mnemonicToKeyPair, normalizeRootId, openSyncedProvider, parseFrontmatter, patchEntry, isInstalled as perfCountersInstalled, diff as perfDiff, instrumentSocket as perfInstrumentSocket, snapshot as perfSnapshot, pickEntrySpace, populateYDocFromMarkdown, readAuthMessage, readBlocksFromFragment, readEntries, reconcileDocCover, recordFromYAny, removeServer, reset as resetPerfCounters, resolvePageType, resolveServer, saveServerRegistry, serverRegistryPath, setDefault, setLifecycleGate, signChallengeWithSeed, toPlain, uninstall as uninstallPerfCounters, unwrapSeed, validateMnemonic, waitForSync, withTimeout, wrapSeed, writeAuthenticated, writeAuthentication, writePermissionDenied, writeTokenSyncRequest, yjsToMarkdown };
22233
23116
  //# sourceMappingURL=abracadabra-provider.esm.js.map