@lunora/client 1.0.0-alpha.69 → 1.0.0-alpha.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -742,8 +742,8 @@ declare class OfflineQueue {
742
742
  *
743
743
  * The durable rewrite is remove-then-append because `PersistenceAdapter.append`
744
744
  * is an insert (the IndexedDB adapter's store has a unique index on `id`), not
745
- * an upsert. Best-effort, like every other persistence call here: a failure
746
- * leaves the record under its old stamp, which is exactly today's behaviour.
745
+ * an upsert see {@link OfflineQueue.rewriteStamp}, which owns the failure
746
+ * handling that ordering forces.
747
747
  */
748
748
  restampIdentity(from: string | null, to: string | null): void;
749
749
  /**
@@ -771,6 +771,25 @@ declare class OfflineQueue {
771
771
  */
772
772
  drainConflict(): QueuedMutation[];
773
773
  clear(): void;
774
+ /**
775
+ * The durable half of {@link OfflineQueue.restampIdentity}: remove the record
776
+ * and re-append it under the new stamp, because `PersistenceAdapter.append`
777
+ * is an insert, not an upsert.
778
+ *
779
+ * That ordering has a window the naive version lost writes in. A failed
780
+ * `remove` is harmless — the record stands under its old stamp. A `remove`
781
+ * that SUCCEEDS followed by an `append` that fails leaves nothing durable at
782
+ * all, while the in-memory entry has already advanced: a reload before the
783
+ * next flush loses the write permanently. So the append failure is
784
+ * compensated by re-appending under the ORIGINAL stamp, which restores the
785
+ * documented "leaves the record under its old stamp" outcome (a replay under
786
+ * a stale stamp is rejected with `OFFLINE_IDENTITY_CHANGED` — recoverable
787
+ * and visible, unlike a silent loss).
788
+ *
789
+ * Each failure is reported under the operation that actually failed, not a
790
+ * hardcoded `"append"`.
791
+ */
792
+ private rewriteStamp;
774
793
  /**
775
794
  * Evict entries from the FRONT of `items` (the oldest — FIFO order) until
776
795
  * the queue is at or under `maxItems`, rejecting each with
package/dist/index.d.ts CHANGED
@@ -742,8 +742,8 @@ declare class OfflineQueue {
742
742
  *
743
743
  * The durable rewrite is remove-then-append because `PersistenceAdapter.append`
744
744
  * is an insert (the IndexedDB adapter's store has a unique index on `id`), not
745
- * an upsert. Best-effort, like every other persistence call here: a failure
746
- * leaves the record under its old stamp, which is exactly today's behaviour.
745
+ * an upsert see {@link OfflineQueue.rewriteStamp}, which owns the failure
746
+ * handling that ordering forces.
747
747
  */
748
748
  restampIdentity(from: string | null, to: string | null): void;
749
749
  /**
@@ -771,6 +771,25 @@ declare class OfflineQueue {
771
771
  */
772
772
  drainConflict(): QueuedMutation[];
773
773
  clear(): void;
774
+ /**
775
+ * The durable half of {@link OfflineQueue.restampIdentity}: remove the record
776
+ * and re-append it under the new stamp, because `PersistenceAdapter.append`
777
+ * is an insert, not an upsert.
778
+ *
779
+ * That ordering has a window the naive version lost writes in. A failed
780
+ * `remove` is harmless — the record stands under its old stamp. A `remove`
781
+ * that SUCCEEDS followed by an `append` that fails leaves nothing durable at
782
+ * all, while the in-memory entry has already advanced: a reload before the
783
+ * next flush loses the write permanently. So the append failure is
784
+ * compensated by re-appending under the ORIGINAL stamp, which restores the
785
+ * documented "leaves the record under its old stamp" outcome (a replay under
786
+ * a stale stamp is rejected with `OFFLINE_IDENTITY_CHANGED` — recoverable
787
+ * and visible, unlike a silent loss).
788
+ *
789
+ * Each failure is reported under the operation that actually failed, not a
790
+ * hardcoded `"append"`.
791
+ */
792
+ private rewriteStamp;
774
793
  /**
775
794
  * Evict entries from the FRONT of `items` (the oldest — FIFO order) until
776
795
  * the queue is at or under `maxItems`, rejecting each with
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{anyApi as o}from"./packem_shared/anyApi-CBOws2ZA.mjs";import{RETIRE_AFTER_DURABLE_SEQ_ADVANCE as a,maxSeq as c,reconcileOptimistic as p}from"./packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs";import{createAsyncStoragePersistence as n}from"./packem_shared/createAsyncStoragePersistence-CNdM5o1u.mjs";import{createAsyncStorageQueryCache as f}from"./packem_shared/createAsyncStorageQueryCache-C0mJLuZK.mjs";import{default as s}from"./packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs";import{createCallRunner as l}from"./packem_shared/createCallRunner-Bwcrfh76.mjs";import{createClientQuery as d}from"./packem_shared/createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as C}from"./packem_shared/TabCoordinator-CXD7vulJ.mjs";import{a as S,i as A}from"./packem_shared/delta-merge-CVSN-uoC.mjs";import{CONFLICT_ERROR_CODE as Q,getErrorCode as _,getRetryAfterMs as h,isConflictError as I,isForbiddenError as M,isRateLimitedError as g,isUnauthorizedError as F}from"./packem_shared/CONFLICT_ERROR_CODE-CDDneB-G.mjs";import{httpStream as O}from"./packem_shared/httpStream-x6q-x4yK.mjs";import{c as b}from"./packem_shared/local-store-BQuKm9n6.mjs";import{LunoraClient as U}from"./packem_shared/LunoraClient-NP7mgVkC.mjs";import{createMutatorRunner as B}from"./packem_shared/createMutatorRunner-CuMRJpUx.mjs";import{O as N}from"./packem_shared/offline-queue-Bmeyg5fy.mjs";import{createInMemoryPersistence as w,createIndexedDbPersistence as z}from"./packem_shared/createInMemoryPersistence-C0qm7c47.mjs";import{preloadQuery as V,preloadedQueryResult as W}from"./packem_shared/preloadQuery-uFy24PCR.mjs";import{createInMemoryQueryCache as j,createIndexedDbQueryCache as G,queryCacheKey as H}from"./packem_shared/createInMemoryQueryCache-D2uNHLfM.mjs";import{createReconnect as Y}from"./packem_shared/createReconnect-CjTmjJDH.mjs";import{default as $}from"./packem_shared/createSnapshotPrecondition-ZyQDet2v.mjs";import{DEFAULT_MAX_BUFFER as re,createStream as oe}from"./packem_shared/DEFAULT_MAX_BUFFER-D3QH2iaq.mjs";import{SubscriptionRegistry as ae}from"./packem_shared/SubscriptionRegistry-D7n5ZE5F.mjs";import{ClientServiceWorker as pe}from"./packem_shared/ClientServiceWorker-DXnBXeWK.mjs";import{createReply as ne,sendToSw as ie}from"./packem_shared/createReply-CwFABEJs.mjs";export{Q as CONFLICT_ERROR_CODE,pe as ClientServiceWorker,re as DEFAULT_MAX_BUFFER,U as LunoraClient,N as OfflineQueue,a as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,ae as SubscriptionRegistry,C as TabCoordinator,o as anyApi,S as applyDelta,n as createAsyncStoragePersistence,f as createAsyncStorageQueryCache,l as createCallRunner,d as createClientQuery,s as createInMemoryBookmarkStorage,w as createInMemoryPersistence,j as createInMemoryQueryCache,z as createIndexedDbPersistence,G as createIndexedDbQueryCache,b as createLocalStore,B as createMutatorRunner,Y as createReconnect,ne as createReply,$ as createSnapshotPrecondition,oe as createStream,_ as getErrorCode,h as getRetryAfterMs,O as httpStream,I as isConflictError,M as isForbiddenError,A as isMutationDelta,g as isRateLimitedError,F as isUnauthorizedError,c as maxSeq,V as preloadQuery,W as preloadedQueryResult,H as queryCacheKey,p as reconcileOptimistic,ie as sendToSw};
1
+ import{anyApi as o}from"./packem_shared/anyApi-CBOws2ZA.mjs";import{RETIRE_AFTER_DURABLE_SEQ_ADVANCE as a,maxSeq as c,reconcileOptimistic as p}from"./packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs";import{createAsyncStoragePersistence as n}from"./packem_shared/createAsyncStoragePersistence-CNdM5o1u.mjs";import{createAsyncStorageQueryCache as f}from"./packem_shared/createAsyncStorageQueryCache-C0mJLuZK.mjs";import{default as s}from"./packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs";import{createCallRunner as l}from"./packem_shared/createCallRunner-Bwcrfh76.mjs";import{createClientQuery as d}from"./packem_shared/createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as C}from"./packem_shared/TabCoordinator-CXD7vulJ.mjs";import{a as S,i as A}from"./packem_shared/delta-merge-CVSN-uoC.mjs";import{CONFLICT_ERROR_CODE as Q,getErrorCode as _,getRetryAfterMs as h,isConflictError as I,isForbiddenError as M,isRateLimitedError as g,isUnauthorizedError as F}from"./packem_shared/CONFLICT_ERROR_CODE-CDDneB-G.mjs";import{httpStream as O}from"./packem_shared/httpStream-x6q-x4yK.mjs";import{c as b}from"./packem_shared/local-store-BQuKm9n6.mjs";import{LunoraClient as U}from"./packem_shared/LunoraClient-BYXxJohQ.mjs";import{createMutatorRunner as B}from"./packem_shared/createMutatorRunner-CuMRJpUx.mjs";import{O as N}from"./packem_shared/offline-queue-8mpNPwG8.mjs";import{createInMemoryPersistence as w,createIndexedDbPersistence as z}from"./packem_shared/createInMemoryPersistence-C0qm7c47.mjs";import{preloadQuery as V,preloadedQueryResult as W}from"./packem_shared/preloadQuery-uFy24PCR.mjs";import{createInMemoryQueryCache as j,createIndexedDbQueryCache as G,queryCacheKey as H}from"./packem_shared/createInMemoryQueryCache-D2uNHLfM.mjs";import{createReconnect as Y}from"./packem_shared/createReconnect-CjTmjJDH.mjs";import{default as $}from"./packem_shared/createSnapshotPrecondition-ZyQDet2v.mjs";import{DEFAULT_MAX_BUFFER as re,createStream as oe}from"./packem_shared/DEFAULT_MAX_BUFFER-D3QH2iaq.mjs";import{SubscriptionRegistry as ae}from"./packem_shared/SubscriptionRegistry-D7n5ZE5F.mjs";import{ClientServiceWorker as pe}from"./packem_shared/ClientServiceWorker-DXnBXeWK.mjs";import{createReply as ne,sendToSw as ie}from"./packem_shared/createReply-CwFABEJs.mjs";export{Q as CONFLICT_ERROR_CODE,pe as ClientServiceWorker,re as DEFAULT_MAX_BUFFER,U as LunoraClient,N as OfflineQueue,a as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,ae as SubscriptionRegistry,C as TabCoordinator,o as anyApi,S as applyDelta,n as createAsyncStoragePersistence,f as createAsyncStorageQueryCache,l as createCallRunner,d as createClientQuery,s as createInMemoryBookmarkStorage,w as createInMemoryPersistence,j as createInMemoryQueryCache,z as createIndexedDbPersistence,G as createIndexedDbQueryCache,b as createLocalStore,B as createMutatorRunner,Y as createReconnect,ne as createReply,$ as createSnapshotPrecondition,oe as createStream,_ as getErrorCode,h as getRetryAfterMs,O as httpStream,I as isConflictError,M as isForbiddenError,A as isMutationDelta,g as isRateLimitedError,F as isUnauthorizedError,c as maxSeq,V as preloadQuery,W as preloadedQueryResult,H as queryCacheKey,p as reconcileOptimistic,ie as sendToSw};
@@ -1 +1 @@
1
- import{LunoraError as m}from"@lunora/errors";import{i as j,a as J,P as Y}from"./delta-merge-CVSN-uoC.mjs";import{e as O,d as b}from"./wire-codec-PBOTh_2d.mjs";import{s as K}from"./wire-key-Dl7EFWSD.mjs";import X from"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import{ClientQueryStore as Z}from"./createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as ee}from"./TabCoordinator-CXD7vulJ.mjs";import{httpStream as te}from"./httpStream-x6q-x4yK.mjs";import{d as R,n as H,f as F,a as se,c as re}from"./local-store-BQuKm9n6.mjs";import{O as ie,n as B,i as ne,r as ae}from"./offline-queue-Bmeyg5fy.mjs";import{resolvePersistenceAdapter as oe}from"./createInMemoryPersistence-C0qm7c47.mjs";import{resolveQueryCacheAdapter as ce,queryCacheKey as L}from"./createInMemoryQueryCache-D2uNHLfM.mjs";import{createReconnect as D}from"./createReconnect-CjTmjJDH.mjs";import he from"./createSnapshotPrecondition-ZyQDet2v.mjs";import{createStream as de}from"./DEFAULT_MAX_BUFFER-D3QH2iaq.mjs";import{SubscriptionRegistry as g}from"./SubscriptionRegistry-D7n5ZE5F.mjs";const M=500,ue=(h,e)=>{if(h.size<e)return;const t=h.keys().next().value;t!==void 0&&h.delete(t)};class w{listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){const[t]=e;for(const s of this.listeners)try{s(t)}catch{}}clear(){this.listeners.clear()}}const le="/_lunora/rpc",W="/_lunora/rpc-batch",fe="/_lunora/ws",U=h=>h===void 0||h===""?"":`&bucket=${encodeURIComponent(h)}`,A=h=>{for(let e=h.length-1;e>=0;e-=1)h[e]?.()},$=Symbol("lunora.unmergeableDelta"),me=(h,e)=>{for(const t of e)t.op==="delete"?h.delete(t.key):t.value!==void 0&&h.set(t.key,t.value)},pe="lunora-ping",ye=3e4,Se=1e4,be=250,Te=5e3,ke=64,ge="/_lunora/admin/shard-traffic",ve="/_lunora/admin/scheduled",Ce="/_lunora/admin/scheduled/status",we="/_lunora/admin/scheduled/ws",Ee="/_lunora/admin/scheduled/cancel",_e="/_lunora/admin/scheduled/dead",Ae="/_lunora/admin/scheduled/dead/retry",Ie="/_lunora/admin/scheduled/dead/cancel",Oe="/_lunora/admin/workflows/instances",Pe="/_lunora/admin/workflows/instance",Re="/_lunora/admin/workflows/status",x="/_lunora/admin/storage",He="/_lunora/admin/storage/url",Fe="/_lunora/admin/storage/buckets",Le="/_lunora/admin/functions",Me="/_lunora/admin/cron-jobs",Ue="/_lunora/admin/cron-jobs/run",xe="/_lunora/admin/openapi",Ne="/_lunora/admin/openrpc",Ke="/_lunora/admin/global/tables",Be="/_lunora/admin/global/table",De="/_lunora/admin/global/facet",We="/_lunora/admin/vector/indexes",$e="/_lunora/admin/vector/query",qe="/_lunora/admin/logs/archive",Qe="/_lunora/admin/kv/namespaces",Ge="/_lunora/admin/kv/keys",N="/_lunora/admin/kv/value",ze="/_lunora/admin/auth/users",Ve="/_lunora/admin/auth/sessions",je="/_lunora/admin/auth/users/create",Je="/_lunora/admin/auth/users/role",Ye="/_lunora/admin/auth/users/ban",Xe="/_lunora/admin/auth/users/unban",Ze="/_lunora/admin/auth/users/password",et="/_lunora/admin/auth/users/remove",tt="/_lunora/admin/auth/users/impersonate",st="/_lunora/admin/auth/sessions/revoke",rt="/_lunora/admin/auth/sessions/revoke-all",it="/_lunora/admin/auth/capabilities",nt="/_lunora/admin/auth/users/update",at="/_lunora/admin/auth/accounts",ot="/_lunora/admin/auth/accounts/unlink",ct="/_lunora/admin/auth/passkeys",ht="/_lunora/admin/auth/passkeys/delete",dt="/_lunora/admin/auth/two-factor/disable",ut="/_lunora/admin/auth/organizations",lt="/_lunora/admin/auth/organizations/members",ft="/_lunora/admin/auth/organizations/invitations",mt="/_lunora/admin/auth/organizations/members/remove",pt="/_lunora/admin/auth/organizations/invitations/cancel",yt="/_lunora/admin/auth/config",St="/_lunora/admin/auth/organizations/create",bt="/_lunora/admin/auth/organizations/update",Tt="/_lunora/admin/auth/organizations/remove",kt="/_lunora/admin/auth/organizations/members/add",gt="/_lunora/admin/auth/organizations/members/invite",vt="/_lunora/admin/auth/organizations/members/role",Ct="/_lunora/admin/auth/organizations/teams",wt="/_lunora/admin/auth/organizations/teams/create",Et="/_lunora/admin/auth/organizations/teams/update",_t="/_lunora/admin/auth/organizations/teams/remove",At="/_lunora/admin/auth/organizations/teams/members",It="/_lunora/admin/auth/organizations/teams/members/add",Ot="/_lunora/admin/auth/organizations/teams/members/remove",Pt="/_lunora/admin/auth/organizations/roles",Rt="/_lunora/admin/auth/organizations/roles/create",Ht="/_lunora/admin/auth/organizations/roles/update",Ft="/_lunora/admin/auth/organizations/roles/remove",Lt="/api/auth",Mt="/get-session",q=h=>h.startsWith("https://")?`wss://${h.slice(8)}`:h.startsWith("http://")?`ws://${h.slice(7)}`:h,v=(h,e)=>`${h.endsWith("/")?h.slice(0,-1):h}${e}`,y=(h,e)=>{const t=new URLSearchParams;for(const[r,i]of Object.entries(e))i!==void 0&&i!==""&&t.set(r,String(i));const s=t.toString();return s===""?h:`${h}?${s}`},Ut=[Y],f=h=>h??"",G=(h,e)=>{const t=h.error,s=typeof t?.code=="string"?t.code:void 0,r=typeof t?.message=="string"?t.message:void 0;return{code:s,messageText:(typeof h.message=="string"?h.message:void 0)??r??e}},xt=h=>{const{code:e,messageText:t}=G(h,"stream error");return e===void 0?new Error(t):new m(e,t)},Q=h=>{const{code:e,messageText:t}=G(h,"subscription error");return{message:t,...e===void 0?{}:{code:e}}},I=(h,e)=>{for(const t of h)try{t(e)}catch{}},Nt=new TextDecoder,Kt=h=>{if(typeof h=="string")return h;if(h instanceof ArrayBuffer)return Nt.decode(h)},S=(h,e)=>{if(!h.socket||h.wsState!=="open")return!1;try{return h.socket.send(JSON.stringify(e)),!0}catch{return!1}},E=h=>{const e=new Error(h.message??"request failed");return e.code=h.code,h.data!==void 0&&(e.data=b(h.data)),h.hint!==void 0&&(e.hint=h.hint),h.docsUrl!==void 0&&(e.docsUrl=h.docsUrl),e},C=(h,e)=>{try{return O(h)}catch(t){const s=t instanceof Error?t.message:String(t);throw new TypeError(`LunoraClient: cannot encode ${e} — ${s}`,t instanceof Error?{cause:t}:void 0)}},Bt=(h,e)=>{const t=Array.from({length:e});for(const s of h){if(typeof s.id!="number"||s.id<0||s.id>=e)continue;const r=s.body;t[s.id]=r&&"error"in r&&r.error?{error:E(r.error),ok:!1}:{ok:!0,value:b(r?.result)}}return t.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},Dt=new Set(["SHARD_ERROR","SHARD_UNAVAILABLE"]),Wt=Promise.resolve();class z{static MAX_POKE_BUFFERS=256;static createClientQuery(e,t){return{defaultValue:t,key:e}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;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 g;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 w;statusListeners=new w;tokenExpiredListeners=new w;mutationSettledListeners=new w;pendingChangeListeners=new w;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;offlineFlushes=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??v(q(e.url),fe),this.wsToken=e.wsToken;const t=e.authBasePath??Lt;this.authBasePath=t.endsWith("/")?t.slice(0,-1):t,this.fetchImpl=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=e.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=e.bookmarkStorage??X(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??ye,this.connectTimeoutMs=e.connectTimeoutMs??Se,this.defaultConnectionContext=e.connectionContext,this.persistence=oe(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=ce(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new Z,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=Wt),this.offlineQueue=new ie(e.offlineQueue,{onEvict:(s,r)=>{this.emitItemSettled(s,"rejected",r)},onSizeChange:s=>{this.pendingChangeListeners.emit(s)},persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${B()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})})}setAuthToken(e,t){const s=this.authToken!==e,r=this.identityFingerprint();this.authToken=e,t!==void 0&&(this.authSubject=t);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(e)}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,t,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(e,t,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:r,onMutationAck:d=>{a=d}});if(a!==void 0&&a>(this.clientWatermarks.get(n??"")?.get(i)??0)){let d=this.clientWatermarks.get(n??"");d===void 0&&(d=new Map,this.clientWatermarks.set(n??"",d)),d.set(i,a)}return{applied:a===void 0||a===r,result:o}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}async getCurrentUser(){if(this.closed||!this.fetchImpl)return null;const e={};this.authToken&&(e.authorization=`Bearer ${this.authToken}`);try{const t=await this.fetchImpl(v(this.url,`${this.authBasePath}${Mt}`),{credentials:"include",headers:e,method:"GET"});return t.ok?(await t.json())?.user??null:null}catch{return null}}setWsToken(e){if(this.wsToken!==e){this.wsToken=e;for(const t of this.connections.values())if(t.socket)try{t.socket.close()}catch{}}}setConnectionContext(e,t={}){this.assertLeaderOwnedSurface("setConnectionContext");const s=f(t.shardKey);e===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,e),this.refreshConnectionContext(s)}acquireConnectionContext(e,t={}){if(this.followsAnotherTab())return()=>{};const s=f(t.shardKey),r={context:e},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(e,t,s={}){this.assertLeaderOwnedSurface("whisperSubscribe");const r=f(s.shardKey);let i=this.whisperHandlers.get(r);i||(i=new Map,this.whisperHandlers.set(r,i));let n=i.get(e);const a=n===void 0;if(n||(n=new Set,i.set(e,n)),n.add(t),this.ensureSocket(s.shardKey),a){const o=this.getConnection(s.shardKey);o&&S(o,{topic:e,type:"whisper_subscribe"})}return()=>{const o=this.whisperHandlers.get(r),c=o?.get(e);if(!c?.delete(t)||c.size>0)return;o?.delete(e),o?.size===0&&this.whisperHandlers.delete(r);const d=this.getConnection(s.shardKey);d&&S(d,{topic:e,type:"whisper_unsubscribe"})}}whisper(e,t,s={}){this.assertLeaderOwnedSurface("whisper"),this.ensureSocket(s.shardKey);const r=this.getConnection(s.shardKey);r&&S(r,{data:C(t??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"})}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){const t=this.statusListeners.add(e);return e(this.computeStatus()),t}pendingCount(){return this.offlineQueue.size}debug(){const e=[],t=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...t?.keys()??[]]);for(const i of s){const n=this.connections.get(i);e.push({confirmedMutationWatermark:t?.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:e.toSorted((i,n)=>(i.shardKey??"").localeCompare(n.shardKey??"")),subscriptions:r.toSorted((i,n)=>i.functionPath.localeCompare(n.functionPath))}}onPendingChange(e){const t=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),t}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,t){this.clientQueryStore.set(e,t)}subscribeClientQuery(e,t){return this.clientQueryStore.subscribe(e,t)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,t,s){return he(this,e,t,s)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,t,s){if(!this.readyResolved)return;const r=K(t),i=L(e,r,s),n=this.hydratedQueryCache.get(i);if(n!==void 0)return n.identity===this.identityFingerprint()?n.value:void 0}peekActiveQuerySnapshot(e,t,s){const r=g.key(e,t,s),i=this.subscriptions.get(r);return{present:i!==void 0,value:i?.lastValue}}async query(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0})}async batch(e){if(this.assertOpen(),!this.fetchImpl)throw new m("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];const t=await this.fetchImpl(v(this.url,W),{body:JSON.stringify({calls:e.map((i,n)=>({args:C(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=t.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let r;try{r=await t.json()}catch{throw new m("INTERNAL",`LunoraClient: batch response was not JSON (status ${t.status.toString()})`)}if(!t.ok||r.error&&!r.results)throw r.error?E(r.error):new m("INTERNAL",`LunoraClient: batch request failed (status ${t.status.toString()})`);for(const i of r.results??[]){const n=i.body?.commitCursor;typeof i.id=="number"&&typeof n=="number"&&this.recordShardCursor(e[i.id]?.shardKey,n)}return Bt(r.results??[],e.length)}async mutation(e,t,s={}){this.assertOpen();const r=t,i=s.mutationId??B(),{confirms:n,rollbacks:a}=this.applyOptimisticUpdates(e.__lunoraRef,r,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,t,s.shardKey,a,n);const o=this.offlineFlushes.get(f(s.shardKey));o!==void 0&&await o;const{hasSocket:c,wasEverConnected:d,wsState:u}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:l}=this.offlineQueue,p=d||l,T=this.WebSocketImpl!==void 0&&p;if(u!=="open"&&!c&&T||u==="connecting"&&p)return this.enqueueOfflineMutation(e,r,s.shardKey,i,a,n,s.precondition);try{let _;const V=await this.rpc(e.__lunoraRef,r,s.shardKey,{captureBookmark:!0,mutationId:i,onCommitCursor:P=>{_=P}});for(const P of n)P(_);return V}catch(_){throw A(a),_}}async action(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0,captureBookmark:!0})}async importRows(e,t,s={}){this.assertOpen();const r=Math.max(1,Math.trunc(s.chunkSize??500)),i=s.toArgs??(c=>({rows:c})),n=t.length;let a=0,o=0;for(let c=0;c<n;c+=r){const d=t.slice(c,c+r),u=o;await this.mutation(e,i(d),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(u)}`},shardKey:s.shardKey}),o+=1,a+=d.length,s.onProgress?.({done:a,total:n})}return{chunks:o,imported:a}}async shardTraffic(e){this.assertOpen();const t=await this.adminFetch(ge,"POST",{table:e});return{failed:t.failed??0,ok:t.ok??0,shards:t.shards??[]}}async listScheduledJobs(){return this.assertOpen(),(await this.adminFetch(ve,"GET")).records??[]}async schedulerStatus(){this.assertOpen();const e=await this.adminFetch(Ce,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}}async cancelScheduledJob(e){return this.assertOpen(),{cancelled:(await this.adminFetch(Ee,"POST",{id:e})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await this.adminFetch(_e,"GET")).records??[]}async retryDeadJob(e){return this.assertOpen(),{retried:(await this.adminFetch(Ae,"POST",{id:e})).retried===!0}}async removeDeadJob(e){return this.assertOpen(),{removed:(await this.adminFetch(Ie,"POST",{id:e})).removed===!0}}async listWorkflowInstances(e){this.assertOpen();const t=new URLSearchParams({name:e.name});e.status!==void 0&&t.set("status",e.status),e.page!==void 0&&t.set("page",String(e.page)),e.perPage!==void 0&&t.set("perPage",String(e.perPage));const s=await this.adminFetch(`${Oe}?${t.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}}async getWorkflowInstance(e){this.assertOpen();const t=new URLSearchParams({id:e.id,name:e.name}),s=await this.adminFetch(`${Pe}?${t.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??e.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}}async setWorkflowInstanceStatus(e){return this.assertOpen(),{status:(await this.adminFetch(Re,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const t=v(q(this.url),we),s=D(this.reconnectOptions),r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let i,n=!1;const a=()=>{n||this.closed||(i=setTimeout(d,s.next()))},o=l=>{if(n||this.WebSocketImpl===void 0)return;const p=l===void 0?t:`${t}?token=${encodeURIComponent(l)}`;this.openManagedSocket(r,p,this.connectTimeoutMs,{onClose:()=>{a()},onMessage:T=>{try{const k=JSON.parse(typeof T.data=="string"?T.data:"");k.type==="jobs"&&Array.isArray(k.records)&&(s.reset(),e(k.records))}catch{}}})},c=async l=>{let p;try{p=await l()}catch{a();return}o(p)},d=()=>{if(n||this.WebSocketImpl===void 0)return;const{wsToken:l}=this;if(typeof l=="function"){c(l).catch(()=>{});return}o(l)};d();const u=()=>{n=!0,i!==void 0&&(clearTimeout(i),i=void 0),r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),this.stopHeartbeat(r),r.socket?.close(),r.socket=void 0};return this.adminSocketTeardowns.add(u),()=>{this.adminSocketTeardowns.delete(u),u()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(Le,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(Me,"GET")).jobs??[]}async runCronJob(e){this.assertOpen();const t=await this.adminFetch(Ue,"POST",{name:e});return{name:t.name??e,ran:t.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(xe,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(Ne,"GET")}async listStorageObjects(e={}){this.assertOpen();const t=y(x,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await this.adminFetch(t,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(e,t){this.assertOpen();const s=`${x}?key=${encodeURIComponent(e)}${U(t?.bucket)}`,r=await this.adminFetch(s,"DELETE");return{deleted:r.deleted===!0,key:r.key??e}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(Fe,"GET")).buckets??[]}async uploadStorageObject(e){this.assertOpen();const t=`${x}?key=${encodeURIComponent(e.key)}${U(e.bucket)}`,s=await this.adminFetch(t,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}}async signedStorageUrl(e,t){this.assertOpen();const s=t?.expiresInSeconds,r=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,i=`${He}?key=${encodeURIComponent(e)}${r}${U(t?.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(Ke,"GET")}async readGlobalTablePage(e){this.assertOpen();const t=new URLSearchParams({table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(O(e.filters))),b(await this.adminFetch(`${Be}?${t.toString()}`,"GET"))}async facetGlobalColumn(e){this.assertOpen();const t=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(O(e.filters))),b(await this.adminFetch(`${De}?${t.toString()}`,"GET"))}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch(We,"GET")).indexes??[]}async queryVectorIndex(e){return this.assertOpen(),(await this.adminFetch($e,"POST",e)).matches??[]}async queryLogArchive(e={}){this.assertOpen();const t=await this.adminFetch(qe,"POST",e);return{nextCursor:t.nextCursor,rows:t.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(Qe,"GET")).namespaces??[]}async listKvKeys(e){this.assertOpen();const t=y(Ge,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await this.adminFetch(t,"GET")}async getKvValue(e){this.assertOpen();const t=y(N,{key:e.key,namespace:e.namespace});return await this.adminFetch(t,"GET")}async putKvValue(e){this.assertOpen(),await this.adminFetch(N,"PUT",e)}async deleteKvKey(e){this.assertOpen();const t=y(N,{key:e.key,namespace:e.namespace});await this.adminFetch(t,"DELETE")}async listAuthUsers(e={}){this.assertOpen();const t=y(ze,{filterField:e.filterField,filterValue:e.filterValue,limit:e.limit,offset:e.offset,search:e.search,searchField:e.searchField,sortBy:e.sortBy,sortDirection:e.sortDirection});return await this.adminFetch(t,"GET")}async createAuthUser(e){return await this.adminFetch(je,"POST",e)}async setAuthUserRole(e){return await this.adminFetch(Je,"POST",e)}async banAuthUser(e){return await this.adminFetch(Ye,"POST",e)}async unbanAuthUser(e){return await this.adminFetch(Xe,"POST",e)}async setAuthUserPassword(e){await this.adminFetch(Ze,"POST",e)}async removeAuthUser(e){await this.adminFetch(et,"POST",e)}async impersonateAuthUser(e){return await this.adminFetch(tt,"POST",e)}async revokeAuthSession(e){await this.adminFetch(st,"POST",e)}async revokeAuthUserSessions(e){await this.adminFetch(rt,"POST",e)}async getAuthCapabilities(){return await this.adminFetch(it,"GET")}async updateAuthUser(e){return await this.adminFetch(nt,"POST",e)}async listAuthAccounts(e){return await this.adminFetch(y(at,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){await this.adminFetch(ot,"POST",e)}async listAuthPasskeys(e){return await this.adminFetch(y(ct,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){await this.adminFetch(ht,"POST",e)}async disableAuthTwoFactor(e){await this.adminFetch(dt,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(y(ut,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){const t=y(lt,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthOrgInvitations(e){const t=y(ft,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async removeAuthOrgMember(e){await this.adminFetch(mt,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(pt,"POST",e)}async getAuthConfig(){return await this.adminFetch(yt,"GET")}async createAuthOrganization(e){return await this.adminFetch(St,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(bt,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(Tt,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch(kt,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(gt,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch(vt,"POST",e)}async listAuthOrgTeams(e){const t=y(Ct,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(wt,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch(Et,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(_t,"POST",e)}async listAuthOrgTeamMembers(e){const t=y(At,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(t,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(It,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(Ot,"POST",e)}async listAuthOrgRoles(e){const t=y(Pt,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgRole(e){return await this.adminFetch(Rt,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(Ht,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(Ft,"POST",e)}async listAuthSessions(e={}){this.assertOpen();const t=y(Ve,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(t,"GET")}subscribe(e,t,s,r={}){this.assertOpen();const i=t??{},n=g.key(e.__lunoraRef,i,r.shardKey);let a=this.subscriptions.get(n);const o=s,c=r.onError;if(!a){this.nextSubId+=1;const u=`sub_${this.nextSubId.toString()}`,l=K(i),p=this.takeHydratedCache(e.__lunoraRef,l,r.shardKey);a={acked:!1,args:i,argsKey:l,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:u,lastValue:p?.value,optimisticLayers:[],serverBase:p?.value,serverCursor:p?.serverCursor,shardKey:r.shardKey,...p?.serverEpoch===void 0?{}:{serverEpoch:p.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 d=a;return()=>{d.callbacks.delete(o),c&&d.errorCallbacks.delete(c),r.onCheckpoint&&d.checkpointCallbacks.delete(r.onCheckpoint),d.callbacks.size===0&&(this.sendOrQueueUnsubscribe(d.shardKey,d.id,"unsubscribe"),this.subscriptions.remove(d))}}subscribeShape(e,t,s={}){if(this.assertOpen(),this.followsAnotherTab())return()=>{};this.nextShapeId+=1;const r=`shape_${this.nextShapeId.toString()}`,i={args:e.args,callbacks:new Set([t]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:r,name:e.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:e.args===void 0?void 0:C(e.args,`shape args for '${e.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(e,t,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=t??{},{handle:a,iterable:o}=de({maxBuffer:s.maxBuffer,onCancel:()=>{this.cancelStream(r,i)}});this.ensureSocket(i);const c=this.getConnection(i),d={id:r,query:{args:C(n,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:i},type:"stream"},u={durable:s.durable===!0,generation:void 0,handle:a,lastSeq:0,message:d,shardKey:i,started:!1};this.streams.set(r,u);const l=c?.wsState==="open"&&S(c,d);if(u.started=l,!l&&c===void 0)return this.streams.delete(r),a.fail(new m("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),o;if(!l){for(c.pendingStreams=c.pendingStreams??[];c.pendingStreams.length>=ke;){const T=c.pendingStreams.shift()?.id,k=T?this.streams.get(T):void 0;k&&(k.handle.fail(new m("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(T))}c.pendingStreams.push(d)}return o}httpStream(e,t,s={}){if(this.closed)throw new m("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new m("INTERNAL","LunoraClient: no `fetch` implementation available");const r={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return te(e,t,{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 e of this.streams.values())e.handle.fail(new m("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(const e of this.connections.values())this.teardownConnection(e);for(const e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear(),this.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.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new m("INTERNAL","LunoraClient is closed")}followsAnotherTab(){const e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;const t=e.leaderTabId;return t!==void 0&&t!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new m("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}teardownConnection(e){const t=f(e.shardKey);for(const[s,r]of this.streams)f(r.shardKey)===t&&(r.handle.fail(new m("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(s));if(e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.clearConnectionTimers(e),this.stopHeartbeat(e),e.socket){try{e.socket.close()}catch{}e.socket=void 0}e.wsState="closed"}createTabCoordinator(){const e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new ee({channelName:e,onBecomeLeader:()=>{for(const t of this.subscriptions.all())this.ensureSocket(t.shardKey),this.sendSubscribeIfOpen(t);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},onStopBeingLeader:()=>{for(const[t,s]of this.connections)this.teardownConnection(s),this.connections.delete(t);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},onConnectionStatus:(t,s)=>{if(s!==void 0&&s!==this.identityFingerprint())return;const r=t==="connected"&&this.leaderStatus!=="connected";this.leaderStatus=t,t==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),r&&this.flushAllOfflineQueues()},onSubscriptionData:(t,s,r,i,n)=>{if(n!==void 0&&n!==this.identityFingerprint())return;const a=this.subscriptions.get(t);a&&(a.serverBase=s,r!==void 0&&(a.serverCursor=r,i!==void 0&&(a.serverEpoch=i),R(a,r)),H(a,F(s,a.optimisticLayers)))},onLeaderClaimAnswered:()=>{this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},onSubscriptionError:(t,s,r)=>{if(r!==void 0&&r!==this.identityFingerprint())return;const i=this.subscriptions.get(t);i&&I(i.errorCallbacks,s)},onSubscriptionSettled:(t,s,r,i,n,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;const o=this.subscriptions.get(t);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(e,t,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:t,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:`${this.clientId}:${String(c)}`,identity:o,mutationId:c,shardKey:s})}catch(d){throw A(i),d instanceof Error?d:new Error(String(d))}for(const d of n)d(void 0);return}return new Promise((c,d)=>{const u={args:t,functionPath:e.__lunoraRef,liveAwaiter:!0,id:r,clientId:this.clientId,identity:o,precondition:a,onCommit:l=>{for(const p of n)p(l)},reject:l=>{this.queuedIdentities.delete(r),A(i),d(l instanceof Error?l:new Error(String(l)))},resolve:c,shardKey:s};this.offlineQueue.enqueue(u),this.queuedOfflineShardKeys.add(s),u.id!==void 0&&this.queuedIdentities.set(u.id,o)})}async hydratePersistedQueue(){try{const e=await this.offlineQueue.hydrate();for(const t of e)this.queuedOfflineShardKeys.add(t),this.ensureSocket(t)}catch{}}hydrateAsOutboxLeader(){const e=()=>{this.hydratePersistedQueue().catch(()=>{})},t=globalThis.navigator?.locks;if(!t){e();return}t.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{const e=await this.queryCache.load();for(const{key:t,...s}of e){if(ne(this.persistenceVersion,s.version)){this.queryCache.remove(t).catch(()=>{});continue}this.hydratedQueryCache.set(t,s)}}catch{}}takeHydratedCache(e,t,s){const r=L(e,t,s),i=this.hydratedQueryCache.get(r);if(i!==void 0)return this.hydratedQueryCache.delete(r),i.identity===this.identityFingerprint()?i:void 0}persistQueryValue(e){const t=e.serverBase;if(!this.queryCache||t===void 0)return;const s=L(e.fn.__lunoraRef,e.argsKey,e.shardKey),r=this.getConnection(e.shardKey)?.identity;this.pendingCacheWrites.set(s,{identity:r===void 0?this.identityFingerprint():r,serverCursor:e.serverCursor,ts:Date.now(),value:t,...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},be)}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;const{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}const t=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(t.map(async([s,r])=>e.put(s,r)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";const e=[...this.connections.values()];return e.length===0?"idle":e.some(t=>t.wsState==="open")?"connected":e.some(t=>t.wsState==="connecting")?"connecting":"offline"}emitConnectionStatus(){const e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,t,s){this.mutationSettledListeners.emit({args:e.args,code:s===void 0?void 0:s.code,error:s,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:t})}applyOptimisticUpdates(e,t,s,r){const i=[],n=[];if(!r)return{confirms:i,rollbacks:n};const a=g.key(e,t,s),o=this.subscriptions.get(a);if(o){const c=se(o,r);c&&(i.push(c.confirm),n.push(c.rollback))}return{confirms:i,rollbacks:n}}applyOptimisticUpdate(e,t,s,r,i){const{confirms:n,rollbacks:a,store:o}=re(this.subscriptions,s);try{e(o,t)}catch{A(a);return}r.push(...a),i.push(...n)}getConnection(e){return this.connections.get(f(e))}sendOrQueueUnsubscribe(e,t,s){const r=this.getConnection(e);r&&!S(r,{id:t,type:s})&&r.pendingUnsubscribes.push({id:t,type:s})}connectionGateState(e){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 t=this.getConnection(e);return{hasSocket:t?.socket!==void 0,wasEverConnected:t?.wasEverConnected??!1,wsState:t?.wsState??"idle"}}getOrCreateConnection(e){const t=f(e);let s=this.connections.get(t);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],reconnect:D(this.reconnectOptions),reconnectTimer:void 0,shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:!1,wsState:"idle"},this.connections.set(t,s)),s}wsUrlFor(e,t){const s=[];if(e!==void 0&&s.push(`shard=${encodeURIComponent(e)}`),t!==void 0&&s.push(`token=${encodeURIComponent(t)}`),s.length===0)return this.wsUrl;const r=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${r}${s.join("&")}`}rpcRequestHeaders(e,t){const s={"content-type":"application/json"},r=this.shardCursors.get(this.cursorKeyFor(t));if(r!==void 0&&(s["x-lunora-min-seq"]=r.toString()),this.authToken&&(s.authorization=`Bearer ${this.authToken}`),e.mutationId&&(s["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(s["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(s["x-lunora-client-seq"]=e.clientSeq.toString()),e.attachBookmark){const i=this.bookmark.get();i&&(s["x-d1-bookmark"]=i)}return s}async rpc(e,t,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,le),{body:JSON.stringify({args:C(t,`args for '${e}'`),functionPath:e,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 E(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(e,t,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,e),{body:a,headers:i,method:t});let c;try{c=await o.json()}catch{const d=o.statusText?` ${o.statusText}`:"";throw new m("INTERNAL",`LunoraClient: response was not JSON (status ${o.status.toString()}${d})`)}if(typeof c=="object"&&c!==null&&"error"in c){const d=c.error,u=new Error(d.message??"admin request failed");throw u.code=d.code,u}if(!o.ok){const d=o.statusText?` ${o.statusText}`:"";throw new m("INTERNAL",`LunoraClient: admin request failed (status ${o.status.toString()}${d})`)}return c}effectiveConnectionContext(e){const t=this.connectionContextHolders.get(e);return t&&t.length>0?t[t.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){const t=this.connections.get(e);t?.wsState==="open"&&this.sendConnectEnvelope(t)}sendConnectEnvelope(e){const t=this.effectiveConnectionContext(f(e.shardKey));S(e,{caps:Ut,clientId:this.clientId,id:"connect",type:"connect",...t===void 0?{}:{context:t}})}resendShapeSubscriptions(e){for(const t of this.shapeSubscriptions.values())f(t.shardKey)===f(e)&&this.sendShapeSubscribeIfOpen(t)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const t=this.getOrCreateConnection(e);if(!(t.wsState==="open"||t.wsState==="connecting")){if(t.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(t,e,this.wsToken).catch(()=>{});return}this.openSocket(t,e,this.wsToken)}}async openSocketWithProvidedToken(e,t,s){let r;try{r=await s()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,t,r)}openManagedSocket(e,t,s,r){const{WebSocketImpl:i}=this;if(i===void 0)throw new m("INTERNAL","no WebSocket implementation available");const n=new i(t);e.socket=n;const a=()=>{this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket===n&&(e.socket=void 0)},o=c=>{a(),r.onClose(c)};s>0&&(e.connectTimer=setTimeout(()=>{if(e.connectTimer=void 0,e.socket===n){try{n.close()}catch{}o()}},s)),n.addEventListener("open",()=>{e.socket===n&&(e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.lastFrameAt=Date.now(),r.onOpen?.(),this.startHeartbeat(e,o))}),n.addEventListener("message",c=>{e.socket===n&&(e.lastFrameAt=Date.now(),r.onMessage(c))}),n.addEventListener("close",c=>{e.socket===n&&o(c)}),n.addEventListener("error",()=>{e.socket===n&&o()})}openSocket(e,t,s){this.WebSocketImpl!==void 0&&(e.identity=this.identityFingerprint(),this.openManagedSocket(e,this.wsUrlFor(t,s),this.connectTimeoutMs,{onClose:r=>{r?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},onMessage:r=>{this.handleServerMessage(r.data,t)},onOpen:()=>{e.wsState="open",e.wasEverConnected=!0,clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},Te),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(t);for(const i of this.subscriptions.all())f(i.shardKey)===f(t)&&this.sendSubscribeIfOpen(i);if(this.resendShapeSubscriptions(t),e.pendingUnsubscribes.length>0){const i=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(const{id:n,type:a}of i)S(e,{id:n,type:a})}this.flushPendingStreams(e);const r=this.whisperHandlers.get(f(t));if(r)for(const i of r.keys())S(e,{topic:i,type:"whisper_subscribe"});this.flushOfflineQueue(t).catch(()=>{})}}))}flushPendingStreams(e){if(!e.pendingStreams||e.pendingStreams.length===0)return;const t=e.pendingStreams;e.pendingStreams=[];for(const s of t){const r=S(e,s)?this.streams.get(String(s.id)):void 0;r&&(r.started=!0)}}cancelStream(e,t){const s=this.getConnection(t),r=this.streams.get(e);s&&(s.pendingStreams=s.pendingStreams?.filter(i=>i.id!==e),!S(s,{id:e,type:"unsubscribe"})&&r?.durable===!0&&r.started&&s.pendingUnsubscribes.push({id:e,type:"unsubscribe"})),this.streams.delete(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;this.stopHeartbeat(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey);const t=new Set((e.pendingStreams??[]).map(r=>r.id));for(const[r,i]of this.streams)if(!(f(i.shardKey)!==f(e.shardKey)||t.has(r))){if(i.durable){const n={...i.message,...i.generation===void 0?{}:{generation:i.generation},sinceChunk:i.lastSeq};i.message=n,e.pendingStreams=[...(e.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=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},s)}startHeartbeat(e,t){this.stopHeartbeat(e),!(this.heartbeatIntervalMs<=0)&&(e.heartbeatTimer=setInterval(()=>{if(!e.socket)return;const{socket:s}=e;if(Date.now()-e.lastFrameAt>this.heartbeatIntervalMs*2.5){try{s.close()}catch{}t();return}try{s.send(pe)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(e){e.heartbeatTimer!==void 0&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=void 0)}markShardPendingAck(e){const t=f(e);for(const s of this.subscriptions.all())f(s.shardKey)===t&&(s.acked=!1)}sendSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);if(t?.wsState!=="open"||e.acked)return;const s=e.fn.__lunoraTable??e.fn.__lunoraRef,r=e.serverCursor!==void 0&&e.serverBase!==void 0;S(t,{id:e.id,query:{args:O(e.args),functionPath:e.fn.__lunoraRef,table:s,...r?{sinceSeq:e.serverCursor}:{},...r&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);t?.wsState==="open"&&S(t,{id:e.id,shape:{name:e.name,...e.wireArgs===void 0?{}:{args:e.wireArgs}},type:"shape_subscribe",...e.serverCursor===void 0?{}:{sinceCheckpoint:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,t){const s=Kt(e);if(s===void 0)return;let r;try{r=JSON.parse(s)}catch{return}switch(r.type!=="error"&&this.getConnection(t)?.reconnect.reset(),r.type){case"ack":{const i=this.subscriptions.getById(r.id);i&&(i.acked=!0);return}case"chunk":{const{data:i,generation:n,id:a,seq:o}=r,c=this.streams.get(a);c&&typeof o=="number"&&(c.lastSeq=o,typeof n=="number"&&(c.generation=n),c.durable=!0),c?.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,t);break}case"pokePart":{this.handlePokePart(r,t);break}case"pokeStart":{this.handlePokeStart(r,t);break}case"resume":{this.handleResumeMessage(r);break}case"settled":{this.handleSettledMessage(r);break}case"whisper":{this.dispatchWhisper(r,t);break}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}const{id:s}=e,r=s===void 0?void 0:this.streams.get(s);if(r&&s!==void 0){r.handle.fail(xt(e)),this.streams.delete(s);return}const i=s===void 0?void 0:this.subscriptions.getById(s);if(i){const a=Q(e),o=this.identityFingerprint(),c=g.key(i.fn.__lunoraRef,i.args,i.shardKey);I(i.errorCallbacks,a),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(c,a,o);return}const n=s===void 0?void 0:this.shapeSubscriptions.get(s);n&&I(n.errorCallbacks,Q(e))}pokeBufferKey(e,t){return`${f(e)}\0${t}`}handlePokeStart(e,t){ue(this.pokeBuffers,z.MAX_POKE_BUFFERS),this.pokeBuffers.set(this.pokeBufferKey(t,e.pokeId),{baseCheckpoint:e.baseCheckpoint,bases:new Map,epoch:e.epoch,lastMutationId:new Map,parts:new Map,resets:new Set})}handlePokePart(e,t){const s=this.pokeBuffers.get(this.pokeBufferKey(t,e.pokeId));if(!s)return;const r=s.parts.get(e.shapeId)??[];for(const n of e.rowsPatch)r.push(n.value===void 0?n:{...n,value:b(n.value)});s.parts.set(e.shapeId,r),e.lastMutationId!==void 0&&s.lastMutationId.set(e.shapeId,e.lastMutationId);const i=e.baseCheckpoint??s.baseCheckpoint;i!==void 0&&s.bases.set(e.shapeId,i),e.reset===!0&&s.resets.add(e.shapeId)}handlePokeEnd(e,t){const s=this.pokeBufferKey(t,e.pokeId),r=this.pokeBuffers.get(s);if(r){this.pokeBuffers.delete(s);for(const i of r.parts.keys()){const n=this.shapeSubscriptions.get(i);n&&this.applyPokePart(n,r,e)}}}applyPokePart(e,t,s){const r=t.parts.get(e.id)??[],i=t.resets.has(e.id),n=t.bases.get(e.id),a=t.epoch!==void 0&&e.serverEpoch!==void 0&&t.epoch!==e.serverEpoch,o=n!==void 0&&e.serverCursor!==void 0&&e.serverCursor!==n;if(!i&&(a||o)){e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(e),this.sendShapeSubscribeIfOpen(e);return}i&&e.rows.clear(),me(e.rows,r),s.checkpoint!==void 0&&(e.serverCursor=s.checkpoint),s.epoch!==void 0&&(e.serverEpoch=s.epoch);const c=t.lastMutationId.get(e.id);c!==void 0&&(e.lastMutationId=c),this.emitShapeRows(e),e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}emitShapeRows(e){const t=[...e.rows.values()];for(const s of e.callbacks)try{s(t)}catch{}}handleDataMessage(e){const{id:t}=e,s=t?this.subscriptions.getById(t):void 0;if(!s)return;const r=this.resolveDataPayload(e,s);if(r===$){this.resnapshotSubscription(s);return}if(s.serverBase=r,e.cursor!==void 0&&(s.serverCursor=e.cursor),e.epoch!==void 0&&(s.serverEpoch=e.epoch),e.lastMutationId!==void 0){s.lastMutationId=Math.max(s.lastMutationId??0,e.lastMutationId);for(const i of s.checkpointCallbacks)i({checkpoint:s.serverCursor,mutationId:s.lastMutationId})}if(this.persistQueryValue(s),R(s,s.serverCursor),H(s,F(r,s.optimisticLayers)),this.tabCoordinator?.isLeader()){const i=g.key(s.fn.__lunoraRef,s.args,s.shardKey);this.tabCoordinator.broadcastSubscriptionData(i,r,s.serverCursor,s.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){const t=this.subscriptions.getById(e.id);t&&this.ackAndAdvanceCursor(t,e.cursor,e.epoch)}handleSettledMessage(e){const t=this.subscriptions.getById(e.id);if(t){this.ackAndAdvanceCursor(t,e.cursor,e.epoch),e.lastMutationId!==void 0&&(t.lastMutationId=Math.max(t.lastMutationId??0,e.lastMutationId));for(const s of t.checkpointCallbacks)s({checkpoint:t.serverCursor,mutationId:t.lastMutationId});if(this.tabCoordinator?.isLeader()){const s=g.key(t.fn.__lunoraRef,t.args,t.shardKey);this.tabCoordinator.broadcastSubscriptionSettled(s,t.serverCursor,t.serverEpoch,t.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(e,t,s){e.acked=!0,(t!==void 0&&t!==e.serverCursor||s!==void 0&&s!==e.serverEpoch)&&(t!==void 0&&(e.serverCursor=t),s!==void 0&&(e.serverEpoch=s),this.persistQueryValue(e),R(e,e.serverCursor)&&H(e,F(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,t){if("data"in e&&e.data!==void 0)return b(e.data);const s=b(e.delta);return j(s)?t.serverBase===void 0?s:J(t.serverBase,s)??$:s}dispatchWhisper(e,t){const s=this.whisperHandlers.get(f(t))?.get(e.topic);if(!s)return;const r=b(e.data);for(const i of s)try{i(r,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){const t=this.streams.get(e);if(t){t.handle.complete(),this.streams.delete(e);return}const s=this.subscriptions.getById(e);s&&(s.acked=!1,I(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(t=>{ae(this.onPersistenceError,"remove",t,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let t=2166136261,s=5381;for(let r=0;r<e.length;r+=1){const i=e.charCodeAt(r);t^=i,t=Math.imul(t,16777619),s=Math.imul(s,33)+i}return`${e.length.toString(36)}:${(t>>>0).toString(36)}:${(s>>>0).toString(36)}`}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;const t=this.authToken;return t===null?!1:this.hashToken(t)===e}rejectQueuedForIdentityChange(){const e=this.offlineQueue.drain();for(const t of e){this.queuedIdentities.delete(t.id??""),this.unpersist(t.id);const s=new Error("offline mutation discarded: auth identity changed before replay");s.code="OFFLINE_IDENTITY_CHANGED",t.reject(s),this.emitItemSettled(t,"rejected",s)}this.clearQueryCacheForIdentityChange()}restampQueuedIdentity(e,t){for(const[s,r]of this.queuedIdentities)r===e&&this.queuedIdentities.set(s,t);this.offlineQueue.restampIdentity(e,t)}restampWatermarks(e,t){const s=e??"",r=this.clientWatermarks.get(s);if(r===void 0)return;this.clientWatermarks.delete(s);const i=t??"",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 e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){const t=f(e),s=this.offlineFlushes.get(t);if(s===void 0&&this.offlineQueue.size===0)return;const r=(async()=>{await(s??Promise.resolve());try{await this.drainOfflineQueue(e)}catch{}})();this.offlineFlushes.set(t,r),await r,this.offlineFlushes.get(t)===r&&this.offlineFlushes.delete(t)}async drainOfflineQueue(e){const t=this.offlineQueue.drainConflict();for(const c of t){this.unpersist(c.id),this.queuedIdentities.delete(c.id??"");const d=new Error("offline mutation skipped: precondition failed before replay");d.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(c,"rejected",d)}const s=f(e),r=this.offlineQueue.drain(c=>f(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+=M){const d=a.slice(c,c+M),u=await this.replayBatched(d);if(o.push(...u.requeue),u.stop){o.push(...a.slice(c+M));break}}o.length>0&&this.offlineQueue.requeue(o)}encodableOrSettleTerminal(e){const t=[];for(const s of e)try{C(s.args,`args for '${s.functionPath}'`),t.push(s)}catch(r){this.settleReplayTerminal(s,r instanceof Error?r:new Error(String(r)))}return t}passesReplayIdentityGate(e,t){const s=e.id===void 0?void 0:this.queuedIdentities.get(e.id),r=s===void 0?e.identity:s;if(r!==void 0&&r!==t&&!this.isSameCredentialUnderTokenHash(r)){this.queuedIdentities.delete(e.id??""),this.unpersist(e.id);const i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",e.reject(i),this.emitItemSettled(e,"rejected",i),!1}return this.queuedIdentities.delete(e.id??""),!0}settleReplaySuccess(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.resolve(t),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,t){const s=e.headers.get("x-lunora-shard-key");if(s===null||t!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;const r=this.shardCursors.get("");r!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,r)),this.shardCursors.delete(""))}recordShardCursor(e,t){if(typeof t!="number")return;const s=this.cursorKeyFor(e);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,t))}settleReplayTerminal(e,t){this.unpersist(e.id),e.reject(t),this.emitItemSettled(e,"rejected",t)}async replaySequential(e){for(let t=0;t<e.length;t+=1){const s=e[t];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(e.slice(t));return}}}async replayBatched(e){if(!this.fetchImpl)return{requeue:e,stop:!0};let t;try{t=await this.fetchImpl(v(this.url,W),{body:JSON.stringify({calls:e.map((i,n)=>({args:C(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:e,stop:!0}}const s=t.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let r;try{r=await t.json()}catch{return{requeue:e,stop:!0}}if(!r.results){if(r.error){const i=E(r.error);for(const n of e)this.settleReplayTerminal(n,i);return{requeue:[],stop:!1}}return{requeue:e,stop:!0}}return{requeue:this.settleReplayBatchSlots(e,r.results),stop:!1}}settleReplayBatchSlots(e,t){const s=new Map;for(const i of t)typeof i.id=="number"&&i.body!==void 0&&s.set(i.id,i.body);const r=[];for(const[i,n]of e.entries()){const a=s.get(i);a===void 0?r.push(n):"error"in a?Dt.has(a.error.code)?r.push(n):this.settleReplayTerminal(n,E(a.error)):this.settleReplaySuccess(n,b(a.result),a.commitCursor)}return r}}export{z as LunoraClient};
1
+ import{LunoraError as m}from"@lunora/errors";import{i as j,a as J,P as Y}from"./delta-merge-CVSN-uoC.mjs";import{e as O,d as b}from"./wire-codec-PBOTh_2d.mjs";import{s as K}from"./wire-key-Dl7EFWSD.mjs";import X from"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import{ClientQueryStore as Z}from"./createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as ee}from"./TabCoordinator-CXD7vulJ.mjs";import{httpStream as te}from"./httpStream-x6q-x4yK.mjs";import{d as R,n as H,f as F,a as se,c as re}from"./local-store-BQuKm9n6.mjs";import{O as ie,n as B,i as ne,r as ae}from"./offline-queue-8mpNPwG8.mjs";import{resolvePersistenceAdapter as oe}from"./createInMemoryPersistence-C0qm7c47.mjs";import{resolveQueryCacheAdapter as ce,queryCacheKey as L}from"./createInMemoryQueryCache-D2uNHLfM.mjs";import{createReconnect as D}from"./createReconnect-CjTmjJDH.mjs";import he from"./createSnapshotPrecondition-ZyQDet2v.mjs";import{createStream as de}from"./DEFAULT_MAX_BUFFER-D3QH2iaq.mjs";import{SubscriptionRegistry as g}from"./SubscriptionRegistry-D7n5ZE5F.mjs";const M=500,ue=(h,e)=>{if(h.size<e)return;const t=h.keys().next().value;t!==void 0&&h.delete(t)};class w{listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){const[t]=e;for(const s of this.listeners)try{s(t)}catch{}}clear(){this.listeners.clear()}}const le="/_lunora/rpc",W="/_lunora/rpc-batch",fe="/_lunora/ws",U=h=>h===void 0||h===""?"":`&bucket=${encodeURIComponent(h)}`,A=h=>{for(let e=h.length-1;e>=0;e-=1)h[e]?.()},$=Symbol("lunora.unmergeableDelta"),me=(h,e)=>{for(const t of e)t.op==="delete"?h.delete(t.key):t.value!==void 0&&h.set(t.key,t.value)},pe="lunora-ping",ye=3e4,Se=1e4,be=250,Te=5e3,ke=64,ge="/_lunora/admin/shard-traffic",ve="/_lunora/admin/scheduled",Ce="/_lunora/admin/scheduled/status",we="/_lunora/admin/scheduled/ws",Ee="/_lunora/admin/scheduled/cancel",_e="/_lunora/admin/scheduled/dead",Ae="/_lunora/admin/scheduled/dead/retry",Ie="/_lunora/admin/scheduled/dead/cancel",Oe="/_lunora/admin/workflows/instances",Pe="/_lunora/admin/workflows/instance",Re="/_lunora/admin/workflows/status",x="/_lunora/admin/storage",He="/_lunora/admin/storage/url",Fe="/_lunora/admin/storage/buckets",Le="/_lunora/admin/functions",Me="/_lunora/admin/cron-jobs",Ue="/_lunora/admin/cron-jobs/run",xe="/_lunora/admin/openapi",Ne="/_lunora/admin/openrpc",Ke="/_lunora/admin/global/tables",Be="/_lunora/admin/global/table",De="/_lunora/admin/global/facet",We="/_lunora/admin/vector/indexes",$e="/_lunora/admin/vector/query",qe="/_lunora/admin/logs/archive",Qe="/_lunora/admin/kv/namespaces",Ge="/_lunora/admin/kv/keys",N="/_lunora/admin/kv/value",ze="/_lunora/admin/auth/users",Ve="/_lunora/admin/auth/sessions",je="/_lunora/admin/auth/users/create",Je="/_lunora/admin/auth/users/role",Ye="/_lunora/admin/auth/users/ban",Xe="/_lunora/admin/auth/users/unban",Ze="/_lunora/admin/auth/users/password",et="/_lunora/admin/auth/users/remove",tt="/_lunora/admin/auth/users/impersonate",st="/_lunora/admin/auth/sessions/revoke",rt="/_lunora/admin/auth/sessions/revoke-all",it="/_lunora/admin/auth/capabilities",nt="/_lunora/admin/auth/users/update",at="/_lunora/admin/auth/accounts",ot="/_lunora/admin/auth/accounts/unlink",ct="/_lunora/admin/auth/passkeys",ht="/_lunora/admin/auth/passkeys/delete",dt="/_lunora/admin/auth/two-factor/disable",ut="/_lunora/admin/auth/organizations",lt="/_lunora/admin/auth/organizations/members",ft="/_lunora/admin/auth/organizations/invitations",mt="/_lunora/admin/auth/organizations/members/remove",pt="/_lunora/admin/auth/organizations/invitations/cancel",yt="/_lunora/admin/auth/config",St="/_lunora/admin/auth/organizations/create",bt="/_lunora/admin/auth/organizations/update",Tt="/_lunora/admin/auth/organizations/remove",kt="/_lunora/admin/auth/organizations/members/add",gt="/_lunora/admin/auth/organizations/members/invite",vt="/_lunora/admin/auth/organizations/members/role",Ct="/_lunora/admin/auth/organizations/teams",wt="/_lunora/admin/auth/organizations/teams/create",Et="/_lunora/admin/auth/organizations/teams/update",_t="/_lunora/admin/auth/organizations/teams/remove",At="/_lunora/admin/auth/organizations/teams/members",It="/_lunora/admin/auth/organizations/teams/members/add",Ot="/_lunora/admin/auth/organizations/teams/members/remove",Pt="/_lunora/admin/auth/organizations/roles",Rt="/_lunora/admin/auth/organizations/roles/create",Ht="/_lunora/admin/auth/organizations/roles/update",Ft="/_lunora/admin/auth/organizations/roles/remove",Lt="/api/auth",Mt="/get-session",q=h=>h.startsWith("https://")?`wss://${h.slice(8)}`:h.startsWith("http://")?`ws://${h.slice(7)}`:h,v=(h,e)=>`${h.endsWith("/")?h.slice(0,-1):h}${e}`,y=(h,e)=>{const t=new URLSearchParams;for(const[r,i]of Object.entries(e))i!==void 0&&i!==""&&t.set(r,String(i));const s=t.toString();return s===""?h:`${h}?${s}`},Ut=[Y],f=h=>h??"",G=(h,e)=>{const t=h.error,s=typeof t?.code=="string"?t.code:void 0,r=typeof t?.message=="string"?t.message:void 0;return{code:s,messageText:(typeof h.message=="string"?h.message:void 0)??r??e}},xt=h=>{const{code:e,messageText:t}=G(h,"stream error");return e===void 0?new Error(t):new m(e,t)},Q=h=>{const{code:e,messageText:t}=G(h,"subscription error");return{message:t,...e===void 0?{}:{code:e}}},I=(h,e)=>{for(const t of h)try{t(e)}catch{}},Nt=new TextDecoder,Kt=h=>{if(typeof h=="string")return h;if(h instanceof ArrayBuffer)return Nt.decode(h)},S=(h,e)=>{if(!h.socket||h.wsState!=="open")return!1;try{return h.socket.send(JSON.stringify(e)),!0}catch{return!1}},E=h=>{const e=new Error(h.message??"request failed");return e.code=h.code,h.data!==void 0&&(e.data=b(h.data)),h.hint!==void 0&&(e.hint=h.hint),h.docsUrl!==void 0&&(e.docsUrl=h.docsUrl),e},C=(h,e)=>{try{return O(h)}catch(t){const s=t instanceof Error?t.message:String(t);throw new TypeError(`LunoraClient: cannot encode ${e} — ${s}`,t instanceof Error?{cause:t}:void 0)}},Bt=(h,e)=>{const t=Array.from({length:e});for(const s of h){if(typeof s.id!="number"||s.id<0||s.id>=e)continue;const r=s.body;t[s.id]=r&&"error"in r&&r.error?{error:E(r.error),ok:!1}:{ok:!0,value:b(r?.result)}}return t.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},Dt=new Set(["SHARD_ERROR","SHARD_UNAVAILABLE"]),Wt=Promise.resolve();class z{static MAX_POKE_BUFFERS=256;static createClientQuery(e,t){return{defaultValue:t,key:e}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;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 g;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 w;statusListeners=new w;tokenExpiredListeners=new w;mutationSettledListeners=new w;pendingChangeListeners=new w;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;offlineFlushes=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??v(q(e.url),fe),this.wsToken=e.wsToken;const t=e.authBasePath??Lt;this.authBasePath=t.endsWith("/")?t.slice(0,-1):t,this.fetchImpl=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=e.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=e.bookmarkStorage??X(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??ye,this.connectTimeoutMs=e.connectTimeoutMs??Se,this.defaultConnectionContext=e.connectionContext,this.persistence=oe(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=ce(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new Z,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=Wt),this.offlineQueue=new ie(e.offlineQueue,{onEvict:(s,r)=>{this.emitItemSettled(s,"rejected",r)},onSizeChange:s=>{this.pendingChangeListeners.emit(s)},persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${B()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})})}setAuthToken(e,t){const s=this.authToken!==e,r=this.identityFingerprint();this.authToken=e,t!==void 0&&(this.authSubject=t);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(e)}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,t,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(e,t,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:r,onMutationAck:d=>{a=d}});if(a!==void 0&&a>(this.clientWatermarks.get(n??"")?.get(i)??0)){let d=this.clientWatermarks.get(n??"");d===void 0&&(d=new Map,this.clientWatermarks.set(n??"",d)),d.set(i,a)}return{applied:a===void 0||a===r,result:o}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}async getCurrentUser(){if(this.closed||!this.fetchImpl)return null;const e={};this.authToken&&(e.authorization=`Bearer ${this.authToken}`);try{const t=await this.fetchImpl(v(this.url,`${this.authBasePath}${Mt}`),{credentials:"include",headers:e,method:"GET"});return t.ok?(await t.json())?.user??null:null}catch{return null}}setWsToken(e){if(this.wsToken!==e){this.wsToken=e;for(const t of this.connections.values())if(t.socket)try{t.socket.close()}catch{}}}setConnectionContext(e,t={}){this.assertLeaderOwnedSurface("setConnectionContext");const s=f(t.shardKey);e===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,e),this.refreshConnectionContext(s)}acquireConnectionContext(e,t={}){if(this.followsAnotherTab())return()=>{};const s=f(t.shardKey),r={context:e},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(e,t,s={}){this.assertLeaderOwnedSurface("whisperSubscribe");const r=f(s.shardKey);let i=this.whisperHandlers.get(r);i||(i=new Map,this.whisperHandlers.set(r,i));let n=i.get(e);const a=n===void 0;if(n||(n=new Set,i.set(e,n)),n.add(t),this.ensureSocket(s.shardKey),a){const o=this.getConnection(s.shardKey);o&&S(o,{topic:e,type:"whisper_subscribe"})}return()=>{const o=this.whisperHandlers.get(r),c=o?.get(e);if(!c?.delete(t)||c.size>0)return;o?.delete(e),o?.size===0&&this.whisperHandlers.delete(r);const d=this.getConnection(s.shardKey);d&&S(d,{topic:e,type:"whisper_unsubscribe"})}}whisper(e,t,s={}){this.assertLeaderOwnedSurface("whisper"),this.ensureSocket(s.shardKey);const r=this.getConnection(s.shardKey);r&&S(r,{data:C(t??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"})}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){const t=this.statusListeners.add(e);return e(this.computeStatus()),t}pendingCount(){return this.offlineQueue.size}debug(){const e=[],t=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...t?.keys()??[]]);for(const i of s){const n=this.connections.get(i);e.push({confirmedMutationWatermark:t?.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:e.toSorted((i,n)=>(i.shardKey??"").localeCompare(n.shardKey??"")),subscriptions:r.toSorted((i,n)=>i.functionPath.localeCompare(n.functionPath))}}onPendingChange(e){const t=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),t}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,t){this.clientQueryStore.set(e,t)}subscribeClientQuery(e,t){return this.clientQueryStore.subscribe(e,t)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,t,s){return he(this,e,t,s)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,t,s){if(!this.readyResolved)return;const r=K(t),i=L(e,r,s),n=this.hydratedQueryCache.get(i);if(n!==void 0)return n.identity===this.identityFingerprint()?n.value:void 0}peekActiveQuerySnapshot(e,t,s){const r=g.key(e,t,s),i=this.subscriptions.get(r);return{present:i!==void 0,value:i?.lastValue}}async query(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0})}async batch(e){if(this.assertOpen(),!this.fetchImpl)throw new m("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];const t=await this.fetchImpl(v(this.url,W),{body:JSON.stringify({calls:e.map((i,n)=>({args:C(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=t.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let r;try{r=await t.json()}catch{throw new m("INTERNAL",`LunoraClient: batch response was not JSON (status ${t.status.toString()})`)}if(!t.ok||r.error&&!r.results)throw r.error?E(r.error):new m("INTERNAL",`LunoraClient: batch request failed (status ${t.status.toString()})`);for(const i of r.results??[]){const n=i.body?.commitCursor;typeof i.id=="number"&&typeof n=="number"&&this.recordShardCursor(e[i.id]?.shardKey,n)}return Bt(r.results??[],e.length)}async mutation(e,t,s={}){this.assertOpen();const r=t,i=s.mutationId??B(),{confirms:n,rollbacks:a}=this.applyOptimisticUpdates(e.__lunoraRef,r,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,t,s.shardKey,a,n);const o=this.offlineFlushes.get(f(s.shardKey));o!==void 0&&await o;const{hasSocket:c,wasEverConnected:d,wsState:u}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:l}=this.offlineQueue,p=d||l,T=this.WebSocketImpl!==void 0&&p;if(u!=="open"&&!c&&T||u==="connecting"&&p)return this.enqueueOfflineMutation(e,r,s.shardKey,i,a,n,s.precondition);try{let _;const V=await this.rpc(e.__lunoraRef,r,s.shardKey,{captureBookmark:!0,mutationId:i,onCommitCursor:P=>{_=P}});for(const P of n)P(_);return V}catch(_){throw A(a),_}}async action(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0,captureBookmark:!0})}async importRows(e,t,s={}){this.assertOpen();const r=Math.max(1,Math.trunc(s.chunkSize??500)),i=s.toArgs??(c=>({rows:c})),n=t.length;let a=0,o=0;for(let c=0;c<n;c+=r){const d=t.slice(c,c+r),u=o;await this.mutation(e,i(d),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(u)}`},shardKey:s.shardKey}),o+=1,a+=d.length,s.onProgress?.({done:a,total:n})}return{chunks:o,imported:a}}async shardTraffic(e){this.assertOpen();const t=await this.adminFetch(ge,"POST",{table:e});return{failed:t.failed??0,ok:t.ok??0,shards:t.shards??[]}}async listScheduledJobs(){return this.assertOpen(),(await this.adminFetch(ve,"GET")).records??[]}async schedulerStatus(){this.assertOpen();const e=await this.adminFetch(Ce,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}}async cancelScheduledJob(e){return this.assertOpen(),{cancelled:(await this.adminFetch(Ee,"POST",{id:e})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await this.adminFetch(_e,"GET")).records??[]}async retryDeadJob(e){return this.assertOpen(),{retried:(await this.adminFetch(Ae,"POST",{id:e})).retried===!0}}async removeDeadJob(e){return this.assertOpen(),{removed:(await this.adminFetch(Ie,"POST",{id:e})).removed===!0}}async listWorkflowInstances(e){this.assertOpen();const t=new URLSearchParams({name:e.name});e.status!==void 0&&t.set("status",e.status),e.page!==void 0&&t.set("page",String(e.page)),e.perPage!==void 0&&t.set("perPage",String(e.perPage));const s=await this.adminFetch(`${Oe}?${t.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}}async getWorkflowInstance(e){this.assertOpen();const t=new URLSearchParams({id:e.id,name:e.name}),s=await this.adminFetch(`${Pe}?${t.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??e.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}}async setWorkflowInstanceStatus(e){return this.assertOpen(),{status:(await this.adminFetch(Re,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const t=v(q(this.url),we),s=D(this.reconnectOptions),r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let i,n=!1;const a=()=>{n||this.closed||(i=setTimeout(d,s.next()))},o=l=>{if(n||this.WebSocketImpl===void 0)return;const p=l===void 0?t:`${t}?token=${encodeURIComponent(l)}`;this.openManagedSocket(r,p,this.connectTimeoutMs,{onClose:()=>{a()},onMessage:T=>{try{const k=JSON.parse(typeof T.data=="string"?T.data:"");k.type==="jobs"&&Array.isArray(k.records)&&(s.reset(),e(k.records))}catch{}}})},c=async l=>{let p;try{p=await l()}catch{a();return}o(p)},d=()=>{if(n||this.WebSocketImpl===void 0)return;const{wsToken:l}=this;if(typeof l=="function"){c(l).catch(()=>{});return}o(l)};d();const u=()=>{n=!0,i!==void 0&&(clearTimeout(i),i=void 0),r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),this.stopHeartbeat(r),r.socket?.close(),r.socket=void 0};return this.adminSocketTeardowns.add(u),()=>{this.adminSocketTeardowns.delete(u),u()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(Le,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(Me,"GET")).jobs??[]}async runCronJob(e){this.assertOpen();const t=await this.adminFetch(Ue,"POST",{name:e});return{name:t.name??e,ran:t.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(xe,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(Ne,"GET")}async listStorageObjects(e={}){this.assertOpen();const t=y(x,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await this.adminFetch(t,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(e,t){this.assertOpen();const s=`${x}?key=${encodeURIComponent(e)}${U(t?.bucket)}`,r=await this.adminFetch(s,"DELETE");return{deleted:r.deleted===!0,key:r.key??e}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(Fe,"GET")).buckets??[]}async uploadStorageObject(e){this.assertOpen();const t=`${x}?key=${encodeURIComponent(e.key)}${U(e.bucket)}`,s=await this.adminFetch(t,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}}async signedStorageUrl(e,t){this.assertOpen();const s=t?.expiresInSeconds,r=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,i=`${He}?key=${encodeURIComponent(e)}${r}${U(t?.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(Ke,"GET")}async readGlobalTablePage(e){this.assertOpen();const t=new URLSearchParams({table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(O(e.filters))),b(await this.adminFetch(`${Be}?${t.toString()}`,"GET"))}async facetGlobalColumn(e){this.assertOpen();const t=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(O(e.filters))),b(await this.adminFetch(`${De}?${t.toString()}`,"GET"))}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch(We,"GET")).indexes??[]}async queryVectorIndex(e){return this.assertOpen(),(await this.adminFetch($e,"POST",e)).matches??[]}async queryLogArchive(e={}){this.assertOpen();const t=await this.adminFetch(qe,"POST",e);return{nextCursor:t.nextCursor,rows:t.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(Qe,"GET")).namespaces??[]}async listKvKeys(e){this.assertOpen();const t=y(Ge,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await this.adminFetch(t,"GET")}async getKvValue(e){this.assertOpen();const t=y(N,{key:e.key,namespace:e.namespace});return await this.adminFetch(t,"GET")}async putKvValue(e){this.assertOpen(),await this.adminFetch(N,"PUT",e)}async deleteKvKey(e){this.assertOpen();const t=y(N,{key:e.key,namespace:e.namespace});await this.adminFetch(t,"DELETE")}async listAuthUsers(e={}){this.assertOpen();const t=y(ze,{filterField:e.filterField,filterValue:e.filterValue,limit:e.limit,offset:e.offset,search:e.search,searchField:e.searchField,sortBy:e.sortBy,sortDirection:e.sortDirection});return await this.adminFetch(t,"GET")}async createAuthUser(e){return await this.adminFetch(je,"POST",e)}async setAuthUserRole(e){return await this.adminFetch(Je,"POST",e)}async banAuthUser(e){return await this.adminFetch(Ye,"POST",e)}async unbanAuthUser(e){return await this.adminFetch(Xe,"POST",e)}async setAuthUserPassword(e){await this.adminFetch(Ze,"POST",e)}async removeAuthUser(e){await this.adminFetch(et,"POST",e)}async impersonateAuthUser(e){return await this.adminFetch(tt,"POST",e)}async revokeAuthSession(e){await this.adminFetch(st,"POST",e)}async revokeAuthUserSessions(e){await this.adminFetch(rt,"POST",e)}async getAuthCapabilities(){return await this.adminFetch(it,"GET")}async updateAuthUser(e){return await this.adminFetch(nt,"POST",e)}async listAuthAccounts(e){return await this.adminFetch(y(at,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){await this.adminFetch(ot,"POST",e)}async listAuthPasskeys(e){return await this.adminFetch(y(ct,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){await this.adminFetch(ht,"POST",e)}async disableAuthTwoFactor(e){await this.adminFetch(dt,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(y(ut,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){const t=y(lt,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthOrgInvitations(e){const t=y(ft,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async removeAuthOrgMember(e){await this.adminFetch(mt,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(pt,"POST",e)}async getAuthConfig(){return await this.adminFetch(yt,"GET")}async createAuthOrganization(e){return await this.adminFetch(St,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(bt,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(Tt,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch(kt,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(gt,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch(vt,"POST",e)}async listAuthOrgTeams(e){const t=y(Ct,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(wt,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch(Et,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(_t,"POST",e)}async listAuthOrgTeamMembers(e){const t=y(At,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(t,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(It,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(Ot,"POST",e)}async listAuthOrgRoles(e){const t=y(Pt,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgRole(e){return await this.adminFetch(Rt,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(Ht,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(Ft,"POST",e)}async listAuthSessions(e={}){this.assertOpen();const t=y(Ve,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(t,"GET")}subscribe(e,t,s,r={}){this.assertOpen();const i=t??{},n=g.key(e.__lunoraRef,i,r.shardKey);let a=this.subscriptions.get(n);const o=s,c=r.onError;if(!a){this.nextSubId+=1;const u=`sub_${this.nextSubId.toString()}`,l=K(i),p=this.takeHydratedCache(e.__lunoraRef,l,r.shardKey);a={acked:!1,args:i,argsKey:l,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:u,lastValue:p?.value,optimisticLayers:[],serverBase:p?.value,serverCursor:p?.serverCursor,shardKey:r.shardKey,...p?.serverEpoch===void 0?{}:{serverEpoch:p.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 d=a;return()=>{d.callbacks.delete(o),c&&d.errorCallbacks.delete(c),r.onCheckpoint&&d.checkpointCallbacks.delete(r.onCheckpoint),d.callbacks.size===0&&(this.sendOrQueueUnsubscribe(d.shardKey,d.id,"unsubscribe"),this.subscriptions.remove(d))}}subscribeShape(e,t,s={}){if(this.assertOpen(),this.followsAnotherTab())return()=>{};this.nextShapeId+=1;const r=`shape_${this.nextShapeId.toString()}`,i={args:e.args,callbacks:new Set([t]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:r,name:e.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:e.args===void 0?void 0:C(e.args,`shape args for '${e.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(e,t,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=t??{},{handle:a,iterable:o}=de({maxBuffer:s.maxBuffer,onCancel:()=>{this.cancelStream(r,i)}});this.ensureSocket(i);const c=this.getConnection(i),d={id:r,query:{args:C(n,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:i},type:"stream"},u={durable:s.durable===!0,generation:void 0,handle:a,lastSeq:0,message:d,shardKey:i,started:!1};this.streams.set(r,u);const l=c?.wsState==="open"&&S(c,d);if(u.started=l,!l&&c===void 0)return this.streams.delete(r),a.fail(new m("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),o;if(!l){for(c.pendingStreams=c.pendingStreams??[];c.pendingStreams.length>=ke;){const T=c.pendingStreams.shift()?.id,k=T?this.streams.get(T):void 0;k&&(k.handle.fail(new m("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(T))}c.pendingStreams.push(d)}return o}httpStream(e,t,s={}){if(this.closed)throw new m("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new m("INTERNAL","LunoraClient: no `fetch` implementation available");const r={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return te(e,t,{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 e of this.streams.values())e.handle.fail(new m("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(const e of this.connections.values())this.teardownConnection(e);for(const e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear(),this.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.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new m("INTERNAL","LunoraClient is closed")}followsAnotherTab(){const e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;const t=e.leaderTabId;return t!==void 0&&t!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new m("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}teardownConnection(e){const t=f(e.shardKey);for(const[s,r]of this.streams)f(r.shardKey)===t&&(r.handle.fail(new m("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(s));if(e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.clearConnectionTimers(e),this.stopHeartbeat(e),e.socket){try{e.socket.close()}catch{}e.socket=void 0}e.wsState="closed"}createTabCoordinator(){const e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new ee({channelName:e,onBecomeLeader:()=>{for(const t of this.subscriptions.all())this.ensureSocket(t.shardKey),this.sendSubscribeIfOpen(t);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},onStopBeingLeader:()=>{for(const[t,s]of this.connections)this.teardownConnection(s),this.connections.delete(t);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},onConnectionStatus:(t,s)=>{if(s!==void 0&&s!==this.identityFingerprint())return;const r=t==="connected"&&this.leaderStatus!=="connected";this.leaderStatus=t,t==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),r&&this.flushAllOfflineQueues()},onSubscriptionData:(t,s,r,i,n)=>{if(n!==void 0&&n!==this.identityFingerprint())return;const a=this.subscriptions.get(t);a&&(a.serverBase=s,r!==void 0&&(a.serverCursor=r,i!==void 0&&(a.serverEpoch=i),R(a,r)),H(a,F(s,a.optimisticLayers)))},onLeaderClaimAnswered:()=>{this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},onSubscriptionError:(t,s,r)=>{if(r!==void 0&&r!==this.identityFingerprint())return;const i=this.subscriptions.get(t);i&&I(i.errorCallbacks,s)},onSubscriptionSettled:(t,s,r,i,n,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;const o=this.subscriptions.get(t);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(e,t,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:t,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:`${this.clientId}:${String(c)}`,identity:o,mutationId:c,shardKey:s})}catch(d){throw A(i),d instanceof Error?d:new Error(String(d))}for(const d of n)d(void 0);return}return new Promise((c,d)=>{const u={args:t,functionPath:e.__lunoraRef,liveAwaiter:!0,id:r,clientId:this.clientId,identity:o,precondition:a,onCommit:l=>{for(const p of n)p(l)},reject:l=>{this.queuedIdentities.delete(r),A(i),d(l instanceof Error?l:new Error(String(l)))},resolve:c,shardKey:s};this.offlineQueue.enqueue(u),this.queuedOfflineShardKeys.add(s),u.id!==void 0&&this.queuedIdentities.set(u.id,o)})}async hydratePersistedQueue(){try{const e=await this.offlineQueue.hydrate();for(const t of e)this.queuedOfflineShardKeys.add(t),this.ensureSocket(t)}catch{}}hydrateAsOutboxLeader(){const e=()=>{this.hydratePersistedQueue().catch(()=>{})},t=globalThis.navigator?.locks;if(!t){e();return}t.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{const e=await this.queryCache.load();for(const{key:t,...s}of e){if(ne(this.persistenceVersion,s.version)){this.queryCache.remove(t).catch(()=>{});continue}this.hydratedQueryCache.set(t,s)}}catch{}}takeHydratedCache(e,t,s){const r=L(e,t,s),i=this.hydratedQueryCache.get(r);if(i!==void 0)return this.hydratedQueryCache.delete(r),i.identity===this.identityFingerprint()?i:void 0}persistQueryValue(e){const t=e.serverBase;if(!this.queryCache||t===void 0)return;const s=L(e.fn.__lunoraRef,e.argsKey,e.shardKey),r=this.getConnection(e.shardKey)?.identity;this.pendingCacheWrites.set(s,{identity:r===void 0?this.identityFingerprint():r,serverCursor:e.serverCursor,ts:Date.now(),value:t,...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},be)}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;const{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}const t=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(t.map(async([s,r])=>e.put(s,r)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";const e=[...this.connections.values()];return e.length===0?"idle":e.some(t=>t.wsState==="open")?"connected":e.some(t=>t.wsState==="connecting")?"connecting":"offline"}emitConnectionStatus(){const e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,t,s){this.mutationSettledListeners.emit({args:e.args,code:s===void 0?void 0:s.code,error:s,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:t})}applyOptimisticUpdates(e,t,s,r){const i=[],n=[];if(!r)return{confirms:i,rollbacks:n};const a=g.key(e,t,s),o=this.subscriptions.get(a);if(o){const c=se(o,r);c&&(i.push(c.confirm),n.push(c.rollback))}return{confirms:i,rollbacks:n}}applyOptimisticUpdate(e,t,s,r,i){const{confirms:n,rollbacks:a,store:o}=re(this.subscriptions,s);try{e(o,t)}catch{A(a);return}r.push(...a),i.push(...n)}getConnection(e){return this.connections.get(f(e))}sendOrQueueUnsubscribe(e,t,s){const r=this.getConnection(e);r&&!S(r,{id:t,type:s})&&r.pendingUnsubscribes.push({id:t,type:s})}connectionGateState(e){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 t=this.getConnection(e);return{hasSocket:t?.socket!==void 0,wasEverConnected:t?.wasEverConnected??!1,wsState:t?.wsState??"idle"}}getOrCreateConnection(e){const t=f(e);let s=this.connections.get(t);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],reconnect:D(this.reconnectOptions),reconnectTimer:void 0,shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:!1,wsState:"idle"},this.connections.set(t,s)),s}wsUrlFor(e,t){const s=[];if(e!==void 0&&s.push(`shard=${encodeURIComponent(e)}`),t!==void 0&&s.push(`token=${encodeURIComponent(t)}`),s.length===0)return this.wsUrl;const r=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${r}${s.join("&")}`}rpcRequestHeaders(e,t){const s={"content-type":"application/json"},r=this.shardCursors.get(this.cursorKeyFor(t));if(r!==void 0&&(s["x-lunora-min-seq"]=r.toString()),this.authToken&&(s.authorization=`Bearer ${this.authToken}`),e.mutationId&&(s["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(s["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(s["x-lunora-client-seq"]=e.clientSeq.toString()),e.attachBookmark){const i=this.bookmark.get();i&&(s["x-d1-bookmark"]=i)}return s}async rpc(e,t,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,le),{body:JSON.stringify({args:C(t,`args for '${e}'`),functionPath:e,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 E(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(e,t,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,e),{body:a,headers:i,method:t});let c;try{c=await o.json()}catch{const d=o.statusText?` ${o.statusText}`:"";throw new m("INTERNAL",`LunoraClient: response was not JSON (status ${o.status.toString()}${d})`)}if(typeof c=="object"&&c!==null&&"error"in c){const d=c.error,u=new Error(d.message??"admin request failed");throw u.code=d.code,u}if(!o.ok){const d=o.statusText?` ${o.statusText}`:"";throw new m("INTERNAL",`LunoraClient: admin request failed (status ${o.status.toString()}${d})`)}return c}effectiveConnectionContext(e){const t=this.connectionContextHolders.get(e);return t&&t.length>0?t[t.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){const t=this.connections.get(e);t?.wsState==="open"&&this.sendConnectEnvelope(t)}sendConnectEnvelope(e){const t=this.effectiveConnectionContext(f(e.shardKey));S(e,{caps:Ut,clientId:this.clientId,id:"connect",type:"connect",...t===void 0?{}:{context:t}})}resendShapeSubscriptions(e){for(const t of this.shapeSubscriptions.values())f(t.shardKey)===f(e)&&this.sendShapeSubscribeIfOpen(t)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const t=this.getOrCreateConnection(e);if(!(t.wsState==="open"||t.wsState==="connecting")){if(t.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(t,e,this.wsToken).catch(()=>{});return}this.openSocket(t,e,this.wsToken)}}async openSocketWithProvidedToken(e,t,s){let r;try{r=await s()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,t,r)}openManagedSocket(e,t,s,r){const{WebSocketImpl:i}=this;if(i===void 0)throw new m("INTERNAL","no WebSocket implementation available");const n=new i(t);e.socket=n;const a=()=>{this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket===n&&(e.socket=void 0)},o=c=>{a(),r.onClose(c)};s>0&&(e.connectTimer=setTimeout(()=>{if(e.connectTimer=void 0,e.socket===n){try{n.close()}catch{}o()}},s)),n.addEventListener("open",()=>{e.socket===n&&(e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.lastFrameAt=Date.now(),r.onOpen?.(),this.startHeartbeat(e,o))}),n.addEventListener("message",c=>{e.socket===n&&(e.lastFrameAt=Date.now(),r.onMessage(c))}),n.addEventListener("close",c=>{e.socket===n&&o(c)}),n.addEventListener("error",()=>{e.socket===n&&o()})}openSocket(e,t,s){this.WebSocketImpl!==void 0&&(e.identity=this.identityFingerprint(),this.openManagedSocket(e,this.wsUrlFor(t,s),this.connectTimeoutMs,{onClose:r=>{r?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},onMessage:r=>{this.handleServerMessage(r.data,t)},onOpen:()=>{e.wsState="open",e.wasEverConnected=!0,clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},Te),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(t);for(const i of this.subscriptions.all())f(i.shardKey)===f(t)&&this.sendSubscribeIfOpen(i);if(this.resendShapeSubscriptions(t),e.pendingUnsubscribes.length>0){const i=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(const{id:n,type:a}of i)S(e,{id:n,type:a})}this.flushPendingStreams(e);const r=this.whisperHandlers.get(f(t));if(r)for(const i of r.keys())S(e,{topic:i,type:"whisper_subscribe"});this.flushOfflineQueue(t).catch(()=>{})}}))}flushPendingStreams(e){if(!e.pendingStreams||e.pendingStreams.length===0)return;const t=e.pendingStreams;e.pendingStreams=[];for(const s of t){const r=S(e,s)?this.streams.get(String(s.id)):void 0;r&&(r.started=!0)}}cancelStream(e,t){const s=this.getConnection(t),r=this.streams.get(e);s&&(s.pendingStreams=s.pendingStreams?.filter(i=>i.id!==e),!S(s,{id:e,type:"unsubscribe"})&&r?.durable===!0&&r.started&&s.pendingUnsubscribes.push({id:e,type:"unsubscribe"})),this.streams.delete(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;this.stopHeartbeat(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey);const t=new Set((e.pendingStreams??[]).map(r=>r.id));for(const[r,i]of this.streams)if(!(f(i.shardKey)!==f(e.shardKey)||t.has(r))){if(i.durable){const n={...i.message,...i.generation===void 0?{}:{generation:i.generation},sinceChunk:i.lastSeq};i.message=n,e.pendingStreams=[...(e.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=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},s)}startHeartbeat(e,t){this.stopHeartbeat(e),!(this.heartbeatIntervalMs<=0)&&(e.heartbeatTimer=setInterval(()=>{if(!e.socket)return;const{socket:s}=e;if(Date.now()-e.lastFrameAt>this.heartbeatIntervalMs*2.5){try{s.close()}catch{}t();return}try{s.send(pe)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(e){e.heartbeatTimer!==void 0&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=void 0)}markShardPendingAck(e){const t=f(e);for(const s of this.subscriptions.all())f(s.shardKey)===t&&(s.acked=!1)}sendSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);if(t?.wsState!=="open"||e.acked)return;const s=e.fn.__lunoraTable??e.fn.__lunoraRef,r=e.serverCursor!==void 0&&e.serverBase!==void 0;S(t,{id:e.id,query:{args:O(e.args),functionPath:e.fn.__lunoraRef,table:s,...r?{sinceSeq:e.serverCursor}:{},...r&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);t?.wsState==="open"&&S(t,{id:e.id,shape:{name:e.name,...e.wireArgs===void 0?{}:{args:e.wireArgs}},type:"shape_subscribe",...e.serverCursor===void 0?{}:{sinceCheckpoint:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,t){const s=Kt(e);if(s===void 0)return;let r;try{r=JSON.parse(s)}catch{return}switch(r.type!=="error"&&this.getConnection(t)?.reconnect.reset(),r.type){case"ack":{const i=this.subscriptions.getById(r.id);i&&(i.acked=!0);return}case"chunk":{const{data:i,generation:n,id:a,seq:o}=r,c=this.streams.get(a);c&&typeof o=="number"&&(c.lastSeq=o,typeof n=="number"&&(c.generation=n),c.durable=!0),c?.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,t);break}case"pokePart":{this.handlePokePart(r,t);break}case"pokeStart":{this.handlePokeStart(r,t);break}case"resume":{this.handleResumeMessage(r);break}case"settled":{this.handleSettledMessage(r);break}case"whisper":{this.dispatchWhisper(r,t);break}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}const{id:s}=e,r=s===void 0?void 0:this.streams.get(s);if(r&&s!==void 0){r.handle.fail(xt(e)),this.streams.delete(s);return}const i=s===void 0?void 0:this.subscriptions.getById(s);if(i){const a=Q(e),o=this.identityFingerprint(),c=g.key(i.fn.__lunoraRef,i.args,i.shardKey);I(i.errorCallbacks,a),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(c,a,o);return}const n=s===void 0?void 0:this.shapeSubscriptions.get(s);n&&I(n.errorCallbacks,Q(e))}pokeBufferKey(e,t){return`${f(e)}\0${t}`}handlePokeStart(e,t){ue(this.pokeBuffers,z.MAX_POKE_BUFFERS),this.pokeBuffers.set(this.pokeBufferKey(t,e.pokeId),{baseCheckpoint:e.baseCheckpoint,bases:new Map,epoch:e.epoch,lastMutationId:new Map,parts:new Map,resets:new Set})}handlePokePart(e,t){const s=this.pokeBuffers.get(this.pokeBufferKey(t,e.pokeId));if(!s)return;const r=s.parts.get(e.shapeId)??[];for(const n of e.rowsPatch)r.push(n.value===void 0?n:{...n,value:b(n.value)});s.parts.set(e.shapeId,r),e.lastMutationId!==void 0&&s.lastMutationId.set(e.shapeId,e.lastMutationId);const i=e.baseCheckpoint??s.baseCheckpoint;i!==void 0&&s.bases.set(e.shapeId,i),e.reset===!0&&s.resets.add(e.shapeId)}handlePokeEnd(e,t){const s=this.pokeBufferKey(t,e.pokeId),r=this.pokeBuffers.get(s);if(r){this.pokeBuffers.delete(s);for(const i of r.parts.keys()){const n=this.shapeSubscriptions.get(i);n&&this.applyPokePart(n,r,e)}}}applyPokePart(e,t,s){const r=t.parts.get(e.id)??[],i=t.resets.has(e.id),n=t.bases.get(e.id),a=t.epoch!==void 0&&e.serverEpoch!==void 0&&t.epoch!==e.serverEpoch,o=n!==void 0&&e.serverCursor!==void 0&&e.serverCursor!==n;if(!i&&(a||o)){e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(e),this.sendShapeSubscribeIfOpen(e);return}i&&e.rows.clear(),me(e.rows,r),s.checkpoint!==void 0&&(e.serverCursor=s.checkpoint),s.epoch!==void 0&&(e.serverEpoch=s.epoch);const c=t.lastMutationId.get(e.id);c!==void 0&&(e.lastMutationId=c),this.emitShapeRows(e),e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}emitShapeRows(e){const t=[...e.rows.values()];for(const s of e.callbacks)try{s(t)}catch{}}handleDataMessage(e){const{id:t}=e,s=t?this.subscriptions.getById(t):void 0;if(!s)return;const r=this.resolveDataPayload(e,s);if(r===$){this.resnapshotSubscription(s);return}if(s.serverBase=r,e.cursor!==void 0&&(s.serverCursor=e.cursor),e.epoch!==void 0&&(s.serverEpoch=e.epoch),e.lastMutationId!==void 0){s.lastMutationId=Math.max(s.lastMutationId??0,e.lastMutationId);for(const i of s.checkpointCallbacks)i({checkpoint:s.serverCursor,mutationId:s.lastMutationId})}if(this.persistQueryValue(s),R(s,s.serverCursor),H(s,F(r,s.optimisticLayers)),this.tabCoordinator?.isLeader()){const i=g.key(s.fn.__lunoraRef,s.args,s.shardKey);this.tabCoordinator.broadcastSubscriptionData(i,r,s.serverCursor,s.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){const t=this.subscriptions.getById(e.id);t&&this.ackAndAdvanceCursor(t,e.cursor,e.epoch)}handleSettledMessage(e){const t=this.subscriptions.getById(e.id);if(t){this.ackAndAdvanceCursor(t,e.cursor,e.epoch),e.lastMutationId!==void 0&&(t.lastMutationId=Math.max(t.lastMutationId??0,e.lastMutationId));for(const s of t.checkpointCallbacks)s({checkpoint:t.serverCursor,mutationId:t.lastMutationId});if(this.tabCoordinator?.isLeader()){const s=g.key(t.fn.__lunoraRef,t.args,t.shardKey);this.tabCoordinator.broadcastSubscriptionSettled(s,t.serverCursor,t.serverEpoch,t.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(e,t,s){e.acked=!0,(t!==void 0&&t!==e.serverCursor||s!==void 0&&s!==e.serverEpoch)&&(t!==void 0&&(e.serverCursor=t),s!==void 0&&(e.serverEpoch=s),this.persistQueryValue(e),R(e,e.serverCursor)&&H(e,F(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,t){if("data"in e&&e.data!==void 0)return b(e.data);const s=b(e.delta);return j(s)?t.serverBase===void 0?s:J(t.serverBase,s)??$:s}dispatchWhisper(e,t){const s=this.whisperHandlers.get(f(t))?.get(e.topic);if(!s)return;const r=b(e.data);for(const i of s)try{i(r,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){const t=this.streams.get(e);if(t){t.handle.complete(),this.streams.delete(e);return}const s=this.subscriptions.getById(e);s&&(s.acked=!1,I(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(t=>{ae(this.onPersistenceError,"remove",t,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let t=2166136261,s=5381;for(let r=0;r<e.length;r+=1){const i=e.charCodeAt(r);t^=i,t=Math.imul(t,16777619),s=Math.imul(s,33)+i}return`${e.length.toString(36)}:${(t>>>0).toString(36)}:${(s>>>0).toString(36)}`}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;const t=this.authToken;return t===null?!1:this.hashToken(t)===e}rejectQueuedForIdentityChange(){const e=this.offlineQueue.drain();for(const t of e){this.queuedIdentities.delete(t.id??""),this.unpersist(t.id);const s=new Error("offline mutation discarded: auth identity changed before replay");s.code="OFFLINE_IDENTITY_CHANGED",t.reject(s),this.emitItemSettled(t,"rejected",s)}this.clearQueryCacheForIdentityChange()}restampQueuedIdentity(e,t){for(const[s,r]of this.queuedIdentities)r===e&&this.queuedIdentities.set(s,t);this.offlineQueue.restampIdentity(e,t)}restampWatermarks(e,t){const s=e??"",r=this.clientWatermarks.get(s);if(r===void 0)return;this.clientWatermarks.delete(s);const i=t??"",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 e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){const t=f(e),s=this.offlineFlushes.get(t);if(s===void 0&&this.offlineQueue.size===0)return;const r=(async()=>{await(s??Promise.resolve());try{await this.drainOfflineQueue(e)}catch{}})();this.offlineFlushes.set(t,r),await r,this.offlineFlushes.get(t)===r&&this.offlineFlushes.delete(t)}async drainOfflineQueue(e){const t=this.offlineQueue.drainConflict();for(const c of t){this.unpersist(c.id),this.queuedIdentities.delete(c.id??"");const d=new Error("offline mutation skipped: precondition failed before replay");d.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(c,"rejected",d)}const s=f(e),r=this.offlineQueue.drain(c=>f(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+=M){const d=a.slice(c,c+M),u=await this.replayBatched(d);if(o.push(...u.requeue),u.stop){o.push(...a.slice(c+M));break}}o.length>0&&this.offlineQueue.requeue(o)}encodableOrSettleTerminal(e){const t=[];for(const s of e)try{C(s.args,`args for '${s.functionPath}'`),t.push(s)}catch(r){this.settleReplayTerminal(s,r instanceof Error?r:new Error(String(r)))}return t}passesReplayIdentityGate(e,t){const s=e.id===void 0?void 0:this.queuedIdentities.get(e.id),r=s===void 0?e.identity:s;if(r!==void 0&&r!==t&&!this.isSameCredentialUnderTokenHash(r)){this.queuedIdentities.delete(e.id??""),this.unpersist(e.id);const i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",e.reject(i),this.emitItemSettled(e,"rejected",i),!1}return this.queuedIdentities.delete(e.id??""),!0}settleReplaySuccess(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.resolve(t),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,t){const s=e.headers.get("x-lunora-shard-key");if(s===null||t!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;const r=this.shardCursors.get("");r!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,r)),this.shardCursors.delete(""))}recordShardCursor(e,t){if(typeof t!="number")return;const s=this.cursorKeyFor(e);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,t))}settleReplayTerminal(e,t){this.unpersist(e.id),e.reject(t),this.emitItemSettled(e,"rejected",t)}async replaySequential(e){for(let t=0;t<e.length;t+=1){const s=e[t];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(e.slice(t));return}}}async replayBatched(e){if(!this.fetchImpl)return{requeue:e,stop:!0};let t;try{t=await this.fetchImpl(v(this.url,W),{body:JSON.stringify({calls:e.map((i,n)=>({args:C(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:e,stop:!0}}const s=t.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let r;try{r=await t.json()}catch{return{requeue:e,stop:!0}}if(!r.results){if(r.error){const i=E(r.error);for(const n of e)this.settleReplayTerminal(n,i);return{requeue:[],stop:!1}}return{requeue:e,stop:!0}}return{requeue:this.settleReplayBatchSlots(e,r.results),stop:!1}}settleReplayBatchSlots(e,t){const s=new Map;for(const i of t)typeof i.id=="number"&&i.body!==void 0&&s.set(i.id,i.body);const r=[];for(const[i,n]of e.entries()){const a=s.get(i);a===void 0?r.push(n):"error"in a?Dt.has(a.error.code)?r.push(n):this.settleReplayTerminal(n,E(a.error)):this.settleReplaySuccess(n,b(a.result),a.commitCursor)}return r}}export{z as LunoraClient};
@@ -0,0 +1 @@
1
+ import{O as s,n,r as o}from"./offline-queue-8mpNPwG8.mjs";export{s as OfflineQueue,n as nextId,o as reportPersistenceError};
@@ -1 +1 @@
1
- import{LunoraClient as r}from"./LunoraClient-NP7mgVkC.mjs";const c=e=>{const t=new r({fetch:e.fetch,url:e.url});return e.token!==void 0&&t.setAuthToken(e.token),t};export{c as createServerClient};
1
+ import{LunoraClient as r}from"./LunoraClient-BYXxJohQ.mjs";const c=e=>{const t=new r({fetch:e.fetch,url:e.url});return e.token!==void 0&&t.setAuthToken(e.token),t};export{c as createServerClient};
@@ -0,0 +1 @@
1
+ let h=0;const d=()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();h+=1;const r=typeof crypto<"u"&&typeof crypto.getRandomValues=="function"?Array.from(crypto.getRandomValues(new Uint8Array(8)),e=>e.toString(16).padStart(2,"0")).join(""):Math.random().toString(16).slice(2,12);return`id_${Date.now().toString(36)}_${h.toString(36)}_${r}`},f=(r,e)=>r!==void 0&&e!==r,u=d,c=(r,e,t,i)=>{if(r)try{r({error:t,mutationId:i,operation:e});return}catch{}console.warn(`[lunora] offline-queue persistence ${e} failed`,t)};class p{queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;version;items=[];constructor(e={},t={}){this.maxItems=e.maxItems??1e3,this.queueBeforeFirstConnect=e.queueBeforeFirstConnect??!1,this.onPersistenceError=e.onPersistenceError,this.persistence=t.persistence,this.onEvict=t.onEvict,this.onSizeChange=t.onSizeChange,this.version=t.version}get size(){return this.items.length}enqueue(e){const t=e;t.id??=u(),this.items.push(t),this.persistence?.append({args:t.args,clientId:t.clientId,functionPath:t.functionPath,id:t.id,identity:t.identity,shardKey:t.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(i=>{c(this.onPersistenceError,"append",i,t.id)}),this.evictOverflow(),this.notifySize()}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(s){throw c(this.onPersistenceError,"load",s),s}const t=[],i=new Set(this.items.map(s=>s.id));for(const s of e)if(!i.has(s.id)){if(f(this.version,s.version)){this.persistence.remove(s.id).catch(a=>{c(this.onPersistenceError,"remove",a,s.id)});continue}i.add(s.id),t.push({args:s.args,clientId:s.clientId,functionPath:s.functionPath,id:s.id,identity:s.identity,reject:()=>{},resolve:()=>{},shardKey:s.shardKey})}this.items.unshift(...t),this.evictOverflow(),this.notifySize();const n=new Set(this.items),o=new Set;for(const s of t)n.has(s)&&o.add(s.shardKey);return[...o]}restampIdentity(e,t){for(const i of this.items){if(i.identity!==e)continue;i.identity=t;const{id:n}=i;if(!this.persistence||n===void 0)continue;const o={args:i.args,clientId:i.clientId,functionPath:i.functionPath,id:n,identity:t,shardKey:i.shardKey,...this.version===void 0?{}:{version:this.version}};this.rewriteStamp(n,o,e).catch(s=>{c(this.onPersistenceError,"append",s,n)})}}drain(e){if(!e){const n=[...this.items];return this.items.length=0,this.notifySize(),n}const t=[],i=[];for(const n of this.items)(e(n)?t:i).push(n);return this.items.length=0,this.items.push(...i),this.notifySize(),t}requeue(e){e.length!==0&&(this.items.unshift(...e),this.notifySize())}drainConflict(){const e=[],t=[];for(const i of this.items)if(i.precondition!==void 0&&!i.precondition()){const n=new Error("offline mutation skipped: precondition failed before replay");n.code="OFFLINE_PRECONDITION_FAILED",i.reject(n),e.push(i)}else t.push(i);return e.length>0&&(this.items.length=0,this.items.push(...t),this.notifySize()),e}clear(){for(const e of this.items){const t=new Error("CLIENT_CLOSED");t.code="CLIENT_CLOSED",e.reject(t)}this.items.length=0,this.notifySize()}async rewriteStamp(e,t,i){const n=this.persistence;if(n){try{await n.remove(e)}catch(o){c(this.onPersistenceError,"remove",o,e);return}try{await n.append(t)}catch(o){c(this.onPersistenceError,"append",o,e);try{await n.append({...t,identity:i})}catch(s){c(this.onPersistenceError,"append",s,e)}}}}evictOverflow(){for(;this.items.length>this.maxItems;){const e=this.items.shift();if(e){e.id&&this.persistence?.remove(e.id).catch(i=>{c(this.onPersistenceError,"remove",i,e.id)});const t=new Error("offline queue overflow");t.code="OFFLINE_QUEUE_OVERFLOW",e.reject(t),this.onEvict?.(e,t)}}}notifySize(){this.onSizeChange?.(this.items.length)}}export{p as O,f as i,u as n,c as r};
@@ -1 +1 @@
1
- import{getServerSession as o}from"../packem_shared/getServerSession-BaOoo1p6.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-CHfOFpka.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-DwpNFoKP.mjs";import{preloadQuery as s,preloadedQueryResult as f}from"../packem_shared/preloadQuery-uFy24PCR.mjs";export{i as createServerClient,l as deserializePreloaded,o as getServerSession,s as preloadQuery,f as preloadedQueryResult,t as serializePreloaded};
1
+ import{getServerSession as o}from"../packem_shared/getServerSession-BaOoo1p6.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-CHfOFpka.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-l9OHvYqk.mjs";import{preloadQuery as s,preloadedQueryResult as f}from"../packem_shared/preloadQuery-uFy24PCR.mjs";export{i as createServerClient,l as deserializePreloaded,o as getServerSession,s as preloadQuery,f as preloadedQueryResult,t as serializePreloaded};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/client",
3
- "version": "1.0.0-alpha.69",
3
+ "version": "1.0.0-alpha.70",
4
4
  "description": "Lunora browser SDK: WebSocket transport, optimistic updates, and an offline mutation queue",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -70,7 +70,7 @@
70
70
  "access": "public"
71
71
  },
72
72
  "dependencies": {
73
- "@lunora/errors": "1.0.0-alpha.27",
73
+ "@lunora/errors": "1.0.0-alpha.28",
74
74
  "@visulima/storage-client": "1.0.2"
75
75
  },
76
76
  "peerDependencies": {
@@ -1 +0,0 @@
1
- import{O as s,n,r as o}from"./offline-queue-Bmeyg5fy.mjs";export{s as OfflineQueue,n as nextId,o as reportPersistenceError};
@@ -1 +0,0 @@
1
- let h=0;const a=()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();h+=1;const r=typeof crypto<"u"&&typeof crypto.getRandomValues=="function"?Array.from(crypto.getRandomValues(new Uint8Array(8)),t=>t.toString(16).padStart(2,"0")).join(""):Math.random().toString(16).slice(2,12);return`id_${Date.now().toString(36)}_${h.toString(36)}_${r}`},f=(r,t)=>r!==void 0&&t!==r,u=a,o=(r,t,e,i)=>{if(r){r({error:e,mutationId:i,operation:t});return}console.warn(`[lunora] offline-queue persistence ${t} failed`,e)};class m{queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;version;items=[];constructor(t={},e={}){this.maxItems=t.maxItems??1e3,this.queueBeforeFirstConnect=t.queueBeforeFirstConnect??!1,this.onPersistenceError=t.onPersistenceError,this.persistence=e.persistence,this.onEvict=e.onEvict,this.onSizeChange=e.onSizeChange,this.version=e.version}get size(){return this.items.length}enqueue(t){const e=t;e.id??=u(),this.items.push(e),this.persistence?.append({args:e.args,clientId:e.clientId,functionPath:e.functionPath,id:e.id,identity:e.identity,shardKey:e.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(i=>{o(this.onPersistenceError,"append",i,e.id)}),this.evictOverflow(),this.notifySize()}async hydrate(){if(!this.persistence)return[];let t;try{t=await this.persistence.load()}catch(s){throw o(this.onPersistenceError,"load",s),s}const e=[],i=new Set(this.items.map(s=>s.id));for(const s of t)if(!i.has(s.id)){if(f(this.version,s.version)){this.persistence.remove(s.id).catch(d=>{o(this.onPersistenceError,"remove",d,s.id)});continue}i.add(s.id),e.push({args:s.args,clientId:s.clientId,functionPath:s.functionPath,id:s.id,identity:s.identity,reject:()=>{},resolve:()=>{},shardKey:s.shardKey})}this.items.unshift(...e),this.evictOverflow(),this.notifySize();const n=new Set(this.items),c=new Set;for(const s of e)n.has(s)&&c.add(s.shardKey);return[...c]}restampIdentity(t,e){for(const i of this.items){if(i.identity!==t)continue;i.identity=e;const{id:n}=i;if(!this.persistence||n===void 0)continue;const c={args:i.args,clientId:i.clientId,functionPath:i.functionPath,id:n,identity:e,shardKey:i.shardKey,...this.version===void 0?{}:{version:this.version}};this.persistence.remove(n).then(async()=>this.persistence?.append(c)).catch(s=>{o(this.onPersistenceError,"append",s,n)})}}drain(t){if(!t){const n=[...this.items];return this.items.length=0,this.notifySize(),n}const e=[],i=[];for(const n of this.items)(t(n)?e:i).push(n);return this.items.length=0,this.items.push(...i),this.notifySize(),e}requeue(t){t.length!==0&&(this.items.unshift(...t),this.notifySize())}drainConflict(){const t=[],e=[];for(const i of this.items)if(i.precondition!==void 0&&!i.precondition()){const n=new Error("offline mutation skipped: precondition failed before replay");n.code="OFFLINE_PRECONDITION_FAILED",i.reject(n),t.push(i)}else e.push(i);return t.length>0&&(this.items.length=0,this.items.push(...e),this.notifySize()),t}clear(){for(const t of this.items){const e=new Error("CLIENT_CLOSED");e.code="CLIENT_CLOSED",t.reject(e)}this.items.length=0,this.notifySize()}evictOverflow(){for(;this.items.length>this.maxItems;){const t=this.items.shift();if(t){t.id&&this.persistence?.remove(t.id).catch(i=>{o(this.onPersistenceError,"remove",i,t.id)});const e=new Error("offline queue overflow");e.code="OFFLINE_QUEUE_OVERFLOW",t.reject(e),this.onEvict?.(t,e)}}}notifySize(){this.onSizeChange?.(this.items.length)}}export{m as O,f as i,u as n,o as r};