@lunora/studio 1.0.0-alpha.306 → 1.0.0-alpha.307
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-UEI6ZPVI.js → chunk-26CD344Y.js} +1 -1
- package/dist/standalone/{chunk-KWF2J6VZ.js → chunk-2DLQNWOP.js} +1 -1
- package/dist/standalone/{chunk-2I3ZBXYL.js → chunk-2IS4QPKN.js} +1 -1
- package/dist/standalone/{chunk-7YCLG2IM.js → chunk-2XZUV2WP.js} +1 -1
- package/dist/standalone/{chunk-JOEGJYP3.js → chunk-2ZL6DTRQ.js} +1 -1
- package/dist/standalone/{chunk-HGROP7QC.js → chunk-3WMHXMYX.js} +1 -1
- package/dist/standalone/{chunk-XSUJREQY.js → chunk-4APLHRSM.js} +1 -1
- package/dist/standalone/{chunk-6VMXAGAI.js → chunk-4EX2MIWB.js} +1 -1
- package/dist/standalone/{chunk-ZOO22NF2.js → chunk-4XBXMX5F.js} +1 -1
- package/dist/standalone/{chunk-ECFQBJBI.js → chunk-6GAJMPAN.js} +1 -1
- package/dist/standalone/{chunk-GPXBDGXB.js → chunk-6GWFTKCC.js} +1 -1
- package/dist/standalone/{chunk-AAHERFLQ.js → chunk-6L77KIMU.js} +1 -1
- package/dist/standalone/{chunk-BT2EOZVA.js → chunk-ABC4YDEX.js} +1 -1
- package/dist/standalone/{chunk-L6VLCPLU.js → chunk-AQ44DOJ2.js} +1 -1
- package/dist/standalone/{chunk-GH37NSJK.js → chunk-AS7S4GPM.js} +1 -1
- package/dist/standalone/{chunk-VA2UTSYB.js → chunk-B5DSWN4E.js} +1 -1
- package/dist/standalone/{chunk-BQQX4UAT.js → chunk-BQDCHAKC.js} +1 -1
- package/dist/standalone/{chunk-VIKNFO4J.js → chunk-CQW2A24E.js} +1 -1
- package/dist/standalone/{chunk-TQRER6XR.js → chunk-D4AGRVQK.js} +1 -1
- package/dist/standalone/{chunk-SDS7L3YN.js → chunk-DBSDFOSE.js} +1 -1
- package/dist/standalone/{chunk-2SHDUJ44.js → chunk-DMSQZT7T.js} +1 -1
- package/dist/standalone/{chunk-O3AIAMBR.js → chunk-FGOW3HNU.js} +1 -1
- package/dist/standalone/{chunk-T5NA7KNM.js → chunk-FJHI244I.js} +1 -1
- package/dist/standalone/{chunk-J3DCFI3D.js → chunk-G5J3XIOX.js} +1 -1
- package/dist/standalone/{chunk-BQUMKK6S.js → chunk-GXJMMVSO.js} +1 -1
- package/dist/standalone/{chunk-GNMF6VYU.js → chunk-IMSZQEM3.js} +1 -1
- package/dist/standalone/{chunk-EGSOTMVT.js → chunk-IRGYOUYT.js} +1 -1
- package/dist/standalone/{chunk-2VP4X53H.js → chunk-JEX77V32.js} +1 -1
- package/dist/standalone/{chunk-3CCXF6R4.js → chunk-KBLRZSAO.js} +1 -1
- package/dist/standalone/{chunk-XSPGGID6.js → chunk-LCHOGYA2.js} +1 -1
- package/dist/standalone/{chunk-CHGVE7TY.js → chunk-LMAAYLXZ.js} +1 -1
- package/dist/standalone/{chunk-SXG6KDMB.js → chunk-MOKI7YUO.js} +1 -1
- package/dist/standalone/{chunk-P6MZCVDN.js → chunk-MOSFJCGQ.js} +1 -1
- package/dist/standalone/{chunk-N4VNDUMJ.js → chunk-N3MQC4AQ.js} +1 -1
- package/dist/standalone/{chunk-3XRFNCOJ.js → chunk-OOTMIHY7.js} +1 -1
- package/dist/standalone/{chunk-LKCHSZST.js → chunk-P6TRSJ5M.js} +1 -1
- package/dist/standalone/{chunk-LBFYD5FZ.js → chunk-P7T4D4EK.js} +1 -1
- package/dist/standalone/{chunk-H6BK2PFM.js → chunk-R35CIBI7.js} +1 -1
- package/dist/standalone/{chunk-3LZ4WYM6.js → chunk-RDJ4DAWB.js} +1 -1
- package/dist/standalone/{chunk-7VZPLCQD.js → chunk-RKQW3JZL.js} +1 -1
- package/dist/standalone/{chunk-RSYONXXA.js → chunk-RMF7DYKW.js} +1 -1
- package/dist/standalone/{chunk-3OCAUWBW.js → chunk-RQ5FJ44G.js} +1 -1
- package/dist/standalone/{chunk-F7NRVS2A.js → chunk-RWVYO4DJ.js} +1 -1
- package/dist/standalone/{chunk-53UDFNJH.js → chunk-SKQUAYIV.js} +1 -1
- package/dist/standalone/{chunk-WONK2QST.js → chunk-TNYIHG5L.js} +1 -1
- package/dist/standalone/{chunk-JCOVEMPK.js → chunk-TTYYOI4M.js} +1 -1
- package/dist/standalone/{chunk-56OCEDA6.js → chunk-TU4SWAYE.js} +1 -1
- package/dist/standalone/chunk-TVABCOKH.js +9 -0
- package/dist/standalone/{chunk-PY7HHLXU.js → chunk-TYYAOZ6L.js} +1 -1
- package/dist/standalone/{chunk-CPT3AWVP.js → chunk-VFVA5JS3.js} +1 -1
- package/dist/standalone/{chunk-FUTFZZ65.js → chunk-WK73RTAA.js} +1 -1
- package/dist/standalone/{chunk-W4SFBONV.js → chunk-XD3DLHGP.js} +1 -1
- package/dist/standalone/{chunk-WH4PDIP4.js → chunk-XFTPM6XZ.js} +1 -1
- package/dist/standalone/{chunk-MG36CTLD.js → chunk-YDB52C77.js} +1 -1
- package/dist/standalone/{chunk-H4O24DQA.js → chunk-YGBNJQSJ.js} +1 -1
- package/dist/standalone/{chunk-W2DW4WFN.js → chunk-YKT4OK5G.js} +1 -1
- package/dist/standalone/{chunk-7IEEZGGC.js → chunk-ZAVHKDVJ.js} +1 -1
- package/dist/standalone/{chunk-DC7GNRSW.js → chunk-ZBGEEMTX.js} +1 -1
- package/dist/standalone/{chunk-S2OILIZO.js → chunk-ZOPYK2Q7.js} +1 -1
- package/dist/standalone/studio.js +1 -1
- package/package.json +4 -4
- package/dist/standalone/chunk-PLYOESZS.js +0 -9
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import{a as Gt,d as b}from"./chunk-LEQBVZJL.js";import{a as n,d as x,e as Y,f as Jt,g as rt}from"./chunk-I26MS5PJ.js";var yr=/["\\\u0000-\u001F\uD800-\uDFFF]/,Yt=n(t=>yr.test(t)?JSON.stringify(t):`"${t}"`,"y"),br=n(t=>Number.isNaN(t)?"nan":t===1/0?"inf":t===-1/0?"-inf":Object.is(t,-0)?"-0":void 0,"p"),gr=n((t,e)=>{let s=Object.getPrototypeOf(t);if(s!==null&&s!==Object.prototype){let c=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${c} 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,i=Object.keys(r).sort(),a="{",o=!0;for(let c of i){let u=r[c];u!==void 0&&(o?o=!1:a+=",",a+=Yt(c),a+=":",a+=e(u))}return`${a}}`},"u"),me=n(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"){let e=br(t);if(e!==void 0)return e}return typeof t=="string"?Yt(t):t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${Array.from({length:t.length},(e,s)=>me(t[s])).join(",")}]`:gr(t,me)},"c");var Ie=n(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"e");var Re=n(t=>{let e="";for(let s=0;s<t.length;s+=32768)e+=String.fromCharCode(...t.subarray(s,s+32768));return btoa(e)},"f"),vr=n(t=>{let e=atob(t),s=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)s[r]=e.codePointAt(r)??0;return s},"l"),O="$lunora.wire$",Ae=64,Fe=1024,Sr="__proto__",wr=/^-?\d+$/,Xt={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},Zt={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},it=n((t,e,s)=>{e===Sr?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:s,writable:!0}):t[e]=s},"y");var Cr=n(t=>{let e=t.toString();if(e.length>Fe)throw new RangeError(`wire-codec: over-long bigint (max ${String(Fe)} digits)`);return[O,"bigint",e]},"T"),kr=n(t=>Number.isNaN(t)?[O,"nan"]:t===1/0?[O,"inf"]:t===-1/0?[O,"-inf"]:t,"j"),Tr=n((t,e)=>{let s=e(Object.fromEntries(Object.keys(t).map(a=>[a,t[a]]))),r=t,i=[O,"error",String(r.name),String(r.message),s];return t.cause!==void 0&&i.push(e(t.cause)),i},"R"),Er=n(t=>{let e=t.constructor.name,s=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return e==="Uint8Array"?[O,"bytes",Re(s)]:[O,"bytes",Re(s),e]},"S"),Or=n((t,e)=>t instanceof Date?[O,"date",e(t.getTime())]:t instanceof Error?Tr(t,e):t instanceof URL?[O,"url",t.href]:t instanceof Map?[O,"map",[...t.entries()].map(([s,r])=>[e(s),e(r)])]:t instanceof Set?[O,"set",[...t].map(s=>e(s))]:t instanceof ArrayBuffer?[O,"bytes",Re(new Uint8Array(t)),"ArrayBuffer"]:ArrayBuffer.isView(t)?Er(t):void 0,"U"),Ir=n((t,e)=>{let s=t.map(r=>e(r));return s.length>0&&s[0]===O?[O,"arr",s]:s},"I"),Rr=n((t,e)=>{let s={};for(let r of Object.keys(t)){let i=t[r];i!==void 0&&it(s,r,e(i))}return s},"B"),q=n((t,e=0)=>{if(e>Ae)throw new RangeError(`wire-codec: value nesting exceeds the ${String(Ae)}-level limit`);if(t===void 0)return[O,"undefined"];if(t===null)return t;if(typeof t=="bigint")return Cr(t);if(typeof t=="number")return kr(t);if(typeof t!="object")return t;let s=n(i=>q(i,e+1),"t"),r=Or(t,s);if(r!==void 0)return r;if(Array.isArray(t))return Ir(t,s);if(!Ie(t)){let i=t.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${i} over the Lunora wire \u2014 only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}return Rr(t,s)},"m"),Ar=n(t=>{let e=t[2];if(typeof e!="string"||e.length>Fe||!wr.test(e))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${String(Fe)} digits)`);return BigInt(e)},"N"),Fr=n((t,e)=>{let s=e(t[2]);if(typeof s!="number")throw new TypeError("wire-codec: malformed date \u2014 epoch must be a number");return new Date(s)},"_"),Pr=n((t,e)=>{let s=t[2];return new Map(s.map(r=>{if(!Array.isArray(r)||r.length!==2)throw new TypeError("wire-codec: malformed map entry \u2014 expected a [key, value] pair");return[e(r[0]),e(r[1])]}))},"$"),Mr=n(t=>{let e=t[2];if(typeof e!="string")throw new TypeError("wire-codec: malformed url \u2014 href must be a string");return new URL(e)},"k"),xr=n((t,e)=>{let s=t[2],r=t[3];if(typeof s!="string"||typeof r!="string")throw new TypeError("wire-codec: malformed error \u2014 name and message must be strings");let i=(Object.hasOwn(Zt,s)?Zt[s]:void 0)??Error,a=new i(r);a.name!==s&&Object.defineProperty(a,"name",{configurable:!0,value:s,writable:!0});let o=e(t[4]);if(o===null||typeof o!="object"||Array.isArray(o))throw new TypeError("wire-codec: malformed error \u2014 props must be an object");for(let[c,u]of Object.entries(o))it(a,c,u);return t.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:e(t[5]),writable:!0}),a},"P"),Qr=n(t=>{let e=t[2];if(typeof e!="string")throw new TypeError("wire-codec: malformed bytes \u2014 payload must be a base64 string");let s=vr(e);if(Re(s)!==e)throw new TypeError("wire-codec: malformed bytes \u2014 payload must be canonical padded base64");let r=t[3]??"Uint8Array";if(r==="ArrayBuffer")return s.buffer.byteLength===s.byteLength?s.buffer:new Uint8Array(s).buffer;let i=Object.hasOwn(Xt,r)?Xt[r]:void 0;return i?new i(new Uint8Array(s).buffer):s},"D"),_r=n((t,e)=>{switch(t[1]){case"-inf":return-1/0;case"arr":return t[2].map(s=>e(s));case"bigint":return Ar(t);case"bytes":return Qr(t);case"date":return Fr(t,e);case"error":return xr(t,e);case"inf":return 1/0;case"map":return Pr(t,e);case"nan":return Number.NaN;case"set":return new Set(t[2].map(s=>e(s)));case"undefined":return;case"url":return Mr(t);default:return t.map(s=>e(s))}},"C"),Lr=n((t,e)=>{let s={};for(let r of Object.keys(t))it(s,r,e(t[r]));return s},"L"),T=n((t,e=0)=>{if(e>Ae)throw new RangeError(`wire-codec: value nesting exceeds the ${String(Ae)}-level limit`);if(t===null||typeof t!="object")return t;let s=n(r=>T(r,e+1),"t");if(Array.isArray(t)){let r=t;return r[0]===O?_r(r,s):r.map(i=>s(i))}return Lr(t,s)},"A"),Dr=n(t=>{try{let e=T(JSON.parse(t));return Ie(e)?e:void 0}catch{return}},"F");var U=n(t=>me(q(t)),"a");var ae=x(Y(),1),es=x(rt(),1);var ye=ae.createContext(void 0),be=n(t=>{let e=ae.useContext(ye);if(t)return t;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},"useQueryClient"),nt=n(({client:t,children:e})=>(ae.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,es.jsx)(ye.Provider,{value:t,children:e})),"QueryClientProvider");var Q=class{static{n(this,"Subscribable")}constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var Ur=class extends Q{static{n(this,"FocusManager")}#e;#t;#s;constructor(){super(),this.#s=t=>{if(typeof window<"u"&&window.addEventListener){let e=n(()=>t(),"listener");return window.addEventListener("visibilitychange",e,!1),()=>{window.removeEventListener("visibilitychange",e)}}}}onSubscribe(){this.#t||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#s=t,this.#t?.(),this.#t=t(e=>{typeof e=="boolean"?this.setFocused(e):this.onFocus()})}setFocused(t){this.#e!==t&&(this.#e=t,this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(e=>{e(t)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},oe=new Ur;var Kr={setTimeout:n((t,e)=>setTimeout(t,e),"setTimeout"),clearTimeout:n(t=>clearTimeout(t),"clearTimeout"),setInterval:n((t,e)=>setInterval(t,e),"setInterval"),clearInterval:n(t=>clearInterval(t),"clearInterval")},qr=class{static{n(this,"TimeoutManager")}#e=Kr;#t=!1;setTimeoutProvider(t){this.#e=t}setTimeout(t,e){return this.#e.setTimeout(t,e)}clearTimeout(t){this.#e.clearTimeout(t)}setInterval(t,e){return this.#e.setInterval(t,e)}clearInterval(t){this.#e.clearInterval(t)}},N=new qr;function ts(t){setTimeout(t,0)}n(ts,"systemSetTimeoutZero");var ot=typeof window>"u"||"Deno"in globalThis;function C(){}n(C,"noop");function is(t,e){return typeof t=="function"?t(e):t}n(is,"functionalUpdate");function ge(t){return typeof t=="number"&&t>=0&&t!==1/0}n(ge,"isValidTimeout");function Pe(t,e){return Math.max(t+(e||0)-Date.now(),0)}n(Pe,"timeUntilStale");function K(t,e){return typeof t=="function"?t(e):t}n(K,"resolveStaleTime");function R(t,e){return typeof t=="function"?t(e):t}n(R,"resolveQueryBoolean");function Me(t,e){let{type:s="all",exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:c}=t;if(o){if(r){if(e.queryHash!==ve(o,e.options))return!1}else if(!X(e.queryKey,o))return!1}if(s!=="all"){let u=e.isActive();if(s==="active"&&!u||s==="inactive"&&u)return!1}return!(typeof c=="boolean"&&e.isStale()!==c||i&&i!==e.state.fetchStatus||a&&!a(e))}n(Me,"matchQuery");function xe(t,e){let{exact:s,status:r,predicate:i,mutationKey:a}=t;if(a){if(!e.options.mutationKey)return!1;if(s){if(j(e.options.mutationKey)!==j(a))return!1}else if(!X(e.options.mutationKey,a))return!1}return!(r&&e.state.status!==r||i&&!i(e))}n(xe,"matchMutation");function ve(t,e){return(e?.queryKeyHashFn||j)(t)}n(ve,"hashQueryKeyByOptions");function j(t){return JSON.stringify(t,(e,s)=>at(s)?Object.keys(s).sort().reduce((r,i)=>(r[i]=s[i],r),{}):s)}n(j,"hashKey");function X(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(t&&e&&typeof t=="object"&&typeof e=="object"){if(Array.isArray(t)&&Array.isArray(e)){for(let r=0;r<e.length;r++)if(!X(t[r],e[r]))return!1;return!0}let s=Object.keys(e);for(let r of s)if(!X(t[r],e[r]))return!1;return!0}return!1}n(X,"partialMatchKey");var Nr=Object.prototype.hasOwnProperty;function ct(t,e,s=0){if(t===e)return t;if(s>500)return e;let r=ss(t)&&ss(e);if(!r&&!(at(t)&&at(e)))return e;let a=(r?t:Object.keys(t)).length,o=r?e:Object.keys(e),c=o.length,u=r?new Array(c):{},d=0;for(let h=0;h<c;h++){let l=r?h:o[h],f=t[l],p=e[l];if(f===p){u[l]=f,(r?h<a:Nr.call(t,l))&&d++;continue}if(f===null||p===null||typeof f!="object"||typeof p!="object"){u[l]=p;continue}let m=ct(f,p,s+1);u[l]=m,m===f&&d++}return a===c&&d===a?t:u}n(ct,"replaceEqualDeep");function ce(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(let s in t)if(t[s]!==e[s])return!1;return!0}n(ce,"shallowEqualObjects");function ss(t){return Array.isArray(t)&&t.length===Object.keys(t).length}n(ss,"isPlainArray");function at(t){if(!rs(t))return!1;let e=t.constructor;if(e===void 0)return!0;let s=e.prototype;return!(!rs(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}n(at,"isPlainObject");function rs(t){return Object.prototype.toString.call(t)==="[object Object]"}n(rs,"hasObjectPrototype");function ns(t){return new Promise(e=>{N.setTimeout(e,t)})}n(ns,"sleep");function Se(t,e,s){return typeof s.structuralSharing=="function"?s.structuralSharing(t,e):s.structuralSharing!==!1?ct(t,e):e}n(Se,"replaceData");function jr(t){return t}n(jr,"keepPreviousData");function as(t,e,s=0){let r=[...t,e];return s&&r.length>s?r.slice(1):r}n(as,"addToEnd");function os(t,e,s=0){let r=[e,...t];return s&&r.length>s?r.slice(0,-1):r}n(os,"addToStart");var ue=Symbol();function Qe(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===ue?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}n(Qe,"ensureQueryFn");function he(t,e){return typeof t=="function"?t(...e):!!t}n(he,"shouldThrowError");function cs(t,e,s){let r=!1,i;return Object.defineProperty(t,"signal",{enumerable:!0,get:n(()=>(i??=e(),r||(r=!0,i.aborted?s():i.addEventListener("abort",s,{once:!0})),i),"get")}),t}n(cs,"addConsumeAwareSignal");var B=(()=>{let t=n(()=>ot,"isServerFn");return{isServer(){return t()},setIsServer(e){t=e}}})();function we(){let t,e,s=new Promise((i,a)=>{t=i,e=a});s.status="pending",s.catch(()=>{});function r(i){Object.assign(s,i),delete s.resolve,delete s.reject}return n(r,"finalize"),s.resolve=i=>{r({status:"fulfilled",value:i}),t(i)},s.reject=i=>{r({status:"rejected",reason:i}),e(i)},s}n(we,"pendingThenable");var us=ts;function Br(){let t=[],e=0,s=n(c=>{c()},"notifyFn"),r=n(c=>{c()},"batchNotifyFn"),i=us,a=n(c=>{e?t.push(c):i(()=>{s(c)})},"schedule"),o=n(()=>{let c=t;t=[],c.length&&i(()=>{r(()=>{c.forEach(u=>{s(u)})})})},"flush");return{batch:n(c=>{let u;e++;try{u=c()}finally{e--,e||o()}return u},"batch"),batchCalls:n(c=>(...u)=>{a(()=>{c(...u)})},"batchCalls"),schedule:a,setNotifyFunction:n(c=>{s=c},"setNotifyFunction"),setBatchNotifyFunction:n(c=>{r=c},"setBatchNotifyFunction"),setScheduler:n(c=>{i=c},"setScheduler")}}n(Br,"createNotifyManager");var v=Br();var $r=class extends Q{static{n(this,"OnlineManager")}#e=!0;#t;#s;constructor(){super(),this.#s=t=>{if(typeof window<"u"&&window.addEventListener){let e=n(()=>t(!0),"onlineListener"),s=n(()=>t(!1),"offlineListener");return window.addEventListener("online",e,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",e),window.removeEventListener("offline",s)}}}}onSubscribe(){this.#t||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#s=t,this.#t?.(),this.#t=t(this.setOnline.bind(this))}setOnline(t){this.#e!==t&&(this.#e=t,this.listeners.forEach(s=>{s(t)}))}isOnline(){return this.#e}},de=new $r;function Hr(t){return Math.min(1e3*2**t,3e4)}n(Hr,"defaultRetryDelay");function ut(t){return(t??"online")==="online"?de.isOnline():!0}n(ut,"canFetch");var _e=class extends Error{static{n(this,"CancelledError")}constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function Le(t){let e=!1,s=0,r,i=we(),a=n(()=>i.status!=="pending","isResolved"),o=n(y=>{if(!a()){let S=new _e(y);f(S),t.onCancel?.(S)}},"cancel"),c=n(()=>{e=!0},"cancelRetry"),u=n(()=>{e=!1},"continueRetry"),d=n(()=>oe.isFocused()&&(t.networkMode==="always"||de.isOnline())&&t.canRun(),"canContinue"),h=n(()=>ut(t.networkMode)&&t.canRun(),"canStart"),l=n(y=>{a()||(r?.(),i.resolve(y))},"resolve"),f=n(y=>{a()||(r?.(),i.reject(y))},"reject"),p=n(()=>new Promise(y=>{r=n(S=>{(a()||d())&&y(S)},"continueFn"),t.onPause?.()}).then(()=>{r=void 0,a()||t.onContinue?.()}),"pause"),m=n(()=>{if(a())return;let y,S=s===0?t.initialPromise:void 0;try{y=S??t.fn()}catch(w){y=Promise.reject(w)}Promise.resolve(y).then(l).catch(w=>{if(a())return;let k=t.retry??(B.isServer()?0:3),E=t.retryDelay??Hr,H=typeof E=="function"?E(s,w):E,W=k===!0||typeof k=="number"&&s<k||typeof k=="function"&&k(s,w);if(e||!W){f(w);return}s++,t.onFail?.(s,w),ns(H).then(()=>d()?void 0:p()).then(()=>{e?f(w):m()})})},"run");return{promise:i,status:n(()=>i.status,"status"),cancel:o,continue:n(()=>(r?.(),i),"continue"),cancelRetry:c,continueRetry:u,canStart:h,start:n(()=>(h()?m():p().then(m),i),"start")}}n(Le,"createRetryer");var De=class{static{n(this,"Removable")}#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ge(this.gcTime)&&(this.#e=N.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(B.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(N.clearTimeout(this.#e),this.#e=void 0)}};function ds(t){return{onFetch:n((e,s)=>{let r=e.options,i=e.fetchOptions?.meta?.fetchMore?.direction,a=e.state.data?.pages||[],o=e.state.data?.pageParams||[],c={pages:[],pageParams:[]},u=0,d=n(async()=>{let h=!1,l=n(m=>{cs(m,()=>e.signal,()=>h=!0)},"addSignalProperty"),f=Qe(e.options,e.fetchOptions),p=n(async(m,y,S)=>{if(h)return Promise.reject(e.signal.reason);if(y==null&&m.pages.length)return Promise.resolve(m);let k=n(()=>{let pe={client:e.client,queryKey:e.queryKey,pageParam:y,direction:S?"backward":"forward",meta:e.options.meta};return l(pe),pe},"createQueryFnContext")(),E=await f(k),{maxPages:H}=e.options,W=S?os:as;return{pages:W(m.pages,E,H),pageParams:W(m.pageParams,y,H)}},"fetchPage");if(i&&a.length){let m=i==="backward",y=m?Wr:hs,S={pages:a,pageParams:o},w=y(r,S);c=await p(S,w,m)}else{let m=t??a.length;do{let y=u===0?o[0]??r.initialPageParam:hs(r,c);if(u>0&&y==null)break;c=await p(c,y),u++}while(u<m)}return c},"fetchFn");e.options.persister?e.fetchFn=()=>e.options.persister?.(d,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},s):e.fetchFn=d},"onFetch")}}n(ds,"infiniteQueryBehavior");function hs(t,{pages:e,pageParams:s}){let r=e.length-1;return e.length>0?t.getNextPageParam(e[r],e,s[r],s):void 0}n(hs,"getNextPageParam");function Wr(t,{pages:e,pageParams:s}){return e.length>0?t.getPreviousPageParam?.(e[0],e,s[0],s):void 0}n(Wr,"getPreviousPageParam");var ps=class extends De{static{n(this,"Query")}#e;#t;#s;#r;#n;#i;#o;#a;constructor(t){super(),this.#a=!1,this.#o=t.defaultOptions,this.setOptions(t.options),this.observers=[],this.#n=t.client,this.#r=this.#n.getQueryCache(),this.queryKey=t.queryKey,this.queryHash=t.queryHash,this.#t=fs(this.options),this.state=t.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#i?.promise}setOptions(t){if(this.options={...this.#o,...t},t?._type&&(this.#e=t._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=fs(this.options);e.data!==void 0&&(this.setState(ls(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#r.remove(this)}setData(t,e){let s=Se(this.state.data,t,this.options);return this.#c({data:s,type:"success",dataUpdatedAt:e?.updatedAt,manual:e?.manual}),s}setState(t){this.#c({type:"setState",state:t})}cancel(t){let e=this.#i?.promise;return this.#i?.cancel(t),e?e.then(C).catch(C):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>R(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===ue||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>K(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!Pe(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#i?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#i?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),this.#r.notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(e=>e!==t),this.observers.length||(this.#i&&(this.#a||this.#h()?this.#i.cancel({revert:!0}):this.#i.cancelRetry()),this.scheduleGc()),this.#r.notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}#h(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#c({type:"invalidate"})}async fetch(t,e){if(this.state.fetchStatus!=="idle"&&this.#i?.status()!=="rejected"){if(this.state.data!==void 0&&e?.cancelRefetch)this.cancel({silent:!0});else if(this.#i)return this.#i.continueRetry(),this.#i.promise}if(t&&this.setOptions(t),!this.options.queryFn){let u=this.observers.find(d=>d.options.queryFn);u&&this.setOptions(u.options)}let s=new AbortController,r=n(u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:n(()=>(this.#a=!0,s.signal),"get")})},"addSignalProperty"),i=n(()=>{let u=Qe(this.options,e),h=n(()=>{let l={client:this.#n,queryKey:this.queryKey,meta:this.meta};return r(l),l},"createQueryFnContext")();return this.#a=!1,this.options.persister?this.options.persister(u,h,this):u(h)},"fetchFn"),o=n(()=>{let u={fetchOptions:e,options:this.options,queryKey:this.queryKey,client:this.#n,state:this.state,fetchFn:i};return r(u),u},"createFetchContext")();(this.#e==="infinite"?ds(this.options.pages):this.options.behavior)?.onFetch(o,this),this.#s=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#c({type:"fetch",meta:o.fetchOptions?.meta}),this.#i=Le({initialPromise:e?.initialPromise,fn:o.fetchFn,onCancel:n(u=>{u instanceof _e&&u.revert&&this.setState({...this.#s,fetchStatus:"idle"}),s.abort()},"onCancel"),onFail:n((u,d)=>{this.#c({type:"failed",failureCount:u,error:d})},"onFail"),onPause:n(()=>{this.#c({type:"pause"})},"onPause"),onContinue:n(()=>{this.#c({type:"continue"})},"onContinue"),retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:n(()=>!0,"canRun")});try{let u=await this.#i.start();if(u===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(u),this.#r.config.onSuccess?.(u,this),this.#r.config.onSettled?.(u,this.state.error,this),u}catch(u){if(u instanceof _e){if(u.silent)return this.#i.promise;if(u.revert){if(this.state.data===void 0)throw u;return this.state.data}}throw this.#c({type:"error",error:u}),this.#r.config.onError?.(u,this),this.#r.config.onSettled?.(this.state.data,u,this),u}finally{this.scheduleGc()}}#c(t){let e=n(s=>{switch(t.type){case"failed":return{...s,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...ht(s.data,this.options),fetchMeta:t.meta??null};case"success":let r={...s,...ls(t.data,t.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#s=t.manual?r:void 0,r;case"error":let i=t.error;return{...s,error:i,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...t.state}}},"reducer");this.state=e(this.state),v.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),this.#r.notify({query:this,type:"updated",action:t})})}};function ht(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ut(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}n(ht,"fetchState");function ls(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}n(ls,"successState");function fs(t){let e=typeof t.initialData=="function"?t.initialData():t.initialData,s=e!==void 0,r=s?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:s?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:s?"success":"pending",fetchStatus:"idle"}}n(fs,"getDefaultState");var lt=class extends Q{static{n(this,"QueryObserver")}constructor(t,e){super(),this.options=e,this.#e=t,this.#a=null,this.#o=we(),this.bindMethods(),this.setOptions(e)}#e;#t=void 0;#s=void 0;#r=void 0;#n;#i;#o;#a;#h;#c;#p;#d;#l;#u;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),ms(this.#t,this.options)?this.#f():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return dt(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return dt(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#S(),this.#w(),this.#t.removeObserver(this)}setOptions(t){let e=this.options,s=this.#t;if(this.options=this.#e.defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof R(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#C(),this.#t.setOptions(this.options),e._defaulted&&!ce(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});let r=this.hasListeners();r&&ys(this.#t,s,this.options,e)&&this.#f(),this.updateResult(),r&&(this.#t!==s||R(this.options.enabled,this.#t)!==R(e.enabled,this.#t)||K(this.options.staleTime,this.#t)!==K(e.staleTime,this.#t))&&this.#y();let i=this.#b();r&&(this.#t!==s||R(this.options.enabled,this.#t)!==R(e.enabled,this.#t)||i!==this.#u)&&this.#g(i)}getOptimisticResult(t){let e=this.#e.getQueryCache().build(this.#e,t),s=this.createResult(e,t);return Vr(this,s)&&(this.#r=s,this.#i=this.options,this.#n=this.#t.state),s}getCurrentResult(){return this.#r}trackResult(t,e){return new Proxy(t,{get:n((s,r)=>(this.trackProp(r),e?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,r)),"get")})}trackProp(t){this.#m.add(t)}getCurrentQuery(){return this.#t}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let e=this.#e.defaultQueryOptions(t),s=this.#e.getQueryCache().build(this.#e,e);return s.fetch().then(()=>this.createResult(s,e))}fetch(t){return this.#f({...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#f(t){this.#C();let e=this.#t.fetch(this.options,t);return t?.throwOnError||(e=e.catch(C)),e}#y(){this.#S();let t=K(this.options.staleTime,this.#t);if(B.isServer()||this.#r.isStale||!ge(t))return;let s=Pe(this.#r.dataUpdatedAt,t)+1;this.#d=N.setTimeout(()=>{this.#r.isStale||this.updateResult()},s)}#b(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#g(t){this.#w(),this.#u=t,!(B.isServer()||R(this.options.enabled,this.#t)===!1||!ge(this.#u)||this.#u===0)&&(this.#l=N.setInterval(()=>{(this.options.refetchIntervalInBackground||oe.isFocused())&&this.#f()},this.#u))}#v(){this.#y(),this.#g(this.#b())}#S(){this.#d!==void 0&&(N.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#l!==void 0&&(N.clearInterval(this.#l),this.#l=void 0)}createResult(t,e){let s=this.#t,r=this.options,i=this.#r,a=this.#n,o=this.#i,u=t!==s?t.state:this.#s,{state:d}=t,h={...d},l=!1,f;if(e._optimisticResults){let I=this.hasListeners(),D=!I&&ms(t,e),J=I&&ys(t,s,e,r);(D||J)&&(h={...h,...ht(d.data,t.options)}),e._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:p,errorUpdatedAt:m,status:y}=h;f=h.data;let S=!1;if(e.placeholderData!==void 0&&f===void 0&&y==="pending"){let I;i?.isPlaceholderData&&e.placeholderData===o?.placeholderData?(I=i.data,S=!0):I=typeof e.placeholderData=="function"?e.placeholderData(this.#p?.state.data,this.#p):e.placeholderData,I!==void 0&&(y="success",f=Se(i?.data,I,e),l=!0)}if(e.select&&f!==void 0&&!S)if(i&&f===a?.data&&e.select===this.#h)f=this.#c;else try{this.#h=e.select,f=e.select(f),f=Se(i?.data,f,e),this.#c=f,this.#a=null}catch(I){this.#a=I}this.#a&&(p=this.#a,f=this.#c,m=Date.now(),y="error");let w=h.fetchStatus==="fetching",k=y==="pending",E=y==="error",H=k&&w,W=f!==void 0,L={status:y,fetchStatus:h.fetchStatus,isPending:k,isSuccess:y==="success",isError:E,isInitialLoading:H,isLoading:H,data:f,dataUpdatedAt:h.dataUpdatedAt,error:p,errorUpdatedAt:m,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:h.dataUpdateCount>u.dataUpdateCount||h.errorUpdateCount>u.errorUpdateCount,isFetching:w,isRefetching:w&&!k,isLoadingError:E&&!W,isPaused:h.fetchStatus==="paused",isPlaceholderData:l,isRefetchError:E&&W,isStale:ft(t,e),refetch:this.refetch,promise:this.#o,isEnabled:R(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let I=L.data!==void 0,D=L.status==="error"&&!I,J=n(Oe=>{D?Oe.reject(L.error):I&&Oe.resolve(L.data)},"finalizeThenableIfPossible"),Vt=n(()=>{let Oe=this.#o=L.promise=we();J(Oe)},"recreateThenable"),Ee=this.#o;switch(Ee.status){case"pending":t.queryHash===s.queryHash&&J(Ee);break;case"fulfilled":(D||L.data!==Ee.value)&&Vt();break;case"rejected":(!D||L.error!==Ee.reason)&&Vt();break}}return L}updateResult(){let t=this.#r,e=this.createResult(this.#t,this.options);if(this.#n=this.#t.state,this.#i=this.options,this.#n.data!==void 0&&(this.#p=this.#t),ce(e,t))return;this.#r=e;let s=n(()=>{if(!t)return!0;let{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#m.size)return!0;let a=new Set(i??this.#m);return this.options.throwOnError&&a.add("error"),Object.keys(this.#r).some(o=>{let c=o;return this.#r[c]!==t[c]&&a.has(c)})},"shouldNotifyListeners");this.#k({listeners:s()})}#C(){let t=this.#e.getQueryCache().build(this.#e,this.options);if(t===this.#t)return;let e=this.#t;this.#t=t,this.#s=t.state,this.hasListeners()&&(e?.removeObserver(this),t.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#v()}#k(t){v.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function zr(t,e){return R(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&R(e.retryOnMount,t)===!1)}n(zr,"shouldLoadOnMount");function ms(t,e){return zr(t,e)||t.state.data!==void 0&&dt(t,e,e.refetchOnMount)}n(ms,"shouldFetchOnMount");function dt(t,e,s){if(R(e.enabled,t)!==!1&&K(e.staleTime,t)!=="static"){let r=typeof s=="function"?s(t):s;return r==="always"||r!==!1&&ft(t,e)}return!1}n(dt,"shouldFetchOn");function ys(t,e,s,r){return(t!==e||R(r.enabled,t)===!1)&&(!s.suspense||t.state.status!=="error")&&ft(t,s)}n(ys,"shouldFetchOptionally");function ft(t,e){return R(e.enabled,t)!==!1&&t.isStaleByTime(K(e.staleTime,t))}n(ft,"isStale");function Vr(t,e){return!ce(t.getCurrentResult(),e)}n(Vr,"shouldAssignObserverCurrentProperties");var bs=class extends De{static{n(this,"Mutation")}#e;#t;#s;#r;constructor(t){super(),this.#e=t.client,this.mutationId=t.mutationId,this.#s=t.mutationCache,this.#t=[],this.state=t.state||pt(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){this.#t.includes(t)||(this.#t.push(t),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){this.#t=this.#t.filter(e=>e!==t),this.scheduleGc(),this.#s.notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#s.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(t){let e=n(()=>{this.#n({type:"continue"})},"onContinue"),s={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#r=Le({fn:n(()=>this.options.mutationFn?this.options.mutationFn(t,s):Promise.reject(new Error("No mutationFn found")),"fn"),onFail:n((a,o)=>{this.#n({type:"failed",failureCount:a,error:o})},"onFail"),onPause:n(()=>{this.#n({type:"pause"})},"onPause"),onContinue:e,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:n(()=>this.#s.canRun(this),"canRun")});let r=this.state.status==="pending",i=!this.#r.canStart();try{if(r)e();else{this.#n({type:"pending",variables:t,isPaused:i}),this.#s.config.onMutate&&await this.#s.config.onMutate(t,this,s);let o=await this.options.onMutate?.(t,s);o!==this.state.context&&this.#n({type:"pending",context:o,variables:t,isPaused:i})}let a=await this.#r.start();return await this.#s.config.onSuccess?.(a,t,this.state.context,this,s),await this.options.onSuccess?.(a,t,this.state.context,s),await this.#s.config.onSettled?.(a,null,this.state.variables,this.state.context,this,s),await this.options.onSettled?.(a,null,t,this.state.context,s),this.#n({type:"success",data:a}),a}catch(a){try{await this.#s.config.onError?.(a,t,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onError?.(a,t,this.state.context,s)}catch(o){Promise.reject(o)}try{await this.#s.config.onSettled?.(void 0,a,this.state.variables,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,a,t,this.state.context,s)}catch(o){Promise.reject(o)}throw this.#n({type:"error",error:a}),a}finally{this.#s.runNext(this)}}#n(t){let e=n(s=>{switch(t.type){case"failed":return{...s,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...s,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:t.error,failureCount:s.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}},"reducer");this.state=e(this.state),v.batch(()=>{this.#t.forEach(s=>{s.onMutationUpdate(t)}),this.#s.notify({mutation:this,type:"updated",action:t})})}};function pt(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}n(pt,"getDefaultState");var gs=class extends Q{static{n(this,"MutationCache")}constructor(t={}){super(),this.config=t,this.#e=new Set,this.#t=new Map,this.#s=0}#e;#t;#s;build(t,e,s){let r=new bs({client:t,mutationCache:this,mutationId:++this.#s,options:t.defaultMutationOptions(e),state:s});return this.add(r),r}add(t){this.#e.add(t);let e=Ue(t);if(typeof e=="string"){let s=this.#t.get(e);s?s.push(t):this.#t.set(e,[t])}this.notify({type:"added",mutation:t})}remove(t){if(this.#e.delete(t)){let e=Ue(t);if(typeof e=="string"){let s=this.#t.get(e);if(s)if(s.length>1){let r=s.indexOf(t);r!==-1&&s.splice(r,1)}else s[0]===t&&this.#t.delete(e)}}this.notify({type:"removed",mutation:t})}canRun(t){let e=Ue(t);if(typeof e=="string"){let r=this.#t.get(e)?.find(i=>i.state.status==="pending");return!r||r===t}else return!0}runNext(t){let e=Ue(t);return typeof e=="string"?this.#t.get(e)?.find(r=>r!==t&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){v.batch(()=>{this.#e.forEach(t=>{this.notify({type:"removed",mutation:t})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(t){let e={exact:!0,...t};return this.getAll().find(s=>xe(e,s))}findAll(t={}){return this.getAll().filter(e=>xe(t,e))}notify(t){v.batch(()=>{this.listeners.forEach(e=>{e(t)})})}resumePausedMutations(){let t=this.getAll().filter(e=>e.state.isPaused);return v.batch(()=>Promise.all(t.map(e=>e.continue().catch(C))))}};function Ue(t){return t.options.scope?.id}n(Ue,"scopeFor");var mt=class extends Q{static{n(this,"MutationObserver")}#e;#t=void 0;#s;#r;constructor(t,e){super(),this.#e=t,this.setOptions(e),this.bindMethods(),this.#n()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let e=this.options;this.options=this.#e.defaultMutationOptions(t),ce(this.options,e)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#s,observer:this}),e?.mutationKey&&this.options.mutationKey&&j(e.mutationKey)!==j(this.options.mutationKey)?this.reset():this.#s?.state.status==="pending"&&this.#s.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#s?.removeObserver(this)}onMutationUpdate(t){this.#n(),this.#i(t)}getCurrentResult(){return this.#t}reset(){this.#s?.removeObserver(this),this.#s=void 0,this.#n(),this.#i()}mutate(t,e){return this.#r=e,this.#s?.removeObserver(this),this.#s=this.#e.getMutationCache().build(this.#e,this.options),this.#s.addObserver(this),this.#s.execute(t)}#n(){let t=this.#s?.state??pt();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#i(t){v.batch(()=>{if(this.#r&&this.hasListeners()){let e=this.#t.variables,s=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{this.#r.onSuccess?.(t.data,e,s,r)}catch(i){Promise.reject(i)}try{this.#r.onSettled?.(t.data,null,e,s,r)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{this.#r.onError?.(t.error,e,s,r)}catch(i){Promise.reject(i)}try{this.#r.onSettled?.(void 0,t.error,e,s,r)}catch(i){Promise.reject(i)}}}this.listeners.forEach(e=>{e(this.#t)})})}};var vs=class extends Q{static{n(this,"QueryCache")}constructor(t={}){super(),this.config=t,this.#e=new Map}#e;build(t,e,s){let r=e.queryKey,i=e.queryHash??ve(r,e),a=this.get(i);return a||(a=new ps({client:t,queryKey:r,queryHash:i,options:t.defaultQueryOptions(e),state:s,defaultOptions:t.getQueryDefaults(r)}),this.add(a)),a}add(t){this.#e.has(t.queryHash)||(this.#e.set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let e=this.#e.get(t.queryHash);e&&(t.destroy(),e===t&&this.#e.delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){v.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return this.#e.get(t)}getAll(){return[...this.#e.values()]}find(t){let e={exact:!0,...t};return this.getAll().find(s=>Me(e,s))}findAll(t={}){let e=this.getAll();return Object.keys(t).length>0?e.filter(s=>Me(t,s)):e}notify(t){v.batch(()=>{this.listeners.forEach(e=>{e(t)})})}onFocus(){v.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){v.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}};var yt=class{static{n(this,"QueryClient")}#e;#t;#s;#r;#n;#i;#o;#a;constructor(t={}){this.#e=t.queryCache||new vs,this.#t=t.mutationCache||new gs,this.#s=t.defaultOptions||{},this.#r=new Map,this.#n=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#o=oe.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#a=de.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#i--,this.#i===0&&(this.#o?.(),this.#o=void 0,this.#a?.(),this.#a=void 0)}isFetching(t){return this.#e.findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return this.#t.findAll({...t,status:"pending"}).length}getQueryData(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state.data}ensureQueryData(t){let e=this.defaultQueryOptions(t),s=this.#e.build(this,e),r=s.state.data;return r===void 0?this.fetchQuery(t):(t.revalidateIfStale&&s.isStaleByTime(K(e.staleTime,s))&&this.prefetchQuery(e),Promise.resolve(r))}getQueriesData(t){return this.#e.findAll(t).map(({queryKey:e,state:s})=>{let r=s.data;return[e,r]})}setQueryData(t,e,s){let r=this.defaultQueryOptions({queryKey:t}),a=this.#e.get(r.queryHash)?.state.data,o=is(e,a);if(o!==void 0)return this.#e.build(this,r).setData(o,{...s,manual:!0})}setQueriesData(t,e,s){return v.batch(()=>this.#e.findAll(t).map(({queryKey:r})=>[r,this.setQueryData(r,e,s)]))}getQueryState(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state}removeQueries(t){let e=this.#e;v.batch(()=>{e.findAll(t).forEach(s=>{e.remove(s)})})}resetQueries(t,e){let s=this.#e;return v.batch(()=>(s.findAll(t).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){let s={revert:!0,...e},r=v.batch(()=>this.#e.findAll(t).map(i=>i.cancel(s)));return Promise.all(r).then(C).catch(C)}invalidateQueries(t,e={}){return v.batch(()=>(this.#e.findAll(t).forEach(s=>{s.invalidate()}),t?.refetchType==="none"?Promise.resolve():this.refetchQueries({...t,type:t?.refetchType??t?.type??"active"},e)))}refetchQueries(t,e={}){let s={...e,cancelRefetch:e.cancelRefetch??!0},r=v.batch(()=>this.#e.findAll(t).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let a=i.fetch(void 0,s);return s.throwOnError||(a=a.catch(C)),i.state.fetchStatus==="paused"?Promise.resolve():a}));return Promise.all(r).then(C)}fetchQuery(t){let e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);let s=this.#e.build(this,e);return s.isStaleByTime(K(e.staleTime,s))?s.fetch(e):Promise.resolve(s.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(C).catch(C)}fetchInfiniteQuery(t){return t._type="infinite",this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(C).catch(C)}ensureInfiniteQueryData(t){return t._type="infinite",this.ensureQueryData(t)}resumePausedMutations(){return de.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#s}setDefaultOptions(t){this.#s=t}setQueryDefaults(t,e){this.#r.set(j(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){let e=[...this.#r.values()],s={};return e.forEach(r=>{X(t,r.queryKey)&&Object.assign(s,r.defaultOptions)}),s}setMutationDefaults(t,e){this.#n.set(j(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){let e=[...this.#n.values()],s={};return e.forEach(r=>{X(t,r.mutationKey)&&Object.assign(s,r.defaultOptions)}),s}defaultQueryOptions(t){if(t._defaulted)return t;let e={...this.#s.queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=ve(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===ue&&(e.enabled=!1),e}defaultMutationOptions(t){return t?._defaulted?t:{...this.#s.mutations,...t?.mutationKey&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}};var Z=x(Y(),1);var Ce=x(Y(),1),Gr=x(rt(),1);function Jr(){let t=!1;return{clearReset:n(()=>{t=!1},"clearReset"),reset:n(()=>{t=!0},"reset"),isReset:n(()=>t,"isReset")}}n(Jr,"createValue");var Yr=Ce.createContext(Jr()),Ss=n(()=>Ce.useContext(Yr),"useQueryErrorResetBoundary");var ws=x(Y(),1);var Cs=n((t,e,s)=>{let r=s?.state.error&&typeof t.throwOnError=="function"?he(t.throwOnError,[s.state.error,s]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||r)&&(e.isReset()||(t.retryOnMount=!1))},"ensurePreventErrorBoundaryRetry"),ks=n(t=>{ws.useEffect(()=>{t.clearReset()},[t])},"useClearResetErrorBoundary"),Ts=n(({result:t,errorResetBoundary:e,throwOnError:s,query:r,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&r&&(i&&t.data===void 0||he(s,[t.error,r])),"getHasError");var Ke=x(Y(),1);var Es=Ke.createContext(!1),Os=n(()=>Ke.useContext(Es),"useIsRestoring"),rh=Es.Provider;var Is=n(t=>{if(t.suspense){let s=n(i=>i==="static"?i:Math.max(i??1e3,1e3),"clamp"),r=t.staleTime;t.staleTime=typeof r=="function"?(...i)=>s(r(...i)):s(r),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},"ensureSuspenseTimers"),Rs=n((t,e)=>t.isLoading&&t.isFetching&&!e,"willFetch"),As=n((t,e)=>t?.suspense&&e.isPending,"shouldSuspend"),bt=n((t,e,s)=>e.fetchOptimistic(t).catch(()=>{s.clearReset()}),"fetchOptimistic");function Fs(t,e,s){let r=Os(),i=Ss(),a=be(s),o=a.defaultQueryOptions(t);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let c=a.getQueryCache().get(o.queryHash),u=t.subscribed!==!1;o._optimisticResults=r?"isRestoring":u?"optimistic":void 0,Is(o),Cs(o,i,c),ks(i);let d=!a.getQueryCache().get(o.queryHash),[h]=Z.useState(()=>new e(a,o)),l=h.getOptimisticResult(o),f=!r&&u;if(Z.useSyncExternalStore(Z.useCallback(p=>{let m=f?h.subscribe(v.batchCalls(p)):C;return h.updateResult(),m},[h,f]),()=>h.getCurrentResult(),()=>h.getCurrentResult()),Z.useEffect(()=>{h.setOptions(o)},[o,h]),As(o,l))throw bt(o,h,i);if(Ts({result:l,errorResetBoundary:i,throwOnError:o.throwOnError,query:c,suspense:o.suspense}))throw l.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,l),o.experimental_prefetchInRender&&!B.isServer()&&Rs(l,r)&&(d?bt(o,h,i):c?.promise)?.catch(C).finally(()=>{h.updateResult()}),o.notifyOnChangeProps?l:h.trackResult(l)}n(Fs,"useBaseQuery");function Xr(t,e){return Fs(t,lt,e)}n(Xr,"useQuery");var z=x(Y(),1);function Zr(t,e){let s=be(e),[r]=z.useState(()=>new mt(s,t));z.useEffect(()=>{r.setOptions(t)},[r,t]);let i=z.useSyncExternalStore(z.useCallback(o=>r.subscribe(v.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=z.useCallback((o,c)=>{r.mutate(o,c).catch(C)},[r]);if(i.error&&he(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}n(Zr,"useMutation");var xs=x(Jt(),1);var F=x(Y(),1);var qe=n(t=>U(t),"o");var Ne=x(rt(),1);var Ps=n(t=>{t!==void 0&&(t.cancel({silent:!0}),t.setState({...t.state,data:void 0,dataUpdatedAt:0,error:null,fetchStatus:"idle",status:"pending"}))},"Q"),vt=class{static{n(this,"A")}constructor(e){this.client=e}client;entries=new Map;pushes=new Map;samples=new Map;identityWatched=new Set;listening=!1;hasConsumers(e){return this.entries.has(qe(e))}openSnapshotSample(e){let s=qe(e);return this.samples.set(s,(this.samples.get(s)??0)+1),{key:s,pushes:this.pushes.get(s)??0}}closeSnapshotSample(e){let s=(this.samples.get(e.key)??1)-1,r=(this.pushes.get(e.key)??0)===e.pushes;return s>0?(this.samples.set(e.key,s),r):(this.samples.delete(e.key),this.entries.has(e.key)||this.pushes.delete(e.key),r)}clearOnIdentityChange(e){this.listenForIdentityChange(),this.identityWatched.add(e)}stopClearingOnIdentityChange(e){this.identityWatched.delete(e)}subscribeIdentityEpoch=n(e=>(this.listenForIdentityChange(),this.client.onIdentityChange(e)),"subscribeIdentityEpoch");listenForIdentityChange(){this.listening||(this.listening=!0,this.client.onIdentityChange(()=>{for(let e of this.identityWatched)this.clearQueries(e)}))}clearQueries(e){let s=e.getQueryCache();for(let r of s.findAll({queryKey:["lunora"]}))Ps(r),r.getObserversCount()===0&&!this.hasConsumers(r.queryKey)&&s.remove(r)}attach(e,s,r,i,a,o={}){let c=qe(s),u=this.entries.get(c);if(!u){u={errorCallbacks:new Set,refCount:0,unsubscribe:void 0},this.entries.set(c,u);let l=u;try{u.unsubscribe=this.client.subscribe(r,i,f=>{if(this.pushes.set(c,(this.pushes.get(c)??0)+1),f===void 0){Ps(e.getQueryCache().find({exact:!0,queryKey:s}));return}e.setQueryData(s,f)},{onError:n(f=>{for(let p of l.errorCallbacks)p(f)},"onError"),shardKey:a})}catch(f){throw this.entries.delete(c),f}}u.refCount+=1;let{onError:d}=o;d&&u.errorCallbacks.add(d);let h=!1;return()=>{if(h)return;h=!0;let l=this.entries.get(c);l&&(l.refCount-=1,d&&l.errorCallbacks.delete(d),l.refCount<=0&&(l.unsubscribe?.(),this.entries.delete(c)))}}},Ms=new WeakMap,gt=n(t=>{let e=Ms.get(t);return e||(e=new vt(t),Ms.set(t,e)),e},"I"),Qs=(0,F.createContext)(null),ei=(0,F.createContext)(!1),ti=n(()=>new yt({defaultOptions:{mutations:{retry:0},queries:{gcTime:5*6e4,retry:0,staleTime:Number.POSITIVE_INFINITY}}}),"q"),si=n(t=>{let e=(0,xs.c)(20),{children:s,client:r,queryClient:i}=t,a=(0,F.use)(ye),o;e[0]!==a||e[1]!==i?(o=n(()=>i??a??ti(),"d"),e[0]=a,e[1]=i,e[2]=o):o=e[2];let[c]=(0,F.useState)(o),u=i??a??c,d,h;e[3]!==r||e[4]!==u?(d=n(()=>{gt(r).clearOnIdentityChange(u)},"u"),h=[r,u],e[3]=r,e[4]=u,e[5]=d,e[6]=h):(d=e[5],h=e[6]),(0,F.useEffect)(d,h);let l=(0,F.useRef)(r),f,p;e[7]!==r||e[8]!==u?(f=n(()=>{l.current!==r&&(gt(l.current).stopClearingOnIdentityChange(u),l.current=r,gt(r).clearQueries(u),u.invalidateQueries({queryKey:["lunora"]}))},"o"),p=[r,u],e[7]=r,e[8]=u,e[9]=f,e[10]=p):(f=e[9],p=e[10]),(0,F.useEffect)(f,p);let[m]=(0,F.useState)(r),y=r!==m,S;e[11]!==s||e[12]!==y?(S=(0,Ne.jsx)(ei,{value:y,children:s}),e[11]=s,e[12]=y,e[13]=S):S=e[13];let w;e[14]!==r||e[15]!==S?(w=(0,Ne.jsx)(Qs,{value:r,children:S}),e[14]=r,e[15]=S,e[16]=w):w=e[16];let k=w;if(a===u)return k;let E;return e[17]!==k||e[18]!==u?(E=(0,Ne.jsx)(nt,{client:u,children:k}),e[17]=k,e[18]=u,e[19]=E):E=e[19],E},"V");var St=n(()=>{let t=(0,F.use)(Qs);if(!t)throw new b("INTERNAL","useLunora must be used inside <LunoraProvider />");return t},"_");var P=n(t=>new Promise((e,s)=>{t.addEventListener("success",()=>{e(t.result)}),t.addEventListener("error",()=>{s(t.error??new Error("IndexedDB request failed"))})}),"c"),je=n((t,e,s,r)=>{let i;return()=>i||(i=new Promise((a,o)=>{let c=t.open(e,s);c.addEventListener("upgradeneeded",()=>{r(c.result)}),c.addEventListener("success",()=>{a(c.result)}),c.addEventListener("error",()=>{o(c.error??new Error("IndexedDB open failed"))})}),i)},"E"),Be=n((t,e)=>async(s,r)=>{let i=(await t()).transaction(e,s),a=await r(i.objectStore(e));return await new Promise((o,c)=>{i.addEventListener("complete",()=>{o()}),i.addEventListener("error",()=>{c(i.error??new Error("IndexedDB transaction failed"))}),i.addEventListener("abort",()=>{c(i.error??new Error("IndexedDB transaction aborted"))})}),a},"u");var ne=n((t,e,s)=>`${t}::${e}::${s??""}`,"T"),ri=500,ii=n((t,e)=>{if(!Number.isInteger(t)||t<1)throw new b("INTERNAL",`${e}: maxEntries must be a positive integer, got ${String(t)}`);return t},"E");var ni="lunora-query-cache",ai="query-cache",_s="by_ts",oi=1,ci=n((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new b("INTERNAL","createIndexedDbQueryCache: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryQueryCache()");let s=t.databaseName??ni,r=t.storeName??ai,i=ii(t.maxEntries??ri,"createIndexedDbQueryCache"),a=je(e,s,oi,u=>{u.objectStoreNames.contains(r)||u.createObjectStore(r,{keyPath:"key"}).createIndex(_s,"ts",{unique:!1})}),o=Be(a,r),c=n(async u=>{let d=await P(u.count())-i;d<=0||await new Promise((h,l)=>{let f=u.index(_s).openCursor();f.addEventListener("success",()=>{let p=f.result;if(!p||d<=0){h();return}p.delete(),d-=1,p.continue()}),f.addEventListener("error",()=>{l(f.error??new Error("IndexedDB eviction failed"))})})},"y");return{clear:n(async()=>{await o("readwrite",u=>P(u.clear()))},"clear"),load:n(async()=>o("readonly",u=>P(u.getAll())),"load"),put:n(async(u,d)=>{await o("readwrite",async h=>{await P(h.put({...d,key:u})),await c(h)})},"put"),remove:n(async u=>{await o("readwrite",d=>P(d.delete(u)))},"remove")}},"N"),Ls=n(t=>{if(t!==!1){if(t)return t;if(!(typeof indexedDB>"u"))return ci()}},"L");var Ds=n(()=>{let t=null;return{get:n(()=>t,"get"),set:n(e=>{t=e},"set")}},"r");var $e=class{static{n(this,"u")}values=new Map;subscribers=new Map;get(e){return this.values.has(e.key)?this.values.get(e.key):e.defaultValue}set(e,s){if(s===void 0){this.reset(e);return}this.values.set(e.key,s),this.notify(e.key,s)}reset(e){this.values.delete(e.key),this.notify(e.key,e.defaultValue)}clear(){this.values.clear(),this.subscribers.clear()}subscribe(e,s){let r=this.subscribers.get(e.key);return r||(r=new Set,this.subscribers.set(e.key,r)),r.add(s),()=>{r.delete(s),r.size===0&&this.subscribers.delete(e.key)}}notify(e,s){let r=this.subscribers.get(e);if(r)for(let i of r)try{i(s)}catch{}}};var Us=0,ui="lunora-bridge",hi=1e3,di=3e3,He=class{static{n(this,"l")}bc;tabId;heartbeatInterval;leaderTimeout;knownLeader=void 0;leader=!1;running=!1;promotionPending=!1;lastHeartbeat=0;heartbeatTimer=void 0;leaderCheckTimer=void 0;onBecomeLeader;onStopBeingLeader;onConnectionStatus;onSubscriptionData;onLeaderClaimAnswered;onSubscriptionError;onSubscriptionSettled;constructor(e={}){if(Us+=1,this.tabId=`tab_${String(Us)}_${crypto.randomUUID()}`,this.heartbeatInterval=e.heartbeatInterval??hi,this.leaderTimeout=e.leaderTimeout??di,this.onBecomeLeader=e.onBecomeLeader,this.onStopBeingLeader=e.onStopBeingLeader,this.onConnectionStatus=e.onConnectionStatus,this.onSubscriptionData=e.onSubscriptionData,this.onLeaderClaimAnswered=e.onLeaderClaimAnswered,this.onSubscriptionError=e.onSubscriptionError,this.onSubscriptionSettled=e.onSubscriptionSettled,typeof BroadcastChannel>"u"){this.bc=void 0;return}this.bc=new BroadcastChannel(e.channelName??ui),this.bc.addEventListener("message",s=>{this.handleMessage(s.data)})}start(){if(!this.running){if(this.running=!0,this.bc===void 0){this.becomeLeader();return}this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout),this.leaderCheckTimer=setInterval(()=>{this.checkLeaderHealth()},this.leaderTimeout),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeat()},this.heartbeatInterval)}}stop(){this.running=!1,this.leader&&(this.broadcast({type:"yield-leadership",tabId:this.tabId}),this.leader=!1,this.knownLeader=void 0,this.onStopBeingLeader?.()),this.heartbeatTimer!==void 0&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0),this.leaderCheckTimer!==void 0&&(clearInterval(this.leaderCheckTimer),this.leaderCheckTimer=void 0),this.bc?.close()}isLeader(){return this.leader}promoteImmediately(){this.running&&this.becomeLeader()}get leaderTabId(){return this.knownLeader}get id(){return this.tabId}get isRunning(){return this.running}broadcastSubscriptionData(e,s,r,i,a){this.leader&&this.broadcast({type:"subscription-data",tabId:this.tabId,key:e,data:s,...r===void 0?{}:{cursor:r},...i===void 0?{}:{epoch:i},...a===void 0?{}:{identity:a}})}broadcastSubscriptionError(e,s,r){this.leader&&this.broadcast({type:"subscription-error",tabId:this.tabId,key:e,error:s,...r===void 0?{}:{identity:r}})}broadcastSubscriptionSettled(e,s,r,i,a,o){this.leader&&this.broadcast({type:"subscription-settled",tabId:this.tabId,key:e,...s===void 0?{}:{cursor:s},...r===void 0?{}:{epoch:r},...i===void 0?{}:{lastMutationId:i},...a===void 0?{}:{clientId:a},...o===void 0?{}:{identity:o}})}broadcastConnectionStatus(e,s){this.leader&&this.broadcast({type:"connection-status",tabId:this.tabId,status:e,...s===void 0?{}:{identity:s}})}broadcast(e){this.bc?.postMessage(e)}handleMessage(e){switch(e.type){case"claim-leadership":{this.handleClaimLeadership(e);break}case"connection-status":{if(this.leader||e.tabId===this.tabId)break;this.onConnectionStatus?.(e.status,e.identity);break}case"heartbeat":{this.handleHeartbeat(e);break}case"subscription-data":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionData?.(e.key,e.data,e.cursor,e.epoch,e.identity);break}case"subscription-error":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionError?.(e.key,e.error,e.identity);break}case"subscription-settled":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionSettled?.(e.key,e.cursor,e.epoch,e.lastMutationId,e.clientId,e.identity);break}case"yield-leadership":{this.knownLeader===e.tabId&&(this.knownLeader=void 0,this.running&&!this.leader&&this.claimAndPromote());break}}}handleClaimLeadership(e){if(e.tabId!==this.tabId){if(this.leader){this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}),this.onLeaderClaimAnswered?.();return}this.knownLeader===void 0&&e.tabId<this.tabId&&(this.knownLeader=e.tabId,this.lastHeartbeat=e.ts)}}handleHeartbeat(e){if(e.tabId!==this.tabId){if(this.leader){this.resolveLeaderVsLeaderTieBreak(e);return}this.lastHeartbeat=e.ts,this.knownLeader=e.tabId}}resolveLeaderVsLeaderTieBreak(e){e.tabId<this.tabId?(this.leader=!1,this.knownLeader=e.tabId,this.lastHeartbeat=e.ts,this.onStopBeingLeader?.()):this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}becomeLeader(){this.leader||(this.leader=!0,this.knownLeader=this.tabId,this.lastHeartbeat=Date.now(),this.onBecomeLeader?.(),this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}))}sendHeartbeat(){this.leader&&this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}checkLeaderHealth(){if(!(!this.running||this.leader)){if(this.knownLeader===void 0){this.claimAndPromote();return}Date.now()-this.lastHeartbeat>this.leaderTimeout&&(this.knownLeader=void 0,this.claimAndPromote())}}claimAndPromote(){this.promotionPending||(this.promotionPending=!0,this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.promotionPending=!1,this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout))}};var li=n(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"y"),wt="_id",Ct="_creationTime",kt="page",Ks="pageDelta",fi=n(t=>{if(Array.isArray(t))return t;if(li(t)&&Array.isArray(t[kt]))return t[kt]},"g"),pi=n(t=>{let e;for(let s of t){let r=s[Ct];if(typeof r=="number"){if(e!==void 0){if(r<e)return!0;if(r>e)return!1}e=r}}return!1},"A"),mi=n((t,e)=>{let s=e[Ct];if(typeof s!="number")return t.length;let r=pi(t);for(let[i,a]of t.entries()){let o=a[Ct];if(typeof o=="number"&&(r?o<s:o>s))return i}return t.length},"x"),yi=n(t=>{if(typeof t!="object"||t===null)return;let e=t[wt];return typeof e=="string"?e:void 0},"b"),bi=n(t=>{if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.key=="string"&&typeof e.table=="string"&&(e.op==="insert"||e.op==="update"||e.op==="delete")},"D"),gi=n((t,e)=>{let s=[];for(let u of t){if(yi(u)===void 0)return;s.push(u)}let{key:r,op:i,row:a}=e;if(i==="delete"){let u=s.filter(d=>d[wt]!==r);return u.length===s.length?[...s]:u}if(a===void 0)return;let o=[...s],c=s.findIndex(u=>u[wt]===r);return c===-1?o.splice(mi(s,a),0,a):o[c]=a,o},"E"),vi=n((t,e)=>{let s=fi(t);if(s===void 0)return;let r=gi(s,e);return r===void 0||Array.isArray(t)?r:{...t,[kt]:r}},"I"),Tt=Symbol("lunora.unmergeableDelta"),qs=n((t,e)=>{if("data"in t&&t.data!==void 0)return T(t.data);let s=T(t.delta);return bi(s)?e===void 0?s:vi(e,s)??Tt:s},"P");var ed=new Set(Object.keys(Gt)),$=class extends b{static{n(this,"R")}constructor(e,s){super("INTERNAL",e,{data:s})}};var We=n(t=>{let e=t?.data?.retryAfterMs;return typeof e=="number"&&Number.isFinite(e)?e:void 0},"f"),Et=new Set(["TOKEN_EXPIRED","UNAUTHENTICATED"]),ze=n(t=>Et.has(t?.code??""),"u");var Si=1024,Ve=n(t=>{let e=t.maxBuffer??Si,s=[],r=[],i=!1,a,o=!1,c=n(()=>{let h=r.shift();if(!h)return!1;if(a)return h.reject(a),!0;if(s.length>0){let l=s.shift();return h.resolve({done:!1,value:l}),!0}return i?(h.resolve({done:!0,value:void 0}),!0):(r.unshift(h),!1)},"u"),u={complete(){if(!(i||a))for(i=!0;c(););},fail(h){if(!(i||a))for(a=h,s.length=0;c(););},push(h){if(!(i||a||o)){if(s.length>=e){u.fail(new b("STREAM_BACKPRESSURE",`stream buffer overflow (max=${e.toString()}); the consumer cannot keep up with the producer`));return}s.push(h),c()}}},d=n(()=>{if(!o){o=!0,i=!0,s.length=0;try{t.onCancel()}catch{}for(;c(););}},"c");return{handle:u,iterable:{cancel:d,[Symbol.asyncIterator](){return{next(){if(a)return Promise.reject(a);if(s.length>0){let h=s.shift();return Promise.resolve({done:!1,value:h})}return i?Promise.resolve({done:!0,value:void 0}):new Promise((h,l)=>{r.push({reject:l,resolve:h})})},return(){return d(),Promise.resolve({done:!0,value:void 0})}}}}}},"p");var Ns=/^ /u,js=n(t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),"h"),wi=n(t=>{let e="",s=[];for(let r of t.split(`
|
|
2
|
-
`))r.startsWith("event:")?e=r.slice(6).replace(Ns,""):r.startsWith("data:")&&s.push(r.slice(5).replace(Ns,""));return{data:s.join(`
|
|
3
|
-
`),event:e}},"S"),Ci=n((t,e,s)=>{let r=e.params??{},i=t.path.split("/").map(c=>{if(!c.startsWith(":"))return c;let u=c.slice(1),d=r[u];if(d===void 0)throw new b("HTTP_STREAM_MISSING_PARAM",`httpStream: missing path param ":${u}" for route ${t.path}`);return encodeURIComponent(js(d))}).join("/"),a=new URLSearchParams;for(let[c,u]of Object.entries(e.searchParams??{}))u!==void 0&&a.set(c,js(u));let o=a.toString();return`${s.endsWith("/")?s.slice(0,-1):s}${i}${o===""?"":`?${o}`}`},"T"),ki=n((t,e)=>{if(t.event==="complete")return e.complete(),!0;if(t.event==="error"){let s={};try{s=JSON.parse(t.data)}catch{}let r=typeof s.message=="string"?s.message:"stream error",i=typeof s.code=="string"?s.code:"HTTP_STREAM_ERROR";return e.fail(new b(i,r)),!0}if((t.event===""||t.event==="message")&&t.data!=="")try{e.push(T(JSON.parse(t.data)))}catch{return e.fail(new b("HTTP_STREAM_BAD_CHUNK","httpStream: malformed SSE chunk (invalid JSON)")),!0}return!1},"E"),Ti=n(async(t,e)=>{let s=t.getReader(),r=new TextDecoder,i="",a=!1,o=n(u=>{let d=a?`\r${u}`:u;a=d.endsWith("\r"),a&&(d=d.slice(0,-1)),i+=d.replaceAll(`\r
|
|
4
|
-
`,`
|
|
5
|
-
`)},"l"),c=n(()=>{let u=i.indexOf(`
|
|
6
|
-
|
|
7
|
-
`);for(;u!==-1;){let d=wi(i.slice(0,u));if(i=i.slice(u+2),ki(d,e))return!0;u=i.indexOf(`
|
|
8
|
-
|
|
9
|
-
`)}return!1},"d");for(;;){let{done:u,value:d}=await s.read();if(u)break;if(o(r.decode(d,{stream:!0})),c()){await s.cancel().catch(()=>{});return}}o(r.decode()),c()||e.fail(new b("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"))},"b"),Bs=n((t,e,s={})=>{let r=s.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!r)throw new b("INTERNAL","httpStream: no `fetch` implementation available");let i=Ci(t,e??{},s.baseUrl??""),a=new AbortController,o;s.signal&&(s.signal.aborted?a.abort():(o=n(()=>{a.abort()},"l"),s.signal.addEventListener("abort",o,{once:!0})));let c=n(()=>{o&&s.signal?.removeEventListener("abort",o)},"d"),{handle:u,iterable:d}=Ve({maxBuffer:s.maxBuffer,onCancel:n(()=>{a.abort()},"onCancel")});return(async()=>{try{let h=await r(i,{headers:{accept:"text/event-stream",...s.headers},method:t.method,signal:a.signal});if(!h.ok){await h.body?.cancel().catch(()=>{}),u.fail(new b("HTTP_STREAM_STATUS",`httpStream: request failed (status ${h.status.toString()})`,{status:h.status}));return}if(!h.body){u.fail(new b("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}await Ti(h.body,u)}finally{c()}})().catch(h=>{if(a.signal.aborted){u.complete();return}if(h instanceof Error&&"code"in h){u.fail(h);return}u.fail(new b("HTTP_STREAM_TRANSPORT",h instanceof Error?h.message:String(h),{cause:h}))}),d},"_");var M=class t{static{n(this,"t")}static key(e,s,r){return`${e}::${U(s)}::${r??""}`}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 s=t.keyOf(e);this.byKey.get(s)===e&&this.byKey.delete(s),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}clear(){this.byKey.clear(),this.byId.clear()}};function Ge(t){if(t!==void 0)return e=>{t(e)}}n(Ge,"b");var V=n((t,e)=>{for(let s of t)try{s(e)}catch{}},"d");var Ot=0,$s=n(()=>Ot,"h"),Ei=n((t,e)=>{let s=t;for(let r of e)try{s=r.transform(s)}catch{}return s},"p"),Hs=n((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let s of t.callbacks)try{s(e)}catch{}}},"d"),ee=n((t,e)=>{Hs(t,Ei(e,t.optimisticLayers))},"y"),It=n((t,e)=>{let s;try{s=e(t.lastValue)}catch{return}let r={id:Symbol("optimistic"),transform:e},i=!1;t.optimisticLayers.push(r),Hs(t,s);let a=n(()=>{let c=t.optimisticLayers.findIndex(u=>u.id===r.id);return c===-1?!1:(t.optimisticLayers.splice(c,1),!0)},"l"),o=n(()=>{ee(t,t.serverBase)},"s");return{confirm:n(c=>{if(c===void 0){a();return}r.commitCursor=c,Ot+=1,r.acknowledgedAt=Ot,t.serverCursor!==void 0&&t.serverCursor>=c&&a()&&o()},"confirm"),rollback:n(()=>{i||(i=!0,a(),o())},"rollback")}},"g"),Je=n((t,e)=>{if(e===void 0||t.optimisticLayers.length===0)return!1;let s=t.optimisticLayers.length;return t.optimisticLayers=t.optimisticLayers.filter(r=>r.commitCursor===void 0||r.commitCursor>e),t.optimisticLayers.length!==s},"k"),Ws=n((t,e)=>{t.optimisticLayers.length!==0&&(t.optimisticLayers=t.optimisticLayers.filter(s=>s.acknowledgedAt===void 0||s.acknowledgedAt>e))},"b"),le=n(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"v"),zs=n((t,e)=>{let s=[],r=[],i=n((a,o)=>t.get(M.key(a,o,e)),"c");return{confirms:s,rollbacks:r,store:{getAllQueries:n(a=>{let o=[];for(let c of t.all())c.fn.__lunoraRef===a.__lunoraRef&&(c.shardKey??"")===(e??"")&&o.push({args:c.args,value:c.lastValue});return o},"getAllQueries"),getQuery:n((a,o)=>i(a.__lunoraRef,o??{})?.lastValue,"getQuery"),setQuery:n((a,o,c)=>{let u=i(a.__lunoraRef,o??{});if(!u)return;let d=It(u,()=>c);d&&(s.push(d.confirm),r.push(d.rollback))},"setQuery")}}},"_");var Rt=n(t=>{if(t===null)return;let e=Number(t);if(Number.isFinite(e))return e>0?e*1e3:void 0;let s=Date.parse(t);if(Number.isNaN(s))return;let r=s-Date.now();return r>0?r:void 0},"f"),Oi=n((t,e)=>{let s=Rt(e);if(!(s===void 0||We(t)!==void 0))return t.data===void 0?{retryAfterMs:s}:typeof t.data=="object"&&t.data!==null&&!Array.isArray(t.data)?{...t.data,retryAfterMs:s}:void 0},"v"),fe=n(t=>{let e=t?.error;return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0},"l"),Ii=n(()=>new $("LunoraClient: batch slot carried no error envelope"),"m"),Vs=n((t,e)=>{let s=t.error,r=typeof s?.code=="string"?s.code:void 0,i=typeof s?.message=="string"?s.message:void 0;return{code:r,messageText:(typeof t.message=="string"?t.message:void 0)??i??e}},"s"),Gs=n(t=>{let{code:e,messageText:s}=Vs(t,"stream error");return e===void 0?new Error(s):new b(e,s)},"g"),At=n(t=>{let{code:e,messageText:s}=Vs(t,"subscription error");return{message:s,...e===void 0?{}:{code:e}}},"A"),Ye=n(t=>{let e=new Error(t.message??"request failed");if(e.code=t.code,t.data!==void 0)try{e.data=T(t.data)}catch{}return t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),e},"n"),Ft=n((t,e)=>{let s=Ye(t),r=Oi(s,e);return r!==void 0&&(s.data=r),s},"y"),Xe=n(t=>{let e=fe(t);return e===void 0?Ii():Ye(e)},"h");var Js=0,Ri=n(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();Js+=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)}_${Js.toString(36)}_${t}`},"d"),Pt=n((t,e)=>t!==void 0&&e!==t,"f"),et=Ri,te=n((t,e,s,r)=>{if(t)try{t({error:s,mutationId:r,operation:e});return}catch{}console.warn(`[lunora] offline-queue persistence ${e} failed`,s)},"o"),Ze=class{static{n(this,"l")}queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;version;items=[];constructor(e={},s={}){this.maxItems=e.maxItems??1e3,this.queueBeforeFirstConnect=e.queueBeforeFirstConnect??!1,this.onPersistenceError=e.onPersistenceError,this.persistence=s.persistence,this.onEvict=s.onEvict,this.onSizeChange=s.onSizeChange,this.version=s.version}get size(){return this.items.length}enqueue(e){let s=e;s.id??=et(),this.items.push(s),this.persistence?.append({args:s.args,...s.baselineSeq===void 0?{}:{baselineSeq:s.baselineSeq},clientId:s.clientId,functionPath:s.functionPath,id:s.id,identity:s.identity,shardKey:s.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(r=>{te(this.onPersistenceError,"append",r,s.id)}),this.evictOverflow(),this.notifySize()}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(o){throw te(this.onPersistenceError,"load",o),o}let s=[],r=new Set(this.items.map(o=>o.id));for(let o of e)if(!r.has(o.id)){if(Pt(this.version,o.version)){this.persistence.remove(o.id).catch(c=>{te(this.onPersistenceError,"remove",c,o.id)});continue}r.add(o.id),s.push({args:o.args,baselineSeq:o.baselineSeq,clientId:o.clientId,functionPath:o.functionPath,id:o.id,identity:o.identity,reject:n(()=>{},"reject"),resolve:n(()=>{},"resolve"),shardKey:o.shardKey})}this.items.unshift(...s),this.evictOverflow(),this.notifySize();let i=new Set(this.items),a=new Set;for(let o of s)i.has(o)&&a.add(o.shardKey);return[...a]}restampIdentity(e,s){for(let r of this.items){if(r.identity!==e)continue;r.identity=s;let{id:i}=r;if(!this.persistence||i===void 0)continue;let a={args:r.args,...r.baselineSeq===void 0?{}:{baselineSeq:r.baselineSeq},clientId:r.clientId,functionPath:r.functionPath,id:i,identity:s,shardKey:r.shardKey,...this.version===void 0?{}:{version:this.version}};this.rewriteStamp(i,a).catch(o=>{te(this.onPersistenceError,"replace",o,i)})}}hasPending(e){return this.items.some(s=>e(s))}drain(e){if(!e){let i=[...this.items];return this.items.length=0,this.notifySize(),i}let s=[],r=[];for(let i of this.items)(e(i)?s:r).push(i);return this.items.length=0,this.items.push(...r),this.notifySize(),s}requeue(e){e.length!==0&&(this.items.unshift(...e),this.notifySize())}drainConflict(){let e=[],s=[];for(let r of this.items)if(r.precondition!==void 0&&!r.precondition()){let i=new Error("offline mutation skipped: precondition failed before replay");i.code="OFFLINE_PRECONDITION_FAILED",r.reject(i),e.push(r)}else s.push(r);return e.length>0&&(this.items.length=0,this.items.push(...s),this.notifySize()),e}clear(){for(let e of this.items){let s=new Error("CLIENT_CLOSED");s.code="CLIENT_CLOSED",e.reject(s)}this.items.length=0,this.notifySize()}async rewriteStamp(e,s){let r=this.persistence;if(r)try{await r.replace(s)}catch(i){te(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(r=>{te(this.onPersistenceError,"remove",r,e.id)});let s=new Error("offline queue overflow");s.code="OFFLINE_QUEUE_OVERFLOW",e.reject(s),this.onEvict?.(e,s)}}}notifySize(){this.onSizeChange?.(this.items.length)}};var Ai="lunora-outbox",Fi="offline-mutations",Mt="by_id",Pi=n((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new b("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let s=t.databaseName??Ai,r=t.storeName??Fi,i=je(e,s,1,o=>{o.objectStoreNames.contains(r)||o.createObjectStore(r,{autoIncrement:!0}).createIndex(Mt,"id",{unique:!0})}),a=Be(i,r);return{append:n(async o=>{await a("readwrite",c=>P(c.add(o)))},"append"),clear:n(async()=>{await a("readwrite",o=>P(o.clear()))},"clear"),load:n(async()=>a("readonly",o=>P(o.getAll())),"load"),remove:n(async o=>{await a("readwrite",async c=>{let u=await P(c.index(Mt).getKey(o));u!==void 0&&await P(c.delete(u))})},"remove"),replace:n(async o=>{await a("readwrite",async c=>{let u=await P(c.index(Mt).getKey(o.id));u!==void 0&&await P(c.put(o,u))})},"replace")}},"w"),Ys=n((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return Pi()}},"b");var xt=n((t={},e=Math.random)=>{let s=t.initialDelayMs??250,r=t.maxDelayMs??3e4,i=t.jitter??!0,a=0;return{next(){let o=Math.min(r,s*2**a);if(a+=1,!i)return o;let c=o/2;return Math.floor(c+e()*(o-c))},reset(){a=0}}},"s");var Xs=n((t,e,s,r)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r),a=i.present?U(i.value):void 0;return()=>{let o=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r);return!i.present||!o.present?!0:U(o.value)===a}},"c");var Qt=500,ar=n((t,e)=>{if(t.size<e)return;let s=t.keys().next().value;s!==void 0&&t.delete(s)},"ge"),G="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Mi=n(t=>{let e="",s=0,r=t.length-2;for(;s<r;s+=3){let a=t[s]<<16|t[s+1]<<8|t[s+2];e+=G.charAt(a>>18&63)+G.charAt(a>>12&63)+G.charAt(a>>6&63)+G.charAt(a&63)}let i=t.length-s;if(i===1){let a=t[s]<<16;e+=G.charAt(a>>18&63)+G.charAt(a>>12&63)}else if(i===2){let a=t[s]<<16|t[s+1]<<8;e+=G.charAt(a>>18&63)+G.charAt(a>>12&63)+G.charAt(a>>6&63)}return e},"et");new TextDecoder;var xi=new TextEncoder,Qi=n(t=>Mi(xi.encode(JSON.stringify(t))),"st"),_i="x-lunora-expect-subject",Li=n(t=>Qi({subject:t}),"it"),Zs=Symbol.for("lunora:session-change"),Di="lunora:session-change",Ui="better-auth.message",Ki="signout",or=n(()=>{let t=globalThis,e=t[Zs];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},t[Zs]=e),e},"Te"),qi=n(()=>"document"in globalThis,"ct"),Ni=n(async()=>{let t=[];for(let e of or().listeners)try{t.push(e())}catch{}await Promise.allSettled(t)},"dt"),ji=n((t,e)=>{if(t!==Ui||e===null)return!1;try{let s=JSON.parse(e);return s?.event==="session"&&s.data?.trigger===Ki}catch{return!1}},"ht"),Bi=n(t=>{let e=[],s=n(()=>{Ni().catch(()=>{})},"t"),r;try{r=typeof BroadcastChannel=="function"?new BroadcastChannel(Di):void 0}catch{r=void 0}if(r!==void 0){let a=r;a.addEventListener("message",o=>{o.data?.type==="lunora:session-change"&&o.data.tab!==t&&s()}),e.push(()=>{a.close()})}let i=globalThis;if(typeof i.addEventListener=="function"){let a=n(o=>{ji(o.key,o.newValue)&&s()},"n");i.addEventListener("storage",a),e.push(()=>{i.removeEventListener?.("storage",a)})}return()=>{for(let a of e)a()}},"ut"),$i=n(t=>{let e=or();return e.listeners.add(t),e.detach===void 0&&qi()&&(e.detach=Bi(e.tab)),()=>{e.listeners.delete(t),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},"lt"),Hi="/_lunora/rpc",_t="/_lunora/rpc-batch",Wi="/_lunora/ws",zi="/_lunora/admin/shard-traffic",Vi="/_lunora/admin/scheduled",Gi="/_lunora/admin/scheduled/status",Ji="/_lunora/admin/scheduled/ws",Yi="/_lunora/admin/scheduled/cancel",er="/_lunora/admin/scheduled/dead",Xi="/_lunora/admin/scheduled/dead/retry",Zi="/_lunora/admin/scheduled/dead/cancel",en="/_lunora/admin/workflows/instances",tn="/_lunora/admin/workflows/instance",sn="/_lunora/admin/workflows/status",$t="/_lunora/admin/storage",rn="/_lunora/admin/storage/url",nn="/_lunora/admin/storage/buckets",an="/_lunora/admin/functions",on="/_lunora/admin/cron-jobs",cn="/_lunora/admin/cron-jobs/run",un="/_lunora/admin/architecture",hn="/_lunora/admin/openapi",dn="/_lunora/admin/openrpc",ln="/_lunora/admin/global/tables",fn="/_lunora/admin/global/table",pn="/_lunora/admin/global/facet",mn="/_lunora/admin/vector/indexes",yn="/_lunora/admin/vector/query",bn="/_lunora/admin/logs/archive",gn="/_lunora/admin/kv/namespaces",vn="/_lunora/admin/kv/keys",Ht="/_lunora/admin/kv/value",Sn="/_lunora/admin/auth/users",wn="/_lunora/admin/auth/sessions",Cn="/_lunora/admin/auth/users/create",kn="/_lunora/admin/auth/users/role",Tn="/_lunora/admin/auth/users/ban",En="/_lunora/admin/auth/users/unban",On="/_lunora/admin/auth/users/password",In="/_lunora/admin/auth/users/remove",Rn="/_lunora/admin/auth/users/impersonate",An="/_lunora/admin/auth/sessions/revoke",Fn="/_lunora/admin/auth/sessions/revoke-all",Pn="/_lunora/admin/auth/capabilities",Mn="/_lunora/admin/auth/users/update",xn="/_lunora/admin/auth/accounts",Qn="/_lunora/admin/auth/accounts/unlink",_n="/_lunora/admin/auth/passkeys",Ln="/_lunora/admin/auth/passkeys/delete",Dn="/_lunora/admin/auth/two-factor/disable",Un="/_lunora/admin/auth/organizations",Kn="/_lunora/admin/auth/organizations/members",qn="/_lunora/admin/auth/organizations/invitations",Nn="/_lunora/admin/auth/organizations/members/remove",jn="/_lunora/admin/auth/organizations/invitations/cancel",Bn="/_lunora/admin/auth/config",$n="/_lunora/admin/auth/sign-up-invitations",Hn="/_lunora/admin/auth/sign-up-invitations/create",Wn="/_lunora/admin/auth/sign-up-invitations/revoke",zn="/_lunora/admin/auth/organizations/create",Vn="/_lunora/admin/auth/organizations/update",Gn="/_lunora/admin/auth/organizations/remove",Jn="/_lunora/admin/auth/organizations/members/add",Yn="/_lunora/admin/auth/organizations/members/invite",Xn="/_lunora/admin/auth/organizations/members/role",Zn="/_lunora/admin/auth/organizations/teams",ea="/_lunora/admin/auth/organizations/teams/create",ta="/_lunora/admin/auth/organizations/teams/update",sa="/_lunora/admin/auth/organizations/teams/remove",ra="/_lunora/admin/auth/organizations/teams/members",ia="/_lunora/admin/auth/organizations/teams/members/add",na="/_lunora/admin/auth/organizations/teams/members/remove",aa="/_lunora/admin/auth/organizations/roles",oa="/_lunora/admin/auth/organizations/roles/create",ca="/_lunora/admin/auth/organizations/roles/update",ua="/_lunora/admin/auth/organizations/roles/remove",ha="/api/auth",da="/get-session",la="lunora-ping",fa=n(async t=>(t.assertOpen(),(await t.adminFetch(an,"GET")).functions??[]),"Ls"),pa=n(async t=>(t.assertOpen(),(await t.adminFetch(on,"GET")).jobs??[]),"Ms"),ma=n(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(cn,"POST",{name:e});return{name:s.name??e,ran:s.ran===!0}},"Us"),ya=n(async t=>(t.assertOpen(),await t.adminFetch(hn,"GET")),"Ns"),ba=n(async t=>(t.assertOpen(),await t.adminFetch(un,"GET")),"xs"),ga=n(async t=>(t.assertOpen(),await t.adminFetch(dn,"GET")),"Bs"),va=n(async t=>(t.assertOpen(),await t.adminFetch(ln,"GET")),"Ds"),Sa=n(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({table:e.table});return e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&s.set("filters",JSON.stringify(q(e.filters))),T(await t.adminFetch(`${fn}?${s.toString()}`,"GET"))},"Qs"),wa=n(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&s.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&s.set("filters",JSON.stringify(q(e.filters))),T(await t.adminFetch(`${pn}?${s.toString()}`,"GET"))},"Ks"),Wt=n(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"ie"),tr=n(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"pe"),se=n((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"w"),A=n((t,e)=>{let s=new URLSearchParams;for(let[i,a]of Object.entries(e))a!==void 0&&a!==""&&s.set(i,String(a));let r=s.toString();return r===""?t:`${t}?${r}`},"S"),Ca=n(async t=>(t.assertOpen(),(await t.adminFetch(gn,"GET")).namespaces??[]),"qs"),ka=n(async(t,e)=>{t.assertOpen();let s=A(vn,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await t.adminFetch(s,"GET")},"Ws"),Ta=n(async(t,e)=>{t.assertOpen();let s=A(Ht,{key:e.key,namespace:e.namespace});return await t.adminFetch(s,"GET")},"js"),Ea=n(async(t,e)=>{t.assertOpen(),await t.adminFetch(Ht,"PUT",e)},"$s"),Oa=n(async(t,e)=>{t.assertOpen();let s=A(Ht,{key:e.key,namespace:e.namespace});await t.adminFetch(s,"DELETE")},"Gs"),Ia=n(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(zi,"POST",{table:e});return{failed:s.failed??0,ok:s.ok??0,shards:s.shards??[]}},"Vs"),Ra=n(async(t,e={})=>{t.assertOpen();let s=await t.adminFetch(bn,"POST",e);return{nextCursor:s.nextCursor,rows:s.rows??[]}},"zs"),Aa=n(async t=>{let e=[],s;for(;;){let r=await t(s);if(e.push(...Array.isArray(r.records)?r.records:[]),r.truncated!==!0||typeof r.cursor!="string"||r.cursor.length===0)return e;if(r.cursor===s)throw new Error("collectPages: the list did not advance its cursor \u2014 refusing to page forever");s=r.cursor}},"Js"),zt=n(t=>"args"in t?{...t,args:T(t.args)}:t,"ne"),Fa=n(async t=>(t.assertOpen(),((await t.adminFetch(Vi,"GET")).records??[]).map(e=>zt(e))),"Ys"),Pa=n(async t=>{t.assertOpen();let e=await t.adminFetch(Gi,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},"Xs"),Ma=n(async(t,e)=>(t.assertOpen(),{cancelled:(await t.adminFetch(Yi,"POST",{id:e})).cancelled===!0}),"Zs"),xa=n(async t=>(t.assertOpen(),(await Aa(async e=>await t.adminFetch(e===void 0?er:`${er}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>zt(e))),"er"),Qa=n(async(t,e)=>(t.assertOpen(),{retried:(await t.adminFetch(Xi,"POST",{id:e})).retried===!0}),"tr"),_a=n(async(t,e)=>(t.assertOpen(),{removed:(await t.adminFetch(Zi,"POST",{id:e})).removed===!0}),"sr"),La=n(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({name:e.name});e.status!==void 0&&s.set("status",e.status),e.page!==void 0&&s.set("page",String(e.page)),e.perPage!==void 0&&s.set("perPage",String(e.perPage));let r=await t.adminFetch(`${en}?${s.toString()}`,"GET");return{configured:r.configured,instances:r.instances??[],page:r.page??1,perPage:r.perPage??e.perPage??0,totalCount:r.totalCount}},"rr"),Da=n(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({id:e.id,name:e.name}),r=await t.adminFetch(`${tn}?${s.toString()}`,"GET");return{createdOn:r.createdOn,endedOn:r.endedOn,error:r.error,id:r.id??e.id,output:r.output,params:r.params,startedOn:r.startedOn,status:r.status??"unknown",steps:r.steps??[]}},"ir"),Ua=n(async(t,e)=>(t.assertOpen(),{status:(await t.adminFetch(sn,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),"nr"),Ka=n(async(t,e={})=>{t.assertOpen();let s=A($t,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),r=await t.adminFetch(s,"GET");return{cursor:r.cursor,objects:r.objects??[]}},"ar"),qa=n(async(t,e,s)=>{t.assertOpen();let r=`${$t}?key=${encodeURIComponent(e)}${Wt(s?.bucket)}`,i=await t.adminFetch(r,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}},"or"),Na=n(async t=>(t.assertOpen(),(await t.adminFetch(nn,"GET")).buckets??[]),"cr"),ja=n(async(t,e)=>{t.assertOpen();let s=`${$t}?key=${encodeURIComponent(e.key)}${Wt(e.bucket)}`,r=await t.adminFetch(s,"PUT",e.body,e.contentType);return{etag:r.etag,key:r.key??e.key}},"dr"),Ba=n(async(t,e,s)=>{t.assertOpen();let r=s?.expiresInSeconds,i=r===void 0?"":`&expiresIn=${encodeURIComponent(r.toString())}`,a=`${rn}?key=${encodeURIComponent(e)}${i}${Wt(s?.bucket)}`,o=await t.adminFetch(a,"GET");if(typeof o.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return o.url},"hr"),$a=n(async t=>(t.assertOpen(),(await t.adminFetch(mn,"GET")).indexes??[]),"ur"),Ha=n(async(t,e)=>(t.assertOpen(),(await t.adminFetch(yn,"POST",e)).matches??[]),"lr"),re=n((t,e)=>{try{return q(t)}catch(s){let r=s instanceof Error?s.message:String(s);throw new TypeError(`LunoraClient: cannot encode ${e} \u2014 ${r}`,s instanceof Error?{cause:s}:void 0)}},"E"),sr=n(t=>{try{return q(t),!0}catch{return!1}},"me"),cr=n(t=>t!==null&&typeof t=="object"&&("error"in t||"result"in t),"ve"),Wa=n((t,e)=>{let s=Array.from({length:e});for(let r of t){if(typeof r.id!="number"||r.id<0||r.id>=e)continue;if(!cr(r.body)){s[r.id]={error:Xe({}),ok:!1};continue}let i=r.body;s[r.id]="error"in i?{error:Xe(i),ok:!1}:{ok:!0,value:T(i.result)}}return s.map(r=>r??{error:new Error("batch call returned no result"),ok:!1})},"fr"),Lt=n((t,e)=>e!==null?{}:t===null?{expectSubject:null}:t?.startsWith("subj:")===!0?{expectSubject:t.slice(5)}:{},"V"),za=3e4,Va=1e4,Ga=5e3,Ja=3,Ya=250,Xa=5e3,Za=5e3,eo=64,to=3,so=1e4,ro=8,Dt=n(t=>t==="connected"||t==="polling","z"),g=n(t=>t??"","l"),_=n((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"g"),io=n(t=>{if(!t.pendingStreams||t.pendingStreams.length===0)return;let e=t.pendingStreams;t.pendingStreams=[];for(let s of e)_(t,s)},"Er"),no=new TextDecoder,ao=n(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return no.decode(t)},"_r"),ie=class{static{n(this,"I")}listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){let[s]=e;for(let r of this.listeners)try{r(s)}catch{}}clear(){this.listeners.clear()}},Te=n(t=>{t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)},"H"),oo=n((t,e,s)=>{Te(t),!(e<=0)&&(t.heartbeatTimer=setInterval(()=>{if(!t.socket)return;let{socket:r}=t;if(Date.now()-t.lastFrameAt>e*2.5){try{r.close()}catch{}s();return}try{r.send(la)}catch{}},e))},"Ir"),rr=n((t,e,s,r)=>{let{WebSocketImpl:i,connectTimeoutMs:a,heartbeatIntervalMs:o}=s;if(i===void 0)throw new b("INTERNAL","no WebSocket implementation available");let c=new i(e);t.socket=c;let u=n(()=>{Te(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket===c&&(t.socket=void 0)},"c"),d=n(h=>{u(),r.onClose(h)},"d");a>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===c){try{c.close()}catch{}d()}},a)),c.addEventListener("open",()=>{if(t.socket===c){t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.lastFrameAt=Date.now();try{r.onOpen?.()}catch(h){console.error("[lunora] connection open handler threw",h)}oo(t,o,d)}}),c.addEventListener("message",h=>{if(t.socket===c){t.lastFrameAt=Date.now();try{r.onMessage(h)}catch(l){console.error("[lunora] server frame handler threw",l)}}}),c.addEventListener("close",h=>{t.socket===c&&d(h)}),c.addEventListener("error",()=>{t.socket===c&&d()})},"ye"),co=n(t=>{let{afterFailedAttempts:e,intervalMs:s,onReachable:r,onStateChange:i,poll:a}=t,o=s>0&&e>0,c=0,u,d=!1,h=!1,l=n(()=>{u!==void 0&&(clearInterval(u),u=void 0,d=!1,i())},"u"),f=n(m=>{if(u!==void 0){if(!m){l();return}d||(d=!0,i()),r()}},"p"),p=n(()=>{h||(h=!0,a().then(f).finally(()=>{h=!1}).catch(()=>{}))},"m");return{isPolling:n(()=>u!==void 0&&d,"isPolling"),noteFailedOpen:n(()=>{c+=1,!(!o||u!==void 0||c<e)&&(u=setInterval(p,s),i(),p())},"noteFailedOpen"),noteOpen:n(()=>{c=0,l()},"noteOpen"),stop:l}},"Or"),uo=1e4,ir=n(async t=>{let e=new AbortController,s,r=new Promise((i,a)=>{s=setTimeout(()=>{e.abort(),a(new TypeError("LunoraClient: poll timed out"))},uo)});try{return await Promise.race([t(e.signal),r])}catch(i){throw e.signal.aborted?new TypeError("LunoraClient: poll timed out"):i}finally{clearTimeout(s)}},"Se"),ur=new Set(["RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),ho=n(t=>{if(t instanceof $)return!0;let e=t?.code;return e===void 0||ur.has(e)||Et.has(e)},"Pr"),hr=6e4,lo=1e3,fo={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},ke=n((t,e,s)=>{let r=Rt(s),i=r===void 0?void 0:{retryAfterMs:r},a=`LunoraClient: response carried no error envelope (status ${t.toString()}${e?` ${e}`:""})`;return t<400||t>=500||t===408?new $(a,i):new b(fo[t]??"BAD_REQUEST",a,{data:i})},"F"),Kt=n((t,e=Math.random)=>{let s=Math.min(lo*2**Math.max(t-1,0),hr);return Math.round(s*(.5+e()*.5))},"Z"),po=n(t=>t instanceof $||ur.has(t?.code??""),"Lr"),mo=n((t,e,s)=>{let r=We(t);return r!==void 0&&r>0?Math.min(r,hr):po(t)?Kt(e,s):void 0},"Mr"),yo=983040,bo=n(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"Nr"),dr=new WeakSet,lr=n(t=>{let e=new b("WIRE_DECODE_FAILED",`LunoraClient: the call succeeded but its result could not be decoded (a mutation has still committed) \u2014 ${t instanceof Error?t.message:String(t)}`,{cause:t});return dr.add(e),e},"Ee"),tt=n(t=>t instanceof Error&&dr.has(t),"x"),go=n(t=>{let e=new Map;for(let s of t)typeof s.id=="number"&&cr(s.body)&&e.set(s.id,s.body);return e},"xr"),vo=n(t=>{if(t===void 0)return{kind:"unanswered"};if("error"in t)return{error:Xe(t),kind:"errored"};try{return{commitCursor:t.commitCursor,kind:"committed",value:T(t.result)}}catch(e){return{commitCursor:t.commitCursor,error:lr(e),kind:"undecodable"}}},"Br"),Ut=n((t,e)=>`${g(t)}\0${e}`,"J"),So=n((t,e)=>{for(let s of e)s.op==="delete"?t.delete(s.key):s.value!==void 0&&t.set(s.key,s.value)},"Dr"),qt=class{static{n(this,"Qr")}constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,s){ar(this.buffers,this.maxBuffers),this.buffers.set(Ut(e,s.pokeId),{baseCheckpoint:s.baseCheckpoint,bases:new Map,epoch:s.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}part(e,s){let r=this.buffers.get(Ut(e,s.pokeId));if(!r)return;let i=[];try{for(let c of s.rowsPatch)i.push(c.value===void 0?c:{...c,value:T(c.value)})}catch(c){r.undecodable.set(s.shapeId,c);return}let a=r.parts.get(s.shapeId)??[];for(let c of i)a.push(c);r.parts.set(s.shapeId,a),s.lastMutationId!==void 0&&r.lastMutationId.set(s.shapeId,s.lastMutationId);let o=s.baseCheckpoint??r.baseCheckpoint;o!==void 0&&r.bases.set(s.shapeId,o),s.reset===!0&&r.resets.add(s.shapeId)}end(e,s){let r=Ut(e,s),i=this.buffers.get(r);return i&&this.buffers.delete(r),i}clear(){this.buffers.clear()}},wo=n((t,e,s)=>{let r=e.parts.get(t.id)??[],i=e.resets.has(t.id),a=e.bases.get(t.id),o=e.epoch!==void 0&&t.serverEpoch!==void 0&&e.epoch!==t.serverEpoch,c=a!==void 0&&t.serverCursor!==void 0&&t.serverCursor!==a;if(!i&&(o||c))return t.rows.clear(),t.serverCursor=void 0,t.serverEpoch=void 0,"reseed";i&&t.rows.clear(),So(t.rows,r),s.checkpoint!==void 0&&(t.serverCursor=s.checkpoint),s.epoch!==void 0&&(t.serverEpoch=s.epoch);let u=e.lastMutationId.get(t.id);return u!==void 0&&(t.lastMutationId=u),"applied"},"Kr"),nr=n(t=>{let e=[...t.rows.values()];for(let s of t.callbacks)try{s(e)}catch{}},"be"),Co=n((t,e)=>{for(let[s,r]of e.undecodable){let i=t.get(s);i&&V(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape \u2014 ${r instanceof Error?r.message:String(r)}`})}},"qr"),Nt=n((t,e)=>{t.lastMutationId=Math.max(t.lastMutationId??0,e)},"ee"),jt=n((t,e=!1)=>{for(let s of t.checkpointCallbacks)s({checkpoint:t.serverCursor,mutationId:t.lastMutationId,...e&&{rowsFollow:!0}})},"te"),fr=n((t,e,s)=>{t.serverBase=e,s.cursor!==void 0&&(t.serverCursor=s.cursor),s.epoch!==void 0&&(t.serverEpoch=s.epoch)},"Ae"),st=n((t,e)=>t!==void 0&&t!==e,"B"),ko=n((t,e)=>e==="connected"&&t!=="connected"||e==="polling"&&t!=="connected"&&t!=="polling","Wr"),To=n(t=>{for(let e of t.activeSubscriptions())t.ensureSocket(e.shardKey),t.queueResubscribe(e);for(let e of t.queuedShardKeys())t.ensureSocket(e);t.broadcastStatus(t.computeStatus(),t.identityFingerprint())},"jr"),Eo=n(t=>{t.closeConnections();let e=t.leader;e.status=void 0,e.wasEverConnected=!1},"$r"),Oo=n((t,e,s)=>{if(st(s,t.identityFingerprint()))return;let r=t.leader,i=ko(r.status,e);r.status=e,e==="connected"&&(r.wasEverConnected=!0),t.emitConnectionStatus(),i&&t.flushOfflineQueues()},"Gr"),Io=n(t=>{t.isLeader()&&t.broadcastStatus(t.computeStatus(),t.identityFingerprint())},"Vr"),Ro=n((t,e,s,r,i,a)=>{if(st(a,t.identityFingerprint()))return;let o=t.subscription(e);o&&(t.dropCacheSeed(e),fr(o,s,r===void 0?{}:{cursor:r,epoch:i}),r!==void 0&&Je(o,r),ee(o,s))},"zr"),Ao=n((t,e,s,r)=>{if(st(r,t.identityFingerprint()))return;let i=t.subscription(e);i&&V(i.errorCallbacks,s)},"Jr"),Fo=n((t,e,s,r,i,a,o)=>{if(st(o,t.identityFingerprint()))return;let c=t.subscription(e);c&&(t.ackAndAdvanceCursor(c,s,r),i!==void 0&&a===t.clientIdentifier()&&Nt(c,i),jt(c))},"Yr"),Po=n((t,e,s)=>t!==null||e&&s===null,"Xr"),Mo=[Ks],xo=Promise.resolve(),Bt=class t{static{n(this,"_e")}static MAX_POKE_BUFFERS=256;static createClientQuery(e,s){return{defaultValue:s,key:e}}url;wsUrl;adminHost={adminFetch:n((...e)=>this.adminFetch(...e),"adminFetch"),assertOpen:n(()=>{this.assertOpen()},"assertOpen")};clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new M;tabCoordinator;leader={status:void 0,wasEverConnected:!1};connections=new Map;idleClosedShards=new Set;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;subjectToken=null;sessionProbesInFlight=0;sessionProbeGeneration=0;identityQuestions=0;identityAnsweredAt=0;releaseSessionChangeListener;warnedIdentityDisagreement=!1;identityResolutionExpected=!1;identitySettled=!1;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new ie;statusListeners=new ie;tokenExpiredListeners=new ie;identityChangeListeners=new ie;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new ie;pendingChangeListeners=new ie;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;pokeAssembler=new qt(t.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??se(tr(e.url),Wi),this.wsToken=e.wsToken;let s=e.authBasePath??ha;this.authBasePath=s.endsWith("/")?s.slice(0,-1):s,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??Ds(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??za,this.connectTimeoutMs=e.connectTimeoutMs??Va,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??Ga,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??Ja,this.defaultConnectionContext=e.connectionContext,this.persistence=Ys(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Ls(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new $e,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(r=>{this.readyResolve=r}):(this.readyResolved=!0,this.readyPromise=xo),this.offlineQueue=new Ze(e.offlineQueue,{onEvict:n((r,i)=>{this.emitItemSettled(r,"rejected",i),this.releaseIdleShard(r.shardKey)},"onEvict"),onSizeChange:n(r=>{this.pendingChangeListeners.emit(r)},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${et()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=$i(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,s){let r=this.authToken!==e,i=this.identityFingerprint(),a=this.authSubject===void 0||this.subjectToken===this.authToken,o=this.subjectAwaitingReconfirm(),c=this.isKnownNobody(),u=this.authToken;this.authToken=e,this.applySubject(e,s);let d=this.identityFingerprint();d!==i&&(!r&&e!==null&&a?(this.restampQueuedIdentity(i,d),this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):!r&&e===null&&i===null&&a&&!c?(this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(i),this.warnRefreshWithoutSubject(u,e),Po(i,c,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(o),r&&this.authTokenListeners.emit(e),(d!==i||r||o)&&this.offlineQueue.size>0&&Dt(this.computeStatus())&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}expectIdentityResolution(){this.identityResolutionExpected=!0}currentBaseline(e){return this.baselineCursorFor(e)}replayIdentityVerdict(e){let s=this.identityVerdict(e);if(s!=="match")return{verdict:s};let r=Object.freeze({});return this.replayCredentials.set(r,{authToken:this.authToken,stamp:e}),{credential:r,verdict:s}}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,s,r){let i=r?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new b("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let a=r?.shardKey??"",o=this.identityFingerprint(),c,u,d;try{u=await this.rpc(e,s,r?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:n(h=>{c=h},"onMutationAck")})}catch(h){if(!tt(h))throw h;d=h}if(c!==void 0&&c>(this.clientWatermarks.get(o??"")?.get(a)??0)){let h=this.clientWatermarks.get(o??"");h===void 0&&(ar(this.clientWatermarks,ro),h=new Map,this.clientWatermarks.set(o??"",h)),h.set(a,c)}if(d!==void 0)throw d;return{applied:c===void 0||c===i,result:u}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}onIdentityChange(e){return this.identityChangeListeners.add(e)}identityEpoch(){return this.retiredIdentities}async getCurrentUser(){if(this.identityResolutionExpected=!0,this.closed||!this.fetchImpl)return this.identitySettled=!0,null;let e={},s=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`),this.sessionProbesInFlight+=1,this.identityQuestions+=1,this.sessionProbeGeneration=this.identityQuestions;let r=this.sessionProbeGeneration;try{let i=await this.fetchImpl(se(this.url,`${this.authBasePath}${da}`),{credentials:"include",headers:e,method:"GET"});if(!i.ok)return this.identitySettled=!0,i.status===401&&this.adoptResolvedSubject(s,null,r),null;let a=(await i.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(s,a,r),a}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.bounceShardSockets())}setConnectionContext(e,s={}){this.assertLeaderOwnedSurface("setConnectionContext");let r=g(s.shardKey);e===void 0?this.connectionContexts.delete(r):this.connectionContexts.set(r,e),this.refreshConnectionContext(r),e===void 0&&this.releaseIdleShard(s.shardKey)}acquireConnectionContext(e,s={}){if(this.followsAnotherTab())return()=>{};let r=g(s.shardKey),i={context:e},a=this.connectionContextHolders.get(r);a?a.push(i):this.connectionContextHolders.set(r,[i]),this.refreshConnectionContext(r);let o=!1;return()=>{if(o)return;o=!0;let c=this.connectionContextHolders.get(r);if(!c)return;let u=c.indexOf(i);u!==-1&&c.splice(u,1),c.length===0&&this.connectionContextHolders.delete(r),this.refreshConnectionContext(r),this.releaseIdleShard(s.shardKey)}}whisperSubscribe(e,s,r={}){this.assertLeaderOwnedSurface("whisperSubscribe");let i=g(r.shardKey),a=this.whisperHandlers.get(i);a||(a=new Map,this.whisperHandlers.set(i,a));let o=a.get(e),c=o===void 0;if(o||(o=new Set,a.set(e,o)),o.add(s),this.ensureSocket(r.shardKey),c){let u=this.getConnection(r.shardKey);u&&_(u,{topic:e,type:"whisper_subscribe"})}return()=>{let u=this.whisperHandlers.get(i),d=u?.get(e);if(!d?.delete(s)||d.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let h=this.getConnection(r.shardKey);h&&_(h,{topic:e,type:"whisper_unsubscribe"}),this.releaseIdleShard(r.shardKey)}}whisper(e,s,r={}){this.assertLeaderOwnedSurface("whisper"),this.ensureSocket(r.shardKey);let i=this.getConnection(r.shardKey);i&&_(i,{data:re(s??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"}),this.releaseIdleShard(r.shardKey)}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let s=this.statusListeners.add(e);return e(this.computeStatus()),s}pendingCount(){return this.offlineQueue.size}debug(){let e=[],s=this.clientWatermarks.get(this.identityFingerprint()??""),r=new Set([...this.connections.keys(),...s?.keys()??[]]);for(let a of r){let o=this.connections.get(a);e.push({confirmedMutationWatermark:s?.get(a)??0,hasSocket:o?.socket!==void 0,shardKey:a===""?void 0:a,wasEverConnected:o?.wasEverConnected??!1,wsState:o?.wsState??"idle"})}let i=this.subscriptions.all().map(a=>({acked:a.acked,functionPath:a.fn.__lunoraRef,id:a.id,kind:"query",lastMutationId:a.lastMutationId,pendingOptimisticLayers:a.optimisticLayers.length,serverCursor:a.serverCursor,shardKey:a.shardKey,subscriberCount:a.callbacks.size}));for(let a of this.shapeSubscriptions.values())i.push({acked:a.serverCursor!==void 0,functionPath:`shape:${a.name}`,id:a.id,kind:"shape",lastMutationId:a.lastMutationId,pendingOptimisticLayers:0,rowCount:a.rows.size,serverCursor:a.serverCursor,shardKey:a.shardKey,subscriberCount:a.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((a,o)=>(a.shardKey??"").localeCompare(o.shardKey??"")),subscriptions:i.toSorted((a,o)=>a.functionPath.localeCompare(o.functionPath))}}onPendingChange(e){let s=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),s}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,s){this.clientQueryStore.set(e,s)}subscribeClientQuery(e,s){return this.clientQueryStore.subscribe(e,s)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,s,r){return Xs(this,e,s,r)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,s,r){return this.peekHydratedQueryByKey(e,U(s),r)}peekHydratedQueryByKey(e,s,r){if(!this.readyResolved)return;let i=ne(e,s,r),a=this.hydratedQueryCache.get(i);if(a!==void 0)return this.cachedQueryMatchesIdentity(a)?a.value:void 0}peekActiveQuerySnapshot(e,s,r){let i=M.key(e,s,r),a=this.subscriptions.get(i);return{present:a!==void 0,value:a?.lastValue}}async query(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0})}async batch(e){return this.sendBatch(e)}async mutation(e,s,r={}){let{value:i}=await this.runMutation(e,s,r);return i}canQueueOffline(e){let{wasEverConnected:s}=this.connectionGateState(e);return this.WebSocketImpl!==void 0&&(s||this.offlineQueue.queueBeforeFirstConnect)}async action(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0,captureBookmark:!0})}async importRows(e,s,r={}){this.assertOpen();let i=Math.max(1,Math.trunc(r.chunkSize??500)),a=r.toArgs??(h=>({rows:h})),o=s.length,c=0,u=0,d=0;for(let h=0;h<o;h+=i){let l=s.slice(h,h+i),f=d,{committed:p}=await this.runMutation(e,a(l),{...r.importId===void 0?{}:{mutationId:`${r.importId}:${String(f)}`},shardKey:r.shardKey});d+=1,c+=l.length,p&&(u+=l.length),r.onProgress?.({done:c,total:o})}return{chunks:d,imported:u,queued:c-u}}async shardTraffic(e){return Ia(this.adminHost,e)}async listScheduledJobs(){return Fa(this.adminHost)}async schedulerStatus(){return Pa(this.adminHost)}async cancelScheduledJob(e){return Ma(this.adminHost,e)}async listDeadJobs(){return xa(this.adminHost)}async retryDeadJob(e){return Qa(this.adminHost,e)}async removeDeadJob(e){return _a(this.adminHost,e)}async listWorkflowInstances(e){return La(this.adminHost,e)}async getWorkflowInstance(e){return Da(this.adminHost,e)}async setWorkflowInstanceStatus(e){return Ua(this.adminHost,e)}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let s=se(tr(this.url),Ji),r=xt(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},a,o=!1,c=n(()=>{o||this.closed||(a=setTimeout(h,r.next()))},"a"),u=n(f=>{if(o||this.WebSocketImpl===void 0)return;let p=f===void 0?s:`${s}?token=${encodeURIComponent(f)}`;rr(i,p,this.managedSocketOptions,{onClose:n(()=>{c()},"onClose"),onMessage:n(m=>{let y;try{y=JSON.parse(typeof m.data=="string"?m.data:"")}catch{return}y.type==="jobs"&&Array.isArray(y.records)&&(r.reset(),e(y.records.map(S=>zt(S))))},"onMessage")})},"c"),d=n(async f=>{let p;try{p=await f()}catch{c();return}u(p)},"d"),h=n(()=>{if(o||this.WebSocketImpl===void 0)return;let{wsToken:f}=this;if(typeof f=="function"){d(f).catch(()=>{});return}u(f)},"h");h();let l=n(()=>{o=!0,a!==void 0&&(clearTimeout(a),a=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),Te(i),i.socket?.close(),i.socket=void 0},"u");return this.adminSocketTeardowns.add(l),()=>{this.adminSocketTeardowns.delete(l),l()}}async listFunctions(){return fa(this.adminHost)}async getCronJobs(){return pa(this.adminHost)}async runCronJob(e){return ma(this.adminHost,e)}async fetchOpenApi(){return ya(this.adminHost)}async fetchArchitecture(){return ba(this.adminHost)}async fetchOpenRpc(){return ga(this.adminHost)}async listStorageObjects(e={}){return Ka(this.adminHost,e)}async deleteStorageObject(e,s){return qa(this.adminHost,e,s)}async listStorageBuckets(){return Na(this.adminHost)}async uploadStorageObject(e){return ja(this.adminHost,e)}async signedStorageUrl(e,s){return Ba(this.adminHost,e,s)}async listGlobalTables(){return va(this.adminHost)}async readGlobalTablePage(e){return Sa(this.adminHost,e)}async facetGlobalColumn(e){return wa(this.adminHost,e)}async listVectorIndexes(){return $a(this.adminHost)}async queryVectorIndex(e){return Ha(this.adminHost,e)}async queryLogArchive(e={}){return Ra(this.adminHost,e)}async listKvNamespaces(){return Ca(this.adminHost)}async listKvKeys(e){return ka(this.adminHost,e)}async getKvValue(e){return Ta(this.adminHost,e)}async putKvValue(e){return Ea(this.adminHost,e)}async deleteKvKey(e){return Oa(this.adminHost,e)}async listAuthUsers(e={}){this.assertOpen();let s=A(Sn,{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(s,"GET")}async createAuthUser(e){return this.assertOpen(),await this.adminFetch(Cn,"POST",e)}async setAuthUserRole(e){return this.assertOpen(),await this.adminFetch(kn,"POST",e)}async banAuthUser(e){return this.assertOpen(),await this.adminFetch(Tn,"POST",e)}async unbanAuthUser(e){return this.assertOpen(),await this.adminFetch(En,"POST",e)}async setAuthUserPassword(e){this.assertOpen(),await this.adminFetch(On,"POST",e)}async removeAuthUser(e){this.assertOpen(),await this.adminFetch(In,"POST",e)}async impersonateAuthUser(e){return this.assertOpen(),await this.adminFetch(Rn,"POST",e)}async revokeAuthSession(e){this.assertOpen(),await this.adminFetch(An,"POST",e)}async revokeAuthUserSessions(e){this.assertOpen(),await this.adminFetch(Fn,"POST",e)}async getAuthCapabilities(){return this.assertOpen(),await this.adminFetch(Pn,"GET")}async updateAuthUser(e){return this.assertOpen(),await this.adminFetch(Mn,"POST",e)}async listAuthAccounts(e){return this.assertOpen(),await this.adminFetch(A(xn,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.assertOpen(),await this.adminFetch(Qn,"POST",e)}async listAuthPasskeys(e){return this.assertOpen(),await this.adminFetch(A(_n,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.assertOpen(),await this.adminFetch(Ln,"POST",e)}async disableAuthTwoFactor(e){this.assertOpen(),await this.adminFetch(Dn,"POST",e)}async listAuthOrganizations(e={}){return this.assertOpen(),await this.adminFetch(A(Un,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.assertOpen();let s=A(Kn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthOrgInvitations(e){this.assertOpen();let s=A(qn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthSignUpInvitations(e={}){this.assertOpen();let s=A($n,{limit:e.limit,offset:e.offset});return await this.adminFetch(s,"GET")}async createAuthSignUpInvitation(e){return this.assertOpen(),await this.adminFetch(Hn,"POST",e)}async revokeAuthSignUpInvitation(e){this.assertOpen(),await this.adminFetch(Wn,"POST",e)}async removeAuthOrgMember(e){this.assertOpen(),await this.adminFetch(Nn,"POST",e)}async cancelAuthOrgInvitation(e){this.assertOpen(),await this.adminFetch(jn,"POST",e)}async getAuthConfig(){return this.assertOpen(),await this.adminFetch(Bn,"GET")}async createAuthOrganization(e){return this.assertOpen(),await this.adminFetch(zn,"POST",e)}async updateAuthOrganization(e){return this.assertOpen(),await this.adminFetch(Vn,"POST",e)}async deleteAuthOrganization(e){this.assertOpen(),await this.adminFetch(Gn,"POST",e)}async addAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(Jn,"POST",e)}async inviteAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(Yn,"POST",e)}async setAuthOrgMemberRole(e){return this.assertOpen(),await this.adminFetch(Xn,"POST",e)}async listAuthOrgTeams(e){this.assertOpen();let s=A(Zn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(ea,"POST",e)}async updateAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(ta,"POST",e)}async removeAuthOrgTeam(e){this.assertOpen(),await this.adminFetch(sa,"POST",e)}async listAuthOrgTeamMembers(e){this.assertOpen();let s=A(ra,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(s,"GET")}async addAuthOrgTeamMember(e){return this.assertOpen(),await this.adminFetch(ia,"POST",e)}async removeAuthOrgTeamMember(e){this.assertOpen(),await this.adminFetch(na,"POST",e)}async listAuthOrgRoles(e){this.assertOpen();let s=A(aa,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(oa,"POST",e)}async updateAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(ca,"POST",e)}async deleteAuthOrgRole(e){this.assertOpen(),await this.adminFetch(ua,"POST",e)}async listAuthSessions(e={}){this.assertOpen();let s=A(wn,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(s,"GET")}subscribe(e,s,r,i={}){this.assertOpen();let a=s??{},o=M.key(e.__lunoraRef,a,i.shardKey),c=this.subscriptions.get(o),u=Ge(r),d=Ge(i.onError),h=Ge(i.onCheckpoint);if(!c){this.nextSubId+=1;let f=`sub_${this.nextSubId.toString()}`,p=U(a),m=this.takeHydratedCache(e.__lunoraRef,p,i.shardKey);c={acked:!1,args:a,argsKey:p,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:re(a,`args for '${e.__lunoraRef}'`),...m?.serverEpoch===void 0?{}:{serverEpoch:m.serverEpoch}},this.subscriptions.add(c),m!==void 0&&this.cacheSeededQueries.set(o,m)}if(c.callbacks.add(u),d&&c.errorCallbacks.add(d),h&&c.checkpointCallbacks.add(h),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let l=c;return()=>{l.callbacks.delete(u),d&&l.errorCallbacks.delete(d),h&&l.checkpointCallbacks.delete(h),l.callbacks.size===0&&(this.sendOrQueueUnsubscribe(l.shardKey,l.id,"unsubscribe"),this.returnCacheSeed(M.keyOf(l)),this.subscriptions.remove(l),this.releaseIdleShard(l.shardKey))}}subscribeShape(e,s,r={}){if(this.assertOpen(),this.followsAnotherTab()){let{onError:o}=r;return o!==void 0&&queueMicrotask(()=>{o({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()}`,a={args:e.args,callbacks:new Set([s]),errorCallbacks:r.onError?new Set([r.onError]):new Set,id:i,name:e.name,onCheckpoint:r.onCheckpoint,rows:new Map,shardKey:r.shardKey,wireArgs:e.args===void 0?void 0:re(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,a),this.ensureSocket(r.shardKey),this.sendShapeSubscribeIfOpen(a),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(a.shardKey,i,"shape_unsubscribe"),this.releaseIdleShard(a.shardKey)}}stream(e,s,r={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new b("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;let i=`stream_${this.nextStreamId.toString()}`,{shardKey:a}=r,o=s??{},{handle:c,iterable:u}=Ve({maxBuffer:r.maxBuffer,onCancel:n(()=>{this.cancelStream(i,a)},"onCancel")});this.ensureSocket(a);let d=this.getConnection(a),h={id:i,query:{args:re(o,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:a},type:"stream"},l={durable:r.durable===!0,generation:void 0,handle:c,lastSeq:0,message:h,shardKey:a};this.streams.set(i,l);let f=d?.wsState==="open"&&_(d,h);if(!f&&d===void 0)return this.forgetStream(i),c.fail(new b("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(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=eo;){let p=d.pendingStreams.shift()?.id,m=p?this.streams.get(p):void 0;m&&(m.handle.fail(new b("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(p))}d.pendingStreams.push(h)}return u}httpStream(e,s,r={}){if(this.closed)throw new b("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...r.headers};return Bs(e,s,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:r.maxBuffer,signal:r.signal})}close(){this.closed=!0,this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(let e of this.streams.values())e.handle.fail(new b("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.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeAssembler.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 b("INTERNAL","LunoraClient is closed")}followsAnotherTab(){let e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;let s=e.leaderTabId;return s!==void 0&&s!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new b("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}shardInUse(e){let s=n(r=>g(r)===e,"t");return this.subscriptions.all().some(r=>s(r.shardKey))||[...this.shapeSubscriptions.values()].some(r=>s(r.shardKey))||[...this.streams.values()].some(r=>s(r.shardKey))||this.whisperHandlers.has(e)||this.connectionContexts.has(e)||this.connectionContextHolders.has(e)||this.offlineFlushes.has(e)||this.offlineQueue.hasPending(r=>s(r.shardKey))}releaseIdleShard(e){let s=g(e),r=this.connections.get(s);this.closed||s===""||r===void 0||(clearTimeout(r.idleTimer),r.idleTimer=setTimeout(()=>{r.idleTimer=void 0,!(this.closed||this.connections.get(s)!==r||this.shardInUse(s))&&(r.wasEverConnected&&this.idleClosedShards.add(s),this.teardownConnection(r),this.connections.delete(s),this.emitConnectionStatus())},Za))}forgetStream(e){let s=this.streams.get(e);this.streams.delete(e),s&&this.releaseIdleShard(s.shardKey)}teardownConnection(e){e.polling.stop();let s=g(e.shardKey);for(let[i,a]of this.streams)g(a.shardKey)===s&&(a.handle.fail(new b("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(i));e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.clearResubscribeQueue(e),this.clearConnectionTimers(e),clearTimeout(e.idleTimer),e.idleTimer=void 0,Te(e);let{socket:r}=e;if(r){e.socket=void 0;try{r.close()}catch{}}e.wsState="closed"}createTabCoordinator(){let e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`,s={activeSubscriptions:n(()=>this.subscriptions.all(),"activeSubscriptions"),broadcastStatus:n((r,i)=>this.tabCoordinator?.broadcastConnectionStatus(r,i),"broadcastStatus"),closeConnections:n(()=>{for(let[r,i]of this.connections)this.teardownConnection(i),this.connections.delete(r)},"closeConnections"),computeStatus:n(()=>this.computeStatus(),"computeStatus"),emitConnectionStatus:n(()=>{this.emitConnectionStatus()},"emitConnectionStatus"),ensureSocket:n(r=>{this.ensureSocket(r)},"ensureSocket"),flushOfflineQueues:n(()=>{this.flushAllOfflineQueues()},"flushOfflineQueues"),identityFingerprint:n(()=>this.identityFingerprint(),"identityFingerprint"),isLeader:n(()=>this.tabCoordinator?.isLeader()===!0,"isLeader"),leader:this.leader,queueResubscribe:n(r=>{this.queueResubscribe(r)},"queueResubscribe"),queuedShardKeys:n(()=>this.queuedOfflineShardKeys,"queuedShardKeys"),clientIdentifier:n(()=>this.clientId,"clientIdentifier"),dropCacheSeed:n(r=>{this.dropCacheSeed(r)},"dropCacheSeed"),ackAndAdvanceCursor:n((r,i,a)=>{this.ackAndAdvanceCursor(r,i,a)},"ackAndAdvanceCursor"),subscription:n(r=>this.subscriptions.get(r),"subscription")};return new He({channelName:e,onBecomeLeader:n(()=>{To(s)},"onBecomeLeader"),onStopBeingLeader:n(()=>{Eo(s)},"onStopBeingLeader"),onConnectionStatus:n((r,i)=>{Oo(s,r,i)},"onConnectionStatus"),onSubscriptionData:n((r,i,a,o,c)=>{Ro(s,r,i,a,o,c)},"onSubscriptionData"),onLeaderClaimAnswered:n(()=>{Io(s)},"onLeaderClaimAnswered"),onSubscriptionError:n((r,i,a)=>{Ao(s,r,i,a)},"onSubscriptionError"),onSubscriptionSettled:n((r,i,a,o,c,u)=>{Fo(s,r,i,a,o,c,u)},"onSubscriptionSettled")})}async sendBatch(e,s){if(this.assertOpen(),!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(se(this.url,_t),{body:JSON.stringify({calls:e.map((c,u)=>({args:re(c.args??{},`args for batch call '${c.fn.__lunoraRef}'`),functionPath:c.fn.__lunoraRef,id:u,shardKey:c.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:s}),i=r.headers.get("x-d1-bookmark");i&&this.bookmark.set(i);let a;try{a=await r.json()}catch{throw new b("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`)}let o=fe(a);if(!r.ok||o!==void 0&&!a.results)throw o!==void 0?Ye(o):new b("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`);for(let c of a.results??[]){let u=c.body?.commitCursor;typeof c.id=="number"&&typeof u=="number"&&this.recordShardCursor(e[c.id]?.shardKey,u)}return Wa(a.results??[],e.length)}async runMutation(e,s,r){this.assertOpen();let i=s,a=r.mutationId??et(),o=this.takeReplayCredential(r.replayCredential),c=r.replayBaseline===void 0?this.baselineCursorFor(r.shardKey):r.replayBaseline??void 0,{confirms:u,rollbacks:d}=this.applyOptimisticUpdates(e.__lunoraRef,i,r.shardKey,r.optimistic);r.optimisticUpdate&&this.applyOptimisticUpdate(r.optimisticUpdate,s,r.shardKey,d,u);let h=this.offlineFlushes.get(g(r.shardKey));h!==void 0&&await h;let{hasSocket:l,idleClosed:f,polling:p,wasEverConnected:m,wsState:y}=this.connectionGateState(r.shardKey),{queueBeforeFirstConnect:S}=this.offlineQueue,w=m||S,k=this.WebSocketImpl!==void 0&&w,E=p||f,H=y==="connecting"&&w&&!E,W=y!=="open"&&!l&&k&&!E,pe=k&&r.replayBaseline===void 0&&this.hasPendingWriteAhead(r.shardKey),L=n(async()=>this.enqueueOfflineMutation(e,i,r.shardKey,c,a,d,u,r.precondition,r.mutationId,o?.stamp),"ae");if(W||H||pe)return L();let I;try{let D=await this.rpc(e.__lunoraRef,i,r.shardKey,{baselineSeq:c,captureBookmark:!0,...o?.flags,mutationId:a,onCommitCursor:n(J=>{I=J},"onCommitCursor")});for(let J of u)J(I);return{committed:!0,value:D}}catch(D){if(E&&k&&D instanceof TypeError&&sr(i))return L();throw this.settleFailedDirectWrite(D,I,u,d,o?.flags.authToken),D}}settleFailedDirectWrite(e,s,r,i,a){if(this.noteIdentityMismatch(e),a!==void 0&&this.noteReplayAuthRefusal(e,a),tt(e)){for(let o of r)o(s);return}le(i)}async enqueueOfflineMutation(e,s,r,i,a,o,c,u,d,h){let l=h===void 0?this.identityFingerprint():h;if(this.outbox){this.outboxMutationCounter+=1;let f=this.outboxMutationCounter;try{await this.outbox.enqueue({args:s,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:d??`${this.clientId}:${String(f)}`,identity:l,mutationId:f,...o.length>0&&{onRejected:n(()=>{le(o)},"onRejected")},shardKey:r})}catch(p){throw le(o),p instanceof Error?p:new Error(String(p))}for(let p of c)p(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((f,p)=>{let m={args:s,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:a,clientId:this.clientId,identity:l,precondition:u,onCommit:n(y=>{for(let S of c)S(y)},"onCommit"),reject:n(y=>{this.queuedIdentities.delete(a),tt(y)||le(o),p(y instanceof Error?y:new Error(String(y))),this.releaseIdleShard(r)},"reject"),resolve:f,shardKey:r};this.offlineQueue.enqueue(m),this.queuedOfflineShardKeys.add(r),this.ensureSocket(r),m.id!==void 0&&this.queuedIdentities.set(m.id,l)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;let s=g(e);return this.offlineQueue.hasPending(r=>g(r.shardKey)===s)}async hydratePersistedQueue(){try{let e=await this.offlineQueue.hydrate();for(let s of e)this.queuedOfflineShardKeys.add(s),this.ensureSocket(s)}catch{}}hydrateAsOutboxLeader(){let e=n(()=>{this.hydratePersistedQueue().catch(()=>{})},"e"),s=globalThis.navigator?.locks;if(!s){e();return}s.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(r=>{if(this.closed){r();return}this.outboxLeaderRelease=r}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{let e=await this.queryCache.load(),s=new Map;for(let r of this.subscriptions.all())s.set(ne(r.fn.__lunoraRef,r.argsKey,r.shardKey),r);for(let{key:r,...i}of e){if(Pt(this.persistenceVersion,i.version)){this.queryCache.remove(r).catch(()=>{});continue}let a=s.get(r);if(a&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(a,i);continue}this.hydratedQueryCache.set(r,i)}}catch{}}seedSubscriptionFromCache(e,s){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(s)||(e.serverBase=s.value,e.serverCursor=s.serverCursor,s.serverEpoch!==void 0&&(e.serverEpoch=s.serverEpoch),this.cacheSeededQueries.set(ne(e.fn.__lunoraRef,e.argsKey,e.shardKey),s),ee(e,s.value))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}returnCacheSeed(e){let s=this.cacheSeededQueries.get(e);s!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,s))}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(let[e,s]of this.cacheSeededQueries){let r=this.subscriptions.get(e);r!==void 0&&(r.serverBase=void 0,r.serverCursor=void 0,r.serverEpoch=void 0,ee(r,void 0)),this.hydratedQueryCache.set(e,s)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,s,r){let i=ne(e,s,r),a=this.hydratedQueryCache.get(i);if(!(a===void 0||!this.cachedQueryMatchesIdentity(a)))return this.hydratedQueryCache.delete(i),a}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(let e of this.subscriptions.all()){let s=ne(e.fn.__lunoraRef,e.argsKey,e.shardKey),r=this.hydratedQueryCache.get(s);r!==void 0&&this.cachedQueryMatchesIdentity(r)&&(this.hydratedQueryCache.delete(s),this.seedSubscriptionFromCache(e,r))}}persistQueryValue(e){let s=e.serverBase;if(!this.queryCache||s===void 0)return;let r=ne(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,a=i===void 0?this.identityFingerprint():i;a===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(r,{identity:a,serverCursor:e.serverCursor,ts:Date.now(),value:s,...a===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(()=>{})},Ya))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;let{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}let s=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(s.map(async([r,i])=>e.put(r,i)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leader.status??"idle";let e=[...this.connections.values()];return e.length===0?"idle":e.some(s=>s.wsState==="open")?"connected":e.some(s=>s.polling.isPolling())?"polling":e.some(s=>s.wsState==="connecting")?"connecting":"offline"}baselineCursorFor(e){let s=g(e),r;for(let i of this.subscriptions.all())g(i.shardKey)!==s||i.serverCursor===void 0||(r=r===void 0?i.serverCursor:Math.max(r,i.serverCursor));return r}async pollSubscriptions(e){let s=g(e),r=[];for(let c of this.subscriptions.all())g(c.shardKey)===s&&(sr(c.args)?r.push(c):V(c.errorCallbacks,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"}));if(r.length===0)return this.probeOrigin();let i=$s(),a=this.identityFingerprint(),o;try{o=await ir(async c=>this.sendBatch(r.map(u=>({args:u.args,fn:u.fn,shardKey:u.shardKey})),c))}catch(c){return!(c instanceof TypeError)}if(this.identityFingerprint()!==a)return!0;for(let[c,u]of r.entries()){let d=o[c];if(d!==void 0){if(!d.ok){V(u.errorCallbacks,{code:d.error.code,message:d.error.message});continue}this.handleDataMessage({data:q(d.value),id:u.id,type:"data"},i)}}return!0}async probeOrigin(){let{fetchImpl:e}=this;if(!e)return!1;try{return await ir(async s=>e(se(this.url,_t),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:s})),!0}catch{return!1}}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,s,r){this.mutationSettledListeners.emit({args:e.args,code:r===void 0?void 0:r.code,error:r,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:s})}applyOptimisticUpdates(e,s,r,i){let a=[],o=[];if(!i)return{confirms:a,rollbacks:o};let c=M.key(e,s,r),u=this.subscriptions.get(c);if(u){let d=It(u,i);d&&(a.push(d.confirm),o.push(d.rollback))}return{confirms:a,rollbacks:o}}applyOptimisticUpdate(e,s,r,i,a){let{confirms:o,rollbacks:c,store:u}=zs(this.subscriptions,r);try{e(u,s)}catch{le(c);return}i.push(...c),a.push(...o)}getConnection(e){return this.connections.get(g(e))}sendOrQueueUnsubscribe(e,s,r){let i=this.getConnection(e);i&&!_(i,{id:s,type:r})&&i.pendingUnsubscribes.push({id:s,type:r})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let i="idle";return this.leader.status==="connected"?i="open":this.leader.status==="connecting"&&(i="connecting"),{hasSocket:!1,idleClosed:!1,polling:this.leader.status==="polling",wasEverConnected:this.leader.wasEverConnected,wsState:i}}let s=this.getConnection(e),r=s===void 0&&this.idleClosedShards.has(g(e));return{hasSocket:s?.socket!==void 0,idleClosed:r,polling:s?.polling.isPolling()??!1,wasEverConnected:s?.wasEverConnected??r,wsState:s?.wsState??"idle"}}getOrCreateConnection(e){let s=g(e),r=this.connections.get(s);return r||(r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:co({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:n(()=>{this.flushOfflineQueue(e).catch(()=>{})},"onReachable"),onStateChange:n(()=>{this.emitConnectionStatus()},"onStateChange"),poll:n(async()=>this.pollSubscriptions(e),"poll")}),reconnect:xt(this.reconnectOptions),reconnectTimer:void 0,resubscribePending:new Map,resubscribeQueue:[],shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:this.idleClosedShards.delete(s),wsState:"idle"},this.connections.set(s,r)),r}wsUrlFor(e,s){let r=[];if(e!==void 0&&r.push(`shard=${encodeURIComponent(e)}`),s!==void 0&&r.push(`token=${encodeURIComponent(s)}`),r.length===0)return this.wsUrl;let i=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${i}${r.join("&")}`}rpcRequestHeaders(e,s){let r={"content-type":"application/json"};e.expectSubject!==void 0&&(r[_i]=Li(e.expectSubject));let i=this.shardCursors.get(this.cursorKeyFor(s));i!==void 0&&(r["x-lunora-min-seq"]=i.toString());let a=e.authToken===void 0?this.authToken:e.authToken;if(a&&(r.authorization=`Bearer ${a}`),e.mutationId&&(r["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(r["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(r["x-lunora-client-seq"]=e.clientSeq.toString()),e.baselineSeq!==void 0&&(r["x-lunora-base-seq"]=e.baselineSeq.toString()),e.attachBookmark){let o=this.bookmark.get();o&&(r["x-d1-bookmark"]=o)}return r}async rpc(e,s,r,i={}){if(!this.fetchImpl)throw new $("LunoraClient: no `fetch` implementation available");let a=this.rpcRequestHeaders(i,r),o=i.authToken===void 0?this.authToken:i.authToken,c=await this.fetchImpl(se(this.url,Hi),{body:JSON.stringify({args:re(s,`args for '${e}'`),functionPath:e,shardKey:r}),headers:a,method:"POST"});if(i.captureBookmark){let l=c.headers.get("x-d1-bookmark");l&&this.bookmark.set(l)}let u;try{u=await c.json()}catch{throw ke(c.status,c.statusText,c.headers.get("retry-after"))}let d=u;if(typeof d!="object"||d===null||Array.isArray(d))throw ke(c.status,c.statusText,c.headers.get("retry-after"));let h=fe(u);if(h!==void 0)throw Ft(h,c.headers.get("retry-after"));if(!c.ok)throw ke(c.status,c.statusText,c.headers.get("retry-after"));i.onMutationAck?.(u.lastMutationId),i.onCommitCursor?.(u.commitCursor),this.noteCredentialAccepted(o),this.learnDefaultShardKey(c,r),this.recordShardCursor(r,u.commitCursor);try{return T(u.result)}catch(l){throw lr(l)}}async adminFetch(e,s,r,i){if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");let a={};this.authToken&&(a.authorization=`Bearer ${this.authToken}`);let o=r instanceof ArrayBuffer||r instanceof Blob,c;r===void 0?c=void 0:o?(c=r,i!==void 0&&(a["content-type"]=i)):(c=JSON.stringify(r),a["content-type"]="application/json");let u=await this.fetchImpl(se(this.url,e),{body:c,headers:a,method:s}),d;try{d=await u.json()}catch{let l=u.statusText?` ${u.statusText}`:"";throw new b("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${l})`)}let h=fe(d);if(h!==void 0){let l=new Error(h.message??"admin request failed");throw l.code=h.code,l}if(!u.ok){let l=u.statusText?` ${u.statusText}`:"";throw new b("INTERNAL",`LunoraClient: admin request failed (status ${u.status.toString()}${l})`)}return d}effectiveConnectionContext(e){let s=this.connectionContextHolders.get(e);return s&&s.length>0?s[s.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){let s=this.connections.get(e);s?.wsState==="open"&&this.sendConnectEnvelope(s)}sendConnectEnvelope(e){let s=this.effectiveConnectionContext(g(e.shardKey));_(e,{caps:Mo,clientId:this.clientId,id:"connect",type:"connect",...s===void 0?{}:{context:s}})}resendShapeSubscriptions(e){for(let s of this.shapeSubscriptions.values())g(s.shardKey)===g(e)&&this.sendShapeSubscribeIfOpen(s)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;let s=this.getOrCreateConnection(e);if(!(s.wsState==="open"||s.wsState==="connecting")){if(s.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(s,e,this.wsToken).catch(()=>{});return}this.openSocket(s,e,this.wsToken)}}async openSocketWithProvidedToken(e,s,r){let i;try{i=await r()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,s,i)}openSocket(e,s,r){this.WebSocketImpl!==void 0&&(e.identity=this.identityFingerprint(),r===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.retired=!1,rr(e,this.wsUrlFor(s,r),this.managedSocketOptions,{onClose:n(i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},"onClose"),onMessage:n(i=>{e.retired!==!0&&this.handleServerMessage(i.data,s)},"onMessage"),onOpen:n(()=>{e.wsState="open",e.wasEverConnected=!0,e.polling.noteOpen(),clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},Xa),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(s),this.clearResubscribeQueue(e);for(let a of this.subscriptions.all())g(a.shardKey)===g(s)&&this.queueResubscribe(a);if(this.resendShapeSubscriptions(s),e.pendingUnsubscribes.length>0){let a=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:o,type:c}of a)_(e,{id:o,type:c});this.releaseIdleShard(s)}io(e);let i=this.whisperHandlers.get(g(s));if(i)for(let a of i.keys())_(e,{topic:a,type:"whisper_subscribe"});this.flushOfflineQueue(s).catch(()=>{})},"onOpen")}))}cancelStream(e,s){let r=this.getConnection(s);r&&(r.pendingStreams=r.pendingStreams?.filter(i=>i.id!==e),_(r,{id:e,type:"unsubscribe"})),this.forgetStream(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;e.wsState==="connecting"&&e.polling.noteFailedOpen(),Te(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e);let s=new Set((e.pendingStreams??[]).map(i=>i.id));for(let[i,a]of this.streams)if(!(g(a.shardKey)!==g(e.shardKey)||s.has(i))){if(a.durable){let o={...a.message,...a.generation===void 0?{}:{generation:a.generation},sinceChunk:a.lastSeq};a.message=o,e.pendingStreams=[...(e.pendingStreams??[]).filter(c=>c.id!==i),o];continue}a.handle.fail(new b("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.forgetStream(i)}if(this.WebSocketImpl===void 0)return;let r=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},r)}markShardPendingAck(e){let s=g(e);for(let r of this.subscriptions.all())g(r.shardKey)===s&&(r.acked=!1)}queueResubscribe(e){let s=this.getConnection(e.shardKey);s&&(s.resubscribeQueue.push(e),this.drainResubscribeQueue(s))}drainResubscribeQueue(e){for(;e.resubscribePending.size<to;){let s=e.resubscribeQueue.shift();if(!s)return;this.subscriptions.getById(s.id)&&this.sendSubscribeIfOpen(s)&&e.resubscribePending.set(s.id,setTimeout(()=>{this.releaseResubscribeSlot(e,s.id)},so))}}releaseResubscribeSlot(e,s){let r=e.resubscribePending.get(s);r!==void 0&&(clearTimeout(r),e.resubscribePending.delete(s),this.drainResubscribeQueue(e))}clearResubscribeQueue(e){for(let s of e.resubscribePending.values())clearTimeout(s);e.resubscribePending.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);if(s?.wsState!=="open"||e.acked)return!1;let r=e.serverCursor!==void 0&&e.serverBase!==void 0;return _(s,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...r?{sinceSeq:e.serverCursor}:{},...r&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);s?.wsState==="open"&&_(s,{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,s){let r=ao(e);if(r===void 0)return;let i;try{i=JSON.parse(r)}catch{return}if(i.type!=="error"&&this.getConnection(s)?.reconnect.reset(),typeof i.id=="string"){let a=this.getConnection(s);a&&this.releaseResubscribeSlot(a,i.id)}switch(i.type){case"ack":{let a=this.subscriptions.getById(i.id);a&&(a.acked=!0);return}case"chunk":{let{data:a,generation:o,id:c,seq:u}=i,d=this.streams.get(c);d&&typeof u=="number"&&(d.lastSeq=u,typeof o=="number"&&(d.generation=o),d.durable=!0),d?.handle.push(T(a));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"identity":{this.handleIdentityFrame(i,s);break}case"pokeEnd":{this.handlePokeEnd(i,s);break}case"pokePart":{this.pokeAssembler.part(s,i);break}case"pokeStart":{this.pokeAssembler.start(s,i);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,s);break}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}let{id:s}=e,r=s===void 0?void 0:this.streams.get(s);if(r&&s!==void 0){r.handle.fail(Gs(e)),this.forgetStream(s);return}let i=s===void 0?void 0:this.subscriptions.getById(s);if(i){let o=At(e),c=this.identityFingerprint(),u=M.keyOf(i);V(i.errorCallbacks,o),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(u,o,c);return}let a=s===void 0?void 0:this.shapeSubscriptions.get(s);a&&V(a.errorCallbacks,At(e))}handlePokeEnd(e,s){let r=this.pokeAssembler.end(s,e.pokeId);if(r){Co(this.shapeSubscriptions,r);for(let i of r.parts.keys()){let a=this.shapeSubscriptions.get(i);a&&!r.undecodable.has(i)&&this.applyPokePart(a,r,e)}}}applyPokePart(e,s,r){let i=wo(e,s,r);if(nr(e),i==="reseed"){this.sendShapeSubscribeIfOpen(e);return}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)}handleDataMessage(e,s){let{id:r}=e,i=r?this.subscriptions.getById(r):void 0;if(!i)return;let a;try{a=qs(e,i.serverBase)}catch(o){V(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription \u2014 ${o instanceof Error?o.message:String(o)}`});return}if(a===Tt){this.resnapshotSubscription(i);return}if(this.dropCacheSeed(M.keyOf(i)),fr(i,a,{cursor:e.cursor,epoch:e.epoch}),e.lastMutationId!==void 0&&(Nt(i,e.lastMutationId),jt(i,!0)),this.persistQueryValue(i),Je(i,i.serverCursor),s!==void 0&&Ws(i,s),ee(i,a),this.tabCoordinator?.isLeader()){let o=M.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(o,a,i.serverCursor,i.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){let s=this.subscriptions.getById(e.id);s&&this.ackAndAdvanceCursor(s,e.cursor,e.epoch)}handleSettledMessage(e){let s=this.subscriptions.getById(e.id);if(s&&(this.ackAndAdvanceCursor(s,e.cursor,e.epoch),e.lastMutationId!==void 0&&Nt(s,e.lastMutationId),jt(s),this.tabCoordinator?.isLeader())){let r=M.keyOf(s);this.tabCoordinator.broadcastSubscriptionSettled(r,s.serverCursor,s.serverEpoch,s.lastMutationId,this.clientId,this.identityFingerprint())}}ackAndAdvanceCursor(e,s,r){e.acked=!0,(s!==void 0&&s!==e.serverCursor||r!==void 0&&r!==e.serverEpoch)&&(s!==void 0&&(e.serverCursor=s),r!==void 0&&(e.serverEpoch=r),this.persistQueryValue(e),Je(e,e.serverCursor)&&ee(e,e.serverBase))}dispatchWhisper(e,s){let r=this.whisperHandlers.get(g(s))?.get(e.topic);if(!r)return;let i=T(e.data);for(let a of r)try{a(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){let s=this.streams.get(e);if(s){s.handle.complete(),this.forgetStream(e);return}let r=this.subscriptions.getById(e);r&&(r.acked=!1,V(r.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(s=>{te(this.onPersistenceError,"remove",s,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 s=2166136261,r=5381;for(let i=0;i<e.length;i+=1){let a=e.charCodeAt(i);s^=a,s=Math.imul(s,16777619),r=Math.imul(r,33)+a}return`${e.length.toString(36)}:${(s>>>0).toString(36)}:${(r>>>0).toString(36)}`}credentialStamp(){let e=this.authToken;return e===null?{}:{credential:this.hashToken(e)}}cachedQueryMatchesIdentity(e){return this.identityFingerprint()===null&&this.identityUnresolved()?!1:!this.subjectAwaitingReconfirm()&&e.identity===this.identityFingerprint()||this.isSameCredentialUnderTokenHash(e.identity)?!0:e.credential!==void 0&&e.credential===this.credentialStamp().credential}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;let s=this.authToken;return s===null?!1:this.hashToken(s)===e}releaseSessionProbe(){this.sessionProbesInFlight-=1,!(this.identityUnresolved()||this.identityFingerprint()!==null)&&!this.closed&&this.offlineQueue.size>0&&Dt(this.computeStatus())&&this.flushAllOfflineQueues()}identityUnresolved(){return this.sessionProbesInFlight>0?!0:this.identityResolutionExpected&&!this.identitySettled}adoptResolvedSubject(e,s,r){if(!(this.closed||this.authToken!==e||r!==this.sessionProbeGeneration)){if(e===null){this.adoptCookieSubject(s?.id??null,r);return}s!==null&&this.setAuthToken(e,s.id)}}adoptCookieSubject(e,s){return this.closed||this.authToken!==null||s<this.identityAnsweredAt?!1:(this.identityAnsweredAt=s,this.identitySettled=!0,this.setAuthToken(null,e),!0)}handleIdentityFrame(e,s){let r=this.getConnection(s)?.identityQuestion,{subject:i}=e;r===void 0||i!==null&&typeof i!="string"||this.adoptCookieSubject(i,r)||!this.closed&&this.authToken===null&&(i===null?null:`subj:${i}`)!==this.identityFingerprint()&&this.evictPreviousIdentitySession()}applySubject(e,s){if(s!==void 0){this.authSubject=s,this.subjectToken=e;return}(e===null&&this.authSubject!==null||e!==null&&this.authSubject===null)&&(this.authSubject=void 0,this.subjectToken=null)}isKnownNobody(){return this.authSubject===null&&this.authToken===null}subjectAwaitingReconfirm(){return this.authSubject!==void 0&&this.authSubject!==null&&this.subjectToken!==this.authToken}stampOf(e){let s=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return s===void 0?e.identity:s}warnRefreshWithoutSubject(e,s){e===null||s===null||this.authSubject!==void 0||this.authRefusalNotifiedFor!==this.hashToken(e)||console.warn("[lunora] setAuthToken replaced a token that was just refused for a queued write, with no subject: without one a refresh reads as a user switch, so the held writes were discarded (OFFLINE_IDENTITY_CHANGED). Pass the user id, e.g. setAuthToken(token, user.id), to keep them across a refresh.")}rejectQueuedForIdentityChange(e){let s=this.offlineQueue.drain(),r=[];for(let i of s){if(this.identityVerdict(this.stampOf(i))!=="mismatch"){r.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);let a=new Error("offline mutation discarded: auth identity changed before replay");a.code="OFFLINE_IDENTITY_CHANGED",i.reject(a),this.emitItemSettled(i,"rejected",a)}this.offlineQueue.requeue(r),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,s){for(let r of this.connections.values())r.identity===e&&(r.identity=s)}restampQueuedIdentity(e,s){for(let[r,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(r,s);this.offlineQueue.restampIdentity(e,s)}restampWatermarks(e,s){let r=e??"",i=this.clientWatermarks.get(r);if(i===void 0)return;this.clientWatermarks.delete(r);let a=s??"",o=this.clientWatermarks.get(a);if(o===void 0)this.clientWatermarks.set(a,i);else for(let[c,u]of i)o.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(()=>{})}evictPreviousIdentitySession(){this.revokeCacheSeededValues();for(let e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.acked=!1,ee(e,void 0);for(let e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,nr(e);this.bounceShardSockets(),this.retiredIdentities+=1,this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;let e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}bounceShardSockets(){for(let e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}}flushAllOfflineQueues(){for(let e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){let s=g(e),r=this.offlineFlushes.get(s);if(r===void 0&&this.offlineQueue.size===0)return;let i=(async()=>{await(r??Promise.resolve());let{authToken:a}=this;try{await this.drainOfflineQueue(e,a)}catch{}!this.closed&&this.authToken!==a&&this.offlineQueue.size>0&&Dt(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(s,i),await i,this.offlineFlushes.get(s)===i&&(this.offlineFlushes.delete(s),this.releaseIdleShard(e))}async drainOfflineQueue(e,s){let r=this.offlineQueue.drainConflict();for(let h of r){this.unpersist(h.id),this.queuedIdentities.delete(h.id??"");let l=new Error("offline mutation skipped: precondition failed before replay");l.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(h,"rejected",l)}let i=g(e),a=this.offlineQueue.drain(h=>g(h.shardKey)===i);if(a.length===0)return;let o=[],c=[];for(let h of a){let l=this.replayGateVerdict(h);l==="send"?o.push(h):l==="hold"&&c.push(h)}if(this.offlineQueue.requeue(c),c.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),o.length===0){this.scheduleRateLimitedRetry(e);return}let u=this.encodableOrSettleTerminal(o);if(u.length===0){this.scheduleRateLimitedRetry(e);return}if(u.length===1){await this.replaySequential(u,e,s),this.scheduleRateLimitedRetry(e);return}let d=[];for(let h=0;h<u.length;h+=Qt){let l=u.slice(h,h+Qt),f=await this.replayBatched(l,e,s);if(d.push(...f.requeue),f.stop){d.push(...u.slice(h+Qt));break}}d.length>0&&this.offlineQueue.requeue(d),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){let s=g(e),r=this.replayRetryState.get(s),i=(r?.attempts??0)+1;this.replayRetryState.set(s,{attempts:i,delayMs:Math.max(r?.delayMs??0,Kt(i))})}noteReplayRetryDelay(e,s,r){let i=g(e),a=this.replayRetryState.get(i),o=(a?.attempts??0)+1,c=mo(s,o)??(r===null&&ze(s)?Kt(o):void 0);this.replayRetryState.set(i,{attempts:o,delayMs:c===void 0?a?.delayMs:Math.max(a?.delayMs??0,c)})}scheduleRateLimitedRetry(e){let s=g(e),r=this.replayRetryState.get(s),i=r?.delayMs;if(r===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(s);return}r.delayMs=void 0;let a=this.replayRetryTimers.get(s);a!==void 0&&clearTimeout(a),this.replayRetryTimers.set(s,setTimeout(()=>{this.replayRetryTimers.delete(s),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){let s=[];for(let r of e)try{re(r.args,`args for '${r.functionPath}'`),s.push(r)}catch(i){this.settleReplayTerminal(r,i instanceof Error?i:new Error(String(i)))}return s}identityVerdict(e){if(this.subjectAwaitingReconfirm())return"unknown";let s=this.identityFingerprint();return s===null&&this.identityUnresolved()?"unknown":e===s||e!==void 0&&this.isSameCredentialUnderTokenHash(e)?"match":s===null?"unknown":"mismatch"}replayGateVerdict(e){let s=this.stampOf(e);if(s===void 0)return this.queuedIdentities.delete(e.id??""),"send";let r=this.identityVerdict(s);if(r==="unknown")return"hold";if(this.queuedIdentities.delete(e.id??""),r==="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,s,r){this.unpersist(e.id),this.recordShardCursor(e.shardKey,r),e.onCommit?.(r),e.resolve(s),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,s){let r=e.headers.get("x-lunora-shard-key");if(r===null||s!==void 0||this.defaultShardKey===r)return;this.defaultShardKey=r;let i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(r,Math.max(this.shardCursors.get(r)??0,i)),this.shardCursors.delete(""))}recordShardCursor(e,s){if(typeof s!="number")return;let r=this.cursorKeyFor(e);this.shardCursors.set(r,Math.max(this.shardCursors.get(r)??0,s))}shouldRequeueReplayFailure(e,s){return this.noteIdentityMismatch(e)?!0:this.noteReplayAuthRefusal(e,s)||ho(e)}noteReplayAuthRefusal(e,s){if(!ze(e))return!1;let r=this.hashToken(s??"");return s===this.authToken&&this.authRefusalNotifiedFor!==r&&(this.authRefusalNotifiedFor=r,this.notifyTokenExpired()),!0}noteCredentialAccepted(e){this.authRefusalNotifiedFor!==void 0&&this.authRefusalNotifiedFor===this.hashToken(e??"")&&(this.authRefusalNotifiedFor=void 0)}takeReplayCredential(e){if(e===void 0)return;let s=this.replayCredentials.get(e);if(s===void 0)throw new TypeError("LunoraClient: `replayCredential` must come from this client's `replayIdentityVerdict`, and is single use");return this.replayCredentials.delete(e),{flags:{authToken:s.authToken,...Lt(s.stamp,s.authToken)},stamp:s.stamp}}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;let s=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===s&&(this.warnedIdentityDisagreement=!0,console.warn('[lunora] a replayed write was refused with IDENTITY_MISMATCH, but `/get-session` still names the same user. The worker\'s `resolveIdentity` must return the same `userId` as the better-auth `user.id`, and RPC requests must carry the session cookie (`credentials: "include"` on a cross-origin fetch).'))}).catch(()=>{}),!0}settleReplayUndecodable(e,s,r){this.unpersist(e.id),this.recordShardCursor(e.shardKey,r),e.onCommit?.(r),e.reject(s),this.emitItemSettled(e,"committed",s)}settleReplayTerminal(e,s){this.unpersist(e.id),e.reject(s),this.emitItemSettled(e,"rejected",s)}async replaySequential(e,s,r){for(let i=0;i<e.length;i+=1){let a=e[i];if(!a)continue;let o;try{let c=await this.rpc(a.functionPath,a.args,a.shardKey,{authToken:r,baselineSeq:a.baselineSeq,captureBookmark:!0,clientId:a.clientId??this.clientId,...Lt(a.identity,r),mutationId:a.id,onCommitCursor:n(u=>{o=u},"onCommitCursor")});this.settleReplaySuccess(a,c,o)}catch(c){if(tt(c)){this.settleReplayUndecodable(a,c,o);continue}if(!this.shouldRequeueReplayFailure(c,r)){this.settleReplayTerminal(a,c);continue}this.noteReplayRetryDelay(s,c,r),this.offlineQueue.requeue(e.slice(i));return}}}async replayBatched(e,s,r){if(!this.fetchImpl)return{requeue:e,stop:!0};let i=JSON.stringify({calls:e.map((d,h)=>({args:re(d.args,`args for '${d.functionPath}'`),baselineSeq:d.baselineSeq,functionPath:d.functionPath,id:h,clientId:d.clientId??this.clientId,mutationId:d.id,shardKey:d.shardKey}))});if(e.length>1&&bo(i)>yo)return await this.replayBatchedHalves(e,s,r);let a;try{a=await this.fetchImpl(se(this.url,_t),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:r,...Lt(e.find(d=>d.identity!==void 0)?.identity,r)}),method:"POST"})}catch{return{requeue:e,stop:!0}}let o=a.headers.get("x-d1-bookmark");if(o&&this.bookmark.set(o),a.status===413&&e.length>1)return await this.replayBatchedHalves(e,s,r);let c,u=a.headers.get("retry-after");try{c=await a.json()}catch{return this.settleWholeBatchError(e,ke(a.status,a.statusText,u),s,r)}if(!c.results){let d=fe(c),h=d===void 0?ke(a.status,a.statusText,u):Ft(d,u);return this.settleWholeBatchError(e,h,s,r)}return{requeue:this.settleReplayBatchSlots(e,c.results,s,r),stop:!1}}settleWholeBatchError(e,s,r,i){if(s instanceof $||s.code!==void 0&&this.shouldRequeueReplayFailure(s,i))return this.noteReplayRetryDelay(r,s,i),{requeue:e,stop:!0};for(let a of e)this.settleReplayTerminal(a,s);return{requeue:[],stop:!1}}async replayBatchedHalves(e,s,r){let i=Math.ceil(e.length/2),a=await this.replayBatched(e.slice(0,i),s,r);if(a.stop)return{requeue:[...a.requeue,...e.slice(i)],stop:!0};let o=await this.replayBatched(e.slice(i),s,r);return{requeue:[...a.requeue,...o.requeue],stop:o.stop}}settleReplayBatchSlots(e,s,r,i){let a=go(s),o=[],c=!1,u=!1;for(let[d,h]of e.entries()){let l=vo(a.get(d));switch(l.kind){case"committed":{c=!0,this.settleReplaySuccess(h,l.value,l.commitCursor);break}case"errored":{u||=ze(l.error),this.shouldRequeueReplayFailure(l.error,i)?(this.noteReplayRetryDelay(r,l.error,i),o.push(h)):this.settleReplayTerminal(h,l.error);break}case"unanswered":{o.push(h);break}default:c=!0,this.settleReplayUndecodable(h,l.error,l.commitCursor)}}return c&&!u&&this.noteCredentialAccepted(i),o}};var pr=x(Jt(),1),mr=x(Y(),1);var Qo=n(()=>{let t=(0,pr.c)(4),e=St(),s,r,i;return t[0]!==e?(s=n(a=>e.onConnectionStatus(()=>{a()}),"o"),r=n(()=>e.connectionStatus(),"e"),i=n(()=>e.connectionStatus(),"s"),t[0]=e,t[1]=s,t[2]=r,t[3]=i):(s=t[1],r=t[2],i=t[3]),(0,mr.useSyncExternalStore)(s,r,i)},"S");export{me as a,Ie as b,q as c,T as d,Dr as e,Bt as f,jr as g,be as h,Xr as i,Zr as j,si as k,St as l,Qo as m};
|