@lunora/studio 1.0.0-alpha.120 → 1.0.0-alpha.121
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/packem_chunks/ApiTab.js +1 -1
- package/dist/packem_shared/{ApiReferencePanel-DXrGI45U.js → ApiReferencePanel-CZDVN7zg.js} +1 -1
- package/dist/packem_shared/{OpenRpcReferencePanel-DkYBLJGb.js → OpenRpcReferencePanel-XoYdKuMg.js} +1 -1
- package/dist/packem_shared/reference-view-DY3CaRxH.js +13 -0
- package/dist/standalone/{chunk-QXLU6YPU.js → chunk-2AJMY73I.js} +1 -1
- package/dist/standalone/{chunk-D3ZLKFO4.js → chunk-2EWSVBWG.js} +1 -1
- package/dist/standalone/{chunk-2VLBFSIX.js → chunk-2FFV3NB7.js} +1 -1
- package/dist/standalone/{chunk-BKW7FMAU.js → chunk-2HW5M4MK.js} +1 -1
- package/dist/standalone/{chunk-6KJLNWPJ.js → chunk-33TNFS73.js} +1 -1
- package/dist/standalone/{chunk-WFABZPAK.js → chunk-3K4F3B56.js} +1 -1
- package/dist/standalone/{chunk-4DJQV5UA.js → chunk-3WFIPW6W.js} +1 -1
- package/dist/standalone/{chunk-2RASQG3R.js → chunk-4HWTEDVV.js} +1 -1
- package/dist/standalone/{chunk-T5SC5RAD.js → chunk-4O7MEQMU.js} +1 -1
- package/dist/standalone/{chunk-L6ATKZKO.js → chunk-5DEXJ766.js} +1 -1
- package/dist/standalone/{chunk-TCKQ4E5Y.js → chunk-5VKIJNHE.js} +1 -1
- package/dist/standalone/{chunk-XUX7B54Z.js → chunk-7EOXUWAI.js} +1 -1
- package/dist/standalone/{chunk-5COHJLQF.js → chunk-7MO56FXL.js} +1 -1
- package/dist/standalone/{chunk-PRWFHSHC.js → chunk-AVBUV42G.js} +1 -1
- package/dist/standalone/{chunk-6QKKYBML.js → chunk-B6YM5NAF.js} +1 -1
- package/dist/standalone/{chunk-W3PCX3TU.js → chunk-DXXXNZ3P.js} +1 -1
- package/dist/standalone/{chunk-DYKGLIBC.js → chunk-E4RVRJHD.js} +1 -1
- package/dist/standalone/{chunk-ATGYWQUI.js → chunk-EIWXXEVA.js} +1 -1
- package/dist/standalone/{chunk-J2GQE4PW.js → chunk-FKXX3Y2J.js} +1 -1
- package/dist/standalone/{chunk-JIPVSPSG.js → chunk-FS7FGJOU.js} +1 -1
- package/dist/standalone/{chunk-P4QIDUCY.js → chunk-GDC3W3DZ.js} +1 -1
- package/dist/standalone/{chunk-2F6FYL5O.js → chunk-GISVVEPU.js} +1 -1
- package/dist/standalone/{chunk-RSG2DVHH.js → chunk-GNN5HJ56.js} +1 -1
- package/dist/standalone/{chunk-YN2KHW3B.js → chunk-ICQTVV6U.js} +1 -1
- package/dist/standalone/{chunk-B3BKR5ZW.js → chunk-JCSDJBBZ.js} +1 -1
- package/dist/standalone/{chunk-RK5XWYUL.js → chunk-K3SXMDKL.js} +1 -1
- package/dist/standalone/{chunk-KWGHNORP.js → chunk-KJNDUIZG.js} +1 -1
- package/dist/standalone/{chunk-PS66CRK5.js → chunk-KNI5YDPT.js} +1 -1
- package/dist/standalone/{chunk-BYJZGWWY.js → chunk-KR6SZXOI.js} +1 -1
- package/dist/standalone/{chunk-VDSFYFDH.js → chunk-KTEVBZIV.js} +1 -1
- package/dist/standalone/{chunk-P54YTPHL.js → chunk-MHB2TOAK.js} +1 -1
- package/dist/standalone/{chunk-XFU6YBYL.js → chunk-MTGEDJQH.js} +1 -1
- package/dist/standalone/{chunk-A44VDLY3.js → chunk-N7PPYEHW.js} +1 -1
- package/dist/standalone/{chunk-YTYRZTG6.js → chunk-NIUA7EHL.js} +1 -1
- package/dist/standalone/{chunk-GTEXP4P3.js → chunk-O4RQGUJ7.js} +1 -1
- package/dist/standalone/{chunk-WYSR5F77.js → chunk-OCZ2IP5A.js} +1 -1
- package/dist/standalone/{chunk-GK2UBSBQ.js → chunk-PAJQOSEU.js} +1 -1
- package/dist/standalone/{chunk-D52S7TOI.js → chunk-PGTCEMBA.js} +1 -1
- package/dist/standalone/{chunk-WIFYD4A6.js → chunk-POD66K2Y.js} +1 -1
- package/dist/standalone/{chunk-KPQROFH5.js → chunk-QBONDY5I.js} +1 -1
- package/dist/standalone/{chunk-2QLWSNDL.js → chunk-R7EV3YND.js} +1 -1
- package/dist/standalone/{chunk-G3NGXYJY.js → chunk-RAFPVMXJ.js} +1 -1
- package/dist/standalone/{chunk-QLG2EJU3.js → chunk-SQSMHFA7.js} +1 -1
- package/dist/standalone/{chunk-5JF2HAU4.js → chunk-TCAX32PK.js} +1 -1
- package/dist/standalone/{chunk-27IF4PXG.js → chunk-TDH7K7E7.js} +1 -1
- package/dist/standalone/{chunk-5HICO276.js → chunk-THTL2KBP.js} +1 -1
- package/dist/standalone/{chunk-R3G55P4J.js → chunk-TI5RJJRX.js} +1 -1
- package/dist/standalone/{chunk-QDGAB4R2.js → chunk-TKKRBSUB.js} +1 -1
- package/dist/standalone/{chunk-QKN5EHEF.js → chunk-U2FRMJAN.js} +1 -1
- package/dist/standalone/{chunk-6J5TEYI5.js → chunk-U32MMDFO.js} +1 -1
- package/dist/standalone/chunk-UDCFI5NF.js +14 -0
- package/dist/standalone/{chunk-XRC7KEEN.js → chunk-UFUOW6UJ.js} +1 -1
- package/dist/standalone/{chunk-4PVSXT34.js → chunk-VJQAOU2U.js} +1 -1
- package/dist/standalone/{chunk-4LVLLM6B.js → chunk-VTFMI4DC.js} +1 -1
- package/dist/standalone/{chunk-4Y2QHI65.js → chunk-XYWLXNTV.js} +1 -1
- package/dist/standalone/{chunk-R52YOHVU.js → chunk-ZWATJNSU.js} +1 -1
- package/dist/standalone/studio.js +1 -1
- package/package.json +3 -3
- package/dist/packem_shared/reference-view-CxW7paCK.js +0 -12
- package/dist/standalone/chunk-XTNSQYXW.js +0 -13
|
@@ -8,4 +8,4 @@ import{c as p}from"./chunk-VYW2PAWC.js";import{a,d as P,e as H,f as mt,g as Ue}f
|
|
|
8
8
|
`,`
|
|
9
9
|
`),n()){await r.cancel().catch(()=>{});return}}i+=s.decode().replaceAll(`\r
|
|
10
10
|
`,`
|
|
11
|
-
`),n()||e.fail(new p("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"))},"E"),ar=a((t,e,r={})=>{let s=r.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!s)throw new p("INTERNAL","httpStream: no `fetch` implementation available");let i=Zr(t,e??{},r.baseUrl??""),n=new AbortController,o;r.signal&&(r.signal.aborted?n.abort():(o=a(()=>{n.abort()},"s"),r.signal.addEventListener("abort",o,{once:!0})));let c=a(()=>{o&&r.signal?.removeEventListener("abort",o)},"d"),{handle:u,iterable:h}=Fe({maxBuffer:r.maxBuffer,onCancel:a(()=>{n.abort()},"onCancel")});return(async()=>{try{let d=await s(i,{headers:{accept:"text/event-stream",...r.headers},method:t.method,signal:n.signal});if(!d.ok){await d.body?.cancel().catch(()=>{}),u.fail(new p("HTTP_STREAM_STATUS",`httpStream: request failed (status ${d.status.toString()})`,{status:d.status}));return}if(!d.body){u.fail(new p("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}await ts(d.body,u)}finally{c()}})().catch(d=>{if(n.signal.aborted){u.complete();return}if(d instanceof Error&&"code"in d){u.fail(d);return}u.fail(new p("HTTP_STREAM_TRANSPORT",d instanceof Error?d.message:String(d),{cause:d}))}),h},"w");var rs=a((t,e)=>t<e?-1:t>e?1:0,"f"),nt=a(t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key \u2014 pass it as a string, or use stableWireKey");if(typeof t=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t))return`[${t.map(n=>nt(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(rs),i=[];for(let n of s){let o=r[n];o!==void 0&&i.push(`${JSON.stringify(n)}:${nt(o)}`)}return`{${i.join(",")}}`},"e"),B=a(t=>nt(O(t)),"p");var _=class t{static{a(this,"r")}static key(e,r,s){return`${e}::${B(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 he=a((t,e)=>{let r=t;for(let s of e)try{r=s.transform(r)}catch{}return r},"p"),te=a((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let r of t.callbacks)try{r(e)}catch{}}},"u"),at=a((t,e)=>{let r;try{r=e(t.lastValue)}catch{return}let s={id:Symbol("optimistic"),transform:e};t.optimisticLayers.push(s),te(t,r);let i=a(()=>{let o=t.optimisticLayers.findIndex(c=>c.id===s.id);return o===-1?!1:(t.optimisticLayers.splice(o,1),!0)},"c"),n=a(()=>{te(t,he(t.serverBase,t.optimisticLayers))},"a");return{confirm:a(o=>{if(o===void 0){i();return}s.commitCursor=o,t.serverCursor!==void 0&&t.serverCursor>=o&&i()&&n()},"confirm"),rollback:a(()=>{i()&&n()},"rollback")}},"y"),Me=a((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},"h"),or=a((t,e)=>{let r=[],s=[],i=a((n,o)=>t.get(_.key(n,o,e)),"c");return{confirms:r,rollbacks:s,store:{getAllQueries:a(n=>{let o=[];for(let c of t.all())c.fn.__lunoraRef===n.__lunoraRef&&(c.shardKey??"")===(e??"")&&o.push({args:c.args,value:c.lastValue});return o},"getAllQueries"),getQuery:a((n,o)=>i(n.__lunoraRef,o??{})?.lastValue,"getQuery"),setQuery:a((n,o,c)=>{let u=i(n.__lunoraRef,o??{});if(!u)return;let h=at(u,()=>c);h&&(r.push(h.confirm),s.push(h.rollback))},"setQuery")}}},"L");var cr=0,ss=a(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();cr+=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)}_${cr.toString(36)}_${t}`},"a"),ot=a((t,e)=>t!==void 0&&e!==t,"f"),_e=ss,re=a((t,e,r,s)=>{if(t){t({error:r,mutationId:s,operation:e});return}console.warn(`[lunora] offline-queue persistence ${e} failed`,r)},"o"),xe=class{static{a(this,"m")}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??=_e(),this.items.push(r),this.persistence?.append({args:r.args,clientId:r.clientId,functionPath:r.functionPath,id:r.id,identity:r.identity,shardKey:r.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(s=>{re(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(o){throw re(this.onPersistenceError,"load",o),o}let r=[],s=new Set(this.items.map(o=>o.id));for(let o of e)if(!s.has(o.id)){if(ot(this.version,o.version)){this.persistence.remove(o.id).catch(c=>{re(this.onPersistenceError,"remove",c,o.id)});continue}s.add(o.id),r.push({args:o.args,clientId:o.clientId,functionPath:o.functionPath,id:o.id,identity:o.identity,reject:a(()=>{},"reject"),resolve:a(()=>{},"resolve"),shardKey:o.shardKey})}this.items.unshift(...r),this.evictOverflow(),this.notifySize();let i=new Set(this.items),n=new Set;for(let o of r)i.has(o)&&n.add(o.shardKey);return[...n]}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=>{re(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 is="lunora-outbox",ns="offline-mutations",ur="by_id",as=a((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new p("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let r=t.databaseName??is,s=t.storeName??ns,i=Te(e,r,1,o=>{o.objectStoreNames.contains(s)||o.createObjectStore(s,{autoIncrement:!0}).createIndex(ur,"id",{unique:!0})}),n=Oe(i,s);return{append:a(async o=>{await n("readwrite",c=>A(c.add(o)))},"append"),clear:a(async()=>{await n("readwrite",o=>A(o.clear()))},"clear"),load:a(async()=>n("readonly",o=>A(o.getAll())),"load"),remove:a(async o=>{await n("readwrite",async c=>{let u=await A(c.index(ur).getKey(o));u!==void 0&&await A(c.delete(u))})},"remove")}},"p"),hr=a((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return as()}},"b");var ct=a((t={},e=Math.random)=>{let r=t.initialDelayMs??250,s=t.maxDelayMs??3e4,i=t.jitter??!0,n=0;return{next(){let o=Math.min(s,r*2**n);if(n+=1,!i)return o;let c=o/2;return Math.floor(c+e()*(o-c))},reset(){n=0}}},"s");var dr=a((t,e,r,s)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,r,s),n=i.present?B(i.value):void 0;return()=>{let o=t.peekActiveQuerySnapshot(e.__lunoraRef,r,s);return!i.present||!o.present?!0:B(o.value)===n}},"c");var ut=500,os=a((t,e)=>{if(t.size<e)return;let r=t.keys().next().value;r!==void 0&&t.delete(r)},"he"),J=class{static{a(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()}},cs="/_lunora/rpc",lr="/_lunora/rpc-batch",us="/_lunora/ws",ht=a(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"L"),Le=a(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"E"),hs=a((t,e)=>{for(let r of e)r.op==="delete"?t.delete(r.key):r.value!==void 0&&t.set(r.key,r.value)},"le"),ds="lunora-ping",ls=3e4,fs=1e4,ps=250,ms=64,ys="/_lunora/admin/shard-traffic",bs="/_lunora/admin/scheduled",gs="/_lunora/admin/scheduled/status",vs="/_lunora/admin/scheduled/ws",Ss="/_lunora/admin/scheduled/cancel",ws="/_lunora/admin/scheduled/dead",Cs="/_lunora/admin/scheduled/dead/retry",ks="/_lunora/admin/scheduled/dead/cancel",Is="/_lunora/admin/workflows/instances",Es="/_lunora/admin/workflows/instance",Ts="/_lunora/admin/workflows/status",dt="/_lunora/admin/storage",Os="/_lunora/admin/storage/url",Rs="/_lunora/admin/storage/buckets",Ps="/_lunora/admin/functions",As="/_lunora/admin/cron-jobs",Fs="/_lunora/admin/cron-jobs/run",Ms="/_lunora/admin/openapi",xs="/_lunora/admin/openrpc",_s="/_lunora/admin/global/tables",Ls="/_lunora/admin/global/table",Qs="/_lunora/admin/global/facet",Ds="/_lunora/admin/vector/indexes",Us="/_lunora/admin/vector/query",qs="/_lunora/admin/logs/archive",Ns="/_lunora/admin/kv/namespaces",Ks="/_lunora/admin/kv/keys",lt="/_lunora/admin/kv/value",Bs="/_lunora/admin/auth/users",js="/_lunora/admin/auth/sessions",$s="/_lunora/admin/auth/users/create",Hs="/_lunora/admin/auth/users/role",zs="/_lunora/admin/auth/users/ban",Ws="/_lunora/admin/auth/users/unban",Vs="/_lunora/admin/auth/users/password",Gs="/_lunora/admin/auth/users/remove",Js="/_lunora/admin/auth/users/impersonate",Xs="/_lunora/admin/auth/sessions/revoke",Ys="/_lunora/admin/auth/sessions/revoke-all",Zs="/_lunora/admin/auth/capabilities",ei="/_lunora/admin/auth/users/update",ti="/_lunora/admin/auth/accounts",ri="/_lunora/admin/auth/accounts/unlink",si="/_lunora/admin/auth/passkeys",ii="/_lunora/admin/auth/passkeys/delete",ni="/_lunora/admin/auth/two-factor/disable",ai="/_lunora/admin/auth/organizations",oi="/_lunora/admin/auth/organizations/members",ci="/_lunora/admin/auth/organizations/invitations",ui="/_lunora/admin/auth/organizations/members/remove",hi="/_lunora/admin/auth/organizations/invitations/cancel",di="/_lunora/admin/auth/config",li="/_lunora/admin/auth/organizations/create",fi="/_lunora/admin/auth/organizations/update",pi="/_lunora/admin/auth/organizations/remove",mi="/_lunora/admin/auth/organizations/members/add",yi="/_lunora/admin/auth/organizations/members/invite",bi="/_lunora/admin/auth/organizations/members/role",gi="/_lunora/admin/auth/organizations/teams",vi="/_lunora/admin/auth/organizations/teams/create",Si="/_lunora/admin/auth/organizations/teams/update",wi="/_lunora/admin/auth/organizations/teams/remove",Ci="/_lunora/admin/auth/organizations/teams/members",ki="/_lunora/admin/auth/organizations/teams/members/add",Ii="/_lunora/admin/auth/organizations/teams/members/remove",Ei="/_lunora/admin/auth/organizations/roles",Ti="/_lunora/admin/auth/organizations/roles/create",Oi="/_lunora/admin/auth/organizations/roles/update",Ri="/_lunora/admin/auth/organizations/roles/remove",Pi="/api/auth",Ai="/get-session",fr=a(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"W"),V=a((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"k"),T=a((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}`},"y"),Fi=[tr],C=a(t=>t??"","m"),mr=a((t,e)=>{let r=t.error,s=typeof r?.code=="string"?r.code:void 0,i=typeof r?.message=="string"?r.message:void 0;return{code:s,messageText:(typeof t.message=="string"?t.message:void 0)??i??e}},"$"),Mi=a(t=>{let{code:e,messageText:r}=mr(t,"stream error");return e===void 0?new Error(r):new p(e,r)},"Lt"),pr=a(t=>{let{code:e,messageText:r}=mr(t,"subscription error");return{message:r,...e===void 0?{}:{code:e}}},"q"),Qe=a((t,e)=>{for(let r of t)try{r(e)}catch{}},"A"),xi=new TextDecoder,_i=a(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return xi.decode(t)},"Ut"),F=a((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"S"),de=a(t=>{let e=new Error(t.message??"request failed");return e.code=t.code,t.data!==void 0&&(e.data=S(t.data)),t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),e},"_"),G=a((t,e)=>{try{return O(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)}},"v"),Li=a((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:S(i?.result)}}return r.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},"xt"),Qi=new Set(["SHARD_ERROR","SHARD_UNAVAILABLE"]),Di=Promise.resolve(),ft=class t{static{a(this,"Q")}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;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new _;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 J;statusListeners=new J;tokenExpiredListeners=new J;mutationSettledListeners=new J;pendingChangeListeners=new J;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??V(fr(e.url),us),this.wsToken=e.wsToken;let r=e.authBasePath??Pi;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??Zt(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??ls,this.connectTimeoutMs=e.connectTimeoutMs??fs,this.defaultConnectionContext=e.connectionContext,this.persistence=hr(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Yt(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new Pe,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=Di),this.offlineQueue=new xe(e.offlineQueue,{onEvict:a((s,i)=>{this.emitItemSettled(s,"rejected",i)},"onEvict"),onSizeChange:a(s=>{this.pendingChangeListeners.emit(s)},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${_e()}`,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.restampWatermarks(i,n)),this.tabCoordinator)){let o=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),o&&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(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,r,s){let i=s?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new p("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let n=s?.shardKey??"",o=this.identityFingerprint(),c,u=await this.rpc(e,r,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:a(h=>{c=h},"onMutationAck")});if(c!==void 0&&c>(this.clientWatermarks.get(o??"")?.get(n)??0)){let h=this.clientWatermarks.get(o??"");h===void 0&&(h=new Map,this.clientWatermarks.set(o??"",h)),h.set(n,c)}return{applied:c===void 0||c===i,result:u}}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(V(this.url,`${this.authBasePath}${Ai}`),{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 o=!1;return()=>{if(o)return;o=!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 o=n.get(e),c=o===void 0;if(o||(o=new Set,n.set(e,o)),o.add(r),this.ensureSocket(s.shardKey),c){let u=this.getConnection(s.shardKey);u&&F(u,{topic:e,type:"whisper_subscribe"})}return()=>{let u=this.whisperHandlers.get(i),h=u?.get(e);if(!h?.delete(r)||h.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let d=this.getConnection(s.shardKey);d&&F(d,{topic:e,type:"whisper_unsubscribe"})}}whisper(e,r,s={}){this.ensureSocket(s.shardKey);let i=this.getConnection(s.shardKey);i&&F(i,{data:G(r??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"})}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let r=this.statusListeners.add(e);return e(this.computeStatus()),r}pendingCount(){return this.offlineQueue.size}debug(){let e=[],r=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...r?.keys()??[]]);for(let n of s){let o=this.connections.get(n);e.push({confirmedMutationWatermark:r?.get(n)??0,hasSocket:o?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:o?.wasEverConnected??!1,wsState:o?.wsState??"idle"})}let i=this.subscriptions.all().map(n=>({acked:n.acked,functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(let n of this.shapeSubscriptions.values())i.push({acked:n.serverCursor!==void 0,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,o)=>(n.shardKey??"").localeCompare(o.shardKey??"")),subscriptions:i.toSorted((n,o)=>n.functionPath.localeCompare(o.functionPath))}}onPendingChange(e){let r=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),r}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,r){this.clientQueryStore.set(e,r)}subscribeClientQuery(e,r){return this.clientQueryStore.subscribe(e,r)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,r,s){return dr(this,e,r,s)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,r,s){if(!this.readyResolved)return;let i=B(r),n=Re(e,i,s),o=this.hydratedQueryCache.get(n);if(o!==void 0)return o.identity===this.identityFingerprint()?o.value:void 0}peekActiveQuerySnapshot(e,r,s){let i=_.key(e,r,s),n=this.subscriptions.get(i);return{present:n!==void 0,value:n?.lastValue}}async query(e,r,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,r,s.shardKey,{attachBookmark:!0})}async batch(e){if(this.assertOpen(),!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(V(this.url,lr),{body:JSON.stringify({calls:e.map((n,o)=>({args:G(n.args??{},`args for batch call '${n.fn.__lunoraRef}'`),functionPath:n.fn.__lunoraRef,id:o,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 p("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 p("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`);for(let n of i.results??[]){let o=n.body?.commitCursor;typeof n.id=="number"&&typeof o=="number"&&this.recordShardCursor(e[n.id]?.shardKey,o)}return Li(i.results??[],e.length)}async mutation(e,r,s={}){this.assertOpen();let i=r,n=s.mutationId??_e(),{confirms:o,rollbacks:c}=this.applyOptimisticUpdates(e.__lunoraRef,i,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,r,s.shardKey,c,o);let{hasSocket:u,wasEverConnected:h,wsState:d}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:l}=this.offlineQueue,f=h||l,m=this.WebSocketImpl!==void 0&&f;if(d!=="open"&&!u&&m||d==="connecting"&&f)return this.enqueueOfflineMutation(e,i,s.shardKey,n,c,o,s.precondition);try{let y,b=await this.rpc(e.__lunoraRef,i,s.shardKey,{captureBookmark:!0,mutationId:n,onCommitCursor:a(w=>{y=w},"onCommitCursor")});for(let w of o)w(y);return b}catch(y){throw Le(c),y}}async action(e,r,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,r,s.shardKey)}async importRows(e,r,s={}){this.assertOpen();let i=Math.max(1,Math.trunc(s.chunkSize??500)),n=s.toArgs??(h=>({rows:h})),o=r.length,c=0,u=0;for(let h=0;h<o;h+=i){let d=r.slice(h,h+i),l=u;await this.mutation(e,n(d),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(l)}`},shardKey:s.shardKey}),u+=1,c+=d.length,s.onProgress?.({done:c,total:o})}return{chunks:u,imported:c}}async shardTraffic(e){this.assertOpen();let r=await this.adminFetch(ys,"POST",{table:e});return{failed:r.failed??0,ok:r.ok??0,shards:r.shards??[]}}async listScheduledJobs(){return this.assertOpen(),(await this.adminFetch(bs,"GET")).records??[]}async schedulerStatus(){this.assertOpen();let e=await this.adminFetch(gs,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}}async cancelScheduledJob(e){return this.assertOpen(),{cancelled:(await this.adminFetch(Ss,"POST",{id:e})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await this.adminFetch(ws,"GET")).records??[]}async retryDeadJob(e){return this.assertOpen(),{retried:(await this.adminFetch(Cs,"POST",{id:e})).retried===!0}}async removeDeadJob(e){return this.assertOpen(),{removed:(await this.adminFetch(ks,"POST",{id:e})).removed===!0}}async listWorkflowInstances(e){this.assertOpen();let r=new URLSearchParams({name:e.name});e.status!==void 0&&r.set("status",e.status),e.page!==void 0&&r.set("page",String(e.page)),e.perPage!==void 0&&r.set("perPage",String(e.perPage));let s=await this.adminFetch(`${Is}?${r.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}}async getWorkflowInstance(e){this.assertOpen();let r=new URLSearchParams({id:e.id,name:e.name}),s=await this.adminFetch(`${Es}?${r.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??e.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}}async setWorkflowInstanceStatus(e){return this.assertOpen(),{status:(await this.adminFetch(Ts,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let r=V(fr(this.url),vs),s=ct(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},n,o=!1,c=a(()=>{o||(n=setTimeout(d,s.next()))},"a"),u=a(l=>{if(o||this.WebSocketImpl===void 0)return;let f=l===void 0?r:`${r}?token=${encodeURIComponent(l)}`;this.openManagedSocket(i,f,this.connectTimeoutMs,{onClose:a(()=>{c()},"onClose"),onMessage:a(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:a(()=>{s.reset()},"onOpen")})},"o"),h=a(async l=>{let f;try{f=await l()}catch{c();return}u(f)},"c"),d=a(()=>{if(o||this.WebSocketImpl===void 0)return;let{wsToken:l}=this;if(typeof l=="function"){h(l).catch(()=>{});return}u(l)},"d");return d(),()=>{o=!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(){return this.assertOpen(),(await this.adminFetch(Ps,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(As,"GET")).jobs??[]}async runCronJob(e){this.assertOpen();let r=await this.adminFetch(Fs,"POST",{name:e});return{name:r.name??e,ran:r.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(Ms,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(xs,"GET")}async listStorageObjects(e={}){this.assertOpen();let r=T(dt,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await this.adminFetch(r,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(e,r){this.assertOpen();let s=`${dt}?key=${encodeURIComponent(e)}${ht(r?.bucket)}`,i=await this.adminFetch(s,"DELETE");return{deleted:i.deleted??!0,key:i.key??e}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(Rs,"GET")).buckets??[]}async uploadStorageObject(e){this.assertOpen();let r=`${dt}?key=${encodeURIComponent(e.key)}${ht(e.bucket)}`,s=await this.adminFetch(r,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}}async signedStorageUrl(e,r){this.assertOpen();let s=r?.expiresInSeconds,i=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,n=`${Os}?key=${encodeURIComponent(e)}${i}${ht(r?.bucket)}`,o=await this.adminFetch(n,"GET");if(typeof o.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return o.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(_s,"GET")}async readGlobalTablePage(e){this.assertOpen();let r=new URLSearchParams({table:e.table});return e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&r.set("filters",JSON.stringify(e.filters)),await this.adminFetch(`${Ls}?${r.toString()}`,"GET")}async facetGlobalColumn(e){this.assertOpen();let r=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&r.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&r.set("filters",JSON.stringify(e.filters)),await this.adminFetch(`${Qs}?${r.toString()}`,"GET")}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch(Ds,"GET")).indexes??[]}async queryVectorIndex(e){return this.assertOpen(),(await this.adminFetch(Us,"POST",e)).matches??[]}async queryLogArchive(e={}){this.assertOpen();let r=await this.adminFetch(qs,"POST",e);return{nextCursor:r.nextCursor,rows:r.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(Ns,"GET")).namespaces??[]}async listKvKeys(e){this.assertOpen();let r=T(Ks,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await this.adminFetch(r,"GET")}async getKvValue(e){this.assertOpen();let r=T(lt,{key:e.key,namespace:e.namespace});return await this.adminFetch(r,"GET")}async putKvValue(e){this.assertOpen(),await this.adminFetch(lt,"PUT",e)}async deleteKvKey(e){this.assertOpen();let r=T(lt,{key:e.key,namespace:e.namespace});await this.adminFetch(r,"DELETE")}async listAuthUsers(e={}){this.assertOpen();let r=T(Bs,{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($s,"POST",e)}async setAuthUserRole(e){return await this.adminFetch(Hs,"POST",e)}async banAuthUser(e){return await this.adminFetch(zs,"POST",e)}async unbanAuthUser(e){return await this.adminFetch(Ws,"POST",e)}async setAuthUserPassword(e){await this.adminFetch(Vs,"POST",e)}async removeAuthUser(e){await this.adminFetch(Gs,"POST",e)}async impersonateAuthUser(e){return await this.adminFetch(Js,"POST",e)}async revokeAuthSession(e){await this.adminFetch(Xs,"POST",e)}async revokeAuthUserSessions(e){await this.adminFetch(Ys,"POST",e)}async getAuthCapabilities(){return await this.adminFetch(Zs,"GET")}async updateAuthUser(e){return await this.adminFetch(ei,"POST",e)}async listAuthAccounts(e){return await this.adminFetch(T(ti,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){await this.adminFetch(ri,"POST",e)}async listAuthPasskeys(e){return await this.adminFetch(T(si,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){await this.adminFetch(ii,"POST",e)}async disableAuthTwoFactor(e){await this.adminFetch(ni,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(T(ai,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){let r=T(oi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async listAuthOrgInvitations(e){let r=T(ci,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async removeAuthOrgMember(e){await this.adminFetch(ui,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(hi,"POST",e)}async getAuthConfig(){return await this.adminFetch(di,"GET")}async createAuthOrganization(e){return await this.adminFetch(li,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(fi,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(pi,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch(mi,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(yi,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch(bi,"POST",e)}async listAuthOrgTeams(e){let r=T(gi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(vi,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch(Si,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(wi,"POST",e)}async listAuthOrgTeamMembers(e){let r=T(Ci,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(r,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(ki,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(Ii,"POST",e)}async listAuthOrgRoles(e){let r=T(Ei,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async createAuthOrgRole(e){return await this.adminFetch(Ti,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(Oi,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(Ri,"POST",e)}async listAuthSessions(e={}){this.assertOpen();let r=T(js,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(r,"GET")}subscribe(e,r,s,i={}){this.assertOpen();let n=r??{},o=_.key(e.__lunoraRef,n,i.shardKey),c=this.subscriptions.get(o),u=s,h=i.onError;if(!c){this.nextSubId+=1;let l=`sub_${this.nextSubId.toString()}`,f=B(n),m=this.takeHydratedCache(e.__lunoraRef,f,i.shardKey);c={acked:!1,args:n,argsKey:f,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:l,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),h&&c.errorCallbacks.add(h),i.onCheckpoint&&c.checkpointCallbacks.add(i.onCheckpoint),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let d=c;return()=>{d.callbacks.delete(u),h&&d.errorCallbacks.delete(h),i.onCheckpoint&&d.checkpointCallbacks.delete(i.onCheckpoint),d.callbacks.size===0&&(this.sendOrQueueUnsubscribe(d.shardKey,d.id,"unsubscribe"),this.subscriptions.remove(d))}}subscribeShape(e,r,s={}){this.assertOpen(),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:G(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,n),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(n.shardKey,i,"shape_unsubscribe")}}stream(e,r,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new p("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;let i=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=s,o=r??{},{handle:c,iterable:u}=Fe({maxBuffer:s.maxBuffer,onCancel:a(()=>{let l=this.getConnection(n);l&&F(l,{id:i,type:"unsubscribe"}),this.streams.delete(i)},"onCancel")});this.ensureSocket(n);let h=this.getConnection(n),d={id:i,query:{args:G(o,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"};if(this.streams.set(i,{durable:s.durable===!0,handle:c,lastSeq:0,message:d,shardKey:n}),!(h?.wsState==="open"&&F(h,d))&&h){for(h.pendingStreams=h.pendingStreams??[];h.pendingStreams.length>=ms;){let l=h.pendingStreams.shift()?.id,f=l?this.streams.get(l):void 0;f&&(f.handle.fail(new p("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(l))}h.pendingStreams.push(d)}return u}httpStream(e,r,s={}){if(this.closed)throw new p("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return ar(e,r,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(let e of this.streams.values())e.handle.fail(new p("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}assertOpen(){if(this.closed)throw new p("INTERNAL","LunoraClient is closed")}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 Ae({channelName:e,onBecomeLeader:a(()=>{for(let r of this.subscriptions.all())this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(r);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},"onBecomeLeader"),onStopBeingLeader:a(()=>{for(let[r,s]of this.connections)this.teardownConnection(s),this.connections.delete(r);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},"onStopBeingLeader"),onConnectionStatus:a((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:a((r,s,i,n,o)=>{if(o!==void 0&&o!==this.identityFingerprint())return;let c=this.subscriptions.get(r);c&&(c.serverBase=s,i!==void 0&&(c.serverCursor=i,n!==void 0&&(c.serverEpoch=n),Me(c,i)),te(c,he(s,c.optimisticLayers)))},"onSubscriptionData"),onSubscriptionError:a((r,s)=>{let i=this.subscriptions.get(r);i&&Qe(i.errorCallbacks,s)},"onSubscriptionError"),onSubscriptionSettled:a((r,s,i,n,o,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&&o===this.clientId&&(u.lastMutationId=Math.max(u.lastMutationId??0,n));for(let h of u.checkpointCallbacks)h({checkpoint:u.serverCursor,mutationId:u.lastMutationId})}},"onSubscriptionSettled")})}async enqueueOfflineMutation(e,r,s,i,n,o,c){let u=this.identityFingerprint();if(this.outbox){this.outboxMutationCounter+=1;let h=this.outboxMutationCounter;try{await this.outbox.enqueue({args:r,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:`${this.clientId}:${String(h)}`,identity:u,mutationId:h,shardKey:s})}catch(d){throw Le(n),d instanceof Error?d:new Error(String(d))}for(let d of o)d(void 0);return}return new Promise((h,d)=>{let l={args:r,functionPath:e.__lunoraRef,liveAwaiter:!0,id:i,clientId:this.clientId,identity:u,precondition:c,onCommit:a(f=>{for(let m of o)m(f)},"onCommit"),reject:a(f=>{this.queuedIdentities.delete(i),Le(n),d(f instanceof Error?f:new Error(String(f)))},"reject"),resolve:h,shardKey:s};this.offlineQueue.enqueue(l),this.queuedOfflineShardKeys.add(s),l.id!==void 0&&this.queuedIdentities.set(l.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=a(()=>{this.hydratePersistedQueue().catch(()=>{})},"e"),r=globalThis.navigator?.locks;if(!r){e();return}r.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{let e=await this.queryCache.load();for(let{key:r,...s}of e){if(ot(this.persistenceVersion,s.version)){this.queryCache.remove(r).catch(()=>{});continue}this.hydratedQueryCache.set(r,s)}}catch{}}takeHydratedCache(e,r,s){let i=Re(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=Re(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(()=>{})},ps)}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;let{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}let r=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(r.map(async([s,i])=>e.put(s,i)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";let e=[...this.connections.values()];return e.length===0?"idle":e.some(r=>r.wsState==="open")?"connected":e.some(r=>r.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=[],o=[];if(!i)return{confirms:n,rollbacks:o};let c=_.key(e,r,s),u=this.subscriptions.get(c);if(u){let h=at(u,i);h&&(n.push(h.confirm),o.push(h.rollback))}return{confirms:n,rollbacks:o}}applyOptimisticUpdate(e,r,s,i,n){let{confirms:o,rollbacks:c,store:u}=or(this.subscriptions,s);try{e(u,r)}catch{Le(c);return}i.push(...c),n.push(...o)}getConnection(e){return this.connections.get(C(e))}sendOrQueueUnsubscribe(e,r,s){let i=this.getConnection(e);i&&!F(i,{id:r,type:s})&&i.pendingUnsubscribes.push({id:r,type:s})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let s="idle";return this.leaderStatus==="connected"?s="open":this.leaderStatus==="connecting"&&(s="connecting"),{hasSocket:!1,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:ct(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,r){let s={"content-type":"application/json"},i=this.shardCursors.get(this.cursorKeyFor(r));if(i!==void 0&&(s["x-lunora-min-seq"]=i.toString()),this.authToken&&(s.authorization=`Bearer ${this.authToken}`),e.mutationId&&(s["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(s["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(s["x-lunora-client-seq"]=e.clientSeq.toString()),e.attachBookmark){let n=this.bookmark.get();n&&(s["x-d1-bookmark"]=n)}return s}async rpc(e,r,s,i={}){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");let n=this.rpcRequestHeaders(i,s),o=await this.fetchImpl(V(this.url,cs),{body:JSON.stringify({args:G(r,`args for '${e}'`),functionPath:e,shardKey:s}),headers:n,method:"POST"});if(i.captureBookmark){let u=o.headers.get("x-d1-bookmark");u&&this.bookmark.set(u)}let c;try{c=await o.json()}catch{let u=o.statusText?` ${o.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${o.status.toString()}${u})`)}if("error"in c)throw de(c.error);if(!o.ok){let u=o.statusText?` ${o.statusText}`:"";throw new p("INTERNAL",`LunoraClient: request failed (status ${o.status.toString()}${u})`)}return i.onMutationAck?.(c.lastMutationId),i.onCommitCursor?.(c.commitCursor),this.learnDefaultShardKey(o,s),this.recordShardCursor(s,c.commitCursor),S(c.result)}async adminFetch(e,r,s,i){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");let n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);let o=s instanceof ArrayBuffer||s instanceof Blob,c;s===void 0?c=void 0:o?(c=s,i!==void 0&&(n["content-type"]=i)):(c=JSON.stringify(s),n["content-type"]="application/json");let u=await this.fetchImpl(V(this.url,e),{body:c,headers:n,method:r}),h;try{h=await u.json()}catch{let d=u.statusText?` ${u.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${d})`)}if(typeof h=="object"&&h!==null&&"error"in h){let d=h.error,l=new Error(d.message??"admin request failed");throw l.code=d.code,l}if(!u.ok){let d=u.statusText?` ${u.statusText}`:"";throw new p("INTERNAL",`LunoraClient: admin request failed (status ${u.status.toString()}${d})`)}return h}effectiveConnectionContext(e){let r=this.connectionContextHolders.get(e);return r&&r.length>0?r[r.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){let r=this.connections.get(e);r?.wsState==="open"&&this.sendConnectEnvelope(r)}sendConnectEnvelope(e){let r=this.effectiveConnectionContext(C(e.shardKey));F(e,{caps:Fi,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 p("INTERNAL","no WebSocket implementation available");let o=new n(r);e.socket=o;let c=a(()=>{this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket===o&&(e.socket=void 0)},"a"),u=a(h=>{c(),i.onClose(h)},"o");s>0&&(e.connectTimer=setTimeout(()=>{if(e.connectTimer=void 0,e.socket===o){try{o.close()}catch{}u()}},s)),o.addEventListener("open",()=>{e.socket===o&&(e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.lastFrameAt=Date.now(),i.onOpen(),this.startHeartbeat(e,u))}),o.addEventListener("message",h=>{e.socket===o&&(e.lastFrameAt=Date.now(),i.onMessage(h))}),o.addEventListener("close",h=>{e.socket===o&&u(h)}),o.addEventListener("error",()=>{e.socket===o&&u()})}openSocket(e,r,s){this.WebSocketImpl!==void 0&&this.openManagedSocket(e,this.wsUrlFor(r,s),this.connectTimeoutMs,{onClose:a(i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},"onClose"),onMessage:a(i=>{this.handleServerMessage(i.data,r)},"onMessage"),onOpen:a(()=>{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:o,type:c}of n)F(e,{id:o,type:c})}if(e.pendingStreams&&e.pendingStreams.length>0){let n=e.pendingStreams;e.pendingStreams=[];for(let o of n)F(e,o)}let i=this.whisperHandlers.get(C(r));if(i)for(let n of i.keys())F(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)if(!(C(n.shardKey)!==C(e.shardKey)||r.has(i))){if(n.durable){let o={...n.message,sinceChunk:n.lastSeq};n.message=o,e.pendingStreams=[...(e.pendingStreams??[]).filter(c=>c.id!==i),o];continue}n.handle.fail(new p("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(ds)}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;F(r,{id:e.id,query:{args:O(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"&&F(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=_i(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:o,seq:c}=i,u=this.streams.get(o);u&&typeof c=="number"&&(u.lastSeq=c,u.durable=!0),u?.handle.push(S(n));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"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(Mi(e)),this.streams.delete(r);return}let i=r===void 0?void 0:this.subscriptions.getById(r);if(i){Qe(i.errorCallbacks,pr(e));return}let n=r===void 0?void 0:this.shapeSubscriptions.get(r);n&&Qe(n.errorCallbacks,pr(e))}handlePokeStart(e){os(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:S(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 o=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(o||c){n.rows.clear(),n.serverCursor=void 0,n.serverEpoch=void 0,this.emitShapeRows(n),this.sendShapeSubscribeIfOpen(n);continue}hs(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),Me(s,s.serverCursor),te(s,he(i,s.optimisticLayers)),this.tabCoordinator?.isLeader()){let n=_.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=_.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),Me(e,e.serverCursor)&&te(e,he(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,r){if("data"in e&&e.data!==void 0)return S(e.data);let s=S(e.delta);if(rr(s)&&r.serverBase!==void 0){let i=sr(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=S(e.data);for(let n of s)try{n(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){let r=this.streams.get(e);if(r){r.handle.complete(),this.streams.delete(e);return}let s=this.subscriptions.getById(e);s&&(s.acked=!1,Qe(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(r=>{re(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)}restampWatermarks(e,r){let s=e??"",i=this.clientWatermarks.get(s);if(i===void 0)return;this.clientWatermarks.delete(s);let n=r??"",o=this.clientWatermarks.get(n);if(o===void 0)this.clientWatermarks.set(n,i);else for(let[c,u]of i)o.set(c,u)}clearQueryCacheForIdentityChange(){this.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 h of r){this.unpersist(h.id),this.queuedIdentities.delete(h.id??"");let d=new Error("offline mutation skipped: precondition failed before replay");d.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(h,"rejected",d)}let s=C(e),i=this.offlineQueue.drain(h=>C(h.shardKey)===s);if(i.length===0)return;let n=this.identityFingerprint(),o=[];for(let h of i)this.passesReplayIdentityGate(h,n)&&o.push(h);if(o.length===0)return;let c=this.encodableOrSettleTerminal(o);if(c.length===0)return;if(c.length===1){await this.replaySequential(c);return}let u=[];for(let h=0;h<c.length;h+=ut){let d=c.slice(h,h+ut),l=await this.replayBatched(d);if(u.push(...l.requeue),l.stop){u.push(...c.slice(h+ut));break}}u.length>0&&this.offlineQueue.requeue(u)}encodableOrSettleTerminal(e){let r=[];for(let s of e)try{G(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),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.resolve(r),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,r){let s=e.headers.get("x-lunora-shard-key");if(s===null||r!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;let i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,i)),this.shardCursors.delete(""))}recordShardCursor(e,r){if(typeof r!="number")return;let s=this.cursorKeyFor(e);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,r))}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,clientId:s.clientId??this.clientId,mutationId:s.id,onCommitCursor:a(o=>{i=o},"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(V(this.url,lr),{body:JSON.stringify({calls:e.map((n,o)=>({args:G(n.args,`args for '${n.functionPath}'`),functionPath:n.functionPath,id:o,clientId:n.clientId??this.clientId,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 o of e)this.settleReplayTerminal(o,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,o]of e.entries()){let c=s.get(n);c===void 0?i.push(o):"error"in c?Qi.has(c.error.code)?i.push(o):this.settleReplayTerminal(o,de(c.error)):this.settleReplaySuccess(o,S(c.result),c.commitCursor)}return i}};var yr=P(mt(),1),br=P(H(),1);var Ui=a(()=>{let t=(0,yr.c)(4),e=Ye(),r,s,i;return t[0]!==e?(r=a(n=>e.onConnectionStatus(()=>{n()}),"o"),s=a(()=>e.connectionStatus(),"e"),i=a(()=>e.connectionStatus(),"c"),t[0]=e,t[1]=r,t[2]=s,t[3]=i):(r=t[1],s=t[2],i=t[3]),(0,br.useSyncExternalStore)(r,s,i)},"S");export{ft as a,Cr as b,Ve as c,xr as d,Lr as e,Ye as f,Ui as g};
|
|
11
|
+
`),n()||e.fail(new p("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"))},"E"),ar=a((t,e,r={})=>{let s=r.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!s)throw new p("INTERNAL","httpStream: no `fetch` implementation available");let i=Zr(t,e??{},r.baseUrl??""),n=new AbortController,o;r.signal&&(r.signal.aborted?n.abort():(o=a(()=>{n.abort()},"s"),r.signal.addEventListener("abort",o,{once:!0})));let c=a(()=>{o&&r.signal?.removeEventListener("abort",o)},"d"),{handle:u,iterable:h}=Fe({maxBuffer:r.maxBuffer,onCancel:a(()=>{n.abort()},"onCancel")});return(async()=>{try{let d=await s(i,{headers:{accept:"text/event-stream",...r.headers},method:t.method,signal:n.signal});if(!d.ok){await d.body?.cancel().catch(()=>{}),u.fail(new p("HTTP_STREAM_STATUS",`httpStream: request failed (status ${d.status.toString()})`,{status:d.status}));return}if(!d.body){u.fail(new p("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}await ts(d.body,u)}finally{c()}})().catch(d=>{if(n.signal.aborted){u.complete();return}if(d instanceof Error&&"code"in d){u.fail(d);return}u.fail(new p("HTTP_STREAM_TRANSPORT",d instanceof Error?d.message:String(d),{cause:d}))}),h},"w");var rs=a((t,e)=>t<e?-1:t>e?1:0,"f"),nt=a(t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key \u2014 pass it as a string, or use stableWireKey");if(typeof t=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t))return`[${t.map(n=>nt(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(rs),i=[];for(let n of s){let o=r[n];o!==void 0&&i.push(`${JSON.stringify(n)}:${nt(o)}`)}return`{${i.join(",")}}`},"e"),B=a(t=>nt(O(t)),"p");var _=class t{static{a(this,"r")}static key(e,r,s){return`${e}::${B(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 he=a((t,e)=>{let r=t;for(let s of e)try{r=s.transform(r)}catch{}return r},"p"),te=a((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let r of t.callbacks)try{r(e)}catch{}}},"u"),at=a((t,e)=>{let r;try{r=e(t.lastValue)}catch{return}let s={id:Symbol("optimistic"),transform:e};t.optimisticLayers.push(s),te(t,r);let i=a(()=>{let o=t.optimisticLayers.findIndex(c=>c.id===s.id);return o===-1?!1:(t.optimisticLayers.splice(o,1),!0)},"c"),n=a(()=>{te(t,he(t.serverBase,t.optimisticLayers))},"a");return{confirm:a(o=>{if(o===void 0){i();return}s.commitCursor=o,t.serverCursor!==void 0&&t.serverCursor>=o&&i()&&n()},"confirm"),rollback:a(()=>{i()&&n()},"rollback")}},"y"),Me=a((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},"h"),or=a((t,e)=>{let r=[],s=[],i=a((n,o)=>t.get(_.key(n,o,e)),"c");return{confirms:r,rollbacks:s,store:{getAllQueries:a(n=>{let o=[];for(let c of t.all())c.fn.__lunoraRef===n.__lunoraRef&&(c.shardKey??"")===(e??"")&&o.push({args:c.args,value:c.lastValue});return o},"getAllQueries"),getQuery:a((n,o)=>i(n.__lunoraRef,o??{})?.lastValue,"getQuery"),setQuery:a((n,o,c)=>{let u=i(n.__lunoraRef,o??{});if(!u)return;let h=at(u,()=>c);h&&(r.push(h.confirm),s.push(h.rollback))},"setQuery")}}},"L");var cr=0,ss=a(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();cr+=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)}_${cr.toString(36)}_${t}`},"a"),ot=a((t,e)=>t!==void 0&&e!==t,"f"),_e=ss,re=a((t,e,r,s)=>{if(t){t({error:r,mutationId:s,operation:e});return}console.warn(`[lunora] offline-queue persistence ${e} failed`,r)},"o"),xe=class{static{a(this,"m")}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??=_e(),this.items.push(r),this.persistence?.append({args:r.args,clientId:r.clientId,functionPath:r.functionPath,id:r.id,identity:r.identity,shardKey:r.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(s=>{re(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(o){throw re(this.onPersistenceError,"load",o),o}let r=[],s=new Set(this.items.map(o=>o.id));for(let o of e)if(!s.has(o.id)){if(ot(this.version,o.version)){this.persistence.remove(o.id).catch(c=>{re(this.onPersistenceError,"remove",c,o.id)});continue}s.add(o.id),r.push({args:o.args,clientId:o.clientId,functionPath:o.functionPath,id:o.id,identity:o.identity,reject:a(()=>{},"reject"),resolve:a(()=>{},"resolve"),shardKey:o.shardKey})}this.items.unshift(...r),this.evictOverflow(),this.notifySize();let i=new Set(this.items),n=new Set;for(let o of r)i.has(o)&&n.add(o.shardKey);return[...n]}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=>{re(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 is="lunora-outbox",ns="offline-mutations",ur="by_id",as=a((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new p("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let r=t.databaseName??is,s=t.storeName??ns,i=Te(e,r,1,o=>{o.objectStoreNames.contains(s)||o.createObjectStore(s,{autoIncrement:!0}).createIndex(ur,"id",{unique:!0})}),n=Oe(i,s);return{append:a(async o=>{await n("readwrite",c=>A(c.add(o)))},"append"),clear:a(async()=>{await n("readwrite",o=>A(o.clear()))},"clear"),load:a(async()=>n("readonly",o=>A(o.getAll())),"load"),remove:a(async o=>{await n("readwrite",async c=>{let u=await A(c.index(ur).getKey(o));u!==void 0&&await A(c.delete(u))})},"remove")}},"p"),hr=a((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return as()}},"b");var ct=a((t={},e=Math.random)=>{let r=t.initialDelayMs??250,s=t.maxDelayMs??3e4,i=t.jitter??!0,n=0;return{next(){let o=Math.min(s,r*2**n);if(n+=1,!i)return o;let c=o/2;return Math.floor(c+e()*(o-c))},reset(){n=0}}},"s");var dr=a((t,e,r,s)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,r,s),n=i.present?B(i.value):void 0;return()=>{let o=t.peekActiveQuerySnapshot(e.__lunoraRef,r,s);return!i.present||!o.present?!0:B(o.value)===n}},"c");var ut=500,os=a((t,e)=>{if(t.size<e)return;let r=t.keys().next().value;r!==void 0&&t.delete(r)},"he"),J=class{static{a(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()}},cs="/_lunora/rpc",lr="/_lunora/rpc-batch",us="/_lunora/ws",ht=a(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"L"),Le=a(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"E"),hs=a((t,e)=>{for(let r of e)r.op==="delete"?t.delete(r.key):r.value!==void 0&&t.set(r.key,r.value)},"le"),ds="lunora-ping",ls=3e4,fs=1e4,ps=250,ms=64,ys="/_lunora/admin/shard-traffic",bs="/_lunora/admin/scheduled",gs="/_lunora/admin/scheduled/status",vs="/_lunora/admin/scheduled/ws",Ss="/_lunora/admin/scheduled/cancel",ws="/_lunora/admin/scheduled/dead",Cs="/_lunora/admin/scheduled/dead/retry",ks="/_lunora/admin/scheduled/dead/cancel",Is="/_lunora/admin/workflows/instances",Es="/_lunora/admin/workflows/instance",Ts="/_lunora/admin/workflows/status",dt="/_lunora/admin/storage",Os="/_lunora/admin/storage/url",Rs="/_lunora/admin/storage/buckets",Ps="/_lunora/admin/functions",As="/_lunora/admin/cron-jobs",Fs="/_lunora/admin/cron-jobs/run",Ms="/_lunora/admin/openapi",xs="/_lunora/admin/openrpc",_s="/_lunora/admin/global/tables",Ls="/_lunora/admin/global/table",Qs="/_lunora/admin/global/facet",Ds="/_lunora/admin/vector/indexes",Us="/_lunora/admin/vector/query",qs="/_lunora/admin/logs/archive",Ns="/_lunora/admin/kv/namespaces",Ks="/_lunora/admin/kv/keys",lt="/_lunora/admin/kv/value",Bs="/_lunora/admin/auth/users",js="/_lunora/admin/auth/sessions",$s="/_lunora/admin/auth/users/create",Hs="/_lunora/admin/auth/users/role",zs="/_lunora/admin/auth/users/ban",Ws="/_lunora/admin/auth/users/unban",Vs="/_lunora/admin/auth/users/password",Gs="/_lunora/admin/auth/users/remove",Js="/_lunora/admin/auth/users/impersonate",Xs="/_lunora/admin/auth/sessions/revoke",Ys="/_lunora/admin/auth/sessions/revoke-all",Zs="/_lunora/admin/auth/capabilities",ei="/_lunora/admin/auth/users/update",ti="/_lunora/admin/auth/accounts",ri="/_lunora/admin/auth/accounts/unlink",si="/_lunora/admin/auth/passkeys",ii="/_lunora/admin/auth/passkeys/delete",ni="/_lunora/admin/auth/two-factor/disable",ai="/_lunora/admin/auth/organizations",oi="/_lunora/admin/auth/organizations/members",ci="/_lunora/admin/auth/organizations/invitations",ui="/_lunora/admin/auth/organizations/members/remove",hi="/_lunora/admin/auth/organizations/invitations/cancel",di="/_lunora/admin/auth/config",li="/_lunora/admin/auth/organizations/create",fi="/_lunora/admin/auth/organizations/update",pi="/_lunora/admin/auth/organizations/remove",mi="/_lunora/admin/auth/organizations/members/add",yi="/_lunora/admin/auth/organizations/members/invite",bi="/_lunora/admin/auth/organizations/members/role",gi="/_lunora/admin/auth/organizations/teams",vi="/_lunora/admin/auth/organizations/teams/create",Si="/_lunora/admin/auth/organizations/teams/update",wi="/_lunora/admin/auth/organizations/teams/remove",Ci="/_lunora/admin/auth/organizations/teams/members",ki="/_lunora/admin/auth/organizations/teams/members/add",Ii="/_lunora/admin/auth/organizations/teams/members/remove",Ei="/_lunora/admin/auth/organizations/roles",Ti="/_lunora/admin/auth/organizations/roles/create",Oi="/_lunora/admin/auth/organizations/roles/update",Ri="/_lunora/admin/auth/organizations/roles/remove",Pi="/api/auth",Ai="/get-session",fr=a(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"W"),V=a((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"k"),T=a((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}`},"y"),Fi=[tr],C=a(t=>t??"","m"),mr=a((t,e)=>{let r=t.error,s=typeof r?.code=="string"?r.code:void 0,i=typeof r?.message=="string"?r.message:void 0;return{code:s,messageText:(typeof t.message=="string"?t.message:void 0)??i??e}},"$"),Mi=a(t=>{let{code:e,messageText:r}=mr(t,"stream error");return e===void 0?new Error(r):new p(e,r)},"Lt"),pr=a(t=>{let{code:e,messageText:r}=mr(t,"subscription error");return{message:r,...e===void 0?{}:{code:e}}},"q"),Qe=a((t,e)=>{for(let r of t)try{r(e)}catch{}},"A"),xi=new TextDecoder,_i=a(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return xi.decode(t)},"Ut"),F=a((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"S"),de=a(t=>{let e=new Error(t.message??"request failed");return e.code=t.code,t.data!==void 0&&(e.data=S(t.data)),t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),e},"_"),G=a((t,e)=>{try{return O(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)}},"g"),Li=a((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:S(i?.result)}}return r.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},"xt"),Qi=new Set(["SHARD_ERROR","SHARD_UNAVAILABLE"]),Di=Promise.resolve(),ft=class t{static{a(this,"Q")}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;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new _;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 J;statusListeners=new J;tokenExpiredListeners=new J;mutationSettledListeners=new J;pendingChangeListeners=new J;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??V(fr(e.url),us),this.wsToken=e.wsToken;let r=e.authBasePath??Pi;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??Zt(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??ls,this.connectTimeoutMs=e.connectTimeoutMs??fs,this.defaultConnectionContext=e.connectionContext,this.persistence=hr(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Yt(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new Pe,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=Di),this.offlineQueue=new xe(e.offlineQueue,{onEvict:a((s,i)=>{this.emitItemSettled(s,"rejected",i)},"onEvict"),onSizeChange:a(s=>{this.pendingChangeListeners.emit(s)},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${_e()}`,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.restampWatermarks(i,n)),this.tabCoordinator)){let o=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),o&&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(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,r,s){let i=s?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new p("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let n=s?.shardKey??"",o=this.identityFingerprint(),c,u=await this.rpc(e,r,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:a(h=>{c=h},"onMutationAck")});if(c!==void 0&&c>(this.clientWatermarks.get(o??"")?.get(n)??0)){let h=this.clientWatermarks.get(o??"");h===void 0&&(h=new Map,this.clientWatermarks.set(o??"",h)),h.set(n,c)}return{applied:c===void 0||c===i,result:u}}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(V(this.url,`${this.authBasePath}${Ai}`),{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 o=!1;return()=>{if(o)return;o=!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 o=n.get(e),c=o===void 0;if(o||(o=new Set,n.set(e,o)),o.add(r),this.ensureSocket(s.shardKey),c){let u=this.getConnection(s.shardKey);u&&F(u,{topic:e,type:"whisper_subscribe"})}return()=>{let u=this.whisperHandlers.get(i),h=u?.get(e);if(!h?.delete(r)||h.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let d=this.getConnection(s.shardKey);d&&F(d,{topic:e,type:"whisper_unsubscribe"})}}whisper(e,r,s={}){this.ensureSocket(s.shardKey);let i=this.getConnection(s.shardKey);i&&F(i,{data:G(r??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"})}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let r=this.statusListeners.add(e);return e(this.computeStatus()),r}pendingCount(){return this.offlineQueue.size}debug(){let e=[],r=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...r?.keys()??[]]);for(let n of s){let o=this.connections.get(n);e.push({confirmedMutationWatermark:r?.get(n)??0,hasSocket:o?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:o?.wasEverConnected??!1,wsState:o?.wsState??"idle"})}let i=this.subscriptions.all().map(n=>({acked:n.acked,functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(let n of this.shapeSubscriptions.values())i.push({acked:n.serverCursor!==void 0,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,o)=>(n.shardKey??"").localeCompare(o.shardKey??"")),subscriptions:i.toSorted((n,o)=>n.functionPath.localeCompare(o.functionPath))}}onPendingChange(e){let r=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),r}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,r){this.clientQueryStore.set(e,r)}subscribeClientQuery(e,r){return this.clientQueryStore.subscribe(e,r)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,r,s){return dr(this,e,r,s)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,r,s){if(!this.readyResolved)return;let i=B(r),n=Re(e,i,s),o=this.hydratedQueryCache.get(n);if(o!==void 0)return o.identity===this.identityFingerprint()?o.value:void 0}peekActiveQuerySnapshot(e,r,s){let i=_.key(e,r,s),n=this.subscriptions.get(i);return{present:n!==void 0,value:n?.lastValue}}async query(e,r,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,r,s.shardKey,{attachBookmark:!0})}async batch(e){if(this.assertOpen(),!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(V(this.url,lr),{body:JSON.stringify({calls:e.map((n,o)=>({args:G(n.args??{},`args for batch call '${n.fn.__lunoraRef}'`),functionPath:n.fn.__lunoraRef,id:o,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 p("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 p("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`);for(let n of i.results??[]){let o=n.body?.commitCursor;typeof n.id=="number"&&typeof o=="number"&&this.recordShardCursor(e[n.id]?.shardKey,o)}return Li(i.results??[],e.length)}async mutation(e,r,s={}){this.assertOpen();let i=r,n=s.mutationId??_e(),{confirms:o,rollbacks:c}=this.applyOptimisticUpdates(e.__lunoraRef,i,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,r,s.shardKey,c,o);let{hasSocket:u,wasEverConnected:h,wsState:d}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:l}=this.offlineQueue,f=h||l,m=this.WebSocketImpl!==void 0&&f;if(d!=="open"&&!u&&m||d==="connecting"&&f)return this.enqueueOfflineMutation(e,i,s.shardKey,n,c,o,s.precondition);try{let y,b=await this.rpc(e.__lunoraRef,i,s.shardKey,{captureBookmark:!0,mutationId:n,onCommitCursor:a(w=>{y=w},"onCommitCursor")});for(let w of o)w(y);return b}catch(y){throw Le(c),y}}async action(e,r,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,r,s.shardKey)}async importRows(e,r,s={}){this.assertOpen();let i=Math.max(1,Math.trunc(s.chunkSize??500)),n=s.toArgs??(h=>({rows:h})),o=r.length,c=0,u=0;for(let h=0;h<o;h+=i){let d=r.slice(h,h+i),l=u;await this.mutation(e,n(d),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(l)}`},shardKey:s.shardKey}),u+=1,c+=d.length,s.onProgress?.({done:c,total:o})}return{chunks:u,imported:c}}async shardTraffic(e){this.assertOpen();let r=await this.adminFetch(ys,"POST",{table:e});return{failed:r.failed??0,ok:r.ok??0,shards:r.shards??[]}}async listScheduledJobs(){return this.assertOpen(),(await this.adminFetch(bs,"GET")).records??[]}async schedulerStatus(){this.assertOpen();let e=await this.adminFetch(gs,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}}async cancelScheduledJob(e){return this.assertOpen(),{cancelled:(await this.adminFetch(Ss,"POST",{id:e})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await this.adminFetch(ws,"GET")).records??[]}async retryDeadJob(e){return this.assertOpen(),{retried:(await this.adminFetch(Cs,"POST",{id:e})).retried===!0}}async removeDeadJob(e){return this.assertOpen(),{removed:(await this.adminFetch(ks,"POST",{id:e})).removed===!0}}async listWorkflowInstances(e){this.assertOpen();let r=new URLSearchParams({name:e.name});e.status!==void 0&&r.set("status",e.status),e.page!==void 0&&r.set("page",String(e.page)),e.perPage!==void 0&&r.set("perPage",String(e.perPage));let s=await this.adminFetch(`${Is}?${r.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}}async getWorkflowInstance(e){this.assertOpen();let r=new URLSearchParams({id:e.id,name:e.name}),s=await this.adminFetch(`${Es}?${r.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??e.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}}async setWorkflowInstanceStatus(e){return this.assertOpen(),{status:(await this.adminFetch(Ts,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let r=V(fr(this.url),vs),s=ct(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},n,o=!1,c=a(()=>{o||(n=setTimeout(d,s.next()))},"a"),u=a(l=>{if(o||this.WebSocketImpl===void 0)return;let f=l===void 0?r:`${r}?token=${encodeURIComponent(l)}`;this.openManagedSocket(i,f,this.connectTimeoutMs,{onClose:a(()=>{c()},"onClose"),onMessage:a(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:a(()=>{s.reset()},"onOpen")})},"o"),h=a(async l=>{let f;try{f=await l()}catch{c();return}u(f)},"c"),d=a(()=>{if(o||this.WebSocketImpl===void 0)return;let{wsToken:l}=this;if(typeof l=="function"){h(l).catch(()=>{});return}u(l)},"d");return d(),()=>{o=!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(){return this.assertOpen(),(await this.adminFetch(Ps,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(As,"GET")).jobs??[]}async runCronJob(e){this.assertOpen();let r=await this.adminFetch(Fs,"POST",{name:e});return{name:r.name??e,ran:r.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(Ms,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(xs,"GET")}async listStorageObjects(e={}){this.assertOpen();let r=T(dt,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await this.adminFetch(r,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(e,r){this.assertOpen();let s=`${dt}?key=${encodeURIComponent(e)}${ht(r?.bucket)}`,i=await this.adminFetch(s,"DELETE");return{deleted:i.deleted??!0,key:i.key??e}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(Rs,"GET")).buckets??[]}async uploadStorageObject(e){this.assertOpen();let r=`${dt}?key=${encodeURIComponent(e.key)}${ht(e.bucket)}`,s=await this.adminFetch(r,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}}async signedStorageUrl(e,r){this.assertOpen();let s=r?.expiresInSeconds,i=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,n=`${Os}?key=${encodeURIComponent(e)}${i}${ht(r?.bucket)}`,o=await this.adminFetch(n,"GET");if(typeof o.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return o.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(_s,"GET")}async readGlobalTablePage(e){this.assertOpen();let r=new URLSearchParams({table:e.table});return e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&r.set("filters",JSON.stringify(e.filters)),await this.adminFetch(`${Ls}?${r.toString()}`,"GET")}async facetGlobalColumn(e){this.assertOpen();let r=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&r.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&r.set("filters",JSON.stringify(e.filters)),await this.adminFetch(`${Qs}?${r.toString()}`,"GET")}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch(Ds,"GET")).indexes??[]}async queryVectorIndex(e){return this.assertOpen(),(await this.adminFetch(Us,"POST",e)).matches??[]}async queryLogArchive(e={}){this.assertOpen();let r=await this.adminFetch(qs,"POST",e);return{nextCursor:r.nextCursor,rows:r.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(Ns,"GET")).namespaces??[]}async listKvKeys(e){this.assertOpen();let r=T(Ks,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await this.adminFetch(r,"GET")}async getKvValue(e){this.assertOpen();let r=T(lt,{key:e.key,namespace:e.namespace});return await this.adminFetch(r,"GET")}async putKvValue(e){this.assertOpen(),await this.adminFetch(lt,"PUT",e)}async deleteKvKey(e){this.assertOpen();let r=T(lt,{key:e.key,namespace:e.namespace});await this.adminFetch(r,"DELETE")}async listAuthUsers(e={}){this.assertOpen();let r=T(Bs,{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($s,"POST",e)}async setAuthUserRole(e){return await this.adminFetch(Hs,"POST",e)}async banAuthUser(e){return await this.adminFetch(zs,"POST",e)}async unbanAuthUser(e){return await this.adminFetch(Ws,"POST",e)}async setAuthUserPassword(e){await this.adminFetch(Vs,"POST",e)}async removeAuthUser(e){await this.adminFetch(Gs,"POST",e)}async impersonateAuthUser(e){return await this.adminFetch(Js,"POST",e)}async revokeAuthSession(e){await this.adminFetch(Xs,"POST",e)}async revokeAuthUserSessions(e){await this.adminFetch(Ys,"POST",e)}async getAuthCapabilities(){return await this.adminFetch(Zs,"GET")}async updateAuthUser(e){return await this.adminFetch(ei,"POST",e)}async listAuthAccounts(e){return await this.adminFetch(T(ti,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){await this.adminFetch(ri,"POST",e)}async listAuthPasskeys(e){return await this.adminFetch(T(si,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){await this.adminFetch(ii,"POST",e)}async disableAuthTwoFactor(e){await this.adminFetch(ni,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(T(ai,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){let r=T(oi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async listAuthOrgInvitations(e){let r=T(ci,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async removeAuthOrgMember(e){await this.adminFetch(ui,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(hi,"POST",e)}async getAuthConfig(){return await this.adminFetch(di,"GET")}async createAuthOrganization(e){return await this.adminFetch(li,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(fi,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(pi,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch(mi,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(yi,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch(bi,"POST",e)}async listAuthOrgTeams(e){let r=T(gi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(vi,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch(Si,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(wi,"POST",e)}async listAuthOrgTeamMembers(e){let r=T(Ci,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(r,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(ki,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(Ii,"POST",e)}async listAuthOrgRoles(e){let r=T(Ei,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async createAuthOrgRole(e){return await this.adminFetch(Ti,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(Oi,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(Ri,"POST",e)}async listAuthSessions(e={}){this.assertOpen();let r=T(js,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(r,"GET")}subscribe(e,r,s,i={}){this.assertOpen();let n=r??{},o=_.key(e.__lunoraRef,n,i.shardKey),c=this.subscriptions.get(o),u=s,h=i.onError;if(!c){this.nextSubId+=1;let l=`sub_${this.nextSubId.toString()}`,f=B(n),m=this.takeHydratedCache(e.__lunoraRef,f,i.shardKey);c={acked:!1,args:n,argsKey:f,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:l,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),h&&c.errorCallbacks.add(h),i.onCheckpoint&&c.checkpointCallbacks.add(i.onCheckpoint),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let d=c;return()=>{d.callbacks.delete(u),h&&d.errorCallbacks.delete(h),i.onCheckpoint&&d.checkpointCallbacks.delete(i.onCheckpoint),d.callbacks.size===0&&(this.sendOrQueueUnsubscribe(d.shardKey,d.id,"unsubscribe"),this.subscriptions.remove(d))}}subscribeShape(e,r,s={}){this.assertOpen(),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:G(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,n),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(n.shardKey,i,"shape_unsubscribe")}}stream(e,r,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new p("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;let i=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=s,o=r??{},{handle:c,iterable:u}=Fe({maxBuffer:s.maxBuffer,onCancel:a(()=>{let l=this.getConnection(n);l&&F(l,{id:i,type:"unsubscribe"}),this.streams.delete(i)},"onCancel")});this.ensureSocket(n);let h=this.getConnection(n),d={id:i,query:{args:G(o,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"};if(this.streams.set(i,{durable:s.durable===!0,generation:void 0,handle:c,lastSeq:0,message:d,shardKey:n}),!(h?.wsState==="open"&&F(h,d))&&h){for(h.pendingStreams=h.pendingStreams??[];h.pendingStreams.length>=ms;){let l=h.pendingStreams.shift()?.id,f=l?this.streams.get(l):void 0;f&&(f.handle.fail(new p("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(l))}h.pendingStreams.push(d)}return u}httpStream(e,r,s={}){if(this.closed)throw new p("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return ar(e,r,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(let e of this.streams.values())e.handle.fail(new p("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}assertOpen(){if(this.closed)throw new p("INTERNAL","LunoraClient is closed")}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 Ae({channelName:e,onBecomeLeader:a(()=>{for(let r of this.subscriptions.all())this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(r);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},"onBecomeLeader"),onStopBeingLeader:a(()=>{for(let[r,s]of this.connections)this.teardownConnection(s),this.connections.delete(r);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},"onStopBeingLeader"),onConnectionStatus:a((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:a((r,s,i,n,o)=>{if(o!==void 0&&o!==this.identityFingerprint())return;let c=this.subscriptions.get(r);c&&(c.serverBase=s,i!==void 0&&(c.serverCursor=i,n!==void 0&&(c.serverEpoch=n),Me(c,i)),te(c,he(s,c.optimisticLayers)))},"onSubscriptionData"),onSubscriptionError:a((r,s)=>{let i=this.subscriptions.get(r);i&&Qe(i.errorCallbacks,s)},"onSubscriptionError"),onSubscriptionSettled:a((r,s,i,n,o,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&&o===this.clientId&&(u.lastMutationId=Math.max(u.lastMutationId??0,n));for(let h of u.checkpointCallbacks)h({checkpoint:u.serverCursor,mutationId:u.lastMutationId})}},"onSubscriptionSettled")})}async enqueueOfflineMutation(e,r,s,i,n,o,c){let u=this.identityFingerprint();if(this.outbox){this.outboxMutationCounter+=1;let h=this.outboxMutationCounter;try{await this.outbox.enqueue({args:r,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:`${this.clientId}:${String(h)}`,identity:u,mutationId:h,shardKey:s})}catch(d){throw Le(n),d instanceof Error?d:new Error(String(d))}for(let d of o)d(void 0);return}return new Promise((h,d)=>{let l={args:r,functionPath:e.__lunoraRef,liveAwaiter:!0,id:i,clientId:this.clientId,identity:u,precondition:c,onCommit:a(f=>{for(let m of o)m(f)},"onCommit"),reject:a(f=>{this.queuedIdentities.delete(i),Le(n),d(f instanceof Error?f:new Error(String(f)))},"reject"),resolve:h,shardKey:s};this.offlineQueue.enqueue(l),this.queuedOfflineShardKeys.add(s),l.id!==void 0&&this.queuedIdentities.set(l.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=a(()=>{this.hydratePersistedQueue().catch(()=>{})},"e"),r=globalThis.navigator?.locks;if(!r){e();return}r.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{let e=await this.queryCache.load();for(let{key:r,...s}of e){if(ot(this.persistenceVersion,s.version)){this.queryCache.remove(r).catch(()=>{});continue}this.hydratedQueryCache.set(r,s)}}catch{}}takeHydratedCache(e,r,s){let i=Re(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=Re(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(()=>{})},ps)}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;let{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}let r=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(r.map(async([s,i])=>e.put(s,i)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";let e=[...this.connections.values()];return e.length===0?"idle":e.some(r=>r.wsState==="open")?"connected":e.some(r=>r.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=[],o=[];if(!i)return{confirms:n,rollbacks:o};let c=_.key(e,r,s),u=this.subscriptions.get(c);if(u){let h=at(u,i);h&&(n.push(h.confirm),o.push(h.rollback))}return{confirms:n,rollbacks:o}}applyOptimisticUpdate(e,r,s,i,n){let{confirms:o,rollbacks:c,store:u}=or(this.subscriptions,s);try{e(u,r)}catch{Le(c);return}i.push(...c),n.push(...o)}getConnection(e){return this.connections.get(C(e))}sendOrQueueUnsubscribe(e,r,s){let i=this.getConnection(e);i&&!F(i,{id:r,type:s})&&i.pendingUnsubscribes.push({id:r,type:s})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let s="idle";return this.leaderStatus==="connected"?s="open":this.leaderStatus==="connecting"&&(s="connecting"),{hasSocket:!1,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:ct(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,r){let s={"content-type":"application/json"},i=this.shardCursors.get(this.cursorKeyFor(r));if(i!==void 0&&(s["x-lunora-min-seq"]=i.toString()),this.authToken&&(s.authorization=`Bearer ${this.authToken}`),e.mutationId&&(s["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(s["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(s["x-lunora-client-seq"]=e.clientSeq.toString()),e.attachBookmark){let n=this.bookmark.get();n&&(s["x-d1-bookmark"]=n)}return s}async rpc(e,r,s,i={}){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");let n=this.rpcRequestHeaders(i,s),o=await this.fetchImpl(V(this.url,cs),{body:JSON.stringify({args:G(r,`args for '${e}'`),functionPath:e,shardKey:s}),headers:n,method:"POST"});if(i.captureBookmark){let u=o.headers.get("x-d1-bookmark");u&&this.bookmark.set(u)}let c;try{c=await o.json()}catch{let u=o.statusText?` ${o.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${o.status.toString()}${u})`)}if("error"in c)throw de(c.error);if(!o.ok){let u=o.statusText?` ${o.statusText}`:"";throw new p("INTERNAL",`LunoraClient: request failed (status ${o.status.toString()}${u})`)}return i.onMutationAck?.(c.lastMutationId),i.onCommitCursor?.(c.commitCursor),this.learnDefaultShardKey(o,s),this.recordShardCursor(s,c.commitCursor),S(c.result)}async adminFetch(e,r,s,i){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");let n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);let o=s instanceof ArrayBuffer||s instanceof Blob,c;s===void 0?c=void 0:o?(c=s,i!==void 0&&(n["content-type"]=i)):(c=JSON.stringify(s),n["content-type"]="application/json");let u=await this.fetchImpl(V(this.url,e),{body:c,headers:n,method:r}),h;try{h=await u.json()}catch{let d=u.statusText?` ${u.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${d})`)}if(typeof h=="object"&&h!==null&&"error"in h){let d=h.error,l=new Error(d.message??"admin request failed");throw l.code=d.code,l}if(!u.ok){let d=u.statusText?` ${u.statusText}`:"";throw new p("INTERNAL",`LunoraClient: admin request failed (status ${u.status.toString()}${d})`)}return h}effectiveConnectionContext(e){let r=this.connectionContextHolders.get(e);return r&&r.length>0?r[r.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){let r=this.connections.get(e);r?.wsState==="open"&&this.sendConnectEnvelope(r)}sendConnectEnvelope(e){let r=this.effectiveConnectionContext(C(e.shardKey));F(e,{caps:Fi,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 p("INTERNAL","no WebSocket implementation available");let o=new n(r);e.socket=o;let c=a(()=>{this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket===o&&(e.socket=void 0)},"a"),u=a(h=>{c(),i.onClose(h)},"o");s>0&&(e.connectTimer=setTimeout(()=>{if(e.connectTimer=void 0,e.socket===o){try{o.close()}catch{}u()}},s)),o.addEventListener("open",()=>{e.socket===o&&(e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.lastFrameAt=Date.now(),i.onOpen(),this.startHeartbeat(e,u))}),o.addEventListener("message",h=>{e.socket===o&&(e.lastFrameAt=Date.now(),i.onMessage(h))}),o.addEventListener("close",h=>{e.socket===o&&u(h)}),o.addEventListener("error",()=>{e.socket===o&&u()})}openSocket(e,r,s){this.WebSocketImpl!==void 0&&this.openManagedSocket(e,this.wsUrlFor(r,s),this.connectTimeoutMs,{onClose:a(i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},"onClose"),onMessage:a(i=>{this.handleServerMessage(i.data,r)},"onMessage"),onOpen:a(()=>{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:o,type:c}of n)F(e,{id:o,type:c})}if(e.pendingStreams&&e.pendingStreams.length>0){let n=e.pendingStreams;e.pendingStreams=[];for(let o of n)F(e,o)}let i=this.whisperHandlers.get(C(r));if(i)for(let n of i.keys())F(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)if(!(C(n.shardKey)!==C(e.shardKey)||r.has(i))){if(n.durable){let o={...n.message,...n.generation===void 0?{}:{generation:n.generation},sinceChunk:n.lastSeq};n.message=o,e.pendingStreams=[...(e.pendingStreams??[]).filter(c=>c.id!==i),o];continue}n.handle.fail(new p("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(ds)}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;F(r,{id:e.id,query:{args:O(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"&&F(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=_i(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,generation:o,id:c,seq:u}=i,h=this.streams.get(c);h&&typeof u=="number"&&(h.lastSeq=u,typeof o=="number"&&(h.generation=o),h.durable=!0),h?.handle.push(S(n));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"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(Mi(e)),this.streams.delete(r);return}let i=r===void 0?void 0:this.subscriptions.getById(r);if(i){Qe(i.errorCallbacks,pr(e));return}let n=r===void 0?void 0:this.shapeSubscriptions.get(r);n&&Qe(n.errorCallbacks,pr(e))}handlePokeStart(e){os(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:S(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 o=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(o||c){n.rows.clear(),n.serverCursor=void 0,n.serverEpoch=void 0,this.emitShapeRows(n),this.sendShapeSubscribeIfOpen(n);continue}hs(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),Me(s,s.serverCursor),te(s,he(i,s.optimisticLayers)),this.tabCoordinator?.isLeader()){let n=_.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=_.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),Me(e,e.serverCursor)&&te(e,he(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,r){if("data"in e&&e.data!==void 0)return S(e.data);let s=S(e.delta);if(rr(s)&&r.serverBase!==void 0){let i=sr(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=S(e.data);for(let n of s)try{n(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){let r=this.streams.get(e);if(r){r.handle.complete(),this.streams.delete(e);return}let s=this.subscriptions.getById(e);s&&(s.acked=!1,Qe(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(r=>{re(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)}restampWatermarks(e,r){let s=e??"",i=this.clientWatermarks.get(s);if(i===void 0)return;this.clientWatermarks.delete(s);let n=r??"",o=this.clientWatermarks.get(n);if(o===void 0)this.clientWatermarks.set(n,i);else for(let[c,u]of i)o.set(c,u)}clearQueryCacheForIdentityChange(){this.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 h of r){this.unpersist(h.id),this.queuedIdentities.delete(h.id??"");let d=new Error("offline mutation skipped: precondition failed before replay");d.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(h,"rejected",d)}let s=C(e),i=this.offlineQueue.drain(h=>C(h.shardKey)===s);if(i.length===0)return;let n=this.identityFingerprint(),o=[];for(let h of i)this.passesReplayIdentityGate(h,n)&&o.push(h);if(o.length===0)return;let c=this.encodableOrSettleTerminal(o);if(c.length===0)return;if(c.length===1){await this.replaySequential(c);return}let u=[];for(let h=0;h<c.length;h+=ut){let d=c.slice(h,h+ut),l=await this.replayBatched(d);if(u.push(...l.requeue),l.stop){u.push(...c.slice(h+ut));break}}u.length>0&&this.offlineQueue.requeue(u)}encodableOrSettleTerminal(e){let r=[];for(let s of e)try{G(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),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.resolve(r),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,r){let s=e.headers.get("x-lunora-shard-key");if(s===null||r!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;let i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,i)),this.shardCursors.delete(""))}recordShardCursor(e,r){if(typeof r!="number")return;let s=this.cursorKeyFor(e);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,r))}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,clientId:s.clientId??this.clientId,mutationId:s.id,onCommitCursor:a(o=>{i=o},"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(V(this.url,lr),{body:JSON.stringify({calls:e.map((n,o)=>({args:G(n.args,`args for '${n.functionPath}'`),functionPath:n.functionPath,id:o,clientId:n.clientId??this.clientId,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 o of e)this.settleReplayTerminal(o,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,o]of e.entries()){let c=s.get(n);c===void 0?i.push(o):"error"in c?Qi.has(c.error.code)?i.push(o):this.settleReplayTerminal(o,de(c.error)):this.settleReplaySuccess(o,S(c.result),c.commitCursor)}return i}};var yr=P(mt(),1),br=P(H(),1);var Ui=a(()=>{let t=(0,yr.c)(4),e=Ye(),r,s,i;return t[0]!==e?(r=a(n=>e.onConnectionStatus(()=>{n()}),"o"),s=a(()=>e.connectionStatus(),"e"),i=a(()=>e.connectionStatus(),"c"),t[0]=e,t[1]=r,t[2]=s,t[3]=i):(r=t[1],s=t[2],i=t[3]),(0,br.useSyncExternalStore)(r,s,i)},"S");export{ft as a,Cr as b,Ve as c,xr as d,Lr as e,Ye as f,Ui as g};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as Qe}from"./chunk-UBT2FIU5.js";import{a as Me,b as Re}from"./chunk-7SROZWKL.js";import"./chunk-FJ6G6FNE.js";import"./chunk-CP4ZFBVW.js";import"./chunk-CN2AINNY.js";import{a as we}from"./chunk-NXXGISFB.js";import"./chunk-EDHW2EEG.js";import"./chunk-ZSOLGJFC.js";import"./chunk-DUDQV6XJ.js";import"./chunk-VZCS5GXZ.js";import"./chunk-DKSLOJDQ.js";import"./chunk-JV7KTJPY.js";import{a as He}from"./chunk-CKTKI4IY.js";import{a as Xe}from"./chunk-6UN4V2HB.js";import{b as Je}from"./chunk-KVSQKUWD.js";import{e as Ue}from"./chunk-4YTSKL4R.js";import"./chunk-ZHPDAJBM.js";import{P as Ae}from"./chunk-AOAJGSYZ.js";import"./chunk-INQICZYC.js";import"./chunk-TFMQSCGC.js";import{a as me}from"./chunk-BWEXJENB.js";import"./chunk-74ASA4WU.js";import"./chunk-XQS7KSHL.js";import{b as ze}from"./chunk-SPDZUX4P.js";import"./chunk-7PIHTTND.js";import{a as je}from"./chunk-DZGOHOOE.js";import{f as Ve}from"./chunk-YTYRZTG6.js";import"./chunk-RCZTUWG3.js";import{a as We}from"./chunk-UANVABQG.js";import{a as qe,b as Pe,c as Ge,d as Ke,e as Le}from"./chunk-IYWVSMAY.js";import{d as Fe,f as Ee,g as $e,h as Oe,o as ue}from"./chunk-BKM6PMSO.js";import"./chunk-VYW2PAWC.js";import{a as r,d as Be,e as at,f as nt,g as st,i as De}from"./chunk-R5ZTCHCE.js";var Ce=Be(nt(),1);var x=Be(at(),1);var t=Be(st(),1);var rt=Ee(je.listTables),ot=Ee(je.listTableIndexes),it=Ee(je.readTablePage),dt=Ee(je.describeTables),ct={},Ye=[],mt=r(s=>{let e=(0,Ce.c)(74),{initialShardKey:u,initialTable:n}=s,l=Ve(),[a,m]=(0,x.useState)("graph"),{queryShardKey:c,setShardKey:d,shardKey:g}=He(u),[o,p]=(0,x.useState)(""),[i,v]=(0,x.useState)(null),[b,P]=(0,x.useState)(null),_;e[0]===Symbol.for("react.memo_cache_sentinel")?(_={},e[0]=_):_=e[0];let[L,y]=(0,x.useState)(_),G;e[1]===Symbol.for("react.memo_cache_sentinel")?(G={},e[1]=G):G=e[1];let[E,M]=(0,x.useState)(G),[S,C]=(0,x.useState)(null),F;e[2]===Symbol.for("react.memo_cache_sentinel")?(F={},e[2]=F):F=e[2];let[$,he]=(0,x.useState)(F),Q;e[3]===Symbol.for("react.memo_cache_sentinel")?(Q={},e[3]=Q):Q=e[3];let[I,K]=(0,x.useState)(Q),[k,pe]=(0,x.useState)(null),[B,oe]=(0,x.useState)(null),Y;e[4]===Symbol.for("react.memo_cache_sentinel")?(Y={},e[4]=Y):Y=e[4];let[W,xe]=(0,x.useState)(Y),[J,ie]=(0,x.useState)(null),ve;e[5]!==l?(ve=r(async h=>{P(null);try{let w=await l.query(rt,{},$e(h));Je(h),v(w),y({}),M({}),C(null),he(N=>Object.fromEntries(Object.entries(N).filter(q=>{let[A]=q;return A!==h}))),K(N=>Object.fromEntries(Object.entries(N).filter(q=>{let[A]=q;return A!==h})))}catch(w){let N=w;v(null),P(Oe(N))}},"ve"),e[5]=l,e[6]=ve):ve=e[6];let O=ve,Z;e[7]!==l?(Z=r(async()=>{oe(null);try{pe(await l.listGlobalTables())}catch(h){let w=h;pe(null),oe(Oe(w))}},"Z"),e[7]=l,e[8]=Z):Z=e[8];let ee=Z,de,D;e[9]!==c||e[10]!==O||e[11]!==ee?(de=r(()=>{ue(O(c)),ue(ee())},"de"),D=[O,ee,c],e[9]=c,e[10]=O,e[11]=ee,e[12]=de,e[13]=D):(de=e[12],D=e[13]),(0,x.useEffect)(de,D);let te;e[14]!==l||e[15]!==L||e[16]!==S||e[17]!==c?(te=r(async h=>{if(S===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},$e(c)),l.query(ot,{table:h},$e(c))]);N.status==="fulfilled"?y(A=>({...A,[w]:N.value.columns})):P(Oe(N.reason)),q.status==="fulfilled"&&M(A=>({...A,[w]:q.value.indexes}))},"te"),e[14]=l,e[15]=L,e[16]=S,e[17]=c,e[18]=te):te=e[18];let j=te,ye;e[19]!==l||e[20]!==W||e[21]!==J?(ye=r(async h=>{if(J===h){ie(null);return}if(ie(h),W[h]===void 0)try{let w=await l.readGlobalTablePage({limit:1,offset:0,table:h});xe(N=>({...N,[h]:w.columns}))}catch(w){oe(Oe(w))}},"ye"),e[19]=l,e[20]=W,e[21]=J,e[22]=ye):ye=e[22];let ce=ye,be=(0,x.useRef)(void 0),R,X;e[23]!==n||e[24]!==i||e[25]!==j?(R=r(()=>{n===void 0||i===null||be.current===n||i.some(h=>h.name===n)&&(be.current=n,ue(j(n)))},"K"),X=[n,i,j],e[23]=n,e[24]=i,e[25]=j,e[26]=R,e[27]=X):(R=e[26],X=e[27]),(0,x.useEffect)(R,X);let V;e[28]!==l?(V=r(async(h,w,N)=>{let[q,A]=await Promise.all([Promise.allSettled([l.query(dt,{tables:[...w,...N]},$e(h))]),Promise.all(N.map(async T=>{let ge=await Promise.allSettled([l.readGlobalTablePage({limit:1,offset:0,table:T})]),Ie=ge[0].status==="fulfilled"?ge[0].value:void 0;return{columns:Ie?.columns??[],refs:Ie?.refs??{},table:T}}))]),Te=q[0].status==="fulfilled"?q[0].value?.columnsByTable??{}:{},Se=q[0].status==="rejected",_e=new Map(A.map(ut)),ke=[...w,...N].map(T=>{let ge=Te[T]??[];return[T,ge.length>0?ge:_e.get(T)??[]]});he(T=>({...T,[h]:Object.fromEntries(ke)})),K(T=>({...T,[h]:Se}))},"U"),e[28]=l,e[29]=V):V=e[29];let le=V,U,ae;e[30]!==B||e[31]!==k||e[32]!==le||e[33]!==c||e[34]!==$||e[35]!==i||e[36]!==a?(U=r(()=>{a!=="graph"||i===null||k===null&&B===null||$[c]!==void 0||ue(le(c,i.map(ht),(k??[]).map(pt)))},"V"),ae=[a,i,k,B,c,$,le],e[30]=B,e[31]=k,e[32]=le,e[33]=c,e[34]=$,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=$[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]??Ye,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]??Ye,name:A.name,tier:"global"}),"x"),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,H;if(e[50]!==k||e[51]!==o){let h=o.trim().toLowerCase();H=(k??[]).filter(w=>w.name.toLowerCase().includes(h)),e[50]=k,e[51]=o,e[52]=H}else H=e[52];let Ne=H,fe;return e[53]!==L||e[54]!==se||e[55]!==b||e[56]!==S||e[57]!==Ne||e[58]!==re||e[59]!==W||e[60]!==B||e[61]!==J||e[62]!==k||e[63]!==E||e[64]!==O||e[65]!==d||e[66]!==I||e[67]!==g||e[68]!==o||e[69]!==i||e[70]!==j||e[71]!==ce||e[72]!==a?(fe={columns:L,diagramTables:se,error:b,expanded:S,filteredGlobalTables:Ne,filteredTables:re,globalColumns:W,globalError:B,globalExpanded:J,globalTables:k,indexes:E,refresh:O,setShardKey:d,setTableFilter:p,setView:m,shardColumnsError:I,shardKey:g,tableFilter:o,tables:i,toggle:j,toggleGlobal:ce,view:a},e[53]=L,e[54]=se,e[55]=b,e[56]=S,e[57]=Ne,e[58]=re,e[59]=W,e[60]=B,e[61]=J,e[62]=k,e[63]=E,e[64]=O,e[65]=d,e[66]=I,e[67]=g,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,"ft");var bt="/__lunora/schema-edit",ft=r(async s=>{let e=await fetch(bt,{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)})`}},"pt"),gt=r(s=>{let e=(0,Ce.c)(32),{hasTables:u,mode:n,onAddColumn:l,onAddIndex:a,onAddTable:m,onDestructive:c}=s,d=Fe(),g=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]!==g||e[4]!==o?(p=(0,t.jsx)(me,{"data-testid":"sc-editor-add-table",onClick:m,size:"xs",type:"button",variant:g,children:o}),e[2]=m,e[3]=g,e[4]=o,e[5]=p):p=e[5];let i=!u,v=n==="addColumn"?"default":"outline",b;e[6]!==d?(b=d("Add column"),e[6]=d,e[7]=b):b=e[7];let P;e[8]!==l||e[9]!==i||e[10]!==v||e[11]!==b?(P=(0,t.jsx)(me,{"data-testid":"sc-editor-add-column",disabled:i,onClick:l,size:"xs",type:"button",variant:v,children:b}),e[8]=l,e[9]=i,e[10]=v,e[11]=b,e[12]=P):P=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 G;e[15]!==a||e[16]!==y||e[17]!==_||e[18]!==L?(G=(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]=G):G=e[19];let E=!u,M=n==="destructive"?"default":"ghost",S;e[20]!==d?(S=d("Rename / drop / change type\u2026"),e[20]=d,e[21]=S):S=e[21];let C;e[22]!==c||e[23]!==E||e[24]!==M||e[25]!==S?(C=(0,t.jsx)(me,{"data-testid":"sc-editor-destructive",disabled:E,onClick:c,size:"xs",type:"button",variant:M,children:S}),e[22]=c,e[23]=E,e[24]=M,e[25]=S,e[26]=C):C=e[26];let F;return e[27]!==G||e[28]!==C||e[29]!==p||e[30]!==P?(F=(0,t.jsxs)("div",{className:"flex flex-wrap gap-2",children:[p,P,G,C]}),e[27]=G,e[28]=C,e[29]=p,e[30]=P,e[31]=F):F=e[31],F},"gt"),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 b;return e[13]!==p||e[14]!==v?(b=(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]=b):b=e[15],b}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 g;return e[25]!==m||e[26]!==d?(g=(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]=g):g=e[27],g},"bt");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!==""),"Ct"),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,g]=(0,x.useState)(!1),[o,p]=(0,x.useState)(null),[i,v]=(0,x.useState)(""),[b,P]=(0,x.useState)(""),[_,L]=(0,x.useState)(Nt),[y,G]=(0,x.useState)(n[0]??""),[E,M]=(0,x.useState)(""),[S,C]=(0,x.useState)(""),[F,$]=(0,x.useState)(!1),he;e[0]===Symbol.for("react.memo_cache_sentinel")?(he=r(()=>{c(null),v(""),P(""),M(""),C(""),$(!1)},"me"),e[0]=he):he=e[0];let Q=he,I;e[1]!==u?(I=r(async T=>{g(!0),p(null);try{let ge=await ft(T);p(ge),ge.kind==="ok"&&(u(ge.tables),Q())}catch(ge){let Ie=ge;p({kind:"error",message:Ie instanceof Error?Ie.message:String(Ie)})}g(!1)},"I"),e[1]=u,e[2]=I):I=e[2];let K=I,k;e[3]!==K||e[4]!==i?(k=r(()=>{ue(K({kind:"addTable",table:i.trim()}))},"_"),e[3]=K,e[4]=i,e[5]=k):k=e[5];let pe=k,B;e[6]!==b||e[7]!==K||e[8]!==y||e[9]!==_?(B=r(()=>{ue(K({column:b.trim(),kind:"addOptionalColumn",table:y,validator:_}))},"j"),e[6]=b,e[7]=K,e[8]=y,e[9]=_,e[10]=B):B=e[10];let oe=B,Y;e[11]!==S||e[12]!==E||e[13]!==K||e[14]!==y||e[15]!==F?(Y=r(()=>{ue(K({fields:Ct(S),kind:"addIndex",name:E.trim(),table:y,unique:F}))},"Q"),e[11]=S,e[12]=E,e[13]=K,e[14]=y,e[15]=F,e[16]=Y):Y=e[16];let W=Y,xe;e[17]===Symbol.for("react.memo_cache_sentinel")?(xe=r(()=>{p(null),c("addTable")},"xe"),e[17]=xe):xe=e[17];let J=xe,ie;e[18]===Symbol.for("react.memo_cache_sentinel")?(ie=r(()=>{p(null),c("addColumn")},"re"),e[18]=ie):ie=e[18];let ve=ie,O;e[19]===Symbol.for("react.memo_cache_sentinel")?(O=r(()=>{p(null),c("addIndex")},"O"),e[19]=O):O=e[19];let Z=O,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,D;e[22]===Symbol.for("react.memo_cache_sentinel")?(D=r(T=>{v(T.target.value)},"R"),e[22]=D):D=e[22];let te=D,j;e[23]===Symbol.for("react.memo_cache_sentinel")?(j=r(T=>{P(T.target.value)},"M"),e[23]=j):j=e[23];let ye=j,ce;e[24]===Symbol.for("react.memo_cache_sentinel")?(ce=r(T=>{L(T.target.value)},"ce"),e[24]=ce):ce=e[24];let be=ce,R;e[25]===Symbol.for("react.memo_cache_sentinel")?(R=r(T=>{G(T.target.value)},"K"),e[25]=R):R=e[25];let X=R,V;e[26]===Symbol.for("react.memo_cache_sentinel")?(V=r(T=>{M(T.target.value)},"U"),e[26]=V):V=e[26];let le=V,U;e[27]===Symbol.for("react.memo_cache_sentinel")?(U=r(T=>{C(T.target.value)},"V"),e[27]=U):U=e[27];let ae=U,z;e[28]===Symbol.for("react.memo_cache_sentinel")?(z=r(T=>{$(T.target.checked)},"$"),e[28]=z):z=e[28];let ne=z,se;e[29]!==a?(se=r(()=>{ue(a({to:"/migrations"}))},"ne"),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 H;e[33]!==re?(H=(0,t.jsx)(Ge,{children:re}),e[33]=re,e[34]=H):H=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)(Ke,{children:Ne}),e[37]=Ne,e[38]=fe):fe=e[38];let h;e[39]!==H||e[40]!==fe?(h=(0,t.jsxs)(Pe,{children:[H,fe]}),e[39]=H,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)(gt,{hasTables:w,mode:m,onAddColumn:ve,onAddIndex:Z,onAddTable:J,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:Q,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]!==b||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(Tt)})]}),(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:b})]}),(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:be,value:_,children:yt.map(St)})]}),(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||b.trim()===""||y==="",onClick:oe,size:"xs",type:"button",children:l(d?"Applying\u2026":"Apply")}),(0,t.jsx)(me,{onClick:Q,size:"xs",type:"button",variant:"ghost",children:l("Cancel")})]}),e[52]=d,e[53]=b,e[54]=m,e[55]=oe,e[56]=l,e[57]=n,e[58]=y,e[59]=_,e[60]=A):A=e[60];let Te;e[61]!==d||e[62]!==S||e[63]!==E||e[64]!==m||e[65]!==W||e[66]!==l||e[67]!==n||e[68]!==y||e[69]!==F?(Te=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:S})]}),(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()===""||S.trim()==="",onClick:W,size:"xs",type:"button",children:l(d?"Applying\u2026":"Apply")}),(0,t.jsx)(me,{onClick:Q,size:"xs",type:"button",variant:"ghost",children:l("Cancel")})]}),e[61]=d,e[62]=S,e[63]=E,e[64]=m,e[65]=W,e[66]=l,e[67]=n,e[68]=y,e[69]=F,e[70]=Te):Te=e[70];let Se;e[71]!==f||e[72]!==o?(Se=(0,t.jsx)(xt,{onOpenMigrations:f,result:o}),e[71]=f,e[72]=o,e[73]=Se):Se=e[73];let _e;e[74]!==N||e[75]!==q||e[76]!==A||e[77]!==Te||e[78]!==Se?(_e=(0,t.jsxs)(Le,{children:[N,q,A,Te,Se]}),e[74]=N,e[75]=q,e[76]=A,e[77]=Te,e[78]=Se,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},"Nt");function Tt(s){return(0,t.jsx)("option",{value:s,children:s},s)}r(Tt,"Tt");function St(s){return(0,t.jsx)("option",{value:s.validator,children:s.label},s.validator)}r(St,"St");function _t(s){return(0,t.jsx)("option",{value:s,children:s},s)}r(_t,"wt");var Ze=[],kt=r(s=>{let e=(0,Ce.c)(5),{open:u}=s,n=u&&"rotate-90",l;e[0]!==n?(l=De("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,g;e[0]!==n?(g=(0,t.jsx)(kt,{open:n}),e[0]=n,e[1]=g):g=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]!==g||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:[g,o," ",p]}),e[6]=n,e[7]=a,e[8]=g,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 b;return e[16]!==c||e[17]!==i||e[18]!==v?(b=(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]=b):b=e[19],b},"Ye"),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},"He"),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},"Et"),lt=r(s=>De("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"),"Xe"),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:g,expanded:o,filteredGlobalTables:p,filteredTables:i,globalColumns:v,globalError:b,globalExpanded:P,globalTables:_,indexes:L,refresh:y,setShardKey:G,setTableFilter:E,setView:M,shardColumnsError:S,shardKey:C,tableFilter:F,tables:$,toggle:he,toggleGlobal:Q,view:I}=mt(m),K;e[3]!==M?(K=r(()=>{M("list")},"q"),e[3]=M,e[4]=K):K=e[4];let k=K,pe;e[5]!==M?(pe=r(()=>{M("graph")},"ue"),e[5]=M,e[6]=pe):pe=e[6];let B=pe,oe;e[7]!==E?(oe=r(f=>{E(f.target.value)},"ie"),e[7]=E,e[8]=oe):oe=e[8];let Y=oe,W;e[9]!==y||e[10]!==C?(W=r(f=>{ue(y(C))},"Y"),e[9]=y,e[10]=C,e[11]=W):W=e[11];let xe=W,J;e[12]!==$?(J=$??[],e[12]=$,e[13]=J):J=e[13];let ie;e[14]!==J?(ie=J.map(zt),e[14]=J,e[15]=ie):ie=e[15];let ve=ie,O;e[16]!==G||e[17]!==C?(O=(0,t.jsx)(Xe,{onChange:G,testId:"sc-shard-input",value:C}),e[16]=G,e[17]=C,e[18]=O):O=e[18];let Z;e[19]!==a?(Z=a("Schema view"),e[19]=a,e[20]=Z):Z=e[20];let ee=I==="graph",de=I==="graph",D;e[21]!==de?(D=lt(de),e[21]=de,e[22]=D):D=e[22];let te;e[23]!==a?(te=a("Graph"),e[23]=a,e[24]=te):te=e[24];let j;e[25]!==B||e[26]!==ee||e[27]!==D||e[28]!==te?(j=(0,t.jsx)("button",{"aria-selected":ee,className:D,"data-testid":"sc-view-graph",onClick:B,role:"tab",type:"button",children:te}),e[25]=B,e[26]=ee,e[27]=D,e[28]=te,e[29]=j):j=e[29];let ye=I==="list",ce=I==="list",be;e[30]!==ce?(be=lt(ce),e[30]=ce,e[31]=be):be=e[31];let R;e[32]!==a?(R=a("Table list"),e[32]=a,e[33]=R):R=e[33];let X;e[34]!==k||e[35]!==ye||e[36]!==be||e[37]!==R?(X=(0,t.jsx)("button",{"aria-selected":ye,className:be,"data-testid":"sc-view-list",onClick:k,role:"tab",type:"button",children:R}),e[34]=k,e[35]=ye,e[36]=be,e[37]=R,e[38]=X):X=e[38];let V;e[39]!==j||e[40]!==X||e[41]!==Z?(V=(0,t.jsxs)("div",{"aria-label":Z,className:"flex items-center gap-1","data-testid":"sc-view-toggle",role:"tablist",children:[j,X]}),e[39]=j,e[40]=X,e[41]=Z,e[42]=V):V=e[42];let le;e[43]!==V||e[44]!==O?(le=(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[O,V]}),e[43]=V,e[44]=O,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]!==Y||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:Y,placeholder:a("Filter tables"),value:F}),e[50]=Y,e[51]=a,e[52]=F,e[53]=I,e[54]=ae):ae=e[54];let z;e[55]!==d||e[56]!==g||e[57]!==b||e[58]!==S||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:[g!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"sc-error",role:"alert",children:g}),b!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"sc-global-error",role:"alert",children:b}),(0,t.jsx)(Qe,{columnsError:S[C]===!0,tables:d,testIdPrefix:"sc-graph"})]}),e[55]=d,e[56]=g,e[57]=b,e[58]=S,e[59]=C,e[60]=I,e[61]=z):z=e[61];let ne;e[62]!==c||e[63]!==g||e[64]!==o||e[65]!==p||e[66]!==i||e[67]!==v||e[68]!==b||e[69]!==P||e[70]!==_||e[71]!==L||e[72]!==C||e[73]!==a||e[74]!==$||e[75]!==he||e[76]!==Q||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)(Pe,{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Re,{tier:"shard"}),(0,t.jsx)(Ge,{children:a("Shard tables")}),$!==null&&(0,t.jsx)(ze,{className:"ms-auto tabular-nums",variant:"outline",children:i.length})]}),(0,t.jsx)(Ke,{children:Me.shard.hint})]}),(0,t.jsxs)(Le,{children:[g!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"sc-error",role:"alert",children:g}),$!==null&&$.length===0&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground","data-testid":"sc-empty",children:a("No tables in this shard.")}),$!==null&&$.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}`,H=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]??Ze,testId:`sc-columns-${f.name}`}),H.length>0&&(0,t.jsx)(It,{heading:a("Indexes"),indexes:H,testId:`sc-indexes-${f.name}`})]},f.name)})})]})]}),(0,t.jsxs)(qe,{"data-testid":"sc-global-section",size:"sm",children:[(0,t.jsxs)(Pe,{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Re,{tier:"global"}),(0,t.jsx)(Ge,{children:a("Global tables (D1)")}),_!==null&&(0,t.jsx)(ze,{className:"ms-auto tabular-nums",variant:"outline",children:p.length})]}),(0,t.jsx)(Ke,{children:Me.global.hint})]}),(0,t.jsxs)(Le,{children:[b!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"sc-global-error",role:"alert",children:b}),_!==null&&_.length===0&&(0,t.jsx)(We,{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:P===f.name,name:f.name,onToggle:r(()=>{ue(Q(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]??Ze,testId:`sc-global-columns-${f.name}`})},f.name))})]})]})]}),e[62]=c,e[63]=g,e[64]=o,e[65]=p,e[66]=i,e[67]=v,e[68]=b,e[69]=P,e[70]=_,e[71]=L,e[72]=C,e[73]=a,e[74]=$,e[75]=he,e[76]=Q,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},"Wt");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,"It");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,"kt");function zt(s){return s.name}r(zt,"At");export{Xt as SchemaViewer};
|
|
1
|
+
import{a as Qe}from"./chunk-UBT2FIU5.js";import{a as Me,b as Re}from"./chunk-7SROZWKL.js";import"./chunk-FJ6G6FNE.js";import"./chunk-CP4ZFBVW.js";import"./chunk-CN2AINNY.js";import{a as we}from"./chunk-NXXGISFB.js";import"./chunk-EDHW2EEG.js";import"./chunk-ZSOLGJFC.js";import"./chunk-DUDQV6XJ.js";import"./chunk-VZCS5GXZ.js";import"./chunk-DKSLOJDQ.js";import"./chunk-JV7KTJPY.js";import{a as He}from"./chunk-CKTKI4IY.js";import{a as Xe}from"./chunk-6UN4V2HB.js";import{b as Je}from"./chunk-KVSQKUWD.js";import{e as Ue}from"./chunk-4YTSKL4R.js";import"./chunk-ZHPDAJBM.js";import{P as Ae}from"./chunk-AOAJGSYZ.js";import"./chunk-INQICZYC.js";import"./chunk-TFMQSCGC.js";import{a as me}from"./chunk-BWEXJENB.js";import"./chunk-74ASA4WU.js";import"./chunk-XQS7KSHL.js";import{b as ze}from"./chunk-SPDZUX4P.js";import"./chunk-7PIHTTND.js";import{a as je}from"./chunk-DZGOHOOE.js";import{f as Ve}from"./chunk-NIUA7EHL.js";import"./chunk-RCZTUWG3.js";import{a as We}from"./chunk-UANVABQG.js";import{a as qe,b as Pe,c as Ge,d as Ke,e as Le}from"./chunk-IYWVSMAY.js";import{d as Fe,f as Ee,g as $e,h as Oe,o as ue}from"./chunk-BKM6PMSO.js";import"./chunk-VYW2PAWC.js";import{a as r,d as Be,e as at,f as nt,g as st,i as De}from"./chunk-R5ZTCHCE.js";var Ce=Be(nt(),1);var x=Be(at(),1);var t=Be(st(),1);var rt=Ee(je.listTables),ot=Ee(je.listTableIndexes),it=Ee(je.readTablePage),dt=Ee(je.describeTables),ct={},Ye=[],mt=r(s=>{let e=(0,Ce.c)(74),{initialShardKey:u,initialTable:n}=s,l=Ve(),[a,m]=(0,x.useState)("graph"),{queryShardKey:c,setShardKey:d,shardKey:g}=He(u),[o,p]=(0,x.useState)(""),[i,v]=(0,x.useState)(null),[b,P]=(0,x.useState)(null),_;e[0]===Symbol.for("react.memo_cache_sentinel")?(_={},e[0]=_):_=e[0];let[L,y]=(0,x.useState)(_),G;e[1]===Symbol.for("react.memo_cache_sentinel")?(G={},e[1]=G):G=e[1];let[E,M]=(0,x.useState)(G),[S,C]=(0,x.useState)(null),F;e[2]===Symbol.for("react.memo_cache_sentinel")?(F={},e[2]=F):F=e[2];let[$,he]=(0,x.useState)(F),Q;e[3]===Symbol.for("react.memo_cache_sentinel")?(Q={},e[3]=Q):Q=e[3];let[I,K]=(0,x.useState)(Q),[k,pe]=(0,x.useState)(null),[B,oe]=(0,x.useState)(null),Y;e[4]===Symbol.for("react.memo_cache_sentinel")?(Y={},e[4]=Y):Y=e[4];let[W,xe]=(0,x.useState)(Y),[J,ie]=(0,x.useState)(null),ve;e[5]!==l?(ve=r(async h=>{P(null);try{let w=await l.query(rt,{},$e(h));Je(h),v(w),y({}),M({}),C(null),he(N=>Object.fromEntries(Object.entries(N).filter(q=>{let[A]=q;return A!==h}))),K(N=>Object.fromEntries(Object.entries(N).filter(q=>{let[A]=q;return A!==h})))}catch(w){let N=w;v(null),P(Oe(N))}},"ve"),e[5]=l,e[6]=ve):ve=e[6];let O=ve,Z;e[7]!==l?(Z=r(async()=>{oe(null);try{pe(await l.listGlobalTables())}catch(h){let w=h;pe(null),oe(Oe(w))}},"Z"),e[7]=l,e[8]=Z):Z=e[8];let ee=Z,de,D;e[9]!==c||e[10]!==O||e[11]!==ee?(de=r(()=>{ue(O(c)),ue(ee())},"de"),D=[O,ee,c],e[9]=c,e[10]=O,e[11]=ee,e[12]=de,e[13]=D):(de=e[12],D=e[13]),(0,x.useEffect)(de,D);let te;e[14]!==l||e[15]!==L||e[16]!==S||e[17]!==c?(te=r(async h=>{if(S===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},$e(c)),l.query(ot,{table:h},$e(c))]);N.status==="fulfilled"?y(A=>({...A,[w]:N.value.columns})):P(Oe(N.reason)),q.status==="fulfilled"&&M(A=>({...A,[w]:q.value.indexes}))},"te"),e[14]=l,e[15]=L,e[16]=S,e[17]=c,e[18]=te):te=e[18];let j=te,ye;e[19]!==l||e[20]!==W||e[21]!==J?(ye=r(async h=>{if(J===h){ie(null);return}if(ie(h),W[h]===void 0)try{let w=await l.readGlobalTablePage({limit:1,offset:0,table:h});xe(N=>({...N,[h]:w.columns}))}catch(w){oe(Oe(w))}},"ye"),e[19]=l,e[20]=W,e[21]=J,e[22]=ye):ye=e[22];let ce=ye,be=(0,x.useRef)(void 0),R,X;e[23]!==n||e[24]!==i||e[25]!==j?(R=r(()=>{n===void 0||i===null||be.current===n||i.some(h=>h.name===n)&&(be.current=n,ue(j(n)))},"K"),X=[n,i,j],e[23]=n,e[24]=i,e[25]=j,e[26]=R,e[27]=X):(R=e[26],X=e[27]),(0,x.useEffect)(R,X);let V;e[28]!==l?(V=r(async(h,w,N)=>{let[q,A]=await Promise.all([Promise.allSettled([l.query(dt,{tables:[...w,...N]},$e(h))]),Promise.all(N.map(async T=>{let ge=await Promise.allSettled([l.readGlobalTablePage({limit:1,offset:0,table:T})]),Ie=ge[0].status==="fulfilled"?ge[0].value:void 0;return{columns:Ie?.columns??[],refs:Ie?.refs??{},table:T}}))]),Te=q[0].status==="fulfilled"?q[0].value?.columnsByTable??{}:{},Se=q[0].status==="rejected",_e=new Map(A.map(ut)),ke=[...w,...N].map(T=>{let ge=Te[T]??[];return[T,ge.length>0?ge:_e.get(T)??[]]});he(T=>({...T,[h]:Object.fromEntries(ke)})),K(T=>({...T,[h]:Se}))},"U"),e[28]=l,e[29]=V):V=e[29];let le=V,U,ae;e[30]!==B||e[31]!==k||e[32]!==le||e[33]!==c||e[34]!==$||e[35]!==i||e[36]!==a?(U=r(()=>{a!=="graph"||i===null||k===null&&B===null||$[c]!==void 0||ue(le(c,i.map(ht),(k??[]).map(pt)))},"V"),ae=[a,i,k,B,c,$,le],e[30]=B,e[31]=k,e[32]=le,e[33]=c,e[34]=$,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=$[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]??Ye,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]??Ye,name:A.name,tier:"global"}),"x"),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,H;if(e[50]!==k||e[51]!==o){let h=o.trim().toLowerCase();H=(k??[]).filter(w=>w.name.toLowerCase().includes(h)),e[50]=k,e[51]=o,e[52]=H}else H=e[52];let Ne=H,fe;return e[53]!==L||e[54]!==se||e[55]!==b||e[56]!==S||e[57]!==Ne||e[58]!==re||e[59]!==W||e[60]!==B||e[61]!==J||e[62]!==k||e[63]!==E||e[64]!==O||e[65]!==d||e[66]!==I||e[67]!==g||e[68]!==o||e[69]!==i||e[70]!==j||e[71]!==ce||e[72]!==a?(fe={columns:L,diagramTables:se,error:b,expanded:S,filteredGlobalTables:Ne,filteredTables:re,globalColumns:W,globalError:B,globalExpanded:J,globalTables:k,indexes:E,refresh:O,setShardKey:d,setTableFilter:p,setView:m,shardColumnsError:I,shardKey:g,tableFilter:o,tables:i,toggle:j,toggleGlobal:ce,view:a},e[53]=L,e[54]=se,e[55]=b,e[56]=S,e[57]=Ne,e[58]=re,e[59]=W,e[60]=B,e[61]=J,e[62]=k,e[63]=E,e[64]=O,e[65]=d,e[66]=I,e[67]=g,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,"ft");var bt="/__lunora/schema-edit",ft=r(async s=>{let e=await fetch(bt,{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)})`}},"pt"),gt=r(s=>{let e=(0,Ce.c)(32),{hasTables:u,mode:n,onAddColumn:l,onAddIndex:a,onAddTable:m,onDestructive:c}=s,d=Fe(),g=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]!==g||e[4]!==o?(p=(0,t.jsx)(me,{"data-testid":"sc-editor-add-table",onClick:m,size:"xs",type:"button",variant:g,children:o}),e[2]=m,e[3]=g,e[4]=o,e[5]=p):p=e[5];let i=!u,v=n==="addColumn"?"default":"outline",b;e[6]!==d?(b=d("Add column"),e[6]=d,e[7]=b):b=e[7];let P;e[8]!==l||e[9]!==i||e[10]!==v||e[11]!==b?(P=(0,t.jsx)(me,{"data-testid":"sc-editor-add-column",disabled:i,onClick:l,size:"xs",type:"button",variant:v,children:b}),e[8]=l,e[9]=i,e[10]=v,e[11]=b,e[12]=P):P=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 G;e[15]!==a||e[16]!==y||e[17]!==_||e[18]!==L?(G=(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]=G):G=e[19];let E=!u,M=n==="destructive"?"default":"ghost",S;e[20]!==d?(S=d("Rename / drop / change type\u2026"),e[20]=d,e[21]=S):S=e[21];let C;e[22]!==c||e[23]!==E||e[24]!==M||e[25]!==S?(C=(0,t.jsx)(me,{"data-testid":"sc-editor-destructive",disabled:E,onClick:c,size:"xs",type:"button",variant:M,children:S}),e[22]=c,e[23]=E,e[24]=M,e[25]=S,e[26]=C):C=e[26];let F;return e[27]!==G||e[28]!==C||e[29]!==p||e[30]!==P?(F=(0,t.jsxs)("div",{className:"flex flex-wrap gap-2",children:[p,P,G,C]}),e[27]=G,e[28]=C,e[29]=p,e[30]=P,e[31]=F):F=e[31],F},"gt"),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 b;return e[13]!==p||e[14]!==v?(b=(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]=b):b=e[15],b}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 g;return e[25]!==m||e[26]!==d?(g=(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]=g):g=e[27],g},"bt");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!==""),"Ct"),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,g]=(0,x.useState)(!1),[o,p]=(0,x.useState)(null),[i,v]=(0,x.useState)(""),[b,P]=(0,x.useState)(""),[_,L]=(0,x.useState)(Nt),[y,G]=(0,x.useState)(n[0]??""),[E,M]=(0,x.useState)(""),[S,C]=(0,x.useState)(""),[F,$]=(0,x.useState)(!1),he;e[0]===Symbol.for("react.memo_cache_sentinel")?(he=r(()=>{c(null),v(""),P(""),M(""),C(""),$(!1)},"me"),e[0]=he):he=e[0];let Q=he,I;e[1]!==u?(I=r(async T=>{g(!0),p(null);try{let ge=await ft(T);p(ge),ge.kind==="ok"&&(u(ge.tables),Q())}catch(ge){let Ie=ge;p({kind:"error",message:Ie instanceof Error?Ie.message:String(Ie)})}g(!1)},"I"),e[1]=u,e[2]=I):I=e[2];let K=I,k;e[3]!==K||e[4]!==i?(k=r(()=>{ue(K({kind:"addTable",table:i.trim()}))},"_"),e[3]=K,e[4]=i,e[5]=k):k=e[5];let pe=k,B;e[6]!==b||e[7]!==K||e[8]!==y||e[9]!==_?(B=r(()=>{ue(K({column:b.trim(),kind:"addOptionalColumn",table:y,validator:_}))},"j"),e[6]=b,e[7]=K,e[8]=y,e[9]=_,e[10]=B):B=e[10];let oe=B,Y;e[11]!==S||e[12]!==E||e[13]!==K||e[14]!==y||e[15]!==F?(Y=r(()=>{ue(K({fields:Ct(S),kind:"addIndex",name:E.trim(),table:y,unique:F}))},"Q"),e[11]=S,e[12]=E,e[13]=K,e[14]=y,e[15]=F,e[16]=Y):Y=e[16];let W=Y,xe;e[17]===Symbol.for("react.memo_cache_sentinel")?(xe=r(()=>{p(null),c("addTable")},"xe"),e[17]=xe):xe=e[17];let J=xe,ie;e[18]===Symbol.for("react.memo_cache_sentinel")?(ie=r(()=>{p(null),c("addColumn")},"re"),e[18]=ie):ie=e[18];let ve=ie,O;e[19]===Symbol.for("react.memo_cache_sentinel")?(O=r(()=>{p(null),c("addIndex")},"O"),e[19]=O):O=e[19];let Z=O,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,D;e[22]===Symbol.for("react.memo_cache_sentinel")?(D=r(T=>{v(T.target.value)},"R"),e[22]=D):D=e[22];let te=D,j;e[23]===Symbol.for("react.memo_cache_sentinel")?(j=r(T=>{P(T.target.value)},"M"),e[23]=j):j=e[23];let ye=j,ce;e[24]===Symbol.for("react.memo_cache_sentinel")?(ce=r(T=>{L(T.target.value)},"ce"),e[24]=ce):ce=e[24];let be=ce,R;e[25]===Symbol.for("react.memo_cache_sentinel")?(R=r(T=>{G(T.target.value)},"K"),e[25]=R):R=e[25];let X=R,V;e[26]===Symbol.for("react.memo_cache_sentinel")?(V=r(T=>{M(T.target.value)},"U"),e[26]=V):V=e[26];let le=V,U;e[27]===Symbol.for("react.memo_cache_sentinel")?(U=r(T=>{C(T.target.value)},"V"),e[27]=U):U=e[27];let ae=U,z;e[28]===Symbol.for("react.memo_cache_sentinel")?(z=r(T=>{$(T.target.checked)},"$"),e[28]=z):z=e[28];let ne=z,se;e[29]!==a?(se=r(()=>{ue(a({to:"/migrations"}))},"ne"),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 H;e[33]!==re?(H=(0,t.jsx)(Ge,{children:re}),e[33]=re,e[34]=H):H=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)(Ke,{children:Ne}),e[37]=Ne,e[38]=fe):fe=e[38];let h;e[39]!==H||e[40]!==fe?(h=(0,t.jsxs)(Pe,{children:[H,fe]}),e[39]=H,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)(gt,{hasTables:w,mode:m,onAddColumn:ve,onAddIndex:Z,onAddTable:J,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:Q,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]!==b||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(Tt)})]}),(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:b})]}),(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:be,value:_,children:yt.map(St)})]}),(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||b.trim()===""||y==="",onClick:oe,size:"xs",type:"button",children:l(d?"Applying\u2026":"Apply")}),(0,t.jsx)(me,{onClick:Q,size:"xs",type:"button",variant:"ghost",children:l("Cancel")})]}),e[52]=d,e[53]=b,e[54]=m,e[55]=oe,e[56]=l,e[57]=n,e[58]=y,e[59]=_,e[60]=A):A=e[60];let Te;e[61]!==d||e[62]!==S||e[63]!==E||e[64]!==m||e[65]!==W||e[66]!==l||e[67]!==n||e[68]!==y||e[69]!==F?(Te=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:S})]}),(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()===""||S.trim()==="",onClick:W,size:"xs",type:"button",children:l(d?"Applying\u2026":"Apply")}),(0,t.jsx)(me,{onClick:Q,size:"xs",type:"button",variant:"ghost",children:l("Cancel")})]}),e[61]=d,e[62]=S,e[63]=E,e[64]=m,e[65]=W,e[66]=l,e[67]=n,e[68]=y,e[69]=F,e[70]=Te):Te=e[70];let Se;e[71]!==f||e[72]!==o?(Se=(0,t.jsx)(xt,{onOpenMigrations:f,result:o}),e[71]=f,e[72]=o,e[73]=Se):Se=e[73];let _e;e[74]!==N||e[75]!==q||e[76]!==A||e[77]!==Te||e[78]!==Se?(_e=(0,t.jsxs)(Le,{children:[N,q,A,Te,Se]}),e[74]=N,e[75]=q,e[76]=A,e[77]=Te,e[78]=Se,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},"Nt");function Tt(s){return(0,t.jsx)("option",{value:s,children:s},s)}r(Tt,"Tt");function St(s){return(0,t.jsx)("option",{value:s.validator,children:s.label},s.validator)}r(St,"St");function _t(s){return(0,t.jsx)("option",{value:s,children:s},s)}r(_t,"wt");var Ze=[],kt=r(s=>{let e=(0,Ce.c)(5),{open:u}=s,n=u&&"rotate-90",l;e[0]!==n?(l=De("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,g;e[0]!==n?(g=(0,t.jsx)(kt,{open:n}),e[0]=n,e[1]=g):g=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]!==g||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:[g,o," ",p]}),e[6]=n,e[7]=a,e[8]=g,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 b;return e[16]!==c||e[17]!==i||e[18]!==v?(b=(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]=b):b=e[19],b},"Ye"),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},"He"),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},"Et"),lt=r(s=>De("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"),"Xe"),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:g,expanded:o,filteredGlobalTables:p,filteredTables:i,globalColumns:v,globalError:b,globalExpanded:P,globalTables:_,indexes:L,refresh:y,setShardKey:G,setTableFilter:E,setView:M,shardColumnsError:S,shardKey:C,tableFilter:F,tables:$,toggle:he,toggleGlobal:Q,view:I}=mt(m),K;e[3]!==M?(K=r(()=>{M("list")},"q"),e[3]=M,e[4]=K):K=e[4];let k=K,pe;e[5]!==M?(pe=r(()=>{M("graph")},"ue"),e[5]=M,e[6]=pe):pe=e[6];let B=pe,oe;e[7]!==E?(oe=r(f=>{E(f.target.value)},"ie"),e[7]=E,e[8]=oe):oe=e[8];let Y=oe,W;e[9]!==y||e[10]!==C?(W=r(f=>{ue(y(C))},"Y"),e[9]=y,e[10]=C,e[11]=W):W=e[11];let xe=W,J;e[12]!==$?(J=$??[],e[12]=$,e[13]=J):J=e[13];let ie;e[14]!==J?(ie=J.map(zt),e[14]=J,e[15]=ie):ie=e[15];let ve=ie,O;e[16]!==G||e[17]!==C?(O=(0,t.jsx)(Xe,{onChange:G,testId:"sc-shard-input",value:C}),e[16]=G,e[17]=C,e[18]=O):O=e[18];let Z;e[19]!==a?(Z=a("Schema view"),e[19]=a,e[20]=Z):Z=e[20];let ee=I==="graph",de=I==="graph",D;e[21]!==de?(D=lt(de),e[21]=de,e[22]=D):D=e[22];let te;e[23]!==a?(te=a("Graph"),e[23]=a,e[24]=te):te=e[24];let j;e[25]!==B||e[26]!==ee||e[27]!==D||e[28]!==te?(j=(0,t.jsx)("button",{"aria-selected":ee,className:D,"data-testid":"sc-view-graph",onClick:B,role:"tab",type:"button",children:te}),e[25]=B,e[26]=ee,e[27]=D,e[28]=te,e[29]=j):j=e[29];let ye=I==="list",ce=I==="list",be;e[30]!==ce?(be=lt(ce),e[30]=ce,e[31]=be):be=e[31];let R;e[32]!==a?(R=a("Table list"),e[32]=a,e[33]=R):R=e[33];let X;e[34]!==k||e[35]!==ye||e[36]!==be||e[37]!==R?(X=(0,t.jsx)("button",{"aria-selected":ye,className:be,"data-testid":"sc-view-list",onClick:k,role:"tab",type:"button",children:R}),e[34]=k,e[35]=ye,e[36]=be,e[37]=R,e[38]=X):X=e[38];let V;e[39]!==j||e[40]!==X||e[41]!==Z?(V=(0,t.jsxs)("div",{"aria-label":Z,className:"flex items-center gap-1","data-testid":"sc-view-toggle",role:"tablist",children:[j,X]}),e[39]=j,e[40]=X,e[41]=Z,e[42]=V):V=e[42];let le;e[43]!==V||e[44]!==O?(le=(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[O,V]}),e[43]=V,e[44]=O,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]!==Y||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:Y,placeholder:a("Filter tables"),value:F}),e[50]=Y,e[51]=a,e[52]=F,e[53]=I,e[54]=ae):ae=e[54];let z;e[55]!==d||e[56]!==g||e[57]!==b||e[58]!==S||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:[g!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"sc-error",role:"alert",children:g}),b!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"sc-global-error",role:"alert",children:b}),(0,t.jsx)(Qe,{columnsError:S[C]===!0,tables:d,testIdPrefix:"sc-graph"})]}),e[55]=d,e[56]=g,e[57]=b,e[58]=S,e[59]=C,e[60]=I,e[61]=z):z=e[61];let ne;e[62]!==c||e[63]!==g||e[64]!==o||e[65]!==p||e[66]!==i||e[67]!==v||e[68]!==b||e[69]!==P||e[70]!==_||e[71]!==L||e[72]!==C||e[73]!==a||e[74]!==$||e[75]!==he||e[76]!==Q||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)(Pe,{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Re,{tier:"shard"}),(0,t.jsx)(Ge,{children:a("Shard tables")}),$!==null&&(0,t.jsx)(ze,{className:"ms-auto tabular-nums",variant:"outline",children:i.length})]}),(0,t.jsx)(Ke,{children:Me.shard.hint})]}),(0,t.jsxs)(Le,{children:[g!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"sc-error",role:"alert",children:g}),$!==null&&$.length===0&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground","data-testid":"sc-empty",children:a("No tables in this shard.")}),$!==null&&$.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}`,H=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]??Ze,testId:`sc-columns-${f.name}`}),H.length>0&&(0,t.jsx)(It,{heading:a("Indexes"),indexes:H,testId:`sc-indexes-${f.name}`})]},f.name)})})]})]}),(0,t.jsxs)(qe,{"data-testid":"sc-global-section",size:"sm",children:[(0,t.jsxs)(Pe,{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Re,{tier:"global"}),(0,t.jsx)(Ge,{children:a("Global tables (D1)")}),_!==null&&(0,t.jsx)(ze,{className:"ms-auto tabular-nums",variant:"outline",children:p.length})]}),(0,t.jsx)(Ke,{children:Me.global.hint})]}),(0,t.jsxs)(Le,{children:[b!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"sc-global-error",role:"alert",children:b}),_!==null&&_.length===0&&(0,t.jsx)(We,{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:P===f.name,name:f.name,onToggle:r(()=>{ue(Q(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]??Ze,testId:`sc-global-columns-${f.name}`})},f.name))})]})]})]}),e[62]=c,e[63]=g,e[64]=o,e[65]=p,e[66]=i,e[67]=v,e[68]=b,e[69]=P,e[70]=_,e[71]=L,e[72]=C,e[73]=a,e[74]=$,e[75]=he,e[76]=Q,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},"Wt");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,"It");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,"kt");function zt(s){return s.name}r(zt,"At");export{Xt as SchemaViewer};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as P}from"./chunk-
|
|
1
|
+
import{b as P}from"./chunk-4HWTEDVV.js";import{c as K,d as X,e as z,f as L,h as B,i as E,j as G,k as q,l as A,m as O,n as W,o as $,p as D}from"./chunk-XL2OT5WB.js";import{a as F,b as H,c as I,d as S,e as J,f as M}from"./chunk-L4EZAHCD.js";import{d as C,m as j}from"./chunk-BKM6PMSO.js";import{a as f,d as T,f as U,g as V}from"./chunk-R5ZTCHCE.js";var N=T(U(),1);var t=T(V(),1);var _=50,R={value:{colors:{dark:["var(--chart-1)"],light:["var(--chart-1)"]},label:"value"}},Q=f(r=>{let a=r.columns.find(e=>r.rows.length>0&&r.rows.every(n=>typeof n[e]=="number"))??null;return{label:r.columns.find(e=>e!==a)??null,value:a}},"D"),Y=f(r=>{let a=(0,N.c)(3),{data:e,kind:n}=r,l;return a[0]!==e||a[1]!==n?(l=(0,t.jsx)(G,{className:"h-full w-full",config:R,children:n==="area"?(0,t.jsxs)(E,{data:e,children:[(0,t.jsx)(K,{vertical:!1}),(0,t.jsx)(L,{axisLine:!1,dataKey:"label",tickLine:!1}),(0,t.jsx)(A,{content:(0,t.jsx)(q,{})}),(0,t.jsx)(z,{dataKey:"value",fill:"var(--color-value-0)",fillOpacity:.2,stroke:"var(--color-value-0)",type:"monotone"})]}):(0,t.jsxs)(B,{data:e,children:[(0,t.jsx)(K,{vertical:!1}),(0,t.jsx)(L,{axisLine:!1,dataKey:"label",tickLine:!1}),(0,t.jsx)(A,{content:(0,t.jsx)(q,{})}),(0,t.jsx)(X,{dataKey:"value",dot:!1,stroke:"var(--color-value-0)",strokeWidth:2,type:"monotone"})]})}),a[0]=e,a[1]=n,a[2]=l):l=a[2],l},"J"),na=f(r=>{let a=(0,N.c)(21),{axes:e,kind:n,result:l}=r,u=C(),o;a[0]!==l?(o=Q(l),a[0]=l,a[1]=o):o=a[1];let d=o,m;a[2]!==l.columns?(m=new Set(l.columns),a[2]=l.columns,a[3]=m):m=a[3];let s=m,c=e!==void 0&&s.has(e.x)?e.x:d.label,p;a[4]!==e?.y||a[5]!==s?(p=e?.y.find(i=>s.has(i)),a[4]=e?.y,a[5]=s,a[6]=p):p=a[6];let x=p,y=x??d.value,b;a[7]!==c||a[8]!==l.rows||a[9]!==y?(b=y===null?[]:l.rows.slice(0,_).map((i,w)=>({label:c===null?`#${(w+1).toString()}`:j(i[c]),value:Number(i[y])||0})),a[7]=c,a[8]=l.rows,a[9]=y,a[10]=b):b=a[10];let k=b;if(y===null){let i;a[11]!==u?(i=u("No numeric column to chart."),a[11]=u,a[12]=i):i=a[12];let w;return a[13]!==i?(w=(0,t.jsx)("p",{className:"p-4 text-sm text-muted-foreground","data-testid":"sql-chart-empty",children:i}),a[13]=i,a[14]=w):w=a[14],w}let h=n??(e!==void 0&&x!==void 0?e.kind:"bar"),v;a[15]!==k||a[16]!==h?(v=h==="bar"?(0,t.jsxs)(O,{className:"h-full w-full",config:R,data:k,children:[(0,t.jsx)($,{dataKey:"label"}),(0,t.jsx)(W,{dataKey:"value"}),(0,t.jsx)(D,{})]}):(0,t.jsx)(Y,{data:k,kind:h}),a[15]=k,a[16]=h,a[17]=v):v=a[17];let g;return a[18]!==h||a[19]!==v?(g=(0,t.jsx)("div",{className:"h-80 w-full p-3","data-chart-kind":h,"data-testid":"sql-chart",children:v}),a[18]=h,a[19]=v,a[20]=g):g=a[20],g},"oe"),oa=f(r=>{let a=(0,N.c)(19),{result:e}=r,n=C();if(e.columns.length===0){let s;a[0]!==e.rowCount||a[1]!==n?(s=n("{count} rows",{count:e.rowCount}),a[0]=e.rowCount,a[1]=n,a[2]=s):s=a[2];let c;return a[3]!==s?(c=(0,t.jsx)("p",{className:"p-4 text-sm text-muted-foreground",children:s}),a[3]=s,a[4]=c):c=a[4],c}let l;a[5]!==e.columns?(l=e.columns.map(Z),a[5]=e.columns,a[6]=l):l=a[6];let u;a[7]!==l?(u=(0,t.jsx)(H,{className:"sticky top-0 z-10 bg-muted",children:(0,t.jsx)(S,{children:l})}),a[7]=l,a[8]=u):u=a[8];let o;if(a[9]!==e.columns||a[10]!==e.rows){let s;a[12]!==e.columns?(s=f((c,p)=>(0,t.jsx)(S,{"data-testid":"sql-row",children:e.columns.map(x=>(0,t.jsx)(M,{className:"max-w-md truncate font-mono text-xs",children:(0,t.jsx)(P,{value:c[x]})},x))},p),"s"),a[12]=e.columns,a[13]=s):s=a[13],o=e.rows.map(s),a[9]=e.columns,a[10]=e.rows,a[11]=o}else o=a[11];let d;a[14]!==o?(d=(0,t.jsx)(I,{children:o}),a[14]=o,a[15]=d):d=a[15];let m;return a[16]!==u||a[17]!==d?(m=(0,t.jsxs)(F,{"data-testid":"sql-rows",children:[u,d]}),a[16]=u,a[17]=d,a[18]=m):m=a[18],m},"ne");function Z(r){return(0,t.jsx)(J,{children:r},r)}f(Z,"P");export{na as a,oa as b};
|