@lunora/client 1.0.0-alpha.221 → 1.0.0-alpha.222

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.
@@ -1,4 +1,4 @@
1
- import { U as User, L as LunoraClient } from "../packem_shared/lunora-client.d-B22TAgVj.mjs";
1
+ import { U as User, L as LunoraClient } from "../packem_shared/lunora-client.d-BtqCoSVw.mjs";
2
2
  import '@lunora/errors';
3
3
  import "../packem_shared/function-reference.d-Br_hsKje.mjs";
4
4
  import '@lunora/runtime';
@@ -1,4 +1,4 @@
1
- import { U as User, L as LunoraClient } from "../packem_shared/lunora-client.d-Cq8NykWg.js";
1
+ import { U as User, L as LunoraClient } from "../packem_shared/lunora-client.d-Fds53_IH.js";
2
2
  import '@lunora/errors';
3
3
  import "../packem_shared/function-reference.d-Br_hsKje.js";
4
4
  import '@lunora/runtime';
package/dist/index.d.mts CHANGED
@@ -1,8 +1,8 @@
1
- import { R as ReconnectOptions, c as PersistenceAdapter, Q as QueryCacheAdapter, B as BookmarkStorage, C as ConnectionStatus, S as SubscriptionError, H as HttpStreamRef, d as HttpStreamArgsOf, e as HttpStreamChunkOf, f as StreamIterable, O as OfflineQueueOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-B22TAgVj.mjs";
2
- export { type A as ActionCallOptions, type g as BatchSlot, type h as CachedQuery, type i as ClientDebugShard, type j as ClientDebugSnapshot, type k as ClientDebugSubscription, type l as ClientMessage, type m as ClientQueryRef, type n as ClientShapeSubscribeMessage, type o as ClientShapeUnsubscribeMessage, D as DEFAULT_MAX_BUFFER, type F as FunctionArgumentDescriptor, type p as FunctionDescriptor, type G as GlobalFacetResult, type q as GlobalFacetValue, type r as GlobalFilterClause, type s as GlobalTableInfo, type t as GlobalTablePage, type u as HttpStreamCallArgs, type v as LunoraClientError, type w as LunoraClientOptions, type M as MutationCallOptions, type x as MutationSettledEvent, type y as OptimisticLocalStore, type z as OptimisticUpdate, type E as OutboxMutation, type I as OutboxSink, type J as PersistedMutation, type P as Preloaded, type K as ReplayCredential, type N as ReplayIdentityVerdict, type T as RoomRef, type V as RowOp, type W as RpcEnvelope, type X as RpcResponseBody, type Y as ScheduleRecord, type Z as ScheduleRetryPolicy, type _ as SchedulerPoolStatus, type $ as SchedulerStatus, type a0 as ServerMessage, type a1 as ServerPokeEndMessage, type a2 as ServerPokePartMessage, type a3 as ServerPokeStartMessage, type a4 as ShardTrafficEntry, type a5 as ShardTrafficResult, type a6 as StorageListPage, type a7 as StorageObject, type a8 as StoredQuery, type a9 as StreamHandle, type aa as SubscriptionCallback, type b as SubscriptionErrorCallback, ab as SubscriptionRegistry, type ac as SubscriptionState, type ad as SyncWatermark, type a as Unsubscribe, type U as User, type ae as WorkflowInstanceAction, type af as WorkflowInstanceDetail, type ag as WorkflowInstancePage, type ah as WorkflowInstanceStatus, type ai as WorkflowInstanceSummary, type aj as WorkflowStepDetail, type ak as WsTokenProvider, al as createClientQuery, am as createLocalStore, an as createStream } from "./packem_shared/lunora-client.d-B22TAgVj.mjs";
1
+ import { R as ReconnectOptions, c as PersistenceAdapter, Q as QueryCacheAdapter, B as BookmarkStorage, C as ConnectionStatus, S as SubscriptionError, H as HttpStreamRef, d as HttpStreamArgsOf, e as HttpStreamChunkOf, f as StreamIterable, O as OfflineQueueOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-BtqCoSVw.mjs";
2
+ export { type A as ActionCallOptions, type g as BatchSlot, type h as CachedQuery, type i as ClientDebugShard, type j as ClientDebugSnapshot, type k as ClientDebugSubscription, type l as ClientMessage, type m as ClientQueryRef, type n as ClientShapeSubscribeMessage, type o as ClientShapeUnsubscribeMessage, D as DEFAULT_MAX_BUFFER, type F as FunctionArgumentDescriptor, type p as FunctionDescriptor, type G as GlobalFacetResult, type q as GlobalFacetValue, type r as GlobalFilterClause, type s as GlobalTableInfo, type t as GlobalTablePage, type u as HttpStreamCallArgs, type v as LunoraClientError, type w as LunoraClientOptions, type M as MutationCallOptions, type x as MutationSettledEvent, type y as OptimisticLocalStore, type z as OptimisticUpdate, type E as OutboxMutation, type I as OutboxSink, type J as PersistedMutation, type P as Preloaded, type K as ReplayCredential, type N as ReplayIdentityVerdict, type T as RoomRef, type V as RowOp, type W as RpcEnvelope, type X as RpcResponseBody, type Y as ScheduleRecord, type Z as ScheduleRetryPolicy, type _ as SchedulerPoolStatus, type $ as SchedulerStatus, type a0 as ServerMessage, type a1 as ServerPokeEndMessage, type a2 as ServerPokePartMessage, type a3 as ServerPokeStartMessage, type a4 as ShardTrafficEntry, type a5 as ShardTrafficResult, type a6 as StorageListPage, type a7 as StorageObject, type a8 as StoredQuery, type a9 as StreamHandle, type aa as SubscriptionCallback, type b as SubscriptionErrorCallback, ab as SubscriptionRegistry, type ac as SubscriptionState, type ad as SyncWatermark, type a as Unsubscribe, type U as User, type ae as WorkflowInstanceAction, type af as WorkflowInstanceDetail, type ag as WorkflowInstancePage, type ah as WorkflowInstanceStatus, type ai as WorkflowInstanceSummary, type aj as WorkflowStepDetail, type ak as WsTokenProvider, al as createClientQuery, am as createLocalStore, an as createStream } from "./packem_shared/lunora-client.d-BtqCoSVw.mjs";
3
3
  import { LunoraError, LunoraErrorCode } from '@lunora/errors';
4
4
  export type { LunoraErrorCode } from '@lunora/errors';
5
- export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-3Sb8o5sD.mjs";
5
+ export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-2WDfHuro.mjs";
6
6
  import { F as FunctionReference } from "./packem_shared/function-reference.d-Br_hsKje.mjs";
7
7
  export type { A as ArgsOf, R as ReturnOf } from "./packem_shared/function-reference.d-Br_hsKje.mjs";
8
8
  export type { AuthCapabilities, AuthConfigInfo, AuthImpersonation, AuthPage, AuthSession, AuthUser, AuthUserFieldSpec, CronJobInfo, KvKeyEntry, KvKeyListResult, KvNamespaceSummary, KvValueResult, PipelineLogColumnMap, PipelineLogCursor, PipelineLogField, PipelineLogPage, PipelineLogQuery, PipelineLogRow, VectorIndexSummary, VectorQueryMatch } from '@lunora/runtime';
@@ -605,6 +605,66 @@ interface HttpStreamOptions {
605
605
  * aborts the underlying fetch, which the server observes via `request.signal`.
606
606
  */
607
607
  declare const httpStream: <Ref extends HttpStreamRef>(route: Ref, args?: HttpStreamArgsOf<Ref>, options?: HttpStreamOptions) => StreamIterable<HttpStreamChunkOf<Ref>>;
608
+ /** Options for {@link connectLiveStream}. */
609
+ interface ConnectLiveStreamOptions {
610
+ /** `fetch` override (a test seam, or a custom transport). */
611
+ fetch?: typeof fetch;
612
+ /** Extra headers sent on both the stream and the control requests. */
613
+ headers?: Record<string, string>;
614
+ /** Ceiling for the reconnect backoff, in ms. Defaults to `30000`. */
615
+ maxDelayMs?: number;
616
+ /** Base reconnect delay in ms. Defaults to `1000`. */
617
+ retryDelay?: number;
618
+ /** Send cookies / credentials on the stream and control requests. */
619
+ withCredentials?: boolean;
620
+ }
621
+ /** A delivered live event. */
622
+ interface LiveStreamEvent {
623
+ /** The decoded payload the publisher sent. */
624
+ payload: unknown;
625
+ /** The topic the event was published on. */
626
+ topic: string;
627
+ }
628
+ /** Options for {@link LiveStream.subscribe}. */
629
+ /** A subscribe the shard refused for good: a reconnect would only be refused again. */
630
+ interface LiveStreamSubscribeError {
631
+ /** The HTTP status of the refusal, e.g. 403, 409 or 429. */
632
+ status: number;
633
+ subscriptionId: string;
634
+ topic: string;
635
+ }
636
+ interface LiveStreamSubscribeOptions {
637
+ /** Stable caller id; a generated one is used when omitted. */
638
+ id?: string;
639
+ /**
640
+ * Called when the shard refuses this subscription (403, 409, 429 and similar). The subscription is dropped
641
+ * first, so a later subscribe with the same id is accepted. A 401 is not reported: the stream reconnects,
642
+ * which re-authenticates and registers the subscription again.
643
+ */
644
+ onError?: (error: LiveStreamSubscribeError) => void;
645
+ /** Called for every event on `topic`. */
646
+ onEvent?: (payload: unknown) => void;
647
+ /** The topic to follow. */
648
+ topic: string;
649
+ }
650
+ /** A live stream connection. */
651
+ interface LiveStream {
652
+ /** Close the stream and stop reconnecting. */
653
+ close: () => void;
654
+ /** The server-minted connection id, or `undefined` before the first connect. */
655
+ readonly connectionId: string | undefined;
656
+ /** Observe every event on the connection; returns an unsubscribe handle. */
657
+ onEvent: (handler: (event: LiveStreamEvent) => void) => () => void;
658
+ /** Resolves once the first connection is established (rejects only if `close`d first). */
659
+ readonly ready: Promise<void>;
660
+ /** Follow a topic; returns an unsubscribe handle. */
661
+ subscribe: (options: LiveStreamSubscribeOptions) => () => void;
662
+ }
663
+ /**
664
+ * Connect to a live topic stream. See the module docblock.
665
+ * @param url the `connect` route URL (its sibling `control` route is derived)
666
+ */
667
+ declare const connectLiveStream: (url: string, options?: ConnectLiveStreamOptions) => LiveStream;
608
668
  /**
609
669
  * The structural surface of a TanStack `Transaction` a bound custom mutator
610
670
  * returns — its `isPersisted.promise` resolves once the write is persisted and
@@ -958,4 +1018,4 @@ declare const createIndexedDbQueryCache: (options?: IndexedDbQueryCacheOptions)
958
1018
  * ```
959
1019
  */
960
1020
  declare const createSnapshotPrecondition: (client: LunoraClient, functionRef: FunctionReference, args: Record<string, unknown>, shardKey?: string) => (() => boolean);
961
- export { type AsyncStorageLike, type AsyncStoragePersistenceOptions, type AsyncStorageQueryCacheOptions, type BookmarkStorage, CONFLICT_ERROR_CODE, type ConnectionStatus, type FunctionReference, type HttpStreamArgsOf, type HttpStreamChunkOf, type HttpStreamOptions, type HttpStreamRef, type IndexedDbPersistenceOptions, type IndexedDbQueryCacheOptions, LunoraClient, type MutationDelta, type MutatorHandle, type MutatorRunnerSinks, type MutatorTransaction, OfflineQueue, type OfflineQueueOptions, type OptimisticMessage, type PersistenceAdapter, type QueryCacheAdapter, type QueuedMutation, RETIRE_AFTER_DURABLE_SEQ_ADVANCE, type ReconcileDurableMessage, type ReconnectCalculator, type ReconnectOptions, type StreamIterable, type SubscriptionError, TabCoordinator, TransportError, applyDelta, createAsyncStoragePersistence, createAsyncStorageQueryCache, createCallRunner, createInMemoryBookmarkStorage, createInMemoryPersistence, createInMemoryQueryCache, createIndexedDbPersistence, createIndexedDbQueryCache, createMutatorRunner, createReconnect, createSnapshotPrecondition, getErrorCode, getRetryAfterMs, httpStream, isAuthReplayFailure, isConflictError, isForbiddenError, isMutationDelta, isRateLimitedError, isUnauthorizedError, maxSeq, queryCacheKey, reconcileOptimistic };
1021
+ export { type AsyncStorageLike, type AsyncStoragePersistenceOptions, type AsyncStorageQueryCacheOptions, type BookmarkStorage, CONFLICT_ERROR_CODE, type ConnectLiveStreamOptions, type ConnectionStatus, type FunctionReference, type HttpStreamArgsOf, type HttpStreamChunkOf, type HttpStreamOptions, type HttpStreamRef, type IndexedDbPersistenceOptions, type IndexedDbQueryCacheOptions, type LiveStream, type LiveStreamEvent, type LiveStreamSubscribeOptions, LunoraClient, type MutationDelta, type MutatorHandle, type MutatorRunnerSinks, type MutatorTransaction, OfflineQueue, type OfflineQueueOptions, type OptimisticMessage, type PersistenceAdapter, type QueryCacheAdapter, type QueuedMutation, RETIRE_AFTER_DURABLE_SEQ_ADVANCE, type ReconcileDurableMessage, type ReconnectCalculator, type ReconnectOptions, type StreamIterable, type SubscriptionError, TabCoordinator, TransportError, applyDelta, connectLiveStream, createAsyncStoragePersistence, createAsyncStorageQueryCache, createCallRunner, createInMemoryBookmarkStorage, createInMemoryPersistence, createInMemoryQueryCache, createIndexedDbPersistence, createIndexedDbQueryCache, createMutatorRunner, createReconnect, createSnapshotPrecondition, getErrorCode, getRetryAfterMs, httpStream, isAuthReplayFailure, isConflictError, isForbiddenError, isMutationDelta, isRateLimitedError, isUnauthorizedError, maxSeq, queryCacheKey, reconcileOptimistic };
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { R as ReconnectOptions, c as PersistenceAdapter, Q as QueryCacheAdapter, B as BookmarkStorage, C as ConnectionStatus, S as SubscriptionError, H as HttpStreamRef, d as HttpStreamArgsOf, e as HttpStreamChunkOf, f as StreamIterable, O as OfflineQueueOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-Cq8NykWg.js";
2
- export { type A as ActionCallOptions, type g as BatchSlot, type h as CachedQuery, type i as ClientDebugShard, type j as ClientDebugSnapshot, type k as ClientDebugSubscription, type l as ClientMessage, type m as ClientQueryRef, type n as ClientShapeSubscribeMessage, type o as ClientShapeUnsubscribeMessage, D as DEFAULT_MAX_BUFFER, type F as FunctionArgumentDescriptor, type p as FunctionDescriptor, type G as GlobalFacetResult, type q as GlobalFacetValue, type r as GlobalFilterClause, type s as GlobalTableInfo, type t as GlobalTablePage, type u as HttpStreamCallArgs, type v as LunoraClientError, type w as LunoraClientOptions, type M as MutationCallOptions, type x as MutationSettledEvent, type y as OptimisticLocalStore, type z as OptimisticUpdate, type E as OutboxMutation, type I as OutboxSink, type J as PersistedMutation, type P as Preloaded, type K as ReplayCredential, type N as ReplayIdentityVerdict, type T as RoomRef, type V as RowOp, type W as RpcEnvelope, type X as RpcResponseBody, type Y as ScheduleRecord, type Z as ScheduleRetryPolicy, type _ as SchedulerPoolStatus, type $ as SchedulerStatus, type a0 as ServerMessage, type a1 as ServerPokeEndMessage, type a2 as ServerPokePartMessage, type a3 as ServerPokeStartMessage, type a4 as ShardTrafficEntry, type a5 as ShardTrafficResult, type a6 as StorageListPage, type a7 as StorageObject, type a8 as StoredQuery, type a9 as StreamHandle, type aa as SubscriptionCallback, type b as SubscriptionErrorCallback, ab as SubscriptionRegistry, type ac as SubscriptionState, type ad as SyncWatermark, type a as Unsubscribe, type U as User, type ae as WorkflowInstanceAction, type af as WorkflowInstanceDetail, type ag as WorkflowInstancePage, type ah as WorkflowInstanceStatus, type ai as WorkflowInstanceSummary, type aj as WorkflowStepDetail, type ak as WsTokenProvider, al as createClientQuery, am as createLocalStore, an as createStream } from "./packem_shared/lunora-client.d-Cq8NykWg.js";
1
+ import { R as ReconnectOptions, c as PersistenceAdapter, Q as QueryCacheAdapter, B as BookmarkStorage, C as ConnectionStatus, S as SubscriptionError, H as HttpStreamRef, d as HttpStreamArgsOf, e as HttpStreamChunkOf, f as StreamIterable, O as OfflineQueueOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-Fds53_IH.js";
2
+ export { type A as ActionCallOptions, type g as BatchSlot, type h as CachedQuery, type i as ClientDebugShard, type j as ClientDebugSnapshot, type k as ClientDebugSubscription, type l as ClientMessage, type m as ClientQueryRef, type n as ClientShapeSubscribeMessage, type o as ClientShapeUnsubscribeMessage, D as DEFAULT_MAX_BUFFER, type F as FunctionArgumentDescriptor, type p as FunctionDescriptor, type G as GlobalFacetResult, type q as GlobalFacetValue, type r as GlobalFilterClause, type s as GlobalTableInfo, type t as GlobalTablePage, type u as HttpStreamCallArgs, type v as LunoraClientError, type w as LunoraClientOptions, type M as MutationCallOptions, type x as MutationSettledEvent, type y as OptimisticLocalStore, type z as OptimisticUpdate, type E as OutboxMutation, type I as OutboxSink, type J as PersistedMutation, type P as Preloaded, type K as ReplayCredential, type N as ReplayIdentityVerdict, type T as RoomRef, type V as RowOp, type W as RpcEnvelope, type X as RpcResponseBody, type Y as ScheduleRecord, type Z as ScheduleRetryPolicy, type _ as SchedulerPoolStatus, type $ as SchedulerStatus, type a0 as ServerMessage, type a1 as ServerPokeEndMessage, type a2 as ServerPokePartMessage, type a3 as ServerPokeStartMessage, type a4 as ShardTrafficEntry, type a5 as ShardTrafficResult, type a6 as StorageListPage, type a7 as StorageObject, type a8 as StoredQuery, type a9 as StreamHandle, type aa as SubscriptionCallback, type b as SubscriptionErrorCallback, ab as SubscriptionRegistry, type ac as SubscriptionState, type ad as SyncWatermark, type a as Unsubscribe, type U as User, type ae as WorkflowInstanceAction, type af as WorkflowInstanceDetail, type ag as WorkflowInstancePage, type ah as WorkflowInstanceStatus, type ai as WorkflowInstanceSummary, type aj as WorkflowStepDetail, type ak as WsTokenProvider, al as createClientQuery, am as createLocalStore, an as createStream } from "./packem_shared/lunora-client.d-Fds53_IH.js";
3
3
  import { LunoraError, LunoraErrorCode } from '@lunora/errors';
4
4
  export type { LunoraErrorCode } from '@lunora/errors';
5
- export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-CPzCWpiu.js";
5
+ export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-mgtct7Xi.js";
6
6
  import { F as FunctionReference } from "./packem_shared/function-reference.d-Br_hsKje.js";
7
7
  export type { A as ArgsOf, R as ReturnOf } from "./packem_shared/function-reference.d-Br_hsKje.js";
8
8
  export type { AuthCapabilities, AuthConfigInfo, AuthImpersonation, AuthPage, AuthSession, AuthUser, AuthUserFieldSpec, CronJobInfo, KvKeyEntry, KvKeyListResult, KvNamespaceSummary, KvValueResult, PipelineLogColumnMap, PipelineLogCursor, PipelineLogField, PipelineLogPage, PipelineLogQuery, PipelineLogRow, VectorIndexSummary, VectorQueryMatch } from '@lunora/runtime';
@@ -605,6 +605,66 @@ interface HttpStreamOptions {
605
605
  * aborts the underlying fetch, which the server observes via `request.signal`.
606
606
  */
607
607
  declare const httpStream: <Ref extends HttpStreamRef>(route: Ref, args?: HttpStreamArgsOf<Ref>, options?: HttpStreamOptions) => StreamIterable<HttpStreamChunkOf<Ref>>;
608
+ /** Options for {@link connectLiveStream}. */
609
+ interface ConnectLiveStreamOptions {
610
+ /** `fetch` override (a test seam, or a custom transport). */
611
+ fetch?: typeof fetch;
612
+ /** Extra headers sent on both the stream and the control requests. */
613
+ headers?: Record<string, string>;
614
+ /** Ceiling for the reconnect backoff, in ms. Defaults to `30000`. */
615
+ maxDelayMs?: number;
616
+ /** Base reconnect delay in ms. Defaults to `1000`. */
617
+ retryDelay?: number;
618
+ /** Send cookies / credentials on the stream and control requests. */
619
+ withCredentials?: boolean;
620
+ }
621
+ /** A delivered live event. */
622
+ interface LiveStreamEvent {
623
+ /** The decoded payload the publisher sent. */
624
+ payload: unknown;
625
+ /** The topic the event was published on. */
626
+ topic: string;
627
+ }
628
+ /** Options for {@link LiveStream.subscribe}. */
629
+ /** A subscribe the shard refused for good: a reconnect would only be refused again. */
630
+ interface LiveStreamSubscribeError {
631
+ /** The HTTP status of the refusal, e.g. 403, 409 or 429. */
632
+ status: number;
633
+ subscriptionId: string;
634
+ topic: string;
635
+ }
636
+ interface LiveStreamSubscribeOptions {
637
+ /** Stable caller id; a generated one is used when omitted. */
638
+ id?: string;
639
+ /**
640
+ * Called when the shard refuses this subscription (403, 409, 429 and similar). The subscription is dropped
641
+ * first, so a later subscribe with the same id is accepted. A 401 is not reported: the stream reconnects,
642
+ * which re-authenticates and registers the subscription again.
643
+ */
644
+ onError?: (error: LiveStreamSubscribeError) => void;
645
+ /** Called for every event on `topic`. */
646
+ onEvent?: (payload: unknown) => void;
647
+ /** The topic to follow. */
648
+ topic: string;
649
+ }
650
+ /** A live stream connection. */
651
+ interface LiveStream {
652
+ /** Close the stream and stop reconnecting. */
653
+ close: () => void;
654
+ /** The server-minted connection id, or `undefined` before the first connect. */
655
+ readonly connectionId: string | undefined;
656
+ /** Observe every event on the connection; returns an unsubscribe handle. */
657
+ onEvent: (handler: (event: LiveStreamEvent) => void) => () => void;
658
+ /** Resolves once the first connection is established (rejects only if `close`d first). */
659
+ readonly ready: Promise<void>;
660
+ /** Follow a topic; returns an unsubscribe handle. */
661
+ subscribe: (options: LiveStreamSubscribeOptions) => () => void;
662
+ }
663
+ /**
664
+ * Connect to a live topic stream. See the module docblock.
665
+ * @param url the `connect` route URL (its sibling `control` route is derived)
666
+ */
667
+ declare const connectLiveStream: (url: string, options?: ConnectLiveStreamOptions) => LiveStream;
608
668
  /**
609
669
  * The structural surface of a TanStack `Transaction` a bound custom mutator
610
670
  * returns — its `isPersisted.promise` resolves once the write is persisted and
@@ -958,4 +1018,4 @@ declare const createIndexedDbQueryCache: (options?: IndexedDbQueryCacheOptions)
958
1018
  * ```
959
1019
  */
960
1020
  declare const createSnapshotPrecondition: (client: LunoraClient, functionRef: FunctionReference, args: Record<string, unknown>, shardKey?: string) => (() => boolean);
961
- export { type AsyncStorageLike, type AsyncStoragePersistenceOptions, type AsyncStorageQueryCacheOptions, type BookmarkStorage, CONFLICT_ERROR_CODE, type ConnectionStatus, type FunctionReference, type HttpStreamArgsOf, type HttpStreamChunkOf, type HttpStreamOptions, type HttpStreamRef, type IndexedDbPersistenceOptions, type IndexedDbQueryCacheOptions, LunoraClient, type MutationDelta, type MutatorHandle, type MutatorRunnerSinks, type MutatorTransaction, OfflineQueue, type OfflineQueueOptions, type OptimisticMessage, type PersistenceAdapter, type QueryCacheAdapter, type QueuedMutation, RETIRE_AFTER_DURABLE_SEQ_ADVANCE, type ReconcileDurableMessage, type ReconnectCalculator, type ReconnectOptions, type StreamIterable, type SubscriptionError, TabCoordinator, TransportError, applyDelta, createAsyncStoragePersistence, createAsyncStorageQueryCache, createCallRunner, createInMemoryBookmarkStorage, createInMemoryPersistence, createInMemoryQueryCache, createIndexedDbPersistence, createIndexedDbQueryCache, createMutatorRunner, createReconnect, createSnapshotPrecondition, getErrorCode, getRetryAfterMs, httpStream, isAuthReplayFailure, isConflictError, isForbiddenError, isMutationDelta, isRateLimitedError, isUnauthorizedError, maxSeq, queryCacheKey, reconcileOptimistic };
1021
+ export { type AsyncStorageLike, type AsyncStoragePersistenceOptions, type AsyncStorageQueryCacheOptions, type BookmarkStorage, CONFLICT_ERROR_CODE, type ConnectLiveStreamOptions, type ConnectionStatus, type FunctionReference, type HttpStreamArgsOf, type HttpStreamChunkOf, type HttpStreamOptions, type HttpStreamRef, type IndexedDbPersistenceOptions, type IndexedDbQueryCacheOptions, type LiveStream, type LiveStreamEvent, type LiveStreamSubscribeOptions, LunoraClient, type MutationDelta, type MutatorHandle, type MutatorRunnerSinks, type MutatorTransaction, OfflineQueue, type OfflineQueueOptions, type OptimisticMessage, type PersistenceAdapter, type QueryCacheAdapter, type QueuedMutation, RETIRE_AFTER_DURABLE_SEQ_ADVANCE, type ReconcileDurableMessage, type ReconnectCalculator, type ReconnectOptions, type StreamIterable, type SubscriptionError, TabCoordinator, TransportError, applyDelta, connectLiveStream, createAsyncStoragePersistence, createAsyncStorageQueryCache, createCallRunner, createInMemoryBookmarkStorage, createInMemoryPersistence, createInMemoryQueryCache, createIndexedDbPersistence, createIndexedDbQueryCache, createMutatorRunner, createReconnect, createSnapshotPrecondition, getErrorCode, getRetryAfterMs, httpStream, isAuthReplayFailure, isConflictError, isForbiddenError, isMutationDelta, isRateLimitedError, isUnauthorizedError, maxSeq, queryCacheKey, reconcileOptimistic };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{RETIRE_AFTER_DURABLE_SEQ_ADVANCE as o,maxSeq as t,reconcileOptimistic as a}from"./packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs";import{createAsyncStoragePersistence as n}from"./packem_shared/createAsyncStoragePersistence-6FCvqc6C.mjs";import{createAsyncStorageQueryCache as i}from"./packem_shared/createAsyncStorageQueryCache-f5023fdB.mjs";import{default as f}from"./packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs";import{createCallRunner as x}from"./packem_shared/createCallRunner-Bwcrfh76.mjs";import{createClientQuery as l}from"./packem_shared/createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as d}from"./packem_shared/TabCoordinator-CXD7vulJ.mjs";import{a as R,i as C}from"./packem_shared/delta-merge-Ls3DED4g.mjs";import{CONFLICT_ERROR_CODE as S,TransportError as h,getErrorCode as D,getRetryAfterMs as Q,isAuthReplayFailure as _,isConflictError as F,isForbiddenError as I,isRateLimitedError as M,isUnauthorizedError as g}from"./packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as O}from"./packem_shared/httpStream-BhSpxRWB.mjs";import{c as b}from"./packem_shared/local-store-fqWV2n_Z.mjs";import{LunoraClient as U}from"./packem_shared/LunoraClient-C7RQBwz0.mjs";import{createMutatorRunner as k}from"./packem_shared/createMutatorRunner-CuMRJpUx.mjs";import{O as N}from"./packem_shared/offline-queue-D_fr-uQ3.mjs";import{createInMemoryPersistence as K,createIndexedDbPersistence as V}from"./packem_shared/createInMemoryPersistence-Cz2W6XVj.mjs";import{preloadQuery as j,preloadedQueryResult as v}from"./packem_shared/preloadQuery-uFy24PCR.mjs";import{createInMemoryQueryCache as G,createIndexedDbQueryCache as H,queryCacheKey as J}from"./packem_shared/createInMemoryQueryCache-D2uNHLfM.mjs";import{createReconnect as Y}from"./packem_shared/createReconnect-CjTmjJDH.mjs";import{default as $}from"./packem_shared/createSnapshotPrecondition-CLkxVeN1.mjs";import{DEFAULT_MAX_BUFFER as re,createStream as oe}from"./packem_shared/DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";import{SubscriptionRegistry as ae}from"./packem_shared/SubscriptionRegistry-DKIXE7M7.mjs";export{S as CONFLICT_ERROR_CODE,re as DEFAULT_MAX_BUFFER,U as LunoraClient,N as OfflineQueue,o as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,ae as SubscriptionRegistry,d as TabCoordinator,h as TransportError,R as applyDelta,n as createAsyncStoragePersistence,i as createAsyncStorageQueryCache,x as createCallRunner,l as createClientQuery,f as createInMemoryBookmarkStorage,K as createInMemoryPersistence,G as createInMemoryQueryCache,V as createIndexedDbPersistence,H as createIndexedDbQueryCache,b as createLocalStore,k as createMutatorRunner,Y as createReconnect,$ as createSnapshotPrecondition,oe as createStream,D as getErrorCode,Q as getRetryAfterMs,O as httpStream,_ as isAuthReplayFailure,F as isConflictError,I as isForbiddenError,C as isMutationDelta,M as isRateLimitedError,g as isUnauthorizedError,t as maxSeq,j as preloadQuery,v as preloadedQueryResult,J as queryCacheKey,a as reconcileOptimistic};
1
+ import{RETIRE_AFTER_DURABLE_SEQ_ADVANCE as o,maxSeq as t,reconcileOptimistic as a}from"./packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs";import{createAsyncStoragePersistence as n}from"./packem_shared/createAsyncStoragePersistence-6FCvqc6C.mjs";import{createAsyncStorageQueryCache as p}from"./packem_shared/createAsyncStorageQueryCache-f5023fdB.mjs";import{default as f}from"./packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs";import{createCallRunner as x}from"./packem_shared/createCallRunner-Bwcrfh76.mjs";import{createClientQuery as l}from"./packem_shared/createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as d}from"./packem_shared/TabCoordinator-CXD7vulJ.mjs";import{a as R,i as C}from"./packem_shared/delta-merge-Ls3DED4g.mjs";import{CONFLICT_ERROR_CODE as A,TransportError as h,getErrorCode as D,getRetryAfterMs as Q,isAuthReplayFailure as _,isConflictError as F,isForbiddenError as I,isRateLimitedError as L,isUnauthorizedError as M}from"./packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as O}from"./packem_shared/httpStream-BhSpxRWB.mjs";import{connectLiveStream as b}from"./packem_shared/connectLiveStream-73E_egA7.mjs";import{c as U}from"./packem_shared/local-store-fqWV2n_Z.mjs";import{LunoraClient as k}from"./packem_shared/LunoraClient-1GSUcavS.mjs";import{createMutatorRunner as N}from"./packem_shared/createMutatorRunner-CuMRJpUx.mjs";import{O as z}from"./packem_shared/offline-queue-D_fr-uQ3.mjs";import{createInMemoryPersistence as V,createIndexedDbPersistence as X}from"./packem_shared/createInMemoryPersistence-Cz2W6XVj.mjs";import{preloadQuery as w,preloadedQueryResult as G}from"./packem_shared/preloadQuery-uFy24PCR.mjs";import{createInMemoryQueryCache as J,createIndexedDbQueryCache as W,queryCacheKey as Y}from"./packem_shared/createInMemoryQueryCache-D2uNHLfM.mjs";import{createReconnect as $}from"./packem_shared/createReconnect-CjTmjJDH.mjs";import{default as re}from"./packem_shared/createSnapshotPrecondition-CLkxVeN1.mjs";import{DEFAULT_MAX_BUFFER as te,createStream as ae}from"./packem_shared/DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";import{SubscriptionRegistry as ne}from"./packem_shared/SubscriptionRegistry-DKIXE7M7.mjs";export{A as CONFLICT_ERROR_CODE,te as DEFAULT_MAX_BUFFER,k as LunoraClient,z as OfflineQueue,o as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,ne as SubscriptionRegistry,d as TabCoordinator,h as TransportError,R as applyDelta,b as connectLiveStream,n as createAsyncStoragePersistence,p as createAsyncStorageQueryCache,x as createCallRunner,l as createClientQuery,f as createInMemoryBookmarkStorage,V as createInMemoryPersistence,J as createInMemoryQueryCache,X as createIndexedDbPersistence,W as createIndexedDbQueryCache,U as createLocalStore,N as createMutatorRunner,$ as createReconnect,re as createSnapshotPrecondition,ae as createStream,D as getErrorCode,Q as getRetryAfterMs,O as httpStream,_ as isAuthReplayFailure,F as isConflictError,I as isForbiddenError,C as isMutationDelta,L as isRateLimitedError,M as isUnauthorizedError,t as maxSeq,w as preloadQuery,G as preloadedQueryResult,Y as queryCacheKey,a as reconcileOptimistic};
@@ -0,0 +1 @@
1
+ import{LunoraError as y}from"@lunora/errors";import{encodeWire as M,decodeWire as T,stableWireKey as ae}from"@lunora/wire";import{r as Fe,U as Le,P as He}from"./delta-merge-Ls3DED4g.mjs";import Me from"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import{s as Y,a as Ue,e as N,r as Ne,b as ce,c as xe,d as de}from"./wire-errors-WYlbE1Nh.mjs";import{ClientQueryStore as De}from"./createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as Be}from"./TabCoordinator-CXD7vulJ.mjs";import{TransportError as H,getRetryAfterMs as Qe,AUTH_REPLAY_ERROR_CODES as We,isAuthReplayFailure as K}from"./CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as qe}from"./httpStream-BhSpxRWB.mjs";import{d as X,r as O,a as P,b as Ke,c as je,e as Ge,f as $e}from"./local-store-fqWV2n_Z.mjs";import{O as Ve,n as he,i as ze,r as Je}from"./offline-queue-D_fr-uQ3.mjs";import{resolvePersistenceAdapter as Ye}from"./createInMemoryPersistence-Cz2W6XVj.mjs";import{resolveQueryCacheAdapter as Xe,queryCacheKey as _}from"./createInMemoryQueryCache-D2uNHLfM.mjs";import{createReconnect as ue}from"./createReconnect-CjTmjJDH.mjs";import{fanSubscriptionError as A,SubscriptionRegistry as C,wrapSubscriber as j}from"./SubscriptionRegistry-DKIXE7M7.mjs";import Ze from"./createSnapshotPrecondition-CLkxVeN1.mjs";import{createStream as et}from"./DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";const G=500,ge=(i,e)=>{if(i.size<e)return;const t=i.keys().next().value;t!==void 0&&i.delete(t)},k="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",tt=i=>{let e="",t=0;const s=i.length-2;for(;t<s;t+=3){const n=i[t]<<16|i[t+1]<<8|i[t+2];e+=k.charAt(n>>18&63)+k.charAt(n>>12&63)+k.charAt(n>>6&63)+k.charAt(n&63)}const r=i.length-t;if(r===1){const n=i[t]<<16;e+=k.charAt(n>>18&63)+k.charAt(n>>12&63)}else if(r===2){const n=i[t]<<16|i[t+1]<<8;e+=k.charAt(n>>18&63)+k.charAt(n>>12&63)+k.charAt(n>>6&63)}return e};new TextDecoder;const st=new TextEncoder,rt=i=>tt(st.encode(JSON.stringify(i))),it="x-lunora-expect-subject",nt=i=>rt({subject:i}),le=Symbol.for("lunora:session-change"),ot="lunora:session-change",at="better-auth.message",ct="signout",ve=()=>{const i=globalThis;let e=i[le];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},i[le]=e),e},dt=()=>"document"in globalThis,ht=async()=>{const i=[];for(const e of ve().listeners)try{i.push(e())}catch{}await Promise.allSettled(i)},ut=(i,e)=>{if(i!==at||e===null)return!1;try{const t=JSON.parse(e);return t?.event==="session"&&t.data?.trigger===ct}catch{return!1}},lt=i=>{const e=[],t=()=>{ht().catch(()=>{})};let s;try{s=typeof BroadcastChannel=="function"?new BroadcastChannel(ot):void 0}catch{s=void 0}if(s!==void 0){const n=s;n.addEventListener("message",a=>{a.data?.type==="lunora:session-change"&&a.data.tab!==i&&t()}),e.push(()=>{n.close()})}const r=globalThis;if(typeof r.addEventListener=="function"){const n=a=>{ut(a.key,a.newValue)&&t()};r.addEventListener("storage",n),e.push(()=>{r.removeEventListener?.("storage",n)})}return()=>{for(const n of e)n()}},ft=i=>{const e=ve();return e.listeners.add(i),e.detach===void 0&&dt()&&(e.detach=lt(e.tab)),()=>{e.listeners.delete(i),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},pt="/_lunora/rpc",$="/_lunora/rpc-batch",mt="/_lunora/ws",yt="/_lunora/admin/shard-traffic",St="/_lunora/admin/scheduled",bt="/_lunora/admin/scheduled/status",gt="/_lunora/admin/scheduled/ws",vt="/_lunora/admin/scheduled/cancel",fe="/_lunora/admin/scheduled/dead",Tt="/_lunora/admin/scheduled/dead/retry",Ct="/_lunora/admin/scheduled/dead/cancel",kt="/_lunora/admin/workflows/instances",wt="/_lunora/admin/workflows/instance",Et="/_lunora/admin/workflows/status",se="/_lunora/admin/storage",At="/_lunora/admin/storage/url",_t="/_lunora/admin/storage/buckets",It="/_lunora/admin/functions",Ot="/_lunora/admin/cron-jobs",Rt="/_lunora/admin/cron-jobs/run",Pt="/_lunora/admin/architecture",Ft="/_lunora/admin/openapi",Lt="/_lunora/admin/openrpc",Ht="/_lunora/admin/global/tables",Mt="/_lunora/admin/global/table",Ut="/_lunora/admin/global/facet",Nt="/_lunora/admin/vector/indexes",xt="/_lunora/admin/vector/query",Dt="/_lunora/admin/logs/archive",Bt="/_lunora/admin/kv/namespaces",Qt="/_lunora/admin/kv/keys",re="/_lunora/admin/kv/value",Wt="/_lunora/admin/auth/users",qt="/_lunora/admin/auth/sessions",Kt="/_lunora/admin/auth/users/create",jt="/_lunora/admin/auth/users/role",Gt="/_lunora/admin/auth/users/ban",$t="/_lunora/admin/auth/users/unban",Vt="/_lunora/admin/auth/users/password",zt="/_lunora/admin/auth/users/remove",Jt="/_lunora/admin/auth/users/impersonate",Yt="/_lunora/admin/auth/sessions/revoke",Xt="/_lunora/admin/auth/sessions/revoke-all",Zt="/_lunora/admin/auth/capabilities",es="/_lunora/admin/auth/users/update",ts="/_lunora/admin/auth/accounts",ss="/_lunora/admin/auth/accounts/unlink",rs="/_lunora/admin/auth/passkeys",is="/_lunora/admin/auth/passkeys/delete",ns="/_lunora/admin/auth/two-factor/disable",os="/_lunora/admin/auth/organizations",as="/_lunora/admin/auth/organizations/members",cs="/_lunora/admin/auth/organizations/invitations",ds="/_lunora/admin/auth/organizations/members/remove",hs="/_lunora/admin/auth/organizations/invitations/cancel",us="/_lunora/admin/auth/config",ls="/_lunora/admin/auth/sign-up-invitations",fs="/_lunora/admin/auth/sign-up-invitations/create",ps="/_lunora/admin/auth/sign-up-invitations/revoke",ms="/_lunora/admin/auth/organizations/create",ys="/_lunora/admin/auth/organizations/update",Ss="/_lunora/admin/auth/organizations/remove",bs="/_lunora/admin/auth/organizations/members/add",gs="/_lunora/admin/auth/organizations/members/invite",vs="/_lunora/admin/auth/organizations/members/role",Ts="/_lunora/admin/auth/organizations/teams",Cs="/_lunora/admin/auth/organizations/teams/create",ks="/_lunora/admin/auth/organizations/teams/update",ws="/_lunora/admin/auth/organizations/teams/remove",Es="/_lunora/admin/auth/organizations/teams/members",As="/_lunora/admin/auth/organizations/teams/members/add",_s="/_lunora/admin/auth/organizations/teams/members/remove",Is="/_lunora/admin/auth/organizations/roles",Os="/_lunora/admin/auth/organizations/roles/create",Rs="/_lunora/admin/auth/organizations/roles/update",Ps="/_lunora/admin/auth/organizations/roles/remove",Fs="/api/auth",Ls="/get-session",Hs="lunora-ping",Ms=async i=>(i.assertOpen(),(await i.adminFetch(It,"GET")).functions??[]),Us=async i=>(i.assertOpen(),(await i.adminFetch(Ot,"GET")).jobs??[]),Ns=async(i,e)=>{i.assertOpen();const t=await i.adminFetch(Rt,"POST",{name:e});return{name:t.name??e,ran:t.ran===!0}},xs=async i=>(i.assertOpen(),await i.adminFetch(Ft,"GET")),Ds=async i=>(i.assertOpen(),await i.adminFetch(Pt,"GET")),Bs=async i=>(i.assertOpen(),await i.adminFetch(Lt,"GET")),Qs=async i=>(i.assertOpen(),await i.adminFetch(Ht,"GET")),Ws=async(i,e)=>{i.assertOpen();const t=new URLSearchParams({table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(M(e.filters))),T(await i.adminFetch(`${Mt}?${t.toString()}`,"GET"))},qs=async(i,e)=>{i.assertOpen();const t=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(M(e.filters))),T(await i.adminFetch(`${Ut}?${t.toString()}`,"GET"))},ie=i=>i===void 0||i===""?"":`&bucket=${encodeURIComponent(i)}`,pe=i=>i.startsWith("https://")?`wss://${i.slice(8)}`:i.startsWith("http://")?`ws://${i.slice(7)}`:i,w=(i,e)=>`${i.endsWith("/")?i.slice(0,-1):i}${e}`,b=(i,e)=>{const t=new URLSearchParams;for(const[r,n]of Object.entries(e))n!==void 0&&n!==""&&t.set(r,String(n));const s=t.toString();return s===""?i:`${i}?${s}`},Ks=async i=>(i.assertOpen(),(await i.adminFetch(Bt,"GET")).namespaces??[]),js=async(i,e)=>{i.assertOpen();const t=b(Qt,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await i.adminFetch(t,"GET")},Gs=async(i,e)=>{i.assertOpen();const t=b(re,{key:e.key,namespace:e.namespace});return await i.adminFetch(t,"GET")},$s=async(i,e)=>{i.assertOpen(),await i.adminFetch(re,"PUT",e)},Vs=async(i,e)=>{i.assertOpen();const t=b(re,{key:e.key,namespace:e.namespace});await i.adminFetch(t,"DELETE")},zs=async(i,e)=>{i.assertOpen();const t=await i.adminFetch(yt,"POST",{table:e});return{failed:t.failed??0,ok:t.ok??0,shards:t.shards??[]}},Js=async(i,e={})=>{i.assertOpen();const t=await i.adminFetch(Dt,"POST",e);return{nextCursor:t.nextCursor,rows:t.rows??[]}},Ys=async i=>{const e=[];let t;for(;;){const s=await i(t);if(e.push(...Array.isArray(s.records)?s.records:[]),s.truncated!==!0||typeof s.cursor!="string"||s.cursor.length===0)return e;if(s.cursor===t)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");t=s.cursor}},ne=i=>"args"in i?{...i,args:T(i.args)}:i,Xs=async i=>(i.assertOpen(),((await i.adminFetch(St,"GET")).records??[]).map(t=>ne(t))),Zs=async i=>{i.assertOpen();const e=await i.adminFetch(bt,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},er=async(i,e)=>(i.assertOpen(),{cancelled:(await i.adminFetch(vt,"POST",{id:e})).cancelled===!0}),tr=async i=>(i.assertOpen(),(await Ys(async t=>await i.adminFetch(t===void 0?fe:`${fe}?cursor=${encodeURIComponent(t)}`,"GET"))).map(t=>ne(t))),sr=async(i,e)=>(i.assertOpen(),{retried:(await i.adminFetch(Tt,"POST",{id:e})).retried===!0}),rr=async(i,e)=>(i.assertOpen(),{removed:(await i.adminFetch(Ct,"POST",{id:e})).removed===!0}),ir=async(i,e)=>{i.assertOpen();const t=new URLSearchParams({name:e.name});e.status!==void 0&&t.set("status",e.status),e.page!==void 0&&t.set("page",String(e.page)),e.perPage!==void 0&&t.set("perPage",String(e.perPage));const s=await i.adminFetch(`${kt}?${t.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}},nr=async(i,e)=>{i.assertOpen();const t=new URLSearchParams({id:e.id,name:e.name}),s=await i.adminFetch(`${wt}?${t.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??e.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}},or=async(i,e)=>(i.assertOpen(),{status:(await i.adminFetch(Et,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),ar=async(i,e={})=>{i.assertOpen();const t=b(se,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await i.adminFetch(t,"GET");return{cursor:s.cursor,objects:s.objects??[]}},cr=async(i,e,t)=>{i.assertOpen();const s=`${se}?key=${encodeURIComponent(e)}${ie(t?.bucket)}`,r=await i.adminFetch(s,"DELETE");return{deleted:r.deleted===!0,key:r.key??e}},dr=async i=>(i.assertOpen(),(await i.adminFetch(_t,"GET")).buckets??[]),hr=async(i,e)=>{i.assertOpen();const t=`${se}?key=${encodeURIComponent(e.key)}${ie(e.bucket)}`,s=await i.adminFetch(t,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}},ur=async(i,e,t)=>{i.assertOpen();const s=t?.expiresInSeconds,r=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,n=`${At}?key=${encodeURIComponent(e)}${r}${ie(t?.bucket)}`,a=await i.adminFetch(n,"GET");if(typeof a.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return a.url},lr=async i=>(i.assertOpen(),(await i.adminFetch(Nt,"GET")).indexes??[]),fr=async(i,e)=>(i.assertOpen(),(await i.adminFetch(xt,"POST",e)).matches??[]),E=(i,e)=>{try{return M(i)}catch(t){const s=t instanceof Error?t.message:String(t);throw new TypeError(`LunoraClient: cannot encode ${e} — ${s}`,t instanceof Error?{cause:t}:void 0)}},me=i=>{try{return M(i),!0}catch{return!1}},Te=i=>i!==null&&typeof i=="object"&&("error"in i||"result"in i),pr=(i,e)=>{const t=Array.from({length:e});for(const s of i){if(typeof s.id!="number"||s.id<0||s.id>=e)continue;if(!Te(s.body)){t[s.id]={error:Y({}),ok:!1};continue}const r=s.body;t[s.id]="error"in r?{error:Y(r),ok:!1}:{ok:!0,value:T(r.result)}}return t.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},V=(i,e)=>e!==null?{}:i===null?{expectSubject:null}:i?.startsWith("subj:")===!0?{expectSubject:i.slice(5)}:{},mr=3e4,yr=1e4,Sr=5e3,br=3,gr=250,vr=5e3,Tr=5e3,Cr=64,kr=3,wr=1e4,Er=8,z=i=>i==="connected"||i==="polling",l=i=>i??"",v=(i,e)=>{if(!i.socket||i.wsState!=="open")return!1;try{return i.socket.send(JSON.stringify(e)),!0}catch{return!1}},Ar=i=>{if(!i.pendingStreams||i.pendingStreams.length===0)return;const e=i.pendingStreams;i.pendingStreams=[];for(const t of e)v(i,t)},_r=new TextDecoder,Ir=i=>{if(typeof i=="string")return i;if(i instanceof ArrayBuffer)return _r.decode(i)};class I{listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){const[t]=e;for(const s of this.listeners)try{s(t)}catch{}}clear(){this.listeners.clear()}}const L=i=>{i.heartbeatTimer!==void 0&&(clearInterval(i.heartbeatTimer),i.heartbeatTimer=void 0)},Or=(i,e,t)=>{L(i),!(e<=0)&&(i.heartbeatTimer=setInterval(()=>{if(!i.socket)return;const{socket:s}=i;if(Date.now()-i.lastFrameAt>e*2.5){try{s.close()}catch{}t();return}try{s.send(Hs)}catch{}},e))},ye=(i,e,t,s)=>{const{WebSocketImpl:r,connectTimeoutMs:n,heartbeatIntervalMs:a}=t;if(r===void 0)throw new y("INTERNAL","no WebSocket implementation available");const o=new r(e);i.socket=o;const c=()=>{L(i),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),i.socket===o&&(i.socket=void 0)},d=u=>{c(),s.onClose(u)};n>0&&(i.connectTimer=setTimeout(()=>{if(i.connectTimer=void 0,i.socket===o){try{o.close()}catch{}d()}},n)),o.addEventListener("open",()=>{if(i.socket===o){i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),i.lastFrameAt=Date.now();try{s.onOpen?.()}catch(u){console.error("[lunora] connection open handler threw",u)}Or(i,a,d)}}),o.addEventListener("message",u=>{if(i.socket===o){i.lastFrameAt=Date.now();try{s.onMessage(u)}catch(h){console.error("[lunora] server frame handler threw",h)}}}),o.addEventListener("close",u=>{i.socket===o&&d(u)}),o.addEventListener("error",()=>{i.socket===o&&d()})},Rr=i=>{const{afterFailedAttempts:e,intervalMs:t,onReachable:s,onStateChange:r,poll:n}=i,a=t>0&&e>0;let o=0,c,d=!1,u=!1;const h=()=>{c!==void 0&&(clearInterval(c),c=void 0,d=!1,r())},p=f=>{if(c!==void 0){if(!f){h();return}d||(d=!0,r()),s()}},m=()=>{u||(u=!0,n().then(p).finally(()=>{u=!1}).catch(()=>{}))};return{isPolling:()=>c!==void 0&&d,noteFailedOpen:()=>{o+=1,!(!a||c!==void 0||o<e)&&(c=setInterval(m,t),r(),m())},noteOpen:()=>{o=0,h()},stop:h}},Pr=1e4,Se=async i=>{const e=new AbortController;let t;const s=new Promise((r,n)=>{t=setTimeout(()=>{e.abort(),n(new TypeError("LunoraClient: poll timed out"))},Pr)});try{return await Promise.race([i(e.signal),s])}catch(r){throw e.signal.aborted?new TypeError("LunoraClient: poll timed out"):r}finally{clearTimeout(t)}},Ce=new Set(["DELIVERY_FENCED","RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Fr=i=>{if(i instanceof H)return!0;const e=i?.code;return e===void 0||Ce.has(e)||We.has(e)},ke=6e4,Lr=1e3,Hr={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},F=(i,e,t)=>{const s=Ue(t),r=s===void 0?void 0:{retryAfterMs:s},n=`LunoraClient: response carried no error envelope (status ${i.toString()}${e?` ${e}`:""})`;return i<400||i>=500||i===408?new H(n,r):new y(Hr[i]??"BAD_REQUEST",n,{data:r})},Z=(i,e=Math.random)=>{const t=Math.min(Lr*2**Math.max(i-1,0),ke);return Math.round(t*(.5+e()*.5))},Mr=i=>i instanceof H||Ce.has(i?.code??""),Ur=(i,e,t)=>{const s=Qe(i);return s!==void 0&&s>0?Math.min(s,ke):Mr(i)?Z(e,t):void 0},Nr=983040,xr=i=>typeof TextEncoder>"u"?i.length:new TextEncoder().encode(i).length,we=new WeakSet,Ee=i=>{const e=new y("WIRE_DECODE_FAILED",`LunoraClient: the call succeeded but its result could not be decoded (a mutation has still committed) — ${i instanceof Error?i.message:String(i)}`,{cause:i});return we.add(e),e},x=i=>i instanceof Error&&we.has(i),Dr=i=>{const e=new Map;for(const t of i)typeof t.id=="number"&&Te(t.body)&&e.set(t.id,t.body);return e},Br=i=>{if(i===void 0)return{kind:"unanswered"};if("error"in i)return{error:Y(i),kind:"errored"};try{return{commitCursor:i.commitCursor,kind:"committed",value:T(i.result)}}catch(e){return{commitCursor:i.commitCursor,error:Ee(e),kind:"undecodable"}}},J=(i,e)=>`${l(i)}\0${e}`,Qr=(i,e)=>{for(const t of e)t.op==="delete"?i.delete(t.key):t.value!==void 0&&i.set(t.key,t.value)};class Wr{constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,t){ge(this.buffers,this.maxBuffers),this.buffers.set(J(e,t.pokeId),{baseCheckpoint:t.baseCheckpoint,bases:new Map,epoch:t.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}part(e,t){const s=this.buffers.get(J(e,t.pokeId));if(!s)return;const r=[];try{for(const o of t.rowsPatch)r.push(o.value===void 0?o:{...o,value:T(o.value)})}catch(o){s.undecodable.set(t.shapeId,o);return}const n=s.parts.get(t.shapeId)??[];for(const o of r)n.push(o);s.parts.set(t.shapeId,n),t.lastMutationId!==void 0&&s.lastMutationId.set(t.shapeId,t.lastMutationId);const a=t.baseCheckpoint??s.baseCheckpoint;a!==void 0&&s.bases.set(t.shapeId,a),t.reset===!0&&s.resets.add(t.shapeId)}end(e,t){const s=J(e,t),r=this.buffers.get(s);return r&&this.buffers.delete(s),r}clear(){this.buffers.clear()}}const qr=(i,e,t)=>{const s=e.parts.get(i.id)??[],r=e.resets.has(i.id),n=e.bases.get(i.id),a=e.epoch!==void 0&&i.serverEpoch!==void 0&&e.epoch!==i.serverEpoch,o=n!==void 0&&i.serverCursor!==void 0&&i.serverCursor!==n;if(!r&&(a||o))return i.rows.clear(),i.serverCursor=void 0,i.serverEpoch=void 0,"reseed";r&&i.rows.clear(),Qr(i.rows,s),t.checkpoint!==void 0&&(i.serverCursor=t.checkpoint),t.epoch!==void 0&&(i.serverEpoch=t.epoch);const c=e.lastMutationId.get(i.id);return c!==void 0&&(i.lastMutationId=c),"applied"},be=i=>{const e=[...i.rows.values()];for(const t of i.callbacks)try{t(e)}catch{}},Kr=(i,e)=>{for(const[t,s]of e.undecodable){const r=i.get(t);r&&A(r.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape — ${s instanceof Error?s.message:String(s)}`})}},ee=(i,e)=>{i.lastMutationId=Math.max(i.lastMutationId??0,e)},te=(i,e=!1)=>{for(const t of i.checkpointCallbacks)t({checkpoint:i.serverCursor,mutationId:i.lastMutationId,...e&&{rowsFollow:!0}})},Ae=(i,e,t)=>{i.serverBase=e,t.cursor!==void 0&&(i.serverCursor=t.cursor),t.epoch!==void 0&&(i.serverEpoch=t.epoch)},D=(i,e)=>i!==void 0&&i!==e,jr=(i,e)=>e==="connected"&&i!=="connected"||e==="polling"&&i!=="connected"&&i!=="polling",Gr=i=>{for(const e of i.activeSubscriptions())i.ensureSocket(e.shardKey),i.queueResubscribe(e);for(const e of i.queuedShardKeys())i.ensureSocket(e);i.broadcastStatus(i.computeStatus(),i.identityFingerprint())},$r=i=>{i.closeConnections();const e=i.leader;e.status=void 0,e.wasEverConnected=!1},Vr=(i,e,t)=>{if(D(t,i.identityFingerprint()))return;const s=i.leader,r=jr(s.status,e);s.status=e,e==="connected"&&(s.wasEverConnected=!0),i.emitConnectionStatus(),r&&i.flushOfflineQueues()},zr=i=>{i.isLeader()&&i.broadcastStatus(i.computeStatus(),i.identityFingerprint())},Jr=(i,e,t,s,r,n)=>{if(D(n,i.identityFingerprint()))return;const a=i.subscription(e);a&&(i.dropCacheSeed(e),Ae(a,t,s===void 0?{}:{cursor:s,epoch:r}),s!==void 0&&X(a,s),O(a,t))},Yr=(i,e,t,s)=>{if(D(s,i.identityFingerprint()))return;const r=i.subscription(e);r&&A(r.errorCallbacks,t)},Xr=(i,e,t,s,r,n,a)=>{if(D(a,i.identityFingerprint()))return;const o=i.subscription(e);o&&(i.ackAndAdvanceCursor(o,t,s),r!==void 0&&n===i.clientIdentifier()&&ee(o,r),te(o))},Zr=(i,e,t)=>i!==null||e&&t===null,ei=[He],ti=100,_e=1e4,si=async(i,e,t,s)=>{const r=new AbortController,n=setTimeout(()=>{r.abort()},_e);try{const a=await i(e,{body:t,credentials:"include",headers:s,method:"POST",signal:r.signal});return await a.text(),a.status}finally{clearTimeout(n)}},ri=Promise.resolve();class Ie{static MAX_POKE_BUFFERS=256;static createClientQuery(e,t){return{defaultValue:t,key:e}}url;wsUrl;adminHost={adminFetch:(...e)=>this.adminFetch(...e),assertOpen:()=>{this.assertOpen()}};clientQueryStore;wsToken;wsTokenGeneration=0;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new C;tabCoordinator;leader={status:void 0,wasEverConnected:!1};connections=new Map;idleClosedShards=new Set;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;subjectToken=null;sessionProbesInFlight=0;sessionProbeGeneration=0;identityQuestions=0;identityAnsweredAt=0;releaseSessionChangeListener;warnedIdentityDisagreement=!1;identityResolutionExpected=!1;identitySettled=!1;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new I;statusListeners=new I;roomFlushes=new Map;roomIdentityResets=new Set;tokenExpiredListeners=new I;identityChangeListeners=new I;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new I;pendingChangeListeners=new I;whisperHandlers=new Map;liveSocketGrants=new Map;liveControlChain=Promise.resolve();whisperJoins=new Map;nextLiveSocketId=0;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new Wr(Ie.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??w(pe(e.url),mt),this.wsToken=e.wsToken;const t=e.authBasePath??Fs;this.authBasePath=t.endsWith("/")?t.slice(0,-1):t,this.fetchImpl=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=e.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=e.bookmarkStorage??Me(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??mr,this.connectTimeoutMs=e.connectTimeoutMs??yr,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??Sr,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??br,this.defaultConnectionContext=e.connectionContext,this.persistence=Ye(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Xe(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new De,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=ri),this.offlineQueue=new Ve(e.offlineQueue,{onEvict:(s,r)=>{this.emitItemSettled(s,"rejected",r),this.releaseIdleShard(s.shardKey)},onSizeChange:s=>{this.pendingChangeListeners.emit(s)},persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${he()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=ft(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,t){const s=this.authToken!==e,r=this.identityFingerprint(),n=this.authSubject===void 0||this.subjectToken===this.authToken,a=this.subjectAwaitingReconfirm(),o=this.isKnownNobody(),c=this.authToken;this.authToken=e,this.applySubject(e,t);const d=this.identityFingerprint();d!==r&&(!s&&e!==null&&n?(this.restampQueuedIdentity(r,d),this.restampWatermarks(r,d),this.restampConnectionIdentity(r,d),this.reseedFromHydratedCache()):!s&&e===null&&r===null&&n&&!o?(this.restampWatermarks(r,d),this.restampConnectionIdentity(r,d),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(r),this.warnRefreshWithoutSubject(c,e),Zr(r,o,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(a),s&&this.authTokenListeners.emit(e),(d!==r||s||a)&&this.offlineQueue.size>0&&z(this.computeStatus())&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}expectIdentityResolution(){this.identityResolutionExpected=!0}currentBaseline(e){return this.baselineCursorFor(e)}replayIdentityVerdict(e){const t=this.identityVerdict(e);if(t!=="match")return{verdict:t};const s=Object.freeze({});return this.replayCredentials.set(s,{authToken:this.authToken,stamp:e}),{credential:s,verdict:t}}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,t,s){const r=s?.clientSeq;if(r!==void 0&&(!Number.isInteger(r)||r<=0))throw new y("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(r)}`);const n=s?.shardKey??"",a=this.identityFingerprint();let o,c,d;try{c=await this.rpc(e,t,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:r,onMutationAck:h=>{o=h}})}catch(h){if(!x(h))throw h;d=h}if(o!==void 0&&o>(this.clientWatermarks.get(a??"")?.get(n)??0)){let h=this.clientWatermarks.get(a??"");h===void 0&&(ge(this.clientWatermarks,Er),h=new Map,this.clientWatermarks.set(a??"",h)),h.set(n,o)}if(d!==void 0)throw d;return{applied:o===void 0||o===r,result:c}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}onIdentityChange(e){return this.identityChangeListeners.add(e)}identityEpoch(){return this.retiredIdentities}async getCurrentUser(){if(this.identityResolutionExpected=!0,this.closed||!this.fetchImpl)return this.identitySettled=!0,null;const e={},t=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`),this.sessionProbesInFlight+=1,this.identityQuestions+=1,this.sessionProbeGeneration=this.identityQuestions;const s=this.sessionProbeGeneration;try{const r=await this.fetchImpl(w(this.url,`${this.authBasePath}${Ls}`),{credentials:"include",headers:e,method:"GET"});if(!r.ok)return this.identitySettled=!0,r.status===401&&this.adoptResolvedSubject(t,null,s),null;const a=(await r.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(t,a,s),a}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.wsTokenGeneration+=1,this.resetRoomSends(),this.bounceShardSockets())}setConnectionContext(e,t={}){this.assertLeaderOwnedSurface("setConnectionContext");const s=l(t.shardKey);e===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,e),this.refreshConnectionContext(s),e===void 0&&this.releaseIdleShard(t.shardKey)}acquireConnectionContext(e,t={}){if(this.followsAnotherTab())return()=>{};const s=l(t.shardKey),r={context:e},n=this.connectionContextHolders.get(s);n?n.push(r):this.connectionContextHolders.set(s,[r]),this.refreshConnectionContext(s);let a=!1;return()=>{if(a)return;a=!0;const o=this.connectionContextHolders.get(s);if(!o)return;const c=o.indexOf(r);c!==-1&&o.splice(c,1),o.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s),this.releaseIdleShard(t.shardKey)}}whisperSubscribe(e,t,s={}){this.assertLeaderOwnedSurface("whisperSubscribe");const r=l(s.shardKey);let n=this.whisperHandlers.get(r);n||(n=new Map,this.whisperHandlers.set(r,n));let a=n.get(e);const o=a===void 0;if(a||(a=new Set,n.set(e,a)),a.add(t),this.ensureSocket(s.shardKey),o){const c=this.getConnection(s.shardKey);c&&this.sendWhisperJoin(c,r,e)}return()=>{const c=this.whisperHandlers.get(r),d=c?.get(e);if(!d?.delete(t)||d.size>0)return;c?.delete(e),c?.size===0&&this.whisperHandlers.delete(r);const u=this.getConnection(s.shardKey);u&&v(u,{topic:e,type:"whisper_unsubscribe"}),this.releaseIdleShard(s.shardKey)}}subscribeLiveTopic(e){const{onError:t,onEvent:s,shardKey:r,stream:n,topic:a}=e;if(a.length===0)throw new y("INTERNAL","LunoraClient: subscribeLiveTopic needs a non-empty topic");this.nextLiveSocketId+=1;const o=`ws-live-${String(this.nextLiveSocketId)}`,c=l(r),d=`/live/${n}/control`,u=this.whisperSubscribe(a,()=>{},{shardKey:r});let h=this.liveSocketGrants.get(c);h===void 0&&(h=new Map,this.liveSocketGrants.set(c,h)),h.set(o,{onError:t,onEvent:s,stream:n,topic:a});const p=this.getConnection(r)?.connectionId;p!==void 0&&this.grantWhenJoined(r,o,p);let m=!1;return()=>{if(m)return;m=!0;const f=this.liveSocketGrants.get(c),S=f?.delete(o)===!0;f?.size===0&&this.liveSocketGrants.delete(c);const g=this.getConnection(r)?.connectionId;S&&g!==void 0&&this.postLiveControl(d,r,{action:"unsubscribe",connectionId:g,stream:n,subscriptionId:o,topic:a}),u()}}whisper(e,t,s={}){return this.assertLeaderOwnedSurface("whisper"),this.sendEncodedWhisper(e,E(t??null,`whisper data for topic '${e}'`),s)}connectRoom(e,t,s={}){const r=`room:${e.name}`,n=this.whisperSubscribe(r,p=>{t.onMessage(p)},s);let a=!1;const o=[],c=()=>{o.length=0},d=()=>{for(;o.length>0&&this.roomSendsAdmitted(s.shardKey);){if(!this.sendEncodedWhisper(r,o[0],s))return;o.shift()}},u=l(s.shardKey),h=this.roomFlushes.get(u)??new Set;return h.add(d),this.roomFlushes.set(u,h),this.roomIdentityResets.add(c),{close:()=>{a=!0,o.length=0,h.delete(d),h.size===0&&this.roomFlushes.delete(u),this.roomIdentityResets.delete(c),n()},send:p=>{if(a||this.closed||this.WebSocketImpl===void 0)return!1;const m=E(p,`room message for '${r}'`),f=typeof structuredClone=="function"?structuredClone(m):JSON.parse(JSON.stringify(m));return d(),o.length===0&&this.roomSendsAdmitted(s.shardKey)&&this.sendEncodedWhisper(r,f,s)?!0:o.length>=ti?!1:(o.push(f),!0)}}}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){const t=this.statusListeners.add(e);return e(this.computeStatus()),t}pendingCount(){return this.offlineQueue.size}debug(){const e=[],t=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...t?.keys()??[]]);for(const n of s){const a=this.connections.get(n);e.push({confirmedMutationWatermark:t?.get(n)??0,hasSocket:a?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:a?.wasEverConnected??!1,wsState:a?.wsState??"idle"})}const r=this.subscriptions.all().map(n=>({acked:n.acked,functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(const n of this.shapeSubscriptions.values())r.push({acked:n.serverCursor!==void 0,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,a)=>(n.shardKey??"").localeCompare(a.shardKey??"")),subscriptions:r.toSorted((n,a)=>n.functionPath.localeCompare(a.functionPath))}}onPendingChange(e){const t=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),t}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,t){this.clientQueryStore.set(e,t)}subscribeClientQuery(e,t){return this.clientQueryStore.subscribe(e,t)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,t,s){return Ze(this,e,t,s)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,t,s){return this.peekHydratedQueryByKey(e,ae(t),s)}peekHydratedQueryByKey(e,t,s){if(!this.readyResolved)return;const r=_(e,t,s),n=this.hydratedQueryCache.get(r);if(n!==void 0)return this.cachedQueryMatchesIdentity(n)?n.value:void 0}peekActiveQuerySnapshot(e,t,s){const r=C.key(e,t,s),n=this.subscriptions.get(r);return{present:n!==void 0,value:n?.lastValue}}async query(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0})}async batch(e){return this.sendBatch(e)}async mutation(e,t,s={}){const{value:r}=await this.runMutation(e,t,s);return r}canQueueOffline(e){const{wasEverConnected:t}=this.connectionGateState(e);return this.WebSocketImpl!==void 0&&(t||this.offlineQueue.queueBeforeFirstConnect)}async action(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0,captureBookmark:!0})}async importRows(e,t,s={}){this.assertOpen();const r=Math.max(1,Math.trunc(s.chunkSize??500)),n=s.toArgs??(u=>({rows:u})),a=t.length;let o=0,c=0,d=0;for(let u=0;u<a;u+=r){const h=t.slice(u,u+r),p=d,{committed:m}=await this.runMutation(e,n(h),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(p)}`},shardKey:s.shardKey});d+=1,o+=h.length,m&&(c+=h.length),s.onProgress?.({done:o,total:a})}return{chunks:d,imported:c,queued:o-c}}async shardTraffic(e){return zs(this.adminHost,e)}async listScheduledJobs(){return Xs(this.adminHost)}async schedulerStatus(){return Zs(this.adminHost)}async cancelScheduledJob(e){return er(this.adminHost,e)}async listDeadJobs(){return tr(this.adminHost)}async retryDeadJob(e){return sr(this.adminHost,e)}async removeDeadJob(e){return rr(this.adminHost,e)}async listWorkflowInstances(e){return ir(this.adminHost,e)}async getWorkflowInstance(e){return nr(this.adminHost,e)}async setWorkflowInstanceStatus(e){return or(this.adminHost,e)}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const t=w(pe(this.url),gt),s=ue(this.reconnectOptions),r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let n,a=!1;const o=()=>{a||this.closed||(n=setTimeout(u,s.next()))},c=p=>{if(a||this.WebSocketImpl===void 0)return;const m=p===void 0?t:`${t}?token=${encodeURIComponent(p)}`;ye(r,m,this.managedSocketOptions,{onClose:()=>{o()},onMessage:f=>{let S;try{S=JSON.parse(typeof f.data=="string"?f.data:"")}catch{return}S.type==="jobs"&&Array.isArray(S.records)&&(s.reset(),e(S.records.map(g=>ne(g))))}})},d=async p=>{let m;try{m=await p()}catch{o();return}c(m)},u=()=>{if(a||this.WebSocketImpl===void 0)return;const{wsToken:p}=this;if(typeof p=="function"){d(p).catch(()=>{});return}c(p)};u();const h=()=>{a=!0,n!==void 0&&(clearTimeout(n),n=void 0),r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),L(r),r.socket?.close(),r.socket=void 0};return this.adminSocketTeardowns.add(h),()=>{this.adminSocketTeardowns.delete(h),h()}}async listFunctions(){return Ms(this.adminHost)}async getCronJobs(){return Us(this.adminHost)}async runCronJob(e){return Ns(this.adminHost,e)}async fetchOpenApi(){return xs(this.adminHost)}async fetchArchitecture(){return Ds(this.adminHost)}async fetchOpenRpc(){return Bs(this.adminHost)}async listStorageObjects(e={}){return ar(this.adminHost,e)}async deleteStorageObject(e,t){return cr(this.adminHost,e,t)}async listStorageBuckets(){return dr(this.adminHost)}async uploadStorageObject(e){return hr(this.adminHost,e)}async signedStorageUrl(e,t){return ur(this.adminHost,e,t)}async listGlobalTables(){return Qs(this.adminHost)}async readGlobalTablePage(e){return Ws(this.adminHost,e)}async facetGlobalColumn(e){return qs(this.adminHost,e)}async listVectorIndexes(){return lr(this.adminHost)}async queryVectorIndex(e){return fr(this.adminHost,e)}async queryLogArchive(e={}){return Js(this.adminHost,e)}async listKvNamespaces(){return Ks(this.adminHost)}async listKvKeys(e){return js(this.adminHost,e)}async getKvValue(e){return Gs(this.adminHost,e)}async putKvValue(e){return $s(this.adminHost,e)}async deleteKvKey(e){return Vs(this.adminHost,e)}async listAuthUsers(e={}){this.assertOpen();const t=b(Wt,{filterField:e.filterField,filterValue:e.filterValue,limit:e.limit,offset:e.offset,search:e.search,searchField:e.searchField,sortBy:e.sortBy,sortDirection:e.sortDirection});return await this.adminFetch(t,"GET")}async createAuthUser(e){return this.assertOpen(),await this.adminFetch(Kt,"POST",e)}async setAuthUserRole(e){return this.assertOpen(),await this.adminFetch(jt,"POST",e)}async banAuthUser(e){return this.assertOpen(),await this.adminFetch(Gt,"POST",e)}async unbanAuthUser(e){return this.assertOpen(),await this.adminFetch($t,"POST",e)}async setAuthUserPassword(e){this.assertOpen(),await this.adminFetch(Vt,"POST",e)}async removeAuthUser(e){this.assertOpen(),await this.adminFetch(zt,"POST",e)}async impersonateAuthUser(e){return this.assertOpen(),await this.adminFetch(Jt,"POST",e)}async revokeAuthSession(e){this.assertOpen(),await this.adminFetch(Yt,"POST",e)}async revokeAuthUserSessions(e){this.assertOpen(),await this.adminFetch(Xt,"POST",e)}async getAuthCapabilities(){return this.assertOpen(),await this.adminFetch(Zt,"GET")}async updateAuthUser(e){return this.assertOpen(),await this.adminFetch(es,"POST",e)}async listAuthAccounts(e){return this.assertOpen(),await this.adminFetch(b(ts,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.assertOpen(),await this.adminFetch(ss,"POST",e)}async listAuthPasskeys(e){return this.assertOpen(),await this.adminFetch(b(rs,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.assertOpen(),await this.adminFetch(is,"POST",e)}async disableAuthTwoFactor(e){this.assertOpen(),await this.adminFetch(ns,"POST",e)}async listAuthOrganizations(e={}){return this.assertOpen(),await this.adminFetch(b(os,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.assertOpen();const t=b(as,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthOrgInvitations(e){this.assertOpen();const t=b(cs,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthSignUpInvitations(e={}){this.assertOpen();const t=b(ls,{limit:e.limit,offset:e.offset});return await this.adminFetch(t,"GET")}async createAuthSignUpInvitation(e){return this.assertOpen(),await this.adminFetch(fs,"POST",e)}async revokeAuthSignUpInvitation(e){this.assertOpen(),await this.adminFetch(ps,"POST",e)}async removeAuthOrgMember(e){this.assertOpen(),await this.adminFetch(ds,"POST",e)}async cancelAuthOrgInvitation(e){this.assertOpen(),await this.adminFetch(hs,"POST",e)}async getAuthConfig(){return this.assertOpen(),await this.adminFetch(us,"GET")}async createAuthOrganization(e){return this.assertOpen(),await this.adminFetch(ms,"POST",e)}async updateAuthOrganization(e){return this.assertOpen(),await this.adminFetch(ys,"POST",e)}async deleteAuthOrganization(e){this.assertOpen(),await this.adminFetch(Ss,"POST",e)}async addAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(bs,"POST",e)}async inviteAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(gs,"POST",e)}async setAuthOrgMemberRole(e){return this.assertOpen(),await this.adminFetch(vs,"POST",e)}async listAuthOrgTeams(e){this.assertOpen();const t=b(Ts,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(Cs,"POST",e)}async updateAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(ks,"POST",e)}async removeAuthOrgTeam(e){this.assertOpen(),await this.adminFetch(ws,"POST",e)}async listAuthOrgTeamMembers(e){this.assertOpen();const t=b(Es,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(t,"GET")}async addAuthOrgTeamMember(e){return this.assertOpen(),await this.adminFetch(As,"POST",e)}async removeAuthOrgTeamMember(e){this.assertOpen(),await this.adminFetch(_s,"POST",e)}async listAuthOrgRoles(e){this.assertOpen();const t=b(Is,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Os,"POST",e)}async updateAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Rs,"POST",e)}async deleteAuthOrgRole(e){this.assertOpen(),await this.adminFetch(Ps,"POST",e)}async listAuthSessions(e={}){this.assertOpen();const t=b(qt,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(t,"GET")}subscribe(e,t,s,r={}){this.assertOpen();const n=t??{},a=C.key(e.__lunoraRef,n,r.shardKey);let o=this.subscriptions.get(a);const c=j(s),d=j(r.onError),u=j(r.onCheckpoint);if(!o){this.nextSubId+=1;const p=`sub_${this.nextSubId.toString()}`,m=ae(n),f=this.takeHydratedCache(e.__lunoraRef,m,r.shardKey);o={acked:!1,args:n,argsKey:m,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:p,lastValue:f?.value,optimisticLayers:[],serverBase:f?.value,serverCursor:f?.serverCursor,shardKey:r.shardKey,wireArgs:E(n,`args for '${e.__lunoraRef}'`),...f?.serverEpoch===void 0?{}:{serverEpoch:f.serverEpoch}},this.subscriptions.add(o),f!==void 0&&this.cacheSeededQueries.set(a,f)}if(o.callbacks.add(c),d&&o.errorCallbacks.add(d),u&&o.checkpointCallbacks.add(u),o.lastValue!==void 0)try{c(o.lastValue)}catch{}this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(o);const h=o;return()=>{h.callbacks.delete(c),d&&h.errorCallbacks.delete(d),u&&h.checkpointCallbacks.delete(u),h.callbacks.size===0&&(this.sendOrQueueUnsubscribe(h.shardKey,h.id,"unsubscribe"),this.returnCacheSeed(C.keyOf(h)),this.subscriptions.remove(h),this.releaseIdleShard(h.shardKey))}}subscribeShape(e,t,s={}){if(this.assertOpen(),this.followsAnotherTab()){const{onError:a}=s;return a!==void 0&&queueMicrotask(()=>{a({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;const r=`shape_${this.nextShapeId.toString()}`,n={args:e.args,callbacks:new Set([t]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:r,name:e.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:e.args===void 0?void 0:E(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(r,n),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(r),this.sendOrQueueUnsubscribe(n.shardKey,r,"shape_unsubscribe"),this.releaseIdleShard(n.shardKey)}}stream(e,t,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new y("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;const r=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=s,a=t??{},{handle:o,iterable:c}=et({maxBuffer:s.maxBuffer,onCancel:()=>{this.cancelStream(r,n)}});this.ensureSocket(n);const d=this.getConnection(n),u={id:r,query:{args:E(a,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"},h={durable:s.durable===!0,generation:void 0,handle:o,lastSeq:0,message:u,shardKey:n};this.streams.set(r,h);const p=d?.wsState==="open"&&v(d,u);if(!p&&d===void 0)return this.forgetStream(r),o.fail(new y("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),c;if(!p){for(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=Cr;){const f=d.pendingStreams.shift()?.id,S=f?this.streams.get(f):void 0;S&&(S.handle.fail(new y("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(f))}d.pendingStreams.push(u)}return c}httpStream(e,t,s={}){if(this.closed)throw new y("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");const r={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return qe(e,t,{baseUrl:this.url,fetch:this.fetchImpl,headers:r,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0;for(const e of this.whisperJoins.keys())this.dropWhisperJoinWaiters(e);this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const e of this.streams.values())e.handle.fail(new y("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(const e of this.connections.values())this.teardownConnection(e);for(const e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear();for(const e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.liveSocketGrants.clear(),this.roomFlushes.clear(),this.roomIdentityResets.clear(),this.shapeSubscriptions.clear(),this.pokeAssembler.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new y("INTERNAL","LunoraClient is closed")}followsAnotherTab(){const e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;const t=e.leaderTabId;return t!==void 0&&t!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new y("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}shardInUse(e){const t=s=>l(s)===e;return this.subscriptions.all().some(s=>t(s.shardKey))||[...this.shapeSubscriptions.values()].some(s=>t(s.shardKey))||[...this.streams.values()].some(s=>t(s.shardKey))||this.whisperHandlers.has(e)||this.connectionContexts.has(e)||this.connectionContextHolders.has(e)||this.offlineFlushes.has(e)||this.offlineQueue.hasPending(s=>t(s.shardKey))}releaseIdleShard(e){const t=l(e),s=this.connections.get(t);this.closed||t===""||s===void 0||(clearTimeout(s.idleTimer),s.idleTimer=setTimeout(()=>{s.idleTimer=void 0,!(this.closed||this.connections.get(t)!==s||this.shardInUse(t))&&(s.wasEverConnected&&this.idleClosedShards.add(t),this.teardownConnection(s),this.connections.delete(t),this.emitConnectionStatus())},Tr))}forgetStream(e){const t=this.streams.get(e);this.streams.delete(e),t&&this.releaseIdleShard(t.shardKey)}teardownConnection(e){e.polling.stop();const t=l(e.shardKey);for(const[r,n]of this.streams)l(n.shardKey)===t&&(n.handle.fail(new y("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(r));e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.clearResubscribeQueue(e),this.clearConnectionTimers(e),clearTimeout(e.idleTimer),e.idleTimer=void 0,L(e);const{socket:s}=e;if(s){e.socket=void 0;try{s.close()}catch{}}e.wsState="closed"}createTabCoordinator(){const e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`,t={activeSubscriptions:()=>this.subscriptions.all(),broadcastStatus:(s,r)=>this.tabCoordinator?.broadcastConnectionStatus(s,r),closeConnections:()=>{for(const[s,r]of this.connections)this.teardownConnection(r),this.connections.delete(s)},computeStatus:()=>this.computeStatus(),emitConnectionStatus:()=>{this.emitConnectionStatus()},ensureSocket:s=>{this.ensureSocket(s)},flushOfflineQueues:()=>{this.flushAllOfflineQueues()},identityFingerprint:()=>this.identityFingerprint(),isLeader:()=>this.tabCoordinator?.isLeader()===!0,leader:this.leader,queueResubscribe:s=>{this.queueResubscribe(s)},queuedShardKeys:()=>this.queuedOfflineShardKeys,clientIdentifier:()=>this.clientId,dropCacheSeed:s=>{this.dropCacheSeed(s)},ackAndAdvanceCursor:(s,r,n)=>{this.ackAndAdvanceCursor(s,r,n)},subscription:s=>this.subscriptions.get(s)};return new Be({channelName:e,onBecomeLeader:()=>{Gr(t)},onStopBeingLeader:()=>{$r(t)},onConnectionStatus:(s,r)=>{Vr(t,s,r)},onSubscriptionData:(s,r,n,a,o)=>{Jr(t,s,r,n,a,o)},onLeaderClaimAnswered:()=>{zr(t)},onSubscriptionError:(s,r,n)=>{Yr(t,s,r,n)},onSubscriptionSettled:(s,r,n,a,o,c)=>{Xr(t,s,r,n,a,o,c)}})}async sendBatch(e,t){if(this.assertOpen(),!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];const s=await this.fetchImpl(w(this.url,$),{body:JSON.stringify({calls:e.map((o,c)=>({args:E(o.args??{},`args for batch call '${o.fn.__lunoraRef}'`),functionPath:o.fn.__lunoraRef,id:c,shardKey:o.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:t}),r=s.headers.get("x-d1-bookmark");r&&this.bookmark.set(r);let n;try{n=await s.json()}catch{throw new y("INTERNAL",`LunoraClient: batch response was not JSON (status ${s.status.toString()})`)}const a=N(n);if(!s.ok||a!==void 0&&!n.results)throw a!==void 0?Ne(a):new y("INTERNAL",`LunoraClient: batch request failed (status ${s.status.toString()})`);for(const o of n.results??[]){const c=o.body?.commitCursor;typeof o.id=="number"&&typeof c=="number"&&this.recordShardCursor(e[o.id]?.shardKey,c)}return pr(n.results??[],e.length)}async runMutation(e,t,s){this.assertOpen();const r=t,n=s.mutationId??he(),a=this.takeReplayCredential(s.replayCredential),o=s.replayBaseline===void 0?this.baselineCursorFor(s.shardKey):s.replayBaseline??void 0,{confirms:c,rollbacks:d}=this.applyOptimisticUpdates(e.__lunoraRef,r,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,t,s.shardKey,d,c);const u=this.offlineFlushes.get(l(s.shardKey));u!==void 0&&await u;const{hasSocket:h,idleClosed:p,polling:m,wasEverConnected:f,wsState:S}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:g}=this.offlineQueue,U=f||g,B=this.WebSocketImpl!==void 0&&U,Q=m||p,Oe=S==="connecting"&&U&&!Q,Re=S!=="open"&&!h&&B&&!Q,Pe=B&&s.replayBaseline===void 0&&this.hasPendingWriteAhead(s.shardKey),oe=async()=>this.enqueueOfflineMutation(e,r,s.shardKey,o,n,d,c,s.precondition,s.mutationId,a?.stamp);if(Re||Oe||Pe)return oe();let W;try{const R=await this.rpc(e.__lunoraRef,r,s.shardKey,{baselineSeq:o,captureBookmark:!0,...a?.flags,mutationId:n,onCommitCursor:q=>{W=q}});for(const q of c)q(W);return{committed:!0,value:R}}catch(R){if(Q&&B&&R instanceof TypeError&&me(r))return oe();throw this.settleFailedDirectWrite(R,W,c,d,a?.flags.authToken),R}}settleFailedDirectWrite(e,t,s,r,n){if(this.noteIdentityMismatch(e),n!==void 0&&this.noteReplayAuthRefusal(e,n),x(e)){for(const a of s)a(t);return}P(r)}async enqueueOfflineMutation(e,t,s,r,n,a,o,c,d,u){const h=u===void 0?this.identityFingerprint():u;if(this.outbox){this.outboxMutationCounter+=1;const m=this.outboxMutationCounter;try{await this.outbox.enqueue({args:t,baselineSeq:r,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:d??`${this.clientId}:${String(m)}`,identity:h,mutationId:m,...a.length>0&&{onRejected:()=>{P(a)}},shardKey:s})}catch(f){throw P(a),f instanceof Error?f:new Error(String(f))}for(const f of o)f(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((m,f)=>{const S={args:t,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:r,id:n,clientId:this.clientId,identity:h,precondition:c,onCommit:g=>{for(const U of o)U(g)},reject:g=>{this.queuedIdentities.delete(n),x(g)||P(a),f(g instanceof Error?g:new Error(String(g))),this.releaseIdleShard(s)},resolve:m,shardKey:s};this.offlineQueue.enqueue(S),this.queuedOfflineShardKeys.add(s),this.ensureSocket(s),S.id!==void 0&&this.queuedIdentities.set(S.id,h)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;const t=l(e);return this.offlineQueue.hasPending(s=>l(s.shardKey)===t)}async hydratePersistedQueue(){try{const e=await this.offlineQueue.hydrate();for(const t of e)this.queuedOfflineShardKeys.add(t),this.ensureSocket(t)}catch{}}hydrateAsOutboxLeader(){const e=()=>{this.hydratePersistedQueue().catch(()=>{})},t=globalThis.navigator?.locks;if(!t){e();return}t.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{const e=await this.queryCache.load(),t=new Map;for(const s of this.subscriptions.all())t.set(_(s.fn.__lunoraRef,s.argsKey,s.shardKey),s);for(const{key:s,...r}of e){if(ze(this.persistenceVersion,r.version)){this.queryCache.remove(s).catch(()=>{});continue}const n=t.get(s);if(n&&this.cachedQueryMatchesIdentity(r)){this.seedSubscriptionFromCache(n,r);continue}this.hydratedQueryCache.set(s,r)}}catch{}}seedSubscriptionFromCache(e,t){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(t)||(e.serverBase=t.value,e.serverCursor=t.serverCursor,t.serverEpoch!==void 0&&(e.serverEpoch=t.serverEpoch),this.cacheSeededQueries.set(_(e.fn.__lunoraRef,e.argsKey,e.shardKey),t),O(e,t.value))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}returnCacheSeed(e){const t=this.cacheSeededQueries.get(e);t!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,t))}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(const[e,t]of this.cacheSeededQueries){const s=this.subscriptions.get(e);s!==void 0&&(s.serverBase=void 0,s.serverCursor=void 0,s.serverEpoch=void 0,O(s,void 0)),this.hydratedQueryCache.set(e,t)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,t,s){const r=_(e,t,s),n=this.hydratedQueryCache.get(r);if(!(n===void 0||!this.cachedQueryMatchesIdentity(n)))return this.hydratedQueryCache.delete(r),n}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(const e of this.subscriptions.all()){const t=_(e.fn.__lunoraRef,e.argsKey,e.shardKey),s=this.hydratedQueryCache.get(t);s!==void 0&&this.cachedQueryMatchesIdentity(s)&&(this.hydratedQueryCache.delete(t),this.seedSubscriptionFromCache(e,s))}}persistQueryValue(e){const t=e.serverBase;if(!this.queryCache||t===void 0)return;const s=_(e.fn.__lunoraRef,e.argsKey,e.shardKey),r=this.getConnection(e.shardKey)?.identity,n=r===void 0?this.identityFingerprint():r;n===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(s,{identity:n,serverCursor:e.serverCursor,ts:Date.now(),value:t,...n===this.identityFingerprint()&&!this.subjectAwaitingReconfirm()?this.credentialStamp():{},...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},gr))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;const{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}const t=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(t.map(async([s,r])=>e.put(s,r)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leader.status??"idle";const e=[...this.connections.values()];return e.length===0?"idle":e.some(t=>t.wsState==="open")?"connected":e.some(t=>t.polling.isPolling())?"polling":e.some(t=>t.wsState==="connecting")?"connecting":"offline"}baselineCursorFor(e){const t=l(e);let s;for(const r of this.subscriptions.all())l(r.shardKey)!==t||r.serverCursor===void 0||(s=s===void 0?r.serverCursor:Math.max(s,r.serverCursor));return s}async pollSubscriptions(e){const t=l(e),s=[];for(const o of this.subscriptions.all())l(o.shardKey)===t&&(me(o.args)?s.push(o):A(o.errorCallbacks,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"}));if(s.length===0)return this.probeOrigin();const r=$e(),n=this.identityFingerprint();let a;try{a=await Se(async o=>this.sendBatch(s.map(c=>({args:c.args,fn:c.fn,shardKey:c.shardKey})),o))}catch(o){return!(o instanceof TypeError)}if(this.identityFingerprint()!==n)return!0;for(const[o,c]of s.entries()){const d=a[o];if(d!==void 0){if(!d.ok){A(c.errorCallbacks,{code:d.error.code,message:d.error.message});continue}this.handleDataMessage({data:M(d.value),id:c.id,type:"data"},r)}}return!0}async probeOrigin(){const{fetchImpl:e}=this;if(!e)return!1;try{return await Se(async t=>e(w(this.url,$),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:t})),!0}catch{return!1}}emitConnectionStatus(){const e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,t,s){this.mutationSettledListeners.emit({args:e.args,code:s===void 0?void 0:s.code,error:s,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:t})}applyOptimisticUpdates(e,t,s,r){const n=[],a=[];if(!r)return{confirms:n,rollbacks:a};const o=C.key(e,t,s),c=this.subscriptions.get(o);if(c){const d=Ke(c,r);d&&(n.push(d.confirm),a.push(d.rollback))}return{confirms:n,rollbacks:a}}applyOptimisticUpdate(e,t,s,r,n){const{confirms:a,rollbacks:o,store:c}=je(this.subscriptions,s);try{e(c,t)}catch{P(o);return}r.push(...o),n.push(...a)}getConnection(e){return this.connections.get(l(e))}sendOrQueueUnsubscribe(e,t,s){const r=this.getConnection(e);r&&!v(r,{id:t,type:s})&&r.pendingUnsubscribes.push({id:t,type:s})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let r="idle";return this.leader.status==="connected"?r="open":this.leader.status==="connecting"&&(r="connecting"),{hasSocket:!1,idleClosed:!1,polling:this.leader.status==="polling",wasEverConnected:this.leader.wasEverConnected,wsState:r}}const t=this.getConnection(e),s=t===void 0&&this.idleClosedShards.has(l(e));return{hasSocket:t?.socket!==void 0,idleClosed:s,polling:t?.polling.isPolling()??!1,wasEverConnected:t?.wasEverConnected??s,wsState:t?.wsState??"idle"}}getOrCreateConnection(e){const t=l(e);let s=this.connections.get(t);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:Rr({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:()=>{this.flushOfflineQueue(e).catch(()=>{})},onStateChange:()=>{this.emitConnectionStatus()},poll:async()=>this.pollSubscriptions(e)}),reconnect:ue(this.reconnectOptions),reconnectTimer:void 0,resubscribePending:new Map,resubscribeQueue:[],shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:this.idleClosedShards.delete(t),wsState:"idle"},this.connections.set(t,s)),s}wsUrlFor(e,t){const s=[];if(e!==void 0&&s.push(`shard=${encodeURIComponent(e)}`),t!==void 0&&s.push(`token=${encodeURIComponent(t)}`),s.length===0)return this.wsUrl;const r=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${r}${s.join("&")}`}rpcRequestHeaders(e,t){const s={"content-type":"application/json"};e.expectSubject!==void 0&&(s[it]=nt(e.expectSubject));const r=this.shardCursors.get(this.cursorKeyFor(t));r!==void 0&&(s["x-lunora-min-seq"]=r.toString());const n=e.authToken===void 0?this.authToken:e.authToken;if(n&&(s.authorization=`Bearer ${n}`),e.mutationId&&(s["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(s["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(s["x-lunora-client-seq"]=e.clientSeq.toString()),e.baselineSeq!==void 0&&(s["x-lunora-base-seq"]=e.baselineSeq.toString()),e.attachBookmark){const a=this.bookmark.get();a&&(s["x-d1-bookmark"]=a)}return s}async rpc(e,t,s,r={}){if(!this.fetchImpl)throw new H("LunoraClient: no `fetch` implementation available");const n=this.rpcRequestHeaders(r,s),a=r.authToken===void 0?this.authToken:r.authToken,o=await this.fetchImpl(w(this.url,pt),{body:JSON.stringify({args:E(t,`args for '${e}'`),functionPath:e,shardKey:s}),headers:n,method:"POST"});if(r.captureBookmark){const h=o.headers.get("x-d1-bookmark");h&&this.bookmark.set(h)}let c;try{c=await o.json()}catch{throw F(o.status,o.statusText,o.headers.get("retry-after"))}const d=c;if(typeof d!="object"||d===null||Array.isArray(d))throw F(o.status,o.statusText,o.headers.get("retry-after"));const u=N(c);if(u!==void 0)throw ce(u,o.headers.get("retry-after"));if(!o.ok)throw F(o.status,o.statusText,o.headers.get("retry-after"));r.onMutationAck?.(c.lastMutationId),r.onCommitCursor?.(c.commitCursor),this.noteCredentialAccepted(a),this.learnDefaultShardKey(o,s),this.recordShardCursor(s,c.commitCursor);try{return T(c.result)}catch(h){throw Ee(h)}}async adminFetch(e,t,s,r){if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");const n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);const a=s instanceof ArrayBuffer||s instanceof Blob;let o;s===void 0?o=void 0:a?(o=s,r!==void 0&&(n["content-type"]=r)):(o=JSON.stringify(s),n["content-type"]="application/json");const c=await this.fetchImpl(w(this.url,e),{body:o,headers:n,method:t});let d;try{d=await c.json()}catch{const h=c.statusText?` ${c.statusText}`:"";throw new y("INTERNAL",`LunoraClient: response was not JSON (status ${c.status.toString()}${h})`)}const u=N(d);if(u!==void 0){const h=new Error(u.message??"admin request failed");throw h.code=u.code,h}if(!c.ok){const h=c.statusText?` ${c.statusText}`:"";throw new y("INTERNAL",`LunoraClient: admin request failed (status ${c.status.toString()}${h})`)}return d}effectiveConnectionContext(e){const t=this.connectionContextHolders.get(e);return t&&t.length>0?t[t.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){const t=this.connections.get(e);t?.wsState==="open"&&this.sendConnectEnvelope(t)}sendConnectEnvelope(e){const t=this.effectiveConnectionContext(l(e.shardKey));v(e,{caps:ei,clientId:this.clientId,id:"connect",type:"connect",...t===void 0?{}:{context:t}})}resendShapeSubscriptions(e){for(const t of this.shapeSubscriptions.values())l(t.shardKey)===l(e)&&this.sendShapeSubscribeIfOpen(t)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const t=this.getOrCreateConnection(e);if(!(t.wsState==="open"||t.wsState==="connecting")){if(t.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(t,e,this.wsToken).catch(()=>{});return}this.openSocket(t,e,this.wsToken)}}async openSocketWithProvidedToken(e,t,s){const r=this.wsTokenGeneration;let n;try{n=await s()}catch{this.handleDisconnect(e);return}if(!(this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0)){if(r!==this.wsTokenGeneration){typeof this.wsToken=="function"?await this.openSocketWithProvidedToken(e,t,this.wsToken):this.openSocket(e,t,this.wsToken);return}this.openSocket(e,t,n)}}openSocket(e,t,s){this.WebSocketImpl!==void 0&&(e.identity=this.identityFingerprint(),s===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.retired=!1,ye(e,this.wsUrlFor(t,s),this.managedSocketOptions,{onClose:r=>{r?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},onMessage:r=>{e.retired!==!0&&this.handleServerMessage(r.data,t)},onOpen:()=>{e.wsState="open",e.wasEverConnected=!0,e.identityConfirmed=!1,e.connectionId=void 0,e.roomsRejoined=!1,e.polling.noteOpen(),clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},vr),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(t),this.clearResubscribeQueue(e);for(const a of this.subscriptions.all())l(a.shardKey)===l(t)&&this.queueResubscribe(a);if(this.resendShapeSubscriptions(t),e.pendingUnsubscribes.length>0){const a=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(const{id:o,type:c}of a)v(e,{id:o,type:c});this.releaseIdleShard(t)}Ar(e);const r=l(t),n=this.whisperHandlers.get(r);if(this.dropWhisperJoinWaiters(r),this.whisperJoins.set(r,new Map),n)for(const a of n.keys())this.sendWhisperJoin(e,r,a);e.roomsRejoined=!0,this.releaseRoomSends(t),this.flushOfflineQueue(t).catch(()=>{})}}))}cancelStream(e,t){const s=this.getConnection(t);s&&(s.pendingStreams=s.pendingStreams?.filter(r=>r.id!==e),v(s,{id:e,type:"unsubscribe"})),this.forgetStream(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;e.wsState==="connecting"&&e.polling.noteFailedOpen(),L(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",e.connectionId=void 0,e.whisperAck=void 0,this.dropWhisperJoinWaiters(l(e.shardKey)),this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e);const t=new Set((e.pendingStreams??[]).map(r=>r.id));for(const[r,n]of this.streams)if(!(l(n.shardKey)!==l(e.shardKey)||t.has(r))){if(n.durable){const a={...n.message,...n.generation===void 0?{}:{generation:n.generation},sinceChunk:n.lastSeq};n.message=a,e.pendingStreams=[...(e.pendingStreams??[]).filter(o=>o.id!==r),a];continue}n.handle.fail(new y("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.forgetStream(r)}if(this.WebSocketImpl===void 0)return;const s=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},s)}markShardPendingAck(e){const t=l(e);for(const s of this.subscriptions.all())l(s.shardKey)===t&&(s.acked=!1)}queueResubscribe(e){const t=this.getConnection(e.shardKey);t&&(t.resubscribeQueue.push(e),this.drainResubscribeQueue(t))}drainResubscribeQueue(e){for(;e.resubscribePending.size<kr;){const t=e.resubscribeQueue.shift();if(!t)return;this.subscriptions.getById(t.id)&&this.sendSubscribeIfOpen(t)&&e.resubscribePending.set(t.id,setTimeout(()=>{this.releaseResubscribeSlot(e,t.id)},wr))}}releaseResubscribeSlot(e,t){const s=e.resubscribePending.get(t);s!==void 0&&(clearTimeout(s),e.resubscribePending.delete(t),this.drainResubscribeQueue(e))}clearResubscribeQueue(e){for(const t of e.resubscribePending.values())clearTimeout(t);e.resubscribePending.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);if(t?.wsState!=="open"||e.acked)return!1;const s=e.serverCursor!==void 0&&e.serverBase!==void 0;return v(t,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...s?{sinceSeq:e.serverCursor}:{},...s&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);t?.wsState==="open"&&v(t,{id:e.id,shape:{name:e.name,...e.wireArgs===void 0?{}:{args:e.wireArgs}},type:"shape_subscribe",...e.serverCursor===void 0?{}:{sinceCheckpoint:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,t){const s=Ir(e);if(s===void 0)return;let r;try{r=JSON.parse(s)}catch{return}if(r.type!=="error"&&this.getConnection(t)?.reconnect.reset(),typeof r.id=="string"){const n=this.getConnection(t);n&&this.releaseResubscribeSlot(n,r.id)}switch(r.type){case"ack":{const n=this.subscriptions.getById(r.id);n&&(n.acked=!0);return}case"chunk":{const{data:n,generation:a,id:o,seq:c}=r,d=this.streams.get(o);d&&typeof c=="number"&&(d.lastSeq=c,typeof a=="number"&&(d.generation=a),d.durable=!0),d?.handle.push(T(n));return}case"complete":{this.handleCompleteMessage(r.id);return}case"data":case"delta":{this.handleDataMessage(r);return}case"error":{this.handleErrorMessage(r);break}case"identity":{this.handleIdentityFrame(r,t),this.adoptSocketConnectionId(r,t),this.confirmShardIdentity(t);break}case"live":{this.dispatchLive(r,t);break}case"pokeEnd":{this.handlePokeEnd(r,t);break}case"pokePart":{this.pokeAssembler.part(t,r);break}case"pokeStart":{this.pokeAssembler.start(t,r);break}case"resume":{this.handleResumeMessage(r);break}case"settled":{this.handleSettledMessage(r);break}case"whisper":{this.dispatchWhisper(r,t);break}case"whisper_subscribed":{this.acknowledgeWhisperJoin(l(t),r.topic);break}}}handleErrorMessage(e){const t=e.error?.code;if(t==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}if(t==="STREAM_ID_IN_USE")return;const{id:s}=e,r=s===void 0?void 0:this.streams.get(s);if(r&&s!==void 0){r.handle.fail(xe(e)),this.forgetStream(s);return}const n=s===void 0?void 0:this.subscriptions.getById(s);if(n){const o=de(e),c=this.identityFingerprint(),d=C.keyOf(n);A(n.errorCallbacks,o),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(d,o,c);return}const a=s===void 0?void 0:this.shapeSubscriptions.get(s);a&&A(a.errorCallbacks,de(e))}handlePokeEnd(e,t){const s=this.pokeAssembler.end(t,e.pokeId);if(s){Kr(this.shapeSubscriptions,s);for(const r of s.parts.keys()){const n=this.shapeSubscriptions.get(r);n&&!s.undecodable.has(r)&&this.applyPokePart(n,s,e)}}}applyPokePart(e,t,s){const r=qr(e,t,s);if(be(e),r==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}handleDataMessage(e,t){const{id:s}=e,r=s?this.subscriptions.getById(s):void 0;if(!r)return;let n;try{n=Fe(e,r.serverBase)}catch(a){A(r.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription — ${a instanceof Error?a.message:String(a)}`});return}if(n===Le){this.resnapshotSubscription(r);return}if(this.dropCacheSeed(C.keyOf(r)),Ae(r,n,{cursor:e.cursor,epoch:e.epoch}),e.lastMutationId!==void 0&&(ee(r,e.lastMutationId),te(r,!0)),this.persistQueryValue(r),X(r,r.serverCursor),t!==void 0&&Ge(r,t),O(r,n),this.tabCoordinator?.isLeader()){const a=C.keyOf(r);this.tabCoordinator.broadcastSubscriptionData(a,n,r.serverCursor,r.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){const t=this.subscriptions.getById(e.id);t&&this.ackAndAdvanceCursor(t,e.cursor,e.epoch)}handleSettledMessage(e){const t=this.subscriptions.getById(e.id);if(t&&(this.ackAndAdvanceCursor(t,e.cursor,e.epoch),e.lastMutationId!==void 0&&ee(t,e.lastMutationId),te(t),this.tabCoordinator?.isLeader())){const s=C.keyOf(t);this.tabCoordinator.broadcastSubscriptionSettled(s,t.serverCursor,t.serverEpoch,t.lastMutationId,this.clientId,this.identityFingerprint())}}ackAndAdvanceCursor(e,t,s){e.acked=!0,(t!==void 0&&t!==e.serverCursor||s!==void 0&&s!==e.serverEpoch)&&(t!==void 0&&(e.serverCursor=t),s!==void 0&&(e.serverEpoch=s),this.persistQueryValue(e),X(e,e.serverCursor)&&O(e,e.serverBase))}adoptSocketConnectionId(e,t){const s=this.getConnection(t);if(!(s===void 0||typeof e.connectionId!="string")){s.connectionId=e.connectionId,s.whisperAck=e.whisperAck===!0;for(const r of this.liveSocketGrants.get(l(t))?.keys()??[])this.grantWhenJoined(t,r,e.connectionId)}}grantWhenJoined(e,t,s){const r=l(e),n=this.liveSocketGrants.get(r)?.get(t);if(n===void 0)return;const{stream:a,topic:o}=n,c=()=>{this.liveSocketGrants.get(r)?.get(t)===void 0||this.getConnection(e)?.connectionId!==s||this.postLiveControl(`/live/${a}/control`,e,{action:"subscribe",connectionId:s,stream:a,subscriptionId:t,topic:o},u=>{this.refuseLiveGrant(e,t,u)})};this.getConnection(e)?.whisperAck===!0?this.whenWhisperJoined(r,o,c):c()}sendWhisperJoin(e,t,s){const r=this.whisperJoinState(t,s);r.pending+=1,r.joined=!1,v(e,{topic:s,type:"whisper_subscribe"})}acknowledgeWhisperJoin(e,t){const s=this.whisperJoins.get(e)?.get(t);if(s!==void 0&&(s.pending=Math.max(0,s.pending-1),!(s.pending>0))){s.joined=!0;for(const r of s.waiters.splice(0))clearTimeout(r.timer),r.run()}}whenWhisperJoined(e,t,s){const r=this.whisperJoinState(e,t);if(r.joined){s();return}const n={run:s,timer:void 0};n.timer=setTimeout(()=>{r.waiters=r.waiters.filter(a=>a!==n),s()},_e),r.waiters.push(n)}dropWhisperJoinWaiters(e){for(const t of this.whisperJoins.get(e)?.values()??[])for(const s of t.waiters.splice(0))clearTimeout(s.timer)}whisperJoinState(e,t){let s=this.whisperJoins.get(e);s===void 0&&(s=new Map,this.whisperJoins.set(e,s));let r=s.get(t);return r===void 0&&(r={joined:!1,pending:0,waiters:[]},s.set(t,r)),r}refuseLiveGrant(e,t,s){const r=l(e),n=this.liveSocketGrants.get(r),a=n?.get(t);n===void 0||a===void 0||(n.delete(t),n.size===0&&this.liveSocketGrants.delete(r),a.onError?.({status:s,topic:a.topic}))}postLiveControl(e,t,s,r){const{fetchImpl:n}=this;if(!n)return;const a=JSON.stringify(t===void 0?s:{...s,shardKey:t}),o=this.rpcRequestHeaders({},t);this.liveControlChain=this.liveControlChain.then(()=>si(n,w(this.url,e),a,o)).then(c=>{c>=400&&c<500&&c!==404&&c!==401&&r?.(c)}).catch(()=>{})}dispatchLive(e,t){const s=this.liveSocketGrants.get(l(t));if(!s)return;const r=T(e.data);for(const n of s.values())if(!(n.stream!==e.stream||n.topic!==e.topic))try{n.onEvent(r)}catch{}}dispatchWhisper(e,t){const s=this.whisperHandlers.get(l(t))?.get(e.topic);if(!s)return;const r=T(e.data);for(const n of s)try{n(r,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){const t=this.streams.get(e);if(t){t.handle.complete(),this.forgetStream(e);return}const s=this.subscriptions.getById(e);s&&(s.acked=!1,A(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(t=>{Je(this.onPersistenceError,"remove",t,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let t=2166136261,s=5381;for(let r=0;r<e.length;r+=1){const n=e.charCodeAt(r);t^=n,t=Math.imul(t,16777619),s=Math.imul(s,33)+n}return`${e.length.toString(36)}:${(t>>>0).toString(36)}:${(s>>>0).toString(36)}`}credentialStamp(){const e=this.authToken;return e===null?{}:{credential:this.hashToken(e)}}cachedQueryMatchesIdentity(e){return this.identityFingerprint()===null&&this.identityUnresolved()?!1:!this.subjectAwaitingReconfirm()&&e.identity===this.identityFingerprint()||this.isSameCredentialUnderTokenHash(e.identity)?!0:e.credential!==void 0&&e.credential===this.credentialStamp().credential}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;const t=this.authToken;return t===null?!1:this.hashToken(t)===e}releaseSessionProbe(){this.sessionProbesInFlight-=1,!(this.identityUnresolved()||this.identityFingerprint()!==null)&&!this.closed&&this.offlineQueue.size>0&&z(this.computeStatus())&&this.flushAllOfflineQueues()}identityUnresolved(){return this.sessionProbesInFlight>0?!0:this.identityResolutionExpected&&!this.identitySettled}adoptResolvedSubject(e,t,s){if(!(this.closed||this.authToken!==e||s!==this.sessionProbeGeneration)){if(e===null){this.adoptCookieSubject(t?.id??null,s);return}t!==null&&this.setAuthToken(e,t.id)}}adoptCookieSubject(e,t){return this.closed||this.authToken!==null||t<this.identityAnsweredAt?!1:(this.identityAnsweredAt=t,this.identitySettled=!0,this.setAuthToken(null,e),!0)}sendEncodedWhisper(e,t,s){this.ensureSocket(s.shardKey);const r=this.getConnection(s.shardKey),n=r!==void 0&&v(r,{data:t,topic:e,type:"whisper"});return this.releaseIdleShard(s.shardKey),n}roomSendsAdmitted(e){const t=this.getConnection(e);return t?.wsState==="open"&&t.retired!==!0&&t.identityConfirmed===!0&&t.roomsRejoined===!0}releaseRoomSends(e){if(this.roomSendsAdmitted(e))for(const t of this.roomFlushes.get(l(e))??[])t()}confirmShardIdentity(e){const t=this.getConnection(e);t!==void 0&&(t.identityConfirmed=!0),this.releaseRoomSends(e)}handleIdentityFrame(e,t){const s=this.getConnection(t)?.identityQuestion,{subject:r}=e;s===void 0||r!==null&&typeof r!="string"||this.adoptCookieSubject(r,s)||!this.closed&&this.authToken===null&&(r===null?null:`subj:${r}`)!==this.identityFingerprint()&&this.evictPreviousIdentitySession()}applySubject(e,t){if(t!==void 0){this.authSubject=t,this.subjectToken=e;return}(e===null&&this.authSubject!==null||e!==null&&this.authSubject===null)&&(this.authSubject=void 0,this.subjectToken=null)}isKnownNobody(){return this.authSubject===null&&this.authToken===null}subjectAwaitingReconfirm(){return this.authSubject!==void 0&&this.authSubject!==null&&this.subjectToken!==this.authToken}stampOf(e){const t=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return t===void 0?e.identity:t}warnRefreshWithoutSubject(e,t){e===null||t===null||this.authSubject!==void 0||this.authRefusalNotifiedFor!==this.hashToken(e)||console.warn("[lunora] setAuthToken replaced a token that was just refused for a queued write, with no subject: without one a refresh reads as a user switch, so the held writes were discarded (OFFLINE_IDENTITY_CHANGED). Pass the user id, e.g. setAuthToken(token, user.id), to keep them across a refresh.")}rejectQueuedForIdentityChange(e){const t=this.offlineQueue.drain(),s=[];for(const r of t){if(this.identityVerdict(this.stampOf(r))!=="mismatch"){s.push(r);continue}this.queuedIdentities.delete(r.id??""),this.unpersist(r.id);const n=new Error("offline mutation discarded: auth identity changed before replay");n.code="OFFLINE_IDENTITY_CHANGED",r.reject(n),this.emitItemSettled(r,"rejected",n)}this.offlineQueue.requeue(s),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,t){for(const s of this.connections.values())s.identity===e&&(s.identity=t)}restampQueuedIdentity(e,t){for(const[s,r]of this.queuedIdentities)r===e&&this.queuedIdentities.set(s,t);this.offlineQueue.restampIdentity(e,t)}restampWatermarks(e,t){const s=e??"",r=this.clientWatermarks.get(s);if(r===void 0)return;this.clientWatermarks.delete(s);const n=t??"",a=this.clientWatermarks.get(n);if(a===void 0)this.clientWatermarks.set(n,r);else for(const[o,c]of r)a.set(o,c)}clearQueryCacheForIdentityChange(){this.revokeCacheSeededValues(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}evictPreviousIdentitySession(){this.resetRoomSends(),this.revokeCacheSeededValues();for(const e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.acked=!1,O(e,void 0);for(const e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,be(e);this.bounceShardSockets(),this.retiredIdentities+=1,this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;const e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}resetRoomSends(){for(const e of this.roomIdentityResets)e()}bounceShardSockets(){for(const e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}}flushAllOfflineQueues(){for(const e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){const t=l(e),s=this.offlineFlushes.get(t);if(s===void 0&&this.offlineQueue.size===0)return;const r=(async()=>{await(s??Promise.resolve());const{authToken:n}=this;try{await this.drainOfflineQueue(e,n)}catch{}!this.closed&&this.authToken!==n&&this.offlineQueue.size>0&&z(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(t,r),await r,this.offlineFlushes.get(t)===r&&(this.offlineFlushes.delete(t),this.releaseIdleShard(e))}async drainOfflineQueue(e,t){const s=this.offlineQueue.drainConflict();for(const u of s){this.unpersist(u.id),this.queuedIdentities.delete(u.id??"");const h=new Error("offline mutation skipped: precondition failed before replay");h.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(u,"rejected",h)}const r=l(e),n=this.offlineQueue.drain(u=>l(u.shardKey)===r);if(n.length===0)return;const a=[],o=[];for(const u of n){const h=this.replayGateVerdict(u);h==="send"?a.push(u):h==="hold"&&o.push(u)}if(this.offlineQueue.requeue(o),o.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),a.length===0){this.scheduleRateLimitedRetry(e);return}const c=this.encodableOrSettleTerminal(a);if(c.length===0){this.scheduleRateLimitedRetry(e);return}if(c.length===1){await this.replaySequential(c,e,t),this.scheduleRateLimitedRetry(e);return}const d=[];for(let u=0;u<c.length;u+=G){const h=c.slice(u,u+G),p=await this.replayBatched(h,e,t);if(d.push(...p.requeue),p.stop){d.push(...c.slice(u+G));break}}d.length>0&&this.offlineQueue.requeue(d),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){const t=l(e),s=this.replayRetryState.get(t),r=(s?.attempts??0)+1;this.replayRetryState.set(t,{attempts:r,delayMs:Math.max(s?.delayMs??0,Z(r))})}noteReplayRetryDelay(e,t,s){const r=l(e),n=this.replayRetryState.get(r),a=(n?.attempts??0)+1,o=Ur(t,a)??(s===null&&K(t)?Z(a):void 0);this.replayRetryState.set(r,{attempts:a,delayMs:o===void 0?n?.delayMs:Math.max(n?.delayMs??0,o)})}scheduleRateLimitedRetry(e){const t=l(e),s=this.replayRetryState.get(t),r=s?.delayMs;if(s===void 0||r===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(t);return}s.delayMs=void 0;const n=this.replayRetryTimers.get(t);n!==void 0&&clearTimeout(n),this.replayRetryTimers.set(t,setTimeout(()=>{this.replayRetryTimers.delete(t),this.flushOfflineQueue(e).catch(()=>{})},r))}encodableOrSettleTerminal(e){const t=[];for(const s of e)try{E(s.args,`args for '${s.functionPath}'`),t.push(s)}catch(r){this.settleReplayTerminal(s,r instanceof Error?r:new Error(String(r)))}return t}identityVerdict(e){if(this.subjectAwaitingReconfirm())return"unknown";const t=this.identityFingerprint();return t===null&&this.identityUnresolved()?"unknown":e===t||e!==void 0&&this.isSameCredentialUnderTokenHash(e)?"match":t===null?"unknown":"mismatch"}replayGateVerdict(e){const t=this.stampOf(e);if(t===void 0)return this.queuedIdentities.delete(e.id??""),"send";const s=this.identityVerdict(t);if(s==="unknown")return"hold";if(this.queuedIdentities.delete(e.id??""),s==="match")return"send";this.unpersist(e.id);const r=new Error("offline mutation skipped: auth identity changed before replay");return r.code="OFFLINE_IDENTITY_CHANGED",e.reject(r),this.emitItemSettled(e,"rejected",r),"reject"}settleReplaySuccess(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.resolve(t),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,t){const s=e.headers.get("x-lunora-shard-key");if(s===null||t!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;const r=this.shardCursors.get("");r!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,r)),this.shardCursors.delete(""))}recordShardCursor(e,t){if(typeof t!="number")return;const s=this.cursorKeyFor(e);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,t))}shouldRequeueReplayFailure(e,t){return this.noteIdentityMismatch(e)?!0:this.noteReplayAuthRefusal(e,t)||Fr(e)}noteReplayAuthRefusal(e,t){if(!K(e))return!1;const s=this.hashToken(t??"");return t===this.authToken&&this.authRefusalNotifiedFor!==s&&(this.authRefusalNotifiedFor=s,this.notifyTokenExpired()),!0}noteCredentialAccepted(e){this.authRefusalNotifiedFor!==void 0&&this.authRefusalNotifiedFor===this.hashToken(e??"")&&(this.authRefusalNotifiedFor=void 0)}takeReplayCredential(e){if(e===void 0)return;const t=this.replayCredentials.get(e);if(t===void 0)throw new TypeError("LunoraClient: `replayCredential` must come from this client's `replayIdentityVerdict`, and is single use");return this.replayCredentials.delete(e),{flags:{authToken:t.authToken,...V(t.stamp,t.authToken)},stamp:t.stamp}}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;const t=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===t&&(this.warnedIdentityDisagreement=!0,console.warn('[lunora] a replayed write was refused with IDENTITY_MISMATCH, but `/get-session` still names the same user. The worker\'s `resolveIdentity` must return the same `userId` as the better-auth `user.id`, and RPC requests must carry the session cookie (`credentials: "include"` on a cross-origin fetch).'))}).catch(()=>{}),!0}settleReplayUndecodable(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.reject(t),this.emitItemSettled(e,"committed",t)}settleReplayTerminal(e,t){this.unpersist(e.id),e.reject(t),this.emitItemSettled(e,"rejected",t)}async replaySequential(e,t,s){for(let r=0;r<e.length;r+=1){const n=e[r];if(!n)continue;let a;try{const o=await this.rpc(n.functionPath,n.args,n.shardKey,{authToken:s,baselineSeq:n.baselineSeq,captureBookmark:!0,clientId:n.clientId??this.clientId,...V(n.identity,s),mutationId:n.id,onCommitCursor:c=>{a=c}});this.settleReplaySuccess(n,o,a)}catch(o){if(x(o)){this.settleReplayUndecodable(n,o,a);continue}if(!this.shouldRequeueReplayFailure(o,s)){this.settleReplayTerminal(n,o);continue}this.noteReplayRetryDelay(t,o,s),this.offlineQueue.requeue(e.slice(r));return}}}async replayBatched(e,t,s){if(!this.fetchImpl)return{requeue:e,stop:!0};const r=JSON.stringify({calls:e.map((d,u)=>({args:E(d.args,`args for '${d.functionPath}'`),baselineSeq:d.baselineSeq,functionPath:d.functionPath,id:u,clientId:d.clientId??this.clientId,mutationId:d.id,shardKey:d.shardKey}))});if(e.length>1&&xr(r)>Nr)return await this.replayBatchedHalves(e,t,s);let n;try{n=await this.fetchImpl(w(this.url,$),{body:r,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:s,...V(e.find(d=>d.identity!==void 0)?.identity,s)}),method:"POST"})}catch{return{requeue:e,stop:!0}}const a=n.headers.get("x-d1-bookmark");if(a&&this.bookmark.set(a),n.status===413&&e.length>1)return await this.replayBatchedHalves(e,t,s);let o;const c=n.headers.get("retry-after");try{o=await n.json()}catch{return this.settleWholeBatchError(e,F(n.status,n.statusText,c),t,s)}if(!o.results){const d=N(o),u=d===void 0?F(n.status,n.statusText,c):ce(d,c);return this.settleWholeBatchError(e,u,t,s)}return{requeue:this.settleReplayBatchSlots(e,o.results,t,s),stop:!1}}settleWholeBatchError(e,t,s,r){if(t instanceof H||t.code!==void 0&&this.shouldRequeueReplayFailure(t,r))return this.noteReplayRetryDelay(s,t,r),{requeue:e,stop:!0};for(const n of e)this.settleReplayTerminal(n,t);return{requeue:[],stop:!1}}async replayBatchedHalves(e,t,s){const r=Math.ceil(e.length/2),n=await this.replayBatched(e.slice(0,r),t,s);if(n.stop)return{requeue:[...n.requeue,...e.slice(r)],stop:!0};const a=await this.replayBatched(e.slice(r),t,s);return{requeue:[...n.requeue,...a.requeue],stop:a.stop}}settleReplayBatchSlots(e,t,s,r){const n=Dr(t),a=[];let o=!1,c=!1;for(const[d,u]of e.entries()){const h=Br(n.get(d));switch(h.kind){case"committed":{o=!0,this.settleReplaySuccess(u,h.value,h.commitCursor);break}case"errored":{c||=K(h.error),this.shouldRequeueReplayFailure(h.error,r)?(this.noteReplayRetryDelay(s,h.error,r),a.push(u)):this.settleReplayTerminal(u,h.error);break}case"unanswered":{a.push(u);break}default:o=!0,this.settleReplayUndecodable(u,h.error,h.commitCursor)}}return o&&!c&&this.noteCredentialAccepted(r),a}}export{Ie as LunoraClient};
@@ -0,0 +1,10 @@
1
+ import{decodeWire as V}from"@lunora/wire";import{createReconnect as H}from"./createReconnect-CjTmjJDH.mjs";const B="x-lunora-live-connection",G="live",J=/^ /u,q=1e4,F=a=>{const c=a.indexOf("?"),f=c===-1?a:a.slice(0,c);if(!f.endsWith("/connect"))throw new Error(`connectLiveStream: expected a connect URL ending in "/connect", got "${a}"`);return`${f.slice(0,-8)}/control${c===-1?"":a.slice(c)}`},K=a=>{let c="message";const f=[];for(const u of a.split(`
2
+ `))u.startsWith("event:")?c=u.slice(6).trim():u.startsWith("data:")&&f.push(u.slice(5).replace(J,""));return f.length===0?void 0:{data:f.join(`
3
+ `),event:c}},Y=(a,c={})=>{const f=c.fetch??fetch,u=F(a),P=c.maxDelayMs??3e4,T=H({initialDelayMs:c.retryDelay??1e3,maxDelayMs:P}),C=c.withCredentials===!0?"include":"same-origin",O=new URL(a,"https://lunora.invalid").searchParams.get("shard")??void 0,l=new Map,p=new Set;let h,w,A=!1,M=0;const $=()=>{let e;do M+=1,e=`live-${String(M)}`;while(l.has(e));return e},N=()=>A;let y,g;const R=new Promise((e,t)=>{y=e,g=t});R.catch(()=>{});const _={...c.headers},E=new Map,S=new Set,D=async e=>{const t=new AbortController,r=setTimeout(()=>{t.abort()},q);S.add(t);try{const n=await f(u,{body:JSON.stringify(O===void 0?e:{...e,shardKey:O}),credentials:C,headers:{"content-type":"application/json",..._},method:"POST",signal:t.signal});return await n.text(),n.status}catch{return}finally{clearTimeout(r),S.delete(t)}},L=(e,t)=>{const n=(E.get(e)??Promise.resolve()).then(()=>D(t)),o=n.then(()=>{},()=>{});return E.set(e,o),o.then(()=>{E.get(e)===o&&E.delete(e)}).catch(()=>{}),n},U=(e,t)=>{for(const r of l.values())if(r.topic===e)for(const n of r.handlers)try{n(t)}catch{}for(const r of p)try{r({payload:t,topic:e})}catch{}},W=e=>{const t=K(e);if(t?.event===G)try{const r=JSON.parse(t.data);U(r.topic,V(r.data))}catch{}},I=(e,t,r)=>{if(l.get(e)===t){l.delete(e);for(const n of t.errors)try{n({status:r,subscriptionId:e,topic:t.topic})}catch{}}},j=async()=>{const e=await Promise.all([...l].map(async([t,r])=>{const n=await L(t,{action:"subscribe",connectionId:h,subscriptionId:t,topic:r.topic});return{entry:r,id:t,status:n}}));for(const{entry:t,id:r,status:n}of e){if(n===void 0||n>=500||n===404||n===401){w?.abort();return}n>=400&&I(r,t,n)}},k=async e=>{h=e.headers.get(B)??void 0,T.reset();const r=(async()=>{try{await j()}catch{w?.abort();return}y?.(),y=void 0,g=void 0})(),n=e.body?.getReader();if(n===void 0){await r;return}const o=new TextDecoder;let i="",s=!1;for(;;){const{done:m,value:x}=await n.read();if(m)break;const v=o.decode(x,{stream:!0}),b=s?`\r${v}`:v;s=b.endsWith("\r"),i+=(s?b.slice(0,-1):b).replaceAll(`\r
4
+ `,`
5
+ `).replaceAll("\r",`
6
+ `);let d=i.indexOf(`
7
+
8
+ `);for(;d!==-1;)W(i.slice(0,d)),i=i.slice(d+2),d=i.indexOf(`
9
+
10
+ `)}await r};return(async()=>{for(;!N();){w=new AbortController;try{const t=await f(a,{credentials:C,headers:{accept:"text/event-stream",..._},signal:w.signal});if(!t.ok)throw new Error(`live stream connect failed: HTTP ${String(t.status)}`);await k(t)}catch{}if(N())return;const e=T.next();await new Promise(t=>{setTimeout(t,e)})}})().catch(()=>{}),{close:()=>{A=!0,w?.abort();for(const e of S)e.abort();S.clear(),l.clear(),p.clear(),g?.(new Error("connectLiveStream: closed before the first connection")),y=void 0,g=void 0},get connectionId(){return h},onEvent:e=>(p.add(e),()=>p.delete(e)),ready:R,subscribe:({id:e,onError:t,onEvent:r,topic:n})=>{if(A)throw new Error("connectLiveStream: subscribe on a closed stream");const o=e??$(),i=l.get(o);if(i!==void 0&&i.topic!==n)throw new Error(`connectLiveStream: subscription id "${o}" already follows "${i.topic}"; unsubscribe it first`);const s=i??{errors:new Set,handlers:new Set,refs:0,topic:n},m=r===void 0?void 0:v=>{r(v)};if(s.refs+=1,m!==void 0&&s.handlers.add(m),t!==void 0&&s.errors.add(t),i===void 0&&(l.set(o,s),h!==void 0)){const v=h,b=w;L(o,{action:"subscribe",connectionId:v,subscriptionId:o,topic:n}).then(d=>{if(d===void 0||d===401||d===404||d>=500){v===h&&b?.abort();return}d>=400&&I(o,s,d)}).catch(()=>{})}let x=!1;return()=>{x||(x=!0,m!==void 0&&s.handlers.delete(m),s.refs-=1,!(s.refs>0||l.get(o)!==s)&&(l.delete(o),L(o,{action:"unsubscribe",connectionId:h,subscriptionId:o,topic:n}).catch(()=>{})))}}}};export{Y as connectLiveStream};
@@ -1 +1 @@
1
- import{LunoraClient as r}from"./LunoraClient-C7RQBwz0.mjs";const c=e=>{const t=new r({fetch:e.fetch,url:e.url});return e.token!==void 0&&t.setAuthToken(e.token),t};export{c as createServerClient};
1
+ import{LunoraClient as r}from"./LunoraClient-1GSUcavS.mjs";const c=e=>{const t=new r({fetch:e.fetch,url:e.url});return e.token!==void 0&&t.setAuthToken(e.token),t};export{c as createServerClient};
@@ -845,15 +845,42 @@ interface ServerWhisperMessage {
845
845
  topic: string;
846
846
  type: "whisper";
847
847
  }
848
+ /**
849
+ * The shard processed a `whisper_subscribe` for a live (non-room) `topic` on this socket. It is sent
850
+ * whether or not the join was admitted, so it carries no authorization signal. A client that must
851
+ * publish or receive only once its membership took effect waits for it. A room join gets no ack.
852
+ */
853
+ interface ServerWhisperSubscribedMessage {
854
+ topic: string;
855
+ type: "whisper_subscribed";
856
+ }
857
+ /**
858
+ * A server live publish to a WebSocket member granted `stream` on `topic`. Server-only:
859
+ * a peer's whisper never carries this type, so a `live` frame is always the server's.
860
+ * `data` is the published payload, the same as the SSE `live` event.
861
+ */
862
+ interface ServerLiveMessage {
863
+ data: unknown;
864
+ stream: string;
865
+ topic: string;
866
+ type: "live";
867
+ }
848
868
  /**
849
869
  * The user the shard authenticated this socket as, sent in reply to every
850
870
  * `connect` frame. `subject` is the resolved user id, or `null` when the socket
851
871
  * is anonymous. A cookie-session client reads it to learn who it is — a
852
872
  * sign-out or another user's sign-in changes nothing else it can see.
873
+ *
874
+ * `connectionId` names this socket to the live-stream control route, which grants
875
+ * it live topics (see `LunoraClient.subscribeLiveTopic`). `whisperAck` is `true` when the
876
+ * shard answers every live join with `whisper_subscribed`; a client waits for that answer
877
+ * before it posts a grant, and posts at once when the flag is absent.
853
878
  */
854
879
  interface ServerIdentityMessage {
880
+ connectionId?: string;
855
881
  subject: null | string;
856
882
  type: "identity";
883
+ whisperAck?: boolean;
857
884
  }
858
885
  /**
859
886
  * One row-level change in a shape's replication stream — the wire form of the
@@ -934,7 +961,7 @@ interface ServerPokeEndMessage {
934
961
  pokeId: string;
935
962
  type: "pokeEnd";
936
963
  }
937
- type ServerMessage = ServerAckMessage | ServerChunkMessage | ServerCompleteMessage | ServerDataMessage | ServerErrorMessage | ServerIdentityMessage | ServerPokeEndMessage | ServerPokePartMessage | ServerPokeStartMessage | ServerResumeMessage | ServerSettledMessage | ServerWhisperMessage;
964
+ type ServerMessage = ServerAckMessage | ServerChunkMessage | ServerCompleteMessage | ServerDataMessage | ServerErrorMessage | ServerIdentityMessage | ServerLiveMessage | ServerPokeEndMessage | ServerPokePartMessage | ServerPokeStartMessage | ServerResumeMessage | ServerSettledMessage | ServerWhisperMessage | ServerWhisperSubscribedMessage;
938
965
  /**
939
966
  * The authenticated user as exposed client-side, mirroring better-auth's
940
967
  * `user` row (the `user` field of the `get-session` response). Kept minimal
@@ -2072,6 +2099,17 @@ declare class LunoraClient {
2072
2099
  * (re)connect so a topic survives a socket bounce.
2073
2100
  */
2074
2101
  private readonly whisperHandlers;
2102
+ /**
2103
+ * Live-topic grants this client asked for over a WebSocket, keyed `connectionKey(shardKey)` →
2104
+ * subscription id → the stream and topic. Replayed on every `identity` frame: each socket is a
2105
+ * new connection id with no grants, so a bounce would otherwise stop delivery silently.
2106
+ */
2107
+ private readonly liveSocketGrants;
2108
+ /** Tail of the live-grant control posts. One chain keeps a subscribe and its unsubscribe in order. */
2109
+ private liveControlChain;
2110
+ /** Join state of each whisper topic, per `connectionKey(shardKey)`, on the current socket. Reset on every open. */
2111
+ private readonly whisperJoins;
2112
+ private nextLiveSocketId;
2075
2113
  /** Last status broadcast, so we only notify listeners on an actual change. */
2076
2114
  private lastStatus;
2077
2115
  private nextSubId;
@@ -2433,6 +2471,37 @@ declare class LunoraClient {
2433
2471
  whisperSubscribe(topic: string, handler: (data: unknown, from?: string) => void, options?: {
2434
2472
  shardKey?: string;
2435
2473
  }): Unsubscribe;
2474
+ /**
2475
+ * Follow a live topic of a `defineLiveStream` stream over this client's WebSocket, instead of
2476
+ * an SSE connection (`connectLiveStream`). Joins the bare topic as a whisper member, then asks
2477
+ * the stream's control route (`/live/<stream>/control`) to grant this socket the topic, naming
2478
+ * the socket's connection id. A live publish reaches the socket only with both in place.
2479
+ *
2480
+ * The join needs the app's `onWhisper` approval, the same as any whisper join. The shard runs
2481
+ * the authorizer with `action: "subscribe"` on the bare topic, and a denied join is silent:
2482
+ * the shard acknowledges every join once processed, admitted or not, so the client cannot tell
2483
+ * a denial from a quiet topic. The grant is posted only after that acknowledgement (or after
2484
+ * `LIVE_CONTROL_TIMEOUT_MS` if it never arrives), so a publish cannot outrun the membership it
2485
+ * needs. A grant posted for a denied join still has no membership, so the shard relays no
2486
+ * `live` frame and `onEvent` never fires. An app that streams private data here must declare an
2487
+ * `onWhisper` that allows the topic; without one the join is open to any socket on the shard.
2488
+ *
2489
+ * Grants are re-issued on every reconnect, because each socket gets a new connection id.
2490
+ * A control call that fails is not retried here, so a failed grant delivers nothing. A refusal
2491
+ * (a 4xx other than 404 and 401) is final: the local grant is dropped, so a later subscribe can
2492
+ * be tried again, and `onError` is called with the status. A transient failure keeps the grant.
2493
+ * @returns an unsubscribe function that revokes the grant and leaves the topic
2494
+ */
2495
+ subscribeLiveTopic(options: {
2496
+ onError?: (error: {
2497
+ status: number;
2498
+ topic: string;
2499
+ }) => void;
2500
+ onEvent: (payload: unknown) => void;
2501
+ shardKey?: string;
2502
+ stream: string;
2503
+ topic: string;
2504
+ }): Unsubscribe;
2436
2505
  /**
2437
2506
  * Broadcast an ephemeral `data` payload to the other members of a whisper
2438
2507
  * `topic` on `options.shardKey`'s shard. Fire-and-forget: the frame is
@@ -4061,6 +4130,53 @@ declare class LunoraClient {
4061
4130
  * client must re-render changed, but the resume position may have moved".
4062
4131
  */
4063
4132
  private ackAndAdvanceCursor;
4133
+ /**
4134
+ * Record the socket's connection id from its `identity` frame, then re-issue every live grant
4135
+ * this shard holds: a new socket starts with none.
4136
+ */
4137
+ private adoptSocketConnectionId;
4138
+ /**
4139
+ * Post the live grant `subscriptionId` for the socket `connectionId`, once the socket has
4140
+ * acknowledged the join of the grant's topic. A publish reaches a member only with both in
4141
+ * place, so a grant that landed first would drop a publish made before the join took effect.
4142
+ * The post is skipped if the grant was released or refused meanwhile, or if the socket changed
4143
+ * since `connectionId` was read: the new socket's identity posts its own grants.
4144
+ */
4145
+ private grantWhenJoined;
4146
+ /** Send a `whisper_subscribe` for `topic` on `conn`, and count it as pending until the shard acknowledges it. */
4147
+ private sendWhisperJoin;
4148
+ /** One `whisper_subscribed` frame arrived: the topic is joined once every join sent for it is acknowledged. */
4149
+ private acknowledgeWhisperJoin;
4150
+ /**
4151
+ * Run `run` once `topic` is joined on the current socket, or after {@link LIVE_CONTROL_TIMEOUT_MS}.
4152
+ * A lost ack must not hold a grant forever, so the timeout runs it anyway: an unacknowledged
4153
+ * join is not necessarily a failed one, and a grant for a join that never landed delivers nothing.
4154
+ */
4155
+ private whenWhisperJoined;
4156
+ /**
4157
+ * Forget the waiters of a socket that is going away, without running them: a grant for the old
4158
+ * socket's connection id is never valid, and the next socket's identity posts its own grants.
4159
+ */
4160
+ private dropWhisperJoinWaiters;
4161
+ private whisperJoinState;
4162
+ /**
4163
+ * Drop a live grant the shard refused for good, and tell its caller. A grant already released
4164
+ * by its unsubscribe handle is gone from the map, so a late refusal reports nothing.
4165
+ */
4166
+ private refuseLiveGrant;
4167
+ /**
4168
+ * POST one live-grant control call, behind every earlier one. The body names the shard when
4169
+ * the socket is not the default one, as the SSE control call does. A refusal (a 4xx other
4170
+ * than 404 and 401) is handed to `onRefused`. Failures are swallowed: a denied grant must
4171
+ * never surface as an unhandled rejection.
4172
+ */
4173
+ private postLiveControl;
4174
+ /**
4175
+ * Route an inbound live publish to the grants on the originating shard whose stream and topic
4176
+ * match. A grant exists only for a subscribed stream and topic, so a frame naming another
4177
+ * stream reaches no handler.
4178
+ */
4179
+ private dispatchLive;
4064
4180
  /** Route an inbound whisper to the topic's handlers on the originating shard. */
4065
4181
  private dispatchWhisper;
4066
4182
  /** Notify every {@link onTokenExpired} listener (best-effort, listener throws swallowed). */
@@ -845,15 +845,42 @@ interface ServerWhisperMessage {
845
845
  topic: string;
846
846
  type: "whisper";
847
847
  }
848
+ /**
849
+ * The shard processed a `whisper_subscribe` for a live (non-room) `topic` on this socket. It is sent
850
+ * whether or not the join was admitted, so it carries no authorization signal. A client that must
851
+ * publish or receive only once its membership took effect waits for it. A room join gets no ack.
852
+ */
853
+ interface ServerWhisperSubscribedMessage {
854
+ topic: string;
855
+ type: "whisper_subscribed";
856
+ }
857
+ /**
858
+ * A server live publish to a WebSocket member granted `stream` on `topic`. Server-only:
859
+ * a peer's whisper never carries this type, so a `live` frame is always the server's.
860
+ * `data` is the published payload, the same as the SSE `live` event.
861
+ */
862
+ interface ServerLiveMessage {
863
+ data: unknown;
864
+ stream: string;
865
+ topic: string;
866
+ type: "live";
867
+ }
848
868
  /**
849
869
  * The user the shard authenticated this socket as, sent in reply to every
850
870
  * `connect` frame. `subject` is the resolved user id, or `null` when the socket
851
871
  * is anonymous. A cookie-session client reads it to learn who it is — a
852
872
  * sign-out or another user's sign-in changes nothing else it can see.
873
+ *
874
+ * `connectionId` names this socket to the live-stream control route, which grants
875
+ * it live topics (see `LunoraClient.subscribeLiveTopic`). `whisperAck` is `true` when the
876
+ * shard answers every live join with `whisper_subscribed`; a client waits for that answer
877
+ * before it posts a grant, and posts at once when the flag is absent.
853
878
  */
854
879
  interface ServerIdentityMessage {
880
+ connectionId?: string;
855
881
  subject: null | string;
856
882
  type: "identity";
883
+ whisperAck?: boolean;
857
884
  }
858
885
  /**
859
886
  * One row-level change in a shape's replication stream — the wire form of the
@@ -934,7 +961,7 @@ interface ServerPokeEndMessage {
934
961
  pokeId: string;
935
962
  type: "pokeEnd";
936
963
  }
937
- type ServerMessage = ServerAckMessage | ServerChunkMessage | ServerCompleteMessage | ServerDataMessage | ServerErrorMessage | ServerIdentityMessage | ServerPokeEndMessage | ServerPokePartMessage | ServerPokeStartMessage | ServerResumeMessage | ServerSettledMessage | ServerWhisperMessage;
964
+ type ServerMessage = ServerAckMessage | ServerChunkMessage | ServerCompleteMessage | ServerDataMessage | ServerErrorMessage | ServerIdentityMessage | ServerLiveMessage | ServerPokeEndMessage | ServerPokePartMessage | ServerPokeStartMessage | ServerResumeMessage | ServerSettledMessage | ServerWhisperMessage | ServerWhisperSubscribedMessage;
938
965
  /**
939
966
  * The authenticated user as exposed client-side, mirroring better-auth's
940
967
  * `user` row (the `user` field of the `get-session` response). Kept minimal
@@ -2072,6 +2099,17 @@ declare class LunoraClient {
2072
2099
  * (re)connect so a topic survives a socket bounce.
2073
2100
  */
2074
2101
  private readonly whisperHandlers;
2102
+ /**
2103
+ * Live-topic grants this client asked for over a WebSocket, keyed `connectionKey(shardKey)` →
2104
+ * subscription id → the stream and topic. Replayed on every `identity` frame: each socket is a
2105
+ * new connection id with no grants, so a bounce would otherwise stop delivery silently.
2106
+ */
2107
+ private readonly liveSocketGrants;
2108
+ /** Tail of the live-grant control posts. One chain keeps a subscribe and its unsubscribe in order. */
2109
+ private liveControlChain;
2110
+ /** Join state of each whisper topic, per `connectionKey(shardKey)`, on the current socket. Reset on every open. */
2111
+ private readonly whisperJoins;
2112
+ private nextLiveSocketId;
2075
2113
  /** Last status broadcast, so we only notify listeners on an actual change. */
2076
2114
  private lastStatus;
2077
2115
  private nextSubId;
@@ -2433,6 +2471,37 @@ declare class LunoraClient {
2433
2471
  whisperSubscribe(topic: string, handler: (data: unknown, from?: string) => void, options?: {
2434
2472
  shardKey?: string;
2435
2473
  }): Unsubscribe;
2474
+ /**
2475
+ * Follow a live topic of a `defineLiveStream` stream over this client's WebSocket, instead of
2476
+ * an SSE connection (`connectLiveStream`). Joins the bare topic as a whisper member, then asks
2477
+ * the stream's control route (`/live/<stream>/control`) to grant this socket the topic, naming
2478
+ * the socket's connection id. A live publish reaches the socket only with both in place.
2479
+ *
2480
+ * The join needs the app's `onWhisper` approval, the same as any whisper join. The shard runs
2481
+ * the authorizer with `action: "subscribe"` on the bare topic, and a denied join is silent:
2482
+ * the shard acknowledges every join once processed, admitted or not, so the client cannot tell
2483
+ * a denial from a quiet topic. The grant is posted only after that acknowledgement (or after
2484
+ * `LIVE_CONTROL_TIMEOUT_MS` if it never arrives), so a publish cannot outrun the membership it
2485
+ * needs. A grant posted for a denied join still has no membership, so the shard relays no
2486
+ * `live` frame and `onEvent` never fires. An app that streams private data here must declare an
2487
+ * `onWhisper` that allows the topic; without one the join is open to any socket on the shard.
2488
+ *
2489
+ * Grants are re-issued on every reconnect, because each socket gets a new connection id.
2490
+ * A control call that fails is not retried here, so a failed grant delivers nothing. A refusal
2491
+ * (a 4xx other than 404 and 401) is final: the local grant is dropped, so a later subscribe can
2492
+ * be tried again, and `onError` is called with the status. A transient failure keeps the grant.
2493
+ * @returns an unsubscribe function that revokes the grant and leaves the topic
2494
+ */
2495
+ subscribeLiveTopic(options: {
2496
+ onError?: (error: {
2497
+ status: number;
2498
+ topic: string;
2499
+ }) => void;
2500
+ onEvent: (payload: unknown) => void;
2501
+ shardKey?: string;
2502
+ stream: string;
2503
+ topic: string;
2504
+ }): Unsubscribe;
2436
2505
  /**
2437
2506
  * Broadcast an ephemeral `data` payload to the other members of a whisper
2438
2507
  * `topic` on `options.shardKey`'s shard. Fire-and-forget: the frame is
@@ -4061,6 +4130,53 @@ declare class LunoraClient {
4061
4130
  * client must re-render changed, but the resume position may have moved".
4062
4131
  */
4063
4132
  private ackAndAdvanceCursor;
4133
+ /**
4134
+ * Record the socket's connection id from its `identity` frame, then re-issue every live grant
4135
+ * this shard holds: a new socket starts with none.
4136
+ */
4137
+ private adoptSocketConnectionId;
4138
+ /**
4139
+ * Post the live grant `subscriptionId` for the socket `connectionId`, once the socket has
4140
+ * acknowledged the join of the grant's topic. A publish reaches a member only with both in
4141
+ * place, so a grant that landed first would drop a publish made before the join took effect.
4142
+ * The post is skipped if the grant was released or refused meanwhile, or if the socket changed
4143
+ * since `connectionId` was read: the new socket's identity posts its own grants.
4144
+ */
4145
+ private grantWhenJoined;
4146
+ /** Send a `whisper_subscribe` for `topic` on `conn`, and count it as pending until the shard acknowledges it. */
4147
+ private sendWhisperJoin;
4148
+ /** One `whisper_subscribed` frame arrived: the topic is joined once every join sent for it is acknowledged. */
4149
+ private acknowledgeWhisperJoin;
4150
+ /**
4151
+ * Run `run` once `topic` is joined on the current socket, or after {@link LIVE_CONTROL_TIMEOUT_MS}.
4152
+ * A lost ack must not hold a grant forever, so the timeout runs it anyway: an unacknowledged
4153
+ * join is not necessarily a failed one, and a grant for a join that never landed delivers nothing.
4154
+ */
4155
+ private whenWhisperJoined;
4156
+ /**
4157
+ * Forget the waiters of a socket that is going away, without running them: a grant for the old
4158
+ * socket's connection id is never valid, and the next socket's identity posts its own grants.
4159
+ */
4160
+ private dropWhisperJoinWaiters;
4161
+ private whisperJoinState;
4162
+ /**
4163
+ * Drop a live grant the shard refused for good, and tell its caller. A grant already released
4164
+ * by its unsubscribe handle is gone from the map, so a late refusal reports nothing.
4165
+ */
4166
+ private refuseLiveGrant;
4167
+ /**
4168
+ * POST one live-grant control call, behind every earlier one. The body names the shard when
4169
+ * the socket is not the default one, as the SSE control call does. A refusal (a 4xx other
4170
+ * than 404 and 401) is handed to `onRefused`. Failures are swallowed: a denied grant must
4171
+ * never surface as an unhandled rejection.
4172
+ */
4173
+ private postLiveControl;
4174
+ /**
4175
+ * Route an inbound live publish to the grants on the originating shard whose stream and topic
4176
+ * match. A grant exists only for a subscribed stream and topic, so a frame naming another
4177
+ * stream reaches no handler.
4178
+ */
4179
+ private dispatchLive;
4064
4180
  /** Route an inbound whisper to the topic's handlers on the originating shard. */
4065
4181
  private dispatchWhisper;
4066
4182
  /** Notify every {@link onTokenExpired} listener (best-effort, listener throws swallowed). */
@@ -1,4 +1,4 @@
1
- import { L as LunoraClient, P as Preloaded } from "./lunora-client.d-B22TAgVj.mjs";
1
+ import { L as LunoraClient, P as Preloaded } from "./lunora-client.d-BtqCoSVw.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-Cq8NykWg.js";
1
+ import { L as LunoraClient, P as Preloaded } from "./lunora-client.d-Fds53_IH.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,4 +1,4 @@
1
- import { S as SubscriptionError, L as LunoraClient, a as Unsubscribe } from "../packem_shared/lunora-client.d-B22TAgVj.mjs";
1
+ import { S as SubscriptionError, L as LunoraClient, a as Unsubscribe } from "../packem_shared/lunora-client.d-BtqCoSVw.mjs";
2
2
  export type {
3
3
  /**
4
4
  * `@lunora/client/query` — the framework-neutral live-query state machine shared
@@ -10,7 +10,7 @@ export type {
10
10
  * framework — each adapter supplies thin sinks that write into its own ref /
11
11
  * store / signal / cache.
12
12
  */
13
- b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-B22TAgVj.mjs";
13
+ b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-BtqCoSVw.mjs";
14
14
  import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "../packem_shared/function-reference.d-Br_hsKje.mjs";
15
15
  import '@lunora/errors';
16
16
  import '@lunora/runtime';
@@ -1,4 +1,4 @@
1
- import { S as SubscriptionError, L as LunoraClient, a as Unsubscribe } from "../packem_shared/lunora-client.d-Cq8NykWg.js";
1
+ import { S as SubscriptionError, L as LunoraClient, a as Unsubscribe } from "../packem_shared/lunora-client.d-Fds53_IH.js";
2
2
  export type {
3
3
  /**
4
4
  * `@lunora/client/query` — the framework-neutral live-query state machine shared
@@ -10,7 +10,7 @@ export type {
10
10
  * framework — each adapter supplies thin sinks that write into its own ref /
11
11
  * store / signal / cache.
12
12
  */
13
- b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-Cq8NykWg.js";
13
+ b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-Fds53_IH.js";
14
14
  import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "../packem_shared/function-reference.d-Br_hsKje.js";
15
15
  import '@lunora/errors';
16
16
  import '@lunora/runtime';
@@ -1,4 +1,4 @@
1
- import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-B22TAgVj.mjs";
1
+ import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-BtqCoSVw.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-3Sb8o5sD.mjs";
23
+ a as preloadedQueryResult } from "../packem_shared/preload.d-2WDfHuro.mjs";
24
24
  import '@lunora/errors';
25
25
  import '@lunora/runtime';
26
26
  /**
@@ -1,4 +1,4 @@
1
- import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-Cq8NykWg.js";
1
+ import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-Fds53_IH.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-CPzCWpiu.js";
23
+ a as preloadedQueryResult } from "../packem_shared/preload.d-mgtct7Xi.js";
24
24
  import '@lunora/errors';
25
25
  import '@lunora/runtime';
26
26
  /**
@@ -1 +1 @@
1
- import{getServerSession as o}from"../packem_shared/getServerSession-BaOoo1p6.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-CyFK_cv6.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-C5GKWZsC.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-CyFK_cv6.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-D09Qtsyu.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.221",
3
+ "version": "1.0.0-alpha.222",
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{LunoraError as y}from"@lunora/errors";import{encodeWire as M,decodeWire as w,stableWireKey as oe}from"@lunora/wire";import{r as Pe,U as Fe,P as He}from"./delta-merge-Ls3DED4g.mjs";import Le from"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import{s as Y,a as Me,e as N,r as Ue,b as ce,c as Ne,d as de}from"./wire-errors-WYlbE1Nh.mjs";import{ClientQueryStore as xe}from"./createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as De}from"./TabCoordinator-CXD7vulJ.mjs";import{TransportError as L,getRetryAfterMs as Be,AUTH_REPLAY_ERROR_CODES as Qe,isAuthReplayFailure as W}from"./CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as Ke}from"./httpStream-BhSpxRWB.mjs";import{d as X,r as O,a as P,b as qe,c as We,e as je,f as $e}from"./local-store-fqWV2n_Z.mjs";import{O as Ge,n as he,i as Ve,r as ze}from"./offline-queue-D_fr-uQ3.mjs";import{resolvePersistenceAdapter as Je}from"./createInMemoryPersistence-Cz2W6XVj.mjs";import{resolveQueryCacheAdapter as Ye,queryCacheKey as _}from"./createInMemoryQueryCache-D2uNHLfM.mjs";import{createReconnect as ue}from"./createReconnect-CjTmjJDH.mjs";import{fanSubscriptionError as A,SubscriptionRegistry as v,wrapSubscriber as j}from"./SubscriptionRegistry-DKIXE7M7.mjs";import Xe from"./createSnapshotPrecondition-CLkxVeN1.mjs";import{createStream as Ze}from"./DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";const $=500,ge=(i,e)=>{if(i.size<e)return;const t=i.keys().next().value;t!==void 0&&i.delete(t)},C="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",et=i=>{let e="",t=0;const s=i.length-2;for(;t<s;t+=3){const n=i[t]<<16|i[t+1]<<8|i[t+2];e+=C.charAt(n>>18&63)+C.charAt(n>>12&63)+C.charAt(n>>6&63)+C.charAt(n&63)}const r=i.length-t;if(r===1){const n=i[t]<<16;e+=C.charAt(n>>18&63)+C.charAt(n>>12&63)}else if(r===2){const n=i[t]<<16|i[t+1]<<8;e+=C.charAt(n>>18&63)+C.charAt(n>>12&63)+C.charAt(n>>6&63)}return e};new TextDecoder;const tt=new TextEncoder,st=i=>et(tt.encode(JSON.stringify(i))),rt="x-lunora-expect-subject",it=i=>st({subject:i}),le=Symbol.for("lunora:session-change"),nt="lunora:session-change",at="better-auth.message",ot="signout",Te=()=>{const i=globalThis;let e=i[le];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},i[le]=e),e},ct=()=>"document"in globalThis,dt=async()=>{const i=[];for(const e of Te().listeners)try{i.push(e())}catch{}await Promise.allSettled(i)},ht=(i,e)=>{if(i!==at||e===null)return!1;try{const t=JSON.parse(e);return t?.event==="session"&&t.data?.trigger===ot}catch{return!1}},ut=i=>{const e=[],t=()=>{dt().catch(()=>{})};let s;try{s=typeof BroadcastChannel=="function"?new BroadcastChannel(nt):void 0}catch{s=void 0}if(s!==void 0){const n=s;n.addEventListener("message",o=>{o.data?.type==="lunora:session-change"&&o.data.tab!==i&&t()}),e.push(()=>{n.close()})}const r=globalThis;if(typeof r.addEventListener=="function"){const n=o=>{ht(o.key,o.newValue)&&t()};r.addEventListener("storage",n),e.push(()=>{r.removeEventListener?.("storage",n)})}return()=>{for(const n of e)n()}},lt=i=>{const e=Te();return e.listeners.add(i),e.detach===void 0&&ct()&&(e.detach=ut(e.tab)),()=>{e.listeners.delete(i),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},ft="/_lunora/rpc",G="/_lunora/rpc-batch",mt="/_lunora/ws",pt="/_lunora/admin/shard-traffic",yt="/_lunora/admin/scheduled",St="/_lunora/admin/scheduled/status",bt="/_lunora/admin/scheduled/ws",gt="/_lunora/admin/scheduled/cancel",fe="/_lunora/admin/scheduled/dead",Tt="/_lunora/admin/scheduled/dead/retry",vt="/_lunora/admin/scheduled/dead/cancel",Ct="/_lunora/admin/workflows/instances",kt="/_lunora/admin/workflows/instance",wt="/_lunora/admin/workflows/status",se="/_lunora/admin/storage",Et="/_lunora/admin/storage/url",At="/_lunora/admin/storage/buckets",_t="/_lunora/admin/functions",It="/_lunora/admin/cron-jobs",Ot="/_lunora/admin/cron-jobs/run",Rt="/_lunora/admin/architecture",Pt="/_lunora/admin/openapi",Ft="/_lunora/admin/openrpc",Ht="/_lunora/admin/global/tables",Lt="/_lunora/admin/global/table",Mt="/_lunora/admin/global/facet",Ut="/_lunora/admin/vector/indexes",Nt="/_lunora/admin/vector/query",xt="/_lunora/admin/logs/archive",Dt="/_lunora/admin/kv/namespaces",Bt="/_lunora/admin/kv/keys",re="/_lunora/admin/kv/value",Qt="/_lunora/admin/auth/users",Kt="/_lunora/admin/auth/sessions",qt="/_lunora/admin/auth/users/create",Wt="/_lunora/admin/auth/users/role",jt="/_lunora/admin/auth/users/ban",$t="/_lunora/admin/auth/users/unban",Gt="/_lunora/admin/auth/users/password",Vt="/_lunora/admin/auth/users/remove",zt="/_lunora/admin/auth/users/impersonate",Jt="/_lunora/admin/auth/sessions/revoke",Yt="/_lunora/admin/auth/sessions/revoke-all",Xt="/_lunora/admin/auth/capabilities",Zt="/_lunora/admin/auth/users/update",es="/_lunora/admin/auth/accounts",ts="/_lunora/admin/auth/accounts/unlink",ss="/_lunora/admin/auth/passkeys",rs="/_lunora/admin/auth/passkeys/delete",is="/_lunora/admin/auth/two-factor/disable",ns="/_lunora/admin/auth/organizations",as="/_lunora/admin/auth/organizations/members",os="/_lunora/admin/auth/organizations/invitations",cs="/_lunora/admin/auth/organizations/members/remove",ds="/_lunora/admin/auth/organizations/invitations/cancel",hs="/_lunora/admin/auth/config",us="/_lunora/admin/auth/sign-up-invitations",ls="/_lunora/admin/auth/sign-up-invitations/create",fs="/_lunora/admin/auth/sign-up-invitations/revoke",ms="/_lunora/admin/auth/organizations/create",ps="/_lunora/admin/auth/organizations/update",ys="/_lunora/admin/auth/organizations/remove",Ss="/_lunora/admin/auth/organizations/members/add",bs="/_lunora/admin/auth/organizations/members/invite",gs="/_lunora/admin/auth/organizations/members/role",Ts="/_lunora/admin/auth/organizations/teams",vs="/_lunora/admin/auth/organizations/teams/create",Cs="/_lunora/admin/auth/organizations/teams/update",ks="/_lunora/admin/auth/organizations/teams/remove",ws="/_lunora/admin/auth/organizations/teams/members",Es="/_lunora/admin/auth/organizations/teams/members/add",As="/_lunora/admin/auth/organizations/teams/members/remove",_s="/_lunora/admin/auth/organizations/roles",Is="/_lunora/admin/auth/organizations/roles/create",Os="/_lunora/admin/auth/organizations/roles/update",Rs="/_lunora/admin/auth/organizations/roles/remove",Ps="/api/auth",Fs="/get-session",Hs="lunora-ping",Ls=async i=>(i.assertOpen(),(await i.adminFetch(_t,"GET")).functions??[]),Ms=async i=>(i.assertOpen(),(await i.adminFetch(It,"GET")).jobs??[]),Us=async(i,e)=>{i.assertOpen();const t=await i.adminFetch(Ot,"POST",{name:e});return{name:t.name??e,ran:t.ran===!0}},Ns=async i=>(i.assertOpen(),await i.adminFetch(Pt,"GET")),xs=async i=>(i.assertOpen(),await i.adminFetch(Rt,"GET")),Ds=async i=>(i.assertOpen(),await i.adminFetch(Ft,"GET")),Bs=async i=>(i.assertOpen(),await i.adminFetch(Ht,"GET")),Qs=async(i,e)=>{i.assertOpen();const t=new URLSearchParams({table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(M(e.filters))),w(await i.adminFetch(`${Lt}?${t.toString()}`,"GET"))},Ks=async(i,e)=>{i.assertOpen();const t=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(M(e.filters))),w(await i.adminFetch(`${Mt}?${t.toString()}`,"GET"))},ie=i=>i===void 0||i===""?"":`&bucket=${encodeURIComponent(i)}`,me=i=>i.startsWith("https://")?`wss://${i.slice(8)}`:i.startsWith("http://")?`ws://${i.slice(7)}`:i,E=(i,e)=>`${i.endsWith("/")?i.slice(0,-1):i}${e}`,S=(i,e)=>{const t=new URLSearchParams;for(const[r,n]of Object.entries(e))n!==void 0&&n!==""&&t.set(r,String(n));const s=t.toString();return s===""?i:`${i}?${s}`},qs=async i=>(i.assertOpen(),(await i.adminFetch(Dt,"GET")).namespaces??[]),Ws=async(i,e)=>{i.assertOpen();const t=S(Bt,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await i.adminFetch(t,"GET")},js=async(i,e)=>{i.assertOpen();const t=S(re,{key:e.key,namespace:e.namespace});return await i.adminFetch(t,"GET")},$s=async(i,e)=>{i.assertOpen(),await i.adminFetch(re,"PUT",e)},Gs=async(i,e)=>{i.assertOpen();const t=S(re,{key:e.key,namespace:e.namespace});await i.adminFetch(t,"DELETE")},Vs=async(i,e)=>{i.assertOpen();const t=await i.adminFetch(pt,"POST",{table:e});return{failed:t.failed??0,ok:t.ok??0,shards:t.shards??[]}},zs=async(i,e={})=>{i.assertOpen();const t=await i.adminFetch(xt,"POST",e);return{nextCursor:t.nextCursor,rows:t.rows??[]}},Js=async i=>{const e=[];let t;for(;;){const s=await i(t);if(e.push(...Array.isArray(s.records)?s.records:[]),s.truncated!==!0||typeof s.cursor!="string"||s.cursor.length===0)return e;if(s.cursor===t)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");t=s.cursor}},ne=i=>"args"in i?{...i,args:w(i.args)}:i,Ys=async i=>(i.assertOpen(),((await i.adminFetch(yt,"GET")).records??[]).map(t=>ne(t))),Xs=async i=>{i.assertOpen();const e=await i.adminFetch(St,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},Zs=async(i,e)=>(i.assertOpen(),{cancelled:(await i.adminFetch(gt,"POST",{id:e})).cancelled===!0}),er=async i=>(i.assertOpen(),(await Js(async t=>await i.adminFetch(t===void 0?fe:`${fe}?cursor=${encodeURIComponent(t)}`,"GET"))).map(t=>ne(t))),tr=async(i,e)=>(i.assertOpen(),{retried:(await i.adminFetch(Tt,"POST",{id:e})).retried===!0}),sr=async(i,e)=>(i.assertOpen(),{removed:(await i.adminFetch(vt,"POST",{id:e})).removed===!0}),rr=async(i,e)=>{i.assertOpen();const t=new URLSearchParams({name:e.name});e.status!==void 0&&t.set("status",e.status),e.page!==void 0&&t.set("page",String(e.page)),e.perPage!==void 0&&t.set("perPage",String(e.perPage));const s=await i.adminFetch(`${Ct}?${t.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}},ir=async(i,e)=>{i.assertOpen();const t=new URLSearchParams({id:e.id,name:e.name}),s=await i.adminFetch(`${kt}?${t.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??e.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}},nr=async(i,e)=>(i.assertOpen(),{status:(await i.adminFetch(wt,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),ar=async(i,e={})=>{i.assertOpen();const t=S(se,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await i.adminFetch(t,"GET");return{cursor:s.cursor,objects:s.objects??[]}},or=async(i,e,t)=>{i.assertOpen();const s=`${se}?key=${encodeURIComponent(e)}${ie(t?.bucket)}`,r=await i.adminFetch(s,"DELETE");return{deleted:r.deleted===!0,key:r.key??e}},cr=async i=>(i.assertOpen(),(await i.adminFetch(At,"GET")).buckets??[]),dr=async(i,e)=>{i.assertOpen();const t=`${se}?key=${encodeURIComponent(e.key)}${ie(e.bucket)}`,s=await i.adminFetch(t,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}},hr=async(i,e,t)=>{i.assertOpen();const s=t?.expiresInSeconds,r=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,n=`${Et}?key=${encodeURIComponent(e)}${r}${ie(t?.bucket)}`,o=await i.adminFetch(n,"GET");if(typeof o.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return o.url},ur=async i=>(i.assertOpen(),(await i.adminFetch(Ut,"GET")).indexes??[]),lr=async(i,e)=>(i.assertOpen(),(await i.adminFetch(Nt,"POST",e)).matches??[]),k=(i,e)=>{try{return M(i)}catch(t){const s=t instanceof Error?t.message:String(t);throw new TypeError(`LunoraClient: cannot encode ${e} — ${s}`,t instanceof Error?{cause:t}:void 0)}},pe=i=>{try{return M(i),!0}catch{return!1}},ve=i=>i!==null&&typeof i=="object"&&("error"in i||"result"in i),fr=(i,e)=>{const t=Array.from({length:e});for(const s of i){if(typeof s.id!="number"||s.id<0||s.id>=e)continue;if(!ve(s.body)){t[s.id]={error:Y({}),ok:!1};continue}const r=s.body;t[s.id]="error"in r?{error:Y(r),ok:!1}:{ok:!0,value:w(r.result)}}return t.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},V=(i,e)=>e!==null?{}:i===null?{expectSubject:null}:i?.startsWith("subj:")===!0?{expectSubject:i.slice(5)}:{},mr=3e4,pr=1e4,yr=5e3,Sr=3,br=250,gr=5e3,Tr=5e3,vr=64,Cr=3,kr=1e4,wr=8,z=i=>i==="connected"||i==="polling",l=i=>i??"",g=(i,e)=>{if(!i.socket||i.wsState!=="open")return!1;try{return i.socket.send(JSON.stringify(e)),!0}catch{return!1}},Er=i=>{if(!i.pendingStreams||i.pendingStreams.length===0)return;const e=i.pendingStreams;i.pendingStreams=[];for(const t of e)g(i,t)},Ar=new TextDecoder,_r=i=>{if(typeof i=="string")return i;if(i instanceof ArrayBuffer)return Ar.decode(i)};class I{listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){const[t]=e;for(const s of this.listeners)try{s(t)}catch{}}clear(){this.listeners.clear()}}const H=i=>{i.heartbeatTimer!==void 0&&(clearInterval(i.heartbeatTimer),i.heartbeatTimer=void 0)},Ir=(i,e,t)=>{H(i),!(e<=0)&&(i.heartbeatTimer=setInterval(()=>{if(!i.socket)return;const{socket:s}=i;if(Date.now()-i.lastFrameAt>e*2.5){try{s.close()}catch{}t();return}try{s.send(Hs)}catch{}},e))},ye=(i,e,t,s)=>{const{WebSocketImpl:r,connectTimeoutMs:n,heartbeatIntervalMs:o}=t;if(r===void 0)throw new y("INTERNAL","no WebSocket implementation available");const a=new r(e);i.socket=a;const c=()=>{H(i),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),i.socket===a&&(i.socket=void 0)},d=h=>{c(),s.onClose(h)};n>0&&(i.connectTimer=setTimeout(()=>{if(i.connectTimer=void 0,i.socket===a){try{a.close()}catch{}d()}},n)),a.addEventListener("open",()=>{if(i.socket===a){i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),i.lastFrameAt=Date.now();try{s.onOpen?.()}catch(h){console.error("[lunora] connection open handler threw",h)}Ir(i,o,d)}}),a.addEventListener("message",h=>{if(i.socket===a){i.lastFrameAt=Date.now();try{s.onMessage(h)}catch(u){console.error("[lunora] server frame handler threw",u)}}}),a.addEventListener("close",h=>{i.socket===a&&d(h)}),a.addEventListener("error",()=>{i.socket===a&&d()})},Or=i=>{const{afterFailedAttempts:e,intervalMs:t,onReachable:s,onStateChange:r,poll:n}=i,o=t>0&&e>0;let a=0,c,d=!1,h=!1;const u=()=>{c!==void 0&&(clearInterval(c),c=void 0,d=!1,r())},m=f=>{if(c!==void 0){if(!f){u();return}d||(d=!0,r()),s()}},p=()=>{h||(h=!0,n().then(m).finally(()=>{h=!1}).catch(()=>{}))};return{isPolling:()=>c!==void 0&&d,noteFailedOpen:()=>{a+=1,!(!o||c!==void 0||a<e)&&(c=setInterval(p,t),r(),p())},noteOpen:()=>{a=0,u()},stop:u}},Rr=1e4,Se=async i=>{const e=new AbortController;let t;const s=new Promise((r,n)=>{t=setTimeout(()=>{e.abort(),n(new TypeError("LunoraClient: poll timed out"))},Rr)});try{return await Promise.race([i(e.signal),s])}catch(r){throw e.signal.aborted?new TypeError("LunoraClient: poll timed out"):r}finally{clearTimeout(t)}},Ce=new Set(["DELIVERY_FENCED","RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Pr=i=>{if(i instanceof L)return!0;const e=i?.code;return e===void 0||Ce.has(e)||Qe.has(e)},ke=6e4,Fr=1e3,Hr={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},F=(i,e,t)=>{const s=Me(t),r=s===void 0?void 0:{retryAfterMs:s},n=`LunoraClient: response carried no error envelope (status ${i.toString()}${e?` ${e}`:""})`;return i<400||i>=500||i===408?new L(n,r):new y(Hr[i]??"BAD_REQUEST",n,{data:r})},Z=(i,e=Math.random)=>{const t=Math.min(Fr*2**Math.max(i-1,0),ke);return Math.round(t*(.5+e()*.5))},Lr=i=>i instanceof L||Ce.has(i?.code??""),Mr=(i,e,t)=>{const s=Be(i);return s!==void 0&&s>0?Math.min(s,ke):Lr(i)?Z(e,t):void 0},Ur=983040,Nr=i=>typeof TextEncoder>"u"?i.length:new TextEncoder().encode(i).length,we=new WeakSet,Ee=i=>{const e=new y("WIRE_DECODE_FAILED",`LunoraClient: the call succeeded but its result could not be decoded (a mutation has still committed) — ${i instanceof Error?i.message:String(i)}`,{cause:i});return we.add(e),e},x=i=>i instanceof Error&&we.has(i),xr=i=>{const e=new Map;for(const t of i)typeof t.id=="number"&&ve(t.body)&&e.set(t.id,t.body);return e},Dr=i=>{if(i===void 0)return{kind:"unanswered"};if("error"in i)return{error:Y(i),kind:"errored"};try{return{commitCursor:i.commitCursor,kind:"committed",value:w(i.result)}}catch(e){return{commitCursor:i.commitCursor,error:Ee(e),kind:"undecodable"}}},J=(i,e)=>`${l(i)}\0${e}`,Br=(i,e)=>{for(const t of e)t.op==="delete"?i.delete(t.key):t.value!==void 0&&i.set(t.key,t.value)};class Qr{constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,t){ge(this.buffers,this.maxBuffers),this.buffers.set(J(e,t.pokeId),{baseCheckpoint:t.baseCheckpoint,bases:new Map,epoch:t.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}part(e,t){const s=this.buffers.get(J(e,t.pokeId));if(!s)return;const r=[];try{for(const a of t.rowsPatch)r.push(a.value===void 0?a:{...a,value:w(a.value)})}catch(a){s.undecodable.set(t.shapeId,a);return}const n=s.parts.get(t.shapeId)??[];for(const a of r)n.push(a);s.parts.set(t.shapeId,n),t.lastMutationId!==void 0&&s.lastMutationId.set(t.shapeId,t.lastMutationId);const o=t.baseCheckpoint??s.baseCheckpoint;o!==void 0&&s.bases.set(t.shapeId,o),t.reset===!0&&s.resets.add(t.shapeId)}end(e,t){const s=J(e,t),r=this.buffers.get(s);return r&&this.buffers.delete(s),r}clear(){this.buffers.clear()}}const Kr=(i,e,t)=>{const s=e.parts.get(i.id)??[],r=e.resets.has(i.id),n=e.bases.get(i.id),o=e.epoch!==void 0&&i.serverEpoch!==void 0&&e.epoch!==i.serverEpoch,a=n!==void 0&&i.serverCursor!==void 0&&i.serverCursor!==n;if(!r&&(o||a))return i.rows.clear(),i.serverCursor=void 0,i.serverEpoch=void 0,"reseed";r&&i.rows.clear(),Br(i.rows,s),t.checkpoint!==void 0&&(i.serverCursor=t.checkpoint),t.epoch!==void 0&&(i.serverEpoch=t.epoch);const c=e.lastMutationId.get(i.id);return c!==void 0&&(i.lastMutationId=c),"applied"},be=i=>{const e=[...i.rows.values()];for(const t of i.callbacks)try{t(e)}catch{}},qr=(i,e)=>{for(const[t,s]of e.undecodable){const r=i.get(t);r&&A(r.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape — ${s instanceof Error?s.message:String(s)}`})}},ee=(i,e)=>{i.lastMutationId=Math.max(i.lastMutationId??0,e)},te=(i,e=!1)=>{for(const t of i.checkpointCallbacks)t({checkpoint:i.serverCursor,mutationId:i.lastMutationId,...e&&{rowsFollow:!0}})},Ae=(i,e,t)=>{i.serverBase=e,t.cursor!==void 0&&(i.serverCursor=t.cursor),t.epoch!==void 0&&(i.serverEpoch=t.epoch)},D=(i,e)=>i!==void 0&&i!==e,Wr=(i,e)=>e==="connected"&&i!=="connected"||e==="polling"&&i!=="connected"&&i!=="polling",jr=i=>{for(const e of i.activeSubscriptions())i.ensureSocket(e.shardKey),i.queueResubscribe(e);for(const e of i.queuedShardKeys())i.ensureSocket(e);i.broadcastStatus(i.computeStatus(),i.identityFingerprint())},$r=i=>{i.closeConnections();const e=i.leader;e.status=void 0,e.wasEverConnected=!1},Gr=(i,e,t)=>{if(D(t,i.identityFingerprint()))return;const s=i.leader,r=Wr(s.status,e);s.status=e,e==="connected"&&(s.wasEverConnected=!0),i.emitConnectionStatus(),r&&i.flushOfflineQueues()},Vr=i=>{i.isLeader()&&i.broadcastStatus(i.computeStatus(),i.identityFingerprint())},zr=(i,e,t,s,r,n)=>{if(D(n,i.identityFingerprint()))return;const o=i.subscription(e);o&&(i.dropCacheSeed(e),Ae(o,t,s===void 0?{}:{cursor:s,epoch:r}),s!==void 0&&X(o,s),O(o,t))},Jr=(i,e,t,s)=>{if(D(s,i.identityFingerprint()))return;const r=i.subscription(e);r&&A(r.errorCallbacks,t)},Yr=(i,e,t,s,r,n,o)=>{if(D(o,i.identityFingerprint()))return;const a=i.subscription(e);a&&(i.ackAndAdvanceCursor(a,t,s),r!==void 0&&n===i.clientIdentifier()&&ee(a,r),te(a))},Xr=(i,e,t)=>i!==null||e&&t===null,Zr=[He],ei=100,ti=Promise.resolve();class _e{static MAX_POKE_BUFFERS=256;static createClientQuery(e,t){return{defaultValue:t,key:e}}url;wsUrl;adminHost={adminFetch:(...e)=>this.adminFetch(...e),assertOpen:()=>{this.assertOpen()}};clientQueryStore;wsToken;wsTokenGeneration=0;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new v;tabCoordinator;leader={status:void 0,wasEverConnected:!1};connections=new Map;idleClosedShards=new Set;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;subjectToken=null;sessionProbesInFlight=0;sessionProbeGeneration=0;identityQuestions=0;identityAnsweredAt=0;releaseSessionChangeListener;warnedIdentityDisagreement=!1;identityResolutionExpected=!1;identitySettled=!1;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new I;statusListeners=new I;roomFlushes=new Map;roomIdentityResets=new Set;tokenExpiredListeners=new I;identityChangeListeners=new I;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new I;pendingChangeListeners=new I;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new Qr(_e.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??E(me(e.url),mt),this.wsToken=e.wsToken;const t=e.authBasePath??Ps;this.authBasePath=t.endsWith("/")?t.slice(0,-1):t,this.fetchImpl=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=e.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=e.bookmarkStorage??Le(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??mr,this.connectTimeoutMs=e.connectTimeoutMs??pr,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??yr,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??Sr,this.defaultConnectionContext=e.connectionContext,this.persistence=Je(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Ye(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new xe,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=ti),this.offlineQueue=new Ge(e.offlineQueue,{onEvict:(s,r)=>{this.emitItemSettled(s,"rejected",r),this.releaseIdleShard(s.shardKey)},onSizeChange:s=>{this.pendingChangeListeners.emit(s)},persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${he()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=lt(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,t){const s=this.authToken!==e,r=this.identityFingerprint(),n=this.authSubject===void 0||this.subjectToken===this.authToken,o=this.subjectAwaitingReconfirm(),a=this.isKnownNobody(),c=this.authToken;this.authToken=e,this.applySubject(e,t);const d=this.identityFingerprint();d!==r&&(!s&&e!==null&&n?(this.restampQueuedIdentity(r,d),this.restampWatermarks(r,d),this.restampConnectionIdentity(r,d),this.reseedFromHydratedCache()):!s&&e===null&&r===null&&n&&!a?(this.restampWatermarks(r,d),this.restampConnectionIdentity(r,d),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(r),this.warnRefreshWithoutSubject(c,e),Xr(r,a,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(o),s&&this.authTokenListeners.emit(e),(d!==r||s||o)&&this.offlineQueue.size>0&&z(this.computeStatus())&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}expectIdentityResolution(){this.identityResolutionExpected=!0}currentBaseline(e){return this.baselineCursorFor(e)}replayIdentityVerdict(e){const t=this.identityVerdict(e);if(t!=="match")return{verdict:t};const s=Object.freeze({});return this.replayCredentials.set(s,{authToken:this.authToken,stamp:e}),{credential:s,verdict:t}}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,t,s){const r=s?.clientSeq;if(r!==void 0&&(!Number.isInteger(r)||r<=0))throw new y("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(r)}`);const n=s?.shardKey??"",o=this.identityFingerprint();let a,c,d;try{c=await this.rpc(e,t,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:r,onMutationAck:u=>{a=u}})}catch(u){if(!x(u))throw u;d=u}if(a!==void 0&&a>(this.clientWatermarks.get(o??"")?.get(n)??0)){let u=this.clientWatermarks.get(o??"");u===void 0&&(ge(this.clientWatermarks,wr),u=new Map,this.clientWatermarks.set(o??"",u)),u.set(n,a)}if(d!==void 0)throw d;return{applied:a===void 0||a===r,result:c}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}onIdentityChange(e){return this.identityChangeListeners.add(e)}identityEpoch(){return this.retiredIdentities}async getCurrentUser(){if(this.identityResolutionExpected=!0,this.closed||!this.fetchImpl)return this.identitySettled=!0,null;const e={},t=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`),this.sessionProbesInFlight+=1,this.identityQuestions+=1,this.sessionProbeGeneration=this.identityQuestions;const s=this.sessionProbeGeneration;try{const r=await this.fetchImpl(E(this.url,`${this.authBasePath}${Fs}`),{credentials:"include",headers:e,method:"GET"});if(!r.ok)return this.identitySettled=!0,r.status===401&&this.adoptResolvedSubject(t,null,s),null;const o=(await r.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(t,o,s),o}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.wsTokenGeneration+=1,this.resetRoomSends(),this.bounceShardSockets())}setConnectionContext(e,t={}){this.assertLeaderOwnedSurface("setConnectionContext");const s=l(t.shardKey);e===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,e),this.refreshConnectionContext(s),e===void 0&&this.releaseIdleShard(t.shardKey)}acquireConnectionContext(e,t={}){if(this.followsAnotherTab())return()=>{};const s=l(t.shardKey),r={context:e},n=this.connectionContextHolders.get(s);n?n.push(r):this.connectionContextHolders.set(s,[r]),this.refreshConnectionContext(s);let o=!1;return()=>{if(o)return;o=!0;const a=this.connectionContextHolders.get(s);if(!a)return;const c=a.indexOf(r);c!==-1&&a.splice(c,1),a.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s),this.releaseIdleShard(t.shardKey)}}whisperSubscribe(e,t,s={}){this.assertLeaderOwnedSurface("whisperSubscribe");const r=l(s.shardKey);let n=this.whisperHandlers.get(r);n||(n=new Map,this.whisperHandlers.set(r,n));let o=n.get(e);const a=o===void 0;if(o||(o=new Set,n.set(e,o)),o.add(t),this.ensureSocket(s.shardKey),a){const c=this.getConnection(s.shardKey);c&&g(c,{topic:e,type:"whisper_subscribe"})}return()=>{const c=this.whisperHandlers.get(r),d=c?.get(e);if(!d?.delete(t)||d.size>0)return;c?.delete(e),c?.size===0&&this.whisperHandlers.delete(r);const h=this.getConnection(s.shardKey);h&&g(h,{topic:e,type:"whisper_unsubscribe"}),this.releaseIdleShard(s.shardKey)}}whisper(e,t,s={}){return this.assertLeaderOwnedSurface("whisper"),this.sendEncodedWhisper(e,k(t??null,`whisper data for topic '${e}'`),s)}connectRoom(e,t,s={}){const r=`room:${e.name}`,n=this.whisperSubscribe(r,m=>{t.onMessage(m)},s);let o=!1;const a=[],c=()=>{a.length=0},d=()=>{for(;a.length>0&&this.roomSendsAdmitted(s.shardKey);){if(!this.sendEncodedWhisper(r,a[0],s))return;a.shift()}},h=l(s.shardKey),u=this.roomFlushes.get(h)??new Set;return u.add(d),this.roomFlushes.set(h,u),this.roomIdentityResets.add(c),{close:()=>{o=!0,a.length=0,u.delete(d),u.size===0&&this.roomFlushes.delete(h),this.roomIdentityResets.delete(c),n()},send:m=>{if(o||this.closed||this.WebSocketImpl===void 0)return!1;const p=k(m,`room message for '${r}'`),f=typeof structuredClone=="function"?structuredClone(p):JSON.parse(JSON.stringify(p));return d(),a.length===0&&this.roomSendsAdmitted(s.shardKey)&&this.sendEncodedWhisper(r,f,s)?!0:a.length>=ei?!1:(a.push(f),!0)}}}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){const t=this.statusListeners.add(e);return e(this.computeStatus()),t}pendingCount(){return this.offlineQueue.size}debug(){const e=[],t=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...t?.keys()??[]]);for(const n of s){const o=this.connections.get(n);e.push({confirmedMutationWatermark:t?.get(n)??0,hasSocket:o?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:o?.wasEverConnected??!1,wsState:o?.wsState??"idle"})}const r=this.subscriptions.all().map(n=>({acked:n.acked,functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(const n of this.shapeSubscriptions.values())r.push({acked:n.serverCursor!==void 0,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,o)=>(n.shardKey??"").localeCompare(o.shardKey??"")),subscriptions:r.toSorted((n,o)=>n.functionPath.localeCompare(o.functionPath))}}onPendingChange(e){const t=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),t}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,t){this.clientQueryStore.set(e,t)}subscribeClientQuery(e,t){return this.clientQueryStore.subscribe(e,t)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,t,s){return Xe(this,e,t,s)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,t,s){return this.peekHydratedQueryByKey(e,oe(t),s)}peekHydratedQueryByKey(e,t,s){if(!this.readyResolved)return;const r=_(e,t,s),n=this.hydratedQueryCache.get(r);if(n!==void 0)return this.cachedQueryMatchesIdentity(n)?n.value:void 0}peekActiveQuerySnapshot(e,t,s){const r=v.key(e,t,s),n=this.subscriptions.get(r);return{present:n!==void 0,value:n?.lastValue}}async query(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0})}async batch(e){return this.sendBatch(e)}async mutation(e,t,s={}){const{value:r}=await this.runMutation(e,t,s);return r}canQueueOffline(e){const{wasEverConnected:t}=this.connectionGateState(e);return this.WebSocketImpl!==void 0&&(t||this.offlineQueue.queueBeforeFirstConnect)}async action(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0,captureBookmark:!0})}async importRows(e,t,s={}){this.assertOpen();const r=Math.max(1,Math.trunc(s.chunkSize??500)),n=s.toArgs??(h=>({rows:h})),o=t.length;let a=0,c=0,d=0;for(let h=0;h<o;h+=r){const u=t.slice(h,h+r),m=d,{committed:p}=await this.runMutation(e,n(u),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(m)}`},shardKey:s.shardKey});d+=1,a+=u.length,p&&(c+=u.length),s.onProgress?.({done:a,total:o})}return{chunks:d,imported:c,queued:a-c}}async shardTraffic(e){return Vs(this.adminHost,e)}async listScheduledJobs(){return Ys(this.adminHost)}async schedulerStatus(){return Xs(this.adminHost)}async cancelScheduledJob(e){return Zs(this.adminHost,e)}async listDeadJobs(){return er(this.adminHost)}async retryDeadJob(e){return tr(this.adminHost,e)}async removeDeadJob(e){return sr(this.adminHost,e)}async listWorkflowInstances(e){return rr(this.adminHost,e)}async getWorkflowInstance(e){return ir(this.adminHost,e)}async setWorkflowInstanceStatus(e){return nr(this.adminHost,e)}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const t=E(me(this.url),bt),s=ue(this.reconnectOptions),r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let n,o=!1;const a=()=>{o||this.closed||(n=setTimeout(h,s.next()))},c=m=>{if(o||this.WebSocketImpl===void 0)return;const p=m===void 0?t:`${t}?token=${encodeURIComponent(m)}`;ye(r,p,this.managedSocketOptions,{onClose:()=>{a()},onMessage:f=>{let b;try{b=JSON.parse(typeof f.data=="string"?f.data:"")}catch{return}b.type==="jobs"&&Array.isArray(b.records)&&(s.reset(),e(b.records.map(T=>ne(T))))}})},d=async m=>{let p;try{p=await m()}catch{a();return}c(p)},h=()=>{if(o||this.WebSocketImpl===void 0)return;const{wsToken:m}=this;if(typeof m=="function"){d(m).catch(()=>{});return}c(m)};h();const u=()=>{o=!0,n!==void 0&&(clearTimeout(n),n=void 0),r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),H(r),r.socket?.close(),r.socket=void 0};return this.adminSocketTeardowns.add(u),()=>{this.adminSocketTeardowns.delete(u),u()}}async listFunctions(){return Ls(this.adminHost)}async getCronJobs(){return Ms(this.adminHost)}async runCronJob(e){return Us(this.adminHost,e)}async fetchOpenApi(){return Ns(this.adminHost)}async fetchArchitecture(){return xs(this.adminHost)}async fetchOpenRpc(){return Ds(this.adminHost)}async listStorageObjects(e={}){return ar(this.adminHost,e)}async deleteStorageObject(e,t){return or(this.adminHost,e,t)}async listStorageBuckets(){return cr(this.adminHost)}async uploadStorageObject(e){return dr(this.adminHost,e)}async signedStorageUrl(e,t){return hr(this.adminHost,e,t)}async listGlobalTables(){return Bs(this.adminHost)}async readGlobalTablePage(e){return Qs(this.adminHost,e)}async facetGlobalColumn(e){return Ks(this.adminHost,e)}async listVectorIndexes(){return ur(this.adminHost)}async queryVectorIndex(e){return lr(this.adminHost,e)}async queryLogArchive(e={}){return zs(this.adminHost,e)}async listKvNamespaces(){return qs(this.adminHost)}async listKvKeys(e){return Ws(this.adminHost,e)}async getKvValue(e){return js(this.adminHost,e)}async putKvValue(e){return $s(this.adminHost,e)}async deleteKvKey(e){return Gs(this.adminHost,e)}async listAuthUsers(e={}){this.assertOpen();const t=S(Qt,{filterField:e.filterField,filterValue:e.filterValue,limit:e.limit,offset:e.offset,search:e.search,searchField:e.searchField,sortBy:e.sortBy,sortDirection:e.sortDirection});return await this.adminFetch(t,"GET")}async createAuthUser(e){return this.assertOpen(),await this.adminFetch(qt,"POST",e)}async setAuthUserRole(e){return this.assertOpen(),await this.adminFetch(Wt,"POST",e)}async banAuthUser(e){return this.assertOpen(),await this.adminFetch(jt,"POST",e)}async unbanAuthUser(e){return this.assertOpen(),await this.adminFetch($t,"POST",e)}async setAuthUserPassword(e){this.assertOpen(),await this.adminFetch(Gt,"POST",e)}async removeAuthUser(e){this.assertOpen(),await this.adminFetch(Vt,"POST",e)}async impersonateAuthUser(e){return this.assertOpen(),await this.adminFetch(zt,"POST",e)}async revokeAuthSession(e){this.assertOpen(),await this.adminFetch(Jt,"POST",e)}async revokeAuthUserSessions(e){this.assertOpen(),await this.adminFetch(Yt,"POST",e)}async getAuthCapabilities(){return this.assertOpen(),await this.adminFetch(Xt,"GET")}async updateAuthUser(e){return this.assertOpen(),await this.adminFetch(Zt,"POST",e)}async listAuthAccounts(e){return this.assertOpen(),await this.adminFetch(S(es,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.assertOpen(),await this.adminFetch(ts,"POST",e)}async listAuthPasskeys(e){return this.assertOpen(),await this.adminFetch(S(ss,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.assertOpen(),await this.adminFetch(rs,"POST",e)}async disableAuthTwoFactor(e){this.assertOpen(),await this.adminFetch(is,"POST",e)}async listAuthOrganizations(e={}){return this.assertOpen(),await this.adminFetch(S(ns,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.assertOpen();const t=S(as,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthOrgInvitations(e){this.assertOpen();const t=S(os,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthSignUpInvitations(e={}){this.assertOpen();const t=S(us,{limit:e.limit,offset:e.offset});return await this.adminFetch(t,"GET")}async createAuthSignUpInvitation(e){return this.assertOpen(),await this.adminFetch(ls,"POST",e)}async revokeAuthSignUpInvitation(e){this.assertOpen(),await this.adminFetch(fs,"POST",e)}async removeAuthOrgMember(e){this.assertOpen(),await this.adminFetch(cs,"POST",e)}async cancelAuthOrgInvitation(e){this.assertOpen(),await this.adminFetch(ds,"POST",e)}async getAuthConfig(){return this.assertOpen(),await this.adminFetch(hs,"GET")}async createAuthOrganization(e){return this.assertOpen(),await this.adminFetch(ms,"POST",e)}async updateAuthOrganization(e){return this.assertOpen(),await this.adminFetch(ps,"POST",e)}async deleteAuthOrganization(e){this.assertOpen(),await this.adminFetch(ys,"POST",e)}async addAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(Ss,"POST",e)}async inviteAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(bs,"POST",e)}async setAuthOrgMemberRole(e){return this.assertOpen(),await this.adminFetch(gs,"POST",e)}async listAuthOrgTeams(e){this.assertOpen();const t=S(Ts,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(vs,"POST",e)}async updateAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(Cs,"POST",e)}async removeAuthOrgTeam(e){this.assertOpen(),await this.adminFetch(ks,"POST",e)}async listAuthOrgTeamMembers(e){this.assertOpen();const t=S(ws,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(t,"GET")}async addAuthOrgTeamMember(e){return this.assertOpen(),await this.adminFetch(Es,"POST",e)}async removeAuthOrgTeamMember(e){this.assertOpen(),await this.adminFetch(As,"POST",e)}async listAuthOrgRoles(e){this.assertOpen();const t=S(_s,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Is,"POST",e)}async updateAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Os,"POST",e)}async deleteAuthOrgRole(e){this.assertOpen(),await this.adminFetch(Rs,"POST",e)}async listAuthSessions(e={}){this.assertOpen();const t=S(Kt,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(t,"GET")}subscribe(e,t,s,r={}){this.assertOpen();const n=t??{},o=v.key(e.__lunoraRef,n,r.shardKey);let a=this.subscriptions.get(o);const c=j(s),d=j(r.onError),h=j(r.onCheckpoint);if(!a){this.nextSubId+=1;const m=`sub_${this.nextSubId.toString()}`,p=oe(n),f=this.takeHydratedCache(e.__lunoraRef,p,r.shardKey);a={acked:!1,args:n,argsKey:p,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:m,lastValue:f?.value,optimisticLayers:[],serverBase:f?.value,serverCursor:f?.serverCursor,shardKey:r.shardKey,wireArgs:k(n,`args for '${e.__lunoraRef}'`),...f?.serverEpoch===void 0?{}:{serverEpoch:f.serverEpoch}},this.subscriptions.add(a),f!==void 0&&this.cacheSeededQueries.set(o,f)}if(a.callbacks.add(c),d&&a.errorCallbacks.add(d),h&&a.checkpointCallbacks.add(h),a.lastValue!==void 0)try{c(a.lastValue)}catch{}this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(a);const u=a;return()=>{u.callbacks.delete(c),d&&u.errorCallbacks.delete(d),h&&u.checkpointCallbacks.delete(h),u.callbacks.size===0&&(this.sendOrQueueUnsubscribe(u.shardKey,u.id,"unsubscribe"),this.returnCacheSeed(v.keyOf(u)),this.subscriptions.remove(u),this.releaseIdleShard(u.shardKey))}}subscribeShape(e,t,s={}){if(this.assertOpen(),this.followsAnotherTab()){const{onError:o}=s;return o!==void 0&&queueMicrotask(()=>{o({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;const r=`shape_${this.nextShapeId.toString()}`,n={args:e.args,callbacks:new Set([t]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:r,name:e.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:e.args===void 0?void 0:k(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(r,n),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(r),this.sendOrQueueUnsubscribe(n.shardKey,r,"shape_unsubscribe"),this.releaseIdleShard(n.shardKey)}}stream(e,t,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new y("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;const r=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=s,o=t??{},{handle:a,iterable:c}=Ze({maxBuffer:s.maxBuffer,onCancel:()=>{this.cancelStream(r,n)}});this.ensureSocket(n);const d=this.getConnection(n),h={id:r,query:{args:k(o,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"},u={durable:s.durable===!0,generation:void 0,handle:a,lastSeq:0,message:h,shardKey:n};this.streams.set(r,u);const m=d?.wsState==="open"&&g(d,h);if(!m&&d===void 0)return this.forgetStream(r),a.fail(new y("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),c;if(!m){for(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=vr;){const f=d.pendingStreams.shift()?.id,b=f?this.streams.get(f):void 0;b&&(b.handle.fail(new y("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(f))}d.pendingStreams.push(h)}return c}httpStream(e,t,s={}){if(this.closed)throw new y("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");const r={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return Ke(e,t,{baseUrl:this.url,fetch:this.fetchImpl,headers:r,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const e of this.streams.values())e.handle.fail(new y("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(const e of this.connections.values())this.teardownConnection(e);for(const e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear();for(const e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.roomFlushes.clear(),this.roomIdentityResets.clear(),this.shapeSubscriptions.clear(),this.pokeAssembler.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new y("INTERNAL","LunoraClient is closed")}followsAnotherTab(){const e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;const t=e.leaderTabId;return t!==void 0&&t!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new y("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}shardInUse(e){const t=s=>l(s)===e;return this.subscriptions.all().some(s=>t(s.shardKey))||[...this.shapeSubscriptions.values()].some(s=>t(s.shardKey))||[...this.streams.values()].some(s=>t(s.shardKey))||this.whisperHandlers.has(e)||this.connectionContexts.has(e)||this.connectionContextHolders.has(e)||this.offlineFlushes.has(e)||this.offlineQueue.hasPending(s=>t(s.shardKey))}releaseIdleShard(e){const t=l(e),s=this.connections.get(t);this.closed||t===""||s===void 0||(clearTimeout(s.idleTimer),s.idleTimer=setTimeout(()=>{s.idleTimer=void 0,!(this.closed||this.connections.get(t)!==s||this.shardInUse(t))&&(s.wasEverConnected&&this.idleClosedShards.add(t),this.teardownConnection(s),this.connections.delete(t),this.emitConnectionStatus())},Tr))}forgetStream(e){const t=this.streams.get(e);this.streams.delete(e),t&&this.releaseIdleShard(t.shardKey)}teardownConnection(e){e.polling.stop();const t=l(e.shardKey);for(const[r,n]of this.streams)l(n.shardKey)===t&&(n.handle.fail(new y("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(r));e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.clearResubscribeQueue(e),this.clearConnectionTimers(e),clearTimeout(e.idleTimer),e.idleTimer=void 0,H(e);const{socket:s}=e;if(s){e.socket=void 0;try{s.close()}catch{}}e.wsState="closed"}createTabCoordinator(){const e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`,t={activeSubscriptions:()=>this.subscriptions.all(),broadcastStatus:(s,r)=>this.tabCoordinator?.broadcastConnectionStatus(s,r),closeConnections:()=>{for(const[s,r]of this.connections)this.teardownConnection(r),this.connections.delete(s)},computeStatus:()=>this.computeStatus(),emitConnectionStatus:()=>{this.emitConnectionStatus()},ensureSocket:s=>{this.ensureSocket(s)},flushOfflineQueues:()=>{this.flushAllOfflineQueues()},identityFingerprint:()=>this.identityFingerprint(),isLeader:()=>this.tabCoordinator?.isLeader()===!0,leader:this.leader,queueResubscribe:s=>{this.queueResubscribe(s)},queuedShardKeys:()=>this.queuedOfflineShardKeys,clientIdentifier:()=>this.clientId,dropCacheSeed:s=>{this.dropCacheSeed(s)},ackAndAdvanceCursor:(s,r,n)=>{this.ackAndAdvanceCursor(s,r,n)},subscription:s=>this.subscriptions.get(s)};return new De({channelName:e,onBecomeLeader:()=>{jr(t)},onStopBeingLeader:()=>{$r(t)},onConnectionStatus:(s,r)=>{Gr(t,s,r)},onSubscriptionData:(s,r,n,o,a)=>{zr(t,s,r,n,o,a)},onLeaderClaimAnswered:()=>{Vr(t)},onSubscriptionError:(s,r,n)=>{Jr(t,s,r,n)},onSubscriptionSettled:(s,r,n,o,a,c)=>{Yr(t,s,r,n,o,a,c)}})}async sendBatch(e,t){if(this.assertOpen(),!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];const s=await this.fetchImpl(E(this.url,G),{body:JSON.stringify({calls:e.map((a,c)=>({args:k(a.args??{},`args for batch call '${a.fn.__lunoraRef}'`),functionPath:a.fn.__lunoraRef,id:c,shardKey:a.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:t}),r=s.headers.get("x-d1-bookmark");r&&this.bookmark.set(r);let n;try{n=await s.json()}catch{throw new y("INTERNAL",`LunoraClient: batch response was not JSON (status ${s.status.toString()})`)}const o=N(n);if(!s.ok||o!==void 0&&!n.results)throw o!==void 0?Ue(o):new y("INTERNAL",`LunoraClient: batch request failed (status ${s.status.toString()})`);for(const a of n.results??[]){const c=a.body?.commitCursor;typeof a.id=="number"&&typeof c=="number"&&this.recordShardCursor(e[a.id]?.shardKey,c)}return fr(n.results??[],e.length)}async runMutation(e,t,s){this.assertOpen();const r=t,n=s.mutationId??he(),o=this.takeReplayCredential(s.replayCredential),a=s.replayBaseline===void 0?this.baselineCursorFor(s.shardKey):s.replayBaseline??void 0,{confirms:c,rollbacks:d}=this.applyOptimisticUpdates(e.__lunoraRef,r,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,t,s.shardKey,d,c);const h=this.offlineFlushes.get(l(s.shardKey));h!==void 0&&await h;const{hasSocket:u,idleClosed:m,polling:p,wasEverConnected:f,wsState:b}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:T}=this.offlineQueue,U=f||T,B=this.WebSocketImpl!==void 0&&U,Q=p||m,Ie=b==="connecting"&&U&&!Q,Oe=b!=="open"&&!u&&B&&!Q,Re=B&&s.replayBaseline===void 0&&this.hasPendingWriteAhead(s.shardKey),ae=async()=>this.enqueueOfflineMutation(e,r,s.shardKey,a,n,d,c,s.precondition,s.mutationId,o?.stamp);if(Oe||Ie||Re)return ae();let K;try{const R=await this.rpc(e.__lunoraRef,r,s.shardKey,{baselineSeq:a,captureBookmark:!0,...o?.flags,mutationId:n,onCommitCursor:q=>{K=q}});for(const q of c)q(K);return{committed:!0,value:R}}catch(R){if(Q&&B&&R instanceof TypeError&&pe(r))return ae();throw this.settleFailedDirectWrite(R,K,c,d,o?.flags.authToken),R}}settleFailedDirectWrite(e,t,s,r,n){if(this.noteIdentityMismatch(e),n!==void 0&&this.noteReplayAuthRefusal(e,n),x(e)){for(const o of s)o(t);return}P(r)}async enqueueOfflineMutation(e,t,s,r,n,o,a,c,d,h){const u=h===void 0?this.identityFingerprint():h;if(this.outbox){this.outboxMutationCounter+=1;const p=this.outboxMutationCounter;try{await this.outbox.enqueue({args:t,baselineSeq:r,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:d??`${this.clientId}:${String(p)}`,identity:u,mutationId:p,...o.length>0&&{onRejected:()=>{P(o)}},shardKey:s})}catch(f){throw P(o),f instanceof Error?f:new Error(String(f))}for(const f of a)f(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((p,f)=>{const b={args:t,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:r,id:n,clientId:this.clientId,identity:u,precondition:c,onCommit:T=>{for(const U of a)U(T)},reject:T=>{this.queuedIdentities.delete(n),x(T)||P(o),f(T instanceof Error?T:new Error(String(T))),this.releaseIdleShard(s)},resolve:p,shardKey:s};this.offlineQueue.enqueue(b),this.queuedOfflineShardKeys.add(s),this.ensureSocket(s),b.id!==void 0&&this.queuedIdentities.set(b.id,u)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;const t=l(e);return this.offlineQueue.hasPending(s=>l(s.shardKey)===t)}async hydratePersistedQueue(){try{const e=await this.offlineQueue.hydrate();for(const t of e)this.queuedOfflineShardKeys.add(t),this.ensureSocket(t)}catch{}}hydrateAsOutboxLeader(){const e=()=>{this.hydratePersistedQueue().catch(()=>{})},t=globalThis.navigator?.locks;if(!t){e();return}t.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{const e=await this.queryCache.load(),t=new Map;for(const s of this.subscriptions.all())t.set(_(s.fn.__lunoraRef,s.argsKey,s.shardKey),s);for(const{key:s,...r}of e){if(Ve(this.persistenceVersion,r.version)){this.queryCache.remove(s).catch(()=>{});continue}const n=t.get(s);if(n&&this.cachedQueryMatchesIdentity(r)){this.seedSubscriptionFromCache(n,r);continue}this.hydratedQueryCache.set(s,r)}}catch{}}seedSubscriptionFromCache(e,t){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(t)||(e.serverBase=t.value,e.serverCursor=t.serverCursor,t.serverEpoch!==void 0&&(e.serverEpoch=t.serverEpoch),this.cacheSeededQueries.set(_(e.fn.__lunoraRef,e.argsKey,e.shardKey),t),O(e,t.value))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}returnCacheSeed(e){const t=this.cacheSeededQueries.get(e);t!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,t))}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(const[e,t]of this.cacheSeededQueries){const s=this.subscriptions.get(e);s!==void 0&&(s.serverBase=void 0,s.serverCursor=void 0,s.serverEpoch=void 0,O(s,void 0)),this.hydratedQueryCache.set(e,t)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,t,s){const r=_(e,t,s),n=this.hydratedQueryCache.get(r);if(!(n===void 0||!this.cachedQueryMatchesIdentity(n)))return this.hydratedQueryCache.delete(r),n}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(const e of this.subscriptions.all()){const t=_(e.fn.__lunoraRef,e.argsKey,e.shardKey),s=this.hydratedQueryCache.get(t);s!==void 0&&this.cachedQueryMatchesIdentity(s)&&(this.hydratedQueryCache.delete(t),this.seedSubscriptionFromCache(e,s))}}persistQueryValue(e){const t=e.serverBase;if(!this.queryCache||t===void 0)return;const s=_(e.fn.__lunoraRef,e.argsKey,e.shardKey),r=this.getConnection(e.shardKey)?.identity,n=r===void 0?this.identityFingerprint():r;n===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(s,{identity:n,serverCursor:e.serverCursor,ts:Date.now(),value:t,...n===this.identityFingerprint()&&!this.subjectAwaitingReconfirm()?this.credentialStamp():{},...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},br))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;const{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}const t=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(t.map(async([s,r])=>e.put(s,r)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leader.status??"idle";const e=[...this.connections.values()];return e.length===0?"idle":e.some(t=>t.wsState==="open")?"connected":e.some(t=>t.polling.isPolling())?"polling":e.some(t=>t.wsState==="connecting")?"connecting":"offline"}baselineCursorFor(e){const t=l(e);let s;for(const r of this.subscriptions.all())l(r.shardKey)!==t||r.serverCursor===void 0||(s=s===void 0?r.serverCursor:Math.max(s,r.serverCursor));return s}async pollSubscriptions(e){const t=l(e),s=[];for(const a of this.subscriptions.all())l(a.shardKey)===t&&(pe(a.args)?s.push(a):A(a.errorCallbacks,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"}));if(s.length===0)return this.probeOrigin();const r=$e(),n=this.identityFingerprint();let o;try{o=await Se(async a=>this.sendBatch(s.map(c=>({args:c.args,fn:c.fn,shardKey:c.shardKey})),a))}catch(a){return!(a instanceof TypeError)}if(this.identityFingerprint()!==n)return!0;for(const[a,c]of s.entries()){const d=o[a];if(d!==void 0){if(!d.ok){A(c.errorCallbacks,{code:d.error.code,message:d.error.message});continue}this.handleDataMessage({data:M(d.value),id:c.id,type:"data"},r)}}return!0}async probeOrigin(){const{fetchImpl:e}=this;if(!e)return!1;try{return await Se(async t=>e(E(this.url,G),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:t})),!0}catch{return!1}}emitConnectionStatus(){const e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,t,s){this.mutationSettledListeners.emit({args:e.args,code:s===void 0?void 0:s.code,error:s,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:t})}applyOptimisticUpdates(e,t,s,r){const n=[],o=[];if(!r)return{confirms:n,rollbacks:o};const a=v.key(e,t,s),c=this.subscriptions.get(a);if(c){const d=qe(c,r);d&&(n.push(d.confirm),o.push(d.rollback))}return{confirms:n,rollbacks:o}}applyOptimisticUpdate(e,t,s,r,n){const{confirms:o,rollbacks:a,store:c}=We(this.subscriptions,s);try{e(c,t)}catch{P(a);return}r.push(...a),n.push(...o)}getConnection(e){return this.connections.get(l(e))}sendOrQueueUnsubscribe(e,t,s){const r=this.getConnection(e);r&&!g(r,{id:t,type:s})&&r.pendingUnsubscribes.push({id:t,type:s})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let r="idle";return this.leader.status==="connected"?r="open":this.leader.status==="connecting"&&(r="connecting"),{hasSocket:!1,idleClosed:!1,polling:this.leader.status==="polling",wasEverConnected:this.leader.wasEverConnected,wsState:r}}const t=this.getConnection(e),s=t===void 0&&this.idleClosedShards.has(l(e));return{hasSocket:t?.socket!==void 0,idleClosed:s,polling:t?.polling.isPolling()??!1,wasEverConnected:t?.wasEverConnected??s,wsState:t?.wsState??"idle"}}getOrCreateConnection(e){const t=l(e);let s=this.connections.get(t);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:Or({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:()=>{this.flushOfflineQueue(e).catch(()=>{})},onStateChange:()=>{this.emitConnectionStatus()},poll:async()=>this.pollSubscriptions(e)}),reconnect:ue(this.reconnectOptions),reconnectTimer:void 0,resubscribePending:new Map,resubscribeQueue:[],shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:this.idleClosedShards.delete(t),wsState:"idle"},this.connections.set(t,s)),s}wsUrlFor(e,t){const s=[];if(e!==void 0&&s.push(`shard=${encodeURIComponent(e)}`),t!==void 0&&s.push(`token=${encodeURIComponent(t)}`),s.length===0)return this.wsUrl;const r=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${r}${s.join("&")}`}rpcRequestHeaders(e,t){const s={"content-type":"application/json"};e.expectSubject!==void 0&&(s[rt]=it(e.expectSubject));const r=this.shardCursors.get(this.cursorKeyFor(t));r!==void 0&&(s["x-lunora-min-seq"]=r.toString());const n=e.authToken===void 0?this.authToken:e.authToken;if(n&&(s.authorization=`Bearer ${n}`),e.mutationId&&(s["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(s["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(s["x-lunora-client-seq"]=e.clientSeq.toString()),e.baselineSeq!==void 0&&(s["x-lunora-base-seq"]=e.baselineSeq.toString()),e.attachBookmark){const o=this.bookmark.get();o&&(s["x-d1-bookmark"]=o)}return s}async rpc(e,t,s,r={}){if(!this.fetchImpl)throw new L("LunoraClient: no `fetch` implementation available");const n=this.rpcRequestHeaders(r,s),o=r.authToken===void 0?this.authToken:r.authToken,a=await this.fetchImpl(E(this.url,ft),{body:JSON.stringify({args:k(t,`args for '${e}'`),functionPath:e,shardKey:s}),headers:n,method:"POST"});if(r.captureBookmark){const u=a.headers.get("x-d1-bookmark");u&&this.bookmark.set(u)}let c;try{c=await a.json()}catch{throw F(a.status,a.statusText,a.headers.get("retry-after"))}const d=c;if(typeof d!="object"||d===null||Array.isArray(d))throw F(a.status,a.statusText,a.headers.get("retry-after"));const h=N(c);if(h!==void 0)throw ce(h,a.headers.get("retry-after"));if(!a.ok)throw F(a.status,a.statusText,a.headers.get("retry-after"));r.onMutationAck?.(c.lastMutationId),r.onCommitCursor?.(c.commitCursor),this.noteCredentialAccepted(o),this.learnDefaultShardKey(a,s),this.recordShardCursor(s,c.commitCursor);try{return w(c.result)}catch(u){throw Ee(u)}}async adminFetch(e,t,s,r){if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");const n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);const o=s instanceof ArrayBuffer||s instanceof Blob;let a;s===void 0?a=void 0:o?(a=s,r!==void 0&&(n["content-type"]=r)):(a=JSON.stringify(s),n["content-type"]="application/json");const c=await this.fetchImpl(E(this.url,e),{body:a,headers:n,method:t});let d;try{d=await c.json()}catch{const u=c.statusText?` ${c.statusText}`:"";throw new y("INTERNAL",`LunoraClient: response was not JSON (status ${c.status.toString()}${u})`)}const h=N(d);if(h!==void 0){const u=new Error(h.message??"admin request failed");throw u.code=h.code,u}if(!c.ok){const u=c.statusText?` ${c.statusText}`:"";throw new y("INTERNAL",`LunoraClient: admin request failed (status ${c.status.toString()}${u})`)}return d}effectiveConnectionContext(e){const t=this.connectionContextHolders.get(e);return t&&t.length>0?t[t.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){const t=this.connections.get(e);t?.wsState==="open"&&this.sendConnectEnvelope(t)}sendConnectEnvelope(e){const t=this.effectiveConnectionContext(l(e.shardKey));g(e,{caps:Zr,clientId:this.clientId,id:"connect",type:"connect",...t===void 0?{}:{context:t}})}resendShapeSubscriptions(e){for(const t of this.shapeSubscriptions.values())l(t.shardKey)===l(e)&&this.sendShapeSubscribeIfOpen(t)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const t=this.getOrCreateConnection(e);if(!(t.wsState==="open"||t.wsState==="connecting")){if(t.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(t,e,this.wsToken).catch(()=>{});return}this.openSocket(t,e,this.wsToken)}}async openSocketWithProvidedToken(e,t,s){const r=this.wsTokenGeneration;let n;try{n=await s()}catch{this.handleDisconnect(e);return}if(!(this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0)){if(r!==this.wsTokenGeneration){typeof this.wsToken=="function"?await this.openSocketWithProvidedToken(e,t,this.wsToken):this.openSocket(e,t,this.wsToken);return}this.openSocket(e,t,n)}}openSocket(e,t,s){this.WebSocketImpl!==void 0&&(e.identity=this.identityFingerprint(),s===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.retired=!1,ye(e,this.wsUrlFor(t,s),this.managedSocketOptions,{onClose:r=>{r?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},onMessage:r=>{e.retired!==!0&&this.handleServerMessage(r.data,t)},onOpen:()=>{e.wsState="open",e.wasEverConnected=!0,e.identityConfirmed=!1,e.roomsRejoined=!1,e.polling.noteOpen(),clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},gr),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(t),this.clearResubscribeQueue(e);for(const n of this.subscriptions.all())l(n.shardKey)===l(t)&&this.queueResubscribe(n);if(this.resendShapeSubscriptions(t),e.pendingUnsubscribes.length>0){const n=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(const{id:o,type:a}of n)g(e,{id:o,type:a});this.releaseIdleShard(t)}Er(e);const r=this.whisperHandlers.get(l(t));if(r)for(const n of r.keys())g(e,{topic:n,type:"whisper_subscribe"});e.roomsRejoined=!0,this.releaseRoomSends(t),this.flushOfflineQueue(t).catch(()=>{})}}))}cancelStream(e,t){const s=this.getConnection(t);s&&(s.pendingStreams=s.pendingStreams?.filter(r=>r.id!==e),g(s,{id:e,type:"unsubscribe"})),this.forgetStream(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;e.wsState==="connecting"&&e.polling.noteFailedOpen(),H(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e);const t=new Set((e.pendingStreams??[]).map(r=>r.id));for(const[r,n]of this.streams)if(!(l(n.shardKey)!==l(e.shardKey)||t.has(r))){if(n.durable){const o={...n.message,...n.generation===void 0?{}:{generation:n.generation},sinceChunk:n.lastSeq};n.message=o,e.pendingStreams=[...(e.pendingStreams??[]).filter(a=>a.id!==r),o];continue}n.handle.fail(new y("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.forgetStream(r)}if(this.WebSocketImpl===void 0)return;const s=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},s)}markShardPendingAck(e){const t=l(e);for(const s of this.subscriptions.all())l(s.shardKey)===t&&(s.acked=!1)}queueResubscribe(e){const t=this.getConnection(e.shardKey);t&&(t.resubscribeQueue.push(e),this.drainResubscribeQueue(t))}drainResubscribeQueue(e){for(;e.resubscribePending.size<Cr;){const t=e.resubscribeQueue.shift();if(!t)return;this.subscriptions.getById(t.id)&&this.sendSubscribeIfOpen(t)&&e.resubscribePending.set(t.id,setTimeout(()=>{this.releaseResubscribeSlot(e,t.id)},kr))}}releaseResubscribeSlot(e,t){const s=e.resubscribePending.get(t);s!==void 0&&(clearTimeout(s),e.resubscribePending.delete(t),this.drainResubscribeQueue(e))}clearResubscribeQueue(e){for(const t of e.resubscribePending.values())clearTimeout(t);e.resubscribePending.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);if(t?.wsState!=="open"||e.acked)return!1;const s=e.serverCursor!==void 0&&e.serverBase!==void 0;return g(t,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...s?{sinceSeq:e.serverCursor}:{},...s&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);t?.wsState==="open"&&g(t,{id:e.id,shape:{name:e.name,...e.wireArgs===void 0?{}:{args:e.wireArgs}},type:"shape_subscribe",...e.serverCursor===void 0?{}:{sinceCheckpoint:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,t){const s=_r(e);if(s===void 0)return;let r;try{r=JSON.parse(s)}catch{return}if(r.type!=="error"&&this.getConnection(t)?.reconnect.reset(),typeof r.id=="string"){const n=this.getConnection(t);n&&this.releaseResubscribeSlot(n,r.id)}switch(r.type){case"ack":{const n=this.subscriptions.getById(r.id);n&&(n.acked=!0);return}case"chunk":{const{data:n,generation:o,id:a,seq:c}=r,d=this.streams.get(a);d&&typeof c=="number"&&(d.lastSeq=c,typeof o=="number"&&(d.generation=o),d.durable=!0),d?.handle.push(w(n));return}case"complete":{this.handleCompleteMessage(r.id);return}case"data":case"delta":{this.handleDataMessage(r);return}case"error":{this.handleErrorMessage(r);break}case"identity":{this.handleIdentityFrame(r,t),this.confirmShardIdentity(t);break}case"pokeEnd":{this.handlePokeEnd(r,t);break}case"pokePart":{this.pokeAssembler.part(t,r);break}case"pokeStart":{this.pokeAssembler.start(t,r);break}case"resume":{this.handleResumeMessage(r);break}case"settled":{this.handleSettledMessage(r);break}case"whisper":{this.dispatchWhisper(r,t);break}}}handleErrorMessage(e){const t=e.error?.code;if(t==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}if(t==="STREAM_ID_IN_USE")return;const{id:s}=e,r=s===void 0?void 0:this.streams.get(s);if(r&&s!==void 0){r.handle.fail(Ne(e)),this.forgetStream(s);return}const n=s===void 0?void 0:this.subscriptions.getById(s);if(n){const a=de(e),c=this.identityFingerprint(),d=v.keyOf(n);A(n.errorCallbacks,a),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(d,a,c);return}const o=s===void 0?void 0:this.shapeSubscriptions.get(s);o&&A(o.errorCallbacks,de(e))}handlePokeEnd(e,t){const s=this.pokeAssembler.end(t,e.pokeId);if(s){qr(this.shapeSubscriptions,s);for(const r of s.parts.keys()){const n=this.shapeSubscriptions.get(r);n&&!s.undecodable.has(r)&&this.applyPokePart(n,s,e)}}}applyPokePart(e,t,s){const r=Kr(e,t,s);if(be(e),r==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}handleDataMessage(e,t){const{id:s}=e,r=s?this.subscriptions.getById(s):void 0;if(!r)return;let n;try{n=Pe(e,r.serverBase)}catch(o){A(r.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription — ${o instanceof Error?o.message:String(o)}`});return}if(n===Fe){this.resnapshotSubscription(r);return}if(this.dropCacheSeed(v.keyOf(r)),Ae(r,n,{cursor:e.cursor,epoch:e.epoch}),e.lastMutationId!==void 0&&(ee(r,e.lastMutationId),te(r,!0)),this.persistQueryValue(r),X(r,r.serverCursor),t!==void 0&&je(r,t),O(r,n),this.tabCoordinator?.isLeader()){const o=v.keyOf(r);this.tabCoordinator.broadcastSubscriptionData(o,n,r.serverCursor,r.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){const t=this.subscriptions.getById(e.id);t&&this.ackAndAdvanceCursor(t,e.cursor,e.epoch)}handleSettledMessage(e){const t=this.subscriptions.getById(e.id);if(t&&(this.ackAndAdvanceCursor(t,e.cursor,e.epoch),e.lastMutationId!==void 0&&ee(t,e.lastMutationId),te(t),this.tabCoordinator?.isLeader())){const s=v.keyOf(t);this.tabCoordinator.broadcastSubscriptionSettled(s,t.serverCursor,t.serverEpoch,t.lastMutationId,this.clientId,this.identityFingerprint())}}ackAndAdvanceCursor(e,t,s){e.acked=!0,(t!==void 0&&t!==e.serverCursor||s!==void 0&&s!==e.serverEpoch)&&(t!==void 0&&(e.serverCursor=t),s!==void 0&&(e.serverEpoch=s),this.persistQueryValue(e),X(e,e.serverCursor)&&O(e,e.serverBase))}dispatchWhisper(e,t){const s=this.whisperHandlers.get(l(t))?.get(e.topic);if(!s)return;const r=w(e.data);for(const n of s)try{n(r,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){const t=this.streams.get(e);if(t){t.handle.complete(),this.forgetStream(e);return}const s=this.subscriptions.getById(e);s&&(s.acked=!1,A(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(t=>{ze(this.onPersistenceError,"remove",t,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let t=2166136261,s=5381;for(let r=0;r<e.length;r+=1){const n=e.charCodeAt(r);t^=n,t=Math.imul(t,16777619),s=Math.imul(s,33)+n}return`${e.length.toString(36)}:${(t>>>0).toString(36)}:${(s>>>0).toString(36)}`}credentialStamp(){const e=this.authToken;return e===null?{}:{credential:this.hashToken(e)}}cachedQueryMatchesIdentity(e){return this.identityFingerprint()===null&&this.identityUnresolved()?!1:!this.subjectAwaitingReconfirm()&&e.identity===this.identityFingerprint()||this.isSameCredentialUnderTokenHash(e.identity)?!0:e.credential!==void 0&&e.credential===this.credentialStamp().credential}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;const t=this.authToken;return t===null?!1:this.hashToken(t)===e}releaseSessionProbe(){this.sessionProbesInFlight-=1,!(this.identityUnresolved()||this.identityFingerprint()!==null)&&!this.closed&&this.offlineQueue.size>0&&z(this.computeStatus())&&this.flushAllOfflineQueues()}identityUnresolved(){return this.sessionProbesInFlight>0?!0:this.identityResolutionExpected&&!this.identitySettled}adoptResolvedSubject(e,t,s){if(!(this.closed||this.authToken!==e||s!==this.sessionProbeGeneration)){if(e===null){this.adoptCookieSubject(t?.id??null,s);return}t!==null&&this.setAuthToken(e,t.id)}}adoptCookieSubject(e,t){return this.closed||this.authToken!==null||t<this.identityAnsweredAt?!1:(this.identityAnsweredAt=t,this.identitySettled=!0,this.setAuthToken(null,e),!0)}sendEncodedWhisper(e,t,s){this.ensureSocket(s.shardKey);const r=this.getConnection(s.shardKey),n=r!==void 0&&g(r,{data:t,topic:e,type:"whisper"});return this.releaseIdleShard(s.shardKey),n}roomSendsAdmitted(e){const t=this.getConnection(e);return t?.wsState==="open"&&t.retired!==!0&&t.identityConfirmed===!0&&t.roomsRejoined===!0}releaseRoomSends(e){if(this.roomSendsAdmitted(e))for(const t of this.roomFlushes.get(l(e))??[])t()}confirmShardIdentity(e){const t=this.getConnection(e);t!==void 0&&(t.identityConfirmed=!0),this.releaseRoomSends(e)}handleIdentityFrame(e,t){const s=this.getConnection(t)?.identityQuestion,{subject:r}=e;s===void 0||r!==null&&typeof r!="string"||this.adoptCookieSubject(r,s)||!this.closed&&this.authToken===null&&(r===null?null:`subj:${r}`)!==this.identityFingerprint()&&this.evictPreviousIdentitySession()}applySubject(e,t){if(t!==void 0){this.authSubject=t,this.subjectToken=e;return}(e===null&&this.authSubject!==null||e!==null&&this.authSubject===null)&&(this.authSubject=void 0,this.subjectToken=null)}isKnownNobody(){return this.authSubject===null&&this.authToken===null}subjectAwaitingReconfirm(){return this.authSubject!==void 0&&this.authSubject!==null&&this.subjectToken!==this.authToken}stampOf(e){const t=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return t===void 0?e.identity:t}warnRefreshWithoutSubject(e,t){e===null||t===null||this.authSubject!==void 0||this.authRefusalNotifiedFor!==this.hashToken(e)||console.warn("[lunora] setAuthToken replaced a token that was just refused for a queued write, with no subject: without one a refresh reads as a user switch, so the held writes were discarded (OFFLINE_IDENTITY_CHANGED). Pass the user id, e.g. setAuthToken(token, user.id), to keep them across a refresh.")}rejectQueuedForIdentityChange(e){const t=this.offlineQueue.drain(),s=[];for(const r of t){if(this.identityVerdict(this.stampOf(r))!=="mismatch"){s.push(r);continue}this.queuedIdentities.delete(r.id??""),this.unpersist(r.id);const n=new Error("offline mutation discarded: auth identity changed before replay");n.code="OFFLINE_IDENTITY_CHANGED",r.reject(n),this.emitItemSettled(r,"rejected",n)}this.offlineQueue.requeue(s),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,t){for(const s of this.connections.values())s.identity===e&&(s.identity=t)}restampQueuedIdentity(e,t){for(const[s,r]of this.queuedIdentities)r===e&&this.queuedIdentities.set(s,t);this.offlineQueue.restampIdentity(e,t)}restampWatermarks(e,t){const s=e??"",r=this.clientWatermarks.get(s);if(r===void 0)return;this.clientWatermarks.delete(s);const n=t??"",o=this.clientWatermarks.get(n);if(o===void 0)this.clientWatermarks.set(n,r);else for(const[a,c]of r)o.set(a,c)}clearQueryCacheForIdentityChange(){this.revokeCacheSeededValues(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}evictPreviousIdentitySession(){this.resetRoomSends(),this.revokeCacheSeededValues();for(const e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.acked=!1,O(e,void 0);for(const e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,be(e);this.bounceShardSockets(),this.retiredIdentities+=1,this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;const e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}resetRoomSends(){for(const e of this.roomIdentityResets)e()}bounceShardSockets(){for(const e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}}flushAllOfflineQueues(){for(const e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){const t=l(e),s=this.offlineFlushes.get(t);if(s===void 0&&this.offlineQueue.size===0)return;const r=(async()=>{await(s??Promise.resolve());const{authToken:n}=this;try{await this.drainOfflineQueue(e,n)}catch{}!this.closed&&this.authToken!==n&&this.offlineQueue.size>0&&z(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(t,r),await r,this.offlineFlushes.get(t)===r&&(this.offlineFlushes.delete(t),this.releaseIdleShard(e))}async drainOfflineQueue(e,t){const s=this.offlineQueue.drainConflict();for(const h of s){this.unpersist(h.id),this.queuedIdentities.delete(h.id??"");const u=new Error("offline mutation skipped: precondition failed before replay");u.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(h,"rejected",u)}const r=l(e),n=this.offlineQueue.drain(h=>l(h.shardKey)===r);if(n.length===0)return;const o=[],a=[];for(const h of n){const u=this.replayGateVerdict(h);u==="send"?o.push(h):u==="hold"&&a.push(h)}if(this.offlineQueue.requeue(a),a.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),o.length===0){this.scheduleRateLimitedRetry(e);return}const c=this.encodableOrSettleTerminal(o);if(c.length===0){this.scheduleRateLimitedRetry(e);return}if(c.length===1){await this.replaySequential(c,e,t),this.scheduleRateLimitedRetry(e);return}const d=[];for(let h=0;h<c.length;h+=$){const u=c.slice(h,h+$),m=await this.replayBatched(u,e,t);if(d.push(...m.requeue),m.stop){d.push(...c.slice(h+$));break}}d.length>0&&this.offlineQueue.requeue(d),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){const t=l(e),s=this.replayRetryState.get(t),r=(s?.attempts??0)+1;this.replayRetryState.set(t,{attempts:r,delayMs:Math.max(s?.delayMs??0,Z(r))})}noteReplayRetryDelay(e,t,s){const r=l(e),n=this.replayRetryState.get(r),o=(n?.attempts??0)+1,a=Mr(t,o)??(s===null&&W(t)?Z(o):void 0);this.replayRetryState.set(r,{attempts:o,delayMs:a===void 0?n?.delayMs:Math.max(n?.delayMs??0,a)})}scheduleRateLimitedRetry(e){const t=l(e),s=this.replayRetryState.get(t),r=s?.delayMs;if(s===void 0||r===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(t);return}s.delayMs=void 0;const n=this.replayRetryTimers.get(t);n!==void 0&&clearTimeout(n),this.replayRetryTimers.set(t,setTimeout(()=>{this.replayRetryTimers.delete(t),this.flushOfflineQueue(e).catch(()=>{})},r))}encodableOrSettleTerminal(e){const t=[];for(const s of e)try{k(s.args,`args for '${s.functionPath}'`),t.push(s)}catch(r){this.settleReplayTerminal(s,r instanceof Error?r:new Error(String(r)))}return t}identityVerdict(e){if(this.subjectAwaitingReconfirm())return"unknown";const t=this.identityFingerprint();return t===null&&this.identityUnresolved()?"unknown":e===t||e!==void 0&&this.isSameCredentialUnderTokenHash(e)?"match":t===null?"unknown":"mismatch"}replayGateVerdict(e){const t=this.stampOf(e);if(t===void 0)return this.queuedIdentities.delete(e.id??""),"send";const s=this.identityVerdict(t);if(s==="unknown")return"hold";if(this.queuedIdentities.delete(e.id??""),s==="match")return"send";this.unpersist(e.id);const r=new Error("offline mutation skipped: auth identity changed before replay");return r.code="OFFLINE_IDENTITY_CHANGED",e.reject(r),this.emitItemSettled(e,"rejected",r),"reject"}settleReplaySuccess(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.resolve(t),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,t){const s=e.headers.get("x-lunora-shard-key");if(s===null||t!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;const r=this.shardCursors.get("");r!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,r)),this.shardCursors.delete(""))}recordShardCursor(e,t){if(typeof t!="number")return;const s=this.cursorKeyFor(e);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,t))}shouldRequeueReplayFailure(e,t){return this.noteIdentityMismatch(e)?!0:this.noteReplayAuthRefusal(e,t)||Pr(e)}noteReplayAuthRefusal(e,t){if(!W(e))return!1;const s=this.hashToken(t??"");return t===this.authToken&&this.authRefusalNotifiedFor!==s&&(this.authRefusalNotifiedFor=s,this.notifyTokenExpired()),!0}noteCredentialAccepted(e){this.authRefusalNotifiedFor!==void 0&&this.authRefusalNotifiedFor===this.hashToken(e??"")&&(this.authRefusalNotifiedFor=void 0)}takeReplayCredential(e){if(e===void 0)return;const t=this.replayCredentials.get(e);if(t===void 0)throw new TypeError("LunoraClient: `replayCredential` must come from this client's `replayIdentityVerdict`, and is single use");return this.replayCredentials.delete(e),{flags:{authToken:t.authToken,...V(t.stamp,t.authToken)},stamp:t.stamp}}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;const t=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===t&&(this.warnedIdentityDisagreement=!0,console.warn('[lunora] a replayed write was refused with IDENTITY_MISMATCH, but `/get-session` still names the same user. The worker\'s `resolveIdentity` must return the same `userId` as the better-auth `user.id`, and RPC requests must carry the session cookie (`credentials: "include"` on a cross-origin fetch).'))}).catch(()=>{}),!0}settleReplayUndecodable(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.reject(t),this.emitItemSettled(e,"committed",t)}settleReplayTerminal(e,t){this.unpersist(e.id),e.reject(t),this.emitItemSettled(e,"rejected",t)}async replaySequential(e,t,s){for(let r=0;r<e.length;r+=1){const n=e[r];if(!n)continue;let o;try{const a=await this.rpc(n.functionPath,n.args,n.shardKey,{authToken:s,baselineSeq:n.baselineSeq,captureBookmark:!0,clientId:n.clientId??this.clientId,...V(n.identity,s),mutationId:n.id,onCommitCursor:c=>{o=c}});this.settleReplaySuccess(n,a,o)}catch(a){if(x(a)){this.settleReplayUndecodable(n,a,o);continue}if(!this.shouldRequeueReplayFailure(a,s)){this.settleReplayTerminal(n,a);continue}this.noteReplayRetryDelay(t,a,s),this.offlineQueue.requeue(e.slice(r));return}}}async replayBatched(e,t,s){if(!this.fetchImpl)return{requeue:e,stop:!0};const r=JSON.stringify({calls:e.map((d,h)=>({args:k(d.args,`args for '${d.functionPath}'`),baselineSeq:d.baselineSeq,functionPath:d.functionPath,id:h,clientId:d.clientId??this.clientId,mutationId:d.id,shardKey:d.shardKey}))});if(e.length>1&&Nr(r)>Ur)return await this.replayBatchedHalves(e,t,s);let n;try{n=await this.fetchImpl(E(this.url,G),{body:r,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:s,...V(e.find(d=>d.identity!==void 0)?.identity,s)}),method:"POST"})}catch{return{requeue:e,stop:!0}}const o=n.headers.get("x-d1-bookmark");if(o&&this.bookmark.set(o),n.status===413&&e.length>1)return await this.replayBatchedHalves(e,t,s);let a;const c=n.headers.get("retry-after");try{a=await n.json()}catch{return this.settleWholeBatchError(e,F(n.status,n.statusText,c),t,s)}if(!a.results){const d=N(a),h=d===void 0?F(n.status,n.statusText,c):ce(d,c);return this.settleWholeBatchError(e,h,t,s)}return{requeue:this.settleReplayBatchSlots(e,a.results,t,s),stop:!1}}settleWholeBatchError(e,t,s,r){if(t instanceof L||t.code!==void 0&&this.shouldRequeueReplayFailure(t,r))return this.noteReplayRetryDelay(s,t,r),{requeue:e,stop:!0};for(const n of e)this.settleReplayTerminal(n,t);return{requeue:[],stop:!1}}async replayBatchedHalves(e,t,s){const r=Math.ceil(e.length/2),n=await this.replayBatched(e.slice(0,r),t,s);if(n.stop)return{requeue:[...n.requeue,...e.slice(r)],stop:!0};const o=await this.replayBatched(e.slice(r),t,s);return{requeue:[...n.requeue,...o.requeue],stop:o.stop}}settleReplayBatchSlots(e,t,s,r){const n=xr(t),o=[];let a=!1,c=!1;for(const[d,h]of e.entries()){const u=Dr(n.get(d));switch(u.kind){case"committed":{a=!0,this.settleReplaySuccess(h,u.value,u.commitCursor);break}case"errored":{c||=W(u.error),this.shouldRequeueReplayFailure(u.error,r)?(this.noteReplayRetryDelay(s,u.error,r),o.push(h)):this.settleReplayTerminal(h,u.error);break}case"unanswered":{o.push(h);break}default:a=!0,this.settleReplayUndecodable(h,u.error,u.commitCursor)}}return a&&!c&&this.noteCredentialAccepted(r),o}}export{_e as LunoraClient};