@lunora/client 1.0.0-alpha.303 → 1.0.0-alpha.304

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 { ae as ShardTrafficResult, t as DeploymentPauseStatus, a2 as ScheduleRecord, a8 as SchedulerStatus, a6 as ScheduledJobView, a4 as ScheduledHistoryPage, s as CronRunsResult, as as WorkflowInstanceStatus, ar as WorkflowInstancePage, aq as WorkflowInstanceDetail, ap as WorkflowInstanceCreated, ao as WorkflowInstanceAction, u as FunctionDescriptor, af as StorageListPage, x as GlobalTableInfo, w as GlobalFilterClause, y as GlobalTablePage, G as GlobalFacetResult, L as LunoraClient } from "../packem_shared/lunora-client.d-BxU8-4s5.mjs";
1
+ import { ae as ShardTrafficResult, t as DeploymentPauseStatus, a2 as ScheduleRecord, a8 as SchedulerStatus, a6 as ScheduledJobView, a4 as ScheduledHistoryPage, s as CronRunsResult, as as WorkflowInstanceStatus, ar as WorkflowInstancePage, aq as WorkflowInstanceDetail, ap as WorkflowInstanceCreated, ao as WorkflowInstanceAction, u as FunctionDescriptor, af as StorageListPage, x as GlobalTableInfo, w as GlobalFilterClause, y as GlobalTablePage, G as GlobalFacetResult, L as LunoraClient } from "../packem_shared/lunora-client.d-ReTNaYnW.mjs";
2
2
  import { CronJobInfo, VectorIndexSummary, VectorQueryMatch, PipelineLogQuery, PipelineLogPage, AdminTokenSummary, CreatedAdminToken, KvNamespaceSummary, KvKeyListResult, KvValueResult, AuthUser, AuthPage, AuthImpersonation, AuthCapabilities, AuthConfigInfo, AuthSession } from '@lunora/runtime';
3
3
  import '@lunora/errors';
4
4
  import "../packem_shared/function-reference.d-Br_hsKje.mjs";
@@ -1,4 +1,4 @@
1
- import { ae as ShardTrafficResult, t as DeploymentPauseStatus, a2 as ScheduleRecord, a8 as SchedulerStatus, a6 as ScheduledJobView, a4 as ScheduledHistoryPage, s as CronRunsResult, as as WorkflowInstanceStatus, ar as WorkflowInstancePage, aq as WorkflowInstanceDetail, ap as WorkflowInstanceCreated, ao as WorkflowInstanceAction, u as FunctionDescriptor, af as StorageListPage, x as GlobalTableInfo, w as GlobalFilterClause, y as GlobalTablePage, G as GlobalFacetResult, L as LunoraClient } from "../packem_shared/lunora-client.d-CrkO-uRI.js";
1
+ import { ae as ShardTrafficResult, t as DeploymentPauseStatus, a2 as ScheduleRecord, a8 as SchedulerStatus, a6 as ScheduledJobView, a4 as ScheduledHistoryPage, s as CronRunsResult, as as WorkflowInstanceStatus, ar as WorkflowInstancePage, aq as WorkflowInstanceDetail, ap as WorkflowInstanceCreated, ao as WorkflowInstanceAction, u as FunctionDescriptor, af as StorageListPage, x as GlobalTableInfo, w as GlobalFilterClause, y as GlobalTablePage, G as GlobalFacetResult, L as LunoraClient } from "../packem_shared/lunora-client.d-BC8i2bd_.js";
2
2
  import { CronJobInfo, VectorIndexSummary, VectorQueryMatch, PipelineLogQuery, PipelineLogPage, AdminTokenSummary, CreatedAdminToken, KvNamespaceSummary, KvKeyListResult, KvValueResult, AuthUser, AuthPage, AuthImpersonation, AuthCapabilities, AuthConfigInfo, AuthSession } from '@lunora/runtime';
3
3
  import '@lunora/errors';
4
4
  import "../packem_shared/function-reference.d-Br_hsKje.js";
@@ -1 +1 @@
1
- import{LunoraAdminClient as e,isLunoraAdminClient as r,requireAdminAuthClient as t}from"../packem_shared/LunoraAdminClient-Cmj8MYMe.mjs";export{e as LunoraAdminClient,r as isLunoraAdminClient,t as requireAdminAuthClient};
1
+ import{LunoraAdminClient as e,isLunoraAdminClient as r,requireAdminAuthClient as t}from"../packem_shared/LunoraAdminClient-GJZcfaGV.mjs";export{e as LunoraAdminClient,r as isLunoraAdminClient,t as requireAdminAuthClient};
@@ -47,7 +47,7 @@
47
47
  * authenticated. Branch on `status`, never on `user === null`, to tell "signed
48
48
  * out" from "signed in, identity not resolved yet".
49
49
  */
50
- import { L as LunoraClient, U as User } from "../packem_shared/lunora-client.d-BxU8-4s5.mjs";
50
+ import { L as LunoraClient, U as User } from "../packem_shared/lunora-client.d-ReTNaYnW.mjs";
51
51
  import { LunoraAdminClient } from "../admin/index.mjs";
52
52
  import { AuthPage, AuthImpersonation, AuthSession, AuthUser } from '@lunora/runtime';
53
53
  import '@lunora/errors';
@@ -47,7 +47,7 @@
47
47
  * authenticated. Branch on `status`, never on `user === null`, to tell "signed
48
48
  * out" from "signed in, identity not resolved yet".
49
49
  */
50
- import { L as LunoraClient, U as User } from "../packem_shared/lunora-client.d-CrkO-uRI.js";
50
+ import { L as LunoraClient, U as User } from "../packem_shared/lunora-client.d-BC8i2bd_.js";
51
51
  import { LunoraAdminClient } from "../admin/index.js";
52
52
  import { AuthPage, AuthImpersonation, AuthSession, AuthUser } from '@lunora/runtime';
53
53
  import '@lunora/errors';
package/dist/index.d.mts CHANGED
@@ -1,8 +1,8 @@
1
- import { R as ReconnectOptions, c as PersistenceAdapter, Q as QueryCacheAdapter, L as LunoraClient, a as Unsubscribe, B as BookmarkStorage, C as ConnectionStatus, S as SubscriptionError, H as HttpStreamRef, d as HttpStreamArgsOf, e as HttpStreamChunkOf, f as StreamIterable, O as OfflineQueueOptions } from "./packem_shared/lunora-client.d-BxU8-4s5.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, type p as CronRunInFlight, type q as CronRunRecord, type r as CronRunStatus, type s as CronRunsResult, D as DEFAULT_MAX_BUFFER, type t as DeploymentPauseStatus, type F as FunctionArgumentDescriptor, type u as FunctionDescriptor, type G as GlobalFacetResult, type v as GlobalFacetValue, type w as GlobalFilterClause, type x as GlobalTableInfo, type y as GlobalTablePage, type z as HttpStreamCallArgs, type E as LunoraClientError, type I as LunoraClientOptions, type M as MutationCallOptions, type J as MutationSettledEvent, type K as OnlineOnlyOption, type N as OptimisticLocalStore, type T as OptimisticUpdate, type V as OutboxMutation, type W as OutboxSink, type X as PersistedMutation, type P as Preloaded, type Y as ReplayCredential, type Z as ReplayIdentityVerdict, type _ as RoomRef, type $ as RowOp, type a0 as RpcEnvelope, type a1 as RpcResponseBody, type a2 as ScheduleRecord, type a3 as ScheduleRetryPolicy, type a4 as ScheduledHistoryPage, type a5 as ScheduledJobState, type a6 as ScheduledJobView, type a7 as SchedulerPoolStatus, type a8 as SchedulerStatus, type a9 as ServerMessage, type aa as ServerPokeEndMessage, type ab as ServerPokePartMessage, type ac as ServerPokeStartMessage, type ad as ShardTrafficEntry, type ae as ShardTrafficResult, type af as StorageListPage, type ag as StorageObject, type ah as StoredQuery, type ai as StreamHandle, type aj as SubscriptionCallback, type b as SubscriptionErrorCallback, ak as SubscriptionRegistry, type al as SubscriptionState, type am as SyncStatus, type an as SyncWatermark, type U as User, type ao as WorkflowInstanceAction, type ap as WorkflowInstanceCreated, type aq as WorkflowInstanceDetail, type ar as WorkflowInstancePage, type as as WorkflowInstanceStatus, type at as WorkflowInstanceSummary, type au as WorkflowStepDetail, type av as WsTokenProvider, aw as createClientQuery, ax as createLocalStore, ay as createStream } from "./packem_shared/lunora-client.d-BxU8-4s5.mjs";
1
+ import { R as ReconnectOptions, c as PersistenceAdapter, Q as QueryCacheAdapter, L as LunoraClient, a as Unsubscribe, B as BookmarkStorage, C as ConnectionStatus, S as SubscriptionError, H as HttpStreamRef, d as HttpStreamArgsOf, e as HttpStreamChunkOf, f as StreamIterable, O as OfflineQueueOptions } from "./packem_shared/lunora-client.d-ReTNaYnW.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, type p as CronRunInFlight, type q as CronRunRecord, type r as CronRunStatus, type s as CronRunsResult, D as DEFAULT_MAX_BUFFER, type t as DeploymentPauseStatus, type F as FunctionArgumentDescriptor, type u as FunctionDescriptor, type G as GlobalFacetResult, type v as GlobalFacetValue, type w as GlobalFilterClause, type x as GlobalTableInfo, type y as GlobalTablePage, type z as HttpStreamCallArgs, type E as LunoraClientError, type I as LunoraClientOptions, type M as MutationCallOptions, type J as MutationSettledEvent, type K as OnlineOnlyOption, type N as OptimisticLocalStore, type T as OptimisticUpdate, type V as OutboxMutation, type W as OutboxSink, type X as PersistedMutation, type P as Preloaded, type Y as ReplayCredential, type Z as ReplayIdentityVerdict, type _ as RoomRef, type $ as RowOp, type a0 as RpcEnvelope, type a1 as RpcResponseBody, type a2 as ScheduleRecord, type a3 as ScheduleRetryPolicy, type a4 as ScheduledHistoryPage, type a5 as ScheduledJobState, type a6 as ScheduledJobView, type a7 as SchedulerPoolStatus, type a8 as SchedulerStatus, type a9 as ServerMessage, type aa as ServerPokeEndMessage, type ab as ServerPokePartMessage, type ac as ServerPokeStartMessage, type ad as ShardTrafficEntry, type ae as ShardTrafficResult, type af as StorageListPage, type ag as StorageObject, type ah as StoredQuery, type ai as StreamHandle, type aj as SubscriptionCallback, type b as SubscriptionErrorCallback, ak as SubscriptionRegistry, type al as SubscriptionState, type am as SyncStatus, type an as SyncWatermark, type U as User, type ao as WorkflowInstanceAction, type ap as WorkflowInstanceCreated, type aq as WorkflowInstanceDetail, type ar as WorkflowInstancePage, type as as WorkflowInstanceStatus, type at as WorkflowInstanceSummary, type au as WorkflowStepDetail, type av as WsTokenProvider, aw as createClientQuery, ax as createLocalStore, ay as createStream } from "./packem_shared/lunora-client.d-ReTNaYnW.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-ByaSovKg.mjs";
5
+ export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-C2eH0Vm2.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 { AdminTokenSummary, AuthCapabilities, AuthConfigInfo, AuthImpersonation, AuthPage, AuthSession, AuthUser, AuthUserFieldSpec, CreatedAdminToken, CronJobInfo, KvKeyEntry, KvKeyListResult, KvNamespaceSummary, KvValueResult, PipelineLogColumnMap, PipelineLogCursor, PipelineLogField, PipelineLogPage, PipelineLogQuery, PipelineLogRow, VectorIndexSummary, VectorQueryMatch } from '@lunora/runtime';
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { R as ReconnectOptions, c as PersistenceAdapter, Q as QueryCacheAdapter, L as LunoraClient, a as Unsubscribe, B as BookmarkStorage, C as ConnectionStatus, S as SubscriptionError, H as HttpStreamRef, d as HttpStreamArgsOf, e as HttpStreamChunkOf, f as StreamIterable, O as OfflineQueueOptions } from "./packem_shared/lunora-client.d-CrkO-uRI.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, type p as CronRunInFlight, type q as CronRunRecord, type r as CronRunStatus, type s as CronRunsResult, D as DEFAULT_MAX_BUFFER, type t as DeploymentPauseStatus, type F as FunctionArgumentDescriptor, type u as FunctionDescriptor, type G as GlobalFacetResult, type v as GlobalFacetValue, type w as GlobalFilterClause, type x as GlobalTableInfo, type y as GlobalTablePage, type z as HttpStreamCallArgs, type E as LunoraClientError, type I as LunoraClientOptions, type M as MutationCallOptions, type J as MutationSettledEvent, type K as OnlineOnlyOption, type N as OptimisticLocalStore, type T as OptimisticUpdate, type V as OutboxMutation, type W as OutboxSink, type X as PersistedMutation, type P as Preloaded, type Y as ReplayCredential, type Z as ReplayIdentityVerdict, type _ as RoomRef, type $ as RowOp, type a0 as RpcEnvelope, type a1 as RpcResponseBody, type a2 as ScheduleRecord, type a3 as ScheduleRetryPolicy, type a4 as ScheduledHistoryPage, type a5 as ScheduledJobState, type a6 as ScheduledJobView, type a7 as SchedulerPoolStatus, type a8 as SchedulerStatus, type a9 as ServerMessage, type aa as ServerPokeEndMessage, type ab as ServerPokePartMessage, type ac as ServerPokeStartMessage, type ad as ShardTrafficEntry, type ae as ShardTrafficResult, type af as StorageListPage, type ag as StorageObject, type ah as StoredQuery, type ai as StreamHandle, type aj as SubscriptionCallback, type b as SubscriptionErrorCallback, ak as SubscriptionRegistry, type al as SubscriptionState, type am as SyncStatus, type an as SyncWatermark, type U as User, type ao as WorkflowInstanceAction, type ap as WorkflowInstanceCreated, type aq as WorkflowInstanceDetail, type ar as WorkflowInstancePage, type as as WorkflowInstanceStatus, type at as WorkflowInstanceSummary, type au as WorkflowStepDetail, type av as WsTokenProvider, aw as createClientQuery, ax as createLocalStore, ay as createStream } from "./packem_shared/lunora-client.d-CrkO-uRI.js";
1
+ import { R as ReconnectOptions, c as PersistenceAdapter, Q as QueryCacheAdapter, L as LunoraClient, a as Unsubscribe, B as BookmarkStorage, C as ConnectionStatus, S as SubscriptionError, H as HttpStreamRef, d as HttpStreamArgsOf, e as HttpStreamChunkOf, f as StreamIterable, O as OfflineQueueOptions } from "./packem_shared/lunora-client.d-BC8i2bd_.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, type p as CronRunInFlight, type q as CronRunRecord, type r as CronRunStatus, type s as CronRunsResult, D as DEFAULT_MAX_BUFFER, type t as DeploymentPauseStatus, type F as FunctionArgumentDescriptor, type u as FunctionDescriptor, type G as GlobalFacetResult, type v as GlobalFacetValue, type w as GlobalFilterClause, type x as GlobalTableInfo, type y as GlobalTablePage, type z as HttpStreamCallArgs, type E as LunoraClientError, type I as LunoraClientOptions, type M as MutationCallOptions, type J as MutationSettledEvent, type K as OnlineOnlyOption, type N as OptimisticLocalStore, type T as OptimisticUpdate, type V as OutboxMutation, type W as OutboxSink, type X as PersistedMutation, type P as Preloaded, type Y as ReplayCredential, type Z as ReplayIdentityVerdict, type _ as RoomRef, type $ as RowOp, type a0 as RpcEnvelope, type a1 as RpcResponseBody, type a2 as ScheduleRecord, type a3 as ScheduleRetryPolicy, type a4 as ScheduledHistoryPage, type a5 as ScheduledJobState, type a6 as ScheduledJobView, type a7 as SchedulerPoolStatus, type a8 as SchedulerStatus, type a9 as ServerMessage, type aa as ServerPokeEndMessage, type ab as ServerPokePartMessage, type ac as ServerPokeStartMessage, type ad as ShardTrafficEntry, type ae as ShardTrafficResult, type af as StorageListPage, type ag as StorageObject, type ah as StoredQuery, type ai as StreamHandle, type aj as SubscriptionCallback, type b as SubscriptionErrorCallback, ak as SubscriptionRegistry, type al as SubscriptionState, type am as SyncStatus, type an as SyncWatermark, type U as User, type ao as WorkflowInstanceAction, type ap as WorkflowInstanceCreated, type aq as WorkflowInstanceDetail, type ar as WorkflowInstancePage, type as as WorkflowInstanceStatus, type at as WorkflowInstanceSummary, type au as WorkflowStepDetail, type av as WsTokenProvider, aw as createClientQuery, ax as createLocalStore, ay as createStream } from "./packem_shared/lunora-client.d-BC8i2bd_.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-BB2CUNhN.js";
5
+ export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-C4nGCFfk.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 { AdminTokenSummary, AuthCapabilities, AuthConfigInfo, AuthImpersonation, AuthPage, AuthSession, AuthUser, AuthUserFieldSpec, CreatedAdminToken, CronJobInfo, KvKeyEntry, KvKeyListResult, KvNamespaceSummary, KvValueResult, PipelineLogColumnMap, PipelineLogCursor, PipelineLogField, PipelineLogPage, PipelineLogQuery, PipelineLogRow, VectorIndexSummary, VectorQueryMatch } from '@lunora/runtime';
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 i}from"./packem_shared/createAsyncStoragePersistence-BgfdvLwe.mjs";import{createAsyncStorageQueryCache as n}from"./packem_shared/createAsyncStorageQueryCache-6Y94ocbQ.mjs";import{setAuthTokenProvider as s}from"./packem_shared/setAuthTokenProvider-DhBppDiZ.mjs";import{default as x}from"./packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs";import{createCallRunner as l}from"./packem_shared/createCallRunner-Bwcrfh76.mjs";import{createClientQuery as y}from"./packem_shared/createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as R}from"./packem_shared/TabCoordinator-DIySdaRV.mjs";import{a as S,i as A}from"./packem_shared/delta-merge-C6OqMEPH.mjs";import{CONFLICT_ERROR_CODE as h,TransportError as D,getErrorCode as L,getRetryAfterMs as T,isAuthReplayFailure as Q,isConflictError as _,isForbiddenError as F,isRateLimitedError as I,isUnauthorizedError as M}from"./packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as g}from"./packem_shared/httpStream-DN3D9WqW.mjs";import{c as v}from"./packem_shared/live-stream-DBKgZlnb.mjs";import{liveTopicSubscription as k,subscribeLiveTopic as B}from"./packem_shared/liveTopicSubscription-DQtKMFKw.mjs";import{createLocalStore as N}from"./packem_shared/createLocalStore-WKNHD1ca.mjs";import{L as K}from"./packem_shared/lunora-client-DbMT_z_l.mjs";import{createMutatorRunner as X}from"./packem_shared/createMutatorRunner-CuMRJpUx.mjs";import{O as w}from"./packem_shared/offline-queue-HwrYARIL.mjs";import{default as H}from"./packem_shared/OutboxDeclinedError-D6vF-WyL.mjs";import{createInMemoryPersistence as W,createIndexedDbPersistence as Y}from"./packem_shared/createInMemoryPersistence-C-IzNVbg.mjs";import{preloadQuery as $,preloadedQueryResult as ee}from"./packem_shared/preloadQuery-uFy24PCR.mjs";import{createInMemoryQueryCache as oe,createIndexedDbQueryCache as te,queryCacheKey as ae}from"./packem_shared/createInMemoryQueryCache-DR6AorA2.mjs";import{createReconnect as ie}from"./packem_shared/createReconnect-CjTmjJDH.mjs";import{c as ne}from"./packem_shared/snapshot-precondition-BEtcSbWr.mjs";import{DEFAULT_MAX_BUFFER as se,createStream as fe}from"./packem_shared/DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";import{SubscriptionRegistry as ue}from"./packem_shared/SubscriptionRegistry-DjFfxba2.mjs";export{h as CONFLICT_ERROR_CODE,se as DEFAULT_MAX_BUFFER,K as LunoraClient,w as OfflineQueue,H as OutboxDeclinedError,o as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,ue as SubscriptionRegistry,R as TabCoordinator,D as TransportError,S as applyDelta,v as connectLiveStream,i as createAsyncStoragePersistence,n as createAsyncStorageQueryCache,l as createCallRunner,y as createClientQuery,x as createInMemoryBookmarkStorage,W as createInMemoryPersistence,oe as createInMemoryQueryCache,Y as createIndexedDbPersistence,te as createIndexedDbQueryCache,N as createLocalStore,X as createMutatorRunner,ie as createReconnect,ne as createSnapshotPrecondition,fe as createStream,L as getErrorCode,T as getRetryAfterMs,g as httpStream,Q as isAuthReplayFailure,_ as isConflictError,F as isForbiddenError,A as isMutationDelta,I as isRateLimitedError,M as isUnauthorizedError,k as liveTopicSubscription,t as maxSeq,$ as preloadQuery,ee as preloadedQueryResult,ae as queryCacheKey,a as reconcileOptimistic,s as setAuthTokenProvider,B as subscribeLiveTopic};
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 i}from"./packem_shared/createAsyncStoragePersistence-BgfdvLwe.mjs";import{createAsyncStorageQueryCache as n}from"./packem_shared/createAsyncStorageQueryCache-6Y94ocbQ.mjs";import{setAuthTokenProvider as s}from"./packem_shared/setAuthTokenProvider-DhBppDiZ.mjs";import{default as x}from"./packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs";import{createCallRunner as l}from"./packem_shared/createCallRunner-Bwcrfh76.mjs";import{createClientQuery as y}from"./packem_shared/createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as R}from"./packem_shared/TabCoordinator-DIySdaRV.mjs";import{a as S,i as A}from"./packem_shared/delta-merge-C6OqMEPH.mjs";import{CONFLICT_ERROR_CODE as h,TransportError as D,getErrorCode as L,getRetryAfterMs as T,isAuthReplayFailure as Q,isConflictError as _,isForbiddenError as F,isRateLimitedError as I,isUnauthorizedError as M}from"./packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as g}from"./packem_shared/httpStream-DN3D9WqW.mjs";import{c as v}from"./packem_shared/live-stream-DBKgZlnb.mjs";import{liveTopicSubscription as k,subscribeLiveTopic as B}from"./packem_shared/liveTopicSubscription-DQtKMFKw.mjs";import{createLocalStore as N}from"./packem_shared/createLocalStore-WKNHD1ca.mjs";import{L as K}from"./packem_shared/lunora-client-DsPXE0O9.mjs";import{createMutatorRunner as X}from"./packem_shared/createMutatorRunner-CuMRJpUx.mjs";import{O as w}from"./packem_shared/offline-queue-HwrYARIL.mjs";import{default as H}from"./packem_shared/OutboxDeclinedError-D6vF-WyL.mjs";import{createInMemoryPersistence as W,createIndexedDbPersistence as Y}from"./packem_shared/createInMemoryPersistence-C-IzNVbg.mjs";import{preloadQuery as $,preloadedQueryResult as ee}from"./packem_shared/preloadQuery-uFy24PCR.mjs";import{createInMemoryQueryCache as oe,createIndexedDbQueryCache as te,queryCacheKey as ae}from"./packem_shared/createInMemoryQueryCache-DR6AorA2.mjs";import{createReconnect as ie}from"./packem_shared/createReconnect-CjTmjJDH.mjs";import{c as ne}from"./packem_shared/snapshot-precondition-BEtcSbWr.mjs";import{DEFAULT_MAX_BUFFER as se,createStream as fe}from"./packem_shared/DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";import{SubscriptionRegistry as ue}from"./packem_shared/SubscriptionRegistry-DjFfxba2.mjs";export{h as CONFLICT_ERROR_CODE,se as DEFAULT_MAX_BUFFER,K as LunoraClient,w as OfflineQueue,H as OutboxDeclinedError,o as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,ue as SubscriptionRegistry,R as TabCoordinator,D as TransportError,S as applyDelta,v as connectLiveStream,i as createAsyncStoragePersistence,n as createAsyncStorageQueryCache,l as createCallRunner,y as createClientQuery,x as createInMemoryBookmarkStorage,W as createInMemoryPersistence,oe as createInMemoryQueryCache,Y as createIndexedDbPersistence,te as createIndexedDbQueryCache,N as createLocalStore,X as createMutatorRunner,ie as createReconnect,ne as createSnapshotPrecondition,fe as createStream,L as getErrorCode,T as getRetryAfterMs,g as httpStream,Q as isAuthReplayFailure,_ as isConflictError,F as isForbiddenError,A as isMutationDelta,I as isRateLimitedError,M as isUnauthorizedError,k as liveTopicSubscription,t as maxSeq,$ as preloadQuery,ee as preloadedQueryResult,ae as queryCacheKey,a as reconcileOptimistic,s as setAuthTokenProvider,B as subscribeLiveTopic};
@@ -1 +1 @@
1
- import{LunoraError as A}from"@lunora/errors";import{A as r,F as u,C as O,a as l,O as y,b as _,c as E,G as P,d as S,e as p,K as f,f as w,g as c,S as U,h as F,i as o,j as b,k as I,V as g,l as R,L as G,m as k,s as C,n as N,o as M,p as L,q as v,r as V,t as D,u as K,v as B,w as J,x,y as $,z as W,B as z,D as j,E as q,H as Y,I as Q,J as X,M as Z,N as tt,P as at,Q as st,R as et,T as nt,U as it,W as rt,X as ct,Y as ot,Z as dt,_ as mt,$ as ht,a0 as Tt,a1 as Ht,a2 as At,a3 as ut,a4 as Ot,a5 as lt,a6 as yt,a7 as _t,a8 as Et,a9 as Pt,aa as St,ab as pt,ac as ft,ad as wt,ae as Ut,af as Ft,ag as bt,ah as It,ai as gt,aj as Rt,ak as Gt,al as kt,am as Ct,an as Nt,ao as Mt,ap as Lt,aq as vt,ar as Vt,as as Dt}from"./lunora-client-DbMT_z_l.mjs";import{w as e,b as d}from"./client-urls-BHLUjjcG.mjs";import{encodeWire as h,decodeWire as T}from"@lunora/wire";const Kt=async a=>(a.assertOpen(),(await a.adminFetch(r,"GET")).tokens??[]),Bt=async(a,t)=>(a.assertOpen(),await a.adminFetch(r,"POST",t)),Jt=async(a,t)=>{a.assertOpen(),await a.adminFetch(e(r,{name:t}),"DELETE")},xt=async a=>(a.assertOpen(),(await a.adminFetch(u,"GET")).functions??[]),$t=async a=>(a.assertOpen(),(await a.adminFetch(O,"GET")).jobs??[]),Wt=async(a,t)=>{a.assertOpen();const s=await a.adminFetch(l,"POST",{name:t});return{name:s.name??t,ran:s.ran===!0}},zt=async a=>(a.assertOpen(),await a.adminFetch(y,"GET")),jt=async a=>(a.assertOpen(),await a.adminFetch(_,"GET")),qt=async a=>(a.assertOpen(),await a.adminFetch(E,"GET")),Yt=async a=>(a.assertOpen(),await a.adminFetch(P,"GET")),Qt=async(a,t)=>{a.assertOpen();const s=new URLSearchParams({table:t.table});return t.limit!==void 0&&s.set("limit",String(t.limit)),t.offset!==void 0&&s.set("offset",String(t.offset)),t.filters!==void 0&&t.filters.length>0&&s.set("filters",JSON.stringify(h(t.filters))),T(await a.adminFetch(`${S}?${s.toString()}`,"GET"))},Xt=async(a,t)=>{a.assertOpen();const s=new URLSearchParams({column:t.column,table:t.table});return t.limit!==void 0&&s.set("limit",String(t.limit)),t.filters!==void 0&&t.filters.length>0&&s.set("filters",JSON.stringify(h(t.filters))),T(await a.adminFetch(`${p}?${s.toString()}`,"GET"))},Zt=async a=>(a.assertOpen(),(await a.adminFetch(f,"GET")).namespaces??[]),ta=async(a,t)=>{a.assertOpen();const s=e(w,{cursor:t.cursor,limit:t.limit,namespace:t.namespace,prefix:t.prefix});return await a.adminFetch(s,"GET")},aa=async(a,t)=>{a.assertOpen();const s=e(c,{key:t.key,namespace:t.namespace});return await a.adminFetch(s,"GET")},sa=async(a,t)=>{a.assertOpen(),await a.adminFetch(c,"PUT",t)},ea=async(a,t)=>{a.assertOpen();const s=e(c,{key:t.key,namespace:t.namespace});await a.adminFetch(s,"DELETE")},na=async(a,t)=>{a.assertOpen();const s=await a.adminFetch(U,"POST",{table:t});return{failed:s.failed??0,ok:s.ok??0,shards:s.shards??[]}},ia=async(a,t={})=>{a.assertOpen();const s=await a.adminFetch(F,"POST",t);return{nextCursor:s.nextCursor,rows:s.rows??[]}},ra=async(a,t={})=>{a.assertOpen();const s=e(o,{bucket:t.bucket,cursor:t.cursor,limit:t.limit,prefix:t.prefix}),n=await a.adminFetch(s,"GET");return{cursor:n.cursor,objects:n.objects??[]}},ca=async(a,t,s)=>{a.assertOpen();const n=`${o}?key=${encodeURIComponent(t)}${d(s?.bucket)}`,i=await a.adminFetch(n,"DELETE");return{deleted:i.deleted===!0,key:i.key??t}},oa=async a=>(a.assertOpen(),(await a.adminFetch(b,"GET")).buckets??[]),da=async(a,t)=>{a.assertOpen();const s=`${o}?key=${encodeURIComponent(t.key)}${d(t.bucket)}`,n=await a.adminFetch(s,"PUT",t.body,t.contentType);return{etag:n.etag,key:n.key??t.key}},ma=async(a,t,s)=>{a.assertOpen();const n=s?.expiresInSeconds,i=n===void 0?"":`&expiresIn=${encodeURIComponent(n.toString())}`,H=`${I}?key=${encodeURIComponent(t)}${i}${d(s?.bucket)}`,m=await a.adminFetch(H,"GET");if(typeof m.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return m.url},ha=async a=>(a.assertOpen(),(await a.adminFetch(g,"GET")).indexes??[]),Ta=async(a,t)=>(a.assertOpen(),(await a.adminFetch(R,"POST",t)).matches??[]);class ya extends G{async shardTraffic(t){return na(this.adminHost,t)}async getDeploymentPause(){return k(this.adminHost)}async setDeploymentPause(t,s){return C(this.adminHost,t,s)}async listScheduledJobs(){return N(this.adminHost)}async schedulerStatus(){return M(this.adminHost)}async getScheduledJob(t){return L(this.adminHost,t)}async listScheduledHistory(t={}){return v(this.adminHost,t)}async listCronRuns(){return V(this.adminHost)}async cancelScheduledJob(t){return D(this.adminHost,t)}async listDeadJobs(){return K(this.adminHost)}async retryDeadJob(t){return B(this.adminHost,t)}async removeDeadJob(t){return J(this.adminHost,t)}async listWorkflowInstances(t){return x(this.adminHost,t)}async getWorkflowInstance(t){return $(this.adminHost,t)}async createWorkflowInstance(t){return W(this.adminHost,t)}async sendWorkflowEvent(t){return z(this.adminHost,t)}async setWorkflowInstanceStatus(t){return j(this.adminHost,t)}async listFunctions(){return xt(this.adminHost)}async getCronJobs(){return $t(this.adminHost)}async runCronJob(t){return Wt(this.adminHost,t)}async fetchOpenApi(){return zt(this.adminHost)}async fetchArchitecture(){return jt(this.adminHost)}async fetchOpenRpc(){return qt(this.adminHost)}async listStorageObjects(t={}){return ra(this.adminHost,t)}async deleteStorageObject(t,s){return ca(this.adminHost,t,s)}async listStorageBuckets(){return oa(this.adminHost)}async uploadStorageObject(t){return da(this.adminHost,t)}async signedStorageUrl(t,s){return ma(this.adminHost,t,s)}async listGlobalTables(){return Yt(this.adminHost)}async readGlobalTablePage(t){return Qt(this.adminHost,t)}async facetGlobalColumn(t){return Xt(this.adminHost,t)}async listVectorIndexes(){return ha(this.adminHost)}async queryVectorIndex(t){return Ta(this.adminHost,t)}async queryLogArchive(t={}){return ia(this.adminHost,t)}async listAdminTokens(){return Kt(this.adminHost)}async createAdminToken(t){return Bt(this.adminHost,t)}async revokeAdminToken(t){return Jt(this.adminHost,t)}async listKvNamespaces(){return Zt(this.adminHost)}async listKvKeys(t){return ta(this.adminHost,t)}async getKvValue(t){return aa(this.adminHost,t)}async putKvValue(t){return sa(this.adminHost,t)}async deleteKvKey(t){return ea(this.adminHost,t)}async listAuthUsers(t={}){this.adminHost.assertOpen();const s=e(q,{filterField:t.filterField,filterValue:t.filterValue,limit:t.limit,offset:t.offset,search:t.search,searchField:t.searchField,sortBy:t.sortBy,sortDirection:t.sortDirection});return await this.adminHost.adminFetch(s,"GET")}async createAuthUser(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Y,"POST",t)}async setAuthUserRole(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Q,"POST",t)}async banAuthUser(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(X,"POST",t)}async unbanAuthUser(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Z,"POST",t)}async setAuthUserPassword(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(tt,"POST",t)}async removeAuthUser(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(at,"POST",t)}async impersonateAuthUser(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(st,"POST",t)}async revokeAuthSession(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(et,"POST",t)}async revokeAuthUserSessions(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(nt,"POST",t)}async getAuthCapabilities(){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(it,"GET")}async updateAuthUser(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(rt,"POST",t)}async listAuthAccounts(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(e(ct,{userId:t.userId}),"GET")}async unlinkAuthAccount(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(ot,"POST",t)}async listAuthApiKeys(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(e(dt,{userId:t.userId}),"GET")}async deleteAuthApiKey(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(mt,"POST",t)}async listAuthPasskeys(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(e(ht,{userId:t.userId}),"GET")}async deleteAuthPasskey(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Tt,"POST",t)}async disableAuthTwoFactor(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ht,"POST",t)}async listAuthOrganizations(t={}){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(e(At,{limit:t.limit,offset:t.offset}),"GET")}async listAuthOrgMembers(t){this.adminHost.assertOpen();const s=e(ut,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminHost.adminFetch(s,"GET")}async listAuthOrgInvitations(t){this.adminHost.assertOpen();const s=e(Ot,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminHost.adminFetch(s,"GET")}async listAuthSignUpInvitations(t={}){this.adminHost.assertOpen();const s=e(lt,{limit:t.limit,offset:t.offset});return await this.adminHost.adminFetch(s,"GET")}async createAuthSignUpInvitation(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(yt,"POST",t)}async revokeAuthSignUpInvitation(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(_t,"POST",t)}async removeAuthOrgMember(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Et,"POST",t)}async cancelAuthOrgInvitation(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Pt,"POST",t)}async getAuthConfig(){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(St,"GET")}async createAuthOrganization(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(pt,"POST",t)}async updateAuthOrganization(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(ft,"POST",t)}async deleteAuthOrganization(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(wt,"POST",t)}async addAuthOrgMember(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ut,"POST",t)}async inviteAuthOrgMember(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ft,"POST",t)}async setAuthOrgMemberRole(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(bt,"POST",t)}async listAuthOrgTeams(t){this.adminHost.assertOpen();const s=e(It,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminHost.adminFetch(s,"GET")}async createAuthOrgTeam(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(gt,"POST",t)}async updateAuthOrgTeam(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Rt,"POST",t)}async removeAuthOrgTeam(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Gt,"POST",t)}async listAuthOrgTeamMembers(t){this.adminHost.assertOpen();const s=e(kt,{limit:t.limit,offset:t.offset,teamId:t.teamId});return await this.adminHost.adminFetch(s,"GET")}async addAuthOrgTeamMember(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ct,"POST",t)}async removeAuthOrgTeamMember(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Nt,"POST",t)}async listAuthOrgRoles(t){this.adminHost.assertOpen();const s=e(Mt,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminHost.adminFetch(s,"GET")}async createAuthOrgRole(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Lt,"POST",t)}async updateAuthOrgRole(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(vt,"POST",t)}async deleteAuthOrgRole(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Vt,"POST",t)}async listAuthSessions(t={}){this.adminHost.assertOpen();const s=e(Dt,{limit:t.limit,offset:t.offset,userId:t.userId});return await this.adminHost.adminFetch(s,"GET")}}const Ha=a=>"listAuthUsers"in a,_a=a=>{if(!Ha(a))throw new A("INTERNAL","The admin auth hooks need a LunoraAdminClient: construct the provider's client with `new LunoraAdminClient(...)` from `@lunora/client/admin`.");return a};export{ya as LunoraAdminClient,Ha as isLunoraAdminClient,_a as requireAdminAuthClient};
1
+ import{LunoraError as A}from"@lunora/errors";import{A as r,F as u,C as O,a as l,O as y,b as _,c as E,G as P,d as S,e as p,K as f,f as w,g as c,S as U,h as F,i as o,j as b,k as I,V as g,l as R,L as G,m as k,s as C,n as N,o as M,p as L,q as v,r as V,t as D,u as K,v as B,w as J,x,y as $,z as W,B as z,D as j,E as q,H as Y,I as Q,J as X,M as Z,N as tt,P as at,Q as st,R as et,T as nt,U as it,W as rt,X as ct,Y as ot,Z as dt,_ as mt,$ as ht,a0 as Tt,a1 as Ht,a2 as At,a3 as ut,a4 as Ot,a5 as lt,a6 as yt,a7 as _t,a8 as Et,a9 as Pt,aa as St,ab as pt,ac as ft,ad as wt,ae as Ut,af as Ft,ag as bt,ah as It,ai as gt,aj as Rt,ak as Gt,al as kt,am as Ct,an as Nt,ao as Mt,ap as Lt,aq as vt,ar as Vt,as as Dt}from"./lunora-client-DsPXE0O9.mjs";import{w as e,b as d}from"./client-urls-BHLUjjcG.mjs";import{encodeWire as h,decodeWire as T}from"@lunora/wire";const Kt=async a=>(a.assertOpen(),(await a.adminFetch(r,"GET")).tokens??[]),Bt=async(a,t)=>(a.assertOpen(),await a.adminFetch(r,"POST",t)),Jt=async(a,t)=>{a.assertOpen(),await a.adminFetch(e(r,{name:t}),"DELETE")},xt=async a=>(a.assertOpen(),(await a.adminFetch(u,"GET")).functions??[]),$t=async a=>(a.assertOpen(),(await a.adminFetch(O,"GET")).jobs??[]),Wt=async(a,t)=>{a.assertOpen();const s=await a.adminFetch(l,"POST",{name:t});return{name:s.name??t,ran:s.ran===!0}},zt=async a=>(a.assertOpen(),await a.adminFetch(y,"GET")),jt=async a=>(a.assertOpen(),await a.adminFetch(_,"GET")),qt=async a=>(a.assertOpen(),await a.adminFetch(E,"GET")),Yt=async a=>(a.assertOpen(),await a.adminFetch(P,"GET")),Qt=async(a,t)=>{a.assertOpen();const s=new URLSearchParams({table:t.table});return t.limit!==void 0&&s.set("limit",String(t.limit)),t.offset!==void 0&&s.set("offset",String(t.offset)),t.filters!==void 0&&t.filters.length>0&&s.set("filters",JSON.stringify(h(t.filters))),T(await a.adminFetch(`${S}?${s.toString()}`,"GET"))},Xt=async(a,t)=>{a.assertOpen();const s=new URLSearchParams({column:t.column,table:t.table});return t.limit!==void 0&&s.set("limit",String(t.limit)),t.filters!==void 0&&t.filters.length>0&&s.set("filters",JSON.stringify(h(t.filters))),T(await a.adminFetch(`${p}?${s.toString()}`,"GET"))},Zt=async a=>(a.assertOpen(),(await a.adminFetch(f,"GET")).namespaces??[]),ta=async(a,t)=>{a.assertOpen();const s=e(w,{cursor:t.cursor,limit:t.limit,namespace:t.namespace,prefix:t.prefix});return await a.adminFetch(s,"GET")},aa=async(a,t)=>{a.assertOpen();const s=e(c,{key:t.key,namespace:t.namespace});return await a.adminFetch(s,"GET")},sa=async(a,t)=>{a.assertOpen(),await a.adminFetch(c,"PUT",t)},ea=async(a,t)=>{a.assertOpen();const s=e(c,{key:t.key,namespace:t.namespace});await a.adminFetch(s,"DELETE")},na=async(a,t)=>{a.assertOpen();const s=await a.adminFetch(U,"POST",{table:t});return{failed:s.failed??0,ok:s.ok??0,shards:s.shards??[]}},ia=async(a,t={})=>{a.assertOpen();const s=await a.adminFetch(F,"POST",t);return{nextCursor:s.nextCursor,rows:s.rows??[]}},ra=async(a,t={})=>{a.assertOpen();const s=e(o,{bucket:t.bucket,cursor:t.cursor,limit:t.limit,prefix:t.prefix}),n=await a.adminFetch(s,"GET");return{cursor:n.cursor,objects:n.objects??[]}},ca=async(a,t,s)=>{a.assertOpen();const n=`${o}?key=${encodeURIComponent(t)}${d(s?.bucket)}`,i=await a.adminFetch(n,"DELETE");return{deleted:i.deleted===!0,key:i.key??t}},oa=async a=>(a.assertOpen(),(await a.adminFetch(b,"GET")).buckets??[]),da=async(a,t)=>{a.assertOpen();const s=`${o}?key=${encodeURIComponent(t.key)}${d(t.bucket)}`,n=await a.adminFetch(s,"PUT",t.body,t.contentType);return{etag:n.etag,key:n.key??t.key}},ma=async(a,t,s)=>{a.assertOpen();const n=s?.expiresInSeconds,i=n===void 0?"":`&expiresIn=${encodeURIComponent(n.toString())}`,H=`${I}?key=${encodeURIComponent(t)}${i}${d(s?.bucket)}`,m=await a.adminFetch(H,"GET");if(typeof m.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return m.url},ha=async a=>(a.assertOpen(),(await a.adminFetch(g,"GET")).indexes??[]),Ta=async(a,t)=>(a.assertOpen(),(await a.adminFetch(R,"POST",t)).matches??[]);class ya extends G{async shardTraffic(t){return na(this.adminHost,t)}async getDeploymentPause(){return k(this.adminHost)}async setDeploymentPause(t,s){return C(this.adminHost,t,s)}async listScheduledJobs(){return N(this.adminHost)}async schedulerStatus(){return M(this.adminHost)}async getScheduledJob(t){return L(this.adminHost,t)}async listScheduledHistory(t={}){return v(this.adminHost,t)}async listCronRuns(){return V(this.adminHost)}async cancelScheduledJob(t){return D(this.adminHost,t)}async listDeadJobs(){return K(this.adminHost)}async retryDeadJob(t){return B(this.adminHost,t)}async removeDeadJob(t){return J(this.adminHost,t)}async listWorkflowInstances(t){return x(this.adminHost,t)}async getWorkflowInstance(t){return $(this.adminHost,t)}async createWorkflowInstance(t){return W(this.adminHost,t)}async sendWorkflowEvent(t){return z(this.adminHost,t)}async setWorkflowInstanceStatus(t){return j(this.adminHost,t)}async listFunctions(){return xt(this.adminHost)}async getCronJobs(){return $t(this.adminHost)}async runCronJob(t){return Wt(this.adminHost,t)}async fetchOpenApi(){return zt(this.adminHost)}async fetchArchitecture(){return jt(this.adminHost)}async fetchOpenRpc(){return qt(this.adminHost)}async listStorageObjects(t={}){return ra(this.adminHost,t)}async deleteStorageObject(t,s){return ca(this.adminHost,t,s)}async listStorageBuckets(){return oa(this.adminHost)}async uploadStorageObject(t){return da(this.adminHost,t)}async signedStorageUrl(t,s){return ma(this.adminHost,t,s)}async listGlobalTables(){return Yt(this.adminHost)}async readGlobalTablePage(t){return Qt(this.adminHost,t)}async facetGlobalColumn(t){return Xt(this.adminHost,t)}async listVectorIndexes(){return ha(this.adminHost)}async queryVectorIndex(t){return Ta(this.adminHost,t)}async queryLogArchive(t={}){return ia(this.adminHost,t)}async listAdminTokens(){return Kt(this.adminHost)}async createAdminToken(t){return Bt(this.adminHost,t)}async revokeAdminToken(t){return Jt(this.adminHost,t)}async listKvNamespaces(){return Zt(this.adminHost)}async listKvKeys(t){return ta(this.adminHost,t)}async getKvValue(t){return aa(this.adminHost,t)}async putKvValue(t){return sa(this.adminHost,t)}async deleteKvKey(t){return ea(this.adminHost,t)}async listAuthUsers(t={}){this.adminHost.assertOpen();const s=e(q,{filterField:t.filterField,filterValue:t.filterValue,limit:t.limit,offset:t.offset,search:t.search,searchField:t.searchField,sortBy:t.sortBy,sortDirection:t.sortDirection});return await this.adminHost.adminFetch(s,"GET")}async createAuthUser(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Y,"POST",t)}async setAuthUserRole(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Q,"POST",t)}async banAuthUser(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(X,"POST",t)}async unbanAuthUser(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Z,"POST",t)}async setAuthUserPassword(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(tt,"POST",t)}async removeAuthUser(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(at,"POST",t)}async impersonateAuthUser(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(st,"POST",t)}async revokeAuthSession(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(et,"POST",t)}async revokeAuthUserSessions(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(nt,"POST",t)}async getAuthCapabilities(){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(it,"GET")}async updateAuthUser(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(rt,"POST",t)}async listAuthAccounts(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(e(ct,{userId:t.userId}),"GET")}async unlinkAuthAccount(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(ot,"POST",t)}async listAuthApiKeys(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(e(dt,{userId:t.userId}),"GET")}async deleteAuthApiKey(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(mt,"POST",t)}async listAuthPasskeys(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(e(ht,{userId:t.userId}),"GET")}async deleteAuthPasskey(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Tt,"POST",t)}async disableAuthTwoFactor(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ht,"POST",t)}async listAuthOrganizations(t={}){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(e(At,{limit:t.limit,offset:t.offset}),"GET")}async listAuthOrgMembers(t){this.adminHost.assertOpen();const s=e(ut,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminHost.adminFetch(s,"GET")}async listAuthOrgInvitations(t){this.adminHost.assertOpen();const s=e(Ot,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminHost.adminFetch(s,"GET")}async listAuthSignUpInvitations(t={}){this.adminHost.assertOpen();const s=e(lt,{limit:t.limit,offset:t.offset});return await this.adminHost.adminFetch(s,"GET")}async createAuthSignUpInvitation(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(yt,"POST",t)}async revokeAuthSignUpInvitation(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(_t,"POST",t)}async removeAuthOrgMember(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Et,"POST",t)}async cancelAuthOrgInvitation(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Pt,"POST",t)}async getAuthConfig(){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(St,"GET")}async createAuthOrganization(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(pt,"POST",t)}async updateAuthOrganization(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(ft,"POST",t)}async deleteAuthOrganization(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(wt,"POST",t)}async addAuthOrgMember(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ut,"POST",t)}async inviteAuthOrgMember(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ft,"POST",t)}async setAuthOrgMemberRole(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(bt,"POST",t)}async listAuthOrgTeams(t){this.adminHost.assertOpen();const s=e(It,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminHost.adminFetch(s,"GET")}async createAuthOrgTeam(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(gt,"POST",t)}async updateAuthOrgTeam(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Rt,"POST",t)}async removeAuthOrgTeam(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Gt,"POST",t)}async listAuthOrgTeamMembers(t){this.adminHost.assertOpen();const s=e(kt,{limit:t.limit,offset:t.offset,teamId:t.teamId});return await this.adminHost.adminFetch(s,"GET")}async addAuthOrgTeamMember(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ct,"POST",t)}async removeAuthOrgTeamMember(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Nt,"POST",t)}async listAuthOrgRoles(t){this.adminHost.assertOpen();const s=e(Mt,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminHost.adminFetch(s,"GET")}async createAuthOrgRole(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Lt,"POST",t)}async updateAuthOrgRole(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(vt,"POST",t)}async deleteAuthOrgRole(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Vt,"POST",t)}async listAuthSessions(t={}){this.adminHost.assertOpen();const s=e(Dt,{limit:t.limit,offset:t.offset,userId:t.userId});return await this.adminHost.adminFetch(s,"GET")}}const Ha=a=>"listAuthUsers"in a,_a=a=>{if(!Ha(a))throw new A("INTERNAL","The admin auth hooks need a LunoraAdminClient: construct the provider's client with `new LunoraAdminClient(...)` from `@lunora/client/admin`.");return a};export{ya as LunoraAdminClient,Ha as isLunoraAdminClient,_a as requireAdminAuthClient};
@@ -1 +1 @@
1
- import{L as k}from"./lunora-client-DbMT_z_l.mjs";import"./delta-merge-C6OqMEPH.mjs";import"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import"./createClientQuery-B8Nfj-7o.mjs";import"./client-tuning-C10B2KCO.mjs";import"./client-urls-BHLUjjcG.mjs";import"./TabCoordinator-DIySdaRV.mjs";import"./CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import"./httpStream-DN3D9WqW.mjs";import"./createLocalStore-WKNHD1ca.mjs";import"./offline-queue-HwrYARIL.mjs";import"./optimistic-layers-BI61YTO3.mjs";import"./OutboxDeclinedError-D6vF-WyL.mjs";import"./createInMemoryPersistence-C-IzNVbg.mjs";import"./createInMemoryQueryCache-DR6AorA2.mjs";import"./createReconnect-CjTmjJDH.mjs";import"./stream-idle-C7CsIT_m.mjs";import"./snapshot-precondition-BEtcSbWr.mjs";import"./DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";import"./SubscriptionRegistry-DjFfxba2.mjs";import"./wire-errors-BDckSTKZ.mjs";export{k as LunoraClient};
1
+ import{L as k}from"./lunora-client-DsPXE0O9.mjs";import"./delta-merge-C6OqMEPH.mjs";import"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import"./createClientQuery-B8Nfj-7o.mjs";import"./client-tuning-C10B2KCO.mjs";import"./client-urls-BHLUjjcG.mjs";import"./TabCoordinator-DIySdaRV.mjs";import"./CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import"./httpStream-DN3D9WqW.mjs";import"./createLocalStore-WKNHD1ca.mjs";import"./offline-queue-HwrYARIL.mjs";import"./optimistic-layers-BI61YTO3.mjs";import"./OutboxDeclinedError-D6vF-WyL.mjs";import"./createInMemoryPersistence-C-IzNVbg.mjs";import"./createInMemoryQueryCache-DR6AorA2.mjs";import"./createReconnect-CjTmjJDH.mjs";import"./stream-idle-C7CsIT_m.mjs";import"./snapshot-precondition-BEtcSbWr.mjs";import"./DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";import"./SubscriptionRegistry-DjFfxba2.mjs";import"./wire-errors-BDckSTKZ.mjs";export{k as LunoraClient};
@@ -1 +1 @@
1
- import{L as r}from"./lunora-client-DbMT_z_l.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{L as r}from"./lunora-client-DsPXE0O9.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};
@@ -0,0 +1 @@
1
+ import{LunoraError as m,OFFLINE_NOT_QUEUED_HINT as st}from"@lunora/errors";import{decodeWire as _,encodeWire as he,stableWireKey as ye}from"@lunora/wire";import{t as Be}from"./base64-849R7V-V.mjs";import{r as it,U as rt,P as nt}from"./delta-merge-C6OqMEPH.mjs";import ot from"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import{w as A,u as ue,s as We,a as at,i as q,r as z,e as K,b as Se,c as ct,d as ve,f as dt}from"./wire-errors-BDckSTKZ.mjs";import{ClientQueryStore as lt}from"./createClientQuery-B8Nfj-7o.mjs";import{D as ht,a as ut,b as ft,c as pt,d as mt,S as be,M as yt,I as St,Q as vt,R as bt,e as Ce,f as Ct,g as wt}from"./client-tuning-C10B2KCO.mjs";import{j as w,d as we,p as j,s as ge}from"./client-urls-BHLUjjcG.mjs";import{TabCoordinator as gt}from"./TabCoordinator-DIySdaRV.mjs";import{TransportError as F,getRetryAfterMs as Tt,AUTH_REPLAY_ERROR_CODES as kt,isAuthReplayFailure as $}from"./CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as Et,pumpSseBody as At}from"./httpStream-DN3D9WqW.mjs";import{createLocalStore as _t}from"./createLocalStore-WKNHD1ca.mjs";import{n as N,O as Rt,i as It}from"./offline-queue-HwrYARIL.mjs";import{d as Ot,b as oe,r as I,c as L,a as Lt,w as Pt,e as Ft,f as Mt}from"./optimistic-layers-BI61YTO3.mjs";import Ht from"./OutboxDeclinedError-D6vF-WyL.mjs";import{resolvePersistenceAdapter as Ut}from"./createInMemoryPersistence-C-IzNVbg.mjs";import{w as U,a as Te,b as Dt}from"./stream-idle-C7CsIT_m.mjs";import{resolveQueryCacheAdapter as Nt,queryCacheKey as H}from"./createInMemoryQueryCache-DR6AorA2.mjs";import{createReconnect as ke}from"./createReconnect-CjTmjJDH.mjs";import{fanSubscriptionError as fe,setSubscriptionAck as O,SubscriptionRegistry as g,wrapSubscriber as J,replaySubscriptionRefusal as Bt,failSubscription as B,releaseSubscribeFrame as Y}from"./SubscriptionRegistry-DjFfxba2.mjs";import{c as Wt,s as Ee,r as Qt}from"./snapshot-precondition-BEtcSbWr.mjs";import{createStream as xt}from"./DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";const Ae="/_lunora/rpc",X="/_lunora/rpc-batch",Z="/_lunora/ws",Wi="/_lunora/admin/shard-traffic",qt="/_lunora/admin/scheduled",Kt="/_lunora/admin/scheduled/status",jt="/_lunora/admin/scheduled/ws",$t="/_lunora/admin/scheduled/cancel",_e="/_lunora/admin/scheduled/dead",Vt="/_lunora/admin/scheduled/dead/retry",Gt="/_lunora/admin/scheduled/dead/cancel",Re="/_lunora/admin/scheduled/history",zt="/_lunora/admin/scheduled/job",Jt="/_lunora/admin/scheduled/cron-runs",Qe="/_lunora/admin/pause",Yt="/_lunora/admin/workflows/instances",Xt="/_lunora/admin/workflows/instance",Zt="/_lunora/admin/workflows/status",es="/_lunora/admin/workflows/create",ts="/_lunora/admin/workflows/event",Qi="/_lunora/admin/storage",xi="/_lunora/admin/storage/url",qi="/_lunora/admin/storage/buckets",Ki="/_lunora/admin/functions",ji="/_lunora/admin/cron-jobs",$i="/_lunora/admin/cron-jobs/run",Vi="/_lunora/admin/architecture",Gi="/_lunora/admin/openapi",zi="/_lunora/admin/openrpc",Ji="/_lunora/admin/global/tables",Yi="/_lunora/admin/global/table",Xi="/_lunora/admin/global/facet",Zi="/_lunora/admin/vector/indexes",er="/_lunora/admin/vector/query",tr="/_lunora/admin/logs/archive",sr="/_lunora/admin/kv/namespaces",ir="/_lunora/admin/tokens",rr="/_lunora/admin/kv/keys",nr="/_lunora/admin/kv/value",or="/_lunora/admin/auth/users",ar="/_lunora/admin/auth/sessions",cr="/_lunora/admin/auth/users/create",dr="/_lunora/admin/auth/users/role",lr="/_lunora/admin/auth/users/ban",hr="/_lunora/admin/auth/users/unban",ur="/_lunora/admin/auth/users/password",fr="/_lunora/admin/auth/users/remove",pr="/_lunora/admin/auth/users/impersonate",mr="/_lunora/admin/auth/sessions/revoke",yr="/_lunora/admin/auth/sessions/revoke-all",Sr="/_lunora/admin/auth/capabilities",vr="/_lunora/admin/auth/users/update",br="/_lunora/admin/auth/accounts",Cr="/_lunora/admin/auth/accounts/unlink",wr="/_lunora/admin/auth/passkeys",gr="/_lunora/admin/auth/passkeys/delete",Tr="/_lunora/admin/auth/api-keys",kr="/_lunora/admin/auth/api-keys/delete",Er="/_lunora/admin/auth/two-factor/disable",Ar="/_lunora/admin/auth/organizations",_r="/_lunora/admin/auth/organizations/members",Rr="/_lunora/admin/auth/organizations/invitations",Ir="/_lunora/admin/auth/organizations/members/remove",Or="/_lunora/admin/auth/organizations/invitations/cancel",Lr="/_lunora/admin/auth/config",Pr="/_lunora/admin/auth/sign-up-invitations",Fr="/_lunora/admin/auth/sign-up-invitations/create",Mr="/_lunora/admin/auth/sign-up-invitations/revoke",Hr="/_lunora/admin/auth/organizations/create",Ur="/_lunora/admin/auth/organizations/update",Dr="/_lunora/admin/auth/organizations/remove",Nr="/_lunora/admin/auth/organizations/members/add",Br="/_lunora/admin/auth/organizations/members/invite",Wr="/_lunora/admin/auth/organizations/members/role",Qr="/_lunora/admin/auth/organizations/teams",xr="/_lunora/admin/auth/organizations/teams/create",qr="/_lunora/admin/auth/organizations/teams/update",Kr="/_lunora/admin/auth/organizations/teams/remove",jr="/_lunora/admin/auth/organizations/teams/members",$r="/_lunora/admin/auth/organizations/teams/members/add",Vr="/_lunora/admin/auth/organizations/teams/members/remove",Gr="/_lunora/admin/auth/organizations/roles",zr="/_lunora/admin/auth/organizations/roles/create",Jr="/_lunora/admin/auth/organizations/roles/update",Yr="/_lunora/admin/auth/organizations/roles/remove",ss="/api/auth",is="/get-session",rs="lunora-ping",ee=500,xe=(n,e)=>{if(n.size<e)return;const t=n.keys().next().value;t!==void 0&&n.delete(t)};new TextDecoder;const ns=new TextEncoder,os=n=>Be(ns.encode(n)),as=n=>os(JSON.stringify(n)),cs="x-lunora-expect-subject",ds=n=>as({subject:n}),ls="refreshBatch",Ie=Symbol.for("lunora:session-change"),hs="lunora:session-change",us="better-auth.message",fs="signout",pe=()=>{const n=globalThis;let e=n[Ie];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},n[Ie]=e),e},ps=()=>"document"in globalThis,ms=async()=>{const n=[];for(const e of pe().listeners)try{n.push(e())}catch{}await Promise.allSettled(n)},ys=(n,e)=>{if(n!==us||e===null)return!1;try{const t=JSON.parse(e);return t?.event==="session"&&t.data?.trigger===fs}catch{return!1}},Ss=n=>{const e=[],t=()=>{ms().catch(()=>{})};let s;try{s=typeof BroadcastChannel=="function"?new BroadcastChannel(hs):void 0}catch{s=void 0}if(s!==void 0){const r=s;r.addEventListener("message",a=>{a.data?.type==="lunora:session-change"&&a.data.tab!==n&&t()}),e.push(()=>{r.close()})}const i=globalThis;if(typeof i.addEventListener=="function"){const r=a=>{ys(a.key,a.newValue)&&t()};i.addEventListener("storage",r),e.push(()=>{i.removeEventListener?.("storage",r)})}return()=>{for(const r of e)r()}},vs=n=>{const e=pe();return e.listeners.add(n),e.detach===void 0&&ps()&&(e.detach=Ss(e.tab)),()=>{e.listeners.delete(n),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},Oe=()=>pe().sourceDeclared===!0,Le="/_lunora/ws/reauth",bs=4005,Cs="identity_changed",ws="/_lunora/claims",gs="lunora",Ts="lunora.bearer.",ks=n=>`${Ts}${Be(new TextEncoder().encode(n))}`,Es=async n=>{const e=[];let t;for(;;){const s=await n(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}},qe=n=>({paused:n.paused===!0,...typeof n.pausedAt=="number"?{pausedAt:n.pausedAt}:{},...typeof n.reason=="string"?{reason:n.reason}:{},supported:n.supported===!0}),Q=n=>"args"in n?{...n,args:_(n.args)}:n,Xr=async n=>(n.assertOpen(),((await n.adminFetch(qt,"GET")).records??[]).map(t=>Q(t))),Zr=async(n,e)=>{n.assertOpen();const t=await n.adminFetch(`${zt}?id=${encodeURIComponent(e)}`,"GET");return t.record===void 0?null:Q(t.record)},en=async(n,e={})=>{n.assertOpen();const t=e.cursor===void 0?Re:`${Re}?cursor=${encodeURIComponent(e.cursor)}`,s=await n.adminFetch(t,"GET"),i=(s.records??[]).map(r=>Q(r));return s.truncated===!0&&s.cursor!==void 0?{cursor:s.cursor,records:i}:{records:i}},tn=async n=>{n.assertOpen();const e=await n.adminFetch(Jt,"GET");return{inFlight:e.inFlight??[],runs:e.runs??[]}},sn=async n=>(n.assertOpen(),qe(await n.adminFetch(Qe,"GET"))),rn=async(n,e,t)=>(n.assertOpen(),qe(await n.adminFetch(Qe,"POST",t===void 0?{paused:e}:{paused:e,reason:t}))),nn=async n=>{n.assertOpen();const e=await n.adminFetch(Kt,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},on=async(n,e)=>(n.assertOpen(),{cancelled:(await n.adminFetch($t,"POST",{id:e})).cancelled===!0}),an=async n=>(n.assertOpen(),(await Es(async t=>await n.adminFetch(t===void 0?_e:`${_e}?cursor=${encodeURIComponent(t)}`,"GET"))).map(t=>Q(t))),cn=async(n,e)=>(n.assertOpen(),{retried:(await n.adminFetch(Vt,"POST",{id:e})).retried===!0}),dn=async(n,e)=>(n.assertOpen(),{removed:(await n.adminFetch(Gt,"POST",{id:e})).removed===!0}),ln=async(n,e)=>{n.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 n.adminFetch(`${Yt}?${t.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}},hn=async(n,e)=>{n.assertOpen();const t=new URLSearchParams({id:e.id,name:e.name}),s=await n.adminFetch(`${Xt}?${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??[]}},un=async(n,e)=>{n.assertOpen();const t=await n.adminFetch(es,"POST",{id:e.id,name:e.name,params:e.params}),s=t.id??e.id;if(s===void 0)throw new m("WORKFLOWS_REST_ERROR","Workflows create response carried no instance id",{status:502});return{id:s,status:t.status??"unknown"}},fn=async(n,e)=>{n.assertOpen();const t=await n.adminFetch(ts,"POST",{id:e.id,name:e.name,payload:e.payload,type:e.type});return{instanceId:t.instanceId??e.id,timestamp:t.timestamp}},pn=async(n,e)=>(n.assertOpen(),{status:(await n.adminFetch(Zt,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),k=(n,e)=>{try{return he(n)}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)}},ae=n=>{try{return he(n),!0}catch{return!1}},Ke=n=>n!==null&&typeof n=="object"&&("error"in n||"result"in n),As=(n,e,t)=>{const s=Array.from({length:e}),i=r=>({error:A(We(r),t),ok:!1});for(const r of n){if(typeof r.id!="number"||r.id<0||r.id>=e)continue;if(!Ke(r.body)){s[r.id]=i({});continue}const a=r.body;if("error"in a){s[r.id]=i(a);continue}try{s[r.id]={ok:!0,value:_(a.result)}}catch(o){s[r.id]={error:A(ue(o),t),ok:!1}}}return s.map(r=>r??{error:A(new Error("batch call returned no result"),t),ok:!1})},te=(n,e)=>e!==null?{}:n===null?{expectSubject:null}:n?.startsWith("subj:")===!0?{expectSubject:n.slice(5)}:{},R=n=>n==="connected"||n==="polling",f=n=>n??"",E=(n,e)=>{if(!n.socket||n.wsState!=="open")return!1;try{return n.socket.send(JSON.stringify(e)),!0}catch{return!1}},_s=n=>{if(!n.pendingStreams||n.pendingStreams.length===0)return;const e=n.pendingStreams;n.pendingStreams=[];for(const t of e)E(n,t)},Rs=new TextDecoder,Is=n=>{if(typeof n=="string")return n;if(n instanceof ArrayBuffer)return Rs.decode(n)};class P{listeners=new Set;get size(){return this.listeners.size}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 D=n=>{n.heartbeatTimer!==void 0&&(clearInterval(n.heartbeatTimer),n.heartbeatTimer=void 0)},Os=(n,e,t)=>{D(n),!(e<=0)&&(n.heartbeatTimer=setInterval(()=>{if(!n.socket)return;const{socket:s}=n;if(Date.now()-n.lastFrameAt>e*2.5){try{s.close()}catch{}t();return}try{s.send(rs)}catch{}},e))},Pe=(n,e,t,s)=>{const{WebSocketImpl:i,connectTimeoutMs:r,heartbeatIntervalMs:a}=t;if(i===void 0)throw new m("INTERNAL","no WebSocket implementation available");const o=s.protocols===void 0?new i(e):new i(e,s.protocols);n.socket=o;const c=()=>{D(n),n.connectTimer!==void 0&&(clearTimeout(n.connectTimer),n.connectTimer=void 0),n.socket===o&&(n.socket=void 0)},d=l=>{c(),s.onClose(l)};r>0&&(n.connectTimer=setTimeout(()=>{if(n.connectTimer=void 0,n.socket===o){try{o.close()}catch{}d()}},r)),o.addEventListener("open",()=>{if(n.socket===o){n.connectTimer!==void 0&&(clearTimeout(n.connectTimer),n.connectTimer=void 0),n.lastFrameAt=Date.now();try{s.onOpen?.()}catch(l){console.error("[lunora] connection open handler threw",l)}n.socket===o&&Os(n,a,d)}}),o.addEventListener("message",l=>{if(n.socket===o){n.lastFrameAt=Date.now();try{s.onMessage(l)}catch(h){console.error("[lunora] server frame handler threw",h)}}}),o.addEventListener("close",l=>{n.socket===o&&d(l)}),o.addEventListener("error",()=>{n.socket===o&&d()})},Ls=n=>{const{afterFailedAttempts:e,intervalMs:t,onReachable:s,onStateChange:i,poll:r}=n,a=t>0&&e>0;let o=0,c,d=!1,l=!1;const h=()=>{c!==void 0&&(clearInterval(c),c=void 0,d=!1,i())},u=S=>{if(c!==void 0){if(!S){h();return}d||(d=!0,i()),s()}},p=()=>{l||(l=!0,r().then(u).finally(()=>{l=!1}).catch(()=>{}))};return{hasFailedOpen:()=>o>0,isPolling:()=>c!==void 0&&d,noteFailedOpen:()=>{o+=1,!(!a||c!==void 0||o<e)&&(c=setInterval(p,t),i(),p())},noteOpen:()=>{o=0,h()},stop:h}},Ps=1e4,Fe=async n=>U(Ps,void 0,n,()=>new TypeError("LunoraClient: poll timed out")),je=new Set(["DELIVERY_FENCED","RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Me=n=>{if(n instanceof F)return!0;const e=n?.code;return e===void 0||je.has(e)||kt.has(e)},Fs=1e3,$e=6e4,Ms={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},W=(n,e,t)=>{const s=at(t.get("retry-after")),i=s===void 0?void 0:{retryAfterMs:s},r=`LunoraClient: response carried no error envelope (status ${n.toString()}${e?` ${e}`:""})`,a=n<400||n>=500||n===408?new F(r,i):new m(Ms[n]??"BAD_REQUEST",r,{data:i});return A(a,t)},ce=(n,e=Math.random)=>{const t=Math.min(Fs*2**Math.max(n-1,0),$e);return Math.round(t*(.5+e()*.5))},Hs=n=>{const e=n?.code;return n instanceof F||e===void 0||je.has(e)},Us=(n,e,t)=>{const s=Tt(n);return s!==void 0&&s>0?Math.min(s,$e):Hs(n)?ce(e,t):void 0},Ds=983040,Ns=n=>typeof TextEncoder>"u"?n.length:new TextEncoder().encode(n).length,Bs=n=>{const e=new Map;for(const t of n)typeof t.id=="number"&&Ke(t.body)&&e.set(t.id,t.body);return e},Ws=(n,e)=>{if(n===void 0)return{kind:"unanswered"};if("error"in n)return{error:A(We(n),e),kind:"errored"};try{return{commitCursor:n.commitCursor,kind:"committed",value:_(n.result)}}catch(t){return{commitCursor:n.commitCursor,error:A(ue(t),e),kind:"undecodable"}}},se=(n,e)=>`${f(n)}\0${e}`,Qs=(n,e)=>{for(const t of e)t.op==="delete"?n.delete(t.key):t.value!==void 0&&n.set(t.key,t.value)};class xs{constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,t){xe(this.buffers,this.maxBuffers),this.buffers.set(se(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(se(e,t.pokeId));if(!s)return;const i=[];try{for(const o of t.rowsPatch)i.push(o.value===void 0?o:{...o,value:_(o.value)})}catch(o){s.undecodable.set(t.shapeId,o);return}const r=s.parts.get(t.shapeId)??[];for(const o of i)r.push(o);s.parts.set(t.shapeId,r),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=se(e,t),i=this.buffers.get(s);return i&&this.buffers.delete(s),i}clear(){this.buffers.clear()}}const qs=(n,e,t)=>{const s=e.parts.get(n.id)??[],i=e.resets.has(n.id),r=e.bases.get(n.id),a=e.epoch!==void 0&&n.serverEpoch!==void 0&&e.epoch!==n.serverEpoch,o=r!==void 0&&n.serverCursor!==void 0&&n.serverCursor!==r;if(!i&&(a||o))return n.rows.clear(),n.serverCursor=void 0,n.serverEpoch=void 0,n.answered=!1,"reseed";i&&n.rows.clear(),Qs(n.rows,s),n.answered=!0,t.checkpoint!==void 0&&(n.serverCursor=t.checkpoint),t.epoch!==void 0&&(n.serverEpoch=t.epoch);const c=e.lastMutationId.get(n.id);return c!==void 0&&(n.lastMutationId=c),"applied"},He=n=>{const e=[...n.rows.values()];for(const t of n.callbacks)try{t(e)}catch{}},Ks=(n,e)=>{for(const[t,s]of e.undecodable){const i=n.get(t);i&&fe(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape — ${s instanceof Error?s.message:String(s)}`})}},de=(n,e)=>{n.lastMutationId=Math.max(n.lastMutationId??0,e)},le=(n,e=!1)=>{const t=n.serverCursor,s=n.lastMutationId;Ot(()=>{for(const i of n.checkpointCallbacks)i({checkpoint:t,mutationId:s,...e&&{rowsFollow:!0}})})},Ve=(n,e,t)=>{n.serverBase=e,n.serverBaseCommitted=!0,n.awaitingSnapshot=!1,n.baseIncomplete=!1,n.serverClaims=t.claims,t.cursor!==void 0&&(n.serverCursor=t.cursor),t.epoch!==void 0&&(n.serverEpoch=t.epoch)},js=n=>n.awaitingSnapshot===!0?void 0:n.lastValue,$s=(n,e)=>e.cursor!==void 0&&n.serverCursor!==void 0&&(n.serverBase!==void 0||n.serverBaseCommitted===!0)&&e.epoch!==void 0&&e.epoch===n.serverEpoch&&e.cursor<n.serverCursor,Vs=n=>n.type==="delta"&&n.more===!0,V=(n,e)=>n!==void 0&&n!==e,Gs=(n,e)=>e==="connected"&&n!=="connected"||e==="polling"&&n!=="connected"&&n!=="polling",me=(n,e,t,s,i=!1)=>{if(t===void 0)return!i||n.ownClaims(e,s,"")===null;const r=n.ownClaims(e,s,t);return r!==void 0&&(r===null||r===t)},zs=n=>{for(const e of n.activeSubscriptions())O(e,"idle"),e.valueReceived=!1,n.ensureSocket(e.shardKey),n.queueResubscribe(e);for(const e of n.activeShapes())e.answered=!1,n.ensureSocket(e.shardKey);for(const e of n.queuedShardKeys())n.ensureSocket(e);n.broadcastStatus(n.computeStatus(),n.identityFingerprint()),n.emitConnectionStatus()},Js=n=>{n.closeConnections();const e=n.leader;e.status=void 0,e.wasEverConnected=!1;for(const t of n.activeSubscriptions())O(t,"idle"),t.valueReceived=!1;for(const t of n.activeShapes())t.answered=!1;n.emitConnectionStatus()},Ys=(n,e,t)=>{if(V(t,n.identityFingerprint()))return;const s=n.leader,i=Gs(s.status,e);s.status=e,e==="connected"&&(s.wasEverConnected=!0),n.emitConnectionStatus(),i&&(n.awaitLeaderAnswers(),n.flushOfflineQueues())},Xs=n=>{n.isLeader()&&n.broadcastStatus(n.computeStatus(),n.identityFingerprint())},Ge=(n,e,t,s,i,r,a)=>{if(V(r,n.identityFingerprint())||!me(n,e,a,()=>{Ge(n,e,t,s,i,r,a)},t!==void 0))return;const o=n.subscription(e);if(!o)return;n.dropCacheSeed(e);const c=!o.valueReceived;o.valueReceived=!0,Ve(o,t,s===void 0?{claims:a}:{claims:a,cursor:s,epoch:i}),o.refusal=void 0,s!==void 0&&oe(o,s),I(o,t),c&&n.emitConnectionStatus(),n.settleAwaitedAnswer(o,!0)},ze=(n,e,t,s,i)=>{if(V(s,n.identityFingerprint())||!me(n,`error:${e}`,i,()=>{ze(n,e,t,s,i)}))return;const r=n.subscription(e);if(r){const a=!r.valueReceived;r.valueReceived=!0,r.refusal=t,fe(r.errorCallbacks,t),a&&n.emitConnectionStatus(),n.settleAwaitedAnswer(r,!1)}},Je=(n,e,t,s,i,r,a,o)=>{if(V(a,n.identityFingerprint()))return;const c=n.subscription(e);c&&me(n,`settled:${e}`,o,()=>{Je(n,e,t,s,i,r,a,o)})&&(n.ackAndAdvanceCursor(c,t,s),i!==void 0&&r===n.clientIdentifier()&&de(c,i),le(c))},Zs=(n,e,t)=>n!==null||e&&t===null,ei=n=>n.sensitive===!0,ti=(n,e)=>{if(!ei(n))return e;if(e.onlineOnly===!1)throw new m("BAD_REQUEST",`'${n.__lunoraRef}' takes a sensitive argument and is always online-only; onlineOnly: false is not allowed`);return{...e,onlineOnly:!0}},ie="prov:",si=[nt,ls],ii=n=>n.type==="data"||n.type==="delta"||n.type==="settled"||n.type==="resume"||n.type==="error"&&typeof n.id=="string",ri=100,Ye=1e4,ni=5,oi=500,ai=1e3,Ue=3e4,De=1e4,ci=1e4,di=(n,e)=>{let t;const s=new Promise((r,a)=>{t=setTimeout(()=>{a(new Error("ws ticket mint timed out"))},e)}),i=(async()=>n())();return Promise.race([i,s]).finally(()=>{clearTimeout(t)})},li=(n,e)=>{const t=[n===void 0?"":`shard=${encodeURIComponent(n)}`,e===void 0?"":`token=${encodeURIComponent(e)}`].filter(Boolean).join("&");return t===""?Le:`${Le}?${t}`},re=async n=>typeof n=="function"?await n():n,ne=async(n,e,t,s)=>{const i=new AbortController,r=setTimeout(()=>{i.abort()},Ye);try{const a=await n(e,{body:t,credentials:"include",headers:s,method:"POST",signal:i.signal});return{status:a.status,text:await a.text()}}finally{clearTimeout(r)}},Ne=(n,e)=>new m("OFFLINE_NOT_QUEUED",`'${n}' is online-only and the connection is not live, so it was not queued`,{cause:e,hint:st}),hi=()=>new Error("LunoraClient: the connection is not live, so the durable replay was not sent; it stays queued"),ui=(n,e)=>n instanceof TypeError&&ae(e),fi=()=>globalThis.navigator?.onLine===!1,pi=(n,e,t,s)=>e||n===!0&&t&&!s,mi=Promise.resolve(),yi=async(n,e,t)=>{let s,i;const r=new AbortController,a=()=>{r.abort(e?.reason)};e?.addEventListener("abort",a,{once:!0});try{await At(n,{complete:o=>{e?.aborted!==!0&&(s=o)},fail:o=>{i=o},push:o=>{e?.aborted!==!0&&t?.(o)}},{},r)}finally{e?.removeEventListener("abort",a)}if(e?.aborted===!0)throw e.reason instanceof Error?e.reason:new DOMException("The operation was aborted.","AbortError");return{failure:i,terminal:s}};class Xe{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;wsTicket;wsCredentialGeneration=0;refusedCredentialGeneration;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;rpcTimeoutMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;ownClaimsValue;heldLeaderFrames=new Map;ownClaimsFetch;claimsVerifiedAgainst=new Set;ownClaimsRetryTimer;ownClaimsFailures=0;suspendedFollowerValues=new Map;frameClaims;authTokenOnUpgrade;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;mutationIssueCounter=0;identityRetirements=0;persistence;persistenceVersion;releasePageHideFlush;outboxLeaderRelease;queryCache;queryCacheEpoch=0;queryCacheChain=Promise.resolve();hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new g;pendingSubscriptionRetries=new Map;tabCoordinator;leader={status:void 0,wasEverConnected:!1};connections=new Map;idleClosedShards=new Set;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;tokenFingerprint;authSubject=void 0;subjectToken=null;sessionProbesInFlight=0;sessionProbeGeneration=0;identityQuestions=0;identityAnsweredAt=0;releaseSessionChangeListener;warnedIdentityDisagreement=!1;identityResolutionExpected=!1;identitySettled=!1;queuedIdentities=new Map;provisionalStamp=`${ie}${N()}`;retiredProvisionalStamps=new Set;provisionalStampQuestion=0;provisionalBinding;resolvesDeclaredSession=!1;declaredSessionFailures=0;declaredSessionRetryTimer;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new P;statusListeners=new P;roomFlushes=new Map;roomIdentityResets=new Set;tokenExpiredListeners=new P;identityChangeListeners=new P;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new P;pendingChangeListeners=new P;syncStatusListeners=new P;lastSyncStatus;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;supplementaryBounces=new Set;offlineFlushes=new Map;awaitingAnswer=new WeakSet;answeredUnreadable=new WeakSet;answerHeldShards=new Set;leaderAnswerTimers=new Map;replayRetryState=new Map;replayAttempts=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new xs(Xe.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??w(we(e.url),Z),this.wsToken=e.wsToken,this.wsTicket=e.wsTicket;const t=e.authBasePath??ss;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??ot(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??ht,this.connectTimeoutMs=e.connectTimeoutMs??ut,this.rpcTimeoutMs=e.rpcTimeoutMs??ft,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??pt,this.authTokenOnUpgrade=e.authTokenOnUpgrade??!1,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??mt,this.defaultConnectionContext=e.connectionContext,this.persistence=Ut(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Nt(e.queryCache),this.clientQueryStore=new lt,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=mi),this.offlineQueue=new Rt(e.offlineQueue,{onEvict:(s,i)=>{this.emitItemSettled(s,"rejected",i),this.releaseIdleShard(s.shardKey)},onReplayingChange:()=>{this.emitSyncStatus()},onSizeChange:s=>{this.pendingChangeListeners.emit(s),this.emitSyncStatus()},persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${N()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.installPageHideFlush(),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=vs(async()=>{this.retireProvisionalStamp(),!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}),this.statusListeners.add(s=>{this.resolvesDeclaredSession&&!this.identitySettled&&R(s)&&(this.declaredSessionFailures=0,this.resolveDeclaredSession())}))}setAuthToken(e,t){const s=this.authToken!==e;s&&this.resetOwnClaims();const i=this.identityFingerprint(),r=this.authSubject===void 0||this.subjectToken===this.authToken,a=this.subjectAwaitingReconfirm(),o=this.isKnownNobody(),c=this.authToken;this.authToken=e,s&&(this.tokenFingerprint=void 0),this.applySubject(e,t);const d=this.identityFingerprint();this.bindBearerProvisionalStamp(e,d);const l=!s&&e!==null&&r,h=!s&&e===null&&i===null&&r&&!o,u=d!==i;let p=!1;u&&(l?(this.restampQueuedIdentity(i,d),this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):h?(this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):p=this.retirePreviousIdentity(i,o,c,e)),p||this.applyUpgradeBearer(this.reconcileUpgradeBearer(c,e,u)),u&&this.restartTabCoordinatorForIdentity(),this.syncReadCacheToCredential(a),s&&this.authTokenListeners.emit(e),(d!==i||s||a)&&this.offlineQueue.size>0&&R(this.computeStatus())&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}writeIdentityStamp(){const e=this.identityFingerprint();return e===null&&this.provisionalBinding===void 0&&!this.identitySettled&&this.identityUnresolved()?this.provisionalStamp:e}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:this.stampedIdentity(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 i=s?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new m("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);const r=s?.shardKey??"",a=this.identityFingerprint();let o,c,d;try{c=await this.rpc(e,t,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:h=>{o=h}})}catch(h){if(!q(h))throw h;d=h}if(o!==void 0&&o>(this.clientWatermarks.get(a??"")?.get(r)??0)){let h=this.clientWatermarks.get(a??"");h===void 0&&(xe(this.clientWatermarks,wt),h=new Map,this.clientWatermarks.set(a??"",h)),h.set(r,o)}if(d!==void 0)throw d;return{applied:o===void 0||o===i,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,this.bindProvisionalStamp(this.identityFingerprint()),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,i=new AbortController;let r;const a=new Promise((o,c)=>{r=setTimeout(()=>{i.abort(),c(new Error(`session probe timed out after ${String(De)}ms`))},De)});try{const o=await Promise.race([this.fetchImpl(w(this.url,`${this.authBasePath}${is}`),{credentials:"include",headers:e,method:"GET",signal:i.signal}),a]);if(!o.ok)return this.identitySettled=!0,o.status===401&&this.adoptResolvedSubject(t,null,s),null;const d=(await Promise.race([o.json(),a]))?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(t,d,s),d}finally{clearTimeout(r),this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.applyWsCredentialChange())}setWsTicket(e){this.wsTicket!==e&&(this.wsTicket=e,this.applyWsCredentialChange())}setConnectionContext(e,t={}){this.assertLeaderOwnedSurface("setConnectionContext");const s=f(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=f(t.shardKey),i={context:e},r=this.connectionContextHolders.get(s);r?r.push(i):this.connectionContextHolders.set(s,[i]),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(i);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 i=f(s.shardKey);let r=this.whisperHandlers.get(i);r||(r=new Map,this.whisperHandlers.set(i,r));let a=r.get(e);const o=a===void 0;if(a||(a=new Set,r.set(e,a)),a.add(t),this.ensureSocket(s.shardKey),o){const c=this.getConnection(s.shardKey);c&&this.sendWhisperJoin(c,i,e)}return()=>{const c=this.whisperHandlers.get(i),d=c?.get(e);if(!d?.delete(t)||d.size>0)return;c?.delete(e),c?.size===0&&this.whisperHandlers.delete(i);const l=this.getConnection(s.shardKey);l&&E(l,{topic:e,type:"whisper_unsubscribe"}),this.releaseWhisperJoin(i,e),this.releaseIdleShard(s.shardKey)}}subscribeLiveTopic(e){const{onError:t,onEvent:s,shardKey:i,stream:r,topic:a}=e;if(a.length===0)throw new m("INTERNAL","LunoraClient: subscribeLiveTopic needs a non-empty topic");this.nextLiveSocketId+=1;const o=`ws-live-${String(this.nextLiveSocketId)}`,c=f(i),d=`/live/${r}/control`;let h=this.whisperSubscribe(a,()=>{},{shardKey:i});const u=()=>{const b=h;h=void 0,b?.()};let p=this.liveSocketGrants.get(c);p===void 0&&(p=new Map,this.liveSocketGrants.set(c,p)),p.set(o,{onError:t,onEvent:s,release:u,stream:r,topic:a});const S=this.getConnection(i)?.connectionId;S!==void 0&&this.grantWhenJoined(i,o,S);let y=!1;return()=>{if(y)return;y=!0;const b=this.liveSocketGrants.get(c),v=b?.delete(o)===!0;b?.size===0&&this.liveSocketGrants.delete(c);const C=this.getConnection(i)?.connectionId;v&&C!==void 0&&this.postLiveControl(d,i,{action:"unsubscribe",connectionId:C,stream:r,subscriptionId:o,topic:a}),u()}}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 i=`room:${e.name}`,r=this.whisperSubscribe(i,u=>{t.onMessage(u)},s);let a=!1;const o=[],c=()=>{o.length=0},d=()=>{for(;o.length>0&&this.roomSendsAdmitted(s.shardKey);){if(!this.sendEncodedWhisper(i,o[0],s))return;o.shift()}},l=f(s.shardKey),h=this.roomFlushes.get(l)??new Set;return h.add(d),this.roomFlushes.set(l,h),this.roomIdentityResets.add(c),{close:()=>{a=!0,o.length=0,h.delete(d),h.size===0&&this.roomFlushes.delete(l),this.roomIdentityResets.delete(c),r()},send:u=>{if(a||this.closed||this.WebSocketImpl===void 0)return!1;const p=k(u,`room message for '${i}'`),S=typeof structuredClone=="function"?structuredClone(p):JSON.parse(JSON.stringify(p));return d(),o.length===0&&this.roomSendsAdmitted(s.shardKey)&&this.sendEncodedWhisper(i,S,s)?!0:o.length>=ri?!1:(o.push(S),!0)}}}connectWebSocket(e,t,s={}){if(this.assertLeaderOwnedSurface("connectWebSocket"),this.WebSocketImpl===void 0||this.closed)return{close:()=>{},send:()=>{}};const i=o=>{try{o?.()}catch(c){console.error("[lunora] socket route handler threw",c)}};let r;const a=this.openSupplementarySocket(this.supplementaryUrl(e),{offerBearer:!0,onClose:()=>{clearTimeout(r),i(t.onClose)},onMessage:o=>{let c;try{c=JSON.parse(typeof o.data=="string"?o.data:"")}catch{return}c.type==="message"&&(a.resetBackoff(),i(()=>{t.onMessage(_(c.data))}))},onOpen:()=>{clearTimeout(r);const o=a.socket();r=setTimeout(()=>{a.socket()===o&&a.resetBackoff()},be),i(t.onOpen)},shardKey:s.shardKey});return{close:()=>{clearTimeout(r),a.close()},send:o=>{const c=JSON.stringify(k(o,`socket message for '${e}'`)),d=a.socket();if(d!==void 0)try{d.send(c)}catch{}}}}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){const t=this.statusListeners.add(e);return e(this.computeStatus()),t}syncStatus(){const e=this.computeStatus(),t=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader();let s=0;for(const r of this.subscriptions.all())(t||this.connectionGateState(r.shardKey).polling?r.valueReceived:r.ack==="acked")||(s+=1);for(const r of this.shapeSubscriptions.values())r.answered||(s+=1);const i=this.offlineQueue.size+this.offlineQueue.replaying;return{connection:e,pendingSubscriptions:s,pendingWrites:i,synced:R(e)&&s===0&&i===0}}onSyncStatus(e){const t=this.syncStatusListeners.add(e),s=this.syncStatus();return this.lastSyncStatus=s,e(s),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 r of s){const a=this.connections.get(r);e.push({confirmedMutationWatermark:t?.get(r)??0,hasSocket:a?.socket!==void 0,shardKey:r===""?void 0:r,wasEverConnected:a?.wasEverConnected??!1,wsState:a?.wsState??"idle"})}const i=this.subscriptions.all().map(r=>({acked:r.ack==="acked",functionPath:r.fn.__lunoraRef,id:r.id,kind:"query",lastMutationId:r.lastMutationId,pendingOptimisticLayers:r.optimisticLayers.length,serverCursor:r.serverCursor,shardKey:r.shardKey,subscriberCount:r.callbacks.size}));for(const r of this.shapeSubscriptions.values())i.push({acked:r.answered,functionPath:`shape:${r.name}`,id:r.id,kind:"shape",lastMutationId:r.lastMutationId,pendingOptimisticLayers:0,rowCount:r.rows.size,serverCursor:r.serverCursor,shardKey:r.shardKey,subscriberCount:r.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((r,a)=>(r.shardKey??"").localeCompare(a.shardKey??"")),subscriptions:i.toSorted((r,a)=>r.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(){const{WebSocketImpl:e}=this;if(e===void 0)return;const t=a=>a.protocol==="wss:"||a.protocol==="https:",s=j(this.wsUrl),i=a=>{const o=j(String(a));return o.host===s.host&&t(o)===t(s)},r=e;return new Proxy(e,{construct:(a,[o,c,...d])=>new r(o,c??(i(o)?this.upgradeProtocols():void 0),...d)})}isCrossTabFollower(){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()}expectsPush(e={}){const t=this.getConnection(e.shardKey);return t===void 0||t.wsState==="open"?!0:t.polling.isPolling()||!t.polling.hasFailedOpen()}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 Wt(this,e,t,s)}whenReady(e={}){return e.signal===void 0?this.readyPromise:Te(this.readyPromise,e.signal)}get isReady(){return this.readyResolved}peekHydratedQuery(e,t,s){return this.peekHydratedQueryByKey(e,ye(t),s)}peekHydratedQueryByKey(e,t,s){if(!this.readyResolved)return;const i=H(e,t,s),r=this.hydratedQueryCache.get(i);if(r!==void 0)return this.cachedQueryMatchesIdentity(r)?r.value:void 0}peekActiveQuerySnapshot(e,t,s){const i=g.key(e,t,s),r=this.subscriptions.get(i);return{answered:r!==void 0&&(r.lastValue!==void 0||r.ack==="acked"||r.valueReceived),present:r!==void 0,value:r?.lastValue}}async query(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0,signal:s.signal})}async batch(e){return U(this.rpcTimeoutMs,void 0,async t=>this.sendBatch(e,t))}async mutation(e,t,s={}){if(s.signal?.aborted)throw Dt(s.signal);const{value:i}=await Te(this.runMutation(e,t,s),s.signal);return i}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,signal:s.signal,unbounded:!0})}async importRows(e,t,s={}){this.assertOpen();const i=Math.max(1,Math.trunc(s.chunkSize??500)),r=s.toArgs??(l=>({rows:l})),a=t.length;let o=0,c=0,d=0;for(let l=0;l<a;l+=i){const h=t.slice(l,l+i),u=d,{committed:p}=await this.runMutation(e,r(h),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(u)}`},shardKey:s.shardKey});d+=1,o+=h.length,p&&(c+=h.length),s.onProgress?.({done:o,total:a})}return{chunks:d,imported:c,queued:o-c}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const t=this.openSupplementarySocket(w(we(this.url),jt),{onMessage:s=>{let i;try{i=JSON.parse(typeof s.data=="string"?s.data:"")}catch{return}i.type==="jobs"&&Array.isArray(i.records)&&(t.resetBackoff(),e(i.records.map(r=>Q(r))))}});return t.close}resnapshot(e,t,s={}){this.assertOpen();const i=this.subscriptions.get(g.key(e.__lunoraRef,t??{},s.shardKey));i!==void 0&&(this.cancelSubscriptionRetry(i.id),this.resnapshotSubscription(i)&&(i.awaitingSnapshot=!0))}subscribe(e,t,s,i={}){if(this.assertOpen(),i.signal?.aborted)return()=>{};const r=t??{},a=g.key(e.__lunoraRef,r,i.shardKey);let o=this.subscriptions.get(a);const c=J(s),d=J(i.onError),l=J(i.onCheckpoint);if(!o){this.nextSubId+=1;const y=`sub_${this.nextSubId.toString()}`,b=ye(r),v=this.takeHydratedCache(e.__lunoraRef,b,i.shardKey);o={ack:"idle",args:r,argsKey:b,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:y,lastValue:v?.value,optimisticLayers:[],serverBase:v?.value,serverCursor:v?.serverCursor,serverClaims:v?.claims,shardKey:i.shardKey,valueReceived:!1,wireArgs:k(r,`args for '${e.__lunoraRef}'`),...v?.serverEpoch===void 0?{}:{serverEpoch:v.serverEpoch}},this.subscriptions.add(o),this.emitSyncStatus(),this.isCrossTabFollower()&&R(this.computeStatus())&&this.awaitLeaderAnswer(o),v!==void 0&&this.cacheSeededQueries.set(a,v)}o.callbacks.add(c),d&&o.errorCallbacks.add(d),l&&o.checkpointCallbacks.add(l);const h=js(o);if(h!==void 0)try{c(h)}catch{}Bt(o,d),this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(o);const u=o;let p=!1;const S=()=>{if(!p&&(p=!0,i.signal?.removeEventListener("abort",S),u.callbacks.delete(c),d&&u.errorCallbacks.delete(d),l&&u.checkpointCallbacks.delete(l),u.callbacks.size===0)){this.sendOrQueueUnsubscribe(u.shardKey,u.id,"unsubscribe"),this.returnCacheSeed(g.keyOf(u)),this.subscriptions.remove(u),this.cancelSubscriptionRetry(u.id);const y=this.getConnection(u.shardKey);y&&this.settleSubscribeWatchdog(y,u.id),this.releaseIdleShard(u.shardKey),this.emitSyncStatus(),this.settleAwaitedAnswer(u,!0)}};return i.signal?.addEventListener("abort",S,{once:!0}),i.signal?.aborted&&S(),S}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 i=`shape_${this.nextShapeId.toString()}`,r={answered:!1,args:e.args,callbacks:new Set([t]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:i,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(i,r),this.emitSyncStatus(),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(r),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(r.shardKey,i,"shape_unsubscribe"),this.releaseIdleShard(r.shardKey),this.emitSyncStatus()}}stream(e,t,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new m("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;const i=`stream_${this.nextStreamId.toString()}`,{shardKey:r}=s,a=t??{},{handle:o,iterable:c}=xt({maxBuffer:s.maxBuffer,onCancel:()=>{this.cancelStream(i,r)}});this.ensureSocket(r);const d=this.getConnection(r),l={id:i,query:{args:k(a,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:r},type:"stream"},h={durable:s.durable===!0,generation:void 0,handle:o,lastSeq:0,message:l,shardKey:r};this.streams.set(i,h);const u=d?.wsState==="open"&&E(d,l);if(!u&&d===void 0)return this.forgetStream(i),o.fail(new m("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),c;if(!u){for(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=yt;){const S=d.pendingStreams.shift()?.id,y=S?this.streams.get(S):void 0;y&&(y.handle.fail(new m("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(S))}d.pendingStreams.push(l)}return c}httpStream(e,t,s={}){if(this.closed)throw new m("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new m("INTERNAL","LunoraClient: no `fetch` implementation available");const i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return Et(e,t,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:s.maxBuffer,signal:s.signal})}async streamRpc(e,t={},s={}){if(this.closed)throw new m("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new m("INTERNAL","LunoraClient: no `fetch` implementation available");const i=e.__lunoraRef,r=await this.fetchImpl(w(this.url,Ae),{body:JSON.stringify({args:k(t,`args for '${i}'`),functionPath:i,shardKey:s.shardKey}),headers:{accept:"text/event-stream",...this.rpcRequestHeaders({},s.shardKey)},method:"POST",...s.signal?{signal:s.signal}:{}});if(!r.ok){const l=await r.json().catch(()=>{});if(l?.error)throw z(l.error);const h=r.statusText?` ${r.statusText}`:"";throw new m("INTERNAL",`LunoraClient: request failed (status ${r.status.toString()}${h})`)}if(!r.body)throw new m("HTTP_STREAM_NO_BODY","LunoraClient: streaming response has no body");const{failure:a,terminal:o}=await yi(r.body,s.signal,s.onFrame);if(a!==void 0)throw a;if(o===void 0)throw new m("HTTP_STREAM_INTERRUPTED","LunoraClient: stream ended without a complete frame");let c;try{c=JSON.parse(o)}catch{throw new m("HTTP_STREAM_BAD_CHUNK","LunoraClient: streaming result is not valid JSON")}if(typeof c!="object"||c===null||!("result"in c))throw new m("HTTP_STREAM_INTERRUPTED","LunoraClient: stream ended without a result");return _(c.result)}close(){this.closed=!0;for(const e of this.pendingSubscriptionRetries.values())clearTimeout(e);this.pendingSubscriptionRetries.clear();for(const e of this.whisperJoins.keys())this.dropWhisperJoinWaiters(e);this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.releasePageHideFlush?.(),this.releasePageHideFlush=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const e of this.streams.values())e.handle.fail(new m("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(),this.supplementaryBounces.clear();for(const e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear(),this.stopOwnClaimsRetry(),clearTimeout(this.declaredSessionRetryTimer),this.declaredSessionRetryTimer=void 0,this.suspendedFollowerValues.clear();for(const e of this.leaderAnswerTimers.values())clearTimeout(e);this.leaderAnswerTimers.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.syncStatusListeners.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}retirePreviousIdentity(e,t,s,i){const r=Zs(e,t,i);return r&&this.discardOptimisticLayers(),this.rejectQueuedForIdentityChange(e),this.warnRefreshWithoutSubject(s,i),r?(this.evictPreviousIdentitySession(),!0):!1}reconcileUpgradeBearer(e,t,s){return!this.authTokenOnUpgrade||t===null||e===t?"none":s?e===null?"cold":"none":e===null?"none":"warm"}upgradeProtocols(){return this.authTokenOnUpgrade&&this.authToken?[gs,ks(this.authToken)]:void 0}applyUpgradeBearer(e){e==="cold"?(this.resetRoomSends(),this.reconnectCold()):e==="warm"&&this.bounceShardSockets(!0)}assertOpen(){if(this.closed)throw new m("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 m("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),clearTimeout(e.revalidateTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0,e.revalidateTimer=void 0}shardInUse(e){const t=s=>f(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=f(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())},St))}forgetStream(e){const t=this.streams.get(e);this.streams.delete(e),t&&this.releaseIdleShard(t.shardKey)}teardownConnection(e){e.polling.stop();const t=f(e.shardKey);for(const[i,r]of this.streams)f(r.shardKey)===t&&(r.handle.fail(new m("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(i));e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e),this.clearConnectionTimers(e),clearTimeout(e.idleTimer),e.idleTimer=void 0,D(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={activeShapes:()=>[...this.shapeSubscriptions.values()],activeSubscriptions:()=>this.subscriptions.all(),awaitLeaderAnswers:()=>{this.awaitLeaderAnswers()},broadcastStatus:(s,i)=>this.tabCoordinator?.broadcastConnectionStatus(s,i),closeConnections:()=>{for(const[s,i]of this.connections)this.teardownConnection(i),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,ownClaims:(s,i,r)=>this.followerClaims(s,i,r),queueResubscribe:s=>{this.queueResubscribe(s)},queuedShardKeys:()=>this.queuedOfflineShardKeys,clientIdentifier:()=>this.clientId,dropCacheSeed:s=>{this.dropCacheSeed(s)},ackAndAdvanceCursor:(s,i,r)=>{this.ackAndAdvanceCursor(s,i,r)},settleAwaitedAnswer:(s,i)=>{this.settleAwaitedAnswer(s,i)},subscription:s=>this.subscriptions.get(s)};return new gt({channelName:e,onBecomeLeader:()=>{zs(t)},onStopBeingLeader:()=>{Js(t)},onConnectionStatus:(s,i)=>{Ys(t,s,i)},onSubscriptionData:(s,i,r,a,o,c)=>{Ge(t,s,i,r,a,o,c)},onLeaderClaimAnswered:()=>{Xs(t)},onSubscriptionError:(s,i,r,a)=>{ze(t,s,i,r,a)},onSubscriptionSettled:(s,i,r,a,o,c,d)=>{Je(t,s,i,r,a,o,c,d)}})}async sendBatch(e,t){if(this.assertOpen(),!this.fetchImpl)throw new m("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];const s=await this.fetchImpl(w(this.url,X),{body:JSON.stringify({calls:e.map((o,c)=>({args:k(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}),i=s.headers.get("x-d1-bookmark");i&&this.bookmark.set(i);let r;try{r=await s.json()}catch{throw A(new m("INTERNAL",`LunoraClient: batch response was not JSON (status ${s.status.toString()})`),s.headers)}const a=K(r);if(!s.ok||a!==void 0&&!r.results)throw a!==void 0?A(z(a),s.headers):A(new m("INTERNAL",`LunoraClient: batch request failed (status ${s.status.toString()})`),s.headers);for(const o of r.results??[]){const c=o.body?.commitCursor;typeof o.id=="number"&&typeof c=="number"&&this.recordShardCursor(e[o.id]?.shardKey,c)}return As(r.results??[],e.length,s.headers)}async runMutation(e,t,s){this.assertOpen();const i=ti(e,s),r=t,a=i.mutationId??N();this.mutationIssueCounter+=1;const o=this.mutationIssueCounter,c=this.takeReplayCredential(i.replayCredential),d=this.composedBaselineFor(i.replayBaseline,i.shardKey);this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i);const l=this.identityRetirements,{confirms:h,rollbacks:u}=this.applyOptimisticUpdates(e.__lunoraRef,r,i.shardKey,i.optimistic);this.applyOptionalOptimisticUpdate(i.optimisticUpdate,t,i.shardKey,u,h,()=>this.identityRetirements===l);const p=i.onlineOnly?void 0:this.offlineFlushes.get(f(i.shardKey));p!==void 0&&await p;const{httpFirst:S,midReconnect:y,shouldQueueOffline:b,socketDown:v}=this.writeQueueGate(i.shardKey),C=!i.onlineOnly&&b&&i.replayBaseline===void 0&&this.hasPendingWriteAhead(i.shardKey),x=async(T=!1)=>this.enqueueOfflineMutation(e,r,i.shardKey,d,a,u,h,T?void 0:i.precondition,i.mutationId,c?.stamp,T,o);if(this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i,u),i.replayBaseline!==void 0&&(v||y)&&(L(u),this.refuseDurableReplayNotSent(v,i.shardKey)),v||y||C)return x();let G;try{const T=await this.rpc(e.__lunoraRef,r,i.shardKey,{baselineSeq:d,captureBookmark:!0,clientId:i.replayClientId,...c?.flags,mutationId:a,onCommitCursor:M=>{G=M}});for(const M of h)M(G);return{committed:!0,value:T}}catch(T){const M=ui(T,r),Ze=S&&b&&M,et=this.ownSocketOpen(i.shardKey);if(b&&!i.onlineOnly&&this.fetchImpl!==void 0&&!this.outbox&&i.replayBaseline===void 0&&(T instanceof TypeError||T instanceof F)&&ae(r)){const tt=x(!0);return this.noteHeldRetryDelay(i.shardKey),this.scheduleRateLimitedRetry(i.shardKey),tt}throw this.settleFailedDirectWrite(T,G,h,u,c?.flags.authToken),pi(i.onlineOnly,Ze,M,et)?Ne(e.__lunoraRef,T):T}}refuseOnlineOnlyWhenDown(e,t,s=[]){if(!t.onlineOnly)return;const i=this.writeQueueGate(t.shardKey);if(i.socketDown||i.midReconnect)throw L(s),Ne(e)}ownSocketOpen(e){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()?!1:this.writeQueueGate(e).socketOpen}writeQueueGate(e){const{hasSocket:t,idleClosed:s,polling:i,wasEverConnected:r,wsState:a}=this.connectionGateState(e),{queueBeforeFirstConnect:o}=this.offlineQueue,c=r||o,d=this.WebSocketImpl!==void 0&&c,l=i||s;return{httpFirst:l,midReconnect:a==="connecting"&&c&&!l,shouldQueueOffline:d,socketDown:a!=="open"&&!t&&d&&!l,socketOpen:a==="open"}}settleFailedDirectWrite(e,t,s,i,r){if(this.noteIdentityMismatch(e),r!==void 0&&this.noteReplayAuthRefusal(e,r),q(e)){for(const a of s)a(t);return}L(i)}async delegateToOutbox(e,t,s,i,r,a,o,c){this.outboxMutationCounter+=1;const d=this.outboxMutationCounter;try{await e.enqueue({args:s,baselineSeq:r,clientId:this.clientId,functionPath:t,idempotencyKey:o??`${this.clientId}:${N()}`,identity:c,mutationId:d,...a.length>0&&{onRejected:()=>{L(a)}},shardKey:i})}catch(l){if(l instanceof Ht)return!1;throw L(a),l instanceof Error?l:new Error(String(l))}return!0}async enqueueOfflineMutation(e,t,s,i,r,a,o,c,d,l,h,u){const p=l===void 0?this.writeIdentityStamp():l;if(this.outbox&&await this.delegateToOutbox(this.outbox,e.__lunoraRef,t,s,i,a,d,p)){for(const y of o)y(void 0);return{committed:!1,value:void 0}}if(this.closed)throw L(a),new m("CLIENT_CLOSED","LunoraClient closed");return{committed:!0,value:await new Promise((y,b)=>{const v={ambiguousSend:h,args:t,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:r,issueSeq:u,clientId:this.clientId,identity:p,precondition:this.holdWhileUnanswered(c),onCommit:C=>{for(const x of o)x(C)},reject:C=>{this.queuedIdentities.delete(r),q(C)||L(a),b(C instanceof Error?C:new Error(String(C))),this.releaseIdleShard(s)},resolve:y,shardKey:s};this.offlineQueue.enqueue(v),this.queuedOfflineShardKeys.add(s),this.ensureSocket(s),v.id!==void 0&&this.queuedIdentities.set(v.id,p),this.outbox!==void 0&&!h&&R(this.computeStatus())&&this.flushOfflineQueue(s).catch(()=>{})})}}hasPendingWriteAhead(e){const t=f(e);return(this.outbox?.pending?.()??!1)||this.offlineQueue.hasPending(s=>f(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=this.queryCacheEpoch,t=await this.queryCache.load();if(e!==this.queryCacheEpoch)return;const s=new Map;for(const i of this.subscriptions.all())s.set(H(i.fn.__lunoraRef,i.argsKey,i.shardKey),i);for(const{key:i,...r}of t){if(It(this.persistenceVersion,r.version)){this.queryCache.remove(i).catch(()=>{});continue}const a=s.get(i);if(a&&this.cachedQueryMatchesIdentity(r)){this.seedSubscriptionFromCache(a,r);continue}this.hydratedQueryCache.set(i,r)}}catch{}}seedSubscriptionFromCache(e,t){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(t)||(e.serverBase=t.value,e.serverCursor=t.serverCursor,e.serverClaims=t.claims,t.serverEpoch!==void 0&&(e.serverEpoch=t.serverEpoch),this.cacheSeededQueries.set(H(e.fn.__lunoraRef,e.argsKey,e.shardKey),t),I(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.serverBaseCommitted=!1,s.serverCursor=void 0,s.serverEpoch=void 0,I(s,void 0)),this.hydratedQueryCache.set(e,t)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,t,s){const i=H(e,t,s),r=this.hydratedQueryCache.get(i);if(!(r===void 0||!this.cachedQueryMatchesIdentity(r)))return this.hydratedQueryCache.delete(i),r}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(const e of this.subscriptions.all()){const t=H(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=H(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,r=i===void 0?this.identityFingerprint():i;r===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(s,{identity:r,serverCursor:e.serverCursor,ts:Date.now(),value:t,...e.serverClaims===void 0?{}:{claims:e.serverClaims},...r===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(()=>{})},vt))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;const{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}const t=[...this.pendingCacheWrites.entries()],{queryCacheEpoch:s}=this;this.pendingCacheWrites.clear();const i=this.queryCacheChain.then(async()=>s===this.queryCacheEpoch?Promise.allSettled(t.map(async([r,a])=>e.put(r,a))):void 0);this.queryCacheChain=i.catch(()=>{}),await i}installPageHideFlush(){const e=globalThis;if(!this.persistence&&!this.queryCache||!("document"in globalThis)||typeof e.addEventListener!="function")return;const t=()=>{this.offlineQueue.flushUnpersisted(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.flushQueryCacheWrites().catch(()=>{}))},s=()=>{e.document?.visibilityState==="hidden"&&t()};e.addEventListener("pagehide",t),e.document?.addEventListener("visibilitychange",s),this.releasePageHideFlush=()=>{e.removeEventListener?.("pagehide",t),e.document?.removeEventListener("visibilitychange",s)}}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=f(e);let s;for(const i of this.subscriptions.all())f(i.shardKey)!==t||i.serverCursor===void 0||(s=s===void 0?i.serverCursor:Math.max(s,i.serverCursor));return s}composedBaselineFor(e,t){return e===void 0?this.baselineCursorFor(t):e??void 0}async pollSubscriptions(e){const t=f(e),s=[];for(const o of this.subscriptions.all())f(o.shardKey)===t&&(ae(o.args)?s.push(o):(this.markQueryRejected(o,!0),o.refusal={code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"},B(o,o.refusal)));if(s.length===0)return this.probeOrigin();const i=Mt(),r=this.identityFingerprint();let a;try{a=await Fe(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()!==r)return!0;for(const[o,c]of s.entries()){const d=a[o];if(d!==void 0){if(!d.ok){this.markQueryRejected(c,!0),c.refusal={code:d.error.code,message:d.error.message},B(c,c.refusal);continue}this.handleDataMessage({data:he(d.value),id:c.id,type:"data"},i)}}return!0}async probeOrigin(){const{fetchImpl:e}=this;if(!e)return!1;try{return await Fe(async t=>e(w(this.url,X),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:t})),!0}catch{return!1}}emitSyncStatus(){if(this.syncStatusListeners.size===0)return;const e=this.syncStatus(),t=this.lastSyncStatus;t?.connection===e.connection&&t.pendingSubscriptions===e.pendingSubscriptions&&t.pendingWrites===e.pendingWrites&&t.synced===e.synced||(this.lastSyncStatus=e,this.syncStatusListeners.emit(e))}emitConnectionStatus(){const e=this.computeStatus();this.emitSyncStatus(),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,i){const r=[],a=[];if(!i)return{confirms:r,rollbacks:a};const o=g.key(e,t,s),c=this.subscriptions.get(o);if(c){const d=Lt(c,i);d&&(r.push(d.confirm),a.push(d.rollback))}return{confirms:r,rollbacks:a}}applyOptionalOptimisticUpdate(e,t,s,i,r,a){e&&this.applyOptimisticUpdate(e,t,s,i,r,a)}applyOptimisticUpdate(e,t,s,i,r,a){const{confirms:o,rollbacks:c,store:d}=_t(this.subscriptions,s,a);try{e(d,t)}catch{L(c);return}i.push(...c),r.push(...o)}getConnection(e){return this.connections.get(f(e))}sendOrQueueUnsubscribe(e,t,s){const i=this.getConnection(e);i&&!E(i,{id:t,type:s})&&i.pendingUnsubscribes.push({id:t,type:s})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let i="idle";return this.leader.status==="connected"?i="open":this.leader.status==="connecting"&&(i="connecting"),{hasSocket:!1,idleClosed:!1,polling:this.leader.status==="polling",wasEverConnected:this.leader.wasEverConnected,wsState:i}}const t=this.getConnection(e),s=t===void 0&&this.idleClosedShards.has(f(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=f(e);let s=this.connections.get(t);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:Ls({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:()=>{this.flushOfflineQueue(e).catch(()=>{})},onStateChange:()=>{this.emitConnectionStatus()},poll:async()=>this.pollSubscriptions(e)}),reconnect:ke(this.reconnectOptions),reconnectTimer:void 0,resubscribeQueue:[],resubscribeSlots:new Set,shardKey:e,socket:void 0,stableTimer:void 0,unackedWatchdogs:new Map,wasEverConnected:this.idleClosedShards.delete(t),wsState:"idle"},this.connections.set(t,s)),s}openSupplementarySocket(e,t){if(this.WebSocketImpl===void 0||this.closed)return{close:()=>{},resetBackoff:()=>{},socket:()=>{}};const s=ke(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let r,a=!1;const o=()=>{a||this.closed||(r=setTimeout(u,s.next()))},c=y=>{a||this.WebSocketImpl===void 0||Pe(i,this.wsUrlFor(t.shardKey,y,e),this.managedSocketOptions,{onClose:b=>{b?.code===4001&&this.notifyTokenExpired(),o(),t.onClose?.()},onMessage:t.onMessage,...t.onOpen===void 0?{}:{onOpen:t.onOpen},...t.offerBearer===!0?{protocols:this.upgradeProtocols()}:{}})};let d=0,l;const h=async y=>{const b=this.wsCredentialGeneration;d+=1;const v=d;let C;l=b;try{C=await di(y,ci)}catch{v===d&&(l=void 0,o());return}if(v===d){if(l=void 0,b!==this.wsCredentialGeneration){u();return}c(C)}},u=()=>{if(a||this.WebSocketImpl===void 0)return;const{wsTicket:y}=this;if(typeof y=="function"){h(y).catch(()=>{});return}c(y)};u();const p=()=>{a=!0,r!==void 0&&(clearTimeout(r),r=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),D(i);const{socket:y}=i;i.socket=void 0;try{y?.close()}catch{}};this.adminSocketTeardowns.add(p);const S=()=>{const{socket:y}=i;if(y===void 0){l!==void 0&&l!==this.wsCredentialGeneration&&(d+=1,l=void 0,u());return}i.socket=void 0,i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),D(i);try{y.close()}catch{}t.onClose?.(),o()};return this.supplementaryBounces.add(S),{close:()=>{p(),this.adminSocketTeardowns.delete(p),this.supplementaryBounces.delete(S)},resetBackoff:()=>{s.reset()},socket:()=>i.socket}}supplementaryUrl(e){const t=j(this.wsUrl),s=t.pathname.endsWith(Z)?t.pathname.slice(0,-Z.length):t.pathname;return t.pathname=w(s,e),ge(t,this.wsUrl)}wsUrlFor(e,t,s=this.wsUrl){const i=j(s);if(e===void 0&&t===void 0&&!i.searchParams.has("token"))return s;const r=new Set([...e===void 0?[]:["shard"],"token"]),a=[...i.searchParams].filter(([o])=>!r.has(o)).map(([o,c])=>`${encodeURIComponent(o)}=${encodeURIComponent(c)}`);return e!==void 0&&a.push(`shard=${encodeURIComponent(e)}`),t!==void 0&&a.push(`token=${encodeURIComponent(t)}`),i.search=a.join("&"),ge(i,s)}rpcRequestHeaders(e,t){const s={"content-type":"application/json"};e.expectSubject!==void 0&&(s[cs]=ds(e.expectSubject));const i=this.shardCursors.get(this.cursorKeyFor(t));i!==void 0&&(s["x-lunora-min-seq"]=i.toString());const r=e.authToken===void 0?this.authToken:e.authToken;if(r&&(s.authorization=`Bearer ${r}`),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,i={}){const{fetchImpl:r}=this;if(!r)throw new F("LunoraClient: no `fetch` implementation available");const a=this.rpcRequestHeaders(i,s),o=i.authToken===void 0?this.authToken:i.authToken,c=JSON.stringify({args:k(t,`args for '${e}'`),functionPath:e,shardKey:s}),{body:d,response:l}=await U(i.unbounded?0:this.rpcTimeoutMs,i.signal,async p=>{const S=await r(w(this.url,Ae),{body:c,headers:a,method:"POST",signal:p});try{return{body:await S.json(),response:S}}catch{return{body:void 0,response:S}}});if(i.captureBookmark){const p=l.headers.get("x-d1-bookmark");p&&this.bookmark.set(p)}if(d===void 0)throw W(l.status,l.statusText,l.headers);const h=d;if(typeof h!="object"||h===null||Array.isArray(h))throw W(l.status,l.statusText,l.headers);const u=K(d);if(u!==void 0)throw Se(u,l.headers);if(!l.ok)throw W(l.status,l.statusText,l.headers);i.onMutationAck?.(d.lastMutationId),i.onCommitCursor?.(d.commitCursor),this.noteCredentialAccepted(o),this.learnDefaultShardKey(l,s),this.recordShardCursor(s,d.commitCursor);try{return _(d.result)}catch(p){throw A(ue(p),l.headers)}}async adminFetch(e,t,s,i){if(!this.fetchImpl)throw new m("INTERNAL","LunoraClient: no `fetch` implementation available");const r={};this.authToken&&(r.authorization=`Bearer ${this.authToken}`);const a=s instanceof ArrayBuffer||s instanceof Blob;let o;s===void 0?o=void 0:a?(o=s,i!==void 0&&(r["content-type"]=i)):(o=JSON.stringify(s),r["content-type"]="application/json");const c=await this.fetchImpl(w(this.url,e),{body:o,headers:r,method:t});let d;try{d=await c.json()}catch{const h=c.statusText?` ${c.statusText}`:"";throw new m("INTERNAL",`LunoraClient: response was not JSON (status ${c.status.toString()}${h})`)}const l=K(d);if(l!==void 0)throw z({...l,message:l.message??"admin request failed"});if(!c.ok){const h=c.statusText?` ${c.statusText}`:"";throw new m("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(f(e.shardKey));E(e,{caps:si,clientId:this.clientId,id:"connect",type:"connect",...t===void 0?{}:{context:t},...e.sessionToken===void 0?{}:{token:e.sessionToken}})}resendShapeSubscriptions(e){for(const t of this.shapeSubscriptions.values())f(t.shardKey)===f(e)&&this.sendShapeSubscribeIfOpen(t)}refuseDurableReplayNotSent(e,t){throw e&&this.ensureSocket(t),hi()}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const t=this.getOrCreateConnection(e);t.wsState==="open"||t.wsState==="connecting"||(t.wsState="connecting",this.emitConnectionStatus(),this.startShardSocket(t,e).catch(()=>{this.handleDisconnect(t)}))}applyWsCredentialChange(){this.wsCredentialGeneration+=1,this.resetRoomSends(),this.bounceShardSockets()}async startShardSocket(e,t){const{wsToken:s,wsTicket:i}=this;if(typeof s=="function"||typeof i=="function"){await this.openSocketWithProvidedCredentials(e,t);return}this.openSocket(e,t,{session:s,ticket:i})}async openSocketWithProvidedCredentials(e,t){const s=this.wsCredentialGeneration,i=Symbol("ws-token-attempt");let r;e.providerAttempt=i;try{r=await U(this.connectTimeoutMs,void 0,async()=>({session:await re(this.wsToken),ticket:await re(this.wsTicket)}),()=>new Error("LunoraClient: ws credential provider timed out"))}catch{e.providerAttempt===i&&(e.providerAttempt=void 0,this.handleDisconnect(e));return}if(e.providerAttempt===i&&(e.providerAttempt=void 0,!(this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0))){if(s!==this.wsCredentialGeneration){await this.startShardSocket(e,t);return}this.openSocket(e,t,r)}}openSocket(e,t,s){if(this.WebSocketImpl===void 0)return;e.providerAttempt=void 0,e.identity=this.identityFingerprint(),e.ticketed=s.ticket!==void 0,e.upgradeBearer=this.authTokenOnUpgrade?this.authToken??void 0:void 0,s.ticket===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.sessionToken=s.session,e.retired=!1;const i=this.wsCredentialGeneration;Pe(e,this.wsUrlFor(t,s.ticket),this.managedSocketOptions,{onClose:r=>{r?.code===4003&&e.polling.noteFailedOpen(),r?.code===bs&&r.reason===Cs?e.retired!==!0&&!this.closed&&this.retireChangedClaims():r?.code===4001?this.notifyTokenExpired():r?.code===4003&&r.reason!=="connect deadline"&&i===this.wsCredentialGeneration&&this.refusedCredentialGeneration!==i&&(this.refusedCredentialGeneration=i,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.reauthPending=!1,e.claims=void 0,e.heldFrames=void 0,e.roomsRejoined=!1,clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},be),this.sendConnectEnvelope(e),this.markShardPendingAck(t,!0),this.emitConnectionStatus(),this.clearResubscribeQueue(e);for(const o of this.subscriptions.all())f(o.shardKey)===f(t)&&this.queueResubscribe(o);if(this.resendShapeSubscriptions(t),e.pendingUnsubscribes.length>0){const o=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(const{id:c,type:d}of o)E(e,{id:c,type:d});this.releaseIdleShard(t)}_s(e);const r=f(t),a=this.whisperHandlers.get(r);if(this.dropWhisperJoinWaiters(r),this.whisperJoins.set(r,new Map),a)for(const o of a.keys())this.sendWhisperJoin(e,r,o);e.roomsRejoined=!0,this.releaseRoomSends(t),this.flushOfflineQueue(t).catch(()=>{})},protocols:this.upgradeProtocols()})}cancelStream(e,t){const s=this.getConnection(t);s&&(s.pendingStreams=s.pendingStreams?.filter(i=>i.id!==e),E(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(),D(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",e.connectionId=void 0,e.heldFrames=void 0,e.whisperAck=void 0,this.dropWhisperJoinWaiters(f(e.shardKey)),this.markShardPendingAck(e.shardKey),this.emitConnectionStatus(),this.clearResubscribeQueue(e);const t=new Set((e.pendingStreams??[]).map(i=>i.id));for(const[i,r]of this.streams)if(!(f(r.shardKey)!==f(e.shardKey)||t.has(i))){if(r.durable){const a={...r.message,...r.generation===void 0?{}:{generation:r.generation},sinceChunk:r.lastSeq};r.message=a,e.pendingStreams=[...(e.pendingStreams??[]).filter(o=>o.id!==i),a];continue}r.handle.fail(new m("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.forgetStream(i)}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,t=!1){const s=f(e);for(const i of this.subscriptions.all())f(i.shardKey)===s&&(this.cancelSubscriptionRetry(i.id),O(i,"idle"),i.pendingDeltaRun=void 0,t&&(i.valueReceived=!1,this.awaitingAnswer.add(i),this.answeredUnreadable.delete(i)));for(const i of this.shapeSubscriptions.values())f(i.shardKey)===s&&(i.answered=!1)}queueResubscribe(e){const t=this.getConnection(e.shardKey);t&&(t.resubscribeQueue.push(e),this.drainResubscribeQueue(t))}drainResubscribeQueue(e){for(;e.resubscribeSlots.size<bt;){const t=e.resubscribeQueue.shift();if(!t)return;this.subscriptions.getById(t.id)&&this.sendSubscribeIfOpen(t)&&e.resubscribeSlots.add(t.id)}}settleSubscribeWatchdog(e,t){clearTimeout(e.unackedWatchdogs.get(t)),e.unackedWatchdogs.delete(t),e.resubscribeSlots.delete(t)&&this.drainResubscribeQueue(e)}clearResubscribeQueue(e){for(const t of e.unackedWatchdogs.values())clearTimeout(t);e.unackedWatchdogs.clear(),e.resubscribeSlots.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e,t=!1){const s=this.getConnection(e.shardKey);if(s?.wsState!=="open"||e.ack==="acked"||!t&&e.ack==="inflight")return!1;const i=e.serverCursor!==void 0&&e.serverBase!==void 0,r=E(s,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...i?{sinceSeq:e.serverCursor}:{},...i&&e.serverClaims!==void 0?{sinceClaims:e.serverClaims}:{},...i&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"});return r&&O(e,"inflight"),r&&!t&&this.armUnackedWatchdog(s,e),r}armUnackedWatchdog(e,t,s=!1){clearTimeout(e.unackedWatchdogs.get(t.id)),e.unackedWatchdogs.set(t.id,setTimeout(()=>{if(s){e.unackedWatchdogs.delete(t.id),Y(t),this.settleAwaitedAnswer(t,!1);return}const i=t.ack!=="acked"&&this.subscriptions.getById(t.id)===t&&this.sendSubscribeIfOpen(t,!0);this.settleSubscribeWatchdog(e,t.id),i?this.armUnackedWatchdog(e,t,!0):Y(t)},Ce))}sendShapeSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);t?.wsState==="open"&&E(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.serverCursor===void 0||e.serverClaims===void 0?{}:{sinceClaims:e.serverClaims},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,t){const s=Is(e);if(s===void 0)return;let i;try{i=JSON.parse(s)}catch{return}const r=this.getConnection(t);if(i.type!=="error"&&r?.reconnect.reset(),r&&typeof i.id=="string"&&this.settleSubscribeWatchdog(r,i.id),i.type==="batchStart")r&&(r.heldFrames=[]);else if(i.type==="batchEnd"){const a=r?.heldFrames;if(r&&a){const{socket:o}=r;r.heldFrames=void 0,Pt(()=>{for(const c of a){if(r.retired===!0||r.socket!==o)break;this.dispatchServerMessage(c,t)}},()=>!this.closed)}}else r?.heldFrames&&ii(i)?r.heldFrames.push(i):this.dispatchServerMessage(i,t)}dispatchServerMessage(e,t){switch(e.type){case"ack":{const s=this.subscriptions.getById(e.id);s&&this.ackAndAdvanceCursor(s,void 0,void 0);return}case"chunk":{const{data:s,generation:i,id:r,seq:a}=e,o=this.streams.get(r);o&&typeof a=="number"&&(o.lastSeq=a,typeof i=="number"&&(o.generation=i),o.durable=!0),o?.handle.push(_(s));return}case"complete":{this.handleCompleteMessage(e.id);return}case"data":case"delta":{this.withFrameClaims(t,()=>{this.handleDataMessage(e)});return}case"error":{this.handleErrorMessage(e,t);break}case"identity":{this.handleIdentityFrame(e,t),this.adoptSocketConnectionId(e,t),this.confirmShardIdentity(t);break}case"live":{this.dispatchLive(e,t);break}case"pokeEnd":{this.withFrameClaims(t,()=>{this.handlePokeEnd(e,t)});break}case"pokePart":{this.pokeAssembler.part(t,e);break}case"pokeStart":{this.pokeAssembler.start(t,e);break}case"resume":{this.withFrameClaims(t,()=>{this.handleResumeMessage(e)});break}case"settled":{this.handleSettledMessage(e);break}case"whisper":{this.dispatchWhisper(e,t);break}case"whisper_subscribed":{this.acknowledgeWhisperJoin(f(t),e.topic);break}}}handleErrorMessage(e,t){const s=e.error?.code;if(s==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}if(s==="STREAM_ID_IN_USE")return;const{id:i}=e,r=i===void 0?void 0:this.streams.get(i);if(r&&i!==void 0){r.handle.fail(ct(e)),this.forgetStream(i);return}const a=i===void 0?void 0:this.subscriptions.getById(i);if(a){Y(a);const c=ve(e),d=this.identityFingerprint(),l=g.keyOf(a),h=this.getConnection(t)?.claims;this.markQueryRejected(a),a.refusal=c,this.scheduleSubscriptionRetry(a,e.error?.retryAfterMs),B(a,c),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(l,c,d,h);return}const o=i===void 0?void 0:this.shapeSubscriptions.get(i);o&&(o.answered||(o.answered=!0,this.emitSyncStatus()),fe(o.errorCallbacks,ve(e)))}markQueryRejected(e,t=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()||this.connectionGateState(e.shardKey).polling){this.settleAwaitedAnswer(e,!1),!(t?e.valueReceived:e.ack==="acked")&&(t?e.valueReceived=!0:O(e,"acked"),this.emitSyncStatus())}handlePokeEnd(e,t){const s=this.pokeAssembler.end(t,e.pokeId);if(s){Ks(this.shapeSubscriptions,s);for(const i of s.parts.keys()){const r=this.shapeSubscriptions.get(i);r&&!s.undecodable.has(i)&&this.applyPokePart(r,s,e)}}}applyPokePart(e,t,s){const i=e.answered,r=qs(e,t,s);if(e.answered!==i&&this.emitSyncStatus(),He(e),r==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.serverClaims=this.frameClaims,e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){return O(e,"idle"),e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,this.emitSyncStatus(),this.sendSubscribeIfOpen(e)}scheduleSubscriptionRetry(e,t){if(this.cancelSubscriptionRetry(e.id),this.closed||typeof t!="number"||!Number.isFinite(t)||t<0)return;const s=setTimeout(()=>{this.pendingSubscriptionRetries.delete(e.id),!this.closed&&this.subscriptions.getById(e.id)===e&&this.resnapshotSubscription(e)&&(e.awaitingSnapshot=!0)},t);this.pendingSubscriptionRetries.set(e.id,s)}cancelSubscriptionRetry(e){const t=this.pendingSubscriptionRetries.get(e);t!==void 0&&(clearTimeout(t),this.pendingSubscriptionRetries.delete(e))}resnapshotDiscardedRun(e){const{serverCursor:t,serverEpoch:s}=e;e.baseIncomplete=!0,this.resnapshotSubscription(e)&&(e.awaitingSnapshot=!0),e.serverCursor=t,e.serverEpoch=s}failUndecodableFrame(e,t,s){B(e,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription — ${t instanceof Error?t.message:String(t)}`}),s&&this.subscriptions.getById(e.id)===e&&this.resnapshotDiscardedRun(e),this.settleAwaitedAnswer(e,!1)}handleDataMessage(e,t){const{id:s}=e,i=s?this.subscriptions.getById(s):void 0;if(!i||e.type==="data"&&$s(i,e)||e.type==="delta"&&i.baseIncomplete===!0)return;this.cancelSubscriptionRetry(i.id);let r;const a=i.pendingDeltaRun;try{r=it(e,a===void 0?i.serverBase:a.payload)}catch(c){i.pendingDeltaRun=void 0,this.failUndecodableFrame(i,c,e.type==="delta");return}if(r===rt){console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.resnapshotSubscription(i);return}if(Vs(e)){i.pendingDeltaRun={payload:r};return}i.pendingDeltaRun=void 0,this.dropCacheSeed(g.keyOf(i));const o=t!==void 0&&!i.valueReceived;if(Ve(i,r,{claims:this.frameClaims,cursor:e.cursor,epoch:e.epoch}),i.refusal=void 0,o&&(i.valueReceived=!0,this.emitSyncStatus()),e.lastMutationId!==void 0&&(de(i,e.lastMutationId),le(i,!0)),this.persistQueryValue(i),oe(i,i.serverCursor),t!==void 0&&Ft(i,t),I(i,r),this.tabCoordinator?.isLeader()){const c=g.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(c,r,i.serverCursor,i.serverEpoch,this.identityFingerprint(),i.serverClaims)}this.settleAwaitedAnswer(i,!0)}followerClaims(e,t,s){if(this.identityFingerprint()===null&&!this.identityUnresolved())return null;if(s==="")return(this.ownClaimsValue===void 0||this.ownClaimsValue!==null&&!this.claimsVerifiedAgainst.has(""))&&(this.claimsVerifiedAgainst.add(""),this.heldLeaderFrames.set(e,t),this.fetchOwnClaims()),this.ownClaimsValue;if(this.ownClaimsValue===void 0)this.heldLeaderFrames.set(e,t),this.fetchOwnClaims();else if(s!==void 0&&s!==this.ownClaimsValue&&!this.claimsVerifiedAgainst.has(s)){this.claimsVerifiedAgainst.add(s),this.heldLeaderFrames.set(e,t),this.fetchOwnClaims();return}return this.ownClaimsValue}isFollowerTab(){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()}resetOwnClaims(){this.ownClaimsValue=void 0,this.ownClaimsFetch=void 0,this.claimsVerifiedAgainst.clear(),this.stopOwnClaimsRetry(),this.suspendFollowerValues(),this.heldLeaderFrames.size>0&&queueMicrotask(()=>{this.fetchOwnClaims()})}suspendFollowerValues(){if(this.isFollowerTab())for(const e of this.subscriptions.all())e.serverClaims!==void 0&&e.serverBase!==void 0&&this.suspendedFollowerValues.set(e,{base:e.serverBase,claims:e.serverClaims,cursor:e.serverCursor,epoch:e.serverEpoch}),e.serverClaims!==void 0&&(e.serverBase=void 0,e.serverBaseCommitted=!1,e.serverCursor=void 0,e.serverClaims=void 0,I(e,void 0))}applyOwnClaims(e){e!==this.ownClaimsValue&&this.claimsVerifiedAgainst.clear(),this.ownClaimsValue=e,this.ownClaimsFailures=0;for(const[t,s]of this.suspendedFollowerValues)s.claims===e&&t.serverBase===void 0&&(t.serverBase=s.base,t.serverCursor=s.cursor,t.serverEpoch=s.epoch,t.serverClaims=e,I(t,s.base));this.suspendedFollowerValues.clear();for(const t of this.subscriptions.all())t.serverClaims!==void 0&&t.serverClaims!==e&&(t.serverBase=void 0,t.serverBaseCommitted=!1,t.serverCursor=void 0,t.serverClaims=void 0,I(t,void 0));this.dropClaimedEntries(e),this.releaseHeldFrames()}releaseHeldFrames(){const e=[...this.heldLeaderFrames.values()];this.heldLeaderFrames.clear();for(const t of e)t()}dropClaimedEntries(e){for(const t of[this.hydratedQueryCache,this.cacheSeededQueries])for(const[s,i]of t)if(i.claims!==void 0&&i.claims!==e){t.delete(s),this.pendingCacheWrites.delete(s);const{queryCache:r}=this;r&&(this.queryCacheChain=this.queryCacheChain.then(async()=>r.remove(s)).catch(()=>{}))}}fetchOwnClaims(){const{authToken:e,fetchImpl:t}=this;if(t===void 0||this.ownClaimsFetch!==void 0)return;const s=ne(t,w(this.url,ws),"{}",e===null||!this.authTokenOnUpgrade?{"content-type":"application/json"}:{authorization:`Bearer ${e}`,"content-type":"application/json"}).then(({status:i,text:r})=>{const{claims:a}=JSON.parse(r);this.ownClaimsFetch===s&&(typeof a=="string"?this.applyOwnClaims(a):i===200&&(this.ownClaimsValue=null,this.releaseHeldFrames()))}).catch(()=>{this.ownClaimsFetch===s&&this.scheduleOwnClaimsRetry()}).finally(()=>{this.ownClaimsFetch===s&&(this.ownClaimsFetch=void 0)});this.ownClaimsFetch=s}scheduleOwnClaimsRetry(){if(this.closed||this.heldLeaderFrames.size===0||this.ownClaimsRetryTimer!==void 0||this.ownClaimsFailures>=ni)return;const e=oi*2**this.ownClaimsFailures;this.ownClaimsFailures+=1,this.ownClaimsRetryTimer=setTimeout(()=>{this.ownClaimsRetryTimer=void 0,this.fetchOwnClaims()},e)}stopOwnClaimsRetry(){clearTimeout(this.ownClaimsRetryTimer),this.ownClaimsRetryTimer=void 0,this.ownClaimsFailures=0}withFrameClaims(e,t){this.frameClaims=this.getConnection(e)?.claims;try{t()}finally{this.frameClaims=void 0}}handleResumeMessage(e){const t=this.subscriptions.getById(e.id);t&&(t.pendingDeltaRun=void 0,t.awaitingSnapshot=!1,t.baseIncomplete=!1,t.serverClaims=this.frameClaims,this.ackAndAdvanceCursor(t,e.cursor,e.epoch),this.tabCoordinator?.isLeader()&&t.serverBase!==void 0&&this.tabCoordinator.broadcastSubscriptionData(g.keyOf(t),t.serverBase,t.serverCursor,t.serverEpoch,this.identityFingerprint(),t.serverClaims),this.settleAwaitedAnswer(t,!0))}handleSettledMessage(e){const t=this.subscriptions.getById(e.id);if(!t)return;const s=t.pendingDeltaRun!==void 0;if(s&&(t.pendingDeltaRun=void 0,this.resnapshotDiscardedRun(t)),!(s||t.baseIncomplete===!0)&&(this.ackAndAdvanceCursor(t,e.cursor,e.epoch),e.lastMutationId!==void 0&&de(t,e.lastMutationId),le(t),this.tabCoordinator?.isLeader())){const i=g.keyOf(t);this.tabCoordinator.broadcastSubscriptionSettled(i,t.serverCursor,t.serverEpoch,t.lastMutationId,this.clientId,this.identityFingerprint(),t.serverClaims)}}ackAndAdvanceCursor(e,t,s){this.cancelSubscriptionRetry(e.id);const i=e.ack!=="acked";O(e,"acked"),i&&this.emitSyncStatus(),(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),oe(e,e.serverCursor)&&I(e,e.serverBase))}adoptSocketConnectionId(e,t){const s=this.getConnection(t);if(s===void 0||typeof e.connectionId!="string")return;const i=s.connectionId===e.connectionId;s.connectionId=e.connectionId,s.claims=e.claims,s.whisperAck=e.whisperAck===!0,(!i||s.revalidateTimer===void 0&&s.reauthPending!==!0)&&this.armSocketRevalidation(s,e.revalidateMs);for(const r of this.liveSocketGrants.get(f(t))?.keys()??[])this.grantWhenJoined(t,r,e.connectionId)}grantWhenJoined(e,t,s){const i=f(e),r=this.liveSocketGrants.get(i)?.get(t);if(r===void 0)return;const{stream:a,topic:o}=r,c=()=>{this.liveSocketGrants.get(i)?.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},l=>{this.refuseLiveGrant(e,t,l,s)})};this.getConnection(e)?.whisperAck===!0?this.whenWhisperJoined(i,o,c):c()}sendWhisperJoin(e,t,s){const i=this.whisperJoinState(t,s);i.pending+=1,i.joined=!1,E(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 i of s.waiters.splice(0))clearTimeout(i.timer),i.run();this.releaseWhisperJoin(e,t)}}releaseWhisperJoin(e,t){if(this.whisperHandlers.get(e)?.has(t)===!0)return;const s=this.whisperJoins.get(e),i=s?.get(t);if(!(s===void 0||i===void 0||i.pending>0)){for(const r of i.waiters.splice(0))clearTimeout(r.timer);s.delete(t),s.size===0&&this.whisperJoins.delete(e)}}whenWhisperJoined(e,t,s){const i=this.whisperJoinState(e,t);if(i.joined){s();return}const r={run:s,timer:void 0};r.timer=setTimeout(()=>{i.waiters=i.waiters.filter(a=>a!==r),s()},Ye),i.waiters.push(r)}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 i=s.get(t);return i===void 0&&(i={joined:!1,pending:0,waiters:[]},s.set(t,i)),i}refuseLiveGrant(e,t,s,i){const r=f(e),a=this.liveSocketGrants.get(r),o=a?.get(t);a===void 0||o===void 0||this.getConnection(e)?.connectionId!==i||(a.delete(t),a.size===0&&this.liveSocketGrants.delete(r),o.release(),o.onError?.({status:s,topic:o.topic}))}postLiveControl(e,t,s,i){const{fetchImpl:r}=this;if(!r)return;const a=JSON.stringify(t===void 0?s:{...s,shardKey:t}),o=this.rpcRequestHeaders({},t);this.liveControlChain=this.liveControlChain.then(()=>ne(r,w(this.url,e),a,o)).then(({status:c})=>{c>=400&&c<500&&c!==404&&c!==401&&i?.(c)}).catch(()=>{})}dispatchLive(e,t){const s=this.liveSocketGrants.get(f(t));if(!s)return;const i=_(e.data);for(const r of s.values())if(!(r.stream!==e.stream||r.topic!==e.topic))try{r.onEvent(i)}catch{}}dispatchWhisper(e,t){const s=this.whisperHandlers.get(f(t))?.get(e.topic);if(!s)return;const i=_(e.data);for(const r of s)try{r(i,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&&(O(s,"idle"),this.emitSyncStatus(),B(s,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&(this.replayAttempts.delete(e),this.offlineQueue.discard(e))}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const e=this.authToken;return e===null?null:(this.tokenFingerprint?.token!==e&&(this.tokenFingerprint={hash:this.hashToken(e),token:e}),this.tokenFingerprint.hash)}hashToken(e){let t=2166136261,s=5381;for(let i=0;i<e.length;i+=1){const r=e.charCodeAt(i);t^=r,t=Math.imul(t,16777619),s=Math.imul(s,33)+r}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()||e.claims!==void 0&&e.claims!==this.ownClaimsValue&&(this.ownClaimsValue!==void 0||this.isFollowerTab())?!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}bindProvisionalStamp(e){this.provisionalBinding??={identity:e}}bindBearerProvisionalStamp(e,t){e!==null&&t!==null&&this.bindProvisionalStamp(t)}retireProvisionalStamp(){this.provisionalBinding===void 0&&(this.retiredProvisionalStamps.add(this.provisionalStamp),this.provisionalStamp=`${ie}${N()}`,this.provisionalStampQuestion=this.identityQuestions)}resolveDeclaredSession(){this.closed||this.sessionProbesInFlight>0||(this.resolvesDeclaredSession=!0,this.askDeclaredSession().catch(()=>{}))}async askDeclaredSession(){await this.getCurrentUser().catch(()=>{}),this.retryDeclaredSession()}retryDeclaredSession(){if(this.closed||this.identitySettled||this.declaredSessionRetryTimer!==void 0||!R(this.computeStatus()))return;const e=Math.min(ai*2**this.declaredSessionFailures,Ue);e<Ue&&(this.declaredSessionFailures+=1),this.declaredSessionRetryTimer=setTimeout(()=>{this.declaredSessionRetryTimer=void 0,this.identitySettled||this.resolveDeclaredSession()},e)}stampedIdentity(e){return e===this.provisionalStamp?this.provisionalBinding===void 0?null:this.provisionalBinding.identity:e?.startsWith(ie)===!0?null:e}releaseSessionProbe(){this.sessionProbesInFlight-=1,!(this.identityUnresolved()||this.identityFingerprint()!==null)&&!this.closed&&this.offlineQueue.size>0&&R(this.computeStatus())&&this.flushAllOfflineQueues()}identityUnresolved(){return this.sessionProbesInFlight>0?!0:(!this.identityResolutionExpected&&!this.identitySettled&&Oe()&&this.resolveDeclaredSession(),(this.identityResolutionExpected||Oe())&&!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){if(this.closed||this.authToken!==null||t<this.identityAnsweredAt)return!1;const s=this.provisionalBinding===void 0;return this.identityAnsweredAt=t,this.identitySettled=!0,t>this.provisionalStampQuestion&&this.bindProvisionalStamp(e===null?null:`subj:${e}`),this.setAuthToken(null,e),s&&e===null&&this.offlineQueue.size>0&&R(this.computeStatus())&&this.flushAllOfflineQueues(),!0}sendEncodedWhisper(e,t,s){this.ensureSocket(s.shardKey);const i=this.getConnection(s.shardKey),r=i!==void 0&&E(i,{data:t,topic:e,type:"whisper"});return this.releaseIdleShard(s.shardKey),r}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(f(e))??[])t()}confirmShardIdentity(e){const t=this.getConnection(e);t!==void 0&&(t.identityConfirmed=!0,t.polling.noteOpen()),this.releaseRoomSends(e)}handleIdentityFrame(e,t){const s=this.getConnection(t)?.identityQuestion,{subject:i}=e;s===void 0||i!==null&&typeof i!="string"||this.adoptCookieSubject(i,s)||!this.closed&&this.authToken===null&&(i===null?null:`subj:${i}`)!==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 i of t){if(this.identityVerdict(this.stampOf(i))!=="mismatch"){s.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);const r=new Error("offline mutation discarded: auth identity changed before replay");r.code="OFFLINE_IDENTITY_CHANGED",i.reject(r),this.emitItemSettled(i,"rejected",r)}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,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(s,t);this.provisionalBinding?.identity===e&&(this.provisionalBinding={identity:t}),this.offlineQueue.restampIdentity(e,t)}restampWatermarks(e,t){const s=e??"",i=this.clientWatermarks.get(s);if(i===void 0)return;this.clientWatermarks.delete(s);const r=t??"",a=this.clientWatermarks.get(r);if(a===void 0)this.clientWatermarks.set(r,i);else for(const[o,c]of i)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.queryCacheEpoch+=1;const{queryCache:e}=this;e&&(this.queryCacheChain=this.queryCacheChain.then(async()=>e.clear()).catch(()=>{}))}discardOptimisticLayers(){this.identityRetirements+=1;for(const e of this.subscriptions.all())e.optimisticLayers=[],e.retirements=(e.retirements??0)+1}evictPreviousIdentitySession(){this.resetOwnClaims(),this.resetRoomSends(),this.revokeCacheSeededValues(),this.reconnectCold(),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()}reconnectCold(){for(const e of this.subscriptions.all())e.serverBase=void 0,e.serverBaseCommitted=!1,e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,O(e,"idle"),e.valueReceived=!1,I(e,void 0);for(const e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,e.answered=!1,He(e);this.emitSyncStatus(),this.bounceShardSockets()}bounceShardSockets(e=!1){const{authToken:t,fetchImpl:s}=this;for(const i of this.connections.values()){const{connectionId:r}=i;e&&t!==null&&s!==void 0&&i.socket!==void 0&&r!==void 0&&i.retired!==!0?this.reauthenticateShardSocket(i,r,t):this.bounceShardSocket(i)}for(const i of this.supplementaryBounces)i()}retireChangedClaims(){if(this.clearQueryCacheForIdentityChange(),this.evictPreviousIdentitySession(),this.tabCoordinator?.isLeader())for(const e of this.subscriptions.all())this.tabCoordinator.broadcastSubscriptionData(g.keyOf(e),void 0,void 0,void 0,this.identityFingerprint())}reauthenticateShardSocket(e,t,s){const{authToken:i,fetchImpl:r}=this,{socket:a}=e;if(r===void 0)return;const o=(e.reauthAttempt??0)+1;clearTimeout(e.revalidateTimer),e.revalidateTimer=void 0,e.reauthAttempt=o,e.reauthPending=!0,(e.ticketed===!0?U(this.connectTimeoutMs,void 0,async()=>re(this.wsTicket),()=>new Error("LunoraClient: ws ticket provider timed out")).catch(()=>{}):Promise.resolve(void 0)).then(async c=>ne(r,w(this.url,li(e.shardKey,c)),JSON.stringify({connectionId:t}),s===null?{"content-type":"application/json"}:{authorization:`Bearer ${s}`,"content-type":"application/json"})).then(({text:c})=>{const d=JSON.parse(c);return d?.ok===!0?"ok":d?.error?.code==="IDENTITY_CHANGED"?"changed":"refused"}).catch(()=>"refused").then(c=>{e.reauthAttempt===o&&(e.reauthPending=!1,!(this.closed||s!==null&&this.authToken!==i||e.connectionId!==t||e.socket!==a||e.retired===!0)&&(c==="ok"?(e.upgradeBearer=s??e.upgradeBearer,this.armSocketRevalidation(e,e.revalidateMs)):c==="changed"?this.retireChangedClaims():this.bounceShardSocket(e)))}).catch(()=>{})}armSocketRevalidation(e,t){clearTimeout(e.revalidateTimer),e.revalidateTimer=void 0,e.revalidateMs=typeof t=="number"&&t>0?t:void 0,e.revalidateMs!==void 0&&(e.revalidateTimer=setTimeout(()=>{e.revalidateTimer=void 0;const s=e.upgradeBearer??(e.sessionToken===void 0?null:this.authToken??void 0);s!==void 0&&e.connectionId!==void 0&&e.socket!==void 0&&e.retired!==!0&&this.reauthenticateShardSocket(e,e.connectionId,s)},e.revalidateMs/2))}bounceShardSocket(e){if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}else e.providerAttempt!==void 0&&this.startShardSocket(e,e.shardKey).catch(()=>{this.handleDisconnect(e)})}flushAllOfflineQueues(){for(const e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){const t=f(e),s=this.offlineFlushes.get(t);if(s===void 0&&this.offlineQueue.size===0)return;const i=(async()=>{await(s??Promise.resolve());const{authToken:r}=this;try{await this.drainOfflineQueue(e,r)}catch{}!this.closed&&this.authToken!==r&&this.offlineQueue.size>0&&R(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(t,i),await i,this.offlineFlushes.get(t)===i&&(this.offlineFlushes.delete(t),this.releaseIdleShard(e))}snapshotAnswer(e){const t=Ee(e),s=t&&this.subscriptions.get(g.key(t.functionPath,t.args,t.shardKey));if(s!==void 0)return this.awaitingAnswer.has(s)?"awaiting":this.answeredUnreadable.has(s)?"unreadable":void 0}holdWhileUnanswered(e){const t=Ee(e);if(e===void 0||t===void 0)return e;const s=()=>this.snapshotAnswer(e)!==void 0||e();return Qt(s,t),s}awaitLeaderAnswers(){for(const e of this.subscriptions.all())this.awaitLeaderAnswer(e)}awaitLeaderAnswer(e){this.awaitingAnswer.add(e),this.answeredUnreadable.delete(e),clearTimeout(this.leaderAnswerTimers.get(e)),this.leaderAnswerTimers.set(e,setTimeout(()=>{this.leaderAnswerTimers.delete(e),this.isCrossTabFollower()&&this.settleAwaitedAnswer(e,!1)},2*Ce))}settleAwaitedAnswer(e,t){clearTimeout(this.leaderAnswerTimers.get(e)),this.leaderAnswerTimers.delete(e),t&&this.answeredUnreadable.delete(e),this.awaitingAnswer.delete(e)&&(t||this.answeredUnreadable.add(e),this.answerHeldShards.delete(f(e.shardKey))&&this.flushOfflineQueue(e.shardKey).catch(()=>{}))}holdUndecidedWrites(e,t){const s=t.findIndex(i=>this.snapshotAnswer(i.precondition)==="awaiting");return s===-1?t:(this.offlineQueue.requeue(t.slice(s)),this.answerHeldShards.add(e),t.slice(0,s))}async drainOfflineQueue(e,t){const s=this.offlineQueue.drainConflict();for(const l of s){this.unpersist(l.id),this.queuedIdentities.delete(l.id??"");const h=new Error("offline mutation skipped: precondition failed before replay");h.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(l,"rejected",h)}const i=f(e),r=this.holdUndecidedWrites(i,this.offlineQueue.drain(l=>f(l.shardKey)===i));if(r.length===0)return;const a=[],o=[];for(const l of r){const h=this.replayGateVerdict(l);h==="send"?a.push(l):h==="hold"&&o.push(l)}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 l=0;l<c.length;l+=ee){const h=c.slice(l,l+ee),u=await this.replayBatched(h,e,t);if(d.push(...u.requeue),u.stop||u.requeue.length>0){d.push(...c.slice(l+ee));break}}d.length>0&&this.offlineQueue.requeue(d),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){const t=f(e),s=this.replayRetryState.get(t),i=(s?.attempts??0)+1;this.replayRetryState.set(t,{attempts:i,delayMs:Math.max(s?.delayMs??0,ce(i))})}noteReplayRetryDelay(e,t,s){const i=f(e),r=this.replayRetryState.get(i),a=(r?.attempts??0)+1,o=Us(t,a)??(s===null&&$(t)?ce(a):void 0);this.replayRetryState.set(i,{attempts:a,delayMs:o===void 0?r?.delayMs:Math.max(r?.delayMs??0,o)})}scheduleRateLimitedRetry(e){const t=f(e),s=this.replayRetryState.get(t),i=s?.delayMs;if(s===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(t);return}s.delayMs=void 0;const r=this.replayRetryTimers.get(t);r!==void 0&&clearTimeout(r),this.replayRetryTimers.set(t,setTimeout(()=>{this.replayRetryTimers.delete(t),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){const t=[];for(const s of e)try{k(s.args,`args for '${s.functionPath}'`),t.push(s)}catch(i){this.settleReplayTerminal(s,i instanceof Error?i:new Error(String(i)))}return t}identityVerdict(e){if(this.subjectAwaitingReconfirm())return"unknown";if(e!=null&&this.retiredProvisionalStamps.has(e))return"mismatch";if(e===this.provisionalStamp&&this.provisionalBinding===void 0&&this.identityUnresolved())return"unknown";const t=this.stampedIdentity(e),s=this.identityFingerprint();return s===null&&this.identityUnresolved()?"unknown":t===s||t!==void 0&&this.isSameCredentialUnderTokenHash(t)?"match":s===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 i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",e.reject(i),this.emitItemSettled(e,"rejected",i),"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 i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,i)),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)||Me(e)}noteReplayAuthRefusal(e,t){if(!$(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,...te(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)}spendsLastReplayAttempt(e,t){if(e.id===void 0)return!1;const s=t?.code;if(e.ambiguousSend!==!0||$(t)||s==="RATE_LIMITED"||s==="TOO_MANY_REQUESTS"||(t instanceof TypeError||t instanceof F)&&fi()||!Me(t))return!1;const i=(this.replayAttempts.get(e.id)??0)+1;return this.replayAttempts.set(e.id,i),i>=Ct}keepUnexhaustedAmbiguousWrites(e,t){return e.filter(s=>s.ambiguousSend===!0&&this.spendsLastReplayAttempt(s,t)?(this.settleReplayTerminal(s,t),!1):!0)}settleReplayTerminal(e,t){this.unpersist(e.id),e.reject(t),this.emitItemSettled(e,"rejected",t)}async replaySequential(e,t,s){for(let i=0;i<e.length;i+=1){const r=e[i];if(!r)continue;let a;try{const o=await this.rpc(r.functionPath,r.args,r.shardKey,{authToken:s,baselineSeq:r.baselineSeq,captureBookmark:!0,clientId:r.clientId??this.clientId,...te(this.stampedIdentity(r.identity),s),mutationId:r.id,onCommitCursor:c=>{a=c}});this.settleReplaySuccess(r,o,a)}catch(o){if(q(o)){this.settleReplayUndecodable(r,o,a);continue}if(!this.shouldRequeueReplayFailure(o,s)||this.spendsLastReplayAttempt(r,o)){this.settleReplayTerminal(r,o);continue}this.noteReplayRetryDelay(t,o,s),this.offlineQueue.requeue(e.slice(i));return}}}async replayBatched(e,t,s){if(!this.fetchImpl)return{requeue:e,stop:!0};const i=JSON.stringify({calls:e.map((d,l)=>({args:k(d.args,`args for '${d.functionPath}'`),baselineSeq:d.baselineSeq,functionPath:d.functionPath,id:l,clientId:d.clientId??this.clientId,mutationId:d.id,shardKey:d.shardKey}))});if(e.length>1&&Ns(i)>Ds)return await this.replayBatchedHalves(e,t,s);const{fetchImpl:r}=this;let a,o;try{({payload:o,response:a}=await U(this.rpcTimeoutMs,void 0,async d=>{const l=await r(w(this.url,X),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:s,...te(this.stampedIdentity(e.find(h=>h.identity!==void 0)?.identity),s)}),method:"POST",signal:d});if(l.status===413&&e.length>1)return{payload:void 0,response:l};try{return{payload:await l.json(),response:l}}catch{return{payload:void 0,response:l}}}))}catch(d){return this.noteReplayRetryDelay(t,d,s),{requeue:this.keepUnexhaustedAmbiguousWrites(e,d),stop:!0}}const c=a.headers.get("x-d1-bookmark");if(c&&this.bookmark.set(c),a.status===413&&e.length>1)return await this.replayBatchedHalves(e,t,s);if(!o)return this.settleWholeBatchError(e,W(a.status,a.statusText,a.headers),t,s);if(!Array.isArray(o.results)){const d=K(o),l=d===void 0?W(a.status,a.statusText,a.headers):Se(d,a.headers);return this.settleWholeBatchError(e,l,t,s)}return{requeue:this.settleReplayBatchSlots(e,o.results,t,s,a.headers),stop:!1}}settleWholeBatchError(e,t,s,i){if(t instanceof F||t.code!==void 0&&this.shouldRequeueReplayFailure(t,i))return this.noteReplayRetryDelay(s,t,i),{requeue:this.keepUnexhaustedAmbiguousWrites(e,t),stop:!0};for(const r of e)this.settleReplayTerminal(r,t);return{requeue:[],stop:!1}}async replayBatchedHalves(e,t,s){const i=Math.ceil(e.length/2),r=await this.replayBatched(e.slice(0,i),t,s);if(r.stop||r.requeue.length>0)return{requeue:[...r.requeue,...e.slice(i)],stop:!0};const a=await this.replayBatched(e.slice(i),t,s);return{requeue:[...r.requeue,...a.requeue],stop:a.stop}}settleReplayBatchSlots(e,t,s,i,r){const a=Bs(t),o=[];let c=!1,d=!1;for(const[l,h]of e.entries()){const u=Ws(a.get(l),r);switch(u.kind){case"committed":{c=!0,this.settleReplaySuccess(h,u.value,u.commitCursor);break}case"errored":{d||=$(u.error),this.shouldRequeueReplayFailure(u.error,i)&&!this.spendsLastReplayAttempt(h,u.error)?(this.noteReplayRetryDelay(s,u.error,i),o.push(h)):this.settleReplayTerminal(h,u.error);break}case"unanswered":{const p=A(dt(),r);if(this.spendsLastReplayAttempt(h,p)){this.settleReplayTerminal(h,p);break}this.noteReplayRetryDelay(s,p,i),o.push(h);break}default:c=!0,this.settleReplayUndecodable(h,u.error,u.commitCursor)}}return c&&!d&&this.noteCredentialAccepted(i),o}}export{wr as $,ir as A,fn as B,ji as C,pn as D,or as E,Ki as F,Ji as G,cr as H,dr as I,lr as J,sr as K,Xe as L,hr as M,ur as N,Gi as O,fr as P,pr as Q,mr as R,Wi as S,yr as T,Sr as U,Zi as V,vr as W,br as X,Cr as Y,Tr as Z,kr as _,$i as a,gr as a0,Er as a1,Ar as a2,_r as a3,Rr as a4,Pr as a5,Fr as a6,Mr as a7,Ir as a8,Or as a9,Lr as aa,Hr as ab,Ur as ac,Dr as ad,Nr as ae,Br as af,Wr as ag,Qr as ah,xr as ai,qr as aj,Kr as ak,jr as al,$r as am,Vr as an,Gr as ao,zr as ap,Jr as aq,Yr as ar,ar as as,Vi as b,zi as c,Yi as d,Xi as e,rr as f,nr as g,tr as h,Qi as i,qi as j,xi as k,er as l,sn as m,Xr as n,nn as o,Zr as p,en as q,tn as r,rn as s,on as t,an as u,cn as v,dn as w,ln as x,hn as y,un as z};
@@ -2389,9 +2389,10 @@ declare class LunoraClient {
2389
2389
  * settled forever and shared with nobody — from a cookie app that simply
2390
2390
  * has not asked yet. Nothing in the client's own configuration says which
2391
2391
  * it is (`authBasePath` has a default), so the answer is declared: a
2392
- * `getCurrentUser()` call, or `@lunora/client/auth`'s identity store
2393
- * attaching itself, is what makes `null` provisional. An app that does
2394
- * neither keeps its read cache and its offline queue exactly as before.
2392
+ * `getCurrentUser()` call, `@lunora/client/auth`'s identity store attaching
2393
+ * itself, or — page-wide — `lunoraSessionSync()` being built is what makes
2394
+ * `null` provisional. An app that does none of these keeps its read cache
2395
+ * and its offline queue exactly as before.
2395
2396
  */
2396
2397
  private identityResolutionExpected;
2397
2398
  /**
@@ -2412,6 +2413,31 @@ declare class LunoraClient {
2412
2413
  * See `identityFingerprint` for the fingerprint shape.
2413
2414
  */
2414
2415
  private readonly queuedIdentities;
2416
+ /**
2417
+ * What a write composed before this client's identity first settled is
2418
+ * stamped with — see `writeIdentityStamp`. Random per instance, so a
2419
+ * write persisted by an earlier page can never claim this page's binding.
2420
+ */
2421
+ private provisionalStamp;
2422
+ /**
2423
+ * Provisional stamps retired by a session change before anything was bound
2424
+ * — see `retireProvisionalStamp`. A write carrying one was composed under a
2425
+ * session that is gone, so it never replays.
2426
+ */
2427
+ private readonly retiredProvisionalStamps;
2428
+ /**
2429
+ * The `identityQuestions` count when the current provisional stamp was minted. An
2430
+ * answer to a question asked before then — a socket upgraded under the session a
2431
+ * change replaced — describes that session, so it may not bind the stamp.
2432
+ */
2433
+ private provisionalStampQuestion;
2434
+ /** The identity this client settled on first, which `provisionalStamp` stands for; `undefined` until then. */
2435
+ private provisionalBinding;
2436
+ /** Set once this client asks `/get-session` on the page-wide declaration alone — see `resolveDeclaredSession`. */
2437
+ private resolvesDeclaredSession;
2438
+ /** Timed re-asks of a declared-session probe that failed while the connection stayed live, and the pending one. */
2439
+ private declaredSessionFailures;
2440
+ private declaredSessionRetryTimer;
2415
2441
  /**
2416
2442
  * Distinct shard keys with a mutation currently sitting in `offlineQueue`
2417
2443
  * — fresh writes queued this session (`enqueueOfflineMutation`) or writes
@@ -2592,13 +2618,28 @@ declare class LunoraClient {
2592
2618
  setAuthToken(token: string | null, subject?: string | null): void;
2593
2619
  getAuthToken(): string | null;
2594
2620
  /**
2595
- * The current identity fingerprint (the same stamp queued offline writes
2596
- * carry). Exposed so a durable {@link OutboxSink}'s replay handler — which
2597
- * owns its own at-least-once replay outside the built-in `OfflineQueue` —
2598
- * can drop a persisted write whose captured `identity` no longer matches the
2599
- * signed-in user, the guard the queue path applies in `flushOfflineQueue`.
2621
+ * The current identity fingerprint: a `subj:` label, a token hash, or `null`
2622
+ * for nobody. Key per-identity state on it. To stamp a durable write for a
2623
+ * later {@link replayIdentityVerdict}, use {@link writeIdentityStamp}, which
2624
+ * differs from this before the identity first settles.
2600
2625
  */
2601
2626
  currentIdentity(): string | null;
2627
+ /**
2628
+ * The identity stamp for a write composed now: what a durable
2629
+ * {@link OutboxSink} stores beside the write and later hands to
2630
+ * {@link replayIdentityVerdict}.
2631
+ *
2632
+ * The same as {@link currentIdentity}, except before this client's identity
2633
+ * first settles. There the fingerprint is a provisional `null` that the
2634
+ * session resolve in progress is about to name, and a `null` stamp reads as
2635
+ * anonymous: once the user's own session answered, the replay judged `null`
2636
+ * against `subj:<id>` as a different user and dropped the write, so a click
2637
+ * on page load, before `/get-session` returned, was lost. The provisional
2638
+ * stamp stands for whichever identity this client settles on first. Any
2639
+ * other client (a reload) reads it as the `null` it replaces, because it
2640
+ * cannot know which session minted it.
2641
+ */
2642
+ writeIdentityStamp(): string | null;
2602
2643
  /**
2603
2644
  * Declare that this client's identity is resolved by something — call it
2604
2645
  * before the first `getCurrentUser()`, not after.
@@ -4439,6 +4480,50 @@ declare class LunoraClient {
4439
4480
  * fall back to the stale token-hash and wrongly reject the same user's write.
4440
4481
  */
4441
4482
  private isSameCredentialUnderTokenHash;
4483
+ /**
4484
+ * Fix what `provisionalStamp` stands for, once: the first identity this
4485
+ * client establishes. Only an identity actually established may bind it — a
4486
+ * response that names nobody (a 403, a superseded probe) binds nothing, or a
4487
+ * real answer after it could not rebind the stamp and would drop the write.
4488
+ */
4489
+ private bindProvisionalStamp;
4490
+ /**
4491
+ * Bind the provisional stamp to a bearer identity the app set itself. Bearer only:
4492
+ * a cookie answer arrives as `setAuthToken(null, subject)` and binds in
4493
+ * `adoptCookieSubject`, which can tell a stale answer from a current one; and
4494
+ * `null` names nobody, which only an adopted "no session" answer may bind.
4495
+ */
4496
+ private bindBearerProvisionalStamp;
4497
+ /**
4498
+ * A session change reported before anything bound the provisional stamp —
4499
+ * a sign-in or sign-out here, or in another tab — means the cookie the
4500
+ * pending writes were composed under is gone. Binding them to the identity
4501
+ * that answers next would run one user's write as another's, so the stamp
4502
+ * is retired (its writes are rejected) and writes from now on get a new one.
4503
+ */
4504
+ private retireProvisionalStamp;
4505
+ /**
4506
+ * Ask `/get-session` for a client whose only reason to expect a session is
4507
+ * the page-wide declaration (`lunoraSessionSync()`). No identity store is
4508
+ * attached to ask for it, and a socket that authenticates with a ticket or a
4509
+ * token, or none opening at all, never delivers the cookie identity, so
4510
+ * without this its early writes were held and its read cache refused for the
4511
+ * life of the page. A probe that fails is asked again when the connection is
4512
+ * live again (see the constructor), or after a capped backoff for as long as it
4513
+ * keeps failing while the connection stays live and no transition is coming.
4514
+ */
4515
+ private resolveDeclaredSession;
4516
+ /** One declared-session probe, then the retry it may need. */
4517
+ private askDeclaredSession;
4518
+ /** Re-ask a declared-session probe that got no answer while the connection stayed live, at a capped backoff. */
4519
+ private retryDeclaredSession;
4520
+ /**
4521
+ * The identity a write stamp stands for. This client's provisional stamp is
4522
+ * the identity it settled on first (`undefined` until then); another
4523
+ * client's reads as the `null` it replaced, since this one cannot know which
4524
+ * session minted it; any other stamp is itself.
4525
+ */
4526
+ private stampedIdentity;
4442
4527
  /**
4443
4528
  * Release one {@link sessionProbesInFlight} hold and re-flush the writes
4444
4529
  * that hold alone was holding.
@@ -2389,9 +2389,10 @@ declare class LunoraClient {
2389
2389
  * settled forever and shared with nobody — from a cookie app that simply
2390
2390
  * has not asked yet. Nothing in the client's own configuration says which
2391
2391
  * it is (`authBasePath` has a default), so the answer is declared: a
2392
- * `getCurrentUser()` call, or `@lunora/client/auth`'s identity store
2393
- * attaching itself, is what makes `null` provisional. An app that does
2394
- * neither keeps its read cache and its offline queue exactly as before.
2392
+ * `getCurrentUser()` call, `@lunora/client/auth`'s identity store attaching
2393
+ * itself, or — page-wide — `lunoraSessionSync()` being built is what makes
2394
+ * `null` provisional. An app that does none of these keeps its read cache
2395
+ * and its offline queue exactly as before.
2395
2396
  */
2396
2397
  private identityResolutionExpected;
2397
2398
  /**
@@ -2412,6 +2413,31 @@ declare class LunoraClient {
2412
2413
  * See `identityFingerprint` for the fingerprint shape.
2413
2414
  */
2414
2415
  private readonly queuedIdentities;
2416
+ /**
2417
+ * What a write composed before this client's identity first settled is
2418
+ * stamped with — see `writeIdentityStamp`. Random per instance, so a
2419
+ * write persisted by an earlier page can never claim this page's binding.
2420
+ */
2421
+ private provisionalStamp;
2422
+ /**
2423
+ * Provisional stamps retired by a session change before anything was bound
2424
+ * — see `retireProvisionalStamp`. A write carrying one was composed under a
2425
+ * session that is gone, so it never replays.
2426
+ */
2427
+ private readonly retiredProvisionalStamps;
2428
+ /**
2429
+ * The `identityQuestions` count when the current provisional stamp was minted. An
2430
+ * answer to a question asked before then — a socket upgraded under the session a
2431
+ * change replaced — describes that session, so it may not bind the stamp.
2432
+ */
2433
+ private provisionalStampQuestion;
2434
+ /** The identity this client settled on first, which `provisionalStamp` stands for; `undefined` until then. */
2435
+ private provisionalBinding;
2436
+ /** Set once this client asks `/get-session` on the page-wide declaration alone — see `resolveDeclaredSession`. */
2437
+ private resolvesDeclaredSession;
2438
+ /** Timed re-asks of a declared-session probe that failed while the connection stayed live, and the pending one. */
2439
+ private declaredSessionFailures;
2440
+ private declaredSessionRetryTimer;
2415
2441
  /**
2416
2442
  * Distinct shard keys with a mutation currently sitting in `offlineQueue`
2417
2443
  * — fresh writes queued this session (`enqueueOfflineMutation`) or writes
@@ -2592,13 +2618,28 @@ declare class LunoraClient {
2592
2618
  setAuthToken(token: string | null, subject?: string | null): void;
2593
2619
  getAuthToken(): string | null;
2594
2620
  /**
2595
- * The current identity fingerprint (the same stamp queued offline writes
2596
- * carry). Exposed so a durable {@link OutboxSink}'s replay handler — which
2597
- * owns its own at-least-once replay outside the built-in `OfflineQueue` —
2598
- * can drop a persisted write whose captured `identity` no longer matches the
2599
- * signed-in user, the guard the queue path applies in `flushOfflineQueue`.
2621
+ * The current identity fingerprint: a `subj:` label, a token hash, or `null`
2622
+ * for nobody. Key per-identity state on it. To stamp a durable write for a
2623
+ * later {@link replayIdentityVerdict}, use {@link writeIdentityStamp}, which
2624
+ * differs from this before the identity first settles.
2600
2625
  */
2601
2626
  currentIdentity(): string | null;
2627
+ /**
2628
+ * The identity stamp for a write composed now: what a durable
2629
+ * {@link OutboxSink} stores beside the write and later hands to
2630
+ * {@link replayIdentityVerdict}.
2631
+ *
2632
+ * The same as {@link currentIdentity}, except before this client's identity
2633
+ * first settles. There the fingerprint is a provisional `null` that the
2634
+ * session resolve in progress is about to name, and a `null` stamp reads as
2635
+ * anonymous: once the user's own session answered, the replay judged `null`
2636
+ * against `subj:<id>` as a different user and dropped the write, so a click
2637
+ * on page load, before `/get-session` returned, was lost. The provisional
2638
+ * stamp stands for whichever identity this client settles on first. Any
2639
+ * other client (a reload) reads it as the `null` it replaces, because it
2640
+ * cannot know which session minted it.
2641
+ */
2642
+ writeIdentityStamp(): string | null;
2602
2643
  /**
2603
2644
  * Declare that this client's identity is resolved by something — call it
2604
2645
  * before the first `getCurrentUser()`, not after.
@@ -4439,6 +4480,50 @@ declare class LunoraClient {
4439
4480
  * fall back to the stale token-hash and wrongly reject the same user's write.
4440
4481
  */
4441
4482
  private isSameCredentialUnderTokenHash;
4483
+ /**
4484
+ * Fix what `provisionalStamp` stands for, once: the first identity this
4485
+ * client establishes. Only an identity actually established may bind it — a
4486
+ * response that names nobody (a 403, a superseded probe) binds nothing, or a
4487
+ * real answer after it could not rebind the stamp and would drop the write.
4488
+ */
4489
+ private bindProvisionalStamp;
4490
+ /**
4491
+ * Bind the provisional stamp to a bearer identity the app set itself. Bearer only:
4492
+ * a cookie answer arrives as `setAuthToken(null, subject)` and binds in
4493
+ * `adoptCookieSubject`, which can tell a stale answer from a current one; and
4494
+ * `null` names nobody, which only an adopted "no session" answer may bind.
4495
+ */
4496
+ private bindBearerProvisionalStamp;
4497
+ /**
4498
+ * A session change reported before anything bound the provisional stamp —
4499
+ * a sign-in or sign-out here, or in another tab — means the cookie the
4500
+ * pending writes were composed under is gone. Binding them to the identity
4501
+ * that answers next would run one user's write as another's, so the stamp
4502
+ * is retired (its writes are rejected) and writes from now on get a new one.
4503
+ */
4504
+ private retireProvisionalStamp;
4505
+ /**
4506
+ * Ask `/get-session` for a client whose only reason to expect a session is
4507
+ * the page-wide declaration (`lunoraSessionSync()`). No identity store is
4508
+ * attached to ask for it, and a socket that authenticates with a ticket or a
4509
+ * token, or none opening at all, never delivers the cookie identity, so
4510
+ * without this its early writes were held and its read cache refused for the
4511
+ * life of the page. A probe that fails is asked again when the connection is
4512
+ * live again (see the constructor), or after a capped backoff for as long as it
4513
+ * keeps failing while the connection stays live and no transition is coming.
4514
+ */
4515
+ private resolveDeclaredSession;
4516
+ /** One declared-session probe, then the retry it may need. */
4517
+ private askDeclaredSession;
4518
+ /** Re-ask a declared-session probe that got no answer while the connection stayed live, at a capped backoff. */
4519
+ private retryDeclaredSession;
4520
+ /**
4521
+ * The identity a write stamp stands for. This client's provisional stamp is
4522
+ * the identity it settled on first (`undefined` until then); another
4523
+ * client's reads as the `null` it replaced, since this one cannot know which
4524
+ * session minted it; any other stamp is itself.
4525
+ */
4526
+ private stampedIdentity;
4442
4527
  /**
4443
4528
  * Release one {@link sessionProbesInFlight} hold and re-flush the writes
4444
4529
  * that hold alone was holding.
@@ -1,4 +1,4 @@
1
- import { L as LunoraClient, P as Preloaded } from "./lunora-client.d-BxU8-4s5.mjs";
1
+ import { L as LunoraClient, P as Preloaded } from "./lunora-client.d-ReTNaYnW.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-CrkO-uRI.js";
1
+ import { L as LunoraClient, P as Preloaded } from "./lunora-client.d-BC8i2bd_.js";
2
2
  import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./function-reference.d-Br_hsKje.js";
3
3
  /**
4
4
  * Run a query once on the server (during SSR) and capture its result in a
@@ -1,5 +1,5 @@
1
1
  import { F as FunctionReference, R as ReturnOf, A as ArgsOf } from "../packem_shared/function-reference.d-Br_hsKje.mjs";
2
- import { L as LunoraClient, S as SubscriptionError, a as Unsubscribe } from "../packem_shared/lunora-client.d-BxU8-4s5.mjs";
2
+ import { L as LunoraClient, S as SubscriptionError, a as Unsubscribe } from "../packem_shared/lunora-client.d-ReTNaYnW.mjs";
3
3
  export type {
4
4
  /**
5
5
  * `@lunora/client/query` — the framework-neutral live-query state machine shared
@@ -15,7 +15,7 @@ export type {
15
15
  * `lunoraQueryOptions`), so every adapter and server entry keys a Lunora query
16
16
  * the same way.
17
17
  */
18
- b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-BxU8-4s5.mjs";
18
+ b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-ReTNaYnW.mjs";
19
19
  import '@lunora/errors';
20
20
  /**
21
21
  * The TanStack Query cache-key contract for Lunora queries. It lives here, not
@@ -1,5 +1,5 @@
1
1
  import { F as FunctionReference, R as ReturnOf, A as ArgsOf } from "../packem_shared/function-reference.d-Br_hsKje.js";
2
- import { L as LunoraClient, S as SubscriptionError, a as Unsubscribe } from "../packem_shared/lunora-client.d-CrkO-uRI.js";
2
+ import { L as LunoraClient, S as SubscriptionError, a as Unsubscribe } from "../packem_shared/lunora-client.d-BC8i2bd_.js";
3
3
  export type {
4
4
  /**
5
5
  * `@lunora/client/query` — the framework-neutral live-query state machine shared
@@ -15,7 +15,7 @@ export type {
15
15
  * `lunoraQueryOptions`), so every adapter and server entry keys a Lunora query
16
16
  * the same way.
17
17
  */
18
- b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-CrkO-uRI.js";
18
+ b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-BC8i2bd_.js";
19
19
  import '@lunora/errors';
20
20
  /**
21
21
  * The TanStack Query cache-key contract for Lunora queries. It lives here, not
@@ -1,4 +1,4 @@
1
- import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-BxU8-4s5.mjs";
1
+ import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-ReTNaYnW.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-ByaSovKg.mjs";
23
+ a as preloadedQueryResult } from "../packem_shared/preload.d-C2eH0Vm2.mjs";
24
24
  import '@lunora/errors';
25
25
  /**
26
26
  * Structural shape of a better-auth `getSession` call's resolved value.
@@ -1,4 +1,4 @@
1
- import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-CrkO-uRI.js";
1
+ import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-BC8i2bd_.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-BB2CUNhN.js";
23
+ a as preloadedQueryResult } from "../packem_shared/preload.d-C4nGCFfk.js";
24
24
  import '@lunora/errors';
25
25
  /**
26
26
  * Structural shape of a better-auth `getSession` call's resolved value.
@@ -1 +1 @@
1
- import{getServerSession as o}from"../packem_shared/getServerSession-BaOoo1p6.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-DxozvweR.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-6RlA9jJE.mjs";import{preloadQuery as s,preloadedQueryResult as f}from"../packem_shared/preloadQuery-uFy24PCR.mjs";export{i as createServerClient,l as deserializePreloaded,o as getServerSession,s as preloadQuery,f as preloadedQueryResult,t as serializePreloaded};
1
+ import{getServerSession as o}from"../packem_shared/getServerSession-BaOoo1p6.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-DxozvweR.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-C6SWU3rv.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.303",
3
+ "version": "1.0.0-alpha.304",
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 m,OFFLINE_NOT_QUEUED_HINT as Xe}from"@lunora/errors";import{decodeWire as _,encodeWire as le,stableWireKey as pe}from"@lunora/wire";import{t as Me}from"./base64-849R7V-V.mjs";import{r as Ze,U as et,P as tt}from"./delta-merge-C6OqMEPH.mjs";import st from"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import{w as A,u as ue,s as He,a as it,i as x,r as $,e as q,b as me,c as rt,d as ye,f as nt}from"./wire-errors-BDckSTKZ.mjs";import{ClientQueryStore as ot}from"./createClientQuery-B8Nfj-7o.mjs";import{D as at,a as ct,b as dt,c as lt,d as ut,S as Se,M as ht,I as ft,Q as pt,R as mt,e as ve,f as yt,g as St}from"./client-tuning-C10B2KCO.mjs";import{j as w,d as be,p as K,s as Ce}from"./client-urls-BHLUjjcG.mjs";import{TabCoordinator as vt}from"./TabCoordinator-DIySdaRV.mjs";import{TransportError as P,getRetryAfterMs as bt,AUTH_REPLAY_ERROR_CODES as Ct,isAuthReplayFailure as j}from"./CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as wt,pumpSseBody as gt}from"./httpStream-DN3D9WqW.mjs";import{createLocalStore as Tt}from"./createLocalStore-WKNHD1ca.mjs";import{O as kt,n as J,i as Et}from"./offline-queue-HwrYARIL.mjs";import{d as At,b as ne,r as R,c as O,a as _t,w as Rt,e as It,f as Ot}from"./optimistic-layers-BI61YTO3.mjs";import Lt from"./OutboxDeclinedError-D6vF-WyL.mjs";import{resolvePersistenceAdapter as Pt}from"./createInMemoryPersistence-C-IzNVbg.mjs";import{w as U,a as we,b as Ft}from"./stream-idle-C7CsIT_m.mjs";import{resolveQueryCacheAdapter as Mt,queryCacheKey as M}from"./createInMemoryQueryCache-DR6AorA2.mjs";import{createReconnect as ge}from"./createReconnect-CjTmjJDH.mjs";import{fanSubscriptionError as he,setSubscriptionAck as I,SubscriptionRegistry as g,wrapSubscriber as z,replaySubscriptionRefusal as Ht,failSubscription as D,releaseSubscribeFrame as Y}from"./SubscriptionRegistry-DjFfxba2.mjs";import{c as Ut,s as Te,r as Nt}from"./snapshot-precondition-BEtcSbWr.mjs";import{createStream as Dt}from"./DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";const ke="/_lunora/rpc",X="/_lunora/rpc-batch",Z="/_lunora/ws",Hi="/_lunora/admin/shard-traffic",Bt="/_lunora/admin/scheduled",Wt="/_lunora/admin/scheduled/status",Qt="/_lunora/admin/scheduled/ws",xt="/_lunora/admin/scheduled/cancel",Ee="/_lunora/admin/scheduled/dead",qt="/_lunora/admin/scheduled/dead/retry",Kt="/_lunora/admin/scheduled/dead/cancel",Ae="/_lunora/admin/scheduled/history",jt="/_lunora/admin/scheduled/job",Vt="/_lunora/admin/scheduled/cron-runs",Ue="/_lunora/admin/pause",Gt="/_lunora/admin/workflows/instances",$t="/_lunora/admin/workflows/instance",Jt="/_lunora/admin/workflows/status",zt="/_lunora/admin/workflows/create",Yt="/_lunora/admin/workflows/event",Ui="/_lunora/admin/storage",Ni="/_lunora/admin/storage/url",Di="/_lunora/admin/storage/buckets",Bi="/_lunora/admin/functions",Wi="/_lunora/admin/cron-jobs",Qi="/_lunora/admin/cron-jobs/run",xi="/_lunora/admin/architecture",qi="/_lunora/admin/openapi",Ki="/_lunora/admin/openrpc",ji="/_lunora/admin/global/tables",Vi="/_lunora/admin/global/table",Gi="/_lunora/admin/global/facet",$i="/_lunora/admin/vector/indexes",Ji="/_lunora/admin/vector/query",zi="/_lunora/admin/logs/archive",Yi="/_lunora/admin/kv/namespaces",Xi="/_lunora/admin/tokens",Zi="/_lunora/admin/kv/keys",er="/_lunora/admin/kv/value",tr="/_lunora/admin/auth/users",sr="/_lunora/admin/auth/sessions",ir="/_lunora/admin/auth/users/create",rr="/_lunora/admin/auth/users/role",nr="/_lunora/admin/auth/users/ban",or="/_lunora/admin/auth/users/unban",ar="/_lunora/admin/auth/users/password",cr="/_lunora/admin/auth/users/remove",dr="/_lunora/admin/auth/users/impersonate",lr="/_lunora/admin/auth/sessions/revoke",ur="/_lunora/admin/auth/sessions/revoke-all",hr="/_lunora/admin/auth/capabilities",fr="/_lunora/admin/auth/users/update",pr="/_lunora/admin/auth/accounts",mr="/_lunora/admin/auth/accounts/unlink",yr="/_lunora/admin/auth/passkeys",Sr="/_lunora/admin/auth/passkeys/delete",vr="/_lunora/admin/auth/api-keys",br="/_lunora/admin/auth/api-keys/delete",Cr="/_lunora/admin/auth/two-factor/disable",wr="/_lunora/admin/auth/organizations",gr="/_lunora/admin/auth/organizations/members",Tr="/_lunora/admin/auth/organizations/invitations",kr="/_lunora/admin/auth/organizations/members/remove",Er="/_lunora/admin/auth/organizations/invitations/cancel",Ar="/_lunora/admin/auth/config",_r="/_lunora/admin/auth/sign-up-invitations",Rr="/_lunora/admin/auth/sign-up-invitations/create",Ir="/_lunora/admin/auth/sign-up-invitations/revoke",Or="/_lunora/admin/auth/organizations/create",Lr="/_lunora/admin/auth/organizations/update",Pr="/_lunora/admin/auth/organizations/remove",Fr="/_lunora/admin/auth/organizations/members/add",Mr="/_lunora/admin/auth/organizations/members/invite",Hr="/_lunora/admin/auth/organizations/members/role",Ur="/_lunora/admin/auth/organizations/teams",Nr="/_lunora/admin/auth/organizations/teams/create",Dr="/_lunora/admin/auth/organizations/teams/update",Br="/_lunora/admin/auth/organizations/teams/remove",Wr="/_lunora/admin/auth/organizations/teams/members",Qr="/_lunora/admin/auth/organizations/teams/members/add",xr="/_lunora/admin/auth/organizations/teams/members/remove",qr="/_lunora/admin/auth/organizations/roles",Kr="/_lunora/admin/auth/organizations/roles/create",jr="/_lunora/admin/auth/organizations/roles/update",Vr="/_lunora/admin/auth/organizations/roles/remove",Xt="/api/auth",Zt="/get-session",es="lunora-ping",ee=500,Ne=(n,e)=>{if(n.size<e)return;const t=n.keys().next().value;t!==void 0&&n.delete(t)};new TextDecoder;const ts=new TextEncoder,ss=n=>Me(ts.encode(n)),is=n=>ss(JSON.stringify(n)),rs="x-lunora-expect-subject",ns=n=>is({subject:n}),os="refreshBatch",_e=Symbol.for("lunora:session-change"),as="lunora:session-change",cs="better-auth.message",ds="signout",De=()=>{const n=globalThis;let e=n[_e];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},n[_e]=e),e},ls=()=>"document"in globalThis,us=async()=>{const n=[];for(const e of De().listeners)try{n.push(e())}catch{}await Promise.allSettled(n)},hs=(n,e)=>{if(n!==cs||e===null)return!1;try{const t=JSON.parse(e);return t?.event==="session"&&t.data?.trigger===ds}catch{return!1}},fs=n=>{const e=[],t=()=>{us().catch(()=>{})};let s;try{s=typeof BroadcastChannel=="function"?new BroadcastChannel(as):void 0}catch{s=void 0}if(s!==void 0){const r=s;r.addEventListener("message",a=>{a.data?.type==="lunora:session-change"&&a.data.tab!==n&&t()}),e.push(()=>{r.close()})}const i=globalThis;if(typeof i.addEventListener=="function"){const r=a=>{hs(a.key,a.newValue)&&t()};i.addEventListener("storage",r),e.push(()=>{i.removeEventListener?.("storage",r)})}return()=>{for(const r of e)r()}},ps=n=>{const e=De();return e.listeners.add(n),e.detach===void 0&&ls()&&(e.detach=fs(e.tab)),()=>{e.listeners.delete(n),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},Re="/_lunora/ws/reauth",ms=4005,ys="identity_changed",Ss="/_lunora/claims",vs="lunora",bs="lunora.bearer.",Cs=n=>`${bs}${Me(new TextEncoder().encode(n))}`,ws=async n=>{const e=[];let t;for(;;){const s=await n(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}},Be=n=>({paused:n.paused===!0,...typeof n.pausedAt=="number"?{pausedAt:n.pausedAt}:{},...typeof n.reason=="string"?{reason:n.reason}:{},supported:n.supported===!0}),W=n=>"args"in n?{...n,args:_(n.args)}:n,Gr=async n=>(n.assertOpen(),((await n.adminFetch(Bt,"GET")).records??[]).map(t=>W(t))),$r=async(n,e)=>{n.assertOpen();const t=await n.adminFetch(`${jt}?id=${encodeURIComponent(e)}`,"GET");return t.record===void 0?null:W(t.record)},Jr=async(n,e={})=>{n.assertOpen();const t=e.cursor===void 0?Ae:`${Ae}?cursor=${encodeURIComponent(e.cursor)}`,s=await n.adminFetch(t,"GET"),i=(s.records??[]).map(r=>W(r));return s.truncated===!0&&s.cursor!==void 0?{cursor:s.cursor,records:i}:{records:i}},zr=async n=>{n.assertOpen();const e=await n.adminFetch(Vt,"GET");return{inFlight:e.inFlight??[],runs:e.runs??[]}},Yr=async n=>(n.assertOpen(),Be(await n.adminFetch(Ue,"GET"))),Xr=async(n,e,t)=>(n.assertOpen(),Be(await n.adminFetch(Ue,"POST",t===void 0?{paused:e}:{paused:e,reason:t}))),Zr=async n=>{n.assertOpen();const e=await n.adminFetch(Wt,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},en=async(n,e)=>(n.assertOpen(),{cancelled:(await n.adminFetch(xt,"POST",{id:e})).cancelled===!0}),tn=async n=>(n.assertOpen(),(await ws(async t=>await n.adminFetch(t===void 0?Ee:`${Ee}?cursor=${encodeURIComponent(t)}`,"GET"))).map(t=>W(t))),sn=async(n,e)=>(n.assertOpen(),{retried:(await n.adminFetch(qt,"POST",{id:e})).retried===!0}),rn=async(n,e)=>(n.assertOpen(),{removed:(await n.adminFetch(Kt,"POST",{id:e})).removed===!0}),nn=async(n,e)=>{n.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 n.adminFetch(`${Gt}?${t.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}},on=async(n,e)=>{n.assertOpen();const t=new URLSearchParams({id:e.id,name:e.name}),s=await n.adminFetch(`${$t}?${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??[]}},an=async(n,e)=>{n.assertOpen();const t=await n.adminFetch(zt,"POST",{id:e.id,name:e.name,params:e.params}),s=t.id??e.id;if(s===void 0)throw new m("WORKFLOWS_REST_ERROR","Workflows create response carried no instance id",{status:502});return{id:s,status:t.status??"unknown"}},cn=async(n,e)=>{n.assertOpen();const t=await n.adminFetch(Yt,"POST",{id:e.id,name:e.name,payload:e.payload,type:e.type});return{instanceId:t.instanceId??e.id,timestamp:t.timestamp}},dn=async(n,e)=>(n.assertOpen(),{status:(await n.adminFetch(Jt,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),k=(n,e)=>{try{return le(n)}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)}},oe=n=>{try{return le(n),!0}catch{return!1}},We=n=>n!==null&&typeof n=="object"&&("error"in n||"result"in n),gs=(n,e,t)=>{const s=Array.from({length:e}),i=r=>({error:A(He(r),t),ok:!1});for(const r of n){if(typeof r.id!="number"||r.id<0||r.id>=e)continue;if(!We(r.body)){s[r.id]=i({});continue}const a=r.body;if("error"in a){s[r.id]=i(a);continue}try{s[r.id]={ok:!0,value:_(a.result)}}catch(o){s[r.id]={error:A(ue(o),t),ok:!1}}}return s.map(r=>r??{error:A(new Error("batch call returned no result"),t),ok:!1})},te=(n,e)=>e!==null?{}:n===null?{expectSubject:null}:n?.startsWith("subj:")===!0?{expectSubject:n.slice(5)}:{},H=n=>n==="connected"||n==="polling",f=n=>n??"",E=(n,e)=>{if(!n.socket||n.wsState!=="open")return!1;try{return n.socket.send(JSON.stringify(e)),!0}catch{return!1}},Ts=n=>{if(!n.pendingStreams||n.pendingStreams.length===0)return;const e=n.pendingStreams;n.pendingStreams=[];for(const t of e)E(n,t)},ks=new TextDecoder,Es=n=>{if(typeof n=="string")return n;if(n instanceof ArrayBuffer)return ks.decode(n)};class L{listeners=new Set;get size(){return this.listeners.size}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 N=n=>{n.heartbeatTimer!==void 0&&(clearInterval(n.heartbeatTimer),n.heartbeatTimer=void 0)},As=(n,e,t)=>{N(n),!(e<=0)&&(n.heartbeatTimer=setInterval(()=>{if(!n.socket)return;const{socket:s}=n;if(Date.now()-n.lastFrameAt>e*2.5){try{s.close()}catch{}t();return}try{s.send(es)}catch{}},e))},Ie=(n,e,t,s)=>{const{WebSocketImpl:i,connectTimeoutMs:r,heartbeatIntervalMs:a}=t;if(i===void 0)throw new m("INTERNAL","no WebSocket implementation available");const o=s.protocols===void 0?new i(e):new i(e,s.protocols);n.socket=o;const c=()=>{N(n),n.connectTimer!==void 0&&(clearTimeout(n.connectTimer),n.connectTimer=void 0),n.socket===o&&(n.socket=void 0)},d=l=>{c(),s.onClose(l)};r>0&&(n.connectTimer=setTimeout(()=>{if(n.connectTimer=void 0,n.socket===o){try{o.close()}catch{}d()}},r)),o.addEventListener("open",()=>{if(n.socket===o){n.connectTimer!==void 0&&(clearTimeout(n.connectTimer),n.connectTimer=void 0),n.lastFrameAt=Date.now();try{s.onOpen?.()}catch(l){console.error("[lunora] connection open handler threw",l)}n.socket===o&&As(n,a,d)}}),o.addEventListener("message",l=>{if(n.socket===o){n.lastFrameAt=Date.now();try{s.onMessage(l)}catch(u){console.error("[lunora] server frame handler threw",u)}}}),o.addEventListener("close",l=>{n.socket===o&&d(l)}),o.addEventListener("error",()=>{n.socket===o&&d()})},_s=n=>{const{afterFailedAttempts:e,intervalMs:t,onReachable:s,onStateChange:i,poll:r}=n,a=t>0&&e>0;let o=0,c,d=!1,l=!1;const u=()=>{c!==void 0&&(clearInterval(c),c=void 0,d=!1,i())},h=S=>{if(c!==void 0){if(!S){u();return}d||(d=!0,i()),s()}},p=()=>{l||(l=!0,r().then(h).finally(()=>{l=!1}).catch(()=>{}))};return{hasFailedOpen:()=>o>0,isPolling:()=>c!==void 0&&d,noteFailedOpen:()=>{o+=1,!(!a||c!==void 0||o<e)&&(c=setInterval(p,t),i(),p())},noteOpen:()=>{o=0,u()},stop:u}},Rs=1e4,Oe=async n=>U(Rs,void 0,n,()=>new TypeError("LunoraClient: poll timed out")),Qe=new Set(["DELIVERY_FENCED","RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Le=n=>{if(n instanceof P)return!0;const e=n?.code;return e===void 0||Qe.has(e)||Ct.has(e)},Is=1e3,xe=6e4,Os={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},B=(n,e,t)=>{const s=it(t.get("retry-after")),i=s===void 0?void 0:{retryAfterMs:s},r=`LunoraClient: response carried no error envelope (status ${n.toString()}${e?` ${e}`:""})`,a=n<400||n>=500||n===408?new P(r,i):new m(Os[n]??"BAD_REQUEST",r,{data:i});return A(a,t)},ae=(n,e=Math.random)=>{const t=Math.min(Is*2**Math.max(n-1,0),xe);return Math.round(t*(.5+e()*.5))},Ls=n=>{const e=n?.code;return n instanceof P||e===void 0||Qe.has(e)},Ps=(n,e,t)=>{const s=bt(n);return s!==void 0&&s>0?Math.min(s,xe):Ls(n)?ae(e,t):void 0},Fs=983040,Ms=n=>typeof TextEncoder>"u"?n.length:new TextEncoder().encode(n).length,Hs=n=>{const e=new Map;for(const t of n)typeof t.id=="number"&&We(t.body)&&e.set(t.id,t.body);return e},Us=(n,e)=>{if(n===void 0)return{kind:"unanswered"};if("error"in n)return{error:A(He(n),e),kind:"errored"};try{return{commitCursor:n.commitCursor,kind:"committed",value:_(n.result)}}catch(t){return{commitCursor:n.commitCursor,error:A(ue(t),e),kind:"undecodable"}}},se=(n,e)=>`${f(n)}\0${e}`,Ns=(n,e)=>{for(const t of e)t.op==="delete"?n.delete(t.key):t.value!==void 0&&n.set(t.key,t.value)};class Ds{constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,t){Ne(this.buffers,this.maxBuffers),this.buffers.set(se(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(se(e,t.pokeId));if(!s)return;const i=[];try{for(const o of t.rowsPatch)i.push(o.value===void 0?o:{...o,value:_(o.value)})}catch(o){s.undecodable.set(t.shapeId,o);return}const r=s.parts.get(t.shapeId)??[];for(const o of i)r.push(o);s.parts.set(t.shapeId,r),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=se(e,t),i=this.buffers.get(s);return i&&this.buffers.delete(s),i}clear(){this.buffers.clear()}}const Bs=(n,e,t)=>{const s=e.parts.get(n.id)??[],i=e.resets.has(n.id),r=e.bases.get(n.id),a=e.epoch!==void 0&&n.serverEpoch!==void 0&&e.epoch!==n.serverEpoch,o=r!==void 0&&n.serverCursor!==void 0&&n.serverCursor!==r;if(!i&&(a||o))return n.rows.clear(),n.serverCursor=void 0,n.serverEpoch=void 0,n.answered=!1,"reseed";i&&n.rows.clear(),Ns(n.rows,s),n.answered=!0,t.checkpoint!==void 0&&(n.serverCursor=t.checkpoint),t.epoch!==void 0&&(n.serverEpoch=t.epoch);const c=e.lastMutationId.get(n.id);return c!==void 0&&(n.lastMutationId=c),"applied"},Pe=n=>{const e=[...n.rows.values()];for(const t of n.callbacks)try{t(e)}catch{}},Ws=(n,e)=>{for(const[t,s]of e.undecodable){const i=n.get(t);i&&he(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape — ${s instanceof Error?s.message:String(s)}`})}},ce=(n,e)=>{n.lastMutationId=Math.max(n.lastMutationId??0,e)},de=(n,e=!1)=>{const t=n.serverCursor,s=n.lastMutationId;At(()=>{for(const i of n.checkpointCallbacks)i({checkpoint:t,mutationId:s,...e&&{rowsFollow:!0}})})},qe=(n,e,t)=>{n.serverBase=e,n.serverBaseCommitted=!0,n.awaitingSnapshot=!1,n.baseIncomplete=!1,n.serverClaims=t.claims,t.cursor!==void 0&&(n.serverCursor=t.cursor),t.epoch!==void 0&&(n.serverEpoch=t.epoch)},Qs=n=>n.awaitingSnapshot===!0?void 0:n.lastValue,xs=(n,e)=>e.cursor!==void 0&&n.serverCursor!==void 0&&(n.serverBase!==void 0||n.serverBaseCommitted===!0)&&e.epoch!==void 0&&e.epoch===n.serverEpoch&&e.cursor<n.serverCursor,qs=n=>n.type==="delta"&&n.more===!0,V=(n,e)=>n!==void 0&&n!==e,Ks=(n,e)=>e==="connected"&&n!=="connected"||e==="polling"&&n!=="connected"&&n!=="polling",fe=(n,e,t,s,i=!1)=>{if(t===void 0)return!i||n.ownClaims(e,s,"")===null;const r=n.ownClaims(e,s,t);return r!==void 0&&(r===null||r===t)},js=n=>{for(const e of n.activeSubscriptions())I(e,"idle"),e.valueReceived=!1,n.ensureSocket(e.shardKey),n.queueResubscribe(e);for(const e of n.activeShapes())e.answered=!1,n.ensureSocket(e.shardKey);for(const e of n.queuedShardKeys())n.ensureSocket(e);n.broadcastStatus(n.computeStatus(),n.identityFingerprint()),n.emitConnectionStatus()},Vs=n=>{n.closeConnections();const e=n.leader;e.status=void 0,e.wasEverConnected=!1;for(const t of n.activeSubscriptions())I(t,"idle"),t.valueReceived=!1;for(const t of n.activeShapes())t.answered=!1;n.emitConnectionStatus()},Gs=(n,e,t)=>{if(V(t,n.identityFingerprint()))return;const s=n.leader,i=Ks(s.status,e);s.status=e,e==="connected"&&(s.wasEverConnected=!0),n.emitConnectionStatus(),i&&(n.awaitLeaderAnswers(),n.flushOfflineQueues())},$s=n=>{n.isLeader()&&n.broadcastStatus(n.computeStatus(),n.identityFingerprint())},Ke=(n,e,t,s,i,r,a)=>{if(V(r,n.identityFingerprint())||!fe(n,e,a,()=>{Ke(n,e,t,s,i,r,a)},t!==void 0))return;const o=n.subscription(e);if(!o)return;n.dropCacheSeed(e);const c=!o.valueReceived;o.valueReceived=!0,qe(o,t,s===void 0?{claims:a}:{claims:a,cursor:s,epoch:i}),o.refusal=void 0,s!==void 0&&ne(o,s),R(o,t),c&&n.emitConnectionStatus(),n.settleAwaitedAnswer(o,!0)},je=(n,e,t,s,i)=>{if(V(s,n.identityFingerprint())||!fe(n,`error:${e}`,i,()=>{je(n,e,t,s,i)}))return;const r=n.subscription(e);if(r){const a=!r.valueReceived;r.valueReceived=!0,r.refusal=t,he(r.errorCallbacks,t),a&&n.emitConnectionStatus(),n.settleAwaitedAnswer(r,!1)}},Ve=(n,e,t,s,i,r,a,o)=>{if(V(a,n.identityFingerprint()))return;const c=n.subscription(e);c&&fe(n,`settled:${e}`,o,()=>{Ve(n,e,t,s,i,r,a,o)})&&(n.ackAndAdvanceCursor(c,t,s),i!==void 0&&r===n.clientIdentifier()&&ce(c,i),de(c))},Js=(n,e,t)=>n!==null||e&&t===null,zs=n=>n.sensitive===!0,Ys=(n,e)=>{if(!zs(n))return e;if(e.onlineOnly===!1)throw new m("BAD_REQUEST",`'${n.__lunoraRef}' takes a sensitive argument and is always online-only; onlineOnly: false is not allowed`);return{...e,onlineOnly:!0}},Xs=[tt,os],Zs=n=>n.type==="data"||n.type==="delta"||n.type==="settled"||n.type==="resume"||n.type==="error"&&typeof n.id=="string",ei=100,Ge=1e4,ti=5,si=500,ii=1e4,ri=(n,e)=>{let t;const s=new Promise((r,a)=>{t=setTimeout(()=>{a(new Error("ws ticket mint timed out"))},e)}),i=(async()=>n())();return Promise.race([i,s]).finally(()=>{clearTimeout(t)})},ni=(n,e)=>{const t=[n===void 0?"":`shard=${encodeURIComponent(n)}`,e===void 0?"":`token=${encodeURIComponent(e)}`].filter(Boolean).join("&");return t===""?Re:`${Re}?${t}`},ie=async n=>typeof n=="function"?await n():n,re=async(n,e,t,s)=>{const i=new AbortController,r=setTimeout(()=>{i.abort()},Ge);try{const a=await n(e,{body:t,credentials:"include",headers:s,method:"POST",signal:i.signal});return{status:a.status,text:await a.text()}}finally{clearTimeout(r)}},Fe=(n,e)=>new m("OFFLINE_NOT_QUEUED",`'${n}' is online-only and the connection is not live, so it was not queued`,{cause:e,hint:Xe}),oi=()=>new Error("LunoraClient: the connection is not live, so the durable replay was not sent; it stays queued"),ai=(n,e)=>n instanceof TypeError&&oe(e),ci=()=>globalThis.navigator?.onLine===!1,di=(n,e,t,s)=>e||n===!0&&t&&!s,li=Promise.resolve(),ui=async(n,e,t)=>{let s,i;const r=new AbortController,a=()=>{r.abort(e?.reason)};e?.addEventListener("abort",a,{once:!0});try{await gt(n,{complete:o=>{e?.aborted!==!0&&(s=o)},fail:o=>{i=o},push:o=>{e?.aborted!==!0&&t?.(o)}},{},r)}finally{e?.removeEventListener("abort",a)}if(e?.aborted===!0)throw e.reason instanceof Error?e.reason:new DOMException("The operation was aborted.","AbortError");return{failure:i,terminal:s}};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;wsTicket;wsCredentialGeneration=0;refusedCredentialGeneration;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;rpcTimeoutMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;ownClaimsValue;heldLeaderFrames=new Map;ownClaimsFetch;claimsVerifiedAgainst=new Set;ownClaimsRetryTimer;ownClaimsFailures=0;suspendedFollowerValues=new Map;frameClaims;authTokenOnUpgrade;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;mutationIssueCounter=0;identityRetirements=0;persistence;persistenceVersion;releasePageHideFlush;outboxLeaderRelease;queryCache;queryCacheEpoch=0;queryCacheChain=Promise.resolve();hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new g;pendingSubscriptionRetries=new Map;tabCoordinator;leader={status:void 0,wasEverConnected:!1};connections=new Map;idleClosedShards=new Set;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;tokenFingerprint;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 L;statusListeners=new L;roomFlushes=new Map;roomIdentityResets=new Set;tokenExpiredListeners=new L;identityChangeListeners=new L;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new L;pendingChangeListeners=new L;syncStatusListeners=new L;lastSyncStatus;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;supplementaryBounces=new Set;offlineFlushes=new Map;awaitingAnswer=new WeakSet;answeredUnreadable=new WeakSet;answerHeldShards=new Set;leaderAnswerTimers=new Map;replayRetryState=new Map;replayAttempts=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new Ds($e.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??w(be(e.url),Z),this.wsToken=e.wsToken,this.wsTicket=e.wsTicket;const t=e.authBasePath??Xt;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??st(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??at,this.connectTimeoutMs=e.connectTimeoutMs??ct,this.rpcTimeoutMs=e.rpcTimeoutMs??dt,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??lt,this.authTokenOnUpgrade=e.authTokenOnUpgrade??!1,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??ut,this.defaultConnectionContext=e.connectionContext,this.persistence=Pt(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Mt(e.queryCache),this.clientQueryStore=new ot,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=li),this.offlineQueue=new kt(e.offlineQueue,{onEvict:(s,i)=>{this.emitItemSettled(s,"rejected",i),this.releaseIdleShard(s.shardKey)},onReplayingChange:()=>{this.emitSyncStatus()},onSizeChange:s=>{this.pendingChangeListeners.emit(s),this.emitSyncStatus()},persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${J()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.installPageHideFlush(),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=ps(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,t){const s=this.authToken!==e;s&&this.resetOwnClaims();const i=this.identityFingerprint(),r=this.authSubject===void 0||this.subjectToken===this.authToken,a=this.subjectAwaitingReconfirm(),o=this.isKnownNobody(),c=this.authToken;this.authToken=e,s&&(this.tokenFingerprint=void 0),this.applySubject(e,t);const d=this.identityFingerprint(),l=!s&&e!==null&&r,u=!s&&e===null&&i===null&&r&&!o,h=d!==i;let p=!1;h&&(l?(this.restampQueuedIdentity(i,d),this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):u?(this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):p=this.retirePreviousIdentity(i,o,c,e)),p||this.applyUpgradeBearer(this.reconcileUpgradeBearer(c,e,h)),h&&this.restartTabCoordinatorForIdentity(),this.syncReadCacheToCredential(a),s&&this.authTokenListeners.emit(e),(d!==i||s||a)&&this.offlineQueue.size>0&&H(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 i=s?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new m("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);const r=s?.shardKey??"",a=this.identityFingerprint();let o,c,d;try{c=await this.rpc(e,t,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:u=>{o=u}})}catch(u){if(!x(u))throw u;d=u}if(o!==void 0&&o>(this.clientWatermarks.get(a??"")?.get(r)??0)){let u=this.clientWatermarks.get(a??"");u===void 0&&(Ne(this.clientWatermarks,St),u=new Map,this.clientWatermarks.set(a??"",u)),u.set(r,o)}if(d!==void 0)throw d;return{applied:o===void 0||o===i,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 i=await this.fetchImpl(w(this.url,`${this.authBasePath}${Zt}`),{credentials:"include",headers:e,method:"GET"});if(!i.ok)return this.identitySettled=!0,i.status===401&&this.adoptResolvedSubject(t,null,s),null;const a=(await i.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.applyWsCredentialChange())}setWsTicket(e){this.wsTicket!==e&&(this.wsTicket=e,this.applyWsCredentialChange())}setConnectionContext(e,t={}){this.assertLeaderOwnedSurface("setConnectionContext");const s=f(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=f(t.shardKey),i={context:e},r=this.connectionContextHolders.get(s);r?r.push(i):this.connectionContextHolders.set(s,[i]),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(i);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 i=f(s.shardKey);let r=this.whisperHandlers.get(i);r||(r=new Map,this.whisperHandlers.set(i,r));let a=r.get(e);const o=a===void 0;if(a||(a=new Set,r.set(e,a)),a.add(t),this.ensureSocket(s.shardKey),o){const c=this.getConnection(s.shardKey);c&&this.sendWhisperJoin(c,i,e)}return()=>{const c=this.whisperHandlers.get(i),d=c?.get(e);if(!d?.delete(t)||d.size>0)return;c?.delete(e),c?.size===0&&this.whisperHandlers.delete(i);const l=this.getConnection(s.shardKey);l&&E(l,{topic:e,type:"whisper_unsubscribe"}),this.releaseWhisperJoin(i,e),this.releaseIdleShard(s.shardKey)}}subscribeLiveTopic(e){const{onError:t,onEvent:s,shardKey:i,stream:r,topic:a}=e;if(a.length===0)throw new m("INTERNAL","LunoraClient: subscribeLiveTopic needs a non-empty topic");this.nextLiveSocketId+=1;const o=`ws-live-${String(this.nextLiveSocketId)}`,c=f(i),d=`/live/${r}/control`;let u=this.whisperSubscribe(a,()=>{},{shardKey:i});const h=()=>{const b=u;u=void 0,b?.()};let p=this.liveSocketGrants.get(c);p===void 0&&(p=new Map,this.liveSocketGrants.set(c,p)),p.set(o,{onError:t,onEvent:s,release:h,stream:r,topic:a});const S=this.getConnection(i)?.connectionId;S!==void 0&&this.grantWhenJoined(i,o,S);let y=!1;return()=>{if(y)return;y=!0;const b=this.liveSocketGrants.get(c),v=b?.delete(o)===!0;b?.size===0&&this.liveSocketGrants.delete(c);const C=this.getConnection(i)?.connectionId;v&&C!==void 0&&this.postLiveControl(d,i,{action:"unsubscribe",connectionId:C,stream:r,subscriptionId:o,topic:a}),h()}}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 i=`room:${e.name}`,r=this.whisperSubscribe(i,h=>{t.onMessage(h)},s);let a=!1;const o=[],c=()=>{o.length=0},d=()=>{for(;o.length>0&&this.roomSendsAdmitted(s.shardKey);){if(!this.sendEncodedWhisper(i,o[0],s))return;o.shift()}},l=f(s.shardKey),u=this.roomFlushes.get(l)??new Set;return u.add(d),this.roomFlushes.set(l,u),this.roomIdentityResets.add(c),{close:()=>{a=!0,o.length=0,u.delete(d),u.size===0&&this.roomFlushes.delete(l),this.roomIdentityResets.delete(c),r()},send:h=>{if(a||this.closed||this.WebSocketImpl===void 0)return!1;const p=k(h,`room message for '${i}'`),S=typeof structuredClone=="function"?structuredClone(p):JSON.parse(JSON.stringify(p));return d(),o.length===0&&this.roomSendsAdmitted(s.shardKey)&&this.sendEncodedWhisper(i,S,s)?!0:o.length>=ei?!1:(o.push(S),!0)}}}connectWebSocket(e,t,s={}){if(this.assertLeaderOwnedSurface("connectWebSocket"),this.WebSocketImpl===void 0||this.closed)return{close:()=>{},send:()=>{}};const i=o=>{try{o?.()}catch(c){console.error("[lunora] socket route handler threw",c)}};let r;const a=this.openSupplementarySocket(this.supplementaryUrl(e),{offerBearer:!0,onClose:()=>{clearTimeout(r),i(t.onClose)},onMessage:o=>{let c;try{c=JSON.parse(typeof o.data=="string"?o.data:"")}catch{return}c.type==="message"&&(a.resetBackoff(),i(()=>{t.onMessage(_(c.data))}))},onOpen:()=>{clearTimeout(r);const o=a.socket();r=setTimeout(()=>{a.socket()===o&&a.resetBackoff()},Se),i(t.onOpen)},shardKey:s.shardKey});return{close:()=>{clearTimeout(r),a.close()},send:o=>{const c=JSON.stringify(k(o,`socket message for '${e}'`)),d=a.socket();if(d!==void 0)try{d.send(c)}catch{}}}}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){const t=this.statusListeners.add(e);return e(this.computeStatus()),t}syncStatus(){const e=this.computeStatus(),t=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader();let s=0;for(const r of this.subscriptions.all())(t||this.connectionGateState(r.shardKey).polling?r.valueReceived:r.ack==="acked")||(s+=1);for(const r of this.shapeSubscriptions.values())r.answered||(s+=1);const i=this.offlineQueue.size+this.offlineQueue.replaying;return{connection:e,pendingSubscriptions:s,pendingWrites:i,synced:H(e)&&s===0&&i===0}}onSyncStatus(e){const t=this.syncStatusListeners.add(e),s=this.syncStatus();return this.lastSyncStatus=s,e(s),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 r of s){const a=this.connections.get(r);e.push({confirmedMutationWatermark:t?.get(r)??0,hasSocket:a?.socket!==void 0,shardKey:r===""?void 0:r,wasEverConnected:a?.wasEverConnected??!1,wsState:a?.wsState??"idle"})}const i=this.subscriptions.all().map(r=>({acked:r.ack==="acked",functionPath:r.fn.__lunoraRef,id:r.id,kind:"query",lastMutationId:r.lastMutationId,pendingOptimisticLayers:r.optimisticLayers.length,serverCursor:r.serverCursor,shardKey:r.shardKey,subscriberCount:r.callbacks.size}));for(const r of this.shapeSubscriptions.values())i.push({acked:r.answered,functionPath:`shape:${r.name}`,id:r.id,kind:"shape",lastMutationId:r.lastMutationId,pendingOptimisticLayers:0,rowCount:r.rows.size,serverCursor:r.serverCursor,shardKey:r.shardKey,subscriberCount:r.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((r,a)=>(r.shardKey??"").localeCompare(a.shardKey??"")),subscriptions:i.toSorted((r,a)=>r.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(){const{WebSocketImpl:e}=this;if(e===void 0)return;const t=a=>a.protocol==="wss:"||a.protocol==="https:",s=K(this.wsUrl),i=a=>{const o=K(String(a));return o.host===s.host&&t(o)===t(s)},r=e;return new Proxy(e,{construct:(a,[o,c,...d])=>new r(o,c??(i(o)?this.upgradeProtocols():void 0),...d)})}isCrossTabFollower(){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()}expectsPush(e={}){const t=this.getConnection(e.shardKey);return t===void 0||t.wsState==="open"?!0:t.polling.isPolling()||!t.polling.hasFailedOpen()}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 Ut(this,e,t,s)}whenReady(e={}){return e.signal===void 0?this.readyPromise:we(this.readyPromise,e.signal)}get isReady(){return this.readyResolved}peekHydratedQuery(e,t,s){return this.peekHydratedQueryByKey(e,pe(t),s)}peekHydratedQueryByKey(e,t,s){if(!this.readyResolved)return;const i=M(e,t,s),r=this.hydratedQueryCache.get(i);if(r!==void 0)return this.cachedQueryMatchesIdentity(r)?r.value:void 0}peekActiveQuerySnapshot(e,t,s){const i=g.key(e,t,s),r=this.subscriptions.get(i);return{answered:r!==void 0&&(r.lastValue!==void 0||r.ack==="acked"||r.valueReceived),present:r!==void 0,value:r?.lastValue}}async query(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0,signal:s.signal})}async batch(e){return U(this.rpcTimeoutMs,void 0,async t=>this.sendBatch(e,t))}async mutation(e,t,s={}){if(s.signal?.aborted)throw Ft(s.signal);const{value:i}=await we(this.runMutation(e,t,s),s.signal);return i}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,signal:s.signal,unbounded:!0})}async importRows(e,t,s={}){this.assertOpen();const i=Math.max(1,Math.trunc(s.chunkSize??500)),r=s.toArgs??(l=>({rows:l})),a=t.length;let o=0,c=0,d=0;for(let l=0;l<a;l+=i){const u=t.slice(l,l+i),h=d,{committed:p}=await this.runMutation(e,r(u),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(h)}`},shardKey:s.shardKey});d+=1,o+=u.length,p&&(c+=u.length),s.onProgress?.({done:o,total:a})}return{chunks:d,imported:c,queued:o-c}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const t=this.openSupplementarySocket(w(be(this.url),Qt),{onMessage:s=>{let i;try{i=JSON.parse(typeof s.data=="string"?s.data:"")}catch{return}i.type==="jobs"&&Array.isArray(i.records)&&(t.resetBackoff(),e(i.records.map(r=>W(r))))}});return t.close}resnapshot(e,t,s={}){this.assertOpen();const i=this.subscriptions.get(g.key(e.__lunoraRef,t??{},s.shardKey));i!==void 0&&(this.cancelSubscriptionRetry(i.id),this.resnapshotSubscription(i)&&(i.awaitingSnapshot=!0))}subscribe(e,t,s,i={}){if(this.assertOpen(),i.signal?.aborted)return()=>{};const r=t??{},a=g.key(e.__lunoraRef,r,i.shardKey);let o=this.subscriptions.get(a);const c=z(s),d=z(i.onError),l=z(i.onCheckpoint);if(!o){this.nextSubId+=1;const y=`sub_${this.nextSubId.toString()}`,b=pe(r),v=this.takeHydratedCache(e.__lunoraRef,b,i.shardKey);o={ack:"idle",args:r,argsKey:b,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:y,lastValue:v?.value,optimisticLayers:[],serverBase:v?.value,serverCursor:v?.serverCursor,serverClaims:v?.claims,shardKey:i.shardKey,valueReceived:!1,wireArgs:k(r,`args for '${e.__lunoraRef}'`),...v?.serverEpoch===void 0?{}:{serverEpoch:v.serverEpoch}},this.subscriptions.add(o),this.emitSyncStatus(),this.isCrossTabFollower()&&H(this.computeStatus())&&this.awaitLeaderAnswer(o),v!==void 0&&this.cacheSeededQueries.set(a,v)}o.callbacks.add(c),d&&o.errorCallbacks.add(d),l&&o.checkpointCallbacks.add(l);const u=Qs(o);if(u!==void 0)try{c(u)}catch{}Ht(o,d),this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(o);const h=o;let p=!1;const S=()=>{if(!p&&(p=!0,i.signal?.removeEventListener("abort",S),h.callbacks.delete(c),d&&h.errorCallbacks.delete(d),l&&h.checkpointCallbacks.delete(l),h.callbacks.size===0)){this.sendOrQueueUnsubscribe(h.shardKey,h.id,"unsubscribe"),this.returnCacheSeed(g.keyOf(h)),this.subscriptions.remove(h),this.cancelSubscriptionRetry(h.id);const y=this.getConnection(h.shardKey);y&&this.settleSubscribeWatchdog(y,h.id),this.releaseIdleShard(h.shardKey),this.emitSyncStatus(),this.settleAwaitedAnswer(h,!0)}};return i.signal?.addEventListener("abort",S,{once:!0}),i.signal?.aborted&&S(),S}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 i=`shape_${this.nextShapeId.toString()}`,r={answered:!1,args:e.args,callbacks:new Set([t]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:i,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(i,r),this.emitSyncStatus(),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(r),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(r.shardKey,i,"shape_unsubscribe"),this.releaseIdleShard(r.shardKey),this.emitSyncStatus()}}stream(e,t,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new m("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;const i=`stream_${this.nextStreamId.toString()}`,{shardKey:r}=s,a=t??{},{handle:o,iterable:c}=Dt({maxBuffer:s.maxBuffer,onCancel:()=>{this.cancelStream(i,r)}});this.ensureSocket(r);const d=this.getConnection(r),l={id:i,query:{args:k(a,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:r},type:"stream"},u={durable:s.durable===!0,generation:void 0,handle:o,lastSeq:0,message:l,shardKey:r};this.streams.set(i,u);const h=d?.wsState==="open"&&E(d,l);if(!h&&d===void 0)return this.forgetStream(i),o.fail(new m("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),c;if(!h){for(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=ht;){const S=d.pendingStreams.shift()?.id,y=S?this.streams.get(S):void 0;y&&(y.handle.fail(new m("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(S))}d.pendingStreams.push(l)}return c}httpStream(e,t,s={}){if(this.closed)throw new m("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new m("INTERNAL","LunoraClient: no `fetch` implementation available");const i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return wt(e,t,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:s.maxBuffer,signal:s.signal})}async streamRpc(e,t={},s={}){if(this.closed)throw new m("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new m("INTERNAL","LunoraClient: no `fetch` implementation available");const i=e.__lunoraRef,r=await this.fetchImpl(w(this.url,ke),{body:JSON.stringify({args:k(t,`args for '${i}'`),functionPath:i,shardKey:s.shardKey}),headers:{accept:"text/event-stream",...this.rpcRequestHeaders({},s.shardKey)},method:"POST",...s.signal?{signal:s.signal}:{}});if(!r.ok){const l=await r.json().catch(()=>{});if(l?.error)throw $(l.error);const u=r.statusText?` ${r.statusText}`:"";throw new m("INTERNAL",`LunoraClient: request failed (status ${r.status.toString()}${u})`)}if(!r.body)throw new m("HTTP_STREAM_NO_BODY","LunoraClient: streaming response has no body");const{failure:a,terminal:o}=await ui(r.body,s.signal,s.onFrame);if(a!==void 0)throw a;if(o===void 0)throw new m("HTTP_STREAM_INTERRUPTED","LunoraClient: stream ended without a complete frame");let c;try{c=JSON.parse(o)}catch{throw new m("HTTP_STREAM_BAD_CHUNK","LunoraClient: streaming result is not valid JSON")}if(typeof c!="object"||c===null||!("result"in c))throw new m("HTTP_STREAM_INTERRUPTED","LunoraClient: stream ended without a result");return _(c.result)}close(){this.closed=!0;for(const e of this.pendingSubscriptionRetries.values())clearTimeout(e);this.pendingSubscriptionRetries.clear();for(const e of this.whisperJoins.keys())this.dropWhisperJoinWaiters(e);this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.releasePageHideFlush?.(),this.releasePageHideFlush=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const e of this.streams.values())e.handle.fail(new m("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(),this.supplementaryBounces.clear();for(const e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear(),this.stopOwnClaimsRetry(),this.suspendedFollowerValues.clear();for(const e of this.leaderAnswerTimers.values())clearTimeout(e);this.leaderAnswerTimers.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.syncStatusListeners.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}retirePreviousIdentity(e,t,s,i){const r=Js(e,t,i);return r&&this.discardOptimisticLayers(),this.rejectQueuedForIdentityChange(e),this.warnRefreshWithoutSubject(s,i),r?(this.evictPreviousIdentitySession(),!0):!1}reconcileUpgradeBearer(e,t,s){return!this.authTokenOnUpgrade||t===null||e===t?"none":s?e===null?"cold":"none":e===null?"none":"warm"}upgradeProtocols(){return this.authTokenOnUpgrade&&this.authToken?[vs,Cs(this.authToken)]:void 0}applyUpgradeBearer(e){e==="cold"?(this.resetRoomSends(),this.reconnectCold()):e==="warm"&&this.bounceShardSockets(!0)}assertOpen(){if(this.closed)throw new m("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 m("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),clearTimeout(e.revalidateTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0,e.revalidateTimer=void 0}shardInUse(e){const t=s=>f(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=f(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())},ft))}forgetStream(e){const t=this.streams.get(e);this.streams.delete(e),t&&this.releaseIdleShard(t.shardKey)}teardownConnection(e){e.polling.stop();const t=f(e.shardKey);for(const[i,r]of this.streams)f(r.shardKey)===t&&(r.handle.fail(new m("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(i));e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e),this.clearConnectionTimers(e),clearTimeout(e.idleTimer),e.idleTimer=void 0,N(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={activeShapes:()=>[...this.shapeSubscriptions.values()],activeSubscriptions:()=>this.subscriptions.all(),awaitLeaderAnswers:()=>{this.awaitLeaderAnswers()},broadcastStatus:(s,i)=>this.tabCoordinator?.broadcastConnectionStatus(s,i),closeConnections:()=>{for(const[s,i]of this.connections)this.teardownConnection(i),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,ownClaims:(s,i,r)=>this.followerClaims(s,i,r),queueResubscribe:s=>{this.queueResubscribe(s)},queuedShardKeys:()=>this.queuedOfflineShardKeys,clientIdentifier:()=>this.clientId,dropCacheSeed:s=>{this.dropCacheSeed(s)},ackAndAdvanceCursor:(s,i,r)=>{this.ackAndAdvanceCursor(s,i,r)},settleAwaitedAnswer:(s,i)=>{this.settleAwaitedAnswer(s,i)},subscription:s=>this.subscriptions.get(s)};return new vt({channelName:e,onBecomeLeader:()=>{js(t)},onStopBeingLeader:()=>{Vs(t)},onConnectionStatus:(s,i)=>{Gs(t,s,i)},onSubscriptionData:(s,i,r,a,o,c)=>{Ke(t,s,i,r,a,o,c)},onLeaderClaimAnswered:()=>{$s(t)},onSubscriptionError:(s,i,r,a)=>{je(t,s,i,r,a)},onSubscriptionSettled:(s,i,r,a,o,c,d)=>{Ve(t,s,i,r,a,o,c,d)}})}async sendBatch(e,t){if(this.assertOpen(),!this.fetchImpl)throw new m("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];const s=await this.fetchImpl(w(this.url,X),{body:JSON.stringify({calls:e.map((o,c)=>({args:k(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}),i=s.headers.get("x-d1-bookmark");i&&this.bookmark.set(i);let r;try{r=await s.json()}catch{throw A(new m("INTERNAL",`LunoraClient: batch response was not JSON (status ${s.status.toString()})`),s.headers)}const a=q(r);if(!s.ok||a!==void 0&&!r.results)throw a!==void 0?A($(a),s.headers):A(new m("INTERNAL",`LunoraClient: batch request failed (status ${s.status.toString()})`),s.headers);for(const o of r.results??[]){const c=o.body?.commitCursor;typeof o.id=="number"&&typeof c=="number"&&this.recordShardCursor(e[o.id]?.shardKey,c)}return gs(r.results??[],e.length,s.headers)}async runMutation(e,t,s){this.assertOpen();const i=Ys(e,s),r=t,a=i.mutationId??J();this.mutationIssueCounter+=1;const o=this.mutationIssueCounter,c=this.takeReplayCredential(i.replayCredential),d=this.composedBaselineFor(i.replayBaseline,i.shardKey);this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i);const l=this.identityRetirements,{confirms:u,rollbacks:h}=this.applyOptimisticUpdates(e.__lunoraRef,r,i.shardKey,i.optimistic);this.applyOptionalOptimisticUpdate(i.optimisticUpdate,t,i.shardKey,h,u,()=>this.identityRetirements===l);const p=i.onlineOnly?void 0:this.offlineFlushes.get(f(i.shardKey));p!==void 0&&await p;const{httpFirst:S,midReconnect:y,shouldQueueOffline:b,socketDown:v}=this.writeQueueGate(i.shardKey),C=!i.onlineOnly&&b&&i.replayBaseline===void 0&&this.hasPendingWriteAhead(i.shardKey),Q=async(T=!1)=>this.enqueueOfflineMutation(e,r,i.shardKey,d,a,h,u,T?void 0:i.precondition,i.mutationId,c?.stamp,T,o);if(this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i,h),i.replayBaseline!==void 0&&(v||y)&&(O(h),this.refuseDurableReplayNotSent(v,i.shardKey)),v||y||C)return Q();let G;try{const T=await this.rpc(e.__lunoraRef,r,i.shardKey,{baselineSeq:d,captureBookmark:!0,clientId:i.replayClientId,...c?.flags,mutationId:a,onCommitCursor:F=>{G=F}});for(const F of u)F(G);return{committed:!0,value:T}}catch(T){const F=ai(T,r),Je=S&&b&&F,ze=this.ownSocketOpen(i.shardKey);if(b&&!i.onlineOnly&&this.fetchImpl!==void 0&&!this.outbox&&i.replayBaseline===void 0&&(T instanceof TypeError||T instanceof P)&&oe(r)){const Ye=Q(!0);return this.noteHeldRetryDelay(i.shardKey),this.scheduleRateLimitedRetry(i.shardKey),Ye}throw this.settleFailedDirectWrite(T,G,u,h,c?.flags.authToken),di(i.onlineOnly,Je,F,ze)?Fe(e.__lunoraRef,T):T}}refuseOnlineOnlyWhenDown(e,t,s=[]){if(!t.onlineOnly)return;const i=this.writeQueueGate(t.shardKey);if(i.socketDown||i.midReconnect)throw O(s),Fe(e)}ownSocketOpen(e){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()?!1:this.writeQueueGate(e).socketOpen}writeQueueGate(e){const{hasSocket:t,idleClosed:s,polling:i,wasEverConnected:r,wsState:a}=this.connectionGateState(e),{queueBeforeFirstConnect:o}=this.offlineQueue,c=r||o,d=this.WebSocketImpl!==void 0&&c,l=i||s;return{httpFirst:l,midReconnect:a==="connecting"&&c&&!l,shouldQueueOffline:d,socketDown:a!=="open"&&!t&&d&&!l,socketOpen:a==="open"}}settleFailedDirectWrite(e,t,s,i,r){if(this.noteIdentityMismatch(e),r!==void 0&&this.noteReplayAuthRefusal(e,r),x(e)){for(const a of s)a(t);return}O(i)}async delegateToOutbox(e,t,s,i,r,a,o,c){this.outboxMutationCounter+=1;const d=this.outboxMutationCounter;try{await e.enqueue({args:s,baselineSeq:r,clientId:this.clientId,functionPath:t,idempotencyKey:o??`${this.clientId}:${J()}`,identity:c,mutationId:d,...a.length>0&&{onRejected:()=>{O(a)}},shardKey:i})}catch(l){if(l instanceof Lt)return!1;throw O(a),l instanceof Error?l:new Error(String(l))}return!0}async enqueueOfflineMutation(e,t,s,i,r,a,o,c,d,l,u,h){const p=l===void 0?this.identityFingerprint():l;if(this.outbox&&await this.delegateToOutbox(this.outbox,e.__lunoraRef,t,s,i,a,d,p)){for(const y of o)y(void 0);return{committed:!1,value:void 0}}if(this.closed)throw O(a),new m("CLIENT_CLOSED","LunoraClient closed");return{committed:!0,value:await new Promise((y,b)=>{const v={ambiguousSend:u,args:t,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:r,issueSeq:h,clientId:this.clientId,identity:p,precondition:this.holdWhileUnanswered(c),onCommit:C=>{for(const Q of o)Q(C)},reject:C=>{this.queuedIdentities.delete(r),x(C)||O(a),b(C instanceof Error?C:new Error(String(C))),this.releaseIdleShard(s)},resolve:y,shardKey:s};this.offlineQueue.enqueue(v),this.queuedOfflineShardKeys.add(s),this.ensureSocket(s),v.id!==void 0&&this.queuedIdentities.set(v.id,p),this.outbox!==void 0&&!u&&H(this.computeStatus())&&this.flushOfflineQueue(s).catch(()=>{})})}}hasPendingWriteAhead(e){const t=f(e);return(this.outbox?.pending?.()??!1)||this.offlineQueue.hasPending(s=>f(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=this.queryCacheEpoch,t=await this.queryCache.load();if(e!==this.queryCacheEpoch)return;const s=new Map;for(const i of this.subscriptions.all())s.set(M(i.fn.__lunoraRef,i.argsKey,i.shardKey),i);for(const{key:i,...r}of t){if(Et(this.persistenceVersion,r.version)){this.queryCache.remove(i).catch(()=>{});continue}const a=s.get(i);if(a&&this.cachedQueryMatchesIdentity(r)){this.seedSubscriptionFromCache(a,r);continue}this.hydratedQueryCache.set(i,r)}}catch{}}seedSubscriptionFromCache(e,t){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(t)||(e.serverBase=t.value,e.serverCursor=t.serverCursor,e.serverClaims=t.claims,t.serverEpoch!==void 0&&(e.serverEpoch=t.serverEpoch),this.cacheSeededQueries.set(M(e.fn.__lunoraRef,e.argsKey,e.shardKey),t),R(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.serverBaseCommitted=!1,s.serverCursor=void 0,s.serverEpoch=void 0,R(s,void 0)),this.hydratedQueryCache.set(e,t)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,t,s){const i=M(e,t,s),r=this.hydratedQueryCache.get(i);if(!(r===void 0||!this.cachedQueryMatchesIdentity(r)))return this.hydratedQueryCache.delete(i),r}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(const e of this.subscriptions.all()){const t=M(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=M(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,r=i===void 0?this.identityFingerprint():i;r===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(s,{identity:r,serverCursor:e.serverCursor,ts:Date.now(),value:t,...e.serverClaims===void 0?{}:{claims:e.serverClaims},...r===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(()=>{})},pt))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;const{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}const t=[...this.pendingCacheWrites.entries()],{queryCacheEpoch:s}=this;this.pendingCacheWrites.clear();const i=this.queryCacheChain.then(async()=>s===this.queryCacheEpoch?Promise.allSettled(t.map(async([r,a])=>e.put(r,a))):void 0);this.queryCacheChain=i.catch(()=>{}),await i}installPageHideFlush(){const e=globalThis;if(!this.persistence&&!this.queryCache||!("document"in globalThis)||typeof e.addEventListener!="function")return;const t=()=>{this.offlineQueue.flushUnpersisted(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.flushQueryCacheWrites().catch(()=>{}))},s=()=>{e.document?.visibilityState==="hidden"&&t()};e.addEventListener("pagehide",t),e.document?.addEventListener("visibilitychange",s),this.releasePageHideFlush=()=>{e.removeEventListener?.("pagehide",t),e.document?.removeEventListener("visibilitychange",s)}}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=f(e);let s;for(const i of this.subscriptions.all())f(i.shardKey)!==t||i.serverCursor===void 0||(s=s===void 0?i.serverCursor:Math.max(s,i.serverCursor));return s}composedBaselineFor(e,t){return e===void 0?this.baselineCursorFor(t):e??void 0}async pollSubscriptions(e){const t=f(e),s=[];for(const o of this.subscriptions.all())f(o.shardKey)===t&&(oe(o.args)?s.push(o):(this.markQueryRejected(o,!0),o.refusal={code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"},D(o,o.refusal)));if(s.length===0)return this.probeOrigin();const i=Ot(),r=this.identityFingerprint();let a;try{a=await Oe(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()!==r)return!0;for(const[o,c]of s.entries()){const d=a[o];if(d!==void 0){if(!d.ok){this.markQueryRejected(c,!0),c.refusal={code:d.error.code,message:d.error.message},D(c,c.refusal);continue}this.handleDataMessage({data:le(d.value),id:c.id,type:"data"},i)}}return!0}async probeOrigin(){const{fetchImpl:e}=this;if(!e)return!1;try{return await Oe(async t=>e(w(this.url,X),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:t})),!0}catch{return!1}}emitSyncStatus(){if(this.syncStatusListeners.size===0)return;const e=this.syncStatus(),t=this.lastSyncStatus;t?.connection===e.connection&&t.pendingSubscriptions===e.pendingSubscriptions&&t.pendingWrites===e.pendingWrites&&t.synced===e.synced||(this.lastSyncStatus=e,this.syncStatusListeners.emit(e))}emitConnectionStatus(){const e=this.computeStatus();this.emitSyncStatus(),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,i){const r=[],a=[];if(!i)return{confirms:r,rollbacks:a};const o=g.key(e,t,s),c=this.subscriptions.get(o);if(c){const d=_t(c,i);d&&(r.push(d.confirm),a.push(d.rollback))}return{confirms:r,rollbacks:a}}applyOptionalOptimisticUpdate(e,t,s,i,r,a){e&&this.applyOptimisticUpdate(e,t,s,i,r,a)}applyOptimisticUpdate(e,t,s,i,r,a){const{confirms:o,rollbacks:c,store:d}=Tt(this.subscriptions,s,a);try{e(d,t)}catch{O(c);return}i.push(...c),r.push(...o)}getConnection(e){return this.connections.get(f(e))}sendOrQueueUnsubscribe(e,t,s){const i=this.getConnection(e);i&&!E(i,{id:t,type:s})&&i.pendingUnsubscribes.push({id:t,type:s})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let i="idle";return this.leader.status==="connected"?i="open":this.leader.status==="connecting"&&(i="connecting"),{hasSocket:!1,idleClosed:!1,polling:this.leader.status==="polling",wasEverConnected:this.leader.wasEverConnected,wsState:i}}const t=this.getConnection(e),s=t===void 0&&this.idleClosedShards.has(f(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=f(e);let s=this.connections.get(t);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:_s({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:()=>{this.flushOfflineQueue(e).catch(()=>{})},onStateChange:()=>{this.emitConnectionStatus()},poll:async()=>this.pollSubscriptions(e)}),reconnect:ge(this.reconnectOptions),reconnectTimer:void 0,resubscribeQueue:[],resubscribeSlots:new Set,shardKey:e,socket:void 0,stableTimer:void 0,unackedWatchdogs:new Map,wasEverConnected:this.idleClosedShards.delete(t),wsState:"idle"},this.connections.set(t,s)),s}openSupplementarySocket(e,t){if(this.WebSocketImpl===void 0||this.closed)return{close:()=>{},resetBackoff:()=>{},socket:()=>{}};const s=ge(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let r,a=!1;const o=()=>{a||this.closed||(r=setTimeout(h,s.next()))},c=y=>{a||this.WebSocketImpl===void 0||Ie(i,this.wsUrlFor(t.shardKey,y,e),this.managedSocketOptions,{onClose:b=>{b?.code===4001&&this.notifyTokenExpired(),o(),t.onClose?.()},onMessage:t.onMessage,...t.onOpen===void 0?{}:{onOpen:t.onOpen},...t.offerBearer===!0?{protocols:this.upgradeProtocols()}:{}})};let d=0,l;const u=async y=>{const b=this.wsCredentialGeneration;d+=1;const v=d;let C;l=b;try{C=await ri(y,ii)}catch{v===d&&(l=void 0,o());return}if(v===d){if(l=void 0,b!==this.wsCredentialGeneration){h();return}c(C)}},h=()=>{if(a||this.WebSocketImpl===void 0)return;const{wsTicket:y}=this;if(typeof y=="function"){u(y).catch(()=>{});return}c(y)};h();const p=()=>{a=!0,r!==void 0&&(clearTimeout(r),r=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),N(i);const{socket:y}=i;i.socket=void 0;try{y?.close()}catch{}};this.adminSocketTeardowns.add(p);const S=()=>{const{socket:y}=i;if(y===void 0){l!==void 0&&l!==this.wsCredentialGeneration&&(d+=1,l=void 0,h());return}i.socket=void 0,i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),N(i);try{y.close()}catch{}t.onClose?.(),o()};return this.supplementaryBounces.add(S),{close:()=>{p(),this.adminSocketTeardowns.delete(p),this.supplementaryBounces.delete(S)},resetBackoff:()=>{s.reset()},socket:()=>i.socket}}supplementaryUrl(e){const t=K(this.wsUrl),s=t.pathname.endsWith(Z)?t.pathname.slice(0,-Z.length):t.pathname;return t.pathname=w(s,e),Ce(t,this.wsUrl)}wsUrlFor(e,t,s=this.wsUrl){const i=K(s);if(e===void 0&&t===void 0&&!i.searchParams.has("token"))return s;const r=new Set([...e===void 0?[]:["shard"],"token"]),a=[...i.searchParams].filter(([o])=>!r.has(o)).map(([o,c])=>`${encodeURIComponent(o)}=${encodeURIComponent(c)}`);return e!==void 0&&a.push(`shard=${encodeURIComponent(e)}`),t!==void 0&&a.push(`token=${encodeURIComponent(t)}`),i.search=a.join("&"),Ce(i,s)}rpcRequestHeaders(e,t){const s={"content-type":"application/json"};e.expectSubject!==void 0&&(s[rs]=ns(e.expectSubject));const i=this.shardCursors.get(this.cursorKeyFor(t));i!==void 0&&(s["x-lunora-min-seq"]=i.toString());const r=e.authToken===void 0?this.authToken:e.authToken;if(r&&(s.authorization=`Bearer ${r}`),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,i={}){const{fetchImpl:r}=this;if(!r)throw new P("LunoraClient: no `fetch` implementation available");const a=this.rpcRequestHeaders(i,s),o=i.authToken===void 0?this.authToken:i.authToken,c=JSON.stringify({args:k(t,`args for '${e}'`),functionPath:e,shardKey:s}),{body:d,response:l}=await U(i.unbounded?0:this.rpcTimeoutMs,i.signal,async p=>{const S=await r(w(this.url,ke),{body:c,headers:a,method:"POST",signal:p});try{return{body:await S.json(),response:S}}catch{return{body:void 0,response:S}}});if(i.captureBookmark){const p=l.headers.get("x-d1-bookmark");p&&this.bookmark.set(p)}if(d===void 0)throw B(l.status,l.statusText,l.headers);const u=d;if(typeof u!="object"||u===null||Array.isArray(u))throw B(l.status,l.statusText,l.headers);const h=q(d);if(h!==void 0)throw me(h,l.headers);if(!l.ok)throw B(l.status,l.statusText,l.headers);i.onMutationAck?.(d.lastMutationId),i.onCommitCursor?.(d.commitCursor),this.noteCredentialAccepted(o),this.learnDefaultShardKey(l,s),this.recordShardCursor(s,d.commitCursor);try{return _(d.result)}catch(p){throw A(ue(p),l.headers)}}async adminFetch(e,t,s,i){if(!this.fetchImpl)throw new m("INTERNAL","LunoraClient: no `fetch` implementation available");const r={};this.authToken&&(r.authorization=`Bearer ${this.authToken}`);const a=s instanceof ArrayBuffer||s instanceof Blob;let o;s===void 0?o=void 0:a?(o=s,i!==void 0&&(r["content-type"]=i)):(o=JSON.stringify(s),r["content-type"]="application/json");const c=await this.fetchImpl(w(this.url,e),{body:o,headers:r,method:t});let d;try{d=await c.json()}catch{const u=c.statusText?` ${c.statusText}`:"";throw new m("INTERNAL",`LunoraClient: response was not JSON (status ${c.status.toString()}${u})`)}const l=q(d);if(l!==void 0)throw $({...l,message:l.message??"admin request failed"});if(!c.ok){const u=c.statusText?` ${c.statusText}`:"";throw new m("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(f(e.shardKey));E(e,{caps:Xs,clientId:this.clientId,id:"connect",type:"connect",...t===void 0?{}:{context:t},...e.sessionToken===void 0?{}:{token:e.sessionToken}})}resendShapeSubscriptions(e){for(const t of this.shapeSubscriptions.values())f(t.shardKey)===f(e)&&this.sendShapeSubscribeIfOpen(t)}refuseDurableReplayNotSent(e,t){throw e&&this.ensureSocket(t),oi()}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const t=this.getOrCreateConnection(e);t.wsState==="open"||t.wsState==="connecting"||(t.wsState="connecting",this.emitConnectionStatus(),this.startShardSocket(t,e).catch(()=>{this.handleDisconnect(t)}))}applyWsCredentialChange(){this.wsCredentialGeneration+=1,this.resetRoomSends(),this.bounceShardSockets()}async startShardSocket(e,t){const{wsToken:s,wsTicket:i}=this;if(typeof s=="function"||typeof i=="function"){await this.openSocketWithProvidedCredentials(e,t);return}this.openSocket(e,t,{session:s,ticket:i})}async openSocketWithProvidedCredentials(e,t){const s=this.wsCredentialGeneration,i=Symbol("ws-token-attempt");let r;e.providerAttempt=i;try{r=await U(this.connectTimeoutMs,void 0,async()=>({session:await ie(this.wsToken),ticket:await ie(this.wsTicket)}),()=>new Error("LunoraClient: ws credential provider timed out"))}catch{e.providerAttempt===i&&(e.providerAttempt=void 0,this.handleDisconnect(e));return}if(e.providerAttempt===i&&(e.providerAttempt=void 0,!(this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0))){if(s!==this.wsCredentialGeneration){await this.startShardSocket(e,t);return}this.openSocket(e,t,r)}}openSocket(e,t,s){if(this.WebSocketImpl===void 0)return;e.providerAttempt=void 0,e.identity=this.identityFingerprint(),e.ticketed=s.ticket!==void 0,e.upgradeBearer=this.authTokenOnUpgrade?this.authToken??void 0:void 0,s.ticket===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.sessionToken=s.session,e.retired=!1;const i=this.wsCredentialGeneration;Ie(e,this.wsUrlFor(t,s.ticket),this.managedSocketOptions,{onClose:r=>{r?.code===4003&&e.polling.noteFailedOpen(),r?.code===ms&&r.reason===ys?e.retired!==!0&&!this.closed&&this.retireChangedClaims():r?.code===4001?this.notifyTokenExpired():r?.code===4003&&r.reason!=="connect deadline"&&i===this.wsCredentialGeneration&&this.refusedCredentialGeneration!==i&&(this.refusedCredentialGeneration=i,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.reauthPending=!1,e.claims=void 0,e.heldFrames=void 0,e.roomsRejoined=!1,clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},Se),this.sendConnectEnvelope(e),this.markShardPendingAck(t,!0),this.emitConnectionStatus(),this.clearResubscribeQueue(e);for(const o of this.subscriptions.all())f(o.shardKey)===f(t)&&this.queueResubscribe(o);if(this.resendShapeSubscriptions(t),e.pendingUnsubscribes.length>0){const o=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(const{id:c,type:d}of o)E(e,{id:c,type:d});this.releaseIdleShard(t)}Ts(e);const r=f(t),a=this.whisperHandlers.get(r);if(this.dropWhisperJoinWaiters(r),this.whisperJoins.set(r,new Map),a)for(const o of a.keys())this.sendWhisperJoin(e,r,o);e.roomsRejoined=!0,this.releaseRoomSends(t),this.flushOfflineQueue(t).catch(()=>{})},protocols:this.upgradeProtocols()})}cancelStream(e,t){const s=this.getConnection(t);s&&(s.pendingStreams=s.pendingStreams?.filter(i=>i.id!==e),E(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(),N(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",e.connectionId=void 0,e.heldFrames=void 0,e.whisperAck=void 0,this.dropWhisperJoinWaiters(f(e.shardKey)),this.markShardPendingAck(e.shardKey),this.emitConnectionStatus(),this.clearResubscribeQueue(e);const t=new Set((e.pendingStreams??[]).map(i=>i.id));for(const[i,r]of this.streams)if(!(f(r.shardKey)!==f(e.shardKey)||t.has(i))){if(r.durable){const a={...r.message,...r.generation===void 0?{}:{generation:r.generation},sinceChunk:r.lastSeq};r.message=a,e.pendingStreams=[...(e.pendingStreams??[]).filter(o=>o.id!==i),a];continue}r.handle.fail(new m("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.forgetStream(i)}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,t=!1){const s=f(e);for(const i of this.subscriptions.all())f(i.shardKey)===s&&(this.cancelSubscriptionRetry(i.id),I(i,"idle"),i.pendingDeltaRun=void 0,t&&(i.valueReceived=!1,this.awaitingAnswer.add(i),this.answeredUnreadable.delete(i)));for(const i of this.shapeSubscriptions.values())f(i.shardKey)===s&&(i.answered=!1)}queueResubscribe(e){const t=this.getConnection(e.shardKey);t&&(t.resubscribeQueue.push(e),this.drainResubscribeQueue(t))}drainResubscribeQueue(e){for(;e.resubscribeSlots.size<mt;){const t=e.resubscribeQueue.shift();if(!t)return;this.subscriptions.getById(t.id)&&this.sendSubscribeIfOpen(t)&&e.resubscribeSlots.add(t.id)}}settleSubscribeWatchdog(e,t){clearTimeout(e.unackedWatchdogs.get(t)),e.unackedWatchdogs.delete(t),e.resubscribeSlots.delete(t)&&this.drainResubscribeQueue(e)}clearResubscribeQueue(e){for(const t of e.unackedWatchdogs.values())clearTimeout(t);e.unackedWatchdogs.clear(),e.resubscribeSlots.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e,t=!1){const s=this.getConnection(e.shardKey);if(s?.wsState!=="open"||e.ack==="acked"||!t&&e.ack==="inflight")return!1;const i=e.serverCursor!==void 0&&e.serverBase!==void 0,r=E(s,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...i?{sinceSeq:e.serverCursor}:{},...i&&e.serverClaims!==void 0?{sinceClaims:e.serverClaims}:{},...i&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"});return r&&I(e,"inflight"),r&&!t&&this.armUnackedWatchdog(s,e),r}armUnackedWatchdog(e,t,s=!1){clearTimeout(e.unackedWatchdogs.get(t.id)),e.unackedWatchdogs.set(t.id,setTimeout(()=>{if(s){e.unackedWatchdogs.delete(t.id),Y(t),this.settleAwaitedAnswer(t,!1);return}const i=t.ack!=="acked"&&this.subscriptions.getById(t.id)===t&&this.sendSubscribeIfOpen(t,!0);this.settleSubscribeWatchdog(e,t.id),i?this.armUnackedWatchdog(e,t,!0):Y(t)},ve))}sendShapeSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);t?.wsState==="open"&&E(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.serverCursor===void 0||e.serverClaims===void 0?{}:{sinceClaims:e.serverClaims},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,t){const s=Es(e);if(s===void 0)return;let i;try{i=JSON.parse(s)}catch{return}const r=this.getConnection(t);if(i.type!=="error"&&r?.reconnect.reset(),r&&typeof i.id=="string"&&this.settleSubscribeWatchdog(r,i.id),i.type==="batchStart")r&&(r.heldFrames=[]);else if(i.type==="batchEnd"){const a=r?.heldFrames;if(r&&a){const{socket:o}=r;r.heldFrames=void 0,Rt(()=>{for(const c of a){if(r.retired===!0||r.socket!==o)break;this.dispatchServerMessage(c,t)}},()=>!this.closed)}}else r?.heldFrames&&Zs(i)?r.heldFrames.push(i):this.dispatchServerMessage(i,t)}dispatchServerMessage(e,t){switch(e.type){case"ack":{const s=this.subscriptions.getById(e.id);s&&this.ackAndAdvanceCursor(s,void 0,void 0);return}case"chunk":{const{data:s,generation:i,id:r,seq:a}=e,o=this.streams.get(r);o&&typeof a=="number"&&(o.lastSeq=a,typeof i=="number"&&(o.generation=i),o.durable=!0),o?.handle.push(_(s));return}case"complete":{this.handleCompleteMessage(e.id);return}case"data":case"delta":{this.withFrameClaims(t,()=>{this.handleDataMessage(e)});return}case"error":{this.handleErrorMessage(e,t);break}case"identity":{this.handleIdentityFrame(e,t),this.adoptSocketConnectionId(e,t),this.confirmShardIdentity(t);break}case"live":{this.dispatchLive(e,t);break}case"pokeEnd":{this.withFrameClaims(t,()=>{this.handlePokeEnd(e,t)});break}case"pokePart":{this.pokeAssembler.part(t,e);break}case"pokeStart":{this.pokeAssembler.start(t,e);break}case"resume":{this.withFrameClaims(t,()=>{this.handleResumeMessage(e)});break}case"settled":{this.handleSettledMessage(e);break}case"whisper":{this.dispatchWhisper(e,t);break}case"whisper_subscribed":{this.acknowledgeWhisperJoin(f(t),e.topic);break}}}handleErrorMessage(e,t){const s=e.error?.code;if(s==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}if(s==="STREAM_ID_IN_USE")return;const{id:i}=e,r=i===void 0?void 0:this.streams.get(i);if(r&&i!==void 0){r.handle.fail(rt(e)),this.forgetStream(i);return}const a=i===void 0?void 0:this.subscriptions.getById(i);if(a){Y(a);const c=ye(e),d=this.identityFingerprint(),l=g.keyOf(a),u=this.getConnection(t)?.claims;this.markQueryRejected(a),a.refusal=c,this.scheduleSubscriptionRetry(a,e.error?.retryAfterMs),D(a,c),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(l,c,d,u);return}const o=i===void 0?void 0:this.shapeSubscriptions.get(i);o&&(o.answered||(o.answered=!0,this.emitSyncStatus()),he(o.errorCallbacks,ye(e)))}markQueryRejected(e,t=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()||this.connectionGateState(e.shardKey).polling){this.settleAwaitedAnswer(e,!1),!(t?e.valueReceived:e.ack==="acked")&&(t?e.valueReceived=!0:I(e,"acked"),this.emitSyncStatus())}handlePokeEnd(e,t){const s=this.pokeAssembler.end(t,e.pokeId);if(s){Ws(this.shapeSubscriptions,s);for(const i of s.parts.keys()){const r=this.shapeSubscriptions.get(i);r&&!s.undecodable.has(i)&&this.applyPokePart(r,s,e)}}}applyPokePart(e,t,s){const i=e.answered,r=Bs(e,t,s);if(e.answered!==i&&this.emitSyncStatus(),Pe(e),r==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.serverClaims=this.frameClaims,e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){return I(e,"idle"),e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,this.emitSyncStatus(),this.sendSubscribeIfOpen(e)}scheduleSubscriptionRetry(e,t){if(this.cancelSubscriptionRetry(e.id),this.closed||typeof t!="number"||!Number.isFinite(t)||t<0)return;const s=setTimeout(()=>{this.pendingSubscriptionRetries.delete(e.id),!this.closed&&this.subscriptions.getById(e.id)===e&&this.resnapshotSubscription(e)&&(e.awaitingSnapshot=!0)},t);this.pendingSubscriptionRetries.set(e.id,s)}cancelSubscriptionRetry(e){const t=this.pendingSubscriptionRetries.get(e);t!==void 0&&(clearTimeout(t),this.pendingSubscriptionRetries.delete(e))}resnapshotDiscardedRun(e){const{serverCursor:t,serverEpoch:s}=e;e.baseIncomplete=!0,this.resnapshotSubscription(e)&&(e.awaitingSnapshot=!0),e.serverCursor=t,e.serverEpoch=s}failUndecodableFrame(e,t,s){D(e,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription — ${t instanceof Error?t.message:String(t)}`}),s&&this.subscriptions.getById(e.id)===e&&this.resnapshotDiscardedRun(e),this.settleAwaitedAnswer(e,!1)}handleDataMessage(e,t){const{id:s}=e,i=s?this.subscriptions.getById(s):void 0;if(!i||e.type==="data"&&xs(i,e)||e.type==="delta"&&i.baseIncomplete===!0)return;this.cancelSubscriptionRetry(i.id);let r;const a=i.pendingDeltaRun;try{r=Ze(e,a===void 0?i.serverBase:a.payload)}catch(c){i.pendingDeltaRun=void 0,this.failUndecodableFrame(i,c,e.type==="delta");return}if(r===et){console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.resnapshotSubscription(i);return}if(qs(e)){i.pendingDeltaRun={payload:r};return}i.pendingDeltaRun=void 0,this.dropCacheSeed(g.keyOf(i));const o=t!==void 0&&!i.valueReceived;if(qe(i,r,{claims:this.frameClaims,cursor:e.cursor,epoch:e.epoch}),i.refusal=void 0,o&&(i.valueReceived=!0,this.emitSyncStatus()),e.lastMutationId!==void 0&&(ce(i,e.lastMutationId),de(i,!0)),this.persistQueryValue(i),ne(i,i.serverCursor),t!==void 0&&It(i,t),R(i,r),this.tabCoordinator?.isLeader()){const c=g.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(c,r,i.serverCursor,i.serverEpoch,this.identityFingerprint(),i.serverClaims)}this.settleAwaitedAnswer(i,!0)}followerClaims(e,t,s){if(this.identityFingerprint()===null&&!this.identityUnresolved())return null;if(s==="")return(this.ownClaimsValue===void 0||this.ownClaimsValue!==null&&!this.claimsVerifiedAgainst.has(""))&&(this.claimsVerifiedAgainst.add(""),this.heldLeaderFrames.set(e,t),this.fetchOwnClaims()),this.ownClaimsValue;if(this.ownClaimsValue===void 0)this.heldLeaderFrames.set(e,t),this.fetchOwnClaims();else if(s!==void 0&&s!==this.ownClaimsValue&&!this.claimsVerifiedAgainst.has(s)){this.claimsVerifiedAgainst.add(s),this.heldLeaderFrames.set(e,t),this.fetchOwnClaims();return}return this.ownClaimsValue}isFollowerTab(){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()}resetOwnClaims(){this.ownClaimsValue=void 0,this.ownClaimsFetch=void 0,this.claimsVerifiedAgainst.clear(),this.stopOwnClaimsRetry(),this.suspendFollowerValues(),this.heldLeaderFrames.size>0&&queueMicrotask(()=>{this.fetchOwnClaims()})}suspendFollowerValues(){if(this.isFollowerTab())for(const e of this.subscriptions.all())e.serverClaims!==void 0&&e.serverBase!==void 0&&this.suspendedFollowerValues.set(e,{base:e.serverBase,claims:e.serverClaims,cursor:e.serverCursor,epoch:e.serverEpoch}),e.serverClaims!==void 0&&(e.serverBase=void 0,e.serverBaseCommitted=!1,e.serverCursor=void 0,e.serverClaims=void 0,R(e,void 0))}applyOwnClaims(e){e!==this.ownClaimsValue&&this.claimsVerifiedAgainst.clear(),this.ownClaimsValue=e,this.ownClaimsFailures=0;for(const[t,s]of this.suspendedFollowerValues)s.claims===e&&t.serverBase===void 0&&(t.serverBase=s.base,t.serverCursor=s.cursor,t.serverEpoch=s.epoch,t.serverClaims=e,R(t,s.base));this.suspendedFollowerValues.clear();for(const t of this.subscriptions.all())t.serverClaims!==void 0&&t.serverClaims!==e&&(t.serverBase=void 0,t.serverBaseCommitted=!1,t.serverCursor=void 0,t.serverClaims=void 0,R(t,void 0));this.dropClaimedEntries(e),this.releaseHeldFrames()}releaseHeldFrames(){const e=[...this.heldLeaderFrames.values()];this.heldLeaderFrames.clear();for(const t of e)t()}dropClaimedEntries(e){for(const t of[this.hydratedQueryCache,this.cacheSeededQueries])for(const[s,i]of t)if(i.claims!==void 0&&i.claims!==e){t.delete(s),this.pendingCacheWrites.delete(s);const{queryCache:r}=this;r&&(this.queryCacheChain=this.queryCacheChain.then(async()=>r.remove(s)).catch(()=>{}))}}fetchOwnClaims(){const{authToken:e,fetchImpl:t}=this;if(t===void 0||this.ownClaimsFetch!==void 0)return;const s=re(t,w(this.url,Ss),"{}",e===null||!this.authTokenOnUpgrade?{"content-type":"application/json"}:{authorization:`Bearer ${e}`,"content-type":"application/json"}).then(({status:i,text:r})=>{const{claims:a}=JSON.parse(r);this.ownClaimsFetch===s&&(typeof a=="string"?this.applyOwnClaims(a):i===200&&(this.ownClaimsValue=null,this.releaseHeldFrames()))}).catch(()=>{this.ownClaimsFetch===s&&this.scheduleOwnClaimsRetry()}).finally(()=>{this.ownClaimsFetch===s&&(this.ownClaimsFetch=void 0)});this.ownClaimsFetch=s}scheduleOwnClaimsRetry(){if(this.closed||this.heldLeaderFrames.size===0||this.ownClaimsRetryTimer!==void 0||this.ownClaimsFailures>=ti)return;const e=si*2**this.ownClaimsFailures;this.ownClaimsFailures+=1,this.ownClaimsRetryTimer=setTimeout(()=>{this.ownClaimsRetryTimer=void 0,this.fetchOwnClaims()},e)}stopOwnClaimsRetry(){clearTimeout(this.ownClaimsRetryTimer),this.ownClaimsRetryTimer=void 0,this.ownClaimsFailures=0}withFrameClaims(e,t){this.frameClaims=this.getConnection(e)?.claims;try{t()}finally{this.frameClaims=void 0}}handleResumeMessage(e){const t=this.subscriptions.getById(e.id);t&&(t.pendingDeltaRun=void 0,t.awaitingSnapshot=!1,t.baseIncomplete=!1,t.serverClaims=this.frameClaims,this.ackAndAdvanceCursor(t,e.cursor,e.epoch),this.tabCoordinator?.isLeader()&&t.serverBase!==void 0&&this.tabCoordinator.broadcastSubscriptionData(g.keyOf(t),t.serverBase,t.serverCursor,t.serverEpoch,this.identityFingerprint(),t.serverClaims),this.settleAwaitedAnswer(t,!0))}handleSettledMessage(e){const t=this.subscriptions.getById(e.id);if(!t)return;const s=t.pendingDeltaRun!==void 0;if(s&&(t.pendingDeltaRun=void 0,this.resnapshotDiscardedRun(t)),!(s||t.baseIncomplete===!0)&&(this.ackAndAdvanceCursor(t,e.cursor,e.epoch),e.lastMutationId!==void 0&&ce(t,e.lastMutationId),de(t),this.tabCoordinator?.isLeader())){const i=g.keyOf(t);this.tabCoordinator.broadcastSubscriptionSettled(i,t.serverCursor,t.serverEpoch,t.lastMutationId,this.clientId,this.identityFingerprint(),t.serverClaims)}}ackAndAdvanceCursor(e,t,s){this.cancelSubscriptionRetry(e.id);const i=e.ack!=="acked";I(e,"acked"),i&&this.emitSyncStatus(),(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),ne(e,e.serverCursor)&&R(e,e.serverBase))}adoptSocketConnectionId(e,t){const s=this.getConnection(t);if(s===void 0||typeof e.connectionId!="string")return;const i=s.connectionId===e.connectionId;s.connectionId=e.connectionId,s.claims=e.claims,s.whisperAck=e.whisperAck===!0,(!i||s.revalidateTimer===void 0&&s.reauthPending!==!0)&&this.armSocketRevalidation(s,e.revalidateMs);for(const r of this.liveSocketGrants.get(f(t))?.keys()??[])this.grantWhenJoined(t,r,e.connectionId)}grantWhenJoined(e,t,s){const i=f(e),r=this.liveSocketGrants.get(i)?.get(t);if(r===void 0)return;const{stream:a,topic:o}=r,c=()=>{this.liveSocketGrants.get(i)?.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},l=>{this.refuseLiveGrant(e,t,l,s)})};this.getConnection(e)?.whisperAck===!0?this.whenWhisperJoined(i,o,c):c()}sendWhisperJoin(e,t,s){const i=this.whisperJoinState(t,s);i.pending+=1,i.joined=!1,E(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 i of s.waiters.splice(0))clearTimeout(i.timer),i.run();this.releaseWhisperJoin(e,t)}}releaseWhisperJoin(e,t){if(this.whisperHandlers.get(e)?.has(t)===!0)return;const s=this.whisperJoins.get(e),i=s?.get(t);if(!(s===void 0||i===void 0||i.pending>0)){for(const r of i.waiters.splice(0))clearTimeout(r.timer);s.delete(t),s.size===0&&this.whisperJoins.delete(e)}}whenWhisperJoined(e,t,s){const i=this.whisperJoinState(e,t);if(i.joined){s();return}const r={run:s,timer:void 0};r.timer=setTimeout(()=>{i.waiters=i.waiters.filter(a=>a!==r),s()},Ge),i.waiters.push(r)}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 i=s.get(t);return i===void 0&&(i={joined:!1,pending:0,waiters:[]},s.set(t,i)),i}refuseLiveGrant(e,t,s,i){const r=f(e),a=this.liveSocketGrants.get(r),o=a?.get(t);a===void 0||o===void 0||this.getConnection(e)?.connectionId!==i||(a.delete(t),a.size===0&&this.liveSocketGrants.delete(r),o.release(),o.onError?.({status:s,topic:o.topic}))}postLiveControl(e,t,s,i){const{fetchImpl:r}=this;if(!r)return;const a=JSON.stringify(t===void 0?s:{...s,shardKey:t}),o=this.rpcRequestHeaders({},t);this.liveControlChain=this.liveControlChain.then(()=>re(r,w(this.url,e),a,o)).then(({status:c})=>{c>=400&&c<500&&c!==404&&c!==401&&i?.(c)}).catch(()=>{})}dispatchLive(e,t){const s=this.liveSocketGrants.get(f(t));if(!s)return;const i=_(e.data);for(const r of s.values())if(!(r.stream!==e.stream||r.topic!==e.topic))try{r.onEvent(i)}catch{}}dispatchWhisper(e,t){const s=this.whisperHandlers.get(f(t))?.get(e.topic);if(!s)return;const i=_(e.data);for(const r of s)try{r(i,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&&(I(s,"idle"),this.emitSyncStatus(),D(s,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&(this.replayAttempts.delete(e),this.offlineQueue.discard(e))}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const e=this.authToken;return e===null?null:(this.tokenFingerprint?.token!==e&&(this.tokenFingerprint={hash:this.hashToken(e),token:e}),this.tokenFingerprint.hash)}hashToken(e){let t=2166136261,s=5381;for(let i=0;i<e.length;i+=1){const r=e.charCodeAt(i);t^=r,t=Math.imul(t,16777619),s=Math.imul(s,33)+r}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()||e.claims!==void 0&&e.claims!==this.ownClaimsValue&&(this.ownClaimsValue!==void 0||this.isFollowerTab())?!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&&H(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 i=this.getConnection(s.shardKey),r=i!==void 0&&E(i,{data:t,topic:e,type:"whisper"});return this.releaseIdleShard(s.shardKey),r}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(f(e))??[])t()}confirmShardIdentity(e){const t=this.getConnection(e);t!==void 0&&(t.identityConfirmed=!0,t.polling.noteOpen()),this.releaseRoomSends(e)}handleIdentityFrame(e,t){const s=this.getConnection(t)?.identityQuestion,{subject:i}=e;s===void 0||i!==null&&typeof i!="string"||this.adoptCookieSubject(i,s)||!this.closed&&this.authToken===null&&(i===null?null:`subj:${i}`)!==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 i of t){if(this.identityVerdict(this.stampOf(i))!=="mismatch"){s.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);const r=new Error("offline mutation discarded: auth identity changed before replay");r.code="OFFLINE_IDENTITY_CHANGED",i.reject(r),this.emitItemSettled(i,"rejected",r)}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,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(s,t);this.offlineQueue.restampIdentity(e,t)}restampWatermarks(e,t){const s=e??"",i=this.clientWatermarks.get(s);if(i===void 0)return;this.clientWatermarks.delete(s);const r=t??"",a=this.clientWatermarks.get(r);if(a===void 0)this.clientWatermarks.set(r,i);else for(const[o,c]of i)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.queryCacheEpoch+=1;const{queryCache:e}=this;e&&(this.queryCacheChain=this.queryCacheChain.then(async()=>e.clear()).catch(()=>{}))}discardOptimisticLayers(){this.identityRetirements+=1;for(const e of this.subscriptions.all())e.optimisticLayers=[],e.retirements=(e.retirements??0)+1}evictPreviousIdentitySession(){this.resetOwnClaims(),this.resetRoomSends(),this.revokeCacheSeededValues(),this.reconnectCold(),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()}reconnectCold(){for(const e of this.subscriptions.all())e.serverBase=void 0,e.serverBaseCommitted=!1,e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,I(e,"idle"),e.valueReceived=!1,R(e,void 0);for(const e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,e.answered=!1,Pe(e);this.emitSyncStatus(),this.bounceShardSockets()}bounceShardSockets(e=!1){const{authToken:t,fetchImpl:s}=this;for(const i of this.connections.values()){const{connectionId:r}=i;e&&t!==null&&s!==void 0&&i.socket!==void 0&&r!==void 0&&i.retired!==!0?this.reauthenticateShardSocket(i,r,t):this.bounceShardSocket(i)}for(const i of this.supplementaryBounces)i()}retireChangedClaims(){if(this.clearQueryCacheForIdentityChange(),this.evictPreviousIdentitySession(),this.tabCoordinator?.isLeader())for(const e of this.subscriptions.all())this.tabCoordinator.broadcastSubscriptionData(g.keyOf(e),void 0,void 0,void 0,this.identityFingerprint())}reauthenticateShardSocket(e,t,s){const{authToken:i,fetchImpl:r}=this,{socket:a}=e;if(r===void 0)return;const o=(e.reauthAttempt??0)+1;clearTimeout(e.revalidateTimer),e.revalidateTimer=void 0,e.reauthAttempt=o,e.reauthPending=!0,(e.ticketed===!0?U(this.connectTimeoutMs,void 0,async()=>ie(this.wsTicket),()=>new Error("LunoraClient: ws ticket provider timed out")).catch(()=>{}):Promise.resolve(void 0)).then(async c=>re(r,w(this.url,ni(e.shardKey,c)),JSON.stringify({connectionId:t}),s===null?{"content-type":"application/json"}:{authorization:`Bearer ${s}`,"content-type":"application/json"})).then(({text:c})=>{const d=JSON.parse(c);return d?.ok===!0?"ok":d?.error?.code==="IDENTITY_CHANGED"?"changed":"refused"}).catch(()=>"refused").then(c=>{e.reauthAttempt===o&&(e.reauthPending=!1,!(this.closed||s!==null&&this.authToken!==i||e.connectionId!==t||e.socket!==a||e.retired===!0)&&(c==="ok"?(e.upgradeBearer=s??e.upgradeBearer,this.armSocketRevalidation(e,e.revalidateMs)):c==="changed"?this.retireChangedClaims():this.bounceShardSocket(e)))}).catch(()=>{})}armSocketRevalidation(e,t){clearTimeout(e.revalidateTimer),e.revalidateTimer=void 0,e.revalidateMs=typeof t=="number"&&t>0?t:void 0,e.revalidateMs!==void 0&&(e.revalidateTimer=setTimeout(()=>{e.revalidateTimer=void 0;const s=e.upgradeBearer??(e.sessionToken===void 0?null:this.authToken??void 0);s!==void 0&&e.connectionId!==void 0&&e.socket!==void 0&&e.retired!==!0&&this.reauthenticateShardSocket(e,e.connectionId,s)},e.revalidateMs/2))}bounceShardSocket(e){if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}else e.providerAttempt!==void 0&&this.startShardSocket(e,e.shardKey).catch(()=>{this.handleDisconnect(e)})}flushAllOfflineQueues(){for(const e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){const t=f(e),s=this.offlineFlushes.get(t);if(s===void 0&&this.offlineQueue.size===0)return;const i=(async()=>{await(s??Promise.resolve());const{authToken:r}=this;try{await this.drainOfflineQueue(e,r)}catch{}!this.closed&&this.authToken!==r&&this.offlineQueue.size>0&&H(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(t,i),await i,this.offlineFlushes.get(t)===i&&(this.offlineFlushes.delete(t),this.releaseIdleShard(e))}snapshotAnswer(e){const t=Te(e),s=t&&this.subscriptions.get(g.key(t.functionPath,t.args,t.shardKey));if(s!==void 0)return this.awaitingAnswer.has(s)?"awaiting":this.answeredUnreadable.has(s)?"unreadable":void 0}holdWhileUnanswered(e){const t=Te(e);if(e===void 0||t===void 0)return e;const s=()=>this.snapshotAnswer(e)!==void 0||e();return Nt(s,t),s}awaitLeaderAnswers(){for(const e of this.subscriptions.all())this.awaitLeaderAnswer(e)}awaitLeaderAnswer(e){this.awaitingAnswer.add(e),this.answeredUnreadable.delete(e),clearTimeout(this.leaderAnswerTimers.get(e)),this.leaderAnswerTimers.set(e,setTimeout(()=>{this.leaderAnswerTimers.delete(e),this.isCrossTabFollower()&&this.settleAwaitedAnswer(e,!1)},2*ve))}settleAwaitedAnswer(e,t){clearTimeout(this.leaderAnswerTimers.get(e)),this.leaderAnswerTimers.delete(e),t&&this.answeredUnreadable.delete(e),this.awaitingAnswer.delete(e)&&(t||this.answeredUnreadable.add(e),this.answerHeldShards.delete(f(e.shardKey))&&this.flushOfflineQueue(e.shardKey).catch(()=>{}))}holdUndecidedWrites(e,t){const s=t.findIndex(i=>this.snapshotAnswer(i.precondition)==="awaiting");return s===-1?t:(this.offlineQueue.requeue(t.slice(s)),this.answerHeldShards.add(e),t.slice(0,s))}async drainOfflineQueue(e,t){const s=this.offlineQueue.drainConflict();for(const l of s){this.unpersist(l.id),this.queuedIdentities.delete(l.id??"");const u=new Error("offline mutation skipped: precondition failed before replay");u.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(l,"rejected",u)}const i=f(e),r=this.holdUndecidedWrites(i,this.offlineQueue.drain(l=>f(l.shardKey)===i));if(r.length===0)return;const a=[],o=[];for(const l of r){const u=this.replayGateVerdict(l);u==="send"?a.push(l):u==="hold"&&o.push(l)}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 l=0;l<c.length;l+=ee){const u=c.slice(l,l+ee),h=await this.replayBatched(u,e,t);if(d.push(...h.requeue),h.stop||h.requeue.length>0){d.push(...c.slice(l+ee));break}}d.length>0&&this.offlineQueue.requeue(d),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){const t=f(e),s=this.replayRetryState.get(t),i=(s?.attempts??0)+1;this.replayRetryState.set(t,{attempts:i,delayMs:Math.max(s?.delayMs??0,ae(i))})}noteReplayRetryDelay(e,t,s){const i=f(e),r=this.replayRetryState.get(i),a=(r?.attempts??0)+1,o=Ps(t,a)??(s===null&&j(t)?ae(a):void 0);this.replayRetryState.set(i,{attempts:a,delayMs:o===void 0?r?.delayMs:Math.max(r?.delayMs??0,o)})}scheduleRateLimitedRetry(e){const t=f(e),s=this.replayRetryState.get(t),i=s?.delayMs;if(s===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(t);return}s.delayMs=void 0;const r=this.replayRetryTimers.get(t);r!==void 0&&clearTimeout(r),this.replayRetryTimers.set(t,setTimeout(()=>{this.replayRetryTimers.delete(t),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){const t=[];for(const s of e)try{k(s.args,`args for '${s.functionPath}'`),t.push(s)}catch(i){this.settleReplayTerminal(s,i instanceof Error?i:new Error(String(i)))}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 i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",e.reject(i),this.emitItemSettled(e,"rejected",i),"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 i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,i)),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)||Le(e)}noteReplayAuthRefusal(e,t){if(!j(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,...te(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)}spendsLastReplayAttempt(e,t){if(e.id===void 0)return!1;const s=t?.code;if(e.ambiguousSend!==!0||j(t)||s==="RATE_LIMITED"||s==="TOO_MANY_REQUESTS"||(t instanceof TypeError||t instanceof P)&&ci()||!Le(t))return!1;const i=(this.replayAttempts.get(e.id)??0)+1;return this.replayAttempts.set(e.id,i),i>=yt}keepUnexhaustedAmbiguousWrites(e,t){return e.filter(s=>s.ambiguousSend===!0&&this.spendsLastReplayAttempt(s,t)?(this.settleReplayTerminal(s,t),!1):!0)}settleReplayTerminal(e,t){this.unpersist(e.id),e.reject(t),this.emitItemSettled(e,"rejected",t)}async replaySequential(e,t,s){for(let i=0;i<e.length;i+=1){const r=e[i];if(!r)continue;let a;try{const o=await this.rpc(r.functionPath,r.args,r.shardKey,{authToken:s,baselineSeq:r.baselineSeq,captureBookmark:!0,clientId:r.clientId??this.clientId,...te(r.identity,s),mutationId:r.id,onCommitCursor:c=>{a=c}});this.settleReplaySuccess(r,o,a)}catch(o){if(x(o)){this.settleReplayUndecodable(r,o,a);continue}if(!this.shouldRequeueReplayFailure(o,s)||this.spendsLastReplayAttempt(r,o)){this.settleReplayTerminal(r,o);continue}this.noteReplayRetryDelay(t,o,s),this.offlineQueue.requeue(e.slice(i));return}}}async replayBatched(e,t,s){if(!this.fetchImpl)return{requeue:e,stop:!0};const i=JSON.stringify({calls:e.map((d,l)=>({args:k(d.args,`args for '${d.functionPath}'`),baselineSeq:d.baselineSeq,functionPath:d.functionPath,id:l,clientId:d.clientId??this.clientId,mutationId:d.id,shardKey:d.shardKey}))});if(e.length>1&&Ms(i)>Fs)return await this.replayBatchedHalves(e,t,s);const{fetchImpl:r}=this;let a,o;try{({payload:o,response:a}=await U(this.rpcTimeoutMs,void 0,async d=>{const l=await r(w(this.url,X),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:s,...te(e.find(u=>u.identity!==void 0)?.identity,s)}),method:"POST",signal:d});if(l.status===413&&e.length>1)return{payload:void 0,response:l};try{return{payload:await l.json(),response:l}}catch{return{payload:void 0,response:l}}}))}catch(d){return this.noteReplayRetryDelay(t,d,s),{requeue:this.keepUnexhaustedAmbiguousWrites(e,d),stop:!0}}const c=a.headers.get("x-d1-bookmark");if(c&&this.bookmark.set(c),a.status===413&&e.length>1)return await this.replayBatchedHalves(e,t,s);if(!o)return this.settleWholeBatchError(e,B(a.status,a.statusText,a.headers),t,s);if(!Array.isArray(o.results)){const d=q(o),l=d===void 0?B(a.status,a.statusText,a.headers):me(d,a.headers);return this.settleWholeBatchError(e,l,t,s)}return{requeue:this.settleReplayBatchSlots(e,o.results,t,s,a.headers),stop:!1}}settleWholeBatchError(e,t,s,i){if(t instanceof P||t.code!==void 0&&this.shouldRequeueReplayFailure(t,i))return this.noteReplayRetryDelay(s,t,i),{requeue:this.keepUnexhaustedAmbiguousWrites(e,t),stop:!0};for(const r of e)this.settleReplayTerminal(r,t);return{requeue:[],stop:!1}}async replayBatchedHalves(e,t,s){const i=Math.ceil(e.length/2),r=await this.replayBatched(e.slice(0,i),t,s);if(r.stop||r.requeue.length>0)return{requeue:[...r.requeue,...e.slice(i)],stop:!0};const a=await this.replayBatched(e.slice(i),t,s);return{requeue:[...r.requeue,...a.requeue],stop:a.stop}}settleReplayBatchSlots(e,t,s,i,r){const a=Hs(t),o=[];let c=!1,d=!1;for(const[l,u]of e.entries()){const h=Us(a.get(l),r);switch(h.kind){case"committed":{c=!0,this.settleReplaySuccess(u,h.value,h.commitCursor);break}case"errored":{d||=j(h.error),this.shouldRequeueReplayFailure(h.error,i)&&!this.spendsLastReplayAttempt(u,h.error)?(this.noteReplayRetryDelay(s,h.error,i),o.push(u)):this.settleReplayTerminal(u,h.error);break}case"unanswered":{const p=A(nt(),r);if(this.spendsLastReplayAttempt(u,p)){this.settleReplayTerminal(u,p);break}this.noteReplayRetryDelay(s,p,i),o.push(u);break}default:c=!0,this.settleReplayUndecodable(u,h.error,h.commitCursor)}}return c&&!d&&this.noteCredentialAccepted(i),o}}export{yr as $,Xi as A,cn as B,Wi as C,dn as D,tr as E,Bi as F,ji as G,ir as H,rr as I,nr as J,Yi as K,$e as L,or as M,ar as N,qi as O,cr as P,dr as Q,lr as R,Hi as S,ur as T,hr as U,$i as V,fr as W,pr as X,mr as Y,vr as Z,br as _,Qi as a,Sr as a0,Cr as a1,wr as a2,gr as a3,Tr as a4,_r as a5,Rr as a6,Ir as a7,kr as a8,Er as a9,Ar as aa,Or as ab,Lr as ac,Pr as ad,Fr as ae,Mr as af,Hr as ag,Ur as ah,Nr as ai,Dr as aj,Br as ak,Wr as al,Qr as am,xr as an,qr as ao,Kr as ap,jr as aq,Vr as ar,sr as as,xi as b,Ki as c,Vi as d,Gi as e,Zi as f,er as g,zi as h,Ui as i,Di as j,Ni as k,Ji as l,Yr as m,Gr as n,Zr as o,$r as p,Jr as q,zr as r,Xr as s,en as t,tn as u,sn as v,rn as w,nn as x,on as y,an as z};