@lunora/studio 1.0.0-alpha.177 → 1.0.0-alpha.178
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/standalone/{chunk-ZP7XN3FG.js → chunk-2ADU5FA5.js} +1 -1
- package/dist/standalone/{chunk-VBRXTL6X.js → chunk-2NYASBOP.js} +1 -1
- package/dist/standalone/{chunk-CX5PIWVR.js → chunk-2W365SXI.js} +1 -1
- package/dist/standalone/{chunk-RBR23GOF.js → chunk-3JDH25N2.js} +1 -1
- package/dist/standalone/{chunk-D6MZSOBE.js → chunk-5PBVNSPQ.js} +1 -1
- package/dist/standalone/{chunk-B3V2AP35.js → chunk-6HVFOKP5.js} +1 -1
- package/dist/standalone/{chunk-BJZAZXKM.js → chunk-7HFDITXH.js} +1 -1
- package/dist/standalone/{chunk-BGYP2QED.js → chunk-AKG3SL2Z.js} +1 -1
- package/dist/standalone/{chunk-EJEEQOLY.js → chunk-ANXXWNJG.js} +1 -1
- package/dist/standalone/{chunk-SJHRP5XZ.js → chunk-BR64TOG4.js} +1 -1
- package/dist/standalone/{chunk-EQM6MBPU.js → chunk-CXGPKEDJ.js} +1 -1
- package/dist/standalone/{chunk-FK6DWL3I.js → chunk-D2SSRZG5.js} +1 -1
- package/dist/standalone/{chunk-SUPR4OQL.js → chunk-D7PVLNBP.js} +1 -1
- package/dist/standalone/{chunk-B3DO4BO4.js → chunk-E366YQXO.js} +1 -1
- package/dist/standalone/{chunk-K35G3ZK3.js → chunk-FTR6JAWG.js} +1 -1
- package/dist/standalone/{chunk-OQCKLTIK.js → chunk-G22LSAIH.js} +1 -1
- package/dist/standalone/{chunk-UB4OLVSF.js → chunk-GDYRC6T6.js} +1 -1
- package/dist/standalone/{chunk-OEQVPFRR.js → chunk-I3OOVU3O.js} +1 -1
- package/dist/standalone/{chunk-NOOT4TBC.js → chunk-I5V3IHPF.js} +1 -1
- package/dist/standalone/{chunk-33KTQE6M.js → chunk-IBM6X4XI.js} +1 -1
- package/dist/standalone/{chunk-NFDXLXT3.js → chunk-IUKHT5XV.js} +1 -1
- package/dist/standalone/{chunk-Q2Y2CJVK.js → chunk-KIEUFC6E.js} +1 -1
- package/dist/standalone/{chunk-AIXYDNPW.js → chunk-KQMWK6QZ.js} +1 -1
- package/dist/standalone/{chunk-F6MZ2ZMN.js → chunk-KYMUE3MZ.js} +1 -1
- package/dist/standalone/{chunk-OQM3I5XY.js → chunk-KZDIKRZ3.js} +1 -1
- package/dist/standalone/{chunk-HXZCKTSY.js → chunk-LKKZMIZK.js} +1 -1
- package/dist/standalone/{chunk-DYK3ISZY.js → chunk-M7QQYXU4.js} +1 -1
- package/dist/standalone/{chunk-KIKAXEXE.js → chunk-MBP4SZYB.js} +1 -1
- package/dist/standalone/{chunk-HD6DNNBW.js → chunk-MNQSYFV6.js} +1 -1
- package/dist/standalone/{chunk-2CXDHA24.js → chunk-MOMBFDIA.js} +1 -1
- package/dist/standalone/{chunk-GMSHLYNP.js → chunk-MOYNBJNW.js} +1 -1
- package/dist/standalone/{chunk-IXPWYPHR.js → chunk-MWUR2KP6.js} +1 -1
- package/dist/standalone/{chunk-SBMI5R22.js → chunk-N2VWHDGA.js} +1 -1
- package/dist/standalone/{chunk-ZCIDKRNF.js → chunk-NLHKRU3D.js} +1 -1
- package/dist/standalone/{chunk-IVDDMDBA.js → chunk-P4V5VRUR.js} +1 -1
- package/dist/standalone/{chunk-2YUHEQNZ.js → chunk-P6F4CNT5.js} +1 -1
- package/dist/standalone/{chunk-BSTFYU5B.js → chunk-PHYKYBCE.js} +1 -1
- package/dist/standalone/{chunk-WWYOHW3E.js → chunk-QCFJKKLX.js} +1 -1
- package/dist/standalone/{chunk-SERHQJBE.js → chunk-RSULZ5QU.js} +1 -1
- package/dist/standalone/{chunk-MJ7FX455.js → chunk-RY66ZJJQ.js} +1 -1
- package/dist/standalone/{chunk-YJJNA2P5.js → chunk-SA5SGD3V.js} +1 -1
- package/dist/standalone/{chunk-DAKCWZ4G.js → chunk-TXLWUHAU.js} +1 -1
- package/dist/standalone/{chunk-XHNFCVRS.js → chunk-U2YJ64UT.js} +1 -1
- package/dist/standalone/{chunk-7AXSOHFV.js → chunk-U3T6FYYZ.js} +1 -1
- package/dist/standalone/{chunk-HEYVHUP6.js → chunk-U7A2W7UG.js} +1 -1
- package/dist/standalone/{chunk-OZGHJG66.js → chunk-V5FOHTRB.js} +1 -1
- package/dist/standalone/{chunk-Z4MWXKHX.js → chunk-VR3OL4A6.js} +1 -1
- package/dist/standalone/{chunk-AVIMIDVJ.js → chunk-WHPKXZN2.js} +1 -1
- package/dist/standalone/{chunk-WWGF3DF5.js → chunk-WV2AW6IT.js} +1 -1
- package/dist/standalone/{chunk-IGHD6IAV.js → chunk-WX6MJS7P.js} +1 -1
- package/dist/standalone/{chunk-S6BSRO54.js → chunk-Y5IE2W4U.js} +1 -1
- package/dist/standalone/{chunk-GF3C2NLS.js → chunk-YAAM5IKA.js} +1 -1
- package/dist/standalone/{chunk-QANF7PJP.js → chunk-YK7JO7NP.js} +1 -1
- package/dist/standalone/{chunk-UUN54AL3.js → chunk-YRZFU7OM.js} +1 -1
- package/dist/standalone/{chunk-PPUG6WPN.js → chunk-Z7WCKAUJ.js} +1 -1
- package/dist/standalone/{chunk-IKLD7RQP.js → chunk-ZTA7WN4R.js} +1 -1
- package/dist/standalone/studio.js +1 -1
- package/package.json +5 -5
|
@@ -8,4 +8,4 @@ import{a as wt,d as p}from"./chunk-2Y6PXGIS.js";import{a as o,d as F,e as G,f as
|
|
|
8
8
|
`,`
|
|
9
9
|
`),n()){await r.cancel().catch(()=>{});return}}i+=s.decode().replaceAll(`\r
|
|
10
10
|
`,`
|
|
11
|
-
`),n()||e.fail(new p("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"))},"b"),fr=o((t,e,r={})=>{let s=r.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!s)throw new p("INTERNAL","httpStream: no `fetch` implementation available");let i=ps(t,e??{},r.baseUrl??""),n=new AbortController,a;r.signal&&(r.signal.aborted?n.abort():(a=o(()=>{n.abort()},"s"),r.signal.addEventListener("abort",a,{once:!0})));let c=o(()=>{a&&r.signal?.removeEventListener("abort",a)},"d"),{handle:u,iterable:h}=Le({maxBuffer:r.maxBuffer,onCancel:o(()=>{n.abort()},"onCancel")});return(async()=>{try{let d=await s(i,{headers:{accept:"text/event-stream",...r.headers},method:t.method,signal:n.signal});if(!d.ok){await d.body?.cancel().catch(()=>{}),u.fail(new p("HTTP_STREAM_STATUS",`httpStream: request failed (status ${d.status.toString()})`,{status:d.status}));return}if(!d.body){u.fail(new p("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}await ys(d.body,u)}finally{c()}})().catch(d=>{if(n.signal.aborted){u.complete();return}if(d instanceof Error&&"code"in d){u.fail(d);return}u.fail(new p("HTTP_STREAM_TRANSPORT",d instanceof Error?d.message:String(d),{cause:d}))}),h},"_");var bs=/["\\\u0000-\u001F\uD800-\uDFFF]/,pr=o(t=>bs.test(t)?JSON.stringify(t):`"${t}"`,"y"),ct=o(t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key \u2014 pass it as a string, or use stableWireKey");if(typeof t=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(typeof t=="string")return pr(t);if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t)){let a="[";for(let c=0;c<t.length;c++)c>0&&(a+=","),a+=ct(t[c]);return a+"]"}let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype){let a=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${a} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}let r=t,s=Object.keys(r).sort(),i="{",n=!0;for(let a of s){let c=r[a];c!==void 0&&(n?n=!1:i+=",",i+=pr(a),i+=":",i+=ct(c))}return i+"}"},"i"),j=o(t=>ct(O(t)),"u");var P=class t{static{o(this,"r")}static key(e,r,s){return`${e}::${j(r)}::${s??""}`}static keyOf(e){return`${e.fn.__lunoraRef}::${e.argsKey}::${e.shardKey??""}`}byKey=new Map;byId=new Map;get(e){return this.byKey.get(e)}getById(e){return this.byId.get(e)}add(e){this.byKey.set(t.keyOf(e),e),this.byId.set(e.id,e)}remove(e){let r=t.keyOf(e);this.byKey.get(r)===e&&this.byKey.delete(r),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}clear(){this.byKey.clear(),this.byId.clear()}};var Z=o((t,e)=>{let r=t;for(let s of e)try{r=s.transform(r)}catch{}return r},"p"),$=o((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let r of t.callbacks)try{r(e)}catch{}}},"u"),ut=o((t,e)=>{let r;try{r=e(t.lastValue)}catch{return}let s={id:Symbol("optimistic"),transform:e},i=!1;t.optimisticLayers.push(s),$(t,r);let n=o(()=>{let c=t.optimisticLayers.findIndex(u=>u.id===s.id);return c===-1?!1:(t.optimisticLayers.splice(c,1),!0)},"l"),a=o(()=>{$(t,Z(t.serverBase,t.optimisticLayers))},"i");return{confirm:o(c=>{if(c===void 0){n();return}s.commitCursor=c,t.serverCursor!==void 0&&t.serverCursor>=c&&n()&&a()},"confirm"),rollback:o(()=>{i||(i=!0,n(),a())},"rollback")}},"y"),Qe=o((t,e)=>{if(e===void 0||t.optimisticLayers.length===0)return!1;let r=t.optimisticLayers.length;return t.optimisticLayers=t.optimisticLayers.filter(s=>s.commitCursor===void 0||s.commitCursor>e),t.optimisticLayers.length!==r},"h"),mr=o((t,e)=>{let r=[],s=[],i=o((n,a)=>t.get(P.key(n,a,e)),"c");return{confirms:r,rollbacks:s,store:{getAllQueries:o(n=>{let a=[];for(let c of t.all())c.fn.__lunoraRef===n.__lunoraRef&&(c.shardKey??"")===(e??"")&&a.push({args:c.args,value:c.lastValue});return a},"getAllQueries"),getQuery:o((n,a)=>i(n.__lunoraRef,a??{})?.lastValue,"getQuery"),setQuery:o((n,a,c)=>{let u=i(n.__lunoraRef,a??{});if(!u)return;let h=ut(u,()=>c);h&&(r.push(h.confirm),s.push(h.rollback))},"setQuery")}}},"L");var yr=0,vs=o(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();yr+=1;let t=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)}_${yr.toString(36)}_${t}`},"d"),ht=o((t,e)=>t!==void 0&&e!==t,"f"),Ue=vs,H=o((t,e,r,s)=>{if(t)try{t({error:r,mutationId:s,operation:e});return}catch{}console.warn(`[lunora] offline-queue persistence ${e} failed`,r)},"o"),De=class{static{o(this,"m")}queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;version;items=[];constructor(e={},r={}){this.maxItems=e.maxItems??1e3,this.queueBeforeFirstConnect=e.queueBeforeFirstConnect??!1,this.onPersistenceError=e.onPersistenceError,this.persistence=r.persistence,this.onEvict=r.onEvict,this.onSizeChange=r.onSizeChange,this.version=r.version}get size(){return this.items.length}enqueue(e){let r=e;r.id??=Ue(),this.items.push(r),this.persistence?.append({args:r.args,clientId:r.clientId,functionPath:r.functionPath,id:r.id,identity:r.identity,shardKey:r.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(s=>{H(this.onPersistenceError,"append",s,r.id)}),this.evictOverflow(),this.notifySize()}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(a){throw H(this.onPersistenceError,"load",a),a}let r=[],s=new Set(this.items.map(a=>a.id));for(let a of e)if(!s.has(a.id)){if(ht(this.version,a.version)){this.persistence.remove(a.id).catch(c=>{H(this.onPersistenceError,"remove",c,a.id)});continue}s.add(a.id),r.push({args:a.args,clientId:a.clientId,functionPath:a.functionPath,id:a.id,identity:a.identity,reject:o(()=>{},"reject"),resolve:o(()=>{},"resolve"),shardKey:a.shardKey})}this.items.unshift(...r),this.evictOverflow(),this.notifySize();let i=new Set(this.items),n=new Set;for(let a of r)i.has(a)&&n.add(a.shardKey);return[...n]}restampIdentity(e,r){for(let s of this.items){if(s.identity!==e)continue;s.identity=r;let{id:i}=s;if(!this.persistence||i===void 0)continue;let n={args:s.args,clientId:s.clientId,functionPath:s.functionPath,id:i,identity:r,shardKey:s.shardKey,...this.version===void 0?{}:{version:this.version}};this.rewriteStamp(i,n).catch(a=>{H(this.onPersistenceError,"replace",a,i)})}}drain(e){if(!e){let i=[...this.items];return this.items.length=0,this.notifySize(),i}let r=[],s=[];for(let i of this.items)(e(i)?r:s).push(i);return this.items.length=0,this.items.push(...s),this.notifySize(),r}requeue(e){e.length!==0&&(this.items.unshift(...e),this.notifySize())}drainConflict(){let e=[],r=[];for(let s of this.items)if(s.precondition!==void 0&&!s.precondition()){let i=new Error("offline mutation skipped: precondition failed before replay");i.code="OFFLINE_PRECONDITION_FAILED",s.reject(i),e.push(s)}else r.push(s);return e.length>0&&(this.items.length=0,this.items.push(...r),this.notifySize()),e}clear(){for(let e of this.items){let r=new Error("CLIENT_CLOSED");r.code="CLIENT_CLOSED",e.reject(r)}this.items.length=0,this.notifySize()}async rewriteStamp(e,r){let s=this.persistence;if(s)try{await s.replace(r)}catch(i){H(this.onPersistenceError,"replace",i,e)}}evictOverflow(){for(;this.items.length>this.maxItems;){let e=this.items.shift();if(e){e.id&&this.persistence?.remove(e.id).catch(s=>{H(this.onPersistenceError,"remove",s,e.id)});let r=new Error("offline queue overflow");r.code="OFFLINE_QUEUE_OVERFLOW",e.reject(r),this.onEvict?.(e,r)}}}notifySize(){this.onSizeChange?.(this.items.length)}};var gs="lunora-outbox",Ss="offline-mutations",dt="by_id",ws=o((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new p("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let r=t.databaseName??gs,s=t.storeName??Ss,i=Fe(e,r,1,a=>{a.objectStoreNames.contains(s)||a.createObjectStore(s,{autoIncrement:!0}).createIndex(dt,"id",{unique:!0})}),n=Me(i,s);return{append:o(async a=>{await n("readwrite",c=>R(c.add(a)))},"append"),clear:o(async()=>{await n("readwrite",a=>R(a.clear()))},"clear"),load:o(async()=>n("readonly",a=>R(a.getAll())),"load"),remove:o(async a=>{await n("readwrite",async c=>{let u=await R(c.index(dt).getKey(a));u!==void 0&&await R(c.delete(u))})},"remove"),replace:o(async a=>{await n("readwrite",async c=>{let u=await R(c.index(dt).getKey(a.id));u!==void 0&&await R(c.put(a,u))})},"replace")}},"w"),br=o((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return ws()}},"b");var lt=o((t={},e=Math.random)=>{let r=t.initialDelayMs??250,s=t.maxDelayMs??3e4,i=t.jitter??!0,n=0;return{next(){let a=Math.min(s,r*2**n);if(n+=1,!i)return a;let c=a/2;return Math.floor(c+e()*(a-c))},reset(){n=0}}},"s");var vr=o((t,e,r,s)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,r,s),n=i.present?j(i.value):void 0;return()=>{let a=t.peekActiveQuerySnapshot(e.__lunoraRef,r,s);return!i.present||!a.present?!0:j(a.value)===n}},"c");var ft=500,Cs=o(async t=>{let e=[],r;for(;;){let s=await t(r);if(e.push(...Array.isArray(s.records)?s.records:[]),s.truncated!==!0||typeof s.cursor!="string"||s.cursor.length===0)return e;if(s.cursor===r)throw new Error("collectPages: the list did not advance its cursor \u2014 refusing to page forever");r=s.cursor}},"Ce"),gr=o((t,e)=>{if(t.size<e)return;let r=t.keys().next().value;r!==void 0&&t.delete(r)},"G"),te=class{static{o(this,"I")}listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){let[r]=e;for(let s of this.listeners)try{s(r)}catch{}}clear(){this.listeners.clear()}},Ir=new Set(["RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Or=new Set(["TOKEN_EXPIRED","UNAUTHENTICATED","UNAUTHORIZED"]),ks=o(t=>Or.has(t?.code??""),"we"),Ts=o(t=>{if(t instanceof B)return!0;let e=t?.code;return e===void 0||Ir.has(e)||Or.has(e)},"Ee"),Rr=6e4,Es=1e3,Pr=o(t=>{if(t===null)return;let e=Number(t);if(Number.isFinite(e))return e>0?e*1e3:void 0;let r=Date.parse(t);if(Number.isNaN(r))return;let s=r-Date.now();return s>0?s:void 0},"re"),Is={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},Ne=o((t,e,r)=>{let s=Pr(r),i=s===void 0?void 0:{retryAfterMs:s},n=`LunoraClient: response carried no error envelope (status ${t.toString()}${e?` ${e}`:""})`;return t<400||t>=500||t===408?new B(n,i):new p(Is[t]??"BAD_REQUEST",n,{data:i})},"M"),Os=o((t,e)=>{let r=Pr(e);if(!(r===void 0||ot(t)!==void 0))return t.data===void 0?{retryAfterMs:r}:typeof t.data=="object"&&t.data!==null&&!Array.isArray(t.data)?{...t.data,retryAfterMs:r}:void 0},"Ie"),Rs=o((t,e=Math.random)=>{let r=Math.min(Es*2**Math.max(t-1,0),Rr);return Math.round(r*(.5+e()*.5))},"Oe"),Ps=o(t=>t instanceof B||Ir.has(t?.code??""),"Re"),As=o((t,e,r)=>{let s=ot(t);return s!==void 0&&s>0?Math.min(s,Rr):Ps(t)?Rs(e,r):void 0},"Pe"),Fs=983040,Ms=o(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"Fe"),xs="/_lunora/rpc",Sr="/_lunora/rpc-batch",_s="/_lunora/ws",pt=o(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"N"),fe=o(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"O"),wr=Symbol("lunora.unmergeableDelta"),Ls=o((t,e)=>{for(let r of e)r.op==="delete"?t.delete(r.key):r.value!==void 0&&t.set(r.key,r.value)},"Ue"),Qs="lunora-ping",Ds=3e4,Us=1e4,Ns=250,qs=5e3,Ks=64,Bs=8,js="/_lunora/admin/shard-traffic",$s="/_lunora/admin/scheduled",Hs="/_lunora/admin/scheduled/status",zs="/_lunora/admin/scheduled/ws",Ws="/_lunora/admin/scheduled/cancel",Cr="/_lunora/admin/scheduled/dead",Vs="/_lunora/admin/scheduled/dead/retry",Gs="/_lunora/admin/scheduled/dead/cancel",Js="/_lunora/admin/workflows/instances",Xs="/_lunora/admin/workflows/instance",Ys="/_lunora/admin/workflows/status",mt="/_lunora/admin/storage",Zs="/_lunora/admin/storage/url",ei="/_lunora/admin/storage/buckets",ti="/_lunora/admin/functions",ri="/_lunora/admin/cron-jobs",si="/_lunora/admin/cron-jobs/run",ii="/_lunora/admin/openapi",ni="/_lunora/admin/openrpc",ai="/_lunora/admin/global/tables",oi="/_lunora/admin/global/table",ci="/_lunora/admin/global/facet",ui="/_lunora/admin/vector/indexes",hi="/_lunora/admin/vector/query",di="/_lunora/admin/logs/archive",li="/_lunora/admin/kv/namespaces",fi="/_lunora/admin/kv/keys",yt="/_lunora/admin/kv/value",pi="/_lunora/admin/auth/users",mi="/_lunora/admin/auth/sessions",yi="/_lunora/admin/auth/users/create",bi="/_lunora/admin/auth/users/role",vi="/_lunora/admin/auth/users/ban",gi="/_lunora/admin/auth/users/unban",Si="/_lunora/admin/auth/users/password",wi="/_lunora/admin/auth/users/remove",Ci="/_lunora/admin/auth/users/impersonate",ki="/_lunora/admin/auth/sessions/revoke",Ti="/_lunora/admin/auth/sessions/revoke-all",Ei="/_lunora/admin/auth/capabilities",Ii="/_lunora/admin/auth/users/update",Oi="/_lunora/admin/auth/accounts",Ri="/_lunora/admin/auth/accounts/unlink",Pi="/_lunora/admin/auth/passkeys",Ai="/_lunora/admin/auth/passkeys/delete",Fi="/_lunora/admin/auth/two-factor/disable",Mi="/_lunora/admin/auth/organizations",xi="/_lunora/admin/auth/organizations/members",_i="/_lunora/admin/auth/organizations/invitations",Li="/_lunora/admin/auth/organizations/members/remove",Qi="/_lunora/admin/auth/organizations/invitations/cancel",Di="/_lunora/admin/auth/config",Ui="/_lunora/admin/auth/sign-up-invitations",Ni="/_lunora/admin/auth/sign-up-invitations/create",qi="/_lunora/admin/auth/sign-up-invitations/revoke",Ki="/_lunora/admin/auth/organizations/create",Bi="/_lunora/admin/auth/organizations/update",ji="/_lunora/admin/auth/organizations/remove",$i="/_lunora/admin/auth/organizations/members/add",Hi="/_lunora/admin/auth/organizations/members/invite",zi="/_lunora/admin/auth/organizations/members/role",Wi="/_lunora/admin/auth/organizations/teams",Vi="/_lunora/admin/auth/organizations/teams/create",Gi="/_lunora/admin/auth/organizations/teams/update",Ji="/_lunora/admin/auth/organizations/teams/remove",Xi="/_lunora/admin/auth/organizations/teams/members",Yi="/_lunora/admin/auth/organizations/teams/members/add",Zi="/_lunora/admin/auth/organizations/teams/members/remove",en="/_lunora/admin/auth/organizations/roles",tn="/_lunora/admin/auth/organizations/roles/create",rn="/_lunora/admin/auth/organizations/roles/update",sn="/_lunora/admin/auth/organizations/roles/remove",nn="/api/auth",an="/get-session",kr=o(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"Y"),ee=o((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"C"),I=o((t,e)=>{let r=new URLSearchParams;for(let[i,n]of Object.entries(e))n!==void 0&&n!==""&&r.set(i,String(n));let s=r.toString();return s===""?t:`${t}?${s}`},"y"),on=[cr],S=o(t=>t??"","l"),Ar=o((t,e)=>{let r=t.error,s=typeof r?.code=="string"?r.code:void 0,i=typeof r?.message=="string"?r.message:void 0;return{code:s,messageText:(typeof t.message=="string"?t.message:void 0)??i??e}},"ie"),cn=o(t=>{let{code:e,messageText:r}=Ar(t,"stream error");return e===void 0?new Error(r):new p(e,r)},"cs"),Tr=o(t=>{let{code:e,messageText:r}=Ar(t,"subscription error");return{message:r,...e===void 0?{}:{code:e}}},"J");function bt(t){if(t!==void 0)return e=>{t(e)}}o(bt,"B");var pe=o((t,e)=>{for(let r of t)try{r(e)}catch{}},"R"),un=new TextDecoder,hn=o(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return un.decode(t)},"ds"),M=o((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"b"),qe=o(t=>{let e=new Error(t.message??"request failed");return e.code=t.code,t.data!==void 0&&(e.data=g(t.data)),t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),e},"F"),Er=o((t,e)=>{let r=qe(t),s=Os(r,e);return s!==void 0&&(r.data=s),r},"X"),z=o((t,e)=>{try{return O(t)}catch(r){let s=r instanceof Error?r.message:String(r);throw new TypeError(`LunoraClient: cannot encode ${e} \u2014 ${s}`,r instanceof Error?{cause:r}:void 0)}},"k"),vt=o(t=>"args"in t?{...t,args:g(t.args)}:t,"Q"),dn=o((t,e)=>{let r=Array.from({length:e});for(let s of t){if(typeof s.id!="number"||s.id<0||s.id>=e)continue;let i=s.body;r[s.id]=i&&"error"in i&&i.error?{error:qe(i.error),ok:!1}:{ok:!0,value:g(i?.result)}}return r.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},"us"),ln=Promise.resolve(),gt=class t{static{o(this,"ne")}static MAX_POKE_BUFFERS=256;static createClientQuery(e,r){return{defaultValue:r,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;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new P;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;subjectToken=null;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new te;statusListeners=new te;tokenExpiredListeners=new te;authRefusalNotifiedFor;mutationSettledListeners=new te;pendingChangeListeners=new te;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??ee(kr(e.url),_s),this.wsToken=e.wsToken;let r=e.authBasePath??nn;this.authBasePath=r.endsWith("/")?r.slice(0,-1):r,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??ar(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??Ds,this.connectTimeoutMs=e.connectTimeoutMs??Us,this.defaultConnectionContext=e.connectionContext,this.persistence=br(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=nr(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new xe,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=ln),this.offlineQueue=new De(e.offlineQueue,{onEvict:o((s,i)=>{this.emitItemSettled(s,"rejected",i)},"onEvict"),onSizeChange:o(s=>{this.pendingChangeListeners.emit(s)},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${Ue()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})})}setAuthToken(e,r){let s=this.authToken!==e,i=this.identityFingerprint(),n=this.authSubject===void 0||this.subjectToken===this.authToken,a=this.subjectAwaitingReconfirm();this.authToken=e,r!==void 0?(this.authSubject=r,this.subjectToken=e):e===null&&(this.authSubject=void 0,this.subjectToken=null);let c=this.identityFingerprint();if(c!==i&&(!s&&n?(this.restampQueuedIdentity(i,c),this.restampWatermarks(i,c),this.restampConnectionIdentity(i,c),this.reseedFromHydratedCache()):this.rejectQueuedForIdentityChange(i),this.tabCoordinator)){let u=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),u&&this.tabCoordinator.promoteImmediately()}this.syncReadCacheToCredential(a),s&&this.authTokenListeners.emit(e),this.offlineQueue.size>0&&this.computeStatus()==="connected"&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}replayIdentityVerdict(e){if(this.subjectAwaitingReconfirm())return"unknown";let r=this.identityFingerprint();return e===r||e!==void 0&&this.isSameCredentialUnderTokenHash(e)?"match":r===null?"unknown":"mismatch"}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,r,s){let i=s?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new p("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let n=s?.shardKey??"",a=this.identityFingerprint(),c,u=await this.rpc(e,r,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:o(h=>{c=h},"onMutationAck")});if(c!==void 0&&c>(this.clientWatermarks.get(a??"")?.get(n)??0)){let h=this.clientWatermarks.get(a??"");h===void 0&&(gr(this.clientWatermarks,Bs),h=new Map,this.clientWatermarks.set(a??"",h)),h.set(n,c)}return{applied:c===void 0||c===i,result:u}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}async getCurrentUser(){if(this.closed||!this.fetchImpl)return null;let e={},r=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`);try{let s=await this.fetchImpl(ee(this.url,`${this.authBasePath}${an}`),{credentials:"include",headers:e,method:"GET"});if(!s.ok)return null;let i=(await s.json())?.user??null;return this.adoptResolvedSubject(r,i),i}catch{return null}}setWsToken(e){if(this.wsToken!==e){this.wsToken=e;for(let r of this.connections.values())if(r.socket)try{r.socket.close()}catch{}}}setConnectionContext(e,r={}){this.assertLeaderOwnedSurface("setConnectionContext");let s=S(r.shardKey);e===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,e),this.refreshConnectionContext(s)}acquireConnectionContext(e,r={}){if(this.followsAnotherTab())return()=>{};let s=S(r.shardKey),i={context:e},n=this.connectionContextHolders.get(s);n?n.push(i):this.connectionContextHolders.set(s,[i]),this.refreshConnectionContext(s);let a=!1;return()=>{if(a)return;a=!0;let c=this.connectionContextHolders.get(s);if(!c)return;let u=c.indexOf(i);u!==-1&&c.splice(u,1),c.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s)}}whisperSubscribe(e,r,s={}){this.assertLeaderOwnedSurface("whisperSubscribe");let i=S(s.shardKey),n=this.whisperHandlers.get(i);n||(n=new Map,this.whisperHandlers.set(i,n));let a=n.get(e),c=a===void 0;if(a||(a=new Set,n.set(e,a)),a.add(r),this.ensureSocket(s.shardKey),c){let u=this.getConnection(s.shardKey);u&&M(u,{topic:e,type:"whisper_subscribe"})}return()=>{let u=this.whisperHandlers.get(i),h=u?.get(e);if(!h?.delete(r)||h.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let d=this.getConnection(s.shardKey);d&&M(d,{topic:e,type:"whisper_unsubscribe"})}}whisper(e,r,s={}){this.assertLeaderOwnedSurface("whisper"),this.ensureSocket(s.shardKey);let i=this.getConnection(s.shardKey);i&&M(i,{data:z(r??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"})}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let r=this.statusListeners.add(e);return e(this.computeStatus()),r}pendingCount(){return this.offlineQueue.size}debug(){let e=[],r=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...r?.keys()??[]]);for(let n of s){let a=this.connections.get(n);e.push({confirmedMutationWatermark:r?.get(n)??0,hasSocket:a?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:a?.wasEverConnected??!1,wsState:a?.wsState??"idle"})}let i=this.subscriptions.all().map(n=>({acked:n.acked,functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(let n of this.shapeSubscriptions.values())i.push({acked:n.serverCursor!==void 0,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,a)=>(n.shardKey??"").localeCompare(a.shardKey??"")),subscriptions:i.toSorted((n,a)=>n.functionPath.localeCompare(a.functionPath))}}onPendingChange(e){let r=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),r}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,r){this.clientQueryStore.set(e,r)}subscribeClientQuery(e,r){return this.clientQueryStore.subscribe(e,r)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,r,s){return vr(this,e,r,s)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,r,s){if(!this.readyResolved)return;let i=j(r),n=Y(e,i,s),a=this.hydratedQueryCache.get(n);if(a!==void 0)return this.cachedQueryMatchesIdentity(a)?a.value:void 0}peekActiveQuerySnapshot(e,r,s){let i=P.key(e,r,s),n=this.subscriptions.get(i);return{present:n!==void 0,value:n?.lastValue}}async query(e,r,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,r,s.shardKey,{attachBookmark:!0})}async batch(e){if(this.assertOpen(),!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(ee(this.url,Sr),{body:JSON.stringify({calls:e.map((n,a)=>({args:z(n.args??{},`args for batch call '${n.fn.__lunoraRef}'`),functionPath:n.fn.__lunoraRef,id:a,shardKey:n.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"}),s=r.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let i;try{i=await r.json()}catch{throw new p("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`)}if(!r.ok||i.error&&!i.results)throw i.error?qe(i.error):new p("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`);for(let n of i.results??[]){let a=n.body?.commitCursor;typeof n.id=="number"&&typeof a=="number"&&this.recordShardCursor(e[n.id]?.shardKey,a)}return dn(i.results??[],e.length)}async mutation(e,r,s={}){this.assertOpen();let i=r,n=s.mutationId??Ue(),{confirms:a,rollbacks:c}=this.applyOptimisticUpdates(e.__lunoraRef,i,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,r,s.shardKey,c,a);let u=this.offlineFlushes.get(S(s.shardKey));u!==void 0&&await u;let{hasSocket:h,wasEverConnected:d,wsState:l}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:f}=this.offlineQueue,y=d||f,m=this.WebSocketImpl!==void 0&&y;if(l!=="open"&&!h&&m||l==="connecting"&&y)return this.enqueueOfflineMutation(e,i,s.shardKey,n,c,a,s.precondition);try{let b,C=await this.rpc(e.__lunoraRef,i,s.shardKey,{captureBookmark:!0,mutationId:n,onCommitCursor:o(k=>{b=k},"onCommitCursor")});for(let k of a)k(b);return C}catch(b){throw fe(c),b}}async action(e,r,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,r,s.shardKey,{attachBookmark:!0,captureBookmark:!0})}async importRows(e,r,s={}){this.assertOpen();let i=Math.max(1,Math.trunc(s.chunkSize??500)),n=s.toArgs??(h=>({rows:h})),a=r.length,c=0,u=0;for(let h=0;h<a;h+=i){let d=r.slice(h,h+i),l=u;await this.mutation(e,n(d),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(l)}`},shardKey:s.shardKey}),u+=1,c+=d.length,s.onProgress?.({done:c,total:a})}return{chunks:u,imported:c}}async shardTraffic(e){this.assertOpen();let r=await this.adminFetch(js,"POST",{table:e});return{failed:r.failed??0,ok:r.ok??0,shards:r.shards??[]}}async listScheduledJobs(){return this.assertOpen(),((await this.adminFetch($s,"GET")).records??[]).map(e=>vt(e))}async schedulerStatus(){this.assertOpen();let e=await this.adminFetch(Hs,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}}async cancelScheduledJob(e){return this.assertOpen(),{cancelled:(await this.adminFetch(Ws,"POST",{id:e})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await Cs(async e=>await this.adminFetch(e===void 0?Cr:`${Cr}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>vt(e))}async retryDeadJob(e){return this.assertOpen(),{retried:(await this.adminFetch(Vs,"POST",{id:e})).retried===!0}}async removeDeadJob(e){return this.assertOpen(),{removed:(await this.adminFetch(Gs,"POST",{id:e})).removed===!0}}async listWorkflowInstances(e){this.assertOpen();let r=new URLSearchParams({name:e.name});e.status!==void 0&&r.set("status",e.status),e.page!==void 0&&r.set("page",String(e.page)),e.perPage!==void 0&&r.set("perPage",String(e.perPage));let s=await this.adminFetch(`${Js}?${r.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();let r=new URLSearchParams({id:e.id,name:e.name}),s=await this.adminFetch(`${Xs}?${r.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(Ys,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let r=ee(kr(this.url),zs),s=lt(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},n,a=!1,c=o(()=>{a||this.closed||(n=setTimeout(d,s.next()))},"a"),u=o(f=>{if(a||this.WebSocketImpl===void 0)return;let y=f===void 0?r:`${r}?token=${encodeURIComponent(f)}`;this.openManagedSocket(i,y,this.connectTimeoutMs,{onClose:o(()=>{c()},"onClose"),onMessage:o(m=>{let b;try{b=JSON.parse(typeof m.data=="string"?m.data:"")}catch{return}b.type==="jobs"&&Array.isArray(b.records)&&(s.reset(),e(b.records.map(C=>vt(C))))},"onMessage")})},"c"),h=o(async f=>{let y;try{y=await f()}catch{c();return}u(y)},"h"),d=o(()=>{if(a||this.WebSocketImpl===void 0)return;let{wsToken:f}=this;if(typeof f=="function"){h(f).catch(()=>{});return}u(f)},"d");d();let l=o(()=>{a=!0,n!==void 0&&(clearTimeout(n),n=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),this.stopHeartbeat(i),i.socket?.close(),i.socket=void 0},"u");return this.adminSocketTeardowns.add(l),()=>{this.adminSocketTeardowns.delete(l),l()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(ti,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(ri,"GET")).jobs??[]}async runCronJob(e){this.assertOpen();let r=await this.adminFetch(si,"POST",{name:e});return{name:r.name??e,ran:r.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(ii,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(ni,"GET")}async listStorageObjects(e={}){this.assertOpen();let r=I(mt,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await this.adminFetch(r,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(e,r){this.assertOpen();let s=`${mt}?key=${encodeURIComponent(e)}${pt(r?.bucket)}`,i=await this.adminFetch(s,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(ei,"GET")).buckets??[]}async uploadStorageObject(e){this.assertOpen();let r=`${mt}?key=${encodeURIComponent(e.key)}${pt(e.bucket)}`,s=await this.adminFetch(r,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}}async signedStorageUrl(e,r){this.assertOpen();let s=r?.expiresInSeconds,i=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,n=`${Zs}?key=${encodeURIComponent(e)}${i}${pt(r?.bucket)}`,a=await this.adminFetch(n,"GET");if(typeof a.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return a.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(ai,"GET")}async readGlobalTablePage(e){this.assertOpen();let r=new URLSearchParams({table:e.table});return e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&r.set("filters",JSON.stringify(O(e.filters))),g(await this.adminFetch(`${oi}?${r.toString()}`,"GET"))}async facetGlobalColumn(e){this.assertOpen();let r=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&r.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&r.set("filters",JSON.stringify(O(e.filters))),g(await this.adminFetch(`${ci}?${r.toString()}`,"GET"))}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch(ui,"GET")).indexes??[]}async queryVectorIndex(e){return this.assertOpen(),(await this.adminFetch(hi,"POST",e)).matches??[]}async queryLogArchive(e={}){this.assertOpen();let r=await this.adminFetch(di,"POST",e);return{nextCursor:r.nextCursor,rows:r.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(li,"GET")).namespaces??[]}async listKvKeys(e){this.assertOpen();let r=I(fi,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await this.adminFetch(r,"GET")}async getKvValue(e){this.assertOpen();let r=I(yt,{key:e.key,namespace:e.namespace});return await this.adminFetch(r,"GET")}async putKvValue(e){this.assertOpen(),await this.adminFetch(yt,"PUT",e)}async deleteKvKey(e){this.assertOpen();let r=I(yt,{key:e.key,namespace:e.namespace});await this.adminFetch(r,"DELETE")}async listAuthUsers(e={}){this.assertOpen();let r=I(pi,{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(r,"GET")}async createAuthUser(e){return await this.adminFetch(yi,"POST",e)}async setAuthUserRole(e){return await this.adminFetch(bi,"POST",e)}async banAuthUser(e){return await this.adminFetch(vi,"POST",e)}async unbanAuthUser(e){return await this.adminFetch(gi,"POST",e)}async setAuthUserPassword(e){await this.adminFetch(Si,"POST",e)}async removeAuthUser(e){await this.adminFetch(wi,"POST",e)}async impersonateAuthUser(e){return await this.adminFetch(Ci,"POST",e)}async revokeAuthSession(e){await this.adminFetch(ki,"POST",e)}async revokeAuthUserSessions(e){await this.adminFetch(Ti,"POST",e)}async getAuthCapabilities(){return await this.adminFetch(Ei,"GET")}async updateAuthUser(e){return await this.adminFetch(Ii,"POST",e)}async listAuthAccounts(e){return await this.adminFetch(I(Oi,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){await this.adminFetch(Ri,"POST",e)}async listAuthPasskeys(e){return await this.adminFetch(I(Pi,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){await this.adminFetch(Ai,"POST",e)}async disableAuthTwoFactor(e){await this.adminFetch(Fi,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(I(Mi,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){let r=I(xi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async listAuthOrgInvitations(e){let r=I(_i,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async listAuthSignUpInvitations(e={}){let r=I(Ui,{limit:e.limit,offset:e.offset});return await this.adminFetch(r,"GET")}async createAuthSignUpInvitation(e){return await this.adminFetch(Ni,"POST",e)}async revokeAuthSignUpInvitation(e){await this.adminFetch(qi,"POST",e)}async removeAuthOrgMember(e){await this.adminFetch(Li,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(Qi,"POST",e)}async getAuthConfig(){return await this.adminFetch(Di,"GET")}async createAuthOrganization(e){return await this.adminFetch(Ki,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(Bi,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(ji,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch($i,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(Hi,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch(zi,"POST",e)}async listAuthOrgTeams(e){let r=I(Wi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(Vi,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch(Gi,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(Ji,"POST",e)}async listAuthOrgTeamMembers(e){let r=I(Xi,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(r,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(Yi,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(Zi,"POST",e)}async listAuthOrgRoles(e){let r=I(en,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async createAuthOrgRole(e){return await this.adminFetch(tn,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(rn,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(sn,"POST",e)}async listAuthSessions(e={}){this.assertOpen();let r=I(mi,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(r,"GET")}subscribe(e,r,s,i={}){this.assertOpen();let n=r??{},a=P.key(e.__lunoraRef,n,i.shardKey),c=this.subscriptions.get(a),u=bt(s),h=bt(i.onError),d=bt(i.onCheckpoint);if(!c){this.nextSubId+=1;let f=`sub_${this.nextSubId.toString()}`,y=j(n),m=this.takeHydratedCache(e.__lunoraRef,y,i.shardKey);c={acked:!1,args:n,argsKey:y,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:f,lastValue:m?.value,optimisticLayers:[],serverBase:m?.value,serverCursor:m?.serverCursor,shardKey:i.shardKey,wireArgs:z(n,`args for '${e.__lunoraRef}'`),...m?.serverEpoch===void 0?{}:{serverEpoch:m.serverEpoch}},this.subscriptions.add(c),m!==void 0&&this.cacheSeededQueries.set(a,m)}if(c.callbacks.add(u),h&&c.errorCallbacks.add(h),d&&c.checkpointCallbacks.add(d),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let l=c;return()=>{l.callbacks.delete(u),h&&l.errorCallbacks.delete(h),d&&l.checkpointCallbacks.delete(d),l.callbacks.size===0&&(this.sendOrQueueUnsubscribe(l.shardKey,l.id,"unsubscribe"),this.returnCacheSeed(P.keyOf(l)),this.subscriptions.remove(l))}}subscribeShape(e,r,s={}){if(this.assertOpen(),this.followsAnotherTab()){let{onError:a}=s;return a!==void 0&&queueMicrotask(()=>{a({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;let i=`shape_${this.nextShapeId.toString()}`,n={args:e.args,callbacks:new Set([r]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:i,name:e.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:e.args===void 0?void 0:z(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,n),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(n.shardKey,i,"shape_unsubscribe")}}stream(e,r,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new p("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;let i=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=s,a=r??{},{handle:c,iterable:u}=Le({maxBuffer:s.maxBuffer,onCancel:o(()=>{this.cancelStream(i,n)},"onCancel")});this.ensureSocket(n);let h=this.getConnection(n),d={id:i,query:{args:z(a,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"},l={durable:s.durable===!0,generation:void 0,handle:c,lastSeq:0,message:d,shardKey:n,started:!1};this.streams.set(i,l);let f=h?.wsState==="open"&&M(h,d);if(l.started=f,!f&&h===void 0)return this.streams.delete(i),c.fail(new p("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),u;if(!f){for(h.pendingStreams=h.pendingStreams??[];h.pendingStreams.length>=Ks;){let y=h.pendingStreams.shift()?.id,m=y?this.streams.get(y):void 0;m&&(m.handle.fail(new p("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(y))}h.pendingStreams.push(d)}return u}httpStream(e,r,s={}){if(this.closed)throw new p("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return fr(e,r,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(let e of this.streams.values())e.handle.fail(new p("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(let e of this.connections.values())this.teardownConnection(e);for(let e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear();for(let e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new p("INTERNAL","LunoraClient is closed")}followsAnotherTab(){let e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;let r=e.leaderTabId;return r!==void 0&&r!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new p("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){let r=S(e.shardKey);for(let[s,i]of this.streams)S(i.shardKey)===r&&(i.handle.fail(new p("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(){let e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new _e({channelName:e,onBecomeLeader:o(()=>{for(let r of this.subscriptions.all())this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(r);for(let r of this.queuedOfflineShardKeys)this.ensureSocket(r);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},"onBecomeLeader"),onStopBeingLeader:o(()=>{for(let[r,s]of this.connections)this.teardownConnection(s),this.connections.delete(r);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},"onStopBeingLeader"),onConnectionStatus:o((r,s)=>{if(s!==void 0&&s!==this.identityFingerprint())return;let i=r==="connected"&&this.leaderStatus!=="connected";this.leaderStatus=r,r==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),i&&this.flushAllOfflineQueues()},"onConnectionStatus"),onSubscriptionData:o((r,s,i,n,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;let c=this.subscriptions.get(r);c&&(c.serverBase=s,this.dropCacheSeed(r),i!==void 0&&(c.serverCursor=i,n!==void 0&&(c.serverEpoch=n),Qe(c,i)),$(c,Z(s,c.optimisticLayers)))},"onSubscriptionData"),onLeaderClaimAnswered:o(()=>{this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},"onLeaderClaimAnswered"),onSubscriptionError:o((r,s,i)=>{if(i!==void 0&&i!==this.identityFingerprint())return;let n=this.subscriptions.get(r);n&&pe(n.errorCallbacks,s)},"onSubscriptionError"),onSubscriptionSettled:o((r,s,i,n,a,c)=>{if(c!==void 0&&c!==this.identityFingerprint())return;let u=this.subscriptions.get(r);if(u){this.ackAndAdvanceCursor(u,s,i),n!==void 0&&a===this.clientId&&(u.lastMutationId=Math.max(u.lastMutationId??0,n));for(let h of u.checkpointCallbacks)h({checkpoint:u.serverCursor,mutationId:u.lastMutationId})}},"onSubscriptionSettled")})}async enqueueOfflineMutation(e,r,s,i,n,a,c){let u=this.identityFingerprint();if(this.outbox){this.outboxMutationCounter+=1;let h=this.outboxMutationCounter;try{await this.outbox.enqueue({args:r,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:`${this.clientId}:${String(h)}`,identity:u,mutationId:h,...n.length>0&&{onRejected:o(()=>{fe(n)},"onRejected")},shardKey:s})}catch(d){throw fe(n),d instanceof Error?d:new Error(String(d))}for(let d of a)d(void 0);return}return new Promise((h,d)=>{let l={args:r,functionPath:e.__lunoraRef,liveAwaiter:!0,id:i,clientId:this.clientId,identity:u,precondition:c,onCommit:o(f=>{for(let y of a)y(f)},"onCommit"),reject:o(f=>{this.queuedIdentities.delete(i),fe(n),d(f instanceof Error?f:new Error(String(f)))},"reject"),resolve:h,shardKey:s};this.offlineQueue.enqueue(l),this.queuedOfflineShardKeys.add(s),l.id!==void 0&&this.queuedIdentities.set(l.id,u)})}async hydratePersistedQueue(){try{let e=await this.offlineQueue.hydrate();for(let r of e)this.queuedOfflineShardKeys.add(r),this.ensureSocket(r)}catch{}}hydrateAsOutboxLeader(){let e=o(()=>{this.hydratePersistedQueue().catch(()=>{})},"e"),r=globalThis.navigator?.locks;if(!r){e();return}r.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{let e=await this.queryCache.load(),r=new Map;for(let s of this.subscriptions.all())r.set(Y(s.fn.__lunoraRef,s.argsKey,s.shardKey),s);for(let{key:s,...i}of e){if(ht(this.persistenceVersion,i.version)){this.queryCache.remove(s).catch(()=>{});continue}let n=r.get(s);if(n&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(n,i);continue}this.hydratedQueryCache.set(s,i)}}catch{}}seedSubscriptionFromCache(e,r){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(r)||(e.serverBase=r.value,e.serverCursor=r.serverCursor,r.serverEpoch!==void 0&&(e.serverEpoch=r.serverEpoch),this.cacheSeededQueries.set(Y(e.fn.__lunoraRef,e.argsKey,e.shardKey),r),$(e,Z(r.value,e.optimisticLayers)))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}returnCacheSeed(e){let r=this.cacheSeededQueries.get(e);r!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,r))}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(let[e,r]of this.cacheSeededQueries){let s=this.subscriptions.get(e);s!==void 0&&(s.serverBase=void 0,s.serverCursor=void 0,s.serverEpoch=void 0,$(s,Z(void 0,s.optimisticLayers))),this.hydratedQueryCache.set(e,r)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,r,s){let i=Y(e,r,s),n=this.hydratedQueryCache.get(i);if(!(n===void 0||!this.cachedQueryMatchesIdentity(n)))return this.hydratedQueryCache.delete(i),n}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(let e of this.subscriptions.all()){let r=Y(e.fn.__lunoraRef,e.argsKey,e.shardKey),s=this.hydratedQueryCache.get(r);s!==void 0&&this.cachedQueryMatchesIdentity(s)&&(this.hydratedQueryCache.delete(r),this.seedSubscriptionFromCache(e,s))}}persistQueryValue(e){let r=e.serverBase;if(!this.queryCache||r===void 0)return;let s=Y(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,n=i===void 0?this.identityFingerprint():i;this.pendingCacheWrites.set(s,{identity:n,serverCursor:e.serverCursor,ts:Date.now(),value:r,...n===this.identityFingerprint()&&!this.subjectAwaitingReconfirm()?this.credentialStamp():{},...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},Ns)}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;let{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}let r=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(r.map(async([s,i])=>e.put(s,i)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";let e=[...this.connections.values()];return e.length===0?"idle":e.some(r=>r.wsState==="open")?"connected":e.some(r=>r.wsState==="connecting")?"connecting":"offline"}emitConnectionStatus(){let e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,r,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:r})}applyOptimisticUpdates(e,r,s,i){let n=[],a=[];if(!i)return{confirms:n,rollbacks:a};let c=P.key(e,r,s),u=this.subscriptions.get(c);if(u){let h=ut(u,i);h&&(n.push(h.confirm),a.push(h.rollback))}return{confirms:n,rollbacks:a}}applyOptimisticUpdate(e,r,s,i,n){let{confirms:a,rollbacks:c,store:u}=mr(this.subscriptions,s);try{e(u,r)}catch{fe(c);return}i.push(...c),n.push(...a)}getConnection(e){return this.connections.get(S(e))}sendOrQueueUnsubscribe(e,r,s){let i=this.getConnection(e);i&&!M(i,{id:r,type:s})&&i.pendingUnsubscribes.push({id:r,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}}let r=this.getConnection(e);return{hasSocket:r?.socket!==void 0,wasEverConnected:r?.wasEverConnected??!1,wsState:r?.wsState??"idle"}}getOrCreateConnection(e){let r=S(e),s=this.connections.get(r);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],reconnect:lt(this.reconnectOptions),reconnectTimer:void 0,shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:!1,wsState:"idle"},this.connections.set(r,s)),s}wsUrlFor(e,r){let s=[];if(e!==void 0&&s.push(`shard=${encodeURIComponent(e)}`),r!==void 0&&s.push(`token=${encodeURIComponent(r)}`),s.length===0)return this.wsUrl;let i=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${i}${s.join("&")}`}rpcRequestHeaders(e,r){let s={"content-type":"application/json"},i=this.shardCursors.get(this.cursorKeyFor(r));if(i!==void 0&&(s["x-lunora-min-seq"]=i.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){let n=this.bookmark.get();n&&(s["x-d1-bookmark"]=n)}return s}async rpc(e,r,s,i={}){if(!this.fetchImpl)throw new B("LunoraClient: no `fetch` implementation available");let n=this.rpcRequestHeaders(i,s),a=await this.fetchImpl(ee(this.url,xs),{body:JSON.stringify({args:z(r,`args for '${e}'`),functionPath:e,shardKey:s}),headers:n,method:"POST"});if(i.captureBookmark){let u=a.headers.get("x-d1-bookmark");u&&this.bookmark.set(u)}let c;try{c=await a.json()}catch{throw Ne(a.status,a.statusText,a.headers.get("retry-after"))}if("error"in c)throw Er(c.error,a.headers.get("retry-after"));if(!a.ok)throw Ne(a.status,a.statusText,a.headers.get("retry-after"));return i.onMutationAck?.(c.lastMutationId),i.onCommitCursor?.(c.commitCursor),this.learnDefaultShardKey(a,s),this.recordShardCursor(s,c.commitCursor),g(c.result)}async adminFetch(e,r,s,i){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");let n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);let a=s instanceof ArrayBuffer||s instanceof Blob,c;s===void 0?c=void 0:a?(c=s,i!==void 0&&(n["content-type"]=i)):(c=JSON.stringify(s),n["content-type"]="application/json");let u=await this.fetchImpl(ee(this.url,e),{body:c,headers:n,method:r}),h;try{h=await u.json()}catch{let d=u.statusText?` ${u.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${d})`)}if(typeof h=="object"&&h!==null&&"error"in h){let d=h.error,l=new Error(d.message??"admin request failed");throw l.code=d.code,l}if(!u.ok){let d=u.statusText?` ${u.statusText}`:"";throw new p("INTERNAL",`LunoraClient: admin request failed (status ${u.status.toString()}${d})`)}return h}effectiveConnectionContext(e){let r=this.connectionContextHolders.get(e);return r&&r.length>0?r[r.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){let r=this.connections.get(e);r?.wsState==="open"&&this.sendConnectEnvelope(r)}sendConnectEnvelope(e){let r=this.effectiveConnectionContext(S(e.shardKey));M(e,{caps:on,clientId:this.clientId,id:"connect",type:"connect",...r===void 0?{}:{context:r}})}resendShapeSubscriptions(e){for(let r of this.shapeSubscriptions.values())S(r.shardKey)===S(e)&&this.sendShapeSubscribeIfOpen(r)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;let r=this.getOrCreateConnection(e);if(!(r.wsState==="open"||r.wsState==="connecting")){if(r.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(r,e,this.wsToken).catch(()=>{});return}this.openSocket(r,e,this.wsToken)}}async openSocketWithProvidedToken(e,r,s){let i;try{i=await s()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,r,i)}openManagedSocket(e,r,s,i){let{WebSocketImpl:n}=this;if(n===void 0)throw new p("INTERNAL","no WebSocket implementation available");let a=new n(r);e.socket=a;let c=o(()=>{this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket===a&&(e.socket=void 0)},"a"),u=o(h=>{c(),i.onClose(h)},"c");s>0&&(e.connectTimer=setTimeout(()=>{if(e.connectTimer=void 0,e.socket===a){try{a.close()}catch{}u()}},s)),a.addEventListener("open",()=>{if(e.socket===a){e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.lastFrameAt=Date.now();try{i.onOpen?.()}catch(h){console.error("[lunora] connection open handler threw",h)}this.startHeartbeat(e,u)}}),a.addEventListener("message",h=>{if(e.socket===a){e.lastFrameAt=Date.now();try{i.onMessage(h)}catch(d){console.error("[lunora] server frame handler threw",d)}}}),a.addEventListener("close",h=>{e.socket===a&&u(h)}),a.addEventListener("error",()=>{e.socket===a&&u()})}openSocket(e,r,s){this.WebSocketImpl!==void 0&&(e.identity=this.identityFingerprint(),this.openManagedSocket(e,this.wsUrlFor(r,s),this.connectTimeoutMs,{onClose:o(i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},"onClose"),onMessage:o(i=>{this.handleServerMessage(i.data,r)},"onMessage"),onOpen:o(()=>{e.wsState="open",e.wasEverConnected=!0,clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},qs),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(r);for(let n of this.subscriptions.all())S(n.shardKey)===S(r)&&this.sendSubscribeIfOpen(n);if(this.resendShapeSubscriptions(r),e.pendingUnsubscribes.length>0){let n=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:a,type:c}of n)M(e,{id:a,type:c})}this.flushPendingStreams(e);let i=this.whisperHandlers.get(S(r));if(i)for(let n of i.keys())M(e,{topic:n,type:"whisper_subscribe"});this.flushOfflineQueue(r).catch(()=>{})},"onOpen")}))}flushPendingStreams(e){if(!e.pendingStreams||e.pendingStreams.length===0)return;let r=e.pendingStreams;e.pendingStreams=[];for(let s of r){let i=M(e,s)?this.streams.get(String(s.id)):void 0;i&&(i.started=!0)}}cancelStream(e,r){let s=this.getConnection(r),i=this.streams.get(e);s&&(s.pendingStreams=s.pendingStreams?.filter(n=>n.id!==e),!M(s,{id:e,type:"unsubscribe"})&&i?.durable===!0&&i.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);let r=new Set((e.pendingStreams??[]).map(i=>i.id));for(let[i,n]of this.streams)if(!(S(n.shardKey)!==S(e.shardKey)||r.has(i))){if(n.durable){let a={...n.message,...n.generation===void 0?{}:{generation:n.generation},sinceChunk:n.lastSeq};n.message=a,e.pendingStreams=[...(e.pendingStreams??[]).filter(c=>c.id!==i),a];continue}n.handle.fail(new p("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.streams.delete(i)}if(this.WebSocketImpl===void 0)return;let s=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},s)}startHeartbeat(e,r){this.stopHeartbeat(e),!(this.heartbeatIntervalMs<=0)&&(e.heartbeatTimer=setInterval(()=>{if(!e.socket)return;let{socket:s}=e;if(Date.now()-e.lastFrameAt>this.heartbeatIntervalMs*2.5){try{s.close()}catch{}r();return}try{s.send(Qs)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(e){e.heartbeatTimer!==void 0&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=void 0)}markShardPendingAck(e){let r=S(e);for(let s of this.subscriptions.all())S(s.shardKey)===r&&(s.acked=!1)}sendSubscribeIfOpen(e){let r=this.getConnection(e.shardKey);if(r?.wsState!=="open"||e.acked)return;let s=e.fn.__lunoraTable??e.fn.__lunoraRef,i=e.serverCursor!==void 0&&e.serverBase!==void 0;M(r,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:s,...i?{sinceSeq:e.serverCursor}:{},...i&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){let r=this.getConnection(e.shardKey);r?.wsState==="open"&&M(r,{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,r){let s=hn(e);if(s===void 0)return;let i;try{i=JSON.parse(s)}catch{return}switch(i.type!=="error"&&this.getConnection(r)?.reconnect.reset(),i.type){case"ack":{let n=this.subscriptions.getById(i.id);n&&(n.acked=!0);return}case"chunk":{let{data:n,generation:a,id:c,seq:u}=i,h=this.streams.get(c);h&&typeof u=="number"&&(h.lastSeq=u,typeof a=="number"&&(h.generation=a),h.durable=!0),h?.handle.push(g(n));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"pokeEnd":{this.handlePokeEnd(i,r);break}case"pokePart":{this.handlePokePart(i,r);break}case"pokeStart":{this.handlePokeStart(i,r);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,r);break}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}let{id:r}=e,s=r===void 0?void 0:this.streams.get(r);if(s&&r!==void 0){s.handle.fail(cn(e)),this.streams.delete(r);return}let i=r===void 0?void 0:this.subscriptions.getById(r);if(i){let a=Tr(e),c=this.identityFingerprint(),u=P.keyOf(i);pe(i.errorCallbacks,a),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(u,a,c);return}let n=r===void 0?void 0:this.shapeSubscriptions.get(r);n&&pe(n.errorCallbacks,Tr(e))}pokeBufferKey(e,r){return`${S(e)}\0${r}`}handlePokeStart(e,r){gr(this.pokeBuffers,t.MAX_POKE_BUFFERS),this.pokeBuffers.set(this.pokeBufferKey(r,e.pokeId),{baseCheckpoint:e.baseCheckpoint,bases:new Map,epoch:e.epoch,lastMutationId:new Map,parts:new Map,resets:new Set})}handlePokePart(e,r){let s=this.pokeBuffers.get(this.pokeBufferKey(r,e.pokeId));if(!s)return;let i=s.parts.get(e.shapeId)??[];for(let a of e.rowsPatch)i.push(a.value===void 0?a:{...a,value:g(a.value)});s.parts.set(e.shapeId,i),e.lastMutationId!==void 0&&s.lastMutationId.set(e.shapeId,e.lastMutationId);let n=e.baseCheckpoint??s.baseCheckpoint;n!==void 0&&s.bases.set(e.shapeId,n),e.reset===!0&&s.resets.add(e.shapeId)}handlePokeEnd(e,r){let s=this.pokeBufferKey(r,e.pokeId),i=this.pokeBuffers.get(s);if(i){this.pokeBuffers.delete(s);for(let n of i.parts.keys()){let a=this.shapeSubscriptions.get(n);a&&this.applyPokePart(a,i,e)}}}applyPokePart(e,r,s){let i=r.parts.get(e.id)??[],n=r.resets.has(e.id),a=r.bases.get(e.id),c=r.epoch!==void 0&&e.serverEpoch!==void 0&&r.epoch!==e.serverEpoch,u=a!==void 0&&e.serverCursor!==void 0&&e.serverCursor!==a;if(!n&&(c||u)){e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(e),this.sendShapeSubscribeIfOpen(e);return}n&&e.rows.clear(),Ls(e.rows,i),s.checkpoint!==void 0&&(e.serverCursor=s.checkpoint),s.epoch!==void 0&&(e.serverEpoch=s.epoch);let h=r.lastMutationId.get(e.id);h!==void 0&&(e.lastMutationId=h),this.emitShapeRows(e),e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}emitShapeRows(e){let r=[...e.rows.values()];for(let s of e.callbacks)try{s(r)}catch{}}handleDataMessage(e){let{id:r}=e,s=r?this.subscriptions.getById(r):void 0;if(!s)return;let i;try{i=this.resolveDataPayload(e,s)}catch(n){pe(s.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription \u2014 ${n instanceof Error?n.message:String(n)}`});return}if(i===wr){this.resnapshotSubscription(s);return}if(s.serverBase=i,this.dropCacheSeed(P.keyOf(s)),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(let n of s.checkpointCallbacks)n({checkpoint:s.serverCursor,mutationId:s.lastMutationId,rowsFollow:!0})}if(this.persistQueryValue(s),Qe(s,s.serverCursor),$(s,Z(i,s.optimisticLayers)),this.tabCoordinator?.isLeader()){let n=P.keyOf(s);this.tabCoordinator.broadcastSubscriptionData(n,i,s.serverCursor,s.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){let r=this.subscriptions.getById(e.id);r&&this.ackAndAdvanceCursor(r,e.cursor,e.epoch)}handleSettledMessage(e){let r=this.subscriptions.getById(e.id);if(r){this.ackAndAdvanceCursor(r,e.cursor,e.epoch),e.lastMutationId!==void 0&&(r.lastMutationId=Math.max(r.lastMutationId??0,e.lastMutationId));for(let s of r.checkpointCallbacks)s({checkpoint:r.serverCursor,mutationId:r.lastMutationId});if(this.tabCoordinator?.isLeader()){let s=P.keyOf(r);this.tabCoordinator.broadcastSubscriptionSettled(s,r.serverCursor,r.serverEpoch,r.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(e,r,s){e.acked=!0,(r!==void 0&&r!==e.serverCursor||s!==void 0&&s!==e.serverEpoch)&&(r!==void 0&&(e.serverCursor=r),s!==void 0&&(e.serverEpoch=s),this.persistQueryValue(e),Qe(e,e.serverCursor)&&$(e,Z(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,r){if("data"in e&&e.data!==void 0)return g(e.data);let s=g(e.delta);return ur(s)?r.serverBase===void 0?s:hr(r.serverBase,s)??wr:s}dispatchWhisper(e,r){let s=this.whisperHandlers.get(S(r))?.get(e.topic);if(!s)return;let i=g(e.data);for(let n of s)try{n(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){let r=this.streams.get(e);if(r){r.handle.complete(),this.streams.delete(e);return}let s=this.subscriptions.getById(e);s&&(s.acked=!1,pe(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(r=>{H(this.onPersistenceError,"remove",r,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;let e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let r=2166136261,s=5381;for(let i=0;i<e.length;i+=1){let n=e.charCodeAt(i);r^=n,r=Math.imul(r,16777619),s=Math.imul(s,33)+n}return`${e.length.toString(36)}:${(r>>>0).toString(36)}:${(s>>>0).toString(36)}`}credentialStamp(){let e=this.authToken;return e===null?{}:{credential:this.hashToken(e)}}cachedQueryMatchesIdentity(e){return!this.subjectAwaitingReconfirm()&&e.identity===this.identityFingerprint()||this.isSameCredentialUnderTokenHash(e.identity)?!0:e.credential!==void 0&&e.credential===this.credentialStamp().credential}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;let r=this.authToken;return r===null?!1:this.hashToken(r)===e}adoptResolvedSubject(e,r){this.closed||r===null||this.authToken!==e||this.setAuthToken(e,r.id)}subjectAwaitingReconfirm(){return this.authSubject!==void 0&&this.authSubject!==null&&this.subjectToken!==this.authToken}stampOf(e){let r=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return r===void 0?e.identity:r}rejectQueuedForIdentityChange(e){let r=this.offlineQueue.drain(),s=[];for(let i of r){if(this.replayIdentityVerdict(this.stampOf(i))!=="mismatch"){s.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);let n=new Error("offline mutation discarded: auth identity changed before replay");n.code="OFFLINE_IDENTITY_CHANGED",i.reject(n),this.emitItemSettled(i,"rejected",n)}this.offlineQueue.requeue(s),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,r){for(let s of this.connections.values())s.identity===e&&(s.identity=r)}restampQueuedIdentity(e,r){for(let[s,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(s,r);this.offlineQueue.restampIdentity(e,r)}restampWatermarks(e,r){let s=e??"",i=this.clientWatermarks.get(s);if(i===void 0)return;this.clientWatermarks.delete(s);let n=r??"",a=this.clientWatermarks.get(n);if(a===void 0)this.clientWatermarks.set(n,i);else for(let[c,u]of i)a.set(c,u)}clearQueryCacheForIdentityChange(){this.revokeCacheSeededValues(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}flushAllOfflineQueues(){for(let e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){let r=S(e),s=this.offlineFlushes.get(r);if(s===void 0&&this.offlineQueue.size===0)return;let i=(async()=>{await(s??Promise.resolve());try{await this.drainOfflineQueue(e)}catch{}})();this.offlineFlushes.set(r,i),await i,this.offlineFlushes.get(r)===i&&this.offlineFlushes.delete(r)}async drainOfflineQueue(e){let r=this.offlineQueue.drainConflict();for(let h of r){this.unpersist(h.id),this.queuedIdentities.delete(h.id??"");let d=new Error("offline mutation skipped: precondition failed before replay");d.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(h,"rejected",d)}let s=S(e),i=this.offlineQueue.drain(h=>S(h.shardKey)===s);if(i.length===0)return;let n=[],a=[];for(let h of i){let d=this.replayGateVerdict(h);d==="send"?n.push(h):d==="hold"&&a.push(h)}if(this.offlineQueue.requeue(a),a.length>0&&this.subjectAwaitingReconfirm()&&this.getCurrentUser().catch(()=>{}),n.length===0)return;let c=this.encodableOrSettleTerminal(n);if(c.length===0)return;if(c.length===1){await this.replaySequential(c,e),this.scheduleRateLimitedRetry(e);return}let u=[];for(let h=0;h<c.length;h+=ft){let d=c.slice(h,h+ft),l=await this.replayBatched(d,e);if(u.push(...l.requeue),l.stop){u.push(...c.slice(h+ft));break}}u.length>0&&this.offlineQueue.requeue(u),this.scheduleRateLimitedRetry(e)}noteReplayRetryDelay(e,r){let s=S(e),i=this.replayRetryState.get(s),n=(i?.attempts??0)+1,a=As(r,n);this.replayRetryState.set(s,{attempts:n,delayMs:a===void 0?i?.delayMs:Math.max(i?.delayMs??0,a)})}scheduleRateLimitedRetry(e){let r=S(e),s=this.replayRetryState.get(r),i=s?.delayMs;if(s===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(r);return}s.delayMs=void 0;let n=this.replayRetryTimers.get(r);n!==void 0&&clearTimeout(n),this.replayRetryTimers.set(r,setTimeout(()=>{this.replayRetryTimers.delete(r),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){let r=[];for(let s of e)try{z(s.args,`args for '${s.functionPath}'`),r.push(s)}catch(i){this.settleReplayTerminal(s,i instanceof Error?i:new Error(String(i)))}return r}replayGateVerdict(e){let r=this.stampOf(e);if(r===void 0)return this.queuedIdentities.delete(e.id??""),"send";let s=this.replayIdentityVerdict(r);if(s==="unknown")return"hold";if(this.queuedIdentities.delete(e.id??""),s==="match")return"send";this.unpersist(e.id);let i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",e.reject(i),this.emitItemSettled(e,"rejected",i),"reject"}settleReplaySuccess(e,r,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.resolve(r),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,r){let s=e.headers.get("x-lunora-shard-key");if(s===null||r!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;let i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,i)),this.shardCursors.delete(""))}recordShardCursor(e,r){if(typeof r!="number")return;let s=this.cursorKeyFor(e);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,r))}shouldRequeueReplayFailure(e){if(ks(e)){let r=this.hashToken(this.authToken??"");return this.authRefusalNotifiedFor!==r&&(this.authRefusalNotifiedFor=r,this.notifyTokenExpired()),!0}return Ts(e)}settleReplayTerminal(e,r){this.unpersist(e.id),e.reject(r),this.emitItemSettled(e,"rejected",r)}async replaySequential(e,r){for(let s=0;s<e.length;s+=1){let i=e[s];if(i)try{let n,a=await this.rpc(i.functionPath,i.args,i.shardKey,{captureBookmark:!0,clientId:i.clientId??this.clientId,mutationId:i.id,onCommitCursor:o(c=>{n=c},"onCommitCursor")});this.settleReplaySuccess(i,a,n)}catch(n){if(!this.shouldRequeueReplayFailure(n)){this.settleReplayTerminal(i,n);continue}this.noteReplayRetryDelay(r,n),this.offlineQueue.requeue(e.slice(s));return}}}async replayBatched(e,r){if(!this.fetchImpl)return{requeue:e,stop:!0};let s=JSON.stringify({calls:e.map((u,h)=>({args:z(u.args,`args for '${u.functionPath}'`),functionPath:u.functionPath,id:h,clientId:u.clientId??this.clientId,mutationId:u.id,shardKey:u.shardKey}))});if(e.length>1&&Ms(s)>Fs)return await this.replayBatchedHalves(e,r);let i;try{i=await this.fetchImpl(ee(this.url,Sr),{body:s,headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"})}catch{return{requeue:e,stop:!0}}let n=i.headers.get("x-d1-bookmark");if(n&&this.bookmark.set(n),i.status===413&&e.length>1)return await this.replayBatchedHalves(e,r);let a,c=i.headers.get("retry-after");try{a=await i.json()}catch{return this.settleWholeBatchError(e,Ne(i.status,i.statusText,c),r)}if(!a.results){let u=a.error===void 0?Ne(i.status,i.statusText,c):Er(a.error,c);return this.settleWholeBatchError(e,u,r)}return{requeue:this.settleReplayBatchSlots(e,a.results,r),stop:!1}}settleWholeBatchError(e,r,s){if(r instanceof B||r.code!==void 0&&this.shouldRequeueReplayFailure(r))return this.noteReplayRetryDelay(s,r),{requeue:e,stop:!0};for(let i of e)this.settleReplayTerminal(i,r);return{requeue:[],stop:!1}}async replayBatchedHalves(e,r){let s=Math.ceil(e.length/2),i=await this.replayBatched(e.slice(0,s),r);if(i.stop)return{requeue:[...i.requeue,...e.slice(s)],stop:!0};let n=await this.replayBatched(e.slice(s),r);return{requeue:[...i.requeue,...n.requeue],stop:n.stop}}settleReplayBatchSlots(e,r,s){let i=new Map;for(let a of r)typeof a.id=="number"&&a.body!==void 0&&i.set(a.id,a.body);let n=[];for(let[a,c]of e.entries()){let u=i.get(a);if(u===void 0)n.push(c);else if("error"in u){let h=qe(u.error);this.shouldRequeueReplayFailure(h)?(this.noteReplayRetryDelay(s,h),n.push(c)):this.settleReplayTerminal(c,h)}else this.settleReplaySuccess(c,g(u.result),u.commitCursor)}return n}};var Fr=F(Ct(),1),Mr=F(G(),1);var fn=o(()=>{let t=(0,Fr.c)(4),e=rt(),r,s,i;return t[0]!==e?(r=o(n=>e.onConnectionStatus(()=>{n()}),"o"),s=o(()=>e.connectionStatus(),"e"),i=o(()=>e.connectionStatus(),"c"),t[0]=e,t[1]=r,t[2]=s,t[3]=i):(r=t[1],s=t[2],i=t[3]),(0,Mr.useSyncExternalStore)(r,s,i)},"S");export{gt as a,Dr as b,Ye as c,Vr as d,Jr as e,rt as f,fn as g};
|
|
11
|
+
`),n()||e.fail(new p("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"))},"b"),fr=o((t,e,r={})=>{let s=r.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!s)throw new p("INTERNAL","httpStream: no `fetch` implementation available");let i=ps(t,e??{},r.baseUrl??""),n=new AbortController,a;r.signal&&(r.signal.aborted?n.abort():(a=o(()=>{n.abort()},"s"),r.signal.addEventListener("abort",a,{once:!0})));let c=o(()=>{a&&r.signal?.removeEventListener("abort",a)},"d"),{handle:u,iterable:h}=Le({maxBuffer:r.maxBuffer,onCancel:o(()=>{n.abort()},"onCancel")});return(async()=>{try{let d=await s(i,{headers:{accept:"text/event-stream",...r.headers},method:t.method,signal:n.signal});if(!d.ok){await d.body?.cancel().catch(()=>{}),u.fail(new p("HTTP_STREAM_STATUS",`httpStream: request failed (status ${d.status.toString()})`,{status:d.status}));return}if(!d.body){u.fail(new p("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}await ys(d.body,u)}finally{c()}})().catch(d=>{if(n.signal.aborted){u.complete();return}if(d instanceof Error&&"code"in d){u.fail(d);return}u.fail(new p("HTTP_STREAM_TRANSPORT",d instanceof Error?d.message:String(d),{cause:d}))}),h},"_");var bs=/["\\\u0000-\u001F\uD800-\uDFFF]/,pr=o(t=>bs.test(t)?JSON.stringify(t):`"${t}"`,"y"),ct=o(t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key \u2014 pass it as a string, or use stableWireKey");if(typeof t=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(typeof t=="string")return pr(t);if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t)){let a="[";for(let c=0;c<t.length;c++)c>0&&(a+=","),a+=ct(t[c]);return a+"]"}let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype){let a=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${a} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}let r=t,s=Object.keys(r).sort(),i="{",n=!0;for(let a of s){let c=r[a];c!==void 0&&(n?n=!1:i+=",",i+=pr(a),i+=":",i+=ct(c))}return i+"}"},"i"),j=o(t=>ct(O(t)),"u");var P=class t{static{o(this,"r")}static key(e,r,s){return`${e}::${j(r)}::${s??""}`}static keyOf(e){return`${e.fn.__lunoraRef}::${e.argsKey}::${e.shardKey??""}`}byKey=new Map;byId=new Map;get(e){return this.byKey.get(e)}getById(e){return this.byId.get(e)}add(e){this.byKey.set(t.keyOf(e),e),this.byId.set(e.id,e)}remove(e){let r=t.keyOf(e);this.byKey.get(r)===e&&this.byKey.delete(r),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}clear(){this.byKey.clear(),this.byId.clear()}};var Z=o((t,e)=>{let r=t;for(let s of e)try{r=s.transform(r)}catch{}return r},"p"),$=o((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let r of t.callbacks)try{r(e)}catch{}}},"u"),ut=o((t,e)=>{let r;try{r=e(t.lastValue)}catch{return}let s={id:Symbol("optimistic"),transform:e},i=!1;t.optimisticLayers.push(s),$(t,r);let n=o(()=>{let c=t.optimisticLayers.findIndex(u=>u.id===s.id);return c===-1?!1:(t.optimisticLayers.splice(c,1),!0)},"l"),a=o(()=>{$(t,Z(t.serverBase,t.optimisticLayers))},"i");return{confirm:o(c=>{if(c===void 0){n();return}s.commitCursor=c,t.serverCursor!==void 0&&t.serverCursor>=c&&n()&&a()},"confirm"),rollback:o(()=>{i||(i=!0,n(),a())},"rollback")}},"y"),Qe=o((t,e)=>{if(e===void 0||t.optimisticLayers.length===0)return!1;let r=t.optimisticLayers.length;return t.optimisticLayers=t.optimisticLayers.filter(s=>s.commitCursor===void 0||s.commitCursor>e),t.optimisticLayers.length!==r},"h"),mr=o((t,e)=>{let r=[],s=[],i=o((n,a)=>t.get(P.key(n,a,e)),"c");return{confirms:r,rollbacks:s,store:{getAllQueries:o(n=>{let a=[];for(let c of t.all())c.fn.__lunoraRef===n.__lunoraRef&&(c.shardKey??"")===(e??"")&&a.push({args:c.args,value:c.lastValue});return a},"getAllQueries"),getQuery:o((n,a)=>i(n.__lunoraRef,a??{})?.lastValue,"getQuery"),setQuery:o((n,a,c)=>{let u=i(n.__lunoraRef,a??{});if(!u)return;let h=ut(u,()=>c);h&&(r.push(h.confirm),s.push(h.rollback))},"setQuery")}}},"L");var yr=0,vs=o(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();yr+=1;let t=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)}_${yr.toString(36)}_${t}`},"d"),ht=o((t,e)=>t!==void 0&&e!==t,"f"),Ue=vs,H=o((t,e,r,s)=>{if(t)try{t({error:r,mutationId:s,operation:e});return}catch{}console.warn(`[lunora] offline-queue persistence ${e} failed`,r)},"o"),De=class{static{o(this,"m")}queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;version;items=[];constructor(e={},r={}){this.maxItems=e.maxItems??1e3,this.queueBeforeFirstConnect=e.queueBeforeFirstConnect??!1,this.onPersistenceError=e.onPersistenceError,this.persistence=r.persistence,this.onEvict=r.onEvict,this.onSizeChange=r.onSizeChange,this.version=r.version}get size(){return this.items.length}enqueue(e){let r=e;r.id??=Ue(),this.items.push(r),this.persistence?.append({args:r.args,clientId:r.clientId,functionPath:r.functionPath,id:r.id,identity:r.identity,shardKey:r.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(s=>{H(this.onPersistenceError,"append",s,r.id)}),this.evictOverflow(),this.notifySize()}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(a){throw H(this.onPersistenceError,"load",a),a}let r=[],s=new Set(this.items.map(a=>a.id));for(let a of e)if(!s.has(a.id)){if(ht(this.version,a.version)){this.persistence.remove(a.id).catch(c=>{H(this.onPersistenceError,"remove",c,a.id)});continue}s.add(a.id),r.push({args:a.args,clientId:a.clientId,functionPath:a.functionPath,id:a.id,identity:a.identity,reject:o(()=>{},"reject"),resolve:o(()=>{},"resolve"),shardKey:a.shardKey})}this.items.unshift(...r),this.evictOverflow(),this.notifySize();let i=new Set(this.items),n=new Set;for(let a of r)i.has(a)&&n.add(a.shardKey);return[...n]}restampIdentity(e,r){for(let s of this.items){if(s.identity!==e)continue;s.identity=r;let{id:i}=s;if(!this.persistence||i===void 0)continue;let n={args:s.args,clientId:s.clientId,functionPath:s.functionPath,id:i,identity:r,shardKey:s.shardKey,...this.version===void 0?{}:{version:this.version}};this.rewriteStamp(i,n).catch(a=>{H(this.onPersistenceError,"replace",a,i)})}}drain(e){if(!e){let i=[...this.items];return this.items.length=0,this.notifySize(),i}let r=[],s=[];for(let i of this.items)(e(i)?r:s).push(i);return this.items.length=0,this.items.push(...s),this.notifySize(),r}requeue(e){e.length!==0&&(this.items.unshift(...e),this.notifySize())}drainConflict(){let e=[],r=[];for(let s of this.items)if(s.precondition!==void 0&&!s.precondition()){let i=new Error("offline mutation skipped: precondition failed before replay");i.code="OFFLINE_PRECONDITION_FAILED",s.reject(i),e.push(s)}else r.push(s);return e.length>0&&(this.items.length=0,this.items.push(...r),this.notifySize()),e}clear(){for(let e of this.items){let r=new Error("CLIENT_CLOSED");r.code="CLIENT_CLOSED",e.reject(r)}this.items.length=0,this.notifySize()}async rewriteStamp(e,r){let s=this.persistence;if(s)try{await s.replace(r)}catch(i){H(this.onPersistenceError,"replace",i,e)}}evictOverflow(){for(;this.items.length>this.maxItems;){let e=this.items.shift();if(e){e.id&&this.persistence?.remove(e.id).catch(s=>{H(this.onPersistenceError,"remove",s,e.id)});let r=new Error("offline queue overflow");r.code="OFFLINE_QUEUE_OVERFLOW",e.reject(r),this.onEvict?.(e,r)}}}notifySize(){this.onSizeChange?.(this.items.length)}};var gs="lunora-outbox",Ss="offline-mutations",dt="by_id",ws=o((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new p("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let r=t.databaseName??gs,s=t.storeName??Ss,i=Fe(e,r,1,a=>{a.objectStoreNames.contains(s)||a.createObjectStore(s,{autoIncrement:!0}).createIndex(dt,"id",{unique:!0})}),n=Me(i,s);return{append:o(async a=>{await n("readwrite",c=>R(c.add(a)))},"append"),clear:o(async()=>{await n("readwrite",a=>R(a.clear()))},"clear"),load:o(async()=>n("readonly",a=>R(a.getAll())),"load"),remove:o(async a=>{await n("readwrite",async c=>{let u=await R(c.index(dt).getKey(a));u!==void 0&&await R(c.delete(u))})},"remove"),replace:o(async a=>{await n("readwrite",async c=>{let u=await R(c.index(dt).getKey(a.id));u!==void 0&&await R(c.put(a,u))})},"replace")}},"w"),br=o((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return ws()}},"b");var lt=o((t={},e=Math.random)=>{let r=t.initialDelayMs??250,s=t.maxDelayMs??3e4,i=t.jitter??!0,n=0;return{next(){let a=Math.min(s,r*2**n);if(n+=1,!i)return a;let c=a/2;return Math.floor(c+e()*(a-c))},reset(){n=0}}},"s");var vr=o((t,e,r,s)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,r,s),n=i.present?j(i.value):void 0;return()=>{let a=t.peekActiveQuerySnapshot(e.__lunoraRef,r,s);return!i.present||!a.present?!0:j(a.value)===n}},"c");var ft=500,Cs=o(async t=>{let e=[],r;for(;;){let s=await t(r);if(e.push(...Array.isArray(s.records)?s.records:[]),s.truncated!==!0||typeof s.cursor!="string"||s.cursor.length===0)return e;if(s.cursor===r)throw new Error("collectPages: the list did not advance its cursor \u2014 refusing to page forever");r=s.cursor}},"Ce"),gr=o((t,e)=>{if(t.size<e)return;let r=t.keys().next().value;r!==void 0&&t.delete(r)},"G"),te=class{static{o(this,"I")}listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){let[r]=e;for(let s of this.listeners)try{s(r)}catch{}}clear(){this.listeners.clear()}},Ir=new Set(["RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Or=new Set(["TOKEN_EXPIRED","UNAUTHENTICATED","UNAUTHORIZED"]),ks=o(t=>Or.has(t?.code??""),"we"),Ts=o(t=>{if(t instanceof B)return!0;let e=t?.code;return e===void 0||Ir.has(e)||Or.has(e)},"Ee"),Rr=6e4,Es=1e3,Pr=o(t=>{if(t===null)return;let e=Number(t);if(Number.isFinite(e))return e>0?e*1e3:void 0;let r=Date.parse(t);if(Number.isNaN(r))return;let s=r-Date.now();return s>0?s:void 0},"re"),Is={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},Ne=o((t,e,r)=>{let s=Pr(r),i=s===void 0?void 0:{retryAfterMs:s},n=`LunoraClient: response carried no error envelope (status ${t.toString()}${e?` ${e}`:""})`;return t<400||t>=500||t===408?new B(n,i):new p(Is[t]??"BAD_REQUEST",n,{data:i})},"M"),Os=o((t,e)=>{let r=Pr(e);if(!(r===void 0||ot(t)!==void 0))return t.data===void 0?{retryAfterMs:r}:typeof t.data=="object"&&t.data!==null&&!Array.isArray(t.data)?{...t.data,retryAfterMs:r}:void 0},"Ie"),Rs=o((t,e=Math.random)=>{let r=Math.min(Es*2**Math.max(t-1,0),Rr);return Math.round(r*(.5+e()*.5))},"Oe"),Ps=o(t=>t instanceof B||Ir.has(t?.code??""),"Re"),As=o((t,e,r)=>{let s=ot(t);return s!==void 0&&s>0?Math.min(s,Rr):Ps(t)?Rs(e,r):void 0},"Pe"),Fs=983040,Ms=o(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"Fe"),xs="/_lunora/rpc",Sr="/_lunora/rpc-batch",_s="/_lunora/ws",pt=o(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"N"),fe=o(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"O"),wr=Symbol("lunora.unmergeableDelta"),Ls=o((t,e)=>{for(let r of e)r.op==="delete"?t.delete(r.key):r.value!==void 0&&t.set(r.key,r.value)},"Ue"),Qs="lunora-ping",Ds=3e4,Us=1e4,Ns=250,qs=5e3,Ks=64,Bs=8,js="/_lunora/admin/shard-traffic",$s="/_lunora/admin/scheduled",Hs="/_lunora/admin/scheduled/status",zs="/_lunora/admin/scheduled/ws",Ws="/_lunora/admin/scheduled/cancel",Cr="/_lunora/admin/scheduled/dead",Vs="/_lunora/admin/scheduled/dead/retry",Gs="/_lunora/admin/scheduled/dead/cancel",Js="/_lunora/admin/workflows/instances",Xs="/_lunora/admin/workflows/instance",Ys="/_lunora/admin/workflows/status",mt="/_lunora/admin/storage",Zs="/_lunora/admin/storage/url",ei="/_lunora/admin/storage/buckets",ti="/_lunora/admin/functions",ri="/_lunora/admin/cron-jobs",si="/_lunora/admin/cron-jobs/run",ii="/_lunora/admin/openapi",ni="/_lunora/admin/openrpc",ai="/_lunora/admin/global/tables",oi="/_lunora/admin/global/table",ci="/_lunora/admin/global/facet",ui="/_lunora/admin/vector/indexes",hi="/_lunora/admin/vector/query",di="/_lunora/admin/logs/archive",li="/_lunora/admin/kv/namespaces",fi="/_lunora/admin/kv/keys",yt="/_lunora/admin/kv/value",pi="/_lunora/admin/auth/users",mi="/_lunora/admin/auth/sessions",yi="/_lunora/admin/auth/users/create",bi="/_lunora/admin/auth/users/role",vi="/_lunora/admin/auth/users/ban",gi="/_lunora/admin/auth/users/unban",Si="/_lunora/admin/auth/users/password",wi="/_lunora/admin/auth/users/remove",Ci="/_lunora/admin/auth/users/impersonate",ki="/_lunora/admin/auth/sessions/revoke",Ti="/_lunora/admin/auth/sessions/revoke-all",Ei="/_lunora/admin/auth/capabilities",Ii="/_lunora/admin/auth/users/update",Oi="/_lunora/admin/auth/accounts",Ri="/_lunora/admin/auth/accounts/unlink",Pi="/_lunora/admin/auth/passkeys",Ai="/_lunora/admin/auth/passkeys/delete",Fi="/_lunora/admin/auth/two-factor/disable",Mi="/_lunora/admin/auth/organizations",xi="/_lunora/admin/auth/organizations/members",_i="/_lunora/admin/auth/organizations/invitations",Li="/_lunora/admin/auth/organizations/members/remove",Qi="/_lunora/admin/auth/organizations/invitations/cancel",Di="/_lunora/admin/auth/config",Ui="/_lunora/admin/auth/sign-up-invitations",Ni="/_lunora/admin/auth/sign-up-invitations/create",qi="/_lunora/admin/auth/sign-up-invitations/revoke",Ki="/_lunora/admin/auth/organizations/create",Bi="/_lunora/admin/auth/organizations/update",ji="/_lunora/admin/auth/organizations/remove",$i="/_lunora/admin/auth/organizations/members/add",Hi="/_lunora/admin/auth/organizations/members/invite",zi="/_lunora/admin/auth/organizations/members/role",Wi="/_lunora/admin/auth/organizations/teams",Vi="/_lunora/admin/auth/organizations/teams/create",Gi="/_lunora/admin/auth/organizations/teams/update",Ji="/_lunora/admin/auth/organizations/teams/remove",Xi="/_lunora/admin/auth/organizations/teams/members",Yi="/_lunora/admin/auth/organizations/teams/members/add",Zi="/_lunora/admin/auth/organizations/teams/members/remove",en="/_lunora/admin/auth/organizations/roles",tn="/_lunora/admin/auth/organizations/roles/create",rn="/_lunora/admin/auth/organizations/roles/update",sn="/_lunora/admin/auth/organizations/roles/remove",nn="/api/auth",an="/get-session",kr=o(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"Y"),ee=o((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"C"),I=o((t,e)=>{let r=new URLSearchParams;for(let[i,n]of Object.entries(e))n!==void 0&&n!==""&&r.set(i,String(n));let s=r.toString();return s===""?t:`${t}?${s}`},"y"),on=[cr],S=o(t=>t??"","l"),Ar=o((t,e)=>{let r=t.error,s=typeof r?.code=="string"?r.code:void 0,i=typeof r?.message=="string"?r.message:void 0;return{code:s,messageText:(typeof t.message=="string"?t.message:void 0)??i??e}},"ie"),cn=o(t=>{let{code:e,messageText:r}=Ar(t,"stream error");return e===void 0?new Error(r):new p(e,r)},"cs"),Tr=o(t=>{let{code:e,messageText:r}=Ar(t,"subscription error");return{message:r,...e===void 0?{}:{code:e}}},"J");function bt(t){if(t!==void 0)return e=>{t(e)}}o(bt,"B");var pe=o((t,e)=>{for(let r of t)try{r(e)}catch{}},"R"),un=new TextDecoder,hn=o(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return un.decode(t)},"ds"),M=o((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"b"),qe=o(t=>{let e=new Error(t.message??"request failed");return e.code=t.code,t.data!==void 0&&(e.data=g(t.data)),t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),e},"F"),Er=o((t,e)=>{let r=qe(t),s=Os(r,e);return s!==void 0&&(r.data=s),r},"X"),z=o((t,e)=>{try{return O(t)}catch(r){let s=r instanceof Error?r.message:String(r);throw new TypeError(`LunoraClient: cannot encode ${e} \u2014 ${s}`,r instanceof Error?{cause:r}:void 0)}},"k"),vt=o(t=>"args"in t?{...t,args:g(t.args)}:t,"Q"),dn=o((t,e)=>{let r=Array.from({length:e});for(let s of t){if(typeof s.id!="number"||s.id<0||s.id>=e)continue;let i=s.body;r[s.id]=i&&"error"in i&&i.error?{error:qe(i.error),ok:!1}:{ok:!0,value:g(i?.result)}}return r.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},"us"),ln=Promise.resolve(),gt=class t{static{o(this,"ne")}static MAX_POKE_BUFFERS=256;static createClientQuery(e,r){return{defaultValue:r,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;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new P;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;subjectToken=null;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new te;statusListeners=new te;tokenExpiredListeners=new te;authRefusalNotifiedFor;mutationSettledListeners=new te;pendingChangeListeners=new te;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??ee(kr(e.url),_s),this.wsToken=e.wsToken;let r=e.authBasePath??nn;this.authBasePath=r.endsWith("/")?r.slice(0,-1):r,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??ar(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??Ds,this.connectTimeoutMs=e.connectTimeoutMs??Us,this.defaultConnectionContext=e.connectionContext,this.persistence=br(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=nr(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new xe,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=ln),this.offlineQueue=new De(e.offlineQueue,{onEvict:o((s,i)=>{this.emitItemSettled(s,"rejected",i)},"onEvict"),onSizeChange:o(s=>{this.pendingChangeListeners.emit(s)},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${Ue()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})})}setAuthToken(e,r){let s=this.authToken!==e,i=this.identityFingerprint(),n=this.authSubject===void 0||this.subjectToken===this.authToken,a=this.subjectAwaitingReconfirm();this.authToken=e,r!==void 0?(this.authSubject=r,this.subjectToken=e):e===null&&(this.authSubject=void 0,this.subjectToken=null);let c=this.identityFingerprint();if(c!==i&&(!s&&n?(this.restampQueuedIdentity(i,c),this.restampWatermarks(i,c),this.restampConnectionIdentity(i,c),this.reseedFromHydratedCache()):this.rejectQueuedForIdentityChange(i),this.tabCoordinator)){let u=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),u&&this.tabCoordinator.promoteImmediately()}this.syncReadCacheToCredential(a),s&&this.authTokenListeners.emit(e),this.offlineQueue.size>0&&this.computeStatus()==="connected"&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}replayIdentityVerdict(e){if(this.subjectAwaitingReconfirm())return"unknown";let r=this.identityFingerprint();return e===r||e!==void 0&&this.isSameCredentialUnderTokenHash(e)?"match":r===null?"unknown":"mismatch"}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,r,s){let i=s?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new p("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let n=s?.shardKey??"",a=this.identityFingerprint(),c,u=await this.rpc(e,r,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:o(h=>{c=h},"onMutationAck")});if(c!==void 0&&c>(this.clientWatermarks.get(a??"")?.get(n)??0)){let h=this.clientWatermarks.get(a??"");h===void 0&&(gr(this.clientWatermarks,Bs),h=new Map,this.clientWatermarks.set(a??"",h)),h.set(n,c)}return{applied:c===void 0||c===i,result:u}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}async getCurrentUser(){if(this.closed||!this.fetchImpl)return null;let e={},r=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`);let s=await this.fetchImpl(ee(this.url,`${this.authBasePath}${an}`),{credentials:"include",headers:e,method:"GET"});if(!s.ok)return null;let i=(await s.json())?.user??null;return this.adoptResolvedSubject(r,i),i}setWsToken(e){if(this.wsToken!==e){this.wsToken=e;for(let r of this.connections.values())if(r.socket)try{r.socket.close()}catch{}}}setConnectionContext(e,r={}){this.assertLeaderOwnedSurface("setConnectionContext");let s=S(r.shardKey);e===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,e),this.refreshConnectionContext(s)}acquireConnectionContext(e,r={}){if(this.followsAnotherTab())return()=>{};let s=S(r.shardKey),i={context:e},n=this.connectionContextHolders.get(s);n?n.push(i):this.connectionContextHolders.set(s,[i]),this.refreshConnectionContext(s);let a=!1;return()=>{if(a)return;a=!0;let c=this.connectionContextHolders.get(s);if(!c)return;let u=c.indexOf(i);u!==-1&&c.splice(u,1),c.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s)}}whisperSubscribe(e,r,s={}){this.assertLeaderOwnedSurface("whisperSubscribe");let i=S(s.shardKey),n=this.whisperHandlers.get(i);n||(n=new Map,this.whisperHandlers.set(i,n));let a=n.get(e),c=a===void 0;if(a||(a=new Set,n.set(e,a)),a.add(r),this.ensureSocket(s.shardKey),c){let u=this.getConnection(s.shardKey);u&&M(u,{topic:e,type:"whisper_subscribe"})}return()=>{let u=this.whisperHandlers.get(i),h=u?.get(e);if(!h?.delete(r)||h.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let d=this.getConnection(s.shardKey);d&&M(d,{topic:e,type:"whisper_unsubscribe"})}}whisper(e,r,s={}){this.assertLeaderOwnedSurface("whisper"),this.ensureSocket(s.shardKey);let i=this.getConnection(s.shardKey);i&&M(i,{data:z(r??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"})}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let r=this.statusListeners.add(e);return e(this.computeStatus()),r}pendingCount(){return this.offlineQueue.size}debug(){let e=[],r=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...r?.keys()??[]]);for(let n of s){let a=this.connections.get(n);e.push({confirmedMutationWatermark:r?.get(n)??0,hasSocket:a?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:a?.wasEverConnected??!1,wsState:a?.wsState??"idle"})}let i=this.subscriptions.all().map(n=>({acked:n.acked,functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(let n of this.shapeSubscriptions.values())i.push({acked:n.serverCursor!==void 0,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,a)=>(n.shardKey??"").localeCompare(a.shardKey??"")),subscriptions:i.toSorted((n,a)=>n.functionPath.localeCompare(a.functionPath))}}onPendingChange(e){let r=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),r}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,r){this.clientQueryStore.set(e,r)}subscribeClientQuery(e,r){return this.clientQueryStore.subscribe(e,r)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,r,s){return vr(this,e,r,s)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,r,s){if(!this.readyResolved)return;let i=j(r),n=Y(e,i,s),a=this.hydratedQueryCache.get(n);if(a!==void 0)return this.cachedQueryMatchesIdentity(a)?a.value:void 0}peekActiveQuerySnapshot(e,r,s){let i=P.key(e,r,s),n=this.subscriptions.get(i);return{present:n!==void 0,value:n?.lastValue}}async query(e,r,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,r,s.shardKey,{attachBookmark:!0})}async batch(e){if(this.assertOpen(),!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(ee(this.url,Sr),{body:JSON.stringify({calls:e.map((n,a)=>({args:z(n.args??{},`args for batch call '${n.fn.__lunoraRef}'`),functionPath:n.fn.__lunoraRef,id:a,shardKey:n.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"}),s=r.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let i;try{i=await r.json()}catch{throw new p("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`)}if(!r.ok||i.error&&!i.results)throw i.error?qe(i.error):new p("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`);for(let n of i.results??[]){let a=n.body?.commitCursor;typeof n.id=="number"&&typeof a=="number"&&this.recordShardCursor(e[n.id]?.shardKey,a)}return dn(i.results??[],e.length)}async mutation(e,r,s={}){this.assertOpen();let i=r,n=s.mutationId??Ue(),{confirms:a,rollbacks:c}=this.applyOptimisticUpdates(e.__lunoraRef,i,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,r,s.shardKey,c,a);let u=this.offlineFlushes.get(S(s.shardKey));u!==void 0&&await u;let{hasSocket:h,wasEverConnected:d,wsState:l}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:f}=this.offlineQueue,y=d||f,m=this.WebSocketImpl!==void 0&&y;if(l!=="open"&&!h&&m||l==="connecting"&&y)return this.enqueueOfflineMutation(e,i,s.shardKey,n,c,a,s.precondition);try{let b,C=await this.rpc(e.__lunoraRef,i,s.shardKey,{captureBookmark:!0,mutationId:n,onCommitCursor:o(k=>{b=k},"onCommitCursor")});for(let k of a)k(b);return C}catch(b){throw fe(c),b}}async action(e,r,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,r,s.shardKey,{attachBookmark:!0,captureBookmark:!0})}async importRows(e,r,s={}){this.assertOpen();let i=Math.max(1,Math.trunc(s.chunkSize??500)),n=s.toArgs??(h=>({rows:h})),a=r.length,c=0,u=0;for(let h=0;h<a;h+=i){let d=r.slice(h,h+i),l=u;await this.mutation(e,n(d),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(l)}`},shardKey:s.shardKey}),u+=1,c+=d.length,s.onProgress?.({done:c,total:a})}return{chunks:u,imported:c}}async shardTraffic(e){this.assertOpen();let r=await this.adminFetch(js,"POST",{table:e});return{failed:r.failed??0,ok:r.ok??0,shards:r.shards??[]}}async listScheduledJobs(){return this.assertOpen(),((await this.adminFetch($s,"GET")).records??[]).map(e=>vt(e))}async schedulerStatus(){this.assertOpen();let e=await this.adminFetch(Hs,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}}async cancelScheduledJob(e){return this.assertOpen(),{cancelled:(await this.adminFetch(Ws,"POST",{id:e})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await Cs(async e=>await this.adminFetch(e===void 0?Cr:`${Cr}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>vt(e))}async retryDeadJob(e){return this.assertOpen(),{retried:(await this.adminFetch(Vs,"POST",{id:e})).retried===!0}}async removeDeadJob(e){return this.assertOpen(),{removed:(await this.adminFetch(Gs,"POST",{id:e})).removed===!0}}async listWorkflowInstances(e){this.assertOpen();let r=new URLSearchParams({name:e.name});e.status!==void 0&&r.set("status",e.status),e.page!==void 0&&r.set("page",String(e.page)),e.perPage!==void 0&&r.set("perPage",String(e.perPage));let s=await this.adminFetch(`${Js}?${r.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();let r=new URLSearchParams({id:e.id,name:e.name}),s=await this.adminFetch(`${Xs}?${r.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(Ys,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let r=ee(kr(this.url),zs),s=lt(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},n,a=!1,c=o(()=>{a||this.closed||(n=setTimeout(d,s.next()))},"a"),u=o(f=>{if(a||this.WebSocketImpl===void 0)return;let y=f===void 0?r:`${r}?token=${encodeURIComponent(f)}`;this.openManagedSocket(i,y,this.connectTimeoutMs,{onClose:o(()=>{c()},"onClose"),onMessage:o(m=>{let b;try{b=JSON.parse(typeof m.data=="string"?m.data:"")}catch{return}b.type==="jobs"&&Array.isArray(b.records)&&(s.reset(),e(b.records.map(C=>vt(C))))},"onMessage")})},"c"),h=o(async f=>{let y;try{y=await f()}catch{c();return}u(y)},"h"),d=o(()=>{if(a||this.WebSocketImpl===void 0)return;let{wsToken:f}=this;if(typeof f=="function"){h(f).catch(()=>{});return}u(f)},"d");d();let l=o(()=>{a=!0,n!==void 0&&(clearTimeout(n),n=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),this.stopHeartbeat(i),i.socket?.close(),i.socket=void 0},"u");return this.adminSocketTeardowns.add(l),()=>{this.adminSocketTeardowns.delete(l),l()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(ti,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(ri,"GET")).jobs??[]}async runCronJob(e){this.assertOpen();let r=await this.adminFetch(si,"POST",{name:e});return{name:r.name??e,ran:r.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(ii,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(ni,"GET")}async listStorageObjects(e={}){this.assertOpen();let r=I(mt,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await this.adminFetch(r,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(e,r){this.assertOpen();let s=`${mt}?key=${encodeURIComponent(e)}${pt(r?.bucket)}`,i=await this.adminFetch(s,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(ei,"GET")).buckets??[]}async uploadStorageObject(e){this.assertOpen();let r=`${mt}?key=${encodeURIComponent(e.key)}${pt(e.bucket)}`,s=await this.adminFetch(r,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}}async signedStorageUrl(e,r){this.assertOpen();let s=r?.expiresInSeconds,i=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,n=`${Zs}?key=${encodeURIComponent(e)}${i}${pt(r?.bucket)}`,a=await this.adminFetch(n,"GET");if(typeof a.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return a.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(ai,"GET")}async readGlobalTablePage(e){this.assertOpen();let r=new URLSearchParams({table:e.table});return e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&r.set("filters",JSON.stringify(O(e.filters))),g(await this.adminFetch(`${oi}?${r.toString()}`,"GET"))}async facetGlobalColumn(e){this.assertOpen();let r=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&r.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&r.set("filters",JSON.stringify(O(e.filters))),g(await this.adminFetch(`${ci}?${r.toString()}`,"GET"))}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch(ui,"GET")).indexes??[]}async queryVectorIndex(e){return this.assertOpen(),(await this.adminFetch(hi,"POST",e)).matches??[]}async queryLogArchive(e={}){this.assertOpen();let r=await this.adminFetch(di,"POST",e);return{nextCursor:r.nextCursor,rows:r.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(li,"GET")).namespaces??[]}async listKvKeys(e){this.assertOpen();let r=I(fi,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await this.adminFetch(r,"GET")}async getKvValue(e){this.assertOpen();let r=I(yt,{key:e.key,namespace:e.namespace});return await this.adminFetch(r,"GET")}async putKvValue(e){this.assertOpen(),await this.adminFetch(yt,"PUT",e)}async deleteKvKey(e){this.assertOpen();let r=I(yt,{key:e.key,namespace:e.namespace});await this.adminFetch(r,"DELETE")}async listAuthUsers(e={}){this.assertOpen();let r=I(pi,{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(r,"GET")}async createAuthUser(e){return await this.adminFetch(yi,"POST",e)}async setAuthUserRole(e){return await this.adminFetch(bi,"POST",e)}async banAuthUser(e){return await this.adminFetch(vi,"POST",e)}async unbanAuthUser(e){return await this.adminFetch(gi,"POST",e)}async setAuthUserPassword(e){await this.adminFetch(Si,"POST",e)}async removeAuthUser(e){await this.adminFetch(wi,"POST",e)}async impersonateAuthUser(e){return await this.adminFetch(Ci,"POST",e)}async revokeAuthSession(e){await this.adminFetch(ki,"POST",e)}async revokeAuthUserSessions(e){await this.adminFetch(Ti,"POST",e)}async getAuthCapabilities(){return await this.adminFetch(Ei,"GET")}async updateAuthUser(e){return await this.adminFetch(Ii,"POST",e)}async listAuthAccounts(e){return await this.adminFetch(I(Oi,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){await this.adminFetch(Ri,"POST",e)}async listAuthPasskeys(e){return await this.adminFetch(I(Pi,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){await this.adminFetch(Ai,"POST",e)}async disableAuthTwoFactor(e){await this.adminFetch(Fi,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(I(Mi,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){let r=I(xi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async listAuthOrgInvitations(e){let r=I(_i,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async listAuthSignUpInvitations(e={}){let r=I(Ui,{limit:e.limit,offset:e.offset});return await this.adminFetch(r,"GET")}async createAuthSignUpInvitation(e){return await this.adminFetch(Ni,"POST",e)}async revokeAuthSignUpInvitation(e){await this.adminFetch(qi,"POST",e)}async removeAuthOrgMember(e){await this.adminFetch(Li,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(Qi,"POST",e)}async getAuthConfig(){return await this.adminFetch(Di,"GET")}async createAuthOrganization(e){return await this.adminFetch(Ki,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(Bi,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(ji,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch($i,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(Hi,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch(zi,"POST",e)}async listAuthOrgTeams(e){let r=I(Wi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(Vi,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch(Gi,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(Ji,"POST",e)}async listAuthOrgTeamMembers(e){let r=I(Xi,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(r,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(Yi,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(Zi,"POST",e)}async listAuthOrgRoles(e){let r=I(en,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async createAuthOrgRole(e){return await this.adminFetch(tn,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(rn,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(sn,"POST",e)}async listAuthSessions(e={}){this.assertOpen();let r=I(mi,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(r,"GET")}subscribe(e,r,s,i={}){this.assertOpen();let n=r??{},a=P.key(e.__lunoraRef,n,i.shardKey),c=this.subscriptions.get(a),u=bt(s),h=bt(i.onError),d=bt(i.onCheckpoint);if(!c){this.nextSubId+=1;let f=`sub_${this.nextSubId.toString()}`,y=j(n),m=this.takeHydratedCache(e.__lunoraRef,y,i.shardKey);c={acked:!1,args:n,argsKey:y,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:f,lastValue:m?.value,optimisticLayers:[],serverBase:m?.value,serverCursor:m?.serverCursor,shardKey:i.shardKey,wireArgs:z(n,`args for '${e.__lunoraRef}'`),...m?.serverEpoch===void 0?{}:{serverEpoch:m.serverEpoch}},this.subscriptions.add(c),m!==void 0&&this.cacheSeededQueries.set(a,m)}if(c.callbacks.add(u),h&&c.errorCallbacks.add(h),d&&c.checkpointCallbacks.add(d),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let l=c;return()=>{l.callbacks.delete(u),h&&l.errorCallbacks.delete(h),d&&l.checkpointCallbacks.delete(d),l.callbacks.size===0&&(this.sendOrQueueUnsubscribe(l.shardKey,l.id,"unsubscribe"),this.returnCacheSeed(P.keyOf(l)),this.subscriptions.remove(l))}}subscribeShape(e,r,s={}){if(this.assertOpen(),this.followsAnotherTab()){let{onError:a}=s;return a!==void 0&&queueMicrotask(()=>{a({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;let i=`shape_${this.nextShapeId.toString()}`,n={args:e.args,callbacks:new Set([r]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:i,name:e.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:e.args===void 0?void 0:z(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,n),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(n.shardKey,i,"shape_unsubscribe")}}stream(e,r,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new p("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;let i=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=s,a=r??{},{handle:c,iterable:u}=Le({maxBuffer:s.maxBuffer,onCancel:o(()=>{this.cancelStream(i,n)},"onCancel")});this.ensureSocket(n);let h=this.getConnection(n),d={id:i,query:{args:z(a,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"},l={durable:s.durable===!0,generation:void 0,handle:c,lastSeq:0,message:d,shardKey:n,started:!1};this.streams.set(i,l);let f=h?.wsState==="open"&&M(h,d);if(l.started=f,!f&&h===void 0)return this.streams.delete(i),c.fail(new p("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),u;if(!f){for(h.pendingStreams=h.pendingStreams??[];h.pendingStreams.length>=Ks;){let y=h.pendingStreams.shift()?.id,m=y?this.streams.get(y):void 0;m&&(m.handle.fail(new p("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(y))}h.pendingStreams.push(d)}return u}httpStream(e,r,s={}){if(this.closed)throw new p("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return fr(e,r,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(let e of this.streams.values())e.handle.fail(new p("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(let e of this.connections.values())this.teardownConnection(e);for(let e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear();for(let e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new p("INTERNAL","LunoraClient is closed")}followsAnotherTab(){let e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;let r=e.leaderTabId;return r!==void 0&&r!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new p("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){let r=S(e.shardKey);for(let[s,i]of this.streams)S(i.shardKey)===r&&(i.handle.fail(new p("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(){let e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new _e({channelName:e,onBecomeLeader:o(()=>{for(let r of this.subscriptions.all())this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(r);for(let r of this.queuedOfflineShardKeys)this.ensureSocket(r);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},"onBecomeLeader"),onStopBeingLeader:o(()=>{for(let[r,s]of this.connections)this.teardownConnection(s),this.connections.delete(r);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},"onStopBeingLeader"),onConnectionStatus:o((r,s)=>{if(s!==void 0&&s!==this.identityFingerprint())return;let i=r==="connected"&&this.leaderStatus!=="connected";this.leaderStatus=r,r==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),i&&this.flushAllOfflineQueues()},"onConnectionStatus"),onSubscriptionData:o((r,s,i,n,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;let c=this.subscriptions.get(r);c&&(c.serverBase=s,this.dropCacheSeed(r),i!==void 0&&(c.serverCursor=i,n!==void 0&&(c.serverEpoch=n),Qe(c,i)),$(c,Z(s,c.optimisticLayers)))},"onSubscriptionData"),onLeaderClaimAnswered:o(()=>{this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},"onLeaderClaimAnswered"),onSubscriptionError:o((r,s,i)=>{if(i!==void 0&&i!==this.identityFingerprint())return;let n=this.subscriptions.get(r);n&&pe(n.errorCallbacks,s)},"onSubscriptionError"),onSubscriptionSettled:o((r,s,i,n,a,c)=>{if(c!==void 0&&c!==this.identityFingerprint())return;let u=this.subscriptions.get(r);if(u){this.ackAndAdvanceCursor(u,s,i),n!==void 0&&a===this.clientId&&(u.lastMutationId=Math.max(u.lastMutationId??0,n));for(let h of u.checkpointCallbacks)h({checkpoint:u.serverCursor,mutationId:u.lastMutationId})}},"onSubscriptionSettled")})}async enqueueOfflineMutation(e,r,s,i,n,a,c){let u=this.identityFingerprint();if(this.outbox){this.outboxMutationCounter+=1;let h=this.outboxMutationCounter;try{await this.outbox.enqueue({args:r,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:`${this.clientId}:${String(h)}`,identity:u,mutationId:h,...n.length>0&&{onRejected:o(()=>{fe(n)},"onRejected")},shardKey:s})}catch(d){throw fe(n),d instanceof Error?d:new Error(String(d))}for(let d of a)d(void 0);return}return new Promise((h,d)=>{let l={args:r,functionPath:e.__lunoraRef,liveAwaiter:!0,id:i,clientId:this.clientId,identity:u,precondition:c,onCommit:o(f=>{for(let y of a)y(f)},"onCommit"),reject:o(f=>{this.queuedIdentities.delete(i),fe(n),d(f instanceof Error?f:new Error(String(f)))},"reject"),resolve:h,shardKey:s};this.offlineQueue.enqueue(l),this.queuedOfflineShardKeys.add(s),l.id!==void 0&&this.queuedIdentities.set(l.id,u)})}async hydratePersistedQueue(){try{let e=await this.offlineQueue.hydrate();for(let r of e)this.queuedOfflineShardKeys.add(r),this.ensureSocket(r)}catch{}}hydrateAsOutboxLeader(){let e=o(()=>{this.hydratePersistedQueue().catch(()=>{})},"e"),r=globalThis.navigator?.locks;if(!r){e();return}r.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{let e=await this.queryCache.load(),r=new Map;for(let s of this.subscriptions.all())r.set(Y(s.fn.__lunoraRef,s.argsKey,s.shardKey),s);for(let{key:s,...i}of e){if(ht(this.persistenceVersion,i.version)){this.queryCache.remove(s).catch(()=>{});continue}let n=r.get(s);if(n&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(n,i);continue}this.hydratedQueryCache.set(s,i)}}catch{}}seedSubscriptionFromCache(e,r){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(r)||(e.serverBase=r.value,e.serverCursor=r.serverCursor,r.serverEpoch!==void 0&&(e.serverEpoch=r.serverEpoch),this.cacheSeededQueries.set(Y(e.fn.__lunoraRef,e.argsKey,e.shardKey),r),$(e,Z(r.value,e.optimisticLayers)))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}returnCacheSeed(e){let r=this.cacheSeededQueries.get(e);r!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,r))}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(let[e,r]of this.cacheSeededQueries){let s=this.subscriptions.get(e);s!==void 0&&(s.serverBase=void 0,s.serverCursor=void 0,s.serverEpoch=void 0,$(s,Z(void 0,s.optimisticLayers))),this.hydratedQueryCache.set(e,r)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,r,s){let i=Y(e,r,s),n=this.hydratedQueryCache.get(i);if(!(n===void 0||!this.cachedQueryMatchesIdentity(n)))return this.hydratedQueryCache.delete(i),n}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(let e of this.subscriptions.all()){let r=Y(e.fn.__lunoraRef,e.argsKey,e.shardKey),s=this.hydratedQueryCache.get(r);s!==void 0&&this.cachedQueryMatchesIdentity(s)&&(this.hydratedQueryCache.delete(r),this.seedSubscriptionFromCache(e,s))}}persistQueryValue(e){let r=e.serverBase;if(!this.queryCache||r===void 0)return;let s=Y(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,n=i===void 0?this.identityFingerprint():i;this.pendingCacheWrites.set(s,{identity:n,serverCursor:e.serverCursor,ts:Date.now(),value:r,...n===this.identityFingerprint()&&!this.subjectAwaitingReconfirm()?this.credentialStamp():{},...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},Ns)}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;let{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}let r=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(r.map(async([s,i])=>e.put(s,i)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";let e=[...this.connections.values()];return e.length===0?"idle":e.some(r=>r.wsState==="open")?"connected":e.some(r=>r.wsState==="connecting")?"connecting":"offline"}emitConnectionStatus(){let e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,r,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:r})}applyOptimisticUpdates(e,r,s,i){let n=[],a=[];if(!i)return{confirms:n,rollbacks:a};let c=P.key(e,r,s),u=this.subscriptions.get(c);if(u){let h=ut(u,i);h&&(n.push(h.confirm),a.push(h.rollback))}return{confirms:n,rollbacks:a}}applyOptimisticUpdate(e,r,s,i,n){let{confirms:a,rollbacks:c,store:u}=mr(this.subscriptions,s);try{e(u,r)}catch{fe(c);return}i.push(...c),n.push(...a)}getConnection(e){return this.connections.get(S(e))}sendOrQueueUnsubscribe(e,r,s){let i=this.getConnection(e);i&&!M(i,{id:r,type:s})&&i.pendingUnsubscribes.push({id:r,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}}let r=this.getConnection(e);return{hasSocket:r?.socket!==void 0,wasEverConnected:r?.wasEverConnected??!1,wsState:r?.wsState??"idle"}}getOrCreateConnection(e){let r=S(e),s=this.connections.get(r);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],reconnect:lt(this.reconnectOptions),reconnectTimer:void 0,shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:!1,wsState:"idle"},this.connections.set(r,s)),s}wsUrlFor(e,r){let s=[];if(e!==void 0&&s.push(`shard=${encodeURIComponent(e)}`),r!==void 0&&s.push(`token=${encodeURIComponent(r)}`),s.length===0)return this.wsUrl;let i=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${i}${s.join("&")}`}rpcRequestHeaders(e,r){let s={"content-type":"application/json"},i=this.shardCursors.get(this.cursorKeyFor(r));if(i!==void 0&&(s["x-lunora-min-seq"]=i.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){let n=this.bookmark.get();n&&(s["x-d1-bookmark"]=n)}return s}async rpc(e,r,s,i={}){if(!this.fetchImpl)throw new B("LunoraClient: no `fetch` implementation available");let n=this.rpcRequestHeaders(i,s),a=await this.fetchImpl(ee(this.url,xs),{body:JSON.stringify({args:z(r,`args for '${e}'`),functionPath:e,shardKey:s}),headers:n,method:"POST"});if(i.captureBookmark){let u=a.headers.get("x-d1-bookmark");u&&this.bookmark.set(u)}let c;try{c=await a.json()}catch{throw Ne(a.status,a.statusText,a.headers.get("retry-after"))}if("error"in c)throw Er(c.error,a.headers.get("retry-after"));if(!a.ok)throw Ne(a.status,a.statusText,a.headers.get("retry-after"));return i.onMutationAck?.(c.lastMutationId),i.onCommitCursor?.(c.commitCursor),this.learnDefaultShardKey(a,s),this.recordShardCursor(s,c.commitCursor),g(c.result)}async adminFetch(e,r,s,i){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");let n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);let a=s instanceof ArrayBuffer||s instanceof Blob,c;s===void 0?c=void 0:a?(c=s,i!==void 0&&(n["content-type"]=i)):(c=JSON.stringify(s),n["content-type"]="application/json");let u=await this.fetchImpl(ee(this.url,e),{body:c,headers:n,method:r}),h;try{h=await u.json()}catch{let d=u.statusText?` ${u.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${d})`)}if(typeof h=="object"&&h!==null&&"error"in h){let d=h.error,l=new Error(d.message??"admin request failed");throw l.code=d.code,l}if(!u.ok){let d=u.statusText?` ${u.statusText}`:"";throw new p("INTERNAL",`LunoraClient: admin request failed (status ${u.status.toString()}${d})`)}return h}effectiveConnectionContext(e){let r=this.connectionContextHolders.get(e);return r&&r.length>0?r[r.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){let r=this.connections.get(e);r?.wsState==="open"&&this.sendConnectEnvelope(r)}sendConnectEnvelope(e){let r=this.effectiveConnectionContext(S(e.shardKey));M(e,{caps:on,clientId:this.clientId,id:"connect",type:"connect",...r===void 0?{}:{context:r}})}resendShapeSubscriptions(e){for(let r of this.shapeSubscriptions.values())S(r.shardKey)===S(e)&&this.sendShapeSubscribeIfOpen(r)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;let r=this.getOrCreateConnection(e);if(!(r.wsState==="open"||r.wsState==="connecting")){if(r.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(r,e,this.wsToken).catch(()=>{});return}this.openSocket(r,e,this.wsToken)}}async openSocketWithProvidedToken(e,r,s){let i;try{i=await s()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,r,i)}openManagedSocket(e,r,s,i){let{WebSocketImpl:n}=this;if(n===void 0)throw new p("INTERNAL","no WebSocket implementation available");let a=new n(r);e.socket=a;let c=o(()=>{this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket===a&&(e.socket=void 0)},"a"),u=o(h=>{c(),i.onClose(h)},"c");s>0&&(e.connectTimer=setTimeout(()=>{if(e.connectTimer=void 0,e.socket===a){try{a.close()}catch{}u()}},s)),a.addEventListener("open",()=>{if(e.socket===a){e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.lastFrameAt=Date.now();try{i.onOpen?.()}catch(h){console.error("[lunora] connection open handler threw",h)}this.startHeartbeat(e,u)}}),a.addEventListener("message",h=>{if(e.socket===a){e.lastFrameAt=Date.now();try{i.onMessage(h)}catch(d){console.error("[lunora] server frame handler threw",d)}}}),a.addEventListener("close",h=>{e.socket===a&&u(h)}),a.addEventListener("error",()=>{e.socket===a&&u()})}openSocket(e,r,s){this.WebSocketImpl!==void 0&&(e.identity=this.identityFingerprint(),this.openManagedSocket(e,this.wsUrlFor(r,s),this.connectTimeoutMs,{onClose:o(i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},"onClose"),onMessage:o(i=>{this.handleServerMessage(i.data,r)},"onMessage"),onOpen:o(()=>{e.wsState="open",e.wasEverConnected=!0,clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},qs),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(r);for(let n of this.subscriptions.all())S(n.shardKey)===S(r)&&this.sendSubscribeIfOpen(n);if(this.resendShapeSubscriptions(r),e.pendingUnsubscribes.length>0){let n=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:a,type:c}of n)M(e,{id:a,type:c})}this.flushPendingStreams(e);let i=this.whisperHandlers.get(S(r));if(i)for(let n of i.keys())M(e,{topic:n,type:"whisper_subscribe"});this.flushOfflineQueue(r).catch(()=>{})},"onOpen")}))}flushPendingStreams(e){if(!e.pendingStreams||e.pendingStreams.length===0)return;let r=e.pendingStreams;e.pendingStreams=[];for(let s of r){let i=M(e,s)?this.streams.get(String(s.id)):void 0;i&&(i.started=!0)}}cancelStream(e,r){let s=this.getConnection(r),i=this.streams.get(e);s&&(s.pendingStreams=s.pendingStreams?.filter(n=>n.id!==e),!M(s,{id:e,type:"unsubscribe"})&&i?.durable===!0&&i.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);let r=new Set((e.pendingStreams??[]).map(i=>i.id));for(let[i,n]of this.streams)if(!(S(n.shardKey)!==S(e.shardKey)||r.has(i))){if(n.durable){let a={...n.message,...n.generation===void 0?{}:{generation:n.generation},sinceChunk:n.lastSeq};n.message=a,e.pendingStreams=[...(e.pendingStreams??[]).filter(c=>c.id!==i),a];continue}n.handle.fail(new p("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.streams.delete(i)}if(this.WebSocketImpl===void 0)return;let s=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},s)}startHeartbeat(e,r){this.stopHeartbeat(e),!(this.heartbeatIntervalMs<=0)&&(e.heartbeatTimer=setInterval(()=>{if(!e.socket)return;let{socket:s}=e;if(Date.now()-e.lastFrameAt>this.heartbeatIntervalMs*2.5){try{s.close()}catch{}r();return}try{s.send(Qs)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(e){e.heartbeatTimer!==void 0&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=void 0)}markShardPendingAck(e){let r=S(e);for(let s of this.subscriptions.all())S(s.shardKey)===r&&(s.acked=!1)}sendSubscribeIfOpen(e){let r=this.getConnection(e.shardKey);if(r?.wsState!=="open"||e.acked)return;let s=e.fn.__lunoraTable??e.fn.__lunoraRef,i=e.serverCursor!==void 0&&e.serverBase!==void 0;M(r,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:s,...i?{sinceSeq:e.serverCursor}:{},...i&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){let r=this.getConnection(e.shardKey);r?.wsState==="open"&&M(r,{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,r){let s=hn(e);if(s===void 0)return;let i;try{i=JSON.parse(s)}catch{return}switch(i.type!=="error"&&this.getConnection(r)?.reconnect.reset(),i.type){case"ack":{let n=this.subscriptions.getById(i.id);n&&(n.acked=!0);return}case"chunk":{let{data:n,generation:a,id:c,seq:u}=i,h=this.streams.get(c);h&&typeof u=="number"&&(h.lastSeq=u,typeof a=="number"&&(h.generation=a),h.durable=!0),h?.handle.push(g(n));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"pokeEnd":{this.handlePokeEnd(i,r);break}case"pokePart":{this.handlePokePart(i,r);break}case"pokeStart":{this.handlePokeStart(i,r);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,r);break}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}let{id:r}=e,s=r===void 0?void 0:this.streams.get(r);if(s&&r!==void 0){s.handle.fail(cn(e)),this.streams.delete(r);return}let i=r===void 0?void 0:this.subscriptions.getById(r);if(i){let a=Tr(e),c=this.identityFingerprint(),u=P.keyOf(i);pe(i.errorCallbacks,a),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(u,a,c);return}let n=r===void 0?void 0:this.shapeSubscriptions.get(r);n&&pe(n.errorCallbacks,Tr(e))}pokeBufferKey(e,r){return`${S(e)}\0${r}`}handlePokeStart(e,r){gr(this.pokeBuffers,t.MAX_POKE_BUFFERS),this.pokeBuffers.set(this.pokeBufferKey(r,e.pokeId),{baseCheckpoint:e.baseCheckpoint,bases:new Map,epoch:e.epoch,lastMutationId:new Map,parts:new Map,resets:new Set})}handlePokePart(e,r){let s=this.pokeBuffers.get(this.pokeBufferKey(r,e.pokeId));if(!s)return;let i=s.parts.get(e.shapeId)??[];for(let a of e.rowsPatch)i.push(a.value===void 0?a:{...a,value:g(a.value)});s.parts.set(e.shapeId,i),e.lastMutationId!==void 0&&s.lastMutationId.set(e.shapeId,e.lastMutationId);let n=e.baseCheckpoint??s.baseCheckpoint;n!==void 0&&s.bases.set(e.shapeId,n),e.reset===!0&&s.resets.add(e.shapeId)}handlePokeEnd(e,r){let s=this.pokeBufferKey(r,e.pokeId),i=this.pokeBuffers.get(s);if(i){this.pokeBuffers.delete(s);for(let n of i.parts.keys()){let a=this.shapeSubscriptions.get(n);a&&this.applyPokePart(a,i,e)}}}applyPokePart(e,r,s){let i=r.parts.get(e.id)??[],n=r.resets.has(e.id),a=r.bases.get(e.id),c=r.epoch!==void 0&&e.serverEpoch!==void 0&&r.epoch!==e.serverEpoch,u=a!==void 0&&e.serverCursor!==void 0&&e.serverCursor!==a;if(!n&&(c||u)){e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(e),this.sendShapeSubscribeIfOpen(e);return}n&&e.rows.clear(),Ls(e.rows,i),s.checkpoint!==void 0&&(e.serverCursor=s.checkpoint),s.epoch!==void 0&&(e.serverEpoch=s.epoch);let h=r.lastMutationId.get(e.id);h!==void 0&&(e.lastMutationId=h),this.emitShapeRows(e),e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}emitShapeRows(e){let r=[...e.rows.values()];for(let s of e.callbacks)try{s(r)}catch{}}handleDataMessage(e){let{id:r}=e,s=r?this.subscriptions.getById(r):void 0;if(!s)return;let i;try{i=this.resolveDataPayload(e,s)}catch(n){pe(s.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription \u2014 ${n instanceof Error?n.message:String(n)}`});return}if(i===wr){this.resnapshotSubscription(s);return}if(s.serverBase=i,this.dropCacheSeed(P.keyOf(s)),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(let n of s.checkpointCallbacks)n({checkpoint:s.serverCursor,mutationId:s.lastMutationId,rowsFollow:!0})}if(this.persistQueryValue(s),Qe(s,s.serverCursor),$(s,Z(i,s.optimisticLayers)),this.tabCoordinator?.isLeader()){let n=P.keyOf(s);this.tabCoordinator.broadcastSubscriptionData(n,i,s.serverCursor,s.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){let r=this.subscriptions.getById(e.id);r&&this.ackAndAdvanceCursor(r,e.cursor,e.epoch)}handleSettledMessage(e){let r=this.subscriptions.getById(e.id);if(r){this.ackAndAdvanceCursor(r,e.cursor,e.epoch),e.lastMutationId!==void 0&&(r.lastMutationId=Math.max(r.lastMutationId??0,e.lastMutationId));for(let s of r.checkpointCallbacks)s({checkpoint:r.serverCursor,mutationId:r.lastMutationId});if(this.tabCoordinator?.isLeader()){let s=P.keyOf(r);this.tabCoordinator.broadcastSubscriptionSettled(s,r.serverCursor,r.serverEpoch,r.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(e,r,s){e.acked=!0,(r!==void 0&&r!==e.serverCursor||s!==void 0&&s!==e.serverEpoch)&&(r!==void 0&&(e.serverCursor=r),s!==void 0&&(e.serverEpoch=s),this.persistQueryValue(e),Qe(e,e.serverCursor)&&$(e,Z(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,r){if("data"in e&&e.data!==void 0)return g(e.data);let s=g(e.delta);return ur(s)?r.serverBase===void 0?s:hr(r.serverBase,s)??wr:s}dispatchWhisper(e,r){let s=this.whisperHandlers.get(S(r))?.get(e.topic);if(!s)return;let i=g(e.data);for(let n of s)try{n(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){let r=this.streams.get(e);if(r){r.handle.complete(),this.streams.delete(e);return}let s=this.subscriptions.getById(e);s&&(s.acked=!1,pe(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(r=>{H(this.onPersistenceError,"remove",r,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;let e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let r=2166136261,s=5381;for(let i=0;i<e.length;i+=1){let n=e.charCodeAt(i);r^=n,r=Math.imul(r,16777619),s=Math.imul(s,33)+n}return`${e.length.toString(36)}:${(r>>>0).toString(36)}:${(s>>>0).toString(36)}`}credentialStamp(){let e=this.authToken;return e===null?{}:{credential:this.hashToken(e)}}cachedQueryMatchesIdentity(e){return!this.subjectAwaitingReconfirm()&&e.identity===this.identityFingerprint()||this.isSameCredentialUnderTokenHash(e.identity)?!0:e.credential!==void 0&&e.credential===this.credentialStamp().credential}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;let r=this.authToken;return r===null?!1:this.hashToken(r)===e}adoptResolvedSubject(e,r){this.closed||r===null||this.authToken!==e||this.setAuthToken(e,r.id)}subjectAwaitingReconfirm(){return this.authSubject!==void 0&&this.authSubject!==null&&this.subjectToken!==this.authToken}stampOf(e){let r=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return r===void 0?e.identity:r}rejectQueuedForIdentityChange(e){let r=this.offlineQueue.drain(),s=[];for(let i of r){if(this.replayIdentityVerdict(this.stampOf(i))!=="mismatch"){s.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);let n=new Error("offline mutation discarded: auth identity changed before replay");n.code="OFFLINE_IDENTITY_CHANGED",i.reject(n),this.emitItemSettled(i,"rejected",n)}this.offlineQueue.requeue(s),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,r){for(let s of this.connections.values())s.identity===e&&(s.identity=r)}restampQueuedIdentity(e,r){for(let[s,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(s,r);this.offlineQueue.restampIdentity(e,r)}restampWatermarks(e,r){let s=e??"",i=this.clientWatermarks.get(s);if(i===void 0)return;this.clientWatermarks.delete(s);let n=r??"",a=this.clientWatermarks.get(n);if(a===void 0)this.clientWatermarks.set(n,i);else for(let[c,u]of i)a.set(c,u)}clearQueryCacheForIdentityChange(){this.revokeCacheSeededValues(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}flushAllOfflineQueues(){for(let e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){let r=S(e),s=this.offlineFlushes.get(r);if(s===void 0&&this.offlineQueue.size===0)return;let i=(async()=>{await(s??Promise.resolve());try{await this.drainOfflineQueue(e)}catch{}})();this.offlineFlushes.set(r,i),await i,this.offlineFlushes.get(r)===i&&this.offlineFlushes.delete(r)}async drainOfflineQueue(e){let r=this.offlineQueue.drainConflict();for(let h of r){this.unpersist(h.id),this.queuedIdentities.delete(h.id??"");let d=new Error("offline mutation skipped: precondition failed before replay");d.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(h,"rejected",d)}let s=S(e),i=this.offlineQueue.drain(h=>S(h.shardKey)===s);if(i.length===0)return;let n=[],a=[];for(let h of i){let d=this.replayGateVerdict(h);d==="send"?n.push(h):d==="hold"&&a.push(h)}if(this.offlineQueue.requeue(a),a.length>0&&this.subjectAwaitingReconfirm()&&this.getCurrentUser().catch(()=>{}),n.length===0)return;let c=this.encodableOrSettleTerminal(n);if(c.length===0)return;if(c.length===1){await this.replaySequential(c,e),this.scheduleRateLimitedRetry(e);return}let u=[];for(let h=0;h<c.length;h+=ft){let d=c.slice(h,h+ft),l=await this.replayBatched(d,e);if(u.push(...l.requeue),l.stop){u.push(...c.slice(h+ft));break}}u.length>0&&this.offlineQueue.requeue(u),this.scheduleRateLimitedRetry(e)}noteReplayRetryDelay(e,r){let s=S(e),i=this.replayRetryState.get(s),n=(i?.attempts??0)+1,a=As(r,n);this.replayRetryState.set(s,{attempts:n,delayMs:a===void 0?i?.delayMs:Math.max(i?.delayMs??0,a)})}scheduleRateLimitedRetry(e){let r=S(e),s=this.replayRetryState.get(r),i=s?.delayMs;if(s===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(r);return}s.delayMs=void 0;let n=this.replayRetryTimers.get(r);n!==void 0&&clearTimeout(n),this.replayRetryTimers.set(r,setTimeout(()=>{this.replayRetryTimers.delete(r),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){let r=[];for(let s of e)try{z(s.args,`args for '${s.functionPath}'`),r.push(s)}catch(i){this.settleReplayTerminal(s,i instanceof Error?i:new Error(String(i)))}return r}replayGateVerdict(e){let r=this.stampOf(e);if(r===void 0)return this.queuedIdentities.delete(e.id??""),"send";let s=this.replayIdentityVerdict(r);if(s==="unknown")return"hold";if(this.queuedIdentities.delete(e.id??""),s==="match")return"send";this.unpersist(e.id);let i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",e.reject(i),this.emitItemSettled(e,"rejected",i),"reject"}settleReplaySuccess(e,r,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.resolve(r),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,r){let s=e.headers.get("x-lunora-shard-key");if(s===null||r!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;let i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,i)),this.shardCursors.delete(""))}recordShardCursor(e,r){if(typeof r!="number")return;let s=this.cursorKeyFor(e);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,r))}shouldRequeueReplayFailure(e){if(ks(e)){let r=this.hashToken(this.authToken??"");return this.authRefusalNotifiedFor!==r&&(this.authRefusalNotifiedFor=r,this.notifyTokenExpired()),!0}return Ts(e)}settleReplayTerminal(e,r){this.unpersist(e.id),e.reject(r),this.emitItemSettled(e,"rejected",r)}async replaySequential(e,r){for(let s=0;s<e.length;s+=1){let i=e[s];if(i)try{let n,a=await this.rpc(i.functionPath,i.args,i.shardKey,{captureBookmark:!0,clientId:i.clientId??this.clientId,mutationId:i.id,onCommitCursor:o(c=>{n=c},"onCommitCursor")});this.settleReplaySuccess(i,a,n)}catch(n){if(!this.shouldRequeueReplayFailure(n)){this.settleReplayTerminal(i,n);continue}this.noteReplayRetryDelay(r,n),this.offlineQueue.requeue(e.slice(s));return}}}async replayBatched(e,r){if(!this.fetchImpl)return{requeue:e,stop:!0};let s=JSON.stringify({calls:e.map((u,h)=>({args:z(u.args,`args for '${u.functionPath}'`),functionPath:u.functionPath,id:h,clientId:u.clientId??this.clientId,mutationId:u.id,shardKey:u.shardKey}))});if(e.length>1&&Ms(s)>Fs)return await this.replayBatchedHalves(e,r);let i;try{i=await this.fetchImpl(ee(this.url,Sr),{body:s,headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"})}catch{return{requeue:e,stop:!0}}let n=i.headers.get("x-d1-bookmark");if(n&&this.bookmark.set(n),i.status===413&&e.length>1)return await this.replayBatchedHalves(e,r);let a,c=i.headers.get("retry-after");try{a=await i.json()}catch{return this.settleWholeBatchError(e,Ne(i.status,i.statusText,c),r)}if(!a.results){let u=a.error===void 0?Ne(i.status,i.statusText,c):Er(a.error,c);return this.settleWholeBatchError(e,u,r)}return{requeue:this.settleReplayBatchSlots(e,a.results,r),stop:!1}}settleWholeBatchError(e,r,s){if(r instanceof B||r.code!==void 0&&this.shouldRequeueReplayFailure(r))return this.noteReplayRetryDelay(s,r),{requeue:e,stop:!0};for(let i of e)this.settleReplayTerminal(i,r);return{requeue:[],stop:!1}}async replayBatchedHalves(e,r){let s=Math.ceil(e.length/2),i=await this.replayBatched(e.slice(0,s),r);if(i.stop)return{requeue:[...i.requeue,...e.slice(s)],stop:!0};let n=await this.replayBatched(e.slice(s),r);return{requeue:[...i.requeue,...n.requeue],stop:n.stop}}settleReplayBatchSlots(e,r,s){let i=new Map;for(let a of r)typeof a.id=="number"&&a.body!==void 0&&i.set(a.id,a.body);let n=[];for(let[a,c]of e.entries()){let u=i.get(a);if(u===void 0)n.push(c);else if("error"in u){let h=qe(u.error);this.shouldRequeueReplayFailure(h)?(this.noteReplayRetryDelay(s,h),n.push(c)):this.settleReplayTerminal(c,h)}else this.settleReplaySuccess(c,g(u.result),u.commitCursor)}return n}};var Fr=F(Ct(),1),Mr=F(G(),1);var fn=o(()=>{let t=(0,Fr.c)(4),e=rt(),r,s,i;return t[0]!==e?(r=o(n=>e.onConnectionStatus(()=>{n()}),"o"),s=o(()=>e.connectionStatus(),"e"),i=o(()=>e.connectionStatus(),"c"),t[0]=e,t[1]=r,t[2]=s,t[3]=i):(r=t[1],s=t[2],i=t[3]),(0,Mr.useSyncExternalStore)(r,s,i)},"S");export{gt as a,Dr as b,Ye as c,Vr as d,Jr as e,rt as f,fn as g};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as u}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{a as y}from"./chunk-
|
|
1
|
+
import{b as u}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{a as y}from"./chunk-KZDIKRZ3.js";import"./chunk-ULIQFBZU.js";import"./chunk-2W365SXI.js";import"./chunk-35DM4JJG.js";import{a as N}from"./chunk-4ZEL6BYL.js";import{c as v}from"./chunk-MBP4SZYB.js";import"./chunk-Z7WCKAUJ.js";import"./chunk-FSRSK4LY.js";import"./chunk-2Y6PXGIS.js";import{a as g}from"./chunk-FKVZRPV5.js";import{a as w,b,c as S,d as c,e as s,f as o}from"./chunk-HEAQVSNS.js";import{a as f,e as x}from"./chunk-WUWBZPUK.js";import{d as p}from"./chunk-FODLDLE2.js";import{a as n,d as R,g as T}from"./chunk-YKXDMIHQ.js";var e=R(T(),1);var $={active:"default",failing:"destructive",idle:"secondary"},j=n(a=>a===void 0?"\u2014":`${new Date(a).toISOString().slice(0,19).replace("T"," ")} UTC`,"I"),U=n(a=>{let t=a.runs+a.suppressed;return t===0?void 0:Math.round(a.suppressed/t*100)},"$"),F=n(({initialShardKey:a=""})=>{let t=p(),{data:l,error:E,errorSource:A,liveError:I}=v(N.listReactors,{},{live:!0,shardKey:a}),C=l!==void 0,i=Array.isArray(l?.reactors)?l.reactors:[],d;C&&i.length===0?d=(0,e.jsx)(g,{description:t("No reactor is declared in this deployment. Export an onQueryChange(select, handler) from lunora/ to run server-side logic when a query's result changes."),testId:"reactors-empty",title:t("No reactors declared")}):d=(0,e.jsx)(f,{className:"overflow-hidden py-0",children:(0,e.jsx)(x,{className:"px-0",children:(0,e.jsxs)(w,{"data-testid":"reactors-table",children:[(0,e.jsx)(b,{children:(0,e.jsxs)(c,{children:[(0,e.jsx)(s,{children:t("Reactor")}),(0,e.jsx)(s,{children:t("State")}),(0,e.jsx)(s,{children:t("Ran")}),(0,e.jsx)(s,{children:t("Suppressed")}),(0,e.jsx)(s,{children:t("Errors")}),(0,e.jsx)(s,{children:t("Watches")}),(0,e.jsx)(s,{children:t("Last dispatch")})]})}),(0,e.jsx)(S,{children:i.map(r=>{let m=U(r);return(0,e.jsxs)(c,{"data-testid":`reactors-row-${r.path}`,children:[(0,e.jsx)(o,{className:"font-mono text-xs",children:r.path}),(0,e.jsx)(o,{children:(0,e.jsx)(u,{"data-testid":`reactors-state-${r.path}`,variant:$[r.state],children:r.state})}),(0,e.jsx)(o,{className:"font-mono text-xs",children:r.runs}),(0,e.jsxs)(o,{className:"font-mono text-xs text-muted-foreground",children:[r.suppressed,m===void 0?"":` (${String(m)}%)`]}),(0,e.jsx)(o,{className:"font-mono text-xs",children:r.errors===0?(0,e.jsx)("span",{className:"text-muted-foreground",children:"0"}):(0,e.jsx)("span",{className:"text-destructive",children:r.errors})}),(0,e.jsx)(o,{className:"font-mono text-xs text-muted-foreground",children:r.tables===void 0||r.tables.length===0?"\u2014":r.tables.join(", ")}),(0,e.jsx)(o,{className:"font-mono text-xs text-muted-foreground",children:j(r.lastRanAt)})]},r.path)})})]})})});let h=i.filter(r=>r.state==="failing");return(0,e.jsxs)("div",{className:"flex flex-col gap-6","data-testid":"lunora-reactors-panel",children:[E!==null&&(0,e.jsx)(y,{error:A,testId:"reactors-error"}),(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:t("A reactor runs after a write flush, but only when the result of the query it watches actually changed \u2014 a trigger fires on a row write, a reactor fires on a result changing. Suppressed dispatches are the ones where the read re-ran and nothing had moved.")}),h.length>0&&(0,e.jsx)("div",{className:"flex flex-col gap-2","data-testid":"reactors-failing",children:h.map(r=>(0,e.jsxs)("p",{className:"text-xs text-destructive",role:"alert",children:[(0,e.jsx)("span",{className:"font-mono",children:r.path}),": ",r.lastError??t("last dispatch failed")]},r.path))}),I!==void 0&&(0,e.jsx)("p",{className:"text-xs text-amber-600 dark:text-amber-500","data-testid":"reactors-live-error",role:"alert",children:t("Live updates unavailable; showing the last reading.")}),d]})},"U");export{F as default};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Yi,b as Ve,c as Ri,d as Je,e as Zi,f as xi,k as ji}from"./chunk-NOOT4TBC.js";import"./chunk-Q4CAKBWN.js";import"./chunk-ZCIDKRNF.js";import"./chunk-RLLKECZT.js";import"./chunk-YPRQLCKF.js";import"./chunk-GMS77BZD.js";import"./chunk-3Q2P62UR.js";import{a as pi}from"./chunk-QKEJLVC5.js";import"./chunk-AWHXPIXU.js";import"./chunk-V3VJAA4D.js";import"./chunk-5WJXVZMZ.js";import"./chunk-EVTM6Q43.js";import"./chunk-K7AJEMKE.js";import"./chunk-6D6Z2KXU.js";import{a as Le}from"./chunk-OKG3HWSJ.js";import{W as Xi}from"./chunk-PLHA3OWK.js";import"./chunk-Y6CXU7T4.js";import{a as zy}from"./chunk-4L4WTGN5.js";import{a as Gi}from"./chunk-55754F6H.js";import"./chunk-IS6LVJ6L.js";import"./chunk-AAVLPU5Q.js";import"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{b as Ke}from"./chunk-CX5PIWVR.js";import"./chunk-35DM4JJG.js";import"./chunk-4ZEL6BYL.js";import"./chunk-KIKAXEXE.js";import{a as Hi,e as qi}from"./chunk-PPUG6WPN.js";import"./chunk-FSRSK4LY.js";import{d as _i}from"./chunk-2Y6PXGIS.js";import"./chunk-FKVZRPV5.js";import"./chunk-WUWBZPUK.js";import{a as Qi,d as je,p as Ci}from"./chunk-FODLDLE2.js";import{a as c,b as vn,d as fu,e as Ni,f as Ay,g as Bi,i as xe}from"./chunk-YKXDMIHQ.js";var ri=vn(w=>{"use strict";function $e(l,t){var a=l.length;l.push(t);l:for(;0<a;){var u=a-1>>>1,n=l[u];if(0<yn(n,t))l[u]=t,l[a]=n,a=u;else break l}}c($e,"push");function wl(l){return l.length===0?null:l[0]}c(wl,"peek");function hn(l){if(l.length===0)return null;var t=l[0],a=l.pop();if(a!==t){l[0]=a;l:for(var u=0,n=l.length,e=n>>>1;u<e;){var f=2*(u+1)-1,i=l[f],m=f+1,d=l[m];if(0>yn(i,a))m<n&&0>yn(d,i)?(l[u]=d,l[m]=a,u=m):(l[u]=i,l[f]=a,u=f);else if(m<n&&0>yn(d,a))l[u]=d,l[m]=a,u=m;else break l}}return t}c(hn,"pop");function yn(l,t){var a=l.sortIndex-t.sortIndex;return a!==0?a:l.id-t.id}c(yn,"compare");w.unstable_now=void 0;typeof performance=="object"&&typeof performance.now=="function"?(Vi=performance,w.unstable_now=function(){return Vi.now()}):(We=Date,Li=We.now(),w.unstable_now=function(){return We.now()-Li});var Vi,We,Li,tt=[],Et=[],Ty=1,Ql=null,Sl=3,ke=!1,iu=!1,mu=!1,re=!1,Wi=typeof setTimeout=="function"?setTimeout:null,wi=typeof clearTimeout=="function"?clearTimeout:null,Ki=typeof setImmediate<"u"?setImmediate:null;function dn(l){for(var t=wl(Et);t!==null;){if(t.callback===null)hn(Et);else if(t.startTime<=l)hn(Et),t.sortIndex=t.expirationTime,$e(tt,t);else break;t=wl(Et)}}c(dn,"advanceTimers");function Ie(l){if(mu=!1,dn(l),!iu)if(wl(tt)!==null)iu=!0,oa||(oa=!0,ga());else{var t=wl(Et);t!==null&&Pe(Ie,t.startTime-l)}}c(Ie,"handleTimeout");var oa=!1,vu=-1,Fi=5,$i=-1;function ki(){return re?!0:!(w.unstable_now()-$i<Fi)}c(ki,"shouldYieldToHost");function we(){if(re=!1,oa){var l=w.unstable_now();$i=l;var t=!0;try{l:{iu=!1,mu&&(mu=!1,wi(vu),vu=-1),ke=!0;var a=Sl;try{t:{for(dn(l),Ql=wl(tt);Ql!==null&&!(Ql.expirationTime>l&&ki());){var u=Ql.callback;if(typeof u=="function"){Ql.callback=null,Sl=Ql.priorityLevel;var n=u(Ql.expirationTime<=l);if(l=w.unstable_now(),typeof n=="function"){Ql.callback=n,dn(l),t=!0;break t}Ql===wl(tt)&&hn(tt),dn(l)}else hn(tt);Ql=wl(tt)}if(Ql!==null)t=!0;else{var e=wl(Et);e!==null&&Pe(Ie,e.startTime-l),t=!1}}break l}finally{Ql=null,Sl=a,ke=!1}t=void 0}}finally{t?ga():oa=!1}}}c(we,"performWorkUntilDeadline");var ga;typeof Ki=="function"?ga=c(function(){Ki(we)},"schedulePerformWorkUntilDeadline"):typeof MessageChannel<"u"?(Fe=new MessageChannel,Ji=Fe.port2,Fe.port1.onmessage=we,ga=c(function(){Ji.postMessage(null)},"schedulePerformWorkUntilDeadline")):ga=c(function(){Wi(we,0)},"schedulePerformWorkUntilDeadline");var Fe,Ji;function Pe(l,t){vu=Wi(function(){l(w.unstable_now())},t)}c(Pe,"requestHostTimeout");w.unstable_IdlePriority=5;w.unstable_ImmediatePriority=1;w.unstable_LowPriority=4;w.unstable_NormalPriority=3;w.unstable_Profiling=null;w.unstable_UserBlockingPriority=2;w.unstable_cancelCallback=function(l){l.callback=null};w.unstable_forceFrameRate=function(l){0>l||125<l?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):Fi=0<l?Math.floor(1e3/l):5};w.unstable_getCurrentPriorityLevel=function(){return Sl};w.unstable_next=function(l){switch(Sl){case 1:case 2:case 3:var t=3;break;default:t=Sl}var a=Sl;Sl=t;try{return l()}finally{Sl=a}};w.unstable_requestPaint=function(){re=!0};w.unstable_runWithPriority=function(l,t){switch(l){case 1:case 2:case 3:case 4:case 5:break;default:l=3}var a=Sl;Sl=l;try{return t()}finally{Sl=a}};w.unstable_scheduleCallback=function(l,t,a){var u=w.unstable_now();switch(typeof a=="object"&&a!==null?(a=a.delay,a=typeof a=="number"&&0<a?u+a:u):a=u,l){case 1:var n=-1;break;case 2:n=250;break;case 5:n=1073741823;break;case 4:n=1e4;break;default:n=5e3}return n=a+n,l={id:Ty++,callback:t,priorityLevel:l,startTime:a,expirationTime:n,sortIndex:-1},a>u?(l.sortIndex=a,$e(Et,l),wl(tt)===null&&l===wl(Et)&&(mu?(wi(vu),vu=-1):mu=!0,Pe(Ie,a-u))):(l.sortIndex=n,$e(tt,l),iu||ke||(iu=!0,oa||(oa=!0,ga()))),l};w.unstable_shouldYield=ki;w.unstable_wrapCallback=function(l){var t=Sl;return function(){var a=Sl;Sl=t;try{return l.apply(this,arguments)}finally{Sl=a}}}});var Pi=vn((e2,Ii)=>{"use strict";Ii.exports=ri()});var yy=vn(Re=>{"use strict";var el=Pi(),U1=Ni(),Ey=zy();function z(l){var t="https://react.dev/errors/"+l;if(1<arguments.length){t+="?args[]="+encodeURIComponent(arguments[1]);for(var a=2;a<arguments.length;a++)t+="&args[]="+encodeURIComponent(arguments[a])}return"Minified React error #"+l+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}c(z,"formatProdErrorMessage");function D1(l){return!(!l||l.nodeType!==1&&l.nodeType!==9&&l.nodeType!==11)}c(D1,"isValidContainer");function ku(l){var t=l,a=l;if(l.alternate)for(;t.return;)t=t.return;else{l=t;do t=l,(t.flags&4098)!==0&&(a=t.return),l=t.return;while(l)}return t.tag===3?a:null}c(ku,"getNearestMountedFiber");function _1(l){if(l.tag===13){var t=l.memoizedState;if(t===null&&(l=l.alternate,l!==null&&(t=l.memoizedState)),t!==null)return t.dehydrated}return null}c(_1,"getSuspenseInstanceFromFiber");function N1(l){if(l.tag===31){var t=l.memoizedState;if(t===null&&(l=l.alternate,l!==null&&(t=l.memoizedState)),t!==null)return t.dehydrated}return null}c(N1,"getActivityInstanceFromFiber");function l0(l){if(ku(l)!==l)throw Error(z(188))}c(l0,"assertIsMounted");function My(l){var t=l.alternate;if(!t){if(t=ku(l),t===null)throw Error(z(188));return t!==l?null:l}for(var a=l,u=t;;){var n=a.return;if(n===null)break;var e=n.alternate;if(e===null){if(u=n.return,u!==null){a=u;continue}break}if(n.child===e.child){for(e=n.child;e;){if(e===a)return l0(n),l;if(e===u)return l0(n),t;e=e.sibling}throw Error(z(188))}if(a.return!==u.return)a=n,u=e;else{for(var f=!1,i=n.child;i;){if(i===a){f=!0,a=n,u=e;break}if(i===u){f=!0,u=n,a=e;break}i=i.sibling}if(!f){for(i=e.child;i;){if(i===a){f=!0,a=e,u=n;break}if(i===u){f=!0,u=e,a=n;break}i=i.sibling}if(!f)throw Error(z(189))}}if(a.alternate!==u)throw Error(z(190))}if(a.tag!==3)throw Error(z(188));return a.stateNode.current===a?l:t}c(My,"findCurrentFiberUsingSlowPath");function H1(l){var t=l.tag;if(t===5||t===26||t===27||t===6)return l;for(l=l.child;l!==null;){if(t=H1(l),t!==null)return t;l=l.sibling}return null}c(H1,"findCurrentHostFiberImpl");var W=Object.assign,Oy=Symbol.for("react.element"),Sn=Symbol.for("react.transitional.element"),su=Symbol.for("react.portal"),Ea=Symbol.for("react.fragment"),B1=Symbol.for("react.strict_mode"),Qc=Symbol.for("react.profiler"),q1=Symbol.for("react.consumer"),mt=Symbol.for("react.context"),Hf=Symbol.for("react.forward_ref"),Xc=Symbol.for("react.suspense"),Gc=Symbol.for("react.suspense_list"),Bf=Symbol.for("react.memo"),Mt=Symbol.for("react.lazy"),Cc=Symbol.for("react.activity"),Uy=Symbol.for("react.memo_cache_sentinel"),t0=Symbol.iterator;function yu(l){return l===null||typeof l!="object"?null:(l=t0&&l[t0]||l["@@iterator"],typeof l=="function"?l:null)}c(yu,"getIteratorFn");var Dy=Symbol.for("react.client.reference");function pc(l){if(l==null)return null;if(typeof l=="function")return l.$$typeof===Dy?null:l.displayName||l.name||null;if(typeof l=="string")return l;switch(l){case Ea:return"Fragment";case Qc:return"Profiler";case B1:return"StrictMode";case Xc:return"Suspense";case Gc:return"SuspenseList";case Cc:return"Activity"}if(typeof l=="object")switch(l.$$typeof){case su:return"Portal";case mt:return l.displayName||"Context";case q1:return(l._context.displayName||"Context")+".Consumer";case Hf:var t=l.render;return l=l.displayName,l||(l=t.displayName||t.name||"",l=l!==""?"ForwardRef("+l+")":"ForwardRef"),l;case Bf:return t=l.displayName||null,t!==null?t:pc(l.type)||"Memo";case Mt:t=l._payload,l=l._init;try{return pc(l(t))}catch{}}return null}c(pc,"getComponentNameFromType");var zu=Array.isArray,D=U1.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,C=Ey.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,la={pending:!1,data:null,method:null,action:null},Rc=[],Ma=-1;function Il(l){return{current:l}}c(Il,"createCursor");function il(l){0>Ma||(l.current=Rc[Ma],Rc[Ma]=null,Ma--)}c(il,"pop");function L(l,t){Ma++,Rc[Ma]=l.current,l.current=t}c(L,"push");var rl=Il(null),Cu=Il(null),Xt=Il(null),wn=Il(null);function Fn(l,t){switch(L(Xt,t),L(Cu,l),L(rl,null),t.nodeType){case 9:case 11:l=(l=t.documentElement)&&(l=l.namespaceURI)?i1(l):0;break;default:if(l=t.tagName,t=t.namespaceURI)t=i1(t),l=rv(t,l);else switch(l){case"svg":l=1;break;case"math":l=2;break;default:l=0}}il(rl),L(rl,l)}c(Fn,"pushHostContainer");function ja(){il(rl),il(Cu),il(Xt)}c(ja,"popHostContainer");function Zc(l){l.memoizedState!==null&&L(wn,l);var t=rl.current,a=rv(t,l.type);t!==a&&(L(Cu,l),L(rl,a))}c(Zc,"pushHostContext");function $n(l){Cu.current===l&&(il(rl),il(Cu)),wn.current===l&&(il(wn),wu._currentValue=la)}c($n,"popHostContext");var lc,a0;function kt(l){if(lc===void 0)try{throw Error()}catch(a){var t=a.stack.trim().match(/\n( *(at )?)/);lc=t&&t[1]||"",a0=-1<a.stack.indexOf(`
|
|
1
|
+
import{a as Yi,b as Ve,c as Ri,d as Je,e as Zi,f as xi,k as ji}from"./chunk-I5V3IHPF.js";import"./chunk-Q4CAKBWN.js";import"./chunk-NLHKRU3D.js";import"./chunk-RLLKECZT.js";import"./chunk-YPRQLCKF.js";import"./chunk-GMS77BZD.js";import"./chunk-3Q2P62UR.js";import{a as pi}from"./chunk-QKEJLVC5.js";import"./chunk-AWHXPIXU.js";import"./chunk-V3VJAA4D.js";import"./chunk-5WJXVZMZ.js";import"./chunk-EVTM6Q43.js";import"./chunk-K7AJEMKE.js";import"./chunk-6D6Z2KXU.js";import{a as Le}from"./chunk-OKG3HWSJ.js";import{W as Xi}from"./chunk-PLHA3OWK.js";import"./chunk-Y6CXU7T4.js";import{a as zy}from"./chunk-4L4WTGN5.js";import{a as Gi}from"./chunk-55754F6H.js";import"./chunk-IS6LVJ6L.js";import"./chunk-AAVLPU5Q.js";import"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{b as Ke}from"./chunk-2W365SXI.js";import"./chunk-35DM4JJG.js";import"./chunk-4ZEL6BYL.js";import"./chunk-MBP4SZYB.js";import{a as Hi,e as qi}from"./chunk-Z7WCKAUJ.js";import"./chunk-FSRSK4LY.js";import{d as _i}from"./chunk-2Y6PXGIS.js";import"./chunk-FKVZRPV5.js";import"./chunk-WUWBZPUK.js";import{a as Qi,d as je,p as Ci}from"./chunk-FODLDLE2.js";import{a as c,b as vn,d as fu,e as Ni,f as Ay,g as Bi,i as xe}from"./chunk-YKXDMIHQ.js";var ri=vn(w=>{"use strict";function $e(l,t){var a=l.length;l.push(t);l:for(;0<a;){var u=a-1>>>1,n=l[u];if(0<yn(n,t))l[u]=t,l[a]=n,a=u;else break l}}c($e,"push");function wl(l){return l.length===0?null:l[0]}c(wl,"peek");function hn(l){if(l.length===0)return null;var t=l[0],a=l.pop();if(a!==t){l[0]=a;l:for(var u=0,n=l.length,e=n>>>1;u<e;){var f=2*(u+1)-1,i=l[f],m=f+1,d=l[m];if(0>yn(i,a))m<n&&0>yn(d,i)?(l[u]=d,l[m]=a,u=m):(l[u]=i,l[f]=a,u=f);else if(m<n&&0>yn(d,a))l[u]=d,l[m]=a,u=m;else break l}}return t}c(hn,"pop");function yn(l,t){var a=l.sortIndex-t.sortIndex;return a!==0?a:l.id-t.id}c(yn,"compare");w.unstable_now=void 0;typeof performance=="object"&&typeof performance.now=="function"?(Vi=performance,w.unstable_now=function(){return Vi.now()}):(We=Date,Li=We.now(),w.unstable_now=function(){return We.now()-Li});var Vi,We,Li,tt=[],Et=[],Ty=1,Ql=null,Sl=3,ke=!1,iu=!1,mu=!1,re=!1,Wi=typeof setTimeout=="function"?setTimeout:null,wi=typeof clearTimeout=="function"?clearTimeout:null,Ki=typeof setImmediate<"u"?setImmediate:null;function dn(l){for(var t=wl(Et);t!==null;){if(t.callback===null)hn(Et);else if(t.startTime<=l)hn(Et),t.sortIndex=t.expirationTime,$e(tt,t);else break;t=wl(Et)}}c(dn,"advanceTimers");function Ie(l){if(mu=!1,dn(l),!iu)if(wl(tt)!==null)iu=!0,oa||(oa=!0,ga());else{var t=wl(Et);t!==null&&Pe(Ie,t.startTime-l)}}c(Ie,"handleTimeout");var oa=!1,vu=-1,Fi=5,$i=-1;function ki(){return re?!0:!(w.unstable_now()-$i<Fi)}c(ki,"shouldYieldToHost");function we(){if(re=!1,oa){var l=w.unstable_now();$i=l;var t=!0;try{l:{iu=!1,mu&&(mu=!1,wi(vu),vu=-1),ke=!0;var a=Sl;try{t:{for(dn(l),Ql=wl(tt);Ql!==null&&!(Ql.expirationTime>l&&ki());){var u=Ql.callback;if(typeof u=="function"){Ql.callback=null,Sl=Ql.priorityLevel;var n=u(Ql.expirationTime<=l);if(l=w.unstable_now(),typeof n=="function"){Ql.callback=n,dn(l),t=!0;break t}Ql===wl(tt)&&hn(tt),dn(l)}else hn(tt);Ql=wl(tt)}if(Ql!==null)t=!0;else{var e=wl(Et);e!==null&&Pe(Ie,e.startTime-l),t=!1}}break l}finally{Ql=null,Sl=a,ke=!1}t=void 0}}finally{t?ga():oa=!1}}}c(we,"performWorkUntilDeadline");var ga;typeof Ki=="function"?ga=c(function(){Ki(we)},"schedulePerformWorkUntilDeadline"):typeof MessageChannel<"u"?(Fe=new MessageChannel,Ji=Fe.port2,Fe.port1.onmessage=we,ga=c(function(){Ji.postMessage(null)},"schedulePerformWorkUntilDeadline")):ga=c(function(){Wi(we,0)},"schedulePerformWorkUntilDeadline");var Fe,Ji;function Pe(l,t){vu=Wi(function(){l(w.unstable_now())},t)}c(Pe,"requestHostTimeout");w.unstable_IdlePriority=5;w.unstable_ImmediatePriority=1;w.unstable_LowPriority=4;w.unstable_NormalPriority=3;w.unstable_Profiling=null;w.unstable_UserBlockingPriority=2;w.unstable_cancelCallback=function(l){l.callback=null};w.unstable_forceFrameRate=function(l){0>l||125<l?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):Fi=0<l?Math.floor(1e3/l):5};w.unstable_getCurrentPriorityLevel=function(){return Sl};w.unstable_next=function(l){switch(Sl){case 1:case 2:case 3:var t=3;break;default:t=Sl}var a=Sl;Sl=t;try{return l()}finally{Sl=a}};w.unstable_requestPaint=function(){re=!0};w.unstable_runWithPriority=function(l,t){switch(l){case 1:case 2:case 3:case 4:case 5:break;default:l=3}var a=Sl;Sl=l;try{return t()}finally{Sl=a}};w.unstable_scheduleCallback=function(l,t,a){var u=w.unstable_now();switch(typeof a=="object"&&a!==null?(a=a.delay,a=typeof a=="number"&&0<a?u+a:u):a=u,l){case 1:var n=-1;break;case 2:n=250;break;case 5:n=1073741823;break;case 4:n=1e4;break;default:n=5e3}return n=a+n,l={id:Ty++,callback:t,priorityLevel:l,startTime:a,expirationTime:n,sortIndex:-1},a>u?(l.sortIndex=a,$e(Et,l),wl(tt)===null&&l===wl(Et)&&(mu?(wi(vu),vu=-1):mu=!0,Pe(Ie,a-u))):(l.sortIndex=n,$e(tt,l),iu||ke||(iu=!0,oa||(oa=!0,ga()))),l};w.unstable_shouldYield=ki;w.unstable_wrapCallback=function(l){var t=Sl;return function(){var a=Sl;Sl=t;try{return l.apply(this,arguments)}finally{Sl=a}}}});var Pi=vn((e2,Ii)=>{"use strict";Ii.exports=ri()});var yy=vn(Re=>{"use strict";var el=Pi(),U1=Ni(),Ey=zy();function z(l){var t="https://react.dev/errors/"+l;if(1<arguments.length){t+="?args[]="+encodeURIComponent(arguments[1]);for(var a=2;a<arguments.length;a++)t+="&args[]="+encodeURIComponent(arguments[a])}return"Minified React error #"+l+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}c(z,"formatProdErrorMessage");function D1(l){return!(!l||l.nodeType!==1&&l.nodeType!==9&&l.nodeType!==11)}c(D1,"isValidContainer");function ku(l){var t=l,a=l;if(l.alternate)for(;t.return;)t=t.return;else{l=t;do t=l,(t.flags&4098)!==0&&(a=t.return),l=t.return;while(l)}return t.tag===3?a:null}c(ku,"getNearestMountedFiber");function _1(l){if(l.tag===13){var t=l.memoizedState;if(t===null&&(l=l.alternate,l!==null&&(t=l.memoizedState)),t!==null)return t.dehydrated}return null}c(_1,"getSuspenseInstanceFromFiber");function N1(l){if(l.tag===31){var t=l.memoizedState;if(t===null&&(l=l.alternate,l!==null&&(t=l.memoizedState)),t!==null)return t.dehydrated}return null}c(N1,"getActivityInstanceFromFiber");function l0(l){if(ku(l)!==l)throw Error(z(188))}c(l0,"assertIsMounted");function My(l){var t=l.alternate;if(!t){if(t=ku(l),t===null)throw Error(z(188));return t!==l?null:l}for(var a=l,u=t;;){var n=a.return;if(n===null)break;var e=n.alternate;if(e===null){if(u=n.return,u!==null){a=u;continue}break}if(n.child===e.child){for(e=n.child;e;){if(e===a)return l0(n),l;if(e===u)return l0(n),t;e=e.sibling}throw Error(z(188))}if(a.return!==u.return)a=n,u=e;else{for(var f=!1,i=n.child;i;){if(i===a){f=!0,a=n,u=e;break}if(i===u){f=!0,u=n,a=e;break}i=i.sibling}if(!f){for(i=e.child;i;){if(i===a){f=!0,a=e,u=n;break}if(i===u){f=!0,u=e,a=n;break}i=i.sibling}if(!f)throw Error(z(189))}}if(a.alternate!==u)throw Error(z(190))}if(a.tag!==3)throw Error(z(188));return a.stateNode.current===a?l:t}c(My,"findCurrentFiberUsingSlowPath");function H1(l){var t=l.tag;if(t===5||t===26||t===27||t===6)return l;for(l=l.child;l!==null;){if(t=H1(l),t!==null)return t;l=l.sibling}return null}c(H1,"findCurrentHostFiberImpl");var W=Object.assign,Oy=Symbol.for("react.element"),Sn=Symbol.for("react.transitional.element"),su=Symbol.for("react.portal"),Ea=Symbol.for("react.fragment"),B1=Symbol.for("react.strict_mode"),Qc=Symbol.for("react.profiler"),q1=Symbol.for("react.consumer"),mt=Symbol.for("react.context"),Hf=Symbol.for("react.forward_ref"),Xc=Symbol.for("react.suspense"),Gc=Symbol.for("react.suspense_list"),Bf=Symbol.for("react.memo"),Mt=Symbol.for("react.lazy"),Cc=Symbol.for("react.activity"),Uy=Symbol.for("react.memo_cache_sentinel"),t0=Symbol.iterator;function yu(l){return l===null||typeof l!="object"?null:(l=t0&&l[t0]||l["@@iterator"],typeof l=="function"?l:null)}c(yu,"getIteratorFn");var Dy=Symbol.for("react.client.reference");function pc(l){if(l==null)return null;if(typeof l=="function")return l.$$typeof===Dy?null:l.displayName||l.name||null;if(typeof l=="string")return l;switch(l){case Ea:return"Fragment";case Qc:return"Profiler";case B1:return"StrictMode";case Xc:return"Suspense";case Gc:return"SuspenseList";case Cc:return"Activity"}if(typeof l=="object")switch(l.$$typeof){case su:return"Portal";case mt:return l.displayName||"Context";case q1:return(l._context.displayName||"Context")+".Consumer";case Hf:var t=l.render;return l=l.displayName,l||(l=t.displayName||t.name||"",l=l!==""?"ForwardRef("+l+")":"ForwardRef"),l;case Bf:return t=l.displayName||null,t!==null?t:pc(l.type)||"Memo";case Mt:t=l._payload,l=l._init;try{return pc(l(t))}catch{}}return null}c(pc,"getComponentNameFromType");var zu=Array.isArray,D=U1.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,C=Ey.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,la={pending:!1,data:null,method:null,action:null},Rc=[],Ma=-1;function Il(l){return{current:l}}c(Il,"createCursor");function il(l){0>Ma||(l.current=Rc[Ma],Rc[Ma]=null,Ma--)}c(il,"pop");function L(l,t){Ma++,Rc[Ma]=l.current,l.current=t}c(L,"push");var rl=Il(null),Cu=Il(null),Xt=Il(null),wn=Il(null);function Fn(l,t){switch(L(Xt,t),L(Cu,l),L(rl,null),t.nodeType){case 9:case 11:l=(l=t.documentElement)&&(l=l.namespaceURI)?i1(l):0;break;default:if(l=t.tagName,t=t.namespaceURI)t=i1(t),l=rv(t,l);else switch(l){case"svg":l=1;break;case"math":l=2;break;default:l=0}}il(rl),L(rl,l)}c(Fn,"pushHostContainer");function ja(){il(rl),il(Cu),il(Xt)}c(ja,"popHostContainer");function Zc(l){l.memoizedState!==null&&L(wn,l);var t=rl.current,a=rv(t,l.type);t!==a&&(L(Cu,l),L(rl,a))}c(Zc,"pushHostContext");function $n(l){Cu.current===l&&(il(rl),il(Cu)),wn.current===l&&(il(wn),wu._currentValue=la)}c($n,"popHostContext");var lc,a0;function kt(l){if(lc===void 0)try{throw Error()}catch(a){var t=a.stack.trim().match(/\n( *(at )?)/);lc=t&&t[1]||"",a0=-1<a.stack.indexOf(`
|
|
2
2
|
at`)?" (<anonymous>)":-1<a.stack.indexOf("@")?"@unknown:0:0":""}return`
|
|
3
3
|
`+lc+l+a0}c(kt,"describeBuiltInComponentFrame");var tc=!1;function ac(l,t){if(!l||tc)return"";tc=!0;var a=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var u={DetermineComponentFrameRoot:c(function(){try{if(t){var b=c(function(){throw Error()},"Fake");if(Object.defineProperty(b.prototype,"props",{set:c(function(){throw Error()},"set")}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(b,[])}catch(g){var S=g}Reflect.construct(l,[],b)}else{try{b.call()}catch(g){S=g}l.call(b.prototype)}}else{try{throw Error()}catch(g){S=g}(b=l())&&typeof b.catch=="function"&&b.catch(function(){})}}catch(g){if(g&&S&&typeof g.stack=="string")return[g.stack,S.stack]}return[null,null]},"DetermineComponentFrameRoot")};u.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var n=Object.getOwnPropertyDescriptor(u.DetermineComponentFrameRoot,"name");n&&n.configurable&&Object.defineProperty(u.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var e=u.DetermineComponentFrameRoot(),f=e[0],i=e[1];if(f&&i){var m=f.split(`
|
|
4
4
|
`),d=i.split(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/studio",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.178",
|
|
4
4
|
"description": "The Lunora Studio: a local admin UI for your schema, data, logs, and advisors",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"admin-ui",
|
|
@@ -58,11 +58,11 @@
|
|
|
58
58
|
"@hugeicons/react": "^1.1.10",
|
|
59
59
|
"@lingui/core": "^6.6.0",
|
|
60
60
|
"@lingui/message-utils": "^6.6.0",
|
|
61
|
-
"@lunora/advisor": "1.0.0-alpha.
|
|
62
|
-
"@lunora/bindings": "1.0.0-alpha.
|
|
63
|
-
"@lunora/client": "1.0.0-alpha.
|
|
61
|
+
"@lunora/advisor": "1.0.0-alpha.130",
|
|
62
|
+
"@lunora/bindings": "1.0.0-alpha.58",
|
|
63
|
+
"@lunora/client": "1.0.0-alpha.102",
|
|
64
64
|
"@lunora/errors": "1.0.0-alpha.36",
|
|
65
|
-
"@lunora/react": "1.0.0-alpha.
|
|
65
|
+
"@lunora/react": "1.0.0-alpha.107",
|
|
66
66
|
"@tanstack/react-query": "5.101.4",
|
|
67
67
|
"@tanstack/react-router": "^1.170.32",
|
|
68
68
|
"@tanstack/react-table": "^9.2.4",
|