@fungi.computer/inkcap 0.3.3 → 0.4.0
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/assets/{FileTab-BIzFBzDK.js → FileTab-ZK1QFAd5.js} +25 -25
- package/dist/assets/InkcapFileTree-DTYIjm_0.js +1 -0
- package/dist/assets/InkcapRepositoryApp-q1CrI-Kd.js +1 -0
- package/dist/assets/empty-state-BPRNo51e.js +1 -0
- package/dist/assets/index-B5ZsAojZ.js +2 -0
- package/dist/assets/index-dbf7RxFf.css +2 -0
- package/dist/assets/refresh-cw-xZ5ayQTq.js +1 -0
- package/dist/assets/{dialog-C49TyOKM.js → tree-path-B5mQdKbM.js} +3 -2
- package/dist/assets/{useFileTree-Dyiqmbq-.js → useFileTree-grDspEh1.js} +1 -1
- package/dist/assets/useForm-DF2JFOTS.js +1 -0
- package/dist/index.html +4 -4
- package/package.json +8 -7
- package/dist/assets/InkcapFileTree-WCY0DAx7.js +0 -1
- package/dist/assets/InkcapRepositoryApp-C74ueO0p.js +0 -1
- package/dist/assets/index-BfmirAP5.css +0 -2
- package/dist/assets/index-D89bIeb6.js +0 -2
- package/dist/assets/refresh-cw-LAlYuFfb.js +0 -1
- package/dist/assets/tree-path-BjPaqwnl.js +0 -1
- package/dist/assets/useForm-LW3qRsbm.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,$n as n,$r as r,A as i,Ai as a,An as o,Ar as s,B as c,Bi as l,Bn as u,Br as d,Bt as f,C as p,Cn as m,Ct as h,D as g,Di as _,Dn as v,Dr as y,Dt as b,E as x,Ei as S,En as C,Et as w,F as T,Fi as E,Fn as D,Fr as O,G as k,Gi as A,Gn as j,H as M,Hi as N,Hn as ee,Hr as P,I as F,Ii as te,In as ne,Ir as re,J as ie,Jn as ae,Jr as oe,Jt as se,K as ce,L as le,Li as ue,Ln as de,Lr as fe,M as pe,Mi as me,Mn as he,Mr as ge,N as _e,Ni as ve,Nn as ye,Nr as be,O as xe,Oi as Se,On as Ce,Or as we,Ot as Te,P as Ee,Pi as De,Pn as Oe,Pr as ke,Qn as Ae,Qr as I,R as je,Rr as Me,S as Ne,Sn as Pe,Ti as Fe,Tn as L,Tt as R,U as Ie,Ui as Le,Ur as Re,V as ze,Vi as Be,Vn as z,Vr as Ve,Vt as He,W as Ue,Wi as We,Wr as Ge,Xn as Ke,Xt as qe,Y as Je,Yn as Ye,Yr as Xe,Yt as Ze,Z as Qe,Zn as $e,Zr as et,Zt as tt,_ as nt,_n as rt,ai as it,an as at,ar as ot,at as st,b as ct,bi as lt,bn as ut,bt as dt,ci as B,cn as ft,ct as pt,dn as V,dt as mt,ei as ht,er as gt,et as _t,f as vt,fi as yt,fn as H,ft as bt,g as xt,gn as U,gt as St,h as Ct,hn as wt,i as Tt,ir as Et,it as Dt,j as Ot,ji as kt,jn as At,jr as jt,ki as Mt,kn as Nt,kr as Pt,kt as W,l as Ft,ln as It,m as Lt,mn as Rt,ni as zt,nn as Bt,nr as Vt,nt as Ht,o as Ut,on as Wt,ot as Gt,p as Kt,pn as qt,pt as Jt,qn as Yt,r as Xt,ri as Zt,rn as G,rr as Qt,rt as $t,s as en,sn as tn,t as nn,tn as rn,tr as an,tt as on,u as sn,un as cn,ut as K,v as ln,vn as un,w as dn,wi as fn,wn as pn,x as mn,xn as hn,xt as gn,y as _n,yn as vn,z as yn,zn as bn}from"./tree-path-B5mQdKbM.js";import{Ct as xn,Ot as Sn,a as Cn,b as wn,f as Tn,gt as En,i as Dn,kt as On,l as kn,mt as An,n as jn,o as Mn,r as Nn,t as Pn,u as Fn,xt as In,yt as Ln}from"./empty-state-BPRNo51e.js";import{a as Rn,c as zn,d as Bn,i as Vn,l as Hn,n as Un,o as Wn,r as Gn,s as Kn,t as qn,u as Jn}from"./useFileTree-grDspEh1.js";import{C as Yn,S as Xn,_ as Zn,a as Qn,b as $n,c as er,d as tr,f as nr,g as rr,h as ir,i as ar,l as or,m as sr,n as cr,o as lr,p as ur,r as dr,s as fr,t as pr,u as mr,v as hr,w as gr,x as _r,y as vr}from"./useForm-DF2JFOTS.js";import{t as yr}from"./refresh-cw-xZ5ayQTq.js";function br(e,t){let n=new Set(t);return e.filter(e=>!n.has(e))}var xr=class extends En{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l=[];constructor(e,t,n){super(),this.#e=e,this.#r=n,this.#n=[],this.#i=[],this.#t=[],this.setQueries(t)}onSubscribe(){this.listeners.size===1&&this.#i.forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#i.forEach(e=>{e.destroy()})}setQueries(e,t){this.#n=e,this.#r=t,An.batch(()=>{let e=this.#i,t=this.#p(this.#n);t.forEach(e=>e.observer.setOptions(e.defaultedQueryOptions));let n=t.map(e=>e.observer),r=n.map(e=>e.getCurrentResult()),i=e.length!==n.length,a=n.some((t,n)=>t!==e[n]),o=i||a,s=o?!0:r.some((e,t)=>{let n=this.#t[t];return!n||!xn(e,n)});!o&&!s||(o&&(this.#l=t,this.#i=n),this.#t=r,this.hasListeners()&&(o&&(br(e,n).forEach(e=>{e.destroy()}),br(n,e).forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})),this.#h()))})}getCurrentResult(){return this.#t}getQueries(){return this.#i.map(e=>e.getCurrentQuery())}getObservers(){return this.#i}getOptimisticResult(e,t){let n=this.#p(e),r=n.map(e=>e.observer.getOptimisticResult(e.defaultedQueryOptions)),i=n.map(e=>e.defaultedQueryOptions.queryHash);return[r,e=>this.#d(e??r,t,i),()=>this.#u(r,n)]}#u(e,t){let n=new Set;return t.map((r,i)=>{let a=e[i];return r.defaultedQueryOptions.notifyOnChangeProps?a:r.observer.trackResult(a,e=>{n.has(e)||(n.add(e),t.forEach(t=>{t.observer.trackProp(e)}))})})}#d(e,t,n){if(t){let r=this.#c,i=n!==void 0&&r!==void 0&&(r.length!==n.length||n.some((e,t)=>e!==r[t]));return(this.#t!==this.#s||i||t!==this.#o)&&(this.#o=t,this.#s=this.#t,n!==void 0&&(this.#c=n),this.#a=In(this.#a,t(e))),this.#a}return e}#f(){return!this.#r?.combine||this.#i.some((e,t)=>e.options.suspense&&this.#t[t]?.data===void 0)}#p(e){let t=new Map;this.#i.forEach(e=>{let n=e.options.queryHash;if(!n)return;let r=t.get(n);r?r.push(e):t.set(n,[e])});let n=[];return e.forEach(e=>{let r=this.#e.defaultQueryOptions(e),i=t.get(r.queryHash)?.shift()??new Bn(this.#e,r);n.push({defaultedQueryOptions:r,observer:i})}),n}#m(e,t){let n=this.#i.indexOf(e);n!==-1&&(this.#t=this.#t.slice(),this.#t[n]=t,this.#h())}#h(){if(this.hasListeners()){let e=this.#f(),t=this.#a,n=e?t:this.#d(this.#u(this.#t,this.#l),this.#r?.combine);(e||t!==n)&&An.batch(()=>{this.listeners.forEach(e=>{e(this.#t)})})}}},q=e(Ve(),1);function Sr({queries:e,...t},n){let r=Sn(n),i=Jn(),a=Hn(),o=t.subscribed!==!1,s=q.useMemo(()=>e.map(e=>{let t=r.defaultQueryOptions(e);return t._optimisticResults=i?`isRestoring`:o?`optimistic`:void 0,t}),[e,r,i,o]);s.forEach(e=>{Gn(e);let t=r.getQueryCache().get(e.queryHash);Wn(e,a,t)}),zn(a);let[c]=q.useState(()=>new xr(r,s,t)),[l,u,d]=c.getOptimisticResult(s,t.combine),f=!i&&o;q.useSyncExternalStore(q.useCallback(e=>f?c.subscribe(An.batchCalls(e)):Ln,[c,f]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),q.useEffect(()=>{c.setQueries(s,t)},[s,t,c]);let p=l.some((e,t)=>Rn(s[t],e))?l.flatMap((e,t)=>{let n=s[t];if(n&&Rn(n,e)){let e=new Bn(r,n);return Vn(n,e,a)}return[]}):[];if(p.length>0)throw Promise.all(p);let m=l.find((e,t)=>{let n=s[t];return n&&Kn({result:e,errorResetBoundary:a,throwOnError:n.throwOnError,query:r.getQueryCache().get(n.queryHash),suspense:n.suspense})});if(m)throw m.error;return u(d())}var Cr=Me(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);s.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>jt(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>be(e,t,n),e.parseAsync=async(t,n)=>ge(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>ke(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>O(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),wr=Me(`ZodMiniObject`,(e,t)=>{Pt.init(e,t),Cr.init(e,t),re(e,`shape`,()=>t.shape)});function Tr(e,t){return new wr({type:`object`,shape:e??{},...fe(t)})}var Er=Me(`ZodMiniLiteral`,(e,t)=>{we.init(e,t),Cr.init(e,t)});function Dr(e,t){return new Er({type:`literal`,values:Array.isArray(e)?e:[e],...fe(t)})}var Or=u(`Check`,[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]),kr=u(`ChevronDown`,[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]),Ar=u(`EyeOff`,[[`path`,{d:`M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49`,key:`ct8e1f`}],[`path`,{d:`M14.084 14.158a3 3 0 0 1-4.242-4.242`,key:`151rxh`}],[`path`,{d:`M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143`,key:`13bj9a`}],[`path`,{d:`m2 2 20 20`,key:`1ooewy`}]]),jr=u(`FileImage`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`circle`,{cx:`10`,cy:`12`,r:`2`,key:`737tya`}],[`path`,{d:`m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22`,key:`wt3hpn`}]]),Mr=u(`FolderPlus`,[[`path`,{d:`M12 10v6`,key:`1bos4e`}],[`path`,{d:`M9 13h6`,key:`1uhe8q`}],[`path`,{d:`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`,key:`1kt360`}]]),Nr=u(`RotateCcw`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}]]),J=C*10,Pr=class{constructor(e={}){let t=!ut(e.bounce)||!ut(e.duration);this.timeStep=.02,this.restThreshold=5e-4,this.restDuration=200,this.maxDuration=6e4,this.maxRestSteps=this.restDuration/this.timeStep/C,this.maxIterations=this.maxDuration/this.timeStep/C,this.bn=U(H(e.bounce,.5),-1,1),this.pd=U(H(e.duration,628),10*L.timeScale,J*L.timeScale),this.m=U(H(e.mass,1),1,J),this.s=U(H(e.stiffness,100),v,J),this.d=U(H(e.damping,10),v,J),this.v=U(H(e.velocity,0),-J,J),this.w0=0,this.zeta=0,this.wd=0,this.b=0,this.completed=!1,this.solverDuration=0,this.settlingDuration=0,this.parent=null,this.onComplete=e.onComplete||Ce,t&&this.calculateSDFromBD(),this.compute(),this.ease=e=>{let t=e*this.settlingDuration,n=this.completed,r=this.pd;return t>=r&&!n&&(this.completed=!0,this.onComplete(this.parent)),t<r&&n&&(this.completed=!1),e===0||e===1?e:this.solve(e*this.solverDuration)}}solve(e){let{zeta:t,w0:n,wd:r,b:i}=this,a=e;return a=t<1?un(-a*t*n)*(1*rt(r*a)+i*m(r*a)):t===1?(1+i*a)*un(-a*n):((1+i)*un((-t*n+r)*a)+(1-i)*un((-t*n-r)*a))/2,1-a}calculateSDFromBD(){let e=L.timeScale===1?this.pd/C:this.pd;this.m=1,this.v=0,this.s=hn(2*qt/e,2),this.d=this.bn>=0?(1-this.bn)*4*qt/e:4*qt/(e*(1+this.bn)),this.s=Pe(U(this.s,v,J),3),this.d=Pe(U(this.d,v,300),3)}calculateBDFromSD(){let e=2*qt/pn(this.s);this.pd=e*(L.timeScale===1?C:1),this.bn=this.d/(2*pn(this.s))<=1?1-this.d*e/(4*qt):4*qt/(this.d*e)-1,this.bn=Pe(U(this.bn,-1,1),3),this.pd=Pe(U(this.pd,10*L.timeScale,J*L.timeScale),3)}compute(){let{maxRestSteps:e,maxIterations:t,restThreshold:n,timeStep:r,m:i,d:a,s:o,v:s}=this,c=this.w0=U(pn(o/i),v,C),l=this.zeta=a/(2*pn(o*i));l<1?(this.wd=c*pn(1-l*l),this.b=(l*c+-s)/this.wd):l===1?(this.wd=0,this.b=-s+c):(this.wd=c*pn(l*l-1),this.b=(l*c+-s)/this.wd);let u=0,d=0,f=0;for(;d<=e&&f<=t;)Rt(1-this.solve(u))<n?d++:d=0,this.solverDuration=u,u+=r,f++;this.settlingDuration=Pe(this.solverDuration*C,0)*L.timeScale}get bounce(){return this.bn}set bounce(e){this.bn=U(H(e,1),-1,1),this.calculateSDFromBD(),this.compute()}get duration(){return this.pd}set duration(e){this.pd=U(H(e,1),10*L.timeScale,J*L.timeScale),this.calculateSDFromBD(),this.compute()}get stiffness(){return this.s}set stiffness(e){this.s=U(H(e,100),v,J),this.calculateBDFromSD(),this.compute()}get damping(){return this.d}set damping(e){this.d=U(H(e,10),v,J),this.calculateBDFromSD(),this.compute()}get mass(){return this.m}set mass(e){this.m=U(H(e,1),1,J),this.compute()}get velocity(){return this.v}set velocity(e){this.v=U(H(e,0),-J,J),this.compute()}},Fr=e=>new Pr(e),Ir=(e=10,t)=>{let n=t?wt:vn;return t=>n(U(t,0,1)*e)*(1/e)},Lr=e(ee(),1),Rr={current:null};function zr(e,t={}){let{enabled:n=!0,delay:r=0,handleClose:i=null,mouseOnly:a=!1,restMs:o=0,move:s=!0,triggerElementRef:c=Rr,externalTree:l,isActiveTrigger:u=!0,getHandleCloseContext:d,isClosing:p,shouldOpen:m,guardStaleOpen:g=!1}=t,{dataRef:_,events:v}=e.context,y=ie(l),x=$n(e),S=q.useRef(!1),C=Dt(i),w=Dt(r),T=Dt(o),E=Dt(n),D=Dt(m),O=Dt(p),k=W(()=>Yn(_.current.openEvent?.type,x.interactedInside)),A=W(()=>D.current?.()!==!1),j=W((t,n,r)=>{let i=e.context.triggerElements;if(i.hasElement(n))return!t||!K(t,n);if(!f(r))return!1;let a=r;return i.hasMatchingElement(e=>K(e,a))&&(!t||!K(t,a))}),M=W(()=>{x.handler&&=(b(e.select(`domReferenceElement`)).removeEventListener(`mousemove`,x.handler),void 0)}),N=W(()=>{vr(x)});return u&&(x.handleCloseOptions=i?.__options),q.useEffect(()=>M,[M]),q.useEffect(()=>{if(!n)return;function e(e){e.open?S.current=!1:(S.current=e.reason===h,M(),x.openChangeTimeout.clear(),x.restTimeout.clear(),x.blockMouseMove=!0,x.restTimeoutPending=!1)}return v.on(`openchange`,e),()=>{v.off(`openchange`,e)}},[n,v,x,M]),q.useEffect(()=>{if(!n)return;function t(t,n=!0){let r=_r(w.current,`close`,x.pointerType);r?x.openChangeTimeout.start(r,()=>{e.setOpen(!1,R(h,t)),y?.events.emit(`floating.closed`,t)}):n&&(x.openChangeTimeout.clear(),e.setOpen(!1,R(h,t)),y?.events.emit(`floating.closed`,t))}let r=c.current??(u?e.select(`domReferenceElement`):null);if(!f(r))return;function i(t){if(x.openChangeTimeout.clear(),x.blockMouseMove=!1,a&&!bt(x.pointerType))return;let n=Xn(T.current),r=_r(w.current,`open`,x.pointerType),i=mt(t),o=t.currentTarget??null,s=e.select(`domReferenceElement`),c=o;if(f(i)&&!e.context.triggerElements.hasElement(i)){for(let t of e.context.triggerElements.elements())if(K(t,i)){c=t;break}}f(o)&&f(s)&&!e.context.triggerElements.hasElement(o)&&K(o,s)&&(c=s);let l=c!=null&&j(s,c,i),u=e.select(`open`),d=O.current?.()??e.select(`transitionStatus`)===`ending`,p=!u&&d&&S.current,m=!l&&f(c)&&f(s)&&K(s,c)&&p,g=n>0&&!r,_=l&&(u||p)||m,v=!u||l;if(_){A()&&e.setOpen(!0,R(h,t,c));return}g||(r?x.openChangeTimeout.start(r,()=>{v&&A()&&e.setOpen(!0,R(h,t,c))}):v&&A()&&e.setOpen(!0,R(h,t,c)))}function o(n){if(k()){N();return}M();let r=e.select(`domReferenceElement`),i=b(r);x.restTimeout.clear(),x.restTimeoutPending=!1;let a=_.current.floatingContext??d?.();if(!pt(n.relatedTarget,e.context.triggerElements)){if(C.current&&a){e.select(`open`)||x.openChangeTimeout.clear();let r=c.current;x.handler=C.current({...a,tree:y,x:n.clientX,y:n.clientY,onClose(){N(),M(),E.current&&!k()&&r===e.select(`domReferenceElement`)&&t(n,!0)}}),i.addEventListener(`mousemove`,x.handler),x.handler(n);return}(x.pointerType!==`touch`||!K(e.select(`floatingElement`),n.relatedTarget))&&t(n)}}function l(e){K(r,e.relatedTarget)||(x.openChangeTimeout.clear(),x.restTimeout.clear(),x.restTimeoutPending=!1)}let p=g?Gt(r,`mouseout`,l):void 0;return s?st(Gt(r,`mousemove`,i,{once:!0}),Gt(r,`mouseenter`,i),Gt(r,`mouseleave`,o),p):st(Gt(r,`mouseenter`,i),Gt(r,`mouseleave`,o),p)},[M,N,_,w,e,n,C,x,u,j,k,a,s,T,c,y,E,d,O,A,g]),q.useMemo(()=>{if(!n)return;function t(e){x.pointerType=e.pointerType}return{onPointerDown:t,onPointerEnter:t,onMouseMove(t){let{nativeEvent:n}=t,r=t.currentTarget,i=e.select(`domReferenceElement`),o=e.select(`open`),s=j(i,r,t.target);if(a&&!bt(x.pointerType))return;if(o&&s&&x.handleCloseOptions?.blockPointerEvents){let t=e.select(`floatingElement`);if(t){let e=x.handleCloseOptions?.getScope?.()??r.ownerDocument.body;hr(x,{scopeElement:e,referenceElement:r,floatingElement:t})}}let c=Xn(T.current);if(o&&!s||c===0||!s&&x.restTimeoutPending&&t.movementX**2+t.movementY**2<2)return;x.restTimeout.clear();function l(){if(x.restTimeoutPending=!1,k())return;let t=e.select(`open`);!x.blockMouseMove&&(!t||s)&&A()&&e.setOpen(!0,R(h,n,r))}x.pointerType===`touch`?Lr.flushSync(()=>{l()}):s&&o?l():(x.restTimeoutPending=!0,x.restTimeout.start(c,l))}}},[n,x,k,j,a,e,T,A])}var Br=.1,Vr=Br*Br,Y=.5;function Hr(e,t,n,r,i,a){return r>=t!=a>=t&&e<=(i-n)*(t-r)/(a-r)+n}function Ur(e,t,n,r,i,a,o,s,c,l){let u=!1;return Hr(e,t,n,r,i,a)&&(u=!u),Hr(e,t,i,a,o,s)&&(u=!u),Hr(e,t,o,s,c,l)&&(u=!u),Hr(e,t,c,l,n,r)&&(u=!u),u}function Wr(e,t,n){return e>=n.x&&e<=n.x+n.width&&t>=n.y&&t<=n.y+n.height}function Gr(e,t,n,r,i,a){return e>=Math.min(n,i)&&e<=Math.max(n,i)&&t>=Math.min(r,a)&&t<=Math.max(r,a)}function Kr(e={}){let{blockPointerEvents:t=!1}=e,n=new Jt,r=({x:e,y:t,placement:r,elements:i,onClose:a,nodeId:o,tree:s})=>{let c=r?.split(`-`)[0],l=!1,u=null,d=null,p=typeof performance<`u`?performance.now():0;function m(e,t){let n=performance.now(),r=n-p;if(u===null||d===null||r===0)return u=e,d=t,p=n,!1;let i=e-u,a=t-d,o=i*i+a*a,s=r*r*Vr;return u=e,d=t,p=n,o<s}function h(){n.clear(),a()}return function(r){n.clear();let a=i.domReference,u=i.floating;if(!a||!u||c==null||e==null||t==null)return;let{clientX:d,clientY:p}=r,g=mt(r),_=r.type===`mouseleave`,v=K(u,g),y=K(a,g);if(v&&(l=!0,!_))return;if(y&&(l=!1,!_)){l=!0;return}if(_&&f(r.relatedTarget)&&K(u,r.relatedTarget))return;function b(){return!!(s&&_t(s.nodesRef.current,o).length>0)}function x(){b()||h()}if(b())return;let S=a.getBoundingClientRect(),C=u.getBoundingClientRect(),w=e>C.right-C.width/2,T=t>C.bottom-C.height/2,E=C.width>S.width,D=C.height>S.height,O=(E?S:C).left,k=(E?S:C).right,A=(D?S:C).top,j=(D?S:C).bottom;if(c===`top`&&t>=S.bottom-1||c===`bottom`&&t<=S.top+1||c===`left`&&e>=S.right-1||c===`right`&&e<=S.left+1){x();return}let M=!1;switch(c){case`top`:M=Gr(d,p,O,S.top+1,k,C.bottom-1);break;case`bottom`:M=Gr(d,p,O,C.top+1,k,S.bottom-1);break;case`left`:M=Gr(d,p,C.right-1,j,S.left+1,A);break;case`right`:M=Gr(d,p,S.right-1,j,C.left+1,A)}if(M)return;if(l&&!Wr(d,p,S)){x();return}if(!_&&m(d,p)){x();return}let N=!1;switch(c){case`top`:{let n=E?Y/2:Y*4,r=E||w?e+n:e-n,i=E?e-n:w?e+n:e-n,a=t+Y+1,o=w||E?C.bottom-Y:C.top,s=w?E?C.bottom-Y:C.top:C.bottom-Y;N=Ur(d,p,r,a,i,a,C.left,o,C.right,s);break}case`bottom`:{let n=E?Y/2:Y*4,r=E||w?e+n:e-n,i=E?e-n:w?e+n:e-n,a=t-Y,o=w||E?C.top+Y:C.bottom,s=w?E?C.top+Y:C.bottom:C.top+Y;N=Ur(d,p,r,a,i,a,C.left,o,C.right,s);break}case`left`:{let n=D?Y/2:Y*4,r=D||T?t+n:t-n,i=D?t-n:T?t+n:t-n,a=e+Y+1,o=T||D?C.right-Y:C.left,s=T?D?C.right-Y:C.left:C.right-Y;N=Ur(d,p,o,C.top,s,C.bottom,a,r,a,i);break}case`right`:{let n=D?Y/2:Y*4,r=D||T?t+n:t-n,i=D?t-n:T?t+n:t-n,a=e-Y,o=T||D?C.left+Y:C.right,s=T?D?C.left+Y:C.right:C.left+Y;N=Ur(d,p,a,r,a,i,o,C.top,s,C.bottom);break}}N?l||n.start(40,x):x()}};return r.__options={...e,blockPointerEvents:t},r}function qr(e,t,n){return`${e.endsWith(`/`)?e:`${e}/`}${t}${n===`directory`?`/`:``}`}function Jr(e,t,n){let r=t.entries.filter(e=>e.type!==`symlink`).map(e=>qr(t.path,e.name,e.type)),i=r.filter(e=>!n.has(e));if(i.length>0){let t=i.map(e=>({type:`add`,path:e}));e.batch(t)}n.add(t.path);for(let e of r)n.add(e);return i}function Yr(e,t){let n=t===`/`?`/`:t.replace(/\/+$/,``);if(n!==`/`&&e!==n&&!e.startsWith(`${n}/`))return[];let r=n===`/`?e.split(`/`).filter(Boolean):e.slice(n.length).split(`/`).filter(Boolean),i=[n],a=n;for(let e of r.slice(0,-1))a=`${a===`/`?``:a}/${e}`,i.push(a);return i}function Xr({app:e,rootPath:t,rootLabel:n=`Computer`,activePath:r,onOpenFile:i,onSelectPath:a}){let o=Sn(),s=wn(e),c=(0,q.useCallback)(t=>e.capabilities.subscribe(t),[e]),l=(0,q.useCallback)(()=>e.capabilities.version,[e]),u=(0,q.useSyncExternalStore)(c,l,l),d=(0,q.useMemo)(()=>({app:e,rootPath:t,computerId:s,version:u}),[e,t,s,u]),[f,p]=(0,q.useState)(null),m=f?.scope===d?f:null,h=r?Yr(r,t):[],g=m?.activePath===r?m.path:h.at(-1)??t,_=new Map;for(let e of[t,...h])_.set(`${e}:0`,{path:e,offset:0});for(let e of m?.pages??[])_.set(`${e.path}:${String(e.offset)}`,e);let v=[..._.values()],y=(t,n)=>Tn.of(e,`tree`,u,t,n),b=Sr({queries:v.map(({path:t,offset:n})=>Fn(e,Dn,y(t,n),async(e,r)=>{let i=await e.list({path:t,offset:n,limit:256});return r.throwIfAborted(),i})),combine:e=>({listings:e.flatMap((e,t)=>e.data?[{request:v[t],listing:e.data}]:[]),busy:e.some(e=>e.isFetching),failure:e.find(e=>e.error)?.error??null})}),x=(0,q.useRef)({activePath:r,onOpenFile:i,onSelectPath:a,rootLabel:n});x.current={activePath:r,onOpenFile:i,onSelectPath:a,rootLabel:n};let S=(e,t)=>{let n=e.replace(/\/+$/,``)||`/`,i=y(n,t);o.getQueryState(i)?.status===`error`&&o.invalidateQueries({queryKey:i,exact:!0}),p(e=>({scope:d,activePath:r,path:n,pages:[...e?.scope===d?e.pages.filter(e=>e.path!==n||e.offset!==t):[],{path:n,offset:t}]}))},C=(0,q.useRef)(S);C.current=S;let{model:w}=qn({paths:[],itemHeight:32,initialExpansion:1,composition:{contextMenu:{enabled:!0}},renderRowDecoration:({row:e})=>e.path===`/`?{text:x.current.rootLabel}:null,unsafeCSS:`[data-item-section="content"] { display: flex; align-items: center; }[data-item-path="/"] [data-item-section="decoration"] { justify-content: flex-start; color: inherit; }`,onSelectionChange(e){let t=e[0];t&&(x.current.onSelectPath?.(t),t.endsWith(`/`)?C.current(t,0):t!==x.current.activePath&&x.current.onOpenFile(t))}}),T=(0,q.useRef)(new Set),E=(0,q.useRef)(new Map),D=(0,q.useRef)(null);(0,q.useLayoutEffect)(()=>{T.current.clear(),E.current.clear(),w.resetPaths([]),D.current=null},[w,d]),(0,q.useLayoutEffect)(()=>{D.current=null;for(let e of w.getSelectedPaths())!e.endsWith(`/`)&&e!==r&&w.getItem(e)?.deselect()},[r,w]),(0,q.useLayoutEffect)(()=>{b.listings.length===0&&(T.current.clear(),E.current.clear(),w.resetPaths([]),D.current=null);for(let{request:e,listing:t}of b.listings){let n=`${e.path}:${String(e.offset)}`,r=t.entries.filter(e=>e.type!==`symlink`).map(e=>qr(t.path,e.name,e.type)),i=E.current.get(n)??[];E.current.set(n,r);let a=new Set([...E.current.values()].flat());for(let e of i)if(!a.has(e)){w.getItem(e)&&w.remove(e,{recursive:!0});for(let t of T.current)(t===e||e.endsWith(`/`)&&t.startsWith(e))&&T.current.delete(t)}Jr(w,t,T.current)}if(!r||D.current===r)return;let e=Yr(r,t);if(!e.every(e=>T.current.has(e)))return;for(let t of e){let e=w.getItem(t);e&&`expand`in e&&e.expand()}let n=w.getItem(r);n&&(D.current=r,n.select(),w.scrollToPath(r,{focus:!1}))},[r,w,t,d,b.listings]),(0,q.useEffect)(()=>{b.failure&&console.error(`Inkcap directory listing failed`,On(b.failure))},[b.failure]);let O=b.listings.filter(({request:e})=>e.path===g).sort((e,t)=>e.request.offset-t.request.offset).at(-1)?.listing,k={path:O?.path??g,next:O?.nextOffset??null},A=b.listings.some(({request:e,listing:n})=>e.path===t&&e.offset===0&&n.entries.length===0&&n.nextOffset===null);return{model:w,page:k,error:b.failure?`Could not list this directory. Existing files remain available.`:``,busy:b.busy,rootEmpty:A,reloadRoot:()=>{o.invalidateQueries({queryKey:Tn.of(e,`tree`,u)})},loadNext:()=>{k.next!==null&&S(k.path,k.next)}}}var Zr=B(I),Qr=B(r({message:I}));function $r(e){for(let t of e.errors){let e=Be(A(Le(Qr(t),e=>e.message),()=>Zr(t)));if(e!==void 0&&e.length>0)return e}}var X=Object.freeze({ease:`linear`,duration:0});function ei(e,t){let n=ye(e,t.duration);return n<=0?X:e.steps>0?{ease:Ir(e.steps),duration:n}:{ease:Fr({bounce:At(e,t.bounce),duration:n}),duration:n}}function Z(e,t){let n=Oe(e,t.duration);return{ease:e.steps>0?Ir(e.steps):t.ease,duration:n}}var Q=d(),ti={dot:{y:-4,height:8,cy:0},pill:{y:-16,height:32,cy:0},bang:{y:-16,height:20,cy:12}};function ni({className:e,glyph:t,motion:n}){let r=`caps-status-${(0,q.useId)().replaceAll(`:`,``)}`,i=(0,q.useRef)(null),a=(0,q.useRef)(null),o=(0,q.useRef)(null),s=(0,q.useRef)(null),c=(0,q.useRef)(null),l=(0,q.useRef)(null),u=(0,q.useRef)(ti[t]).current,d=(0,q.useRef)(t===`dot`?1:4).current,f=(0,q.useRef)(+(t===`bang`)).current,p=(0,q.useRef)(t),m=ne(s),{reduced:h}=m;return(0,q.useLayoutEffect)(()=>{if(!i.current||!a.current||!c.current||!l.current)return;let e=ti[t],n=h||p.current===t;p.current=t;let r=D(i.current),o=n?{duration:0}:ei(r,{bounce:.3,duration:360}),s=V(i.current,{y:e.y,height:e.height,...o}),u=V(a.current,{cy:e.cy,...n?{duration:0}:{delay:Oe(r,35),...ei(r,{bounce:.3,duration:420})}}),d=V(c.current,{gradientTransform:`matrix(1 0 0 ${t===`dot`?`1`:`4`} 0 0)`,...o}),f=V(l.current,{opacity:+(t===`bang`),...n?X:Z(r,{ease:`inOutSine`,duration:220})});return()=>{s.cancel(),u.cancel(),d.cancel(),f.cancel()}},[t,h]),(0,q.useLayoutEffect)(()=>{if(!o.current||!s.current||h||n===`none`)return;let e=n===`pulse`?V(o.current,{opacity:[1,.45],...Z(m,{ease:`inOutSine`,duration:750}),alternate:!0,loop:!0}):V(o.current,{keyframes:{"0%":{translateY:0,scaleX:1,scaleY:1},"18%":{translateY:.25,scaleX:1.1,scaleY:.91},"42%":{translateY:-1.3,scaleX:.94,scaleY:1.06},"62%":{translateY:-1.65,scaleX:1,scaleY:1},"82%":{translateY:.15,scaleX:1.06,scaleY:.95},"100%":{translateY:0,scaleX:1,scaleY:1}},...Z(m,{ease:`inOutSine`,duration:1e3}),loop:!0}),t=at(s.current,t=>{t?e.resume():e.pause()});return()=>{t(),e.revert()}},[n,h,m]),(0,Q.jsxs)(`svg`,{ref:s,"aria-hidden":`true`,className:`caps-status-bead ${e??``}`,width:`8`,height:`8`,viewBox:`-4 -4 8 8`,focusable:`false`,children:[(0,Q.jsxs)(`defs`,{children:[(0,Q.jsx)(Wt,{id:r,values:cn}),(0,Q.jsx)(It,{ref:c,id:`${r}-surface`,transform:`matrix(1 0 0 ${String(d)} 0 0)`}),(0,Q.jsxs)(`radialGradient`,{id:`${r}-drop-light`,gradientUnits:`userSpaceOnUse`,cx:`-1.2`,cy:`10.4`,r:`5.6`,children:[(0,Q.jsx)(`stop`,{offset:`0`,stopColor:`var(--color-white)`,style:{stopOpacity:`calc(var(--depth) * 0.5)`}}),(0,Q.jsx)(`stop`,{offset:`1`,stopColor:`var(--color-white)`,stopOpacity:`0`})]}),(0,Q.jsx)(ft,{id:`${r}-shadow`}),(0,Q.jsx)(`mask`,{id:`${r}-silhouette`,maskUnits:`userSpaceOnUse`,x:`-12`,y:`-24`,width:`24`,height:`48`,style:{maskType:`alpha`},children:(0,Q.jsxs)(`g`,{fill:`var(--color-white)`,filter:`url(#${r})`,children:[(0,Q.jsx)(`rect`,{ref:i,x:`-4`,y:u.y,width:`8`,height:u.height,rx:`4`}),(0,Q.jsx)(`circle`,{ref:a,cx:`0`,cy:u.cy,r:`4`})]})})]}),(0,Q.jsx)(`g`,{ref:o,filter:`url(#${r}-shadow)`,children:(0,Q.jsxs)(`g`,{mask:`url(#${r}-silhouette)`,children:[(0,Q.jsx)(`rect`,{x:`-12`,y:`-24`,width:`24`,height:`48`,fill:`url(#${r}-surface)`}),(0,Q.jsx)(`rect`,{ref:l,x:`-12`,y:`-24`,width:`24`,height:`48`,fill:`url(#${r}-drop-light)`,opacity:f})]})})]})}var ri=.28;function ii(e,t){switch(e){case`ring`:return{dashes:1,track:0,arc:0,sweep:0,disc:0,tick:0,cross:0};case`arc`:return{dashes:0,track:1,arc:1,sweep:t===void 0?ri:Math.min(1,Math.max(0,t)),disc:0,tick:0,cross:0};case`check`:return{dashes:0,track:0,arc:1,sweep:1,disc:1,tick:1,cross:0};case`cross`:return{dashes:0,track:0,arc:1,sweep:1,disc:1,tick:0,cross:1}}}var ai=7.25;function oi({className:e,glyph:t,progress:n}){let r=`caps-status-mark-${(0,q.useId)().replaceAll(`:`,``)}`,i=(0,q.useRef)(null),a=(0,q.useRef)(null),o=(0,q.useRef)(null),s=(0,q.useRef)(null),c=(0,q.useRef)(null),l=(0,q.useRef)(null),u=(0,q.useRef)(null),d=(0,q.useRef)(null),f=(0,q.useRef)(ii(t,n)).current,p=(0,q.useRef)(t),m=de();(0,q.useLayoutEffect)(()=>{let e=i.current,r=a.current,c=o.current,f=s.current,h=l.current,g=u.current,_=d.current;if(!e||!r||!c||!f||!h||!g||!_)return;let v=ii(t,n),y=p.current;p.current=t;let b=D(e),x=m||y===t&&t!==`arc`,S=x?m?{ease:b.ease,duration:b.fast}:X:Z(b,{ease:`outQuad`,duration:160}),C=(t===`check`||t===`cross`)&&!x,w=Z(b,{ease:`inOutSine`,duration:220}),T=[V(r,{opacity:v.dashes,...S}),V(c,{opacity:v.track*.28,...S}),V(f,{opacity:v.arc,"stroke-dasharray":`${String(v.sweep)} 1`,...x?m?X:S:w}),V(h,{r:v.disc*ai,...C?{delay:w.duration*.7,...ei(b,{bounce:.35,duration:360})}:m?X:Z(b,{ease:`inCubic`,duration:140})}),V(g,{"stroke-dashoffset":1-v.tick,...C&&v.tick>0?{delay:w.duration*.7+b.fast,...Z(b,{ease:`outCubic`,duration:240})}:X}),V(_,{"stroke-dashoffset":1-v.cross,...C&&v.cross>0?{delay:w.duration*.7+b.fast,...Z(b,{ease:`outCubic`,duration:240})}:X})];return t===`cross`&&C&&b.shake>0&&T.push(V(e,{translateX:[0,-b.shake,b.shake,-b.shake/2,0],delay:w.duration+b.fast,...Z(b,{ease:`linear`,duration:300})})),()=>{for(let e of T)e.cancel()}},[t,n,m]);let h=t===`arc`&&n===void 0&&!m;return(0,q.useLayoutEffect)(()=>{if(!h||!c.current||!i.current)return;let e=D(i.current),t=V(c.current,{rotate:[0,360],...Z(e,{ease:`linear`,duration:900}),loop:!0}),n=at(i.current,e=>{e?t.resume():t.pause()});return()=>{n(),t.revert()}},[h]),(0,Q.jsxs)(`svg`,{ref:i,"aria-hidden":`true`,className:`caps-status-mark ${e??``}`,viewBox:`0 0 16 16`,focusable:`false`,children:[(0,Q.jsxs)(`defs`,{children:[(0,Q.jsx)(It,{id:`${r}-surface`,transform:`matrix(1.6 0 0 1.6 8 8)`}),(0,Q.jsxs)(`mask`,{id:`${r}-knock`,maskUnits:`userSpaceOnUse`,x:`0`,y:`0`,width:`16`,height:`16`,children:[(0,Q.jsx)(`rect`,{width:`16`,height:`16`,fill:`var(--color-white)`}),(0,Q.jsx)(`path`,{ref:u,d:`M4.9 8.3 7.1 10.5 11.2 5.9`,fill:`none`,stroke:`var(--color-black)`,strokeWidth:`1.9`,strokeLinecap:`round`,strokeLinejoin:`round`,pathLength:1,strokeDasharray:`1 1`,strokeDashoffset:1-f.tick}),(0,Q.jsx)(`path`,{ref:d,d:`M5.4 5.4 10.6 10.6 M10.6 5.4 5.4 10.6`,fill:`none`,stroke:`var(--color-black)`,strokeWidth:`1.9`,strokeLinecap:`round`,pathLength:1,strokeDasharray:`1 1`,strokeDashoffset:1-f.cross})]})]}),(0,Q.jsx)(`circle`,{ref:a,cx:`8`,cy:`8`,r:`6.25`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeDasharray:`1.7 2.2`,opacity:f.dashes}),(0,Q.jsx)(`circle`,{ref:o,cx:`8`,cy:`8`,r:`6.25`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,opacity:f.track*.28}),(0,Q.jsx)(`g`,{ref:c,className:`caps-status-mark-spin`,children:(0,Q.jsx)(`circle`,{ref:s,cx:`8`,cy:`8`,r:`6.25`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,pathLength:1,strokeDasharray:`${String(f.sweep)} 1`,transform:`rotate(-90 8 8)`,opacity:f.arc})}),(0,Q.jsx)(`circle`,{ref:l,cx:`8`,cy:`8`,r:f.disc*ai,fill:`url(#${r}-surface)`,mask:`url(#${r}-knock)`})]})}var si=new Set([`ring`,`arc`,`check`,`cross`]);function ci(e){return si.has(e)}var li={neutral:`text-base-content`,primary:`text-primary`,secondary:`text-secondary`,accent:`text-accent`,success:`text-success`,info:`text-info`,warning:`text-warning`,error:`text-error`},ui=(0,q.forwardRef)(function({className:e,label:t,glyph:n=`dot`,motion:r=`none`,tone:i=`neutral`,size:a=`default`,appearance:o=`plain`,progress:s,...c},l){return(0,Q.jsxs)(`span`,{...c,className:z(`caps-status`,a===`compact`&&`caps-status-compact`,o===`chip`&&`caps-status-chip`,e),"data-tone":o===`chip`?i:void 0,"data-glyph":n,"data-motion":r,ref:l,children:[ci(n)?(0,Q.jsx)(oi,{className:li[i],glyph:n,progress:s}):(0,Q.jsx)(ni,{className:li[i],glyph:n,motion:r}),t===void 0?null:(0,Q.jsx)(`span`,{children:t})]})}),di={neutral:`progress-neutral`,primary:`progress-primary`,secondary:`progress-secondary`,accent:`progress-accent`,success:`progress-success`,info:`progress-info`,warning:`progress-warning`,error:`progress-error`},fi=(0,q.forwardRef)(function({className:e,tone:t=`primary`,...n},r){return(0,Q.jsx)(`progress`,{...n,"data-complete":n.value!==void 0&&Number(n.value)>=Number(n.max??1)?`true`:void 0,className:z(`progress caps-gooey-motion caps-gooey-progress w-full`,di[t],e),ref:r})});(0,q.forwardRef)(function({label:e,value:t,max:n,tone:r=`info`,className:i,...a},o){return(0,Q.jsxs)(`div`,{...a,ref:o,className:z(`caps-game-meter`,i),children:[(0,Q.jsxs)(`div`,{className:`caps-game-meter-readout`,children:[(0,Q.jsx)(`span`,{children:e}),(0,Q.jsxs)(`span`,{className:`caps-game-meter-value`,children:[t,` / `,n]})]}),(0,Q.jsx)(fi,{"aria-label":e,value:t,max:n,tone:r})]})});function pi({className:e,items:t,onCancel:n,onRemove:r,onRetry:i,rowClassName:a}){return t.length?(0,Q.jsx)(`div`,{"aria-live":`polite`,className:`caps-upload-queue flex w-full min-w-0 flex-col gap-sm ${e??``}`,"data-upload-rows":!0,children:t.map(e=>(0,Q.jsx)(gi,{item:e,onCancel:n,onRemove:r,onRetry:i,...a===void 0?{}:{rowClassName:a}},e.id))}):null}function mi({action:e,id:t,onAction:n,retry:r=!1}){return e?(0,Q.jsx)(Bt,{"aria-label":e.accessibleLabel,title:e.label,variant:`ghost`,size:`xs`,className:`motion-reduce:transition-none`,icon:r?(0,Q.jsx)(Nr,{}):(0,Q.jsx)(bn,{}),onClick:()=>void n(t),type:`button`}):null}function hi({item:e}){return(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsx)(`span`,{className:`block min-w-0 truncate`,title:e.name,children:e.name}),(0,Q.jsx)(`div`,{className:`caps-upload-details`,children:(0,Q.jsxs)(`span`,{"aria-live":e.alert?`assertive`:void 0,className:`caps-upload-status min-w-0 break-words`,"data-upload-status":!0,role:e.alert?`alert`:void 0,children:[e.alert??e.statusLabel,` `,e.progressLabel]})})]})}function gi({item:e,onCancel:t,onRemove:n,onRetry:r,rowClassName:i}){return(0,Q.jsxs)(`div`,{className:`caps-upload-row grid w-full min-w-0 max-w-full grid-cols-[2rem_minmax(0,1fr)_auto] items-center gap-sm p-sm text-xs ${i??``}`,children:[e.preview.kind===`image`?(0,Q.jsx)(`img`,{alt:``,className:`caps-upload-preview mask mask-squircle size-8 shrink-0 object-cover`,src:e.preview.url}):(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`caps-upload-preview mask mask-squircle flex size-8 shrink-0 items-center justify-center bg-base-300`,children:(0,Q.jsx)(jr,{className:`size-4`})}),(0,Q.jsx)(hi,{item:e}),(0,Q.jsx)(_i,{actions:e.actions,id:e.id,onCancel:t,onRemove:n,onRetry:r}),(0,Q.jsx)(fi,{"aria-label":`${e.name} progress`,className:`caps-upload-progress`,tone:e.alert?`error`:e.progress===100?`success`:`accent`,max:100,value:e.progress??(e.alert?0:void 0)})]})}function _i({actions:e,id:t,onCancel:n,onRemove:r,onRetry:i}){return(0,Q.jsxs)(`div`,{className:`caps-upload-actions flex min-w-0 flex-wrap justify-end gap-xs`,children:[(0,Q.jsx)(mi,{action:e.retry,id:t,onAction:i,retry:!0}),(0,Q.jsx)(mi,{action:e.cancel,id:t,onAction:n}),(0,Q.jsx)(mi,{action:e.remove,id:t,onAction:r})]})}var vi={unchecked:`M3.25 5.9 L5.1 7.9 L8.8 3.8`,checked:`M3.25 5.9 L5.1 7.9 L8.8 3.8`,mixed:`M3.4 6 L6 6 L8.6 6`},yi={blurStdDeviation:.22,alphaSlope:18,alphaIntercept:-8};function bi({state:e}){let t=`caps-checkbox-${(0,q.useId)().replaceAll(`:`,``)}`,n=(0,q.useRef)(null),r=(0,q.useRef)(e).current,i=(0,q.useRef)(e),a=de();return(0,q.useLayoutEffect)(()=>{if(!n.current)return;let t=e!==`unchecked`,r=i.current!==`unchecked`,o=a||i.current===e;i.current=e;let s=D(n.current),c=Z(s,{ease:`inCubic`,duration:160}),l=V(n.current,{d:{to:vi[e],...o?X:Z(s,{ease:`outCubic`,duration:200})},"stroke-dashoffset":{to:+!t,...o?X:t?Z(s,{ease:`inOutSine`,duration:260}):c},"stroke-width":o?{to:t?2.4:0,duration:0}:t&&!r?[{to:2.2,...Z(s,{ease:`outCubic`,duration:65})},{to:2.4,delay:Oe(s,120),...ei(s,{bounce:.35,duration:220})}]:{to:t?2.4:0,...c}});return()=>{l.cancel()}},[e,a]),(0,Q.jsxs)(`svg`,{className:`caps-checkbox-visual`,width:`24`,height:`24`,viewBox:`0 0 12 12`,"aria-hidden":`true`,focusable:`false`,children:[(0,Q.jsxs)(`defs`,{children:[(0,Q.jsx)(It,{id:`${t}-surface`,transform:`matrix(1 0 0 1 6 6)`}),(0,Q.jsx)(ft,{id:`${t}-shadow`}),(0,Q.jsx)(tn,{id:`${t}-inset`}),(0,Q.jsx)(Wt,{id:`${t}-goo`,values:yi}),(0,Q.jsxs)(`filter`,{id:`${t}-relief`,x:`-25%`,y:`-25%`,width:`150%`,height:`150%`,colorInterpolationFilters:`sRGB`,children:[(0,Q.jsx)(`feGaussianBlur`,{in:`SourceAlpha`,stdDeviation:`0.28`,result:`relief`}),(0,Q.jsx)(`feSpecularLighting`,{in:`relief`,surfaceScale:`1.2`,specularConstant:`0.55`,specularExponent:`18`,lightingColor:`color-mix(in srgb, var(--color-white) calc(var(--depth) * 100%), var(--color-black))`,result:`light`,children:(0,Q.jsx)(`feDistantLight`,{azimuth:`225`,elevation:`55`})}),(0,Q.jsx)(`feComposite`,{in:`light`,in2:`SourceAlpha`,operator:`in`,result:`clipped-light`}),(0,Q.jsx)(`feBlend`,{in:`SourceGraphic`,in2:`clipped-light`,mode:`screen`})]}),(0,Q.jsx)(`mask`,{id:`${t}-contour`,maskUnits:`userSpaceOnUse`,x:`0`,y:`0`,width:`12`,height:`12`,style:{maskType:`alpha`},children:(0,Q.jsx)(`path`,{ref:n,d:vi[r],fill:`none`,stroke:`var(--color-white)`,strokeWidth:r===`unchecked`?0:2.4,pathLength:`1`,strokeDasharray:`1`,strokeDashoffset:+(r===`unchecked`),strokeLinecap:`round`,strokeLinejoin:`round`,filter:e===`mixed`?void 0:`url(#${t}-goo)`})}),(0,Q.jsx)(`clipPath`,{id:`${t}-well`,children:(0,Q.jsx)(`rect`,{x:`1`,y:`1`,width:`10`,height:`10`,rx:`2.5`})})]}),(0,Q.jsx)(`rect`,{className:`caps-checkbox-track`,x:`0.5`,y:`0.5`,width:`11`,height:`11`,rx:`3`,filter:`url(#${t}-inset)`}),(0,Q.jsx)(`g`,{clipPath:`url(#${t}-well)`,children:(0,Q.jsx)(`g`,{filter:`url(#${t}-shadow)`,children:(0,Q.jsx)(`g`,{filter:`url(#${t}-relief)`,children:(0,Q.jsx)(`g`,{mask:`url(#${t}-contour)`,children:(0,Q.jsx)(`rect`,{x:`0`,y:`0`,width:`12`,height:`12`,fill:`url(#${t}-surface)`})})})})})]})}var xi=(0,q.forwardRef)(function({className:e,appearance:t,indicator:n,invalid:r,indeterminate:i=!1,checked:a,defaultChecked:o=!1,onChange:s,...c},l){let u=(0,q.useRef)(null),[d,f]=(0,q.useState)(o),p=a??d,m=i?`mixed`:p?`checked`:`unchecked`;return(0,q.useImperativeHandle)(l,()=>{if(!u.current)throw Error(`Checkbox input is not mounted`);return u.current},[]),(0,q.useLayoutEffect)(()=>{u.current&&(u.current.indeterminate=i)},[i]),(0,q.useEffect)(()=>{let e=u.current?.form;if(!e||a!==void 0)return;let t=e=>{queueMicrotask(()=>{!e.defaultPrevented&&u.current&&f(o)})};return e.addEventListener(`reset`,t),()=>{e.removeEventListener(`reset`,t)}},[a,o,c.form]),(0,Q.jsxs)(`span`,{className:`caps-checkbox`,"data-appearance":t===`compact`?t:void 0,"data-state":m,"data-custom-indicator":n!==void 0||void 0,children:[(0,Q.jsx)(`input`,{...c,checked:p,"aria-checked":i?`mixed`:p,"aria-invalid":r?!0:c[`aria-invalid`]===!1?void 0:c[`aria-invalid`],className:z(`caps-checkbox-input`,e),onChange:e=>{a===void 0&&f(e.target.checked),s?.(e),e.currentTarget.indeterminate=i},ref:u,type:`checkbox`}),n===void 0?(0,Q.jsx)(bi,{state:m}):n]})}),Si=Tr({keyCode:Dr(229)});function Ci(e){return e.nativeEvent.isComposing||be(Si,e.nativeEvent).success}var wi=q.createContext(void 0);function Ti(e){let t=q.useContext(wi);if(t===void 0&&!e)throw Error(rn(47));return t}var Ei={...mn,disabled:e=>e.disabled,instantType:e=>e.instantType===`trigger-change`&&!mn.open(e)?void 0:e.instantType,openMethod:e=>e.openMethod,openChangeReason:e=>e.openChangeReason,isPressOpenedByTrigger:(e,t)=>e.openChangeReason===`trigger-press`&&mn.isOpenedByTrigger(e,t),isTouchPressOpen:(e,t)=>t&&e.openMethod===`touch`&&e.openChangeReason===`trigger-press`,hasTriggerFocusGuards:(e,t)=>mn.isOpenedByTrigger(e,t)&&!e.focusManagerModal,modal:e=>e.modal,titleElementId:e=>e.titleElementId,descriptionElementId:e=>e.descriptionElementId,openOnHover:e=>e.openOnHover,closeDelay:e=>e.closeDelay,adaptiveOrigin:e=>e.adaptiveOrigin},Di=class extends Ne{constructor(e,t,n){let r=new x;super(Oi(e,r,t,n),ki(r),Ei)}setOpen=(e,t)=>{let n=t.reason===h,r=t.reason===`trigger-press`&&t.event.detail===0,a=!e&&(t.reason===`escape-key`||t.reason==null),o=i(t),s=this.select(`activeTriggerId`);if(!e&&t.reason===`close-press`&&t.trigger==null&&s!=null&&(t.trigger=this.context.triggerElements.getById(s)??this.select(`activeTriggerElement`)??void 0),this.context.onOpenChange?.(e,t),t.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(e,t);let c=()=>{let n=pe(this.state,e,t.trigger,o());n.openChangeReason=t.reason,this.update(n)};n?(this.context.stickIfOpen=!0,this.context.stickIfOpenTimeout.start(500,()=>{this.context.stickIfOpen=!1}),Lr.flushSync(c)):c();let l;r?l=`click`:a?l=`dismiss`:t.reason===`focus-out`&&(l=`focus`),this.set(`instantType`,l)}};function Oi(e,t,n,r=!1){let i={...ct(t,n,r),disabled:!1,modal:!1,focusManagerModal:!1,instantType:void 0,openMethod:null,openChangeReason:null,titleElementId:void 0,descriptionElementId:void 0,openOnHover:!1,closeDelay:0,adaptiveOrigin:void 0,...e};return i.open&&e?.mounted===void 0&&(i.mounted=!0),i}function ki(e){return{popupRef:q.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerFocusTargetRef:q.createRef(),beforeTriggerFocusGuardRef:q.createRef(),beforeContentFocusGuardRef:q.createRef(),stickIfOpenTimeout:new Jt,stickIfOpen:!0,triggerElements:e}}var Ai=p(function({props:e}){let{children:t,open:n,defaultOpen:r=!1,onOpenChange:i,onOpenChangeComplete:a,modal:o=!1,handle:s,triggerId:c,defaultTriggerId:l=null}=e,u=Mi(s,{modal:o,open:r,openProp:n,activeTriggerId:l,triggerIdProp:c});u.useControlledProp(`openProp`,n),u.useControlledProp(`triggerIdProp`,c);let d=u.useState(`open`),f=u.useState(`mounted`),p=u.useState(`payload`);u.useContextCallback(`onOpenChange`,i),u.useContextCallback(`onOpenChangeComplete`,a),le(u,d),_e(u);let{forceUnmount:m}=Ee(d,u,()=>{u.context.stickIfOpen=!0,u.set(`openChangeReason`,null)});u.useSyncedValues({modal:o}),q.useEffect(()=>{d||u.context.stickIfOpenTimeout.clear()},[u,d]),q.useImperativeHandle(e.actionsRef,()=>({unmount:m,close:()=>u.setOpen(!1,R(gn))}),[m,u]);let h=d||f||s!=null;return(0,Q.jsxs)(wi.Provider,{value:u,children:[s&&(0,Q.jsx)(xe,{handle:s,store:u}),h&&(0,Q.jsx)(Ni,{store:u,modal:o}),typeof t==`function`?t({payload:p}):t]})});function ji(e){return Ti(!0)?(0,Q.jsx)(Ai,{props:e}):(0,Q.jsx)(k,{children:(0,Q.jsx)(Ai,{props:e})})}function Mi(e,t){let n=F((e,n)=>new Di(t,e,n));return q.useEffect(()=>n.context.stickIfOpenTimeout.disposeEffect(),[n]),n}function Ni({store:e,modal:t}){let n=e.useState(`floatingRootContext`),r=ze(n,{outsidePressEvent:{mouse:t===`trap-focus`?`sloppy`:`intentional`,touch:`sloppy`}}),i=r.reference,a=r.floating;return T(e,{activeTriggerProps:i,inactiveTriggerProps:i,popupProps:a}),null}function Pi(e,t){function n(n,r,i){let a=n.currentTarget;Lr.flushSync(()=>{e.setOpen(!1,R(dt,n.nativeEvent,a))}),on(a.isConnected?a:t.current,r,i)?.focus()}function r(t){n(t,-1,e.select(`positionerElement`))}function i(t){let r=e.select(`positionerElement`);r&&Ht(t,r)?e.context.beforeContentFocusGuardRef.current?.focus():n(t,1,r)}return{handlePreFocusGuardFocus:r,handleFocusTargetFocus:i}}var Fi=dn(function(e,t){let{render:n,className:r,style:i,disabled:a=!1,nativeButton:o=!0,handle:s,payload:c,openOnHover:l=!1,delay:u=300,closeDelay:d=0,id:f,...p}=e,m=Ti(!0),h=_n(s)??m;if(!h)throw Error(rn(74));let g=St(f),_=h.useState(`isTriggerActive`,g),v=h.useState(`floatingRootContext`),y=h.useState(`isOpenedByTrigger`,g),b=h.useState(`triggerPopupId`,g),x=q.useRef(null),{registerTrigger:S,isMountedByThisTrigger:C}=je(g,x,h,{payload:c,disabled:a,openOnHover:l,closeDelay:d}),T=h.useState(`isPressOpenedByTrigger`,g),E=h.useState(`isTouchPressOpen`,l),D=h.useState(`hasTriggerFocusGuards`,g),O=zr(v,{enabled:!a&&l&&!E,mouseOnly:!0,move:!1,handleClose:Kr(),restMs:u,delay:{close:d},triggerElementRef:x,isActiveTrigger:_,isClosing:()=>h.select(`transitionStatus`)===`ending`}),k=W(()=>h.context.stickIfOpen),A=M(v,{stickIfOpen:k}),j=Lt(()=>h.select(`open`),e=>{h.set(`openMethod`,e)}),N=h.useState(`triggerProps`,C),{getButtonProps:ee,buttonRef:P}=w({disabled:a,native:o}),F={open(e){return T?Ze.open(e):qe.open(e)}},{handlePreFocusGuardFocus:te,handleFocusTargetFocus:ne}=Pi(h,x),re=tt(`button`,e,{state:{disabled:a,open:y},ref:[P,t,S,x],props:[A.reference,O,N,j,{[Qe]:``,id:g,"aria-haspopup":`dialog`,"aria-expanded":y,"aria-controls":b},p,ee],stateAttributesMapping:F}),ie=(0,Q.jsx)(q.Fragment,{children:re},g);return D?(0,Q.jsxs)(q.Fragment,{children:[(0,Q.jsx)($t,{ref:h.context.beforeTriggerFocusGuardRef,onFocus:te}),ie,(0,Q.jsx)($t,{ref:h.context.triggerFocusTargetRef,onFocus:ne})]}):ie}),Ii=q.createContext(void 0);function Li(){let e=q.useContext(Ii);if(e===void 0)throw Error(rn(45));return e}var Ri=q.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e;return Ti().useState(`mounted`)||n?(0,Q.jsx)(Ii.Provider,{value:n,children:(0,Q.jsx)(Je,{ref:t,...r})}):null}),zi=q.createContext(void 0);function Bi(){let e=q.useContext(zi);if(!e)throw Error(rn(46));return e}function Vi(e){let{store:t,domReference:n,positionerElement:r,open:i}=e,a=q.useRef(null),o=q.useRef(null),s=c(r);Te(()=>{i||(o.current?.abort(),o.current=null,t.state.instantType===`trigger-change`&&t.set(`instantType`,void 0))},[i,t]),Te(()=>{let e=n,r=a.current;if(e&&(a.current=e),!r||!e||e===r||!t.select(`open`))return;t.set(`instantType`,void 0);let i=new AbortController;return o.current=i,s(()=>{t.select(`open`)&&t.set(`instantType`,`trigger-change`)},i.signal),()=>{i.abort()}},[n,s,t])}var Hi=20;function Ui(e,t,n,r){let[i,a]=q.useState(!1);Te(()=>{if(!e||!t||n==null){a(!1);return}let r=b(n).documentElement.clientWidth,i=n.offsetWidth;a(r>0&&i>0&&i>=r-Hi)},[e,t,n]),Ct(e&&(!t||i),r)}var Wi=q.forwardRef(function(e,n){let{render:r,className:i,style:a,anchor:o,positionMethod:s,side:c,align:l,sideOffset:u,alignOffset:d,collisionBoundary:f=`clipping-ancestors`,collisionPadding:p,arrowPadding:m,sticky:h,disableAnchorTracking:g=!1,collisionAvoidance:_=t,...v}=e,y=Ti(),b=Li(),x=ce(),S=y.useState(`floatingRootContext`),C=y.useState(`mounted`),w=y.useState(`open`),T=y.useState(`openChangeReason`),E=y.useState(`activeTriggerElement`),D=y.useState(`modal`),O=y.useState(`openMethod`),k=y.useState(`positionerElement`),A=y.useState(`instantType`),j=y.useState(`transitionStatus`),M=y.useState(`adaptiveOrigin`),N=ir({anchor:o,floatingRootContext:S,positionMethod:s,mounted:C,side:c,sideOffset:u,align:l,alignOffset:d,arrowPadding:m,collisionBoundary:f,collisionPadding:p,sticky:h,disableAnchorTracking:g,keepMounted:b,nodeId:x,collisionAvoidance:_,adaptiveOrigin:M});Vi({store:y,domReference:S.useState(`domReferenceElement`),positionerElement:k,open:w});let ee=D===!0&&T!==`trigger-hover`;Ui(w&&ee,O===`touch`,k,E);let P=y.useStateSetter(`positionerElement`),F={open:w,side:N.side,align:N.align,anchorHidden:N.anchorHidden,instant:A},te=ur(e,F,{styles:N.positionerStyles,transitionStatus:j,props:v,refs:[n,P],hidden:!C,inert:!w});return(0,Q.jsxs)(zi.Provider,{value:N,children:[C&&ee&&(0,Q.jsx)(xt,{inert:nt(!w),cutout:E}),(0,Q.jsx)(Ue,{id:x,children:te})]})}),Gi=q.createContext(void 0);function Ki(e){let t=q.useContext(Gi);if(t===void 0&&!e)throw Error(rn(69));return t}var qi=q.createContext(void 0);function Ji(){let[e,t]=q.useState(0),n=W(()=>(t(e=>e+1),()=>{t(e=>Math.max(0,e-1))}));return{context:q.useMemo(()=>({register:n}),[n]),hasClosePart:e>0}}var Yi=q.forwardRef(function(e,t){let{render:n,className:r,style:i,initialFocus:a,finalFocus:o,...s}=e,c=Ti(),l=Bi(),u=Ki(!0)!=null,{context:d,hasClosePart:f}=Ji(),p=c.useState(`open`),m=c.useState(`openMethod`),h=c.useState(`instantType`),_=c.useState(`transitionStatus`),v=c.useState(`popupProps`),y=c.useState(`titleElementId`),b=c.useState(`descriptionElementId`),x=c.useState(`modal`),S=c.useState(`mounted`),C=c.useState(`openChangeReason`),w=c.useState(`activeTriggerElement`),T=c.useState(`floatingRootContext`),E=T.useState(`floatingId`),D=c.useState(`disabled`),O=c.useState(`openOnHover`),k=c.useState(`closeDelay`);yn({open:p,ref:c.context.popupRef,onComplete(){p&&c.context.onOpenChangeComplete?.(!0)}}),Zn(T,{enabled:O&&!D,closeDelay:k});let A=a===void 0?Ot(c.context.popupRef):a,j=x!==!1&&f;c.useSyncedValue(`focusManagerModal`,j);let M=c.useStateSetter(`popupElement`),N={open:p,side:l.side,align:l.align,instant:h,transitionStatus:_},ee=tt(`div`,e,{state:N,ref:[t,c.context.popupRef,M],props:[v,{id:E,role:`dialog`,...g,"aria-labelledby":y,"aria-describedby":b,onKeyDown(e){u&&ln.has(e.key)&&e.stopPropagation()}},sr(_),s],stateAttributesMapping:se});return(0,Q.jsx)(Ie,{context:T,openInteractionType:m,modal:j,disabled:!S||C===`trigger-hover`,initialFocus:A,returnFocus:o,restoreFocus:`popup`,getInsideElements:()=>[c.context.beforeTriggerFocusGuardRef.current],previousFocusableElement:He(w)?w:void 0,nextFocusableElement:c.context.triggerFocusTargetRef,beforeContentFocusGuardRef:c.context.beforeContentFocusGuardRef,children:(0,Q.jsx)(qi.Provider,{value:d,children:ee})})}),Xi=`data-glide-stand-in`;function Zi(e,t){let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();return{x:r.left-n.left+e.scrollLeft-e.clientLeft,y:r.top-n.top+e.scrollTop-e.clientTop,width:r.width,height:r.height}}function Qi(e){return{transform:`translate(${String(e.x)}px, ${String(e.y)}px)`,width:`${String(e.width)}px`,height:`${String(e.height)}px`}}function $i(e){let t=(0,q.useRef)(null);return(0,q.useCallback)(n=>{t.current?.(),t.current=n?ea(n,e):null},[e])}function ea(e,t){if(!o(e))return()=>void 0;let n=e.ownerDocument,r=e.querySelector(t),i=r?Zi(e,r):null,a=null,s=null,c=new Set,l=()=>{for(let e of c)e.removeAttribute(Xi);c.clear(),a&&(a.hidden=!0),s=null},u=()=>{if(a)return a;let t=n.createElement(`span`);return t.className=`caps-glide`,t.setAttribute(`aria-hidden`,`true`),e.prepend(t),e.classList.add(`caps-glide-host`),getComputedStyle(e).position===`static`&&e.classList.add(`caps-glide-anchor`),a=t,t},d=(t,n)=>{let r=D(e),o=Zi(e,t),d=s&&a?Zi(e,a):i;if(i=o,s?.cancel(),l(),r.reduced||d===null||Math.abs(d.y-o.y)<1&&Math.abs(d.x-o.x)<1)return;t.setAttribute(Xi,`measure`);let f=getComputedStyle(t),p=f.backgroundColor,m=f.borderRadius;for(let e of[t,n])e&&(e.setAttribute(Xi,``),c.add(e));let h=u();h.hidden=!1,h.style.backgroundColor=p,h.style.borderRadius=m;let g=h.animate([Qi(d),Qi(o)],{duration:r.normal,easing:he(r,r.ease),fill:`forwards`});s=g,g.addEventListener(`finish`,()=>{s===g&&l()})},f=()=>{let n=e.querySelector(t);if(n===r)return;let i=r;r=n,n&&d(n,i)},p=new MutationObserver(f);return p.observe(e,{subtree:!0,attributes:!0,attributeFilter:[`data-highlighted`,`data-active`,`data-navigation`,`aria-selected`]}),e.addEventListener(`pointerover`,f),e.addEventListener(`pointerout`,f),()=>{p.disconnect(),e.removeEventListener(`pointerover`,f),e.removeEventListener(`pointerout`,f),s?.cancel(),l(),a?.remove()}}function ta({getKey:e,isDisabled:t=()=>!1,items:n}){let r=(0,q.useMemo)(()=>{let r=n.map(e);if(r.some(e=>!e))throw Error(`Selectable items require non-empty keys`);if(new Set(r).size!==r.length)throw Error(`Selectable items require unique keys`);return n.filter(e=>!t(e))},[e,t,n]),[i,a]=(0,q.useState)(null);(0,q.useEffect)(()=>{i!==null&&!r.some(t=>e(t)===i)&&a(null)},[i,r,e]);let o=r.find(t=>e(t)===i),s=o?r.findIndex(t=>e(t)===i):-1;return{activeIndex:s,activeItem:o,activeKey:i,enabledItems:r,move:(t,n)=>{if(r.length===0)return;let i=n?n===`start`?0:r.length-1:s<0?t>0?0:r.length-1:(s+t+r.length)%r.length,o=r[i];o&&a(e(o))},setActiveKey:a}}var na=(0,q.forwardRef)(function({children:e,className:t,type:n=`button`,...r},i){return(0,Q.jsxs)(`button`,{...r,ref:i,type:n,className:z(`select caps-select caps-combobox-trigger w-full`,t),children:[(0,Q.jsx)(`span`,{children:e}),(0,Q.jsx)(kr,{className:`caps-select-chevron`,"aria-hidden":`true`})]})});function ra({defaultOpen:e,defaultValue:t,getKey:n,getSearchText:r,groupBy:i,id:a,isDisabled:o,items:s,onOpenChange:c,onCommit:l,multiple:u,controlledOpen:d,controlledKeys:f,trigger:p}){let m=`${a}-listbox`,[h,g]=(0,q.useState)(``),[_,v]=(0,q.useState)(!1),[y,b]=(0,q.useState)(t),[x,S]=(0,q.useState)(e),C=f??(y===null?[]:[y]),w=p?d??x:!0,T=(0,q.useMemo)(()=>{let e=h.trim().toLowerCase();return e?s.filter(t=>r(t).toLowerCase().includes(e)):s},[r,s,h]),E=ta({getKey:n,isDisabled:o,items:T});(0,q.useEffect)(()=>{if(E.activeKey!==null)return;let e=E.enabledItems.find(e=>C.includes(n(e)))??E.enabledItems[0];e&&E.setActiveKey(n(e))},[E.activeKey,E.enabledItems,E.setActiveKey,n,C]);let D=e=>{v(!1),e||g(``),d===void 0&&S(e),c?.(e)},O=e=>`${m}-option-${encodeURIComponent(e)}`,k=e=>{let t=n(e);f===void 0&&b(t),l(e),p&&!u&&D(!1)},A=e=>{v(!0),g(e.target.value),E.setActiveKey(null)},j=e=>{if(Ci(e))return;let t;switch(e.key){case`ArrowDown`:t=[1,void 0];break;case`ArrowUp`:t=[-1,void 0];break;case`End`:t=[1,`end`];break;case`Home`:t=[-1,`start`]}t?(v(!0),e.preventDefault(),E.move(t[0],t[1])):e.key===`Enter`&&E.activeItem&&(e.preventDefault(),k(E.activeItem))},M=(0,q.useMemo)(()=>{if(!i)return[{label:``,items:T}];let e=new Map;for(let t of T){let n=i(t),r=e.get(n);r?r.push(t):e.set(n,[t])}return[...e].map(([e,t])=>({label:e,items:t}))},[T,i]);return{keyboardNavigation:_,onPointerMove:()=>{v(!1)},activeKey:E.activeKey,activeItem:E.activeItem,groups:M,inputValue:h,listboxId:m,onInputChange:A,onInputKeyDown:j,optionId:O,open:w,commit:k,selectedKeys:C,setOpen:D}}function ia(e){let{"aria-describedby":t,"aria-invalid":n,"aria-label":r,"aria-labelledby":i,"aria-required":a,activeTone:o=`neutral`,container:s,contentClassName:c,defaultOpen:l=!1,defaultValue:u=null,emptyMessage:d=`No matches`,getKey:f,getLabel:p,getSearchText:m=p,groupBy:h,id:g,inputProps:_,inputRef:v,isDisabled:y=()=>!1,items:b,onOpenChange:x,onValueChange:S,multiple:C,open:w,placeholder:T=`Search…`,renderItem:E,rootRef:D,trigger:O,triggerRef:k,value:A,...j}=e,M=e=>{let t=f(e);if(C){let e=A.includes(t)?A.filter(e=>e!==t):[...A,t];S?.(e,b.filter(t=>e.includes(f(t))))}else S?.(t,e)},N;C?N=A:A!==void 0&&(N=A===null?[]:[A]);let ee=(0,q.useId)(),P=O?.props??_,F=g??P?.id??ee,te={id:F,"aria-describedby":[t,P?.[`aria-describedby`]].filter(Boolean).join(` `)||void 0,"aria-invalid":n??P?.[`aria-invalid`],"aria-label":P?.[`aria-label`]??r,"aria-labelledby":P?.[`aria-labelledby`]??i,"aria-required":a??P?.[`aria-required`]},{keyboardNavigation:ne,onPointerMove:re,activeItem:ie,activeKey:ae,commit:oe,groups:se,inputValue:ce,listboxId:le,onInputChange:ue,onInputKeyDown:de,open:fe,optionId:pe,selectedKeys:me,setOpen:he}=ra({defaultOpen:l,defaultValue:u,getKey:f,getSearchText:m,groupBy:h,id:F,isDisabled:y,items:b,onOpenChange:x,onCommit:M,multiple:C??!1,controlledOpen:w,controlledKeys:N,trigger:O});vt(()=>{O&&he(!1)});let ge=Kt(`popover`),_e=s===void 0?ge:s,ve=$i(`.caps-combobox-option[data-active="true"]:not(:disabled), [data-navigation="pointer"] .caps-combobox-option:hover:not(:disabled)`),ye=(0,Q.jsx)(rr,{..._,...O?{}:te,"aria-activedescendant":ie?pe(f(ie)):void 0,"aria-autocomplete":`list`,"aria-controls":le,"aria-expanded":!0,className:z(`input-sm`,_?.className),id:O?_?.id??`${F}-input`:F,onChange:e=>{_?.onChange?.(e),ue(e)},onKeyDown:e=>{_?.onKeyDown?.(e),e.defaultPrevented||de(e)},placeholder:_?.placeholder??T,ref:v,role:`combobox`,value:ce}),be=(0,Q.jsx)(`div`,{id:le,ref:ve,className:`caps-combobox-list`,"data-navigation":ne?`keyboard`:`pointer`,onPointerMove:re,role:`listbox`,"aria-multiselectable":C??void 0,children:se.every(e=>e.items.length===0)?(0,Q.jsx)(`div`,{className:`px-md py-md text-sm text-base-content`,children:d}):se.map(e=>(0,Q.jsxs)(`div`,{"aria-label":e.label||void 0,role:e.label?`group`:void 0,children:[e.label?(0,Q.jsx)(`div`,{className:`px-md pb-xs pt-sm text-xs text-base-content uppercase tracking-wider`,children:e.label}):null,e.items.map(e=>{let t=f(e),n=y(e),r=ae===t,i={active:r,disabled:n,selected:me.includes(t)};return(0,Q.jsxs)(`button`,{"aria-disabled":n||void 0,"aria-selected":i.selected,className:`caps-combobox-option`,"data-active":r&&ne,disabled:n,id:pe(t),onClick:()=>{oe(e)},onMouseDown:e=>{e.preventDefault()},role:`option`,tabIndex:-1,type:`button`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`caps-combobox-check`,children:i.selected?(0,Q.jsx)(Or,{}):null}),E?.(e,r,i)??p(e)]},t)})]},e.label))});return O?(0,Q.jsx)(`div`,{...j,className:z(j.className),ref:D,children:(0,Q.jsxs)(ji,{modal:!0,onOpenChange:he,open:fe,children:[(0,Q.jsx)(Fi,{...te,"aria-haspopup":`dialog`,className:`btn`,ref:k,render:O}),_e===null?null:(0,Q.jsx)(Ri,{container:_e,children:(0,Q.jsx)(Wi,{align:`start`,side:`bottom`,sideOffset:4,children:(0,Q.jsxs)(Yi,{"data-active-tone":o,className:z(`min-w-40 rounded-box border border-base-300 bg-base-100 p-xs shadow-lg outline-none caps-combobox-panel caps-combobox-popup`,c),children:[(0,Q.jsx)(`div`,{className:`caps-combobox-search`,children:ye}),be]})})})]})}):(0,Q.jsx)(`div`,{...j,className:z(j.className),ref:D,children:(0,Q.jsxs)(`div`,{className:z(`caps-combobox-panel`,c),"data-active-tone":o,children:[(0,Q.jsx)(`div`,{className:`caps-combobox-search`,children:ye}),be]})})}function aa({icon:e,caption:t}){return(0,Q.jsxs)(`span`,{className:`caps-icon-choice-mark`,"aria-hidden":`true`,children:[(0,Q.jsx)(`span`,{className:`caps-icon-choice-art`,children:e}),t?(0,Q.jsx)(`span`,{className:`caps-icon-choice-caption`,children:t}):null,(0,Q.jsx)(`span`,{className:`caps-icon-choice-lamp`})]})}var oa=(0,q.forwardRef)(function({label:e,icon:t,caption:n,appearance:r,className:i,...a},o){return(0,Q.jsx)(`label`,{className:`caps-icon-choice`,"data-appearance":r===`compact`?r:void 0,children:(0,Q.jsx)(xi,{...a,appearance:r??`default`,"aria-label":e,className:z(`caps-icon-choice-input`,i),indicator:(0,Q.jsx)(aa,{icon:t,caption:n}),ref:o})})}),sa=(0,q.forwardRef)(function({label:e,icon:t,hint:n,className:r,...i},a){let o=(0,q.useId)(),s=[i[`aria-describedby`],n?o:null].filter(Boolean).join(` `)||void 0;return(0,Q.jsx)(`label`,{className:`caps-check-key`,children:(0,Q.jsx)(xi,{...i,"aria-label":e,"aria-describedby":s,className:z(`caps-check-key-input`,r),indicator:(0,Q.jsxs)(`span`,{className:`caps-check-key-face`,"aria-hidden":`true`,children:[t?(0,Q.jsx)(`span`,{className:`caps-check-key-icon`,children:t}):null,(0,Q.jsxs)(`span`,{className:`caps-check-key-copy`,children:[(0,Q.jsx)(`span`,{className:`caps-check-key-label`,children:e}),n?(0,Q.jsx)(`span`,{className:`caps-check-key-hint`,id:o,children:n}):null]}),(0,Q.jsx)(`span`,{className:`caps-check-key-lamp`})]}),ref:a})})});function ca({className:e,...t}){return(0,Q.jsx)(`div`,{...t,className:z(`caps-check-keys`,e)})}function la({checked:e}){let t=`caps-radio-${(0,q.useId)().replaceAll(`:`,``)}`,n=(0,q.useRef)(null),r=(0,q.useRef)(e).current,i=(0,q.useRef)(e),a=(0,q.useRef)(null),o=ne(a),{reduced:s}=o;return(0,q.useLayoutEffect)(()=>{if(!n.current)return;let t=s||i.current===e;i.current=e;let r=e?4:0,a=Z(o,{ease:`outCubic`,duration:75}),c=e?ei(o,{bounce:.65,duration:300}):Z(o,{ease:`inCubic`,duration:100}),l=V(n.current,t?{rx:r,ry:r,cy:6,duration:0}:{rx:[{to:e?3.5:4.15,...a},{to:r,...c}],ry:[{to:e?4.5:3.85,...a},{to:r,...c}],cy:[{to:e?5.85:6.1,...a},{to:6,...c}]});return()=>{l.cancel()}},[e,s,o]),(0,Q.jsxs)(`svg`,{ref:a,className:`caps-radio-visual`,width:`24`,height:`24`,viewBox:`0 0 12 12`,"aria-hidden":`true`,focusable:`false`,children:[(0,Q.jsxs)(`defs`,{children:[(0,Q.jsx)(It,{id:`${t}-surface`,transform:`matrix(1 0 0 1 6 6)`}),(0,Q.jsx)(ft,{id:`${t}-shadow`}),(0,Q.jsx)(tn,{id:`${t}-inset`}),(0,Q.jsx)(`clipPath`,{id:`${t}-well`,children:(0,Q.jsx)(`circle`,{cx:`6`,cy:`6`,r:`5`})})]}),(0,Q.jsx)(`circle`,{className:`caps-radio-track`,cx:`6`,cy:`6`,r:`5.5`,filter:`url(#${t}-inset)`}),(0,Q.jsx)(`g`,{clipPath:`url(#${t}-well)`,children:(0,Q.jsx)(`ellipse`,{ref:n,cx:`6`,cy:`6`,rx:r?4:0,ry:r?4:0,fill:`url(#${t}-surface)`,filter:`url(#${t}-shadow)`})})]})}var ua=(0,q.createContext)(null),da=(0,q.forwardRef)(function({children:e,className:t,defaultValue:n,disabled:r=!1,name:i,onValueChange:a,orientation:o=`vertical`,value:s,...c},l){let u=(0,q.useId)(),d=(0,q.useRef)(null);(0,q.useImperativeHandle)(l,()=>{if(!d.current)throw Error(`RadioGroup is not mounted`);return d.current},[]);let f=i??`radio-group-${u}`,[p,m]=(0,q.useState)(n),h=s??p;return(0,q.useEffect)(()=>{let e=d.current?.form;if(!e||s!==void 0)return;let t=e=>{queueMicrotask(()=>{e.defaultPrevented||m(n)})};return e.addEventListener(`reset`,t),()=>{e.removeEventListener(`reset`,t)}},[s,n,c.form]),(0,Q.jsx)(ua.Provider,{value:{disabled:r,name:f,onValueChange:e=>{s===void 0&&m(e),a?.(e)},value:h},children:(0,Q.jsx)(`fieldset`,{...c,className:z(`flex gap-md`,o===`horizontal`?`flex-row flex-wrap`:`flex-col`,t),disabled:r,role:c.role??`radiogroup`,ref:d,children:e})})}),fa=(0,q.forwardRef)(function({className:e,indicator:t,onChange:n,onClick:r,value:i,...a},o){let s=(0,q.useContext)(ua);if(!s)throw Error(`RadioGroupItem must be used inside <RadioGroup>`);let c=s.value===i,l=e=>{n?.(e),e.target.checked&&s.onValueChange?.(i)};return(0,Q.jsxs)(`span`,{className:`caps-radio`,"data-checked":c,"data-custom-indicator":t!==void 0||void 0,children:[(0,Q.jsx)(`input`,{...a,"aria-checked":c,checked:c,className:z(`caps-radio-input`,e),disabled:s.disabled||a.disabled,name:s.name,onChange:l,onClick:r,ref:o,type:`radio`,value:i}),t===void 0?(0,Q.jsx)(la,{checked:c}):t]})}),pa=(0,q.forwardRef)(function({description:e,id:t,meta:n,title:r,...i},a){let o=(0,q.useContext)(ua),s=(0,q.useId)(),c=t??s,l=o?.value===i.value,u=o?.disabled===!0||i.disabled===!0;return(0,Q.jsxs)(`label`,{className:`caps-choice-card`,"data-checked":l,"data-disabled":u||void 0,htmlFor:c,children:[(0,Q.jsx)(fa,{...i,"aria-describedby":e?`${c}-description`:void 0,"aria-labelledby":`${c}-title`,id:c,ref:a}),(0,Q.jsxs)(`span`,{className:`caps-choice-card-copy`,children:[(0,Q.jsx)(`span`,{className:`caps-choice-card-title`,id:`${c}-title`,children:r}),e?(0,Q.jsx)(`span`,{className:`caps-choice-card-description`,id:`${c}-description`,children:e}):null]}),n?(0,Q.jsx)(`span`,{className:`caps-choice-card-meta`,children:n}):null]})}),ma=(0,q.forwardRef)(function({label:e,icon:t,caption:n,art:r=`dim`,className:i,...a},o){return(0,Q.jsx)(`label`,{className:`caps-icon-choice`,"data-art":r===`color`?r:void 0,children:(0,Q.jsx)(fa,{...a,"aria-label":e,className:z(`caps-icon-choice-input`,i),indicator:(0,Q.jsx)(aa,{icon:t,caption:n}),ref:o})})});(0,q.forwardRef)(function({label:e,color:t,className:n,...r},i){return(0,Q.jsx)(`label`,{className:`caps-icon-choice`,"data-art":`color`,"data-swatch":``,title:e,children:(0,Q.jsx)(fa,{...r,"aria-label":e,className:z(`caps-icon-choice-input`,n),indicator:(0,Q.jsx)(aa,{icon:(0,Q.jsx)(`span`,{className:`caps-swatch-dot`,style:{backgroundColor:t}})}),ref:i})})});var ha=(0,q.forwardRef)(function({className:e,invalid:t,...n},r){return(0,Q.jsxs)(`span`,{className:`caps-select-shell`,children:[(0,Q.jsx)(`select`,{...n,"aria-invalid":t?!0:n[`aria-invalid`]===!1?void 0:n[`aria-invalid`],className:z(`select select-bordered caps-select w-full`,t&&`select-error`,e),ref:r}),!n.multiple&&(!n.size||n.size<=1)?(0,Q.jsx)(kr,{className:`caps-select-chevron`,"aria-hidden":`true`}):null]})});function ga({checked:e}){let t=`caps-switch-${(0,q.useId)().replaceAll(`:`,``)}`,n=(0,q.useRef)(null),r=(0,q.useRef)(null),i=(0,q.useRef)(e).current,a=(0,q.useRef)(e),o=de();return(0,q.useLayoutEffect)(()=>{if(!n.current||!r.current)return;let t=o||a.current===e;a.current=e;let i=e?16:8,s=D(n.current),c=ei(s,{bounce:.25,duration:440}),l=Z(s,{ease:`inOutSine`,duration:100}),u=V(n.current,t?{x:2,y:2,width:i,height:8,duration:0}:{x:[{to:e?2.5:1.5,...l},{to:2,...c}],y:[{to:1.5,...l},{to:2,...c}],height:[{to:9,...l},{to:8,...c}],width:[{to:e?7:16.5,...l},{to:i,...c}]}),d=V(r.current,{gradientTransform:e?`matrix(2 0 0 1 10 6)`:`matrix(1 0 0 1 6 6)`,...t?{duration:0}:{delay:l.duration,...c}});return()=>{u.cancel(),d.cancel()}},[e,o]),(0,Q.jsxs)(`svg`,{className:`caps-switch-visual`,width:`40`,height:`24`,viewBox:`0 0 20 12`,"aria-hidden":`true`,focusable:`false`,children:[(0,Q.jsxs)(`defs`,{children:[(0,Q.jsx)(It,{ref:r,id:`${t}-surface`,transform:i?`matrix(2 0 0 1 10 6)`:`matrix(1 0 0 1 6 6)`}),(0,Q.jsx)(ft,{id:`${t}-shadow`}),(0,Q.jsx)(tn,{id:`${t}-inset`}),(0,Q.jsx)(`clipPath`,{id:`${t}-track`,children:(0,Q.jsx)(`rect`,{x:`1`,y:`1`,width:`18`,height:`10`,rx:`5`})})]}),(0,Q.jsx)(`rect`,{className:`caps-switch-track`,filter:`url(#${t}-inset)`,x:`0.5`,y:`0.5`,width:`19`,height:`11`,rx:`5.5`}),(0,Q.jsx)(`g`,{clipPath:`url(#${t}-track)`,children:(0,Q.jsx)(`rect`,{ref:n,x:`2`,y:`2`,width:i?16:8,height:`8`,rx:`4`,fill:`url(#${t}-surface)`,filter:`url(#${t}-shadow)`})})]})}var _a=(0,q.forwardRef)(function({className:e,checked:t,defaultChecked:n=!1,onChange:r,onCheckedChange:i,...a},o){let s=(0,q.useRef)(null),[c,l]=(0,q.useState)(n),u=t??c;return(0,q.useImperativeHandle)(o,()=>{if(!s.current)throw Error(`Switch input is not mounted`);return s.current},[]),(0,q.useEffect)(()=>{let e=s.current?.form;if(!e||t!==void 0)return;let r=e=>{queueMicrotask(()=>{!e.defaultPrevented&&s.current&&l(n)})};return e.addEventListener(`reset`,r),()=>{e.removeEventListener(`reset`,r)}},[t,n,a.form]),(0,Q.jsxs)(`span`,{className:`caps-switch`,"data-checked":u,children:[(0,Q.jsx)(`input`,{...a,checked:u,className:z(`caps-switch-input`,e),onChange:e=>{t===void 0&&l(e.target.checked),r?.(e),i?.(e.target.checked)},ref:s,role:`switch`,type:`checkbox`}),(0,Q.jsx)(ga,{checked:u})]})}),va=(0,q.forwardRef)(function({className:e,invalid:t,...n},r){return(0,Q.jsx)(`textarea`,{...n,"aria-invalid":t?!0:n[`aria-invalid`]===!1?void 0:n[`aria-invalid`],className:z(`textarea textarea-bordered w-full`,t&&`textarea-error`,e),ref:r})}),ya=B(I),ba=B(Re),xa=B(Xe(Ge)),Sa=B(P(I)),Ca=P(yt(File)),wa=B(Ca),Ta=Zt([I,Ge,Re,oe,zt,P(I),Ca]),Ea=B(Ta),$=e=>l(ya(e.state.value),()=>``),Da=e=>l(ba(e.state.value),()=>!1),Oa=e=>l(xa(e.state.value),()=>null),ka=e=>l(Sa(e.state.value),()=>[]),Aa=e=>l(wa(e.state.value),()=>[]),ja=e=>l(Ea(e.state.value),()=>null);function Ma({field:e,spec:t,locked:n,...r}){let[i,a]=(0,q.useState)(!1);return(0,Q.jsxs)(tr,{children:[(0,Q.jsx)(rr,{...r,name:t.name,disabled:n,type:i?`text`:`password`,autoComplete:`off`,spellCheck:!1,className:`caps-field-secret`,placeholder:t.placeholder,readOnly:t.readOnly,value:$(e),onBlur:e.handleBlur,onChange:t=>{e.handleChange(t.currentTarget.value)}}),(0,Q.jsx)(G,{type:`button`,variant:`outline`,size:`icon`,"aria-label":i?`Hide`:`Show`,"aria-pressed":i,disabled:n,onClick:()=>{a(e=>!e)},children:i?(0,Q.jsx)(Ar,{"aria-hidden":`true`}):(0,Q.jsx)(gr,{"aria-hidden":`true`})})]})}var Na={text:`text`,email:`email`,url:`url`,tel:`tel`};function Pa({spec:e,field:t,locked:n,...r}){let i=Aa(t),a=n||e.readOnly===!0,o=(0,q.useRef)(null);return(0,Q.jsxs)(`div`,{className:`flex flex-col gap-sm`,children:[(0,Q.jsx)(Nt,{asChild:!0,children:(0,Q.jsx)(`input`,{...r,ref:o,type:`file`,tabIndex:-1,required:r.required===!0&&i.length===0,name:e.name,accept:e.accept,multiple:e.multiple,disabled:a,onBlur:t.handleBlur,onChange:e=>{t.handleChange(Array.from(e.currentTarget.files??[])),e.currentTarget.value=``}})}),(0,Q.jsx)(G,{type:`button`,variant:`outline`,"aria-label":`Choose files for ${e.label}`,"aria-describedby":r[`aria-describedby`],"aria-invalid":r[`aria-invalid`],disabled:a,onBlur:t.handleBlur,onClick:()=>{o.current?.click()},children:`Choose files`}),(0,Q.jsx)(pi,{items:i.map((e,t)=>({id:String(t),name:e.name,preview:{kind:`file`},progress:0,progressLabel:`${String(e.size)} bytes`,statusLabel:`Selected`,actions:a?{}:{remove:{label:`Remove`,accessibleLabel:`Remove ${e.name}`}}})),onRemove:e=>{t.handleChange(i.filter((t,n)=>String(n)!==e))},onCancel:()=>void 0,onRetry:()=>void 0})]})}function Fa({spec:e,field:t,locked:n,...r}){let i=e=>{t.handleChange(e)},a={...r,name:e.name,disabled:n,onBlur:t.handleBlur};switch(e.kind){case`text`:case`email`:case`url`:case`tel`:return(0,Q.jsx)(rr,{...a,type:Na[e.kind],inputMode:e.kind===`text`?void 0:e.kind,autoComplete:e.autoComplete,placeholder:e.placeholder,maxLength:e.maxLength,readOnly:e.readOnly,value:$(t),onChange:e=>{i(e.currentTarget.value)}});case`textarea`:return(0,Q.jsx)(va,{...a,rows:e.rows??3,placeholder:e.placeholder,maxLength:e.maxLength,readOnly:e.readOnly,value:$(t),onChange:e=>{i(e.currentTarget.value)}});case`secret`:return(0,Q.jsx)(Ma,{...r,field:t,spec:e,locked:n});case`money`:return(0,Q.jsxs)(tr,{children:[(0,Q.jsx)(nr,{className:`caps-field-currency`,children:e.currency??`USD`}),(0,Q.jsx)(rr,{...a,inputMode:`decimal`,autoComplete:`off`,className:`caps-field-amount`,placeholder:e.placeholder??`0.00`,readOnly:e.readOnly,value:$(t),onChange:e=>{i(e.currentTarget.value)}})]});case`date`:return(0,Q.jsx)(rr,{...a,type:`date`,readOnly:e.readOnly,value:$(t),onChange:e=>{i(e.currentTarget.value)}});case`number`:return(0,Q.jsx)(mr,{...a,...e.min===void 0?{}:{min:e.min},...e.max===void 0?{}:{max:e.max},...e.step===void 0?{}:{step:e.step},...e.unit===void 0?{}:{unit:e.unit},...e.wrap===void 0?{}:{wrap:e.wrap},disabled:n||e.readOnly===!0,decrementLabel:`Decrease ${e.label}`,incrementLabel:`Increase ${e.label}`,value:Oa(t),onValueChange:e=>{t.handleChange(e)}});case`select`:return(0,Q.jsxs)(ha,{...a,value:$(t),onChange:e=>{i(e.currentTarget.value)},children:[e.placeholder===void 0?null:(0,Q.jsx)(`option`,{value:``,disabled:!0,children:e.placeholder}),e.options.map(e=>(0,Q.jsx)(`option`,{value:e.value,disabled:e.disabled,children:e.label},e.value))]});case`combobox`:return(0,Q.jsx)(ia,{id:r.id??e.name,"aria-describedby":r[`aria-describedby`],"aria-invalid":r[`aria-invalid`],"aria-required":r[`aria-required`],items:e.options,getKey:e=>e.value,getLabel:e=>e.label,isDisabled:t=>t.disabled||n||e.readOnly===!0,value:$(t),...e.placeholder===void 0?{}:{placeholder:e.placeholder},trigger:(0,Q.jsx)(na,{name:e.name,disabled:n||e.readOnly===!0,onBlur:t.handleBlur,children:e.options.find(e=>e.value===$(t))?.label??e.placeholder??`Choose…`}),inputProps:{"aria-label":`Search ${e.label}`,disabled:n||e.readOnly===!0},onValueChange:e=>{i(e??``),t.handleBlur()}});case`file`:return(0,Q.jsx)(Pa,{...r,spec:e,field:t,locked:n});case`checkbox`:return(0,Q.jsx)(xi,{...a,disabled:n||e.readOnly===!0,checked:Da(t),onChange:e=>{t.handleChange(e.currentTarget.checked)}});case`switch`:return(0,Q.jsx)(_a,{...a,disabled:n||e.readOnly===!0,checked:Da(t),onCheckedChange:e=>{t.handleChange(e)}});case`radio`:case`icon-radio`:case`checkboxes`:case`icon-checkboxes`:return null}}var Ia=new Set([`radio`,`icon-radio`,`checkboxes`,`icon-checkboxes`]);function La({spec:e,field:t,locked:n,error:r,layout:i}){let a=n||e.readOnly===!0,o=e.label;if(e.kind===`checkboxes`||e.kind===`icon-checkboxes`){let n=ka(t),s=(e,r)=>{t.handleChange(r?[...n,e]:n.filter(t=>t!==e))};return(0,Q.jsx)(lr,{legend:o,icon:e.icon,layout:i,...i===`columns`?{legendTitle:o}:{},description:e.help,disabled:a,error:r??null,children:e.kind===`icon-checkboxes`?(0,Q.jsx)(`div`,{className:`caps-field-icon-choices`,children:e.options.map(r=>(0,Q.jsx)(oa,{name:e.name,value:r.value,label:r.label,...r.caption===void 0?{}:{caption:r.caption},icon:r.icon,disabled:r.disabled,checked:n.includes(r.value),onBlur:t.handleBlur,onChange:e=>{s(r.value,e.currentTarget.checked)}},r.value))}):(0,Q.jsx)(ca,{children:e.options.map(r=>(0,Q.jsx)(sa,{name:e.name,value:r.value,label:r.label,icon:r.icon,hint:r.description,disabled:r.disabled,checked:n.includes(r.value),onBlur:t.handleBlur,onChange:e=>{s(r.value,e.currentTarget.checked)}},r.value))})})}let s=e.options.some(e=>e.description!==void 0||e.meta!==void 0);return(0,Q.jsx)(lr,{legend:o,icon:e.icon,layout:i,...i===`columns`?{legendTitle:o}:{},description:e.help,disabled:a,error:r??null,children:(0,Q.jsx)(da,{name:e.name,"aria-label":o,value:$(t),onValueChange:e=>{t.handleChange(e),t.handleBlur()},orientation:e.kind===`icon-radio`||s?`horizontal`:`vertical`,children:e.options.map(t=>e.kind===`icon-radio`?(0,Q.jsx)(ma,{value:t.value,label:t.label,...t.caption===void 0?{}:{caption:t.caption},icon:t.icon,disabled:t.disabled},t.value):s?(0,Q.jsx)(pa,{value:t.value,title:t.label,description:t.description,meta:t.meta,disabled:t.disabled},t.value):(0,Q.jsx)(Qn,{label:t.label,orientation:`inline`,children:(0,Q.jsx)(fa,{value:t.value,disabled:t.disabled})},t.value))})})}function Ra({spec:e,field:t,locked:n,error:r,render:i,...a}){return i({name:e.name,label:e.label,help:e.help,value:ja(t),onChange:e=>{t.handleChange(e)},onBlur:t.handleBlur,error:r,disabled:n,id:a.id??e.name,"aria-describedby":a[`aria-describedby`],"aria-invalid":r!==void 0})}function za({form:e,spec:t,locked:n,layout:r}){let i=cr({form:e,name:t.name}),a=dr(e.store,e=>e.submissionAttempts>0),o=i.state.meta.isBlurred||a?$r(i.state.meta):void 0;if(t.render===void 0&&Ia.has(t.kind))return(0,Q.jsx)(La,{spec:t,field:i,locked:n,error:o,layout:r});let s=r===`columns`?t.kind===`switch`||t.kind===`checkbox`?`horizontal`:`vertical`:t.kind===`checkbox`?`inline`:(t.layout??(t.kind===`switch`?`row`:`stacked`))===`row`?`horizontal`:`vertical`;return(0,Q.jsx)(Qn,{label:t.label,...r===`columns`?{labelTitle:t.label}:{},description:t.help,icon:t.icon,orientation:s,error:o,...t.required===void 0?{}:{required:t.required},...t.optional===void 0?{}:{optional:t.optional},children:t.render===void 0?(0,Q.jsx)(Fa,{spec:t,field:i,locked:n}):(0,Q.jsx)(Ra,{spec:t,field:i,locked:n,error:o,render:t.render})})}var Ba=B(et(I,Ta));function Va({form:e,spec:t,locked:n,layout:r}){let i=t.when;return dr(e.store,e=>i===void 0||i(l(Ba(e.values),()=>({}))))?(0,Q.jsx)(za,{form:e,spec:t,locked:n,layout:r}):null}function Ha({form:e,section:t,locked:n,layout:r}){let i=t.fields.map(t=>(0,Q.jsx)(Va,{form:e,spec:t,locked:n,layout:r},t.name));return t.title===void 0?i:(0,Q.jsx)(or,{title:t.title,description:t.description,layout:r,children:i})}function Ua({model:e,names:t,disabled:n=!1,layout:r}){let i=e.form;return t===void 0?e.description.sections.map(e=>(0,Q.jsx)(Ha,{form:i,section:e,locked:n,layout:r},e.id??``)):t.map(t=>{let a=e.description.fields.find(e=>e.name===t);return a===void 0?null:(0,Q.jsx)(Va,{form:i,spec:a,locked:n,layout:r},t)})}var Wa=class{annotation;constructor(e){this.annotation=e}},Ga=class{sections;constructor(e){this.sections=e}},Ka=`caps/form`,qa=0;function Ja(e){qa+=1;let t={[`${Ka}:${String(qa)}`]:new Wa(e)};return e.label!==void 0&&(t.title=e.label),e.help!==void 0&&(t.description=e.help),t}I.annotate(Ja({kind:`secret`})).pipe(it(`Secret`));var Ya=e=>{let t=e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/[-_]+/g,` `).toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)};function Xa(e){return Object.values(e??{}).reduce((e,t)=>t instanceof Wa?{...e,...t.annotation}:e,{})}function Za(e){return e.reduce((e,t)=>({...e,...Xa(t)}),{})}function Qa(e){let t=e?.[Ka];return t instanceof Ga?t.sections:{}}var $a=B(I);function eo(e){if(_(e))return We($a(e.literal),{onNone:()=>null,onSome:e=>[e]});if(!ve(e))return null;let t=[];for(let n of e.types){if(me(n))continue;let e=eo(n);if(e===null)return null;t.push(...e)}return t}function to(e){if(kt(e))return{type:`string`,literals:[]};if(Mt(e))return{type:`number`,nullable:!1};if(S(e))return{type:`boolean`};let t=eo(e);if(t!==null)return{type:`string`,literals:t};if(Fe(e)){let[t]=e.rest;if(t===void 0)return null;if(kt(t))return{type:`strings`,literals:[]};let n=eo(t);return n===null?null:{type:`strings`,literals:n}}if(ve(e)){let t=e.types.filter(e=>!me(e)&&!Se(e)),n=e.types.some(e=>Se(e)),[r]=t;if(t.length!==1||r===void 0)return null;let i=to(r);return i?.type===`number`?{type:`number`,nullable:n}:n?null:i}return null}function no(e){let t=e.ast;if(!a(t))throw Error(`A schema form needs a Schema.Struct.`);return{fields:t.propertySignatures.map(e=>{let t=String(e.name),n=ue(e.type),r=Za([e.type.annotations,...(e.type.checks??[]).map(e=>e.annotations)]),i=r.kind===`file`?{type:`files`}:to(n);if(i===null)throw Error(`Schema field "${t}" has no form control. Annotate it with field({ render }) or a kind.`);return{name:t,valueType:i,optional:e.type.context?.isOptional===!0,annotation:r,title:te(e.type),description:E(e.type)}}),sections:Qa(De(t))}}function ro(e){let t=e,n=!1,r=!1;for(;;)if(t instanceof an)n=!0,t=t.unwrap();else if(t instanceof Ae)r=!0,t=t.unwrap();else if(t instanceof Ye)t=t.unwrap();else if(t instanceof Vt)t=t.in;else return{node:t,optional:n,nullable:r}}function io(e){if(e instanceof ot){let t=e.options.map(e=>io(e));return t.some(e=>e===null)?null:t.flatMap(e=>e??[])}let t=e instanceof Ke?e.options:e instanceof $e?[...e.values]:null;if(t===null)return null;let n=t.map(e=>$a(e));return n.every(N)?n.map(e=>e.value):null}function ao(e){let{node:t,nullable:r}=ro(e);if(t instanceof Qt)return{type:`string`,literals:[]};if(t instanceof n)return{type:`number`,nullable:r};if(t instanceof ae)return{type:`boolean`};let i=io(t);if(i!==null)return{type:`string`,literals:i};if(t instanceof Yt){let e=ro(t.element).node;if(e instanceof Qt)return{type:`strings`,literals:[]};let n=io(e);return n===null?null:{type:`strings`,literals:n}}return null}function oo(e){let t=[e];for(;;){let e=t[t.length-1];if(e===void 0)break;let n=e instanceof an||e instanceof Ae||e instanceof Ye?e.unwrap():e instanceof Vt?e.in:e;if(n===e)break;t.push(n)}return t.reverse().map(e=>y.get(e))}function so(e){return oo(e).reduce((e,t)=>({...e,...t}),{})}function co(e){return Object.entries(e.shape)}function lo(e){let t=ro(e).node;if(!(t instanceof gt))throw Error(`A schema form needs a z.object.`);return{fields:co(t).map(([e,t])=>{let n=Za(oo(t)),r=n.kind===`file`?{type:`files`}:ao(t);if(r===null)throw Error(`Schema field "${e}" has no form control. Annotate it with field({ render }) or a kind.`);let i=so(t);return{name:e,valueType:r,optional:ro(t).optional,annotation:n,title:i.title,description:i.description}}),sections:Qa(so(e))}}function uo(e,t){let n=t.options??{};return(e.length>0?e:Object.keys(n)).map(e=>{let t=n[e],r=t===void 0?{}:t instanceof Object?t:{label:t};return{value:e,label:r.label??Ya(e),description:r.description,meta:r.meta,icon:r.icon,caption:r.caption,disabled:r.disabled===!0}})}function fo(e,t){let n=t.some(e=>e.icon!==void 0);switch(e.type){case`boolean`:return`switch`;case`number`:return`number`;case`strings`:return n?`icon-checkboxes`:`checkboxes`;case`files`:return`file`;case`string`:return t.length===0?`text`:t.length>12?`combobox`:n?`icon-radio`:t.some(e=>e.description!==void 0||e.meta!==void 0)||t.length<=3?`radio`:`select`}}function po(e,t){switch(e.type){case`boolean`:return!1;case`number`:return e.nullable?null:0;case`strings`:case`files`:return[];case`string`:return t[0]?.value??``}}function mo(e){let t=e instanceof Et?lo(e):no(e),n=t.fields.map((e,t)=>{let{kind:n,...r}=e.annotation,i=uo(e.valueType.type===`string`||e.valueType.type===`strings`?e.valueType.literals:[],e.annotation),a=r.help??e.description;return{...r,name:e.name,label:r.label??e.title??Ya(e.name),help:a,kind:n??fo(e.valueType,i),options:i,optionalInSchema:e.optional,index:t}}),r={};t.fields.forEach((e,t)=>{let i=n[t];i&&(r[e.name]=po(e.valueType,i.options))});let i=e=>e.order??e.index,a=e=>e.section!==void 0&&Object.hasOwn(t.sections,e.section)?e.section:null,o=e=>n.filter(t=>a(t)===e).sort((e,t)=>i(e)-i(t)),s=Object.entries(t.sections).map(([e,t])=>({id:e,title:t.title,description:t.description,fields:o(e)}));return{fields:n,sections:[{id:null,title:void 0,description:void 0,fields:o(null)},...s].filter(e=>e.fields.length>0),defaults:r}}function ho(e){let t=e instanceof Et?e:fn(e);return{"~standard":{...t[`~standard`],validate:e=>{let n=t[`~standard`].validate(e);return n instanceof Promise?n.then(e=>go(e)):go(n)}}}}function go(e){return e.issues===void 0?e:{issues:e.issues.map(e=>e.path===void 0?e:{...e,path:e.path.slice(0,1)})}}var _o=`onServer`;function vo(e){let t=e?.querySelector(`[aria-invalid="true"]`);t?.matches(`input, select, textarea, button, [tabindex]`)?t.focus():t?.querySelector(`input, select, textarea, button`)?.focus()}function yo(e){return e.state.meta.errorMap.onServer!==void 0}function bo(e){e.setMeta(e=>({...e,errorMap:{...e.errorMap,[_o]:void 0}}))}function xo(e,t,n){e.setFieldMeta(t,e=>({...e,isBlurred:!0,errorMap:{...e.errorMap,[_o]:n}}))}function So(e){let[t,n]=(0,q.useState)(null),[r,i]=(0,q.useState)(null),[a,o]=(0,q.useState)(e.defaultValues),[s,c]=(0,q.useState)(null);ar(a,e.defaultValues)||(o(e.defaultValues),c(null));let{schema:l}=e,u=(0,q.useMemo)(()=>mo(l),[l]),d=(0,q.useMemo)(()=>ho(l),[l]),f=pr({defaultValues:s??a,validators:{onChange:d,onSubmit:d},listeners:{onChange:({fieldApi:e})=>{n(null),i(null),yo(e)&&bo(e)}},onSubmit:async({value:t,formApi:r})=>{n(null),i(null);let a=await ho(l)[`~standard`].validate(t);if(a.issues){n(a.issues[0]?.message??`Check the form and try again.`);return}let o;try{o=await e.onSubmit(a.value,t)??{kind:`saved`}}catch(t){console.error(`SchemaForm submit failed`,t),n(e.failure??`Couldn't save changes. Try again.`);return}if(o.kind===`refused`){n(o.error??null);let e=r;for(let[t,n]of Object.entries(o.fields??{}))n!==void 0&&n.length>0&&xo(e,t,n);return}let s=o.values??t;c(s),r.reset(s),i(o.message??`Saved`),e.onSaved?.(s)}});return{description:u,form:f,error:t,saved:r,discard:()=>{n(null),i(null),f.reset()},submit:()=>f.handleSubmit()}}function Co(e){return{dirty:dr(e.form.store,e=>!e.isDefaultValue),submitting:dr(e.form.store,e=>e.isSubmitting),canSubmit:dr(e.form.store,e=>e.canSubmit)}}function wo({model:e,submitLabel:t=`Save changes`,discardLabel:n,onCancel:r,cancelLabel:i,allowClean:a,layout:o,footer:s,children:c,disabled:l=!1,...u}){let{submitting:d}=Co(e),f=(0,q.useRef)(null);return(0,Q.jsxs)(fr,{...u,ref:f,layout:o,busy:d,noValidate:!0,onSubmit:t=>{t.preventDefault(),e.form.state.isSubmitting||e.submit().then(()=>{setTimeout(()=>{vo(f.current)},0)})},children:[c??(0,Q.jsx)(Ua,{model:e,disabled:l,layout:o}),s===void 0?(0,Q.jsx)(Do,{model:e,label:t,discardLabel:r===void 0?n:void 0,onCancel:r,cancelLabel:i,allowClean:a??r!==void 0,divider:r===void 0}):s]})}function To({schema:e,defaultValues:t,onSubmit:n,onSaved:r,failure:i,...a}){let o=So({schema:e,defaultValues:t,onSubmit:n,onSaved:r,failure:i});return(0,Q.jsx)(wo,{...a,model:o})}function Eo(e){return`model`in e?(0,Q.jsx)(wo,{...e}):(0,Q.jsx)(To,{...e})}function Do({model:e,label:t,discardLabel:n,onCancel:r,cancelLabel:i=`Cancel`,allowClean:a=!1,dirtyLabel:o=`Unsaved changes`,buttonProps:s,...c}){let{dirty:l,submitting:u}=Co(e),d=u?null:e.saved&&!l?(0,Q.jsx)(ui,{tone:`success`,size:`compact`,label:e.saved}):l?(0,Q.jsx)(ui,{tone:`neutral`,size:`compact`,label:o}):null;return(0,Q.jsxs)(er,{...c,error:e.error,status:d,children:[r?(0,Q.jsx)(G,{type:`button`,variant:`ghost`,disabled:u,onClick:r,children:i}):n&&l?(0,Q.jsx)(G,{type:`button`,variant:`ghost`,disabled:u,onClick:e.discard,children:n}):null,(0,Q.jsx)(G,{...s,type:`submit`,loading:u,disabled:u||!l&&!a,title:!l&&!a?`No changes to save`:void 0,children:t})]})}var Oo=ht.check(lt(/^(?!\.{1,2}$)[^/]+$/u,{message:`Enter a single file or folder name.`})),ko={file:r({name:Oo.annotate(Ja({label:`File name`}))}),folder:r({name:Oo.annotate(Ja({label:`Folder name`}))})};function Ao(e){return(0,Q.jsx)(jo,{...e},e.creation?`${e.creation.kind}:${e.creation.directory}`:`closed`)}function jo({creation:e,rootPath:t,onCreate:n,onClose:r}){let i=So({schema:ko[e?.kind??`file`],defaultValues:{name:``},onSubmit:async t=>{if(!e)return;let i=await n(e,t.name);if(i)return i===`That name already exists in this directory.`?{kind:`refused`,fields:{name:i}}:{kind:`refused`,error:i};r()}}),{submitting:a}=Co(i);return(0,Q.jsx)(Tt,{open:e!==null,onOpenChange:e=>{!e&&!i.form.state.isSubmitting&&r()},children:(0,Q.jsxs)(Ut,{children:[(0,Q.jsxs)(Ft,{className:`mb-4`,children:[(0,Q.jsxs)(sn,{children:[`New `,e?.kind===`folder`?`folder`:`file`]}),(0,Q.jsxs)(en,{children:[`Create in `,e?.directory??t,` on this Computer.`]})]}),(0,Q.jsx)(Eo,{model:i,onSubmitCapture:()=>{i.form.state.isSubmitting||i.form.setFieldValue(`name`,e=>e)},footer:(0,Q.jsxs)(er,{divider:!1,error:i.error,children:[(0,Q.jsx)(G,{variant:`ghost`,type:`button`,disabled:a,onClick:r,children:`Cancel`}),(0,Q.jsx)(G,{type:`submit`,disabled:a,loading:a,children:a?`Creating…`:`Create`})]})})]})})}function Mo({app:e,onOpenFile:t,activePath:n,rootPath:r=`/`,rootLabel:i=`Computer`,onSelectPath:a,creationRequest:o=null,onCreationRequestHandled:s}){let[c,l]=(0,q.useState)(null),u=Xr({app:e,rootPath:r,rootLabel:i,activePath:n,onOpenFile:t,onSelectPath:e=>{l(e),a?.(e)}}),[d,f]=(0,q.useState)(null),p=e.capabilities.has(Cn);function m(e,t){f({kind:e,directory:nn(t)})}(0,q.useEffect)(()=>{o&&(f({kind:o.kind,directory:nn(c??`${r}/`)}),s?.())},[o,s,r,c]);async function h(n,r){let i=Xt(r,n.directory);try{let a=0;for(;a!==null;){let t=a,i=await Mn(e.capabilities,{path:n.directory,limit:256,offset:t});if(i.entries.some(e=>e.name===r))return`That name already exists in this directory.`;if(i.nextOffset!==null&&i.nextOffset<=t)return`Could not verify that name is available.`;a=i.nextOffset}n.kind===`folder`?(await e.capabilities.require(Cn).mkdir({path:i}),u.model.batch([{type:`add`,path:`${i}/`}])):(await kn(e.capabilities,{path:i,content:new Blob([])},{}),u.model.batch([{type:`add`,path:i}]),t(i));return}catch(e){return e instanceof Error?j(e).message:`Couldn't create ${n.kind}. Check Computer write access.`}}return(0,Q.jsxs)(`aside`,{className:`inkcap-tree`,"aria-label":`File tree`,children:[(0,Q.jsxs)(`div`,{className:`inkcap-tree-toolbar`,children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(jn,{"aria-hidden":`true`}),` Explorer`]}),(0,Q.jsxs)(`span`,{className:`inkcap-tree-actions`,children:[(0,Q.jsx)(Bt,{icon:(0,Q.jsx)(Nn,{}),"aria-label":`New file`,title:`New file`,variant:`ghost`,size:`xs`,disabled:!p,onClick:()=>{m(`file`,c??`${r}/`)}}),(0,Q.jsx)(Bt,{icon:(0,Q.jsx)(Mr,{}),"aria-label":`New folder`,title:`New folder`,variant:`ghost`,size:`xs`,disabled:!p,onClick:()=>{m(`folder`,c??`${r}/`)}}),(0,Q.jsx)(Bt,{icon:(0,Q.jsx)(yr,{}),"aria-label":`Refresh files`,title:`Refresh files`,variant:`ghost`,size:`xs`,disabled:u.busy,onClick:u.reloadRoot})]})]}),u.error&&(0,Q.jsx)(`p`,{role:`alert`,children:u.error}),u.rootEmpty?(0,Q.jsx)(Pn,{className:`inkcap-tree-empty`,variant:`quiet`,title:`This folder is empty`,description:`Use New file or New folder above to start.`}):null,(0,Q.jsx)(Un,{model:u.model,style:{flex:`1`,"--trees-item-height":`32px`,"--trees-padding-inline-override":`var(--spacing-xs)`,"--trees-item-margin-x-override":`0px`,"--trees-item-padding-x-override":`var(--spacing-xs)`,"--trees-item-row-gap-override":`var(--spacing-xs)`,"--trees-bg-override":`var(--color-base-100)`,"--trees-fg-override":`var(--color-base-content)`,"--trees-bg-muted-override":`var(--color-base-200)`,"--trees-selected-bg-override":`var(--color-base-300)`,"--trees-border-radius-override":`var(--radius-field)`,"--trees-font-family-override":`var(--font-sans)`,"--trees-font-size-override":`12px`},renderContextMenu:(e,t)=>(0,Q.jsxs)(`div`,{className:`flex min-w-36 flex-col gap-xs p-xs`,role:`menu`,children:[(0,Q.jsxs)(G,{className:`w-full justify-start`,disabled:!p,role:`menuitem`,title:p?void 0:`Computer write access is not granted.`,size:`sm`,variant:`ghost`,onClick:()=>{t.close({restoreFocus:!1}),m(`file`,e.path)},children:[(0,Q.jsx)(Nn,{"aria-hidden":`true`}),` New file`]}),(0,Q.jsxs)(G,{className:`w-full justify-start`,disabled:!p,role:`menuitem`,title:p?void 0:`Computer write access is not granted.`,size:`sm`,variant:`ghost`,onClick:()=>{t.close({restoreFocus:!1}),m(`folder`,e.path)},children:[(0,Q.jsx)(Mr,{"aria-hidden":`true`}),` New folder`]})]})}),(0,Q.jsx)(Ao,{creation:d,rootPath:r,onCreate:h,onClose:()=>{f(null)}}),u.page.next!==null&&(0,Q.jsxs)(G,{disabled:u.busy,onClick:u.loadNext,children:[`More in `,u.page.path]})]})}export{Mo as InkcapFileTree};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{Bn as t,Br as n,Un as r,Vr as i,i as a,l as o,nn as s,o as c,rn as l,s as u,u as d}from"./tree-path-B5mQdKbM.js";import{Ot as f,mt as p,n as m,yt as h}from"./empty-state-BPRNo51e.js";import{a as g,c as _,d as v,i as y,l as b,n as x,o as S,r as C,s as w,t as T,u as E}from"./useFileTree-grDspEh1.js";import{t as D}from"./refresh-cw-xZ5ayQTq.js";import{_ as O,a as k,b as A,c as j,d as M,f as N,g as P,h as F,l as I,m as L,n as ee,p as R,t as z,u as B,v as V,y as H}from"./index-B5ZsAojZ.js";var U=e(i(),1);function W(e,t,n){let r=E(),i=b(),a=f(n),o=a.defaultQueryOptions(e),s=a.getQueryCache().get(o.queryHash),c=e.subscribed!==!1;o._optimisticResults=r?`isRestoring`:c?`optimistic`:void 0,C(o),S(o,i,s),_(i);let[l]=U.useState(()=>new t(a,o)),u=l.getOptimisticResult(o),d=!r&&c;if(U.useSyncExternalStore(U.useCallback(e=>{let t=d?l.subscribe(p.batchCalls(e)):h;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),U.useEffect(()=>{l.setOptions(o)},[o,l]),g(o,u))throw y(o,l,i);if(w({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return o.notifyOnChangeProps?u:l.trackResult(u)}function G(e,t){return W(e,v,t)}var K=t(`GitBranch`,[[`line`,{x1:`6`,x2:`6`,y1:`3`,y2:`15`,key:`17qcm7`}],[`circle`,{cx:`18`,cy:`6`,r:`3`,key:`1h7g24`}],[`circle`,{cx:`6`,cy:`18`,r:`3`,key:`fqmcym`}],[`path`,{d:`M18 9a9 9 0 0 1-9 9`,key:`n2h4wq`}]]),q=t(`History`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}],[`path`,{d:`M12 7v5l4 2`,key:`1fdv2h`}]]),J=256;async function Y(e,t,n,i,a){i.throwIfAborted();let o=await n(e,t);if(!O.safeParse(o).success)return o;a(!0);try{let a=null,o=!1;for(let e=0;e<J&&!o;e++){i.throwIfAborted();let e=I.parse(await n(`rebuildCopies`,{cursor:a}));o=e.done,a=e.cursor}if(!o)throw new r(`Bonsai is still preparing this repository. Try again shortly.`,{code:`TIMEOUT`,retryable:!0});i.throwIfAborted();let s=await n(e,t);if(O.safeParse(s).success)throw Error(`The repository changed while loading. Refresh to retry.`);return s}finally{a(!1)}}function X({repository:e,branch:t,request:n,onSaved:i,onSaveState:a}){let o=new Map;async function s(i,a){a.throwIfAborted();let o=B.parse(await n(`files.read`,{repo:e,ref:t,path:i}));if(a.throwIfAborted(),o.binary)throw Error(`This Bonsai file is not a text document.`);if(o.text===null&&o.blob!==null)throw new r(`This Bonsai file is too large to edit.`,{code:`FILE_TOO_LARGE`,retryable:!1});return o}async function c(s,c){c.throwIfAborted();let l=P.parse(await n(`files.sync`,{}));c.throwIfAborted();let u=l.settled.find(n=>n.repo===e&&n.branch===t&&n.path===s);if(u){if(u.result.kind===`refused`)throw new r(`Bonsai refused sync: ${u.result.reason}`,{code:`CAPABILITY_DENIED`,retryable:u.result.reason===`background-unavailable`});let e=o.get(s);if(u.result.revision!==e?.version)throw new r(`Your saved file changed. Compare before syncing.`,{code:`CONFLICT`,retryable:!0});a(s,u.result)}i()}async function l(l,u,d,f){f.throwIfAborted();let p=o.get(l);if(d===void 0){let e=await s(l,f);p={file:e,contents:e.pending?.text??e.text??``,version:e.version}}if(!p)throw Error(`Reopen this Bonsai file before saving.`);if(d!==void 0&&p.contents!==d)throw new r(`The file baseline changed. Compare before saving.`,{code:`CONFLICT`,retryable:!0});if(d!==void 0){let e=await s(l,f);if(e.version!==p.version||(e.pending?.text??e.text??``)!==p.contents)throw new r(`The file changed. Compare before saving.`,{code:`CONFLICT`,retryable:!0});e.pending===void 0&&(p.file=e)}let m=L.parse({repo:e,branch:t,path:l,baseCommit:p.file.commit,baseBlob:p.file.blob,text:u,revision:p.version}),h=F.parse(await n(`files.save`,m));if(h.kind===`refused`)throw new r(`Bonsai refused this save: ${h.reason}`,{code:`CAPABILITY_DENIED`,retryable:h.reason===`background-unavailable`});if(a(l,h),h.kind===`conflict`)throw new r(`Your saved file changed. Compare before saving.`,{code:`CONFLICT`,retryable:!0});o.set(l,{file:p.file,contents:u,version:h.revision}),i(),h.kind===`saved`&&c(l,f).catch(e=>{console.error(`Bonsai sync status could not be refreshed`,e),!(o.get(l)?.version!==h.revision||f.aborted)&&a(l,{kind:`failed`,revision:h.revision,reason:`sync_failed`})})}return{kind:`repository`,id:`${e}:${t}`,label:`${e} · ${t}`,async read(e,t,n){let r=n?.revision,i=await s(e,t);if(n?.closed)return{kind:`closed`};if(n&&n.revision!==r)return{kind:`changed`};let c=i.pending?.text??i.text??``;o.set(e,{file:i,contents:c,version:i.version});let l=i.pending;return l?.state===`pending`?a(e,{kind:`saved`,revision:l.revision,state:`pending`}):l?.state===`conflict`?a(e,{kind:`conflict`,revision:l.revision,theirs:l.theirs}):l?.state===`failed`?a(e,{kind:`failed`,revision:l.revision,reason:l.failure??`sync_failed`}):i.version!==null&&a(e,{kind:`synced`,revision:i.version,commit:i.commit}),{kind:`text`,contents:c}},replace:(e,t,n,r)=>l(e,t,n,r),write:(e,t,n)=>l(e,t,void 0,n),retry:c,async discard(s,c){c.throwIfAborted();let l=o.get(s);if(!l)throw Error(`Reopen this saved file before discarding it.`);if(l.version===null)return;let u=M.parse({repo:e,branch:t,path:s,revision:l.version}),d=N.parse(await n(`files.discard`,u));if(c.throwIfAborted(),d.kind===`conflict`)throw new r(`Your saved file changed. Refresh before discarding.`,{code:`CONFLICT`,retryable:!0});o.delete(s),a(s,null),i()},async readCommitted(e,t){let n=await s(e,t),r=n.text??``;return o.has(e)||o.set(e,{file:n,contents:r,version:n.version}),r}}}async function Z(e,t,n){let r={repo:t,ref:n},i=V.parse(await e(`files.tree`,{...r,path:``})),a=R.parse(await e(`files.list`,r)),o=j.parse(await e(`commits.list`,{...r,limit:20}));if(i.commit.hash!==a.commit.hash)throw Error(`The repository changed while loading. Refresh to retry.`);return{head:i.commit.hash,branch:n,files:a.paths.map(e=>({path:e})),history:o.commits.map(e=>e.commit),truncated:a.truncated}}var Q=n();function te({files:e,dirtyPaths:t,activePath:n,busy:r,onRefresh:i,onOpenFile:a}){let o=(0,U.useRef)({files:e,onOpenFile:a});o.current={files:e,onOpenFile:a};let{model:c}=T({paths:[],initialExpansion:`open`,itemHeight:32,onSelectionChange(e){let t=e[0];t&&!t.endsWith(`/`)&&o.current.files.some(e=>e.path===t)&&o.current.onOpenFile(t)}}),l=(0,U.useMemo)(()=>{let n=new Set(t);return e.flatMap(e=>n.has(e.path)?[{path:e.path,status:`modified`}]:[])},[e,t]);return(0,U.useEffect)(()=>{c.resetPaths(e.map(e=>e.path))},[c,e]),(0,U.useEffect)(()=>{c.setGitStatus(l)},[c,l]),(0,U.useEffect)(()=>{for(let e of c.getSelectedPaths())e!==n&&c.getItem(e)?.deselect();n&&c.getItem(n)?.select()},[c,n]),(0,Q.jsxs)(`aside`,{className:`inkcap-tree`,"aria-label":`Repository files`,children:[(0,Q.jsxs)(`div`,{className:`inkcap-tree-toolbar`,children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(m,{"aria-hidden":`true`}),` Explorer`]}),(0,Q.jsx)(s,{icon:(0,Q.jsx)(D,{}),"aria-label":`Refresh repository`,variant:`ghost`,size:`xs`,disabled:r,onClick:i})]}),(0,Q.jsx)(`p`,{className:`inkcap-repository-legend`,children:`Changes in latest commit · drafts marked modified`}),(0,Q.jsx)(x,{model:c,style:{flex:`1`,"--trees-item-height":`32px`,"--trees-padding-inline-override":`var(--spacing-xs)`,"--trees-item-margin-x-override":`0px`,"--trees-item-padding-x-override":`var(--spacing-xs)`,"--trees-item-row-gap-override":`var(--spacing-xs)`,"--trees-border-radius-override":`var(--radius-field)`,"--trees-bg-override":`var(--color-base-100)`,"--trees-fg-override":`var(--color-base-content)`,"--trees-bg-muted-override":`var(--color-base-200)`,"--trees-selected-bg-override":`var(--color-base-300)`,"--trees-font-family-override":`var(--font-sans)`,"--trees-font-size-override":`12px`}})]})}var $={all:(e,t)=>[`inkcap-repository`,e,t],branch:(e,t,n)=>[...$.all(e,t),n]};function ne({connection:e,repository:t,initialBranch:n,initialPath:r,openRequestId:i,transport:s,onReady:p}){let m=f(),[h,g]=(0,U.useState)(!1),[_,v]=(0,U.useState)(0),[y,b]=(0,U.useState)(new Map),[x,S]=(0,U.useState)(``),C=(0,U.useRef)(new AbortController);(0,U.useEffect)(()=>{let e=new AbortController;return C.current=e,()=>{e.abort()}},[]);let w=(0,U.useCallback)((t,n)=>s?s(t,n):e.app.capabilities.require(A).call(`app_bonsai`,t,JSON.stringify(n)),[e.app,s]),T=(0,U.useCallback)((e,t)=>Y(e,t,w,C.current.signal,e=>{v(t=>t+(e?1:-1))}),[w]),E=(0,U.useCallback)(()=>{m.invalidateQueries({queryKey:$.all(e.app.identity.surfaceId,t)})},[m,e.app,t]),D=(0,U.useRef)(new Map),O=(0,U.useMemo)(()=>{let r=`${e.app.identity.surfaceId}:${t}:${n}`,i=D.current.get(r);if(i?.app===e.app)return i;let a=X({repository:t,branch:n,request:T,onSaved:E,onSaveState:(e,r)=>{C.current.signal.aborted||b(i=>{let a=new Map(i),o=`${t}:${n}:${e}`;return r===null?a.delete(o):a.set(o,r),a})}}),o={app:e.app,source:a};return D.current.set(r,o),o},[t,n,T,E,e.app]),j=z({connection:O}),M=G({queryKey:$.branch(e.app.identity.surfaceId,t,n),queryFn:()=>Z(T,t,n),refetchInterval:15e3});(0,U.useEffect)(()=>e.app.window.onBeforeClose(j.requestWindowClose),[e.app,j.requestWindowClose]),(0,U.useEffect)(()=>{p?.({requestWindowClose:j.requestWindowClose})},[p,j.requestWindowClose]);let N=(0,U.useRef)(),P=(0,U.useRef)(new Map),F=(0,U.useRef)(new Set);(0,U.useEffect)(()=>{if(!M.data)return;let e=`${O.app.identity.surfaceId}:${O.source.id}:${i}`;N.current!==e&&(N.current=e,j.onOpenFile(r));let t=P.current.get(O.source.id),n=t!==void 0&&t!==M.data.head;P.current.set(O.source.id,M.data.head);let a=new Set(j.tabs.map(e=>e.tabKey));for(let e of F.current)a.has(e)||F.current.delete(e);for(let e of j.tabs)if(!(e.target.closed||e.connection!==O||!n&&!F.current.has(e.tabKey))){if(e.target.saving){F.current.add(e.tabKey);continue}F.current.delete(e.tabKey),e.target.dirty||j.onReopen(e,{background:!0})}},[M.data,O,r,i,j]);let I=j.tabs.find(e=>e.tabKey===j.active),L=I?.connection?.source?y.get(`${I.connection.source.id}:${I.path}`):void 0,R=L?.kind===`saved`?`Saved · syncing`:L?.kind===`synced`?`Synced · ${L.commit.slice(0,7)}`:L?.kind===`conflict`?`Sync conflict · Compare`:L?.kind===`failed`?`Sync failed · Retry`:void 0;async function B(){if(!I?.connection?.source)return;let e=D.current.get(`${I.connection.app.identity.surfaceId}:${I.connection.source.id}`);if(e)try{S(``),await e.source.retry(I.path,C.current.signal)}catch(e){console.error(`Bonsai sync retry failed`,e),S(`Could not retry sync. Your saved text remains in Bonsai.`)}}async function V(){if(!I?.connection?.source)return;let e=()=>!I.target.dirty&&!I.target.saving&&!I.target.closed;if(!e())return;let t=D.current.get(`${I.connection.app.identity.surfaceId}:${I.connection.source.id}`);if(t)try{S(``);let n=await t.source.read(I.path,C.current.signal);if(n.kind!==`text`)throw Error(`This saved text is unavailable.`);if(!e())return;await t.source.replace(I.path,n.contents,n.contents,C.current.signal)}catch(e){console.error(`Bonsai explicit re-save failed`,e),S(`Could not save again. Your saved text and open edits remain available.`)}}return(0,Q.jsxs)(`div`,{className:`inkcap-repository`,children:[(0,Q.jsxs)(`div`,{className:`inkcap-repository-toolbar`,children:[(0,Q.jsxs)(`span`,{className:`inkcap-repository-name`,children:[(0,Q.jsx)(K,{"aria-hidden":`true`}),` `,t,` · `,n]}),(0,Q.jsxs)(l,{size:`sm`,variant:`outline`,onClick:()=>{g(!0)},children:[(0,Q.jsx)(q,{"aria-hidden":`true`,className:`size-[var(--stipe-icon-size-sm)]`}),` `,`History`]})]}),_>0&&(0,Q.jsx)(k,{message:`Loading this repository…`}),M.data?.truncated&&(0,Q.jsx)(H,{tone:`info`,title:`Only the indexed files are shown`}),x&&(0,Q.jsx)(H,{tone:`error`,title:`Sync unavailable`,description:x}),L?.kind===`failed`&&(0,Q.jsx)(H,{tone:`warning`,title:L.reason===`permanent_material`?`Sync needs a new save`:`Sync failed`,description:L.reason===`permanent_material`?`Your text is saved. Save again using the current repository state to retry sync.`:`Your file is saved in Bonsai. Retry when access is available.`,action:(0,Q.jsx)(l,{size:`sm`,disabled:L.reason===`permanent_material`&&I!==void 0&&(I.target.dirty||I.target.saving),onClick:()=>void(L.reason===`permanent_material`?V():B()),children:L.reason===`permanent_material`?`Save again`:`Retry`})}),(0,Q.jsx)(ee,{model:{...j,repositoryStatus:R,repositoryStates:y,canList:!0,sourceLabel:O.source.label,onReadCurrent:async(e,t)=>{if(e.connection?.source?.kind!==`repository`)return j.onReadCurrent(e);let n=D.current.get(`${e.connection.app.identity.surfaceId}:${e.connection.source.id}`);if(!n||e.target.closed)throw Error(`This Bonsai file is no longer open.`);return t&&await n.source.discard(e.path,C.current.signal),n.source.readCommitted(e.path,C.current.signal)},error:M.error?`Could not refresh this repository. Your open edits remain available.`:j.error,fileTree:e=>(0,Q.jsx)(te,{files:M.data?.files??[],dirtyPaths:j.tabs.filter(e=>e.connection===O&&e.dirty).map(e=>e.path),activePath:I?.connection===O?I.path:null,busy:M.isFetching,onRefresh:E,onOpenFile:e})}}),(0,Q.jsx)(a,{open:h,onOpenChange:g,children:(0,Q.jsxs)(c,{children:[(0,Q.jsxs)(o,{children:[(0,Q.jsx)(d,{children:`Commit history`}),(0,Q.jsxs)(u,{children:[t,` · `,n]})]}),(0,Q.jsx)(`ol`,{className:`inkcap-repository-history`,children:M.data?.history.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`code`,{children:e.hash.slice(0,7)}),` `,e.message,(0,Q.jsx)(`span`,{className:`text-dim`,children:e.author.name})]},e.hash))})]})})]})}export{ne as InkcapRepositoryApp};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{$r as t,Bn as n,Br as r,Ci as i,Cr as a,Gr as o,Hr as s,In as c,Ji as l,Jr as u,Ki as d,Kn as f,Kr as p,Pn as ee,Qr as m,Ri as te,Si as h,Sr as g,Tr as ne,Un as _,Ur as v,Vn as re,Vr as ie,Wn as ae,Xi as oe,Xr as y,Yi as se,Yr as b,Zi as ce,_i as x,_r as le,bi as ue,br as de,ci as fe,cr as pe,di as me,dr as he,ea as ge,fi as _e,gi as ve,gr as S,hi as ye,hr as C,ii as w,in as be,li as xe,lr as Se,mi as Ce,mr as we,na as Te,ni as Ee,oi as T,pr as De,qi as Oe,qr as E,ri as D,rn as ke,sr as Ae,ti as je,ui as O,ur as k,vi as A,vr as j,wr as M,xi as Me,yi as Ne,yr as Pe,zi as Fe}from"./tree-path-B5mQdKbM.js";var Ie=new WeakMap,Le=`~effect/Redacted`,Re=e=>ce(e,Le),ze=(e,t)=>{let n=Object.create(Be);return t?.label&&(n.label=t.label),Ie.set(n,e),n},Be={[Le]:{_A:e=>e},label:void 0,...d,toJSON(){return this.toString()},toString(){return`<redacted${ge(this.label)?`:`+this.label:``}>`},[oe](){return se(Ie.get(this))},[l](e){return Re(e)&&Oe(Ie.get(this),Ie.get(e))}},N=e(ie(),1),P=r(),Ve=N.createContext(void 0),He=e=>{let t=N.useContext(Ve);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},Ue=({client:e,children:t})=>(N.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,P.jsx)(Ve.Provider,{value:e,children:t})),We={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Ge=new class{#e=We;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function Ke(e){setTimeout(e,0)}var qe=typeof window>`u`||`Deno`in globalThis;function F(){}function Je(e,t){return typeof e==`function`?e(t):e}function Ye(e){return typeof e==`number`&&e>=0&&e!==1/0}function Xe(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Ze(e,t){return typeof e==`function`?e(t):e}function Qe(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==et(o,t.options))return!1}else if(!nt(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function $e(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(tt(t.options.mutationKey)!==tt(a))return!1}else if(!nt(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function et(e,t){return(t?.queryKeyHashFn||tt)(e)}function tt(e){return JSON.stringify(e,(e,t)=>st(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function nt(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){for(let n=0;n<t.length;n++)if(!nt(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!nt(e[r],t[r]))return!1;return!0}return!1}var rt=Object.prototype.hasOwnProperty;function it(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=ot(e)&&ot(t);if(!r&&!(st(e)&&st(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:rt.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=it(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function at(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function ot(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function st(e){if(!ct(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!ct(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function ct(e){return Object.prototype.toString.call(e)===`[object Object]`}function lt(e){return new Promise(t=>{Ge.setTimeout(t,e)})}function ut(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:it(e,t)}function dt(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function ft(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var pt=Symbol();function mt(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===pt?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ht(e,t){return typeof e==`function`?e(...t):!!e}function gt(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var _t=()=>qe,vt=()=>_t(),yt=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},bt=new class extends yt{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},xt=Ke;function St(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=xt,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var I=St(),Ct=new class extends yt{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function wt(e){return Math.min(1e3*2**e,3e4)}function Tt(e){return(e??`online`)!==`online`||Ct.isOnline()}var Et=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function Dt(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(F);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new Et(t);m(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>bt.isFocused()&&(e.networkMode===`always`||Ct.isOnline())&&e.canRun(),p=()=>Tt(e.networkMode)&&e.canRun(),ee=e=>{c()||(r?.(),i=`resolved`,a(e))},m=e=>{c()||(r?.(),i=`rejected`,o(e))},te=()=>new Promise(t=>{r=e=>{(c()||f())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),h=()=>{if(c())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(ee).catch(r=>{if(c())return;let i=e.retry??(vt()?0:3),a=e.retryDelay??wt,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);if(t||!s){m(r);return}n++,e.onFail?.(n,r),lt(o).then(()=>f()?void 0:te()).then(()=>{t?m(r):h()})})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:p,start:()=>(p()?h():te().then(h),s)}}var Ot=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ye(this.gcTime)&&(this.#e=Ge.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(vt()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(Ge.clearTimeout(this.#e),this.#e=void 0)}};function kt(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{gt(e,()=>t.signal,()=>n=!0)},u=mt(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?ft:dt;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?jt:At,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:At(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function At(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function jt(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var Mt=class extends Ot{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Ft(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=Ft(this.options);e.data!==void 0&&(this.setState(Pt(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=ut(this.state.data,e,this.options);return this.#c({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#c({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(F).catch(F):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>Ze(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===pt||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>Ze(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!Xe(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#s||this.state.fetchStatus===`paused`&&this.state.status===`pending`?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#c({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=mt(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?kt(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=Dt({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof Et&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#c({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#c({type:`pause`})},onContinue:()=>{this.#c({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await o.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof Et){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#c({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0),this.scheduleGc()}}#c(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...Nt(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...Pt(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),I.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function Nt(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Tt(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function Pt(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function Ft(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var It=class extends Ot{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||Lt(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??(this.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},r=this.#r=Dt({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),i=this.state.status===`pending`,a=!r.canStart();try{if(i)t();else{this.#i({type:`pending`,variables:e,isPaused:a}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:a})}let o=await r.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#i({type:`success`,data:o}),o}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#r===r&&(this.#r=void 0),this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),I.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function Lt(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var Rt=class extends yt{#e;#t;#n;constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}build(e,t,n){let r=new It({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=zt(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=zt(e);if(typeof t==`string`){let n=this.#t.get(t);if(n){if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=zt(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}return!0}runNext(e){let t=zt(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){I.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>$e(t,e))}findAll(e={}){return this.getAll().filter(t=>$e(e,t))}notify(e){I.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return I.batch(()=>Promise.all(e.map(e=>e.continue().catch(F))))}};function zt(e){return e.options.scope?.id}var Bt=class extends yt{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){let r=t.queryKey,i=t.queryHash??et(r,t),a=this.get(i);return a||(a=new Mt({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){I.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>Qe(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>Qe(e,t)):t}notify(e){I.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){I.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){I.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Vt=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new Bt,this.#t=e.mutationCache||new Rt,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=bt.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=Ct.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Ze(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=Je(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return I.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;I.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return I.batch(()=>{let r=n.findAll(e),i=new Set(r);return r.forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,predicate:e=>i.has(e)},t)})}cancelQueries(e,t={}){let n={revert:!0,...t},r=I.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(F).catch(F)}invalidateQueries(e,t={}){return I.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=I.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(F)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(F)}async query(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t),r=n.isStaleByTime(Ze(t.staleTime,n))?await n.fetch(t):n.state.data,i=t.select;return i?i(r):r}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(Ze(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(F).catch(F)}infiniteQuery(e){return e._type=`infinite`,this.query(e)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(F).catch(F)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return Ct.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(tt(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{nt(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(tt(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{nt(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=et(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===pt&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}};function Ht(e){return e}var Ut=we(),Wt=C(()=>De(`status`,[j({status:S(`available`)}).strict(),j({status:S(`unavailable`),reason:g()}).strict()])),Gt=Ut,Kt=C(()=>de(g(),Gt)),qt=e=>Gt.parse(e),Jt=C(()=>j({code:g().min(1).max(160),message:g().min(1).max(512),details:Gt.optional()}).strict()),Yt=e=>Jt.parse(e),Xt=Kt,L=C(()=>g().refine(e=>e.trim().length>0)),Zt=Wt,Qt=C(()=>a([j({type:S(`action`)}).strict(),j({type:S(`custom`),data:Kt}).strict(),j({type:S(`choice`),options:k(j({value:Gt,label:L,description:L.optional()}))}).strict(),j({type:S(`form`),submitLabel:L.optional()}).strict(),j({type:S(`confirmation`),message:L,confirmLabel:L.optional(),cancelLabel:L.optional()}).strict()])),$t=C(()=>j({inputSchema:Xt.optional(),outputSchema:Xt.optional(),presentation:Qt.optional()}).strict()),en=C(()=>le().int().refine(e=>Number.isSafeInteger(e))),tn=C(()=>j({hint:L.pipe(g().max(120)),words:k(j({word:g().regex(/^\S{1,64}$/u),description:L.pipe(g().max(512)).optional(),arguments:Kt}).strict()).max(32).optional(),text:j({field:L.pipe(g().max(120)),arguments:Kt,requestIdField:L.pipe(g().max(120)).optional()}).strict().optional()}).strict().refine(e=>e.words!==void 0||e.text!==void 0,`slash arguments need words or text`)),nn=C(()=>j({order:en.optional()}).strict()),rn=C(()=>j({bindings:j({order:en.optional(),values:k(L).max(16)}).strict().optional(),agent:j({keybind:L.optional(),order:en.optional()}).strict().optional(),help:nn.optional(),menu:nn.optional(),palette:nn.optional(),slash:j({aliases:k(L).max(16),consumesDraft:he().optional(),order:en.optional(),arguments:tn.optional()}).strict().optional()}).strict()),an=C(()=>j({id:L.refine(e=>!e.includes(`:`)),title:L,category:L,description:L.optional(),projections:rn.optional(),action:$t.optional(),availability:Zt.optional()}).strict()),on=e=>an.parse(e),sn=C(()=>j({inputSchema:Xt.optional(),outputSchema:Xt.optional()}).strict()),cn=g().min(1).brand(),ln=C(()=>j({commandId:cn,command:j({namespace:g(),id:g()}).strict(),sourceId:g(),scope:g().optional(),title:g(),category:g(),description:g().optional(),order:le(),availability:Wt,action:sn.optional(),keybind:g().optional()}).strict());k(ln);var un=8192,R=L.pipe(g().max(un)),dn=L.pipe(g().max(60)),fn=ne({protocol:/^https?$/u}),pn=j({label:R,value:R}).strict(),mn={summary:R.optional(),facts:k(pn).max(4).optional(),body:R.optional(),bodyLabel:R.optional(),details:k(pn).max(24).optional()};De(`type`,[j({type:S(`choice`),message:dn,...mn,current:R.optional(),collapsedGroup:R.optional(),options:k(j({value:R,label:R,description:R.optional(),group:R.optional(),destructive:S(!0).optional()}).strict()).min(1).max(256)}).strict(),j({type:S(`text`),message:dn,...mn,placeholder:R.optional(),secret:he().optional()}).strict(),j({type:S(`confirmation`),message:dn,...mn,confirmLabel:R.optional(),cancelLabel:R.optional(),destructive:S(!0).optional()}).strict(),j({type:S(`decision`),message:dn,...mn,options:k(j({value:R,label:R,description:R.optional(),destructive:S(!0).optional()}).strict()).min(1).max(8).refine(e=>new Set(e.map(e=>e.value)).size===e.length,`Decision option values must be unique`),multiple:he().optional(),other:j({label:R,placeholder:R.optional(),maxLength:le().int().min(1).max(un),blank:R.optional()}).strict().optional(),escape:R.optional()}).strict().refine(e=>[e.escape,e.other?.blank].every(t=>t===void 0||e.options.some(e=>e.value===t)),`A decision's escape and blank answers must be offered options`)]),C(()=>De(`type`,[j({type:S(`info`),message:R,links:k(j({url:fn,label:R.optional()}).strict()).max(16).optional()}).strict(),j({type:S(`progress`),message:R}).strict(),j({type:S(`handoff`),url:fn,code:R.optional(),message:R.optional()}).strict(),j({type:S(`success`),message:R}).strict()]));var hn=class extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name=`WhistleActionError`}},gn=class extends Error{constructor(){super(`Whistle runtime is closed`),this.name=`WhistleClosedError`}};function _n(){let e=!1,t=Jn,n=[],r=[],i=!1,a=[],o=new Set,s=()=>{for(let e of o)e()};return Object.freeze({close:()=>{e||(e=!0,n=[],a=[],r=[],t=Jn,s(),o.clear())},contribute:t=>{if(En(t),e)throw new gn;Dn(t,n),On(t,n);let r=Symbol(`whistle-contribution`);Tn(t)||(n=[...n,{contribution:kn(t),generation:r}],i=!0,s());let a=!0;return qn(o=>{if(!a||e)return;let c={...t,commands:o};En(c);let l=n.findIndex(e=>e.generation===r),u=n.filter(e=>e.generation!==r);Dn(c,u),On(c,u);let d=kn(c);if(Tn(c)){if(l<0)return;n=u}else n=l<0?[...n,{contribution:d,generation:r}]:n.map(e=>e.generation===r?{contribution:d,generation:r}:e);i=!0,s()},()=>{a&&(a=!1,n.find(e=>e.generation===r)!==void 0&&(n=n.filter(e=>e.generation!==r),i=!0,s()))})},execute:async(t,r)=>{if(t.namespace.trim().length===0||t.id.trim().length===0)return{status:`invalid`};if(e)return{status:`closed`};let i=wn(t,n);if(i===void 0)return{status:`missing`};let o;try{let e=Xn(i);if(e.status===`unavailable`)return e;let n=a.at(-1)?.presenter;r.interaction===void 0&&n!==void 0&&vn.has(r.origin)&&(o=n({commandId:Cn(t.namespace,t.id),title:i.title}));let s={...r,signal:r.signal??new AbortController().signal};o!==void 0&&(s.interaction=o.interaction,s.signal=AbortSignal.any([s.signal,o.interaction.signal]));let c=await i.handler(s);return o?.settle({status:`handled`}),c===void 0?{status:`handled`}:{status:`handled`,result:c}}catch(e){let t=Qn(e instanceof Error?e:Error(`Command handler threw a non-Error value`));return o?.settle(o.interaction.signal.aborted?{status:`cancelled`}:{status:`failed`,message:t.message}),{status:`failed`,error:t}}},present:t=>{let n={presenter:t};return e||(a=[...a,n]),()=>{a=a.filter(e=>e!==n)}},snapshot:()=>{if(e)return Jn;let a=n.flatMap(e=>e.contribution.commands.map(Xn));return(i||a.some((e,t)=>!Zn(e,r[t])))&&(t=$n(n,a),r=a,i=!1),t},subscribe:t=>e?()=>void 0:(o.add(t),()=>{o.delete(t)})})}var vn=new Set([`browser`,`keyboard`,`menu`,`palette`,`slash`,`terminal`]),yn=16,bn=32,xn=64,Sn=256;function Cn(e,t){return cn.parse(`${e}:${t}`)}function wn(e,t){for(let n of t)if(n.contribution.namespace===e.namespace){for(let t of n.contribution.commands)if(t.id===e.id)return t}}function Tn(e){return e.commands.length===0}function En(e){z(e.sourceId,`source ID`),z(e.namespace,`namespace`),e.scope!==void 0&&z(e.scope,`scope`);for(let t of e.commands)Vn(t)}function Dn(e,t){t.find(t=>t.contribution.namespace===e.namespace&&t.contribution.sourceId!==e.sourceId)!==void 0&&B(`Namespace is already owned by another source`);let n=new Set,r=new Set;for(let i of t){let t=i.contribution.scope===e.scope;for(let e of i.contribution.commands)if(n.add(Cn(i.contribution.namespace,e.id)),t)for(let t of e.projections?.slash?.aliases??[])r.add(t)}for(let t of e.commands){let i=Cn(e.namespace,t.id);n.has(i)&&B(`Canonical command ID is already registered`),n.add(i);for(let e of t.projections?.slash?.aliases??[])r.has(e)&&B(`Slash alias is already registered`),r.add(e)}}function On(e,t){t.length>=xn&&B(`Live contribution capacity exceeded`),t.reduce((e,t)=>e+t.contribution.commands.length,0)+e.commands.length>Sn&&B(`Live command capacity exceeded`)}function kn(e){let t={sourceId:e.sourceId,namespace:e.namespace,commands:e.commands.map(An)};return e.scope===void 0?t:{...t,scope:e.scope}}function An(e){let t={id:e.id,title:e.title,category:e.category,handler:e.handler};return e.description!==void 0&&(t.description=e.description),e.action!==void 0&&(t.action=jn(e.action)),e.availability!==void 0&&(t.availability=e.availability),e.projections!==void 0&&(t.projections=Fn(e.projections)),t}function jn(e){let t={};return e.inputSchema!==void 0&&(t.inputSchema=Mn(e.inputSchema)),e.outputSchema!==void 0&&(t.outputSchema=Mn(e.outputSchema)),e.presentation!==void 0&&(t.presentation=Pn(e.presentation)),Object.freeze(t)}function Mn(e){return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Nn(t)])))}function Nn(e){return Array.isArray(e)?Object.freeze(e.map(Nn)):e!==null&&e instanceof Object?Object.freeze(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Nn(t)]))):e}function Pn(e){switch(e.type){case`action`:return Object.freeze({type:`action`});case`custom`:return Object.freeze({type:`custom`,data:Mn(e.data)});case`choice`:return Object.freeze({type:`choice`,options:Object.freeze(e.options.map(e=>Object.freeze({...e,value:Nn(e.value)})))});case`form`:return Object.freeze({...e});case`confirmation`:return Object.freeze({...e})}}function Fn(e){let t={};return e.bindings!==void 0&&(t.bindings=In(e.bindings)),e.agent!==void 0&&(t.agent=Ln(e.agent)),e.help!==void 0&&(t.help=Rn(e.help.order)),e.menu!==void 0&&(t.menu=Rn(e.menu.order)),e.palette!==void 0&&(t.palette=Rn(e.palette.order)),e.slash!==void 0&&(t.slash=zn(e.slash)),t}function In(e){let t={values:[...e.values]};return e.order!==void 0&&(t.order=e.order),t}function Ln(e){let t={};return e.keybind!==void 0&&(t.keybind=e.keybind),e.order!==void 0&&(t.order=e.order),t}function Rn(e){let t={};return e!==void 0&&(t.order=e),t}function zn(e){let t={aliases:[...e.aliases]};return e.order!==void 0&&(t.order=e.order),e.consumesDraft!==void 0&&(t.consumesDraft=e.consumesDraft),e.arguments!==void 0&&(t.arguments=Bn(e.arguments)),t}function Bn(e){let t={hint:e.hint};return e.words!==void 0&&(t.words=Object.freeze(e.words.map(e=>Object.freeze({...e,arguments:Mn(e.arguments)})))),e.text!==void 0&&(t.text=Object.freeze({...e.text,arguments:Mn(e.text.arguments)})),Object.freeze(t)}function Vn(e){z(e.id,`command ID`,!0),z(e.title,`title`),z(e.category,`category`),Hn(e.action),Un(e.projections)}function Hn(e){if(e?.presentation!==void 0)switch(e.presentation.type){case`action`:case`custom`:return;case`choice`:for(let t of e.presentation.options)z(t.label,`choice label`),t.description!==void 0&&z(t.description,`choice description`);return;case`form`:e.presentation.submitLabel!==void 0&&z(e.presentation.submitLabel,`submit label`);return;case`confirmation`:z(e.presentation.message,`confirmation message`),e.presentation.confirmLabel!==void 0&&z(e.presentation.confirmLabel,`confirmation label`),e.presentation.cancelLabel!==void 0&&z(e.presentation.cancelLabel,`cancellation label`)}}function Un(e){if(e!==void 0){for(let t of[e.bindings,e.palette,e.slash,e.help,e.menu,e.agent])t!==void 0&&Kn(t.order);if(e.bindings!==void 0&&Gn(e.bindings.values,`binding`),e.slash!==void 0){Gn(e.slash.aliases,`slash alias`);for(let t of e.slash.aliases)/\s/u.test(t)&&B(`slash alias must not contain whitespace`);Wn(e.slash.arguments)}e.agent?.keybind!==void 0&&z(e.agent.keybind,`agent keybind`)}}function Wn(e){if(e===void 0)return;z(e.hint,`argument hint`),e.words===void 0&&e.text===void 0&&B(`slash arguments need words or text`);let t=new Set;for(let n of e.words??[])z(n.word,`argument word`),/\s/u.test(n.word)&&B(`argument word must not contain whitespace`),t.has(n.word)&&B(`argument word is repeated`),t.add(n.word),n.description!==void 0&&z(n.description,`argument word description`);t.size>bn&&B(`argument word count exceeds 32`),e.text!==void 0&&(z(e.text.field,`argument text field`),e.text.requestIdField!==void 0&&z(e.text.requestIdField,`request id field`))}function Gn(e,t){e.length>yn&&B(`${t} count exceeds 16`);for(let n of e)z(n,t)}function z(e,t,n=!1){e.trim().length===0&&B(`${t} must not be blank`),n&&e.includes(`:`)&&B(`${t} must not contain a colon`)}function Kn(e){e!==void 0&&!Number.isSafeInteger(e)&&B(`order must be a safe integer`)}function qn(e=()=>void 0,t=()=>void 0){return Object.freeze({update:e,dispose:t})}function B(e){throw Error(e)}var Jn=Object.freeze({bindings:Object.freeze([]),palette:Object.freeze([]),slash:Object.freeze([]),help:Object.freeze([]),menu:Object.freeze([]),agent:Object.freeze([])}),Yn=Object.freeze({status:`available`});function Xn(e){let t=e.availability?.()??Yn;return t.status===`available`?Yn:Object.freeze({status:`unavailable`,reason:t.reason})}function Zn(e,t){return e.status===`available`?t?.status===`available`:t?.status===`unavailable`&&e.reason===t.reason}function Qn(e){if(e instanceof hn){let t={code:e.code,message:e.message};return Object.freeze(e.details===void 0?t:{...t,details:Nn(e.details)})}return Object.freeze({code:`command_failed`,message:e.message})}function $n(e,t){let n=[],r=[],i=[],a=[],o=[],s=[],c=0;for(let l of e){let e=l.contribution;for(let l of e.commands){let u=l.projections,d=t[c++]??Yn;if(u?.bindings!==void 0)for(let t of u.bindings.values)n.push({...or(e,l,u.bindings.order,d),binding:t});if(u?.palette!==void 0&&r.push({...or(e,l,u.palette.order,d)}),u?.slash!==void 0)for(let t of u.slash.aliases){let n={...or(e,l,u.slash.order,d),alias:t};u.slash.consumesDraft!==void 0&&(n={...n,consumesDraft:u.slash.consumesDraft}),u.slash.arguments!==void 0&&(n={...n,arguments:u.slash.arguments}),i.push(n)}u?.help!==void 0&&a.push({...or(e,l,u.help.order,d)}),u?.menu!==void 0&&o.push({...or(e,l,u.menu.order,d)}),u?.agent!==void 0&&s.push(cr(e,l,u.agent,d))}}return rr(n),ir(i),nr(r),nr(a),nr(o),nr(s),Object.freeze({bindings:ar(n),palette:ar(r),slash:ar(i),help:ar(a),menu:ar(o),agent:ar(s)})}var er=new TextEncoder;function tr(e,t){let n=er.encode(e),r=er.encode(t),i=Math.min(n.length,r.length);for(let e=0;e<i;e+=1){let t=n[e]??0,i=r[e]??0;if(t!==i)return t<i?-1:1}return n.length<r.length?-1:+(n.length>r.length)}function nr(e){e.sort((e,t)=>e.order-t.order||tr(e.commandId,t.commandId))}function rr(e){e.sort((e,t)=>e.order-t.order||tr(e.commandId,t.commandId)||tr(e.binding,t.binding))}function ir(e){e.sort((e,t)=>e.order-t.order||tr(e.commandId,t.commandId)||tr(e.alias,t.alias))}function ar(e){return Object.freeze(e.map(e=>Object.freeze(e)))}function or(e,t,n,r){let i=sr(e,t,n,r);return e.scope===void 0?i:{...i,scope:e.scope}}function sr(e,t,n,r){let i={commandId:Cn(e.namespace,t.id),command:Object.freeze({namespace:e.namespace,id:t.id}),sourceId:e.sourceId,title:t.title,category:t.category,order:n??0,availability:r},a=t.description===void 0?i:{...i,description:t.description};return t.action===void 0?a:{...a,action:t.action}}function cr(e,t,n,r){let i=or(e,t,n.order,r),a=i.action===void 0?i:{...i,action:lr(i.action)};return n.keybind===void 0?a:{...a,keybind:n.keybind}}function lr(e){let t={};return e.inputSchema!==void 0&&(t.inputSchema=e.inputSchema),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),Object.freeze(t)}function ur(e,t){let n=!1,r=[];for(let i of t){let{availability:t,handler:a,...o}=i,s=a,c=t===void 0?o:{...o,availability:t()};e.register(c,async({arguments:e,origin:t,signal:n})=>{let r=await s(e===void 0?{origin:t,signal:n}:{arguments:e,origin:t,signal:n});return r===void 0?void 0:qt(r)}).then(e=>{n?e():r.push(e)},e=>{console.warn(`App command ${i.id} was not registered`,e)})}return()=>{if(!n){n=!0;for(let e of r.splice(0))e()}}}function dr(e,t){console.error(JSON.stringify({source:`agar`,operation:e,failureKind:t instanceof Error?`Error`:`NonErrorThrown`}),ze(t))}var fr=Symbol(`workers-module`);Symbol.dispose||(Symbol.dispose=Symbol.for(`dispose`)),Symbol.asyncDispose||(Symbol.asyncDispose=Symbol.for(`asyncDispose`)),Promise.withResolvers||(Promise.withResolvers=function(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}});var pr=globalThis[fr],mr=pr?pr.RpcTarget:class{},hr=async function(){}.constructor,gr=typeof Buffer<`u`?Buffer.prototype:void 0;function _r(e){switch(typeof e){case`boolean`:case`number`:case`string`:return`primitive`;case`undefined`:return`undefined`;case`object`:case`function`:break;case`bigint`:return`bigint`;default:return`unsupported`}if(e===null)return`primitive`;let t=Object.getPrototypeOf(e);switch(t){case Object.prototype:return`object`;case Function.prototype:case hr.prototype:return`function`;case Array.prototype:return`array`;case Date.prototype:return`date`;case Uint8Array.prototype:case gr:case ArrayBuffer.prototype:case DataView.prototype:case Int8Array.prototype:case Uint8ClampedArray.prototype:case Int16Array.prototype:case Uint16Array.prototype:case Int32Array.prototype:case Uint32Array.prototype:case BigInt64Array.prototype:case BigUint64Array.prototype:case Float32Array.prototype:case Float64Array.prototype:return`bytes`;case WritableStream.prototype:return`writable`;case ReadableStream.prototype:return`readable`;case URL.prototype:return`url`;case Headers.prototype:return`headers`;case Request.prototype:return`request`;case Response.prototype:return`response`;case Blob.prototype:return`blob`;case W.prototype:return`stub`;case G.prototype:return`rpc-promise`;default:if(pr){if(t==pr.RpcStub.prototype||e instanceof pr.ServiceStub)return`rpc-target`;if(t==pr.RpcPromise.prototype||t==pr.RpcProperty.prototype)return`rpc-thenable`}return e instanceof mr?`rpc-target`:e instanceof Error?`error`:`unsupported`}}function vr(){throw Error(`RPC map() implementation was not loaded.`)}var yr={applyMap:vr,sendMap:vr};function br(){throw Error(`Stream implementation was not loaded.`)}var V={createWritableStreamHook:br,createWritableStreamFromHook:br,createReadableStreamHook:br},xr=class{stream(e,t){let n=this.call(e,t),r;try{r=n.pull()}catch(e){throw n.dispose(),e}let i;return r instanceof Promise?i=r.then(e=>{e.dispose()}):(r.dispose(),i=Promise.resolve()),{promise:i}}},H=class extends xr{error;constructor(e){super(),this.error=e}call(e,t){return t.dispose(),this}map(e,t,n){for(let e of t)e.dispose();return this}get(e){return this}dup(){return this}pull(){return Promise.reject(this.error)}ignoreUnhandledRejections(){}dispose(){}onBroken(e){try{e(this.error)}catch(e){Promise.resolve(e)}}},Sr=new H(Error(`Attempted to use RPC stub after it has been disposed.`)),Cr=(e,t,n)=>e.call(t,n);function wr(e,t){let n=Cr;Cr=e;try{return t()}finally{Cr=n}}var U=Symbol(`realStub`),Tr={apply(e,t,n){let r=e.raw;return new G(Cr(r.hook,r.pathIfPromise||[],K.fromAppParams(n)),[])},get(e,t,n){let r=e.raw;if(t===U)return r;if(t in G.prototype)return r[t];if(typeof t==`string`)return new G(r.hook,r.pathIfPromise?[...r.pathIfPromise,t]:[t]);if(t===Symbol.dispose&&(!r.pathIfPromise||r.pathIfPromise.length==0))return()=>{r.hook.dispose(),r.hook=Sr}},has(e,t){let n=e.raw;return t===U?!0:t in G.prototype?t in n:typeof t==`string`||t===Symbol.dispose&&(!n.pathIfPromise||n.pathIfPromise.length==0)},construct(e,t){throw Error(`An RPC stub cannot be used as a constructor.`)},defineProperty(e,t,n){throw Error(`Can't define properties on RPC stubs.`)},deleteProperty(e,t){throw Error(`Can't delete properties on RPC stubs.`)},getOwnPropertyDescriptor(e,t){},getPrototypeOf(e){return Object.getPrototypeOf(e.raw)},isExtensible(e){return!1},ownKeys(e){return[]},preventExtensions(e){return!0},set(e,t,n,r){throw Error(`Can't assign properties on RPC stubs.`)},setPrototypeOf(e,t){throw Error(`Can't override prototype of RPC stubs.`)}},W=class e extends mr{constructor(e,t){if(super(),!(e instanceof xr)){let n=e;if(e=n instanceof mr||n instanceof Function?Fr.create(n,void 0):new q(K.fromAppReturn(n)),t)throw TypeError(`RpcStub constructor expected one argument, received two.`)}this.hook=e,this.pathIfPromise=t;let n=()=>{};return n.raw=this,new Proxy(n,Tr)}hook;pathIfPromise;dup(){let t=this[U];return t.pathIfPromise?new e(t.hook.get(t.pathIfPromise)):new e(t.hook.dup())}onRpcBroken(e){this[U].hook.onBroken(e)}map(e){let{hook:t,pathIfPromise:n}=this[U];return yr.sendMap(t,n||[],e)}toString(){return`[object RpcStub]`}},G=class extends W{constructor(e,t){if(e instanceof xr)super(e,t??[]);else{if(t!==void 0)throw TypeError(`RpcPromise constructor expected one argument, received two.`);let n=_r(e);if(n===`rpc-promise`){let t=Ar(e);if(t.pathIfPromise.length>0)super(t.hook,t.pathIfPromise);else{let e=t.hook;t.hook=Sr,super(e,[])}}else if(n===`rpc-thenable`)super(Fr.create(e,void 0),[]);else{let t=new Ir(Promise.resolve(e).then(e=>new q(K.fromAppReturn(e))));t.ignoreUnhandledRejections(),super(t,[])}}}then(e,t){return jr(this).then(...arguments)}catch(e){return jr(this).catch(...arguments)}finally(e){return jr(this).finally(...arguments)}toString(){return`[object RpcPromise]`}};function Er(e){let{hook:t,pathIfPromise:n}=e[U];return n&&n.length>0?t.get(n):t}function Dr(e){let{hook:t,pathIfPromise:n}=e[U];return n?t.get(n):t.dup()}function Or(e){let{hook:t,pathIfPromise:n}=e[U];if(!(n&&n.length>0))return t}function kr(e){return e[U].hook}function Ar(e){return e[U]}async function jr(e){let{hook:t,pathIfPromise:n}=e[U];return n.length>0&&(t=t.get(n)),(await t.pull()).deliverResolve()}var K=class e{value;source;hooks;promises;static fromAppParams(t){return new e(t,`params`)}static fromAppReturn(t){return new e(t,`return`)}static fromArray(t){let n=[],r=[],i=[];for(let e of t){e.ensureDeepCopied();for(let t of e.hooks)n.push(t);for(let t of e.promises)t.parent===e&&(t={parent:i,property:i.length,promise:t.promise}),r.push(t);i.push(e.value)}return new e(i,`owned`,n,r)}static forEvaluate(t,n){return new e(null,`owned`,t,n)}static deepCopyFrom(t,n,r){let i=new e(null,`owned`,[],[]);return i.value=i.deepCopy(t,n,`value`,i,!0,r),i}constructor(e,t,n,r){this.value=e,this.source=t,this.hooks=n,this.promises=r}rpcTargets;getHookForRpcTarget(e,t,n=!0){if(this.source===`params`){if(n){let t=e;typeof t.dup==`function`&&(e=t.dup())}return Fr.create(e,t)}if(this.source===`return`){let r=this.rpcTargets?.get(e);return r?n?r.dup():(this.rpcTargets?.delete(e),r):(r=Fr.create(e,t),n?(this.rpcTargets||=new Map,this.rpcTargets.set(e,r),r.dup()):r)}throw Error(`owned payload shouldn't contain raw RpcTargets`)}getHookForWritableStream(e,t,n=!0){if(this.source===`params`)return V.createWritableStreamHook(e);if(this.source===`return`){let t=this.rpcTargets?.get(e);return t?n?t.dup():(this.rpcTargets?.delete(e),t):(t=V.createWritableStreamHook(e),n?(this.rpcTargets||=new Map,this.rpcTargets.set(e,t),t.dup()):t)}throw Error(`owned payload shouldn't contain raw WritableStreams`)}getHookForReadableStream(e,t,n=!0){if(this.source===`params`)return V.createReadableStreamHook(e);if(this.source===`return`){let t=this.rpcTargets?.get(e);return t?n?t.dup():(this.rpcTargets?.delete(e),t):(t=V.createReadableStreamHook(e),n?(this.rpcTargets||=new Map,this.rpcTargets.set(e,t),t.dup()):t)}throw Error(`owned payload shouldn't contain raw ReadableStreams`)}deepCopy(e,t,n,r,i,a){switch(_r(e)){case`unsupported`:return e;case`primitive`:case`bigint`:case`date`:case`bytes`:case`blob`:case`url`:case`error`:case`undefined`:return e;case`array`:{let t=e,n=t.length,r=Array(n);for(let e=0;e<n;e++)r[e]=this.deepCopy(t[e],t,e,r,i,a);return r}case`object`:{let t={},n=e;for(let e in n)t[e]=this.deepCopy(n[e],n,e,t,i,a);return t}case`stub`:case`rpc-promise`:{let t=e,a;if(a=i?Dr(t):Er(t),t instanceof G){let e=new G(a,[]);return this.promises.push({parent:r,property:n,promise:e}),e}return this.hooks.push(a),new W(a)}case`function`:case`rpc-target`:{let n=e,r;return r=a?a.getHookForRpcTarget(n,t,i):Fr.create(n,t),this.hooks.push(r),new W(r)}case`rpc-thenable`:{let o=e,s;return s=a?new G(a.getHookForRpcTarget(o,t,i),[]):new G(Fr.create(o,t),[]),this.promises.push({parent:r,property:n,promise:s}),s}case`writable`:{let n=e,r;return r=a?a.getHookForWritableStream(n,t,i):V.createWritableStreamHook(n),this.hooks.push(r),n}case`readable`:{let n=e,r;return r=a?a.getHookForReadableStream(n,t,i):V.createReadableStreamHook(n),this.hooks.push(r),n}case`headers`:return new Headers(e);case`request`:{let t=e;return t.body&&this.deepCopy(t.body,t,`body`,t,i,a),new Request(t)}case`response`:{let t=e;return t.body&&this.deepCopy(t.body,t,`body`,t,i,a),new Response(t.body,t)}default:throw Error(`unreachable`)}}ensureDeepCopied(){if(this.source!==`owned`){let e=this.source===`params`;this.hooks=[],this.promises=[];try{this.value=this.deepCopy(this.value,void 0,`value`,this,e,this)}catch(e){throw this.hooks=void 0,this.promises=void 0,e}if(this.source=`owned`,this.rpcTargets&&this.rpcTargets.size>0)throw Error(`Not all rpcTargets were accounted for in deep-copy?`);this.rpcTargets=void 0}}deliverTo(t,n,r){if(this.ensureDeepCopied(),this.value instanceof G)e.deliverRpcPromiseTo(this.value,t,n,r);else{t[n]=this.value;for(let t of this.promises)e.deliverRpcPromiseTo(t.promise,t.parent,t.property,r)}}static deliverRpcPromiseTo(t,n,r,i){let a=Or(t);if(!a)throw Error(`property promises should have been resolved earlier`);let o=a.pull();o instanceof e?o.deliverTo(n,r,i):i.push(o.then(e=>{let t=[];if(e.deliverTo(n,r,t),t.length>0)return Promise.all(t)}))}async deliverCall(t,n){try{let r=[];this.deliverTo(this,`value`,r),r.length>0&&await Promise.all(r);let i=Function.prototype.apply.call(t,n,this.value);return i instanceof G?e.fromAppReturn(i):e.fromAppReturn(await i)}finally{this.dispose()}}async deliverStreamWrite(t){try{let n=[];this.deliverTo(this,`value`,n),n.length>0&&await Promise.all(n);let r=this.value[0];return(this.hooks.length>0||this.promises.length>0)&&r instanceof Object?(Symbol.dispose in r||Object.defineProperty(r,Symbol.dispose,{value:()=>this.dispose(),writable:!0,enumerable:!1,configurable:!0}),await t.write(r),e.fromAppReturn(void 0)):(await t.write(r),this.dispose(),e.fromAppReturn(void 0))}catch(e){throw this.dispose(),e}}async deliverResolve(){try{let e=[];this.deliverTo(this,`value`,e),e.length>0&&await Promise.all(e);let t=this.value;return t instanceof Object&&(Symbol.dispose in t||Object.defineProperty(t,Symbol.dispose,{value:()=>this.dispose(),writable:!0,enumerable:!1,configurable:!0})),t}catch(e){throw this.dispose(),e}}dispose(){if(this.source===`owned`)this.hooks.forEach(e=>e.dispose()),this.promises.forEach(e=>e.promise[Symbol.dispose]());else if(this.source===`return`&&(this.disposeImpl(this.value,void 0),this.rpcTargets&&this.rpcTargets.size>0))throw Error(`Not all rpcTargets were accounted for in disposeImpl()?`);this.source=`owned`,this.hooks=[],this.promises=[]}disposeImpl(e,t){switch(_r(e)){case`unsupported`:case`primitive`:case`bigint`:case`bytes`:case`blob`:case`date`:case`url`:case`error`:case`undefined`:return;case`array`:{let t=e,n=t.length;for(let e=0;e<n;e++)this.disposeImpl(t[e],t);return}case`object`:{let t=e;for(let e in t)this.disposeImpl(t[e],t);return}case`stub`:case`rpc-promise`:{let t=Or(e);t&&t.dispose();return}case`function`:case`rpc-target`:{let t=e,n=this.rpcTargets?.get(t);n?(n.dispose(),this.rpcTargets.delete(t)):Pr(t);return}case`rpc-thenable`:return;case`headers`:return;case`request`:{let t=e;t.body&&this.disposeImpl(t.body,t);return}case`response`:{let t=e;t.body&&this.disposeImpl(t.body,t);return}case`writable`:{let t=e,n=this.rpcTargets?.get(t);n?this.rpcTargets.delete(t):n=V.createWritableStreamHook(t),n.dispose();return}case`readable`:{let t=e,n=this.rpcTargets?.get(t);n?this.rpcTargets.delete(t):n=V.createReadableStreamHook(t),n.dispose();return}default:return}}ignoreUnhandledRejections(){this.hooks?(this.hooks.forEach(e=>{e.ignoreUnhandledRejections()}),this.promises.forEach(e=>kr(e.promise).ignoreUnhandledRejections())):this.ignoreUnhandledRejectionsImpl(this.value)}ignoreUnhandledRejectionsImpl(e){switch(_r(e)){case`unsupported`:case`primitive`:case`bigint`:case`bytes`:case`blob`:case`date`:case`error`:case`undefined`:case`function`:case`rpc-target`:case`writable`:case`readable`:case`url`:case`headers`:case`request`:case`response`:return;case`array`:{let t=e,n=t.length;for(let e=0;e<n;e++)this.ignoreUnhandledRejectionsImpl(t[e]);return}case`object`:{let t=e;for(let e in t)this.ignoreUnhandledRejectionsImpl(t[e]);return}case`stub`:case`rpc-promise`:kr(e).ignoreUnhandledRejections();return;case`rpc-thenable`:e.then(e=>{},e=>{});return;default:return}}};function Mr(e,t,n,r){for(let i=0;i<n.length;i++){t=e;let a=n[i];if(a in Object.prototype){e=void 0;continue}switch(_r(e)){case`object`:case`function`:e=Object.hasOwn(e,a)?e[a]:void 0;break;case`array`:e=Number.isInteger(a)&&a>=0?e[a]:void 0;break;case`rpc-target`:case`rpc-thenable`:if(Object.hasOwn(e,a))throw TypeError(`Attempted to access property '${a}', which is an instance property of the RpcTarget. To avoid leaking private internals, instance properties cannot be accessed over RPC. If you want to make this property available over RPC, define it as a method or getter on the class, instead of an instance property.`);e=e[a],r=null;break;case`stub`:case`rpc-promise`:{let{hook:t,pathIfPromise:r}=Ar(e);return{hook:t,remainingPath:r?r.concat(n.slice(i)):n.slice(i)}}case`writable`:e=void 0;break;case`readable`:e=void 0;break;case`primitive`:case`bigint`:case`bytes`:case`blob`:case`date`:case`error`:case`url`:case`headers`:case`request`:case`response`:e=void 0;break;case`undefined`:e=e[a];break;case`unsupported`:if(i===0)throw TypeError(`RPC stub points at a non-serializable type.`);{let e=n.slice(0,i).join(`.`),t=n.slice(0,i).join(`.`);throw TypeError(`'${e}' is not a serializable type, so property ${t} cannot be accessed.`)}default:throw TypeError(`unreachable`)}}if(e instanceof G){let{hook:t,pathIfPromise:n}=Ar(e);return{hook:t,remainingPath:n||[]}}return{value:e,parent:t,owner:r}}var Nr=class extends xr{call(e,t){let n;try{let{value:t,owner:r}=this.getValue();n=Mr(t,void 0,e,r)}catch(e){return t.dispose(),new H(e)}return n.hook?n.hook.call(n.remainingPath,t):typeof n.value==`function`?new Ir(t.deliverCall(n.value,n.parent).then(e=>new q(e))):(t.dispose(),new H(TypeError(`'${e.join(`.`)}' is not a function.`)))}map(e,t,n){try{let r;try{let{value:t,owner:n}=this.getValue();r=Mr(t,void 0,e,n)}catch(e){for(let e of t)e.dispose();throw e}return r.hook?r.hook.map(r.remainingPath,t,n):yr.applyMap(r.value,r.parent,r.owner,t,n)}catch(e){return new H(e)}}get(e){try{let{value:t,owner:n}=this.getValue();if(e.length===0&&n===null){if(t instanceof Object&&`then`in t)return this.dup();throw Error(`Can't dup an RpcTarget stub as a promise.`)}let r=Mr(t,void 0,e,n);return r.hook?r.hook.get(r.remainingPath):new q(K.deepCopyFrom(r.value,r.parent,r.owner))}catch(e){return new H(e)}}},q=class e extends Nr{constructor(e){super(),this.payload=e}payload;getPayload(){if(this.payload)return this.payload;throw Error(`Attempted to use an RPC StubHook after it was disposed.`)}getValue(){let e=this.getPayload();return{value:e.value,owner:e}}dup(){let t=this.getPayload();return new e(K.deepCopyFrom(t.value,void 0,t))}pull(){return this.getPayload()}ignoreUnhandledRejections(){this.payload&&this.payload.ignoreUnhandledRejections()}dispose(){this.payload&&=(this.payload.dispose(),void 0)}onBroken(e){this.payload&&this.payload.value instanceof W&&this.payload.value.onRpcBroken(e)}};function Pr(e){if(Symbol.dispose in e)try{e[Symbol.dispose]()}catch(e){Promise.reject(e)}}var Fr=class e extends Nr{static create(t,n){return typeof t!=`function`&&(n=void 0),new e(t,n)}constructor(e,t,n){super(),this.target=e,this.parent=t,n?n.refcount&&(this.refcount=n.refcount,++this.refcount.count):Symbol.dispose in e&&(this.refcount={count:1})}target;parent;refcount;getTarget(){if(this.target)return this.target;throw Error(`Attempted to use an RPC StubHook after it was disposed.`)}getValue(){return{value:this.getTarget(),owner:null}}dup(){return new e(this.getTarget(),this.parent,this)}pull(){let e=this.getTarget();return`then`in e?Promise.resolve(e).then(e=>K.fromAppReturn(e)):Promise.reject(Error(`Tried to resolve a non-promise stub.`))}ignoreUnhandledRejections(){}dispose(){this.target&&=(this.refcount&&--this.refcount.count==0&&Pr(this.target),void 0)}onBroken(e){let t=this.target;t&&`then`in t&&Promise.resolve(t).then(()=>{},e)}},Ir=class e extends xr{promise;resolution;constructor(e){super(),this.promise=e.then(e=>(this.resolution=e,e))}call(t,n){return n.ensureDeepCopied(),new e(this.promise.then(e=>e.call(t,n),e=>{throw n.dispose(),e}))}stream(e,t){return t.ensureDeepCopied(),{promise:this.promise.then(n=>n.stream(e,t).promise,e=>{throw t.dispose(),e})}}map(t,n,r){return new e(this.promise.then(e=>e.map(t,n,r),e=>{for(let e of n)e.dispose();throw e}))}get(t){return new e(this.promise.then(e=>e.get(t)))}dup(){return this.resolution?this.resolution.dup():new e(this.promise.then(e=>e.dup()))}pull(){return this.resolution?this.resolution.pull():this.promise.then(e=>e.pull())}ignoreUnhandledRejections(){this.resolution?this.resolution.ignoreUnhandledRejections():this.promise.then(e=>{e.ignoreUnhandledRejections()},e=>{})}dispose(){this.promise.then(e=>e.dispose(),()=>{})}onBroken(e){this.resolution?this.resolution.onBroken(e):this.promise.then(t=>{t.onBroken(e)},e)}},Lr={maxBigIntDigits:16384,maxDepth:256,maxMessageSize:33554432},Rr=new Uint8Array(new Uint16Array([1]).buffer)[0]===1,zr=[`ArrayBuffer`,`DataView`,`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`Int16Array`,`Uint16Array`,`Int32Array`,`Uint32Array`,`BigInt64Array`,`BigUint64Array`,`Float32Array`,`Float64Array`];function Br(e){return zr.includes(e)}var Vr={ArrayBuffer:void 0,DataView:void 0,Int8Array:void 0,Uint8Array:void 0,Uint8ClampedArray:void 0,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,BigInt64Array:8,BigUint64Array:8,Float32Array:4,Float64Array:8},Hr={ArrayBuffer:ArrayBuffer.prototype,DataView:DataView.prototype,Int8Array:Int8Array.prototype,Uint8ClampedArray:Uint8ClampedArray.prototype,Int16Array:Int16Array.prototype,Uint16Array:Uint16Array.prototype,Int32Array:Int32Array.prototype,Uint32Array:Uint32Array.prototype,BigInt64Array:BigInt64Array.prototype,BigUint64Array:BigUint64Array.prototype,Float32Array:Float32Array.prototype,Float64Array:Float64Array.prototype},Ur=new Map;for(let e of Object.keys(Hr))Ur.set(Hr[e],e);function Wr(e,t){if(t!==2&&t!==4&&t!==8)throw RangeError(`Unsupported element size: ${t}`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let r=0;r<e.byteLength;r+=t)switch(t){case 2:n.setUint16(r,n.getUint16(r,!1),!0);break;case 4:n.setUint32(r,n.getUint32(r,!1),!0);break;case 8:n.setBigUint64(r,n.getBigUint64(r,!1),!0)}}var Gr=new class{exportStub(e){throw Error(`Cannot serialize RPC stubs without an RPC session.`)}exportPromise(e){throw Error(`Cannot serialize RPC stubs without an RPC session.`)}getImport(e){}unexport(e){}createPipe(e){throw Error(`Cannot create pipes without an RPC session.`)}onSendError(e){}};async function Kr(e,t){let n=await new Response(e).blob();return n.type===t?n:n.slice(0,n.size,t)}var qr={__proto__:null,Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError},Jr=class e{exporter;source;encodingLevel;constructor(e,t,n){this.exporter=e,this.source=t,this.encodingLevel=n}static devaluate(t,n,r=Gr,i,a=`string`){let o=new e(r,i,a);try{return o.devaluateImpl(t,n,0)}catch(e){if(o.exports)try{r.unexport(o.exports)}catch{}throw e}}exports;devaluateImpl(e,t,n){if(n>=256)throw Error(`Serialization exceeded maximum allowed depth. (Does the message contain cycles?)`);switch(_r(e)){case`unsupported`:{let t;try{t=`Cannot serialize value: ${e}`}catch{t=`Cannot serialize value: (couldn't stringify value)`}throw TypeError(t)}case`primitive`:return typeof e==`number`&&!isFinite(e)?this.encodingLevel===`structuredClonable`?e:e===1/0?[`inf`]:e===-1/0?[`-inf`]:[`nan`]:e;case`object`:{let t=e,r={};for(let e in t)r[e]=this.devaluateImpl(t[e],t,n+1);return r}case`array`:{let t=e,r=t.length,i=Array(r);for(let e=0;e<r;e++)i[e]=this.devaluateImpl(t[e],t,n+1);return[i]}case`bigint`:return this.encodingLevel===`structuredClonable`?e:[`bigint`,e.toString()];case`date`:{if(this.encodingLevel===`structuredClonable`)return e;let t=e.getTime();return[`date`,Number.isNaN(t)?null:t]}case`bytes`:{let t=Ur.get(Object.getPrototypeOf(e)),n;if(t===`ArrayBuffer`)n=new Uint8Array(e);else if(t===void 0)n=e;else{let r=e;n=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);let i=Vr[t];!Rr&&i&&(n=n.slice(),Wr(n,i))}if(this.encodingLevel===`structuredClonable`||this.encodingLevel===`jsonCompatibleWithBytes`)return t===void 0?[`bytes`,n]:[`bytes`,n,t];let r;if(n.toBase64)r=n.toBase64({omitPadding:!0});else if(typeof Buffer<`u`)r=(n instanceof Buffer?n:Buffer.from(n.buffer,n.byteOffset,n.byteLength)).toString(`base64`);else{let e=``;for(let t=0;t<n.length;t++)e+=String.fromCharCode(n[t]);r=btoa(e)}return r=r.replace(/=+$/,``),t===void 0?[`bytes`,r]:[`bytes`,r,t]}case`url`:return[`url`,e.href];case`headers`:return[`headers`,[...e]];case`request`:{let t=e,r={};t.method!==`GET`&&(r.method=t.method);let i=[...t.headers];if(i.length>0&&(r.headers=i),t.body)r.body=this.devaluateImpl(t.body,t,n+1),r.duplex=t.duplex||`half`;else if(t.body===void 0&&![`GET`,`HEAD`,`OPTIONS`,`TRACE`,`DELETE`].includes(t.method)){let e=t.arrayBuffer(),n=new ReadableStream({async start(t){try{t.enqueue(new Uint8Array(await e)),t.close()}catch(e){t.error(e)}}}),i=V.createReadableStreamHook(n);r.body=[`readable`,this.exporter.createPipe(n,i)],r.duplex=t.duplex||`half`}t.cache&&t.cache!=="default"&&(r.cache=t.cache),t.redirect!==`follow`&&(r.redirect=t.redirect),t.integrity&&(r.integrity=t.integrity),t.mode&&t.mode!==`cors`&&(r.mode=t.mode),t.credentials&&t.credentials!==`same-origin`&&(r.credentials=t.credentials),t.referrer&&t.referrer!==`about:client`&&(r.referrer=t.referrer),t.referrerPolicy&&(r.referrerPolicy=t.referrerPolicy),t.keepalive&&(r.keepalive=t.keepalive);let a=t;return a.cf&&(r.cf=a.cf),a.encodeResponseBody&&a.encodeResponseBody!==`automatic`&&(r.encodeResponseBody=a.encodeResponseBody),[`request`,t.url,r]}case`response`:{let t=e,r=this.devaluateImpl(t.body,t,n+1),i={};t.status!==200&&(i.status=t.status),t.statusText&&(i.statusText=t.statusText);let a=[...t.headers];a.length>0&&(i.headers=a);let o=t;if(o.cf&&(i.cf=o.cf),o.encodeBody&&o.encodeBody!==`automatic`&&(i.encodeBody=o.encodeBody),o.webSocket)throw TypeError(`Can't serialize a Response containing a webSocket.`);return[`response`,r,i]}case`blob`:{let t=e,n=t.stream(),r=V.createReadableStreamHook(n),i=this.exporter.createPipe(n,r);return[`blob`,t.type,[`readable`,i]]}case`error`:{let t=e,r=this.exporter.onSendError(t);r&&(t=r);let i=t,a,o=(e,r)=>{let i=this.exports?.length??0;try{let i=this.devaluateImpl(r,t,n+1);a||={},a[e]=i}catch{if(this.exports&&this.exports.length>i){let e=this.exports.splice(i);try{this.exporter.unexport(e)}catch{}}}};for(let e of Object.keys(t))e!==`name`&&e!==`message`&&e!==`stack`&&o(e,i[e]);`cause`in t&&o(`cause`,i.cause),t instanceof AggregateError&&o(`errors`,t.errors);let s=[`error`,t.name,t.message];return a?(s.push(r&&r.stack?r.stack:null),s.push(a)):r&&r.stack&&s.push(r.stack),s}case`undefined`:return this.encodingLevel===`structuredClonable`?void 0:[`undefined`];case`stub`:case`rpc-promise`:{if(!this.source)throw Error(`Can't serialize RPC stubs in this context.`);let{hook:t,pathIfPromise:n}=Ar(e),r=this.exporter.getImport(t);return r===void 0?(t=n?t.get(n):t.dup(),this.devaluateHook(n?`promise`:`export`,t)):n?n.length>0?[`pipeline`,r,n]:[`pipeline`,r]:[`import`,r]}case`function`:case`rpc-target`:{if(!this.source)throw Error(`Can't serialize RPC stubs in this context.`);let n=this.source.getHookForRpcTarget(e,t);return this.devaluateHook(`export`,n)}case`rpc-thenable`:{if(!this.source)throw Error(`Can't serialize RPC stubs in this context.`);let n=this.source.getHookForRpcTarget(e,t);return this.devaluateHook(`promise`,n)}case`writable`:{if(!this.source)throw Error(`Can't serialize WritableStream in this context.`);let n=this.source.getHookForWritableStream(e,t);return this.devaluateHook(`writable`,n)}case`readable`:{if(!this.source)throw Error(`Can't serialize ReadableStream in this context.`);let n=e,r=this.source.getHookForReadableStream(n,t);return[`readable`,this.exporter.createPipe(n,r)]}default:throw Error(`unreachable`)}}devaluateHook(e,t){this.exports||=[];let n=e===`promise`?this.exporter.exportPromise(t):this.exporter.exportStub(t);return this.exports.push(n),[e,n]}};new class{importStub(e){throw Error(`Cannot deserialize RPC stubs without an RPC session.`)}importPromise(e){throw Error(`Cannot deserialize RPC stubs without an RPC session.`)}getExport(e){}getPipeReadable(e){throw Error(`Cannot retrieve pipe readable without an RPC session.`)}getLimits(){return Lr}};function Yr(e,t){return new G(new Ir(new Response(t).arrayBuffer().then(t=>{let n=new Uint8Array(t),r=new Request(e,{body:n});return new q(K.fromAppReturn(r))})),[])}function Xr(e,t){return new G(new Ir(Kr(e,t).then(e=>new q(K.fromAppReturn(e)))),[])}var Zr=class e{importer;encodingLevel;limits;constructor(e,t=`string`){this.importer=e,this.encodingLevel=t,this.limits=e.getLimits()}hooks=[];promises=[];evaluate(e){return this.evaluateWithDepth(e,0)}evaluateWithDepth(e,t){let n=K.forEvaluate(this.hooks,this.promises);try{return n.value=this.evaluateImpl(e,n,`value`,t),n}catch(e){throw n.dispose(),e}}evaluateCopy(e){return this.evaluate(structuredClone(e))}evaluateImpl(t,n,r,i){let a=this.limits.maxDepth;if(i>=a)throw TypeError(`Deserialization exceeded maximum allowed message depth of ${a}.`);if(this.encodingLevel===`structuredClonable`&&(t instanceof Date||typeof t==`bigint`))return t;if(t instanceof Array){if(t.length==1&&t[0]instanceof Array){let e=t[0];for(let t=0;t<e.length;t++)e[t]=this.evaluateImpl(e[t],e,t,i+1);return e}switch(t[0]){case`bigint`:if(typeof t[1]==`string`){let e=t[1],n=this.limits.maxBigIntDigits;if(e.length>n)throw TypeError(`Deserialized bigint exceeds maximum length of ${n} digits.`);return BigInt(e)}break;case`date`:if(t[1]===null)return new Date(NaN);if(typeof t[1]==`number`)return new Date(t[1]);break;case`bytes`:{let e;if(t[1]instanceof Uint8Array)e=t[1];else if(typeof t[1]==`string`){if(typeof Buffer<`u`)e=Buffer.from(t[1],`base64`);else if(Uint8Array.fromBase64)e=Uint8Array.fromBase64(t[1]);else{let n=atob(t[1]),r=n.length;e=new Uint8Array(r);for(let t=0;t<r;t++)e[t]=n.charCodeAt(t)}}else break;if(t.length===2)return e;if(typeof t[2]!=`string`)throw TypeError(`Unknown bytes type marker type: ${typeof t[2]}`);if(!Br(t[2])){let e=t[2].slice(0,64);throw TypeError(`Unknown bytes type marker: ${e}`)}let n=t[2],r=Vr[n];if(r!==void 0&&e.byteLength%r!==0)throw TypeError(`Invalid byte length ${e.byteLength} for ${n}; expected a multiple of ${r}`);let i=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);switch(!Rr&&r!==void 0&&Wr(new Uint8Array(i),r),n){case`ArrayBuffer`:return i;case`DataView`:return new DataView(i);case`Int8Array`:return new Int8Array(i);case`Uint8Array`:return new Uint8Array(i);case`Uint8ClampedArray`:return new Uint8ClampedArray(i);case`Int16Array`:return new Int16Array(i);case`Uint16Array`:return new Uint16Array(i);case`Int32Array`:return new Int32Array(i);case`Uint32Array`:return new Uint32Array(i);case`BigInt64Array`:return new BigInt64Array(i);case`BigUint64Array`:return new BigUint64Array(i);case`Float32Array`:return new Float32Array(i);case`Float64Array`:return new Float64Array(i)}}case`error`:if(t.length>=3&&typeof t[1]==`string`&&typeof t[2]==`string`){let e=qr[t[1]]||Error,n=e===AggregateError?new e([],t[2]):new e(t[2]);if(typeof t[3]==`string`&&(n.stack=t[3]),t.length>=5){let e=t[4];if(!e||typeof e!=`object`||Array.isArray(e))break;let r=n,a=e;for(let e of Object.keys(a))if(e!==`name`&&e!==`message`&&e!==`stack`){if(e in Object.prototype||e===`toJSON`){this.evaluateImpl(a[e],n,e,i+1);continue}r[e]=this.evaluateImpl(a[e],n,e,i+1)}}return n}break;case`undefined`:if(t.length===1)return;break;case`inf`:return 1/0;case`-inf`:return-1/0;case`nan`:return NaN;case`url`:if(t.length===2&&typeof t[1]==`string`)return new URL(t[1]);break;case`headers`:if(t.length===2&&t[1]instanceof Array)return new Headers(t[1]);break;case`request`:{if(t.length!==3||typeof t[1]!=`string`)break;let e=t[1],a=t[2];if(typeof a!=`object`||!a)break;if(a.body&&(a.body=this.evaluateImpl(a.body,a,`body`,i+1),!(a.body===null||typeof a.body==`string`||a.body instanceof Uint8Array||a.body instanceof ReadableStream)))throw TypeError(`Request body must be of type ReadableStream.`);if(a.signal&&(a.signal=this.evaluateImpl(a.signal,a,`signal`,i+1),!(a.signal instanceof AbortSignal)))throw TypeError(`Request siganl must be of type AbortSignal.`);if(a.headers&&!(a.headers instanceof Array))throw TypeError(`Request headers must be serialized as an array of pairs.`);let o=new Request(e,a);if(a.body instanceof ReadableStream&&o.body===void 0){let e=Yr(o,a.body);return this.promises.push({promise:e,parent:n,property:r}),e}return o}case`response`:{if(t.length!==3)break;let e=this.evaluateImpl(t[1],n,r,i+1);if(!(e===null||typeof e==`string`||e instanceof Uint8Array||e instanceof ReadableStream))throw TypeError(`Response body must be of type ReadableStream.`);let a=t[2];if(typeof a!=`object`||!a)break;if(a.webSocket)throw TypeError(`Can't deserialize a Response containing a webSocket.`);if(a.headers&&!(a.headers instanceof Array))throw TypeError(`Request headers must be serialized as an array of pairs.`);return new Response(e,a)}case`blob`:{if(t.length!==3||typeof t[1]!=`string`)break;let e=t[1],a=this.evaluateImpl(t[2],n,r,i+1);if(!(a instanceof ReadableStream))throw TypeError(`Blob content must be serialized as a ReadableStream.`);let o=Xr(a,e);return this.promises.push({promise:o,parent:n,property:r}),o}case`import`:case`pipeline`:{if(t.length<2||t.length>4||typeof t[1]!=`number`)break;let a=this.importer.getExport(t[1]);if(!a)throw Error(`no such entry on exports table: ${t[1]}`);let o=t[0]==`pipeline`,s=e=>{if(o){let t=new G(e,[]);return this.promises.push({promise:t,parent:n,property:r}),t}return this.hooks.push(e),new G(e,[])};if(t.length==2)return s(o?a.get([]):a.dup());let c=t[2];if(!(c instanceof Array)||!c.every(e=>typeof e==`string`||typeof e==`number`))break;if(t.length==3)return s(a.get(c));let l=t[3];if(!(l instanceof Array))break;return l=new e(this.importer).evaluateWithDepth([l],i),s(a.call(c,l))}case`remap`:{if(t.length!==5||typeof t[1]!=`number`||!(t[2]instanceof Array)||!(t[3]instanceof Array)||!(t[4]instanceof Array))break;let e=this.importer.getExport(t[1]);if(!e)throw Error(`no such entry on exports table: ${t[1]}`);let i=t[2];if(!i.every(e=>typeof e==`string`||typeof e==`number`))break;let a=t[3].map(e=>{if(!(e instanceof Array)||e.length!==2||e[0]!==`import`&&e[0]!==`export`||typeof e[1]!=`number`)throw TypeError(`unknown map capture: ${JSON.stringify(e)}`);if(e[0]===`export`)return this.importer.importStub(e[1]);{let t=this.importer.getExport(e[1]);if(!t)throw Error(`no such entry on exports table: ${e[1]}`);return t.dup()}}),o=t[4],s=new G(e.map(i,a,o),[]);return this.promises.push({promise:s,parent:n,property:r}),s}case`export`:case`promise`:if(typeof t[1]==`number`){if(t[0]==`promise`){let e=new G(this.importer.importPromise(t[1]),[]);return this.promises.push({parent:n,property:r,promise:e}),e}{let e=this.importer.importStub(t[1]);return this.hooks.push(e),new W(e)}}break;case`writable`:if(typeof t[1]==`number`){let e=this.importer.importStub(t[1]),n=V.createWritableStreamFromHook(e);return this.hooks.push(e),n}break;case`readable`:if(typeof t[1]==`number`){let e=this.importer.getPipeReadable(t[1]),n=V.createReadableStreamHook(e);return this.hooks.push(n),e}}throw TypeError(`unknown special value: ${JSON.stringify(t)}`)}if(t instanceof Object){let e=t;for(let t in e)t in Object.prototype||t===`toJSON`?(this.evaluateImpl(e[t],e,t,i+1),delete e[t]):e[t]=this.evaluateImpl(e[t],e,t,i+1);return e}return t}},Qr=16,$r=8,ei=16,ti=64;function ni(e){return 2+e.length*3}function ri(e,t,n=0){if(n>=ti)return $r;switch(typeof e){case`string`:return ni(e);case`number`:return 16;case`bigint`:return 16;case`boolean`:return 8;case`undefined`:return 16;case`object`:{if(e===null)return 8;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return ei+e.byteLength;if(typeof Blob<`u`&&e instanceof Blob)return ei+e.size;if(e instanceof Date)return 16;if(t??=new WeakSet,t.has(e))return $r;if(t.add(e),e instanceof Array){let r=Qr;for(let i of e)r+=$r+ri(i,t,n+1);return r}if(e instanceof Error){let r=Qr+ni(e.name)+ni(e.message)+ni(e.stack??``);for(let i of Object.keys(e))r+=$r+ni(i)+ri(e[i],t,n+1);return r}let r=Qr;for(let i of Object.keys(e))r+=$r+ni(i)+ri(e[i],t,n+1);return r}default:return 16}}var ii=class{session;importId;constructor(e,t,n){this.session=e,this.importId=t,n&&(this.activePull=Promise.withResolvers())}localRefcount=0;remoteRefcount=1;activePull;resolution;onBrokenRegistrations;resolve(e){if(this.localRefcount==0){e.dispose();return}if(this.resolution=e,this.sendRelease(),this.onBrokenRegistrations){for(let t of this.onBrokenRegistrations){let n=this.session.onBrokenCallbacks[t],r=this.session.onBrokenCallbacks.length;e.onBroken(n),this.session.onBrokenCallbacks[r]===n?delete this.session.onBrokenCallbacks[r]:delete this.session.onBrokenCallbacks[t]}this.onBrokenRegistrations=void 0}this.activePull&&=(this.activePull.resolve(),void 0)}async awaitResolution(){return this.activePull||=(this.session.sendPull(this.importId),Promise.withResolvers()),await this.activePull.promise,this.resolution.pull()}dispose(){this.resolution?this.resolution.dispose():(this.abort(Error(`RPC was canceled because the RpcPromise was disposed.`)),this.sendRelease())}abort(e){if(!this.resolution){if(this.resolution=new H(e),this.activePull&&=(this.activePull.reject(e),void 0),this.onBrokenRegistrations)for(let e of this.onBrokenRegistrations)delete this.session.onBrokenCallbacks[e];this.onBrokenRegistrations=void 0}}onBroken(e){if(this.resolution)this.resolution.onBroken(e);else{let t=this.session.onBrokenCallbacks.length;this.session.onBrokenCallbacks.push(e),this.onBrokenRegistrations||=[],this.onBrokenRegistrations.push(t)}}sendRelease(){this.remoteRefcount>0&&(this.session.sendRelease(this.importId,this.remoteRefcount),this.remoteRefcount=0)}},ai=class e extends xr{isPromise;entry;constructor(e,t){super(),this.isPromise=e,++t.localRefcount,this.entry=t}collectPath(e){return this}getEntry(){if(this.entry)return this.entry;throw Error(`This RpcImportHook was already disposed.`)}getEntryTakingOwnership(e){try{return this.getEntry()}catch(t){throw e(),t}}call(e,t){let n=this.getEntryTakingOwnership(()=>t.dispose());return n.resolution?n.resolution.call(e,t):n.session.sendCall(n.importId,e,t)}stream(e,t){let n=this.getEntryTakingOwnership(()=>t.dispose());return n.resolution?n.resolution.stream(e,t):n.session.sendStream(n.importId,e,t)}map(e,t,n){let r=this.getEntryTakingOwnership(()=>{for(let e of t)e.dispose()});return r.resolution?r.resolution.map(e,t,n):r.session.sendMap(r.importId,e,t,n)}get(e){let t=this.getEntry();return t.resolution?t.resolution.get(e):t.session.sendCall(t.importId,e)}dup(){return new e(!1,this.getEntry())}pull(){let e=this.getEntry();if(!this.isPromise)throw Error(`Can't pull this hook because it's not a promise hook.`);return e.resolution?e.resolution.pull():e.awaitResolution()}ignoreUnhandledRejections(){}dispose(){let e=this.entry;this.entry=void 0,e&&--e.localRefcount===0&&e.dispose()}onBroken(e){this.entry&&this.entry.onBroken(e)}},oi=class extends ai{session;constructor(e){super(!1,e),this.session=e.session}dispose(){if(this.session){let e=this.session;this.session=void 0,e.shutdown()}}},si=class{transport;options;exports=[];reverseExports=new Map;imports=[];abortReason;cancelReadLoop;nextExportId=-1;onBatchDone;pullCount=0;onBrokenCallbacks=[];encodingLevel;limits;constructor(e,t,n){this.transport=e,this.options=n;let r=`string`;if(`encodingLevel`in e){let t=e.encodingLevel;if(t!==void 0){if(t!==`string`&&t!==`jsonCompatible`&&t!==`jsonCompatibleWithBytes`&&t!==`structuredClonable`)throw TypeError(`Unknown transport encodingLevel: ${String(t)}`);r=t}}this.encodingLevel=r,this.limits={...Lr,...n.limits},this.exports.push({hook:t,refcount:1}),this.imports.push(new ii(this,0,!1)),this.readLoop().catch(e=>this.abort(e))}getMainImport(){return new oi(this.imports[0])}shutdown(){this.abort(Error(`RPC session was shut down by disposing the main stub`),!1)}exportStub(e){if(this.abortReason)throw this.abortReason;let t=this.reverseExports.get(e);if(t!==void 0)return++this.exports[t].refcount,t;{let t=this.nextExportId--;return this.exports[t]={hook:e,refcount:1},this.reverseExports.set(e,t),this.watchExport(t,e),t}}exportPromise(e){if(this.abortReason)throw this.abortReason;let t=this.nextExportId--;return this.exports[t]={hook:e,refcount:1},this.reverseExports.set(e,t),this.ensureResolvingExport(t),t}unexport(e){for(let t of e)this.releaseExport(t,1)}watchExport(e,t){t.onBroken(n=>{queueMicrotask(()=>{if(this.abortReason===void 0&&this.exports[e]?.hook===t)try{this.send([`reject`,e,Jr.devaluate(n,void 0,this,void 0,this.encodingLevel)])}catch(e){this.abort(e)}})})}releaseExport(e,t){let n=this.exports[e];if(!n)throw Error(`no such export ID: ${e}`);if(n.refcount<t)throw Error(`refcount would go negative: ${n.refcount} < ${t}`);n.refcount-=t,n.refcount===0&&(delete this.exports[e],this.reverseExports.delete(n.hook),n.hook.dispose())}onSendError(e){if(this.options.onSendError)return this.options.onSendError(e)}ensureResolvingExport(e){let t=this.exports[e];if(!t)throw Error(`no such export ID: ${e}`);if(!t.pull){let n=async()=>{let e=t.hook;for(;;){let t=await e.pull();if(t.value instanceof W){let{hook:n,pathIfPromise:r}=Ar(t.value);if(r&&r.length==0&&this.getImport(e)===void 0){e=n;continue}}return t}},r=t.autoRelease;++this.pullCount,t.pull=n().then(t=>{let n=Jr.devaluate(t.value,void 0,this,t,this.encodingLevel);this.send([`resolve`,e,n]),r&&this.releaseExport(e,1)},t=>{this.send([`reject`,e,Jr.devaluate(t,void 0,this,void 0,this.encodingLevel)]),r&&this.releaseExport(e,1)}).catch(t=>{try{this.send([`reject`,e,Jr.devaluate(t,void 0,this,void 0,this.encodingLevel)]),r&&this.releaseExport(e,1)}catch(e){this.abort(e)}}).finally(()=>{--this.pullCount===0&&this.onBatchDone&&this.onBatchDone.resolve()})}}getImport(e){if(e instanceof ai&&e.entry&&e.entry.session===this)return e.entry.importId}importStub(e){if(this.abortReason)throw this.abortReason;let t=this.imports[e];return t||(t=new ii(this,e,!1),this.imports[e]=t),new ai(!1,t)}importPromise(e){if(this.abortReason)throw this.abortReason;if(this.imports[e])return new H(Error(`Bug in RPC system: The peer sent a promise reusing an existing export ID.`));let t=new ii(this,e,!0);return this.imports[e]=t,new ai(!0,t)}getExport(e){return this.exports[e]?.hook}getPipeReadable(e){let t=this.exports[e];if(!t||!t.pipeReadable)throw Error(`Export ${e} is not a pipe or its readable end was already consumed.`);let n=t.pipeReadable;return t.pipeReadable=void 0,n}getLimits(){return this.limits}createPipe(e,t){if(this.abortReason)throw this.abortReason;this.send([`pipe`]);let n=this.imports.length,r=new ii(this,n,!1);this.imports.push(r);let i=new ai(!1,r),a=V.createWritableStreamFromHook(i);return e.pipeTo(a).catch(()=>{}).finally(()=>t.dispose()),n}send(e){if(this.abortReason!==void 0)return 0;if(this.encodingLevel===`string`){let t;try{t=JSON.stringify(e)}catch(e){try{this.abort(e)}catch{}throw e}try{let e=this.transport.send(t);e!==void 0&&typeof e.catch==`function`&&e.catch(e=>this.abort(e,!1))}catch(e){queueMicrotask(()=>this.abort(e,!1))}return t.length}try{let t=this.transport.send(e);if(typeof t==`number`)return t;let n=t;n&&typeof n.then==`function`&&Promise.resolve(n).catch(e=>this.abort(e,!1));return}catch(e){queueMicrotask(()=>this.abort(e,!1));return}}sendCall(e,t,n){if(this.abortReason)throw n?.dispose(),this.abortReason;let r=[`pipeline`,e,t];if(n){let e;try{e=Jr.devaluate(n.value,void 0,this,n,this.encodingLevel)}catch(e){throw n.dispose(),e}r.push(e[0])}this.send([`push`,r]);let i=new ii(this,this.imports.length,!1);return this.imports.push(i),new ai(!0,i)}sendStream(e,t,n){if(this.abortReason)throw n.dispose(),this.abortReason;let r=[`pipeline`,e,t],i;try{i=Jr.devaluate(n.value,void 0,this,n,this.encodingLevel)}catch(e){throw n.dispose(),e}r.push(i[0]);let a=[`stream`,r],o=this.send(a);o===void 0&&(o=ri(a));let s=this.imports.length,c=new ii(this,s,!0);return c.remoteRefcount=0,c.localRefcount=1,this.imports.push(c),{promise:c.awaitResolution().then(e=>{e.dispose(),delete this.imports[s]},e=>{throw delete this.imports[s],e}),size:o}}sendMap(e,t,n,r){if(this.abortReason){for(let e of n)e.dispose();throw this.abortReason}let i=[`remap`,e,t,n.map(e=>{let t=this.getImport(e);return t===void 0?[`export`,this.exportStub(e)]:[`import`,t]}),r];this.send([`push`,i]);let a=new ii(this,this.imports.length,!1);return this.imports.push(a),new ai(!0,a)}sendPull(e){if(this.abortReason)throw this.abortReason;this.send([`pull`,e])}sendRelease(e,t){this.abortReason||(this.send([`release`,e,t]),delete this.imports[e])}abort(e,t=!0){if(this.abortReason===void 0){if(this.cancelReadLoop?.(e),this.cancelReadLoop=void 0,t)try{let t=[`abort`,Jr.devaluate(e,void 0,this,void 0,this.encodingLevel)];if(this.encodingLevel===`string`){let e=this.transport.send(JSON.stringify(t));e!==void 0&&typeof e.catch==`function`&&e.catch(e=>{})}else{let e=this.transport.send(t);e&&typeof e.then==`function`&&Promise.resolve(e).catch(e=>{})}}catch{}if(e===void 0&&(e=`undefined`),this.abortReason=e,this.onBatchDone&&this.onBatchDone.reject(e),this.transport.abort)try{this.transport.abort(e)}catch(e){Promise.resolve(e)}for(let t of Object.values(this.onBrokenCallbacks))try{t(e)}catch(e){Promise.resolve(e)}for(let t in this.imports)this.imports[t].abort(e);for(let e in this.exports)this.exports[e].hook.dispose()}}async readLoop(){for(;!this.abortReason;){let e=Promise.withResolvers();this.cancelReadLoop=e.reject;let t;try{t=await Promise.race([this.transport.receive(),e.promise])}finally{this.cancelReadLoop===e.reject&&(this.cancelReadLoop=void 0)}if(this.encodingLevel===`string`&&t.length>this.limits.maxMessageSize)throw TypeError(`Incoming message exceeds maximum size of ${this.limits.maxMessageSize} UTF-16 code units.`);if(this.abortReason)break;let n=this.encodingLevel===`string`?JSON.parse(t):t;if(n instanceof Array)switch(n[0]){case`push`:if(n.length>1){let e=new q(new Zr(this,this.encodingLevel).evaluate(n[1]));e.ignoreUnhandledRejections(),this.exports.push({hook:e,refcount:1});continue}break;case`stream`:if(n.length>1){let e=new q(new Zr(this,this.encodingLevel).evaluate(n[1]));e.ignoreUnhandledRejections();let t=this.exports.length;this.exports.push({hook:e,refcount:1,autoRelease:!0}),this.ensureResolvingExport(t);continue}break;case`pipe`:{let{readable:e,writable:t}=new TransformStream,n=V.createWritableStreamHook(t),r=this.exports.length;this.exports.push({hook:n,refcount:1,pipeReadable:e}),this.watchExport(r,n);continue}case`pull`:{let e=n[1];if(typeof e==`number`){this.ensureResolvingExport(e);continue}break}case`resolve`:case`reject`:{let e=n[1];if(typeof e==`number`&&n.length>2){let t=this.imports[e];if(t){if(n[0]==`resolve`)t.resolve(new q(new Zr(this,this.encodingLevel).evaluate(n[2])));else{let e=new Zr(this,this.encodingLevel).evaluate(n[2]);e.dispose(),t.resolve(new H(e.value))}}else n[0]==`resolve`&&new Zr(this,this.encodingLevel).evaluate(n[2]).dispose();continue}break}case`release`:{let e=n[1],t=n[2];if(typeof e==`number`&&typeof t==`number`){this.releaseExport(e,t);continue}break}case`abort`:{let e=new Zr(this,this.encodingLevel).evaluate(n[1]);e.dispose(),this.abort(e.value,!1);break}}throw Error(`bad RPC message: ${JSON.stringify(n)}`)}}async drain(){if(this.abortReason)throw this.abortReason;if(this.pullCount>0){let{promise:e,resolve:t,reject:n}=Promise.withResolvers();this.onBatchDone={resolve:t,reject:n},await e}}getStats(){let e={imports:0,exports:0};for(let t in this.imports)++e.imports;for(let t in this.exports)++e.exports;return e}},ci=class{#e;#t;constructor(e,t,n={}){let r;r=t?new q(K.fromAppReturn(t)):new H(Error(`This connection has no main object.`)),this.#e=new si(e,r,n),this.#t=new W(this.#e.getMainImport())}getRemoteMain(){return this.#t}getStats(){return this.#e.getStats()}drain(){return this.#e.drain()}};function li(e,t,n){return new ci(new ui(e),t,n).getRemoteMain()}var ui=class{encodingLevel=`structuredClonable`;constructor(e){this.#e=e,e.start(),e.addEventListener(`message`,e=>{this.#i||(e.data===null?this.#a(Error(`Peer closed MessagePort connection.`)):this.#t?(this.#t(e.data),this.#t=void 0,this.#n=void 0):this.#r.push(e.data))}),e.addEventListener(`messageerror`,e=>{this.#a(Error(`MessagePort message error.`))})}#e;#t;#n;#r=[];#i;send(e){if(this.#i)throw this.#i;this.#e.postMessage(e)}async receive(){if(this.#r.length>0)return this.#r.shift();if(this.#i)throw this.#i;return new Promise((e,t)=>{this.#t=e,this.#n=t})}abort(e){try{this.#e.postMessage(null)}catch{}this.#e.close(),this.#i||=e}#a(e){this.#i||(this.#i=e,this.#n&&=(this.#n(e),this.#t=void 0,void 0))}},di,fi=class{context;captureMap=new Map;instructions=[];constructor(e,t){this.context=di?{parent:di,captures:[],subject:di.capture(e),path:t}:{parent:void 0,captures:[],subject:e,path:t},di=this}unregister(){di=this.context.parent}makeInput(){return new mi(this,0)}makeOutput(e){let t;try{t=Jr.devaluate(e.value,void 0,this,e)}finally{e.dispose()}return this.instructions.push(t),this.context.parent?(this.context.parent.instructions.push([`remap`,this.context.subject,this.context.path,this.context.captures.map(e=>[`import`,e]),this.instructions]),new mi(this.context.parent,this.context.parent.instructions.length)):this.context.subject.map(this.context.path,this.context.captures,this.instructions)}pushCall(e,t,n){let r=Jr.devaluate(n.value,void 0,this,n);r=r[0];let i=this.capture(e.dup());return this.instructions.push([`pipeline`,i,t,r]),new mi(this,this.instructions.length)}pushGet(e,t){let n=this.capture(e.dup());return this.instructions.push([`pipeline`,n,t]),new mi(this,this.instructions.length)}capture(e){if(e instanceof mi&&e.mapper===this)return e.idx;let t=this.captureMap.get(e);if(t===void 0){if(this.context.parent){let t=this.context.parent.capture(e);this.context.captures.push(t)}else this.context.captures.push(e);t=-this.context.captures.length,this.captureMap.set(e,t)}return t}exportStub(e){throw Error(`Can't construct an RpcTarget or RPC callback inside a mapper function. Try creating a new RpcStub outside the callback first, then using it inside the callback.`)}exportPromise(e){return this.exportStub(e)}getImport(e){return this.capture(e)}unexport(e){}createPipe(e){throw Error(`Cannot send ReadableStream inside a mapper function.`)}onSendError(e){}};yr.sendMap=(e,t,n)=>{let r=new fi(e,t),i;try{i=K.fromAppReturn(wr(r.pushCall.bind(r),()=>n(new G(r.makeInput(),[]))))}finally{r.unregister()}if(i instanceof Promise)throw i.catch(e=>{}),Error(`RPC map() callbacks cannot be async.`);return new G(r.makeOutput(i),[])};function pi(){throw Error(`Attempted to use an abstract placeholder from a mapper function. Please make sure your map function has no side effects.`)}var mi=class extends xr{mapper;idx;constructor(e,t){super(),this.mapper=e,this.idx=t}dup(){return this}dispose(){}get(e){if(e.length==0)return this;if(di)return di.pushGet(this,e);pi()}call(e,t){t.dispose(),pi()}map(e,t,n){for(let e of t)e.dispose();pi()}pull(){pi()}ignoreUnhandledRejections(){}onBroken(e){pi()}},hi=class{captures;variables;constructor(e,t){this.captures=e,this.variables=[t]}dispose(){for(let e of this.variables)e.dispose()}apply(e){try{if(e.length<1)throw Error(`Invalid empty mapper function.`);for(let t of e.slice(0,-1)){let e=new Zr(this).evaluateCopy(t);if(e.value instanceof W){let t=Or(e.value);if(t){this.variables.push(t);continue}}this.variables.push(new q(e))}return new Zr(this).evaluateCopy(e[e.length-1])}finally{for(let e of this.variables)e.dispose()}}importStub(e){throw Error(`A mapper function cannot refer to exports.`)}importPromise(e){return this.importStub(e)}getExport(e){return e<0?this.captures[-e-1]:this.variables[e]}getPipeReadable(e){throw Error(`A mapper function cannot use pipe readables.`)}getLimits(){return Lr}};function gi(e,t,n,r,i){let a=new hi(r,new q(K.deepCopyFrom(e,t,n)));try{return a.apply(i)}finally{a.dispose()}}yr.applyMap=(e,t,n,r,i)=>{try{let a;if(e instanceof G)throw Error(`applyMap() can't be called on RpcPromise`);if(e instanceof Array){let t=[];try{for(let a of e)t.push(gi(a,e,n,r,i))}catch(e){for(let e of t)e.dispose();throw e}a=K.fromArray(t)}else a=e==null?K.fromAppReturn(e):gi(e,t,n,r,i);return new q(a)}finally{for(let e of r)e.dispose()}};var _i=class e extends xr{state;static create(t){let n=t.getWriter();return new e({refcount:1,writer:n,closed:!1})}constructor(e,t){super(),this.state=e,t&&++e.refcount}getState(){if(this.state)return this.state;throw Error(`Attempted to use a WritableStreamStubHook after it was disposed.`)}call(e,t){try{let n=this.getState();if(e.length!==1||typeof e[0]!=`string`)throw Error(`WritableStream stub only supports direct method calls`);let r=e[0];if(r!==`write`&&r!==`close`&&r!==`abort`)throw Error(`Unknown WritableStream method: ${r}`);return(r===`close`||r===`abort`)&&(n.closed=!0),new Ir((r===`write`?t.deliverStreamWrite(n.writer):t.deliverCall(n.writer[r],n.writer)).then(e=>new q(e)))}catch(e){return t.dispose(),new H(e)}}map(e,t,n){for(let e of t)e.dispose();return new H(Error(`Cannot use map() on a WritableStream`))}get(e){return new H(Error(`Cannot access properties on a WritableStream stub`))}dup(){let t=this.getState();return new e(t,this)}pull(){return Promise.reject(Error(`Cannot pull a WritableStream stub`))}ignoreUnhandledRejections(){}dispose(){let e=this.state;this.state=void 0,e&&--e.refcount===0&&(e.closed||e.writer.abort(Error(`WritableStream RPC stub was disposed without calling close()`)).catch(()=>{}),e.writer.releaseLock())}onBroken(e){this.getState().writer.closed.then(void 0,e)}},vi=262144,yi=1073741824,bi=65536,xi=2,Si=1.25,Ci=.9,wi=3,Ti=class{now;window=vi;bytesInFlight=0;inStartupPhase=!0;delivered=0;deliveredTime=0;firstAckTime=0;firstAckDelivered=0;minRtt=1/0;roundsWithoutIncrease=0;lastRoundWindow=0;roundStartTime=0;constructor(e){this.now=e}onSend(e){this.bytesInFlight+=e;let t={sentTime:this.now(),size:e,deliveredAtSend:this.delivered,deliveredTimeAtSend:this.deliveredTime,windowAtSend:this.window,windowFullAtSend:this.bytesInFlight>=this.window};return{token:t,shouldBlock:t.windowFullAtSend}}onError(e){this.bytesInFlight-=e.size}onAck(e){let t=this.now();this.delivered+=e.size,this.deliveredTime=t,this.bytesInFlight-=e.size;let n=t-e.sentTime;if(this.minRtt=Math.min(this.minRtt,n),this.firstAckTime===0)this.firstAckTime=t,this.firstAckDelivered=this.delivered;else{let n,r;e.deliveredTimeAtSend===0?(n=this.firstAckTime,r=this.firstAckDelivered):(n=e.deliveredTimeAtSend,r=e.deliveredAtSend);let i=t-n,a=(this.delivered-r)/i,o=this.inStartupPhase?xi:Si,s=a*this.minRtt*o;s=Math.min(s,e.windowAtSend*o),s=e.windowFullAtSend?Math.max(s,e.windowAtSend*Ci):Math.max(s,this.window),this.window=Math.max(Math.min(s,yi),bi),this.inStartupPhase&&e.sentTime>=this.roundStartTime&&(this.window>this.lastRoundWindow*Si?this.roundsWithoutIncrease=0:++this.roundsWithoutIncrease>=wi&&(this.inStartupPhase=!1),this.roundStartTime=t,this.lastRoundWindow=this.window)}return this.bytesInFlight<this.window}};function Ei(e){let t,n=!1,r=new Ti(()=>performance.now()),i,a,o=()=>{n||(n=!0,e.dispose())};return new WritableStream({start(n){e.onBroken(e=>{t===void 0&&(t=e,n.error(e),o()),a&&=(a(e),i=void 0,void 0)})},write(n,s){if(t!==void 0)throw t;let c=K.fromAppParams([n]),{promise:l,size:u}=e.stream([`write`],c);if(u===void 0)return l.catch(e=>{throw t===void 0&&(t=e),e});{let{token:e,shouldBlock:n}=r.onSend(u);if(l.then(()=>{r.onAck(e)&&i&&(i(),i=void 0,a=void 0)},n=>{r.onError(e),t===void 0&&(t=n,s.error(n),o()),a&&=(a(n),i=void 0,void 0)}),n)return new Promise((e,t)=>{i=e,a=t})}},async close(){if(t!==void 0)throw o(),t;let{promise:n}=e.stream([`close`],K.fromAppParams([]));try{await n}catch(e){throw t??e}finally{o()}},abort(n){if(t!==void 0)return;t=n??Error(`WritableStream was aborted`),a&&=(a(t),i=void 0,void 0);let{promise:r}=e.stream([`abort`],K.fromAppParams([n]));r.then(()=>o(),()=>o())}})}var Di=class e extends xr{state;static create(t){return new e({refcount:1,stream:t,canceled:!1})}constructor(e,t){super(),this.state=e,t&&++e.refcount}call(e,t){return t.dispose(),new H(Error(`Cannot call methods on a ReadableStream stub`))}map(e,t,n){for(let e of t)e.dispose();return new H(Error(`Cannot use map() on a ReadableStream`))}get(e){return new H(Error(`Cannot access properties on a ReadableStream stub`))}dup(){let t=this.state;if(!t)throw Error(`Attempted to dup a ReadableStreamStubHook after it was disposed.`);return new e(t,this)}pull(){return Promise.reject(Error(`Cannot pull a ReadableStream stub`))}ignoreUnhandledRejections(){}dispose(){let e=this.state;this.state=void 0,e&&--e.refcount===0&&(e.canceled||(e.canceled=!0,e.stream.locked||e.stream.cancel(Error(`ReadableStream RPC stub was disposed without being consumed`)).catch(()=>{})))}onBroken(e){}};V.createWritableStreamHook=_i.create,V.createWritableStreamFromHook=Ei,V.createReadableStreamHook=Di.create;var Oi=W,ki=mr,Ai=li;function ji(e){return e<32||e>=127&&e<=159||e===1564||e>=8203&&e<=8207||e===8232||e===8233||e>=8234&&e<=8238||e>=8294&&e<=8297||e===65279}function Mi(e,t){let n=e.find(e=>e.id===t.itemId);if(n===void 0||n.kind===`text`)return!1;if(n.kind===`menu`){let e=n.options.find(e=>e.id===t.optionId);return e!==void 0&&e.disabled!==!0}return t.optionId===void 0?n.kind!==`button`||n.disabled!==!0:!1}Object.freeze({publish:()=>Promise.resolve(),onBack:()=>()=>void 0,onActivate:()=>()=>void 0});function Ni(e,t){if(t.kind===`action`){let n=[...e.primary??[],...e.menu??[]].find(e=>e.id===t.actionId);return n!==void 0&&n.disabled!==!0}let n=e.crumbs?.find(e=>e.id===t.crumbId);return n===void 0?!1:t.siblingId===void 0||n.siblings?.some(e=>e.id===t.siblingId)===!0}var Pi=`fungi.app.ready`,Fi=`fungi.app.connect`,J=e=>m.pipe(T(Ne(1)),T(A(e))),Ii=e=>h(J(e)),Li=y.pipe(T(x()),T(Me(Number.isSafeInteger,{message:`Expected a safe integer`}))),Ri=Li.pipe(T(ve(0))),zi=Li.pipe(T(ye(0))),Bi=t({appId:J(160),releaseId:J(160),surfaceId:J(160)}),Vi=t({editing:v,surface:D([J(160),u])}),Hi=D([t({kind:o(`compose`),requestId:J(160),text:J(2e3)}),t({kind:o(`navigate`),requestId:J(160),params:s(t({key:J(64),value:J(4096)})).pipe(T(A(16)))})]),Ui=t({computerId:D([J(256),u]),teamHasComputers:h(b(v)),computerAccessGranted:h(v),focus:Vi,openRequest:D([u,Hi]),visibility:p([`visible`,`hidden`])}),Wi=p([`connecting`,`connected`,`suspended`,`disconnected`,`disposing`,`disposed`]),Gi=t({altKey:v,ctrlKey:v,id:J(160),key:J(64),metaKey:v,shiftKey:v}),Ki=t({action:h(w),availability:h(w),category:J(160),description:Ii(512),id:J(160),projections:h(w),title:J(160)}),qi=t({arguments:h(w),commandId:J(321),origin:p([`agent`,`browser`,`keyboard`,`menu`,`palette`,`programmatic`,`slash`,`terminal`]),requestId:J(160)}),Ji=D([t({result:h(w),status:o(`handled`)}),t({error:w,status:o(`failed`)})]),Yi=e=>J(e).pipe(T(Me(e=>{for(let t=0;t<e.length;t+=1)if(ji(e.charCodeAt(t)))return!1;return!0},{message:`Expected one line of plain text`}))),Xi={id:J(64),text:Yi(80),end:i(v)},Zi=i(y.pipe(T(x()),T(Ce({minimum:0,maximum:9999})))),Qi=s(D([t({...Xi,kind:o(`text`),tone:i(p([`neutral`,`success`,`warning`,`error`]))}),t({...Xi,kind:o(`button`),icon:i(p([`folder`,`ports`,`processes`,`access`])),count:Zi,tone:i(p([`neutral`,`success`,`warning`,`error`])),busy:i(v),title:i(Yi(1024)),disabled:i(v),opens:i(o(`dialog`)),expanded:i(v)}),t({...Xi,kind:o(`toggle`),pressed:v}),t({...Xi,kind:o(`menu`),count:Zi,title:i(Yi(1024)),options:s(t({id:J(64),text:Yi(80),checked:i(v),disabled:i(v)})).pipe(T(A(16)),T(Me(e=>new Set(e.map(e=>e.id)).size===e.length,{message:`Expected unique status option ids`})))})])).pipe(T(A(6)),T(Me(e=>new Set(e.map(e=>e.id)).size===e.length,{message:`Expected unique status item ids`}))),$i=t({computerId:J(256),path:J(1024)}),ea=J(80).pipe(T(Me(e=>e.trim()===e,{message:`Expected a trimmed title`}))),ta=J(64),na=J(80),ra=e=>new Set(e.map(e=>e.id)).size===e.length,ia=t({id:ta,label:na,siblings:h(s(t({id:ta,label:na})).pipe(T(A(16)),T(Me(ra,{message:`Expected unique crumb sibling ids`}))))}),aa=t({id:ta,label:na,icon:h(o(`play`)),variant:h(p([`primary`,`outline`,`ghost`])),tone:h(o(`destructive`)),disabled:h(v)}),oa=e=>s(aa).pipe(T(A(e)),T(Me(ra,{message:`Expected unique header command ids`}))),sa=t({id:ta,label:na,presentation:h(o(`bead`)),tone:h(p([`neutral`,`info`,`warning`,`success`,`error`]))}),ca={status:h(s(sa).pipe(T(A(4)),T(Me(ra,{message:`Expected unique header status ids`})))),crumbs:h(s(ia).pipe(T(A(8)),T(Me(ra,{message:`Expected unique crumb ids`})))),primary:h(oa(3)),menu:h(oa(12))},la=t({contractVersion:o(1),canGoBack:v,title:h(ea),...ca}),ua=t({canGoBack:v,title:h(m),...ca}),da=D([t({kind:o(`crumb`),crumbId:ta,siblingId:h(ta)}),t({kind:o(`action`),actionId:ta})]),fa=b(t({agentId:J(256),sessionId:J(256)})),pa=t({agents:h(s(p([`agent.list`,`agent.manage`,`agent.read`,`agent.send`])).pipe(T(A(4)))),computers:h(s(p([`computer.list`,`computer.readFile`,`computer.writeFile`,`computer.execute`])).pipe(T(A(4))))}),ma=p([`granted`,`declined`,`customize`]),ha=t({message:J(512),tone:h(p([`info`,`success`,`warning`,`error`]))}),ga=p(ae);t({code:ga.pick([`DELIVERY_PENDING`])});var _a=t({code:ga,message:J(512),retryable:v,need:i(f)}),va=t({protocolVersion:o(2),type:o(Pi)}),ya=t({epoch:J(160),protocolVersion:o(2),type:o(Fi)}),ba=t({epoch:J(160),protocolVersion:o(2)}),xa={[Symbol.dispose]:h(w)},Sa=D([t({...xa,ok:o(!0),value:w}),t({...xa,error:_a,ok:o(!1)})]);function Y(e,t,n=`PROTOCOL`){return Te(xe(e,{onExcessProperty:`error`}),Fe({onFailure:e=>{throw new _(`The peer sent malformed protocol data`,{cause:e,code:n,retryable:!1})},onSuccess:t}))}function X(e){return Object.freeze(e)}function Ca(e,t){let n=e.arguments===void 0?void 0:qt(e.arguments),r={origin:e.origin,signal:t};return n!==void 0&&Object.assign(r,{arguments:n}),X(r)}var wa=Y(Ki,e=>{let t={category:e.category,id:e.id,title:e.title};return e.action!==void 0&&Object.assign(t,{action:e.action}),e.availability!==void 0&&Object.assign(t,{availability:e.availability}),e.description!==void 0&&Object.assign(t,{description:e.description}),e.projections!==void 0&&Object.assign(t,{projections:e.projections}),X(mo(()=>on(t)))},`INVALID_ARGUMENT`),Ta=Y(J(321),e=>e),Ea=Y(qi,e=>{let t=e.arguments===void 0?void 0:qt(e.arguments),n={commandId:e.commandId,origin:e.origin,requestId:e.requestId};return t!==void 0&&Object.assign(n,{arguments:t}),X(n)}),Da=Y(D([Ee,w]),e=>e===void 0?void 0:qt(e)),Oa=Y(ya,e=>X(e));Y(ba,e=>X(e));var ka=Y(Ui,e=>{let t={computerId:e.computerId,focus:X({...e.focus}),openRequest:e.openRequest===null?null:X({...e.openRequest}),visibility:e.visibility};return e.teamHasComputers!==void 0&&(t.teamHasComputers=e.teamHasComputers),e.computerAccessGranted!==void 0&&(t.computerAccessGranted=e.computerAccessGranted),X(t)}),Aa=Y(_a,e=>X({...e})),ja=Y(Vi,e=>X({...e}),`INVALID_ARGUMENT`),Ma=Y(Bi,e=>X({...e})),Na=Y(Wi,e=>e),Pa=Y(Qi,e=>X(e.map(e=>e.kind===`menu`?X({...e,options:X(e.options.map(e=>X(e)))}):X(e))),`INVALID_ARGUMENT`),Fa=Y(t({itemId:J(64),optionId:i(J(64)),anchor:i(t({start:y.pipe(T(Ce({minimum:0,maximum:1e5}))),width:y.pipe(T(Ce({minimum:0,maximum:1e5})))}))}),e=>X(e.anchor===void 0?{...e}:{...e,anchor:X({...e.anchor})}),`INVALID_ARGUMENT`),Ia=Y($i,e=>X({...e}),`INVALID_ARGUMENT`);function La(e){let t={id:e.id,label:e.label};return e.presentation!==void 0&&(t={...t,presentation:e.presentation}),e.tone!==void 0&&(t={...t,tone:e.tone}),X(t)}function Ra(e){let t={id:e.id,label:e.label};return e.siblings===void 0?X(t):X({...t,siblings:X(e.siblings.map(e=>X({...e})))})}function za(e){let t={id:e.id,label:e.label};return e.icon!==void 0&&(t={...t,icon:e.icon}),e.variant!==void 0&&(t={...t,variant:e.variant}),e.tone!==void 0&&(t={...t,tone:e.tone}),e.disabled!==void 0&&(t={...t,disabled:e.disabled}),X(t)}function Ba(e){let t={canGoBack:e.canGoBack};return e.title!==void 0&&(t={...t,title:e.title}),e.crumbs!==void 0&&(t={...t,crumbs:X(e.crumbs.map(Ra))}),e.primary!==void 0&&(t={...t,primary:X(e.primary.map(za))}),e.menu!==void 0&&(t={...t,menu:X(e.menu.map(za))}),e.status!==void 0&&(t={...t,status:X(e.status.map(La))}),X(t)}var Va=Y(la,Ba,`INVALID_ARGUMENT`),Ha=Y(ua,e=>{let t=e.title?.trim();return Ua({...Ba({...e,title:t===void 0||t.length===0?void 0:t}),contractVersion:1})},`INVALID_ARGUMENT`),Ua=Y(la,e=>X({...Ba(e),contractVersion:1}),`INVALID_ARGUMENT`),Wa=Y(da,e=>e.kind===`action`?X({...e}):X(e.siblingId===void 0?{kind:e.kind,crumbId:e.crumbId}:e),`INVALID_ARGUMENT`),Ga=Y(fa,e=>e===null?null:X({...e}),`INVALID_ARGUMENT`),Ka=Y(pa,e=>X({agents:X([...new Set(e.agents??[])]),computers:X([...new Set(e.computers??[])])}),`INVALID_ARGUMENT`);Y(va,e=>X(e));var qa=Y(J(512),e=>e),Ja=Y(ha,e=>X({...e}),`INVALID_ARGUMENT`);Y(t({id:J(160),repeat:v}),e=>X(e));var Ya=Y(s(Gi).pipe(T(A(64))),e=>{if(new Set(e.map(e=>e.id)).size!==e.length)throw new _(`Reserved chords are invalid`,{code:`PROTOCOL`,retryable:!1});return X(e.map(e=>X({...e})))});function Xa(e){return Y(t({value:w,version:Ri}),t=>X({value:e(t.value),version:t.version}))}var Za=Xa(ka),Qa=Y(t({capabilities:s(w).pipe(T(A(128))),context:w}),e=>X({capabilities:X(e.capabilities.map(e=>io(e))),context:Za(e.context)})),$a=Xa(Na),eo=Xa(Ya),to=Xa(qa),no=Te($a,e=>{if(e.value!==`connected`&&e.value!==`suspended`)throw new _(`The host lifecycle is invalid`,{code:`PROTOCOL`,retryable:!1});return X({value:e.value,version:e.version})});function ro(e){return Y(t({handle:w,id:J(160),version:zi}),t=>{if(!(t.handle instanceof Oi)&&!(e&&t.handle instanceof ki))throw new _(`A capability handle is invalid`,{code:`PROTOCOL`,retryable:!1});return X({handle:t.handle,id:t.id,version:t.version})})}var io=ro(!1),ao=ro(!0);function oo(e){let n=e?ao:io;return Y(t({capabilities:s(w).pipe(T(A(128))),context:w,identity:w,lifecycle:w,reservedChords:w,theme:w}),e=>X({capabilities:X(e.capabilities.map(e=>n(e))),context:Za(e.context),identity:Ma(e.identity),lifecycle:no(e.lifecycle),reservedChords:eo(e.reservedChords),theme:to(e.theme)}))}var so=oo(!1);oo(!0);function co(e){return Y(Sa,t=>t.ok?X({ok:!0,value:e(t.value)}):X({ok:!1,error:Aa(t.error)}))}var lo=co(so),uo=co(Y(t({commandId:J(321)}),e=>X(e)));co(Y(Ji,e=>{if(e.status===`failed`)return X({status:`failed`,error:mo(()=>Yt(e.error))});let t=e.result===void 0?void 0:qt(e.result);return X(t===void 0?{status:`handled`}:{status:`handled`,result:t})}));var fo=co(Y(Ee,()=>void 0)),po=co(Y(ma,e=>e));co(Y(v,e=>e)),co(Y(v,e=>e));function mo(e){try{return e()}catch(e){throw new _(`The command metadata is invalid`,{cause:e,code:`INVALID_ARGUMENT`,retryable:!1})}}var ho=D([t({kind:o(`saveFile`),name:J(255).pipe(T(ue(/^[^\p{Cc}/\\]+$/u))),mime:J(255),bytes:je}),t({kind:o(`copyText`),text:m})]);function go(e){let t=xe(ho,{onExcessProperty:`error`})(e);if(te(t))return{kind:`refused`,reason:`invalid-request`};let n=t.success;return n.kind===`saveFile`?n.name===`.`||n.name===`..`?{kind:`refused`,reason:`invalid-request`}:n.bytes.byteLength>33554432?{kind:`refused`,reason:`too-large`}:{...n,bytes:new Uint8Array(n.bytes)}:n.text.length>1048576||new TextEncoder().encode(n.text).byteLength>1048576?{kind:`refused`,reason:`too-large`}:n}var _o=co(Y(D([t({kind:o(`saved`)}),t({kind:o(`copied`)}),t({kind:o(`refused`),reason:p([`no-user-gesture`,`too-large`,`invalid-request`,`unavailable`,`denied`,`busy`])})]),e=>X(e)));function vo(e){let t=e,n=new Set;return{get:()=>t,subscribe(e){n.add(e);let t=!0;return()=>{t&&(t=!1,n.delete(e))}},update(e){if(!Object.is(t,e)){t=e;for(let e of Array.from(n))try{e(t)}catch(e){console.warn(`App store subscriber failed`,e)}}}}}function yo(e){let t=new Map,n=vo(0),r=!1,i=e=>{let t=new Map;try{for(let n of e){let e=io(n),r=Co(e.id,e.version);if(t.has(r))throw xo(e.handle),new _(`Duplicate capability grant`,{code:`PROTOCOL`,retryable:!1});t.set(r,e.handle)}}catch(e){for(let e of t.values())xo(e);throw e}return t};for(let[n,r]of i(e))t.set(n,r);let a=e=>{for(let t of e)xo(t)},o=e=>{if(r)throw new _(`The app connection is disposed`,{code:`DISCONNECTED`,retryable:!0});let n=Co(e.id,e.version);return t.get(n)};return{directory:Object.freeze({get version(){return n.get()},subscribe:e=>n.subscribe(e),has(e){return!!o(e)},require(e){let t=o(e);if(!t)throw new _(`The capability is not granted`,{code:`CAPABILITY_DENIED`,retryable:!1});try{return e.schema.parse(t)}catch(e){throw new _(`The capability interface is malformed`,{cause:e,code:`PROTOCOL`,retryable:!1})}}}),replace(e){if(r)throw new _(`The app connection is disposed`,{code:`DISCONNECTED`,retryable:!0});let o=i(e),s=[...t.values()];t.clear();for(let[e,n]of o)t.set(e,n);a(s.filter(e=>![...o.values()].includes(e))),n.update(n.get()+1)},disconnect(){r||(r=!0,a(t.values()),t.clear(),n.update(n.get()+1))}}}var bo=M().transform(e=>{let n=pe(Object).safeParse(e);if(!n.success)return;let r=Object.create(n.data),i=O(t({[Symbol.dispose]:h(_e(Function))}))(r);return{owner:n.data,dispose:i[Symbol.dispose]}});function xo(e){try{let t=bo.parse(e);if(t===void 0||So.has(t.owner))return;So.add(t.owner),t.dispose?.call(t.owner)}catch(e){console.warn(`RPC value disposal failed`,e)}}var So=new WeakSet;function Co(e,t){return`${e}@${String(t)}`}function wo(e){let t=(0,N.useCallback)(t=>e?.subscribe(t)??(()=>void 0),[e]),n=(0,N.useCallback)(()=>e?.get(),[e]);return(0,N.useSyncExternalStore)(t,n,n)}function To(e){return wo(e?.context)??null}function Eo(e){return To(e)?.computerId??null}function Do(e,t,n,r){let i=(0,N.useRef)(t);i.current=t;let a=(0,N.useRef)(n);a.current=n;let o=(0,N.useRef)(r);o.current=r;let s=JSON.stringify(t),c=n!==void 0;(0,N.useEffect)(()=>{e&&e.ui.reportStatus(i.current).catch(e=>{o.current?o.current(e):console.error(`Window status report failed`,e)})},[e,s]),(0,N.useEffect)(()=>{if(!(!e||!c))return e.ui.onStatusAction(e=>a.current?.(e)??!1)},[e,c]),(0,N.useEffect)(()=>()=>{e?.ui.reportStatus([]).catch(e=>{console.error(`Window status report failed`,e)})},[e])}function Oo(e,{sourceId:t,namespace:n},r){let i=(0,N.useMemo)(()=>_n(),[]),a=(0,N.useMemo)(r,[r]);return(0,N.useEffect)(()=>{let e=i.contribute({sourceId:t,namespace:n,commands:a});return()=>{e.dispose()}},[i,t,n,a]),(0,N.useEffect)(()=>e?ur(e.commands,a):void 0,[e,a]),i}function ko(e,{canGoBack:t,title:n,crumbs:r,primary:i,menu:a,status:o,onBack:s,onCrumb:c,onAction:l}){let u=(0,N.useRef)(s),d=(0,N.useRef)(c),f=(0,N.useRef)(l);(0,N.useEffect)(()=>{u.current=s,d.current=c,f.current=l},[s,c,l]),(0,N.useEffect)(()=>{if(!e)return;let t=e.onBack(()=>u.current()),n=e.onActivate(e=>{if(e.kind===`action`){let t=f.current;return t?.(e.actionId),t!==void 0}let t=d.current;return e.siblingId===void 0?t?.(e.crumbId):t?.(e.crumbId,e.siblingId),t!==void 0});return()=>{t(),n(),Ao(e,{canGoBack:!1})}},[e]);let p=JSON.stringify([r,i,a,o]),ee=(0,N.useRef)({crumbs:r,primary:i,menu:a,status:o});(0,N.useEffect)(()=>{ee.current={crumbs:r,primary:i,menu:a,status:o}},[r,i,a,o]),(0,N.useEffect)(()=>{if(!e)return;let r={canGoBack:t};n!==void 0&&(r={...r,title:n});let i=ee.current;i.crumbs!==void 0&&(r={...r,crumbs:i.crumbs}),i.primary!==void 0&&(r={...r,primary:i.primary}),i.menu!==void 0&&(r={...r,menu:i.menu}),i.status!==void 0&&(r={...r,status:i.status}),Ao(e,r)},[e,t,n,p])}function Ao(e,t){e.publish(t).catch(e=>{e instanceof _&&e.code===`DISCONNECTED`||console.warn(`App navigation report failed`,e)})}var jo=class{id;version;#e;constructor(e,t,n){this.id=e,this.version=t,this.#e=n,Object.freeze(this)}get schema(){return this.#e}};function Mo(e,t,n){return new jo(e,t,n)}function Z(e){let t=j(e),n=pe(Object),r=j(Object.fromEntries(Object.keys(e).map(e=>[e,M().optional()])));return M().transform(e=>{let i=n.parse(e),a=Object.create(i),o=r.parse(a),s=Object.fromEntries(Object.entries(o).map(([e,t])=>[e,Ae().parse(t).bind(i)]));return{...t.parse(s),[Symbol.dispose](){xo(e)}}})}function Q(e){return M().transform(t=>{try{return e.parse(t)}catch(e){throw e instanceof _?e:new _(`The capability returned malformed data`,{cause:e,code:`PROTOCOL`,retryable:!1})}finally{xo(t)}})}function $(e){return Ae({output:Pe(M().transform(t=>{try{return e.parse(t)}catch(e){throw xo(t),e instanceof _?e:new _(`The capability returned a malformed result`,{cause:e,code:`PROTOCOL`,retryable:!1})}}))})}var No=$(Q(Se()));Z({fetch:$(pe(Response)),close:No});function Po(e){return e instanceof _?e:new _(`App operation failed`,{cause:e,code:`HOST_FAILURE`,retryable:!1})}var Fo=new WeakMap,Io={of(e,...t){return[e?.identity.surfaceId??null,e?.context.get().computerId??null,...t]}};function Lo(e){let t={};return e&&Fo.set(t,e),t}function Ro(){let e=new Vt({defaultOptions:{queries:{retry:!1,staleTime:3e4,refetchOnWindowFocus:!1},mutations:{retry:!1}}}),t=new Map;return e.getQueryCache().subscribe(n=>{let r=n.query;if(n.type===`removed`){t.get(r.queryHash)?.release(),t.delete(r.queryHash);return}let i=r.meta&&Fo.get(r.meta),a=t.get(r.queryHash);if(a?.app===i||(a?.release(),t.delete(r.queryHash),!i))return;let o=()=>{queueMicrotask(()=>{e.getQueryCache().get(r.queryHash)===r&&t.get(r.queryHash)?.app===i&&e.resetQueries({predicate:e=>e===r})})},s=i.capabilities.subscribe(o);t.set(r.queryHash,{app:i,release:s}),a&&o()}),e}function zo(e,t,n,r){let i=e?.context.get().computerId;return Ht({queryKey:n,meta:Lo(e),enabled:e!==null,retry:!1,queryFn:async({signal:n})=>{try{if(!e)throw new _(`No App connection`,{code:`DISCONNECTED`,retryable:!0});if(e.context.get().computerId!==i)throw new _(`The selected Computer changed`,{code:`SELECTION_CHANGED`,retryable:!1});return await r(e.capabilities.require(t),n)}catch(e){throw Po(e)}}})}var Bo=fe(me(t({error:o(`too_large`)})));async function Vo(e,t){let n,r=()=>n??=e.close(),i=()=>{r().catch(e=>{dr(`files.read.abort-close`,e)})};t.signal?.addEventListener(`abort`,i,{once:!0});try{t.signal?.throwIfAborted();let n=await e.response();try{let e=O(_e(Response))(n);if(e.status===413){let t=Bo(await e.text());throw new _(`App file exceeds the read bound`,{code:t._tag===`Some`?`FILE_TOO_LARGE`:`PROTOCOL`,retryable:!1})}if(!e.ok)throw Error(`App file unavailable (${String(e.status)})`);let r=await e.blob();return t.signal?.throwIfAborted(),new File([r],t.name,{type:r.type,lastModified:0})}finally{xo(n)}}finally{t.signal?.removeEventListener(`abort`,i);try{await r()}finally{e[Symbol.dispose]()}}}async function Ho(e,t,n){let r,i=()=>r??=e.close(),a=()=>{i().catch(e=>{dr(`files.write.abort-close`,e)})};n.signal?.addEventListener(`abort`,a,{once:!0});try{n.signal?.throwIfAborted(),await e.write(t.stream())}finally{n.signal?.removeEventListener(`abort`,a);try{await i()}catch(e){dr(`files.write.remote-close`,e)}try{e[Symbol.dispose]()}catch(e){dr(`files.write.local-dispose`,e)}}}var Uo=t({path:m,entries:s(t({name:m,type:p([`file`,`directory`,`symlink`]),size:y,modifiedAt:y})),nextOffset:b(y)}),Wo=Mo(`computer.list`,1,C(()=>Z({list:$(Q(M().transform(e=>O(Uo)(e))))}))),Go=D([t({state:p([`running`,`sleeping`,`starting`,`start_failed`])}),t({state:o(`queued`),position:y.pipe(T(x()),T(ye(0)))})]),Ko=t({enabled:v,effective:v,blockedBy:b(p([`team`,`global`]))}),qo=t({computerId:E,name:E,runtime:Go,backends:s(t({id:E,kind:p([`platform-container`,`on-box-vm`,`local`]),status:p([`ready`,`queued`,`online`,`offline`]),queuePosition:b(y.pipe(T(x()),T(ye(0)))),hostId:b(m),hostLabel:b(m),folderLabel:b(m),detachable:v})),internet:Ko});Mo(`computer.instrument.read`,1,C(()=>Z({read:$(Q(M().transform(e=>O(qo)(e))))}))),Mo(`computer.instrument.control`,1,C(()=>Z({start:$(Q(M().transform(e=>O(Go)(e)))),setInternetAccess:$(Q(M().transform(e=>O(Ko)(e)))),detachLocal:$(Q(M().transform(e=>O(t({detached:v}))(e))))})));var Jo=t({ports:s(t({port:y.pipe(T(x()),T(Ce({minimum:1,maximum:65535}))),previewUrl:E,openMode:p([`inline`,`external-only`]),expiresAt:y.pipe(T(x()),T(ye(0)))})).pipe(T(A(64)))}),Yo=D([Jo,t({error:o(`port_previews_not_configured`)})]),Xo=t({port:y.annotate({message:`Use a port from 1 to 65535.`}).check(x({message:`Use a port from 1 to 65535.`}),Ce({minimum:1,maximum:65535},{message:`Use a port from 1 to 65535.`})),exposed:v}),Zo=t({port:y.pipe(T(x()),T(Ce({minimum:1,maximum:65535}))),removed:v});Mo(`computer.ports`,2,C(()=>Z({list:$(Q(M().transform(e=>O(Yo)(e)))),expose:$(Q(M().transform(e=>O(Xo)(e)))),unexpose:$(Q(M().transform(e=>O(Zo)(e))))})));var Qo=p([`synced`,`pending`,`unknown`]),$o=t({port:b(Xo.fields.port),id:E,command:E,cwd:b(m),startedAt:y.pipe(T(x()),T(ve(0))),state:p([`running`,`exited`,`uncertain`]),exitCode:b(y.pipe(T(x()))),sync:Qo,endedAt:b(y.pipe(T(x()),T(ve(0))))}),es=t({processes:s($o)}),ts=t({process:$o,signalled:v});t({requestId:E.pipe(T(A(256))),command:E.pipe(T(A(16384))),cwd:i(m),port:i(Xo.fields.port)}),Mo(`computer.processes`,1,C(()=>Z({start:$(Q(M().transform(e=>O($o)(e)))),list:$(Q(M().transform(e=>O(es)(e)))),kill:$(Q(M().transform(e=>O(ts)(e))))})));var ns=Mo(`computer.readFile`,1,C(()=>Z({open:$(Z({response:$(pe(Response)),close:No}))})));async function rs(e,t,n){return await Vo(await e.require(ns).open(t),{...n,name:t.path.split(`/`).at(-1)??`file`})}async function is(e,t){return O(Uo)(await e.require(Wo).list(t))}var as=Mo(`computer.writeFile`,3,C(()=>Z({open:$(Z({write:No,close:No})),mkdir:No,replace:$(Q(M().transform(e=>O(os)(e))))}))),os=D([t({kind:o(`replaced`),path:E,bytes:y.pipe(T(x()),T(ve(0)))}),t({kind:o(`conflict`)})]);async function ss(e,t,n){n.signal?.throwIfAborted();let r=await e.require(as).replace(t);if(r.kind===`conflict`)throw new _(`Computer file changed since it was opened`,{code:`CONFLICT`,retryable:!1});return{path:r.path,bytes:r.bytes}}var cs=t({computerName:E.pipe(T(A(256))),teamName:E.pipe(T(A(256))),modelDoor:E.pipe(T(A(256))),uptimeSeconds:y.pipe(T(x()),T(ve(0))),version:E.pipe(T(A(64)))});Mo(`computer.terminal`,2,C(()=>Z({open:$(Z({information:$(Q(M().transform(e=>O(cs)(e)))),output:$(pe(ReadableStream).transform(e=>e.pipeThrough(new TransformStream({transform(e,t){t.enqueue(pe(Uint8Array).parse(e))}})))),input:$(pe(WritableStream)),resize:No,close:No}))})));async function ls(e,t,n){await Ho(await e.require(as).open({path:t.path}),t.content,n)}var us=n(`FilePlus2`,[[`path`,{d:`M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4`,key:`1pf5j1`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M3 15h6`,key:`4e2qda`}],[`path`,{d:`M6 12v6`,key:`1u72j0`}]]),ds=n(`FolderOpen`,[[`path`,{d:`m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2`,key:`usdka0`}]]),fs={2:`h2`,3:`h3`,4:`h4`};function ps(e,t){let{reduced:n}=t,r=e&&!n,i=ee(t,600),[a,o]=(0,N.useState)(r);return(0,N.useEffect)(()=>{if(o(r),!r)return;let e=globalThis.setTimeout(()=>{o(!1)},i);return()=>{globalThis.clearTimeout(e)}},[r,i]),a}var ms=(0,P.jsx)(be,{decorative:!0,pace:`idle`,size:`md`,tone:`primary`,variant:`wander`}),hs=(0,N.forwardRef)(function({actions:e,className:t,description:n,headingLevel:r=2,primaryAction:i,suggestions:a,thinking:o=!1,title:s,visual:l,renderVisual:u,variant:d=`plain`,...f},p){let ee=(0,N.useId)(),m=(0,N.useRef)(null),te=c(m),h=ps(d===`speech`,te)&&!o,g=fs[r],ne=l??(d===`panel`?`blobs`:void 0),_=u?u({speaking:h,thinking:o}):ne===`blobs`?ms:ne,v=`${ee}-reason`,ie=(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(g,{ref:m,className:`empty-state-title`,id:f[`aria-labelledby`]?void 0:ee,children:s}),(0,P.jsx)(`p`,{children:n}),i?(0,P.jsxs)(`div`,{className:`empty-state-primary`,children:[(0,P.jsx)(ke,{"aria-describedby":i.disabled&&i.disabledReason?v:void 0,disabled:i.disabled,loading:i.pending===!0,onClick:i.onSelect,variant:`primary`,children:i.label}),i.disabled&&i.disabledReason?(0,P.jsx)(`span`,{className:`empty-state-reason`,id:v,children:i.disabledReason}):null]}):null,a&&a.length>0?(0,P.jsx)(`ul`,{"aria-label":`Try one of these`,className:`empty-state-suggestions`,children:a.map((e,t)=>(0,P.jsx)(`li`,{children:(0,P.jsx)(ke,{disabled:e.disabled,loading:e.pending===!0,size:`sm`,variant:`outline`,onClick:e.onSelect,children:e.label})},`${String(t)}:${e.label}`))}):null,e?(0,P.jsx)(`div`,{className:`empty-state-actions`,children:e}):null]});return(0,P.jsxs)(`section`,{...f,"aria-labelledby":f[`aria-labelledby`]??ee,className:re(`empty-state`,d!==`plain`&&`empty-state-${d}`,t),ref:p,children:[_?(0,P.jsx)(`div`,{"aria-hidden":`true`,className:`empty-state-visual`,children:_}):null,d===`speech`?(0,P.jsx)(`div`,{className:`empty-state-bubble`,children:ie}):ie]})});export{qa as $,_o as A,Qa as B,yo as C,at as Ct,Ga as D,Ue as Dt,Ca as E,Ge as Et,Oa as F,Va as G,Na as H,ka as I,Ka as J,Ha as K,Aa as L,Ta as M,Ea as N,lo as O,He as Ot,Da as P,Pa as Q,Xa as R,Do as S,Ze as St,vo as T,Xe as Tt,Ia as U,Ma as V,Wa as W,Ya as X,uo as Y,Fa as Z,Mo as _,vt as _t,as as a,Mi as at,Eo as b,ut as bt,ss as c,Ai as ct,Ro as d,Yt as dt,Ja as et,Io as f,qt as ft,No as g,yt as gt,$ as h,bt as ht,Wo as i,Ni as it,wa as j,go as k,ze as kt,ls as l,dr as lt,Z as m,I as mt,ds as n,Fi as nt,is as o,Oi as ot,Q as p,Nt as pt,po as q,us as r,Pi as rt,rs as s,ki as st,hs as t,fo as tt,zo as u,hn as ut,Oo as v,Ye as vt,xo as w,ht as wt,ko as x,it as xt,To as y,F as yt,ja as z};
|