@lunora/client 1.0.0-alpha.261 → 1.0.0-alpha.262
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.
- package/dist/admin/index.d.mts +1 -1
- package/dist/admin/index.d.ts +1 -1
- package/dist/admin/index.mjs +1 -1
- package/dist/auth/index.d.mts +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/index.d.mts +7 -3
- package/dist/index.d.ts +7 -3
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{LunoraAdminClient-DMK1sZpm.mjs → LunoraAdminClient-BAZgIQ1V.mjs} +1 -1
- package/dist/packem_shared/LunoraClient-C_0r-av9.mjs +1 -0
- package/dist/packem_shared/TabCoordinator-JAkvuahE.mjs +1 -0
- package/dist/packem_shared/createLocalStore-D38o4O8Z.mjs +1 -0
- package/dist/packem_shared/{createServerClient-CCCSB2eL.mjs → createServerClient-BqlNr7xM.mjs} +1 -1
- package/dist/packem_shared/lunora-client-CciSmQ-I.mjs +1 -0
- package/dist/packem_shared/{lunora-client.d-D3G_fsa6.d.mts → lunora-client.d-B03X64bx.d.mts} +27 -7
- package/dist/packem_shared/{lunora-client.d-eugqse6z.d.ts → lunora-client.d-DD4bVp9S.d.ts} +27 -7
- package/dist/packem_shared/optimistic-layers-D-7D3yeJ.mjs +1 -0
- package/dist/packem_shared/{preload.d-C3esb5ZQ.d.mts → preload.d-BuQpOeP-.d.mts} +1 -1
- package/dist/packem_shared/{preload.d-N9jMP9ai.d.ts → preload.d-tOPIEVGY.d.ts} +1 -1
- package/dist/query/index.d.mts +2 -2
- package/dist/query/index.d.ts +2 -2
- package/dist/ssr/index.d.mts +2 -2
- package/dist/ssr/index.d.ts +2 -2
- package/dist/ssr/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/LunoraClient-CeaiXMQN.mjs +0 -1
- package/dist/packem_shared/TabCoordinator-DBuR7Dwv.mjs +0 -1
- package/dist/packem_shared/createLocalStore-CsKA0HPB.mjs +0 -1
- package/dist/packem_shared/local-store-C3bw2MPY.mjs +0 -1
- package/dist/packem_shared/lunora-client-Csrg4U0l.mjs +0 -1
package/dist/admin/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a6 as ShardTrafficResult, Z as ScheduleRecord, a0 as SchedulerStatus, aj as WorkflowInstanceStatus, ai as WorkflowInstancePage, ah as WorkflowInstanceDetail, ag as WorkflowInstanceAction, p as FunctionDescriptor, a7 as StorageListPage, s as GlobalTableInfo, r as GlobalFilterClause, t as GlobalTablePage, G as GlobalFacetResult, L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
1
|
+
import { a6 as ShardTrafficResult, Z as ScheduleRecord, a0 as SchedulerStatus, aj as WorkflowInstanceStatus, ai as WorkflowInstancePage, ah as WorkflowInstanceDetail, ag as WorkflowInstanceAction, p as FunctionDescriptor, a7 as StorageListPage, s as GlobalTableInfo, r as GlobalFilterClause, t as GlobalTablePage, G as GlobalFacetResult, L as LunoraClient } from "../packem_shared/lunora-client.d-B03X64bx.mjs";
|
|
2
2
|
import { CronJobInfo, VectorIndexSummary, VectorQueryMatch, PipelineLogQuery, PipelineLogPage, 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";
|
package/dist/admin/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a6 as ShardTrafficResult, Z as ScheduleRecord, a0 as SchedulerStatus, aj as WorkflowInstanceStatus, ai as WorkflowInstancePage, ah as WorkflowInstanceDetail, ag as WorkflowInstanceAction, p as FunctionDescriptor, a7 as StorageListPage, s as GlobalTableInfo, r as GlobalFilterClause, t as GlobalTablePage, G as GlobalFacetResult, L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
1
|
+
import { a6 as ShardTrafficResult, Z as ScheduleRecord, a0 as SchedulerStatus, aj as WorkflowInstanceStatus, ai as WorkflowInstancePage, ah as WorkflowInstanceDetail, ag as WorkflowInstanceAction, p as FunctionDescriptor, a7 as StorageListPage, s as GlobalTableInfo, r as GlobalFilterClause, t as GlobalTablePage, G as GlobalFacetResult, L as LunoraClient } from "../packem_shared/lunora-client.d-DD4bVp9S.js";
|
|
2
2
|
import { CronJobInfo, VectorIndexSummary, VectorQueryMatch, PipelineLogQuery, PipelineLogPage, 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";
|
package/dist/admin/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraAdminClient as o,isLunoraAdminClient as r}from"../packem_shared/LunoraAdminClient-
|
|
1
|
+
import{LunoraAdminClient as o,isLunoraAdminClient as r}from"../packem_shared/LunoraAdminClient-BAZgIQ1V.mjs";export{o as LunoraAdminClient,r as isLunoraAdminClient};
|
package/dist/auth/index.d.mts
CHANGED
|
@@ -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-
|
|
50
|
+
import { L as LunoraClient, U as User } from "../packem_shared/lunora-client.d-B03X64bx.mjs";
|
|
51
51
|
import { LunoraAdminClient } from "../admin/index.mjs";
|
|
52
52
|
import { AuthPage, AuthSession, AuthUser } from '@lunora/runtime';
|
|
53
53
|
import '@lunora/errors';
|
package/dist/auth/index.d.ts
CHANGED
|
@@ -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-
|
|
50
|
+
import { L as LunoraClient, U as User } from "../packem_shared/lunora-client.d-DD4bVp9S.js";
|
|
51
51
|
import { LunoraAdminClient } from "../admin/index.js";
|
|
52
52
|
import { AuthPage, 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-
|
|
2
|
-
export { type A as ActionCallOptions, type g as BatchSlot, type h as CachedQuery, type i as ClientDebugShard, type j as ClientDebugSnapshot, type k as ClientDebugSubscription, type l as ClientMessage, type m as ClientQueryRef, type n as ClientShapeSubscribeMessage, type o as ClientShapeUnsubscribeMessage, D as DEFAULT_MAX_BUFFER, type F as FunctionArgumentDescriptor, type p as FunctionDescriptor, type G as GlobalFacetResult, type q as GlobalFacetValue, type r as GlobalFilterClause, type s as GlobalTableInfo, type t as GlobalTablePage, type u as HttpStreamCallArgs, type v as LunoraClientError, type w as LunoraClientOptions, type M as MutationCallOptions, type x as MutationSettledEvent, type y as OnlineOnlyOption, type z as OptimisticLocalStore, type E as OptimisticUpdate, type I as OutboxMutation, type J as OutboxSink, type K as PersistedMutation, type P as Preloaded, type N as ReplayCredential, type T as ReplayIdentityVerdict, type V as RoomRef, type W as RowOp, type X as RpcEnvelope, type Y as RpcResponseBody, type Z as ScheduleRecord, type _ as ScheduleRetryPolicy, type $ as SchedulerPoolStatus, type a0 as SchedulerStatus, type a1 as ServerMessage, type a2 as ServerPokeEndMessage, type a3 as ServerPokePartMessage, type a4 as ServerPokeStartMessage, type a5 as ShardTrafficEntry, type a6 as ShardTrafficResult, type a7 as StorageListPage, type a8 as StorageObject, type a9 as StoredQuery, type aa as StreamHandle, type ab as SubscriptionCallback, type b as SubscriptionErrorCallback, ac as SubscriptionRegistry, type ad as SubscriptionState, type ae as SyncStatus, type af as SyncWatermark, type U as User, type ag as WorkflowInstanceAction, type ah as WorkflowInstanceDetail, type ai as WorkflowInstancePage, type aj as WorkflowInstanceStatus, type ak as WorkflowInstanceSummary, type al as WorkflowStepDetail, type am as WsTokenProvider, an as createClientQuery, ao as createLocalStore, ap as createStream } from "./packem_shared/lunora-client.d-
|
|
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-B03X64bx.mjs";
|
|
2
|
+
export { type A as ActionCallOptions, type g as BatchSlot, type h as CachedQuery, type i as ClientDebugShard, type j as ClientDebugSnapshot, type k as ClientDebugSubscription, type l as ClientMessage, type m as ClientQueryRef, type n as ClientShapeSubscribeMessage, type o as ClientShapeUnsubscribeMessage, D as DEFAULT_MAX_BUFFER, type F as FunctionArgumentDescriptor, type p as FunctionDescriptor, type G as GlobalFacetResult, type q as GlobalFacetValue, type r as GlobalFilterClause, type s as GlobalTableInfo, type t as GlobalTablePage, type u as HttpStreamCallArgs, type v as LunoraClientError, type w as LunoraClientOptions, type M as MutationCallOptions, type x as MutationSettledEvent, type y as OnlineOnlyOption, type z as OptimisticLocalStore, type E as OptimisticUpdate, type I as OutboxMutation, type J as OutboxSink, type K as PersistedMutation, type P as Preloaded, type N as ReplayCredential, type T as ReplayIdentityVerdict, type V as RoomRef, type W as RowOp, type X as RpcEnvelope, type Y as RpcResponseBody, type Z as ScheduleRecord, type _ as ScheduleRetryPolicy, type $ as SchedulerPoolStatus, type a0 as SchedulerStatus, type a1 as ServerMessage, type a2 as ServerPokeEndMessage, type a3 as ServerPokePartMessage, type a4 as ServerPokeStartMessage, type a5 as ShardTrafficEntry, type a6 as ShardTrafficResult, type a7 as StorageListPage, type a8 as StorageObject, type a9 as StoredQuery, type aa as StreamHandle, type ab as SubscriptionCallback, type b as SubscriptionErrorCallback, ac as SubscriptionRegistry, type ad as SubscriptionState, type ae as SyncStatus, type af as SyncWatermark, type U as User, type ag as WorkflowInstanceAction, type ah as WorkflowInstanceDetail, type ai as WorkflowInstancePage, type aj as WorkflowInstanceStatus, type ak as WorkflowInstanceSummary, type al as WorkflowStepDetail, type am as WsTokenProvider, an as createClientQuery, ao as createLocalStore, ap as createStream } from "./packem_shared/lunora-client.d-B03X64bx.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-
|
|
5
|
+
export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-BuQpOeP-.mjs";
|
|
6
6
|
import { F as FunctionReference } from "./packem_shared/function-reference.d-Br_hsKje.mjs";
|
|
7
7
|
export type { A as ArgsOf, R as ReturnOf } from "./packem_shared/function-reference.d-Br_hsKje.mjs";
|
|
8
8
|
export type { AuthCapabilities, AuthConfigInfo, AuthImpersonation, AuthPage, AuthSession, AuthUser, AuthUserFieldSpec, CronJobInfo, KvKeyEntry, KvKeyListResult, KvNamespaceSummary, KvValueResult, PipelineLogColumnMap, PipelineLogCursor, PipelineLogField, PipelineLogPage, PipelineLogQuery, PipelineLogRow, VectorIndexSummary, VectorQueryMatch } from '@lunora/runtime';
|
|
@@ -434,6 +434,8 @@ declare class TabCoordinator {
|
|
|
434
434
|
* whole value for every tab on the channel.
|
|
435
435
|
*/
|
|
436
436
|
private readonly pendingData;
|
|
437
|
+
/** Snapshots received under `more`, per leader tab, applied with the frame that closes their flush. */
|
|
438
|
+
private readonly heldData;
|
|
437
439
|
private heartbeatTimer;
|
|
438
440
|
private leaderCheckTimer;
|
|
439
441
|
/** Callbacks set via constructor options. */
|
|
@@ -529,6 +531,8 @@ declare class TabCoordinator {
|
|
|
529
531
|
private broadcast;
|
|
530
532
|
/** Post the snapshots queued this tick — unless leadership was lost meanwhile, when the new leader's own snapshots supersede them. */
|
|
531
533
|
private flushPendingData;
|
|
534
|
+
/** Hold a snapshot marked `more`; on the one that closes its flush, apply them all and notify once. */
|
|
535
|
+
private applySubscriptionData;
|
|
532
536
|
private handleMessage;
|
|
533
537
|
private handleClaimLeadership;
|
|
534
538
|
private handleHeartbeat;
|
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-
|
|
2
|
-
export { type A as ActionCallOptions, type g as BatchSlot, type h as CachedQuery, type i as ClientDebugShard, type j as ClientDebugSnapshot, type k as ClientDebugSubscription, type l as ClientMessage, type m as ClientQueryRef, type n as ClientShapeSubscribeMessage, type o as ClientShapeUnsubscribeMessage, D as DEFAULT_MAX_BUFFER, type F as FunctionArgumentDescriptor, type p as FunctionDescriptor, type G as GlobalFacetResult, type q as GlobalFacetValue, type r as GlobalFilterClause, type s as GlobalTableInfo, type t as GlobalTablePage, type u as HttpStreamCallArgs, type v as LunoraClientError, type w as LunoraClientOptions, type M as MutationCallOptions, type x as MutationSettledEvent, type y as OnlineOnlyOption, type z as OptimisticLocalStore, type E as OptimisticUpdate, type I as OutboxMutation, type J as OutboxSink, type K as PersistedMutation, type P as Preloaded, type N as ReplayCredential, type T as ReplayIdentityVerdict, type V as RoomRef, type W as RowOp, type X as RpcEnvelope, type Y as RpcResponseBody, type Z as ScheduleRecord, type _ as ScheduleRetryPolicy, type $ as SchedulerPoolStatus, type a0 as SchedulerStatus, type a1 as ServerMessage, type a2 as ServerPokeEndMessage, type a3 as ServerPokePartMessage, type a4 as ServerPokeStartMessage, type a5 as ShardTrafficEntry, type a6 as ShardTrafficResult, type a7 as StorageListPage, type a8 as StorageObject, type a9 as StoredQuery, type aa as StreamHandle, type ab as SubscriptionCallback, type b as SubscriptionErrorCallback, ac as SubscriptionRegistry, type ad as SubscriptionState, type ae as SyncStatus, type af as SyncWatermark, type U as User, type ag as WorkflowInstanceAction, type ah as WorkflowInstanceDetail, type ai as WorkflowInstancePage, type aj as WorkflowInstanceStatus, type ak as WorkflowInstanceSummary, type al as WorkflowStepDetail, type am as WsTokenProvider, an as createClientQuery, ao as createLocalStore, ap as createStream } from "./packem_shared/lunora-client.d-
|
|
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-DD4bVp9S.js";
|
|
2
|
+
export { type A as ActionCallOptions, type g as BatchSlot, type h as CachedQuery, type i as ClientDebugShard, type j as ClientDebugSnapshot, type k as ClientDebugSubscription, type l as ClientMessage, type m as ClientQueryRef, type n as ClientShapeSubscribeMessage, type o as ClientShapeUnsubscribeMessage, D as DEFAULT_MAX_BUFFER, type F as FunctionArgumentDescriptor, type p as FunctionDescriptor, type G as GlobalFacetResult, type q as GlobalFacetValue, type r as GlobalFilterClause, type s as GlobalTableInfo, type t as GlobalTablePage, type u as HttpStreamCallArgs, type v as LunoraClientError, type w as LunoraClientOptions, type M as MutationCallOptions, type x as MutationSettledEvent, type y as OnlineOnlyOption, type z as OptimisticLocalStore, type E as OptimisticUpdate, type I as OutboxMutation, type J as OutboxSink, type K as PersistedMutation, type P as Preloaded, type N as ReplayCredential, type T as ReplayIdentityVerdict, type V as RoomRef, type W as RowOp, type X as RpcEnvelope, type Y as RpcResponseBody, type Z as ScheduleRecord, type _ as ScheduleRetryPolicy, type $ as SchedulerPoolStatus, type a0 as SchedulerStatus, type a1 as ServerMessage, type a2 as ServerPokeEndMessage, type a3 as ServerPokePartMessage, type a4 as ServerPokeStartMessage, type a5 as ShardTrafficEntry, type a6 as ShardTrafficResult, type a7 as StorageListPage, type a8 as StorageObject, type a9 as StoredQuery, type aa as StreamHandle, type ab as SubscriptionCallback, type b as SubscriptionErrorCallback, ac as SubscriptionRegistry, type ad as SubscriptionState, type ae as SyncStatus, type af as SyncWatermark, type U as User, type ag as WorkflowInstanceAction, type ah as WorkflowInstanceDetail, type ai as WorkflowInstancePage, type aj as WorkflowInstanceStatus, type ak as WorkflowInstanceSummary, type al as WorkflowStepDetail, type am as WsTokenProvider, an as createClientQuery, ao as createLocalStore, ap as createStream } from "./packem_shared/lunora-client.d-DD4bVp9S.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-
|
|
5
|
+
export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-tOPIEVGY.js";
|
|
6
6
|
import { F as FunctionReference } from "./packem_shared/function-reference.d-Br_hsKje.js";
|
|
7
7
|
export type { A as ArgsOf, R as ReturnOf } from "./packem_shared/function-reference.d-Br_hsKje.js";
|
|
8
8
|
export type { AuthCapabilities, AuthConfigInfo, AuthImpersonation, AuthPage, AuthSession, AuthUser, AuthUserFieldSpec, CronJobInfo, KvKeyEntry, KvKeyListResult, KvNamespaceSummary, KvValueResult, PipelineLogColumnMap, PipelineLogCursor, PipelineLogField, PipelineLogPage, PipelineLogQuery, PipelineLogRow, VectorIndexSummary, VectorQueryMatch } from '@lunora/runtime';
|
|
@@ -434,6 +434,8 @@ declare class TabCoordinator {
|
|
|
434
434
|
* whole value for every tab on the channel.
|
|
435
435
|
*/
|
|
436
436
|
private readonly pendingData;
|
|
437
|
+
/** Snapshots received under `more`, per leader tab, applied with the frame that closes their flush. */
|
|
438
|
+
private readonly heldData;
|
|
437
439
|
private heartbeatTimer;
|
|
438
440
|
private leaderCheckTimer;
|
|
439
441
|
/** Callbacks set via constructor options. */
|
|
@@ -529,6 +531,8 @@ declare class TabCoordinator {
|
|
|
529
531
|
private broadcast;
|
|
530
532
|
/** Post the snapshots queued this tick — unless leadership was lost meanwhile, when the new leader's own snapshots supersede them. */
|
|
531
533
|
private flushPendingData;
|
|
534
|
+
/** Hold a snapshot marked `more`; on the one that closes its flush, apply them all and notify once. */
|
|
535
|
+
private applySubscriptionData;
|
|
532
536
|
private handleMessage;
|
|
533
537
|
private handleClaimLeadership;
|
|
534
538
|
private handleHeartbeat;
|
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-6FCvqc6C.mjs";import{createAsyncStorageQueryCache as n}from"./packem_shared/createAsyncStorageQueryCache-D8NJXPJa.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 d}from"./packem_shared/createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as R}from"./packem_shared/TabCoordinator-
|
|
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-6FCvqc6C.mjs";import{createAsyncStorageQueryCache as n}from"./packem_shared/createAsyncStorageQueryCache-D8NJXPJa.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 d}from"./packem_shared/createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as R}from"./packem_shared/TabCoordinator-JAkvuahE.mjs";import{a as S,i as A}from"./packem_shared/delta-merge-C6OqMEPH.mjs";import{CONFLICT_ERROR_CODE as L,TransportError as T,getErrorCode as b,getRetryAfterMs as D,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 O}from"./packem_shared/httpStream-ChJxN9M1.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-D38o4O8Z.mjs";import{L as K}from"./packem_shared/lunora-client-CciSmQ-I.mjs";import{createMutatorRunner as X}from"./packem_shared/createMutatorRunner-CuMRJpUx.mjs";import{O as w}from"./packem_shared/offline-queue-BEqCPDmw.mjs";import{createInMemoryPersistence as H,createIndexedDbPersistence as J}from"./packem_shared/createInMemoryPersistence-C-IzNVbg.mjs";import{preloadQuery as Y,preloadedQueryResult as Z}from"./packem_shared/preloadQuery-uFy24PCR.mjs";import{createInMemoryQueryCache as ee,createIndexedDbQueryCache as re,queryCacheKey as oe}from"./packem_shared/createInMemoryQueryCache-DR6AorA2.mjs";import{createReconnect as ae}from"./packem_shared/createReconnect-CjTmjJDH.mjs";import{c as ie}from"./packem_shared/snapshot-precondition-BEtcSbWr.mjs";import{DEFAULT_MAX_BUFFER as ne,createStream as me}from"./packem_shared/DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";import{SubscriptionRegistry as fe}from"./packem_shared/SubscriptionRegistry-BKgQtuh9.mjs";export{L as CONFLICT_ERROR_CODE,ne as DEFAULT_MAX_BUFFER,K as LunoraClient,w as OfflineQueue,o as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,fe as SubscriptionRegistry,R as TabCoordinator,T as TransportError,S as applyDelta,v as connectLiveStream,i as createAsyncStoragePersistence,n as createAsyncStorageQueryCache,l as createCallRunner,d as createClientQuery,x as createInMemoryBookmarkStorage,H as createInMemoryPersistence,ee as createInMemoryQueryCache,J as createIndexedDbPersistence,re as createIndexedDbQueryCache,N as createLocalStore,X as createMutatorRunner,ae as createReconnect,ie as createSnapshotPrecondition,me as createStream,b as getErrorCode,D as getRetryAfterMs,O 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,Y as preloadQuery,Z as preloadedQueryResult,oe as queryCacheKey,a as reconcileOptimistic,s as setAuthTokenProvider,B as subscribeLiveTopic};
|
package/dist/packem_shared/{LunoraAdminClient-DMK1sZpm.mjs → LunoraAdminClient-BAZgIQ1V.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{F as H,C as A,a as u,O,A as _,b as l,G as y,c as E,d as P,K as S,e as f,f as r,S as U,g as p,h as c,i as w,j as F,V as b,k as I,L as R,l as g,s as G,m as C,n as N,r as M,o as k,p as v,q as L,t as V,u as K,v as B,w as D,x as J,y as x,z as $,B as z,D as j,E as W,H as q,I as Q,J as Y,M as X,N as Z,P as tt,Q as at,R as st,T as et,U as nt,W as it,X as rt,Y as ct,Z as dt,_ as ot,$ as mt,a0 as ht,a1 as Tt,a2 as Ht,a3 as At,a4 as ut,a5 as Ot,a6 as _t,a7 as lt,a8 as yt,a9 as Et,aa as Pt,ab as St,ac as ft,ad as Ut,ae as pt,af as wt,ag as Ft,ah as bt,ai as It}from"./lunora-client-Csrg4U0l.mjs";import{w as e,b as d}from"./client-urls-BHLUjjcG.mjs";import{encodeWire as m,decodeWire as h}from"@lunora/wire";const Rt=async a=>(a.assertOpen(),(await a.adminFetch(H,"GET")).functions??[]),gt=async a=>(a.assertOpen(),(await a.adminFetch(A,"GET")).jobs??[]),Gt=async(a,t)=>{a.assertOpen();const s=await a.adminFetch(u,"POST",{name:t});return{name:s.name??t,ran:s.ran===!0}},Ct=async a=>(a.assertOpen(),await a.adminFetch(O,"GET")),Nt=async a=>(a.assertOpen(),await a.adminFetch(_,"GET")),Mt=async a=>(a.assertOpen(),await a.adminFetch(l,"GET")),kt=async a=>(a.assertOpen(),await a.adminFetch(y,"GET")),vt=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(m(t.filters))),h(await a.adminFetch(`${E}?${s.toString()}`,"GET"))},Lt=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(m(t.filters))),h(await a.adminFetch(`${P}?${s.toString()}`,"GET"))},Vt=async a=>(a.assertOpen(),(await a.adminFetch(S,"GET")).namespaces??[]),Kt=async(a,t)=>{a.assertOpen();const s=e(f,{cursor:t.cursor,limit:t.limit,namespace:t.namespace,prefix:t.prefix});return await a.adminFetch(s,"GET")},Bt=async(a,t)=>{a.assertOpen();const s=e(r,{key:t.key,namespace:t.namespace});return await a.adminFetch(s,"GET")},Dt=async(a,t)=>{a.assertOpen(),await a.adminFetch(r,"PUT",t)},Jt=async(a,t)=>{a.assertOpen();const s=e(r,{key:t.key,namespace:t.namespace});await a.adminFetch(s,"DELETE")},xt=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??[]}},$t=async(a,t={})=>{a.assertOpen();const s=await a.adminFetch(p,"POST",t);return{nextCursor:s.nextCursor,rows:s.rows??[]}},zt=async(a,t={})=>{a.assertOpen();const s=e(c,{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??[]}},jt=async(a,t,s)=>{a.assertOpen();const n=`${c}?key=${encodeURIComponent(t)}${d(s?.bucket)}`,i=await a.adminFetch(n,"DELETE");return{deleted:i.deleted===!0,key:i.key??t}},Wt=async a=>(a.assertOpen(),(await a.adminFetch(w,"GET")).buckets??[]),qt=async(a,t)=>{a.assertOpen();const s=`${c}?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}},Qt=async(a,t,s)=>{a.assertOpen();const n=s?.expiresInSeconds,i=n===void 0?"":`&expiresIn=${encodeURIComponent(n.toString())}`,T=`${F}?key=${encodeURIComponent(t)}${i}${d(s?.bucket)}`,o=await a.adminFetch(T,"GET");if(typeof o.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return o.url},Yt=async a=>(a.assertOpen(),(await a.adminFetch(b,"GET")).indexes??[]),Xt=async(a,t)=>(a.assertOpen(),(await a.adminFetch(I,"POST",t)).matches??[]);class sa extends R{async shardTraffic(t){return xt(this.adminHost,t)}async listScheduledJobs(){return g(this.adminHost)}async schedulerStatus(){return G(this.adminHost)}async cancelScheduledJob(t){return C(this.adminHost,t)}async listDeadJobs(){return N(this.adminHost)}async retryDeadJob(t){return M(this.adminHost,t)}async removeDeadJob(t){return k(this.adminHost,t)}async listWorkflowInstances(t){return v(this.adminHost,t)}async getWorkflowInstance(t){return L(this.adminHost,t)}async setWorkflowInstanceStatus(t){return V(this.adminHost,t)}async listFunctions(){return Rt(this.adminHost)}async getCronJobs(){return gt(this.adminHost)}async runCronJob(t){return Gt(this.adminHost,t)}async fetchOpenApi(){return Ct(this.adminHost)}async fetchArchitecture(){return Nt(this.adminHost)}async fetchOpenRpc(){return Mt(this.adminHost)}async listStorageObjects(t={}){return zt(this.adminHost,t)}async deleteStorageObject(t,s){return jt(this.adminHost,t,s)}async listStorageBuckets(){return Wt(this.adminHost)}async uploadStorageObject(t){return qt(this.adminHost,t)}async signedStorageUrl(t,s){return Qt(this.adminHost,t,s)}async listGlobalTables(){return kt(this.adminHost)}async readGlobalTablePage(t){return vt(this.adminHost,t)}async facetGlobalColumn(t){return Lt(this.adminHost,t)}async listVectorIndexes(){return Yt(this.adminHost)}async queryVectorIndex(t){return Xt(this.adminHost,t)}async queryLogArchive(t={}){return $t(this.adminHost,t)}async listKvNamespaces(){return Vt(this.adminHost)}async listKvKeys(t){return Kt(this.adminHost,t)}async getKvValue(t){return Bt(this.adminHost,t)}async putKvValue(t){return Dt(this.adminHost,t)}async deleteKvKey(t){return Jt(this.adminHost,t)}async listAuthUsers(t={}){this.adminHost.assertOpen();const s=e(K,{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(B,"POST",t)}async setAuthUserRole(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(D,"POST",t)}async banAuthUser(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(J,"POST",t)}async unbanAuthUser(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(x,"POST",t)}async setAuthUserPassword(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch($,"POST",t)}async removeAuthUser(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(z,"POST",t)}async impersonateAuthUser(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(j,"POST",t)}async revokeAuthSession(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(W,"POST",t)}async revokeAuthUserSessions(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(q,"POST",t)}async getAuthCapabilities(){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Q,"GET")}async updateAuthUser(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Y,"POST",t)}async listAuthAccounts(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(e(X,{userId:t.userId}),"GET")}async unlinkAuthAccount(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Z,"POST",t)}async listAuthPasskeys(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(e(tt,{userId:t.userId}),"GET")}async deleteAuthPasskey(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(at,"POST",t)}async disableAuthTwoFactor(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(st,"POST",t)}async listAuthOrganizations(t={}){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(e(et,{limit:t.limit,offset:t.offset}),"GET")}async listAuthOrgMembers(t){this.adminHost.assertOpen();const s=e(nt,{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(it,{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(rt,{limit:t.limit,offset:t.offset});return await this.adminHost.adminFetch(s,"GET")}async createAuthSignUpInvitation(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(ct,"POST",t)}async revokeAuthSignUpInvitation(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(dt,"POST",t)}async removeAuthOrgMember(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(ot,"POST",t)}async cancelAuthOrgInvitation(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(mt,"POST",t)}async getAuthConfig(){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(ht,"GET")}async createAuthOrganization(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Tt,"POST",t)}async updateAuthOrganization(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ht,"POST",t)}async deleteAuthOrganization(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(At,"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(Ot,"POST",t)}async setAuthOrgMemberRole(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(_t,"POST",t)}async listAuthOrgTeams(t){this.adminHost.assertOpen();const s=e(lt,{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(yt,"POST",t)}async updateAuthOrgTeam(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Et,"POST",t)}async removeAuthOrgTeam(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Pt,"POST",t)}async listAuthOrgTeamMembers(t){this.adminHost.assertOpen();const s=e(St,{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(ft,"POST",t)}async removeAuthOrgTeamMember(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ut,"POST",t)}async listAuthOrgRoles(t){this.adminHost.assertOpen();const s=e(pt,{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(wt,"POST",t)}async updateAuthOrgRole(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ft,"POST",t)}async deleteAuthOrgRole(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(bt,"POST",t)}async listAuthSessions(t={}){this.adminHost.assertOpen();const s=e(It,{limit:t.limit,offset:t.offset,userId:t.userId});return await this.adminHost.adminFetch(s,"GET")}}const ea=a=>"listAuthUsers"in a;export{sa as LunoraAdminClient,ea as isLunoraAdminClient};
|
|
1
|
+
import{F as H,C as A,a as u,O,A as _,b as l,G as y,c as E,d as P,K as S,e as f,f as r,S as U,g as p,h as c,i as w,j as F,V as b,k as I,L as R,l as g,s as G,m as C,n as N,r as M,o as k,p as v,q as L,t as V,u as K,v as B,w as D,x as J,y as x,z as $,B as z,D as j,E as W,H as q,I as Q,J as Y,M as X,N as Z,P as tt,Q as at,R as st,T as et,U as nt,W as it,X as rt,Y as ct,Z as dt,_ as ot,$ as mt,a0 as ht,a1 as Tt,a2 as Ht,a3 as At,a4 as ut,a5 as Ot,a6 as _t,a7 as lt,a8 as yt,a9 as Et,aa as Pt,ab as St,ac as ft,ad as Ut,ae as pt,af as wt,ag as Ft,ah as bt,ai as It}from"./lunora-client-CciSmQ-I.mjs";import{w as e,b as d}from"./client-urls-BHLUjjcG.mjs";import{encodeWire as m,decodeWire as h}from"@lunora/wire";const Rt=async a=>(a.assertOpen(),(await a.adminFetch(H,"GET")).functions??[]),gt=async a=>(a.assertOpen(),(await a.adminFetch(A,"GET")).jobs??[]),Gt=async(a,t)=>{a.assertOpen();const s=await a.adminFetch(u,"POST",{name:t});return{name:s.name??t,ran:s.ran===!0}},Ct=async a=>(a.assertOpen(),await a.adminFetch(O,"GET")),Nt=async a=>(a.assertOpen(),await a.adminFetch(_,"GET")),Mt=async a=>(a.assertOpen(),await a.adminFetch(l,"GET")),kt=async a=>(a.assertOpen(),await a.adminFetch(y,"GET")),vt=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(m(t.filters))),h(await a.adminFetch(`${E}?${s.toString()}`,"GET"))},Lt=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(m(t.filters))),h(await a.adminFetch(`${P}?${s.toString()}`,"GET"))},Vt=async a=>(a.assertOpen(),(await a.adminFetch(S,"GET")).namespaces??[]),Kt=async(a,t)=>{a.assertOpen();const s=e(f,{cursor:t.cursor,limit:t.limit,namespace:t.namespace,prefix:t.prefix});return await a.adminFetch(s,"GET")},Bt=async(a,t)=>{a.assertOpen();const s=e(r,{key:t.key,namespace:t.namespace});return await a.adminFetch(s,"GET")},Dt=async(a,t)=>{a.assertOpen(),await a.adminFetch(r,"PUT",t)},Jt=async(a,t)=>{a.assertOpen();const s=e(r,{key:t.key,namespace:t.namespace});await a.adminFetch(s,"DELETE")},xt=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??[]}},$t=async(a,t={})=>{a.assertOpen();const s=await a.adminFetch(p,"POST",t);return{nextCursor:s.nextCursor,rows:s.rows??[]}},zt=async(a,t={})=>{a.assertOpen();const s=e(c,{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??[]}},jt=async(a,t,s)=>{a.assertOpen();const n=`${c}?key=${encodeURIComponent(t)}${d(s?.bucket)}`,i=await a.adminFetch(n,"DELETE");return{deleted:i.deleted===!0,key:i.key??t}},Wt=async a=>(a.assertOpen(),(await a.adminFetch(w,"GET")).buckets??[]),qt=async(a,t)=>{a.assertOpen();const s=`${c}?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}},Qt=async(a,t,s)=>{a.assertOpen();const n=s?.expiresInSeconds,i=n===void 0?"":`&expiresIn=${encodeURIComponent(n.toString())}`,T=`${F}?key=${encodeURIComponent(t)}${i}${d(s?.bucket)}`,o=await a.adminFetch(T,"GET");if(typeof o.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return o.url},Yt=async a=>(a.assertOpen(),(await a.adminFetch(b,"GET")).indexes??[]),Xt=async(a,t)=>(a.assertOpen(),(await a.adminFetch(I,"POST",t)).matches??[]);class sa extends R{async shardTraffic(t){return xt(this.adminHost,t)}async listScheduledJobs(){return g(this.adminHost)}async schedulerStatus(){return G(this.adminHost)}async cancelScheduledJob(t){return C(this.adminHost,t)}async listDeadJobs(){return N(this.adminHost)}async retryDeadJob(t){return M(this.adminHost,t)}async removeDeadJob(t){return k(this.adminHost,t)}async listWorkflowInstances(t){return v(this.adminHost,t)}async getWorkflowInstance(t){return L(this.adminHost,t)}async setWorkflowInstanceStatus(t){return V(this.adminHost,t)}async listFunctions(){return Rt(this.adminHost)}async getCronJobs(){return gt(this.adminHost)}async runCronJob(t){return Gt(this.adminHost,t)}async fetchOpenApi(){return Ct(this.adminHost)}async fetchArchitecture(){return Nt(this.adminHost)}async fetchOpenRpc(){return Mt(this.adminHost)}async listStorageObjects(t={}){return zt(this.adminHost,t)}async deleteStorageObject(t,s){return jt(this.adminHost,t,s)}async listStorageBuckets(){return Wt(this.adminHost)}async uploadStorageObject(t){return qt(this.adminHost,t)}async signedStorageUrl(t,s){return Qt(this.adminHost,t,s)}async listGlobalTables(){return kt(this.adminHost)}async readGlobalTablePage(t){return vt(this.adminHost,t)}async facetGlobalColumn(t){return Lt(this.adminHost,t)}async listVectorIndexes(){return Yt(this.adminHost)}async queryVectorIndex(t){return Xt(this.adminHost,t)}async queryLogArchive(t={}){return $t(this.adminHost,t)}async listKvNamespaces(){return Vt(this.adminHost)}async listKvKeys(t){return Kt(this.adminHost,t)}async getKvValue(t){return Bt(this.adminHost,t)}async putKvValue(t){return Dt(this.adminHost,t)}async deleteKvKey(t){return Jt(this.adminHost,t)}async listAuthUsers(t={}){this.adminHost.assertOpen();const s=e(K,{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(B,"POST",t)}async setAuthUserRole(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(D,"POST",t)}async banAuthUser(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(J,"POST",t)}async unbanAuthUser(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(x,"POST",t)}async setAuthUserPassword(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch($,"POST",t)}async removeAuthUser(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(z,"POST",t)}async impersonateAuthUser(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(j,"POST",t)}async revokeAuthSession(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(W,"POST",t)}async revokeAuthUserSessions(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(q,"POST",t)}async getAuthCapabilities(){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Q,"GET")}async updateAuthUser(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Y,"POST",t)}async listAuthAccounts(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(e(X,{userId:t.userId}),"GET")}async unlinkAuthAccount(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Z,"POST",t)}async listAuthPasskeys(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(e(tt,{userId:t.userId}),"GET")}async deleteAuthPasskey(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(at,"POST",t)}async disableAuthTwoFactor(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(st,"POST",t)}async listAuthOrganizations(t={}){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(e(et,{limit:t.limit,offset:t.offset}),"GET")}async listAuthOrgMembers(t){this.adminHost.assertOpen();const s=e(nt,{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(it,{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(rt,{limit:t.limit,offset:t.offset});return await this.adminHost.adminFetch(s,"GET")}async createAuthSignUpInvitation(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(ct,"POST",t)}async revokeAuthSignUpInvitation(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(dt,"POST",t)}async removeAuthOrgMember(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(ot,"POST",t)}async cancelAuthOrgInvitation(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(mt,"POST",t)}async getAuthConfig(){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(ht,"GET")}async createAuthOrganization(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Tt,"POST",t)}async updateAuthOrganization(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ht,"POST",t)}async deleteAuthOrganization(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(At,"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(Ot,"POST",t)}async setAuthOrgMemberRole(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(_t,"POST",t)}async listAuthOrgTeams(t){this.adminHost.assertOpen();const s=e(lt,{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(yt,"POST",t)}async updateAuthOrgTeam(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Et,"POST",t)}async removeAuthOrgTeam(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Pt,"POST",t)}async listAuthOrgTeamMembers(t){this.adminHost.assertOpen();const s=e(St,{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(ft,"POST",t)}async removeAuthOrgTeamMember(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ut,"POST",t)}async listAuthOrgRoles(t){this.adminHost.assertOpen();const s=e(pt,{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(wt,"POST",t)}async updateAuthOrgRole(t){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ft,"POST",t)}async deleteAuthOrgRole(t){this.adminHost.assertOpen(),await this.adminHost.adminFetch(bt,"POST",t)}async listAuthSessions(t={}){this.adminHost.assertOpen();const s=e(It,{limit:t.limit,offset:t.offset,userId:t.userId});return await this.adminHost.adminFetch(s,"GET")}}const ea=a=>"listAuthUsers"in a;export{sa as LunoraAdminClient,ea as isLunoraAdminClient};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{L as j}from"./lunora-client-CciSmQ-I.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-JAkvuahE.mjs";import"./CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import"./httpStream-ChJxN9M1.mjs";import"./createLocalStore-D38o4O8Z.mjs";import"./offline-queue-BEqCPDmw.mjs";import"./optimistic-layers-D-7D3yeJ.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-BKgQtuh9.mjs";import"./wire-errors-BDckSTKZ.mjs";export{j as LunoraClient};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{w as s}from"./optimistic-layers-D-7D3yeJ.mjs";let d=0;const o="lunora-bridge",h=1e3,b=3e3;class u{bc;tabId;heartbeatInterval;leaderTimeout;knownLeader=void 0;leader=!1;running=!1;promotionPending=!1;lastHeartbeat=0;pendingData=new Map;heldData=new Map;heartbeatTimer=void 0;leaderCheckTimer=void 0;onBecomeLeader;onStopBeingLeader;onConnectionStatus;onSubscriptionData;onLeaderClaimAnswered;onSubscriptionError;onSubscriptionSettled;constructor(t={}){if(d+=1,this.tabId=`tab_${String(d)}_${crypto.randomUUID()}`,this.heartbeatInterval=t.heartbeatInterval??h,this.leaderTimeout=t.leaderTimeout??b,this.onBecomeLeader=t.onBecomeLeader,this.onStopBeingLeader=t.onStopBeingLeader,this.onConnectionStatus=t.onConnectionStatus,this.onSubscriptionData=t.onSubscriptionData,this.onLeaderClaimAnswered=t.onLeaderClaimAnswered,this.onSubscriptionError=t.onSubscriptionError,this.onSubscriptionSettled=t.onSubscriptionSettled,typeof BroadcastChannel>"u"){this.bc=void 0;return}this.bc=new BroadcastChannel(t.channelName??o),this.bc.addEventListener("message",e=>{this.handleMessage(e.data)})}start(){if(!this.running){if(this.running=!0,this.bc===void 0){this.becomeLeader();return}this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout),this.leaderCheckTimer=setInterval(()=>{this.checkLeaderHealth()},this.leaderTimeout),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeat()},this.heartbeatInterval)}}stop(){this.running=!1,this.leader&&(this.broadcast({type:"yield-leadership",tabId:this.tabId}),this.leader=!1,this.knownLeader=void 0,this.onStopBeingLeader?.()),this.heartbeatTimer!==void 0&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0),this.leaderCheckTimer!==void 0&&(clearInterval(this.leaderCheckTimer),this.leaderCheckTimer=void 0),this.bc?.close()}isLeader(){return this.leader}promoteImmediately(){this.running&&this.becomeLeader()}get leaderTabId(){return this.knownLeader}get id(){return this.tabId}get isRunning(){return this.running}broadcastSubscriptionData(t,e,i,r,a){this.leader&&(this.pendingData.size===0&&queueMicrotask(()=>{this.flushPendingData()}),this.pendingData.set(t,{type:"subscription-data",tabId:this.tabId,key:t,data:e,...i===void 0?{}:{cursor:i},...r===void 0?{}:{epoch:r},...a===void 0?{}:{identity:a}}))}broadcastSubscriptionError(t,e,i){this.leader&&this.broadcast({type:"subscription-error",tabId:this.tabId,key:t,error:e,...i===void 0?{}:{identity:i}})}broadcastSubscriptionSettled(t,e,i,r,a,n){this.leader&&this.broadcast({type:"subscription-settled",tabId:this.tabId,key:t,...e===void 0?{}:{cursor:e},...i===void 0?{}:{epoch:i},...r===void 0?{}:{lastMutationId:r},...a===void 0?{}:{clientId:a},...n===void 0?{}:{identity:n}})}broadcastConnectionStatus(t,e){this.leader&&this.broadcast({type:"connection-status",tabId:this.tabId,status:t,...e===void 0?{}:{identity:e}})}broadcast(t){this.flushPendingData(),this.bc?.postMessage(t)}flushPendingData(){if(this.pendingData.size===0)return;const t=[...this.pendingData.values()];if(this.pendingData.clear(),!this.leader)return;let e,i=!0;for(const[r,a]of t.entries()){const n=r<t.length-1;try{this.bc?.postMessage(n?{...a,more:!0}:a),e=a,i=!n}catch{}}!i&&e!==void 0&&this.bc?.postMessage(e)}applySubscriptionData(t){const e=this.heldData.get(t.tabId)??[];if(e.push(t),t.more===!0){this.heldData.set(t.tabId,e);return}this.heldData.delete(t.tabId),s(()=>{for(const i of e)this.onSubscriptionData?.(i.key,i.data,i.cursor,i.epoch,i.identity)},()=>this.running)}handleMessage(t){switch(t.type){case"claim-leadership":{this.handleClaimLeadership(t);break}case"connection-status":{if(this.leader||t.tabId===this.tabId)break;this.onConnectionStatus?.(t.status,t.identity);break}case"heartbeat":{this.handleHeartbeat(t);break}case"subscription-data":{if(this.leader||t.tabId===this.tabId)break;this.applySubscriptionData(t);break}case"subscription-error":{if(this.leader||t.tabId===this.tabId)break;this.onSubscriptionError?.(t.key,t.error,t.identity);break}case"subscription-settled":{if(this.leader||t.tabId===this.tabId)break;this.onSubscriptionSettled?.(t.key,t.cursor,t.epoch,t.lastMutationId,t.clientId,t.identity);break}case"yield-leadership":{this.heldData.delete(t.tabId),this.knownLeader===t.tabId&&(this.knownLeader=void 0,this.running&&!this.leader&&this.claimAndPromote());break}}}handleClaimLeadership(t){if(t.tabId!==this.tabId){if(this.leader){this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}),this.onLeaderClaimAnswered?.();return}this.knownLeader===void 0&&t.tabId<this.tabId&&(this.knownLeader=t.tabId,this.lastHeartbeat=t.ts)}}handleHeartbeat(t){if(t.tabId!==this.tabId){if(this.leader){this.resolveLeaderVsLeaderTieBreak(t);return}this.lastHeartbeat=t.ts,this.knownLeader=t.tabId}}resolveLeaderVsLeaderTieBreak(t){t.tabId<this.tabId?(this.leader=!1,this.knownLeader=t.tabId,this.lastHeartbeat=t.ts,this.onStopBeingLeader?.()):this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}becomeLeader(){this.leader||(this.leader=!0,this.knownLeader=this.tabId,this.lastHeartbeat=Date.now(),this.onBecomeLeader?.(),this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}))}sendHeartbeat(){this.leader&&this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}checkLeaderHealth(){if(!this.running||this.leader)return;if(this.knownLeader===void 0){this.claimAndPromote();return}Date.now()-this.lastHeartbeat>this.leaderTimeout&&(this.heldData.delete(this.knownLeader),this.knownLeader=void 0,this.claimAndPromote())}claimAndPromote(){this.promotionPending||(this.promotionPending=!0,this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.promotionPending=!1,this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout))}}export{u as TabCoordinator};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as f}from"./optimistic-layers-D-7D3yeJ.mjs";import{SubscriptionRegistry as i}from"./SubscriptionRegistry-BKgQtuh9.mjs";const g=(s,a)=>{const n=[],l=[],c=(e,t)=>s.get(i.key(e,t,a));return{confirms:n,rollbacks:l,store:{getAllQueries:e=>{const t=[];for(const r of s.all())r.fn.__lunoraRef===e.__lunoraRef&&(r.shardKey??"")===(a??"")&&t.push({args:r.args,value:r.lastValue});return t},getQuery:(e,t)=>c(e.__lunoraRef,t??{})?.lastValue,setQuery:(e,t,r)=>{const u=c(e.__lunoraRef,t??{});if(!u)return;const o=f(u,()=>r);o&&(n.push(o.confirm),l.push(o.rollback))}}}};export{g as createLocalStore};
|
package/dist/packem_shared/{createServerClient-CCCSB2eL.mjs → createServerClient-BqlNr7xM.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{L as r}from"./lunora-client-
|
|
1
|
+
import{L as r}from"./lunora-client-CciSmQ-I.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 v,OFFLINE_NOT_QUEUED_HINT as xe}from"@lunora/errors";import{decodeWire as _,encodeWire as re,stableWireKey as ae}from"@lunora/wire";import{t as Re}from"./base64-849R7V-V.mjs";import{r as qe,U as Ke,P as je}from"./delta-merge-C6OqMEPH.mjs";import Ge from"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import{w as C,u as ne,s as Oe,a as $e,i as Q,e as x,r as ce,b as de,c as Ve,d as ue,f as ze}from"./wire-errors-BDckSTKZ.mjs";import{ClientQueryStore as Je}from"./createClientQuery-B8Nfj-7o.mjs";import{D as Ye,a as Xe,b as Ze,c as et,d as tt,S as he,M as st,I as it,Q as rt,R as nt,e as le,f as ot,g as at}from"./client-tuning-C10B2KCO.mjs";import{j as w,d as fe,p as q,s as pe}from"./client-urls-BHLUjjcG.mjs";import{TabCoordinator as ct}from"./TabCoordinator-JAkvuahE.mjs";import{TransportError as U,getRetryAfterMs as dt,AUTH_REPLAY_ERROR_CODES as ut,isAuthReplayFailure as K}from"./CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as ht}from"./httpStream-ChJxN9M1.mjs";import{createLocalStore as lt}from"./createLocalStore-D38o4O8Z.mjs";import{O as ft,n as me,i as pt}from"./offline-queue-BEqCPDmw.mjs";import{d as mt,b as Z,r as F,c as P,a as yt,w as St,e as vt,f as bt}from"./optimistic-layers-D-7D3yeJ.mjs";import{resolvePersistenceAdapter as gt}from"./createInMemoryPersistence-C-IzNVbg.mjs";import{w as D,a as ye,b as wt}from"./stream-idle-C7CsIT_m.mjs";import{resolveQueryCacheAdapter as Tt,queryCacheKey as M}from"./createInMemoryQueryCache-DR6AorA2.mjs";import{createReconnect as Se}from"./createReconnect-CjTmjJDH.mjs";import{fanSubscriptionError as R,setSubscriptionAck as I,SubscriptionRegistry as T,wrapSubscriber as G,releaseSubscribeFrame as $}from"./SubscriptionRegistry-BKgQtuh9.mjs";import{c as kt,s as ve,r as Ct}from"./snapshot-precondition-BEtcSbWr.mjs";import{createStream as At}from"./DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";const Et="/_lunora/rpc",V="/_lunora/rpc-batch",z="/_lunora/ws",hi="/_lunora/admin/shard-traffic",_t="/_lunora/admin/scheduled",It="/_lunora/admin/scheduled/status",Rt="/_lunora/admin/scheduled/ws",Ot="/_lunora/admin/scheduled/cancel",be="/_lunora/admin/scheduled/dead",Lt="/_lunora/admin/scheduled/dead/retry",Pt="/_lunora/admin/scheduled/dead/cancel",Mt="/_lunora/admin/workflows/instances",Ft="/_lunora/admin/workflows/instance",Ht="/_lunora/admin/workflows/status",li="/_lunora/admin/storage",fi="/_lunora/admin/storage/url",pi="/_lunora/admin/storage/buckets",mi="/_lunora/admin/functions",yi="/_lunora/admin/cron-jobs",Si="/_lunora/admin/cron-jobs/run",vi="/_lunora/admin/architecture",bi="/_lunora/admin/openapi",gi="/_lunora/admin/openrpc",wi="/_lunora/admin/global/tables",Ti="/_lunora/admin/global/table",ki="/_lunora/admin/global/facet",Ci="/_lunora/admin/vector/indexes",Ai="/_lunora/admin/vector/query",Ei="/_lunora/admin/logs/archive",_i="/_lunora/admin/kv/namespaces",Ii="/_lunora/admin/kv/keys",Ri="/_lunora/admin/kv/value",Oi="/_lunora/admin/auth/users",Li="/_lunora/admin/auth/sessions",Pi="/_lunora/admin/auth/users/create",Mi="/_lunora/admin/auth/users/role",Fi="/_lunora/admin/auth/users/ban",Hi="/_lunora/admin/auth/users/unban",Ui="/_lunora/admin/auth/users/password",Ni="/_lunora/admin/auth/users/remove",Wi="/_lunora/admin/auth/users/impersonate",Bi="/_lunora/admin/auth/sessions/revoke",Di="/_lunora/admin/auth/sessions/revoke-all",Qi="/_lunora/admin/auth/capabilities",xi="/_lunora/admin/auth/users/update",qi="/_lunora/admin/auth/accounts",Ki="/_lunora/admin/auth/accounts/unlink",ji="/_lunora/admin/auth/passkeys",Gi="/_lunora/admin/auth/passkeys/delete",$i="/_lunora/admin/auth/two-factor/disable",Vi="/_lunora/admin/auth/organizations",zi="/_lunora/admin/auth/organizations/members",Ji="/_lunora/admin/auth/organizations/invitations",Yi="/_lunora/admin/auth/organizations/members/remove",Xi="/_lunora/admin/auth/organizations/invitations/cancel",Zi="/_lunora/admin/auth/config",er="/_lunora/admin/auth/sign-up-invitations",tr="/_lunora/admin/auth/sign-up-invitations/create",sr="/_lunora/admin/auth/sign-up-invitations/revoke",ir="/_lunora/admin/auth/organizations/create",rr="/_lunora/admin/auth/organizations/update",nr="/_lunora/admin/auth/organizations/remove",or="/_lunora/admin/auth/organizations/members/add",ar="/_lunora/admin/auth/organizations/members/invite",cr="/_lunora/admin/auth/organizations/members/role",dr="/_lunora/admin/auth/organizations/teams",ur="/_lunora/admin/auth/organizations/teams/create",hr="/_lunora/admin/auth/organizations/teams/update",lr="/_lunora/admin/auth/organizations/teams/remove",fr="/_lunora/admin/auth/organizations/teams/members",pr="/_lunora/admin/auth/organizations/teams/members/add",mr="/_lunora/admin/auth/organizations/teams/members/remove",yr="/_lunora/admin/auth/organizations/roles",Sr="/_lunora/admin/auth/organizations/roles/create",vr="/_lunora/admin/auth/organizations/roles/update",br="/_lunora/admin/auth/organizations/roles/remove",Ut="/api/auth",Nt="/get-session",Wt="lunora-ping",J=500,Le=(n,e)=>{if(n.size<e)return;const t=n.keys().next().value;t!==void 0&&n.delete(t)};new TextDecoder;const Bt=new TextEncoder,Dt=n=>Re(Bt.encode(n)),Qt=n=>Dt(JSON.stringify(n)),xt="x-lunora-expect-subject",qt=n=>Qt({subject:n}),Kt="refreshBatch",ge=Symbol.for("lunora:session-change"),jt="lunora:session-change",Gt="better-auth.message",$t="signout",Pe=()=>{const n=globalThis;let e=n[ge];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},n[ge]=e),e},Vt=()=>"document"in globalThis,zt=async()=>{const n=[];for(const e of Pe().listeners)try{n.push(e())}catch{}await Promise.allSettled(n)},Jt=(n,e)=>{if(n!==Gt||e===null)return!1;try{const t=JSON.parse(e);return t?.event==="session"&&t.data?.trigger===$t}catch{return!1}},Yt=n=>{const e=[],t=()=>{zt().catch(()=>{})};let s;try{s=typeof BroadcastChannel=="function"?new BroadcastChannel(jt):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=>{Jt(a.key,a.newValue)&&t()};i.addEventListener("storage",r),e.push(()=>{i.removeEventListener?.("storage",r)})}return()=>{for(const r of e)r()}},Xt=n=>{const e=Pe();return e.listeners.add(n),e.detach===void 0&&Vt()&&(e.detach=Yt(e.tab)),()=>{e.listeners.delete(n),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},we="/_lunora/ws/reauth",Zt="lunora",es="lunora.bearer.",ts=n=>`${es}${Re(new TextEncoder().encode(n))}`,ss=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}},oe=n=>"args"in n?{...n,args:_(n.args)}:n,gr=async n=>(n.assertOpen(),((await n.adminFetch(_t,"GET")).records??[]).map(t=>oe(t))),wr=async n=>{n.assertOpen();const e=await n.adminFetch(It,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},Tr=async(n,e)=>(n.assertOpen(),{cancelled:(await n.adminFetch(Ot,"POST",{id:e})).cancelled===!0}),kr=async n=>(n.assertOpen(),(await ss(async t=>await n.adminFetch(t===void 0?be:`${be}?cursor=${encodeURIComponent(t)}`,"GET"))).map(t=>oe(t))),Cr=async(n,e)=>(n.assertOpen(),{retried:(await n.adminFetch(Lt,"POST",{id:e})).retried===!0}),Ar=async(n,e)=>(n.assertOpen(),{removed:(await n.adminFetch(Pt,"POST",{id:e})).removed===!0}),Er=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(`${Mt}?${t.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}},_r=async(n,e)=>{n.assertOpen();const t=new URLSearchParams({id:e.id,name:e.name}),s=await n.adminFetch(`${Ft}?${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??[]}},Ir=async(n,e)=>(n.assertOpen(),{status:(await n.adminFetch(Ht,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),E=(n,e)=>{try{return re(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)}},ee=n=>{try{return re(n),!0}catch{return!1}},Me=n=>n!==null&&typeof n=="object"&&("error"in n||"result"in n),is=(n,e,t)=>{const s=Array.from({length:e}),i=r=>({error:C(Oe(r),t),ok:!1});for(const r of n){if(typeof r.id!="number"||r.id<0||r.id>=e)continue;if(!Me(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:C(ne(o),t),ok:!1}}}return s.map(r=>r??{error:C(new Error("batch call returned no result"),t),ok:!1})},Y=(n,e)=>e!==null?{}:n===null?{expectSubject:null}:n?.startsWith("subj:")===!0?{expectSubject:n.slice(5)}:{},W=n=>n==="connected"||n==="polling",f=n=>n??"",k=(n,e)=>{if(!n.socket||n.wsState!=="open")return!1;try{return n.socket.send(JSON.stringify(e)),!0}catch{return!1}},rs=n=>{if(!n.pendingStreams||n.pendingStreams.length===0)return;const e=n.pendingStreams;n.pendingStreams=[];for(const t of e)k(n,t)},ns=new TextDecoder,os=n=>{if(typeof n=="string")return n;if(n instanceof ArrayBuffer)return ns.decode(n)};class O{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 H=n=>{n.heartbeatTimer!==void 0&&(clearInterval(n.heartbeatTimer),n.heartbeatTimer=void 0)},as=(n,e,t)=>{H(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(Wt)}catch{}},e))},Te=(n,e,t,s)=>{const{WebSocketImpl:i,connectTimeoutMs:r,heartbeatIntervalMs:a}=t;if(i===void 0)throw new v("INTERNAL","no WebSocket implementation available");const o=s.protocols===void 0?new i(e):new i(e,s.protocols);n.socket=o;const c=()=>{H(n),n.connectTimer!==void 0&&(clearTimeout(n.connectTimer),n.connectTimer=void 0),n.socket===o&&(n.socket=void 0)},d=u=>{c(),s.onClose(u)};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(u){console.error("[lunora] connection open handler threw",u)}n.socket===o&&as(n,a,d)}}),o.addEventListener("message",u=>{if(n.socket===o){n.lastFrameAt=Date.now();try{s.onMessage(u)}catch(h){console.error("[lunora] server frame handler threw",h)}}}),o.addEventListener("close",u=>{n.socket===o&&d(u)}),o.addEventListener("error",()=>{n.socket===o&&d()})},cs=n=>{const{afterFailedAttempts:e,intervalMs:t,onReachable:s,onStateChange:i,poll:r}=n,a=t>0&&e>0;let o=0,c,d=!1,u=!1;const h=()=>{c!==void 0&&(clearInterval(c),c=void 0,d=!1,i())},l=y=>{if(c!==void 0){if(!y){h();return}d||(d=!0,i()),s()}},p=()=>{u||(u=!0,r().then(l).finally(()=>{u=!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}},ds=1e4,ke=async n=>D(ds,void 0,n,()=>new TypeError("LunoraClient: poll timed out")),Fe=new Set(["DELIVERY_FENCED","RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Ce=n=>{if(n instanceof U)return!0;const e=n?.code;return e===void 0||Fe.has(e)||ut.has(e)},us=1e3,He=6e4,hs={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},B=(n,e,t)=>{const s=$e(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 U(r,i):new v(hs[n]??"BAD_REQUEST",r,{data:i});return C(a,t)},te=(n,e=Math.random)=>{const t=Math.min(us*2**Math.max(n-1,0),He);return Math.round(t*(.5+e()*.5))},ls=n=>{const e=n?.code;return n instanceof U||e===void 0||Fe.has(e)},fs=(n,e,t)=>{const s=dt(n);return s!==void 0&&s>0?Math.min(s,He):ls(n)?te(e,t):void 0},ps=983040,ms=n=>typeof TextEncoder>"u"?n.length:new TextEncoder().encode(n).length,ys=n=>{const e=new Map;for(const t of n)typeof t.id=="number"&&Me(t.body)&&e.set(t.id,t.body);return e},Ss=(n,e)=>{if(n===void 0)return{kind:"unanswered"};if("error"in n)return{error:C(Oe(n),e),kind:"errored"};try{return{commitCursor:n.commitCursor,kind:"committed",value:_(n.result)}}catch(t){return{commitCursor:n.commitCursor,error:C(ne(t),e),kind:"undecodable"}}},X=(n,e)=>`${f(n)}\0${e}`,vs=(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 bs{constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,t){Le(this.buffers,this.maxBuffers),this.buffers.set(X(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(X(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=X(e,t),i=this.buffers.get(s);return i&&this.buffers.delete(s),i}clear(){this.buffers.clear()}}const gs=(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(),vs(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"},Ae=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&&R(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape — ${s instanceof Error?s.message:String(s)}`})}},se=(n,e)=>{n.lastMutationId=Math.max(n.lastMutationId??0,e)},ie=(n,e=!1)=>{const t=n.serverCursor,s=n.lastMutationId;mt(()=>{for(const i of n.checkpointCallbacks)i({checkpoint:t,mutationId:s,...e&&{rowsFollow:!0}})})},Ue=(n,e,t)=>{n.serverBase=e,t.cursor!==void 0&&(n.serverCursor=t.cursor),t.epoch!==void 0&&(n.serverEpoch=t.epoch)},Ts=(n,e)=>e.cursor!==void 0&&n.serverCursor!==void 0&&n.serverBase!==void 0&&e.epoch!==void 0&&e.epoch===n.serverEpoch&&e.cursor<n.serverCursor,ks=n=>n.type==="delta"&&n.more===!0,j=(n,e)=>n!==void 0&&n!==e,Cs=(n,e)=>e==="connected"&&n!=="connected"||e==="polling"&&n!=="connected"&&n!=="polling",As=n=>{for(const e of n.activeSubscriptions())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()},Es=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()},_s=(n,e,t)=>{if(j(t,n.identityFingerprint()))return;const s=n.leader,i=Cs(s.status,e);s.status=e,e==="connected"&&(s.wasEverConnected=!0),n.emitConnectionStatus(),i&&(n.awaitLeaderAnswers(),n.flushOfflineQueues())},Is=n=>{n.isLeader()&&n.broadcastStatus(n.computeStatus(),n.identityFingerprint())},Rs=(n,e,t,s,i,r)=>{if(j(r,n.identityFingerprint()))return;const a=n.subscription(e);if(!a)return;n.dropCacheSeed(e);const o=!a.valueReceived;a.valueReceived=!0,Ue(a,t,s===void 0?{}:{cursor:s,epoch:i}),s!==void 0&&Z(a,s),F(a,t),o&&n.emitConnectionStatus(),n.settleAwaitedAnswer(a,!0)},Os=(n,e,t,s)=>{if(j(s,n.identityFingerprint()))return;const i=n.subscription(e);if(i){const r=!i.valueReceived;i.valueReceived=!0,R(i.errorCallbacks,t),r&&n.emitConnectionStatus(),n.settleAwaitedAnswer(i,!1)}},Ls=(n,e,t,s,i,r,a)=>{if(j(a,n.identityFingerprint()))return;const o=n.subscription(e);o&&(n.ackAndAdvanceCursor(o,t,s),i!==void 0&&r===n.clientIdentifier()&&se(o,i),ie(o))},Ps=(n,e,t)=>n!==null||e&&t===null,Ms=n=>n.sensitive===!0,Fs=(n,e)=>{if(!Ms(n))return e;if(e.onlineOnly===!1)throw new v("BAD_REQUEST",`'${n.__lunoraRef}' takes a sensitive argument and is always online-only; onlineOnly: false is not allowed`);return{...e,onlineOnly:!0}},Hs=[je,Kt],Us=n=>n.type==="data"||n.type==="delta"||n.type==="settled"||n.type==="resume"||n.type==="error"&&typeof n.id=="string",Ns=100,Ne=1e4,Ws=1e4,Bs=(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)})},Ee=async n=>typeof n=="function"?await n():n,_e=async(n,e,t,s)=>{const i=new AbortController,r=setTimeout(()=>{i.abort()},Ne);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)}},Ie=(n,e)=>new v("OFFLINE_NOT_QUEUED",`'${n}' is online-only and the connection is not live, so it was not queued`,{cause:e,hint:xe}),Ds=(n,e)=>n instanceof TypeError&&ee(e),Qs=(n,e,t,s)=>e||n===!0&&t&&!s,xs=Promise.resolve();class We{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;authTokenOnUpgrade;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;mutationIssueCounter=0;persistence;persistenceVersion;releasePageHideFlush;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new T;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 O;statusListeners=new O;roomFlushes=new Map;roomIdentityResets=new Set;tokenExpiredListeners=new O;identityChangeListeners=new O;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new O;pendingChangeListeners=new O;syncStatusListeners=new O;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 bs(We.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??w(fe(e.url),z),this.wsToken=e.wsToken,this.wsTicket=e.wsTicket;const t=e.authBasePath??Ut;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??Ge(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??Ye,this.connectTimeoutMs=e.connectTimeoutMs??Xe,this.rpcTimeoutMs=e.rpcTimeoutMs??Ze,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??et,this.authTokenOnUpgrade=e.authTokenOnUpgrade??!1,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??tt,this.defaultConnectionContext=e.connectionContext,this.persistence=gt(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Tt(e.queryCache),this.clientQueryStore=new Je,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=xs),this.offlineQueue=new ft(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-${me()}`,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=Xt(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,t){const s=this.authToken!==e,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(),u=!s&&e!==null&&r,h=!s&&e===null&&i===null&&r&&!o,l=d!==i;let p=!1;l&&(u?(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,l)),l&&this.restartTabCoordinatorForIdentity(),this.syncReadCacheToCredential(a),s&&this.authTokenListeners.emit(e),(d!==i||s||a)&&this.offlineQueue.size>0&&W(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 v("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&&(Le(this.clientWatermarks,at),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,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}${Nt}`),{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 u=this.getConnection(s.shardKey);u&&k(u,{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 v("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 l=()=>{const S=h;h=void 0,S?.()};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:l,stream:r,topic:a});const y=this.getConnection(i)?.connectionId;y!==void 0&&this.grantWhenJoined(i,o,y);let m=!1;return()=>{if(m)return;m=!0;const S=this.liveSocketGrants.get(c),A=S?.delete(o)===!0;S?.size===0&&this.liveSocketGrants.delete(c);const b=this.getConnection(i)?.connectionId;A&&b!==void 0&&this.postLiveControl(d,i,{action:"unsubscribe",connectionId:b,stream:r,subscriptionId:o,topic:a}),l()}}whisper(e,t,s={}){return this.assertLeaderOwnedSurface("whisper"),this.sendEncodedWhisper(e,E(t??null,`whisper data for topic '${e}'`),s)}connectRoom(e,t,s={}){const i=`room:${e.name}`,r=this.whisperSubscribe(i,l=>{t.onMessage(l)},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()}},u=f(s.shardKey),h=this.roomFlushes.get(u)??new Set;return h.add(d),this.roomFlushes.set(u,h),this.roomIdentityResets.add(c),{close:()=>{a=!0,o.length=0,h.delete(d),h.size===0&&this.roomFlushes.delete(u),this.roomIdentityResets.delete(c),r()},send:l=>{if(a||this.closed||this.WebSocketImpl===void 0)return!1;const p=E(l,`room message for '${i}'`),y=typeof structuredClone=="function"?structuredClone(p):JSON.parse(JSON.stringify(p));return d(),o.length===0&&this.roomSendsAdmitted(s.shardKey)&&this.sendEncodedWhisper(i,y,s)?!0:o.length>=Ns?!1:(o.push(y),!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()},he),i(t.onOpen)},shardKey:s.shardKey});return{close:()=>{clearTimeout(r),a.close()},send:o=>{const c=JSON.stringify(E(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:W(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=q(this.wsUrl),i=a=>{const o=q(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 kt(this,e,t,s)}whenReady(e={}){return e.signal===void 0?this.readyPromise:ye(this.readyPromise,e.signal)}get isReady(){return this.readyResolved}peekHydratedQuery(e,t,s){return this.peekHydratedQueryByKey(e,ae(t),s)}peekHydratedQueryByKey(e,t,s){if(!this.readyResolved)return;const 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=T.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 D(this.rpcTimeoutMs,void 0,async t=>this.sendBatch(e,t))}async mutation(e,t,s={}){if(s.signal?.aborted)throw wt(s.signal);const{value:i}=await ye(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??(u=>({rows:u})),a=t.length;let o=0,c=0,d=0;for(let u=0;u<a;u+=i){const h=t.slice(u,u+i),l=d,{committed:p}=await this.runMutation(e,r(h),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(l)}`},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(fe(this.url),Rt),{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=>oe(r))))}});return t.close}subscribe(e,t,s,i={}){if(this.assertOpen(),i.signal?.aborted)return()=>{};const r=t??{},a=T.key(e.__lunoraRef,r,i.shardKey);let o=this.subscriptions.get(a);const c=G(s),d=G(i.onError),u=G(i.onCheckpoint);if(!o){this.nextSubId+=1;const y=`sub_${this.nextSubId.toString()}`,m=ae(r),S=this.takeHydratedCache(e.__lunoraRef,m,i.shardKey);o={ack:"idle",args:r,argsKey:m,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:y,lastValue:S?.value,optimisticLayers:[],serverBase:S?.value,serverCursor:S?.serverCursor,shardKey:i.shardKey,valueReceived:!1,wireArgs:E(r,`args for '${e.__lunoraRef}'`),...S?.serverEpoch===void 0?{}:{serverEpoch:S.serverEpoch}},this.subscriptions.add(o),this.emitSyncStatus(),this.isCrossTabFollower()&&W(this.computeStatus())&&this.awaitLeaderAnswer(o),S!==void 0&&this.cacheSeededQueries.set(a,S)}if(o.callbacks.add(c),d&&o.errorCallbacks.add(d),u&&o.checkpointCallbacks.add(u),o.lastValue!==void 0)try{c(o.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(o);const h=o;let l=!1;const p=()=>{if(!l&&(l=!0,i.signal?.removeEventListener("abort",p),h.callbacks.delete(c),d&&h.errorCallbacks.delete(d),u&&h.checkpointCallbacks.delete(u),h.callbacks.size===0)){this.sendOrQueueUnsubscribe(h.shardKey,h.id,"unsubscribe"),this.returnCacheSeed(T.keyOf(h)),this.subscriptions.remove(h);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",p,{once:!0}),i.signal?.aborted&&p(),p}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:E(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 v("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}=At({maxBuffer:s.maxBuffer,onCancel:()=>{this.cancelStream(i,r)}});this.ensureSocket(r);const d=this.getConnection(r),u={id:i,query:{args:E(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:u,shardKey:r};this.streams.set(i,h);const l=d?.wsState==="open"&&k(d,u);if(!l&&d===void 0)return this.forgetStream(i),o.fail(new v("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),c;if(!l){for(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=st;){const y=d.pendingStreams.shift()?.id,m=y?this.streams.get(y):void 0;m&&(m.handle.fail(new v("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(y))}d.pendingStreams.push(u)}return c}httpStream(e,t,s={}){if(this.closed)throw new v("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new v("INTERNAL","LunoraClient: no `fetch` implementation available");const i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return ht(e,t,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0;for(const e of this.whisperJoins.keys())this.dropWhisperJoinWaiters(e);this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.releasePageHideFlush?.(),this.releasePageHideFlush=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const e of this.streams.values())e.handle.fail(new v("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();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){return this.rejectQueuedForIdentityChange(e),this.warnRefreshWithoutSubject(s,i),Ps(e,t,i)?(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?[Zt,ts(this.authToken)]:void 0}applyUpgradeBearer(e){e==="cold"?(this.resetRoomSends(),this.reconnectCold()):e==="warm"&&this.bounceShardSockets(!0)}assertOpen(){if(this.closed)throw new v("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 v("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}shardInUse(e){const t=s=>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())},it))}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 v("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,H(e);const{socket:s}=e;if(s){e.socket=void 0;try{s.close()}catch{}}e.wsState="closed"}createTabCoordinator(){const e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`,t={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,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 ct({channelName:e,onBecomeLeader:()=>{As(t)},onStopBeingLeader:()=>{Es(t)},onConnectionStatus:(s,i)=>{_s(t,s,i)},onSubscriptionData:(s,i,r,a,o)=>{Rs(t,s,i,r,a,o)},onLeaderClaimAnswered:()=>{Is(t)},onSubscriptionError:(s,i,r)=>{Os(t,s,i,r)},onSubscriptionSettled:(s,i,r,a,o,c)=>{Ls(t,s,i,r,a,o,c)}})}async sendBatch(e,t){if(this.assertOpen(),!this.fetchImpl)throw new v("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];const s=await this.fetchImpl(w(this.url,V),{body:JSON.stringify({calls:e.map((o,c)=>({args:E(o.args??{},`args for batch call '${o.fn.__lunoraRef}'`),functionPath:o.fn.__lunoraRef,id:c,shardKey:o.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:t}),i=s.headers.get("x-d1-bookmark");i&&this.bookmark.set(i);let r;try{r=await s.json()}catch{throw C(new v("INTERNAL",`LunoraClient: batch response was not JSON (status ${s.status.toString()})`),s.headers)}const a=x(r);if(!s.ok||a!==void 0&&!r.results)throw a!==void 0?C(ce(a),s.headers):C(new v("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 is(r.results??[],e.length,s.headers)}async runMutation(e,t,s){this.assertOpen();const i=Fs(e,s),r=t,a=i.mutationId??me();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{confirms:u,rollbacks:h}=this.applyOptimisticUpdates(e.__lunoraRef,r,i.shardKey,i.optimistic);this.applyOptionalOptimisticUpdate(i.optimisticUpdate,t,i.shardKey,h,u);const l=i.onlineOnly?void 0:this.offlineFlushes.get(f(i.shardKey));l!==void 0&&await l;const{httpFirst:p,midReconnect:y,shouldQueueOffline:m,socketDown:S}=this.writeQueueGate(i.shardKey),A=!i.onlineOnly&&m&&i.replayBaseline===void 0&&this.hasPendingWriteAhead(i.shardKey),b=async(g=!1)=>this.enqueueOfflineMutation(e,r,i.shardKey,d,a,h,u,g?void 0:i.precondition,i.mutationId,c?.stamp,g,o);if(this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i,h),S||y||A)return b();let N;try{const g=await this.rpc(e.__lunoraRef,r,i.shardKey,{baselineSeq:d,captureBookmark:!0,...c?.flags,mutationId:a,onCommitCursor:L=>{N=L}});for(const L of u)L(N);return{committed:!0,value:g}}catch(g){const L=Ds(g,r),Be=p&&m&&L,De=this.ownSocketOpen(i.shardKey);if(m&&!i.onlineOnly&&this.fetchImpl!==void 0&&!this.outbox&&i.replayBaseline===void 0&&(g instanceof TypeError||g instanceof U)&&ee(r)){const Qe=b(!0);return this.noteHeldRetryDelay(i.shardKey),this.scheduleRateLimitedRetry(i.shardKey),Qe}throw this.settleFailedDirectWrite(g,N,u,h,c?.flags.authToken),Qs(i.onlineOnly,Be,L,De)?Ie(e.__lunoraRef,g):g}}refuseOnlineOnlyWhenDown(e,t,s=[]){if(!t.onlineOnly)return;const i=this.writeQueueGate(t.shardKey);if(i.socketDown||i.midReconnect)throw P(s),Ie(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,u=i||s;return{httpFirst:u,midReconnect:a==="connecting"&&c&&!u,shouldQueueOffline:d,socketDown:a!=="open"&&!t&&d&&!u,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}P(i)}async enqueueOfflineMutation(e,t,s,i,r,a,o,c,d,u,h,l){const p=u===void 0?this.identityFingerprint():u;if(this.outbox){this.outboxMutationCounter+=1;const m=this.outboxMutationCounter;try{await this.outbox.enqueue({args:t,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:d??`${this.clientId}:${String(m)}`,identity:p,mutationId:m,...a.length>0&&{onRejected:()=>{P(a)}},shardKey:s})}catch(S){throw P(a),S instanceof Error?S:new Error(String(S))}for(const S of o)S(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((m,S)=>{const A={ambiguousSend:h,args:t,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:r,issueSeq:l,clientId:this.clientId,identity:p,precondition:this.holdWhileUnanswered(c),onCommit:b=>{for(const N of o)N(b)},reject:b=>{this.queuedIdentities.delete(r),Q(b)||P(a),S(b instanceof Error?b:new Error(String(b))),this.releaseIdleShard(s)},resolve:m,shardKey:s};this.offlineQueue.enqueue(A),this.queuedOfflineShardKeys.add(s),this.ensureSocket(s),A.id!==void 0&&this.queuedIdentities.set(A.id,p)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;const t=f(e);return 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=await this.queryCache.load(),t=new Map;for(const s of this.subscriptions.all())t.set(M(s.fn.__lunoraRef,s.argsKey,s.shardKey),s);for(const{key:s,...i}of e){if(pt(this.persistenceVersion,i.version)){this.queryCache.remove(s).catch(()=>{});continue}const r=t.get(s);if(r&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(r,i);continue}this.hydratedQueryCache.set(s,i)}}catch{}}seedSubscriptionFromCache(e,t){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(t)||(e.serverBase=t.value,e.serverCursor=t.serverCursor,t.serverEpoch!==void 0&&(e.serverEpoch=t.serverEpoch),this.cacheSeededQueries.set(M(e.fn.__lunoraRef,e.argsKey,e.shardKey),t),F(e,t.value))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}returnCacheSeed(e){const t=this.cacheSeededQueries.get(e);t!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,t))}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(const[e,t]of this.cacheSeededQueries){const s=this.subscriptions.get(e);s!==void 0&&(s.serverBase=void 0,s.serverCursor=void 0,s.serverEpoch=void 0,F(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,...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(()=>{})},rt))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;const{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}const t=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(t.map(async([s,i])=>e.put(s,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&&(ee(o.args)?s.push(o):(this.markQueryRejected(o,!0),R(o.errorCallbacks,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"})));if(s.length===0)return this.probeOrigin();const i=bt(),r=this.identityFingerprint();let a;try{a=await ke(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),R(c.errorCallbacks,{code:d.error.code,message:d.error.message});continue}this.handleDataMessage({data:re(d.value),id:c.id,type:"data"},i)}}return!0}async probeOrigin(){const{fetchImpl:e}=this;if(!e)return!1;try{return await ke(async t=>e(w(this.url,V),{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=T.key(e,t,s),c=this.subscriptions.get(o);if(c){const d=yt(c,i);d&&(r.push(d.confirm),a.push(d.rollback))}return{confirms:r,rollbacks:a}}applyOptionalOptimisticUpdate(e,t,s,i,r){e&&this.applyOptimisticUpdate(e,t,s,i,r)}applyOptimisticUpdate(e,t,s,i,r){const{confirms:a,rollbacks:o,store:c}=lt(this.subscriptions,s);try{e(c,t)}catch{P(o);return}i.push(...o),r.push(...a)}getConnection(e){return this.connections.get(f(e))}sendOrQueueUnsubscribe(e,t,s){const i=this.getConnection(e);i&&!k(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:cs({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:()=>{this.flushOfflineQueue(e).catch(()=>{})},onStateChange:()=>{this.emitConnectionStatus()},poll:async()=>this.pollSubscriptions(e)}),reconnect:Se(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=Se(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(l,s.next()))},c=m=>{a||this.WebSocketImpl===void 0||Te(i,this.wsUrlFor(t.shardKey,m,e),this.managedSocketOptions,{onClose:()=>{o(),t.onClose?.()},onMessage:t.onMessage,...t.onOpen===void 0?{}:{onOpen:t.onOpen},...t.offerBearer===!0?{protocols:this.upgradeProtocols()}:{}})};let d=0,u;const h=async m=>{const S=this.wsCredentialGeneration;d+=1;const A=d;let b;u=S;try{b=await Bs(m,Ws)}catch{A===d&&(u=void 0,o());return}if(A===d){if(u=void 0,S!==this.wsCredentialGeneration){l();return}c(b)}},l=()=>{if(a||this.WebSocketImpl===void 0)return;const{wsTicket:m}=this;if(typeof m=="function"){h(m).catch(()=>{});return}c(m)};l();const p=()=>{a=!0,r!==void 0&&(clearTimeout(r),r=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),H(i);const{socket:m}=i;i.socket=void 0;try{m?.close()}catch{}};this.adminSocketTeardowns.add(p);const y=()=>{const{socket:m}=i;if(m===void 0){u!==void 0&&u!==this.wsCredentialGeneration&&(d+=1,u=void 0,l());return}i.socket=void 0,i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),H(i);try{m.close()}catch{}t.onClose?.(),o()};return this.supplementaryBounces.add(y),{close:()=>{p(),this.adminSocketTeardowns.delete(p),this.supplementaryBounces.delete(y)},resetBackoff:()=>{s.reset()},socket:()=>i.socket}}supplementaryUrl(e){const t=q(this.wsUrl),s=t.pathname.endsWith(z)?t.pathname.slice(0,-z.length):t.pathname;return t.pathname=w(s,e),pe(t,this.wsUrl)}wsUrlFor(e,t,s=this.wsUrl){const i=q(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("&"),pe(i,s)}rpcRequestHeaders(e,t){const s={"content-type":"application/json"};e.expectSubject!==void 0&&(s[xt]=qt(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 U("LunoraClient: no `fetch` implementation available");const a=this.rpcRequestHeaders(i,s),o=i.authToken===void 0?this.authToken:i.authToken,c=JSON.stringify({args:E(t,`args for '${e}'`),functionPath:e,shardKey:s}),{body:d,response:u}=await D(i.unbounded?0:this.rpcTimeoutMs,i.signal,async p=>{const y=await r(w(this.url,Et),{body:c,headers:a,method:"POST",signal:p});try{return{body:await y.json(),response:y}}catch{return{body:void 0,response:y}}});if(i.captureBookmark){const p=u.headers.get("x-d1-bookmark");p&&this.bookmark.set(p)}if(d===void 0)throw B(u.status,u.statusText,u.headers);const h=d;if(typeof h!="object"||h===null||Array.isArray(h))throw B(u.status,u.statusText,u.headers);const l=x(d);if(l!==void 0)throw de(l,u.headers);if(!u.ok)throw B(u.status,u.statusText,u.headers);i.onMutationAck?.(d.lastMutationId),i.onCommitCursor?.(d.commitCursor),this.noteCredentialAccepted(o),this.learnDefaultShardKey(u,s),this.recordShardCursor(s,d.commitCursor);try{return _(d.result)}catch(p){throw C(ne(p),u.headers)}}async adminFetch(e,t,s,i){if(!this.fetchImpl)throw new v("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 v("INTERNAL",`LunoraClient: response was not JSON (status ${c.status.toString()}${h})`)}const u=x(d);if(u!==void 0)throw ce({...u,message:u.message??"admin request failed"});if(!c.ok){const h=c.statusText?` ${c.statusText}`:"";throw new v("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));k(e,{caps:Hs,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)}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 D(this.connectTimeoutMs,void 0,async()=>({session:await Ee(this.wsToken),ticket:await Ee(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(),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;Te(e,this.wsUrlFor(t,s.ticket),this.managedSocketOptions,{onClose:r=>{r?.code===4003&&e.polling.noteFailedOpen(),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.heldFrames=void 0,e.roomsRejoined=!1,clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},he),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)k(e,{id:c,type:d});this.releaseIdleShard(t)}rs(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),k(s,{id:e,type:"unsubscribe"})),this.forgetStream(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;e.wsState==="connecting"&&e.polling.noteFailedOpen(),H(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",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 v("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&&(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<nt;){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=k(s,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...i?{sinceSeq:e.serverCursor}:{},...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),$(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):$(t)},le))}sendShapeSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);t?.wsState==="open"&&k(t,{id:e.id,shape:{name:e.name,...e.wireArgs===void 0?{}:{args:e.wireArgs}},type:"shape_subscribe",...e.serverCursor===void 0?{}:{sinceCheckpoint:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,t){const s=os(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,St(()=>{for(const c of a){if(r.retired===!0||r.socket!==o)break;this.dispatchServerMessage(c,t)}},()=>!this.closed)}}else r?.heldFrames&&Us(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.handleDataMessage(e);return}case"error":{this.handleErrorMessage(e);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.handlePokeEnd(e,t);break}case"pokePart":{this.pokeAssembler.part(t,e);break}case"pokeStart":{this.pokeAssembler.start(t,e);break}case"resume":{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){const t=e.error?.code;if(t==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}if(t==="STREAM_ID_IN_USE")return;const{id:s}=e,i=s===void 0?void 0:this.streams.get(s);if(i&&s!==void 0){i.handle.fail(Ve(e)),this.forgetStream(s);return}const r=s===void 0?void 0:this.subscriptions.getById(s);if(r){$(r);const o=ue(e),c=this.identityFingerprint(),d=T.keyOf(r);this.markQueryRejected(r),R(r.errorCallbacks,o),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(d,o,c);return}const a=s===void 0?void 0:this.shapeSubscriptions.get(s);a&&(a.answered||(a.answered=!0,this.emitSyncStatus()),R(a.errorCallbacks,ue(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=gs(e,t,s);if(e.answered!==i&&this.emitSyncStatus(),Ae(e),r==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){I(e,"idle"),e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,this.emitSyncStatus(),console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}handleDataMessage(e,t){const{id:s}=e,i=s?this.subscriptions.getById(s):void 0;if(!i||e.type==="data"&&Ts(i,e))return;let r;const a=i.pendingDeltaRun;try{r=qe(e,a===void 0?i.serverBase:a.payload)}catch(c){i.pendingDeltaRun=void 0,R(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription — ${c instanceof Error?c.message:String(c)}`}),this.settleAwaitedAnswer(i,!1);return}if(r===Ke){this.resnapshotSubscription(i);return}if(ks(e)){i.pendingDeltaRun={payload:r};return}i.pendingDeltaRun=void 0,this.dropCacheSeed(T.keyOf(i));const o=t!==void 0&&!i.valueReceived;if(Ue(i,r,{cursor:e.cursor,epoch:e.epoch}),o&&(i.valueReceived=!0,this.emitSyncStatus()),e.lastMutationId!==void 0&&(se(i,e.lastMutationId),ie(i,!0)),this.persistQueryValue(i),Z(i,i.serverCursor),t!==void 0&&vt(i,t),F(i,r),this.tabCoordinator?.isLeader()){const c=T.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(c,r,i.serverCursor,i.serverEpoch,this.identityFingerprint())}this.settleAwaitedAnswer(i,!0)}handleResumeMessage(e){const t=this.subscriptions.getById(e.id);t&&(t.pendingDeltaRun=void 0,this.ackAndAdvanceCursor(t,e.cursor,e.epoch),this.tabCoordinator?.isLeader()&&t.serverBase!==void 0&&this.tabCoordinator.broadcastSubscriptionData(T.keyOf(t),t.serverBase,t.serverCursor,t.serverEpoch,this.identityFingerprint()),this.settleAwaitedAnswer(t,!0))}handleSettledMessage(e){const t=this.subscriptions.getById(e.id);if(t&&(this.ackAndAdvanceCursor(t,e.cursor,e.epoch),e.lastMutationId!==void 0&&se(t,e.lastMutationId),ie(t),this.tabCoordinator?.isLeader())){const s=T.keyOf(t);this.tabCoordinator.broadcastSubscriptionSettled(s,t.serverCursor,t.serverEpoch,t.lastMutationId,this.clientId,this.identityFingerprint())}}ackAndAdvanceCursor(e,t,s){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),Z(e,e.serverCursor)&&F(e,e.serverBase))}adoptSocketConnectionId(e,t){const s=this.getConnection(t);if(!(s===void 0||typeof e.connectionId!="string")){s.connectionId=e.connectionId,s.whisperAck=e.whisperAck===!0;for(const i of this.liveSocketGrants.get(f(t))?.keys()??[])this.grantWhenJoined(t,i,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},u=>{this.refuseLiveGrant(e,t,u,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,k(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()},Ne),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(()=>_e(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(),R(s.errorCallbacks,{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()?!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&&W(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&&k(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.queryCache?.clear().catch(()=>{})}evictPreviousIdentitySession(){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.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,I(e,"idle"),e.valueReceived=!1,F(e,void 0);for(const e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,e.answered=!1,Ae(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?_e(s,w(this.url,i.shardKey===void 0?we:`${we}?shard=${encodeURIComponent(i.shardKey)}`),JSON.stringify({connectionId:r}),{authorization:`Bearer ${t}`,"content-type":"application/json"}).then(({text:a})=>JSON.parse(a)?.ok===!0).catch(()=>!1).then(a=>{!a&&!this.closed&&this.authToken===t&&i.connectionId===r&&this.bounceShardSocket(i)}).catch(()=>{}):this.bounceShardSocket(i)}for(const i of this.supplementaryBounces)i()}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&&W(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=ve(e),s=t&&this.subscriptions.get(T.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=ve(e);if(e===void 0||t===void 0)return e;const s=()=>this.snapshotAnswer(e)!==void 0||e();return Ct(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*le))}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 u of s){this.unpersist(u.id),this.queuedIdentities.delete(u.id??"");const h=new Error("offline mutation skipped: precondition failed before replay");h.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(u,"rejected",h)}const i=f(e),r=this.holdUndecidedWrites(i,this.offlineQueue.drain(u=>f(u.shardKey)===i));if(r.length===0)return;const a=[],o=[];for(const u of r){const h=this.replayGateVerdict(u);h==="send"?a.push(u):h==="hold"&&o.push(u)}if(this.offlineQueue.requeue(o),o.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),a.length===0){this.scheduleRateLimitedRetry(e);return}const c=this.encodableOrSettleTerminal(a);if(c.length===0){this.scheduleRateLimitedRetry(e);return}if(c.length===1){await this.replaySequential(c,e,t),this.scheduleRateLimitedRetry(e);return}const d=[];for(let u=0;u<c.length;u+=J){const h=c.slice(u,u+J),l=await this.replayBatched(h,e,t);if(d.push(...l.requeue),l.stop||l.requeue.length>0){d.push(...c.slice(u+J));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,te(i))})}noteReplayRetryDelay(e,t,s){const i=f(e),r=this.replayRetryState.get(i),a=(r?.attempts??0)+1,o=fs(t,a)??(s===null&&K(t)?te(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{E(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)||Ce(e)}noteReplayAuthRefusal(e,t){if(!K(e))return!1;const s=this.hashToken(t??"");return t===this.authToken&&this.authRefusalNotifiedFor!==s&&(this.authRefusalNotifiedFor=s,this.notifyTokenExpired()),!0}noteCredentialAccepted(e){this.authRefusalNotifiedFor!==void 0&&this.authRefusalNotifiedFor===this.hashToken(e??"")&&(this.authRefusalNotifiedFor=void 0)}takeReplayCredential(e){if(e===void 0)return;const t=this.replayCredentials.get(e);if(t===void 0)throw new TypeError("LunoraClient: `replayCredential` must come from this client's `replayIdentityVerdict`, and is single use");return this.replayCredentials.delete(e),{flags:{authToken:t.authToken,...Y(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||K(t)||s==="RATE_LIMITED"||s==="TOO_MANY_REQUESTS"||!Ce(t))return!1;const i=(this.replayAttempts.get(e.id)??0)+1;return this.replayAttempts.set(e.id,i),i>=ot}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,...Y(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,u)=>({args:E(d.args,`args for '${d.functionPath}'`),baselineSeq:d.baselineSeq,functionPath:d.functionPath,id:u,clientId:d.clientId??this.clientId,mutationId:d.id,shardKey:d.shardKey}))});if(e.length>1&&ms(i)>ps)return await this.replayBatchedHalves(e,t,s);const{fetchImpl:r}=this;let a,o;try{({payload:o,response:a}=await D(this.rpcTimeoutMs,void 0,async d=>{const u=await r(w(this.url,V),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:s,...Y(e.find(h=>h.identity!==void 0)?.identity,s)}),method:"POST",signal:d});if(u.status===413&&e.length>1)return{payload:void 0,response:u};try{return{payload:await u.json(),response:u}}catch{return{payload:void 0,response:u}}}))}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=x(o),u=d===void 0?B(a.status,a.statusText,a.headers):de(d,a.headers);return this.settleWholeBatchError(e,u,t,s)}return{requeue:this.settleReplayBatchSlots(e,o.results,t,s,a.headers),stop:!1}}settleWholeBatchError(e,t,s,i){if(t instanceof U||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=ys(t),o=[];let c=!1,d=!1;for(const[u,h]of e.entries()){const l=Ss(a.get(u),r);switch(l.kind){case"committed":{c=!0,this.settleReplaySuccess(h,l.value,l.commitCursor);break}case"errored":{d||=K(l.error),this.shouldRequeueReplayFailure(l.error,i)&&!this.spendsLastReplayAttempt(h,l.error)?(this.noteReplayRetryDelay(s,l.error,i),o.push(h)):this.settleReplayTerminal(h,l.error);break}case"unanswered":{const p=C(ze(),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,l.error,l.commitCursor)}}return c&&!d&&this.noteCredentialAccepted(i),o}}export{Xi as $,vi as A,Ni as B,yi as C,Wi as D,Bi as E,mi as F,wi as G,Di as H,Qi as I,xi as J,_i as K,We as L,qi as M,Ki as N,bi as O,ji as P,Gi as Q,$i as R,hi as S,Vi as T,zi as U,Ci as V,Ji as W,er as X,tr as Y,sr as Z,Yi as _,Si as a,Zi as a0,ir as a1,rr as a2,nr as a3,or as a4,ar as a5,cr as a6,dr as a7,ur as a8,hr as a9,lr as aa,fr as ab,pr as ac,mr as ad,yr as ae,Sr as af,vr as ag,br as ah,Li as ai,gi as b,Ti as c,ki as d,Ii as e,Ri as f,Ei as g,li as h,pi as i,fi as j,Ai as k,gr as l,Tr as m,kr as n,Ar as o,Er as p,_r as q,Cr as r,wr as s,Ir as t,Oi as u,Pi as v,Mi as w,Fi as x,Hi as y,Ui as z};
|
package/dist/packem_shared/{lunora-client.d-D3G_fsa6.d.mts → lunora-client.d-B03X64bx.d.mts}
RENAMED
|
@@ -403,8 +403,10 @@ interface LunoraClientOptions {
|
|
|
403
403
|
* `@lunora/react-native` turns this on by default on native, where the bearer
|
|
404
404
|
* also rides an `Authorization` header (the header wins).
|
|
405
405
|
*
|
|
406
|
-
* A sign-in from signed-out then reconnects the shard sockets cold
|
|
407
|
-
* refreshed bearer
|
|
406
|
+
* A sign-in from signed-out then reconnects the shard sockets cold. A
|
|
407
|
+
* refreshed bearer for the same user is handed to the open shard sockets in
|
|
408
|
+
* place (`POST /_lunora/ws/reauth`); one the server will not take bounces them
|
|
409
|
+
* warm, so the server sees the current token either way.
|
|
408
410
|
* The default `false` keeps cookie-session sockets (and their live values)
|
|
409
411
|
* alone.
|
|
410
412
|
*/
|
|
@@ -1021,7 +1023,15 @@ interface ServerPokeEndMessage {
|
|
|
1021
1023
|
pokeId: string;
|
|
1022
1024
|
type: "pokeEnd";
|
|
1023
1025
|
}
|
|
1024
|
-
|
|
1026
|
+
/**
|
|
1027
|
+
* Brackets the frames one write sends to this socket (`batchStart` … `batchEnd`).
|
|
1028
|
+
* Sent only to a client that announced `refreshBatch` on `connect`; the frames
|
|
1029
|
+
* between the two are applied together and their listeners notified once.
|
|
1030
|
+
*/
|
|
1031
|
+
interface ServerBatchMessage {
|
|
1032
|
+
type: "batchEnd" | "batchStart";
|
|
1033
|
+
}
|
|
1034
|
+
type ServerMessage = ServerAckMessage | ServerBatchMessage | ServerChunkMessage | ServerCompleteMessage | ServerDataMessage | ServerErrorMessage | ServerIdentityMessage | ServerLiveMessage | ServerPokeEndMessage | ServerPokePartMessage | ServerPokeStartMessage | ServerResumeMessage | ServerSettledMessage | ServerWhisperMessage | ServerWhisperSubscribedMessage;
|
|
1025
1035
|
/**
|
|
1026
1036
|
* The authenticated user as exposed client-side, mirroring better-auth's
|
|
1027
1037
|
* `user` row (the `user` field of the `get-session` response). Kept minimal
|
|
@@ -3308,8 +3318,8 @@ declare class LunoraClient {
|
|
|
3308
3318
|
*
|
|
3309
3319
|
* A sign-in from signed-out is `"cold"`: the sockets upgraded anonymously,
|
|
3310
3320
|
* and no view may resume from an anonymous cursor. A refreshed bearer under
|
|
3311
|
-
* an unchanged identity is `"warm"`: the
|
|
3312
|
-
* cursors.
|
|
3321
|
+
* an unchanged identity is `"warm"`: it is handed to the open sockets in
|
|
3322
|
+
* place, and a socket that refuses it reconnects and resumes from its cursors.
|
|
3313
3323
|
*
|
|
3314
3324
|
* A sign-out or an account switch leaves a previous identity behind and is
|
|
3315
3325
|
* evicted by `setAuthToken` before this is asked.
|
|
@@ -3921,6 +3931,7 @@ declare class LunoraClient {
|
|
|
3921
3931
|
private armUnackedWatchdog;
|
|
3922
3932
|
private sendShapeSubscribeIfOpen;
|
|
3923
3933
|
private handleServerMessage;
|
|
3934
|
+
private dispatchServerMessage;
|
|
3924
3935
|
private handleErrorMessage;
|
|
3925
3936
|
/** Count a query the server refused as answered, by the evidence {@link syncStatus} asks of it, emitting only on a change. */
|
|
3926
3937
|
private markQueryRejected;
|
|
@@ -4416,10 +4427,19 @@ declare class LunoraClient {
|
|
|
4416
4427
|
*
|
|
4417
4428
|
* Non-terminal, unlike {@link close}: the `ShardConnection` records and the
|
|
4418
4429
|
* subscriptions riding them survive, and the registered `close` handler
|
|
4419
|
-
* (`handleDisconnect`) schedules the retry and replays the subscribes.
|
|
4420
|
-
*
|
|
4430
|
+
* (`handleDisconnect`) schedules the retry and replays the subscribes. A
|
|
4431
|
+
* credential rides the upgrade, so this is how a socket moves to a new
|
|
4432
|
+
* identity.
|
|
4433
|
+
*
|
|
4434
|
+
* `inPlace` is a refreshed bearer for the same user: it is handed to each open
|
|
4435
|
+
* shard socket (`SOCKET_REAUTH_PATH`), so a token lifetime no longer costs a
|
|
4436
|
+
* reconnect and a full re-seed. A socket the server will not re-authenticate —
|
|
4437
|
+
* not yet named by its `identity` frame, held under different claims, or behind a
|
|
4438
|
+
* server without the route — is bounced. Route and scheduled sockets carry their
|
|
4439
|
+
* bearer on the upgrade, so they are always bounced.
|
|
4421
4440
|
*/
|
|
4422
4441
|
private bounceShardSockets;
|
|
4442
|
+
private bounceShardSocket;
|
|
4423
4443
|
/**
|
|
4424
4444
|
* Flush every shard with a mutation currently queued in `offlineQueue`
|
|
4425
4445
|
* (see `queuedOfflineShardKeys`). Used on a FOLLOWER tab when the
|
|
@@ -403,8 +403,10 @@ interface LunoraClientOptions {
|
|
|
403
403
|
* `@lunora/react-native` turns this on by default on native, where the bearer
|
|
404
404
|
* also rides an `Authorization` header (the header wins).
|
|
405
405
|
*
|
|
406
|
-
* A sign-in from signed-out then reconnects the shard sockets cold
|
|
407
|
-
* refreshed bearer
|
|
406
|
+
* A sign-in from signed-out then reconnects the shard sockets cold. A
|
|
407
|
+
* refreshed bearer for the same user is handed to the open shard sockets in
|
|
408
|
+
* place (`POST /_lunora/ws/reauth`); one the server will not take bounces them
|
|
409
|
+
* warm, so the server sees the current token either way.
|
|
408
410
|
* The default `false` keeps cookie-session sockets (and their live values)
|
|
409
411
|
* alone.
|
|
410
412
|
*/
|
|
@@ -1021,7 +1023,15 @@ interface ServerPokeEndMessage {
|
|
|
1021
1023
|
pokeId: string;
|
|
1022
1024
|
type: "pokeEnd";
|
|
1023
1025
|
}
|
|
1024
|
-
|
|
1026
|
+
/**
|
|
1027
|
+
* Brackets the frames one write sends to this socket (`batchStart` … `batchEnd`).
|
|
1028
|
+
* Sent only to a client that announced `refreshBatch` on `connect`; the frames
|
|
1029
|
+
* between the two are applied together and their listeners notified once.
|
|
1030
|
+
*/
|
|
1031
|
+
interface ServerBatchMessage {
|
|
1032
|
+
type: "batchEnd" | "batchStart";
|
|
1033
|
+
}
|
|
1034
|
+
type ServerMessage = ServerAckMessage | ServerBatchMessage | ServerChunkMessage | ServerCompleteMessage | ServerDataMessage | ServerErrorMessage | ServerIdentityMessage | ServerLiveMessage | ServerPokeEndMessage | ServerPokePartMessage | ServerPokeStartMessage | ServerResumeMessage | ServerSettledMessage | ServerWhisperMessage | ServerWhisperSubscribedMessage;
|
|
1025
1035
|
/**
|
|
1026
1036
|
* The authenticated user as exposed client-side, mirroring better-auth's
|
|
1027
1037
|
* `user` row (the `user` field of the `get-session` response). Kept minimal
|
|
@@ -3308,8 +3318,8 @@ declare class LunoraClient {
|
|
|
3308
3318
|
*
|
|
3309
3319
|
* A sign-in from signed-out is `"cold"`: the sockets upgraded anonymously,
|
|
3310
3320
|
* and no view may resume from an anonymous cursor. A refreshed bearer under
|
|
3311
|
-
* an unchanged identity is `"warm"`: the
|
|
3312
|
-
* cursors.
|
|
3321
|
+
* an unchanged identity is `"warm"`: it is handed to the open sockets in
|
|
3322
|
+
* place, and a socket that refuses it reconnects and resumes from its cursors.
|
|
3313
3323
|
*
|
|
3314
3324
|
* A sign-out or an account switch leaves a previous identity behind and is
|
|
3315
3325
|
* evicted by `setAuthToken` before this is asked.
|
|
@@ -3921,6 +3931,7 @@ declare class LunoraClient {
|
|
|
3921
3931
|
private armUnackedWatchdog;
|
|
3922
3932
|
private sendShapeSubscribeIfOpen;
|
|
3923
3933
|
private handleServerMessage;
|
|
3934
|
+
private dispatchServerMessage;
|
|
3924
3935
|
private handleErrorMessage;
|
|
3925
3936
|
/** Count a query the server refused as answered, by the evidence {@link syncStatus} asks of it, emitting only on a change. */
|
|
3926
3937
|
private markQueryRejected;
|
|
@@ -4416,10 +4427,19 @@ declare class LunoraClient {
|
|
|
4416
4427
|
*
|
|
4417
4428
|
* Non-terminal, unlike {@link close}: the `ShardConnection` records and the
|
|
4418
4429
|
* subscriptions riding them survive, and the registered `close` handler
|
|
4419
|
-
* (`handleDisconnect`) schedules the retry and replays the subscribes.
|
|
4420
|
-
*
|
|
4430
|
+
* (`handleDisconnect`) schedules the retry and replays the subscribes. A
|
|
4431
|
+
* credential rides the upgrade, so this is how a socket moves to a new
|
|
4432
|
+
* identity.
|
|
4433
|
+
*
|
|
4434
|
+
* `inPlace` is a refreshed bearer for the same user: it is handed to each open
|
|
4435
|
+
* shard socket (`SOCKET_REAUTH_PATH`), so a token lifetime no longer costs a
|
|
4436
|
+
* reconnect and a full re-seed. A socket the server will not re-authenticate —
|
|
4437
|
+
* not yet named by its `identity` frame, held under different claims, or behind a
|
|
4438
|
+
* server without the route — is bounced. Route and scheduled sockets carry their
|
|
4439
|
+
* bearer on the upgrade, so they are always bounced.
|
|
4421
4440
|
*/
|
|
4422
4441
|
private bounceShardSockets;
|
|
4442
|
+
private bounceShardSocket;
|
|
4423
4443
|
/**
|
|
4424
4444
|
* Flush every shard with a mutation currently queued in `offlineQueue`
|
|
4425
4445
|
* (see `queuedOfflineShardKeys`). Used on a FOLLOWER tab when the
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
let l=0,n;const f=(i,o)=>{for(const r of i)try{r(o)}catch{}},p=i=>{const o=[...i.callbacks],r=i.lastValue;return()=>{for(const e of o){if(i.lastValue!==r)return;i.callbacks.has(e)&&f([e],r)}}},k=i=>{n===void 0?i():n.add(i)},L=()=>l,y=(i,o)=>{let r=i;for(const e of o)try{r=e.transform(r)}catch{}return r},d=(i,o)=>{o!==i.lastValue&&(i.lastValue=o,n===void 0?f(i.callbacks,o):n.add(i))},v=(i,o=()=>!0)=>{const r=new Set;n=r;try{i()}finally{n=void 0;const e=[...r].map(c=>typeof c=="function"?c:p(c));for(const c of e){if(!o())break;try{c()}catch{}}}},m=(i,o)=>{d(i,y(o,i.optimisticLayers))},b=(i,o)=>{let r;try{r=o(i.lastValue)}catch{return}const e={id:Symbol("optimistic"),transform:o};let c=!1;i.optimisticLayers.push(e),d(i,r);const s=()=>{const t=i.optimisticLayers.findIndex(u=>u.id===e.id);return t===-1?!1:(i.optimisticLayers.splice(t,1),!0)},a=()=>{m(i,i.serverBase)};return{confirm:t=>{if(t===void 0){s();return}e.commitCursor=t,l+=1,e.acknowledgedAt=l,i.serverCursor!==void 0&&i.serverCursor>=t&&s()&&a()},rollback:()=>{c||(c=!0,s(),a())}}},h=(i,o)=>{if(o===void 0||i.optimisticLayers.length===0)return!1;const r=i.optimisticLayers.length;return i.optimisticLayers=i.optimisticLayers.filter(e=>e.commitCursor===void 0||e.commitCursor>o),i.optimisticLayers.length!==r},g=(i,o)=>{i.optimisticLayers.length!==0&&(i.optimisticLayers=i.optimisticLayers.filter(r=>r.acknowledgedAt===void 0||r.acknowledgedAt>o))},w=i=>{for(let o=i.length-1;o>=0;o-=1)i[o]?.()};export{b as a,h as b,w as c,k as d,g as e,L as f,m as r,v as w};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { L as LunoraClient, P as Preloaded } from "./lunora-client.d-
|
|
1
|
+
import { L as LunoraClient, P as Preloaded } from "./lunora-client.d-B03X64bx.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-
|
|
1
|
+
import { L as LunoraClient, P as Preloaded } from "./lunora-client.d-DD4bVp9S.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
|
package/dist/query/index.d.mts
CHANGED
|
@@ -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-
|
|
2
|
+
import { L as LunoraClient, S as SubscriptionError, a as Unsubscribe } from "../packem_shared/lunora-client.d-B03X64bx.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-
|
|
18
|
+
b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-B03X64bx.mjs";
|
|
19
19
|
import '@lunora/errors';
|
|
20
20
|
/**
|
|
21
21
|
* The TanStack Query cache-key contract for Lunora queries. It lives here, not
|
package/dist/query/index.d.ts
CHANGED
|
@@ -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-
|
|
2
|
+
import { L as LunoraClient, S as SubscriptionError, a as Unsubscribe } from "../packem_shared/lunora-client.d-DD4bVp9S.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-
|
|
18
|
+
b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-DD4bVp9S.js";
|
|
19
19
|
import '@lunora/errors';
|
|
20
20
|
/**
|
|
21
21
|
* The TanStack Query cache-key contract for Lunora queries. It lives here, not
|
package/dist/ssr/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
1
|
+
import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-B03X64bx.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-
|
|
23
|
+
a as preloadedQueryResult } from "../packem_shared/preload.d-BuQpOeP-.mjs";
|
|
24
24
|
import '@lunora/errors';
|
|
25
25
|
/**
|
|
26
26
|
* Structural shape of a better-auth `getSession` call's resolved value.
|
package/dist/ssr/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
1
|
+
import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-DD4bVp9S.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-
|
|
23
|
+
a as preloadedQueryResult } from "../packem_shared/preload.d-tOPIEVGY.js";
|
|
24
24
|
import '@lunora/errors';
|
|
25
25
|
/**
|
|
26
26
|
* Structural shape of a better-auth `getSession` call's resolved value.
|
package/dist/ssr/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getServerSession as o}from"../packem_shared/getServerSession-BaOoo1p6.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-CyFK_cv6.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-
|
|
1
|
+
import{getServerSession as o}from"../packem_shared/getServerSession-BaOoo1p6.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-CyFK_cv6.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-BqlNr7xM.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 +0,0 @@
|
|
|
1
|
-
import{L as h}from"./lunora-client-Csrg4U0l.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-DBuR7Dwv.mjs";import"./CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import"./httpStream-ChJxN9M1.mjs";import"./local-store-C3bw2MPY.mjs";import"./offline-queue-BEqCPDmw.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-BKgQtuh9.mjs";import"./wire-errors-BDckSTKZ.mjs";export{h as LunoraClient};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
let d=0;const s="lunora-bridge",o=1e3,h=3e3;class l{bc;tabId;heartbeatInterval;leaderTimeout;knownLeader=void 0;leader=!1;running=!1;promotionPending=!1;lastHeartbeat=0;pendingData=new Map;heartbeatTimer=void 0;leaderCheckTimer=void 0;onBecomeLeader;onStopBeingLeader;onConnectionStatus;onSubscriptionData;onLeaderClaimAnswered;onSubscriptionError;onSubscriptionSettled;constructor(t={}){if(d+=1,this.tabId=`tab_${String(d)}_${crypto.randomUUID()}`,this.heartbeatInterval=t.heartbeatInterval??o,this.leaderTimeout=t.leaderTimeout??h,this.onBecomeLeader=t.onBecomeLeader,this.onStopBeingLeader=t.onStopBeingLeader,this.onConnectionStatus=t.onConnectionStatus,this.onSubscriptionData=t.onSubscriptionData,this.onLeaderClaimAnswered=t.onLeaderClaimAnswered,this.onSubscriptionError=t.onSubscriptionError,this.onSubscriptionSettled=t.onSubscriptionSettled,typeof BroadcastChannel>"u"){this.bc=void 0;return}this.bc=new BroadcastChannel(t.channelName??s),this.bc.addEventListener("message",e=>{this.handleMessage(e.data)})}start(){if(!this.running){if(this.running=!0,this.bc===void 0){this.becomeLeader();return}this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout),this.leaderCheckTimer=setInterval(()=>{this.checkLeaderHealth()},this.leaderTimeout),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeat()},this.heartbeatInterval)}}stop(){this.running=!1,this.leader&&(this.broadcast({type:"yield-leadership",tabId:this.tabId}),this.leader=!1,this.knownLeader=void 0,this.onStopBeingLeader?.()),this.heartbeatTimer!==void 0&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0),this.leaderCheckTimer!==void 0&&(clearInterval(this.leaderCheckTimer),this.leaderCheckTimer=void 0),this.bc?.close()}isLeader(){return this.leader}promoteImmediately(){this.running&&this.becomeLeader()}get leaderTabId(){return this.knownLeader}get id(){return this.tabId}get isRunning(){return this.running}broadcastSubscriptionData(t,e,i,a,r){this.leader&&(this.pendingData.size===0&&queueMicrotask(()=>{this.flushPendingData()}),this.pendingData.set(t,{type:"subscription-data",tabId:this.tabId,key:t,data:e,...i===void 0?{}:{cursor:i},...a===void 0?{}:{epoch:a},...r===void 0?{}:{identity:r}}))}broadcastSubscriptionError(t,e,i){this.leader&&this.broadcast({type:"subscription-error",tabId:this.tabId,key:t,error:e,...i===void 0?{}:{identity:i}})}broadcastSubscriptionSettled(t,e,i,a,r,n){this.leader&&this.broadcast({type:"subscription-settled",tabId:this.tabId,key:t,...e===void 0?{}:{cursor:e},...i===void 0?{}:{epoch:i},...a===void 0?{}:{lastMutationId:a},...r===void 0?{}:{clientId:r},...n===void 0?{}:{identity:n}})}broadcastConnectionStatus(t,e){this.leader&&this.broadcast({type:"connection-status",tabId:this.tabId,status:t,...e===void 0?{}:{identity:e}})}broadcast(t){this.flushPendingData(),this.bc?.postMessage(t)}flushPendingData(){if(this.pendingData.size===0)return;const t=[...this.pendingData.values()];if(this.pendingData.clear(),!!this.leader)for(const e of t)this.bc?.postMessage(e)}handleMessage(t){switch(t.type){case"claim-leadership":{this.handleClaimLeadership(t);break}case"connection-status":{if(this.leader||t.tabId===this.tabId)break;this.onConnectionStatus?.(t.status,t.identity);break}case"heartbeat":{this.handleHeartbeat(t);break}case"subscription-data":{if(this.leader||t.tabId===this.tabId)break;this.onSubscriptionData?.(t.key,t.data,t.cursor,t.epoch,t.identity);break}case"subscription-error":{if(this.leader||t.tabId===this.tabId)break;this.onSubscriptionError?.(t.key,t.error,t.identity);break}case"subscription-settled":{if(this.leader||t.tabId===this.tabId)break;this.onSubscriptionSettled?.(t.key,t.cursor,t.epoch,t.lastMutationId,t.clientId,t.identity);break}case"yield-leadership":{this.knownLeader===t.tabId&&(this.knownLeader=void 0,this.running&&!this.leader&&this.claimAndPromote());break}}}handleClaimLeadership(t){if(t.tabId!==this.tabId){if(this.leader){this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}),this.onLeaderClaimAnswered?.();return}this.knownLeader===void 0&&t.tabId<this.tabId&&(this.knownLeader=t.tabId,this.lastHeartbeat=t.ts)}}handleHeartbeat(t){if(t.tabId!==this.tabId){if(this.leader){this.resolveLeaderVsLeaderTieBreak(t);return}this.lastHeartbeat=t.ts,this.knownLeader=t.tabId}}resolveLeaderVsLeaderTieBreak(t){t.tabId<this.tabId?(this.leader=!1,this.knownLeader=t.tabId,this.lastHeartbeat=t.ts,this.onStopBeingLeader?.()):this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}becomeLeader(){this.leader||(this.leader=!0,this.knownLeader=this.tabId,this.lastHeartbeat=Date.now(),this.onBecomeLeader?.(),this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}))}sendHeartbeat(){this.leader&&this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}checkLeaderHealth(){if(!this.running||this.leader)return;if(this.knownLeader===void 0){this.claimAndPromote();return}Date.now()-this.lastHeartbeat>this.leaderTimeout&&(this.knownLeader=void 0,this.claimAndPromote())}claimAndPromote(){this.promotionPending||(this.promotionPending=!0,this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.promotionPending=!1,this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout))}}export{l as TabCoordinator};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as t}from"./local-store-C3bw2MPY.mjs";import"./SubscriptionRegistry-BKgQtuh9.mjs";export{t as createLocalStore};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{SubscriptionRegistry as m}from"./SubscriptionRegistry-BKgQtuh9.mjs";let f=0;const h=()=>f,p=(r,e)=>{let t=r;for(const i of e)try{t=i.transform(t)}catch{}return t},d=(r,e)=>{if(e!==r.lastValue){r.lastValue=e;for(const t of r.callbacks)try{t(e)}catch{}}},y=(r,e)=>{d(r,p(e,r.optimisticLayers))},g=(r,e)=>{let t;try{t=e(r.lastValue)}catch{return}const i={id:Symbol("optimistic"),transform:e};let c=!1;r.optimisticLayers.push(i),d(r,t);const l=()=>{const o=r.optimisticLayers.findIndex(n=>n.id===i.id);return o===-1?!1:(r.optimisticLayers.splice(o,1),!0)},s=()=>{y(r,r.serverBase)};return{confirm:o=>{if(o===void 0){l();return}i.commitCursor=o,f+=1,i.acknowledgedAt=f,r.serverCursor!==void 0&&r.serverCursor>=o&&l()&&s()},rollback:()=>{c||(c=!0,l(),s())}}},k=(r,e)=>{if(e===void 0||r.optimisticLayers.length===0)return!1;const t=r.optimisticLayers.length;return r.optimisticLayers=r.optimisticLayers.filter(i=>i.commitCursor===void 0||i.commitCursor>e),r.optimisticLayers.length!==t},b=(r,e)=>{r.optimisticLayers.length!==0&&(r.optimisticLayers=r.optimisticLayers.filter(t=>t.acknowledgedAt===void 0||t.acknowledgedAt>e))},v=r=>{for(let e=r.length-1;e>=0;e-=1)r[e]?.()},_=(r,e)=>{const t=[],i=[],c=(s,o)=>r.get(m.key(s,o,e));return{confirms:t,rollbacks:i,store:{getAllQueries:s=>{const o=[];for(const n of r.all())n.fn.__lunoraRef===s.__lunoraRef&&(n.shardKey??"")===(e??"")&&o.push({args:n.args,value:n.lastValue});return o},getQuery:(s,o)=>c(s.__lunoraRef,o??{})?.lastValue,setQuery:(s,o,n)=>{const u=c(s.__lunoraRef,o??{});if(!u)return;const a=g(u,()=>n);a&&(t.push(a.confirm),i.push(a.rollback))}}}};export{v as a,g as b,_ as c,k as d,b as e,h as f,y as r};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as v,OFFLINE_NOT_QUEUED_HINT as Be}from"@lunora/errors";import{decodeWire as _,encodeWire as re,stableWireKey as ae}from"@lunora/wire";import{t as _e}from"./base64-849R7V-V.mjs";import{r as Qe,U as xe,P as qe}from"./delta-merge-C6OqMEPH.mjs";import Ke from"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import{w as C,u as ne,s as Ie,a as je,i as Q,e as x,r as ce,b as de,c as Ge,d as ue,f as $e}from"./wire-errors-BDckSTKZ.mjs";import{ClientQueryStore as Ve}from"./createClientQuery-B8Nfj-7o.mjs";import{D as ze,a as Je,b as Ye,c as Xe,d as Ze,S as he,M as et,I as tt,Q as st,R as it,e as le,f as rt,g as nt}from"./client-tuning-C10B2KCO.mjs";import{j as A,d as fe,p as q,s as pe}from"./client-urls-BHLUjjcG.mjs";import{TabCoordinator as ot}from"./TabCoordinator-DBuR7Dwv.mjs";import{TransportError as H,getRetryAfterMs as at,AUTH_REPLAY_ERROR_CODES as ct,isAuthReplayFailure as K}from"./CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as dt}from"./httpStream-ChJxN9M1.mjs";import{d as Z,r as F,a as P,b as ut,c as ht,e as lt,f as ft}from"./local-store-C3bw2MPY.mjs";import{O as pt,n as me,i as mt}from"./offline-queue-BEqCPDmw.mjs";import{resolvePersistenceAdapter as yt}from"./createInMemoryPersistence-C-IzNVbg.mjs";import{w as B,a as ye,b as St}from"./stream-idle-C7CsIT_m.mjs";import{resolveQueryCacheAdapter as vt,queryCacheKey as M}from"./createInMemoryQueryCache-DR6AorA2.mjs";import{createReconnect as Se}from"./createReconnect-CjTmjJDH.mjs";import{fanSubscriptionError as R,setSubscriptionAck as I,SubscriptionRegistry as w,wrapSubscriber as G,releaseSubscribeFrame as $}from"./SubscriptionRegistry-BKgQtuh9.mjs";import{c as bt,s as ve,r as gt}from"./snapshot-precondition-BEtcSbWr.mjs";import{createStream as wt}from"./DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs";const Tt="/_lunora/rpc",V="/_lunora/rpc-batch",z="/_lunora/ws",ni="/_lunora/admin/shard-traffic",Ct="/_lunora/admin/scheduled",kt="/_lunora/admin/scheduled/status",At="/_lunora/admin/scheduled/ws",Et="/_lunora/admin/scheduled/cancel",be="/_lunora/admin/scheduled/dead",_t="/_lunora/admin/scheduled/dead/retry",It="/_lunora/admin/scheduled/dead/cancel",Rt="/_lunora/admin/workflows/instances",Ot="/_lunora/admin/workflows/instance",Lt="/_lunora/admin/workflows/status",oi="/_lunora/admin/storage",ai="/_lunora/admin/storage/url",ci="/_lunora/admin/storage/buckets",di="/_lunora/admin/functions",ui="/_lunora/admin/cron-jobs",hi="/_lunora/admin/cron-jobs/run",li="/_lunora/admin/architecture",fi="/_lunora/admin/openapi",pi="/_lunora/admin/openrpc",mi="/_lunora/admin/global/tables",yi="/_lunora/admin/global/table",Si="/_lunora/admin/global/facet",vi="/_lunora/admin/vector/indexes",bi="/_lunora/admin/vector/query",gi="/_lunora/admin/logs/archive",wi="/_lunora/admin/kv/namespaces",Ti="/_lunora/admin/kv/keys",Ci="/_lunora/admin/kv/value",ki="/_lunora/admin/auth/users",Ai="/_lunora/admin/auth/sessions",Ei="/_lunora/admin/auth/users/create",_i="/_lunora/admin/auth/users/role",Ii="/_lunora/admin/auth/users/ban",Ri="/_lunora/admin/auth/users/unban",Oi="/_lunora/admin/auth/users/password",Li="/_lunora/admin/auth/users/remove",Pi="/_lunora/admin/auth/users/impersonate",Mi="/_lunora/admin/auth/sessions/revoke",Fi="/_lunora/admin/auth/sessions/revoke-all",Ui="/_lunora/admin/auth/capabilities",Hi="/_lunora/admin/auth/users/update",Ni="/_lunora/admin/auth/accounts",Wi="/_lunora/admin/auth/accounts/unlink",Di="/_lunora/admin/auth/passkeys",Bi="/_lunora/admin/auth/passkeys/delete",Qi="/_lunora/admin/auth/two-factor/disable",xi="/_lunora/admin/auth/organizations",qi="/_lunora/admin/auth/organizations/members",Ki="/_lunora/admin/auth/organizations/invitations",ji="/_lunora/admin/auth/organizations/members/remove",Gi="/_lunora/admin/auth/organizations/invitations/cancel",$i="/_lunora/admin/auth/config",Vi="/_lunora/admin/auth/sign-up-invitations",zi="/_lunora/admin/auth/sign-up-invitations/create",Ji="/_lunora/admin/auth/sign-up-invitations/revoke",Yi="/_lunora/admin/auth/organizations/create",Xi="/_lunora/admin/auth/organizations/update",Zi="/_lunora/admin/auth/organizations/remove",er="/_lunora/admin/auth/organizations/members/add",tr="/_lunora/admin/auth/organizations/members/invite",sr="/_lunora/admin/auth/organizations/members/role",ir="/_lunora/admin/auth/organizations/teams",rr="/_lunora/admin/auth/organizations/teams/create",nr="/_lunora/admin/auth/organizations/teams/update",or="/_lunora/admin/auth/organizations/teams/remove",ar="/_lunora/admin/auth/organizations/teams/members",cr="/_lunora/admin/auth/organizations/teams/members/add",dr="/_lunora/admin/auth/organizations/teams/members/remove",ur="/_lunora/admin/auth/organizations/roles",hr="/_lunora/admin/auth/organizations/roles/create",lr="/_lunora/admin/auth/organizations/roles/update",fr="/_lunora/admin/auth/organizations/roles/remove",Pt="/api/auth",Mt="/get-session",Ft="lunora-ping",J=500,Re=(n,e)=>{if(n.size<e)return;const t=n.keys().next().value;t!==void 0&&n.delete(t)};new TextDecoder;const Ut=new TextEncoder,Ht=n=>_e(Ut.encode(n)),Nt=n=>Ht(JSON.stringify(n)),Wt="x-lunora-expect-subject",Dt=n=>Nt({subject:n}),ge=Symbol.for("lunora:session-change"),Bt="lunora:session-change",Qt="better-auth.message",xt="signout",Oe=()=>{const n=globalThis;let e=n[ge];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},n[ge]=e),e},qt=()=>"document"in globalThis,Kt=async()=>{const n=[];for(const e of Oe().listeners)try{n.push(e())}catch{}await Promise.allSettled(n)},jt=(n,e)=>{if(n!==Qt||e===null)return!1;try{const t=JSON.parse(e);return t?.event==="session"&&t.data?.trigger===xt}catch{return!1}},Gt=n=>{const e=[],t=()=>{Kt().catch(()=>{})};let s;try{s=typeof BroadcastChannel=="function"?new BroadcastChannel(Bt):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=>{jt(a.key,a.newValue)&&t()};i.addEventListener("storage",r),e.push(()=>{i.removeEventListener?.("storage",r)})}return()=>{for(const r of e)r()}},$t=n=>{const e=Oe();return e.listeners.add(n),e.detach===void 0&&qt()&&(e.detach=Gt(e.tab)),()=>{e.listeners.delete(n),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},Vt="lunora",zt="lunora.bearer.",Jt=n=>`${zt}${_e(new TextEncoder().encode(n))}`,Yt=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}},oe=n=>"args"in n?{...n,args:_(n.args)}:n,pr=async n=>(n.assertOpen(),((await n.adminFetch(Ct,"GET")).records??[]).map(t=>oe(t))),mr=async n=>{n.assertOpen();const e=await n.adminFetch(kt,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},yr=async(n,e)=>(n.assertOpen(),{cancelled:(await n.adminFetch(Et,"POST",{id:e})).cancelled===!0}),Sr=async n=>(n.assertOpen(),(await Yt(async t=>await n.adminFetch(t===void 0?be:`${be}?cursor=${encodeURIComponent(t)}`,"GET"))).map(t=>oe(t))),vr=async(n,e)=>(n.assertOpen(),{retried:(await n.adminFetch(_t,"POST",{id:e})).retried===!0}),br=async(n,e)=>(n.assertOpen(),{removed:(await n.adminFetch(It,"POST",{id:e})).removed===!0}),gr=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(`${Rt}?${t.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}},wr=async(n,e)=>{n.assertOpen();const t=new URLSearchParams({id:e.id,name:e.name}),s=await n.adminFetch(`${Ot}?${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??[]}},Tr=async(n,e)=>(n.assertOpen(),{status:(await n.adminFetch(Lt,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),E=(n,e)=>{try{return re(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)}},ee=n=>{try{return re(n),!0}catch{return!1}},Le=n=>n!==null&&typeof n=="object"&&("error"in n||"result"in n),Xt=(n,e,t)=>{const s=Array.from({length:e}),i=r=>({error:C(Ie(r),t),ok:!1});for(const r of n){if(typeof r.id!="number"||r.id<0||r.id>=e)continue;if(!Le(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:C(ne(o),t),ok:!1}}}return s.map(r=>r??{error:C(new Error("batch call returned no result"),t),ok:!1})},Y=(n,e)=>e!==null?{}:n===null?{expectSubject:null}:n?.startsWith("subj:")===!0?{expectSubject:n.slice(5)}:{},W=n=>n==="connected"||n==="polling",f=n=>n??"",T=(n,e)=>{if(!n.socket||n.wsState!=="open")return!1;try{return n.socket.send(JSON.stringify(e)),!0}catch{return!1}},Zt=n=>{if(!n.pendingStreams||n.pendingStreams.length===0)return;const e=n.pendingStreams;n.pendingStreams=[];for(const t of e)T(n,t)},es=new TextDecoder,ts=n=>{if(typeof n=="string")return n;if(n instanceof ArrayBuffer)return es.decode(n)};class O{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 U=n=>{n.heartbeatTimer!==void 0&&(clearInterval(n.heartbeatTimer),n.heartbeatTimer=void 0)},ss=(n,e,t)=>{U(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(Ft)}catch{}},e))},we=(n,e,t,s)=>{const{WebSocketImpl:i,connectTimeoutMs:r,heartbeatIntervalMs:a}=t;if(i===void 0)throw new v("INTERNAL","no WebSocket implementation available");const o=s.protocols===void 0?new i(e):new i(e,s.protocols);n.socket=o;const c=()=>{U(n),n.connectTimer!==void 0&&(clearTimeout(n.connectTimer),n.connectTimer=void 0),n.socket===o&&(n.socket=void 0)},d=u=>{c(),s.onClose(u)};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(u){console.error("[lunora] connection open handler threw",u)}n.socket===o&&ss(n,a,d)}}),o.addEventListener("message",u=>{if(n.socket===o){n.lastFrameAt=Date.now();try{s.onMessage(u)}catch(h){console.error("[lunora] server frame handler threw",h)}}}),o.addEventListener("close",u=>{n.socket===o&&d(u)}),o.addEventListener("error",()=>{n.socket===o&&d()})},is=n=>{const{afterFailedAttempts:e,intervalMs:t,onReachable:s,onStateChange:i,poll:r}=n,a=t>0&&e>0;let o=0,c,d=!1,u=!1;const h=()=>{c!==void 0&&(clearInterval(c),c=void 0,d=!1,i())},l=y=>{if(c!==void 0){if(!y){h();return}d||(d=!0,i()),s()}},p=()=>{u||(u=!0,r().then(l).finally(()=>{u=!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}},rs=1e4,Te=async n=>B(rs,void 0,n,()=>new TypeError("LunoraClient: poll timed out")),Pe=new Set(["DELIVERY_FENCED","RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Ce=n=>{if(n instanceof H)return!0;const e=n?.code;return e===void 0||Pe.has(e)||ct.has(e)},ns=1e3,Me=6e4,os={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},D=(n,e,t)=>{const s=je(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 H(r,i):new v(os[n]??"BAD_REQUEST",r,{data:i});return C(a,t)},te=(n,e=Math.random)=>{const t=Math.min(ns*2**Math.max(n-1,0),Me);return Math.round(t*(.5+e()*.5))},as=n=>{const e=n?.code;return n instanceof H||e===void 0||Pe.has(e)},cs=(n,e,t)=>{const s=at(n);return s!==void 0&&s>0?Math.min(s,Me):as(n)?te(e,t):void 0},ds=983040,us=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"&&Le(t.body)&&e.set(t.id,t.body);return e},ls=(n,e)=>{if(n===void 0)return{kind:"unanswered"};if("error"in n)return{error:C(Ie(n),e),kind:"errored"};try{return{commitCursor:n.commitCursor,kind:"committed",value:_(n.result)}}catch(t){return{commitCursor:n.commitCursor,error:C(ne(t),e),kind:"undecodable"}}},X=(n,e)=>`${f(n)}\0${e}`,fs=(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 ps{constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,t){Re(this.buffers,this.maxBuffers),this.buffers.set(X(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(X(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=X(e,t),i=this.buffers.get(s);return i&&this.buffers.delete(s),i}clear(){this.buffers.clear()}}const ms=(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(),fs(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"},ke=n=>{const e=[...n.rows.values()];for(const t of n.callbacks)try{t(e)}catch{}},ys=(n,e)=>{for(const[t,s]of e.undecodable){const i=n.get(t);i&&R(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape — ${s instanceof Error?s.message:String(s)}`})}},se=(n,e)=>{n.lastMutationId=Math.max(n.lastMutationId??0,e)},ie=(n,e=!1)=>{for(const t of n.checkpointCallbacks)t({checkpoint:n.serverCursor,mutationId:n.lastMutationId,...e&&{rowsFollow:!0}})},Fe=(n,e,t)=>{n.serverBase=e,t.cursor!==void 0&&(n.serverCursor=t.cursor),t.epoch!==void 0&&(n.serverEpoch=t.epoch)},Ss=(n,e)=>e.cursor!==void 0&&n.serverCursor!==void 0&&n.serverBase!==void 0&&e.epoch!==void 0&&e.epoch===n.serverEpoch&&e.cursor<n.serverCursor,vs=n=>n.type==="delta"&&n.more===!0,j=(n,e)=>n!==void 0&&n!==e,bs=(n,e)=>e==="connected"&&n!=="connected"||e==="polling"&&n!=="connected"&&n!=="polling",gs=n=>{for(const e of n.activeSubscriptions())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()},ws=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()},Ts=(n,e,t)=>{if(j(t,n.identityFingerprint()))return;const s=n.leader,i=bs(s.status,e);s.status=e,e==="connected"&&(s.wasEverConnected=!0),n.emitConnectionStatus(),i&&(n.awaitLeaderAnswers(),n.flushOfflineQueues())},Cs=n=>{n.isLeader()&&n.broadcastStatus(n.computeStatus(),n.identityFingerprint())},ks=(n,e,t,s,i,r)=>{if(j(r,n.identityFingerprint()))return;const a=n.subscription(e);if(!a)return;n.dropCacheSeed(e);const o=!a.valueReceived;a.valueReceived=!0,Fe(a,t,s===void 0?{}:{cursor:s,epoch:i}),s!==void 0&&Z(a,s),F(a,t),o&&n.emitConnectionStatus(),n.settleAwaitedAnswer(a,!0)},As=(n,e,t,s)=>{if(j(s,n.identityFingerprint()))return;const i=n.subscription(e);if(i){const r=!i.valueReceived;i.valueReceived=!0,R(i.errorCallbacks,t),r&&n.emitConnectionStatus(),n.settleAwaitedAnswer(i,!1)}},Es=(n,e,t,s,i,r,a)=>{if(j(a,n.identityFingerprint()))return;const o=n.subscription(e);o&&(n.ackAndAdvanceCursor(o,t,s),i!==void 0&&r===n.clientIdentifier()&&se(o,i),ie(o))},_s=(n,e,t)=>n!==null||e&&t===null,Is=n=>n.sensitive===!0,Rs=(n,e)=>{if(!Is(n))return e;if(e.onlineOnly===!1)throw new v("BAD_REQUEST",`'${n.__lunoraRef}' takes a sensitive argument and is always online-only; onlineOnly: false is not allowed`);return{...e,onlineOnly:!0}},Os=[qe],Ls=100,Ue=1e4,Ps=1e4,Ms=(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)})},Ae=async n=>typeof n=="function"?await n():n,Fs=async(n,e,t,s)=>{const i=new AbortController,r=setTimeout(()=>{i.abort()},Ue);try{const a=await n(e,{body:t,credentials:"include",headers:s,method:"POST",signal:i.signal});return await a.text(),a.status}finally{clearTimeout(r)}},Ee=(n,e)=>new v("OFFLINE_NOT_QUEUED",`'${n}' is online-only and the connection is not live, so it was not queued`,{cause:e,hint:Be}),Us=(n,e)=>n instanceof TypeError&&ee(e),Hs=(n,e,t,s)=>e||n===!0&&t&&!s,Ns=Promise.resolve();class He{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;authTokenOnUpgrade;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;mutationIssueCounter=0;persistence;persistenceVersion;releasePageHideFlush;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new w;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 O;statusListeners=new O;roomFlushes=new Map;roomIdentityResets=new Set;tokenExpiredListeners=new O;identityChangeListeners=new O;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new O;pendingChangeListeners=new O;syncStatusListeners=new O;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 ps(He.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??A(fe(e.url),z),this.wsToken=e.wsToken,this.wsTicket=e.wsTicket;const t=e.authBasePath??Pt;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??Ke(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??ze,this.connectTimeoutMs=e.connectTimeoutMs??Je,this.rpcTimeoutMs=e.rpcTimeoutMs??Ye,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??Xe,this.authTokenOnUpgrade=e.authTokenOnUpgrade??!1,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??Ze,this.defaultConnectionContext=e.connectionContext,this.persistence=yt(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=vt(e.queryCache),this.clientQueryStore=new Ve,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=Ns),this.offlineQueue=new pt(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-${me()}`,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=$t(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,t){const s=this.authToken!==e,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(),u=!s&&e!==null&&r,h=!s&&e===null&&i===null&&r&&!o,l=d!==i;let p=!1;l&&(u?(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,l)),l&&this.restartTabCoordinatorForIdentity(),this.syncReadCacheToCredential(a),s&&this.authTokenListeners.emit(e),(d!==i||s||a)&&this.offlineQueue.size>0&&W(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 v("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&&(Re(this.clientWatermarks,nt),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,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(A(this.url,`${this.authBasePath}${Mt}`),{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 u=this.getConnection(s.shardKey);u&&T(u,{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 v("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 l=()=>{const S=h;h=void 0,S?.()};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:l,stream:r,topic:a});const y=this.getConnection(i)?.connectionId;y!==void 0&&this.grantWhenJoined(i,o,y);let m=!1;return()=>{if(m)return;m=!0;const S=this.liveSocketGrants.get(c),k=S?.delete(o)===!0;S?.size===0&&this.liveSocketGrants.delete(c);const b=this.getConnection(i)?.connectionId;k&&b!==void 0&&this.postLiveControl(d,i,{action:"unsubscribe",connectionId:b,stream:r,subscriptionId:o,topic:a}),l()}}whisper(e,t,s={}){return this.assertLeaderOwnedSurface("whisper"),this.sendEncodedWhisper(e,E(t??null,`whisper data for topic '${e}'`),s)}connectRoom(e,t,s={}){const i=`room:${e.name}`,r=this.whisperSubscribe(i,l=>{t.onMessage(l)},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()}},u=f(s.shardKey),h=this.roomFlushes.get(u)??new Set;return h.add(d),this.roomFlushes.set(u,h),this.roomIdentityResets.add(c),{close:()=>{a=!0,o.length=0,h.delete(d),h.size===0&&this.roomFlushes.delete(u),this.roomIdentityResets.delete(c),r()},send:l=>{if(a||this.closed||this.WebSocketImpl===void 0)return!1;const p=E(l,`room message for '${i}'`),y=typeof structuredClone=="function"?structuredClone(p):JSON.parse(JSON.stringify(p));return d(),o.length===0&&this.roomSendsAdmitted(s.shardKey)&&this.sendEncodedWhisper(i,y,s)?!0:o.length>=Ls?!1:(o.push(y),!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()},he),i(t.onOpen)},shardKey:s.shardKey});return{close:()=>{clearTimeout(r),a.close()},send:o=>{const c=JSON.stringify(E(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:W(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=q(this.wsUrl),i=a=>{const o=q(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 bt(this,e,t,s)}whenReady(e={}){return e.signal===void 0?this.readyPromise:ye(this.readyPromise,e.signal)}get isReady(){return this.readyResolved}peekHydratedQuery(e,t,s){return this.peekHydratedQueryByKey(e,ae(t),s)}peekHydratedQueryByKey(e,t,s){if(!this.readyResolved)return;const 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=w.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 B(this.rpcTimeoutMs,void 0,async t=>this.sendBatch(e,t))}async mutation(e,t,s={}){if(s.signal?.aborted)throw St(s.signal);const{value:i}=await ye(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??(u=>({rows:u})),a=t.length;let o=0,c=0,d=0;for(let u=0;u<a;u+=i){const h=t.slice(u,u+i),l=d,{committed:p}=await this.runMutation(e,r(h),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(l)}`},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(A(fe(this.url),At),{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=>oe(r))))}});return t.close}subscribe(e,t,s,i={}){if(this.assertOpen(),i.signal?.aborted)return()=>{};const r=t??{},a=w.key(e.__lunoraRef,r,i.shardKey);let o=this.subscriptions.get(a);const c=G(s),d=G(i.onError),u=G(i.onCheckpoint);if(!o){this.nextSubId+=1;const y=`sub_${this.nextSubId.toString()}`,m=ae(r),S=this.takeHydratedCache(e.__lunoraRef,m,i.shardKey);o={ack:"idle",args:r,argsKey:m,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:y,lastValue:S?.value,optimisticLayers:[],serverBase:S?.value,serverCursor:S?.serverCursor,shardKey:i.shardKey,valueReceived:!1,wireArgs:E(r,`args for '${e.__lunoraRef}'`),...S?.serverEpoch===void 0?{}:{serverEpoch:S.serverEpoch}},this.subscriptions.add(o),this.emitSyncStatus(),this.isCrossTabFollower()&&W(this.computeStatus())&&this.awaitLeaderAnswer(o),S!==void 0&&this.cacheSeededQueries.set(a,S)}if(o.callbacks.add(c),d&&o.errorCallbacks.add(d),u&&o.checkpointCallbacks.add(u),o.lastValue!==void 0)try{c(o.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(o);const h=o;let l=!1;const p=()=>{if(!l&&(l=!0,i.signal?.removeEventListener("abort",p),h.callbacks.delete(c),d&&h.errorCallbacks.delete(d),u&&h.checkpointCallbacks.delete(u),h.callbacks.size===0)){this.sendOrQueueUnsubscribe(h.shardKey,h.id,"unsubscribe"),this.returnCacheSeed(w.keyOf(h)),this.subscriptions.remove(h);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",p,{once:!0}),i.signal?.aborted&&p(),p}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:E(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 v("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}=wt({maxBuffer:s.maxBuffer,onCancel:()=>{this.cancelStream(i,r)}});this.ensureSocket(r);const d=this.getConnection(r),u={id:i,query:{args:E(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:u,shardKey:r};this.streams.set(i,h);const l=d?.wsState==="open"&&T(d,u);if(!l&&d===void 0)return this.forgetStream(i),o.fail(new v("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),c;if(!l){for(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=et;){const y=d.pendingStreams.shift()?.id,m=y?this.streams.get(y):void 0;m&&(m.handle.fail(new v("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(y))}d.pendingStreams.push(u)}return c}httpStream(e,t,s={}){if(this.closed)throw new v("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new v("INTERNAL","LunoraClient: no `fetch` implementation available");const i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return dt(e,t,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0;for(const e of this.whisperJoins.keys())this.dropWhisperJoinWaiters(e);this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.releasePageHideFlush?.(),this.releasePageHideFlush=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const e of this.streams.values())e.handle.fail(new v("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();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){return this.rejectQueuedForIdentityChange(e),this.warnRefreshWithoutSubject(s,i),_s(e,t,i)?(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?[Vt,Jt(this.authToken)]:void 0}applyUpgradeBearer(e){e==="cold"?(this.resetRoomSends(),this.reconnectCold()):e==="warm"&&this.bounceShardSockets()}assertOpen(){if(this.closed)throw new v("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 v("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}shardInUse(e){const t=s=>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())},tt))}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 v("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,U(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,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 ot({channelName:e,onBecomeLeader:()=>{gs(t)},onStopBeingLeader:()=>{ws(t)},onConnectionStatus:(s,i)=>{Ts(t,s,i)},onSubscriptionData:(s,i,r,a,o)=>{ks(t,s,i,r,a,o)},onLeaderClaimAnswered:()=>{Cs(t)},onSubscriptionError:(s,i,r)=>{As(t,s,i,r)},onSubscriptionSettled:(s,i,r,a,o,c)=>{Es(t,s,i,r,a,o,c)}})}async sendBatch(e,t){if(this.assertOpen(),!this.fetchImpl)throw new v("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];const s=await this.fetchImpl(A(this.url,V),{body:JSON.stringify({calls:e.map((o,c)=>({args:E(o.args??{},`args for batch call '${o.fn.__lunoraRef}'`),functionPath:o.fn.__lunoraRef,id:c,shardKey:o.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:t}),i=s.headers.get("x-d1-bookmark");i&&this.bookmark.set(i);let r;try{r=await s.json()}catch{throw C(new v("INTERNAL",`LunoraClient: batch response was not JSON (status ${s.status.toString()})`),s.headers)}const a=x(r);if(!s.ok||a!==void 0&&!r.results)throw a!==void 0?C(ce(a),s.headers):C(new v("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 Xt(r.results??[],e.length,s.headers)}async runMutation(e,t,s){this.assertOpen();const i=Rs(e,s),r=t,a=i.mutationId??me();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{confirms:u,rollbacks:h}=this.applyOptimisticUpdates(e.__lunoraRef,r,i.shardKey,i.optimistic);this.applyOptionalOptimisticUpdate(i.optimisticUpdate,t,i.shardKey,h,u);const l=i.onlineOnly?void 0:this.offlineFlushes.get(f(i.shardKey));l!==void 0&&await l;const{httpFirst:p,midReconnect:y,shouldQueueOffline:m,socketDown:S}=this.writeQueueGate(i.shardKey),k=!i.onlineOnly&&m&&i.replayBaseline===void 0&&this.hasPendingWriteAhead(i.shardKey),b=async(g=!1)=>this.enqueueOfflineMutation(e,r,i.shardKey,d,a,h,u,g?void 0:i.precondition,i.mutationId,c?.stamp,g,o);if(this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i,h),S||y||k)return b();let N;try{const g=await this.rpc(e.__lunoraRef,r,i.shardKey,{baselineSeq:d,captureBookmark:!0,...c?.flags,mutationId:a,onCommitCursor:L=>{N=L}});for(const L of u)L(N);return{committed:!0,value:g}}catch(g){const L=Us(g,r),Ne=p&&m&&L,We=this.ownSocketOpen(i.shardKey);if(m&&!i.onlineOnly&&this.fetchImpl!==void 0&&!this.outbox&&i.replayBaseline===void 0&&(g instanceof TypeError||g instanceof H)&&ee(r)){const De=b(!0);return this.noteHeldRetryDelay(i.shardKey),this.scheduleRateLimitedRetry(i.shardKey),De}throw this.settleFailedDirectWrite(g,N,u,h,c?.flags.authToken),Hs(i.onlineOnly,Ne,L,We)?Ee(e.__lunoraRef,g):g}}refuseOnlineOnlyWhenDown(e,t,s=[]){if(!t.onlineOnly)return;const i=this.writeQueueGate(t.shardKey);if(i.socketDown||i.midReconnect)throw P(s),Ee(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,u=i||s;return{httpFirst:u,midReconnect:a==="connecting"&&c&&!u,shouldQueueOffline:d,socketDown:a!=="open"&&!t&&d&&!u,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}P(i)}async enqueueOfflineMutation(e,t,s,i,r,a,o,c,d,u,h,l){const p=u===void 0?this.identityFingerprint():u;if(this.outbox){this.outboxMutationCounter+=1;const m=this.outboxMutationCounter;try{await this.outbox.enqueue({args:t,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:d??`${this.clientId}:${String(m)}`,identity:p,mutationId:m,...a.length>0&&{onRejected:()=>{P(a)}},shardKey:s})}catch(S){throw P(a),S instanceof Error?S:new Error(String(S))}for(const S of o)S(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((m,S)=>{const k={ambiguousSend:h,args:t,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:r,issueSeq:l,clientId:this.clientId,identity:p,precondition:this.holdWhileUnanswered(c),onCommit:b=>{for(const N of o)N(b)},reject:b=>{this.queuedIdentities.delete(r),Q(b)||P(a),S(b instanceof Error?b:new Error(String(b))),this.releaseIdleShard(s)},resolve:m,shardKey:s};this.offlineQueue.enqueue(k),this.queuedOfflineShardKeys.add(s),this.ensureSocket(s),k.id!==void 0&&this.queuedIdentities.set(k.id,p)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;const t=f(e);return 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=await this.queryCache.load(),t=new Map;for(const s of this.subscriptions.all())t.set(M(s.fn.__lunoraRef,s.argsKey,s.shardKey),s);for(const{key:s,...i}of e){if(mt(this.persistenceVersion,i.version)){this.queryCache.remove(s).catch(()=>{});continue}const r=t.get(s);if(r&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(r,i);continue}this.hydratedQueryCache.set(s,i)}}catch{}}seedSubscriptionFromCache(e,t){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(t)||(e.serverBase=t.value,e.serverCursor=t.serverCursor,t.serverEpoch!==void 0&&(e.serverEpoch=t.serverEpoch),this.cacheSeededQueries.set(M(e.fn.__lunoraRef,e.argsKey,e.shardKey),t),F(e,t.value))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}returnCacheSeed(e){const t=this.cacheSeededQueries.get(e);t!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,t))}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(const[e,t]of this.cacheSeededQueries){const s=this.subscriptions.get(e);s!==void 0&&(s.serverBase=void 0,s.serverCursor=void 0,s.serverEpoch=void 0,F(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,...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(()=>{})},st))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;const{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}const t=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(t.map(async([s,i])=>e.put(s,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&&(ee(o.args)?s.push(o):(this.markQueryRejected(o,!0),R(o.errorCallbacks,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"})));if(s.length===0)return this.probeOrigin();const i=ft(),r=this.identityFingerprint();let a;try{a=await Te(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),R(c.errorCallbacks,{code:d.error.code,message:d.error.message});continue}this.handleDataMessage({data:re(d.value),id:c.id,type:"data"},i)}}return!0}async probeOrigin(){const{fetchImpl:e}=this;if(!e)return!1;try{return await Te(async t=>e(A(this.url,V),{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=w.key(e,t,s),c=this.subscriptions.get(o);if(c){const d=ut(c,i);d&&(r.push(d.confirm),a.push(d.rollback))}return{confirms:r,rollbacks:a}}applyOptionalOptimisticUpdate(e,t,s,i,r){e&&this.applyOptimisticUpdate(e,t,s,i,r)}applyOptimisticUpdate(e,t,s,i,r){const{confirms:a,rollbacks:o,store:c}=ht(this.subscriptions,s);try{e(c,t)}catch{P(o);return}i.push(...o),r.push(...a)}getConnection(e){return this.connections.get(f(e))}sendOrQueueUnsubscribe(e,t,s){const i=this.getConnection(e);i&&!T(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:is({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:()=>{this.flushOfflineQueue(e).catch(()=>{})},onStateChange:()=>{this.emitConnectionStatus()},poll:async()=>this.pollSubscriptions(e)}),reconnect:Se(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=Se(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(l,s.next()))},c=m=>{a||this.WebSocketImpl===void 0||we(i,this.wsUrlFor(t.shardKey,m,e),this.managedSocketOptions,{onClose:()=>{o(),t.onClose?.()},onMessage:t.onMessage,...t.onOpen===void 0?{}:{onOpen:t.onOpen},...t.offerBearer===!0?{protocols:this.upgradeProtocols()}:{}})};let d=0,u;const h=async m=>{const S=this.wsCredentialGeneration;d+=1;const k=d;let b;u=S;try{b=await Ms(m,Ps)}catch{k===d&&(u=void 0,o());return}if(k===d){if(u=void 0,S!==this.wsCredentialGeneration){l();return}c(b)}},l=()=>{if(a||this.WebSocketImpl===void 0)return;const{wsTicket:m}=this;if(typeof m=="function"){h(m).catch(()=>{});return}c(m)};l();const p=()=>{a=!0,r!==void 0&&(clearTimeout(r),r=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),U(i);const{socket:m}=i;i.socket=void 0;try{m?.close()}catch{}};this.adminSocketTeardowns.add(p);const y=()=>{const{socket:m}=i;if(m===void 0){u!==void 0&&u!==this.wsCredentialGeneration&&(d+=1,u=void 0,l());return}i.socket=void 0,i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),U(i);try{m.close()}catch{}t.onClose?.(),o()};return this.supplementaryBounces.add(y),{close:()=>{p(),this.adminSocketTeardowns.delete(p),this.supplementaryBounces.delete(y)},resetBackoff:()=>{s.reset()},socket:()=>i.socket}}supplementaryUrl(e){const t=q(this.wsUrl),s=t.pathname.endsWith(z)?t.pathname.slice(0,-z.length):t.pathname;return t.pathname=A(s,e),pe(t,this.wsUrl)}wsUrlFor(e,t,s=this.wsUrl){const i=q(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("&"),pe(i,s)}rpcRequestHeaders(e,t){const s={"content-type":"application/json"};e.expectSubject!==void 0&&(s[Wt]=Dt(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 H("LunoraClient: no `fetch` implementation available");const a=this.rpcRequestHeaders(i,s),o=i.authToken===void 0?this.authToken:i.authToken,c=JSON.stringify({args:E(t,`args for '${e}'`),functionPath:e,shardKey:s}),{body:d,response:u}=await B(i.unbounded?0:this.rpcTimeoutMs,i.signal,async p=>{const y=await r(A(this.url,Tt),{body:c,headers:a,method:"POST",signal:p});try{return{body:await y.json(),response:y}}catch{return{body:void 0,response:y}}});if(i.captureBookmark){const p=u.headers.get("x-d1-bookmark");p&&this.bookmark.set(p)}if(d===void 0)throw D(u.status,u.statusText,u.headers);const h=d;if(typeof h!="object"||h===null||Array.isArray(h))throw D(u.status,u.statusText,u.headers);const l=x(d);if(l!==void 0)throw de(l,u.headers);if(!u.ok)throw D(u.status,u.statusText,u.headers);i.onMutationAck?.(d.lastMutationId),i.onCommitCursor?.(d.commitCursor),this.noteCredentialAccepted(o),this.learnDefaultShardKey(u,s),this.recordShardCursor(s,d.commitCursor);try{return _(d.result)}catch(p){throw C(ne(p),u.headers)}}async adminFetch(e,t,s,i){if(!this.fetchImpl)throw new v("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(A(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 v("INTERNAL",`LunoraClient: response was not JSON (status ${c.status.toString()}${h})`)}const u=x(d);if(u!==void 0)throw ce({...u,message:u.message??"admin request failed"});if(!c.ok){const h=c.statusText?` ${c.statusText}`:"";throw new v("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));T(e,{caps:Os,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)}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 B(this.connectTimeoutMs,void 0,async()=>({session:await Ae(this.wsToken),ticket:await Ae(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(),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;we(e,this.wsUrlFor(t,s.ticket),this.managedSocketOptions,{onClose:r=>{r?.code===4003&&e.polling.noteFailedOpen(),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.roomsRejoined=!1,clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},he),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)T(e,{id:c,type:d});this.releaseIdleShard(t)}Zt(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),T(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(),U(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",e.connectionId=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 v("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&&(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<it;){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=T(s,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...i?{sinceSeq:e.serverCursor}:{},...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),$(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):$(t)},le))}sendShapeSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);t?.wsState==="open"&&T(t,{id:e.id,shape:{name:e.name,...e.wireArgs===void 0?{}:{args:e.wireArgs}},type:"shape_subscribe",...e.serverCursor===void 0?{}:{sinceCheckpoint:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,t){const s=ts(e);if(s===void 0)return;let i;try{i=JSON.parse(s)}catch{return}if(i.type!=="error"&&this.getConnection(t)?.reconnect.reset(),typeof i.id=="string"){const r=this.getConnection(t);if(r){const{id:a}=i;this.settleSubscribeWatchdog(r,a)}}switch(i.type){case"ack":{const r=this.subscriptions.getById(i.id);r&&this.ackAndAdvanceCursor(r,void 0,void 0);return}case"chunk":{const{data:r,generation:a,id:o,seq:c}=i,d=this.streams.get(o);d&&typeof c=="number"&&(d.lastSeq=c,typeof a=="number"&&(d.generation=a),d.durable=!0),d?.handle.push(_(r));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"identity":{this.handleIdentityFrame(i,t),this.adoptSocketConnectionId(i,t),this.confirmShardIdentity(t);break}case"live":{this.dispatchLive(i,t);break}case"pokeEnd":{this.handlePokeEnd(i,t);break}case"pokePart":{this.pokeAssembler.part(t,i);break}case"pokeStart":{this.pokeAssembler.start(t,i);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,t);break}case"whisper_subscribed":{this.acknowledgeWhisperJoin(f(t),i.topic);break}}}handleErrorMessage(e){const t=e.error?.code;if(t==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}if(t==="STREAM_ID_IN_USE")return;const{id:s}=e,i=s===void 0?void 0:this.streams.get(s);if(i&&s!==void 0){i.handle.fail(Ge(e)),this.forgetStream(s);return}const r=s===void 0?void 0:this.subscriptions.getById(s);if(r){$(r);const o=ue(e),c=this.identityFingerprint(),d=w.keyOf(r);this.markQueryRejected(r),R(r.errorCallbacks,o),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(d,o,c);return}const a=s===void 0?void 0:this.shapeSubscriptions.get(s);a&&(a.answered||(a.answered=!0,this.emitSyncStatus()),R(a.errorCallbacks,ue(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){ys(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=ms(e,t,s);if(e.answered!==i&&this.emitSyncStatus(),ke(e),r==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){I(e,"idle"),e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,this.emitSyncStatus(),console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}handleDataMessage(e,t){const{id:s}=e,i=s?this.subscriptions.getById(s):void 0;if(!i||e.type==="data"&&Ss(i,e))return;let r;const a=i.pendingDeltaRun;try{r=Qe(e,a===void 0?i.serverBase:a.payload)}catch(c){i.pendingDeltaRun=void 0,R(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription — ${c instanceof Error?c.message:String(c)}`}),this.settleAwaitedAnswer(i,!1);return}if(r===xe){this.resnapshotSubscription(i);return}if(vs(e)){i.pendingDeltaRun={payload:r};return}i.pendingDeltaRun=void 0,this.dropCacheSeed(w.keyOf(i));const o=t!==void 0&&!i.valueReceived;if(Fe(i,r,{cursor:e.cursor,epoch:e.epoch}),o&&(i.valueReceived=!0,this.emitSyncStatus()),e.lastMutationId!==void 0&&(se(i,e.lastMutationId),ie(i,!0)),this.persistQueryValue(i),Z(i,i.serverCursor),t!==void 0&<(i,t),F(i,r),this.tabCoordinator?.isLeader()){const c=w.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(c,r,i.serverCursor,i.serverEpoch,this.identityFingerprint())}this.settleAwaitedAnswer(i,!0)}handleResumeMessage(e){const t=this.subscriptions.getById(e.id);t&&(t.pendingDeltaRun=void 0,this.ackAndAdvanceCursor(t,e.cursor,e.epoch),this.tabCoordinator?.isLeader()&&t.serverBase!==void 0&&this.tabCoordinator.broadcastSubscriptionData(w.keyOf(t),t.serverBase,t.serverCursor,t.serverEpoch,this.identityFingerprint()),this.settleAwaitedAnswer(t,!0))}handleSettledMessage(e){const t=this.subscriptions.getById(e.id);if(t&&(this.ackAndAdvanceCursor(t,e.cursor,e.epoch),e.lastMutationId!==void 0&&se(t,e.lastMutationId),ie(t),this.tabCoordinator?.isLeader())){const s=w.keyOf(t);this.tabCoordinator.broadcastSubscriptionSettled(s,t.serverCursor,t.serverEpoch,t.lastMutationId,this.clientId,this.identityFingerprint())}}ackAndAdvanceCursor(e,t,s){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),Z(e,e.serverCursor)&&F(e,e.serverBase))}adoptSocketConnectionId(e,t){const s=this.getConnection(t);if(!(s===void 0||typeof e.connectionId!="string")){s.connectionId=e.connectionId,s.whisperAck=e.whisperAck===!0;for(const i of this.liveSocketGrants.get(f(t))?.keys()??[])this.grantWhenJoined(t,i,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},u=>{this.refuseLiveGrant(e,t,u,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,T(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()},Ue),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(()=>Fs(r,A(this.url,e),a,o)).then(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(),R(s.errorCallbacks,{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()?!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&&W(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&&T(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.queryCache?.clear().catch(()=>{})}evictPreviousIdentitySession(){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.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,I(e,"idle"),e.valueReceived=!1,F(e,void 0);for(const e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,e.answered=!1,ke(e);this.emitSyncStatus(),this.bounceShardSockets()}bounceShardSockets(){for(const e of this.connections.values())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)});for(const e of this.supplementaryBounces)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&&W(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=ve(e),s=t&&this.subscriptions.get(w.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=ve(e);if(e===void 0||t===void 0)return e;const s=()=>this.snapshotAnswer(e)!==void 0||e();return gt(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*le))}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 u of s){this.unpersist(u.id),this.queuedIdentities.delete(u.id??"");const h=new Error("offline mutation skipped: precondition failed before replay");h.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(u,"rejected",h)}const i=f(e),r=this.holdUndecidedWrites(i,this.offlineQueue.drain(u=>f(u.shardKey)===i));if(r.length===0)return;const a=[],o=[];for(const u of r){const h=this.replayGateVerdict(u);h==="send"?a.push(u):h==="hold"&&o.push(u)}if(this.offlineQueue.requeue(o),o.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),a.length===0){this.scheduleRateLimitedRetry(e);return}const c=this.encodableOrSettleTerminal(a);if(c.length===0){this.scheduleRateLimitedRetry(e);return}if(c.length===1){await this.replaySequential(c,e,t),this.scheduleRateLimitedRetry(e);return}const d=[];for(let u=0;u<c.length;u+=J){const h=c.slice(u,u+J),l=await this.replayBatched(h,e,t);if(d.push(...l.requeue),l.stop||l.requeue.length>0){d.push(...c.slice(u+J));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,te(i))})}noteReplayRetryDelay(e,t,s){const i=f(e),r=this.replayRetryState.get(i),a=(r?.attempts??0)+1,o=cs(t,a)??(s===null&&K(t)?te(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{E(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)||Ce(e)}noteReplayAuthRefusal(e,t){if(!K(e))return!1;const s=this.hashToken(t??"");return t===this.authToken&&this.authRefusalNotifiedFor!==s&&(this.authRefusalNotifiedFor=s,this.notifyTokenExpired()),!0}noteCredentialAccepted(e){this.authRefusalNotifiedFor!==void 0&&this.authRefusalNotifiedFor===this.hashToken(e??"")&&(this.authRefusalNotifiedFor=void 0)}takeReplayCredential(e){if(e===void 0)return;const t=this.replayCredentials.get(e);if(t===void 0)throw new TypeError("LunoraClient: `replayCredential` must come from this client's `replayIdentityVerdict`, and is single use");return this.replayCredentials.delete(e),{flags:{authToken:t.authToken,...Y(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||K(t)||s==="RATE_LIMITED"||s==="TOO_MANY_REQUESTS"||!Ce(t))return!1;const i=(this.replayAttempts.get(e.id)??0)+1;return this.replayAttempts.set(e.id,i),i>=rt}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,...Y(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,u)=>({args:E(d.args,`args for '${d.functionPath}'`),baselineSeq:d.baselineSeq,functionPath:d.functionPath,id:u,clientId:d.clientId??this.clientId,mutationId:d.id,shardKey:d.shardKey}))});if(e.length>1&&us(i)>ds)return await this.replayBatchedHalves(e,t,s);const{fetchImpl:r}=this;let a,o;try{({payload:o,response:a}=await B(this.rpcTimeoutMs,void 0,async d=>{const u=await r(A(this.url,V),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:s,...Y(e.find(h=>h.identity!==void 0)?.identity,s)}),method:"POST",signal:d});if(u.status===413&&e.length>1)return{payload:void 0,response:u};try{return{payload:await u.json(),response:u}}catch{return{payload:void 0,response:u}}}))}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,D(a.status,a.statusText,a.headers),t,s);if(!Array.isArray(o.results)){const d=x(o),u=d===void 0?D(a.status,a.statusText,a.headers):de(d,a.headers);return this.settleWholeBatchError(e,u,t,s)}return{requeue:this.settleReplayBatchSlots(e,o.results,t,s,a.headers),stop:!1}}settleWholeBatchError(e,t,s,i){if(t instanceof H||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[u,h]of e.entries()){const l=ls(a.get(u),r);switch(l.kind){case"committed":{c=!0,this.settleReplaySuccess(h,l.value,l.commitCursor);break}case"errored":{d||=K(l.error),this.shouldRequeueReplayFailure(l.error,i)&&!this.spendsLastReplayAttempt(h,l.error)?(this.noteReplayRetryDelay(s,l.error,i),o.push(h)):this.settleReplayTerminal(h,l.error);break}case"unanswered":{const p=C($e(),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,l.error,l.commitCursor)}}return c&&!d&&this.noteCredentialAccepted(i),o}}export{Gi as $,li as A,Li as B,ui as C,Pi as D,Mi as E,di as F,mi as G,Fi as H,Ui as I,Hi as J,wi as K,He as L,Ni as M,Wi as N,fi as O,Di as P,Bi as Q,Qi as R,ni as S,xi as T,qi as U,vi as V,Ki as W,Vi as X,zi as Y,Ji as Z,ji as _,hi as a,$i as a0,Yi as a1,Xi as a2,Zi as a3,er as a4,tr as a5,sr as a6,ir as a7,rr as a8,nr as a9,or as aa,ar as ab,cr as ac,dr as ad,ur as ae,hr as af,lr as ag,fr as ah,Ai as ai,pi as b,yi as c,Si as d,Ti as e,Ci as f,gi as g,oi as h,ci as i,ai as j,bi as k,pr as l,yr as m,Sr as n,br as o,gr as p,wr as q,vr as r,mr as s,Tr as t,ki as u,Ei as v,_i as w,Ii as x,Ri as y,Oi as z};
|