@lunora/studio 1.0.0-alpha.360 → 1.0.0-alpha.362
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 +4 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.mjs +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 +24 -9
- 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 -0
- package/dist/packem_chunks/ai-usage-panel.mjs +1 -1
- package/dist/packem_chunks/assistant-panel.mjs +3 -0
- 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/log-drains-panel.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-DUXsXId1.mjs +1 -0
- package/dist/packem_shared/{ApiDocsPanel-DD2Uns6b.mjs → ApiDocsPanel-B9S9l1Ce.mjs} +1 -1
- package/dist/packem_shared/{DataBrowser-CVRWnNWu.mjs → DataBrowser-Dm-jhIUP.mjs} +2 -2
- package/dist/packem_shared/{GlobalDataBrowser-DC47T6Zl.mjs → GlobalDataBrowser-C1Y8GUhe.mjs} +1 -1
- package/dist/packem_shared/{HomePanel-D12HxHQo.mjs → HomePanel-B5ytwPIo.mjs} +1 -1
- package/dist/packem_shared/{MigrationsPanel-DMkxSXNl.mjs → MigrationsPanel-CwLikxDT.mjs} +1 -1
- package/dist/packem_shared/Studio-B89ZNMOD.mjs +1 -0
- package/dist/packem_shared/{StudioApp-isdWpF9P.mjs → StudioApp-C9l1a3A8.mjs} +1 -1
- package/dist/packem_shared/advisor-view-CzieqKMe.mjs +5 -0
- package/dist/packem_shared/assistant-provider-Bp72uWsq.mjs +1 -0
- package/dist/packem_shared/assistant-reason-D6EwMCxT.mjs +1 -0
- package/dist/packem_shared/{cf-links-CBJ5SywP.mjs → cf-links-C4DVTr8A.mjs} +1 -1
- package/dist/packem_shared/error-alert-DKXm5h19.mjs +6 -0
- package/dist/packem_shared/{home-panel-CDVTuTF8.mjs → home-panel-5fGktYeD.mjs} +1 -1
- package/dist/packem_shared/recording-client-z4CBi0y8.mjs +1 -0
- package/dist/packem_shared/studio-gZfpz1wC.mjs +2 -0
- package/dist/packem_shared/{table-list-sidebar-CNadcIgG.mjs → table-list-sidebar-kpHaDWjy.mjs} +1 -1
- package/dist/packem_shared/use-assistant-rpc-GCUK2zPa.mjs +1 -0
- package/dist/standalone/chunk-2DT3QG6Q.js +1 -0
- package/dist/standalone/chunk-2EB7FN5S.js +1 -0
- package/dist/standalone/chunk-2FTGLXYA.js +1 -0
- package/dist/standalone/chunk-2H6VLY2M.js +1 -0
- package/dist/standalone/chunk-2NGKUO32.js +1 -0
- package/dist/standalone/chunk-2SNHKJXK.js +1 -0
- package/dist/standalone/chunk-2W4UO5BC.js +1 -0
- package/dist/standalone/{chunk-SLIDAWNX.js → chunk-3D67ZJRW.js} +1 -1
- package/dist/standalone/chunk-3RZD6VJ7.js +1 -0
- package/dist/standalone/chunk-3X3NXJBR.js +1 -0
- package/dist/standalone/chunk-4EPW63HS.js +1 -0
- package/dist/standalone/{chunk-WS36BO4R.js → chunk-4NKJV7YX.js} +1 -1
- package/dist/standalone/chunk-4PI2OSSP.js +1 -0
- package/dist/standalone/chunk-53CGUTRT.js +1 -0
- package/dist/standalone/chunk-5EWIOOBI.js +1 -0
- package/dist/standalone/chunk-5GYHGDIF.js +8 -0
- package/dist/standalone/chunk-5NIQHOPN.js +1 -0
- package/dist/standalone/chunk-5O7ICPWV.js +1 -0
- package/dist/standalone/chunk-5PEAXTYQ.js +1 -0
- package/dist/standalone/{chunk-O2NMPIV2.js → chunk-5WNGRT7N.js} +1 -1
- package/dist/standalone/chunk-66BMMNUR.js +1 -0
- package/dist/standalone/chunk-66LYVBXB.js +1 -0
- package/dist/standalone/chunk-6FPV3EK2.js +1 -0
- package/dist/standalone/chunk-6G3E4PJ2.js +1 -0
- package/dist/standalone/chunk-6KE7ILEZ.js +1 -0
- package/dist/standalone/chunk-7KJCRT4B.js +1 -0
- package/dist/standalone/chunk-7O5SGABV.js +1 -0
- package/dist/standalone/chunk-7QEZ2SFW.js +1 -0
- package/dist/standalone/chunk-7WV3EPE6.js +1 -0
- package/dist/standalone/chunk-A2Q3TGIQ.js +1 -0
- package/dist/standalone/chunk-ABMHWBYA.js +1 -0
- package/dist/standalone/chunk-AEU3EF4T.js +1 -0
- package/dist/standalone/chunk-ALQHMFOC.js +1 -0
- package/dist/standalone/chunk-AZIKM5BA.js +1 -0
- package/dist/standalone/chunk-BCUOQNI2.js +1 -0
- package/dist/standalone/chunk-BG2CJOVS.js +1 -0
- package/dist/standalone/chunk-BKI3JMXQ.js +1 -0
- package/dist/standalone/chunk-BO5NNWMO.js +1 -0
- package/dist/standalone/chunk-BX7TFVCC.js +1 -0
- package/dist/standalone/chunk-CKEQX655.js +1 -0
- package/dist/standalone/{chunk-DX55P3KZ.js → chunk-CL3JOU6F.js} +1 -1
- package/dist/standalone/chunk-COLSZPCE.js +1 -0
- package/dist/standalone/chunk-CVSIFPI5.js +1 -0
- package/dist/standalone/chunk-D65UVZIA.js +1 -0
- package/dist/standalone/{chunk-DBVJ5VLI.js → chunk-DA2CAFXI.js} +1 -1
- package/dist/standalone/chunk-DB6QX4X6.js +1 -0
- package/dist/standalone/{chunk-7ZIYHKLX.js → chunk-E2FFHKGI.js} +3 -3
- package/dist/standalone/chunk-EE2COWFF.js +1 -0
- package/dist/standalone/chunk-ELSQ4FVH.js +1 -0
- package/dist/standalone/chunk-EXFERMUT.js +1 -0
- package/dist/standalone/chunk-FACXM2UB.js +7 -0
- package/dist/standalone/chunk-FBDIQ67D.js +1 -0
- package/dist/standalone/chunk-FHLODLBC.js +1 -0
- package/dist/standalone/chunk-FQEZUQ36.js +1 -0
- package/dist/standalone/{chunk-VEWQWS3J.js → chunk-FWM5Z6CH.js} +1 -1
- package/dist/standalone/chunk-GC3GKGWD.js +1 -0
- package/dist/standalone/chunk-GJXCPZDN.js +1 -0
- package/dist/standalone/chunk-GNI37YCV.js +33 -0
- package/dist/standalone/chunk-GVZ3VFGG.js +1 -0
- package/dist/standalone/chunk-GWNGVKLG.js +1 -0
- package/dist/standalone/chunk-GXTSE66Z.js +1 -0
- package/dist/standalone/chunk-H7BQUL7D.js +1 -0
- package/dist/standalone/chunk-HCCQTUHS.js +1 -0
- package/dist/standalone/chunk-HCOF7HOM.js +1 -0
- package/dist/standalone/chunk-HZDLUAWS.js +1 -0
- package/dist/standalone/chunk-IDZLHZIA.js +1 -0
- package/dist/standalone/{chunk-SU5DTRGK.js → chunk-IHGRWY3Y.js} +1 -1
- package/dist/standalone/chunk-IUGNIG6L.js +6 -0
- package/dist/standalone/chunk-J3BZWYJQ.js +1 -0
- package/dist/standalone/chunk-J45HAKBU.js +1 -0
- package/dist/standalone/chunk-J4PQAVOF.js +1 -0
- package/dist/standalone/chunk-J6FR2B77.js +1 -0
- package/dist/standalone/chunk-J6XQKD2F.js +1 -0
- package/dist/standalone/chunk-JCRFMCNP.js +1 -0
- package/dist/standalone/chunk-JD6PRRFO.js +1 -0
- package/dist/standalone/chunk-JENPPZFV.js +1 -0
- package/dist/standalone/chunk-JHTL3QHW.js +1 -0
- package/dist/standalone/chunk-JOPNP4EO.js +1 -0
- package/dist/standalone/chunk-JVP3TR3A.js +1 -0
- package/dist/standalone/chunk-KGLIQIZU.js +1 -0
- package/dist/standalone/{chunk-ONWGX5Y4.js → chunk-KH6OXCG3.js} +1 -1
- package/dist/standalone/{chunk-3FS22LNI.js → chunk-L26RMC2W.js} +3 -3
- package/dist/standalone/chunk-L2FYX4FN.js +1 -0
- package/dist/standalone/{chunk-XIRKBJPD.js → chunk-LPFUEJZ4.js} +5 -5
- package/dist/standalone/chunk-LSEUUZN4.js +1 -0
- package/dist/standalone/{chunk-BYOGQ2IV.js → chunk-MJTVTUNI.js} +2 -2
- package/dist/standalone/chunk-MQTI3STP.js +1 -0
- package/dist/standalone/chunk-N7WQJPOM.js +1 -0
- package/dist/standalone/chunk-NF2Q75WM.js +1 -0
- package/dist/standalone/chunk-NGZNXNRD.js +1 -0
- package/dist/standalone/chunk-O3AZ7JKE.js +1 -0
- package/dist/standalone/chunk-OK2QU2EV.js +1 -0
- package/dist/standalone/{chunk-IH2CJZF2.js → chunk-ONTGYVAN.js} +1 -1
- package/dist/standalone/chunk-OP4QEV27.js +1 -0
- package/dist/standalone/chunk-OPIMGKWU.js +1 -0
- package/dist/standalone/chunk-OWRKSQPE.js +1 -0
- package/dist/standalone/chunk-P5EVJEGC.js +1 -0
- package/dist/standalone/chunk-PAZKX7I6.js +1 -0
- package/dist/standalone/chunk-PDBW6GTJ.js +1 -0
- package/dist/standalone/chunk-PJUVJTDR.js +1 -0
- package/dist/standalone/chunk-Q2J73V2C.js +2 -0
- package/dist/standalone/chunk-Q2KL457J.js +1 -0
- package/dist/standalone/chunk-QAOZXPLU.js +1 -0
- package/dist/standalone/{chunk-3PAYDWHN.js → chunk-QEFLZBT7.js} +2 -2
- package/dist/standalone/chunk-QKUVJIRX.js +1 -0
- package/dist/standalone/chunk-QNM2J7MG.js +1 -0
- package/dist/standalone/chunk-QRA7AKYO.js +1 -0
- package/dist/standalone/chunk-RCXNYW7P.js +1 -0
- package/dist/standalone/chunk-RE7GRXBM.js +1 -0
- package/dist/standalone/{chunk-TDVDZ7XQ.js → chunk-RIAOZECW.js} +1 -1
- package/dist/standalone/{chunk-LUHXNZI4.js → chunk-RTS5G3ET.js} +1 -1
- package/dist/standalone/chunk-S36FVTKK.js +1 -0
- package/dist/standalone/chunk-SR6CPTRT.js +1 -0
- package/dist/standalone/chunk-T3ZCW3RG.js +1 -0
- package/dist/standalone/chunk-TKBTZX4K.js +1 -0
- package/dist/standalone/chunk-TMWKF4XM.js +5 -0
- package/dist/standalone/chunk-TW4O2BA5.js +159 -0
- package/dist/standalone/chunk-UD5REVU2.js +1 -0
- package/dist/standalone/{chunk-PQH2LSJX.js → chunk-UQA2AJGI.js} +1 -1
- package/dist/standalone/chunk-UW6QNC74.js +3 -0
- package/dist/standalone/chunk-UXBNXITB.js +1 -0
- package/dist/standalone/chunk-UZ2ZXB74.js +1 -0
- package/dist/standalone/chunk-V3BE427M.js +1 -0
- package/dist/standalone/chunk-VHPTPEZ4.js +1 -0
- package/dist/standalone/chunk-W4LJQYCI.js +1 -0
- package/dist/standalone/chunk-WADY55J2.js +30 -0
- package/dist/standalone/chunk-WCWP4EAW.js +1 -0
- package/dist/standalone/chunk-X54WR7FF.js +1 -0
- package/dist/standalone/chunk-XWWQIAF6.js +1 -0
- package/dist/standalone/{chunk-SYGCASPT.js → chunk-Y2YLTUMD.js} +1 -1
- package/dist/standalone/chunk-YEVTA35E.js +1 -0
- package/dist/standalone/{chunk-R36QXQZX.js → chunk-YORPLSI5.js} +1 -1
- package/dist/standalone/chunk-YX2N5PJW.js +1 -0
- package/dist/standalone/chunk-Z57KMMOK.js +1 -0
- package/dist/standalone/chunk-ZFQ253FX.js +1 -0
- package/dist/standalone/chunk-ZG3IUVQ2.js +1 -0
- package/dist/standalone/chunk-ZKEYRU5C.js +1 -0
- package/dist/standalone/{chunk-5R2YO7HF.js → chunk-ZOKSVUID.js} +4 -4
- package/dist/standalone/{chunk-H7HZ42JY.js → chunk-ZPQBVYNN.js} +1 -1
- package/dist/standalone/chunk-ZSLKFLWE.js +1 -0
- package/dist/standalone/chunk-ZSWW2UGP.js +1 -0
- package/dist/standalone/studio.js +2 -2
- package/dist/styles.css +1 -1
- package/package.json +7 -6
- package/dist/packem_shared/ADMIN_FUNCTIONS-4aGsMs95.mjs +0 -1
- package/dist/packem_shared/Studio-MA8kKZLu.mjs +0 -1
- package/dist/packem_shared/advisor-view-tBumWci_.mjs +0 -1
- package/dist/packem_shared/error-alert-C0R39DO1.mjs +0 -1
- package/dist/packem_shared/recording-client-DAipTA_n.mjs +0 -1
- package/dist/packem_shared/studio-UhUrPz5J.mjs +0 -2
- package/dist/packem_shared/use-sql-assistant-rZPs3LC3.mjs +0 -1
- package/dist/standalone/chunk-2AH4ABE5.js +0 -1
- package/dist/standalone/chunk-2G57ENH5.js +0 -1
- package/dist/standalone/chunk-3GXPALXG.js +0 -1
- package/dist/standalone/chunk-3GYLOE4V.js +0 -1
- package/dist/standalone/chunk-473JK2PQ.js +0 -1
- package/dist/standalone/chunk-4C4THJUD.js +0 -1
- package/dist/standalone/chunk-4DAKKAK7.js +0 -1
- package/dist/standalone/chunk-4M57OYFX.js +0 -1
- package/dist/standalone/chunk-4SQBAPY6.js +0 -1
- package/dist/standalone/chunk-5DNGK3NT.js +0 -1
- package/dist/standalone/chunk-5GIQ6C5N.js +0 -1
- package/dist/standalone/chunk-5WJG7FMH.js +0 -1
- package/dist/standalone/chunk-63KDHS3H.js +0 -1
- package/dist/standalone/chunk-6B6ARRMI.js +0 -1
- package/dist/standalone/chunk-6LMO2D54.js +0 -1
- package/dist/standalone/chunk-6M7FLLMT.js +0 -1
- package/dist/standalone/chunk-6QEXGYWH.js +0 -1
- package/dist/standalone/chunk-6UTZXEW3.js +0 -1
- package/dist/standalone/chunk-6VAY6L4J.js +0 -1
- package/dist/standalone/chunk-7PADVGQX.js +0 -1
- package/dist/standalone/chunk-7RGYCU6F.js +0 -1
- package/dist/standalone/chunk-7UM5ROG6.js +0 -1
- package/dist/standalone/chunk-A566HCBX.js +0 -1
- package/dist/standalone/chunk-A5JISKHE.js +0 -1
- package/dist/standalone/chunk-ADNRFCMZ.js +0 -1
- package/dist/standalone/chunk-AP4PC2M4.js +0 -1
- package/dist/standalone/chunk-BFE2DRP6.js +0 -33
- package/dist/standalone/chunk-BPEB4KFE.js +0 -1
- package/dist/standalone/chunk-BVX45MU5.js +0 -7
- package/dist/standalone/chunk-C6GN7ZXJ.js +0 -1
- package/dist/standalone/chunk-CL2VZNDI.js +0 -1
- package/dist/standalone/chunk-CNA3TVUK.js +0 -1
- package/dist/standalone/chunk-CZ6HBDIL.js +0 -1
- package/dist/standalone/chunk-D6S7MXW4.js +0 -1
- package/dist/standalone/chunk-E26OT26O.js +0 -1
- package/dist/standalone/chunk-FCAXVYAX.js +0 -1
- package/dist/standalone/chunk-FXPAJDES.js +0 -1
- package/dist/standalone/chunk-HHRYM6UW.js +0 -1
- package/dist/standalone/chunk-HPRF5LMA.js +0 -1
- package/dist/standalone/chunk-IB22LETR.js +0 -1
- package/dist/standalone/chunk-IBJVVHV5.js +0 -1
- package/dist/standalone/chunk-IENQRRQT.js +0 -1
- package/dist/standalone/chunk-IQ4TTHQT.js +0 -1
- package/dist/standalone/chunk-ITH5LRWM.js +0 -1
- package/dist/standalone/chunk-J6VFG6M5.js +0 -1
- package/dist/standalone/chunk-JSDKOE4U.js +0 -1
- package/dist/standalone/chunk-JTGGWF7R.js +0 -1
- package/dist/standalone/chunk-JZD7ZN3F.js +0 -1
- package/dist/standalone/chunk-K3CWB3AM.js +0 -1
- package/dist/standalone/chunk-KNFB3FGW.js +0 -1
- package/dist/standalone/chunk-KNXWDE4N.js +0 -1
- package/dist/standalone/chunk-KRPXOSBL.js +0 -1
- package/dist/standalone/chunk-KRY7BYHT.js +0 -1
- package/dist/standalone/chunk-KYAG2YMF.js +0 -1
- package/dist/standalone/chunk-KZCEJFZF.js +0 -1
- package/dist/standalone/chunk-KZILJQX3.js +0 -8
- package/dist/standalone/chunk-LEYUH5TS.js +0 -1
- package/dist/standalone/chunk-LFM672WN.js +0 -1
- package/dist/standalone/chunk-LIGOLZND.js +0 -1
- package/dist/standalone/chunk-LPU6YTSU.js +0 -1
- package/dist/standalone/chunk-MWJC3S62.js +0 -1
- package/dist/standalone/chunk-NP2AQOLE.js +0 -1
- package/dist/standalone/chunk-NVKLYDOH.js +0 -1
- package/dist/standalone/chunk-O2X2XYCM.js +0 -1
- package/dist/standalone/chunk-O3MDWYXF.js +0 -1
- package/dist/standalone/chunk-ONG4JEZD.js +0 -1
- package/dist/standalone/chunk-OS26JXYA.js +0 -1
- package/dist/standalone/chunk-OXFKZ4BM.js +0 -1
- package/dist/standalone/chunk-PGTEGUAB.js +0 -1
- package/dist/standalone/chunk-PTBUWRBY.js +0 -1
- package/dist/standalone/chunk-Q6HA3L2H.js +0 -1
- package/dist/standalone/chunk-QGV5ARD2.js +0 -1
- package/dist/standalone/chunk-QWRK4ESB.js +0 -1
- package/dist/standalone/chunk-RL2ITK2N.js +0 -1
- package/dist/standalone/chunk-RTJO3AR4.js +0 -1
- package/dist/standalone/chunk-SFY646MC.js +0 -1
- package/dist/standalone/chunk-T5UMHPAB.js +0 -1
- package/dist/standalone/chunk-T6HV2FQP.js +0 -2
- package/dist/standalone/chunk-T7ZKNNGX.js +0 -1
- package/dist/standalone/chunk-TCYPNSTV.js +0 -1
- package/dist/standalone/chunk-TQM6XHBA.js +0 -1
- package/dist/standalone/chunk-TRMWBRRU.js +0 -1
- package/dist/standalone/chunk-TW7KJSMR.js +0 -15
- package/dist/standalone/chunk-TYD3V4NB.js +0 -1
- package/dist/standalone/chunk-TZKLK52W.js +0 -1
- package/dist/standalone/chunk-U4RXQSQ7.js +0 -1
- package/dist/standalone/chunk-UNZ2UBVL.js +0 -1
- package/dist/standalone/chunk-VJRNOSRY.js +0 -1
- package/dist/standalone/chunk-W2BCSK5S.js +0 -1
- package/dist/standalone/chunk-W7MRISE3.js +0 -1
- package/dist/standalone/chunk-WM72PRE3.js +0 -1
- package/dist/standalone/chunk-X4WHMCOZ.js +0 -1
- package/dist/standalone/chunk-X74GEPSG.js +0 -1
- package/dist/standalone/chunk-XKPD4SFN.js +0 -1
- package/dist/standalone/chunk-XMSNLMWU.js +0 -1
- package/dist/standalone/chunk-XOPFDWXX.js +0 -1
- package/dist/standalone/chunk-XQLOVFPP.js +0 -1
- package/dist/standalone/chunk-XSHYZPGF.js +0 -1
- package/dist/standalone/chunk-XST3UEHU.js +0 -1
- package/dist/standalone/chunk-XYR5NST4.js +0 -1
- package/dist/standalone/chunk-Y74LIFSL.js +0 -1
- package/dist/standalone/chunk-YHTHRYP5.js +0 -1
- package/dist/standalone/chunk-YMEKCV27.js +0 -1
- package/dist/standalone/chunk-Z5EV64KS.js +0 -1
- package/dist/standalone/chunk-ZBON5T5A.js +0 -1
- package/dist/standalone/chunk-ZGSL4DPP.js +0 -1
- package/dist/standalone/chunk-ZOQTXWPK.js +0 -1
- package/dist/standalone/chunk-ZTOREMGH.js +0 -1
- package/dist/standalone/chunk-ZZ5GICTF.js +0 -1
- /package/dist/standalone/{chunk-UYEZR3BI.js → chunk-P6VNMPWR.js} +0 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{a as _s,b,c as Qs,d as Ds}from"./chunk-GNI37YCV.js";import{a as Us}from"./chunk-GWNGVKLG.js";import{a as ne,b as Lt}from"./chunk-6G3E4PJ2.js";import{a,d as U}from"./chunk-5PEAXTYQ.js";var le=U(ne(),1),Ns=U(Lt(),1);var Ee=le.createContext(void 0),Ie=a(t=>{let e=le.useContext(Ee);if(t)return t;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},"useQueryClient"),Mt=a(({client:t,children:e})=>(le.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,Ns.jsx)(Ee.Provider,{value:t,children:e})),"QueryClientProvider");var W=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 qn=class extends W{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"}},pe=new qn;var Bn={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")},$n=class{static{a(this,"TimeoutManager")}#e=Bn;#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)}},z=new $n;function js(t){setTimeout(t,0)}a(js,"systemSetTimeoutZero");var _t=typeof window>"u"||"Deno"in globalThis;function O(){}a(O,"noop");function Ws(t,e){return typeof t=="function"?t(e):t}a(Ws,"functionalUpdate");function Re(t){return typeof t=="number"&&t>=0&&t!==1/0}a(Re,"isValidTimeout");function ze(t,e){return Math.max(t+(e||0)-Date.now(),0)}a(ze,"timeUntilStale");function q(t,e){return typeof t=="function"?t(e):t}a(q,"resolveStaleTime");function _(t,e){return typeof t=="function"?t(e):t}a(_,"resolveQueryBoolean");function Ge(t,e){let{type:s="all",exact:r,fetchStatus:i,predicate:n,queryKey:o,stale:c}=t;if(o){if(r){if(e.queryHash!==Ae(o,e.options))return!1}else if(!ae(e.queryKey,o))return!1}if(s!=="all"){let u=e.isActive();if(s==="active"&&!u||s==="inactive"&&u)return!1}return!(typeof c=="boolean"&&e.isStale()!==c||i&&i!==e.state.fetchStatus||n&&!n(e))}a(Ge,"matchQuery");function Je(t,e){let{exact:s,status:r,predicate:i,mutationKey:n}=t;if(n){if(!e.options.mutationKey)return!1;if(s){if(G(e.options.mutationKey)!==G(n))return!1}else if(!ae(e.options.mutationKey,n))return!1}return!(r&&e.state.status!==r||i&&!i(e))}a(Je,"matchMutation");function Ae(t,e){return(e?.queryKeyHashFn||G)(t)}a(Ae,"hashQueryKeyByOptions");function G(t){return JSON.stringify(t,(e,s)=>xt(s)?Object.keys(s).sort().reduce((r,i)=>(r[i]=s[i],r),{}):s)}a(G,"hashKey");function ae(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(!ae(t[r],e[r]))return!1;return!0}let s=Object.keys(e);for(let r of s)if(!ae(t[r],e[r]))return!1;return!0}return!1}a(ae,"partialMatchKey");var zn=Object.prototype.hasOwnProperty;function Qt(t,e,s=0){if(t===e)return t;if(s>500)return e;let r=Ks(t)&&Ks(e);if(!r&&!(xt(t)&&xt(e)))return e;let n=(r?t:Object.keys(t)).length,o=r?e:Object.keys(e),c=o.length,u=r?new Array(c):{},h=0;for(let d=0;d<c;d++){let l=r?d:o[d],p=t[l],f=e[l];if(p===f){u[l]=p,(r?d<n:zn.call(t,l))&&h++;continue}if(p===null||f===null||typeof p!="object"||typeof f!="object"){u[l]=f;continue}let y=Qt(p,f,s+1);u[l]=y,y===p&&h++}return n===c&&h===n?t:u}a(Qt,"replaceEqualDeep");function fe(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(fe,"shallowEqualObjects");function Ks(t){return Array.isArray(t)&&t.length===Object.keys(t).length}a(Ks,"isPlainArray");function xt(t){if(!Hs(t))return!1;let e=t.constructor;if(e===void 0)return!0;let s=e.prototype;return!(!Hs(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}a(xt,"isPlainObject");function Hs(t){return Object.prototype.toString.call(t)==="[object Object]"}a(Hs,"hasObjectPrototype");function qs(t){return new Promise(e=>{z.setTimeout(e,t)})}a(qs,"sleep");function Fe(t,e,s){return typeof s.structuralSharing=="function"?s.structuralSharing(t,e):s.structuralSharing!==!1?Qt(t,e):e}a(Fe,"replaceData");function Gn(t){return t}a(Gn,"keepPreviousData");function Bs(t,e,s=0){let r=[...t,e];return s&&r.length>s?r.slice(1):r}a(Bs,"addToEnd");function $s(t,e,s=0){let r=[e,...t];return s&&r.length>s?r.slice(0,-1):r}a($s,"addToStart");var me=Symbol();function Ve(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===me?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}a(Ve,"ensureQueryFn");function ye(t,e){return typeof t=="function"?t(...e):!!t}a(ye,"shouldThrowError");function zs(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(zs,"addConsumeAwareSignal");var J=(()=>{let t=a(()=>_t,"isServerFn");return{isServer(){return t()},setIsServer(e){t=e}}})();function Pe(){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(Pe,"pendingThenable");var Gs=js;function Jn(){let t=[],e=0,s=a(c=>{c()},"notifyFn"),r=a(c=>{c()},"batchNotifyFn"),i=Gs,n=a(c=>{e?t.push(c):i(()=>{s(c)})},"schedule"),o=a(()=>{let c=t;t=[],c.length&&i(()=>{r(()=>{c.forEach(u=>{s(u)})})})},"flush");return{batch:a(c=>{let u;e++;try{u=c()}finally{e--,e||o()}return u},"batch"),batchCalls:a(c=>(...u)=>{n(()=>{c(...u)})},"batchCalls"),schedule:n,setNotifyFunction:a(c=>{s=c},"setNotifyFunction"),setBatchNotifyFunction:a(c=>{r=c},"setBatchNotifyFunction"),setScheduler:a(c=>{i=c},"setScheduler")}}a(Jn,"createNotifyManager");var C=Jn();var Vn=class extends W{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}},be=new Vn;function Yn(t){return Math.min(1e3*2**t,3e4)}a(Yn,"defaultRetryDelay");function Dt(t){return(t??"online")==="online"?be.isOnline():!0}a(Dt,"canFetch");var Ye=class extends Error{static{a(this,"CancelledError")}constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function Xe(t){let e=!1,s=0,r,i=Pe(),n=a(()=>i.status!=="pending","isResolved"),o=a(m=>{if(!n()){let v=new Ye(m);p(v),t.onCancel?.(v)}},"cancel"),c=a(()=>{e=!0},"cancelRetry"),u=a(()=>{e=!1},"continueRetry"),h=a(()=>pe.isFocused()&&(t.networkMode==="always"||be.isOnline())&&t.canRun(),"canContinue"),d=a(()=>Dt(t.networkMode)&&t.canRun(),"canStart"),l=a(m=>{n()||(r?.(),i.resolve(m))},"resolve"),p=a(m=>{n()||(r?.(),i.reject(m))},"reject"),f=a(()=>new Promise(m=>{r=a(v=>{(n()||h())&&m(v)},"continueFn"),t.onPause?.()}).then(()=>{r=void 0,n()||t.onContinue?.()}),"pause"),y=a(()=>{if(n())return;let m,v=s===0?t.initialPromise:void 0;try{m=v??t.fn()}catch(w){m=Promise.reject(w)}Promise.resolve(m).then(l).catch(w=>{if(n())return;let k=t.retry??(J.isServer()?0:3),E=t.retryDelay??Yn,S=typeof E=="function"?E(s,w):E,I=k===!0||typeof k=="number"&&s<k||typeof k=="function"&&k(s,w);if(e||!I){p(w);return}s++,t.onFail?.(s,w),qs(S).then(()=>h()?void 0:f()).then(()=>{e?p(w):y()})})},"run");return{promise:i,status:a(()=>i.status,"status"),cancel:o,continue:a(()=>(r?.(),i),"continue"),cancelRetry:c,continueRetry:u,canStart:d,start:a(()=>(d()?y():f().then(y),i),"start")}}a(Xe,"createRetryer");var Ze=class{static{a(this,"Removable")}#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Re(this.gcTime)&&(this.#e=z.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(J.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(z.clearTimeout(this.#e),this.#e=void 0)}};function Vs(t){return{onFetch:a((e,s)=>{let r=e.options,i=e.fetchOptions?.meta?.fetchMore?.direction,n=e.state.data?.pages||[],o=e.state.data?.pageParams||[],c={pages:[],pageParams:[]},u=0,h=a(async()=>{let d=!1,l=a(y=>{zs(y,()=>e.signal,()=>d=!0)},"addSignalProperty"),p=Ve(e.options,e.fetchOptions),f=a(async(y,m,v)=>{if(d)return Promise.reject(e.signal.reason);if(m==null&&y.pages.length)return Promise.resolve(y);let k=a(()=>{let ie={client:e.client,queryKey:e.queryKey,pageParam:m,direction:v?"backward":"forward",meta:e.options.meta};return l(ie),ie},"createQueryFnContext")(),E=await p(k),{maxPages:S}=e.options,I=v?$s:Bs;return{pages:I(y.pages,E,S),pageParams:I(y.pageParams,m,S)}},"fetchPage");if(i&&n.length){let y=i==="backward",m=y?Xn:Js,v={pages:n,pageParams:o},w=m(r,v);c=await f(v,w,y)}else{let y=t??n.length;do{let m=u===0?o[0]??r.initialPageParam:Js(r,c);if(u>0&&m==null)break;c=await f(c,m),u++}while(u<y)}return c},"fetchFn");e.options.persister?e.fetchFn=()=>e.options.persister?.(h,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},s):e.fetchFn=h},"onFetch")}}a(Vs,"infiniteQueryBehavior");function Js(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(Js,"getNextPageParam");function Xn(t,{pages:e,pageParams:s}){return e.length>0?t.getPreviousPageParam?.(e[0],e,s[0],s):void 0}a(Xn,"getPreviousPageParam");var Zs=class extends Ze{static{a(this,"Query")}#e;#t;#s;#r;#n;#i;#o;#a;constructor(t){super(),this.#a=!1,this.#o=t.defaultOptions,this.setOptions(t.options),this.observers=[],this.#n=t.client,this.#r=this.#n.getQueryCache(),this.queryKey=t.queryKey,this.queryHash=t.queryHash,this.#t=Xs(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=Xs(this.options);e.data!==void 0&&(this.setState(Ys(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#r.remove(this)}setData(t,e){let s=Fe(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=>_(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===me||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>q(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!ze(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 u=this.observers.find(h=>h.options.queryFn);u&&this.setOptions(u.options)}let s=new AbortController,r=a(u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:a(()=>(this.#a=!0,s.signal),"get")})},"addSignalProperty"),i=a(()=>{let u=Ve(this.options,e),d=a(()=>{let l={client:this.#n,queryKey:this.queryKey,meta:this.meta};return r(l),l},"createQueryFnContext")();return this.#a=!1,this.options.persister?this.options.persister(u,d,this):u(d)},"fetchFn"),o=a(()=>{let u={fetchOptions:e,options:this.options,queryKey:this.queryKey,client:this.#n,state:this.state,fetchFn:i};return r(u),u},"createFetchContext")();(this.#e==="infinite"?Vs(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=Xe({initialPromise:e?.initialPromise,fn:o.fetchFn,onCancel:a(u=>{u instanceof Ye&&u.revert&&this.setState({...this.#s,fetchStatus:"idle"}),s.abort()},"onCancel"),onFail:a((u,h)=>{this.#c({type:"failed",failureCount:u,error:h})},"onFail"),onPause:a(()=>{this.#c({type:"pause"})},"onPause"),onContinue:a(()=>{this.#c({type:"continue"})},"onContinue"),retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:a(()=>!0,"canRun")});try{let u=await this.#i.start();if(u===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(u),this.#r.config.onSuccess?.(u,this),this.#r.config.onSettled?.(u,this.state.error,this),u}catch(u){if(u instanceof Ye){if(u.silent)return this.#i.promise;if(u.revert){if(this.state.data===void 0)throw u;return this.state.data}}throw this.#c({type:"error",error:u}),this.#r.config.onError?.(u,this),this.#r.config.onSettled?.(this.state.data,u,this),u}finally{this.scheduleGc()}}#c(t){let e=a(s=>{switch(t.type){case"failed":return{...s,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...Ut(s.data,this.options),fetchMeta:t.meta??null};case"success":let r={...s,...Ys(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 Ut(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Dt(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}a(Ut,"fetchState");function Ys(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}a(Ys,"successState");function Xs(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(Xs,"getDefaultState");var jt=class extends W{static{a(this,"QueryObserver")}constructor(t,e){super(),this.options=e,this.#e=t,this.#a=null,this.#o=Pe(),this.bindMethods(),this.setOptions(e)}#e;#t=void 0;#s=void 0;#r=void 0;#n;#i;#o;#a;#d;#c;#f;#h;#l;#u;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),er(this.#t,this.options)?this.#p():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Nt(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Nt(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 _(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&&!fe(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});let r=this.hasListeners();r&&tr(this.#t,s,this.options,e)&&this.#p(),this.updateResult(),r&&(this.#t!==s||_(this.options.enabled,this.#t)!==_(e.enabled,this.#t)||q(this.options.staleTime,this.#t)!==q(e.staleTime,this.#t))&&this.#y();let i=this.#b();r&&(this.#t!==s||_(this.options.enabled,this.#t)!==_(e.enabled,this.#t)||i!==this.#u)&&this.#g(i)}getOptimisticResult(t){let e=this.#e.getQueryCache().build(this.#e,t),s=this.createResult(e,t);return ea(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=q(this.options.staleTime,this.#t);if(J.isServer()||this.#r.isStale||!Re(t))return;let s=ze(this.#r.dataUpdatedAt,t)+1;this.#h=z.setTimeout(()=>{this.#r.isStale||this.updateResult()},s)}#b(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#g(t){this.#S(),this.#u=t,!(J.isServer()||_(this.options.enabled,this.#t)===!1||!Re(this.#u)||this.#u===0)&&(this.#l=z.setInterval(()=>{(this.options.refetchIntervalInBackground||pe.isFocused())&&this.#p()},this.#u))}#v(){this.#y(),this.#g(this.#b())}#w(){this.#h!==void 0&&(z.clearTimeout(this.#h),this.#h=void 0)}#S(){this.#l!==void 0&&(z.clearInterval(this.#l),this.#l=void 0)}createResult(t,e){let s=this.#t,r=this.options,i=this.#r,n=this.#n,o=this.#i,u=t!==s?t.state:this.#s,{state:h}=t,d={...h},l=!1,p;if(e._optimisticResults){let F=this.hasListeners(),R=!F&&er(t,e),X=F&&tr(t,s,e,r);(R||X)&&(d={...d,...Ut(h.data,t.options)}),e._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:f,errorUpdatedAt:y,status:m}=d;p=d.data;let v=!1;if(e.placeholderData!==void 0&&p===void 0&&m==="pending"){let F;i?.isPlaceholderData&&e.placeholderData===o?.placeholderData?(F=i.data,v=!0):F=typeof e.placeholderData=="function"?e.placeholderData(this.#f?.state.data,this.#f):e.placeholderData,F!==void 0&&(m="success",p=Fe(i?.data,F,e),l=!0)}if(e.select&&p!==void 0&&!v)if(i&&p===n?.data&&e.select===this.#d)p=this.#c;else try{this.#d=e.select,p=e.select(p),p=Fe(i?.data,p,e),this.#c=p,this.#a=null}catch(F){this.#a=F}this.#a&&(f=this.#a,p=this.#c,y=Date.now(),m="error");let w=d.fetchStatus==="fetching",k=m==="pending",E=m==="error",S=k&&w,I=p!==void 0,x={status:m,fetchStatus:d.fetchStatus,isPending:k,isSuccess:m==="success",isError:E,isInitialLoading:S,isLoading:S,data:p,dataUpdatedAt:d.dataUpdatedAt,error:f,errorUpdatedAt:y,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:d.dataUpdateCount>u.dataUpdateCount||d.errorUpdateCount>u.errorUpdateCount,isFetching:w,isRefetching:w&&!k,isLoadingError:E&&!I,isPaused:d.fetchStatus==="paused",isPlaceholderData:l,isRefetchError:E&&I,isStale:Kt(t,e),refetch:this.refetch,promise:this.#o,isEnabled:_(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let F=x.data!==void 0,R=x.status==="error"&&!F,X=a($e=>{R?$e.reject(x.error):F&&$e.resolve(x.data)},"finalizeThenableIfPossible"),xs=a(()=>{let $e=this.#o=x.promise=Pe();X($e)},"recreateThenable"),Be=this.#o;switch(Be.status){case"pending":t.queryHash===s.queryHash&&X(Be);break;case"fulfilled":(R||x.data!==Be.value)&&xs();break;case"rejected":(!R||x.error!==Be.reason)&&xs();break}}return x}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),fe(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.#v()}#k(t){C.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function Zn(t,e){return _(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&_(e.retryOnMount,t)===!1)}a(Zn,"shouldLoadOnMount");function er(t,e){return Zn(t,e)||t.state.data!==void 0&&Nt(t,e,e.refetchOnMount)}a(er,"shouldFetchOnMount");function Nt(t,e,s){if(_(e.enabled,t)!==!1&&q(e.staleTime,t)!=="static"){let r=typeof s=="function"?s(t):s;return r==="always"||r!==!1&&Kt(t,e)}return!1}a(Nt,"shouldFetchOn");function tr(t,e,s,r){return(t!==e||_(r.enabled,t)===!1)&&(!s.suspense||t.state.status!=="error")&&Kt(t,s)}a(tr,"shouldFetchOptionally");function Kt(t,e){return _(e.enabled,t)!==!1&&t.isStaleByTime(q(e.staleTime,t))}a(Kt,"isStale");function ea(t,e){return!fe(t.getCurrentResult(),e)}a(ea,"shouldAssignObserverCurrentProperties");var sr=class extends Ze{static{a(this,"Mutation")}#e;#t;#s;#r;constructor(t){super(),this.#e=t.client,this.mutationId=t.mutationId,this.#s=t.mutationCache,this.#t=[],this.state=t.state||Ht(),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=Xe({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 Ht(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}a(Ht,"getDefaultState");var rr=class extends W{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 sr({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=et(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=et(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=et(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=et(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=>Je(e,s))}findAll(t={}){return this.getAll().filter(e=>Je(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 et(t){return t.options.scope?.id}a(et,"scopeFor");var Wt=class extends W{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),fe(this.options,e)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#s,observer:this}),e?.mutationKey&&this.options.mutationKey&&G(e.mutationKey)!==G(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??Ht();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 ir=class extends W{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??Ae(r,e),n=this.get(i);return n||(n=new Zs({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=>Ge(e,s))}findAll(t={}){let e=this.getAll();return Object.keys(t).length>0?e.filter(s=>Ge(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 qt=class{static{a(this,"QueryClient")}#e;#t;#s;#r;#n;#i;#o;#a;constructor(t={}){this.#e=t.queryCache||new ir,this.#t=t.mutationCache||new rr,this.#s=t.defaultOptions||{},this.#r=new Map,this.#n=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#o=pe.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#a=be.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#i--,this.#i===0&&(this.#o?.(),this.#o=void 0,this.#a?.(),this.#a=void 0)}isFetching(t){return this.#e.findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return this.#t.findAll({...t,status:"pending"}).length}getQueryData(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state.data}ensureQueryData(t){let e=this.defaultQueryOptions(t),s=this.#e.build(this,e),r=s.state.data;return r===void 0?this.fetchQuery(t):(t.revalidateIfStale&&s.isStaleByTime(q(e.staleTime,s))&&this.prefetchQuery(e),Promise.resolve(r))}getQueriesData(t){return this.#e.findAll(t).map(({queryKey:e,state:s})=>{let r=s.data;return[e,r]})}setQueryData(t,e,s){let r=this.defaultQueryOptions({queryKey:t}),n=this.#e.get(r.queryHash)?.state.data,o=Ws(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(q(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 be.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(G(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){let e=[...this.#r.values()],s={};return e.forEach(r=>{ae(t,r.queryKey)&&Object.assign(s,r.defaultOptions)}),s}setMutationDefaults(t,e){this.#n.set(G(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){let e=[...this.#n.values()],s={};return e.forEach(r=>{ae(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=Ae(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===me&&(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 oe=U(ne(),1);var Le=U(ne(),1),ta=U(Lt(),1);function sa(){let t=!1;return{clearReset:a(()=>{t=!1},"clearReset"),reset:a(()=>{t=!0},"reset"),isReset:a(()=>t,"isReset")}}a(sa,"createValue");var ra=Le.createContext(sa()),nr=a(()=>Le.useContext(ra),"useQueryErrorResetBoundary");var ar=U(ne(),1);var or=a((t,e,s)=>{let r=s?.state.error&&typeof t.throwOnError=="function"?ye(t.throwOnError,[s.state.error,s]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||r)&&(e.isReset()||(t.retryOnMount=!1))},"ensurePreventErrorBoundaryRetry"),cr=a(t=>{ar.useEffect(()=>{t.clearReset()},[t])},"useClearResetErrorBoundary"),ur=a(({result:t,errorResetBoundary:e,throwOnError:s,query:r,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&r&&(i&&t.data===void 0||ye(s,[t.error,r])),"getHasError");var tt=U(ne(),1);var dr=tt.createContext(!1),hr=a(()=>tt.useContext(dr),"useIsRestoring"),Bh=dr.Provider;var lr=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"),pr=a((t,e)=>t.isLoading&&t.isFetching&&!e,"willFetch"),fr=a((t,e)=>t?.suspense&&e.isPending,"shouldSuspend"),Bt=a((t,e,s)=>e.fetchOptimistic(t).catch(()=>{s.clearReset()}),"fetchOptimistic");function mr(t,e,s){let r=hr(),i=nr(),n=Ie(s),o=n.defaultQueryOptions(t);n.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let c=n.getQueryCache().get(o.queryHash),u=t.subscribed!==!1;o._optimisticResults=r?"isRestoring":u?"optimistic":void 0,lr(o),or(o,i,c),cr(i);let h=!n.getQueryCache().get(o.queryHash),[d]=oe.useState(()=>new e(n,o)),l=d.getOptimisticResult(o),p=!r&&u;if(oe.useSyncExternalStore(oe.useCallback(f=>{let y=p?d.subscribe(C.batchCalls(f)):O;return d.updateResult(),y},[d,p]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),oe.useEffect(()=>{d.setOptions(o)},[o,d]),fr(o,l))throw Bt(o,d,i);if(ur({result:l,errorResetBoundary:i,throwOnError:o.throwOnError,query:c,suspense:o.suspense}))throw l.error;return n.getDefaultOptions().queries?._experimental_afterQuery?.(o,l),o.experimental_prefetchInRender&&!J.isServer()&&pr(l,r)&&(h?Bt(o,d,i):c?.promise)?.catch(O).finally(()=>{d.updateResult()}),o.notifyOnChangeProps?l:d.trackResult(l)}a(mr,"useBaseQuery");function ia(t,e){return mr(t,jt,e)}a(ia,"useQuery");var Z=U(ne(),1);function na(t,e){let s=Ie(e),[r]=Z.useState(()=>new Wt(s,t));Z.useEffect(()=>{r.setOptions(t)},[r,t]);let i=Z.useSyncExternalStore(Z.useCallback(o=>r.subscribe(C.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),n=Z.useCallback((o,c)=>{r.mutate(o,c).catch(O)},[r]);if(i.error&&ye(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:n,mutateAsync:i.mutate}}a(na,"useMutation");var aa=/["\\\u0000-\u001F\uD800-\uDFFF]/,yr=a(t=>aa.test(t)?JSON.stringify(t):`"${t}"`,"y"),oa=a(t=>Number.isNaN(t)?"nan":t===1/0?"inf":t===-1/0?"-inf":Object.is(t,-0)?"-0":void 0,"b"),ca=a((t,e)=>{let s=Object.getPrototypeOf(t);if(s!==null&&s!==Object.prototype){let c=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${c} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}let r=t,i=Object.keys(r).sort(),n="{",o=!0;for(let c of i){let u=r[c];u!==void 0&&(o?o=!1:n+=",",n+=yr(c),n+=":",n+=e(u))}return`${n}}`},"u"),ua=a(t=>{let{length:e}=t,s=Number.isInteger(e)?e:Math.trunc(e)||0;if(s>4294967295)throw new RangeError("stable-key: array length exceeds 2**32 - 1");return s},"g"),Me=a(t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key \u2014 pass it as a string, or use stableWireKey");if(typeof t=="function"||typeof t=="symbol")throw new TypeError(`stableStringify: cannot use a ${typeof t} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported`);if(typeof t=="number"){let e=oa(t);if(e!==void 0)return e}if(typeof t=="string")return yr(t);if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t)){let e=ua(t),s="[";for(let r=0;r<e;r+=1)r>0&&(s+=","),s+=Me(t[r]);return`${s}]`}return ca(t,Me)},"c");var st=a(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"e");var rt=a(t=>{let e="";for(let s=0;s<t.length;s+=32768)e+=String.fromCharCode(...t.subarray(s,s+32768));return btoa(e)},"f"),da=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},"h"),A="$lunora.wire$",it=64,nt=1024,ha="__proto__",la=/^-?\d+$/,br={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},gr={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},$t=a((t,e,s)=>{e===ha?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:s,writable:!0}):t[e]=s},"g");var pa=a(t=>{let e=t.toString();if(e.length>nt)throw new RangeError(`wire-codec: over-long bigint (max ${String(nt)} digits)`);return[A,"bigint",e]},"j"),fa=a(t=>Number.isNaN(t)?[A,"nan"]:t===1/0?[A,"inf"]:t===-1/0?[A,"-inf"]:t,"S"),ma=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},"R"),ya=a(t=>{let e=t.constructor.name,s=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return e==="Uint8Array"?[A,"bytes",rt(s)]:[A,"bytes",rt(s),e]},"U"),ba=a((t,e)=>t instanceof Date?[A,"date",e(t.getTime())]:t instanceof Error?ma(t,e):t instanceof URL?[A,"url",t.href]:t instanceof Map?[A,"map",[...t.entries()].map(([s,r])=>[e(s),e(r)])]:t instanceof Set?[A,"set",[...t].map(s=>e(s))]:t instanceof ArrayBuffer?[A,"bytes",rt(new Uint8Array(t)),"ArrayBuffer"]:ArrayBuffer.isView(t)?ya(t):void 0,"I"),ga=a((t,e)=>{let s=t.map(r=>ge(r,e));return s.length>0&&s[0]===A?[A,"arr",s]:s},"N"),va=a((t,e)=>{let s={};for(let r of Object.keys(t)){let i=t[r];i!==void 0&&$t(s,r,ge(i,e))}return s},"B"),ge=a((t,e=0)=>{if(e>it)throw new RangeError(`wire-codec: value nesting exceeds the ${String(it)}-level limit`);if(t===void 0)return[A,"undefined"];if(t===null)return t;if(typeof t=="bigint")return pa(t);if(typeof t=="number")return fa(t);if(typeof t!="object")return t;if(Array.isArray(t))return ga(t,e+1);if(st(t))return va(t,e+1);let s=ba(t,i=>ge(i,e+1));if(s!==void 0)return s;let r=t.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} 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"),wa=a(t=>{let e=t[2];if(typeof e!="string"||e.length>nt||!la.test(e))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${String(nt)} digits)`);return BigInt(e)},"_"),Sa=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)},"P"),Ca=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])]}))},"$"),ka=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)},"D"),Ta=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(gr,s)?gr[s]:void 0)??Error,n=new i(r);n.name!==s&&Object.defineProperty(n,"name",{configurable:!0,value:s,writable:!0});let o=e(t[4]);if(o===null||typeof o!="object"||Array.isArray(o))throw new TypeError("wire-codec: malformed error \u2014 props must be an object");for(let[c,u]of Object.entries(o))$t(n,c,u);return t.length>5&&Object.defineProperty(n,"cause",{configurable:!0,value:e(t[5]),writable:!0}),n},"k"),Oa=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=da(e);if(rt(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(br,r)?br[r]:void 0;return i?new i(new Uint8Array(s).buffer):s},"C"),Ea=a((t,e)=>{switch(t[1]){case"-inf":return-1/0;case"arr":return t[2].map(s=>e(s));case"bigint":return wa(t);case"bytes":return Oa(t);case"date":return Sa(t,e);case"error":return Ta(t,e);case"inf":return 1/0;case"map":return Ca(t,e);case"nan":return Number.NaN;case"set":return new Set(t[2].map(s=>e(s)));case"undefined":return;case"url":return ka(t);default:return t.map(s=>e(s))}},"L"),Ia=a((t,e)=>{let s={};for(let r of Object.keys(t))$t(s,r,xe(t[r],e));return s},"M"),xe=a((t,e=0)=>{if(e>it)throw new RangeError(`wire-codec: value nesting exceeds the ${String(it)}-level limit`);if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let s=t;return s[0]===A?Ea(s,r=>xe(r,e+1)):s.map(r=>xe(r,e+1))}return Ia(t,e+1)},"u"),vr=a(t=>{let e=JSON.parse(t);return t.includes(A)||t.includes(String.raw`\u`)?xe(e):e},"F"),Ra=a(t=>{try{let e=vr(t);return st(e)?e:void 0}catch{return}},"W");var zt=a(t=>Me(ge(t)),"a");var ve=a(t=>{try{return t(),!0}catch{return!1}},"o"),Aa=new Set([Object.prototype,Function.prototype]),Qe=a((t,e,s)=>{let r;for(let i=t;i!==null&&!Aa.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)=>Qe(t,e,"get"),"r"),Cr=Qe(Date.prototype,"getTime","value"),Fa=V(Map.prototype,"size"),Pa=V(Set.prototype,"size"),La=V(ArrayBuffer.prototype,"byteLength"),_e=typeof URL=="function"?V(URL.prototype,"href"):void 0,Gt=typeof URL=="function"?URL.prototype:void 0,Ma=_e!==void 0&&Function.prototype.toString.call(_e).includes("[native code]"),wr=Qe(Error,"isError","value"),Sr=Error.prototype,xa=a((t,e)=>typeof wr=="function"?wr(t):e!==null&&(e===Sr||Sr.isPrototypeOf(e)),"L"),_a=Qe(Map.prototype,"forEach","value"),Qa=Qe(Set.prototype,"forEach","value"),Jt=Object.getPrototypeOf(Uint8Array.prototype),Vt={data:{buffer:V(DataView.prototype,"buffer"),byteLength:V(DataView.prototype,"byteLength"),byteOffset:V(DataView.prototype,"byteOffset")},typed:{buffer:V(Jt,"buffer"),byteLength:V(Jt,"byteLength"),byteOffset:V(Jt,"byteOffset")}},kr=a(t=>Reflect.apply(Cr,t,[]),"S"),Tr=a(t=>Reflect.apply(_e,t,[]),"m"),Or=a(t=>{let e=[];return Reflect.apply(_a,t,[(s,r)=>e.push([r,s])]),e},"A"),Er=a(t=>{let e=[];return Reflect.apply(Qa,t,[s=>e.push(s)]),e},"w"),Ir=a(t=>{let e=ve(()=>Reflect.apply(Vt.typed.buffer,t,[]))?Vt.typed:Vt.data;return new Uint8Array(Reflect.apply(e.buffer,t,[]),Reflect.apply(e.byteOffset,t,[]),Reflect.apply(e.byteLength,t,[]))},"j"),at=a(t=>{if(Array.isArray(t))return"array";let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype?"plain":ve(()=>Reflect.apply(Cr,t,[]))?"builtin-date":ve(()=>Reflect.apply(Fa,t,[]))?"builtin-map":ve(()=>Reflect.apply(Pa,t,[]))?"builtin-set":ve(()=>Reflect.apply(La,t,[]))?"builtin-array-buffer":ArrayBuffer.isView(t)?"builtin-view":xa(t,e)?"builtin-error":_e!==void 0&&(Ma||Gt!==void 0&&e!==null&&(e===Gt||Gt.isPrototypeOf(e)))&&ve(()=>Reflect.apply(_e,t,[]))?"builtin-url":"other"},"D");var Da=2**32-1,Ua=/["\\\u0000-\u001F\uD800-\uDFFF]/,Rr=a(t=>Ua.test(t)?JSON.stringify(t):`"${t}"`,"y"),Na=a(t=>Number.isNaN(t)?"nan":t===1/0?"inf":t===-1/0?"-inf":Object.is(t,-0)?"-0":void 0,"u"),ja=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+=Rr(o),i+=":",i+=e(c))}return`${i}}`},"g"),Ka=a(t=>{let{length:e}=t,s=Number.isInteger(e)?e:Math.trunc(e)||0;if(s>Da)throw new RangeError("stable-key: array length exceeds 2**32 - 1");return s},"d"),ot=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=Na(t);if(s!==void 0)return s}if(typeof t=="string")return Rr(t);if(t===null||typeof t!="object")return JSON.stringify(t);let e=at(t);if(e==="array"){let s=Ka(t),r="[";for(let i=0;i<s;i+=1)i>0&&(r+=","),r+=ot(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 ja(t,ot)},"c");var ct=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"),Ha=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"),P="$lunora.wire$",ut=64,dt=1024,Wa="__proto__",qa=/^-?\d+$/,Ar={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},Fr={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},Yt=a((t,e,s)=>{e===Wa?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:s,writable:!0}):t[e]=s},"b");var Ba=a(t=>{let e=t.toString();if(e.length>dt)throw new RangeError(`wire-codec: over-long bigint (max ${String(dt)} digits)`);return[P,"bigint",e]},"B"),$a=a(t=>Number.isNaN(t)?[P,"nan"]:t===1/0?[P,"inf"]:t===-1/0?[P,"-inf"]:t,"_"),za=a((t,e)=>{let s=e(Object.fromEntries(Object.keys(t).map(n=>[n,t[n]]))),r=t,i=[P,"error",String(r.name),String(r.message),s];return t.cause!==void 0&&i.push(e(t.cause)),i},"P"),Ga=a(t=>{let e=t.constructor.name,s=Ir(t);return e==="Uint8Array"?[P,"bytes",ct(s)]:[P,"bytes",ct(s),e]},"$"),Ja=a((t,e,s)=>{switch(e){case"builtin-array-buffer":return[P,"bytes",ct(new Uint8Array(t)),"ArrayBuffer"];case"builtin-date":return[P,"date",s(kr(t))];case"builtin-error":return za(t,s);case"builtin-map":return[P,"map",Or(t).map(([r,i])=>[s(r),s(i)])];case"builtin-set":return[P,"set",Er(t).map(r=>s(r))];case"builtin-url":return[P,"url",Tr(t)];case"builtin-view":return Ga(t);default:return}},"k"),Va=a((t,e)=>{let s=t.map(r=>N(r,e));return s.length>0&&s[0]===P?[P,"arr",s]:s},"D"),Ya=a((t,e)=>{let s={};for(let r of Object.keys(t)){let i=t[r];i!==void 0&&Yt(s,r,N(i,e))}return s},"C"),N=a((t,e=0)=>{if(e>ut)throw new RangeError(`wire-codec: value nesting exceeds the ${String(ut)}-level limit`);if(t===void 0)return[P,"undefined"];if(t===null)return t;if(typeof t=="bigint")return Ba(t);if(typeof t=="number")return $a(t);if(typeof t!="object")return t;let s=at(t);if(s==="array")return Va(t,e+1);if(s==="plain")return Ya(t,e+1);let r=Ja(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"),Xa=a(t=>{let e=t[2];if(typeof e!="string"||e.length>dt||!qa.test(e))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${String(dt)} digits)`);return BigInt(e)},"M"),Za=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"),eo=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"),to=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"),so=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(Fr,s)?Fr[s]:void 0)??Error,n=new i(r);n.name!==s&&Object.defineProperty(n,"name",{configurable:!0,value:s,writable:!0});let o=e(t[4]);if(o===null||typeof o!="object"||Array.isArray(o))throw new TypeError("wire-codec: malformed error \u2014 props must be an object");for(let[c,u]of Object.entries(o))Yt(n,c,u);return t.length>5&&Object.defineProperty(n,"cause",{configurable:!0,value:e(t[5]),writable:!0}),n},"W"),ro=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=Ha(e);if(ct(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(Ar,r)?Ar[r]:void 0;return i?new i(new Uint8Array(s).buffer):s},"v"),io=a((t,e)=>{switch(t[1]){case"-inf":return-1/0;case"arr":return t[2].map(s=>e(s));case"bigint":return Xa(t);case"bytes":return ro(t);case"date":return Za(t,e);case"error":return so(t,e);case"inf":return 1/0;case"map":return eo(t,e);case"nan":return Number.NaN;case"set":return new Set(t[2].map(s=>e(s)));case"undefined":return;case"url":return to(t);default:return t.map(s=>e(s))}},"Y"),no=a((t,e)=>{let s={};for(let r of Object.keys(t))Yt(s,r,T(t[r],e));return s},"H"),T=a((t,e=0)=>{if(e>ut)throw new RangeError(`wire-codec: value nesting exceeds the ${String(ut)}-level limit`);if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let s=t;return s[0]===P?io(s,r=>T(r,e+1)):s.map(r=>T(r,e+1))}return no(t,e+1)},"f");var ee=a(t=>ot(N(t)),"a");var te="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Xt=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 ao=a(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"l"),oo="_id",Zt="_creationTime",es="page",Pr="pageDelta",co=a(t=>{if(Array.isArray(t))return t;if(ao(t)&&Array.isArray(t[es]))return t[es]},"y"),uo=a(t=>{let e;for(let s of t){let r=s[Zt];if(typeof r=="number"){if(e!==void 0){if(r<e)return!0;if(r>e)return!1}e=r}}return!1},"g"),ho=a((t,e)=>{let s=e[Zt];if(typeof s!="number")return t.length;let r=uo(t);for(let[i,n]of t.entries()){let o=n[Zt];if(typeof o=="number"&&(r?o<s:o>s))return i}return t.length},"A"),lo=a(t=>{if(typeof t!="object"||t===null)return;let e=t[oo];return typeof e=="string"?e:void 0},"b"),po=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"),fo=a((t,e)=>{let{key:s,op:r,row:i}=e,n=[],o=-1;for(let c of t){let u=lo(c);if(u===void 0)return;if(u===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(ho(n,i),0,i):n[o]=i,n},"x"),mo=a((t,e)=>{let s=co(t);if(s===void 0)return;let r=fo(s,e);return r===void 0||Array.isArray(t)?r:{...t,[es]:r}},"E"),ts=Symbol("lunora.unmergeableDelta"),Lr=a((t,e)=>{if("data"in t&&t.data!==void 0)return T(t.data);let s=T(t.delta);return po(s)?e===void 0?s:mo(e,s)??ts:s},"m");var Mr=a(()=>{let t=null;return{get:a(()=>t,"get"),set:a(e=>{t=e},"set")}},"r");var up=new Set(Object.keys(_s)),j=class extends b{static{a(this,"R")}constructor(e,s){super("INTERNAL",e,{data:s})}};var ht=a(t=>{let e=t?.data?.retryAfterMs;return typeof e=="number"&&Number.isFinite(e)?e:void 0},"f"),ss=new Set(["TOKEN_EXPIRED","UNAUTHENTICATED"]),De=a(t=>ss.has(t?.code??""),"u");var Ue=a(t=>typeof t=="string"||Array.isArray(t)&&t.every(e=>typeof e=="string")?{hint:t}:{},"n");var rs=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"),yo=a((t,e)=>{let s=rs(e);if(!(s===void 0||ht(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"),is=a(()=>new j("LunoraClient: batch slot carried no error envelope"),"E"),xr=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"),_r=a(t=>{let{code:e,messageText:s}=xr(t,"stream error"),r=t.error,i=r?.why,n=e===void 0?new Error(s):new b(e,s,Ue(r?.hint));return typeof i=="string"&&(n.why=i),n},"D"),ns=a(t=>{let{code:e,messageText:s}=xr(t,"subscription error"),r=t.error,i=typeof r?.why=="string"?{why:r.why}:{};return{message:s,...e===void 0?{}:{code:e},...Ue(r?.hint),...i}},"O"),bo=Symbol.for("lunora.serverVerdict"),Se=a(t=>{let e=new Error(t.message??"request failed");if(e.code=t.code,e[bo]=!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"),go=a(t=>Object.freeze(Object.fromEntries([...t].filter(([e])=>e!=="set-cookie"))),"b"),K=a((t,e)=>Object.defineProperty(t,"headers",{value:go(e)}),"w"),as=a((t,e)=>{let s=Se(t),r=yo(s,e.get("retry-after"));return r!==void 0&&(s.data=r),K(s,e)},"j"),os=a(t=>{let e=we(t);return e===void 0?is():Se(e)},"M"),Qr=new WeakSet,lt=a(t=>{let e=new b("WIRE_DECODE_FAILED",`LunoraClient: the call succeeded but its result could not be decoded (a mutation has still committed) \u2014 ${t instanceof Error?t.message:String(t)}`,{cause:t});return Qr.add(e),e},"N"),Ne=a(t=>t instanceof Error&&Qr.has(t),"T");var pt=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 ft=a(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"a"),cs=a(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"h"),H=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"),vo="http://same-origin.invalid",je=a(t=>new URL(t,vo),"p"),wo=/^[a-z][a-z\d+.-]*:/iu,us=a((t,e)=>{if(wo.test(e))return t.toString();let s=`${t.pathname}${t.search}${t.hash}`;return e.startsWith("//")?`//${t.host}${s}`:s},"S");var ds=0,Ce,Dr=a((t,e)=>{for(let s of t)try{s(e)}catch{}},"f"),So=a(t=>{let e=[...t.callbacks],s=t.lastValue;return()=>{for(let r of e){if(t.lastValue!==s)return;t.callbacks.has(r)&&Dr([r],s)}}},"p"),Ur=a(t=>{Ce===void 0?t():Ce.add(t)},"k"),Nr=a(()=>ds,"L"),Co=a((t,e)=>{let s=t;for(let r of e)try{s=r.transform(s)}catch{}return s},"y"),jr=a((t,e)=>{e!==t.lastValue&&(t.lastValue=e,Ce===void 0?Dr(t.callbacks,e):Ce.add(t))},"d"),mt=a((t,e=()=>!0)=>{let s=new Set;Ce=s;try{t()}finally{Ce=void 0;let r=[...s].map(i=>typeof i=="function"?i:So(i));for(let i of r){if(!e())break;try{i()}catch{}}}},"v"),ce=a((t,e)=>{jr(t,Co(e,t.optimisticLayers))},"m"),yt=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),jr(t,s);let n=a(()=>{let c=t.optimisticLayers.findIndex(u=>u.id===r.id);return c===-1?!1:(t.optimisticLayers.splice(c,1),!0)},"s"),o=a(()=>{ce(t,t.serverBase)},"a");return{confirm:a(c=>{if(c===void 0){n();return}r.commitCursor=c,ds+=1,r.acknowledgedAt=ds,t.serverCursor!==void 0&&t.serverCursor>=c&&n()&&o()},"confirm"),rollback:a(()=>{i||(i=!0,n(),o())},"rollback")}},"b"),bt=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"),Kr=a((t,e)=>{t.optimisticLayers.length!==0&&(t.optimisticLayers=t.optimisticLayers.filter(s=>s.acknowledgedAt===void 0||s.acknowledgedAt>e))},"g"),ue=a(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"w");var Hr=0,ko="lunora-bridge",To=1e3,Oo=3e3,gt=class{static{a(this,"u")}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(Hr+=1,this.tabId=`tab_${String(Hr)}_${crypto.randomUUID()}`,this.heartbeatInterval=e.heartbeatInterval??To,this.leaderTimeout=e.leaderTimeout??Oo,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??ko),this.bc.addEventListener("message",s=>{this.handleMessage(s.data)})}start(){if(!this.running){if(this.running=!0,this.bc===void 0){this.becomeLeader();return}this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout),this.leaderCheckTimer=setInterval(()=>{this.checkLeaderHealth()},this.leaderTimeout),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeat()},this.heartbeatInterval)}}stop(){this.running=!1,this.leader&&(this.broadcast({type:"yield-leadership",tabId:this.tabId}),this.leader=!1,this.knownLeader=void 0,this.onStopBeingLeader?.()),this.heartbeatTimer!==void 0&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0),this.leaderCheckTimer!==void 0&&(clearInterval(this.leaderCheckTimer),this.leaderCheckTimer=void 0),this.bc?.close()}isLeader(){return this.leader}promoteImmediately(){this.running&&this.becomeLeader()}get leaderTabId(){return this.knownLeader}get id(){return this.tabId}get isRunning(){return this.running}broadcastSubscriptionData(e,s,r,i,n){this.leader&&(this.pendingData.size===0&&queueMicrotask(()=>{this.flushPendingData()}),this.pendingData.set(e,{type:"subscription-data",tabId:this.tabId,key:e,data:s,...r===void 0?{}:{cursor:r},...i===void 0?{}:{epoch:i},...n===void 0?{}:{identity:n}}))}broadcastSubscriptionError(e,s,r){this.leader&&this.broadcast({type:"subscription-error",tabId:this.tabId,key:e,error:s,...r===void 0?{}:{identity:r}})}broadcastSubscriptionSettled(e,s,r,i,n,o){this.leader&&this.broadcast({type:"subscription-settled",tabId:this.tabId,key:e,...s===void 0?{}:{cursor:s},...r===void 0?{}:{epoch:r},...i===void 0?{}:{lastMutationId:i},...n===void 0?{}:{clientId:n},...o===void 0?{}:{identity:o}})}broadcastConnectionStatus(e,s){this.leader&&this.broadcast({type:"connection-status",tabId:this.tabId,status:e,...s===void 0?{}:{identity:s}})}broadcast(e){this.flushPendingData(),this.bc?.postMessage(e)}flushPendingData(){if(this.pendingData.size===0)return;let e=[...this.pendingData.values()];if(this.pendingData.clear(),!this.leader)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),mt(()=>{for(let r of s)this.onSubscriptionData?.(r.key,r.data,r.cursor,r.epoch,r.identity)},()=>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);break}case"subscription-settled":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionSettled?.(e.key,e.cursor,e.epoch,e.lastMutationId,e.clientId,e.identity);break}case"yield-leadership":{this.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 Ke=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 Eo=1024,vt=a(t=>{let e=t.maxBuffer??Eo,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 l=s.shift();return d.resolve({done:!1,value:l}),!0}return i?(d.resolve({done:!0,value:void 0}),!0):(r.unshift(d),!1)},"u"),u={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){u.fail(new b("STREAM_BACKPRESSURE",`stream buffer overflow (max=${e.toString()}); the consumer cannot keep up with the producer`));return}s.push(d),c()}}},h=a(()=>{if(!o){o=!0,i=!0,s.length=0;try{t.onCancel()}catch{}for(;c(););}},"c");return{handle:u,iterable:{cancel:h,[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,l)=>{r.push({reject:l,resolve:d})})},return(){return h(),Promise.resolve({done:!0,value:void 0})}}}}}},"p");var ke=a(t=>t.reason??Object.assign(new Error("The operation was aborted"),{name:"AbortError"}),"c"),de=a(async(t,e,s,r=()=>new j(`LunoraClient: request timed out after ${t.toString()}ms`))=>{if(e?.aborted)throw ke(e);let i=new AbortController,n=[],o=new Promise((u,h)=>{if(t>0){let d=setTimeout(()=>{h(r()),i.abort()},t);n.push(()=>{clearTimeout(d)})}if(e){let d=a(()=>{i.abort(),h(ke(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 u of n)u()}},"m"),hs=a(async(t,e)=>{if(e===void 0)return t;if(e.aborted)throw t.catch(()=>{}),ke(e);let s=a(()=>{},"o"),r=new Promise((i,n)=>{s=a(()=>{n(ke(e))},"o"),e.addEventListener("abort",s,{once:!0})});t.catch(()=>{});try{return await Promise.race([t,r])}finally{e.removeEventListener("abort",s)}},"E"),Wr=a(async(t,e)=>!Number.isFinite(e)||e<=0?t.read():de(e,void 0,async()=>t.read(),()=>new b("STREAM_IDLE",`stream received nothing for ${e.toString()}ms`)),"y");var wt=/^ /u,Io=/^\d+$/u,Ro=2147483647,Ao=10,Fo=1e3,qr=a(t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),"O"),Po=a(t=>{let e="",s,r,i=[];for(let n of t.split(`
|
|
2
|
+
`))if(n.startsWith("event:"))e=n.slice(6).replace(wt,"");else if(n.startsWith("data:"))i.push(n.slice(5).replace(wt,""));else if(n.startsWith("id:")){let o=n.slice(3).replace(wt,"");o.includes("\0")||(s=o)}else if(n.startsWith("retry:")){let o=n.slice(6).replace(wt,"");Io.test(o)&&Number.isSafeInteger(Number(o))&&(r=Math.min(Number(o),Ro))}return{data:i.join(`
|
|
3
|
+
`),event:e,id:s,retry:r}},"U"),Lo=a((t,e,s)=>{let r=e.params??{},i=t.path.split("/").map(c=>{if(!c.startsWith(":"))return c;let u=c.slice(1),h=r[u];if(h===void 0)throw new b("HTTP_STREAM_MISSING_PARAM",`httpStream: missing path param ":${u}" for route ${t.path}`);return encodeURIComponent(qr(h))}).join("/"),n=new URLSearchParams;for(let[c,u]of Object.entries(e.searchParams??{}))u!==void 0&&n.set(c,qr(u));let o=n.toString();return`${s.endsWith("/")?s.slice(0,-1):s}${i}${o===""?"":`?${o}`}`},"Y"),Mo=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 b(i,r,Ue(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 b("HTTP_STREAM_BAD_CHUNK","httpStream: malformed SSE chunk (invalid JSON)")),!0}return!1},"J"),$r=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=Po(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),Mo(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"),ls=a(async(t,e,s,r,i=0)=>{let n=t.getReader(),o=new TextDecoder,c=$r(e,s),u=a(()=>n.cancel().then(()=>{},()=>{}),"a");try{for(;;){let{done:h,value:d}=await Wr(n,i);if(h)break;if(c.append(o.decode(d,{stream:!0})),c.drain())return await u(),!0}return c.append(o.decode()),c.drain()}catch(h){throw r.abort(),u().catch(()=>{}),h}},"q"),zr=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"),xo=a(async(t,e,s,r)=>{let i=$r(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 zr(0,r.signal)}},"K"),_o=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 b("HTTP_STREAM_STATUS",`httpStream: request failed (status ${e.toString()}, ${s}): ${r}`,{status:e,why:typeof i=="string"?i:void 0})},"X"),Qo=a(async(t,e)=>{let s,r=new Promise(n=>{s=setTimeout(()=>{n(void 0)},Fo)}),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"),Do=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"),Br=a(t=>t instanceof Error&&"code"in t?t:new b("HTTP_STREAM_TRANSPORT",t instanceof Error?t.message:String(t),{cause:t}),"M"),Gr=a((t,e,s={})=>{let r=s.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!r)throw new b("INTERNAL","httpStream: no `fetch` implementation available");let i=Lo(t,e??{},s.baseUrl??""),n=new AbortController,o;s.signal&&(s.signal.aborted?n.abort():(o=a(()=>{n.abort()},"i"),s.signal.addEventListener("abort",o,{once:!0})));let c=a(()=>{o&&s.signal?.removeEventListener("abort",o)},"c"),{handle:u,iterable:h}=vt({maxBuffer:s.maxBuffer,onCancel:a(()=>{n.abort()},"onCancel"),onFail:a(()=>{n.abort()},"onFail")}),d=s.reconnect??!1,l=Ke(),{lastEventId:p}=s,f,y=0,m=a(()=>{l.reset(),y=0},"x"),v={},w=a(S=>{try{S()}catch(I){throw v.value={error:I},I}},"R"),k={onFrame:m,onId:a(S=>{w(()=>s.onEventId?.(S)),p=S},"onId"),onRetry:a(S=>{w(()=>s.onRetry?.(S)),f=S},"onRetry")},E=a(async()=>{let S=Do(s.headers,p),I=new b("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"),ie=a(R=>{if(n.signal.aborted){u.complete();return}return{completed:R,error:I}},"_"),x=new AbortController,F=a(()=>{x.abort()},"A");n.signal.addEventListener("abort",F,{once:!0});try{let R=await r(i,{headers:S,method:t.method,signal:x.signal});if(!R.ok){let X=await Qo(R,n.signal);u.fail(_o(X,R.status)??new b("HTTP_STREAM_STATUS",`httpStream: request failed (status ${R.status.toString()})`,{status:R.status}));return}if(!R.body){if(typeof R.text!="function"){u.fail(new b("HTTP_STREAM_NO_BODY","httpStream: response exposes neither a body stream nor a text() read",{hint:Ds}));return}return ie(await xo(R,u,k,x))}return ie(await ls(R.body,u,k,x,s.idleTimeoutMs))}catch(R){if(n.signal.aborted){u.complete();return}if(v.value){let{error:X}=v.value;u.fail(X instanceof Error?X:new b("HTTP_STREAM_CALLBACK","httpStream: an onEventId/onRetry callback threw"));return}return{completed:!1,error:Br(R)}}finally{n.signal.removeEventListener("abort",F)}},"H");return(async()=>{try{for(;;){if(n.signal.aborted){u.complete();return}let S=await E();if(!S)return;if(S.completed||!d||y>=Ao){S.completed||u.fail(S.error);return}y+=1,await zr(f??l.next(),n.signal)}}finally{c()}})().catch(S=>{if(n.signal.aborted){u.complete();return}u.fail(Br(S))}),h},"ne");var M=class t{static{a(this,"y")}static key(e,s,r){return`${e}::${ee(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()}},Y=a((t,e)=>{t.ack=e},"s"),St=a(t=>{t.ack==="inflight"&&Y(t,"idle")},"b");function Ct(t){if(t!==void 0)return e=>{t(e)}}a(Ct,"o");var se=a((t,e)=>{for(let s of t)try{s(e)}catch{}},"d");var Jr=a((t,e)=>{let s=[],r=[],i=a((n,o)=>t.get(M.key(n,o,e)),"c");return{confirms:s,rollbacks:r,store:{getAllQueries:a(n=>{let o=[];for(let c of t.all())c.fn.__lunoraRef===n.__lunoraRef&&(c.shardKey??"")===(e??"")&&o.push({args:c.args,value:c.lastValue});return o},"getAllQueries"),getQuery:a((n,o)=>i(n.__lunoraRef,o??{})?.lastValue,"getQuery"),setQuery:a((n,o,c)=>{let u=i(n.__lunoraRef,o??{});if(!u)return;let h=yt(u,()=>c);h&&(s.push(h.confirm),r.push(h.rollback))},"setQuery")}}},"g");var Vr=0,Uo=a(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();Vr+=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)}_${Vr.toString(36)}_${t}`},"d"),ps=a((t,e)=>t!==void 0&&e!==t,"l"),Tt=Uo,Te=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"),kt=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??=Tt();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=>{Te(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 Te(this.onPersistenceError,"load",o),o}let s=[],r=new Set(this.items.map(o=>o.id));for(let o of e)if(!r.has(o.id)){if(ps(this.version,o.version)){this.persistence.remove(o.id).catch(c=>{Te(this.onPersistenceError,"remove",c,o.id)});continue}r.add(o.id),s.push({args:o.args,baselineSeq:o.baselineSeq,clientId:o.clientId,functionPath:o.functionPath,id:o.id,identity:o.identity,reject: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=>{Te(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),Te(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){Te(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 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"),Ot=a((t,e,s,r)=>{let i;return()=>{if(i)return i;let n=new Promise((o,c)=>{let u=t.open(e,s);u.addEventListener("upgradeneeded",()=>{r(u.result)}),u.addEventListener("success",()=>{o(u.result)}),u.addEventListener("error",()=>{c(u.error??new Error("IndexedDB open failed"))})});return i=n,n.catch(()=>{i===n&&(i=void 0)}),n}},"E"),Et=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 No="lunora-outbox",jo="offline-mutations",fs="by_id",Ko=a((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new b("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let s=t.databaseName??No,r=t.storeName??jo,i=Ot(e,s,1,o=>{o.objectStoreNames.contains(r)||o.createObjectStore(r,{autoIncrement:!0}).createIndex(fs,"id",{unique:!0})}),n=Et(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 u=await Q(c.index(fs).getKey(o));u!==void 0&&await Q(c.delete(u))})},"remove"),replace:a(async o=>{await n("readwrite",async c=>{let u=await Q(c.index(fs).getKey(o.id));u!==void 0&&await Q(c.put(o,u))})},"replace")}},"w"),Yr=a((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return Ko()}},"b");var he=a((t,e,s)=>`${t}::${e}::${s??""}`,"T"),Ho=500,Wo=a((t,e)=>{if(!Number.isInteger(t)||t<1)throw new b("INTERNAL",`${e}: maxEntries must be a positive integer, got ${String(t)}`);return t},"E");var qo="lunora-query-cache",Bo="query-cache",Xr="by_ts",$o=1,zo=a((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new b("INTERNAL","createIndexedDbQueryCache: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryQueryCache()");let s=t.databaseName??qo,r=t.storeName??Bo,i=Wo(t.maxEntries??Ho,"createIndexedDbQueryCache"),n=Ot(e,s,$o,u=>{u.objectStoreNames.contains(r)||u.createObjectStore(r,{keyPath:"key"}).createIndex(Xr,"ts",{unique:!1})}),o=Et(n,r),c=a(async u=>{let h=await Q(u.count())-i;h<=0||await new Promise((d,l)=>{let p=u.index(Xr).openCursor();p.addEventListener("success",()=>{let f=p.result;if(!f||h<=0){d();return}f.delete(),h-=1,f.continue()}),p.addEventListener("error",()=>{l(p.error??new Error("IndexedDB eviction failed"))})})},"y");return{clear:a(async()=>{await o("readwrite",u=>Q(u.clear()))},"clear"),load:a(async()=>o("readonly",u=>Q(u.getAll())),"load"),put:a(async(u,h)=>{await o("readwrite",async d=>{await Q(d.put({...h,key:u})),await c(d)})},"put"),remove:a(async u=>{await o("readwrite",h=>Q(h.delete(u)))},"remove")}},"N"),Zr=a(t=>{if(t!==!1){if(t)return t;if(!(typeof indexedDB>"u"))return zo()}},"L");var ei=new WeakMap,ms=a((t,e)=>{ei.set(t,e)},"i"),ys=a(t=>t===void 0?void 0:ei.get(t),"d"),ti=a((t,e,s,r)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r),n=i.present&&i.answered?ee(i.value):void 0,o=a(()=>{let c=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r);return!i.present||!i.answered||!c.present||!c.answered?!0:ee(c.value)===n},"c");return n!==void 0&&ms(o,{args:s,functionPath:e.__lunoraRef,shardKey:r}),o},"h");var si="/_lunora/rpc",bs="/_lunora/rpc-batch",gs="/_lunora/ws",pi="/_lunora/admin/shard-traffic",Vo="/_lunora/admin/scheduled",Yo="/_lunora/admin/scheduled/status",Xo="/_lunora/admin/scheduled/ws",Zo="/_lunora/admin/scheduled/cancel",ri="/_lunora/admin/scheduled/dead",ec="/_lunora/admin/scheduled/dead/retry",tc="/_lunora/admin/scheduled/dead/cancel",sc="/_lunora/admin/workflows/instances",rc="/_lunora/admin/workflows/instance",ic="/_lunora/admin/workflows/status",Rt="/_lunora/admin/storage",fi="/_lunora/admin/storage/url",mi="/_lunora/admin/storage/buckets",yi="/_lunora/admin/functions",bi="/_lunora/admin/cron-jobs",gi="/_lunora/admin/cron-jobs/run",vi="/_lunora/admin/architecture",wi="/_lunora/admin/openapi",Si="/_lunora/admin/openrpc",Ci="/_lunora/admin/global/tables",ki="/_lunora/admin/global/table",Ti="/_lunora/admin/global/facet",Oi="/_lunora/admin/vector/indexes",Ei="/_lunora/admin/vector/query",Ii="/_lunora/admin/logs/archive",Ri="/_lunora/admin/kv/namespaces",Ai="/_lunora/admin/kv/keys",At="/_lunora/admin/kv/value",Fi="/_lunora/admin/auth/users",Pi="/_lunora/admin/auth/sessions",Li="/_lunora/admin/auth/users/create",Mi="/_lunora/admin/auth/users/role",xi="/_lunora/admin/auth/users/ban",_i="/_lunora/admin/auth/users/unban",Qi="/_lunora/admin/auth/users/password",Di="/_lunora/admin/auth/users/remove",Ui="/_lunora/admin/auth/users/impersonate",Ni="/_lunora/admin/auth/sessions/revoke",ji="/_lunora/admin/auth/sessions/revoke-all",Ki="/_lunora/admin/auth/capabilities",Hi="/_lunora/admin/auth/users/update",Wi="/_lunora/admin/auth/accounts",qi="/_lunora/admin/auth/accounts/unlink",Bi="/_lunora/admin/auth/passkeys",$i="/_lunora/admin/auth/passkeys/delete",zi="/_lunora/admin/auth/two-factor/disable",Gi="/_lunora/admin/auth/organizations",Ji="/_lunora/admin/auth/organizations/members",Vi="/_lunora/admin/auth/organizations/invitations",Yi="/_lunora/admin/auth/organizations/members/remove",Xi="/_lunora/admin/auth/organizations/invitations/cancel",Zi="/_lunora/admin/auth/config",en="/_lunora/admin/auth/sign-up-invitations",tn="/_lunora/admin/auth/sign-up-invitations/create",sn="/_lunora/admin/auth/sign-up-invitations/revoke",rn="/_lunora/admin/auth/organizations/create",nn="/_lunora/admin/auth/organizations/update",an="/_lunora/admin/auth/organizations/remove",on="/_lunora/admin/auth/organizations/members/add",cn="/_lunora/admin/auth/organizations/members/invite",un="/_lunora/admin/auth/organizations/members/role",dn="/_lunora/admin/auth/organizations/teams",hn="/_lunora/admin/auth/organizations/teams/create",ln="/_lunora/admin/auth/organizations/teams/update",pn="/_lunora/admin/auth/organizations/teams/remove",fn="/_lunora/admin/auth/organizations/teams/members",mn="/_lunora/admin/auth/organizations/teams/members/add",yn="/_lunora/admin/auth/organizations/teams/members/remove",bn="/_lunora/admin/auth/organizations/roles",gn="/_lunora/admin/auth/organizations/roles/create",vn="/_lunora/admin/auth/organizations/roles/update",wn="/_lunora/admin/auth/organizations/roles/remove",nc="/api/auth",ac="/get-session",oc="lunora-ping",vs=500,Sn=a((t,e)=>{if(t.size<e)return;let s=t.keys().next().value;s!==void 0&&t.delete(s)},"Pe");new TextDecoder;var cc=new TextEncoder,uc=a(t=>Xt(cc.encode(t)),"Qt"),dc=a(t=>uc(JSON.stringify(t)),"xt"),hc="x-lunora-expect-subject",lc=a(t=>dc({subject:t}),"Kt"),pc="refreshBatch",ii=Symbol.for("lunora:session-change"),fc="lunora:session-change",mc="better-auth.message",yc="signout",Cn=a(()=>{let t=globalThis,e=t[ii];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},t[ii]=e),e},"Me"),bc=a(()=>"document"in globalThis,"Jt"),gc=a(async()=>{let t=[];for(let e of Cn().listeners)try{t.push(e())}catch{}await Promise.allSettled(t)},"zt"),vc=a((t,e)=>{if(t!==mc||e===null)return!1;try{let s=JSON.parse(e);return s?.event==="session"&&s.data?.trigger===yc}catch{return!1}},"Yt"),wc=a(t=>{let e=[],s=a(()=>{gc().catch(()=>{})},"t"),r;try{r=typeof BroadcastChannel=="function"?new BroadcastChannel(fc):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=>{vc(o.key,o.newValue)&&s()},"r");i.addEventListener("storage",n),e.push(()=>{i.removeEventListener?.("storage",n)})}return()=>{for(let n of e)n()}},"Xt"),Sc=a(t=>{let e=Cn();return e.listeners.add(t),e.detach===void 0&&bc()&&(e.detach=wc(e.tab)),()=>{e.listeners.delete(t),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},"Zt"),ni="/_lunora/ws/reauth",Cc="lunora",kc="lunora.bearer.",Tc=a(t=>`${kc}${Xt(new TextEncoder().encode(t))}`,"ss"),Oc=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}},"is"),Is=a(t=>"args"in t?{...t,args:T(t.args)}:t,"ae"),kn=a(async t=>(t.assertOpen(),((await t.adminFetch(Vo,"GET")).records??[]).map(e=>Is(e))),"Tr"),Tn=a(async t=>{t.assertOpen();let e=await t.adminFetch(Yo,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},"Cr"),On=a(async(t,e)=>(t.assertOpen(),{cancelled:(await t.adminFetch(Zo,"POST",{id:e})).cancelled===!0}),"kr"),En=a(async t=>(t.assertOpen(),(await Oc(async e=>await t.adminFetch(e===void 0?ri:`${ri}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>Is(e))),"Ar"),In=a(async(t,e)=>(t.assertOpen(),{retried:(await t.adminFetch(ec,"POST",{id:e})).retried===!0}),"Er"),Rn=a(async(t,e)=>(t.assertOpen(),{removed:(await t.adminFetch(tc,"POST",{id:e})).removed===!0}),"_r"),An=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(`${sc}?${s.toString()}`,"GET");return{configured:r.configured,instances:r.instances??[],page:r.page??1,perPage:r.perPage??e.perPage??0,totalCount:r.totalCount}},"Ir"),Fn=a(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({id:e.id,name:e.name}),r=await t.adminFetch(`${rc}?${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??[]}},"Rr"),Pn=a(async(t,e)=>(t.assertOpen(),{status:(await t.adminFetch(ic,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),"Or"),B=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)}},"C"),Cs=a(t=>{try{return N(t),!0}catch{return!1}},"te"),Ln=a(t=>t!==null&&typeof t=="object"&&("error"in t||"result"in t),"Fe"),Ec=a((t,e,s)=>{let r=Array.from({length:e}),i=a(n=>({error:K(os(n),s),ok:!1}),"i");for(let n of t){if(typeof n.id!="number"||n.id<0||n.id>=e)continue;if(!Ln(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(lt(c),s),ok:!1}}}return r.map(n=>n??{error:K(new Error("batch call returned no result"),s),ok:!1})},"rs"),ws=a((t,e)=>e!==null?{}:t===null?{expectSubject:null}:t?.startsWith("subj:")===!0?{expectSubject:t.slice(5)}:{},"X"),He=a(t=>t==="connected"||t==="polling","D"),g=a(t=>t??"","f"),$=a((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"k"),Ic=a(t=>{if(!t.pendingStreams||t.pendingStreams.length===0)return;let e=t.pendingStreams;t.pendingStreams=[];for(let s of e)$(t,s)},"ns"),Rc=new TextDecoder,Ac=a(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return Rc.decode(t)},"as"),re=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()}},Oe=a(t=>{t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)},"H"),Fc=a((t,e,s)=>{Oe(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(oc)}catch{}},e))},"cs"),ai=a((t,e,s,r)=>{let{WebSocketImpl:i,connectTimeoutMs:n,heartbeatIntervalMs:o}=s;if(i===void 0)throw new b("INTERNAL","no WebSocket implementation available");let c=r.protocols===void 0?new i(e):new i(e,r.protocols);t.socket=c;let u=a(()=>{Oe(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket===c&&(t.socket=void 0)},"c"),h=a(d=>{u(),r.onClose(d)},"d");n>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===c){try{c.close()}catch{}h()}},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&&Fc(t,o,h)}}),c.addEventListener("message",d=>{if(t.socket===c){t.lastFrameAt=Date.now();try{r.onMessage(d)}catch(l){console.error("[lunora] server frame handler threw",l)}}}),c.addEventListener("close",d=>{t.socket===c&&h(d)}),c.addEventListener("error",()=>{t.socket===c&&h()})},"Ce"),Pc=a(t=>{let{afterFailedAttempts:e,intervalMs:s,onReachable:r,onStateChange:i,poll:n}=t,o=s>0&&e>0,c=0,u,h=!1,d=!1,l=a(()=>{u!==void 0&&(clearInterval(u),u=void 0,h=!1,i())},"h"),p=a(y=>{if(u!==void 0){if(!y){l();return}h||(h=!0,i()),r()}},"l"),f=a(()=>{d||(d=!0,n().then(p).finally(()=>{d=!1}).catch(()=>{}))},"p");return{hasFailedOpen:a(()=>c>0,"hasFailedOpen"),isPolling:a(()=>u!==void 0&&h,"isPolling"),noteFailedOpen:a(()=>{c+=1,!(!o||u!==void 0||c<e)&&(u=setInterval(f,s),i(),f())},"noteFailedOpen"),noteOpen:a(()=>{c=0,l()},"noteOpen"),stop:l}},"ds"),Lc=1e4,oi=a(async t=>de(Lc,void 0,t,()=>new TypeError("LunoraClient: poll timed out")),"ke"),Mn=new Set(["DELIVERY_FENCED","RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),ci=a(t=>{if(t instanceof j)return!0;let e=t?.code;return e===void 0||Mn.has(e)||ss.has(e)},"Ae"),Mc=1e3,xn=6e4,xc={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},We=a((t,e,s)=>{let r=rs(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 j(n,i):new b(xc[t]??"BAD_REQUEST",n,{data:i});return K(o,s)},"W"),ks=a((t,e=Math.random)=>{let s=Math.min(Mc*2**Math.max(t-1,0),xn);return Math.round(s*(.5+e()*.5))},"se"),_c=a(t=>{let e=t?.code;return t instanceof j||e===void 0||Mn.has(e)},"fs"),Qc=a((t,e,s)=>{let r=ht(t);return r!==void 0&&r>0?Math.min(r,xn):_c(t)?ks(e,s):void 0},"ps"),Dc=983040,Uc=a(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"ys"),Nc=a(t=>{let e=new Map;for(let s of t)typeof s.id=="number"&&Ln(s.body)&&e.set(s.id,s.body);return e},"Ss"),jc=a((t,e)=>{if(t===void 0)return{kind:"unanswered"};if("error"in t)return{error:K(os(t),e),kind:"errored"};try{return{commitCursor:t.commitCursor,kind:"committed",value:T(t.result)}}catch(s){return{commitCursor:t.commitCursor,error:K(lt(s),e),kind:"undecodable"}}},"vs"),Ss=a((t,e)=>`${g(t)}\0${e}`,"Z"),Kc=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)},"bs"),Ts=class{static{a(this,"gs")}constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,s){Sn(this.buffers,this.maxBuffers),this.buffers.set(Ss(e,s.pokeId),{baseCheckpoint:s.baseCheckpoint,bases:new Map,epoch:s.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}part(e,s){let r=this.buffers.get(Ss(e,s.pokeId));if(!r)return;let i=[];try{for(let c of s.rowsPatch)i.push(c.value===void 0?c:{...c,value:T(c.value)})}catch(c){r.undecodable.set(s.shapeId,c);return}let n=r.parts.get(s.shapeId)??[];for(let c of i)n.push(c);r.parts.set(s.shapeId,n),s.lastMutationId!==void 0&&r.lastMutationId.set(s.shapeId,s.lastMutationId);let o=s.baseCheckpoint??r.baseCheckpoint;o!==void 0&&r.bases.set(s.shapeId,o),s.reset===!0&&r.resets.add(s.shapeId)}end(e,s){let r=Ss(e,s),i=this.buffers.get(r);return i&&this.buffers.delete(r),i}clear(){this.buffers.clear()}},Hc=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(),Kc(t.rows,r),t.answered=!0,s.checkpoint!==void 0&&(t.serverCursor=s.checkpoint),s.epoch!==void 0&&(t.serverEpoch=s.epoch);let u=e.lastMutationId.get(t.id);return u!==void 0&&(t.lastMutationId=u),"applied"},"ws"),ui=a(t=>{let e=[...t.rows.values()];for(let s of t.callbacks)try{s(e)}catch{}},"Ee"),Wc=a((t,e)=>{for(let[s,r]of e.undecodable){let i=t.get(s);i&&se(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape \u2014 ${r instanceof Error?r.message:String(r)}`})}},"Ts"),Os=a((t,e)=>{t.lastMutationId=Math.max(t.lastMutationId??0,e)},"ie"),Es=a((t,e=!1)=>{let s=t.serverCursor,r=t.lastMutationId;Ur(()=>{for(let i of t.checkpointCallbacks)i({checkpoint:s,mutationId:r,...e&&{rowsFollow:!0}})})},"re"),_n=a((t,e,s)=>{t.serverBase=e,s.cursor!==void 0&&(t.serverCursor=s.cursor),s.epoch!==void 0&&(t.serverEpoch=s.epoch)},"Ne"),qc=a((t,e)=>e.cursor!==void 0&&t.serverCursor!==void 0&&t.serverBase!==void 0&&e.epoch!==void 0&&e.epoch===t.serverEpoch&&e.cursor<t.serverCursor,"Cs"),Bc=a(t=>t.type==="delta"&&t.more===!0,"ks"),Ft=a((t,e)=>t!==void 0&&t!==e,"j"),$c=a((t,e)=>e==="connected"&&t!=="connected"||e==="polling"&&t!=="connected"&&t!=="polling","As"),zc=a(t=>{for(let e of t.activeSubscriptions())e.valueReceived=!1,t.ensureSocket(e.shardKey),t.queueResubscribe(e);for(let e of t.activeShapes())e.answered=!1,t.ensureSocket(e.shardKey);for(let e of t.queuedShardKeys())t.ensureSocket(e);t.broadcastStatus(t.computeStatus(),t.identityFingerprint()),t.emitConnectionStatus()},"Es"),Gc=a(t=>{t.closeConnections();let e=t.leader;e.status=void 0,e.wasEverConnected=!1;for(let s of t.activeSubscriptions())Y(s,"idle"),s.valueReceived=!1;for(let s of t.activeShapes())s.answered=!1;t.emitConnectionStatus()},"_s"),Jc=a((t,e,s)=>{if(Ft(s,t.identityFingerprint()))return;let r=t.leader,i=$c(r.status,e);r.status=e,e==="connected"&&(r.wasEverConnected=!0),t.emitConnectionStatus(),i&&(t.awaitLeaderAnswers(),t.flushOfflineQueues())},"Is"),Vc=a(t=>{t.isLeader()&&t.broadcastStatus(t.computeStatus(),t.identityFingerprint())},"Rs"),Yc=a((t,e,s,r,i,n)=>{if(Ft(n,t.identityFingerprint()))return;let o=t.subscription(e);if(!o)return;t.dropCacheSeed(e);let c=!o.valueReceived;o.valueReceived=!0,_n(o,s,r===void 0?{}:{cursor:r,epoch:i}),r!==void 0&&bt(o,r),ce(o,s),c&&t.emitConnectionStatus(),t.settleAwaitedAnswer(o,!0)},"Os"),Xc=a((t,e,s,r)=>{if(Ft(r,t.identityFingerprint()))return;let i=t.subscription(e);if(i){let n=!i.valueReceived;i.valueReceived=!0,se(i.errorCallbacks,s),n&&t.emitConnectionStatus(),t.settleAwaitedAnswer(i,!1)}},"Ls"),Zc=a((t,e,s,r,i,n,o)=>{if(Ft(o,t.identityFingerprint()))return;let c=t.subscription(e);c&&(t.ackAndAdvanceCursor(c,s,r),i!==void 0&&n===t.clientIdentifier()&&Os(c,i),Es(c))},"Ps"),eu=a((t,e,s)=>t!==null||e&&s===null,"Ms"),tu=a(t=>t.sensitive===!0,"Fs"),su=a((t,e)=>{if(!tu(t))return e;if(e.onlineOnly===!1)throw new b("BAD_REQUEST",`'${t.__lunoraRef}' takes a sensitive argument and is always online-only; onlineOnly: false is not allowed`);return{...e,onlineOnly:!0}},"Hs"),ru=[Pr,pc],iu=a(t=>t.type==="data"||t.type==="delta"||t.type==="settled"||t.type==="resume"||t.type==="error"&&typeof t.id=="string","Ns"),nu=100,Qn=1e4,au=1e4,ou=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)})},"Bs"),di=a(async t=>typeof t=="function"?await t():t,"_e"),hi=a(async(t,e,s,r)=>{let i=new AbortController,n=setTimeout(()=>{i.abort()},Qn);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)}},"Ie"),li=a((t,e)=>new b("OFFLINE_NOT_QUEUED",`'${t}' is online-only and the connection is not live, so it was not queued`,{cause:e,hint:Qs}),"Re"),cu=a((t,e)=>t instanceof TypeError&&Cs(e),"Qs"),uu=a((t,e,s,r)=>e||t===!0&&s&&!r,"xs"),du=Promise.resolve(),hu=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 ls(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}},"Ks"),It=class t{static{a(this,"We")}static MAX_POKE_BUFFERS=256;static createClientQuery(e,s){return{defaultValue:s,key:e}}url;wsUrl;adminHost={adminFetch:a((...e)=>this.adminFetch(...e),"adminFetch"),assertOpen:a(()=>{this.assertOpen()},"assertOpen")};clientQueryStore;wsToken;wsTicket;wsCredentialGeneration=0;refusedCredentialGeneration;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;rpcTimeoutMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;authTokenOnUpgrade;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;mutationIssueCounter=0;persistence;persistenceVersion;releasePageHideFlush;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new M;tabCoordinator;leader={status:void 0,wasEverConnected:!1};connections=new Map;idleClosedShards=new Set;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;tokenFingerprint;authSubject=void 0;subjectToken=null;sessionProbesInFlight=0;sessionProbeGeneration=0;identityQuestions=0;identityAnsweredAt=0;releaseSessionChangeListener;warnedIdentityDisagreement=!1;identityResolutionExpected=!1;identitySettled=!1;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new re;statusListeners=new re;roomFlushes=new Map;roomIdentityResets=new Set;tokenExpiredListeners=new re;identityChangeListeners=new re;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new re;pendingChangeListeners=new re;syncStatusListeners=new re;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??H(cs(e.url),gs),this.wsToken=e.wsToken,this.wsTicket=e.wsTicket;let s=e.authBasePath??nc;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??Mr(),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=Zr(e.queryCache),this.clientQueryStore=new pt,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=du),this.offlineQueue=new kt(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-${Tt()}`,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=Sc(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,s){let r=this.authToken!==e,i=this.identityFingerprint(),n=this.authSubject===void 0||this.subjectToken===this.authToken,o=this.subjectAwaitingReconfirm(),c=this.isKnownNobody(),u=this.authToken;this.authToken=e,r&&(this.tokenFingerprint=void 0),this.applySubject(e,s);let h=this.identityFingerprint(),d=!r&&e!==null&&n,l=!r&&e===null&&i===null&&n&&!c,p=h!==i,f=!1;p&&(d?(this.restampQueuedIdentity(i,h),this.restampWatermarks(i,h),this.restampConnectionIdentity(i,h),this.reseedFromHydratedCache()):l?(this.restampWatermarks(i,h),this.restampConnectionIdentity(i,h),this.reseedFromHydratedCache()):f=this.retirePreviousIdentity(i,c,u,e)),f||this.applyUpgradeBearer(this.reconcileUpgradeBearer(u,e,p)),p&&this.restartTabCoordinatorForIdentity(),this.syncReadCacheToCredential(o),r&&this.authTokenListeners.emit(e),(h!==i||r||o)&&this.offlineQueue.size>0&&He(this.computeStatus())&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}expectIdentityResolution(){this.identityResolutionExpected=!0}currentBaseline(e){return this.baselineCursorFor(e)}replayIdentityVerdict(e){let s=this.identityVerdict(e);if(s!=="match")return{verdict:s};let r=Object.freeze({});return this.replayCredentials.set(r,{authToken:this.authToken,stamp:e}),{credential:r,verdict:s}}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,s,r){let i=r?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new b("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let n=r?.shardKey??"",o=this.identityFingerprint(),c,u,h;try{u=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;h=d}if(c!==void 0&&c>(this.clientWatermarks.get(o??"")?.get(n)??0)){let d=this.clientWatermarks.get(o??"");d===void 0&&(Sn(this.clientWatermarks,8),d=new Map,this.clientWatermarks.set(o??"",d)),d.set(n,c)}if(h!==void 0)throw h;return{applied:c===void 0||c===i,result:u}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}onIdentityChange(e){return this.identityChangeListeners.add(e)}identityEpoch(){return this.retiredIdentities}async getCurrentUser(){if(this.identityResolutionExpected=!0,this.closed||!this.fetchImpl)return this.identitySettled=!0,null;let e={},s=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`),this.sessionProbesInFlight+=1,this.identityQuestions+=1,this.sessionProbeGeneration=this.identityQuestions;let r=this.sessionProbeGeneration;try{let i=await this.fetchImpl(H(this.url,`${this.authBasePath}${ac}`),{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=g(s.shardKey);e===void 0?this.connectionContexts.delete(r):this.connectionContexts.set(r,e),this.refreshConnectionContext(r),e===void 0&&this.releaseIdleShard(s.shardKey)}acquireConnectionContext(e,s={}){if(this.followsAnotherTab())return()=>{};let r=g(s.shardKey),i={context:e},n=this.connectionContextHolders.get(r);n?n.push(i):this.connectionContextHolders.set(r,[i]),this.refreshConnectionContext(r);let o=!1;return()=>{if(o)return;o=!0;let c=this.connectionContextHolders.get(r);if(!c)return;let u=c.indexOf(i);u!==-1&&c.splice(u,1),c.length===0&&this.connectionContextHolders.delete(r),this.refreshConnectionContext(r),this.releaseIdleShard(s.shardKey)}}whisperSubscribe(e,s,r={}){this.assertLeaderOwnedSurface("whisperSubscribe");let i=g(r.shardKey),n=this.whisperHandlers.get(i);n||(n=new Map,this.whisperHandlers.set(i,n));let o=n.get(e),c=o===void 0;if(o||(o=new Set,n.set(e,o)),o.add(s),this.ensureSocket(r.shardKey),c){let u=this.getConnection(r.shardKey);u&&this.sendWhisperJoin(u,i,e)}return()=>{let u=this.whisperHandlers.get(i),h=u?.get(e);if(!h?.delete(s)||h.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let d=this.getConnection(r.shardKey);d&&$(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 b("INTERNAL","LunoraClient: subscribeLiveTopic needs a non-empty topic");this.nextLiveSocketId+=1;let c=`ws-live-${String(this.nextLiveSocketId)}`,u=g(i),h=`/live/${n}/control`,d=this.whisperSubscribe(o,()=>{},{shardKey:i}),l=a(()=>{let m=d;d=void 0,m?.()},"l"),p=this.liveSocketGrants.get(u);p===void 0&&(p=new Map,this.liveSocketGrants.set(u,p)),p.set(c,{onError:s,onEvent:r,release:l,stream:n,topic:o});let f=this.getConnection(i)?.connectionId;f!==void 0&&this.grantWhenJoined(i,c,f);let y=!1;return()=>{if(y)return;y=!0;let m=this.liveSocketGrants.get(u),v=m?.delete(c)===!0;m?.size===0&&this.liveSocketGrants.delete(u);let w=this.getConnection(i)?.connectionId;v&&w!==void 0&&this.postLiveControl(h,i,{action:"unsubscribe",connectionId:w,stream:n,subscriptionId:c,topic:o}),l()}}whisper(e,s,r={}){return this.assertLeaderOwnedSurface("whisper"),this.sendEncodedWhisper(e,B(s??null,`whisper data for topic '${e}'`),r)}connectRoom(e,s,r={}){let i=`room:${e.name}`,n=this.whisperSubscribe(i,p=>{s.onMessage(p)},r),o=!1,c=[],u=a(()=>{c.length=0},"c"),h=a(()=>{for(;c.length>0&&this.roomSendsAdmitted(r.shardKey);){if(!this.sendEncodedWhisper(i,c[0],r))return;c.shift()}},"d"),d=g(r.shardKey),l=this.roomFlushes.get(d)??new Set;return l.add(h),this.roomFlushes.set(d,l),this.roomIdentityResets.add(u),{close:a(()=>{o=!0,c.length=0,l.delete(h),l.size===0&&this.roomFlushes.delete(d),this.roomIdentityResets.delete(u),n()},"close"),send:a(p=>{if(o||this.closed||this.WebSocketImpl===void 0)return!1;let f=B(p,`room message for '${i}'`),y=typeof structuredClone=="function"?structuredClone(f):JSON.parse(JSON.stringify(f));return h(),c.length===0&&this.roomSendsAdmitted(r.shardKey)&&this.sendEncodedWhisper(i,y,r)?!0:c.length>=nu?!1:(c.push(y),!0)},"send")}}connectWebSocket(e,s,r={}){if(this.assertLeaderOwnedSurface("connectWebSocket"),this.WebSocketImpl===void 0||this.closed)return{close:a(()=>{},"close"),send:a(()=>{},"send")};let i=a(c=>{try{c?.()}catch(u){console.error("[lunora] socket route handler threw",u)}},"i"),n,o=this.openSupplementarySocket(this.supplementaryUrl(e),{offerBearer:!0,onClose:a(()=>{clearTimeout(n),i(s.onClose)},"onClose"),onMessage:a(c=>{let u;try{u=JSON.parse(typeof c.data=="string"?c.data:"")}catch{return}u.type==="message"&&(o.resetBackoff(),i(()=>{s.onMessage(T(u.data))}))},"onMessage"),onOpen:a(()=>{clearTimeout(n);let c=o.socket();n=setTimeout(()=>{o.socket()===c&&o.resetBackoff()},5e3),i(s.onOpen)},"onOpen"),shardKey:r.shardKey});return{close:a(()=>{clearTimeout(n),o.close()},"close"),send:a(c=>{let u=JSON.stringify(B(c,`socket message for '${e}'`)),h=o.socket();if(h!==void 0)try{h.send(u)}catch{}},"send")}}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let s=this.statusListeners.add(e);return e(this.computeStatus()),s}syncStatus(){let e=this.computeStatus(),s=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader(),r=0;for(let n of this.subscriptions.all())(s||this.connectionGateState(n.shardKey).polling?n.valueReceived:n.ack==="acked")||(r+=1);for(let n of this.shapeSubscriptions.values())n.answered||(r+=1);let i=this.offlineQueue.size+this.offlineQueue.replaying;return{connection:e,pendingSubscriptions:r,pendingWrites:i,synced:He(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=je(this.wsUrl),i=a(o=>{let c=je(String(o));return c.host===r.host&&s(c)===s(r)},"i"),n=e;return new Proxy(e,{construct:a((o,[c,u,...h])=>new n(c,u??(i(c)?this.upgradeProtocols():void 0),...h),"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 ti(this,e,s,r)}whenReady(e={}){return e.signal===void 0?this.readyPromise:hs(this.readyPromise,e.signal)}get isReady(){return this.readyResolved}peekHydratedQuery(e,s,r){return this.peekHydratedQueryByKey(e,ee(s),r)}peekHydratedQueryByKey(e,s,r){if(!this.readyResolved)return;let i=he(e,s,r),n=this.hydratedQueryCache.get(i);if(n!==void 0)return this.cachedQueryMatchesIdentity(n)?n.value:void 0}peekActiveQuerySnapshot(e,s,r){let i=M.key(e,s,r),n=this.subscriptions.get(i);return{answered:n!==void 0&&(n.lastValue!==void 0||n.ack==="acked"||n.valueReceived),present:n!==void 0,value:n?.lastValue}}async query(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0,signal:r.signal})}async batch(e){return de(this.rpcTimeoutMs,void 0,async s=>this.sendBatch(e,s))}async mutation(e,s,r={}){if(r.signal?.aborted)throw ke(r.signal);let{value:i}=await hs(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,u=0,h=0;for(let d=0;d<o;d+=i){let l=s.slice(d,d+i),p=h,{committed:f}=await this.runMutation(e,n(l),{...r.importId===void 0?{}:{mutationId:`${r.importId}:${String(p)}`},shardKey:r.shardKey});h+=1,c+=l.length,f&&(u+=l.length),r.onProgress?.({done:c,total:o})}return{chunks:h,imported:u,queued:c-u}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let s=this.openSupplementarySocket(H(cs(this.url),Xo),{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=>Is(n))))},"onMessage")});return s.close}subscribe(e,s,r,i={}){if(this.assertOpen(),i.signal?.aborted)return()=>{};let n=s??{},o=M.key(e.__lunoraRef,n,i.shardKey),c=this.subscriptions.get(o),u=Ct(r),h=Ct(i.onError),d=Ct(i.onCheckpoint);if(!c){this.nextSubId+=1;let y=`sub_${this.nextSubId.toString()}`,m=ee(n),v=this.takeHydratedCache(e.__lunoraRef,m,i.shardKey);c={ack:"idle",args:n,argsKey:m,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:y,lastValue:v?.value,optimisticLayers:[],serverBase:v?.value,serverCursor:v?.serverCursor,shardKey:i.shardKey,valueReceived:!1,wireArgs:B(n,`args for '${e.__lunoraRef}'`),...v?.serverEpoch===void 0?{}:{serverEpoch:v.serverEpoch}},this.subscriptions.add(c),this.emitSyncStatus(),this.isCrossTabFollower()&&He(this.computeStatus())&&this.awaitLeaderAnswer(c),v!==void 0&&this.cacheSeededQueries.set(o,v)}if(c.callbacks.add(u),h&&c.errorCallbacks.add(h),d&&c.checkpointCallbacks.add(d),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let l=c,p=!1,f=a(()=>{if(!p&&(p=!0,i.signal?.removeEventListener("abort",f),l.callbacks.delete(u),h&&l.errorCallbacks.delete(h),d&&l.checkpointCallbacks.delete(d),l.callbacks.size===0)){this.sendOrQueueUnsubscribe(l.shardKey,l.id,"unsubscribe"),this.returnCacheSeed(M.keyOf(l)),this.subscriptions.remove(l);let y=this.getConnection(l.shardKey);y&&this.settleSubscribeWatchdog(y,l.id),this.releaseIdleShard(l.shardKey),this.emitSyncStatus(),this.settleAwaitedAnswer(l,!0)}},"p");return i.signal?.addEventListener("abort",f,{once:!0}),i.signal?.aborted&&f(),f}subscribeShape(e,s,r={}){if(this.assertOpen(),this.followsAnotherTab()){let{onError:o}=r;return o!==void 0&&queueMicrotask(()=>{o({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;let i=`shape_${this.nextShapeId.toString()}`,n={answered:!1,args:e.args,callbacks:new Set([s]),errorCallbacks:r.onError?new Set([r.onError]):new Set,id:i,name:e.name,onCheckpoint:r.onCheckpoint,rows:new Map,shardKey:r.shardKey,wireArgs:e.args===void 0?void 0:B(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 b("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;let i=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=r,o=s??{},{handle:c,iterable:u}=vt({maxBuffer:r.maxBuffer,onCancel:a(()=>{this.cancelStream(i,n)},"onCancel")});this.ensureSocket(n);let h=this.getConnection(n),d={id:i,query:{args:B(o,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"},l={durable:r.durable===!0,generation:void 0,handle:c,lastSeq:0,message:d,shardKey:n};this.streams.set(i,l);let p=h?.wsState==="open"&&$(h,d);if(!p&&h===void 0)return this.forgetStream(i),c.fail(new b("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),u;if(!p){for(h.pendingStreams=h.pendingStreams??[];h.pendingStreams.length>=64;){let f=h.pendingStreams.shift()?.id,y=f?this.streams.get(f):void 0;y&&(y.handle.fail(new b("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(f))}h.pendingStreams.push(d)}return u}httpStream(e,s,r={}){if(this.closed)throw new b("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...r.headers};return Gr(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 b("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");let i=e.__lunoraRef,n=await this.fetchImpl(H(this.url,si),{body:JSON.stringify({args:B(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 h=await n.json().catch(()=>{});if(h?.error)throw Se(h.error);let d=n.statusText?` ${n.statusText}`:"";throw new b("INTERNAL",`LunoraClient: request failed (status ${n.status.toString()}${d})`)}if(!n.body)throw new b("HTTP_STREAM_NO_BODY","LunoraClient: streaming response has no body");let{failure:o,terminal:c}=await hu(n.body,r.signal,r.onFrame);if(o!==void 0)throw o;if(c===void 0)throw new b("HTTP_STREAM_INTERRUPTED","LunoraClient: stream ended without a complete frame");let u;try{u=JSON.parse(c)}catch{throw new b("HTTP_STREAM_BAD_CHUNK","LunoraClient: streaming result is not valid JSON")}if(typeof u!="object"||u===null||!("result"in u))throw new b("HTTP_STREAM_INTERRUPTED","LunoraClient: stream ended without a result");return T(u.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 b("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(let e of this.connections.values())this.teardownConnection(e);for(let e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear(),this.supplementaryBounces.clear();for(let e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear();for(let e of this.leaderAnswerTimers.values())clearTimeout(e);this.leaderAnswerTimers.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.syncStatusListeners.clear(),this.whisperHandlers.clear(),this.liveSocketGrants.clear(),this.roomFlushes.clear(),this.roomIdentityResets.clear(),this.shapeSubscriptions.clear(),this.pokeAssembler.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}retirePreviousIdentity(e,s,r,i){return this.rejectQueuedForIdentityChange(e),this.warnRefreshWithoutSubject(r,i),eu(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?[Cc,Tc(this.authToken)]:void 0}applyUpgradeBearer(e){e==="cold"?(this.resetRoomSends(),this.reconnectCold()):e==="warm"&&this.bounceShardSockets(!0)}assertOpen(){if(this.closed)throw new b("INTERNAL","LunoraClient is closed")}followsAnotherTab(){let e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;let s=e.leaderTabId;return s!==void 0&&s!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new b("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}shardInUse(e){let s=a(r=>g(r)===e,"t");return this.subscriptions.all().some(r=>s(r.shardKey))||[...this.shapeSubscriptions.values()].some(r=>s(r.shardKey))||[...this.streams.values()].some(r=>s(r.shardKey))||this.whisperHandlers.has(e)||this.connectionContexts.has(e)||this.connectionContextHolders.has(e)||this.offlineFlushes.has(e)||this.offlineQueue.hasPending(r=>s(r.shardKey))}releaseIdleShard(e){let s=g(e),r=this.connections.get(s);this.closed||s===""||r===void 0||(clearTimeout(r.idleTimer),r.idleTimer=setTimeout(()=>{r.idleTimer=void 0,!(this.closed||this.connections.get(s)!==r||this.shardInUse(s))&&(r.wasEverConnected&&this.idleClosedShards.add(s),this.teardownConnection(r),this.connections.delete(s),this.emitConnectionStatus())},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=g(e.shardKey);for(let[i,n]of this.streams)g(n.shardKey)===s&&(n.handle.fail(new b("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(i));e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e),this.clearConnectionTimers(e),clearTimeout(e.idleTimer),e.idleTimer=void 0,Oe(e);let{socket:r}=e;if(r){e.socket=void 0;try{r.close()}catch{}}e.wsState="closed"}createTabCoordinator(){let e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`,s={activeShapes:a(()=>[...this.shapeSubscriptions.values()],"activeShapes"),activeSubscriptions:a(()=>this.subscriptions.all(),"activeSubscriptions"),awaitLeaderAnswers:a(()=>{this.awaitLeaderAnswers()},"awaitLeaderAnswers"),broadcastStatus:a((r,i)=>this.tabCoordinator?.broadcastConnectionStatus(r,i),"broadcastStatus"),closeConnections:a(()=>{for(let[r,i]of this.connections)this.teardownConnection(i),this.connections.delete(r)},"closeConnections"),computeStatus:a(()=>this.computeStatus(),"computeStatus"),emitConnectionStatus:a(()=>{this.emitConnectionStatus()},"emitConnectionStatus"),ensureSocket:a(r=>{this.ensureSocket(r)},"ensureSocket"),flushOfflineQueues:a(()=>{this.flushAllOfflineQueues()},"flushOfflineQueues"),identityFingerprint:a(()=>this.identityFingerprint(),"identityFingerprint"),isLeader:a(()=>this.tabCoordinator?.isLeader()===!0,"isLeader"),leader:this.leader,queueResubscribe:a(r=>{this.queueResubscribe(r)},"queueResubscribe"),queuedShardKeys:a(()=>this.queuedOfflineShardKeys,"queuedShardKeys"),clientIdentifier:a(()=>this.clientId,"clientIdentifier"),dropCacheSeed:a(r=>{this.dropCacheSeed(r)},"dropCacheSeed"),ackAndAdvanceCursor:a((r,i,n)=>{this.ackAndAdvanceCursor(r,i,n)},"ackAndAdvanceCursor"),settleAwaitedAnswer:a((r,i)=>{this.settleAwaitedAnswer(r,i)},"settleAwaitedAnswer"),subscription:a(r=>this.subscriptions.get(r),"subscription")};return new gt({channelName:e,onBecomeLeader:a(()=>{zc(s)},"onBecomeLeader"),onStopBeingLeader:a(()=>{Gc(s)},"onStopBeingLeader"),onConnectionStatus:a((r,i)=>{Jc(s,r,i)},"onConnectionStatus"),onSubscriptionData:a((r,i,n,o,c)=>{Yc(s,r,i,n,o,c)},"onSubscriptionData"),onLeaderClaimAnswered:a(()=>{Vc(s)},"onLeaderClaimAnswered"),onSubscriptionError:a((r,i,n)=>{Xc(s,r,i,n)},"onSubscriptionError"),onSubscriptionSettled:a((r,i,n,o,c,u)=>{Zc(s,r,i,n,o,c,u)},"onSubscriptionSettled")})}async sendBatch(e,s){if(this.assertOpen(),!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(H(this.url,bs),{body:JSON.stringify({calls:e.map((c,u)=>({args:B(c.args??{},`args for batch call '${c.fn.__lunoraRef}'`),functionPath:c.fn.__lunoraRef,id:u,shardKey:c.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:s}),i=r.headers.get("x-d1-bookmark");i&&this.bookmark.set(i);let n;try{n=await r.json()}catch{throw K(new b("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 b("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`),r.headers);for(let c of n.results??[]){let u=c.body?.commitCursor;typeof c.id=="number"&&typeof u=="number"&&this.recordShardCursor(e[c.id]?.shardKey,u)}return Ec(n.results??[],e.length,r.headers)}async runMutation(e,s,r){this.assertOpen();let i=su(e,r),n=s,o=i.mutationId??Tt();this.mutationIssueCounter+=1;let c=this.mutationIssueCounter,u=this.takeReplayCredential(i.replayCredential),h=this.composedBaselineFor(i.replayBaseline,i.shardKey);this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i);let{confirms:d,rollbacks:l}=this.applyOptimisticUpdates(e.__lunoraRef,n,i.shardKey,i.optimistic);this.applyOptionalOptimisticUpdate(i.optimisticUpdate,s,i.shardKey,l,d);let p=i.onlineOnly?void 0:this.offlineFlushes.get(g(i.shardKey));p!==void 0&&await p;let{httpFirst:f,midReconnect:y,shouldQueueOffline:m,socketDown:v}=this.writeQueueGate(i.shardKey),w=!i.onlineOnly&&m&&i.replayBaseline===void 0&&this.hasPendingWriteAhead(i.shardKey),k=a(async(S=!1)=>this.enqueueOfflineMutation(e,n,i.shardKey,h,o,l,d,S?void 0:i.precondition,i.mutationId,u?.stamp,S,c),"b");if(this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i,l),v||y||w)return k();let E;try{let S=await this.rpc(e.__lunoraRef,n,i.shardKey,{baselineSeq:h,captureBookmark:!0,...u?.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=cu(S,n),ie=f&&m&&I,x=this.ownSocketOpen(i.shardKey);if(m&&!i.onlineOnly&&this.fetchImpl!==void 0&&!this.outbox&&i.replayBaseline===void 0&&(S instanceof TypeError||S instanceof j)&&Cs(n)){let F=k(!0);return this.noteHeldRetryDelay(i.shardKey),this.scheduleRateLimitedRetry(i.shardKey),F}throw this.settleFailedDirectWrite(S,E,d,l,u?.flags.authToken),uu(i.onlineOnly,ie,I,x)?li(e.__lunoraRef,S):S}}refuseOnlineOnlyWhenDown(e,s,r=[]){if(!s.onlineOnly)return;let i=this.writeQueueGate(s.shardKey);if(i.socketDown||i.midReconnect)throw ue(r),li(e)}ownSocketOpen(e){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()?!1:this.writeQueueGate(e).socketOpen}writeQueueGate(e){let{hasSocket:s,idleClosed:r,polling:i,wasEverConnected:n,wsState:o}=this.connectionGateState(e),{queueBeforeFirstConnect:c}=this.offlineQueue,u=n||c,h=this.WebSocketImpl!==void 0&&u,d=i||r;return{httpFirst:d,midReconnect:o==="connecting"&&u&&!d,shouldQueueOffline:h,socketDown:o!=="open"&&!s&&h&&!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}ue(i)}async enqueueOfflineMutation(e,s,r,i,n,o,c,u,h,d,l,p){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:h??`${this.clientId}:${String(y)}`,identity:f,mutationId:y,...o.length>0&&{onRejected:a(()=>{ue(o)},"onRejected")},shardKey:r})}catch(m){throw ue(o),m instanceof Error?m:new Error(String(m))}for(let m of c)m(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((y,m)=>{let v={ambiguousSend:l,args:s,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:n,issueSeq:p,clientId:this.clientId,identity:f,precondition:this.holdWhileUnanswered(u),onCommit:a(w=>{for(let k of c)k(w)},"onCommit"),reject:a(w=>{this.queuedIdentities.delete(n),Ne(w)||ue(o),m(w instanceof Error?w:new Error(String(w))),this.releaseIdleShard(r)},"reject"),resolve:y,shardKey:r};this.offlineQueue.enqueue(v),this.queuedOfflineShardKeys.add(r),this.ensureSocket(r),v.id!==void 0&&this.queuedIdentities.set(v.id,f)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;let s=g(e);return this.offlineQueue.hasPending(r=>g(r.shardKey)===s)}async hydratePersistedQueue(){try{let e=await this.offlineQueue.hydrate();for(let s of e)this.queuedOfflineShardKeys.add(s),this.ensureSocket(s)}catch{}}hydrateAsOutboxLeader(){let e=a(()=>{this.hydratePersistedQueue().catch(()=>{})},"e"),s=globalThis.navigator?.locks;if(!s){e();return}s.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(r=>{if(this.closed){r();return}this.outboxLeaderRelease=r}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{let e=await this.queryCache.load(),s=new Map;for(let r of this.subscriptions.all())s.set(he(r.fn.__lunoraRef,r.argsKey,r.shardKey),r);for(let{key:r,...i}of e){if(ps(this.persistenceVersion,i.version)){this.queryCache.remove(r).catch(()=>{});continue}let n=s.get(r);if(n&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(n,i);continue}this.hydratedQueryCache.set(r,i)}}catch{}}seedSubscriptionFromCache(e,s){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(s)||(e.serverBase=s.value,e.serverCursor=s.serverCursor,s.serverEpoch!==void 0&&(e.serverEpoch=s.serverEpoch),this.cacheSeededQueries.set(he(e.fn.__lunoraRef,e.argsKey,e.shardKey),s),ce(e,s.value))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}returnCacheSeed(e){let s=this.cacheSeededQueries.get(e);s!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,s))}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(let[e,s]of this.cacheSeededQueries){let r=this.subscriptions.get(e);r!==void 0&&(r.serverBase=void 0,r.serverCursor=void 0,r.serverEpoch=void 0,ce(r,void 0)),this.hydratedQueryCache.set(e,s)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,s,r){let i=he(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=he(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=he(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,n=i===void 0?this.identityFingerprint():i;n===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(r,{identity:n,serverCursor:e.serverCursor,ts:Date.now(),value:s,...n===this.identityFingerprint()&&!this.subjectAwaitingReconfirm()?this.credentialStamp():{},...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},250))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;let{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}let s=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(s.map(async([r,i])=>e.put(r,i)))}installPageHideFlush(){let e=globalThis;if(!this.persistence&&!this.queryCache||!("document"in globalThis)||typeof e.addEventListener!="function")return;let s=a(()=>{this.offlineQueue.flushUnpersisted(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.flushQueryCacheWrites().catch(()=>{}))},"t"),r=a(()=>{e.document?.visibilityState==="hidden"&&s()},"s");e.addEventListener("pagehide",s),e.document?.addEventListener("visibilitychange",r),this.releasePageHideFlush=()=>{e.removeEventListener?.("pagehide",s),e.document?.removeEventListener("visibilitychange",r)}}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leader.status??"idle";let e=[...this.connections.values()];return e.length===0?"idle":e.some(s=>s.wsState==="open")?"connected":e.some(s=>s.polling.isPolling())?"polling":e.some(s=>s.wsState==="connecting")?"connecting":"offline"}baselineCursorFor(e){let s=g(e),r;for(let i of this.subscriptions.all())g(i.shardKey)!==s||i.serverCursor===void 0||(r=r===void 0?i.serverCursor:Math.max(r,i.serverCursor));return r}composedBaselineFor(e,s){return e===void 0?this.baselineCursorFor(s):e??void 0}async pollSubscriptions(e){let s=g(e),r=[];for(let c of this.subscriptions.all())g(c.shardKey)===s&&(Cs(c.args)?r.push(c):(this.markQueryRejected(c,!0),se(c.errorCallbacks,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"})));if(r.length===0)return this.probeOrigin();let i=Nr(),n=this.identityFingerprint(),o;try{o=await oi(async c=>this.sendBatch(r.map(u=>({args:u.args,fn:u.fn,shardKey:u.shardKey})),c))}catch(c){return!(c instanceof TypeError)}if(this.identityFingerprint()!==n)return!0;for(let[c,u]of r.entries()){let h=o[c];if(h!==void 0){if(!h.ok){this.markQueryRejected(u,!0),se(u.errorCallbacks,{code:h.error.code,message:h.error.message});continue}this.handleDataMessage({data:N(h.value),id:u.id,type:"data"},i)}}return!0}async probeOrigin(){let{fetchImpl:e}=this;if(!e)return!1;try{return await oi(async s=>e(H(this.url,bs),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:s})),!0}catch{return!1}}emitSyncStatus(){if(this.syncStatusListeners.size===0)return;let e=this.syncStatus(),s=this.lastSyncStatus;s?.connection===e.connection&&s.pendingSubscriptions===e.pendingSubscriptions&&s.pendingWrites===e.pendingWrites&&s.synced===e.synced||(this.lastSyncStatus=e,this.syncStatusListeners.emit(e))}emitConnectionStatus(){let e=this.computeStatus();this.emitSyncStatus(),e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,s,r){this.mutationSettledListeners.emit({args:e.args,code:r===void 0?void 0:r.code,error:r,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:s})}applyOptimisticUpdates(e,s,r,i){let n=[],o=[];if(!i)return{confirms:n,rollbacks:o};let c=M.key(e,s,r),u=this.subscriptions.get(c);if(u){let h=yt(u,i);h&&(n.push(h.confirm),o.push(h.rollback))}return{confirms:n,rollbacks:o}}applyOptionalOptimisticUpdate(e,s,r,i,n){e&&this.applyOptimisticUpdate(e,s,r,i,n)}applyOptimisticUpdate(e,s,r,i,n){let{confirms:o,rollbacks:c,store:u}=Jr(this.subscriptions,r);try{e(u,s)}catch{ue(c);return}i.push(...c),n.push(...o)}getConnection(e){return this.connections.get(g(e))}sendOrQueueUnsubscribe(e,s,r){let i=this.getConnection(e);i&&!$(i,{id:s,type:r})&&i.pendingUnsubscribes.push({id:s,type:r})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let i="idle";return this.leader.status==="connected"?i="open":this.leader.status==="connecting"&&(i="connecting"),{hasSocket:!1,idleClosed:!1,polling:this.leader.status==="polling",wasEverConnected:this.leader.wasEverConnected,wsState:i}}let s=this.getConnection(e),r=s===void 0&&this.idleClosedShards.has(g(e));return{hasSocket:s?.socket!==void 0,idleClosed:r,polling:s?.polling.isPolling()??!1,wasEverConnected:s?.wasEverConnected??r,wsState:s?.wsState??"idle"}}getOrCreateConnection(e){let s=g(e),r=this.connections.get(s);return r||(r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:Pc({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:Ke(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=Ke(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},n,o=!1,c=a(()=>{o||this.closed||(n=setTimeout(p,r.next()))},"o"),u=a(m=>{o||this.WebSocketImpl===void 0||ai(i,this.wsUrlFor(s.shardKey,m,e),this.managedSocketOptions,{onClose:a(()=>{c(),s.onClose?.()},"onClose"),onMessage:s.onMessage,...s.onOpen===void 0?{}:{onOpen:s.onOpen},...s.offerBearer===!0?{protocols:this.upgradeProtocols()}:{}})},"c"),h=0,d,l=a(async m=>{let v=this.wsCredentialGeneration;h+=1;let w=h,k;d=v;try{k=await ou(m,au)}catch{w===h&&(d=void 0,c());return}if(w===h){if(d=void 0,v!==this.wsCredentialGeneration){p();return}u(k)}},"h"),p=a(()=>{if(o||this.WebSocketImpl===void 0)return;let{wsTicket:m}=this;if(typeof m=="function"){l(m).catch(()=>{});return}u(m)},"l");p();let f=a(()=>{o=!0,n!==void 0&&(clearTimeout(n),n=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),Oe(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&&(h+=1,d=void 0,p());return}i.socket=void 0,i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),Oe(i);try{m.close()}catch{}s.onClose?.(),c()},"S");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=je(this.wsUrl),r=s.pathname.endsWith(gs)?s.pathname.slice(0,-gs.length):s.pathname;return s.pathname=H(r,e),us(s,this.wsUrl)}wsUrlFor(e,s,r=this.wsUrl){let i=je(r);if(e===void 0&&s===void 0&&!i.searchParams.has("token"))return r;let n=new Set([...e===void 0?[]:["shard"],"token"]),o=[...i.searchParams].filter(([c])=>!n.has(c)).map(([c,u])=>`${encodeURIComponent(c)}=${encodeURIComponent(u)}`);return e!==void 0&&o.push(`shard=${encodeURIComponent(e)}`),s!==void 0&&o.push(`token=${encodeURIComponent(s)}`),i.search=o.join("&"),us(i,r)}rpcRequestHeaders(e,s){let r={"content-type":"application/json"};e.expectSubject!==void 0&&(r[hc]=lc(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 j("LunoraClient: no `fetch` implementation available");let o=this.rpcRequestHeaders(i,r),c=i.authToken===void 0?this.authToken:i.authToken,u=JSON.stringify({args:B(s,`args for '${e}'`),functionPath:e,shardKey:r}),{body:h,response:d}=await de(i.unbounded?0:this.rpcTimeoutMs,i.signal,async f=>{let y=await n(H(this.url,si),{body:u,headers:o,method:"POST",signal:f});try{return{body:await y.json(),response:y}}catch{return{body:void 0,response:y}}});if(i.captureBookmark){let f=d.headers.get("x-d1-bookmark");f&&this.bookmark.set(f)}if(h===void 0)throw We(d.status,d.statusText,d.headers);let l=h;if(typeof l!="object"||l===null||Array.isArray(l))throw We(d.status,d.statusText,d.headers);let p=we(h);if(p!==void 0)throw as(p,d.headers);if(!d.ok)throw We(d.status,d.statusText,d.headers);i.onMutationAck?.(h.lastMutationId),i.onCommitCursor?.(h.commitCursor),this.noteCredentialAccepted(c),this.learnDefaultShardKey(d,r),this.recordShardCursor(r,h.commitCursor);try{return T(h.result)}catch(f){throw K(lt(f),d.headers)}}async adminFetch(e,s,r,i){if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");let n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);let o=r instanceof ArrayBuffer||r instanceof Blob,c;r===void 0?c=void 0:o?(c=r,i!==void 0&&(n["content-type"]=i)):(c=JSON.stringify(r),n["content-type"]="application/json");let u=await this.fetchImpl(H(this.url,e),{body:c,headers:n,method:s}),h;try{h=await u.json()}catch{let l=u.statusText?` ${u.statusText}`:"";throw new b("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${l})`)}let d=we(h);if(d!==void 0)throw Se({...d,message:d.message??"admin request failed"});if(!u.ok){let l=u.statusText?` ${u.statusText}`:"";throw new b("INTERNAL",`LunoraClient: admin request failed (status ${u.status.toString()}${l})`)}return h}effectiveConnectionContext(e){let s=this.connectionContextHolders.get(e);return s&&s.length>0?s[s.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){let s=this.connections.get(e);s?.wsState==="open"&&this.sendConnectEnvelope(s)}sendConnectEnvelope(e){let s=this.effectiveConnectionContext(g(e.shardKey));$(e,{caps:ru,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())g(s.shardKey)===g(e)&&this.sendShapeSubscribeIfOpen(s)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;let s=this.getOrCreateConnection(e);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 de(this.connectTimeoutMs,void 0,async()=>({session:await di(this.wsToken),ticket:await di(this.wsTicket)}),()=>new Error("LunoraClient: ws credential provider timed out"))}catch{e.providerAttempt===i&&(e.providerAttempt=void 0,this.handleDisconnect(e));return}if(e.providerAttempt===i&&(e.providerAttempt=void 0,!(this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0))){if(r!==this.wsCredentialGeneration){await this.startShardSocket(e,s);return}this.openSocket(e,s,n)}}openSocket(e,s,r){if(this.WebSocketImpl===void 0)return;e.providerAttempt=void 0,e.identity=this.identityFingerprint(),r.ticket===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.sessionToken=r.session,e.retired=!1;let i=this.wsCredentialGeneration;ai(e,this.wsUrlFor(s,r.ticket),this.managedSocketOptions,{onClose:a(n=>{n?.code===4003&&e.polling.noteFailedOpen(),n?.code===4001?this.notifyTokenExpired():n?.code===4003&&n.reason!=="connect deadline"&&i===this.wsCredentialGeneration&&this.refusedCredentialGeneration!==i&&(this.refusedCredentialGeneration=i,this.notifyTokenExpired()),this.handleDisconnect(e)},"onClose"),onMessage:a(n=>{e.retired!==!0&&this.handleServerMessage(n.data,s)},"onMessage"),onOpen:a(()=>{e.wsState="open",e.wasEverConnected=!0,e.identityConfirmed=!1,e.connectionId=void 0,e.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())g(c.shardKey)===g(s)&&this.queueResubscribe(c);if(this.resendShapeSubscriptions(s),e.pendingUnsubscribes.length>0){let c=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:u,type:h}of c)$(e,{id:u,type:h});this.releaseIdleShard(s)}Ic(e);let n=g(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),$(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(),Oe(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(g(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(!(g(n.shardKey)!==g(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 b("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.forgetStream(i)}if(this.WebSocketImpl===void 0)return;let r=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},r)}markShardPendingAck(e,s=!1){let r=g(e);for(let i of this.subscriptions.all())g(i.shardKey)===r&&(Y(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())g(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=$(r,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...i?{sinceSeq:e.serverCursor}:{},...i&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"});return n&&Y(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),St(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):St(s)},1e4))}sendShapeSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);s?.wsState==="open"&&$(s,{id:e.id,shape:{name:e.name,...e.wireArgs===void 0?{}:{args:e.wireArgs}},type:"shape_subscribe",...e.serverCursor===void 0?{}:{sinceCheckpoint:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,s){let r=Ac(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,mt(()=>{for(let u of o){if(n.retired===!0||n.socket!==c)break;this.dispatchServerMessage(u,s)}},()=>!this.closed)}}else n?.heldFrames&&iu(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.handleDataMessage(e);return}case"error":{this.handleErrorMessage(e);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.handlePokeEnd(e,s);break}case"pokePart":{this.pokeAssembler.part(s,e);break}case"pokeStart":{this.pokeAssembler.start(s,e);break}case"resume":{this.handleResumeMessage(e);break}case"settled":{this.handleSettledMessage(e);break}case"whisper":{this.dispatchWhisper(e,s);break}case"whisper_subscribed":{this.acknowledgeWhisperJoin(g(s),e.topic);break}}}handleErrorMessage(e){let s=e.error?.code;if(s==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}if(s==="STREAM_ID_IN_USE")return;let{id:r}=e,i=r===void 0?void 0:this.streams.get(r);if(i&&r!==void 0){i.handle.fail(_r(e)),this.forgetStream(r);return}let n=r===void 0?void 0:this.subscriptions.getById(r);if(n){St(n);let c=ns(e),u=this.identityFingerprint(),h=M.keyOf(n);this.markQueryRejected(n),se(n.errorCallbacks,c),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(h,c,u);return}let o=r===void 0?void 0:this.shapeSubscriptions.get(r);o&&(o.answered||(o.answered=!0,this.emitSyncStatus()),se(o.errorCallbacks,ns(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:Y(e,"acked"),this.emitSyncStatus())}handlePokeEnd(e,s){let r=this.pokeAssembler.end(s,e.pokeId);if(r){Wc(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=Hc(e,s,r);if(e.answered!==i&&this.emitSyncStatus(),ui(e),n==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){Y(e,"idle"),e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,this.emitSyncStatus(),console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}handleDataMessage(e,s){let{id:r}=e,i=r?this.subscriptions.getById(r):void 0;if(!i||e.type==="data"&&qc(i,e))return;let n,o=i.pendingDeltaRun;try{n=Lr(e,o===void 0?i.serverBase:o.payload)}catch(u){i.pendingDeltaRun=void 0,se(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription \u2014 ${u instanceof Error?u.message:String(u)}`}),this.settleAwaitedAnswer(i,!1);return}if(n===ts){this.resnapshotSubscription(i);return}if(Bc(e)){i.pendingDeltaRun={payload:n};return}i.pendingDeltaRun=void 0,this.dropCacheSeed(M.keyOf(i));let c=s!==void 0&&!i.valueReceived;if(_n(i,n,{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),bt(i,i.serverCursor),s!==void 0&&Kr(i,s),ce(i,n),this.tabCoordinator?.isLeader()){let u=M.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(u,n,i.serverCursor,i.serverEpoch,this.identityFingerprint())}this.settleAwaitedAnswer(i,!0)}handleResumeMessage(e){let s=this.subscriptions.getById(e.id);s&&(s.pendingDeltaRun=void 0,this.ackAndAdvanceCursor(s,e.cursor,e.epoch),this.tabCoordinator?.isLeader()&&s.serverBase!==void 0&&this.tabCoordinator.broadcastSubscriptionData(M.keyOf(s),s.serverBase,s.serverCursor,s.serverEpoch,this.identityFingerprint()),this.settleAwaitedAnswer(s,!0))}handleSettledMessage(e){let s=this.subscriptions.getById(e.id);if(s&&(this.ackAndAdvanceCursor(s,e.cursor,e.epoch),e.lastMutationId!==void 0&&Os(s,e.lastMutationId),Es(s),this.tabCoordinator?.isLeader())){let r=M.keyOf(s);this.tabCoordinator.broadcastSubscriptionSettled(r,s.serverCursor,s.serverEpoch,s.lastMutationId,this.clientId,this.identityFingerprint())}}ackAndAdvanceCursor(e,s,r){let i=e.ack!=="acked";Y(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),bt(e,e.serverCursor)&&ce(e,e.serverBase))}adoptSocketConnectionId(e,s){let r=this.getConnection(s);if(!(r===void 0||typeof e.connectionId!="string")){r.connectionId=e.connectionId,r.whisperAck=e.whisperAck===!0;for(let i of this.liveSocketGrants.get(g(s))?.keys()??[])this.grantWhenJoined(s,i,e.connectionId)}}grantWhenJoined(e,s,r){let i=g(e),n=this.liveSocketGrants.get(i)?.get(s);if(n===void 0)return;let{stream:o,topic:c}=n,u=a(()=>{this.liveSocketGrants.get(i)?.get(s)===void 0||this.getConnection(e)?.connectionId!==r||this.postLiveControl(`/live/${o}/control`,e,{action:"subscribe",connectionId:r,stream:o,subscriptionId:s,topic:c},h=>{this.refuseLiveGrant(e,s,h,r)})},"c");this.getConnection(e)?.whisperAck===!0?this.whenWhisperJoined(i,c,u):u()}sendWhisperJoin(e,s,r){let i=this.whisperJoinState(s,r);i.pending+=1,i.joined=!1,$(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()},Qn),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=g(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(()=>hi(n,H(this.url,e),o,c)).then(({status:u})=>{u>=400&&u<500&&u!==404&&u!==401&&i?.(u)}).catch(()=>{})}dispatchLive(e,s){let r=this.liveSocketGrants.get(g(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(g(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&&(Y(r,"idle"),this.emitSyncStatus(),se(r.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&(this.replayAttempts.delete(e),this.offlineQueue.discard(e))}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;let e=this.authToken;return e===null?null:(this.tokenFingerprint?.token!==e&&(this.tokenFingerprint={hash:this.hashToken(e),token:e}),this.tokenFingerprint.hash)}hashToken(e){let s=2166136261,r=5381;for(let i=0;i<e.length;i+=1){let n=e.charCodeAt(i);s^=n,s=Math.imul(s,16777619),r=Math.imul(r,33)+n}return`${e.length.toString(36)}:${(s>>>0).toString(36)}:${(r>>>0).toString(36)}`}credentialStamp(){let e=this.authToken;return e===null?{}:{credential:this.hashToken(e)}}cachedQueryMatchesIdentity(e){return this.identityFingerprint()===null&&this.identityUnresolved()?!1:!this.subjectAwaitingReconfirm()&&e.identity===this.identityFingerprint()||this.isSameCredentialUnderTokenHash(e.identity)?!0:e.credential!==void 0&&e.credential===this.credentialStamp().credential}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;let s=this.authToken;return s===null?!1:this.hashToken(s)===e}releaseSessionProbe(){this.sessionProbesInFlight-=1,!(this.identityUnresolved()||this.identityFingerprint()!==null)&&!this.closed&&this.offlineQueue.size>0&&He(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&&$(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(g(e))??[])s()}confirmShardIdentity(e){let s=this.getConnection(e);s!==void 0&&(s.identityConfirmed=!0,s.polling.noteOpen()),this.releaseRoomSends(e)}handleIdentityFrame(e,s){let r=this.getConnection(s)?.identityQuestion,{subject:i}=e;r===void 0||i!==null&&typeof i!="string"||this.adoptCookieSubject(i,r)||!this.closed&&this.authToken===null&&(i===null?null:`subj:${i}`)!==this.identityFingerprint()&&this.evictPreviousIdentitySession()}applySubject(e,s){if(s!==void 0){this.authSubject=s,this.subjectToken=e;return}(e===null&&this.authSubject!==null||e!==null&&this.authSubject===null)&&(this.authSubject=void 0,this.subjectToken=null)}isKnownNobody(){return this.authSubject===null&&this.authToken===null}subjectAwaitingReconfirm(){return this.authSubject!==void 0&&this.authSubject!==null&&this.subjectToken!==this.authToken}stampOf(e){let s=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return s===void 0?e.identity:s}warnRefreshWithoutSubject(e,s){e===null||s===null||this.authSubject!==void 0||this.authRefusalNotifiedFor!==this.hashToken(e)||console.warn("[lunora] setAuthToken replaced a token that was just refused for a queued write, with no subject: without one a refresh reads as a user switch, so the held writes were discarded (OFFLINE_IDENTITY_CHANGED). Pass the user id, e.g. setAuthToken(token, user.id), to keep them across a refresh.")}rejectQueuedForIdentityChange(e){let s=this.offlineQueue.drain(),r=[];for(let i of s){if(this.identityVerdict(this.stampOf(i))!=="mismatch"){r.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);let n=new Error("offline mutation discarded: auth identity changed before replay");n.code="OFFLINE_IDENTITY_CHANGED",i.reject(n),this.emitItemSettled(i,"rejected",n)}this.offlineQueue.requeue(r),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,s){for(let r of this.connections.values())r.identity===e&&(r.identity=s)}restampQueuedIdentity(e,s){for(let[r,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(r,s);this.offlineQueue.restampIdentity(e,s)}restampWatermarks(e,s){let r=e??"",i=this.clientWatermarks.get(r);if(i===void 0)return;this.clientWatermarks.delete(r);let n=s??"",o=this.clientWatermarks.get(n);if(o===void 0)this.clientWatermarks.set(n,i);else for(let[c,u]of i)o.set(c,u)}clearQueryCacheForIdentityChange(){this.revokeCacheSeededValues(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}evictPreviousIdentitySession(){this.resetRoomSends(),this.revokeCacheSeededValues(),this.reconnectCold(),this.retiredIdentities+=1,this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;let e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}resetRoomSends(){for(let e of this.roomIdentityResets)e()}reconnectCold(){for(let e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,Y(e,"idle"),e.valueReceived=!1,ce(e,void 0);for(let e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,e.answered=!1,ui(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?hi(r,H(this.url,i.shardKey===void 0?ni:`${ni}?shard=${encodeURIComponent(i.shardKey)}`),JSON.stringify({connectionId:n}),{authorization:`Bearer ${s}`,"content-type":"application/json"}).then(({text:o})=>JSON.parse(o)?.ok===!0).catch(()=>!1).then(o=>{!o&&!this.closed&&this.authToken===s&&i.connectionId===n&&this.bounceShardSocket(i)}).catch(()=>{}):this.bounceShardSocket(i)}for(let i of this.supplementaryBounces)i()}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=g(e),r=this.offlineFlushes.get(s);if(r===void 0&&this.offlineQueue.size===0)return;let i=(async()=>{await(r??Promise.resolve());let{authToken:n}=this;try{await this.drainOfflineQueue(e,n)}catch{}!this.closed&&this.authToken!==n&&this.offlineQueue.size>0&&He(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=ys(e),r=s&&this.subscriptions.get(M.key(s.functionPath,s.args,s.shardKey));if(r!==void 0)return this.awaitingAnswer.has(r)?"awaiting":this.answeredUnreadable.has(r)?"unreadable":void 0}holdWhileUnanswered(e){let s=ys(e);if(e===void 0||s===void 0)return e;let r=a(()=>this.snapshotAnswer(e)!==void 0||e(),"s");return ms(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(g(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 l=new Error("offline mutation skipped: precondition failed before replay");l.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(d,"rejected",l)}let i=g(e),n=this.holdUndecidedWrites(i,this.offlineQueue.drain(d=>g(d.shardKey)===i));if(n.length===0)return;let o=[],c=[];for(let d of n){let l=this.replayGateVerdict(d);l==="send"?o.push(d):l==="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 u=this.encodableOrSettleTerminal(o);if(u.length===0){this.scheduleRateLimitedRetry(e);return}if(u.length===1){await this.replaySequential(u,e,s),this.scheduleRateLimitedRetry(e);return}let h=[];for(let d=0;d<u.length;d+=vs){let l=u.slice(d,d+vs),p=await this.replayBatched(l,e,s);if(h.push(...p.requeue),p.stop||p.requeue.length>0){h.push(...u.slice(d+vs));break}}h.length>0&&this.offlineQueue.requeue(h),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){let s=g(e),r=this.replayRetryState.get(s),i=(r?.attempts??0)+1;this.replayRetryState.set(s,{attempts:i,delayMs:Math.max(r?.delayMs??0,ks(i))})}noteReplayRetryDelay(e,s,r){let i=g(e),n=this.replayRetryState.get(i),o=(n?.attempts??0)+1,c=Qc(s,o)??(r===null&&De(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=g(e),r=this.replayRetryState.get(s),i=r?.delayMs;if(r===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(s);return}r.delayMs=void 0;let 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{B(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)||ci(e)}noteReplayAuthRefusal(e,s){if(!De(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,...ws(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||De(s)||r==="RATE_LIMITED"||r==="TOO_MANY_REQUESTS"||!ci(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,...ws(n.identity,r),mutationId:n.id,onCommitCursor:a(u=>{o=u},"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((h,d)=>({args:B(h.args,`args for '${h.functionPath}'`),baselineSeq:h.baselineSeq,functionPath:h.functionPath,id:d,clientId:h.clientId??this.clientId,mutationId:h.id,shardKey:h.shardKey}))});if(e.length>1&&Uc(i)>Dc)return await this.replayBatchedHalves(e,s,r);let{fetchImpl:n}=this,o,c;try{({payload:c,response:o}=await de(this.rpcTimeoutMs,void 0,async h=>{let d=await n(H(this.url,bs),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:r,...ws(e.find(l=>l.identity!==void 0)?.identity,r)}),method:"POST",signal:h});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(h){return this.noteReplayRetryDelay(s,h,r),{requeue:this.keepUnexhaustedAmbiguousWrites(e,h),stop:!0}}let u=o.headers.get("x-d1-bookmark");if(u&&this.bookmark.set(u),o.status===413&&e.length>1)return await this.replayBatchedHalves(e,s,r);if(!c)return this.settleWholeBatchError(e,We(o.status,o.statusText,o.headers),s,r);if(!Array.isArray(c.results)){let h=we(c),d=h===void 0?We(o.status,o.statusText,o.headers):as(h,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 j||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=Nc(s),c=[],u=!1,h=!1;for(let[d,l]of e.entries()){let p=jc(o.get(d),n);switch(p.kind){case"committed":{u=!0,this.settleReplaySuccess(l,p.value,p.commitCursor);break}case"errored":{h||=De(p.error),this.shouldRequeueReplayFailure(p.error,i)&&!this.spendsLastReplayAttempt(l,p.error)?(this.noteReplayRetryDelay(r,p.error,i),c.push(l)):this.settleReplayTerminal(l,p.error);break}case"unanswered":{let f=K(is(),n);if(this.spendsLastReplayAttempt(l,f)){this.settleReplayTerminal(l,f);break}this.noteReplayRetryDelay(r,f,i),c.push(l);break}default:u=!0,this.settleReplayUndecodable(l,p.error,p.commitCursor)}}return u&&!h&&this.noteCredentialAccepted(i),c}};var lu=a(async t=>(t.assertOpen(),(await t.adminFetch(yi,"GET")).functions??[]),"Rt"),pu=a(async t=>(t.assertOpen(),(await t.adminFetch(bi,"GET")).jobs??[]),"gt"),fu=a(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(gi,"POST",{name:e});return{name:s.name??e,ran:s.ran===!0}},"Gt"),mu=a(async t=>(t.assertOpen(),await t.adminFetch(wi,"GET")),"Ct"),yu=a(async t=>(t.assertOpen(),await t.adminFetch(vi,"GET")),"Nt"),bu=a(async t=>(t.assertOpen(),await t.adminFetch(Si,"GET")),"Mt"),gu=a(async t=>(t.assertOpen(),await t.adminFetch(Ci,"GET")),"kt"),vu=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(`${ki}?${s.toString()}`,"GET"))},"vt"),wu=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(`${Ti}?${s.toString()}`,"GET"))},"Lt"),Su=a(async t=>(t.assertOpen(),(await t.adminFetch(Ri,"GET")).namespaces??[]),"Vt"),Cu=a(async(t,e)=>{t.assertOpen();let s=L(Ai,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await t.adminFetch(s,"GET")},"Kt"),ku=a(async(t,e)=>{t.assertOpen();let s=L(At,{key:e.key,namespace:e.namespace});return await t.adminFetch(s,"GET")},"Bt"),Tu=a(async(t,e)=>{t.assertOpen(),await t.adminFetch(At,"PUT",e)},"Dt"),Ou=a(async(t,e)=>{t.assertOpen();let s=L(At,{key:e.key,namespace:e.namespace});await t.adminFetch(s,"DELETE")},"Jt"),Eu=a(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(pi,"POST",{table:e});return{failed:s.failed??0,ok:s.ok??0,shards:s.shards??[]}},"xt"),Iu=a(async(t,e={})=>{t.assertOpen();let s=await t.adminFetch(Ii,"POST",e);return{nextCursor:s.nextCursor,rows:s.rows??[]}},"$t"),Ru=a(async(t,e={})=>{t.assertOpen();let s=L(Rt,{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??[]}},"zt"),Au=a(async(t,e,s)=>{t.assertOpen();let r=`${Rt}?key=${encodeURIComponent(e)}${ft(s?.bucket)}`,i=await t.adminFetch(r,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}},"jt"),Fu=a(async t=>(t.assertOpen(),(await t.adminFetch(mi,"GET")).buckets??[]),"Wt"),Pu=a(async(t,e)=>{t.assertOpen();let s=`${Rt}?key=${encodeURIComponent(e.key)}${ft(e.bucket)}`,r=await t.adminFetch(s,"PUT",e.body,e.contentType);return{etag:r.etag,key:r.key??e.key}},"qt"),Lu=a(async(t,e,s)=>{t.assertOpen();let r=s?.expiresInSeconds,i=r===void 0?"":`&expiresIn=${encodeURIComponent(r.toString())}`,n=`${fi}?key=${encodeURIComponent(e)}${i}${ft(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},"Qt"),Mu=a(async t=>(t.assertOpen(),(await t.adminFetch(Oi,"GET")).indexes??[]),"Yt"),xu=a(async(t,e)=>(t.assertOpen(),(await t.adminFetch(Ei,"POST",e)).matches??[]),"Xt"),Rs=class extends It{static{a(this,"sa")}async shardTraffic(e){return Eu(this.adminHost,e)}async listScheduledJobs(){return kn(this.adminHost)}async schedulerStatus(){return Tn(this.adminHost)}async cancelScheduledJob(e){return On(this.adminHost,e)}async listDeadJobs(){return En(this.adminHost)}async retryDeadJob(e){return In(this.adminHost,e)}async removeDeadJob(e){return Rn(this.adminHost,e)}async listWorkflowInstances(e){return An(this.adminHost,e)}async getWorkflowInstance(e){return Fn(this.adminHost,e)}async setWorkflowInstanceStatus(e){return Pn(this.adminHost,e)}async listFunctions(){return lu(this.adminHost)}async getCronJobs(){return pu(this.adminHost)}async runCronJob(e){return fu(this.adminHost,e)}async fetchOpenApi(){return mu(this.adminHost)}async fetchArchitecture(){return yu(this.adminHost)}async fetchOpenRpc(){return bu(this.adminHost)}async listStorageObjects(e={}){return Ru(this.adminHost,e)}async deleteStorageObject(e,s){return Au(this.adminHost,e,s)}async listStorageBuckets(){return Fu(this.adminHost)}async uploadStorageObject(e){return Pu(this.adminHost,e)}async signedStorageUrl(e,s){return Lu(this.adminHost,e,s)}async listGlobalTables(){return gu(this.adminHost)}async readGlobalTablePage(e){return vu(this.adminHost,e)}async facetGlobalColumn(e){return wu(this.adminHost,e)}async listVectorIndexes(){return Mu(this.adminHost)}async queryVectorIndex(e){return xu(this.adminHost,e)}async queryLogArchive(e={}){return Iu(this.adminHost,e)}async listKvNamespaces(){return Su(this.adminHost)}async listKvKeys(e){return Cu(this.adminHost,e)}async getKvValue(e){return ku(this.adminHost,e)}async putKvValue(e){return Tu(this.adminHost,e)}async deleteKvKey(e){return Ou(this.adminHost,e)}async listAuthUsers(e={}){this.adminHost.assertOpen();let s=L(Fi,{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(Li,"POST",e)}async setAuthUserRole(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Mi,"POST",e)}async banAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(xi,"POST",e)}async unbanAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(_i,"POST",e)}async setAuthUserPassword(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Qi,"POST",e)}async removeAuthUser(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Di,"POST",e)}async impersonateAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ui,"POST",e)}async revokeAuthSession(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ni,"POST",e)}async revokeAuthUserSessions(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(ji,"POST",e)}async getAuthCapabilities(){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ki,"GET")}async updateAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Hi,"POST",e)}async listAuthAccounts(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(L(Wi,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(qi,"POST",e)}async listAuthPasskeys(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(L(Bi,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch($i,"POST",e)}async disableAuthTwoFactor(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(zi,"POST",e)}async listAuthOrganizations(e={}){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(L(Gi,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.adminHost.assertOpen();let s=L(Ji,{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(Vi,{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(en,{limit:e.limit,offset:e.offset});return await this.adminHost.adminFetch(s,"GET")}async createAuthSignUpInvitation(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(tn,"POST",e)}async revokeAuthSignUpInvitation(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(sn,"POST",e)}async removeAuthOrgMember(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Yi,"POST",e)}async cancelAuthOrgInvitation(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Xi,"POST",e)}async getAuthConfig(){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Zi,"GET")}async createAuthOrganization(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(rn,"POST",e)}async updateAuthOrganization(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(nn,"POST",e)}async deleteAuthOrganization(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(an,"POST",e)}async addAuthOrgMember(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(on,"POST",e)}async inviteAuthOrgMember(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(cn,"POST",e)}async setAuthOrgMemberRole(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(un,"POST",e)}async listAuthOrgTeams(e){this.adminHost.assertOpen();let s=L(dn,{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(ln,"POST",e)}async removeAuthOrgTeam(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(pn,"POST",e)}async listAuthOrgTeamMembers(e){this.adminHost.assertOpen();let s=L(fn,{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(mn,"POST",e)}async removeAuthOrgTeamMember(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(yn,"POST",e)}async listAuthOrgRoles(e){this.adminHost.assertOpen();let s=L(bn,{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(gn,"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(wn,"POST",e)}async listAuthSessions(e={}){this.adminHost.assertOpen();let s=L(Pi,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminHost.adminFetch(s,"GET")}},As=a(t=>"listAuthUsers"in t,"ea");var jn=U(Us(),1);var D=U(ne(),1);var Pt=U(Lt(),1);var Fs=a(t=>zt(t),"b");var Dn=a(t=>{t!==void 0&&(t.cancel({silent:!0}),t.setState({...t.state,data:void 0,dataUpdatedAt:0,error:null,fetchStatus:"idle",status:"pending"}))},"E"),Ps={status:"idle"},Un=a((t,e)=>{for(let s of t.waiters)s(e);t.waiters.clear()},"F"),_u=1e4,Qu=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(h),e.removeEventListener("abort",u)},"l"),u=a(()=>{c(),i(e.reason)},"t"),h=a(d=>{c(),r(d)},"n");n=setTimeout(()=>{h(!1)},_u),t.waiters.add(h),e.addEventListener("abort",u,{once:!0}),o=s(()=>{h(!1)}),t.waiters.has(h)||o()}),"U"),Ms=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(Fs(e))}async liveValue(e,s,r,i){let{fetch:n,shardKey:o,waitForPush:c=!0}=i;if(!("window"in globalThis)||this.client.getWebSocketImpl()===void 0)return n();let u=Fs(s),h=this.liveFor(u),d=h.state.status==="pushed"?e.getQueryData(s)??h.state.value:void 0;if(d!==void 0)return d;if(c&&h.state.status!=="errored"&&!this.client.isCrossTabFollower()&&this.client.expectsPush({shardKey:o})){let f;try{f=await Qu(h,r,y=>this.client.onConnectionStatus(()=>{this.client.expectsPush({shardKey:o})||y()}))}finally{this.forgetIdleLive(u)}if(f)return this.liveValue(e,s,r,i)}let l=h.state,p;try{p=await n()}finally{this.forgetIdleLive(u)}if(h.state!==l&&h.state.status==="pushed"){let f=e.getQueryData(s);return f!==void 0?f:h.state.value}return p}clearOnIdentityChange(e){this.listenForIdentityChange(),this.identityWatched.add(e)}stopClearingOnIdentityChange(e){this.identityWatched.delete(e)}subscribeIdentityEpoch=a(e=>(this.listenForIdentityChange(),this.client.onIdentityChange(e)),"subscribeIdentityEpoch");listenForIdentityChange(){this.listening||(this.listening=!0,this.client.onIdentityChange(()=>{for(let e of this.identityWatched)this.clearQueries(e)}))}clearQueries(e){let s=e.getQueryCache();for(let r of s.findAll({queryKey:["lunora"]}))Dn(r),r.getObserversCount()===0&&!this.hasConsumers(r.queryKey)&&s.remove(r)}attach(e,s,r,i,n,o={}){let c=Fs(s),u=this.entries.get(c);if(!u){u={clients:new Map([[e,0]]),errorCallbacks:new Set,unsubscribe:void 0},this.entries.set(c,u);let p=u;try{u.unsubscribe=this.client.subscribe(r,i,f=>{let y=this.liveFor(c);if(f===void 0){y.state=Ps;for(let m of p.clients.keys())Dn(m.getQueryCache().find({exact:!0,queryKey:s}));return}for(let m of p.clients.keys())m.setQueryData(s,f);y.state={status:"pushed",value:f},Un(y,!0)},{onError:a(f=>{let y=this.liveFor(c);y.state.status!=="pushed"&&(y.state={status:"errored"},Un(y,!1));for(let m of p.errorCallbacks)m(f)},"onError"),shardKey:n})}catch(f){throw this.entries.delete(c),this.dropLive(c),f}}u.clients.set(e,(u.clients.get(e)??0)+1);let h=this.live.get(c);h?.state.status==="pushed"&&e.setQueryData(s,h.state.value);let{onError:d}=o;d&&u.errorCallbacks.add(d);let l=!1;return()=>{if(l)return;l=!0;let p=this.entries.get(c);if(!p)return;let f=(p.clients.get(e)??1)-1;f>0?p.clients.set(e,f):p.clients.delete(e),d&&p.errorCallbacks.delete(d),p.clients.size===0&&(p.unsubscribe?.(),this.entries.delete(c),this.dropLive(c))}}liveFor(e){let s=this.live.get(e);return s||(s={state:Ps,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=Ps)}},Nn=new WeakMap,Ls=a(t=>{let e=Nn.get(t);return e||(e=new Ms(t),Nn.set(t,e)),e},"L"),Kn=(0,D.createContext)(null),Du=(0,D.createContext)(!1),Uu=a(()=>new qt({defaultOptions:{mutations:{retry:0},queries:{gcTime:5*6e4,retry:0,staleTime:Number.POSITIVE_INFINITY}}}),"B"),Nu=a(t=>{let e=(0,jn.c)(20),{children:s,client:r,queryClient:i}=t,n=(0,D.use)(Ee),o;e[0]!==n||e[1]!==i?(o=a(()=>i??n??Uu(),"h"),e[0]=n,e[1]=i,e[2]=o):o=e[2];let[c]=(0,D.useState)(o),u=i??n??c,h,d;e[3]!==r||e[4]!==u?(h=a(()=>{Ls(r).clearOnIdentityChange(u)},"n"),d=[r,u],e[3]=r,e[4]=u,e[5]=h,e[6]=d):(h=e[5],d=e[6]),(0,D.useEffect)(h,d);let l=(0,D.useRef)(r),p,f;e[7]!==r||e[8]!==u?(p=a(()=>{l.current!==r&&(Ls(l.current).stopClearingOnIdentityChange(u),l.current=r,Ls(r).clearQueries(u),u.invalidateQueries({queryKey:["lunora"]}))},"a"),f=[r,u],e[7]=r,e[8]=u,e[9]=p,e[10]=f):(p=e[9],f=e[10]),(0,D.useEffect)(p,f);let[y]=(0,D.useState)(r),m=r!==y,v;e[11]!==s||e[12]!==m?(v=(0,Pt.jsx)(Du,{value:m,children:s}),e[11]=s,e[12]=m,e[13]=v):v=e[13];let w;e[14]!==r||e[15]!==v?(w=(0,Pt.jsx)(Kn,{value:r,children:v}),e[14]=r,e[15]=v,e[16]=w):w=e[16];let k=w;if(n===u)return k;let E;return e[17]!==k||e[18]!==u?(E=(0,Pt.jsx)(Mt,{client:u,children:k}),e[17]=k,e[18]=u,e[19]=E):E=e[19],E},"X");var qe=a(()=>{let t=(0,D.use)(Kn);if(!t)throw new b("INTERNAL","useLunora must be used inside <LunoraProvider />");return t},"q");var Hn=U(Us(),1),Wn=U(ne(),1);var ju=a(()=>{let t=(0,Hn.c)(4),e=qe(),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,Wn.useSyncExternalStore)(s,r,i)},"S");var ym=a(()=>{let t=qe();if(!As(t))throw new b("INTERNAL","The Studio needs a LunoraAdminClient (`@lunora/client/admin`), not a plain LunoraClient.");return t},"a");export{Rs as a,Gn as b,Ie as c,ia as d,na as e,Me as f,st as g,ge as h,xe as i,Ra as j,Nu as k,ju as l,ym as m};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as j,c as v,d as D,m as q}from"./chunk-FACXM2UB.js";import{h as g,i as S,j as P,s as w}from"./chunk-GNI37YCV.js";import{a as M}from"./chunk-GWNGVKLG.js";import{a as L}from"./chunk-6G3E4PJ2.js";import{a as i,d as A}from"./chunk-5PEAXTYQ.js";var E=A(M(),1);var p=A(L(),1);var I=300,l=i(t=>typeof t=="string"?t===""?void 0:t:typeof t=="number"||typeof t=="boolean"?String(t):void 0,"c"),u=i(t=>t.filter(r=>r!==void 0).join(" "),"u"),T=i(t=>{let r=Array.isArray(t.filters)?t.filters.length:0,e=typeof t.search=="string"&&t.search!=="";return r===0&&!e?"no predicate":u([r===0?void 0:`${String(r)} filters`,e?"search":void 0])},"q"),N={clearTable:i(t=>u([l(t.table),"whole table"]),"clearTable"),deleteRows:i(t=>u([l(t.table),T(t)]),"deleteRows"),facetColumn:i(t=>u([l(t.table),l(t.column)]),"facetColumn"),importShard:i(t=>{if(!Array.isArray(t.rows))return"";let r=[...new Set(t.rows.filter(e=>typeof e=="object"&&e!==null).map(e=>e.table).filter(e=>typeof e=="string"))].toSorted((e,s)=>e.localeCompare(s));return u([`${String(t.rows.length)} rows`,r.length===0?void 0:`into ${r.join(", ")}`])},"importShard"),lintSql:i(()=>"sql","lintSql"),patchRows:i(t=>u([l(t.table),typeof t.doc=="object"&&t.doc!==null?`set ${Object.keys(t.doc).join(", ")}`:void 0,T(t)]),"patchRows"),pitrRestore:i(t=>u([l(t.time)===void 0?void 0:`to ${String(t.time)}`,typeof t.bookmark=="string"&&t.bookmark!==""?"from bookmark":void 0,t.restart===!0?"restart now":void 0]),"pitrRestore"),readTablePage:i(t=>u([l(t.table),Array.isArray(t.filters)&&t.filters.length>0?`${String(t.filters.length)} filters`:void 0,typeof t.search=="string"&&t.search!==""?"search":void 0,typeof t.limit=="number"?`limit ${String(t.limit)}`:void 0]),"readTablePage"),runMigration:i(t=>u([l(t.id),l(t.direction),t.dryRun===!0?"dry-run":void 0]),"runMigration"),runSql:i(t=>typeof t.sql=="string"?`${String(t.sql.length)} chars`:"","runSql"),schemaVersion:i(t=>typeof t.hash=="string"?t.hash.slice(0,8):"","schemaVersion"),writeRow:i(t=>u([l(t.table),"1 row"]),"writeRow")},$="__lunora_admin__:",F=i((t,r)=>{let e=t.startsWith($)?t.slice($.length):t,s=N[e];if(s!==void 0)return s(r);let n=Object.keys(r);return n.length===0?"":n.join(", ")},"M"),V=i(t=>{if(Array.isArray(t))return t.length;if(!(typeof t!="object"||t===null)){for(let r of Object.values(t))if(Array.isArray(r))return r.length}},"K"),k=class{static{i(this,"x")}entries=[];listeners=new Set;nextSeq=1;getSnapshot=i(()=>this.entries,"getSnapshot");subscribe=i(r=>(this.listeners.add(r),()=>{this.listeners.delete(r)}),"subscribe");start(r,e,s){return this.append(r,e,s,"call","pending")}startSubscription(r,e,s){return this.append(r,e,s,"subscription","live")}recordPush(r){if(this.listeners.size===0){let e=this.entries.find(s=>s.seq===r);e!==void 0&&(e.pushes=(e.pushes??0)+1);return}this.patch(r,e=>({...e,pushes:(e.pushes??0)+1}))}failSubscription(r,e){this.patch(r,s=>({...s,error:e,status:"error"}))}endSubscription(r){this.patch(r,e=>e.status==="error"?e:{...e,durationMs:Date.now()-e.startedAt,status:"closed"})}lastErrorSeq(){return this.entries.findLast(r=>r.status==="error")?.seq}settle(r,e){this.patch(r,s=>({...s,durationMs:Date.now()-s.startedAt,...e.error===void 0?{resultCount:V(e.result),status:"ok"}:{error:e.error,status:"error"}}))}clear(){this.entries=[],this.emit()}append(r,e,s,n,a){let c=this.nextSeq;this.nextSeq+=1;let d={functionPath:r,kind:n,seq:c,shardKey:s,startedAt:Date.now(),status:a,summary:F(r,e),...n==="subscription"?{pushes:0}:{}},o=[...this.entries,d];return this.entries=o.length>I?o.slice(o.length-I):o,this.emit(),c}patch(r,e){let s=this.entries.findIndex(n=>n.seq===r);s!==-1&&(this.entries=this.entries.with(s,e(this.entries[s])),this.emit())}emit(){for(let r of this.listeners)r()}},f=new k,O=i((t,r,e)=>["lunora-admin",t,r,e.trim()],"E"),_=i((t,r)=>[...t,r],"j");function W(t,r,e={}){let s=q(),{enabled:n=!0,keepPreviousData:a=!1,staleTime:c=0}=e,d=_(t,s.clientIdentifier()),o=D({enabled:n,queryFn:r,placeholderData:a?j:void 0,queryKey:d,staleTime:c});return{data:o.data,error:o.error?P(o.error):o.error,errorSource:o.error??void 0,isLoading:o.isLoading,liveError:void 0,refetch:i(()=>{w(o.refetch())},"refetch"),poll:i(async()=>{await o.refetch({throwOnError:!0})},"poll")}}i(W,"F");function Y(t,r,e={}){let s=q(),n=v(),{enabled:a=!0,keepPreviousData:c=!1,live:d=!1,shardKey:o="",staleTime:R}=e,m=O(t,r,o),C=W(m,()=>s.query(g(t),r,S(o)),{enabled:a,keepPreviousData:c,staleTime:R??(d?Number.POSITIVE_INFINITY:0)}),[K,b]=(0,p.useState)(void 0),Q=JSON.stringify(m);return(0,p.useEffect)(()=>{if(!a||!d)return;b(void 0);let y=f.startSubscription(t,r,o),x=s.subscribe(g(t),r,h=>{f.recordPush(y),b(void 0),n.setQueryData(_(m,s.clientIdentifier()),h)},{...S(o),onError:i(h=>{f.failSubscription(y,h.message),b(h.message)},"onError")});return()=>{f.endSubscription(y),x()}},[s,Q,a,d]),{...C,liveError:a&&d?K:void 0}}i(Y,"U");var B=i(()=>{let t=(0,E.c)(2),r=v(),e;return t[0]!==r?(e=i((s,n,a)=>{let c=n===void 0?["lunora-admin",s]:O(s,n,a??"");w(r.invalidateQueries({queryKey:c}))},"r"),t[0]=r,t[1]=e):e=t[1],e},"W");export{f as a,W as b,Y as c,B as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as k}from"./chunk-3D67ZJRW.js";import{i as j}from"./chunk-IHGRWY3Y.js";import{B as b}from"./chunk-GNI37YCV.js";import{a as $}from"./chunk-GWNGVKLG.js";import{a as w,b as A}from"./chunk-6G3E4PJ2.js";import{a as m,d as S}from"./chunk-5PEAXTYQ.js";var y=S($(),1),h=S(w(),1);var a=S(A(),1);var z=m(i=>{let t=(0,y.c)(21),{id:f,onChange:g,testId:e,value:v}=i,s=b(),u=(0,h.useId)(),[d]=(0,h.useState)(F),c;t[0]!==g?(c=m(C=>{g(C.target.value)},"d"),t[0]=g,t[1]=c):c=t[1];let I=c,o;t[2]!==s?(o=s("Shard key"),t[2]=s,t[3]=o):o=t[3];let x=d.length>0?u:void 0,r;t[4]!==s?(r=s("shard key (optional)"),t[4]=s,t[5]=r):r=t[5];let l;t[6]!==f||t[7]!==I||t[8]!==o||t[9]!==x||t[10]!==r||t[11]!==e||t[12]!==v?(l=(0,a.jsx)(j,{"aria-label":o,className:"h-8 w-48","data-testid":e,id:f,list:x,onChange:I,placeholder:r,value:v}),t[6]=f,t[7]=I,t[8]=o,t[9]=x,t[10]=r,t[11]=e,t[12]=v,t[13]=l):l=t[13];let n;t[14]!==u||t[15]!==d||t[16]!==e?(n=d.length>0&&(0,a.jsx)("datalist",{"data-testid":`${e}-recents`,id:u,children:d.map(N)}),t[14]=u,t[15]=d,t[16]=e,t[17]=n):n=t[17];let p;return t[18]!==l||t[19]!==n?(p=(0,a.jsxs)(a.Fragment,{children:[l,n]}),t[18]=l,t[19]=n,t[20]=p):p=t[20],p},"A");function F(){return k()}m(F,"$");function N(i){return(0,a.jsx)("option",{"aria-label":i,value:i},i)}m(N,"w");export{z as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as ee}from"./chunk-QKUVJIRX.js";import{a as ne}from"./chunk-RCXNYW7P.js";import{b as Z}from"./chunk-UQA2AJGI.js";import"./chunk-T3ZCW3RG.js";import{a as O}from"./chunk-OK2QU2EV.js";import{d as se,m as X}from"./chunk-FACXM2UB.js";import"./chunk-ZPQBVYNN.js";import{B as re,w as le,x as Y}from"./chunk-GNI37YCV.js";import"./chunk-PDBW6GTJ.js";import{a as ce}from"./chunk-GWNGVKLG.js";import{b as me}from"./chunk-6G3E4PJ2.js";import{a as k,d as ae}from"./chunk-5PEAXTYQ.js";var te=ae(ce(),1);var a=ae(me(),1);var pe="/_lunora/health",he="/_lunora/health/ready",ue=k((r,e)=>(r.endsWith("/")?r.slice(0,-1):r)+e,"me"),fe=k(()=>{let r=X();return async e=>{let w=e==="ready"?he:pe,t=r.getAuthToken(),y=ue(r.url,w);try{let i=await fetch(y,{headers:t===null?{}:{authorization:`Bearer ${t}`}}),p=null;try{p=await i.json()}catch{p=null}return{body:p,ok:i.ok,status:i.status}}catch(i){return{body:null,error:i instanceof Error?i.message:String(i),ok:!1,status:0}}}},"pe"),ge={crit:"bg-destructive",ok:"bg-success",warn:"bg-warning"},ye=k(r=>r==="unhealthy"?"crit":r==="degraded"?"warn":"ok","fe"),ie=k(r=>{let e=(0,te.c)(13),{label:w,level:t,testId:y,value:i}=r,p=ge[t],d;e[0]!==p?(d=Y("size-1.5 shrink-0 rounded-full",p),e[0]=p,e[1]=d):d=e[1];let o;e[2]!==d?(o=(0,a.jsx)("span",{"aria-hidden":"true",className:d}),e[2]=d,e[3]=o):o=e[3];let c;e[4]!==w||e[5]!==o?(c=(0,a.jsxs)("span",{className:"flex items-center gap-1.5 font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:[o,w]}),e[4]=w,e[5]=o,e[6]=c):c=e[6];let h;e[7]!==y||e[8]!==i?(h=(0,a.jsx)("span",{className:"text-lg font-semibold text-foreground","data-testid":y,children:i}),e[7]=y,e[8]=i,e[9]=h):h=e[9];let C;return e[10]!==c||e[11]!==h?(C=(0,a.jsx)(O,{className:"gap-0 py-0",children:(0,a.jsxs)("div",{className:"flex flex-col gap-2.5 p-4",children:[c,h]})}),e[10]=c,e[11]=h,e[12]=C):C=e[12],C},"Z"),Ie=k(r=>{let e=(0,te.c)(107),{probe:w}=r,t=re(),y=X(),i=fe(),p=w??i,d;e[0]!==p?(d=k(async()=>{let[s,n]=await Promise.all([p("live"),p("ready")]);return{live:s,ready:n}},"o"),e[0]=p,e[1]=d):d=e[1];let o;e[2]!==y?(o=y.clientIdentifier(),e[2]=y,e[3]=o):o=e[3];let c;e[4]!==o?(c=["deployment-health",o],e[4]=o,e[5]=c):c=e[5];let h;e[6]!==d||e[7]!==c?(h={queryFn:d,queryKey:c},e[6]=d,e[7]=c,e[8]=h):h=e[8];let{data:C,isPending:de}=se(h),Q=C?.live??null,oe=C?.ready??null;if(de){let s;return e[9]===Symbol.for("react.memo_cache_sentinel")?(s=(0,a.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"deployment-health-loading",children:[(0,a.jsx)(ee,{className:"h-16 w-full"}),(0,a.jsx)(ee,{className:"h-40 w-full"})]}),e[9]=s):s=e[9],s}let l=Q?.body??null;if(l===null){let s=Q?.status===403,n;e[10]!==s||e[11]!==Q?.error||e[12]!==t?(n=s?t("The health endpoint is in the admin posture. Paste a valid admin token in the connect popover, or set its auth to public."):t("Couldn't reach the health endpoint: {message}",{message:Q?.error??t("no response")}),e[10]=s,e[11]=Q?.error,e[12]=t,e[13]=n):n=e[13];let m;e[14]!==t?(m=t("Health endpoint unavailable"),e[14]=t,e[15]=m):m=e[15];let f;return e[16]!==n||e[17]!==m?(f=(0,a.jsx)(ne,{description:n,testId:"deployment-health-error",title:m}),e[16]=n,e[17]=m,e[18]=f):f=e[18],f}let J;e[19]!==l.status?(J=ye(l.status),e[19]=l.status,e[20]=J):J=e[20];let W=J,u;if(l.status==="unhealthy"){let s;e[21]!==t?(s=t("Unhealthy"),e[21]=t,e[22]=s):s=e[22],u=s}else if(l.status==="degraded"){let s;e[23]!==t?(s=t("Degraded"),e[23]=t,e[24]=s):s=e[24],u=s}else{let s;e[25]!==t?(s=t("Healthy"),e[25]=t,e[26]=s):s=e[26],u=s}let _=oe?.ok??!1,G=_?"ok":"crit",j,H,I,x,N,v,S,V,b,P;if(e[27]!==l.appName||e[28]!==l.appVersion||e[29]!==l.checks||e[30]!==l.timestamp||e[31]!==W||e[32]!==G||e[33]!==_||e[34]!==u||e[35]!==t){let s=[...l.checks].toSorted(xe);H="flex flex-col gap-6",I="deployment-health";let n;e[46]!==t?(n=t("Live liveness, readiness, and per-binding health from the deployment's /_lunora/health endpoint \u2014 wire an uptime monitor or a Cloudflare Health Check at it."),e[46]=t,e[47]=n):n=e[47],e[48]!==n?(x=(0,a.jsx)("p",{className:"text-sm text-muted-foreground",children:n}),e[48]=n,e[49]=x):x=e[49];let m;e[50]!==u?(m=(0,a.jsx)("span",{className:"text-sm font-semibold text-foreground","data-testid":"dh-status",children:u}),e[50]=u,e[51]=m):m=e[51];let f;e[52]!==l.appName||e[53]!==l.appVersion?(f=(0,a.jsxs)("span",{className:"font-mono text-[13px] text-muted-foreground","data-testid":"dh-app",children:[l.appName," \xB7 ",l.appVersion]}),e[52]=l.appName,e[53]=l.appVersion,e[54]=f):f=e[54];let D;e[55]!==m||e[56]!==f?(D=(0,a.jsx)("div",{className:"flex items-center gap-3",children:(0,a.jsxs)("div",{className:"grid leading-tight",children:[m,f]})}),e[55]=m,e[56]=f,e[57]=D):D=e[57];let T;e[58]!==t?(T=t("Checked"),e[58]=t,e[59]=T):T=e[59];let $;e[60]!==T?($=(0,a.jsx)("div",{className:"font-mono text-[10px] tracking-wide text-muted-foreground uppercase",children:T}),e[60]=T,e[61]=$):$=e[61];let q;e[62]!==l.timestamp?(q=le(l.timestamp),e[62]=l.timestamp,e[63]=q):q=e[63];let B;e[64]!==q?(B=(0,a.jsx)("time",{className:"text-[13px] text-muted-foreground","data-testid":"dh-timestamp",children:q}),e[64]=q,e[65]=B):B=e[65];let E;e[66]!==$||e[67]!==B?(E=(0,a.jsxs)("div",{className:"text-end",children:[$,B]}),e[66]=$,e[67]=B,e[68]=E):E=e[68],e[69]!==D||e[70]!==E?(N=(0,a.jsx)(O,{className:"gap-0 py-0",children:(0,a.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-4 p-4",children:[D,E]})}),e[69]=D,e[70]=E,e[71]=N):N=e[71];let L;e[72]!==t?(L=t("Liveness"),e[72]=t,e[73]=L):L=e[73];let R;e[74]!==W||e[75]!==u||e[76]!==L?(R=(0,a.jsx)(ie,{label:L,level:W,testId:"dh-liveness",value:u}),e[74]=W,e[75]=u,e[76]=L,e[77]=R):R=e[77];let U;e[78]!==t?(U=t("Readiness"),e[78]=t,e[79]=U):U=e[79];let A;e[80]!==_||e[81]!==t?(A=t(_?"Ready":"Not ready"),e[80]=_,e[81]=t,e[82]=A):A=e[82];let F;e[83]!==G||e[84]!==U||e[85]!==A?(F=(0,a.jsx)(ie,{label:U,level:G,testId:"dh-readiness",value:A}),e[83]=G,e[84]=U,e[85]=A,e[86]=F):F=e[86],e[87]!==R||e[88]!==F?(v=(0,a.jsxs)("div",{className:"grid gap-3 sm:grid-cols-2","data-testid":"dh-probes",children:[R,F]}),e[87]=R,e[88]=F,e[89]=v):v=e[89],j=O,S="gap-0 py-0",V="dh-checks";let K;e[90]!==t?(K=t("Subsystem checks"),e[90]=t,e[91]=K):K=e[91],e[92]!==K?(b=(0,a.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,a.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:K})}),e[92]=K,e[93]=b):b=e[93],P=s.length===0?(0,a.jsx)("p",{className:"px-4 py-8 text-center text-sm text-muted-foreground","data-testid":"dh-checks-empty",children:t("No checks reported.")}):(0,a.jsx)("ul",{className:"divide-y divide-border",children:s.map(g=>(0,a.jsxs)("li",{className:"flex flex-wrap items-center justify-between gap-2 px-4 py-2.5 text-xs","data-testid":`dh-check-${g.name}`,children:[(0,a.jsxs)("span",{className:"flex items-center gap-2",children:[(0,a.jsx)("span",{"aria-hidden":"true",className:Y("size-1.5 shrink-0 rounded-full",g.status==="up"?"bg-success":"bg-destructive")}),(0,a.jsx)("span",{className:"font-mono text-foreground",children:g.name}),g.critical&&(0,a.jsx)(Z,{variant:"outline",children:t("Critical")})]}),(0,a.jsxs)("span",{className:"flex shrink-0 items-center gap-2",children:[g.message!==void 0&&(0,a.jsx)("span",{className:"text-muted-foreground",children:g.message}),(0,a.jsx)(Z,{"data-testid":`dh-check-status-${g.name}`,variant:g.status==="up"?"secondary":"destructive",children:g.status==="up"?t("Up"):t("Down")})]})]},g.name))}),e[27]=l.appName,e[28]=l.appVersion,e[29]=l.checks,e[30]=l.timestamp,e[31]=W,e[32]=G,e[33]=_,e[34]=u,e[35]=t,e[36]=j,e[37]=H,e[38]=I,e[39]=x,e[40]=N,e[41]=v,e[42]=S,e[43]=V,e[44]=b,e[45]=P}else j=e[36],H=e[37],I=e[38],x=e[39],N=e[40],v=e[41],S=e[42],V=e[43],b=e[44],P=e[45];let z;e[94]!==j||e[95]!==S||e[96]!==V||e[97]!==b||e[98]!==P?(z=(0,a.jsxs)(j,{className:S,"data-testid":V,children:[b,P]}),e[94]=j,e[95]=S,e[96]=V,e[97]=b,e[98]=P,e[99]=z):z=e[99];let M;return e[100]!==H||e[101]!==I||e[102]!==x||e[103]!==N||e[104]!==v||e[105]!==z?(M=(0,a.jsxs)("div",{className:H,"data-testid":I,children:[x,N,v,z]}),e[100]=H,e[101]=I,e[102]=x,e[103]=N,e[104]=v,e[105]=z,e[106]=M):M=e[106],M},"_e");function xe(r,e){return r.name.localeCompare(e.name)}k(xe,"he");export{Ie as DeploymentHealthPanel};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as i}from"./chunk-
|
|
1
|
+
import{a as i}from"./chunk-5PEAXTYQ.js";var e=i(t=>{let r=Math.floor(t/1e3),o=Math.floor(r/3600),n=Math.floor(r%3600/60),a=r%60;return o>0?`${o.toString()}h ${n.toString()}m`:n>0?`${n.toString()}m ${a.toString()}s`:`${a.toString()}s`},"e"),m=i((t,r)=>{let o=t+r;return o===0?"\u2014":`${(t/o*100).toFixed(1)}%`},"a"),s=i(t=>t<=0?"\u2014":t<1?`${(t*1e3).toFixed(0)}\u03BCs`:t<1e3?`${t.toFixed(1)}ms`:`${(t/1e3).toFixed(2)}s`,"s"),c=i((t,r)=>new Intl.NumberFormat(r,t===0||Math.abs(t)>=1?{currency:"USD",maximumFractionDigits:2,minimumFractionDigits:2,style:"currency"}:{currency:"USD",maximumSignificantDigits:3,style:"currency"}).format(t),"c"),u=i((t,r)=>new Intl.NumberFormat(r,{maximumFractionDigits:0}).format(t),"m");export{e as a,m as b,s as c,c as d,u as e};
|