@lunora/studio 1.0.0-alpha.376 → 1.0.0-alpha.378
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +16 -5
- package/dist/index.d.ts +16 -5
- package/dist/index.mjs +1 -1
- package/dist/mount.d.mts +1 -1
- package/dist/mount.d.ts +1 -1
- package/dist/mount.mjs +1 -1
- package/dist/packem_chunks/AdvisorHealthPanel.mjs +1 -1
- package/dist/packem_chunks/ApiTab.mjs +1 -1
- package/dist/packem_chunks/AuditPanel.mjs +1 -1
- package/dist/packem_chunks/ExportImportPanel.mjs +1 -1
- package/dist/packem_chunks/FileBrowser.mjs +1 -1
- package/dist/packem_chunks/FunctionRunner.mjs +1 -1
- package/dist/packem_chunks/FunctionStatsPanel.mjs +1 -1
- package/dist/packem_chunks/HealthPanel.mjs +1 -1
- package/dist/packem_chunks/InsightsPanel.mjs +1 -1
- package/dist/packem_chunks/LogsPanel.mjs +1 -1
- package/dist/packem_chunks/MailPanel.mjs +1 -1
- package/dist/packem_chunks/MetricsPanel.mjs +1 -1
- package/dist/packem_chunks/NotificationsPanel.mjs +1 -1
- package/dist/packem_chunks/PitrPanel.mjs +1 -1
- package/dist/packem_chunks/SchemaViewer.mjs +1 -1
- package/dist/packem_chunks/SecurityAdvisorPanel.mjs +1 -1
- package/dist/packem_chunks/SettingsPanel.mjs +1 -1
- package/dist/packem_chunks/SqlEditorPanel.mjs +1 -1
- package/dist/packem_chunks/TableEditor.mjs +1 -1
- package/dist/packem_chunks/agents-panel.mjs +1 -1
- package/dist/packem_chunks/ai-knowledge.mjs +1 -1
- package/dist/packem_chunks/ai-usage-panel.mjs +1 -1
- package/dist/packem_chunks/assistant-panel.mjs +1 -1
- package/dist/packem_chunks/auth-audit-panel.mjs +1 -1
- package/dist/packem_chunks/containers-panel.mjs +1 -1
- package/dist/packem_chunks/dashboards-panel.mjs +1 -1
- package/dist/packem_chunks/evals-panel.mjs +1 -1
- package/dist/packem_chunks/fanout-panel.mjs +1 -1
- package/dist/packem_chunks/flags-panel.mjs +1 -1
- package/dist/packem_chunks/issues-panel.mjs +1 -1
- package/dist/packem_chunks/kv-browser.mjs +1 -1
- package/dist/packem_chunks/migrations-route.mjs +1 -1
- package/dist/packem_chunks/payments-panel.mjs +1 -1
- package/dist/packem_chunks/permissions-panel.mjs +1 -1
- package/dist/packem_chunks/privacy-requests-panel.mjs +1 -1
- package/dist/packem_chunks/queues-panel.mjs +1 -1
- package/dist/packem_chunks/reactors-panel.mjs +1 -1
- package/dist/packem_chunks/rls-panel.mjs +1 -1
- package/dist/packem_chunks/schedule-panel.mjs +1 -1
- package/dist/packem_chunks/storage-rules-panel.mjs +1 -1
- package/dist/packem_chunks/subscriptions-panel.mjs +1 -1
- package/dist/packem_chunks/traces-panel.mjs +1 -1
- package/dist/packem_chunks/workflows-panel.mjs +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-DAHZ35kM.mjs +1 -0
- package/dist/packem_shared/{ApiDocsPanel-xqgxgYCy.mjs → ApiDocsPanel-sEDqUNQq.mjs} +1 -1
- package/dist/packem_shared/{DataBrowser-BR2nrvMW.mjs → DataBrowser-CkVOu6py.mjs} +1 -1
- package/dist/packem_shared/{GlobalDataBrowser-Df5S1NxG.mjs → GlobalDataBrowser-l2ECwXCm.mjs} +1 -1
- package/dist/packem_shared/{HomePanel-CHq9VBrh.mjs → HomePanel-c7as4tvl.mjs} +1 -1
- package/dist/packem_shared/{MigrationsPanel-BWGgOwmX.mjs → MigrationsPanel-BQol4Un1.mjs} +1 -1
- package/dist/packem_shared/{Studio-JuMI1hpi.mjs → Studio-BmbkaUrx.mjs} +1 -1
- package/dist/packem_shared/{StudioApp-02dw_keu.mjs → StudioApp-CsyDnrg2.mjs} +1 -1
- package/dist/packem_shared/{advisor-view-Dj-mZPAq.mjs → advisor-view-gtf_DhUU.mjs} +1 -1
- package/dist/packem_shared/{app.d-BXrVLb99.d.mts → app.d-DpxFQ0qO.d.mts} +14 -0
- package/dist/packem_shared/{app.d-BXrVLb99.d.ts → app.d-DpxFQ0qO.d.ts} +14 -0
- package/dist/packem_shared/{assistant-provider-BQG7QZAu.mjs → assistant-provider-Dw0roZh3.mjs} +1 -1
- package/dist/packem_shared/{error-alert-BzZfqmf4.mjs → error-alert-3AR_-s_s.mjs} +1 -1
- package/dist/packem_shared/{home-panel-DTWHlX5S.mjs → home-panel-TpxiaHgB.mjs} +1 -1
- package/dist/packem_shared/log-fields-PjFFEqv0.mjs +8 -0
- package/dist/packem_shared/log-line-DnvvQnY5.mjs +1 -0
- package/dist/packem_shared/{studio-DtxNxSjs.mjs → studio-DZlpp4Vx.mjs} +1 -1
- package/dist/packem_shared/{table-list-sidebar-C8qPvzGk.mjs → table-list-sidebar-Bfmg04MD.mjs} +1 -1
- package/dist/packem_shared/{use-assistant-rpc-DCC6ph2u.mjs → use-assistant-rpc-AKu8hvPm.mjs} +1 -1
- package/dist/standalone/{chunk-SW52HGM4.js → chunk-27YLJQRE.js} +1 -1
- package/dist/standalone/{chunk-J45HAKBU.js → chunk-2KTN53PK.js} +1 -1
- package/dist/standalone/chunk-2NUCBQFU.js +1 -0
- package/dist/standalone/{chunk-CCETXQNF.js → chunk-2Q66YTBU.js} +1 -1
- package/dist/standalone/{chunk-WSG35SRF.js → chunk-2RL5YVB7.js} +1 -1
- package/dist/standalone/chunk-2SWWUGUK.js +1 -0
- package/dist/standalone/{chunk-VXZAS5VS.js → chunk-3OVNOP65.js} +1 -1
- package/dist/standalone/{chunk-AFVVESAA.js → chunk-3PRGO2WY.js} +1 -1
- package/dist/standalone/{chunk-N3FNOCHB.js → chunk-3RZB5QXH.js} +1 -1
- package/dist/standalone/{chunk-4EPW63HS.js → chunk-4AG356VE.js} +1 -1
- package/dist/standalone/{chunk-IJNP6YSD.js → chunk-4I23RURI.js} +1 -1
- package/dist/standalone/{chunk-ZSWW2UGP.js → chunk-4KPATTV6.js} +1 -1
- package/dist/standalone/chunk-4S7ZIMWI.js +33 -0
- package/dist/standalone/{chunk-HFBSWKJS.js → chunk-4SY2N2RS.js} +1 -1
- package/dist/standalone/{chunk-25WEL5RI.js → chunk-4XNMLHOA.js} +1 -1
- package/dist/standalone/{chunk-4NKJV7YX.js → chunk-4YENBZSS.js} +1 -1
- package/dist/standalone/{chunk-645S7KRU.js → chunk-5G2OOLMF.js} +1 -1
- package/dist/standalone/{chunk-B76HLC52.js → chunk-66PQJM66.js} +1 -1
- package/dist/standalone/{chunk-K3MVWN6E.js → chunk-6DKBHMBL.js} +1 -1
- package/dist/standalone/{chunk-YTPE33AO.js → chunk-6EPIINAW.js} +1 -1
- package/dist/standalone/{chunk-QURCU2N2.js → chunk-6IECLZ2U.js} +1 -1
- package/dist/standalone/{chunk-SUUBCPUD.js → chunk-77PKR3WU.js} +1 -1
- package/dist/standalone/{chunk-6BH5TIGF.js → chunk-7MQI2RNF.js} +1 -1
- package/dist/standalone/chunk-7WGZSDRS.js +2 -0
- package/dist/standalone/{chunk-64LU3VU6.js → chunk-A5HJXHD2.js} +1 -1
- package/dist/standalone/{chunk-MWYGLPDV.js → chunk-A5INOAIL.js} +1 -1
- package/dist/standalone/{chunk-FEHRNTIU.js → chunk-A6E46F3B.js} +1 -1
- package/dist/standalone/{chunk-GWNGVKLG.js → chunk-A6TVTNKO.js} +1 -1
- package/dist/standalone/{chunk-6G3E4PJ2.js → chunk-ADABTCDI.js} +1 -1
- package/dist/standalone/{chunk-GXTSE66Z.js → chunk-AFLNQEZ5.js} +1 -1
- package/dist/standalone/{chunk-CLQKKJHL.js → chunk-AKC4XWCD.js} +1 -1
- package/dist/standalone/{chunk-BE3FD3E6.js → chunk-APTQ5BDE.js} +1 -1
- package/dist/standalone/{chunk-B4PRNI7H.js → chunk-ASSIQ4W7.js} +1 -1
- package/dist/standalone/{chunk-PEVNCIZQ.js → chunk-BEC2C3JD.js} +1 -1
- package/dist/standalone/{chunk-HSI24FPH.js → chunk-BMGCCYQL.js} +1 -1
- package/dist/standalone/{chunk-F4S2YEYW.js → chunk-BMS6CAKT.js} +1 -1
- package/dist/standalone/{chunk-D3DZZHZA.js → chunk-BOYBN3TE.js} +1 -1
- package/dist/standalone/{chunk-BQS3C5V3.js → chunk-BR2A4DYH.js} +1 -1
- package/dist/standalone/{chunk-OSHODLMU.js → chunk-CB22PV3X.js} +1 -1
- package/dist/standalone/chunk-CX2T7TTB.js +5 -0
- package/dist/standalone/{chunk-WB6VGH7X.js → chunk-CXAPSZF2.js} +1 -1
- package/dist/standalone/{chunk-CAEJQOMU.js → chunk-D5VO54BI.js} +1 -1
- package/dist/standalone/chunk-DKEK4ZO6.js +8 -0
- package/dist/standalone/{chunk-G6VBT4AU.js → chunk-DQWEVUGA.js} +1 -1
- package/dist/standalone/{chunk-2DT3QG6Q.js → chunk-DRHZZ7IN.js} +1 -1
- package/dist/standalone/{chunk-GMT66LBU.js → chunk-EA3RERQQ.js} +1 -1
- package/dist/standalone/{chunk-3D67ZJRW.js → chunk-EDL46BPM.js} +1 -1
- package/dist/standalone/{chunk-EYJX6GXU.js → chunk-ELXPUNSN.js} +1 -1
- package/dist/standalone/{chunk-4PI2OSSP.js → chunk-EOFWXI3T.js} +1 -1
- package/dist/standalone/{chunk-UBTKEHX6.js → chunk-F2EGC6HE.js} +1 -1
- package/dist/standalone/{chunk-HPD2PZP2.js → chunk-F32O6VAS.js} +1 -1
- package/dist/standalone/{chunk-X72A525Z.js → chunk-F5DCBRCJ.js} +1 -1
- package/dist/standalone/{chunk-OT2YNQPU.js → chunk-FBG5SSXS.js} +1 -1
- package/dist/standalone/chunk-FFQISGOB.js +1 -0
- package/dist/standalone/{chunk-QAQ3KMY6.js → chunk-FGEN2V4E.js} +1 -1
- package/dist/standalone/{chunk-7LCGAQWG.js → chunk-FNE6FFFN.js} +1 -1
- package/dist/standalone/{chunk-RDS46R5R.js → chunk-FOURRGSO.js} +1 -1
- package/dist/standalone/chunk-FPRVR763.js +8 -0
- package/dist/standalone/{chunk-PUU56AIE.js → chunk-FXSY2FCG.js} +1 -1
- package/dist/standalone/{chunk-C4BS3LHQ.js → chunk-FXZ6GEUP.js} +1 -1
- package/dist/standalone/{chunk-HAK2T6YN.js → chunk-H5AOMWTU.js} +1 -1
- package/dist/standalone/{chunk-2EB7FN5S.js → chunk-H6VTIXVB.js} +1 -1
- package/dist/standalone/{chunk-LQCF6SZW.js → chunk-HNNAMZHQ.js} +1 -1
- package/dist/standalone/{chunk-2BQNNRAP.js → chunk-IIIAOQ22.js} +1 -1
- package/dist/standalone/{chunk-LKML3CX4.js → chunk-IO3TEFOW.js} +1 -1
- package/dist/standalone/{chunk-KTK4NDWQ.js → chunk-IQ5CIBXJ.js} +1 -1
- package/dist/standalone/{chunk-QGAWQTUE.js → chunk-J76P372V.js} +1 -1
- package/dist/standalone/{chunk-7SNL633X.js → chunk-J7M7G2BA.js} +1 -1
- package/dist/standalone/{chunk-2MZLFQR5.js → chunk-JAY3ZKY6.js} +1 -1
- package/dist/standalone/{chunk-ELUYMLPL.js → chunk-JLPBW5EC.js} +1 -1
- package/dist/standalone/{chunk-HCOF7HOM.js → chunk-JNWK5MJC.js} +1 -1
- package/dist/standalone/{chunk-4DIRNQHR.js → chunk-KEICHBPK.js} +1 -1
- package/dist/standalone/{chunk-F5WJCL3F.js → chunk-KFDOGDD2.js} +1 -1
- package/dist/standalone/{chunk-MGFELY5Q.js → chunk-KMEDIMYZ.js} +1 -1
- package/dist/standalone/{chunk-YUVGMKHG.js → chunk-L27FKJTG.js} +1 -1
- package/dist/standalone/chunk-LDWYV63L.js +1 -0
- package/dist/standalone/{chunk-UBX5ZPLV.js → chunk-LMCBMC2V.js} +1 -1
- package/dist/standalone/chunk-LYVYUTQY.js +1 -0
- package/dist/standalone/{chunk-JIBRGVA7.js → chunk-MFVL3BKJ.js} +1 -1
- package/dist/standalone/chunk-MHZNDDGI.js +1 -0
- package/dist/standalone/{chunk-FERYOTLW.js → chunk-MSZMSG3J.js} +1 -1
- package/dist/standalone/{chunk-X45MVUVK.js → chunk-N5A7KU32.js} +1 -1
- package/dist/standalone/{chunk-QRA7AKYO.js → chunk-N7FOBAV3.js} +1 -1
- package/dist/standalone/{chunk-ZFEDRJ7R.js → chunk-NIGA74BG.js} +1 -1
- package/dist/standalone/{chunk-RTE7SDRS.js → chunk-NOJMUWHR.js} +1 -1
- package/dist/standalone/{chunk-QXNMGPXW.js → chunk-NSPPZR3Q.js} +1 -1
- package/dist/standalone/{chunk-CURIWKKC.js → chunk-O5NP5MVG.js} +1 -1
- package/dist/standalone/{chunk-TW4O2BA5.js → chunk-O5QATFN3.js} +3 -3
- package/dist/standalone/{chunk-PYQUCCUO.js → chunk-O65MHZCA.js} +1 -1
- package/dist/standalone/{chunk-6FPV3EK2.js → chunk-ODEIAS3V.js} +1 -1
- package/dist/standalone/{chunk-D65UVZIA.js → chunk-OWRWDDJT.js} +1 -1
- package/dist/standalone/{chunk-VUOEJJUH.js → chunk-OZID3UYF.js} +1 -1
- package/dist/standalone/{chunk-K46QTJR6.js → chunk-PKOFJJA2.js} +1 -1
- package/dist/standalone/{chunk-UVNJG3UL.js → chunk-PLONGJJL.js} +1 -1
- package/dist/standalone/{chunk-W2FHSEQW.js → chunk-QEQGGAZQ.js} +1 -1
- package/dist/standalone/{chunk-VNH4OBJS.js → chunk-QF743FSL.js} +1 -1
- package/dist/standalone/{chunk-ONTGYVAN.js → chunk-QLZGKBOW.js} +1 -1
- package/dist/standalone/chunk-R3RIZDUS.js +1 -0
- package/dist/standalone/{chunk-4RGKUS3H.js → chunk-R55GP52Y.js} +1 -1
- package/dist/standalone/{chunk-WAIESA3E.js → chunk-R6B5XFEW.js} +1 -1
- package/dist/standalone/chunk-SAV5V3DG.js +7 -0
- package/dist/standalone/{chunk-JYCGHNPF.js → chunk-SBY32RYL.js} +1 -1
- package/dist/standalone/{chunk-JMZT3CEW.js → chunk-SCTYLLJT.js} +1 -1
- package/dist/standalone/{chunk-BYUXIOPZ.js → chunk-SHTZR3TU.js} +1 -1
- package/dist/standalone/{chunk-KBYFBEG2.js → chunk-SZCXVIVT.js} +1 -1
- package/dist/standalone/{chunk-O3AZ7JKE.js → chunk-T7UKRA6J.js} +1 -1
- package/dist/standalone/{chunk-EX2DUBRT.js → chunk-TOBQK3ZF.js} +1 -1
- package/dist/standalone/{chunk-M4TCBPSY.js → chunk-TRJMN2YI.js} +1 -1
- package/dist/standalone/{chunk-ZCXG3567.js → chunk-TU2IB3GT.js} +1 -1
- package/dist/standalone/{chunk-EVJSGZXV.js → chunk-UA7DC3LX.js} +1 -1
- package/dist/standalone/{chunk-ALNEZ5D2.js → chunk-UCOKDCSX.js} +1 -1
- package/dist/standalone/{chunk-SWFSB4QT.js → chunk-UEM26EYR.js} +1 -1
- package/dist/standalone/{chunk-SZBLYYV6.js → chunk-UL5GMSAW.js} +1 -1
- package/dist/standalone/{chunk-EYMLYHWK.js → chunk-UVMD7C4J.js} +1 -1
- package/dist/standalone/{chunk-6YBEKVUG.js → chunk-V4D77Q45.js} +1 -1
- package/dist/standalone/{chunk-D6CDIHHL.js → chunk-VONBNFUJ.js} +1 -1
- package/dist/standalone/{chunk-3D2E7WXH.js → chunk-VY5KDMVO.js} +1 -1
- package/dist/standalone/{chunk-CHIQ3CJZ.js → chunk-W46UJQN7.js} +1 -1
- package/dist/standalone/{chunk-AQ62YJJ5.js → chunk-W5LH6U6X.js} +1 -1
- package/dist/standalone/{chunk-S36FVTKK.js → chunk-W7CLOQOU.js} +1 -1
- package/dist/standalone/{chunk-FWOOA2ZR.js → chunk-X26D3KTK.js} +1 -1
- package/dist/standalone/chunk-X2KZTOZR.js +1 -0
- package/dist/standalone/chunk-Y6OVSHPH.js +1 -0
- package/dist/standalone/{chunk-B3TXCZUI.js → chunk-YIOJWQ3G.js} +1 -1
- package/dist/standalone/{chunk-XLYFGUEF.js → chunk-YNCZVYCO.js} +1 -1
- package/dist/standalone/{chunk-OVEOTKK5.js → chunk-YU67D2FL.js} +1 -1
- package/dist/standalone/{chunk-AERXMIND.js → chunk-YV6YBDCS.js} +1 -1
- package/dist/standalone/{chunk-A2Q3TGIQ.js → chunk-YYJGL32M.js} +1 -1
- package/dist/standalone/{chunk-R3P6KKUH.js → chunk-YZUJTBSJ.js} +1 -1
- package/dist/standalone/{chunk-42RZZFLX.js → chunk-ZBP4ZBS6.js} +1 -1
- package/dist/standalone/{chunk-QHKR5JW4.js → chunk-ZF4WXT7S.js} +1 -1
- package/dist/standalone/{chunk-JAAXDIR5.js → chunk-ZK2HQFGQ.js} +1 -1
- package/dist/standalone/studio.js +3 -3
- package/dist/styles.css +1 -1
- package/package.json +10 -10
- package/dist/packem_shared/ADMIN_FUNCTIONS-C6U-ugro.mjs +0 -1
- package/dist/packem_shared/log-fields-BolUoZ9g.mjs +0 -1
- package/dist/packem_shared/log-line-BH0iWiBv.mjs +0 -1
- package/dist/standalone/chunk-3BQ6FMEA.js +0 -5
- package/dist/standalone/chunk-6A6AELDJ.js +0 -1
- package/dist/standalone/chunk-ASD6UAND.js +0 -1
- package/dist/standalone/chunk-BG2CJOVS.js +0 -1
- package/dist/standalone/chunk-BKI3JMXQ.js +0 -1
- package/dist/standalone/chunk-CZA2P2TU.js +0 -1
- package/dist/standalone/chunk-KGLIQIZU.js +0 -1
- package/dist/standalone/chunk-PFPJA2HR.js +0 -7
- package/dist/standalone/chunk-PUK3H4RN.js +0 -33
- package/dist/standalone/chunk-QAOZXPLU.js +0 -1
- package/dist/standalone/chunk-RTS5G3ET.js +0 -2
- package/dist/standalone/chunk-RWMOWRJX.js +0 -1
- package/dist/standalone/chunk-U4X2I55T.js +0 -1
- package/dist/standalone/chunk-YORPLSI5.js +0 -1
- package/dist/standalone/chunk-Z7ZGAQ5J.js +0 -8
- /package/dist/standalone/{chunk-NGVP66OH.js → chunk-QHVUXMRV.js} +0 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{a as Ps,b as v,c as Ls,d as Ms}from"./chunk-4S7ZIMWI.js";import{a as xs}from"./chunk-A6TVTNKO.js";import{a as ie,b as At}from"./chunk-ADABTCDI.js";import{a,d as H}from"./chunk-5PEAXTYQ.js";var de=a(t=>{try{return t(),!0}catch{return!1}},"o"),Gn=new Set([Object.prototype,Function.prototype]),Oe=a((t,e,s)=>{let r;for(let i=t;i!==null&&!Gn.has(i);i=Object.getPrototypeOf(i)){let n=Object.getOwnPropertyDescriptor(i,e)?.[s];typeof n=="function"&&(r=n)}return r},"y"),V=a((t,e)=>Oe(t,e,"get"),"r"),Ds=Oe(Date.prototype,"getTime","value"),Vn=V(Map.prototype,"size"),Jn=V(Set.prototype,"size"),Yn=V(ArrayBuffer.prototype,"byteLength"),Te=typeof URL=="function"?V(URL.prototype,"href"):void 0,Ft=typeof URL=="function"?URL.prototype:void 0,Xn=Te!==void 0&&Function.prototype.toString.call(Te).includes("[native code]"),_s=Oe(Error,"isError","value"),Qs=Error.prototype,Zn=a((t,e)=>typeof _s=="function"?_s(t):e!==null&&(e===Qs||Qs.isPrototypeOf(e)),"L"),ea=Oe(Map.prototype,"forEach","value"),ta=Oe(Set.prototype,"forEach","value"),Pt=Object.getPrototypeOf(Uint8Array.prototype),Lt={data:{buffer:V(DataView.prototype,"buffer"),byteLength:V(DataView.prototype,"byteLength"),byteOffset:V(DataView.prototype,"byteOffset")},typed:{buffer:V(Pt,"buffer"),byteLength:V(Pt,"byteLength"),byteOffset:V(Pt,"byteOffset")}},Us=a(t=>Reflect.apply(Ds,t,[]),"S"),Hs=a(t=>Reflect.apply(Te,t,[]),"m"),Ns=a(t=>{let e=[];return Reflect.apply(ea,t,[(s,r)=>e.push([r,s])]),e},"A"),Ks=a(t=>{let e=[];return Reflect.apply(ta,t,[s=>e.push(s)]),e},"w"),js=a(t=>{let e=de(()=>Reflect.apply(Lt.typed.buffer,t,[]))?Lt.typed:Lt.data;return new Uint8Array(Reflect.apply(e.buffer,t,[]),Reflect.apply(e.byteOffset,t,[]),Reflect.apply(e.byteLength,t,[]))},"j"),$e=a(t=>{if(Array.isArray(t))return"array";let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype?"plain":de(()=>Reflect.apply(Ds,t,[]))?"builtin-date":de(()=>Reflect.apply(Vn,t,[]))?"builtin-map":de(()=>Reflect.apply(Jn,t,[]))?"builtin-set":de(()=>Reflect.apply(Yn,t,[]))?"builtin-array-buffer":ArrayBuffer.isView(t)?"builtin-view":Zn(t,e)?"builtin-error":Te!==void 0&&(Xn||Ft!==void 0&&e!==null&&(e===Ft||Ft.isPrototypeOf(e)))&&de(()=>Reflect.apply(Te,t,[]))?"builtin-url":"other"},"D");var sa=2**32-1,ra=/["\\\u0000-\u001F\uD800-\uDFFF]/,qs=a(t=>ra.test(t)?JSON.stringify(t):`"${t}"`,"y"),ia=a(t=>Number.isNaN(t)?"nan":t===1/0?"inf":t===-1/0?"-inf":Object.is(t,-0)?"-0":void 0,"u"),na=a((t,e)=>{let s=t,r=Object.keys(s).sort(),i="{",n=!0;for(let o of r){let c=s[o];c!==void 0&&(n?n=!1:i+=",",i+=qs(o),i+=":",i+=e(c))}return`${i}}`},"g"),aa=a(t=>{let{length:e}=t,s=Number.isInteger(e)?e:Math.trunc(e)||0;if(s>sa)throw new RangeError("stable-key: array length exceeds 2**32 - 1");return s},"d"),Ee=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 s=ia(t);if(s!==void 0)return s}if(typeof t=="string")return qs(t);if(t===null||typeof t!="object")return JSON.stringify(t);let e=$e(t);if(e==="array"){let s=aa(t),r="[";for(let i=0;i<s;i+=1)i>0&&(r+=","),r+=Ee(t[i]);return`${r}]`}if(e!=="plain"){let s=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${s} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}return na(t,Ee)},"c");var Mt=a(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"e");var ze=a(t=>{let e="";for(let s=0;s<t.length;s+=32768)e+=String.fromCharCode(...t.subarray(s,s+32768));return btoa(e)},"u"),oa=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},"R"),A="$lunora.wire$",Ge=64,Ve=1024,ca="__proto__",ha=/^-?\d+$/,Bs={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},Ws={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},xt=a((t,e,s)=>{e===ca?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:s,writable:!0}):t[e]=s},"b");var da=a(t=>{let e=t.toString();if(e.length>Ve)throw new RangeError(`wire-codec: over-long bigint (max ${String(Ve)} digits)`);return[A,"bigint",e]},"B"),ua=a(t=>Number.isNaN(t)?[A,"nan"]:t===1/0?[A,"inf"]:t===-1/0?[A,"-inf"]:t,"_"),la=a((t,e)=>{let s=e(Object.fromEntries(Object.keys(t).map(n=>[n,t[n]]))),r=t,i=[A,"error",String(r.name),String(r.message),s];return t.cause!==void 0&&i.push(e(t.cause)),i},"P"),pa=a(t=>{let e=t.constructor.name,s=js(t);return e==="Uint8Array"?[A,"bytes",ze(s)]:[A,"bytes",ze(s),e]},"$"),fa=a((t,e,s)=>{switch(e){case"builtin-array-buffer":return[A,"bytes",ze(new Uint8Array(t)),"ArrayBuffer"];case"builtin-date":return[A,"date",s(Us(t))];case"builtin-error":return la(t,s);case"builtin-map":return[A,"map",Ns(t).map(([r,i])=>[s(r),s(i)])];case"builtin-set":return[A,"set",Ks(t).map(r=>s(r))];case"builtin-url":return[A,"url",Hs(t)];case"builtin-view":return pa(t);default:return}},"k"),ma=a((t,e)=>{let s=t.map(r=>N(r,e));return s.length>0&&s[0]===A?[A,"arr",s]:s},"D"),ya=a((t,e)=>{let s={};for(let r of Object.keys(t)){let i=t[r];i!==void 0&&xt(s,r,N(i,e))}return s},"C"),N=a((t,e=0)=>{if(e>Ge)throw new RangeError(`wire-codec: value nesting exceeds the ${String(Ge)}-level limit`);if(t===void 0)return[A,"undefined"];if(t===null)return t;if(typeof t=="bigint")return da(t);if(typeof t=="number")return ua(t);if(typeof t!="object")return t;let s=$e(t);if(s==="array")return ma(t,e+1);if(s==="plain")return ya(t,e+1);let r=fa(t,s,n=>N(n,e+1));if(r!==void 0)return r;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`)},"y"),va=a(t=>{let e=t[2];if(typeof e!="string"||e.length>Ve||!ha.test(e))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${String(Ve)} digits)`);return BigInt(e)},"M"),ga=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)},"F"),ba=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])]}))},"G"),wa=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)},"L"),Sa=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(Ws,s)?Ws[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,h]of Object.entries(o))xt(n,c,h);return t.length>5&&Object.defineProperty(n,"cause",{configurable:!0,value:e(t[5]),writable:!0}),n},"W"),Ca=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=oa(e);if(ze(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(Bs,r)?Bs[r]:void 0;return i?new i(new Uint8Array(s).buffer):s},"v"),ka=a((t,e)=>{switch(t[1]){case"-inf":return-1/0;case"arr":return t[2].map(s=>e(s));case"bigint":return va(t);case"bytes":return Ca(t);case"date":return ga(t,e);case"error":return Sa(t,e);case"inf":return 1/0;case"map":return ba(t,e);case"nan":return Number.NaN;case"set":return new Set(t[2].map(s=>e(s)));case"undefined":return;case"url":return wa(t);default:return t.map(s=>e(s))}},"Y"),Ta=a((t,e)=>{let s={};for(let r of Object.keys(t))xt(s,r,T(t[r],e));return s},"H"),T=a((t,e=0)=>{if(e>Ge)throw new RangeError(`wire-codec: value nesting exceeds the ${String(Ge)}-level limit`);if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let s=t;return s[0]===A?ka(s,r=>T(r,e+1)):s.map(r=>T(r,e+1))}return Ta(t,e+1)},"f"),$s=a(t=>{let e=JSON.parse(t);return t.includes(A)||t.includes(String.raw`\u`)?T(e):e},"J"),Oa=a(t=>{try{let e=$s(t);return Mt(e)?e:void 0}catch{return}},"X");var q=a(t=>Ee(N(t)),"a");var ue=H(ie(),1),zs=H(At(),1);var Ie=ue.createContext(void 0),Re=a(t=>{let e=ue.useContext(Ie);if(t)return t;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},"useQueryClient"),_t=a(({client:t,children:e})=>(ue.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,zs.jsx)(Ie.Provider,{value:t,children:e})),"QueryClientProvider");var j=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 Ea=class extends j{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"}},le=new Ea;var Ia={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")},Ra=class{static{a(this,"TimeoutManager")}#e=Ia;#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)}},J=new Ra;function Gs(t){setTimeout(t,0)}a(Gs,"systemSetTimeoutZero");var Dt=typeof window>"u"||"Deno"in globalThis;function O(){}a(O,"noop");function Ys(t,e){return typeof t=="function"?t(e):t}a(Ys,"functionalUpdate");function Ae(t){return typeof t=="number"&&t>=0&&t!==1/0}a(Ae,"isValidTimeout");function Je(t,e){return Math.max(t+(e||0)-Date.now(),0)}a(Je,"timeUntilStale");function B(t,e){return typeof t=="function"?t(e):t}a(B,"resolveStaleTime");function x(t,e){return typeof t=="function"?t(e):t}a(x,"resolveQueryBoolean");function Ye(t,e){let{type:s="all",exact:r,fetchStatus:i,predicate:n,queryKey:o,stale:c}=t;if(o){if(r){if(e.queryHash!==Fe(o,e.options))return!1}else if(!ne(e.queryKey,o))return!1}if(s!=="all"){let h=e.isActive();if(s==="active"&&!h||s==="inactive"&&h)return!1}return!(typeof c=="boolean"&&e.isStale()!==c||i&&i!==e.state.fetchStatus||n&&!n(e))}a(Ye,"matchQuery");function Xe(t,e){let{exact:s,status:r,predicate:i,mutationKey:n}=t;if(n){if(!e.options.mutationKey)return!1;if(s){if(Y(e.options.mutationKey)!==Y(n))return!1}else if(!ne(e.options.mutationKey,n))return!1}return!(r&&e.state.status!==r||i&&!i(e))}a(Xe,"matchMutation");function Fe(t,e){return(e?.queryKeyHashFn||Y)(t)}a(Fe,"hashQueryKeyByOptions");function Y(t){return JSON.stringify(t,(e,s)=>Qt(s)?Object.keys(s).sort().reduce((r,i)=>(r[i]=s[i],r),{}):s)}a(Y,"hashKey");function ne(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(!ne(t[r],e[r]))return!1;return!0}let s=Object.keys(e);for(let r of s)if(!ne(t[r],e[r]))return!1;return!0}return!1}a(ne,"partialMatchKey");var Aa=Object.prototype.hasOwnProperty;function Ut(t,e,s=0){if(t===e)return t;if(s>500)return e;let r=Vs(t)&&Vs(e);if(!r&&!(Qt(t)&&Qt(e)))return e;let n=(r?t:Object.keys(t)).length,o=r?e:Object.keys(e),c=o.length,h=r?new Array(c):{},u=0;for(let d=0;d<c;d++){let p=r?d:o[d],l=t[p],f=e[p];if(l===f){h[p]=l,(r?d<n:Aa.call(t,p))&&u++;continue}if(l===null||f===null||typeof l!="object"||typeof f!="object"){h[p]=f;continue}let y=Ut(l,f,s+1);h[p]=y,y===l&&u++}return n===c&&u===n?t:h}a(Ut,"replaceEqualDeep");function pe(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(pe,"shallowEqualObjects");function Vs(t){return Array.isArray(t)&&t.length===Object.keys(t).length}a(Vs,"isPlainArray");function Qt(t){if(!Js(t))return!1;let e=t.constructor;if(e===void 0)return!0;let s=e.prototype;return!(!Js(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}a(Qt,"isPlainObject");function Js(t){return Object.prototype.toString.call(t)==="[object Object]"}a(Js,"hasObjectPrototype");function Xs(t){return new Promise(e=>{J.setTimeout(e,t)})}a(Xs,"sleep");function Pe(t,e,s){return typeof s.structuralSharing=="function"?s.structuralSharing(t,e):s.structuralSharing!==!1?Ut(t,e):e}a(Pe,"replaceData");function Fa(t){return t}a(Fa,"keepPreviousData");function Zs(t,e,s=0){let r=[...t,e];return s&&r.length>s?r.slice(1):r}a(Zs,"addToEnd");function er(t,e,s=0){let r=[e,...t];return s&&r.length>s?r.slice(0,-1):r}a(er,"addToStart");var fe=Symbol();function Ze(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===fe?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}a(Ze,"ensureQueryFn");function me(t,e){return typeof t=="function"?t(...e):!!t}a(me,"shouldThrowError");function tr(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(tr,"addConsumeAwareSignal");var X=(()=>{let t=a(()=>Dt,"isServerFn");return{isServer(){return t()},setIsServer(e){t=e}}})();function Le(){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(Le,"pendingThenable");var sr=Gs;function Pa(){let t=[],e=0,s=a(c=>{c()},"notifyFn"),r=a(c=>{c()},"batchNotifyFn"),i=sr,n=a(c=>{e?t.push(c):i(()=>{s(c)})},"schedule"),o=a(()=>{let c=t;t=[],c.length&&i(()=>{r(()=>{c.forEach(h=>{s(h)})})})},"flush");return{batch:a(c=>{let h;e++;try{h=c()}finally{e--,e||o()}return h},"batch"),batchCalls:a(c=>(...h)=>{n(()=>{c(...h)})},"batchCalls"),schedule:n,setNotifyFunction:a(c=>{s=c},"setNotifyFunction"),setBatchNotifyFunction:a(c=>{r=c},"setBatchNotifyFunction"),setScheduler:a(c=>{i=c},"setScheduler")}}a(Pa,"createNotifyManager");var C=Pa();var La=class extends j{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}},ye=new La;function Ma(t){return Math.min(1e3*2**t,3e4)}a(Ma,"defaultRetryDelay");function Ht(t){return(t??"online")==="online"?ye.isOnline():!0}a(Ht,"canFetch");var et=class extends Error{static{a(this,"CancelledError")}constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function tt(t){let e=!1,s=0,r,i=Le(),n=a(()=>i.status!=="pending","isResolved"),o=a(m=>{if(!n()){let w=new et(m);l(w),t.onCancel?.(w)}},"cancel"),c=a(()=>{e=!0},"cancelRetry"),h=a(()=>{e=!1},"continueRetry"),u=a(()=>le.isFocused()&&(t.networkMode==="always"||ye.isOnline())&&t.canRun(),"canContinue"),d=a(()=>Ht(t.networkMode)&&t.canRun(),"canStart"),p=a(m=>{n()||(r?.(),i.resolve(m))},"resolve"),l=a(m=>{n()||(r?.(),i.reject(m))},"reject"),f=a(()=>new Promise(m=>{r=a(w=>{(n()||u())&&m(w)},"continueFn"),t.onPause?.()}).then(()=>{r=void 0,n()||t.onContinue?.()}),"pause"),y=a(()=>{if(n())return;let m,w=s===0?t.initialPromise:void 0;try{m=w??t.fn()}catch(g){m=Promise.reject(g)}Promise.resolve(m).then(p).catch(g=>{if(n())return;let k=t.retry??(X.isServer()?0:3),E=t.retryDelay??Ma,S=typeof E=="function"?E(s,g):E,I=k===!0||typeof k=="number"&&s<k||typeof k=="function"&&k(s,g);if(e||!I){l(g);return}s++,t.onFail?.(s,g),Xs(S).then(()=>u()?void 0:f()).then(()=>{e?l(g):y()})})},"run");return{promise:i,status:a(()=>i.status,"status"),cancel:o,continue:a(()=>(r?.(),i),"continue"),cancelRetry:c,continueRetry:h,canStart:d,start:a(()=>(d()?y():f().then(y),i),"start")}}a(tt,"createRetryer");var st=class{static{a(this,"Removable")}#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ae(this.gcTime)&&(this.#e=J.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(X.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(J.clearTimeout(this.#e),this.#e=void 0)}};function ir(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:[]},h=0,u=a(async()=>{let d=!1,p=a(y=>{tr(y,()=>e.signal,()=>d=!0)},"addSignalProperty"),l=Ze(e.options,e.fetchOptions),f=a(async(y,m,w)=>{if(d)return Promise.reject(e.signal.reason);if(m==null&&y.pages.length)return Promise.resolve(y);let k=a(()=>{let re={client:e.client,queryKey:e.queryKey,pageParam:m,direction:w?"backward":"forward",meta:e.options.meta};return p(re),re},"createQueryFnContext")(),E=await l(k),{maxPages:S}=e.options,I=w?er:Zs;return{pages:I(y.pages,E,S),pageParams:I(y.pageParams,m,S)}},"fetchPage");if(i&&n.length){let y=i==="backward",m=y?xa:rr,w={pages:n,pageParams:o},g=m(r,w);c=await f(w,g,y)}else{let y=t??n.length;do{let m=h===0?o[0]??r.initialPageParam:rr(r,c);if(h>0&&m==null)break;c=await f(c,m),h++}while(h<y)}return c},"fetchFn");e.options.persister?e.fetchFn=()=>e.options.persister?.(u,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},s):e.fetchFn=u},"onFetch")}}a(ir,"infiniteQueryBehavior");function rr(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(rr,"getNextPageParam");function xa(t,{pages:e,pageParams:s}){return e.length>0?t.getPreviousPageParam?.(e[0],e,s[0],s):void 0}a(xa,"getPreviousPageParam");var or=class extends st{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=ar(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=ar(this.options);e.data!==void 0&&(this.setState(nr(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#r.remove(this)}setData(t,e){let s=Pe(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(O).catch(O):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===fe||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>B(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.#d()?this.#i.cancel({revert:!0}):this.#i.cancelRetry()),this.scheduleGc()),this.#r.notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}#d(){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 h=this.observers.find(u=>u.options.queryFn);h&&this.setOptions(h.options)}let s=new AbortController,r=a(h=>{Object.defineProperty(h,"signal",{enumerable:!0,get:a(()=>(this.#a=!0,s.signal),"get")})},"addSignalProperty"),i=a(()=>{let h=Ze(this.options,e),d=a(()=>{let p={client:this.#n,queryKey:this.queryKey,meta:this.meta};return r(p),p},"createQueryFnContext")();return this.#a=!1,this.options.persister?this.options.persister(h,d,this):h(d)},"fetchFn"),o=a(()=>{let h={fetchOptions:e,options:this.options,queryKey:this.queryKey,client:this.#n,state:this.state,fetchFn:i};return r(h),h},"createFetchContext")();(this.#e==="infinite"?ir(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=tt({initialPromise:e?.initialPromise,fn:o.fetchFn,onCancel:a(h=>{h instanceof et&&h.revert&&this.setState({...this.#s,fetchStatus:"idle"}),s.abort()},"onCancel"),onFail:a((h,u)=>{this.#c({type:"failed",failureCount:h,error:u})},"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 h=await this.#i.start();if(h===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(h),this.#r.config.onSuccess?.(h,this),this.#r.config.onSettled?.(h,this.state.error,this),h}catch(h){if(h instanceof et){if(h.silent)return this.#i.promise;if(h.revert){if(this.state.data===void 0)throw h;return this.state.data}}throw this.#c({type:"error",error:h}),this.#r.config.onError?.(h,this),this.#r.config.onSettled?.(this.state.data,h,this),h}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,...Nt(s.data,this.options),fetchMeta:t.meta??null};case"success":let r={...s,...nr(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 Nt(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Ht(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}a(Nt,"fetchState");function nr(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}a(nr,"successState");function ar(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(ar,"getDefaultState");var jt=class extends j{static{a(this,"QueryObserver")}constructor(t,e){super(),this.options=e,this.#e=t,this.#a=null,this.#o=Le(),this.bindMethods(),this.setOptions(e)}#e;#t=void 0;#s=void 0;#r=void 0;#n;#i;#o;#a;#d;#c;#f;#u;#l;#h;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),cr(this.#t,this.options)?this.#p():this.updateResult(),this.#b())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Kt(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Kt(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#w(),this.#S(),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&&!pe(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});let r=this.hasListeners();r&&hr(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)||B(this.options.staleTime,this.#t)!==B(e.staleTime,this.#t))&&this.#y();let i=this.#v();r&&(this.#t!==s||x(this.options.enabled,this.#t)!==x(e.enabled,this.#t)||i!==this.#h)&&this.#g(i)}getOptimisticResult(t){let e=this.#e.getQueryCache().build(this.#e,t),s=this.createResult(e,t);return Qa(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(O)),e}#y(){this.#w();let t=B(this.options.staleTime,this.#t);if(X.isServer()||this.#r.isStale||!Ae(t))return;let s=Je(this.#r.dataUpdatedAt,t)+1;this.#u=J.setTimeout(()=>{this.#r.isStale||this.updateResult()},s)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#g(t){this.#S(),this.#h=t,!(X.isServer()||x(this.options.enabled,this.#t)===!1||!Ae(this.#h)||this.#h===0)&&(this.#l=J.setInterval(()=>{(this.options.refetchIntervalInBackground||le.isFocused())&&this.#p()},this.#h))}#b(){this.#y(),this.#g(this.#v())}#w(){this.#u!==void 0&&(J.clearTimeout(this.#u),this.#u=void 0)}#S(){this.#l!==void 0&&(J.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,h=t!==s?t.state:this.#s,{state:u}=t,d={...u},p=!1,l;if(e._optimisticResults){let P=this.hasListeners(),R=!P&&cr(t,e),Z=P&&hr(t,s,e,r);(R||Z)&&(d={...d,...Nt(u.data,t.options)}),e._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:f,errorUpdatedAt:y,status:m}=d;l=d.data;let w=!1;if(e.placeholderData!==void 0&&l===void 0&&m==="pending"){let P;i?.isPlaceholderData&&e.placeholderData===o?.placeholderData?(P=i.data,w=!0):P=typeof e.placeholderData=="function"?e.placeholderData(this.#f?.state.data,this.#f):e.placeholderData,P!==void 0&&(m="success",l=Pe(i?.data,P,e),p=!0)}if(e.select&&l!==void 0&&!w)if(i&&l===n?.data&&e.select===this.#d)l=this.#c;else try{this.#d=e.select,l=e.select(l),l=Pe(i?.data,l,e),this.#c=l,this.#a=null}catch(P){this.#a=P}this.#a&&(f=this.#a,l=this.#c,y=Date.now(),m="error");let g=d.fetchStatus==="fetching",k=m==="pending",E=m==="error",S=k&&g,I=l!==void 0,M={status:m,fetchStatus:d.fetchStatus,isPending:k,isSuccess:m==="success",isError:E,isInitialLoading:S,isLoading:S,data:l,dataUpdatedAt:d.dataUpdatedAt,error:f,errorUpdatedAt:y,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:d.dataUpdateCount>h.dataUpdateCount||d.errorUpdateCount>h.errorUpdateCount,isFetching:g,isRefetching:g&&!k,isLoadingError:E&&!I,isPaused:d.fetchStatus==="paused",isPlaceholderData:p,isRefetchError:E&&I,isStale:qt(t,e),refetch:this.refetch,promise:this.#o,isEnabled:x(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let P=M.data!==void 0,R=M.status==="error"&&!P,Z=a(We=>{R?We.reject(M.error):P&&We.resolve(M.data)},"finalizeThenableIfPossible"),Fs=a(()=>{let We=this.#o=M.promise=Le();Z(We)},"recreateThenable"),Be=this.#o;switch(Be.status){case"pending":t.queryHash===s.queryHash&&Z(Be);break;case"fulfilled":(R||M.data!==Be.value)&&Fs();break;case"rejected":(!R||M.error!==Be.reason)&&Fs();break}}return M}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),pe(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 _a(t,e){return x(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&x(e.retryOnMount,t)===!1)}a(_a,"shouldLoadOnMount");function cr(t,e){return _a(t,e)||t.state.data!==void 0&&Kt(t,e,e.refetchOnMount)}a(cr,"shouldFetchOnMount");function Kt(t,e,s){if(x(e.enabled,t)!==!1&&B(e.staleTime,t)!=="static"){let r=typeof s=="function"?s(t):s;return r==="always"||r!==!1&&qt(t,e)}return!1}a(Kt,"shouldFetchOn");function hr(t,e,s,r){return(t!==e||x(r.enabled,t)===!1)&&(!s.suspense||t.state.status!=="error")&&qt(t,s)}a(hr,"shouldFetchOptionally");function qt(t,e){return x(e.enabled,t)!==!1&&t.isStaleByTime(B(e.staleTime,t))}a(qt,"isStale");function Qa(t,e){return!pe(t.getCurrentResult(),e)}a(Qa,"shouldAssignObserverCurrentProperties");var dr=class extends st{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||Bt(),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=tt({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 Bt(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}a(Bt,"getDefaultState");var ur=class extends j{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 dr({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=rt(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=rt(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=rt(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=rt(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=>Xe(e,s))}findAll(t={}){return this.getAll().filter(e=>Xe(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(O))))}};function rt(t){return t.options.scope?.id}a(rt,"scopeFor");var Wt=class extends j{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),pe(this.options,e)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#s,observer:this}),e?.mutationKey&&this.options.mutationKey&&Y(e.mutationKey)!==Y(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??Bt();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 lr=class extends j{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??Fe(r,e),n=this.get(i);return n||(n=new or({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=>Ye(e,s))}findAll(t={}){let e=this.getAll();return Object.keys(t).length>0?e.filter(s=>Ye(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 $t=class{static{a(this,"QueryClient")}#e;#t;#s;#r;#n;#i;#o;#a;constructor(t={}){this.#e=t.queryCache||new lr,this.#t=t.mutationCache||new ur,this.#s=t.defaultOptions||{},this.#r=new Map,this.#n=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#o=le.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#a=ye.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(B(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=Ys(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(O).catch(O)}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(O)),i.state.fetchStatus==="paused"?Promise.resolve():n}));return Promise.all(r).then(O)}fetchQuery(t){let e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);let s=this.#e.build(this,e);return s.isStaleByTime(B(e.staleTime,s))?s.fetch(e):Promise.resolve(s.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(O).catch(O)}fetchInfiniteQuery(t){return t._type="infinite",this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(O).catch(O)}ensureInfiniteQueryData(t){return t._type="infinite",this.ensureQueryData(t)}resumePausedMutations(){return ye.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(Y(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){let e=[...this.#r.values()],s={};return e.forEach(r=>{ne(t,r.queryKey)&&Object.assign(s,r.defaultOptions)}),s}setMutationDefaults(t,e){this.#n.set(Y(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){let e=[...this.#n.values()],s={};return e.forEach(r=>{ne(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=Fe(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===fe&&(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 ae=H(ie(),1);var Me=H(ie(),1),Da=H(At(),1);function Ua(){let t=!1;return{clearReset:a(()=>{t=!1},"clearReset"),reset:a(()=>{t=!0},"reset"),isReset:a(()=>t,"isReset")}}a(Ua,"createValue");var Ha=Me.createContext(Ua()),pr=a(()=>Me.useContext(Ha),"useQueryErrorResetBoundary");var fr=H(ie(),1);var mr=a((t,e,s)=>{let r=s?.state.error&&typeof t.throwOnError=="function"?me(t.throwOnError,[s.state.error,s]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||r)&&(e.isReset()||(t.retryOnMount=!1))},"ensurePreventErrorBoundaryRetry"),yr=a(t=>{fr.useEffect(()=>{t.clearReset()},[t])},"useClearResetErrorBoundary"),vr=a(({result:t,errorResetBoundary:e,throwOnError:s,query:r,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&r&&(i&&t.data===void 0||me(s,[t.error,r])),"getHasError");var it=H(ie(),1);var gr=it.createContext(!1),br=a(()=>it.useContext(gr),"useIsRestoring"),ol=gr.Provider;var wr=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"),Sr=a((t,e)=>t.isLoading&&t.isFetching&&!e,"willFetch"),Cr=a((t,e)=>t?.suspense&&e.isPending,"shouldSuspend"),zt=a((t,e,s)=>e.fetchOptimistic(t).catch(()=>{s.clearReset()}),"fetchOptimistic");function kr(t,e,s){let r=br(),i=pr(),n=Re(s),o=n.defaultQueryOptions(t);n.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let c=n.getQueryCache().get(o.queryHash),h=t.subscribed!==!1;o._optimisticResults=r?"isRestoring":h?"optimistic":void 0,wr(o),mr(o,i,c),yr(i);let u=!n.getQueryCache().get(o.queryHash),[d]=ae.useState(()=>new e(n,o)),p=d.getOptimisticResult(o),l=!r&&h;if(ae.useSyncExternalStore(ae.useCallback(f=>{let y=l?d.subscribe(C.batchCalls(f)):O;return d.updateResult(),y},[d,l]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),ae.useEffect(()=>{d.setOptions(o)},[o,d]),Cr(o,p))throw zt(o,d,i);if(vr({result:p,errorResetBoundary:i,throwOnError:o.throwOnError,query:c,suspense:o.suspense}))throw p.error;return n.getDefaultOptions().queries?._experimental_afterQuery?.(o,p),o.experimental_prefetchInRender&&!X.isServer()&&Sr(p,r)&&(u?zt(o,d,i):c?.promise)?.catch(O).finally(()=>{d.updateResult()}),o.notifyOnChangeProps?p:d.trackResult(p)}a(kr,"useBaseQuery");function Na(t,e){return kr(t,jt,e)}a(Na,"useQuery");var ee=H(ie(),1);function Ka(t,e){let s=Re(e),[r]=ee.useState(()=>new Wt(s,t));ee.useEffect(()=>{r.setOptions(t)},[r,t]);let i=ee.useSyncExternalStore(ee.useCallback(o=>r.subscribe(C.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),n=ee.useCallback((o,c)=>{r.mutate(o,c).catch(O)},[r]);if(i.error&&me(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:n,mutateAsync:i.mutate}}a(Ka,"useMutation");var Ir=H(xs(),1);var _=H(ie(),1);var ot=H(At(),1);var nt=a(t=>q(t),"w");var Tr=a(t=>{t!==void 0&&(t.cancel({silent:!0}),t.setState({...t.state,data:void 0,dataUpdatedAt:0,error:null,fetchStatus:"idle",status:"pending"}))},"T"),at={status:"idle"},Or=a((t,e)=>{for(let s of t.waiters)s(e);t.waiters.clear()},"E"),ja=1e4,qa=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(u),e.removeEventListener("abort",h)},"l"),h=a(()=>{c(),i(e.reason)},"s"),u=a(d=>{c(),r(d)},"n");n=setTimeout(()=>{u(!1)},ja),t.waiters.add(u),e.addEventListener("abort",h,{once:!0}),o=s(()=>{u(!1)}),t.waiters.has(u)||o()}),"U"),Vt=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(nt(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 h=nt(s),u=this.liveFor(h),d=u.state.status==="pushed"?e.getQueryData(s)??u.state.value:void 0;if(d!==void 0)return d;if(c&&u.state.status!=="errored"&&!this.client.isCrossTabFollower()&&this.client.expectsPush({shardKey:o})){let f;try{f=await qa(u,r,y=>this.client.onConnectionStatus(()=>{this.client.expectsPush({shardKey:o})||y()}))}finally{this.forgetIdleLive(h)}if(f)return this.liveValue(e,s,r,i)}let p=u.state,l;try{l=await n()}finally{this.forgetIdleLive(h)}if(u.state!==p&&u.state.status==="pushed"){let f=e.getQueryData(s);return f!==void 0?f:u.state.value}return l}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"]}))Tr(r),r.getObserversCount()===0&&!this.hasConsumers(r.queryKey)&&s.remove(r)}attach(e,s,r,i,n,o={}){let c=nt(s),h=this.entries.get(c);if(!h){h={clients:new Map([[e,0]]),errorCallbacks:new Set,unsubscribe:void 0},this.entries.set(c,h);let l=h;try{h.unsubscribe=this.client.subscribe(r,i,f=>{let y=this.liveFor(c);if(f===void 0){y.state=at;for(let m of l.clients.keys())Tr(m.getQueryCache().find({exact:!0,queryKey:s}));return}for(let m of l.clients.keys())m.setQueryData(s,f);y.state={status:"pushed",value:f},Or(y,!0)},{onError:a(f=>{let y=this.liveFor(c);y.state.status!=="pushed"&&(y.state={status:"errored"},Or(y,!1));for(let m of l.errorCallbacks)m(f)},"onError"),shardKey:n})}catch(f){throw this.entries.delete(c),this.dropLive(c),f}}h.clients.set(e,(h.clients.get(e)??0)+1);let u=this.live.get(c);u?.state.status==="pushed"&&e.setQueryData(s,u.state.value);let{onError:d}=o;d&&h.errorCallbacks.add(d);let p=!1;return()=>{if(p)return;p=!0;let l=this.entries.get(c);if(!l)return;let f=(l.clients.get(e)??1)-1;f>0?l.clients.set(e,f):l.clients.delete(e),d&&l.errorCallbacks.delete(d),l.clients.size===0&&(l.unsubscribe?.(),this.entries.delete(c),this.dropLive(c))}}awaitFreshPush(e){let s=this.live.get(nt(e));s?.state.status==="pushed"&&(s.state=at)}liveFor(e){let s=this.live.get(e);return s||(s={state:at,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=at)}},Er=new WeakMap,Gt=a(t=>{let e=Er.get(t);return e||(e=new Vt(t),Er.set(t,e)),e},"L"),Rr=(0,_.createContext)(null),Ba=(0,_.createContext)(!1),Wa=a(()=>new $t({defaultOptions:{mutations:{retry:0},queries:{gcTime:5*6e4,retry:0,staleTime:Number.POSITIVE_INFINITY}}}),"B"),$a=a(t=>{let e=(0,Ir.c)(20),{children:s,client:r,queryClient:i}=t,n=(0,_.use)(Ie),o;e[0]!==n||e[1]!==i?(o=a(()=>i??n??Wa(),"h"),e[0]=n,e[1]=i,e[2]=o):o=e[2];let[c]=(0,_.useState)(o),h=i??n??c,u,d;e[3]!==r||e[4]!==h?(u=a(()=>{Gt(r).clearOnIdentityChange(h)},"n"),d=[r,h],e[3]=r,e[4]=h,e[5]=u,e[6]=d):(u=e[5],d=e[6]),(0,_.useEffect)(u,d);let p=(0,_.useRef)(r),l,f;e[7]!==r||e[8]!==h?(l=a(()=>{p.current!==r&&(Gt(p.current).stopClearingOnIdentityChange(h),p.current=r,Gt(r).clearQueries(h),h.invalidateQueries({queryKey:["lunora"]}))},"o"),f=[r,h],e[7]=r,e[8]=h,e[9]=l,e[10]=f):(l=e[9],f=e[10]),(0,_.useEffect)(l,f);let[y]=(0,_.useState)(r),m=r!==y,w;e[11]!==s||e[12]!==m?(w=(0,ot.jsx)(Ba,{value:m,children:s}),e[11]=s,e[12]=m,e[13]=w):w=e[13];let g;e[14]!==r||e[15]!==w?(g=(0,ot.jsx)(Rr,{value:r,children:w}),e[14]=r,e[15]=w,e[16]=g):g=e[16];let k=g;if(n===h)return k;let E;return e[17]!==k||e[18]!==h?(E=(0,ot.jsx)(_t,{client:h,children:k}),e[17]=k,e[18]=h,e[19]=E):E=e[19],E},"X");var xe=a(()=>{let t=(0,_.use)(Rr);if(!t)throw new v("INTERNAL","useLunora must be used inside <LunoraProvider />");return t},"q");var Q=a(t=>new Promise((e,s)=>{t.addEventListener("success",()=>{e(t.result)}),t.addEventListener("error",()=>{s(t.error??new Error("IndexedDB request failed"))})}),"c"),ct=a((t,e,s,r)=>{let i;return()=>{if(i)return i;let n=new Promise((o,c)=>{let h=t.open(e,s);h.addEventListener("upgradeneeded",()=>{r(h.result)}),h.addEventListener("success",()=>{o(h.result)}),h.addEventListener("error",()=>{c(h.error??new Error("IndexedDB open failed"))})});return i=n,n.catch(()=>{i===n&&(i=void 0)}),n}},"E"),ht=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 ce=a((t,e,s)=>`${t}::${e}::${s??""}`,"T"),za=500,Ga=a((t,e)=>{if(!Number.isInteger(t)||t<1)throw new v("INTERNAL",`${e}: maxEntries must be a positive integer, got ${String(t)}`);return t},"E");var Va="lunora-query-cache",Ja="query-cache",Ar="by_ts",Ya=1,Xa=a((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new v("INTERNAL","createIndexedDbQueryCache: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryQueryCache()");let s=t.databaseName??Va,r=t.storeName??Ja,i=Ga(t.maxEntries??za,"createIndexedDbQueryCache"),n=ct(e,s,Ya,h=>{h.objectStoreNames.contains(r)||h.createObjectStore(r,{keyPath:"key"}).createIndex(Ar,"ts",{unique:!1})}),o=ht(n,r),c=a(async h=>{let u=await Q(h.count())-i;u<=0||await new Promise((d,p)=>{let l=h.index(Ar).openCursor();l.addEventListener("success",()=>{let f=l.result;if(!f||u<=0){d();return}f.delete(),u-=1,f.continue()}),l.addEventListener("error",()=>{p(l.error??new Error("IndexedDB eviction failed"))})})},"y");return{clear:a(async()=>{await o("readwrite",h=>Q(h.clear()))},"clear"),load:a(async()=>o("readonly",h=>Q(h.getAll())),"load"),put:a(async(h,u)=>{await o("readwrite",async d=>{await Q(d.put({...u,key:h})),await c(d)})},"put"),remove:a(async h=>{await o("readwrite",u=>Q(u.delete(h)))},"remove")}},"N"),Fr=a(t=>{if(t!==!1){if(t)return t;if(!(typeof indexedDB>"u"))return Xa()}},"L");var te="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Jt=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+=te.charAt(n>>18&63)+te.charAt(n>>12&63)+te.charAt(n>>6&63)+te.charAt(n&63)}let i=t.length-s;if(i===1){let n=t[s]<<16;e+=te.charAt(n>>18&63)+te.charAt(n>>12&63)}else if(i===2){let n=t[s]<<16|t[s+1]<<8;e+=te.charAt(n>>18&63)+te.charAt(n>>12&63)+te.charAt(n>>6&63)}return e},"A");var Pr=a(()=>{let t=null;return{get:a(()=>t,"get"),set:a(e=>{t=e},"set")}},"r");var dt=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 Yt=0,ve,Lr=a((t,e)=>{for(let s of t)try{s(e)}catch{}},"f"),Za=a(t=>{let e=[...t.callbacks],s=t.lastValue;return()=>{for(let r of e){if(t.lastValue!==s)return;t.callbacks.has(r)&&Lr([r],s)}}},"p"),Mr=a(t=>{ve===void 0?t():ve.add(t)},"k"),xr=a(()=>Yt,"L"),eo=a((t,e)=>{let s=t;for(let r of e)try{s=r.transform(s)}catch{}return s},"y"),_r=a((t,e)=>{e!==t.lastValue&&(t.lastValue=e,ve===void 0?Lr(t.callbacks,e):ve.add(t))},"d"),ut=a((t,e=()=>!0)=>{let s=new Set;ve=s;try{t()}finally{ve=void 0;let r=[...s].map(i=>typeof i=="function"?i:Za(i));for(let i of r){if(!e())break;try{i()}catch{}}}},"v"),W=a((t,e)=>{_r(t,eo(e,t.optimisticLayers))},"m"),lt=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),_r(t,s);let n=a(()=>{let c=t.optimisticLayers.findIndex(h=>h.id===r.id);return c===-1?!1:(t.optimisticLayers.splice(c,1),!0)},"s"),o=a(()=>{W(t,t.serverBase)},"a");return{confirm:a(c=>{if(c===void 0){n();return}r.commitCursor=c,Yt+=1,r.acknowledgedAt=Yt,t.serverCursor!==void 0&&t.serverCursor>=c&&n()&&o()},"confirm"),rollback:a(()=>{i||(i=!0,n(),o())},"rollback")}},"b"),pt=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},"h"),Qr=a((t,e)=>{t.optimisticLayers.length!==0&&(t.optimisticLayers=t.optimisticLayers.filter(s=>s.acknowledgedAt===void 0||s.acknowledgedAt>e))},"g"),he=a(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"w");var Dr=0,to="lunora-bridge",so=1e3,ro=3e3,ft=class{static{a(this,"p")}bc;tabId;heartbeatInterval;leaderTimeout;knownLeader=void 0;leader=!1;running=!1;promotionPending=!1;lastHeartbeat=0;pendingData=new Map;heldData=new Map;heartbeatTimer=void 0;leaderCheckTimer=void 0;onBecomeLeader;onStopBeingLeader;onConnectionStatus;onSubscriptionData;onLeaderClaimAnswered;onSubscriptionError;onSubscriptionSettled;constructor(e={}){if(Dr+=1,this.tabId=`tab_${String(Dr)}_${crypto.randomUUID()}`,this.heartbeatInterval=e.heartbeatInterval??so,this.leaderTimeout=e.leaderTimeout??ro,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??to),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,o){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},...o===void 0?{}:{claims:o}}))}broadcastSubscriptionError(e,s,r,i){this.leader&&this.broadcast({type:"subscription-error",tabId:this.tabId,key:e,error:s,...r===void 0?{}:{identity:r},...i===void 0?{}:{claims:i}})}broadcastSubscriptionSettled(e,s,r,i,n,o,c){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},...c===void 0?{}:{claims:c}})}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)return;let s,r=!0;for(let[i,n]of e.entries()){let o=i<e.length-1;try{this.bc?.postMessage(o?{...n,more:!0}:n),s=n,r=!o}catch{}}!r&&s!==void 0&&this.bc?.postMessage(s)}applySubscriptionData(e){let s=this.heldData.get(e.tabId)??[];if(s.push(e),e.more===!0){this.heldData.set(e.tabId,s);return}this.heldData.delete(e.tabId),ut(()=>{for(let r of s)this.onSubscriptionData?.(r.key,r.data,r.cursor,r.epoch,r.identity,r.claims)},()=>this.running)}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.applySubscriptionData(e);break}case"subscription-error":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionError?.(e.key,e.error,e.identity,e.claims);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,e.claims);break}case"yield-leadership":{this.heldData.delete(e.tabId),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.heldData.delete(this.knownLeader),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 io=a(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"l"),no="_id",Xt="_creationTime",Zt="page",Ur="pageDelta",ao=a(t=>{if(Array.isArray(t))return t;if(io(t)&&Array.isArray(t[Zt]))return t[Zt]},"y"),oo=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},"g"),co=a((t,e)=>{let s=e[Xt];if(typeof s!="number")return t.length;let r=oo(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},"A"),ho=a(t=>{if(typeof t!="object"||t===null)return;let e=t[no];return typeof e=="string"?e:void 0},"b"),uo=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"),lo=a((t,e)=>{let{key:s,op:r,row:i}=e,n=[],o=-1;for(let c of t){let h=ho(c);if(h===void 0)return;if(h===s){if(r==="delete")continue;o===-1&&(o=n.length)}n.push(c)}if(r==="delete")return n;if(i!==void 0)return o===-1?n.splice(co(n,i),0,i):n[o]=i,n},"x"),po=a((t,e)=>{let s=ao(t);if(s===void 0)return;let r=lo(s,e);return r===void 0||Array.isArray(t)?r:{...t,[Zt]:r}},"E"),es=Symbol("lunora.unmergeableDelta"),Hr=a((t,e)=>{if("data"in t&&t.data!==void 0)return T(t.data);let s=T(t.delta);return uo(s)?e===void 0?s:po(e,s)??es:s},"m");var ap=new Set(Object.keys(Ps)),D=class extends v{static{a(this,"R")}constructor(e,s){super("INTERNAL",e,{data:s})}};var mt=a(t=>{let e=t?.data?.retryAfterMs;return typeof e=="number"&&Number.isFinite(e)?e:void 0},"f"),ts=new Set(["TOKEN_EXPIRED","UNAUTHENTICATED"]),_e=a(t=>ts.has(t?.code??""),"u");var Qe=a(t=>typeof t=="string"||Array.isArray(t)&&t.every(e=>typeof e=="string")?{hint:t}:{},"n");var De=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 fo=1024,yt=a(t=>{let e=t.maxBuffer??fo,s=[],r=[],i=!1,n,o=!1,c=a(()=>{let d=r.shift();if(!d)return!1;if(n)return d.reject(n),!0;if(s.length>0){let p=s.shift();return d.resolve({done:!1,value:p}),!0}return i?(d.resolve({done:!0,value:void 0}),!0):(r.unshift(d),!1)},"u"),h={complete(){if(!(i||n))for(i=!0;c(););},fail(d){if(!(i||n)){for(n=d,s.length=0;c(););t.onFail?.()}},push(d){if(!(i||n||o)){if(s.length>=e){h.fail(new v("STREAM_BACKPRESSURE",`stream buffer overflow (max=${e.toString()}); the consumer cannot keep up with the producer`));return}s.push(d),c()}}},u=a(()=>{if(!o){o=!0,i=!0,s.length=0;try{t.onCancel()}catch{}for(;c(););}},"c");return{handle:h,iterable:{cancel:u,[Symbol.asyncIterator](){return{next(){if(n)return Promise.reject(n);if(s.length>0){let d=s.shift();return Promise.resolve({done:!1,value:d})}return i?Promise.resolve({done:!0,value:void 0}):new Promise((d,p)=>{r.push({reject:p,resolve:d})})},return(){return u(),Promise.resolve({done:!0,value:void 0})}}}}}},"p");var ge=a(t=>t.reason??Object.assign(new Error("The operation was aborted"),{name:"AbortError"}),"c"),oe=a(async(t,e,s,r=()=>new D(`LunoraClient: request timed out after ${t.toString()}ms`))=>{if(e?.aborted)throw ge(e);let i=new AbortController,n=[],o=new Promise((h,u)=>{if(t>0){let d=setTimeout(()=>{u(r()),i.abort()},t);n.push(()=>{clearTimeout(d)})}if(e){let d=a(()=>{i.abort(),u(ge(e))},"a");e.addEventListener("abort",d,{once:!0}),n.push(()=>{e.removeEventListener("abort",d)})}}),c=s(i.signal);c.catch(()=>{});try{return await Promise.race([c,o])}finally{for(let h of n)h()}},"m"),ss=a(async(t,e)=>{if(e===void 0)return t;if(e.aborted)throw t.catch(()=>{}),ge(e);let s=a(()=>{},"o"),r=new Promise((i,n)=>{s=a(()=>{n(ge(e))},"o"),e.addEventListener("abort",s,{once:!0})});t.catch(()=>{});try{return await Promise.race([t,r])}finally{e.removeEventListener("abort",s)}},"E"),Nr=a(async(t,e)=>!Number.isFinite(e)||e<=0?t.read():oe(e,void 0,async()=>t.read(),()=>new v("STREAM_IDLE",`stream received nothing for ${e.toString()}ms`)),"y");var vt=/^ /u,mo=/^\d+$/u,yo=2147483647,vo=10,go=1e3,Kr=a(t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),"O"),bo=a(t=>{let e="",s,r,i=[];for(let n of t.split(`
|
|
2
|
+
`))if(n.startsWith("event:"))e=n.slice(6).replace(vt,"");else if(n.startsWith("data:"))i.push(n.slice(5).replace(vt,""));else if(n.startsWith("id:")){let o=n.slice(3).replace(vt,"");o.includes("\0")||(s=o)}else if(n.startsWith("retry:")){let o=n.slice(6).replace(vt,"");mo.test(o)&&Number.isSafeInteger(Number(o))&&(r=Math.min(Number(o),yo))}return{data:i.join(`
|
|
3
|
+
`),event:e,id:s,retry:r}},"U"),wo=a((t,e,s)=>{let r=e.params??{},i=t.path.split("/").map(c=>{if(!c.startsWith(":"))return c;let h=c.slice(1),u=r[h];if(u===void 0)throw new v("HTTP_STREAM_MISSING_PARAM",`httpStream: missing path param ":${h}" for route ${t.path}`);return encodeURIComponent(Kr(u))}).join("/"),n=new URLSearchParams;for(let[c,h]of Object.entries(e.searchParams??{}))h!==void 0&&n.set(c,Kr(h));let o=n.toString();return`${s.endsWith("/")?s.slice(0,-1):s}${i}${o===""?"":`?${o}`}`},"Y"),So=a((t,e)=>{if(t.event==="complete")return e.complete(t.data),!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 v(i,r,Qe(s.hint));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 v("HTTP_STREAM_BAD_CHUNK","httpStream: malformed SSE chunk (invalid JSON)")),!0}return!1},"J"),qr=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=bo(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),So(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}},"P"),rs=a(async(t,e,s,r,i=0)=>{let n=t.getReader(),o=new TextDecoder,c=qr(e,s),h=a(()=>n.cancel().then(()=>{},()=>{}),"a");try{for(;;){let{done:u,value:d}=await Nr(n,i);if(u)break;if(c.append(o.decode(d,{stream:!0})),c.drain())return await h(),!0}return c.append(o.decode()),c.drain()}catch(u){throw r.abort(),h().catch(()=>{}),u}},"q"),Br=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"),Co=a(async(t,e,s,r)=>{let i=qr(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 Br(0,r.signal)}},"K"),ko=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 v("HTTP_STREAM_STATUS",`httpStream: request failed (status ${e.toString()}, ${s}): ${r}`,{status:e,why:typeof i=="string"?i:void 0})},"X"),To=a(async(t,e)=>{let s,r=new Promise(n=>{s=setTimeout(()=>{n(void 0)},go)}),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(()=>{})}},"G"),Oo=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}}},"z"),jr=a(t=>t instanceof Error&&"code"in t?t:new v("HTTP_STREAM_TRANSPORT",t instanceof Error?t.message:String(t),{cause:t}),"M"),Wr=a((t,e,s={})=>{let r=s.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!r)throw new v("INTERNAL","httpStream: no `fetch` implementation available");let i=wo(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:h,iterable:u}=yt({maxBuffer:s.maxBuffer,onCancel:a(()=>{n.abort()},"onCancel"),onFail:a(()=>{n.abort()},"onFail")}),d=s.reconnect??!1,p=De(),{lastEventId:l}=s,f,y=0,m=a(()=>{p.reset(),y=0},"x"),w={},g=a(S=>{try{S()}catch(I){throw w.value={error:I},I}},"R"),k={onFrame:m,onId:a(S=>{g(()=>s.onEventId?.(S)),l=S},"onId"),onRetry:a(S=>{g(()=>s.onRetry?.(S)),f=S},"onRetry")},E=a(async()=>{let S=Oo(s.headers,l),I=new v("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"),re=a(R=>{if(n.signal.aborted){h.complete();return}return{completed:R,error:I}},"_"),M=new AbortController,P=a(()=>{M.abort()},"A");n.signal.addEventListener("abort",P,{once:!0});try{let R=await r(i,{headers:S,method:t.method,signal:M.signal});if(!R.ok){let Z=await To(R,n.signal);h.fail(ko(Z,R.status)??new v("HTTP_STREAM_STATUS",`httpStream: request failed (status ${R.status.toString()})`,{status:R.status}));return}if(!R.body){if(typeof R.text!="function"){h.fail(new v("HTTP_STREAM_NO_BODY","httpStream: response exposes neither a body stream nor a text() read",{hint:Ms}));return}return re(await Co(R,h,k,M))}return re(await rs(R.body,h,k,M,s.idleTimeoutMs))}catch(R){if(n.signal.aborted){h.complete();return}if(w.value){let{error:Z}=w.value;h.fail(Z instanceof Error?Z:new v("HTTP_STREAM_CALLBACK","httpStream: an onEventId/onRetry callback threw"));return}return{completed:!1,error:jr(R)}}finally{n.signal.removeEventListener("abort",P)}},"H");return(async()=>{try{for(;;){if(n.signal.aborted){h.complete();return}let S=await E();if(!S)return;if(S.completed||!d||y>=vo){S.completed||h.fail(S.error);return}y+=1,await Br(f??p.next(),n.signal)}}finally{c()}})().catch(S=>{if(n.signal.aborted){h.complete();return}h.fail(jr(S))}),u},"ne");var gt=a(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"a"),is=a(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"h"),U=a((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"$"),L=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"),Eo="http://same-origin.invalid",Ue=a(t=>new URL(t,Eo),"p"),Io=/^[a-z][a-z\d+.-]*:/iu,ns=a((t,e)=>{if(Io.test(e))return t.toString();let s=`${t.pathname}${t.search}${t.hash}`;return e.startsWith("//")?`//${t.host}${s}`:s},"S");var F=class t{static{a(this,"t")}static key(e,s,r){return`${e}::${q(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()}},$=a((t,e)=>{t.ack=e},"s"),bt=a(t=>{t.ack==="inflight"&&$(t,"idle")},"a");function wt(t){if(t!==void 0)return e=>{t(e)}}a(wt,"b");var He=a((t,e)=>{for(let s of t)try{s(e)}catch{}},"c"),be=a((t,e)=>{t.awaitingSnapshot=!1,He(t.errorCallbacks,e)},"l");var $r=a((t,e)=>{let s=[],r=[],i=a((n,o)=>t.get(F.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 h=i(n.__lunoraRef,o??{});if(!h)return;let u=lt(h,()=>c);u&&(s.push(u.confirm),r.push(u.rollback))},"setQuery")}}},"g");var as=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},"v"),Ro=a((t,e)=>{let s=as(e);if(!(s===void 0||mt(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},"p"),we=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},"y"),os=a(()=>new D("LunoraClient: batch slot carried no error envelope"),"E"),zr=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}},"c"),Gr=a(t=>{let{code:e,messageText:s}=zr(t,"stream error"),r=t.error,i=r?.why,n=e===void 0?new Error(s):new v(e,s,Qe(r?.hint));return typeof i=="string"&&(n.why=i),n},"D"),cs=a(t=>{let{code:e,messageText:s}=zr(t,"subscription error"),r=t.error,i=typeof r?.why=="string"?{why:r.why}:{};return{message:s,...e===void 0?{}:{code:e},...Qe(r?.hint),...i}},"O"),Ao=Symbol.for("lunora.serverVerdict"),Se=a(t=>{let e=new Error(t.message??"request failed");if(e.code=t.code,e[Ao]=!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},"d"),Fo=a(t=>Object.freeze(Object.fromEntries([...t].filter(([e])=>e!=="set-cookie"))),"b"),K=a((t,e)=>Object.defineProperty(t,"headers",{value:Fo(e)}),"w"),hs=a((t,e)=>{let s=Se(t),r=Ro(s,e.get("retry-after"));return r!==void 0&&(s.data=r),K(s,e)},"j"),ds=a(t=>{let e=we(t);return e===void 0?os():Se(e)},"M"),Vr=new WeakSet,St=a(t=>{let e=new v("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},"N"),Ne=a(t=>t instanceof Error&&Vr.has(t),"T");var Jr=0,Po=a(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();Jr+=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)}_${Jr.toString(36)}_${t}`},"d"),us=a((t,e)=>t!==void 0&&e!==t,"l"),kt=Po,Ce=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"),Ct=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??=kt();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=>{Ce(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 Ce(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(us(this.version,o.version)){this.persistence.remove(o.id).catch(c=>{Ce(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=>{Ce(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),Ce(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){Ce(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 Lo="lunora-outbox",Mo="offline-mutations",ls="by_id",xo=a((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new v("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let s=t.databaseName??Lo,r=t.storeName??Mo,i=ct(e,s,1,o=>{o.objectStoreNames.contains(r)||o.createObjectStore(r,{autoIncrement:!0}).createIndex(ls,"id",{unique:!0})}),n=ht(i,r);return{append:a(async o=>{await n("readwrite",c=>Q(c.add(o)))},"append"),clear:a(async()=>{await n("readwrite",o=>Q(o.clear()))},"clear"),load:a(async()=>n("readonly",o=>Q(o.getAll())),"load"),remove:a(async o=>{await n("readwrite",async c=>{let h=await Q(c.index(ls).getKey(o));h!==void 0&&await Q(c.delete(h))})},"remove"),replace:a(async o=>{await n("readwrite",async c=>{let h=await Q(c.index(ls).getKey(o.id));h!==void 0&&await Q(c.put(o,h))})},"replace")}},"w"),Yr=a((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return xo()}},"b");var Xr=new WeakMap,ps=a((t,e)=>{Xr.set(t,e)},"i"),fs=a(t=>t===void 0?void 0:Xr.get(t),"d"),Zr=a((t,e,s,r)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r),n=i.present&&i.answered?q(i.value):void 0,o=a(()=>{let c=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r);return!i.present||!i.answered||!c.present||!c.answered?!0:q(c.value)===n},"c");return n!==void 0&&ps(o,{args:s,functionPath:e.__lunoraRef,shardKey:r}),o},"h");var ei="/_lunora/rpc",ms="/_lunora/rpc-batch",ys="/_lunora/ws",di="/_lunora/admin/shard-traffic",Do="/_lunora/admin/scheduled",Uo="/_lunora/admin/scheduled/status",Ho="/_lunora/admin/scheduled/ws",No="/_lunora/admin/scheduled/cancel",ti="/_lunora/admin/scheduled/dead",Ko="/_lunora/admin/scheduled/dead/retry",jo="/_lunora/admin/scheduled/dead/cancel",si="/_lunora/admin/scheduled/history",qo="/_lunora/admin/scheduled/job",Bo="/_lunora/admin/scheduled/cron-runs",ui="/_lunora/admin/pause",Wo="/_lunora/admin/workflows/instances",$o="/_lunora/admin/workflows/instance",zo="/_lunora/admin/workflows/status",Go="/_lunora/admin/workflows/create",Vo="/_lunora/admin/workflows/event",Ot="/_lunora/admin/storage",li="/_lunora/admin/storage/url",pi="/_lunora/admin/storage/buckets",fi="/_lunora/admin/functions",mi="/_lunora/admin/cron-jobs",yi="/_lunora/admin/cron-jobs/run",vi="/_lunora/admin/architecture",gi="/_lunora/admin/openapi",bi="/_lunora/admin/openrpc",wi="/_lunora/admin/global/tables",Si="/_lunora/admin/global/table",Ci="/_lunora/admin/global/facet",ki="/_lunora/admin/vector/indexes",Ti="/_lunora/admin/vector/query",Oi="/_lunora/admin/logs/archive",Ei="/_lunora/admin/kv/namespaces",Et="/_lunora/admin/tokens",Ii="/_lunora/admin/kv/keys",It="/_lunora/admin/kv/value",Ri="/_lunora/admin/auth/users",Ai="/_lunora/admin/auth/sessions",Fi="/_lunora/admin/auth/users/create",Pi="/_lunora/admin/auth/users/role",Li="/_lunora/admin/auth/users/ban",Mi="/_lunora/admin/auth/users/unban",xi="/_lunora/admin/auth/users/password",_i="/_lunora/admin/auth/users/remove",Qi="/_lunora/admin/auth/users/impersonate",Di="/_lunora/admin/auth/sessions/revoke",Ui="/_lunora/admin/auth/sessions/revoke-all",Hi="/_lunora/admin/auth/capabilities",Ni="/_lunora/admin/auth/users/update",Ki="/_lunora/admin/auth/accounts",ji="/_lunora/admin/auth/accounts/unlink",qi="/_lunora/admin/auth/passkeys",Bi="/_lunora/admin/auth/passkeys/delete",Wi="/_lunora/admin/auth/two-factor/disable",$i="/_lunora/admin/auth/organizations",zi="/_lunora/admin/auth/organizations/members",Gi="/_lunora/admin/auth/organizations/invitations",Vi="/_lunora/admin/auth/organizations/members/remove",Ji="/_lunora/admin/auth/organizations/invitations/cancel",Yi="/_lunora/admin/auth/config",Xi="/_lunora/admin/auth/sign-up-invitations",Zi="/_lunora/admin/auth/sign-up-invitations/create",en="/_lunora/admin/auth/sign-up-invitations/revoke",tn="/_lunora/admin/auth/organizations/create",sn="/_lunora/admin/auth/organizations/update",rn="/_lunora/admin/auth/organizations/remove",nn="/_lunora/admin/auth/organizations/members/add",an="/_lunora/admin/auth/organizations/members/invite",on="/_lunora/admin/auth/organizations/members/role",cn="/_lunora/admin/auth/organizations/teams",hn="/_lunora/admin/auth/organizations/teams/create",dn="/_lunora/admin/auth/organizations/teams/update",un="/_lunora/admin/auth/organizations/teams/remove",ln="/_lunora/admin/auth/organizations/teams/members",pn="/_lunora/admin/auth/organizations/teams/members/add",fn="/_lunora/admin/auth/organizations/teams/members/remove",mn="/_lunora/admin/auth/organizations/roles",yn="/_lunora/admin/auth/organizations/roles/create",vn="/_lunora/admin/auth/organizations/roles/update",gn="/_lunora/admin/auth/organizations/roles/remove",Jo="/api/auth",Yo="/get-session",Xo="lunora-ping",vs=500,bn=a((t,e)=>{if(t.size<e)return;let s=t.keys().next().value;s!==void 0&&t.delete(s)},"Ue");new TextDecoder;var Zo=new TextEncoder,ec=a(t=>Jt(Zo.encode(t)),"Zt"),tc=a(t=>ec(JSON.stringify(t)),"es"),sc="x-lunora-expect-subject",rc=a(t=>tc({subject:t}),"ss"),ic="refreshBatch",ri=Symbol.for("lunora:session-change"),nc="lunora:session-change",ac="better-auth.message",oc="signout",wn=a(()=>{let t=globalThis,e=t[ri];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},t[ri]=e),e},"Ne"),cc=a(()=>"document"in globalThis,"as"),hc=a(async()=>{let t=[];for(let e of wn().listeners)try{t.push(e())}catch{}await Promise.allSettled(t)},"cs"),dc=a((t,e)=>{if(t!==ac||e===null)return!1;try{let s=JSON.parse(e);return s?.event==="session"&&s.data?.trigger===oc}catch{return!1}},"ds"),uc=a(t=>{let e=[],s=a(()=>{hc().catch(()=>{})},"t"),r;try{r=typeof BroadcastChannel=="function"?new BroadcastChannel(nc):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=>{dc(o.key,o.newValue)&&s()},"r");i.addEventListener("storage",n),e.push(()=>{i.removeEventListener?.("storage",n)})}return()=>{for(let n of e)n()}},"hs"),lc=a(t=>{let e=wn();return e.listeners.add(t),e.detach===void 0&&cc()&&(e.detach=uc(e.tab)),()=>{e.listeners.delete(t),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},"ls"),ii="/_lunora/ws/reauth",pc=4005,fc="identity_changed",mc="/_lunora/claims",yc="lunora",vc="lunora.bearer.",gc=a(t=>`${vc}${Jt(new TextEncoder().encode(t))}`,"vs"),bc=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}},"Ss"),Sn=a(t=>({paused:t.paused===!0,...typeof t.pausedAt=="number"?{pausedAt:t.pausedAt}:{},...typeof t.reason=="string"?{reason:t.reason}:{},supported:t.supported===!0}),"Be"),qe=a(t=>"args"in t?{...t,args:T(t.args)}:t,"Q"),Cn=a(async t=>(t.assertOpen(),((await t.adminFetch(Do,"GET")).records??[]).map(e=>qe(e))),"Wr"),kn=a(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(`${qo}?id=${encodeURIComponent(e)}`,"GET");return s.record===void 0?null:qe(s.record)},"Qr"),Tn=a(async(t,e={})=>{t.assertOpen();let s=e.cursor===void 0?si:`${si}?cursor=${encodeURIComponent(e.cursor)}`,r=await t.adminFetch(s,"GET"),i=(r.records??[]).map(n=>qe(n));return r.truncated===!0&&r.cursor!==void 0?{cursor:r.cursor,records:i}:{records:i}},"xr"),On=a(async t=>{t.assertOpen();let e=await t.adminFetch(Bo,"GET");return{inFlight:e.inFlight??[],runs:e.runs??[]}},"qr"),En=a(async t=>(t.assertOpen(),Sn(await t.adminFetch(ui,"GET"))),"Kr"),In=a(async(t,e,s)=>(t.assertOpen(),Sn(await t.adminFetch(ui,"POST",s===void 0?{paused:e}:{paused:e,reason:s}))),"jr"),Rn=a(async t=>{t.assertOpen();let e=await t.adminFetch(Uo,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},"Vr"),An=a(async(t,e)=>(t.assertOpen(),{cancelled:(await t.adminFetch(No,"POST",{id:e})).cancelled===!0}),"Gr"),Fn=a(async t=>(t.assertOpen(),(await bc(async e=>await t.adminFetch(e===void 0?ti:`${ti}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>qe(e))),"$r"),Pn=a(async(t,e)=>(t.assertOpen(),{retried:(await t.adminFetch(Ko,"POST",{id:e})).retried===!0}),"Jr"),Ln=a(async(t,e)=>(t.assertOpen(),{removed:(await t.adminFetch(jo,"POST",{id:e})).removed===!0}),"zr"),Mn=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(`${Wo}?${s.toString()}`,"GET");return{configured:r.configured,instances:r.instances??[],page:r.page??1,perPage:r.perPage??e.perPage??0,totalCount:r.totalCount}},"Yr"),xn=a(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({id:e.id,name:e.name}),r=await t.adminFetch(`${$o}?${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??[]}},"Xr"),_n=a(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(Go,"POST",{id:e.id,name:e.name,params:e.params}),r=s.id??e.id;if(r===void 0)throw new v("WORKFLOWS_REST_ERROR","Workflows create response carried no instance id",{status:502});return{id:r,status:s.status??"unknown"}},"Zr"),Qn=a(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(Vo,"POST",{id:e.id,name:e.name,payload:e.payload,type:e.type});return{instanceId:s.instanceId??e.id,timestamp:s.timestamp}},"en"),Dn=a(async(t,e)=>(t.assertOpen(),{status:(await t.adminFetch(zo,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),"tn"),z=a((t,e)=>{try{return N(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)}},"k"),Cs=a(t=>{try{return N(t),!0}catch{return!1}},"re"),Un=a(t=>t!==null&&typeof t=="object"&&("error"in t||"result"in t),"De"),wc=a((t,e,s)=>{let r=Array.from({length:e}),i=a(n=>({error:K(ds(n),s),ok:!1}),"i");for(let n of t){if(typeof n.id!="number"||n.id<0||n.id>=e)continue;if(!Un(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(St(c),s),ok:!1}}}return r.map(n=>n??{error:K(new Error("batch call returned no result"),s),ok:!1})},"bs"),gs=a((t,e)=>e!==null?{}:t===null?{expectSubject:null}:t?.startsWith("subj:")===!0?{expectSubject:t.slice(5)}:{},"Z"),Ke=a(t=>t==="connected"||t==="polling","D"),b=a(t=>t??"","f"),G=a((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"E"),Sc=a(t=>{if(!t.pendingStreams||t.pendingStreams.length===0)return;let e=t.pendingStreams;t.pendingStreams=[];for(let s of e)G(t,s)},"Cs"),Cc=new TextDecoder,kc=a(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return Cc.decode(t)},"gs"),se=class{static{a(this,"O")}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()}},ke=a(t=>{t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)},"U"),Tc=a((t,e,s)=>{ke(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(Xo)}catch{}},e))},"Ts"),ni=a((t,e,s,r)=>{let{WebSocketImpl:i,connectTimeoutMs:n,heartbeatIntervalMs:o}=s;if(i===void 0)throw new v("INTERNAL","no WebSocket implementation available");let c=r.protocols===void 0?new i(e):new i(e,r.protocols);t.socket=c;let h=a(()=>{ke(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket===c&&(t.socket=void 0)},"c"),u=a(d=>{h(),r.onClose(d)},"d");n>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===c){try{c.close()}catch{}u()}},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(d){console.error("[lunora] connection open handler threw",d)}t.socket===c&&Tc(t,o,u)}}),c.addEventListener("message",d=>{if(t.socket===c){t.lastFrameAt=Date.now();try{r.onMessage(d)}catch(p){console.error("[lunora] server frame handler threw",p)}}}),c.addEventListener("close",d=>{t.socket===c&&u(d)}),c.addEventListener("error",()=>{t.socket===c&&u()})},"Re"),Oc=a(t=>{let{afterFailedAttempts:e,intervalMs:s,onReachable:r,onStateChange:i,poll:n}=t,o=s>0&&e>0,c=0,h,u=!1,d=!1,p=a(()=>{h!==void 0&&(clearInterval(h),h=void 0,u=!1,i())},"l"),l=a(y=>{if(h!==void 0){if(!y){p();return}u||(u=!0,i()),r()}},"u"),f=a(()=>{d||(d=!0,n().then(l).finally(()=>{d=!1}).catch(()=>{}))},"p");return{hasFailedOpen:a(()=>c>0,"hasFailedOpen"),isPolling:a(()=>h!==void 0&&u,"isPolling"),noteFailedOpen:a(()=>{c+=1,!(!o||h!==void 0||c<e)&&(h=setInterval(f,s),i(),f())},"noteFailedOpen"),noteOpen:a(()=>{c=0,p()},"noteOpen"),stop:p}},"ks"),Ec=1e4,ai=a(async t=>oe(Ec,void 0,t,()=>new TypeError("LunoraClient: poll timed out")),"Ie"),Hn=new Set(["DELIVERY_FENCED","RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),oi=a(t=>{if(t instanceof D)return!0;let e=t?.code;return e===void 0||Hn.has(e)||ts.has(e)},"Oe"),Ic=1e3,Nn=6e4,Rc={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},je=a((t,e,s)=>{let r=as(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 D(n,i):new v(Rc[t]??"BAD_REQUEST",n,{data:i});return K(o,s)},"W"),ks=a((t,e=Math.random)=>{let s=Math.min(Ic*2**Math.max(t-1,0),Nn);return Math.round(s*(.5+e()*.5))},"ne"),Ac=a(t=>{let e=t?.code;return t instanceof D||e===void 0||Hn.has(e)},"Rs"),Fc=a((t,e,s)=>{let r=mt(t);return r!==void 0&&r>0?Math.min(r,Nn):Ac(t)?ks(e,s):void 0},"Is"),Pc=983040,Lc=a(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"Ls"),Mc=a(t=>{let e=new Map;for(let s of t)typeof s.id=="number"&&Un(s.body)&&e.set(s.id,s.body);return e},"Ps"),xc=a((t,e)=>{if(t===void 0)return{kind:"unanswered"};if("error"in t)return{error:K(ds(t),e),kind:"errored"};try{return{commitCursor:t.commitCursor,kind:"committed",value:T(t.result)}}catch(s){return{commitCursor:t.commitCursor,error:K(St(s),e),kind:"undecodable"}}},"Fs"),bs=a((t,e)=>`${b(t)}\0${e}`,"ee"),_c=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)},"Ms"),Ts=class{static{a(this,"Hs")}constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,s){bn(this.buffers,this.maxBuffers),this.buffers.set(bs(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(bs(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=bs(e,s),i=this.buffers.get(r);return i&&this.buffers.delete(r),i}clear(){this.buffers.clear()}},Qc=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(),_c(t.rows,r),t.answered=!0,s.checkpoint!==void 0&&(t.serverCursor=s.checkpoint),s.epoch!==void 0&&(t.serverEpoch=s.epoch);let h=e.lastMutationId.get(t.id);return h!==void 0&&(t.lastMutationId=h),"applied"},"Us"),ci=a(t=>{let e=[...t.rows.values()];for(let s of t.callbacks)try{s(e)}catch{}},"Le"),Dc=a((t,e)=>{for(let[s,r]of e.undecodable){let i=t.get(s);i&&He(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape \u2014 ${r instanceof Error?r.message:String(r)}`})}},"Ns"),Os=a((t,e)=>{t.lastMutationId=Math.max(t.lastMutationId??0,e)},"oe"),Es=a((t,e=!1)=>{let s=t.serverCursor,r=t.lastMutationId;Mr(()=>{for(let i of t.checkpointCallbacks)i({checkpoint:s,mutationId:r,...e&&{rowsFollow:!0}})})},"ae"),Kn=a((t,e,s)=>{t.serverBase=e,t.serverBaseCommitted=!0,t.awaitingSnapshot=!1,t.serverClaims=s.claims,s.cursor!==void 0&&(t.serverCursor=s.cursor),s.epoch!==void 0&&(t.serverEpoch=s.epoch)},"xe"),Uc=a(t=>t.awaitingSnapshot===!0?void 0:t.lastValue,"Bs"),Hc=a((t,e)=>e.cursor!==void 0&&t.serverCursor!==void 0&&(t.serverBase!==void 0||t.serverBaseCommitted===!0)&&e.epoch!==void 0&&e.epoch===t.serverEpoch&&e.cursor<t.serverCursor,"Ds"),Nc=a(t=>t.type==="delta"&&t.more===!0,"Ws"),Rt=a((t,e)=>t!==void 0&&t!==e,"V"),Kc=a((t,e)=>e==="connected"&&t!=="connected"||e==="polling"&&t!=="connected"&&t!=="polling","Qs"),Is=a((t,e,s,r,i=!1)=>{if(s===void 0)return!i||t.ownClaims(e,r,"")===null;let n=t.ownClaims(e,r,s);return n!==void 0&&(n===null||n===s)},"le"),jc=a(t=>{for(let e of t.activeSubscriptions())$(e,"idle"),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()},"xs"),qc=a(t=>{t.closeConnections();let e=t.leader;e.status=void 0,e.wasEverConnected=!1;for(let s of t.activeSubscriptions())$(s,"idle"),s.valueReceived=!1;for(let s of t.activeShapes())s.answered=!1;t.emitConnectionStatus()},"qs"),Bc=a((t,e,s)=>{if(Rt(s,t.identityFingerprint()))return;let r=t.leader,i=Kc(r.status,e);r.status=e,e==="connected"&&(r.wasEverConnected=!0),t.emitConnectionStatus(),i&&(t.awaitLeaderAnswers(),t.flushOfflineQueues())},"Ks"),Wc=a(t=>{t.isLeader()&&t.broadcastStatus(t.computeStatus(),t.identityFingerprint())},"js"),jn=a((t,e,s,r,i,n,o)=>{if(Rt(n,t.identityFingerprint())||!Is(t,e,o,()=>{jn(t,e,s,r,i,n,o)},s!==void 0))return;let c=t.subscription(e);if(!c)return;t.dropCacheSeed(e);let h=!c.valueReceived;c.valueReceived=!0,Kn(c,s,r===void 0?{claims:o}:{claims:o,cursor:r,epoch:i}),r!==void 0&&pt(c,r),W(c,s),h&&t.emitConnectionStatus(),t.settleAwaitedAnswer(c,!0)},"qe"),qn=a((t,e,s,r,i)=>{if(Rt(r,t.identityFingerprint())||!Is(t,`error:${e}`,i,()=>{qn(t,e,s,r,i)}))return;let n=t.subscription(e);if(n){let o=!n.valueReceived;n.valueReceived=!0,He(n.errorCallbacks,s),o&&t.emitConnectionStatus(),t.settleAwaitedAnswer(n,!1)}},"Ke"),Bn=a((t,e,s,r,i,n,o,c)=>{if(Rt(o,t.identityFingerprint()))return;let h=t.subscription(e);h&&Is(t,`settled:${e}`,c,()=>{Bn(t,e,s,r,i,n,o,c)})&&(t.ackAndAdvanceCursor(h,s,r),i!==void 0&&n===t.clientIdentifier()&&Os(h,i),Es(h))},"je"),$c=a((t,e,s)=>t!==null||e&&s===null,"Vs"),zc=a(t=>t.sensitive===!0,"Gs"),Gc=a((t,e)=>{if(!zc(t))return e;if(e.onlineOnly===!1)throw new v("BAD_REQUEST",`'${t.__lunoraRef}' takes a sensitive argument and is always online-only; onlineOnly: false is not allowed`);return{...e,onlineOnly:!0}},"$s"),Vc=[Ur,ic],Jc=a(t=>t.type==="data"||t.type==="delta"||t.type==="settled"||t.type==="resume"||t.type==="error"&&typeof t.id=="string","zs"),Yc=100,Wn=1e4,Xc=5,Zc=500,eh=1e4,th=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)})},"ti"),sh=a((t,e)=>{let s=[t===void 0?"":`shard=${encodeURIComponent(t)}`,e===void 0?"":`token=${encodeURIComponent(e)}`].filter(Boolean).join("&");return s===""?ii:`${ii}?${s}`},"si"),ws=a(async t=>typeof t=="function"?await t():t,"te"),Ss=a(async(t,e,s,r)=>{let i=new AbortController,n=setTimeout(()=>{i.abort()},Wn);try{let o=await t(e,{body:s,credentials:"include",headers:r,method:"POST",signal:i.signal});return{status:o.status,text:await o.text()}}finally{clearTimeout(n)}},"se"),hi=a((t,e)=>new v("OFFLINE_NOT_QUEUED",`'${t}' is online-only and the connection is not live, so it was not queued`,{cause:e,hint:Ls}),"Pe"),rh=a((t,e)=>t instanceof TypeError&&Cs(e),"ii"),ih=a(()=>globalThis.navigator?.onLine===!1,"ri"),nh=a((t,e,s,r)=>e||t===!0&&s&&!r,"ni"),ah=Promise.resolve(),oh=a(async(t,e,s)=>{let r,i,n=new AbortController,o=a(()=>{n.abort(e?.reason)},"a");e?.addEventListener("abort",o,{once:!0});try{await rs(t,{complete:a(c=>{e?.aborted!==!0&&(r=c)},"complete"),fail:a(c=>{i=c},"fail"),push:a(c=>{e?.aborted!==!0&&s?.(c)},"push")},{},n)}finally{e?.removeEventListener("abort",o)}if(e?.aborted===!0)throw e.reason instanceof Error?e.reason:new DOMException("The operation was aborted.","AbortError");return{failure:i,terminal:r}},"ai"),Tt=class t{static{a(this,"Ge")}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;ownClaimsValue;heldLeaderFrames=new Map;ownClaimsFetch;claimsVerifiedAgainst=new Set;ownClaimsRetryTimer;ownClaimsFailures=0;suspendedFollowerValues=new Map;frameClaims;authTokenOnUpgrade;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;mutationIssueCounter=0;persistence;persistenceVersion;releasePageHideFlush;outboxLeaderRelease;queryCache;queryCacheEpoch=0;queryCacheChain=Promise.resolve();hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new F;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 se;statusListeners=new se;roomFlushes=new Map;roomIdentityResets=new Set;tokenExpiredListeners=new se;identityChangeListeners=new se;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new se;pendingChangeListeners=new se;syncStatusListeners=new se;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 Ts(t.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??U(is(e.url),ys),this.wsToken=e.wsToken,this.wsTicket=e.wsTicket;let s=e.authBasePath??Jo;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??Pr(),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=Yr(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Fr(e.queryCache),this.clientQueryStore=new dt,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=ah),this.offlineQueue=new Ct(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-${kt()}`,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=lc(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,s){let r=this.authToken!==e;r&&this.resetOwnClaims();let i=this.identityFingerprint(),n=this.authSubject===void 0||this.subjectToken===this.authToken,o=this.subjectAwaitingReconfirm(),c=this.isKnownNobody(),h=this.authToken;this.authToken=e,r&&(this.tokenFingerprint=void 0),this.applySubject(e,s);let u=this.identityFingerprint(),d=!r&&e!==null&&n,p=!r&&e===null&&i===null&&n&&!c,l=u!==i,f=!1;l&&(d?(this.restampQueuedIdentity(i,u),this.restampWatermarks(i,u),this.restampConnectionIdentity(i,u),this.reseedFromHydratedCache()):p?(this.restampWatermarks(i,u),this.restampConnectionIdentity(i,u),this.reseedFromHydratedCache()):f=this.retirePreviousIdentity(i,c,h,e)),f||this.applyUpgradeBearer(this.reconcileUpgradeBearer(h,e,l)),l&&this.restartTabCoordinatorForIdentity(),this.syncReadCacheToCredential(o),r&&this.authTokenListeners.emit(e),(u!==i||r||o)&&this.offlineQueue.size>0&&Ke(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 v("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let n=r?.shardKey??"",o=this.identityFingerprint(),c,h,u;try{h=await this.rpc(e,s,r?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:a(d=>{c=d},"onMutationAck")})}catch(d){if(!Ne(d))throw d;u=d}if(c!==void 0&&c>(this.clientWatermarks.get(o??"")?.get(n)??0)){let d=this.clientWatermarks.get(o??"");d===void 0&&(bn(this.clientWatermarks,8),d=new Map,this.clientWatermarks.set(o??"",d)),d.set(n,c)}if(u!==void 0)throw u;return{applied:c===void 0||c===i,result:h}}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(U(this.url,`${this.authBasePath}${Yo}`),{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=b(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=b(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 h=c.indexOf(i);h!==-1&&c.splice(h,1),c.length===0&&this.connectionContextHolders.delete(r),this.refreshConnectionContext(r),this.releaseIdleShard(s.shardKey)}}whisperSubscribe(e,s,r={}){this.assertLeaderOwnedSurface("whisperSubscribe");let i=b(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 h=this.getConnection(r.shardKey);h&&this.sendWhisperJoin(h,i,e)}return()=>{let h=this.whisperHandlers.get(i),u=h?.get(e);if(!u?.delete(s)||u.size>0)return;h?.delete(e),h?.size===0&&this.whisperHandlers.delete(i);let d=this.getConnection(r.shardKey);d&&G(d,{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 v("INTERNAL","LunoraClient: subscribeLiveTopic needs a non-empty topic");this.nextLiveSocketId+=1;let c=`ws-live-${String(this.nextLiveSocketId)}`,h=b(i),u=`/live/${n}/control`,d=this.whisperSubscribe(o,()=>{},{shardKey:i}),p=a(()=>{let m=d;d=void 0,m?.()},"u"),l=this.liveSocketGrants.get(h);l===void 0&&(l=new Map,this.liveSocketGrants.set(h,l)),l.set(c,{onError:s,onEvent:r,release:p,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(h),w=m?.delete(c)===!0;m?.size===0&&this.liveSocketGrants.delete(h);let g=this.getConnection(i)?.connectionId;w&&g!==void 0&&this.postLiveControl(u,i,{action:"unsubscribe",connectionId:g,stream:n,subscriptionId:c,topic:o}),p()}}whisper(e,s,r={}){return this.assertLeaderOwnedSurface("whisper"),this.sendEncodedWhisper(e,z(s??null,`whisper data for topic '${e}'`),r)}connectRoom(e,s,r={}){let i=`room:${e.name}`,n=this.whisperSubscribe(i,l=>{s.onMessage(l)},r),o=!1,c=[],h=a(()=>{c.length=0},"c"),u=a(()=>{for(;c.length>0&&this.roomSendsAdmitted(r.shardKey);){if(!this.sendEncodedWhisper(i,c[0],r))return;c.shift()}},"d"),d=b(r.shardKey),p=this.roomFlushes.get(d)??new Set;return p.add(u),this.roomFlushes.set(d,p),this.roomIdentityResets.add(h),{close:a(()=>{o=!0,c.length=0,p.delete(u),p.size===0&&this.roomFlushes.delete(d),this.roomIdentityResets.delete(h),n()},"close"),send:a(l=>{if(o||this.closed||this.WebSocketImpl===void 0)return!1;let f=z(l,`room message for '${i}'`),y=typeof structuredClone=="function"?structuredClone(f):JSON.parse(JSON.stringify(f));return u(),c.length===0&&this.roomSendsAdmitted(r.shardKey)&&this.sendEncodedWhisper(i,y,r)?!0:c.length>=Yc?!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(h){console.error("[lunora] socket route handler threw",h)}},"i"),n,o=this.openSupplementarySocket(this.supplementaryUrl(e),{offerBearer:!0,onClose:a(()=>{clearTimeout(n),i(s.onClose)},"onClose"),onMessage:a(c=>{let h;try{h=JSON.parse(typeof c.data=="string"?c.data:"")}catch{return}h.type==="message"&&(o.resetBackoff(),i(()=>{s.onMessage(T(h.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 h=JSON.stringify(z(c,`socket message for '${e}'`)),u=o.socket();if(u!==void 0)try{u.send(h)}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:Ke(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=Ue(this.wsUrl),i=a(o=>{let c=Ue(String(o));return c.host===r.host&&s(c)===s(r)},"i"),n=e;return new Proxy(e,{construct:a((o,[c,h,...u])=>new n(c,h??(i(c)?this.upgradeProtocols():void 0),...u),"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 Zr(this,e,s,r)}whenReady(e={}){return e.signal===void 0?this.readyPromise:ss(this.readyPromise,e.signal)}get isReady(){return this.readyResolved}peekHydratedQuery(e,s,r){return this.peekHydratedQueryByKey(e,q(s),r)}peekHydratedQueryByKey(e,s,r){if(!this.readyResolved)return;let i=ce(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=F.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 oe(this.rpcTimeoutMs,void 0,async s=>this.sendBatch(e,s))}async mutation(e,s,r={}){if(r.signal?.aborted)throw ge(r.signal);let{value:i}=await ss(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??(d=>({rows:d})),o=s.length,c=0,h=0,u=0;for(let d=0;d<o;d+=i){let p=s.slice(d,d+i),l=u,{committed:f}=await this.runMutation(e,n(p),{...r.importId===void 0?{}:{mutationId:`${r.importId}:${String(l)}`},shardKey:r.shardKey});u+=1,c+=p.length,f&&(h+=p.length),r.onProgress?.({done:c,total:o})}return{chunks:u,imported:h,queued:c-h}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let s=this.openSupplementarySocket(U(is(this.url),Ho),{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=>qe(n))))},"onMessage")});return s.close}resnapshot(e,s,r={}){this.assertOpen();let i=this.subscriptions.get(F.key(e.__lunoraRef,s??{},r.shardKey));i!==void 0&&this.resnapshotSubscription(i)&&(i.awaitingSnapshot=!0)}subscribe(e,s,r,i={}){if(this.assertOpen(),i.signal?.aborted)return()=>{};let n=s??{},o=F.key(e.__lunoraRef,n,i.shardKey),c=this.subscriptions.get(o),h=wt(r),u=wt(i.onError),d=wt(i.onCheckpoint);if(!c){this.nextSubId+=1;let m=`sub_${this.nextSubId.toString()}`,w=q(n),g=this.takeHydratedCache(e.__lunoraRef,w,i.shardKey);c={ack:"idle",args:n,argsKey:w,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:m,lastValue:g?.value,optimisticLayers:[],serverBase:g?.value,serverCursor:g?.serverCursor,serverClaims:g?.claims,shardKey:i.shardKey,valueReceived:!1,wireArgs:z(n,`args for '${e.__lunoraRef}'`),...g?.serverEpoch===void 0?{}:{serverEpoch:g.serverEpoch}},this.subscriptions.add(c),this.emitSyncStatus(),this.isCrossTabFollower()&&Ke(this.computeStatus())&&this.awaitLeaderAnswer(c),g!==void 0&&this.cacheSeededQueries.set(o,g)}c.callbacks.add(h),u&&c.errorCallbacks.add(u),d&&c.checkpointCallbacks.add(d);let p=Uc(c);if(p!==void 0)try{h(p)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let l=c,f=!1,y=a(()=>{if(!f&&(f=!0,i.signal?.removeEventListener("abort",y),l.callbacks.delete(h),u&&l.errorCallbacks.delete(u),d&&l.checkpointCallbacks.delete(d),l.callbacks.size===0)){this.sendOrQueueUnsubscribe(l.shardKey,l.id,"unsubscribe"),this.returnCacheSeed(F.keyOf(l)),this.subscriptions.remove(l);let m=this.getConnection(l.shardKey);m&&this.settleSubscribeWatchdog(m,l.id),this.releaseIdleShard(l.shardKey),this.emitSyncStatus(),this.settleAwaitedAnswer(l,!0)}},"v");return i.signal?.addEventListener("abort",y,{once:!0}),i.signal?.aborted&&y(),y}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:z(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 v("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;let i=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=r,o=s??{},{handle:c,iterable:h}=yt({maxBuffer:r.maxBuffer,onCancel:a(()=>{this.cancelStream(i,n)},"onCancel")});this.ensureSocket(n);let u=this.getConnection(n),d={id:i,query:{args:z(o,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"},p={durable:r.durable===!0,generation:void 0,handle:c,lastSeq:0,message:d,shardKey:n};this.streams.set(i,p);let l=u?.wsState==="open"&&G(u,d);if(!l&&u===void 0)return this.forgetStream(i),c.fail(new v("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),h;if(!l){for(u.pendingStreams=u.pendingStreams??[];u.pendingStreams.length>=64;){let f=u.pendingStreams.shift()?.id,y=f?this.streams.get(f):void 0;y&&(y.handle.fail(new v("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(f))}u.pendingStreams.push(d)}return h}httpStream(e,s,r={}){if(this.closed)throw new v("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new v("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...r.headers};return Wr(e,s,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:r.maxBuffer,signal:r.signal})}async streamRpc(e,s={},r={}){if(this.closed)throw new v("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new v("INTERNAL","LunoraClient: no `fetch` implementation available");let i=e.__lunoraRef,n=await this.fetchImpl(U(this.url,ei),{body:JSON.stringify({args:z(s,`args for '${i}'`),functionPath:i,shardKey:r.shardKey}),headers:{accept:"text/event-stream",...this.rpcRequestHeaders({},r.shardKey)},method:"POST",...r.signal?{signal:r.signal}:{}});if(!n.ok){let u=await n.json().catch(()=>{});if(u?.error)throw Se(u.error);let d=n.statusText?` ${n.statusText}`:"";throw new v("INTERNAL",`LunoraClient: request failed (status ${n.status.toString()}${d})`)}if(!n.body)throw new v("HTTP_STREAM_NO_BODY","LunoraClient: streaming response has no body");let{failure:o,terminal:c}=await oh(n.body,r.signal,r.onFrame);if(o!==void 0)throw o;if(c===void 0)throw new v("HTTP_STREAM_INTERRUPTED","LunoraClient: stream ended without a complete frame");let h;try{h=JSON.parse(c)}catch{throw new v("HTTP_STREAM_BAD_CHUNK","LunoraClient: streaming result is not valid JSON")}if(typeof h!="object"||h===null||!("result"in h))throw new v("HTTP_STREAM_INTERRUPTED","LunoraClient: stream ended without a result");return T(h.result)}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 v("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(),this.stopOwnClaimsRetry(),this.suspendedFollowerValues.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),$c(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?[yc,gc(this.authToken)]:void 0}applyUpgradeBearer(e){e==="cold"?(this.resetRoomSends(),this.reconnectCold()):e==="warm"&&this.bounceShardSockets(!0)}assertOpen(){if(this.closed)throw new v("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 v("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),clearTimeout(e.revalidateTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0,e.revalidateTimer=void 0}shardInUse(e){let s=a(r=>b(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=b(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=b(e.shardKey);for(let[i,n]of this.streams)b(n.shardKey)===s&&(n.handle.fail(new v("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,ke(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,ownClaims:a((r,i,n)=>this.followerClaims(r,i,n),"ownClaims"),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 ft({channelName:e,onBecomeLeader:a(()=>{jc(s)},"onBecomeLeader"),onStopBeingLeader:a(()=>{qc(s)},"onStopBeingLeader"),onConnectionStatus:a((r,i)=>{Bc(s,r,i)},"onConnectionStatus"),onSubscriptionData:a((r,i,n,o,c,h)=>{jn(s,r,i,n,o,c,h)},"onSubscriptionData"),onLeaderClaimAnswered:a(()=>{Wc(s)},"onLeaderClaimAnswered"),onSubscriptionError:a((r,i,n,o)=>{qn(s,r,i,n,o)},"onSubscriptionError"),onSubscriptionSettled:a((r,i,n,o,c,h,u)=>{Bn(s,r,i,n,o,c,h,u)},"onSubscriptionSettled")})}async sendBatch(e,s){if(this.assertOpen(),!this.fetchImpl)throw new v("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(U(this.url,ms),{body:JSON.stringify({calls:e.map((c,h)=>({args:z(c.args??{},`args for batch call '${c.fn.__lunoraRef}'`),functionPath:c.fn.__lunoraRef,id:h,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 v("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`),r.headers)}let o=we(n);if(!r.ok||o!==void 0&&!n.results)throw o!==void 0?K(Se(o),r.headers):K(new v("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`),r.headers);for(let c of n.results??[]){let h=c.body?.commitCursor;typeof c.id=="number"&&typeof h=="number"&&this.recordShardCursor(e[c.id]?.shardKey,h)}return wc(n.results??[],e.length,r.headers)}async runMutation(e,s,r){this.assertOpen();let i=Gc(e,r),n=s,o=i.mutationId??kt();this.mutationIssueCounter+=1;let c=this.mutationIssueCounter,h=this.takeReplayCredential(i.replayCredential),u=this.composedBaselineFor(i.replayBaseline,i.shardKey);this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i);let{confirms:d,rollbacks:p}=this.applyOptimisticUpdates(e.__lunoraRef,n,i.shardKey,i.optimistic);this.applyOptionalOptimisticUpdate(i.optimisticUpdate,s,i.shardKey,p,d);let l=i.onlineOnly?void 0:this.offlineFlushes.get(b(i.shardKey));l!==void 0&&await l;let{httpFirst:f,midReconnect:y,shouldQueueOffline:m,socketDown:w}=this.writeQueueGate(i.shardKey),g=!i.onlineOnly&&m&&i.replayBaseline===void 0&&this.hasPendingWriteAhead(i.shardKey),k=a(async(S=!1)=>this.enqueueOfflineMutation(e,n,i.shardKey,u,o,p,d,S?void 0:i.precondition,i.mutationId,h?.stamp,S,c),"C");if(this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i,p),w||y||g)return k();let E;try{let S=await this.rpc(e.__lunoraRef,n,i.shardKey,{baselineSeq:u,captureBookmark:!0,...h?.flags,mutationId:o,onCommitCursor:a(I=>{E=I},"onCommitCursor")});for(let I of d)I(E);return{committed:!0,value:S}}catch(S){let I=rh(S,n),re=f&&m&&I,M=this.ownSocketOpen(i.shardKey);if(m&&!i.onlineOnly&&this.fetchImpl!==void 0&&!this.outbox&&i.replayBaseline===void 0&&(S instanceof TypeError||S instanceof D)&&Cs(n)){let P=k(!0);return this.noteHeldRetryDelay(i.shardKey),this.scheduleRateLimitedRetry(i.shardKey),P}throw this.settleFailedDirectWrite(S,E,d,p,h?.flags.authToken),nh(i.onlineOnly,re,I,M)?hi(e.__lunoraRef,S):S}}refuseOnlineOnlyWhenDown(e,s,r=[]){if(!s.onlineOnly)return;let i=this.writeQueueGate(s.shardKey);if(i.socketDown||i.midReconnect)throw he(r),hi(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,h=n||c,u=this.WebSocketImpl!==void 0&&h,d=i||r;return{httpFirst:d,midReconnect:o==="connecting"&&h&&!d,shouldQueueOffline:u,socketDown:o!=="open"&&!s&&u&&!d,socketOpen:o==="open"}}settleFailedDirectWrite(e,s,r,i,n){if(this.noteIdentityMismatch(e),n!==void 0&&this.noteReplayAuthRefusal(e,n),Ne(e)){for(let o of r)o(s);return}he(i)}async enqueueOfflineMutation(e,s,r,i,n,o,c,h,u,d,p,l){let f=d===void 0?this.identityFingerprint():d;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:u??`${this.clientId}:${String(y)}`,identity:f,mutationId:y,...o.length>0&&{onRejected:a(()=>{he(o)},"onRejected")},shardKey:r})}catch(m){throw he(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 w={ambiguousSend:p,args:s,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:n,issueSeq:l,clientId:this.clientId,identity:f,precondition:this.holdWhileUnanswered(h),onCommit:a(g=>{for(let k of c)k(g)},"onCommit"),reject:a(g=>{this.queuedIdentities.delete(n),Ne(g)||he(o),m(g instanceof Error?g:new Error(String(g))),this.releaseIdleShard(r)},"reject"),resolve:y,shardKey:r};this.offlineQueue.enqueue(w),this.queuedOfflineShardKeys.add(r),this.ensureSocket(r),w.id!==void 0&&this.queuedIdentities.set(w.id,f)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;let s=b(e);return this.offlineQueue.hasPending(r=>b(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=this.queryCacheEpoch,s=await this.queryCache.load();if(e!==this.queryCacheEpoch)return;let r=new Map;for(let i of this.subscriptions.all())r.set(ce(i.fn.__lunoraRef,i.argsKey,i.shardKey),i);for(let{key:i,...n}of s){if(us(this.persistenceVersion,n.version)){this.queryCache.remove(i).catch(()=>{});continue}let o=r.get(i);if(o&&this.cachedQueryMatchesIdentity(n)){this.seedSubscriptionFromCache(o,n);continue}this.hydratedQueryCache.set(i,n)}}catch{}}seedSubscriptionFromCache(e,s){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(s)||(e.serverBase=s.value,e.serverCursor=s.serverCursor,e.serverClaims=s.claims,s.serverEpoch!==void 0&&(e.serverEpoch=s.serverEpoch),this.cacheSeededQueries.set(ce(e.fn.__lunoraRef,e.argsKey,e.shardKey),s),W(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.serverBaseCommitted=!1,r.serverCursor=void 0,r.serverEpoch=void 0,W(r,void 0)),this.hydratedQueryCache.set(e,s)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,s,r){let i=ce(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=ce(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=ce(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,...e.serverClaims===void 0?{}:{claims:e.serverClaims},...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()],{queryCacheEpoch:r}=this;this.pendingCacheWrites.clear();let i=this.queryCacheChain.then(async()=>r===this.queryCacheEpoch?Promise.allSettled(s.map(async([n,o])=>e.put(n,o))):void 0);this.queryCacheChain=i.catch(()=>{}),await 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=b(e),r;for(let i of this.subscriptions.all())b(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=b(e),r=[];for(let c of this.subscriptions.all())b(c.shardKey)===s&&(Cs(c.args)?r.push(c):(this.markQueryRejected(c,!0),be(c,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"})));if(r.length===0)return this.probeOrigin();let i=xr(),n=this.identityFingerprint(),o;try{o=await ai(async c=>this.sendBatch(r.map(h=>({args:h.args,fn:h.fn,shardKey:h.shardKey})),c))}catch(c){return!(c instanceof TypeError)}if(this.identityFingerprint()!==n)return!0;for(let[c,h]of r.entries()){let u=o[c];if(u!==void 0){if(!u.ok){this.markQueryRejected(h,!0),be(h,{code:u.error.code,message:u.error.message});continue}this.handleDataMessage({data:N(u.value),id:h.id,type:"data"},i)}}return!0}async probeOrigin(){let{fetchImpl:e}=this;if(!e)return!1;try{return await ai(async s=>e(U(this.url,ms),{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=F.key(e,s,r),h=this.subscriptions.get(c);if(h){let u=lt(h,i);u&&(n.push(u.confirm),o.push(u.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:h}=$r(this.subscriptions,r);try{e(h,s)}catch{he(c);return}i.push(...c),n.push(...o)}getConnection(e){return this.connections.get(b(e))}sendOrQueueUnsubscribe(e,s,r){let i=this.getConnection(e);i&&!G(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(b(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=b(e),r=this.connections.get(s);return r||(r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:Oc({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:De(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=De(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},n,o=!1,c=a(()=>{o||this.closed||(n=setTimeout(l,r.next()))},"o"),h=a(m=>{o||this.WebSocketImpl===void 0||ni(i,this.wsUrlFor(s.shardKey,m,e),this.managedSocketOptions,{onClose:a(w=>{w?.code===4001&&this.notifyTokenExpired(),c(),s.onClose?.()},"onClose"),onMessage:s.onMessage,...s.onOpen===void 0?{}:{onOpen:s.onOpen},...s.offerBearer===!0?{protocols:this.upgradeProtocols()}:{}})},"c"),u=0,d,p=a(async m=>{let w=this.wsCredentialGeneration;u+=1;let g=u,k;d=w;try{k=await th(m,eh)}catch{g===u&&(d=void 0,c());return}if(g===u){if(d=void 0,w!==this.wsCredentialGeneration){l();return}h(k)}},"l"),l=a(()=>{if(o||this.WebSocketImpl===void 0)return;let{wsTicket:m}=this;if(typeof m=="function"){p(m).catch(()=>{});return}h(m)},"u");l();let f=a(()=>{o=!0,n!==void 0&&(clearTimeout(n),n=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),ke(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){d!==void 0&&d!==this.wsCredentialGeneration&&(u+=1,d=void 0,l());return}i.socket=void 0,i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),ke(i);try{m.close()}catch{}s.onClose?.(),c()},"v");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=Ue(this.wsUrl),r=s.pathname.endsWith(ys)?s.pathname.slice(0,-ys.length):s.pathname;return s.pathname=U(r,e),ns(s,this.wsUrl)}wsUrlFor(e,s,r=this.wsUrl){let i=Ue(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,h])=>`${encodeURIComponent(c)}=${encodeURIComponent(h)}`);return e!==void 0&&o.push(`shard=${encodeURIComponent(e)}`),s!==void 0&&o.push(`token=${encodeURIComponent(s)}`),i.search=o.join("&"),ns(i,r)}rpcRequestHeaders(e,s){let r={"content-type":"application/json"};e.expectSubject!==void 0&&(r[sc]=rc(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 D("LunoraClient: no `fetch` implementation available");let o=this.rpcRequestHeaders(i,r),c=i.authToken===void 0?this.authToken:i.authToken,h=JSON.stringify({args:z(s,`args for '${e}'`),functionPath:e,shardKey:r}),{body:u,response:d}=await oe(i.unbounded?0:this.rpcTimeoutMs,i.signal,async f=>{let y=await n(U(this.url,ei),{body:h,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=d.headers.get("x-d1-bookmark");f&&this.bookmark.set(f)}if(u===void 0)throw je(d.status,d.statusText,d.headers);let p=u;if(typeof p!="object"||p===null||Array.isArray(p))throw je(d.status,d.statusText,d.headers);let l=we(u);if(l!==void 0)throw hs(l,d.headers);if(!d.ok)throw je(d.status,d.statusText,d.headers);i.onMutationAck?.(u.lastMutationId),i.onCommitCursor?.(u.commitCursor),this.noteCredentialAccepted(c),this.learnDefaultShardKey(d,r),this.recordShardCursor(r,u.commitCursor);try{return T(u.result)}catch(f){throw K(St(f),d.headers)}}async adminFetch(e,s,r,i){if(!this.fetchImpl)throw new v("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 h=await this.fetchImpl(U(this.url,e),{body:c,headers:n,method:s}),u;try{u=await h.json()}catch{let p=h.statusText?` ${h.statusText}`:"";throw new v("INTERNAL",`LunoraClient: response was not JSON (status ${h.status.toString()}${p})`)}let d=we(u);if(d!==void 0)throw Se({...d,message:d.message??"admin request failed"});if(!h.ok){let p=h.statusText?` ${h.statusText}`:"";throw new v("INTERNAL",`LunoraClient: admin request failed (status ${h.status.toString()}${p})`)}return u}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(b(e.shardKey));G(e,{caps:Vc,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())b(s.shardKey)===b(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 oe(this.connectTimeoutMs,void 0,async()=>({session:await ws(this.wsToken),ticket:await ws(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(),e.ticketed=r.ticket!==void 0,e.upgradeBearer=this.authTokenOnUpgrade?this.authToken??void 0:void 0,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;ni(e,this.wsUrlFor(s,r.ticket),this.managedSocketOptions,{onClose:a(n=>{n?.code===4003&&e.polling.noteFailedOpen(),n?.code===pc&&n.reason===fc?e.retired!==!0&&!this.closed&&this.retireChangedClaims():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.reauthPending=!1,e.claims=void 0,e.heldFrames=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())b(c.shardKey)===b(s)&&this.queueResubscribe(c);if(this.resendShapeSubscriptions(s),e.pendingUnsubscribes.length>0){let c=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:h,type:u}of c)G(e,{id:h,type:u});this.releaseIdleShard(s)}Sc(e);let n=b(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),G(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(),ke(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",e.connectionId=void 0,e.heldFrames=void 0,e.whisperAck=void 0,this.dropWhisperJoinWaiters(b(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(!(b(n.shardKey)!==b(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 v("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=b(e);for(let i of this.subscriptions.all())b(i.shardKey)===r&&($(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())b(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=G(r,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...i?{sinceSeq:e.serverCursor}:{},...i&&e.serverClaims!==void 0?{sinceClaims:e.serverClaims}:{},...i&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"});return n&&$(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),bt(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):bt(s)},1e4))}sendShapeSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);s?.wsState==="open"&&G(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.serverCursor===void 0||e.serverClaims===void 0?{}:{sinceClaims:e.serverClaims},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,s){let r=kc(e);if(r===void 0)return;let i;try{i=JSON.parse(r)}catch{return}let n=this.getConnection(s);if(i.type!=="error"&&n?.reconnect.reset(),n&&typeof i.id=="string"&&this.settleSubscribeWatchdog(n,i.id),i.type==="batchStart")n&&(n.heldFrames=[]);else if(i.type==="batchEnd"){let o=n?.heldFrames;if(n&&o){let{socket:c}=n;n.heldFrames=void 0,ut(()=>{for(let h of o){if(n.retired===!0||n.socket!==c)break;this.dispatchServerMessage(h,s)}},()=>!this.closed)}}else n?.heldFrames&&Jc(i)?n.heldFrames.push(i):this.dispatchServerMessage(i,s)}dispatchServerMessage(e,s){switch(e.type){case"ack":{let r=this.subscriptions.getById(e.id);r&&this.ackAndAdvanceCursor(r,void 0,void 0);return}case"chunk":{let{data:r,generation:i,id:n,seq:o}=e,c=this.streams.get(n);c&&typeof o=="number"&&(c.lastSeq=o,typeof i=="number"&&(c.generation=i),c.durable=!0),c?.handle.push(T(r));return}case"complete":{this.handleCompleteMessage(e.id);return}case"data":case"delta":{this.withFrameClaims(s,()=>{this.handleDataMessage(e)});return}case"error":{this.handleErrorMessage(e,s);break}case"identity":{this.handleIdentityFrame(e,s),this.adoptSocketConnectionId(e,s),this.confirmShardIdentity(s);break}case"live":{this.dispatchLive(e,s);break}case"pokeEnd":{this.withFrameClaims(s,()=>{this.handlePokeEnd(e,s)});break}case"pokePart":{this.pokeAssembler.part(s,e);break}case"pokeStart":{this.pokeAssembler.start(s,e);break}case"resume":{this.withFrameClaims(s,()=>{this.handleResumeMessage(e)});break}case"settled":{this.handleSettledMessage(e);break}case"whisper":{this.dispatchWhisper(e,s);break}case"whisper_subscribed":{this.acknowledgeWhisperJoin(b(s),e.topic);break}}}handleErrorMessage(e,s){let r=e.error?.code;if(r==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}if(r==="STREAM_ID_IN_USE")return;let{id:i}=e,n=i===void 0?void 0:this.streams.get(i);if(n&&i!==void 0){n.handle.fail(Gr(e)),this.forgetStream(i);return}let o=i===void 0?void 0:this.subscriptions.getById(i);if(o){bt(o);let h=cs(e),u=this.identityFingerprint(),d=F.keyOf(o),p=this.getConnection(s)?.claims;this.markQueryRejected(o),be(o,h),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(d,h,u,p);return}let c=i===void 0?void 0:this.shapeSubscriptions.get(i);c&&(c.answered||(c.answered=!0,this.emitSyncStatus()),He(c.errorCallbacks,cs(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:$(e,"acked"),this.emitSyncStatus())}handlePokeEnd(e,s){let r=this.pokeAssembler.end(s,e.pokeId);if(r){Dc(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=Qc(e,s,r);if(e.answered!==i&&this.emitSyncStatus(),ci(e),n==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.serverClaims=this.frameClaims,e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){return $(e,"idle"),e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,this.emitSyncStatus(),this.sendSubscribeIfOpen(e)}handleDataMessage(e,s){let{id:r}=e,i=r?this.subscriptions.getById(r):void 0;if(!i||e.type==="data"&&Hc(i,e))return;let n,o=i.pendingDeltaRun;try{n=Hr(e,o===void 0?i.serverBase:o.payload)}catch(h){i.pendingDeltaRun=void 0,be(i,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription \u2014 ${h instanceof Error?h.message:String(h)}`}),this.settleAwaitedAnswer(i,!1);return}if(n===es){console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.resnapshotSubscription(i);return}if(Nc(e)){i.pendingDeltaRun={payload:n};return}i.pendingDeltaRun=void 0,this.dropCacheSeed(F.keyOf(i));let c=s!==void 0&&!i.valueReceived;if(Kn(i,n,{claims:this.frameClaims,cursor:e.cursor,epoch:e.epoch}),c&&(i.valueReceived=!0,this.emitSyncStatus()),e.lastMutationId!==void 0&&(Os(i,e.lastMutationId),Es(i,!0)),this.persistQueryValue(i),pt(i,i.serverCursor),s!==void 0&&Qr(i,s),W(i,n),this.tabCoordinator?.isLeader()){let h=F.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(h,n,i.serverCursor,i.serverEpoch,this.identityFingerprint(),i.serverClaims)}this.settleAwaitedAnswer(i,!0)}followerClaims(e,s,r){if(this.identityFingerprint()===null&&!this.identityUnresolved())return null;if(r==="")return(this.ownClaimsValue===void 0||this.ownClaimsValue!==null&&!this.claimsVerifiedAgainst.has(""))&&(this.claimsVerifiedAgainst.add(""),this.heldLeaderFrames.set(e,s),this.fetchOwnClaims()),this.ownClaimsValue;if(this.ownClaimsValue===void 0)this.heldLeaderFrames.set(e,s),this.fetchOwnClaims();else if(r!==void 0&&r!==this.ownClaimsValue&&!this.claimsVerifiedAgainst.has(r)){this.claimsVerifiedAgainst.add(r),this.heldLeaderFrames.set(e,s),this.fetchOwnClaims();return}return this.ownClaimsValue}isFollowerTab(){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()}resetOwnClaims(){this.ownClaimsValue=void 0,this.ownClaimsFetch=void 0,this.claimsVerifiedAgainst.clear(),this.stopOwnClaimsRetry(),this.suspendFollowerValues(),this.heldLeaderFrames.size>0&&queueMicrotask(()=>{this.fetchOwnClaims()})}suspendFollowerValues(){if(this.isFollowerTab())for(let e of this.subscriptions.all())e.serverClaims!==void 0&&e.serverBase!==void 0&&this.suspendedFollowerValues.set(e,{base:e.serverBase,claims:e.serverClaims,cursor:e.serverCursor,epoch:e.serverEpoch}),e.serverClaims!==void 0&&(e.serverBase=void 0,e.serverBaseCommitted=!1,e.serverCursor=void 0,e.serverClaims=void 0,W(e,void 0))}applyOwnClaims(e){e!==this.ownClaimsValue&&this.claimsVerifiedAgainst.clear(),this.ownClaimsValue=e,this.ownClaimsFailures=0;for(let[s,r]of this.suspendedFollowerValues)r.claims===e&&s.serverBase===void 0&&(s.serverBase=r.base,s.serverCursor=r.cursor,s.serverEpoch=r.epoch,s.serverClaims=e,W(s,r.base));this.suspendedFollowerValues.clear();for(let s of this.subscriptions.all())s.serverClaims!==void 0&&s.serverClaims!==e&&(s.serverBase=void 0,s.serverBaseCommitted=!1,s.serverCursor=void 0,s.serverClaims=void 0,W(s,void 0));this.dropClaimedEntries(e),this.releaseHeldFrames()}releaseHeldFrames(){let e=[...this.heldLeaderFrames.values()];this.heldLeaderFrames.clear();for(let s of e)s()}dropClaimedEntries(e){for(let s of[this.hydratedQueryCache,this.cacheSeededQueries])for(let[r,i]of s)if(i.claims!==void 0&&i.claims!==e){s.delete(r),this.pendingCacheWrites.delete(r);let{queryCache:n}=this;n&&(this.queryCacheChain=this.queryCacheChain.then(async()=>n.remove(r)).catch(()=>{}))}}fetchOwnClaims(){let{authToken:e,fetchImpl:s}=this;if(s===void 0||this.ownClaimsFetch!==void 0)return;let r=Ss(s,U(this.url,mc),"{}",e===null||!this.authTokenOnUpgrade?{"content-type":"application/json"}:{authorization:`Bearer ${e}`,"content-type":"application/json"}).then(({status:i,text:n})=>{let{claims:o}=JSON.parse(n);this.ownClaimsFetch===r&&(typeof o=="string"?this.applyOwnClaims(o):i===200&&(this.ownClaimsValue=null,this.releaseHeldFrames()))}).catch(()=>{this.ownClaimsFetch===r&&this.scheduleOwnClaimsRetry()}).finally(()=>{this.ownClaimsFetch===r&&(this.ownClaimsFetch=void 0)});this.ownClaimsFetch=r}scheduleOwnClaimsRetry(){if(this.closed||this.heldLeaderFrames.size===0||this.ownClaimsRetryTimer!==void 0||this.ownClaimsFailures>=Xc)return;let e=Zc*2**this.ownClaimsFailures;this.ownClaimsFailures+=1,this.ownClaimsRetryTimer=setTimeout(()=>{this.ownClaimsRetryTimer=void 0,this.fetchOwnClaims()},e)}stopOwnClaimsRetry(){clearTimeout(this.ownClaimsRetryTimer),this.ownClaimsRetryTimer=void 0,this.ownClaimsFailures=0}withFrameClaims(e,s){this.frameClaims=this.getConnection(e)?.claims;try{s()}finally{this.frameClaims=void 0}}handleResumeMessage(e){let s=this.subscriptions.getById(e.id);s&&(s.pendingDeltaRun=void 0,s.serverClaims=this.frameClaims,this.ackAndAdvanceCursor(s,e.cursor,e.epoch),this.tabCoordinator?.isLeader()&&s.serverBase!==void 0&&this.tabCoordinator.broadcastSubscriptionData(F.keyOf(s),s.serverBase,s.serverCursor,s.serverEpoch,this.identityFingerprint(),s.serverClaims),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&&Os(s,e.lastMutationId),Es(s),this.tabCoordinator?.isLeader())){let r=F.keyOf(s);this.tabCoordinator.broadcastSubscriptionSettled(r,s.serverCursor,s.serverEpoch,s.lastMutationId,this.clientId,this.identityFingerprint(),s.serverClaims)}}ackAndAdvanceCursor(e,s,r){let i=e.ack!=="acked";$(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),pt(e,e.serverCursor)&&W(e,e.serverBase))}adoptSocketConnectionId(e,s){let r=this.getConnection(s);if(r===void 0||typeof e.connectionId!="string")return;let i=r.connectionId===e.connectionId;r.connectionId=e.connectionId,r.claims=e.claims,r.whisperAck=e.whisperAck===!0,(!i||r.revalidateTimer===void 0&&r.reauthPending!==!0)&&this.armSocketRevalidation(r,e.revalidateMs);for(let n of this.liveSocketGrants.get(b(s))?.keys()??[])this.grantWhenJoined(s,n,e.connectionId)}grantWhenJoined(e,s,r){let i=b(e),n=this.liveSocketGrants.get(i)?.get(s);if(n===void 0)return;let{stream:o,topic:c}=n,h=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},u=>{this.refuseLiveGrant(e,s,u,r)})},"c");this.getConnection(e)?.whisperAck===!0?this.whenWhisperJoined(i,c,h):h()}sendWhisperJoin(e,s,r){let i=this.whisperJoinState(s,r);i.pending+=1,i.joined=!1,G(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()},Wn),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=b(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(()=>Ss(n,U(this.url,e),o,c)).then(({status:h})=>{h>=400&&h<500&&h!==404&&h!==401&&i?.(h)}).catch(()=>{})}dispatchLive(e,s){let r=this.liveSocketGrants.get(b(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(b(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&&($(r,"idle"),this.emitSyncStatus(),be(r,{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()||e.claims!==void 0&&e.claims!==this.ownClaimsValue&&(this.ownClaimsValue!==void 0||this.isFollowerTab())?!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&&Ke(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&&G(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(b(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,h]of i)o.set(c,h)}clearQueryCacheForIdentityChange(){this.revokeCacheSeededValues(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCacheEpoch+=1;let{queryCache:e}=this;e&&(this.queryCacheChain=this.queryCacheChain.then(async()=>e.clear()).catch(()=>{}))}evictPreviousIdentitySession(){this.resetOwnClaims(),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.serverBaseCommitted=!1,e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,$(e,"idle"),e.valueReceived=!1,W(e,void 0);for(let e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,e.answered=!1,ci(e);this.emitSyncStatus(),this.bounceShardSockets()}bounceShardSockets(e=!1){let{authToken:s,fetchImpl:r}=this;for(let i of this.connections.values()){let{connectionId:n}=i;e&&s!==null&&r!==void 0&&i.socket!==void 0&&n!==void 0&&i.retired!==!0?this.reauthenticateShardSocket(i,n,s):this.bounceShardSocket(i)}for(let i of this.supplementaryBounces)i()}retireChangedClaims(){if(this.clearQueryCacheForIdentityChange(),this.evictPreviousIdentitySession(),this.tabCoordinator?.isLeader())for(let e of this.subscriptions.all())this.tabCoordinator.broadcastSubscriptionData(F.keyOf(e),void 0,void 0,void 0,this.identityFingerprint())}reauthenticateShardSocket(e,s,r){let{authToken:i,fetchImpl:n}=this,{socket:o}=e;if(n===void 0)return;let c=(e.reauthAttempt??0)+1;clearTimeout(e.revalidateTimer),e.revalidateTimer=void 0,e.reauthAttempt=c,e.reauthPending=!0,(e.ticketed===!0?oe(this.connectTimeoutMs,void 0,async()=>ws(this.wsTicket),()=>new Error("LunoraClient: ws ticket provider timed out")).catch(()=>{}):Promise.resolve(void 0)).then(async h=>Ss(n,U(this.url,sh(e.shardKey,h)),JSON.stringify({connectionId:s}),r===null?{"content-type":"application/json"}:{authorization:`Bearer ${r}`,"content-type":"application/json"})).then(({text:h})=>{let u=JSON.parse(h);return u?.ok===!0?"ok":u?.error?.code==="IDENTITY_CHANGED"?"changed":"refused"}).catch(()=>"refused").then(h=>{e.reauthAttempt===c&&(e.reauthPending=!1,!(this.closed||r!==null&&this.authToken!==i||e.connectionId!==s||e.socket!==o||e.retired===!0)&&(h==="ok"?(e.upgradeBearer=r??e.upgradeBearer,this.armSocketRevalidation(e,e.revalidateMs)):h==="changed"?this.retireChangedClaims():this.bounceShardSocket(e)))}).catch(()=>{})}armSocketRevalidation(e,s){clearTimeout(e.revalidateTimer),e.revalidateTimer=void 0,e.revalidateMs=typeof s=="number"&&s>0?s:void 0,e.revalidateMs!==void 0&&(e.revalidateTimer=setTimeout(()=>{e.revalidateTimer=void 0;let r=e.upgradeBearer??(e.sessionToken===void 0?null:this.authToken??void 0);r!==void 0&&e.connectionId!==void 0&&e.socket!==void 0&&e.retired!==!0&&this.reauthenticateShardSocket(e,e.connectionId,r)},e.revalidateMs/2))}bounceShardSocket(e){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)})}flushAllOfflineQueues(){for(let e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){let s=b(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&&Ke(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=fs(e),r=s&&this.subscriptions.get(F.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=fs(e);if(e===void 0||s===void 0)return e;let r=a(()=>this.snapshotAnswer(e)!==void 0||e(),"s");return ps(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(b(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 d of r){this.unpersist(d.id),this.queuedIdentities.delete(d.id??"");let p=new Error("offline mutation skipped: precondition failed before replay");p.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(d,"rejected",p)}let i=b(e),n=this.holdUndecidedWrites(i,this.offlineQueue.drain(d=>b(d.shardKey)===i));if(n.length===0)return;let o=[],c=[];for(let d of n){let p=this.replayGateVerdict(d);p==="send"?o.push(d):p==="hold"&&c.push(d)}if(this.offlineQueue.requeue(c),c.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),o.length===0){this.scheduleRateLimitedRetry(e);return}let h=this.encodableOrSettleTerminal(o);if(h.length===0){this.scheduleRateLimitedRetry(e);return}if(h.length===1){await this.replaySequential(h,e,s),this.scheduleRateLimitedRetry(e);return}let u=[];for(let d=0;d<h.length;d+=vs){let p=h.slice(d,d+vs),l=await this.replayBatched(p,e,s);if(u.push(...l.requeue),l.stop||l.requeue.length>0){u.push(...h.slice(d+vs));break}}u.length>0&&this.offlineQueue.requeue(u),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){let s=b(e),r=this.replayRetryState.get(s),i=(r?.attempts??0)+1;this.replayRetryState.set(s,{attempts:i,delayMs:Math.max(r?.delayMs??0,ks(i))})}noteReplayRetryDelay(e,s,r){let i=b(e),n=this.replayRetryState.get(i),o=(n?.attempts??0)+1,c=Fc(s,o)??(r===null&&_e(s)?ks(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=b(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{z(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)||oi(e)}noteReplayAuthRefusal(e,s){if(!_e(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,...gs(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||_e(s)||r==="RATE_LIMITED"||r==="TOO_MANY_REQUESTS"||(s instanceof TypeError||s instanceof D)&&ih()||!oi(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,...gs(n.identity,r),mutationId:n.id,onCommitCursor:a(h=>{o=h},"onCommitCursor")});this.settleReplaySuccess(n,c,o)}catch(c){if(Ne(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((u,d)=>({args:z(u.args,`args for '${u.functionPath}'`),baselineSeq:u.baselineSeq,functionPath:u.functionPath,id:d,clientId:u.clientId??this.clientId,mutationId:u.id,shardKey:u.shardKey}))});if(e.length>1&&Lc(i)>Pc)return await this.replayBatchedHalves(e,s,r);let{fetchImpl:n}=this,o,c;try{({payload:c,response:o}=await oe(this.rpcTimeoutMs,void 0,async u=>{let d=await n(U(this.url,ms),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:r,...gs(e.find(p=>p.identity!==void 0)?.identity,r)}),method:"POST",signal:u});if(d.status===413&&e.length>1)return{payload:void 0,response:d};try{return{payload:await d.json(),response:d}}catch{return{payload:void 0,response:d}}}))}catch(u){return this.noteReplayRetryDelay(s,u,r),{requeue:this.keepUnexhaustedAmbiguousWrites(e,u),stop:!0}}let h=o.headers.get("x-d1-bookmark");if(h&&this.bookmark.set(h),o.status===413&&e.length>1)return await this.replayBatchedHalves(e,s,r);if(!c)return this.settleWholeBatchError(e,je(o.status,o.statusText,o.headers),s,r);if(!Array.isArray(c.results)){let u=we(c),d=u===void 0?je(o.status,o.statusText,o.headers):hs(u,o.headers);return this.settleWholeBatchError(e,d,s,r)}return{requeue:this.settleReplayBatchSlots(e,c.results,s,r,o.headers),stop:!1}}settleWholeBatchError(e,s,r,i){if(s instanceof D||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=Mc(s),c=[],h=!1,u=!1;for(let[d,p]of e.entries()){let l=xc(o.get(d),n);switch(l.kind){case"committed":{h=!0,this.settleReplaySuccess(p,l.value,l.commitCursor);break}case"errored":{u||=_e(l.error),this.shouldRequeueReplayFailure(l.error,i)&&!this.spendsLastReplayAttempt(p,l.error)?(this.noteReplayRetryDelay(r,l.error,i),c.push(p)):this.settleReplayTerminal(p,l.error);break}case"unanswered":{let f=K(os(),n);if(this.spendsLastReplayAttempt(p,f)){this.settleReplayTerminal(p,f);break}this.noteReplayRetryDelay(r,f,i),c.push(p);break}default:h=!0,this.settleReplayUndecodable(p,l.error,l.commitCursor)}}return h&&!u&&this.noteCredentialAccepted(i),c}};var ch=a(async t=>(t.assertOpen(),(await t.adminFetch(Et,"GET")).tokens??[]),"Lt"),hh=a(async(t,e)=>(t.assertOpen(),await t.adminFetch(Et,"POST",e)),"Vt"),dh=a(async(t,e)=>{t.assertOpen(),await t.adminFetch(L(Et,{name:e}),"DELETE")},"Dt"),uh=a(async t=>(t.assertOpen(),(await t.adminFetch(fi,"GET")).functions??[]),"Kt"),lh=a(async t=>(t.assertOpen(),(await t.adminFetch(mi,"GET")).jobs??[]),"Bt"),ph=a(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(yi,"POST",{name:e});return{name:s.name??e,ran:s.ran===!0}},"Jt"),fh=a(async t=>(t.assertOpen(),await t.adminFetch(gi,"GET")),"xt"),mh=a(async t=>(t.assertOpen(),await t.adminFetch(vi,"GET")),"$t"),yh=a(async t=>(t.assertOpen(),await t.adminFetch(bi,"GET")),"Wt"),vh=a(async t=>(t.assertOpen(),await t.adminFetch(wi,"GET")),"zt"),gh=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(N(e.filters))),T(await t.adminFetch(`${Si}?${s.toString()}`,"GET"))},"jt"),bh=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(N(e.filters))),T(await t.adminFetch(`${Ci}?${s.toString()}`,"GET"))},"qt"),wh=a(async t=>(t.assertOpen(),(await t.adminFetch(Ei,"GET")).namespaces??[]),"Qt"),Sh=a(async(t,e)=>{t.assertOpen();let s=L(Ii,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await t.adminFetch(s,"GET")},"Yt"),Ch=a(async(t,e)=>{t.assertOpen();let s=L(It,{key:e.key,namespace:e.namespace});return await t.adminFetch(s,"GET")},"Xt"),kh=a(async(t,e)=>{t.assertOpen(),await t.adminFetch(It,"PUT",e)},"Zt"),Th=a(async(t,e)=>{t.assertOpen();let s=L(It,{key:e.key,namespace:e.namespace});await t.adminFetch(s,"DELETE")},"ta"),Oh=a(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(di,"POST",{table:e});return{failed:s.failed??0,ok:s.ok??0,shards:s.shards??[]}},"aa"),Eh=a(async(t,e={})=>{t.assertOpen();let s=await t.adminFetch(Oi,"POST",e);return{nextCursor:s.nextCursor,rows:s.rows??[]}},"sa"),Ih=a(async(t,e={})=>{t.assertOpen();let s=L(Ot,{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??[]}},"ea"),Rh=a(async(t,e,s)=>{t.assertOpen();let r=`${Ot}?key=${encodeURIComponent(e)}${gt(s?.bucket)}`,i=await t.adminFetch(r,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}},"na"),Ah=a(async t=>(t.assertOpen(),(await t.adminFetch(pi,"GET")).buckets??[]),"ia"),Fh=a(async(t,e)=>{t.assertOpen();let s=`${Ot}?key=${encodeURIComponent(e.key)}${gt(e.bucket)}`,r=await t.adminFetch(s,"PUT",e.body,e.contentType);return{etag:r.etag,key:r.key??e.key}},"ra"),Ph=a(async(t,e,s)=>{t.assertOpen();let r=s?.expiresInSeconds,i=r===void 0?"":`&expiresIn=${encodeURIComponent(r.toString())}`,n=`${li}?key=${encodeURIComponent(e)}${i}${gt(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},"ca"),Lh=a(async t=>(t.assertOpen(),(await t.adminFetch(ki,"GET")).indexes??[]),"oa"),Mh=a(async(t,e)=>(t.assertOpen(),(await t.adminFetch(Ti,"POST",e)).matches??[]),"da"),Rs=class extends Tt{static{a(this,"Ha")}async shardTraffic(e){return Oh(this.adminHost,e)}async getDeploymentPause(){return En(this.adminHost)}async setDeploymentPause(e,s){return In(this.adminHost,e,s)}async listScheduledJobs(){return Cn(this.adminHost)}async schedulerStatus(){return Rn(this.adminHost)}async getScheduledJob(e){return kn(this.adminHost,e)}async listScheduledHistory(e={}){return Tn(this.adminHost,e)}async listCronRuns(){return On(this.adminHost)}async cancelScheduledJob(e){return An(this.adminHost,e)}async listDeadJobs(){return Fn(this.adminHost)}async retryDeadJob(e){return Pn(this.adminHost,e)}async removeDeadJob(e){return Ln(this.adminHost,e)}async listWorkflowInstances(e){return Mn(this.adminHost,e)}async getWorkflowInstance(e){return xn(this.adminHost,e)}async createWorkflowInstance(e){return _n(this.adminHost,e)}async sendWorkflowEvent(e){return Qn(this.adminHost,e)}async setWorkflowInstanceStatus(e){return Dn(this.adminHost,e)}async listFunctions(){return uh(this.adminHost)}async getCronJobs(){return lh(this.adminHost)}async runCronJob(e){return ph(this.adminHost,e)}async fetchOpenApi(){return fh(this.adminHost)}async fetchArchitecture(){return mh(this.adminHost)}async fetchOpenRpc(){return yh(this.adminHost)}async listStorageObjects(e={}){return Ih(this.adminHost,e)}async deleteStorageObject(e,s){return Rh(this.adminHost,e,s)}async listStorageBuckets(){return Ah(this.adminHost)}async uploadStorageObject(e){return Fh(this.adminHost,e)}async signedStorageUrl(e,s){return Ph(this.adminHost,e,s)}async listGlobalTables(){return vh(this.adminHost)}async readGlobalTablePage(e){return gh(this.adminHost,e)}async facetGlobalColumn(e){return bh(this.adminHost,e)}async listVectorIndexes(){return Lh(this.adminHost)}async queryVectorIndex(e){return Mh(this.adminHost,e)}async queryLogArchive(e={}){return Eh(this.adminHost,e)}async listAdminTokens(){return ch(this.adminHost)}async createAdminToken(e){return hh(this.adminHost,e)}async revokeAdminToken(e){return dh(this.adminHost,e)}async listKvNamespaces(){return wh(this.adminHost)}async listKvKeys(e){return Sh(this.adminHost,e)}async getKvValue(e){return Ch(this.adminHost,e)}async putKvValue(e){return kh(this.adminHost,e)}async deleteKvKey(e){return Th(this.adminHost,e)}async listAuthUsers(e={}){this.adminHost.assertOpen();let s=L(Ri,{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.adminHost.adminFetch(s,"GET")}async createAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Fi,"POST",e)}async setAuthUserRole(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Pi,"POST",e)}async banAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Li,"POST",e)}async unbanAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Mi,"POST",e)}async setAuthUserPassword(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(xi,"POST",e)}async removeAuthUser(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(_i,"POST",e)}async impersonateAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Qi,"POST",e)}async revokeAuthSession(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Di,"POST",e)}async revokeAuthUserSessions(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ui,"POST",e)}async getAuthCapabilities(){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Hi,"GET")}async updateAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ni,"POST",e)}async listAuthAccounts(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(L(Ki,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(ji,"POST",e)}async listAuthPasskeys(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(L(qi,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Bi,"POST",e)}async disableAuthTwoFactor(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Wi,"POST",e)}async listAuthOrganizations(e={}){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(L($i,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.adminHost.assertOpen();let s=L(zi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminHost.adminFetch(s,"GET")}async listAuthOrgInvitations(e){this.adminHost.assertOpen();let s=L(Gi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminHost.adminFetch(s,"GET")}async listAuthSignUpInvitations(e={}){this.adminHost.assertOpen();let s=L(Xi,{limit:e.limit,offset:e.offset});return await this.adminHost.adminFetch(s,"GET")}async createAuthSignUpInvitation(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Zi,"POST",e)}async revokeAuthSignUpInvitation(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(en,"POST",e)}async removeAuthOrgMember(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Vi,"POST",e)}async cancelAuthOrgInvitation(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ji,"POST",e)}async getAuthConfig(){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Yi,"GET")}async createAuthOrganization(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(tn,"POST",e)}async updateAuthOrganization(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(sn,"POST",e)}async deleteAuthOrganization(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(rn,"POST",e)}async addAuthOrgMember(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(nn,"POST",e)}async inviteAuthOrgMember(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(an,"POST",e)}async setAuthOrgMemberRole(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(on,"POST",e)}async listAuthOrgTeams(e){this.adminHost.assertOpen();let s=L(cn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminHost.adminFetch(s,"GET")}async createAuthOrgTeam(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(hn,"POST",e)}async updateAuthOrgTeam(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(dn,"POST",e)}async removeAuthOrgTeam(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(un,"POST",e)}async listAuthOrgTeamMembers(e){this.adminHost.assertOpen();let s=L(ln,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminHost.adminFetch(s,"GET")}async addAuthOrgTeamMember(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(pn,"POST",e)}async removeAuthOrgTeamMember(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(fn,"POST",e)}async listAuthOrgRoles(e){this.adminHost.assertOpen();let s=L(mn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminHost.adminFetch(s,"GET")}async createAuthOrgRole(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(yn,"POST",e)}async updateAuthOrgRole(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(vn,"POST",e)}async deleteAuthOrgRole(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(gn,"POST",e)}async listAuthSessions(e={}){this.adminHost.assertOpen();let s=L(Ai,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminHost.adminFetch(s,"GET")}},As=a(t=>"listAuthUsers"in t,"Aa");var $n=H(xs(),1),zn=H(ie(),1);var xh=a(()=>{let t=(0,$n.c)(4),e=xe(),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,zn.useSyncExternalStore)(s,r,i)},"S");var Vf=a(()=>{let t=xe();if(!As(t))throw new v("INTERNAL","The Studio needs a LunoraAdminClient (`@lunora/client/admin`), not a plain LunoraClient.");return t},"a");export{Ee as a,Mt as b,N as c,T as d,Oa as e,Rs as f,Fa as g,Re as h,Na as i,Ka as j,$a as k,xe as l,xh as m,Vf as n};
|