@lunora/client 1.0.0-alpha.276 → 1.0.0-alpha.277

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.
@@ -306,6 +306,8 @@ interface OutboxSink {
306
306
  * needed to render offline on reload and to resume the live subscription.
307
307
  */
308
308
  interface CachedQuery {
309
+ /** Fingerprint of the claims the value was read under (see `SubscriptionState.serverClaims`), replayed as `sinceClaims`. */
310
+ claims?: string;
309
311
  /**
310
312
  * Token-hash fingerprint of the bearer the value was cached under, when the
311
313
  * entry was written by the identity the client currently advertises.
@@ -663,6 +665,7 @@ interface ClientSubscribeMessage {
663
665
  query: {
664
666
  args?: Record<string, unknown>;
665
667
  functionPath?: string;
668
+ sinceClaims?: string;
666
669
  sinceEpoch?: string;
667
670
  sinceSeq?: number;
668
671
  table?: string;
@@ -725,6 +728,8 @@ interface ClientShapeSubscribeMessage {
725
728
  * delta.
726
729
  */
727
730
  sinceCheckpoint?: number;
731
+ /** The claims fingerprint {@link ClientShapeSubscribeMessage.sinceCheckpoint} was read under; absent resumes cold. */
732
+ sinceClaims?: string;
728
733
  /**
729
734
  * The CDC epoch {@link ClientShapeSubscribeMessage.sinceCheckpoint} belongs
730
735
  * to. A mismatch (forked changelog timeline) forces a full re-seed even when
@@ -939,7 +944,18 @@ interface ServerLiveMessage {
939
944
  * before it posts a grant, and posts at once when the flag is absent.
940
945
  */
941
946
  interface ServerIdentityMessage {
947
+ /**
948
+ * Fingerprint of the verified claims the socket is authenticated with. Opaque to the client, which only
949
+ * hands it back as `sinceClaims` when it resubscribes from a cursor read under these claims.
950
+ */
951
+ claims?: string;
942
952
  connectionId?: string;
953
+ /**
954
+ * Milliseconds within which the socket must be re-authenticated through
955
+ * `POST /_lunora/ws/reauth`, or the server closes it with `4005`. Present only
956
+ * for an authenticated subscription socket.
957
+ */
958
+ revalidateMs?: number;
943
959
  subject: null | string;
944
960
  type: "identity";
945
961
  whisperAck?: boolean;
@@ -1497,6 +1513,12 @@ interface SubscriptionState {
1497
1513
  * persists this, never the optimistic overlay.
1498
1514
  */
1499
1515
  serverBase: unknown;
1516
+ /**
1517
+ * Fingerprint of the claims the value and cursor were read under, as the shard announced it; replayed
1518
+ * as `sinceClaims` so the server resumes only when the socket's claims are still those. Absent when the
1519
+ * shard announced none, which the server treats as a mismatch (a full snapshot).
1520
+ */
1521
+ serverClaims?: string;
1500
1522
  /**
1501
1523
  * The `__cdc_log` high-watermark (`cursor`) the `lastValue` reflects,
1502
1524
  * captured from the last `data`/`delta`/`resume` frame. Persisted to the
@@ -2044,6 +2066,23 @@ declare class LunoraClient {
2044
2066
  private readonly pollingFallbackAfterFailedAttempts;
2045
2067
  /** Polling-fallback cadence (ms); `0` disables it. See {@link LunoraClientOptions.pollingFallback}. */
2046
2068
  private readonly pollingFallbackIntervalMs;
2069
+ /** This tab's own claims fingerprint, fetched from the worker; `undefined` until known and again after any credential change, `null` once the server is known to announce none. */
2070
+ private ownClaimsValue;
2071
+ /** Frames a follower held for want of `ownClaimsValue`, one per subscription, applied once it is known. */
2072
+ private readonly heldLeaderFrames;
2073
+ private ownClaimsFetch;
2074
+ /** Leader fingerprints this tab already re-verified its own against, so a tab that truly differs asks once, not per frame. */
2075
+ private readonly claimsVerifiedAgainst;
2076
+ /** The claims request failed while frames were held: its retry timer and how many have failed in a row. */
2077
+ private ownClaimsRetryTimer;
2078
+ private ownClaimsFailures;
2079
+ /** What a reset hid from a follower's subscriptions, put back if the answer shows the same claims. */
2080
+ private readonly suspendedFollowerValues;
2081
+ /**
2082
+ * The claims fingerprint of the socket whose `data`, `delta`, `resume` or poke frame is being applied, set only
2083
+ * for the synchronous span of that handler. A value and its cursor are stamped with it as they are committed.
2084
+ */
2085
+ private frameClaims;
2047
2086
  /** See {@link LunoraClientOptions.authTokenOnUpgrade}. */
2048
2087
  private readonly authTokenOnUpgrade;
2049
2088
  private readonly offlineQueue;
@@ -2120,6 +2159,13 @@ declare class LunoraClient {
2120
2159
  private outboxLeaderRelease;
2121
2160
  /** Durable read cache (Pillar 2); `undefined` when `queryCache` is omitted or `false`. */
2122
2161
  private readonly queryCache;
2162
+ /**
2163
+ * Counts the clears of the read cache. A load or a write batch begun before a clear belongs to the identity
2164
+ * the clear retired, so it is dropped when its epoch no longer matches.
2165
+ */
2166
+ private queryCacheEpoch;
2167
+ /** Durable cache writes and clears, run in order so a clear cannot finish over a later write. */
2168
+ private queryCacheChain;
2123
2169
  /**
2124
2170
  * Values restored from the `queryCache` at construction, keyed by the
2125
2171
  * read-cache key, awaiting the `subscribe()` that will consume them. A
@@ -4053,6 +4099,27 @@ declare class LunoraClient {
4053
4099
  * by a poll, which carries no cursor: see {@link pollSubscriptions}.
4054
4100
  */
4055
4101
  private handleDataMessage;
4102
+ private followerClaims;
4103
+ private isFollowerTab;
4104
+ /** Forget this tab's own fingerprint: the credential it described may have changed. */
4105
+ private resetOwnClaims;
4106
+ /**
4107
+ * A follower's claims-stamped values were read under claims this tab may no longer hold. They are taken off the
4108
+ * views and the caches until the tab knows its own fingerprint again; {@link applyOwnClaims} puts back those that
4109
+ * were read under the claims it finds, so a plain token refresh does not leave the tab blank.
4110
+ */
4111
+ private suspendFollowerValues;
4112
+ /** Take `claims` as this tab's own: drop what a leader committed under others, from memory and the restored cache, and run the held frames. */
4113
+ private applyOwnClaims;
4114
+ private releaseHeldFrames;
4115
+ /** Remove what was read under claims other than `claims` from every cache a subscription could be seeded from. */
4116
+ private dropClaimedEntries;
4117
+ private fetchOwnClaims;
4118
+ /** Ask for the tab's claims again, with a growing delay and a bound, for as long as frames wait on the answer. */
4119
+ private scheduleOwnClaimsRetry;
4120
+ private stopOwnClaimsRetry;
4121
+ /** Run `apply` with the claims fingerprint of the socket that delivered the frame, for the values and cursors it commits. */
4122
+ private withFrameClaims;
4056
4123
  /**
4057
4124
  * Handle a `resume` frame (Pillar 1b): the server proved nothing the
4058
4125
  * subscription reads changed since our `sinceSeq`, so the cached value is
@@ -4537,6 +4604,25 @@ declare class LunoraClient {
4537
4604
  * bearer on the upgrade, so they are always bounced.
4538
4605
  */
4539
4606
  private bounceShardSockets;
4607
+ /**
4608
+ * The same user resolved under different claims. The identity fingerprint names the user, not the claims, so the
4609
+ * read cache's own gate would accept what was read under the old ones: drop it (hydrated, pending and durable) as
4610
+ * well as the views, so nothing read under the old claims is shown or resumed from. Queued offline mutations are
4611
+ * kept: they carry no read data, and the server authorizes each under the new claims when it replays.
4612
+ */
4613
+ private retireChangedClaims;
4614
+ /**
4615
+ * Post a credential for `conn`'s socket to {@link SOCKET_REAUTH_PATH} and bounce the socket
4616
+ * unless the server took it. `bearer` is `null` to present the cookie session alone, which
4617
+ * the request carries on its own (`credentials: "include"`).
4618
+ */
4619
+ private reauthenticateShardSocket;
4620
+ /**
4621
+ * Re-auth `conn`'s socket at half its revalidation window, leaving the other half for a slow
4622
+ * worker before the server closes the socket with `4005`. A server that announced no window
4623
+ * holds the socket to nothing, so nothing is armed.
4624
+ */
4625
+ private armSocketRevalidation;
4540
4626
  private bounceShardSocket;
4541
4627
  /**
4542
4628
  * Flush every shard with a mutation currently queued in `offlineQueue`
@@ -306,6 +306,8 @@ interface OutboxSink {
306
306
  * needed to render offline on reload and to resume the live subscription.
307
307
  */
308
308
  interface CachedQuery {
309
+ /** Fingerprint of the claims the value was read under (see `SubscriptionState.serverClaims`), replayed as `sinceClaims`. */
310
+ claims?: string;
309
311
  /**
310
312
  * Token-hash fingerprint of the bearer the value was cached under, when the
311
313
  * entry was written by the identity the client currently advertises.
@@ -663,6 +665,7 @@ interface ClientSubscribeMessage {
663
665
  query: {
664
666
  args?: Record<string, unknown>;
665
667
  functionPath?: string;
668
+ sinceClaims?: string;
666
669
  sinceEpoch?: string;
667
670
  sinceSeq?: number;
668
671
  table?: string;
@@ -725,6 +728,8 @@ interface ClientShapeSubscribeMessage {
725
728
  * delta.
726
729
  */
727
730
  sinceCheckpoint?: number;
731
+ /** The claims fingerprint {@link ClientShapeSubscribeMessage.sinceCheckpoint} was read under; absent resumes cold. */
732
+ sinceClaims?: string;
728
733
  /**
729
734
  * The CDC epoch {@link ClientShapeSubscribeMessage.sinceCheckpoint} belongs
730
735
  * to. A mismatch (forked changelog timeline) forces a full re-seed even when
@@ -939,7 +944,18 @@ interface ServerLiveMessage {
939
944
  * before it posts a grant, and posts at once when the flag is absent.
940
945
  */
941
946
  interface ServerIdentityMessage {
947
+ /**
948
+ * Fingerprint of the verified claims the socket is authenticated with. Opaque to the client, which only
949
+ * hands it back as `sinceClaims` when it resubscribes from a cursor read under these claims.
950
+ */
951
+ claims?: string;
942
952
  connectionId?: string;
953
+ /**
954
+ * Milliseconds within which the socket must be re-authenticated through
955
+ * `POST /_lunora/ws/reauth`, or the server closes it with `4005`. Present only
956
+ * for an authenticated subscription socket.
957
+ */
958
+ revalidateMs?: number;
943
959
  subject: null | string;
944
960
  type: "identity";
945
961
  whisperAck?: boolean;
@@ -1497,6 +1513,12 @@ interface SubscriptionState {
1497
1513
  * persists this, never the optimistic overlay.
1498
1514
  */
1499
1515
  serverBase: unknown;
1516
+ /**
1517
+ * Fingerprint of the claims the value and cursor were read under, as the shard announced it; replayed
1518
+ * as `sinceClaims` so the server resumes only when the socket's claims are still those. Absent when the
1519
+ * shard announced none, which the server treats as a mismatch (a full snapshot).
1520
+ */
1521
+ serverClaims?: string;
1500
1522
  /**
1501
1523
  * The `__cdc_log` high-watermark (`cursor`) the `lastValue` reflects,
1502
1524
  * captured from the last `data`/`delta`/`resume` frame. Persisted to the
@@ -2044,6 +2066,23 @@ declare class LunoraClient {
2044
2066
  private readonly pollingFallbackAfterFailedAttempts;
2045
2067
  /** Polling-fallback cadence (ms); `0` disables it. See {@link LunoraClientOptions.pollingFallback}. */
2046
2068
  private readonly pollingFallbackIntervalMs;
2069
+ /** This tab's own claims fingerprint, fetched from the worker; `undefined` until known and again after any credential change, `null` once the server is known to announce none. */
2070
+ private ownClaimsValue;
2071
+ /** Frames a follower held for want of `ownClaimsValue`, one per subscription, applied once it is known. */
2072
+ private readonly heldLeaderFrames;
2073
+ private ownClaimsFetch;
2074
+ /** Leader fingerprints this tab already re-verified its own against, so a tab that truly differs asks once, not per frame. */
2075
+ private readonly claimsVerifiedAgainst;
2076
+ /** The claims request failed while frames were held: its retry timer and how many have failed in a row. */
2077
+ private ownClaimsRetryTimer;
2078
+ private ownClaimsFailures;
2079
+ /** What a reset hid from a follower's subscriptions, put back if the answer shows the same claims. */
2080
+ private readonly suspendedFollowerValues;
2081
+ /**
2082
+ * The claims fingerprint of the socket whose `data`, `delta`, `resume` or poke frame is being applied, set only
2083
+ * for the synchronous span of that handler. A value and its cursor are stamped with it as they are committed.
2084
+ */
2085
+ private frameClaims;
2047
2086
  /** See {@link LunoraClientOptions.authTokenOnUpgrade}. */
2048
2087
  private readonly authTokenOnUpgrade;
2049
2088
  private readonly offlineQueue;
@@ -2120,6 +2159,13 @@ declare class LunoraClient {
2120
2159
  private outboxLeaderRelease;
2121
2160
  /** Durable read cache (Pillar 2); `undefined` when `queryCache` is omitted or `false`. */
2122
2161
  private readonly queryCache;
2162
+ /**
2163
+ * Counts the clears of the read cache. A load or a write batch begun before a clear belongs to the identity
2164
+ * the clear retired, so it is dropped when its epoch no longer matches.
2165
+ */
2166
+ private queryCacheEpoch;
2167
+ /** Durable cache writes and clears, run in order so a clear cannot finish over a later write. */
2168
+ private queryCacheChain;
2123
2169
  /**
2124
2170
  * Values restored from the `queryCache` at construction, keyed by the
2125
2171
  * read-cache key, awaiting the `subscribe()` that will consume them. A
@@ -4053,6 +4099,27 @@ declare class LunoraClient {
4053
4099
  * by a poll, which carries no cursor: see {@link pollSubscriptions}.
4054
4100
  */
4055
4101
  private handleDataMessage;
4102
+ private followerClaims;
4103
+ private isFollowerTab;
4104
+ /** Forget this tab's own fingerprint: the credential it described may have changed. */
4105
+ private resetOwnClaims;
4106
+ /**
4107
+ * A follower's claims-stamped values were read under claims this tab may no longer hold. They are taken off the
4108
+ * views and the caches until the tab knows its own fingerprint again; {@link applyOwnClaims} puts back those that
4109
+ * were read under the claims it finds, so a plain token refresh does not leave the tab blank.
4110
+ */
4111
+ private suspendFollowerValues;
4112
+ /** Take `claims` as this tab's own: drop what a leader committed under others, from memory and the restored cache, and run the held frames. */
4113
+ private applyOwnClaims;
4114
+ private releaseHeldFrames;
4115
+ /** Remove what was read under claims other than `claims` from every cache a subscription could be seeded from. */
4116
+ private dropClaimedEntries;
4117
+ private fetchOwnClaims;
4118
+ /** Ask for the tab's claims again, with a growing delay and a bound, for as long as frames wait on the answer. */
4119
+ private scheduleOwnClaimsRetry;
4120
+ private stopOwnClaimsRetry;
4121
+ /** Run `apply` with the claims fingerprint of the socket that delivered the frame, for the values and cursors it commits. */
4122
+ private withFrameClaims;
4056
4123
  /**
4057
4124
  * Handle a `resume` frame (Pillar 1b): the server proved nothing the
4058
4125
  * subscription reads changed since our `sinceSeq`, so the cached value is
@@ -4537,6 +4604,25 @@ declare class LunoraClient {
4537
4604
  * bearer on the upgrade, so they are always bounced.
4538
4605
  */
4539
4606
  private bounceShardSockets;
4607
+ /**
4608
+ * The same user resolved under different claims. The identity fingerprint names the user, not the claims, so the
4609
+ * read cache's own gate would accept what was read under the old ones: drop it (hydrated, pending and durable) as
4610
+ * well as the views, so nothing read under the old claims is shown or resumed from. Queued offline mutations are
4611
+ * kept: they carry no read data, and the server authorizes each under the new claims when it replays.
4612
+ */
4613
+ private retireChangedClaims;
4614
+ /**
4615
+ * Post a credential for `conn`'s socket to {@link SOCKET_REAUTH_PATH} and bounce the socket
4616
+ * unless the server took it. `bearer` is `null` to present the cookie session alone, which
4617
+ * the request carries on its own (`credentials: "include"`).
4618
+ */
4619
+ private reauthenticateShardSocket;
4620
+ /**
4621
+ * Re-auth `conn`'s socket at half its revalidation window, leaving the other half for a slow
4622
+ * worker before the server closes the socket with `4005`. A server that announced no window
4623
+ * holds the socket to nothing, so nothing is armed.
4624
+ */
4625
+ private armSocketRevalidation;
4540
4626
  private bounceShardSocket;
4541
4627
  /**
4542
4628
  * Flush every shard with a mutation currently queued in `offlineQueue`
@@ -1,4 +1,4 @@
1
- import { L as LunoraClient, P as Preloaded } from "./lunora-client.d-B4UG-Rj6.mjs";
1
+ import { L as LunoraClient, P as Preloaded } from "./lunora-client.d-BoT_6QjF.mjs";
2
2
  import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./function-reference.d-Br_hsKje.mjs";
3
3
  /**
4
4
  * Run a query once on the server (during SSR) and capture its result in a
@@ -1,4 +1,4 @@
1
- import { L as LunoraClient, P as Preloaded } from "./lunora-client.d-44IAL_TZ.js";
1
+ import { L as LunoraClient, P as Preloaded } from "./lunora-client.d-B9ucPXKp.js";
2
2
  import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./function-reference.d-Br_hsKje.js";
3
3
  /**
4
4
  * Run a query once on the server (during SSR) and capture its result in a
@@ -1,5 +1,5 @@
1
1
  import { F as FunctionReference, R as ReturnOf, A as ArgsOf } from "../packem_shared/function-reference.d-Br_hsKje.mjs";
2
- import { L as LunoraClient, S as SubscriptionError, a as Unsubscribe } from "../packem_shared/lunora-client.d-B4UG-Rj6.mjs";
2
+ import { L as LunoraClient, S as SubscriptionError, a as Unsubscribe } from "../packem_shared/lunora-client.d-BoT_6QjF.mjs";
3
3
  export type {
4
4
  /**
5
5
  * `@lunora/client/query` — the framework-neutral live-query state machine shared
@@ -15,7 +15,7 @@ export type {
15
15
  * `lunoraQueryOptions`), so every adapter and server entry keys a Lunora query
16
16
  * the same way.
17
17
  */
18
- b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-B4UG-Rj6.mjs";
18
+ b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-BoT_6QjF.mjs";
19
19
  import '@lunora/errors';
20
20
  /**
21
21
  * The TanStack Query cache-key contract for Lunora queries. It lives here, not
@@ -1,5 +1,5 @@
1
1
  import { F as FunctionReference, R as ReturnOf, A as ArgsOf } from "../packem_shared/function-reference.d-Br_hsKje.js";
2
- import { L as LunoraClient, S as SubscriptionError, a as Unsubscribe } from "../packem_shared/lunora-client.d-44IAL_TZ.js";
2
+ import { L as LunoraClient, S as SubscriptionError, a as Unsubscribe } from "../packem_shared/lunora-client.d-B9ucPXKp.js";
3
3
  export type {
4
4
  /**
5
5
  * `@lunora/client/query` — the framework-neutral live-query state machine shared
@@ -15,7 +15,7 @@ export type {
15
15
  * `lunoraQueryOptions`), so every adapter and server entry keys a Lunora query
16
16
  * the same way.
17
17
  */
18
- b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-44IAL_TZ.js";
18
+ b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-B9ucPXKp.js";
19
19
  import '@lunora/errors';
20
20
  /**
21
21
  * The TanStack Query cache-key contract for Lunora queries. It lives here, not
@@ -1,4 +1,4 @@
1
- import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-B4UG-Rj6.mjs";
1
+ import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-BoT_6QjF.mjs";
2
2
  export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/function-reference.d-Br_hsKje.mjs";
3
3
  export {
4
4
  /**
@@ -20,7 +20,7 @@ p as preloadQuery,
20
20
  * WebSocket or touches a UI framework, so it is safe to import from any SSR
21
21
  * loader.
22
22
  */
23
- a as preloadedQueryResult } from "../packem_shared/preload.d-ffYgjmVU.mjs";
23
+ a as preloadedQueryResult } from "../packem_shared/preload.d-CSdHBvul.mjs";
24
24
  import '@lunora/errors';
25
25
  /**
26
26
  * Structural shape of a better-auth `getSession` call's resolved value.
@@ -1,4 +1,4 @@
1
- import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-44IAL_TZ.js";
1
+ import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-B9ucPXKp.js";
2
2
  export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/function-reference.d-Br_hsKje.js";
3
3
  export {
4
4
  /**
@@ -20,7 +20,7 @@ p as preloadQuery,
20
20
  * WebSocket or touches a UI framework, so it is safe to import from any SSR
21
21
  * loader.
22
22
  */
23
- a as preloadedQueryResult } from "../packem_shared/preload.d-cslUUu1t.js";
23
+ a as preloadedQueryResult } from "../packem_shared/preload.d-Dt_4IWk_.js";
24
24
  import '@lunora/errors';
25
25
  /**
26
26
  * Structural shape of a better-auth `getSession` call's resolved value.
@@ -1 +1 @@
1
- import{getServerSession as o}from"../packem_shared/getServerSession-BaOoo1p6.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-DxozvweR.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-mUxENnFT.mjs";import{preloadQuery as s,preloadedQueryResult as f}from"../packem_shared/preloadQuery-uFy24PCR.mjs";export{i as createServerClient,l as deserializePreloaded,o as getServerSession,s as preloadQuery,f as preloadedQueryResult,t as serializePreloaded};
1
+ import{getServerSession as o}from"../packem_shared/getServerSession-BaOoo1p6.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-DxozvweR.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-97d5uFpA.mjs";import{preloadQuery as s,preloadedQueryResult as f}from"../packem_shared/preloadQuery-uFy24PCR.mjs";export{i as createServerClient,l as deserializePreloaded,o as getServerSession,s as preloadQuery,f as preloadedQueryResult,t as serializePreloaded};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/client",
3
- "version": "1.0.0-alpha.276",
3
+ "version": "1.0.0-alpha.277",
4
4
  "description": "Lunora browser SDK: WebSocket transport, optimistic updates, and an offline mutation queue",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -1 +0,0 @@
1
- import{w as s}from"./optimistic-layers-D-7D3yeJ.mjs";let d=0;const o="lunora-bridge",h=1e3,b=3e3;class u{bc;tabId;heartbeatInterval;leaderTimeout;knownLeader=void 0;leader=!1;running=!1;promotionPending=!1;lastHeartbeat=0;pendingData=new Map;heldData=new Map;heartbeatTimer=void 0;leaderCheckTimer=void 0;onBecomeLeader;onStopBeingLeader;onConnectionStatus;onSubscriptionData;onLeaderClaimAnswered;onSubscriptionError;onSubscriptionSettled;constructor(t={}){if(d+=1,this.tabId=`tab_${String(d)}_${crypto.randomUUID()}`,this.heartbeatInterval=t.heartbeatInterval??h,this.leaderTimeout=t.leaderTimeout??b,this.onBecomeLeader=t.onBecomeLeader,this.onStopBeingLeader=t.onStopBeingLeader,this.onConnectionStatus=t.onConnectionStatus,this.onSubscriptionData=t.onSubscriptionData,this.onLeaderClaimAnswered=t.onLeaderClaimAnswered,this.onSubscriptionError=t.onSubscriptionError,this.onSubscriptionSettled=t.onSubscriptionSettled,typeof BroadcastChannel>"u"){this.bc=void 0;return}this.bc=new BroadcastChannel(t.channelName??o),this.bc.addEventListener("message",e=>{this.handleMessage(e.data)})}start(){if(!this.running){if(this.running=!0,this.bc===void 0){this.becomeLeader();return}this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout),this.leaderCheckTimer=setInterval(()=>{this.checkLeaderHealth()},this.leaderTimeout),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeat()},this.heartbeatInterval)}}stop(){this.running=!1,this.leader&&(this.broadcast({type:"yield-leadership",tabId:this.tabId}),this.leader=!1,this.knownLeader=void 0,this.onStopBeingLeader?.()),this.heartbeatTimer!==void 0&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0),this.leaderCheckTimer!==void 0&&(clearInterval(this.leaderCheckTimer),this.leaderCheckTimer=void 0),this.bc?.close()}isLeader(){return this.leader}promoteImmediately(){this.running&&this.becomeLeader()}get leaderTabId(){return this.knownLeader}get id(){return this.tabId}get isRunning(){return this.running}broadcastSubscriptionData(t,e,i,r,a){this.leader&&(this.pendingData.size===0&&queueMicrotask(()=>{this.flushPendingData()}),this.pendingData.set(t,{type:"subscription-data",tabId:this.tabId,key:t,data:e,...i===void 0?{}:{cursor:i},...r===void 0?{}:{epoch:r},...a===void 0?{}:{identity:a}}))}broadcastSubscriptionError(t,e,i){this.leader&&this.broadcast({type:"subscription-error",tabId:this.tabId,key:t,error:e,...i===void 0?{}:{identity:i}})}broadcastSubscriptionSettled(t,e,i,r,a,n){this.leader&&this.broadcast({type:"subscription-settled",tabId:this.tabId,key:t,...e===void 0?{}:{cursor:e},...i===void 0?{}:{epoch:i},...r===void 0?{}:{lastMutationId:r},...a===void 0?{}:{clientId:a},...n===void 0?{}:{identity:n}})}broadcastConnectionStatus(t,e){this.leader&&this.broadcast({type:"connection-status",tabId:this.tabId,status:t,...e===void 0?{}:{identity:e}})}broadcast(t){this.flushPendingData(),this.bc?.postMessage(t)}flushPendingData(){if(this.pendingData.size===0)return;const t=[...this.pendingData.values()];if(this.pendingData.clear(),!this.leader)return;let e,i=!0;for(const[r,a]of t.entries()){const n=r<t.length-1;try{this.bc?.postMessage(n?{...a,more:!0}:a),e=a,i=!n}catch{}}!i&&e!==void 0&&this.bc?.postMessage(e)}applySubscriptionData(t){const e=this.heldData.get(t.tabId)??[];if(e.push(t),t.more===!0){this.heldData.set(t.tabId,e);return}this.heldData.delete(t.tabId),s(()=>{for(const i of e)this.onSubscriptionData?.(i.key,i.data,i.cursor,i.epoch,i.identity)},()=>this.running)}handleMessage(t){switch(t.type){case"claim-leadership":{this.handleClaimLeadership(t);break}case"connection-status":{if(this.leader||t.tabId===this.tabId)break;this.onConnectionStatus?.(t.status,t.identity);break}case"heartbeat":{this.handleHeartbeat(t);break}case"subscription-data":{if(this.leader||t.tabId===this.tabId)break;this.applySubscriptionData(t);break}case"subscription-error":{if(this.leader||t.tabId===this.tabId)break;this.onSubscriptionError?.(t.key,t.error,t.identity);break}case"subscription-settled":{if(this.leader||t.tabId===this.tabId)break;this.onSubscriptionSettled?.(t.key,t.cursor,t.epoch,t.lastMutationId,t.clientId,t.identity);break}case"yield-leadership":{this.heldData.delete(t.tabId),this.knownLeader===t.tabId&&(this.knownLeader=void 0,this.running&&!this.leader&&this.claimAndPromote());break}}}handleClaimLeadership(t){if(t.tabId!==this.tabId){if(this.leader){this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}),this.onLeaderClaimAnswered?.();return}this.knownLeader===void 0&&t.tabId<this.tabId&&(this.knownLeader=t.tabId,this.lastHeartbeat=t.ts)}}handleHeartbeat(t){if(t.tabId!==this.tabId){if(this.leader){this.resolveLeaderVsLeaderTieBreak(t);return}this.lastHeartbeat=t.ts,this.knownLeader=t.tabId}}resolveLeaderVsLeaderTieBreak(t){t.tabId<this.tabId?(this.leader=!1,this.knownLeader=t.tabId,this.lastHeartbeat=t.ts,this.onStopBeingLeader?.()):this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}becomeLeader(){this.leader||(this.leader=!0,this.knownLeader=this.tabId,this.lastHeartbeat=Date.now(),this.onBecomeLeader?.(),this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}))}sendHeartbeat(){this.leader&&this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}checkLeaderHealth(){if(!this.running||this.leader)return;if(this.knownLeader===void 0){this.claimAndPromote();return}Date.now()-this.lastHeartbeat>this.leaderTimeout&&(this.heldData.delete(this.knownLeader),this.knownLeader=void 0,this.claimAndPromote())}claimAndPromote(){this.promotionPending||(this.promotionPending=!0,this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.promotionPending=!1,this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout))}}export{u as TabCoordinator};