@lunora/client 1.0.0-alpha.48 → 1.0.0-alpha.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { L as LunoraClient } from "../packem_shared/lunora-client.d-nHupuaoI.mjs";
1
+ import { L as LunoraClient } from "../packem_shared/lunora-client.d-BOmxvSrG.mjs";
2
2
  import { U as User } from "../packem_shared/types.d-CsuRAQvb.mjs";
3
3
  import '@lunora/runtime';
4
4
  interface IdentityStore {
@@ -1,4 +1,4 @@
1
- import { L as LunoraClient } from "../packem_shared/lunora-client.d-Dv40CCsu.js";
1
+ import { L as LunoraClient } from "../packem_shared/lunora-client.d-K16SL8Tj.js";
2
2
  import { U as User } from "../packem_shared/types.d-CsuRAQvb.js";
3
3
  import '@lunora/runtime';
4
4
  interface IdentityStore {
package/dist/index.d.mts CHANGED
@@ -1,8 +1,8 @@
1
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-CsuRAQvb.mjs";
2
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-CsuRAQvb.mjs";
3
- import { C as ConnectionStatus, S as SubscriptionError, b as StreamIterable, M as MutationCallOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-nHupuaoI.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-nHupuaoI.mjs";
5
- export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-y5DTDa0X.mjs";
3
+ import { C as ConnectionStatus, S as SubscriptionError, b as StreamIterable, M as MutationCallOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-BOmxvSrG.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-BOmxvSrG.mjs";
5
+ export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-BprjXhJi.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
  /**
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
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-CsuRAQvb.js";
2
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-CsuRAQvb.js";
3
- import { C as ConnectionStatus, S as SubscriptionError, b as StreamIterable, M as MutationCallOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-Dv40CCsu.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-Dv40CCsu.js";
5
- export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-DtFFNok3.js";
3
+ import { C as ConnectionStatus, S as SubscriptionError, b as StreamIterable, M as MutationCallOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-K16SL8Tj.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-K16SL8Tj.js";
5
+ export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-CM8-Mg2A.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
  /**
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{y as l,w as R}from"./packem_shared/delta-merge-DoT5IpTP.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-CGsgaEph.mjs";import{LunoraClient as b}from"./packem_shared/LunoraClient-BluyW2SA.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 w,createIndexedDbPersistence as N}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-A10yhOpq.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-HXgW6BXq.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,l as applyDelta,m as createAsyncStoragePersistence,s as createClientQuery,f as createInMemoryBookmarkStorage,w as createInMemoryPersistence,W as createInMemoryQueryCache,N 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};
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{y as l,w as R}from"./packem_shared/delta-merge-DoT5IpTP.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-CGsgaEph.mjs";import{LunoraClient as b}from"./packem_shared/LunoraClient-M_ArXnWT.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 w,createIndexedDbPersistence as N}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-A10yhOpq.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-HXgW6BXq.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,l as applyDelta,m as createAsyncStoragePersistence,s as createClientQuery,f as createInMemoryBookmarkStorage,w as createInMemoryPersistence,W as createInMemoryQueryCache,N 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 m}from"@lunora/errors";import{w as D,y as j,a as H}from"./delta-merge-DoT5IpTP.mjs";import{s as b,a as N}from"./wire-codec-aTWt2XiW.mjs";import{t as I}from"./wire-key-Cb-kXfSh.mjs";import V from"./createInMemoryBookmarkStorage-DCd5Ej-t.mjs";import{ClientQueryStore as J}from"./createClientQuery-CrdRoicO.mjs";import{TabCoordinator as X}from"./TabCoordinator-CMFYQCL-.mjs";import{httpStream as Y}from"./httpStream-Cz4_QyjV.mjs";import{d as F,n as P,f as A,a as Z,c as tt}from"./local-store-CGsgaEph.mjs";import{h as et,u as $,d as st,s as rt}from"./offline-queue-CKMw-5rF.mjs";import{resolvePersistenceAdapter as it}from"./createInMemoryPersistence-CQYXy8UP.mjs";import{resolveQueryCacheAdapter as nt,queryCacheKey as x}from"./createInMemoryQueryCache-DjCKrLjk.mjs";import{createReconnect as q}from"./createReconnect-CFT7YRSR.mjs";import{createStream as at}from"./DEFAULT_MAX_BUFFER-TBn2s7Rz.mjs";import{SubscriptionRegistry as w}from"./SubscriptionRegistry-HXgW6BXq.mjs";const R=500,ot=(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 ct="/_lunora/rpc",Q="/_lunora/rpc-batch",ht="/_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]?.()},ut=(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",lt=3e4,mt=1e4,pt=250,ft=64,yt="/_lunora/admin/shard-traffic",gt="/_lunora/admin/scheduled",bt="/_lunora/admin/scheduled/status",St="/_lunora/admin/scheduled/ws",vt="/_lunora/admin/scheduled/cancel",kt="/_lunora/admin/scheduled/dead",wt="/_lunora/admin/scheduled/dead/retry",Ct="/_lunora/admin/scheduled/dead/cancel",Tt="/_lunora/admin/workflows/instances",It="/_lunora/admin/workflows/instance",Ot="/_lunora/admin/workflows/status",L="/_lunora/admin/storage",Et="/_lunora/admin/storage/url",_t="/_lunora/admin/storage/buckets",Ft="/_lunora/admin/functions",Pt="/_lunora/admin/cron-jobs",At="/_lunora/admin/cron-jobs/run",xt="/_lunora/admin/openapi",Rt="/_lunora/admin/openrpc",Mt="/_lunora/admin/global/tables",Lt="/_lunora/admin/global/table",Kt="/_lunora/admin/global/facet",$t="/_lunora/admin/vector/indexes",qt="/_lunora/admin/vector/query",Qt="/_lunora/admin/logs/archive",Ut="/_lunora/admin/kv/namespaces",Wt="/_lunora/admin/kv/keys",K="/_lunora/admin/kv/value",Nt="/_lunora/admin/auth/users",Bt="/_lunora/admin/auth/sessions",zt="/_lunora/admin/auth/users/create",Gt="/_lunora/admin/auth/users/role",Dt="/_lunora/admin/auth/users/ban",jt="/_lunora/admin/auth/users/unban",Ht="/_lunora/admin/auth/users/password",Vt="/_lunora/admin/auth/users/remove",Jt="/_lunora/admin/auth/users/impersonate",Xt="/_lunora/admin/auth/sessions/revoke",Yt="/_lunora/admin/auth/sessions/revoke-all",Zt="/_lunora/admin/auth/capabilities",te="/_lunora/admin/auth/users/update",ee="/_lunora/admin/auth/accounts",se="/_lunora/admin/auth/accounts/unlink",re="/_lunora/admin/auth/passkeys",ie="/_lunora/admin/auth/passkeys/delete",ne="/_lunora/admin/auth/two-factor/disable",ae="/_lunora/admin/auth/organizations",oe="/_lunora/admin/auth/organizations/members",ce="/_lunora/admin/auth/organizations/invitations",he="/_lunora/admin/auth/organizations/members/remove",ue="/_lunora/admin/auth/organizations/invitations/cancel",de="/_lunora/admin/auth/config",le="/_lunora/admin/auth/organizations/create",me="/_lunora/admin/auth/organizations/update",pe="/_lunora/admin/auth/organizations/remove",fe="/_lunora/admin/auth/organizations/members/add",ye="/_lunora/admin/auth/organizations/members/invite",ge="/_lunora/admin/auth/organizations/members/role",be="/_lunora/admin/auth/organizations/teams",Se="/_lunora/admin/auth/organizations/teams/create",ve="/_lunora/admin/auth/organizations/teams/update",ke="/_lunora/admin/auth/organizations/teams/remove",we="/_lunora/admin/auth/organizations/teams/members",Ce="/_lunora/admin/auth/organizations/teams/members/add",Te="/_lunora/admin/auth/organizations/teams/members/remove",Ie="/_lunora/admin/auth/organizations/roles",Oe="/_lunora/admin/auth/organizations/roles/create",Ee="/_lunora/admin/auth/organizations/roles/update",_e="/_lunora/admin/auth/organizations/roles/remove",Fe="/api/auth",Pe="/get-session",U=h=>h.startsWith("https://")?`wss://${h.slice(8)}`:h.startsWith("http://")?`ws://${h.slice(7)}`:h,v=(h,t)=>`${h.endsWith("/")?h.slice(0,-1):h}${t}`,f=(h,t)=>{const e=new URLSearchParams;for(const[r,i]of Object.entries(t))i!==void 0&&i!==""&&e.set(r,String(i));const s=e.toString();return s===""?h:`${h}?${s}`},Ae=[H],p=h=>h??"",B=(h,t)=>{const e=h.error,s=typeof e?.code=="string"?e.code:void 0,r=typeof e?.message=="string"?e.message:void 0;return{code:s,messageText:(typeof h.message=="string"?h.message:void 0)??r??t}},xe=h=>{const{code:t,messageText:e}=B(h,"stream error");return t===void 0?new Error(e):new m(t,e)},W=h=>{const{code:t,messageText:e}=B(h,"subscription error");return{message:e,...t===void 0?{}:{code:t}}},E=(h,t)=>{for(const e of h)try{e(t)}catch{}},Re=new TextDecoder,Me=h=>{if(typeof h=="string")return h;if(h instanceof ArrayBuffer)return Re.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 N(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 r=s.body;e[s.id]=r&&"error"in r&&r.error?{error:T(r.error),ok:!1}:{ok:!0,value:b(r?.result)}}return e.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},Ke=new Set(["SHARD_ERROR","SHARD_UNAVAILABLE"]),$e=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;shardCursors=new Map;defaultShardKey;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??v(U(t.url),ht),this.wsToken=t.wsToken;const e=t.authBasePath??Fe;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??V(),this.reconnectOptions=t.reconnect,this.heartbeatIntervalMs=t.heartbeatIntervalMs??lt,this.connectTimeoutMs=t.connectTimeoutMs??mt,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=$e),this.offlineQueue=new et(t.offlineQueue,{onEvict:(s,r)=>{this.emitItemSettled(s,"rejected",r)},onSizeChange:s=>{this.pendingChangeListeners.emit(s)},persistence:this.persistence,version:t.persistenceVersion}),this.outbox=t.outbox,this.clientId=t.clientId??`client-${$()}`,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,r=this.identityFingerprint();this.authToken=t,e!==void 0&&(this.authSubject=e);const i=this.identityFingerprint();if(i!==r&&(s?this.rejectQueuedForIdentityChange():(this.restampQueuedIdentity(r,i),this.restampWatermarks(r,i)),this.tabCoordinator)){const n=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),n&&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(this.identityFingerprint()??"")?.get(t??"")??0}async callMutator(t,e,s){const r=s?.clientSeq;if(r!==void 0&&(!Number.isInteger(r)||r<=0))throw new m("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(r)}`);const i=s?.shardKey??"",n=this.identityFingerprint();let a;const o=await this.rpc(t,e,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:r,onMutationAck:c=>{a=c}});if(a!==void 0&&a>(this.clientWatermarks.get(n??"")?.get(i)??0)){let c=this.clientWatermarks.get(n??"");c===void 0&&(c=new Map,this.clientWatermarks.set(n??"",c)),c.set(i,a)}return{applied:a===void 0||a===r,result:o}}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(v(this.url,`${this.authBasePath}${Pe}`),{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=p(e.shardKey);t===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,t),this.refreshConnectionContext(s)}acquireConnectionContext(t,e={}){const s=p(e.shardKey),r={context:t},i=this.connectionContextHolders.get(s);i?i.push(r):this.connectionContextHolders.set(s,[r]),this.refreshConnectionContext(s);let n=!1;return()=>{if(n)return;n=!0;const a=this.connectionContextHolders.get(s);if(!a)return;const o=a.indexOf(r);o!==-1&&a.splice(o,1),a.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s)}}whisperSubscribe(t,e,s={}){const r=p(s.shardKey);let i=this.whisperHandlers.get(r);i||(i=new Map,this.whisperHandlers.set(r,i));let n=i.get(t);const a=n===void 0;if(n||(n=new Set,i.set(t,n)),n.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(r),c=o?.get(t);if(!c?.delete(e)||c.size>0)return;o?.delete(t),o?.size===0&&this.whisperHandlers.delete(r);const u=this.getConnection(s.shardKey);u&&g(u,{topic:t,type:"whisper_unsubscribe"})}}whisper(t,e,s={}){this.ensureSocket(s.shardKey);const r=this.getConnection(s.shardKey);r&&g(r,{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=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...e?.keys()??[]]);for(const i of s){const n=this.connections.get(i);t.push({confirmedMutationWatermark:e?.get(i)??0,hasSocket:n?.socket!==void 0,shardKey:i===""?void 0:i,wasEverConnected:n?.wasEverConnected??!1,wsState:n?.wsState??"idle"})}const r=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())r.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:r.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 r=this.peekActiveQueryValue(t.__lunoraRef,e,s),i=r===void 0?void 0:I(r);return()=>{const n=this.peekActiveQueryValue(t.__lunoraRef,e,s);return i===void 0&&n===void 0?!0:i===void 0||n===void 0?!1:I(n)===i}}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(t,e,s){if(!this.readyResolved)return;const r=I(e),i=x(t,r,s),n=this.hydratedQueryCache.get(i);if(n!==void 0)return n.identity===this.identityFingerprint()?n.value:void 0}peekActiveQueryValue(t,e,s){const r=w.key(t,e,s);return this.subscriptions.get(r)?.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 m("INTERNAL","LunoraClient: no `fetch` implementation available");if(t.length===0)return[];const e=await this.fetchImpl(v(this.url,Q),{body:JSON.stringify({calls:t.map((i,n)=>({args:k(i.args??{},`args for batch call '${i.fn.__lunoraRef}'`),functionPath:i.fn.__lunoraRef,id:n,shardKey:i.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"}),s=e.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let r;try{r=await e.json()}catch{throw new m("INTERNAL",`LunoraClient: batch response was not JSON (status ${e.status.toString()})`)}if(!e.ok||r.error&&!r.results)throw r.error?T(r.error):new m("INTERNAL",`LunoraClient: batch request failed (status ${e.status.toString()})`);for(const i of r.results??[]){const n=i.body?.commitCursor;typeof i.id=="number"&&typeof n=="number"&&this.recordShardCursor(t[i.id]?.shardKey,n)}return Le(r.results??[],t.length)}async mutation(t,e,s={}){this.assertOpen();const r=e,i=s.mutationId??$(),{confirms:n,rollbacks:a}=this.applyOptimisticUpdates(t.__lunoraRef,r,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,e,s.shardKey,a,n);const{hasSocket:o,wasEverConnected:c,wsState:u}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:d}=this.offlineQueue,l=c||d,y=this.WebSocketImpl!==void 0&&l;if(u!=="open"&&!o&&y||u==="connecting"&&l)return this.enqueueOfflineMutation(t,r,s.shardKey,i,a,n,s.precondition);try{let S;const G=await this.rpc(t.__lunoraRef,r,s.shardKey,{captureBookmark:!0,mutationId:i,onCommitCursor:_=>{S=_}});for(const _ of n)_(S);return G}catch(S){throw O(a),S}}async action(t,e,s={}){return this.assertOpen(),await this.rpc(t.__lunoraRef,e,s.shardKey)}async importRows(t,e,s={}){this.assertOpen();const r=Math.max(1,Math.trunc(s.chunkSize??500)),i=s.toArgs??(c=>({rows:c})),n=e.length;let a=0,o=0;for(let c=0;c<n;c+=r){const u=e.slice(c,c+r),d=o;await this.mutation(t,i(u),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(d)}`},shardKey:s.shardKey}),o+=1,a+=u.length,s.onProgress?.({done:a,total:n})}return{chunks:o,imported:a}}async shardTraffic(t){this.assertOpen();const e=await this.adminFetch(yt,"POST",{table:t});return{failed:e.failed??0,ok:e.ok??0,shards:e.shards??[]}}async listScheduledJobs(){return this.assertOpen(),(await this.adminFetch(gt,"GET")).records??[]}async schedulerStatus(){this.assertOpen();const t=await this.adminFetch(bt,"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(kt,"GET")).records??[]}async retryDeadJob(t){return this.assertOpen(),{retried:(await this.adminFetch(wt,"POST",{id:t})).retried===!0}}async removeDeadJob(t){return this.assertOpen(),{removed:(await this.adminFetch(Ct,"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(`${Tt}?${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(`${It}?${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(Ot,"POST",{action:t.action,id:t.id,name:t.name})).status??"unknown"}}subscribeScheduledJobs(t){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const e=v(U(this.url),St),s=q(this.reconnectOptions),r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let i,n=!1;const a=()=>{n||(i=setTimeout(u,s.next()))},o=d=>{if(n||this.WebSocketImpl===void 0)return;const l=d===void 0?e:`${e}?token=${encodeURIComponent(d)}`;this.openManagedSocket(r,l,this.connectTimeoutMs,{onClose:()=>{a()},onMessage:y=>{try{const S=JSON.parse(typeof y.data=="string"?y.data:"");S.type==="jobs"&&Array.isArray(S.records)&&t(S.records)}catch{}},onOpen:()=>{s.reset()}})},c=async d=>{let l;try{l=await d()}catch{a();return}o(l)},u=()=>{if(n||this.WebSocketImpl===void 0)return;const{wsToken:d}=this;if(typeof d=="function"){c(d).catch(()=>{});return}o(d)};return u(),()=>{n=!0,i!==void 0&&clearTimeout(i),r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),this.stopHeartbeat(r),r.socket?.close()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(Ft,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(Pt,"GET")).jobs??[]}async runCronJob(t){this.assertOpen();const e=await this.adminFetch(At,"POST",{name:t});return{name:e.name??t,ran:e.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(xt,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(Rt,"GET")}async listStorageObjects(t={}){this.assertOpen();const e=f(L,{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=`${L}?key=${encodeURIComponent(t)}${M(e?.bucket)}`,r=await this.adminFetch(s,"DELETE");return{deleted:r.deleted??!0,key:r.key??t}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(_t,"GET")).buckets??[]}async uploadStorageObject(t){this.assertOpen();const e=`${L}?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,r=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,i=`${Et}?key=${encodeURIComponent(t)}${r}${M(e?.bucket)}`,n=await this.adminFetch(i,"GET");if(typeof n.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return n.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(Mt,"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(`${Lt}?${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(`${Kt}?${e.toString()}`,"GET")}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch($t,"GET")).indexes??[]}async queryVectorIndex(t){return this.assertOpen(),(await this.adminFetch(qt,"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(Ut,"GET")).namespaces??[]}async listKvKeys(t){this.assertOpen();const e=f(Wt,{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(K,{key:t.key,namespace:t.namespace});return await this.adminFetch(e,"GET")}async putKvValue(t){this.assertOpen(),await this.adminFetch(K,"PUT",t)}async deleteKvKey(t){this.assertOpen();const e=f(K,{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(zt,"POST",t)}async setAuthUserRole(t){return await this.adminFetch(Gt,"POST",t)}async banAuthUser(t){return await this.adminFetch(Dt,"POST",t)}async unbanAuthUser(t){return await this.adminFetch(jt,"POST",t)}async setAuthUserPassword(t){await this.adminFetch(Ht,"POST",t)}async removeAuthUser(t){await this.adminFetch(Vt,"POST",t)}async impersonateAuthUser(t){return await this.adminFetch(Jt,"POST",t)}async revokeAuthSession(t){await this.adminFetch(Xt,"POST",t)}async revokeAuthUserSessions(t){await this.adminFetch(Yt,"POST",t)}async getAuthCapabilities(){return await this.adminFetch(Zt,"GET")}async updateAuthUser(t){return await this.adminFetch(te,"POST",t)}async listAuthAccounts(t){return await this.adminFetch(f(ee,{userId:t.userId}),"GET")}async unlinkAuthAccount(t){await this.adminFetch(se,"POST",t)}async listAuthPasskeys(t){return await this.adminFetch(f(re,{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(ae,{limit:t.limit,offset:t.offset}),"GET")}async listAuthOrgMembers(t){const e=f(oe,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async listAuthOrgInvitations(t){const e=f(ce,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async removeAuthOrgMember(t){await this.adminFetch(he,"POST",t)}async cancelAuthOrgInvitation(t){await this.adminFetch(ue,"POST",t)}async getAuthConfig(){return await this.adminFetch(de,"GET")}async createAuthOrganization(t){return await this.adminFetch(le,"POST",t)}async updateAuthOrganization(t){return await this.adminFetch(me,"POST",t)}async deleteAuthOrganization(t){await this.adminFetch(pe,"POST",t)}async addAuthOrgMember(t){return await this.adminFetch(fe,"POST",t)}async inviteAuthOrgMember(t){return await this.adminFetch(ye,"POST",t)}async setAuthOrgMemberRole(t){return await this.adminFetch(ge,"POST",t)}async listAuthOrgTeams(t){const e=f(be,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async createAuthOrgTeam(t){return await this.adminFetch(Se,"POST",t)}async updateAuthOrgTeam(t){return await this.adminFetch(ve,"POST",t)}async removeAuthOrgTeam(t){await this.adminFetch(ke,"POST",t)}async listAuthOrgTeamMembers(t){const e=f(we,{limit:t.limit,offset:t.offset,teamId:t.teamId});return await this.adminFetch(e,"GET")}async addAuthOrgTeamMember(t){return await this.adminFetch(Ce,"POST",t)}async removeAuthOrgTeamMember(t){await this.adminFetch(Te,"POST",t)}async listAuthOrgRoles(t){const e=f(Ie,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async createAuthOrgRole(t){return await this.adminFetch(Oe,"POST",t)}async updateAuthOrgRole(t){return await this.adminFetch(Ee,"POST",t)}async deleteAuthOrgRole(t){await this.adminFetch(_e,"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,r={}){this.assertOpen();const i=e??{},n=w.key(t.__lunoraRef,i,r.shardKey);let a=this.subscriptions.get(n);const o=s,c=r.onError;if(!a){this.nextSubId+=1;const d=`sub_${this.nextSubId.toString()}`,l=I(i),y=this.takeHydratedCache(t.__lunoraRef,l,r.shardKey);a={acked:!1,args:i,argsKey:l,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:t,id:d,lastValue:y?.value,optimisticLayers:[],serverBase:y?.value,serverCursor:y?.serverCursor,shardKey:r.shardKey,...y?.serverEpoch===void 0?{}:{serverEpoch:y.serverEpoch}},this.subscriptions.add(a)}if(a.callbacks.add(o),c&&a.errorCallbacks.add(c),r.onCheckpoint&&a.checkpointCallbacks.add(r.onCheckpoint),a.lastValue!==void 0)try{o(a.lastValue)}catch{}this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(a);const u=a;return()=>{u.callbacks.delete(o),c&&u.errorCallbacks.delete(c),r.onCheckpoint&&u.checkpointCallbacks.delete(r.onCheckpoint),u.callbacks.size===0&&(this.sendOrQueueUnsubscribe(u.shardKey,u.id,"unsubscribe"),this.subscriptions.remove(u))}}subscribeShape(t,e,s={}){this.assertOpen(),this.nextShapeId+=1;const r=`shape_${this.nextShapeId.toString()}`,i={args:t.args,callbacks:new Set([e]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:r,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(r,i),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(i),()=>{this.shapeSubscriptions.delete(r),this.sendOrQueueUnsubscribe(i.shardKey,r,"shape_unsubscribe")}}stream(t,e,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new m("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;const r=`stream_${this.nextStreamId.toString()}`,{shardKey:i}=s,n=e??{},{handle:a,iterable:o}=at({maxBuffer:s.maxBuffer,onCancel:()=>{const d=this.getConnection(i);d&&g(d,{id:r,type:"unsubscribe"}),this.streams.delete(r)}});this.ensureSocket(i);const c=this.getConnection(i),u={id:r,query:{args:k(n,`stream args for '${t.__lunoraRef}'`),functionPath:t.__lunoraRef,shardKey:i},type:"stream"};if(this.streams.set(r,{durable:s.durable===!0,handle:a,lastSeq:0,message:u,shardKey:i}),!(c?.wsState==="open"&&g(c,u))&&c){for(c.pendingStreams=c.pendingStreams??[];c.pendingStreams.length>=ft;){const d=c.pendingStreams.shift()?.id,l=d?this.streams.get(d):void 0;l&&(l.handle.fail(new m("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(d))}c.pendingStreams.push(u)}return o}httpStream(t,e,s={}){if(this.closed)throw new m("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new m("INTERNAL","LunoraClient: no `fetch` implementation available");const r={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return Y(t,e,{baseUrl:this.url,fetch:this.fetchImpl,headers:r,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 m("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 m("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 X({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 r=e==="connected"&&this.leaderStatus!=="connected";this.leaderStatus=e,e==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),r&&this.flushAllOfflineQueues()},onSubscriptionData:(e,s,r,i,n)=>{if(n!==void 0&&n!==this.identityFingerprint())return;const a=this.subscriptions.get(e);a&&(a.serverBase=s,r!==void 0&&(a.serverCursor=r,i!==void 0&&(a.serverEpoch=i),F(a,r)),P(a,A(s,a.optimisticLayers)))},onSubscriptionError:(e,s)=>{const r=this.subscriptions.get(e);r&&E(r.errorCallbacks,s)},onSubscriptionSettled:(e,s,r,i,n,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;const o=this.subscriptions.get(e);if(o){this.ackAndAdvanceCursor(o,s,r),i!==void 0&&n===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,r,i,n,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(u){throw O(i),u instanceof Error?u:new Error(String(u))}for(const u of n)u(void 0);return}return new Promise((c,u)=>{const d={args:e,functionPath:t.__lunoraRef,liveAwaiter:!0,id:r,clientId:this.clientId,identity:o,precondition:a,onCommit:l=>{for(const y of n)y(l)},reject:l=>{this.queuedIdentities.delete(r),O(i),u(l instanceof Error?l:new Error(String(l)))},resolve:c,shardKey:s};this.offlineQueue.enqueue(d),this.queuedOfflineShardKeys.add(s),d.id!==void 0&&this.queuedIdentities.set(d.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(st(this.persistenceVersion,s.version)){this.queryCache.remove(e).catch(()=>{});continue}this.hydratedQueryCache.set(e,s)}}catch{}}takeHydratedCache(t,e,s){const r=x(t,e,s),i=this.hydratedQueryCache.get(r);if(i!==void 0)return this.hydratedQueryCache.delete(r),i.identity===this.identityFingerprint()?i:void 0}persistQueryValue(t){const e=t.serverBase;if(!this.queryCache||e===void 0)return;const s=x(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,r])=>t.put(s,r)))}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,r){const i=[],n=[];if(!r)return{confirms:i,rollbacks:n};const a=w.key(t,e,s),o=this.subscriptions.get(a);if(o){const c=Z(o,r);c&&(i.push(c.confirm),n.push(c.rollback))}return{confirms:i,rollbacks:n}}applyOptimisticUpdate(t,e,s,r,i){const{confirms:n,rollbacks:a,store:o}=tt(this.subscriptions,s);try{t(o,e)}catch{O(a);return}r.push(...a),i.push(...n)}getConnection(t){return this.connections.get(p(t))}sendOrQueueUnsubscribe(t,e,s){const r=this.getConnection(t);r&&!g(r,{id:e,type:s})&&r.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=p(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 r=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${r}${s.join("&")}`}rpcRequestHeaders(t,e){const s={"content-type":"application/json"},r=this.shardCursors.get(this.cursorKeyFor(e));if(r!==void 0&&(s["x-lunora-min-seq"]=r.toString()),this.authToken&&(s.authorization=`Bearer ${this.authToken}`),t.mutationId&&(s["x-lunora-mutation-id"]=t.mutationId),(t.clientId!==void 0||t.mutationId!==void 0)&&(s["x-lunora-client-id"]=t.clientId??this.clientId),t.clientSeq!==void 0&&(s["x-lunora-client-seq"]=t.clientSeq.toString()),t.attachBookmark){const i=this.bookmark.get();i&&(s["x-d1-bookmark"]=i)}return s}async rpc(t,e,s,r={}){if(!this.fetchImpl)throw new m("INTERNAL","LunoraClient: no `fetch` implementation available");const i=this.rpcRequestHeaders(r,s),n=await this.fetchImpl(v(this.url,ct),{body:JSON.stringify({args:k(e,`args for '${t}'`),functionPath:t,shardKey:s}),headers:i,method:"POST"});if(r.captureBookmark){const o=n.headers.get("x-d1-bookmark");o&&this.bookmark.set(o)}let a;try{a=await n.json()}catch{const o=n.statusText?` ${n.statusText}`:"";throw new m("INTERNAL",`LunoraClient: response was not JSON (status ${n.status.toString()}${o})`)}if("error"in a)throw T(a.error);if(!n.ok){const o=n.statusText?` ${n.statusText}`:"";throw new m("INTERNAL",`LunoraClient: request failed (status ${n.status.toString()}${o})`)}return r.onMutationAck?.(a.lastMutationId),r.onCommitCursor?.(a.commitCursor),this.learnDefaultShardKey(n,s),this.recordShardCursor(s,a.commitCursor),b(a.result)}async adminFetch(t,e,s,r){if(!this.fetchImpl)throw new m("INTERNAL","LunoraClient: no `fetch` implementation available");const i={};this.authToken&&(i.authorization=`Bearer ${this.authToken}`);const n=s instanceof ArrayBuffer||s instanceof Blob;let a;s===void 0?a=void 0:n?(a=s,r!==void 0&&(i["content-type"]=r)):(a=JSON.stringify(s),i["content-type"]="application/json");const o=await this.fetchImpl(v(this.url,t),{body:a,headers:i,method:e});let c;try{c=await o.json()}catch{const u=o.statusText?` ${o.statusText}`:"";throw new m("INTERNAL",`LunoraClient: response was not JSON (status ${o.status.toString()}${u})`)}if(typeof c=="object"&&c!==null&&"error"in c){const u=c.error,d=new Error(u.message??"admin request failed");throw d.code=u.code,d}if(!o.ok){const u=o.statusText?` ${o.statusText}`:"";throw new m("INTERNAL",`LunoraClient: admin request failed (status ${o.status.toString()}${u})`)}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(p(t.shardKey));g(t,{caps:Ae,clientId:this.clientId,id:"connect",type:"connect",...e===void 0?{}:{context:e}})}resendShapeSubscriptions(t){for(const e of this.shapeSubscriptions.values())p(e.shardKey)===p(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 r;try{r=await s()}catch{this.handleDisconnect(t);return}this.closed||this.WebSocketImpl===void 0||t.wsState!=="connecting"||t.socket!==void 0||this.openSocket(t,e,r)}openManagedSocket(t,e,s,r){const{WebSocketImpl:i}=this;if(i===void 0)throw new m("INTERNAL","no WebSocket implementation available");const n=new i(e);t.socket=n;const a=()=>{this.stopHeartbeat(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket===n&&(t.socket=void 0)},o=c=>{a(),r.onClose(c)};s>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===n){try{n.close()}catch{}o()}},s)),n.addEventListener("open",()=>{t.socket===n&&(t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.lastFrameAt=Date.now(),r.onOpen(),this.startHeartbeat(t,o))}),n.addEventListener("message",c=>{t.socket===n&&(t.lastFrameAt=Date.now(),r.onMessage(c))}),n.addEventListener("close",c=>{t.socket===n&&o(c)}),n.addEventListener("error",()=>{t.socket===n&&o()})}openSocket(t,e,s){this.WebSocketImpl!==void 0&&this.openManagedSocket(t,this.wsUrlFor(e,s),this.connectTimeoutMs,{onClose:r=>{r?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(t)},onMessage:r=>{this.handleServerMessage(r.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())p(i.shardKey)===p(e)&&this.sendSubscribeIfOpen(i);if(this.resendShapeSubscriptions(e),t.pendingUnsubscribes.length>0){const i=t.pendingUnsubscribes;t.pendingUnsubscribes=[];for(const{id:n,type:a}of i)g(t,{id:n,type:a})}if(t.pendingStreams&&t.pendingStreams.length>0){const i=t.pendingStreams;t.pendingStreams=[];for(const n of i)g(t,n)}const r=this.whisperHandlers.get(p(e));if(r)for(const i of r.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(r=>r.id));for(const[r,i]of this.streams)if(!(p(i.shardKey)!==p(t.shardKey)||e.has(r))){if(i.durable){const n={...i.message,sinceChunk:i.lastSeq};i.message=n,t.pendingStreams=[...(t.pendingStreams??[]).filter(a=>a.id!==r),n];continue}i.handle.fail(new m("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.streams.delete(r)}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=p(t);for(const s of this.subscriptions.all())p(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:N(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=Me(t);if(s===void 0)return;let r;try{r=JSON.parse(s)}catch{return}switch(r.type){case"ack":{const i=this.subscriptions.getById(r.id);i&&(i.acked=!0);return}case"chunk":{const{data:i,id:n,seq:a}=r,o=this.streams.get(n);o&&typeof a=="number"&&(o.lastSeq=a,o.durable=!0),o?.handle.push(b(i));return}case"complete":{this.handleCompleteMessage(r.id);return}case"data":case"delta":{this.handleDataMessage(r);return}case"error":{this.handleErrorMessage(r);break}case"pokeEnd":{this.handlePokeEnd(r);break}case"pokePart":{this.handlePokePart(r);break}case"pokeStart":{this.handlePokeStart(r);break}case"resume":{this.handleResumeMessage(r);break}case"settled":{this.handleSettledMessage(r);break}case"whisper":{this.dispatchWhisper(r,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(xe(t)),this.streams.delete(e);return}const r=e===void 0?void 0:this.subscriptions.getById(e);if(r){E(r.errorCallbacks,W(t));return}const i=e===void 0?void 0:this.shapeSubscriptions.get(e);i&&E(i.errorCallbacks,W(t))}handlePokeStart(t){ot(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 r of t.rowsPatch)s.push(r.value===void 0?r:{...r,value:b(r.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,r]of e.parts){const i=this.shapeSubscriptions.get(s);if(!i)continue;const n=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(n||a){i.rows.clear(),i.serverCursor=void 0,i.serverEpoch=void 0,this.emitShapeRows(i),this.sendShapeSubscribeIfOpen(i);continue}ut(i.rows,r),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 r=this.resolveDataPayload(t,s);if(s.serverBase=r,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(r,s.optimisticLayers)),this.tabCoordinator?.isLeader()){const i=w.key(s.fn.__lunoraRef,s.args,s.shardKey);this.tabCoordinator.broadcastSubscriptionData(i,r,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(D(s)&&e.serverBase!==void 0){const r=j(e.serverBase,s);if(r!==void 0)return r}return s}dispatchWhisper(t,e){const s=this.whisperHandlers.get(p(e))?.get(t.topic);if(!s)return;const r=b(t.data);for(const i of s)try{i(r,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=>{rt(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 r=0;r<t.length;r+=1){const i=t.charCodeAt(r);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,r]of this.queuedIdentities)r===t&&this.queuedIdentities.set(s,e)}restampWatermarks(t,e){const s=t??"",r=this.clientWatermarks.get(s);if(r===void 0)return;this.clientWatermarks.delete(s);const i=e??"",n=this.clientWatermarks.get(i);if(n===void 0)this.clientWatermarks.set(i,r);else for(const[a,o]of r)n.set(a,o)}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 u=new Error("offline mutation skipped: precondition failed before replay");u.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(c,"rejected",u)}const s=p(t),r=this.offlineQueue.drain(c=>p(c.shardKey)===s);if(r.length===0)return;const i=this.identityFingerprint(),n=[];for(const c of r)this.passesReplayIdentityGate(c,i)&&n.push(c);if(n.length===0)return;const a=this.encodableOrSettleTerminal(n);if(a.length===0)return;if(a.length===1){await this.replaySequential(a);return}const o=[];for(let c=0;c<a.length;c+=R){const u=a.slice(c,c+R),d=await this.replayBatched(u);if(o.push(...d.requeue),d.stop){o.push(...a.slice(c+R));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(r){this.settleReplayTerminal(s,r instanceof Error?r:new Error(String(r)))}return e}passesReplayIdentityGate(t,e){const s=t.id===void 0?void 0:this.queuedIdentities.get(t.id),r=s===void 0?t.identity:s;if(r!==void 0&&r!==e&&!this.isSameCredentialUnderTokenHash(r)){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),this.recordShardCursor(t.shardKey,s),t.onCommit?.(s),t.resolve(e),this.emitItemSettled(t,"committed")}cursorKeyFor(t){return t??this.defaultShardKey??""}learnDefaultShardKey(t,e){const s=t.headers.get("x-lunora-shard-key");if(s===null||e!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;const r=this.shardCursors.get("");r!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,r)),this.shardCursors.delete(""))}recordShardCursor(t,e){if(typeof e!="number")return;const s=this.cursorKeyFor(t);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,e))}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 r;const i=await this.rpc(s.functionPath,s.args,s.shardKey,{captureBookmark:!0,clientId:s.clientId??this.clientId,mutationId:s.id,onCommitCursor:n=>{r=n}});this.settleReplaySuccess(s,i,r)}catch(r){if(r.code!==void 0){this.settleReplayTerminal(s,r);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(v(this.url,Q),{body:JSON.stringify({calls:t.map((i,n)=>({args:k(i.args,`args for '${i.functionPath}'`),functionPath:i.functionPath,id:n,clientId:i.clientId??this.clientId,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 r;try{r=await e.json()}catch{return{requeue:t,stop:!0}}if(!r.results){if(r.error){const i=T(r.error);for(const n of t)this.settleReplayTerminal(n,i);return{requeue:[],stop:!1}}return{requeue:t,stop:!0}}return{requeue:this.settleReplayBatchSlots(t,r.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 r=[];for(const[i,n]of t.entries()){const a=s.get(i);a===void 0?r.push(n):"error"in a?Ke.has(a.error.code)?r.push(n):this.settleReplayTerminal(n,T(a.error)):this.settleReplaySuccess(n,b(a.result),a.commitCursor)}return r}}export{z as LunoraClient};
@@ -1 +1 @@
1
- import{LunoraClient as r}from"./LunoraClient-BluyW2SA.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
+ import{LunoraClient as r}from"./LunoraClient-M_ArXnWT.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};
@@ -533,11 +533,22 @@ declare class LunoraClient {
533
533
  private readonly readyPromise;
534
534
  /**
535
535
  * Highest custom-mutator watermark the server has echoed for this client,
536
- * keyed by shard bucket (`shardKey ?? ""`) since the DO tracks one
537
- * `__client_watermark` per shard. `callMutator` bumps it from every
538
- * ack; the `@lunora/db` mutator runtime seeds its `clientSeq` generator from
539
- * it so a reload (which resets the in-memory counter) never reissues a stale
540
- * sequence the server would silently swallow as a replay.
536
+ * nested by identity fingerprint (`identityFingerprint() ?? ""`) then shard
537
+ * bucket (`shardKey ?? ""`) the DO tracks one `__client_watermark` per
538
+ * `(identity, clientId)` pair, not per bucket alone, so a bucket-only key
539
+ * would let a user switch claim the previous identity's sequence and wedge
540
+ * every push on `OUT_OF_ORDER` until a reload (plan 316). A nested map
541
+ * (rather than a single map composite-keyed by a joined string) is what a
542
+ * previous fix here tried and got wrong: an identity fingerprint or a
543
+ * `shardKey` is an arbitrary string, so any string delimiter — even one as
544
+ * exotic as U+FFFD — can appear in one operand and collide with the other
545
+ * (a fingerprint of `a<SEP>x` + bucket `y` joins to the same string as
546
+ * a fingerprint of `a` + bucket `x<SEP>y`), mixing two identities' watermarks.
547
+ * The nested map has no join step, so there is no delimiter to collide.
548
+ * `callMutator` bumps it from every ack; the `@lunora/db` mutator runtime
549
+ * seeds its `clientSeq` generator from it so a reload (which resets the
550
+ * in-memory counter) never reissues a stale sequence the server would
551
+ * silently swallow as a replay.
541
552
  */
542
553
  private readonly clientWatermarks;
543
554
  /** Monotonic per-client mutation counter backing the server `__client_watermark`. */
@@ -2098,6 +2109,21 @@ declare class LunoraClient {
2098
2109
  * instead of the flush guard discarding them as a mismatch.
2099
2110
  */
2100
2111
  private restampQueuedIdentity;
2112
+ /**
2113
+ * Migrate the {@link clientWatermarks} bucket map nested under identity
2114
+ * `from` to identity `to` — the sibling of {@link restampQueuedIdentity},
2115
+ * for the same same-credential-subject-resolves case. Without this, a
2116
+ * bucket's watermark cached under the token-hash fingerprint would look
2117
+ * unset once the fingerprint relabels to `subj:…`, so the next push
2118
+ * re-derives `1` against a server watermark the DO already advanced — the
2119
+ * OUT_OF_ORDER wedge this cache-keying scheme exists to fix, reintroduced
2120
+ * by the fix itself. `to` may already hold a bucket map (switching back to
2121
+ * an identity that has its own cached watermarks); merge into it rather
2122
+ * than clobbering it, with `from`'s entries winning on a colliding bucket —
2123
+ * the same overwrite a plain `Map.set` would have done before this was a
2124
+ * nested map.
2125
+ */
2126
+ private restampWatermarks;
2101
2127
  /**
2102
2128
  * Drop the durable read cache on an identity change so a cached value stamped
2103
2129
  * under the previous identity can never hydrate into a new session. Clears
@@ -533,11 +533,22 @@ declare class LunoraClient {
533
533
  private readonly readyPromise;
534
534
  /**
535
535
  * Highest custom-mutator watermark the server has echoed for this client,
536
- * keyed by shard bucket (`shardKey ?? ""`) since the DO tracks one
537
- * `__client_watermark` per shard. `callMutator` bumps it from every
538
- * ack; the `@lunora/db` mutator runtime seeds its `clientSeq` generator from
539
- * it so a reload (which resets the in-memory counter) never reissues a stale
540
- * sequence the server would silently swallow as a replay.
536
+ * nested by identity fingerprint (`identityFingerprint() ?? ""`) then shard
537
+ * bucket (`shardKey ?? ""`) the DO tracks one `__client_watermark` per
538
+ * `(identity, clientId)` pair, not per bucket alone, so a bucket-only key
539
+ * would let a user switch claim the previous identity's sequence and wedge
540
+ * every push on `OUT_OF_ORDER` until a reload (plan 316). A nested map
541
+ * (rather than a single map composite-keyed by a joined string) is what a
542
+ * previous fix here tried and got wrong: an identity fingerprint or a
543
+ * `shardKey` is an arbitrary string, so any string delimiter — even one as
544
+ * exotic as U+FFFD — can appear in one operand and collide with the other
545
+ * (a fingerprint of `a<SEP>x` + bucket `y` joins to the same string as
546
+ * a fingerprint of `a` + bucket `x<SEP>y`), mixing two identities' watermarks.
547
+ * The nested map has no join step, so there is no delimiter to collide.
548
+ * `callMutator` bumps it from every ack; the `@lunora/db` mutator runtime
549
+ * seeds its `clientSeq` generator from it so a reload (which resets the
550
+ * in-memory counter) never reissues a stale sequence the server would
551
+ * silently swallow as a replay.
541
552
  */
542
553
  private readonly clientWatermarks;
543
554
  /** Monotonic per-client mutation counter backing the server `__client_watermark`. */
@@ -2098,6 +2109,21 @@ declare class LunoraClient {
2098
2109
  * instead of the flush guard discarding them as a mismatch.
2099
2110
  */
2100
2111
  private restampQueuedIdentity;
2112
+ /**
2113
+ * Migrate the {@link clientWatermarks} bucket map nested under identity
2114
+ * `from` to identity `to` — the sibling of {@link restampQueuedIdentity},
2115
+ * for the same same-credential-subject-resolves case. Without this, a
2116
+ * bucket's watermark cached under the token-hash fingerprint would look
2117
+ * unset once the fingerprint relabels to `subj:…`, so the next push
2118
+ * re-derives `1` against a server watermark the DO already advanced — the
2119
+ * OUT_OF_ORDER wedge this cache-keying scheme exists to fix, reintroduced
2120
+ * by the fix itself. `to` may already hold a bucket map (switching back to
2121
+ * an identity that has its own cached watermarks); merge into it rather
2122
+ * than clobbering it, with `from`'s entries winning on a colliding bucket —
2123
+ * the same overwrite a plain `Map.set` would have done before this was a
2124
+ * nested map.
2125
+ */
2126
+ private restampWatermarks;
2101
2127
  /**
2102
2128
  * Drop the durable read cache on an identity change so a cached value stamped
2103
2129
  * under the previous identity can never hydrate into a new session. Clears
@@ -1,4 +1,4 @@
1
- import { L as LunoraClient } from "./lunora-client.d-nHupuaoI.mjs";
1
+ import { L as LunoraClient } from "./lunora-client.d-BOmxvSrG.mjs";
2
2
  import { F as FunctionReference, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./types.d-CsuRAQvb.mjs";
3
3
  /**
4
4
  * Run a query once on the server (during SSR) and capture its result in a
@@ -1,4 +1,4 @@
1
- import { L as LunoraClient } from "./lunora-client.d-Dv40CCsu.js";
1
+ import { L as LunoraClient } from "./lunora-client.d-K16SL8Tj.js";
2
2
  import { F as FunctionReference, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./types.d-CsuRAQvb.js";
3
3
  /**
4
4
  * Run a query once on the server (during SSR) and capture its result in a
@@ -1,6 +1,6 @@
1
1
  import { F as FunctionReference, A as ArgsOf, R as ReturnOf, a as Unsubscribe } from "../packem_shared/types.d-CsuRAQvb.mjs";
2
- import { S as SubscriptionError, L as LunoraClient } from "../packem_shared/lunora-client.d-nHupuaoI.mjs";
3
- export type { a as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-nHupuaoI.mjs";
2
+ import { S as SubscriptionError, L as LunoraClient } from "../packem_shared/lunora-client.d-BOmxvSrG.mjs";
3
+ export type { a as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-BOmxvSrG.mjs";
4
4
  import '@lunora/runtime';
5
5
  /**
6
6
  * The sentinel a framework adapter resolves its reactive args to when it wants
@@ -1,6 +1,6 @@
1
1
  import { F as FunctionReference, A as ArgsOf, R as ReturnOf, a as Unsubscribe } from "../packem_shared/types.d-CsuRAQvb.js";
2
- import { S as SubscriptionError, L as LunoraClient } from "../packem_shared/lunora-client.d-Dv40CCsu.js";
3
- export type { a as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-Dv40CCsu.js";
2
+ import { S as SubscriptionError, L as LunoraClient } from "../packem_shared/lunora-client.d-K16SL8Tj.js";
3
+ export type { a as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-K16SL8Tj.js";
4
4
  import '@lunora/runtime';
5
5
  /**
6
6
  * The sentinel a framework adapter resolves its reactive args to when it wants
@@ -1,7 +1,7 @@
1
1
  import { P as Preloaded } from "../packem_shared/types.d-CsuRAQvb.mjs";
2
2
  export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/types.d-CsuRAQvb.mjs";
3
- export { p as preloadQuery, a as preloadedQueryResult } from "../packem_shared/preload.d-y5DTDa0X.mjs";
4
- import { L as LunoraClient } from "../packem_shared/lunora-client.d-nHupuaoI.mjs";
3
+ export { p as preloadQuery, a as preloadedQueryResult } from "../packem_shared/preload.d-BprjXhJi.mjs";
4
+ import { L as LunoraClient } from "../packem_shared/lunora-client.d-BOmxvSrG.mjs";
5
5
  import '@lunora/runtime';
6
6
  /**
7
7
  * Structural shape of a better-auth `getSession` call's resolved value.
@@ -1,7 +1,7 @@
1
1
  import { P as Preloaded } from "../packem_shared/types.d-CsuRAQvb.js";
2
2
  export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/types.d-CsuRAQvb.js";
3
- export { p as preloadQuery, a as preloadedQueryResult } from "../packem_shared/preload.d-DtFFNok3.js";
4
- import { L as LunoraClient } from "../packem_shared/lunora-client.d-Dv40CCsu.js";
3
+ export { p as preloadQuery, a as preloadedQueryResult } from "../packem_shared/preload.d-CM8-Mg2A.js";
4
+ import { L as LunoraClient } from "../packem_shared/lunora-client.d-K16SL8Tj.js";
5
5
  import '@lunora/runtime';
6
6
  /**
7
7
  * Structural shape of a better-auth `getSession` call's resolved value.
@@ -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-DoNhxkkm.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};
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-BywwAr17.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.48",
3
+ "version": "1.0.0-alpha.49",
4
4
  "description": "Lunora browser SDK: WebSocket transport, optimistic updates, and an offline mutation queue",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -1 +0,0 @@
1
- import{LunoraError as p}from"@lunora/errors";import{w as D,y as j,a as H}from"./delta-merge-DoT5IpTP.mjs";import{s as b,a as B}from"./wire-codec-aTWt2XiW.mjs";import{t as I}from"./wire-key-Cb-kXfSh.mjs";import V from"./createInMemoryBookmarkStorage-DCd5Ej-t.mjs";import{ClientQueryStore as J}from"./createClientQuery-CrdRoicO.mjs";import{TabCoordinator as X}from"./TabCoordinator-CMFYQCL-.mjs";import{httpStream as Y}from"./httpStream-Cz4_QyjV.mjs";import{d as F,n as P,f as A,a as Z,c as tt}from"./local-store-CGsgaEph.mjs";import{h as et,u as $,d as st,s as rt}from"./offline-queue-CKMw-5rF.mjs";import{resolvePersistenceAdapter as it}from"./createInMemoryPersistence-CQYXy8UP.mjs";import{resolveQueryCacheAdapter as nt,queryCacheKey as x}from"./createInMemoryQueryCache-DjCKrLjk.mjs";import{createReconnect as q}from"./createReconnect-CFT7YRSR.mjs";import{createStream as at}from"./DEFAULT_MAX_BUFFER-TBn2s7Rz.mjs";import{SubscriptionRegistry as w}from"./SubscriptionRegistry-HXgW6BXq.mjs";const R=500,ot=(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 ct="/_lunora/rpc",Q="/_lunora/rpc-batch",ht="/_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]?.()},ut=(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",lt=3e4,pt=1e4,mt=250,ft=64,yt="/_lunora/admin/shard-traffic",gt="/_lunora/admin/scheduled",bt="/_lunora/admin/scheduled/status",St="/_lunora/admin/scheduled/ws",vt="/_lunora/admin/scheduled/cancel",kt="/_lunora/admin/scheduled/dead",wt="/_lunora/admin/scheduled/dead/retry",Ct="/_lunora/admin/scheduled/dead/cancel",Tt="/_lunora/admin/workflows/instances",It="/_lunora/admin/workflows/instance",Ot="/_lunora/admin/workflows/status",L="/_lunora/admin/storage",Et="/_lunora/admin/storage/url",_t="/_lunora/admin/storage/buckets",Ft="/_lunora/admin/functions",Pt="/_lunora/admin/cron-jobs",At="/_lunora/admin/cron-jobs/run",xt="/_lunora/admin/openapi",Rt="/_lunora/admin/openrpc",Mt="/_lunora/admin/global/tables",Lt="/_lunora/admin/global/table",Kt="/_lunora/admin/global/facet",$t="/_lunora/admin/vector/indexes",qt="/_lunora/admin/vector/query",Qt="/_lunora/admin/logs/archive",Ut="/_lunora/admin/kv/namespaces",Nt="/_lunora/admin/kv/keys",K="/_lunora/admin/kv/value",Bt="/_lunora/admin/auth/users",Wt="/_lunora/admin/auth/sessions",zt="/_lunora/admin/auth/users/create",Gt="/_lunora/admin/auth/users/role",Dt="/_lunora/admin/auth/users/ban",jt="/_lunora/admin/auth/users/unban",Ht="/_lunora/admin/auth/users/password",Vt="/_lunora/admin/auth/users/remove",Jt="/_lunora/admin/auth/users/impersonate",Xt="/_lunora/admin/auth/sessions/revoke",Yt="/_lunora/admin/auth/sessions/revoke-all",Zt="/_lunora/admin/auth/capabilities",te="/_lunora/admin/auth/users/update",ee="/_lunora/admin/auth/accounts",se="/_lunora/admin/auth/accounts/unlink",re="/_lunora/admin/auth/passkeys",ie="/_lunora/admin/auth/passkeys/delete",ne="/_lunora/admin/auth/two-factor/disable",ae="/_lunora/admin/auth/organizations",oe="/_lunora/admin/auth/organizations/members",ce="/_lunora/admin/auth/organizations/invitations",he="/_lunora/admin/auth/organizations/members/remove",ue="/_lunora/admin/auth/organizations/invitations/cancel",de="/_lunora/admin/auth/config",le="/_lunora/admin/auth/organizations/create",pe="/_lunora/admin/auth/organizations/update",me="/_lunora/admin/auth/organizations/remove",fe="/_lunora/admin/auth/organizations/members/add",ye="/_lunora/admin/auth/organizations/members/invite",ge="/_lunora/admin/auth/organizations/members/role",be="/_lunora/admin/auth/organizations/teams",Se="/_lunora/admin/auth/organizations/teams/create",ve="/_lunora/admin/auth/organizations/teams/update",ke="/_lunora/admin/auth/organizations/teams/remove",we="/_lunora/admin/auth/organizations/teams/members",Ce="/_lunora/admin/auth/organizations/teams/members/add",Te="/_lunora/admin/auth/organizations/teams/members/remove",Ie="/_lunora/admin/auth/organizations/roles",Oe="/_lunora/admin/auth/organizations/roles/create",Ee="/_lunora/admin/auth/organizations/roles/update",_e="/_lunora/admin/auth/organizations/roles/remove",Fe="/api/auth",Pe="/get-session",U=h=>h.startsWith("https://")?`wss://${h.slice(8)}`:h.startsWith("http://")?`ws://${h.slice(7)}`:h,v=(h,t)=>`${h.endsWith("/")?h.slice(0,-1):h}${t}`,f=(h,t)=>{const e=new URLSearchParams;for(const[r,i]of Object.entries(t))i!==void 0&&i!==""&&e.set(r,String(i));const s=e.toString();return s===""?h:`${h}?${s}`},Ae=[H],m=h=>h??"",W=(h,t)=>{const e=h.error,s=typeof e?.code=="string"?e.code:void 0,r=typeof e?.message=="string"?e.message:void 0;return{code:s,messageText:(typeof h.message=="string"?h.message:void 0)??r??t}},xe=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{}},Re=new TextDecoder,Me=h=>{if(typeof h=="string")return h;if(h instanceof ArrayBuffer)return Re.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 r=s.body;e[s.id]=r&&"error"in r&&r.error?{error:T(r.error),ok:!1}:{ok:!0,value:b(r?.result)}}return e.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},Ke=new Set(["SHARD_ERROR","SHARD_UNAVAILABLE"]),$e=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;shardCursors=new Map;defaultShardKey;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??v(U(t.url),ht),this.wsToken=t.wsToken;const e=t.authBasePath??Fe;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??V(),this.reconnectOptions=t.reconnect,this.heartbeatIntervalMs=t.heartbeatIntervalMs??lt,this.connectTimeoutMs=t.connectTimeoutMs??pt,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=$e),this.offlineQueue=new et(t.offlineQueue,{onEvict:(s,r)=>{this.emitItemSettled(s,"rejected",r)},onSizeChange:s=>{this.pendingChangeListeners.emit(s)},persistence:this.persistence,version:t.persistenceVersion}),this.outbox=t.outbox,this.clientId=t.clientId??`client-${$()}`,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,r=this.identityFingerprint();this.authToken=t,e!==void 0&&(this.authSubject=e);const i=this.identityFingerprint();if(i!==r&&(s?this.rejectQueuedForIdentityChange():this.restampQueuedIdentity(r,i),this.tabCoordinator)){const n=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),n&&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 r=s?.clientSeq;if(r!==void 0&&(!Number.isInteger(r)||r<=0))throw new p("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(r)}`);const i=s?.shardKey??"";let n;const a=await this.rpc(t,e,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:r,onMutationAck:o=>{n=o}});return n!==void 0&&n>(this.clientWatermarks.get(i)??0)&&this.clientWatermarks.set(i,n),{applied:n===void 0||n===r,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(v(this.url,`${this.authBasePath}${Pe}`),{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),r={context:t},i=this.connectionContextHolders.get(s);i?i.push(r):this.connectionContextHolders.set(s,[r]),this.refreshConnectionContext(s);let n=!1;return()=>{if(n)return;n=!0;const a=this.connectionContextHolders.get(s);if(!a)return;const o=a.indexOf(r);o!==-1&&a.splice(o,1),a.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s)}}whisperSubscribe(t,e,s={}){const r=m(s.shardKey);let i=this.whisperHandlers.get(r);i||(i=new Map,this.whisperHandlers.set(r,i));let n=i.get(t);const a=n===void 0;if(n||(n=new Set,i.set(t,n)),n.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(r),c=o?.get(t);if(!c?.delete(e)||c.size>0)return;o?.delete(t),o?.size===0&&this.whisperHandlers.delete(r);const u=this.getConnection(s.shardKey);u&&g(u,{topic:t,type:"whisper_unsubscribe"})}}whisper(t,e,s={}){this.ensureSocket(s.shardKey);const r=this.getConnection(s.shardKey);r&&g(r,{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 r of e){const i=this.connections.get(r);t.push({confirmedMutationWatermark:this.clientWatermarks.get(r)??0,hasSocket:i?.socket!==void 0,shardKey:r===""?void 0:r,wasEverConnected:i?.wasEverConnected??!1,wsState:i?.wsState??"idle"})}const s=this.subscriptions.all().map(r=>({acked:r.acked,functionPath:r.fn.__lunoraRef,id:r.id,kind:"query",lastMutationId:r.lastMutationId,pendingOptimisticLayers:r.optimisticLayers.length,serverCursor:r.serverCursor,shardKey:r.shardKey,subscriberCount:r.callbacks.size}));for(const r of this.shapeSubscriptions.values())s.push({acked:r.serverCursor!==void 0,functionPath:`shape:${r.name}`,id:r.id,kind:"shape",lastMutationId:r.lastMutationId,pendingOptimisticLayers:0,rowCount:r.rows.size,serverCursor:r.serverCursor,shardKey:r.shardKey,subscriberCount:r.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:t.toSorted((r,i)=>(r.shardKey??"").localeCompare(i.shardKey??"")),subscriptions:s.toSorted((r,i)=>r.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 r=this.peekActiveQueryValue(t.__lunoraRef,e,s),i=r===void 0?void 0:I(r);return()=>{const n=this.peekActiveQueryValue(t.__lunoraRef,e,s);return i===void 0&&n===void 0?!0:i===void 0||n===void 0?!1:I(n)===i}}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(t,e,s){if(!this.readyResolved)return;const r=I(e),i=x(t,r,s),n=this.hydratedQueryCache.get(i);if(n!==void 0)return n.identity===this.identityFingerprint()?n.value:void 0}peekActiveQueryValue(t,e,s){const r=w.key(t,e,s);return this.subscriptions.get(r)?.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(v(this.url,Q),{body:JSON.stringify({calls:t.map((i,n)=>({args:k(i.args??{},`args for batch call '${i.fn.__lunoraRef}'`),functionPath:i.fn.__lunoraRef,id:n,shardKey:i.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"}),s=e.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let r;try{r=await e.json()}catch{throw new p("INTERNAL",`LunoraClient: batch response was not JSON (status ${e.status.toString()})`)}if(!e.ok||r.error&&!r.results)throw r.error?T(r.error):new p("INTERNAL",`LunoraClient: batch request failed (status ${e.status.toString()})`);for(const i of r.results??[]){const n=i.body?.commitCursor;typeof i.id=="number"&&typeof n=="number"&&this.recordShardCursor(t[i.id]?.shardKey,n)}return Le(r.results??[],t.length)}async mutation(t,e,s={}){this.assertOpen();const r=e,i=s.mutationId??$(),{confirms:n,rollbacks:a}=this.applyOptimisticUpdates(t.__lunoraRef,r,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,e,s.shardKey,a,n);const{hasSocket:o,wasEverConnected:c,wsState:u}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:d}=this.offlineQueue,l=c||d,y=this.WebSocketImpl!==void 0&&l;if(u!=="open"&&!o&&y||u==="connecting"&&l)return this.enqueueOfflineMutation(t,r,s.shardKey,i,a,n,s.precondition);try{let S;const G=await this.rpc(t.__lunoraRef,r,s.shardKey,{captureBookmark:!0,mutationId:i,onCommitCursor:_=>{S=_}});for(const _ of n)_(S);return G}catch(S){throw O(a),S}}async action(t,e,s={}){return this.assertOpen(),await this.rpc(t.__lunoraRef,e,s.shardKey)}async importRows(t,e,s={}){this.assertOpen();const r=Math.max(1,Math.trunc(s.chunkSize??500)),i=s.toArgs??(c=>({rows:c})),n=e.length;let a=0,o=0;for(let c=0;c<n;c+=r){const u=e.slice(c,c+r),d=o;await this.mutation(t,i(u),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(d)}`},shardKey:s.shardKey}),o+=1,a+=u.length,s.onProgress?.({done:a,total:n})}return{chunks:o,imported:a}}async shardTraffic(t){this.assertOpen();const e=await this.adminFetch(yt,"POST",{table:t});return{failed:e.failed??0,ok:e.ok??0,shards:e.shards??[]}}async listScheduledJobs(){return this.assertOpen(),(await this.adminFetch(gt,"GET")).records??[]}async schedulerStatus(){this.assertOpen();const t=await this.adminFetch(bt,"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(kt,"GET")).records??[]}async retryDeadJob(t){return this.assertOpen(),{retried:(await this.adminFetch(wt,"POST",{id:t})).retried===!0}}async removeDeadJob(t){return this.assertOpen(),{removed:(await this.adminFetch(Ct,"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(`${Tt}?${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(`${It}?${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(Ot,"POST",{action:t.action,id:t.id,name:t.name})).status??"unknown"}}subscribeScheduledJobs(t){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const e=v(U(this.url),St),s=q(this.reconnectOptions),r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let i,n=!1;const a=()=>{n||(i=setTimeout(u,s.next()))},o=d=>{if(n||this.WebSocketImpl===void 0)return;const l=d===void 0?e:`${e}?token=${encodeURIComponent(d)}`;this.openManagedSocket(r,l,this.connectTimeoutMs,{onClose:()=>{a()},onMessage:y=>{try{const S=JSON.parse(typeof y.data=="string"?y.data:"");S.type==="jobs"&&Array.isArray(S.records)&&t(S.records)}catch{}},onOpen:()=>{s.reset()}})},c=async d=>{let l;try{l=await d()}catch{a();return}o(l)},u=()=>{if(n||this.WebSocketImpl===void 0)return;const{wsToken:d}=this;if(typeof d=="function"){c(d).catch(()=>{});return}o(d)};return u(),()=>{n=!0,i!==void 0&&clearTimeout(i),r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),this.stopHeartbeat(r),r.socket?.close()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(Ft,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(Pt,"GET")).jobs??[]}async runCronJob(t){this.assertOpen();const e=await this.adminFetch(At,"POST",{name:t});return{name:e.name??t,ran:e.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(xt,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(Rt,"GET")}async listStorageObjects(t={}){this.assertOpen();const e=f(L,{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=`${L}?key=${encodeURIComponent(t)}${M(e?.bucket)}`,r=await this.adminFetch(s,"DELETE");return{deleted:r.deleted??!0,key:r.key??t}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(_t,"GET")).buckets??[]}async uploadStorageObject(t){this.assertOpen();const e=`${L}?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,r=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,i=`${Et}?key=${encodeURIComponent(t)}${r}${M(e?.bucket)}`,n=await this.adminFetch(i,"GET");if(typeof n.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return n.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(Mt,"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(`${Lt}?${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(`${Kt}?${e.toString()}`,"GET")}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch($t,"GET")).indexes??[]}async queryVectorIndex(t){return this.assertOpen(),(await this.adminFetch(qt,"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(Ut,"GET")).namespaces??[]}async listKvKeys(t){this.assertOpen();const e=f(Nt,{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(K,{key:t.key,namespace:t.namespace});return await this.adminFetch(e,"GET")}async putKvValue(t){this.assertOpen(),await this.adminFetch(K,"PUT",t)}async deleteKvKey(t){this.assertOpen();const e=f(K,{key:t.key,namespace:t.namespace});await this.adminFetch(e,"DELETE")}async listAuthUsers(t={}){this.assertOpen();const e=f(Bt,{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(zt,"POST",t)}async setAuthUserRole(t){return await this.adminFetch(Gt,"POST",t)}async banAuthUser(t){return await this.adminFetch(Dt,"POST",t)}async unbanAuthUser(t){return await this.adminFetch(jt,"POST",t)}async setAuthUserPassword(t){await this.adminFetch(Ht,"POST",t)}async removeAuthUser(t){await this.adminFetch(Vt,"POST",t)}async impersonateAuthUser(t){return await this.adminFetch(Jt,"POST",t)}async revokeAuthSession(t){await this.adminFetch(Xt,"POST",t)}async revokeAuthUserSessions(t){await this.adminFetch(Yt,"POST",t)}async getAuthCapabilities(){return await this.adminFetch(Zt,"GET")}async updateAuthUser(t){return await this.adminFetch(te,"POST",t)}async listAuthAccounts(t){return await this.adminFetch(f(ee,{userId:t.userId}),"GET")}async unlinkAuthAccount(t){await this.adminFetch(se,"POST",t)}async listAuthPasskeys(t){return await this.adminFetch(f(re,{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(ae,{limit:t.limit,offset:t.offset}),"GET")}async listAuthOrgMembers(t){const e=f(oe,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async listAuthOrgInvitations(t){const e=f(ce,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async removeAuthOrgMember(t){await this.adminFetch(he,"POST",t)}async cancelAuthOrgInvitation(t){await this.adminFetch(ue,"POST",t)}async getAuthConfig(){return await this.adminFetch(de,"GET")}async createAuthOrganization(t){return await this.adminFetch(le,"POST",t)}async updateAuthOrganization(t){return await this.adminFetch(pe,"POST",t)}async deleteAuthOrganization(t){await this.adminFetch(me,"POST",t)}async addAuthOrgMember(t){return await this.adminFetch(fe,"POST",t)}async inviteAuthOrgMember(t){return await this.adminFetch(ye,"POST",t)}async setAuthOrgMemberRole(t){return await this.adminFetch(ge,"POST",t)}async listAuthOrgTeams(t){const e=f(be,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async createAuthOrgTeam(t){return await this.adminFetch(Se,"POST",t)}async updateAuthOrgTeam(t){return await this.adminFetch(ve,"POST",t)}async removeAuthOrgTeam(t){await this.adminFetch(ke,"POST",t)}async listAuthOrgTeamMembers(t){const e=f(we,{limit:t.limit,offset:t.offset,teamId:t.teamId});return await this.adminFetch(e,"GET")}async addAuthOrgTeamMember(t){return await this.adminFetch(Ce,"POST",t)}async removeAuthOrgTeamMember(t){await this.adminFetch(Te,"POST",t)}async listAuthOrgRoles(t){const e=f(Ie,{limit:t.limit,offset:t.offset,organizationId:t.organizationId});return await this.adminFetch(e,"GET")}async createAuthOrgRole(t){return await this.adminFetch(Oe,"POST",t)}async updateAuthOrgRole(t){return await this.adminFetch(Ee,"POST",t)}async deleteAuthOrgRole(t){await this.adminFetch(_e,"POST",t)}async listAuthSessions(t={}){this.assertOpen();const e=f(Wt,{limit:t.limit,offset:t.offset,userId:t.userId});return await this.adminFetch(e,"GET")}subscribe(t,e,s,r={}){this.assertOpen();const i=e??{},n=w.key(t.__lunoraRef,i,r.shardKey);let a=this.subscriptions.get(n);const o=s,c=r.onError;if(!a){this.nextSubId+=1;const d=`sub_${this.nextSubId.toString()}`,l=I(i),y=this.takeHydratedCache(t.__lunoraRef,l,r.shardKey);a={acked:!1,args:i,argsKey:l,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:t,id:d,lastValue:y?.value,optimisticLayers:[],serverBase:y?.value,serverCursor:y?.serverCursor,shardKey:r.shardKey,...y?.serverEpoch===void 0?{}:{serverEpoch:y.serverEpoch}},this.subscriptions.add(a)}if(a.callbacks.add(o),c&&a.errorCallbacks.add(c),r.onCheckpoint&&a.checkpointCallbacks.add(r.onCheckpoint),a.lastValue!==void 0)try{o(a.lastValue)}catch{}this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(a);const u=a;return()=>{u.callbacks.delete(o),c&&u.errorCallbacks.delete(c),r.onCheckpoint&&u.checkpointCallbacks.delete(r.onCheckpoint),u.callbacks.size===0&&(this.sendOrQueueUnsubscribe(u.shardKey,u.id,"unsubscribe"),this.subscriptions.remove(u))}}subscribeShape(t,e,s={}){this.assertOpen(),this.nextShapeId+=1;const r=`shape_${this.nextShapeId.toString()}`,i={args:t.args,callbacks:new Set([e]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:r,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(r,i),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(i),()=>{this.shapeSubscriptions.delete(r),this.sendOrQueueUnsubscribe(i.shardKey,r,"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 r=`stream_${this.nextStreamId.toString()}`,{shardKey:i}=s,n=e??{},{handle:a,iterable:o}=at({maxBuffer:s.maxBuffer,onCancel:()=>{const d=this.getConnection(i);d&&g(d,{id:r,type:"unsubscribe"}),this.streams.delete(r)}});this.ensureSocket(i);const c=this.getConnection(i),u={id:r,query:{args:k(n,`stream args for '${t.__lunoraRef}'`),functionPath:t.__lunoraRef,shardKey:i},type:"stream"};if(this.streams.set(r,{durable:s.durable===!0,handle:a,lastSeq:0,message:u,shardKey:i}),!(c?.wsState==="open"&&g(c,u))&&c){for(c.pendingStreams=c.pendingStreams??[];c.pendingStreams.length>=ft;){const d=c.pendingStreams.shift()?.id,l=d?this.streams.get(d):void 0;l&&(l.handle.fail(new p("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(d))}c.pendingStreams.push(u)}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 r={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return Y(t,e,{baseUrl:this.url,fetch:this.fetchImpl,headers:r,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 X({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 r=e==="connected"&&this.leaderStatus!=="connected";this.leaderStatus=e,e==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),r&&this.flushAllOfflineQueues()},onSubscriptionData:(e,s,r,i,n)=>{if(n!==void 0&&n!==this.identityFingerprint())return;const a=this.subscriptions.get(e);a&&(a.serverBase=s,r!==void 0&&(a.serverCursor=r,i!==void 0&&(a.serverEpoch=i),F(a,r)),P(a,A(s,a.optimisticLayers)))},onSubscriptionError:(e,s)=>{const r=this.subscriptions.get(e);r&&E(r.errorCallbacks,s)},onSubscriptionSettled:(e,s,r,i,n,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;const o=this.subscriptions.get(e);if(o){this.ackAndAdvanceCursor(o,s,r),i!==void 0&&n===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,r,i,n,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(u){throw O(i),u instanceof Error?u:new Error(String(u))}for(const u of n)u(void 0);return}return new Promise((c,u)=>{const d={args:e,functionPath:t.__lunoraRef,liveAwaiter:!0,id:r,clientId:this.clientId,identity:o,precondition:a,onCommit:l=>{for(const y of n)y(l)},reject:l=>{this.queuedIdentities.delete(r),O(i),u(l instanceof Error?l:new Error(String(l)))},resolve:c,shardKey:s};this.offlineQueue.enqueue(d),this.queuedOfflineShardKeys.add(s),d.id!==void 0&&this.queuedIdentities.set(d.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(st(this.persistenceVersion,s.version)){this.queryCache.remove(e).catch(()=>{});continue}this.hydratedQueryCache.set(e,s)}}catch{}}takeHydratedCache(t,e,s){const r=x(t,e,s),i=this.hydratedQueryCache.get(r);if(i!==void 0)return this.hydratedQueryCache.delete(r),i.identity===this.identityFingerprint()?i:void 0}persistQueryValue(t){const e=t.serverBase;if(!this.queryCache||e===void 0)return;const s=x(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(()=>{})},mt)}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,r])=>t.put(s,r)))}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,r){const i=[],n=[];if(!r)return{confirms:i,rollbacks:n};const a=w.key(t,e,s),o=this.subscriptions.get(a);if(o){const c=Z(o,r);c&&(i.push(c.confirm),n.push(c.rollback))}return{confirms:i,rollbacks:n}}applyOptimisticUpdate(t,e,s,r,i){const{confirms:n,rollbacks:a,store:o}=tt(this.subscriptions,s);try{t(o,e)}catch{O(a);return}r.push(...a),i.push(...n)}getConnection(t){return this.connections.get(m(t))}sendOrQueueUnsubscribe(t,e,s){const r=this.getConnection(t);r&&!g(r,{id:e,type:s})&&r.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 r=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${r}${s.join("&")}`}rpcRequestHeaders(t,e){const s={"content-type":"application/json"},r=this.shardCursors.get(this.cursorKeyFor(e));if(r!==void 0&&(s["x-lunora-min-seq"]=r.toString()),this.authToken&&(s.authorization=`Bearer ${this.authToken}`),t.mutationId&&(s["x-lunora-mutation-id"]=t.mutationId),(t.clientId!==void 0||t.mutationId!==void 0)&&(s["x-lunora-client-id"]=t.clientId??this.clientId),t.clientSeq!==void 0&&(s["x-lunora-client-seq"]=t.clientSeq.toString()),t.attachBookmark){const i=this.bookmark.get();i&&(s["x-d1-bookmark"]=i)}return s}async rpc(t,e,s,r={}){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");const i=this.rpcRequestHeaders(r,s),n=await this.fetchImpl(v(this.url,ct),{body:JSON.stringify({args:k(e,`args for '${t}'`),functionPath:t,shardKey:s}),headers:i,method:"POST"});if(r.captureBookmark){const o=n.headers.get("x-d1-bookmark");o&&this.bookmark.set(o)}let a;try{a=await n.json()}catch{const o=n.statusText?` ${n.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${n.status.toString()}${o})`)}if("error"in a)throw T(a.error);if(!n.ok){const o=n.statusText?` ${n.statusText}`:"";throw new p("INTERNAL",`LunoraClient: request failed (status ${n.status.toString()}${o})`)}return r.onMutationAck?.(a.lastMutationId),r.onCommitCursor?.(a.commitCursor),this.learnDefaultShardKey(n,s),this.recordShardCursor(s,a.commitCursor),b(a.result)}async adminFetch(t,e,s,r){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");const i={};this.authToken&&(i.authorization=`Bearer ${this.authToken}`);const n=s instanceof ArrayBuffer||s instanceof Blob;let a;s===void 0?a=void 0:n?(a=s,r!==void 0&&(i["content-type"]=r)):(a=JSON.stringify(s),i["content-type"]="application/json");const o=await this.fetchImpl(v(this.url,t),{body:a,headers:i,method:e});let c;try{c=await o.json()}catch{const u=o.statusText?` ${o.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${o.status.toString()}${u})`)}if(typeof c=="object"&&c!==null&&"error"in c){const u=c.error,d=new Error(u.message??"admin request failed");throw d.code=u.code,d}if(!o.ok){const u=o.statusText?` ${o.statusText}`:"";throw new p("INTERNAL",`LunoraClient: admin request failed (status ${o.status.toString()}${u})`)}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,{caps:Ae,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 r;try{r=await s()}catch{this.handleDisconnect(t);return}this.closed||this.WebSocketImpl===void 0||t.wsState!=="connecting"||t.socket!==void 0||this.openSocket(t,e,r)}openManagedSocket(t,e,s,r){const{WebSocketImpl:i}=this;if(i===void 0)throw new p("INTERNAL","no WebSocket implementation available");const n=new i(e);t.socket=n;const a=()=>{this.stopHeartbeat(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket===n&&(t.socket=void 0)},o=c=>{a(),r.onClose(c)};s>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===n){try{n.close()}catch{}o()}},s)),n.addEventListener("open",()=>{t.socket===n&&(t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.lastFrameAt=Date.now(),r.onOpen(),this.startHeartbeat(t,o))}),n.addEventListener("message",c=>{t.socket===n&&(t.lastFrameAt=Date.now(),r.onMessage(c))}),n.addEventListener("close",c=>{t.socket===n&&o(c)}),n.addEventListener("error",()=>{t.socket===n&&o()})}openSocket(t,e,s){this.WebSocketImpl!==void 0&&this.openManagedSocket(t,this.wsUrlFor(e,s),this.connectTimeoutMs,{onClose:r=>{r?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(t)},onMessage:r=>{this.handleServerMessage(r.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:n,type:a}of i)g(t,{id:n,type:a})}if(t.pendingStreams&&t.pendingStreams.length>0){const i=t.pendingStreams;t.pendingStreams=[];for(const n of i)g(t,n)}const r=this.whisperHandlers.get(m(e));if(r)for(const i of r.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(r=>r.id));for(const[r,i]of this.streams)if(!(m(i.shardKey)!==m(t.shardKey)||e.has(r))){if(i.durable){const n={...i.message,sinceChunk:i.lastSeq};i.message=n,t.pendingStreams=[...(t.pendingStreams??[]).filter(a=>a.id!==r),n];continue}i.handle.fail(new p("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.streams.delete(r)}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=Me(t);if(s===void 0)return;let r;try{r=JSON.parse(s)}catch{return}switch(r.type){case"ack":{const i=this.subscriptions.getById(r.id);i&&(i.acked=!0);return}case"chunk":{const{data:i,id:n,seq:a}=r,o=this.streams.get(n);o&&typeof a=="number"&&(o.lastSeq=a,o.durable=!0),o?.handle.push(b(i));return}case"complete":{this.handleCompleteMessage(r.id);return}case"data":case"delta":{this.handleDataMessage(r);return}case"error":{this.handleErrorMessage(r);break}case"pokeEnd":{this.handlePokeEnd(r);break}case"pokePart":{this.handlePokePart(r);break}case"pokeStart":{this.handlePokeStart(r);break}case"resume":{this.handleResumeMessage(r);break}case"settled":{this.handleSettledMessage(r);break}case"whisper":{this.dispatchWhisper(r,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(xe(t)),this.streams.delete(e);return}const r=e===void 0?void 0:this.subscriptions.getById(e);if(r){E(r.errorCallbacks,N(t));return}const i=e===void 0?void 0:this.shapeSubscriptions.get(e);i&&E(i.errorCallbacks,N(t))}handlePokeStart(t){ot(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 r of t.rowsPatch)s.push(r.value===void 0?r:{...r,value:b(r.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,r]of e.parts){const i=this.shapeSubscriptions.get(s);if(!i)continue;const n=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(n||a){i.rows.clear(),i.serverCursor=void 0,i.serverEpoch=void 0,this.emitShapeRows(i),this.sendShapeSubscribeIfOpen(i);continue}ut(i.rows,r),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 r=this.resolveDataPayload(t,s);if(s.serverBase=r,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(r,s.optimisticLayers)),this.tabCoordinator?.isLeader()){const i=w.key(s.fn.__lunoraRef,s.args,s.shardKey);this.tabCoordinator.broadcastSubscriptionData(i,r,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(D(s)&&e.serverBase!==void 0){const r=j(e.serverBase,s);if(r!==void 0)return r}return s}dispatchWhisper(t,e){const s=this.whisperHandlers.get(m(e))?.get(t.topic);if(!s)return;const r=b(t.data);for(const i of s)try{i(r,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=>{rt(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 r=0;r<t.length;r+=1){const i=t.charCodeAt(r);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,r]of this.queuedIdentities)r===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 u=new Error("offline mutation skipped: precondition failed before replay");u.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(c,"rejected",u)}const s=m(t),r=this.offlineQueue.drain(c=>m(c.shardKey)===s);if(r.length===0)return;const i=this.identityFingerprint(),n=[];for(const c of r)this.passesReplayIdentityGate(c,i)&&n.push(c);if(n.length===0)return;const a=this.encodableOrSettleTerminal(n);if(a.length===0)return;if(a.length===1){await this.replaySequential(a);return}const o=[];for(let c=0;c<a.length;c+=R){const u=a.slice(c,c+R),d=await this.replayBatched(u);if(o.push(...d.requeue),d.stop){o.push(...a.slice(c+R));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(r){this.settleReplayTerminal(s,r instanceof Error?r:new Error(String(r)))}return e}passesReplayIdentityGate(t,e){const s=t.id===void 0?void 0:this.queuedIdentities.get(t.id),r=s===void 0?t.identity:s;if(r!==void 0&&r!==e&&!this.isSameCredentialUnderTokenHash(r)){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),this.recordShardCursor(t.shardKey,s),t.onCommit?.(s),t.resolve(e),this.emitItemSettled(t,"committed")}cursorKeyFor(t){return t??this.defaultShardKey??""}learnDefaultShardKey(t,e){const s=t.headers.get("x-lunora-shard-key");if(s===null||e!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;const r=this.shardCursors.get("");r!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,r)),this.shardCursors.delete(""))}recordShardCursor(t,e){if(typeof e!="number")return;const s=this.cursorKeyFor(t);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,e))}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 r;const i=await this.rpc(s.functionPath,s.args,s.shardKey,{captureBookmark:!0,clientId:s.clientId??this.clientId,mutationId:s.id,onCommitCursor:n=>{r=n}});this.settleReplaySuccess(s,i,r)}catch(r){if(r.code!==void 0){this.settleReplayTerminal(s,r);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(v(this.url,Q),{body:JSON.stringify({calls:t.map((i,n)=>({args:k(i.args,`args for '${i.functionPath}'`),functionPath:i.functionPath,id:n,clientId:i.clientId??this.clientId,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 r;try{r=await e.json()}catch{return{requeue:t,stop:!0}}if(!r.results){if(r.error){const i=T(r.error);for(const n of t)this.settleReplayTerminal(n,i);return{requeue:[],stop:!1}}return{requeue:t,stop:!0}}return{requeue:this.settleReplayBatchSlots(t,r.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 r=[];for(const[i,n]of t.entries()){const a=s.get(i);a===void 0?r.push(n):"error"in a?Ke.has(a.error.code)?r.push(n):this.settleReplayTerminal(n,T(a.error)):this.settleReplaySuccess(n,b(a.result),a.commitCursor)}return r}}export{z as LunoraClient};