@lunora/studio 1.0.0-alpha.347 → 1.0.0-alpha.349

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.
Files changed (71) hide show
  1. package/dist/standalone/{chunk-H6FW2TMO.js → chunk-4H5PBJNF.js} +1 -1
  2. package/dist/standalone/{chunk-4TYCTORB.js → chunk-4UBF7HMZ.js} +1 -1
  3. package/dist/standalone/{chunk-IIU4TZRG.js → chunk-533J6WYA.js} +1 -1
  4. package/dist/standalone/{chunk-MT4E42PB.js → chunk-5J4FLDJH.js} +1 -1
  5. package/dist/standalone/{chunk-CCTWURT3.js → chunk-5ZNIQENA.js} +1 -1
  6. package/dist/standalone/{chunk-E4Y6TF6C.js → chunk-63QLK2KW.js} +1 -1
  7. package/dist/standalone/{chunk-SQYX2Z5H.js → chunk-63Z6OJ6G.js} +1 -1
  8. package/dist/standalone/{chunk-V7IFSDTT.js → chunk-75M6ZLLS.js} +1 -1
  9. package/dist/standalone/{chunk-R37RA67H.js → chunk-7EHAUFJY.js} +1 -1
  10. package/dist/standalone/{chunk-3FWAGIOT.js → chunk-7TN6VTTF.js} +1 -1
  11. package/dist/standalone/{chunk-XWGORWQU.js → chunk-AWWECTQT.js} +1 -1
  12. package/dist/standalone/{chunk-WQW4IPHB.js → chunk-AXL4YZJR.js} +1 -1
  13. package/dist/standalone/{chunk-R75AFV7G.js → chunk-C7FJ2JKY.js} +1 -1
  14. package/dist/standalone/{chunk-6TJHYXQW.js → chunk-COK5BCWN.js} +1 -1
  15. package/dist/standalone/{chunk-L4BDA4VZ.js → chunk-CULVXE3K.js} +1 -1
  16. package/dist/standalone/{chunk-XEGAP64U.js → chunk-CWPBPBWJ.js} +1 -1
  17. package/dist/standalone/{chunk-JD6SCY7V.js → chunk-E4BAGQ53.js} +1 -1
  18. package/dist/standalone/{chunk-R457VG7L.js → chunk-EBTYSPZB.js} +1 -1
  19. package/dist/standalone/{chunk-B57UZJ6W.js → chunk-EC5PMSQ6.js} +1 -1
  20. package/dist/standalone/{chunk-IQ3SMVFW.js → chunk-G43F7LYA.js} +1 -1
  21. package/dist/standalone/{chunk-NARRSYMQ.js → chunk-GC5UHRDR.js} +1 -1
  22. package/dist/standalone/{chunk-XR2JH2A7.js → chunk-GRHO2IUN.js} +1 -1
  23. package/dist/standalone/{chunk-KZJ5IOS2.js → chunk-GZEWLX7U.js} +1 -1
  24. package/dist/standalone/{chunk-6FZLAL4W.js → chunk-H467GBSD.js} +1 -1
  25. package/dist/standalone/chunk-HBO4SMAO.js +15 -0
  26. package/dist/standalone/{chunk-FTN4XJOQ.js → chunk-HBTGWHTW.js} +1 -1
  27. package/dist/standalone/{chunk-DJ3BKVAZ.js → chunk-HZTJLEIJ.js} +1 -1
  28. package/dist/standalone/{chunk-XCWVO6DI.js → chunk-I57ZVLUB.js} +1 -1
  29. package/dist/standalone/{chunk-2PMCHTCC.js → chunk-IRKWOUXO.js} +1 -1
  30. package/dist/standalone/{chunk-EGYPW6UY.js → chunk-IUSKFS3B.js} +1 -1
  31. package/dist/standalone/{chunk-ATVMUIBN.js → chunk-L5MI4PTP.js} +1 -1
  32. package/dist/standalone/{chunk-TET2ESOI.js → chunk-LVIL2SFA.js} +1 -1
  33. package/dist/standalone/{chunk-6XPDVZVB.js → chunk-LYQZERWS.js} +1 -1
  34. package/dist/standalone/{chunk-BOMFGCKX.js → chunk-MPEIBWCJ.js} +1 -1
  35. package/dist/standalone/{chunk-N45O7D5G.js → chunk-NCFYQR4L.js} +1 -1
  36. package/dist/standalone/{chunk-WW7D5RFR.js → chunk-NOS2OC45.js} +1 -1
  37. package/dist/standalone/{chunk-JGUKFZ3R.js → chunk-OQ2ORNN6.js} +1 -1
  38. package/dist/standalone/{chunk-C7SAXSO3.js → chunk-OVBYLXPD.js} +1 -1
  39. package/dist/standalone/{chunk-U7KUGVBB.js → chunk-OWQHP4KI.js} +1 -1
  40. package/dist/standalone/{chunk-LI2GRPOB.js → chunk-PKSRXFSZ.js} +1 -1
  41. package/dist/standalone/{chunk-EFGDGZHN.js → chunk-QC2GLF3I.js} +1 -1
  42. package/dist/standalone/{chunk-4GHCKQLY.js → chunk-QFK4UI4Q.js} +1 -1
  43. package/dist/standalone/{chunk-EPI4SHLN.js → chunk-QJ4AALXU.js} +1 -1
  44. package/dist/standalone/{chunk-M7HCYBJJ.js → chunk-R3RBUT32.js} +1 -1
  45. package/dist/standalone/{chunk-5YLFS5NU.js → chunk-RNYOBPQA.js} +1 -1
  46. package/dist/standalone/{chunk-T2JHVL34.js → chunk-RX755NMO.js} +1 -1
  47. package/dist/standalone/{chunk-MFZF7GEM.js → chunk-RYBLB23Z.js} +1 -1
  48. package/dist/standalone/{chunk-RTWSDGPV.js → chunk-S3EWTSAN.js} +1 -1
  49. package/dist/standalone/{chunk-JLQPIE3Z.js → chunk-S4AR74DJ.js} +2 -2
  50. package/dist/standalone/{chunk-KEHDC5BQ.js → chunk-SFMIR4YV.js} +1 -1
  51. package/dist/standalone/{chunk-4HYPC5NN.js → chunk-SROQCZ3P.js} +1 -1
  52. package/dist/standalone/{chunk-TNPF3XGI.js → chunk-T4SIZOJG.js} +1 -1
  53. package/dist/standalone/{chunk-GDP3S4GQ.js → chunk-U37BPX5J.js} +1 -1
  54. package/dist/standalone/{chunk-34OJ2OXP.js → chunk-UFZVSXRW.js} +1 -1
  55. package/dist/standalone/{chunk-XCVO3IAH.js → chunk-UQWGBWQ3.js} +1 -1
  56. package/dist/standalone/{chunk-PTIKIQY6.js → chunk-V6LPISRQ.js} +1 -1
  57. package/dist/standalone/{chunk-TVSU6RYZ.js → chunk-VFFW3ANI.js} +1 -1
  58. package/dist/standalone/{chunk-5TQHZVNN.js → chunk-WEPM5G3R.js} +1 -1
  59. package/dist/standalone/{chunk-XJPJSZ4W.js → chunk-WGBAHXMK.js} +1 -1
  60. package/dist/standalone/{chunk-6BELLPMP.js → chunk-WGUN4FNJ.js} +1 -1
  61. package/dist/standalone/{chunk-SJYQFABZ.js → chunk-WNMY5ZKL.js} +1 -1
  62. package/dist/standalone/{chunk-6I2QO7SE.js → chunk-WOEHFC4J.js} +1 -1
  63. package/dist/standalone/{chunk-QDHFLZ3N.js → chunk-WX647YQ7.js} +1 -1
  64. package/dist/standalone/chunk-YBDF3DET.js +7 -0
  65. package/dist/standalone/{chunk-PQ6DUCKC.js → chunk-YJI56OCF.js} +1 -1
  66. package/dist/standalone/{chunk-RLVR5BRF.js → chunk-YUPEDAX3.js} +1 -1
  67. package/dist/standalone/{chunk-KNUGID7F.js → chunk-ZN7TURF4.js} +1 -1
  68. package/dist/standalone/studio.js +1 -1
  69. package/package.json +5 -5
  70. package/dist/standalone/chunk-3I25WO3P.js +0 -15
  71. package/dist/standalone/chunk-AVSMQPR3.js +0 -7
@@ -0,0 +1,7 @@
1
+ import{a as ps,d as g}from"./chunk-HBO4SMAO.js";import{a,d as D,e as re,f as fs,g as lt}from"./chunk-I26MS5PJ.js";var Nr=/["\\\u0000-\u001F\uD800-\uDFFF]/,ms=a(t=>Nr.test(t)?JSON.stringify(t):`"${t}"`,"c"),jr=a(t=>Number.isNaN(t)?"nan":t===1/0?"inf":t===-1/0?"-inf":Object.is(t,-0)?"-0":void 0,"b"),qr=a((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(),n="{",o=!0;for(let c of i){let u=r[c];u!==void 0&&(o?o=!1:n+=",",n+=ms(c),n+=":",n+=e(u))}return`${n}}`},"u"),Se=a(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=="function"||typeof t=="symbol")throw new TypeError(`stableStringify: cannot use a ${typeof t} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported`);if(typeof t=="number"){let e=jr(t);if(e!==void 0)return e}return typeof t=="string"?ms(t):t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${Array.from({length:t.length},(e,s)=>Se(t[s])).join(",")}]`:qr(t,Se)},"y");var De=a(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"e");var Ue=a(t=>{let e="";for(let s=0;s<t.length;s+=32768)e+=String.fromCharCode(...t.subarray(s,s+32768));return btoa(e)},"f"),Wr=a(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"),F="$lunora.wire$",Ke=64,Ne=1024,Br="__proto__",$r=/^-?\d+$/,ys={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},gs={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},pt=a((t,e,s)=>{e===Br?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:s,writable:!0}):t[e]=s},"y");var Hr=a(t=>{let e=t.toString();if(e.length>Ne)throw new RangeError(`wire-codec: over-long bigint (max ${String(Ne)} digits)`);return[F,"bigint",e]},"T"),zr=a(t=>Number.isNaN(t)?[F,"nan"]:t===1/0?[F,"inf"]:t===-1/0?[F,"-inf"]:t,"j"),Gr=a((t,e)=>{let s=e(Object.fromEntries(Object.keys(t).map(n=>[n,t[n]]))),r=t,i=[F,"error",String(r.name),String(r.message),s];return t.cause!==void 0&&i.push(e(t.cause)),i},"R"),Vr=a(t=>{let e=t.constructor.name,s=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return e==="Uint8Array"?[F,"bytes",Ue(s)]:[F,"bytes",Ue(s),e]},"S"),Jr=a((t,e)=>t instanceof Date?[F,"date",e(t.getTime())]:t instanceof Error?Gr(t,e):t instanceof URL?[F,"url",t.href]:t instanceof Map?[F,"map",[...t.entries()].map(([s,r])=>[e(s),e(r)])]:t instanceof Set?[F,"set",[...t].map(s=>e(s))]:t instanceof ArrayBuffer?[F,"bytes",Ue(new Uint8Array(t)),"ArrayBuffer"]:ArrayBuffer.isView(t)?Vr(t):void 0,"U"),Yr=a((t,e)=>{let s=t.map(r=>e(r));return s.length>0&&s[0]===F?[F,"arr",s]:s},"I"),Xr=a((t,e)=>{let s={};for(let r of Object.keys(t)){let i=t[r];i!==void 0&&pt(s,r,e(i))}return s},"B"),$=a((t,e=0)=>{if(e>Ke)throw new RangeError(`wire-codec: value nesting exceeds the ${String(Ke)}-level limit`);if(t===void 0)return[F,"undefined"];if(t===null)return t;if(typeof t=="bigint")return Hr(t);if(typeof t=="number")return zr(t);if(typeof t!="object")return t;let s=a(i=>$(i,e+1),"t"),r=Jr(t,s);if(r!==void 0)return r;if(Array.isArray(t))return Yr(t,s);if(!De(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 Xr(t,s)},"m"),Zr=a(t=>{let e=t[2];if(typeof e!="string"||e.length>Ne||!$r.test(e))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${String(Ne)} digits)`);return BigInt(e)},"N"),ei=a((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)},"_"),ti=a((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])]}))},"$"),si=a(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"),ri=a((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(gs,s)?gs[s]:void 0)??Error,n=new i(r);n.name!==s&&Object.defineProperty(n,"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))pt(n,c,u);return t.length>5&&Object.defineProperty(n,"cause",{configurable:!0,value:e(t[5]),writable:!0}),n},"P"),ii=a(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=Wr(e);if(Ue(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(ys,r)?ys[r]:void 0;return i?new i(new Uint8Array(s).buffer):s},"D"),ni=a((t,e)=>{switch(t[1]){case"-inf":return-1/0;case"arr":return t[2].map(s=>e(s));case"bigint":return Zr(t);case"bytes":return ii(t);case"date":return ei(t,e);case"error":return ri(t,e);case"inf":return 1/0;case"map":return ti(t,e);case"nan":return Number.NaN;case"set":return new Set(t[2].map(s=>e(s)));case"undefined":return;case"url":return si(t);default:return t.map(s=>e(s))}},"C"),ai=a((t,e)=>{let s={};for(let r of Object.keys(t))pt(s,r,e(t[r]));return s},"L"),T=a((t,e=0)=>{if(e>Ke)throw new RangeError(`wire-codec: value nesting exceeds the ${String(Ke)}-level limit`);if(t===null||typeof t!="object")return t;let s=a(r=>T(r,e+1),"t");if(Array.isArray(t)){let r=t;return r[0]===F?ni(r,s):r.map(i=>s(i))}return ai(t,s)},"A"),oi=a(t=>{try{let e=T(JSON.parse(t));return De(e)?e:void 0}catch{return}},"F");var j=a(t=>Se($(t)),"a");var he=D(re(),1),vs=D(lt(),1);var we=he.createContext(void 0),Ce=a(t=>{let e=he.useContext(we);if(t)return t;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},"useQueryClient"),ft=a(({client:t,children:e})=>(he.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,vs.jsx)(we.Provider,{value:t,children:e})),"QueryClientProvider");var N=class{static{a(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 ci=class extends N{static{a(this,"FocusManager")}#e;#t;#s;constructor(){super(),this.#s=t=>{if(typeof window<"u"&&window.addEventListener){let e=a(()=>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"}},de=new ci;var ui={setTimeout:a((t,e)=>setTimeout(t,e),"setTimeout"),clearTimeout:a(t=>clearTimeout(t),"clearTimeout"),setInterval:a((t,e)=>setInterval(t,e),"setInterval"),clearInterval:a(t=>clearInterval(t),"clearInterval")},hi=class{static{a(this,"TimeoutManager")}#e=ui;#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)}},H=new hi;function bs(t){setTimeout(t,0)}a(bs,"systemSetTimeoutZero");var yt=typeof window>"u"||"Deno"in globalThis;function E(){}a(E,"noop");function Cs(t,e){return typeof t=="function"?t(e):t}a(Cs,"functionalUpdate");function ke(t){return typeof t=="number"&&t>=0&&t!==1/0}a(ke,"isValidTimeout");function je(t,e){return Math.max(t+(e||0)-Date.now(),0)}a(je,"timeUntilStale");function q(t,e){return typeof t=="function"?t(e):t}a(q,"resolveStaleTime");function x(t,e){return typeof t=="function"?t(e):t}a(x,"resolveQueryBoolean");function qe(t,e){let{type:s="all",exact:r,fetchStatus:i,predicate:n,queryKey:o,stale:c}=t;if(o){if(r){if(e.queryHash!==Te(o,e.options))return!1}else if(!ie(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||n&&!n(e))}a(qe,"matchQuery");function We(t,e){let{exact:s,status:r,predicate:i,mutationKey:n}=t;if(n){if(!e.options.mutationKey)return!1;if(s){if(z(e.options.mutationKey)!==z(n))return!1}else if(!ie(e.options.mutationKey,n))return!1}return!(r&&e.state.status!==r||i&&!i(e))}a(We,"matchMutation");function Te(t,e){return(e?.queryKeyHashFn||z)(t)}a(Te,"hashQueryKeyByOptions");function z(t){return JSON.stringify(t,(e,s)=>mt(s)?Object.keys(s).sort().reduce((r,i)=>(r[i]=s[i],r),{}):s)}a(z,"hashKey");function ie(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(!ie(t[r],e[r]))return!1;return!0}let s=Object.keys(e);for(let r of s)if(!ie(t[r],e[r]))return!1;return!0}return!1}a(ie,"partialMatchKey");var di=Object.prototype.hasOwnProperty;function gt(t,e,s=0){if(t===e)return t;if(s>500)return e;let r=Ss(t)&&Ss(e);if(!r&&!(mt(t)&&mt(e)))return e;let n=(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],p=t[l],f=e[l];if(p===f){u[l]=p,(r?h<n:di.call(t,l))&&d++;continue}if(p===null||f===null||typeof p!="object"||typeof f!="object"){u[l]=f;continue}let y=gt(p,f,s+1);u[l]=y,y===p&&d++}return n===c&&d===n?t:u}a(gt,"replaceEqualDeep");function le(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}a(le,"shallowEqualObjects");function Ss(t){return Array.isArray(t)&&t.length===Object.keys(t).length}a(Ss,"isPlainArray");function mt(t){if(!ws(t))return!1;let e=t.constructor;if(e===void 0)return!0;let s=e.prototype;return!(!ws(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}a(mt,"isPlainObject");function ws(t){return Object.prototype.toString.call(t)==="[object Object]"}a(ws,"hasObjectPrototype");function ks(t){return new Promise(e=>{H.setTimeout(e,t)})}a(ks,"sleep");function Ee(t,e,s){return typeof s.structuralSharing=="function"?s.structuralSharing(t,e):s.structuralSharing!==!1?gt(t,e):e}a(Ee,"replaceData");function li(t){return t}a(li,"keepPreviousData");function Ts(t,e,s=0){let r=[...t,e];return s&&r.length>s?r.slice(1):r}a(Ts,"addToEnd");function Es(t,e,s=0){let r=[e,...t];return s&&r.length>s?r.slice(0,-1):r}a(Es,"addToStart");var pe=Symbol();function Be(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===pe?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}a(Be,"ensureQueryFn");function fe(t,e){return typeof t=="function"?t(...e):!!t}a(fe,"shouldThrowError");function Os(t,e,s){let r=!1,i;return Object.defineProperty(t,"signal",{enumerable:!0,get:a(()=>(i??=e(),r||(r=!0,i.aborted?s():i.addEventListener("abort",s,{once:!0})),i),"get")}),t}a(Os,"addConsumeAwareSignal");var G=(()=>{let t=a(()=>yt,"isServerFn");return{isServer(){return t()},setIsServer(e){t=e}}})();function Oe(){let t,e,s=new Promise((i,n)=>{t=i,e=n});s.status="pending",s.catch(()=>{});function r(i){Object.assign(s,i),delete s.resolve,delete s.reject}return a(r,"finalize"),s.resolve=i=>{r({status:"fulfilled",value:i}),t(i)},s.reject=i=>{r({status:"rejected",reason:i}),e(i)},s}a(Oe,"pendingThenable");var Is=bs;function pi(){let t=[],e=0,s=a(c=>{c()},"notifyFn"),r=a(c=>{c()},"batchNotifyFn"),i=Is,n=a(c=>{e?t.push(c):i(()=>{s(c)})},"schedule"),o=a(()=>{let c=t;t=[],c.length&&i(()=>{r(()=>{c.forEach(u=>{s(u)})})})},"flush");return{batch:a(c=>{let u;e++;try{u=c()}finally{e--,e||o()}return u},"batch"),batchCalls:a(c=>(...u)=>{n(()=>{c(...u)})},"batchCalls"),schedule:n,setNotifyFunction:a(c=>{s=c},"setNotifyFunction"),setBatchNotifyFunction:a(c=>{r=c},"setBatchNotifyFunction"),setScheduler:a(c=>{i=c},"setScheduler")}}a(pi,"createNotifyManager");var C=pi();var fi=class extends N{static{a(this,"OnlineManager")}#e=!0;#t;#s;constructor(){super(),this.#s=t=>{if(typeof window<"u"&&window.addEventListener){let e=a(()=>t(!0),"onlineListener"),s=a(()=>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}},me=new fi;function mi(t){return Math.min(1e3*2**t,3e4)}a(mi,"defaultRetryDelay");function vt(t){return(t??"online")==="online"?me.isOnline():!0}a(vt,"canFetch");var $e=class extends Error{static{a(this,"CancelledError")}constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function He(t){let e=!1,s=0,r,i=Oe(),n=a(()=>i.status!=="pending","isResolved"),o=a(m=>{if(!n()){let b=new $e(m);p(b),t.onCancel?.(b)}},"cancel"),c=a(()=>{e=!0},"cancelRetry"),u=a(()=>{e=!1},"continueRetry"),d=a(()=>de.isFocused()&&(t.networkMode==="always"||me.isOnline())&&t.canRun(),"canContinue"),h=a(()=>vt(t.networkMode)&&t.canRun(),"canStart"),l=a(m=>{n()||(r?.(),i.resolve(m))},"resolve"),p=a(m=>{n()||(r?.(),i.reject(m))},"reject"),f=a(()=>new Promise(m=>{r=a(b=>{(n()||d())&&m(b)},"continueFn"),t.onPause?.()}).then(()=>{r=void 0,n()||t.onContinue?.()}),"pause"),y=a(()=>{if(n())return;let m,b=s===0?t.initialPromise:void 0;try{m=b??t.fn()}catch(S){m=Promise.reject(S)}Promise.resolve(m).then(l).catch(S=>{if(n())return;let k=t.retry??(G.isServer()?0:3),O=t.retryDelay??mi,w=typeof O=="function"?O(s,S):O,I=k===!0||typeof k=="number"&&s<k||typeof k=="function"&&k(s,S);if(e||!I){p(S);return}s++,t.onFail?.(s,S),ks(w).then(()=>d()?void 0:f()).then(()=>{e?p(S):y()})})},"run");return{promise:i,status:a(()=>i.status,"status"),cancel:o,continue:a(()=>(r?.(),i),"continue"),cancelRetry:c,continueRetry:u,canStart:h,start:a(()=>(h()?y():f().then(y),i),"start")}}a(He,"createRetryer");var ze=class{static{a(this,"Removable")}#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ke(this.gcTime)&&(this.#e=H.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(G.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(H.clearTimeout(this.#e),this.#e=void 0)}};function As(t){return{onFetch:a((e,s)=>{let r=e.options,i=e.fetchOptions?.meta?.fetchMore?.direction,n=e.state.data?.pages||[],o=e.state.data?.pageParams||[],c={pages:[],pageParams:[]},u=0,d=a(async()=>{let h=!1,l=a(y=>{Os(y,()=>e.signal,()=>h=!0)},"addSignalProperty"),p=Be(e.options,e.fetchOptions),f=a(async(y,m,b)=>{if(h)return Promise.reject(e.signal.reason);if(m==null&&y.pages.length)return Promise.resolve(y);let k=a(()=>{let se={client:e.client,queryKey:e.queryKey,pageParam:m,direction:b?"backward":"forward",meta:e.options.meta};return l(se),se},"createQueryFnContext")(),O=await p(k),{maxPages:w}=e.options,I=b?Es:Ts;return{pages:I(y.pages,O,w),pageParams:I(y.pageParams,m,w)}},"fetchPage");if(i&&n.length){let y=i==="backward",m=y?yi:Rs,b={pages:n,pageParams:o},S=m(r,b);c=await f(b,S,y)}else{let y=t??n.length;do{let m=u===0?o[0]??r.initialPageParam:Rs(r,c);if(u>0&&m==null)break;c=await f(c,m),u++}while(u<y)}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")}}a(As,"infiniteQueryBehavior");function Rs(t,{pages:e,pageParams:s}){let r=e.length-1;return e.length>0?t.getNextPageParam(e[r],e,s[r],s):void 0}a(Rs,"getNextPageParam");function yi(t,{pages:e,pageParams:s}){return e.length>0?t.getPreviousPageParam?.(e[0],e,s[0],s):void 0}a(yi,"getPreviousPageParam");var Ms=class extends ze{static{a(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=Ps(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=Ps(this.options);e.data!==void 0&&(this.setState(Fs(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#r.remove(this)}setData(t,e){let s=Ee(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(E).catch(E):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=>x(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===pe||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>q(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:!je(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=a(u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:a(()=>(this.#a=!0,s.signal),"get")})},"addSignalProperty"),i=a(()=>{let u=Be(this.options,e),h=a(()=>{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=a(()=>{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"?As(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=He({initialPromise:e?.initialPromise,fn:o.fetchFn,onCancel:a(u=>{u instanceof $e&&u.revert&&this.setState({...this.#s,fetchStatus:"idle"}),s.abort()},"onCancel"),onFail:a((u,d)=>{this.#c({type:"failed",failureCount:u,error:d})},"onFail"),onPause:a(()=>{this.#c({type:"pause"})},"onPause"),onContinue:a(()=>{this.#c({type:"continue"})},"onContinue"),retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:a(()=>!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=a(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,...bt(s.data,this.options),fetchMeta:t.meta??null};case"success":let r={...s,...Fs(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),C.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),this.#r.notify({query:this,type:"updated",action:t})})}};function bt(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:vt(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}a(bt,"fetchState");function Fs(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}a(Fs,"successState");function Ps(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"}}a(Ps,"getDefaultState");var wt=class extends N{static{a(this,"QueryObserver")}constructor(t,e){super(),this.options=e,this.#e=t,this.#a=null,this.#o=Oe(),this.bindMethods(),this.setOptions(e)}#e;#t=void 0;#s=void 0;#r=void 0;#n;#i;#o;#a;#h;#c;#f;#d;#l;#u;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Ls(this.#t,this.options)?this.#p():this.updateResult(),this.#b())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return St(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return St(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 x(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&&!le(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});let r=this.hasListeners();r&&xs(this.#t,s,this.options,e)&&this.#p(),this.updateResult(),r&&(this.#t!==s||x(this.options.enabled,this.#t)!==x(e.enabled,this.#t)||q(this.options.staleTime,this.#t)!==q(e.staleTime,this.#t))&&this.#y();let i=this.#g();r&&(this.#t!==s||x(this.options.enabled,this.#t)!==x(e.enabled,this.#t)||i!==this.#u)&&this.#v(i)}getOptimisticResult(t){let e=this.#e.getQueryCache().build(this.#e,t),s=this.createResult(e,t);return vi(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:a((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.#p({...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#p(t){this.#C();let e=this.#t.fetch(this.options,t);return t?.throwOnError||(e=e.catch(E)),e}#y(){this.#S();let t=q(this.options.staleTime,this.#t);if(G.isServer()||this.#r.isStale||!ke(t))return;let s=je(this.#r.dataUpdatedAt,t)+1;this.#d=H.setTimeout(()=>{this.#r.isStale||this.updateResult()},s)}#g(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(t){this.#w(),this.#u=t,!(G.isServer()||x(this.options.enabled,this.#t)===!1||!ke(this.#u)||this.#u===0)&&(this.#l=H.setInterval(()=>{(this.options.refetchIntervalInBackground||de.isFocused())&&this.#p()},this.#u))}#b(){this.#y(),this.#v(this.#g())}#S(){this.#d!==void 0&&(H.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#l!==void 0&&(H.clearInterval(this.#l),this.#l=void 0)}createResult(t,e){let s=this.#t,r=this.options,i=this.#r,n=this.#n,o=this.#i,u=t!==s?t.state:this.#s,{state:d}=t,h={...d},l=!1,p;if(e._optimisticResults){let A=this.hasListeners(),R=!A&&Ls(t,e),Y=A&&xs(t,s,e,r);(R||Y)&&(h={...h,...bt(d.data,t.options)}),e._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:f,errorUpdatedAt:y,status:m}=h;p=h.data;let b=!1;if(e.placeholderData!==void 0&&p===void 0&&m==="pending"){let A;i?.isPlaceholderData&&e.placeholderData===o?.placeholderData?(A=i.data,b=!0):A=typeof e.placeholderData=="function"?e.placeholderData(this.#f?.state.data,this.#f):e.placeholderData,A!==void 0&&(m="success",p=Ee(i?.data,A,e),l=!0)}if(e.select&&p!==void 0&&!b)if(i&&p===n?.data&&e.select===this.#h)p=this.#c;else try{this.#h=e.select,p=e.select(p),p=Ee(i?.data,p,e),this.#c=p,this.#a=null}catch(A){this.#a=A}this.#a&&(f=this.#a,p=this.#c,y=Date.now(),m="error");let S=h.fetchStatus==="fetching",k=m==="pending",O=m==="error",w=k&&S,I=p!==void 0,L={status:m,fetchStatus:h.fetchStatus,isPending:k,isSuccess:m==="success",isError:O,isInitialLoading:w,isLoading:w,data:p,dataUpdatedAt:h.dataUpdatedAt,error:f,errorUpdatedAt:y,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:h.dataUpdateCount>u.dataUpdateCount||h.errorUpdateCount>u.errorUpdateCount,isFetching:S,isRefetching:S&&!k,isLoadingError:O&&!I,isPaused:h.fetchStatus==="paused",isPlaceholderData:l,isRefetchError:O&&I,isStale:Ct(t,e),refetch:this.refetch,promise:this.#o,isEnabled:x(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let A=L.data!==void 0,R=L.status==="error"&&!A,Y=a(_e=>{R?_e.reject(L.error):A&&_e.resolve(L.data)},"finalizeThenableIfPossible"),ls=a(()=>{let _e=this.#o=L.promise=Oe();Y(_e)},"recreateThenable"),Qe=this.#o;switch(Qe.status){case"pending":t.queryHash===s.queryHash&&Y(Qe);break;case"fulfilled":(R||L.data!==Qe.value)&&ls();break;case"rejected":(!R||L.error!==Qe.reason)&&ls();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.#f=this.#t),le(e,t))return;this.#r=e;let s=a(()=>{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 n=new Set(i??this.#m);return this.options.throwOnError&&n.add("error"),Object.keys(this.#r).some(o=>{let c=o;return this.#r[c]!==t[c]&&n.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.#b()}#k(t){C.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function gi(t,e){return x(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&x(e.retryOnMount,t)===!1)}a(gi,"shouldLoadOnMount");function Ls(t,e){return gi(t,e)||t.state.data!==void 0&&St(t,e,e.refetchOnMount)}a(Ls,"shouldFetchOnMount");function St(t,e,s){if(x(e.enabled,t)!==!1&&q(e.staleTime,t)!=="static"){let r=typeof s=="function"?s(t):s;return r==="always"||r!==!1&&Ct(t,e)}return!1}a(St,"shouldFetchOn");function xs(t,e,s,r){return(t!==e||x(r.enabled,t)===!1)&&(!s.suspense||t.state.status!=="error")&&Ct(t,s)}a(xs,"shouldFetchOptionally");function Ct(t,e){return x(e.enabled,t)!==!1&&t.isStaleByTime(q(e.staleTime,t))}a(Ct,"isStale");function vi(t,e){return!le(t.getCurrentResult(),e)}a(vi,"shouldAssignObserverCurrentProperties");var Qs=class extends ze{static{a(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||kt(),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=a(()=>{this.#n({type:"continue"})},"onContinue"),s={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#r=He({fn:a(()=>this.options.mutationFn?this.options.mutationFn(t,s):Promise.reject(new Error("No mutationFn found")),"fn"),onFail:a((n,o)=>{this.#n({type:"failed",failureCount:n,error:o})},"onFail"),onPause:a(()=>{this.#n({type:"pause"})},"onPause"),onContinue:e,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:a(()=>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 n=await this.#r.start();return await this.#s.config.onSuccess?.(n,t,this.state.context,this,s),await this.options.onSuccess?.(n,t,this.state.context,s),await this.#s.config.onSettled?.(n,null,this.state.variables,this.state.context,this,s),await this.options.onSettled?.(n,null,t,this.state.context,s),this.#n({type:"success",data:n}),n}catch(n){try{await this.#s.config.onError?.(n,t,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onError?.(n,t,this.state.context,s)}catch(o){Promise.reject(o)}try{await this.#s.config.onSettled?.(void 0,n,this.state.variables,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,n,t,this.state.context,s)}catch(o){Promise.reject(o)}throw this.#n({type:"error",error:n}),n}finally{this.#s.runNext(this)}}#n(t){let e=a(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),C.batch(()=>{this.#t.forEach(s=>{s.onMutationUpdate(t)}),this.#s.notify({mutation:this,type:"updated",action:t})})}};function kt(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}a(kt,"getDefaultState");var _s=class extends N{static{a(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 Qs({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=Ge(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=Ge(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=Ge(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=Ge(t);return typeof e=="string"?this.#t.get(e)?.find(r=>r!==t&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){C.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=>We(e,s))}findAll(t={}){return this.getAll().filter(e=>We(t,e))}notify(t){C.batch(()=>{this.listeners.forEach(e=>{e(t)})})}resumePausedMutations(){let t=this.getAll().filter(e=>e.state.isPaused);return C.batch(()=>Promise.all(t.map(e=>e.continue().catch(E))))}};function Ge(t){return t.options.scope?.id}a(Ge,"scopeFor");var Tt=class extends N{static{a(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),le(this.options,e)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#s,observer:this}),e?.mutationKey&&this.options.mutationKey&&z(e.mutationKey)!==z(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??kt();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){C.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 Ds=class extends N{static{a(this,"QueryCache")}constructor(t={}){super(),this.config=t,this.#e=new Map}#e;build(t,e,s){let r=e.queryKey,i=e.queryHash??Te(r,e),n=this.get(i);return n||(n=new Ms({client:t,queryKey:r,queryHash:i,options:t.defaultQueryOptions(e),state:s,defaultOptions:t.getQueryDefaults(r)}),this.add(n)),n}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(){C.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=>qe(e,s))}findAll(t={}){let e=this.getAll();return Object.keys(t).length>0?e.filter(s=>qe(t,s)):e}notify(t){C.batch(()=>{this.listeners.forEach(e=>{e(t)})})}onFocus(){C.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){C.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}};var Et=class{static{a(this,"QueryClient")}#e;#t;#s;#r;#n;#i;#o;#a;constructor(t={}){this.#e=t.queryCache||new Ds,this.#t=t.mutationCache||new _s,this.#s=t.defaultOptions||{},this.#r=new Map,this.#n=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#o=de.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#a=me.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(q(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}),n=this.#e.get(r.queryHash)?.state.data,o=Cs(e,n);if(o!==void 0)return this.#e.build(this,r).setData(o,{...s,manual:!0})}setQueriesData(t,e,s){return C.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;C.batch(()=>{e.findAll(t).forEach(s=>{e.remove(s)})})}resetQueries(t,e){let s=this.#e;return C.batch(()=>(s.findAll(t).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){let s={revert:!0,...e},r=C.batch(()=>this.#e.findAll(t).map(i=>i.cancel(s)));return Promise.all(r).then(E).catch(E)}invalidateQueries(t,e={}){return C.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=C.batch(()=>this.#e.findAll(t).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let n=i.fetch(void 0,s);return s.throwOnError||(n=n.catch(E)),i.state.fetchStatus==="paused"?Promise.resolve():n}));return Promise.all(r).then(E)}fetchQuery(t){let e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);let s=this.#e.build(this,e);return s.isStaleByTime(q(e.staleTime,s))?s.fetch(e):Promise.resolve(s.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(E).catch(E)}fetchInfiniteQuery(t){return t._type="infinite",this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(E).catch(E)}ensureInfiniteQueryData(t){return t._type="infinite",this.ensureQueryData(t)}resumePausedMutations(){return me.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(z(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){let e=[...this.#r.values()],s={};return e.forEach(r=>{ie(t,r.queryKey)&&Object.assign(s,r.defaultOptions)}),s}setMutationDefaults(t,e){this.#n.set(z(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){let e=[...this.#n.values()],s={};return e.forEach(r=>{ie(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=Te(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===pe&&(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 ne=D(re(),1);var Ie=D(re(),1),bi=D(lt(),1);function Si(){let t=!1;return{clearReset:a(()=>{t=!1},"clearReset"),reset:a(()=>{t=!0},"reset"),isReset:a(()=>t,"isReset")}}a(Si,"createValue");var wi=Ie.createContext(Si()),Us=a(()=>Ie.useContext(wi),"useQueryErrorResetBoundary");var Ks=D(re(),1);var Ns=a((t,e,s)=>{let r=s?.state.error&&typeof t.throwOnError=="function"?fe(t.throwOnError,[s.state.error,s]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||r)&&(e.isReset()||(t.retryOnMount=!1))},"ensurePreventErrorBoundaryRetry"),js=a(t=>{Ks.useEffect(()=>{t.clearReset()},[t])},"useClearResetErrorBoundary"),qs=a(({result:t,errorResetBoundary:e,throwOnError:s,query:r,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&r&&(i&&t.data===void 0||fe(s,[t.error,r])),"getHasError");var Ve=D(re(),1);var Ws=Ve.createContext(!1),Bs=a(()=>Ve.useContext(Ws),"useIsRestoring"),jh=Ws.Provider;var $s=a(t=>{if(t.suspense){let s=a(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"),Hs=a((t,e)=>t.isLoading&&t.isFetching&&!e,"willFetch"),zs=a((t,e)=>t?.suspense&&e.isPending,"shouldSuspend"),Ot=a((t,e,s)=>e.fetchOptimistic(t).catch(()=>{s.clearReset()}),"fetchOptimistic");function Gs(t,e,s){let r=Bs(),i=Us(),n=Ce(s),o=n.defaultQueryOptions(t);n.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let c=n.getQueryCache().get(o.queryHash),u=t.subscribed!==!1;o._optimisticResults=r?"isRestoring":u?"optimistic":void 0,$s(o),Ns(o,i,c),js(i);let d=!n.getQueryCache().get(o.queryHash),[h]=ne.useState(()=>new e(n,o)),l=h.getOptimisticResult(o),p=!r&&u;if(ne.useSyncExternalStore(ne.useCallback(f=>{let y=p?h.subscribe(C.batchCalls(f)):E;return h.updateResult(),y},[h,p]),()=>h.getCurrentResult(),()=>h.getCurrentResult()),ne.useEffect(()=>{h.setOptions(o)},[o,h]),zs(o,l))throw Ot(o,h,i);if(qs({result:l,errorResetBoundary:i,throwOnError:o.throwOnError,query:c,suspense:o.suspense}))throw l.error;return n.getDefaultOptions().queries?._experimental_afterQuery?.(o,l),o.experimental_prefetchInRender&&!G.isServer()&&Hs(l,r)&&(d?Ot(o,h,i):c?.promise)?.catch(E).finally(()=>{h.updateResult()}),o.notifyOnChangeProps?l:h.trackResult(l)}a(Gs,"useBaseQuery");function Ci(t,e){return Gs(t,wt,e)}a(Ci,"useQuery");var X=D(re(),1);function ki(t,e){let s=Ce(e),[r]=X.useState(()=>new Tt(s,t));X.useEffect(()=>{r.setOptions(t)},[r,t]);let i=X.useSyncExternalStore(X.useCallback(o=>r.subscribe(C.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),n=X.useCallback((o,c)=>{r.mutate(o,c).catch(E)},[r]);if(i.error&&fe(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:n,mutateAsync:i.mutate}}a(ki,"useMutation");var Xs=D(fs(),1);var Q=D(re(),1);var Je=D(lt(),1);var It=a(t=>j(t),"b");var Vs=a(t=>{t!==void 0&&(t.cancel({silent:!0}),t.setState({...t.state,data:void 0,dataUpdatedAt:0,error:null,fetchStatus:"idle",status:"pending"}))},"E"),Rt={status:"idle"},Js=a((t,e)=>{for(let s of t.waiters)s(e);t.waiters.clear()},"F"),Ti=1e4,Ei=a(async(t,e,s)=>new Promise((r,i)=>{if(e.aborted){i(e.reason);return}let n,o,c=a(()=>{clearTimeout(n),o?.(),t.waiters.delete(d),e.removeEventListener("abort",u)},"l"),u=a(()=>{c(),i(e.reason)},"t"),d=a(h=>{c(),r(h)},"n");n=setTimeout(()=>{d(!1)},Ti),t.waiters.add(d),e.addEventListener("abort",u,{once:!0}),o=s(()=>{d(!1)}),t.waiters.has(d)||o()}),"U"),Ft=class{static{a(this,"V")}constructor(e){this.client=e}client;entries=new Map;live=new Map;identityWatched=new Set;listening=!1;hasConsumers(e){return this.entries.has(It(e))}async liveValue(e,s,r,i){let{fetch:n,shardKey:o,waitForPush:c=!0}=i;if(!("window"in globalThis)||this.client.getWebSocketImpl()===void 0)return n();let u=It(s),d=this.liveFor(u),h=d.state.status==="pushed"?e.getQueryData(s)??d.state.value:void 0;if(h!==void 0)return h;if(c&&d.state.status!=="errored"&&!this.client.isCrossTabFollower()&&this.client.expectsPush({shardKey:o})){let f;try{f=await Ei(d,r,y=>this.client.onConnectionStatus(()=>{this.client.expectsPush({shardKey:o})||y()}))}finally{this.forgetIdleLive(u)}if(f)return this.liveValue(e,s,r,i)}let l=d.state,p;try{p=await n()}finally{this.forgetIdleLive(u)}if(d.state!==l&&d.state.status==="pushed"){let f=e.getQueryData(s);return f!==void 0?f:d.state.value}return p}clearOnIdentityChange(e){this.listenForIdentityChange(),this.identityWatched.add(e)}stopClearingOnIdentityChange(e){this.identityWatched.delete(e)}subscribeIdentityEpoch=a(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"]}))Vs(r),r.getObserversCount()===0&&!this.hasConsumers(r.queryKey)&&s.remove(r)}attach(e,s,r,i,n,o={}){let c=It(s),u=this.entries.get(c);if(!u){u={clients:new Map([[e,0]]),errorCallbacks:new Set,unsubscribe:void 0},this.entries.set(c,u);let p=u;try{u.unsubscribe=this.client.subscribe(r,i,f=>{let y=this.liveFor(c);if(f===void 0){y.state=Rt;for(let m of p.clients.keys())Vs(m.getQueryCache().find({exact:!0,queryKey:s}));return}for(let m of p.clients.keys())m.setQueryData(s,f);y.state={status:"pushed",value:f},Js(y,!0)},{onError:a(f=>{let y=this.liveFor(c);y.state.status!=="pushed"&&(y.state={status:"errored"},Js(y,!1));for(let m of p.errorCallbacks)m(f)},"onError"),shardKey:n})}catch(f){throw this.entries.delete(c),this.dropLive(c),f}}u.clients.set(e,(u.clients.get(e)??0)+1);let d=this.live.get(c);d?.state.status==="pushed"&&e.setQueryData(s,d.state.value);let{onError:h}=o;h&&u.errorCallbacks.add(h);let l=!1;return()=>{if(l)return;l=!0;let p=this.entries.get(c);if(!p)return;let f=(p.clients.get(e)??1)-1;f>0?p.clients.set(e,f):p.clients.delete(e),h&&p.errorCallbacks.delete(h),p.clients.size===0&&(p.unsubscribe?.(),this.entries.delete(c),this.dropLive(c))}}liveFor(e){let s=this.live.get(e);return s||(s={state:Rt,waiters:new Set},this.live.set(e,s)),s}forgetIdleLive(e){!this.entries.has(e)&&this.live.get(e)?.waiters.size===0&&this.live.delete(e)}dropLive(e){let s=this.live.get(e);s!==void 0&&(s.waiters.size===0?this.live.delete(e):s.state=Rt)}},Ys=new WeakMap,At=a(t=>{let e=Ys.get(t);return e||(e=new Ft(t),Ys.set(t,e)),e},"L"),Zs=(0,Q.createContext)(null),Oi=(0,Q.createContext)(!1),Ii=a(()=>new Et({defaultOptions:{mutations:{retry:0},queries:{gcTime:5*6e4,retry:0,staleTime:Number.POSITIVE_INFINITY}}}),"B"),Ri=a(t=>{let e=(0,Xs.c)(20),{children:s,client:r,queryClient:i}=t,n=(0,Q.use)(we),o;e[0]!==n||e[1]!==i?(o=a(()=>i??n??Ii(),"h"),e[0]=n,e[1]=i,e[2]=o):o=e[2];let[c]=(0,Q.useState)(o),u=i??n??c,d,h;e[3]!==r||e[4]!==u?(d=a(()=>{At(r).clearOnIdentityChange(u)},"n"),h=[r,u],e[3]=r,e[4]=u,e[5]=d,e[6]=h):(d=e[5],h=e[6]),(0,Q.useEffect)(d,h);let l=(0,Q.useRef)(r),p,f;e[7]!==r||e[8]!==u?(p=a(()=>{l.current!==r&&(At(l.current).stopClearingOnIdentityChange(u),l.current=r,At(r).clearQueries(u),u.invalidateQueries({queryKey:["lunora"]}))},"a"),f=[r,u],e[7]=r,e[8]=u,e[9]=p,e[10]=f):(p=e[9],f=e[10]),(0,Q.useEffect)(p,f);let[y]=(0,Q.useState)(r),m=r!==y,b;e[11]!==s||e[12]!==m?(b=(0,Je.jsx)(Oi,{value:m,children:s}),e[11]=s,e[12]=m,e[13]=b):b=e[13];let S;e[14]!==r||e[15]!==b?(S=(0,Je.jsx)(Zs,{value:r,children:b}),e[14]=r,e[15]=b,e[16]=S):S=e[16];let k=S;if(n===u)return k;let O;return e[17]!==k||e[18]!==u?(O=(0,Je.jsx)(ft,{client:u,children:k}),e[17]=k,e[18]=u,e[19]=O):O=e[19],O},"X");var Pt=a(()=>{let t=(0,Q.use)(Zs);if(!t)throw new g("INTERNAL","useLunora must be used inside <LunoraProvider />");return t},"q");var _=a(t=>new Promise((e,s)=>{t.addEventListener("success",()=>{e(t.result)}),t.addEventListener("error",()=>{s(t.error??new Error("IndexedDB request failed"))})}),"c"),Ye=a((t,e,s,r)=>{let i;return()=>{if(i)return i;let n=new Promise((o,c)=>{let u=t.open(e,s);u.addEventListener("upgradeneeded",()=>{r(u.result)}),u.addEventListener("success",()=>{o(u.result)}),u.addEventListener("error",()=>{c(u.error??new Error("IndexedDB open failed"))})});return i=n,n.catch(()=>{i===n&&(i=void 0)}),n}},"E"),Xe=a((t,e)=>async(s,r)=>{let i=(await t()).transaction(e,s),n=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"))})}),n},"u");var oe=a((t,e,s)=>`${t}::${e}::${s??""}`,"T"),Ai=500,Fi=a((t,e)=>{if(!Number.isInteger(t)||t<1)throw new g("INTERNAL",`${e}: maxEntries must be a positive integer, got ${String(t)}`);return t},"E");var Pi="lunora-query-cache",Mi="query-cache",er="by_ts",Li=1,xi=a((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new g("INTERNAL","createIndexedDbQueryCache: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryQueryCache()");let s=t.databaseName??Pi,r=t.storeName??Mi,i=Fi(t.maxEntries??Ai,"createIndexedDbQueryCache"),n=Ye(e,s,Li,u=>{u.objectStoreNames.contains(r)||u.createObjectStore(r,{keyPath:"key"}).createIndex(er,"ts",{unique:!1})}),o=Xe(n,r),c=a(async u=>{let d=await _(u.count())-i;d<=0||await new Promise((h,l)=>{let p=u.index(er).openCursor();p.addEventListener("success",()=>{let f=p.result;if(!f||d<=0){h();return}f.delete(),d-=1,f.continue()}),p.addEventListener("error",()=>{l(p.error??new Error("IndexedDB eviction failed"))})})},"y");return{clear:a(async()=>{await o("readwrite",u=>_(u.clear()))},"clear"),load:a(async()=>o("readonly",u=>_(u.getAll())),"load"),put:a(async(u,d)=>{await o("readwrite",async h=>{await _(h.put({...d,key:u})),await c(h)})},"put"),remove:a(async u=>{await o("readwrite",d=>_(d.delete(u)))},"remove")}},"N"),tr=a(t=>{if(t!==!1){if(t)return t;if(!(typeof indexedDB>"u"))return xi()}},"L");var Z="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Mt=a(t=>{let e="",s=0,r=t.length-2;for(;s<r;s+=3){let n=t[s]<<16|t[s+1]<<8|t[s+2];e+=Z.charAt(n>>18&63)+Z.charAt(n>>12&63)+Z.charAt(n>>6&63)+Z.charAt(n&63)}let i=t.length-s;if(i===1){let n=t[s]<<16;e+=Z.charAt(n>>18&63)+Z.charAt(n>>12&63)}else if(i===2){let n=t[s]<<16|t[s+1]<<8;e+=Z.charAt(n>>18&63)+Z.charAt(n>>12&63)+Z.charAt(n>>6&63)}return e},"A");var sr=a(()=>{let t=null;return{get:a(()=>t,"get"),set:a(e=>{t=e},"set")}},"r");var Ze=class{static{a(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 rr=0,Qi="lunora-bridge",_i=1e3,Di=3e3,et=class{static{a(this,"l")}bc;tabId;heartbeatInterval;leaderTimeout;knownLeader=void 0;leader=!1;running=!1;promotionPending=!1;lastHeartbeat=0;pendingData=new Map;heartbeatTimer=void 0;leaderCheckTimer=void 0;onBecomeLeader;onStopBeingLeader;onConnectionStatus;onSubscriptionData;onLeaderClaimAnswered;onSubscriptionError;onSubscriptionSettled;constructor(e={}){if(rr+=1,this.tabId=`tab_${String(rr)}_${crypto.randomUUID()}`,this.heartbeatInterval=e.heartbeatInterval??_i,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??Qi),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,n){this.leader&&(this.pendingData.size===0&&queueMicrotask(()=>{this.flushPendingData()}),this.pendingData.set(e,{type:"subscription-data",tabId:this.tabId,key:e,data:s,...r===void 0?{}:{cursor:r},...i===void 0?{}:{epoch:i},...n===void 0?{}:{identity:n}}))}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,n,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},...n===void 0?{}:{clientId:n},...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.flushPendingData(),this.bc?.postMessage(e)}flushPendingData(){if(this.pendingData.size===0)return;let e=[...this.pendingData.values()];if(this.pendingData.clear(),!!this.leader)for(let s of e)this.bc?.postMessage(s)}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 Ui=a(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"y"),Lt="_id",xt="_creationTime",Qt="page",ir="pageDelta",Ki=a(t=>{if(Array.isArray(t))return t;if(Ui(t)&&Array.isArray(t[Qt]))return t[Qt]},"g"),Ni=a(t=>{let e;for(let s of t){let r=s[xt];if(typeof r=="number"){if(e!==void 0){if(r<e)return!0;if(r>e)return!1}e=r}}return!1},"A"),ji=a((t,e)=>{let s=e[xt];if(typeof s!="number")return t.length;let r=Ni(t);for(let[i,n]of t.entries()){let o=n[xt];if(typeof o=="number"&&(r?o<s:o>s))return i}return t.length},"x"),qi=a(t=>{if(typeof t!="object"||t===null)return;let e=t[Lt];return typeof e=="string"?e:void 0},"b"),Wi=a(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"),Bi=a((t,e)=>{let s=[];for(let u of t){if(qi(u)===void 0)return;s.push(u)}let{key:r,op:i,row:n}=e;if(i==="delete"){let u=s.filter(d=>d[Lt]!==r);return u.length===s.length?[...s]:u}if(n===void 0)return;let o=[...s],c=s.findIndex(u=>u[Lt]===r);return c===-1?o.splice(ji(s,n),0,n):o[c]=n,o},"E"),$i=a((t,e)=>{let s=Ki(t);if(s===void 0)return;let r=Bi(s,e);return r===void 0||Array.isArray(t)?r:{...t,[Qt]:r}},"I"),_t=Symbol("lunora.unmergeableDelta"),nr=a((t,e)=>{if("data"in t&&t.data!==void 0)return T(t.data);let s=T(t.delta);return Wi(s)?e===void 0?s:$i(e,s)??_t:s},"P");var Dd=new Set(Object.keys(ps)),U=class extends g{static{a(this,"R")}constructor(e,s){super("INTERNAL",e,{data:s})}};var tt=a(t=>{let e=t?.data?.retryAfterMs;return typeof e=="number"&&Number.isFinite(e)?e:void 0},"f"),Dt=new Set(["TOKEN_EXPIRED","UNAUTHENTICATED"]),Re=a(t=>Dt.has(t?.code??""),"u");var Ae=a((t={},e=Math.random)=>{let s=t.initialDelayMs??250,r=t.maxDelayMs??3e4,i=t.jitter??!0,n=0;return{next(){let o=Math.min(r,s*2**n);if(n+=1,!i)return o;let c=o/2;return Math.floor(c+e()*(o-c))},reset(){n=0}}},"s");var Hi=1024,st=a(t=>{let e=t.maxBuffer??Hi,s=[],r=[],i=!1,n,o=!1,c=a(()=>{let h=r.shift();if(!h)return!1;if(n)return h.reject(n),!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||n))for(i=!0;c(););},fail(h){if(!(i||n)){for(n=h,s.length=0;c(););t.onFail?.()}},push(h){if(!(i||n||o)){if(s.length>=e){u.fail(new g("STREAM_BACKPRESSURE",`stream buffer overflow (max=${e.toString()}); the consumer cannot keep up with the producer`));return}s.push(h),c()}}},d=a(()=>{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(n)return Promise.reject(n);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 ye=a(t=>t.reason??Object.assign(new Error("The operation was aborted"),{name:"AbortError"}),"c"),ce=a(async(t,e,s,r=()=>new U(`LunoraClient: request timed out after ${t.toString()}ms`))=>{if(e?.aborted)throw ye(e);let i=new AbortController,n=[],o=new Promise((u,d)=>{if(t>0){let h=setTimeout(()=>{d(r()),i.abort()},t);n.push(()=>{clearTimeout(h)})}if(e){let h=a(()=>{i.abort(),d(ye(e))},"a");e.addEventListener("abort",h,{once:!0}),n.push(()=>{e.removeEventListener("abort",h)})}}),c=s(i.signal);c.catch(()=>{});try{return await Promise.race([c,o])}finally{for(let u of n)u()}},"m"),Ut=a(async(t,e)=>{if(e===void 0)return t;if(e.aborted)throw t.catch(()=>{}),ye(e);let s=a(()=>{},"o"),r=new Promise((i,n)=>{s=a(()=>{n(ye(e))},"o"),e.addEventListener("abort",s,{once:!0})});t.catch(()=>{});try{return await Promise.race([t,r])}finally{e.removeEventListener("abort",s)}},"E"),ar=a(async(t,e)=>!Number.isFinite(e)||e<=0?t.read():ce(e,void 0,async()=>t.read(),()=>new g("STREAM_IDLE",`stream received nothing for ${e.toString()}ms`)),"y");var rt=/^ /u,zi=/^\d+$/u,Gi=2147483647,Vi=10,Ji=1e3,or=a(t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),"M"),Yi=a(t=>{let e="",s,r,i=[];for(let n of t.split(`
2
+ `))if(n.startsWith("event:"))e=n.slice(6).replace(rt,"");else if(n.startsWith("data:"))i.push(n.slice(5).replace(rt,""));else if(n.startsWith("id:")){let o=n.slice(3).replace(rt,"");o.includes("\0")||(s=o)}else if(n.startsWith("retry:")){let o=n.slice(6).replace(rt,"");zi.test(o)&&Number.isSafeInteger(Number(o))&&(r=Math.min(Number(o),Gi))}return{data:i.join(`
3
+ `),event:e,id:s,retry:r}},"j"),Xi=a((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 g("HTTP_STREAM_MISSING_PARAM",`httpStream: missing path param ":${u}" for route ${t.path}`);return encodeURIComponent(or(d))}).join("/"),n=new URLSearchParams;for(let[c,u]of Object.entries(e.searchParams??{}))u!==void 0&&n.set(c,or(u));let o=n.toString();return`${s.endsWith("/")?s.slice(0,-1):s}${i}${o===""?"":`?${o}`}`},"D"),Zi=a((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",n=new g(i,r);return typeof s.why=="string"&&(n.why=s.why),e.fail(n),!0}if((t.event===""||t.event==="message")&&t.data!=="")try{e.push(T(JSON.parse(t.data)))}catch{return e.fail(new g("HTTP_STREAM_BAD_CHUNK","httpStream: malformed SSE chunk (invalid JSON)")),!0}return!1},"U"),ur=a((t,e)=>{let s="",r=!1,i=a(o=>{let c=r?`\r${o}`:o;r=c.endsWith("\r"),r&&(c=c.slice(0,-1)),s+=c.replaceAll(`\r
4
+ `,`
5
+ `)},"s"),n=a(()=>{let o=s.indexOf(`
6
+
7
+ `);if(o===-1)return"empty";let c=Yi(s.slice(0,o));return s=s.slice(o+2),e.onFrame?.(),c.id!==void 0&&e.onId?.(c.id),c.retry!==void 0&&e.onRetry?.(c.retry),Zi(c,t)?"terminal":"dispatched"},"r");return{append:i,drain:a(()=>{for(;;){let o=n();if(o==="empty")return!1;if(o==="terminal")return!0}},"drain"),next:n}},"O"),en=a(async(t,e,s,r,i=0)=>{let n=t.getReader(),o=new TextDecoder,c=ur(e,s),u=a(()=>n.cancel().then(()=>{},()=>{}),"a");try{for(;;){let{done:d,value:h}=await ar(n,i);if(d)break;if(c.append(o.decode(h,{stream:!0})),c.drain())return await u(),!0}return c.append(o.decode()),c.drain()}catch(d){throw r.abort(),u().catch(()=>{}),d}},"J"),hr=a(async(t,e)=>{e.aborted||await new Promise(s=>{let r,i=a(()=>{clearTimeout(r),s()},"s");r=setTimeout(()=>{e.removeEventListener("abort",i),s()},t),e.addEventListener("abort",i,{once:!0})})},"N"),tn=a(async(t,e,s,r)=>{let i=ur(e,s);try{i.append(await t.text())}catch(n){throw r.abort(),n}for(;;){if(r.signal.aborted)return!1;let n=i.next();if(n==="empty")return!1;if(n==="terminal")return!0;await hr(0,r.signal)}},"Y"),sn=a((t,e)=>{if(typeof t!="object"||t===null)return;let{code:s,error:r,why:i}=t;if(!(typeof s!="string"||typeof r!="string"))return new g("HTTP_STREAM_STATUS",`httpStream: request failed (status ${e.toString()}, ${s}): ${r}`,{status:e,why:typeof i=="string"?i:void 0})},"q"),rn=a(async(t,e)=>{let s,r=new Promise(n=>{s=setTimeout(()=>{n(void 0)},Ji)}),i=t.json().catch(n=>{if(e.aborted)throw n});try{return await Promise.race([i,r])}finally{clearTimeout(s),await t.body?.cancel().catch(()=>{})}},"K"),nn=a((t,e)=>{let s=Object.entries(t??{}).filter(([r])=>e===void 0||r.toLowerCase()!=="last-event-id");return{accept:"text/event-stream",...Object.fromEntries(s),...e===void 0?{}:{"last-event-id":e}}},"X"),cr=a(t=>t instanceof Error&&"code"in t?t:new g("HTTP_STREAM_TRANSPORT",t instanceof Error?t.message:String(t),{cause:t}),"P"),dr=a((t,e,s={})=>{let r=s.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!r)throw new g("INTERNAL","httpStream: no `fetch` implementation available");let i=Xi(t,e??{},s.baseUrl??""),n=new AbortController,o;s.signal&&(s.signal.aborted?n.abort():(o=a(()=>{n.abort()},"i"),s.signal.addEventListener("abort",o,{once:!0})));let c=a(()=>{o&&s.signal?.removeEventListener("abort",o)},"c"),{handle:u,iterable:d}=st({maxBuffer:s.maxBuffer,onCancel:a(()=>{n.abort()},"onCancel"),onFail:a(()=>{n.abort()},"onFail")}),h=s.reconnect??!1,l=Ae(),{lastEventId:p}=s,f,y=0,m=a(()=>{l.reset(),y=0},"x"),b={},S=a(w=>{try{w()}catch(I){throw b.value={error:I},I}},"g"),k={onFrame:m,onId:a(w=>{S(()=>s.onEventId?.(w)),p=w},"onId"),onRetry:a(w=>{S(()=>s.onRetry?.(w)),f=w},"onRetry")},O=a(async()=>{let w=nn(s.headers,p),I=new g("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"),se=a(R=>{if(n.signal.aborted){u.complete();return}return{completed:R,error:I}},"_"),L=new AbortController,A=a(()=>{L.abort()},"A");n.signal.addEventListener("abort",A,{once:!0});try{let R=await r(i,{headers:w,method:t.method,signal:L.signal});if(!R.ok){let Y=await rn(R,n.signal);u.fail(sn(Y,R.status)??new g("HTTP_STREAM_STATUS",`httpStream: request failed (status ${R.status.toString()})`,{status:R.status}));return}if(!R.body){if(typeof R.text!="function"){u.fail(new g("HTTP_STREAM_NO_BODY","httpStream: response exposes neither a body stream nor a text() read"));return}return se(await tn(R,u,k,L))}return se(await en(R.body,u,k,L,s.idleTimeoutMs))}catch(R){if(n.signal.aborted){u.complete();return}if(b.value){let{error:Y}=b.value;u.fail(Y instanceof Error?Y:new g("HTTP_STREAM_CALLBACK","httpStream: an onEventId/onRetry callback threw"));return}return{completed:!1,error:cr(R)}}finally{n.signal.removeEventListener("abort",A)}},"L");return(async()=>{try{for(;;){if(n.signal.aborted){u.complete();return}let w=await O();if(!w)return;if(w.completed||!h||y>=Vi){w.completed||u.fail(w.error);return}y+=1,await hr(f??l.next(),n.signal)}}finally{c()}})().catch(w=>{if(n.signal.aborted){u.complete();return}u.fail(cr(w))}),d},"ee");var it=a(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"a"),Kt=a(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"h"),W=a((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"$"),P=a((t,e)=>{let s=new URLSearchParams;for(let[i,n]of Object.entries(e))n!==void 0&&n!==""&&s.set(i,String(n));let r=s.toString();return r===""?t:`${t}?${r}`},"d"),an="http://same-origin.invalid",Fe=a(t=>new URL(t,an),"p"),on=/^[a-z][a-z\d+.-]*:/iu,Nt=a((t,e)=>{if(on.test(e))return t.toString();let s=`${t.pathname}${t.search}${t.hash}`;return e.startsWith("//")?`//${t.host}${s}`:s},"S");var M=class t{static{a(this,"y")}static key(e,s,r){return`${e}::${j(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()}},V=a((t,e)=>{t.ack=e},"s"),nt=a(t=>{t.ack==="inflight"&&V(t,"idle")},"b");function at(t){if(t!==void 0)return e=>{t(e)}}a(at,"o");var ee=a((t,e)=>{for(let s of t)try{s(e)}catch{}},"d");var jt=0,lr=a(()=>jt,"h"),cn=a((t,e)=>{let s=t;for(let r of e)try{s=r.transform(s)}catch{}return s},"p"),pr=a((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let s of t.callbacks)try{s(e)}catch{}}},"d"),ae=a((t,e)=>{pr(t,cn(e,t.optimisticLayers))},"y"),qt=a((t,e)=>{let s;try{s=e(t.lastValue)}catch{return}let r={id:Symbol("optimistic"),transform:e},i=!1;t.optimisticLayers.push(r),pr(t,s);let n=a(()=>{let c=t.optimisticLayers.findIndex(u=>u.id===r.id);return c===-1?!1:(t.optimisticLayers.splice(c,1),!0)},"l"),o=a(()=>{ae(t,t.serverBase)},"s");return{confirm:a(c=>{if(c===void 0){n();return}r.commitCursor=c,jt+=1,r.acknowledgedAt=jt,t.serverCursor!==void 0&&t.serverCursor>=c&&n()&&o()},"confirm"),rollback:a(()=>{i||(i=!0,n(),o())},"rollback")}},"g"),ot=a((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"),fr=a((t,e)=>{t.optimisticLayers.length!==0&&(t.optimisticLayers=t.optimisticLayers.filter(s=>s.acknowledgedAt===void 0||s.acknowledgedAt>e))},"b"),ue=a(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"v"),mr=a((t,e)=>{let s=[],r=[],i=a((n,o)=>t.get(M.key(n,o,e)),"c");return{confirms:s,rollbacks:r,store:{getAllQueries:a(n=>{let o=[];for(let c of t.all())c.fn.__lunoraRef===n.__lunoraRef&&(c.shardKey??"")===(e??"")&&o.push({args:c.args,value:c.lastValue});return o},"getAllQueries"),getQuery:a((n,o)=>i(n.__lunoraRef,o??{})?.lastValue,"getQuery"),setQuery:a((n,o,c)=>{let u=i(n.__lunoraRef,o??{});if(!u)return;let d=qt(u,()=>c);d&&(s.push(d.confirm),r.push(d.rollback))},"setQuery")}}},"_");var Wt=a(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},"l"),un=a((t,e)=>{let s=Wt(e);if(!(s===void 0||tt(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"),ge=a(t=>{let e=t?.error;if(typeof e!="object"||e===null||Array.isArray(e))return;let{why:s,...r}=e;return typeof s=="string"?{...r,why:s}:r},"p"),Bt=a(()=>new U("LunoraClient: batch slot carried no error envelope"),"E"),yr=a((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}},"i"),gr=a(t=>{let{code:e,messageText:s}=yr(t,"stream error"),r=t.error?.why,i=e===void 0?new Error(s):new g(e,s);return typeof r=="string"&&(i.why=r),i},"A"),$t=a(t=>{let{code:e,messageText:s}=yr(t,"subscription error"),r=t.error?.why;return{message:s,...e===void 0?{}:{code:e},...typeof r=="string"?{why:r}:{}}},"R"),hn=Symbol.for("lunora.serverVerdict"),Pe=a(t=>{let e=new Error(t.message??"request failed");if(e.code=t.code,e[hn]=!0,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),typeof t.why=="string"&&(e.why=t.why),e},"a"),dn=a(t=>Object.freeze(Object.fromEntries([...t].filter(([e])=>e!=="set-cookie"))),"m"),K=a((t,e)=>Object.defineProperty(t,"headers",{value:dn(e)}),"b"),Ht=a((t,e)=>{let s=Pe(t),r=un(s,e.get("retry-after"));return r!==void 0&&(s.data=r),K(s,e)},"S"),zt=a(t=>{let e=ge(t);return e===void 0?Bt():Pe(e)},"D"),vr=new WeakSet,ct=a(t=>{let e=new g("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 vr.add(e),e},"j"),Me=a(t=>t instanceof Error&&vr.has(t),"M");var br=0,ln=a(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();br+=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)}_${br.toString(36)}_${t}`},"d"),Gt=a((t,e)=>t!==void 0&&e!==t,"l"),ht=ln,ve=a((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)},"h"),ut=class{static{a(this,"p")}queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;onReplayingChange;version;items=[];replayingIds=new Set;appending=new Map;unsettled=new Map;unpersisted=new Set;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.onReplayingChange=s.onReplayingChange,this.version=s.version}get size(){return this.items.length}get replaying(){return this.replayingIds.size}enqueue(e){let s=e;s.id??=ht();let r=this.items.length;for(;s.issueSeq!==void 0&&r>0&&(this.items[r-1]?.issueSeq??-1)>s.issueSeq;)r-=1;this.items.splice(r,0,s),this.unsettled.set(s.id,s),this.persist(this.recordOf(s,s.id)),this.evictOverflow(),this.notifySize()}discard(e){this.unsettled.delete(e),this.unpersisted.delete(e),this.replayingIds.delete(e)&&this.onReplayingChange?.();let{persistence:s}=this;s&&(this.appending.get(e)??Promise.resolve()).then(async()=>s.remove(e)).catch(r=>{ve(this.onPersistenceError,"remove",r,e)})}flushUnpersisted(){for(let e of this.unpersisted){let s=this.unsettled.get(e);s&&!this.appending.has(e)&&this.persist(this.recordOf(s,e))}}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(o){throw ve(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(Gt(this.version,o.version)){this.persistence.remove(o.id).catch(c=>{ve(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:a(()=>{},"reject"),resolve:a(()=>{},"resolve"),shardKey:o.shardKey})}this.items.unshift(...s),this.evictOverflow(),this.notifySize();let i=new Set(this.items),n=new Set;for(let o of s)i.has(o)&&n.add(o.shardKey);return[...n]}restampIdentity(e,s){for(let r of this.items){if(r.identity!==e)continue;r.identity=s;let{id:i}=r;!this.persistence||i===void 0||this.rewriteStamp(i,this.recordOf(r,i)).catch(n=>{ve(this.onPersistenceError,"replace",n,i)})}}hasPending(e){return this.items.some(s=>e(s))}drain(e){if(!e){let i=[...this.items];return this.items.length=0,this.markReplaying(i),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.markReplaying(s),this.notifySize(),s}requeue(e){if(e.length!==0){for(let s of e)s.id!==void 0&&this.replayingIds.delete(s.id);this.items.unshift(...e),this.notifySize()}}drainConflict(){let e=[],s=[];for(let r of this.items){let i=!0,n;if(r.precondition!==void 0)try{i=r.precondition()}catch(o){i=!1,n=o}if(i)s.push(r);else{let o=new Error("offline mutation skipped: precondition failed before replay",n===void 0?void 0:{cause:n});o.code="OFFLINE_PRECONDITION_FAILED",r.reject(o),e.push(r)}}return e.length>0&&(this.items.length=0,this.items.push(...s),this.notifySize()),e}clear(){for(let e of new Set([...this.items,...this.unsettled.values()])){let s=new Error("CLIENT_CLOSED"),r=e.id??"",i=a(o=>{s.code="CLIENT_CLOSED",s.persisted=o,e.reject(s)},"n"),n=this.appending.get(r);this.replayingIds.has(r)?i(!1):n===void 0?i(this.persistence!==void 0&&!this.unpersisted.has(r)):n.catch(()=>!1).then(i).catch(()=>{})}this.items.length=0,this.replayingIds.clear(),this.unsettled.clear(),this.unpersisted.clear(),this.notifySize()}recordOf(e,s){return{args:e.args,...e.baselineSeq===void 0?{}:{baselineSeq:e.baselineSeq},clientId:e.clientId,functionPath:e.functionPath,id:s,identity:e.identity,shardKey:e.shardKey,...this.version===void 0?{}:{version:this.version}}}persist(e){let{persistence:s}=this;if(!s)return;let r=(async()=>{try{return await s.append(e),this.unpersisted.delete(e.id),!0}catch(i){return this.unsettled.has(e.id)&&this.unpersisted.add(e.id),ve(this.onPersistenceError,"append",i,e.id),!1}})();this.appending.set(e.id,r),r.finally(()=>{this.appending.get(e.id)===r&&this.appending.delete(e.id)}).catch(()=>{})}async rewriteStamp(e,s){let r=this.persistence;if(r)try{await this.appending.get(e),await r.replace(s)}catch(i){ve(this.onPersistenceError,"replace",i,e)}}evictOverflow(){for(;this.items.length>this.maxItems;){let e=this.items.shift();if(e){e.id&&this.discard(e.id);let s=new Error("offline queue overflow");s.code="OFFLINE_QUEUE_OVERFLOW",e.reject(s),this.onEvict?.(e,s)}}}markReplaying(e){for(let s of e)s.id!==void 0&&this.replayingIds.add(s.id)}notifySize(){this.onSizeChange?.(this.items.length)}};var pn="lunora-outbox",fn="offline-mutations",Vt="by_id",mn=a((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new g("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let s=t.databaseName??pn,r=t.storeName??fn,i=Ye(e,s,1,o=>{o.objectStoreNames.contains(r)||o.createObjectStore(r,{autoIncrement:!0}).createIndex(Vt,"id",{unique:!0})}),n=Xe(i,r);return{append:a(async o=>{await n("readwrite",c=>_(c.add(o)))},"append"),clear:a(async()=>{await n("readwrite",o=>_(o.clear()))},"clear"),load:a(async()=>n("readonly",o=>_(o.getAll())),"load"),remove:a(async o=>{await n("readwrite",async c=>{let u=await _(c.index(Vt).getKey(o));u!==void 0&&await _(c.delete(u))})},"remove"),replace:a(async o=>{await n("readwrite",async c=>{let u=await _(c.index(Vt).getKey(o.id));u!==void 0&&await _(c.put(o,u))})},"replace")}},"w"),Sr=a((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return mn()}},"b");var wr=new WeakMap,Jt=a((t,e)=>{wr.set(t,e)},"i"),Yt=a(t=>t===void 0?void 0:wr.get(t),"d"),Cr=a((t,e,s,r)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r),n=i.present&&i.answered?j(i.value):void 0,o=a(()=>{let c=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r);return!i.present||!i.answered||!c.present||!c.answered?!0:j(c.value)===n},"c");return n!==void 0&&Jt(o,{args:s,functionPath:e.__lunoraRef,shardKey:r}),o},"h");var Xt=500,Pr=a((t,e)=>{if(t.size<e)return;let s=t.keys().next().value;s!==void 0&&t.delete(s)},"Le");new TextDecoder;var vn=new TextEncoder,bn=a(t=>Mt(vn.encode(JSON.stringify(t))),"Et"),Sn="x-lunora-expect-subject",wn=a(t=>bn({subject:t}),"Ot"),kr=Symbol.for("lunora:session-change"),Cn="lunora:session-change",kn="better-auth.message",Tn="signout",Mr=a(()=>{let t=globalThis,e=t[kr];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},t[kr]=e),e},"Me"),En=a(()=>"document"in globalThis,"Ft"),On=a(async()=>{let t=[];for(let e of Mr().listeners)try{t.push(e())}catch{}await Promise.allSettled(t)},"Lt"),In=a((t,e)=>{if(t!==kn||e===null)return!1;try{let s=JSON.parse(e);return s?.event==="session"&&s.data?.trigger===Tn}catch{return!1}},"Mt"),Rn=a(t=>{let e=[],s=a(()=>{On().catch(()=>{})},"t"),r;try{r=typeof BroadcastChannel=="function"?new BroadcastChannel(Cn):void 0}catch{r=void 0}if(r!==void 0){let n=r;n.addEventListener("message",o=>{o.data?.type==="lunora:session-change"&&o.data.tab!==t&&s()}),e.push(()=>{n.close()})}let i=globalThis;if(typeof i.addEventListener=="function"){let n=a(o=>{In(o.key,o.newValue)&&s()},"n");i.addEventListener("storage",n),e.push(()=>{i.removeEventListener?.("storage",n)})}return()=>{for(let n of e)n()}},"Ht"),An=a(t=>{let e=Mr();return e.listeners.add(t),e.detach===void 0&&En()&&(e.detach=Rn(e.tab)),()=>{e.listeners.delete(t),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},"Ut"),Fn="lunora",Pn="lunora.bearer.",Mn=a(t=>`${Pn}${Mt(new TextEncoder().encode(t))}`,"Dt"),Ln="/_lunora/rpc",Zt="/_lunora/rpc-batch",es="/_lunora/ws",xn="/_lunora/admin/shard-traffic",Qn="/_lunora/admin/scheduled",_n="/_lunora/admin/scheduled/status",Dn="/_lunora/admin/scheduled/ws",Un="/_lunora/admin/scheduled/cancel",Tr="/_lunora/admin/scheduled/dead",Kn="/_lunora/admin/scheduled/dead/retry",Nn="/_lunora/admin/scheduled/dead/cancel",jn="/_lunora/admin/workflows/instances",qn="/_lunora/admin/workflows/instance",Wn="/_lunora/admin/workflows/status",us="/_lunora/admin/storage",Bn="/_lunora/admin/storage/url",$n="/_lunora/admin/storage/buckets",Hn="/_lunora/admin/functions",zn="/_lunora/admin/cron-jobs",Gn="/_lunora/admin/cron-jobs/run",Vn="/_lunora/admin/architecture",Jn="/_lunora/admin/openapi",Yn="/_lunora/admin/openrpc",Xn="/_lunora/admin/global/tables",Zn="/_lunora/admin/global/table",ea="/_lunora/admin/global/facet",ta="/_lunora/admin/vector/indexes",sa="/_lunora/admin/vector/query",ra="/_lunora/admin/logs/archive",ia="/_lunora/admin/kv/namespaces",na="/_lunora/admin/kv/keys",hs="/_lunora/admin/kv/value",aa="/_lunora/admin/auth/users",oa="/_lunora/admin/auth/sessions",ca="/_lunora/admin/auth/users/create",ua="/_lunora/admin/auth/users/role",ha="/_lunora/admin/auth/users/ban",da="/_lunora/admin/auth/users/unban",la="/_lunora/admin/auth/users/password",pa="/_lunora/admin/auth/users/remove",fa="/_lunora/admin/auth/users/impersonate",ma="/_lunora/admin/auth/sessions/revoke",ya="/_lunora/admin/auth/sessions/revoke-all",ga="/_lunora/admin/auth/capabilities",va="/_lunora/admin/auth/users/update",ba="/_lunora/admin/auth/accounts",Sa="/_lunora/admin/auth/accounts/unlink",wa="/_lunora/admin/auth/passkeys",Ca="/_lunora/admin/auth/passkeys/delete",ka="/_lunora/admin/auth/two-factor/disable",Ta="/_lunora/admin/auth/organizations",Ea="/_lunora/admin/auth/organizations/members",Oa="/_lunora/admin/auth/organizations/invitations",Ia="/_lunora/admin/auth/organizations/members/remove",Ra="/_lunora/admin/auth/organizations/invitations/cancel",Aa="/_lunora/admin/auth/config",Fa="/_lunora/admin/auth/sign-up-invitations",Pa="/_lunora/admin/auth/sign-up-invitations/create",Ma="/_lunora/admin/auth/sign-up-invitations/revoke",La="/_lunora/admin/auth/organizations/create",xa="/_lunora/admin/auth/organizations/update",Qa="/_lunora/admin/auth/organizations/remove",_a="/_lunora/admin/auth/organizations/members/add",Da="/_lunora/admin/auth/organizations/members/invite",Ua="/_lunora/admin/auth/organizations/members/role",Ka="/_lunora/admin/auth/organizations/teams",Na="/_lunora/admin/auth/organizations/teams/create",ja="/_lunora/admin/auth/organizations/teams/update",qa="/_lunora/admin/auth/organizations/teams/remove",Wa="/_lunora/admin/auth/organizations/teams/members",Ba="/_lunora/admin/auth/organizations/teams/members/add",$a="/_lunora/admin/auth/organizations/teams/members/remove",Ha="/_lunora/admin/auth/organizations/roles",za="/_lunora/admin/auth/organizations/roles/create",Ga="/_lunora/admin/auth/organizations/roles/update",Va="/_lunora/admin/auth/organizations/roles/remove",Ja="/api/auth",Ya="/get-session",Xa="lunora-ping",Za=a(async t=>(t.assertOpen(),(await t.adminFetch(Hn,"GET")).functions??[]),"oi"),eo=a(async t=>(t.assertOpen(),(await t.adminFetch(zn,"GET")).jobs??[]),"ai"),to=a(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(Gn,"POST",{name:e});return{name:s.name??e,ran:s.ran===!0}},"ci"),so=a(async t=>(t.assertOpen(),await t.adminFetch(Jn,"GET")),"di"),ro=a(async t=>(t.assertOpen(),await t.adminFetch(Vn,"GET")),"hi"),io=a(async t=>(t.assertOpen(),await t.adminFetch(Yn,"GET")),"ui"),no=a(async t=>(t.assertOpen(),await t.adminFetch(Xn,"GET")),"li"),ao=a(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($(e.filters))),T(await t.adminFetch(`${Zn}?${s.toString()}`,"GET"))},"fi"),oo=a(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($(e.filters))),T(await t.adminFetch(`${ea}?${s.toString()}`,"GET"))},"pi"),co=a(async t=>(t.assertOpen(),(await t.adminFetch(ia,"GET")).namespaces??[]),"mi"),uo=a(async(t,e)=>{t.assertOpen();let s=P(na,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await t.adminFetch(s,"GET")},"yi"),ho=a(async(t,e)=>{t.assertOpen();let s=P(hs,{key:e.key,namespace:e.namespace});return await t.adminFetch(s,"GET")},"Si"),lo=a(async(t,e)=>{t.assertOpen(),await t.adminFetch(hs,"PUT",e)},"bi"),po=a(async(t,e)=>{t.assertOpen();let s=P(hs,{key:e.key,namespace:e.namespace});await t.adminFetch(s,"DELETE")},"vi"),fo=a(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(xn,"POST",{table:e});return{failed:s.failed??0,ok:s.ok??0,shards:s.shards??[]}},"gi"),mo=a(async(t,e={})=>{t.assertOpen();let s=await t.adminFetch(ra,"POST",e);return{nextCursor:s.nextCursor,rows:s.rows??[]}},"wi"),yo=a(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}},"Ti"),ds=a(t=>"args"in t?{...t,args:T(t.args)}:t,"he"),go=a(async t=>(t.assertOpen(),((await t.adminFetch(Qn,"GET")).records??[]).map(e=>ds(e))),"ki"),vo=a(async t=>{t.assertOpen();let e=await t.adminFetch(_n,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},"Ci"),bo=a(async(t,e)=>(t.assertOpen(),{cancelled:(await t.adminFetch(Un,"POST",{id:e})).cancelled===!0}),"Ai"),So=a(async t=>(t.assertOpen(),(await yo(async e=>await t.adminFetch(e===void 0?Tr:`${Tr}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>ds(e))),"Ei"),wo=a(async(t,e)=>(t.assertOpen(),{retried:(await t.adminFetch(Kn,"POST",{id:e})).retried===!0}),"_i"),Co=a(async(t,e)=>(t.assertOpen(),{removed:(await t.adminFetch(Nn,"POST",{id:e})).removed===!0}),"Oi"),ko=a(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(`${jn}?${s.toString()}`,"GET");return{configured:r.configured,instances:r.instances??[],page:r.page??1,perPage:r.perPage??e.perPage??0,totalCount:r.totalCount}},"Ii"),To=a(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({id:e.id,name:e.name}),r=await t.adminFetch(`${qn}?${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??[]}},"Ri"),Eo=a(async(t,e)=>(t.assertOpen(),{status:(await t.adminFetch(Wn,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),"Pi"),Oo=a(async(t,e={})=>{t.assertOpen();let s=P(us,{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??[]}},"Fi"),Io=a(async(t,e,s)=>{t.assertOpen();let r=`${us}?key=${encodeURIComponent(e)}${it(s?.bucket)}`,i=await t.adminFetch(r,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}},"Li"),Ro=a(async t=>(t.assertOpen(),(await t.adminFetch($n,"GET")).buckets??[]),"Mi"),Ao=a(async(t,e)=>{t.assertOpen();let s=`${us}?key=${encodeURIComponent(e.key)}${it(e.bucket)}`,r=await t.adminFetch(s,"PUT",e.body,e.contentType);return{etag:r.etag,key:r.key??e.key}},"Hi"),Fo=a(async(t,e,s)=>{t.assertOpen();let r=s?.expiresInSeconds,i=r===void 0?"":`&expiresIn=${encodeURIComponent(r.toString())}`,n=`${Bn}?key=${encodeURIComponent(e)}${i}${it(s?.bucket)}`,o=await t.adminFetch(n,"GET");if(typeof o.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return o.url},"Ui"),Po=a(async t=>(t.assertOpen(),(await t.adminFetch(ta,"GET")).indexes??[]),"Ni"),Mo=a(async(t,e)=>(t.assertOpen(),(await t.adminFetch(sa,"POST",e)).matches??[]),"Wi"),J=a((t,e)=>{try{return $(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)}},"O"),rs=a(t=>{try{return $(t),!0}catch{return!1}},"se"),Lr=a(t=>t!==null&&typeof t=="object"&&("error"in t||"result"in t),"He"),Lo=a((t,e,s)=>{let r=Array.from({length:e}),i=a(n=>({error:K(zt(n),s),ok:!1}),"i");for(let n of t){if(typeof n.id!="number"||n.id<0||n.id>=e)continue;if(!Lr(n.body)){r[n.id]=i({});continue}let o=n.body;if("error"in o){r[n.id]=i(o);continue}try{r[n.id]={ok:!0,value:T(o.result)}}catch(c){r[n.id]={error:K(ct(c),s),ok:!1}}}return r.map(n=>n??{error:K(new Error("batch call returned no result"),s),ok:!1})},"Di"),ts=a((t,e)=>e!==null?{}:t===null?{expectSubject:null}:t?.startsWith("subj:")===!0?{expectSubject:t.slice(5)}:{},"Z"),Le=a(t=>t==="connected"||t==="polling","D"),v=a(t=>t??"","f"),B=a((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"k"),xo=a(t=>{if(!t.pendingStreams||t.pendingStreams.length===0)return;let e=t.pendingStreams;t.pendingStreams=[];for(let s of e)B(t,s)},"Bi"),Qo=new TextDecoder,_o=a(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return Qo.decode(t)},"Qi"),te=class{static{a(this,"P")}listeners=new Set;get size(){return this.listeners.size}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()}},be=a(t=>{t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)},"U"),Do=a((t,e,s)=>{be(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(Xa)}catch{}},e))},"Ki"),Er=a((t,e,s,r)=>{let{WebSocketImpl:i,connectTimeoutMs:n,heartbeatIntervalMs:o}=s;if(i===void 0)throw new g("INTERNAL","no WebSocket implementation available");let c=r.protocols===void 0?new i(e):new i(e,r.protocols);t.socket=c;let u=a(()=>{be(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket===c&&(t.socket=void 0)},"c"),d=a(h=>{u(),r.onClose(h)},"d");n>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===c){try{c.close()}catch{}d()}},n)),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)}t.socket===c&&Do(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()})},"Ae"),Uo=a(t=>{let{afterFailedAttempts:e,intervalMs:s,onReachable:r,onStateChange:i,poll:n}=t,o=s>0&&e>0,c=0,u,d=!1,h=!1,l=a(()=>{u!==void 0&&(clearInterval(u),u=void 0,d=!1,i())},"u"),p=a(y=>{if(u!==void 0){if(!y){l();return}d||(d=!0,i()),r()}},"l"),f=a(()=>{h||(h=!0,n().then(p).finally(()=>{h=!1}).catch(()=>{}))},"p");return{hasFailedOpen:a(()=>c>0,"hasFailedOpen"),isPolling:a(()=>u!==void 0&&d,"isPolling"),noteFailedOpen:a(()=>{c+=1,!(!o||u!==void 0||c<e)&&(u=setInterval(f,s),i(),f())},"noteFailedOpen"),noteOpen:a(()=>{c=0,l()},"noteOpen"),stop:l}},"qi"),Ko=1e4,Or=a(async t=>ce(Ko,void 0,t,()=>new TypeError("LunoraClient: poll timed out")),"Ee"),xr=new Set(["DELIVERY_FENCED","RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Ir=a(t=>{if(t instanceof U)return!0;let e=t?.code;return e===void 0||xr.has(e)||Dt.has(e)},"_e"),No=1e3,Qr=6e4,jo={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},xe=a((t,e,s)=>{let r=Wt(s.get("retry-after")),i=r===void 0?void 0:{retryAfterMs:r},n=`LunoraClient: response carried no error envelope (status ${t.toString()}${e?` ${e}`:""})`,o=t<400||t>=500||t===408?new U(n,i):new g(jo[t]??"BAD_REQUEST",n,{data:i});return K(o,s)},"B"),is=a((t,e=Math.random)=>{let s=Math.min(No*2**Math.max(t-1,0),Qr);return Math.round(s*(.5+e()*.5))},"ie"),qo=a(t=>{let e=t?.code;return t instanceof U||e===void 0||xr.has(e)},"Vi"),Wo=a((t,e,s)=>{let r=tt(t);return r!==void 0&&r>0?Math.min(r,Qr):qo(t)?is(e,s):void 0},"zi"),Bo=983040,$o=a(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"Yi"),Ho=a(t=>{let e=new Map;for(let s of t)typeof s.id=="number"&&Lr(s.body)&&e.set(s.id,s.body);return e},"Xi"),zo=a((t,e)=>{if(t===void 0)return{kind:"unanswered"};if("error"in t)return{error:K(zt(t),e),kind:"errored"};try{return{commitCursor:t.commitCursor,kind:"committed",value:T(t.result)}}catch(s){return{commitCursor:t.commitCursor,error:K(ct(s),e),kind:"undecodable"}}},"Zi"),ss=a((t,e)=>`${v(t)}\0${e}`,"ee"),Go=a((t,e)=>{for(let s of e)s.op==="delete"?t.delete(s.key):s.value!==void 0&&t.set(s.key,s.value)},"er"),ns=class{static{a(this,"tr")}constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,s){Pr(this.buffers,this.maxBuffers),this.buffers.set(ss(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(ss(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 n=r.parts.get(s.shapeId)??[];for(let c of i)n.push(c);r.parts.set(s.shapeId,n),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=ss(e,s),i=this.buffers.get(r);return i&&this.buffers.delete(r),i}clear(){this.buffers.clear()}},Vo=a((t,e,s)=>{let r=e.parts.get(t.id)??[],i=e.resets.has(t.id),n=e.bases.get(t.id),o=e.epoch!==void 0&&t.serverEpoch!==void 0&&e.epoch!==t.serverEpoch,c=n!==void 0&&t.serverCursor!==void 0&&t.serverCursor!==n;if(!i&&(o||c))return t.rows.clear(),t.serverCursor=void 0,t.serverEpoch=void 0,t.answered=!1,"reseed";i&&t.rows.clear(),Go(t.rows,r),t.answered=!0,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"},"sr"),Rr=a(t=>{let e=[...t.rows.values()];for(let s of t.callbacks)try{s(e)}catch{}},"Oe"),Jo=a((t,e)=>{for(let[s,r]of e.undecodable){let i=t.get(s);i&&ee(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape \u2014 ${r instanceof Error?r.message:String(r)}`})}},"ir"),as=a((t,e)=>{t.lastMutationId=Math.max(t.lastMutationId??0,e)},"re"),os=a((t,e=!1)=>{for(let s of t.checkpointCallbacks)s({checkpoint:t.serverCursor,mutationId:t.lastMutationId,...e&&{rowsFollow:!0}})},"ne"),_r=a((t,e,s)=>{t.serverBase=e,s.cursor!==void 0&&(t.serverCursor=s.cursor),s.epoch!==void 0&&(t.serverEpoch=s.epoch)},"We"),Yo=a((t,e)=>e.cursor!==void 0&&t.serverCursor!==void 0&&t.serverBase!==void 0&&e.epoch!==void 0&&e.epoch===t.serverEpoch&&e.cursor<t.serverCursor,"rr"),Xo=a(t=>t.type==="delta"&&t.more===!0,"nr"),dt=a((t,e)=>t!==void 0&&t!==e,"$"),Zo=a((t,e)=>e==="connected"&&t!=="connected"||e==="polling"&&t!=="connected"&&t!=="polling","or"),ec=a(t=>{for(let e of t.activeSubscriptions())e.valueReceived=!1,t.ensureSocket(e.shardKey),t.queueResubscribe(e);for(let e of t.activeShapes())e.answered=!1,t.ensureSocket(e.shardKey);for(let e of t.queuedShardKeys())t.ensureSocket(e);t.broadcastStatus(t.computeStatus(),t.identityFingerprint()),t.emitConnectionStatus()},"ar"),tc=a(t=>{t.closeConnections();let e=t.leader;e.status=void 0,e.wasEverConnected=!1;for(let s of t.activeSubscriptions())V(s,"idle"),s.valueReceived=!1;for(let s of t.activeShapes())s.answered=!1;t.emitConnectionStatus()},"cr"),sc=a((t,e,s)=>{if(dt(s,t.identityFingerprint()))return;let r=t.leader,i=Zo(r.status,e);r.status=e,e==="connected"&&(r.wasEverConnected=!0),t.emitConnectionStatus(),i&&(t.awaitLeaderAnswers(),t.flushOfflineQueues())},"dr"),rc=a(t=>{t.isLeader()&&t.broadcastStatus(t.computeStatus(),t.identityFingerprint())},"hr"),ic=a((t,e,s,r,i,n)=>{if(dt(n,t.identityFingerprint()))return;let o=t.subscription(e);if(!o)return;t.dropCacheSeed(e);let c=!o.valueReceived;o.valueReceived=!0,_r(o,s,r===void 0?{}:{cursor:r,epoch:i}),r!==void 0&&ot(o,r),ae(o,s),c&&t.emitConnectionStatus(),t.settleAwaitedAnswer(o,!0)},"ur"),nc=a((t,e,s,r)=>{if(dt(r,t.identityFingerprint()))return;let i=t.subscription(e);if(i){let n=!i.valueReceived;i.valueReceived=!0,ee(i.errorCallbacks,s),n&&t.emitConnectionStatus(),t.settleAwaitedAnswer(i,!1)}},"lr"),ac=a((t,e,s,r,i,n,o)=>{if(dt(o,t.identityFingerprint()))return;let c=t.subscription(e);c&&(t.ackAndAdvanceCursor(c,s,r),i!==void 0&&n===t.clientIdentifier()&&as(c,i),os(c))},"fr"),oc=a((t,e,s)=>t!==null||e&&s===null,"pr"),cc=a(t=>t.sensitive===!0,"mr"),uc=a((t,e)=>{if(!cc(t))return e;if(e.onlineOnly===!1)throw new g("BAD_REQUEST",`'${t.__lunoraRef}' takes a sensitive argument and is always online-only; onlineOnly: false is not allowed`);return{...e,onlineOnly:!0}},"yr"),hc=[ir],dc=100,Dr=1e4,lc=1e4,pc=a((t,e)=>{let s,r=new Promise((n,o)=>{s=setTimeout(()=>{o(new Error("ws ticket mint timed out"))},e)}),i=(async()=>t())();return Promise.race([i,r]).finally(()=>{clearTimeout(s)})},"gr"),Ar=a(async t=>typeof t=="function"?await t():t,"Ie"),fc=a(async(t,e,s,r)=>{let i=new AbortController,n=setTimeout(()=>{i.abort()},Dr);try{let o=await t(e,{body:s,credentials:"include",headers:r,method:"POST",signal:i.signal});return await o.text(),o.status}finally{clearTimeout(n)}},"wr"),Fr=a((t,e)=>new g("OFFLINE_NOT_QUEUED",`'${t}' is online-only and the connection is not live, so it was not queued`,{cause:e}),"Re"),mc=a((t,e)=>t instanceof TypeError&&rs(e),"Tr"),yc=a((t,e,s,r)=>e||t===!0&&s&&!r,"kr"),gc=Promise.resolve(),cs=class t{static{a(this,"Be")}static MAX_POKE_BUFFERS=256;static createClientQuery(e,s){return{defaultValue:s,key:e}}url;wsUrl;adminHost={adminFetch:a((...e)=>this.adminFetch(...e),"adminFetch"),assertOpen:a(()=>{this.assertOpen()},"assertOpen")};clientQueryStore;wsToken;wsTicket;wsCredentialGeneration=0;refusedCredentialGeneration;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;rpcTimeoutMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;authTokenOnUpgrade;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;mutationIssueCounter=0;persistence;persistenceVersion;releasePageHideFlush;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;tokenFingerprint;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 te;statusListeners=new te;roomFlushes=new Map;roomIdentityResets=new Set;tokenExpiredListeners=new te;identityChangeListeners=new te;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new te;pendingChangeListeners=new te;syncStatusListeners=new te;lastSyncStatus;whisperHandlers=new Map;liveSocketGrants=new Map;liveControlChain=Promise.resolve();whisperJoins=new Map;nextLiveSocketId=0;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;supplementaryBounces=new Set;offlineFlushes=new Map;awaitingAnswer=new WeakSet;answeredUnreadable=new WeakSet;answerHeldShards=new Set;leaderAnswerTimers=new Map;replayRetryState=new Map;replayAttempts=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new ns(t.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??W(Kt(e.url),es),this.wsToken=e.wsToken,this.wsTicket=e.wsTicket;let s=e.authBasePath??Ja;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??sr(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??3e4,this.connectTimeoutMs=e.connectTimeoutMs??1e4,this.rpcTimeoutMs=e.rpcTimeoutMs??3e4,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??5e3,this.authTokenOnUpgrade=e.authTokenOnUpgrade??!1,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??3,this.defaultConnectionContext=e.connectionContext,this.persistence=Sr(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=tr(e.queryCache),this.clientQueryStore=new Ze,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=gc),this.offlineQueue=new ut(e.offlineQueue,{onEvict:a((r,i)=>{this.emitItemSettled(r,"rejected",i),this.releaseIdleShard(r.shardKey)},"onEvict"),onReplayingChange:a(()=>{this.emitSyncStatus()},"onReplayingChange"),onSizeChange:a(r=>{this.pendingChangeListeners.emit(r),this.emitSyncStatus()},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${ht()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.installPageHideFlush(),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=An(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,s){let r=this.authToken!==e,i=this.identityFingerprint(),n=this.authSubject===void 0||this.subjectToken===this.authToken,o=this.subjectAwaitingReconfirm(),c=this.isKnownNobody(),u=this.authToken;this.authToken=e,r&&(this.tokenFingerprint=void 0),this.applySubject(e,s);let d=this.identityFingerprint(),h=!r&&e!==null&&n,l=!r&&e===null&&i===null&&n&&!c,p=d!==i,f=!1;p&&(h?(this.restampQueuedIdentity(i,d),this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):l?(this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):f=this.retirePreviousIdentity(i,c,u,e)),f||this.applyUpgradeBearer(this.reconcileUpgradeBearer(u,e,p)),p&&this.restartTabCoordinatorForIdentity(),this.syncReadCacheToCredential(o),r&&this.authTokenListeners.emit(e),(d!==i||r||o)&&this.offlineQueue.size>0&&Le(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 g("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let n=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:a(h=>{c=h},"onMutationAck")})}catch(h){if(!Me(h))throw h;d=h}if(c!==void 0&&c>(this.clientWatermarks.get(o??"")?.get(n)??0)){let h=this.clientWatermarks.get(o??"");h===void 0&&(Pr(this.clientWatermarks,8),h=new Map,this.clientWatermarks.set(o??"",h)),h.set(n,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(W(this.url,`${this.authBasePath}${Ya}`),{credentials:"include",headers:e,method:"GET"});if(!i.ok)return this.identitySettled=!0,i.status===401&&this.adoptResolvedSubject(s,null,r),null;let n=(await i.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(s,n,r),n}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.applyWsCredentialChange())}setWsTicket(e){this.wsTicket!==e&&(this.wsTicket=e,this.applyWsCredentialChange())}setConnectionContext(e,s={}){this.assertLeaderOwnedSurface("setConnectionContext");let r=v(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=v(s.shardKey),i={context:e},n=this.connectionContextHolders.get(r);n?n.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=v(r.shardKey),n=this.whisperHandlers.get(i);n||(n=new Map,this.whisperHandlers.set(i,n));let o=n.get(e),c=o===void 0;if(o||(o=new Set,n.set(e,o)),o.add(s),this.ensureSocket(r.shardKey),c){let u=this.getConnection(r.shardKey);u&&this.sendWhisperJoin(u,i,e)}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&&B(h,{topic:e,type:"whisper_unsubscribe"}),this.releaseWhisperJoin(i,e),this.releaseIdleShard(r.shardKey)}}subscribeLiveTopic(e){let{onError:s,onEvent:r,shardKey:i,stream:n,topic:o}=e;if(o.length===0)throw new g("INTERNAL","LunoraClient: subscribeLiveTopic needs a non-empty topic");this.nextLiveSocketId+=1;let c=`ws-live-${String(this.nextLiveSocketId)}`,u=v(i),d=`/live/${n}/control`,h=this.whisperSubscribe(o,()=>{},{shardKey:i}),l=a(()=>{let m=h;h=void 0,m?.()},"l"),p=this.liveSocketGrants.get(u);p===void 0&&(p=new Map,this.liveSocketGrants.set(u,p)),p.set(c,{onError:s,onEvent:r,release:l,stream:n,topic:o});let f=this.getConnection(i)?.connectionId;f!==void 0&&this.grantWhenJoined(i,c,f);let y=!1;return()=>{if(y)return;y=!0;let m=this.liveSocketGrants.get(u),b=m?.delete(c)===!0;m?.size===0&&this.liveSocketGrants.delete(u);let S=this.getConnection(i)?.connectionId;b&&S!==void 0&&this.postLiveControl(d,i,{action:"unsubscribe",connectionId:S,stream:n,subscriptionId:c,topic:o}),l()}}whisper(e,s,r={}){return this.assertLeaderOwnedSurface("whisper"),this.sendEncodedWhisper(e,J(s??null,`whisper data for topic '${e}'`),r)}connectRoom(e,s,r={}){let i=`room:${e.name}`,n=this.whisperSubscribe(i,p=>{s.onMessage(p)},r),o=!1,c=[],u=a(()=>{c.length=0},"c"),d=a(()=>{for(;c.length>0&&this.roomSendsAdmitted(r.shardKey);){if(!this.sendEncodedWhisper(i,c[0],r))return;c.shift()}},"d"),h=v(r.shardKey),l=this.roomFlushes.get(h)??new Set;return l.add(d),this.roomFlushes.set(h,l),this.roomIdentityResets.add(u),{close:a(()=>{o=!0,c.length=0,l.delete(d),l.size===0&&this.roomFlushes.delete(h),this.roomIdentityResets.delete(u),n()},"close"),send:a(p=>{if(o||this.closed||this.WebSocketImpl===void 0)return!1;let f=J(p,`room message for '${i}'`),y=typeof structuredClone=="function"?structuredClone(f):JSON.parse(JSON.stringify(f));return d(),c.length===0&&this.roomSendsAdmitted(r.shardKey)&&this.sendEncodedWhisper(i,y,r)?!0:c.length>=dc?!1:(c.push(y),!0)},"send")}}connectWebSocket(e,s,r={}){if(this.assertLeaderOwnedSurface("connectWebSocket"),this.WebSocketImpl===void 0||this.closed)return{close:a(()=>{},"close"),send:a(()=>{},"send")};let i=a(c=>{try{c?.()}catch(u){console.error("[lunora] socket route handler threw",u)}},"i"),n,o=this.openSupplementarySocket(this.supplementaryUrl(e),{offerBearer:!0,onClose:a(()=>{clearTimeout(n),i(s.onClose)},"onClose"),onMessage:a(c=>{let u;try{u=JSON.parse(typeof c.data=="string"?c.data:"")}catch{return}u.type==="message"&&(o.resetBackoff(),i(()=>{s.onMessage(T(u.data))}))},"onMessage"),onOpen:a(()=>{clearTimeout(n);let c=o.socket();n=setTimeout(()=>{o.socket()===c&&o.resetBackoff()},5e3),i(s.onOpen)},"onOpen"),shardKey:r.shardKey});return{close:a(()=>{clearTimeout(n),o.close()},"close"),send:a(c=>{let u=JSON.stringify(J(c,`socket message for '${e}'`)),d=o.socket();if(d!==void 0)try{d.send(u)}catch{}},"send")}}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let s=this.statusListeners.add(e);return e(this.computeStatus()),s}syncStatus(){let e=this.computeStatus(),s=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader(),r=0;for(let n of this.subscriptions.all())(s||this.connectionGateState(n.shardKey).polling?n.valueReceived:n.ack==="acked")||(r+=1);for(let n of this.shapeSubscriptions.values())n.answered||(r+=1);let i=this.offlineQueue.size+this.offlineQueue.replaying;return{connection:e,pendingSubscriptions:r,pendingWrites:i,synced:Le(e)&&r===0&&i===0}}onSyncStatus(e){let s=this.syncStatusListeners.add(e),r=this.syncStatus();return this.lastSyncStatus=r,e(r),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 n of r){let o=this.connections.get(n);e.push({confirmedMutationWatermark:s?.get(n)??0,hasSocket:o?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:o?.wasEverConnected??!1,wsState:o?.wsState??"idle"})}let i=this.subscriptions.all().map(n=>({acked:n.ack==="acked",functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(let n of this.shapeSubscriptions.values())i.push({acked:n.answered,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,o)=>(n.shardKey??"").localeCompare(o.shardKey??"")),subscriptions:i.toSorted((n,o)=>n.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(){let{WebSocketImpl:e}=this;if(e===void 0)return;let s=a(o=>o.protocol==="wss:"||o.protocol==="https:","t"),r=Fe(this.wsUrl),i=a(o=>{let c=Fe(String(o));return c.host===r.host&&s(c)===s(r)},"i"),n=e;return new Proxy(e,{construct:a((o,[c,u,...d])=>new n(c,u??(i(c)?this.upgradeProtocols():void 0),...d),"construct")})}isCrossTabFollower(){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()}expectsPush(e={}){let s=this.getConnection(e.shardKey);return s===void 0||s.wsState==="open"?!0:s.polling.isPolling()||!s.polling.hasFailedOpen()}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 Cr(this,e,s,r)}whenReady(e={}){return e.signal===void 0?this.readyPromise:Ut(this.readyPromise,e.signal)}get isReady(){return this.readyResolved}peekHydratedQuery(e,s,r){return this.peekHydratedQueryByKey(e,j(s),r)}peekHydratedQueryByKey(e,s,r){if(!this.readyResolved)return;let i=oe(e,s,r),n=this.hydratedQueryCache.get(i);if(n!==void 0)return this.cachedQueryMatchesIdentity(n)?n.value:void 0}peekActiveQuerySnapshot(e,s,r){let i=M.key(e,s,r),n=this.subscriptions.get(i);return{answered:n!==void 0&&(n.lastValue!==void 0||n.ack==="acked"||n.valueReceived),present:n!==void 0,value:n?.lastValue}}async query(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0,signal:r.signal})}async batch(e){return ce(this.rpcTimeoutMs,void 0,async s=>this.sendBatch(e,s))}async mutation(e,s,r={}){if(r.signal?.aborted)throw ye(r.signal);let{value:i}=await Ut(this.runMutation(e,s,r),r.signal);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,signal:r.signal,unbounded:!0})}async importRows(e,s,r={}){this.assertOpen();let i=Math.max(1,Math.trunc(r.chunkSize??500)),n=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),p=d,{committed:f}=await this.runMutation(e,n(l),{...r.importId===void 0?{}:{mutationId:`${r.importId}:${String(p)}`},shardKey:r.shardKey});d+=1,c+=l.length,f&&(u+=l.length),r.onProgress?.({done:c,total:o})}return{chunks:d,imported:u,queued:c-u}}async shardTraffic(e){return fo(this.adminHost,e)}async listScheduledJobs(){return go(this.adminHost)}async schedulerStatus(){return vo(this.adminHost)}async cancelScheduledJob(e){return bo(this.adminHost,e)}async listDeadJobs(){return So(this.adminHost)}async retryDeadJob(e){return wo(this.adminHost,e)}async removeDeadJob(e){return Co(this.adminHost,e)}async listWorkflowInstances(e){return ko(this.adminHost,e)}async getWorkflowInstance(e){return To(this.adminHost,e)}async setWorkflowInstanceStatus(e){return Eo(this.adminHost,e)}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let s=this.openSupplementarySocket(W(Kt(this.url),Dn),{onMessage:a(r=>{let i;try{i=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}i.type==="jobs"&&Array.isArray(i.records)&&(s.resetBackoff(),e(i.records.map(n=>ds(n))))},"onMessage")});return s.close}async listFunctions(){return Za(this.adminHost)}async getCronJobs(){return eo(this.adminHost)}async runCronJob(e){return to(this.adminHost,e)}async fetchOpenApi(){return so(this.adminHost)}async fetchArchitecture(){return ro(this.adminHost)}async fetchOpenRpc(){return io(this.adminHost)}async listStorageObjects(e={}){return Oo(this.adminHost,e)}async deleteStorageObject(e,s){return Io(this.adminHost,e,s)}async listStorageBuckets(){return Ro(this.adminHost)}async uploadStorageObject(e){return Ao(this.adminHost,e)}async signedStorageUrl(e,s){return Fo(this.adminHost,e,s)}async listGlobalTables(){return no(this.adminHost)}async readGlobalTablePage(e){return ao(this.adminHost,e)}async facetGlobalColumn(e){return oo(this.adminHost,e)}async listVectorIndexes(){return Po(this.adminHost)}async queryVectorIndex(e){return Mo(this.adminHost,e)}async queryLogArchive(e={}){return mo(this.adminHost,e)}async listKvNamespaces(){return co(this.adminHost)}async listKvKeys(e){return uo(this.adminHost,e)}async getKvValue(e){return ho(this.adminHost,e)}async putKvValue(e){return lo(this.adminHost,e)}async deleteKvKey(e){return po(this.adminHost,e)}async listAuthUsers(e={}){this.assertOpen();let s=P(aa,{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(ca,"POST",e)}async setAuthUserRole(e){return this.assertOpen(),await this.adminFetch(ua,"POST",e)}async banAuthUser(e){return this.assertOpen(),await this.adminFetch(ha,"POST",e)}async unbanAuthUser(e){return this.assertOpen(),await this.adminFetch(da,"POST",e)}async setAuthUserPassword(e){this.assertOpen(),await this.adminFetch(la,"POST",e)}async removeAuthUser(e){this.assertOpen(),await this.adminFetch(pa,"POST",e)}async impersonateAuthUser(e){return this.assertOpen(),await this.adminFetch(fa,"POST",e)}async revokeAuthSession(e){this.assertOpen(),await this.adminFetch(ma,"POST",e)}async revokeAuthUserSessions(e){this.assertOpen(),await this.adminFetch(ya,"POST",e)}async getAuthCapabilities(){return this.assertOpen(),await this.adminFetch(ga,"GET")}async updateAuthUser(e){return this.assertOpen(),await this.adminFetch(va,"POST",e)}async listAuthAccounts(e){return this.assertOpen(),await this.adminFetch(P(ba,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.assertOpen(),await this.adminFetch(Sa,"POST",e)}async listAuthPasskeys(e){return this.assertOpen(),await this.adminFetch(P(wa,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.assertOpen(),await this.adminFetch(Ca,"POST",e)}async disableAuthTwoFactor(e){this.assertOpen(),await this.adminFetch(ka,"POST",e)}async listAuthOrganizations(e={}){return this.assertOpen(),await this.adminFetch(P(Ta,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.assertOpen();let s=P(Ea,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthOrgInvitations(e){this.assertOpen();let s=P(Oa,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthSignUpInvitations(e={}){this.assertOpen();let s=P(Fa,{limit:e.limit,offset:e.offset});return await this.adminFetch(s,"GET")}async createAuthSignUpInvitation(e){return this.assertOpen(),await this.adminFetch(Pa,"POST",e)}async revokeAuthSignUpInvitation(e){this.assertOpen(),await this.adminFetch(Ma,"POST",e)}async removeAuthOrgMember(e){this.assertOpen(),await this.adminFetch(Ia,"POST",e)}async cancelAuthOrgInvitation(e){this.assertOpen(),await this.adminFetch(Ra,"POST",e)}async getAuthConfig(){return this.assertOpen(),await this.adminFetch(Aa,"GET")}async createAuthOrganization(e){return this.assertOpen(),await this.adminFetch(La,"POST",e)}async updateAuthOrganization(e){return this.assertOpen(),await this.adminFetch(xa,"POST",e)}async deleteAuthOrganization(e){this.assertOpen(),await this.adminFetch(Qa,"POST",e)}async addAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(_a,"POST",e)}async inviteAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(Da,"POST",e)}async setAuthOrgMemberRole(e){return this.assertOpen(),await this.adminFetch(Ua,"POST",e)}async listAuthOrgTeams(e){this.assertOpen();let s=P(Ka,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(Na,"POST",e)}async updateAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(ja,"POST",e)}async removeAuthOrgTeam(e){this.assertOpen(),await this.adminFetch(qa,"POST",e)}async listAuthOrgTeamMembers(e){this.assertOpen();let s=P(Wa,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(s,"GET")}async addAuthOrgTeamMember(e){return this.assertOpen(),await this.adminFetch(Ba,"POST",e)}async removeAuthOrgTeamMember(e){this.assertOpen(),await this.adminFetch($a,"POST",e)}async listAuthOrgRoles(e){this.assertOpen();let s=P(Ha,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(za,"POST",e)}async updateAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Ga,"POST",e)}async deleteAuthOrgRole(e){this.assertOpen(),await this.adminFetch(Va,"POST",e)}async listAuthSessions(e={}){this.assertOpen();let s=P(oa,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(s,"GET")}subscribe(e,s,r,i={}){if(this.assertOpen(),i.signal?.aborted)return()=>{};let n=s??{},o=M.key(e.__lunoraRef,n,i.shardKey),c=this.subscriptions.get(o),u=at(r),d=at(i.onError),h=at(i.onCheckpoint);if(!c){this.nextSubId+=1;let y=`sub_${this.nextSubId.toString()}`,m=j(n),b=this.takeHydratedCache(e.__lunoraRef,m,i.shardKey);c={ack:"idle",args:n,argsKey:m,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:y,lastValue:b?.value,optimisticLayers:[],serverBase:b?.value,serverCursor:b?.serverCursor,shardKey:i.shardKey,valueReceived:!1,wireArgs:J(n,`args for '${e.__lunoraRef}'`),...b?.serverEpoch===void 0?{}:{serverEpoch:b.serverEpoch}},this.subscriptions.add(c),this.emitSyncStatus(),this.isCrossTabFollower()&&Le(this.computeStatus())&&this.awaitLeaderAnswer(c),b!==void 0&&this.cacheSeededQueries.set(o,b)}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,p=!1,f=a(()=>{if(!p&&(p=!0,i.signal?.removeEventListener("abort",f),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);let y=this.getConnection(l.shardKey);y&&this.settleSubscribeWatchdog(y,l.id),this.releaseIdleShard(l.shardKey),this.emitSyncStatus(),this.settleAwaitedAnswer(l,!0)}},"p");return i.signal?.addEventListener("abort",f,{once:!0}),i.signal?.aborted&&f(),f}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()}`,n={answered:!1,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:J(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,n),this.emitSyncStatus(),this.ensureSocket(r.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(n.shardKey,i,"shape_unsubscribe"),this.releaseIdleShard(n.shardKey),this.emitSyncStatus()}}stream(e,s,r={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new g("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;let i=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=r,o=s??{},{handle:c,iterable:u}=st({maxBuffer:r.maxBuffer,onCancel:a(()=>{this.cancelStream(i,n)},"onCancel")});this.ensureSocket(n);let d=this.getConnection(n),h={id:i,query:{args:J(o,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"},l={durable:r.durable===!0,generation:void 0,handle:c,lastSeq:0,message:h,shardKey:n};this.streams.set(i,l);let p=d?.wsState==="open"&&B(d,h);if(!p&&d===void 0)return this.forgetStream(i),c.fail(new g("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),u;if(!p){for(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=64;){let f=d.pendingStreams.shift()?.id,y=f?this.streams.get(f):void 0;y&&(y.handle.fail(new g("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(f))}d.pendingStreams.push(h)}return u}httpStream(e,s,r={}){if(this.closed)throw new g("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new g("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...r.headers};return dr(e,s,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:r.maxBuffer,signal:r.signal})}close(){this.closed=!0;for(let e of this.whisperJoins.keys())this.dropWhisperJoinWaiters(e);this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.releasePageHideFlush?.(),this.releasePageHideFlush=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(let e of this.streams.values())e.handle.fail(new g("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(),this.supplementaryBounces.clear();for(let e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear();for(let e of this.leaderAnswerTimers.values())clearTimeout(e);this.leaderAnswerTimers.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.syncStatusListeners.clear(),this.whisperHandlers.clear(),this.liveSocketGrants.clear(),this.roomFlushes.clear(),this.roomIdentityResets.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}retirePreviousIdentity(e,s,r,i){return this.rejectQueuedForIdentityChange(e),this.warnRefreshWithoutSubject(r,i),oc(e,s,i)?(this.evictPreviousIdentitySession(),!0):!1}reconcileUpgradeBearer(e,s,r){return!this.authTokenOnUpgrade||s===null||e===s?"none":r?e===null?"cold":"none":e===null?"none":"warm"}upgradeProtocols(){return this.authTokenOnUpgrade&&this.authToken?[Fn,Mn(this.authToken)]:void 0}applyUpgradeBearer(e){e==="cold"?(this.resetRoomSends(),this.reconnectCold()):e==="warm"&&this.bounceShardSockets()}assertOpen(){if(this.closed)throw new g("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 g("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=a(r=>v(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=v(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())},5e3))}forgetStream(e){let s=this.streams.get(e);this.streams.delete(e),s&&this.releaseIdleShard(s.shardKey)}teardownConnection(e){e.polling.stop();let s=v(e.shardKey);for(let[i,n]of this.streams)v(n.shardKey)===s&&(n.handle.fail(new g("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(i));e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e),this.clearConnectionTimers(e),clearTimeout(e.idleTimer),e.idleTimer=void 0,be(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={activeShapes:a(()=>[...this.shapeSubscriptions.values()],"activeShapes"),activeSubscriptions:a(()=>this.subscriptions.all(),"activeSubscriptions"),awaitLeaderAnswers:a(()=>{this.awaitLeaderAnswers()},"awaitLeaderAnswers"),broadcastStatus:a((r,i)=>this.tabCoordinator?.broadcastConnectionStatus(r,i),"broadcastStatus"),closeConnections:a(()=>{for(let[r,i]of this.connections)this.teardownConnection(i),this.connections.delete(r)},"closeConnections"),computeStatus:a(()=>this.computeStatus(),"computeStatus"),emitConnectionStatus:a(()=>{this.emitConnectionStatus()},"emitConnectionStatus"),ensureSocket:a(r=>{this.ensureSocket(r)},"ensureSocket"),flushOfflineQueues:a(()=>{this.flushAllOfflineQueues()},"flushOfflineQueues"),identityFingerprint:a(()=>this.identityFingerprint(),"identityFingerprint"),isLeader:a(()=>this.tabCoordinator?.isLeader()===!0,"isLeader"),leader:this.leader,queueResubscribe:a(r=>{this.queueResubscribe(r)},"queueResubscribe"),queuedShardKeys:a(()=>this.queuedOfflineShardKeys,"queuedShardKeys"),clientIdentifier:a(()=>this.clientId,"clientIdentifier"),dropCacheSeed:a(r=>{this.dropCacheSeed(r)},"dropCacheSeed"),ackAndAdvanceCursor:a((r,i,n)=>{this.ackAndAdvanceCursor(r,i,n)},"ackAndAdvanceCursor"),settleAwaitedAnswer:a((r,i)=>{this.settleAwaitedAnswer(r,i)},"settleAwaitedAnswer"),subscription:a(r=>this.subscriptions.get(r),"subscription")};return new et({channelName:e,onBecomeLeader:a(()=>{ec(s)},"onBecomeLeader"),onStopBeingLeader:a(()=>{tc(s)},"onStopBeingLeader"),onConnectionStatus:a((r,i)=>{sc(s,r,i)},"onConnectionStatus"),onSubscriptionData:a((r,i,n,o,c)=>{ic(s,r,i,n,o,c)},"onSubscriptionData"),onLeaderClaimAnswered:a(()=>{rc(s)},"onLeaderClaimAnswered"),onSubscriptionError:a((r,i,n)=>{nc(s,r,i,n)},"onSubscriptionError"),onSubscriptionSettled:a((r,i,n,o,c,u)=>{ac(s,r,i,n,o,c,u)},"onSubscriptionSettled")})}async sendBatch(e,s){if(this.assertOpen(),!this.fetchImpl)throw new g("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(W(this.url,Zt),{body:JSON.stringify({calls:e.map((c,u)=>({args:J(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 n;try{n=await r.json()}catch{throw K(new g("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`),r.headers)}let o=ge(n);if(!r.ok||o!==void 0&&!n.results)throw o!==void 0?K(Pe(o),r.headers):K(new g("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`),r.headers);for(let c of n.results??[]){let u=c.body?.commitCursor;typeof c.id=="number"&&typeof u=="number"&&this.recordShardCursor(e[c.id]?.shardKey,u)}return Lo(n.results??[],e.length,r.headers)}async runMutation(e,s,r){this.assertOpen();let i=uc(e,r),n=s,o=i.mutationId??ht();this.mutationIssueCounter+=1;let c=this.mutationIssueCounter,u=this.takeReplayCredential(i.replayCredential),d=this.composedBaselineFor(i.replayBaseline,i.shardKey);this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i);let{confirms:h,rollbacks:l}=this.applyOptimisticUpdates(e.__lunoraRef,n,i.shardKey,i.optimistic);this.applyOptionalOptimisticUpdate(i.optimisticUpdate,s,i.shardKey,l,h);let p=i.onlineOnly?void 0:this.offlineFlushes.get(v(i.shardKey));p!==void 0&&await p;let{httpFirst:f,midReconnect:y,shouldQueueOffline:m,socketDown:b}=this.writeQueueGate(i.shardKey),S=!i.onlineOnly&&m&&i.replayBaseline===void 0&&this.hasPendingWriteAhead(i.shardKey),k=a(async(w=!1)=>this.enqueueOfflineMutation(e,n,i.shardKey,d,o,l,h,w?void 0:i.precondition,i.mutationId,u?.stamp,w,c),"v");if(this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i,l),b||y||S)return k();let O;try{let w=await this.rpc(e.__lunoraRef,n,i.shardKey,{baselineSeq:d,captureBookmark:!0,...u?.flags,mutationId:o,onCommitCursor:a(I=>{O=I},"onCommitCursor")});for(let I of h)I(O);return{committed:!0,value:w}}catch(w){let I=mc(w,n),se=f&&m&&I,L=this.ownSocketOpen(i.shardKey);if(m&&!i.onlineOnly&&this.fetchImpl!==void 0&&!this.outbox&&i.replayBaseline===void 0&&(w instanceof TypeError||w instanceof U)&&rs(n)){let A=k(!0);return this.noteHeldRetryDelay(i.shardKey),this.scheduleRateLimitedRetry(i.shardKey),A}throw this.settleFailedDirectWrite(w,O,h,l,u?.flags.authToken),yc(i.onlineOnly,se,I,L)?Fr(e.__lunoraRef,w):w}}refuseOnlineOnlyWhenDown(e,s,r=[]){if(!s.onlineOnly)return;let i=this.writeQueueGate(s.shardKey);if(i.socketDown||i.midReconnect)throw ue(r),Fr(e)}ownSocketOpen(e){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()?!1:this.writeQueueGate(e).socketOpen}writeQueueGate(e){let{hasSocket:s,idleClosed:r,polling:i,wasEverConnected:n,wsState:o}=this.connectionGateState(e),{queueBeforeFirstConnect:c}=this.offlineQueue,u=n||c,d=this.WebSocketImpl!==void 0&&u,h=i||r;return{httpFirst:h,midReconnect:o==="connecting"&&u&&!h,shouldQueueOffline:d,socketDown:o!=="open"&&!s&&d&&!h,socketOpen:o==="open"}}settleFailedDirectWrite(e,s,r,i,n){if(this.noteIdentityMismatch(e),n!==void 0&&this.noteReplayAuthRefusal(e,n),Me(e)){for(let o of r)o(s);return}ue(i)}async enqueueOfflineMutation(e,s,r,i,n,o,c,u,d,h,l,p){let f=h===void 0?this.identityFingerprint():h;if(this.outbox){this.outboxMutationCounter+=1;let y=this.outboxMutationCounter;try{await this.outbox.enqueue({args:s,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:d??`${this.clientId}:${String(y)}`,identity:f,mutationId:y,...o.length>0&&{onRejected:a(()=>{ue(o)},"onRejected")},shardKey:r})}catch(m){throw ue(o),m instanceof Error?m:new Error(String(m))}for(let m of c)m(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((y,m)=>{let b={ambiguousSend:l,args:s,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:n,issueSeq:p,clientId:this.clientId,identity:f,precondition:this.holdWhileUnanswered(u),onCommit:a(S=>{for(let k of c)k(S)},"onCommit"),reject:a(S=>{this.queuedIdentities.delete(n),Me(S)||ue(o),m(S instanceof Error?S:new Error(String(S))),this.releaseIdleShard(r)},"reject"),resolve:y,shardKey:r};this.offlineQueue.enqueue(b),this.queuedOfflineShardKeys.add(r),this.ensureSocket(r),b.id!==void 0&&this.queuedIdentities.set(b.id,f)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;let s=v(e);return this.offlineQueue.hasPending(r=>v(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=a(()=>{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(oe(r.fn.__lunoraRef,r.argsKey,r.shardKey),r);for(let{key:r,...i}of e){if(Gt(this.persistenceVersion,i.version)){this.queryCache.remove(r).catch(()=>{});continue}let n=s.get(r);if(n&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(n,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(oe(e.fn.__lunoraRef,e.argsKey,e.shardKey),s),ae(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,ae(r,void 0)),this.hydratedQueryCache.set(e,s)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,s,r){let i=oe(e,s,r),n=this.hydratedQueryCache.get(i);if(!(n===void 0||!this.cachedQueryMatchesIdentity(n)))return this.hydratedQueryCache.delete(i),n}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(let e of this.subscriptions.all()){let s=oe(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=oe(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,n=i===void 0?this.identityFingerprint():i;n===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(r,{identity:n,serverCursor:e.serverCursor,ts:Date.now(),value:s,...n===this.identityFingerprint()&&!this.subjectAwaitingReconfirm()?this.credentialStamp():{},...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},250))}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)))}installPageHideFlush(){let e=globalThis;if(!this.persistence&&!this.queryCache||!("document"in globalThis)||typeof e.addEventListener!="function")return;let s=a(()=>{this.offlineQueue.flushUnpersisted(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.flushQueryCacheWrites().catch(()=>{}))},"t"),r=a(()=>{e.document?.visibilityState==="hidden"&&s()},"s");e.addEventListener("pagehide",s),e.document?.addEventListener("visibilitychange",r),this.releasePageHideFlush=()=>{e.removeEventListener?.("pagehide",s),e.document?.removeEventListener("visibilitychange",r)}}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=v(e),r;for(let i of this.subscriptions.all())v(i.shardKey)!==s||i.serverCursor===void 0||(r=r===void 0?i.serverCursor:Math.max(r,i.serverCursor));return r}composedBaselineFor(e,s){return e===void 0?this.baselineCursorFor(s):e??void 0}async pollSubscriptions(e){let s=v(e),r=[];for(let c of this.subscriptions.all())v(c.shardKey)===s&&(rs(c.args)?r.push(c):(this.markQueryRejected(c,!0),ee(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=lr(),n=this.identityFingerprint(),o;try{o=await Or(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()!==n)return!0;for(let[c,u]of r.entries()){let d=o[c];if(d!==void 0){if(!d.ok){this.markQueryRejected(u,!0),ee(u.errorCallbacks,{code:d.error.code,message:d.error.message});continue}this.handleDataMessage({data:$(d.value),id:u.id,type:"data"},i)}}return!0}async probeOrigin(){let{fetchImpl:e}=this;if(!e)return!1;try{return await Or(async s=>e(W(this.url,Zt),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:s})),!0}catch{return!1}}emitSyncStatus(){if(this.syncStatusListeners.size===0)return;let e=this.syncStatus(),s=this.lastSyncStatus;s?.connection===e.connection&&s.pendingSubscriptions===e.pendingSubscriptions&&s.pendingWrites===e.pendingWrites&&s.synced===e.synced||(this.lastSyncStatus=e,this.syncStatusListeners.emit(e))}emitConnectionStatus(){let e=this.computeStatus();this.emitSyncStatus(),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 n=[],o=[];if(!i)return{confirms:n,rollbacks:o};let c=M.key(e,s,r),u=this.subscriptions.get(c);if(u){let d=qt(u,i);d&&(n.push(d.confirm),o.push(d.rollback))}return{confirms:n,rollbacks:o}}applyOptionalOptimisticUpdate(e,s,r,i,n){e&&this.applyOptimisticUpdate(e,s,r,i,n)}applyOptimisticUpdate(e,s,r,i,n){let{confirms:o,rollbacks:c,store:u}=mr(this.subscriptions,r);try{e(u,s)}catch{ue(c);return}i.push(...c),n.push(...o)}getConnection(e){return this.connections.get(v(e))}sendOrQueueUnsubscribe(e,s,r){let i=this.getConnection(e);i&&!B(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(v(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=v(e),r=this.connections.get(s);return r||(r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:Uo({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:a(()=>{this.flushOfflineQueue(e).catch(()=>{})},"onReachable"),onStateChange:a(()=>{this.emitConnectionStatus()},"onStateChange"),poll:a(async()=>this.pollSubscriptions(e),"poll")}),reconnect:Ae(this.reconnectOptions),reconnectTimer:void 0,resubscribeQueue:[],resubscribeSlots:new Set,shardKey:e,socket:void 0,stableTimer:void 0,unackedWatchdogs:new Map,wasEverConnected:this.idleClosedShards.delete(s),wsState:"idle"},this.connections.set(s,r)),r}openSupplementarySocket(e,s){if(this.WebSocketImpl===void 0||this.closed)return{close:a(()=>{},"close"),resetBackoff:a(()=>{},"resetBackoff"),socket:a(()=>{},"socket")};let r=Ae(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},n,o=!1,c=a(()=>{o||this.closed||(n=setTimeout(p,r.next()))},"o"),u=a(m=>{o||this.WebSocketImpl===void 0||Er(i,this.wsUrlFor(s.shardKey,m,e),this.managedSocketOptions,{onClose:a(()=>{c(),s.onClose?.()},"onClose"),onMessage:s.onMessage,...s.onOpen===void 0?{}:{onOpen:s.onOpen},...s.offerBearer===!0?{protocols:this.upgradeProtocols()}:{}})},"c"),d=0,h,l=a(async m=>{let b=this.wsCredentialGeneration;d+=1;let S=d,k;h=b;try{k=await pc(m,lc)}catch{S===d&&(h=void 0,c());return}if(S===d){if(h=void 0,b!==this.wsCredentialGeneration){p();return}u(k)}},"u"),p=a(()=>{if(o||this.WebSocketImpl===void 0)return;let{wsTicket:m}=this;if(typeof m=="function"){l(m).catch(()=>{});return}u(m)},"l");p();let f=a(()=>{o=!0,n!==void 0&&(clearTimeout(n),n=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),be(i);let{socket:m}=i;i.socket=void 0;try{m?.close()}catch{}},"p");this.adminSocketTeardowns.add(f);let y=a(()=>{let{socket:m}=i;if(m===void 0){h!==void 0&&h!==this.wsCredentialGeneration&&(d+=1,h=void 0,p());return}i.socket=void 0,i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),be(i);try{m.close()}catch{}s.onClose?.(),c()},"y");return this.supplementaryBounces.add(y),{close:a(()=>{f(),this.adminSocketTeardowns.delete(f),this.supplementaryBounces.delete(y)},"close"),resetBackoff:a(()=>{r.reset()},"resetBackoff"),socket:a(()=>i.socket,"socket")}}supplementaryUrl(e){let s=Fe(this.wsUrl),r=s.pathname.endsWith(es)?s.pathname.slice(0,-es.length):s.pathname;return s.pathname=W(r,e),Nt(s,this.wsUrl)}wsUrlFor(e,s,r=this.wsUrl){let i=Fe(r);if(e===void 0&&s===void 0&&!i.searchParams.has("token"))return r;let n=new Set([...e===void 0?[]:["shard"],"token"]),o=[...i.searchParams].filter(([c])=>!n.has(c)).map(([c,u])=>`${encodeURIComponent(c)}=${encodeURIComponent(u)}`);return e!==void 0&&o.push(`shard=${encodeURIComponent(e)}`),s!==void 0&&o.push(`token=${encodeURIComponent(s)}`),i.search=o.join("&"),Nt(i,r)}rpcRequestHeaders(e,s){let r={"content-type":"application/json"};e.expectSubject!==void 0&&(r[Sn]=wn(e.expectSubject));let i=this.shardCursors.get(this.cursorKeyFor(s));i!==void 0&&(r["x-lunora-min-seq"]=i.toString());let n=e.authToken===void 0?this.authToken:e.authToken;if(n&&(r.authorization=`Bearer ${n}`),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={}){let{fetchImpl:n}=this;if(!n)throw new U("LunoraClient: no `fetch` implementation available");let o=this.rpcRequestHeaders(i,r),c=i.authToken===void 0?this.authToken:i.authToken,u=JSON.stringify({args:J(s,`args for '${e}'`),functionPath:e,shardKey:r}),{body:d,response:h}=await ce(i.unbounded?0:this.rpcTimeoutMs,i.signal,async f=>{let y=await n(W(this.url,Ln),{body:u,headers:o,method:"POST",signal:f});try{return{body:await y.json(),response:y}}catch{return{body:void 0,response:y}}});if(i.captureBookmark){let f=h.headers.get("x-d1-bookmark");f&&this.bookmark.set(f)}if(d===void 0)throw xe(h.status,h.statusText,h.headers);let l=d;if(typeof l!="object"||l===null||Array.isArray(l))throw xe(h.status,h.statusText,h.headers);let p=ge(d);if(p!==void 0)throw Ht(p,h.headers);if(!h.ok)throw xe(h.status,h.statusText,h.headers);i.onMutationAck?.(d.lastMutationId),i.onCommitCursor?.(d.commitCursor),this.noteCredentialAccepted(c),this.learnDefaultShardKey(h,r),this.recordShardCursor(r,d.commitCursor);try{return T(d.result)}catch(f){throw K(ct(f),h.headers)}}async adminFetch(e,s,r,i){if(!this.fetchImpl)throw new g("INTERNAL","LunoraClient: no `fetch` implementation available");let n={};this.authToken&&(n.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&&(n["content-type"]=i)):(c=JSON.stringify(r),n["content-type"]="application/json");let u=await this.fetchImpl(W(this.url,e),{body:c,headers:n,method:s}),d;try{d=await u.json()}catch{let l=u.statusText?` ${u.statusText}`:"";throw new g("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${l})`)}let h=ge(d);if(h!==void 0)throw Pe({...h,message:h.message??"admin request failed"});if(!u.ok){let l=u.statusText?` ${u.statusText}`:"";throw new g("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(v(e.shardKey));B(e,{caps:hc,clientId:this.clientId,id:"connect",type:"connect",...s===void 0?{}:{context:s},...e.sessionToken===void 0?{}:{token:e.sessionToken}})}resendShapeSubscriptions(e){for(let s of this.shapeSubscriptions.values())v(s.shardKey)===v(e)&&this.sendShapeSubscribeIfOpen(s)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;let s=this.getOrCreateConnection(e);s.wsState==="open"||s.wsState==="connecting"||(s.wsState="connecting",this.emitConnectionStatus(),this.startShardSocket(s,e).catch(()=>{this.handleDisconnect(s)}))}applyWsCredentialChange(){this.wsCredentialGeneration+=1,this.resetRoomSends(),this.bounceShardSockets()}async startShardSocket(e,s){let{wsToken:r,wsTicket:i}=this;if(typeof r=="function"||typeof i=="function"){await this.openSocketWithProvidedCredentials(e,s);return}this.openSocket(e,s,{session:r,ticket:i})}async openSocketWithProvidedCredentials(e,s){let r=this.wsCredentialGeneration,i=Symbol("ws-token-attempt"),n;e.providerAttempt=i;try{n=await ce(this.connectTimeoutMs,void 0,async()=>({session:await Ar(this.wsToken),ticket:await Ar(this.wsTicket)}),()=>new Error("LunoraClient: ws credential provider timed out"))}catch{e.providerAttempt===i&&(e.providerAttempt=void 0,this.handleDisconnect(e));return}if(e.providerAttempt===i&&(e.providerAttempt=void 0,!(this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0))){if(r!==this.wsCredentialGeneration){await this.startShardSocket(e,s);return}this.openSocket(e,s,n)}}openSocket(e,s,r){if(this.WebSocketImpl===void 0)return;e.providerAttempt=void 0,e.identity=this.identityFingerprint(),r.ticket===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.sessionToken=r.session,e.retired=!1;let i=this.wsCredentialGeneration;Er(e,this.wsUrlFor(s,r.ticket),this.managedSocketOptions,{onClose:a(n=>{n?.code===4003&&e.polling.noteFailedOpen(),n?.code===4001?this.notifyTokenExpired():n?.code===4003&&n.reason!=="connect deadline"&&i===this.wsCredentialGeneration&&this.refusedCredentialGeneration!==i&&(this.refusedCredentialGeneration=i,this.notifyTokenExpired()),this.handleDisconnect(e)},"onClose"),onMessage:a(n=>{e.retired!==!0&&this.handleServerMessage(n.data,s)},"onMessage"),onOpen:a(()=>{e.wsState="open",e.wasEverConnected=!0,e.identityConfirmed=!1,e.connectionId=void 0,e.roomsRejoined=!1,clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},5e3),this.sendConnectEnvelope(e),this.markShardPendingAck(s,!0),this.emitConnectionStatus(),this.clearResubscribeQueue(e);for(let c of this.subscriptions.all())v(c.shardKey)===v(s)&&this.queueResubscribe(c);if(this.resendShapeSubscriptions(s),e.pendingUnsubscribes.length>0){let c=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:u,type:d}of c)B(e,{id:u,type:d});this.releaseIdleShard(s)}xo(e);let n=v(s),o=this.whisperHandlers.get(n);if(this.dropWhisperJoinWaiters(n),this.whisperJoins.set(n,new Map),o)for(let c of o.keys())this.sendWhisperJoin(e,n,c);e.roomsRejoined=!0,this.releaseRoomSends(s),this.flushOfflineQueue(s).catch(()=>{})},"onOpen"),protocols:this.upgradeProtocols()})}cancelStream(e,s){let r=this.getConnection(s);r&&(r.pendingStreams=r.pendingStreams?.filter(i=>i.id!==e),B(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(),be(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",e.connectionId=void 0,e.whisperAck=void 0,this.dropWhisperJoinWaiters(v(e.shardKey)),this.markShardPendingAck(e.shardKey),this.emitConnectionStatus(),this.clearResubscribeQueue(e);let s=new Set((e.pendingStreams??[]).map(i=>i.id));for(let[i,n]of this.streams)if(!(v(n.shardKey)!==v(e.shardKey)||s.has(i))){if(n.durable){let o={...n.message,...n.generation===void 0?{}:{generation:n.generation},sinceChunk:n.lastSeq};n.message=o,e.pendingStreams=[...(e.pendingStreams??[]).filter(c=>c.id!==i),o];continue}n.handle.fail(new g("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,s=!1){let r=v(e);for(let i of this.subscriptions.all())v(i.shardKey)===r&&(V(i,"idle"),i.pendingDeltaRun=void 0,s&&(i.valueReceived=!1,this.awaitingAnswer.add(i),this.answeredUnreadable.delete(i)));for(let i of this.shapeSubscriptions.values())v(i.shardKey)===r&&(i.answered=!1)}queueResubscribe(e){let s=this.getConnection(e.shardKey);s&&(s.resubscribeQueue.push(e),this.drainResubscribeQueue(s))}drainResubscribeQueue(e){for(;e.resubscribeSlots.size<3;){let s=e.resubscribeQueue.shift();if(!s)return;this.subscriptions.getById(s.id)&&this.sendSubscribeIfOpen(s)&&e.resubscribeSlots.add(s.id)}}settleSubscribeWatchdog(e,s){clearTimeout(e.unackedWatchdogs.get(s)),e.unackedWatchdogs.delete(s),e.resubscribeSlots.delete(s)&&this.drainResubscribeQueue(e)}clearResubscribeQueue(e){for(let s of e.unackedWatchdogs.values())clearTimeout(s);e.unackedWatchdogs.clear(),e.resubscribeSlots.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e,s=!1){let r=this.getConnection(e.shardKey);if(r?.wsState!=="open"||e.ack==="acked"||!s&&e.ack==="inflight")return!1;let i=e.serverCursor!==void 0&&e.serverBase!==void 0,n=B(r,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...i?{sinceSeq:e.serverCursor}:{},...i&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"});return n&&V(e,"inflight"),n&&!s&&this.armUnackedWatchdog(r,e),n}armUnackedWatchdog(e,s,r=!1){clearTimeout(e.unackedWatchdogs.get(s.id)),e.unackedWatchdogs.set(s.id,setTimeout(()=>{if(r){e.unackedWatchdogs.delete(s.id),nt(s),this.settleAwaitedAnswer(s,!1);return}let i=s.ack!=="acked"&&this.subscriptions.getById(s.id)===s&&this.sendSubscribeIfOpen(s,!0);this.settleSubscribeWatchdog(e,s.id),i?this.armUnackedWatchdog(e,s,!0):nt(s)},1e4))}sendShapeSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);s?.wsState==="open"&&B(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=_o(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 n=this.getConnection(s);if(n){let{id:o}=i;this.settleSubscribeWatchdog(n,o)}}switch(i.type){case"ack":{let n=this.subscriptions.getById(i.id);n&&this.ackAndAdvanceCursor(n,void 0,void 0);return}case"chunk":{let{data:n,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(n));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),this.adoptSocketConnectionId(i,s),this.confirmShardIdentity(s);break}case"live":{this.dispatchLive(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}case"whisper_subscribed":{this.acknowledgeWhisperJoin(v(s),i.topic);break}}}handleErrorMessage(e){let s=e.error?.code;if(s==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}if(s==="STREAM_ID_IN_USE")return;let{id:r}=e,i=r===void 0?void 0:this.streams.get(r);if(i&&r!==void 0){i.handle.fail(gr(e)),this.forgetStream(r);return}let n=r===void 0?void 0:this.subscriptions.getById(r);if(n){nt(n);let c=$t(e),u=this.identityFingerprint(),d=M.keyOf(n);this.markQueryRejected(n),ee(n.errorCallbacks,c),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(d,c,u);return}let o=r===void 0?void 0:this.shapeSubscriptions.get(r);o&&(o.answered||(o.answered=!0,this.emitSyncStatus()),ee(o.errorCallbacks,$t(e)))}markQueryRejected(e,s=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()||this.connectionGateState(e.shardKey).polling){this.settleAwaitedAnswer(e,!1),!(s?e.valueReceived:e.ack==="acked")&&(s?e.valueReceived=!0:V(e,"acked"),this.emitSyncStatus())}handlePokeEnd(e,s){let r=this.pokeAssembler.end(s,e.pokeId);if(r){Jo(this.shapeSubscriptions,r);for(let i of r.parts.keys()){let n=this.shapeSubscriptions.get(i);n&&!r.undecodable.has(i)&&this.applyPokePart(n,r,e)}}}applyPokePart(e,s,r){let i=e.answered,n=Vo(e,s,r);if(e.answered!==i&&this.emitSyncStatus(),Rr(e),n==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){V(e,"idle"),e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,this.emitSyncStatus(),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||e.type==="data"&&Yo(i,e))return;let n,o=i.pendingDeltaRun;try{n=nr(e,o===void 0?i.serverBase:o.payload)}catch(u){i.pendingDeltaRun=void 0,ee(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription \u2014 ${u instanceof Error?u.message:String(u)}`}),this.settleAwaitedAnswer(i,!1);return}if(n===_t){this.resnapshotSubscription(i);return}if(Xo(e)){i.pendingDeltaRun={payload:n};return}i.pendingDeltaRun=void 0,this.dropCacheSeed(M.keyOf(i));let c=s!==void 0&&!i.valueReceived;if(_r(i,n,{cursor:e.cursor,epoch:e.epoch}),c&&(i.valueReceived=!0,this.emitSyncStatus()),e.lastMutationId!==void 0&&(as(i,e.lastMutationId),os(i,!0)),this.persistQueryValue(i),ot(i,i.serverCursor),s!==void 0&&fr(i,s),ae(i,n),this.tabCoordinator?.isLeader()){let u=M.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(u,n,i.serverCursor,i.serverEpoch,this.identityFingerprint())}this.settleAwaitedAnswer(i,!0)}handleResumeMessage(e){let s=this.subscriptions.getById(e.id);s&&(s.pendingDeltaRun=void 0,this.ackAndAdvanceCursor(s,e.cursor,e.epoch),this.tabCoordinator?.isLeader()&&s.serverBase!==void 0&&this.tabCoordinator.broadcastSubscriptionData(M.keyOf(s),s.serverBase,s.serverCursor,s.serverEpoch,this.identityFingerprint()),this.settleAwaitedAnswer(s,!0))}handleSettledMessage(e){let s=this.subscriptions.getById(e.id);if(s&&(this.ackAndAdvanceCursor(s,e.cursor,e.epoch),e.lastMutationId!==void 0&&as(s,e.lastMutationId),os(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){let i=e.ack!=="acked";V(e,"acked"),i&&this.emitSyncStatus(),(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),ot(e,e.serverCursor)&&ae(e,e.serverBase))}adoptSocketConnectionId(e,s){let r=this.getConnection(s);if(!(r===void 0||typeof e.connectionId!="string")){r.connectionId=e.connectionId,r.whisperAck=e.whisperAck===!0;for(let i of this.liveSocketGrants.get(v(s))?.keys()??[])this.grantWhenJoined(s,i,e.connectionId)}}grantWhenJoined(e,s,r){let i=v(e),n=this.liveSocketGrants.get(i)?.get(s);if(n===void 0)return;let{stream:o,topic:c}=n,u=a(()=>{this.liveSocketGrants.get(i)?.get(s)===void 0||this.getConnection(e)?.connectionId!==r||this.postLiveControl(`/live/${o}/control`,e,{action:"subscribe",connectionId:r,stream:o,subscriptionId:s,topic:c},d=>{this.refuseLiveGrant(e,s,d,r)})},"c");this.getConnection(e)?.whisperAck===!0?this.whenWhisperJoined(i,c,u):u()}sendWhisperJoin(e,s,r){let i=this.whisperJoinState(s,r);i.pending+=1,i.joined=!1,B(e,{topic:r,type:"whisper_subscribe"})}acknowledgeWhisperJoin(e,s){let r=this.whisperJoins.get(e)?.get(s);if(r!==void 0&&(r.pending=Math.max(0,r.pending-1),!(r.pending>0))){r.joined=!0;for(let i of r.waiters.splice(0))clearTimeout(i.timer),i.run();this.releaseWhisperJoin(e,s)}}releaseWhisperJoin(e,s){if(this.whisperHandlers.get(e)?.has(s)===!0)return;let r=this.whisperJoins.get(e),i=r?.get(s);if(!(r===void 0||i===void 0||i.pending>0)){for(let n of i.waiters.splice(0))clearTimeout(n.timer);r.delete(s),r.size===0&&this.whisperJoins.delete(e)}}whenWhisperJoined(e,s,r){let i=this.whisperJoinState(e,s);if(i.joined){r();return}let n={run:r,timer:void 0};n.timer=setTimeout(()=>{i.waiters=i.waiters.filter(o=>o!==n),r()},Dr),i.waiters.push(n)}dropWhisperJoinWaiters(e){for(let s of this.whisperJoins.get(e)?.values()??[])for(let r of s.waiters.splice(0))clearTimeout(r.timer)}whisperJoinState(e,s){let r=this.whisperJoins.get(e);r===void 0&&(r=new Map,this.whisperJoins.set(e,r));let i=r.get(s);return i===void 0&&(i={joined:!1,pending:0,waiters:[]},r.set(s,i)),i}refuseLiveGrant(e,s,r,i){let n=v(e),o=this.liveSocketGrants.get(n),c=o?.get(s);o===void 0||c===void 0||this.getConnection(e)?.connectionId!==i||(o.delete(s),o.size===0&&this.liveSocketGrants.delete(n),c.release(),c.onError?.({status:r,topic:c.topic}))}postLiveControl(e,s,r,i){let{fetchImpl:n}=this;if(!n)return;let o=JSON.stringify(s===void 0?r:{...r,shardKey:s}),c=this.rpcRequestHeaders({},s);this.liveControlChain=this.liveControlChain.then(()=>fc(n,W(this.url,e),o,c)).then(u=>{u>=400&&u<500&&u!==404&&u!==401&&i?.(u)}).catch(()=>{})}dispatchLive(e,s){let r=this.liveSocketGrants.get(v(s));if(!r)return;let i=T(e.data);for(let n of r.values())if(!(n.stream!==e.stream||n.topic!==e.topic))try{n.onEvent(i)}catch{}}dispatchWhisper(e,s){let r=this.whisperHandlers.get(v(s))?.get(e.topic);if(!r)return;let i=T(e.data);for(let n of r)try{n(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&&(V(r,"idle"),this.emitSyncStatus(),ee(r.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&(this.replayAttempts.delete(e),this.offlineQueue.discard(e))}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;let e=this.authToken;return e===null?null:(this.tokenFingerprint?.token!==e&&(this.tokenFingerprint={hash:this.hashToken(e),token:e}),this.tokenFingerprint.hash)}hashToken(e){let s=2166136261,r=5381;for(let i=0;i<e.length;i+=1){let n=e.charCodeAt(i);s^=n,s=Math.imul(s,16777619),r=Math.imul(r,33)+n}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&&Le(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)}sendEncodedWhisper(e,s,r){this.ensureSocket(r.shardKey);let i=this.getConnection(r.shardKey),n=i!==void 0&&B(i,{data:s,topic:e,type:"whisper"});return this.releaseIdleShard(r.shardKey),n}roomSendsAdmitted(e){let s=this.getConnection(e);return s?.wsState==="open"&&s.retired!==!0&&s.identityConfirmed===!0&&s.roomsRejoined===!0}releaseRoomSends(e){if(this.roomSendsAdmitted(e))for(let s of this.roomFlushes.get(v(e))??[])s()}confirmShardIdentity(e){let s=this.getConnection(e);s!==void 0&&(s.identityConfirmed=!0,s.polling.noteOpen()),this.releaseRoomSends(e)}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 n=new Error("offline mutation discarded: auth identity changed before replay");n.code="OFFLINE_IDENTITY_CHANGED",i.reject(n),this.emitItemSettled(i,"rejected",n)}this.offlineQueue.requeue(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 n=s??"",o=this.clientWatermarks.get(n);if(o===void 0)this.clientWatermarks.set(n,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.resetRoomSends(),this.revokeCacheSeededValues(),this.reconnectCold(),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()}resetRoomSends(){for(let e of this.roomIdentityResets)e()}reconnectCold(){for(let e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,V(e,"idle"),e.valueReceived=!1,ae(e,void 0);for(let e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,e.answered=!1,Rr(e);this.emitSyncStatus(),this.bounceShardSockets()}bounceShardSockets(){for(let e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}else e.providerAttempt!==void 0&&this.startShardSocket(e,e.shardKey).catch(()=>{this.handleDisconnect(e)});for(let e of this.supplementaryBounces)e()}flushAllOfflineQueues(){for(let e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){let s=v(e),r=this.offlineFlushes.get(s);if(r===void 0&&this.offlineQueue.size===0)return;let i=(async()=>{await(r??Promise.resolve());let{authToken:n}=this;try{await this.drainOfflineQueue(e,n)}catch{}!this.closed&&this.authToken!==n&&this.offlineQueue.size>0&&Le(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))}snapshotAnswer(e){let s=Yt(e),r=s&&this.subscriptions.get(M.key(s.functionPath,s.args,s.shardKey));if(r!==void 0)return this.awaitingAnswer.has(r)?"awaiting":this.answeredUnreadable.has(r)?"unreadable":void 0}holdWhileUnanswered(e){let s=Yt(e);if(e===void 0||s===void 0)return e;let r=a(()=>this.snapshotAnswer(e)!==void 0||e(),"s");return Jt(r,s),r}awaitLeaderAnswers(){for(let e of this.subscriptions.all())this.awaitLeaderAnswer(e)}awaitLeaderAnswer(e){this.awaitingAnswer.add(e),this.answeredUnreadable.delete(e),clearTimeout(this.leaderAnswerTimers.get(e)),this.leaderAnswerTimers.set(e,setTimeout(()=>{this.leaderAnswerTimers.delete(e),this.isCrossTabFollower()&&this.settleAwaitedAnswer(e,!1)},2*1e4))}settleAwaitedAnswer(e,s){clearTimeout(this.leaderAnswerTimers.get(e)),this.leaderAnswerTimers.delete(e),s&&this.answeredUnreadable.delete(e),this.awaitingAnswer.delete(e)&&(s||this.answeredUnreadable.add(e),this.answerHeldShards.delete(v(e.shardKey))&&this.flushOfflineQueue(e.shardKey).catch(()=>{}))}holdUndecidedWrites(e,s){let r=s.findIndex(i=>this.snapshotAnswer(i.precondition)==="awaiting");return r===-1?s:(this.offlineQueue.requeue(s.slice(r)),this.answerHeldShards.add(e),s.slice(0,r))}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=v(e),n=this.holdUndecidedWrites(i,this.offlineQueue.drain(h=>v(h.shardKey)===i));if(n.length===0)return;let o=[],c=[];for(let h of n){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+=Xt){let l=u.slice(h,h+Xt),p=await this.replayBatched(l,e,s);if(d.push(...p.requeue),p.stop||p.requeue.length>0){d.push(...u.slice(h+Xt));break}}d.length>0&&this.offlineQueue.requeue(d),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){let s=v(e),r=this.replayRetryState.get(s),i=(r?.attempts??0)+1;this.replayRetryState.set(s,{attempts:i,delayMs:Math.max(r?.delayMs??0,is(i))})}noteReplayRetryDelay(e,s,r){let i=v(e),n=this.replayRetryState.get(i),o=(n?.attempts??0)+1,c=Wo(s,o)??(r===null&&Re(s)?is(o):void 0);this.replayRetryState.set(i,{attempts:o,delayMs:c===void 0?n?.delayMs:Math.max(n?.delayMs??0,c)})}scheduleRateLimitedRetry(e){let s=v(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 n=this.replayRetryTimers.get(s);n!==void 0&&clearTimeout(n),this.replayRetryTimers.set(s,setTimeout(()=>{this.replayRetryTimers.delete(s),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){let s=[];for(let r of e)try{J(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)||Ir(e)}noteReplayAuthRefusal(e,s){if(!Re(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,...ts(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)}spendsLastReplayAttempt(e,s){if(e.id===void 0)return!1;let r=s?.code;if(e.ambiguousSend!==!0||Re(s)||r==="RATE_LIMITED"||r==="TOO_MANY_REQUESTS"||!Ir(s))return!1;let i=(this.replayAttempts.get(e.id)??0)+1;return this.replayAttempts.set(e.id,i),i>=5}keepUnexhaustedAmbiguousWrites(e,s){return e.filter(r=>r.ambiguousSend===!0&&this.spendsLastReplayAttempt(r,s)?(this.settleReplayTerminal(r,s),!1):!0)}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 n=e[i];if(!n)continue;let o;try{let c=await this.rpc(n.functionPath,n.args,n.shardKey,{authToken:r,baselineSeq:n.baselineSeq,captureBookmark:!0,clientId:n.clientId??this.clientId,...ts(n.identity,r),mutationId:n.id,onCommitCursor:a(u=>{o=u},"onCommitCursor")});this.settleReplaySuccess(n,c,o)}catch(c){if(Me(c)){this.settleReplayUndecodable(n,c,o);continue}if(!this.shouldRequeueReplayFailure(c,r)||this.spendsLastReplayAttempt(n,c)){this.settleReplayTerminal(n,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:J(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&&$o(i)>Bo)return await this.replayBatchedHalves(e,s,r);let{fetchImpl:n}=this,o,c;try{({payload:c,response:o}=await ce(this.rpcTimeoutMs,void 0,async d=>{let h=await n(W(this.url,Zt),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:r,...ts(e.find(l=>l.identity!==void 0)?.identity,r)}),method:"POST",signal:d});if(h.status===413&&e.length>1)return{payload:void 0,response:h};try{return{payload:await h.json(),response:h}}catch{return{payload:void 0,response:h}}}))}catch(d){return this.noteReplayRetryDelay(s,d,r),{requeue:this.keepUnexhaustedAmbiguousWrites(e,d),stop:!0}}let u=o.headers.get("x-d1-bookmark");if(u&&this.bookmark.set(u),o.status===413&&e.length>1)return await this.replayBatchedHalves(e,s,r);if(!c)return this.settleWholeBatchError(e,xe(o.status,o.statusText,o.headers),s,r);if(!Array.isArray(c.results)){let d=ge(c),h=d===void 0?xe(o.status,o.statusText,o.headers):Ht(d,o.headers);return this.settleWholeBatchError(e,h,s,r)}return{requeue:this.settleReplayBatchSlots(e,c.results,s,r,o.headers),stop:!1}}settleWholeBatchError(e,s,r,i){if(s instanceof U||s.code!==void 0&&this.shouldRequeueReplayFailure(s,i))return this.noteReplayRetryDelay(r,s,i),{requeue:this.keepUnexhaustedAmbiguousWrites(e,s),stop:!0};for(let n of e)this.settleReplayTerminal(n,s);return{requeue:[],stop:!1}}async replayBatchedHalves(e,s,r){let i=Math.ceil(e.length/2),n=await this.replayBatched(e.slice(0,i),s,r);if(n.stop||n.requeue.length>0)return{requeue:[...n.requeue,...e.slice(i)],stop:!0};let o=await this.replayBatched(e.slice(i),s,r);return{requeue:[...n.requeue,...o.requeue],stop:o.stop}}settleReplayBatchSlots(e,s,r,i,n){let o=Ho(s),c=[],u=!1,d=!1;for(let[h,l]of e.entries()){let p=zo(o.get(h),n);switch(p.kind){case"committed":{u=!0,this.settleReplaySuccess(l,p.value,p.commitCursor);break}case"errored":{d||=Re(p.error),this.shouldRequeueReplayFailure(p.error,i)&&!this.spendsLastReplayAttempt(l,p.error)?(this.noteReplayRetryDelay(r,p.error,i),c.push(l)):this.settleReplayTerminal(l,p.error);break}case"unanswered":{let f=K(Bt(),n);if(this.spendsLastReplayAttempt(l,f)){this.settleReplayTerminal(l,f);break}this.noteReplayRetryDelay(r,f,i),c.push(l);break}default:u=!0,this.settleReplayUndecodable(l,p.error,p.commitCursor)}}return u&&!d&&this.noteCredentialAccepted(i),c}};var Ur=D(fs(),1),Kr=D(re(),1);var vc=a(()=>{let t=(0,Ur.c)(4),e=Pt(),s,r,i;return t[0]!==e?(s=a(n=>e.onConnectionStatus(()=>{n()}),"o"),r=a(()=>e.connectionStatus(),"e"),i=a(()=>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,Kr.useSyncExternalStore)(s,r,i)},"S");export{Se as a,De as b,$ as c,T as d,oi as e,cs as f,li as g,Ce as h,Ci as i,ki as j,Ri as k,Pt as l,vc as m};
@@ -1 +1 @@
1
- import{b as g}from"./chunk-E4Y6TF6C.js";import"./chunk-R75AFV7G.js";import"./chunk-NCPW7WHO.js";import"./chunk-IQ3SMVFW.js";import"./chunk-55UGUCQ6.js";import{a as f}from"./chunk-4ZEL6BYL.js";import{c as m}from"./chunk-T2JHVL34.js";import"./chunk-AVSMQPR3.js";import"./chunk-QAQDMS6R.js";import"./chunk-3I25WO3P.js";import"./chunk-HCTJKP5J.js";import"./chunk-2IKDEUCX.js";import{d as p}from"./chunk-74IYYDDI.js";import{a as r,d as h,f as S,g as A}from"./chunk-I26MS5PJ.js";var R=h(S(),1);var k=h(A(),1);var _=r((e,s)=>({"admin-token-weak":e("Weak admin token"),"auth-secret-weak":e("Weak auth secret"),"cookies-insecure":e("Session cookies are not Secure"),"cors-wildcard-credentials":e("Wildcard CORS with credentials"),"csrf-disabled":e("CSRF/origin guard is off"),"dev-args-unredacted":e("Request log keeps un-redacted args"),"security-headers-disabled":e("Security headers are off"),"ws-gate-open":e("User subscriptions are ungated")})[s.kind],"k"),w=r(e=>Array.isArray(e.findings)?e.findings:[],"g"),b=r(e=>({"admin-token-weak":"LUNORA_ADMIN_TOKEN","auth-secret-weak":"AUTH_SECRET","cookies-insecure":"BETTER_AUTH_URL","cors-wildcard-credentials":"LUNORA_ALLOWED_ORIGINS","csrf-disabled":"LUNORA_SECURITY_CSRF","dev-args-unredacted":"request log","security-headers-disabled":"LUNORA_SECURITY_HEADERS","ws-gate-open":"LUNORA_WS_BEARER"})[e.kind],"S"),E=r((e,s)=>({"admin-token-weak":e("Your admin token is {length} characters \u2014 use at least {min} for a brute-force-resistant secret.",{length:s.detail?.length,min:s.detail?.min}),"auth-secret-weak":e("Your auth secret is {length} characters \u2014 use at least {min} (e.g. `openssl rand -hex 32`) to sign sessions safely.",{length:s.detail?.length,min:s.detail?.min}),"cookies-insecure":e("BETTER_AUTH_URL is a plaintext http:// origin, so session cookies cannot be Secure and ride in cleartext. Serve auth over https:// in production."),"cors-wildcard-credentials":e("LUNORA_ALLOWED_ORIGINS includes a wildcard while credentials are allowed \u2014 browsers reject this and it defeats the allowlist. Name explicit origins instead of *."),"csrf-disabled":e("LUNORA_SECURITY_CSRF is off, so cross-origin state-changing cookie requests are not blocked. Re-enable it in production to keep mutations un-forgeable."),"dev-args-unredacted":e("This worker reports a development environment, so the request log stores raw args and identity. Confirm it isn't a mislabeled production deploy."),"security-headers-disabled":e("LUNORA_SECURITY_HEADERS is off, so HSTS, CSP, nosniff, and frame-options are not applied. Re-enable the baseline headers in production."),"ws-gate-open":e("LUNORA_WS_BEARER is unset, so the WebSocket upgrade gate is open: anyone who can reach the worker can open a socket and run ordinary user subscriptions. Admin subscriptions are unaffected \u2014 they need the admin token. Set it if subscribers should present a shared credential.")})[s.kind],"A"),O=r(()=>{let e=(0,R.c)(8),s=p(),i;e[0]===Symbol.for("react.memo_cache_sentinel")?(i={},e[0]=i):i=e[0];let{data:a,error:d,errorSource:c}=m(f.getSecurityAudit,i),n;if(e[1]!==a||e[2]!==s){let u=a===void 0?null:w(a);n=u===null?null:u.map(t=>({description:E(s,t),entity:b(t),issueType:_(s,t),key:t.kind,level:t.level})),e[1]=a,e[2]=s,e[3]=n}else n=e[3];let l=n,o;return e[4]!==d||e[5]!==c||e[6]!==l?(o=(0,k.jsx)(g,{error:d,errorSource:c,rows:l,testId:"lunora-security-advisor"}),e[4]=d,e[5]=c,e[6]=l,e[7]=o):o=e[7],o},"T");export{O as default};
1
+ import{b as g}from"./chunk-63QLK2KW.js";import"./chunk-C7FJ2JKY.js";import"./chunk-NCPW7WHO.js";import"./chunk-G43F7LYA.js";import"./chunk-55UGUCQ6.js";import{a as f}from"./chunk-4ZEL6BYL.js";import{c as m}from"./chunk-RX755NMO.js";import"./chunk-YBDF3DET.js";import"./chunk-QAQDMS6R.js";import"./chunk-HBO4SMAO.js";import"./chunk-HCTJKP5J.js";import"./chunk-2IKDEUCX.js";import{d as p}from"./chunk-74IYYDDI.js";import{a as r,d as h,f as S,g as A}from"./chunk-I26MS5PJ.js";var R=h(S(),1);var k=h(A(),1);var _=r((e,s)=>({"admin-token-weak":e("Weak admin token"),"auth-secret-weak":e("Weak auth secret"),"cookies-insecure":e("Session cookies are not Secure"),"cors-wildcard-credentials":e("Wildcard CORS with credentials"),"csrf-disabled":e("CSRF/origin guard is off"),"dev-args-unredacted":e("Request log keeps un-redacted args"),"security-headers-disabled":e("Security headers are off"),"ws-gate-open":e("User subscriptions are ungated")})[s.kind],"k"),w=r(e=>Array.isArray(e.findings)?e.findings:[],"g"),b=r(e=>({"admin-token-weak":"LUNORA_ADMIN_TOKEN","auth-secret-weak":"AUTH_SECRET","cookies-insecure":"BETTER_AUTH_URL","cors-wildcard-credentials":"LUNORA_ALLOWED_ORIGINS","csrf-disabled":"LUNORA_SECURITY_CSRF","dev-args-unredacted":"request log","security-headers-disabled":"LUNORA_SECURITY_HEADERS","ws-gate-open":"LUNORA_WS_BEARER"})[e.kind],"S"),E=r((e,s)=>({"admin-token-weak":e("Your admin token is {length} characters \u2014 use at least {min} for a brute-force-resistant secret.",{length:s.detail?.length,min:s.detail?.min}),"auth-secret-weak":e("Your auth secret is {length} characters \u2014 use at least {min} (e.g. `openssl rand -hex 32`) to sign sessions safely.",{length:s.detail?.length,min:s.detail?.min}),"cookies-insecure":e("BETTER_AUTH_URL is a plaintext http:// origin, so session cookies cannot be Secure and ride in cleartext. Serve auth over https:// in production."),"cors-wildcard-credentials":e("LUNORA_ALLOWED_ORIGINS includes a wildcard while credentials are allowed \u2014 browsers reject this and it defeats the allowlist. Name explicit origins instead of *."),"csrf-disabled":e("LUNORA_SECURITY_CSRF is off, so cross-origin state-changing cookie requests are not blocked. Re-enable it in production to keep mutations un-forgeable."),"dev-args-unredacted":e("This worker reports a development environment, so the request log stores raw args and identity. Confirm it isn't a mislabeled production deploy."),"security-headers-disabled":e("LUNORA_SECURITY_HEADERS is off, so HSTS, CSP, nosniff, and frame-options are not applied. Re-enable the baseline headers in production."),"ws-gate-open":e("LUNORA_WS_BEARER is unset, so the WebSocket upgrade gate is open: anyone who can reach the worker can open a socket and run ordinary user subscriptions. Admin subscriptions are unaffected \u2014 they need the admin token. Set it if subscribers should present a shared credential.")})[s.kind],"A"),O=r(()=>{let e=(0,R.c)(8),s=p(),i;e[0]===Symbol.for("react.memo_cache_sentinel")?(i={},e[0]=i):i=e[0];let{data:a,error:d,errorSource:c}=m(f.getSecurityAudit,i),n;if(e[1]!==a||e[2]!==s){let u=a===void 0?null:w(a);n=u===null?null:u.map(t=>({description:E(s,t),entity:b(t),issueType:_(s,t),key:t.kind,level:t.level})),e[1]=a,e[2]=s,e[3]=n}else n=e[3];let l=n,o;return e[4]!==d||e[5]!==c||e[6]!==l?(o=(0,k.jsx)(g,{error:d,errorSource:c,rows:l,testId:"lunora-security-advisor"}),e[4]=d,e[5]=c,e[6]=l,e[7]=o):o=e[7],o},"T");export{O as default};