@lunora/client 1.0.0-alpha.193 → 1.0.0-alpha.195
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/auth/index.d.mts +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/index.d.mts +17 -17
- package/dist/index.d.ts +17 -17
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/LunoraClient-BIzBh60k.mjs +1 -0
- package/dist/packem_shared/SubscriptionRegistry-5CHmk3d8.mjs +1 -0
- package/dist/packem_shared/applyDelta-5zZaiLB7.mjs +1 -0
- package/dist/packem_shared/createLocalStore-CIh8bYs-.mjs +1 -0
- package/dist/packem_shared/{createServerClient-HdISrPXa.mjs → createServerClient-D7zkixlG.mjs} +1 -1
- package/dist/packem_shared/delta-merge-Cu-cN5Cb.mjs +1 -0
- package/dist/packem_shared/local-store-SJVMlM2Z.mjs +1 -0
- package/dist/packem_shared/{lunora-client.d-DDVPWV7D.d.mts → lunora-client.d-SHCNd1Cn.d.mts} +78 -117
- package/dist/packem_shared/{lunora-client.d-C6lZEDyl.d.ts → lunora-client.d-YjgrrB49.d.ts} +78 -117
- package/dist/packem_shared/{preload.d-CdYylQeH.d.ts → preload.d-BTB4TAd_.d.ts} +1 -1
- package/dist/packem_shared/{preload.d-Cf8tiYKi.d.mts → preload.d-Cenry5u_.d.mts} +1 -1
- package/dist/packem_shared/wire-errors-8iZTTKRN.mjs +1 -0
- package/dist/query/index.d.mts +2 -2
- package/dist/query/index.d.ts +2 -2
- package/dist/service.mjs +1 -1
- 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-sL0hnKnB.mjs +0 -1
- package/dist/packem_shared/SubscriptionRegistry-CxKugiaA.mjs +0 -1
- package/dist/packem_shared/applyDelta-CK4TguD-.mjs +0 -1
- package/dist/packem_shared/createLocalStore-Di9RGozS.mjs +0 -1
- package/dist/packem_shared/delta-merge-BCAy1Q0H.mjs +0 -1
- package/dist/packem_shared/local-store-C9mvzb5T.mjs +0 -1
- package/dist/packem_shared/replay-CXXDZ1_h.mjs +0 -1
package/dist/auth/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { U as User, L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
1
|
+
import { U as User, L as LunoraClient } from "../packem_shared/lunora-client.d-SHCNd1Cn.mjs";
|
|
2
2
|
import '@lunora/errors';
|
|
3
3
|
import "../packem_shared/function-reference.d-Br_hsKje.mjs";
|
|
4
4
|
import '@lunora/runtime';
|
package/dist/auth/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { U as User, L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
1
|
+
import { U as User, L as LunoraClient } from "../packem_shared/lunora-client.d-YjgrrB49.js";
|
|
2
2
|
import '@lunora/errors';
|
|
3
3
|
import "../packem_shared/function-reference.d-Br_hsKje.js";
|
|
4
4
|
import '@lunora/runtime';
|
package/dist/index.d.mts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { c as PersistenceAdapter, Q as QueryCacheAdapter, B as BookmarkStorage, C as ConnectionStatus, S as SubscriptionError, H as HttpStreamRef, d as HttpStreamArgsOf, e as HttpStreamChunkOf, f as StreamIterable, O as OfflineQueueOptions,
|
|
2
|
-
export { type A as ActionCallOptions, type g as BatchSlot, type h as CachedQuery, type i as ClientDebugShard, type j as ClientDebugSnapshot, type k as ClientDebugSubscription, type l as ClientMessage, type m as ClientQueryRef, type n as ClientShapeSubscribeMessage, type o as ClientShapeUnsubscribeMessage, D as DEFAULT_MAX_BUFFER, type F as FunctionArgumentDescriptor, type p as FunctionDescriptor, type G as GlobalFacetResult, type q as GlobalFacetValue, type r as GlobalFilterClause, type s as GlobalTableInfo, type t as GlobalTablePage, type u as HttpStreamCallArgs, type v as LunoraClientError, type w as LunoraClientOptions, type M as MutationCallOptions, type x as MutationSettledEvent, type y as OptimisticLocalStore, type z as OptimisticUpdate, type E as OutboxMutation, type I as OutboxSink, type J as PersistedMutation, type P as Preloaded, type K as ReplayCredential, type N as ReplayIdentityVerdict, type T as RowOp, type V as RpcEnvelope, type W as RpcResponseBody, type X as ScheduleRecord, type Y as ScheduleRetryPolicy, type Z as SchedulerPoolStatus, type _ as SchedulerStatus, type $ as ServerMessage, type a0 as ServerPokeEndMessage, type a1 as ServerPokePartMessage, type a2 as ServerPokeStartMessage, type a3 as ShardTrafficEntry, type a4 as ShardTrafficResult, type a5 as StorageListPage, type a6 as StorageObject, type a7 as StoredQuery, type a8 as StreamHandle, type a9 as SubscriptionCallback, type b as SubscriptionErrorCallback, aa as SubscriptionRegistry, type ab as SubscriptionState, type ac as SyncWatermark, type a as Unsubscribe, type U as User, type ad as WorkflowInstanceAction, type ae as WorkflowInstanceDetail, type af as WorkflowInstancePage, type ag as WorkflowInstanceStatus, type ah as WorkflowInstanceSummary, type ai as WorkflowStepDetail, type aj as WsTokenProvider, ak as createClientQuery, al as createLocalStore, am as createStream } from "./packem_shared/lunora-client.d-
|
|
1
|
+
import { R as ReconnectOptions, c as PersistenceAdapter, Q as QueryCacheAdapter, B as BookmarkStorage, C as ConnectionStatus, S as SubscriptionError, H as HttpStreamRef, d as HttpStreamArgsOf, e as HttpStreamChunkOf, f as StreamIterable, O as OfflineQueueOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-SHCNd1Cn.mjs";
|
|
2
|
+
export { type A as ActionCallOptions, type g as BatchSlot, type h as CachedQuery, type i as ClientDebugShard, type j as ClientDebugSnapshot, type k as ClientDebugSubscription, type l as ClientMessage, type m as ClientQueryRef, type n as ClientShapeSubscribeMessage, type o as ClientShapeUnsubscribeMessage, D as DEFAULT_MAX_BUFFER, type F as FunctionArgumentDescriptor, type p as FunctionDescriptor, type G as GlobalFacetResult, type q as GlobalFacetValue, type r as GlobalFilterClause, type s as GlobalTableInfo, type t as GlobalTablePage, type u as HttpStreamCallArgs, type v as LunoraClientError, type w as LunoraClientOptions, type M as MutationCallOptions, type x as MutationSettledEvent, type y as OptimisticLocalStore, type z as OptimisticUpdate, type E as OutboxMutation, type I as OutboxSink, type J as PersistedMutation, type P as Preloaded, type K as ReplayCredential, type N as ReplayIdentityVerdict, type T as RowOp, type V as RpcEnvelope, type W as RpcResponseBody, type X as ScheduleRecord, type Y as ScheduleRetryPolicy, type Z as SchedulerPoolStatus, type _ as SchedulerStatus, type $ as ServerMessage, type a0 as ServerPokeEndMessage, type a1 as ServerPokePartMessage, type a2 as ServerPokeStartMessage, type a3 as ShardTrafficEntry, type a4 as ShardTrafficResult, type a5 as StorageListPage, type a6 as StorageObject, type a7 as StoredQuery, type a8 as StreamHandle, type a9 as SubscriptionCallback, type b as SubscriptionErrorCallback, aa as SubscriptionRegistry, type ab as SubscriptionState, type ac as SyncWatermark, type a as Unsubscribe, type U as User, type ad as WorkflowInstanceAction, type ae as WorkflowInstanceDetail, type af as WorkflowInstancePage, type ag as WorkflowInstanceStatus, type ah as WorkflowInstanceSummary, type ai as WorkflowStepDetail, type aj as WsTokenProvider, ak as createClientQuery, al as createLocalStore, am as createStream } from "./packem_shared/lunora-client.d-SHCNd1Cn.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-Cenry5u_.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';
|
|
@@ -79,6 +79,20 @@ declare const getRetryAfterMs: (error: unknown) => number | undefined;
|
|
|
79
79
|
* write for the next attempt instead of dropping it.
|
|
80
80
|
*/
|
|
81
81
|
declare const isAuthReplayFailure: (error: unknown) => boolean;
|
|
82
|
+
/**
|
|
83
|
+
* Exponential backoff calculator with optional jitter.
|
|
84
|
+
*
|
|
85
|
+
* `next()` doubles the delay each call up to `maxDelayMs`. When `jitter` is
|
|
86
|
+
* enabled the returned value is randomized in `[delay/2, delay]` so a fleet
|
|
87
|
+
* of clients reconnecting at the same time spread out their retries.
|
|
88
|
+
*/
|
|
89
|
+
interface ReconnectCalculator {
|
|
90
|
+
/** Returns the delay to wait before the next reconnect attempt. */
|
|
91
|
+
next: () => number;
|
|
92
|
+
/** Resets the backoff to the initial delay (call on successful reconnect). */
|
|
93
|
+
reset: () => void;
|
|
94
|
+
}
|
|
95
|
+
declare const createReconnect: (options?: ReconnectOptions, random?: () => number) => ReconnectCalculator;
|
|
82
96
|
/**
|
|
83
97
|
* Optimistic-reconcile logic shared by every `@lunora/*` framework adapter's
|
|
84
98
|
* agent-chat surface (`@lunora/react` `useAgentChat`, plus the `@lunora/vue`,
|
|
@@ -905,20 +919,6 @@ interface IndexedDbQueryCacheOptions {
|
|
|
905
919
|
* environments should use {@link createInMemoryQueryCache}.
|
|
906
920
|
*/
|
|
907
921
|
declare const createIndexedDbQueryCache: (options?: IndexedDbQueryCacheOptions) => QueryCacheAdapter;
|
|
908
|
-
/**
|
|
909
|
-
* Exponential backoff calculator with optional jitter.
|
|
910
|
-
*
|
|
911
|
-
* `next()` doubles the delay each call up to `maxDelayMs`. When `jitter` is
|
|
912
|
-
* enabled the returned value is randomized in `[delay/2, delay]` so a fleet
|
|
913
|
-
* of clients reconnecting at the same time spread out their retries.
|
|
914
|
-
*/
|
|
915
|
-
interface ReconnectCalculator {
|
|
916
|
-
/** Returns the delay to wait before the next reconnect attempt. */
|
|
917
|
-
next: () => number;
|
|
918
|
-
/** Resets the backoff to the initial delay (call on successful reconnect). */
|
|
919
|
-
reset: () => void;
|
|
920
|
-
}
|
|
921
|
-
declare const createReconnect: (options?: ReconnectOptions, random?: () => number) => ReconnectCalculator;
|
|
922
922
|
/**
|
|
923
923
|
* Capture a snapshot of the current live query value at call time and produce a
|
|
924
924
|
* `() => boolean` precondition that compares it against the value at replay time.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { c as PersistenceAdapter, Q as QueryCacheAdapter, B as BookmarkStorage, C as ConnectionStatus, S as SubscriptionError, H as HttpStreamRef, d as HttpStreamArgsOf, e as HttpStreamChunkOf, f as StreamIterable, O as OfflineQueueOptions,
|
|
2
|
-
export { type A as ActionCallOptions, type g as BatchSlot, type h as CachedQuery, type i as ClientDebugShard, type j as ClientDebugSnapshot, type k as ClientDebugSubscription, type l as ClientMessage, type m as ClientQueryRef, type n as ClientShapeSubscribeMessage, type o as ClientShapeUnsubscribeMessage, D as DEFAULT_MAX_BUFFER, type F as FunctionArgumentDescriptor, type p as FunctionDescriptor, type G as GlobalFacetResult, type q as GlobalFacetValue, type r as GlobalFilterClause, type s as GlobalTableInfo, type t as GlobalTablePage, type u as HttpStreamCallArgs, type v as LunoraClientError, type w as LunoraClientOptions, type M as MutationCallOptions, type x as MutationSettledEvent, type y as OptimisticLocalStore, type z as OptimisticUpdate, type E as OutboxMutation, type I as OutboxSink, type J as PersistedMutation, type P as Preloaded, type K as ReplayCredential, type N as ReplayIdentityVerdict, type T as RowOp, type V as RpcEnvelope, type W as RpcResponseBody, type X as ScheduleRecord, type Y as ScheduleRetryPolicy, type Z as SchedulerPoolStatus, type _ as SchedulerStatus, type $ as ServerMessage, type a0 as ServerPokeEndMessage, type a1 as ServerPokePartMessage, type a2 as ServerPokeStartMessage, type a3 as ShardTrafficEntry, type a4 as ShardTrafficResult, type a5 as StorageListPage, type a6 as StorageObject, type a7 as StoredQuery, type a8 as StreamHandle, type a9 as SubscriptionCallback, type b as SubscriptionErrorCallback, aa as SubscriptionRegistry, type ab as SubscriptionState, type ac as SyncWatermark, type a as Unsubscribe, type U as User, type ad as WorkflowInstanceAction, type ae as WorkflowInstanceDetail, type af as WorkflowInstancePage, type ag as WorkflowInstanceStatus, type ah as WorkflowInstanceSummary, type ai as WorkflowStepDetail, type aj as WsTokenProvider, ak as createClientQuery, al as createLocalStore, am as createStream } from "./packem_shared/lunora-client.d-
|
|
1
|
+
import { R as ReconnectOptions, c as PersistenceAdapter, Q as QueryCacheAdapter, B as BookmarkStorage, C as ConnectionStatus, S as SubscriptionError, H as HttpStreamRef, d as HttpStreamArgsOf, e as HttpStreamChunkOf, f as StreamIterable, O as OfflineQueueOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-YjgrrB49.js";
|
|
2
|
+
export { type A as ActionCallOptions, type g as BatchSlot, type h as CachedQuery, type i as ClientDebugShard, type j as ClientDebugSnapshot, type k as ClientDebugSubscription, type l as ClientMessage, type m as ClientQueryRef, type n as ClientShapeSubscribeMessage, type o as ClientShapeUnsubscribeMessage, D as DEFAULT_MAX_BUFFER, type F as FunctionArgumentDescriptor, type p as FunctionDescriptor, type G as GlobalFacetResult, type q as GlobalFacetValue, type r as GlobalFilterClause, type s as GlobalTableInfo, type t as GlobalTablePage, type u as HttpStreamCallArgs, type v as LunoraClientError, type w as LunoraClientOptions, type M as MutationCallOptions, type x as MutationSettledEvent, type y as OptimisticLocalStore, type z as OptimisticUpdate, type E as OutboxMutation, type I as OutboxSink, type J as PersistedMutation, type P as Preloaded, type K as ReplayCredential, type N as ReplayIdentityVerdict, type T as RowOp, type V as RpcEnvelope, type W as RpcResponseBody, type X as ScheduleRecord, type Y as ScheduleRetryPolicy, type Z as SchedulerPoolStatus, type _ as SchedulerStatus, type $ as ServerMessage, type a0 as ServerPokeEndMessage, type a1 as ServerPokePartMessage, type a2 as ServerPokeStartMessage, type a3 as ShardTrafficEntry, type a4 as ShardTrafficResult, type a5 as StorageListPage, type a6 as StorageObject, type a7 as StoredQuery, type a8 as StreamHandle, type a9 as SubscriptionCallback, type b as SubscriptionErrorCallback, aa as SubscriptionRegistry, type ab as SubscriptionState, type ac as SyncWatermark, type a as Unsubscribe, type U as User, type ad as WorkflowInstanceAction, type ae as WorkflowInstanceDetail, type af as WorkflowInstancePage, type ag as WorkflowInstanceStatus, type ah as WorkflowInstanceSummary, type ai as WorkflowStepDetail, type aj as WsTokenProvider, ak as createClientQuery, al as createLocalStore, am as createStream } from "./packem_shared/lunora-client.d-YjgrrB49.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-BTB4TAd_.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';
|
|
@@ -79,6 +79,20 @@ declare const getRetryAfterMs: (error: unknown) => number | undefined;
|
|
|
79
79
|
* write for the next attempt instead of dropping it.
|
|
80
80
|
*/
|
|
81
81
|
declare const isAuthReplayFailure: (error: unknown) => boolean;
|
|
82
|
+
/**
|
|
83
|
+
* Exponential backoff calculator with optional jitter.
|
|
84
|
+
*
|
|
85
|
+
* `next()` doubles the delay each call up to `maxDelayMs`. When `jitter` is
|
|
86
|
+
* enabled the returned value is randomized in `[delay/2, delay]` so a fleet
|
|
87
|
+
* of clients reconnecting at the same time spread out their retries.
|
|
88
|
+
*/
|
|
89
|
+
interface ReconnectCalculator {
|
|
90
|
+
/** Returns the delay to wait before the next reconnect attempt. */
|
|
91
|
+
next: () => number;
|
|
92
|
+
/** Resets the backoff to the initial delay (call on successful reconnect). */
|
|
93
|
+
reset: () => void;
|
|
94
|
+
}
|
|
95
|
+
declare const createReconnect: (options?: ReconnectOptions, random?: () => number) => ReconnectCalculator;
|
|
82
96
|
/**
|
|
83
97
|
* Optimistic-reconcile logic shared by every `@lunora/*` framework adapter's
|
|
84
98
|
* agent-chat surface (`@lunora/react` `useAgentChat`, plus the `@lunora/vue`,
|
|
@@ -905,20 +919,6 @@ interface IndexedDbQueryCacheOptions {
|
|
|
905
919
|
* environments should use {@link createInMemoryQueryCache}.
|
|
906
920
|
*/
|
|
907
921
|
declare const createIndexedDbQueryCache: (options?: IndexedDbQueryCacheOptions) => QueryCacheAdapter;
|
|
908
|
-
/**
|
|
909
|
-
* Exponential backoff calculator with optional jitter.
|
|
910
|
-
*
|
|
911
|
-
* `next()` doubles the delay each call up to `maxDelayMs`. When `jitter` is
|
|
912
|
-
* enabled the returned value is randomized in `[delay/2, delay]` so a fleet
|
|
913
|
-
* of clients reconnecting at the same time spread out their retries.
|
|
914
|
-
*/
|
|
915
|
-
interface ReconnectCalculator {
|
|
916
|
-
/** Returns the delay to wait before the next reconnect attempt. */
|
|
917
|
-
next: () => number;
|
|
918
|
-
/** Resets the backoff to the initial delay (call on successful reconnect). */
|
|
919
|
-
reset: () => void;
|
|
920
|
-
}
|
|
921
|
-
declare const createReconnect: (options?: ReconnectOptions, random?: () => number) => ReconnectCalculator;
|
|
922
922
|
/**
|
|
923
923
|
* Capture a snapshot of the current live query value at call time and produce a
|
|
924
924
|
* `() => boolean` precondition that compares it against the value at replay time.
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{RETIRE_AFTER_DURABLE_SEQ_ADVANCE as o,maxSeq as t,reconcileOptimistic as a}from"./packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs";import{createAsyncStoragePersistence as n}from"./packem_shared/createAsyncStoragePersistence-DXlhLrFv.mjs";import{createAsyncStorageQueryCache as i}from"./packem_shared/createAsyncStorageQueryCache-CAPNYhcK.mjs";import{default as f}from"./packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs";import{createCallRunner as x}from"./packem_shared/createCallRunner-Bwcrfh76.mjs";import{createClientQuery as l}from"./packem_shared/createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as d}from"./packem_shared/TabCoordinator-CXD7vulJ.mjs";import{a as R,i as C}from"./packem_shared/delta-merge-
|
|
1
|
+
import{RETIRE_AFTER_DURABLE_SEQ_ADVANCE as o,maxSeq as t,reconcileOptimistic as a}from"./packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs";import{createAsyncStoragePersistence as n}from"./packem_shared/createAsyncStoragePersistence-DXlhLrFv.mjs";import{createAsyncStorageQueryCache as i}from"./packem_shared/createAsyncStorageQueryCache-CAPNYhcK.mjs";import{default as f}from"./packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs";import{createCallRunner as x}from"./packem_shared/createCallRunner-Bwcrfh76.mjs";import{createClientQuery as l}from"./packem_shared/createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as d}from"./packem_shared/TabCoordinator-CXD7vulJ.mjs";import{a as R,i as C}from"./packem_shared/delta-merge-Cu-cN5Cb.mjs";import{CONFLICT_ERROR_CODE as S,TransportError as h,getErrorCode as D,getRetryAfterMs as Q,isAuthReplayFailure as _,isConflictError as F,isForbiddenError as I,isRateLimitedError as M,isUnauthorizedError as g}from"./packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as O}from"./packem_shared/httpStream-B5J3zeB8.mjs";import{c as b}from"./packem_shared/local-store-SJVMlM2Z.mjs";import{LunoraClient as U}from"./packem_shared/LunoraClient-BIzBh60k.mjs";import{createMutatorRunner as k}from"./packem_shared/createMutatorRunner-CuMRJpUx.mjs";import{O as N}from"./packem_shared/offline-queue-D_fr-uQ3.mjs";import{createInMemoryPersistence as K,createIndexedDbPersistence as V}from"./packem_shared/createInMemoryPersistence-Cz2W6XVj.mjs";import{preloadQuery as j,preloadedQueryResult as v}from"./packem_shared/preloadQuery-uFy24PCR.mjs";import{createInMemoryQueryCache as G,createIndexedDbQueryCache as H,queryCacheKey as J}from"./packem_shared/createInMemoryQueryCache-D2uNHLfM.mjs";import{createReconnect as Y}from"./packem_shared/createReconnect-CjTmjJDH.mjs";import{default as $}from"./packem_shared/createSnapshotPrecondition-D-WkMTIs.mjs";import{DEFAULT_MAX_BUFFER as re,createStream as oe}from"./packem_shared/DEFAULT_MAX_BUFFER-D3QH2iaq.mjs";import{SubscriptionRegistry as ae}from"./packem_shared/SubscriptionRegistry-5CHmk3d8.mjs";export{S as CONFLICT_ERROR_CODE,re as DEFAULT_MAX_BUFFER,U as LunoraClient,N as OfflineQueue,o as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,ae as SubscriptionRegistry,d as TabCoordinator,h as TransportError,R as applyDelta,n as createAsyncStoragePersistence,i as createAsyncStorageQueryCache,x as createCallRunner,l as createClientQuery,f as createInMemoryBookmarkStorage,K as createInMemoryPersistence,G as createInMemoryQueryCache,V as createIndexedDbPersistence,H as createIndexedDbQueryCache,b as createLocalStore,k as createMutatorRunner,Y as createReconnect,$ as createSnapshotPrecondition,oe as createStream,D as getErrorCode,Q as getRetryAfterMs,O as httpStream,_ as isAuthReplayFailure,F as isConflictError,I as isForbiddenError,C as isMutationDelta,M as isRateLimitedError,g as isUnauthorizedError,t as maxSeq,j as preloadQuery,v as preloadedQueryResult,J as queryCacheKey,a as reconcileOptimistic};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{t as Ae,a as M,d as g}from"./wire-codec-3Mj5UgNj.mjs";import{U as ie,i as _e,a as Ie,P as Re}from"./delta-merge-Cu-cN5Cb.mjs";import{s as re}from"./wire-key-3XBGlnux.mjs";import Oe from"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import{s as ee,r as Pe,e as N,a as Fe,b as ne,c as Me,d as ae}from"./wire-errors-8iZTTKRN.mjs";import{ClientQueryStore as Le}from"./createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as He}from"./TabCoordinator-CXD7vulJ.mjs";import{TransportError as H,getRetryAfterMs as Ue,AUTH_REPLAY_ERROR_CODES as Ne,isAuthReplayFailure as q}from"./CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as Be}from"./httpStream-B5J3zeB8.mjs";import{d as W,n as A,f as _,r as P,a as xe,c as De,b as Qe,e as Ke}from"./local-store-SJVMlM2Z.mjs";import{O as qe,n as oe,i as We,r as je}from"./offline-queue-D_fr-uQ3.mjs";import{resolvePersistenceAdapter as $e}from"./createInMemoryPersistence-Cz2W6XVj.mjs";import{resolveQueryCacheAdapter as Ge,queryCacheKey as I}from"./createInMemoryQueryCache-D2uNHLfM.mjs";import{createReconnect as ce}from"./createReconnect-CjTmjJDH.mjs";import Ve from"./createSnapshotPrecondition-D-WkMTIs.mjs";import{createStream as ze}from"./DEFAULT_MAX_BUFFER-D3QH2iaq.mjs";import{SubscriptionRegistry as C,wrapSubscriber as j,fanSubscriptionError as k}from"./SubscriptionRegistry-5CHmk3d8.mjs";const $=500,Ye=async o=>{const e=[];let t;for(;;){const s=await o(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}},he=(o,e)=>{if(o.size<e)return;const t=o.keys().next().value;t!==void 0&&o.delete(t)};new TextDecoder;const Je=new TextEncoder,Xe=o=>Ae(Je.encode(JSON.stringify(o))),Ze="x-lunora-expect-subject",et=o=>Xe({subject:o}),de=Symbol.for("lunora:session-change"),tt="lunora:session-change",st="better-auth.message",it="signout",Se=()=>{const o=globalThis;let e=o[de];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},o[de]=e),e},rt=()=>"document"in globalThis,nt=async()=>{const o=[];for(const e of Se().listeners)try{o.push(e())}catch{}await Promise.allSettled(o)},at=(o,e)=>{if(o!==st||e===null)return!1;try{const t=JSON.parse(e);return t?.event==="session"&&t.data?.trigger===it}catch{return!1}},ot=o=>{const e=[],t=()=>{nt().catch(()=>{})};let s;try{s=typeof BroadcastChannel=="function"?new BroadcastChannel(tt):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!==o&&t()}),e.push(()=>{r.close()})}const i=globalThis;if(typeof i.addEventListener=="function"){const r=a=>{at(a.key,a.newValue)&&t()};i.addEventListener("storage",r),e.push(()=>{i.removeEventListener?.("storage",r)})}return()=>{for(const r of e)r()}},ct=o=>{const e=Se();return e.listeners.add(o),e.detach===void 0&&rt()&&(e.detach=ot(e.tab)),()=>{e.listeners.delete(o),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},E=(o,e)=>{try{return M(o)}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)}},ue=o=>{try{return M(o),!0}catch{return!1}},be=o=>o!==null&&typeof o=="object"&&("error"in o||"result"in o),ht=(o,e)=>{const t=Array.from({length:e});for(const s of o){if(typeof s.id!="number"||s.id<0||s.id>=e)continue;if(!be(s.body)){t[s.id]={error:ee({}),ok:!1};continue}const i=s.body;t[s.id]="error"in i?{error:ee(i),ok:!1}:{ok:!0,value:g(i.result)}}return t.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},G=(o,e)=>e!==null?{}:o===null?{expectSubject:null}:o?.startsWith("subj:")===!0?{expectSubject:o.slice(5)}:{},dt="/_lunora/rpc",V="/_lunora/rpc-batch",ut="/_lunora/ws",lt="/_lunora/admin/shard-traffic",ft="/_lunora/admin/scheduled",pt="/_lunora/admin/scheduled/status",mt="/_lunora/admin/scheduled/ws",yt="/_lunora/admin/scheduled/cancel",le="/_lunora/admin/scheduled/dead",St="/_lunora/admin/scheduled/dead/retry",bt="/_lunora/admin/scheduled/dead/cancel",Tt="/_lunora/admin/workflows/instances",gt="/_lunora/admin/workflows/instance",vt="/_lunora/admin/workflows/status",z="/_lunora/admin/storage",Ct="/_lunora/admin/storage/url",kt="/_lunora/admin/storage/buckets",Et="/_lunora/admin/functions",wt="/_lunora/admin/cron-jobs",At="/_lunora/admin/cron-jobs/run",_t="/_lunora/admin/architecture",It="/_lunora/admin/openapi",Rt="/_lunora/admin/openrpc",Ot="/_lunora/admin/global/tables",Pt="/_lunora/admin/global/table",Ft="/_lunora/admin/global/facet",Mt="/_lunora/admin/vector/indexes",Lt="/_lunora/admin/vector/query",Ht="/_lunora/admin/logs/archive",Ut="/_lunora/admin/kv/namespaces",Nt="/_lunora/admin/kv/keys",Y="/_lunora/admin/kv/value",Bt="/_lunora/admin/auth/users",xt="/_lunora/admin/auth/sessions",Dt="/_lunora/admin/auth/users/create",Qt="/_lunora/admin/auth/users/role",Kt="/_lunora/admin/auth/users/ban",qt="/_lunora/admin/auth/users/unban",Wt="/_lunora/admin/auth/users/password",jt="/_lunora/admin/auth/users/remove",$t="/_lunora/admin/auth/users/impersonate",Gt="/_lunora/admin/auth/sessions/revoke",Vt="/_lunora/admin/auth/sessions/revoke-all",zt="/_lunora/admin/auth/capabilities",Yt="/_lunora/admin/auth/users/update",Jt="/_lunora/admin/auth/accounts",Xt="/_lunora/admin/auth/accounts/unlink",Zt="/_lunora/admin/auth/passkeys",es="/_lunora/admin/auth/passkeys/delete",ts="/_lunora/admin/auth/two-factor/disable",ss="/_lunora/admin/auth/organizations",is="/_lunora/admin/auth/organizations/members",rs="/_lunora/admin/auth/organizations/invitations",ns="/_lunora/admin/auth/organizations/members/remove",as="/_lunora/admin/auth/organizations/invitations/cancel",os="/_lunora/admin/auth/config",cs="/_lunora/admin/auth/sign-up-invitations",hs="/_lunora/admin/auth/sign-up-invitations/create",ds="/_lunora/admin/auth/sign-up-invitations/revoke",us="/_lunora/admin/auth/organizations/create",ls="/_lunora/admin/auth/organizations/update",fs="/_lunora/admin/auth/organizations/remove",ps="/_lunora/admin/auth/organizations/members/add",ms="/_lunora/admin/auth/organizations/members/invite",ys="/_lunora/admin/auth/organizations/members/role",Ss="/_lunora/admin/auth/organizations/teams",bs="/_lunora/admin/auth/organizations/teams/create",Ts="/_lunora/admin/auth/organizations/teams/update",gs="/_lunora/admin/auth/organizations/teams/remove",vs="/_lunora/admin/auth/organizations/teams/members",Cs="/_lunora/admin/auth/organizations/teams/members/add",ks="/_lunora/admin/auth/organizations/teams/members/remove",Es="/_lunora/admin/auth/organizations/roles",ws="/_lunora/admin/auth/organizations/roles/create",As="/_lunora/admin/auth/organizations/roles/update",_s="/_lunora/admin/auth/organizations/roles/remove",Is="/api/auth",Rs="/get-session",Os="lunora-ping",Ps=3e4,Fs=1e4,Ms=5e3,Ls=3,Hs=250,Us=5e3,Ns=5e3,Bs=64,xs=3,Ds=1e4,Qs=8,J=o=>o===void 0||o===""?"":`&bucket=${encodeURIComponent(o)}`,fe=o=>o.startsWith("https://")?`wss://${o.slice(8)}`:o.startsWith("http://")?`ws://${o.slice(7)}`:o,w=(o,e)=>`${o.endsWith("/")?o.slice(0,-1):o}${e}`,S=(o,e)=>{const t=new URLSearchParams;for(const[i,r]of Object.entries(e))r!==void 0&&r!==""&&t.set(i,String(r));const s=t.toString();return s===""?o:`${o}?${s}`},X=o=>o==="connected"||o==="polling",l=o=>o??"",T=(o,e)=>{if(!o.socket||o.wsState!=="open")return!1;try{return o.socket.send(JSON.stringify(e)),!0}catch{return!1}},Ks=o=>{if(!o.pendingStreams||o.pendingStreams.length===0)return;const e=o.pendingStreams;o.pendingStreams=[];for(const t of e)T(o,t)},qs=new TextDecoder,Ws=o=>{if(typeof o=="string")return o;if(o instanceof ArrayBuffer)return qs.decode(o)};class R{listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){const[t]=e;for(const s of this.listeners)try{s(t)}catch{}}clear(){this.listeners.clear()}}const L=o=>{o.heartbeatTimer!==void 0&&(clearInterval(o.heartbeatTimer),o.heartbeatTimer=void 0)},js=(o,e,t)=>{L(o),!(e<=0)&&(o.heartbeatTimer=setInterval(()=>{if(!o.socket)return;const{socket:s}=o;if(Date.now()-o.lastFrameAt>e*2.5){try{s.close()}catch{}t();return}try{s.send(Os)}catch{}},e))},pe=(o,e,t,s)=>{const{WebSocketImpl:i,connectTimeoutMs:r,heartbeatIntervalMs:a}=t;if(i===void 0)throw new y("INTERNAL","no WebSocket implementation available");const n=new i(e);o.socket=n;const c=()=>{L(o),o.connectTimer!==void 0&&(clearTimeout(o.connectTimer),o.connectTimer=void 0),o.socket===n&&(o.socket=void 0)},h=d=>{c(),s.onClose(d)};r>0&&(o.connectTimer=setTimeout(()=>{if(o.connectTimer=void 0,o.socket===n){try{n.close()}catch{}h()}},r)),n.addEventListener("open",()=>{if(o.socket===n){o.connectTimer!==void 0&&(clearTimeout(o.connectTimer),o.connectTimer=void 0),o.lastFrameAt=Date.now();try{s.onOpen?.()}catch(d){console.error("[lunora] connection open handler threw",d)}js(o,a,h)}}),n.addEventListener("message",d=>{if(o.socket===n){o.lastFrameAt=Date.now();try{s.onMessage(d)}catch(u){console.error("[lunora] server frame handler threw",u)}}}),n.addEventListener("close",d=>{o.socket===n&&h(d)}),n.addEventListener("error",()=>{o.socket===n&&h()})},$s=o=>{const{afterFailedAttempts:e,intervalMs:t,onReachable:s,onStateChange:i,poll:r}=o,a=t>0&&e>0;let n=0,c,h=!1,d=!1;const u=()=>{c!==void 0&&(clearInterval(c),c=void 0,h=!1,i())},f=p=>{if(c!==void 0){if(!p){u();return}h||(h=!0,i()),s()}},m=()=>{d||(d=!0,r().then(f).finally(()=>{d=!1}).catch(()=>{}))};return{isPolling:()=>c!==void 0&&h,noteFailedOpen:()=>{n+=1,!(!a||c!==void 0||n<e)&&(c=setInterval(m,t),i(),m())},noteOpen:()=>{n=0,u()},stop:u}},Gs=1e4,me=async o=>{const e=new AbortController;let t;const s=new Promise((i,r)=>{t=setTimeout(()=>{e.abort(),r(new TypeError("LunoraClient: poll timed out"))},Gs)});try{return await Promise.race([o(e.signal),s])}catch(i){throw e.signal.aborted?new TypeError("LunoraClient: poll timed out"):i}finally{clearTimeout(t)}},Te=new Set(["RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Vs=o=>{if(o instanceof H)return!0;const e=o?.code;return e===void 0||Te.has(e)||Ne.has(e)},ge=6e4,zs=1e3,Ys={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},F=(o,e,t)=>{const s=Pe(t),i=s===void 0?void 0:{retryAfterMs:s},r=`LunoraClient: response carried no error envelope (status ${o.toString()}${e?` ${e}`:""})`;return o<400||o>=500||o===408?new H(r,i):new y(Ys[o]??"BAD_REQUEST",r,{data:i})},te=(o,e=Math.random)=>{const t=Math.min(zs*2**Math.max(o-1,0),ge);return Math.round(t*(.5+e()*.5))},Js=o=>o instanceof H||Te.has(o?.code??""),Xs=(o,e,t)=>{const s=Ue(o);return s!==void 0&&s>0?Math.min(s,ge):Js(o)?te(e,t):void 0},Zs=983040,ei=o=>typeof TextEncoder>"u"?o.length:new TextEncoder().encode(o).length,ve=new WeakSet,ye=o=>{const e=new y("WIRE_DECODE_FAILED",`LunoraClient: the call succeeded but its result could not be decoded (a mutation has still committed) — ${o instanceof Error?o.message:String(o)}`,{cause:o});return ve.add(e),e},B=o=>o instanceof Error&&ve.has(o),ti=(o,e)=>{for(const t of e)t.op==="delete"?o.delete(t.key):t.value!==void 0&&o.set(t.key,t.value)},si=(o,e,t)=>o!==null||e&&t===null,ii=[Re],Z=o=>"args"in o?{...o,args:g(o.args)}:o,ri=Promise.resolve();class Ce{static MAX_POKE_BUFFERS=256;static createClientQuery(e,t){return{defaultValue:t,key:e}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new C;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;idleClosedShards=new Set;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;subjectToken=null;sessionProbesInFlight=0;sessionProbeGeneration=0;identityQuestions=0;identityAnsweredAt=0;releaseSessionChangeListener;warnedIdentityDisagreement=!1;identityResolutionExpected=!1;identitySettled=!1;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new R;statusListeners=new R;tokenExpiredListeners=new R;identityChangeListeners=new R;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new R;pendingChangeListeners=new R;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??w(fe(e.url),ut),this.wsToken=e.wsToken;const t=e.authBasePath??Is;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??Oe(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??Ps,this.connectTimeoutMs=e.connectTimeoutMs??Fs,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??Ms,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??Ls,this.defaultConnectionContext=e.connectionContext,this.persistence=$e(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Ge(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new Le,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=ri),this.offlineQueue=new qe(e.offlineQueue,{onEvict:(s,i)=>{this.emitItemSettled(s,"rejected",i),this.releaseIdleShard(s.shardKey)},onSizeChange:s=>{this.pendingChangeListeners.emit(s)},persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${oe()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=ct(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(),n=this.isKnownNobody(),c=this.authToken;this.authToken=e,this.applySubject(e,t);const h=this.identityFingerprint();h!==i&&(!s&&e!==null&&r?(this.restampQueuedIdentity(i,h),this.restampWatermarks(i,h),this.restampConnectionIdentity(i,h),this.reseedFromHydratedCache()):!s&&e===null&&i===null&&r&&!n?(this.restampWatermarks(i,h),this.restampConnectionIdentity(i,h),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(i),this.warnRefreshWithoutSubject(c,e),si(i,n,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(a),s&&this.authTokenListeners.emit(e),(h!==i||s||a)&&this.offlineQueue.size>0&&X(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 y("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);const r=s?.shardKey??"",a=this.identityFingerprint();let n,c,h;try{c=await this.rpc(e,t,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:u=>{n=u}})}catch(u){if(!B(u))throw u;h=u}if(n!==void 0&&n>(this.clientWatermarks.get(a??"")?.get(r)??0)){let u=this.clientWatermarks.get(a??"");u===void 0&&(he(this.clientWatermarks,Qs),u=new Map,this.clientWatermarks.set(a??"",u)),u.set(r,n)}if(h!==void 0)throw h;return{applied:n===void 0||n===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}${Rs}`),{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.bounceShardSockets())}setConnectionContext(e,t={}){this.assertLeaderOwnedSurface("setConnectionContext");const s=l(t.shardKey);e===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,e),this.refreshConnectionContext(s),e===void 0&&this.releaseIdleShard(t.shardKey)}acquireConnectionContext(e,t={}){if(this.followsAnotherTab())return()=>{};const s=l(t.shardKey),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 n=this.connectionContextHolders.get(s);if(!n)return;const c=n.indexOf(i);c!==-1&&n.splice(c,1),n.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s),this.releaseIdleShard(t.shardKey)}}whisperSubscribe(e,t,s={}){this.assertLeaderOwnedSurface("whisperSubscribe");const i=l(s.shardKey);let r=this.whisperHandlers.get(i);r||(r=new Map,this.whisperHandlers.set(i,r));let a=r.get(e);const n=a===void 0;if(a||(a=new Set,r.set(e,a)),a.add(t),this.ensureSocket(s.shardKey),n){const c=this.getConnection(s.shardKey);c&&T(c,{topic:e,type:"whisper_subscribe"})}return()=>{const c=this.whisperHandlers.get(i),h=c?.get(e);if(!h?.delete(t)||h.size>0)return;c?.delete(e),c?.size===0&&this.whisperHandlers.delete(i);const d=this.getConnection(s.shardKey);d&&T(d,{topic:e,type:"whisper_unsubscribe"}),this.releaseIdleShard(s.shardKey)}}whisper(e,t,s={}){this.assertLeaderOwnedSurface("whisper"),this.ensureSocket(s.shardKey);const i=this.getConnection(s.shardKey);i&&T(i,{data:E(t??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"}),this.releaseIdleShard(s.shardKey)}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){const t=this.statusListeners.add(e);return e(this.computeStatus()),t}pendingCount(){return this.offlineQueue.size}debug(){const e=[],t=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...t?.keys()??[]]);for(const 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.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.serverCursor!==void 0,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(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,t){this.clientQueryStore.set(e,t)}subscribeClientQuery(e,t){return this.clientQueryStore.subscribe(e,t)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,t,s){return Ve(this,e,t,s)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,t,s){if(!this.readyResolved)return;const i=re(t),r=I(e,i,s),a=this.hydratedQueryCache.get(r);if(a!==void 0)return this.cachedQueryMatchesIdentity(a)?a.value:void 0}peekActiveQuerySnapshot(e,t,s){const i=C.key(e,t,s),r=this.subscriptions.get(i);return{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})}async batch(e){return this.sendBatch(e)}async mutation(e,t,s={}){const{value:i}=await this.runMutation(e,t,s);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})}async importRows(e,t,s={}){this.assertOpen();const i=Math.max(1,Math.trunc(s.chunkSize??500)),r=s.toArgs??(d=>({rows:d})),a=t.length;let n=0,c=0,h=0;for(let d=0;d<a;d+=i){const u=t.slice(d,d+i),f=h,{committed:m}=await this.runMutation(e,r(u),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(f)}`},shardKey:s.shardKey});h+=1,n+=u.length,m&&(c+=u.length),s.onProgress?.({done:n,total:a})}return{chunks:h,imported:c,queued:n-c}}async shardTraffic(e){this.assertOpen();const t=await this.adminFetch(lt,"POST",{table:e});return{failed:t.failed??0,ok:t.ok??0,shards:t.shards??[]}}async listScheduledJobs(){return this.assertOpen(),((await this.adminFetch(ft,"GET")).records??[]).map(t=>Z(t))}async schedulerStatus(){this.assertOpen();const e=await this.adminFetch(pt,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}}async cancelScheduledJob(e){return this.assertOpen(),{cancelled:(await this.adminFetch(yt,"POST",{id:e})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await Ye(async t=>await this.adminFetch(t===void 0?le:`${le}?cursor=${encodeURIComponent(t)}`,"GET"))).map(t=>Z(t))}async retryDeadJob(e){return this.assertOpen(),{retried:(await this.adminFetch(St,"POST",{id:e})).retried===!0}}async removeDeadJob(e){return this.assertOpen(),{removed:(await this.adminFetch(bt,"POST",{id:e})).removed===!0}}async listWorkflowInstances(e){this.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 this.adminFetch(`${Tt}?${t.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}}async getWorkflowInstance(e){this.assertOpen();const t=new URLSearchParams({id:e.id,name:e.name}),s=await this.adminFetch(`${gt}?${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??[]}}async setWorkflowInstanceStatus(e){return this.assertOpen(),{status:(await this.adminFetch(vt,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const t=w(fe(this.url),mt),s=ce(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let r,a=!1;const n=()=>{a||this.closed||(r=setTimeout(d,s.next()))},c=f=>{if(a||this.WebSocketImpl===void 0)return;const m=f===void 0?t:`${t}?token=${encodeURIComponent(f)}`;pe(i,m,this.managedSocketOptions,{onClose:()=>{n()},onMessage:p=>{let b;try{b=JSON.parse(typeof p.data=="string"?p.data:"")}catch{return}b.type==="jobs"&&Array.isArray(b.records)&&(s.reset(),e(b.records.map(v=>Z(v))))}})},h=async f=>{let m;try{m=await f()}catch{n();return}c(m)},d=()=>{if(a||this.WebSocketImpl===void 0)return;const{wsToken:f}=this;if(typeof f=="function"){h(f).catch(()=>{});return}c(f)};d();const u=()=>{a=!0,r!==void 0&&(clearTimeout(r),r=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),L(i),i.socket?.close(),i.socket=void 0};return this.adminSocketTeardowns.add(u),()=>{this.adminSocketTeardowns.delete(u),u()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(Et,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(wt,"GET")).jobs??[]}async runCronJob(e){this.assertOpen();const t=await this.adminFetch(At,"POST",{name:e});return{name:t.name??e,ran:t.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(It,"GET")}async fetchArchitecture(){return this.assertOpen(),await this.adminFetch(_t,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(Rt,"GET")}async listStorageObjects(e={}){this.assertOpen();const t=S(z,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await this.adminFetch(t,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(e,t){this.assertOpen();const s=`${z}?key=${encodeURIComponent(e)}${J(t?.bucket)}`,i=await this.adminFetch(s,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(kt,"GET")).buckets??[]}async uploadStorageObject(e){this.assertOpen();const t=`${z}?key=${encodeURIComponent(e.key)}${J(e.bucket)}`,s=await this.adminFetch(t,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}}async signedStorageUrl(e,t){this.assertOpen();const s=t?.expiresInSeconds,i=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,r=`${Ct}?key=${encodeURIComponent(e)}${i}${J(t?.bucket)}`,a=await this.adminFetch(r,"GET");if(typeof a.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return a.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(Ot,"GET")}async readGlobalTablePage(e){this.assertOpen();const t=new URLSearchParams({table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(M(e.filters))),g(await this.adminFetch(`${Pt}?${t.toString()}`,"GET"))}async facetGlobalColumn(e){this.assertOpen();const t=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(M(e.filters))),g(await this.adminFetch(`${Ft}?${t.toString()}`,"GET"))}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch(Mt,"GET")).indexes??[]}async queryVectorIndex(e){return this.assertOpen(),(await this.adminFetch(Lt,"POST",e)).matches??[]}async queryLogArchive(e={}){this.assertOpen();const t=await this.adminFetch(Ht,"POST",e);return{nextCursor:t.nextCursor,rows:t.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(Ut,"GET")).namespaces??[]}async listKvKeys(e){this.assertOpen();const t=S(Nt,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await this.adminFetch(t,"GET")}async getKvValue(e){this.assertOpen();const t=S(Y,{key:e.key,namespace:e.namespace});return await this.adminFetch(t,"GET")}async putKvValue(e){this.assertOpen(),await this.adminFetch(Y,"PUT",e)}async deleteKvKey(e){this.assertOpen();const t=S(Y,{key:e.key,namespace:e.namespace});await this.adminFetch(t,"DELETE")}async listAuthUsers(e={}){this.assertOpen();const t=S(Bt,{filterField:e.filterField,filterValue:e.filterValue,limit:e.limit,offset:e.offset,search:e.search,searchField:e.searchField,sortBy:e.sortBy,sortDirection:e.sortDirection});return await this.adminFetch(t,"GET")}async createAuthUser(e){return await this.adminFetch(Dt,"POST",e)}async setAuthUserRole(e){return await this.adminFetch(Qt,"POST",e)}async banAuthUser(e){return await this.adminFetch(Kt,"POST",e)}async unbanAuthUser(e){return await this.adminFetch(qt,"POST",e)}async setAuthUserPassword(e){await this.adminFetch(Wt,"POST",e)}async removeAuthUser(e){await this.adminFetch(jt,"POST",e)}async impersonateAuthUser(e){return await this.adminFetch($t,"POST",e)}async revokeAuthSession(e){await this.adminFetch(Gt,"POST",e)}async revokeAuthUserSessions(e){await this.adminFetch(Vt,"POST",e)}async getAuthCapabilities(){return await this.adminFetch(zt,"GET")}async updateAuthUser(e){return await this.adminFetch(Yt,"POST",e)}async listAuthAccounts(e){return await this.adminFetch(S(Jt,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){await this.adminFetch(Xt,"POST",e)}async listAuthPasskeys(e){return await this.adminFetch(S(Zt,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){await this.adminFetch(es,"POST",e)}async disableAuthTwoFactor(e){await this.adminFetch(ts,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(S(ss,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){const t=S(is,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthOrgInvitations(e){const t=S(rs,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthSignUpInvitations(e={}){const t=S(cs,{limit:e.limit,offset:e.offset});return await this.adminFetch(t,"GET")}async createAuthSignUpInvitation(e){return await this.adminFetch(hs,"POST",e)}async revokeAuthSignUpInvitation(e){await this.adminFetch(ds,"POST",e)}async removeAuthOrgMember(e){await this.adminFetch(ns,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(as,"POST",e)}async getAuthConfig(){return await this.adminFetch(os,"GET")}async createAuthOrganization(e){return await this.adminFetch(us,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(ls,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(fs,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch(ps,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(ms,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch(ys,"POST",e)}async listAuthOrgTeams(e){const t=S(Ss,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(bs,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch(Ts,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(gs,"POST",e)}async listAuthOrgTeamMembers(e){const t=S(vs,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(t,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(Cs,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(ks,"POST",e)}async listAuthOrgRoles(e){const t=S(Es,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgRole(e){return await this.adminFetch(ws,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(As,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(_s,"POST",e)}async listAuthSessions(e={}){this.assertOpen();const t=S(xt,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(t,"GET")}subscribe(e,t,s,i={}){this.assertOpen();const r=t??{},a=C.key(e.__lunoraRef,r,i.shardKey);let n=this.subscriptions.get(a);const c=j(s),h=j(i.onError),d=j(i.onCheckpoint);if(!n){this.nextSubId+=1;const f=`sub_${this.nextSubId.toString()}`,m=re(r),p=this.takeHydratedCache(e.__lunoraRef,m,i.shardKey);n={acked:!1,args:r,argsKey:m,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:f,lastValue:p?.value,optimisticLayers:[],serverBase:p?.value,serverCursor:p?.serverCursor,shardKey:i.shardKey,wireArgs:E(r,`args for '${e.__lunoraRef}'`),...p?.serverEpoch===void 0?{}:{serverEpoch:p.serverEpoch}},this.subscriptions.add(n),p!==void 0&&this.cacheSeededQueries.set(a,p)}if(n.callbacks.add(c),h&&n.errorCallbacks.add(h),d&&n.checkpointCallbacks.add(d),n.lastValue!==void 0)try{c(n.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(n);const u=n;return()=>{u.callbacks.delete(c),h&&u.errorCallbacks.delete(h),d&&u.checkpointCallbacks.delete(d),u.callbacks.size===0&&(this.sendOrQueueUnsubscribe(u.shardKey,u.id,"unsubscribe"),this.returnCacheSeed(C.keyOf(u)),this.subscriptions.remove(u),this.releaseIdleShard(u.shardKey))}}subscribeShape(e,t,s={}){if(this.assertOpen(),this.followsAnotherTab()){const{onError:a}=s;return a!==void 0&&queueMicrotask(()=>{a({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;const i=`shape_${this.nextShapeId.toString()}`,r={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.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(r),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(r.shardKey,i,"shape_unsubscribe"),this.releaseIdleShard(r.shardKey)}}stream(e,t,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new y("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;const i=`stream_${this.nextStreamId.toString()}`,{shardKey:r}=s,a=t??{},{handle:n,iterable:c}=ze({maxBuffer:s.maxBuffer,onCancel:()=>{this.cancelStream(i,r)}});this.ensureSocket(r);const h=this.getConnection(r),d={id:i,query:{args:E(a,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:r},type:"stream"},u={durable:s.durable===!0,generation:void 0,handle:n,lastSeq:0,message:d,shardKey:r};this.streams.set(i,u);const f=h?.wsState==="open"&&T(h,d);if(!f&&h===void 0)return this.forgetStream(i),n.fail(new y("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),c;if(!f){for(h.pendingStreams=h.pendingStreams??[];h.pendingStreams.length>=Bs;){const p=h.pendingStreams.shift()?.id,b=p?this.streams.get(p):void 0;b&&(b.handle.fail(new y("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(p))}h.pendingStreams.push(d)}return c}httpStream(e,t,s={}){if(this.closed)throw new y("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");const i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return Be(e,t,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const e of this.streams.values())e.handle.fail(new y("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(const e of this.connections.values())this.teardownConnection(e);for(const e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear();for(const e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new y("INTERNAL","LunoraClient is closed")}followsAnotherTab(){const e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;const t=e.leaderTabId;return t!==void 0&&t!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new y("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}shardInUse(e){const t=s=>l(s)===e;return this.subscriptions.all().some(s=>t(s.shardKey))||[...this.shapeSubscriptions.values()].some(s=>t(s.shardKey))||[...this.streams.values()].some(s=>t(s.shardKey))||this.whisperHandlers.has(e)||this.connectionContexts.has(e)||this.connectionContextHolders.has(e)||this.offlineFlushes.has(e)||this.offlineQueue.hasPending(s=>t(s.shardKey))}releaseIdleShard(e){const t=l(e),s=this.connections.get(t);this.closed||t===""||s===void 0||(clearTimeout(s.idleTimer),s.idleTimer=setTimeout(()=>{s.idleTimer=void 0,!(this.closed||this.connections.get(t)!==s||this.shardInUse(t))&&(s.wasEverConnected&&this.idleClosedShards.add(t),this.teardownConnection(s),this.connections.delete(t),this.emitConnectionStatus())},Ns))}forgetStream(e){const t=this.streams.get(e);this.streams.delete(e),t&&this.releaseIdleShard(t.shardKey)}teardownConnection(e){e.polling.stop();const t=l(e.shardKey);for(const[i,r]of this.streams)l(r.shardKey)===t&&(r.handle.fail(new y("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(i));e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.clearResubscribeQueue(e),this.clearConnectionTimers(e),clearTimeout(e.idleTimer),e.idleTimer=void 0,L(e);const{socket:s}=e;if(s){e.socket=void 0;try{s.close()}catch{}}e.wsState="closed"}createTabCoordinator(){const e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new He({channelName:e,onBecomeLeader:()=>{for(const t of this.subscriptions.all())this.ensureSocket(t.shardKey),this.queueResubscribe(t);for(const t of this.queuedOfflineShardKeys)this.ensureSocket(t);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},onStopBeingLeader:()=>{for(const[t,s]of this.connections)this.teardownConnection(s),this.connections.delete(t);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},onConnectionStatus:(t,s)=>{if(s!==void 0&&s!==this.identityFingerprint())return;const i=t==="connected"&&this.leaderStatus!=="connected"||t==="polling"&&this.leaderStatus!=="connected"&&this.leaderStatus!=="polling";this.leaderStatus=t,t==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),i&&this.flushAllOfflineQueues()},onSubscriptionData:(t,s,i,r,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;const n=this.subscriptions.get(t);n&&(n.serverBase=s,this.dropCacheSeed(t),i!==void 0&&(n.serverCursor=i,r!==void 0&&(n.serverEpoch=r),W(n,i)),A(n,_(s,n.optimisticLayers)))},onLeaderClaimAnswered:()=>{this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},onSubscriptionError:(t,s,i)=>{if(i!==void 0&&i!==this.identityFingerprint())return;const r=this.subscriptions.get(t);r&&k(r.errorCallbacks,s)},onSubscriptionSettled:(t,s,i,r,a,n)=>{if(n!==void 0&&n!==this.identityFingerprint())return;const c=this.subscriptions.get(t);if(c){this.ackAndAdvanceCursor(c,s,i),r!==void 0&&a===this.clientId&&(c.lastMutationId=Math.max(c.lastMutationId??0,r));for(const h of c.checkpointCallbacks)h({checkpoint:c.serverCursor,mutationId:c.lastMutationId})}}})}async sendBatch(e,t){if(this.assertOpen(),!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];const s=await this.fetchImpl(w(this.url,V),{body:JSON.stringify({calls:e.map((n,c)=>({args:E(n.args??{},`args for batch call '${n.fn.__lunoraRef}'`),functionPath:n.fn.__lunoraRef,id:c,shardKey:n.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 new y("INTERNAL",`LunoraClient: batch response was not JSON (status ${s.status.toString()})`)}const a=N(r);if(!s.ok||a!==void 0&&!r.results)throw a!==void 0?Fe(a):new y("INTERNAL",`LunoraClient: batch request failed (status ${s.status.toString()})`);for(const n of r.results??[]){const c=n.body?.commitCursor;typeof n.id=="number"&&typeof c=="number"&&this.recordShardCursor(e[n.id]?.shardKey,c)}return ht(r.results??[],e.length)}async runMutation(e,t,s){this.assertOpen();const i=t,r=s.mutationId??oe(),a=this.takeReplayCredential(s.replayCredential),n=s.replayBaseline===void 0?this.baselineCursorFor(s.shardKey):s.replayBaseline??void 0,{confirms:c,rollbacks:h}=this.applyOptimisticUpdates(e.__lunoraRef,i,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,t,s.shardKey,h,c);const d=this.offlineFlushes.get(l(s.shardKey));d!==void 0&&await d;const{hasSocket:u,idleClosed:f,polling:m,wasEverConnected:p,wsState:b}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:v}=this.offlineQueue,U=p||v,x=this.WebSocketImpl!==void 0&&U,D=m||f,ke=b==="connecting"&&U&&!D,Ee=b!=="open"&&!u&&x&&!D,we=x&&s.replayBaseline===void 0&&this.hasPendingWriteAhead(s.shardKey),se=async()=>this.enqueueOfflineMutation(e,i,s.shardKey,n,r,h,c,s.precondition,s.mutationId,a?.stamp);if(Ee||ke||we)return se();let Q;try{const O=await this.rpc(e.__lunoraRef,i,s.shardKey,{baselineSeq:n,captureBookmark:!0,...a?.flags,mutationId:r,onCommitCursor:K=>{Q=K}});for(const K of c)K(Q);return{committed:!0,value:O}}catch(O){if(D&&x&&O instanceof TypeError&&ue(i))return se();throw this.settleFailedDirectWrite(O,Q,c,h,a?.flags.authToken),O}}settleFailedDirectWrite(e,t,s,i,r){if(this.noteIdentityMismatch(e),r!==void 0&&this.noteReplayAuthRefusal(e,r),B(e)){for(const a of s)a(t);return}P(i)}async enqueueOfflineMutation(e,t,s,i,r,a,n,c,h,d){const u=d===void 0?this.identityFingerprint():d;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:h??`${this.clientId}:${String(m)}`,identity:u,mutationId:m,...a.length>0&&{onRejected:()=>{P(a)}},shardKey:s})}catch(p){throw P(a),p instanceof Error?p:new Error(String(p))}for(const p of n)p(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((m,p)=>{const b={args:t,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:r,clientId:this.clientId,identity:u,precondition:c,onCommit:v=>{for(const U of n)U(v)},reject:v=>{this.queuedIdentities.delete(r),B(v)||P(a),p(v instanceof Error?v:new Error(String(v))),this.releaseIdleShard(s)},resolve:m,shardKey:s};this.offlineQueue.enqueue(b),this.queuedOfflineShardKeys.add(s),this.ensureSocket(s),b.id!==void 0&&this.queuedIdentities.set(b.id,u)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;const t=l(e);return this.offlineQueue.hasPending(s=>l(s.shardKey)===t)}async hydratePersistedQueue(){try{const e=await this.offlineQueue.hydrate();for(const t of e)this.queuedOfflineShardKeys.add(t),this.ensureSocket(t)}catch{}}hydrateAsOutboxLeader(){const e=()=>{this.hydratePersistedQueue().catch(()=>{})},t=globalThis.navigator?.locks;if(!t){e();return}t.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{const e=await this.queryCache.load(),t=new Map;for(const s of this.subscriptions.all())t.set(I(s.fn.__lunoraRef,s.argsKey,s.shardKey),s);for(const{key:s,...i}of e){if(We(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(I(e.fn.__lunoraRef,e.argsKey,e.shardKey),t),A(e,_(t.value,e.optimisticLayers)))}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,A(s,_(void 0,s.optimisticLayers))),this.hydratedQueryCache.set(e,t)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,t,s){const i=I(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=I(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=I(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(()=>{})},Hs))}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)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";const e=[...this.connections.values()];return e.length===0?"idle":e.some(t=>t.wsState==="open")?"connected":e.some(t=>t.polling.isPolling())?"polling":e.some(t=>t.wsState==="connecting")?"connecting":"offline"}baselineCursorFor(e){const t=l(e);let s;for(const i of this.subscriptions.all())l(i.shardKey)!==t||i.serverCursor===void 0||(s=s===void 0?i.serverCursor:Math.max(s,i.serverCursor));return s}async pollSubscriptions(e){const t=l(e),s=[];for(const n of this.subscriptions.all())l(n.shardKey)===t&&(ue(n.args)?s.push(n):k(n.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=Ke(),r=this.identityFingerprint();let a;try{a=await me(async n=>this.sendBatch(s.map(c=>({args:c.args,fn:c.fn,shardKey:c.shardKey})),n))}catch(n){return!(n instanceof TypeError)}if(this.identityFingerprint()!==r)return!0;for(const[n,c]of s.entries()){const h=a[n];if(h!==void 0){if(!h.ok){k(c.errorCallbacks,{code:h.error.code,message:h.error.message});continue}this.handleDataMessage({data:M(h.value),id:c.id,type:"data"},i)}}return!0}async probeOrigin(){const{fetchImpl:e}=this;if(!e)return!1;try{return await me(async t=>e(w(this.url,V),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:t})),!0}catch{return!1}}emitConnectionStatus(){const e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,t,s){this.mutationSettledListeners.emit({args:e.args,code:s===void 0?void 0:s.code,error:s,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:t})}applyOptimisticUpdates(e,t,s,i){const r=[],a=[];if(!i)return{confirms:r,rollbacks:a};const n=C.key(e,t,s),c=this.subscriptions.get(n);if(c){const h=xe(c,i);h&&(r.push(h.confirm),a.push(h.rollback))}return{confirms:r,rollbacks:a}}applyOptimisticUpdate(e,t,s,i,r){const{confirms:a,rollbacks:n,store:c}=De(this.subscriptions,s);try{e(c,t)}catch{P(n);return}i.push(...n),r.push(...a)}getConnection(e){return this.connections.get(l(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.leaderStatus==="connected"?i="open":this.leaderStatus==="connecting"&&(i="connecting"),{hasSocket:!1,idleClosed:!1,polling:this.leaderStatus==="polling",wasEverConnected:this.leaderWasEverConnected,wsState:i}}const t=this.getConnection(e),s=t===void 0&&this.idleClosedShards.has(l(e));return{hasSocket:t?.socket!==void 0,idleClosed:s,polling:t?.polling.isPolling()??!1,wasEverConnected:t?.wasEverConnected??s,wsState:t?.wsState??"idle"}}getOrCreateConnection(e){const t=l(e);let s=this.connections.get(t);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:$s({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:()=>{this.flushOfflineQueue(e).catch(()=>{})},onStateChange:()=>{this.emitConnectionStatus()},poll:async()=>this.pollSubscriptions(e)}),reconnect:ce(this.reconnectOptions),reconnectTimer:void 0,resubscribePending:new Map,resubscribeQueue:[],shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:this.idleClosedShards.delete(t),wsState:"idle"},this.connections.set(t,s)),s}wsUrlFor(e,t){const s=[];if(e!==void 0&&s.push(`shard=${encodeURIComponent(e)}`),t!==void 0&&s.push(`token=${encodeURIComponent(t)}`),s.length===0)return this.wsUrl;const i=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${i}${s.join("&")}`}rpcRequestHeaders(e,t){const s={"content-type":"application/json"};e.expectSubject!==void 0&&(s[Ze]=et(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={}){if(!this.fetchImpl)throw new H("LunoraClient: no `fetch` implementation available");const r=this.rpcRequestHeaders(i,s),a=i.authToken===void 0?this.authToken:i.authToken,n=await this.fetchImpl(w(this.url,dt),{body:JSON.stringify({args:E(t,`args for '${e}'`),functionPath:e,shardKey:s}),headers:r,method:"POST"});if(i.captureBookmark){const u=n.headers.get("x-d1-bookmark");u&&this.bookmark.set(u)}let c;try{c=await n.json()}catch{throw F(n.status,n.statusText,n.headers.get("retry-after"))}const h=c;if(typeof h!="object"||h===null||Array.isArray(h))throw F(n.status,n.statusText,n.headers.get("retry-after"));const d=N(c);if(d!==void 0)throw ne(d,n.headers.get("retry-after"));if(!n.ok)throw F(n.status,n.statusText,n.headers.get("retry-after"));i.onMutationAck?.(c.lastMutationId),i.onCommitCursor?.(c.commitCursor),this.noteCredentialAccepted(a),this.learnDefaultShardKey(n,s),this.recordShardCursor(s,c.commitCursor);try{return g(c.result)}catch(u){throw ye(u)}}async adminFetch(e,t,s,i){if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");const r={};this.authToken&&(r.authorization=`Bearer ${this.authToken}`);const a=s instanceof ArrayBuffer||s instanceof Blob;let n;s===void 0?n=void 0:a?(n=s,i!==void 0&&(r["content-type"]=i)):(n=JSON.stringify(s),r["content-type"]="application/json");const c=await this.fetchImpl(w(this.url,e),{body:n,headers:r,method:t});let h;try{h=await c.json()}catch{const u=c.statusText?` ${c.statusText}`:"";throw new y("INTERNAL",`LunoraClient: response was not JSON (status ${c.status.toString()}${u})`)}const d=N(h);if(d!==void 0){const u=new Error(d.message??"admin request failed");throw u.code=d.code,u}if(!c.ok){const u=c.statusText?` ${c.statusText}`:"";throw new y("INTERNAL",`LunoraClient: admin request failed (status ${c.status.toString()}${u})`)}return h}effectiveConnectionContext(e){const t=this.connectionContextHolders.get(e);return t&&t.length>0?t[t.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){const t=this.connections.get(e);t?.wsState==="open"&&this.sendConnectEnvelope(t)}sendConnectEnvelope(e){const t=this.effectiveConnectionContext(l(e.shardKey));T(e,{caps:ii,clientId:this.clientId,id:"connect",type:"connect",...t===void 0?{}:{context:t}})}resendShapeSubscriptions(e){for(const t of this.shapeSubscriptions.values())l(t.shardKey)===l(e)&&this.sendShapeSubscribeIfOpen(t)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const t=this.getOrCreateConnection(e);if(!(t.wsState==="open"||t.wsState==="connecting")){if(t.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(t,e,this.wsToken).catch(()=>{});return}this.openSocket(t,e,this.wsToken)}}async openSocketWithProvidedToken(e,t,s){let i;try{i=await s()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,t,i)}openSocket(e,t,s){this.WebSocketImpl!==void 0&&(e.identity=this.identityFingerprint(),s===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.retired=!1,pe(e,this.wsUrlFor(t,s),this.managedSocketOptions,{onClose:i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},onMessage:i=>{e.retired!==!0&&this.handleServerMessage(i.data,t)},onOpen:()=>{e.wsState="open",e.wasEverConnected=!0,e.polling.noteOpen(),clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},Us),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(t),this.clearResubscribeQueue(e);for(const r of this.subscriptions.all())l(r.shardKey)===l(t)&&this.queueResubscribe(r);if(this.resendShapeSubscriptions(t),e.pendingUnsubscribes.length>0){const r=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(const{id:a,type:n}of r)T(e,{id:a,type:n});this.releaseIdleShard(t)}Ks(e);const i=this.whisperHandlers.get(l(t));if(i)for(const r of i.keys())T(e,{topic:r,type:"whisper_subscribe"});this.flushOfflineQueue(t).catch(()=>{})}}))}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(),L(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e);const t=new Set((e.pendingStreams??[]).map(i=>i.id));for(const[i,r]of this.streams)if(!(l(r.shardKey)!==l(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(n=>n.id!==i),a];continue}r.handle.fail(new y("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){const t=l(e);for(const s of this.subscriptions.all())l(s.shardKey)===t&&(s.acked=!1)}queueResubscribe(e){const t=this.getConnection(e.shardKey);t&&(t.resubscribeQueue.push(e),this.drainResubscribeQueue(t))}drainResubscribeQueue(e){for(;e.resubscribePending.size<xs;){const t=e.resubscribeQueue.shift();if(!t)return;this.subscriptions.getById(t.id)&&this.sendSubscribeIfOpen(t)&&e.resubscribePending.set(t.id,setTimeout(()=>{this.releaseResubscribeSlot(e,t.id)},Ds))}}releaseResubscribeSlot(e,t){const s=e.resubscribePending.get(t);s!==void 0&&(clearTimeout(s),e.resubscribePending.delete(t),this.drainResubscribeQueue(e))}clearResubscribeQueue(e){for(const t of e.resubscribePending.values())clearTimeout(t);e.resubscribePending.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);if(t?.wsState!=="open"||e.acked)return!1;const s=e.serverCursor!==void 0&&e.serverBase!==void 0;return T(t,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...s?{sinceSeq:e.serverCursor}:{},...s&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);t?.wsState==="open"&&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=Ws(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);r&&this.releaseResubscribeSlot(r,i.id)}switch(i.type){case"ack":{const r=this.subscriptions.getById(i.id);r&&(r.acked=!0);return}case"chunk":{const{data:r,generation:a,id:n,seq:c}=i,h=this.streams.get(n);h&&typeof c=="number"&&(h.lastSeq=c,typeof a=="number"&&(h.generation=a),h.durable=!0),h?.handle.push(g(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);break}case"pokeEnd":{this.handlePokeEnd(i,t);break}case"pokePart":{this.handlePokePart(i,t);break}case"pokeStart":{this.handlePokeStart(i,t);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,t);break}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}const{id:s}=e,i=s===void 0?void 0:this.streams.get(s);if(i&&s!==void 0){i.handle.fail(Me(e)),this.forgetStream(s);return}const r=s===void 0?void 0:this.subscriptions.getById(s);if(r){const n=ae(e),c=this.identityFingerprint(),h=C.keyOf(r);k(r.errorCallbacks,n),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(h,n,c);return}const a=s===void 0?void 0:this.shapeSubscriptions.get(s);a&&k(a.errorCallbacks,ae(e))}pokeBufferKey(e,t){return`${l(e)}\0${t}`}handlePokeStart(e,t){he(this.pokeBuffers,Ce.MAX_POKE_BUFFERS),this.pokeBuffers.set(this.pokeBufferKey(t,e.pokeId),{baseCheckpoint:e.baseCheckpoint,bases:new Map,epoch:e.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}handlePokePart(e,t){const s=this.pokeBuffers.get(this.pokeBufferKey(t,e.pokeId));if(!s)return;const i=[];try{for(const n of e.rowsPatch)i.push(n.value===void 0?n:{...n,value:g(n.value)})}catch(n){s.undecodable.set(e.shapeId,n);return}const r=s.parts.get(e.shapeId)??[];for(const n of i)r.push(n);s.parts.set(e.shapeId,r),e.lastMutationId!==void 0&&s.lastMutationId.set(e.shapeId,e.lastMutationId);const a=e.baseCheckpoint??s.baseCheckpoint;a!==void 0&&s.bases.set(e.shapeId,a),e.reset===!0&&s.resets.add(e.shapeId)}handlePokeEnd(e,t){const s=this.pokeBufferKey(t,e.pokeId),i=this.pokeBuffers.get(s);if(i){this.pokeBuffers.delete(s);for(const[r,a]of i.undecodable){const n=this.shapeSubscriptions.get(r);n&&k(n.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape — ${a instanceof Error?a.message:String(a)}`})}for(const r of i.parts.keys()){const a=this.shapeSubscriptions.get(r);a&&!i.undecodable.has(r)&&this.applyPokePart(a,i,e)}}}applyPokePart(e,t,s){const i=t.parts.get(e.id)??[],r=t.resets.has(e.id),a=t.bases.get(e.id),n=t.epoch!==void 0&&e.serverEpoch!==void 0&&t.epoch!==e.serverEpoch,c=a!==void 0&&e.serverCursor!==void 0&&e.serverCursor!==a;if(!r&&(n||c)){e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(e),this.sendShapeSubscribeIfOpen(e);return}r&&e.rows.clear(),ti(e.rows,i),s.checkpoint!==void 0&&(e.serverCursor=s.checkpoint),s.epoch!==void 0&&(e.serverEpoch=s.epoch);const h=t.lastMutationId.get(e.id);h!==void 0&&(e.lastMutationId=h),this.emitShapeRows(e),e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}emitShapeRows(e){const t=[...e.rows.values()];for(const s of e.callbacks)try{s(t)}catch{}}handleDataMessage(e,t){const{id:s}=e,i=s?this.subscriptions.getById(s):void 0;if(!i)return;let r;try{r=this.resolveDataPayload(e,i)}catch(a){k(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription — ${a instanceof Error?a.message:String(a)}`});return}if(r===ie){this.resnapshotSubscription(i);return}if(i.serverBase=r,this.dropCacheSeed(C.keyOf(i)),e.cursor!==void 0&&(i.serverCursor=e.cursor),e.epoch!==void 0&&(i.serverEpoch=e.epoch),e.lastMutationId!==void 0){i.lastMutationId=Math.max(i.lastMutationId??0,e.lastMutationId);for(const a of i.checkpointCallbacks)a({checkpoint:i.serverCursor,mutationId:i.lastMutationId,rowsFollow:!0})}if(this.persistQueryValue(i),W(i,i.serverCursor),t!==void 0&&Qe(i,t),A(i,_(r,i.optimisticLayers)),this.tabCoordinator?.isLeader()){const a=C.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(a,r,i.serverCursor,i.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){const t=this.subscriptions.getById(e.id);t&&this.ackAndAdvanceCursor(t,e.cursor,e.epoch)}handleSettledMessage(e){const t=this.subscriptions.getById(e.id);if(t){this.ackAndAdvanceCursor(t,e.cursor,e.epoch),e.lastMutationId!==void 0&&(t.lastMutationId=Math.max(t.lastMutationId??0,e.lastMutationId));for(const s of t.checkpointCallbacks)s({checkpoint:t.serverCursor,mutationId:t.lastMutationId});if(this.tabCoordinator?.isLeader()){const s=C.keyOf(t);this.tabCoordinator.broadcastSubscriptionSettled(s,t.serverCursor,t.serverEpoch,t.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(e,t,s){e.acked=!0,(t!==void 0&&t!==e.serverCursor||s!==void 0&&s!==e.serverEpoch)&&(t!==void 0&&(e.serverCursor=t),s!==void 0&&(e.serverEpoch=s),this.persistQueryValue(e),W(e,e.serverCursor)&&A(e,_(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,t){if("data"in e&&e.data!==void 0)return g(e.data);const s=g(e.delta);return _e(s)?t.serverBase===void 0?s:Ie(t.serverBase,s)??ie:s}dispatchWhisper(e,t){const s=this.whisperHandlers.get(l(t))?.get(e.topic);if(!s)return;const i=g(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&&(s.acked=!1,k(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(t=>{je(this.onPersistenceError,"remove",t,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let t=2166136261,s=5381;for(let 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&&X(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)}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[n,c]of i)a.set(n,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.revokeCacheSeededValues();for(const e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.acked=!1,A(e,_(void 0,e.optimisticLayers));for(const e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(e);this.bounceShardSockets(),this.retiredIdentities+=1,this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;const e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}bounceShardSockets(){for(const e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}}flushAllOfflineQueues(){for(const e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){const t=l(e),s=this.offlineFlushes.get(t);if(s===void 0&&this.offlineQueue.size===0)return;const 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&&X(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))}async drainOfflineQueue(e,t){const s=this.offlineQueue.drainConflict();for(const d of s){this.unpersist(d.id),this.queuedIdentities.delete(d.id??"");const u=new Error("offline mutation skipped: precondition failed before replay");u.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(d,"rejected",u)}const i=l(e),r=this.offlineQueue.drain(d=>l(d.shardKey)===i);if(r.length===0)return;const a=[],n=[];for(const d of r){const u=this.replayGateVerdict(d);u==="send"?a.push(d):u==="hold"&&n.push(d)}if(this.offlineQueue.requeue(n),n.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 h=[];for(let d=0;d<c.length;d+=$){const u=c.slice(d,d+$),f=await this.replayBatched(u,e,t);if(h.push(...f.requeue),f.stop){h.push(...c.slice(d+$));break}}h.length>0&&this.offlineQueue.requeue(h),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){const t=l(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=l(e),r=this.replayRetryState.get(i),a=(r?.attempts??0)+1,n=Xs(t,a)??(s===null&&q(t)?te(a):void 0);this.replayRetryState.set(i,{attempts:a,delayMs:n===void 0?r?.delayMs:Math.max(r?.delayMs??0,n)})}scheduleRateLimitedRetry(e){const t=l(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)||Vs(e)}noteReplayAuthRefusal(e,t){if(!q(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,...G(t.stamp,t.authToken)},stamp:t.stamp}}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;const t=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===t&&(this.warnedIdentityDisagreement=!0,console.warn('[lunora] a replayed write was refused with IDENTITY_MISMATCH, but `/get-session` still names the same user. The worker\'s `resolveIdentity` must return the same `userId` as the better-auth `user.id`, and RPC requests must carry the session cookie (`credentials: "include"` on a cross-origin fetch).'))}).catch(()=>{}),!0}settleReplayUndecodable(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.reject(t),this.emitItemSettled(e,"committed",t)}settleReplayTerminal(e,t){this.unpersist(e.id),e.reject(t),this.emitItemSettled(e,"rejected",t)}async replaySequential(e,t,s){for(let i=0;i<e.length;i+=1){const r=e[i];if(!r)continue;let a;try{const n=await this.rpc(r.functionPath,r.args,r.shardKey,{authToken:s,baselineSeq:r.baselineSeq,captureBookmark:!0,clientId:r.clientId??this.clientId,...G(r.identity,s),mutationId:r.id,onCommitCursor:c=>{a=c}});this.settleReplaySuccess(r,n,a)}catch(n){if(B(n)){this.settleReplayUndecodable(r,n,a);continue}if(!this.shouldRequeueReplayFailure(n,s)){this.settleReplayTerminal(r,n);continue}this.noteReplayRetryDelay(t,n,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((h,d)=>({args:E(h.args,`args for '${h.functionPath}'`),baselineSeq:h.baselineSeq,functionPath:h.functionPath,id:d,clientId:h.clientId??this.clientId,mutationId:h.id,shardKey:h.shardKey}))});if(e.length>1&&ei(i)>Zs)return await this.replayBatchedHalves(e,t,s);let r;try{r=await this.fetchImpl(w(this.url,V),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:s,...G(e.find(h=>h.identity!==void 0)?.identity,s)}),method:"POST"})}catch{return{requeue:e,stop:!0}}const a=r.headers.get("x-d1-bookmark");if(a&&this.bookmark.set(a),r.status===413&&e.length>1)return await this.replayBatchedHalves(e,t,s);let n;const c=r.headers.get("retry-after");try{n=await r.json()}catch{return this.settleWholeBatchError(e,F(r.status,r.statusText,c),t,s)}if(!n.results){const h=N(n),d=h===void 0?F(r.status,r.statusText,c):ne(h,c);return this.settleWholeBatchError(e,d,t,s)}return{requeue:this.settleReplayBatchSlots(e,n.results,t,s),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:e,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)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){const r=new Map;for(const h of t)typeof h.id=="number"&&be(h.body)&&r.set(h.id,h.body);const a=[];let n=!1,c=!1;for(const[h,d]of e.entries()){const u=r.get(h);if(u===void 0)a.push(d);else if("error"in u){const f=ee(u);c||=q(f),this.shouldRequeueReplayFailure(f,i)?(this.noteReplayRetryDelay(s,f,i),a.push(d)):this.settleReplayTerminal(d,f)}else n=!0,this.settleReplayBatchResult(d,u)}return n&&!c&&this.noteCredentialAccepted(i),a}settleReplayBatchResult(e,t){let s;try{s=g(t.result)}catch(i){this.settleReplayUndecodable(e,ye(i),t.commitCursor);return}this.settleReplaySuccess(e,s,t.commitCursor)}}export{Ce as LunoraClient};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{s}from"./wire-key-3XBGlnux.mjs";class t{static key(e,r,i){return`${e}::${s(r)}::${i??""}`}static keyOf(e){return`${e.fn.__lunoraRef}::${e.argsKey}::${e.shardKey??""}`}byKey=new Map;byId=new Map;get(e){return this.byKey.get(e)}getById(e){return this.byId.get(e)}add(e){this.byKey.set(t.keyOf(e),e),this.byId.set(e.id,e)}remove(e){const r=t.keyOf(e);this.byKey.get(r)===e&&this.byKey.delete(r),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}clear(){this.byKey.clear(),this.byId.clear()}}function b(y){if(y!==void 0)return e=>{y(e)}}const d=(y,e)=>{for(const r of y)try{r(e)}catch{}};export{t as SubscriptionRegistry,d as fanSubscriptionError,b as wrapSubscriber};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{U as s,a as E,i as e}from"./delta-merge-Cu-cN5Cb.mjs";export{s as UNMERGEABLE_DELTA,E as applyDelta,e as isMutationDelta};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as t}from"./local-store-SJVMlM2Z.mjs";import"./SubscriptionRegistry-5CHmk3d8.mjs";export{t as createLocalStore};
|
package/dist/packem_shared/{createServerClient-HdISrPXa.mjs → createServerClient-D7zkixlG.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraClient as r}from"./LunoraClient-
|
|
1
|
+
import{LunoraClient as r}from"./LunoraClient-BIzBh60k.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{i as l}from"./wire-codec-3Mj5UgNj.mjs";const c="_id",d="_creationTime",a="page",I="pageDelta",g=t=>{if(Array.isArray(t))return t;if(l(t)&&Array.isArray(t[a]))return t[a]},y=t=>{let e;for(const n of t){const o=n[d];if(typeof o=="number"){if(e!==void 0){if(o<e)return!0;if(o>e)return!1}e=o}}return!1},A=(t,e)=>{const n=e[d];if(typeof n!="number")return t.length;const o=y(t);for(const[f,s]of t.entries()){const r=s[d];if(typeof r=="number"&&(o?r<n:r>n))return f}return t.length},x=t=>{if(typeof t!="object"||t===null)return;const e=t[c];return typeof e=="string"?e:void 0},m=t=>{if(typeof t!="object"||t===null)return!1;const e=t;return typeof e.key=="string"&&typeof e.table=="string"&&(e.op==="insert"||e.op==="update"||e.op==="delete")},D=(t,e)=>{const n=[];for(const i of t){if(x(i)===void 0)return;n.push(i)}const{key:o,op:f,row:s}=e;if(f==="delete"){const i=n.filter(p=>p[c]!==o);return i.length===n.length?[...n]:i}if(s===void 0)return;const r=[...n],u=n.findIndex(i=>i[c]===o);return u===-1?r.splice(A(n,s),0,s):r[u]=s,r},b=(t,e)=>{const n=g(t);if(n===void 0)return;const o=D(n,e);return o===void 0||Array.isArray(t)?o:{...t,[a]:o}},L=Symbol("lunora.unmergeableDelta");export{I as P,L as U,b as a,m as i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SubscriptionRegistry as m}from"./SubscriptionRegistry-5CHmk3d8.mjs";let f=0;const L=()=>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)=>{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=()=>{d(r,p(r.serverBase,r.optimisticLayers))};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())}}},h=(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},k=(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]?.()},b=(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=y(u,()=>n);a&&(t.push(a.confirm),i.push(a.rollback))}}}};export{y as a,k as b,b as c,h as d,L as e,p as f,d as n,v as r};
|