@lunora/client 1.0.0-alpha.41 → 1.0.0-alpha.43
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 +2 -2
- package/dist/auth/index.d.ts +2 -2
- package/dist/index.d.mts +11 -5
- package/dist/index.d.ts +11 -5
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/LunoraClient-CrIthWcp.mjs +1 -0
- package/dist/packem_shared/{OfflineQueue-y4mymc5n.mjs → OfflineQueue-D1yiY7sF.mjs} +1 -1
- package/dist/packem_shared/{createServerClient-C1At_rrh.mjs → createServerClient-BKDKj3mJ.mjs} +1 -1
- package/dist/packem_shared/{lunora-client.d-cFPjoyDb.d.ts → lunora-client.d-B-hIlqf_.d.mts} +1 -1
- package/dist/packem_shared/{lunora-client.d-D_WLwpn0.d.mts → lunora-client.d-Rv8-L9mJ.d.ts} +1 -1
- package/dist/packem_shared/offline-queue-CKMw-5rF.mjs +1 -0
- package/dist/packem_shared/{preload.d-DNxm6niZ.d.mts → preload.d-C6emVQoK.d.mts} +2 -2
- package/dist/packem_shared/{preload.d-BkbCVtZe.d.ts → preload.d-CBi9DddN.d.ts} +2 -2
- package/dist/packem_shared/{types.d-CA7ZeJm9.d.mts → types.d-MI8BwMXt.d.mts} +9 -0
- package/dist/packem_shared/{types.d-CA7ZeJm9.d.ts → types.d-MI8BwMXt.d.ts} +9 -0
- package/dist/query/index.d.mts +3 -3
- package/dist/query/index.d.ts +3 -3
- package/dist/service.d.mts +1 -1
- package/dist/service.d.ts +1 -1
- package/dist/ssr/index.d.mts +4 -4
- package/dist/ssr/index.d.ts +4 -4
- package/dist/ssr/index.mjs +1 -1
- package/package.json +2 -2
- package/dist/packem_shared/LunoraClient-CB5y0HME.mjs +0 -1
- package/dist/packem_shared/offline-queue-BeWay5u5.mjs +0 -1
package/dist/auth/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
2
|
-
import { U as User } from "../packem_shared/types.d-
|
|
1
|
+
import { L as LunoraClient } from "../packem_shared/lunora-client.d-B-hIlqf_.mjs";
|
|
2
|
+
import { U as User } from "../packem_shared/types.d-MI8BwMXt.mjs";
|
|
3
3
|
import '@lunora/runtime';
|
|
4
4
|
interface IdentityStore {
|
|
5
5
|
/** Read the current resolved user, or `null` when signed out / not yet resolved. */
|
package/dist/auth/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
2
|
-
import { U as User } from "../packem_shared/types.d-
|
|
1
|
+
import { L as LunoraClient } from "../packem_shared/lunora-client.d-Rv8-L9mJ.js";
|
|
2
|
+
import { U as User } from "../packem_shared/types.d-MI8BwMXt.js";
|
|
3
3
|
import '@lunora/runtime';
|
|
4
4
|
interface IdentityStore {
|
|
5
5
|
/** Read the current resolved user, or `null` when signed out / not yet resolved. */
|
package/dist/index.d.mts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { o as PersistenceAdapter, B as BookmarkStorage, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf, F as FunctionReference, A as ArgsOf, R as ReturnOf, O as OfflineQueueOptions, Q as QueryCacheAdapter, p as ReconnectOptions } from "./packem_shared/types.d-
|
|
2
|
-
export type { C as CachedQuery, q as ClientMessage, r as ClientShapeSubscribeMessage, s as ClientShapeUnsubscribeMessage, t as FunctionArgumentDescriptor, h as FunctionDescriptor, l as GlobalFacetResult, u as GlobalFacetValue, j as GlobalFilterClause, G as GlobalTableInfo, k as GlobalTablePage, v as HttpStreamCallArgs, L as LunoraClientOptions, w as OutboxMutation, x as OutboxSink, y as PersistedMutation, P as Preloaded, z as RowOp, D as RpcEnvelope, E as RpcResponseBody, b as ScheduleRecord, I as SchedulerPoolStatus, c as SchedulerStatus, J as ServerMessage, K as ServerPokeEndMessage, M as ServerPokePartMessage, N as ServerPokeStartMessage, T as ShardTrafficEntry, S as ShardTrafficResult, i as StorageListPage, V as StorageObject, a as Unsubscribe, U as User, g as WorkflowInstanceAction, f as WorkflowInstanceDetail, e as WorkflowInstancePage, d as WorkflowInstanceStatus, X as WorkflowInstanceSummary, Y as WorkflowStepDetail, W as WsTokenProvider } from "./packem_shared/types.d-
|
|
3
|
-
import { C as ConnectionStatus, S as SubscriptionError, b as StreamIterable, M as MutationCallOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-
|
|
4
|
-
export { type B as BatchSlot, c as CONFLICT_ERROR_CODE, type d as ClientDebugShard, type e as ClientDebugSnapshot, type f as ClientDebugSubscription, type g as ClientQueryRef, D as DEFAULT_MAX_BUFFER, type h as LunoraClientError, type i as LunoraErrorCode, type j as MutationSettledEvent, type O as OptimisticLocalStore, type k as OptimisticUpdate, type l as StreamHandle, type m as SubscriptionCallback, type a as SubscriptionErrorCallback, n as SubscriptionRegistry, type o as SubscriptionState, type p as SyncWatermark, q as createClientQuery, r as createLocalStore, s as createStream, t as getErrorCode, u as getRetryAfterMs, v as isConflictError, w as isForbiddenError, x as isRateLimitedError, y as isUnauthorizedError } from "./packem_shared/lunora-client.d-
|
|
5
|
-
export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-
|
|
1
|
+
import { o as PersistenceAdapter, B as BookmarkStorage, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf, F as FunctionReference, A as ArgsOf, R as ReturnOf, O as OfflineQueueOptions, Q as QueryCacheAdapter, p as ReconnectOptions } from "./packem_shared/types.d-MI8BwMXt.mjs";
|
|
2
|
+
export type { C as CachedQuery, q as ClientMessage, r as ClientShapeSubscribeMessage, s as ClientShapeUnsubscribeMessage, t as FunctionArgumentDescriptor, h as FunctionDescriptor, l as GlobalFacetResult, u as GlobalFacetValue, j as GlobalFilterClause, G as GlobalTableInfo, k as GlobalTablePage, v as HttpStreamCallArgs, L as LunoraClientOptions, w as OutboxMutation, x as OutboxSink, y as PersistedMutation, P as Preloaded, z as RowOp, D as RpcEnvelope, E as RpcResponseBody, b as ScheduleRecord, I as SchedulerPoolStatus, c as SchedulerStatus, J as ServerMessage, K as ServerPokeEndMessage, M as ServerPokePartMessage, N as ServerPokeStartMessage, T as ShardTrafficEntry, S as ShardTrafficResult, i as StorageListPage, V as StorageObject, a as Unsubscribe, U as User, g as WorkflowInstanceAction, f as WorkflowInstanceDetail, e as WorkflowInstancePage, d as WorkflowInstanceStatus, X as WorkflowInstanceSummary, Y as WorkflowStepDetail, W as WsTokenProvider } from "./packem_shared/types.d-MI8BwMXt.mjs";
|
|
3
|
+
import { C as ConnectionStatus, S as SubscriptionError, b as StreamIterable, M as MutationCallOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-B-hIlqf_.mjs";
|
|
4
|
+
export { type B as BatchSlot, c as CONFLICT_ERROR_CODE, type d as ClientDebugShard, type e as ClientDebugSnapshot, type f as ClientDebugSubscription, type g as ClientQueryRef, D as DEFAULT_MAX_BUFFER, type h as LunoraClientError, type i as LunoraErrorCode, type j as MutationSettledEvent, type O as OptimisticLocalStore, type k as OptimisticUpdate, type l as StreamHandle, type m as SubscriptionCallback, type a as SubscriptionErrorCallback, n as SubscriptionRegistry, type o as SubscriptionState, type p as SyncWatermark, q as createClientQuery, r as createLocalStore, s as createStream, t as getErrorCode, u as getRetryAfterMs, v as isConflictError, w as isForbiddenError, x as isRateLimitedError, y as isUnauthorizedError } from "./packem_shared/lunora-client.d-B-hIlqf_.mjs";
|
|
5
|
+
export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-C6emVQoK.mjs";
|
|
6
6
|
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';
|
|
7
7
|
declare const anyApi: Record<string, Record<string, unknown>>;
|
|
8
8
|
/**
|
|
@@ -521,6 +521,12 @@ declare const createMutatorRunner: <TArgs>(handle: MutatorHandle<TArgs>, sinks:
|
|
|
521
521
|
};
|
|
522
522
|
interface QueuedMutation<T = unknown> {
|
|
523
523
|
readonly args: Record<string, unknown>;
|
|
524
|
+
/**
|
|
525
|
+
* The client id that queued this write (see {@link PersistedMutation.clientId}).
|
|
526
|
+
* Persisted and restored, so a replay namespaces by the id that issued the
|
|
527
|
+
* write rather than whatever the current session minted.
|
|
528
|
+
*/
|
|
529
|
+
clientId?: string;
|
|
524
530
|
readonly functionPath: string;
|
|
525
531
|
/** Stable id used to remove the entry from durable storage once replayed; assigned by the queue when absent. */
|
|
526
532
|
id?: string;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { o as PersistenceAdapter, B as BookmarkStorage, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf, F as FunctionReference, A as ArgsOf, R as ReturnOf, O as OfflineQueueOptions, Q as QueryCacheAdapter, p as ReconnectOptions } from "./packem_shared/types.d-
|
|
2
|
-
export type { C as CachedQuery, q as ClientMessage, r as ClientShapeSubscribeMessage, s as ClientShapeUnsubscribeMessage, t as FunctionArgumentDescriptor, h as FunctionDescriptor, l as GlobalFacetResult, u as GlobalFacetValue, j as GlobalFilterClause, G as GlobalTableInfo, k as GlobalTablePage, v as HttpStreamCallArgs, L as LunoraClientOptions, w as OutboxMutation, x as OutboxSink, y as PersistedMutation, P as Preloaded, z as RowOp, D as RpcEnvelope, E as RpcResponseBody, b as ScheduleRecord, I as SchedulerPoolStatus, c as SchedulerStatus, J as ServerMessage, K as ServerPokeEndMessage, M as ServerPokePartMessage, N as ServerPokeStartMessage, T as ShardTrafficEntry, S as ShardTrafficResult, i as StorageListPage, V as StorageObject, a as Unsubscribe, U as User, g as WorkflowInstanceAction, f as WorkflowInstanceDetail, e as WorkflowInstancePage, d as WorkflowInstanceStatus, X as WorkflowInstanceSummary, Y as WorkflowStepDetail, W as WsTokenProvider } from "./packem_shared/types.d-
|
|
3
|
-
import { C as ConnectionStatus, S as SubscriptionError, b as StreamIterable, M as MutationCallOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-
|
|
4
|
-
export { type B as BatchSlot, c as CONFLICT_ERROR_CODE, type d as ClientDebugShard, type e as ClientDebugSnapshot, type f as ClientDebugSubscription, type g as ClientQueryRef, D as DEFAULT_MAX_BUFFER, type h as LunoraClientError, type i as LunoraErrorCode, type j as MutationSettledEvent, type O as OptimisticLocalStore, type k as OptimisticUpdate, type l as StreamHandle, type m as SubscriptionCallback, type a as SubscriptionErrorCallback, n as SubscriptionRegistry, type o as SubscriptionState, type p as SyncWatermark, q as createClientQuery, r as createLocalStore, s as createStream, t as getErrorCode, u as getRetryAfterMs, v as isConflictError, w as isForbiddenError, x as isRateLimitedError, y as isUnauthorizedError } from "./packem_shared/lunora-client.d-
|
|
5
|
-
export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-
|
|
1
|
+
import { o as PersistenceAdapter, B as BookmarkStorage, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf, F as FunctionReference, A as ArgsOf, R as ReturnOf, O as OfflineQueueOptions, Q as QueryCacheAdapter, p as ReconnectOptions } from "./packem_shared/types.d-MI8BwMXt.js";
|
|
2
|
+
export type { C as CachedQuery, q as ClientMessage, r as ClientShapeSubscribeMessage, s as ClientShapeUnsubscribeMessage, t as FunctionArgumentDescriptor, h as FunctionDescriptor, l as GlobalFacetResult, u as GlobalFacetValue, j as GlobalFilterClause, G as GlobalTableInfo, k as GlobalTablePage, v as HttpStreamCallArgs, L as LunoraClientOptions, w as OutboxMutation, x as OutboxSink, y as PersistedMutation, P as Preloaded, z as RowOp, D as RpcEnvelope, E as RpcResponseBody, b as ScheduleRecord, I as SchedulerPoolStatus, c as SchedulerStatus, J as ServerMessage, K as ServerPokeEndMessage, M as ServerPokePartMessage, N as ServerPokeStartMessage, T as ShardTrafficEntry, S as ShardTrafficResult, i as StorageListPage, V as StorageObject, a as Unsubscribe, U as User, g as WorkflowInstanceAction, f as WorkflowInstanceDetail, e as WorkflowInstancePage, d as WorkflowInstanceStatus, X as WorkflowInstanceSummary, Y as WorkflowStepDetail, W as WsTokenProvider } from "./packem_shared/types.d-MI8BwMXt.js";
|
|
3
|
+
import { C as ConnectionStatus, S as SubscriptionError, b as StreamIterable, M as MutationCallOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-Rv8-L9mJ.js";
|
|
4
|
+
export { type B as BatchSlot, c as CONFLICT_ERROR_CODE, type d as ClientDebugShard, type e as ClientDebugSnapshot, type f as ClientDebugSubscription, type g as ClientQueryRef, D as DEFAULT_MAX_BUFFER, type h as LunoraClientError, type i as LunoraErrorCode, type j as MutationSettledEvent, type O as OptimisticLocalStore, type k as OptimisticUpdate, type l as StreamHandle, type m as SubscriptionCallback, type a as SubscriptionErrorCallback, n as SubscriptionRegistry, type o as SubscriptionState, type p as SyncWatermark, q as createClientQuery, r as createLocalStore, s as createStream, t as getErrorCode, u as getRetryAfterMs, v as isConflictError, w as isForbiddenError, x as isRateLimitedError, y as isUnauthorizedError } from "./packem_shared/lunora-client.d-Rv8-L9mJ.js";
|
|
5
|
+
export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-CBi9DddN.js";
|
|
6
6
|
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';
|
|
7
7
|
declare const anyApi: Record<string, Record<string, unknown>>;
|
|
8
8
|
/**
|
|
@@ -521,6 +521,12 @@ declare const createMutatorRunner: <TArgs>(handle: MutatorHandle<TArgs>, sinks:
|
|
|
521
521
|
};
|
|
522
522
|
interface QueuedMutation<T = unknown> {
|
|
523
523
|
readonly args: Record<string, unknown>;
|
|
524
|
+
/**
|
|
525
|
+
* The client id that queued this write (see {@link PersistedMutation.clientId}).
|
|
526
|
+
* Persisted and restored, so a replay namespaces by the id that issued the
|
|
527
|
+
* write rather than whatever the current session minted.
|
|
528
|
+
*/
|
|
529
|
+
clientId?: string;
|
|
524
530
|
readonly functionPath: string;
|
|
525
531
|
/** Stable id used to remove the entry from durable storage once replayed; assigned by the queue when absent. */
|
|
526
532
|
id?: string;
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{anyApi as o}from"./packem_shared/anyApi-BD4dgvDY.mjs";import{RETIRE_AFTER_DURABLE_SEQ_ADVANCE as a,maxSeq as n,reconcileOptimistic as p}from"./packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-D96iRJDY.mjs";import{createAsyncStoragePersistence as m}from"./packem_shared/createAsyncStoragePersistence-BRLqeXsC.mjs";import{default as f}from"./packem_shared/createInMemoryBookmarkStorage-DCd5Ej-t.mjs";import{createClientQuery as s}from"./packem_shared/createClientQuery-CrdRoicO.mjs";import{TabCoordinator as d}from"./packem_shared/TabCoordinator-CMFYQCL-.mjs";import{applyDelta as y,isMutationDelta as R}from"./packem_shared/applyDelta-DXqQORbM.mjs";import{CONFLICT_ERROR_CODE as C,getErrorCode as S,getRetryAfterMs as A,isConflictError as D,isForbiddenError as M,isRateLimitedError as _,isUnauthorizedError as h}from"./packem_shared/CONFLICT_ERROR_CODE-B2SU0CaJ.mjs";import{httpStream as Q}from"./packem_shared/httpStream-Cz4_QyjV.mjs";import{c as L}from"./packem_shared/local-store-DFMSEM2j.mjs";import{LunoraClient as b}from"./packem_shared/LunoraClient-
|
|
1
|
+
import{anyApi as o}from"./packem_shared/anyApi-BD4dgvDY.mjs";import{RETIRE_AFTER_DURABLE_SEQ_ADVANCE as a,maxSeq as n,reconcileOptimistic as p}from"./packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-D96iRJDY.mjs";import{createAsyncStoragePersistence as m}from"./packem_shared/createAsyncStoragePersistence-BRLqeXsC.mjs";import{default as f}from"./packem_shared/createInMemoryBookmarkStorage-DCd5Ej-t.mjs";import{createClientQuery as s}from"./packem_shared/createClientQuery-CrdRoicO.mjs";import{TabCoordinator as d}from"./packem_shared/TabCoordinator-CMFYQCL-.mjs";import{applyDelta as y,isMutationDelta as R}from"./packem_shared/applyDelta-DXqQORbM.mjs";import{CONFLICT_ERROR_CODE as C,getErrorCode as S,getRetryAfterMs as A,isConflictError as D,isForbiddenError as M,isRateLimitedError as _,isUnauthorizedError as h}from"./packem_shared/CONFLICT_ERROR_CODE-B2SU0CaJ.mjs";import{httpStream as Q}from"./packem_shared/httpStream-Cz4_QyjV.mjs";import{c as L}from"./packem_shared/local-store-DFMSEM2j.mjs";import{LunoraClient as b}from"./packem_shared/LunoraClient-CrIthWcp.mjs";import{createMutationRunner as O}from"./packem_shared/createMutationRunner-lQXH8Amk.mjs";import{createMutatorRunner as U}from"./packem_shared/createMutatorRunner-BVzo0FBZ.mjs";import{h as B}from"./packem_shared/offline-queue-CKMw-5rF.mjs";import{createInMemoryPersistence as N,createIndexedDbPersistence as v}from"./packem_shared/createInMemoryPersistence-CQYXy8UP.mjs";import{preloadQuery as z,preloadedQueryResult as K}from"./packem_shared/preloadQuery-DjwSjFwt.mjs";import{createInMemoryQueryCache as W,createIndexedDbQueryCache as X,queryCacheKey as j}from"./packem_shared/createInMemoryQueryCache-DjCKrLjk.mjs";import{createReconnect as H}from"./packem_shared/createReconnect-CFT7YRSR.mjs";import{default as Y}from"./packem_shared/createSnapshotPrecondition-CKvCNKyD.mjs";import{DEFAULT_MAX_BUFFER as $,createStream as ee}from"./packem_shared/DEFAULT_MAX_BUFFER-TBn2s7Rz.mjs";import{SubscriptionRegistry as oe}from"./packem_shared/SubscriptionRegistry-C72rCp44.mjs";import{ClientServiceWorker as ae}from"./packem_shared/ClientServiceWorker-CRQ5yl7-.mjs";import{createReply as pe,sendToSw as ce}from"./packem_shared/createReply-DF0jRsv-.mjs";export{C as CONFLICT_ERROR_CODE,ae as ClientServiceWorker,$ as DEFAULT_MAX_BUFFER,b as LunoraClient,B as OfflineQueue,a as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,oe as SubscriptionRegistry,d as TabCoordinator,o as anyApi,y as applyDelta,m as createAsyncStoragePersistence,s as createClientQuery,f as createInMemoryBookmarkStorage,N as createInMemoryPersistence,W as createInMemoryQueryCache,v as createIndexedDbPersistence,X as createIndexedDbQueryCache,L as createLocalStore,O as createMutationRunner,U as createMutatorRunner,H as createReconnect,pe as createReply,Y as createSnapshotPrecondition,ee as createStream,S as getErrorCode,A as getRetryAfterMs,Q as httpStream,D as isConflictError,M as isForbiddenError,R as isMutationDelta,_ as isRateLimitedError,h as isUnauthorizedError,n as maxSeq,z as preloadQuery,K as preloadedQueryResult,j as queryCacheKey,p as reconcileOptimistic,ce as sendToSw};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as p}from"@lunora/errors";import{s as b,a as B}from"./wire-codec-D_fiax9d.mjs";import{t as I}from"./wire-key-j8BZ65HQ.mjs";import D from"./createInMemoryBookmarkStorage-DCd5Ej-t.mjs";import{ClientQueryStore as j}from"./createClientQuery-CrdRoicO.mjs";import{TabCoordinator as H}from"./TabCoordinator-CMFYQCL-.mjs";import{isMutationDelta as V,applyDelta as J}from"./applyDelta-DXqQORbM.mjs";import{httpStream as X}from"./httpStream-Cz4_QyjV.mjs";import{d as F,n as P,f as A,a as Y,c as Z}from"./local-store-DFMSEM2j.mjs";import{h as tt,u as K,d as et,s as st}from"./offline-queue-CKMw-5rF.mjs";import{resolvePersistenceAdapter as it}from"./createInMemoryPersistence-CQYXy8UP.mjs";import{resolveQueryCacheAdapter as nt,queryCacheKey as R}from"./createInMemoryQueryCache-DjCKrLjk.mjs";import{createReconnect as q}from"./createReconnect-CFT7YRSR.mjs";import{createStream as rt}from"./DEFAULT_MAX_BUFFER-TBn2s7Rz.mjs";import{SubscriptionRegistry as w}from"./SubscriptionRegistry-C72rCp44.mjs";const L=500,at=(h,t)=>{if(h.size<t)return;const e=h.keys().next().value;e!==void 0&&h.delete(e)};class C{listeners=new Set;add(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}emit(...t){const[e]=t;for(const s of this.listeners)try{s(e)}catch{}}clear(){this.listeners.clear()}}const ot="/_lunora/rpc",Q="/_lunora/rpc-batch",ct="/_lunora/ws",M=h=>h===void 0||h===""?"":`&bucket=${encodeURIComponent(h)}`,O=h=>{for(let t=h.length-1;t>=0;t-=1)h[t]?.()},ht=(h,t)=>{for(const e of t)e.op==="delete"?h.delete(e.key):e.value!==void 0&&h.set(e.key,e.value)},dt="lunora-ping",ut=3e4,lt=1e4,pt=250,mt=64,ft="/_lunora/admin/shard-traffic",yt="/_lunora/admin/scheduled",gt="/_lunora/admin/scheduled/status",bt="/_lunora/admin/scheduled/ws",vt="/_lunora/admin/scheduled/cancel",St="/_lunora/admin/scheduled/dead",kt="/_lunora/admin/scheduled/dead/retry",wt="/_lunora/admin/scheduled/dead/cancel",Ct="/_lunora/admin/workflows/instances",Tt="/_lunora/admin/workflows/instance",It="/_lunora/admin/workflows/status",x="/_lunora/admin/storage",Ot="/_lunora/admin/storage/url",Et="/_lunora/admin/storage/buckets",_t="/_lunora/admin/functions",Ft="/_lunora/admin/cron-jobs",Pt="/_lunora/admin/cron-jobs/run",At="/_lunora/admin/openapi",Rt="/_lunora/admin/openrpc",Lt="/_lunora/admin/global/tables",Mt="/_lunora/admin/global/table",xt="/_lunora/admin/global/facet",$t="/_lunora/admin/vector/indexes",Kt="/_lunora/admin/vector/query",qt="/_lunora/admin/logs/archive",Qt="/_lunora/admin/kv/namespaces",Ut="/_lunora/admin/kv/keys",$="/_lunora/admin/kv/value",Nt="/_lunora/admin/auth/users",Bt="/_lunora/admin/auth/sessions",Wt="/_lunora/admin/auth/users/create",zt="/_lunora/admin/auth/users/role",Gt="/_lunora/admin/auth/users/ban",Dt="/_lunora/admin/auth/users/unban",jt="/_lunora/admin/auth/users/password",Ht="/_lunora/admin/auth/users/remove",Vt="/_lunora/admin/auth/users/impersonate",Jt="/_lunora/admin/auth/sessions/revoke",Xt="/_lunora/admin/auth/sessions/revoke-all",Yt="/_lunora/admin/auth/capabilities",Zt="/_lunora/admin/auth/users/update",te="/_lunora/admin/auth/accounts",ee="/_lunora/admin/auth/accounts/unlink",se="/_lunora/admin/auth/passkeys",ie="/_lunora/admin/auth/passkeys/delete",ne="/_lunora/admin/auth/two-factor/disable",re="/_lunora/admin/auth/organizations",ae="/_lunora/admin/auth/organizations/members",oe="/_lunora/admin/auth/organizations/invitations",ce="/_lunora/admin/auth/organizations/members/remove",he="/_lunora/admin/auth/organizations/invitations/cancel",de="/_lunora/admin/auth/config",ue="/_lunora/admin/auth/organizations/create",le="/_lunora/admin/auth/organizations/update",pe="/_lunora/admin/auth/organizations/remove",me="/_lunora/admin/auth/organizations/members/add",fe="/_lunora/admin/auth/organizations/members/invite",ye="/_lunora/admin/auth/organizations/members/role",ge="/_lunora/admin/auth/organizations/teams",be="/_lunora/admin/auth/organizations/teams/create",ve="/_lunora/admin/auth/organizations/teams/update",Se="/_lunora/admin/auth/organizations/teams/remove",ke="/_lunora/admin/auth/organizations/teams/members",we="/_lunora/admin/auth/organizations/teams/members/add",Ce="/_lunora/admin/auth/organizations/teams/members/remove",Te="/_lunora/admin/auth/organizations/roles",Ie="/_lunora/admin/auth/organizations/roles/create",Oe="/_lunora/admin/auth/organizations/roles/update",Ee="/_lunora/admin/auth/organizations/roles/remove",_e="/api/auth",Fe="/get-session",U=h=>h.startsWith("https://")?`wss://${h.slice(8)}`:h.startsWith("http://")?`ws://${h.slice(7)}`:h,S=(h,t)=>`${h.endsWith("/")?h.slice(0,-1):h}${t}`,f=(h,t)=>{const e=new URLSearchParams;for(const[i,n]of Object.entries(t))n!==void 0&&n!==""&&e.set(i,String(n));const s=e.toString();return s===""?h:`${h}?${s}`},m=h=>h??"",W=(h,t)=>{const e=h.error,s=typeof e?.code=="string"?e.code:void 0,i=typeof e?.message=="string"?e.message:void 0;return{code:s,messageText:(typeof h.message=="string"?h.message:void 0)??i??t}},Pe=h=>{const{code:t,messageText:e}=W(h,"stream error");return t===void 0?new Error(e):new p(t,e)},N=h=>{const{code:t,messageText:e}=W(h,"subscription error");return{message:e,...t===void 0?{}:{code:t}}},E=(h,t)=>{for(const e of h)try{e(t)}catch{}},Ae=new TextDecoder,Re=h=>{if(typeof h=="string")return h;if(h instanceof ArrayBuffer)return Ae.decode(h)},g=(h,t)=>{if(!h.socket||h.wsState!=="open")return!1;try{return h.socket.send(JSON.stringify(t)),!0}catch{return!1}},T=h=>{const t=new Error(h.message??"request failed");return t.code=h.code,h.data!==void 0&&(t.data=b(h.data)),h.hint!==void 0&&(t.hint=h.hint),h.docsUrl!==void 0&&(t.docsUrl=h.docsUrl),t},k=(h,t)=>{try{return B(h)}catch(e){const s=e instanceof Error?e.message:String(e);throw new TypeError(`LunoraClient: cannot encode ${t} — ${s}`,e instanceof Error?{cause:e}:void 0)}},Le=(h,t)=>{const e=Array.from({length:t});for(const s of h){if(typeof s.id!="number"||s.id<0||s.id>=t)continue;const i=s.body;e[s.id]=i&&"error"in i&&i.error?{error:T(i.error),ok:!1}:{ok:!0,value:b(i?.result)}}return e.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},Me=new Set(["SHARD_ERROR","SHARD_UNAVAILABLE"]),xe=Promise.resolve();class z{static MAX_POKE_BUFFERS=256;static createClientQuery(t,e){return{defaultValue:e,key:t}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;offlineQueue;outbox;clientId;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new w;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new C;statusListeners=new C;tokenExpiredListeners=new C;mutationSettledListeners=new C;pendingChangeListeners=new C;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(t){this.url=t.url,this.wsUrl=t.wsUrl??S(U(t.url),ct),this.wsToken=t.wsToken;const e=t.authBasePath??_e;this.authBasePath=e.endsWith("/")?e.slice(0,-1):e,this.fetchImpl=t.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=t.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=t.bookmarkStorage??D(),this.reconnectOptions=t.reconnect,this.heartbeatIntervalMs=t.heartbeatIntervalMs??ut,this.connectTimeoutMs=t.connectTimeoutMs??lt,this.defaultConnectionContext=t.connectionContext,this.persistence=it(t.persistence,t.outbox===void 0),this.persistenceVersion=t.persistenceVersion,this.queryCache=nt(t.queryCache),this.onPersistenceError=t.offlineQueue?.onPersistenceError,this.clientQueryStore=new j,t.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,t.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=xe),this.offlineQueue=new tt(t.offlineQueue,{onEvict:(s,i)=>{this.emitItemSettled(s,"rejected",i)},onSizeChange:s=>{this.pendingChangeListeners.emit(s)},persistence:this.persistence,version:t.persistenceVersion}),this.outbox=t.outbox,this.clientId=t.clientId??`client-${K()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})})}setAuthToken(t,e){const s=this.authToken!==t,i=this.identityFingerprint();this.authToken=t,e!==void 0&&(this.authSubject=e);const n=this.identityFingerprint();if(n!==i&&(s?this.rejectQueuedForIdentityChange():this.restampQueuedIdentity(i,n),this.tabCoordinator)){const r=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),r&&this.tabCoordinator.promoteImmediately()}s&&this.authTokenListeners.emit(t)}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}clientIdentifier(){return this.clientId}confirmedMutationWatermark(t){return this.clientWatermarks.get(t??"")??0}async callMutator(t,e,s){const i=s?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new p("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);const n=s?.shardKey??"";let r;const a=await this.rpc(t,e,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:o=>{r=o}});return r!==void 0&&r>(this.clientWatermarks.get(n)??0)&&this.clientWatermarks.set(n,r),{applied:r===void 0||r===i,result:a}}onAuthTokenChange(t){return this.authTokenListeners.add(t)}async getCurrentUser(){if(this.closed||!this.fetchImpl)return null;const t={};this.authToken&&(t.authorization=`Bearer ${this.authToken}`);try{const e=await this.fetchImpl(S(this.url,`${this.authBasePath}${Fe}`),{credentials:"include",headers:t,method:"GET"});return e.ok?(await e.json())?.user??null:null}catch{return null}}setWsToken(t){if(this.wsToken!==t){this.wsToken=t;for(const e of this.connections.values())if(e.socket)try{e.socket.close()}catch{}}}setConnectionContext(t,e={}){const s=m(e.shardKey);t===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,t),this.refreshConnectionContext(s)}acquireConnectionContext(t,e={}){const s=m(e.shardKey),i={context:t},n=this.connectionContextHolders.get(s);n?n.push(i):this.connectionContextHolders.set(s,[i]),this.refreshConnectionContext(s);let r=!1;return()=>{if(r)return;r=!0;const a=this.connectionContextHolders.get(s);if(!a)return;const o=a.indexOf(i);o!==-1&&a.splice(o,1),a.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s)}}whisperSubscribe(t,e,s={}){const i=m(s.shardKey);let n=this.whisperHandlers.get(i);n||(n=new Map,this.whisperHandlers.set(i,n));let r=n.get(t);const a=r===void 0;if(r||(r=new Set,n.set(t,r)),r.add(e),this.ensureSocket(s.shardKey),a){const o=this.getConnection(s.shardKey);o&&g(o,{topic:t,type:"whisper_subscribe"})}return()=>{const o=this.whisperHandlers.get(i),c=o?.get(t);if(!c?.delete(e)||c.size>0)return;o?.delete(t),o?.size===0&&this.whisperHandlers.delete(i);const d=this.getConnection(s.shardKey);d&&g(d,{topic:t,type:"whisper_unsubscribe"})}}whisper(t,e,s={}){this.ensureSocket(s.shardKey);const i=this.getConnection(s.shardKey);i&&g(i,{data:k(e??null,`whisper data for topic '${t}'`),topic:t,type:"whisper"})}onTokenExpired(t){return this.tokenExpiredListeners.add(t)}connectionStatus(){return this.computeStatus()}onConnectionStatus(t){const e=this.statusListeners.add(t);return t(this.computeStatus()),e}pendingCount(){return this.offlineQueue.size}debug(){const t=[],e=new Set([...this.connections.keys(),...this.clientWatermarks.keys()]);for(const i of e){const n=this.connections.get(i);t.push({confirmedMutationWatermark:this.clientWatermarks.get(i)??0,hasSocket:n?.socket!==void 0,shardKey:i===""?void 0:i,wasEverConnected:n?.wasEverConnected??!1,wsState:n?.wsState??"idle"})}const s=this.subscriptions.all().map(i=>({acked:i.acked,functionPath:i.fn.__lunoraRef,id:i.id,kind:"query",lastMutationId:i.lastMutationId,pendingOptimisticLayers:i.optimisticLayers.length,serverCursor:i.serverCursor,shardKey:i.shardKey,subscriberCount:i.callbacks.size}));for(const i of this.shapeSubscriptions.values())s.push({acked:i.serverCursor!==void 0,functionPath:`shape:${i.name}`,id:i.id,kind:"shape",lastMutationId:i.lastMutationId,pendingOptimisticLayers:0,rowCount:i.rows.size,serverCursor:i.serverCursor,shardKey:i.shardKey,subscriberCount:i.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:t.toSorted((i,n)=>(i.shardKey??"").localeCompare(n.shardKey??"")),subscriptions:s.toSorted((i,n)=>i.functionPath.localeCompare(n.functionPath))}}onPendingChange(t){const e=this.pendingChangeListeners.add(t);return t(this.offlineQueue.size),e}onMutationSettled(t){return this.mutationSettledListeners.add(t)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(t){return this.clientQueryStore.get(t)}setClientQuery(t,e){this.clientQueryStore.set(t,e)}subscribeClientQuery(t,e){return this.clientQueryStore.subscribe(t,e)}resetClientQuery(t){this.clientQueryStore.reset(t)}snapshotPrecondition(t,e,s){const i=this.peekActiveQueryValue(t.__lunoraRef,e,s),n=i===void 0?void 0:I(i);return()=>{const r=this.peekActiveQueryValue(t.__lunoraRef,e,s);return n===void 0&&r===void 0?!0:n===void 0||r===void 0?!1:I(r)===n}}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(t,e,s){if(!this.readyResolved)return;const i=I(e),n=R(t,i,s),r=this.hydratedQueryCache.get(n);if(r!==void 0)return r.identity===this.identityFingerprint()?r.value:void 0}peekActiveQueryValue(t,e,s){const i=w.key(t,e,s);return this.subscriptions.get(i)?.lastValue}async query(t,e,s={}){return this.assertOpen(),await this.rpc(t.__lunoraRef,e,s.shardKey,{attachBookmark:!0})}async batch(t){if(this.assertOpen(),!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");if(t.length===0)return[];const e=await this.fetchImpl(S(this.url,Q),{body:JSON.stringify({calls:t.map((n,r)=>({args:k(n.args??{},`args for batch call '${n.fn.__lunoraRef}'`),functionPath:n.fn.__lunoraRef,id:r,shardKey:n.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"}),s=e.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let i;try{i=await e.json()}catch{throw new p("INTERNAL",`LunoraClient: batch response was not JSON (status ${e.status.toString()})`)}if(!e.ok||i.error&&!i.results)throw i.error?T(i.error):new p("INTERNAL",`LunoraClient: batch request failed (status ${e.status.toString()})`);return Le(i.results??[],t.length)}async mutation(t,e,s={}){this.assertOpen();const i=e,n=s.mutationId??K(),{confirms:r,rollbacks:a}=this.applyOptimisticUpdates(t.__lunoraRef,i,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,e,s.shardKey,a,r);const{hasSocket:o,wasEverConnected:c,wsState:d}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:u}=this.offlineQueue,l=c||u,y=this.WebSocketImpl!==void 0&&l;if(d!=="open"&&!o&&y||d==="connecting"&&l)return this.enqueueOfflineMutation(t,i,s.shardKey,n,a,r,s.precondition);try{let v;const G=await this.rpc(t.__lunoraRef,i,s.shardKey,{captureBookmark:!0,mutationId:n,onCommitCursor:_=>{v=_}});for(const _ of r)_(v);return G}catch(v){throw O(a),v}}async action(t,e,s={}){return this.assertOpen(),await this.rpc(t.__lunoraRef,e,s.shardKey)}async importRows(t,e,s={}){this.assertOpen();const i=Math.max(1,Math.trunc(s.chunkSize??500)),n=s.toArgs??(c=>({rows:c})),r=e.length;let a=0,o=0;for(let c=0;c<r;c+=i){const d=e.slice(c,c+i),u=o;await this.mutation(t,n(d),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(u)}`},shardKey:s.shardKey}),o+=1,a+=d.length,s.onProgress?.({done:a,total:r})}return{chunks:o,imported:a}}async shardTraffic(t){this.assertOpen();const e=await this.adminFetch(ft,"POST",{table:t});return{failed:e.failed??0,ok:e.ok??0,shards:e.shards??[]}}async listScheduledJobs(){return this.assertOpen(),(await this.adminFetch(yt,"GET")).records??[]}async schedulerStatus(){this.assertOpen();const t=await this.adminFetch(gt,"GET");return{backlog:t.backlog??0,inFlight:t.inFlight??0,pools:t.pools??[]}}async cancelScheduledJob(t){return this.assertOpen(),{cancelled:(await this.adminFetch(vt,"POST",{id:t})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await this.adminFetch(St,"GET")).records??[]}async retryDeadJob(t){return this.assertOpen(),{retried:(await this.adminFetch(kt,"POST",{id:t})).retried===!0}}async removeDeadJob(t){return this.assertOpen(),{removed:(await this.adminFetch(wt,"POST",{id:t})).removed===!0}}async listWorkflowInstances(t){this.assertOpen();const e=new URLSearchParams({name:t.name});t.status!==void 0&&e.set("status",t.status),t.page!==void 0&&e.set("page",String(t.page)),t.perPage!==void 0&&e.set("perPage",String(t.perPage));const s=await this.adminFetch(`${Ct}?${e.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??t.perPage??0,totalCount:s.totalCount}}async getWorkflowInstance(t){this.assertOpen();const e=new URLSearchParams({id:t.id,name:t.name}),s=await this.adminFetch(`${Tt}?${e.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??t.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}}async setWorkflowInstanceStatus(t){return this.assertOpen(),{status:(await this.adminFetch(It,"POST",{action:t.action,id:t.id,name:t.name})).status??"unknown"}}subscribeScheduledJobs(t){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const e=S(U(this.url),bt),s=q(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let n,r=!1;const a=()=>{r||(n=setTimeout(d,s.next()))},o=u=>{if(r||this.WebSocketImpl===void 0)return;const l=u===void 0?e:`${e}?token=${encodeURIComponent(u)}`;this.openManagedSocket(i,l,this.connectTimeoutMs,{onClose:()=>{a()},onMessage:y=>{try{const v=JSON.parse(typeof y.data=="string"?y.data:"");v.type==="jobs"&&Array.isArray(v.records)&&t(v.records)}catch{}},onOpen:()=>{s.reset()}})},c=async u=>{let l;try{l=await u()}catch{a();return}o(l)},d=()=>{if(r||this.WebSocketImpl===void 0)return;const{wsToken:u}=this;if(typeof u=="function"){c(u).catch(()=>{});return}o(u)};return d(),()=>{r=!0,n!==void 0&&clearTimeout(n),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),this.stopHeartbeat(i),i.socket?.close()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(_t,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(Ft,"GET")).jobs??[]}async runCronJob(t){this.assertOpen();const e=await this.adminFetch(Pt,"POST",{name:t});return{name:e.name??t,ran:e.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(At,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(Rt,"GET")}async listStorageObjects(t={}){this.assertOpen();const e=f(x,{bucket:t.bucket,cursor:t.cursor,limit:t.limit,prefix:t.prefix}),s=await this.adminFetch(e,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(t,e){this.assertOpen();const s=`${x}?key=${encodeURIComponent(t)}${M(e?.bucket)}`,i=await this.adminFetch(s,"DELETE");return{deleted:i.deleted??!0,key:i.key??t}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(Et,"GET")).buckets??[]}async uploadStorageObject(t){this.assertOpen();const e=`${x}?key=${encodeURIComponent(t.key)}${M(t.bucket)}`,s=await this.adminFetch(e,"PUT",t.body,t.contentType);return{etag:s.etag,key:s.key??t.key}}async signedStorageUrl(t,e){this.assertOpen();const s=e?.expiresInSeconds,i=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,n=`${Ot}?key=${encodeURIComponent(t)}${i}${M(e?.bucket)}`,r=await this.adminFetch(n,"GET");if(typeof r.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return r.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(Lt,"GET")}async readGlobalTablePage(t){this.assertOpen();const e=new URLSearchParams({table:t.table});return t.limit!==void 0&&e.set("limit",String(t.limit)),t.offset!==void 0&&e.set("offset",String(t.offset)),t.filters!==void 0&&t.filters.length>0&&e.set("filters",JSON.stringify(t.filters)),await this.adminFetch(`${Mt}?${e.toString()}`,"GET")}async facetGlobalColumn(t){this.assertOpen();const e=new URLSearchParams({column:t.column,table:t.table});return t.limit!==void 0&&e.set("limit",String(t.limit)),t.filters!==void 0&&t.filters.length>0&&e.set("filters",JSON.stringify(t.filters)),await this.adminFetch(`${xt}?${e.toString()}`,"GET")}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch($t,"GET")).indexes??[]}async queryVectorIndex(t){return this.assertOpen(),(await this.adminFetch(Kt,"POST",t)).matches??[]}async queryLogArchive(t={}){this.assertOpen();const e=await this.adminFetch(qt,"POST",t);return{nextCursor:e.nextCursor,rows:e.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(Qt,"GET")).namespaces??[]}async listKvKeys(t){this.assertOpen();const e=f(Ut,{cursor:t.cursor,limit:t.limit,namespace:t.namespace,prefix:t.prefix});return await this.adminFetch(e,"GET")}async getKvValue(t){this.assertOpen();const e=f($,{key:t.key,namespace:t.namespace});return await this.adminFetch(e,"GET")}async putKvValue(t){this.assertOpen(),await this.adminFetch($,"PUT",t)}async deleteKvKey(t){this.assertOpen();const e=f($,{key:t.key,namespace:t.namespace});await this.adminFetch(e,"DELETE")}async listAuthUsers(t={}){this.assertOpen();const e=f(Nt,{filterField:t.filterField,filterValue:t.filterValue,limit:t.limit,offset:t.offset,search:t.search,searchField:t.searchField,sortBy:t.sortBy,sortDirection:t.sortDirection});return await this.adminFetch(e,"GET")}async createAuthUser(t){return await this.adminFetch(Wt,"POST",t)}async setAuthUserRole(t){return await this.adminFetch(zt,"POST",t)}async banAuthUser(t){return await this.adminFetch(Gt,"POST",t)}async unbanAuthUser(t){return await this.adminFetch(Dt,"POST",t)}async setAuthUserPassword(t){await this.adminFetch(jt,"POST",t)}async removeAuthUser(t){await this.adminFetch(Ht,"POST",t)}async impersonateAuthUser(t){return await this.adminFetch(Vt,"POST",t)}async revokeAuthSession(t){await this.adminFetch(Jt,"POST",t)}async revokeAuthUserSessions(t){await this.adminFetch(Xt,"POST",t)}async getAuthCapabilities(){return await this.adminFetch(Yt,"GET")}async updateAuthUser(t){return await this.adminFetch(Zt,"POST",t)}async listAuthAccounts(t){return await this.adminFetch(f(te,{userId:t.userId}),"GET")}async unlinkAuthAccount(t){await this.adminFetch(ee,"POST",t)}async listAuthPasskeys(t){return await this.adminFetch(f(se,{userId:t.userId}),"GET")}async deleteAuthPasskey(t){await this.adminFetch(ie,"POST",t)}async disableAuthTwoFactor(t){await this.adminFetch(ne,"POST",t)}async listAuthOrganizations(t={}){return await this.adminFetch(f(re,{limit:t.limit,offset:t.offset}),"GET")}async listAuthOrgMembers(t){const e=f(ae,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async listAuthOrgInvitations(t){const e=f(oe,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async removeAuthOrgMember(t){await this.adminFetch(ce,"POST",t)}async cancelAuthOrgInvitation(t){await this.adminFetch(he,"POST",t)}async getAuthConfig(){return await this.adminFetch(de,"GET")}async createAuthOrganization(t){return await this.adminFetch(ue,"POST",t)}async updateAuthOrganization(t){return await this.adminFetch(le,"POST",t)}async deleteAuthOrganization(t){await this.adminFetch(pe,"POST",t)}async addAuthOrgMember(t){return await this.adminFetch(me,"POST",t)}async inviteAuthOrgMember(t){return await this.adminFetch(fe,"POST",t)}async setAuthOrgMemberRole(t){return await this.adminFetch(ye,"POST",t)}async listAuthOrgTeams(t){const e=f(ge,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async createAuthOrgTeam(t){return await this.adminFetch(be,"POST",t)}async updateAuthOrgTeam(t){return await this.adminFetch(ve,"POST",t)}async removeAuthOrgTeam(t){await this.adminFetch(Se,"POST",t)}async listAuthOrgTeamMembers(t){const e=f(ke,{limit:t.limit,offset:t.offset,teamId:t.teamId});return await this.adminFetch(e,"GET")}async addAuthOrgTeamMember(t){return await this.adminFetch(we,"POST",t)}async removeAuthOrgTeamMember(t){await this.adminFetch(Ce,"POST",t)}async listAuthOrgRoles(t){const e=f(Te,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async createAuthOrgRole(t){return await this.adminFetch(Ie,"POST",t)}async updateAuthOrgRole(t){return await this.adminFetch(Oe,"POST",t)}async deleteAuthOrgRole(t){await this.adminFetch(Ee,"POST",t)}async listAuthSessions(t={}){this.assertOpen();const e=f(Bt,{limit:t.limit,offset:t.offset,userId:t.userId});return await this.adminFetch(e,"GET")}subscribe(t,e,s,i={}){this.assertOpen();const n=e??{},r=w.key(t.__lunoraRef,n,i.shardKey);let a=this.subscriptions.get(r);const o=s,c=i.onError;if(!a){this.nextSubId+=1;const u=`sub_${this.nextSubId.toString()}`,l=I(n),y=this.takeHydratedCache(t.__lunoraRef,l,i.shardKey);a={acked:!1,args:n,argsKey:l,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:t,id:u,lastValue:y?.value,optimisticLayers:[],serverBase:y?.value,serverCursor:y?.serverCursor,shardKey:i.shardKey,...y?.serverEpoch===void 0?{}:{serverEpoch:y.serverEpoch}},this.subscriptions.add(a)}if(a.callbacks.add(o),c&&a.errorCallbacks.add(c),i.onCheckpoint&&a.checkpointCallbacks.add(i.onCheckpoint),a.lastValue!==void 0)try{o(a.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(a);const d=a;return()=>{d.callbacks.delete(o),c&&d.errorCallbacks.delete(c),i.onCheckpoint&&d.checkpointCallbacks.delete(i.onCheckpoint),d.callbacks.size===0&&(this.sendOrQueueUnsubscribe(d.shardKey,d.id,"unsubscribe"),this.subscriptions.remove(d))}}subscribeShape(t,e,s={}){this.assertOpen(),this.nextShapeId+=1;const i=`shape_${this.nextShapeId.toString()}`,n={args:t.args,callbacks:new Set([e]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:i,name:t.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:t.args===void 0?void 0:k(t.args,`shape args for '${t.name}'`)};return this.shapeSubscriptions.set(i,n),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(n.shardKey,i,"shape_unsubscribe")}}stream(t,e,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new p("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;const i=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=s,r=e??{},{handle:a,iterable:o}=rt({maxBuffer:s.maxBuffer,onCancel:()=>{const u=this.getConnection(n);u&&g(u,{id:i,type:"unsubscribe"}),this.streams.delete(i)}});this.streams.set(i,{handle:a,shardKey:n}),this.ensureSocket(n);const c=this.getConnection(n),d={id:i,query:{args:k(r,`stream args for '${t.__lunoraRef}'`),functionPath:t.__lunoraRef,shardKey:n},type:"stream"};if(!(c?.wsState==="open"&&g(c,d))&&c){for(c.pendingStreams=c.pendingStreams??[];c.pendingStreams.length>=mt;){const u=c.pendingStreams.shift()?.id,l=u?this.streams.get(u):void 0;l&&(l.handle.fail(new p("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(u))}c.pendingStreams.push(d)}return o}httpStream(t,e,s={}){if(this.closed)throw new p("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");const i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return X(t,e,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const t of this.streams.values())t.handle.fail(new p("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(const t of this.connections.values())this.teardownConnection(t);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.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new p("INTERNAL","LunoraClient is closed")}teardownConnection(t){if(t.reconnectTimer!==void 0&&(clearTimeout(t.reconnectTimer),t.reconnectTimer=void 0),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),this.stopHeartbeat(t),t.socket){try{t.socket.close()}catch{}t.socket=void 0}t.wsState="closed"}createTabCoordinator(){const t=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new H({channelName:t,onBecomeLeader:()=>{for(const e of this.subscriptions.all())this.ensureSocket(e.shardKey),this.sendSubscribeIfOpen(e);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},onStopBeingLeader:()=>{for(const[e,s]of this.connections)this.teardownConnection(s),this.connections.delete(e);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},onConnectionStatus:(e,s)=>{if(s!==void 0&&s!==this.identityFingerprint())return;const i=e==="connected"&&this.leaderStatus!=="connected";this.leaderStatus=e,e==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),i&&this.flushAllOfflineQueues()},onSubscriptionData:(e,s,i,n,r)=>{if(r!==void 0&&r!==this.identityFingerprint())return;const a=this.subscriptions.get(e);a&&(a.serverBase=s,i!==void 0&&(a.serverCursor=i,n!==void 0&&(a.serverEpoch=n),F(a,i)),P(a,A(s,a.optimisticLayers)))},onSubscriptionError:(e,s)=>{const i=this.subscriptions.get(e);i&&E(i.errorCallbacks,s)},onSubscriptionSettled:(e,s,i,n,r,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;const o=this.subscriptions.get(e);if(o){this.ackAndAdvanceCursor(o,s,i),n!==void 0&&r===this.clientId&&(o.lastMutationId=Math.max(o.lastMutationId??0,n));for(const c of o.checkpointCallbacks)c({checkpoint:o.serverCursor,mutationId:o.lastMutationId})}}})}async enqueueOfflineMutation(t,e,s,i,n,r,a){const o=this.identityFingerprint();if(this.outbox){this.outboxMutationCounter+=1;const c=this.outboxMutationCounter;try{await this.outbox.enqueue({args:e,clientId:this.clientId,functionPath:t.__lunoraRef,idempotencyKey:`${this.clientId}:${String(c)}`,identity:o,mutationId:c,shardKey:s})}catch(d){throw O(n),d instanceof Error?d:new Error(String(d))}for(const d of r)d(void 0);return}return new Promise((c,d)=>{const u={args:e,functionPath:t.__lunoraRef,liveAwaiter:!0,id:i,clientId:this.clientId,identity:o,precondition:a,onCommit:l=>{for(const y of r)y(l)},reject:l=>{this.queuedIdentities.delete(i),O(n),d(l instanceof Error?l:new Error(String(l)))},resolve:c,shardKey:s};this.offlineQueue.enqueue(u),this.queuedOfflineShardKeys.add(s),u.id!==void 0&&this.queuedIdentities.set(u.id,o)})}async hydratePersistedQueue(){try{const t=await this.offlineQueue.hydrate();for(const e of t)this.queuedOfflineShardKeys.add(e),this.ensureSocket(e)}catch{}}hydrateAsOutboxLeader(){const t=()=>{this.hydratePersistedQueue().catch(()=>{})},e=globalThis.navigator?.locks;if(!e){t();return}e.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||t(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(t)}async hydrateQueryCache(){if(this.queryCache)try{const t=await this.queryCache.load();for(const{key:e,...s}of t){if(et(this.persistenceVersion,s.version)){this.queryCache.remove(e).catch(()=>{});continue}this.hydratedQueryCache.set(e,s)}}catch{}}takeHydratedCache(t,e,s){const i=R(t,e,s),n=this.hydratedQueryCache.get(i);if(n!==void 0)return this.hydratedQueryCache.delete(i),n.identity===this.identityFingerprint()?n:void 0}persistQueryValue(t){const e=t.serverBase;if(!this.queryCache||e===void 0)return;const s=R(t.fn.__lunoraRef,t.argsKey,t.shardKey);this.pendingCacheWrites.set(s,{identity:this.identityFingerprint(),serverCursor:t.serverCursor,ts:Date.now(),value:e,...t.serverEpoch===void 0?{}:{serverEpoch:t.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},pt)}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;const{queryCache:t}=this;if(!t){this.pendingCacheWrites.clear();return}const e=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(e.map(([s,i])=>t.put(s,i)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";const t=[...this.connections.values()];return t.length===0?"idle":t.some(e=>e.wsState==="open")?"connected":t.some(e=>e.wsState==="connecting")?"connecting":"offline"}emitConnectionStatus(){const t=this.computeStatus();t!==this.lastStatus&&(this.lastStatus=t,this.statusListeners.emit(t),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(t,this.identityFingerprint()))}emitItemSettled(t,e,s){this.mutationSettledListeners.emit({args:t.args,code:s===void 0?void 0:s.code,error:s,functionPath:t.functionPath,hadAwaiter:t.liveAwaiter??!1,id:t.id??"",shardKey:t.shardKey,status:e})}applyOptimisticUpdates(t,e,s,i){const n=[],r=[];if(!i)return{confirms:n,rollbacks:r};const a=w.key(t,e,s),o=this.subscriptions.get(a);if(o){const c=Y(o,i);c&&(n.push(c.confirm),r.push(c.rollback))}return{confirms:n,rollbacks:r}}applyOptimisticUpdate(t,e,s,i,n){const{confirms:r,rollbacks:a,store:o}=Z(this.subscriptions,s);try{t(o,e)}catch{O(a);return}i.push(...a),n.push(...r)}getConnection(t){return this.connections.get(m(t))}sendOrQueueUnsubscribe(t,e,s){const i=this.getConnection(t);i&&!g(i,{id:e,type:s})&&i.pendingUnsubscribes.push({id:e,type:s})}connectionGateState(t){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let s="idle";return this.leaderStatus==="connected"?s="open":this.leaderStatus==="connecting"&&(s="connecting"),{hasSocket:!1,wasEverConnected:this.leaderWasEverConnected,wsState:s}}const e=this.getConnection(t);return{hasSocket:e?.socket!==void 0,wasEverConnected:e?.wasEverConnected??!1,wsState:e?.wsState??"idle"}}getOrCreateConnection(t){const e=m(t);let s=this.connections.get(e);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],reconnect:q(this.reconnectOptions),reconnectTimer:void 0,shardKey:t,socket:void 0,wasEverConnected:!1,wsState:"idle"},this.connections.set(e,s)),s}wsUrlFor(t,e){const s=[];if(t!==void 0&&s.push(`shard=${encodeURIComponent(t)}`),e!==void 0&&s.push(`token=${encodeURIComponent(e)}`),s.length===0)return this.wsUrl;const i=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${i}${s.join("&")}`}rpcRequestHeaders(t){const e={"content-type":"application/json"};if(this.authToken&&(e.authorization=`Bearer ${this.authToken}`),t.mutationId&&(e["x-lunora-mutation-id"]=t.mutationId),(t.clientId!==void 0||t.mutationId!==void 0)&&(e["x-lunora-client-id"]=t.clientId??this.clientId),t.clientSeq!==void 0&&(e["x-lunora-client-seq"]=t.clientSeq.toString()),t.attachBookmark){const s=this.bookmark.get();s&&(e["x-d1-bookmark"]=s)}return e}async rpc(t,e,s,i={}){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");const n=this.rpcRequestHeaders(i),r=await this.fetchImpl(S(this.url,ot),{body:JSON.stringify({args:k(e,`args for '${t}'`),functionPath:t,shardKey:s}),headers:n,method:"POST"});if(i.captureBookmark){const o=r.headers.get("x-d1-bookmark");o&&this.bookmark.set(o)}let a;try{a=await r.json()}catch{const o=r.statusText?` ${r.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${r.status.toString()}${o})`)}if("error"in a)throw T(a.error);if(!r.ok){const o=r.statusText?` ${r.statusText}`:"";throw new p("INTERNAL",`LunoraClient: request failed (status ${r.status.toString()}${o})`)}return i.onMutationAck?.(a.lastMutationId),i.onCommitCursor?.(a.commitCursor),b(a.result)}async adminFetch(t,e,s,i){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");const n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);const r=s instanceof ArrayBuffer||s instanceof Blob;let a;s===void 0?a=void 0:r?(a=s,i!==void 0&&(n["content-type"]=i)):(a=JSON.stringify(s),n["content-type"]="application/json");const o=await this.fetchImpl(S(this.url,t),{body:a,headers:n,method:e});let c;try{c=await o.json()}catch{const d=o.statusText?` ${o.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${o.status.toString()}${d})`)}if(typeof c=="object"&&c!==null&&"error"in c){const d=c.error,u=new Error(d.message??"admin request failed");throw u.code=d.code,u}if(!o.ok){const d=o.statusText?` ${o.statusText}`:"";throw new p("INTERNAL",`LunoraClient: admin request failed (status ${o.status.toString()}${d})`)}return c}effectiveConnectionContext(t){const e=this.connectionContextHolders.get(t);return e&&e.length>0?e[e.length-1]?.context:this.connectionContexts.get(t)??this.defaultConnectionContext}refreshConnectionContext(t){const e=this.connections.get(t);e?.wsState==="open"&&this.sendConnectEnvelope(e)}sendConnectEnvelope(t){const e=this.effectiveConnectionContext(m(t.shardKey));g(t,{clientId:this.clientId,id:"connect",type:"connect",...e===void 0?{}:{context:e}})}resendShapeSubscriptions(t){for(const e of this.shapeSubscriptions.values())m(e.shardKey)===m(t)&&this.sendShapeSubscribeIfOpen(e)}ensureSocket(t){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const e=this.getOrCreateConnection(t);if(!(e.wsState==="open"||e.wsState==="connecting")){if(e.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(e,t,this.wsToken).catch(()=>{});return}this.openSocket(e,t,this.wsToken)}}async openSocketWithProvidedToken(t,e,s){let i;try{i=await s()}catch{this.handleDisconnect(t);return}this.closed||this.WebSocketImpl===void 0||t.wsState!=="connecting"||t.socket!==void 0||this.openSocket(t,e,i)}openManagedSocket(t,e,s,i){const{WebSocketImpl:n}=this;if(n===void 0)throw new p("INTERNAL","no WebSocket implementation available");const r=new n(e);t.socket=r;const a=()=>{this.stopHeartbeat(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket===r&&(t.socket=void 0)},o=c=>{a(),i.onClose(c)};s>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===r){try{r.close()}catch{}o()}},s)),r.addEventListener("open",()=>{t.socket===r&&(t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.lastFrameAt=Date.now(),i.onOpen(),this.startHeartbeat(t,o))}),r.addEventListener("message",c=>{t.socket===r&&(t.lastFrameAt=Date.now(),i.onMessage(c))}),r.addEventListener("close",c=>{t.socket===r&&o(c)}),r.addEventListener("error",()=>{t.socket===r&&o()})}openSocket(t,e,s){this.WebSocketImpl!==void 0&&this.openManagedSocket(t,this.wsUrlFor(e,s),this.connectTimeoutMs,{onClose:i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(t)},onMessage:i=>{this.handleServerMessage(i.data,e)},onOpen:()=>{t.wsState="open",t.wasEverConnected=!0,t.reconnect.reset(),this.emitConnectionStatus(),this.sendConnectEnvelope(t),this.markShardPendingAck(e);for(const n of this.subscriptions.all())m(n.shardKey)===m(e)&&this.sendSubscribeIfOpen(n);if(this.resendShapeSubscriptions(e),t.pendingUnsubscribes.length>0){const n=t.pendingUnsubscribes;t.pendingUnsubscribes=[];for(const{id:r,type:a}of n)g(t,{id:r,type:a})}if(t.pendingStreams&&t.pendingStreams.length>0){const n=t.pendingStreams;t.pendingStreams=[];for(const r of n)g(t,r)}const i=this.whisperHandlers.get(m(e));if(i)for(const n of i.keys())g(t,{topic:n,type:"whisper_subscribe"});this.flushOfflineQueue(e).catch(()=>{})}})}handleDisconnect(t){if(this.closed||t.wsState==="idle"||t.wsState==="closed")return;this.stopHeartbeat(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket=void 0,t.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(t.shardKey);const e=new Set((t.pendingStreams??[]).map(i=>i.id));for(const[i,n]of this.streams)m(n.shardKey)===m(t.shardKey)&&!e.has(i)&&(n.handle.fail(new p("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.streams.delete(i));if(this.WebSocketImpl===void 0)return;const s=t.reconnect.next();t.reconnectTimer=setTimeout(()=>{t.reconnectTimer=void 0,this.ensureSocket(t.shardKey)},s)}startHeartbeat(t,e){this.stopHeartbeat(t),!(this.heartbeatIntervalMs<=0)&&(t.heartbeatTimer=setInterval(()=>{if(!t.socket)return;const{socket:s}=t;if(Date.now()-t.lastFrameAt>this.heartbeatIntervalMs*2.5){try{s.close()}catch{}e();return}try{s.send(dt)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(t){t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)}markShardPendingAck(t){const e=m(t);for(const s of this.subscriptions.all())m(s.shardKey)===e&&(s.acked=!1)}sendSubscribeIfOpen(t){const e=this.getConnection(t.shardKey);if(e?.wsState!=="open"||t.acked)return;const s=t.fn.__lunoraTable??t.fn.__lunoraRef;g(e,{id:t.id,query:{args:B(t.args),functionPath:t.fn.__lunoraRef,table:s,...t.serverCursor===void 0?{}:{sinceSeq:t.serverCursor},...t.serverEpoch===void 0?{}:{sinceEpoch:t.serverEpoch}},type:"subscribe"})}sendShapeSubscribeIfOpen(t){const e=this.getConnection(t.shardKey);e?.wsState==="open"&&g(e,{id:t.id,shape:{name:t.name,...t.wireArgs===void 0?{}:{args:t.wireArgs}},type:"shape_subscribe",...t.serverCursor===void 0?{}:{sinceCheckpoint:t.serverCursor},...t.serverEpoch===void 0?{}:{sinceEpoch:t.serverEpoch}})}handleServerMessage(t,e){const s=Re(t);if(s===void 0)return;let i;try{i=JSON.parse(s)}catch{return}switch(i.type){case"ack":{const n=this.subscriptions.getById(i.id);n&&(n.acked=!0);return}case"chunk":{const{data:n,id:r}=i;this.streams.get(r)?.handle.push(b(n));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"pokeEnd":{this.handlePokeEnd(i);break}case"pokePart":{this.handlePokePart(i);break}case"pokeStart":{this.handlePokeStart(i);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,e);break}}}handleErrorMessage(t){if(t.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}const{id:e}=t,s=e===void 0?void 0:this.streams.get(e);if(s&&e!==void 0){s.handle.fail(Pe(t)),this.streams.delete(e);return}const i=e===void 0?void 0:this.subscriptions.getById(e);if(i){E(i.errorCallbacks,N(t));return}const n=e===void 0?void 0:this.shapeSubscriptions.get(e);n&&E(n.errorCallbacks,N(t))}handlePokeStart(t){at(this.pokeBuffers,z.MAX_POKE_BUFFERS),this.pokeBuffers.set(t.pokeId,{baseCheckpoint:t.baseCheckpoint,epoch:t.epoch,lastMutationId:new Map,parts:new Map})}handlePokePart(t){const e=this.pokeBuffers.get(t.pokeId);if(!e)return;const s=e.parts.get(t.shapeId)??[];for(const i of t.rowsPatch)s.push(i.value===void 0?i:{...i,value:b(i.value)});e.parts.set(t.shapeId,s),t.lastMutationId!==void 0&&e.lastMutationId.set(t.shapeId,t.lastMutationId)}handlePokeEnd(t){const e=this.pokeBuffers.get(t.pokeId);if(e){this.pokeBuffers.delete(t.pokeId);for(const[s,i]of e.parts){const n=this.shapeSubscriptions.get(s);if(!n)continue;const r=e.epoch!==void 0&&n.serverEpoch!==void 0&&e.epoch!==n.serverEpoch,a=e.baseCheckpoint!==void 0&&n.serverCursor!==void 0&&n.serverCursor!==e.baseCheckpoint;if(r||a){n.rows.clear(),n.serverCursor=void 0,n.serverEpoch=void 0,this.emitShapeRows(n),this.sendShapeSubscribeIfOpen(n);continue}ht(n.rows,i),t.checkpoint!==void 0&&(n.serverCursor=t.checkpoint),t.epoch!==void 0&&(n.serverEpoch=t.epoch);const o=e.lastMutationId.get(s);o!==void 0&&(n.lastMutationId=o),this.emitShapeRows(n),n.onCheckpoint?.({checkpoint:n.serverCursor,mutationId:n.lastMutationId})}}}emitShapeRows(t){const e=[...t.rows.values()];for(const s of t.callbacks)try{s(e)}catch{}}handleDataMessage(t){const{id:e}=t,s=e?this.subscriptions.getById(e):void 0;if(!s)return;const i=this.resolveDataPayload(t,s);if(s.serverBase=i,t.cursor!==void 0&&(s.serverCursor=t.cursor),t.epoch!==void 0&&(s.serverEpoch=t.epoch),t.lastMutationId!==void 0){s.lastMutationId=Math.max(s.lastMutationId??0,t.lastMutationId);for(const n of s.checkpointCallbacks)n({checkpoint:s.serverCursor,mutationId:s.lastMutationId})}if(this.persistQueryValue(s),F(s,s.serverCursor),P(s,A(i,s.optimisticLayers)),this.tabCoordinator?.isLeader()){const n=w.key(s.fn.__lunoraRef,s.args,s.shardKey);this.tabCoordinator.broadcastSubscriptionData(n,i,s.serverCursor,s.serverEpoch,this.identityFingerprint())}}handleResumeMessage(t){const e=this.subscriptions.getById(t.id);e&&this.ackAndAdvanceCursor(e,t.cursor,t.epoch)}handleSettledMessage(t){const e=this.subscriptions.getById(t.id);if(e){this.ackAndAdvanceCursor(e,t.cursor,t.epoch),t.lastMutationId!==void 0&&(e.lastMutationId=t.lastMutationId);for(const s of e.checkpointCallbacks)s({checkpoint:e.serverCursor,mutationId:e.lastMutationId});if(this.tabCoordinator?.isLeader()){const s=w.key(e.fn.__lunoraRef,e.args,e.shardKey);this.tabCoordinator.broadcastSubscriptionSettled(s,e.serverCursor,e.serverEpoch,e.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(t,e,s){t.acked=!0,(e!==void 0&&e!==t.serverCursor||s!==void 0&&s!==t.serverEpoch)&&(e!==void 0&&(t.serverCursor=e),s!==void 0&&(t.serverEpoch=s),this.persistQueryValue(t),F(t,t.serverCursor)&&P(t,A(t.serverBase,t.optimisticLayers)))}resolveDataPayload(t,e){if("data"in t&&t.data!==void 0)return b(t.data);const s=b(t.delta);if(V(s)&&e.serverBase!==void 0){const i=J(e.serverBase,s);if(i!==void 0)return i}return s}dispatchWhisper(t,e){const s=this.whisperHandlers.get(m(e))?.get(t.topic);if(!s)return;const i=b(t.data);for(const n of s)try{n(i,t.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(t){const e=this.streams.get(t);if(e){e.handle.complete(),this.streams.delete(t);return}const s=this.subscriptions.getById(t);s&&(s.acked=!1,E(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(t){t&&this.persistence?.remove(t).catch(e=>{st(this.onPersistenceError,"remove",e,t)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const t=this.authToken;return t===null?null:this.hashToken(t)}hashToken(t){let e=2166136261,s=5381;for(let i=0;i<t.length;i+=1){const n=t.charCodeAt(i);e^=n,e=Math.imul(e,16777619),s=Math.imul(s,33)+n}return`${t.length.toString(36)}:${(e>>>0).toString(36)}:${(s>>>0).toString(36)}`}isSameCredentialUnderTokenHash(t){if(t===null||t.startsWith("subj:"))return!1;const e=this.authToken;return e===null?!1:this.hashToken(e)===t}rejectQueuedForIdentityChange(){const t=this.offlineQueue.drain();for(const e of t){this.queuedIdentities.delete(e.id??""),this.unpersist(e.id);const s=new Error("offline mutation discarded: auth identity changed before replay");s.code="OFFLINE_IDENTITY_CHANGED",e.reject(s),this.emitItemSettled(e,"rejected",s)}this.clearQueryCacheForIdentityChange()}restampQueuedIdentity(t,e){for(const[s,i]of this.queuedIdentities)i===t&&this.queuedIdentities.set(s,e)}clearQueryCacheForIdentityChange(){this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}flushAllOfflineQueues(){for(const t of this.queuedOfflineShardKeys)this.flushOfflineQueue(t).catch(()=>{})}async flushOfflineQueue(t){const e=this.offlineQueue.drainConflict();for(const c of e){this.unpersist(c.id),this.queuedIdentities.delete(c.id??"");const d=new Error("offline mutation skipped: precondition failed before replay");d.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(c,"rejected",d)}const s=m(t),i=this.offlineQueue.drain(c=>m(c.shardKey)===s);if(i.length===0)return;const n=this.identityFingerprint(),r=[];for(const c of i)this.passesReplayIdentityGate(c,n)&&r.push(c);if(r.length===0)return;const a=this.encodableOrSettleTerminal(r);if(a.length===0)return;if(a.length===1){await this.replaySequential(a);return}const o=[];for(let c=0;c<a.length;c+=L){const d=a.slice(c,c+L),u=await this.replayBatched(d);if(o.push(...u.requeue),u.stop){o.push(...a.slice(c+L));break}}o.length>0&&this.offlineQueue.requeue(o)}encodableOrSettleTerminal(t){const e=[];for(const s of t)try{k(s.args,`args for '${s.functionPath}'`),e.push(s)}catch(i){this.settleReplayTerminal(s,i instanceof Error?i:new Error(String(i)))}return e}passesReplayIdentityGate(t,e){const s=t.id===void 0?void 0:this.queuedIdentities.get(t.id),i=s===void 0?t.identity:s;if(i!==void 0&&i!==e&&!this.isSameCredentialUnderTokenHash(i)){this.queuedIdentities.delete(t.id??""),this.unpersist(t.id);const n=new Error("offline mutation skipped: auth identity changed before replay");return n.code="OFFLINE_IDENTITY_CHANGED",t.reject(n),this.emitItemSettled(t,"rejected",n),!1}return this.queuedIdentities.delete(t.id??""),!0}settleReplaySuccess(t,e,s){this.unpersist(t.id),t.onCommit?.(s),t.resolve(e),this.emitItemSettled(t,"committed")}settleReplayTerminal(t,e){this.unpersist(t.id),t.reject(e),this.emitItemSettled(t,"rejected",e)}async replaySequential(t){for(let e=0;e<t.length;e+=1){const s=t[e];if(s)try{let i;const n=await this.rpc(s.functionPath,s.args,s.shardKey,{captureBookmark:!0,clientId:s.clientId??this.clientId,mutationId:s.id,onCommitCursor:r=>{i=r}});this.settleReplaySuccess(s,n,i)}catch(i){if(i.code!==void 0){this.settleReplayTerminal(s,i);continue}this.offlineQueue.requeue(t.slice(e));return}}}async replayBatched(t){if(!this.fetchImpl)return{requeue:t,stop:!0};let e;try{e=await this.fetchImpl(S(this.url,Q),{body:JSON.stringify({calls:t.map((n,r)=>({args:k(n.args,`args for '${n.functionPath}'`),functionPath:n.functionPath,id:r,clientId:n.clientId??this.clientId,mutationId:n.id,shardKey:n.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"})}catch{return{requeue:t,stop:!0}}const s=e.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let i;try{i=await e.json()}catch{return{requeue:t,stop:!0}}if(!i.results){if(i.error){const n=T(i.error);for(const r of t)this.settleReplayTerminal(r,n);return{requeue:[],stop:!1}}return{requeue:t,stop:!0}}return{requeue:this.settleReplayBatchSlots(t,i.results),stop:!1}}settleReplayBatchSlots(t,e){const s=new Map;for(const n of e)typeof n.id=="number"&&n.body!==void 0&&s.set(n.id,n.body);const i=[];for(const[n,r]of t.entries()){const a=s.get(n);a===void 0?i.push(r):"error"in a?Me.has(a.error.code)?i.push(r):this.settleReplayTerminal(r,T(a.error)):this.settleReplaySuccess(r,b(a.result),a.commitCursor)}return i}}export{z as LunoraClient};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{h as s,u as o,s as t}from"./offline-queue-
|
|
1
|
+
import{h as s,u as o,s as t}from"./offline-queue-CKMw-5rF.mjs";export{s as OfflineQueue,o as nextId,t as reportPersistenceError};
|
package/dist/packem_shared/{createServerClient-C1At_rrh.mjs → createServerClient-BKDKj3mJ.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraClient as r}from"./LunoraClient-
|
|
1
|
+
import{LunoraClient as r}from"./LunoraClient-CrIthWcp.mjs";const o=t=>{const e=new r({fetch:t.fetch,url:t.url});return t.token!==void 0&&e.setAuthToken(t.token),e};export{o as createServerClient};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, L as LunoraClientOptions, a as Unsubscribe, U as User, W as WsTokenProvider, S as ShardTrafficResult, b as ScheduleRecord, c as SchedulerStatus, d as WorkflowInstanceStatus, e as WorkflowInstancePage, f as WorkflowInstanceDetail, g as WorkflowInstanceAction, h as FunctionDescriptor, i as StorageListPage, G as GlobalTableInfo, j as GlobalFilterClause, k as GlobalTablePage, l as GlobalFacetResult, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf } from "./types.d-
|
|
1
|
+
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, L as LunoraClientOptions, a as Unsubscribe, U as User, W as WsTokenProvider, S as ShardTrafficResult, b as ScheduleRecord, c as SchedulerStatus, d as WorkflowInstanceStatus, e as WorkflowInstancePage, f as WorkflowInstanceDetail, g as WorkflowInstanceAction, h as FunctionDescriptor, i as StorageListPage, G as GlobalTableInfo, j as GlobalFilterClause, k as GlobalTablePage, l as GlobalFacetResult, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf } from "./types.d-MI8BwMXt.mjs";
|
|
2
2
|
import { CronJobInfo, VectorIndexSummary, VectorQueryMatch, PipelineLogQuery, PipelineLogPage, KvNamespaceSummary, KvKeyListResult, KvValueResult, AuthUser, AuthPage, AuthImpersonation, AuthCapabilities, AuthConfigInfo, AuthSession } from '@lunora/runtime';
|
|
3
3
|
/**
|
|
4
4
|
* Reactive key-value store for local-only client state.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, L as LunoraClientOptions, a as Unsubscribe, U as User, W as WsTokenProvider, S as ShardTrafficResult, b as ScheduleRecord, c as SchedulerStatus, d as WorkflowInstanceStatus, e as WorkflowInstancePage, f as WorkflowInstanceDetail, g as WorkflowInstanceAction, h as FunctionDescriptor, i as StorageListPage, G as GlobalTableInfo, j as GlobalFilterClause, k as GlobalTablePage, l as GlobalFacetResult, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf } from "./types.d-
|
|
1
|
+
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, L as LunoraClientOptions, a as Unsubscribe, U as User, W as WsTokenProvider, S as ShardTrafficResult, b as ScheduleRecord, c as SchedulerStatus, d as WorkflowInstanceStatus, e as WorkflowInstancePage, f as WorkflowInstanceDetail, g as WorkflowInstanceAction, h as FunctionDescriptor, i as StorageListPage, G as GlobalTableInfo, j as GlobalFilterClause, k as GlobalTablePage, l as GlobalFacetResult, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf } from "./types.d-MI8BwMXt.js";
|
|
2
2
|
import { CronJobInfo, VectorIndexSummary, VectorQueryMatch, PipelineLogQuery, PipelineLogPage, KvNamespaceSummary, KvKeyListResult, KvValueResult, AuthUser, AuthPage, AuthImpersonation, AuthCapabilities, AuthConfigInfo, AuthSession } from '@lunora/runtime';
|
|
3
3
|
/**
|
|
4
4
|
* Reactive key-value store for local-only client state.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
let c=0;const a=()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();c+=1;const r=typeof crypto<"u"&&typeof crypto.getRandomValues=="function"?Array.from(crypto.getRandomValues(new Uint8Array(8)),e=>e.toString(16).padStart(2,"0")).join(""):Math.random().toString(16).slice(2,12);return`id_${Date.now().toString(36)}_${c.toString(36)}_${r}`},f=(r,e)=>r!==void 0&&e!==r,d=a,h=(r,e,t,s)=>{if(r){r({error:t,mutationId:s,operation:e});return}console.warn(`[lunora] offline-queue persistence ${e} failed`,t)};class u{queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;version;items=[];constructor(e={},t={}){this.maxItems=e.maxItems??1e3,this.queueBeforeFirstConnect=e.queueBeforeFirstConnect??!1,this.onPersistenceError=e.onPersistenceError,this.persistence=t.persistence,this.onEvict=t.onEvict,this.onSizeChange=t.onSizeChange,this.version=t.version}get size(){return this.items.length}enqueue(e){const t=e;t.id??=d(),this.items.push(t),this.persistence?.append({args:t.args,clientId:t.clientId,functionPath:t.functionPath,id:t.id,identity:t.identity,shardKey:t.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(s=>{h(this.onPersistenceError,"append",s,t.id)}),this.evictOverflow(),this.notifySize()}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(i){throw h(this.onPersistenceError,"load",i),i}const t=[];for(const i of e)if(!(this.items.some(o=>o.id===i.id)||t.some(o=>o.id===i.id))){if(f(this.version,i.version)){this.persistence.remove(i.id).catch(o=>{h(this.onPersistenceError,"remove",o,i.id)});continue}t.push({args:i.args,clientId:i.clientId,functionPath:i.functionPath,id:i.id,identity:i.identity,reject:()=>{},resolve:()=>{},shardKey:i.shardKey})}this.items.unshift(...t),this.evictOverflow(),this.notifySize();const s=new Set(this.items),n=new Set;for(const i of t)s.has(i)&&n.add(i.shardKey);return[...n]}drain(e){if(!e){const n=[...this.items];return this.items.length=0,this.notifySize(),n}const t=[],s=[];for(const n of this.items)(e(n)?t:s).push(n);return this.items.length=0,this.items.push(...s),this.notifySize(),t}requeue(e){e.length!==0&&(this.items.unshift(...e),this.notifySize())}drainConflict(){const e=[],t=[];for(const s of this.items)if(s.precondition!==void 0&&!s.precondition()){const n=new Error("offline mutation skipped: precondition failed before replay");n.code="OFFLINE_PRECONDITION_FAILED",s.reject(n),e.push(s)}else t.push(s);return e.length>0&&(this.items.length=0,this.items.push(...t),this.notifySize()),e}clear(){for(const e of this.items){const t=new Error("CLIENT_CLOSED");t.code="CLIENT_CLOSED",e.reject(t)}this.items.length=0,this.notifySize()}evictOverflow(){for(;this.items.length>this.maxItems;){const e=this.items.shift();if(e){e.id&&this.persistence?.remove(e.id).catch(s=>{h(this.onPersistenceError,"remove",s,e.id)});const t=new Error("offline queue overflow");t.code="OFFLINE_QUEUE_OVERFLOW",e.reject(t),this.onEvict?.(e,t)}}}notifySize(){this.onSizeChange?.(this.items.length)}}export{f as d,u as h,h as s,d as u};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { L as LunoraClient } from "./lunora-client.d-
|
|
2
|
-
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./types.d-
|
|
1
|
+
import { L as LunoraClient } from "./lunora-client.d-B-hIlqf_.mjs";
|
|
2
|
+
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./types.d-MI8BwMXt.mjs";
|
|
3
3
|
/**
|
|
4
4
|
* Run a query once on the server (during SSR) and capture its result in a
|
|
5
5
|
* serializable {@link Preloaded} token. Embed the token in the rendered HTML and
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { L as LunoraClient } from "./lunora-client.d-
|
|
2
|
-
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./types.d-
|
|
1
|
+
import { L as LunoraClient } from "./lunora-client.d-Rv8-L9mJ.js";
|
|
2
|
+
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./types.d-MI8BwMXt.js";
|
|
3
3
|
/**
|
|
4
4
|
* Run a query once on the server (during SSR) and capture its result in a
|
|
5
5
|
* serializable {@link Preloaded} token. Embed the token in the rendered HTML and
|
|
@@ -136,6 +136,15 @@ interface OfflineQueueOptions {
|
|
|
136
136
|
*/
|
|
137
137
|
interface PersistedMutation {
|
|
138
138
|
args: Record<string, unknown>;
|
|
139
|
+
/**
|
|
140
|
+
* The client id that queued this write, persisted so a replay after a reload
|
|
141
|
+
* lands in the SAME server-side dedup namespace it was issued under. The
|
|
142
|
+
* standalone client's own `clientId` is minted per session, so replaying under
|
|
143
|
+
* the live one would miss the `__idempotency` row for an anonymous caller and
|
|
144
|
+
* re-run a write the server already committed. Absent on records written by
|
|
145
|
+
* older client versions, which replay under the live id.
|
|
146
|
+
*/
|
|
147
|
+
clientId?: string;
|
|
139
148
|
functionPath: string;
|
|
140
149
|
id: string;
|
|
141
150
|
/**
|
|
@@ -136,6 +136,15 @@ interface OfflineQueueOptions {
|
|
|
136
136
|
*/
|
|
137
137
|
interface PersistedMutation {
|
|
138
138
|
args: Record<string, unknown>;
|
|
139
|
+
/**
|
|
140
|
+
* The client id that queued this write, persisted so a replay after a reload
|
|
141
|
+
* lands in the SAME server-side dedup namespace it was issued under. The
|
|
142
|
+
* standalone client's own `clientId` is minted per session, so replaying under
|
|
143
|
+
* the live one would miss the `__idempotency` row for an anonymous caller and
|
|
144
|
+
* re-run a write the server already committed. Absent on records written by
|
|
145
|
+
* older client versions, which replay under the live id.
|
|
146
|
+
*/
|
|
147
|
+
clientId?: string;
|
|
139
148
|
functionPath: string;
|
|
140
149
|
id: string;
|
|
141
150
|
/**
|
package/dist/query/index.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, a as Unsubscribe } from "../packem_shared/types.d-
|
|
2
|
-
import { S as SubscriptionError, L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
3
|
-
export type { a as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-
|
|
1
|
+
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, a as Unsubscribe } from "../packem_shared/types.d-MI8BwMXt.mjs";
|
|
2
|
+
import { S as SubscriptionError, L as LunoraClient } from "../packem_shared/lunora-client.d-B-hIlqf_.mjs";
|
|
3
|
+
export type { a as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-B-hIlqf_.mjs";
|
|
4
4
|
import '@lunora/runtime';
|
|
5
5
|
/**
|
|
6
6
|
* The sentinel a framework adapter resolves its reactive args to when it wants
|
package/dist/query/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, a as Unsubscribe } from "../packem_shared/types.d-
|
|
2
|
-
import { S as SubscriptionError, L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
3
|
-
export type { a as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-
|
|
1
|
+
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, a as Unsubscribe } from "../packem_shared/types.d-MI8BwMXt.js";
|
|
2
|
+
import { S as SubscriptionError, L as LunoraClient } from "../packem_shared/lunora-client.d-Rv8-L9mJ.js";
|
|
3
|
+
export type { a as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-Rv8-L9mJ.js";
|
|
4
4
|
import '@lunora/runtime';
|
|
5
5
|
/**
|
|
6
6
|
* The sentinel a framework adapter resolves its reactive args to when it wants
|
package/dist/service.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./packem_shared/types.d-
|
|
1
|
+
import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./packem_shared/types.d-MI8BwMXt.mjs";
|
|
2
2
|
/**
|
|
3
3
|
* The wire endpoint every Lunora Worker serves. Matches `createWorker`'s RPC
|
|
4
4
|
* route; the envelope shape below is that route's documented contract.
|
package/dist/service.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./packem_shared/types.d-
|
|
1
|
+
import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./packem_shared/types.d-MI8BwMXt.js";
|
|
2
2
|
/**
|
|
3
3
|
* The wire endpoint every Lunora Worker serves. Matches `createWorker`'s RPC
|
|
4
4
|
* route; the envelope shape below is that route's documented contract.
|
package/dist/ssr/index.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { P as Preloaded } from "../packem_shared/types.d-
|
|
2
|
-
export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/types.d-
|
|
3
|
-
export { p as preloadQuery, a as preloadedQueryResult } from "../packem_shared/preload.d-
|
|
4
|
-
import { L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
1
|
+
import { P as Preloaded } from "../packem_shared/types.d-MI8BwMXt.mjs";
|
|
2
|
+
export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/types.d-MI8BwMXt.mjs";
|
|
3
|
+
export { p as preloadQuery, a as preloadedQueryResult } from "../packem_shared/preload.d-C6emVQoK.mjs";
|
|
4
|
+
import { L as LunoraClient } from "../packem_shared/lunora-client.d-B-hIlqf_.mjs";
|
|
5
5
|
import '@lunora/runtime';
|
|
6
6
|
/**
|
|
7
7
|
* Structural shape of a better-auth `getSession` call's resolved value.
|
package/dist/ssr/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { P as Preloaded } from "../packem_shared/types.d-
|
|
2
|
-
export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/types.d-
|
|
3
|
-
export { p as preloadQuery, a as preloadedQueryResult } from "../packem_shared/preload.d-
|
|
4
|
-
import { L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
1
|
+
import { P as Preloaded } from "../packem_shared/types.d-MI8BwMXt.js";
|
|
2
|
+
export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/types.d-MI8BwMXt.js";
|
|
3
|
+
export { p as preloadQuery, a as preloadedQueryResult } from "../packem_shared/preload.d-CBi9DddN.js";
|
|
4
|
+
import { L as LunoraClient } from "../packem_shared/lunora-client.d-Rv8-L9mJ.js";
|
|
5
5
|
import '@lunora/runtime';
|
|
6
6
|
/**
|
|
7
7
|
* Structural shape of a better-auth `getSession` call's resolved value.
|
package/dist/ssr/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getServerSession as o}from"../packem_shared/getServerSession-CGjgRBAE.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-CHfOFpka.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-
|
|
1
|
+
import{getServerSession as o}from"../packem_shared/getServerSession-CGjgRBAE.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-CHfOFpka.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-BKDKj3mJ.mjs";import{preloadQuery as s,preloadedQueryResult as f}from"../packem_shared/preloadQuery-DjwSjFwt.mjs";export{i as createServerClient,l as deserializePreloaded,o as getServerSession,s as preloadQuery,f as preloadedQueryResult,t as serializePreloaded};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/client",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.43",
|
|
4
4
|
"description": "Lunora browser SDK: WebSocket transport, optimistic updates, and an offline mutation queue",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -70,7 +70,7 @@
|
|
|
70
70
|
"access": "public"
|
|
71
71
|
},
|
|
72
72
|
"dependencies": {
|
|
73
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
73
|
+
"@lunora/errors": "1.0.0-alpha.16",
|
|
74
74
|
"@visulima/storage-client": "1.0.0"
|
|
75
75
|
},
|
|
76
76
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as p}from"@lunora/errors";import{s as b,a as B}from"./wire-codec-D_fiax9d.mjs";import{t as I}from"./wire-key-j8BZ65HQ.mjs";import D from"./createInMemoryBookmarkStorage-DCd5Ej-t.mjs";import{ClientQueryStore as j}from"./createClientQuery-CrdRoicO.mjs";import{TabCoordinator as H}from"./TabCoordinator-CMFYQCL-.mjs";import{isMutationDelta as V,applyDelta as J}from"./applyDelta-DXqQORbM.mjs";import{httpStream as X}from"./httpStream-Cz4_QyjV.mjs";import{d as F,n as P,f as A,a as Y,c as Z}from"./local-store-DFMSEM2j.mjs";import{h as tt,u as K,d as et,s as st}from"./offline-queue-BeWay5u5.mjs";import{resolvePersistenceAdapter as nt}from"./createInMemoryPersistence-CQYXy8UP.mjs";import{resolveQueryCacheAdapter as it,queryCacheKey as R}from"./createInMemoryQueryCache-DjCKrLjk.mjs";import{createReconnect as q}from"./createReconnect-CFT7YRSR.mjs";import{createStream as rt}from"./DEFAULT_MAX_BUFFER-TBn2s7Rz.mjs";import{SubscriptionRegistry as w}from"./SubscriptionRegistry-C72rCp44.mjs";const L=500,at=(h,t)=>{if(h.size<t)return;const e=h.keys().next().value;e!==void 0&&h.delete(e)};class C{listeners=new Set;add(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}emit(...t){const[e]=t;for(const s of this.listeners)try{s(e)}catch{}}clear(){this.listeners.clear()}}const ot="/_lunora/rpc",Q="/_lunora/rpc-batch",ct="/_lunora/ws",M=h=>h===void 0||h===""?"":`&bucket=${encodeURIComponent(h)}`,O=h=>{for(let t=h.length-1;t>=0;t-=1)h[t]?.()},ht=(h,t)=>{for(const e of t)e.op==="delete"?h.delete(e.key):e.value!==void 0&&h.set(e.key,e.value)},dt="lunora-ping",ut=3e4,lt=1e4,pt=250,mt=64,ft="/_lunora/admin/shard-traffic",yt="/_lunora/admin/scheduled",gt="/_lunora/admin/scheduled/status",bt="/_lunora/admin/scheduled/ws",vt="/_lunora/admin/scheduled/cancel",St="/_lunora/admin/scheduled/dead",kt="/_lunora/admin/scheduled/dead/retry",wt="/_lunora/admin/scheduled/dead/cancel",Ct="/_lunora/admin/workflows/instances",Tt="/_lunora/admin/workflows/instance",It="/_lunora/admin/workflows/status",x="/_lunora/admin/storage",Ot="/_lunora/admin/storage/url",Et="/_lunora/admin/storage/buckets",_t="/_lunora/admin/functions",Ft="/_lunora/admin/cron-jobs",Pt="/_lunora/admin/cron-jobs/run",At="/_lunora/admin/openapi",Rt="/_lunora/admin/openrpc",Lt="/_lunora/admin/global/tables",Mt="/_lunora/admin/global/table",xt="/_lunora/admin/global/facet",$t="/_lunora/admin/vector/indexes",Kt="/_lunora/admin/vector/query",qt="/_lunora/admin/logs/archive",Qt="/_lunora/admin/kv/namespaces",Ut="/_lunora/admin/kv/keys",$="/_lunora/admin/kv/value",Nt="/_lunora/admin/auth/users",Bt="/_lunora/admin/auth/sessions",Wt="/_lunora/admin/auth/users/create",zt="/_lunora/admin/auth/users/role",Gt="/_lunora/admin/auth/users/ban",Dt="/_lunora/admin/auth/users/unban",jt="/_lunora/admin/auth/users/password",Ht="/_lunora/admin/auth/users/remove",Vt="/_lunora/admin/auth/users/impersonate",Jt="/_lunora/admin/auth/sessions/revoke",Xt="/_lunora/admin/auth/sessions/revoke-all",Yt="/_lunora/admin/auth/capabilities",Zt="/_lunora/admin/auth/users/update",te="/_lunora/admin/auth/accounts",ee="/_lunora/admin/auth/accounts/unlink",se="/_lunora/admin/auth/passkeys",ne="/_lunora/admin/auth/passkeys/delete",ie="/_lunora/admin/auth/two-factor/disable",re="/_lunora/admin/auth/organizations",ae="/_lunora/admin/auth/organizations/members",oe="/_lunora/admin/auth/organizations/invitations",ce="/_lunora/admin/auth/organizations/members/remove",he="/_lunora/admin/auth/organizations/invitations/cancel",de="/_lunora/admin/auth/config",ue="/_lunora/admin/auth/organizations/create",le="/_lunora/admin/auth/organizations/update",pe="/_lunora/admin/auth/organizations/remove",me="/_lunora/admin/auth/organizations/members/add",fe="/_lunora/admin/auth/organizations/members/invite",ye="/_lunora/admin/auth/organizations/members/role",ge="/_lunora/admin/auth/organizations/teams",be="/_lunora/admin/auth/organizations/teams/create",ve="/_lunora/admin/auth/organizations/teams/update",Se="/_lunora/admin/auth/organizations/teams/remove",ke="/_lunora/admin/auth/organizations/teams/members",we="/_lunora/admin/auth/organizations/teams/members/add",Ce="/_lunora/admin/auth/organizations/teams/members/remove",Te="/_lunora/admin/auth/organizations/roles",Ie="/_lunora/admin/auth/organizations/roles/create",Oe="/_lunora/admin/auth/organizations/roles/update",Ee="/_lunora/admin/auth/organizations/roles/remove",_e="/api/auth",Fe="/get-session",U=h=>h.startsWith("https://")?`wss://${h.slice(8)}`:h.startsWith("http://")?`ws://${h.slice(7)}`:h,S=(h,t)=>`${h.endsWith("/")?h.slice(0,-1):h}${t}`,f=(h,t)=>{const e=new URLSearchParams;for(const[n,i]of Object.entries(t))i!==void 0&&i!==""&&e.set(n,String(i));const s=e.toString();return s===""?h:`${h}?${s}`},m=h=>h??"",W=(h,t)=>{const e=h.error,s=typeof e?.code=="string"?e.code:void 0,n=typeof e?.message=="string"?e.message:void 0;return{code:s,messageText:(typeof h.message=="string"?h.message:void 0)??n??t}},Pe=h=>{const{code:t,messageText:e}=W(h,"stream error");return t===void 0?new Error(e):new p(t,e)},N=h=>{const{code:t,messageText:e}=W(h,"subscription error");return{message:e,...t===void 0?{}:{code:t}}},E=(h,t)=>{for(const e of h)try{e(t)}catch{}},Ae=new TextDecoder,Re=h=>{if(typeof h=="string")return h;if(h instanceof ArrayBuffer)return Ae.decode(h)},g=(h,t)=>{if(!h.socket||h.wsState!=="open")return!1;try{return h.socket.send(JSON.stringify(t)),!0}catch{return!1}},T=h=>{const t=new Error(h.message??"request failed");return t.code=h.code,h.data!==void 0&&(t.data=b(h.data)),h.hint!==void 0&&(t.hint=h.hint),h.docsUrl!==void 0&&(t.docsUrl=h.docsUrl),t},k=(h,t)=>{try{return B(h)}catch(e){const s=e instanceof Error?e.message:String(e);throw new TypeError(`LunoraClient: cannot encode ${t} — ${s}`,e instanceof Error?{cause:e}:void 0)}},Le=(h,t)=>{const e=Array.from({length:t});for(const s of h){if(typeof s.id!="number"||s.id<0||s.id>=t)continue;const n=s.body;e[s.id]=n&&"error"in n&&n.error?{error:T(n.error),ok:!1}:{ok:!0,value:b(n?.result)}}return e.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},Me=new Set(["SHARD_ERROR","SHARD_UNAVAILABLE"]),xe=Promise.resolve();class z{static MAX_POKE_BUFFERS=256;static createClientQuery(t,e){return{defaultValue:e,key:t}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;offlineQueue;outbox;clientId;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new w;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new C;statusListeners=new C;tokenExpiredListeners=new C;mutationSettledListeners=new C;pendingChangeListeners=new C;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(t){this.url=t.url,this.wsUrl=t.wsUrl??S(U(t.url),ct),this.wsToken=t.wsToken;const e=t.authBasePath??_e;this.authBasePath=e.endsWith("/")?e.slice(0,-1):e,this.fetchImpl=t.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=t.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=t.bookmarkStorage??D(),this.reconnectOptions=t.reconnect,this.heartbeatIntervalMs=t.heartbeatIntervalMs??ut,this.connectTimeoutMs=t.connectTimeoutMs??lt,this.defaultConnectionContext=t.connectionContext,this.persistence=nt(t.persistence,t.outbox===void 0),this.persistenceVersion=t.persistenceVersion,this.queryCache=it(t.queryCache),this.onPersistenceError=t.offlineQueue?.onPersistenceError,this.clientQueryStore=new j,t.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,t.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=xe),this.offlineQueue=new tt(t.offlineQueue,{onEvict:(s,n)=>{this.emitItemSettled(s,"rejected",n)},onSizeChange:s=>{this.pendingChangeListeners.emit(s)},persistence:this.persistence,version:t.persistenceVersion}),this.outbox=t.outbox,this.clientId=t.clientId??`client-${K()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})})}setAuthToken(t,e){const s=this.authToken!==t,n=this.identityFingerprint();this.authToken=t,e!==void 0&&(this.authSubject=e);const i=this.identityFingerprint();if(i!==n&&(s?this.rejectQueuedForIdentityChange():this.restampQueuedIdentity(n,i),this.tabCoordinator)){const r=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),r&&this.tabCoordinator.promoteImmediately()}s&&this.authTokenListeners.emit(t)}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}clientIdentifier(){return this.clientId}confirmedMutationWatermark(t){return this.clientWatermarks.get(t??"")??0}async callMutator(t,e,s){const n=s?.clientSeq;if(n!==void 0&&(!Number.isInteger(n)||n<=0))throw new p("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(n)}`);const i=s?.shardKey??"";let r;const a=await this.rpc(t,e,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:n,onMutationAck:o=>{r=o}});return r!==void 0&&r>(this.clientWatermarks.get(i)??0)&&this.clientWatermarks.set(i,r),{applied:r===void 0||r===n,result:a}}onAuthTokenChange(t){return this.authTokenListeners.add(t)}async getCurrentUser(){if(this.closed||!this.fetchImpl)return null;const t={};this.authToken&&(t.authorization=`Bearer ${this.authToken}`);try{const e=await this.fetchImpl(S(this.url,`${this.authBasePath}${Fe}`),{credentials:"include",headers:t,method:"GET"});return e.ok?(await e.json())?.user??null:null}catch{return null}}setWsToken(t){if(this.wsToken!==t){this.wsToken=t;for(const e of this.connections.values())if(e.socket)try{e.socket.close()}catch{}}}setConnectionContext(t,e={}){const s=m(e.shardKey);t===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,t),this.refreshConnectionContext(s)}acquireConnectionContext(t,e={}){const s=m(e.shardKey),n={context:t},i=this.connectionContextHolders.get(s);i?i.push(n):this.connectionContextHolders.set(s,[n]),this.refreshConnectionContext(s);let r=!1;return()=>{if(r)return;r=!0;const a=this.connectionContextHolders.get(s);if(!a)return;const o=a.indexOf(n);o!==-1&&a.splice(o,1),a.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s)}}whisperSubscribe(t,e,s={}){const n=m(s.shardKey);let i=this.whisperHandlers.get(n);i||(i=new Map,this.whisperHandlers.set(n,i));let r=i.get(t);const a=r===void 0;if(r||(r=new Set,i.set(t,r)),r.add(e),this.ensureSocket(s.shardKey),a){const o=this.getConnection(s.shardKey);o&&g(o,{topic:t,type:"whisper_subscribe"})}return()=>{const o=this.whisperHandlers.get(n),c=o?.get(t);if(!c?.delete(e)||c.size>0)return;o?.delete(t),o?.size===0&&this.whisperHandlers.delete(n);const d=this.getConnection(s.shardKey);d&&g(d,{topic:t,type:"whisper_unsubscribe"})}}whisper(t,e,s={}){this.ensureSocket(s.shardKey);const n=this.getConnection(s.shardKey);n&&g(n,{data:k(e??null,`whisper data for topic '${t}'`),topic:t,type:"whisper"})}onTokenExpired(t){return this.tokenExpiredListeners.add(t)}connectionStatus(){return this.computeStatus()}onConnectionStatus(t){const e=this.statusListeners.add(t);return t(this.computeStatus()),e}pendingCount(){return this.offlineQueue.size}debug(){const t=[],e=new Set([...this.connections.keys(),...this.clientWatermarks.keys()]);for(const n of e){const i=this.connections.get(n);t.push({confirmedMutationWatermark:this.clientWatermarks.get(n)??0,hasSocket:i?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:i?.wasEverConnected??!1,wsState:i?.wsState??"idle"})}const s=this.subscriptions.all().map(n=>({acked:n.acked,functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(const n of this.shapeSubscriptions.values())s.push({acked:n.serverCursor!==void 0,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:t.toSorted((n,i)=>(n.shardKey??"").localeCompare(i.shardKey??"")),subscriptions:s.toSorted((n,i)=>n.functionPath.localeCompare(i.functionPath))}}onPendingChange(t){const e=this.pendingChangeListeners.add(t);return t(this.offlineQueue.size),e}onMutationSettled(t){return this.mutationSettledListeners.add(t)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(t){return this.clientQueryStore.get(t)}setClientQuery(t,e){this.clientQueryStore.set(t,e)}subscribeClientQuery(t,e){return this.clientQueryStore.subscribe(t,e)}resetClientQuery(t){this.clientQueryStore.reset(t)}snapshotPrecondition(t,e,s){const n=this.peekActiveQueryValue(t.__lunoraRef,e,s),i=n===void 0?void 0:I(n);return()=>{const r=this.peekActiveQueryValue(t.__lunoraRef,e,s);return i===void 0&&r===void 0?!0:i===void 0||r===void 0?!1:I(r)===i}}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(t,e,s){if(!this.readyResolved)return;const n=I(e),i=R(t,n,s),r=this.hydratedQueryCache.get(i);if(r!==void 0)return r.identity===this.identityFingerprint()?r.value:void 0}peekActiveQueryValue(t,e,s){const n=w.key(t,e,s);return this.subscriptions.get(n)?.lastValue}async query(t,e,s={}){return this.assertOpen(),await this.rpc(t.__lunoraRef,e,s.shardKey,{attachBookmark:!0})}async batch(t){if(this.assertOpen(),!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");if(t.length===0)return[];const e=await this.fetchImpl(S(this.url,Q),{body:JSON.stringify({calls:t.map((i,r)=>({args:k(i.args??{},`args for batch call '${i.fn.__lunoraRef}'`),functionPath:i.fn.__lunoraRef,id:r,shardKey:i.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"}),s=e.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let n;try{n=await e.json()}catch{throw new p("INTERNAL",`LunoraClient: batch response was not JSON (status ${e.status.toString()})`)}if(!e.ok||n.error&&!n.results)throw n.error?T(n.error):new p("INTERNAL",`LunoraClient: batch request failed (status ${e.status.toString()})`);return Le(n.results??[],t.length)}async mutation(t,e,s={}){this.assertOpen();const n=e,i=s.mutationId??K(),{confirms:r,rollbacks:a}=this.applyOptimisticUpdates(t.__lunoraRef,n,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,e,s.shardKey,a,r);const{hasSocket:o,wasEverConnected:c,wsState:d}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:u}=this.offlineQueue,l=c||u,y=this.WebSocketImpl!==void 0&&l;if(d!=="open"&&!o&&y||d==="connecting"&&l)return this.enqueueOfflineMutation(t,n,s.shardKey,i,a,r,s.precondition);try{let v;const G=await this.rpc(t.__lunoraRef,n,s.shardKey,{captureBookmark:!0,mutationId:i,onCommitCursor:_=>{v=_}});for(const _ of r)_(v);return G}catch(v){throw O(a),v}}async action(t,e,s={}){return this.assertOpen(),await this.rpc(t.__lunoraRef,e,s.shardKey)}async importRows(t,e,s={}){this.assertOpen();const n=Math.max(1,Math.trunc(s.chunkSize??500)),i=s.toArgs??(c=>({rows:c})),r=e.length;let a=0,o=0;for(let c=0;c<r;c+=n){const d=e.slice(c,c+n),u=o;await this.mutation(t,i(d),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(u)}`},shardKey:s.shardKey}),o+=1,a+=d.length,s.onProgress?.({done:a,total:r})}return{chunks:o,imported:a}}async shardTraffic(t){this.assertOpen();const e=await this.adminFetch(ft,"POST",{table:t});return{failed:e.failed??0,ok:e.ok??0,shards:e.shards??[]}}async listScheduledJobs(){return this.assertOpen(),(await this.adminFetch(yt,"GET")).records??[]}async schedulerStatus(){this.assertOpen();const t=await this.adminFetch(gt,"GET");return{backlog:t.backlog??0,inFlight:t.inFlight??0,pools:t.pools??[]}}async cancelScheduledJob(t){return this.assertOpen(),{cancelled:(await this.adminFetch(vt,"POST",{id:t})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await this.adminFetch(St,"GET")).records??[]}async retryDeadJob(t){return this.assertOpen(),{retried:(await this.adminFetch(kt,"POST",{id:t})).retried===!0}}async removeDeadJob(t){return this.assertOpen(),{removed:(await this.adminFetch(wt,"POST",{id:t})).removed===!0}}async listWorkflowInstances(t){this.assertOpen();const e=new URLSearchParams({name:t.name});t.status!==void 0&&e.set("status",t.status),t.page!==void 0&&e.set("page",String(t.page)),t.perPage!==void 0&&e.set("perPage",String(t.perPage));const s=await this.adminFetch(`${Ct}?${e.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??t.perPage??0,totalCount:s.totalCount}}async getWorkflowInstance(t){this.assertOpen();const e=new URLSearchParams({id:t.id,name:t.name}),s=await this.adminFetch(`${Tt}?${e.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??t.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}}async setWorkflowInstanceStatus(t){return this.assertOpen(),{status:(await this.adminFetch(It,"POST",{action:t.action,id:t.id,name:t.name})).status??"unknown"}}subscribeScheduledJobs(t){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const e=S(U(this.url),bt),s=q(this.reconnectOptions),n={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let i,r=!1;const a=()=>{r||(i=setTimeout(d,s.next()))},o=u=>{if(r||this.WebSocketImpl===void 0)return;const l=u===void 0?e:`${e}?token=${encodeURIComponent(u)}`;this.openManagedSocket(n,l,this.connectTimeoutMs,{onClose:()=>{a()},onMessage:y=>{try{const v=JSON.parse(typeof y.data=="string"?y.data:"");v.type==="jobs"&&Array.isArray(v.records)&&t(v.records)}catch{}},onOpen:()=>{s.reset()}})},c=async u=>{let l;try{l=await u()}catch{a();return}o(l)},d=()=>{if(r||this.WebSocketImpl===void 0)return;const{wsToken:u}=this;if(typeof u=="function"){c(u).catch(()=>{});return}o(u)};return d(),()=>{r=!0,i!==void 0&&clearTimeout(i),n.connectTimer!==void 0&&(clearTimeout(n.connectTimer),n.connectTimer=void 0),this.stopHeartbeat(n),n.socket?.close()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(_t,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(Ft,"GET")).jobs??[]}async runCronJob(t){this.assertOpen();const e=await this.adminFetch(Pt,"POST",{name:t});return{name:e.name??t,ran:e.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(At,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(Rt,"GET")}async listStorageObjects(t={}){this.assertOpen();const e=f(x,{bucket:t.bucket,cursor:t.cursor,limit:t.limit,prefix:t.prefix}),s=await this.adminFetch(e,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(t,e){this.assertOpen();const s=`${x}?key=${encodeURIComponent(t)}${M(e?.bucket)}`,n=await this.adminFetch(s,"DELETE");return{deleted:n.deleted??!0,key:n.key??t}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(Et,"GET")).buckets??[]}async uploadStorageObject(t){this.assertOpen();const e=`${x}?key=${encodeURIComponent(t.key)}${M(t.bucket)}`,s=await this.adminFetch(e,"PUT",t.body,t.contentType);return{etag:s.etag,key:s.key??t.key}}async signedStorageUrl(t,e){this.assertOpen();const s=e?.expiresInSeconds,n=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,i=`${Ot}?key=${encodeURIComponent(t)}${n}${M(e?.bucket)}`,r=await this.adminFetch(i,"GET");if(typeof r.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return r.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(Lt,"GET")}async readGlobalTablePage(t){this.assertOpen();const e=new URLSearchParams({table:t.table});return t.limit!==void 0&&e.set("limit",String(t.limit)),t.offset!==void 0&&e.set("offset",String(t.offset)),t.filters!==void 0&&t.filters.length>0&&e.set("filters",JSON.stringify(t.filters)),await this.adminFetch(`${Mt}?${e.toString()}`,"GET")}async facetGlobalColumn(t){this.assertOpen();const e=new URLSearchParams({column:t.column,table:t.table});return t.limit!==void 0&&e.set("limit",String(t.limit)),t.filters!==void 0&&t.filters.length>0&&e.set("filters",JSON.stringify(t.filters)),await this.adminFetch(`${xt}?${e.toString()}`,"GET")}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch($t,"GET")).indexes??[]}async queryVectorIndex(t){return this.assertOpen(),(await this.adminFetch(Kt,"POST",t)).matches??[]}async queryLogArchive(t={}){this.assertOpen();const e=await this.adminFetch(qt,"POST",t);return{nextCursor:e.nextCursor,rows:e.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(Qt,"GET")).namespaces??[]}async listKvKeys(t){this.assertOpen();const e=f(Ut,{cursor:t.cursor,limit:t.limit,namespace:t.namespace,prefix:t.prefix});return await this.adminFetch(e,"GET")}async getKvValue(t){this.assertOpen();const e=f($,{key:t.key,namespace:t.namespace});return await this.adminFetch(e,"GET")}async putKvValue(t){this.assertOpen(),await this.adminFetch($,"PUT",t)}async deleteKvKey(t){this.assertOpen();const e=f($,{key:t.key,namespace:t.namespace});await this.adminFetch(e,"DELETE")}async listAuthUsers(t={}){this.assertOpen();const e=f(Nt,{filterField:t.filterField,filterValue:t.filterValue,limit:t.limit,offset:t.offset,search:t.search,searchField:t.searchField,sortBy:t.sortBy,sortDirection:t.sortDirection});return await this.adminFetch(e,"GET")}async createAuthUser(t){return await this.adminFetch(Wt,"POST",t)}async setAuthUserRole(t){return await this.adminFetch(zt,"POST",t)}async banAuthUser(t){return await this.adminFetch(Gt,"POST",t)}async unbanAuthUser(t){return await this.adminFetch(Dt,"POST",t)}async setAuthUserPassword(t){await this.adminFetch(jt,"POST",t)}async removeAuthUser(t){await this.adminFetch(Ht,"POST",t)}async impersonateAuthUser(t){return await this.adminFetch(Vt,"POST",t)}async revokeAuthSession(t){await this.adminFetch(Jt,"POST",t)}async revokeAuthUserSessions(t){await this.adminFetch(Xt,"POST",t)}async getAuthCapabilities(){return await this.adminFetch(Yt,"GET")}async updateAuthUser(t){return await this.adminFetch(Zt,"POST",t)}async listAuthAccounts(t){return await this.adminFetch(f(te,{userId:t.userId}),"GET")}async unlinkAuthAccount(t){await this.adminFetch(ee,"POST",t)}async listAuthPasskeys(t){return await this.adminFetch(f(se,{userId:t.userId}),"GET")}async deleteAuthPasskey(t){await this.adminFetch(ne,"POST",t)}async disableAuthTwoFactor(t){await this.adminFetch(ie,"POST",t)}async listAuthOrganizations(t={}){return await this.adminFetch(f(re,{limit:t.limit,offset:t.offset}),"GET")}async listAuthOrgMembers(t){const e=f(ae,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async listAuthOrgInvitations(t){const e=f(oe,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async removeAuthOrgMember(t){await this.adminFetch(ce,"POST",t)}async cancelAuthOrgInvitation(t){await this.adminFetch(he,"POST",t)}async getAuthConfig(){return await this.adminFetch(de,"GET")}async createAuthOrganization(t){return await this.adminFetch(ue,"POST",t)}async updateAuthOrganization(t){return await this.adminFetch(le,"POST",t)}async deleteAuthOrganization(t){await this.adminFetch(pe,"POST",t)}async addAuthOrgMember(t){return await this.adminFetch(me,"POST",t)}async inviteAuthOrgMember(t){return await this.adminFetch(fe,"POST",t)}async setAuthOrgMemberRole(t){return await this.adminFetch(ye,"POST",t)}async listAuthOrgTeams(t){const e=f(ge,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async createAuthOrgTeam(t){return await this.adminFetch(be,"POST",t)}async updateAuthOrgTeam(t){return await this.adminFetch(ve,"POST",t)}async removeAuthOrgTeam(t){await this.adminFetch(Se,"POST",t)}async listAuthOrgTeamMembers(t){const e=f(ke,{limit:t.limit,offset:t.offset,teamId:t.teamId});return await this.adminFetch(e,"GET")}async addAuthOrgTeamMember(t){return await this.adminFetch(we,"POST",t)}async removeAuthOrgTeamMember(t){await this.adminFetch(Ce,"POST",t)}async listAuthOrgRoles(t){const e=f(Te,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async createAuthOrgRole(t){return await this.adminFetch(Ie,"POST",t)}async updateAuthOrgRole(t){return await this.adminFetch(Oe,"POST",t)}async deleteAuthOrgRole(t){await this.adminFetch(Ee,"POST",t)}async listAuthSessions(t={}){this.assertOpen();const e=f(Bt,{limit:t.limit,offset:t.offset,userId:t.userId});return await this.adminFetch(e,"GET")}subscribe(t,e,s,n={}){this.assertOpen();const i=e??{},r=w.key(t.__lunoraRef,i,n.shardKey);let a=this.subscriptions.get(r);const o=s,c=n.onError;if(!a){this.nextSubId+=1;const u=`sub_${this.nextSubId.toString()}`,l=I(i),y=this.takeHydratedCache(t.__lunoraRef,l,n.shardKey);a={acked:!1,args:i,argsKey:l,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:t,id:u,lastValue:y?.value,optimisticLayers:[],serverBase:y?.value,serverCursor:y?.serverCursor,shardKey:n.shardKey,...y?.serverEpoch===void 0?{}:{serverEpoch:y.serverEpoch}},this.subscriptions.add(a)}if(a.callbacks.add(o),c&&a.errorCallbacks.add(c),n.onCheckpoint&&a.checkpointCallbacks.add(n.onCheckpoint),a.lastValue!==void 0)try{o(a.lastValue)}catch{}this.ensureSocket(n.shardKey),this.sendSubscribeIfOpen(a);const d=a;return()=>{d.callbacks.delete(o),c&&d.errorCallbacks.delete(c),n.onCheckpoint&&d.checkpointCallbacks.delete(n.onCheckpoint),d.callbacks.size===0&&(this.sendOrQueueUnsubscribe(d.shardKey,d.id,"unsubscribe"),this.subscriptions.remove(d))}}subscribeShape(t,e,s={}){this.assertOpen(),this.nextShapeId+=1;const n=`shape_${this.nextShapeId.toString()}`,i={args:t.args,callbacks:new Set([e]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:n,name:t.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:t.args===void 0?void 0:k(t.args,`shape args for '${t.name}'`)};return this.shapeSubscriptions.set(n,i),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(i),()=>{this.shapeSubscriptions.delete(n),this.sendOrQueueUnsubscribe(i.shardKey,n,"shape_unsubscribe")}}stream(t,e,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new p("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;const n=`stream_${this.nextStreamId.toString()}`,{shardKey:i}=s,r=e??{},{handle:a,iterable:o}=rt({maxBuffer:s.maxBuffer,onCancel:()=>{const u=this.getConnection(i);u&&g(u,{id:n,type:"unsubscribe"}),this.streams.delete(n)}});this.streams.set(n,{handle:a,shardKey:i}),this.ensureSocket(i);const c=this.getConnection(i),d={id:n,query:{args:k(r,`stream args for '${t.__lunoraRef}'`),functionPath:t.__lunoraRef,shardKey:i},type:"stream"};if(!(c?.wsState==="open"&&g(c,d))&&c){for(c.pendingStreams=c.pendingStreams??[];c.pendingStreams.length>=mt;){const u=c.pendingStreams.shift()?.id,l=u?this.streams.get(u):void 0;l&&(l.handle.fail(new p("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(u))}c.pendingStreams.push(d)}return o}httpStream(t,e,s={}){if(this.closed)throw new p("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");const n={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return X(t,e,{baseUrl:this.url,fetch:this.fetchImpl,headers:n,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const t of this.streams.values())t.handle.fail(new p("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(const t of this.connections.values())this.teardownConnection(t);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.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new p("INTERNAL","LunoraClient is closed")}teardownConnection(t){if(t.reconnectTimer!==void 0&&(clearTimeout(t.reconnectTimer),t.reconnectTimer=void 0),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),this.stopHeartbeat(t),t.socket){try{t.socket.close()}catch{}t.socket=void 0}t.wsState="closed"}createTabCoordinator(){const t=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new H({channelName:t,onBecomeLeader:()=>{for(const e of this.subscriptions.all())this.ensureSocket(e.shardKey),this.sendSubscribeIfOpen(e);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},onStopBeingLeader:()=>{for(const[e,s]of this.connections)this.teardownConnection(s),this.connections.delete(e);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},onConnectionStatus:(e,s)=>{if(s!==void 0&&s!==this.identityFingerprint())return;const n=e==="connected"&&this.leaderStatus!=="connected";this.leaderStatus=e,e==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),n&&this.flushAllOfflineQueues()},onSubscriptionData:(e,s,n,i,r)=>{if(r!==void 0&&r!==this.identityFingerprint())return;const a=this.subscriptions.get(e);a&&(a.serverBase=s,n!==void 0&&(a.serverCursor=n,i!==void 0&&(a.serverEpoch=i),F(a,n)),P(a,A(s,a.optimisticLayers)))},onSubscriptionError:(e,s)=>{const n=this.subscriptions.get(e);n&&E(n.errorCallbacks,s)},onSubscriptionSettled:(e,s,n,i,r,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;const o=this.subscriptions.get(e);if(o){this.ackAndAdvanceCursor(o,s,n),i!==void 0&&r===this.clientId&&(o.lastMutationId=Math.max(o.lastMutationId??0,i));for(const c of o.checkpointCallbacks)c({checkpoint:o.serverCursor,mutationId:o.lastMutationId})}}})}async enqueueOfflineMutation(t,e,s,n,i,r,a){const o=this.identityFingerprint();if(this.outbox){this.outboxMutationCounter+=1;const c=this.outboxMutationCounter;try{await this.outbox.enqueue({args:e,clientId:this.clientId,functionPath:t.__lunoraRef,idempotencyKey:`${this.clientId}:${String(c)}`,identity:o,mutationId:c,shardKey:s})}catch(d){throw O(i),d instanceof Error?d:new Error(String(d))}for(const d of r)d(void 0);return}return new Promise((c,d)=>{const u={args:e,functionPath:t.__lunoraRef,liveAwaiter:!0,id:n,identity:o,precondition:a,onCommit:l=>{for(const y of r)y(l)},reject:l=>{this.queuedIdentities.delete(n),O(i),d(l instanceof Error?l:new Error(String(l)))},resolve:c,shardKey:s};this.offlineQueue.enqueue(u),this.queuedOfflineShardKeys.add(s),u.id!==void 0&&this.queuedIdentities.set(u.id,o)})}async hydratePersistedQueue(){try{const t=await this.offlineQueue.hydrate();for(const e of t)this.queuedOfflineShardKeys.add(e),this.ensureSocket(e)}catch{}}hydrateAsOutboxLeader(){const t=()=>{this.hydratePersistedQueue().catch(()=>{})},e=globalThis.navigator?.locks;if(!e){t();return}e.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||t(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(t)}async hydrateQueryCache(){if(this.queryCache)try{const t=await this.queryCache.load();for(const{key:e,...s}of t){if(et(this.persistenceVersion,s.version)){this.queryCache.remove(e).catch(()=>{});continue}this.hydratedQueryCache.set(e,s)}}catch{}}takeHydratedCache(t,e,s){const n=R(t,e,s),i=this.hydratedQueryCache.get(n);if(i!==void 0)return this.hydratedQueryCache.delete(n),i.identity===this.identityFingerprint()?i:void 0}persistQueryValue(t){const e=t.serverBase;if(!this.queryCache||e===void 0)return;const s=R(t.fn.__lunoraRef,t.argsKey,t.shardKey);this.pendingCacheWrites.set(s,{identity:this.identityFingerprint(),serverCursor:t.serverCursor,ts:Date.now(),value:e,...t.serverEpoch===void 0?{}:{serverEpoch:t.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},pt)}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;const{queryCache:t}=this;if(!t){this.pendingCacheWrites.clear();return}const e=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(e.map(([s,n])=>t.put(s,n)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";const t=[...this.connections.values()];return t.length===0?"idle":t.some(e=>e.wsState==="open")?"connected":t.some(e=>e.wsState==="connecting")?"connecting":"offline"}emitConnectionStatus(){const t=this.computeStatus();t!==this.lastStatus&&(this.lastStatus=t,this.statusListeners.emit(t),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(t,this.identityFingerprint()))}emitItemSettled(t,e,s){this.mutationSettledListeners.emit({args:t.args,code:s===void 0?void 0:s.code,error:s,functionPath:t.functionPath,hadAwaiter:t.liveAwaiter??!1,id:t.id??"",shardKey:t.shardKey,status:e})}applyOptimisticUpdates(t,e,s,n){const i=[],r=[];if(!n)return{confirms:i,rollbacks:r};const a=w.key(t,e,s),o=this.subscriptions.get(a);if(o){const c=Y(o,n);c&&(i.push(c.confirm),r.push(c.rollback))}return{confirms:i,rollbacks:r}}applyOptimisticUpdate(t,e,s,n,i){const{confirms:r,rollbacks:a,store:o}=Z(this.subscriptions,s);try{t(o,e)}catch{O(a);return}n.push(...a),i.push(...r)}getConnection(t){return this.connections.get(m(t))}sendOrQueueUnsubscribe(t,e,s){const n=this.getConnection(t);n&&!g(n,{id:e,type:s})&&n.pendingUnsubscribes.push({id:e,type:s})}connectionGateState(t){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let s="idle";return this.leaderStatus==="connected"?s="open":this.leaderStatus==="connecting"&&(s="connecting"),{hasSocket:!1,wasEverConnected:this.leaderWasEverConnected,wsState:s}}const e=this.getConnection(t);return{hasSocket:e?.socket!==void 0,wasEverConnected:e?.wasEverConnected??!1,wsState:e?.wsState??"idle"}}getOrCreateConnection(t){const e=m(t);let s=this.connections.get(e);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],reconnect:q(this.reconnectOptions),reconnectTimer:void 0,shardKey:t,socket:void 0,wasEverConnected:!1,wsState:"idle"},this.connections.set(e,s)),s}wsUrlFor(t,e){const s=[];if(t!==void 0&&s.push(`shard=${encodeURIComponent(t)}`),e!==void 0&&s.push(`token=${encodeURIComponent(e)}`),s.length===0)return this.wsUrl;const n=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${n}${s.join("&")}`}rpcRequestHeaders(t){const e={"content-type":"application/json"};if(this.authToken&&(e.authorization=`Bearer ${this.authToken}`),t.mutationId&&(e["x-lunora-mutation-id"]=t.mutationId),t.clientId!==void 0&&(e["x-lunora-client-id"]=t.clientId),t.clientSeq!==void 0&&(e["x-lunora-client-seq"]=t.clientSeq.toString()),t.attachBookmark){const s=this.bookmark.get();s&&(e["x-d1-bookmark"]=s)}return e}async rpc(t,e,s,n={}){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");const i=this.rpcRequestHeaders(n),r=await this.fetchImpl(S(this.url,ot),{body:JSON.stringify({args:k(e,`args for '${t}'`),functionPath:t,shardKey:s}),headers:i,method:"POST"});if(n.captureBookmark){const o=r.headers.get("x-d1-bookmark");o&&this.bookmark.set(o)}let a;try{a=await r.json()}catch{const o=r.statusText?` ${r.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${r.status.toString()}${o})`)}if("error"in a)throw T(a.error);if(!r.ok){const o=r.statusText?` ${r.statusText}`:"";throw new p("INTERNAL",`LunoraClient: request failed (status ${r.status.toString()}${o})`)}return n.onMutationAck?.(a.lastMutationId),n.onCommitCursor?.(a.commitCursor),b(a.result)}async adminFetch(t,e,s,n){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");const i={};this.authToken&&(i.authorization=`Bearer ${this.authToken}`);const r=s instanceof ArrayBuffer||s instanceof Blob;let a;s===void 0?a=void 0:r?(a=s,n!==void 0&&(i["content-type"]=n)):(a=JSON.stringify(s),i["content-type"]="application/json");const o=await this.fetchImpl(S(this.url,t),{body:a,headers:i,method:e});let c;try{c=await o.json()}catch{const d=o.statusText?` ${o.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${o.status.toString()}${d})`)}if(typeof c=="object"&&c!==null&&"error"in c){const d=c.error,u=new Error(d.message??"admin request failed");throw u.code=d.code,u}if(!o.ok){const d=o.statusText?` ${o.statusText}`:"";throw new p("INTERNAL",`LunoraClient: admin request failed (status ${o.status.toString()}${d})`)}return c}effectiveConnectionContext(t){const e=this.connectionContextHolders.get(t);return e&&e.length>0?e[e.length-1]?.context:this.connectionContexts.get(t)??this.defaultConnectionContext}refreshConnectionContext(t){const e=this.connections.get(t);e?.wsState==="open"&&this.sendConnectEnvelope(e)}sendConnectEnvelope(t){const e=this.effectiveConnectionContext(m(t.shardKey));g(t,{clientId:this.clientId,id:"connect",type:"connect",...e===void 0?{}:{context:e}})}resendShapeSubscriptions(t){for(const e of this.shapeSubscriptions.values())m(e.shardKey)===m(t)&&this.sendShapeSubscribeIfOpen(e)}ensureSocket(t){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const e=this.getOrCreateConnection(t);if(!(e.wsState==="open"||e.wsState==="connecting")){if(e.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(e,t,this.wsToken).catch(()=>{});return}this.openSocket(e,t,this.wsToken)}}async openSocketWithProvidedToken(t,e,s){let n;try{n=await s()}catch{this.handleDisconnect(t);return}this.closed||this.WebSocketImpl===void 0||t.wsState!=="connecting"||t.socket!==void 0||this.openSocket(t,e,n)}openManagedSocket(t,e,s,n){const{WebSocketImpl:i}=this;if(i===void 0)throw new p("INTERNAL","no WebSocket implementation available");const r=new i(e);t.socket=r;const a=()=>{this.stopHeartbeat(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket===r&&(t.socket=void 0)},o=c=>{a(),n.onClose(c)};s>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===r){try{r.close()}catch{}o()}},s)),r.addEventListener("open",()=>{t.socket===r&&(t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.lastFrameAt=Date.now(),n.onOpen(),this.startHeartbeat(t,o))}),r.addEventListener("message",c=>{t.socket===r&&(t.lastFrameAt=Date.now(),n.onMessage(c))}),r.addEventListener("close",c=>{t.socket===r&&o(c)}),r.addEventListener("error",()=>{t.socket===r&&o()})}openSocket(t,e,s){this.WebSocketImpl!==void 0&&this.openManagedSocket(t,this.wsUrlFor(e,s),this.connectTimeoutMs,{onClose:n=>{n?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(t)},onMessage:n=>{this.handleServerMessage(n.data,e)},onOpen:()=>{t.wsState="open",t.wasEverConnected=!0,t.reconnect.reset(),this.emitConnectionStatus(),this.sendConnectEnvelope(t),this.markShardPendingAck(e);for(const i of this.subscriptions.all())m(i.shardKey)===m(e)&&this.sendSubscribeIfOpen(i);if(this.resendShapeSubscriptions(e),t.pendingUnsubscribes.length>0){const i=t.pendingUnsubscribes;t.pendingUnsubscribes=[];for(const{id:r,type:a}of i)g(t,{id:r,type:a})}if(t.pendingStreams&&t.pendingStreams.length>0){const i=t.pendingStreams;t.pendingStreams=[];for(const r of i)g(t,r)}const n=this.whisperHandlers.get(m(e));if(n)for(const i of n.keys())g(t,{topic:i,type:"whisper_subscribe"});this.flushOfflineQueue(e).catch(()=>{})}})}handleDisconnect(t){if(this.closed||t.wsState==="idle"||t.wsState==="closed")return;this.stopHeartbeat(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket=void 0,t.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(t.shardKey);const e=new Set((t.pendingStreams??[]).map(n=>n.id));for(const[n,i]of this.streams)m(i.shardKey)===m(t.shardKey)&&!e.has(n)&&(i.handle.fail(new p("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.streams.delete(n));if(this.WebSocketImpl===void 0)return;const s=t.reconnect.next();t.reconnectTimer=setTimeout(()=>{t.reconnectTimer=void 0,this.ensureSocket(t.shardKey)},s)}startHeartbeat(t,e){this.stopHeartbeat(t),!(this.heartbeatIntervalMs<=0)&&(t.heartbeatTimer=setInterval(()=>{if(!t.socket)return;const{socket:s}=t;if(Date.now()-t.lastFrameAt>this.heartbeatIntervalMs*2.5){try{s.close()}catch{}e();return}try{s.send(dt)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(t){t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)}markShardPendingAck(t){const e=m(t);for(const s of this.subscriptions.all())m(s.shardKey)===e&&(s.acked=!1)}sendSubscribeIfOpen(t){const e=this.getConnection(t.shardKey);if(e?.wsState!=="open"||t.acked)return;const s=t.fn.__lunoraTable??t.fn.__lunoraRef;g(e,{id:t.id,query:{args:B(t.args),functionPath:t.fn.__lunoraRef,table:s,...t.serverCursor===void 0?{}:{sinceSeq:t.serverCursor},...t.serverEpoch===void 0?{}:{sinceEpoch:t.serverEpoch}},type:"subscribe"})}sendShapeSubscribeIfOpen(t){const e=this.getConnection(t.shardKey);e?.wsState==="open"&&g(e,{id:t.id,shape:{name:t.name,...t.wireArgs===void 0?{}:{args:t.wireArgs}},type:"shape_subscribe",...t.serverCursor===void 0?{}:{sinceCheckpoint:t.serverCursor},...t.serverEpoch===void 0?{}:{sinceEpoch:t.serverEpoch}})}handleServerMessage(t,e){const s=Re(t);if(s===void 0)return;let n;try{n=JSON.parse(s)}catch{return}switch(n.type){case"ack":{const i=this.subscriptions.getById(n.id);i&&(i.acked=!0);return}case"chunk":{const{data:i,id:r}=n;this.streams.get(r)?.handle.push(b(i));return}case"complete":{this.handleCompleteMessage(n.id);return}case"data":case"delta":{this.handleDataMessage(n);return}case"error":{this.handleErrorMessage(n);break}case"pokeEnd":{this.handlePokeEnd(n);break}case"pokePart":{this.handlePokePart(n);break}case"pokeStart":{this.handlePokeStart(n);break}case"resume":{this.handleResumeMessage(n);break}case"settled":{this.handleSettledMessage(n);break}case"whisper":{this.dispatchWhisper(n,e);break}}}handleErrorMessage(t){if(t.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}const{id:e}=t,s=e===void 0?void 0:this.streams.get(e);if(s&&e!==void 0){s.handle.fail(Pe(t)),this.streams.delete(e);return}const n=e===void 0?void 0:this.subscriptions.getById(e);if(n){E(n.errorCallbacks,N(t));return}const i=e===void 0?void 0:this.shapeSubscriptions.get(e);i&&E(i.errorCallbacks,N(t))}handlePokeStart(t){at(this.pokeBuffers,z.MAX_POKE_BUFFERS),this.pokeBuffers.set(t.pokeId,{baseCheckpoint:t.baseCheckpoint,epoch:t.epoch,lastMutationId:new Map,parts:new Map})}handlePokePart(t){const e=this.pokeBuffers.get(t.pokeId);if(!e)return;const s=e.parts.get(t.shapeId)??[];for(const n of t.rowsPatch)s.push(n.value===void 0?n:{...n,value:b(n.value)});e.parts.set(t.shapeId,s),t.lastMutationId!==void 0&&e.lastMutationId.set(t.shapeId,t.lastMutationId)}handlePokeEnd(t){const e=this.pokeBuffers.get(t.pokeId);if(e){this.pokeBuffers.delete(t.pokeId);for(const[s,n]of e.parts){const i=this.shapeSubscriptions.get(s);if(!i)continue;const r=e.epoch!==void 0&&i.serverEpoch!==void 0&&e.epoch!==i.serverEpoch,a=e.baseCheckpoint!==void 0&&i.serverCursor!==void 0&&i.serverCursor!==e.baseCheckpoint;if(r||a){i.rows.clear(),i.serverCursor=void 0,i.serverEpoch=void 0,this.emitShapeRows(i),this.sendShapeSubscribeIfOpen(i);continue}ht(i.rows,n),t.checkpoint!==void 0&&(i.serverCursor=t.checkpoint),t.epoch!==void 0&&(i.serverEpoch=t.epoch);const o=e.lastMutationId.get(s);o!==void 0&&(i.lastMutationId=o),this.emitShapeRows(i),i.onCheckpoint?.({checkpoint:i.serverCursor,mutationId:i.lastMutationId})}}}emitShapeRows(t){const e=[...t.rows.values()];for(const s of t.callbacks)try{s(e)}catch{}}handleDataMessage(t){const{id:e}=t,s=e?this.subscriptions.getById(e):void 0;if(!s)return;const n=this.resolveDataPayload(t,s);if(s.serverBase=n,t.cursor!==void 0&&(s.serverCursor=t.cursor),t.epoch!==void 0&&(s.serverEpoch=t.epoch),t.lastMutationId!==void 0){s.lastMutationId=Math.max(s.lastMutationId??0,t.lastMutationId);for(const i of s.checkpointCallbacks)i({checkpoint:s.serverCursor,mutationId:s.lastMutationId})}if(this.persistQueryValue(s),F(s,s.serverCursor),P(s,A(n,s.optimisticLayers)),this.tabCoordinator?.isLeader()){const i=w.key(s.fn.__lunoraRef,s.args,s.shardKey);this.tabCoordinator.broadcastSubscriptionData(i,n,s.serverCursor,s.serverEpoch,this.identityFingerprint())}}handleResumeMessage(t){const e=this.subscriptions.getById(t.id);e&&this.ackAndAdvanceCursor(e,t.cursor,t.epoch)}handleSettledMessage(t){const e=this.subscriptions.getById(t.id);if(e){this.ackAndAdvanceCursor(e,t.cursor,t.epoch),t.lastMutationId!==void 0&&(e.lastMutationId=t.lastMutationId);for(const s of e.checkpointCallbacks)s({checkpoint:e.serverCursor,mutationId:e.lastMutationId});if(this.tabCoordinator?.isLeader()){const s=w.key(e.fn.__lunoraRef,e.args,e.shardKey);this.tabCoordinator.broadcastSubscriptionSettled(s,e.serverCursor,e.serverEpoch,e.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(t,e,s){t.acked=!0,(e!==void 0&&e!==t.serverCursor||s!==void 0&&s!==t.serverEpoch)&&(e!==void 0&&(t.serverCursor=e),s!==void 0&&(t.serverEpoch=s),this.persistQueryValue(t),F(t,t.serverCursor)&&P(t,A(t.serverBase,t.optimisticLayers)))}resolveDataPayload(t,e){if("data"in t&&t.data!==void 0)return b(t.data);const s=b(t.delta);if(V(s)&&e.serverBase!==void 0){const n=J(e.serverBase,s);if(n!==void 0)return n}return s}dispatchWhisper(t,e){const s=this.whisperHandlers.get(m(e))?.get(t.topic);if(!s)return;const n=b(t.data);for(const i of s)try{i(n,t.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(t){const e=this.streams.get(t);if(e){e.handle.complete(),this.streams.delete(t);return}const s=this.subscriptions.getById(t);s&&(s.acked=!1,E(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(t){t&&this.persistence?.remove(t).catch(e=>{st(this.onPersistenceError,"remove",e,t)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const t=this.authToken;return t===null?null:this.hashToken(t)}hashToken(t){let e=2166136261,s=5381;for(let n=0;n<t.length;n+=1){const i=t.charCodeAt(n);e^=i,e=Math.imul(e,16777619),s=Math.imul(s,33)+i}return`${t.length.toString(36)}:${(e>>>0).toString(36)}:${(s>>>0).toString(36)}`}isSameCredentialUnderTokenHash(t){if(t===null||t.startsWith("subj:"))return!1;const e=this.authToken;return e===null?!1:this.hashToken(e)===t}rejectQueuedForIdentityChange(){const t=this.offlineQueue.drain();for(const e of t){this.queuedIdentities.delete(e.id??""),this.unpersist(e.id);const s=new Error("offline mutation discarded: auth identity changed before replay");s.code="OFFLINE_IDENTITY_CHANGED",e.reject(s),this.emitItemSettled(e,"rejected",s)}this.clearQueryCacheForIdentityChange()}restampQueuedIdentity(t,e){for(const[s,n]of this.queuedIdentities)n===t&&this.queuedIdentities.set(s,e)}clearQueryCacheForIdentityChange(){this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}flushAllOfflineQueues(){for(const t of this.queuedOfflineShardKeys)this.flushOfflineQueue(t).catch(()=>{})}async flushOfflineQueue(t){const e=this.offlineQueue.drainConflict();for(const c of e){this.unpersist(c.id),this.queuedIdentities.delete(c.id??"");const d=new Error("offline mutation skipped: precondition failed before replay");d.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(c,"rejected",d)}const s=m(t),n=this.offlineQueue.drain(c=>m(c.shardKey)===s);if(n.length===0)return;const i=this.identityFingerprint(),r=[];for(const c of n)this.passesReplayIdentityGate(c,i)&&r.push(c);if(r.length===0)return;const a=this.encodableOrSettleTerminal(r);if(a.length===0)return;if(a.length===1){await this.replaySequential(a);return}const o=[];for(let c=0;c<a.length;c+=L){const d=a.slice(c,c+L),u=await this.replayBatched(d);if(o.push(...u.requeue),u.stop){o.push(...a.slice(c+L));break}}o.length>0&&this.offlineQueue.requeue(o)}encodableOrSettleTerminal(t){const e=[];for(const s of t)try{k(s.args,`args for '${s.functionPath}'`),e.push(s)}catch(n){this.settleReplayTerminal(s,n instanceof Error?n:new Error(String(n)))}return e}passesReplayIdentityGate(t,e){const s=t.id===void 0?void 0:this.queuedIdentities.get(t.id),n=s===void 0?t.identity:s;if(n!==void 0&&n!==e&&!this.isSameCredentialUnderTokenHash(n)){this.queuedIdentities.delete(t.id??""),this.unpersist(t.id);const i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",t.reject(i),this.emitItemSettled(t,"rejected",i),!1}return this.queuedIdentities.delete(t.id??""),!0}settleReplaySuccess(t,e,s){this.unpersist(t.id),t.onCommit?.(s),t.resolve(e),this.emitItemSettled(t,"committed")}settleReplayTerminal(t,e){this.unpersist(t.id),t.reject(e),this.emitItemSettled(t,"rejected",e)}async replaySequential(t){for(let e=0;e<t.length;e+=1){const s=t[e];if(s)try{let n;const i=await this.rpc(s.functionPath,s.args,s.shardKey,{captureBookmark:!0,mutationId:s.id,onCommitCursor:r=>{n=r}});this.settleReplaySuccess(s,i,n)}catch(n){if(n.code!==void 0){this.settleReplayTerminal(s,n);continue}this.offlineQueue.requeue(t.slice(e));return}}}async replayBatched(t){if(!this.fetchImpl)return{requeue:t,stop:!0};let e;try{e=await this.fetchImpl(S(this.url,Q),{body:JSON.stringify({calls:t.map((i,r)=>({args:k(i.args,`args for '${i.functionPath}'`),functionPath:i.functionPath,id:r,mutationId:i.id,shardKey:i.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"})}catch{return{requeue:t,stop:!0}}const s=e.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let n;try{n=await e.json()}catch{return{requeue:t,stop:!0}}if(!n.results){if(n.error){const i=T(n.error);for(const r of t)this.settleReplayTerminal(r,i);return{requeue:[],stop:!1}}return{requeue:t,stop:!0}}return{requeue:this.settleReplayBatchSlots(t,n.results),stop:!1}}settleReplayBatchSlots(t,e){const s=new Map;for(const i of e)typeof i.id=="number"&&i.body!==void 0&&s.set(i.id,i.body);const n=[];for(const[i,r]of t.entries()){const a=s.get(i);a===void 0?n.push(r):"error"in a?Me.has(a.error.code)?n.push(r):this.settleReplayTerminal(r,T(a.error)):this.settleReplaySuccess(r,b(a.result),a.commitCursor)}return n}}export{z as LunoraClient};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
let c=0;const a=()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();c+=1;const r=typeof crypto<"u"&&typeof crypto.getRandomValues=="function"?Array.from(crypto.getRandomValues(new Uint8Array(8)),t=>t.toString(16).padStart(2,"0")).join(""):Math.random().toString(16).slice(2,12);return`id_${Date.now().toString(36)}_${c.toString(36)}_${r}`},f=(r,t)=>r!==void 0&&t!==r,d=a,h=(r,t,e,i)=>{if(r){r({error:e,mutationId:i,operation:t});return}console.warn(`[lunora] offline-queue persistence ${t} failed`,e)};class u{queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;version;items=[];constructor(t={},e={}){this.maxItems=t.maxItems??1e3,this.queueBeforeFirstConnect=t.queueBeforeFirstConnect??!1,this.onPersistenceError=t.onPersistenceError,this.persistence=e.persistence,this.onEvict=e.onEvict,this.onSizeChange=e.onSizeChange,this.version=e.version}get size(){return this.items.length}enqueue(t){const e=t;e.id??=d(),this.items.push(e),this.persistence?.append({args:e.args,functionPath:e.functionPath,id:e.id,identity:e.identity,shardKey:e.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(i=>{h(this.onPersistenceError,"append",i,e.id)}),this.evictOverflow(),this.notifySize()}async hydrate(){if(!this.persistence)return[];let t;try{t=await this.persistence.load()}catch(s){throw h(this.onPersistenceError,"load",s),s}const e=[];for(const s of t)if(!(this.items.some(o=>o.id===s.id)||e.some(o=>o.id===s.id))){if(f(this.version,s.version)){this.persistence.remove(s.id).catch(o=>{h(this.onPersistenceError,"remove",o,s.id)});continue}e.push({args:s.args,functionPath:s.functionPath,id:s.id,identity:s.identity,reject:()=>{},resolve:()=>{},shardKey:s.shardKey})}this.items.unshift(...e),this.evictOverflow(),this.notifySize();const i=new Set(this.items),n=new Set;for(const s of e)i.has(s)&&n.add(s.shardKey);return[...n]}drain(t){if(!t){const n=[...this.items];return this.items.length=0,this.notifySize(),n}const e=[],i=[];for(const n of this.items)(t(n)?e:i).push(n);return this.items.length=0,this.items.push(...i),this.notifySize(),e}requeue(t){t.length!==0&&(this.items.unshift(...t),this.notifySize())}drainConflict(){const t=[],e=[];for(const i of this.items)if(i.precondition!==void 0&&!i.precondition()){const n=new Error("offline mutation skipped: precondition failed before replay");n.code="OFFLINE_PRECONDITION_FAILED",i.reject(n),t.push(i)}else e.push(i);return t.length>0&&(this.items.length=0,this.items.push(...e),this.notifySize()),t}clear(){for(const t of this.items){const e=new Error("CLIENT_CLOSED");e.code="CLIENT_CLOSED",t.reject(e)}this.items.length=0,this.notifySize()}evictOverflow(){for(;this.items.length>this.maxItems;){const t=this.items.shift();if(t){t.id&&this.persistence?.remove(t.id).catch(i=>{h(this.onPersistenceError,"remove",i,t.id)});const e=new Error("offline queue overflow");e.code="OFFLINE_QUEUE_OVERFLOW",t.reject(e),this.onEvict?.(t,e)}}}notifySize(){this.onSizeChange?.(this.items.length)}}export{f as d,u as h,h as s,d as u};
|