@lunora/studio 1.0.0-alpha.90 → 1.0.0-alpha.91
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/mount.js +1 -1
- package/dist/packem_chunks/AdvisorHealthPanel.js +1 -1
- package/dist/packem_chunks/ApiTab.js +1 -1
- package/dist/packem_chunks/AuditPanel.js +1 -1
- package/dist/packem_chunks/DeploymentHealthPanel.js +1 -1
- package/dist/packem_chunks/ExportImportPanel.js +1 -1
- package/dist/packem_chunks/FileBrowser.js +1 -1
- package/dist/packem_chunks/FunctionRunner.js +1 -1
- package/dist/packem_chunks/FunctionStatsPanel.js +1 -1
- package/dist/packem_chunks/HealthPanel.js +1 -1
- package/dist/packem_chunks/InsightsPanel.js +1 -1
- package/dist/packem_chunks/LogsPanel.js +1 -1
- package/dist/packem_chunks/MailPanel.js +1 -1
- package/dist/packem_chunks/MetricsPanel.js +1 -1
- package/dist/packem_chunks/NotificationsPanel.js +1 -1
- package/dist/packem_chunks/PitrPanel.js +1 -1
- package/dist/packem_chunks/SchemaViewer.js +1 -1
- package/dist/packem_chunks/SecurityAdvisorPanel.js +1 -1
- package/dist/packem_chunks/SettingsPanel.js +1 -1
- package/dist/packem_chunks/SqlEditorPanel.js +1 -1
- package/dist/packem_chunks/TableEditor.js +1 -1
- package/dist/packem_chunks/agents-panel.js +1 -1
- package/dist/packem_chunks/analytics-panel.js +1 -1
- package/dist/packem_chunks/auth-audit-panel.js +1 -1
- package/dist/packem_chunks/auth-config-panel.js +1 -1
- package/dist/packem_chunks/auth-sessions-panel.js +1 -1
- package/dist/packem_chunks/containers-panel.js +1 -1
- package/dist/packem_chunks/dashboards-panel.js +1 -1
- package/dist/packem_chunks/fanout-panel.js +1 -1
- package/dist/packem_chunks/flags-panel.js +1 -1
- package/dist/packem_chunks/issues-panel.js +1 -1
- package/dist/packem_chunks/kv-browser.js +1 -1
- package/dist/packem_chunks/log-drains-panel.js +1 -1
- package/dist/packem_chunks/migrations-route.js +1 -1
- package/dist/packem_chunks/organizations-panel.js +1 -1
- package/dist/packem_chunks/payments-panel.js +1 -1
- package/dist/packem_chunks/permissions-panel.js +1 -1
- package/dist/packem_chunks/queues-panel.js +1 -1
- package/dist/packem_chunks/rls-panel.js +1 -1
- package/dist/packem_chunks/schedule-panel.js +1 -1
- package/dist/packem_chunks/storage-rules-panel.js +1 -1
- package/dist/packem_chunks/subscriptions-panel.js +1 -1
- package/dist/packem_chunks/sync-client-panel.js +1 -1
- package/dist/packem_chunks/traces-panel.js +1 -1
- package/dist/packem_chunks/users-panel.js +1 -1
- package/dist/packem_chunks/vector-browser.js +1 -1
- package/dist/packem_chunks/workflows-panel.js +1 -1
- package/dist/packem_shared/{ApiDocsPanel-DLMeLZ5-.js → ApiDocsPanel-Cu_QmzO0.js} +1 -1
- package/dist/packem_shared/{ApiReferencePanel-9q8BbJl-.js → ApiReferencePanel-DuIU1P8B.js} +1 -1
- package/dist/packem_shared/{CommandPalette--SQwfTW1.js → CommandPalette-mPR8-vIm.js} +1 -1
- package/dist/packem_shared/DataBrowser-BPRDaOHx.js +1 -0
- package/dist/packem_shared/{GlobalDataBrowser-DpkjHfDg.js → GlobalDataBrowser-CeA8bDjX.js} +1 -1
- package/dist/packem_shared/HomePanel-DLP1nQdC.js +1 -0
- package/dist/packem_shared/{MigrationsPanel-dygzHUvg.js → MigrationsPanel-dm_M75mR.js} +1 -1
- package/dist/packem_shared/{OpenRpcReferencePanel-qOZcWXMs.js → OpenRpcReferencePanel-DXeffPFr.js} +1 -1
- package/dist/packem_shared/{ScheduledJobs-D8kBZWBu.js → ScheduledJobs-DDJG9Je7.js} +1 -1
- package/dist/packem_shared/{Studio-forQt-PC.js → Studio-BYg65qWq.js} +1 -1
- package/dist/packem_shared/{StudioApp-B1AWsBzi.js → StudioApp-D0UOg0a_.js} +1 -1
- package/dist/packem_shared/{advisor-view-Pa8HLtBv.js → advisor-view-Coipc04R.js} +1 -1
- package/dist/packem_shared/{data-grid-DcxyIXwG.js → data-grid-Ci4-tZkk.js} +1 -1
- package/dist/packem_shared/{error-alert-t6cpEi0z.js → error-alert--Ie7ofJ0.js} +1 -1
- package/dist/packem_shared/{grid-features-jnrD0SpX.js → grid-features-Db_BNYRo.js} +3 -3
- package/dist/packem_shared/{home-panel-CeeqqV0z.js → home-panel-BtxdqXDe.js} +1 -1
- package/dist/packem_shared/internal-zkEvTqy8.js +2 -0
- package/dist/packem_shared/{recording-client-DRAZEmzE.js → recording-client-DtUxwVNY.js} +1 -1
- package/dist/packem_shared/{reference-view-DnYYWr7I.js → reference-view-DncEStdm.js} +1 -1
- package/dist/packem_shared/{result-chart-DzJOVsaw.js → result-chart-Gywg9DOk.js} +1 -1
- package/dist/packem_shared/{schema-diagram-cg-bz_VL.js → schema-diagram-DTRaCp6Y.js} +1 -1
- package/dist/packem_shared/{studio-BtC7WPbz.js → studio-Drf4en3j.js} +1 -1
- package/dist/packem_shared/{table-list-sidebar-D9Bd4qgi.js → table-list-sidebar-fz0m_4I4.js} +1 -1
- package/dist/packem_shared/{use-admin-query-QJ-ibl5u.js → use-admin-query-CnnyWJXM.js} +1 -1
- package/dist/packem_shared/{use-async-submit-q3ymBJkD.js → use-async-submit-BFIMhRqh.js} +1 -1
- package/dist/packem_shared/{use-auth-config-BObBpdsi.js → use-auth-config-0EnNCdLu.js} +1 -1
- package/dist/packem_shared/{use-sql-assistant-C6dl2_Ty.js → use-sql-assistant-Dtw55kKM.js} +1 -1
- package/dist/packem_shared/wire-codec-BUrWLklj.js +1 -0
- package/dist/standalone/{chunk-ZPLWCC4I.js → chunk-2NX5QU44.js} +1 -1
- package/dist/standalone/{chunk-WB5IUUUU.js → chunk-2QWHVQ6P.js} +1 -1
- package/dist/standalone/{chunk-WLZ7YPBH.js → chunk-3FIN5PH4.js} +4 -4
- package/dist/standalone/{chunk-XZSGE5ST.js → chunk-3XQMTTW2.js} +1 -1
- package/dist/standalone/{chunk-SHMNA6UL.js → chunk-4D7XIQ5Q.js} +1 -1
- package/dist/standalone/{chunk-SF4MF2FT.js → chunk-4PLB4ZNI.js} +1 -1
- package/dist/standalone/{chunk-PB7FNRDB.js → chunk-4VEAVSAZ.js} +1 -1
- package/dist/standalone/{chunk-3AV5CV6K.js → chunk-6QKJ6JPJ.js} +1 -1
- package/dist/standalone/{chunk-IC64YIX5.js → chunk-6WWX4FJB.js} +1 -1
- package/dist/standalone/{chunk-62EKHKTS.js → chunk-6XKVQES4.js} +1 -1
- package/dist/standalone/{chunk-C3HXK3A5.js → chunk-7QMX3D4D.js} +1 -1
- package/dist/standalone/{chunk-ULCZDGWQ.js → chunk-7YXDJXNL.js} +1 -1
- package/dist/standalone/{chunk-DMCYISRF.js → chunk-A7647FJE.js} +1 -1
- package/dist/standalone/{chunk-D3HXVA33.js → chunk-AQT6EPZT.js} +1 -1
- package/dist/standalone/{chunk-QXXIJAD5.js → chunk-AREBQI6D.js} +1 -1
- package/dist/standalone/{chunk-TBBJPPZ3.js → chunk-BCGEI67L.js} +1 -1
- package/dist/standalone/chunk-BENJFRZL.js +1 -0
- package/dist/standalone/{chunk-LQAKPCFX.js → chunk-BYIS2KWZ.js} +1 -1
- package/dist/standalone/{chunk-QYIOW7CD.js → chunk-C6GLTSPO.js} +1 -1
- package/dist/standalone/{chunk-JFW3YNVQ.js → chunk-CMP33R3N.js} +1 -1
- package/dist/standalone/{chunk-5ZXDB6LB.js → chunk-CRHCAN4W.js} +1 -1
- package/dist/standalone/{chunk-BRQMMGOS.js → chunk-CUAGAM2B.js} +1 -1
- package/dist/standalone/chunk-DBWOWJYT.js +11 -0
- package/dist/standalone/{chunk-QV6KV4SD.js → chunk-ESEEVSPC.js} +1 -1
- package/dist/standalone/chunk-F3TP5L34.js +1 -0
- package/dist/standalone/{chunk-6MKDYZ7A.js → chunk-FBNRATNR.js} +1 -1
- package/dist/standalone/{chunk-LAHYLAT4.js → chunk-HKG5I64M.js} +1 -1
- package/dist/standalone/{chunk-GKSRVABT.js → chunk-HWOD25QD.js} +1 -1
- package/dist/standalone/{chunk-XR7RBXKA.js → chunk-IBVBIKUI.js} +1 -1
- package/dist/standalone/{chunk-CTNB2KIA.js → chunk-IGCNMZSB.js} +1 -1
- package/dist/standalone/{chunk-IAKPXGTQ.js → chunk-IUUSMC2R.js} +1 -1
- package/dist/standalone/{chunk-OG4N2XHD.js → chunk-IUYFXK4X.js} +9 -9
- package/dist/standalone/{chunk-E7TB4USI.js → chunk-IZ3ISXSM.js} +1 -1
- package/dist/standalone/{chunk-BUTBQGUU.js → chunk-J3FR2XBV.js} +1 -1
- package/dist/standalone/{chunk-QP7IQOKF.js → chunk-JWXKUXYA.js} +1 -1
- package/dist/standalone/{chunk-OG2AMGOC.js → chunk-KUFAOKU3.js} +1 -1
- package/dist/standalone/{chunk-PM37X2V3.js → chunk-LDYOCGEG.js} +1 -1
- package/dist/standalone/{chunk-CT6ZDXLL.js → chunk-LUU4SDHW.js} +1 -1
- package/dist/standalone/chunk-LYQY7L72.js +4 -0
- package/dist/standalone/{chunk-GSKOAKQ2.js → chunk-LZH7RDRV.js} +1 -1
- package/dist/standalone/{chunk-LJISXTZJ.js → chunk-ML5IJMH6.js} +1 -1
- package/dist/standalone/{chunk-DG7YINFM.js → chunk-N233NOIN.js} +1 -1
- package/dist/standalone/{chunk-QWBRD6PX.js → chunk-NH3VWHCL.js} +1 -1
- package/dist/standalone/{chunk-ARP36PTE.js → chunk-NNRFDPSD.js} +1 -1
- package/dist/standalone/{chunk-AQX2QFCN.js → chunk-O2QUUHGF.js} +1 -1
- package/dist/standalone/{chunk-U6TNNM5U.js → chunk-Q2Q7FR3R.js} +1 -1
- package/dist/standalone/{chunk-Z7G74IH4.js → chunk-Q4AI6JRP.js} +1 -1
- package/dist/standalone/{chunk-AZAGCJVI.js → chunk-QGA2HITH.js} +1 -1
- package/dist/standalone/{chunk-6VTLIGVX.js → chunk-QWJ4HKPY.js} +1 -1
- package/dist/standalone/{chunk-Y7JXGNXD.js → chunk-QZGTDXV5.js} +1 -1
- package/dist/standalone/{chunk-24JLZ2Z5.js → chunk-RHPP74O4.js} +1 -1
- package/dist/standalone/{chunk-AUQKJYHL.js → chunk-RKGCSNAW.js} +1 -1
- package/dist/standalone/{chunk-X665E2HU.js → chunk-RMN2JN4S.js} +1 -1
- package/dist/standalone/{chunk-S4ILMYP5.js → chunk-RNOSWEMO.js} +1 -1
- package/dist/standalone/{chunk-MHAXZQVO.js → chunk-ULYM26IH.js} +1 -1
- package/dist/standalone/{chunk-PGC523I2.js → chunk-WOEGO5M6.js} +1 -1
- package/dist/standalone/{chunk-67DKQC23.js → chunk-XDEDCAYN.js} +1 -1
- package/dist/standalone/{chunk-YOUKADZH.js → chunk-XGMZESWC.js} +1 -1
- package/dist/standalone/{chunk-T6OAYQTX.js → chunk-XKKP2VFZ.js} +1 -1
- package/dist/standalone/{chunk-SP5SBO2W.js → chunk-XTEWLG3J.js} +2 -2
- package/dist/standalone/{chunk-BL6NO3U3.js → chunk-XXXMUP6L.js} +1 -1
- package/dist/standalone/{chunk-LJIFMW67.js → chunk-ZKTWHB7Q.js} +1 -1
- package/dist/standalone/{chunk-53KJRSHE.js → chunk-ZNMZQXWN.js} +1 -1
- package/dist/standalone/{chunk-YU5CI2FD.js → chunk-ZWSTXAG3.js} +1 -1
- package/dist/standalone/studio.js +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/DataBrowser-CZZ_WkJ-.js +0 -1
- package/dist/packem_shared/HomePanel-3baDsDBU.js +0 -1
- package/dist/packem_shared/internal-BSIsQVC6.js +0 -2
- package/dist/standalone/chunk-4COKHD2C.js +0 -1
- package/dist/standalone/chunk-V2U5CL3S.js +0 -11
- package/dist/standalone/chunk-VFQDHG7I.js +0 -4
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Pe}from"./chunk-V53KNYRN.js";import{a as he}from"./chunk-5Y3QLNWX.js";import{d as Ne,f as ke,g as we,k as oe}from"./chunk-QBWRC5YX.js";import{a as Q}from"./chunk-HPFLBYRI.js";import{a as Oe}from"./chunk-
|
|
1
|
+
import{a as Pe}from"./chunk-V53KNYRN.js";import{a as he}from"./chunk-5Y3QLNWX.js";import{d as Ne,f as ke,g as we,k as oe}from"./chunk-QBWRC5YX.js";import{a as Q}from"./chunk-HPFLBYRI.js";import{a as Oe}from"./chunk-RMN2JN4S.js";import"./chunk-GRL5MG3Z.js";import"./chunk-7T7UOTYK.js";import{R as ye}from"./chunk-CFPZYHPY.js";import"./chunk-7QIFDWQV.js";import{c as U}from"./chunk-FXCBF4XT.js";import"./chunk-2OUPA2WJ.js";import{b as ve}from"./chunk-THIXMMZD.js";import"./chunk-6ST5ECQA.js";import{a as Ie}from"./chunk-VDW32UET.js";import{f as H}from"./chunk-DBWOWJYT.js";import"./chunk-XBDKZZ67.js";import{a as B}from"./chunk-XQCVZAGU.js";import{d as E,e as Se,f as se,g as ie,h as le,o as $e,q as ae}from"./chunk-IUYFXK4X.js";import{c as be}from"./chunk-XNGYYOLS.js";import{a as u,e as K,f as ue,g as te,h as re,j as fe}from"./chunk-3XIESWL4.js";var Fe=K(te(),1),ge=K(ue(),1);var Z=K(te(),1);var X=K(ue(),1);var T=K(re(),1);var Ve=se(Ie.listTables),Qe=["react","client","cli"],Xe=!1,Ze={action:"action",mutation:"mutation",query:"query"},_e=u(t=>{let e=t.indexOf(":");return e===-1?{file:"",fn:t}:{file:t.slice(0,e),fn:t.slice(e+1)}},"J"),Ce=u(({file:t,fn:e,kind:a})=>`await client.${Ze[a]}(api.${t}.${e}, { /* args */ });`,"U"),Ye=u(t=>{let e=`api.${t.file}.${t.fn}`;switch(t.kind){case"action":return Ce(t);case"mutation":return`const ${t.fn} = useMutation(${e});`;default:return`const data = useQuery(${e}, { /* args */ });`}},"re"),et=u(({file:t,fn:e})=>`lunora run ${t}:${e} --args '{ }'`,"se"),tt=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
2
|
`),"de"),rt=u((t,e)=>{switch(t){case"cli":return et(e);case"client":return Ce(e);default:return Ye(e)}},"ce"),Te=u(t=>{let e=(0,Z.c)(19),{code:a,label:r,testId:n}=t,s=E(),o;e[0]!==a?(o=u(()=>{ae(a)},"s"),e[0]=a,e[1]=o):o=e[1];let i=o,d;e[2]!==r?(d=(0,T.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,T.jsx)(U,{"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,T.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 x;e[13]!==a||e[14]!==n?(x=(0,T.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]=x):x=e[15];let h;return e[16]!==f||e[17]!==x?(h=(0,T.jsxs)("div",{className:"flex flex-col gap-1.5",children:[f,x]}),e[16]=f,e[17]=x,e[18]=h):h=e[18],h},"V"),at=u(t=>{let e=(0,Z.c)(50),{file:a,fn:r,kind:n}=t,s=E(),[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 $={file:a,fn:r,kind:n},S;e[8]!==s?(S=s("CLI"),e[8]=s,e[9]=S):S=e[9];let C;e[10]!==s?(C=s("Client"),e[10]=s,e[11]=C):C=e[11];let A;e[12]!==s?(A=s("React"),e[12]=s,e[13]=A):A=e[13];let M;e[14]!==S||e[15]!==C||e[16]!==A?(M={cli:S,client:C,react:A},e[14]=S,e[15]=C,e[16]=A,e[17]=M):M=e[17],l=M;let _;e[18]===Symbol.for("react.memo_cache_sentinel")?(_=u(J=>{i(J.currentTarget.dataset.tab)},"D"),e[18]=_):_=e[18],d=_,m=rt(o,$),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=n==="action"&&o==="react"&&!Xe,x=`api.${a}.${r}`,h;e[19]!==x?(h=(0,T.jsx)("h2",{className:"font-mono text-sm font-semibold text-foreground","data-testid":"api-fn-title",children:x}),e[19]=x,e[20]=h):h=e[20];let b;e[21]!==n||e[22]!==s?(b=s("Call this {kind} from your app.",{kind:n}),e[21]=n,e[22]=s,e[23]=b):b=e[23];let y;e[24]!==b?(y=(0,T.jsx)("p",{className:"text-xs text-muted-foreground",children:b}),e[24]=b,e[25]=y):y=e[25];let N;e[26]!==h||e[27]!==y?(N=(0,T.jsxs)("div",{children:[h,y]}),e[26]=h,e[27]=y,e[28]=N):N=e[28];let v;e[29]!==s?(v=s("Snippet flavour"),e[29]=s,e[30]=v):v=e[30];let g;e[31]!==d||e[32]!==o||e[33]!==l?(g=Qe.map($=>(0,T.jsx)(U,{"aria-selected":o===$,"data-tab":$,"data-testid":`api-tab-${$}`,onClick:d,role:"tab",size:"xs",type:"button",variant:o===$?"default":"outline",children:l[$]},$)),e[31]=d,e[32]=o,e[33]=l,e[34]=g):g=e[34];let k;e[35]!==v||e[36]!==g?(k=(0,T.jsx)("div",{"aria-label":v,className:"flex gap-1.5","data-testid":"api-tabs",role:"tablist",children:g}),e[35]=v,e[36]=g,e[37]=k):k=e[37];let O=l[o],P=`api-snippet-${o}`,w;e[38]!==c||e[39]!==O||e[40]!==P?(w=(0,T.jsx)(Te,{code:c,label:O,testId:P}),e[38]=c,e[39]=O,e[40]=P,e[41]=w):w=e[41];let I;e[42]!==f||e[43]!==s?(I=f&&(0,T.jsx)("p",{className:"text-xs text-muted-foreground","data-testid":"api-action-note",children:s("Actions have no React hook \u2014 call them through the client.")}),e[42]=f,e[43]=s,e[44]=I):I=e[44];let j;return e[45]!==w||e[46]!==I||e[47]!==N||e[48]!==k?(j=(0,T.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"api-fn-doc",children:[N,k,w,I]}),e[45]=w,e[46]=I,e[47]=N,e[48]=k,e[49]=j):j=e[49],j},"pe"),nt=u(t=>{let e=(0,Z.c)(19),{name:a}=t,r=E(),n;e[0]!==a?(n=tt(a),e[0]=a,e[1]=n):n=e[1];let s=n,o;e[2]!==a?(o=(0,T.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,T.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,T.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,T.jsx)(Te,{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,T.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"),je=u(t=>{let e=(0,Z.c)(8),{active:a,label:r,onSelect:n,testId:s,value:o}=t,i;e[0]!==n||e[1]!==o?(i=u(()=>{n(o)},"u"),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,T.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"),ot=u(t=>{let e=new Map;for(let a of t){let{file:r,fn:n}=_e(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))},"me"),Ae=u(t=>{let e=(0,Z.c)(58),{functions:a,initialShardKey:r}=t,n=E(),s=H(),[o,i]=(0,X.useState)(null),[d,m]=(0,X.useState)(null),l,c;e[0]!==s||e[1]!==r?(l=u(()=>{let M=!1;return s.query(Ve,{},ie(r??"")).then(_=>(M||i(_),_)).catch(()=>{M||i([])}),()=>{M=!0}},"r"),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,x,h,b,y,N,v,g,k,O;if(e[4]!==a||e[5]!==d||e[6]!==n||e[7]!==o){let M=a??[],_=ot(M),J=(o??[]).map(st).toSorted(it),R;e[18]===Symbol.for("react.memo_cache_sentinel")?(R=u(z=>{m({kind:"fn",path:z})},"F"),e[18]=R):R=e[18];let D=R,V;e[19]===Symbol.for("react.memo_cache_sentinel")?(V=u(z=>{m({kind:"table",name:z})},"H"),e[19]=V):V=e[19];let Ge=V;x=d?.kind==="fn"?M.find(z=>z.path===d.path):void 0,f=M.length>0||J.length>0,h=x===void 0?void 0:_e(x.path),k="grid min-h-0 gap-6 md:grid-cols-[16rem_minmax(0,1fr)]",O="lunora-api-docs",e[20]!==n?(b=n("API resources"),e[20]=n,e[21]=b):b=e[21],y="flex flex-col gap-4 overflow-y-auto",N="api-rail";let ne;e[22]!==d||e[23]!==n?(ne=u(z=>(0,T.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,T.jsx)("span",{className:"px-2 font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:z.file||n("(root)")}),z.items.map(ee=>(0,T.jsx)(je,{active:d?.kind==="fn"&&d.path===ee.path,label:ee.fn,onSelect:D,testId:`api-rail-fn-${ee.path}`,value:ee.path},ee.path))]},z.file),"K"),e[22]=d,e[23]=n,e[24]=ne):ne=e[24],v=_.map(ne),g=J.length>0&&(0,T.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,T.jsx)("span",{className:"px-2 font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:n("Tables")}),J.map(z=>(0,T.jsx)(je,{active:d?.kind==="table"&&d.name===z,label:z,onSelect:Ge,testId:`api-rail-table-${z}`,value:z},z))]}),e[4]=a,e[5]=d,e[6]=n,e[7]=o,e[8]=f,e[9]=x,e[10]=h,e[11]=b,e[12]=y,e[13]=N,e[14]=v,e[15]=g,e[16]=k,e[17]=O}else f=e[8],x=e[9],h=e[10],b=e[11],y=e[12],N=e[13],v=e[14],g=e[15],k=e[16],O=e[17];let P;e[25]!==f||e[26]!==n?(P=!f&&(0,T.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]=P):P=e[27];let w;e[28]!==P||e[29]!==b||e[30]!==y||e[31]!==N||e[32]!==v||e[33]!==g?(w=(0,T.jsxs)("nav",{"aria-label":b,className:y,"data-testid":N,children:[v,g,P]}),e[28]=P,e[29]=b,e[30]=y,e[31]=N,e[32]=v,e[33]=g,e[34]=w):w=e[34];let I;e[35]!==d||e[36]!==n?(I=d===null&&(0,T.jsx)(B,{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]=I):I=e[37];let j;e[38]!==d?.kind||e[39]!==x||e[40]!==h?(j=d?.kind==="fn"&&x!==void 0&&h!==void 0&&(0,T.jsx)(at,{file:h.file,fn:h.fn,kind:x.kind},x.path),e[38]=d?.kind,e[39]=x,e[40]=h,e[41]=j):j=e[41];let $;e[42]!==d?.kind||e[43]!==x||e[44]!==n?($=d?.kind==="fn"&&x===void 0&&(0,T.jsx)(B,{testId:"api-empty",title:n("API usage snippets")}),e[42]=d?.kind,e[43]=x,e[44]=n,e[45]=$):$=e[45];let S;e[46]!==d?(S=d?.kind==="table"&&(0,T.jsx)(nt,{name:d.name}),e[46]=d,e[47]=S):S=e[47];let C;e[48]!==I||e[49]!==j||e[50]!==$||e[51]!==S?(C=(0,T.jsxs)("div",{className:"min-w-0",children:[I,j,$,S]}),e[48]=I,e[49]=j,e[50]=$,e[51]=S,e[52]=C):C=e[52];let A;return e[53]!==w||e[54]!==C||e[55]!==k||e[56]!==O?(A=(0,T.jsxs)("div",{className:k,"data-testid":O,children:[w,C]}),e[53]=w,e[54]=C,e[55]=k,e[56]=O,e[57]=A):A=e[57],A},"Se");function st(t){return t.name}u(st,"ue");function it(t,e){return t.localeCompare(e)}u(it,"he");var We=K(te(),1);var q=K(te(),1),L=K(ue(),1);var p=K(re(),1);var pe=u(function(t,e,a){let r=(0,q.c)(10),n;r[0]===Symbol.for("react.memo_cache_sentinel")?(n={kind:"loading"},r[0]=n):n=r[0];let[s,o]=(0,L.useState)(n),i,d;r[1]!==a||r[2]!==e||r[3]!==t?(i=u(()=>{if(t!==void 0)return;let l=!1;return e().then(c=>(l||o(a(c)),c)).catch(c=>{l||o({kind:"error",message:le(c)})}),()=>{l=!0}},"l"),d=[a,e,t],r[1]=a,r[2]=e,r[3]=t,r[4]=i,r[5]=d):(i=r[4],d=r[5]),(0,L.useEffect)(i,d);let m;return r[6]!==a||r[7]!==s||r[8]!==t?(m=t===void 0?s:a(t),r[6]=a,r[7]=s,r[8]=t,r[9]=m):m=r[9],m},"gt"),lt=u(t=>typeof t=="number"?"number":typeof t=="boolean"?"boolean":"string","$e"),Re=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)},"X"),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","B"),dt=u(t=>{let e=Re(t);return e!==void 0?t.type??lt(e[0]):ce(t)},"ke"),ct=u(t=>{let e=Re(t);return e===void 0?void 0:e.map(a=>JSON.stringify(a)).join(" | ")},"Se"),pt=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},"we"),mt=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},"Oe"),Y=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 Y(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]=Y(r);return e}case"string":return"";default:return null}},"q"),de=u(t=>{let e=(0,q.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},"W"),ut=u(t=>{let e=(0,q.c)(40),{name:a,required:r,schema:n}=t,s=E(),o;e[0]!==n?(o=pt(n),e[0]=n,e[1]=o):o=e[1];let i=o,d;e[2]!==n?(d=ct(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=mt(n),e[4]=n,e[5]=f):f=e[5];let x=f,h=r?"*":"?",b;e[6]!==h?(b=(0,p.jsx)("span",{className:"text-muted-foreground",children:h}),e[6]=h,e[7]=b):b=e[7];let y;e[8]!==a||e[9]!==b?(y=(0,p.jsxs)("span",{className:"font-mono text-foreground",children:[a,b]}),e[8]=a,e[9]=b,e[10]=y):y=e[10];let N;e[11]!==n?(N=dt(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 g;e[15]!==y||e[16]!==v?(g=(0,p.jsxs)("div",{className:"flex items-baseline gap-2",children:[y,v]}),e[15]=y,e[16]=v,e[17]=g):g=e[17];let k;e[18]!==n.description?(k=n.description!==void 0&&(0,p.jsx)("p",{className:"max-w-prose text-muted-foreground",children:n.description}),e[18]=n.description,e[19]=k):k=e[19];let O;e[20]!==c||e[21]!==i||e[22]!==l||e[23]!==n.format||e[24]!==s||e[25]!==m?(O=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]=O):O=e[26];let P;e[27]!==k||e[28]!==O||e[29]!==g?(P=(0,p.jsxs)("div",{className:"flex flex-col gap-1 py-2",children:[g,k,O]}),e[27]=k,e[28]=O,e[29]=g,e[30]=P):P=e[30];let w=P;if(x===void 0){let S;return e[31]!==w?(S=(0,p.jsx)("div",{className:"border-b border-border/50 last:border-b-0",children:w}),e[31]=w,e[32]=S):S=e[32],S}let I;e[33]!==w?(I=(0,p.jsx)("summary",{className:"cursor-pointer marker:text-muted-foreground",children:w}),e[33]=w,e[34]=I):I=e[34];let j;e[35]!==x?(j=(0,p.jsx)("div",{className:"mb-2 ml-2 border-l border-border pl-3",children:(0,p.jsx)(Je,{schema:x})}),e[35]=x,e[36]=j):j=e[36];let $;return e[37]!==I||e[38]!==j?($=(0,p.jsxs)("details",{className:"border-b border-border/50 last:border-b-0",children:[I,j]}),e[37]=I,e[38]=j,e[39]=$):$=e[39],$},"je"),Je=u(t=>{let e=(0,q.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)(ut,{name:m,required:n.has(m),schema:l},m)})}),e[4]=n,e[5]=o,e[6]=i):i=e[6],i},"Y"),Me=u(t=>{let e=(0,q.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)(Je,{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"),ft=["curl","javascript","lunora"],ht={lunora:"Lunora",curl:"cURL",javascript:"JavaScript"},xt=u(t=>`api.${t.replaceAll(/[/:]/g,".")}`,"Pe"),gt=u(t=>{let e=Y(t.argsSchema)??{};return t.functionPath===void 0?e:{args:e,functionPath:t.functionPath}},"Te"),bt=u((t,e,a)=>{let r=`${a}${e.httpPath}`,n=JSON.stringify(gt(e),void 0,2),s=JSON.stringify(Y(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
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
4
|
import { api } from "./_generated/api";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as He}from"./chunk-IAKPXGTQ.js";import{a as Me,b as Ve}from"./chunk-GMR677FL.js";import"./chunk-7H7LZRLP.js";import"./chunk-SD4BERSA.js";import"./chunk-IC4L6G56.js";import{a as we}from"./chunk-5Y3QLNWX.js";import"./chunk-I6A5C46N.js";import"./chunk-2QSHLBCO.js";import"./chunk-BGBLQ563.js";import"./chunk-IVFHIQOT.js";import"./chunk-QBWRC5YX.js";import"./chunk-4UOFSGUS.js";import{a as Ze}from"./chunk-3CWGJYBB.js";import{a as Xe}from"./chunk-X665E2HU.js";import{b as We}from"./chunk-GRL5MG3Z.js";import{e as Ue}from"./chunk-SMIESS7P.js";import"./chunk-7T7UOTYK.js";import{R as Ae}from"./chunk-CFPZYHPY.js";import"./chunk-T6VMSOBB.js";import"./chunk-7QIFDWQV.js";import{c as me}from"./chunk-FXCBF4XT.js";import"./chunk-2OUPA2WJ.js";import{b as ze}from"./chunk-THIXMMZD.js";import"./chunk-6ST5ECQA.js";import{a as je}from"./chunk-VDW32UET.js";import{f as Be}from"./chunk-V2U5CL3S.js";import"./chunk-XBDKZZ67.js";import{a as Je}from"./chunk-XQCVZAGU.js";import{a as qe,b as Ke,c as Pe,d as Ge,e as Le}from"./chunk-UZERI5YC.js";import{d as Fe,f as Ee,g as Oe,h as $e,m as ue}from"./chunk-OG4N2XHD.js";import"./chunk-XNGYYOLS.js";import{a as r,e as De,f as at,g as nt,h as st,j as Re}from"./chunk-3XIESWL4.js";var Ce=De(nt(),1);var x=De(at(),1);var t=De(st(),1);var rt=Ee(je.listTables),ot=Ee(je.listTableIndexes),it=Ee(je.readTablePage),dt=Ee(je.describeTables),ct={},Qe=[],mt=r(s=>{let e=(0,Ce.c)(74),{initialShardKey:u,initialTable:n}=s,l=Be(),[a,m]=(0,x.useState)("graph"),{queryShardKey:c,setShardKey:d,shardKey:b}=Ze(u),[o,p]=(0,x.useState)(""),[i,v]=(0,x.useState)(null),[g,K]=(0,x.useState)(null),_;e[0]===Symbol.for("react.memo_cache_sentinel")?(_={},e[0]=_):_=e[0];let[L,y]=(0,x.useState)(_),P;e[1]===Symbol.for("react.memo_cache_sentinel")?(P={},e[1]=P):P=e[1];let[E,M]=(0,x.useState)(P),[T,C]=(0,x.useState)(null),F;e[2]===Symbol.for("react.memo_cache_sentinel")?(F={},e[2]=F):F=e[2];let[O,he]=(0,x.useState)(F),H;e[3]===Symbol.for("react.memo_cache_sentinel")?(H={},e[3]=H):H=e[3];let[I,G]=(0,x.useState)(H),[k,pe]=(0,x.useState)(null),[D,oe]=(0,x.useState)(null),Q;e[4]===Symbol.for("react.memo_cache_sentinel")?(Q={},e[4]=Q):Q=e[4];let[J,xe]=(0,x.useState)(Q),[W,ie]=(0,x.useState)(null),ve;e[5]!==l?(ve=r(async h=>{K(null);try{let w=await l.query(rt,{},Oe(h));We(h),v(w),y({}),M({}),C(null),he(N=>Object.fromEntries(Object.entries(N).filter(q=>{let[A]=q;return A!==h}))),G(N=>Object.fromEntries(Object.entries(N).filter(q=>{let[A]=q;return A!==h})))}catch(w){let N=w;v(null),K($e(N))}},"ve"),e[5]=l,e[6]=ve):ve=e[6];let $=ve,Y;e[7]!==l?(Y=r(async()=>{oe(null);try{pe(await l.listGlobalTables())}catch(h){let w=h;pe(null),oe($e(w))}},"Q"),e[7]=l,e[8]=Y):Y=e[8];let ee=Y,de,R;e[9]!==c||e[10]!==$||e[11]!==ee?(de=r(()=>{ue($(c)),ue(ee())},"de"),R=[$,ee,c],e[9]=c,e[10]=$,e[11]=ee,e[12]=de,e[13]=R):(de=e[12],R=e[13]),(0,x.useEffect)(de,R);let te;e[14]!==l||e[15]!==L||e[16]!==T||e[17]!==c?(te=r(async h=>{if(T===h){C(null);return}C(h);let w=`${c}:${h}`;if(L[w]!==void 0)return;let[N,q]=await Promise.allSettled([l.query(it,{limit:1,offset:0,table:h},Oe(c)),l.query(ot,{table:h},Oe(c))]);N.status==="fulfilled"?y(A=>({...A,[w]:N.value.columns})):K($e(N.reason)),q.status==="fulfilled"&&M(A=>({...A,[w]:q.value.indexes}))},"te"),e[14]=l,e[15]=L,e[16]=T,e[17]=c,e[18]=te):te=e[18];let j=te,ye;e[19]!==l||e[20]!==J||e[21]!==W?(ye=r(async h=>{if(W===h){ie(null);return}if(ie(h),J[h]===void 0)try{let w=await l.readGlobalTablePage({limit:1,offset:0,table:h});xe(N=>({...N,[h]:w.columns}))}catch(w){oe($e(w))}},"ye"),e[19]=l,e[20]=J,e[21]=W,e[22]=ye):ye=e[22];let ce=ye,ge=(0,x.useRef)(void 0),V,X;e[23]!==n||e[24]!==i||e[25]!==j?(V=r(()=>{n===void 0||i===null||ge.current===n||i.some(h=>h.name===n)&&(ge.current=n,ue(j(n)))},"V"),X=[n,i,j],e[23]=n,e[24]=i,e[25]=j,e[26]=V,e[27]=X):(V=e[26],X=e[27]),(0,x.useEffect)(V,X);let B;e[28]!==l?(B=r(async(h,w,N)=>{let[q,A]=await Promise.all([Promise.allSettled([l.query(dt,{tables:[...w,...N]},Oe(h))]),Promise.all(N.map(async S=>{let be=await Promise.allSettled([l.readGlobalTablePage({limit:1,offset:0,table:S})]),Ie=be[0].status==="fulfilled"?be[0].value:void 0;return{columns:Ie?.columns??[],refs:Ie?.refs??{},table:S}}))]),Se=q[0].status==="fulfilled"?q[0].value?.columnsByTable??{}:{},Te=q[0].status==="rejected",_e=new Map(A.map(ut)),ke=[...w,...N].map(S=>{let be=Se[S]??[];return[S,be.length>0?be:_e.get(S)??[]]});he(S=>({...S,[h]:Object.fromEntries(ke)})),G(S=>({...S,[h]:Te}))},"B"),e[28]=l,e[29]=B):B=e[29];let le=B,U,ae;e[30]!==D||e[31]!==k||e[32]!==le||e[33]!==c||e[34]!==O||e[35]!==i||e[36]!==a?(U=r(()=>{a!=="graph"||i===null||k===null&&D===null||O[c]!==void 0||ue(le(c,i.map(ht),(k??[]).map(pt)))},"U"),ae=[a,i,k,D,c,O,le],e[30]=D,e[31]=k,e[32]=le,e[33]=c,e[34]=O,e[35]=i,e[36]=a,e[37]=U,e[38]=ae):(U=e[37],ae=e[38]),(0,x.useEffect)(U,ae);let z=O[c]??ct,ne;if(e[39]!==z||e[40]!==k||e[41]!==i){let h;e[43]!==z?(h=r(A=>({columns:z[A.name]??Qe,name:A.name,tier:"shard"}),"u"),e[43]=z,e[44]=h):h=e[44];let w=(i??[]).map(h),N;e[45]!==z?(N=r(A=>({columns:z[A.name]??Qe,name:A.name,tier:"global"}),"y"),e[45]=z,e[46]=N):N=e[46];let q=(k??[]).map(N);ne=[...w,...q],e[39]=z,e[40]=k,e[41]=i,e[42]=ne}else ne=e[42];let se=ne,f;if(e[47]!==o||e[48]!==i){let h=o.trim().toLowerCase();f=(i??[]).filter(w=>w.name.toLowerCase().includes(h)),e[47]=o,e[48]=i,e[49]=f}else f=e[49];let re=f,Z;if(e[50]!==k||e[51]!==o){let h=o.trim().toLowerCase();Z=(k??[]).filter(w=>w.name.toLowerCase().includes(h)),e[50]=k,e[51]=o,e[52]=Z}else Z=e[52];let Ne=Z,fe;return e[53]!==L||e[54]!==se||e[55]!==g||e[56]!==T||e[57]!==Ne||e[58]!==re||e[59]!==J||e[60]!==D||e[61]!==W||e[62]!==k||e[63]!==E||e[64]!==$||e[65]!==d||e[66]!==I||e[67]!==b||e[68]!==o||e[69]!==i||e[70]!==j||e[71]!==ce||e[72]!==a?(fe={columns:L,diagramTables:se,error:g,expanded:T,filteredGlobalTables:Ne,filteredTables:re,globalColumns:J,globalError:D,globalExpanded:W,globalTables:k,indexes:E,refresh:$,setShardKey:d,setTableFilter:p,setView:m,shardColumnsError:I,shardKey:b,tableFilter:o,tables:i,toggle:j,toggleGlobal:ce,view:a},e[53]=L,e[54]=se,e[55]=g,e[56]=T,e[57]=Ne,e[58]=re,e[59]=J,e[60]=D,e[61]=W,e[62]=k,e[63]=E,e[64]=$,e[65]=d,e[66]=I,e[67]=b,e[68]=o,e[69]=i,e[70]=j,e[71]=ce,e[72]=a,e[73]=fe):fe=e[73],fe},"ct");function ut(s){let{columns:e,refs:u,table:n}=s;return[n,e.map(l=>{let a=u[l];return a===void 0?{name:l,optional:!1,type:""}:{name:l,optional:!1,ref:a,type:"id"}})]}r(ut,"mt");function ht(s){return s.name}r(ht,"ut");function pt(s){return s.name}r(pt,"ht");var gt="/__lunora/schema-edit",ft=r(async s=>{let e=await fetch(gt,{body:JSON.stringify(s),headers:{"Content-Type":"application/json","X-Lunora-Studio":"1"},method:"POST"}),u=await e.json();return u.needsMigration===!0?{kind:"needs-migration",message:u.message??"This edit needs a migration."}:e.ok&&u.tables!==void 0?{diagnostics:u.diagnostics??[],kind:"ok",tables:u.tables}:{kind:"error",message:u.error??`schema edit failed (${String(e.status)})`}},"gt"),bt=r(s=>{let e=(0,Ce.c)(32),{hasTables:u,mode:n,onAddColumn:l,onAddIndex:a,onAddTable:m,onDestructive:c}=s,d=Fe(),b=n==="addTable"?"default":"outline",o;e[0]!==d?(o=d("Add table"),e[0]=d,e[1]=o):o=e[1];let p;e[2]!==m||e[3]!==b||e[4]!==o?(p=(0,t.jsx)(me,{"data-testid":"sc-editor-add-table",onClick:m,size:"xs",type:"button",variant:b,children:o}),e[2]=m,e[3]=b,e[4]=o,e[5]=p):p=e[5];let i=!u,v=n==="addColumn"?"default":"outline",g;e[6]!==d?(g=d("Add column"),e[6]=d,e[7]=g):g=e[7];let K;e[8]!==l||e[9]!==i||e[10]!==v||e[11]!==g?(K=(0,t.jsx)(me,{"data-testid":"sc-editor-add-column",disabled:i,onClick:l,size:"xs",type:"button",variant:v,children:g}),e[8]=l,e[9]=i,e[10]=v,e[11]=g,e[12]=K):K=e[12];let _=!u,L=n==="addIndex"?"default":"outline",y;e[13]!==d?(y=d("Add index"),e[13]=d,e[14]=y):y=e[14];let P;e[15]!==a||e[16]!==y||e[17]!==_||e[18]!==L?(P=(0,t.jsx)(me,{"data-testid":"sc-editor-add-index",disabled:_,onClick:a,size:"xs",type:"button",variant:L,children:y}),e[15]=a,e[16]=y,e[17]=_,e[18]=L,e[19]=P):P=e[19];let E=!u,M=n==="destructive"?"default":"ghost",T;e[20]!==d?(T=d("Rename / drop / change type\u2026"),e[20]=d,e[21]=T):T=e[21];let C;e[22]!==c||e[23]!==E||e[24]!==M||e[25]!==T?(C=(0,t.jsx)(me,{"data-testid":"sc-editor-destructive",disabled:E,onClick:c,size:"xs",type:"button",variant:M,children:T}),e[22]=c,e[23]=E,e[24]=M,e[25]=T,e[26]=C):C=e[26];let F;return e[27]!==P||e[28]!==C||e[29]!==p||e[30]!==K?(F=(0,t.jsxs)("div",{className:"flex flex-wrap gap-2",children:[p,K,P,C]}),e[27]=P,e[28]=C,e[29]=p,e[30]=K,e[31]=F):F=e[31],F},"bt"),xt=r(s=>{let e=(0,Ce.c)(28),{onOpenMigrations:u,result:n}=s,l=Fe();if(n===null){let o;return e[0]===Symbol.for("react.memo_cache_sentinel")?(o=(0,t.jsx)(t.Fragment,{}),e[0]=o):o=e[0],o}if(n.kind==="error"){let o;return e[1]!==n.message?(o=(0,t.jsx)("p",{className:"mt-3 text-sm text-destructive","data-testid":"sc-editor-error",role:"alert",children:n.message}),e[1]=n.message,e[2]=o):o=e[2],o}if(n.kind==="needs-migration"){let o;e[3]!==n.message||e[4]!==l?(o=n.message===""?l("This edit changes stored data and must go through a migration. Review the migration before applying."):n.message,e[3]=n.message,e[4]=l,e[5]=o):o=e[5];let p;e[6]!==o?(p=(0,t.jsx)("p",{className:"text-sm text-warning",role:"alert",children:o}),e[6]=o,e[7]=p):p=e[7];let i;e[8]!==l?(i=l("Open Migrations"),e[8]=l,e[9]=i):i=e[9];let v;e[10]!==u||e[11]!==i?(v=(0,t.jsx)(me,{className:"self-start","data-testid":"sc-editor-open-migrations",onClick:u,size:"xs",type:"button",variant:"outline",children:i}),e[10]=u,e[11]=i,e[12]=v):v=e[12];let g;return e[13]!==p||e[14]!==v?(g=(0,t.jsxs)("div",{className:"mt-3 flex flex-col gap-2","data-testid":"sc-editor-needs-migration",children:[p,v]}),e[13]=p,e[14]=v,e[15]=g):g=e[15],g}if(n.diagnostics.length===0){let o;return e[16]===Symbol.for("react.memo_cache_sentinel")?(o=(0,t.jsx)(t.Fragment,{}),e[16]=o):o=e[16],o}let a;e[17]!==l?(a=l("Codegen reported diagnostics:"),e[17]=l,e[18]=a):a=e[18];let m;e[19]!==a?(m=(0,t.jsx)("p",{className:"text-sm text-destructive",role:"alert",children:a}),e[19]=a,e[20]=m):m=e[20];let c;e[21]!==n.diagnostics?(c=n.diagnostics.map(vt),e[21]=n.diagnostics,e[22]=c):c=e[22];let d;e[23]!==c?(d=(0,t.jsx)("ul",{className:"flex flex-col gap-0.5",children:c}),e[23]=c,e[24]=d):d=e[24];let b;return e[25]!==m||e[26]!==d?(b=(0,t.jsxs)("div",{className:"mt-3 flex flex-col gap-1","data-testid":"sc-editor-diagnostics",children:[m,d]}),e[25]=m,e[26]=d,e[27]=b):b=e[27],b},"ft");function vt(s){return(0,t.jsx)("li",{className:"font-mono text-[11px] text-destructive",children:s},s)}r(vt,"xt");var yt=[{label:"string",validator:"v.string()"},{label:"number",validator:"v.number()"},{label:"boolean",validator:"v.boolean()"},{label:"bigint",validator:"v.int64()"},{label:"bytes",validator:"v.bytes()"},{label:"any",validator:"v.any()"}],Nt="v.string()",Ct=r(s=>s.split(",").map(e=>e.trim()).filter(e=>e!==""),"Nt"),wt=r(s=>{let e=(0,Ce.c)(83),{onApplied:u,tableNames:n}=s,l=Fe(),a=Ue(),[m,c]=(0,x.useState)(null),[d,b]=(0,x.useState)(!1),[o,p]=(0,x.useState)(null),[i,v]=(0,x.useState)(""),[g,K]=(0,x.useState)(""),[_,L]=(0,x.useState)(Nt),[y,P]=(0,x.useState)(n[0]??""),[E,M]=(0,x.useState)(""),[T,C]=(0,x.useState)(""),[F,O]=(0,x.useState)(!1),he;e[0]===Symbol.for("react.memo_cache_sentinel")?(he=r(()=>{c(null),v(""),K(""),M(""),C(""),O(!1)},"me"),e[0]=he):he=e[0];let H=he,I;e[1]!==u?(I=r(async S=>{b(!0),p(null);try{let be=await ft(S);p(be),be.kind==="ok"&&(u(be.tables),H())}catch(be){let Ie=be;p({kind:"error",message:Ie instanceof Error?Ie.message:String(Ie)})}b(!1)},"k"),e[1]=u,e[2]=I):I=e[2];let G=I,k;e[3]!==G||e[4]!==i?(k=r(()=>{ue(G({kind:"addTable",table:i.trim()}))},"_"),e[3]=G,e[4]=i,e[5]=k):k=e[5];let pe=k,D;e[6]!==g||e[7]!==G||e[8]!==y||e[9]!==_?(D=r(()=>{ue(G({column:g.trim(),kind:"addOptionalColumn",table:y,validator:_}))},"D"),e[6]=g,e[7]=G,e[8]=y,e[9]=_,e[10]=D):D=e[10];let oe=D,Q;e[11]!==T||e[12]!==E||e[13]!==G||e[14]!==y||e[15]!==F?(Q=r(()=>{ue(G({fields:Ct(T),kind:"addIndex",name:E.trim(),table:y,unique:F}))},"H"),e[11]=T,e[12]=E,e[13]=G,e[14]=y,e[15]=F,e[16]=Q):Q=e[16];let J=Q,xe;e[17]===Symbol.for("react.memo_cache_sentinel")?(xe=r(()=>{p(null),c("addTable")},"xe"),e[17]=xe):xe=e[17];let W=xe,ie;e[18]===Symbol.for("react.memo_cache_sentinel")?(ie=r(()=>{p(null),c("addColumn")},"ie"),e[18]=ie):ie=e[18];let ve=ie,$;e[19]===Symbol.for("react.memo_cache_sentinel")?($=r(()=>{p(null),c("addIndex")},"q"),e[19]=$):$=e[19];let Y=$,ee;e[20]!==l?(ee=r(()=>{c("destructive"),p({kind:"needs-migration",message:l("This edit changes stored data and must go through a migration. Review the migration before applying.")})},"ee"),e[20]=l,e[21]=ee):ee=e[21];let de=ee,R;e[22]===Symbol.for("react.memo_cache_sentinel")?(R=r(S=>{v(S.target.value)},"R"),e[22]=R):R=e[22];let te=R,j;e[23]===Symbol.for("react.memo_cache_sentinel")?(j=r(S=>{K(S.target.value)},"z"),e[23]=j):j=e[23];let ye=j,ce;e[24]===Symbol.for("react.memo_cache_sentinel")?(ce=r(S=>{L(S.target.value)},"ce"),e[24]=ce):ce=e[24];let ge=ce,V;e[25]===Symbol.for("react.memo_cache_sentinel")?(V=r(S=>{P(S.target.value)},"V"),e[25]=V):V=e[25];let X=V,B;e[26]===Symbol.for("react.memo_cache_sentinel")?(B=r(S=>{M(S.target.value)},"B"),e[26]=B):B=e[26];let le=B,U;e[27]===Symbol.for("react.memo_cache_sentinel")?(U=r(S=>{C(S.target.value)},"U"),e[27]=U):U=e[27];let ae=U,z;e[28]===Symbol.for("react.memo_cache_sentinel")?(z=r(S=>{O(S.target.checked)},"E"),e[28]=z):z=e[28];let ne=z,se;e[29]!==a?(se=r(()=>{ue(a({to:"/migrations"}))},"se"),e[29]=a,e[30]=se):se=e[30];let f=se,re;e[31]!==l?(re=l("Edit schema"),e[31]=l,e[32]=re):re=e[32];let Z;e[33]!==re?(Z=(0,t.jsx)(Pe,{children:re}),e[33]=re,e[34]=Z):Z=e[34];let Ne;e[35]!==l?(Ne=l("Adds a table, column, or index to lunora/schema.ts and reruns codegen."),e[35]=l,e[36]=Ne):Ne=e[36];let fe;e[37]!==Ne?(fe=(0,t.jsx)(Ge,{children:Ne}),e[37]=Ne,e[38]=fe):fe=e[38];let h;e[39]!==Z||e[40]!==fe?(h=(0,t.jsxs)(Ke,{children:[Z,fe]}),e[39]=Z,e[40]=fe,e[41]=h):h=e[41];let w=n.length>0,N;e[42]!==m||e[43]!==de||e[44]!==w?(N=(0,t.jsx)(bt,{hasTables:w,mode:m,onAddColumn:ve,onAddIndex:Y,onAddTable:W,onDestructive:de}),e[42]=m,e[43]=de,e[44]=w,e[45]=N):N=e[45];let q;e[46]!==d||e[47]!==m||e[48]!==pe||e[49]!==l||e[50]!==i?(q=m==="addTable"&&(0,t.jsxs)("div",{className:"mt-3 flex flex-wrap items-end gap-2","data-testid":"sc-editor-table-form",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(we,{htmlFor:"sc-editor-table-name",children:l("Table name")}),(0,t.jsx)(Ae,{"data-testid":"sc-editor-table-name",id:"sc-editor-table-name",onChange:te,value:i})]}),(0,t.jsx)(me,{"data-testid":"sc-editor-table-apply",disabled:d||i.trim()==="",onClick:pe,size:"xs",type:"button",children:l(d?"Applying\u2026":"Apply")}),(0,t.jsx)(me,{onClick:H,size:"xs",type:"button",variant:"ghost",children:l("Cancel")})]}),e[46]=d,e[47]=m,e[48]=pe,e[49]=l,e[50]=i,e[51]=q):q=e[51];let A;e[52]!==d||e[53]!==g||e[54]!==m||e[55]!==oe||e[56]!==l||e[57]!==n||e[58]!==y||e[59]!==_?(A=m==="addColumn"&&(0,t.jsxs)("div",{className:"mt-3 flex flex-wrap items-end gap-2","data-testid":"sc-editor-column-form",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(we,{htmlFor:"sc-editor-column-table",children:l("Table name")}),(0,t.jsx)("select",{className:"h-8 rounded-md border border-input bg-transparent px-2 text-xs","data-testid":"sc-editor-column-table",id:"sc-editor-column-table",onChange:X,value:y,children:n.map(St)})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(we,{htmlFor:"sc-editor-column-name",children:l("Column name")}),(0,t.jsx)(Ae,{"data-testid":"sc-editor-column-name",id:"sc-editor-column-name",onChange:ye,value:g})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(we,{htmlFor:"sc-editor-column-type",children:l("Column type")}),(0,t.jsx)("select",{className:"h-8 rounded-md border border-input bg-transparent px-2 text-xs","data-testid":"sc-editor-column-type",id:"sc-editor-column-type",onChange:ge,value:_,children:yt.map(Tt)})]}),(0,t.jsx)("span",{className:"text-[11px] text-muted-foreground",children:l("Optional")}),(0,t.jsx)(me,{"data-testid":"sc-editor-column-apply",disabled:d||g.trim()===""||y==="",onClick:oe,size:"xs",type:"button",children:l(d?"Applying\u2026":"Apply")}),(0,t.jsx)(me,{onClick:H,size:"xs",type:"button",variant:"ghost",children:l("Cancel")})]}),e[52]=d,e[53]=g,e[54]=m,e[55]=oe,e[56]=l,e[57]=n,e[58]=y,e[59]=_,e[60]=A):A=e[60];let Se;e[61]!==d||e[62]!==T||e[63]!==E||e[64]!==m||e[65]!==J||e[66]!==l||e[67]!==n||e[68]!==y||e[69]!==F?(Se=m==="addIndex"&&(0,t.jsxs)("div",{className:"mt-3 flex flex-wrap items-end gap-2","data-testid":"sc-editor-index-form",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(we,{htmlFor:"sc-editor-index-table",children:l("Table name")}),(0,t.jsx)("select",{className:"h-8 rounded-md border border-input bg-transparent px-2 text-xs","data-testid":"sc-editor-index-table",id:"sc-editor-index-table",onChange:X,value:y,children:n.map(_t)})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(we,{htmlFor:"sc-editor-index-name",children:l("Index name")}),(0,t.jsx)(Ae,{"data-testid":"sc-editor-index-name",id:"sc-editor-index-name",onChange:le,value:E})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(we,{htmlFor:"sc-editor-index-fields",children:l("Index fields (comma-separated)")}),(0,t.jsx)(Ae,{"data-testid":"sc-editor-index-fields",id:"sc-editor-index-fields",onChange:ae,value:T})]}),(0,t.jsxs)(we,{className:"flex items-center gap-1 text-xs",htmlFor:"sc-editor-index-unique",children:[(0,t.jsx)("input",{checked:F,"data-testid":"sc-editor-index-unique",id:"sc-editor-index-unique",onChange:ne,type:"checkbox"}),(0,t.jsx)("span",{className:"text-muted-foreground",children:l("Unique")})]}),(0,t.jsx)(me,{"data-testid":"sc-editor-index-apply",disabled:d||E.trim()===""||T.trim()==="",onClick:J,size:"xs",type:"button",children:l(d?"Applying\u2026":"Apply")}),(0,t.jsx)(me,{onClick:H,size:"xs",type:"button",variant:"ghost",children:l("Cancel")})]}),e[61]=d,e[62]=T,e[63]=E,e[64]=m,e[65]=J,e[66]=l,e[67]=n,e[68]=y,e[69]=F,e[70]=Se):Se=e[70];let Te;e[71]!==f||e[72]!==o?(Te=(0,t.jsx)(xt,{onOpenMigrations:f,result:o}),e[71]=f,e[72]=o,e[73]=Te):Te=e[73];let _e;e[74]!==N||e[75]!==q||e[76]!==A||e[77]!==Se||e[78]!==Te?(_e=(0,t.jsxs)(Le,{children:[N,q,A,Se,Te]}),e[74]=N,e[75]=q,e[76]=A,e[77]=Se,e[78]=Te,e[79]=_e):_e=e[79];let ke;return e[80]!==h||e[81]!==_e?(ke=(0,t.jsxs)(qe,{"data-testid":"sc-editor",size:"sm",children:[h,_e]}),e[80]=h,e[81]=_e,e[82]=ke):ke=e[82],ke},"Ct");function St(s){return(0,t.jsx)("option",{value:s,children:s},s)}r(St,"Tt");function Tt(s){return(0,t.jsx)("option",{value:s.validator,children:s.label},s.validator)}r(Tt,"wt");function _t(s){return(0,t.jsx)("option",{value:s,children:s},s)}r(_t,"St");var Ye=[],kt=r(s=>{let e=(0,Ce.c)(5),{open:u}=s,n=u&&"rotate-90",l;e[0]!==n?(l=Re("size-3.5 shrink-0 text-muted-foreground transition-transform duration-150",n),e[0]=n,e[1]=l):l=e[1];let a;e[2]===Symbol.for("react.memo_cache_sentinel")?(a=(0,t.jsx)("path",{d:"m9 6 6 6-6 6"}),e[2]=a):a=e[2];let m;return e[3]!==l?(m=(0,t.jsx)("svg",{"aria-hidden":"true",className:l,fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.8,viewBox:"0 0 24 24",children:a}),e[3]=l,e[4]=m):m=e[4],m},"_t"),et=r(s=>{let e=(0,Ce.c)(20),{children:u,expanded:n,name:l,onToggle:a,rowCount:m,rowTestId:c,toggleTestId:d}=s,b;e[0]!==n?(b=(0,t.jsx)(kt,{open:n}),e[0]=n,e[1]=b):b=e[1];let o;e[2]!==l?(o=(0,t.jsx)("span",{className:"truncate font-mono text-xs text-foreground",title:l,children:l}),e[2]=l,e[3]=o):o=e[3];let p;e[4]!==m?(p=(0,t.jsxs)("span",{className:"ms-auto shrink-0 text-xs text-muted-foreground tabular-nums",children:["(",m,")"]}),e[4]=m,e[5]=p):p=e[5];let i;e[6]!==n||e[7]!==a||e[8]!==b||e[9]!==o||e[10]!==p||e[11]!==d?(i=(0,t.jsxs)("button",{"aria-expanded":n,className:"flex w-full items-center gap-2 px-3 py-2 text-start transition-colors hover:bg-muted/50 aria-expanded:bg-muted/40","data-testid":d,onClick:a,type:"button",children:[b,o," ",p]}),e[6]=n,e[7]=a,e[8]=b,e[9]=o,e[10]=p,e[11]=d,e[12]=i):i=e[12];let v;e[13]!==u||e[14]!==n?(v=n&&(0,t.jsx)("div",{className:"px-3 pb-3 ps-8",children:u}),e[13]=u,e[14]=n,e[15]=v):v=e[15];let g;return e[16]!==c||e[17]!==i||e[18]!==v?(g=(0,t.jsxs)("li",{className:"border-t border-border/60 first:border-t-0","data-testid":c,children:[i,v]}),e[16]=c,e[17]=i,e[18]=v,e[19]=g):g=e[19],g},"Xe"),tt=r(s=>{let e=(0,Ce.c)(5),{columns:u,testId:n}=s,l;e[0]!==u?(l=u.map(At),e[0]=u,e[1]=l):l=e[1];let a;return e[2]!==l||e[3]!==n?(a=(0,t.jsx)("ul",{className:"flex flex-wrap gap-1.5 pt-1","data-testid":n,children:l}),e[2]=l,e[3]=n,e[4]=a):a=e[4],a},"Ye"),It=r(s=>{let e=(0,Ce.c)(10),{heading:u,indexes:n,testId:l}=s,a;e[0]!==u?(a=(0,t.jsx)("p",{className:"mb-1.5 font-mono text-[10px] tracking-wide text-muted-foreground uppercase",children:u}),e[0]=u,e[1]=a):a=e[1];let m;e[2]!==n?(m=n.map(Ft),e[2]=n,e[3]=m):m=e[3];let c;e[4]!==m||e[5]!==l?(c=(0,t.jsx)("ul",{className:"flex flex-col gap-1","data-testid":l,children:m}),e[4]=m,e[5]=l,e[6]=c):c=e[6];let d;return e[7]!==a||e[8]!==c?(d=(0,t.jsxs)("div",{className:"pt-3",children:[a,c]}),e[7]=a,e[8]=c,e[9]=d):d=e[9],d},"$t"),lt=r(s=>Re("border-b-2 px-3 py-2 font-mono text-[11px] tracking-widest uppercase outline-none transition-colors",s?"border-foreground text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),"Je"),Xt=r(s=>{let e=(0,Ce.c)(85),{initialShardKey:u,initialTable:n,schemaEditable:l}=s,a=Fe(),m;e[0]!==u||e[1]!==n?(m={initialShardKey:u,initialTable:n},e[0]=u,e[1]=n,e[2]=m):m=e[2];let{columns:c,diagramTables:d,error:b,expanded:o,filteredGlobalTables:p,filteredTables:i,globalColumns:v,globalError:g,globalExpanded:K,globalTables:_,indexes:L,refresh:y,setShardKey:P,setTableFilter:E,setView:M,shardColumnsError:T,shardKey:C,tableFilter:F,tables:O,toggle:he,toggleGlobal:H,view:I}=mt(m),G;e[3]!==M?(G=r(()=>{M("list")},"G"),e[3]=M,e[4]=G):G=e[4];let k=G,pe;e[5]!==M?(pe=r(()=>{M("graph")},"ue"),e[5]=M,e[6]=pe):pe=e[6];let D=pe,oe;e[7]!==E?(oe=r(f=>{E(f.target.value)},"oe"),e[7]=E,e[8]=oe):oe=e[8];let Q=oe,J;e[9]!==y||e[10]!==C?(J=r(f=>{ue(y(C))},"X"),e[9]=y,e[10]=C,e[11]=J):J=e[11];let xe=J,W;e[12]!==O?(W=O??[],e[12]=O,e[13]=W):W=e[13];let ie;e[14]!==W?(ie=W.map(zt),e[14]=W,e[15]=ie):ie=e[15];let ve=ie,$;e[16]!==P||e[17]!==C?($=(0,t.jsx)(Xe,{onChange:P,testId:"sc-shard-input",value:C}),e[16]=P,e[17]=C,e[18]=$):$=e[18];let Y;e[19]!==a?(Y=a("Schema view"),e[19]=a,e[20]=Y):Y=e[20];let ee=I==="graph",de=I==="graph",R;e[21]!==de?(R=lt(de),e[21]=de,e[22]=R):R=e[22];let te;e[23]!==a?(te=a("Graph"),e[23]=a,e[24]=te):te=e[24];let j;e[25]!==D||e[26]!==ee||e[27]!==R||e[28]!==te?(j=(0,t.jsx)("button",{"aria-selected":ee,className:R,"data-testid":"sc-view-graph",onClick:D,role:"tab",type:"button",children:te}),e[25]=D,e[26]=ee,e[27]=R,e[28]=te,e[29]=j):j=e[29];let ye=I==="list",ce=I==="list",ge;e[30]!==ce?(ge=lt(ce),e[30]=ce,e[31]=ge):ge=e[31];let V;e[32]!==a?(V=a("Table list"),e[32]=a,e[33]=V):V=e[33];let X;e[34]!==k||e[35]!==ye||e[36]!==ge||e[37]!==V?(X=(0,t.jsx)("button",{"aria-selected":ye,className:ge,"data-testid":"sc-view-list",onClick:k,role:"tab",type:"button",children:V}),e[34]=k,e[35]=ye,e[36]=ge,e[37]=V,e[38]=X):X=e[38];let B;e[39]!==j||e[40]!==X||e[41]!==Y?(B=(0,t.jsxs)("div",{"aria-label":Y,className:"flex items-center gap-1","data-testid":"sc-view-toggle",role:"tablist",children:[j,X]}),e[39]=j,e[40]=X,e[41]=Y,e[42]=B):B=e[42];let le;e[43]!==B||e[44]!==$?(le=(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[$,B]}),e[43]=B,e[44]=$,e[45]=le):le=e[45];let U;e[46]!==xe||e[47]!==l||e[48]!==ve?(U=l===!0&&(0,t.jsx)(wt,{onApplied:xe,tableNames:ve}),e[46]=xe,e[47]=l,e[48]=ve,e[49]=U):U=e[49];let ae;e[50]!==Q||e[51]!==a||e[52]!==F||e[53]!==I?(ae=I==="list"&&(0,t.jsx)(Ae,{"aria-label":a("Filter tables"),className:"h-8 max-w-xs","data-testid":"sc-filter",onChange:Q,placeholder:a("Filter tables"),value:F}),e[50]=Q,e[51]=a,e[52]=F,e[53]=I,e[54]=ae):ae=e[54];let z;e[55]!==d||e[56]!==b||e[57]!==g||e[58]!==T||e[59]!==C||e[60]!==I?(z=I==="graph"&&(0,t.jsxs)("div",{className:"flex flex-col gap-2","data-testid":"sc-graph-view",children:[b!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"sc-error",role:"alert",children:b}),g!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"sc-global-error",role:"alert",children:g}),(0,t.jsx)(He,{columnsError:T[C]===!0,tables:d,testIdPrefix:"sc-graph"})]}),e[55]=d,e[56]=b,e[57]=g,e[58]=T,e[59]=C,e[60]=I,e[61]=z):z=e[61];let ne;e[62]!==c||e[63]!==b||e[64]!==o||e[65]!==p||e[66]!==i||e[67]!==v||e[68]!==g||e[69]!==K||e[70]!==_||e[71]!==L||e[72]!==C||e[73]!==a||e[74]!==O||e[75]!==he||e[76]!==H||e[77]!==I?(ne=I==="list"&&(0,t.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,t.jsxs)(qe,{"data-testid":"sc-shard-section",size:"sm",children:[(0,t.jsxs)(Ke,{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Ve,{tier:"shard"}),(0,t.jsx)(Pe,{children:a("Shard tables")}),O!==null&&(0,t.jsx)(ze,{className:"ms-auto tabular-nums",variant:"outline",children:i.length})]}),(0,t.jsx)(Ge,{children:Me.shard.hint})]}),(0,t.jsxs)(Le,{children:[b!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"sc-error",role:"alert",children:b}),O!==null&&O.length===0&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground","data-testid":"sc-empty",children:a("No tables in this shard.")}),O!==null&&O.length>0&&i.length===0&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground","data-testid":"sc-no-match",children:a("No tables match your filter.")}),i.length>0&&(0,t.jsx)("ul",{className:"-mx-3 overflow-hidden border-t border-border","data-testid":"sc-table-list",children:i.map(f=>{let re=`${C}:${f.name}`,Z=L[re]??[];return(0,t.jsxs)(et,{expanded:o===f.name,name:f.name,onToggle:r(()=>{ue(he(f.name))},"onToggle"),rowCount:f.rowCount,rowTestId:`sc-table-${f.name}`,toggleTestId:`sc-toggle-${f.name}`,children:[(0,t.jsx)(tt,{columns:c[re]??Ye,testId:`sc-columns-${f.name}`}),Z.length>0&&(0,t.jsx)(It,{heading:a("Indexes"),indexes:Z,testId:`sc-indexes-${f.name}`})]},f.name)})})]})]}),(0,t.jsxs)(qe,{"data-testid":"sc-global-section",size:"sm",children:[(0,t.jsxs)(Ke,{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Ve,{tier:"global"}),(0,t.jsx)(Pe,{children:a("Global tables (D1)")}),_!==null&&(0,t.jsx)(ze,{className:"ms-auto tabular-nums",variant:"outline",children:p.length})]}),(0,t.jsx)(Ge,{children:Me.global.hint})]}),(0,t.jsxs)(Le,{children:[g!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"sc-global-error",role:"alert",children:g}),_!==null&&_.length===0&&(0,t.jsx)(Je,{description:Me.global.hint,testId:"sc-global-empty",title:a("No global tables.")}),_!==null&&_.length>0&&p.length===0&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground","data-testid":"sc-global-no-match",children:a("No tables match your filter.")}),p.length>0&&(0,t.jsx)("ul",{className:"-mx-3 overflow-hidden border-t border-border","data-testid":"sc-global-table-list",children:p.map(f=>(0,t.jsx)(et,{expanded:K===f.name,name:f.name,onToggle:r(()=>{ue(H(f.name))},"onToggle"),rowCount:f.rowCount,rowTestId:`sc-global-table-${f.name}`,toggleTestId:`sc-global-toggle-${f.name}`,children:(0,t.jsx)(tt,{columns:v[f.name]??Ye,testId:`sc-global-columns-${f.name}`})},f.name))})]})]})]}),e[62]=c,e[63]=b,e[64]=o,e[65]=p,e[66]=i,e[67]=v,e[68]=g,e[69]=K,e[70]=_,e[71]=L,e[72]=C,e[73]=a,e[74]=O,e[75]=he,e[76]=H,e[77]=I,e[78]=ne):ne=e[78];let se;return e[79]!==le||e[80]!==U||e[81]!==ae||e[82]!==z||e[83]!==ne?(se=(0,t.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-schema",children:[le,U,ae,z,ne]}),e[79]=le,e[80]=U,e[81]=ae,e[82]=z,e[83]=ne,e[84]=se):se=e[84],se},"Zt");function At(s){return(0,t.jsx)("li",{className:"rounded bg-muted px-1.5 py-0.5 font-mono text-[11px] text-muted-foreground",children:s},s)}r(At,"kt");function Ft(s){return(0,t.jsxs)("li",{className:"flex flex-wrap items-center gap-1.5 text-xs",children:[(0,t.jsx)("span",{className:"font-mono",children:s.name}),(0,t.jsx)(ze,{variant:"outline",children:s.type}),s.unique===!0&&(0,t.jsx)(ze,{variant:"secondary",children:"unique"}),(0,t.jsx)("span",{className:"text-muted-foreground",children:s.fields.join(", ")})]},`${s.type}:${s.name}`)}r(Ft,"It");function zt(s){return s.name}r(zt,"At");export{Xt as SchemaViewer};
|
|
1
|
+
import{a as He}from"./chunk-IUUSMC2R.js";import{a as Me,b as Ve}from"./chunk-GMR677FL.js";import"./chunk-7H7LZRLP.js";import"./chunk-SD4BERSA.js";import"./chunk-IC4L6G56.js";import{a as we}from"./chunk-5Y3QLNWX.js";import"./chunk-I6A5C46N.js";import"./chunk-2QSHLBCO.js";import"./chunk-BGBLQ563.js";import"./chunk-IVFHIQOT.js";import"./chunk-QBWRC5YX.js";import"./chunk-4UOFSGUS.js";import{a as Ze}from"./chunk-3CWGJYBB.js";import{a as Xe}from"./chunk-RMN2JN4S.js";import{b as We}from"./chunk-GRL5MG3Z.js";import{e as Ue}from"./chunk-SMIESS7P.js";import"./chunk-7T7UOTYK.js";import{R as Ae}from"./chunk-CFPZYHPY.js";import"./chunk-T6VMSOBB.js";import"./chunk-7QIFDWQV.js";import{c as me}from"./chunk-FXCBF4XT.js";import"./chunk-2OUPA2WJ.js";import{b as ze}from"./chunk-THIXMMZD.js";import"./chunk-6ST5ECQA.js";import{a as je}from"./chunk-VDW32UET.js";import{f as Be}from"./chunk-DBWOWJYT.js";import"./chunk-XBDKZZ67.js";import{a as Je}from"./chunk-XQCVZAGU.js";import{a as qe,b as Ke,c as Pe,d as Ge,e as Le}from"./chunk-UZERI5YC.js";import{d as Fe,f as Ee,g as Oe,h as $e,o as ue}from"./chunk-IUYFXK4X.js";import"./chunk-XNGYYOLS.js";import{a as r,e as De,f as at,g as nt,h as st,j as Re}from"./chunk-3XIESWL4.js";var Ce=De(nt(),1);var x=De(at(),1);var t=De(st(),1);var rt=Ee(je.listTables),ot=Ee(je.listTableIndexes),it=Ee(je.readTablePage),dt=Ee(je.describeTables),ct={},Qe=[],mt=r(s=>{let e=(0,Ce.c)(74),{initialShardKey:u,initialTable:n}=s,l=Be(),[a,m]=(0,x.useState)("graph"),{queryShardKey:c,setShardKey:d,shardKey:b}=Ze(u),[o,p]=(0,x.useState)(""),[i,v]=(0,x.useState)(null),[g,K]=(0,x.useState)(null),_;e[0]===Symbol.for("react.memo_cache_sentinel")?(_={},e[0]=_):_=e[0];let[L,y]=(0,x.useState)(_),P;e[1]===Symbol.for("react.memo_cache_sentinel")?(P={},e[1]=P):P=e[1];let[E,M]=(0,x.useState)(P),[T,C]=(0,x.useState)(null),F;e[2]===Symbol.for("react.memo_cache_sentinel")?(F={},e[2]=F):F=e[2];let[O,he]=(0,x.useState)(F),H;e[3]===Symbol.for("react.memo_cache_sentinel")?(H={},e[3]=H):H=e[3];let[I,G]=(0,x.useState)(H),[k,pe]=(0,x.useState)(null),[D,oe]=(0,x.useState)(null),Q;e[4]===Symbol.for("react.memo_cache_sentinel")?(Q={},e[4]=Q):Q=e[4];let[J,xe]=(0,x.useState)(Q),[W,ie]=(0,x.useState)(null),ve;e[5]!==l?(ve=r(async h=>{K(null);try{let w=await l.query(rt,{},Oe(h));We(h),v(w),y({}),M({}),C(null),he(N=>Object.fromEntries(Object.entries(N).filter(q=>{let[A]=q;return A!==h}))),G(N=>Object.fromEntries(Object.entries(N).filter(q=>{let[A]=q;return A!==h})))}catch(w){let N=w;v(null),K($e(N))}},"ve"),e[5]=l,e[6]=ve):ve=e[6];let $=ve,Y;e[7]!==l?(Y=r(async()=>{oe(null);try{pe(await l.listGlobalTables())}catch(h){let w=h;pe(null),oe($e(w))}},"Q"),e[7]=l,e[8]=Y):Y=e[8];let ee=Y,de,R;e[9]!==c||e[10]!==$||e[11]!==ee?(de=r(()=>{ue($(c)),ue(ee())},"de"),R=[$,ee,c],e[9]=c,e[10]=$,e[11]=ee,e[12]=de,e[13]=R):(de=e[12],R=e[13]),(0,x.useEffect)(de,R);let te;e[14]!==l||e[15]!==L||e[16]!==T||e[17]!==c?(te=r(async h=>{if(T===h){C(null);return}C(h);let w=`${c}:${h}`;if(L[w]!==void 0)return;let[N,q]=await Promise.allSettled([l.query(it,{limit:1,offset:0,table:h},Oe(c)),l.query(ot,{table:h},Oe(c))]);N.status==="fulfilled"?y(A=>({...A,[w]:N.value.columns})):K($e(N.reason)),q.status==="fulfilled"&&M(A=>({...A,[w]:q.value.indexes}))},"te"),e[14]=l,e[15]=L,e[16]=T,e[17]=c,e[18]=te):te=e[18];let j=te,ye;e[19]!==l||e[20]!==J||e[21]!==W?(ye=r(async h=>{if(W===h){ie(null);return}if(ie(h),J[h]===void 0)try{let w=await l.readGlobalTablePage({limit:1,offset:0,table:h});xe(N=>({...N,[h]:w.columns}))}catch(w){oe($e(w))}},"ye"),e[19]=l,e[20]=J,e[21]=W,e[22]=ye):ye=e[22];let ce=ye,ge=(0,x.useRef)(void 0),V,X;e[23]!==n||e[24]!==i||e[25]!==j?(V=r(()=>{n===void 0||i===null||ge.current===n||i.some(h=>h.name===n)&&(ge.current=n,ue(j(n)))},"V"),X=[n,i,j],e[23]=n,e[24]=i,e[25]=j,e[26]=V,e[27]=X):(V=e[26],X=e[27]),(0,x.useEffect)(V,X);let B;e[28]!==l?(B=r(async(h,w,N)=>{let[q,A]=await Promise.all([Promise.allSettled([l.query(dt,{tables:[...w,...N]},Oe(h))]),Promise.all(N.map(async S=>{let be=await Promise.allSettled([l.readGlobalTablePage({limit:1,offset:0,table:S})]),Ie=be[0].status==="fulfilled"?be[0].value:void 0;return{columns:Ie?.columns??[],refs:Ie?.refs??{},table:S}}))]),Se=q[0].status==="fulfilled"?q[0].value?.columnsByTable??{}:{},Te=q[0].status==="rejected",_e=new Map(A.map(ut)),ke=[...w,...N].map(S=>{let be=Se[S]??[];return[S,be.length>0?be:_e.get(S)??[]]});he(S=>({...S,[h]:Object.fromEntries(ke)})),G(S=>({...S,[h]:Te}))},"B"),e[28]=l,e[29]=B):B=e[29];let le=B,U,ae;e[30]!==D||e[31]!==k||e[32]!==le||e[33]!==c||e[34]!==O||e[35]!==i||e[36]!==a?(U=r(()=>{a!=="graph"||i===null||k===null&&D===null||O[c]!==void 0||ue(le(c,i.map(ht),(k??[]).map(pt)))},"U"),ae=[a,i,k,D,c,O,le],e[30]=D,e[31]=k,e[32]=le,e[33]=c,e[34]=O,e[35]=i,e[36]=a,e[37]=U,e[38]=ae):(U=e[37],ae=e[38]),(0,x.useEffect)(U,ae);let z=O[c]??ct,ne;if(e[39]!==z||e[40]!==k||e[41]!==i){let h;e[43]!==z?(h=r(A=>({columns:z[A.name]??Qe,name:A.name,tier:"shard"}),"u"),e[43]=z,e[44]=h):h=e[44];let w=(i??[]).map(h),N;e[45]!==z?(N=r(A=>({columns:z[A.name]??Qe,name:A.name,tier:"global"}),"y"),e[45]=z,e[46]=N):N=e[46];let q=(k??[]).map(N);ne=[...w,...q],e[39]=z,e[40]=k,e[41]=i,e[42]=ne}else ne=e[42];let se=ne,f;if(e[47]!==o||e[48]!==i){let h=o.trim().toLowerCase();f=(i??[]).filter(w=>w.name.toLowerCase().includes(h)),e[47]=o,e[48]=i,e[49]=f}else f=e[49];let re=f,Z;if(e[50]!==k||e[51]!==o){let h=o.trim().toLowerCase();Z=(k??[]).filter(w=>w.name.toLowerCase().includes(h)),e[50]=k,e[51]=o,e[52]=Z}else Z=e[52];let Ne=Z,fe;return e[53]!==L||e[54]!==se||e[55]!==g||e[56]!==T||e[57]!==Ne||e[58]!==re||e[59]!==J||e[60]!==D||e[61]!==W||e[62]!==k||e[63]!==E||e[64]!==$||e[65]!==d||e[66]!==I||e[67]!==b||e[68]!==o||e[69]!==i||e[70]!==j||e[71]!==ce||e[72]!==a?(fe={columns:L,diagramTables:se,error:g,expanded:T,filteredGlobalTables:Ne,filteredTables:re,globalColumns:J,globalError:D,globalExpanded:W,globalTables:k,indexes:E,refresh:$,setShardKey:d,setTableFilter:p,setView:m,shardColumnsError:I,shardKey:b,tableFilter:o,tables:i,toggle:j,toggleGlobal:ce,view:a},e[53]=L,e[54]=se,e[55]=g,e[56]=T,e[57]=Ne,e[58]=re,e[59]=J,e[60]=D,e[61]=W,e[62]=k,e[63]=E,e[64]=$,e[65]=d,e[66]=I,e[67]=b,e[68]=o,e[69]=i,e[70]=j,e[71]=ce,e[72]=a,e[73]=fe):fe=e[73],fe},"ct");function ut(s){let{columns:e,refs:u,table:n}=s;return[n,e.map(l=>{let a=u[l];return a===void 0?{name:l,optional:!1,type:""}:{name:l,optional:!1,ref:a,type:"id"}})]}r(ut,"mt");function ht(s){return s.name}r(ht,"ut");function pt(s){return s.name}r(pt,"ht");var gt="/__lunora/schema-edit",ft=r(async s=>{let e=await fetch(gt,{body:JSON.stringify(s),headers:{"Content-Type":"application/json","X-Lunora-Studio":"1"},method:"POST"}),u=await e.json();return u.needsMigration===!0?{kind:"needs-migration",message:u.message??"This edit needs a migration."}:e.ok&&u.tables!==void 0?{diagnostics:u.diagnostics??[],kind:"ok",tables:u.tables}:{kind:"error",message:u.error??`schema edit failed (${String(e.status)})`}},"gt"),bt=r(s=>{let e=(0,Ce.c)(32),{hasTables:u,mode:n,onAddColumn:l,onAddIndex:a,onAddTable:m,onDestructive:c}=s,d=Fe(),b=n==="addTable"?"default":"outline",o;e[0]!==d?(o=d("Add table"),e[0]=d,e[1]=o):o=e[1];let p;e[2]!==m||e[3]!==b||e[4]!==o?(p=(0,t.jsx)(me,{"data-testid":"sc-editor-add-table",onClick:m,size:"xs",type:"button",variant:b,children:o}),e[2]=m,e[3]=b,e[4]=o,e[5]=p):p=e[5];let i=!u,v=n==="addColumn"?"default":"outline",g;e[6]!==d?(g=d("Add column"),e[6]=d,e[7]=g):g=e[7];let K;e[8]!==l||e[9]!==i||e[10]!==v||e[11]!==g?(K=(0,t.jsx)(me,{"data-testid":"sc-editor-add-column",disabled:i,onClick:l,size:"xs",type:"button",variant:v,children:g}),e[8]=l,e[9]=i,e[10]=v,e[11]=g,e[12]=K):K=e[12];let _=!u,L=n==="addIndex"?"default":"outline",y;e[13]!==d?(y=d("Add index"),e[13]=d,e[14]=y):y=e[14];let P;e[15]!==a||e[16]!==y||e[17]!==_||e[18]!==L?(P=(0,t.jsx)(me,{"data-testid":"sc-editor-add-index",disabled:_,onClick:a,size:"xs",type:"button",variant:L,children:y}),e[15]=a,e[16]=y,e[17]=_,e[18]=L,e[19]=P):P=e[19];let E=!u,M=n==="destructive"?"default":"ghost",T;e[20]!==d?(T=d("Rename / drop / change type\u2026"),e[20]=d,e[21]=T):T=e[21];let C;e[22]!==c||e[23]!==E||e[24]!==M||e[25]!==T?(C=(0,t.jsx)(me,{"data-testid":"sc-editor-destructive",disabled:E,onClick:c,size:"xs",type:"button",variant:M,children:T}),e[22]=c,e[23]=E,e[24]=M,e[25]=T,e[26]=C):C=e[26];let F;return e[27]!==P||e[28]!==C||e[29]!==p||e[30]!==K?(F=(0,t.jsxs)("div",{className:"flex flex-wrap gap-2",children:[p,K,P,C]}),e[27]=P,e[28]=C,e[29]=p,e[30]=K,e[31]=F):F=e[31],F},"bt"),xt=r(s=>{let e=(0,Ce.c)(28),{onOpenMigrations:u,result:n}=s,l=Fe();if(n===null){let o;return e[0]===Symbol.for("react.memo_cache_sentinel")?(o=(0,t.jsx)(t.Fragment,{}),e[0]=o):o=e[0],o}if(n.kind==="error"){let o;return e[1]!==n.message?(o=(0,t.jsx)("p",{className:"mt-3 text-sm text-destructive","data-testid":"sc-editor-error",role:"alert",children:n.message}),e[1]=n.message,e[2]=o):o=e[2],o}if(n.kind==="needs-migration"){let o;e[3]!==n.message||e[4]!==l?(o=n.message===""?l("This edit changes stored data and must go through a migration. Review the migration before applying."):n.message,e[3]=n.message,e[4]=l,e[5]=o):o=e[5];let p;e[6]!==o?(p=(0,t.jsx)("p",{className:"text-sm text-warning",role:"alert",children:o}),e[6]=o,e[7]=p):p=e[7];let i;e[8]!==l?(i=l("Open Migrations"),e[8]=l,e[9]=i):i=e[9];let v;e[10]!==u||e[11]!==i?(v=(0,t.jsx)(me,{className:"self-start","data-testid":"sc-editor-open-migrations",onClick:u,size:"xs",type:"button",variant:"outline",children:i}),e[10]=u,e[11]=i,e[12]=v):v=e[12];let g;return e[13]!==p||e[14]!==v?(g=(0,t.jsxs)("div",{className:"mt-3 flex flex-col gap-2","data-testid":"sc-editor-needs-migration",children:[p,v]}),e[13]=p,e[14]=v,e[15]=g):g=e[15],g}if(n.diagnostics.length===0){let o;return e[16]===Symbol.for("react.memo_cache_sentinel")?(o=(0,t.jsx)(t.Fragment,{}),e[16]=o):o=e[16],o}let a;e[17]!==l?(a=l("Codegen reported diagnostics:"),e[17]=l,e[18]=a):a=e[18];let m;e[19]!==a?(m=(0,t.jsx)("p",{className:"text-sm text-destructive",role:"alert",children:a}),e[19]=a,e[20]=m):m=e[20];let c;e[21]!==n.diagnostics?(c=n.diagnostics.map(vt),e[21]=n.diagnostics,e[22]=c):c=e[22];let d;e[23]!==c?(d=(0,t.jsx)("ul",{className:"flex flex-col gap-0.5",children:c}),e[23]=c,e[24]=d):d=e[24];let b;return e[25]!==m||e[26]!==d?(b=(0,t.jsxs)("div",{className:"mt-3 flex flex-col gap-1","data-testid":"sc-editor-diagnostics",children:[m,d]}),e[25]=m,e[26]=d,e[27]=b):b=e[27],b},"ft");function vt(s){return(0,t.jsx)("li",{className:"font-mono text-[11px] text-destructive",children:s},s)}r(vt,"xt");var yt=[{label:"string",validator:"v.string()"},{label:"number",validator:"v.number()"},{label:"boolean",validator:"v.boolean()"},{label:"bigint",validator:"v.int64()"},{label:"bytes",validator:"v.bytes()"},{label:"any",validator:"v.any()"}],Nt="v.string()",Ct=r(s=>s.split(",").map(e=>e.trim()).filter(e=>e!==""),"Nt"),wt=r(s=>{let e=(0,Ce.c)(83),{onApplied:u,tableNames:n}=s,l=Fe(),a=Ue(),[m,c]=(0,x.useState)(null),[d,b]=(0,x.useState)(!1),[o,p]=(0,x.useState)(null),[i,v]=(0,x.useState)(""),[g,K]=(0,x.useState)(""),[_,L]=(0,x.useState)(Nt),[y,P]=(0,x.useState)(n[0]??""),[E,M]=(0,x.useState)(""),[T,C]=(0,x.useState)(""),[F,O]=(0,x.useState)(!1),he;e[0]===Symbol.for("react.memo_cache_sentinel")?(he=r(()=>{c(null),v(""),K(""),M(""),C(""),O(!1)},"me"),e[0]=he):he=e[0];let H=he,I;e[1]!==u?(I=r(async S=>{b(!0),p(null);try{let be=await ft(S);p(be),be.kind==="ok"&&(u(be.tables),H())}catch(be){let Ie=be;p({kind:"error",message:Ie instanceof Error?Ie.message:String(Ie)})}b(!1)},"k"),e[1]=u,e[2]=I):I=e[2];let G=I,k;e[3]!==G||e[4]!==i?(k=r(()=>{ue(G({kind:"addTable",table:i.trim()}))},"_"),e[3]=G,e[4]=i,e[5]=k):k=e[5];let pe=k,D;e[6]!==g||e[7]!==G||e[8]!==y||e[9]!==_?(D=r(()=>{ue(G({column:g.trim(),kind:"addOptionalColumn",table:y,validator:_}))},"D"),e[6]=g,e[7]=G,e[8]=y,e[9]=_,e[10]=D):D=e[10];let oe=D,Q;e[11]!==T||e[12]!==E||e[13]!==G||e[14]!==y||e[15]!==F?(Q=r(()=>{ue(G({fields:Ct(T),kind:"addIndex",name:E.trim(),table:y,unique:F}))},"H"),e[11]=T,e[12]=E,e[13]=G,e[14]=y,e[15]=F,e[16]=Q):Q=e[16];let J=Q,xe;e[17]===Symbol.for("react.memo_cache_sentinel")?(xe=r(()=>{p(null),c("addTable")},"xe"),e[17]=xe):xe=e[17];let W=xe,ie;e[18]===Symbol.for("react.memo_cache_sentinel")?(ie=r(()=>{p(null),c("addColumn")},"ie"),e[18]=ie):ie=e[18];let ve=ie,$;e[19]===Symbol.for("react.memo_cache_sentinel")?($=r(()=>{p(null),c("addIndex")},"q"),e[19]=$):$=e[19];let Y=$,ee;e[20]!==l?(ee=r(()=>{c("destructive"),p({kind:"needs-migration",message:l("This edit changes stored data and must go through a migration. Review the migration before applying.")})},"ee"),e[20]=l,e[21]=ee):ee=e[21];let de=ee,R;e[22]===Symbol.for("react.memo_cache_sentinel")?(R=r(S=>{v(S.target.value)},"R"),e[22]=R):R=e[22];let te=R,j;e[23]===Symbol.for("react.memo_cache_sentinel")?(j=r(S=>{K(S.target.value)},"z"),e[23]=j):j=e[23];let ye=j,ce;e[24]===Symbol.for("react.memo_cache_sentinel")?(ce=r(S=>{L(S.target.value)},"ce"),e[24]=ce):ce=e[24];let ge=ce,V;e[25]===Symbol.for("react.memo_cache_sentinel")?(V=r(S=>{P(S.target.value)},"V"),e[25]=V):V=e[25];let X=V,B;e[26]===Symbol.for("react.memo_cache_sentinel")?(B=r(S=>{M(S.target.value)},"B"),e[26]=B):B=e[26];let le=B,U;e[27]===Symbol.for("react.memo_cache_sentinel")?(U=r(S=>{C(S.target.value)},"U"),e[27]=U):U=e[27];let ae=U,z;e[28]===Symbol.for("react.memo_cache_sentinel")?(z=r(S=>{O(S.target.checked)},"E"),e[28]=z):z=e[28];let ne=z,se;e[29]!==a?(se=r(()=>{ue(a({to:"/migrations"}))},"se"),e[29]=a,e[30]=se):se=e[30];let f=se,re;e[31]!==l?(re=l("Edit schema"),e[31]=l,e[32]=re):re=e[32];let Z;e[33]!==re?(Z=(0,t.jsx)(Pe,{children:re}),e[33]=re,e[34]=Z):Z=e[34];let Ne;e[35]!==l?(Ne=l("Adds a table, column, or index to lunora/schema.ts and reruns codegen."),e[35]=l,e[36]=Ne):Ne=e[36];let fe;e[37]!==Ne?(fe=(0,t.jsx)(Ge,{children:Ne}),e[37]=Ne,e[38]=fe):fe=e[38];let h;e[39]!==Z||e[40]!==fe?(h=(0,t.jsxs)(Ke,{children:[Z,fe]}),e[39]=Z,e[40]=fe,e[41]=h):h=e[41];let w=n.length>0,N;e[42]!==m||e[43]!==de||e[44]!==w?(N=(0,t.jsx)(bt,{hasTables:w,mode:m,onAddColumn:ve,onAddIndex:Y,onAddTable:W,onDestructive:de}),e[42]=m,e[43]=de,e[44]=w,e[45]=N):N=e[45];let q;e[46]!==d||e[47]!==m||e[48]!==pe||e[49]!==l||e[50]!==i?(q=m==="addTable"&&(0,t.jsxs)("div",{className:"mt-3 flex flex-wrap items-end gap-2","data-testid":"sc-editor-table-form",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(we,{htmlFor:"sc-editor-table-name",children:l("Table name")}),(0,t.jsx)(Ae,{"data-testid":"sc-editor-table-name",id:"sc-editor-table-name",onChange:te,value:i})]}),(0,t.jsx)(me,{"data-testid":"sc-editor-table-apply",disabled:d||i.trim()==="",onClick:pe,size:"xs",type:"button",children:l(d?"Applying\u2026":"Apply")}),(0,t.jsx)(me,{onClick:H,size:"xs",type:"button",variant:"ghost",children:l("Cancel")})]}),e[46]=d,e[47]=m,e[48]=pe,e[49]=l,e[50]=i,e[51]=q):q=e[51];let A;e[52]!==d||e[53]!==g||e[54]!==m||e[55]!==oe||e[56]!==l||e[57]!==n||e[58]!==y||e[59]!==_?(A=m==="addColumn"&&(0,t.jsxs)("div",{className:"mt-3 flex flex-wrap items-end gap-2","data-testid":"sc-editor-column-form",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(we,{htmlFor:"sc-editor-column-table",children:l("Table name")}),(0,t.jsx)("select",{className:"h-8 rounded-md border border-input bg-transparent px-2 text-xs","data-testid":"sc-editor-column-table",id:"sc-editor-column-table",onChange:X,value:y,children:n.map(St)})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(we,{htmlFor:"sc-editor-column-name",children:l("Column name")}),(0,t.jsx)(Ae,{"data-testid":"sc-editor-column-name",id:"sc-editor-column-name",onChange:ye,value:g})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(we,{htmlFor:"sc-editor-column-type",children:l("Column type")}),(0,t.jsx)("select",{className:"h-8 rounded-md border border-input bg-transparent px-2 text-xs","data-testid":"sc-editor-column-type",id:"sc-editor-column-type",onChange:ge,value:_,children:yt.map(Tt)})]}),(0,t.jsx)("span",{className:"text-[11px] text-muted-foreground",children:l("Optional")}),(0,t.jsx)(me,{"data-testid":"sc-editor-column-apply",disabled:d||g.trim()===""||y==="",onClick:oe,size:"xs",type:"button",children:l(d?"Applying\u2026":"Apply")}),(0,t.jsx)(me,{onClick:H,size:"xs",type:"button",variant:"ghost",children:l("Cancel")})]}),e[52]=d,e[53]=g,e[54]=m,e[55]=oe,e[56]=l,e[57]=n,e[58]=y,e[59]=_,e[60]=A):A=e[60];let Se;e[61]!==d||e[62]!==T||e[63]!==E||e[64]!==m||e[65]!==J||e[66]!==l||e[67]!==n||e[68]!==y||e[69]!==F?(Se=m==="addIndex"&&(0,t.jsxs)("div",{className:"mt-3 flex flex-wrap items-end gap-2","data-testid":"sc-editor-index-form",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(we,{htmlFor:"sc-editor-index-table",children:l("Table name")}),(0,t.jsx)("select",{className:"h-8 rounded-md border border-input bg-transparent px-2 text-xs","data-testid":"sc-editor-index-table",id:"sc-editor-index-table",onChange:X,value:y,children:n.map(_t)})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(we,{htmlFor:"sc-editor-index-name",children:l("Index name")}),(0,t.jsx)(Ae,{"data-testid":"sc-editor-index-name",id:"sc-editor-index-name",onChange:le,value:E})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(we,{htmlFor:"sc-editor-index-fields",children:l("Index fields (comma-separated)")}),(0,t.jsx)(Ae,{"data-testid":"sc-editor-index-fields",id:"sc-editor-index-fields",onChange:ae,value:T})]}),(0,t.jsxs)(we,{className:"flex items-center gap-1 text-xs",htmlFor:"sc-editor-index-unique",children:[(0,t.jsx)("input",{checked:F,"data-testid":"sc-editor-index-unique",id:"sc-editor-index-unique",onChange:ne,type:"checkbox"}),(0,t.jsx)("span",{className:"text-muted-foreground",children:l("Unique")})]}),(0,t.jsx)(me,{"data-testid":"sc-editor-index-apply",disabled:d||E.trim()===""||T.trim()==="",onClick:J,size:"xs",type:"button",children:l(d?"Applying\u2026":"Apply")}),(0,t.jsx)(me,{onClick:H,size:"xs",type:"button",variant:"ghost",children:l("Cancel")})]}),e[61]=d,e[62]=T,e[63]=E,e[64]=m,e[65]=J,e[66]=l,e[67]=n,e[68]=y,e[69]=F,e[70]=Se):Se=e[70];let Te;e[71]!==f||e[72]!==o?(Te=(0,t.jsx)(xt,{onOpenMigrations:f,result:o}),e[71]=f,e[72]=o,e[73]=Te):Te=e[73];let _e;e[74]!==N||e[75]!==q||e[76]!==A||e[77]!==Se||e[78]!==Te?(_e=(0,t.jsxs)(Le,{children:[N,q,A,Se,Te]}),e[74]=N,e[75]=q,e[76]=A,e[77]=Se,e[78]=Te,e[79]=_e):_e=e[79];let ke;return e[80]!==h||e[81]!==_e?(ke=(0,t.jsxs)(qe,{"data-testid":"sc-editor",size:"sm",children:[h,_e]}),e[80]=h,e[81]=_e,e[82]=ke):ke=e[82],ke},"Ct");function St(s){return(0,t.jsx)("option",{value:s,children:s},s)}r(St,"Tt");function Tt(s){return(0,t.jsx)("option",{value:s.validator,children:s.label},s.validator)}r(Tt,"wt");function _t(s){return(0,t.jsx)("option",{value:s,children:s},s)}r(_t,"St");var Ye=[],kt=r(s=>{let e=(0,Ce.c)(5),{open:u}=s,n=u&&"rotate-90",l;e[0]!==n?(l=Re("size-3.5 shrink-0 text-muted-foreground transition-transform duration-150",n),e[0]=n,e[1]=l):l=e[1];let a;e[2]===Symbol.for("react.memo_cache_sentinel")?(a=(0,t.jsx)("path",{d:"m9 6 6 6-6 6"}),e[2]=a):a=e[2];let m;return e[3]!==l?(m=(0,t.jsx)("svg",{"aria-hidden":"true",className:l,fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.8,viewBox:"0 0 24 24",children:a}),e[3]=l,e[4]=m):m=e[4],m},"_t"),et=r(s=>{let e=(0,Ce.c)(20),{children:u,expanded:n,name:l,onToggle:a,rowCount:m,rowTestId:c,toggleTestId:d}=s,b;e[0]!==n?(b=(0,t.jsx)(kt,{open:n}),e[0]=n,e[1]=b):b=e[1];let o;e[2]!==l?(o=(0,t.jsx)("span",{className:"truncate font-mono text-xs text-foreground",title:l,children:l}),e[2]=l,e[3]=o):o=e[3];let p;e[4]!==m?(p=(0,t.jsxs)("span",{className:"ms-auto shrink-0 text-xs text-muted-foreground tabular-nums",children:["(",m,")"]}),e[4]=m,e[5]=p):p=e[5];let i;e[6]!==n||e[7]!==a||e[8]!==b||e[9]!==o||e[10]!==p||e[11]!==d?(i=(0,t.jsxs)("button",{"aria-expanded":n,className:"flex w-full items-center gap-2 px-3 py-2 text-start transition-colors hover:bg-muted/50 aria-expanded:bg-muted/40","data-testid":d,onClick:a,type:"button",children:[b,o," ",p]}),e[6]=n,e[7]=a,e[8]=b,e[9]=o,e[10]=p,e[11]=d,e[12]=i):i=e[12];let v;e[13]!==u||e[14]!==n?(v=n&&(0,t.jsx)("div",{className:"px-3 pb-3 ps-8",children:u}),e[13]=u,e[14]=n,e[15]=v):v=e[15];let g;return e[16]!==c||e[17]!==i||e[18]!==v?(g=(0,t.jsxs)("li",{className:"border-t border-border/60 first:border-t-0","data-testid":c,children:[i,v]}),e[16]=c,e[17]=i,e[18]=v,e[19]=g):g=e[19],g},"Xe"),tt=r(s=>{let e=(0,Ce.c)(5),{columns:u,testId:n}=s,l;e[0]!==u?(l=u.map(At),e[0]=u,e[1]=l):l=e[1];let a;return e[2]!==l||e[3]!==n?(a=(0,t.jsx)("ul",{className:"flex flex-wrap gap-1.5 pt-1","data-testid":n,children:l}),e[2]=l,e[3]=n,e[4]=a):a=e[4],a},"Ye"),It=r(s=>{let e=(0,Ce.c)(10),{heading:u,indexes:n,testId:l}=s,a;e[0]!==u?(a=(0,t.jsx)("p",{className:"mb-1.5 font-mono text-[10px] tracking-wide text-muted-foreground uppercase",children:u}),e[0]=u,e[1]=a):a=e[1];let m;e[2]!==n?(m=n.map(Ft),e[2]=n,e[3]=m):m=e[3];let c;e[4]!==m||e[5]!==l?(c=(0,t.jsx)("ul",{className:"flex flex-col gap-1","data-testid":l,children:m}),e[4]=m,e[5]=l,e[6]=c):c=e[6];let d;return e[7]!==a||e[8]!==c?(d=(0,t.jsxs)("div",{className:"pt-3",children:[a,c]}),e[7]=a,e[8]=c,e[9]=d):d=e[9],d},"$t"),lt=r(s=>Re("border-b-2 px-3 py-2 font-mono text-[11px] tracking-widest uppercase outline-none transition-colors",s?"border-foreground text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),"Je"),Xt=r(s=>{let e=(0,Ce.c)(85),{initialShardKey:u,initialTable:n,schemaEditable:l}=s,a=Fe(),m;e[0]!==u||e[1]!==n?(m={initialShardKey:u,initialTable:n},e[0]=u,e[1]=n,e[2]=m):m=e[2];let{columns:c,diagramTables:d,error:b,expanded:o,filteredGlobalTables:p,filteredTables:i,globalColumns:v,globalError:g,globalExpanded:K,globalTables:_,indexes:L,refresh:y,setShardKey:P,setTableFilter:E,setView:M,shardColumnsError:T,shardKey:C,tableFilter:F,tables:O,toggle:he,toggleGlobal:H,view:I}=mt(m),G;e[3]!==M?(G=r(()=>{M("list")},"G"),e[3]=M,e[4]=G):G=e[4];let k=G,pe;e[5]!==M?(pe=r(()=>{M("graph")},"ue"),e[5]=M,e[6]=pe):pe=e[6];let D=pe,oe;e[7]!==E?(oe=r(f=>{E(f.target.value)},"oe"),e[7]=E,e[8]=oe):oe=e[8];let Q=oe,J;e[9]!==y||e[10]!==C?(J=r(f=>{ue(y(C))},"X"),e[9]=y,e[10]=C,e[11]=J):J=e[11];let xe=J,W;e[12]!==O?(W=O??[],e[12]=O,e[13]=W):W=e[13];let ie;e[14]!==W?(ie=W.map(zt),e[14]=W,e[15]=ie):ie=e[15];let ve=ie,$;e[16]!==P||e[17]!==C?($=(0,t.jsx)(Xe,{onChange:P,testId:"sc-shard-input",value:C}),e[16]=P,e[17]=C,e[18]=$):$=e[18];let Y;e[19]!==a?(Y=a("Schema view"),e[19]=a,e[20]=Y):Y=e[20];let ee=I==="graph",de=I==="graph",R;e[21]!==de?(R=lt(de),e[21]=de,e[22]=R):R=e[22];let te;e[23]!==a?(te=a("Graph"),e[23]=a,e[24]=te):te=e[24];let j;e[25]!==D||e[26]!==ee||e[27]!==R||e[28]!==te?(j=(0,t.jsx)("button",{"aria-selected":ee,className:R,"data-testid":"sc-view-graph",onClick:D,role:"tab",type:"button",children:te}),e[25]=D,e[26]=ee,e[27]=R,e[28]=te,e[29]=j):j=e[29];let ye=I==="list",ce=I==="list",ge;e[30]!==ce?(ge=lt(ce),e[30]=ce,e[31]=ge):ge=e[31];let V;e[32]!==a?(V=a("Table list"),e[32]=a,e[33]=V):V=e[33];let X;e[34]!==k||e[35]!==ye||e[36]!==ge||e[37]!==V?(X=(0,t.jsx)("button",{"aria-selected":ye,className:ge,"data-testid":"sc-view-list",onClick:k,role:"tab",type:"button",children:V}),e[34]=k,e[35]=ye,e[36]=ge,e[37]=V,e[38]=X):X=e[38];let B;e[39]!==j||e[40]!==X||e[41]!==Y?(B=(0,t.jsxs)("div",{"aria-label":Y,className:"flex items-center gap-1","data-testid":"sc-view-toggle",role:"tablist",children:[j,X]}),e[39]=j,e[40]=X,e[41]=Y,e[42]=B):B=e[42];let le;e[43]!==B||e[44]!==$?(le=(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[$,B]}),e[43]=B,e[44]=$,e[45]=le):le=e[45];let U;e[46]!==xe||e[47]!==l||e[48]!==ve?(U=l===!0&&(0,t.jsx)(wt,{onApplied:xe,tableNames:ve}),e[46]=xe,e[47]=l,e[48]=ve,e[49]=U):U=e[49];let ae;e[50]!==Q||e[51]!==a||e[52]!==F||e[53]!==I?(ae=I==="list"&&(0,t.jsx)(Ae,{"aria-label":a("Filter tables"),className:"h-8 max-w-xs","data-testid":"sc-filter",onChange:Q,placeholder:a("Filter tables"),value:F}),e[50]=Q,e[51]=a,e[52]=F,e[53]=I,e[54]=ae):ae=e[54];let z;e[55]!==d||e[56]!==b||e[57]!==g||e[58]!==T||e[59]!==C||e[60]!==I?(z=I==="graph"&&(0,t.jsxs)("div",{className:"flex flex-col gap-2","data-testid":"sc-graph-view",children:[b!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"sc-error",role:"alert",children:b}),g!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"sc-global-error",role:"alert",children:g}),(0,t.jsx)(He,{columnsError:T[C]===!0,tables:d,testIdPrefix:"sc-graph"})]}),e[55]=d,e[56]=b,e[57]=g,e[58]=T,e[59]=C,e[60]=I,e[61]=z):z=e[61];let ne;e[62]!==c||e[63]!==b||e[64]!==o||e[65]!==p||e[66]!==i||e[67]!==v||e[68]!==g||e[69]!==K||e[70]!==_||e[71]!==L||e[72]!==C||e[73]!==a||e[74]!==O||e[75]!==he||e[76]!==H||e[77]!==I?(ne=I==="list"&&(0,t.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,t.jsxs)(qe,{"data-testid":"sc-shard-section",size:"sm",children:[(0,t.jsxs)(Ke,{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Ve,{tier:"shard"}),(0,t.jsx)(Pe,{children:a("Shard tables")}),O!==null&&(0,t.jsx)(ze,{className:"ms-auto tabular-nums",variant:"outline",children:i.length})]}),(0,t.jsx)(Ge,{children:Me.shard.hint})]}),(0,t.jsxs)(Le,{children:[b!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"sc-error",role:"alert",children:b}),O!==null&&O.length===0&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground","data-testid":"sc-empty",children:a("No tables in this shard.")}),O!==null&&O.length>0&&i.length===0&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground","data-testid":"sc-no-match",children:a("No tables match your filter.")}),i.length>0&&(0,t.jsx)("ul",{className:"-mx-3 overflow-hidden border-t border-border","data-testid":"sc-table-list",children:i.map(f=>{let re=`${C}:${f.name}`,Z=L[re]??[];return(0,t.jsxs)(et,{expanded:o===f.name,name:f.name,onToggle:r(()=>{ue(he(f.name))},"onToggle"),rowCount:f.rowCount,rowTestId:`sc-table-${f.name}`,toggleTestId:`sc-toggle-${f.name}`,children:[(0,t.jsx)(tt,{columns:c[re]??Ye,testId:`sc-columns-${f.name}`}),Z.length>0&&(0,t.jsx)(It,{heading:a("Indexes"),indexes:Z,testId:`sc-indexes-${f.name}`})]},f.name)})})]})]}),(0,t.jsxs)(qe,{"data-testid":"sc-global-section",size:"sm",children:[(0,t.jsxs)(Ke,{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Ve,{tier:"global"}),(0,t.jsx)(Pe,{children:a("Global tables (D1)")}),_!==null&&(0,t.jsx)(ze,{className:"ms-auto tabular-nums",variant:"outline",children:p.length})]}),(0,t.jsx)(Ge,{children:Me.global.hint})]}),(0,t.jsxs)(Le,{children:[g!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"sc-global-error",role:"alert",children:g}),_!==null&&_.length===0&&(0,t.jsx)(Je,{description:Me.global.hint,testId:"sc-global-empty",title:a("No global tables.")}),_!==null&&_.length>0&&p.length===0&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground","data-testid":"sc-global-no-match",children:a("No tables match your filter.")}),p.length>0&&(0,t.jsx)("ul",{className:"-mx-3 overflow-hidden border-t border-border","data-testid":"sc-global-table-list",children:p.map(f=>(0,t.jsx)(et,{expanded:K===f.name,name:f.name,onToggle:r(()=>{ue(H(f.name))},"onToggle"),rowCount:f.rowCount,rowTestId:`sc-global-table-${f.name}`,toggleTestId:`sc-global-toggle-${f.name}`,children:(0,t.jsx)(tt,{columns:v[f.name]??Ye,testId:`sc-global-columns-${f.name}`})},f.name))})]})]})]}),e[62]=c,e[63]=b,e[64]=o,e[65]=p,e[66]=i,e[67]=v,e[68]=g,e[69]=K,e[70]=_,e[71]=L,e[72]=C,e[73]=a,e[74]=O,e[75]=he,e[76]=H,e[77]=I,e[78]=ne):ne=e[78];let se;return e[79]!==le||e[80]!==U||e[81]!==ae||e[82]!==z||e[83]!==ne?(se=(0,t.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-schema",children:[le,U,ae,z,ne]}),e[79]=le,e[80]=U,e[81]=ae,e[82]=z,e[83]=ne,e[84]=se):se=e[84],se},"Zt");function At(s){return(0,t.jsx)("li",{className:"rounded bg-muted px-1.5 py-0.5 font-mono text-[11px] text-muted-foreground",children:s},s)}r(At,"kt");function Ft(s){return(0,t.jsxs)("li",{className:"flex flex-wrap items-center gap-1.5 text-xs",children:[(0,t.jsx)("span",{className:"font-mono",children:s.name}),(0,t.jsx)(ze,{variant:"outline",children:s.type}),s.unique===!0&&(0,t.jsx)(ze,{variant:"secondary",children:"unique"}),(0,t.jsx)("span",{className:"text-muted-foreground",children:s.fields.join(", ")})]},`${s.type}:${s.name}`)}r(Ft,"It");function zt(s){return s.name}r(zt,"At");export{Xt as SchemaViewer};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{c as l}from"./chunk-XNGYYOLS.js";import{a as o,e as P,f as $,g as dt,h as De}from"./chunk-3XIESWL4.js";var _=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 fr=class extends _{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"}},Y=new fr;var pr={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")},mr=class{static{o(this,"TimeoutManager")}#e=pr;#t=!1;setTimeoutProvider(t){this.#e=t}setTimeout(t,e){return this.#e.setTimeout(t,e)}clearTimeout(t){this.#e.clearTimeout(t)}setInterval(t,e){return this.#e.setInterval(t,e)}clearInterval(t){this.#e.clearInterval(t)}},N=new mr;function lt(t){setTimeout(t,0)}o(lt,"systemSetTimeoutZero");var qe=typeof window>"u"||"Deno"in globalThis;function g(){}o(g,"noop");function mt(t,e){return typeof t=="function"?t(e):t}o(mt,"functionalUpdate");function ne(t){return typeof t=="number"&&t>=0&&t!==1/0}o(ne,"isValidTimeout");function me(t,e){return Math.max(t+(e||0)-Date.now(),0)}o(me,"timeUntilStale");function M(t,e){return typeof t=="function"?t(e):t}o(M,"resolveStaleTime");function I(t,e){return typeof t=="function"?t(e):t}o(I,"resolveQueryBoolean");function ye(t,e){let{type:r="all",exact:s,fetchStatus:i,predicate:n,queryKey:a,stale:c}=t;if(a){if(s){if(e.queryHash!==oe(a,e.options))return!1}else if(!q(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(ye,"matchQuery");function be(t,e){let{exact:r,status:s,predicate:i,mutationKey:n}=t;if(n){if(!e.options.mutationKey)return!1;if(r){if(H(e.options.mutationKey)!==H(n))return!1}else if(!q(e.options.mutationKey,n))return!1}return!(s&&e.state.status!==s||i&&!i(e))}o(be,"matchMutation");function oe(t,e){return(e?.queryKeyHashFn||H)(t)}o(oe,"hashQueryKeyByOptions");function H(t){return JSON.stringify(t,(e,r)=>Ue(r)?Object.keys(r).sort().reduce((s,i)=>(s[i]=r[i],s),{}):r)}o(H,"hashKey");function q(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(!q(t[s],e[s]))return!1;return!0}let r=Object.keys(e);for(let s of r)if(!q(t[s],e[s]))return!1;return!0}return!1}o(q,"partialMatchKey");var yr=Object.prototype.hasOwnProperty;function Be(t,e,r=0){if(t===e)return t;if(r>500)return e;let s=ft(t)&&ft(e);if(!s&&!(Ue(t)&&Ue(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):{},d=0;for(let h=0;h<c;h++){let f=s?h:a[h],p=t[f],m=e[f];if(p===m){u[f]=p,(s?h<n:yr.call(t,f))&&d++;continue}if(p===null||m===null||typeof p!="object"||typeof m!="object"){u[f]=m;continue}let y=Be(p,m,r+1);u[f]=y,y===p&&d++}return n===c&&d===n?t:u}o(Be,"replaceEqualDeep");function ve(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(ve,"shallowEqualObjects");function ft(t){return Array.isArray(t)&&t.length===Object.keys(t).length}o(ft,"isPlainArray");function Ue(t){if(!pt(t))return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(!pt(r)||!r.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}o(Ue,"isPlainObject");function pt(t){return Object.prototype.toString.call(t)==="[object Object]"}o(pt,"hasObjectPrototype");function yt(t){return new Promise(e=>{N.setTimeout(e,t)})}o(yt,"sleep");function ae(t,e,r){return typeof r.structuralSharing=="function"?r.structuralSharing(t,e):r.structuralSharing!==!1?Be(t,e):e}o(ae,"replaceData");function br(t){return t}o(br,"keepPreviousData");function bt(t,e,r=0){let s=[...t,e];return r&&s.length>r?s.slice(1):s}o(bt,"addToEnd");function vt(t,e,r=0){let s=[e,...t];return r&&s.length>r?s.slice(0,-1):s}o(vt,"addToStart");var Z=Symbol();function ge(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===Z?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}o(ge,"ensureQueryFn");function we(t,e){return typeof t=="function"?t(...e):!!t}o(we,"shouldThrowError");function gt(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(gt,"addConsumeAwareSignal");var Q=(()=>{let t=o(()=>qe,"isServerFn");return{isServer(){return t()},setIsServer(e){t=e}}})();function ce(){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(ce,"pendingThenable");var wt=lt;function vr(){let t=[],e=0,r=o(c=>{c()},"notifyFn"),s=o(c=>{c()},"batchNotifyFn"),i=wt,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(vr,"createNotifyManager");var v=vr();var gr=class extends _{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}},ee=new gr;function wr(t){return Math.min(1e3*2**t,3e4)}o(wr,"defaultRetryDelay");function Ke(t){return(t??"online")==="online"?ee.isOnline():!0}o(Ke,"canFetch");var Se=class extends Error{static{o(this,"CancelledError")}constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function Ce(t){let e=!1,r=0,s,i=ce(),n=o(()=>i.status!=="pending","isResolved"),a=o(b=>{if(!n()){let S=new Se(b);p(S),t.onCancel?.(S)}},"cancel"),c=o(()=>{e=!0},"cancelRetry"),u=o(()=>{e=!1},"continueRetry"),d=o(()=>Y.isFocused()&&(t.networkMode==="always"||ee.isOnline())&&t.canRun(),"canContinue"),h=o(()=>Ke(t.networkMode)&&t.canRun(),"canStart"),f=o(b=>{n()||(s?.(),i.resolve(b))},"resolve"),p=o(b=>{n()||(s?.(),i.reject(b))},"reject"),m=o(()=>new Promise(b=>{s=o(S=>{(n()||d())&&b(S)},"continueFn"),t.onPause?.()}).then(()=>{s=void 0,n()||t.onContinue?.()}),"pause"),y=o(()=>{if(n())return;let b,S=r===0?t.initialPromise:void 0;try{b=S??t.fn()}catch(E){b=Promise.reject(E)}Promise.resolve(b).then(f).catch(E=>{if(n())return;let F=t.retry??(Q.isServer()?0:3),D=t.retryDelay??wr,K=typeof D=="function"?D(r,E):D,j=F===!0||typeof F=="number"&&r<F||typeof F=="function"&&F(r,E);if(e||!j){p(E);return}r++,t.onFail?.(r,E),yt(K).then(()=>d()?void 0:m()).then(()=>{e?p(E):y()})})},"run");return{promise:i,status:o(()=>i.status,"status"),cancel:a,continue:o(()=>(s?.(),i),"continue"),cancelRetry:c,continueRetry:u,canStart:h,start:o(()=>(h()?y():m().then(y),i),"start")}}o(Ce,"createRetryer");var ke=class{static{o(this,"Removable")}#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ne(this.gcTime)&&(this.#e=N.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(Q.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(N.clearTimeout(this.#e),this.#e=void 0)}};function Ct(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,d=o(async()=>{let h=!1,f=o(y=>{gt(y,()=>e.signal,()=>h=!0)},"addSignalProperty"),p=ge(e.options,e.fetchOptions),m=o(async(y,b,S)=>{if(h)return Promise.reject(e.signal.reason);if(b==null&&y.pages.length)return Promise.resolve(y);let F=o(()=>{let Qe={client:e.client,queryKey:e.queryKey,pageParam:b,direction:S?"backward":"forward",meta:e.options.meta};return f(Qe),Qe},"createQueryFnContext")(),D=await p(F),{maxPages:K}=e.options,j=S?vt:bt;return{pages:j(y.pages,D,K),pageParams:j(y.pageParams,b,K)}},"fetchPage");if(i&&n.length){let y=i==="backward",b=y?Sr:St,S={pages:n,pageParams:a},E=b(s,S);c=await m(S,E,y)}else{let y=t??n.length;do{let b=u===0?a[0]??s.initialPageParam:St(s,c);if(u>0&&b==null)break;c=await m(c,b),u++}while(u<y)}return c},"fetchFn");e.options.persister?e.fetchFn=()=>e.options.persister?.(d,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},r):e.fetchFn=d},"onFetch")}}o(Ct,"infiniteQueryBehavior");function St(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(St,"getNextPageParam");function Sr(t,{pages:e,pageParams:r}){return e.length>0?t.getPreviousPageParam?.(e[0],e,r[0],r):void 0}o(Sr,"getPreviousPageParam");var Et=class extends ke{static{o(this,"Query")}#e;#t;#r;#s;#n;#i;#a;#o;constructor(t){super(),this.#o=!1,this.#a=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=It(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.#a,...t},t?._type&&(this.#e=t._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=It(this.options);e.data!==void 0&&(this.setState(kt(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(t,e){let r=ae(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(g).catch(g):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===Z||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>M(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:!me(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.#o||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(d=>d.options.queryFn);u&&this.setOptions(u.options)}let r=new AbortController,s=o(u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:o(()=>(this.#o=!0,r.signal),"get")})},"addSignalProperty"),i=o(()=>{let u=ge(this.options,e),h=o(()=>{let f={client:this.#n,queryKey:this.queryKey,meta:this.meta};return s(f),f},"createQueryFnContext")();return this.#o=!1,this.options.persister?this.options.persister(u,h,this):u(h)},"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"?Ct(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=Ce({initialPromise:e?.initialPromise,fn:a.fetchFn,onCancel:o(u=>{u instanceof Se&&u.revert&&this.setState({...this.#r,fetchStatus:"idle"}),r.abort()},"onCancel"),onFail:o((u,d)=>{this.#c({type:"failed",failureCount:u,error:d})},"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 Se){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,...je(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...kt(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 je(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Ke(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}o(je,"fetchState");function kt(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}o(kt,"successState");function It(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(It,"getDefaultState");var He=class extends _{static{o(this,"QueryObserver")}constructor(t,e){super(),this.options=e,this.#e=t,this.#o=null,this.#a=ce(),this.bindMethods(),this.setOptions(e)}#e;#t=void 0;#r=void 0;#s=void 0;#n;#i;#a;#o;#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),Tt(this.#t,this.options)?this.#f():this.updateResult(),this.#g())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return $e(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return $e(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#w(),this.#S(),this.#t.removeObserver(this)}setOptions(t){let e=this.options,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&&!ve(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});let s=this.hasListeners();s&&Rt(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)||M(this.options.staleTime,this.#t)!==M(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.#v(i)}getOptimisticResult(t){let e=this.#e.getQueryCache().build(this.#e,t),r=this.createResult(e,t);return kr(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.#a.status==="pending"&&this.#a.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(g)),e}#y(){this.#w();let t=M(this.options.staleTime,this.#t);if(Q.isServer()||this.#s.isStale||!ne(t))return;let r=me(this.#s.dataUpdatedAt,t)+1;this.#d=N.setTimeout(()=>{this.#s.isStale||this.updateResult()},r)}#b(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(t){this.#S(),this.#u=t,!(Q.isServer()||I(this.options.enabled,this.#t)===!1||!ne(this.#u)||this.#u===0)&&(this.#l=N.setInterval(()=>{(this.options.refetchIntervalInBackground||Y.isFocused())&&this.#f()},this.#u))}#g(){this.#y(),this.#v(this.#b())}#w(){this.#d!==void 0&&(N.clearTimeout(this.#d),this.#d=void 0)}#S(){this.#l!==void 0&&(N.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:d}=t,h={...d},f=!1,p;if(e._optimisticResults){let O=this.hasListeners(),ie=!O&&Tt(t,e),le=O&&Rt(t,r,e,s);(ie||le)&&(h={...h,...je(d.data,t.options)}),e._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:m,errorUpdatedAt:y,status:b}=h;p=h.data;let S=!1;if(e.placeholderData!==void 0&&p===void 0&&b==="pending"){let O;i?.isPlaceholderData&&e.placeholderData===a?.placeholderData?(O=i.data,S=!0):O=typeof e.placeholderData=="function"?e.placeholderData(this.#p?.state.data,this.#p):e.placeholderData,O!==void 0&&(b="success",p=ae(i?.data,O,e),f=!0)}if(e.select&&p!==void 0&&!S)if(i&&p===n?.data&&e.select===this.#h)p=this.#c;else try{this.#h=e.select,p=e.select(p),p=ae(i?.data,p,e),this.#c=p,this.#o=null}catch(O){this.#o=O}this.#o&&(m=this.#o,p=this.#c,y=Date.now(),b="error");let E=h.fetchStatus==="fetching",F=b==="pending",D=b==="error",K=F&&E,j=p!==void 0,U={status:b,fetchStatus:h.fetchStatus,isPending:F,isSuccess:b==="success",isError:D,isInitialLoading:K,isLoading:K,data:p,dataUpdatedAt:h.dataUpdatedAt,error:m,errorUpdatedAt:y,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:h.dataUpdateCount>u.dataUpdateCount||h.errorUpdateCount>u.errorUpdateCount,isFetching:E,isRefetching:E&&!F,isLoadingError:D&&!j,isPaused:h.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:D&&j,isStale:ze(t,e),refetch:this.refetch,promise:this.#a,isEnabled:I(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let O=U.data!==void 0,ie=U.status==="error"&&!O,le=o(pe=>{ie?pe.reject(U.error):O&&pe.resolve(U.data)},"finalizeThenableIfPossible"),ht=o(()=>{let pe=this.#a=U.promise=ce();le(pe)},"recreateThenable"),fe=this.#a;switch(fe.status){case"pending":t.queryHash===r.queryHash&&le(fe);break;case"fulfilled":(ie||U.data!==fe.value)&&ht();break;case"rejected":(!ie||U.error!==fe.reason)&&ht();break}}return U}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),ve(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.#g()}#k(t){v.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#s)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function Cr(t,e){return I(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&I(e.retryOnMount,t)===!1)}o(Cr,"shouldLoadOnMount");function Tt(t,e){return Cr(t,e)||t.state.data!==void 0&&$e(t,e,e.refetchOnMount)}o(Tt,"shouldFetchOnMount");function $e(t,e,r){if(I(e.enabled,t)!==!1&&M(e.staleTime,t)!=="static"){let s=typeof r=="function"?r(t):r;return s==="always"||s!==!1&&ze(t,e)}return!1}o($e,"shouldFetchOn");function Rt(t,e,r,s){return(t!==e||I(s.enabled,t)===!1)&&(!r.suspense||t.state.status!=="error")&&ze(t,r)}o(Rt,"shouldFetchOptionally");function ze(t,e){return I(e.enabled,t)!==!1&&t.isStaleByTime(M(e.staleTime,t))}o(ze,"isStale");function kr(t,e){return!ve(t.getCurrentResult(),e)}o(kr,"shouldAssignObserverCurrentProperties");var Ot=class extends ke{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||Ir(),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=Ce({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 Ir(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}o(Ir,"getDefaultState");var Pt=class extends _{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 Ot({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=Ie(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=Ie(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=Ie(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=Ie(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=>be(e,r))}findAll(t={}){return this.getAll().filter(e=>be(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(g))))}};function Ie(t){return t.options.scope?.id}o(Ie,"scopeFor");var At=class extends _{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??oe(s,e),n=this.get(i);return n||(n=new Et({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=>ye(e,r))}findAll(t={}){let e=this.getAll();return Object.keys(t).length>0?e.filter(r=>ye(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 We=class{static{o(this,"QueryClient")}#e;#t;#r;#s;#n;#i;#a;#o;constructor(t={}){this.#e=t.queryCache||new At,this.#t=t.mutationCache||new Pt,this.#r=t.defaultOptions||{},this.#s=new Map,this.#n=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#a=Y.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#o=ee.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#i--,this.#i===0&&(this.#a?.(),this.#a=void 0,this.#o?.(),this.#o=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(M(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=mt(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(g).catch(g)}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(g)),i.state.fetchStatus==="paused"?Promise.resolve():n}));return Promise.all(s).then(g)}fetchQuery(t){let e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);let r=this.#e.build(this,e);return r.isStaleByTime(M(e.staleTime,r))?r.fetch(e):Promise.resolve(r.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(g).catch(g)}fetchInfiniteQuery(t){return t._type="infinite",this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(g).catch(g)}ensureInfiniteQueryData(t){return t._type="infinite",this.ensureQueryData(t)}resumePausedMutations(){return ee.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(H(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){let e=[...this.#s.values()],r={};return e.forEach(s=>{q(t,s.queryKey)&&Object.assign(r,s.defaultOptions)}),r}setMutationDefaults(t,e){this.#n.set(H(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){let e=[...this.#n.values()],r={};return e.forEach(s=>{q(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=oe(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===Z&&(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 B=P($(),1);var te=P($(),1),Lt=P(De(),1);var ue=te.createContext(void 0),Ve=o(t=>{let e=te.useContext(ue);if(t)return t;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},"useQueryClient"),Ge=o(({client:t,children:e})=>(te.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,Lt.jsx)(ue.Provider,{value:t,children:e})),"QueryClientProvider");var he=P($(),1),Er=P(De(),1);function Tr(){let t=!1;return{clearReset:o(()=>{t=!1},"clearReset"),reset:o(()=>{t=!0},"reset"),isReset:o(()=>t,"isReset")}}o(Tr,"createValue");var Rr=he.createContext(Tr()),Ft=o(()=>he.useContext(Rr),"useQueryErrorResetBoundary");var Mt=P($(),1);var xt=o((t,e,r)=>{let s=r?.state.error&&typeof t.throwOnError=="function"?we(t.throwOnError,[r.state.error,r]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||s)&&(e.isReset()||(t.retryOnMount=!1))},"ensurePreventErrorBoundaryRetry"),_t=o(t=>{Mt.useEffect(()=>{t.clearReset()},[t])},"useClearResetErrorBoundary"),Nt=o(({result:t,errorResetBoundary:e,throwOnError:r,query:s,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&s&&(i&&t.data===void 0||we(r,[t.error,s])),"getHasError");var Ee=P($(),1);var Qt=Ee.createContext(!1),Dt=o(()=>Ee.useContext(Qt),"useIsRestoring"),Oo=Qt.Provider;var Ut=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"),qt=o((t,e)=>t.isLoading&&t.isFetching&&!e,"willFetch"),Bt=o((t,e)=>t?.suspense&&e.isPending,"shouldSuspend"),Je=o((t,e,r)=>e.fetchOptimistic(t).catch(()=>{r.clearReset()}),"fetchOptimistic");function Kt(t,e,r){let s=Dt(),i=Ft(),n=Ve(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,Ut(a),xt(a,i,c),_t(i);let d=!n.getQueryCache().get(a.queryHash),[h]=B.useState(()=>new e(n,a)),f=h.getOptimisticResult(a),p=!s&&u;if(B.useSyncExternalStore(B.useCallback(m=>{let y=p?h.subscribe(v.batchCalls(m)):g;return h.updateResult(),y},[h,p]),()=>h.getCurrentResult(),()=>h.getCurrentResult()),B.useEffect(()=>{h.setOptions(a)},[a,h]),Bt(a,f))throw Je(a,h,i);if(Nt({result:f,errorResetBoundary:i,throwOnError:a.throwOnError,query:c,suspense:a.suspense}))throw f.error;return n.getDefaultOptions().queries?._experimental_afterQuery?.(a,f),a.experimental_prefetchInRender&&!Q.isServer()&&qt(f,s)&&(d?Je(a,h,i):c?.promise)?.catch(g).finally(()=>{h.updateResult()}),a.notifyOnChangeProps?f:h.trackResult(f)}o(Kt,"useBaseQuery");function Or(t,e){return Kt(t,He,e)}o(Or,"useQuery");var jt=P(dt(),1);var z=P($(),1),Xe=P(De(),1);var $t=(0,z.createContext)(null),Pr=o(()=>new We({defaultOptions:{mutations:{retry:0},queries:{gcTime:5*6e4,retry:0,staleTime:Number.POSITIVE_INFINITY}}}),"T"),Ar=o(t=>{let e=(0,jt.c)(9),{children:r,client:s,queryClient:i}=t,n=(0,z.use)(ue),a;e[0]!==n||e[1]!==i?(a=o(()=>i??n??Pr(),"i"),e[0]=n,e[1]=i,e[2]=a):a=e[2];let[c]=(0,z.useState)(a),u=i??n??c;if(!u)throw new l("INTERNAL","LunoraProvider: failed to resolve a QueryClient");let d;e[3]!==r||e[4]!==s?(d=(0,Xe.jsx)($t,{value:s,children:r}),e[3]=r,e[4]=s,e[5]=d):d=e[5];let h=d;if(n===u)return h;let f;return e[6]!==h||e[7]!==u?(f=(0,Xe.jsx)(Ge,{client:u,children:h}),e[6]=h,e[7]=u,e[8]=f):f=e[8],f},"b"),Ye=o(()=>{let t=(0,z.use)($t);if(!t)throw new l("INTERNAL","useLunora must be used inside <LunoraProvider />");return t},"q");var Ht=o(()=>{let t=null;return{get:o(()=>t,"get"),set:o(e=>{t=e},"set")}},"l");var Te=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)}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 zt=0,Lr="lunora-bridge",Fr=1e3,Mr=3e3,Re=class{static{o(this,"c")}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;onSubscriptionError;onSubscriptionSettled;constructor(e={}){if(zt+=1,this.tabId=`tab_${String(zt)}_${crypto.randomUUID()}`,this.heartbeatInterval=e.heartbeatInterval??Fr,this.leaderTimeout=e.leaderTimeout??Mr,this.onBecomeLeader=e.onBecomeLeader,this.onStopBeingLeader=e.onStopBeingLeader,this.onConnectionStatus=e.onConnectionStatus,this.onSubscriptionData=e.onSubscriptionData,this.onSubscriptionError=e.onSubscriptionError,this.onSubscriptionSettled=e.onSubscriptionSettled,typeof BroadcastChannel>"u"){this.bc=void 0;return}this.bc=new BroadcastChannel(e.channelName??Lr),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){this.leader&&this.broadcast({type:"subscription-error",tabId:this.tabId,key:e,error:r})}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);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()});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 Ze="_creationTime",xr=o(t=>{if(typeof t!="object"||t===null)return;let e=t._id;return typeof e=="string"?e:void 0},"p"),_r=o(t=>{let e;for(let r of t){let s=r[Ze];if(typeof s=="number"){if(e!==void 0){if(s<e)return!0;if(s>e)return!1}e=s}}return!1},"a"),Nr=o((t,e)=>{let r=e[Ze];if(typeof r!="number")return t.length;let s=_r(t);for(let[i,n]of t.entries()){let a=n[Ze];if(typeof a=="number"&&(s?a<r:a>r))return i}return t.length},"d"),Wt=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")},"y"),Vt=o((t,e)=>{if(!Array.isArray(t))return;let r=[];for(let u of t){if(xr(u)===void 0)return;r.push(u)}let{key:s,op:i,row:n}=e;if(i==="delete"){let u=r.filter(d=>d._id!==s);return u.length===r.length?[...r]:u}if(n===void 0)return;let a=r.findIndex(u=>u._id===s);if(a===-1){let u=[...r];return u.splice(Nr(r,n),0,n),u}let c=[...r];return c[a]=n,c},"g");var Qr=1024,Oe=o(t=>{let e=t.maxBuffer??Qr,r=[],s=[],i=!1,n,a=!1,c=o(()=>{let h=s.shift();if(!h)return!1;if(n)return h.reject(n),!0;if(r.length>0){let f=r.shift();return h.resolve({done:!1,value:f}),!0}return i?(h.resolve({done:!0,value:void 0}),!0):(s.unshift(h),!1)},"n"),u={complete(){if(!(i||n))for(i=!0;c(););},fail(h){if(!(i||n))for(n=h,r.length=0;c(););},push(h){if(!(i||n||a)){if(r.length>=e){u.fail(new l("STREAM_BACKPRESSURE",`stream buffer overflow (max=${e.toString()}); the consumer cannot keep up with the producer`));return}r.push(h),c()}}},d=o(()=>{if(!a){a=!0,i=!0,r.length=0;try{t.onCancel()}catch{}for(;c(););}},"c");return{handle:u,iterable:{cancel:d,[Symbol.asyncIterator](){return{next(){if(n)return Promise.reject(n);if(r.length>0){let h=r.shift();return Promise.resolve({done:!1,value:h})}return i?Promise.resolve({done:!0,value:void 0}):new Promise((h,f)=>{s.push({reject:f,resolve:h})})},return(){return d(),Promise.resolve({done:!0,value:void 0})}}}}}},"d");var Gt=/^ /u,Jt=o(t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),"u"),Dr=o(t=>{let e="",r=[];for(let s of t.split(`
|
|
2
|
+
`))s.startsWith("event:")?e=s.slice(6).replace(Gt,""):s.startsWith("data:")&&r.push(s.slice(5).replace(Gt,""));return{data:r.join(`
|
|
3
|
+
`),event:e}},"p"),Ur=o((t,e,r)=>{let s=e.params??{},i=t.path.split("/").map(c=>{if(!c.startsWith(":"))return c;let u=c.slice(1),d=s[u];if(d===void 0)throw new l("HTTP_STREAM_MISSING_PARAM",`httpStream: missing path param ":${u}" for route ${t.path}`);return encodeURIComponent(Jt(d))}).join("/"),n=new URLSearchParams;for(let[c,u]of Object.entries(e.searchParams??{}))u!==void 0&&n.set(c,Jt(u));let a=n.toString();return`${r.endsWith("/")?r.slice(0,-1):r}${i}${a===""?"":`?${a}`}`},"S"),qr=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 l(i,s)),!0}if((t.event===""||t.event==="message")&&t.data!=="")try{e.push(JSON.parse(t.data))}catch{return e.fail(new l("HTTP_STREAM_BAD_CHUNK","httpStream: malformed SSE chunk (invalid JSON)")),!0}return!1},"T"),Br=o(async(t,e)=>{let r=t.getReader(),s=new TextDecoder,i="",n=o(()=>{let a=i.indexOf(`
|
|
4
|
+
|
|
5
|
+
`);for(;a!==-1;){let c=Dr(i.slice(0,a));if(i=i.slice(a+2),qr(c,e))return!0;a=i.indexOf(`
|
|
6
|
+
|
|
7
|
+
`)}return!1},"c");for(;;){let{done:a,value:c}=await r.read();if(a)break;if(i+=s.decode(c,{stream:!0}).replaceAll(`\r
|
|
8
|
+
`,`
|
|
9
|
+
`),n()){await r.cancel().catch(()=>{});return}}i+=s.decode().replaceAll(`\r
|
|
10
|
+
`,`
|
|
11
|
+
`),n()||e.fail(new l("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"))},"g"),Xt=o((t,e,r={})=>{let s=r.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!s)throw new l("INTERNAL","httpStream: no `fetch` implementation available");let i=Ur(t,e??{},r.baseUrl??""),n=new AbortController,a;r.signal&&(r.signal.aborted?n.abort():(a=o(()=>{n.abort()},"n"),r.signal.addEventListener("abort",a,{once:!0})));let c=o(()=>{a&&r.signal?.removeEventListener("abort",a)},"l"),{handle:u,iterable:d}=Oe({maxBuffer:r.maxBuffer,onCancel:o(()=>{n.abort()},"onCancel")});return(async()=>{try{let h=await s(i,{headers:{accept:"text/event-stream",...r.headers},method:t.method,signal:n.signal});if(!h.ok){await h.body?.cancel().catch(()=>{}),u.fail(new l("HTTP_STREAM_STATUS",`httpStream: request failed (status ${h.status.toString()})`,{status:h.status}));return}if(!h.body){u.fail(new l("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}await Br(h.body,u)}finally{c()}})().catch(h=>{if(n.signal.aborted){u.complete();return}if(h instanceof Error&&"code"in h){u.fail(h);return}u.fail(new l("HTTP_STREAM_TRANSPORT",h instanceof Error?h.message:String(h),{cause:h}))}),d},"w");var et=o(t=>{let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e)},"b"),Kr=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},"w"),k="$lunora.wire$",Yt="__proto__",Zt={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},er={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},jr=o(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"A"),T=o((t,e=0)=>{if(e>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(t===void 0)return[k,"undefined"];if(t===null)return null;let r=typeof t;if(r==="bigint")return[k,"bigint",t.toString()];if(r==="number"){let n=t;return Number.isNaN(n)?[k,"nan"]:n===1/0?[k,"inf"]:n===-1/0?[k,"-inf"]:n}if(r!=="object")return t;if(t instanceof Date)return[k,"date",T(t.getTime(),e+1)];if(t instanceof Error){let n=t,a={};for(let u of Object.keys(n))n[u]!==void 0&&(a[u]=T(n[u],e+1));let c=[k,"error",n.name,n.message,a];return n.cause!==void 0&&c.push(T(n.cause,e+1)),c}if(t instanceof URL)return[k,"url",t.href];if(t instanceof Map)return[k,"map",[...t.entries()].map(([n,a])=>[T(n,e+1),T(a,e+1)])];if(t instanceof Set)return[k,"set",[...t].map(n=>T(n,e+1))];if(t instanceof ArrayBuffer)return[k,"bytes",et(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"?[k,"bytes",et(c)]:[k,"bytes",et(c),a]}if(Array.isArray(t)){let n=t.map(a=>T(a,e+1));return n.length>0&&n[0]===k?[k,"arr",n]:n}if(!jr(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];a!==void 0&&(i[n]=T(a,e+1))}return i},"s"),w=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]===k)switch(t[1]){case"-inf":return-1/0;case"arr":return t[2].map(i=>w(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":return new Date(w(t[2],e+1));case"map":return new Map(t[2].map(([i,n])=>[w(i,e+1),w(n,e+1)]));case"set":return new Set(t[2].map(i=>w(i,e+1)));case"url":return new URL(t[2]);case"error":{let i=t[2],n=t[3],a=(Object.hasOwn(er,i)?er[i]:void 0)??Error,c=new a(n);c.name!==i&&Object.defineProperty(c,"name",{configurable:!0,value:i,writable:!0});let u=w(t[4],e+1);for(let d of Object.keys(u))d===Yt?Object.defineProperty(c,d,{configurable:!0,enumerable:!0,value:u[d],writable:!0}):c[d]=u[d];return t.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:w(t[5],e+1),writable:!0}),c}case"bytes":{let i=Kr(t[2]),n=t[3]??"Uint8Array";if(n==="ArrayBuffer")return i.buffer.byteLength===i.byteLength?i.buffer:i.slice().buffer;let a=Object.hasOwn(Zt,n)?Zt[n]:void 0;return a?new a(i.slice().buffer):i}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return t.map(i=>w(i,e+1))}return t.map(i=>w(i,e+1))}let r=t,s={};for(let i of Object.keys(r)){let n=w(r[i],e+1);i===Yt?Object.defineProperty(s,i,{configurable:!0,enumerable:!0,value:n,writable:!0}):s[i]=n}return s},"f");var $r=o((t,e)=>t<e?-1:t>e?1:0,"y"),tt=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(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t))return`[${t.map(n=>tt(n)).join(",")}]`;let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype){let n=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${n} 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).toSorted($r),i=[];for(let n of s){let a=r[n];a!==void 0&&i.push(`${JSON.stringify(n)}:${tt(a)}`)}return`{${i.join(",")}}`},"n"),W=o(t=>tt(T(t)),"l");var x=class t{static{o(this,"y")}static key(e,r,s){return`${e}::${W(r)}::${s??""}`}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.key(e.fn.__lunoraRef,e.args,e.shardKey),e),this.byId.set(e.id,e)}remove(e){let r=t.key(e.fn.__lunoraRef,e.args,e.shardKey);this.byKey.get(r)===e&&this.byKey.delete(r),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}};var re=o((t,e)=>{let r=t;for(let s of e)try{r=s.transform(r)}catch{}return r},"m"),V=o((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let r of t.callbacks)try{r(e)}catch{}}},"u"),rt=o((t,e)=>{let r;try{r=e(t.lastValue)}catch{return}let s={id:Symbol("optimistic"),transform:e};t.optimisticLayers.push(s),V(t,r);let i=o(()=>{let a=t.optimisticLayers.findIndex(c=>c.id===s.id);return a===-1?!1:(t.optimisticLayers.splice(a,1),!0)},"i"),n=o(()=>{V(t,re(t.serverBase,t.optimisticLayers))},"a");return{confirm:o(a=>{if(a===void 0){i();return}s.commitCursor=a,t.serverCursor!==void 0&&t.serverCursor>=a&&i()&&n()},"confirm"),rollback:o(()=>{i()&&n()},"rollback")}},"p"),Pe=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},"d"),tr=o((t,e)=>{let r=[],s=[],i=o((n,a)=>t.get(x.key(n,a,e)),"i");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 d=rt(u,()=>c);d&&(r.push(d.confirm),s.push(d.rollback))},"setQuery")}}},"L");var rr=0,Hr=o(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();rr+=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)}_${rr.toString(36)}_${t}`},"a"),st=o((t,e)=>t!==void 0&&e!==t,"f"),Le=Hr,se=o((t,e,r,s)=>{if(t){t({error:r,mutationId:s,operation:e});return}console.warn(`[lunora] offline-queue persistence ${e} failed`,r)},"h"),Ae=class{static{o(this,"u")}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??=Le(),this.items.push(r),this.persistence?.append({args:r.args,functionPath:r.functionPath,id:r.id,identity:r.identity,shardKey:r.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(s=>{se(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(n){throw se(this.onPersistenceError,"load",n),n}let r=[];for(let n of e)if(!(this.items.some(a=>a.id===n.id)||r.some(a=>a.id===n.id))){if(st(this.version,n.version)){this.persistence.remove(n.id).catch(a=>{se(this.onPersistenceError,"remove",a,n.id)});continue}r.push({args:n.args,functionPath:n.functionPath,id:n.id,identity:n.identity,reject:o(()=>{},"reject"),resolve:o(()=>{},"resolve"),shardKey:n.shardKey})}this.items.unshift(...r),this.evictOverflow(),this.notifySize();let s=new Set(this.items),i=new Set;for(let n of r)s.has(n)&&i.add(n.shardKey);return[...i]}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()}evictOverflow(){for(;this.items.length>this.maxItems;){let e=this.items.shift();if(e){e.id&&this.persistence?.remove(e.id).catch(s=>{se(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 A=o(t=>new Promise((e,r)=>{t.addEventListener("success",()=>{e(t.result)}),t.addEventListener("error",()=>{r(t.error??new Error("IndexedDB request failed"))})}),"i"),Fe=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)},"c"),Me=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},"E");var zr="lunora-outbox",Wr="offline-mutations",sr="by_id",Vr=o((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new l("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let r=t.databaseName??zr,s=t.storeName??Wr,i=Fe(e,r,1,a=>{a.objectStoreNames.contains(s)||a.createObjectStore(s,{autoIncrement:!0}).createIndex(sr,"id",{unique:!0})}),n=Me(i,s);return{append:o(async a=>{await n("readwrite",c=>A(c.add(a)))},"append"),clear:o(async()=>{await n("readwrite",a=>A(a.clear()))},"clear"),load:o(async()=>n("readonly",a=>A(a.getAll())),"load"),remove:o(async a=>{await n("readwrite",async c=>{let u=await A(c.index(sr).getKey(a));u!==void 0&&await A(c.delete(u))})},"remove")}},"x"),ir=o((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return Vr()}},"P");var xe=o((t,e,r)=>`${t}::${e}::${r??""}`,"k"),Gr=500;var Jr="lunora-query-cache",Xr="query-cache",nr="by_ts",Yr=1,Zr=o((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new l("INTERNAL","createIndexedDbQueryCache: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryQueryCache()");let r=t.databaseName??Jr,s=t.storeName??Xr,i=t.maxEntries??Gr,n=Fe(e,r,Yr,u=>{u.objectStoreNames.contains(s)||u.createObjectStore(s,{keyPath:"key"}).createIndex(nr,"ts",{unique:!1})}),a=Me(n,s),c=o(async u=>{let d=await A(u.count())-i;d<=0||await new Promise((h,f)=>{let p=u.index(nr).openCursor();p.addEventListener("success",()=>{let m=p.result;if(!m||d<=0){h();return}m.delete(),d-=1,m.continue()}),p.addEventListener("error",()=>{f(p.error??new Error("IndexedDB eviction failed"))})})},"y");return{clear:o(async()=>{await a("readwrite",u=>A(u.clear()))},"clear"),load:o(async()=>a("readonly",u=>A(u.getAll())),"load"),put:o(async(u,d)=>{await a("readwrite",async h=>{await A(h.put({...d,key:u})),await c(h)})},"put"),remove:o(async u=>{await a("readwrite",d=>A(d.delete(u)))},"remove")}},"I"),or=o(t=>{if(t!==!1){if(t)return t;if(!(typeof indexedDB>"u"))return Zr()}},"N");var it=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 nt=500,es=o((t,e)=>{if(t.size<e)return;let r=t.keys().next().value;r!==void 0&&t.delete(r)},"ot"),X=class{static{o(this,"C")}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()}},ts="/_lunora/rpc",ar="/_lunora/rpc-batch",rs="/_lunora/ws",ot=o(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"P"),at=o(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"M"),ss=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)},"ht"),is="lunora-ping",ns=3e4,os=1e4,as=250,cs=64,us="/_lunora/admin/shard-traffic",hs="/_lunora/admin/scheduled",ds="/_lunora/admin/scheduled/status",ls="/_lunora/admin/scheduled/ws",fs="/_lunora/admin/scheduled/cancel",ps="/_lunora/admin/scheduled/dead",ms="/_lunora/admin/scheduled/dead/retry",ys="/_lunora/admin/scheduled/dead/cancel",bs="/_lunora/admin/workflows/instances",vs="/_lunora/admin/workflows/instance",gs="/_lunora/admin/workflows/status",_e="/_lunora/admin/storage",ws="/_lunora/admin/storage/url",Ss="/_lunora/admin/storage/buckets",Cs="/_lunora/admin/functions",ks="/_lunora/admin/cron-jobs",Is="/_lunora/admin/cron-jobs/run",Es="/_lunora/admin/openapi",Ts="/_lunora/admin/openrpc",Rs="/_lunora/admin/global/tables",Os="/_lunora/admin/global/table",Ps="/_lunora/admin/global/facet",As="/_lunora/admin/vector/indexes",Ls="/_lunora/admin/vector/query",Fs="/_lunora/admin/logs/archive",Ms="/_lunora/admin/kv/namespaces",xs="/_lunora/admin/kv/keys",ct="/_lunora/admin/kv/value",_s="/_lunora/admin/auth/users",cr="/_lunora/admin/auth/sessions",Ns="/_lunora/admin/auth/users/create",Qs="/_lunora/admin/auth/users/role",Ds="/_lunora/admin/auth/users/ban",Us="/_lunora/admin/auth/users/unban",qs="/_lunora/admin/auth/users/password",Bs="/_lunora/admin/auth/users/remove",Ks="/_lunora/admin/auth/users/impersonate",js="/_lunora/admin/auth/sessions/revoke",$s="/_lunora/admin/auth/sessions/revoke-all",Hs="/_lunora/admin/auth/capabilities",zs="/_lunora/admin/auth/users/update",Ws="/_lunora/admin/auth/accounts",Vs="/_lunora/admin/auth/accounts/unlink",Gs="/_lunora/admin/auth/passkeys",Js="/_lunora/admin/auth/passkeys/delete",Xs="/_lunora/admin/auth/two-factor/disable",Ys="/_lunora/admin/auth/organizations",Zs="/_lunora/admin/auth/organizations/members",ei="/_lunora/admin/auth/organizations/invitations",ti="/_lunora/admin/auth/organizations/members/remove",ri="/_lunora/admin/auth/organizations/invitations/cancel",si="/_lunora/admin/auth/config",ii="/_lunora/admin/auth/organizations/create",ni="/_lunora/admin/auth/organizations/update",oi="/_lunora/admin/auth/organizations/remove",ai="/_lunora/admin/auth/organizations/members/add",ci="/_lunora/admin/auth/organizations/members/invite",ui="/_lunora/admin/auth/organizations/members/role",hi="/_lunora/admin/auth/organizations/teams",di="/_lunora/admin/auth/organizations/teams/create",li="/_lunora/admin/auth/organizations/teams/update",fi="/_lunora/admin/auth/organizations/teams/remove",pi="/_lunora/admin/auth/organizations/teams/members",mi="/_lunora/admin/auth/organizations/teams/members/add",yi="/_lunora/admin/auth/organizations/teams/members/remove",bi="/_lunora/admin/auth/organizations/roles",vi="/_lunora/admin/auth/organizations/roles/create",gi="/_lunora/admin/auth/organizations/roles/update",wi="/_lunora/admin/auth/organizations/roles/remove",Si="/api/auth",Ci="/get-session",ur=o(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"Q"),G=o((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"v"),L=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}`},"g"),C=o(t=>t??"","p"),ki=o(t=>{let e=t.error,r=typeof e?.code=="string"?e.code:void 0,s=typeof e?.message=="string"?e.message:void 0,i=(typeof t.message=="string"?t.message:void 0)??s??"stream error";return r===void 0?new Error(i):new l(r,i)},"Re"),hr=o(t=>{let e=t.error,r=typeof e?.code=="string"?e.code:void 0,s=typeof e?.message=="string"?e.message:void 0;return{message:(typeof t.message=="string"?t.message:void 0)??s??"subscription error",...r===void 0?{}:{code:r}}},"B"),Ne=o((t,e)=>{for(let r of t)try{r(e)}catch{}},"R"),Ii=new TextDecoder,Ei=o(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return Ii.decode(t)},"Ne"),R=o((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"f"),de=o(t=>{let e=new Error(t.message??"request failed");return e.code=t.code,t.data!==void 0&&(e.data=w(t.data)),t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),e},"T"),J=o((t,e)=>{try{return T(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)}},"S"),Ti=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&&"error"in i&&i.error?{error:de(i.error),ok:!1}:{ok:!0,value:w(i?.result)}}return r.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},"_e"),Ri=new Set(["SHARD_ERROR","SHARD_UNAVAILABLE"]),Oi=Promise.resolve(),ut=class t{static{o(this,"z")}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;offlineQueue;outbox;clientId;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new x;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new X;statusListeners=new X;tokenExpiredListeners=new X;mutationSettledListeners=new X;pendingChangeListeners=new X;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??G(ur(e.url),rs),this.wsToken=e.wsToken;let r=e.authBasePath??Si;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??Ht(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??ns,this.connectTimeoutMs=e.connectTimeoutMs??os,this.defaultConnectionContext=e.connectionContext,this.persistence=ir(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=or(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new Te,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=Oi),this.offlineQueue=new Ae(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-${Le()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})})}setAuthToken(e,r){let s=this.authToken!==e,i=this.identityFingerprint();this.authToken=e,r!==void 0&&(this.authSubject=r);let n=this.identityFingerprint();if(n!==i&&(s?this.rejectQueuedForIdentityChange():this.restampQueuedIdentity(i,n),this.tabCoordinator)){let a=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),a&&this.tabCoordinator.promoteImmediately()}s&&this.authTokenListeners.emit(e)}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(e??"")??0}async callMutator(e,r,s){let i=s?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new l("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let n=s?.shardKey??"",a,c=await this.rpc(e,r,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:o(u=>{a=u},"onMutationAck")});return a!==void 0&&a>(this.clientWatermarks.get(n)??0)&&this.clientWatermarks.set(n,a),{applied:a===void 0||a===i,result:c}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}async getCurrentUser(){if(this.closed||!this.fetchImpl)return null;let e={};this.authToken&&(e.authorization=`Bearer ${this.authToken}`);try{let r=await this.fetchImpl(G(this.url,`${this.authBasePath}${Ci}`),{credentials:"include",headers:e,method:"GET"});return r.ok?(await r.json())?.user??null:null}catch{return null}}setWsToken(e){if(this.wsToken!==e){this.wsToken=e;for(let r of this.connections.values())if(r.socket)try{r.socket.close()}catch{}}}setConnectionContext(e,r={}){let s=C(r.shardKey);e===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,e),this.refreshConnectionContext(s)}acquireConnectionContext(e,r={}){let s=C(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={}){let i=C(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&&R(u,{topic:e,type:"whisper_subscribe"})}return()=>{let u=this.whisperHandlers.get(i),d=u?.get(e);if(!d?.delete(r)||d.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let h=this.getConnection(s.shardKey);h&&R(h,{topic:e,type:"whisper_unsubscribe"})}}whisper(e,r,s={}){this.ensureSocket(s.shardKey);let i=this.getConnection(s.shardKey);i&&R(i,{data:J(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=new Set([...this.connections.keys(),...this.clientWatermarks.keys()]);for(let i of r){let n=this.connections.get(i);e.push({confirmedMutationWatermark:this.clientWatermarks.get(i)??0,hasSocket:n?.socket!==void 0,shardKey:i===""?void 0:i,wasEverConnected:n?.wasEverConnected??!1,wsState:n?.wsState??"idle"})}let s=this.subscriptions.all().map(i=>({acked:i.acked,functionPath:i.fn.__lunoraRef,id:i.id,kind:"query",lastMutationId:i.lastMutationId,pendingOptimisticLayers:i.optimisticLayers.length,serverCursor:i.serverCursor,shardKey:i.shardKey,subscriberCount:i.callbacks.size}));for(let i of this.shapeSubscriptions.values())s.push({acked:i.serverCursor!==void 0,functionPath:`shape:${i.name}`,id:i.id,kind:"shape",lastMutationId:i.lastMutationId,pendingOptimisticLayers:0,rowCount:i.rows.size,serverCursor:i.serverCursor,shardKey:i.shardKey,subscriberCount:i.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((i,n)=>(i.shardKey??"").localeCompare(n.shardKey??"")),subscriptions:s.toSorted((i,n)=>i.functionPath.localeCompare(n.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){let i=this.peekActiveQueryValue(e.__lunoraRef,r,s),n=i===void 0?void 0:W(i);return()=>{let a=this.peekActiveQueryValue(e.__lunoraRef,r,s);return n===void 0&&a===void 0?!0:n===void 0||a===void 0?!1:W(a)===n}}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,r,s){if(!this.readyResolved)return;let i=W(r),n=xe(e,i,s),a=this.hydratedQueryCache.get(n);if(a!==void 0)return a.identity===this.identityFingerprint()?a.value:void 0}peekActiveQueryValue(e,r,s){let i=x.key(e,r,s);return this.subscriptions.get(i)?.lastValue}async query(e,r,s={}){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return await this.rpc(e.__lunoraRef,r,s.shardKey,{attachBookmark:!0})}async batch(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");if(!this.fetchImpl)throw new l("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(G(this.url,ar),{body:JSON.stringify({calls:e.map((n,a)=>({args:J(n.args??{},`args for batch call '${n.fn.__lunoraRef}'`),functionPath:n.fn.__lunoraRef,id:a,shardKey:n.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"}),s=r.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let i;try{i=await r.json()}catch{throw new l("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`)}if(!r.ok||i.error&&!i.results)throw i.error?de(i.error):new l("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`);return Ti(i.results??[],e.length)}async mutation(e,r,s={}){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let i=r,n=s.mutationId??Le(),{confirms:a,rollbacks:c}=this.applyOptimisticUpdates(e.__lunoraRef,i,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,r,s.shardKey,c,a);let{hasSocket:u,wasEverConnected:d,wsState:h}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:f}=this.offlineQueue,p=d||f,m=this.WebSocketImpl!==void 0&&p;if(h!=="open"&&!u&&m||h==="connecting"&&p)return this.enqueueOfflineMutation(e,i,s.shardKey,n,c,a,s.precondition);try{let y,b=await this.rpc(e.__lunoraRef,i,s.shardKey,{captureBookmark:!0,mutationId:n,onCommitCursor:o(S=>{y=S},"onCommitCursor")});for(let S of a)S(y);return b}catch(y){throw at(c),y}}async action(e,r,s={}){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return await this.rpc(e.__lunoraRef,r,s.shardKey)}async importRows(e,r,s={}){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let i=Math.max(1,Math.trunc(s.chunkSize??500)),n=s.toArgs??(d=>({rows:d})),a=r.length,c=0,u=0;for(let d=0;d<a;d+=i){let h=r.slice(d,d+i),f=u;await this.mutation(e,n(h),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(f)}`},shardKey:s.shardKey}),u+=1,c+=h.length,s.onProgress?.({done:c,total:a})}return{chunks:u,imported:c}}async shardTraffic(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let r=await this.adminFetch(us,"POST",{table:e});return{failed:r.failed??0,ok:r.ok??0,shards:r.shards??[]}}async listScheduledJobs(){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return(await this.adminFetch(hs,"GET")).records??[]}async schedulerStatus(){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let e=await this.adminFetch(ds,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}}async cancelScheduledJob(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return{cancelled:(await this.adminFetch(fs,"POST",{id:e})).cancelled===!0}}async listDeadJobs(){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return(await this.adminFetch(ps,"GET")).records??[]}async retryDeadJob(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return{retried:(await this.adminFetch(ms,"POST",{id:e})).retried===!0}}async removeDeadJob(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return{removed:(await this.adminFetch(ys,"POST",{id:e})).removed===!0}}async listWorkflowInstances(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");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(`${bs}?${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){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let r=new URLSearchParams({id:e.id,name:e.name}),s=await this.adminFetch(`${vs}?${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){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return{status:(await this.adminFetch(gs,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}}subscribeScheduledJobs(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");if(this.WebSocketImpl===void 0)return()=>{};let r=G(ur(this.url),ls),s=it(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},n,a=!1,c=o(()=>{a||(n=setTimeout(h,s.next()))},"o"),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=>{try{let y=JSON.parse(typeof m.data=="string"?m.data:"");y.type==="jobs"&&Array.isArray(y.records)&&e(y.records)}catch{}},"onMessage"),onOpen:o(()=>{s.reset()},"onOpen")})},"a"),d=o(async f=>{let p;try{p=await f()}catch{c();return}u(p)},"c"),h=o(()=>{if(a||this.WebSocketImpl===void 0)return;let{wsToken:f}=this;if(typeof f=="function"){d(f).catch(()=>{});return}u(f)},"u");return h(),()=>{a=!0,n!==void 0&&clearTimeout(n),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),this.stopHeartbeat(i),i.socket?.close()}}async listFunctions(){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return(await this.adminFetch(Cs,"GET")).functions??[]}async getCronJobs(){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return(await this.adminFetch(ks,"GET")).jobs??[]}async runCronJob(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let r=await this.adminFetch(Is,"POST",{name:e});return{name:r.name??e,ran:r.ran===!0}}async fetchOpenApi(){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return await this.adminFetch(Es,"GET")}async fetchOpenRpc(){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return await this.adminFetch(Ts,"GET")}async listStorageObjects(e={}){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let r=new URLSearchParams;e.prefix!==void 0&&e.prefix!==""&&r.set("prefix",e.prefix),e.cursor!==void 0&&e.cursor!==""&&r.set("cursor",e.cursor),e.limit!==void 0&&r.set("limit",String(e.limit)),e.bucket!==void 0&&e.bucket!==""&&r.set("bucket",e.bucket);let s=r.toString(),i=s===""?_e:`${_e}?${s}`,n=await this.adminFetch(i,"GET");return{cursor:n.cursor,objects:n.objects??[]}}async deleteStorageObject(e,r){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let s=`${_e}?key=${encodeURIComponent(e)}${ot(r?.bucket)}`,i=await this.adminFetch(s,"DELETE");return{deleted:i.deleted??!0,key:i.key??e}}async listStorageBuckets(){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return(await this.adminFetch(Ss,"GET")).buckets??[]}async uploadStorageObject(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let r=`${_e}?key=${encodeURIComponent(e.key)}${ot(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){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let s=r?.expiresInSeconds,i=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,n=`${ws}?key=${encodeURIComponent(e)}${i}${ot(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(){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return await this.adminFetch(Rs,"GET")}async readGlobalTablePage(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");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.filters)),await this.adminFetch(`${Os}?${r.toString()}`,"GET")}async facetGlobalColumn(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");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.filters)),await this.adminFetch(`${Ps}?${r.toString()}`,"GET")}async listVectorIndexes(){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return(await this.adminFetch(As,"GET")).indexes??[]}async queryVectorIndex(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return(await this.adminFetch(Ls,"POST",e)).matches??[]}async queryLogArchive(e={}){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let r=await this.adminFetch(Fs,"POST",e);return{nextCursor:r.nextCursor,rows:r.rows??[]}}async listKvNamespaces(){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return(await this.adminFetch(Ms,"GET")).namespaces??[]}async listKvKeys(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let r=L(xs,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await this.adminFetch(r,"GET")}async getKvValue(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let r=L(ct,{key:e.key,namespace:e.namespace});return await this.adminFetch(r,"GET")}async putKvValue(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");await this.adminFetch(ct,"PUT",e)}async deleteKvKey(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let r=L(ct,{key:e.key,namespace:e.namespace});await this.adminFetch(r,"DELETE")}async listAuthUsers(e={}){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let r=L(_s,{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(Ns,"POST",e)}async setAuthUserRole(e){return await this.adminFetch(Qs,"POST",e)}async banAuthUser(e){return await this.adminFetch(Ds,"POST",e)}async unbanAuthUser(e){return await this.adminFetch(Us,"POST",e)}async setAuthUserPassword(e){await this.adminFetch(qs,"POST",e)}async removeAuthUser(e){await this.adminFetch(Bs,"POST",e)}async impersonateAuthUser(e){return await this.adminFetch(Ks,"POST",e)}async revokeAuthSession(e){await this.adminFetch(js,"POST",e)}async revokeAuthUserSessions(e){await this.adminFetch($s,"POST",e)}async getAuthCapabilities(){return await this.adminFetch(Hs,"GET")}async updateAuthUser(e){return await this.adminFetch(zs,"POST",e)}async listAuthAccounts(e){return await this.adminFetch(L(Ws,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){await this.adminFetch(Vs,"POST",e)}async listAuthPasskeys(e){return await this.adminFetch(L(Gs,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){await this.adminFetch(Js,"POST",e)}async disableAuthTwoFactor(e){await this.adminFetch(Xs,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(L(Ys,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){let r=L(Zs,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async listAuthOrgInvitations(e){let r=L(ei,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async removeAuthOrgMember(e){await this.adminFetch(ti,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(ri,"POST",e)}async getAuthConfig(){return await this.adminFetch(si,"GET")}async createAuthOrganization(e){return await this.adminFetch(ii,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(ni,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(oi,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch(ai,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(ci,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch(ui,"POST",e)}async listAuthOrgTeams(e){let r=L(hi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(di,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch(li,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(fi,"POST",e)}async listAuthOrgTeamMembers(e){let r=L(pi,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(r,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(mi,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(yi,"POST",e)}async listAuthOrgRoles(e){let r=L(bi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async createAuthOrgRole(e){return await this.adminFetch(vi,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(gi,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(wi,"POST",e)}async listAuthSessions(e={}){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let r=new URLSearchParams;e.userId!==void 0&&e.userId!==""&&r.set("userId",e.userId),e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset));let s=r.toString();return await this.adminFetch(s===""?cr:`${cr}?${s}`,"GET")}subscribe(e,r,s,i={}){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let n=r??{},a=x.key(e.__lunoraRef,n,i.shardKey),c=this.subscriptions.get(a),u=s,d=i.onError;if(!c){this.nextSubId+=1;let f=`sub_${this.nextSubId.toString()}`,p=W(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,...m?.serverEpoch===void 0?{}:{serverEpoch:m.serverEpoch}},this.subscriptions.add(c)}if(c.callbacks.add(u),d&&c.errorCallbacks.add(d),i.onCheckpoint&&c.checkpointCallbacks.add(i.onCheckpoint),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let h=c;return()=>{if(h.callbacks.delete(u),d&&h.errorCallbacks.delete(d),i.onCheckpoint&&h.checkpointCallbacks.delete(i.onCheckpoint),h.callbacks.size===0){let f=this.getConnection(h.shardKey);!(f&&R(f,{id:h.id,type:"unsubscribe"}))&&f&&f.pendingUnsubscribes.push({id:h.id,type:"unsubscribe"}),this.subscriptions.remove(h)}}}subscribeShape(e,r,s={}){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");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:J(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,n),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i);let a=this.getConnection(n.shardKey);!(a&&R(a,{id:i,type:"shape_unsubscribe"}))&&a&&a.pendingUnsubscribes.push({id:i,type:"shape_unsubscribe"})}}stream(e,r,s={}){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");if(this.WebSocketImpl===void 0)throw new l("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}=Oe({maxBuffer:s.maxBuffer,onCancel:o(()=>{let f=this.getConnection(n);f&&R(f,{id:i,type:"unsubscribe"}),this.streams.delete(i)},"onCancel")});this.streams.set(i,{handle:c,shardKey:n}),this.ensureSocket(n);let d=this.getConnection(n),h={id:i,query:{args:J(a,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"};if(!(d?.wsState==="open"&&R(d,h))&&d){for(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=cs;){let f=d.pendingStreams.shift()?.id,p=f?this.streams.get(f):void 0;p&&(p.handle.fail(new l("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(f))}d.pendingStreams.push(h)}return u}httpStream(e,r,s={}){if(this.closed)throw new l("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new l("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return Xt(e,r,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(let e of this.streams.values())e.handle.fail(new l("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(let e of this.connections.values())this.teardownConnection(e);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.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}teardownConnection(e){if(e.reconnectTimer!==void 0&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),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 Re({channelName:e,onBecomeLeader:o(()=>{for(let r of this.subscriptions.all())this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(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";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);if(!c)return;if(c.serverBase=s,i!==void 0){c.serverCursor=i,n!==void 0&&(c.serverEpoch=n),Pe(c,i),V(c,c.optimisticLayers.length===0?s:re(s,c.optimisticLayers));return}let u=c.optimisticLayers.length===0?s:re(s,c.optimisticLayers);V(c,u)},"onSubscriptionData"),onSubscriptionError:o((r,s)=>{let i=this.subscriptions.get(r);i&&Ne(i.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 d of u.checkpointCallbacks)d({checkpoint:u.serverCursor,mutationId:u.lastMutationId})}},"onSubscriptionSettled")})}async enqueueOfflineMutation(e,r,s,i,n,a,c){let u=this.identityFingerprint();if(this.outbox){this.outboxMutationCounter+=1;let d=this.outboxMutationCounter;try{await this.outbox.enqueue({args:r,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:`${this.clientId}:${String(d)}`,identity:u,mutationId:d,shardKey:s})}catch(h){throw at(n),h instanceof Error?h:new Error(String(h))}for(let h of a)h(void 0);return}return new Promise((d,h)=>{let f={args:r,functionPath:e.__lunoraRef,liveAwaiter:!0,id:i,identity:u,precondition:c,onCommit:o(p=>{for(let m of a)m(p)},"onCommit"),reject:o(p=>{this.queuedIdentities.delete(i),at(n),h(p instanceof Error?p:new Error(String(p)))},"reject"),resolve:d,shardKey:s};this.offlineQueue.enqueue(f),this.queuedOfflineShardKeys.add(s),f.id!==void 0&&this.queuedIdentities.set(f.id,u)})}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(()=>{})},"t"),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();for(let{key:r,...s}of e){if(st(this.persistenceVersion,s.version)){this.queryCache.remove(r).catch(()=>{});continue}this.hydratedQueryCache.set(r,s)}}catch{}}takeHydratedCache(e,r,s){let i=xe(e,r,s),n=this.hydratedQueryCache.get(i);if(n!==void 0)return this.hydratedQueryCache.delete(i),n.identity===this.identityFingerprint()?n:void 0}persistQueryValue(e){let r=e.serverBase;if(!this.queryCache||r===void 0)return;let s=xe(e.fn.__lunoraRef,e.argsKey,e.shardKey);this.pendingCacheWrites.set(s,{identity:this.identityFingerprint(),serverCursor:e.serverCursor,ts:Date.now(),value:r,...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},as)}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(([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.wsState==="connecting")?"connecting":"offline"}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=x.key(e,r,s),u=this.subscriptions.get(c);if(u){let d=rt(u,i);d&&(n.push(d.confirm),a.push(d.rollback))}return{confirms:n,rollbacks:a}}applyOptimisticUpdate(e,r,s,i,n){let{confirms:a,rollbacks:c,store:u}=tr(this.subscriptions,s);try{e(u,r)}catch{for(let d=c.length-1;d>=0;d-=1)c[d]?.();return}i.push(...c),n.push(...a)}getConnection(e){return this.connections.get(C(e))}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let s="idle";return this.leaderStatus==="connected"?s="open":this.leaderStatus==="connecting"&&(s="connecting"),{hasSocket:!1,wasEverConnected:this.leaderWasEverConnected,wsState:s}}let r=this.getConnection(e);return{hasSocket:r?.socket!==void 0,wasEverConnected:r?.wasEverConnected??!1,wsState:r?.wsState??"idle"}}getOrCreateConnection(e){let r=C(e),s=this.connections.get(r);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],reconnect:it(this.reconnectOptions),reconnectTimer:void 0,shardKey:e,socket: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){let r={"content-type":"application/json"};if(this.authToken&&(r.authorization=`Bearer ${this.authToken}`),e.mutationId&&(r["x-lunora-mutation-id"]=e.mutationId),e.clientId!==void 0&&(r["x-lunora-client-id"]=e.clientId),e.clientSeq!==void 0&&(r["x-lunora-client-seq"]=e.clientSeq.toString()),e.attachBookmark){let s=this.bookmark.get();s&&(r["x-d1-bookmark"]=s)}return r}async rpc(e,r,s,i={}){if(!this.fetchImpl)throw new l("INTERNAL","LunoraClient: no `fetch` implementation available");let n=this.rpcRequestHeaders(i),a=await this.fetchImpl(G(this.url,ts),{body:JSON.stringify({args:J(r,`args for '${e}'`),functionPath:e,shardKey:s}),headers:n,method:"POST"});if(i.captureBookmark){let u=a.headers.get("x-d1-bookmark");u&&this.bookmark.set(u)}let c;try{c=await a.json()}catch{let u=a.statusText?` ${a.statusText}`:"";throw new l("INTERNAL",`LunoraClient: response was not JSON (status ${a.status.toString()}${u})`)}if("error"in c)throw de(c.error);if(!a.ok){let u=a.statusText?` ${a.statusText}`:"";throw new l("INTERNAL",`LunoraClient: request failed (status ${a.status.toString()}${u})`)}return i.onMutationAck?.(c.lastMutationId),i.onCommitCursor?.(c.commitCursor),w(c.result)}async adminFetch(e,r,s,i){if(!this.fetchImpl)throw new l("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(G(this.url,e),{body:c,headers:n,method:r}),d;try{d=await u.json()}catch{let h=u.statusText?` ${u.statusText}`:"";throw new l("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${h})`)}if(typeof d=="object"&&d!==null&&"error"in d){let h=d.error,f=new Error(h.message??"admin request failed");throw f.code=h.code,f}if(!u.ok){let h=u.statusText?` ${u.statusText}`:"";throw new l("INTERNAL",`LunoraClient: admin request failed (status ${u.status.toString()}${h})`)}return d}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(C(e.shardKey));R(e,{clientId:this.clientId,id:"connect",type:"connect",...r===void 0?{}:{context:r}})}resendShapeSubscriptions(e){for(let r of this.shapeSubscriptions.values())C(r.shardKey)===C(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 l("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)},"o"),u=o(d=>{c(),i.onClose(d)},"a");s>0&&(e.connectTimer=setTimeout(()=>{if(e.connectTimer=void 0,e.socket===a){try{a.close()}catch{}u()}},s)),a.addEventListener("open",()=>{e.socket===a&&(e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.lastFrameAt=Date.now(),i.onOpen(),this.startHeartbeat(e,u))}),a.addEventListener("message",d=>{e.socket===a&&(e.lastFrameAt=Date.now(),i.onMessage(d))}),a.addEventListener("close",d=>{e.socket===a&&u(d)}),a.addEventListener("error",()=>{e.socket===a&&u()})}openSocket(e,r,s){this.WebSocketImpl!==void 0&&this.openManagedSocket(e,this.wsUrlFor(r,s),this.connectTimeoutMs,{onClose:o(i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},"onClose"),onMessage:o(i=>{this.handleServerMessage(i.data,r)},"onMessage"),onOpen:o(()=>{e.wsState="open",e.wasEverConnected=!0,e.reconnect.reset(),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(r);for(let n of this.subscriptions.all())C(n.shardKey)===C(r)&&this.sendSubscribeIfOpen(n);if(this.resendShapeSubscriptions(r),e.pendingUnsubscribes.length>0){let n=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:a,type:c}of n)R(e,{id:a,type:c})}if(e.pendingStreams&&e.pendingStreams.length>0){let n=e.pendingStreams;e.pendingStreams=[];for(let a of n)R(e,a)}let i=this.whisperHandlers.get(C(r));if(i)for(let n of i.keys())R(e,{topic:n,type:"whisper_subscribe"});this.flushOfflineQueue(r).catch(()=>{})},"onOpen")})}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket=void 0,e.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey);let r=new Set((e.pendingStreams??[]).map(i=>i.id));for(let[i,n]of this.streams)C(n.shardKey)===C(e.shardKey)&&!r.has(i)&&(n.handle.fail(new l("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(is)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(e){e.heartbeatTimer!==void 0&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=void 0)}markShardPendingAck(e){let r=C(e);for(let s of this.subscriptions.all())C(s.shardKey)===r&&(s.acked=!1)}sendSubscribeIfOpen(e){let r=this.getConnection(e.shardKey);if(r?.wsState!=="open"||e.acked)return;let s=e.fn.__lunoraTable??e.fn.__lunoraRef;R(r,{id:e.id,query:{args:T(e.args),functionPath:e.fn.__lunoraRef,table:s,...e.serverCursor===void 0?{}:{sinceSeq:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){let r=this.getConnection(e.shardKey);r?.wsState==="open"&&R(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=Ei(e);if(s===void 0)return;let i;try{i=JSON.parse(s)}catch{return}switch(i.type){case"ack":{let n=this.subscriptions.getById(i.id);n&&(n.acked=!0);return}case"chunk":{let{data:n,id:a}=i;this.streams.get(a)?.handle.push(w(n));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"pokeEnd":{this.handlePokeEnd(i);break}case"pokePart":{this.handlePokePart(i);break}case"pokeStart":{this.handlePokeStart(i);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(ki(e)),this.streams.delete(r);return}let i=r===void 0?void 0:this.subscriptions.getById(r);if(i){Ne(i.errorCallbacks,hr(e));return}let n=r===void 0?void 0:this.shapeSubscriptions.get(r);n&&Ne(n.errorCallbacks,hr(e))}handlePokeStart(e){es(this.pokeBuffers,t.MAX_POKE_BUFFERS),this.pokeBuffers.set(e.pokeId,{baseCheckpoint:e.baseCheckpoint,epoch:e.epoch,lastMutationId:new Map,parts:new Map})}handlePokePart(e){let r=this.pokeBuffers.get(e.pokeId);if(!r)return;let s=r.parts.get(e.shapeId)??[];for(let i of e.rowsPatch)s.push(i.value===void 0?i:{...i,value:w(i.value)});r.parts.set(e.shapeId,s),e.lastMutationId!==void 0&&r.lastMutationId.set(e.shapeId,e.lastMutationId)}handlePokeEnd(e){let r=this.pokeBuffers.get(e.pokeId);if(r){this.pokeBuffers.delete(e.pokeId);for(let[s,i]of r.parts){let n=this.shapeSubscriptions.get(s);if(!n)continue;let a=r.epoch!==void 0&&n.serverEpoch!==void 0&&r.epoch!==n.serverEpoch,c=r.baseCheckpoint!==void 0&&n.serverCursor!==void 0&&n.serverCursor!==r.baseCheckpoint;if(a||c){n.rows.clear(),n.serverCursor=void 0,n.serverEpoch=void 0,this.emitShapeRows(n),this.sendShapeSubscribeIfOpen(n);continue}ss(n.rows,i),e.checkpoint!==void 0&&(n.serverCursor=e.checkpoint),e.epoch!==void 0&&(n.serverEpoch=e.epoch);let u=r.lastMutationId.get(s);u!==void 0&&(n.lastMutationId=u),this.emitShapeRows(n),n.onCheckpoint?.({checkpoint:n.serverCursor,mutationId:n.lastMutationId})}}}emitShapeRows(e){let r=[...e.rows.values()];for(let s of e.callbacks)try{s(r)}catch{}}handleDataMessage(e){let{id:r}=e,s=r?this.subscriptions.getById(r):void 0;if(!s)return;let i=this.resolveDataPayload(e,s);if(s.serverBase=i,e.cursor!==void 0&&(s.serverCursor=e.cursor),e.epoch!==void 0&&(s.serverEpoch=e.epoch),e.lastMutationId!==void 0){s.lastMutationId=Math.max(s.lastMutationId??0,e.lastMutationId);for(let n of s.checkpointCallbacks)n({checkpoint:s.serverCursor,mutationId:s.lastMutationId})}if(this.persistQueryValue(s),Pe(s,s.serverCursor),V(s,s.optimisticLayers.length===0?i:re(i,s.optimisticLayers)),this.tabCoordinator?.isLeader()){let n=x.key(s.fn.__lunoraRef,s.args,s.shardKey);this.tabCoordinator.broadcastSubscriptionData(n,i,s.serverCursor,s.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=e.lastMutationId);for(let s of r.checkpointCallbacks)s({checkpoint:r.serverCursor,mutationId:r.lastMutationId});if(this.tabCoordinator?.isLeader()){let s=x.key(r.fn.__lunoraRef,r.args,r.shardKey);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),Pe(e,e.serverCursor)&&V(e,re(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,r){if("data"in e&&e.data!==void 0)return w(e.data);let s=w(e.delta);if(Wt(s)&&r.serverBase!==void 0){let i=Vt(r.serverBase,s);if(i!==void 0)return i}return s}dispatchWhisper(e,r){let s=this.whisperHandlers.get(C(r))?.get(e.topic);if(!s)return;let i=w(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=>{se(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)}`}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;let r=this.authToken;return r===null?!1:this.hashToken(r)===e}rejectQueuedForIdentityChange(){let e=this.offlineQueue.drain();for(let r of e){this.queuedIdentities.delete(r.id??""),this.unpersist(r.id);let s=new Error("offline mutation discarded: auth identity changed before replay");s.code="OFFLINE_IDENTITY_CHANGED",r.reject(s),this.emitItemSettled(r,"rejected",s)}this.clearQueryCacheForIdentityChange()}restampQueuedIdentity(e,r){for(let[s,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(s,r)}clearQueryCacheForIdentityChange(){this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}flushAllOfflineQueues(){for(let e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){let r=this.offlineQueue.drainConflict();for(let d of r){this.unpersist(d.id),this.queuedIdentities.delete(d.id??"");let h=new Error("offline mutation skipped: precondition failed before replay");h.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(d,"rejected",h)}let s=C(e),i=this.offlineQueue.drain(d=>C(d.shardKey)===s);if(i.length===0)return;let n=this.identityFingerprint(),a=[];for(let d of i)this.passesReplayIdentityGate(d,n)&&a.push(d);if(a.length===0)return;let c=this.encodableOrSettleTerminal(a);if(c.length===0)return;if(c.length===1){await this.replaySequential(c);return}let u=[];for(let d=0;d<c.length;d+=nt){let h=c.slice(d,d+nt),f=await this.replayBatched(h);if(u.push(...f.requeue),f.stop){u.push(...c.slice(d+nt));break}}u.length>0&&this.offlineQueue.requeue(u)}encodableOrSettleTerminal(e){let r=[];for(let s of e)try{J(s.args,`args for '${s.functionPath}'`),r.push(s)}catch(i){this.settleReplayTerminal(s,i instanceof Error?i:new Error(String(i)))}return r}passesReplayIdentityGate(e,r){let s=e.id===void 0?void 0:this.queuedIdentities.get(e.id),i=s===void 0?e.identity:s;if(i!==void 0&&i!==r&&!this.isSameCredentialUnderTokenHash(i)){this.queuedIdentities.delete(e.id??""),this.unpersist(e.id);let n=new Error("offline mutation skipped: auth identity changed before replay");return n.code="OFFLINE_IDENTITY_CHANGED",e.reject(n),this.emitItemSettled(e,"rejected",n),!1}return this.queuedIdentities.delete(e.id??""),!0}settleReplaySuccess(e,r,s){this.unpersist(e.id),e.onCommit?.(s),e.resolve(r),this.emitItemSettled(e,"committed")}settleReplayTerminal(e,r){this.unpersist(e.id),e.reject(r),this.emitItemSettled(e,"rejected",r)}async replaySequential(e){for(let r=0;r<e.length;r+=1){let s=e[r];if(s)try{let i,n=await this.rpc(s.functionPath,s.args,s.shardKey,{captureBookmark:!0,mutationId:s.id,onCommitCursor:o(a=>{i=a},"onCommitCursor")});this.settleReplaySuccess(s,n,i)}catch(i){if(i.code!==void 0){this.settleReplayTerminal(s,i);continue}this.offlineQueue.requeue(e.slice(r));return}}}async replayBatched(e){if(!this.fetchImpl)return{requeue:e,stop:!0};let r;try{r=await this.fetchImpl(G(this.url,ar),{body:JSON.stringify({calls:e.map((n,a)=>({args:J(n.args,`args for '${n.functionPath}'`),functionPath:n.functionPath,id:a,mutationId:n.id,shardKey:n.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"})}catch{return{requeue:e,stop:!0}}let s=r.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let i;try{i=await r.json()}catch{return{requeue:e,stop:!0}}if(!i.results){if(i.error){let n=de(i.error);for(let a of e)this.settleReplayTerminal(a,n);return{requeue:[],stop:!1}}return{requeue:e,stop:!0}}return{requeue:this.settleReplayBatchSlots(e,i.results),stop:!1}}settleReplayBatchSlots(e,r){let s=new Map;for(let n of r)typeof n.id=="number"&&n.body!==void 0&&s.set(n.id,n.body);let i=[];for(let[n,a]of e.entries()){let c=s.get(n);c===void 0?i.push(a):"error"in c?Ri.has(c.error.code)?i.push(a):this.settleReplayTerminal(a,de(c.error)):this.settleReplaySuccess(a,w(c.result),c.commitCursor)}return i}};var dr=P(dt(),1),lr=P($(),1);var Pi=o(()=>{let t=(0,dr.c)(4),e=Ye(),r,s,i;return t[0]!==e?(r=o(n=>e.onConnectionStatus(()=>{n()}),"n"),s=o(()=>e.connectionStatus(),"e"),i=o(()=>e.connectionStatus(),"r"),t[0]=e,t[1]=r,t[2]=s,t[3]=i):(r=t[1],s=t[2],i=t[3]),(0,lr.useSyncExternalStore)(r,s,i)},"f");export{ut as a,br as b,Ve as c,Or as d,Ar as e,Ye as f,Pi as g};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{R as Q}from"./chunk-CFPZYHPY.js";import"./chunk-7QIFDWQV.js";import{c as W}from"./chunk-FXCBF4XT.js";import"./chunk-2OUPA2WJ.js";import"./chunk-6ST5ECQA.js";import{f as F}from"./chunk-
|
|
1
|
+
import{R as Q}from"./chunk-CFPZYHPY.js";import"./chunk-7QIFDWQV.js";import{c as W}from"./chunk-FXCBF4XT.js";import"./chunk-2OUPA2WJ.js";import"./chunk-6ST5ECQA.js";import{f as F}from"./chunk-DBWOWJYT.js";import"./chunk-XBDKZZ67.js";import{a as Z}from"./chunk-XQCVZAGU.js";import{a as q,b as L,c as B,d as f,e as c,f as d}from"./chunk-MIQTKZAR.js";import{a as I,e as j}from"./chunk-UZERI5YC.js";import{d as K,h as S,m as $,o as V}from"./chunk-IUYFXK4X.js";import"./chunk-XNGYYOLS.js";import{a as h,e as C,f as R,g as P,h as U}from"./chunk-3XIESWL4.js";var A=C(P(),1);var n=C(R(),1);var e=C(U(),1);var X=10,g=h(v=>{let l=(0,A.c)(7),{label:m,value:a}=v,r;l[0]!==m?(r=(0,e.jsx)("span",{className:"font-mono text-[11px] uppercase tracking-wide text-muted-foreground",children:m}),l[0]=m,l[1]=r):r=l[1];let p=a??"\u2014",s;l[2]!==p?(s=(0,e.jsx)("span",{className:"font-mono text-sm",children:p}),l[2]=p,l[3]=s):s=l[3];let u;return l[4]!==r||l[5]!==s?(u=(0,e.jsxs)("div",{className:"flex flex-col gap-0.5",children:[r,s]}),l[4]=r,l[5]=s,l[6]=u):u=l[6],u},"g"),se=h(({loadIndexes:v,runQuery:l}={})=>{let m=F(),a=K(),[r,p]=(0,n.useState)(null),[s,u]=(0,n.useState)(null),[N,E]=(0,n.useState)(null),[b,D]=(0,n.useState)(""),[x,y]=(0,n.useState)(null),[M,w]=(0,n.useState)(null),[T,z]=(0,n.useState)(!1);(0,n.useEffect)(()=>{let t={cancelled:!1};return V((async()=>{try{let i=await(v??(()=>m.listVectorIndexes()))();t.cancelled||(p(i),u(null),E(k=>k??i[0]?.name??null))}catch(i){t.cancelled||(p(null),u(S(i)))}})()),()=>{t.cancelled=!0}},[m,v]);let o=r?.find(t=>t.name===N)??null,G=h(t=>{E(t.currentTarget.dataset.index??null),y(null),w(null)},"K"),H=h(t=>{D(t.target.value)},"T"),J=h(async()=>{let t=b.trim();if(!(N===null||t==="")){z(!0),w(null);try{let i=await(l??(k=>m.queryVectorIndex(k)))({name:N,text:t,topK:X});y(i)}catch(i){y(null),w(S(i))}z(!1)}},"Z"),O=h(()=>{V(J())},"z");return(0,e.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-vector-browser",children:[s!==null&&(0,e.jsx)("p",{className:"text-sm text-destructive","data-testid":"vector-error",role:"alert",children:s}),r!==null&&r.length===0&&(0,e.jsx)(Z,{description:a("Indexes declared with .vectorize() or defineVectorIndex() appear here."),icon:(0,e.jsx)("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.6,viewBox:"0 0 24 24",children:(0,e.jsx)("path",{d:"M4 7l8-4 8 4-8 4-8-4Zm0 5 8 4 8-4M4 17l8 4 8-4"})}),testId:"vector-empty",title:a("No vector indexes.")}),r!==null&&r.length>0&&(0,e.jsx)(I,{className:"overflow-hidden py-0",children:(0,e.jsx)(j,{className:"px-0",children:(0,e.jsxs)(q,{"data-testid":"vector-table",children:[(0,e.jsx)(L,{children:(0,e.jsxs)(f,{children:[(0,e.jsx)(c,{children:a("name")}),(0,e.jsx)(c,{children:a("table")}),(0,e.jsx)(c,{children:a("dimensions")}),(0,e.jsx)(c,{children:a("metric")}),(0,e.jsx)(c,{children:a("vectors")})]})}),(0,e.jsx)(B,{children:r.map(t=>(0,e.jsxs)(f,{className:t.name===N?"border-l-2 border-l-royal-amethyst bg-muted/50":"cursor-pointer","data-index":t.name,"data-testid":`vector-row-${t.name}`,onClick:G,children:[(0,e.jsx)(d,{className:"font-mono text-xs",children:t.name}),(0,e.jsx)(d,{className:"font-mono text-xs",children:t.table}),(0,e.jsx)(d,{className:"tabular-nums",children:t.dimensions??"\u2014"}),(0,e.jsx)(d,{children:t.metric??"\u2014"}),(0,e.jsx)(d,{className:"tabular-nums",children:t.vectorsCount??"\u2014"})]},t.name))})]})})}),o!==null&&(0,e.jsxs)("section",{className:"border border-border bg-card p-3","data-testid":"vector-detail",children:[(0,e.jsxs)("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4",children:[(0,e.jsx)(g,{label:a("field"),value:o.field}),(0,e.jsx)(g,{label:a("dimensions"),value:o.dimensions}),(0,e.jsx)(g,{label:a("metric"),value:o.metric}),(0,e.jsx)(g,{label:a("vectors"),value:o.vectorsCount})]}),o.metadata!==void 0&&o.metadata.length>0&&(0,e.jsxs)("p",{className:"mt-3 text-xs text-muted-foreground","data-testid":"vector-metadata",children:[a("metadata"),": ",(0,e.jsx)("span",{className:"font-mono",children:o.metadata.join(", ")})]}),(0,e.jsxs)("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[(0,e.jsx)(Q,{className:"min-w-[18rem] flex-1","data-testid":"vector-query-input",onChange:H,placeholder:a("Search by similarity\u2026"),value:b}),(0,e.jsx)(W,{"data-testid":"vector-search",disabled:T||b.trim()==="",onClick:O,children:a(T?"Searching\u2026":"Search")})]}),M!==null&&(0,e.jsx)("p",{className:"mt-2 text-sm text-destructive","data-testid":"vector-query-error",role:"alert",children:M}),x!==null&&x.length===0&&(0,e.jsx)("p",{className:"mt-2 text-sm text-muted-foreground","data-testid":"vector-no-matches",children:a("No matches.")}),x!==null&&x.length>0&&(0,e.jsx)(I,{className:"mt-3 overflow-hidden py-0",children:(0,e.jsx)(j,{className:"px-0",children:(0,e.jsxs)(q,{"data-testid":"vector-matches",children:[(0,e.jsx)(L,{children:(0,e.jsxs)(f,{children:[(0,e.jsx)(c,{children:a("id")}),(0,e.jsx)(c,{children:a("score")}),(0,e.jsx)(c,{children:a("metadata")})]})}),(0,e.jsx)(B,{children:x.map(t=>(0,e.jsxs)(f,{"data-testid":`vector-match-${t.id}`,children:[(0,e.jsx)(d,{className:"font-mono text-xs",children:t.id}),(0,e.jsx)(d,{className:"tabular-nums",children:t.score.toFixed(4)}),(0,e.jsx)(d,{className:"max-w-md truncate font-mono text-xs",children:t.metadata===void 0?"\u2014":$(t.metadata)})]},t.id))})]})})})]})]})},"ce");export{se as VectorBrowser};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as k}from"./chunk-BENJFRZL.js";import{a as j}from"./chunk-54MMVNPT.js";import{a as E}from"./chunk-XTEWLG3J.js";import"./chunk-SFDOII3B.js";import"./chunk-SMIESS7P.js";import"./chunk-T6VMSOBB.js";import"./chunk-7QIFDWQV.js";import"./chunk-FXCBF4XT.js";import"./chunk-2OUPA2WJ.js";import{b as x}from"./chunk-THIXMMZD.js";import"./chunk-6ST5ECQA.js";import{a as T}from"./chunk-ZKTWHB7Q.js";import"./chunk-XXQUMVWH.js";import"./chunk-NH3VWHCL.js";import"./chunk-QLQADHFE.js";import{a as y}from"./chunk-VDW32UET.js";import{c as b}from"./chunk-4D7XIQ5Q.js";import"./chunk-DBWOWJYT.js";import"./chunk-XBDKZZ67.js";import{a as w}from"./chunk-XQCVZAGU.js";import{a as I,b as R,c as A,d as v,e as l,f as n}from"./chunk-MIQTKZAR.js";import{a as u,e as N}from"./chunk-UZERI5YC.js";import{d as _,r as S}from"./chunk-IUYFXK4X.js";import"./chunk-XNGYYOLS.js";import{a as c,e as U,h as G}from"./chunk-3XIESWL4.js";var e=U(G(),1);var H=["subscriptions","events"],$={},D=new Set(["active","trialing"]),q=new Set(["past_due","unpaid"]),a=c((s,t)=>{if(s[t]!==void 0)return s[t];let m=s.__doc__;return typeof m=="string"?k(m)?.[t]:void 0},"i"),i=c(s=>typeof s=="string"?s:typeof s=="number"||typeof s=="bigint"||typeof s=="boolean"?String(s):"","s"),z=c(s=>D.has(s)?"default":q.has(s)?"destructive":"outline","L"),ae=c(({limit:s=100})=>{let t=_(),m=E(),{data:g}=b(y.listTables,$,{live:!0}),O=g!==void 0,B=Array.isArray(g)&&H.every(r=>g.some(d=>d.name===r)),p=m.payments&&B,o=b(y.readTablePage,{filters:[],limit:s,offset:0,orderBy:[],search:"",table:"subscriptions"},{enabled:p}),h=b(y.readTablePage,{filters:[],limit:25,offset:0,orderBy:[],search:"",table:"events"},{enabled:p});j(()=>{p&&(o.refetch(),h.refetch())},!0);let f=o.data?.rows??[],C=h.data?.rows??[],F=o.error??h.error,L=o.error===null?h.errorSource:o.errorSource,P=f.filter(r=>D.has(i(a(r,"state")))).length,M=C.toSorted((r,d)=>Number(a(d,"processedAt")??0)-Number(a(r,"processedAt")??0));return O&&!p?(0,e.jsx)("div",{className:"flex flex-col gap-4","data-testid":"payments-panel",children:(0,e.jsx)(w,{description:t("No @lunora/payment tables found in this deployment. Declare the store tables (subscriptions, events, \u2026) in lunora/schema.ts and wire `payment` on createShardDO() to sync customers and subscriptions."),testId:"payments-unconfigured",title:t("No payments configured")})}):(0,e.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"payments-panel",children:[(0,e.jsx)("div",{className:"flex items-center gap-2","data-testid":"payments-summary",children:(0,e.jsxs)(u,{className:"justify-between gap-0 py-0",children:[(0,e.jsxs)("div",{className:"flex flex-col gap-2.5 p-4",children:[(0,e.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:t("Subscriptions")}),(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)("span",{className:"text-2xl font-semibold tabular-nums text-foreground",children:P}),(0,e.jsx)(x,{variant:"default",children:t("{count} active",{count:P})})]})]}),(0,e.jsx)("div",{className:"border-t border-border bg-muted/50 px-4 py-2.5 text-[11px] text-muted-foreground",children:t("{total} total",{total:f.length})})]})}),F===null?void 0:(0,e.jsx)(T,{error:L}),f.length===0&&!o.isLoading?(0,e.jsx)(w,{testId:"payments-empty",title:t("No subscriptions yet")}):(0,e.jsx)(u,{className:"overflow-hidden py-0",children:(0,e.jsx)(N,{className:"px-0",children:(0,e.jsxs)(I,{children:[(0,e.jsx)(R,{children:(0,e.jsxs)(v,{children:[(0,e.jsx)(l,{children:t("Provider")}),(0,e.jsx)(l,{children:t("Reference")}),(0,e.jsx)(l,{children:t("Plan")}),(0,e.jsx)(l,{children:t("State")}),(0,e.jsx)(l,{children:t("Renews")})]})}),(0,e.jsx)(A,{children:f.map(r=>{let d=i(a(r,"state"));return(0,e.jsxs)(v,{"data-testid":"payment-subscription-row",children:[(0,e.jsx)(n,{children:i(a(r,"provider"))}),(0,e.jsx)(n,{children:i(a(r,"referenceId"))}),(0,e.jsx)(n,{children:i(a(r,"priceId"))}),(0,e.jsx)(n,{children:(0,e.jsx)(x,{variant:z(d),children:d})}),(0,e.jsx)(n,{children:S(a(r,"currentPeriodEnd"))})]},i(a(r,"providerSubscriptionId")))})})]})})}),(0,e.jsxs)(u,{className:"overflow-hidden py-0",children:[(0,e.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,e.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:t("Recent webhook events")})}),(0,e.jsx)(N,{className:"px-0",children:(0,e.jsx)(I,{children:(0,e.jsx)(A,{children:M.map(r=>(0,e.jsxs)(v,{"data-testid":"payment-event-row",children:[(0,e.jsx)(n,{children:i(a(r,"provider"))}),(0,e.jsx)(n,{className:"font-medium",children:i(a(r,"type"))}),(0,e.jsx)(n,{className:"text-muted-foreground",children:i(a(r,"providerEventId"))}),(0,e.jsx)(n,{children:S(a(r,"processedAt"))})]},i(a(r,"providerEventId"))))})})})]})]})},"ae");export{ae as PaymentsPanel};
|