@lunora/studio 1.0.0-alpha.216 → 1.0.0-alpha.218

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/dist/index.d.mts +2 -2
  2. package/dist/index.d.ts +2 -2
  3. package/dist/index.mjs +1 -1
  4. package/dist/mount.mjs +1 -1
  5. package/dist/packem_chunks/AdvisorHealthPanel.mjs +1 -1
  6. package/dist/packem_chunks/ApiTab.mjs +1 -1
  7. package/dist/packem_chunks/AuditPanel.mjs +1 -1
  8. package/dist/packem_chunks/DeploymentHealthPanel.mjs +1 -1
  9. package/dist/packem_chunks/ExportImportPanel.mjs +1 -1
  10. package/dist/packem_chunks/FileBrowser.mjs +1 -1
  11. package/dist/packem_chunks/FunctionRunner.mjs +1 -1
  12. package/dist/packem_chunks/FunctionStatsPanel.mjs +1 -1
  13. package/dist/packem_chunks/HealthPanel.mjs +1 -1
  14. package/dist/packem_chunks/InsightsPanel.mjs +1 -1
  15. package/dist/packem_chunks/LogsPanel.mjs +1 -1
  16. package/dist/packem_chunks/MailPanel.mjs +2 -2
  17. package/dist/packem_chunks/MetricsPanel.mjs +1 -1
  18. package/dist/packem_chunks/NotificationsPanel.mjs +1 -1
  19. package/dist/packem_chunks/PitrPanel.mjs +1 -1
  20. package/dist/packem_chunks/SchemaViewer.mjs +1 -1
  21. package/dist/packem_chunks/SecurityAdvisorPanel.mjs +1 -1
  22. package/dist/packem_chunks/SettingsPanel.mjs +1 -1
  23. package/dist/packem_chunks/SqlEditorPanel.mjs +1 -1
  24. package/dist/packem_chunks/TableEditor.mjs +1 -1
  25. package/dist/packem_chunks/agents-panel.mjs +1 -1
  26. package/dist/packem_chunks/analytics-panel.mjs +1 -1
  27. package/dist/packem_chunks/auth-audit-panel.mjs +1 -1
  28. package/dist/packem_chunks/auth-config-panel.mjs +1 -1
  29. package/dist/packem_chunks/auth-sessions-panel.mjs +1 -1
  30. package/dist/packem_chunks/containers-panel.mjs +1 -1
  31. package/dist/packem_chunks/dashboards-panel.mjs +1 -1
  32. package/dist/packem_chunks/evals-panel.mjs +1 -1
  33. package/dist/packem_chunks/fanout-panel.mjs +1 -1
  34. package/dist/packem_chunks/flags-panel.mjs +1 -1
  35. package/dist/packem_chunks/issues-panel.mjs +1 -1
  36. package/dist/packem_chunks/kv-browser.mjs +1 -1
  37. package/dist/packem_chunks/log-drains-panel.mjs +1 -1
  38. package/dist/packem_chunks/migrations-route.mjs +1 -1
  39. package/dist/packem_chunks/organizations-panel.mjs +1 -1
  40. package/dist/packem_chunks/payments-panel.mjs +1 -1
  41. package/dist/packem_chunks/permissions-panel.mjs +1 -1
  42. package/dist/packem_chunks/queues-panel.mjs +1 -1
  43. package/dist/packem_chunks/reactors-panel.mjs +1 -1
  44. package/dist/packem_chunks/rls-panel.mjs +1 -1
  45. package/dist/packem_chunks/schedule-panel.mjs +1 -1
  46. package/dist/packem_chunks/storage-rules-panel.mjs +1 -1
  47. package/dist/packem_chunks/subscriptions-panel.mjs +1 -1
  48. package/dist/packem_chunks/sync-client-panel.mjs +1 -1
  49. package/dist/packem_chunks/traces-panel.mjs +1 -1
  50. package/dist/packem_chunks/users-panel.mjs +1 -1
  51. package/dist/packem_chunks/vector-browser.mjs +1 -1
  52. package/dist/packem_chunks/workflows-panel.mjs +1 -1
  53. package/dist/packem_shared/{ApiDocsPanel-BImfQhyJ.mjs → ApiDocsPanel-DzvVLAev.mjs} +1 -1
  54. package/dist/packem_shared/{ApiReferencePanel-CigvHhCa.mjs → ApiReferencePanel--1Y4o_-l.mjs} +1 -1
  55. package/dist/packem_shared/{CommandPalette-CSdz9zax.mjs → CommandPalette-D7GxhPrH.mjs} +1 -1
  56. package/dist/packem_shared/DataBrowser-CKbaOtDh.mjs +4 -0
  57. package/dist/packem_shared/GlobalDataBrowser-DSexMt80.mjs +1 -0
  58. package/dist/packem_shared/{HomePanel-_BwLI4TQ.mjs → HomePanel-BkCmY0Hl.mjs} +1 -1
  59. package/dist/packem_shared/{MigrationsPanel-BPWzFdxC.mjs → MigrationsPanel-DLQRarWw.mjs} +1 -1
  60. package/dist/packem_shared/{OpenRpcReferencePanel-C6CM791D.mjs → OpenRpcReferencePanel-a_mbqw67.mjs} +1 -1
  61. package/dist/packem_shared/{ScheduledJobs-B4DPADwk.mjs → ScheduledJobs-DSqsMB51.mjs} +1 -1
  62. package/dist/packem_shared/Studio-BE_SzY44.mjs +1 -0
  63. package/dist/packem_shared/{StudioApp-fYFz6zZQ.mjs → StudioApp-kVjMop0V.mjs} +1 -1
  64. package/dist/packem_shared/{advisor-view-CPgOok_h.mjs → advisor-view-DtkbHW2O.mjs} +1 -1
  65. package/dist/packem_shared/aggregateMetrics-5zEJC6Ju.mjs +1 -0
  66. package/dist/packem_shared/auth-pager-DiDnXsfe.mjs +1 -0
  67. package/dist/packem_shared/{data-grid-DTBAKZlm.mjs → data-grid-BPu1a997.mjs} +1 -1
  68. package/dist/packem_shared/data-view-params-DhYmAkcj.mjs +1 -0
  69. package/dist/packem_shared/{error-alert-tf5zvSLV.mjs → error-alert-dQk3g8WI.mjs} +1 -1
  70. package/dist/packem_shared/{grid-features-Dm80ngyR.mjs → grid-features-ByxOklon.mjs} +1 -1
  71. package/dist/packem_shared/grid-pagination-DgzyzfBh.mjs +1 -0
  72. package/dist/packem_shared/home-panel-B_HN6YMA.mjs +3 -0
  73. package/dist/packem_shared/internal-CyDwqA67.mjs +2 -0
  74. package/dist/packem_shared/{log-line-BoObzuue.mjs → log-line-BHZD2Aj4.mjs} +1 -1
  75. package/dist/packem_shared/{recording-client-BXUIyBL4.mjs → recording-client-CjRFjhya.mjs} +1 -1
  76. package/dist/packem_shared/reference-view-vNXUVPlA.mjs +13 -0
  77. package/dist/packem_shared/{schema-diagram-CDj_69jF.mjs → schema-diagram-DADlbs2X.mjs} +1 -1
  78. package/dist/packem_shared/{sql-result-table-C5y0jwaK.mjs → sql-result-table-DS4o0GoC.mjs} +1 -1
  79. package/dist/packem_shared/{studio-OqNyRY1N.mjs → studio-BVQq3QLR.mjs} +1 -1
  80. package/dist/packem_shared/table-list-sidebar-D30qERKx.mjs +1 -0
  81. package/dist/packem_shared/{use-admin-query-BKXiqLci.mjs → use-admin-query-CR9mHt0P.mjs} +1 -1
  82. package/dist/packem_shared/{use-async-submit-BTr3w2-K.mjs → use-async-submit-LWIKsZ8r.mjs} +1 -1
  83. package/dist/packem_shared/{use-auth-config-CuM3eJZz.mjs → use-auth-config-HmTOvrWd.mjs} +1 -1
  84. package/dist/packem_shared/{use-open-trace-BCW0c9qq.mjs → use-open-trace-DdGxsEB9.mjs} +1 -1
  85. package/dist/packem_shared/{use-sql-assistant-BhIMDQHV.mjs → use-sql-assistant-D4XQ0v0R.mjs} +1 -1
  86. package/dist/standalone/{chunk-AO4QYDDE.js → chunk-2ABVDLD3.js} +1 -1
  87. package/dist/standalone/{chunk-S777MGJ4.js → chunk-2GX5QWJO.js} +1 -1
  88. package/dist/standalone/{chunk-TEHBW2ZJ.js → chunk-4MDN4KNZ.js} +1 -1
  89. package/dist/standalone/chunk-4QRACVKS.js +1 -0
  90. package/dist/standalone/chunk-5ICUJ4IA.js +15 -0
  91. package/dist/standalone/{chunk-FODLDLE2.js → chunk-6B7FVPW3.js} +5 -5
  92. package/dist/standalone/chunk-6DAD3RFX.js +1 -0
  93. package/dist/standalone/{chunk-3QBHQHML.js → chunk-6P2CF75M.js} +1 -1
  94. package/dist/standalone/chunk-7MUDJ77E.js +2 -0
  95. package/dist/standalone/chunk-7RC4EUCQ.js +1 -0
  96. package/dist/standalone/{chunk-L3JG4A4O.js → chunk-A2XTI2C3.js} +1 -1
  97. package/dist/standalone/{chunk-B7ITCEGD.js → chunk-AH6MS5JC.js} +1 -1
  98. package/dist/standalone/chunk-AZK27U77.js +5 -0
  99. package/dist/standalone/chunk-C4ZYEJTF.js +1 -0
  100. package/dist/standalone/{chunk-VW4IYQ6B.js → chunk-CP3R2ALX.js} +1 -1
  101. package/dist/standalone/chunk-CPWKS5SR.js +1 -0
  102. package/dist/standalone/{chunk-3CNK6VZ5.js → chunk-CUHQANWF.js} +1 -1
  103. package/dist/standalone/chunk-CYZRKXQ7.js +1 -0
  104. package/dist/standalone/{chunk-TIUMFAN2.js → chunk-DKLSANZA.js} +1 -1
  105. package/dist/standalone/{chunk-MAHWOCKG.js → chunk-DX6246CW.js} +1 -1
  106. package/dist/standalone/{chunk-DX6FAHR2.js → chunk-DXT2DY4I.js} +1 -1
  107. package/dist/standalone/{chunk-AHUCYH5J.js → chunk-EUKWJXVS.js} +1 -1
  108. package/dist/standalone/chunk-EULTOXNM.js +1 -0
  109. package/dist/standalone/{chunk-QYHIT4Y2.js → chunk-FAEOVAT3.js} +1 -1
  110. package/dist/standalone/{chunk-WLBLETPV.js → chunk-FBF54LE5.js} +1 -1
  111. package/dist/standalone/{chunk-S2L6ZWZS.js → chunk-FKERUAF4.js} +1 -1
  112. package/dist/standalone/chunk-FRFZPB5H.js +1 -0
  113. package/dist/standalone/{chunk-E7TOMONS.js → chunk-FS4GMDIW.js} +1 -1
  114. package/dist/standalone/chunk-GIGWJPT6.js +3 -0
  115. package/dist/standalone/chunk-GIKJQCRP.js +1 -0
  116. package/dist/standalone/{chunk-NU5BW3PZ.js → chunk-GZTVFMUP.js} +1 -1
  117. package/dist/standalone/{chunk-SQCDYMGV.js → chunk-HL4ZEZMY.js} +1 -1
  118. package/dist/standalone/{chunk-SDVIMYHO.js → chunk-HP3744HC.js} +1 -1
  119. package/dist/standalone/{chunk-K2JXTI3K.js → chunk-HSFHUX3I.js} +1 -1
  120. package/dist/standalone/{chunk-BOTGXX4H.js → chunk-IJPXZZZ5.js} +1 -1
  121. package/dist/standalone/{chunk-EMI4BFAP.js → chunk-JKIJX6RO.js} +1 -1
  122. package/dist/standalone/{chunk-TBOH7YLA.js → chunk-JORZEU6W.js} +1 -1
  123. package/dist/standalone/{chunk-N7HX56RX.js → chunk-LE6D7O3V.js} +1 -1
  124. package/dist/standalone/{chunk-JM75KC3R.js → chunk-LOXE2EQN.js} +1 -1
  125. package/dist/standalone/{chunk-PR4REGGV.js → chunk-LRXRBN53.js} +1 -1
  126. package/dist/standalone/{chunk-GGPSI4ZR.js → chunk-MDUTVBJZ.js} +1 -1
  127. package/dist/standalone/chunk-NMPKQ7ZP.js +14 -0
  128. package/dist/standalone/{chunk-7F6DLCQ7.js → chunk-NNLGVQGS.js} +1 -1
  129. package/dist/standalone/{chunk-OHW5YMNX.js → chunk-O73LCRWX.js} +1 -1
  130. package/dist/standalone/chunk-OHOQXJGW.js +9 -0
  131. package/dist/standalone/{chunk-HAGQT3Q3.js → chunk-OOPAQUOU.js} +1 -1
  132. package/dist/standalone/{chunk-BSAK46ON.js → chunk-OTSOULJM.js} +1 -1
  133. package/dist/standalone/{chunk-BDO4YYBB.js → chunk-PY5P53RV.js} +3 -3
  134. package/dist/standalone/{chunk-LBMSRD6N.js → chunk-Q2F2DRGB.js} +1 -1
  135. package/dist/standalone/{chunk-6PWVP7AF.js → chunk-Q57WJNAA.js} +1 -1
  136. package/dist/standalone/{chunk-WXILD54E.js → chunk-QHXU4TU5.js} +1 -1
  137. package/dist/standalone/chunk-QKZ2JCH3.js +1 -0
  138. package/dist/standalone/{chunk-6QRG55QT.js → chunk-RQZETKMO.js} +1 -1
  139. package/dist/standalone/{chunk-TTXQWPXA.js → chunk-SDHDZTLI.js} +1 -1
  140. package/dist/standalone/chunk-SDORK4S2.js +1 -0
  141. package/dist/standalone/chunk-T5TFEQQX.js +1 -0
  142. package/dist/standalone/{chunk-4RXSYGEK.js → chunk-TJUJQDTM.js} +1 -1
  143. package/dist/standalone/{chunk-KPJ3CRRA.js → chunk-TOWJVMCP.js} +1 -1
  144. package/dist/standalone/{chunk-RXHFAGPL.js → chunk-TZPC24PB.js} +1 -1
  145. package/dist/standalone/{chunk-X2UMKKLV.js → chunk-V4UHVN7O.js} +1 -1
  146. package/dist/standalone/chunk-V5N7DHTG.js +1 -0
  147. package/dist/standalone/chunk-VQTSESFP.js +1 -0
  148. package/dist/standalone/{chunk-EEV7BCBD.js → chunk-VUIMAZAE.js} +1 -1
  149. package/dist/standalone/{chunk-6XXH4HTP.js → chunk-W2RO7ETU.js} +1 -1
  150. package/dist/standalone/{chunk-PTZF5Z2E.js → chunk-WM4EMDVF.js} +1 -1
  151. package/dist/standalone/{chunk-WOMOO5PU.js → chunk-WQBJWQ4N.js} +1 -1
  152. package/dist/standalone/{chunk-WIZVZKQJ.js → chunk-WSV2XPHL.js} +1 -1
  153. package/dist/standalone/chunk-X77OELCM.js +1 -0
  154. package/dist/standalone/{chunk-YSFHOLG3.js → chunk-XJOQJUZC.js} +1 -1
  155. package/dist/standalone/{chunk-GRCYXMO2.js → chunk-Y5PCZUGU.js} +1 -1
  156. package/dist/standalone/chunk-YV6JXZJO.js +1 -0
  157. package/dist/standalone/{chunk-2DX5MROH.js → chunk-ZHM5ZHPC.js} +1 -1
  158. package/dist/standalone/{chunk-PD6WIDY6.js → chunk-ZJZNCJHY.js} +1 -1
  159. package/dist/standalone/{chunk-BYL5HFB5.js → chunk-ZRMO7SAI.js} +1 -1
  160. package/dist/standalone/chunk-ZU2LKNAK.js +1 -0
  161. package/dist/standalone/studio.js +1 -1
  162. package/dist/styles.css +1 -1
  163. package/package.json +6 -6
  164. package/dist/packem_shared/DataBrowser-DLRa1EYq.mjs +0 -4
  165. package/dist/packem_shared/GlobalDataBrowser-BTbqR6Wc.mjs +0 -1
  166. package/dist/packem_shared/Studio-CcWQdYrV.mjs +0 -1
  167. package/dist/packem_shared/aggregateMetrics-CY05xrYU.mjs +0 -1
  168. package/dist/packem_shared/data-view-params-qoSTqjAj.mjs +0 -1
  169. package/dist/packem_shared/home-panel-DCUKd8Uk.mjs +0 -3
  170. package/dist/packem_shared/internal-B6haJbiP.mjs +0 -2
  171. package/dist/packem_shared/reference-view-DiikOols.mjs +0 -13
  172. package/dist/packem_shared/table-list-sidebar-DHG1UJC4.mjs +0 -1
  173. package/dist/standalone/chunk-55TJJQ57.js +0 -14
  174. package/dist/standalone/chunk-7WO44X5E.js +0 -3
  175. package/dist/standalone/chunk-A3USNEQH.js +0 -1
  176. package/dist/standalone/chunk-A5YGB26Y.js +0 -1
  177. package/dist/standalone/chunk-AEGXKZBQ.js +0 -1
  178. package/dist/standalone/chunk-CSM6OYOI.js +0 -1
  179. package/dist/standalone/chunk-DAD7BLZ4.js +0 -1
  180. package/dist/standalone/chunk-DQYXEGZK.js +0 -1
  181. package/dist/standalone/chunk-HDZXGHWP.js +0 -1
  182. package/dist/standalone/chunk-HMH7KVSI.js +0 -1
  183. package/dist/standalone/chunk-JD6IZRDH.js +0 -1
  184. package/dist/standalone/chunk-KAMSXLSQ.js +0 -1
  185. package/dist/standalone/chunk-KIOIUXMK.js +0 -9
  186. package/dist/standalone/chunk-KTBYRAXO.js +0 -5
  187. package/dist/standalone/chunk-O3FQQDO5.js +0 -2
  188. package/dist/standalone/chunk-QAEMYSRQ.js +0 -1
  189. package/dist/standalone/chunk-RLLKECZT.js +0 -1
  190. package/dist/standalone/chunk-SUDJTC4S.js +0 -1
  191. package/dist/standalone/chunk-UEEULFHK.js +0 -1
  192. package/dist/standalone/chunk-UJNMJTDN.js +0 -15
  193. package/dist/standalone/chunk-WKOSPFHJ.js +0 -1
@@ -0,0 +1,14 @@
1
+ import{a as je}from"./chunk-EA2JKR5D.js";import{a as he}from"./chunk-IMOHEGMV.js";import{d as Ne,f as ke,g as we,k as oe}from"./chunk-V3VJAA4D.js";import{a as V}from"./chunk-5WJXVZMZ.js";import{a as Pe}from"./chunk-ZHM5ZHPC.js";import"./chunk-OGUKYRFM.js";import"./chunk-OKG3HWSJ.js";import{W as ye}from"./chunk-PLHA3OWK.js";import"./chunk-4L4WTGN5.js";import{a as B}from"./chunk-55754F6H.js";import"./chunk-IS6LVJ6L.js";import"./chunk-AAVLPU5Q.js";import{b as ve}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{a as $e}from"./chunk-4ZEL6BYL.js";import{f as F}from"./chunk-OHOQXJGW.js";import"./chunk-FSRSK4LY.js";import{d as be}from"./chunk-5ICUJ4IA.js";import{a as U}from"./chunk-FKVZRPV5.js";import{d as M,e as Se,f as se,g as ie,h as le,m as Ie,p as Oe,s as ae}from"./chunk-6B7FVPW3.js";import{a as u,d as z,e as ue,f as te,g as re,i as fe}from"./chunk-YKXDMIHQ.js";var Ge=z(te(),1),xe=z(ue(),1);var Y=z(te(),1);var X=z(ue(),1);var C=z(re(),1);var Ve=se($e.listTables),Xe=["react","client","cli"],Ye={action:"action",mutation:"mutation",query:"query"},Te=u(t=>{let e=t.indexOf(":");return e===-1?{file:"",fn:t}:{file:t.slice(0,e),fn:t.slice(e+1)}},"Q"),Ze=u(({file:t,fn:e,kind:a})=>`await client.${Ye[a]}(api.${t}.${e}, { /* args */ });`,"ie"),et=u(t=>{let e=`api.${t.file}.${t.fn}`;switch(t.kind){case"action":return`const { call: ${t.fn} } = useAction(${e});`;case"mutation":return`const ${t.fn} = useMutation(${e});`;default:return`const data = useQuery(${e}, { /* args */ });`}},"se"),tt=u(({file:t,fn:e})=>`lunora run ${t}:${e} --args '{ }'`,"oe"),rt=u(t=>["// Read rows",`const rows = await ctx.db.query("${t}").collect();`,"","// Insert a row",`const id = await ctx.db.insert("${t}", { /* fields */ });`,"","// Generated types",`type Row = Doc<"${t}">;`,`type RowId = Id<"${t}">;`].join(`
2
+ `),"ce"),at=u((t,e)=>{switch(t){case"cli":return tt(e);case"client":return Ze(e);default:return et(e)}},"re"),Ce=u(t=>{let e=(0,Y.c)(19),{code:a,label:r,testId:n}=t,s=M(),o;e[0]!==a?(o=u(()=>{ae(a)},"c"),e[0]=a,e[1]=o):o=e[1];let i=o,d;e[2]!==r?(d=(0,C.jsx)("span",{className:"text-xs font-medium text-muted-foreground",children:r}),e[2]=r,e[3]=d):d=e[3];let m=`${n}-copy`,l;e[4]!==s?(l=s("Copy"),e[4]=s,e[5]=l):l=e[5];let c;e[6]!==i||e[7]!==m||e[8]!==l?(c=(0,C.jsx)(B,{"data-testid":m,onClick:i,size:"xs",type:"button",variant:"ghost",children:l}),e[6]=i,e[7]=m,e[8]=l,e[9]=c):c=e[9];let f;e[10]!==d||e[11]!==c?(f=(0,C.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[d,c]}),e[10]=d,e[11]=c,e[12]=f):f=e[12];let h;e[13]!==a||e[14]!==n?(h=(0,C.jsx)("pre",{className:"overflow-auto rounded-md border border-border bg-muted/50 p-3 font-mono text-xs","data-testid":n,children:a}),e[13]=a,e[14]=n,e[15]=h):h=e[15];let g;return e[16]!==f||e[17]!==h?(g=(0,C.jsxs)("div",{className:"flex flex-col gap-1.5",children:[f,h]}),e[16]=f,e[17]=h,e[18]=g):g=e[18],g},"U"),nt=u(t=>{let e=(0,Y.c)(46),{file:a,fn:r,kind:n}=t,s=M(),[o,i]=(0,X.useState)("react"),d,m,l;if(e[0]!==a||e[1]!==r||e[2]!==n||e[3]!==s||e[4]!==o){let w={file:a,fn:r,kind:n},j;e[8]!==s?(j=s("CLI"),e[8]=s,e[9]=j):j=e[9];let O;e[10]!==s?(O=s("Client"),e[10]=s,e[11]=O):O=e[11];let S;e[12]!==s?(S=s("React"),e[12]=s,e[13]=S):S=e[13];let T;e[14]!==j||e[15]!==O||e[16]!==S?(T={cli:j,client:O,react:S},e[14]=j,e[15]=O,e[16]=S,e[17]=T):T=e[17],l=T;let A;e[18]===Symbol.for("react.memo_cache_sentinel")?(A=u(R=>{i(R.currentTarget.dataset.tab)},"B"),e[18]=A):A=e[18],d=A,m=at(o,w),e[0]=a,e[1]=r,e[2]=n,e[3]=s,e[4]=o,e[5]=d,e[6]=m,e[7]=l}else d=e[5],m=e[6],l=e[7];let c=m,f=`api.${a}.${r}`,h;e[19]!==f?(h=(0,C.jsx)("h2",{className:"font-mono text-sm font-semibold text-foreground","data-testid":"api-fn-title",children:f}),e[19]=f,e[20]=h):h=e[20];let g;e[21]!==n||e[22]!==s?(g=s("Call this {kind} from your app.",{kind:n}),e[21]=n,e[22]=s,e[23]=g):g=e[23];let x;e[24]!==g?(x=(0,C.jsx)("p",{className:"text-xs text-muted-foreground",children:g}),e[24]=g,e[25]=x):x=e[25];let y;e[26]!==h||e[27]!==x?(y=(0,C.jsxs)("div",{children:[h,x]}),e[26]=h,e[27]=x,e[28]=y):y=e[28];let N;e[29]!==s?(N=s("Snippet flavour"),e[29]=s,e[30]=N):N=e[30];let v;e[31]!==d||e[32]!==o||e[33]!==l?(v=Xe.map(w=>(0,C.jsx)(B,{"aria-selected":o===w,"data-tab":w,"data-testid":`api-tab-${w}`,onClick:d,role:"tab",size:"xs",type:"button",variant:o===w?"default":"outline",children:l[w]},w)),e[31]=d,e[32]=o,e[33]=l,e[34]=v):v=e[34];let b;e[35]!==N||e[36]!==v?(b=(0,C.jsx)("div",{"aria-label":N,className:"flex gap-1.5","data-testid":"api-tabs",role:"tablist",children:v}),e[35]=N,e[36]=v,e[37]=b):b=e[37];let I=l[o],P=`api-snippet-${o}`,$;e[38]!==c||e[39]!==I||e[40]!==P?($=(0,C.jsx)(Ce,{code:c,label:I,testId:P}),e[38]=c,e[39]=I,e[40]=P,e[41]=$):$=e[41];let k;return e[42]!==$||e[43]!==y||e[44]!==b?(k=(0,C.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"api-fn-doc",children:[y,b,$]}),e[42]=$,e[43]=y,e[44]=b,e[45]=k):k=e[45],k},"de"),ot=u(t=>{let e=(0,Y.c)(19),{name:a}=t,r=M(),n;e[0]!==a?(n=rt(a),e[0]=a,e[1]=n):n=e[1];let s=n,o;e[2]!==a?(o=(0,C.jsx)("h2",{className:"font-mono text-sm font-semibold text-foreground","data-testid":"api-table-title",children:a}),e[2]=a,e[3]=o):o=e[3];let i;e[4]!==r?(i=r("Read and write this table through the typed data model."),e[4]=r,e[5]=i):i=e[5];let d;e[6]!==i?(d=(0,C.jsx)("p",{className:"text-xs text-muted-foreground",children:i}),e[6]=i,e[7]=d):d=e[7];let m;e[8]!==o||e[9]!==d?(m=(0,C.jsxs)("div",{children:[o,d]}),e[8]=o,e[9]=d,e[10]=m):m=e[10];let l;e[11]!==r?(l=r("Data model"),e[11]=r,e[12]=l):l=e[12];let c;e[13]!==s||e[14]!==l?(c=(0,C.jsx)(Ce,{code:s,label:l,testId:"api-snippet-table"}),e[13]=s,e[14]=l,e[15]=c):c=e[15];let f;return e[16]!==m||e[17]!==c?(f=(0,C.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"api-table-doc",children:[m,c]}),e[16]=m,e[17]=c,e[18]=f):f=e[18],f},"fe"),_e=u(t=>{let e=(0,Y.c)(8),{active:a,label:r,onSelect:n,testId:s,value:o}=t,i;e[0]!==n||e[1]!==o?(i=u(()=>{n(o)},"m"),e[0]=n,e[1]=o,e[2]=i):i=e[2];let d=i,m=a?"page":void 0,l;return e[3]!==r||e[4]!==d||e[5]!==m||e[6]!==s?(l=(0,C.jsx)("button",{"aria-current":m,className:"w-full truncate rounded-md px-2 py-1 text-start font-mono text-xs text-muted-foreground outline-none transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:bg-sidebar-accent aria-[current=page]:bg-sidebar-accent aria-[current=page]:font-medium aria-[current=page]:text-foreground","data-testid":s,onClick:d,type:"button",children:r}),e[3]=r,e[4]=d,e[5]=m,e[6]=s,e[7]=l):l=e[7],l},"G"),st=u(t=>{let e=new Map;for(let a of t){let{file:r,fn:n}=Te(a.path),s=e.get(r)??[];s.push({fn:n,kind:a.kind,path:a.path}),e.set(r,s)}return[...e.entries()].map(([a,r])=>({file:a,items:r.toSorted((n,s)=>n.fn.localeCompare(s.fn))})).toSorted((a,r)=>a.file.localeCompare(r.file))},"pe"),Ae=u(t=>{let e=(0,Y.c)(58),{functions:a,initialShardKey:r}=t,n=M(),s=F(),[o,i]=(0,X.useState)(null),[d,m]=(0,X.useState)(null),l,c;e[0]!==s||e[1]!==r?(l=u(()=>{let R=!1;return s.query(Ve,{},ie(r??"")).then(_=>(R||i(_),_)).catch(()=>{R||i([])}),()=>{R=!0}},"o"),c=[s,r],e[0]=s,e[1]=r,e[2]=l,e[3]=c):(l=e[2],c=e[3]),(0,X.useEffect)(l,c);let f,h,g,x,y,N,v,b,I,P;if(e[4]!==a||e[5]!==d||e[6]!==n||e[7]!==o){let R=a??[],_=st(R),L=(o??[]).map(it).toSorted(lt),E;e[18]===Symbol.for("react.memo_cache_sentinel")?(E=u(q=>{m({kind:"fn",path:q})},"P"),e[18]=E):E=e[18];let W=E,Q;e[19]===Symbol.for("react.memo_cache_sentinel")?(Q=u(q=>{m({kind:"table",name:q})},"j"),e[19]=Q):Q=e[19];let Qe=Q;h=d?.kind==="fn"?R.find(q=>q.path===d.path):void 0,f=R.length>0||L.length>0,g=h===void 0?void 0:Te(h.path),I="grid min-h-0 gap-6 md:grid-cols-[16rem_minmax(0,1fr)]",P="lunora-api-docs",e[20]!==n?(x=n("API resources"),e[20]=n,e[21]=x):x=e[21],y="flex flex-col gap-4 overflow-y-auto",N="api-rail";let ne;e[22]!==d||e[23]!==n?(ne=u(q=>(0,C.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,C.jsx)("span",{className:"px-2 font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:q.file||n("(root)")}),q.items.map(ee=>(0,C.jsx)(_e,{active:d?.kind==="fn"&&d.path===ee.path,label:ee.fn,onSelect:W,testId:`api-rail-fn-${ee.path}`,value:ee.path},ee.path))]},q.file),"q"),e[22]=d,e[23]=n,e[24]=ne):ne=e[24],v=_.map(ne),b=L.length>0&&(0,C.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,C.jsx)("span",{className:"px-2 font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:n("Tables")}),L.map(q=>(0,C.jsx)(_e,{active:d?.kind==="table"&&d.name===q,label:q,onSelect:Qe,testId:`api-rail-table-${q}`,value:q},q))]}),e[4]=a,e[5]=d,e[6]=n,e[7]=o,e[8]=f,e[9]=h,e[10]=g,e[11]=x,e[12]=y,e[13]=N,e[14]=v,e[15]=b,e[16]=I,e[17]=P}else f=e[8],h=e[9],g=e[10],x=e[11],y=e[12],N=e[13],v=e[14],b=e[15],I=e[16],P=e[17];let $;e[25]!==f||e[26]!==n?($=!f&&(0,C.jsx)("p",{className:"px-2 text-xs text-muted-foreground","data-testid":"api-rail-empty",children:n("No functions or tables to document yet.")}),e[25]=f,e[26]=n,e[27]=$):$=e[27];let k;e[28]!==$||e[29]!==x||e[30]!==y||e[31]!==N||e[32]!==v||e[33]!==b?(k=(0,C.jsxs)("nav",{"aria-label":x,className:y,"data-testid":N,children:[v,b,$]}),e[28]=$,e[29]=x,e[30]=y,e[31]=N,e[32]=v,e[33]=b,e[34]=k):k=e[34];let w;e[35]!==d||e[36]!==n?(w=d===null&&(0,C.jsx)(U,{description:n("Select a function or table to see how to call it from your app."),testId:"api-empty",title:n("API usage snippets")}),e[35]=d,e[36]=n,e[37]=w):w=e[37];let j;e[38]!==d?.kind||e[39]!==h||e[40]!==g?(j=d?.kind==="fn"&&h!==void 0&&g!==void 0&&(0,C.jsx)(nt,{file:g.file,fn:g.fn,kind:h.kind},h.path),e[38]=d?.kind,e[39]=h,e[40]=g,e[41]=j):j=e[41];let O;e[42]!==d?.kind||e[43]!==h||e[44]!==n?(O=d?.kind==="fn"&&h===void 0&&(0,C.jsx)(U,{testId:"api-empty",title:n("API usage snippets")}),e[42]=d?.kind,e[43]=h,e[44]=n,e[45]=O):O=e[45];let S;e[46]!==d?(S=d?.kind==="table"&&(0,C.jsx)(ot,{name:d.name}),e[46]=d,e[47]=S):S=e[47];let T;e[48]!==w||e[49]!==j||e[50]!==O||e[51]!==S?(T=(0,C.jsxs)("div",{className:"min-w-0",children:[w,j,O,S]}),e[48]=w,e[49]=j,e[50]=O,e[51]=S,e[52]=T):T=e[52];let A;return e[53]!==k||e[54]!==T||e[55]!==I||e[56]!==P?(A=(0,C.jsxs)("div",{className:I,"data-testid":P,children:[k,T]}),e[53]=k,e[54]=T,e[55]=I,e[56]=P,e[57]=A):A=e[57],A},"ke");function it(t){return t.name}u(it,"ue");function lt(t,e){return t.localeCompare(e)}u(lt,"me");var We=z(te(),1);var K=z(te(),1),J=z(ue(),1);var p=z(re(),1);var pe=u(function(t,e,a){let r=(0,K.c)(15),n;r[0]===Symbol.for("react.memo_cache_sentinel")?(n={kind:"loading"},r[0]=n):n=r[0];let[s,o]=(0,J.useState)(n),i;r[1]!==e?(i=u(async()=>e(),"a"),r[1]=e,r[2]=i):i=r[2];let d=(0,J.useEffectEvent)(i),m;r[3]!==a?(m=u(g=>a(g),"d"),r[3]=a,r[4]=m):m=r[4];let l=(0,J.useEffectEvent)(m),c;r[5]!==l||r[6]!==d||r[7]!==t?(c=u(()=>{if(t!==void 0)return;let g=!1;return d().then(x=>(g||o(l(x)),x)).catch(x=>{g||o({kind:"error",message:le(x)})}),()=>{g=!0}},"u"),r[5]=l,r[6]=d,r[7]=t,r[8]=c):c=r[8];let f;r[9]!==t?(f=[t],r[9]=t,r[10]=f):f=r[10],(0,J.useEffect)(c,f);let h;return r[11]!==a||r[12]!==s||r[13]!==t?(h=t===void 0?s:a(t),r[11]=a,r[12]=s,r[13]=t,r[14]=h):h=r[14],h},"Ot"),dt=u(t=>typeof t=="number"?"number":typeof t=="boolean"?"boolean":"string","Oe"),Je=u(t=>{if(t.enum!==void 0&&t.enum.length>0)return t.enum;if(t.anyOf!==void 0&&t.anyOf.length>0&&t.anyOf.every(e=>e.const!==void 0))return t.anyOf.map(e=>e.const)},"Z"),ce=u(t=>t===void 0?"any":t.const!==void 0?JSON.stringify(t.const):t.enum!==void 0&&t.enum.length>0?t.enum.map(e=>JSON.stringify(e)).join(" | "):t.anyOf!==void 0&&t.anyOf.length>0?t.anyOf.map(e=>ce(e)).join(" | "):t.type==="array"?`array<${ce(t.items)}>`:t.type??"any","F"),ct=u(t=>{let e=Je(t);return e!==void 0?t.type??dt(e[0]):ce(t)},"$e"),pt=u(t=>{let e=Je(t);return e===void 0?void 0:e.map(a=>JSON.stringify(a)).join(" | ")},"Te"),mt=u(t=>{let e=[];t.minimum!==void 0?e.push(`${String(t.minimum)} \u2264`):t.exclusiveMinimum!==void 0&&e.push(`${String(t.exclusiveMinimum)} <`);let a=e.length>0;e.push("value"),t.maximum!==void 0?e.push(`\u2264 ${String(t.maximum)}`):t.exclusiveMaximum!==void 0&&e.push(`< ${String(t.exclusiveMaximum)}`);let r=e.length>(a?2:1);return a||r?e.join(" "):void 0},"Ee"),ut=u(t=>{if(t.type==="object"&&t.properties!==void 0)return t;if(t.type==="array"&&t.items?.type==="object"&&t.items.properties!==void 0)return t.items},"Ce"),Z=u(t=>{if(t===void 0)return null;if(t.const!==void 0)return t.const;if(t.enum!==void 0&&t.enum.length>0)return t.enum[0];if(t.anyOf!==void 0&&t.anyOf.length>0)return Z(t.anyOf[0]);switch(t.type){case"array":return[];case"boolean":return!1;case"number":return 0;case"object":{let e={};for(let[a,r]of Object.entries(t.properties??{}))e[a]=Z(r);return e}case"string":return"";default:return null}},"D"),de=u(t=>{let e=(0,K.c)(7),{label:a,value:r}=t,n;e[0]!==a?(n=(0,p.jsx)("span",{className:"text-muted-foreground",children:a}),e[0]=a,e[1]=n):n=e[1];let s;e[2]!==r?(s=(0,p.jsx)("span",{className:"text-foreground",children:r}),e[2]=r,e[3]=s):s=e[3];let o;return e[4]!==n||e[5]!==s?(o=(0,p.jsxs)("span",{className:"inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5 font-mono text-[10px]",children:[n,s]}),e[4]=n,e[5]=s,e[6]=o):o=e[6],o},"K"),ft=u(t=>{let e=(0,K.c)(40),{name:a,required:r,schema:n}=t,s=M(),o;e[0]!==n?(o=mt(n),e[0]=n,e[1]=o):o=e[1];let i=o,d;e[2]!==n?(d=pt(n),e[2]=n,e[3]=d):d=e[3];let m=d,l=n["x-lunora-table"],c=n.format!==void 0||i!==void 0||m!==void 0||l!==void 0,f;e[4]!==n?(f=ut(n),e[4]=n,e[5]=f):f=e[5];let h=f,g=r?"*":"?",x;e[6]!==g?(x=(0,p.jsx)("span",{className:"text-muted-foreground",children:g}),e[6]=g,e[7]=x):x=e[7];let y;e[8]!==a||e[9]!==x?(y=(0,p.jsxs)("span",{className:"font-mono text-foreground",children:[a,x]}),e[8]=a,e[9]=x,e[10]=y):y=e[10];let N;e[11]!==n?(N=ct(n),e[11]=n,e[12]=N):N=e[12];let v;e[13]!==N?(v=(0,p.jsx)("span",{className:"font-mono text-muted-foreground",children:N}),e[13]=N,e[14]=v):v=e[14];let b;e[15]!==y||e[16]!==v?(b=(0,p.jsxs)("div",{className:"flex items-baseline gap-2",children:[y,v]}),e[15]=y,e[16]=v,e[17]=b):b=e[17];let I;e[18]!==n.description?(I=n.description!==void 0&&(0,p.jsx)("p",{className:"max-w-prose text-muted-foreground",children:n.description}),e[18]=n.description,e[19]=I):I=e[19];let P;e[20]!==c||e[21]!==i||e[22]!==l||e[23]!==n.format||e[24]!==s||e[25]!==m?(P=c&&(0,p.jsxs)("div",{className:"flex flex-wrap gap-1",children:[n.format!==void 0&&(0,p.jsx)(de,{label:s("Format"),value:n.format}),i!==void 0&&(0,p.jsx)(de,{label:s("Range"),value:i}),m!==void 0&&(0,p.jsx)(de,{label:s("Value in"),value:m}),l!==void 0&&(0,p.jsx)(de,{label:s("relation"),value:l})]}),e[20]=c,e[21]=i,e[22]=l,e[23]=n.format,e[24]=s,e[25]=m,e[26]=P):P=e[26];let $;e[27]!==I||e[28]!==P||e[29]!==b?($=(0,p.jsxs)("div",{className:"flex flex-col gap-1 py-2",children:[b,I,P]}),e[27]=I,e[28]=P,e[29]=b,e[30]=$):$=e[30];let k=$;if(h===void 0){let S;return e[31]!==k?(S=(0,p.jsx)("div",{className:"border-b border-border/50 last:border-b-0",children:k}),e[31]=k,e[32]=S):S=e[32],S}let w;e[33]!==k?(w=(0,p.jsx)("summary",{className:"cursor-pointer marker:text-muted-foreground",children:k}),e[33]=k,e[34]=w):w=e[34];let j;e[35]!==h?(j=(0,p.jsx)("div",{className:"mb-2 ml-2 border-l border-border pl-3",children:(0,p.jsx)(Me,{schema:h})}),e[35]=h,e[36]=j):j=e[36];let O;return e[37]!==w||e[38]!==j?(O=(0,p.jsxs)("details",{className:"border-b border-border/50 last:border-b-0",children:[w,j]}),e[37]=w,e[38]=j,e[39]=O):O=e[39],O},"Ae"),Me=u(t=>{let e=(0,K.c)(7),{schema:a}=t,r;e[0]!==a.required?(r=new Set(a.required),e[0]=a.required,e[1]=r):r=e[1];let n=r,s;e[2]!==a.properties?(s=Object.entries(a.properties??{}),e[2]=a.properties,e[3]=s):s=e[3];let o=s,i;return e[4]!==n||e[5]!==o?(i=(0,p.jsx)("div",{className:"flex flex-col",children:o.map(d=>{let[m,l]=d;return(0,p.jsx)(ft,{name:m,required:n.has(m),schema:l},m)})}),e[4]=n,e[5]=o,e[6]=i):i=e[6],i},"ee"),Re=u(t=>{let e=(0,K.c)(10),{schema:a,testId:r}=t;if(a?.type!=="object"||Object.keys(a.properties??{}).length===0){let o;e[0]!==a?(o=ce(a),e[0]=a,e[1]=o):o=e[1];let i;return e[2]!==o||e[3]!==r?(i=(0,p.jsx)("p",{className:"font-mono text-xs text-muted-foreground","data-testid":r,children:o}),e[2]=o,e[3]=r,e[4]=i):i=e[4],i}let n;e[5]!==a?(n=(0,p.jsx)(Me,{schema:a}),e[5]=a,e[6]=n):n=e[6];let s;return e[7]!==n||e[8]!==r?(s=(0,p.jsx)("div",{className:"text-xs","data-testid":r,children:n}),e[7]=n,e[8]=r,e[9]=s):s=e[9],s},"G"),ht=["curl","javascript","lunora"],gt={lunora:"Lunora",curl:"cURL",javascript:"JavaScript"},xt=u(t=>`api.${t.replaceAll(/[/:]/g,".")}`,"Ie"),bt=u(t=>{let e=Z(t.argsSchema)??{};return t.functionPath===void 0?e:{args:e,functionPath:t.functionPath}},"Pe"),vt=u((t,e,a)=>{let r=`${a}${e.httpPath}`,n=JSON.stringify(bt(e),void 0,2),s=JSON.stringify(Z(e.argsSchema)??{},void 0,2);switch(t){case"curl":{let o=e.method!=="GET"&&e.method!=="HEAD",i=[`curl -X ${e.method} ${JSON.stringify(r)}`];return o&&i.push(' -H "Content-Type: application/json"',` -d '${n}'`),i.join(` \\
3
+ `)}case"lunora":return e.functionPath===void 0?`await fetch(${JSON.stringify(e.httpPath)}, { method: ${JSON.stringify(e.method)} });`:`import { useLunora } from "@lunora/react";
4
+ import { api } from "./_generated/api";
5
+
6
+ const client = useLunora();
7
+ await client.${e.kind??"query"}(${xt(e.functionPath)}, ${s});`;default:{let o=e.method!=="GET"&&e.method!=="HEAD"?`{
8
+ method: ${JSON.stringify(e.method)},
9
+ headers: { "Content-Type": "application/json" },
10
+ body: JSON.stringify(${n}),
11
+ }`:`{ method: ${JSON.stringify(e.method)} }`;return`const response = await fetch(${JSON.stringify(r)}, ${o});
12
+ const data = await response.json();`}}},"Le"),yt=u(t=>{let e=(0,K.c)(24),{operation:a,server:r}=t,n=M(),[s,o]=(0,J.useState)("curl"),i;e[0]!==a||e[1]!==s||e[2]!==r?(i=vt(s,a,r),e[0]=a,e[1]=s,e[2]=r,e[3]=i):i=e[3];let d=i,m;e[4]!==d?(m=u(()=>{ae(d)},"d"),e[4]=d,e[5]=m):m=e[5];let l=m,c;e[6]===Symbol.for("react.memo_cache_sentinel")?(c=u(I=>{o(I.currentTarget.dataset.sample)},"u"),e[6]=c):c=e[6];let f=c,h;e[7]!==s?(h=ht.map(I=>(0,p.jsx)("button",{"aria-selected":s===I,className:"rounded px-2 py-0.5 text-xs text-muted-foreground transition-colors hover:text-foreground aria-selected:bg-muted aria-selected:font-medium aria-selected:text-foreground","data-sample":I,"data-testid":`api-sample-${I}`,onClick:f,role:"tab",type:"button",children:gt[I]},I)),e[7]=s,e[8]=h):h=e[8];let g;e[9]!==h?(g=(0,p.jsx)("div",{className:"flex gap-1",role:"tablist",children:h}),e[9]=h,e[10]=g):g=e[10];let x;e[11]!==n?(x=n("Copy"),e[11]=n,e[12]=x):x=e[12];let y;e[13]!==l||e[14]!==x?(y=(0,p.jsx)(B,{"data-testid":"api-sample-copy",onClick:l,size:"xs",type:"button",variant:"ghost",children:x}),e[13]=l,e[14]=x,e[15]=y):y=e[15];let N;e[16]!==g||e[17]!==y?(N=(0,p.jsxs)("div",{className:"flex items-center justify-between gap-2 border-b border-border px-3 py-2",children:[g,y]}),e[16]=g,e[17]=y,e[18]=N):N=e[18];let v;e[19]!==d?(v=(0,p.jsx)("pre",{className:"overflow-auto px-3 pb-3 font-mono text-xs","data-testid":"api-sample-source",children:d}),e[19]=d,e[20]=v):v=e[20];let b;return e[21]!==N||e[22]!==v?(b=(0,p.jsxs)("div",{className:"flex flex-col gap-2 rounded-xl border border-border bg-card","data-testid":"api-code-samples",children:[N,v]}),e[21]=N,e[22]=v,e[23]=b):b=e[23],b},"_e"),Nt={blue:"text-info",emerald:"text-success",neutral:"text-muted-foreground",orange:"text-warning",red:"text-destructive",violet:"text-royal-amethyst"},kt=u(t=>{switch(t.toUpperCase()){case"DELETE":return"red";case"GET":return"emerald";case"PATCH":return"orange";case"POST":return"blue";case"PUT":return"orange";default:return"neutral"}},"Me"),wt=u(t=>{switch(t){case"action":return"violet";case"mutation":return"orange";case"query":return"emerald";default:return"neutral"}},"Je"),ge=u(t=>{let e=(0,K.c)(7),{kind:a,method:r,testId:n}=t,s;e[0]!==a||e[1]!==r?(s=a??r.toUpperCase(),e[0]=a,e[1]=r,e[2]=s):s=e[2];let o=s,i=a===void 0?kt(r):wt(a),d=`${Nt[i]} font-mono text-[10px] tracking-wide uppercase`,m;return e[3]!==o||e[4]!==d||e[5]!==n?(m=(0,p.jsx)(ve,{className:d,"data-testid":n,variant:"ghost",children:o}),e[3]=o,e[4]=d,e[5]=n,e[6]=m):m=e[6],m},"H"),Le=u(t=>t.startsWith("2")?"text-emerald-600 dark:text-emerald-400":t==="default"||t.startsWith("4")||t.startsWith("5")?"text-red-600 dark:text-red-400":"text-muted-foreground","te"),qe=u(t=>t.startsWith("2")?"bg-emerald-500":t==="default"||t.startsWith("4")||t.startsWith("5")?"bg-red-500":"bg-muted-foreground","re"),St=new Set([" ",`
13
+ `,"\r"]),Ee=" ",It=u(t=>{let e="";for(let n of t)St.has(n)||(e+=n);let a=0,r=e.length;for(;a<r&&(e[a]??"")<=Ee;)a+=1;for(;r>a&&(e[r-1]??"")<=Ee;)r-=1;return e.slice(a,r)},"Ke"),Ot=/^(?:[a-z][\d+.a-z-]*:)?\/\//i,$t=u((t,e)=>{let a=globalThis.location?.origin??"",r=e===""?a:e,n=It(t);if(r===""){if(Ot.test(n))throw new Error(`restDispatch: refusing to send the admin token off-origin (${n} names its own host and there is no origin to check it against)`);return n}let s=new URL(n,r);if(s.origin!==new URL(r).origin)throw new Error(`restDispatch: refusing to send the admin token off-origin (${s.origin} is not ${r})`);return s.toString()},"ze"),Pt=u(async(t,e,a,r)=>{let n=t.method!=="GET"&&t.method!=="HEAD",s=$t(t.httpPath,a),o=await(await fetch(s,{body:n?JSON.stringify(e):void 0,headers:{...n?{"content-type":"application/json"}:{},...r===null||r===""?{}:{authorization:`Bearer ${r}`}},method:t.method})).text();try{return JSON.parse(o)}catch{return o}},"We"),jt=u(t=>JSON.stringify(Z(t.argsSchema)??{},void 0,2),"qe"),Ke=(0,J.createContext)(null),ze=u(()=>{let t=(0,J.use)(Ke);if(t===null)throw new be("INTERNAL","useOperationRun must be used within an OperationRunProvider");return t},"ne"),_t=u(({children:t,operation:e})=>{let a=M(),r=F(),[n,s]=(0,J.useState)(()=>jt(e)),[o,i]=(0,J.useState)(""),[d,m]=(0,J.useState)("idle"),[l,c]=(0,J.useState)(void 0),[f,h]=(0,J.useState)(null),[g,x]=(0,J.useState)(null),y=u(async()=>{let N;try{N=n.trim()===""?{}:JSON.parse(n)}catch(b){m("error"),c(void 0),x(null),h(a("Invalid JSON args: {message}",{message:le(b)}));return}m("running"),h(null);let v=performance.now();try{let b=await(e.functionPath===void 0?Pt(e,N,r.url,r.getAuthToken()):Se(r,e.kind,se(e.functionPath),N,ie(o)));c(b),x(Math.round(performance.now()-v)),m("success")}catch(b){c(void 0),x(Math.round(performance.now()-v)),h(le(b)),m("error")}},"v");return(0,p.jsx)(Ke,{value:{argsText:n,durationMs:g,error:f,operation:e,response:l,send:u(()=>{Oe(y())},"send"),setArgsText:s,setShardKey:i,shardKey:o,status:d},children:t})},"He"),Tt=u(()=>{let t=(0,K.c)(48),e=M(),{argsText:a,operation:r,send:n,setArgsText:s,setShardKey:o,shardKey:i,status:d}=ze(),m;t[0]!==s?(m=u(_=>{s(_.target.value)},"d"),t[0]=s,t[1]=m):m=t[1];let l=m,c;t[2]!==n?(c=u(_=>{_.key==="Enter"&&(_.metaKey||_.ctrlKey)&&(_.preventDefault(),n())},"u"),t[2]=n,t[3]=c):c=t[3];let f=c,h=d==="running",g;t[4]!==r.kind||t[5]!==r.method?(g=(0,p.jsx)(ge,{kind:r.kind,method:r.method,testId:"api-try-method"}),t[4]=r.kind,t[5]=r.method,t[6]=g):g=t[6];let x=r.functionPath??r.httpPath,y;t[7]!==x?(y=(0,p.jsx)("code",{className:"min-w-0 flex-1 truncate font-mono text-xs text-foreground",children:x}),t[7]=x,t[8]=y):y=t[8];let N=h?"animate-pulse":void 0,v;t[9]!==N?(v=(0,p.jsx)(oe,{className:N,icon:we,strokeWidth:2}),t[9]=N,t[10]=v):v=t[10];let b;t[11]!==h||t[12]!==e?(b=e(h?"Sending\u2026":"Send"),t[11]=h,t[12]=e,t[13]=b):b=t[13];let I;t[14]!==h||t[15]!==n||t[16]!==v||t[17]!==b?(I=(0,p.jsxs)(B,{"data-testid":"api-try-send",disabled:h,onClick:n,size:"sm",type:"button",children:[v,b]}),t[14]=h,t[15]=n,t[16]=v,t[17]=b,t[18]=I):I=t[18];let P;t[19]!==g||t[20]!==y||t[21]!==I?(P=(0,p.jsxs)("div",{className:"flex items-center gap-2 border-b border-border bg-muted px-3 py-2",children:[g,y,I]}),t[19]=g,t[20]=y,t[21]=I,t[22]=P):P=t[22];let $;t[23]!==e?($=e("Arguments (JSON)"),t[23]=e,t[24]=$):$=t[24];let k;t[25]!==$?(k=(0,p.jsx)(he,{htmlFor:"api-try-args",children:$}),t[25]=$,t[26]=k):k=t[26];let w;t[27]!==a?(w=a.split(`
14
+ `),t[27]=a,t[28]=w):w=t[28];let j=Math.min(12,Math.max(3,w.length)),O;t[29]!==a||t[30]!==l||t[31]!==f||t[32]!==j?(O=(0,p.jsx)(je,{className:"font-mono text-xs","data-testid":"api-try-args",id:"api-try-args",onChange:l,onKeyDown:f,rows:j,spellCheck:!1,value:a}),t[29]=a,t[30]=l,t[31]=f,t[32]=j,t[33]=O):O=t[33];let S;t[34]!==k||t[35]!==O?(S=(0,p.jsxs)("div",{className:"flex flex-col gap-1.5",children:[k,O]}),t[34]=k,t[35]=O,t[36]=S):S=t[36];let T;t[37]!==r.functionPath||t[38]!==o||t[39]!==i||t[40]!==e?(T=r.functionPath!==void 0&&(0,p.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,p.jsx)(he,{htmlFor:"shard-input",children:e("Shard key (optional)")}),(0,p.jsx)(Pe,{id:"shard-input",onChange:o,testId:"shard-input",value:i})]}),t[37]=r.functionPath,t[38]=o,t[39]=i,t[40]=e,t[41]=T):T=t[41];let A;t[42]!==S||t[43]!==T?(A=(0,p.jsxs)("div",{className:"flex flex-col gap-3 p-3",children:[S,T]}),t[42]=S,t[43]=T,t[44]=A):A=t[44];let R;return t[45]!==A||t[46]!==P?(R=(0,p.jsxs)("div",{className:"overflow-hidden rounded-xl border border-border bg-card","data-testid":"api-try-it",children:[P,A]}),t[45]=A,t[46]=P,t[47]=R):R=t[47],R},"Ue"),Ct=u(t=>{let e=(0,K.c)(51),{operation:a}=t,r=M(),n=`api-operation-${a.operationId}`,s=a.key,o;e[0]!==a.kind||e[1]!==a.method?(o=(0,p.jsx)(ge,{kind:a.kind,method:a.method,testId:"api-operation-method"}),e[0]=a.kind,e[1]=a.method,e[2]=o):o=e[2];let i=a.functionPath??a.httpPath,d;e[3]!==i?(d=(0,p.jsx)("code",{className:"truncate font-mono text-xs text-muted-foreground",children:i}),e[3]=i,e[4]=d):d=e[4];let m;e[5]!==o||e[6]!==d?(m=(0,p.jsxs)("div",{className:"flex items-center gap-2",children:[o,d]}),e[5]=o,e[6]=d,e[7]=m):m=e[7];let l;e[8]!==a.title?(l=(0,p.jsx)("h1",{className:"text-lg font-semibold text-foreground","data-testid":"api-operation-title",children:a.title}),e[8]=a.title,e[9]=l):l=e[9];let c;e[10]!==a.description?(c=a.description!==void 0&&(0,p.jsx)("p",{className:"text-sm text-muted-foreground",children:a.description}),e[10]=a.description,e[11]=c):c=e[11];let f;e[12]!==m||e[13]!==l||e[14]!==c?(f=(0,p.jsxs)("header",{className:"sticky top-0 z-10 -mx-6 -mt-6 flex flex-col gap-2 border-b border-border bg-background px-6 pt-6 pb-3",children:[m,l,c]}),e[12]=m,e[13]=l,e[14]=c,e[15]=f):f=e[15];let h;e[16]!==r?(h=r("Try it"),e[16]=r,e[17]=h):h=e[17];let g;e[18]!==h?(g=(0,p.jsx)("h2",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:h}),e[18]=h,e[19]=g):g=e[19];let x;e[20]===Symbol.for("react.memo_cache_sentinel")?(x=(0,p.jsx)(Tt,{}),e[20]=x):x=e[20];let y;e[21]!==g?(y=(0,p.jsxs)("section",{className:"flex flex-col gap-2",children:[g,x]}),e[21]=g,e[22]=y):y=e[22];let N;e[23]!==r?(N=r("Request arguments"),e[23]=r,e[24]=N):N=e[24];let v;e[25]!==N?(v=(0,p.jsx)("h2",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:N}),e[25]=N,e[26]=v):v=e[26];let b;e[27]!==a.argsSchema?(b=(0,p.jsx)(Re,{schema:a.argsSchema,testId:"api-operation-args"}),e[27]=a.argsSchema,e[28]=b):b=e[28];let I;e[29]!==v||e[30]!==b?(I=(0,p.jsxs)("section",{className:"flex flex-col gap-2",children:[v,b]}),e[29]=v,e[30]=b,e[31]=I):I=e[31];let P;e[32]!==r?(P=r("Response body"),e[32]=r,e[33]=P):P=e[33];let $;e[34]!==P?($=(0,p.jsx)("h2",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:P}),e[34]=P,e[35]=$):$=e[35];let k;if(e[36]!==a.responses||e[37]!==r){let O;e[39]!==r?(O=u(S=>(0,p.jsxs)("div",{className:"flex flex-col gap-1.5 rounded-xl border border-border bg-card p-3",children:[(0,p.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,p.jsxs)("span",{className:`inline-flex items-center gap-1.5 font-mono text-xs font-semibold ${Le(S.status)}`,children:[(0,p.jsx)("span",{className:`size-1.5 rounded-full ${qe(S.status)}`}),S.status]}),S.schema!==void 0&&(0,p.jsx)("span",{className:"rounded border border-border px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground",children:r("application/json")})]}),S.description!==void 0&&(0,p.jsx)("p",{className:"text-xs text-muted-foreground",children:S.description}),S.schema!==void 0&&(0,p.jsx)(Re,{schema:S.schema,testId:`api-response-${S.status}`})]},S.status),"E"),e[39]=r,e[40]=O):O=e[40],k=a.responses.map(O),e[36]=a.responses,e[37]=r,e[38]=k}else k=e[38];let w;e[41]!==$||e[42]!==k?(w=(0,p.jsxs)("section",{className:"flex flex-col gap-3",children:[$,k]}),e[41]=$,e[42]=k,e[43]=w):w=e[43];let j;return e[44]!==a.key||e[45]!==n||e[46]!==y||e[47]!==I||e[48]!==w||e[49]!==f?(j=(0,p.jsxs)("div",{className:"flex flex-col gap-6 duration-200 animate-in fade-in-0 slide-in-from-bottom-1","data-testid":n,children:[f,y,I,w]},s),e[44]=a.key,e[45]=n,e[46]=y,e[47]=I,e[48]=w,e[49]=f,e[50]=j):j=e[50],j},"Ve"),At={boolean:"text-royal-amethyst",key:"text-sky-sapphire",number:"text-warning",plain:"",string:"text-success"},Rt=/"(?:[^"\\]|\\.)*"|\b(?:true|false|null)\b|-?\d+(?:\.\d+)?/g,Et=/^\s*:/,Jt=u((t,e,a)=>a.startsWith('"')?Et.test(t.slice(e))?"key":"string":a==="true"||a==="false"||a==="null"?"boolean":"number","Qe"),Mt=u(t=>{let e=[],a=0;for(let r of t.matchAll(Rt)){let{index:n}=r,s=r[0],o=n+s.length;n>a&&e.push({kind:"plain",start:a,text:t.slice(a,n)}),e.push({kind:Jt(t,o,s),start:n,text:s}),a=o}return a<t.length&&e.push({kind:"plain",start:a,text:t.slice(a)}),e},"Ze"),Lt=u(t=>{let e=(0,K.c)(4),{code:a}=t,r;e[0]!==a?(r=Mt(a).map(qt),e[0]=a,e[1]=r):r=e[1];let n;return e[2]!==r?(n=(0,p.jsx)(p.Fragment,{children:r}),e[2]=r,e[3]=n):n=e[3],n},"et");function qt(t){return(0,p.jsx)("span",{className:At[t.kind],children:t.text},t.start)}u(qt,"tt");var De="__live__",Kt=u(t=>t.schema===void 0?"":JSON.stringify(Z(t.schema),void 0,2),"rt"),zt=u((t,e,a)=>a?t??"":e===void 0?"":JSON.stringify(e,Ie,2),"st"),Dt=u(t=>{let e=(0,K.c)(18),{active:a,running:r,showError:n}=t,s=M();if(r){let c;e[0]!==s?(c=s("Sending\u2026"),e[0]=s,e[1]=c):c=e[1];let f;return e[2]!==c?(f=(0,p.jsx)("p",{className:"px-3 py-3 text-xs text-muted-foreground","data-testid":"api-response-running",children:c}),e[2]=c,e[3]=f):f=e[3],f}if(a===void 0||a.body===""){let c;e[4]!==a?.live||e[5]!==s?(c=a?.live===!0?s("Send a request to see the response."):s("No example for this response."),e[4]=a?.live,e[5]=s,e[6]=c):c=e[6];let f;return e[7]!==c?(f=(0,p.jsx)("p",{className:"px-3 py-3 text-xs text-muted-foreground","data-testid":"api-response-idle",children:c}),e[7]=c,e[8]=f):f=e[8],f}let o=n&&"text-destructive",i;e[9]!==o?(i=fe("max-h-[28rem] overflow-auto px-3 py-3 font-mono text-xs",o),e[9]=o,e[10]=i):i=e[10];let d=n?"api-response-error":"api-response-body",m;e[11]!==a.body||e[12]!==n?(m=n?a.body:(0,p.jsx)(Lt,{code:a.body}),e[11]=a.body,e[12]=n,e[13]=m):m=e[13];let l;return e[14]!==i||e[15]!==d||e[16]!==m?(l=(0,p.jsx)("pre",{className:i,"data-testid":d,children:m}),e[14]=i,e[15]=d,e[16]=m,e[17]=l):l=e[17],l},"nt"),Wt=u(({durationMs:t,error:e,failed:a,operation:r,ran:n,response:s,t:o})=>{let i=r.responses.map(d=>({body:Kt(d),durationMs:null,id:d.status,label:d.status,live:!1,status:d.status}));return n?[{body:zt(e,s,a),durationMs:t,id:De,label:o("Live"),live:!0,status:a?"error":"200"},...i]:i},"ot"),Bt=u(()=>{let t=(0,K.c)(19),e=M(),{durationMs:a,error:r,operation:n,response:s,status:o}=ze(),i=o==="running",d=o==="error",m=o==="success"||d,l=Wt({durationMs:a,error:r,failed:d,operation:n,ran:m,response:s,t:e}),c=m?De:l.find(Ut)?.id??l[0]?.id??"",[f,h]=(0,J.useState)(null),g=l.find(_=>_.id===(f??c))??l[0],x;t[0]===Symbol.for("react.memo_cache_sentinel")?(x=u(_=>{let{id:L}=_.currentTarget.dataset;L!==void 0&&h(L)},"m"),t[0]=x):x=t[0];let y=x,N=u(()=>{g!==void 0&&ae(g.body)},"k"),v=g?.live===!0?g.durationMs:null,b=g?.live===!0&&g.status==="error",I="flex min-h-0 flex-col rounded-xl border border-border bg-card",P="api-response-panel",$;t[1]!==e?($=e("Response"),t[1]=e,t[2]=$):$=t[2];let k;t[3]!==$?(k=(0,p.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:$}),t[3]=$,t[4]=k):k=t[4];let w=v!==null&&(0,p.jsx)("span",{className:"font-mono text-[10px] text-muted-foreground",children:e("{ms} ms",{ms:v})}),j=g!==void 0&&g.body!==""&&(0,p.jsx)(B,{"aria-label":e("Copy"),"data-testid":"api-response-copy",onClick:N,size:"icon-xs",type:"button",variant:"ghost",children:(0,p.jsx)(oe,{icon:Ne,strokeWidth:2})}),O;t[5]!==w||t[6]!==j?(O=(0,p.jsxs)("div",{className:"flex items-center gap-2",children:[w,j]}),t[5]=w,t[6]=j,t[7]=O):O=t[7];let S;t[8]!==k||t[9]!==O?(S=(0,p.jsxs)("div",{className:"flex items-center justify-between gap-2 border-b border-border px-3 py-2",children:[k,O]}),t[8]=k,t[9]=O,t[10]=S):S=t[10];let T=l.length>0&&(0,p.jsx)("div",{className:"flex gap-1 overflow-x-auto border-b border-border px-2 py-1.5",role:"tablist",children:l.map(_=>{let L=_.id===g?.id;return(0,p.jsxs)("button",{"aria-selected":L,className:fe("inline-flex items-center gap-1.5 rounded px-2 py-0.5 font-mono text-xs transition-colors hover:text-foreground aria-selected:bg-muted aria-selected:font-medium",L?Le(_.status):"text-muted-foreground"),"data-id":_.id,"data-testid":_.live?"api-response-tab-live":`api-response-tab-${_.status}`,onClick:y,role:"tab",type:"button",children:[(0,p.jsx)("span",{className:`size-1.5 rounded-full ${qe(_.status)}`}),_.label]},_.id)})}),A;t[11]!==g||t[12]!==i||t[13]!==b?(A=(0,p.jsx)(Dt,{active:g,running:i,showError:b}),t[11]=g,t[12]=i,t[13]=b,t[14]=A):A=t[14];let R;return t[15]!==A||t[16]!==S||t[17]!==T?(R=(0,p.jsxs)("div",{className:I,"data-testid":P,children:[S,T,A]}),t[15]=A,t[16]=S,t[17]=T,t[18]=R):R=t[18],R},"it");function Ut(t){return t.status.startsWith("2")}u(Ut,"at");var Ft=u((t,e)=>{let a=e.trim().toLowerCase();return a===""?t:t.map(r=>({...r,operations:r.operations.filter(n=>`${n.summary} ${n.operationId}`.toLowerCase().includes(a))})).filter(r=>r.operations.length>0)},"lt"),me=u(t=>{let e=(0,K.c)(53),{model:a}=t,r=M(),n=a.groups[0]?.operations[0]?.key??"",[s,o]=(0,J.useState)(n),[i,d]=(0,J.useState)(""),m;e[0]!==n||e[1]!==a.operationByKey||e[2]!==s?(m=a.operationByKey.get(s)??a.operationByKey.get(n),e[0]=n,e[1]=a.operationByKey,e[2]=s,e[3]=m):m=e[3];let l=m,c,f,h,g,x,y,N,v,b,I;if(e[4]!==i||e[5]!==a.groups||e[6]!==a.server||e[7]!==l?.key||e[8]!==r){c=Ft(a.groups,i);let O;e[19]===Symbol.for("react.memo_cache_sentinel")?(O=u(E=>{let{key:W}=E.currentTarget.dataset;W!==void 0&&o(W)},"E"),e[19]=O):O=e[19];let S=O,T;e[20]===Symbol.for("react.memo_cache_sentinel")?(T=u(E=>{d(E.target.value)},"R"),e[20]=T):T=e[20];let A=T;f=a.server??"",b="grid min-h-0 flex-1 grid-cols-1 overflow-hidden lg:grid-cols-[16rem_minmax(0,1fr)_22rem]",I="api-reference",e[21]!==r?(x=r("API operations"),e[21]=r,e[22]=x):x=e[22],y="flex min-h-0 flex-col overflow-y-auto border-r border-border",N="api-reference-nav";let R;e[23]===Symbol.for("react.memo_cache_sentinel")?(R=(0,p.jsx)(oe,{className:"pointer-events-none absolute top-1/2 left-2 size-3.5 -translate-y-1/2 text-muted-foreground",icon:ke,strokeWidth:2}),e[23]=R):R=e[23];let _;e[24]!==r?(_=r("Filter operations"),e[24]=r,e[25]=_):_=e[25],e[26]!==i||e[27]!==_?(v=(0,p.jsx)("div",{className:"sticky top-0 z-10 border-b border-border bg-sidebar p-2",children:(0,p.jsxs)("div",{className:"relative",children:[R,(0,p.jsx)(ye,{className:"h-7 pl-7","data-testid":"api-filter",onChange:A,placeholder:_,value:i})]})}),e[26]=i,e[27]=_,e[28]=v):v=e[28],h="flex flex-col gap-4 p-2";let L;e[29]!==l?.key||e[30]!==r?(L=u(E=>(0,p.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,p.jsxs)("div",{className:"flex items-center justify-between px-2",children:[(0,p.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:E.name||r("(root)")}),(0,p.jsx)("span",{className:"font-mono text-[10px] text-muted-foreground/70",children:E.operations.length})]}),E.operations.map(W=>{let Q=W.key===l?.key;return(0,p.jsxs)("button",{"aria-current":Q?"page":void 0,className:"flex items-center justify-between gap-2 rounded-md border-l-2 border-transparent px-2 py-1 text-start text-xs text-muted-foreground transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground aria-[current=page]:border-primary aria-[current=page]:bg-sidebar-accent aria-[current=page]:font-medium aria-[current=page]:text-foreground","data-key":W.key,"data-testid":`api-nav-${W.operationId}`,onClick:S,type:"button",children:[(0,p.jsx)("span",{className:"truncate",children:W.summary}),(0,p.jsx)(ge,{kind:W.kind,method:W.method})]},W.key)})]},E.name),"_"),e[29]=l?.key,e[30]=r,e[31]=L):L=e[31],g=c.map(L),e[4]=i,e[5]=a.groups,e[6]=a.server,e[7]=l?.key,e[8]=r,e[9]=c,e[10]=f,e[11]=h,e[12]=g,e[13]=x,e[14]=y,e[15]=N,e[16]=v,e[17]=b,e[18]=I}else c=e[9],f=e[10],h=e[11],g=e[12],x=e[13],y=e[14],N=e[15],v=e[16],b=e[17],I=e[18];let P;e[32]!==c.length||e[33]!==r?(P=c.length===0&&(0,p.jsx)("p",{className:"px-2 py-1 text-xs text-muted-foreground","data-testid":"api-nav-empty",children:r("No operations match your filter.")}),e[32]=c.length,e[33]=r,e[34]=P):P=e[34];let $;e[35]!==P||e[36]!==h||e[37]!==g?($=(0,p.jsxs)("div",{className:h,children:[g,P]}),e[35]=P,e[36]=h,e[37]=g,e[38]=$):$=e[38];let k;e[39]!==$||e[40]!==x||e[41]!==y||e[42]!==N||e[43]!==v?(k=(0,p.jsxs)("nav",{"aria-label":x,className:y,"data-testid":N,children:[v,$]}),e[39]=$,e[40]=x,e[41]=y,e[42]=N,e[43]=v,e[44]=k):k=e[44];let w;e[45]!==l||e[46]!==f?(w=l===void 0?(0,p.jsx)("div",{className:"lg:col-span-2"}):(0,p.jsxs)(_t,{operation:l,children:[(0,p.jsx)("div",{className:"min-w-0 overflow-y-auto p-6","data-testid":"api-reference-main",children:(0,p.jsx)(Ct,{operation:l})}),(0,p.jsxs)("aside",{className:"flex min-w-0 flex-col gap-4 overflow-y-auto border-border p-4 lg:border-l","data-testid":"api-reference-aside",children:[(0,p.jsx)(yt,{operation:l,server:f}),(0,p.jsx)(Bt,{})]})]},l.key),e[45]=l,e[46]=f,e[47]=w):w=e[47];let j;return e[48]!==k||e[49]!==w||e[50]!==b||e[51]!==I?(j=(0,p.jsxs)("div",{className:b,"data-testid":I,children:[k,w]}),e[48]=k,e[49]=w,e[50]=b,e[51]=I,e[52]=j):j=e[52],j},"$t");var H=z(re(),1);var Ht=["get","post","put","patch","delete","head","options","trace"],Be=u(t=>t?.content?.["application/json"]?.schema,"y"),Gt=u((t,e)=>Object.entries(t.responses??{}).map(([a,r])=>{let n=r.$ref?.replace("#/components/responses/",""),s=n===void 0?r:e.components?.responses?.[n]??r;return{description:s.description,schema:Be(s),status:a}}),"j"),Qt=u((t,e,a,r,n)=>{let s=Be(r.requestBody),o=s?.properties?.functionPath?.const,i=typeof o=="string"?o:void 0,d=i===void 0?s:s?.properties?.args,m=r.operationId??`${a} ${e}`;return{argsSchema:d,description:r.description,functionPath:i,httpPath:e,key:t,kind:r["x-lunora-function-kind"],method:a.toUpperCase(),operationId:m,requestSchema:s,responses:Gt(r,n),summary:r.summary??m,tags:r.tags??[],title:r.summary??m}},"b"),Vt=u(t=>{let e=[];for(let[a,r]of Object.entries(t.paths??{})){let n=a.includes("#")?a.slice(0,a.indexOf("#")):a;for(let s of Ht){let o=r[s];o!==void 0&&e.push(Qt(a,n,s,o,t))}}return e},"x"),Xt=u(t=>{let e=t??{},a=Vt(e),r=new Map((e.tags??[]).map(i=>[i.name,i.description])),n=new Set,s=[],o=u(i=>{if(n.has(i))return;n.add(i);let d=a.filter(m=>(m.tags[0]??"")===i);d.length>0&&s.push({description:r.get(i),name:i,operations:d})},"l");for(let i of e.tags??[])o(i.name);for(let i of a)o(i.tags[0]??"");return{groups:s,operationByKey:new Map(a.map(i=>[i.key,i])),server:e.servers?.[0]?.url,title:e.info?.title??"API reference",version:e.info?.version}},"w"),Yt=u(t=>{let{paths:e}=t;return e===void 0||typeof e=="object"&&e!==null&&Object.keys(e).length===0},"R"),Zt=u(t=>{let e=t;return Yt(e)?{kind:"empty"}:{kind:"ready",spec:e}},"T"),Ue=u(t=>{let e=(0,We.c)(23),{spec:a}=t,r=M(),n=F(),s;e[0]!==n?(s=u(()=>n.fetchOpenApi(),"n"),e[0]=n,e[1]=s):s=e[1];let o=pe(a,s,Zt),i;e[2]!==o.kind||e[3]!==o.spec?(i=o.kind==="ready"?Xt(o.spec):void 0,e[2]=o.kind,e[3]=o.spec,e[4]=i):i=e[4];let d=i;if(o.kind==="loading"){let l;return e[5]===Symbol.for("react.memo_cache_sentinel")?(l=(0,H.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"api-reference-loading",children:[(0,H.jsx)(V,{className:"h-8 w-48"}),(0,H.jsx)(V,{className:"h-64 w-full"})]}),e[5]=l):l=e[5],l}if(o.kind==="error"){let l;e[6]!==o.message||e[7]!==r?(l=r("Couldn't load the OpenAPI spec: {message}",{message:o.message}),e[6]=o.message,e[7]=r,e[8]=l):l=e[8];let c;e[9]!==r?(c=r("API reference unavailable"),e[9]=r,e[10]=c):c=e[10];let f;return e[11]!==l||e[12]!==c?(f=(0,H.jsx)(U,{description:l,testId:"api-reference-error",title:c}),e[11]=l,e[12]=c,e[13]=f):f=e[13],f}if(o.kind==="empty"||d===void 0){let l;e[14]!==r?(l=r("Run `lunora codegen` and wire `_generated/openapi.json` to the worker to render the API reference here."),e[14]=r,e[15]=l):l=e[15];let c;e[16]!==r?(c=r("No OpenAPI spec configured"),e[16]=r,e[17]=c):c=e[17];let f;return e[18]!==l||e[19]!==c?(f=(0,H.jsx)(U,{description:l,testId:"api-reference-empty",title:c}),e[18]=l,e[19]=c,e[20]=f):f=e[20],f}let m;return e[21]!==d?(m=(0,H.jsx)(me,{model:d}),e[21]=d,e[22]=m):m=e[22],m},"B");var Fe=z(te(),1);var G=z(re(),1);var er=u(t=>(t.params??[]).find(e=>e.name==="args")??(t.params??[])[0],"x"),tr=u(t=>t["x-tags"]?.[0]?.name??(t.name.includes(":")?t.name.slice(0,t.name.indexOf(":")):""),"v"),rr=u(t=>{let e=er(t)?.schema;return{argsSchema:e,description:t.description,functionPath:t.name,httpPath:"/_lunora/rpc",key:t.name,kind:t["x-lunora-function-kind"],method:"POST",operationId:t.name,requestSchema:e,responses:[{description:t.result?.name,schema:t.result?.schema,status:"200"}],summary:t.summary??t.name,tags:[tr(t)],title:t.summary??t.name}},"w"),ar=u(t=>{let e=t??{},a=(e.methods??[]).map(n=>rr(n)),r=new Map;for(let n of a){let s=n.tags[0]??"",o=r.get(s)??[];o.push(n),r.set(s,o)}return{groups:[...r.entries()].map(([n,s])=>({name:n,operations:s.toSorted((o,i)=>o.operationId.localeCompare(i.operationId))})).toSorted((n,s)=>n.name.localeCompare(s.name)),operationByKey:new Map(a.map(n=>[n.key,n])),title:e.info?.title??"API reference",version:e.info?.version}},"I"),nr=u(t=>t.methods===void 0||t.methods.length===0,"C"),or=u(t=>{let e=t;return nr(e)?{kind:"empty"}:{kind:"ready",spec:e}},"N"),He=u(t=>{let e=(0,Fe.c)(23),{spec:a}=t,r=M(),n=F(),s;e[0]!==n?(s=u(()=>n.fetchOpenRpc(),"a"),e[0]=n,e[1]=s):s=e[1];let o=pe(a,s,or),i;e[2]!==o.kind||e[3]!==o.spec?(i=o.kind==="ready"?ar(o.spec):void 0,e[2]=o.kind,e[3]=o.spec,e[4]=i):i=e[4];let d=i;if(o.kind==="loading"){let l;return e[5]===Symbol.for("react.memo_cache_sentinel")?(l=(0,G.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"openrpc-reference-loading",children:[(0,G.jsx)(V,{className:"h-8 w-48"}),(0,G.jsx)(V,{className:"h-64 w-full"})]}),e[5]=l):l=e[5],l}if(o.kind==="error"){let l;e[6]!==o.message||e[7]!==r?(l=r("Couldn't load the OpenRPC spec: {message}",{message:o.message}),e[6]=o.message,e[7]=r,e[8]=l):l=e[8];let c;e[9]!==r?(c=r("API reference unavailable"),e[9]=r,e[10]=c):c=e[10];let f;return e[11]!==l||e[12]!==c?(f=(0,G.jsx)(U,{description:l,testId:"openrpc-reference-error",title:c}),e[11]=l,e[12]=c,e[13]=f):f=e[13],f}if(o.kind==="empty"||d===void 0){let l;e[14]!==r?(l=r("Run `lunora codegen --api-spec openrpc` and wire `_generated/openrpc.json` to the worker to render the OpenRPC reference here."),e[14]=r,e[15]=l):l=e[15];let c;e[16]!==r?(c=r("No OpenRPC spec configured"),e[16]=r,e[17]=c):c=e[17];let f;return e[18]!==l||e[19]!==c?(f=(0,G.jsx)(U,{description:l,testId:"openrpc-reference-empty",title:c}),e[18]=l,e[19]=c,e[20]=f):f=e[20],f}let m;return e[21]!==d?(m=(0,G.jsx)(me,{model:d}),e[21]=d,e[22]=m):m=e[22],m},"T");var D=z(re(),1);var sr=["reference","snippets"],ir=["openapi","openrpc"],Vr=u(t=>{let e=(0,Ge.c)(51),{functions:a,initialShardKey:r,openApiSpec:n,openRpcSpec:s}=t,o=M(),[i,d]=(0,xe.useState)("reference"),[m,l]=(0,xe.useState)("openapi"),c;e[0]!==o?(c=o("Reference"),e[0]=o,e[1]=c):c=e[1];let f;e[2]!==o?(f=o("Snippets"),e[2]=o,e[3]=f):f=e[3];let h;e[4]!==c||e[5]!==f?(h={reference:c,snippets:f},e[4]=c,e[5]=f,e[6]=h):h=e[6];let g=h,x;e[7]!==o?(x=o("OpenAPI"),e[7]=o,e[8]=x):x=e[8];let y;e[9]!==o?(y=o("OpenRPC"),e[9]=o,e[10]=y):y=e[10];let N;e[11]!==x||e[12]!==y?(N={openapi:x,openrpc:y},e[11]=x,e[12]=y,e[13]=N):N=e[13];let v=N,b;e[14]===Symbol.for("react.memo_cache_sentinel")?(b=u(E=>{d(E.currentTarget.dataset.view)},"S"),e[14]=b):b=e[14];let I=b,P;e[15]===Symbol.for("react.memo_cache_sentinel")?(P=u(E=>{l(E.currentTarget.dataset.format)},"A"),e[15]=P):P=e[15];let $=P,k;e[16]!==o?(k=o("API view"),e[16]=o,e[17]=k):k=e[17];let w;e[18]!==i||e[19]!==g?(w=sr.map(E=>(0,D.jsx)(B,{"aria-selected":i===E,"data-testid":`api-view-${E}`,"data-view":E,onClick:I,role:"tab",size:"sm",type:"button",variant:i===E?"default":"outline",children:g[E]},E)),e[18]=i,e[19]=g,e[20]=w):w=e[20];let j;e[21]!==w||e[22]!==k?(j=(0,D.jsx)("div",{"aria-label":k,className:"flex gap-1.5","data-testid":"api-view-toggle",role:"tablist",children:w}),e[21]=w,e[22]=k,e[23]=j):j=e[23];let O;e[24]!==m||e[25]!==v||e[26]!==o||e[27]!==i?(O=i==="reference"&&(0,D.jsx)("div",{"aria-label":o("API spec format"),className:"flex gap-1.5","data-testid":"api-format-toggle",role:"tablist",children:ir.map(E=>(0,D.jsx)(B,{"aria-selected":m===E,"data-format":E,"data-testid":`api-format-${E}`,onClick:$,role:"tab",size:"sm",type:"button",variant:m===E?"default":"outline",children:v[E]},E))}),e[24]=m,e[25]=v,e[26]=o,e[27]=i,e[28]=O):O=e[28];let S;e[29]!==j||e[30]!==O?(S=(0,D.jsxs)("div",{className:"flex shrink-0 flex-wrap items-center gap-3 border-b border-border px-6 py-3",children:[j,O]}),e[29]=j,e[30]=O,e[31]=S):S=e[31];let T;e[32]!==a||e[33]!==r||e[34]!==i?(T=i==="snippets"&&(0,D.jsx)("div",{className:"min-h-0 flex-1 overflow-y-auto p-6",children:(0,D.jsx)(Ae,{functions:a,initialShardKey:r})}),e[32]=a,e[33]=r,e[34]=i,e[35]=T):T=e[35];let A;e[36]!==m||e[37]!==n||e[38]!==i?(A=i==="reference"&&m==="openapi"&&(0,D.jsx)(Ue,{spec:n}),e[36]=m,e[37]=n,e[38]=i,e[39]=A):A=e[39];let R;e[40]!==m||e[41]!==s||e[42]!==i?(R=i==="reference"&&m==="openrpc"&&(0,D.jsx)(He,{spec:s}),e[40]=m,e[41]=s,e[42]=i,e[43]=R):R=e[43];let _;e[44]!==T||e[45]!==A||e[46]!==R?(_=(0,D.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:[T,A,R]}),e[44]=T,e[45]=A,e[46]=R,e[47]=_):_=e[47];let L;return e[48]!==S||e[49]!==_?(L=(0,D.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col","data-testid":"lunora-api-tab",children:[S,_]}),e[48]=S,e[49]=_,e[50]=L):L=e[50],L},"k");export{Vr as default};
@@ -1 +1 @@
1
- import{a as H}from"./chunk-66UGPQVC.js";import{b as x}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{b as z}from"./chunk-B7ITCEGD.js";import{f as O}from"./chunk-KIOIUXMK.js";import"./chunk-FSRSK4LY.js";import"./chunk-UJNMJTDN.js";import{a as _}from"./chunk-FKVZRPV5.js";import{a as q,b as B,c as E,d as S,e as i,f as s}from"./chunk-HEAQVSNS.js";import{a as A,e as L}from"./chunk-WUWBZPUK.js";import{d as W}from"./chunk-FODLDLE2.js";import{a as R,d as M,f as $,g as D}from"./chunk-YKXDMIHQ.js";var I=M($(),1);var n=M(D(),1);var F=2e3,G=new Set(["open"]),ie=R(Q=>{let e=(0,I.c)(41),{read:y}=Q,t=W(),j=O(),v;e[0]!==j||e[1]!==y?(v=R(()=>Promise.resolve(y?y():j.debug()),"T"),e[0]=j,e[1]=y,e[2]=v):v=e[2];let V=v,K=y?"injected":"live",b;e[3]!==K?(b=["lunora-studio","sync-client-debug",K],e[3]=K,e[4]=b):b=e[4];let{data:c,refetch:Y}=z(b,V);if(H(Y,!0,F),!c){let r;e[5]!==t?(r=t("Reading the sync client's state\u2026"),e[5]=t,e[6]=r):r=e[6];let g;e[7]!==t?(g=t("Sync client"),e[7]=t,e[8]=g):g=e[8];let T;return e[9]!==r||e[10]!==g?(T=(0,n.jsx)(A,{children:(0,n.jsx)(L,{children:(0,n.jsx)(_,{description:r,title:g})})}),e[9]=r,e[10]=g,e[11]=T):T=e[11],T}let{pendingWrites:k,shards:N,subscriptions:w}=c,a;e[12]!==t?(a=t("This Studio session's sync client"),e[12]=t,e[13]=a):a=e[13];let l;e[14]!==a?(l=(0,n.jsx)("span",{className:"text-sm font-medium",children:a}),e[14]=a,e[15]=l):l=e[15];let P=c.connectionStatus==="connected"?"default":"secondary",o;e[16]!==c.connectionStatus||e[17]!==P?(o=(0,n.jsx)(x,{variant:P,children:c.connectionStatus}),e[16]=c.connectionStatus,e[17]=P,e[18]=o):o=e[18];let d;e[19]!==k||e[20]!==t?(d=k>0?(0,n.jsx)(x,{variant:"secondary",children:t("{count} pending writes",{count:k})}):null,e[19]=k,e[20]=t,e[21]=d):d=e[21];let h;e[22]!==l||e[23]!==o||e[24]!==d?(h=(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[l,o,d]}),e[22]=l,e[23]=o,e[24]=d,e[25]=h):h=e[25];let u;e[26]!==t?(u=t("Reads client.debug() for the client running in this page \u2014 not your application's client. Call client.debug() in your app to diagnose a specific stuck overlay there."),e[26]=t,e[27]=u):u=e[27];let m;e[28]!==u?(m=(0,n.jsx)("p",{className:"text-muted-foreground text-xs",children:u}),e[28]=u,e[29]=m):m=e[29];let p;e[30]!==N||e[31]!==t?(p=N.length===0?(0,n.jsx)(_,{description:t("No shard connection has been opened yet."),title:t("No shards")}):(0,n.jsxs)(q,{children:[(0,n.jsx)(B,{children:(0,n.jsxs)(S,{children:[(0,n.jsx)(i,{children:t("Shard")}),(0,n.jsx)(i,{children:t("Socket")}),(0,n.jsx)(i,{children:t("Confirmed watermark")})]})}),(0,n.jsx)(E,{children:N.map(r=>(0,n.jsxs)(S,{children:[(0,n.jsx)(s,{children:r.shardKey??t("(default)")}),(0,n.jsx)(s,{children:(0,n.jsx)(x,{variant:G.has(r.wsState)?"default":"secondary",children:r.wsState})}),(0,n.jsx)(s,{children:r.confirmedMutationWatermark})]},r.shardKey??"__default__"))})]}),e[30]=N,e[31]=t,e[32]=p):p=e[32];let f;e[33]!==w||e[34]!==t?(f=w.length===0?(0,n.jsx)(_,{description:t("This client holds no live queries or shapes."),title:t("No subscriptions")}):(0,n.jsxs)(q,{children:[(0,n.jsx)(B,{children:(0,n.jsxs)(S,{children:[(0,n.jsx)(i,{children:t("Subscription")}),(0,n.jsx)(i,{children:t("Kind")}),(0,n.jsx)(i,{children:t("Acked")}),(0,n.jsx)(i,{children:t("Cursor")}),(0,n.jsx)(i,{children:t("Pending overlays")})]})}),(0,n.jsx)(E,{children:w.map(r=>(0,n.jsxs)(S,{children:[(0,n.jsx)(s,{className:"font-mono text-xs",children:r.functionPath}),(0,n.jsx)(s,{children:r.kind}),(0,n.jsx)(s,{children:(0,n.jsx)(x,{variant:r.acked?"default":"secondary",children:r.acked?t("yes"):t("no")})}),(0,n.jsx)(s,{children:r.serverCursor??"\u2014"}),(0,n.jsx)(s,{children:r.pendingOptimisticLayers})]},r.id))})]}),e[33]=w,e[34]=t,e[35]=f):f=e[35];let C;return e[36]!==m||e[37]!==p||e[38]!==f||e[39]!==h?(C=(0,n.jsx)(A,{children:(0,n.jsxs)(L,{className:"flex flex-col gap-4",children:[h,m,p,f]})}),e[36]=m,e[37]=p,e[38]=f,e[39]=h,e[40]=C):C=e[40],C},"ie");export{ie as default};
1
+ import{a as H}from"./chunk-66UGPQVC.js";import{b as x}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{b as z}from"./chunk-AH6MS5JC.js";import{f as O}from"./chunk-OHOQXJGW.js";import"./chunk-FSRSK4LY.js";import"./chunk-5ICUJ4IA.js";import{a as _}from"./chunk-FKVZRPV5.js";import{a as q,b as B,c as E,d as S,e as i,f as s}from"./chunk-HEAQVSNS.js";import{a as A,e as L}from"./chunk-WUWBZPUK.js";import{d as W}from"./chunk-6B7FVPW3.js";import{a as R,d as M,f as $,g as D}from"./chunk-YKXDMIHQ.js";var I=M($(),1);var n=M(D(),1);var F=2e3,G=new Set(["open"]),ie=R(Q=>{let e=(0,I.c)(41),{read:y}=Q,t=W(),j=O(),v;e[0]!==j||e[1]!==y?(v=R(()=>Promise.resolve(y?y():j.debug()),"T"),e[0]=j,e[1]=y,e[2]=v):v=e[2];let V=v,K=y?"injected":"live",b;e[3]!==K?(b=["lunora-studio","sync-client-debug",K],e[3]=K,e[4]=b):b=e[4];let{data:c,refetch:Y}=z(b,V);if(H(Y,!0,F),!c){let r;e[5]!==t?(r=t("Reading the sync client's state\u2026"),e[5]=t,e[6]=r):r=e[6];let g;e[7]!==t?(g=t("Sync client"),e[7]=t,e[8]=g):g=e[8];let T;return e[9]!==r||e[10]!==g?(T=(0,n.jsx)(A,{children:(0,n.jsx)(L,{children:(0,n.jsx)(_,{description:r,title:g})})}),e[9]=r,e[10]=g,e[11]=T):T=e[11],T}let{pendingWrites:k,shards:N,subscriptions:w}=c,a;e[12]!==t?(a=t("This Studio session's sync client"),e[12]=t,e[13]=a):a=e[13];let l;e[14]!==a?(l=(0,n.jsx)("span",{className:"text-sm font-medium",children:a}),e[14]=a,e[15]=l):l=e[15];let P=c.connectionStatus==="connected"?"default":"secondary",o;e[16]!==c.connectionStatus||e[17]!==P?(o=(0,n.jsx)(x,{variant:P,children:c.connectionStatus}),e[16]=c.connectionStatus,e[17]=P,e[18]=o):o=e[18];let d;e[19]!==k||e[20]!==t?(d=k>0?(0,n.jsx)(x,{variant:"secondary",children:t("{count} pending writes",{count:k})}):null,e[19]=k,e[20]=t,e[21]=d):d=e[21];let h;e[22]!==l||e[23]!==o||e[24]!==d?(h=(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[l,o,d]}),e[22]=l,e[23]=o,e[24]=d,e[25]=h):h=e[25];let u;e[26]!==t?(u=t("Reads client.debug() for the client running in this page \u2014 not your application's client. Call client.debug() in your app to diagnose a specific stuck overlay there."),e[26]=t,e[27]=u):u=e[27];let m;e[28]!==u?(m=(0,n.jsx)("p",{className:"text-muted-foreground text-xs",children:u}),e[28]=u,e[29]=m):m=e[29];let p;e[30]!==N||e[31]!==t?(p=N.length===0?(0,n.jsx)(_,{description:t("No shard connection has been opened yet."),title:t("No shards")}):(0,n.jsxs)(q,{children:[(0,n.jsx)(B,{children:(0,n.jsxs)(S,{children:[(0,n.jsx)(i,{children:t("Shard")}),(0,n.jsx)(i,{children:t("Socket")}),(0,n.jsx)(i,{children:t("Confirmed watermark")})]})}),(0,n.jsx)(E,{children:N.map(r=>(0,n.jsxs)(S,{children:[(0,n.jsx)(s,{children:r.shardKey??t("(default)")}),(0,n.jsx)(s,{children:(0,n.jsx)(x,{variant:G.has(r.wsState)?"default":"secondary",children:r.wsState})}),(0,n.jsx)(s,{children:r.confirmedMutationWatermark})]},r.shardKey??"__default__"))})]}),e[30]=N,e[31]=t,e[32]=p):p=e[32];let f;e[33]!==w||e[34]!==t?(f=w.length===0?(0,n.jsx)(_,{description:t("This client holds no live queries or shapes."),title:t("No subscriptions")}):(0,n.jsxs)(q,{children:[(0,n.jsx)(B,{children:(0,n.jsxs)(S,{children:[(0,n.jsx)(i,{children:t("Subscription")}),(0,n.jsx)(i,{children:t("Kind")}),(0,n.jsx)(i,{children:t("Acked")}),(0,n.jsx)(i,{children:t("Cursor")}),(0,n.jsx)(i,{children:t("Pending overlays")})]})}),(0,n.jsx)(E,{children:w.map(r=>(0,n.jsxs)(S,{children:[(0,n.jsx)(s,{className:"font-mono text-xs",children:r.functionPath}),(0,n.jsx)(s,{children:r.kind}),(0,n.jsx)(s,{children:(0,n.jsx)(x,{variant:r.acked?"default":"secondary",children:r.acked?t("yes"):t("no")})}),(0,n.jsx)(s,{children:r.serverCursor??"\u2014"}),(0,n.jsx)(s,{children:r.pendingOptimisticLayers})]},r.id))})]}),e[33]=w,e[34]=t,e[35]=f):f=e[35];let C;return e[36]!==m||e[37]!==p||e[38]!==f||e[39]!==h?(C=(0,n.jsx)(A,{children:(0,n.jsxs)(L,{className:"flex flex-col gap-4",children:[h,m,p,f]})}),e[36]=m,e[37]=p,e[38]=f,e[39]=h,e[40]=C):C=e[40],C},"ie");export{ie as default};
@@ -1 +1 @@
1
- import{b as y}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{a as R}from"./chunk-PTZF5Z2E.js";import"./chunk-ULIQFBZU.js";import"./chunk-BSAK46ON.js";import"./chunk-35DM4JJG.js";import{a as v}from"./chunk-4ZEL6BYL.js";import{c as $}from"./chunk-B7ITCEGD.js";import"./chunk-KIOIUXMK.js";import"./chunk-FSRSK4LY.js";import"./chunk-UJNMJTDN.js";import{a as S}from"./chunk-FKVZRPV5.js";import{a as A,b as C,c as I,d as x,e as c,f as n}from"./chunk-HEAQVSNS.js";import{a as k,e as w}from"./chunk-WUWBZPUK.js";import{d as N}from"./chunk-FODLDLE2.js";import{a as f,d as b,f as E,g as O}from"./chunk-YKXDMIHQ.js";var j=b(E(),1);var r=b(O(),1);var _=f((e,t)=>({delete:e("Delete"),list:e("List"),read:e("Read"),write:e("Write")})[t],"I"),T={delete:2,list:3,read:0,write:1},B=f(e=>[...e].toSorted((t,a)=>t.bucket.localeCompare(a.bucket)||T[t.on]-T[a.on]||(t.prefix??"").localeCompare(a.prefix??"")),"O"),q=f(()=>{let e=(0,j.c)(14),t=N(),a;e[0]===Symbol.for("react.memo_cache_sentinel")?(a={},e[0]=a):a=e[0];let{data:l,error:i,errorSource:d}=$(v.storageRules,a),h=l!==void 0,m;if(e[1]!==l||e[2]!==i||e[3]!==d||e[4]!==h||e[5]!==t){let g=B(Array.isArray(l?.rules)?l.rules:[]),u;e[7]!==i||e[8]!==d?(u=i!==null&&(0,r.jsx)(R,{error:d,testId:"storage-rules-error"}),e[7]=i,e[8]=d,e[9]=u):u=e[9];let o;e[10]!==t?(o=t("Storage rules are declared in code with defineStorageRule and gate ctx.storage access per bucket. This view is read-only."),e[10]=t,e[11]=o):o=e[11];let p;e[12]!==o?(p=(0,r.jsx)("p",{className:"text-sm text-muted-foreground","data-testid":"storage-rules-note",children:o}),e[12]=o,e[13]=p):p=e[13],m=(0,r.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-storage-rules-panel",children:[u,p,h&&g.length===0?(0,r.jsx)(S,{description:t("No defineStorageRule is wired through .use(storageRules(...)) in this deployment. Add one to gate object access by key prefix."),testId:"storage-rules-empty",title:t("No storage rules defined")}):(0,r.jsx)(k,{className:"overflow-hidden py-0",children:(0,r.jsx)(w,{className:"px-0",children:(0,r.jsxs)(A,{"data-testid":"storage-rules-table",children:[(0,r.jsx)(C,{children:(0,r.jsxs)(x,{children:[(0,r.jsx)(c,{children:t("Bucket")}),(0,r.jsx)(c,{children:t("Operation")}),(0,r.jsx)(c,{children:t("Key prefix")}),(0,r.jsx)(c,{children:t("Guarded by")})]})}),(0,r.jsx)(I,{children:g.map(s=>(0,r.jsxs)(x,{"data-testid":`storage-rule-${s.bucket}-${s.on}-${s.prefix??""}`,children:[(0,r.jsx)(n,{className:"font-mono text-xs",children:s.bucket}),(0,r.jsx)(n,{children:(0,r.jsx)(y,{variant:"secondary",children:_(t,s.on)})}),(0,r.jsx)(n,{className:"font-mono text-xs",children:s.prefix??(0,r.jsx)("span",{className:"text-muted-foreground",children:t("(whole bucket)")})}),(0,r.jsx)(n,{className:"font-mono text-xs text-muted-foreground",children:s.procedure})]},`${s.bucket}:${s.on}:${s.prefix??""}:${s.procedure}`))})]})})})]}),e[1]=l,e[2]=i,e[3]=d,e[4]=h,e[5]=t,e[6]=m}else m=e[6];return m},"M");export{q as default};
1
+ import{b as y}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{a as R}from"./chunk-WM4EMDVF.js";import"./chunk-ULIQFBZU.js";import"./chunk-OTSOULJM.js";import"./chunk-35DM4JJG.js";import{a as v}from"./chunk-4ZEL6BYL.js";import{c as $}from"./chunk-AH6MS5JC.js";import"./chunk-OHOQXJGW.js";import"./chunk-FSRSK4LY.js";import"./chunk-5ICUJ4IA.js";import{a as S}from"./chunk-FKVZRPV5.js";import{a as A,b as C,c as I,d as x,e as c,f as n}from"./chunk-HEAQVSNS.js";import{a as k,e as w}from"./chunk-WUWBZPUK.js";import{d as N}from"./chunk-6B7FVPW3.js";import{a as f,d as b,f as E,g as O}from"./chunk-YKXDMIHQ.js";var j=b(E(),1);var r=b(O(),1);var _=f((e,t)=>({delete:e("Delete"),list:e("List"),read:e("Read"),write:e("Write")})[t],"I"),T={delete:2,list:3,read:0,write:1},B=f(e=>[...e].toSorted((t,a)=>t.bucket.localeCompare(a.bucket)||T[t.on]-T[a.on]||(t.prefix??"").localeCompare(a.prefix??"")),"O"),q=f(()=>{let e=(0,j.c)(14),t=N(),a;e[0]===Symbol.for("react.memo_cache_sentinel")?(a={},e[0]=a):a=e[0];let{data:l,error:i,errorSource:d}=$(v.storageRules,a),h=l!==void 0,m;if(e[1]!==l||e[2]!==i||e[3]!==d||e[4]!==h||e[5]!==t){let g=B(Array.isArray(l?.rules)?l.rules:[]),u;e[7]!==i||e[8]!==d?(u=i!==null&&(0,r.jsx)(R,{error:d,testId:"storage-rules-error"}),e[7]=i,e[8]=d,e[9]=u):u=e[9];let o;e[10]!==t?(o=t("Storage rules are declared in code with defineStorageRule and gate ctx.storage access per bucket. This view is read-only."),e[10]=t,e[11]=o):o=e[11];let p;e[12]!==o?(p=(0,r.jsx)("p",{className:"text-sm text-muted-foreground","data-testid":"storage-rules-note",children:o}),e[12]=o,e[13]=p):p=e[13],m=(0,r.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-storage-rules-panel",children:[u,p,h&&g.length===0?(0,r.jsx)(S,{description:t("No defineStorageRule is wired through .use(storageRules(...)) in this deployment. Add one to gate object access by key prefix."),testId:"storage-rules-empty",title:t("No storage rules defined")}):(0,r.jsx)(k,{className:"overflow-hidden py-0",children:(0,r.jsx)(w,{className:"px-0",children:(0,r.jsxs)(A,{"data-testid":"storage-rules-table",children:[(0,r.jsx)(C,{children:(0,r.jsxs)(x,{children:[(0,r.jsx)(c,{children:t("Bucket")}),(0,r.jsx)(c,{children:t("Operation")}),(0,r.jsx)(c,{children:t("Key prefix")}),(0,r.jsx)(c,{children:t("Guarded by")})]})}),(0,r.jsx)(I,{children:g.map(s=>(0,r.jsxs)(x,{"data-testid":`storage-rule-${s.bucket}-${s.on}-${s.prefix??""}`,children:[(0,r.jsx)(n,{className:"font-mono text-xs",children:s.bucket}),(0,r.jsx)(n,{children:(0,r.jsx)(y,{variant:"secondary",children:_(t,s.on)})}),(0,r.jsx)(n,{className:"font-mono text-xs",children:s.prefix??(0,r.jsx)("span",{className:"text-muted-foreground",children:t("(whole bucket)")})}),(0,r.jsx)(n,{className:"font-mono text-xs text-muted-foreground",children:s.procedure})]},`${s.bucket}:${s.on}:${s.prefix??""}:${s.procedure}`))})]})})})]}),e[1]=l,e[2]=i,e[3]=d,e[4]=h,e[5]=t,e[6]=m}else m=e[6];return m},"M");export{q as default};
@@ -0,0 +1,9 @@
1
+ import{a as Mt,d as y}from"./chunk-5ICUJ4IA.js";import{a as o,d as L,e as re,f as xt,g as We}from"./chunk-YKXDMIHQ.js";var q=class{static{o(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 cs=class extends q{static{o(this,"FocusManager")}#e;#t;#r;constructor(){super(),this.#r=t=>{if(typeof window<"u"&&window.addEventListener){let e=o(()=>t(),"listener");return window.addEventListener("visibilitychange",e,!1),()=>{window.removeEventListener("visibilitychange",e)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#r=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"}},ae=new cs;var us={setTimeout:o((t,e)=>setTimeout(t,e),"setTimeout"),clearTimeout:o(t=>clearTimeout(t),"clearTimeout"),setInterval:o((t,e)=>setInterval(t,e),"setInterval"),clearInterval:o(t=>clearInterval(t),"clearInterval")},hs=class{static{o(this,"TimeoutManager")}#e=us;#t=!1;setTimeoutProvider(t){this.#e=t}setTimeout(t,e){return this.#e.setTimeout(t,e)}clearTimeout(t){this.#e.clearTimeout(t)}setInterval(t,e){return this.#e.setInterval(t,e)}clearInterval(t){this.#e.clearInterval(t)}},j=new hs;function Qt(t){setTimeout(t,0)}o(Qt,"systemSetTimeoutZero");var Ve=typeof window>"u"||"Deno"in globalThis;function C(){}o(C,"noop");function Dt(t,e){return typeof t=="function"?t(e):t}o(Dt,"functionalUpdate");function fe(t){return typeof t=="number"&&t>=0&&t!==1/0}o(fe,"isValidTimeout");function Ee(t,e){return Math.max(t+(e||0)-Date.now(),0)}o(Ee,"timeUntilStale");function U(t,e){return typeof t=="function"?t(e):t}o(U,"resolveStaleTime");function I(t,e){return typeof t=="function"?t(e):t}o(I,"resolveQueryBoolean");function Ie(t,e){let{type:r="all",exact:s,fetchStatus:i,predicate:n,queryKey:a,stale:c}=t;if(a){if(s){if(e.queryHash!==pe(a,e.options))return!1}else if(!V(e.queryKey,a))return!1}if(r!=="all"){let u=e.isActive();if(r==="active"&&!u||r==="inactive"&&u)return!1}return!(typeof c=="boolean"&&e.isStale()!==c||i&&i!==e.state.fetchStatus||n&&!n(e))}o(Ie,"matchQuery");function Oe(t,e){let{exact:r,status:s,predicate:i,mutationKey:n}=t;if(n){if(!e.options.mutationKey)return!1;if(r){if(se(e.options.mutationKey)!==se(n))return!1}else if(!V(e.options.mutationKey,n))return!1}return!(s&&e.state.status!==s||i&&!i(e))}o(Oe,"matchMutation");function pe(t,e){return(e?.queryKeyHashFn||se)(t)}o(pe,"hashQueryKeyByOptions");function se(t){return JSON.stringify(t,(e,r)=>ze(r)?Object.keys(r).sort().reduce((s,i)=>(s[i]=r[i],s),{}):r)}o(se,"hashKey");function V(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 s=0;s<e.length;s++)if(!V(t[s],e[s]))return!1;return!0}let r=Object.keys(e);for(let s of r)if(!V(t[s],e[s]))return!1;return!0}return!1}o(V,"partialMatchKey");var ds=Object.prototype.hasOwnProperty;function Ge(t,e,r=0){if(t===e)return t;if(r>500)return e;let s=Lt(t)&&Lt(e);if(!s&&!(ze(t)&&ze(e)))return e;let n=(s?t:Object.keys(t)).length,a=s?e:Object.keys(e),c=a.length,u=s?new Array(c):{},h=0;for(let d=0;d<c;d++){let l=s?d:a[d],f=t[l],p=e[l];if(f===p){u[l]=f,(s?d<n:ds.call(t,l))&&h++;continue}if(f===null||p===null||typeof f!="object"||typeof p!="object"){u[l]=p;continue}let m=Ge(f,p,r+1);u[l]=m,m===f&&h++}return n===c&&h===n?t:u}o(Ge,"replaceEqualDeep");function Re(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(let r in t)if(t[r]!==e[r])return!1;return!0}o(Re,"shallowEqualObjects");function Lt(t){return Array.isArray(t)&&t.length===Object.keys(t).length}o(Lt,"isPlainArray");function ze(t){if(!_t(t))return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(!_t(r)||!r.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}o(ze,"isPlainObject");function _t(t){return Object.prototype.toString.call(t)==="[object Object]"}o(_t,"hasObjectPrototype");function Ut(t){return new Promise(e=>{j.setTimeout(e,t)})}o(Ut,"sleep");function me(t,e,r){return typeof r.structuralSharing=="function"?r.structuralSharing(t,e):r.structuralSharing!==!1?Ge(t,e):e}o(me,"replaceData");function ls(t){return t}o(ls,"keepPreviousData");function Nt(t,e,r=0){let s=[...t,e];return r&&s.length>r?s.slice(1):s}o(Nt,"addToEnd");function qt(t,e,r=0){let s=[e,...t];return r&&s.length>r?s.slice(0,-1):s}o(qt,"addToStart");var oe=Symbol();function Ae(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===oe?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}o(Ae,"ensureQueryFn");function Pe(t,e){return typeof t=="function"?t(...e):!!t}o(Pe,"shouldThrowError");function jt(t,e,r){let s=!1,i;return Object.defineProperty(t,"signal",{enumerable:!0,get:o(()=>(i??=e(),s||(s=!0,i.aborted?r():i.addEventListener("abort",r,{once:!0})),i),"get")}),t}o(jt,"addConsumeAwareSignal");var K=(()=>{let t=o(()=>Ve,"isServerFn");return{isServer(){return t()},setIsServer(e){t=e}}})();function ye(){let t,e,r=new Promise((i,n)=>{t=i,e=n});r.status="pending",r.catch(()=>{});function s(i){Object.assign(r,i),delete r.resolve,delete r.reject}return o(s,"finalize"),r.resolve=i=>{s({status:"fulfilled",value:i}),t(i)},r.reject=i=>{s({status:"rejected",reason:i}),e(i)},r}o(ye,"pendingThenable");var Kt=Qt;function fs(){let t=[],e=0,r=o(c=>{c()},"notifyFn"),s=o(c=>{c()},"batchNotifyFn"),i=Kt,n=o(c=>{e?t.push(c):i(()=>{r(c)})},"schedule"),a=o(()=>{let c=t;t=[],c.length&&i(()=>{s(()=>{c.forEach(u=>{r(u)})})})},"flush");return{batch:o(c=>{let u;e++;try{u=c()}finally{e--,e||a()}return u},"batch"),batchCalls:o(c=>(...u)=>{n(()=>{c(...u)})},"batchCalls"),schedule:n,setNotifyFunction:o(c=>{r=c},"setNotifyFunction"),setBatchNotifyFunction:o(c=>{s=c},"setBatchNotifyFunction"),setScheduler:o(c=>{i=c},"setScheduler")}}o(fs,"createNotifyManager");var v=fs();var ps=class extends q{static{o(this,"OnlineManager")}#e=!0;#t;#r;constructor(){super(),this.#r=t=>{if(typeof window<"u"&&window.addEventListener){let e=o(()=>t(!0),"onlineListener"),r=o(()=>t(!1),"offlineListener");return window.addEventListener("online",e,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",e),window.removeEventListener("offline",r)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#r=t,this.#t?.(),this.#t=t(this.setOnline.bind(this))}setOnline(t){this.#e!==t&&(this.#e=t,this.listeners.forEach(r=>{r(t)}))}isOnline(){return this.#e}},ce=new ps;function ms(t){return Math.min(1e3*2**t,3e4)}o(ms,"defaultRetryDelay");function Je(t){return(t??"online")==="online"?ce.isOnline():!0}o(Je,"canFetch");var Fe=class extends Error{static{o(this,"CancelledError")}constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function Me(t){let e=!1,r=0,s,i=ye(),n=o(()=>i.status!=="pending","isResolved"),a=o(b=>{if(!n()){let w=new Fe(b);f(w),t.onCancel?.(w)}},"cancel"),c=o(()=>{e=!0},"cancelRetry"),u=o(()=>{e=!1},"continueRetry"),h=o(()=>ae.isFocused()&&(t.networkMode==="always"||ce.isOnline())&&t.canRun(),"canContinue"),d=o(()=>Je(t.networkMode)&&t.canRun(),"canStart"),l=o(b=>{n()||(s?.(),i.resolve(b))},"resolve"),f=o(b=>{n()||(s?.(),i.reject(b))},"reject"),p=o(()=>new Promise(b=>{s=o(w=>{(n()||h())&&b(w)},"continueFn"),t.onPause?.()}).then(()=>{s=void 0,n()||t.onContinue?.()}),"pause"),m=o(()=>{if(n())return;let b,w=r===0?t.initialPromise:void 0;try{b=w??t.fn()}catch(k){b=Promise.reject(k)}Promise.resolve(b).then(l).catch(k=>{if(n())return;let M=t.retry??(K.isServer()?0:3),D=t.retryDelay??ms,N=typeof D=="function"?D(r,k):D,A=M===!0||typeof M=="number"&&r<M||typeof M=="function"&&M(r,k);if(e||!A){f(k);return}r++,t.onFail?.(r,k),Ut(N).then(()=>h()?void 0:p()).then(()=>{e?f(k):m()})})},"run");return{promise:i,status:o(()=>i.status,"status"),cancel:a,continue:o(()=>(s?.(),i),"continue"),cancelRetry:c,continueRetry:u,canStart:d,start:o(()=>(d()?m():p().then(m),i),"start")}}o(Me,"createRetryer");var xe=class{static{o(this,"Removable")}#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),fe(this.gcTime)&&(this.#e=j.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(K.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(j.clearTimeout(this.#e),this.#e=void 0)}};function $t(t){return{onFetch:o((e,r)=>{let s=e.options,i=e.fetchOptions?.meta?.fetchMore?.direction,n=e.state.data?.pages||[],a=e.state.data?.pageParams||[],c={pages:[],pageParams:[]},u=0,h=o(async()=>{let d=!1,l=o(m=>{jt(m,()=>e.signal,()=>d=!0)},"addSignalProperty"),f=Ae(e.options,e.fetchOptions),p=o(async(m,b,w)=>{if(d)return Promise.reject(e.signal.reason);if(b==null&&m.pages.length)return Promise.resolve(m);let M=o(()=>{let de={client:e.client,queryKey:e.queryKey,pageParam:b,direction:w?"backward":"forward",meta:e.options.meta};return l(de),de},"createQueryFnContext")(),D=await f(M),{maxPages:N}=e.options,A=w?qt:Nt;return{pages:A(m.pages,D,N),pageParams:A(m.pageParams,b,N)}},"fetchPage");if(i&&n.length){let m=i==="backward",b=m?ys:Bt,w={pages:n,pageParams:a},k=b(s,w);c=await p(w,k,m)}else{let m=t??n.length;do{let b=u===0?a[0]??s.initialPageParam:Bt(s,c);if(u>0&&b==null)break;c=await p(c,b),u++}while(u<m)}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},r):e.fetchFn=h},"onFetch")}}o($t,"infiniteQueryBehavior");function Bt(t,{pages:e,pageParams:r}){let s=e.length-1;return e.length>0?t.getNextPageParam(e[s],e,r[s],r):void 0}o(Bt,"getNextPageParam");function ys(t,{pages:e,pageParams:r}){return e.length>0?t.getPreviousPageParam?.(e[0],e,r[0],r):void 0}o(ys,"getPreviousPageParam");var zt=class extends xe{static{o(this,"Query")}#e;#t;#r;#s;#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.#s=this.#n.getQueryCache(),this.queryKey=t.queryKey,this.queryHash=t.queryHash,this.#t=Wt(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=Wt(this.options);e.data!==void 0&&(this.setState(Ht(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(t,e){let r=me(this.state.data,t,this.options);return this.#c({data:r,type:"success",dataUpdatedAt:e?.updatedAt,manual:e?.manual}),r}setState(t){this.#c({type:"setState",state:t})}cancel(t){let e=this.#i?.promise;return this.#i?.cancel(t),e?e.then(C).catch(C):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>I(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===oe||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>U(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:!Ee(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.#s.notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(e=>e!==t),this.observers.length||(this.#i&&(this.#a||this.#h()?this.#i.cancel({revert:!0}):this.#i.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}#h(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#c({type:"invalidate"})}async fetch(t,e){if(this.state.fetchStatus!=="idle"&&this.#i?.status()!=="rejected"){if(this.state.data!==void 0&&e?.cancelRefetch)this.cancel({silent:!0});else if(this.#i)return this.#i.continueRetry(),this.#i.promise}if(t&&this.setOptions(t),!this.options.queryFn){let u=this.observers.find(h=>h.options.queryFn);u&&this.setOptions(u.options)}let r=new AbortController,s=o(u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:o(()=>(this.#a=!0,r.signal),"get")})},"addSignalProperty"),i=o(()=>{let u=Ae(this.options,e),d=o(()=>{let l={client:this.#n,queryKey:this.queryKey,meta:this.meta};return s(l),l},"createQueryFnContext")();return this.#a=!1,this.options.persister?this.options.persister(u,d,this):u(d)},"fetchFn"),a=o(()=>{let u={fetchOptions:e,options:this.options,queryKey:this.queryKey,client:this.#n,state:this.state,fetchFn:i};return s(u),u},"createFetchContext")();(this.#e==="infinite"?$t(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#r=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:"fetch",meta:a.fetchOptions?.meta}),this.#i=Me({initialPromise:e?.initialPromise,fn:a.fetchFn,onCancel:o(u=>{u instanceof Fe&&u.revert&&this.setState({...this.#r,fetchStatus:"idle"}),r.abort()},"onCancel"),onFail:o((u,h)=>{this.#c({type:"failed",failureCount:u,error:h})},"onFail"),onPause:o(()=>{this.#c({type:"pause"})},"onPause"),onContinue:o(()=>{this.#c({type:"continue"})},"onContinue"),retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:o(()=>!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.#s.config.onSuccess?.(u,this),this.#s.config.onSettled?.(u,this.state.error,this),u}catch(u){if(u instanceof Fe){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.#s.config.onError?.(u,this),this.#s.config.onSettled?.(this.state.data,u,this),u}finally{this.scheduleGc()}}#c(t){let e=o(r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...Ye(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...Ht(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#r=t.manual?s:void 0,s;case"error":let i=t.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}},"reducer");this.state=e(this.state),v.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:t})})}};function Ye(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Je(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}o(Ye,"fetchState");function Ht(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}o(Ht,"successState");function Wt(t){let e=typeof t.initialData=="function"?t.initialData():t.initialData,r=e!==void 0,s=r?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:r?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:r?"success":"pending",fetchStatus:"idle"}}o(Wt,"getDefaultState");var Ze=class extends q{static{o(this,"QueryObserver")}constructor(t,e){super(),this.options=e,this.#e=t,this.#a=null,this.#o=ye(),this.bindMethods(),this.setOptions(e)}#e;#t=void 0;#r=void 0;#s=void 0;#n;#i;#o;#a;#h;#c;#p;#d;#l;#u;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Vt(this.#t,this.options)?this.#f():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Xe(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Xe(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#S(),this.#w(),this.#t.removeObserver(this)}setOptions(t){let e=this.options,r=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 I(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&&!Re(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});let s=this.hasListeners();s&&Gt(this.#t,r,this.options,e)&&this.#f(),this.updateResult(),s&&(this.#t!==r||I(this.options.enabled,this.#t)!==I(e.enabled,this.#t)||U(this.options.staleTime,this.#t)!==U(e.staleTime,this.#t))&&this.#y();let i=this.#b();s&&(this.#t!==r||I(this.options.enabled,this.#t)!==I(e.enabled,this.#t)||i!==this.#u)&&this.#g(i)}getOptimisticResult(t){let e=this.#e.getQueryCache().build(this.#e,t),r=this.createResult(e,t);return gs(this,r)&&(this.#s=r,this.#i=this.options,this.#n=this.#t.state),r}getCurrentResult(){return this.#s}trackResult(t,e){return new Proxy(t,{get:o((r,s)=>(this.trackProp(s),e?.(s),s==="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(r,s)),"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),r=this.#e.getQueryCache().build(this.#e,e);return r.fetch().then(()=>this.createResult(r,e))}fetch(t){return this.#f({...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#f(t){this.#C();let e=this.#t.fetch(this.options,t);return t?.throwOnError||(e=e.catch(C)),e}#y(){this.#S();let t=U(this.options.staleTime,this.#t);if(K.isServer()||this.#s.isStale||!fe(t))return;let r=Ee(this.#s.dataUpdatedAt,t)+1;this.#d=j.setTimeout(()=>{this.#s.isStale||this.updateResult()},r)}#b(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#g(t){this.#w(),this.#u=t,!(K.isServer()||I(this.options.enabled,this.#t)===!1||!fe(this.#u)||this.#u===0)&&(this.#l=j.setInterval(()=>{(this.options.refetchIntervalInBackground||ae.isFocused())&&this.#f()},this.#u))}#v(){this.#y(),this.#g(this.#b())}#S(){this.#d!==void 0&&(j.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#l!==void 0&&(j.clearInterval(this.#l),this.#l=void 0)}createResult(t,e){let r=this.#t,s=this.options,i=this.#s,n=this.#n,a=this.#i,u=t!==r?t.state:this.#r,{state:h}=t,d={...h},l=!1,f;if(e._optimisticResults){let Q=this.hasListeners(),le=!Q&&Vt(t,e),Ce=Q&&Gt(t,r,e,s);(le||Ce)&&(d={...d,...Ye(h.data,t.options)}),e._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:p,errorUpdatedAt:m,status:b}=d;f=d.data;let w=!1;if(e.placeholderData!==void 0&&f===void 0&&b==="pending"){let Q;i?.isPlaceholderData&&e.placeholderData===a?.placeholderData?(Q=i.data,w=!0):Q=typeof e.placeholderData=="function"?e.placeholderData(this.#p?.state.data,this.#p):e.placeholderData,Q!==void 0&&(b="success",f=me(i?.data,Q,e),l=!0)}if(e.select&&f!==void 0&&!w)if(i&&f===n?.data&&e.select===this.#h)f=this.#c;else try{this.#h=e.select,f=e.select(f),f=me(i?.data,f,e),this.#c=f,this.#a=null}catch(Q){this.#a=Q}this.#a&&(p=this.#a,f=this.#c,m=Date.now(),b="error");let k=d.fetchStatus==="fetching",M=b==="pending",D=b==="error",N=M&&k,A=f!==void 0,x={status:b,fetchStatus:d.fetchStatus,isPending:M,isSuccess:b==="success",isError:D,isInitialLoading:N,isLoading:N,data:f,dataUpdatedAt:d.dataUpdatedAt,error:p,errorUpdatedAt:m,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:d.dataUpdateCount>u.dataUpdateCount||d.errorUpdateCount>u.errorUpdateCount,isFetching:k,isRefetching:k&&!M,isLoadingError:D&&!A,isPaused:d.fetchStatus==="paused",isPlaceholderData:l,isRefetchError:D&&A,isStale:et(t,e),refetch:this.refetch,promise:this.#o,isEnabled:I(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let Q=x.data!==void 0,le=x.status==="error"&&!Q,Ce=o(Te=>{le?Te.reject(x.error):Q&&Te.resolve(x.data)},"finalizeThenableIfPossible"),Ft=o(()=>{let Te=this.#o=x.promise=ye();Ce(Te)},"recreateThenable"),ke=this.#o;switch(ke.status){case"pending":t.queryHash===r.queryHash&&Ce(ke);break;case"fulfilled":(le||x.data!==ke.value)&&Ft();break;case"rejected":(!le||x.error!==ke.reason)&&Ft();break}}return x}updateResult(){let t=this.#s,e=this.createResult(this.#t,this.options);if(this.#n=this.#t.state,this.#i=this.options,this.#n.data!==void 0&&(this.#p=this.#t),Re(e,t))return;this.#s=e;let r=o(()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;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.#s).some(a=>{let c=a;return this.#s[c]!==t[c]&&n.has(c)})},"shouldNotifyListeners");this.#k({listeners:r()})}#C(){let t=this.#e.getQueryCache().build(this.#e,this.options);if(t===this.#t)return;let e=this.#t;this.#t=t,this.#r=t.state,this.hasListeners()&&(e?.removeObserver(this),t.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#v()}#k(t){v.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#s)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function bs(t,e){return I(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&I(e.retryOnMount,t)===!1)}o(bs,"shouldLoadOnMount");function Vt(t,e){return bs(t,e)||t.state.data!==void 0&&Xe(t,e,e.refetchOnMount)}o(Vt,"shouldFetchOnMount");function Xe(t,e,r){if(I(e.enabled,t)!==!1&&U(e.staleTime,t)!=="static"){let s=typeof r=="function"?r(t):r;return s==="always"||s!==!1&&et(t,e)}return!1}o(Xe,"shouldFetchOn");function Gt(t,e,r,s){return(t!==e||I(s.enabled,t)===!1)&&(!r.suspense||t.state.status!=="error")&&et(t,r)}o(Gt,"shouldFetchOptionally");function et(t,e){return I(e.enabled,t)!==!1&&t.isStaleByTime(U(e.staleTime,t))}o(et,"isStale");function gs(t,e){return!Re(t.getCurrentResult(),e)}o(gs,"shouldAssignObserverCurrentProperties");var Jt=class extends xe{static{o(this,"Mutation")}#e;#t;#r;#s;constructor(t){super(),this.#e=t.client,this.mutationId=t.mutationId,this.#r=t.mutationCache,this.#t=[],this.state=t.state||vs(),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.#r.notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){this.#t=this.#t.filter(e=>e!==t),this.scheduleGc(),this.#r.notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#r.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(t){let e=o(()=>{this.#n({type:"continue"})},"onContinue"),r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=Me({fn:o(()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),"fn"),onFail:o((n,a)=>{this.#n({type:"failed",failureCount:n,error:a})},"onFail"),onPause:o(()=>{this.#n({type:"pause"})},"onPause"),onContinue:e,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:o(()=>this.#r.canRun(this),"canRun")});let s=this.state.status==="pending",i=!this.#s.canStart();try{if(s)e();else{this.#n({type:"pending",variables:t,isPaused:i}),this.#r.config.onMutate&&await this.#r.config.onMutate(t,this,r);let a=await this.options.onMutate?.(t,r);a!==this.state.context&&this.#n({type:"pending",context:a,variables:t,isPaused:i})}let n=await this.#s.start();return await this.#r.config.onSuccess?.(n,t,this.state.context,this,r),await this.options.onSuccess?.(n,t,this.state.context,r),await this.#r.config.onSettled?.(n,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(n,null,t,this.state.context,r),this.#n({type:"success",data:n}),n}catch(n){try{await this.#r.config.onError?.(n,t,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onError?.(n,t,this.state.context,r)}catch(a){Promise.reject(a)}try{await this.#r.config.onSettled?.(void 0,n,this.state.variables,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onSettled?.(void 0,n,t,this.state.context,r)}catch(a){Promise.reject(a)}throw this.#n({type:"error",error:n}),n}finally{this.#r.runNext(this)}}#n(t){let e=o(r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,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{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}},"reducer");this.state=e(this.state),v.batch(()=>{this.#t.forEach(r=>{r.onMutationUpdate(t)}),this.#r.notify({mutation:this,type:"updated",action:t})})}};function vs(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}o(vs,"getDefaultState");var Yt=class extends q{static{o(this,"MutationCache")}constructor(t={}){super(),this.config=t,this.#e=new Set,this.#t=new Map,this.#r=0}#e;#t;#r;build(t,e,r){let s=new Jt({client:t,mutationCache:this,mutationId:++this.#r,options:t.defaultMutationOptions(e),state:r});return this.add(s),s}add(t){this.#e.add(t);let e=Qe(t);if(typeof e=="string"){let r=this.#t.get(e);r?r.push(t):this.#t.set(e,[t])}this.notify({type:"added",mutation:t})}remove(t){if(this.#e.delete(t)){let e=Qe(t);if(typeof e=="string"){let r=this.#t.get(e);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&this.#t.delete(e)}}this.notify({type:"removed",mutation:t})}canRun(t){let e=Qe(t);if(typeof e=="string"){let s=this.#t.get(e)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let e=Qe(t);return typeof e=="string"?this.#t.get(e)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){v.batch(()=>{this.#e.forEach(t=>{this.notify({type:"removed",mutation:t})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(t){let e={exact:!0,...t};return this.getAll().find(r=>Oe(e,r))}findAll(t={}){return this.getAll().filter(e=>Oe(t,e))}notify(t){v.batch(()=>{this.listeners.forEach(e=>{e(t)})})}resumePausedMutations(){let t=this.getAll().filter(e=>e.state.isPaused);return v.batch(()=>Promise.all(t.map(e=>e.continue().catch(C))))}};function Qe(t){return t.options.scope?.id}o(Qe,"scopeFor");var Xt=class extends q{static{o(this,"QueryCache")}constructor(t={}){super(),this.config=t,this.#e=new Map}#e;build(t,e,r){let s=e.queryKey,i=e.queryHash??pe(s,e),n=this.get(i);return n||(n=new zt({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(e),state:r,defaultOptions:t.getQueryDefaults(s)}),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(){v.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return this.#e.get(t)}getAll(){return[...this.#e.values()]}find(t){let e={exact:!0,...t};return this.getAll().find(r=>Ie(e,r))}findAll(t={}){let e=this.getAll();return Object.keys(t).length>0?e.filter(r=>Ie(t,r)):e}notify(t){v.batch(()=>{this.listeners.forEach(e=>{e(t)})})}onFocus(){v.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){v.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}};var tt=class{static{o(this,"QueryClient")}#e;#t;#r;#s;#n;#i;#o;#a;constructor(t={}){this.#e=t.queryCache||new Xt,this.#t=t.mutationCache||new Yt,this.#r=t.defaultOptions||{},this.#s=new Map,this.#n=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#o=ae.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#a=ce.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),r=this.#e.build(this,e),s=r.state.data;return s===void 0?this.fetchQuery(t):(t.revalidateIfStale&&r.isStaleByTime(U(e.staleTime,r))&&this.prefetchQuery(e),Promise.resolve(s))}getQueriesData(t){return this.#e.findAll(t).map(({queryKey:e,state:r})=>{let s=r.data;return[e,s]})}setQueryData(t,e,r){let s=this.defaultQueryOptions({queryKey:t}),n=this.#e.get(s.queryHash)?.state.data,a=Dt(e,n);if(a!==void 0)return this.#e.build(this,s).setData(a,{...r,manual:!0})}setQueriesData(t,e,r){return v.batch(()=>this.#e.findAll(t).map(({queryKey:s})=>[s,this.setQueryData(s,e,r)]))}getQueryState(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state}removeQueries(t){let e=this.#e;v.batch(()=>{e.findAll(t).forEach(r=>{e.remove(r)})})}resetQueries(t,e){let r=this.#e;return v.batch(()=>(r.findAll(t).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){let r={revert:!0,...e},s=v.batch(()=>this.#e.findAll(t).map(i=>i.cancel(r)));return Promise.all(s).then(C).catch(C)}invalidateQueries(t,e={}){return v.batch(()=>(this.#e.findAll(t).forEach(r=>{r.invalidate()}),t?.refetchType==="none"?Promise.resolve():this.refetchQueries({...t,type:t?.refetchType??t?.type??"active"},e)))}refetchQueries(t,e={}){let r={...e,cancelRefetch:e.cancelRefetch??!0},s=v.batch(()=>this.#e.findAll(t).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let n=i.fetch(void 0,r);return r.throwOnError||(n=n.catch(C)),i.state.fetchStatus==="paused"?Promise.resolve():n}));return Promise.all(s).then(C)}fetchQuery(t){let e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);let r=this.#e.build(this,e);return r.isStaleByTime(U(e.staleTime,r))?r.fetch(e):Promise.resolve(r.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(C).catch(C)}fetchInfiniteQuery(t){return t._type="infinite",this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(C).catch(C)}ensureInfiniteQueryData(t){return t._type="infinite",this.ensureQueryData(t)}resumePausedMutations(){return ce.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#r}setDefaultOptions(t){this.#r=t}setQueryDefaults(t,e){this.#s.set(se(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){let e=[...this.#s.values()],r={};return e.forEach(s=>{V(t,s.queryKey)&&Object.assign(r,s.defaultOptions)}),r}setMutationDefaults(t,e){this.#n.set(se(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){let e=[...this.#n.values()],r={};return e.forEach(s=>{V(t,s.mutationKey)&&Object.assign(r,s.defaultOptions)}),r}defaultQueryOptions(t){if(t._defaulted)return t;let e={...this.#r.queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=pe(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===oe&&(e.enabled=!1),e}defaultMutationOptions(t){return t?._defaulted?t:{...this.#r.mutations,...t?.mutationKey&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}};var G=L(re(),1);var ue=L(re(),1),Zt=L(We(),1);var be=ue.createContext(void 0),rt=o(t=>{let e=ue.useContext(be);if(t)return t;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},"useQueryClient"),st=o(({client:t,children:e})=>(ue.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,Zt.jsx)(be.Provider,{value:t,children:e})),"QueryClientProvider");var ge=L(re(),1),Ss=L(We(),1);function ws(){let t=!1;return{clearReset:o(()=>{t=!1},"clearReset"),reset:o(()=>{t=!0},"reset"),isReset:o(()=>t,"isReset")}}o(ws,"createValue");var Cs=ge.createContext(ws()),er=o(()=>ge.useContext(Cs),"useQueryErrorResetBoundary");var tr=L(re(),1);var rr=o((t,e,r)=>{let s=r?.state.error&&typeof t.throwOnError=="function"?Pe(t.throwOnError,[r.state.error,r]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||s)&&(e.isReset()||(t.retryOnMount=!1))},"ensurePreventErrorBoundaryRetry"),sr=o(t=>{tr.useEffect(()=>{t.clearReset()},[t])},"useClearResetErrorBoundary"),ir=o(({result:t,errorResetBoundary:e,throwOnError:r,query:s,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&s&&(i&&t.data===void 0||Pe(r,[t.error,s])),"getHasError");var Le=L(re(),1);var nr=Le.createContext(!1),ar=o(()=>Le.useContext(nr),"useIsRestoring"),Jo=nr.Provider;var or=o(t=>{if(t.suspense){let r=o(i=>i==="static"?i:Math.max(i??1e3,1e3),"clamp"),s=t.staleTime;t.staleTime=typeof s=="function"?(...i)=>r(s(...i)):r(s),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},"ensureSuspenseTimers"),cr=o((t,e)=>t.isLoading&&t.isFetching&&!e,"willFetch"),ur=o((t,e)=>t?.suspense&&e.isPending,"shouldSuspend"),it=o((t,e,r)=>e.fetchOptimistic(t).catch(()=>{r.clearReset()}),"fetchOptimistic");function hr(t,e,r){let s=ar(),i=er(),n=rt(r),a=n.defaultQueryOptions(t);n.getDefaultOptions().queries?._experimental_beforeQuery?.(a);let c=n.getQueryCache().get(a.queryHash),u=t.subscribed!==!1;a._optimisticResults=s?"isRestoring":u?"optimistic":void 0,or(a),rr(a,i,c),sr(i);let h=!n.getQueryCache().get(a.queryHash),[d]=G.useState(()=>new e(n,a)),l=d.getOptimisticResult(a),f=!s&&u;if(G.useSyncExternalStore(G.useCallback(p=>{let m=f?d.subscribe(v.batchCalls(p)):C;return d.updateResult(),m},[d,f]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),G.useEffect(()=>{d.setOptions(a)},[a,d]),ur(a,l))throw it(a,d,i);if(ir({result:l,errorResetBoundary:i,throwOnError:a.throwOnError,query:c,suspense:a.suspense}))throw l.error;return n.getDefaultOptions().queries?._experimental_afterQuery?.(a,l),a.experimental_prefetchInRender&&!K.isServer()&&cr(l,s)&&(h?it(a,d,i):c?.promise)?.catch(C).finally(()=>{d.updateResult()}),a.notifyOnChangeProps?l:d.trackResult(l)}o(hr,"useBaseQuery");function ks(t,e){return hr(t,Ze,e)}o(ks,"useQuery");var mr=L(xt(),1);var H=L(re(),1);var Ts=/["\\\u0000-\u001F\uD800-\uDFFF]/,dr=o(t=>Ts.test(t)?JSON.stringify(t):`"${t}"`,"d"),at=o(t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key \u2014 pass it as a string, or use stableWireKey");if(typeof t=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(typeof t=="string")return dr(t);if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t)){let a="[";for(let c=0;c<t.length;c++)c>0&&(a+=","),a+=at(t[c]);return a+"]"}let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype){let a=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${a} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}let r=t,s=Object.keys(r).sort(),i="{",n=!0;for(let a of s){let c=r[a];c!==void 0&&(n?n=!1:i+=",",i+=dr(a),i+=":",i+=at(c))}return i+"}"},"b"),nt=o(t=>{let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e)},"u"),O="$lunora.wire$",lr="__proto__",Es=o(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"m"),$=o((t,e=0)=>{if(e>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(t===void 0)return[O,"undefined"];if(t===null)return null;let r=typeof t;if(r==="bigint")return[O,"bigint",t.toString()];if(r==="number"){let n=t;return Number.isNaN(n)?[O,"nan"]:n===1/0?[O,"inf"]:n===-1/0?[O,"-inf"]:n}if(r!=="object")return t;if(t instanceof Date)return[O,"date",$(t.getTime(),e+1)];if(t instanceof Error){let n=t,a={};for(let u of Object.keys(n)){if(n[u]===void 0)continue;let h=$(n[u],e+1);u===lr?Object.defineProperty(a,u,{configurable:!0,enumerable:!0,value:h,writable:!0}):a[u]=h}let c=[O,"error",String(n.name),String(n.message),a];return n.cause!==void 0&&c.push($(n.cause,e+1)),c}if(t instanceof URL)return[O,"url",t.href];if(t instanceof Map)return[O,"map",[...t.entries()].map(([n,a])=>[$(n,e+1),$(a,e+1)])];if(t instanceof Set)return[O,"set",[...t].map(n=>$(n,e+1))];if(t instanceof ArrayBuffer)return[O,"bytes",nt(new Uint8Array(t)),"ArrayBuffer"];if(ArrayBuffer.isView(t)){let n=t,a=n.constructor.name,c=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);return a==="Uint8Array"?[O,"bytes",nt(c)]:[O,"bytes",nt(c),a]}if(Array.isArray(t)){let n=t.map(a=>$(a,e+1));return n.length>0&&n[0]===O?[O,"arr",n]:n}if(!Es(t)){let n=t.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${n} 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`)}let s=t,i={};for(let n of Object.keys(s)){let a=s[n];if(a===void 0)continue;let c=$(a,e+1);n===lr?Object.defineProperty(i,n,{configurable:!0,enumerable:!0,value:c,writable:!0}):i[n]=c}return i},"a"),Is=o(t=>at($(t)),"w"),ve=o(t=>Is(t),"O");var ot=L(We(),1);var fr=o(t=>{t!==void 0&&(t.cancel({silent:!0}),t.setState({...t.state,data:void 0,dataUpdatedAt:0,error:null,fetchStatus:"idle",status:"pending"}))},"C"),ct=class{static{o(this,"x")}constructor(e){this.client=e}client;entries=new Map;pushes=new Map;samples=new Map;epoch=0;identityWatched=new Set;listening=!1;keyOf(e){return ve(e)}hasConsumers(e){return this.entries.has(ve(e))}openSnapshotSample(e){let r=ve(e);return this.samples.set(r,(this.samples.get(r)??0)+1),{key:r,pushes:this.pushes.get(r)??0}}closeSnapshotSample(e){let r=(this.samples.get(e.key)??1)-1,s=(this.pushes.get(e.key)??0)===e.pushes;return r>0?(this.samples.set(e.key,r),s):(this.samples.delete(e.key),this.entries.has(e.key)||this.pushes.delete(e.key),s)}clearOnIdentityChange(e){this.listenForIdentityChange(),this.identityWatched.add(e)}identityEpoch=o(()=>this.epoch,"identityEpoch");subscribeIdentityEpoch=o(e=>(this.listenForIdentityChange(),this.client.onIdentityChange(e)),"subscribeIdentityEpoch");listenForIdentityChange(){this.listening||(this.listening=!0,this.client.onIdentityChange(()=>{this.epoch+=1;for(let e of this.identityWatched){let r=e.getQueryCache();for(let s of r.findAll({queryKey:["lunora"]}))fr(s),s.getObserversCount()===0&&!this.hasConsumers(s.queryKey)&&r.remove(s)}}))}attach(e,r,s,i,n,a={}){let c=ve(r),u=this.entries.get(c);if(!u){u={errorCallbacks:new Set,refCount:0,unsubscribe:void 0},this.entries.set(c,u);let l=u;try{u.unsubscribe=this.client.subscribe(s,i,f=>{if(this.pushes.set(c,(this.pushes.get(c)??0)+1),f===void 0){fr(e.getQueryCache().find({exact:!0,queryKey:r}));return}e.setQueryData(r,f)},{onError:o(f=>{for(let p of l.errorCallbacks)p(f)},"onError"),shardKey:n})}catch(f){throw this.entries.delete(c),f}}u.refCount+=1;let{onError:h}=a;h&&u.errorCallbacks.add(h);let d=!1;return()=>{if(d)return;d=!0;let l=this.entries.get(c);l&&(l.refCount-=1,h&&l.errorCallbacks.delete(h),l.refCount<=0&&(l.unsubscribe?.(),this.entries.delete(c)))}}},pr=new WeakMap,Os=o(t=>{let e=pr.get(t);return e||(e=new ct(t),pr.set(t,e)),e},"O"),yr=(0,H.createContext)(null),Rs=o(()=>new tt({defaultOptions:{mutations:{retry:0},queries:{gcTime:5*6e4,retry:0,staleTime:Number.POSITIVE_INFINITY}}}),"N"),As=o(t=>{let e=(0,mr.c)(13),{children:r,client:s,queryClient:i}=t,n=(0,H.use)(be),a;e[0]!==n||e[1]!==i?(a=o(()=>i??n??Rs(),"d"),e[0]=n,e[1]=i,e[2]=a):a=e[2];let[c]=(0,H.useState)(a),u=i??n??c,h,d;e[3]!==s||e[4]!==u?(h=o(()=>{Os(s).clearOnIdentityChange(u)},"u"),d=[s,u],e[3]=s,e[4]=u,e[5]=h,e[6]=d):(h=e[5],d=e[6]),(0,H.useEffect)(h,d);let l;e[7]!==r||e[8]!==s?(l=(0,ot.jsx)(yr,{value:s,children:r}),e[7]=r,e[8]=s,e[9]=l):l=e[9];let f=l;if(n===u)return f;let p;return e[10]!==f||e[11]!==u?(p=(0,ot.jsx)(st,{client:u,children:f}),e[10]=f,e[11]=u,e[12]=p):p=e[12],p},"R"),ut=o(()=>{let t=(0,H.use)(yr);if(!t)throw new y("INTERNAL","useLunora must be used inside <LunoraProvider />");return t},"D");var _e=o(t=>{let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e)},"w"),Ps=o(t=>{let e=atob(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s+=1)r[s]=e.codePointAt(s)??0;return r},"p"),W="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",vr=o(t=>{let e="",r=0,s=t.length-2;for(;r<s;r+=3){let n=t[r]<<16|t[r+1]<<8|t[r+2];e+=W.charAt(n>>18&63)+W.charAt(n>>12&63)+W.charAt(n>>6&63)+W.charAt(n&63)}let i=t.length-r;if(i===1){let n=t[r]<<16;e+=W.charAt(n>>18&63)+W.charAt(n>>12&63)}else if(i===2){let n=t[r]<<16|t[r+1]<<8;e+=W.charAt(n>>18&63)+W.charAt(n>>12&63)+W.charAt(n>>6&63)}return e},"h"),T="$lunora.wire$",De="__proto__",br={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},gr={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},ht=o(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"E"),E=o((t,e=0)=>{if(e>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(t===void 0)return[T,"undefined"];if(t===null)return null;let r=typeof t;if(r==="bigint")return[T,"bigint",t.toString()];if(r==="number"){let n=t;return Number.isNaN(n)?[T,"nan"]:n===1/0?[T,"inf"]:n===-1/0?[T,"-inf"]:n}if(r!=="object")return t;if(t instanceof Date)return[T,"date",E(t.getTime(),e+1)];if(t instanceof Error){let n=t,a={};for(let u of Object.keys(n)){if(n[u]===void 0)continue;let h=E(n[u],e+1);u===De?Object.defineProperty(a,u,{configurable:!0,enumerable:!0,value:h,writable:!0}):a[u]=h}let c=[T,"error",String(n.name),String(n.message),a];return n.cause!==void 0&&c.push(E(n.cause,e+1)),c}if(t instanceof URL)return[T,"url",t.href];if(t instanceof Map)return[T,"map",[...t.entries()].map(([n,a])=>[E(n,e+1),E(a,e+1)])];if(t instanceof Set)return[T,"set",[...t].map(n=>E(n,e+1))];if(t instanceof ArrayBuffer)return[T,"bytes",_e(new Uint8Array(t)),"ArrayBuffer"];if(ArrayBuffer.isView(t)){let n=t,a=n.constructor.name,c=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);return a==="Uint8Array"?[T,"bytes",_e(c)]:[T,"bytes",_e(c),a]}if(Array.isArray(t)){let n=t.map(a=>E(a,e+1));return n.length>0&&n[0]===T?[T,"arr",n]:n}if(!ht(t)){let n=t.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${n} 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`)}let s=t,i={};for(let n of Object.keys(s)){let a=s[n];if(a===void 0)continue;let c=E(a,e+1);n===De?Object.defineProperty(i,n,{configurable:!0,enumerable:!0,value:c,writable:!0}):i[n]=c}return i},"d"),S=o((t,e=0)=>{if(e>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(t===null||typeof t!="object")return t;if(Array.isArray(t)){if(t[0]===T)switch(t[1]){case"-inf":return-1/0;case"arr":return t[2].map(i=>S(i,e+1));case"bigint":{let i=t[2];if(typeof i!="string"||i.length>1024||!/^-?\d+$/.test(i))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(i)}case"date":{let i=S(t[2],e+1);if(typeof i!="number")throw new TypeError("wire-codec: malformed date \u2014 epoch must be a number");return new Date(i)}case"map":{let i=t[2];return new Map(i.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry \u2014 expected a [key, value] pair");return[S(n[0],e+1),S(n[1],e+1)]}))}case"set":return new Set(t[2].map(i=>S(i,e+1)));case"url":{let i=t[2];if(typeof i!="string")throw new TypeError("wire-codec: malformed url \u2014 href must be a string");return new URL(i)}case"error":{let i=t[2],n=t[3];if(typeof i!="string"||typeof n!="string")throw new TypeError("wire-codec: malformed error \u2014 name and message must be strings");let a=(Object.hasOwn(gr,i)?gr[i]:void 0)??Error,c=new a(n);c.name!==i&&Object.defineProperty(c,"name",{configurable:!0,value:i,writable:!0});let u=S(t[4],e+1);if(u===null||typeof u!="object"||Array.isArray(u))throw new TypeError("wire-codec: malformed error \u2014 props must be an object");for(let h of Object.keys(u))h===De?Object.defineProperty(c,h,{configurable:!0,enumerable:!0,value:u[h],writable:!0}):c[h]=u[h];return t.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:S(t[5],e+1),writable:!0}),c}case"bytes":{let i=t[2];if(typeof i!="string")throw new TypeError("wire-codec: malformed bytes \u2014 payload must be a base64 string");let n=Ps(i);if(_e(n)!==i)throw new TypeError("wire-codec: malformed bytes \u2014 payload must be canonical padded base64");let a=t[3]??"Uint8Array";if(a==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;let c=Object.hasOwn(br,a)?br[a]:void 0;return c?new c(n.slice().buffer):n}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return t.map(i=>S(i,e+1))}return t.map(i=>S(i,e+1))}let r=t,s={};for(let i of Object.keys(r)){let n=S(r[i],e+1);i===De?Object.defineProperty(s,i,{configurable:!0,enumerable:!0,value:n,writable:!0}):s[i]=n}return s},"u");var P=o(t=>new Promise((e,r)=>{t.addEventListener("success",()=>{e(t.result)}),t.addEventListener("error",()=>{r(t.error??new Error("IndexedDB request failed"))})}),"c"),Ue=o((t,e,r,s)=>{let i;return()=>i||(i=new Promise((n,a)=>{let c=t.open(e,r);c.addEventListener("upgradeneeded",()=>{s(c.result)}),c.addEventListener("success",()=>{n(c.result)}),c.addEventListener("error",()=>{a(c.error??new Error("IndexedDB open failed"))})}),i)},"E"),Ne=o((t,e)=>async(r,s)=>{let i=(await t()).transaction(e,r),n=await s(i.objectStore(e));return await new Promise((a,c)=>{i.addEventListener("complete",()=>{a()}),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 ie=o((t,e,r)=>`${t}::${e}::${r??""}`,"T"),Fs=500,Ms=o((t,e)=>{if(!Number.isInteger(t)||t<1)throw new y("INTERNAL",`${e}: maxEntries must be a positive integer, got ${String(t)}`);return t},"E");var xs="lunora-query-cache",Qs="query-cache",Sr="by_ts",Ls=1,_s=o((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new y("INTERNAL","createIndexedDbQueryCache: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryQueryCache()");let r=t.databaseName??xs,s=t.storeName??Qs,i=Ms(t.maxEntries??Fs,"createIndexedDbQueryCache"),n=Ue(e,r,Ls,u=>{u.objectStoreNames.contains(s)||u.createObjectStore(s,{keyPath:"key"}).createIndex(Sr,"ts",{unique:!1})}),a=Ne(n,s),c=o(async u=>{let h=await P(u.count())-i;h<=0||await new Promise((d,l)=>{let f=u.index(Sr).openCursor();f.addEventListener("success",()=>{let p=f.result;if(!p||h<=0){d();return}p.delete(),h-=1,p.continue()}),f.addEventListener("error",()=>{l(f.error??new Error("IndexedDB eviction failed"))})})},"y");return{clear:o(async()=>{await a("readwrite",u=>P(u.clear()))},"clear"),load:o(async()=>a("readonly",u=>P(u.getAll())),"load"),put:o(async(u,h)=>{await a("readwrite",async d=>{await P(d.put({...h,key:u})),await c(d)})},"put"),remove:o(async u=>{await a("readwrite",h=>P(h.delete(u)))},"remove")}},"N"),wr=o(t=>{if(t!==!1){if(t)return t;if(!(typeof indexedDB>"u"))return _s()}},"L");var Cr=o(()=>{let t=null;return{get:o(()=>t,"get"),set:o(e=>{t=e},"set")}},"r");var qe=class{static{o(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,r){if(r===void 0){this.reset(e);return}this.values.set(e.key,r),this.notify(e.key,r)}reset(e){this.values.delete(e.key),this.notify(e.key,e.defaultValue)}clear(){this.values.clear(),this.subscribers.clear()}subscribe(e,r){let s=this.subscribers.get(e.key);return s||(s=new Set,this.subscribers.set(e.key,s)),s.add(r),()=>{s.delete(r),s.size===0&&this.subscribers.delete(e.key)}}notify(e,r){let s=this.subscribers.get(e);if(s)for(let i of s)try{i(r)}catch{}}};var kr=0,Ds="lunora-bridge",Us=1e3,Ns=3e3,je=class{static{o(this,"l")}bc;tabId;heartbeatInterval;leaderTimeout;knownLeader=void 0;leader=!1;running=!1;promotionPending=!1;lastHeartbeat=0;heartbeatTimer=void 0;leaderCheckTimer=void 0;onBecomeLeader;onStopBeingLeader;onConnectionStatus;onSubscriptionData;onLeaderClaimAnswered;onSubscriptionError;onSubscriptionSettled;constructor(e={}){if(kr+=1,this.tabId=`tab_${String(kr)}_${crypto.randomUUID()}`,this.heartbeatInterval=e.heartbeatInterval??Us,this.leaderTimeout=e.leaderTimeout??Ns,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??Ds),this.bc.addEventListener("message",r=>{this.handleMessage(r.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,r,s,i,n){this.leader&&this.broadcast({type:"subscription-data",tabId:this.tabId,key:e,data:r,...s===void 0?{}:{cursor:s},...i===void 0?{}:{epoch:i},...n===void 0?{}:{identity:n}})}broadcastSubscriptionError(e,r,s){this.leader&&this.broadcast({type:"subscription-error",tabId:this.tabId,key:e,error:r,...s===void 0?{}:{identity:s}})}broadcastSubscriptionSettled(e,r,s,i,n,a){this.leader&&this.broadcast({type:"subscription-settled",tabId:this.tabId,key:e,...r===void 0?{}:{cursor:r},...s===void 0?{}:{epoch:s},...i===void 0?{}:{lastMutationId:i},...n===void 0?{}:{clientId:n},...a===void 0?{}:{identity:a}})}broadcastConnectionStatus(e,r){this.leader&&this.broadcast({type:"connection-status",tabId:this.tabId,status:e,...r===void 0?{}:{identity:r}})}broadcast(e){this.bc?.postMessage(e)}handleMessage(e){switch(e.type){case"claim-leadership":{this.handleClaimLeadership(e);break}case"connection-status":{if(this.leader||e.tabId===this.tabId)break;this.onConnectionStatus?.(e.status,e.identity);break}case"heartbeat":{this.handleHeartbeat(e);break}case"subscription-data":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionData?.(e.key,e.data,e.cursor,e.epoch,e.identity);break}case"subscription-error":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionError?.(e.key,e.error,e.identity);break}case"subscription-settled":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionSettled?.(e.key,e.cursor,e.epoch,e.lastMutationId,e.clientId,e.identity);break}case"yield-leadership":{this.knownLeader===e.tabId&&(this.knownLeader=void 0,this.running&&!this.leader&&this.claimAndPromote());break}}}handleClaimLeadership(e){if(e.tabId!==this.tabId){if(this.leader){this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}),this.onLeaderClaimAnswered?.();return}this.knownLeader===void 0&&e.tabId<this.tabId&&(this.knownLeader=e.tabId,this.lastHeartbeat=e.ts)}}handleHeartbeat(e){if(e.tabId!==this.tabId){if(this.leader){this.resolveLeaderVsLeaderTieBreak(e);return}this.lastHeartbeat=e.ts,this.knownLeader=e.tabId}}resolveLeaderVsLeaderTieBreak(e){e.tabId<this.tabId?(this.leader=!1,this.knownLeader=e.tabId,this.lastHeartbeat=e.ts,this.onStopBeingLeader?.()):this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}becomeLeader(){this.leader||(this.leader=!0,this.knownLeader=this.tabId,this.lastHeartbeat=Date.now(),this.onBecomeLeader?.(),this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}))}sendHeartbeat(){this.leader&&this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}checkLeaderHealth(){if(!(!this.running||this.leader)){if(this.knownLeader===void 0){this.claimAndPromote();return}Date.now()-this.lastHeartbeat>this.leaderTimeout&&(this.knownLeader=void 0,this.claimAndPromote())}}claimAndPromote(){this.promotionPending||(this.promotionPending=!0,this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.promotionPending=!1,this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout))}};var dt="_id",lt="_creationTime",ft="page",Tr="pageDelta",qs=o(t=>{if(Array.isArray(t))return t;if(ht(t)&&Array.isArray(t[ft]))return t[ft]},"y"),js=o(t=>{let e;for(let r of t){let s=r[lt];if(typeof s=="number"){if(e!==void 0){if(s<e)return!0;if(s>e)return!1}e=s}}return!1},"l"),Ks=o((t,e)=>{let r=e[lt];if(typeof r!="number")return t.length;let s=js(t);for(let[i,n]of t.entries()){let a=n[lt];if(typeof a=="number"&&(s?a<r:a>r))return i}return t.length},"x"),Bs=o(t=>{if(typeof t!="object"||t===null)return;let e=t[dt];return typeof e=="string"?e:void 0},"A"),Er=o(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")},"b"),$s=o((t,e)=>{let r=[];for(let u of t){if(Bs(u)===void 0)return;r.push(u)}let{key:s,op:i,row:n}=e;if(i==="delete"){let u=r.filter(h=>h[dt]!==s);return u.length===r.length?[...r]:u}if(n===void 0)return;let a=[...r],c=r.findIndex(u=>u[dt]===s);return c===-1?a.splice(Ks(r,n),0,n):a[c]=n,a},"I"),Ir=o((t,e)=>{let r=qs(t);if(r===void 0)return;let s=$s(r,e);return s===void 0||Array.isArray(t)?s:{...t,[ft]:s}},"E");var Bc=new Set(Object.keys(Mt)),B=class extends y{static{o(this,"E")}constructor(e,r){super("INTERNAL",e,{data:r})}};var pt=o(t=>{let e=t?.data?.retryAfterMs;return typeof e=="number"&&Number.isFinite(e)?e:void 0},"u");var Hs=1024,Ke=o(t=>{let e=t.maxBuffer??Hs,r=[],s=[],i=!1,n,a=!1,c=o(()=>{let d=s.shift();if(!d)return!1;if(n)return d.reject(n),!0;if(r.length>0){let l=r.shift();return d.resolve({done:!1,value:l}),!0}return i?(d.resolve({done:!0,value:void 0}),!0):(s.unshift(d),!1)},"u"),u={complete(){if(!(i||n))for(i=!0;c(););},fail(d){if(!(i||n))for(n=d,r.length=0;c(););},push(d){if(!(i||n||a)){if(r.length>=e){u.fail(new y("STREAM_BACKPRESSURE",`stream buffer overflow (max=${e.toString()}); the consumer cannot keep up with the producer`));return}r.push(d),c()}}},h=o(()=>{if(!a){a=!0,i=!0,r.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(r.length>0){let d=r.shift();return Promise.resolve({done:!1,value:d})}return i?Promise.resolve({done:!0,value:void 0}):new Promise((d,l)=>{s.push({reject:l,resolve:d})})},return(){return h(),Promise.resolve({done:!0,value:void 0})}}}}}},"p");var Or=/^ /u,Rr=o(t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),"h"),Ws=o(t=>{let e="",r=[];for(let s of t.split(`
2
+ `))s.startsWith("event:")?e=s.slice(6).replace(Or,""):s.startsWith("data:")&&r.push(s.slice(5).replace(Or,""));return{data:r.join(`
3
+ `),event:e}},"S"),zs=o((t,e,r)=>{let s=e.params??{},i=t.path.split("/").map(c=>{if(!c.startsWith(":"))return c;let u=c.slice(1),h=s[u];if(h===void 0)throw new y("HTTP_STREAM_MISSING_PARAM",`httpStream: missing path param ":${u}" for route ${t.path}`);return encodeURIComponent(Rr(h))}).join("/"),n=new URLSearchParams;for(let[c,u]of Object.entries(e.searchParams??{}))u!==void 0&&n.set(c,Rr(u));let a=n.toString();return`${r.endsWith("/")?r.slice(0,-1):r}${i}${a===""?"":`?${a}`}`},"T"),Vs=o((t,e)=>{if(t.event==="complete")return e.complete(),!0;if(t.event==="error"){let r={};try{r=JSON.parse(t.data)}catch{}let s=typeof r.message=="string"?r.message:"stream error",i=typeof r.code=="string"?r.code:"HTTP_STREAM_ERROR";return e.fail(new y(i,s)),!0}if((t.event===""||t.event==="message")&&t.data!=="")try{e.push(S(JSON.parse(t.data)))}catch{return e.fail(new y("HTTP_STREAM_BAD_CHUNK","httpStream: malformed SSE chunk (invalid JSON)")),!0}return!1},"E"),Gs=o(async(t,e)=>{let r=t.getReader(),s=new TextDecoder,i="",n=!1,a=o(u=>{let h=n?`\r${u}`:u;n=h.endsWith("\r"),n&&(h=h.slice(0,-1)),i+=h.replaceAll(`\r
4
+ `,`
5
+ `)},"l"),c=o(()=>{let u=i.indexOf(`
6
+
7
+ `);for(;u!==-1;){let h=Ws(i.slice(0,u));if(i=i.slice(u+2),Vs(h,e))return!0;u=i.indexOf(`
8
+
9
+ `)}return!1},"d");for(;;){let{done:u,value:h}=await r.read();if(u)break;if(a(s.decode(h,{stream:!0})),c()){await r.cancel().catch(()=>{});return}}a(s.decode()),c()||e.fail(new y("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"))},"b"),Ar=o((t,e,r={})=>{let s=r.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!s)throw new y("INTERNAL","httpStream: no `fetch` implementation available");let i=zs(t,e??{},r.baseUrl??""),n=new AbortController,a;r.signal&&(r.signal.aborted?n.abort():(a=o(()=>{n.abort()},"l"),r.signal.addEventListener("abort",a,{once:!0})));let c=o(()=>{a&&r.signal?.removeEventListener("abort",a)},"d"),{handle:u,iterable:h}=Ke({maxBuffer:r.maxBuffer,onCancel:o(()=>{n.abort()},"onCancel")});return(async()=>{try{let d=await s(i,{headers:{accept:"text/event-stream",...r.headers},method:t.method,signal:n.signal});if(!d.ok){await d.body?.cancel().catch(()=>{}),u.fail(new y("HTTP_STREAM_STATUS",`httpStream: request failed (status ${d.status.toString()})`,{status:d.status}));return}if(!d.body){u.fail(new y("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}await Gs(d.body,u)}finally{c()}})().catch(d=>{if(n.signal.aborted){u.complete();return}if(d instanceof Error&&"code"in d){u.fail(d);return}u.fail(new y("HTTP_STREAM_TRANSPORT",d instanceof Error?d.message:String(d),{cause:d}))}),h},"_");var Js=/["\\\u0000-\u001F\uD800-\uDFFF]/,Pr=o(t=>Js.test(t)?JSON.stringify(t):`"${t}"`,"y"),mt=o(t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key \u2014 pass it as a string, or use stableWireKey");if(typeof t=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(typeof t=="string")return Pr(t);if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t)){let a="[";for(let c=0;c<t.length;c++)c>0&&(a+=","),a+=mt(t[c]);return a+"]"}let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype){let a=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${a} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}let r=t,s=Object.keys(r).sort(),i="{",n=!0;for(let a of s){let c=r[a];c!==void 0&&(n?n=!1:i+=",",i+=Pr(a),i+=":",i+=mt(c))}return i+"}"},"i"),J=o(t=>mt(E(t)),"u");var F=class t{static{o(this,"r")}static key(e,r,s){return`${e}::${J(r)}::${s??""}`}static keyOf(e){return`${e.fn.__lunoraRef}::${e.argsKey}::${e.shardKey??""}`}byKey=new Map;byId=new Map;get(e){return this.byKey.get(e)}getById(e){return this.byId.get(e)}add(e){this.byKey.set(t.keyOf(e),e),this.byId.set(e.id,e)}remove(e){let r=t.keyOf(e);this.byKey.get(r)===e&&this.byKey.delete(r),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}clear(){this.byKey.clear(),this.byId.clear()}};var yt=0,Fr=o(()=>yt,"L"),Y=o((t,e)=>{let r=t;for(let s of e)try{r=s.transform(r)}catch{}return r},"p"),z=o((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let r of t.callbacks)try{r(e)}catch{}}},"d"),bt=o((t,e)=>{let r;try{r=e(t.lastValue)}catch{return}let s={id:Symbol("optimistic"),transform:e},i=!1;t.optimisticLayers.push(s),z(t,r);let n=o(()=>{let c=t.optimisticLayers.findIndex(u=>u.id===s.id);return c===-1?!1:(t.optimisticLayers.splice(c,1),!0)},"a"),a=o(()=>{z(t,Y(t.serverBase,t.optimisticLayers))},"s");return{confirm:o(c=>{if(c===void 0){n();return}s.commitCursor=c,yt+=1,s.acknowledgedAt=yt,t.serverCursor!==void 0&&t.serverCursor>=c&&n()&&a()},"confirm"),rollback:o(()=>{i||(i=!0,n(),a())},"rollback")}},"y"),Be=o((t,e)=>{if(e===void 0||t.optimisticLayers.length===0)return!1;let r=t.optimisticLayers.length;return t.optimisticLayers=t.optimisticLayers.filter(s=>s.commitCursor===void 0||s.commitCursor>e),t.optimisticLayers.length!==r},"k"),Mr=o((t,e)=>{t.optimisticLayers.length!==0&&(t.optimisticLayers=t.optimisticLayers.filter(r=>r.acknowledgedAt===void 0||r.acknowledgedAt>e))},"h"),xr=o((t,e)=>{let r=[],s=[],i=o((n,a)=>t.get(F.key(n,a,e)),"c");return{confirms:r,rollbacks:s,store:{getAllQueries:o(n=>{let a=[];for(let c of t.all())c.fn.__lunoraRef===n.__lunoraRef&&(c.shardKey??"")===(e??"")&&a.push({args:c.args,value:c.lastValue});return a},"getAllQueries"),getQuery:o((n,a)=>i(n.__lunoraRef,a??{})?.lastValue,"getQuery"),setQuery:o((n,a,c)=>{let u=i(n.__lunoraRef,a??{});if(!u)return;let h=bt(u,()=>c);h&&(r.push(h.confirm),s.push(h.rollback))},"setQuery")}}},"v");var Qr=0,Ys=o(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();Qr+=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)}_${Qr.toString(36)}_${t}`},"d"),gt=o((t,e)=>t!==void 0&&e!==t,"f"),He=Ys,X=o((t,e,r,s)=>{if(t)try{t({error:r,mutationId:s,operation:e});return}catch{}console.warn(`[lunora] offline-queue persistence ${e} failed`,r)},"o"),$e=class{static{o(this,"l")}queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;version;items=[];constructor(e={},r={}){this.maxItems=e.maxItems??1e3,this.queueBeforeFirstConnect=e.queueBeforeFirstConnect??!1,this.onPersistenceError=e.onPersistenceError,this.persistence=r.persistence,this.onEvict=r.onEvict,this.onSizeChange=r.onSizeChange,this.version=r.version}get size(){return this.items.length}enqueue(e){let r=e;r.id??=He(),this.items.push(r),this.persistence?.append({args:r.args,...r.baselineSeq===void 0?{}:{baselineSeq:r.baselineSeq},clientId:r.clientId,functionPath:r.functionPath,id:r.id,identity:r.identity,shardKey:r.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(s=>{X(this.onPersistenceError,"append",s,r.id)}),this.evictOverflow(),this.notifySize()}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(a){throw X(this.onPersistenceError,"load",a),a}let r=[],s=new Set(this.items.map(a=>a.id));for(let a of e)if(!s.has(a.id)){if(gt(this.version,a.version)){this.persistence.remove(a.id).catch(c=>{X(this.onPersistenceError,"remove",c,a.id)});continue}s.add(a.id),r.push({args:a.args,baselineSeq:a.baselineSeq,clientId:a.clientId,functionPath:a.functionPath,id:a.id,identity:a.identity,reject:o(()=>{},"reject"),resolve:o(()=>{},"resolve"),shardKey:a.shardKey})}this.items.unshift(...r),this.evictOverflow(),this.notifySize();let i=new Set(this.items),n=new Set;for(let a of r)i.has(a)&&n.add(a.shardKey);return[...n]}restampIdentity(e,r){for(let s of this.items){if(s.identity!==e)continue;s.identity=r;let{id:i}=s;if(!this.persistence||i===void 0)continue;let n={args:s.args,...s.baselineSeq===void 0?{}:{baselineSeq:s.baselineSeq},clientId:s.clientId,functionPath:s.functionPath,id:i,identity:r,shardKey:s.shardKey,...this.version===void 0?{}:{version:this.version}};this.rewriteStamp(i,n).catch(a=>{X(this.onPersistenceError,"replace",a,i)})}}hasPending(e){return this.items.some(r=>e(r))}drain(e){if(!e){let i=[...this.items];return this.items.length=0,this.notifySize(),i}let r=[],s=[];for(let i of this.items)(e(i)?r:s).push(i);return this.items.length=0,this.items.push(...s),this.notifySize(),r}requeue(e){e.length!==0&&(this.items.unshift(...e),this.notifySize())}drainConflict(){let e=[],r=[];for(let s of this.items)if(s.precondition!==void 0&&!s.precondition()){let i=new Error("offline mutation skipped: precondition failed before replay");i.code="OFFLINE_PRECONDITION_FAILED",s.reject(i),e.push(s)}else r.push(s);return e.length>0&&(this.items.length=0,this.items.push(...r),this.notifySize()),e}clear(){for(let e of this.items){let r=new Error("CLIENT_CLOSED");r.code="CLIENT_CLOSED",e.reject(r)}this.items.length=0,this.notifySize()}async rewriteStamp(e,r){let s=this.persistence;if(s)try{await s.replace(r)}catch(i){X(this.onPersistenceError,"replace",i,e)}}evictOverflow(){for(;this.items.length>this.maxItems;){let e=this.items.shift();if(e){e.id&&this.persistence?.remove(e.id).catch(s=>{X(this.onPersistenceError,"remove",s,e.id)});let r=new Error("offline queue overflow");r.code="OFFLINE_QUEUE_OVERFLOW",e.reject(r),this.onEvict?.(e,r)}}}notifySize(){this.onSizeChange?.(this.items.length)}};var Xs="lunora-outbox",Zs="offline-mutations",vt="by_id",ei=o((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new y("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let r=t.databaseName??Xs,s=t.storeName??Zs,i=Ue(e,r,1,a=>{a.objectStoreNames.contains(s)||a.createObjectStore(s,{autoIncrement:!0}).createIndex(vt,"id",{unique:!0})}),n=Ne(i,s);return{append:o(async a=>{await n("readwrite",c=>P(c.add(a)))},"append"),clear:o(async()=>{await n("readwrite",a=>P(a.clear()))},"clear"),load:o(async()=>n("readonly",a=>P(a.getAll())),"load"),remove:o(async a=>{await n("readwrite",async c=>{let u=await P(c.index(vt).getKey(a));u!==void 0&&await P(c.delete(u))})},"remove"),replace:o(async a=>{await n("readwrite",async c=>{let u=await P(c.index(vt).getKey(a.id));u!==void 0&&await P(c.put(a,u))})},"replace")}},"w"),Lr=o((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return ei()}},"b");var St=o((t={},e=Math.random)=>{let r=t.initialDelayMs??250,s=t.maxDelayMs??3e4,i=t.jitter??!0,n=0;return{next(){let a=Math.min(s,r*2**n);if(n+=1,!i)return a;let c=a/2;return Math.floor(c+e()*(a-c))},reset(){n=0}}},"s");var _r=new Set(["RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Dr=new Set(["TOKEN_EXPIRED","UNAUTHENTICATED","UNAUTHORIZED"]),Ur=o(t=>Dr.has(t?.code??""),"D"),Nr=o(t=>{if(t instanceof B)return!0;let e=t?.code;return e===void 0||_r.has(e)||Dr.has(e)},"S"),qr=6e4,ti=1e3,jr=o(t=>{if(t===null)return;let e=Number(t);if(Number.isFinite(e))return e>0?e*1e3:void 0;let r=Date.parse(t);if(Number.isNaN(r))return;let s=r-Date.now();return s>0?s:void 0},"d"),ri={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},Se=o((t,e,r)=>{let s=jr(r),i=s===void 0?void 0:{retryAfterMs:s},n=`LunoraClient: response carried no error envelope (status ${t.toString()}${e?` ${e}`:""})`;return t<400||t>=500||t===408?new B(n,i):new y(ri[t]??"BAD_REQUEST",n,{data:i})},"O"),he=o(t=>{let e=t?.error;return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0},"M"),Kr=o(()=>new B("LunoraClient: batch slot carried no error envelope"),"p"),Br=o((t,e)=>{let r=jr(e);if(!(r===void 0||pt(t)!==void 0))return t.data===void 0?{retryAfterMs:r}:typeof t.data=="object"&&t.data!==null&&!Array.isArray(t.data)?{...t.data,retryAfterMs:r}:void 0},"N"),wt=o((t,e=Math.random)=>{let r=Math.min(ti*2**Math.max(t-1,0),qr);return Math.round(r*(.5+e()*.5))},"_"),si=o(t=>t instanceof B||_r.has(t?.code??""),"T"),$r=o((t,e,r)=>{let s=pt(t);return s!==void 0&&s>0?Math.min(s,qr):si(t)?wt(e,r):void 0},"v"),Hr=983040,Wr=o(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"h");var zr=o((t,e,r,s)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,r,s),n=i.present?J(i.value):void 0;return()=>{let a=t.peekActiveQuerySnapshot(e.__lunoraRef,r,s);return!i.present||!a.present?!0:J(a.value)===n}},"c");var Ct=500,ii=o(async t=>{let e=[],r;for(;;){let s=await t(r);if(e.push(...Array.isArray(s.records)?s.records:[]),s.truncated!==!0||typeof s.cursor!="string"||s.cursor.length===0)return e;if(s.cursor===r)throw new Error("collectPages: the list did not advance its cursor \u2014 refusing to page forever");r=s.cursor}},"Be"),Vr=o((t,e)=>{if(t.size<e)return;let r=t.keys().next().value;r!==void 0&&t.delete(r)},"J");new TextDecoder;var ni=new TextEncoder,ai=o(t=>vr(ni.encode(JSON.stringify(t))),"qe"),oi="x-lunora-expect-subject",ci=o(t=>ai({subject:t}),"We"),Gr=Symbol.for("lunora:session-change-listeners"),ui=o(()=>{let t=globalThis,e=t[Gr];return e===void 0&&(e=new Set,t[Gr]=e),e},"$e"),hi=o(t=>{let e=ui();return e.add(t),()=>{e.delete(t)}},"je"),te=class{static{o(this,"R")}listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){let[r]=e;for(let s of this.listeners)try{s(r)}catch{}}clear(){this.listeners.clear()}},di=o(t=>{let{afterFailedAttempts:e,intervalMs:r,onReachable:s,onStateChange:i,poll:n}=t,a=r>0&&e>0,c=0,u,h=!1,d=!1,l=o(()=>{u!==void 0&&(clearInterval(u),u=void 0,h=!1,i())},"u"),f=o(m=>{if(u!==void 0){if(!m){l();return}h||(h=!0,i()),s()}},"f"),p=o(()=>{d||(d=!0,n().then(f).finally(()=>{d=!1}).catch(()=>{}))},"p");return{isPolling:o(()=>u!==void 0&&h,"isPolling"),noteFailedOpen:o(()=>{c+=1,!(!a||u!==void 0||c<e)&&(u=setInterval(p,r),i(),p())},"noteFailedOpen"),noteOpen:o(()=>{c=0,l()},"noteOpen"),stop:l}},"Ge"),li="/_lunora/rpc",kt="/_lunora/rpc-batch",fi="/_lunora/ws",Tt=o(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"Q"),we=o(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"P"),Jr=Symbol("lunora.unmergeableDelta"),pi=o((t,e)=>{for(let r of e)r.op==="delete"?t.delete(r.key):r.value!==void 0&&t.set(r.key,r.value)},"Je"),mi="lunora-ping",yi=3e4,bi=1e4,gi=5e3,vi=3,Si=250,wi=5e3,Ci=64,ki=3,Ti=1e4,Ei=8,Ii="/_lunora/admin/shard-traffic",Oi="/_lunora/admin/scheduled",Ri="/_lunora/admin/scheduled/status",Ai="/_lunora/admin/scheduled/ws",Pi="/_lunora/admin/scheduled/cancel",Yr="/_lunora/admin/scheduled/dead",Fi="/_lunora/admin/scheduled/dead/retry",Mi="/_lunora/admin/scheduled/dead/cancel",xi="/_lunora/admin/workflows/instances",Qi="/_lunora/admin/workflows/instance",Li="/_lunora/admin/workflows/status",Et="/_lunora/admin/storage",_i="/_lunora/admin/storage/url",Di="/_lunora/admin/storage/buckets",Ui="/_lunora/admin/functions",Ni="/_lunora/admin/cron-jobs",qi="/_lunora/admin/cron-jobs/run",ji="/_lunora/admin/openapi",Ki="/_lunora/admin/openrpc",Bi="/_lunora/admin/global/tables",$i="/_lunora/admin/global/table",Hi="/_lunora/admin/global/facet",Wi="/_lunora/admin/vector/indexes",zi="/_lunora/admin/vector/query",Vi="/_lunora/admin/logs/archive",Gi="/_lunora/admin/kv/namespaces",Ji="/_lunora/admin/kv/keys",It="/_lunora/admin/kv/value",Yi="/_lunora/admin/auth/users",Xi="/_lunora/admin/auth/sessions",Zi="/_lunora/admin/auth/users/create",en="/_lunora/admin/auth/users/role",tn="/_lunora/admin/auth/users/ban",rn="/_lunora/admin/auth/users/unban",sn="/_lunora/admin/auth/users/password",nn="/_lunora/admin/auth/users/remove",an="/_lunora/admin/auth/users/impersonate",on="/_lunora/admin/auth/sessions/revoke",cn="/_lunora/admin/auth/sessions/revoke-all",un="/_lunora/admin/auth/capabilities",hn="/_lunora/admin/auth/users/update",dn="/_lunora/admin/auth/accounts",ln="/_lunora/admin/auth/accounts/unlink",fn="/_lunora/admin/auth/passkeys",pn="/_lunora/admin/auth/passkeys/delete",mn="/_lunora/admin/auth/two-factor/disable",yn="/_lunora/admin/auth/organizations",bn="/_lunora/admin/auth/organizations/members",gn="/_lunora/admin/auth/organizations/invitations",vn="/_lunora/admin/auth/organizations/members/remove",Sn="/_lunora/admin/auth/organizations/invitations/cancel",wn="/_lunora/admin/auth/config",Cn="/_lunora/admin/auth/sign-up-invitations",kn="/_lunora/admin/auth/sign-up-invitations/create",Tn="/_lunora/admin/auth/sign-up-invitations/revoke",En="/_lunora/admin/auth/organizations/create",In="/_lunora/admin/auth/organizations/update",On="/_lunora/admin/auth/organizations/remove",Rn="/_lunora/admin/auth/organizations/members/add",An="/_lunora/admin/auth/organizations/members/invite",Pn="/_lunora/admin/auth/organizations/members/role",Fn="/_lunora/admin/auth/organizations/teams",Mn="/_lunora/admin/auth/organizations/teams/create",xn="/_lunora/admin/auth/organizations/teams/update",Qn="/_lunora/admin/auth/organizations/teams/remove",Ln="/_lunora/admin/auth/organizations/teams/members",_n="/_lunora/admin/auth/organizations/teams/members/add",Dn="/_lunora/admin/auth/organizations/teams/members/remove",Un="/_lunora/admin/auth/organizations/roles",Nn="/_lunora/admin/auth/organizations/roles/create",qn="/_lunora/admin/auth/organizations/roles/update",jn="/_lunora/admin/auth/organizations/roles/remove",Kn="/api/auth",Bn="/get-session",Xr=o(t=>t==="connected"||t==="polling","ee"),$n=o((t,e,r)=>t!==null||e&&r===null,"Es"),Zr=o(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"te"),Z=o((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"C"),R=o((t,e)=>{let r=new URLSearchParams;for(let[i,n]of Object.entries(e))n!==void 0&&n!==""&&r.set(i,String(n));let s=r.toString();return s===""?t:`${t}?${s}`},"S"),Hn=[Tr],g=o(t=>t??"","l"),is=o((t,e)=>{let r=t.error,s=typeof r?.code=="string"?r.code:void 0,i=typeof r?.message=="string"?r.message:void 0;return{code:s,messageText:(typeof t.message=="string"?t.message:void 0)??i??e}},"ae"),Wn=o(t=>{let{code:e,messageText:r}=is(t,"stream error");return e===void 0?new Error(r):new y(e,r)},"_s"),es=o(t=>{let{code:e,messageText:r}=is(t,"subscription error");return{message:r,...e===void 0?{}:{code:e}}},"se");function Ot(t){if(t!==void 0)return e=>{t(e)}}o(Ot,"q");var ne=o((t,e)=>{for(let r of t)try{r(e)}catch{}},"E"),zn=new TextDecoder,Vn=o(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return zn.decode(t)},"Os"),_=o((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"v"),Pt=o(t=>{let e=new Error(t.message??"request failed");return e.code=t.code,t.data!==void 0&&(e.data=S(t.data)),t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),e},"W"),ts=o((t,e)=>{let r=Pt(t),s=Br(r,e);return s!==void 0&&(r.data=s),r},"re"),ee=o((t,e)=>{try{return E(t)}catch(r){let s=r instanceof Error?r.message:String(r);throw new TypeError(`LunoraClient: cannot encode ${e} \u2014 ${s}`,r instanceof Error?{cause:r}:void 0)}},"k"),Gn=1e4,rs=o(async t=>{let e=new AbortController,r,s=new Promise((i,n)=>{r=setTimeout(()=>{e.abort(),n(new TypeError("LunoraClient: poll timed out"))},Gn)});try{return await Promise.race([t(e.signal),s])}catch(i){throw e.signal.aborted?new TypeError("LunoraClient: poll timed out"):i}finally{clearTimeout(r)}},"ie"),ss=o(t=>{try{return E(t),!0}catch{return!1}},"ne"),Rt=o(t=>"args"in t?{...t,args:S(t.args)}:t,"K"),ns=o(t=>{let e=he(t);return e===void 0?Kr():Pt(e)},"oe"),Jn=o((t,e)=>{let r=Array.from({length:e});for(let s of t){if(typeof s.id!="number"||s.id<0||s.id>=e)continue;let i=s.body;r[s.id]=i!==void 0&&"error"in i?{error:ns(i),ok:!1}:{ok:!0,value:S(i?.result)}}return r.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},"Ps"),Yn=Promise.resolve(),At=class t{static{o(this,"ce")}static MAX_POKE_BUFFERS=256;static createClientQuery(e,r){return{defaultValue:r,key:e}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new F;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;subjectToken=null;sessionProbesInFlight=0;sessionProbeGeneration=0;identityQuestions=0;identityAnsweredAt=0;releaseSessionChangeListener;warnedIdentityDisagreement=!1;identityResolutionExpected=!1;identitySettled=!1;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new te;statusListeners=new te;tokenExpiredListeners=new te;identityChangeListeners=new te;authRefusalNotifiedFor;mutationSettledListeners=new te;pendingChangeListeners=new te;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??Z(Zr(e.url),fi),this.wsToken=e.wsToken;let r=e.authBasePath??Kn;this.authBasePath=r.endsWith("/")?r.slice(0,-1):r,this.fetchImpl=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=e.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=e.bookmarkStorage??Cr(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??yi,this.connectTimeoutMs=e.connectTimeoutMs??bi,this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??gi,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??vi,this.defaultConnectionContext=e.connectionContext,this.persistence=Lr(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=wr(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new qe,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=Yn),this.offlineQueue=new $e(e.offlineQueue,{onEvict:o((s,i)=>{this.emitItemSettled(s,"rejected",i)},"onEvict"),onSizeChange:o(s=>{this.pendingChangeListeners.emit(s)},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${He()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=hi(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,r){let s=this.authToken!==e,i=this.identityFingerprint(),n=this.authSubject===void 0||this.subjectToken===this.authToken,a=this.subjectAwaitingReconfirm(),c=this.isKnownNobody();this.authToken=e,this.applySubject(e,r);let u=this.identityFingerprint();u!==i&&(!s&&e!==null&&n?(this.restampQueuedIdentity(i,u),this.restampWatermarks(i,u),this.restampConnectionIdentity(i,u),this.reseedFromHydratedCache()):!s&&e===null&&i===null&&n&&!c?(this.restampWatermarks(i,u),this.restampConnectionIdentity(i,u),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(i),$n(i,c,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(a),s&&this.authTokenListeners.emit(e),(u!==i||s||a)&&this.offlineQueue.size>0&&Xr(this.computeStatus())&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}expectIdentityResolution(){this.identityResolutionExpected=!0}currentBaseline(e){return this.baselineCursorFor(e)}replayIdentityVerdict(e){if(this.subjectAwaitingReconfirm())return"unknown";let r=this.identityFingerprint();return r===null&&this.identityUnresolved()?"unknown":e===r||e!==void 0&&this.isSameCredentialUnderTokenHash(e)?"match":r===null?"unknown":"mismatch"}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,r,s){let i=s?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new y("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let n=s?.shardKey??"",a=this.identityFingerprint(),c,u=await this.rpc(e,r,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:o(h=>{c=h},"onMutationAck")});if(c!==void 0&&c>(this.clientWatermarks.get(a??"")?.get(n)??0)){let h=this.clientWatermarks.get(a??"");h===void 0&&(Vr(this.clientWatermarks,Ei),h=new Map,this.clientWatermarks.set(a??"",h)),h.set(n,c)}return{applied:c===void 0||c===i,result:u}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}onIdentityChange(e){return this.identityChangeListeners.add(e)}async getCurrentUser(){if(this.identityResolutionExpected=!0,this.closed||!this.fetchImpl)return this.identitySettled=!0,null;let e={},r=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`),this.sessionProbesInFlight+=1,this.identityQuestions+=1,this.sessionProbeGeneration=this.identityQuestions;let s=this.sessionProbeGeneration;try{let i=await this.fetchImpl(Z(this.url,`${this.authBasePath}${Bn}`),{credentials:"include",headers:e,method:"GET"});if(!i.ok)return this.identitySettled=!0,i.status===401&&this.adoptResolvedSubject(r,null,s),null;let n=(await i.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(r,n,s),n}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.bounceShardSockets())}setConnectionContext(e,r={}){this.assertLeaderOwnedSurface("setConnectionContext");let s=g(r.shardKey);e===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,e),this.refreshConnectionContext(s)}acquireConnectionContext(e,r={}){if(this.followsAnotherTab())return()=>{};let s=g(r.shardKey),i={context:e},n=this.connectionContextHolders.get(s);n?n.push(i):this.connectionContextHolders.set(s,[i]),this.refreshConnectionContext(s);let a=!1;return()=>{if(a)return;a=!0;let c=this.connectionContextHolders.get(s);if(!c)return;let u=c.indexOf(i);u!==-1&&c.splice(u,1),c.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s)}}whisperSubscribe(e,r,s={}){this.assertLeaderOwnedSurface("whisperSubscribe");let i=g(s.shardKey),n=this.whisperHandlers.get(i);n||(n=new Map,this.whisperHandlers.set(i,n));let a=n.get(e),c=a===void 0;if(a||(a=new Set,n.set(e,a)),a.add(r),this.ensureSocket(s.shardKey),c){let u=this.getConnection(s.shardKey);u&&_(u,{topic:e,type:"whisper_subscribe"})}return()=>{let u=this.whisperHandlers.get(i),h=u?.get(e);if(!h?.delete(r)||h.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let d=this.getConnection(s.shardKey);d&&_(d,{topic:e,type:"whisper_unsubscribe"})}}whisper(e,r,s={}){this.assertLeaderOwnedSurface("whisper"),this.ensureSocket(s.shardKey);let i=this.getConnection(s.shardKey);i&&_(i,{data:ee(r??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"})}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let r=this.statusListeners.add(e);return e(this.computeStatus()),r}pendingCount(){return this.offlineQueue.size}debug(){let e=[],r=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...r?.keys()??[]]);for(let n of s){let a=this.connections.get(n);e.push({confirmedMutationWatermark:r?.get(n)??0,hasSocket:a?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:a?.wasEverConnected??!1,wsState:a?.wsState??"idle"})}let i=this.subscriptions.all().map(n=>({acked:n.acked,functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(let n of this.shapeSubscriptions.values())i.push({acked:n.serverCursor!==void 0,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,a)=>(n.shardKey??"").localeCompare(a.shardKey??"")),subscriptions:i.toSorted((n,a)=>n.functionPath.localeCompare(a.functionPath))}}onPendingChange(e){let r=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),r}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,r){this.clientQueryStore.set(e,r)}subscribeClientQuery(e,r){return this.clientQueryStore.subscribe(e,r)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,r,s){return zr(this,e,r,s)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,r,s){if(!this.readyResolved)return;let i=J(r),n=ie(e,i,s),a=this.hydratedQueryCache.get(n);if(a!==void 0)return this.cachedQueryMatchesIdentity(a)?a.value:void 0}peekActiveQuerySnapshot(e,r,s){let i=F.key(e,r,s),n=this.subscriptions.get(i);return{present:n!==void 0,value:n?.lastValue}}async query(e,r,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,r,s.shardKey,{attachBookmark:!0})}async batch(e){return this.sendBatch(e)}async mutation(e,r,s={}){let{value:i}=await this.runMutation(e,r,s);return i}canQueueOffline(e){let{wasEverConnected:r}=this.connectionGateState(e);return this.WebSocketImpl!==void 0&&(r||this.offlineQueue.queueBeforeFirstConnect)}async action(e,r,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,r,s.shardKey,{attachBookmark:!0,captureBookmark:!0})}async importRows(e,r,s={}){this.assertOpen();let i=Math.max(1,Math.trunc(s.chunkSize??500)),n=s.toArgs??(d=>({rows:d})),a=r.length,c=0,u=0,h=0;for(let d=0;d<a;d+=i){let l=r.slice(d,d+i),f=h,{committed:p}=await this.runMutation(e,n(l),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(f)}`},shardKey:s.shardKey});h+=1,c+=l.length,p&&(u+=l.length),s.onProgress?.({done:c,total:a})}return{chunks:h,imported:u,queued:c-u}}async shardTraffic(e){this.assertOpen();let r=await this.adminFetch(Ii,"POST",{table:e});return{failed:r.failed??0,ok:r.ok??0,shards:r.shards??[]}}async listScheduledJobs(){return this.assertOpen(),((await this.adminFetch(Oi,"GET")).records??[]).map(e=>Rt(e))}async schedulerStatus(){this.assertOpen();let e=await this.adminFetch(Ri,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}}async cancelScheduledJob(e){return this.assertOpen(),{cancelled:(await this.adminFetch(Pi,"POST",{id:e})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await ii(async e=>await this.adminFetch(e===void 0?Yr:`${Yr}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>Rt(e))}async retryDeadJob(e){return this.assertOpen(),{retried:(await this.adminFetch(Fi,"POST",{id:e})).retried===!0}}async removeDeadJob(e){return this.assertOpen(),{removed:(await this.adminFetch(Mi,"POST",{id:e})).removed===!0}}async listWorkflowInstances(e){this.assertOpen();let r=new URLSearchParams({name:e.name});e.status!==void 0&&r.set("status",e.status),e.page!==void 0&&r.set("page",String(e.page)),e.perPage!==void 0&&r.set("perPage",String(e.perPage));let s=await this.adminFetch(`${xi}?${r.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}}async getWorkflowInstance(e){this.assertOpen();let r=new URLSearchParams({id:e.id,name:e.name}),s=await this.adminFetch(`${Qi}?${r.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??e.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}}async setWorkflowInstanceStatus(e){return this.assertOpen(),{status:(await this.adminFetch(Li,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let r=Z(Zr(this.url),Ai),s=St(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},n,a=!1,c=o(()=>{a||this.closed||(n=setTimeout(d,s.next()))},"a"),u=o(f=>{if(a||this.WebSocketImpl===void 0)return;let p=f===void 0?r:`${r}?token=${encodeURIComponent(f)}`;this.openManagedSocket(i,p,this.connectTimeoutMs,{onClose:o(()=>{c()},"onClose"),onMessage:o(m=>{let b;try{b=JSON.parse(typeof m.data=="string"?m.data:"")}catch{return}b.type==="jobs"&&Array.isArray(b.records)&&(s.reset(),e(b.records.map(w=>Rt(w))))},"onMessage")})},"o"),h=o(async f=>{let p;try{p=await f()}catch{c();return}u(p)},"h"),d=o(()=>{if(a||this.WebSocketImpl===void 0)return;let{wsToken:f}=this;if(typeof f=="function"){h(f).catch(()=>{});return}u(f)},"d");d();let l=o(()=>{a=!0,n!==void 0&&(clearTimeout(n),n=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),this.stopHeartbeat(i),i.socket?.close(),i.socket=void 0},"u");return this.adminSocketTeardowns.add(l),()=>{this.adminSocketTeardowns.delete(l),l()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(Ui,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(Ni,"GET")).jobs??[]}async runCronJob(e){this.assertOpen();let r=await this.adminFetch(qi,"POST",{name:e});return{name:r.name??e,ran:r.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(ji,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(Ki,"GET")}async listStorageObjects(e={}){this.assertOpen();let r=R(Et,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await this.adminFetch(r,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(e,r){this.assertOpen();let s=`${Et}?key=${encodeURIComponent(e)}${Tt(r?.bucket)}`,i=await this.adminFetch(s,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(Di,"GET")).buckets??[]}async uploadStorageObject(e){this.assertOpen();let r=`${Et}?key=${encodeURIComponent(e.key)}${Tt(e.bucket)}`,s=await this.adminFetch(r,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}}async signedStorageUrl(e,r){this.assertOpen();let s=r?.expiresInSeconds,i=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,n=`${_i}?key=${encodeURIComponent(e)}${i}${Tt(r?.bucket)}`,a=await this.adminFetch(n,"GET");if(typeof a.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return a.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(Bi,"GET")}async readGlobalTablePage(e){this.assertOpen();let r=new URLSearchParams({table:e.table});return e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&r.set("filters",JSON.stringify(E(e.filters))),S(await this.adminFetch(`${$i}?${r.toString()}`,"GET"))}async facetGlobalColumn(e){this.assertOpen();let r=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&r.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&r.set("filters",JSON.stringify(E(e.filters))),S(await this.adminFetch(`${Hi}?${r.toString()}`,"GET"))}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch(Wi,"GET")).indexes??[]}async queryVectorIndex(e){return this.assertOpen(),(await this.adminFetch(zi,"POST",e)).matches??[]}async queryLogArchive(e={}){this.assertOpen();let r=await this.adminFetch(Vi,"POST",e);return{nextCursor:r.nextCursor,rows:r.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(Gi,"GET")).namespaces??[]}async listKvKeys(e){this.assertOpen();let r=R(Ji,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await this.adminFetch(r,"GET")}async getKvValue(e){this.assertOpen();let r=R(It,{key:e.key,namespace:e.namespace});return await this.adminFetch(r,"GET")}async putKvValue(e){this.assertOpen(),await this.adminFetch(It,"PUT",e)}async deleteKvKey(e){this.assertOpen();let r=R(It,{key:e.key,namespace:e.namespace});await this.adminFetch(r,"DELETE")}async listAuthUsers(e={}){this.assertOpen();let r=R(Yi,{filterField:e.filterField,filterValue:e.filterValue,limit:e.limit,offset:e.offset,search:e.search,searchField:e.searchField,sortBy:e.sortBy,sortDirection:e.sortDirection});return await this.adminFetch(r,"GET")}async createAuthUser(e){return await this.adminFetch(Zi,"POST",e)}async setAuthUserRole(e){return await this.adminFetch(en,"POST",e)}async banAuthUser(e){return await this.adminFetch(tn,"POST",e)}async unbanAuthUser(e){return await this.adminFetch(rn,"POST",e)}async setAuthUserPassword(e){await this.adminFetch(sn,"POST",e)}async removeAuthUser(e){await this.adminFetch(nn,"POST",e)}async impersonateAuthUser(e){return await this.adminFetch(an,"POST",e)}async revokeAuthSession(e){await this.adminFetch(on,"POST",e)}async revokeAuthUserSessions(e){await this.adminFetch(cn,"POST",e)}async getAuthCapabilities(){return await this.adminFetch(un,"GET")}async updateAuthUser(e){return await this.adminFetch(hn,"POST",e)}async listAuthAccounts(e){return await this.adminFetch(R(dn,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){await this.adminFetch(ln,"POST",e)}async listAuthPasskeys(e){return await this.adminFetch(R(fn,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){await this.adminFetch(pn,"POST",e)}async disableAuthTwoFactor(e){await this.adminFetch(mn,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(R(yn,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){let r=R(bn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async listAuthOrgInvitations(e){let r=R(gn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async listAuthSignUpInvitations(e={}){let r=R(Cn,{limit:e.limit,offset:e.offset});return await this.adminFetch(r,"GET")}async createAuthSignUpInvitation(e){return await this.adminFetch(kn,"POST",e)}async revokeAuthSignUpInvitation(e){await this.adminFetch(Tn,"POST",e)}async removeAuthOrgMember(e){await this.adminFetch(vn,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(Sn,"POST",e)}async getAuthConfig(){return await this.adminFetch(wn,"GET")}async createAuthOrganization(e){return await this.adminFetch(En,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(In,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(On,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch(Rn,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(An,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch(Pn,"POST",e)}async listAuthOrgTeams(e){let r=R(Fn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(Mn,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch(xn,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(Qn,"POST",e)}async listAuthOrgTeamMembers(e){let r=R(Ln,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(r,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(_n,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(Dn,"POST",e)}async listAuthOrgRoles(e){let r=R(Un,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async createAuthOrgRole(e){return await this.adminFetch(Nn,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(qn,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(jn,"POST",e)}async listAuthSessions(e={}){this.assertOpen();let r=R(Xi,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(r,"GET")}subscribe(e,r,s,i={}){this.assertOpen();let n=r??{},a=F.key(e.__lunoraRef,n,i.shardKey),c=this.subscriptions.get(a),u=Ot(s),h=Ot(i.onError),d=Ot(i.onCheckpoint);if(!c){this.nextSubId+=1;let f=`sub_${this.nextSubId.toString()}`,p=J(n),m=this.takeHydratedCache(e.__lunoraRef,p,i.shardKey);c={acked:!1,args:n,argsKey:p,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:f,lastValue:m?.value,optimisticLayers:[],serverBase:m?.value,serverCursor:m?.serverCursor,shardKey:i.shardKey,wireArgs:ee(n,`args for '${e.__lunoraRef}'`),...m?.serverEpoch===void 0?{}:{serverEpoch:m.serverEpoch}},this.subscriptions.add(c),m!==void 0&&this.cacheSeededQueries.set(a,m)}if(c.callbacks.add(u),h&&c.errorCallbacks.add(h),d&&c.checkpointCallbacks.add(d),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let l=c;return()=>{l.callbacks.delete(u),h&&l.errorCallbacks.delete(h),d&&l.checkpointCallbacks.delete(d),l.callbacks.size===0&&(this.sendOrQueueUnsubscribe(l.shardKey,l.id,"unsubscribe"),this.returnCacheSeed(F.keyOf(l)),this.subscriptions.remove(l))}}subscribeShape(e,r,s={}){if(this.assertOpen(),this.followsAnotherTab()){let{onError:a}=s;return a!==void 0&&queueMicrotask(()=>{a({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;let i=`shape_${this.nextShapeId.toString()}`,n={args:e.args,callbacks:new Set([r]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:i,name:e.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:e.args===void 0?void 0:ee(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,n),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(n.shardKey,i,"shape_unsubscribe")}}stream(e,r,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new y("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;let i=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=s,a=r??{},{handle:c,iterable:u}=Ke({maxBuffer:s.maxBuffer,onCancel:o(()=>{this.cancelStream(i,n)},"onCancel")});this.ensureSocket(n);let h=this.getConnection(n),d={id:i,query:{args:ee(a,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"},l={durable:s.durable===!0,generation:void 0,handle:c,lastSeq:0,message:d,shardKey:n,started:!1};this.streams.set(i,l);let f=h?.wsState==="open"&&_(h,d);if(l.started=f,!f&&h===void 0)return this.streams.delete(i),c.fail(new y("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),u;if(!f){for(h.pendingStreams=h.pendingStreams??[];h.pendingStreams.length>=Ci;){let p=h.pendingStreams.shift()?.id,m=p?this.streams.get(p):void 0;m&&(m.handle.fail(new y("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(p))}h.pendingStreams.push(d)}return u}httpStream(e,r,s={}){if(this.closed)throw new y("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return Ar(e,r,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(let e of this.streams.values())e.handle.fail(new y("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(let e of this.connections.values())this.teardownConnection(e);for(let e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear();for(let e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new y("INTERNAL","LunoraClient is closed")}followsAnotherTab(){let e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;let r=e.leaderTabId;return r!==void 0&&r!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new y("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}teardownConnection(e){e.polling.stop();let r=g(e.shardKey);for(let[s,i]of this.streams)g(i.shardKey)===r&&(i.handle.fail(new y("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(s));if(e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.clearResubscribeQueue(e),this.clearConnectionTimers(e),this.stopHeartbeat(e),e.socket){try{e.socket.close()}catch{}e.socket=void 0}e.wsState="closed"}createTabCoordinator(){let e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new je({channelName:e,onBecomeLeader:o(()=>{for(let r of this.subscriptions.all())this.ensureSocket(r.shardKey),this.queueResubscribe(r);for(let r of this.queuedOfflineShardKeys)this.ensureSocket(r);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},"onBecomeLeader"),onStopBeingLeader:o(()=>{for(let[r,s]of this.connections)this.teardownConnection(s),this.connections.delete(r);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},"onStopBeingLeader"),onConnectionStatus:o((r,s)=>{if(s!==void 0&&s!==this.identityFingerprint())return;let i=r==="connected"&&this.leaderStatus!=="connected"||r==="polling"&&this.leaderStatus!=="connected"&&this.leaderStatus!=="polling";this.leaderStatus=r,r==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),i&&this.flushAllOfflineQueues()},"onConnectionStatus"),onSubscriptionData:o((r,s,i,n,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;let c=this.subscriptions.get(r);c&&(c.serverBase=s,this.dropCacheSeed(r),i!==void 0&&(c.serverCursor=i,n!==void 0&&(c.serverEpoch=n),Be(c,i)),z(c,Y(s,c.optimisticLayers)))},"onSubscriptionData"),onLeaderClaimAnswered:o(()=>{this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},"onLeaderClaimAnswered"),onSubscriptionError:o((r,s,i)=>{if(i!==void 0&&i!==this.identityFingerprint())return;let n=this.subscriptions.get(r);n&&ne(n.errorCallbacks,s)},"onSubscriptionError"),onSubscriptionSettled:o((r,s,i,n,a,c)=>{if(c!==void 0&&c!==this.identityFingerprint())return;let u=this.subscriptions.get(r);if(u){this.ackAndAdvanceCursor(u,s,i),n!==void 0&&a===this.clientId&&(u.lastMutationId=Math.max(u.lastMutationId??0,n));for(let h of u.checkpointCallbacks)h({checkpoint:u.serverCursor,mutationId:u.lastMutationId})}},"onSubscriptionSettled")})}async sendBatch(e,r){if(this.assertOpen(),!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let s=await this.fetchImpl(Z(this.url,kt),{body:JSON.stringify({calls:e.map((c,u)=>({args:ee(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:r}),i=s.headers.get("x-d1-bookmark");i&&this.bookmark.set(i);let n;try{n=await s.json()}catch{throw new y("INTERNAL",`LunoraClient: batch response was not JSON (status ${s.status.toString()})`)}let a=he(n);if(!s.ok||a!==void 0&&!n.results)throw a!==void 0?Pt(a):new y("INTERNAL",`LunoraClient: batch request failed (status ${s.status.toString()})`);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 Jn(n.results??[],e.length)}async runMutation(e,r,s){this.assertOpen();let i=r,n=s.mutationId??He(),a=s.replayBaseline===void 0?this.baselineCursorFor(s.shardKey):s.replayBaseline??void 0,{confirms:c,rollbacks:u}=this.applyOptimisticUpdates(e.__lunoraRef,i,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,r,s.shardKey,u,c);let h=this.offlineFlushes.get(g(s.shardKey));h!==void 0&&await h;let{hasSocket:d,polling:l,wasEverConnected:f,wsState:p}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:m}=this.offlineQueue,b=f||m,w=this.WebSocketImpl!==void 0&&b,k=p==="connecting"&&b&&!l,M=p!=="open"&&!d&&w&&!l,D=w&&s.replayBaseline===void 0&&this.hasPendingWriteAhead(s.shardKey),N=o(async()=>this.enqueueOfflineMutation(e,i,s.shardKey,a,n,u,c,s.precondition,s.mutationId),"$");if(M||k||D)return N();try{let A,de=await this.rpc(e.__lunoraRef,i,s.shardKey,{baselineSeq:a,captureBookmark:!0,...this.replayExpectation(s.replayIdentity),mutationId:n,onCommitCursor:o(x=>{A=x},"onCommitCursor")});for(let x of c)x(A);return{committed:!0,value:de}}catch(A){if(l&&w&&A instanceof TypeError&&ss(i))return N();throw this.noteIdentityMismatch(A),we(u),A}}async enqueueOfflineMutation(e,r,s,i,n,a,c,u,h){let d=this.identityFingerprint();if(this.outbox){this.outboxMutationCounter+=1;let l=this.outboxMutationCounter;try{await this.outbox.enqueue({args:r,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:h??`${this.clientId}:${String(l)}`,identity:d,mutationId:l,...a.length>0&&{onRejected:o(()=>{we(a)},"onRejected")},shardKey:s})}catch(f){throw we(a),f instanceof Error?f:new Error(String(f))}for(let f of c)f(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((l,f)=>{let p={args:r,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:n,clientId:this.clientId,identity:d,precondition:u,onCommit:o(m=>{for(let b of c)b(m)},"onCommit"),reject:o(m=>{this.queuedIdentities.delete(n),we(a),f(m instanceof Error?m:new Error(String(m)))},"reject"),resolve:l,shardKey:s};this.offlineQueue.enqueue(p),this.queuedOfflineShardKeys.add(s),p.id!==void 0&&this.queuedIdentities.set(p.id,d)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;let r=g(e);return this.offlineQueue.hasPending(s=>g(s.shardKey)===r)}async hydratePersistedQueue(){try{let e=await this.offlineQueue.hydrate();for(let r of e)this.queuedOfflineShardKeys.add(r),this.ensureSocket(r)}catch{}}hydrateAsOutboxLeader(){let e=o(()=>{this.hydratePersistedQueue().catch(()=>{})},"e"),r=globalThis.navigator?.locks;if(!r){e();return}r.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{let e=await this.queryCache.load(),r=new Map;for(let s of this.subscriptions.all())r.set(ie(s.fn.__lunoraRef,s.argsKey,s.shardKey),s);for(let{key:s,...i}of e){if(gt(this.persistenceVersion,i.version)){this.queryCache.remove(s).catch(()=>{});continue}let n=r.get(s);if(n&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(n,i);continue}this.hydratedQueryCache.set(s,i)}}catch{}}seedSubscriptionFromCache(e,r){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(r)||(e.serverBase=r.value,e.serverCursor=r.serverCursor,r.serverEpoch!==void 0&&(e.serverEpoch=r.serverEpoch),this.cacheSeededQueries.set(ie(e.fn.__lunoraRef,e.argsKey,e.shardKey),r),z(e,Y(r.value,e.optimisticLayers)))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}returnCacheSeed(e){let r=this.cacheSeededQueries.get(e);r!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,r))}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(let[e,r]of this.cacheSeededQueries){let s=this.subscriptions.get(e);s!==void 0&&(s.serverBase=void 0,s.serverCursor=void 0,s.serverEpoch=void 0,z(s,Y(void 0,s.optimisticLayers))),this.hydratedQueryCache.set(e,r)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,r,s){let i=ie(e,r,s),n=this.hydratedQueryCache.get(i);if(!(n===void 0||!this.cachedQueryMatchesIdentity(n)))return this.hydratedQueryCache.delete(i),n}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(let e of this.subscriptions.all()){let r=ie(e.fn.__lunoraRef,e.argsKey,e.shardKey),s=this.hydratedQueryCache.get(r);s!==void 0&&this.cachedQueryMatchesIdentity(s)&&(this.hydratedQueryCache.delete(r),this.seedSubscriptionFromCache(e,s))}}persistQueryValue(e){let r=e.serverBase;if(!this.queryCache||r===void 0)return;let s=ie(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(s,{identity:n,serverCursor:e.serverCursor,ts:Date.now(),value:r,...n===this.identityFingerprint()&&!this.subjectAwaitingReconfirm()?this.credentialStamp():{},...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},Si))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;let{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}let r=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(r.map(async([s,i])=>e.put(s,i)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";let e=[...this.connections.values()];return e.length===0?"idle":e.some(r=>r.wsState==="open")?"connected":e.some(r=>r.polling.isPolling())?"polling":e.some(r=>r.wsState==="connecting")?"connecting":"offline"}baselineCursorFor(e){let r=g(e),s;for(let i of this.subscriptions.all())g(i.shardKey)!==r||i.serverCursor===void 0||(s=s===void 0?i.serverCursor:Math.max(s,i.serverCursor));return s}async pollSubscriptions(e){let r=g(e),s=[];for(let c of this.subscriptions.all())g(c.shardKey)===r&&(ss(c.args)?s.push(c):ne(c.errorCallbacks,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"}));if(s.length===0)return this.probeOrigin();let i=Fr(),n=this.identityFingerprint(),a;try{a=await rs(async c=>this.sendBatch(s.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 s.entries()){let h=a[c];if(h!==void 0){if(!h.ok){ne(u.errorCallbacks,{code:h.error.code,message:h.error.message});continue}this.handleDataMessage({data:E(h.value),id:u.id,type:"data"},i)}}return!0}async probeOrigin(){let{fetchImpl:e}=this;if(!e)return!1;try{return await rs(async r=>e(Z(this.url,kt),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:r})),!0}catch{return!1}}emitConnectionStatus(){let e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,r,s){this.mutationSettledListeners.emit({args:e.args,code:s===void 0?void 0:s.code,error:s,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:r})}applyOptimisticUpdates(e,r,s,i){let n=[],a=[];if(!i)return{confirms:n,rollbacks:a};let c=F.key(e,r,s),u=this.subscriptions.get(c);if(u){let h=bt(u,i);h&&(n.push(h.confirm),a.push(h.rollback))}return{confirms:n,rollbacks:a}}applyOptimisticUpdate(e,r,s,i,n){let{confirms:a,rollbacks:c,store:u}=xr(this.subscriptions,s);try{e(u,r)}catch{we(c);return}i.push(...c),n.push(...a)}getConnection(e){return this.connections.get(g(e))}sendOrQueueUnsubscribe(e,r,s){let i=this.getConnection(e);i&&!_(i,{id:r,type:s})&&i.pendingUnsubscribes.push({id:r,type:s})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let s="idle";return this.leaderStatus==="connected"?s="open":this.leaderStatus==="connecting"&&(s="connecting"),{hasSocket:!1,polling:this.leaderStatus==="polling",wasEverConnected:this.leaderWasEverConnected,wsState:s}}let r=this.getConnection(e);return{hasSocket:r?.socket!==void 0,polling:r?.polling.isPolling()??!1,wasEverConnected:r?.wasEverConnected??!1,wsState:r?.wsState??"idle"}}getOrCreateConnection(e){let r=g(e),s=this.connections.get(r);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:di({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:o(()=>{this.flushOfflineQueue(e).catch(()=>{})},"onReachable"),onStateChange:o(()=>{this.emitConnectionStatus()},"onStateChange"),poll:o(async()=>this.pollSubscriptions(e),"poll")}),reconnect:St(this.reconnectOptions),reconnectTimer:void 0,resubscribePending:new Map,resubscribeQueue:[],shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:!1,wsState:"idle"},this.connections.set(r,s)),s}wsUrlFor(e,r){let s=[];if(e!==void 0&&s.push(`shard=${encodeURIComponent(e)}`),r!==void 0&&s.push(`token=${encodeURIComponent(r)}`),s.length===0)return this.wsUrl;let i=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${i}${s.join("&")}`}rpcRequestHeaders(e,r){let s={"content-type":"application/json"};e.expectSubject!==void 0&&(s[oi]=ci(e.expectSubject));let i=this.shardCursors.get(this.cursorKeyFor(r));if(i!==void 0&&(s["x-lunora-min-seq"]=i.toString()),this.authToken&&(s.authorization=`Bearer ${this.authToken}`),e.mutationId&&(s["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(s["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(s["x-lunora-client-seq"]=e.clientSeq.toString()),e.baselineSeq!==void 0&&(s["x-lunora-base-seq"]=e.baselineSeq.toString()),e.attachBookmark){let n=this.bookmark.get();n&&(s["x-d1-bookmark"]=n)}return s}async rpc(e,r,s,i={}){if(!this.fetchImpl)throw new B("LunoraClient: no `fetch` implementation available");let n=this.rpcRequestHeaders(i,s),a=await this.fetchImpl(Z(this.url,li),{body:JSON.stringify({args:ee(r,`args for '${e}'`),functionPath:e,shardKey:s}),headers:n,method:"POST"});if(i.captureBookmark){let h=a.headers.get("x-d1-bookmark");h&&this.bookmark.set(h)}let c;try{c=await a.json()}catch{throw Se(a.status,a.statusText,a.headers.get("retry-after"))}let u=he(c);if(u!==void 0)throw ts(u,a.headers.get("retry-after"));if(!a.ok)throw Se(a.status,a.statusText,a.headers.get("retry-after"));return i.onMutationAck?.(c.lastMutationId),i.onCommitCursor?.(c.commitCursor),this.learnDefaultShardKey(a,s),this.recordShardCursor(s,c.commitCursor),S(c.result)}async adminFetch(e,r,s,i){if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");let n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);let a=s instanceof ArrayBuffer||s instanceof Blob,c;s===void 0?c=void 0:a?(c=s,i!==void 0&&(n["content-type"]=i)):(c=JSON.stringify(s),n["content-type"]="application/json");let u=await this.fetchImpl(Z(this.url,e),{body:c,headers:n,method:r}),h;try{h=await u.json()}catch{let l=u.statusText?` ${u.statusText}`:"";throw new y("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${l})`)}let d=he(h);if(d!==void 0){let l=new Error(d.message??"admin request failed");throw l.code=d.code,l}if(!u.ok){let l=u.statusText?` ${u.statusText}`:"";throw new y("INTERNAL",`LunoraClient: admin request failed (status ${u.status.toString()}${l})`)}return h}effectiveConnectionContext(e){let r=this.connectionContextHolders.get(e);return r&&r.length>0?r[r.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){let r=this.connections.get(e);r?.wsState==="open"&&this.sendConnectEnvelope(r)}sendConnectEnvelope(e){let r=this.effectiveConnectionContext(g(e.shardKey));_(e,{caps:Hn,clientId:this.clientId,id:"connect",type:"connect",...r===void 0?{}:{context:r}})}resendShapeSubscriptions(e){for(let r of this.shapeSubscriptions.values())g(r.shardKey)===g(e)&&this.sendShapeSubscribeIfOpen(r)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;let r=this.getOrCreateConnection(e);if(!(r.wsState==="open"||r.wsState==="connecting")){if(r.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(r,e,this.wsToken).catch(()=>{});return}this.openSocket(r,e,this.wsToken)}}async openSocketWithProvidedToken(e,r,s){let i;try{i=await s()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,r,i)}openManagedSocket(e,r,s,i){let{WebSocketImpl:n}=this;if(n===void 0)throw new y("INTERNAL","no WebSocket implementation available");let a=new n(r);e.socket=a;let c=o(()=>{this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket===a&&(e.socket=void 0)},"a"),u=o(h=>{c(),i.onClose(h)},"o");s>0&&(e.connectTimer=setTimeout(()=>{if(e.connectTimer=void 0,e.socket===a){try{a.close()}catch{}u()}},s)),a.addEventListener("open",()=>{if(e.socket===a){e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.lastFrameAt=Date.now();try{i.onOpen?.()}catch(h){console.error("[lunora] connection open handler threw",h)}this.startHeartbeat(e,u)}}),a.addEventListener("message",h=>{if(e.socket===a){e.lastFrameAt=Date.now();try{i.onMessage(h)}catch(d){console.error("[lunora] server frame handler threw",d)}}}),a.addEventListener("close",h=>{e.socket===a&&u(h)}),a.addEventListener("error",()=>{e.socket===a&&u()})}openSocket(e,r,s){this.WebSocketImpl!==void 0&&(e.identity=this.identityFingerprint(),s===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.retired=!1,this.openManagedSocket(e,this.wsUrlFor(r,s),this.connectTimeoutMs,{onClose:o(i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},"onClose"),onMessage:o(i=>{e.retired!==!0&&this.handleServerMessage(i.data,r)},"onMessage"),onOpen:o(()=>{e.wsState="open",e.wasEverConnected=!0,e.polling.noteOpen(),clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},wi),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(r),this.clearResubscribeQueue(e);for(let n of this.subscriptions.all())g(n.shardKey)===g(r)&&this.queueResubscribe(n);if(this.resendShapeSubscriptions(r),e.pendingUnsubscribes.length>0){let n=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:a,type:c}of n)_(e,{id:a,type:c})}this.flushPendingStreams(e);let i=this.whisperHandlers.get(g(r));if(i)for(let n of i.keys())_(e,{topic:n,type:"whisper_subscribe"});this.flushOfflineQueue(r).catch(()=>{})},"onOpen")}))}flushPendingStreams(e){if(!e.pendingStreams||e.pendingStreams.length===0)return;let r=e.pendingStreams;e.pendingStreams=[];for(let s of r){let i=_(e,s)?this.streams.get(String(s.id)):void 0;i&&(i.started=!0)}}cancelStream(e,r){let s=this.getConnection(r),i=this.streams.get(e);s&&(s.pendingStreams=s.pendingStreams?.filter(n=>n.id!==e),!_(s,{id:e,type:"unsubscribe"})&&i?.durable===!0&&i.started&&s.pendingUnsubscribes.push({id:e,type:"unsubscribe"})),this.streams.delete(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;e.wsState==="connecting"&&e.polling.noteFailedOpen(),this.stopHeartbeat(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e);let r=new Set((e.pendingStreams??[]).map(i=>i.id));for(let[i,n]of this.streams)if(!(g(n.shardKey)!==g(e.shardKey)||r.has(i))){if(n.durable){let a={...n.message,...n.generation===void 0?{}:{generation:n.generation},sinceChunk:n.lastSeq};n.message=a,e.pendingStreams=[...(e.pendingStreams??[]).filter(c=>c.id!==i),a];continue}n.handle.fail(new y("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.streams.delete(i)}if(this.WebSocketImpl===void 0)return;let s=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},s)}startHeartbeat(e,r){this.stopHeartbeat(e),!(this.heartbeatIntervalMs<=0)&&(e.heartbeatTimer=setInterval(()=>{if(!e.socket)return;let{socket:s}=e;if(Date.now()-e.lastFrameAt>this.heartbeatIntervalMs*2.5){try{s.close()}catch{}r();return}try{s.send(mi)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(e){e.heartbeatTimer!==void 0&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=void 0)}markShardPendingAck(e){let r=g(e);for(let s of this.subscriptions.all())g(s.shardKey)===r&&(s.acked=!1)}queueResubscribe(e){let r=this.getConnection(e.shardKey);r&&(r.resubscribeQueue.push(e),this.drainResubscribeQueue(r))}drainResubscribeQueue(e){for(;e.resubscribePending.size<ki;){let r=e.resubscribeQueue.shift();if(!r)return;this.subscriptions.getById(r.id)&&this.sendSubscribeIfOpen(r)&&e.resubscribePending.set(r.id,setTimeout(()=>{this.releaseResubscribeSlot(e,r.id)},Ti))}}releaseResubscribeSlot(e,r){let s=e.resubscribePending.get(r);s!==void 0&&(clearTimeout(s),e.resubscribePending.delete(r),this.drainResubscribeQueue(e))}clearResubscribeQueue(e){for(let r of e.resubscribePending.values())clearTimeout(r);e.resubscribePending.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e){let r=this.getConnection(e.shardKey);if(r?.wsState!=="open"||e.acked)return!1;let s=e.serverCursor!==void 0&&e.serverBase!==void 0;return _(r,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...s?{sinceSeq:e.serverCursor}:{},...s&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){let r=this.getConnection(e.shardKey);r?.wsState==="open"&&_(r,{id:e.id,shape:{name:e.name,...e.wireArgs===void 0?{}:{args:e.wireArgs}},type:"shape_subscribe",...e.serverCursor===void 0?{}:{sinceCheckpoint:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,r){let s=Vn(e);if(s===void 0)return;let i;try{i=JSON.parse(s)}catch{return}if(i.type!=="error"&&this.getConnection(r)?.reconnect.reset(),typeof i.id=="string"){let n=this.getConnection(r);n&&this.releaseResubscribeSlot(n,i.id)}switch(i.type){case"ack":{let n=this.subscriptions.getById(i.id);n&&(n.acked=!0);return}case"chunk":{let{data:n,generation:a,id:c,seq:u}=i,h=this.streams.get(c);h&&typeof u=="number"&&(h.lastSeq=u,typeof a=="number"&&(h.generation=a),h.durable=!0),h?.handle.push(S(n));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"identity":{this.handleIdentityFrame(i,r);break}case"pokeEnd":{this.handlePokeEnd(i,r);break}case"pokePart":{this.handlePokePart(i,r);break}case"pokeStart":{this.handlePokeStart(i,r);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,r);break}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}let{id:r}=e,s=r===void 0?void 0:this.streams.get(r);if(s&&r!==void 0){s.handle.fail(Wn(e)),this.streams.delete(r);return}let i=r===void 0?void 0:this.subscriptions.getById(r);if(i){let a=es(e),c=this.identityFingerprint(),u=F.keyOf(i);ne(i.errorCallbacks,a),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(u,a,c);return}let n=r===void 0?void 0:this.shapeSubscriptions.get(r);n&&ne(n.errorCallbacks,es(e))}pokeBufferKey(e,r){return`${g(e)}\0${r}`}handlePokeStart(e,r){Vr(this.pokeBuffers,t.MAX_POKE_BUFFERS),this.pokeBuffers.set(this.pokeBufferKey(r,e.pokeId),{baseCheckpoint:e.baseCheckpoint,bases:new Map,epoch:e.epoch,lastMutationId:new Map,parts:new Map,resets:new Set})}handlePokePart(e,r){let s=this.pokeBuffers.get(this.pokeBufferKey(r,e.pokeId));if(!s)return;let i=s.parts.get(e.shapeId)??[];for(let a of e.rowsPatch)i.push(a.value===void 0?a:{...a,value:S(a.value)});s.parts.set(e.shapeId,i),e.lastMutationId!==void 0&&s.lastMutationId.set(e.shapeId,e.lastMutationId);let n=e.baseCheckpoint??s.baseCheckpoint;n!==void 0&&s.bases.set(e.shapeId,n),e.reset===!0&&s.resets.add(e.shapeId)}handlePokeEnd(e,r){let s=this.pokeBufferKey(r,e.pokeId),i=this.pokeBuffers.get(s);if(i){this.pokeBuffers.delete(s);for(let n of i.parts.keys()){let a=this.shapeSubscriptions.get(n);a&&this.applyPokePart(a,i,e)}}}applyPokePart(e,r,s){let i=r.parts.get(e.id)??[],n=r.resets.has(e.id),a=r.bases.get(e.id),c=r.epoch!==void 0&&e.serverEpoch!==void 0&&r.epoch!==e.serverEpoch,u=a!==void 0&&e.serverCursor!==void 0&&e.serverCursor!==a;if(!n&&(c||u)){e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(e),this.sendShapeSubscribeIfOpen(e);return}n&&e.rows.clear(),pi(e.rows,i),s.checkpoint!==void 0&&(e.serverCursor=s.checkpoint),s.epoch!==void 0&&(e.serverEpoch=s.epoch);let h=r.lastMutationId.get(e.id);h!==void 0&&(e.lastMutationId=h),this.emitShapeRows(e),e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}emitShapeRows(e){let r=[...e.rows.values()];for(let s of e.callbacks)try{s(r)}catch{}}handleDataMessage(e,r){let{id:s}=e,i=s?this.subscriptions.getById(s):void 0;if(!i)return;let n;try{n=this.resolveDataPayload(e,i)}catch(a){ne(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription \u2014 ${a instanceof Error?a.message:String(a)}`});return}if(n===Jr){this.resnapshotSubscription(i);return}if(i.serverBase=n,this.dropCacheSeed(F.keyOf(i)),e.cursor!==void 0&&(i.serverCursor=e.cursor),e.epoch!==void 0&&(i.serverEpoch=e.epoch),e.lastMutationId!==void 0){i.lastMutationId=Math.max(i.lastMutationId??0,e.lastMutationId);for(let a of i.checkpointCallbacks)a({checkpoint:i.serverCursor,mutationId:i.lastMutationId,rowsFollow:!0})}if(this.persistQueryValue(i),Be(i,i.serverCursor),r!==void 0&&Mr(i,r),z(i,Y(n,i.optimisticLayers)),this.tabCoordinator?.isLeader()){let a=F.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(a,n,i.serverCursor,i.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){let r=this.subscriptions.getById(e.id);r&&this.ackAndAdvanceCursor(r,e.cursor,e.epoch)}handleSettledMessage(e){let r=this.subscriptions.getById(e.id);if(r){this.ackAndAdvanceCursor(r,e.cursor,e.epoch),e.lastMutationId!==void 0&&(r.lastMutationId=Math.max(r.lastMutationId??0,e.lastMutationId));for(let s of r.checkpointCallbacks)s({checkpoint:r.serverCursor,mutationId:r.lastMutationId});if(this.tabCoordinator?.isLeader()){let s=F.keyOf(r);this.tabCoordinator.broadcastSubscriptionSettled(s,r.serverCursor,r.serverEpoch,r.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(e,r,s){e.acked=!0,(r!==void 0&&r!==e.serverCursor||s!==void 0&&s!==e.serverEpoch)&&(r!==void 0&&(e.serverCursor=r),s!==void 0&&(e.serverEpoch=s),this.persistQueryValue(e),Be(e,e.serverCursor)&&z(e,Y(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,r){if("data"in e&&e.data!==void 0)return S(e.data);let s=S(e.delta);return Er(s)?r.serverBase===void 0?s:Ir(r.serverBase,s)??Jr:s}dispatchWhisper(e,r){let s=this.whisperHandlers.get(g(r))?.get(e.topic);if(!s)return;let i=S(e.data);for(let n of s)try{n(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){let r=this.streams.get(e);if(r){r.handle.complete(),this.streams.delete(e);return}let s=this.subscriptions.getById(e);s&&(s.acked=!1,ne(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(r=>{X(this.onPersistenceError,"remove",r,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;let e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let r=2166136261,s=5381;for(let i=0;i<e.length;i+=1){let n=e.charCodeAt(i);r^=n,r=Math.imul(r,16777619),s=Math.imul(s,33)+n}return`${e.length.toString(36)}:${(r>>>0).toString(36)}:${(s>>>0).toString(36)}`}credentialStamp(){let e=this.authToken;return e===null?{}:{credential:this.hashToken(e)}}cachedQueryMatchesIdentity(e){return this.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 r=this.authToken;return r===null?!1:this.hashToken(r)===e}releaseSessionProbe(){this.sessionProbesInFlight-=1,!(this.identityUnresolved()||this.identityFingerprint()!==null)&&!this.closed&&this.offlineQueue.size>0&&Xr(this.computeStatus())&&this.flushAllOfflineQueues()}identityUnresolved(){return this.sessionProbesInFlight>0?!0:this.identityResolutionExpected&&!this.identitySettled}adoptResolvedSubject(e,r,s){if(!(this.closed||this.authToken!==e||s!==this.sessionProbeGeneration)){if(e===null){this.adoptCookieSubject(r?.id??null,s);return}r!==null&&this.setAuthToken(e,r.id)}}adoptCookieSubject(e,r){return this.closed||this.authToken!==null||r<this.identityAnsweredAt?!1:(this.identityAnsweredAt=r,this.identitySettled=!0,this.setAuthToken(null,e),!0)}handleIdentityFrame(e,r){let s=this.getConnection(r)?.identityQuestion,{subject:i}=e;s===void 0||i!==null&&typeof i!="string"||this.adoptCookieSubject(i,s)||!this.closed&&this.authToken===null&&(i===null?null:`subj:${i}`)!==this.identityFingerprint()&&this.evictPreviousIdentitySession()}applySubject(e,r){if(r!==void 0){this.authSubject=r,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 r=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return r===void 0?e.identity:r}rejectQueuedForIdentityChange(e){let r=this.offlineQueue.drain(),s=[];for(let i of r){if(this.replayIdentityVerdict(this.stampOf(i))!=="mismatch"){s.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);let n=new Error("offline mutation discarded: auth identity changed before replay");n.code="OFFLINE_IDENTITY_CHANGED",i.reject(n),this.emitItemSettled(i,"rejected",n)}this.offlineQueue.requeue(s),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,r){for(let s of this.connections.values())s.identity===e&&(s.identity=r)}restampQueuedIdentity(e,r){for(let[s,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(s,r);this.offlineQueue.restampIdentity(e,r)}restampWatermarks(e,r){let s=e??"",i=this.clientWatermarks.get(s);if(i===void 0)return;this.clientWatermarks.delete(s);let n=r??"",a=this.clientWatermarks.get(n);if(a===void 0)this.clientWatermarks.set(n,i);else for(let[c,u]of i)a.set(c,u)}clearQueryCacheForIdentityChange(){this.revokeCacheSeededValues(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}evictPreviousIdentitySession(){this.revokeCacheSeededValues();for(let e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.acked=!1,z(e,Y(void 0,e.optimisticLayers));for(let e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(e);this.bounceShardSockets(),this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;let e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}bounceShardSockets(){for(let e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}}flushAllOfflineQueues(){for(let e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){let r=g(e),s=this.offlineFlushes.get(r);if(s===void 0&&this.offlineQueue.size===0)return;let i=(async()=>{await(s??Promise.resolve());try{await this.drainOfflineQueue(e)}catch{}})();this.offlineFlushes.set(r,i),await i,this.offlineFlushes.get(r)===i&&this.offlineFlushes.delete(r)}async drainOfflineQueue(e){let r=this.offlineQueue.drainConflict();for(let h of r){this.unpersist(h.id),this.queuedIdentities.delete(h.id??"");let d=new Error("offline mutation skipped: precondition failed before replay");d.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(h,"rejected",d)}let s=g(e),i=this.offlineQueue.drain(h=>g(h.shardKey)===s);if(i.length===0)return;let n=[],a=[];for(let h of i){let d=this.replayGateVerdict(h);d==="send"?n.push(h):d==="hold"&&a.push(h)}if(this.offlineQueue.requeue(a),a.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),n.length===0){this.scheduleRateLimitedRetry(e);return}let c=this.encodableOrSettleTerminal(n);if(c.length===0){this.scheduleRateLimitedRetry(e);return}if(c.length===1){await this.replaySequential(c,e),this.scheduleRateLimitedRetry(e);return}let u=[];for(let h=0;h<c.length;h+=Ct){let d=c.slice(h,h+Ct),l=await this.replayBatched(d,e);if(u.push(...l.requeue),l.stop){u.push(...c.slice(h+Ct));break}}u.length>0&&this.offlineQueue.requeue(u),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){let r=g(e),s=this.replayRetryState.get(r),i=(s?.attempts??0)+1;this.replayRetryState.set(r,{attempts:i,delayMs:Math.max(s?.delayMs??0,wt(i))})}noteReplayRetryDelay(e,r){let s=g(e),i=this.replayRetryState.get(s),n=(i?.attempts??0)+1,a=$r(r,n);this.replayRetryState.set(s,{attempts:n,delayMs:a===void 0?i?.delayMs:Math.max(i?.delayMs??0,a)})}scheduleRateLimitedRetry(e){let r=g(e),s=this.replayRetryState.get(r),i=s?.delayMs;if(s===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(r);return}s.delayMs=void 0;let n=this.replayRetryTimers.get(r);n!==void 0&&clearTimeout(n),this.replayRetryTimers.set(r,setTimeout(()=>{this.replayRetryTimers.delete(r),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){let r=[];for(let s of e)try{ee(s.args,`args for '${s.functionPath}'`),r.push(s)}catch(i){this.settleReplayTerminal(s,i instanceof Error?i:new Error(String(i)))}return r}replayGateVerdict(e){let r=this.stampOf(e);if(r===void 0)return this.queuedIdentities.delete(e.id??""),"send";let s=this.replayIdentityVerdict(r);if(s==="unknown")return"hold";if(this.queuedIdentities.delete(e.id??""),s==="match")return"send";this.unpersist(e.id);let i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",e.reject(i),this.emitItemSettled(e,"rejected",i),"reject"}settleReplaySuccess(e,r,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.resolve(r),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,r){let s=e.headers.get("x-lunora-shard-key");if(s===null||r!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;let i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,i)),this.shardCursors.delete(""))}recordShardCursor(e,r){if(typeof r!="number")return;let s=this.cursorKeyFor(e);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,r))}shouldRequeueReplayFailure(e){if(this.noteIdentityMismatch(e))return!0;if(Ur(e)){let r=this.hashToken(this.authToken??"");return this.authRefusalNotifiedFor!==r&&(this.authRefusalNotifiedFor=r,this.notifyTokenExpired()),!0}return Nr(e)}replayExpectation(e){return this.authToken!==null?{}:e===null?{expectSubject:null}:e?.startsWith("subj:")===!0?{expectSubject:e.slice(5)}:{}}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;let r=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===r&&(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}settleReplayTerminal(e,r){this.unpersist(e.id),e.reject(r),this.emitItemSettled(e,"rejected",r)}async replaySequential(e,r){for(let s=0;s<e.length;s+=1){let i=e[s];if(i)try{let n,a=await this.rpc(i.functionPath,i.args,i.shardKey,{baselineSeq:i.baselineSeq,captureBookmark:!0,clientId:i.clientId??this.clientId,...this.replayExpectation(i.identity),mutationId:i.id,onCommitCursor:o(c=>{n=c},"onCommitCursor")});this.settleReplaySuccess(i,a,n)}catch(n){if(!this.shouldRequeueReplayFailure(n)){this.settleReplayTerminal(i,n);continue}this.noteReplayRetryDelay(r,n),this.offlineQueue.requeue(e.slice(s));return}}}async replayBatched(e,r){if(!this.fetchImpl)return{requeue:e,stop:!0};let s=JSON.stringify({calls:e.map((u,h)=>({args:ee(u.args,`args for '${u.functionPath}'`),baselineSeq:u.baselineSeq,functionPath:u.functionPath,id:h,clientId:u.clientId??this.clientId,mutationId:u.id,shardKey:u.shardKey}))});if(e.length>1&&Wr(s)>Hr)return await this.replayBatchedHalves(e,r);let i;try{i=await this.fetchImpl(Z(this.url,kt),{body:s,headers:this.rpcRequestHeaders({attachBookmark:!0,...this.replayExpectation(e.find(u=>u.identity!==void 0)?.identity)}),method:"POST"})}catch{return{requeue:e,stop:!0}}let n=i.headers.get("x-d1-bookmark");if(n&&this.bookmark.set(n),i.status===413&&e.length>1)return await this.replayBatchedHalves(e,r);let a,c=i.headers.get("retry-after");try{a=await i.json()}catch{return this.settleWholeBatchError(e,Se(i.status,i.statusText,c),r)}if(!a.results){let u=he(a),h=u===void 0?Se(i.status,i.statusText,c):ts(u,c);return this.settleWholeBatchError(e,h,r)}return{requeue:this.settleReplayBatchSlots(e,a.results,r),stop:!1}}settleWholeBatchError(e,r,s){if(r instanceof B||r.code!==void 0&&this.shouldRequeueReplayFailure(r))return this.noteReplayRetryDelay(s,r),{requeue:e,stop:!0};for(let i of e)this.settleReplayTerminal(i,r);return{requeue:[],stop:!1}}async replayBatchedHalves(e,r){let s=Math.ceil(e.length/2),i=await this.replayBatched(e.slice(0,s),r);if(i.stop)return{requeue:[...i.requeue,...e.slice(s)],stop:!0};let n=await this.replayBatched(e.slice(s),r);return{requeue:[...i.requeue,...n.requeue],stop:n.stop}}settleReplayBatchSlots(e,r,s){let i=new Map;for(let a of r)typeof a.id=="number"&&a.body!==void 0&&i.set(a.id,a.body);let n=[];for(let[a,c]of e.entries()){let u=i.get(a);if(u===void 0)n.push(c);else if("error"in u){let h=ns(u);this.shouldRequeueReplayFailure(h)?(this.noteReplayRetryDelay(s,h),n.push(c)):this.settleReplayTerminal(c,h)}else this.settleReplaySuccess(c,S(u.result),u.commitCursor)}return n}};var as=L(xt(),1),os=L(re(),1);var Xn=o(()=>{let t=(0,as.c)(4),e=ut(),r,s,i;return t[0]!==e?(r=o(n=>e.onConnectionStatus(()=>{n()}),"o"),s=o(()=>e.connectionStatus(),"e"),i=o(()=>e.connectionStatus(),"s"),t[0]=e,t[1]=r,t[2]=s,t[3]=i):(r=t[1],s=t[2],i=t[3]),(0,os.useSyncExternalStore)(r,s,i)},"S");export{At as a,ls as b,rt as c,ks as d,As as e,ut as f,Xn as g};
@@ -1 +1 @@
1
- import{b as c}from"./chunk-B7ITCEGD.js";import{f as l}from"./chunk-KIOIUXMK.js";import{a as r,d as f,f as g}from"./chunk-YKXDMIHQ.js";var m=f(g(),1);var p={capabilities:{accounts:!0,admin:!0,inviteOnly:!1,organization:!1,passkey:!1,twoFactor:!1},emailAndPassword:!1,organization:{enabled:!1,roles:!1,teams:!1},plugins:[],rateLimit:{enabled:!1},session:{},socialProviders:[],userFields:[]},h=r(()=>{let a=(0,m.c)(6),s=l(),o;a[0]===Symbol.for("react.memo_cache_sentinel")?(o=["lunora-auth-config"],a[0]=o):o=a[0];let e;a[1]!==s?(e=r(()=>s.getAuthConfig(),"t"),a[1]=s,a[2]=e):e=a[2];let{data:u,isLoading:d}=c(o,e),t=u??p,n=!d,i;return a[3]!==t||a[4]!==n?(i={config:t,ready:n},a[3]=t,a[4]=n,a[5]=i):i=a[5],i},"b");export{p as a,h as b};
1
+ import{b as c}from"./chunk-AH6MS5JC.js";import{f as l}from"./chunk-OHOQXJGW.js";import{a as r,d as f,f as g}from"./chunk-YKXDMIHQ.js";var m=f(g(),1);var p={capabilities:{accounts:!0,admin:!0,inviteOnly:!1,organization:!1,passkey:!1,twoFactor:!1},emailAndPassword:!1,organization:{enabled:!1,roles:!1,teams:!1},plugins:[],rateLimit:{enabled:!1},session:{},socialProviders:[],userFields:[]},h=r(()=>{let a=(0,m.c)(6),s=l(),o;a[0]===Symbol.for("react.memo_cache_sentinel")?(o=["lunora-auth-config"],a[0]=o):o=a[0];let e;a[1]!==s?(e=r(()=>s.getAuthConfig(),"t"),a[1]=s,a[2]=e):e=a[2];let{data:u,isLoading:d}=c(o,e),t=u??p,n=!d,i;return a[3]!==t||a[4]!==n?(i={config:t,ready:n},a[3]=t,a[4]=n,a[5]=i):i=a[5],i},"b");export{p as a,h as b};
@@ -1 +1 @@
1
- import{a as s}from"./chunk-B7ITCEGD.js";import{a as n}from"./chunk-YKXDMIHQ.js";var b="__lunora_admin__:",g=new Set(["action","mutation","query"]),c=Symbol("lunora.operationSeq"),_=n(t=>{if(typeof t!="object"||t===null)return;let e=t[c];return typeof e=="number"?e:void 0},"g"),d=n((t,e)=>{if(!(typeof t!="object"||t===null||!Object.isExtensible(t)))try{Object.defineProperty(t,c,{configurable:!0,enumerable:!1,value:e,writable:!0})}catch{}},"h"),m=n(t=>{if(typeof t!="object"||t===null)return;let e=t.__lunoraRef;return typeof e=="string"&&e.startsWith(b)?e:void 0},"p"),h=n(t=>{if(typeof t!="object"||t===null)return"";let{shardKey:e}=t;return typeof e=="string"?e:""},"O"),w=n(t=>new Proxy(t,{get(e,u,y){let i=Reflect.get(e,u,y);if(typeof i!="function"||typeof u!="string"||!g.has(u))return typeof i=="function"?i.bind(e):i;let f=i;return async(...o)=>{let l=m(o[0]);if(l===void 0)return f.apply(e,o);let p=typeof o[1]=="object"&&o[1]!==null?o[1]:{},a=s.start(l,p,h(o[2]));try{let r=await f.apply(e,o);return s.settle(a,{result:r}),r}catch(r){throw s.settle(a,{error:r instanceof Error?r.message:String(r)}),d(r,a),r}}}}),"E");export{_ as a,w as b};
1
+ import{a as s}from"./chunk-AH6MS5JC.js";import{a as n}from"./chunk-YKXDMIHQ.js";var b="__lunora_admin__:",g=new Set(["action","mutation","query"]),c=Symbol("lunora.operationSeq"),_=n(t=>{if(typeof t!="object"||t===null)return;let e=t[c];return typeof e=="number"?e:void 0},"g"),d=n((t,e)=>{if(!(typeof t!="object"||t===null||!Object.isExtensible(t)))try{Object.defineProperty(t,c,{configurable:!0,enumerable:!1,value:e,writable:!0})}catch{}},"h"),m=n(t=>{if(typeof t!="object"||t===null)return;let e=t.__lunoraRef;return typeof e=="string"&&e.startsWith(b)?e:void 0},"p"),h=n(t=>{if(typeof t!="object"||t===null)return"";let{shardKey:e}=t;return typeof e=="string"?e:""},"O"),w=n(t=>new Proxy(t,{get(e,u,y){let i=Reflect.get(e,u,y);if(typeof i!="function"||typeof u!="string"||!g.has(u))return typeof i=="function"?i.bind(e):i;let f=i;return async(...o)=>{let l=m(o[0]);if(l===void 0)return f.apply(e,o);let p=typeof o[1]=="object"&&o[1]!==null?o[1]:{},a=s.start(l,p,h(o[2]));try{let r=await f.apply(e,o);return s.settle(a,{result:r}),r}catch(r){throw s.settle(a,{error:r instanceof Error?r.message:String(r)}),d(r,a),r}}}}),"E");export{_ as a,w as b};