@fungi.computer/grove 0.10.4 → 0.10.6
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/{anthropic-messages-CZtR6Wkk.js → anthropic-messages-DJIvEmJB.js} +3 -3
- package/dist/assets/{azure-openai-responses-xWQMH1nI.js → azure-openai-responses-BfRLIuwd.js} +1 -1
- package/dist/assets/{burger-DiSLBppO.js → burger-BE3Gxp6Y.js} +1 -1
- package/dist/assets/{cat-C7kQLCMI.js → cat-gQl6DJEL.js} +1 -1
- package/dist/assets/{compat-ymflfqPx.js → compat-DsxllSjm.js} +2 -2
- package/dist/assets/{extension-hook-DXkKDNDm.js → extension-hook-ClyQNPvs.js} +2 -2
- package/dist/assets/{google-generative-ai-9bgLeTus.js → google-generative-ai-Cxdc5oJK.js} +1 -1
- package/dist/assets/{google-shared-DJhPs_5J.js → google-shared-D0zrFjlp.js} +1 -1
- package/dist/assets/{google-vertex-DLbMbpih.js → google-vertex-CcRFi-sr.js} +1 -1
- package/dist/assets/{index-BlAJPA7m.js → index-2Nq0m3K6.js} +4 -4
- package/dist/assets/{mistral-conversations-rDwzNiV7.js → mistral-conversations-CoJ2POrB.js} +1 -1
- package/dist/assets/{node.browser-BKMHLATb.js → node.browser-D3wgLoqB.js} +1 -1
- package/dist/assets/{openai-codex-responses-CtbDzps8.js → openai-codex-responses-C5ydbzLk.js} +1 -1
- package/dist/assets/{openai-completions-CVG5YVCc.js → openai-completions-BQ_15Kkh.js} +1 -1
- package/dist/assets/{openai-responses-DzFMVUgG.js → openai-responses-DPK4DEzd.js} +1 -1
- package/dist/assets/{openai-responses-shared-BcrG3n6z.js → openai-responses-shared-Dda1cu5U.js} +1 -1
- package/dist/assets/{parakeet-D8It96x2.js → parakeet-BXf0kg3T.js} +1 -1
- package/dist/assets/{parakeet-conversation-DTKcx8BS.js → parakeet-conversation-Cdiu-eyV.js} +1 -1
- package/dist/assets/{runtime-core-B3RwT1fj.js → runtime-core-BZbN1OFo.js} +1 -1
- package/dist/assets/{sigil-B__VZ_6c.js → sigil-Ciz-0LU3.js} +1 -1
- package/dist/assets/{transform-messages-beQHkjxo.js → transform-messages-DIZp_gFG.js} +1 -1
- package/dist/assets/{website-conversation-C1IWoELN.js → website-conversation-CX0AUueJ.js} +1 -1
- package/dist/index.html +3 -3
- package/package.json +7 -7
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/runtime-core-
|
|
2
|
-
import{r as e,t}from"./rolldown-runtime-hePW80VL.js";import{$ as n,$n as r,$r as i,A as a,An as o,Ar as s,At as c,B as l,Bn as u,Br as d,Bt as f,C as p,Ci as m,Cn as h,Cr as g,Ct as _,D as v,Dn as y,E as b,Ei as x,En as S,Et as C,F as w,Fn as T,Fr as E,Ft as ee,G as D,Gn as O,Gr as k,H as A,Hn as j,Hr as te,I as ne,In as re,It as ie,J as ae,Jn as oe,K as se,Kn as ce,Kr as le,L as ue,Ln as M,Lr as de,Lt as fe,M as pe,Mr as me,Mt as he,N as ge,Nr as _e,On as ve,P as ye,Pr as be,Pt as N,Q as xe,Qn as Se,Qr as Ce,R as we,Rn as Te,Rr as Ee,Rt as De,S as Oe,Sn as ke,St as Ae,T as je,Ti as Me,Tn as Ne,Tr as Pe,Tt as Fe,U as Ie,Un as Le,Ur as Re,V as ze,Vn as Be,Vr as Ve,Vt as He,W as Ue,Wn as We,Wr as Ge,X as Ke,Xn as qe,Y as Je,Yn as Ye,Z as Xe,Zn as Ze,Zr as Qe,_ as $e,_n as et,_r as tt,_t as nt,a as rt,at as it,b as at,bn as ot,br as st,bt as ct,c as lt,ci as ut,cn as dt,cr as ft,ct as pt,d as mt,di as ht,dr as gt,dt as _t,ei as vt,er as yt,et as bt,f as xt,fi as St,fr as Ct,ft as wt,g as Tt,gi as Et,gn as Dt,gt as Ot,h as kt,hi as At,hn as jt,hr as Mt,ht as Nt,i as Pt,it as Ft,j as It,jn as Lt,jr as Rt,k as zt,ki as Bt,kn as Vt,kt as Ht,l as Ut,li as Wt,ln as Gt,lr as Kt,lt as qt,m as Jt,mi as Yt,mn as Xt,mr as Zt,mt as Qt,n as $t,ni as en,nr as tn,nt as nn,o as rn,oi as an,or as on,ot as sn,p as cn,pi as ln,pr as un,pt as dn,q as fn,qn as pn,qr as mn,r as hn,rr as gn,rt as _n,s as vn,si as yn,sn as bn,sr as xn,st as Sn,t as Cn,ti as wn,tr as Tn,tt as En,ui as Dn,ur as On,v as kn,vn as An,vr as jn,vt as Mn,w as Nn,wi as Pn,wn as Fn,wr as In,x as Ln,xn as Rn,xt as zn,y as Bn,yn as Vn,yr as Hn,yt as Un,z as Wn,zn as Gn,zr as Kn}from"./sigil-B__VZ_6c.js";import{$i as qn,Aa as Jn,Bi as Yn,Ct as Xn,Da as Zn,E as Qn,Ei as $n,F as er,Fa as tr,Gi as nr,Hi as rr,I as ir,Ji as ar,Jn as or,K as sr,Ki as cr,Na as lr,Nn as ur,Oa as dr,Qi as fr,Qn as pr,Ri as mr,St as hr,Ta as gr,Ui as _r,V as vr,Vi as yr,Wi as br,Xi as xr,Y as Sr,Yi as Cr,Z as wr,Zi as Tr,_ as Er,_a as Dr,a as Or,ar as kr,ba as Ar,bt as jr,ca as Mr,d as Nr,da as Pr,ea as Fr,fa as Ir,fr as Lr,g as Rr,ga as zr,gi as Br,gt as Vr,h as Hr,ht as Ur,i as Wr,ir as Gr,it as Kr,j as qr,ji as Jr,ka as Yr,l as Xr,lr as Zr,m as Qr,mt as $r,na as ei,oa as ti,ot as ni,pa as ri,pt as ii,qi as ai,ra as oi,rr as si,s as ci,sa as li,sr as ui,t as di,tt as fi,ur as pi,va as mi,wa as hi,wt as gi,xa as P,xi as _i,xt as vi,y as yi,ya as bi,zi as xi}from"./Effect-CsknxyoC.js";import{$a as Si,$n as Ci,$r as wi,Ai as F,Bi as Ti,Bo as Ei,Ci as I,Co as Di,Cr as Oi,Di as ki,Do as Ai,Ei as ji,Eo as Mi,Er as Ni,Fa as Pi,Fi,Fo as Ii,Ga as Li,Ha as Ri,Hi as zi,Ji as Bi,Jr as Vi,Ka as Hi,Ki as Ui,Lo as Wi,Ma as L,Mi as Gi,Na as R,Ni as z,Nr as Ki,Oi as qi,Oo as Ji,Pa as B,Pi as Yi,Qa as Xi,Qr as Zi,Ri as Qi,Si as V,So as $i,Ta as H,Ti as ea,Tr as ta,Ua as na,Va as ra,Vi as ia,Wa as aa,Wr as oa,Xa as sa,Xi as ca,Ya as la,Yi as ua,Yn as da,Yr as fa,Za as pa,Zi as ma,Zr as ha,_a as ga,aa as _a,ao as va,bi as ya,bo as ba,c as xa,ci as Sa,d as Ca,di as wa,do as Ta,eo as Ea,f as Da,fi as U,fr as Oa,go as ka,i as Aa,ii as W,io as ja,ji as Ma,jo as Na,ka as Pa,la as Fa,li as Ia,m as La,mo as Ra,mr as za,ni as Ba,no as Va,oa as Ha,oi as Ua,oo as Wa,p as Ga,pa as Ka,pi as G,po as qa,pr as Ja,qa as Ya,ri as Xa,ro as Za,to as Qa,ui as $a,uo as eo,vi as to,vo as no,wr as ro,xa as K,xi as io,xo as ao,yi as oo,yo as so,za as co,zi as lo,zo as uo}from"./extension-hook-DXkKDNDm.js";import{a as fo,o as po,s as mo,t as ho}from"./document-Bq-ilh6h.js";import{n as go}from"./animation-Ca8A_H2p.js";import{t as _o}from"./preload-helper-DY31Aviq.js";import{a as vo,i as yo,n as bo,r as xo,t as So}from"./base-face-BYNJAADF.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var q=e(Bt(),1);function Co(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:x(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()}}}var wo=V.pipe(z(H(1)),z(K(80))),To=[`CANCELLED`,`CAPABILITY_DENIED`,`CAPABILITY_REVOKED`,`COMMAND_NOT_DECLARED`,`CONFLICT`,`DELIVERY_PENDING`,`DISCONNECTED`,`FILE_TOO_LARGE`,`HOST_FAILURE`,`IDENTITY`,`INSUFFICIENT_CREDIT`,`INVALID_ARGUMENT`,`MEDIA_PROVIDER_FAILURE`,`MEDIA_PROVIDER_FAILURE_UNCHARGED`,`PROTOCOL`,`SAFETY_FILTER_REFUSED`,`SELECTION_CHANGED`,`SETUP_REQUIRED`,`TIMEOUT`];I({name:U(`AppError`),code:G(To),retryable:Ua,need:R(V)});var J=class extends Error{code;retryable;need;constructor(e,t){super(e,{cause:t.cause}),this.name=`AppError`,this.code=t.code,this.retryable=t.retryable,this.need=t.need}};function Eo(e){return`This needs ${e??`setup`} first.`}Eo(void 0),Tr(`light.dark.latte.mocha.readout.readout-night.field-guide.field-guide-night.embed.embed-dark.phosphor.codec.paper.ember.tide.tape.sunrise.pirate-radio.pirate-radio-night.consulting.consulting-ink.consulting-night.consulting-night-ink.consulting-riso-latte.consulting-riso-latte-ink.consulting-riso-glomzy.consulting-riso-glomzy-ink.vishnu.coin.coin-night.chamfer`.split(`.`));var Do=`data-theme`;function Oo(e){return e||(globalThis.document?.documentElement??null)}function ko(e){let t=e.trim();if(t.length===0)throw TypeError(`Theme must be a non-empty string`);return t}function Ao(e,t){let n=ko(e),r=Oo(t);r&&r.setAttribute(Do,n)}function jo(e){return Oo(e)?.getAttribute(Do)??null}function Mo(e,t){let n=new Set(t);return e.filter(e=>!n.has(e))}var No=class extends yn{#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||!Dn(e,n)});!o&&!s||(o&&(this.#l=t,this.#i=n),this.#t=r,this.hasListeners()&&(o&&(Mo(e,n).forEach(e=>{e.destroy()}),Mo(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=Wt(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 en(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)})})}}},Po=q.createContext(!1),Fo=()=>q.useContext(Po);Po.Provider;var Y=Yt();function Io(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Lo=q.createContext(Io()),Ro=()=>q.useContext(Lo),zo=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?ht(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},Bo=e=>{q.useEffect(()=>{e.clearReset()},[e])},Vo=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||ht(n,[e.error,r])),Ho=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},Uo=(e,t)=>e?.suspense&&t.isPending,Wo=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Go({queries:e,...t},n){let r=ln(n),i=Fo(),a=Ro(),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=>{Ho(e);let t=r.getQueryCache().get(e.queryHash);zo(e,a,t)}),Bo(a);let[c]=q.useState(()=>new No(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)):ut,[c,f]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),q.useEffect(()=>{c.setQueries(s,t)},[s,t,c]);let p=l.some((e,t)=>Uo(s[t],e))?l.flatMap((e,t)=>{let n=s[t];return n&&Uo(n,e)?Wo(n,new en(r,n),a):[]}):[];if(p.length>0)throw Promise.all(p);let m=l.find((e,t)=>{let n=s[t];return n&&Vo({result:e,errorResetBoundary:a,throwOnError:n.throwOnError,query:r.getQueryCache().get(n.queryHash),suspense:n.suspense})});if(m)throw m.error;return u(d())}function Ko(e,t,n){let r=Fo(),i=Ro(),a=ln(n),o=a.defaultQueryOptions(e),s=a.getQueryCache().get(o.queryHash),c=e.subscribed!==!1;o._optimisticResults=r?`isRestoring`:c?`optimistic`:void 0,Ho(o),zo(o,i,s),Bo(i);let[l]=q.useState(()=>new t(a,o)),u=l.getOptimisticResult(o),d=!r&&c;if(q.useSyncExternalStore(q.useCallback(e=>{let t=d?l.subscribe(an.batchCalls(e)):ut;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),q.useEffect(()=>{l.setOptions(o)},[o,l]),Uo(o,u))throw Wo(o,l,i);if(Vo({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return o.notifyOnChangeProps?u:l.trackResult(u)}function qo(e,t){return Ko(e,en,t)}function Jo(e,t){let n=ln(t),[r]=q.useState(()=>new wn(n,e));q.useEffect(()=>{r.setOptions(e)},[r,e]);let i=q.useSyncExternalStore(q.useCallback(e=>r.subscribe(an.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=q.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(ut)},[r]);if(i.error&&ht(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}var Yo=t((e=>{var t=Qe();e.createRoot=t.createRoot,e.hydrateRoot=t.hydrateRoot}))();function Xo(e,t){console.error(JSON.stringify({source:`agar`,operation:e,failureKind:t instanceof Error?`Error`:`NonErrorThrown`}),Ta(t))}var Zo=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 Qo=globalThis[Zo],$o=Qo?Qo.RpcTarget:class{},es=async function(){}.constructor,ts=typeof Buffer<`u`?Buffer.prototype:void 0;function ns(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 es.prototype:return`function`;case Array.prototype:return`array`;case Date.prototype:return`date`;case Uint8Array.prototype:case ts: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 ms.prototype:return`stub`;case hs.prototype:return`rpc-promise`;default:if(Qo){if(t==Qo.RpcStub.prototype||e instanceof Qo.ServiceStub)return`rpc-target`;if(t==Qo.RpcPromise.prototype||t==Qo.RpcProperty.prototype)return`rpc-thenable`}return e instanceof $o?`rpc-target`:e instanceof Error?`error`:`unsupported`}}function rs(){throw Error(`RPC map() implementation was not loaded.`)}var is={applyMap:rs,sendMap:rs};function as(){throw Error(`Stream implementation was not loaded.`)}var os={createWritableStreamHook:as,createWritableStreamFromHook:as,createReadableStreamHook:as},ss=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}}},cs=class extends ss{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)}}},ls=new cs(Error(`Attempted to use RPC stub after it has been disposed.`)),us=(e,t,n)=>e.call(t,n);function ds(e,t){let n=us;us=e;try{return t()}finally{us=n}}var fs=Symbol(`realStub`),ps={apply(e,t,n){let r=e.raw;return new hs(us(r.hook,r.pathIfPromise||[],Ss.fromAppParams(n)),[])},get(e,t,n){let r=e.raw;if(t===fs)return r;if(t in hs.prototype)return r[t];if(typeof t==`string`)return new hs(r.hook,r.pathIfPromise?[...r.pathIfPromise,t]:[t]);if(t===Symbol.dispose&&(!r.pathIfPromise||r.pathIfPromise.length==0))return()=>{r.hook.dispose(),r.hook=ls}},has(e,t){let n=e.raw;return t===fs?!0:t in hs.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.`)}},ms=class e extends $o{constructor(e,t){if(super(),!(e instanceof ss)){let n=e;if(e=n instanceof $o||n instanceof Function?Ds.create(n,void 0):new Ts(Ss.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,ps)}hook;pathIfPromise;dup(){let t=this[fs];return t.pathIfPromise?new e(t.hook.get(t.pathIfPromise)):new e(t.hook.dup())}onRpcBroken(e){this[fs].hook.onBroken(e)}map(e){let{hook:t,pathIfPromise:n}=this[fs];return is.sendMap(t,n||[],e)}toString(){return`[object RpcStub]`}},hs=class extends ms{constructor(e,t){if(e instanceof ss)super(e,t??[]);else{if(t!==void 0)throw TypeError(`RpcPromise constructor expected one argument, received two.`);let n=ns(e);if(n===`rpc-promise`){let t=bs(e);if(t.pathIfPromise.length>0)super(t.hook,t.pathIfPromise);else{let e=t.hook;t.hook=ls,super(e,[])}}else if(n===`rpc-thenable`)super(Ds.create(e,void 0),[]);else{let t=new Os(Promise.resolve(e).then(e=>new Ts(Ss.fromAppReturn(e))));t.ignoreUnhandledRejections(),super(t,[])}}}then(e,t){return xs(this).then(...arguments)}catch(e){return xs(this).catch(...arguments)}finally(e){return xs(this).finally(...arguments)}toString(){return`[object RpcPromise]`}};function gs(e){let{hook:t,pathIfPromise:n}=e[fs];return n&&n.length>0?t.get(n):t}function _s(e){let{hook:t,pathIfPromise:n}=e[fs];return n?t.get(n):t.dup()}function vs(e){let{hook:t,pathIfPromise:n}=e[fs];if(!(n&&n.length>0))return t}function ys(e){return e[fs].hook}function bs(e){return e[fs]}async function xs(e){let{hook:t,pathIfPromise:n}=e[fs];return n.length>0&&(t=t.get(n)),(await t.pull()).deliverResolve()}var Ss=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 Ds.create(e,t)}if(this.source===`return`){let r=this.rpcTargets?.get(e);return r?n?r.dup():(this.rpcTargets?.delete(e),r):(r=Ds.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 os.createWritableStreamHook(e);if(this.source===`return`){let t=this.rpcTargets?.get(e);return t?n?t.dup():(this.rpcTargets?.delete(e),t):(t=os.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 os.createReadableStreamHook(e);if(this.source===`return`){let t=this.rpcTargets?.get(e);return t?n?t.dup():(this.rpcTargets?.delete(e),t):(t=os.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(ns(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?_s(t):gs(t),t instanceof hs){let e=new hs(a,[]);return this.promises.push({parent:r,property:n,promise:e}),e}return this.hooks.push(a),new ms(a)}case`function`:case`rpc-target`:{let n=e,r;return r=a?a.getHookForRpcTarget(n,t,i):Ds.create(n,t),this.hooks.push(r),new ms(r)}case`rpc-thenable`:{let o=e,s;return s=a?new hs(a.getHookForRpcTarget(o,t,i),[]):new hs(Ds.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):os.createWritableStreamHook(n),this.hooks.push(r),n}case`readable`:{let n=e,r;return r=a?a.getHookForReadableStream(n,t,i):os.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 hs)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=vs(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 hs?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(ns(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=vs(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)):Es(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=os.createWritableStreamHook(t),n.dispose();return}case`readable`:{let t=e,n=this.rpcTargets?.get(t);n?this.rpcTargets.delete(t):n=os.createReadableStreamHook(t),n.dispose();return}default:return}}ignoreUnhandledRejections(){this.hooks?(this.hooks.forEach(e=>{e.ignoreUnhandledRejections()}),this.promises.forEach(e=>ys(e.promise).ignoreUnhandledRejections())):this.ignoreUnhandledRejectionsImpl(this.value)}ignoreUnhandledRejectionsImpl(e){switch(ns(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`:ys(e).ignoreUnhandledRejections();return;case`rpc-thenable`:e.then(e=>{},e=>{});return;default:return}}};function Cs(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(ns(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}=bs(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 hs){let{hook:t,pathIfPromise:n}=bs(e);return{hook:t,remainingPath:n||[]}}return{value:e,parent:t,owner:r}}var ws=class extends ss{call(e,t){let n;try{let{value:t,owner:r}=this.getValue();n=Cs(t,void 0,e,r)}catch(e){return t.dispose(),new cs(e)}return n.hook?n.hook.call(n.remainingPath,t):typeof n.value==`function`?new Os(t.deliverCall(n.value,n.parent).then(e=>new Ts(e))):(t.dispose(),new cs(TypeError(`'${e.join(`.`)}' is not a function.`)))}map(e,t,n){try{let r;try{let{value:t,owner:n}=this.getValue();r=Cs(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):is.applyMap(r.value,r.parent,r.owner,t,n)}catch(e){return new cs(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=Cs(t,void 0,e,n);return r.hook?r.hook.get(r.remainingPath):new Ts(Ss.deepCopyFrom(r.value,r.parent,r.owner))}catch(e){return new cs(e)}}},Ts=class e extends ws{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(Ss.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 ms&&this.payload.value.onRpcBroken(e)}};function Es(e){if(Symbol.dispose in e)try{e[Symbol.dispose]()}catch(e){Promise.reject(e)}}var Ds=class e extends ws{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=>Ss.fromAppReturn(e)):Promise.reject(Error(`Tried to resolve a non-promise stub.`))}ignoreUnhandledRejections(){}dispose(){this.target&&=(this.refcount&&--this.refcount.count==0&&Es(this.target),void 0)}onBroken(e){let t=this.target;t&&`then`in t&&Promise.resolve(t).then(()=>{},e)}},Os=class e extends ss{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)}},ks={maxBigIntDigits:16384,maxDepth:256,maxMessageSize:33554432},As=new Uint8Array(new Uint16Array([1]).buffer)[0]===1,js=[`ArrayBuffer`,`DataView`,`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`Int16Array`,`Uint16Array`,`Int32Array`,`Uint32Array`,`BigInt64Array`,`BigUint64Array`,`Float32Array`,`Float64Array`];function Ms(e){return js.includes(e)}var Ns={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},Ps={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},Fs=new Map;for(let e of Object.keys(Ps))Fs.set(Ps[e],e);function Is(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 Ls=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 Rs(e,t){let n=await new Response(e).blob();return n.type===t?n:n.slice(0,n.size,t)}var zs={__proto__:null,Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError},Bs=class e{exporter;source;encodingLevel;constructor(e,t,n){this.exporter=e,this.source=t,this.encodingLevel=n}static devaluate(t,n,r=Ls,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(ns(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=Fs.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=Ns[t];!As&&i&&(n=n.slice(),Is(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=os.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=os.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}=bs(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 ks}};function Vs(e,t){return new hs(new Os(new Response(t).arrayBuffer().then(t=>{let n=new Uint8Array(t),r=new Request(e,{body:n});return new Ts(Ss.fromAppReturn(r))})),[])}function Hs(e,t){return new hs(new Os(Rs(e,t).then(e=>new Ts(Ss.fromAppReturn(e)))),[])}var Us=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=Ss.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(!Ms(t[2])){let e=t[2].slice(0,64);throw TypeError(`Unknown bytes type marker: ${e}`)}let n=t[2],r=Ns[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(!As&&r!==void 0&&Is(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=zs[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=Vs(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=Hs(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 hs(e,[]);return this.promises.push({promise:t,parent:n,property:r}),t}return this.hooks.push(e),new hs(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 hs(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 hs(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 ms(e)}}break;case`writable`:if(typeof t[1]==`number`){let e=this.importer.importStub(t[1]),n=os.createWritableStreamFromHook(e);return this.hooks.push(e),n}break;case`readable`:if(typeof t[1]==`number`){let e=this.importer.getPipeReadable(t[1]),n=os.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}},Ws=16,Gs=8,Ks=16,qs=64;function Js(e){return 2+e.length*3}function Ys(e,t,n=0){if(n>=qs)return Gs;switch(typeof e){case`string`:return Js(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 Ks+e.byteLength;if(typeof Blob<`u`&&e instanceof Blob)return Ks+e.size;if(e instanceof Date)return 16;if(t??=new WeakSet,t.has(e))return Gs;if(t.add(e),e instanceof Array){let r=Ws;for(let i of e)r+=Gs+Ys(i,t,n+1);return r}if(e instanceof Error){let r=Ws+Js(e.name)+Js(e.message)+Js(e.stack??``);for(let i of Object.keys(e))r+=Gs+Js(i)+Ys(e[i],t,n+1);return r}let r=Ws;for(let i of Object.keys(e))r+=Gs+Js(i)+Ys(e[i],t,n+1);return r}default:return 16}}var Xs=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 cs(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)}},Zs=class e extends ss{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)}},Qs=class extends Zs{session;constructor(e){super(!1,e),this.session=e.session}dispose(){if(this.session){let e=this.session;this.session=void 0,e.shutdown()}}},$s=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={...ks,...n.limits},this.exports.push({hook:t,refcount:1}),this.imports.push(new Xs(this,0,!1)),this.readLoop().catch(e=>this.abort(e))}getMainImport(){return new Qs(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,Bs.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 ms){let{hook:n,pathIfPromise:r}=bs(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=Bs.devaluate(t.value,void 0,this,t,this.encodingLevel);this.send([`resolve`,e,n]),r&&this.releaseExport(e,1)},t=>{this.send([`reject`,e,Bs.devaluate(t,void 0,this,void 0,this.encodingLevel)]),r&&this.releaseExport(e,1)}).catch(t=>{try{this.send([`reject`,e,Bs.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 Zs&&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 Xs(this,e,!1),this.imports[e]=t),new Zs(!1,t)}importPromise(e){if(this.abortReason)throw this.abortReason;if(this.imports[e])return new cs(Error(`Bug in RPC system: The peer sent a promise reusing an existing export ID.`));let t=new Xs(this,e,!0);return this.imports[e]=t,new Zs(!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 Xs(this,n,!1);this.imports.push(r);let i=new Zs(!1,r),a=os.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=Bs.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 Xs(this,this.imports.length,!1);return this.imports.push(i),new Zs(!0,i)}sendStream(e,t,n){if(this.abortReason)throw n.dispose(),this.abortReason;let r=[`pipeline`,e,t],i;try{i=Bs.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=Ys(a));let s=this.imports.length,c=new Xs(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 Xs(this,this.imports.length,!1);return this.imports.push(a),new Zs(!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`,Bs.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 Ts(new Us(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 Ts(new Us(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=os.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 Ts(new Us(this,this.encodingLevel).evaluate(n[2])));else{let e=new Us(this,this.encodingLevel).evaluate(n[2]);e.dispose(),t.resolve(new cs(e.value))}}else n[0]==`resolve`&&new Us(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 Us(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}},ec=class{#e;#t;constructor(e,t,n={}){let r;r=t?new Ts(Ss.fromAppReturn(t)):new cs(Error(`This connection has no main object.`)),this.#e=new $s(e,r,n),this.#t=new ms(this.#e.getMainImport())}getRemoteMain(){return this.#t}getStats(){return this.#e.getStats()}drain(){return this.#e.drain()}};function tc(e,t,n){return new ec(new nc(e),t,n).getRemoteMain()}var nc=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))}},rc,ic=class{context;captureMap=new Map;instructions=[];constructor(e,t){this.context=rc?{parent:rc,captures:[],subject:rc.capture(e),path:t}:{parent:void 0,captures:[],subject:e,path:t},rc=this}unregister(){rc=this.context.parent}makeInput(){return new oc(this,0)}makeOutput(e){let t;try{t=Bs.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 oc(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=Bs.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 oc(this,this.instructions.length)}pushGet(e,t){let n=this.capture(e.dup());return this.instructions.push([`pipeline`,n,t]),new oc(this,this.instructions.length)}capture(e){if(e instanceof oc&&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){}};is.sendMap=(e,t,n)=>{let r=new ic(e,t),i;try{i=Ss.fromAppReturn(ds(r.pushCall.bind(r),()=>n(new hs(r.makeInput(),[]))))}finally{r.unregister()}if(i instanceof Promise)throw i.catch(e=>{}),Error(`RPC map() callbacks cannot be async.`);return new hs(r.makeOutput(i),[])};function ac(){throw Error(`Attempted to use an abstract placeholder from a mapper function. Please make sure your map function has no side effects.`)}var oc=class extends ss{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(rc)return rc.pushGet(this,e);ac()}call(e,t){t.dispose(),ac()}map(e,t,n){for(let e of t)e.dispose();ac()}pull(){ac()}ignoreUnhandledRejections(){}onBroken(e){ac()}},sc=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 Us(this).evaluateCopy(t);if(e.value instanceof ms){let t=vs(e.value);if(t){this.variables.push(t);continue}}this.variables.push(new Ts(e))}return new Us(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 ks}};function cc(e,t,n,r,i){let a=new sc(r,new Ts(Ss.deepCopyFrom(e,t,n)));try{return a.apply(i)}finally{a.dispose()}}is.applyMap=(e,t,n,r,i)=>{try{let a;if(e instanceof hs)throw Error(`applyMap() can't be called on RpcPromise`);if(e instanceof Array){let t=[];try{for(let a of e)t.push(cc(a,e,n,r,i))}catch(e){for(let e of t)e.dispose();throw e}a=Ss.fromArray(t)}else a=e==null?Ss.fromAppReturn(e):cc(e,t,n,r,i);return new Ts(a)}finally{for(let e of r)e.dispose()}};var lc=class e extends ss{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 Os((r===`write`?t.deliverStreamWrite(n.writer):t.deliverCall(n.writer[r],n.writer)).then(e=>new Ts(e)))}catch(e){return t.dispose(),new cs(e)}}map(e,t,n){for(let e of t)e.dispose();return new cs(Error(`Cannot use map() on a WritableStream`))}get(e){return new cs(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)}},uc=262144,dc=1073741824,fc=65536,pc=2,mc=1.25,hc=.9,gc=3,_c=class{now;window=uc;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?pc:mc,s=a*this.minRtt*o;s=Math.min(s,e.windowAtSend*o),s=e.windowFullAtSend?Math.max(s,e.windowAtSend*hc):Math.max(s,this.window),this.window=Math.max(Math.min(s,dc),fc),this.inStartupPhase&&e.sentTime>=this.roundStartTime&&(this.window>this.lastRoundWindow*mc?this.roundsWithoutIncrease=0:++this.roundsWithoutIncrease>=gc&&(this.inStartupPhase=!1),this.roundStartTime=t,this.lastRoundWindow=this.window)}return this.bytesInFlight<this.window}};function vc(e){let t,n=!1,r=new _c(()=>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=Ss.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`],Ss.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`],Ss.fromAppParams([n]));r.then(()=>o(),()=>o())}})}var yc=class e extends ss{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 cs(Error(`Cannot call methods on a ReadableStream stub`))}map(e,t,n){for(let e of t)e.dispose();return new cs(Error(`Cannot use map() on a ReadableStream`))}get(e){return new cs(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){}};os.createWritableStreamHook=lc.create,os.createWritableStreamFromHook=vc,os.createReadableStreamHook=yc.create;var bc=ms,xc=$o,Sc=tc;function Cc(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 wc(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 Tc(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}function Ec(e){let t=e.trim().toLowerCase();if(!t)throw Error(`Invalid keymap token: token cannot be empty`);return t}function Dc(e){let t=e.trim().toLowerCase();if(!t)throw Error(`Invalid key name: key name cannot be empty`);return t}function Oc(e){return{name:Dc(e.name),ctrl:e.ctrl??!1,shift:e.shift??!1,meta:e.meta??!1,super:e.super??!1,hyper:e.hyper||void 0}}function kc(e){return{name:e.name,ctrl:e.ctrl,shift:e.shift,meta:e.meta,super:e.super,hyper:e.hyper||void 0}}function Ac(e,t){let n=kc(Oc(e));return{stroke:n,display:t?.display??Rc(n),match:t?.match??Pc(n),tokenName:t?.tokenName?Ec(t.tokenName):void 0}}function jc(e){return{stroke:kc(e.stroke),display:e.display,match:e.match,tokenName:e.tokenName,patternName:e.patternName,payloadKey:e.payloadKey}}function Mc(e){return e.map(e=>jc(e))}function Nc(e){return`match`in e?e.match:`stroke`in e?Pc(e.stroke):Pc(e)}function Pc(e){return`key:${zc(Oc(e))}`}function Fc(e){let t=e.trim();if(!t)throw Error(`Invalid keymap match id: id cannot be empty`);return`text:${t}`}function Ic(e,t){return`stroke`in e?t?.preferDisplay&&e.display?e.display:Rc(e.stroke):Rc(Oc(e))}function Lc(e,t){return e.map(e=>Ic(e,t)).join(t?.separator??``)}function Rc(e){let t=[];return e.ctrl&&t.push(`ctrl`),e.shift&&t.push(`shift`),e.meta&&t.push(`meta`),e.super&&t.push(`super`),e.hyper&&t.push(`hyper`),t.push(e.name===`return`?`enter`:e.name),t.join(`+`)}function zc(e){return`${e.name}:${+!!e.ctrl}:${+!!e.shift}:${+!!e.meta}:${+!!e.super}:${+!!e.hyper}`}var Bc=Symbol(`keymap-extension-context`);function Vc(e){return e.isDestroyed?null:e.getFocusedTarget()}function Hc(e,t,n){let r=t??e.rootTarget,i=t!==null;for(;r;){if(n(r,i)===!1)return;r=e.getParentTarget(r),i=!1}}function Uc(e,t){let n=new Set;return Hc(e,t,e=>{n.add(e)}),n}function Wc(e,t,n){let r=[],i=Uc(t,n),a=Array.isArray(e)?e:Gc(e);for(let e of a)Kc(t,e,n,i)&&r.push(e);return r}function Gc(e){return[...e].sort((e,t)=>t.priority-e.priority||t.order-e.order)}function Kc(e,t,n,r=Uc(e,n)){let i=t.target;return i?e.isTargetDestroyed(i)?!1:t.targetMode===`focus`?i===n:r.has(i):!0}function qc(e){let t=e.binding.sequence[e.index];if(!t?.patternName)return 0;let n=e.patterns?.at(-1);return n?.name===t.patternName?n.values.length:0}function Jc(e,t,n=!0){let r=e.binding.sequence[e.index];if(!r?.patternName)return!0;let i=t.get(r.patternName);return i?qc(e)>=i.min:n}function Yc(e,t,n=!0){let r=e.binding.sequence[e.index];if(r?.patternName){let n=t.get(r.patternName);if(n&&qc(e)<n.max)return!0}return Jc(e,t,n)&&e.index+1<e.binding.sequence.length}function Xc(e,t){return e.index===e.binding.sequence.length-1&&Jc(e,t,!1)}function Zc(e,t,n,r){return{parent:e,depth:e?e.depth+1:0,stroke:t,match:n,pattern:r,children:new Map,patternChildren:[],bindings:[],reachableBindings:[]}}function Qc(e,t){let n=Zc(null,null,null);for(let r of e){if(r.event!==`press`)continue;let e=n;for(let n of r.sequence){let i;if(n.patternName){let r=t.get(n.patternName);i=e.patternChildren.find(e=>e.pattern?.name===n.patternName),i||(i=Zc(e,n.stroke,n.match,r),e.patternChildren.push(i))}else i=e.children.get(n.match),i||(i=Zc(e,n.stroke,n.match),e.children.set(n.match,i));i.reachableBindings.push(r),e=i}e.bindings.push(r)}return n}function $c(e,t){let n=[];for(let r of e){if(!Jc(r,t))continue;let e=r.index+1,i=r.binding.sequence[e];i&&n.push({part:i,binding:r.binding,index:e,exact:e===r.binding.sequence.length-1,continues:e<r.binding.sequence.length-1})}return n}function el(e,t,n,r){let i=n.patternName;if(!i)return{...e,index:t};let a=[...e.patterns??[]],o=a.at(-1);return o?.name===i?a[a.length-1]={...o,values:[...o.values,r],parts:[...o.parts,n]}:a.push({name:i,payloadKey:n.payloadKey??i,values:[r],parts:[n]}),{layer:e.layer,binding:e.binding,index:t,parts:[...e.parts,n],patterns:a}}function tl(e,t){let n=e.parts.at(-1);if(!n||n.patternName)return t.length;let r=t.indexOf(n.match);return r===-1?t.length:r}function nl(e,t,n,r,i,a,o,s,c){let l=t.sequence[n];if(l){if(l.patternName){let a=s(l.patternName,o);if(!a)return;let u=c(o,l.patternName,a);return el({layer:e,binding:t,index:n,parts:r,patterns:i},n,u,a.value??o.name)}if(a.includes(l.match))return{layer:e,binding:t,index:n,parts:[...r,l],patterns:i}}}function rl(e,t,n,r,i,a){let o=e.binding.sequence[e.index];if(o?.patternName){let s=r.get(o.patternName);if(s&&qc(e)<s.max){let t=i(s.name,n);if(t){let r=a(n,s.name,t);return el(e,e.index,r,t.value??n.name)}}return Jc(e,r,!1)?nl(e.layer,e.binding,e.index+1,e.parts,e.patterns,t,n,i,a):void 0}return nl(e.layer,e.binding,e.index+1,e.parts,e.patterns,t,n,i,a)}function il(e,t,n,r,i){let a=[],o=1/0;for(let s of e.bindings){if(s.event!==`press`)continue;let c=nl(e,s,0,[],void 0,t,n,r,i);if(!c)continue;let l=tl(c,t);l<o&&(o=l,a.length=0),l===o&&a.push(c)}return a}import.meta.require;function al(e){let t=Object.create(null),n=(e,n)=>{let r=t[e];if(!r)return;let i=r.filter(e=>e!==n);i.length===0?delete t[e]:i.length!==r.length&&(t[e]=i)};return{hook(e,r){return t[e]=[...t[e]??[],r],()=>n(e,r)},has(e){return(t[e]?.length??0)>0},emit(n,...r){let i=t[n];if(i)for(let t of i)try{r.length===0?t():t(r[0])}catch(t){e(n,t)}}}}function ol(){let e=[];return{get:()=>e,set:t=>{e=t},remove(t){e=e.filter(e=>e!==t)},has:()=>e.length>0,clear:()=>{e=[]}}}function sl(){let e=ol();return{append(t){return e.set([...e.get(),t]),()=>e.remove(t)},prepend(t){return e.set([t,...e.get()]),()=>e.remove(t)},values:e.get,has:e.has,clear:e.clear}}function cl(){let e=ol(),t=0;return{register(n,r){let i={...r,listener:n,order:t++};return e.set([...e.get(),i].sort((e,t)=>t.priority-e.priority||e.order-t.order)),()=>e.remove(i)},entries:e.get,has:e.has,clear:e.clear}}function ll(e){return typeof e==`string`||!!e&&typeof e==`object`&&!Array.isArray(e)}function ul(e){if(!Array.isArray(e))return{ok:!1,reason:`Invalid keymap bindings: expected an array of binding objects`};for(let[t,n]of e.entries()){if(!n||typeof n!=`object`||Array.isArray(n))return{ok:!1,reason:`Invalid keymap binding at index ${t}: expected a binding object`};if(!ll(n.key))return{ok:!1,reason:`Invalid keymap binding at index ${t}: expected "key" to be a string or keystroke object`}}return{ok:!0}}function dl(e){let t=ul(e);if(!t.ok)throw Error(t.reason);return e.map(e=>({...e,key:typeof e.key==`string`?e.key:{...e.key}}))}function fl(e){return{...e,sequence:Mc(e.sequence)}}function pl(e,t){let n=sl();return{prependLayerAnalyzer(e){return n.prepend(e)},appendLayerAnalyzer(e){return n.append(e)},clearLayerAnalyzers(){n.clear()},analyzeLayer(r){let i=n.values();if(i.length===0)return;let a=ml(r.bindings),o={target:r.target,order:r.order,sourceBindings:r.sourceBindings,bindings:a,hasTokenBindings:r.hasTokenBindings,checkCommandResolution(e){return t.getCommandResolutionStatus(e,r.commands)},warn(t,n,r){e.emitWarning(t,n,r)},warnOnce(t,n,r,i){e.warnOnce(t,n,r,i)},error(t,n,r){e.emitError(t,n,r)}};for(let t of i)try{t(o)}catch(t){e.emitError(`layer-analyzer-error`,t,`[Keymap] Error in layer analyzer:`)}}}}function ml(e){return e.map(t=>({sequence:Mc(t.sequence),command:t.command,attrs:t.attrs,event:t.event,preventDefault:t.preventDefault,fallthrough:t.fallthrough,parsedBinding:fl(t.parsedBinding),sourceTarget:t.sourceTarget,sourceLayerOrder:t.sourceLayerOrder,bindingIndex:t.bindingIndex,hasCommandAtSequence:e.some(e=>e.event===`press`&&e.command!==void 0&&hl(e,t)),hasContinuations:e.some(e=>e.event===`press`&&gl(t,e))}))}function hl(e,t){return e.sequence.length===t.sequence.length&&e.sequence.every((e,n)=>e.match===t.sequence[n]?.match)}function gl(e,t){return e.sequence.length<t.sequence.length&&e.sequence.every((e,n)=>e.match===t.sequence[n]?.match)}function _l(){return{version:-1,notifyVersion:-1,focused:void 0,value:[],targets:new WeakMap}}function vl(){return{plain:_l(),bindings:_l(),metadata:_l(),bindingsAndMetadata:_l()}}function yl(e,t){if(t===void 0)return e.plain;let n=t.includeBindings===!0,r=t.includeMetadata===!0;return n?r?e.bindingsAndMetadata:e.bindings:r?e.metadata:e.plain}function bl(e,t,n){let r=n?e.targets.get(n):e.nullTarget;return r?.version===t?r:void 0}function xl(e,t,n,r){let i={version:t,value:r};n?e.targets.set(n,i):e.nullTarget=i}function Sl(e,t){if(e===t)return!0;if(!e||!t||e.captures.length!==t.captures.length)return!1;for(let n=0;n<e.captures.length;n+=1){let r=e.captures[n],i=t.captures[n];if(!r||!i||r.layer!==i.layer||r.binding!==i.binding||r.index!==i.index||r.parts.length!==i.parts.length)return!1;for(let e=0;e<r.parts.length;e+=1)if(r.parts[e]?.match!==i.parts[e]?.match)return!1;let a=r.patterns??[],o=i.patterns??[];if(a.length!==o.length)return!1;for(let e=0;e<a.length;e+=1){let t=a[e],n=o[e];if(!t||!n||t.name!==n.name||t.values.length!==n.values.length)return!1;for(let e=0;e<t.values.length;e+=1)if(!Object.is(t.values[e],n.values[e]))return!1}}return!0}function Cl(e){let t=e.parts.at(-1);if(!t||e.parts.length<=1)return;let n=e.index-1,r=e.patterns;if(t.patternName){let i=r?.at(-1);i?.name===t.patternName&&(i.values.length>1?(n=e.index,r=[...(r??[]).slice(0,-1),{...i,values:i.values.slice(0,-1),parts:i.parts.slice(0,-1)}]):r=(r??[]).slice(0,-1))}return{layer:e.layer,binding:e.binding,index:n,parts:e.parts.slice(0,-1),patterns:r}}function wl(e){let t=e.captures[0];if(!t||t.parts.length===0)return[];let n=[];for(let r=0;r<t.parts.length;r+=1){let i=t.parts[r];if(!i)continue;let a,o,s=!1,c=!1;for(let t of e.captures){let e=t.parts[r];if(e){if(a===void 0){a=e.display,o=e.tokenName;continue}!s&&a!==e.display&&(s=!0),!c&&o!==e.tokenName&&(c=!0)}}(a===void 0||s)&&(a=Ic(i.stroke)),c&&(o=void 0),n.push(Ac(i.stroke,{display:a,match:i.match,tokenName:o}))}return n}function Tl(e){if(e.isDestroyed)throw Error(`Cannot use a keymap after its host was destroyed`);return e}function El(e,t,n,r,i,a,o={}){let s=vl(),c=-1,l=[],u=()=>Tl(t).getFocusedTarget(),d=()=>Vc(t),f=t=>{let n=e.pending;Sl(n,t)||(e.pending=t,o.onPendingSequenceChanged?.(n,t),fe(),r.queueStateChange())},p=()=>{let t=e.pending;if(!t)return;let n=u(),r=a.getActiveCommandView(n),o=t.captures.filter(t=>e.layers.has(t.layer)&&C(t.layer,n)&&i.matchesConditions(t.layer)&&ee(t.binding,n,r)&&Yc(t,e.patterns));if(o.length===0){f(null);return}return o.length!==t.captures.length&&f({captures:o}),e.pending??void 0},m=()=>{t.isDestroyed||!e.pending||p()},h=()=>!t.isDestroyed&&e.pending!==null,g=()=>{if(c===e.cacheVersion)return l;let t=p(),n=t?wl(t):[];return(!t||T())&&(c=e.cacheVersion,l=n),n},_=()=>{let e=p();if(!e)return!1;let t=e.captures[0];if(!t||t.parts.length<=1)return f(null),!0;let n=[];for(let t of e.captures){let e=Cl(t);e&&n.push(e)}return n.length===0?(f(null),!0):(f({captures:n}),!0)},v=t=>{let n=t?.includeBindings===!0,r=t?.includeMetadata===!0,i=yl(s,t);return i.notifyVersion===e.derivedVersion?i.value:y(i,n,r)},y=(n,r,i)=>{t.isDestroyed&&Tl(t);let o=u(),s=bl(n,e.cacheVersion,o);if(s)return n.notifyVersion=e.derivedVersion,n.version=e.cacheVersion,n.focused=o,n.value=s.value,s.value;let c=a.getActiveCommandView(o),l=p(),d=l?[]:S(o),f=l?re(l.captures,r,i,o,c):A(d,r,i,o,c);return(l?T():w(d))&&(n.version=e.cacheVersion,n.notifyVersion=e.derivedVersion,n.focused=o,n.value=f,xl(n,e.cacheVersion,o,f)),f},b=(e,t)=>{let n=t?.includeBindings===!0,r=t?.includeMetadata===!0,i=u(),o=a.getActiveCommandView(i);return re(e,n,r,i,o)},x=(e,t)=>{let n=t?.includeBindings===!0,r=t?.includeMetadata===!0,i=e===d()?p():void 0,o=a.getActiveCommandView(e);return i?re(i.captures,n,r,e,o):A(S(e),n,r,e,o)},S=n=>e.activeLayersCacheVersion===e.cacheVersion&&e.activeLayersCacheFocused===n?e.activeLayersCache:(e.activeLayersCacheVersion=e.cacheVersion,e.activeLayersCacheFocused=n,e.activeLayersCache=Wc(e.sortedLayers,t,n),e.activeLayersCache),C=(e,n)=>Kc(t,e,n),w=t=>!e.commandResolvers.has()&&e.activeKeyCacheBlockers===0,T=()=>!e.commandResolvers.has()&&e.activeKeyCacheBlockers===0,E=(e,t,n)=>{let r=[];for(let o of e)i.matchesConditions(o)&&a.isBindingVisible(o,t,n)&&r.push(o);return r},ee=(e,t,n)=>i.matchesConditions(e)&&a.isBindingVisible(e,t,n),D=(e,t)=>{let n,r,i=!1,a=!1;for(let o of e){let e=o.sequence[t];if(e){if(n===void 0){n=e.display,r=e.tokenName;continue}!i&&n!==e.display&&(i=!0),!a&&r!==e.tokenName&&(a=!0)}}if(n===void 0||i){let r=e[0]?.sequence[t]?.stroke;n=r?Ic(r):``}return a&&(r=void 0),{display:n,tokenName:r}},O=(e,t,n)=>({sequence:e.sequence,command:e.command,commandAttrs:a.getBindingCommandAttrs(e,t,n),attrs:e.attrs,event:e.event,preventDefault:e.preventDefault,fallthrough:e.fallthrough}),k=(e,t,n)=>e.map(e=>O(e,t,n)),A=(e,t,n,r,a)=>{let o=new Map,s=new Set;for(let n of e)n.root.children.size===0&&n.root.patternChildren.length===0||!i.matchesConditions(n)||(j(n.root.children.values(),o,s,t,r,a),j(n.root.patternChildren,o,s,t,r,a));return oe(o,t,n,r,a)},j=(e,t,n,r,i,a)=>{for(let o of e){let e=o.match;if(!e||n.has(e)||!o.stroke)continue;let s=te(o,r,i,a);if(!s)continue;let c=t.get(e);c?M(c,s,r):t.set(e,ue(o.stroke,s,r)),s.stop&&n.add(e)}},te=(e,t,n,r)=>{if(!(e.children.size>0||e.patternChildren.length>0)){let i=le(ne(e)?E(e.bindings,n,r):e.bindings,n,r);if(!i)return;let a=D(i.bindings,e.depth-1);return{display:a.display,tokenName:a.tokenName,continues:!1,firstBinding:i.bindings[0],commandBinding:i.commandBinding,bindings:t?[...i.bindings]:void 0,stop:i.stop}}let i=E(e.reachableBindings,n,r);if(i.length===0)return;let a=le(e.bindings,n,r),o=D(i,e.depth-1);return{display:o.display,tokenName:o.tokenName,continues:!0,firstBinding:a?.bindings[0],commandBinding:a?.commandBinding,bindings:t&&a?[...a.bindings]:void 0,stop:!0}},ne=t=>{if(e.commandResolvers.has())return!0;for(let e of t.bindings)if(e.matchers.length>0)return!0;return!1},re=(t,n,r,i,a)=>{let o=new Map,s=new Set;return ie($c(t,e.patterns),o,s,n,i,a),oe(o,n,r,i,a)},ie=(e,t,n,r,i,a)=>{let o=new Set;for(let s of e)o.has(s.part.match)||(o.add(s.part.match),ae(s,e,t,n,r,i,a))},ae=(e,t,n,r,i,a,o)=>{let s=e.part.match;if(r.has(s))return;let c=se(e,t,i,a,o);if(!c)return;let l=n.get(s);l?M(l,c,i):n.set(s,ue(e.part.stroke,c,i)),c.stop&&r.add(s)},oe=(e,t,n,r,i)=>{let a=[];for(let o of e.values()){let e=de(o,t,n,r,i);e&&a.push(e)}return a},se=(e,t,n,r,i)=>{let a=t.filter(t=>t.part.match===e.part.match),o=a.filter(e=>e.exact).map(e=>e.binding),s=le(o,r,i),c=a.some(e=>e.continues);if(!c&&!s)return;let l=ce(a);return{display:l.display,tokenName:l.tokenName,continues:c,firstBinding:s?.bindings[0],commandBinding:s?.commandBinding,bindings:n&&s?[...s.bindings]:void 0,stop:c||s?.stop===!0}},ce=e=>{let t,n,r=!1,i=!1;for(let a of e){let e=a.part;if(t===void 0){t=e.display,n=e.tokenName;continue}!r&&t!==e.display&&(r=!0),!i&&n!==e.tokenName&&(i=!0)}let a=e[0]?.part;return(t===void 0||r)&&(t=a?Ic(a.stroke):``),i&&(n=void 0),{display:t,tokenName:n}},le=(e,t,n)=>{let r=[],o;for(let s of e)if(!(!i.matchesConditions(s)||!a.isBindingVisible(s,t,n))&&(r.push(s),s.command!==void 0&&(o??=s,!s.fallthrough)))return{bindings:r,commandBinding:o,stop:!0};if(r.length!==0)return{bindings:r,commandBinding:o,stop:!1}},ue=(e,t,n)=>({stroke:e,display:t.display,tokenName:t.tokenName,continues:t.continues,firstBinding:t.firstBinding,commandBinding:t.commandBinding,bindings:n&&t.bindings?[...t.bindings]:void 0}),M=(e,t,n)=>{if(!e.firstBinding&&t.firstBinding&&(e.firstBinding=t.firstBinding),!e.commandBinding&&t.commandBinding&&(e.commandBinding=t.commandBinding),t.continues&&(e.continues=!0),!(!n||!t.bindings||t.bindings.length===0)){if(!e.bindings){e.bindings=[...t.bindings];return}e.bindings.push(...t.bindings)}},de=(e,t,n,r,i)=>{if(!e.commandBinding&&!e.continues)return;let o={stroke:kc(e.stroke),display:e.display,continues:e.continues};if(e.tokenName&&(o.tokenName=e.tokenName),e.commandBinding&&(o.command=e.commandBinding.command),t&&e.bindings&&e.bindings.length>0&&(o.bindings=e.bindings.length===1?[O(e.bindings[0],r,i)]:k(e.bindings,r,i)),n){e.firstBinding?.attrs&&(o.bindingAttrs=e.firstBinding.attrs);let t=e.commandBinding?a.getBindingCommandAttrs(e.commandBinding,r,i):void 0;t&&(o.commandAttrs=t)}return o},fe=()=>{n.has(`pendingSequence`)&&n.emit(`pendingSequence`,e.pending?wl(e.pending):[])};return{getFocusedTarget:u,getFocusedTargetIfAvailable:d,setPendingSequence:f,ensureValidPendingSequence:p,revalidatePendingSequenceIfNeeded:m,hasPendingSequenceState:h,getPendingSequence:g,popPendingSequence:_,getActiveKeys:v,getActiveKeysForCaptures:b,getActiveKeysForFocused:x,getActiveLayers:S,isLayerActiveForFocused:C,collectSequencePartsFromPending:wl,collectMatchingBindings:E,collectActiveBindings:k}}var Dl=new Set([`name`,`run`,`fields`,`attrs`,`rejectedResult`]),Ol=new Set([`key`,`cmd`,`event`,`preventDefault`,`fallthrough`]),kl=new Set([`target`,`targetMode`,`priority`,`bindings`,`commands`]);function Al(e){if(e===void 0||typeof e==`function`)return e;let t=e.trim();if(!t)throw Error(`Invalid keymap command: command cannot be empty`);return t}function jl(e){let t=e.trim();if(!t)throw Error(`Invalid keymap command name: name cannot be empty`);if(/\s/.test(t))throw Error(`Invalid keymap command name "${e}": command names cannot contain whitespace`);return t}function Ml(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function Nl(e){let t=[],n=new Map;for(let r of e.layers)for(let e of r.commands){let i={layer:r,commandState:e};t.push(i),Ml(n,e.command.name,i)}return{entries:t,chainsByName:n}}function Pl(e,t,n){let r=[],i=[],a=new Map,o=new Map;for(let s of e)if(s.commands.length!==0&&!(n&&!t.matchesConditions(s)))for(let e of s.commands){if(!t.matchesConditions(e))continue;let n={layer:s,commandState:e};r.push(n),Ml(o,e.command.name,n),a.has(e.command.name)||(a.set(e.command.name,n),i.push(n))}return{layers:e,entries:r,reachable:i,reachableByName:a,chainsByName:o}}function Fl(e,t,n,r){return(e.activeLayersCacheVersion!==e.cacheVersion||e.activeLayersCacheFocused!==r)&&(e.activeLayersCacheVersion=e.cacheVersion,e.activeLayersCacheFocused=r,e.activeLayersCache=Wc(e.sortedLayers,t,r)),Pl(e.activeLayersCache,n,!0)}function Il(e,t,n,r){if(Object.prototype.hasOwnProperty.call(e,t)&&!Object.is(e[t],n))throw Error(`Conflicting keymap requirement for "${t}" from ${r}`);e[t]=n}function Ll(e,t,n,r){if(Object.prototype.hasOwnProperty.call(e,t)&&!Object.is(e[t],n))throw Error(`Conflicting keymap attribute for "${t}" from ${r}`);e[t]=n}function Rl(e){let t=`field ${e.fieldName}`;return{require(n,r){Il(e.requirements,n,r,t)},attr(n,r){if(!e.attrs)throw Error(`Keymap ${t} cannot publish attrs`);Ll(e.attrs,n,r,t)},activeWhen(n){e.matchers.push(e.conditions.buildRuntimeMatcher(n,t))}}}function zl(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Bl(e,t){return e instanceof Error&&e.message?e.message:t}function Vl(e){return!e||typeof e!=`object`&&typeof e!=`function`?!1:typeof e.then==`function`}function Hl(e,t){let n=t?.deep===!0,r=t?.freeze===!0,i=t?.preserveNonPlainObjects===!0;if(Array.isArray(e)){let i=n?e.map(e=>Hl(e,t)):[...e];return r?Object.freeze(i):i}if(e&&typeof e==`object`){if(i&&!zl(e))return e;let a={};for(let[r,i]of Object.entries(e))a[r]=n?Hl(i,t):i;return r?Object.freeze(a):a}return e}var Ul=[`name`],Wl=Object.freeze({}),Gl=new WeakMap;function Kl(e,t,n,r,i){let a=-1,o,s=-1,c,l,u=-1,d,f,p=-1,m,h=-1,g=new Map,_=t=>Jl({commands:t,commandFields:e.commandFields,conditions:r,onError:(e,t,r)=>{n.emitError(e,t,r)}}),v=t=>oe(()=>e.commandResolvers.prepend(t),t),y=t=>oe(()=>e.commandResolvers.append(t),t),b=()=>{e.commandResolvers.has()&&n.runWithStateChangeBatch(()=>{e.commandResolvers.clear(),i.onCommandResolversChanged(),n.queueStateChange()})},x=e=>me(e).map(e=>ql(e.commandState)),S=e=>{let t=pe(e),n=me(e,t);if(n.length===0)return[];let r=n.map(e=>({entry:e,command:ql(e.commandState),commandAttrs:e.commandState.attrs,bindings:[]})),i=new Map;for(let[e,t]of r.entries()){let n=i.get(t.command.name);n?n.push(e):i.set(t.command.name,[e])}return i.size>0&&he(r,i,t),r.map(e=>({command:e.command,bindings:e.bindings}))},C=t=>{if(t.visibility===`registered`&&u===e.derivedVersion&&d===t.commands&&f)return f;let n=new Map;for(let e of t.commands)n.has(e)||n.set(e,[]);return n.size===0?n:(ge(n,pe(t)),t.visibility===`registered`&&(u=e.derivedVersion,d=t.commands,f=n),n)},w=(e,t,n)=>{let r=j(t);if(n){let i=[],a=r.chainsByName.get(e);if(a)for(let e of a)i.push({target:e.layer.target,command:e.commandState.command,attrs:e.commandState.attrs,payload:n.payload});let o=xe(e,t,{mode:`active`,execution:n});return o.resolved&&i.push(o.resolved),{entries:i.length>0?i:void 0,hadError:o.hadError}}let i=[];for(let t of r.chainsByName.get(e)??[])i.push({target:t.layer.target,command:t.commandState.command,attrs:t.commandState.attrs});let a=xe(e,t,{mode:`active`});return a.resolved&&i.push(a.resolved),{entries:i.length>0?i:void 0,hadError:a.hadError}},T=t=>{if(h!==e.derivedVersion&&(h=e.derivedVersion,g=new Map),g.has(t))return g.get(t)??void 0;let n=ue(le(t));return g.set(t,n??null),n},E=(e,t)=>ue(j(t).chainsByName.get(e)),ee=(e,t)=>xe(e,null,{mode:`registered`,execution:t}),D=(e,t,n)=>xe(e,t,{mode:`active`,execution:n}),O=(e,t)=>se(e,t)?.command,k=e=>ce(e)?.commandState.command,A=(e,n,i)=>{let a=te().chainsByName.get(e);if(!a||a.length===0)return;let o,s;for(let e of a){if(!Kc(t,e.layer,n)){o??=e;continue}(!r.matchesConditions(e.layer)||!r.matchesConditions(e.commandState))&&(s??=e)}let c=s??o;if(c)return{reason:s?`disabled`:`inactive`,command:i?c.commandState.command:void 0}},j=n=>{if(s===e.derivedVersion&&c===n&&l)return l;let i=Fl(e,t,r,n);return ne()&&(s=e.derivedVersion,c=n,l=i),i},te=()=>a===e.derivedVersion&&o?o:(a=e.derivedVersion,o=Nl(e),o),ne=()=>e.activeCommandViewCacheBlockers===0,re=(e,t,n)=>e.command===void 0||e.run?!0:typeof e.command==`string`?n.reachableByName.has(e.command)?!0:M(e.command,t,`active`)!==void 0:!1,ie=(e,t,n)=>{if(typeof e.command!=`string`)return;let r=n.reachableByName.get(e.command);return r?r.commandState.attrs:M(e.command,t,`active`)?.attrs},ae=(e,n)=>{if(n?.some(t=>t.command.name===e)||te().chainsByName.has(e))return`resolved`;let r=xe(e,Vc(t));return r.resolved||r.hadError?r.resolved?`resolved`:`error`:`unresolved`},oe=(t,r)=>n.runWithStateChangeBatch(()=>{let a=t();return i.onCommandResolversChanged(),n.queueStateChange(),()=>{n.runWithStateChangeBatch(()=>{a(),!e.commandResolvers.values().includes(r)&&(i.onCommandResolversChanged(),n.queueStateChange())})}}),se=(e,t)=>{let n=j(t).reachableByName.get(e);return n?{target:n.layer.target,command:n.commandState.command,attrs:n.commandState.attrs}:M(e,t,`active`)},ce=e=>le(e)?.[0],le=t=>{let n=[];for(let r of e.sortedLayers)for(let e of r.commands)e.command.name===t&&n.push({layer:r,commandState:e});return n.length>0?n:void 0},ue=e=>{if(e?.length)return e.map(e=>({target:e.layer.target,command:e.commandState.command,attrs:e.commandState.attrs}))},M=(e,t,n)=>xe(e,t,{mode:n}).resolved,de=()=>te().entries,fe=()=>{if(p===e.derivedVersion&&m)return m;let t=new Map;for(let n of e.layers)for(let e of n.bindings){if(typeof e.command!=`string`)continue;let n=t.get(e.command);n?n.push(e):t.set(e.command,[e])}return p=e.derivedVersion,m=t,t},pe=e=>{let n=e?.visibility??`reachable`,r=e&&Object.prototype.hasOwnProperty.call(e,`focused`)?e.focused??null:Vc(t);return n===`registered`?{visibility:n,focused:r}:{visibility:n,focused:r,activeView:j(r)}},me=(e,t=pe(e))=>{let r;return r=t.visibility===`registered`?de():t.visibility===`active`?t.activeView?.entries??[]:t.activeView?.reachable??[],$l({entries:r,query:e,getCommand:e=>ql(e),onFilterError:e=>{n.emitError(`command-query-filter-error`,e,`[Keymap] Error in command query filter:`)}})},he=(e,t,n)=>{_e(n,n=>{ve(e,t,n)})},ge=(e,t)=>{if(t.visibility===`registered`){let t=fe();for(let[n,r]of e){let e=te().chainsByName.get(n)?.[0]?.commandState.attrs;for(let i of t.get(n)??[])r.push(be(i,e))}return}_e(t,n=>{ye(e,n,t)})},_e=(t,n)=>{if(t.visibility===`registered`){for(let t of e.layers)for(let e of t.bindings)n(e);return}let i=t.activeView;if(i){for(let e of i.layers)if(!(e.bindings.length===0||!r.matchesConditions(e)))for(let a of e.bindings)r.matchesConditions(a)&&re(a,t.focused,i)&&n(a)}},ve=(e,t,n)=>{if(typeof n.command!=`string`)return;let r=t.get(n.command);if(!(!r||r.length===0))for(let t of r){let r=e[t];r&&r.bindings.push(be(n,r.commandAttrs))}},ye=(e,t,n)=>{if(typeof t.command!=`string`)return;let r=e.get(t.command);r&&r.push(be(t,N(t,n)))},be=(e,t)=>({sequence:e.sequence,command:e.command,commandAttrs:t,attrs:e.attrs,event:e.event,preventDefault:e.preventDefault,fallthrough:e.fallthrough}),N=(e,t)=>{if(typeof e.command!=`string`)return;if(t.visibility===`registered`)return te().chainsByName.get(e.command)?.[0]?.commandState.attrs;let n=t.activeView;if(n)return ie(e,t.focused,n)},xe=(t,r,i)=>{let a=i?.mode??`active`,o=i?.execution??{input:t},s=Yl(t,e.commandResolvers.values(),()=>we(r,a,o),e=>{n.emitError(`command-resolver-error`,e,`[Keymap] Error in command resolver for "${t}":`)}),c=s.resolved;if(c){let e=Ce(c.command.name,r,a);e?.commandState.command===c.command&&c.target===void 0&&(c={...c,target:e.layer.target},s.resolved=c)}if(c&&!c.attrs){let e=Se(c.command.name,r,a)??Ql(c.command);e&&(s.resolved={...c,attrs:e})}return s},Se=(e,t,n)=>n===`registered`?ce(e)?.commandState.attrs:j(t).reachableByName.get(e)?.commandState.attrs,Ce=(e,t,n)=>n===`registered`?ce(e):j(t).reachableByName.get(e),we=(e,t,n)=>{let r=n.input,i=n.payload;return{context:{get input(){return r},get payload(){return i},setInput(e){r=e},setPayload(e){i=e},getCommand:n=>t===`registered`?k(n):O(n,e)},getExecutionFields(){return{input:r,payload:i}}}};return{normalizeCommands:_,prependCommandResolver:v,appendCommandResolver:y,clearCommandResolvers:b,getCommands:x,getCommandEntries:S,getCommandBindings:C,getResolvedCommandChain:w,getRegisteredResolvedEntries:T,getActiveRegisteredResolvedEntries:E,resolveRegisteredResolverFallback:ee,resolveActiveResolverFallback:D,getTopCommand:O,getDispatchUnavailableCommandState:A,getActiveCommandView:j,isBindingVisible:re,getBindingCommandAttrs:ie,getCommandResolutionStatus:ae}}function ql(e){return e.command}function Jl(e){let t=[],n=new Set;for(let r of e.commands)try{let i={},a=[],o=jl(r.name),s=Xl(r),c={};if(n.has(o)){e.onError(`duplicate-command`,{command:o},`Duplicate keymap command "${o}" in the same layer`);continue}r.name=o;for(let[t,n]of Object.entries(s)){if(n===void 0)continue;let r=e.commandFields.get(t);r&&r(n,Rl({fieldName:t,conditions:e.conditions,requirements:i,matchers:a,attrs:c}))}let l={command:r,fields:s,attrs:Object.keys(c).length===0?void 0:c,requires:Object.entries(i),matchers:a};n.add(l.command.name),t.push(l)}catch(t){e.onError(`register-command-failed`,t,Bl(t,`Failed to register keymap command "${String(r.name)}"`));continue}return t}function Yl(e,t,n,r){if(t.length===0)return{hadError:!1};let i=!1;for(let a of t){let t,o=n();try{t=a(e,o.context)}catch(e){i=!0,r(e);continue}if(t)return{hadError:i,resolved:Zl(t,o.getExecutionFields())}}return{hadError:i}}function Xl(e){let t={};for(let[n,r]of Object.entries(e))!Dl.has(n)&&r!==void 0&&(t[n]=r);return Object.keys(t).length===0?Wl:t}function Zl(e,t){return{command:e,input:t.input,payload:t.payload}}function Ql(e){let t=Xl(e);return t===Wl?void 0:t}function $l(e){let t=e.query?.namespace,n=eu(e.query?.limit);if(n===0)return[];let r=e.query?.search?.trim().toLowerCase()??``,i=Ul;e.query?.searchIn&&e.query.searchIn.length>0&&(i=e.query.searchIn);let a=e.query?.filter,o,s,c;if(typeof a==`function`)s=a;else if(a){let e=Object.entries(a),t=[];for(let[n,r]of e){if(n===`name`){if(typeof r==`string`){c=new Set([r]);continue}if(Array.isArray(r)){let e=new Set;for(let t of r)typeof t==`string`&&e.add(t);c=e;continue}}t.push([n,r])}o=t.length>0?t:void 0}let l=[];for(let a of e.entries){let u=a.commandState;if(nu(u,t)&&tu(u,r,i)&&!(c&&!c.has(u.command.name))&&ru(u,o,e)){if(s){let t=!1;try{t=s(e.getCommand(u))}catch(t){e.onFilterError(t);continue}if(!t)continue}if(l.push(a),n!==void 0&&l.length>=n)break}}return l}function eu(e){if(e===void 0)return;let t=Math.floor(Number(e));return!Number.isFinite(t)||t<=0?0:t}function tu(e,t,n){if(!t)return!0;for(let r of n)if(iu(e,r,t))return!0;return!1}function nu(e,t){if(t===void 0)return!0;let n=e.fields;return Object.prototype.hasOwnProperty.call(n,`namespace`)?du(n.namespace,t):!1}function ru(e,t,n){if(!t)return!0;for(let[r,i]of t)if(!cu(e,r,i,n))return!1;return!0}function iu(e,t,n){return au(e,t)?.includes(n)===!0}function au(e,t){let n=Gl.get(e);if(n||(n=new Map,Gl.set(e,n)),n.has(t))return n.get(t);let r=e.fields,i=e.attrs,a;t===`name`?a=e.command.name:Object.prototype.hasOwnProperty.call(r,t)?a=r[t]:i&&Object.prototype.hasOwnProperty.call(i,t)&&(a=i[t]);let o=ou(a);return n.set(t,o),o}function ou(e){if(Array.isArray(e)){let t=[];for(let n of e){let e=ou(n);e!==void 0&&t.push(e)}return t.length>0?t.join(`\0`):void 0}if(typeof e==`string`)return e.toLowerCase();if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e).toLowerCase()}function su(e,t,n,r){try{return e(t,n)}catch(e){return r(e),!1}}function cu(e,t,n,r){return typeof n==`function`?lu(e,t,n,r):uu(e,t,n)}function lu(e,t,n,r){let i=e.command,a=e.fields,o=e.attrs,s,c=!1,l=()=>s??=r.getCommand(e);return t===`name`&&(c=!0,su(n,i.name,l(),r.onFilterError))||Object.prototype.hasOwnProperty.call(a,t)&&(c=!0,su(n,a[t],l(),r.onFilterError))||o&&Object.prototype.hasOwnProperty.call(o,t)&&(c=!0,su(n,o[t],l(),r.onFilterError))?!0:!c&&su(n,void 0,l(),r.onFilterError)}function uu(e,t,n){let r=e.command,i=e.fields,a=e.attrs;return t===`name`&&du(r.name,n)||Object.prototype.hasOwnProperty.call(i,t)&&du(i[t],n)?!0:!!a&&Object.prototype.hasOwnProperty.call(a,t)&&du(a[t],n)}function du(e,t){return Array.isArray(t)?t.some(t=>fu(e,t)):fu(e,t)}function fu(e,t){return Array.isArray(e)?e.some(e=>fu(e,t)):Object.is(e,t)}function pu(e,t,n,r,i){let a=(e,t,n,r,a,o)=>({keymap:i.keymap,event:e,focused:t,target:n,data:r,input:a,payload:o}),o=(t,n,r,i)=>{let a=typeof n==`function`?void 0:n,o=typeof n==`function`?n:n.run,s=i?a:void 0,c;try{c=o(a?{...r,command:a}:r)}catch(n){return e.emitError(`command-execution-error`,n,`[Keymap] Error running command "${t}":`),{status:`error`,result:s?{ok:!1,reason:`error`,command:s}:{ok:!1,reason:`error`}}}if(Vl(c))return c.catch(n=>{e.emitError(`async-command-error`,n,`[Keymap] Async error in command "${t}":`)}),{status:`handled`,result:s?{ok:!0,command:s}:{ok:!0}};if(mu(c)){let e=c;return(!c.ok&&c.reason!==`not-found`&&i&&a&&!c.command||c.ok&&i&&a&&!c.command)&&(e={...c,command:a}),{status:c.ok?`handled`:`rejected`,result:e}}return c===!1?{status:`rejected`,result:s?{ok:!1,reason:`rejected`,command:s}:{ok:!1,reason:`rejected`}}:{status:`handled`,result:s?{ok:!0,command:s}:{ok:!0}}},s=(e,t,n,r,i,s,c,l)=>{let u;for(let d of t??[]){let t=o(e,d.command,a(n,r,i??d.target??null,s,e,c),l);if(t.status===`handled`||t.status===`error`)return[t.result,u];u=t.result}return[void 0,u]},c=(e,c,l)=>{let u;try{u=Al(e)}catch{return{ok:!1,reason:`invalid-args`}}if(typeof u!=`string`)return{ok:!1,reason:`not-found`};let d=c?.includeCommand===!0,f=c?.focused??n.getFocusedTargetIfAvailable(),p=c?.event??i.createCommandEvent(),m=t.getReadonlyData(),h=c?.payload,g=l===`registered`?r.getRegisteredResolvedEntries(u):r.getActiveRegisteredResolvedEntries(u,f),[_,v]=s(u,g,p,f,c?.target,m,h,d);if(_)return _;let y=v,b=l===`registered`?r.resolveRegisteredResolverFallback(u,{input:u,payload:h}):r.resolveActiveResolverFallback(u,f,{input:u,payload:h});if(b.resolved){let e=o(u,b.resolved.command,a(p,f,c?.target??b.resolved.target??null,m,b.resolved.input??u,b.resolved.payload),d);if(e.status===`handled`||e.status===`error`)return e.result;y=e.result}if(b.hadError)return{ok:!1,reason:`error`};if(l===`active`){let e=r.getDispatchUnavailableCommandState(u,f,d);if(e)return e.command?{ok:!1,reason:e.reason,command:e.command}:{ok:!1,reason:e.reason}}return y??{ok:!1,reason:`not-found`}};return{runCommand(e,t){return c(e,t,`registered`)},dispatchCommand(e,t){return c(e,t,`active`)},runBinding(e,n,i,s,c){let l=t.getReadonlyData();if(n.run)return o(typeof n.command==`string`?n.command:`<function>`,n.run,a(i,s,e.target??null,l,typeof n.command==`string`?n.command:`<function>`,c),!1).status!==`rejected`&&(hu(n,i),!0);if(typeof n.command!=`string`)return!1;let u=r.getResolvedCommandChain(n.command,s,c===void 0?void 0:{input:n.command,payload:c}).entries;for(let t of u??[])if(o(n.command,t.command,a(i,s,t.target??e.target??null,l,t.input??n.command,t.payload),!1).status!==`rejected`)return hu(n,i),!0;return!1}}}function mu(e){return typeof e==`object`&&!!e&&`ok`in e}function hu(e,t){e.preventDefault&&(t.preventDefault(),t.stopPropagation())}var gu=Object.freeze({}),_u=[],vu=[];function yu(e){if(Object.keys(e).length!==0)return Hl(e,{freeze:!0})}function bu(e,t,n,r){let i=t=>Eu(t,e.bindingParsers.values(),{tokens:e.tokens,patterns:e.patterns,layer:gu,parseObjectKey:(e,t)=>c(e,t)}),a=t=>{if(typeof t!=`string`)return[c(t)];let n=Tu(t,e.bindingParsers.values(),{tokens:e.tokens,patterns:e.patterns,layer:gu,parseObjectKey:(e,t)=>c(e,t)});for(let e of n.unknownTokens)r.warnUnknownToken(e,t);return n.unknownTokens.length>0?[]:n.parts},o=(e,t)=>Lc(a(e),t),s=(i,a,o,s,d)=>{let f=[],p=!1,m=e.bindingExpanders.values(),h=e.bindingParsers.values(),g=e.bindingFields,_=e.disambiguationResolvers.has(),v=r.warnUnknownField,y=r.warnUnknownToken;for(let[r,b]of i.entries()){let i;try{i=Cu(b.key,m,{layer:d})}catch(e){t.emitError(`binding-expand-error`,e,Bl(e,`Failed to expand keymap binding`));continue}for(let m of i){let i=m.key,x;try{x=typeof i==`string`?Tu(i,h,{tokens:a,patterns:e.patterns,layer:d,parseObjectKey:(e,t)=>c(e,t)}):{parts:[c(i)],usedTokens:[],unknownTokens:[],hasTokenBindings:!1},x=wu(x,m)}catch(e){t.emitError(`binding-parse-error`,e,Bl(e,`Failed to parse keymap binding`));continue}let S=x.parts;p||=x.hasTokenBindings;for(let e of x.unknownTokens)y(e,typeof i==`string`?i:String(i.name));if(!(x.unknownTokens.length>0))for(let i of u(b,S,a,h,d))try{let t=l(i.event),a=i.sequence,c={},u={},d=[];for(let e in i){if(e===`sequence`||Ol.has(e))continue;let t=i[e];if(t===void 0)continue;let r=g.get(e);if(!r){v(`binding`,e);continue}r(t,Rl({fieldName:e,conditions:n,requirements:c,matchers:d,attrs:u}))}let p=Object.keys(u).length>0?yu(u):void 0,m=Al(i.cmd),h={binding:b,sequence:a,command:m,event:t,parsedBinding:fl(i),sourceTarget:o,sourceLayerOrder:s,bindingIndex:r,requires:Object.keys(c).length>0?Object.entries(c):_u,matchers:d.length>0?d:vu,preventDefault:i.preventDefault!==!1,fallthrough:i.fallthrough??!1};if(p&&(h.attrs=p),typeof m==`function`&&(h.run=m),a.length===0)continue;if(t===`release`&&a.length>1)throw Error(`Keymap release bindings only support a single key stroke`);let y=a.at(-1);if(y?.patternName){let t=e.patterns.get(y.patternName);if(t&&t.max!==t.min)throw Error(`Keymap unbounded sequence patterns must be followed by a concrete continuation`)}t===`press`&&!_&&Su(f,h),f.push(h)}catch(e){t.emitError(`binding-compile-error`,e,Bl(e,`Failed to compile keymap binding`))}}}return{bindings:f,hasTokenBindings:p}},c=(e,t)=>Ac(e,t),l=e=>{if(e===void 0||e===`press`)return`press`;if(e===`release`)return`release`;throw Error(`Invalid keymap binding event "${String(e)}": expected "press" or "release"`)},u=(n,r,i,a,o)=>{let s=e.bindingTransformers.values();if(s.length===0)return[{...n,sequence:Mc(r)}];let l={...n,sequence:Mc(r)},u=[],d=!0,f=o??gu;for(let n of s)try{n(l,{layer:f,parseKey:t=>Eu(t,a,{tokens:i,patterns:e.patterns,layer:f,parseObjectKey:(e,t)=>c(e,t)}),add:e=>{u.push(fl(e))},skipOriginal:()=>{d=!1}})}catch(e){t.emitError(`binding-transformer-error`,e,`[Keymap] Error in binding transformer:`)}return d?u.length===0?[l]:[l,...u]:u};return{parseTokenKey:i,parseKeySequence:a,formatKey:o,compileBindings:s}}function xu(e,t){if(e.length>=t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]?.match!==t[n]?.match)return!1;return!0}function Su(e,t){for(let n of e)if(n.event===`press`&&(n.command!==void 0&&xu(n.sequence,t.sequence)||t.command!==void 0&&xu(t.sequence,n.sequence)))throw Error(`Keymap bindings cannot use the same sequence as both an exact match and a prefix in the same layer`)}function Cu(e,t,n){if(typeof e!=`string`||t.length===0)return[{key:e}];let r=n?.layer??gu,i=[{key:e}];for(let e of t){let t=[];for(let n of i){let i=e({input:n.key,displays:n.displays,layer:r});if(!i){t.push(n);continue}if(i.length===0)throw Error(`Keymap binding expander must return at least one key sequence for "${n.key}"`);for(let e of i){if(!e||typeof e!=`object`||Array.isArray(e)||typeof e.key!=`string`)throw Error(`Keymap binding expander must return expansion objects with string keys for "${n.key}"`);if(e.displays!==void 0){if(!Array.isArray(e.displays))throw Error(`Keymap binding expander displays must be an array of strings for "${n.key}"`);for(let t of e.displays)if(typeof t!=`string`)throw Error(`Keymap binding expander displays must be an array of strings for "${n.key}"`)}t.push(e)}}i=t}return i}function wu(e,t){if(!t.displays)return e;if(t.displays.length!==e.parts.length)throw Error(`Keymap binding expansion displays length must match parsed sequence length for "${String(t.key)}"`);return{...e,parts:e.parts.map((e,n)=>({...e,display:t.displays[n]}))}}function Tu(e,t,n){if(e.length===0)throw Error(`Invalid key sequence: sequence cannot be empty`);if(t.length===0)throw Error(`No keymap binding parsers are registered`);let r=n.tokens??new Map,i=n.patterns??new Map,a=n.layer??gu,o=n.parseObjectKey,s=[],c=new Set,l=new Set,u=0;for(;u<e.length;){let n=!1;for(let d of t){let t=d({input:e,index:u,layer:a,tokens:r,patterns:i,normalizeTokenName:Ec,createMatch:Fc,parseObjectKey:o});if(t){if(t.nextIndex<=u||t.nextIndex>e.length)throw Error(`Keymap binding parser must advance the input for "${e}" at index ${u}`);s.push(...t.parts);for(let e of t.usedTokens??[])c.add(e);for(let e of t.unknownTokens??[])l.add(e);u=t.nextIndex,n=!0;break}}if(!n)throw Error(`No keymap binding parser handled input at index ${u} in "${e}"`)}return{parts:s,usedTokens:[...c],unknownTokens:[...l],hasTokenBindings:c.size>0||l.size>0}}function Eu(e,t,n){if(typeof e!=`string`)return n.parseObjectKey(e);let{parts:r}=Tu(e,t,n),[i]=r;if(!i||r.length!==1)throw Error(`Invalid key "${String(e)}": expected a single key stroke`);return i}function Du(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.get==`function`&&typeof t.subscribe==`function`}function Ou(e,t){let n=e=>e.requires.length===0&&e.matchers.length===0,r=e=>{try{return e.match()}catch(n){return t.emitError(`runtime-matcher-error`,n,`[Keymap] Error evaluating runtime matcher from ${e.source}:`),!1}},i=e=>{if(e.matchers.length===0)return!0;if(e.matchers.length===1){let[t]=e.matchers;return!t||r(t)}for(let t of e.matchers)if(!r(t))return!1;return!0},a=t=>{if(t.length===0)return!0;for(let[n,r]of t)if(!Object.is(e.data[n],r))return!1;return!0};return{buildRuntimeMatcher(e,t){if(typeof e==`function`)return{source:t,match:e};if(Du(e))return{source:t,match:()=>e.get(),subscribe:t=>e.subscribe(t)};throw Error(`Keymap ${t} expected a function or a reactive matcher`)},matchesConditions:e=>n(e)||a(e.requires)&&i(e)}}var ku=Symbol(`keymap-disambiguation-decision`),Au=Symbol(`keymap-deferred-disambiguation-decision`);function ju(e,t){return{[ku]:!0,action:e,handler:t}}function Mu(e){return{[Au]:!0,action:e}}function Nu(e){return!!e&&typeof e==`object`&&e[ku]===!0}function Pu(e){return!!e&&typeof e==`object`&&e[Au]===!0}function Fu(e,t){return t.aborted?Promise.resolve(!1):new Promise(n=>{let r=setTimeout(()=>{t.removeEventListener(`abort`,i),n(!0)},Math.max(0,e)),i=()=>{clearTimeout(r),t.removeEventListener(`abort`,i),n(!1)};t.addEventListener(`abort`,i,{once:!0})})}function Iu(e,t,n,r){let i=e.get(n);if(i)try{return i.matcher(r)}catch(e){t.emitError(`sequence-pattern-match-error`,e,`[Keymap] Error matching sequence pattern "${i.name}":`);return}}function Lu(e,t,n,r){let i=e.get(n)?.payloadKey??n;return{...Ac({name:t.name,ctrl:t.ctrl,shift:t.shift,meta:t.meta,super:t.super??!1,hyper:t.hyper||void 0},{display:r.display??String(r.value??t.name)}),patternName:n,payloadKey:i}}function Ru(e,t,n){if(!n?.patterns||n.patterns.length===0)return;let r={},i=!1;for(let a of n.patterns){let n=e.get(a.name),o;try{o=n?.finalize?n.finalize(a.values):a.values.length===1?a.values[0]:[...a.values]}catch(e){t.emitError(`sequence-pattern-finalize-error`,e,`[Keymap] Error finalizing sequence pattern "${a.name}":`);continue}let s=r[a.payloadKey];s===void 0?(r[a.payloadKey]=o,i=!0):Array.isArray(s)?s.push(o):r[a.payloadKey]=[s,o]}return i?r:void 0}function zu(e,t,n,r,i,a,o,s,c,l){let u={resolveKey:e=>o.parseTokenKey(e).match},d=null,f=0;function p(t,n,r){if(t===`key`){let t=r;return e.keyHooks.register(n,{priority:t?.priority??0,release:t?.release??!1})}if(t===`key:after`){let t=r;return e.keyAfterHooks.register(n,{priority:t?.priority??0,release:t?.release??!1})}let i=r;return e.rawHooks.register(n,{priority:i?.priority??0})}function m(t){return e.eventMatchResolvers.prepend(t)}function h(t){return e.eventMatchResolvers.append(t)}function g(){e.eventMatchResolvers.clear()}function _(t){return ae(()=>e.disambiguationResolvers.prepend(t),t)}function v(t){return ae(()=>e.disambiguationResolvers.append(t),t)}function y(){e.disambiguationResolvers.has()&&t.runWithStateChangeBatch(()=>{e.disambiguationResolvers.clear(),c.recompileBindings()})}function b(e,t){d&&be()}function x(n){let r=e.rawHooks.entries();if(r.length===0)return!1;let i=!1,a={sequence:n,stop(){i=!0}};for(let e of r){try{e.listener(a)}catch(e){t.emitError(`raw-intercept-error`,e,`[Keymap] Error in raw intercept listener:`)}if(i)return!0}return!1}function S(e,t){return{sequence:Mc(e.sequence),command:e.command,commandAttrs:s.getBindingCommandAttrs(e,t,s.getActiveCommandView(t)),attrs:e.attrs,event:e.event,preventDefault:e.preventDefault,fallthrough:e.fallthrough,sourceLayerOrder:e.sourceLayerOrder,bindingIndex:e.bindingIndex}}function C(e){l.has(`dispatch`)&&l.emit(`dispatch`,e)}function w(e,t,n,r){l.has(`dispatch`)&&C({phase:e,event:n.event,focused:r,layer:{order:t.order,priority:t.priority,target:t.target,targetMode:t.targetMode},binding:S(n,r),sequence:Mc(n.sequence),command:n.command})}function T(e,t,n){if(!l.has(`dispatch`))return;let i=t[0],a=t.length>0?r.collectSequencePartsFromPending({captures:t}):[];C({phase:e,event:`press`,focused:n,layer:i?{order:i.layer.order,priority:i.layer.priority,target:i.layer.target,targetMode:i.layer.targetMode}:void 0,sequence:a})}function E(t){let n=e.keyAfterHooks.entries();for(let e of n)if(e.release===t)return n}function ee(e){return e.sequence?Mc(e.sequence):e.captures?r.collectSequencePartsFromPending({captures:e.captures}):[]}function D(e,t){return{handled:e!==`sequence-miss`,reason:e,captures:t}}function O(e,t){return{handled:t,reason:t?`binding-handled`:`binding-rejected`,sequence:e.sequence}}function k(e,t){return t.handled||e.reason===`no-match`?t:e}function A(e,i,a,o,s){let c={event:i,eventType:a?`release`:`press`,focused:o,handled:s.handled,reason:s.reason,sequence:ee(s),pendingSequence:r.getPendingSequence(),setData:(e,t)=>{n.setData(e,t)},getData:e=>n.getData(e),consume:e=>{let t=e?.preventDefault??!0,n=e?.stopPropagation??!0;t&&i.preventDefault(),n&&i.stopPropagation()}};for(let n of e)if(n.release===a)try{n.listener(c)}catch(e){t.emitError(`key-after-intercept-error`,e,`[Keymap] Error in key:after intercept listener:`)}}function j(){return{handled:!1,reason:`no-match`}}function te(e){e.preventDefault(),e.stopPropagation()}function ne(e,t,n,i){r.setPendingSequence({captures:t});let a=D(`sequence-pending`,t);return T(e,t,n),te(i),a}function re(e,t,n,i){let a=D(e,t);return T(`sequence-clear`,t,n),r.setPendingSequence(null),te(i),a}function ie(i,a){a||be();let o=E(a),s=o?r.getFocusedTarget():null,c=e.keyHooks.entries(),l={event:i,setData:(e,t)=>{n.setData(e,t)},getData:e=>n.getData(e),consume:e=>{let t=e?.preventDefault??!0,n=e?.stopPropagation??!0;t&&i.preventDefault(),n&&i.stopPropagation()}};for(let e of c)if(e.release===a){try{e.listener(l)}catch(e){t.emitError(`key-intercept-error`,e,`[Keymap] Error in key intercept listener:`)}if(i.propagationStopped){o&&A(o,i,a,s,{handled:!0,reason:`intercept-consumed`,sequence:[]});return}}if(a){let e=oe(i);o&&A(o,i,a,s,e);return}let u=se(i);o&&A(o,i,a,s,u)}function ae(n,r){return t.runWithStateChangeBatch(()=>{let i=e.disambiguationResolvers.has(),a=n();return!i&&e.disambiguationResolvers.has()&&c.recompileBindings(),()=>{t.runWithStateChangeBatch(()=>{let t=e.disambiguationResolvers.has();a(),!e.disambiguationResolvers.values().includes(r)&&t&&!e.disambiguationResolvers.has()&&c.recompileBindings()})}})}function oe(e){let t=r.getFocusedTarget(),n=r.getActiveLayers(t),a=Te(e),o=j();for(let r of a)layerLoop:for(let a of n){if(a.bindings.length===0||!i.matchesConditions(a))continue;let n=Ee(a,r,e,t);if(o=k(o,n.outcome),n.handled){if(n.stop)return o;continue layerLoop}}return o}function se(e){let t=r.getFocusedTarget(),n=r.ensureValidPendingSequence(),i=Te(e);if(n)return ce(n,i,e,t);let a=r.getActiveLayers(t),o=j();for(let n of i){let r=ue(a,[n],e,t);if(o=k(o,r),r.handled)return o}return o}function ce(t,n,i,a){let o=s.getActiveCommandView(a),c=[];for(let r of t.captures){let t=rl(r,n,i,e.patterns,De,Oe);t&&c.push(t)}let l=c.reduce((e,t)=>Math.min(e,tl(t,n)),1/0),u=c.filter(e=>tl(e,n)===l);if(u.length===0||!u.some(e=>Me(e,a,o))){let e=D(`sequence-miss`,t.captures);return T(`sequence-clear`,t.captures,a),r.setPendingSequence(null),e}return le(u,0,!1,i,a)}function le(t,n,i,a,o){let s=i,c=j(),l=new Set;for(let i=n;i<t.length;i+=1){let n=t[i];if(!n||l.has(n))continue;let u=Ce(t,i,n);if(u.length>0){if(s)continue;let e=we(t,n);return fe(t,i,u,e,a,o,s)||ne(`sequence-advance`,u,o,a)}if(!Xc(n,e.patterns))continue;let d=we(t,n);for(let e of d)l.add(e);let f=Ne(n.layer,d,a,o);if(c=k(c,f.outcome),f.handled&&(s=!0,f.stop))return T(`sequence-clear`,t,o),r.setPendingSequence(null),c}return T(`sequence-clear`,t,o),r.setPendingSequence(null),c}function ue(e,t,n,r){return M(e,0,t,n,r)}function M(t,n,r,a,o){let c=s.getActiveCommandView(o),l=j();for(let s=n;s<t.length;s+=1){let n=t[s];if(!n||!i.matchesConditions(n))continue;let u=ke(n,r,a,o,c);if(u.length===0)continue;if(u.filter(t=>Yc(t,e.patterns,!1)).length>0){let n=u.filter(t=>Xc(t,e.patterns)),i=Se(t,s,r,a,o);return de(t,s,r,i,n,a,o)||ne(`sequence-start`,i,o,a)}let d=Ne(n,u.filter(t=>Xc(t,e.patterns)),a,o);if(l=k(l,d.outcome),d.handled&&d.stop)return l}return l}function de(e,t,n,i,a,o,s){return pe({event:o,focused:s,continuationCaptures:i,exactBindingsSource:a.map(e=>e.binding),sequencePhase:`sequence-start`,runExact:()=>{r.setPendingSequence(null);let i=a[0]?.layer;if(!i)return j();let c=Ne(i,a,o,s);return c.stop?c.outcome:k(c.outcome,M(e,t+1,n,o,s))}})}function fe(e,t,n,i,a,o,s){return pe({event:a,focused:o,continuationCaptures:n,exactBindingsSource:i.map(e=>e.binding),sequencePhase:`sequence-advance`,runExact:()=>{r.setPendingSequence(null);let n=i[0]?.layer;if(!n)return j();let c=Ne(n,i,a,o);return c.stop?c.outcome:k(c.outcome,le(e,t+1,s||c.handled,a,o))}})}function pe(t){let{event:n,focused:i,continuationCaptures:a,exactBindingsSource:o,sequencePhase:c,runExact:l}=t;if(!e.disambiguationResolvers.has()||a.length===0)return;let u=s.getActiveCommandView(i),d=r.collectMatchingBindings(o,i,u);if(!d.some(e=>e.command!==void 0))return;let f=()=>ne(c,a,i,n),p=()=>re(`sequence-cleared`,a,i,n),m,h=()=>(m??=r.collectSequencePartsFromPending({captures:a}),m),g=he({event:n,focused:i,getSequence:h,exactBindings:d,continuationCaptures:a,activeView:u});return g?me(g,a,l,f,p,i,h):(xe(h()),f())}function me(e,t,n,r,i,a,o){if(e.action===`run-exact`)return n();if(e.action===`continue-sequence`)return r();if(e.action===`clear`)return i();let s=r();return ge(t,e.handler,a,o(),e=>{if(e){if(e.action===`run-exact`){n();return}if(e.action===`continue-sequence`){r();return}i()}}),s}function he(i){let a,o,s,c,l={event:i.event,focused:i.focused,get sequence(){return a??=Mc(i.getSequence()),a},get stroke(){let e=i.getSequence().at(-1);if(!e)throw Error(`Disambiguation context expected a non-empty sequence`);return c??={...e,stroke:kc(e.stroke)},c},get exact(){return o??=r.collectActiveBindings(i.exactBindings,i.focused,i.activeView).map(e=>({...e,sequence:Mc(e.sequence)})),o},get continuations(){return s??=r.getActiveKeysForCaptures(i.continuationCaptures,{includeBindings:!0,includeMetadata:!0}),s},getData:e=>n.getData(e),setData:(e,t)=>{n.setData(e,t)},runExact:()=>ju(`run-exact`),continueSequence:()=>ju(`continue-sequence`),clear:()=>ju(`clear`),defer:e=>ju(`defer`,e)};for(let n of e.disambiguationResolvers.values()){let e;try{e=n(l)}catch(e){t.emitError(`disambiguation-resolver-error`,e,`[Keymap] Error in disambiguation resolver:`);continue}if(e!==void 0){if(Vl(e)){t.emitError(`invalid-disambiguation-resolver-return`,e,`[Keymap] Disambiguation resolvers must return synchronously; use ctx.defer(...) for async handling`);continue}if(!Nu(e)){t.emitError(`invalid-disambiguation-decision`,e,`[Keymap] Invalid disambiguation decision returned by resolver:`);continue}return e}}}function ge(e,t,n,r,i){be();let a=new AbortController,o={id:f++,controller:a,captures:e,apply:i};d=o,queueMicrotask(()=>{_e(o,t,n,r)})}function _e(e,n,r,i){if(!N(e))return;let a={signal:e.controller.signal,sequence:Mc(i),focused:r,sleep:t=>Fu(t,e.controller.signal),runExact:()=>Mu(`run-exact`),continueSequence:()=>Mu(`continue-sequence`),clear:()=>Mu(`clear`)},o;try{o=n(a)}catch(n){N(e)&&(t.emitError(`deferred-disambiguation-error`,n,`[Keymap] Error in deferred disambiguation handler:`),ye(e));return}if(Vl(o)){o.then(t=>{ve(e,t)}).catch(n=>{N(e)&&(t.emitError(`deferred-disambiguation-error`,n,`[Keymap] Error in deferred disambiguation handler:`),ye(e))});return}ve(e,o)}function ve(e,n){if(N(e)){if(n!==void 0&&!Pu(n)){t.emitError(`invalid-deferred-disambiguation-decision`,n,`[Keymap] Invalid deferred disambiguation decision returned by handler:`),ye(e);return}ye(e),e.apply(n)}}function ye(e){N(e)&&(d=null)}function be(){let e=d;e&&(d=null,e.controller.abort())}function N(e){return d===e}function xe(e){let n=Lc(e,{preferDisplay:!0});t.warnOnce(`unresolved-disambiguation:${n}`,`unresolved-disambiguation`,{sequence:n},`[Keymap] Ambiguous exact/prefix sequence "${n}" fell back to prefix handling because no disambiguation resolver resolved it`)}function Se(t,n,r,a,o){let c=[],l=s.getActiveCommandView(o);for(let s=n;s<t.length;s+=1){let n=t[s];if(n&&i.matchesConditions(n))for(let t of ke(n,r,a,o,l))Yc(t,e.patterns,!1)&&c.push(t)}return c}function Ce(t,n,r){return t.filter((t,i)=>i>=n&&Yc(t,e.patterns,!1)&&Vu(t.parts,r.parts))}function we(t,n){return t.filter(t=>t.layer===n.layer&&Xc(t,e.patterns)&&Vu(t.parts,n.parts))}function Te(n){let r=e.eventMatchResolvers.values();if(r.length===0)return[];if(r.length===1)return Bu(r[0],n,u,t);let i=[],a=new Set;for(let e of r){let r;try{r=e(n,u)}catch(e){t.emitError(`event-match-resolver-error`,e,`[Keymap] Error in event match resolver:`);continue}if(!(!r||r.length===0))for(let e of r){if(typeof e!=`string`){t.emitError(`invalid-event-match-resolver-candidate`,e,`[Keymap] Invalid event match resolver candidate:`);continue}a.has(e)||(a.add(e),i.push(e))}}return i}function Ee(e,t,n,r){let o=!1,s=j();for(let c of e.bindings){if(c.event!==`release`)continue;let l=c.sequence[0];if(!l||l.match!==t||!i.matchesConditions(c))continue;let u=a.runBinding(e,c,n,r);if(s=k(s,O(c,u)),!u){w(`binding-reject`,e,c,r);continue}if(w(`binding-execute`,e,c,r),o=!0,!c.fallthrough)return{handled:!0,stop:!0,outcome:s}}return{handled:o,stop:!1,outcome:s}}function De(n,r){return Iu(e.patterns,t,n,r)}function Oe(t,n,r){return Lu(e.patterns,t,n,r)}function ke(e,t,n,r,i){let a=il(e,t,n,De,Oe);return a.some(e=>Me(e,r,i))?a:[]}function Ae(n){return Ru(e.patterns,t,n)}function je(e,t,n){return i.matchesConditions(e)&&s.isBindingVisible(e,t,n)}function Me(e,t,n){return je(e.binding,t,n)}function Ne(e,t,n,r){let o=!1,s=j();for(let c of t){let t=c.binding;if(!i.matchesConditions(t))continue;let l=a.runBinding(e,t,n,r,Ae(c));if(s=k(s,O(t,l)),!l){w(`binding-reject`,e,t,r);continue}if(w(`binding-execute`,e,t,r),o=!0,!t.fallthrough)return{handled:!0,stop:!0,outcome:s}}return{handled:o,stop:!1,outcome:s}}return{intercept:p,prependEventMatchResolver:m,appendEventMatchResolver:h,clearEventMatchResolvers:g,prependDisambiguationResolver:_,appendDisambiguationResolver:v,clearDisambiguationResolvers:y,handlePendingSequenceChange:b,handleRawSequence:x,handleKeyEvent:ie}}function Bu(e,t,n,r){let i;try{i=e(t,n)}catch(e){return r.emitError(`event-match-resolver-error`,e,`[Keymap] Error in event match resolver:`),[]}if(!i||i.length===0)return[];if(i.length===1){let[e]=i;return typeof e==`string`?[e]:(r.emitError(`invalid-event-match-resolver-candidate`,e,`[Keymap] Invalid event match resolver candidate:`),[])}let a=[],o=new Set;for(let e of i){if(typeof e!=`string`){r.emitError(`invalid-event-match-resolver-candidate`,e,`[Keymap] Invalid event match resolver candidate:`);continue}o.has(e)||(o.add(e),a.push(e))}return a}function Vu(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]?.match!==t[n]?.match)return!1;return!0}var Hu=()=>{};function Uu(e,t,n,r){if(n===void 0)return r;if(typeof n!=`number`||!Number.isInteger(n)||n<0)throw Error(`Keymap sequence pattern "${e}" ${t} must be a non-negative integer`);return n}function Wu(e,t){let{kind:n,reservedFields:r,registeredFields:i,emitError:a}=t,o=Object.entries(e),s=[];for(let[e,t]of o){if(r.has(e)){a(`reserved-${n}-field`,{field:e,kind:n},`Keymap ${n} field "${e}" is reserved`);continue}if(i.has(e)){a(`duplicate-${n}-field`,{field:e,kind:n},`Keymap ${n} field "${e}" is already registered`);continue}i.set(e,t),s.push([e,t])}return()=>{for(let[e,t]of s)i.get(e)===t&&i.delete(e)}}function Gu(e,t,n,r,i){let a;try{a=Ec(i.name)}catch(e){return t.emitError(`token-name-normalize-error`,e,Bl(e,`Failed to register keymap token`)),Hu}if(e.tokens.has(a)||e.patterns.has(a))return t.emitError(`duplicate-token`,{token:a},`Keymap token "${a}" is already registered`),Hu;let o;try{if(o=n.parseTokenKey(i.key),o.patternName)throw Error(`Invalid key "${String(i.key)}": expected a concrete key stroke`)}catch(e){return t.emitError(`token-parse-error`,e,Bl(e,`Failed to register keymap token "${a}"`)),Hu}let s={stroke:o.stroke,match:o.match},c=new Map(e.tokens);c.set(a,s);try{r.applyTokenState(c)}catch(e){return t.emitError(`token-register-error`,e,Bl(e,`Failed to register keymap token "${a}"`)),Hu}return()=>{if(e.tokens.get(a)!==s)return;let n=new Map(e.tokens);n.delete(a);try{r.applyTokenState(n)}catch(e){t.emitError(`token-unregister-error`,e,Bl(e,`Failed to unregister keymap token "${a}"`))}}}function Ku(e,t,n,r){let i,a;try{i=Ec(r.name);let e=Uu(i,`min`,r.min,1),t=Uu(i,`max`,r.max,2**53-1);if(t<e)throw Error(`Keymap sequence pattern "${i}" max must be greater than or equal to min`);a={name:i,display:r.display,payloadKey:r.payloadKey??i,match:Fc(`pattern:${i}`),min:e,max:t,matcher:e=>r.match(e),finalize:r.finalize}}catch(e){return t.emitError(`sequence-pattern-register-error`,e,Bl(e,`Failed to register keymap sequence pattern`)),Hu}return e.tokens.has(i)||e.patterns.has(i)?(t.emitError(`duplicate-sequence-pattern`,{pattern:i},`Keymap sequence pattern "${i}" is already registered`),Hu):(e.patterns.set(i,a),n.recompileBindings(),()=>{e.patterns.get(i)===a&&(e.patterns.delete(i),n.recompileBindings())})}function qu(e,t,n,r){return Wu(r,{kind:n,reservedFields:n===`layer`?kl:n===`binding`?Ol:Dl,registeredFields:n===`layer`?e.layerFields:n===`binding`?e.bindingFields:e.commandFields,emitError:(e,n,r)=>t.emitError(e,n,r)})}var Ju=()=>{};function Yu(e,t){return t.priority-e.priority||t.order-e.order}function Xu(e){if(e.matchers.length>0)return!0;for(let t of e.commands)if(t.matchers.length>0)return!0;for(let t of e.bindings)if(t.matchers.length>0)return!0;return!1}function Zu(e){if(e.commands.length===0)return!1;if(e.matchers.length>0)return!0;for(let t of e.commands)if(t.matchers.length>0)return!0;return!1}function Qu(e,t,n,r,i){let a=n=>t.runWithStateChangeBatch(()=>{let a=n.target;if(a&&i.host.isTargetDestroyed(a))return t.emitError(`destroyed-layer-target`,{target:a},`Cannot register a keymap layer for a destroyed keymap target`),Ju;let o,s,c,p,m,v,y;try{y=l(n),o=u(dl(n.bindings??[]),n);let e=d(n.commands??[],n);v=e.length===0?[]:i.commands.normalizeCommands(e),{requires:s,matchers:c,fields:p,attrs:m}=f(n)}catch(e){return t.emitError(`register-layer-failed`,e,Bl(e,`Failed to register keymap layer`)),Ju}let b=e.order++,x=i.compiler.compileBindings(o,e.tokens,a,b,p);if(x.bindings.length===0&&!x.hasTokenBindings&&v.length===0)return Ju;i.diagnostics?.analyzeLayer({target:a,order:b,commands:v,sourceBindings:o,bindings:x.bindings,hasTokenBindings:x.hasTokenBindings});let S={order:b,target:a,targetMode:y,priority:n.priority??0,requires:s,matchers:c,fields:p,attrs:m,commands:v,sourceBindings:o,bindings:x.bindings,root:Qc(x.bindings,e.patterns),hasTokenBindings:x.hasTokenBindings,activeKeyCacheBlocked:!1,activeCommandViewCacheBlocked:!1};_(S),e.layers.add(S),e.sortedLayers=[...e.sortedLayers,S].sort(Yu),g(S);for(let e of S.commands)g(e);for(let e of S.bindings)g(e);return a&&(S.offTargetDestroy=i.host.onTargetDestroy(a,()=>{h(S)})),S.commands.length>0&&r.ensureValidPendingSequence(),t.queueStateChange(),()=>{h(S)}}),o=n=>{t.runWithStateChangeBatch(()=>{let i=new Map;for(let t of e.layers)t.hasTokenBindings&&i.set(t,p(t,n));e.tokens=n;let a=!1;for(let[e,t]of i)m(e,t)&&(a=!0);a&&r.setPendingSequence(null),i.size>0&&t.queueStateChange()})},s=()=>{t.runWithStateChangeBatch(()=>{let n=0,i=!1;for(let t of e.layers){if(t.sourceBindings.length===0)continue;let r=p(t,e.tokens);m(t,r)&&(i=!0),n+=1}i&&r.setPendingSequence(null),n>0&&t.queueStateChange()})},c=()=>{for(let t of e.layers){y(t);for(let e of t.commands)y(e);for(let e of t.bindings)y(e);t.offTargetDestroy?.(),t.offTargetDestroy=void 0}},l=e=>{if(e.targetMode){if(!e.target)throw Error(`Keymap targetMode "${e.targetMode}" requires a target`);return e.targetMode}return e.target?`focus-within`:void 0},u=(t,n)=>{let r=e.layerBindingsTransformers.values();if(r.length===0)return t;let i=t;for(let e of r){let t=e(i,{layer:n,validateBindings:e=>ul(e)});t&&(i=dl(t))}return i},d=(n,r)=>{let i=e.commandTransformers.values();if(n.length===0||i.length===0)return n;let a=[];for(let e of n){let n={...e},o=[],s=!0;for(let e of i)try{e(n,{layer:r,add(e){o.push({...e})},skipOriginal(){s=!1}})}catch(e){t.emitError(`command-transformer-error`,e,`[Keymap] Error in command transformer:`)}s&&a.push(n),a.push(...o)}return a},f=t=>{let r={},a=[],o=Object.create(null),s={};for(let[c,l]of Object.entries(t)){if(kl.has(c)||l===void 0)continue;o[c]=Hl(l);let t=e.layerFields.get(c);if(!t){i.warnUnknownField(`layer`,c);continue}t(l,Rl({fieldName:c,conditions:n,requirements:r,matchers:a,attrs:s}))}return{requires:Object.entries(r),matchers:a,fields:Object.keys(o).length>0?Object.freeze(o):void 0,attrs:Object.keys(s).length>0?Hl(s,{freeze:!0}):void 0}},p=(e,t)=>i.compiler.compileBindings(e.sourceBindings,t,e.target,e.order,e.fields),m=(t,n)=>{i.diagnostics?.analyzeLayer({target:t.target,order:t.order,commands:t.commands,sourceBindings:t.sourceBindings,bindings:n.bindings,hasTokenBindings:n.hasTokenBindings}),v(t);for(let e of t.bindings)y(e);t.bindings=n.bindings,t.root=Qc(n.bindings,e.patterns),t.hasTokenBindings=n.hasTokenBindings,_(t);for(let e of t.bindings)g(e);return e.pending?.captures.some(e=>e.layer===t)??!1},h=n=>{t.runWithStateChangeBatch(()=>{if(e.layers.delete(n)){e.sortedLayers=e.sortedLayers.filter(e=>e!==n),v(n),y(n);for(let e of n.commands)y(e);for(let e of n.bindings)y(e);n.offTargetDestroy?.(),n.offTargetDestroy=void 0,e.pending?.captures.some(e=>e.layer===n)?r.setPendingSequence(null):n.commands.length>0&&!i.host.isDestroyed&&r.ensureValidPendingSequence(),t.queueStateChange()}})},g=e=>{for(let n of e.matchers)if(n.subscribe)try{n.dispose=n.subscribe(()=>{if(!r.hasPendingSequenceState()){t.queueStateChange();return}t.runWithStateChangeBatch(()=>{r.revalidatePendingSequenceIfNeeded(),t.queueStateChange()})})}catch(e){t.emitError(`reactive-matcher-subscribe-error`,e,Bl(e,`Failed to subscribe to reactive matcher from ${n.source}`))}},_=t=>{let n=Xu(t),r=Zu(t);t.activeKeyCacheBlocked=n,t.activeCommandViewCacheBlocked=r,n&&(e.activeKeyCacheBlockers+=1),r&&(e.activeCommandViewCacheBlockers+=1)},v=t=>{t.activeKeyCacheBlocked&&=(--e.activeKeyCacheBlockers,!1),t.activeCommandViewCacheBlocked&&=(--e.activeCommandViewCacheBlockers,!1)},y=e=>{for(let n of e.matchers)if(n.dispose){try{n.dispose()}catch(e){t.emitError(`reactive-matcher-dispose-error`,e,Bl(e,`Failed to dispose reactive matcher from ${n.source}`))}n.dispose=void 0}};return{registerLayer:a,applyTokenState:o,recompileBindings:s,cleanup:c}}var $u=1e3;function ed(e,t,n){let r=(e,n,r)=>{if(!t.has(`warning`)){let t=`[${e}] ${r}`;n instanceof Error?console.warn(t,n):console.warn(t);return}t.emit(`warning`,{code:e,message:r,warning:n})},i=(e,n,r)=>{if(!t.has(`error`)){let t=`[${e}] ${r}`;n instanceof Error?console.error(t,n):console.error(t);return}t.emit(`error`,{code:e,message:r,error:n})},a=()=>{if(!(!e.stateChangePending||e.stateChangeDepth>0||e.flushingStateChange)){e.flushingStateChange=!0;try{let t=0;for(;e.stateChangePending&&e.stateChangeDepth===0;){if(t>=$u){e.stateChangePending=!1,i(`state-change-feedback-loop`,{iterations:$u},`[Keymap] Possible infinite state listener feedback loop detected after ${$u} iterations; pending state notifications were dropped`);break}t+=1,e.stateChangePending=!1,n.emit(`state`)}}finally{e.flushingStateChange=!1}}};return{runWithStateChangeBatch(t){e.stateChangeDepth+=1;try{return t()}finally{--e.stateChangeDepth,e.stateChangeDepth===0&&a()}},queueStateChange(t){e.derivedVersion+=1,t?.invalidateCaches!==!1&&(e.cacheVersion+=1),n.has(`state`)&&(e.stateChangePending=!0,e.stateChangeDepth===0&&!e.flushingStateChange&&a())},emitWarning:r,emitError:i,reportListenerError(e,t){if(e===`state`){i(`state-listener-error`,t,`[Keymap] Error in state listener:`);return}if(e===`pendingSequence`){i(`pending-sequence-listener-error`,t,`[Keymap] Error in pending sequence listener:`);return}e===`dispatch`&&i(`dispatch-listener-error`,t,`[Keymap] Error in dispatch listener:`)},warnOnce(t,n,i,a){e.usedWarningKeys.has(t)||(e.usedWarningKeys.add(t),r(n,i,a))}}}function td(e,t,n){return{getData(t){return e.data[t]},setData(r,i){t.runWithStateChangeBatch(()=>{if(i===void 0){if(!(r in e.data))return;delete e.data[r],e.dataVersion+=1,n.ensureValidPendingSequence(),t.queueStateChange();return}Object.is(e.data[r],i)||(e.data[r]=i,e.dataVersion+=1,n.ensureValidPendingSequence(),t.queueStateChange())})},getReadonlyData(){return e.readonlyDataVersion===e.dataVersion?e.readonlyData:(e.readonlyData=Object.freeze({...e.data}),e.readonlyDataVersion=e.dataVersion,e.readonlyData)}}}var nd=Object.freeze({});function rd(){return{order:0,tokens:new Map,patterns:new Map,layerFields:new Map,layerBindingsTransformers:sl(),bindingExpanders:sl(),bindingParsers:sl(),bindingTransformers:sl(),bindingFields:new Map,commandTransformers:sl(),commandFields:new Map,eventMatchResolvers:sl(),disambiguationResolvers:sl(),keyHooks:cl(),keyAfterHooks:cl(),rawHooks:cl(),layers:new Set,sortedLayers:[],activeLayersCacheVersion:-1,activeLayersCacheFocused:void 0,activeLayersCache:[],activeKeyCacheBlockers:0,activeCommandViewCacheBlockers:0,commandResolvers:sl(),pending:null,data:{},dataVersion:0,readonlyDataVersion:-1,readonlyData:nd,cacheVersion:0,derivedVersion:0,stateChangeDepth:0,stateChangePending:!1,flushingStateChange:!1,usedWarningKeys:new Set}}function id(e){return Nc(e)}var ad=class{#e=rd();#t=!1;#n=new Map;#r=[];#i=al(()=>{});#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;getPendingSequence;getActiveKeys;constructor(e){if(this.#b=e,e.isDestroyed)throw Error(`Cannot create a keymap for a destroyed host`);this.#a=al((e,t)=>{this.#o.reportListenerError(e,t)}),this.#o=ed(this.#e,this.#i,this.#a),this.#l=Ou(this.#e,this.#o),this.#u=Kl(this.#e,this.#b,this.#o,this.#l,{onCommandResolversChanged:()=>{this.#s.ensureValidPendingSequence()}}),this.#s=El(this.#e,this.#b,this.#a,this.#o,this.#l,this.#u,{onPendingSequenceChanged:(e,t)=>{this.#p?.handlePendingSequenceChange(e,t)}}),this.#c=td(this.#e,this.#o,this.#s),this.#d=pu(this.#o,this.#c,this.#s,this.#u,{keymap:this,createCommandEvent:()=>this.#b.createCommandEvent()}),this.#f=bu(this.#e,this.#o,this.#l,{warnUnknownField:(e,t)=>{this.#C(e,t)},warnUnknownToken:(e,t)=>{this.#w(e,t)}}),this.#h=pl(this.#o,this.#u),this.#m=Qu(this.#e,this.#o,this.#l,this.#s,{compiler:this.#f,commands:this.#u,host:this.#b,diagnostics:this.#h,warnUnknownField:(e,t)=>{this.#C(e,t)}}),this.#p=zu(this.#e,this.#o,this.#c,this.#s,this.#l,this.#d,this.#f,this.#u,this.#m,this.#a),this.getPendingSequence=this.#s.getPendingSequence,this.getActiveKeys=this.#s.getActiveKeys,this.#g=e=>{this.#p.handleKeyEvent(e,!1)},this.#_=e=>{this.#p.handleKeyEvent(e,!0)},this.#v=e=>this.#p.handleRawSequence(e),this.#y=e=>{this.#S(e)},this.#r.push(this.#b.onKeyPress(this.#g)),this.#r.push(this.#b.onKeyRelease(this.#_)),this.#b.onRawInput&&this.#r.push(this.#b.onRawInput(this.#v)),this.#r.push(this.#b.onFocusChange(this.#y)),this.#b.onDestroy&&this.#r.push(this.#b.onDestroy(()=>{this.#x()}))}[Bc](){return{state:this.#e,host:this.#b,conditions:this.#l,catalog:this.#u,activation:this.#s}}#x(){if(!this.#t){this.#t=!0,this.#s.setPendingSequence(null);for(let e of this.#n.values())e.dispose();this.#n.clear(),this.#m.cleanup();for(let e of this.#r.splice(0))e()}}setData(e,t){this.#c.setData(e,t)}getData(e){return this.#c.getData(e)}getHostMetadata(){return this.#b.metadata}hasPendingSequence(){return this.#s.ensureValidPendingSequence()!==void 0}createKeyMatcher(e){let t=this.#f.parseTokenKey(e).match;return e=>e?id(e)===t:!1}parseKeySequence(e){return this.#f.parseKeySequence(e)}formatKey(e,t){return this.#f.formatKey(e,t)}clearPendingSequence(){this.#s.setPendingSequence(null)}popPendingSequence(){return this.#s.popPendingSequence()}getCommands(e){return this.#u.getCommands(e)}getCommandEntries(e){return this.#u.getCommandEntries(e)}getCommandBindings(e){return this.#u.getCommandBindings(e)}acquireResource(e,t){if(this.#t||this.#b.isDestroyed)throw Error(`Cannot use a keymap after its host was destroyed`);let n=this.#n.get(e);if(n)return n.count+=1,()=>{this.#T(e,n)};let r={count:1,dispose:t()};return this.#n.set(e,r),()=>{this.#T(e,r)}}runCommand(e,t){return this.#d.runCommand(e,t)}dispatchCommand(e,t){return this.#d.dispatchCommand(e,t)}on(e,t){return e===`warning`||e===`error`?this.#i.hook(e,t):this.#a.hook(e,t)}intercept(e,t,n){return this.#p.intercept(e,t,n)}registerLayer(e){return this.#m.registerLayer(e)}registerLayerFields(e){return qu(this.#e,this.#o,`layer`,e)}prependLayerBindingsTransformer(e){return this.#e.layerBindingsTransformers.prepend(e)}appendLayerBindingsTransformer(e){return this.#e.layerBindingsTransformers.append(e)}clearLayerBindingsTransformers(){this.#e.layerBindingsTransformers.clear()}prependBindingTransformer(e){return this.#e.bindingTransformers.prepend(e)}appendBindingTransformer(e){return this.#e.bindingTransformers.append(e)}clearBindingTransformers(){this.#e.bindingTransformers.clear()}prependCommandTransformer(e){return this.#e.commandTransformers.prepend(e)}appendCommandTransformer(e){return this.#e.commandTransformers.append(e)}clearCommandTransformers(){this.#e.commandTransformers.clear()}prependBindingParser(e){return this.#e.bindingParsers.prepend(e)}appendBindingParser(e){return this.#e.bindingParsers.append(e)}clearBindingParsers(){this.#e.bindingParsers.clear()}registerToken(e){return Gu(this.#e,this.#o,this.#f,this.#m,e)}registerSequencePattern(e){return Ku(this.#e,this.#o,this.#m,e)}prependBindingExpander(e){return this.#e.bindingExpanders.prepend(e)}appendBindingExpander(e){return this.#e.bindingExpanders.append(e)}clearBindingExpanders(){this.#e.bindingExpanders.clear()}registerBindingFields(e){return qu(this.#e,this.#o,`binding`,e)}registerCommandFields(e){return qu(this.#e,this.#o,`command`,e)}prependCommandResolver(e){return this.#u.prependCommandResolver(e)}appendCommandResolver(e){return this.#u.appendCommandResolver(e)}clearCommandResolvers(){this.#u.clearCommandResolvers()}prependLayerAnalyzer(e){return this.#h.prependLayerAnalyzer(e)}appendLayerAnalyzer(e){return this.#h.appendLayerAnalyzer(e)}clearLayerAnalyzers(){this.#h.clearLayerAnalyzers()}prependEventMatchResolver(e){return this.#p.prependEventMatchResolver(e)}appendEventMatchResolver(e){return this.#p.appendEventMatchResolver(e)}clearEventMatchResolvers(){this.#p.clearEventMatchResolvers()}prependDisambiguationResolver(e){return this.#p.prependDisambiguationResolver(e)}appendDisambiguationResolver(e){return this.#p.appendDisambiguationResolver(e)}clearDisambiguationResolvers(){this.#p.clearDisambiguationResolvers()}#S(e){this.#o.runWithStateChangeBatch(()=>{this.#s.setPendingSequence(null),this.#o.queueStateChange({invalidateCaches:!1})})}#C(e,t){this.#o.warnOnce(`${e}:${t}`,`unknown-${e}-field`,{field:t,kind:e},`[Keymap] Unknown ${e} field "${t}" was ignored`)}#w(e,t){this.#o.warnOnce(`token:${e}`,`unknown-token`,{token:e,sequence:t},`[Keymap] Unknown token "${e}" in key sequence "${t}"; binding was skipped until the token is registered`)}#T(e,t){this.#n.get(e)===t&&(--t.count,!(t.count>0)&&(t.dispose(),this.#n.delete(e)))}},od=new Set(`up.down.left.right.clear.escape.return.linefeed.enter.tab.backspace.delete.insert.home.end.pageup.pagedown.space.lt.gt.plus.minus.equal.comma.period.slash.backslash.semicolon.quote.backquote.leftbracket.rightbracket.capslock.numlock.scrolllock.printscreen.pause.menu.apps.kp0.kp1.kp2.kp3.kp4.kp5.kp6.kp7.kp8.kp9.kpdecimal.kpdivide.kpmultiply.kpminus.kpplus.kpenter.kpequal.kpseparator.kpleft.kpright.kpup.kpdown.kppageup.kppagedown.kphome.kpend.kpinsert.kpdelete.mediaplay.mediapause.mediaplaypause.mediareverse.mediastop.mediafastforward.mediarewind.medianext.mediaprev.mediarecord.volumedown.volumeup.mute.leftshift.leftctrl.leftalt.leftsuper.lefthyper.leftmeta.rightshift.rightctrl.rightalt.rightsuper.righthyper.rightmeta.iso_level3_shift.iso_level5_shift.option.alt.meta.super.hyper.control.ctrl.shift`.split(`.`)),sd=new Set([`ctrl`,`control`,`shift`,`meta`,`alt`,`option`,`super`,`hyper`]),cd=ud(od),ld=ud(sd);function ud(e){let t=new Map;for(let n of e){let e=n.charCodeAt(0);if(Number.isNaN(e))continue;let r=t.get(e);r||(r=[],t.set(e,r)),r.push(n)}for(let e of t.values())e.sort((e,t)=>t.length-e.length);return t}function dd(e){return e>=65&&e<=90?e+32:e}function fd(e){return e>=48&&e<=57}function pd(e,t,n){if(e.startsWith(t,n))return!0;if(n+t.length>e.length)return!1;for(let r=0;r<t.length;r+=1)if(dd(e.charCodeAt(n+r))!==t.charCodeAt(r))return!1;return!0}function md(e,t,n){let r=t.charCodeAt(n);if(Number.isNaN(r))return;let i=e.get(dd(r));if(i){for(let e of i)if(pd(t,e,n))return e}}function hd(e,t,n,r,i){return e.parseObjectKey(t,{display:n,match:r,tokenName:i})}function gd(e,t){if(e===` `)return t.parseObjectKey({name:`space`},{display:`space`});if(e===`+`)return t.parseObjectKey({name:`+`},{display:`+`});let n=e.split(`+`),r=``,i=``,a=!1,o=!1,s=!1,c=!1,l=!1;for(let t of n){let n=t.trim();if(!n)continue;let u=n.toLowerCase();if(u===`ctrl`||u===`control`){a=!0;continue}if(u===`shift`){o=!0;continue}if(u===`meta`||u===`alt`||u===`option`){s=!0;continue}if(u===`super`){c=!0;continue}if(u===`hyper`){l=!0;continue}if(r)throw Error(`Invalid key "${e}": multiple key names are not supported`);r=n,i=u}if(!r)throw Error(`Invalid key "${e}": missing key name`);let u=[];return a&&u.push(`ctrl`),o&&u.push(`shift`),s&&u.push(`meta`),c&&u.push(`super`),l&&u.push(`hyper`),u.push(i),t.parseObjectKey({name:r,ctrl:a,shift:o,meta:s,super:c,hyper:l||void 0},{display:u.join(`+`)})}function _d(e,t){let n=e.trim().toLowerCase();return t.parseObjectKey({name:n},{display:n})}function vd(e,t){let n=md(cd,e,t);if(n)return n;if(dd(e.charCodeAt(t))!==102||!fd(e.charCodeAt(t+1)))return;let r=fd(e.charCodeAt(t+2))?t+3:t+2;return e.slice(t,r).toLowerCase()}function yd(e,t){return md(ld,e,t)}function bd(e,t,n){let r=t,i=!1,a=!1,o=!1,s=!1,c=!1;for(;r<e.length;){let t=yd(e,r);if(!t)break;let n=r+t.length;if(e[n]!==`+`)break;t===`ctrl`||t===`control`?i=!0:t===`shift`?a=!0:t===`meta`||t===`alt`||t===`option`?o=!0:t===`super`?s=!0:t===`hyper`&&(c=!0),r=n+1}if(r===t)return;let l=e[r];if(l===void 0)throw Error(`Invalid key "${e.slice(t)}": missing key name`);let u=vd(e,r)??l,d=u===` `?`space`:u===`+`?`+`:u.toLowerCase(),f=[];return i&&f.push(`ctrl`),a&&f.push(`shift`),o&&f.push(`meta`),s&&f.push(`super`),c&&f.push(`hyper`),f.push(d),{part:n.parseObjectKey({name:u===` `?`space`:u,ctrl:i,shift:a,meta:o,super:s,hyper:c||void 0},{display:f.join(`+`)}),nextIndex:r+u.length}}var xd=e=>{let{input:t,index:n,tokens:r,normalizeTokenName:i}=e;if(n===0&&t.includes(`+`)&&/\s/.test(t))return{parts:[gd(t,e)],nextIndex:t.length};let a=t[n];if(a===void 0)return;if(a===`<`){let o=t.indexOf(`>`,n);if(o===-1)return{parts:[gd(a,e)],nextIndex:n+1};let s=i(t.slice(n+1,o)),c=r.get(s);return c?{parts:[hd(e,c.stroke,`<${s}>`,c.match,s)],nextIndex:o+1,usedTokens:[s]}:{parts:[],nextIndex:o+1,unknownTokens:[s]}}if(a===`{`){let r=t.indexOf(`}`,n);if(r===-1)return{parts:[gd(a,e)],nextIndex:n+1};let o=i(t.slice(n+1,r)),s=e.patterns.get(o);return s?{parts:[{...e.parseObjectKey({name:o,ctrl:!1,shift:!1,meta:!1,super:!1},{display:s.display??`{${o}}`,match:s.match}),patternName:s.name,payloadKey:s.payloadKey}],nextIndex:r+1,usedTokens:[o]}:{parts:[],nextIndex:r+1,unknownTokens:[o]}}let o=bd(t,n,e);if(o)return{parts:[o.part],nextIndex:o.nextIndex};let s=vd(t,n);return s?{parts:[_d(s,e)],nextIndex:n+s.length}:{parts:[gd(a,e)],nextIndex:n+1}},Sd=(e,t)=>[t.resolveKey({name:e.name,ctrl:e.ctrl,shift:e.shift,meta:e.meta,super:e.super??!1,hyper:e.hyper||void 0})];function Cd(e){return e.appendBindingParser(e=>xd(e))}function wd(e){return e.appendEventMatchResolver((e,t)=>Sd(e,t))}function Td(e){let t=Cd(e),n=wd(e);return()=>{n(),t()}}var Ed=Symbol(`keymap:mod-bindings`),Dd=/(^|[+,\s])mod(?=\s*\+)/i,Od=/(^|[+,\s])mod(?=\s*\+)/gi;function kd(e){let t=e.primaryModifier;return(t===`ctrl`||t===`super`)&&e.modifiers[t]!==`unsupported`?t:e.modifiers.ctrl===`unsupported`?`super`:`ctrl`}function Ad(e){if(e.includes(`,`))return[e];let t=e.trim();return t.includes(` `)?t.split(/\s+/):[e]}function jd(e){return e.acquireResource(Ed,()=>e.appendBindingExpander(({input:t,displays:n})=>{if(!Dd.test(t))return;let r=kd(e.getHostMetadata());return[{key:t.replace(Od,(e,t)=>`${t}${r}`),displays:n??Ad(t)}]}))}var Md=new Map([[` `,`space`],[`Spacebar`,`space`],[`ArrowUp`,`up`],[`ArrowDown`,`down`],[`ArrowLeft`,`left`],[`ArrowRight`,`right`],[`Escape`,`escape`],[`Esc`,`escape`],[`Enter`,`return`],[`Backspace`,`backspace`],[`Delete`,`delete`],[`Tab`,`tab`],[`Home`,`home`],[`End`,`end`],[`PageUp`,`pageup`],[`PageDown`,`pagedown`],[`Insert`,`insert`],[`CapsLock`,`capslock`],[`NumLock`,`numlock`],[`ScrollLock`,`scrolllock`],[`ContextMenu`,`menu`],[`Meta`,`super`],[`OS`,`super`],[`Alt`,`alt`],[`Control`,`control`],[`Shift`,`shift`]]);function Nd(e){let t=e?.trim().toLowerCase();return t?t.includes(`mac`)||t.includes(`darwin`)?`macos`:t.includes(`win`)?`windows`:t.includes(`linux`)||t.includes(`x11`)?`linux`:`unknown`:`unknown`}function Pd(){let e=globalThis.navigator,t=e?.userAgentData?.platform,n=Nd(t);return n===`unknown`?Nd(e?.platform??e?.userAgent):n}function Fd(){let e=Pd();return{platform:e,primaryModifier:e===`macos`?`super`:e===`unknown`?`unknown`:`ctrl`,modifiers:{ctrl:`supported`,shift:`supported`,meta:`supported`,super:`supported`,hyper:`unsupported`}}}function Id(e){return e.length===1&&!/^[a-z0-9]$/i.test(e)}function Ld(e){let t={name:e.name,ctrl:e.ctrl,shift:e.shift,meta:e.meta,super:e.super??!1,hyper:e.hyper||void 0};return!t.shift||!Id(t.name)?[t]:[t,{...t,shift:!1}]}var Rd=class{name;ctrl;shift;meta;superKey;originalEvent;propagationStopped=!1;constructor(e,t,n,r,i,a){this.name=e,this.ctrl=t,this.shift=n,this.meta=r,this.superKey=i,this.originalEvent=a}get super(){return this.superKey}preventDefault(){this.originalEvent?.preventDefault()}stopPropagation(){this.propagationStopped=!0,this.originalEvent?.stopPropagation()}};function zd(){return globalThis.MutationObserver}function Bd(e){return Md.get(e)||(/^F\d{1,2}$/i.test(e)||e.length===1?e.toLowerCase():e.trim().toLowerCase().replace(/\s+/g,``))}function Vd(e){if(!e)return new Rd(`command`,!1,!1,!1,!1);let t=globalThis.KeyboardEvent;return new Rd(Bd(e.key),e.ctrlKey,e.shiftKey,e.altKey,e.metaKey,t&&e instanceof t?e:void 0)}var Hd=class{metadata=Fd();rootTarget;isDestroyed=!1;observer;targetDestroyListeners=new Map;constructor(e){this.rootTarget=e}getFocusedTarget(){let e=this.rootTarget.ownerDocument.activeElement;return!e||typeof e!=`object`?null:e===this.rootTarget||this.rootTarget.contains(e)?e:null}getParentTarget(e){return e.parentElement}isTargetDestroyed(e){return e===this.rootTarget?!1:!e.isConnected||!this.rootTarget.contains(e)}onKeyPress(e){let t=t=>{e(Vd(t))};return this.rootTarget.addEventListener(`keydown`,t,{capture:!0}),()=>{this.rootTarget.removeEventListener(`keydown`,t,{capture:!0})}}onKeyRelease(e){let t=t=>{e(Vd(t))};return this.rootTarget.addEventListener(`keyup`,t,{capture:!0}),()=>{this.rootTarget.removeEventListener(`keyup`,t,{capture:!0})}}onFocusChange(e){let t=()=>{queueMicrotask(()=>{e(this.getFocusedTarget())})};return this.rootTarget.addEventListener(`focusin`,t,{capture:!0}),this.rootTarget.addEventListener(`focusout`,t,{capture:!0}),()=>{this.rootTarget.removeEventListener(`focusin`,t,{capture:!0}),this.rootTarget.removeEventListener(`focusout`,t,{capture:!0})}}onTargetDestroy(e,t){let n=this.targetDestroyListeners.get(e);return n||(n=new Set,this.targetDestroyListeners.set(e,n)),n.add(t),this.ensureObserver(),this.flushDisconnectedTargets(),()=>{let n=this.targetDestroyListeners.get(e);n&&(n.delete(t),n.size===0&&this.targetDestroyListeners.delete(e),this.targetDestroyListeners.size===0&&this.disconnectObserver())}}createCommandEvent(){return Vd()}ensureObserver(){if(this.observer||this.targetDestroyListeners.size===0)return;let e=zd();e&&(this.observer=new e(()=>{this.flushDisconnectedTargets()}),this.observer.observe(this.rootTarget,{childList:!0,subtree:!0}))}disconnectObserver(){this.observer&&=(this.observer.disconnect(),void 0)}flushDisconnectedTargets(){for(let[e,t]of this.targetDestroyListeners)if(this.isTargetDestroyed(e)){this.targetDestroyListeners.delete(e);for(let e of[...t])e()}this.targetDestroyListeners.size===0&&this.disconnectObserver()}};function Ud(e){return new Hd(e)}var Wd=(e,t)=>Ld(e).map(e=>t.resolveKey(e)),Gd=`fungi.app.ready`,Kd=`fungi.app.connect`,X=e=>V.pipe(z(H(1)),z(K(e))),qd=e=>R(X(e)),Jd=ya.pipe(z(Ka()),z(L(Number.isSafeInteger,{message:`Expected a safe integer`}))),Yd=Jd.pipe(z(Fa(0))),Xd=Jd.pipe(z(Ha(0))),Zd=I({appId:X(160),releaseId:X(160),surfaceId:X(160)}),Qd=I({editing:Ua,surface:F([X(160),to])}),$d=F([I({kind:U(`compose`),requestId:X(160),text:X(2e3)}),I({kind:U(`navigate`),requestId:X(160),params:W(I({key:X(64),value:X(4096)})).pipe(z(K(16)))})]),ef=B(G([`granted`,`missing`])),tf=I({"agent.list":ef,"agent.manage":ef,"agent.read":ef,"agent.send":ef,"computer.list":ef,"computer.readFile":ef,"computer.writeFile":ef,"computer.execute":ef,"git.repository":ef,"workflow.publish":ef,"workflow.arm":ef,"workflow.run":ef,"app.events.emit":ef,"llm.generation":ef,"media.generation":ef,"media.share":ef}),nf=G([`ready`,`missing`,`unknown`]),rf=I({models:nf,media:nf,git:nf,terminal:G([`ready`,`exec-only`,`missing`,`unknown`])}),af=G([`model`,`media`,`git`,`computer`]),of=G([`opened`,`unavailable`]),sf=I({computerId:F([X(256),to]),teamHasComputers:R(oo(Ua)),computerAccessGranted:R(Ua),setup:R(rf),permissions:R(tf),focus:Qd,openRequest:F([to,$d]),visibility:G([`visible`,`hidden`])}),cf=G([`connecting`,`connected`,`suspended`,`disconnected`,`disposing`,`disposed`]),lf=I({altKey:Ua,ctrlKey:Ua,id:X(160),key:X(64),metaKey:Ua,shiftKey:Ua}),uf=I({action:R(Ma),availability:R(Ma),category:X(160),description:qd(512),id:X(160),projections:R(Ma),title:X(160)}),df=I({arguments:R(Ma),commandId:X(321),origin:G([`agent`,`browser`,`keyboard`,`menu`,`palette`,`programmatic`,`slash`,`terminal`]),requestId:X(160)}),ff=F([I({result:R(Ma),status:U(`handled`)}),I({error:Ma,status:U(`failed`)})]),pf=e=>X(e).pipe(z(L(e=>{for(let t=0;t<e.length;t+=1)if(Cc(e.charCodeAt(t)))return!1;return!0},{message:`Expected one line of plain text`}))),mf={id:X(64),text:pf(80),end:B(Ua),priority:B(U(`low`))},hf=B(ya.pipe(z(Ka()),z(ma({minimum:0,maximum:9999})))),gf=W(F([I({...mf,kind:U(`text`),tone:B(G([`neutral`,`success`,`warning`,`error`]))}),I({...mf,kind:U(`button`),icon:B(G([`folder`,`ports`,`processes`,`access`])),count:hf,tone:B(G([`neutral`,`success`,`warning`,`error`])),busy:B(Ua),title:B(pf(1024)),disabled:B(Ua),opens:B(U(`dialog`)),expanded:B(Ua)}),I({...mf,kind:U(`toggle`),pressed:Ua}),I({...mf,kind:U(`menu`),count:hf,title:B(pf(1024)),options:W(I({id:X(64),text:pf(80),checked:B(Ua),disabled:B(Ua)})).pipe(z(K(16)),z(L(e=>new Set(e.map(e=>e.id)).size===e.length,{message:`Expected unique status option ids`})))})])).pipe(z(K(6)),z(L(e=>new Set(e.map(e=>e.id)).size===e.length,{message:`Expected unique status item ids`}))),_f=I({computerId:X(256),path:X(1024)}),vf=X(80).pipe(z(L(e=>e.trim()===e,{message:`Expected a trimmed title`}))),yf=X(64),bf=X(80),xf=e=>new Set(e.map(e=>e.id)).size===e.length,Sf=I({id:yf,label:bf,siblings:R(W(I({id:yf,label:bf})).pipe(z(K(16)),z(L(xf,{message:`Expected unique crumb sibling ids`}))))}),Cf=I({id:yf,label:bf,icon:R(U(`play`)),variant:R(G([`primary`,`outline`,`ghost`])),tone:R(U(`destructive`)),disabled:R(Ua)}),wf=e=>W(Cf).pipe(z(K(e)),z(L(xf,{message:`Expected unique header command ids`}))),Tf=I({id:yf,label:bf,presentation:R(U(`bead`)),tone:R(G([`neutral`,`info`,`warning`,`success`,`error`]))}),Ef={status:R(W(Tf).pipe(z(K(4)),z(L(xf,{message:`Expected unique header status ids`})))),crumbs:R(W(Sf).pipe(z(K(8)),z(L(xf,{message:`Expected unique crumb ids`})))),primary:R(wf(3)),menu:R(wf(12))},Df=I({contractVersion:U(1),canGoBack:Ua,title:R(vf),...Ef}),Of=I({canGoBack:Ua,title:R(V),...Ef}),kf=F([I({kind:U(`crumb`),crumbId:yf,siblingId:R(yf)}),I({kind:U(`action`),actionId:yf})]),Af=oo(I({agentId:X(256),sessionId:X(256)})),jf=e=>R(W(G(e)).pipe(z(K(e.length)))),Mf=I({agents:R(W(G([`agent.list`,`agent.manage`,`agent.read`,`agent.send`])).pipe(z(K(4)))),computers:R(W(G([`computer.list`,`computer.readFile`,`computer.writeFile`,`computer.execute`])).pipe(z(K(4)))),git:jf([`git.repository`]),workflows:jf([`workflow.publish`,`workflow.arm`,`workflow.run`]),events:jf([`app.events.emit`]),generation:jf([`llm.generation`,`media.generation`,`media.share`])}),Nf=G([`granted`,`declined`,`customize`]),Pf=I({message:X(512),tone:R(G([`info`,`success`,`warning`,`error`]))}),Ff=G(To);I({code:Ff.pick([`DELIVERY_PENDING`])});var If=I({code:Ff,message:X(512),retryable:Ua,need:B(wo)}),Lf=I({protocolVersion:U(2),type:U(Gd)}),Rf=I({epoch:X(160),protocolVersion:U(2),type:U(Kd)}),zf=I({epoch:X(160),protocolVersion:U(2)}),Bf={[Symbol.dispose]:R(Ma)},Vf=F([I({...Bf,ok:U(!0),value:Ma}),I({...Bf,error:If,ok:U(!1)})]);function Z(e,t,n=`PROTOCOL`){return Jr(ia(e,{onExcessProperty:`error`}),pr({onFailure:e=>{throw new J(`The peer sent malformed protocol data`,{cause:e,code:n,retryable:!1})},onSuccess:t}))}function Q(e){return Object.freeze(e)}function Hf(e,t){let n=e.arguments===void 0?void 0:x(e.arguments),r={origin:e.origin,signal:t};return n!==void 0&&Object.assign(r,{arguments:n}),Q(r)}var Uf=Z(uf,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}),Q(Pp(()=>m(t)))},`INVALID_ARGUMENT`),Wf=Z(X(321),e=>e),Gf=Z(df,e=>{let t=e.arguments===void 0?void 0:x(e.arguments),n={commandId:e.commandId,origin:e.origin,requestId:e.requestId};return t!==void 0&&Object.assign(n,{arguments:t}),Q(n)}),Kf=Z(F([qi,Ma]),e=>e===void 0?void 0:x(e)),qf=Z(Rf,e=>Q(e));Z(zf,e=>Q(e));var Jf=Z(sf,e=>{let t={computerId:e.computerId,focus:Q({...e.focus}),openRequest:e.openRequest===null?null:Q({...e.openRequest}),visibility:e.visibility};return e.teamHasComputers!==void 0&&(t.teamHasComputers=e.teamHasComputers),e.computerAccessGranted!==void 0&&(t.computerAccessGranted=e.computerAccessGranted),e.setup!==void 0&&(t.setup=Q({...e.setup})),e.permissions!==void 0&&(t.permissions=Q({...e.permissions})),Q(t)}),Yf=Z(If,e=>Q({...e})),Xf=Z(Qd,e=>Q({...e}),`INVALID_ARGUMENT`),Zf=Z(Zd,e=>Q({...e})),Qf=Z(cf,e=>e),$f=Z(gf,e=>Q(e.map(e=>e.kind===`menu`?Q({...e,options:Q(e.options.map(e=>Q(e)))}):Q(e))),`INVALID_ARGUMENT`),ep=Z(I({itemId:X(64),optionId:B(X(64)),anchor:B(I({start:ya.pipe(z(ma({minimum:0,maximum:1e5}))),width:ya.pipe(z(ma({minimum:0,maximum:1e5})))}))}),e=>Q(e.anchor===void 0?{...e}:{...e,anchor:Q({...e.anchor})}),`INVALID_ARGUMENT`),tp=Z(_f,e=>Q({...e}),`INVALID_ARGUMENT`);function np(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}),Q(t)}function rp(e){let t={id:e.id,label:e.label};return e.siblings===void 0?Q(t):Q({...t,siblings:Q(e.siblings.map(e=>Q({...e})))})}function ip(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}),Q(t)}function ap(e){let t={canGoBack:e.canGoBack};return e.title!==void 0&&(t={...t,title:e.title}),e.crumbs!==void 0&&(t={...t,crumbs:Q(e.crumbs.map(rp))}),e.primary!==void 0&&(t={...t,primary:Q(e.primary.map(ip))}),e.menu!==void 0&&(t={...t,menu:Q(e.menu.map(ip))}),e.status!==void 0&&(t={...t,status:Q(e.status.map(np))}),Q(t)}var op=Z(Df,ap,`INVALID_ARGUMENT`),sp=Z(Of,e=>{let t=e.title?.trim();return cp({...ap({...e,title:t===void 0||t.length===0?void 0:t}),contractVersion:1})},`INVALID_ARGUMENT`),cp=Z(Df,e=>Q({...ap(e),contractVersion:1}),`INVALID_ARGUMENT`),lp=Z(kf,e=>e.kind===`action`?Q({...e}):Q(e.siblingId===void 0?{kind:e.kind,crumbId:e.crumbId}:e),`INVALID_ARGUMENT`),up=Z(Af,e=>e===null?null:Q({...e}),`INVALID_ARGUMENT`),dp=Z(Mf,e=>Q({agents:Q([...new Set(e.agents??[])]),computers:Q([...new Set(e.computers??[])]),...e.git&&{git:Q([...new Set(e.git)])},...e.workflows&&{workflows:Q([...new Set(e.workflows)])},...e.events&&{events:Q([...new Set(e.events)])},...e.generation&&{generation:Q([...new Set(e.generation)])}}),`INVALID_ARGUMENT`),fp=Z(af,e=>e,`INVALID_ARGUMENT`);Z(Lf,e=>Q(e));var pp=Z(X(512),e=>e),mp=Z(Pf,e=>Q({...e}),`INVALID_ARGUMENT`);Z(I({id:X(160),repeat:Ua}),e=>Q(e));var hp=Z(W(lf).pipe(z(K(64))),e=>{if(new Set(e.map(e=>e.id)).size!==e.length)throw new J(`Reserved chords are invalid`,{code:`PROTOCOL`,retryable:!1});return Q(e.map(e=>Q({...e})))});function gp(e){return Z(I({value:Ma,version:Yd}),t=>Q({value:e(t.value),version:t.version}))}var _p=gp(Jf),vp=Z(I({capabilities:W(Ma).pipe(z(K(128))),context:Ma}),e=>Q({capabilities:Q(e.capabilities.map(e=>wp(e))),context:_p(e.context)})),yp=gp(Qf),bp=gp(hp),xp=gp(pp),Sp=Jr(yp,e=>{if(e.value!==`connected`&&e.value!==`suspended`)throw new J(`The host lifecycle is invalid`,{code:`PROTOCOL`,retryable:!1});return Q({value:e.value,version:e.version})});function Cp(e){return Z(I({handle:Ma,id:X(160),version:Xd}),t=>{if(!(t.handle instanceof bc)&&!(e&&t.handle instanceof xc))throw new J(`A capability handle is invalid`,{code:`PROTOCOL`,retryable:!1});return Q({handle:t.handle,id:t.id,version:t.version})})}var wp=Cp(!1),Tp=Cp(!0);function Ep(e){let t=e?Tp:wp;return Z(I({capabilities:W(Ma).pipe(z(K(128))),context:Ma,identity:Ma,lifecycle:Ma,reservedChords:Ma,theme:Ma}),e=>Q({capabilities:Q(e.capabilities.map(e=>t(e))),context:_p(e.context),identity:Zf(e.identity),lifecycle:Sp(e.lifecycle),reservedChords:bp(e.reservedChords),theme:xp(e.theme)}))}var Dp=Ep(!1);Ep(!0);function Op(e){return Z(Vf,t=>t.ok?Q({ok:!0,value:e(t.value)}):Q({ok:!1,error:Yf(t.error)}))}var kp=Op(Dp),Ap=Op(Z(I({commandId:X(321)}),e=>Q(e)));Op(Z(ff,e=>{if(e.status===`failed`)return Q({status:`failed`,error:Pp(()=>Pn(e.error))});let t=e.result===void 0?void 0:x(e.result);return Q(t===void 0?{status:`handled`}:{status:`handled`,result:t})}));var jp=Op(Z(qi,()=>void 0)),Mp=Op(Z(Nf,e=>e)),Np=Op(Z(of,e=>e));Op(Z(Ua,e=>e)),Op(Z(Ua,e=>e));function Pp(e){try{return e()}catch(e){throw new J(`The command metadata is invalid`,{cause:e,code:`INVALID_ARGUMENT`,retryable:!1})}}var Fp=F([I({kind:U(`saveFile`),name:X(255).pipe(z(Pa(/^[^\p{Cc}/\\]+$/u))),mime:X(255),bytes:ki}),I({kind:U(`copyText`),text:V})]);function Ip(e){let t=ia(Fp,{onExcessProperty:`error`})(e);if(or(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 Lp=Op(Z(F([I({kind:U(`saved`)}),I({kind:U(`copied`)}),I({kind:U(`refused`),reason:G([`no-user-gesture`,`too-large`,`invalid-request`,`unavailable`,`denied`,`busy`])})]),e=>Q(e)));function Rp(e){return e instanceof J?{code:e.code,message:Bp(e.message),retryable:e.retryable,...e.need!==void 0&&{need:e.need}}:{code:`HOST_FAILURE`,message:`Host operation failed`,retryable:!1}}function zp(e){try{let t=Yf(e);return new J(t.message,{code:t.code,retryable:t.retryable,...t.need!==void 0&&{need:t.need}})}catch(e){return new J(`The host returned a malformed error`,{cause:e,code:`PROTOCOL`,retryable:!1})}}function Bp(e){return e.trim().slice(0,512)||`Host operation failed`}var Vp=e=>({ok:!0,value:e}),Hp=e=>({error:Rp(e),ok:!1});async function Up(e,t){let n,r=new Set;try{return n=await e,Wp(t(n))}catch(e){throw Gp(e)&&Kp(e,r),e instanceof J?e:new J(`The remote operation failed`,{cause:e,code:`HOST_FAILURE`,retryable:!0})}finally{n!==e&&Gp(n)&&Kp(n,r)}}function Wp(e){if(e.ok)return e.value;throw zp(e.error)}function Gp(e){return _i(e)&&Symbol.dispose in e&&Br(e[Symbol.dispose])}function Kp(e,t){if(!t.has(e)){t.add(e);try{e[Symbol.dispose]()}catch(e){console.warn(`RPC result disposal failed`,e)}}}function qp(){let e=[],t=new Set;return{get:()=>e,subscribe:e=>(t.add(e),()=>t.delete(e)),update:n=>{e=n;for(let e of Array.from(t))try{e()}catch(e){console.warn(`App binding subscriber failed`,e)}}}}function Jp(e){let t=hp(e),n=new Set;return{get:()=>t,subscribe:e=>(n.add(e),()=>n.delete(e)),update:e=>{t=hp(e);for(let e of Array.from(n))try{e()}catch(e){console.warn(`Reserved chord subscriber failed`,e)}}}}function Yp(e){let t=!0,n,r=e.window.document.querySelector(`html`);if(!r)return()=>{t=!1};let i=Ud(r),a=new ad(i);Td(a),jd(a),a.prependEventMatchResolver(Wd);let o=Zp(e.onBroken),s=tm(a,e.chords,e.remote,o),c=Xp(e,o,()=>t,e=>{n=e},()=>n),l=i.onFocusChange(()=>{queueMicrotask(c)}),u=()=>{queueMicrotask(c)};e.window.addEventListener(`focus`,u),e.window.addEventListener(`blur`,u);let d=e.bindings,f=()=>Qp(e.window.document,e.identity.surfaceId).editing,p=d===void 0?()=>void 0:$p(a,d,f),m=d===void 0?()=>void 0:d.subscribe(()=>{p(),p=$p(a,d,f)}),h=e.chords.subscribe(()=>{s(),s=tm(a,e.chords,e.remote,o)});return queueMicrotask(c),()=>{t&&(t=!1,l(),e.window.removeEventListener(`focus`,u),e.window.removeEventListener(`blur`,u),h(),s(),m(),p())}}function Xp(e,t,n,r,i){return()=>{if(!n())return;let a=Qp(e.window.document,e.identity.surfaceId),o=i();(a.editing!==o?.editing||a.surface!==o.surface)&&(r(a),t(()=>e.remote.reportFocus(a)))}}function Zp(e){return t=>{try{Up(t(),jp).catch(t=>{Xo(`browser-bridge.host-call`,t),e(t)})}catch(t){Xo(`browser-bridge.host-call`,t),e(t)}}}function Qp(e,t){let n=e.activeElement;return Xf({editing:!!(n?.matches(`input, textarea, select, [contenteditable='true']`)===!0||n?.closest(`[contenteditable='true']`)),surface:e.hasFocus()?t:null})}function $p(e,t,n){let r=t.get();return e.registerLayer({bindings:r.map((e,t)=>({cmd:`app/${String(t)}`,key:e.key})),commands:r.map((e,t)=>({name:`app/${String(t)}`,run:t=>{let r=t.event.originalEvent;if(r?.defaultPrevented||r?.isComposing||em(e.key)&&n())return!1;e.run()}})),priority:500})}function em(e){return!/(?:^|\+)(?:ctrl|control|super|meta|cmd|alt|option|mod)\+/iu.test(e)}function tm(e,t,n,r){let i=t.get();return e.registerLayer({bindings:i.map(e=>({cmd:`reserved/${e.id}`,key:{ctrl:e.ctrlKey,meta:e.altKey,name:Bd(e.key),shift:e.shiftKey,super:e.metaKey}})),commands:i.map(e=>({name:`reserved/${e.id}`,run:t=>{let i=t.event.originalEvent;if(i?.defaultPrevented||i?.isComposing)return!1;r(()=>n.invokeReservedChord(e.id,i?.repeat??!1))}})),priority:1e3})}function nm(e){let t=t=>{if(t.defaultPrevented||t.isComposing)return;let n=am(t,e.mac);n!==null&&(t.preventDefault(),n===`back`&&!t.repeat&&e.canGoBack()&&e.back())},n=t=>{let n=im(t.button);if(n===null)return;let r=t.defaultPrevented;t.preventDefault(),t.type===`mouseup`&&n===`back`&&!r&&e.canGoBack()&&e.back()};e.window.addEventListener(`keydown`,t);for(let t of rm)e.window.addEventListener(t,n);return()=>{e.window.removeEventListener(`keydown`,t);for(let t of rm)e.window.removeEventListener(t,n)}}var rm=[`mousedown`,`mouseup`,`auxclick`];function im(e){return e===3?`back`:e===4?`forward`:null}function am(e,t){return e.shiftKey||e.ctrlKey?null:t?!e.metaKey||e.altKey?null:e.key===`[`?`back`:e.key===`]`?`forward`:om(e.target)?null:e.key===`ArrowLeft`?`back`:e.key===`ArrowRight`?`forward`:null:!e.altKey||e.metaKey?null:e.key===`ArrowLeft`?`back`:e.key===`ArrowRight`?`forward`:null}function om(e){return e instanceof HTMLElement?e.isContentEditable||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement:!1}function sm(){return!$n(globalThis.navigator)&&/Mac|iPhone|iPad/u.test(globalThis.navigator.userAgent)}function cm(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 lm(e){let t=new Map,n=cm(0),r=!1,i=e=>{let t=new Map;try{for(let n of e){let e=wp(n),r=pm(e.id,e.version);if(t.has(r))throw dm(e.handle),new J(`Duplicate capability grant`,{code:`PROTOCOL`,retryable:!1});t.set(r,e.handle)}}catch(e){for(let e of t.values())dm(e);throw e}return t};for(let[n,r]of i(e))t.set(n,r);let a=e=>{for(let t of e)dm(t)},o=e=>{if(r)throw new J(`The app connection is disposed`,{code:`DISCONNECTED`,retryable:!0});let n=pm(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 J(`The capability is not granted`,{code:`CAPABILITY_DENIED`,retryable:!1});try{return e.schema.parse(t)}catch(e){throw new J(`The capability interface is malformed`,{cause:e,code:`PROTOCOL`,retryable:!1})}}}),replace(e){if(r)throw new J(`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 um=gr().transform(e=>{let t=qn(Object).safeParse(e);if(!t.success)return;let n=Object.create(t.data),r=zi(I({[Symbol.dispose]:R(ua(Function))}))(n);return{owner:t.data,dispose:r[Symbol.dispose]}});function dm(e){try{let t=um.parse(e);if(t===void 0||fm.has(t.owner))return;fm.add(t.owner),t.dispose?.call(t.owner)}catch(e){console.warn(`RPC value disposal failed`,e)}}var fm=new WeakSet;function pm(e,t){return`${e}@${String(t)}`}var mm=[];for(let e=0;e<256;++e)mm.push((e+256).toString(16).slice(1));function hm(e,t=0){return(mm[e[t+0]]+mm[e[t+1]]+mm[e[t+2]]+mm[e[t+3]]+`-`+mm[e[t+4]]+mm[e[t+5]]+`-`+mm[e[t+6]]+mm[e[t+7]]+`-`+mm[e[t+8]]+mm[e[t+9]]+`-`+mm[e[t+10]]+mm[e[t+11]]+mm[e[t+12]]+mm[e[t+13]]+mm[e[t+14]]+mm[e[t+15]]).toLowerCase()}var gm,_m=new Uint8Array(16);function vm(){if(!gm){if(typeof crypto>`u`||!crypto.getRandomValues)throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);gm=crypto.getRandomValues.bind(crypto)}return gm(_m)}var ym={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function bm(e,t,n){if(ym.randomUUID&&!t&&!e)return ym.randomUUID();e||={};let r=e.random??e.rng?.()??vm();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return hm(r)}var xm=Zn({version:`v7`}),Sm=P().regex(/^replay_[a-f0-9]{64}$/);li(e=>Sm.safeParse(e).success);var Cm=Zn({version:`v4`});li(e=>xm.safeParse(e).success);var wm=li(e=>Cm.safeParse(e).success);function Tm(){return wm.parse(bm())}var Em=class extends xc{#e=!0;#t;#n=new Map;constructor(e){super(),this.#t=e}cancel(e){try{return this.#n.get(Wf(e))?.abort(),Promise.resolve(Vp(void 0))}catch(e){return Promise.resolve(Hp(e))}}dispose(){if(this.#e){this.#e=!1;for(let e of this.#n.values())e.abort();this.#n.clear()}}async invoke(e){try{if(!this.#e)throw new J(`The command is disposed`,{code:`DISCONNECTED`,retryable:!0});let t=Gf(e);if(this.#n.has(t.requestId))throw new J(`Duplicate command request`,{code:`PROTOCOL`,retryable:!1});if(this.#n.size>=64)throw new J(`Too many command requests`,{code:`HOST_FAILURE`,retryable:!0});let n=new AbortController;this.#n.set(t.requestId,n);try{let e=Kf(await this.#t(Hf(t,n.signal)));return Vp(e===void 0?{status:`handled`}:{status:`handled`,result:e})}finally{this.#n.delete(t.requestId)}}catch(e){if(e instanceof At)try{let t={code:e.code,message:e.message,details:e.details};return Vp({status:`failed`,error:Pn(t)})}catch(e){return Hp(e)}return Hp(e)}}[Symbol.dispose](){this.dispose()}};function Dm(e){let t=[];for(let n of e.values()){let{commandId:e,definition:r,target:i}=n;if(e===void 0)continue;let a=r.availability?.status!==`unavailable`;for(let n of r.projections?.bindings?.values??[])n.trim().includes(` `)||n.startsWith(`<`)||t.push({key:n,run:()=>{a&&Promise.resolve().then(async()=>{let t=Wp(await i.invoke({commandId:e,origin:`keyboard`,requestId:Tm()}));if(t.status===`failed`)throw new At(t.error.code,t.error.message,t.error.details)}).catch(e=>{console.warn(`App key command failed`,e)})}})}return t}function Om(e,t,n,r){let i=new Map,a=!1,o=()=>{r?.update(a?[]:Dm(i))},s=e=>{try{n()}catch(t){console.warn(`App command failure callback failed`,t,e)}},c=e=>{try{Up(e(),jp).catch(e=>{s(e)})}catch(e){console.warn(`App command RPC supervision failed`,e),s(e)}};return{commands:Am(e,t,i,()=>a,t=>{let n=i.get(t);if(!n)return;i.delete(t),n.target.dispose(),o();let r=n.commandId;!a&&r!==void 0&&c(()=>e.unregisterCommand(r))},o),dispose(){if(!a){a=!0;for(let e of i.values())e.target[Symbol.dispose]();i.clear(),o()}}}}function km(e,t,n){let r=t.id;if(e.size>=128||e.has(r))throw n.dispose(),new J(`Command registration is unavailable`,{code:`INVALID_ARGUMENT`,retryable:!1});let i={commandId:void 0,definition:t,target:n};e.set(r,i);let a=!1;return{commit(e){a||(i.commandId=e)},release(){a||(a=!0,e.get(r)===i&&e.delete(r),n.dispose())},target:n}}function Am(e,t,n,r,i,a){return Object.freeze({async register(o,s){if(t(),!Br(s))throw new J(`Command handler must be a function`,{code:`INVALID_ARGUMENT`,retryable:!1});let c=Uf(o),l=new Em(s),u=km(n,c,l);try{let t=await jm(e,c,u.target);r()&&await Mm(e,t.commandId,l),u.commit(t.commandId),a()}catch(e){throw u.release(),e}let d=!0;return()=>{d&&(d=!1,i(c.id))}}})}async function jm(e,t,n){return Up(e.registerCommand(t,n),Ap)}async function Mm(e,t,n){throw n.dispose(),await Up(e.unregisterCommand(t),jp),new J(`The command controller is disposed`,{code:`DISCONNECTED`,retryable:!0})}var Nm=Yi(e=>e instanceof bc),Pm=class extends xc{#e=!1;#t;constructor(e){super(),this.#t=e}disconnect(e){try{if(this.#e)throw Gm();let t=e===void 0?void 0:Yf(e);return setTimeout(()=>this.#t.disconnect?.(t??Ym()),0),Promise.resolve(Vp(void 0))}catch(e){return Promise.resolve(Hp(e))}}async requestClose(){try{if(this.#e)throw Gm();return Vp(await(this.#t.beforeClose?.()??!0))}catch(e){return Hp(e)}}async requestBack(){try{if(this.#e)throw Gm();return Vp(await(this.#t.back?.()??!1))}catch(e){return Hp(e)}}async activateNavigation(e){try{if(this.#e)throw Gm();let t=lp(e);return Tc(this.#t.navigation,t)?Vp(await(this.#t.activate?.(t)??!1)):Vp(!1)}catch(e){return Hp(e)}}async activateStatus(e){try{if(this.#e)throw Gm();let t=ep(e);return wc(this.#t.statusItems,t)?Vp(await(this.#t.statusAction?.(t)??!1)):Vp(!1)}catch(e){return Hp(e)}}[Symbol.dispose](){this.#e=!0}async updateContext(e){return this.#e?Hp(Gm()):this.#n(e,`context`,Jf,e=>{this.#t.context.update(e)})}reconfigure(e){let t=[];try{if(this.#e)throw Gm();let n=vp(e);if(n.context.version<=this.#t.versions.context)return Promise.resolve(Vp(void 0));for(let e of n.capabilities)t.push({...e,handle:zi(Nm)(e.handle).dup()});if(!this.#t.capabilities)throw Gm();return this.#t.capabilities.replace(t),t=[],this.#t.versions.context=n.context.version,this.#t.context.update(n.context.value),Promise.resolve(Vp(void 0))}catch(e){for(let e of t)dm(e.handle);return Promise.resolve(Hp(e))}}updateLifecycle(e){try{if(this.#e)throw Gm();let t=gp(Qf)(e);if(t.version<=this.#t.versions.lifecycle)return Promise.resolve(Vp(void 0));if(!Xm(this.#t.lifecycle.get(),t.value))throw new J(`The host sent an invalid lifecycle transition`,{code:`PROTOCOL`,retryable:!1});return this.#t.versions.lifecycle=t.version,this.#t.lifecycle.update(t.value),Promise.resolve(Vp(void 0))}catch(e){return Promise.resolve(Hp(e))}}async updateReservedChords(e){return this.#e?Hp(Gm()):this.#n(e,`chords`,hp,e=>{this.#t.chords.update(e)})}async updateTheme(e){return this.#e?Hp(Gm()):this.#n(e,`theme`,pp,e=>{this.#t.theme.update(e)})}#n(e,t,n,r){try{let i=gp(n)(e);return i.version>this.#t.versions[t]&&(this.#t.versions[t]=i.version,r(i.value)),Promise.resolve(Vp(void 0))}catch(e){return Promise.resolve(Hp(e))}}};async function Fm(e){let t=zm(),n=new Pm(t),r=Sc(e.port,n),i,a=Rm(r);try{performance.mark(`fungi.app-open.agar-rpc-connect-start`);let o=await Promise.race([r.connect({epoch:e.epoch,protocolVersion:2}),a]);performance.mark(`fungi.app-open.agar-rpc-connect-ready`),i=o;let s=Wp(kp(o));if(!e.isActive())throw Lm();let c=Bm({bootstrap:s,bootstrapOwner:i,options:e,remote:r,state:t,target:n});return performance.mark(`fungi.app-open.agar-root-created`),i=void 0,c}catch(t){return Qm(t,e,n,r,i)}}function Im(e,t){e.context.update(t.context.value),e.theme.update(t.theme.value),e.lifecycle.update(t.lifecycle.value),e.chords.update(t.chords.value),e.versions.context=t.context.version,e.versions.theme=t.theme.version,e.versions.lifecycle=t.lifecycle.version,e.versions.chords=t.chords.version}function Lm(){return new J(`App connection was cancelled`,{code:`CANCELLED`,retryable:!1})}function Rm(e){let t,n=new Promise((e,n)=>{t=n});return n.catch(e=>{Xo(`app-session.rpc-disconnect`,e)}),e.onRpcBroken(()=>t?.(new J(`The app host disconnected`,{code:`DISCONNECTED`,retryable:!0}))),n}function zm(){return{statusItems:[],navigation:{canGoBack:!1},bindings:qp(),chords:Jp([]),context:cm({computerId:null,focus:{editing:!1,surface:null},openRequest:null,visibility:`hidden`}),lifecycle:cm(`connecting`),theme:cm(`default`),canGoBack:!1,versions:{chords:-1,context:-1,lifecycle:-1,theme:-1}}}function Bm(e){let t=Zf(e.bootstrap.identity),n=Zm(e.bootstrap);Im(e.state,n);let r=lm(e.bootstrap.capabilities);return e.state.capabilities=r,Hm(e,t,r)}function Vm(e,t,n){return Yp({bindings:e.state.bindings,chords:e.state.chords,identity:t,onBroken:e=>{n({code:`DISCONNECTED`,message:e instanceof J?e.message:`The app host rejected a browser bridge operation`,retryable:!0})},remote:e.remote,window:e.options.window})}function Hm(e,t,n){let r=!1,i=t=>{r||(r=!0,qm([()=>{t&&e.state.lifecycle.update(`disconnected`)},()=>{e.state.lifecycle.update(`disposing`)},l,u,()=>{o.dispose()},()=>{e.state.beforeClose=void 0,e.state.back=void 0,e.state.activate=void 0,e.state.statusAction=void 0},()=>{n.disconnect()},()=>{e.target[Symbol.dispose]()},()=>{dm(e.bootstrapOwner)},()=>{dm(e.remote)},()=>{e.options.port.close()},()=>{e.state.lifecycle.update(`disposed`)},e.options.onDisposed],`app connection disposal`))},a=()=>{if(r)throw new J(`The app connection is disposed`,{code:`DISCONNECTED`,retryable:!0})},o=Om(e.remote,a,()=>{i({code:`DISCONNECTED`,message:`The app host rejected a terminal command operation`,retryable:!0})},e.state.bindings),s=Wm(e.remote,a,e.state),c=Um(e.state,e.remote,a),l=Vm(e,t,i),u=nm({window:e.options.window,mac:sm(),canGoBack:()=>e.state.canGoBack&&e.state.back!==void 0,back:()=>{let t=e.state.back;t&&Promise.resolve().then(t).catch(e=>{Xo(`app-window.back-input`,e)})}});return e.state.disconnect=i,e.remote.onRpcBroken(()=>{Km(i)}),Jm({capabilities:n.directory,commands:o.commands,context:e.state.context,dispose:i,identity:t,lifecycle:e.state.lifecycle,theme:e.state.theme,ui:s,window:c})}function Um(e,t,n){let r=Object.freeze({async publish(r){n();let i=sp(r);e.canGoBack=i.canGoBack,e.navigation=op(i),await Up(t.reportNavigation(i),jp)},onActivate(t){if(n(),e.activate!==void 0)throw new J(`The App already owns navigation activations`,{code:`INVALID_ARGUMENT`,retryable:!1});e.activate=t;let r=!1;return()=>{r||(r=!0,e.activate===t&&(e.activate=void 0))}},onBack(t){if(n(),e.back!==void 0)throw new J(`The App already owns Back requests`,{code:`INVALID_ARGUMENT`,retryable:!1});e.back=t;let r=!1;return()=>{r||(r=!0,e.back===t&&(e.back=void 0))}}});return Object.freeze({navigation:r,onBeforeClose(t){if(n(),e.beforeClose!==void 0)throw new J(`The App already owns a close consultation`,{code:`INVALID_ARGUMENT`,retryable:!1});e.beforeClose=t;let r=!1;return()=>{r||(r=!0,e.beforeClose===t&&(e.beforeClose=void 0))}}})}function Wm(e,t,n){return Object.freeze({async requestComputerChoice(){t(),await Up(e.requestComputerChoice(),jp)},async requestBrowserAction(n){t();let r=Ip(n);return r.kind===`refused`?r:await Up(e.requestBrowserAction(r),Lp)},onStatusAction(e){if(t(),n.statusAction!==void 0)throw new J(`The App already owns its status actions`,{code:`INVALID_ARGUMENT`,retryable:!1});n.statusAction=e;let r=!1;return()=>{r||(r=!0,n.statusAction===e&&(n.statusAction=void 0))}},async requestAppPermissions(n){return t(),await Up(e.requestAppPermissions(dp(n)),Mp)},async openDesktopSettings(){t(),await Up(e.openDesktopSettings(),jp)},async openSetup(n){return t(),await Up(e.openSetup(fp(n)),Np)},async openTeamBilling(){t(),await Up(e.openTeamBilling(),jp)},async openNavigation(n){t(),await Up(e.openNavigation(tp(n)),jp)},async reportStatus(r){t();let i=$f(r);n.statusItems=i,await Up(e.reportStatus(i),jp)},async reportAgentSessionSelection(n){t(),await Up(e.reportAgentSessionSelection(up(n)),jp)},async showToast(n){t(),await Up(e.showToast(mp(n)),jp)}})}function Gm(){return new J(`The app connection is disposed`,{code:`DISCONNECTED`,retryable:!0})}function Km(e){e({code:`DISCONNECTED`,message:`The app host disconnected`,retryable:!0})}function qm(e,t){for(let n of e)try{n()}catch(e){console.warn(`${t} cleanup failed`,e)}}function Jm(e){return Object.freeze(e)}function Ym(){return{code:`DISCONNECTED`,message:`The app host disconnected`,retryable:!1}}function Xm(e,t){return e===t||e===`connected`&&t===`suspended`||e===`suspended`&&t===`connected`}function Zm(e){let t=gp(Jf)(e.context),n=gp(pp)(e.theme),r=gp(Qf)(e.lifecycle),i=gp(hp)(e.reservedChords);if(r.value!==`connected`&&r.value!==`suspended`)throw new J(`The bootstrap lifecycle is invalid`,{code:`PROTOCOL`,retryable:!1});return{chords:i,context:t,lifecycle:r,theme:n}}function Qm(e,t,n,r,i){throw qm([()=>{n[Symbol.dispose]()},()=>{i&&dm(i)},()=>{dm(r)},()=>{t.port.close()},t.onDisposed],`app connection rejection`),e instanceof J?e:new J(`Unable to establish the app RPC session`,{cause:e,code:`PROTOCOL`,retryable:!1})}var $m=!1,eh=class{options;#e;#t;#n=!1;#r;#i;constructor(e){this.options=e,this.#e=globalThis.window}start(){performance.mark(`fungi.app-open.agar-connect-start`);let e=this.#l();return e?Promise.reject(e):($m=!0,this.#a())}#a(){return new Promise((e,t)=>{let n=(n,a)=>{this.#o(n,a,i,r,e,t)},r=()=>{n(nh())},i=e=>{this.#s(e,n,i)};this.#e.addEventListener(`message`,i),this.options.signal?.addEventListener(`abort`,r,{once:!0});let a=()=>{try{performance.mark(`fungi.app-open.agar-ready-sent`),this.#e.parent.postMessage({protocolVersion:2,type:Gd},`*`)}catch(e){Xo(`connect.notify-host`,e),n(ch(e))}};this.#r=setInterval(a,200),this.#i=setTimeout(()=>{n(ih())},1e4),a()})}#o(e,t,n,r,i,a){if(!this.#n){if(this.#n=!0,this.#c(),this.#e.removeEventListener(`message`,n),this.options.signal?.removeEventListener(`abort`,r),e||!t){this.#t?.close(),$m=!1,a(e??ih());return}i(t)}}#s(e,t,n){if(!sh(e.data))return;if(performance.mark(`fungi.app-open.agar-connect-received`),e.source!==this.#e.parent||ah(e.origin)===void 0){t(oh());return}let r=lh(e,t);if(!r)return;let i=e.ports.length===1?e.ports[0]:void 0;if(!i){t(uh(`The app host did not transfer exactly one port`));return}this.#t=i,this.#c(),this.#e.removeEventListener(`message`,n),Fm({epoch:r.epoch,isActive:()=>!this.#n,onDisposed:()=>{$m=!1},port:i,window:this.#e}).then(e=>{performance.mark(`fungi.app-open.agar-root-ready`),t(void 0,e)},e=>{t(rh(e))})}#c(){clearInterval(this.#r),clearTimeout(this.#i),this.#r=void 0,this.#i=void 0}#l(){if(this.options.signal?.aborted)return nh();if($m)return new J(`An app connection is already live`,{code:`IDENTITY`,retryable:!1});if($n(globalThis.window)||this.#e.parent===this.#e)return new J(`The app host is unavailable`,{code:`DISCONNECTED`,retryable:!0})}};function th(e){return new eh(e).start()}function nh(){return new J(`App connection was cancelled`,{code:`CANCELLED`,retryable:!1})}function rh(e){return e instanceof J?e:new J(`Unable to connect to the app host`,{cause:e,code:`PROTOCOL`,retryable:!1})}function ih(){return new J(`The app host disconnected`,{code:`DISCONNECTED`,retryable:!0})}function ah(e){if(!URL.canParse(e))return;let t=new URL(e).origin;return t===e?t:void 0}function oh(){return new J(`The app connection identity is invalid`,{code:`IDENTITY`,retryable:!1})}var sh=ca(I({type:U(Kd)}));function ch(e){return new J(`Unable to notify the app host`,{cause:e,code:`DISCONNECTED`,retryable:!0})}function lh(e,t){try{return qf(e.data)}catch(e){Xo(`connect.decode-message`,e),t(e instanceof J?e:new J(`Malformed app connection`,{cause:e,code:`PROTOCOL`,retryable:!1}));return}}function uh(e){return new J(e,{code:`PROTOCOL`,retryable:!1})}function dh(e,t,n){e.style.isolation=`isolate`;let r=(0,Yo.createRoot)(e),i=new AbortController,a=e.ownerDocument.documentElement,o=jo(a),s,c,l,u=!1,d=e=>{let i=(0,q.createElement)(fh,{state:e,render:n});r.render(t.queryClient?(0,q.createElement)(St,{client:t.queryClient},i):i)},f=()=>{l?.(),l=void 0,c?.(),c=void 0;let e=s;s=void 0,e?.dispose(),u&&=(o===null?a.removeAttribute(`data-theme`):Ao(o,a),!1)},{defaultView:p}=e.ownerDocument;return performance.mark(`fungi.app-open.react-root-render-start`),p?p.parent===p?d({app:null,status:`standalone`}):(d({app:null,status:`connecting`}),th({host:`parent`,signal:i.signal}).then(e=>{if(i.signal.aborted){e.dispose();return}s=e;let t=()=>{let t=e.lifecycle.get();return t===`disposing`||t===`disconnected`||t===`disposed`?(f(),d({app:null,status:`ended`}),!0):!1};l=e.lifecycle.subscribe(t),!t()&&(u=!0,Ao(e.theme.get(),a),c=e.theme.subscribe(e=>{Ao(e,a)}),d({app:e,status:`live`}))}).catch(e=>{i.signal.aborted&&e instanceof J&&e.code===`CANCELLED`||(console.error(`${t.name} host connection failed`,e),f(),i.signal.aborted||d({app:null,status:`not-hosted`,error:e instanceof J?e:new J(`The App host is unavailable`,{cause:e,code:`HOST_FAILURE`,retryable:!0})}))})):d({app:null,status:`not-hosted`,error:new J(`The App document has no window`,{code:`DISCONNECTED`,retryable:!1})}),()=>{i.signal.aborted||(i.abort(),r.unmount(),f())}}function fh({state:e,render:t}){return(0,q.useLayoutEffect)(()=>{performance.mark(`fungi.app-open.react-initial-commit`)},[]),(0,q.useLayoutEffect)(()=>{e.app&&performance.mark(`fungi.app-open.react-connected-commit`)},[e.app]),(0,q.createElement)(q.Fragment,null,e.status===`not-hosted`?(0,q.createElement)(`p`,{role:`alert`},`App host connection unavailable. Open this App through its host to try again.`):null,t(e))}function ph(e){let t=(0,q.useCallback)(t=>e?.subscribe(t)??(()=>void 0),[e]),n=(0,q.useCallback)(()=>e?.get(),[e]);return(0,q.useSyncExternalStore)(t,n,n)}function mh(e){return ph(e?.context)??null}function hh(e,t,n,r){let i=(0,q.useRef)(t);i.current=t;let a=(0,q.useRef)(n);a.current=n;let o=(0,q.useRef)(r);o.current=r;let s=JSON.stringify(t),c=n!==void 0;(0,q.useEffect)(()=>{e&&e.ui.reportStatus(i.current).catch(e=>{o.current?o.current(e):console.error(`Window status report failed`,e)})},[e,s]),(0,q.useEffect)(()=>{if(!(!e||!c))return e.ui.onStatusAction(e=>a.current?.(e)??!1)},[e,c]),(0,q.useEffect)(()=>()=>{e?.ui.reportStatus([]).catch(e=>{console.error(`Window status report failed`,e)})},[e])}function gh(e,{canGoBack:t,title:n,crumbs:r,primary:i,menu:a,status:o,onBack:s,onCrumb:c,onAction:l}){let u=(0,q.useRef)(s),d=(0,q.useRef)(c),f=(0,q.useRef)(l);(0,q.useEffect)(()=>{u.current=s,d.current=c,f.current=l},[s,c,l]),(0,q.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(),_h(e,{canGoBack:!1})}},[e]);let p=JSON.stringify([r,i,a,o]),m=(0,q.useRef)({crumbs:r,primary:i,menu:a,status:o});(0,q.useEffect)(()=>{m.current={crumbs:r,primary:i,menu:a,status:o}},[r,i,a,o]),(0,q.useEffect)(()=>{if(!e)return;let r={canGoBack:t};n!==void 0&&(r={...r,title:n});let i=m.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}),_h(e,r)},[e,t,n,p])}function _h(e,t){e.publish(t).catch(e=>{e instanceof J&&e.code===`DISCONNECTED`||console.warn(`App navigation report failed`,e)})}var vh=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 yh(e,t,n){return new vh(e,t,n)}function bh(e){let t=Dr(e),n=qn(Object),r=Dr(Object.fromEntries(Object.keys(e).map(e=>[e,gr().optional()])));return gr().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,fr().parse(t).bind(i)]));return{...t.parse(s),[Symbol.dispose](){dm(e)}}})}function xh(e){return gr().transform(t=>{try{return e.parse(t)}catch(e){throw e instanceof J?e:new J(`The capability returned malformed data`,{cause:e,code:`PROTOCOL`,retryable:!1})}finally{dm(t)}})}function Sh(e){return fr({output:mi(gr().transform(t=>{try{return e.parse(t)}catch(e){throw dm(t),e instanceof J?e:new J(`The capability returned a malformed result`,{cause:e,code:`PROTOCOL`,retryable:!1})}}))})}var Ch=Sh(xh(ei())),wh=bh({fetch:Sh(qn(Response)),close:Ch}),Th=Tr([`plain`,`pencil`,`manga`,`riso`,`halftone`,`blueprint`,`crt`,`watercolor`]),Eh={ink:`var(--sprite-ink, var(--color-base-content, #1c1c1a))`,paper:`var(--sprite-paper, var(--color-base-100, #fbfaf6))`,accent:`var(--sprite-accent, var(--color-accent, #d20f39))`,risoFirst:`var(--sprite-riso-first, var(--color-info, #1e66f5))`,risoSecond:`var(--sprite-riso-second, var(--color-accent, #ea76cb))`,blueprint:`var(--sprite-blueprint, color-mix(in oklab, var(--color-info, #1e66f5) 55%, #0b2350))`,blueprintLine:`var(--sprite-blueprint-line, color-mix(in oklab, var(--color-info-content, #ffffff) 25%, #ffffff))`,screen:`var(--sprite-screen, color-mix(in oklab, var(--color-base-content, #111111) 12%, #050805))`,phosphor:`var(--sprite-phosphor, var(--color-success, #40a02b))`},$=(e,t={},...n)=>({tag:e,attributes:t,children:n}),Dh=(e,t,n=1)=>$(`feFlood`,{style:`flood-color: ${e}`,"flood-opacity":n,result:t}),Oh=(e,t,n)=>[$(`feImage`,{href:`data:image/svg+xml,${encodeURIComponent(`<svg xmlns='http://www.w3.org/2000/svg' width='${String(t)}' height='${String(t)}'>${e}</svg>`)}`,width:t,height:t,result:`${n}Cell`}),$(`feTile`,{in:`${n}Cell`,result:n})],kh=(e,t,n)=>$(`feColorMatrix`,{in:t,type:`matrix`,values:`0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ${e}`,result:n}),Ah=(e,t)=>kh(`-0.333 -0.333 -0.333 1 0`,e,t),jh=(e,t,n,r=1.1)=>[$(`feConvolveMatrix`,{in:e,order:3,kernelMatrix:`0 1 0 1 -4 1 0 1 0`,result:`${t}In`}),$(`feConvolveMatrix`,{in:e,order:3,kernelMatrix:`0 -1 0 -1 4 -1 0 -1 0`,result:`${t}Out`}),$(`feComposite`,{in:`${t}In`,in2:`${t}Out`,operator:`arithmetic`,k2:1,k3:1,result:`${t}Edges`}),kh(`${String(n)} ${String(n)} ${String(n)} ${String(r)} 0`,`${t}Edges`,t)],Mh=(e,t,n,r)=>[$(`feConvolveMatrix`,{in:e,order:3,kernelMatrix:`0 1 0 1 -4 1 0 1 0`,preserveAlpha:`true`,result:`${t}In`}),$(`feConvolveMatrix`,{in:e,order:3,kernelMatrix:`0 -1 0 -1 4 -1 0 -1 0`,preserveAlpha:`true`,result:`${t}Out`}),$(`feComposite`,{in:`${t}In`,in2:`${t}Out`,operator:`arithmetic`,k2:1,k3:1,result:`${t}Edges`}),kh(`${String(n)} ${String(n)} ${String(n)} 0 -0.15`,`${t}Edges`,`${t}Inner`),$(`feMorphology`,{in:e,operator:`dilate`,radius:r,result:`${t}Grown`}),$(`feComposite`,{in:`${t}Grown`,in2:e,operator:`out`,result:`${t}Ring`}),kh(`0 0 0 1 0`,`${t}Ring`,`${t}Outline`),Ph(t,`${t}Inner`,`${t}Outline`)],Nh=(e,t,n)=>$(`feComponentTransfer`,{in:e,result:n},$(`feFuncA`,{type:`discrete`,tableValues:t})),Ph=(e,...t)=>$(`feMerge`,{result:e},...t.map(e=>$(`feMergeNode`,{in:e}))),Fh=(e,t,n,r=1)=>[Dh(e,`${n}Flood`,r),$(`feComposite`,{in:`${n}Flood`,in2:t,operator:`in`,result:n})],Ih={x:`0%`,y:`0%`,width:`100%`,height:`100%`},Lh={x:`-8%`,y:`-8%`,width:`116%`,height:`116%`},Rh={value:1.6,line:6,outline:2.4,midHatch:[3.2,-.05],darkHatch:[3.4,-.4],tooth:`0 0 0 -0.7 1.45`,opacity:1},zh=e=>({region:Lh,primitives:[$(`feComponentTransfer`,{in:`SourceGraphic`,result:`valued`},...[`feFuncR`,`feFuncG`,`feFuncB`].map(t=>$(t,{type:`gamma`,amplitude:1,exponent:e.value,offset:0}))),$(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.05,numOctaves:2,seed:1,result:`wobble`,"data-sprite-boil":`wobble`}),$(`feDisplacementMap`,{in:`valued`,in2:`wobble`,scale:2.6,xChannelSelector:`R`,yChannelSelector:`G`,result:`drawn`}),...jh(`drawn`,`line`,e.line,e.outline),Ah(`drawn`,`dark`),...Oh(`<path d='M-1 1l2-2M0 6l6-6M5 7l2-2' stroke='black' stroke-width='1.1'/>`,6,`hatch45`),$(`feOffset`,{in:`hatch45`,dx:0,dy:0,result:`hatchOffset`,"data-sprite-boil":`hatch`}),$(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.07,numOctaves:2,seed:5,result:`strokeBend`}),$(`feDisplacementMap`,{in:`hatchOffset`,in2:`strokeBend`,scale:4,xChannelSelector:`R`,yChannelSelector:`B`,result:`hatchA`}),...Oh(`<path d='M-1 4l2 2M0 0l5 5M4 -1l2 2' stroke='black' stroke-width='0.9'/>`,5,`hatch135`),$(`feDisplacementMap`,{in:`hatch135`,in2:`strokeBend`,scale:3,xChannelSelector:`G`,yChannelSelector:`R`,result:`hatchB`}),$(`feComposite`,{in:`dark`,in2:`hatchA`,operator:`arithmetic`,k1:e.midHatch[0],k4:e.midHatch[1],result:`shadeA`}),$(`feComposite`,{in:`dark`,in2:`hatchB`,operator:`arithmetic`,k1:e.darkHatch[0],k4:e.darkHatch[1],result:`shadeB`}),$(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.9,numOctaves:1,seed:3,result:`tooth`}),kh(e.tooth,`tooth`,`toothMask`),kh(`0 0 0 6 -4.6`,`dark`,`solid`),Ph(`graphiteRaw`,`solid`,`shadeA`,`shadeB`,`line`),$(`feComposite`,{in:`graphiteRaw`,in2:`toothMask`,operator:`in`,result:`graphite`}),...Fh(Eh.ink,`graphite`,`pencil`,e.opacity)],boil:{intervalMs:160,tracks:[{name:`wobble`,attribute:`seed`,frames:[1,2,3]},{name:`hatch`,attribute:`dx`,frames:[0,1,2]}]}}),Bh={region:Lh,primitives:[$(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.04,numOctaves:2,seed:2,result:`brush`,"data-sprite-boil":`brush`}),$(`feDisplacementMap`,{in:`SourceGraphic`,in2:`brush`,scale:2,xChannelSelector:`R`,yChannelSelector:`G`,result:`drawn`}),...Fh(Eh.paper,`SourceAlpha`,`paperFill`),Ah(`drawn`,`dark`),...Oh(`<circle cx='2.5' cy='2.5' r='1.15' fill='black'/>`,5,`dots`),Nh(`dark`,`0 1 1 0`,`midTone`),$(`feComposite`,{in:`dots`,in2:`midTone`,operator:`in`,result:`tone`}),Nh(`dark`,`0 0 0 1`,`solid`),kh(`3 -3 0 0 -0.35`,`drawn`,`satRG`),kh(`-3 3 0 0 -0.35`,`drawn`,`satGR`),kh(`0 3 -3 0 -0.35`,`drawn`,`satGB`),kh(`0 -3 3 0 -0.35`,`drawn`,`satBG`),Ph(`saturation`,`satRG`,`satGR`,`satGB`,`satBG`),Nh(`saturation`,`0 1`,`accentMask`),...Fh(Eh.accent,`accentMask`,`accentFill`),...Mh(`drawn`,`edge`,2,2.2),$(`feMorphology`,{in:`edge`,operator:`dilate`,radius:.25,result:`stroke`}),Ph(`inkRaw`,`tone`,`solid`,`stroke`),...Fh(Eh.ink,`inkRaw`,`ink`),Ph(`manga`,`paperFill`,`accentFill`,`ink`)],boil:{intervalMs:180,tracks:[{name:`brush`,attribute:`seed`,frames:[2,4,6]}]}},Vh={region:Lh,primitives:[kh(`-0.55 -0.55 -0.55 1.65 0`,`SourceGraphic`,`dark`),$(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.85,numOctaves:1,seed:7,result:`grain`}),kh(`0 0 0 -0.9 1.35`,`grain`,`grainMask`),$(`feComposite`,{in:`dark`,in2:`grainMask`,operator:`in`,result:`firstMask`}),...Fh(Eh.risoFirst,`firstMask`,`firstInk`,.92),kh(`0 -1.9 0 1.9 0`,`SourceGraphic`,`secondMask`),...Fh(Eh.risoSecond,`secondMask`,`secondInk`,.9),$(`feOffset`,{in:`firstInk`,dx:-1.5,dy:1,result:`firstPlate`,"data-sprite-boil":`register`}),$(`feOffset`,{in:`secondInk`,dx:1.5,dy:-.5,result:`secondPlate`}),$(`feBlend`,{in:`firstPlate`,in2:`secondPlate`,mode:`multiply`})],boil:{intervalMs:240,tracks:[{name:`register`,attribute:`dx`,frames:[-1.5,-1,-2]}]}},Hh={region:Lh,primitives:[kh(`-0.5 -0.5 -0.5 1.65 0`,`SourceGraphic`,`value`),kh(`0 0 0 0.16 0`,`SourceGraphic`,`floor`),Ph(`dark`,`floor`,`value`),...Oh(`<defs><radialGradient id='d'><stop offset='0' stop-opacity='1'/><stop offset='1' stop-opacity='0'/></radialGradient></defs><rect width='6' height='6' fill='url(#d)'/>`,6,`screen`),$(`feComposite`,{in:`dark`,in2:`screen`,operator:`arithmetic`,k2:1,k3:1,k4:-.92,result:`dotField`}),$(`feComponentTransfer`,{in:`dotField`,result:`dotsRaw`},$(`feFuncA`,{type:`linear`,slope:12,intercept:0})),$(`feComposite`,{in:`dotsRaw`,in2:`SourceAlpha`,operator:`in`,result:`dots`}),...Fh(Eh.ink,`dots`,`halftone`)]},Uh={region:Ih,primitives:[Dh(Eh.blueprint,`ground`),$(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.05,numOctaves:1,seed:4,result:`hand`,"data-sprite-boil":`hand`}),$(`feDisplacementMap`,{in:`SourceGraphic`,in2:`hand`,scale:1.6,xChannelSelector:`R`,yChannelSelector:`G`,result:`drawn`}),...Oh(`<path d='M0 0.5h16M0.5 0v16' stroke='black' stroke-width='1' stroke-opacity='0.22'/>`,16,`grid`),...Fh(Eh.blueprintLine,`grid`,`gridLines`),...Fh(Eh.blueprintLine,`SourceAlpha`,`wash`,.12),...Mh(`drawn`,`edge`,3,1.2),$(`feMorphology`,{in:`edge`,operator:`dilate`,radius:.3,result:`stroke`}),...Fh(Eh.blueprintLine,`stroke`,`lines`),Ph(`blueprint`,`ground`,`gridLines`,`wash`,`lines`)],boil:{intervalMs:200,tracks:[{name:`hand`,attribute:`seed`,frames:[4,5,6]}]}},Wh={region:Ih,primitives:[Dh(Eh.screen,`ground`),$(`feColorMatrix`,{in:`SourceGraphic`,type:`luminanceToAlpha`,result:`lumRaw`}),$(`feComposite`,{in:`lumRaw`,in2:`SourceAlpha`,operator:`in`,result:`lum`}),$(`feComponentTransfer`,{in:`lum`,result:`beam`},$(`feFuncA`,{type:`linear`,slope:1.5,intercept:-.35})),$(`feComposite`,{in:`beam`,in2:`SourceAlpha`,operator:`in`,result:`trace`}),...Fh(Eh.phosphor,`trace`,`glow`),$(`feGaussianBlur`,{in:`glow`,stdDeviation:2.5,result:`bloom`}),...Oh(`<rect y='2' width='3' height='1' fill='black'/>`,3,`scan`),$(`feOffset`,{in:`scan`,dx:0,dy:0,result:`scanRoll`,"data-sprite-boil":`roll`}),...Fh(Eh.screen,`scanRoll`,`scanlines`,.6),Ph(`crt`,`ground`,`bloom`,`glow`,`scanlines`)],boil:{intervalMs:120,tracks:[{name:`roll`,attribute:`dy`,frames:[0,1,2]}]}},Gh={region:Lh,primitives:[$(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.03,numOctaves:3,seed:9,result:`flow`}),$(`feDisplacementMap`,{in:`SourceGraphic`,in2:`flow`,scale:7,xChannelSelector:`R`,yChannelSelector:`G`,result:`bled`}),$(`feGaussianBlur`,{in:`bled`,stdDeviation:1.4,result:`wash`}),$(`feComponentTransfer`,{in:`wash`,result:`thin`},$(`feFuncR`,{type:`linear`,slope:.78,intercept:.2}),$(`feFuncG`,{type:`linear`,slope:.78,intercept:.2}),$(`feFuncB`,{type:`linear`,slope:.78,intercept:.2}),$(`feFuncA`,{type:`linear`,slope:.9,intercept:0})),$(`feGaussianBlur`,{in:`wash`,stdDeviation:3,result:`spread`}),$(`feComposite`,{in:`wash`,in2:`spread`,operator:`arithmetic`,k2:1.6,k3:-1.4,result:`rimMask`}),$(`feComponentTransfer`,{in:`wash`,result:`deep`},$(`feFuncR`,{type:`linear`,slope:.6,intercept:0}),$(`feFuncG`,{type:`linear`,slope:.6,intercept:0}),$(`feFuncB`,{type:`linear`,slope:.6,intercept:0})),$(`feComposite`,{in:`deep`,in2:`rimMask`,operator:`in`,result:`rim`}),$(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.7,numOctaves:2,seed:11,result:`tooth`}),kh(`0 0 0 -0.8 1.5`,`tooth`,`toothMask`),Ah(`SourceGraphic`,`dark`),kh(`0 0 0 5 -3.8`,`dark`,`keyMask`),...Fh(Eh.ink,`keyMask`,`key`,.9),Ph(`paint`,`thin`,`rim`,`key`),$(`feComposite`,{in:`paint`,in2:`toothMask`,operator:`in`})]},Kh=zh(Rh),qh={manga:Bh,riso:Vh,halftone:Hh,blueprint:Uh,crt:Wh,watercolor:Gh},Jh=e=>e===`pencil`?Kh:qh[e],Yh=`http://www.w3.org/2000/svg`,Xh=(e,t)=>{let n=e.createElementNS(Yh,t.tag);for(let[e,r]of Object.entries(t.attributes))n.setAttribute(e,String(r));for(let r of t.children)n.append(Xh(e,r));return n};function Zh(e){let t=`sprite-style-${Tm()}`,n=e.ownerDocument,r=n.defaultView,i=`plain`,a,o,s=!1,c=!0,l,u=0,d=()=>{l!==void 0&&clearInterval(l),l=void 0},f=()=>{if(d(),i===`plain`||!o||s||!c||n.hidden)return;let e=Jh(i).boil;if(!e)return;let t=o;l=setInterval(()=>{if(!n.hidden){u+=1;for(let n of e.tracks){let e=n.frames[u%n.frames.length];t.querySelector(`[data-sprite-boil="${n.name}"]`)?.setAttribute(n.attribute,String(e))}}},e.intervalMs)},p=r?.IntersectionObserver,m=p?new p(e=>{c=e.some(e=>e.isIntersecting),f()}):void 0;m?.observe(e);let h=()=>{d(),o?.remove(),o=void 0,a&&(a.style.filter=``)};return{set(r,s){if(r===i&&s===a||(h(),i=r,a=s,r===`plain`))return;let c=Jh(r),l=`${t}-${r}`,u=n.createElementNS(Yh,`svg`);u.setAttribute(`aria-hidden`,`true`),u.setAttribute(`focusable`,`false`),u.setAttribute(`width`,`0`),u.setAttribute(`height`,`0`),u.style.cssText=`position:absolute;width:0;height:0;overflow:hidden`,u.append(Xh(n,$(`filter`,{id:l,...c.region,"color-interpolation-filters":`sRGB`},...c.primitives))),e.append(u),o=u,s.style.filter=`url(#${l})`,f()},still(e){e!==s&&(s=e,f())},dispose(){h(),a=void 0,m?.disconnect()}}}var Qh=[`mushroom`,`cat`,`burger`];Tr([`shift`,`keep`]);var $h=P().regex(/^#[0-9a-f]{6}$/i),eg=hi([$h,zr(),ti()]),tg=16,ng=Ar({v:ri(1),character:Tr(Qh),appearance:bi(P().min(1),eg).refine(e=>Object.keys(e).length<=tg,{message:`Avatar appearance cannot exceed ${String(tg)} keys`}),expression:P().min(1),renderStyle:Th});function rg(e,t,n){let r=t/100,i=n/100,a=r*Math.min(i,1-i),o=t=>{let n=(t+e/30)%12,r=i-a*Math.max(-1,Math.min(n-3,9-n,1));return Math.round(255*r).toString(16).padStart(2,`0`)};return`#${o(0)}${o(8)}${o(4)}`}function ig(e){let t=2166136261;for(let n of e)t^=n.codePointAt(0)??0,t=Math.imul(t,16777619)>>>0;return t}function ag(e){let t=ig(e)%360;return{cap:rg(t,68,72),capSpot:rg(t,70,92)}}function og(e){return{v:1,character:`mushroom`,appearance:ag(e),expression:`normal`,renderStyle:`plain`}}var sg=V.pipe(z(H(1)),z(K(256))),cg=Yi(e=>ng.safeParse(e).success,{expected:`an Avatar v1 descriptor`}),lg=I({agentId:sg,name:sg,avatar:cg,sessionOperations:W(G([`agent.read`,`agent.send`,`agent.manage`]))});Ir(()=>Ar({agents:oi(Ar({agentId:P(),name:P()}))}));var ug=F([G([`new`,`none`]),I({computerId:sg})]),dg=I({computerId:sg,name:sg,createdAt:ya.pipe(z(Ka()))}),fg=oo(W(dg)),pg=zi(fg,{onExcessProperty:`error`}),mg=I({name:sg,requestId:sg,computer:B(ug),avatar:B(cg)}),hg=W(lg),gg=zi(hg,{onExcessProperty:`error`}),_g=zi(sg),vg=zi(ua(Response)),yg=yh(`agent.list`,1,Ir(()=>bh({list:Sh(xh(gr().transform(e=>gg(e))))}))),bg=yh(`agent.manage`,1,Ir(()=>bh({open:Sh(wh),computers:Sh(xh(gr().transform(e=>pg(e)))),create:Sh(xh(gr().transform(e=>zi(lg)(e))))}))),xg=I({agentId:sg,name:sg}),Sg=yh(`agent.rename`,1,Ir(()=>bh({rename:Sh(xh(gr().transform(e=>zi(lg)(e))))})));async function Cg(e,t){let n=zi(xg)(t),r=await e.require(Sg).rename(n);return zi(lg)(r)}var wg=I({agentId:sg,avatar:cg}),Tg=yh(`agent.avatar`,1,Ir(()=>bh({setAvatar:Sh(xh(gr().transform(e=>zi(lg)(e))))})));async function Eg(e,t){let n=zi(wg)(t),r=await e.require(Tg).setAvatar(n);return zi(lg)(r)}var Dg=Ir(()=>hi([Dr({status:ri(`pending`),revision:P()}),Dr({status:ri(`approved`),revision:P()})])),Og=Ir(()=>hi([Dg,Dr({error:P()})])),kg=yh(`agent.toolPolicy`,1,Ir(()=>bh({status:Sh(xh(hi([Dg,Fr()]))),approve:Sh(xh(Og))}))),Ag=yh(`agent.read`,1,Ir(()=>bh({open:Sh(wh),openInbox:Sh(wh)}))),jg=yh(`agent.send`,1,Ir(()=>bh({open:Sh(wh),openInbox:Sh(wh)})));async function Mg(e,t){let n=zi(mg)(t),r=await e.require(bg).create(n);return zi(lg)(r)}async function Ng(e){let t=pg(await e.require(bg).computers());return t===null?null:[...t].sort((e,t)=>t.createdAt-e.createdAt)}async function Pg(e,t){let n=await e(),r,i,a=()=>{if(i)throw new J(`The Agent connection is closed`,{code:`DISCONNECTED`,retryable:!0})},o=async e=>{try{await e.close()}finally{e[Symbol.dispose]()}};return{fetch:async i=>{a(),i.signal.throwIfAborted();let o=i.method===`GET`||i.method===`HEAD`||e===t?n:await(r??=t());a(),i.signal.throwIfAborted();let s=vg(await o.fetch(i));return s.body===null?s:new Response(s.body.pipeThrough(new TransformStream,{signal:i.signal}),s)},close:()=>(i||(i=Promise.all([o(n),...r?[r.then(o)]:[]]).then(()=>void 0),i.catch(e=>{Xo(`agents.close`,e)})),i)}}var Fg=`https://agent-session.fungi.invalid`;async function Ig(e,t){let n=_g(t.agentId),r=`/agents/id-${encodeURIComponent(n)}`,i=`${Fg}${r}`,a=e.has(Ag)?e.require(Ag):e.has(jg)?e.require(jg):e.require(bg),o=()=>a.open({agentId:n}),s=await Pg(o,e.has(Ag)?()=>(e.has(jg)?e.require(jg):e.require(bg)).open({agentId:n}):o);return Object.freeze({baseUrl:i,fetch:async(e,t)=>{let n=new Request(e,t),i=new URL(n.url);if(i.origin!==Fg||!i.pathname.startsWith(`${r}/`))throw new J(`The Agent request target is invalid`,{code:`INVALID_ARGUMENT`,retryable:!1});return i.pathname=i.pathname.slice(r.length),s.fetch(new Request(i,n))},close:s.close})}var Lg=`${Fg}/member`;async function Rg(e){let t=e.has(Ag)?Ag:jg,n=()=>e.require(t).openInbox(),r=await Pg(n,e.has(Ag)?()=>e.require(jg).openInbox():n);return Object.freeze({baseUrl:Lg,fetch:async(e,t)=>{let n=new Request(e,t),i=new URL(n.url);if(i.origin!==Fg||!i.pathname.startsWith(`/member/inbox`))throw new J(`The inbox request target is invalid`,{code:`INVALID_ARGUMENT`,retryable:!1});return i.pathname=i.pathname.slice(7),r.fetch(new Request(i,n))},close:r.close})}var zg=class extends Event{code;message;constructor(e,t){super(e),this.code=t?.code??void 0,this.message=t?.message??void 0}[Symbol.for(`nodejs.util.inspect.custom`)](e,t,n){return n(Hg(this),t)}[Symbol.for(`Deno.customInspect`)](e,t){return e(Hg(this),t)}};function Bg(e){let t=globalThis.DOMException;return typeof t==`function`?new t(e,`SyntaxError`):SyntaxError(e)}function Vg(e){return e instanceof Error?`errors`in e&&Array.isArray(e.errors)?e.errors.map(Vg).join(`, `):`cause`in e&&e.cause instanceof Error?`${e}: ${Vg(e.cause)}`:e.message:`${e}`}function Hg(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var Ug=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}},Wg=10,Gg=13,Kg=32,qg=6;function Jg(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{maxBufferSize:t,onComment:n,onError:r,onEvent:i,onId:a,onRetry:o}=e,s=[],c=0,l=!0,u,d=``,f=0,p,m=!1,h=!1,g=!1;function _(e){if(m)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,e.charCodeAt(0)===65279?e=e.slice(1):e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),(h||g)&&(e=v(e),!e))return;if(!s.length){let t=S(e);t!==``&&y(t),x();return}if(e.indexOf(`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/runtime-core-BZbN1OFo.js","assets/rolldown-runtime-hePW80VL.js","assets/Effect-CsknxyoC.js","assets/extension-hook-ClyQNPvs.js","assets/preload-helper-DY31Aviq.js","assets/mushroom-Bm99-6Un.js","assets/document-Bq-ilh6h.js","assets/renderer-B77qG8Ri.js","assets/animation-Ca8A_H2p.js","assets/cat-gQl6DJEL.js","assets/base-face-BYNJAADF.js","assets/burger-BE3Gxp6Y.js","assets/website-conversation-CX0AUueJ.js","assets/sigil-Ciz-0LU3.js","assets/parakeet-BXf0kg3T.js","assets/openai-codex.models-B_MCwO6E.js","assets/parakeet-conversation-Cdiu-eyV.js","assets/parakeet-conversation-COndlivb.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as e,t}from"./rolldown-runtime-hePW80VL.js";import{$ as n,$n as r,$r as i,A as a,An as o,Ar as s,At as c,B as l,Bn as u,Br as d,Bt as f,C as p,Ci as m,Cn as h,Cr as g,Ct as _,D as v,Dn as y,E as b,Ei as x,En as S,Et as C,F as w,Fn as T,Fr as E,Ft as ee,G as D,Gn as O,Gr as k,H as A,Hn as j,Hr as te,I as ne,In as re,It as ie,J as ae,Jn as oe,K as se,Kn as ce,Kr as le,L as ue,Ln as M,Lr as de,Lt as fe,M as pe,Mr as me,Mt as he,N as ge,Nr as _e,On as ve,P as ye,Pr as be,Pt as N,Q as xe,Qn as Se,Qr as Ce,R as we,Rn as Te,Rr as Ee,Rt as De,S as Oe,Sn as ke,St as Ae,T as je,Ti as Me,Tn as Ne,Tr as Pe,Tt as Fe,U as Ie,Un as Le,Ur as Re,V as ze,Vn as Be,Vr as Ve,Vt as He,W as Ue,Wn as We,Wr as Ge,X as Ke,Xn as qe,Y as Je,Yn as Ye,Z as Xe,Zn as Ze,Zr as Qe,_ as $e,_n as et,_r as tt,_t as nt,a as rt,at as it,b as at,bn as ot,br as st,bt as ct,c as lt,ci as ut,cn as dt,cr as ft,ct as pt,d as mt,di as ht,dr as gt,dt as _t,ei as vt,er as yt,et as bt,f as xt,fi as St,fr as Ct,ft as wt,g as Tt,gi as Et,gn as Dt,gt as Ot,h as kt,hi as At,hn as jt,hr as Mt,ht as Nt,i as Pt,it as Ft,j as It,jn as Lt,jr as Rt,k as zt,ki as Bt,kn as Vt,kt as Ht,l as Ut,li as Wt,ln as Gt,lr as Kt,lt as qt,m as Jt,mi as Yt,mn as Xt,mr as Zt,mt as Qt,n as $t,ni as en,nr as tn,nt as nn,o as rn,oi as an,or as on,ot as sn,p as cn,pi as ln,pr as un,pt as dn,q as fn,qn as pn,qr as mn,r as hn,rr as gn,rt as _n,s as vn,si as yn,sn as bn,sr as xn,st as Sn,t as Cn,ti as wn,tr as Tn,tt as En,ui as Dn,ur as On,v as kn,vn as An,vr as jn,vt as Mn,w as Nn,wi as Pn,wn as Fn,wr as In,x as Ln,xn as Rn,xt as zn,y as Bn,yn as Vn,yr as Hn,yt as Un,z as Wn,zn as Gn,zr as Kn}from"./sigil-Ciz-0LU3.js";import{$i as qn,Aa as Jn,Bi as Yn,Ct as Xn,Da as Zn,E as Qn,Ei as $n,F as er,Fa as tr,Gi as nr,Hi as rr,I as ir,Ji as ar,Jn as or,K as sr,Ki as cr,Na as lr,Nn as ur,Oa as dr,Qi as fr,Qn as pr,Ri as mr,St as hr,Ta as gr,Ui as _r,V as vr,Vi as yr,Wi as br,Xi as xr,Y as Sr,Yi as Cr,Z as wr,Zi as Tr,_ as Er,_a as Dr,a as Or,ar as kr,ba as Ar,bt as jr,ca as Mr,d as Nr,da as Pr,ea as Fr,fa as Ir,fr as Lr,g as Rr,ga as zr,gi as Br,gt as Vr,h as Hr,ht as Ur,i as Wr,ir as Gr,it as Kr,j as qr,ji as Jr,ka as Yr,l as Xr,lr as Zr,m as Qr,mt as $r,na as ei,oa as ti,ot as ni,pa as ri,pt as ii,qi as ai,ra as oi,rr as si,s as ci,sa as li,sr as ui,t as di,tt as fi,ur as pi,va as mi,wa as hi,wt as gi,xa as P,xi as _i,xt as vi,y as yi,ya as bi,zi as xi}from"./Effect-CsknxyoC.js";import{$a as Si,$n as Ci,$r as wi,Ai as F,Bi as Ti,Bo as Ei,Ci as I,Co as Di,Cr as Oi,Di as ki,Do as Ai,Ei as ji,Eo as Mi,Er as Ni,Fa as Pi,Fi,Fo as Ii,Ga as Li,Ha as Ri,Hi as zi,Ji as Bi,Jr as Vi,Ka as Hi,Ki as Ui,Lo as Wi,Ma as L,Mi as Gi,Na as R,Ni as z,Nr as Ki,Oi as qi,Oo as Ji,Pa as B,Pi as Yi,Qa as Xi,Qr as Zi,Ri as Qi,Si as V,So as $i,Ta as H,Ti as ea,Tr as ta,Ua as na,Va as ra,Vi as ia,Wa as aa,Wr as oa,Xa as sa,Xi as ca,Ya as la,Yi as ua,Yn as da,Yr as fa,Za as pa,Zi as ma,Zr as ha,_a as ga,aa as _a,ao as va,bi as ya,bo as ba,c as xa,ci as Sa,d as Ca,di as wa,do as Ta,eo as Ea,f as Da,fi as U,fr as Oa,go as ka,i as Aa,ii as W,io as ja,ji as Ma,jo as Na,ka as Pa,la as Fa,li as Ia,m as La,mo as Ra,mr as za,ni as Ba,no as Va,oa as Ha,oi as Ua,oo as Wa,p as Ga,pa as Ka,pi as G,po as qa,pr as Ja,qa as Ya,ri as Xa,ro as Za,to as Qa,ui as $a,uo as eo,vi as to,vo as no,wr as ro,xa as K,xi as io,xo as ao,yi as oo,yo as so,za as co,zi as lo,zo as uo}from"./extension-hook-ClyQNPvs.js";import{a as fo,o as po,s as mo,t as ho}from"./document-Bq-ilh6h.js";import{n as go}from"./animation-Ca8A_H2p.js";import{t as _o}from"./preload-helper-DY31Aviq.js";import{a as vo,i as yo,n as bo,r as xo,t as So}from"./base-face-BYNJAADF.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var q=e(Bt(),1);function Co(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:x(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()}}}var wo=V.pipe(z(H(1)),z(K(80))),To=[`CANCELLED`,`CAPABILITY_DENIED`,`CAPABILITY_REVOKED`,`COMMAND_NOT_DECLARED`,`CONFLICT`,`DELIVERY_PENDING`,`DISCONNECTED`,`FILE_TOO_LARGE`,`HOST_FAILURE`,`IDENTITY`,`INSUFFICIENT_CREDIT`,`INVALID_ARGUMENT`,`MEDIA_PROVIDER_FAILURE`,`MEDIA_PROVIDER_FAILURE_UNCHARGED`,`PROTOCOL`,`SAFETY_FILTER_REFUSED`,`SELECTION_CHANGED`,`SETUP_REQUIRED`,`TIMEOUT`];I({name:U(`AppError`),code:G(To),retryable:Ua,need:R(V)});var J=class extends Error{code;retryable;need;constructor(e,t){super(e,{cause:t.cause}),this.name=`AppError`,this.code=t.code,this.retryable=t.retryable,this.need=t.need}};function Eo(e){return`This needs ${e??`setup`} first.`}Eo(void 0),Tr(`light.dark.latte.mocha.readout.readout-night.field-guide.field-guide-night.embed.embed-dark.phosphor.codec.paper.ember.tide.tape.sunrise.pirate-radio.pirate-radio-night.consulting.consulting-ink.consulting-night.consulting-night-ink.consulting-riso-latte.consulting-riso-latte-ink.consulting-riso-glomzy.consulting-riso-glomzy-ink.vishnu.coin.coin-night.chamfer`.split(`.`));var Do=`data-theme`;function Oo(e){return e||(globalThis.document?.documentElement??null)}function ko(e){let t=e.trim();if(t.length===0)throw TypeError(`Theme must be a non-empty string`);return t}function Ao(e,t){let n=ko(e),r=Oo(t);r&&r.setAttribute(Do,n)}function jo(e){return Oo(e)?.getAttribute(Do)??null}function Mo(e,t){let n=new Set(t);return e.filter(e=>!n.has(e))}var No=class extends yn{#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||!Dn(e,n)});!o&&!s||(o&&(this.#l=t,this.#i=n),this.#t=r,this.hasListeners()&&(o&&(Mo(e,n).forEach(e=>{e.destroy()}),Mo(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=Wt(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 en(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)})})}}},Po=q.createContext(!1),Fo=()=>q.useContext(Po);Po.Provider;var Y=Yt();function Io(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Lo=q.createContext(Io()),Ro=()=>q.useContext(Lo),zo=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?ht(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},Bo=e=>{q.useEffect(()=>{e.clearReset()},[e])},Vo=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||ht(n,[e.error,r])),Ho=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},Uo=(e,t)=>e?.suspense&&t.isPending,Wo=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Go({queries:e,...t},n){let r=ln(n),i=Fo(),a=Ro(),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=>{Ho(e);let t=r.getQueryCache().get(e.queryHash);zo(e,a,t)}),Bo(a);let[c]=q.useState(()=>new No(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)):ut,[c,f]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),q.useEffect(()=>{c.setQueries(s,t)},[s,t,c]);let p=l.some((e,t)=>Uo(s[t],e))?l.flatMap((e,t)=>{let n=s[t];return n&&Uo(n,e)?Wo(n,new en(r,n),a):[]}):[];if(p.length>0)throw Promise.all(p);let m=l.find((e,t)=>{let n=s[t];return n&&Vo({result:e,errorResetBoundary:a,throwOnError:n.throwOnError,query:r.getQueryCache().get(n.queryHash),suspense:n.suspense})});if(m)throw m.error;return u(d())}function Ko(e,t,n){let r=Fo(),i=Ro(),a=ln(n),o=a.defaultQueryOptions(e),s=a.getQueryCache().get(o.queryHash),c=e.subscribed!==!1;o._optimisticResults=r?`isRestoring`:c?`optimistic`:void 0,Ho(o),zo(o,i,s),Bo(i);let[l]=q.useState(()=>new t(a,o)),u=l.getOptimisticResult(o),d=!r&&c;if(q.useSyncExternalStore(q.useCallback(e=>{let t=d?l.subscribe(an.batchCalls(e)):ut;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),q.useEffect(()=>{l.setOptions(o)},[o,l]),Uo(o,u))throw Wo(o,l,i);if(Vo({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return o.notifyOnChangeProps?u:l.trackResult(u)}function qo(e,t){return Ko(e,en,t)}function Jo(e,t){let n=ln(t),[r]=q.useState(()=>new wn(n,e));q.useEffect(()=>{r.setOptions(e)},[r,e]);let i=q.useSyncExternalStore(q.useCallback(e=>r.subscribe(an.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=q.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(ut)},[r]);if(i.error&&ht(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}var Yo=t((e=>{var t=Qe();e.createRoot=t.createRoot,e.hydrateRoot=t.hydrateRoot}))();function Xo(e,t){console.error(JSON.stringify({source:`agar`,operation:e,failureKind:t instanceof Error?`Error`:`NonErrorThrown`}),Ta(t))}var Zo=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 Qo=globalThis[Zo],$o=Qo?Qo.RpcTarget:class{},es=async function(){}.constructor,ts=typeof Buffer<`u`?Buffer.prototype:void 0;function ns(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 es.prototype:return`function`;case Array.prototype:return`array`;case Date.prototype:return`date`;case Uint8Array.prototype:case ts: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 ms.prototype:return`stub`;case hs.prototype:return`rpc-promise`;default:if(Qo){if(t==Qo.RpcStub.prototype||e instanceof Qo.ServiceStub)return`rpc-target`;if(t==Qo.RpcPromise.prototype||t==Qo.RpcProperty.prototype)return`rpc-thenable`}return e instanceof $o?`rpc-target`:e instanceof Error?`error`:`unsupported`}}function rs(){throw Error(`RPC map() implementation was not loaded.`)}var is={applyMap:rs,sendMap:rs};function as(){throw Error(`Stream implementation was not loaded.`)}var os={createWritableStreamHook:as,createWritableStreamFromHook:as,createReadableStreamHook:as},ss=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}}},cs=class extends ss{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)}}},ls=new cs(Error(`Attempted to use RPC stub after it has been disposed.`)),us=(e,t,n)=>e.call(t,n);function ds(e,t){let n=us;us=e;try{return t()}finally{us=n}}var fs=Symbol(`realStub`),ps={apply(e,t,n){let r=e.raw;return new hs(us(r.hook,r.pathIfPromise||[],Ss.fromAppParams(n)),[])},get(e,t,n){let r=e.raw;if(t===fs)return r;if(t in hs.prototype)return r[t];if(typeof t==`string`)return new hs(r.hook,r.pathIfPromise?[...r.pathIfPromise,t]:[t]);if(t===Symbol.dispose&&(!r.pathIfPromise||r.pathIfPromise.length==0))return()=>{r.hook.dispose(),r.hook=ls}},has(e,t){let n=e.raw;return t===fs?!0:t in hs.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.`)}},ms=class e extends $o{constructor(e,t){if(super(),!(e instanceof ss)){let n=e;if(e=n instanceof $o||n instanceof Function?Ds.create(n,void 0):new Ts(Ss.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,ps)}hook;pathIfPromise;dup(){let t=this[fs];return t.pathIfPromise?new e(t.hook.get(t.pathIfPromise)):new e(t.hook.dup())}onRpcBroken(e){this[fs].hook.onBroken(e)}map(e){let{hook:t,pathIfPromise:n}=this[fs];return is.sendMap(t,n||[],e)}toString(){return`[object RpcStub]`}},hs=class extends ms{constructor(e,t){if(e instanceof ss)super(e,t??[]);else{if(t!==void 0)throw TypeError(`RpcPromise constructor expected one argument, received two.`);let n=ns(e);if(n===`rpc-promise`){let t=bs(e);if(t.pathIfPromise.length>0)super(t.hook,t.pathIfPromise);else{let e=t.hook;t.hook=ls,super(e,[])}}else if(n===`rpc-thenable`)super(Ds.create(e,void 0),[]);else{let t=new Os(Promise.resolve(e).then(e=>new Ts(Ss.fromAppReturn(e))));t.ignoreUnhandledRejections(),super(t,[])}}}then(e,t){return xs(this).then(...arguments)}catch(e){return xs(this).catch(...arguments)}finally(e){return xs(this).finally(...arguments)}toString(){return`[object RpcPromise]`}};function gs(e){let{hook:t,pathIfPromise:n}=e[fs];return n&&n.length>0?t.get(n):t}function _s(e){let{hook:t,pathIfPromise:n}=e[fs];return n?t.get(n):t.dup()}function vs(e){let{hook:t,pathIfPromise:n}=e[fs];if(!(n&&n.length>0))return t}function ys(e){return e[fs].hook}function bs(e){return e[fs]}async function xs(e){let{hook:t,pathIfPromise:n}=e[fs];return n.length>0&&(t=t.get(n)),(await t.pull()).deliverResolve()}var Ss=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 Ds.create(e,t)}if(this.source===`return`){let r=this.rpcTargets?.get(e);return r?n?r.dup():(this.rpcTargets?.delete(e),r):(r=Ds.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 os.createWritableStreamHook(e);if(this.source===`return`){let t=this.rpcTargets?.get(e);return t?n?t.dup():(this.rpcTargets?.delete(e),t):(t=os.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 os.createReadableStreamHook(e);if(this.source===`return`){let t=this.rpcTargets?.get(e);return t?n?t.dup():(this.rpcTargets?.delete(e),t):(t=os.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(ns(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?_s(t):gs(t),t instanceof hs){let e=new hs(a,[]);return this.promises.push({parent:r,property:n,promise:e}),e}return this.hooks.push(a),new ms(a)}case`function`:case`rpc-target`:{let n=e,r;return r=a?a.getHookForRpcTarget(n,t,i):Ds.create(n,t),this.hooks.push(r),new ms(r)}case`rpc-thenable`:{let o=e,s;return s=a?new hs(a.getHookForRpcTarget(o,t,i),[]):new hs(Ds.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):os.createWritableStreamHook(n),this.hooks.push(r),n}case`readable`:{let n=e,r;return r=a?a.getHookForReadableStream(n,t,i):os.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 hs)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=vs(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 hs?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(ns(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=vs(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)):Es(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=os.createWritableStreamHook(t),n.dispose();return}case`readable`:{let t=e,n=this.rpcTargets?.get(t);n?this.rpcTargets.delete(t):n=os.createReadableStreamHook(t),n.dispose();return}default:return}}ignoreUnhandledRejections(){this.hooks?(this.hooks.forEach(e=>{e.ignoreUnhandledRejections()}),this.promises.forEach(e=>ys(e.promise).ignoreUnhandledRejections())):this.ignoreUnhandledRejectionsImpl(this.value)}ignoreUnhandledRejectionsImpl(e){switch(ns(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`:ys(e).ignoreUnhandledRejections();return;case`rpc-thenable`:e.then(e=>{},e=>{});return;default:return}}};function Cs(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(ns(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}=bs(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 hs){let{hook:t,pathIfPromise:n}=bs(e);return{hook:t,remainingPath:n||[]}}return{value:e,parent:t,owner:r}}var ws=class extends ss{call(e,t){let n;try{let{value:t,owner:r}=this.getValue();n=Cs(t,void 0,e,r)}catch(e){return t.dispose(),new cs(e)}return n.hook?n.hook.call(n.remainingPath,t):typeof n.value==`function`?new Os(t.deliverCall(n.value,n.parent).then(e=>new Ts(e))):(t.dispose(),new cs(TypeError(`'${e.join(`.`)}' is not a function.`)))}map(e,t,n){try{let r;try{let{value:t,owner:n}=this.getValue();r=Cs(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):is.applyMap(r.value,r.parent,r.owner,t,n)}catch(e){return new cs(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=Cs(t,void 0,e,n);return r.hook?r.hook.get(r.remainingPath):new Ts(Ss.deepCopyFrom(r.value,r.parent,r.owner))}catch(e){return new cs(e)}}},Ts=class e extends ws{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(Ss.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 ms&&this.payload.value.onRpcBroken(e)}};function Es(e){if(Symbol.dispose in e)try{e[Symbol.dispose]()}catch(e){Promise.reject(e)}}var Ds=class e extends ws{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=>Ss.fromAppReturn(e)):Promise.reject(Error(`Tried to resolve a non-promise stub.`))}ignoreUnhandledRejections(){}dispose(){this.target&&=(this.refcount&&--this.refcount.count==0&&Es(this.target),void 0)}onBroken(e){let t=this.target;t&&`then`in t&&Promise.resolve(t).then(()=>{},e)}},Os=class e extends ss{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)}},ks={maxBigIntDigits:16384,maxDepth:256,maxMessageSize:33554432},As=new Uint8Array(new Uint16Array([1]).buffer)[0]===1,js=[`ArrayBuffer`,`DataView`,`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`Int16Array`,`Uint16Array`,`Int32Array`,`Uint32Array`,`BigInt64Array`,`BigUint64Array`,`Float32Array`,`Float64Array`];function Ms(e){return js.includes(e)}var Ns={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},Ps={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},Fs=new Map;for(let e of Object.keys(Ps))Fs.set(Ps[e],e);function Is(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 Ls=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 Rs(e,t){let n=await new Response(e).blob();return n.type===t?n:n.slice(0,n.size,t)}var zs={__proto__:null,Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError},Bs=class e{exporter;source;encodingLevel;constructor(e,t,n){this.exporter=e,this.source=t,this.encodingLevel=n}static devaluate(t,n,r=Ls,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(ns(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=Fs.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=Ns[t];!As&&i&&(n=n.slice(),Is(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=os.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=os.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}=bs(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 ks}};function Vs(e,t){return new hs(new Os(new Response(t).arrayBuffer().then(t=>{let n=new Uint8Array(t),r=new Request(e,{body:n});return new Ts(Ss.fromAppReturn(r))})),[])}function Hs(e,t){return new hs(new Os(Rs(e,t).then(e=>new Ts(Ss.fromAppReturn(e)))),[])}var Us=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=Ss.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(!Ms(t[2])){let e=t[2].slice(0,64);throw TypeError(`Unknown bytes type marker: ${e}`)}let n=t[2],r=Ns[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(!As&&r!==void 0&&Is(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=zs[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=Vs(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=Hs(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 hs(e,[]);return this.promises.push({promise:t,parent:n,property:r}),t}return this.hooks.push(e),new hs(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 hs(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 hs(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 ms(e)}}break;case`writable`:if(typeof t[1]==`number`){let e=this.importer.importStub(t[1]),n=os.createWritableStreamFromHook(e);return this.hooks.push(e),n}break;case`readable`:if(typeof t[1]==`number`){let e=this.importer.getPipeReadable(t[1]),n=os.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}},Ws=16,Gs=8,Ks=16,qs=64;function Js(e){return 2+e.length*3}function Ys(e,t,n=0){if(n>=qs)return Gs;switch(typeof e){case`string`:return Js(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 Ks+e.byteLength;if(typeof Blob<`u`&&e instanceof Blob)return Ks+e.size;if(e instanceof Date)return 16;if(t??=new WeakSet,t.has(e))return Gs;if(t.add(e),e instanceof Array){let r=Ws;for(let i of e)r+=Gs+Ys(i,t,n+1);return r}if(e instanceof Error){let r=Ws+Js(e.name)+Js(e.message)+Js(e.stack??``);for(let i of Object.keys(e))r+=Gs+Js(i)+Ys(e[i],t,n+1);return r}let r=Ws;for(let i of Object.keys(e))r+=Gs+Js(i)+Ys(e[i],t,n+1);return r}default:return 16}}var Xs=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 cs(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)}},Zs=class e extends ss{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)}},Qs=class extends Zs{session;constructor(e){super(!1,e),this.session=e.session}dispose(){if(this.session){let e=this.session;this.session=void 0,e.shutdown()}}},$s=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={...ks,...n.limits},this.exports.push({hook:t,refcount:1}),this.imports.push(new Xs(this,0,!1)),this.readLoop().catch(e=>this.abort(e))}getMainImport(){return new Qs(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,Bs.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 ms){let{hook:n,pathIfPromise:r}=bs(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=Bs.devaluate(t.value,void 0,this,t,this.encodingLevel);this.send([`resolve`,e,n]),r&&this.releaseExport(e,1)},t=>{this.send([`reject`,e,Bs.devaluate(t,void 0,this,void 0,this.encodingLevel)]),r&&this.releaseExport(e,1)}).catch(t=>{try{this.send([`reject`,e,Bs.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 Zs&&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 Xs(this,e,!1),this.imports[e]=t),new Zs(!1,t)}importPromise(e){if(this.abortReason)throw this.abortReason;if(this.imports[e])return new cs(Error(`Bug in RPC system: The peer sent a promise reusing an existing export ID.`));let t=new Xs(this,e,!0);return this.imports[e]=t,new Zs(!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 Xs(this,n,!1);this.imports.push(r);let i=new Zs(!1,r),a=os.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=Bs.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 Xs(this,this.imports.length,!1);return this.imports.push(i),new Zs(!0,i)}sendStream(e,t,n){if(this.abortReason)throw n.dispose(),this.abortReason;let r=[`pipeline`,e,t],i;try{i=Bs.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=Ys(a));let s=this.imports.length,c=new Xs(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 Xs(this,this.imports.length,!1);return this.imports.push(a),new Zs(!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`,Bs.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 Ts(new Us(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 Ts(new Us(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=os.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 Ts(new Us(this,this.encodingLevel).evaluate(n[2])));else{let e=new Us(this,this.encodingLevel).evaluate(n[2]);e.dispose(),t.resolve(new cs(e.value))}}else n[0]==`resolve`&&new Us(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 Us(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}},ec=class{#e;#t;constructor(e,t,n={}){let r;r=t?new Ts(Ss.fromAppReturn(t)):new cs(Error(`This connection has no main object.`)),this.#e=new $s(e,r,n),this.#t=new ms(this.#e.getMainImport())}getRemoteMain(){return this.#t}getStats(){return this.#e.getStats()}drain(){return this.#e.drain()}};function tc(e,t,n){return new ec(new nc(e),t,n).getRemoteMain()}var nc=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))}},rc,ic=class{context;captureMap=new Map;instructions=[];constructor(e,t){this.context=rc?{parent:rc,captures:[],subject:rc.capture(e),path:t}:{parent:void 0,captures:[],subject:e,path:t},rc=this}unregister(){rc=this.context.parent}makeInput(){return new oc(this,0)}makeOutput(e){let t;try{t=Bs.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 oc(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=Bs.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 oc(this,this.instructions.length)}pushGet(e,t){let n=this.capture(e.dup());return this.instructions.push([`pipeline`,n,t]),new oc(this,this.instructions.length)}capture(e){if(e instanceof oc&&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){}};is.sendMap=(e,t,n)=>{let r=new ic(e,t),i;try{i=Ss.fromAppReturn(ds(r.pushCall.bind(r),()=>n(new hs(r.makeInput(),[]))))}finally{r.unregister()}if(i instanceof Promise)throw i.catch(e=>{}),Error(`RPC map() callbacks cannot be async.`);return new hs(r.makeOutput(i),[])};function ac(){throw Error(`Attempted to use an abstract placeholder from a mapper function. Please make sure your map function has no side effects.`)}var oc=class extends ss{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(rc)return rc.pushGet(this,e);ac()}call(e,t){t.dispose(),ac()}map(e,t,n){for(let e of t)e.dispose();ac()}pull(){ac()}ignoreUnhandledRejections(){}onBroken(e){ac()}},sc=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 Us(this).evaluateCopy(t);if(e.value instanceof ms){let t=vs(e.value);if(t){this.variables.push(t);continue}}this.variables.push(new Ts(e))}return new Us(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 ks}};function cc(e,t,n,r,i){let a=new sc(r,new Ts(Ss.deepCopyFrom(e,t,n)));try{return a.apply(i)}finally{a.dispose()}}is.applyMap=(e,t,n,r,i)=>{try{let a;if(e instanceof hs)throw Error(`applyMap() can't be called on RpcPromise`);if(e instanceof Array){let t=[];try{for(let a of e)t.push(cc(a,e,n,r,i))}catch(e){for(let e of t)e.dispose();throw e}a=Ss.fromArray(t)}else a=e==null?Ss.fromAppReturn(e):cc(e,t,n,r,i);return new Ts(a)}finally{for(let e of r)e.dispose()}};var lc=class e extends ss{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 Os((r===`write`?t.deliverStreamWrite(n.writer):t.deliverCall(n.writer[r],n.writer)).then(e=>new Ts(e)))}catch(e){return t.dispose(),new cs(e)}}map(e,t,n){for(let e of t)e.dispose();return new cs(Error(`Cannot use map() on a WritableStream`))}get(e){return new cs(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)}},uc=262144,dc=1073741824,fc=65536,pc=2,mc=1.25,hc=.9,gc=3,_c=class{now;window=uc;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?pc:mc,s=a*this.minRtt*o;s=Math.min(s,e.windowAtSend*o),s=e.windowFullAtSend?Math.max(s,e.windowAtSend*hc):Math.max(s,this.window),this.window=Math.max(Math.min(s,dc),fc),this.inStartupPhase&&e.sentTime>=this.roundStartTime&&(this.window>this.lastRoundWindow*mc?this.roundsWithoutIncrease=0:++this.roundsWithoutIncrease>=gc&&(this.inStartupPhase=!1),this.roundStartTime=t,this.lastRoundWindow=this.window)}return this.bytesInFlight<this.window}};function vc(e){let t,n=!1,r=new _c(()=>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=Ss.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`],Ss.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`],Ss.fromAppParams([n]));r.then(()=>o(),()=>o())}})}var yc=class e extends ss{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 cs(Error(`Cannot call methods on a ReadableStream stub`))}map(e,t,n){for(let e of t)e.dispose();return new cs(Error(`Cannot use map() on a ReadableStream`))}get(e){return new cs(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){}};os.createWritableStreamHook=lc.create,os.createWritableStreamFromHook=vc,os.createReadableStreamHook=yc.create;var bc=ms,xc=$o,Sc=tc;function Cc(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 wc(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 Tc(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}function Ec(e){let t=e.trim().toLowerCase();if(!t)throw Error(`Invalid keymap token: token cannot be empty`);return t}function Dc(e){let t=e.trim().toLowerCase();if(!t)throw Error(`Invalid key name: key name cannot be empty`);return t}function Oc(e){return{name:Dc(e.name),ctrl:e.ctrl??!1,shift:e.shift??!1,meta:e.meta??!1,super:e.super??!1,hyper:e.hyper||void 0}}function kc(e){return{name:e.name,ctrl:e.ctrl,shift:e.shift,meta:e.meta,super:e.super,hyper:e.hyper||void 0}}function Ac(e,t){let n=kc(Oc(e));return{stroke:n,display:t?.display??Rc(n),match:t?.match??Pc(n),tokenName:t?.tokenName?Ec(t.tokenName):void 0}}function jc(e){return{stroke:kc(e.stroke),display:e.display,match:e.match,tokenName:e.tokenName,patternName:e.patternName,payloadKey:e.payloadKey}}function Mc(e){return e.map(e=>jc(e))}function Nc(e){return`match`in e?e.match:`stroke`in e?Pc(e.stroke):Pc(e)}function Pc(e){return`key:${zc(Oc(e))}`}function Fc(e){let t=e.trim();if(!t)throw Error(`Invalid keymap match id: id cannot be empty`);return`text:${t}`}function Ic(e,t){return`stroke`in e?t?.preferDisplay&&e.display?e.display:Rc(e.stroke):Rc(Oc(e))}function Lc(e,t){return e.map(e=>Ic(e,t)).join(t?.separator??``)}function Rc(e){let t=[];return e.ctrl&&t.push(`ctrl`),e.shift&&t.push(`shift`),e.meta&&t.push(`meta`),e.super&&t.push(`super`),e.hyper&&t.push(`hyper`),t.push(e.name===`return`?`enter`:e.name),t.join(`+`)}function zc(e){return`${e.name}:${+!!e.ctrl}:${+!!e.shift}:${+!!e.meta}:${+!!e.super}:${+!!e.hyper}`}var Bc=Symbol(`keymap-extension-context`);function Vc(e){return e.isDestroyed?null:e.getFocusedTarget()}function Hc(e,t,n){let r=t??e.rootTarget,i=t!==null;for(;r;){if(n(r,i)===!1)return;r=e.getParentTarget(r),i=!1}}function Uc(e,t){let n=new Set;return Hc(e,t,e=>{n.add(e)}),n}function Wc(e,t,n){let r=[],i=Uc(t,n),a=Array.isArray(e)?e:Gc(e);for(let e of a)Kc(t,e,n,i)&&r.push(e);return r}function Gc(e){return[...e].sort((e,t)=>t.priority-e.priority||t.order-e.order)}function Kc(e,t,n,r=Uc(e,n)){let i=t.target;return i?e.isTargetDestroyed(i)?!1:t.targetMode===`focus`?i===n:r.has(i):!0}function qc(e){let t=e.binding.sequence[e.index];if(!t?.patternName)return 0;let n=e.patterns?.at(-1);return n?.name===t.patternName?n.values.length:0}function Jc(e,t,n=!0){let r=e.binding.sequence[e.index];if(!r?.patternName)return!0;let i=t.get(r.patternName);return i?qc(e)>=i.min:n}function Yc(e,t,n=!0){let r=e.binding.sequence[e.index];if(r?.patternName){let n=t.get(r.patternName);if(n&&qc(e)<n.max)return!0}return Jc(e,t,n)&&e.index+1<e.binding.sequence.length}function Xc(e,t){return e.index===e.binding.sequence.length-1&&Jc(e,t,!1)}function Zc(e,t,n,r){return{parent:e,depth:e?e.depth+1:0,stroke:t,match:n,pattern:r,children:new Map,patternChildren:[],bindings:[],reachableBindings:[]}}function Qc(e,t){let n=Zc(null,null,null);for(let r of e){if(r.event!==`press`)continue;let e=n;for(let n of r.sequence){let i;if(n.patternName){let r=t.get(n.patternName);i=e.patternChildren.find(e=>e.pattern?.name===n.patternName),i||(i=Zc(e,n.stroke,n.match,r),e.patternChildren.push(i))}else i=e.children.get(n.match),i||(i=Zc(e,n.stroke,n.match),e.children.set(n.match,i));i.reachableBindings.push(r),e=i}e.bindings.push(r)}return n}function $c(e,t){let n=[];for(let r of e){if(!Jc(r,t))continue;let e=r.index+1,i=r.binding.sequence[e];i&&n.push({part:i,binding:r.binding,index:e,exact:e===r.binding.sequence.length-1,continues:e<r.binding.sequence.length-1})}return n}function el(e,t,n,r){let i=n.patternName;if(!i)return{...e,index:t};let a=[...e.patterns??[]],o=a.at(-1);return o?.name===i?a[a.length-1]={...o,values:[...o.values,r],parts:[...o.parts,n]}:a.push({name:i,payloadKey:n.payloadKey??i,values:[r],parts:[n]}),{layer:e.layer,binding:e.binding,index:t,parts:[...e.parts,n],patterns:a}}function tl(e,t){let n=e.parts.at(-1);if(!n||n.patternName)return t.length;let r=t.indexOf(n.match);return r===-1?t.length:r}function nl(e,t,n,r,i,a,o,s,c){let l=t.sequence[n];if(l){if(l.patternName){let a=s(l.patternName,o);if(!a)return;let u=c(o,l.patternName,a);return el({layer:e,binding:t,index:n,parts:r,patterns:i},n,u,a.value??o.name)}if(a.includes(l.match))return{layer:e,binding:t,index:n,parts:[...r,l],patterns:i}}}function rl(e,t,n,r,i,a){let o=e.binding.sequence[e.index];if(o?.patternName){let s=r.get(o.patternName);if(s&&qc(e)<s.max){let t=i(s.name,n);if(t){let r=a(n,s.name,t);return el(e,e.index,r,t.value??n.name)}}return Jc(e,r,!1)?nl(e.layer,e.binding,e.index+1,e.parts,e.patterns,t,n,i,a):void 0}return nl(e.layer,e.binding,e.index+1,e.parts,e.patterns,t,n,i,a)}function il(e,t,n,r,i){let a=[],o=1/0;for(let s of e.bindings){if(s.event!==`press`)continue;let c=nl(e,s,0,[],void 0,t,n,r,i);if(!c)continue;let l=tl(c,t);l<o&&(o=l,a.length=0),l===o&&a.push(c)}return a}import.meta.require;function al(e){let t=Object.create(null),n=(e,n)=>{let r=t[e];if(!r)return;let i=r.filter(e=>e!==n);i.length===0?delete t[e]:i.length!==r.length&&(t[e]=i)};return{hook(e,r){return t[e]=[...t[e]??[],r],()=>n(e,r)},has(e){return(t[e]?.length??0)>0},emit(n,...r){let i=t[n];if(i)for(let t of i)try{r.length===0?t():t(r[0])}catch(t){e(n,t)}}}}function ol(){let e=[];return{get:()=>e,set:t=>{e=t},remove(t){e=e.filter(e=>e!==t)},has:()=>e.length>0,clear:()=>{e=[]}}}function sl(){let e=ol();return{append(t){return e.set([...e.get(),t]),()=>e.remove(t)},prepend(t){return e.set([t,...e.get()]),()=>e.remove(t)},values:e.get,has:e.has,clear:e.clear}}function cl(){let e=ol(),t=0;return{register(n,r){let i={...r,listener:n,order:t++};return e.set([...e.get(),i].sort((e,t)=>t.priority-e.priority||e.order-t.order)),()=>e.remove(i)},entries:e.get,has:e.has,clear:e.clear}}function ll(e){return typeof e==`string`||!!e&&typeof e==`object`&&!Array.isArray(e)}function ul(e){if(!Array.isArray(e))return{ok:!1,reason:`Invalid keymap bindings: expected an array of binding objects`};for(let[t,n]of e.entries()){if(!n||typeof n!=`object`||Array.isArray(n))return{ok:!1,reason:`Invalid keymap binding at index ${t}: expected a binding object`};if(!ll(n.key))return{ok:!1,reason:`Invalid keymap binding at index ${t}: expected "key" to be a string or keystroke object`}}return{ok:!0}}function dl(e){let t=ul(e);if(!t.ok)throw Error(t.reason);return e.map(e=>({...e,key:typeof e.key==`string`?e.key:{...e.key}}))}function fl(e){return{...e,sequence:Mc(e.sequence)}}function pl(e,t){let n=sl();return{prependLayerAnalyzer(e){return n.prepend(e)},appendLayerAnalyzer(e){return n.append(e)},clearLayerAnalyzers(){n.clear()},analyzeLayer(r){let i=n.values();if(i.length===0)return;let a=ml(r.bindings),o={target:r.target,order:r.order,sourceBindings:r.sourceBindings,bindings:a,hasTokenBindings:r.hasTokenBindings,checkCommandResolution(e){return t.getCommandResolutionStatus(e,r.commands)},warn(t,n,r){e.emitWarning(t,n,r)},warnOnce(t,n,r,i){e.warnOnce(t,n,r,i)},error(t,n,r){e.emitError(t,n,r)}};for(let t of i)try{t(o)}catch(t){e.emitError(`layer-analyzer-error`,t,`[Keymap] Error in layer analyzer:`)}}}}function ml(e){return e.map(t=>({sequence:Mc(t.sequence),command:t.command,attrs:t.attrs,event:t.event,preventDefault:t.preventDefault,fallthrough:t.fallthrough,parsedBinding:fl(t.parsedBinding),sourceTarget:t.sourceTarget,sourceLayerOrder:t.sourceLayerOrder,bindingIndex:t.bindingIndex,hasCommandAtSequence:e.some(e=>e.event===`press`&&e.command!==void 0&&hl(e,t)),hasContinuations:e.some(e=>e.event===`press`&&gl(t,e))}))}function hl(e,t){return e.sequence.length===t.sequence.length&&e.sequence.every((e,n)=>e.match===t.sequence[n]?.match)}function gl(e,t){return e.sequence.length<t.sequence.length&&e.sequence.every((e,n)=>e.match===t.sequence[n]?.match)}function _l(){return{version:-1,notifyVersion:-1,focused:void 0,value:[],targets:new WeakMap}}function vl(){return{plain:_l(),bindings:_l(),metadata:_l(),bindingsAndMetadata:_l()}}function yl(e,t){if(t===void 0)return e.plain;let n=t.includeBindings===!0,r=t.includeMetadata===!0;return n?r?e.bindingsAndMetadata:e.bindings:r?e.metadata:e.plain}function bl(e,t,n){let r=n?e.targets.get(n):e.nullTarget;return r?.version===t?r:void 0}function xl(e,t,n,r){let i={version:t,value:r};n?e.targets.set(n,i):e.nullTarget=i}function Sl(e,t){if(e===t)return!0;if(!e||!t||e.captures.length!==t.captures.length)return!1;for(let n=0;n<e.captures.length;n+=1){let r=e.captures[n],i=t.captures[n];if(!r||!i||r.layer!==i.layer||r.binding!==i.binding||r.index!==i.index||r.parts.length!==i.parts.length)return!1;for(let e=0;e<r.parts.length;e+=1)if(r.parts[e]?.match!==i.parts[e]?.match)return!1;let a=r.patterns??[],o=i.patterns??[];if(a.length!==o.length)return!1;for(let e=0;e<a.length;e+=1){let t=a[e],n=o[e];if(!t||!n||t.name!==n.name||t.values.length!==n.values.length)return!1;for(let e=0;e<t.values.length;e+=1)if(!Object.is(t.values[e],n.values[e]))return!1}}return!0}function Cl(e){let t=e.parts.at(-1);if(!t||e.parts.length<=1)return;let n=e.index-1,r=e.patterns;if(t.patternName){let i=r?.at(-1);i?.name===t.patternName&&(i.values.length>1?(n=e.index,r=[...(r??[]).slice(0,-1),{...i,values:i.values.slice(0,-1),parts:i.parts.slice(0,-1)}]):r=(r??[]).slice(0,-1))}return{layer:e.layer,binding:e.binding,index:n,parts:e.parts.slice(0,-1),patterns:r}}function wl(e){let t=e.captures[0];if(!t||t.parts.length===0)return[];let n=[];for(let r=0;r<t.parts.length;r+=1){let i=t.parts[r];if(!i)continue;let a,o,s=!1,c=!1;for(let t of e.captures){let e=t.parts[r];if(e){if(a===void 0){a=e.display,o=e.tokenName;continue}!s&&a!==e.display&&(s=!0),!c&&o!==e.tokenName&&(c=!0)}}(a===void 0||s)&&(a=Ic(i.stroke)),c&&(o=void 0),n.push(Ac(i.stroke,{display:a,match:i.match,tokenName:o}))}return n}function Tl(e){if(e.isDestroyed)throw Error(`Cannot use a keymap after its host was destroyed`);return e}function El(e,t,n,r,i,a,o={}){let s=vl(),c=-1,l=[],u=()=>Tl(t).getFocusedTarget(),d=()=>Vc(t),f=t=>{let n=e.pending;Sl(n,t)||(e.pending=t,o.onPendingSequenceChanged?.(n,t),fe(),r.queueStateChange())},p=()=>{let t=e.pending;if(!t)return;let n=u(),r=a.getActiveCommandView(n),o=t.captures.filter(t=>e.layers.has(t.layer)&&C(t.layer,n)&&i.matchesConditions(t.layer)&&ee(t.binding,n,r)&&Yc(t,e.patterns));if(o.length===0){f(null);return}return o.length!==t.captures.length&&f({captures:o}),e.pending??void 0},m=()=>{t.isDestroyed||!e.pending||p()},h=()=>!t.isDestroyed&&e.pending!==null,g=()=>{if(c===e.cacheVersion)return l;let t=p(),n=t?wl(t):[];return(!t||T())&&(c=e.cacheVersion,l=n),n},_=()=>{let e=p();if(!e)return!1;let t=e.captures[0];if(!t||t.parts.length<=1)return f(null),!0;let n=[];for(let t of e.captures){let e=Cl(t);e&&n.push(e)}return n.length===0?(f(null),!0):(f({captures:n}),!0)},v=t=>{let n=t?.includeBindings===!0,r=t?.includeMetadata===!0,i=yl(s,t);return i.notifyVersion===e.derivedVersion?i.value:y(i,n,r)},y=(n,r,i)=>{t.isDestroyed&&Tl(t);let o=u(),s=bl(n,e.cacheVersion,o);if(s)return n.notifyVersion=e.derivedVersion,n.version=e.cacheVersion,n.focused=o,n.value=s.value,s.value;let c=a.getActiveCommandView(o),l=p(),d=l?[]:S(o),f=l?re(l.captures,r,i,o,c):A(d,r,i,o,c);return(l?T():w(d))&&(n.version=e.cacheVersion,n.notifyVersion=e.derivedVersion,n.focused=o,n.value=f,xl(n,e.cacheVersion,o,f)),f},b=(e,t)=>{let n=t?.includeBindings===!0,r=t?.includeMetadata===!0,i=u(),o=a.getActiveCommandView(i);return re(e,n,r,i,o)},x=(e,t)=>{let n=t?.includeBindings===!0,r=t?.includeMetadata===!0,i=e===d()?p():void 0,o=a.getActiveCommandView(e);return i?re(i.captures,n,r,e,o):A(S(e),n,r,e,o)},S=n=>e.activeLayersCacheVersion===e.cacheVersion&&e.activeLayersCacheFocused===n?e.activeLayersCache:(e.activeLayersCacheVersion=e.cacheVersion,e.activeLayersCacheFocused=n,e.activeLayersCache=Wc(e.sortedLayers,t,n),e.activeLayersCache),C=(e,n)=>Kc(t,e,n),w=t=>!e.commandResolvers.has()&&e.activeKeyCacheBlockers===0,T=()=>!e.commandResolvers.has()&&e.activeKeyCacheBlockers===0,E=(e,t,n)=>{let r=[];for(let o of e)i.matchesConditions(o)&&a.isBindingVisible(o,t,n)&&r.push(o);return r},ee=(e,t,n)=>i.matchesConditions(e)&&a.isBindingVisible(e,t,n),D=(e,t)=>{let n,r,i=!1,a=!1;for(let o of e){let e=o.sequence[t];if(e){if(n===void 0){n=e.display,r=e.tokenName;continue}!i&&n!==e.display&&(i=!0),!a&&r!==e.tokenName&&(a=!0)}}if(n===void 0||i){let r=e[0]?.sequence[t]?.stroke;n=r?Ic(r):``}return a&&(r=void 0),{display:n,tokenName:r}},O=(e,t,n)=>({sequence:e.sequence,command:e.command,commandAttrs:a.getBindingCommandAttrs(e,t,n),attrs:e.attrs,event:e.event,preventDefault:e.preventDefault,fallthrough:e.fallthrough}),k=(e,t,n)=>e.map(e=>O(e,t,n)),A=(e,t,n,r,a)=>{let o=new Map,s=new Set;for(let n of e)n.root.children.size===0&&n.root.patternChildren.length===0||!i.matchesConditions(n)||(j(n.root.children.values(),o,s,t,r,a),j(n.root.patternChildren,o,s,t,r,a));return oe(o,t,n,r,a)},j=(e,t,n,r,i,a)=>{for(let o of e){let e=o.match;if(!e||n.has(e)||!o.stroke)continue;let s=te(o,r,i,a);if(!s)continue;let c=t.get(e);c?M(c,s,r):t.set(e,ue(o.stroke,s,r)),s.stop&&n.add(e)}},te=(e,t,n,r)=>{if(!(e.children.size>0||e.patternChildren.length>0)){let i=le(ne(e)?E(e.bindings,n,r):e.bindings,n,r);if(!i)return;let a=D(i.bindings,e.depth-1);return{display:a.display,tokenName:a.tokenName,continues:!1,firstBinding:i.bindings[0],commandBinding:i.commandBinding,bindings:t?[...i.bindings]:void 0,stop:i.stop}}let i=E(e.reachableBindings,n,r);if(i.length===0)return;let a=le(e.bindings,n,r),o=D(i,e.depth-1);return{display:o.display,tokenName:o.tokenName,continues:!0,firstBinding:a?.bindings[0],commandBinding:a?.commandBinding,bindings:t&&a?[...a.bindings]:void 0,stop:!0}},ne=t=>{if(e.commandResolvers.has())return!0;for(let e of t.bindings)if(e.matchers.length>0)return!0;return!1},re=(t,n,r,i,a)=>{let o=new Map,s=new Set;return ie($c(t,e.patterns),o,s,n,i,a),oe(o,n,r,i,a)},ie=(e,t,n,r,i,a)=>{let o=new Set;for(let s of e)o.has(s.part.match)||(o.add(s.part.match),ae(s,e,t,n,r,i,a))},ae=(e,t,n,r,i,a,o)=>{let s=e.part.match;if(r.has(s))return;let c=se(e,t,i,a,o);if(!c)return;let l=n.get(s);l?M(l,c,i):n.set(s,ue(e.part.stroke,c,i)),c.stop&&r.add(s)},oe=(e,t,n,r,i)=>{let a=[];for(let o of e.values()){let e=de(o,t,n,r,i);e&&a.push(e)}return a},se=(e,t,n,r,i)=>{let a=t.filter(t=>t.part.match===e.part.match),o=a.filter(e=>e.exact).map(e=>e.binding),s=le(o,r,i),c=a.some(e=>e.continues);if(!c&&!s)return;let l=ce(a);return{display:l.display,tokenName:l.tokenName,continues:c,firstBinding:s?.bindings[0],commandBinding:s?.commandBinding,bindings:n&&s?[...s.bindings]:void 0,stop:c||s?.stop===!0}},ce=e=>{let t,n,r=!1,i=!1;for(let a of e){let e=a.part;if(t===void 0){t=e.display,n=e.tokenName;continue}!r&&t!==e.display&&(r=!0),!i&&n!==e.tokenName&&(i=!0)}let a=e[0]?.part;return(t===void 0||r)&&(t=a?Ic(a.stroke):``),i&&(n=void 0),{display:t,tokenName:n}},le=(e,t,n)=>{let r=[],o;for(let s of e)if(!(!i.matchesConditions(s)||!a.isBindingVisible(s,t,n))&&(r.push(s),s.command!==void 0&&(o??=s,!s.fallthrough)))return{bindings:r,commandBinding:o,stop:!0};if(r.length!==0)return{bindings:r,commandBinding:o,stop:!1}},ue=(e,t,n)=>({stroke:e,display:t.display,tokenName:t.tokenName,continues:t.continues,firstBinding:t.firstBinding,commandBinding:t.commandBinding,bindings:n&&t.bindings?[...t.bindings]:void 0}),M=(e,t,n)=>{if(!e.firstBinding&&t.firstBinding&&(e.firstBinding=t.firstBinding),!e.commandBinding&&t.commandBinding&&(e.commandBinding=t.commandBinding),t.continues&&(e.continues=!0),!(!n||!t.bindings||t.bindings.length===0)){if(!e.bindings){e.bindings=[...t.bindings];return}e.bindings.push(...t.bindings)}},de=(e,t,n,r,i)=>{if(!e.commandBinding&&!e.continues)return;let o={stroke:kc(e.stroke),display:e.display,continues:e.continues};if(e.tokenName&&(o.tokenName=e.tokenName),e.commandBinding&&(o.command=e.commandBinding.command),t&&e.bindings&&e.bindings.length>0&&(o.bindings=e.bindings.length===1?[O(e.bindings[0],r,i)]:k(e.bindings,r,i)),n){e.firstBinding?.attrs&&(o.bindingAttrs=e.firstBinding.attrs);let t=e.commandBinding?a.getBindingCommandAttrs(e.commandBinding,r,i):void 0;t&&(o.commandAttrs=t)}return o},fe=()=>{n.has(`pendingSequence`)&&n.emit(`pendingSequence`,e.pending?wl(e.pending):[])};return{getFocusedTarget:u,getFocusedTargetIfAvailable:d,setPendingSequence:f,ensureValidPendingSequence:p,revalidatePendingSequenceIfNeeded:m,hasPendingSequenceState:h,getPendingSequence:g,popPendingSequence:_,getActiveKeys:v,getActiveKeysForCaptures:b,getActiveKeysForFocused:x,getActiveLayers:S,isLayerActiveForFocused:C,collectSequencePartsFromPending:wl,collectMatchingBindings:E,collectActiveBindings:k}}var Dl=new Set([`name`,`run`,`fields`,`attrs`,`rejectedResult`]),Ol=new Set([`key`,`cmd`,`event`,`preventDefault`,`fallthrough`]),kl=new Set([`target`,`targetMode`,`priority`,`bindings`,`commands`]);function Al(e){if(e===void 0||typeof e==`function`)return e;let t=e.trim();if(!t)throw Error(`Invalid keymap command: command cannot be empty`);return t}function jl(e){let t=e.trim();if(!t)throw Error(`Invalid keymap command name: name cannot be empty`);if(/\s/.test(t))throw Error(`Invalid keymap command name "${e}": command names cannot contain whitespace`);return t}function Ml(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function Nl(e){let t=[],n=new Map;for(let r of e.layers)for(let e of r.commands){let i={layer:r,commandState:e};t.push(i),Ml(n,e.command.name,i)}return{entries:t,chainsByName:n}}function Pl(e,t,n){let r=[],i=[],a=new Map,o=new Map;for(let s of e)if(s.commands.length!==0&&!(n&&!t.matchesConditions(s)))for(let e of s.commands){if(!t.matchesConditions(e))continue;let n={layer:s,commandState:e};r.push(n),Ml(o,e.command.name,n),a.has(e.command.name)||(a.set(e.command.name,n),i.push(n))}return{layers:e,entries:r,reachable:i,reachableByName:a,chainsByName:o}}function Fl(e,t,n,r){return(e.activeLayersCacheVersion!==e.cacheVersion||e.activeLayersCacheFocused!==r)&&(e.activeLayersCacheVersion=e.cacheVersion,e.activeLayersCacheFocused=r,e.activeLayersCache=Wc(e.sortedLayers,t,r)),Pl(e.activeLayersCache,n,!0)}function Il(e,t,n,r){if(Object.prototype.hasOwnProperty.call(e,t)&&!Object.is(e[t],n))throw Error(`Conflicting keymap requirement for "${t}" from ${r}`);e[t]=n}function Ll(e,t,n,r){if(Object.prototype.hasOwnProperty.call(e,t)&&!Object.is(e[t],n))throw Error(`Conflicting keymap attribute for "${t}" from ${r}`);e[t]=n}function Rl(e){let t=`field ${e.fieldName}`;return{require(n,r){Il(e.requirements,n,r,t)},attr(n,r){if(!e.attrs)throw Error(`Keymap ${t} cannot publish attrs`);Ll(e.attrs,n,r,t)},activeWhen(n){e.matchers.push(e.conditions.buildRuntimeMatcher(n,t))}}}function zl(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Bl(e,t){return e instanceof Error&&e.message?e.message:t}function Vl(e){return!e||typeof e!=`object`&&typeof e!=`function`?!1:typeof e.then==`function`}function Hl(e,t){let n=t?.deep===!0,r=t?.freeze===!0,i=t?.preserveNonPlainObjects===!0;if(Array.isArray(e)){let i=n?e.map(e=>Hl(e,t)):[...e];return r?Object.freeze(i):i}if(e&&typeof e==`object`){if(i&&!zl(e))return e;let a={};for(let[r,i]of Object.entries(e))a[r]=n?Hl(i,t):i;return r?Object.freeze(a):a}return e}var Ul=[`name`],Wl=Object.freeze({}),Gl=new WeakMap;function Kl(e,t,n,r,i){let a=-1,o,s=-1,c,l,u=-1,d,f,p=-1,m,h=-1,g=new Map,_=t=>Jl({commands:t,commandFields:e.commandFields,conditions:r,onError:(e,t,r)=>{n.emitError(e,t,r)}}),v=t=>oe(()=>e.commandResolvers.prepend(t),t),y=t=>oe(()=>e.commandResolvers.append(t),t),b=()=>{e.commandResolvers.has()&&n.runWithStateChangeBatch(()=>{e.commandResolvers.clear(),i.onCommandResolversChanged(),n.queueStateChange()})},x=e=>me(e).map(e=>ql(e.commandState)),S=e=>{let t=pe(e),n=me(e,t);if(n.length===0)return[];let r=n.map(e=>({entry:e,command:ql(e.commandState),commandAttrs:e.commandState.attrs,bindings:[]})),i=new Map;for(let[e,t]of r.entries()){let n=i.get(t.command.name);n?n.push(e):i.set(t.command.name,[e])}return i.size>0&&he(r,i,t),r.map(e=>({command:e.command,bindings:e.bindings}))},C=t=>{if(t.visibility===`registered`&&u===e.derivedVersion&&d===t.commands&&f)return f;let n=new Map;for(let e of t.commands)n.has(e)||n.set(e,[]);return n.size===0?n:(ge(n,pe(t)),t.visibility===`registered`&&(u=e.derivedVersion,d=t.commands,f=n),n)},w=(e,t,n)=>{let r=j(t);if(n){let i=[],a=r.chainsByName.get(e);if(a)for(let e of a)i.push({target:e.layer.target,command:e.commandState.command,attrs:e.commandState.attrs,payload:n.payload});let o=xe(e,t,{mode:`active`,execution:n});return o.resolved&&i.push(o.resolved),{entries:i.length>0?i:void 0,hadError:o.hadError}}let i=[];for(let t of r.chainsByName.get(e)??[])i.push({target:t.layer.target,command:t.commandState.command,attrs:t.commandState.attrs});let a=xe(e,t,{mode:`active`});return a.resolved&&i.push(a.resolved),{entries:i.length>0?i:void 0,hadError:a.hadError}},T=t=>{if(h!==e.derivedVersion&&(h=e.derivedVersion,g=new Map),g.has(t))return g.get(t)??void 0;let n=ue(le(t));return g.set(t,n??null),n},E=(e,t)=>ue(j(t).chainsByName.get(e)),ee=(e,t)=>xe(e,null,{mode:`registered`,execution:t}),D=(e,t,n)=>xe(e,t,{mode:`active`,execution:n}),O=(e,t)=>se(e,t)?.command,k=e=>ce(e)?.commandState.command,A=(e,n,i)=>{let a=te().chainsByName.get(e);if(!a||a.length===0)return;let o,s;for(let e of a){if(!Kc(t,e.layer,n)){o??=e;continue}(!r.matchesConditions(e.layer)||!r.matchesConditions(e.commandState))&&(s??=e)}let c=s??o;if(c)return{reason:s?`disabled`:`inactive`,command:i?c.commandState.command:void 0}},j=n=>{if(s===e.derivedVersion&&c===n&&l)return l;let i=Fl(e,t,r,n);return ne()&&(s=e.derivedVersion,c=n,l=i),i},te=()=>a===e.derivedVersion&&o?o:(a=e.derivedVersion,o=Nl(e),o),ne=()=>e.activeCommandViewCacheBlockers===0,re=(e,t,n)=>e.command===void 0||e.run?!0:typeof e.command==`string`?n.reachableByName.has(e.command)?!0:M(e.command,t,`active`)!==void 0:!1,ie=(e,t,n)=>{if(typeof e.command!=`string`)return;let r=n.reachableByName.get(e.command);return r?r.commandState.attrs:M(e.command,t,`active`)?.attrs},ae=(e,n)=>{if(n?.some(t=>t.command.name===e)||te().chainsByName.has(e))return`resolved`;let r=xe(e,Vc(t));return r.resolved||r.hadError?r.resolved?`resolved`:`error`:`unresolved`},oe=(t,r)=>n.runWithStateChangeBatch(()=>{let a=t();return i.onCommandResolversChanged(),n.queueStateChange(),()=>{n.runWithStateChangeBatch(()=>{a(),!e.commandResolvers.values().includes(r)&&(i.onCommandResolversChanged(),n.queueStateChange())})}}),se=(e,t)=>{let n=j(t).reachableByName.get(e);return n?{target:n.layer.target,command:n.commandState.command,attrs:n.commandState.attrs}:M(e,t,`active`)},ce=e=>le(e)?.[0],le=t=>{let n=[];for(let r of e.sortedLayers)for(let e of r.commands)e.command.name===t&&n.push({layer:r,commandState:e});return n.length>0?n:void 0},ue=e=>{if(e?.length)return e.map(e=>({target:e.layer.target,command:e.commandState.command,attrs:e.commandState.attrs}))},M=(e,t,n)=>xe(e,t,{mode:n}).resolved,de=()=>te().entries,fe=()=>{if(p===e.derivedVersion&&m)return m;let t=new Map;for(let n of e.layers)for(let e of n.bindings){if(typeof e.command!=`string`)continue;let n=t.get(e.command);n?n.push(e):t.set(e.command,[e])}return p=e.derivedVersion,m=t,t},pe=e=>{let n=e?.visibility??`reachable`,r=e&&Object.prototype.hasOwnProperty.call(e,`focused`)?e.focused??null:Vc(t);return n===`registered`?{visibility:n,focused:r}:{visibility:n,focused:r,activeView:j(r)}},me=(e,t=pe(e))=>{let r;return r=t.visibility===`registered`?de():t.visibility===`active`?t.activeView?.entries??[]:t.activeView?.reachable??[],$l({entries:r,query:e,getCommand:e=>ql(e),onFilterError:e=>{n.emitError(`command-query-filter-error`,e,`[Keymap] Error in command query filter:`)}})},he=(e,t,n)=>{_e(n,n=>{ve(e,t,n)})},ge=(e,t)=>{if(t.visibility===`registered`){let t=fe();for(let[n,r]of e){let e=te().chainsByName.get(n)?.[0]?.commandState.attrs;for(let i of t.get(n)??[])r.push(be(i,e))}return}_e(t,n=>{ye(e,n,t)})},_e=(t,n)=>{if(t.visibility===`registered`){for(let t of e.layers)for(let e of t.bindings)n(e);return}let i=t.activeView;if(i){for(let e of i.layers)if(!(e.bindings.length===0||!r.matchesConditions(e)))for(let a of e.bindings)r.matchesConditions(a)&&re(a,t.focused,i)&&n(a)}},ve=(e,t,n)=>{if(typeof n.command!=`string`)return;let r=t.get(n.command);if(!(!r||r.length===0))for(let t of r){let r=e[t];r&&r.bindings.push(be(n,r.commandAttrs))}},ye=(e,t,n)=>{if(typeof t.command!=`string`)return;let r=e.get(t.command);r&&r.push(be(t,N(t,n)))},be=(e,t)=>({sequence:e.sequence,command:e.command,commandAttrs:t,attrs:e.attrs,event:e.event,preventDefault:e.preventDefault,fallthrough:e.fallthrough}),N=(e,t)=>{if(typeof e.command!=`string`)return;if(t.visibility===`registered`)return te().chainsByName.get(e.command)?.[0]?.commandState.attrs;let n=t.activeView;if(n)return ie(e,t.focused,n)},xe=(t,r,i)=>{let a=i?.mode??`active`,o=i?.execution??{input:t},s=Yl(t,e.commandResolvers.values(),()=>we(r,a,o),e=>{n.emitError(`command-resolver-error`,e,`[Keymap] Error in command resolver for "${t}":`)}),c=s.resolved;if(c){let e=Ce(c.command.name,r,a);e?.commandState.command===c.command&&c.target===void 0&&(c={...c,target:e.layer.target},s.resolved=c)}if(c&&!c.attrs){let e=Se(c.command.name,r,a)??Ql(c.command);e&&(s.resolved={...c,attrs:e})}return s},Se=(e,t,n)=>n===`registered`?ce(e)?.commandState.attrs:j(t).reachableByName.get(e)?.commandState.attrs,Ce=(e,t,n)=>n===`registered`?ce(e):j(t).reachableByName.get(e),we=(e,t,n)=>{let r=n.input,i=n.payload;return{context:{get input(){return r},get payload(){return i},setInput(e){r=e},setPayload(e){i=e},getCommand:n=>t===`registered`?k(n):O(n,e)},getExecutionFields(){return{input:r,payload:i}}}};return{normalizeCommands:_,prependCommandResolver:v,appendCommandResolver:y,clearCommandResolvers:b,getCommands:x,getCommandEntries:S,getCommandBindings:C,getResolvedCommandChain:w,getRegisteredResolvedEntries:T,getActiveRegisteredResolvedEntries:E,resolveRegisteredResolverFallback:ee,resolveActiveResolverFallback:D,getTopCommand:O,getDispatchUnavailableCommandState:A,getActiveCommandView:j,isBindingVisible:re,getBindingCommandAttrs:ie,getCommandResolutionStatus:ae}}function ql(e){return e.command}function Jl(e){let t=[],n=new Set;for(let r of e.commands)try{let i={},a=[],o=jl(r.name),s=Xl(r),c={};if(n.has(o)){e.onError(`duplicate-command`,{command:o},`Duplicate keymap command "${o}" in the same layer`);continue}r.name=o;for(let[t,n]of Object.entries(s)){if(n===void 0)continue;let r=e.commandFields.get(t);r&&r(n,Rl({fieldName:t,conditions:e.conditions,requirements:i,matchers:a,attrs:c}))}let l={command:r,fields:s,attrs:Object.keys(c).length===0?void 0:c,requires:Object.entries(i),matchers:a};n.add(l.command.name),t.push(l)}catch(t){e.onError(`register-command-failed`,t,Bl(t,`Failed to register keymap command "${String(r.name)}"`));continue}return t}function Yl(e,t,n,r){if(t.length===0)return{hadError:!1};let i=!1;for(let a of t){let t,o=n();try{t=a(e,o.context)}catch(e){i=!0,r(e);continue}if(t)return{hadError:i,resolved:Zl(t,o.getExecutionFields())}}return{hadError:i}}function Xl(e){let t={};for(let[n,r]of Object.entries(e))!Dl.has(n)&&r!==void 0&&(t[n]=r);return Object.keys(t).length===0?Wl:t}function Zl(e,t){return{command:e,input:t.input,payload:t.payload}}function Ql(e){let t=Xl(e);return t===Wl?void 0:t}function $l(e){let t=e.query?.namespace,n=eu(e.query?.limit);if(n===0)return[];let r=e.query?.search?.trim().toLowerCase()??``,i=Ul;e.query?.searchIn&&e.query.searchIn.length>0&&(i=e.query.searchIn);let a=e.query?.filter,o,s,c;if(typeof a==`function`)s=a;else if(a){let e=Object.entries(a),t=[];for(let[n,r]of e){if(n===`name`){if(typeof r==`string`){c=new Set([r]);continue}if(Array.isArray(r)){let e=new Set;for(let t of r)typeof t==`string`&&e.add(t);c=e;continue}}t.push([n,r])}o=t.length>0?t:void 0}let l=[];for(let a of e.entries){let u=a.commandState;if(nu(u,t)&&tu(u,r,i)&&!(c&&!c.has(u.command.name))&&ru(u,o,e)){if(s){let t=!1;try{t=s(e.getCommand(u))}catch(t){e.onFilterError(t);continue}if(!t)continue}if(l.push(a),n!==void 0&&l.length>=n)break}}return l}function eu(e){if(e===void 0)return;let t=Math.floor(Number(e));return!Number.isFinite(t)||t<=0?0:t}function tu(e,t,n){if(!t)return!0;for(let r of n)if(iu(e,r,t))return!0;return!1}function nu(e,t){if(t===void 0)return!0;let n=e.fields;return Object.prototype.hasOwnProperty.call(n,`namespace`)?du(n.namespace,t):!1}function ru(e,t,n){if(!t)return!0;for(let[r,i]of t)if(!cu(e,r,i,n))return!1;return!0}function iu(e,t,n){return au(e,t)?.includes(n)===!0}function au(e,t){let n=Gl.get(e);if(n||(n=new Map,Gl.set(e,n)),n.has(t))return n.get(t);let r=e.fields,i=e.attrs,a;t===`name`?a=e.command.name:Object.prototype.hasOwnProperty.call(r,t)?a=r[t]:i&&Object.prototype.hasOwnProperty.call(i,t)&&(a=i[t]);let o=ou(a);return n.set(t,o),o}function ou(e){if(Array.isArray(e)){let t=[];for(let n of e){let e=ou(n);e!==void 0&&t.push(e)}return t.length>0?t.join(`\0`):void 0}if(typeof e==`string`)return e.toLowerCase();if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e).toLowerCase()}function su(e,t,n,r){try{return e(t,n)}catch(e){return r(e),!1}}function cu(e,t,n,r){return typeof n==`function`?lu(e,t,n,r):uu(e,t,n)}function lu(e,t,n,r){let i=e.command,a=e.fields,o=e.attrs,s,c=!1,l=()=>s??=r.getCommand(e);return t===`name`&&(c=!0,su(n,i.name,l(),r.onFilterError))||Object.prototype.hasOwnProperty.call(a,t)&&(c=!0,su(n,a[t],l(),r.onFilterError))||o&&Object.prototype.hasOwnProperty.call(o,t)&&(c=!0,su(n,o[t],l(),r.onFilterError))?!0:!c&&su(n,void 0,l(),r.onFilterError)}function uu(e,t,n){let r=e.command,i=e.fields,a=e.attrs;return t===`name`&&du(r.name,n)||Object.prototype.hasOwnProperty.call(i,t)&&du(i[t],n)?!0:!!a&&Object.prototype.hasOwnProperty.call(a,t)&&du(a[t],n)}function du(e,t){return Array.isArray(t)?t.some(t=>fu(e,t)):fu(e,t)}function fu(e,t){return Array.isArray(e)?e.some(e=>fu(e,t)):Object.is(e,t)}function pu(e,t,n,r,i){let a=(e,t,n,r,a,o)=>({keymap:i.keymap,event:e,focused:t,target:n,data:r,input:a,payload:o}),o=(t,n,r,i)=>{let a=typeof n==`function`?void 0:n,o=typeof n==`function`?n:n.run,s=i?a:void 0,c;try{c=o(a?{...r,command:a}:r)}catch(n){return e.emitError(`command-execution-error`,n,`[Keymap] Error running command "${t}":`),{status:`error`,result:s?{ok:!1,reason:`error`,command:s}:{ok:!1,reason:`error`}}}if(Vl(c))return c.catch(n=>{e.emitError(`async-command-error`,n,`[Keymap] Async error in command "${t}":`)}),{status:`handled`,result:s?{ok:!0,command:s}:{ok:!0}};if(mu(c)){let e=c;return(!c.ok&&c.reason!==`not-found`&&i&&a&&!c.command||c.ok&&i&&a&&!c.command)&&(e={...c,command:a}),{status:c.ok?`handled`:`rejected`,result:e}}return c===!1?{status:`rejected`,result:s?{ok:!1,reason:`rejected`,command:s}:{ok:!1,reason:`rejected`}}:{status:`handled`,result:s?{ok:!0,command:s}:{ok:!0}}},s=(e,t,n,r,i,s,c,l)=>{let u;for(let d of t??[]){let t=o(e,d.command,a(n,r,i??d.target??null,s,e,c),l);if(t.status===`handled`||t.status===`error`)return[t.result,u];u=t.result}return[void 0,u]},c=(e,c,l)=>{let u;try{u=Al(e)}catch{return{ok:!1,reason:`invalid-args`}}if(typeof u!=`string`)return{ok:!1,reason:`not-found`};let d=c?.includeCommand===!0,f=c?.focused??n.getFocusedTargetIfAvailable(),p=c?.event??i.createCommandEvent(),m=t.getReadonlyData(),h=c?.payload,g=l===`registered`?r.getRegisteredResolvedEntries(u):r.getActiveRegisteredResolvedEntries(u,f),[_,v]=s(u,g,p,f,c?.target,m,h,d);if(_)return _;let y=v,b=l===`registered`?r.resolveRegisteredResolverFallback(u,{input:u,payload:h}):r.resolveActiveResolverFallback(u,f,{input:u,payload:h});if(b.resolved){let e=o(u,b.resolved.command,a(p,f,c?.target??b.resolved.target??null,m,b.resolved.input??u,b.resolved.payload),d);if(e.status===`handled`||e.status===`error`)return e.result;y=e.result}if(b.hadError)return{ok:!1,reason:`error`};if(l===`active`){let e=r.getDispatchUnavailableCommandState(u,f,d);if(e)return e.command?{ok:!1,reason:e.reason,command:e.command}:{ok:!1,reason:e.reason}}return y??{ok:!1,reason:`not-found`}};return{runCommand(e,t){return c(e,t,`registered`)},dispatchCommand(e,t){return c(e,t,`active`)},runBinding(e,n,i,s,c){let l=t.getReadonlyData();if(n.run)return o(typeof n.command==`string`?n.command:`<function>`,n.run,a(i,s,e.target??null,l,typeof n.command==`string`?n.command:`<function>`,c),!1).status!==`rejected`&&(hu(n,i),!0);if(typeof n.command!=`string`)return!1;let u=r.getResolvedCommandChain(n.command,s,c===void 0?void 0:{input:n.command,payload:c}).entries;for(let t of u??[])if(o(n.command,t.command,a(i,s,t.target??e.target??null,l,t.input??n.command,t.payload),!1).status!==`rejected`)return hu(n,i),!0;return!1}}}function mu(e){return typeof e==`object`&&!!e&&`ok`in e}function hu(e,t){e.preventDefault&&(t.preventDefault(),t.stopPropagation())}var gu=Object.freeze({}),_u=[],vu=[];function yu(e){if(Object.keys(e).length!==0)return Hl(e,{freeze:!0})}function bu(e,t,n,r){let i=t=>Eu(t,e.bindingParsers.values(),{tokens:e.tokens,patterns:e.patterns,layer:gu,parseObjectKey:(e,t)=>c(e,t)}),a=t=>{if(typeof t!=`string`)return[c(t)];let n=Tu(t,e.bindingParsers.values(),{tokens:e.tokens,patterns:e.patterns,layer:gu,parseObjectKey:(e,t)=>c(e,t)});for(let e of n.unknownTokens)r.warnUnknownToken(e,t);return n.unknownTokens.length>0?[]:n.parts},o=(e,t)=>Lc(a(e),t),s=(i,a,o,s,d)=>{let f=[],p=!1,m=e.bindingExpanders.values(),h=e.bindingParsers.values(),g=e.bindingFields,_=e.disambiguationResolvers.has(),v=r.warnUnknownField,y=r.warnUnknownToken;for(let[r,b]of i.entries()){let i;try{i=Cu(b.key,m,{layer:d})}catch(e){t.emitError(`binding-expand-error`,e,Bl(e,`Failed to expand keymap binding`));continue}for(let m of i){let i=m.key,x;try{x=typeof i==`string`?Tu(i,h,{tokens:a,patterns:e.patterns,layer:d,parseObjectKey:(e,t)=>c(e,t)}):{parts:[c(i)],usedTokens:[],unknownTokens:[],hasTokenBindings:!1},x=wu(x,m)}catch(e){t.emitError(`binding-parse-error`,e,Bl(e,`Failed to parse keymap binding`));continue}let S=x.parts;p||=x.hasTokenBindings;for(let e of x.unknownTokens)y(e,typeof i==`string`?i:String(i.name));if(!(x.unknownTokens.length>0))for(let i of u(b,S,a,h,d))try{let t=l(i.event),a=i.sequence,c={},u={},d=[];for(let e in i){if(e===`sequence`||Ol.has(e))continue;let t=i[e];if(t===void 0)continue;let r=g.get(e);if(!r){v(`binding`,e);continue}r(t,Rl({fieldName:e,conditions:n,requirements:c,matchers:d,attrs:u}))}let p=Object.keys(u).length>0?yu(u):void 0,m=Al(i.cmd),h={binding:b,sequence:a,command:m,event:t,parsedBinding:fl(i),sourceTarget:o,sourceLayerOrder:s,bindingIndex:r,requires:Object.keys(c).length>0?Object.entries(c):_u,matchers:d.length>0?d:vu,preventDefault:i.preventDefault!==!1,fallthrough:i.fallthrough??!1};if(p&&(h.attrs=p),typeof m==`function`&&(h.run=m),a.length===0)continue;if(t===`release`&&a.length>1)throw Error(`Keymap release bindings only support a single key stroke`);let y=a.at(-1);if(y?.patternName){let t=e.patterns.get(y.patternName);if(t&&t.max!==t.min)throw Error(`Keymap unbounded sequence patterns must be followed by a concrete continuation`)}t===`press`&&!_&&Su(f,h),f.push(h)}catch(e){t.emitError(`binding-compile-error`,e,Bl(e,`Failed to compile keymap binding`))}}}return{bindings:f,hasTokenBindings:p}},c=(e,t)=>Ac(e,t),l=e=>{if(e===void 0||e===`press`)return`press`;if(e===`release`)return`release`;throw Error(`Invalid keymap binding event "${String(e)}": expected "press" or "release"`)},u=(n,r,i,a,o)=>{let s=e.bindingTransformers.values();if(s.length===0)return[{...n,sequence:Mc(r)}];let l={...n,sequence:Mc(r)},u=[],d=!0,f=o??gu;for(let n of s)try{n(l,{layer:f,parseKey:t=>Eu(t,a,{tokens:i,patterns:e.patterns,layer:f,parseObjectKey:(e,t)=>c(e,t)}),add:e=>{u.push(fl(e))},skipOriginal:()=>{d=!1}})}catch(e){t.emitError(`binding-transformer-error`,e,`[Keymap] Error in binding transformer:`)}return d?u.length===0?[l]:[l,...u]:u};return{parseTokenKey:i,parseKeySequence:a,formatKey:o,compileBindings:s}}function xu(e,t){if(e.length>=t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]?.match!==t[n]?.match)return!1;return!0}function Su(e,t){for(let n of e)if(n.event===`press`&&(n.command!==void 0&&xu(n.sequence,t.sequence)||t.command!==void 0&&xu(t.sequence,n.sequence)))throw Error(`Keymap bindings cannot use the same sequence as both an exact match and a prefix in the same layer`)}function Cu(e,t,n){if(typeof e!=`string`||t.length===0)return[{key:e}];let r=n?.layer??gu,i=[{key:e}];for(let e of t){let t=[];for(let n of i){let i=e({input:n.key,displays:n.displays,layer:r});if(!i){t.push(n);continue}if(i.length===0)throw Error(`Keymap binding expander must return at least one key sequence for "${n.key}"`);for(let e of i){if(!e||typeof e!=`object`||Array.isArray(e)||typeof e.key!=`string`)throw Error(`Keymap binding expander must return expansion objects with string keys for "${n.key}"`);if(e.displays!==void 0){if(!Array.isArray(e.displays))throw Error(`Keymap binding expander displays must be an array of strings for "${n.key}"`);for(let t of e.displays)if(typeof t!=`string`)throw Error(`Keymap binding expander displays must be an array of strings for "${n.key}"`)}t.push(e)}}i=t}return i}function wu(e,t){if(!t.displays)return e;if(t.displays.length!==e.parts.length)throw Error(`Keymap binding expansion displays length must match parsed sequence length for "${String(t.key)}"`);return{...e,parts:e.parts.map((e,n)=>({...e,display:t.displays[n]}))}}function Tu(e,t,n){if(e.length===0)throw Error(`Invalid key sequence: sequence cannot be empty`);if(t.length===0)throw Error(`No keymap binding parsers are registered`);let r=n.tokens??new Map,i=n.patterns??new Map,a=n.layer??gu,o=n.parseObjectKey,s=[],c=new Set,l=new Set,u=0;for(;u<e.length;){let n=!1;for(let d of t){let t=d({input:e,index:u,layer:a,tokens:r,patterns:i,normalizeTokenName:Ec,createMatch:Fc,parseObjectKey:o});if(t){if(t.nextIndex<=u||t.nextIndex>e.length)throw Error(`Keymap binding parser must advance the input for "${e}" at index ${u}`);s.push(...t.parts);for(let e of t.usedTokens??[])c.add(e);for(let e of t.unknownTokens??[])l.add(e);u=t.nextIndex,n=!0;break}}if(!n)throw Error(`No keymap binding parser handled input at index ${u} in "${e}"`)}return{parts:s,usedTokens:[...c],unknownTokens:[...l],hasTokenBindings:c.size>0||l.size>0}}function Eu(e,t,n){if(typeof e!=`string`)return n.parseObjectKey(e);let{parts:r}=Tu(e,t,n),[i]=r;if(!i||r.length!==1)throw Error(`Invalid key "${String(e)}": expected a single key stroke`);return i}function Du(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.get==`function`&&typeof t.subscribe==`function`}function Ou(e,t){let n=e=>e.requires.length===0&&e.matchers.length===0,r=e=>{try{return e.match()}catch(n){return t.emitError(`runtime-matcher-error`,n,`[Keymap] Error evaluating runtime matcher from ${e.source}:`),!1}},i=e=>{if(e.matchers.length===0)return!0;if(e.matchers.length===1){let[t]=e.matchers;return!t||r(t)}for(let t of e.matchers)if(!r(t))return!1;return!0},a=t=>{if(t.length===0)return!0;for(let[n,r]of t)if(!Object.is(e.data[n],r))return!1;return!0};return{buildRuntimeMatcher(e,t){if(typeof e==`function`)return{source:t,match:e};if(Du(e))return{source:t,match:()=>e.get(),subscribe:t=>e.subscribe(t)};throw Error(`Keymap ${t} expected a function or a reactive matcher`)},matchesConditions:e=>n(e)||a(e.requires)&&i(e)}}var ku=Symbol(`keymap-disambiguation-decision`),Au=Symbol(`keymap-deferred-disambiguation-decision`);function ju(e,t){return{[ku]:!0,action:e,handler:t}}function Mu(e){return{[Au]:!0,action:e}}function Nu(e){return!!e&&typeof e==`object`&&e[ku]===!0}function Pu(e){return!!e&&typeof e==`object`&&e[Au]===!0}function Fu(e,t){return t.aborted?Promise.resolve(!1):new Promise(n=>{let r=setTimeout(()=>{t.removeEventListener(`abort`,i),n(!0)},Math.max(0,e)),i=()=>{clearTimeout(r),t.removeEventListener(`abort`,i),n(!1)};t.addEventListener(`abort`,i,{once:!0})})}function Iu(e,t,n,r){let i=e.get(n);if(i)try{return i.matcher(r)}catch(e){t.emitError(`sequence-pattern-match-error`,e,`[Keymap] Error matching sequence pattern "${i.name}":`);return}}function Lu(e,t,n,r){let i=e.get(n)?.payloadKey??n;return{...Ac({name:t.name,ctrl:t.ctrl,shift:t.shift,meta:t.meta,super:t.super??!1,hyper:t.hyper||void 0},{display:r.display??String(r.value??t.name)}),patternName:n,payloadKey:i}}function Ru(e,t,n){if(!n?.patterns||n.patterns.length===0)return;let r={},i=!1;for(let a of n.patterns){let n=e.get(a.name),o;try{o=n?.finalize?n.finalize(a.values):a.values.length===1?a.values[0]:[...a.values]}catch(e){t.emitError(`sequence-pattern-finalize-error`,e,`[Keymap] Error finalizing sequence pattern "${a.name}":`);continue}let s=r[a.payloadKey];s===void 0?(r[a.payloadKey]=o,i=!0):Array.isArray(s)?s.push(o):r[a.payloadKey]=[s,o]}return i?r:void 0}function zu(e,t,n,r,i,a,o,s,c,l){let u={resolveKey:e=>o.parseTokenKey(e).match},d=null,f=0;function p(t,n,r){if(t===`key`){let t=r;return e.keyHooks.register(n,{priority:t?.priority??0,release:t?.release??!1})}if(t===`key:after`){let t=r;return e.keyAfterHooks.register(n,{priority:t?.priority??0,release:t?.release??!1})}let i=r;return e.rawHooks.register(n,{priority:i?.priority??0})}function m(t){return e.eventMatchResolvers.prepend(t)}function h(t){return e.eventMatchResolvers.append(t)}function g(){e.eventMatchResolvers.clear()}function _(t){return ae(()=>e.disambiguationResolvers.prepend(t),t)}function v(t){return ae(()=>e.disambiguationResolvers.append(t),t)}function y(){e.disambiguationResolvers.has()&&t.runWithStateChangeBatch(()=>{e.disambiguationResolvers.clear(),c.recompileBindings()})}function b(e,t){d&&be()}function x(n){let r=e.rawHooks.entries();if(r.length===0)return!1;let i=!1,a={sequence:n,stop(){i=!0}};for(let e of r){try{e.listener(a)}catch(e){t.emitError(`raw-intercept-error`,e,`[Keymap] Error in raw intercept listener:`)}if(i)return!0}return!1}function S(e,t){return{sequence:Mc(e.sequence),command:e.command,commandAttrs:s.getBindingCommandAttrs(e,t,s.getActiveCommandView(t)),attrs:e.attrs,event:e.event,preventDefault:e.preventDefault,fallthrough:e.fallthrough,sourceLayerOrder:e.sourceLayerOrder,bindingIndex:e.bindingIndex}}function C(e){l.has(`dispatch`)&&l.emit(`dispatch`,e)}function w(e,t,n,r){l.has(`dispatch`)&&C({phase:e,event:n.event,focused:r,layer:{order:t.order,priority:t.priority,target:t.target,targetMode:t.targetMode},binding:S(n,r),sequence:Mc(n.sequence),command:n.command})}function T(e,t,n){if(!l.has(`dispatch`))return;let i=t[0],a=t.length>0?r.collectSequencePartsFromPending({captures:t}):[];C({phase:e,event:`press`,focused:n,layer:i?{order:i.layer.order,priority:i.layer.priority,target:i.layer.target,targetMode:i.layer.targetMode}:void 0,sequence:a})}function E(t){let n=e.keyAfterHooks.entries();for(let e of n)if(e.release===t)return n}function ee(e){return e.sequence?Mc(e.sequence):e.captures?r.collectSequencePartsFromPending({captures:e.captures}):[]}function D(e,t){return{handled:e!==`sequence-miss`,reason:e,captures:t}}function O(e,t){return{handled:t,reason:t?`binding-handled`:`binding-rejected`,sequence:e.sequence}}function k(e,t){return t.handled||e.reason===`no-match`?t:e}function A(e,i,a,o,s){let c={event:i,eventType:a?`release`:`press`,focused:o,handled:s.handled,reason:s.reason,sequence:ee(s),pendingSequence:r.getPendingSequence(),setData:(e,t)=>{n.setData(e,t)},getData:e=>n.getData(e),consume:e=>{let t=e?.preventDefault??!0,n=e?.stopPropagation??!0;t&&i.preventDefault(),n&&i.stopPropagation()}};for(let n of e)if(n.release===a)try{n.listener(c)}catch(e){t.emitError(`key-after-intercept-error`,e,`[Keymap] Error in key:after intercept listener:`)}}function j(){return{handled:!1,reason:`no-match`}}function te(e){e.preventDefault(),e.stopPropagation()}function ne(e,t,n,i){r.setPendingSequence({captures:t});let a=D(`sequence-pending`,t);return T(e,t,n),te(i),a}function re(e,t,n,i){let a=D(e,t);return T(`sequence-clear`,t,n),r.setPendingSequence(null),te(i),a}function ie(i,a){a||be();let o=E(a),s=o?r.getFocusedTarget():null,c=e.keyHooks.entries(),l={event:i,setData:(e,t)=>{n.setData(e,t)},getData:e=>n.getData(e),consume:e=>{let t=e?.preventDefault??!0,n=e?.stopPropagation??!0;t&&i.preventDefault(),n&&i.stopPropagation()}};for(let e of c)if(e.release===a){try{e.listener(l)}catch(e){t.emitError(`key-intercept-error`,e,`[Keymap] Error in key intercept listener:`)}if(i.propagationStopped){o&&A(o,i,a,s,{handled:!0,reason:`intercept-consumed`,sequence:[]});return}}if(a){let e=oe(i);o&&A(o,i,a,s,e);return}let u=se(i);o&&A(o,i,a,s,u)}function ae(n,r){return t.runWithStateChangeBatch(()=>{let i=e.disambiguationResolvers.has(),a=n();return!i&&e.disambiguationResolvers.has()&&c.recompileBindings(),()=>{t.runWithStateChangeBatch(()=>{let t=e.disambiguationResolvers.has();a(),!e.disambiguationResolvers.values().includes(r)&&t&&!e.disambiguationResolvers.has()&&c.recompileBindings()})}})}function oe(e){let t=r.getFocusedTarget(),n=r.getActiveLayers(t),a=Te(e),o=j();for(let r of a)layerLoop:for(let a of n){if(a.bindings.length===0||!i.matchesConditions(a))continue;let n=Ee(a,r,e,t);if(o=k(o,n.outcome),n.handled){if(n.stop)return o;continue layerLoop}}return o}function se(e){let t=r.getFocusedTarget(),n=r.ensureValidPendingSequence(),i=Te(e);if(n)return ce(n,i,e,t);let a=r.getActiveLayers(t),o=j();for(let n of i){let r=ue(a,[n],e,t);if(o=k(o,r),r.handled)return o}return o}function ce(t,n,i,a){let o=s.getActiveCommandView(a),c=[];for(let r of t.captures){let t=rl(r,n,i,e.patterns,De,Oe);t&&c.push(t)}let l=c.reduce((e,t)=>Math.min(e,tl(t,n)),1/0),u=c.filter(e=>tl(e,n)===l);if(u.length===0||!u.some(e=>Me(e,a,o))){let e=D(`sequence-miss`,t.captures);return T(`sequence-clear`,t.captures,a),r.setPendingSequence(null),e}return le(u,0,!1,i,a)}function le(t,n,i,a,o){let s=i,c=j(),l=new Set;for(let i=n;i<t.length;i+=1){let n=t[i];if(!n||l.has(n))continue;let u=Ce(t,i,n);if(u.length>0){if(s)continue;let e=we(t,n);return fe(t,i,u,e,a,o,s)||ne(`sequence-advance`,u,o,a)}if(!Xc(n,e.patterns))continue;let d=we(t,n);for(let e of d)l.add(e);let f=Ne(n.layer,d,a,o);if(c=k(c,f.outcome),f.handled&&(s=!0,f.stop))return T(`sequence-clear`,t,o),r.setPendingSequence(null),c}return T(`sequence-clear`,t,o),r.setPendingSequence(null),c}function ue(e,t,n,r){return M(e,0,t,n,r)}function M(t,n,r,a,o){let c=s.getActiveCommandView(o),l=j();for(let s=n;s<t.length;s+=1){let n=t[s];if(!n||!i.matchesConditions(n))continue;let u=ke(n,r,a,o,c);if(u.length===0)continue;if(u.filter(t=>Yc(t,e.patterns,!1)).length>0){let n=u.filter(t=>Xc(t,e.patterns)),i=Se(t,s,r,a,o);return de(t,s,r,i,n,a,o)||ne(`sequence-start`,i,o,a)}let d=Ne(n,u.filter(t=>Xc(t,e.patterns)),a,o);if(l=k(l,d.outcome),d.handled&&d.stop)return l}return l}function de(e,t,n,i,a,o,s){return pe({event:o,focused:s,continuationCaptures:i,exactBindingsSource:a.map(e=>e.binding),sequencePhase:`sequence-start`,runExact:()=>{r.setPendingSequence(null);let i=a[0]?.layer;if(!i)return j();let c=Ne(i,a,o,s);return c.stop?c.outcome:k(c.outcome,M(e,t+1,n,o,s))}})}function fe(e,t,n,i,a,o,s){return pe({event:a,focused:o,continuationCaptures:n,exactBindingsSource:i.map(e=>e.binding),sequencePhase:`sequence-advance`,runExact:()=>{r.setPendingSequence(null);let n=i[0]?.layer;if(!n)return j();let c=Ne(n,i,a,o);return c.stop?c.outcome:k(c.outcome,le(e,t+1,s||c.handled,a,o))}})}function pe(t){let{event:n,focused:i,continuationCaptures:a,exactBindingsSource:o,sequencePhase:c,runExact:l}=t;if(!e.disambiguationResolvers.has()||a.length===0)return;let u=s.getActiveCommandView(i),d=r.collectMatchingBindings(o,i,u);if(!d.some(e=>e.command!==void 0))return;let f=()=>ne(c,a,i,n),p=()=>re(`sequence-cleared`,a,i,n),m,h=()=>(m??=r.collectSequencePartsFromPending({captures:a}),m),g=he({event:n,focused:i,getSequence:h,exactBindings:d,continuationCaptures:a,activeView:u});return g?me(g,a,l,f,p,i,h):(xe(h()),f())}function me(e,t,n,r,i,a,o){if(e.action===`run-exact`)return n();if(e.action===`continue-sequence`)return r();if(e.action===`clear`)return i();let s=r();return ge(t,e.handler,a,o(),e=>{if(e){if(e.action===`run-exact`){n();return}if(e.action===`continue-sequence`){r();return}i()}}),s}function he(i){let a,o,s,c,l={event:i.event,focused:i.focused,get sequence(){return a??=Mc(i.getSequence()),a},get stroke(){let e=i.getSequence().at(-1);if(!e)throw Error(`Disambiguation context expected a non-empty sequence`);return c??={...e,stroke:kc(e.stroke)},c},get exact(){return o??=r.collectActiveBindings(i.exactBindings,i.focused,i.activeView).map(e=>({...e,sequence:Mc(e.sequence)})),o},get continuations(){return s??=r.getActiveKeysForCaptures(i.continuationCaptures,{includeBindings:!0,includeMetadata:!0}),s},getData:e=>n.getData(e),setData:(e,t)=>{n.setData(e,t)},runExact:()=>ju(`run-exact`),continueSequence:()=>ju(`continue-sequence`),clear:()=>ju(`clear`),defer:e=>ju(`defer`,e)};for(let n of e.disambiguationResolvers.values()){let e;try{e=n(l)}catch(e){t.emitError(`disambiguation-resolver-error`,e,`[Keymap] Error in disambiguation resolver:`);continue}if(e!==void 0){if(Vl(e)){t.emitError(`invalid-disambiguation-resolver-return`,e,`[Keymap] Disambiguation resolvers must return synchronously; use ctx.defer(...) for async handling`);continue}if(!Nu(e)){t.emitError(`invalid-disambiguation-decision`,e,`[Keymap] Invalid disambiguation decision returned by resolver:`);continue}return e}}}function ge(e,t,n,r,i){be();let a=new AbortController,o={id:f++,controller:a,captures:e,apply:i};d=o,queueMicrotask(()=>{_e(o,t,n,r)})}function _e(e,n,r,i){if(!N(e))return;let a={signal:e.controller.signal,sequence:Mc(i),focused:r,sleep:t=>Fu(t,e.controller.signal),runExact:()=>Mu(`run-exact`),continueSequence:()=>Mu(`continue-sequence`),clear:()=>Mu(`clear`)},o;try{o=n(a)}catch(n){N(e)&&(t.emitError(`deferred-disambiguation-error`,n,`[Keymap] Error in deferred disambiguation handler:`),ye(e));return}if(Vl(o)){o.then(t=>{ve(e,t)}).catch(n=>{N(e)&&(t.emitError(`deferred-disambiguation-error`,n,`[Keymap] Error in deferred disambiguation handler:`),ye(e))});return}ve(e,o)}function ve(e,n){if(N(e)){if(n!==void 0&&!Pu(n)){t.emitError(`invalid-deferred-disambiguation-decision`,n,`[Keymap] Invalid deferred disambiguation decision returned by handler:`),ye(e);return}ye(e),e.apply(n)}}function ye(e){N(e)&&(d=null)}function be(){let e=d;e&&(d=null,e.controller.abort())}function N(e){return d===e}function xe(e){let n=Lc(e,{preferDisplay:!0});t.warnOnce(`unresolved-disambiguation:${n}`,`unresolved-disambiguation`,{sequence:n},`[Keymap] Ambiguous exact/prefix sequence "${n}" fell back to prefix handling because no disambiguation resolver resolved it`)}function Se(t,n,r,a,o){let c=[],l=s.getActiveCommandView(o);for(let s=n;s<t.length;s+=1){let n=t[s];if(n&&i.matchesConditions(n))for(let t of ke(n,r,a,o,l))Yc(t,e.patterns,!1)&&c.push(t)}return c}function Ce(t,n,r){return t.filter((t,i)=>i>=n&&Yc(t,e.patterns,!1)&&Vu(t.parts,r.parts))}function we(t,n){return t.filter(t=>t.layer===n.layer&&Xc(t,e.patterns)&&Vu(t.parts,n.parts))}function Te(n){let r=e.eventMatchResolvers.values();if(r.length===0)return[];if(r.length===1)return Bu(r[0],n,u,t);let i=[],a=new Set;for(let e of r){let r;try{r=e(n,u)}catch(e){t.emitError(`event-match-resolver-error`,e,`[Keymap] Error in event match resolver:`);continue}if(!(!r||r.length===0))for(let e of r){if(typeof e!=`string`){t.emitError(`invalid-event-match-resolver-candidate`,e,`[Keymap] Invalid event match resolver candidate:`);continue}a.has(e)||(a.add(e),i.push(e))}}return i}function Ee(e,t,n,r){let o=!1,s=j();for(let c of e.bindings){if(c.event!==`release`)continue;let l=c.sequence[0];if(!l||l.match!==t||!i.matchesConditions(c))continue;let u=a.runBinding(e,c,n,r);if(s=k(s,O(c,u)),!u){w(`binding-reject`,e,c,r);continue}if(w(`binding-execute`,e,c,r),o=!0,!c.fallthrough)return{handled:!0,stop:!0,outcome:s}}return{handled:o,stop:!1,outcome:s}}function De(n,r){return Iu(e.patterns,t,n,r)}function Oe(t,n,r){return Lu(e.patterns,t,n,r)}function ke(e,t,n,r,i){let a=il(e,t,n,De,Oe);return a.some(e=>Me(e,r,i))?a:[]}function Ae(n){return Ru(e.patterns,t,n)}function je(e,t,n){return i.matchesConditions(e)&&s.isBindingVisible(e,t,n)}function Me(e,t,n){return je(e.binding,t,n)}function Ne(e,t,n,r){let o=!1,s=j();for(let c of t){let t=c.binding;if(!i.matchesConditions(t))continue;let l=a.runBinding(e,t,n,r,Ae(c));if(s=k(s,O(t,l)),!l){w(`binding-reject`,e,t,r);continue}if(w(`binding-execute`,e,t,r),o=!0,!t.fallthrough)return{handled:!0,stop:!0,outcome:s}}return{handled:o,stop:!1,outcome:s}}return{intercept:p,prependEventMatchResolver:m,appendEventMatchResolver:h,clearEventMatchResolvers:g,prependDisambiguationResolver:_,appendDisambiguationResolver:v,clearDisambiguationResolvers:y,handlePendingSequenceChange:b,handleRawSequence:x,handleKeyEvent:ie}}function Bu(e,t,n,r){let i;try{i=e(t,n)}catch(e){return r.emitError(`event-match-resolver-error`,e,`[Keymap] Error in event match resolver:`),[]}if(!i||i.length===0)return[];if(i.length===1){let[e]=i;return typeof e==`string`?[e]:(r.emitError(`invalid-event-match-resolver-candidate`,e,`[Keymap] Invalid event match resolver candidate:`),[])}let a=[],o=new Set;for(let e of i){if(typeof e!=`string`){r.emitError(`invalid-event-match-resolver-candidate`,e,`[Keymap] Invalid event match resolver candidate:`);continue}o.has(e)||(o.add(e),a.push(e))}return a}function Vu(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]?.match!==t[n]?.match)return!1;return!0}var Hu=()=>{};function Uu(e,t,n,r){if(n===void 0)return r;if(typeof n!=`number`||!Number.isInteger(n)||n<0)throw Error(`Keymap sequence pattern "${e}" ${t} must be a non-negative integer`);return n}function Wu(e,t){let{kind:n,reservedFields:r,registeredFields:i,emitError:a}=t,o=Object.entries(e),s=[];for(let[e,t]of o){if(r.has(e)){a(`reserved-${n}-field`,{field:e,kind:n},`Keymap ${n} field "${e}" is reserved`);continue}if(i.has(e)){a(`duplicate-${n}-field`,{field:e,kind:n},`Keymap ${n} field "${e}" is already registered`);continue}i.set(e,t),s.push([e,t])}return()=>{for(let[e,t]of s)i.get(e)===t&&i.delete(e)}}function Gu(e,t,n,r,i){let a;try{a=Ec(i.name)}catch(e){return t.emitError(`token-name-normalize-error`,e,Bl(e,`Failed to register keymap token`)),Hu}if(e.tokens.has(a)||e.patterns.has(a))return t.emitError(`duplicate-token`,{token:a},`Keymap token "${a}" is already registered`),Hu;let o;try{if(o=n.parseTokenKey(i.key),o.patternName)throw Error(`Invalid key "${String(i.key)}": expected a concrete key stroke`)}catch(e){return t.emitError(`token-parse-error`,e,Bl(e,`Failed to register keymap token "${a}"`)),Hu}let s={stroke:o.stroke,match:o.match},c=new Map(e.tokens);c.set(a,s);try{r.applyTokenState(c)}catch(e){return t.emitError(`token-register-error`,e,Bl(e,`Failed to register keymap token "${a}"`)),Hu}return()=>{if(e.tokens.get(a)!==s)return;let n=new Map(e.tokens);n.delete(a);try{r.applyTokenState(n)}catch(e){t.emitError(`token-unregister-error`,e,Bl(e,`Failed to unregister keymap token "${a}"`))}}}function Ku(e,t,n,r){let i,a;try{i=Ec(r.name);let e=Uu(i,`min`,r.min,1),t=Uu(i,`max`,r.max,2**53-1);if(t<e)throw Error(`Keymap sequence pattern "${i}" max must be greater than or equal to min`);a={name:i,display:r.display,payloadKey:r.payloadKey??i,match:Fc(`pattern:${i}`),min:e,max:t,matcher:e=>r.match(e),finalize:r.finalize}}catch(e){return t.emitError(`sequence-pattern-register-error`,e,Bl(e,`Failed to register keymap sequence pattern`)),Hu}return e.tokens.has(i)||e.patterns.has(i)?(t.emitError(`duplicate-sequence-pattern`,{pattern:i},`Keymap sequence pattern "${i}" is already registered`),Hu):(e.patterns.set(i,a),n.recompileBindings(),()=>{e.patterns.get(i)===a&&(e.patterns.delete(i),n.recompileBindings())})}function qu(e,t,n,r){return Wu(r,{kind:n,reservedFields:n===`layer`?kl:n===`binding`?Ol:Dl,registeredFields:n===`layer`?e.layerFields:n===`binding`?e.bindingFields:e.commandFields,emitError:(e,n,r)=>t.emitError(e,n,r)})}var Ju=()=>{};function Yu(e,t){return t.priority-e.priority||t.order-e.order}function Xu(e){if(e.matchers.length>0)return!0;for(let t of e.commands)if(t.matchers.length>0)return!0;for(let t of e.bindings)if(t.matchers.length>0)return!0;return!1}function Zu(e){if(e.commands.length===0)return!1;if(e.matchers.length>0)return!0;for(let t of e.commands)if(t.matchers.length>0)return!0;return!1}function Qu(e,t,n,r,i){let a=n=>t.runWithStateChangeBatch(()=>{let a=n.target;if(a&&i.host.isTargetDestroyed(a))return t.emitError(`destroyed-layer-target`,{target:a},`Cannot register a keymap layer for a destroyed keymap target`),Ju;let o,s,c,p,m,v,y;try{y=l(n),o=u(dl(n.bindings??[]),n);let e=d(n.commands??[],n);v=e.length===0?[]:i.commands.normalizeCommands(e),{requires:s,matchers:c,fields:p,attrs:m}=f(n)}catch(e){return t.emitError(`register-layer-failed`,e,Bl(e,`Failed to register keymap layer`)),Ju}let b=e.order++,x=i.compiler.compileBindings(o,e.tokens,a,b,p);if(x.bindings.length===0&&!x.hasTokenBindings&&v.length===0)return Ju;i.diagnostics?.analyzeLayer({target:a,order:b,commands:v,sourceBindings:o,bindings:x.bindings,hasTokenBindings:x.hasTokenBindings});let S={order:b,target:a,targetMode:y,priority:n.priority??0,requires:s,matchers:c,fields:p,attrs:m,commands:v,sourceBindings:o,bindings:x.bindings,root:Qc(x.bindings,e.patterns),hasTokenBindings:x.hasTokenBindings,activeKeyCacheBlocked:!1,activeCommandViewCacheBlocked:!1};_(S),e.layers.add(S),e.sortedLayers=[...e.sortedLayers,S].sort(Yu),g(S);for(let e of S.commands)g(e);for(let e of S.bindings)g(e);return a&&(S.offTargetDestroy=i.host.onTargetDestroy(a,()=>{h(S)})),S.commands.length>0&&r.ensureValidPendingSequence(),t.queueStateChange(),()=>{h(S)}}),o=n=>{t.runWithStateChangeBatch(()=>{let i=new Map;for(let t of e.layers)t.hasTokenBindings&&i.set(t,p(t,n));e.tokens=n;let a=!1;for(let[e,t]of i)m(e,t)&&(a=!0);a&&r.setPendingSequence(null),i.size>0&&t.queueStateChange()})},s=()=>{t.runWithStateChangeBatch(()=>{let n=0,i=!1;for(let t of e.layers){if(t.sourceBindings.length===0)continue;let r=p(t,e.tokens);m(t,r)&&(i=!0),n+=1}i&&r.setPendingSequence(null),n>0&&t.queueStateChange()})},c=()=>{for(let t of e.layers){y(t);for(let e of t.commands)y(e);for(let e of t.bindings)y(e);t.offTargetDestroy?.(),t.offTargetDestroy=void 0}},l=e=>{if(e.targetMode){if(!e.target)throw Error(`Keymap targetMode "${e.targetMode}" requires a target`);return e.targetMode}return e.target?`focus-within`:void 0},u=(t,n)=>{let r=e.layerBindingsTransformers.values();if(r.length===0)return t;let i=t;for(let e of r){let t=e(i,{layer:n,validateBindings:e=>ul(e)});t&&(i=dl(t))}return i},d=(n,r)=>{let i=e.commandTransformers.values();if(n.length===0||i.length===0)return n;let a=[];for(let e of n){let n={...e},o=[],s=!0;for(let e of i)try{e(n,{layer:r,add(e){o.push({...e})},skipOriginal(){s=!1}})}catch(e){t.emitError(`command-transformer-error`,e,`[Keymap] Error in command transformer:`)}s&&a.push(n),a.push(...o)}return a},f=t=>{let r={},a=[],o=Object.create(null),s={};for(let[c,l]of Object.entries(t)){if(kl.has(c)||l===void 0)continue;o[c]=Hl(l);let t=e.layerFields.get(c);if(!t){i.warnUnknownField(`layer`,c);continue}t(l,Rl({fieldName:c,conditions:n,requirements:r,matchers:a,attrs:s}))}return{requires:Object.entries(r),matchers:a,fields:Object.keys(o).length>0?Object.freeze(o):void 0,attrs:Object.keys(s).length>0?Hl(s,{freeze:!0}):void 0}},p=(e,t)=>i.compiler.compileBindings(e.sourceBindings,t,e.target,e.order,e.fields),m=(t,n)=>{i.diagnostics?.analyzeLayer({target:t.target,order:t.order,commands:t.commands,sourceBindings:t.sourceBindings,bindings:n.bindings,hasTokenBindings:n.hasTokenBindings}),v(t);for(let e of t.bindings)y(e);t.bindings=n.bindings,t.root=Qc(n.bindings,e.patterns),t.hasTokenBindings=n.hasTokenBindings,_(t);for(let e of t.bindings)g(e);return e.pending?.captures.some(e=>e.layer===t)??!1},h=n=>{t.runWithStateChangeBatch(()=>{if(e.layers.delete(n)){e.sortedLayers=e.sortedLayers.filter(e=>e!==n),v(n),y(n);for(let e of n.commands)y(e);for(let e of n.bindings)y(e);n.offTargetDestroy?.(),n.offTargetDestroy=void 0,e.pending?.captures.some(e=>e.layer===n)?r.setPendingSequence(null):n.commands.length>0&&!i.host.isDestroyed&&r.ensureValidPendingSequence(),t.queueStateChange()}})},g=e=>{for(let n of e.matchers)if(n.subscribe)try{n.dispose=n.subscribe(()=>{if(!r.hasPendingSequenceState()){t.queueStateChange();return}t.runWithStateChangeBatch(()=>{r.revalidatePendingSequenceIfNeeded(),t.queueStateChange()})})}catch(e){t.emitError(`reactive-matcher-subscribe-error`,e,Bl(e,`Failed to subscribe to reactive matcher from ${n.source}`))}},_=t=>{let n=Xu(t),r=Zu(t);t.activeKeyCacheBlocked=n,t.activeCommandViewCacheBlocked=r,n&&(e.activeKeyCacheBlockers+=1),r&&(e.activeCommandViewCacheBlockers+=1)},v=t=>{t.activeKeyCacheBlocked&&=(--e.activeKeyCacheBlockers,!1),t.activeCommandViewCacheBlocked&&=(--e.activeCommandViewCacheBlockers,!1)},y=e=>{for(let n of e.matchers)if(n.dispose){try{n.dispose()}catch(e){t.emitError(`reactive-matcher-dispose-error`,e,Bl(e,`Failed to dispose reactive matcher from ${n.source}`))}n.dispose=void 0}};return{registerLayer:a,applyTokenState:o,recompileBindings:s,cleanup:c}}var $u=1e3;function ed(e,t,n){let r=(e,n,r)=>{if(!t.has(`warning`)){let t=`[${e}] ${r}`;n instanceof Error?console.warn(t,n):console.warn(t);return}t.emit(`warning`,{code:e,message:r,warning:n})},i=(e,n,r)=>{if(!t.has(`error`)){let t=`[${e}] ${r}`;n instanceof Error?console.error(t,n):console.error(t);return}t.emit(`error`,{code:e,message:r,error:n})},a=()=>{if(!(!e.stateChangePending||e.stateChangeDepth>0||e.flushingStateChange)){e.flushingStateChange=!0;try{let t=0;for(;e.stateChangePending&&e.stateChangeDepth===0;){if(t>=$u){e.stateChangePending=!1,i(`state-change-feedback-loop`,{iterations:$u},`[Keymap] Possible infinite state listener feedback loop detected after ${$u} iterations; pending state notifications were dropped`);break}t+=1,e.stateChangePending=!1,n.emit(`state`)}}finally{e.flushingStateChange=!1}}};return{runWithStateChangeBatch(t){e.stateChangeDepth+=1;try{return t()}finally{--e.stateChangeDepth,e.stateChangeDepth===0&&a()}},queueStateChange(t){e.derivedVersion+=1,t?.invalidateCaches!==!1&&(e.cacheVersion+=1),n.has(`state`)&&(e.stateChangePending=!0,e.stateChangeDepth===0&&!e.flushingStateChange&&a())},emitWarning:r,emitError:i,reportListenerError(e,t){if(e===`state`){i(`state-listener-error`,t,`[Keymap] Error in state listener:`);return}if(e===`pendingSequence`){i(`pending-sequence-listener-error`,t,`[Keymap] Error in pending sequence listener:`);return}e===`dispatch`&&i(`dispatch-listener-error`,t,`[Keymap] Error in dispatch listener:`)},warnOnce(t,n,i,a){e.usedWarningKeys.has(t)||(e.usedWarningKeys.add(t),r(n,i,a))}}}function td(e,t,n){return{getData(t){return e.data[t]},setData(r,i){t.runWithStateChangeBatch(()=>{if(i===void 0){if(!(r in e.data))return;delete e.data[r],e.dataVersion+=1,n.ensureValidPendingSequence(),t.queueStateChange();return}Object.is(e.data[r],i)||(e.data[r]=i,e.dataVersion+=1,n.ensureValidPendingSequence(),t.queueStateChange())})},getReadonlyData(){return e.readonlyDataVersion===e.dataVersion?e.readonlyData:(e.readonlyData=Object.freeze({...e.data}),e.readonlyDataVersion=e.dataVersion,e.readonlyData)}}}var nd=Object.freeze({});function rd(){return{order:0,tokens:new Map,patterns:new Map,layerFields:new Map,layerBindingsTransformers:sl(),bindingExpanders:sl(),bindingParsers:sl(),bindingTransformers:sl(),bindingFields:new Map,commandTransformers:sl(),commandFields:new Map,eventMatchResolvers:sl(),disambiguationResolvers:sl(),keyHooks:cl(),keyAfterHooks:cl(),rawHooks:cl(),layers:new Set,sortedLayers:[],activeLayersCacheVersion:-1,activeLayersCacheFocused:void 0,activeLayersCache:[],activeKeyCacheBlockers:0,activeCommandViewCacheBlockers:0,commandResolvers:sl(),pending:null,data:{},dataVersion:0,readonlyDataVersion:-1,readonlyData:nd,cacheVersion:0,derivedVersion:0,stateChangeDepth:0,stateChangePending:!1,flushingStateChange:!1,usedWarningKeys:new Set}}function id(e){return Nc(e)}var ad=class{#e=rd();#t=!1;#n=new Map;#r=[];#i=al(()=>{});#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;getPendingSequence;getActiveKeys;constructor(e){if(this.#b=e,e.isDestroyed)throw Error(`Cannot create a keymap for a destroyed host`);this.#a=al((e,t)=>{this.#o.reportListenerError(e,t)}),this.#o=ed(this.#e,this.#i,this.#a),this.#l=Ou(this.#e,this.#o),this.#u=Kl(this.#e,this.#b,this.#o,this.#l,{onCommandResolversChanged:()=>{this.#s.ensureValidPendingSequence()}}),this.#s=El(this.#e,this.#b,this.#a,this.#o,this.#l,this.#u,{onPendingSequenceChanged:(e,t)=>{this.#p?.handlePendingSequenceChange(e,t)}}),this.#c=td(this.#e,this.#o,this.#s),this.#d=pu(this.#o,this.#c,this.#s,this.#u,{keymap:this,createCommandEvent:()=>this.#b.createCommandEvent()}),this.#f=bu(this.#e,this.#o,this.#l,{warnUnknownField:(e,t)=>{this.#C(e,t)},warnUnknownToken:(e,t)=>{this.#w(e,t)}}),this.#h=pl(this.#o,this.#u),this.#m=Qu(this.#e,this.#o,this.#l,this.#s,{compiler:this.#f,commands:this.#u,host:this.#b,diagnostics:this.#h,warnUnknownField:(e,t)=>{this.#C(e,t)}}),this.#p=zu(this.#e,this.#o,this.#c,this.#s,this.#l,this.#d,this.#f,this.#u,this.#m,this.#a),this.getPendingSequence=this.#s.getPendingSequence,this.getActiveKeys=this.#s.getActiveKeys,this.#g=e=>{this.#p.handleKeyEvent(e,!1)},this.#_=e=>{this.#p.handleKeyEvent(e,!0)},this.#v=e=>this.#p.handleRawSequence(e),this.#y=e=>{this.#S(e)},this.#r.push(this.#b.onKeyPress(this.#g)),this.#r.push(this.#b.onKeyRelease(this.#_)),this.#b.onRawInput&&this.#r.push(this.#b.onRawInput(this.#v)),this.#r.push(this.#b.onFocusChange(this.#y)),this.#b.onDestroy&&this.#r.push(this.#b.onDestroy(()=>{this.#x()}))}[Bc](){return{state:this.#e,host:this.#b,conditions:this.#l,catalog:this.#u,activation:this.#s}}#x(){if(!this.#t){this.#t=!0,this.#s.setPendingSequence(null);for(let e of this.#n.values())e.dispose();this.#n.clear(),this.#m.cleanup();for(let e of this.#r.splice(0))e()}}setData(e,t){this.#c.setData(e,t)}getData(e){return this.#c.getData(e)}getHostMetadata(){return this.#b.metadata}hasPendingSequence(){return this.#s.ensureValidPendingSequence()!==void 0}createKeyMatcher(e){let t=this.#f.parseTokenKey(e).match;return e=>e?id(e)===t:!1}parseKeySequence(e){return this.#f.parseKeySequence(e)}formatKey(e,t){return this.#f.formatKey(e,t)}clearPendingSequence(){this.#s.setPendingSequence(null)}popPendingSequence(){return this.#s.popPendingSequence()}getCommands(e){return this.#u.getCommands(e)}getCommandEntries(e){return this.#u.getCommandEntries(e)}getCommandBindings(e){return this.#u.getCommandBindings(e)}acquireResource(e,t){if(this.#t||this.#b.isDestroyed)throw Error(`Cannot use a keymap after its host was destroyed`);let n=this.#n.get(e);if(n)return n.count+=1,()=>{this.#T(e,n)};let r={count:1,dispose:t()};return this.#n.set(e,r),()=>{this.#T(e,r)}}runCommand(e,t){return this.#d.runCommand(e,t)}dispatchCommand(e,t){return this.#d.dispatchCommand(e,t)}on(e,t){return e===`warning`||e===`error`?this.#i.hook(e,t):this.#a.hook(e,t)}intercept(e,t,n){return this.#p.intercept(e,t,n)}registerLayer(e){return this.#m.registerLayer(e)}registerLayerFields(e){return qu(this.#e,this.#o,`layer`,e)}prependLayerBindingsTransformer(e){return this.#e.layerBindingsTransformers.prepend(e)}appendLayerBindingsTransformer(e){return this.#e.layerBindingsTransformers.append(e)}clearLayerBindingsTransformers(){this.#e.layerBindingsTransformers.clear()}prependBindingTransformer(e){return this.#e.bindingTransformers.prepend(e)}appendBindingTransformer(e){return this.#e.bindingTransformers.append(e)}clearBindingTransformers(){this.#e.bindingTransformers.clear()}prependCommandTransformer(e){return this.#e.commandTransformers.prepend(e)}appendCommandTransformer(e){return this.#e.commandTransformers.append(e)}clearCommandTransformers(){this.#e.commandTransformers.clear()}prependBindingParser(e){return this.#e.bindingParsers.prepend(e)}appendBindingParser(e){return this.#e.bindingParsers.append(e)}clearBindingParsers(){this.#e.bindingParsers.clear()}registerToken(e){return Gu(this.#e,this.#o,this.#f,this.#m,e)}registerSequencePattern(e){return Ku(this.#e,this.#o,this.#m,e)}prependBindingExpander(e){return this.#e.bindingExpanders.prepend(e)}appendBindingExpander(e){return this.#e.bindingExpanders.append(e)}clearBindingExpanders(){this.#e.bindingExpanders.clear()}registerBindingFields(e){return qu(this.#e,this.#o,`binding`,e)}registerCommandFields(e){return qu(this.#e,this.#o,`command`,e)}prependCommandResolver(e){return this.#u.prependCommandResolver(e)}appendCommandResolver(e){return this.#u.appendCommandResolver(e)}clearCommandResolvers(){this.#u.clearCommandResolvers()}prependLayerAnalyzer(e){return this.#h.prependLayerAnalyzer(e)}appendLayerAnalyzer(e){return this.#h.appendLayerAnalyzer(e)}clearLayerAnalyzers(){this.#h.clearLayerAnalyzers()}prependEventMatchResolver(e){return this.#p.prependEventMatchResolver(e)}appendEventMatchResolver(e){return this.#p.appendEventMatchResolver(e)}clearEventMatchResolvers(){this.#p.clearEventMatchResolvers()}prependDisambiguationResolver(e){return this.#p.prependDisambiguationResolver(e)}appendDisambiguationResolver(e){return this.#p.appendDisambiguationResolver(e)}clearDisambiguationResolvers(){this.#p.clearDisambiguationResolvers()}#S(e){this.#o.runWithStateChangeBatch(()=>{this.#s.setPendingSequence(null),this.#o.queueStateChange({invalidateCaches:!1})})}#C(e,t){this.#o.warnOnce(`${e}:${t}`,`unknown-${e}-field`,{field:t,kind:e},`[Keymap] Unknown ${e} field "${t}" was ignored`)}#w(e,t){this.#o.warnOnce(`token:${e}`,`unknown-token`,{token:e,sequence:t},`[Keymap] Unknown token "${e}" in key sequence "${t}"; binding was skipped until the token is registered`)}#T(e,t){this.#n.get(e)===t&&(--t.count,!(t.count>0)&&(t.dispose(),this.#n.delete(e)))}},od=new Set(`up.down.left.right.clear.escape.return.linefeed.enter.tab.backspace.delete.insert.home.end.pageup.pagedown.space.lt.gt.plus.minus.equal.comma.period.slash.backslash.semicolon.quote.backquote.leftbracket.rightbracket.capslock.numlock.scrolllock.printscreen.pause.menu.apps.kp0.kp1.kp2.kp3.kp4.kp5.kp6.kp7.kp8.kp9.kpdecimal.kpdivide.kpmultiply.kpminus.kpplus.kpenter.kpequal.kpseparator.kpleft.kpright.kpup.kpdown.kppageup.kppagedown.kphome.kpend.kpinsert.kpdelete.mediaplay.mediapause.mediaplaypause.mediareverse.mediastop.mediafastforward.mediarewind.medianext.mediaprev.mediarecord.volumedown.volumeup.mute.leftshift.leftctrl.leftalt.leftsuper.lefthyper.leftmeta.rightshift.rightctrl.rightalt.rightsuper.righthyper.rightmeta.iso_level3_shift.iso_level5_shift.option.alt.meta.super.hyper.control.ctrl.shift`.split(`.`)),sd=new Set([`ctrl`,`control`,`shift`,`meta`,`alt`,`option`,`super`,`hyper`]),cd=ud(od),ld=ud(sd);function ud(e){let t=new Map;for(let n of e){let e=n.charCodeAt(0);if(Number.isNaN(e))continue;let r=t.get(e);r||(r=[],t.set(e,r)),r.push(n)}for(let e of t.values())e.sort((e,t)=>t.length-e.length);return t}function dd(e){return e>=65&&e<=90?e+32:e}function fd(e){return e>=48&&e<=57}function pd(e,t,n){if(e.startsWith(t,n))return!0;if(n+t.length>e.length)return!1;for(let r=0;r<t.length;r+=1)if(dd(e.charCodeAt(n+r))!==t.charCodeAt(r))return!1;return!0}function md(e,t,n){let r=t.charCodeAt(n);if(Number.isNaN(r))return;let i=e.get(dd(r));if(i){for(let e of i)if(pd(t,e,n))return e}}function hd(e,t,n,r,i){return e.parseObjectKey(t,{display:n,match:r,tokenName:i})}function gd(e,t){if(e===` `)return t.parseObjectKey({name:`space`},{display:`space`});if(e===`+`)return t.parseObjectKey({name:`+`},{display:`+`});let n=e.split(`+`),r=``,i=``,a=!1,o=!1,s=!1,c=!1,l=!1;for(let t of n){let n=t.trim();if(!n)continue;let u=n.toLowerCase();if(u===`ctrl`||u===`control`){a=!0;continue}if(u===`shift`){o=!0;continue}if(u===`meta`||u===`alt`||u===`option`){s=!0;continue}if(u===`super`){c=!0;continue}if(u===`hyper`){l=!0;continue}if(r)throw Error(`Invalid key "${e}": multiple key names are not supported`);r=n,i=u}if(!r)throw Error(`Invalid key "${e}": missing key name`);let u=[];return a&&u.push(`ctrl`),o&&u.push(`shift`),s&&u.push(`meta`),c&&u.push(`super`),l&&u.push(`hyper`),u.push(i),t.parseObjectKey({name:r,ctrl:a,shift:o,meta:s,super:c,hyper:l||void 0},{display:u.join(`+`)})}function _d(e,t){let n=e.trim().toLowerCase();return t.parseObjectKey({name:n},{display:n})}function vd(e,t){let n=md(cd,e,t);if(n)return n;if(dd(e.charCodeAt(t))!==102||!fd(e.charCodeAt(t+1)))return;let r=fd(e.charCodeAt(t+2))?t+3:t+2;return e.slice(t,r).toLowerCase()}function yd(e,t){return md(ld,e,t)}function bd(e,t,n){let r=t,i=!1,a=!1,o=!1,s=!1,c=!1;for(;r<e.length;){let t=yd(e,r);if(!t)break;let n=r+t.length;if(e[n]!==`+`)break;t===`ctrl`||t===`control`?i=!0:t===`shift`?a=!0:t===`meta`||t===`alt`||t===`option`?o=!0:t===`super`?s=!0:t===`hyper`&&(c=!0),r=n+1}if(r===t)return;let l=e[r];if(l===void 0)throw Error(`Invalid key "${e.slice(t)}": missing key name`);let u=vd(e,r)??l,d=u===` `?`space`:u===`+`?`+`:u.toLowerCase(),f=[];return i&&f.push(`ctrl`),a&&f.push(`shift`),o&&f.push(`meta`),s&&f.push(`super`),c&&f.push(`hyper`),f.push(d),{part:n.parseObjectKey({name:u===` `?`space`:u,ctrl:i,shift:a,meta:o,super:s,hyper:c||void 0},{display:f.join(`+`)}),nextIndex:r+u.length}}var xd=e=>{let{input:t,index:n,tokens:r,normalizeTokenName:i}=e;if(n===0&&t.includes(`+`)&&/\s/.test(t))return{parts:[gd(t,e)],nextIndex:t.length};let a=t[n];if(a===void 0)return;if(a===`<`){let o=t.indexOf(`>`,n);if(o===-1)return{parts:[gd(a,e)],nextIndex:n+1};let s=i(t.slice(n+1,o)),c=r.get(s);return c?{parts:[hd(e,c.stroke,`<${s}>`,c.match,s)],nextIndex:o+1,usedTokens:[s]}:{parts:[],nextIndex:o+1,unknownTokens:[s]}}if(a===`{`){let r=t.indexOf(`}`,n);if(r===-1)return{parts:[gd(a,e)],nextIndex:n+1};let o=i(t.slice(n+1,r)),s=e.patterns.get(o);return s?{parts:[{...e.parseObjectKey({name:o,ctrl:!1,shift:!1,meta:!1,super:!1},{display:s.display??`{${o}}`,match:s.match}),patternName:s.name,payloadKey:s.payloadKey}],nextIndex:r+1,usedTokens:[o]}:{parts:[],nextIndex:r+1,unknownTokens:[o]}}let o=bd(t,n,e);if(o)return{parts:[o.part],nextIndex:o.nextIndex};let s=vd(t,n);return s?{parts:[_d(s,e)],nextIndex:n+s.length}:{parts:[gd(a,e)],nextIndex:n+1}},Sd=(e,t)=>[t.resolveKey({name:e.name,ctrl:e.ctrl,shift:e.shift,meta:e.meta,super:e.super??!1,hyper:e.hyper||void 0})];function Cd(e){return e.appendBindingParser(e=>xd(e))}function wd(e){return e.appendEventMatchResolver((e,t)=>Sd(e,t))}function Td(e){let t=Cd(e),n=wd(e);return()=>{n(),t()}}var Ed=Symbol(`keymap:mod-bindings`),Dd=/(^|[+,\s])mod(?=\s*\+)/i,Od=/(^|[+,\s])mod(?=\s*\+)/gi;function kd(e){let t=e.primaryModifier;return(t===`ctrl`||t===`super`)&&e.modifiers[t]!==`unsupported`?t:e.modifiers.ctrl===`unsupported`?`super`:`ctrl`}function Ad(e){if(e.includes(`,`))return[e];let t=e.trim();return t.includes(` `)?t.split(/\s+/):[e]}function jd(e){return e.acquireResource(Ed,()=>e.appendBindingExpander(({input:t,displays:n})=>{if(!Dd.test(t))return;let r=kd(e.getHostMetadata());return[{key:t.replace(Od,(e,t)=>`${t}${r}`),displays:n??Ad(t)}]}))}var Md=new Map([[` `,`space`],[`Spacebar`,`space`],[`ArrowUp`,`up`],[`ArrowDown`,`down`],[`ArrowLeft`,`left`],[`ArrowRight`,`right`],[`Escape`,`escape`],[`Esc`,`escape`],[`Enter`,`return`],[`Backspace`,`backspace`],[`Delete`,`delete`],[`Tab`,`tab`],[`Home`,`home`],[`End`,`end`],[`PageUp`,`pageup`],[`PageDown`,`pagedown`],[`Insert`,`insert`],[`CapsLock`,`capslock`],[`NumLock`,`numlock`],[`ScrollLock`,`scrolllock`],[`ContextMenu`,`menu`],[`Meta`,`super`],[`OS`,`super`],[`Alt`,`alt`],[`Control`,`control`],[`Shift`,`shift`]]);function Nd(e){let t=e?.trim().toLowerCase();return t?t.includes(`mac`)||t.includes(`darwin`)?`macos`:t.includes(`win`)?`windows`:t.includes(`linux`)||t.includes(`x11`)?`linux`:`unknown`:`unknown`}function Pd(){let e=globalThis.navigator,t=e?.userAgentData?.platform,n=Nd(t);return n===`unknown`?Nd(e?.platform??e?.userAgent):n}function Fd(){let e=Pd();return{platform:e,primaryModifier:e===`macos`?`super`:e===`unknown`?`unknown`:`ctrl`,modifiers:{ctrl:`supported`,shift:`supported`,meta:`supported`,super:`supported`,hyper:`unsupported`}}}function Id(e){return e.length===1&&!/^[a-z0-9]$/i.test(e)}function Ld(e){let t={name:e.name,ctrl:e.ctrl,shift:e.shift,meta:e.meta,super:e.super??!1,hyper:e.hyper||void 0};return!t.shift||!Id(t.name)?[t]:[t,{...t,shift:!1}]}var Rd=class{name;ctrl;shift;meta;superKey;originalEvent;propagationStopped=!1;constructor(e,t,n,r,i,a){this.name=e,this.ctrl=t,this.shift=n,this.meta=r,this.superKey=i,this.originalEvent=a}get super(){return this.superKey}preventDefault(){this.originalEvent?.preventDefault()}stopPropagation(){this.propagationStopped=!0,this.originalEvent?.stopPropagation()}};function zd(){return globalThis.MutationObserver}function Bd(e){return Md.get(e)||(/^F\d{1,2}$/i.test(e)||e.length===1?e.toLowerCase():e.trim().toLowerCase().replace(/\s+/g,``))}function Vd(e){if(!e)return new Rd(`command`,!1,!1,!1,!1);let t=globalThis.KeyboardEvent;return new Rd(Bd(e.key),e.ctrlKey,e.shiftKey,e.altKey,e.metaKey,t&&e instanceof t?e:void 0)}var Hd=class{metadata=Fd();rootTarget;isDestroyed=!1;observer;targetDestroyListeners=new Map;constructor(e){this.rootTarget=e}getFocusedTarget(){let e=this.rootTarget.ownerDocument.activeElement;return!e||typeof e!=`object`?null:e===this.rootTarget||this.rootTarget.contains(e)?e:null}getParentTarget(e){return e.parentElement}isTargetDestroyed(e){return e===this.rootTarget?!1:!e.isConnected||!this.rootTarget.contains(e)}onKeyPress(e){let t=t=>{e(Vd(t))};return this.rootTarget.addEventListener(`keydown`,t,{capture:!0}),()=>{this.rootTarget.removeEventListener(`keydown`,t,{capture:!0})}}onKeyRelease(e){let t=t=>{e(Vd(t))};return this.rootTarget.addEventListener(`keyup`,t,{capture:!0}),()=>{this.rootTarget.removeEventListener(`keyup`,t,{capture:!0})}}onFocusChange(e){let t=()=>{queueMicrotask(()=>{e(this.getFocusedTarget())})};return this.rootTarget.addEventListener(`focusin`,t,{capture:!0}),this.rootTarget.addEventListener(`focusout`,t,{capture:!0}),()=>{this.rootTarget.removeEventListener(`focusin`,t,{capture:!0}),this.rootTarget.removeEventListener(`focusout`,t,{capture:!0})}}onTargetDestroy(e,t){let n=this.targetDestroyListeners.get(e);return n||(n=new Set,this.targetDestroyListeners.set(e,n)),n.add(t),this.ensureObserver(),this.flushDisconnectedTargets(),()=>{let n=this.targetDestroyListeners.get(e);n&&(n.delete(t),n.size===0&&this.targetDestroyListeners.delete(e),this.targetDestroyListeners.size===0&&this.disconnectObserver())}}createCommandEvent(){return Vd()}ensureObserver(){if(this.observer||this.targetDestroyListeners.size===0)return;let e=zd();e&&(this.observer=new e(()=>{this.flushDisconnectedTargets()}),this.observer.observe(this.rootTarget,{childList:!0,subtree:!0}))}disconnectObserver(){this.observer&&=(this.observer.disconnect(),void 0)}flushDisconnectedTargets(){for(let[e,t]of this.targetDestroyListeners)if(this.isTargetDestroyed(e)){this.targetDestroyListeners.delete(e);for(let e of[...t])e()}this.targetDestroyListeners.size===0&&this.disconnectObserver()}};function Ud(e){return new Hd(e)}var Wd=(e,t)=>Ld(e).map(e=>t.resolveKey(e)),Gd=`fungi.app.ready`,Kd=`fungi.app.connect`,X=e=>V.pipe(z(H(1)),z(K(e))),qd=e=>R(X(e)),Jd=ya.pipe(z(Ka()),z(L(Number.isSafeInteger,{message:`Expected a safe integer`}))),Yd=Jd.pipe(z(Fa(0))),Xd=Jd.pipe(z(Ha(0))),Zd=I({appId:X(160),releaseId:X(160),surfaceId:X(160)}),Qd=I({editing:Ua,surface:F([X(160),to])}),$d=F([I({kind:U(`compose`),requestId:X(160),text:X(2e3)}),I({kind:U(`navigate`),requestId:X(160),params:W(I({key:X(64),value:X(4096)})).pipe(z(K(16)))})]),ef=B(G([`granted`,`missing`])),tf=I({"agent.list":ef,"agent.manage":ef,"agent.read":ef,"agent.send":ef,"computer.list":ef,"computer.readFile":ef,"computer.writeFile":ef,"computer.execute":ef,"git.repository":ef,"workflow.publish":ef,"workflow.arm":ef,"workflow.run":ef,"app.events.emit":ef,"llm.generation":ef,"media.generation":ef,"media.share":ef}),nf=G([`ready`,`missing`,`unknown`]),rf=I({models:nf,media:nf,git:nf,terminal:G([`ready`,`exec-only`,`missing`,`unknown`]),terminalReason:R(V)}),af=G([`model`,`media`,`git`,`computer`]),of=G([`opened`,`unavailable`]),sf=I({computerId:F([X(256),to]),teamHasComputers:R(oo(Ua)),computerAccessGranted:R(Ua),setup:R(rf),permissions:R(tf),focus:Qd,openRequest:F([to,$d]),visibility:G([`visible`,`hidden`])}),cf=G([`connecting`,`connected`,`suspended`,`disconnected`,`disposing`,`disposed`]),lf=I({altKey:Ua,ctrlKey:Ua,id:X(160),key:X(64),metaKey:Ua,shiftKey:Ua}),uf=I({action:R(Ma),availability:R(Ma),category:X(160),description:qd(512),id:X(160),projections:R(Ma),title:X(160)}),df=I({arguments:R(Ma),commandId:X(321),origin:G([`agent`,`browser`,`keyboard`,`menu`,`palette`,`programmatic`,`slash`,`terminal`]),requestId:X(160)}),ff=F([I({result:R(Ma),status:U(`handled`)}),I({error:Ma,status:U(`failed`)})]),pf=e=>X(e).pipe(z(L(e=>{for(let t=0;t<e.length;t+=1)if(Cc(e.charCodeAt(t)))return!1;return!0},{message:`Expected one line of plain text`}))),mf={id:X(64),text:pf(80),end:B(Ua),priority:B(U(`low`))},hf=B(ya.pipe(z(Ka()),z(ma({minimum:0,maximum:9999})))),gf=W(F([I({...mf,kind:U(`text`),tone:B(G([`neutral`,`success`,`warning`,`error`]))}),I({...mf,kind:U(`button`),icon:B(G([`folder`,`ports`,`processes`,`access`])),count:hf,tone:B(G([`neutral`,`success`,`warning`,`error`])),busy:B(Ua),title:B(pf(1024)),disabled:B(Ua),opens:B(U(`dialog`)),expanded:B(Ua)}),I({...mf,kind:U(`toggle`),pressed:Ua}),I({...mf,kind:U(`menu`),count:hf,title:B(pf(1024)),options:W(I({id:X(64),text:pf(80),checked:B(Ua),disabled:B(Ua)})).pipe(z(K(16)),z(L(e=>new Set(e.map(e=>e.id)).size===e.length,{message:`Expected unique status option ids`})))})])).pipe(z(K(6)),z(L(e=>new Set(e.map(e=>e.id)).size===e.length,{message:`Expected unique status item ids`}))),_f=I({computerId:X(256),path:X(1024)}),vf=X(80).pipe(z(L(e=>e.trim()===e,{message:`Expected a trimmed title`}))),yf=X(64),bf=X(80),xf=e=>new Set(e.map(e=>e.id)).size===e.length,Sf=I({id:yf,label:bf,siblings:R(W(I({id:yf,label:bf})).pipe(z(K(16)),z(L(xf,{message:`Expected unique crumb sibling ids`}))))}),Cf=I({id:yf,label:bf,icon:R(U(`play`)),variant:R(G([`primary`,`outline`,`ghost`])),tone:R(U(`destructive`)),disabled:R(Ua)}),wf=e=>W(Cf).pipe(z(K(e)),z(L(xf,{message:`Expected unique header command ids`}))),Tf=I({id:yf,label:bf,presentation:R(U(`bead`)),tone:R(G([`neutral`,`info`,`warning`,`success`,`error`]))}),Ef={status:R(W(Tf).pipe(z(K(4)),z(L(xf,{message:`Expected unique header status ids`})))),crumbs:R(W(Sf).pipe(z(K(8)),z(L(xf,{message:`Expected unique crumb ids`})))),primary:R(wf(3)),menu:R(wf(12))},Df=I({contractVersion:U(1),canGoBack:Ua,title:R(vf),...Ef}),Of=I({canGoBack:Ua,title:R(V),...Ef}),kf=F([I({kind:U(`crumb`),crumbId:yf,siblingId:R(yf)}),I({kind:U(`action`),actionId:yf})]),Af=oo(I({agentId:X(256),sessionId:X(256)})),jf=e=>R(W(G(e)).pipe(z(K(e.length)))),Mf=I({agents:R(W(G([`agent.list`,`agent.manage`,`agent.read`,`agent.send`])).pipe(z(K(4)))),computers:R(W(G([`computer.list`,`computer.readFile`,`computer.writeFile`,`computer.execute`])).pipe(z(K(4)))),git:jf([`git.repository`]),workflows:jf([`workflow.publish`,`workflow.arm`,`workflow.run`]),events:jf([`app.events.emit`]),generation:jf([`llm.generation`,`media.generation`,`media.share`])}),Nf=G([`granted`,`declined`,`customize`]),Pf=I({message:X(512),tone:R(G([`info`,`success`,`warning`,`error`]))}),Ff=G(To);I({code:Ff.pick([`DELIVERY_PENDING`])});var If=I({code:Ff,message:X(512),retryable:Ua,need:B(wo)}),Lf=I({protocolVersion:U(2),type:U(Gd)}),Rf=I({epoch:X(160),protocolVersion:U(2),type:U(Kd)}),zf=I({epoch:X(160),protocolVersion:U(2)}),Bf={[Symbol.dispose]:R(Ma)},Vf=F([I({...Bf,ok:U(!0),value:Ma}),I({...Bf,error:If,ok:U(!1)})]);function Z(e,t,n=`PROTOCOL`){return Jr(ia(e,{onExcessProperty:`error`}),pr({onFailure:e=>{throw new J(`The peer sent malformed protocol data`,{cause:e,code:n,retryable:!1})},onSuccess:t}))}function Q(e){return Object.freeze(e)}function Hf(e,t){let n=e.arguments===void 0?void 0:x(e.arguments),r={origin:e.origin,signal:t};return n!==void 0&&Object.assign(r,{arguments:n}),Q(r)}var Uf=Z(uf,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}),Q(Pp(()=>m(t)))},`INVALID_ARGUMENT`),Wf=Z(X(321),e=>e),Gf=Z(df,e=>{let t=e.arguments===void 0?void 0:x(e.arguments),n={commandId:e.commandId,origin:e.origin,requestId:e.requestId};return t!==void 0&&Object.assign(n,{arguments:t}),Q(n)}),Kf=Z(F([qi,Ma]),e=>e===void 0?void 0:x(e)),qf=Z(Rf,e=>Q(e));Z(zf,e=>Q(e));var Jf=Z(sf,e=>{let t={computerId:e.computerId,focus:Q({...e.focus}),openRequest:e.openRequest===null?null:Q({...e.openRequest}),visibility:e.visibility};return e.teamHasComputers!==void 0&&(t.teamHasComputers=e.teamHasComputers),e.computerAccessGranted!==void 0&&(t.computerAccessGranted=e.computerAccessGranted),e.setup!==void 0&&(t.setup=Q({...e.setup})),e.permissions!==void 0&&(t.permissions=Q({...e.permissions})),Q(t)}),Yf=Z(If,e=>Q({...e})),Xf=Z(Qd,e=>Q({...e}),`INVALID_ARGUMENT`),Zf=Z(Zd,e=>Q({...e})),Qf=Z(cf,e=>e),$f=Z(gf,e=>Q(e.map(e=>e.kind===`menu`?Q({...e,options:Q(e.options.map(e=>Q(e)))}):Q(e))),`INVALID_ARGUMENT`),ep=Z(I({itemId:X(64),optionId:B(X(64)),anchor:B(I({start:ya.pipe(z(ma({minimum:0,maximum:1e5}))),width:ya.pipe(z(ma({minimum:0,maximum:1e5})))}))}),e=>Q(e.anchor===void 0?{...e}:{...e,anchor:Q({...e.anchor})}),`INVALID_ARGUMENT`),tp=Z(_f,e=>Q({...e}),`INVALID_ARGUMENT`);function np(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}),Q(t)}function rp(e){let t={id:e.id,label:e.label};return e.siblings===void 0?Q(t):Q({...t,siblings:Q(e.siblings.map(e=>Q({...e})))})}function ip(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}),Q(t)}function ap(e){let t={canGoBack:e.canGoBack};return e.title!==void 0&&(t={...t,title:e.title}),e.crumbs!==void 0&&(t={...t,crumbs:Q(e.crumbs.map(rp))}),e.primary!==void 0&&(t={...t,primary:Q(e.primary.map(ip))}),e.menu!==void 0&&(t={...t,menu:Q(e.menu.map(ip))}),e.status!==void 0&&(t={...t,status:Q(e.status.map(np))}),Q(t)}var op=Z(Df,ap,`INVALID_ARGUMENT`),sp=Z(Of,e=>{let t=e.title?.trim();return cp({...ap({...e,title:t===void 0||t.length===0?void 0:t}),contractVersion:1})},`INVALID_ARGUMENT`),cp=Z(Df,e=>Q({...ap(e),contractVersion:1}),`INVALID_ARGUMENT`),lp=Z(kf,e=>e.kind===`action`?Q({...e}):Q(e.siblingId===void 0?{kind:e.kind,crumbId:e.crumbId}:e),`INVALID_ARGUMENT`),up=Z(Af,e=>e===null?null:Q({...e}),`INVALID_ARGUMENT`),dp=Z(Mf,e=>Q({agents:Q([...new Set(e.agents??[])]),computers:Q([...new Set(e.computers??[])]),...e.git&&{git:Q([...new Set(e.git)])},...e.workflows&&{workflows:Q([...new Set(e.workflows)])},...e.events&&{events:Q([...new Set(e.events)])},...e.generation&&{generation:Q([...new Set(e.generation)])}}),`INVALID_ARGUMENT`),fp=Z(af,e=>e,`INVALID_ARGUMENT`);Z(Lf,e=>Q(e));var pp=Z(X(512),e=>e),mp=Z(Pf,e=>Q({...e}),`INVALID_ARGUMENT`);Z(I({id:X(160),repeat:Ua}),e=>Q(e));var hp=Z(W(lf).pipe(z(K(64))),e=>{if(new Set(e.map(e=>e.id)).size!==e.length)throw new J(`Reserved chords are invalid`,{code:`PROTOCOL`,retryable:!1});return Q(e.map(e=>Q({...e})))});function gp(e){return Z(I({value:Ma,version:Yd}),t=>Q({value:e(t.value),version:t.version}))}var _p=gp(Jf),vp=Z(I({capabilities:W(Ma).pipe(z(K(128))),context:Ma}),e=>Q({capabilities:Q(e.capabilities.map(e=>wp(e))),context:_p(e.context)})),yp=gp(Qf),bp=gp(hp),xp=gp(pp),Sp=Jr(yp,e=>{if(e.value!==`connected`&&e.value!==`suspended`)throw new J(`The host lifecycle is invalid`,{code:`PROTOCOL`,retryable:!1});return Q({value:e.value,version:e.version})});function Cp(e){return Z(I({handle:Ma,id:X(160),version:Xd}),t=>{if(!(t.handle instanceof bc)&&!(e&&t.handle instanceof xc))throw new J(`A capability handle is invalid`,{code:`PROTOCOL`,retryable:!1});return Q({handle:t.handle,id:t.id,version:t.version})})}var wp=Cp(!1),Tp=Cp(!0);function Ep(e){let t=e?Tp:wp;return Z(I({capabilities:W(Ma).pipe(z(K(128))),context:Ma,identity:Ma,lifecycle:Ma,reservedChords:Ma,theme:Ma}),e=>Q({capabilities:Q(e.capabilities.map(e=>t(e))),context:_p(e.context),identity:Zf(e.identity),lifecycle:Sp(e.lifecycle),reservedChords:bp(e.reservedChords),theme:xp(e.theme)}))}var Dp=Ep(!1);Ep(!0);function Op(e){return Z(Vf,t=>t.ok?Q({ok:!0,value:e(t.value)}):Q({ok:!1,error:Yf(t.error)}))}var kp=Op(Dp),Ap=Op(Z(I({commandId:X(321)}),e=>Q(e)));Op(Z(ff,e=>{if(e.status===`failed`)return Q({status:`failed`,error:Pp(()=>Pn(e.error))});let t=e.result===void 0?void 0:x(e.result);return Q(t===void 0?{status:`handled`}:{status:`handled`,result:t})}));var jp=Op(Z(qi,()=>void 0)),Mp=Op(Z(Nf,e=>e)),Np=Op(Z(of,e=>e));Op(Z(Ua,e=>e)),Op(Z(Ua,e=>e));function Pp(e){try{return e()}catch(e){throw new J(`The command metadata is invalid`,{cause:e,code:`INVALID_ARGUMENT`,retryable:!1})}}var Fp=F([I({kind:U(`saveFile`),name:X(255).pipe(z(Pa(/^[^\p{Cc}/\\]+$/u))),mime:X(255),bytes:ki}),I({kind:U(`copyText`),text:V})]);function Ip(e){let t=ia(Fp,{onExcessProperty:`error`})(e);if(or(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 Lp=Op(Z(F([I({kind:U(`saved`)}),I({kind:U(`copied`)}),I({kind:U(`refused`),reason:G([`no-user-gesture`,`too-large`,`invalid-request`,`unavailable`,`denied`,`busy`])})]),e=>Q(e)));function Rp(e){return e instanceof J?{code:e.code,message:Bp(e.message),retryable:e.retryable,...e.need!==void 0&&{need:e.need}}:{code:`HOST_FAILURE`,message:`Host operation failed`,retryable:!1}}function zp(e){try{let t=Yf(e);return new J(t.message,{code:t.code,retryable:t.retryable,...t.need!==void 0&&{need:t.need}})}catch(e){return new J(`The host returned a malformed error`,{cause:e,code:`PROTOCOL`,retryable:!1})}}function Bp(e){return e.trim().slice(0,512)||`Host operation failed`}var Vp=e=>({ok:!0,value:e}),Hp=e=>({error:Rp(e),ok:!1});async function Up(e,t){let n,r=new Set;try{return n=await e,Wp(t(n))}catch(e){throw Gp(e)&&Kp(e,r),e instanceof J?e:new J(`The remote operation failed`,{cause:e,code:`HOST_FAILURE`,retryable:!0})}finally{n!==e&&Gp(n)&&Kp(n,r)}}function Wp(e){if(e.ok)return e.value;throw zp(e.error)}function Gp(e){return _i(e)&&Symbol.dispose in e&&Br(e[Symbol.dispose])}function Kp(e,t){if(!t.has(e)){t.add(e);try{e[Symbol.dispose]()}catch(e){console.warn(`RPC result disposal failed`,e)}}}function qp(){let e=[],t=new Set;return{get:()=>e,subscribe:e=>(t.add(e),()=>t.delete(e)),update:n=>{e=n;for(let e of Array.from(t))try{e()}catch(e){console.warn(`App binding subscriber failed`,e)}}}}function Jp(e){let t=hp(e),n=new Set;return{get:()=>t,subscribe:e=>(n.add(e),()=>n.delete(e)),update:e=>{t=hp(e);for(let e of Array.from(n))try{e()}catch(e){console.warn(`Reserved chord subscriber failed`,e)}}}}function Yp(e){let t=!0,n,r=e.window.document.querySelector(`html`);if(!r)return()=>{t=!1};let i=Ud(r),a=new ad(i);Td(a),jd(a),a.prependEventMatchResolver(Wd);let o=Zp(e.onBroken),s=tm(a,e.chords,e.remote,o),c=Xp(e,o,()=>t,e=>{n=e},()=>n),l=i.onFocusChange(()=>{queueMicrotask(c)}),u=()=>{queueMicrotask(c)};e.window.addEventListener(`focus`,u),e.window.addEventListener(`blur`,u);let d=e.bindings,f=()=>Qp(e.window.document,e.identity.surfaceId).editing,p=d===void 0?()=>void 0:$p(a,d,f),m=d===void 0?()=>void 0:d.subscribe(()=>{p(),p=$p(a,d,f)}),h=e.chords.subscribe(()=>{s(),s=tm(a,e.chords,e.remote,o)});return queueMicrotask(c),()=>{t&&(t=!1,l(),e.window.removeEventListener(`focus`,u),e.window.removeEventListener(`blur`,u),h(),s(),m(),p())}}function Xp(e,t,n,r,i){return()=>{if(!n())return;let a=Qp(e.window.document,e.identity.surfaceId),o=i();(a.editing!==o?.editing||a.surface!==o.surface)&&(r(a),t(()=>e.remote.reportFocus(a)))}}function Zp(e){return t=>{try{Up(t(),jp).catch(t=>{Xo(`browser-bridge.host-call`,t),e(t)})}catch(t){Xo(`browser-bridge.host-call`,t),e(t)}}}function Qp(e,t){let n=e.activeElement;return Xf({editing:!!(n?.matches(`input, textarea, select, [contenteditable='true']`)===!0||n?.closest(`[contenteditable='true']`)),surface:e.hasFocus()?t:null})}function $p(e,t,n){let r=t.get();return e.registerLayer({bindings:r.map((e,t)=>({cmd:`app/${String(t)}`,key:e.key})),commands:r.map((e,t)=>({name:`app/${String(t)}`,run:t=>{let r=t.event.originalEvent;if(r?.defaultPrevented||r?.isComposing||em(e.key)&&n())return!1;e.run()}})),priority:500})}function em(e){return!/(?:^|\+)(?:ctrl|control|super|meta|cmd|alt|option|mod)\+/iu.test(e)}function tm(e,t,n,r){let i=t.get();return e.registerLayer({bindings:i.map(e=>({cmd:`reserved/${e.id}`,key:{ctrl:e.ctrlKey,meta:e.altKey,name:Bd(e.key),shift:e.shiftKey,super:e.metaKey}})),commands:i.map(e=>({name:`reserved/${e.id}`,run:t=>{let i=t.event.originalEvent;if(i?.defaultPrevented||i?.isComposing)return!1;r(()=>n.invokeReservedChord(e.id,i?.repeat??!1))}})),priority:1e3})}function nm(e){let t=t=>{if(t.defaultPrevented||t.isComposing)return;let n=am(t,e.mac);n!==null&&(t.preventDefault(),n===`back`&&!t.repeat&&e.canGoBack()&&e.back())},n=t=>{let n=im(t.button);if(n===null)return;let r=t.defaultPrevented;t.preventDefault(),t.type===`mouseup`&&n===`back`&&!r&&e.canGoBack()&&e.back()};e.window.addEventListener(`keydown`,t);for(let t of rm)e.window.addEventListener(t,n);return()=>{e.window.removeEventListener(`keydown`,t);for(let t of rm)e.window.removeEventListener(t,n)}}var rm=[`mousedown`,`mouseup`,`auxclick`];function im(e){return e===3?`back`:e===4?`forward`:null}function am(e,t){return e.shiftKey||e.ctrlKey?null:t?!e.metaKey||e.altKey?null:e.key===`[`?`back`:e.key===`]`?`forward`:om(e.target)?null:e.key===`ArrowLeft`?`back`:e.key===`ArrowRight`?`forward`:null:!e.altKey||e.metaKey?null:e.key===`ArrowLeft`?`back`:e.key===`ArrowRight`?`forward`:null}function om(e){return e instanceof HTMLElement?e.isContentEditable||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement:!1}function sm(){return!$n(globalThis.navigator)&&/Mac|iPhone|iPad/u.test(globalThis.navigator.userAgent)}function cm(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 lm(e){let t=new Map,n=cm(0),r=!1,i=e=>{let t=new Map;try{for(let n of e){let e=wp(n),r=pm(e.id,e.version);if(t.has(r))throw dm(e.handle),new J(`Duplicate capability grant`,{code:`PROTOCOL`,retryable:!1});t.set(r,e.handle)}}catch(e){for(let e of t.values())dm(e);throw e}return t};for(let[n,r]of i(e))t.set(n,r);let a=e=>{for(let t of e)dm(t)},o=e=>{if(r)throw new J(`The app connection is disposed`,{code:`DISCONNECTED`,retryable:!0});let n=pm(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 J(`The capability is not granted`,{code:`CAPABILITY_DENIED`,retryable:!1});try{return e.schema.parse(t)}catch(e){throw new J(`The capability interface is malformed`,{cause:e,code:`PROTOCOL`,retryable:!1})}}}),replace(e){if(r)throw new J(`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 um=gr().transform(e=>{let t=qn(Object).safeParse(e);if(!t.success)return;let n=Object.create(t.data),r=zi(I({[Symbol.dispose]:R(ua(Function))}))(n);return{owner:t.data,dispose:r[Symbol.dispose]}});function dm(e){try{let t=um.parse(e);if(t===void 0||fm.has(t.owner))return;fm.add(t.owner),t.dispose?.call(t.owner)}catch(e){console.warn(`RPC value disposal failed`,e)}}var fm=new WeakSet;function pm(e,t){return`${e}@${String(t)}`}var mm=[];for(let e=0;e<256;++e)mm.push((e+256).toString(16).slice(1));function hm(e,t=0){return(mm[e[t+0]]+mm[e[t+1]]+mm[e[t+2]]+mm[e[t+3]]+`-`+mm[e[t+4]]+mm[e[t+5]]+`-`+mm[e[t+6]]+mm[e[t+7]]+`-`+mm[e[t+8]]+mm[e[t+9]]+`-`+mm[e[t+10]]+mm[e[t+11]]+mm[e[t+12]]+mm[e[t+13]]+mm[e[t+14]]+mm[e[t+15]]).toLowerCase()}var gm,_m=new Uint8Array(16);function vm(){if(!gm){if(typeof crypto>`u`||!crypto.getRandomValues)throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);gm=crypto.getRandomValues.bind(crypto)}return gm(_m)}var ym={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function bm(e,t,n){if(ym.randomUUID&&!t&&!e)return ym.randomUUID();e||={};let r=e.random??e.rng?.()??vm();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return hm(r)}var xm=Zn({version:`v7`}),Sm=P().regex(/^replay_[a-f0-9]{64}$/);li(e=>Sm.safeParse(e).success);var Cm=Zn({version:`v4`});li(e=>xm.safeParse(e).success);var wm=li(e=>Cm.safeParse(e).success);function Tm(){return wm.parse(bm())}var Em=class extends xc{#e=!0;#t;#n=new Map;constructor(e){super(),this.#t=e}cancel(e){try{return this.#n.get(Wf(e))?.abort(),Promise.resolve(Vp(void 0))}catch(e){return Promise.resolve(Hp(e))}}dispose(){if(this.#e){this.#e=!1;for(let e of this.#n.values())e.abort();this.#n.clear()}}async invoke(e){try{if(!this.#e)throw new J(`The command is disposed`,{code:`DISCONNECTED`,retryable:!0});let t=Gf(e);if(this.#n.has(t.requestId))throw new J(`Duplicate command request`,{code:`PROTOCOL`,retryable:!1});if(this.#n.size>=64)throw new J(`Too many command requests`,{code:`HOST_FAILURE`,retryable:!0});let n=new AbortController;this.#n.set(t.requestId,n);try{let e=Kf(await this.#t(Hf(t,n.signal)));return Vp(e===void 0?{status:`handled`}:{status:`handled`,result:e})}finally{this.#n.delete(t.requestId)}}catch(e){if(e instanceof At)try{let t={code:e.code,message:e.message,details:e.details};return Vp({status:`failed`,error:Pn(t)})}catch(e){return Hp(e)}return Hp(e)}}[Symbol.dispose](){this.dispose()}};function Dm(e){let t=[];for(let n of e.values()){let{commandId:e,definition:r,target:i}=n;if(e===void 0)continue;let a=r.availability?.status!==`unavailable`;for(let n of r.projections?.bindings?.values??[])n.trim().includes(` `)||n.startsWith(`<`)||t.push({key:n,run:()=>{a&&Promise.resolve().then(async()=>{let t=Wp(await i.invoke({commandId:e,origin:`keyboard`,requestId:Tm()}));if(t.status===`failed`)throw new At(t.error.code,t.error.message,t.error.details)}).catch(e=>{console.warn(`App key command failed`,e)})}})}return t}function Om(e,t,n,r){let i=new Map,a=!1,o=()=>{r?.update(a?[]:Dm(i))},s=e=>{try{n()}catch(t){console.warn(`App command failure callback failed`,t,e)}},c=e=>{try{Up(e(),jp).catch(e=>{s(e)})}catch(e){console.warn(`App command RPC supervision failed`,e),s(e)}};return{commands:Am(e,t,i,()=>a,t=>{let n=i.get(t);if(!n)return;i.delete(t),n.target.dispose(),o();let r=n.commandId;!a&&r!==void 0&&c(()=>e.unregisterCommand(r))},o),dispose(){if(!a){a=!0;for(let e of i.values())e.target[Symbol.dispose]();i.clear(),o()}}}}function km(e,t,n){let r=t.id;if(e.size>=128||e.has(r))throw n.dispose(),new J(`Command registration is unavailable`,{code:`INVALID_ARGUMENT`,retryable:!1});let i={commandId:void 0,definition:t,target:n};e.set(r,i);let a=!1;return{commit(e){a||(i.commandId=e)},release(){a||(a=!0,e.get(r)===i&&e.delete(r),n.dispose())},target:n}}function Am(e,t,n,r,i,a){return Object.freeze({async register(o,s){if(t(),!Br(s))throw new J(`Command handler must be a function`,{code:`INVALID_ARGUMENT`,retryable:!1});let c=Uf(o),l=new Em(s),u=km(n,c,l);try{let t=await jm(e,c,u.target);r()&&await Mm(e,t.commandId,l),u.commit(t.commandId),a()}catch(e){throw u.release(),e}let d=!0;return()=>{d&&(d=!1,i(c.id))}}})}async function jm(e,t,n){return Up(e.registerCommand(t,n),Ap)}async function Mm(e,t,n){throw n.dispose(),await Up(e.unregisterCommand(t),jp),new J(`The command controller is disposed`,{code:`DISCONNECTED`,retryable:!0})}var Nm=Yi(e=>e instanceof bc),Pm=class extends xc{#e=!1;#t;constructor(e){super(),this.#t=e}disconnect(e){try{if(this.#e)throw Gm();let t=e===void 0?void 0:Yf(e);return setTimeout(()=>this.#t.disconnect?.(t??Ym()),0),Promise.resolve(Vp(void 0))}catch(e){return Promise.resolve(Hp(e))}}async requestClose(){try{if(this.#e)throw Gm();return Vp(await(this.#t.beforeClose?.()??!0))}catch(e){return Hp(e)}}async requestBack(){try{if(this.#e)throw Gm();return Vp(await(this.#t.back?.()??!1))}catch(e){return Hp(e)}}async activateNavigation(e){try{if(this.#e)throw Gm();let t=lp(e);return Tc(this.#t.navigation,t)?Vp(await(this.#t.activate?.(t)??!1)):Vp(!1)}catch(e){return Hp(e)}}async activateStatus(e){try{if(this.#e)throw Gm();let t=ep(e);return wc(this.#t.statusItems,t)?Vp(await(this.#t.statusAction?.(t)??!1)):Vp(!1)}catch(e){return Hp(e)}}[Symbol.dispose](){this.#e=!0}async updateContext(e){return this.#e?Hp(Gm()):this.#n(e,`context`,Jf,e=>{this.#t.context.update(e)})}reconfigure(e){let t=[];try{if(this.#e)throw Gm();let n=vp(e);if(n.context.version<=this.#t.versions.context)return Promise.resolve(Vp(void 0));for(let e of n.capabilities)t.push({...e,handle:zi(Nm)(e.handle).dup()});if(!this.#t.capabilities)throw Gm();return this.#t.capabilities.replace(t),t=[],this.#t.versions.context=n.context.version,this.#t.context.update(n.context.value),Promise.resolve(Vp(void 0))}catch(e){for(let e of t)dm(e.handle);return Promise.resolve(Hp(e))}}updateLifecycle(e){try{if(this.#e)throw Gm();let t=gp(Qf)(e);if(t.version<=this.#t.versions.lifecycle)return Promise.resolve(Vp(void 0));if(!Xm(this.#t.lifecycle.get(),t.value))throw new J(`The host sent an invalid lifecycle transition`,{code:`PROTOCOL`,retryable:!1});return this.#t.versions.lifecycle=t.version,this.#t.lifecycle.update(t.value),Promise.resolve(Vp(void 0))}catch(e){return Promise.resolve(Hp(e))}}async updateReservedChords(e){return this.#e?Hp(Gm()):this.#n(e,`chords`,hp,e=>{this.#t.chords.update(e)})}async updateTheme(e){return this.#e?Hp(Gm()):this.#n(e,`theme`,pp,e=>{this.#t.theme.update(e)})}#n(e,t,n,r){try{let i=gp(n)(e);return i.version>this.#t.versions[t]&&(this.#t.versions[t]=i.version,r(i.value)),Promise.resolve(Vp(void 0))}catch(e){return Promise.resolve(Hp(e))}}};async function Fm(e){let t=zm(),n=new Pm(t),r=Sc(e.port,n),i,a=Rm(r);try{performance.mark(`fungi.app-open.agar-rpc-connect-start`);let o=await Promise.race([r.connect({epoch:e.epoch,protocolVersion:2}),a]);performance.mark(`fungi.app-open.agar-rpc-connect-ready`),i=o;let s=Wp(kp(o));if(!e.isActive())throw Lm();let c=Bm({bootstrap:s,bootstrapOwner:i,options:e,remote:r,state:t,target:n});return performance.mark(`fungi.app-open.agar-root-created`),i=void 0,c}catch(t){return Qm(t,e,n,r,i)}}function Im(e,t){e.context.update(t.context.value),e.theme.update(t.theme.value),e.lifecycle.update(t.lifecycle.value),e.chords.update(t.chords.value),e.versions.context=t.context.version,e.versions.theme=t.theme.version,e.versions.lifecycle=t.lifecycle.version,e.versions.chords=t.chords.version}function Lm(){return new J(`App connection was cancelled`,{code:`CANCELLED`,retryable:!1})}function Rm(e){let t,n=new Promise((e,n)=>{t=n});return n.catch(e=>{Xo(`app-session.rpc-disconnect`,e)}),e.onRpcBroken(()=>t?.(new J(`The app host disconnected`,{code:`DISCONNECTED`,retryable:!0}))),n}function zm(){return{statusItems:[],navigation:{canGoBack:!1},bindings:qp(),chords:Jp([]),context:cm({computerId:null,focus:{editing:!1,surface:null},openRequest:null,visibility:`hidden`}),lifecycle:cm(`connecting`),theme:cm(`default`),canGoBack:!1,versions:{chords:-1,context:-1,lifecycle:-1,theme:-1}}}function Bm(e){let t=Zf(e.bootstrap.identity),n=Zm(e.bootstrap);Im(e.state,n);let r=lm(e.bootstrap.capabilities);return e.state.capabilities=r,Hm(e,t,r)}function Vm(e,t,n){return Yp({bindings:e.state.bindings,chords:e.state.chords,identity:t,onBroken:e=>{n({code:`DISCONNECTED`,message:e instanceof J?e.message:`The app host rejected a browser bridge operation`,retryable:!0})},remote:e.remote,window:e.options.window})}function Hm(e,t,n){let r=!1,i=t=>{r||(r=!0,qm([()=>{t&&e.state.lifecycle.update(`disconnected`)},()=>{e.state.lifecycle.update(`disposing`)},l,u,()=>{o.dispose()},()=>{e.state.beforeClose=void 0,e.state.back=void 0,e.state.activate=void 0,e.state.statusAction=void 0},()=>{n.disconnect()},()=>{e.target[Symbol.dispose]()},()=>{dm(e.bootstrapOwner)},()=>{dm(e.remote)},()=>{e.options.port.close()},()=>{e.state.lifecycle.update(`disposed`)},e.options.onDisposed],`app connection disposal`))},a=()=>{if(r)throw new J(`The app connection is disposed`,{code:`DISCONNECTED`,retryable:!0})},o=Om(e.remote,a,()=>{i({code:`DISCONNECTED`,message:`The app host rejected a terminal command operation`,retryable:!0})},e.state.bindings),s=Wm(e.remote,a,e.state),c=Um(e.state,e.remote,a),l=Vm(e,t,i),u=nm({window:e.options.window,mac:sm(),canGoBack:()=>e.state.canGoBack&&e.state.back!==void 0,back:()=>{let t=e.state.back;t&&Promise.resolve().then(t).catch(e=>{Xo(`app-window.back-input`,e)})}});return e.state.disconnect=i,e.remote.onRpcBroken(()=>{Km(i)}),Jm({capabilities:n.directory,commands:o.commands,context:e.state.context,dispose:i,identity:t,lifecycle:e.state.lifecycle,theme:e.state.theme,ui:s,window:c})}function Um(e,t,n){let r=Object.freeze({async publish(r){n();let i=sp(r);e.canGoBack=i.canGoBack,e.navigation=op(i),await Up(t.reportNavigation(i),jp)},onActivate(t){if(n(),e.activate!==void 0)throw new J(`The App already owns navigation activations`,{code:`INVALID_ARGUMENT`,retryable:!1});e.activate=t;let r=!1;return()=>{r||(r=!0,e.activate===t&&(e.activate=void 0))}},onBack(t){if(n(),e.back!==void 0)throw new J(`The App already owns Back requests`,{code:`INVALID_ARGUMENT`,retryable:!1});e.back=t;let r=!1;return()=>{r||(r=!0,e.back===t&&(e.back=void 0))}}});return Object.freeze({navigation:r,onBeforeClose(t){if(n(),e.beforeClose!==void 0)throw new J(`The App already owns a close consultation`,{code:`INVALID_ARGUMENT`,retryable:!1});e.beforeClose=t;let r=!1;return()=>{r||(r=!0,e.beforeClose===t&&(e.beforeClose=void 0))}}})}function Wm(e,t,n){return Object.freeze({async requestComputerChoice(){t(),await Up(e.requestComputerChoice(),jp)},async requestBrowserAction(n){t();let r=Ip(n);return r.kind===`refused`?r:await Up(e.requestBrowserAction(r),Lp)},onStatusAction(e){if(t(),n.statusAction!==void 0)throw new J(`The App already owns its status actions`,{code:`INVALID_ARGUMENT`,retryable:!1});n.statusAction=e;let r=!1;return()=>{r||(r=!0,n.statusAction===e&&(n.statusAction=void 0))}},async requestAppPermissions(n){return t(),await Up(e.requestAppPermissions(dp(n)),Mp)},async openDesktopSettings(){t(),await Up(e.openDesktopSettings(),jp)},async openSetup(n){return t(),await Up(e.openSetup(fp(n)),Np)},async openTeamBilling(){t(),await Up(e.openTeamBilling(),jp)},async openNavigation(n){t(),await Up(e.openNavigation(tp(n)),jp)},async reportStatus(r){t();let i=$f(r);n.statusItems=i,await Up(e.reportStatus(i),jp)},async reportAgentSessionSelection(n){t(),await Up(e.reportAgentSessionSelection(up(n)),jp)},async showToast(n){t(),await Up(e.showToast(mp(n)),jp)}})}function Gm(){return new J(`The app connection is disposed`,{code:`DISCONNECTED`,retryable:!0})}function Km(e){e({code:`DISCONNECTED`,message:`The app host disconnected`,retryable:!0})}function qm(e,t){for(let n of e)try{n()}catch(e){console.warn(`${t} cleanup failed`,e)}}function Jm(e){return Object.freeze(e)}function Ym(){return{code:`DISCONNECTED`,message:`The app host disconnected`,retryable:!1}}function Xm(e,t){return e===t||e===`connected`&&t===`suspended`||e===`suspended`&&t===`connected`}function Zm(e){let t=gp(Jf)(e.context),n=gp(pp)(e.theme),r=gp(Qf)(e.lifecycle),i=gp(hp)(e.reservedChords);if(r.value!==`connected`&&r.value!==`suspended`)throw new J(`The bootstrap lifecycle is invalid`,{code:`PROTOCOL`,retryable:!1});return{chords:i,context:t,lifecycle:r,theme:n}}function Qm(e,t,n,r,i){throw qm([()=>{n[Symbol.dispose]()},()=>{i&&dm(i)},()=>{dm(r)},()=>{t.port.close()},t.onDisposed],`app connection rejection`),e instanceof J?e:new J(`Unable to establish the app RPC session`,{cause:e,code:`PROTOCOL`,retryable:!1})}var $m=!1,eh=class{options;#e;#t;#n=!1;#r;#i;constructor(e){this.options=e,this.#e=globalThis.window}start(){performance.mark(`fungi.app-open.agar-connect-start`);let e=this.#l();return e?Promise.reject(e):($m=!0,this.#a())}#a(){return new Promise((e,t)=>{let n=(n,a)=>{this.#o(n,a,i,r,e,t)},r=()=>{n(nh())},i=e=>{this.#s(e,n,i)};this.#e.addEventListener(`message`,i),this.options.signal?.addEventListener(`abort`,r,{once:!0});let a=()=>{try{performance.mark(`fungi.app-open.agar-ready-sent`),this.#e.parent.postMessage({protocolVersion:2,type:Gd},`*`)}catch(e){Xo(`connect.notify-host`,e),n(ch(e))}};this.#r=setInterval(a,200),this.#i=setTimeout(()=>{n(ih())},1e4),a()})}#o(e,t,n,r,i,a){if(!this.#n){if(this.#n=!0,this.#c(),this.#e.removeEventListener(`message`,n),this.options.signal?.removeEventListener(`abort`,r),e||!t){this.#t?.close(),$m=!1,a(e??ih());return}i(t)}}#s(e,t,n){if(!sh(e.data))return;if(performance.mark(`fungi.app-open.agar-connect-received`),e.source!==this.#e.parent||ah(e.origin)===void 0){t(oh());return}let r=lh(e,t);if(!r)return;let i=e.ports.length===1?e.ports[0]:void 0;if(!i){t(uh(`The app host did not transfer exactly one port`));return}this.#t=i,this.#c(),this.#e.removeEventListener(`message`,n),Fm({epoch:r.epoch,isActive:()=>!this.#n,onDisposed:()=>{$m=!1},port:i,window:this.#e}).then(e=>{performance.mark(`fungi.app-open.agar-root-ready`),t(void 0,e)},e=>{t(rh(e))})}#c(){clearInterval(this.#r),clearTimeout(this.#i),this.#r=void 0,this.#i=void 0}#l(){if(this.options.signal?.aborted)return nh();if($m)return new J(`An app connection is already live`,{code:`IDENTITY`,retryable:!1});if($n(globalThis.window)||this.#e.parent===this.#e)return new J(`The app host is unavailable`,{code:`DISCONNECTED`,retryable:!0})}};function th(e){return new eh(e).start()}function nh(){return new J(`App connection was cancelled`,{code:`CANCELLED`,retryable:!1})}function rh(e){return e instanceof J?e:new J(`Unable to connect to the app host`,{cause:e,code:`PROTOCOL`,retryable:!1})}function ih(){return new J(`The app host disconnected`,{code:`DISCONNECTED`,retryable:!0})}function ah(e){if(!URL.canParse(e))return;let t=new URL(e).origin;return t===e?t:void 0}function oh(){return new J(`The app connection identity is invalid`,{code:`IDENTITY`,retryable:!1})}var sh=ca(I({type:U(Kd)}));function ch(e){return new J(`Unable to notify the app host`,{cause:e,code:`DISCONNECTED`,retryable:!0})}function lh(e,t){try{return qf(e.data)}catch(e){Xo(`connect.decode-message`,e),t(e instanceof J?e:new J(`Malformed app connection`,{cause:e,code:`PROTOCOL`,retryable:!1}));return}}function uh(e){return new J(e,{code:`PROTOCOL`,retryable:!1})}function dh(e,t,n){e.style.isolation=`isolate`;let r=(0,Yo.createRoot)(e),i=new AbortController,a=e.ownerDocument.documentElement,o=jo(a),s,c,l,u=!1,d=e=>{let i=(0,q.createElement)(fh,{state:e,render:n});r.render(t.queryClient?(0,q.createElement)(St,{client:t.queryClient},i):i)},f=()=>{l?.(),l=void 0,c?.(),c=void 0;let e=s;s=void 0,e?.dispose(),u&&=(o===null?a.removeAttribute(`data-theme`):Ao(o,a),!1)},{defaultView:p}=e.ownerDocument;return performance.mark(`fungi.app-open.react-root-render-start`),p?p.parent===p?d({app:null,status:`standalone`}):(d({app:null,status:`connecting`}),th({host:`parent`,signal:i.signal}).then(e=>{if(i.signal.aborted){e.dispose();return}s=e;let t=()=>{let t=e.lifecycle.get();return t===`disposing`||t===`disconnected`||t===`disposed`?(f(),d({app:null,status:`ended`}),!0):!1};l=e.lifecycle.subscribe(t),!t()&&(u=!0,Ao(e.theme.get(),a),c=e.theme.subscribe(e=>{Ao(e,a)}),d({app:e,status:`live`}))}).catch(e=>{i.signal.aborted&&e instanceof J&&e.code===`CANCELLED`||(console.error(`${t.name} host connection failed`,e),f(),i.signal.aborted||d({app:null,status:`not-hosted`,error:e instanceof J?e:new J(`The App host is unavailable`,{cause:e,code:`HOST_FAILURE`,retryable:!0})}))})):d({app:null,status:`not-hosted`,error:new J(`The App document has no window`,{code:`DISCONNECTED`,retryable:!1})}),()=>{i.signal.aborted||(i.abort(),r.unmount(),f())}}function fh({state:e,render:t}){return(0,q.useLayoutEffect)(()=>{performance.mark(`fungi.app-open.react-initial-commit`)},[]),(0,q.useLayoutEffect)(()=>{e.app&&performance.mark(`fungi.app-open.react-connected-commit`)},[e.app]),(0,q.createElement)(q.Fragment,null,e.status===`not-hosted`?(0,q.createElement)(`p`,{role:`alert`},`App host connection unavailable. Open this App through its host to try again.`):null,t(e))}function ph(e){let t=(0,q.useCallback)(t=>e?.subscribe(t)??(()=>void 0),[e]),n=(0,q.useCallback)(()=>e?.get(),[e]);return(0,q.useSyncExternalStore)(t,n,n)}function mh(e){return ph(e?.context)??null}function hh(e,t,n,r){let i=(0,q.useRef)(t);i.current=t;let a=(0,q.useRef)(n);a.current=n;let o=(0,q.useRef)(r);o.current=r;let s=JSON.stringify(t),c=n!==void 0;(0,q.useEffect)(()=>{e&&e.ui.reportStatus(i.current).catch(e=>{o.current?o.current(e):console.error(`Window status report failed`,e)})},[e,s]),(0,q.useEffect)(()=>{if(!(!e||!c))return e.ui.onStatusAction(e=>a.current?.(e)??!1)},[e,c]),(0,q.useEffect)(()=>()=>{e?.ui.reportStatus([]).catch(e=>{console.error(`Window status report failed`,e)})},[e])}function gh(e,{canGoBack:t,title:n,crumbs:r,primary:i,menu:a,status:o,onBack:s,onCrumb:c,onAction:l}){let u=(0,q.useRef)(s),d=(0,q.useRef)(c),f=(0,q.useRef)(l);(0,q.useEffect)(()=>{u.current=s,d.current=c,f.current=l},[s,c,l]),(0,q.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(),_h(e,{canGoBack:!1})}},[e]);let p=JSON.stringify([r,i,a,o]),m=(0,q.useRef)({crumbs:r,primary:i,menu:a,status:o});(0,q.useEffect)(()=>{m.current={crumbs:r,primary:i,menu:a,status:o}},[r,i,a,o]),(0,q.useEffect)(()=>{if(!e)return;let r={canGoBack:t};n!==void 0&&(r={...r,title:n});let i=m.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}),_h(e,r)},[e,t,n,p])}function _h(e,t){e.publish(t).catch(e=>{e instanceof J&&e.code===`DISCONNECTED`||console.warn(`App navigation report failed`,e)})}var vh=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 yh(e,t,n){return new vh(e,t,n)}function bh(e){let t=Dr(e),n=qn(Object),r=Dr(Object.fromEntries(Object.keys(e).map(e=>[e,gr().optional()])));return gr().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,fr().parse(t).bind(i)]));return{...t.parse(s),[Symbol.dispose](){dm(e)}}})}function xh(e){return gr().transform(t=>{try{return e.parse(t)}catch(e){throw e instanceof J?e:new J(`The capability returned malformed data`,{cause:e,code:`PROTOCOL`,retryable:!1})}finally{dm(t)}})}function Sh(e){return fr({output:mi(gr().transform(t=>{try{return e.parse(t)}catch(e){throw dm(t),e instanceof J?e:new J(`The capability returned a malformed result`,{cause:e,code:`PROTOCOL`,retryable:!1})}}))})}var Ch=Sh(xh(ei())),wh=bh({fetch:Sh(qn(Response)),close:Ch}),Th=Tr([`plain`,`pencil`,`manga`,`riso`,`halftone`,`blueprint`,`crt`,`watercolor`]),Eh={ink:`var(--sprite-ink, var(--color-base-content, #1c1c1a))`,paper:`var(--sprite-paper, var(--color-base-100, #fbfaf6))`,accent:`var(--sprite-accent, var(--color-accent, #d20f39))`,risoFirst:`var(--sprite-riso-first, var(--color-info, #1e66f5))`,risoSecond:`var(--sprite-riso-second, var(--color-accent, #ea76cb))`,blueprint:`var(--sprite-blueprint, color-mix(in oklab, var(--color-info, #1e66f5) 55%, #0b2350))`,blueprintLine:`var(--sprite-blueprint-line, color-mix(in oklab, var(--color-info-content, #ffffff) 25%, #ffffff))`,screen:`var(--sprite-screen, color-mix(in oklab, var(--color-base-content, #111111) 12%, #050805))`,phosphor:`var(--sprite-phosphor, var(--color-success, #40a02b))`},$=(e,t={},...n)=>({tag:e,attributes:t,children:n}),Dh=(e,t,n=1)=>$(`feFlood`,{style:`flood-color: ${e}`,"flood-opacity":n,result:t}),Oh=(e,t,n)=>[$(`feImage`,{href:`data:image/svg+xml,${encodeURIComponent(`<svg xmlns='http://www.w3.org/2000/svg' width='${String(t)}' height='${String(t)}'>${e}</svg>`)}`,width:t,height:t,result:`${n}Cell`}),$(`feTile`,{in:`${n}Cell`,result:n})],kh=(e,t,n)=>$(`feColorMatrix`,{in:t,type:`matrix`,values:`0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ${e}`,result:n}),Ah=(e,t)=>kh(`-0.333 -0.333 -0.333 1 0`,e,t),jh=(e,t,n,r=1.1)=>[$(`feConvolveMatrix`,{in:e,order:3,kernelMatrix:`0 1 0 1 -4 1 0 1 0`,result:`${t}In`}),$(`feConvolveMatrix`,{in:e,order:3,kernelMatrix:`0 -1 0 -1 4 -1 0 -1 0`,result:`${t}Out`}),$(`feComposite`,{in:`${t}In`,in2:`${t}Out`,operator:`arithmetic`,k2:1,k3:1,result:`${t}Edges`}),kh(`${String(n)} ${String(n)} ${String(n)} ${String(r)} 0`,`${t}Edges`,t)],Mh=(e,t,n,r)=>[$(`feConvolveMatrix`,{in:e,order:3,kernelMatrix:`0 1 0 1 -4 1 0 1 0`,preserveAlpha:`true`,result:`${t}In`}),$(`feConvolveMatrix`,{in:e,order:3,kernelMatrix:`0 -1 0 -1 4 -1 0 -1 0`,preserveAlpha:`true`,result:`${t}Out`}),$(`feComposite`,{in:`${t}In`,in2:`${t}Out`,operator:`arithmetic`,k2:1,k3:1,result:`${t}Edges`}),kh(`${String(n)} ${String(n)} ${String(n)} 0 -0.15`,`${t}Edges`,`${t}Inner`),$(`feMorphology`,{in:e,operator:`dilate`,radius:r,result:`${t}Grown`}),$(`feComposite`,{in:`${t}Grown`,in2:e,operator:`out`,result:`${t}Ring`}),kh(`0 0 0 1 0`,`${t}Ring`,`${t}Outline`),Ph(t,`${t}Inner`,`${t}Outline`)],Nh=(e,t,n)=>$(`feComponentTransfer`,{in:e,result:n},$(`feFuncA`,{type:`discrete`,tableValues:t})),Ph=(e,...t)=>$(`feMerge`,{result:e},...t.map(e=>$(`feMergeNode`,{in:e}))),Fh=(e,t,n,r=1)=>[Dh(e,`${n}Flood`,r),$(`feComposite`,{in:`${n}Flood`,in2:t,operator:`in`,result:n})],Ih={x:`0%`,y:`0%`,width:`100%`,height:`100%`},Lh={x:`-8%`,y:`-8%`,width:`116%`,height:`116%`},Rh={value:1.6,line:6,outline:2.4,midHatch:[3.2,-.05],darkHatch:[3.4,-.4],tooth:`0 0 0 -0.7 1.45`,opacity:1},zh=e=>({region:Lh,primitives:[$(`feComponentTransfer`,{in:`SourceGraphic`,result:`valued`},...[`feFuncR`,`feFuncG`,`feFuncB`].map(t=>$(t,{type:`gamma`,amplitude:1,exponent:e.value,offset:0}))),$(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.05,numOctaves:2,seed:1,result:`wobble`,"data-sprite-boil":`wobble`}),$(`feDisplacementMap`,{in:`valued`,in2:`wobble`,scale:2.6,xChannelSelector:`R`,yChannelSelector:`G`,result:`drawn`}),...jh(`drawn`,`line`,e.line,e.outline),Ah(`drawn`,`dark`),...Oh(`<path d='M-1 1l2-2M0 6l6-6M5 7l2-2' stroke='black' stroke-width='1.1'/>`,6,`hatch45`),$(`feOffset`,{in:`hatch45`,dx:0,dy:0,result:`hatchOffset`,"data-sprite-boil":`hatch`}),$(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.07,numOctaves:2,seed:5,result:`strokeBend`}),$(`feDisplacementMap`,{in:`hatchOffset`,in2:`strokeBend`,scale:4,xChannelSelector:`R`,yChannelSelector:`B`,result:`hatchA`}),...Oh(`<path d='M-1 4l2 2M0 0l5 5M4 -1l2 2' stroke='black' stroke-width='0.9'/>`,5,`hatch135`),$(`feDisplacementMap`,{in:`hatch135`,in2:`strokeBend`,scale:3,xChannelSelector:`G`,yChannelSelector:`R`,result:`hatchB`}),$(`feComposite`,{in:`dark`,in2:`hatchA`,operator:`arithmetic`,k1:e.midHatch[0],k4:e.midHatch[1],result:`shadeA`}),$(`feComposite`,{in:`dark`,in2:`hatchB`,operator:`arithmetic`,k1:e.darkHatch[0],k4:e.darkHatch[1],result:`shadeB`}),$(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.9,numOctaves:1,seed:3,result:`tooth`}),kh(e.tooth,`tooth`,`toothMask`),kh(`0 0 0 6 -4.6`,`dark`,`solid`),Ph(`graphiteRaw`,`solid`,`shadeA`,`shadeB`,`line`),$(`feComposite`,{in:`graphiteRaw`,in2:`toothMask`,operator:`in`,result:`graphite`}),...Fh(Eh.ink,`graphite`,`pencil`,e.opacity)],boil:{intervalMs:160,tracks:[{name:`wobble`,attribute:`seed`,frames:[1,2,3]},{name:`hatch`,attribute:`dx`,frames:[0,1,2]}]}}),Bh={region:Lh,primitives:[$(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.04,numOctaves:2,seed:2,result:`brush`,"data-sprite-boil":`brush`}),$(`feDisplacementMap`,{in:`SourceGraphic`,in2:`brush`,scale:2,xChannelSelector:`R`,yChannelSelector:`G`,result:`drawn`}),...Fh(Eh.paper,`SourceAlpha`,`paperFill`),Ah(`drawn`,`dark`),...Oh(`<circle cx='2.5' cy='2.5' r='1.15' fill='black'/>`,5,`dots`),Nh(`dark`,`0 1 1 0`,`midTone`),$(`feComposite`,{in:`dots`,in2:`midTone`,operator:`in`,result:`tone`}),Nh(`dark`,`0 0 0 1`,`solid`),kh(`3 -3 0 0 -0.35`,`drawn`,`satRG`),kh(`-3 3 0 0 -0.35`,`drawn`,`satGR`),kh(`0 3 -3 0 -0.35`,`drawn`,`satGB`),kh(`0 -3 3 0 -0.35`,`drawn`,`satBG`),Ph(`saturation`,`satRG`,`satGR`,`satGB`,`satBG`),Nh(`saturation`,`0 1`,`accentMask`),...Fh(Eh.accent,`accentMask`,`accentFill`),...Mh(`drawn`,`edge`,2,2.2),$(`feMorphology`,{in:`edge`,operator:`dilate`,radius:.25,result:`stroke`}),Ph(`inkRaw`,`tone`,`solid`,`stroke`),...Fh(Eh.ink,`inkRaw`,`ink`),Ph(`manga`,`paperFill`,`accentFill`,`ink`)],boil:{intervalMs:180,tracks:[{name:`brush`,attribute:`seed`,frames:[2,4,6]}]}},Vh={region:Lh,primitives:[kh(`-0.55 -0.55 -0.55 1.65 0`,`SourceGraphic`,`dark`),$(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.85,numOctaves:1,seed:7,result:`grain`}),kh(`0 0 0 -0.9 1.35`,`grain`,`grainMask`),$(`feComposite`,{in:`dark`,in2:`grainMask`,operator:`in`,result:`firstMask`}),...Fh(Eh.risoFirst,`firstMask`,`firstInk`,.92),kh(`0 -1.9 0 1.9 0`,`SourceGraphic`,`secondMask`),...Fh(Eh.risoSecond,`secondMask`,`secondInk`,.9),$(`feOffset`,{in:`firstInk`,dx:-1.5,dy:1,result:`firstPlate`,"data-sprite-boil":`register`}),$(`feOffset`,{in:`secondInk`,dx:1.5,dy:-.5,result:`secondPlate`}),$(`feBlend`,{in:`firstPlate`,in2:`secondPlate`,mode:`multiply`})],boil:{intervalMs:240,tracks:[{name:`register`,attribute:`dx`,frames:[-1.5,-1,-2]}]}},Hh={region:Lh,primitives:[kh(`-0.5 -0.5 -0.5 1.65 0`,`SourceGraphic`,`value`),kh(`0 0 0 0.16 0`,`SourceGraphic`,`floor`),Ph(`dark`,`floor`,`value`),...Oh(`<defs><radialGradient id='d'><stop offset='0' stop-opacity='1'/><stop offset='1' stop-opacity='0'/></radialGradient></defs><rect width='6' height='6' fill='url(#d)'/>`,6,`screen`),$(`feComposite`,{in:`dark`,in2:`screen`,operator:`arithmetic`,k2:1,k3:1,k4:-.92,result:`dotField`}),$(`feComponentTransfer`,{in:`dotField`,result:`dotsRaw`},$(`feFuncA`,{type:`linear`,slope:12,intercept:0})),$(`feComposite`,{in:`dotsRaw`,in2:`SourceAlpha`,operator:`in`,result:`dots`}),...Fh(Eh.ink,`dots`,`halftone`)]},Uh={region:Ih,primitives:[Dh(Eh.blueprint,`ground`),$(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.05,numOctaves:1,seed:4,result:`hand`,"data-sprite-boil":`hand`}),$(`feDisplacementMap`,{in:`SourceGraphic`,in2:`hand`,scale:1.6,xChannelSelector:`R`,yChannelSelector:`G`,result:`drawn`}),...Oh(`<path d='M0 0.5h16M0.5 0v16' stroke='black' stroke-width='1' stroke-opacity='0.22'/>`,16,`grid`),...Fh(Eh.blueprintLine,`grid`,`gridLines`),...Fh(Eh.blueprintLine,`SourceAlpha`,`wash`,.12),...Mh(`drawn`,`edge`,3,1.2),$(`feMorphology`,{in:`edge`,operator:`dilate`,radius:.3,result:`stroke`}),...Fh(Eh.blueprintLine,`stroke`,`lines`),Ph(`blueprint`,`ground`,`gridLines`,`wash`,`lines`)],boil:{intervalMs:200,tracks:[{name:`hand`,attribute:`seed`,frames:[4,5,6]}]}},Wh={region:Ih,primitives:[Dh(Eh.screen,`ground`),$(`feColorMatrix`,{in:`SourceGraphic`,type:`luminanceToAlpha`,result:`lumRaw`}),$(`feComposite`,{in:`lumRaw`,in2:`SourceAlpha`,operator:`in`,result:`lum`}),$(`feComponentTransfer`,{in:`lum`,result:`beam`},$(`feFuncA`,{type:`linear`,slope:1.5,intercept:-.35})),$(`feComposite`,{in:`beam`,in2:`SourceAlpha`,operator:`in`,result:`trace`}),...Fh(Eh.phosphor,`trace`,`glow`),$(`feGaussianBlur`,{in:`glow`,stdDeviation:2.5,result:`bloom`}),...Oh(`<rect y='2' width='3' height='1' fill='black'/>`,3,`scan`),$(`feOffset`,{in:`scan`,dx:0,dy:0,result:`scanRoll`,"data-sprite-boil":`roll`}),...Fh(Eh.screen,`scanRoll`,`scanlines`,.6),Ph(`crt`,`ground`,`bloom`,`glow`,`scanlines`)],boil:{intervalMs:120,tracks:[{name:`roll`,attribute:`dy`,frames:[0,1,2]}]}},Gh={region:Lh,primitives:[$(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.03,numOctaves:3,seed:9,result:`flow`}),$(`feDisplacementMap`,{in:`SourceGraphic`,in2:`flow`,scale:7,xChannelSelector:`R`,yChannelSelector:`G`,result:`bled`}),$(`feGaussianBlur`,{in:`bled`,stdDeviation:1.4,result:`wash`}),$(`feComponentTransfer`,{in:`wash`,result:`thin`},$(`feFuncR`,{type:`linear`,slope:.78,intercept:.2}),$(`feFuncG`,{type:`linear`,slope:.78,intercept:.2}),$(`feFuncB`,{type:`linear`,slope:.78,intercept:.2}),$(`feFuncA`,{type:`linear`,slope:.9,intercept:0})),$(`feGaussianBlur`,{in:`wash`,stdDeviation:3,result:`spread`}),$(`feComposite`,{in:`wash`,in2:`spread`,operator:`arithmetic`,k2:1.6,k3:-1.4,result:`rimMask`}),$(`feComponentTransfer`,{in:`wash`,result:`deep`},$(`feFuncR`,{type:`linear`,slope:.6,intercept:0}),$(`feFuncG`,{type:`linear`,slope:.6,intercept:0}),$(`feFuncB`,{type:`linear`,slope:.6,intercept:0})),$(`feComposite`,{in:`deep`,in2:`rimMask`,operator:`in`,result:`rim`}),$(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.7,numOctaves:2,seed:11,result:`tooth`}),kh(`0 0 0 -0.8 1.5`,`tooth`,`toothMask`),Ah(`SourceGraphic`,`dark`),kh(`0 0 0 5 -3.8`,`dark`,`keyMask`),...Fh(Eh.ink,`keyMask`,`key`,.9),Ph(`paint`,`thin`,`rim`,`key`),$(`feComposite`,{in:`paint`,in2:`toothMask`,operator:`in`})]},Kh=zh(Rh),qh={manga:Bh,riso:Vh,halftone:Hh,blueprint:Uh,crt:Wh,watercolor:Gh},Jh=e=>e===`pencil`?Kh:qh[e],Yh=`http://www.w3.org/2000/svg`,Xh=(e,t)=>{let n=e.createElementNS(Yh,t.tag);for(let[e,r]of Object.entries(t.attributes))n.setAttribute(e,String(r));for(let r of t.children)n.append(Xh(e,r));return n};function Zh(e){let t=`sprite-style-${Tm()}`,n=e.ownerDocument,r=n.defaultView,i=`plain`,a,o,s=!1,c=!0,l,u=0,d=()=>{l!==void 0&&clearInterval(l),l=void 0},f=()=>{if(d(),i===`plain`||!o||s||!c||n.hidden)return;let e=Jh(i).boil;if(!e)return;let t=o;l=setInterval(()=>{if(!n.hidden){u+=1;for(let n of e.tracks){let e=n.frames[u%n.frames.length];t.querySelector(`[data-sprite-boil="${n.name}"]`)?.setAttribute(n.attribute,String(e))}}},e.intervalMs)},p=r?.IntersectionObserver,m=p?new p(e=>{c=e.some(e=>e.isIntersecting),f()}):void 0;m?.observe(e);let h=()=>{d(),o?.remove(),o=void 0,a&&(a.style.filter=``)};return{set(r,s){if(r===i&&s===a||(h(),i=r,a=s,r===`plain`))return;let c=Jh(r),l=`${t}-${r}`,u=n.createElementNS(Yh,`svg`);u.setAttribute(`aria-hidden`,`true`),u.setAttribute(`focusable`,`false`),u.setAttribute(`width`,`0`),u.setAttribute(`height`,`0`),u.style.cssText=`position:absolute;width:0;height:0;overflow:hidden`,u.append(Xh(n,$(`filter`,{id:l,...c.region,"color-interpolation-filters":`sRGB`},...c.primitives))),e.append(u),o=u,s.style.filter=`url(#${l})`,f()},still(e){e!==s&&(s=e,f())},dispose(){h(),a=void 0,m?.disconnect()}}}var Qh=[`mushroom`,`cat`,`burger`];Tr([`shift`,`keep`]);var $h=P().regex(/^#[0-9a-f]{6}$/i),eg=hi([$h,zr(),ti()]),tg=16,ng=Ar({v:ri(1),character:Tr(Qh),appearance:bi(P().min(1),eg).refine(e=>Object.keys(e).length<=tg,{message:`Avatar appearance cannot exceed ${String(tg)} keys`}),expression:P().min(1),renderStyle:Th});function rg(e,t,n){let r=t/100,i=n/100,a=r*Math.min(i,1-i),o=t=>{let n=(t+e/30)%12,r=i-a*Math.max(-1,Math.min(n-3,9-n,1));return Math.round(255*r).toString(16).padStart(2,`0`)};return`#${o(0)}${o(8)}${o(4)}`}function ig(e){let t=2166136261;for(let n of e)t^=n.codePointAt(0)??0,t=Math.imul(t,16777619)>>>0;return t}function ag(e){let t=ig(e)%360;return{cap:rg(t,68,72),capSpot:rg(t,70,92)}}function og(e){return{v:1,character:`mushroom`,appearance:ag(e),expression:`normal`,renderStyle:`plain`}}var sg=V.pipe(z(H(1)),z(K(256))),cg=Yi(e=>ng.safeParse(e).success,{expected:`an Avatar v1 descriptor`}),lg=I({agentId:sg,name:sg,avatar:cg,sessionOperations:W(G([`agent.read`,`agent.send`,`agent.manage`]))});Ir(()=>Ar({agents:oi(Ar({agentId:P(),name:P()}))}));var ug=F([G([`new`,`none`]),I({computerId:sg})]),dg=I({computerId:sg,name:sg,createdAt:ya.pipe(z(Ka()))}),fg=oo(W(dg)),pg=zi(fg,{onExcessProperty:`error`}),mg=I({name:sg,requestId:sg,computer:B(ug),avatar:B(cg)}),hg=W(lg),gg=zi(hg,{onExcessProperty:`error`}),_g=zi(sg),vg=zi(ua(Response)),yg=yh(`agent.list`,1,Ir(()=>bh({list:Sh(xh(gr().transform(e=>gg(e))))}))),bg=yh(`agent.manage`,1,Ir(()=>bh({open:Sh(wh),computers:Sh(xh(gr().transform(e=>pg(e)))),create:Sh(xh(gr().transform(e=>zi(lg)(e))))}))),xg=I({agentId:sg,name:sg}),Sg=yh(`agent.rename`,1,Ir(()=>bh({rename:Sh(xh(gr().transform(e=>zi(lg)(e))))})));async function Cg(e,t){let n=zi(xg)(t),r=await e.require(Sg).rename(n);return zi(lg)(r)}var wg=I({agentId:sg,avatar:cg}),Tg=yh(`agent.avatar`,1,Ir(()=>bh({setAvatar:Sh(xh(gr().transform(e=>zi(lg)(e))))})));async function Eg(e,t){let n=zi(wg)(t),r=await e.require(Tg).setAvatar(n);return zi(lg)(r)}var Dg=Ir(()=>hi([Dr({status:ri(`pending`),revision:P()}),Dr({status:ri(`approved`),revision:P()})])),Og=Ir(()=>hi([Dg,Dr({error:P()})])),kg=yh(`agent.toolPolicy`,1,Ir(()=>bh({status:Sh(xh(hi([Dg,Fr()]))),approve:Sh(xh(Og))}))),Ag=yh(`agent.read`,1,Ir(()=>bh({open:Sh(wh),openInbox:Sh(wh)}))),jg=yh(`agent.send`,1,Ir(()=>bh({open:Sh(wh),openInbox:Sh(wh)})));async function Mg(e,t){let n=zi(mg)(t),r=await e.require(bg).create(n);return zi(lg)(r)}async function Ng(e){let t=pg(await e.require(bg).computers());return t===null?null:[...t].sort((e,t)=>t.createdAt-e.createdAt)}async function Pg(e,t){let n=await e(),r,i,a=()=>{if(i)throw new J(`The Agent connection is closed`,{code:`DISCONNECTED`,retryable:!0})},o=async e=>{try{await e.close()}finally{e[Symbol.dispose]()}};return{fetch:async i=>{a(),i.signal.throwIfAborted();let o=i.method===`GET`||i.method===`HEAD`||e===t?n:await(r??=t());a(),i.signal.throwIfAborted();let s=vg(await o.fetch(i));return s.body===null?s:new Response(s.body.pipeThrough(new TransformStream,{signal:i.signal}),s)},close:()=>(i||(i=Promise.all([o(n),...r?[r.then(o)]:[]]).then(()=>void 0),i.catch(e=>{Xo(`agents.close`,e)})),i)}}var Fg=`https://agent-session.fungi.invalid`;async function Ig(e,t){let n=_g(t.agentId),r=`/agents/id-${encodeURIComponent(n)}`,i=`${Fg}${r}`,a=e.has(Ag)?e.require(Ag):e.has(jg)?e.require(jg):e.require(bg),o=()=>a.open({agentId:n}),s=await Pg(o,e.has(Ag)?()=>(e.has(jg)?e.require(jg):e.require(bg)).open({agentId:n}):o);return Object.freeze({baseUrl:i,fetch:async(e,t)=>{let n=new Request(e,t),i=new URL(n.url);if(i.origin!==Fg||!i.pathname.startsWith(`${r}/`))throw new J(`The Agent request target is invalid`,{code:`INVALID_ARGUMENT`,retryable:!1});return i.pathname=i.pathname.slice(r.length),s.fetch(new Request(i,n))},close:s.close})}var Lg=`${Fg}/member`;async function Rg(e){let t=e.has(Ag)?Ag:jg,n=()=>e.require(t).openInbox(),r=await Pg(n,e.has(Ag)?()=>e.require(jg).openInbox():n);return Object.freeze({baseUrl:Lg,fetch:async(e,t)=>{let n=new Request(e,t),i=new URL(n.url);if(i.origin!==Fg||!i.pathname.startsWith(`/member/inbox`))throw new J(`The inbox request target is invalid`,{code:`INVALID_ARGUMENT`,retryable:!1});return i.pathname=i.pathname.slice(7),r.fetch(new Request(i,n))},close:r.close})}var zg=class extends Event{code;message;constructor(e,t){super(e),this.code=t?.code??void 0,this.message=t?.message??void 0}[Symbol.for(`nodejs.util.inspect.custom`)](e,t,n){return n(Hg(this),t)}[Symbol.for(`Deno.customInspect`)](e,t){return e(Hg(this),t)}};function Bg(e){let t=globalThis.DOMException;return typeof t==`function`?new t(e,`SyntaxError`):SyntaxError(e)}function Vg(e){return e instanceof Error?`errors`in e&&Array.isArray(e.errors)?e.errors.map(Vg).join(`, `):`cause`in e&&e.cause instanceof Error?`${e}: ${Vg(e.cause)}`:e.message:`${e}`}function Hg(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var Ug=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}},Wg=10,Gg=13,Kg=32,qg=6;function Jg(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{maxBufferSize:t,onComment:n,onError:r,onEvent:i,onId:a,onRetry:o}=e,s=[],c=0,l=!0,u,d=``,f=0,p,m=!1,h=!1,g=!1;function _(e){if(m)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,e.charCodeAt(0)===65279?e=e.slice(1):e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),(h||g)&&(e=v(e),!e))return;if(!s.length){let t=S(e);t!==``&&y(t),x();return}if(e.indexOf(`
|
|
3
3
|
`)===-1&&e.indexOf(`\r`)===-1){if(c<qg&&!b(s.join(``)+e.slice(0,qg-c))){s.length=0,c=0,h=!0;return}s.push(e),c+=e.length,x();return}s.push(e);let t=s.join(``);s.length=0,c=0,y(S(t)),x()}function v(e){if(e.length===0)return e;if(g)return g=!1,e.charCodeAt(0)===Wg?e.slice(1):e;let t=e.indexOf(`\r`),n=e.indexOf(`
|
|
4
4
|
`),r=t===-1?n:n===-1||t<n?t:n;return r===-1?``:r===e.length-1&&e.charCodeAt(r)===Gg?(h=!1,g=!0,``):(h=!1,e.slice(r+(e.charCodeAt(r)===Gg&&e.charCodeAt(r+1)===Wg?2:1)))}function y(e){if(e){if(e.charCodeAt(e.length-1)===Gg){C(e,0,e.length-1),g=!0;return}if(b(e)){s.push(e),c=e.length;return}h=!0}}function b(e){let t=e.charCodeAt(0);return t===58&&!!n||t===100&&Zg(e,`data`)||t===101&&Zg(e,`event`)||t===105&&Zg(e,`id`)||t===114&&Zg(e,`retry`)}function x(){t!==void 0&&(c+d.length<=t||(m=!0,s.length=0,c=0,u=void 0,d=``,f=0,p=void 0,h=!1,g=!1,r?.(new Ug(`Buffered data exceeded max buffer size of ${t} characters`,{type:`max-buffer-size-exceeded`}))))}function S(e){let t=0;if(e.indexOf(`\r`)===-1){let n=e.indexOf(`
|
|
5
5
|
`,t);for(;n!==-1;){if(t===n){u!==void 0&&a?.(u),f>0&&i?.({id:u,event:p,data:d}),u=void 0,d=``,f=0,p=void 0,t=n+1,n=e.indexOf(`
|
|
@@ -113,5 +113,5 @@ import{r as e,t}from"./rolldown-runtime-hePW80VL.js";import{$ as n,$n as r,$r as
|
|
|
113
113
|
recovery_count = ?, recovery_window_started_at = ?
|
|
114
114
|
WHERE job_id = ? AND state = 'running' AND claim_token = ?`,i.recoveryCount,i.windowStartedAt,n.job.jobId,n.claimToken),gS(e,t,n.job.queue),{status:`requeued`};let a=r.row.cancellation_id!==null,o=a?null:r.job.recovery===void 0?`Execution disappeared without a recovery policy`:`Restart recovery budget exhausted (${String(r.job.recovery.maxRecoveries)} recoveries)`;e.sql.exec(`UPDATE watchdog_jobs
|
|
115
115
|
SET state = 'settled', outcome = ?, failure_reason = ?
|
|
116
|
-
WHERE job_id = ? AND state = 'running' AND claim_token = ?`,a?`cancelled`:`interrupted`,o,n.job.jobId,n.claimToken);let s=fS(e,n.job.jobId)?.job;return s?.state===`settled`?(gS(e,t,s.queue,s),{status:`settled`,job:s}):{status:`conflict`}}))})};return Object.freeze({store:i(n),partition:i,transactional:r})}var wS=V.check(H(1),K(256)),TS=V.check(H(1),K(200)),ES=Ia.check(Fa(-(2**53-1)),ga(2**53-1)),DS=Ia.check(Fa(0),ga(2**53-1)),OS=I({maxRecoveries:DS,windowMs:B(Ia.check(Ha(0),ga(2**53-1)))}),kS={jobId:wS,queue:wS,lane:Ux,priority:ES,payload:Ma,notBefore:B(DS),recovery:R(OS)},AS=I({...kS,state:U(`queued`)}),jS=G([`completed`,`failed`,`cancelled`,`outcome_unknown`,`interrupted`]),MS={...kS,outcome:jS,failureReason:B(TS)},NS=I({...MS,state:U(`completing`)}),PS=I({...MS,state:U(`settled`)}),FS=I({...kS,state:U(`running`)}),IS=F([AS,FS,NS,PS]);F([I({kind:U(`retry`)}),I({kind:U(`completed`)}),I({kind:U(`failed`),reason:B(TS)}),I({kind:U(`cancelled`)}),I({kind:U(`outcome_unknown`)})]);var LS=I({jobId:wS,cancellationId:wS,onlyIfQueued:R(Ua)}),RS=F([I({status:U(`absent`)}),I({status:U(`present`),cancellation:LS})]);F([I({status:U(`found`),job:IS,cancellation:RS}),I({status:U(`missing`)})]),F([I({state:U(`idle`)}),I({state:G([`queued`,`running`]),jobId:wS,cancellationRequested:Ua})]),F([I({status:U(`queued`)}),I({status:U(`duplicate`)})]),F([I({status:U(`decided`),outcome:jS}),I({status:G([`recorded`,`replayed`])}),I({status:G([`conflict`,`missing`])})]);var zS=F([ua(ArrayBuffer),V,ya,to]);io(V,zS);function BS(e){return vi({try:()=>{let t=e.concurrentLane===void 0?void 0:zi(Ux)(e.concurrentLane),n=CS(e.owner,e.project,t===void 0?void 0:{lane:t,include:!1}),r=Vx(e,n.store),i={...r,transactional:n.transactional};if(t===void 0)return Object.freeze(i);let a=Vx(e,n.partition({lane:t,include:!0}));return Object.freeze({...i,tickConcurrent:a.tick,close:Wr([Hr(r.close),Hr(a.close)],{concurrency:2}).pipe(yi(e=>{let t=e.find(Mi);return t===void 0?gi:Er(t.cause)})),failLane:e=>e.lane===t?a.failLane(e):r.failLane(e),cancel:e=>r.read(e.jobId).pipe(yi(n=>n.status===`found`&&n.job.lane===t?a.cancel(e):r.cancel(e)))})},catch:e=>e instanceof Rx?e:new Rx(`store_unavailable`,e)})}var VS=e=>({owner:e.owner,project:e.project,isAlive:t=>jr({try:()=>e.isAlive(t),catch:e=>new Rx(`liveness_unavailable`,e)}),executor:{retryPolicy:t=>{let n=e.retryPolicy;return n===void 0?ii(void 0):jr({try:()=>n(t),catch:e=>new Rx(`execution_failed`,e)})},execute:(t,n)=>jr({try:r=>e.execute(t,r,n),catch:()=>new Rx(`execution_failed`)})},wake:{recompute:()=>jr({try:()=>e.wake.recompute(),catch:()=>new Rx(`wake_unavailable`)})}}),HS=e=>Kr(e).then(e=>{if(Ai(e))return e.value;let t=Gr(Ii(e.cause))??uo(e.cause);return Promise.reject(t instanceof Error?t:Error(String(t)))});function US(e){let t=VS(e);return e.concurrentLane===void 0?HS(BS(t)).then(WS):HS(BS({...t,concurrentLane:e.concurrentLane})).then(e=>Object.freeze({...WS(e),tickConcurrent:()=>HS(e.tickConcurrent())}))}function WS(e){return Object.freeze({wakeState:t=>HS(e.wakeState(t)),ingest:t=>HS(e.ingest(t)),read:t=>HS(e.read(t)),readQueueHead:t=>HS(e.readQueueHead(t)),tick:()=>HS(e.tick()),cancel:t=>HS(e.cancel(t)),failLane:t=>HS(e.failLane(t)),purge:t=>HS(e.purge(t)),transactional:e.transactional})}Object.freeze({make:US});function GS(e){return wr(()=>_o(()=>import(`./runtime-core-B3RwT1fj.js`).then(e=>e.t),__vite__mapDeps([0,1,2,3,4]))).pipe(yi(({openRuntimeCore:t})=>t(e)),ir(({agent:e})=>e))}Object.freeze({module:Oa,operation:Ja,gate:za}),Qi(Ci),zi(Bi(Ci));var KS=class extends ur()(`@fungi.computer/shiitake/ExtensionRead`){},qS=class extends ur()(`@fungi.computer/shiitake/ExtensionTx`){},JS=class extends Ei(`ExtensionStateError`){},YS=class extends Ei(`AdmissionError`){},XS=class extends Ei(`ExtensionCommandError`){},ZS=class extends Ei(`ExtensionStop`){};Ei(`ExtensionActivationError`),zi(Aa),zi(xa),ca(V);function QS(e){return e instanceof Oi?e:new Oi(`model`,`rejected`,`Model acquisition failed`,void 0,e)}function $S(e){return new Oi(`model`,`rejected`,`Model release failed`,void 0,e)}function eC(e){let t=jr({try:()=>e.release(),catch:$S}),n={model:e.model,release:t,retryable:e.retryable};return e.failureReason!==void 0&&(n={...n,failureReason:e.failureReason}),e.providerError!==void 0&&(n={...n,providerError:e.providerError}),e.rejection!==void 0&&(n={...n,rejection:e.rejection}),e.stream===void 0?e.retryAfterMs===void 0?Object.freeze(n):Object.freeze({...n,retryAfterMs:e.retryAfterMs}):e.retryAfterMs===void 0?Object.freeze({...n,stream:e.stream}):Object.freeze({...n,stream:e.stream,retryAfterMs:e.retryAfterMs})}function tC(e){return Xr((t,n)=>{if(n.aborted)return;let r;try{r=Promise.resolve(e(n))}catch(e){t(Rr(QS(e)));return}let i=r.then(e=>{if(n.aborted)return Promise.resolve(e.release()).then(()=>void 0);t(ii(eC(e)))},e=>{n.aborted?da(`late-model-acquisition`,e):t(Rr(QS(e)))});return jr({try:()=>i,catch:$S}).pipe(Sr)})}function nC(e){let t,n=Xn(n=>yi(n(e),e=>Ur(()=>(t=e,e))));return di(n,()=>t===void 0?gi:t.release.pipe(Sr),{interruptible:!0})}function rC(e){let t=({sessionId:t,preference:n})=>tC(r=>e.acquire({sessionId:t,preference:n,signal:r})),n=e.describe;return Object.freeze(n===void 0?{acquire:t}:{acquire:t,describe:({sessionId:e,preference:t})=>jr({try:r=>n({sessionId:e,preference:t,signal:r}),catch:QS})})}function iC(e,t){return new Oi(e,`rejected`,t)}var aC=V.pipe(z(H(1)),z(K(256))),oC=V.pipe(z(H(1)),z(L(e=>new TextEncoder().encode(e).byteLength<=32e3))),sC=I({revision:aC,text:oC,modules:B(Yi(e=>Array.isArray(e)&&e.every(_i)))}),cC=Yi(e=>Br(e)),lC=Yi(e=>Br(e)),uC=I({bind:cC}),dC=Yi(e=>Br(e)),fC=I({commit:dC,requestWake:lC,close:lC}),pC=I({close:lC}),mC=ia(sC),hC=ia(uC),gC=ia(fC),_C=ia(pC);function vC(e){return new Oi(`runtime`,`invalid`,`Runtime host is invalid`,void 0,e)}function yC(){return new Oi(`runtime`,`unavailable`,`Runtime host is unavailable`)}function bC(e,t){return vi({try:()=>t.call(e),catch:yC}).pipe(yi(e=>jr({try:()=>Promise.resolve(e),catch:yC})),yi(e=>e===void 0?gi:Rr(vC())))}function xC(e,t,n){let r=_C({close:t});return r._tag===`Failure`?Rr(vC(n)):hr(bC(e,r.success.close)).pipe(vr({onFailure:e=>Rr(vC({cause:n,cleanup:e})),onSuccess:()=>Rr(vC(n))}))}function SC(e){return $r(()=>{if(!_i(e))return Rr(vC());let t=e,n;try{n=t.close}catch(e){return Rr(vC(e))}let r;try{r=t.requestWake}catch(e){return xC(t,n,e)}let i=gC({commit:t.commit,requestWake:r,close:n});return i._tag===`Failure`?xC(t,n):ii(Object.freeze({commit:e=>jr({try:()=>t.commit(()=>Ga(e)),catch:e=>e instanceof Oi?e:yC()}),requestWake:bC(t,i.success.requestWake),close:bC(t,i.success.close)}))})}function CC(e){return vi({try:()=>{let t=e.runtime;if(!_i(t))throw vC();let n=hC(t);if(n._tag===`Failure`)throw vC();return{receiver:t,bind:n.success.bind}},catch:vC}).pipe(ir(({receiver:e,bind:t})=>Object.freeze({bind:({reconcile:n,reconcileHost:r,pendingWork:i})=>vi({try:()=>t.call(e,{reconcile:()=>Ga(n),reconcileHost:r===void 0?void 0:()=>Ga(r),pendingWork:()=>Ga(i)}),catch:yC}).pipe(yi(e=>jr({try:()=>Promise.resolve(e),catch:yC})),yi(SC))})))}function wC(e){return{lane:e.lane,open:t=>{let n=e.open({transactional:t.transactional,readJob:e=>Ga(t.read(e)),tickConcurrent:()=>Ga(t.tickConcurrent())});return{retryPolicy:e=>{let t=n.retryPolicy;return t===void 0?ii(void 0):jr({try:()=>t(e),catch:e=>new Rx(`execution_failed`,e)})},execute:(e,t)=>jr({try:r=>n.execute(e,r,t),catch:e=>new Rx(`execution_failed`,e)})}}}}function TC(e,t){let n={store:e.store,runtime:t,extensions:e.extensions,instructions:{load:({sessionId:t,commandId:n})=>jr({try:r=>e.instructions.load({sessionId:t,commandId:n,signal:r}),catch:()=>iC(`instructions`,`Instruction acquisition failed`)}).pipe(yi(e=>{let t=mC(e);return t._tag===`Success`?ii(t.success):Rr(new Oi(`contract`,`invalid`,`Instruction revision is invalid`))}))},model:rC(e.model)},r=e.recipientStatus,i=e.recipientParent;i!==void 0&&Object.assign(n,{recipientParent:e=>jr(()=>i(e)).pipe(Nr(e=>er(`recipient.parent_unavailable`,Ta(e)).pipe(Or(Rr(new JS({reason:`unavailable`,message:`Recipient parent is unavailable`}))))))}),r!==void 0&&Object.assign(n,{recipientStatus:e=>jr(()=>r(e)).pipe(Nr(e=>er(`recipient.status_unavailable`,Ta(e)).pipe(ci(`unknown`))))}),e.hostJobs!==void 0&&Object.assign(n,{hostJobs:wC(e.hostJobs)}),e.meta!==void 0&&Object.assign(n,{meta:e.meta}),e.storagePressure!==void 0&&Object.assign(n,{storagePressure:e.storagePressure}),e.admission!==void 0&&Object.assign(n,{admission:e.admission}),e.compaction!==void 0&&Object.assign(n,{compaction:e.compaction});let a=e.tools;return a===void 0?n:{...n,tools:Da(a)}}function EC(e,t){return Ga(CC(e).pipe(yi(n=>t(TC(e,n))))).then(La)}Object.freeze({make:e=>EC(e,GS)});var DC=200,OC=Ar({action:ri(`list`)}),kC=bi(P(),Pr()).parse(structuredClone(dr(OC))),AC=120,jC=Ar({title:P()}).optional().transform(e=>e?.title.trim().replaceAll(/\s+/gu,` `)??``),MC=4096,NC=Ar({instructions:P()}).optional().transform(e=>e?.instructions.trim()??``);function PC(e,t){return e?.notify({type:`info`,message:t}),t}function FC(e,t){let n=e=>{throw Error(`${e} is unavailable in this host.`)};return{sourceId:t.sourceId,namespace:t.namespace,commands:[{id:`session`,title:`Session status`,category:`Advanced`,projections:{help:{order:1},palette:{order:1},slash:{aliases:[`session`],order:1}},handler:async({interaction:t})=>{let n=await e.read();return PC(t,`Session ${n.sessionId} is ${bn(dt(n))}; ${String(n.pending.prompts.length)} queued prompt${n.pending.prompts.length===1?``:`s`}.`)}},{id:`queue`,title:`Queued prompts`,category:`Advanced`,projections:{help:{order:3},palette:{order:3},slash:{aliases:[`queue`],order:3,arguments:{hint:`list`,words:[{word:`list`,description:`List accepted queued prompts`,arguments:{action:`list`}}]}}},action:{inputSchema:kC},handler:async({arguments:t,interaction:n})=>{if(!OC.safeParse(t??{action:`list`}).success)throw Error(`/queue requires list.`);let r=await e.read(),i=r.pending.prompts,a=r.terminals.map(e=>`${e.outcome} · ${e.commandId}`);PC(n,i.length===0&&a.length===0?`No queued prompts.`:[...i.map((e,t)=>`${String(t+1)}. queued · accepted: ${e.text}`),...a,...r.pending.hasMore===!0?[`More accepted prompts are waiting outside this view.`]:[]].join(`
|
|
117
|
-
`))}},{id:`resume`,title:`Resume a conversation`,category:`Conversation`,projections:{help:{order:5},palette:{order:5},slash:{aliases:[`resume`],order:5}},handler:async()=>{if(!t.sessionResumeAvailable||t.sessionResume===void 0){n(`/resume`);return}await t.sessionResume()}},{id:`fork`,title:`Fork conversation`,category:`Conversation`,projections:{help:{order:7},palette:{order:7},slash:{aliases:[`fork`],order:7}},handler:async({interaction:r})=>{let i=t.onForked;if(!t.forkAvailable||i===void 0){n(`/fork`);return}let a=await e.read();if(bn(dt(a))!==`idle`)throw Error(`Wait for the current run to finish, then fork.`);let o=He(a.messages??[],a.compactions??[]).items.filter(e=>e.kind===`user_message`);if(o.length===0)throw Error(`No messages to fork from.`);if(r===void 0)throw Error(`Forking a Session needs a person.`);let s=[...o].reverse().slice(0,DC),c=Date.now(),l=await r.prompt({type:`choice`,message:`Fork from which message?`,summary:`Start a new conversation from your message.`,options:s.map(e=>({value:e.id,label:hx(e.text,44)||`(empty message)`,description:e.at===void 0?void 0:mx(e.at,c)}))}),u=await r.run(async()=>{try{return await e.command({type:`fork`,entryId:l})}catch(e){if(e instanceof Oi){if(e.boundary===`runtime`&&e.cause===`conflict`)throw Error(`Wait for the current run to finish, then fork.`,{cause:e});if(e.boundary===`store`&&e.cause===`unavailable`)throw Error(`That message is no longer available to fork from.`,{cause:e});if(e.boundary===`runtime`&&e.cause===`rejected`)throw Error(`This Session is bound to a channel and cannot be forked.`,{cause:e})}throw e}});await r.run(async()=>{await i(u.sessionId)})}},{id:`compact`,title:`Compact conversation`,category:`Conversation`,description:`Summarize older context now; optional text sets its focus`,projections:{help:{order:8},palette:{order:8},slash:{aliases:[`compact`],order:8,arguments:{hint:`[instructions]`,text:{field:`instructions`,arguments:{}}}}},handler:async({arguments:t})=>{let n=NC.safeParse(t);if(!n.success)throw Error(`Use /compact, or /compact <what to focus on>.`);let r=n.data;if(r.length>MC)throw Error(`Compaction instructions are at most ${String(MC)} characters.`);return await e.command(r.length===0?{type:`compact`,requestId:Xa()}:{type:`compact`,requestId:Xa(),instructions:r}),`Compaction queued; it runs after any current work.`}},{id:`name`,title:`Name conversation`,category:`Conversation`,description:`Set the conversation title; no text restores it`,projections:{help:{order:9},palette:{order:9},slash:{aliases:[`name`],order:9,arguments:{hint:`[title]`,text:{field:`title`,arguments:{}}}}},handler:async({arguments:n})=>{let r=jC.safeParse(n);if(!r.success)throw Error(`Use /name <title>, or /name to clear it.`);let i=r.data;if(Array.from(i).length>AC)throw Error(`A conversation title is at most ${String(AC)} characters.`);let a=i.length===0?null:i;return await e.command({type:`title`,title:a}),await t.onTitled?.(a),a===null?`Conversation title cleared; it follows the first prompt again.`:`Conversation named "${a}".`}}]}.commands}function IC(e,t){return t!=null&&!Fn(t)?0:typeof e==`function`?e():e}function LC(e,t,n){let r=IC(e,n);return typeof r==`number`?r:r?.[t]}function RC(e){return typeof e==`function`?e():e}function zC(e,t){return t||e===`click`||e===`mousedown`}function BC(e){return e?.includes(`mouse`)&&e!==`mousedown`}var VC=class e{pointerType=void 0;interactedInside=!1;handler=void 0;blockMouseMove=!0;performedPointerEventsMutation=!1;pointerEventsScopeElement=null;pointerEventsReferenceElement=null;pointerEventsFloatingElement=null;restTimeoutPending=!1;openChangeTimeout=new xn;restTimeout=new xn;handleCloseOptions=void 0;static create(){return new e}dispose=()=>{this.openChangeTimeout.clear(),this.restTimeout.clear()};disposeEffect=()=>this.dispose},HC=new WeakMap;function UC(e){if(!e.performedPointerEventsMutation)return;let t=e.pointerEventsScopeElement;t&&HC.get(t)===e&&(e.pointerEventsScopeElement?.style.removeProperty(`pointer-events`),e.pointerEventsReferenceElement?.style.removeProperty(`pointer-events`),e.pointerEventsFloatingElement?.style.removeProperty(`pointer-events`),HC.delete(t)),e.performedPointerEventsMutation=!1,e.pointerEventsScopeElement=null,e.pointerEventsReferenceElement=null,e.pointerEventsFloatingElement=null}function WC(e,t){let{scopeElement:n,referenceElement:r,floatingElement:i}=t,a=HC.get(n);a&&a!==e&&UC(a),UC(e),e.performedPointerEventsMutation=!0,e.pointerEventsScopeElement=n,e.pointerEventsReferenceElement=r,e.pointerEventsFloatingElement=i,HC.set(n,e),n.style.pointerEvents=`none`,r.style.pointerEvents=`auto`,i.style.pointerEvents=`auto`}function GC(e){let t=e.context.dataRef.current,n=un(()=>t.hoverInteractionState??VC.create()).current;return t.hoverInteractionState||=n,Kt(t.hoverInteractionState.disposeEffect),t.hoverInteractionState}function KC(e,t={}){let{enabled:n=!0,closeDelay:r=0,nodeId:i}=t,a=e.useState(`open`),o=e.useState(`floatingElement`),s=e.useState(`domReferenceElement`),{dataRef:c}=e.context,l=Mn(),u=nt(),d=GC(e),f=ft(),p=Ct(()=>zC(c.current.openEvent?.type,d.interactedInside)),m=Ct(()=>BC(c.current.openEvent?.type)),g=Ct(()=>{UC(d)});ot(()=>{a||(d.pointerType=void 0,d.restTimeoutPending=!1,d.interactedInside=!1,g())},[a,d,g]),q.useEffect(()=>g,[g]),ot(()=>{if(n&&a&&d.handleCloseOptions?.blockPointerEvents&&m()&&Ye(s)&&o){let e=s,t=o,n=h(o),r=l?.nodesRef.current.find(e=>e.id===u)?.context?.elements.floating;r&&(r.style.pointerEvents=``);let i=d.pointerEventsScopeElement===t?null:d.pointerEventsScopeElement,a=r===t?null:r,c=d.handleCloseOptions?.getScope?.()??i??a??T(e,`[data-rootownerid]`)??n.body;return WC(d,{scopeElement:c,referenceElement:e,floatingElement:t}),()=>{g()}}},[n,a,s,o,d,m,l,u,g]),q.useEffect(()=>{if(!n)return;function t(){return!!(l&&u&&Ne(l.nodesRef.current,u).length>0)}function a(t){let n=LC(r,`close`,d.pointerType),i=()=>{e.setOpen(!1,N(he,t)),l?.events.emit(`floating.closed`,t)};n?d.openChangeTimeout.start(n,i):(d.openChangeTimeout.clear(),i())}function s(e){let t=M(e);if(!S(t)){d.interactedInside=!1;return}d.interactedInside=T(t,`[aria-haspopup]`)!=null}function h(){d.openChangeTimeout.clear(),f.clear(),l?.events.off(`floating.closed`,v),g()}function _(n){if(t()&&l){l.events.on(`floating.closed`,v);return}if(y(n.relatedTarget,e.context.triggerElements))return;let r=c.current.floatingContext?.nodeId??i,o=n.relatedTarget;if(!(l&&r&&Ye(o)&&Ne(l.nodesRef.current,r,!1).some(e=>re(e.context?.elements.floating,o)))){if(d.handler){d.handler(n);return}g(),m()&&!p()&&a(n)}}function v(n){!l||!u||t()||f.start(0,()=>{l.events.off(`floating.closed`,v),e.setOpen(!1,N(he,n)),l.events.emit(`floating.closed`,n)})}let b=o;return C(b&&An(b,`mouseenter`,h),b&&An(b,`mouseleave`,_),b&&An(b,`pointerdown`,s,!0),()=>{l?.events.off(`floating.closed`,v)})},[n,o,e,c,r,i,m,p,g,d,l,u,f])}var qC=e(Qe(),1),JC={current:null};function YC(e,t={}){let{enabled:n=!0,delay:r=0,handleClose:i=null,mouseOnly:a=!1,restMs:o=0,move:s=!0,triggerElementRef:c=JC,externalTree:l,isActiveTrigger:u=!0,getHandleCloseContext:d,isClosing:f,shouldOpen:p,guardStaleOpen:m=!1}=t,{dataRef:g,events:_}=e.context,v=Mn(l),b=GC(e),x=q.useRef(!1),S=Fe(i),w=Fe(r),T=Fe(o),E=Fe(n),ee=Fe(p),D=Fe(f),O=Ct(()=>zC(g.current.openEvent?.type,b.interactedInside)),k=Ct(()=>ee.current?.()!==!1),A=Ct((t,n,r)=>{let i=e.context.triggerElements;if(i.hasElement(n))return!t||!re(t,n);if(!Ye(r))return!1;let a=r;return i.hasMatchingElement(e=>re(e,a))&&(!t||!re(t,a))}),j=Ct(()=>{b.handler&&=(h(e.select(`domReferenceElement`)).removeEventListener(`mousemove`,b.handler),void 0)}),te=Ct(()=>{UC(b)});return u&&(b.handleCloseOptions=i?.__options),q.useEffect(()=>j,[j]),q.useEffect(()=>{if(!n)return;function e(e){e.open?x.current=!1:(x.current=e.reason===he,j(),b.openChangeTimeout.clear(),b.restTimeout.clear(),b.blockMouseMove=!0,b.restTimeoutPending=!1)}return _.on(`openchange`,e),()=>{_.off(`openchange`,e)}},[n,_,b,j]),q.useEffect(()=>{if(!n)return;function t(t,n=!0){let r=LC(w.current,`close`,b.pointerType);r?b.openChangeTimeout.start(r,()=>{e.setOpen(!1,N(he,t)),v?.events.emit(`floating.closed`,t)}):n&&(b.openChangeTimeout.clear(),e.setOpen(!1,N(he,t)),v?.events.emit(`floating.closed`,t))}let r=c.current??(u?e.select(`domReferenceElement`):null);if(!Ye(r))return;function i(t){if(b.openChangeTimeout.clear(),b.blockMouseMove=!1,a&&!Fn(b.pointerType))return;let n=RC(T.current),r=LC(w.current,`open`,b.pointerType),i=M(t),o=t.currentTarget??null,s=e.select(`domReferenceElement`),c=o;if(Ye(i)&&!e.context.triggerElements.hasElement(i)){for(let t of e.context.triggerElements.elements())if(re(t,i)){c=t;break}}Ye(o)&&Ye(s)&&!e.context.triggerElements.hasElement(o)&&re(o,s)&&(c=s);let l=c!=null&&A(s,c,i),u=e.select(`open`),d=D.current?.()??e.select(`transitionStatus`)===`ending`,f=!u&&d&&x.current,p=!l&&Ye(c)&&Ye(s)&&re(s,c)&&f,m=n>0&&!r,h=l&&(u||f)||p,g=!u||l;if(h){k()&&e.setOpen(!0,N(he,t,c));return}m||(r?b.openChangeTimeout.start(r,()=>{g&&k()&&e.setOpen(!0,N(he,t,c))}):g&&k()&&e.setOpen(!0,N(he,t,c)))}function o(n){if(O()){te();return}j();let r=e.select(`domReferenceElement`),i=h(r);b.restTimeout.clear(),b.restTimeoutPending=!1;let a=g.current.floatingContext??d?.();if(!y(n.relatedTarget,e.context.triggerElements)){if(S.current&&a){e.select(`open`)||b.openChangeTimeout.clear();let r=c.current;b.handler=S.current({...a,tree:v,x:n.clientX,y:n.clientY,onClose(){te(),j(),E.current&&!O()&&r===e.select(`domReferenceElement`)&&t(n,!0)}}),i.addEventListener(`mousemove`,b.handler),b.handler(n);return}(b.pointerType!==`touch`||!re(e.select(`floatingElement`),n.relatedTarget))&&t(n)}}function l(e){re(r,e.relatedTarget)||(b.openChangeTimeout.clear(),b.restTimeout.clear(),b.restTimeoutPending=!1)}let f=m?An(r,`mouseout`,l):void 0;return s?C(An(r,`mousemove`,i,{once:!0}),An(r,`mouseenter`,i),An(r,`mouseleave`,o),f):C(An(r,`mouseenter`,i),An(r,`mouseleave`,o),f)},[j,te,g,w,e,n,S,b,u,A,O,a,s,T,c,v,E,d,D,k,m]),q.useMemo(()=>{if(!n)return;function t(e){b.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=A(i,r,t.target);if(a&&!Fn(b.pointerType))return;if(o&&s&&b.handleCloseOptions?.blockPointerEvents){let t=e.select(`floatingElement`);if(t){let e=b.handleCloseOptions?.getScope?.()??r.ownerDocument.body;WC(b,{scopeElement:e,referenceElement:r,floatingElement:t})}}let c=RC(T.current);if(o&&!s||c===0||!s&&b.restTimeoutPending&&t.movementX**2+t.movementY**2<2)return;b.restTimeout.clear();function l(){if(b.restTimeoutPending=!1,O())return;let t=e.select(`open`);!b.blockMouseMove&&(!t||s)&&k()&&e.setOpen(!0,N(he,n,r))}b.pointerType===`touch`?qC.flushSync(()=>{l()}):s&&o?l():(b.restTimeoutPending=!0,b.restTimeout.start(c,l))}}},[n,b,O,A,a,e,T,k])}var XC=.1,ZC=XC*XC,QC=.5;function $C(e,t,n,r,i,a){return r>=t!=a>=t&&e<=(i-n)*(t-r)/(a-r)+n}function ew(e,t,n,r,i,a,o,s,c,l){let u=!1;return $C(e,t,n,r,i,a)&&(u=!u),$C(e,t,i,a,o,s)&&(u=!u),$C(e,t,o,s,c,l)&&(u=!u),$C(e,t,c,l,n,r)&&(u=!u),u}function tw(e,t,n){return e>=n.x&&e<=n.x+n.width&&t>=n.y&&t<=n.y+n.height}function nw(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 rw(e={}){let{blockPointerEvents:t=!1}=e,n=new xn,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,f=typeof performance<`u`?performance.now():0;function p(e,t){let n=performance.now(),r=n-f;if(u===null||d===null||r===0)return u=e,d=t,f=n,!1;let i=e-u,a=t-d,o=i*i+a*a,s=r*r*ZC;return u=e,d=t,f=n,o<s}function m(){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:f}=r,h=M(r),g=r.type===`mouseleave`,_=re(u,h),v=re(a,h);if(_&&(l=!0,!g))return;if(v&&(l=!1,!g)){l=!0;return}if(g&&Ye(r.relatedTarget)&&re(u,r.relatedTarget))return;function y(){return!!(s&&Ne(s.nodesRef.current,o).length>0)}function b(){y()||m()}if(y())return;let x=a.getBoundingClientRect(),S=u.getBoundingClientRect(),C=e>S.right-S.width/2,w=t>S.bottom-S.height/2,T=S.width>x.width,E=S.height>x.height,ee=(T?x:S).left,D=(T?x:S).right,O=(E?x:S).top,k=(E?x:S).bottom;if(c===`top`&&t>=x.bottom-1||c===`bottom`&&t<=x.top+1||c===`left`&&e>=x.right-1||c===`right`&&e<=x.left+1){b();return}let A=!1;switch(c){case`top`:A=nw(d,f,ee,x.top+1,D,S.bottom-1);break;case`bottom`:A=nw(d,f,ee,S.top+1,D,x.bottom-1);break;case`left`:A=nw(d,f,S.right-1,k,x.left+1,O);break;case`right`:A=nw(d,f,x.right-1,k,S.left+1,O)}if(A)return;if(l&&!tw(d,f,x)){b();return}if(!g&&p(d,f)){b();return}let j=!1;switch(c){case`top`:{let n=T?QC/2:QC*4,r=T||C?e+n:e-n,i=T?e-n:C?e+n:e-n,a=t+QC+1,o=C||T?S.bottom-QC:S.top,s=C?T?S.bottom-QC:S.top:S.bottom-QC;j=ew(d,f,r,a,i,a,S.left,o,S.right,s);break}case`bottom`:{let n=T?QC/2:QC*4,r=T||C?e+n:e-n,i=T?e-n:C?e+n:e-n,a=t-QC,o=C||T?S.top+QC:S.bottom,s=C?T?S.top+QC:S.bottom:S.top+QC;j=ew(d,f,r,a,i,a,S.left,o,S.right,s);break}case`left`:{let n=E?QC/2:QC*4,r=E||w?t+n:t-n,i=E?t-n:w?t+n:t-n,a=e+QC+1,o=w||E?S.right-QC:S.left,s=w?E?S.right-QC:S.left:S.right-QC;j=ew(d,f,o,S.top,s,S.bottom,a,r,a,i);break}case`right`:{let n=E?QC/2:QC*4,r=E||w?t+n:t-n,i=E?t-n:w?t+n:t-n,a=e-QC,o=w||E?S.left+QC:S.right,s=w?E?S.left+QC:S.right:S.left+QC;j=ew(d,f,a,r,a,i,o,S.top,s,S.bottom);break}}j?l||n.start(40,b):b()}};return r.__options={...e,blockPointerEvents:t},r}function iw(e,t,n){let{reference:r,floating:i}=e,a=fb(t),o=pb(t),s=db(o),c=cb(t),l=a===`y`,u=r.x+r.width/2-i.width/2,d=r.y+r.height/2-i.height/2,f=r[s]/2-i[s]/2,p;switch(c){case`top`:p={x:u,y:r.y-i.height};break;case`bottom`:p={x:u,y:r.y+r.height};break;case`right`:p={x:r.x+r.width,y:d};break;case`left`:p={x:r.x-i.width,y:d};break;default:p={x:r.x,y:r.y}}let m=lb(t);return m&&(p[o]+=f*(m===`end`?1:-1)*(n&&l?-1:1)),p}async function aw(e,t){t===void 0&&(t={});let{x:n,y:r,platform:i,rects:a,elements:o,strategy:s}=e,{boundary:c=`clippingAncestors`,rootBoundary:l=`viewport`,elementContext:u=`floating`,altBoundary:d=!1,padding:f=0}=sb(t,e),p=Tb(f),m=o[d?u===`floating`?`reference`:`floating`:u],h=Eb(await i.getClippingRect({element:await(i.isElement==null?void 0:i.isElement(m))??!0?m:m.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(o.floating)),boundary:c,rootBoundary:l,strategy:s})),g=u===`floating`?{x:n,y:r,width:a.floating.width,height:a.floating.height}:a.reference,_=await(i.getOffsetParent==null?void 0:i.getOffsetParent(o.floating)),v=await(i.isElement==null?void 0:i.isElement(_))&&await(i.getScale==null?void 0:i.getScale(_))||{x:1,y:1},y=Eb(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:g,offsetParent:_,strategy:s}):g);return{top:(h.top-y.top+p.top)/v.y,bottom:(y.bottom-h.bottom+p.bottom)/v.y,left:(h.left-y.left+p.left)/v.x,right:(y.right-h.right+p.right)/v.x}}var ow=50,sw=async(e,t,n)=>{let{placement:r=`bottom`,strategy:i=`absolute`,middleware:a=[],platform:o}=n,s=o.detectOverflow?o:{...o,detectOverflow:aw},c=await(o.isRTL==null?void 0:o.isRTL(t)),l=await o.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:d}=iw(l,r,c),f=r,p=0,m={};for(let n=0;n<a.length;n++){let h=a[n];if(!h)continue;let{name:g,fn:_}=h,{x:v,y,data:b,reset:x}=await _({x:u,y:d,initialPlacement:r,placement:f,strategy:i,middlewareData:m,rects:l,platform:s,elements:{reference:e,floating:t}});u=v??u,d=y??d,m[g]={...m[g],...b},x&&p<ow&&(p++,typeof x==`object`&&(x.placement&&(f=x.placement),x.rects&&(l=x.rects===!0?await o.getElementRects({reference:e,floating:t,strategy:i}):x.rects),{x:u,y:d}=iw(l,f,c)),n=-1)}return{x:u,y:d,placement:f,strategy:i,middlewareData:m}},cw=function(e){return e===void 0&&(e={}),{name:`flip`,options:e,async fn(t){var n;let{placement:r,middlewareData:i,rects:a,initialPlacement:o,platform:s,elements:c}=t,{mainAxis:l=!0,crossAxis:u=!0,fallbackPlacements:d,fallbackStrategy:f=`bestFit`,fallbackAxisSideDirection:p=`none`,flipAlignment:m=!0,...h}=sb(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};let g=cb(r),_=fb(o),v=cb(o)===o,y=await(s.isRTL==null?void 0:s.isRTL(c.floating)),b=d||(v||!m?[Cb(o)]:hb(o)),x=p!==`none`;!d&&x&&b.push(...Sb(o,m,p,y));let S=[o,...b],C=await s.detectOverflow(t,h),w=[],T=i.flip?.overflows||[];if(l&&w.push(C[g]),u){let e=mb(r,a,y);w.push(C[e[0]],C[e[1]])}if(T=[...T,{placement:r,overflows:w}],!w.every(e=>e<=0)){let e=(i.flip?.index||0)+1,t=S[e];if(t&&(u!==`alignment`||_===fb(t)||T.every(e=>fb(e.placement)!==_||e.overflows[0]>0)))return{data:{index:e,overflows:T},reset:{placement:t}};let n=T.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0]?.placement;if(!n)switch(f){case`bestFit`:{let e=T.filter(e=>{if(x){let t=fb(e.placement);return t===_||t===`y`}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0]?.[0];e&&(n=e);break}case`initialPlacement`:n=o}if(r!==n)return{reset:{placement:n}}}return{}}}},lw=new Set([`left`,`top`]);async function uw(e,t){let{placement:n,platform:r,elements:i}=e,a=await(r.isRTL==null?void 0:r.isRTL(i.floating)),o=cb(n),s=lb(n),c=fb(n)===`y`,l=lw.has(o)?-1:1,u=a&&c?-1:1,d=sb(t,e),{mainAxis:f,crossAxis:p,alignmentAxis:m}=typeof d==`number`?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return s&&typeof m==`number`&&(p=s===`end`?m*-1:m),c?{x:p*u,y:f*l}:{x:f*l,y:p*u}}var dw=function(e){return e===void 0&&(e=0),{name:`offset`,options:e,async fn(t){var n;let{x:r,y:i,placement:a,middlewareData:o}=t,s=await uw(t,e);return a===o.offset?.placement&&(n=o.arrow)!=null&&n.alignmentOffset?{}:{x:r+s.x,y:i+s.y,data:{...s,placement:a}}}}},fw=function(e){return e===void 0&&(e={}),{name:`shift`,options:e,async fn(t){let{x:n,y:r,placement:i,platform:a}=t,{mainAxis:o=!0,crossAxis:s=!1,limiter:c={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...l}=sb(e,t),u={x:n,y:r},d=await a.detectOverflow(t,l),f=fb(i),p=ub(f),m=u[p],h=u[f],g=(e,t)=>ob(t+d[e===`y`?`top`:`left`],t,t-d[e===`y`?`bottom`:`right`]);o&&(m=g(p,m)),s&&(h=g(f,h));let _=c.fn({...t,[p]:m,[f]:h});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[p]:o,[f]:s}}}}}},pw=function(e){return e===void 0&&(e={}),{options:e,fn(t){let{x:n,y:r,placement:i,rects:a,middlewareData:o}=t,{offset:s=0,mainAxis:c=!0,crossAxis:l=!0}=sb(e,t),u={x:n,y:r},d=fb(i),f=ub(d),p=u[f],m=u[d],h=sb(s,t),g=typeof h==`number`?{mainAxis:h,crossAxis:0}:{mainAxis:h.mainAxis??0,crossAxis:h.crossAxis??0};if(c){let e=f===`y`?`height`:`width`,t=a.reference[f]-a.floating[e]+g.mainAxis,n=a.reference[f]+a.reference[e]-g.mainAxis;p<t?p=t:p>n&&(p=n)}if(l){let e=f===`y`?`width`:`height`,t=lw.has(cb(i)),n=a.reference[d]-a.floating[e]+(t&&o.offset?.[d]||0)+(t?0:g.crossAxis),r=a.reference[d]+a.reference[e]+(t?0:o.offset?.[d]||0)-(t?g.crossAxis:0);m<n?m=n:m>r&&(m=r)}return{[f]:p,[d]:m}}}},mw=function(e){return e===void 0&&(e={}),{name:`size`,options:e,async fn(t){let{placement:n,rects:r,platform:i,elements:a}=t,{apply:o=()=>{},...s}=sb(e,t),c=await i.detectOverflow(t,s),l=cb(n),u=lb(n),d=fb(n)===`y`,{width:f,height:p}=r.floating,m,h;l===`top`||l===`bottom`?(m=l,h=u===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?`start`:`end`)?`left`:`right`):(h=l,m=u===`end`?`top`:`bottom`);let g=p-c.top-c.bottom,_=f-c.left-c.right,v=eb(p-c[m],g),y=eb(f-c[h],_),b=t.middlewareData.shift,x=!b,S=v,C=y;b!=null&&b.enabled.x&&(C=_),b!=null&&b.enabled.y&&(S=g),x&&!u&&(d?C=f-2*tb(c.left,c.right):S=p-2*tb(c.top,c.bottom)),await o({...t,availableWidth:C,availableHeight:S});let w=await i.getDimensions(a.floating);return f!==w.width||p!==w.height?{reset:{rects:!0}}:{}}}};function hw(e){let t=Gn(e),n=parseFloat(t.width)||0,r=parseFloat(t.height)||0,i=qe(e),a=i?e.offsetWidth:n,o=i?e.offsetHeight:r,s=nb(n)!==a||nb(r)!==o;return s&&(n=a,r=o),{width:n,height:r,$:s}}function gw(e){return Ye(e)?e:e.contextElement}function _w(e){let t=gw(e);if(!qe(t))return ib(1);let n=t.getBoundingClientRect(),{width:r,height:i,$:a}=hw(t),o=(a?nb(n.width):n.width)/r,s=(a?nb(n.height):n.height)/i;return(!o||!Number.isFinite(o))&&(o=1),(!s||!Number.isFinite(s))&&(s=1),{x:o,y:s}}var vw=ib(0);function yw(e){let t=pn(e);return!Tn()||!t.visualViewport?vw:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function bw(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===pn(e)}function xw(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);let i=e.getBoundingClientRect(),a=gw(e),o=ib(1);t&&(r?Ye(r)&&(o=_w(r)):o=_w(e));let s=bw(a,n,r)?yw(a):ib(0),c=(i.left+s.x)/o.x,l=(i.top+s.y)/o.y,u=i.width/o.x,d=i.height/o.y;if(a&&r){let e=pn(a),t=Ye(r)?pn(r):r,n=e,i=j(n);for(;i&&t!==n;){let e=_w(i),t=i.getBoundingClientRect(),r=Gn(i),a=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,o=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;c*=e.x,l*=e.y,u*=e.x,d*=e.y,c+=a,l+=o,n=pn(i),i=j(n)}}return Eb({width:u,height:d,x:c,y:l})}function Sw(e,t){let n=We(e).scrollLeft;return t?t.left+n:xw(Be(e)).left+n}function Cw(e,t){let n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-Sw(e,n),y:n.top+t.scrollTop}}function ww(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e,a=i===`fixed`,o=Be(r),s=t?yt(t.floating):!1;if(r===o||s&&a)return n;let c={scrollLeft:0,scrollTop:0},l=ib(1),u=ib(0),d=qe(r);if((d||!a)&&((Le(r)!==`body`||Se(o))&&(c=We(r)),d)){let e=xw(r);l=_w(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}let f=o&&!d&&!a?Cw(o,c):ib(0);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+u.x+f.x,y:n.y*l.y-c.scrollTop*l.y+u.y+f.y}}function Tw(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function Ew(e){let t=We(e),n=e.ownerDocument.body,r=tb(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=tb(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight),a=-t.scrollLeft+Sw(e),o=-t.scrollTop;return Gn(n).direction===`rtl`&&(a+=tb(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:a,y:o}}var Dw=25;function Ow(e,t,n){n===void 0&&(n=`viewport`);let r=n===`layoutViewport`,i=pn(e),a=Be(e),o=i.visualViewport,s=a.clientWidth,c=a.clientHeight,l=0,u=0;if(o){let e=!Tn()||t===`fixed`;r?e||(l=-o.offsetLeft,u=-o.offsetTop):(s=o.width,c=o.height,e&&(l=o.offsetLeft,u=o.offsetTop))}if(Sw(a)<=0){let e=a.ownerDocument,t=e.body,n=getComputedStyle(t),r=e.compatMode===`CSS1Compat`&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(a.clientWidth-t.clientWidth-r),o=getComputedStyle(a).scrollbarGutter===`stable both-edges`?i/2:i;o<=Dw&&(s-=o)}return{width:s,height:c,x:l,y:u}}function kw(e,t){let n=xw(e,!0,t===`fixed`),r=n.top+e.clientTop,i=n.left+e.clientLeft,a=_w(e);return{width:e.clientWidth*a.x,height:e.clientHeight*a.y,x:i*a.x,y:r*a.y}}function Aw(e,t,n){let r;if(t===`viewport`||t===`layoutViewport`)r=Ow(e,n,t);else if(t===`document`)r=Ew(Be(e));else if(Ye(t))r=kw(t,n);else{let n=yw(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return Eb(r)}function jw(e,t){let n=t.get(e);if(n)return n;let r=O(e,[],!1).filter(e=>Ye(e)&&Le(e)!==`body`),i=null,a=Gn(e).position===`fixed`,o=a?ce(e):e;for(;Ye(o)&&!Ze(o);){let e=Gn(o),t=oe(o),n=i?i.position:a?`fixed`:``;!t&&(n===`fixed`||n===`absolute`&&e.position===`static`)?r=r.filter(e=>e!==o):i=e,o=ce(o)}return t.set(e,r),r}function Mw(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e,a=[...n===`clippingAncestors`?yt(t)?[]:jw(t,this._c):[].concat(n),r],o=Aw(t,a[0],i),s=o.top,c=o.right,l=o.bottom,u=o.left;for(let e=1;e<a.length;e++){let n=Aw(t,a[e],i);s=tb(n.top,s),c=eb(n.right,c),l=eb(n.bottom,l),u=tb(n.left,u)}return{width:c-u,height:l-s,x:u,y:s}}function Nw(e){let{width:t,height:n}=hw(e);return{width:t,height:n}}function Pw(e,t,n){let r=qe(t),i=Be(t),a=n===`fixed`,o=xw(e,!0,a,t),s={scrollLeft:0,scrollTop:0},c=ib(0);if((r||!a)&&((Le(t)!==`body`||Se(i))&&(s=We(t)),r)){let e=xw(t,!0,a,t);c.x=e.x+t.clientLeft,c.y=e.y+t.clientTop}!r&&i&&(c.x=Sw(i));let l=i&&!r&&!a?Cw(i,s):ib(0);return{x:o.left+s.scrollLeft-c.x-l.x,y:o.top+s.scrollTop-c.y-l.y,width:o.width,height:o.height}}function Fw(e){return Gn(e).position===`static`}function Iw(e,t){if(!qe(e)||Gn(e).position===`fixed`)return null;if(t)return t(e);let n=e.offsetParent;return Be(e)===n&&(n=n.ownerDocument.body),n}function Lw(e,t){let n=pn(e);if(yt(e))return n;if(!qe(e)){let t=ce(e);for(;t&&!Ze(t);){if(Ye(t)&&!Fw(t))return t;t=ce(t)}return n}let i=Iw(e,t);for(;i&&r(i)&&Fw(i);)i=Iw(i,t);return i&&Ze(i)&&Fw(i)&&!oe(i)?n:i||u(e)||n}var Rw=async function(e){let t=this.getOffsetParent||Lw,n=this.getDimensions,r=await n(e.floating);return{reference:Pw(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function zw(e){return Gn(e).direction===`rtl`}var Bw={convertOffsetParentRelativeRectToViewportRelativeRect:ww,getDocumentElement:Be,getClippingRect:Mw,getOffsetParent:Lw,getElementRects:Rw,getClientRects:Tw,getDimensions:Nw,getScale:_w,isElement:Ye,isRTL:zw};function Vw(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Hw(e,t,n){let r=null,i,a=Be(e);function o(){var e;clearTimeout(i),(e=r)==null||e.disconnect(),r=null}function s(n,c){n===void 0&&(n=!1),c===void 0&&(c=1),o();let l=e.getBoundingClientRect(),{left:u,top:d,width:f,height:p}=l;if(n||t(),!f||!p)return;let m=rb(d),h=rb(a.clientWidth-(u+f)),g=rb(a.clientHeight-(d+p)),_=rb(u),v={rootMargin:-m+`px `+-h+`px `+-g+`px `+-_+`px`,threshold:tb(0,eb(1,c))||1},y=!0;function b(t){let n=t[0].intersectionRatio;if(!Vw(l,e.getBoundingClientRect()))return s();if(n!==c){if(!y)return s();n?s(!1,n):i=setTimeout(()=>{s(!1,1e-7)},1e3)}y=!1}try{r=new IntersectionObserver(b,{...v,root:a.ownerDocument})}catch{r=new IntersectionObserver(b,v)}r.observe(e)}let c=pn(e),l=()=>s(n);return c.addEventListener(`resize`,l),s(!0),()=>{c.removeEventListener(`resize`,l),o()}}function Uw(e,t,n,r){r===void 0&&(r={});let{ancestorScroll:i=!0,ancestorResize:a=!0,elementResize:o=typeof ResizeObserver==`function`,layoutShift:s=typeof IntersectionObserver==`function`,animationFrame:c=!1}=r,l=gw(e),u=i||a?[...l?O(l):[],...t?O(t):[]]:[];u.forEach(e=>{i&&e.addEventListener(`scroll`,n),a&&e.addEventListener(`resize`,n)});let d=l&&s?Hw(l,n,a):null,f=-1,p=null;o&&(p=new ResizeObserver(e=>{let[r]=e;r&&r.target===l&&p&&t&&(p.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var e;(e=p)==null||e.observe(t)})),n()}),l&&!c&&p.observe(l),t&&p.observe(t));let m,h=c?xw(e):null;c&&g();function g(){let t=xw(e);h&&!Vw(h,t)&&n(),h=t,m=requestAnimationFrame(g)}return n(),()=>{var e;u.forEach(e=>{i&&e.removeEventListener(`scroll`,n),a&&e.removeEventListener(`resize`,n)}),d?.(),(e=p)==null||e.disconnect(),p=null,c&&cancelAnimationFrame(m)}}var Ww=dw,Gw=fw,Kw=cw,qw=mw,Jw=pw,Yw=(e,t,n)=>{let r=new Map,i=n??{},a={...Bw,...i.platform,_c:r};return sw(e,t,{...i,platform:a})},Xw=typeof document<`u`?q.useLayoutEffect:function(){};function Zw(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e==`function`&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e==`object`){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Zw(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){let n=i[r];if(!(n===`_owner`&&e.$$typeof)&&!Zw(e[n],t[n]))return!1}return!0}return e!==e&&t!==t}function Qw(e){return typeof window>`u`?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function $w(e,t){let n=Qw(e);return Math.round(t*n)/n}function eT(e){let t=q.useRef(e);return Xw(()=>{t.current=e}),t}function tT(e){e===void 0&&(e={});let{placement:t=`bottom`,strategy:n=`absolute`,middleware:r=[],platform:i,elements:{reference:a,floating:o}={},transform:s=!0,whileElementsMounted:c,open:l}=e,[u,d]=q.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,p]=q.useState(r);Zw(f,r)||p(r);let[m,h]=q.useState(null),[g,_]=q.useState(null),v=q.useCallback(e=>{e!==S.current&&(S.current=e,h(e))},[]),y=q.useCallback(e=>{e!==C.current&&(C.current=e,_(e))},[]),b=a||m,x=o||g,S=q.useRef(null),C=q.useRef(null),w=q.useRef(u),T=c!=null,E=eT(c),ee=eT(i),D=eT(l),O=q.useCallback(()=>{if(!S.current||!C.current)return;let e={placement:t,strategy:n,middleware:f};ee.current&&(e.platform=ee.current),Yw(S.current,C.current,e).then(e=>{let t={...e,isPositioned:D.current!==!1};k.current&&!Zw(w.current,t)&&(w.current=t,qC.flushSync(()=>{d(t)}))})},[f,t,n,ee,D]);Xw(()=>{l===!1&&w.current.isPositioned&&(w.current.isPositioned=!1,d(e=>({...e,isPositioned:!1})))},[l]);let k=q.useRef(!1);Xw(()=>(k.current=!0,()=>{k.current=!1}),[]),Xw(()=>{if(b&&(S.current=b),x&&(C.current=x),b&&x){if(E.current)return E.current(b,x,O);O()}},[b,x,O,E,T]);let A=q.useMemo(()=>({reference:S,floating:C,setReference:v,setFloating:y}),[v,y]),j=q.useMemo(()=>({reference:b,floating:x}),[b,x]),te=q.useMemo(()=>{let e={position:n,left:0,top:0};if(!j.floating)return e;let t=$w(j.floating,u.x),r=$w(j.floating,u.y);return s?{...e,transform:`translate(`+t+`px, `+r+`px)`,...Qw(j.floating)>=1.5&&{willChange:`transform`}}:{position:n,left:t,top:r}},[n,s,j.floating,u.x,u.y]);return q.useMemo(()=>({...u,update:O,refs:A,elements:j,floatingStyles:te}),[u,O,A,j,te])}var nT=(e,t)=>{let n=Ww(e);return{name:n.name,fn:n.fn,options:[e,t]}},rT=(e,t)=>{let n=Gw(e);return{name:n.name,fn:n.fn,options:[e,t]}},iT=(e,t)=>({fn:Jw(e).fn,options:[e,t]}),aT=(e,t)=>{let n=Kw(e);return{name:n.name,fn:n.fn,options:[e,t]}},oT=(e,t)=>{let n=qw(e);return{name:n.name,fn:n.fn,options:[e,t]}},sT=je(`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`}]]),cT=je(`Eye`,[[`path`,{d:`M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0`,key:`1nclc0`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),lT=je(`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`}]]),uT=je(`Pencil`,[[`path`,{d:`M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z`,key:`1a8usu`}],[`path`,{d:`m15 5 4 4`,key:`1mk7zo`}]]),dT=je(`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`}]]),fT=je(`SquarePen`,[[`path`,{d:`M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7`,key:`1m0v6g`}],[`path`,{d:`M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z`,key:`ohrbg2`}]]),pT=je(`Trash2`,[[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6`,key:`4alrt4`}],[`path`,{d:`M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2`,key:`v07s0e`}],[`line`,{x1:`10`,x2:`10`,y1:`11`,y2:`17`,key:`1uufr5`}],[`line`,{x1:`14`,x2:`14`,y1:`11`,y2:`17`,key:`xtxkd`}]]);function mT(e){let t=2166136261;for(let n of e)t^=n.codePointAt(0)??0,t=Math.imul(t,16777619)>>>0;return t}var hT=[`primary`,`secondary`,`accent`,`info`,`success`,`warning`];function gT(e){return hT[mT(e)%hT.length]??`primary`}var _T=(0,q.forwardRef)(function({className:e,name:t,seed:n,size:r=`default`,subject:i=`actor`,variant:a=`initial`,...o},s){let c=Array.from(t.trim())[0]?.toLocaleUpperCase()??`?`;return(0,Y.jsx)(`span`,{"aria-hidden":`true`,...o,className:E(`caps-monogram`,e),"data-subject":i===`actor`?void 0:i,"data-size":r==="default"?void 0:r,"data-tone":gT(n??t),ref:s,children:a===`specimen`?(0,Y.jsx)(`svg`,{viewBox:`0 0 48 48`,width:`80%`,height:`80%`,fill:`none`,"aria-hidden":`true`,children:(0,Y.jsxs)(`g`,{transform:`rotate(${String((n??t).split(``).reduce((e,t)=>e+(t.codePointAt(0)??0),0)%360)} 24 24)`,stroke:`currentColor`,strokeWidth:`1.5`,children:[Array.from({length:20},(e,t)=>(0,Y.jsx)(`path`,{d:`M24 19 Q19 12 24 5`,transform:`rotate(${String(t*18)} 24 24)`},t)),(0,Y.jsx)(`circle`,{cx:`24`,cy:`24`,r:`5`})]})}):c})}),vT=(0,q.createContext)(null),yT=(0,q.createContext)(void 0);function bT(e){let t=(0,q.useContext)(yT);return e??t}var xT=(0,q.forwardRef)(function({service:e,src:t,activity:n,expression:r,appearance:i,renderStyle:a,performance:o,timeMs:s,paused:c=!1,onState:l,...u},d){let f=bT(s),p=f!==void 0,m=(0,q.useContext)(vT),h=e??m;if(!h)throw Error(`Sprite needs a configured SpriteProvider or service`);let g=(0,q.useRef)(null),_=(0,q.useRef)(null),v=(0,q.useRef)(l);return v.current=l,(0,q.useImperativeHandle)(d,()=>{if(!g.current)throw Error(`Sprite host is not mounted`);return g.current}),(0,q.useEffect)(()=>{if(!g.current)return;let e=h.mount(g.current),t=e.subscribe(e=>{g.current&&(g.current.dataset.spriteStatus=e.status),v.current?.(e)});return _.current=e,()=>{t(),e.dispose().catch(e=>{console.error(`Sprite cleanup failed`,e)}),_.current=null}},[h]),(0,q.useEffect)(()=>{let e=_.current;if(!e)return;let s={src:t};n!==void 0&&(s={...s,activity:n}),r!==void 0&&(s={...s,expression:r}),i!==void 0&&(s={...s,appearance:i}),a!==void 0&&(s={...s,renderStyle:a}),o!==void 0&&(s={...s,performance:o}),f!==void 0&&(s={...s,timeMs:f}),e.set(s)},[h,t,n,r,i,a,o,f]),(0,q.useEffect)(()=>{_.current?.pause(c||p)},[h,c,p]),(0,Y.jsx)(`div`,{...u,ref:g})});function ST(e){return{src:{local:e.character},appearance:e.appearance,expression:e.expression,renderStyle:e.renderStyle}}function CT(e){for(let[t,n]of Object.entries({maxBytes:e.maxBytes,maxTotalBytes:e.maxTotalBytes,maxRequests:e.maxRequests}))if(!Number.isSafeInteger(n)||n<=0)throw Error(`Avatar ${t} must be a positive safe integer`);let t=new Set(e.allowedOrigins.map(e=>new URL(e).origin)),n=e.fetch??globalThis.fetch;return()=>{let r=0,i=0;return async(a,o,s=e.baseURL)=>{let c=new URL(a,s);if(![`http:`,`https:`].includes(c.protocol)||!t.has(c.origin)||c.username||c.password)throw Error(`Avatar asset is not admitted: ${c.origin}`);if(i+=1,i>e.maxRequests)throw Error(`Avatar asset request limit reached`);let l=await n(c.href,{signal:o,redirect:`error`});if(!l.ok)throw Error(`Avatar asset request failed: ${String(l.status)}`);let u=Number(l.headers.get(`content-length`));if(u>e.maxBytes||u>e.maxTotalBytes-r)throw await l.body?.cancel(),Error(`Avatar asset exceeds the byte limit`);let d=l.body?.getReader();if(!d)throw Error(`Avatar asset has no response body`);let f=[],p=0;try{for(;;){o.throwIfAborted();let t=await d.read();if(t.done)break;if(p+=t.value.byteLength,p>e.maxBytes)throw Error(`Avatar asset exceeds the byte limit`);if(t.value.byteLength>e.maxTotalBytes-r)throw Error(`Avatar selection exceeds the total byte limit`);r+=t.value.byteLength,f.push(t.value)}}catch(e){let t=await d.cancel().then(()=>({kind:`cancelled`}),e=>({kind:`failed`,error:e instanceof Error?e:Error(String(e))}));throw t.kind===`failed`?AggregateError([e,t.error],`Avatar asset read and cancellation failed`,{cause:e}):e}finally{d.releaseLock()}let m=new Uint8Array(p),h=0;for(let e of f)m.set(e,h),h+=e.byteLength;return{url:c.href,bytes:m,contentType:l.headers.get(`content-type`)??`application/octet-stream`}}}}var wT=(e,t)=>{let n=po.safeParse(e);return n.success?{kind:`local`,key:n.data.local}:{kind:`remote`,url:new URL(P().parse(e),t).href}},TT=e=>e instanceof Error?e:Error(String(e),{cause:e}),ET=e=>Mi(e)?TT(uo(e.cause)):Error(`Unexpected Sprite success`);function DT(e){let t=e.maxPixels??4194304;if(!Number.isSafeInteger(t)||t<=0)throw Error(`Sprite pixel limit must be a positive safe integer`);let n=e.assets??{baseURL:`https://sprite.invalid/`,allowedOrigins:[],maxBytes:1,maxTotalBytes:1,maxRequests:1},r=CT(n),i=new WeakSet,a=new WeakMap,o=e=>{let t=wT(e,n.baseURL);return t.kind===`remote`?t.url:`local:${t.key}`};return{mount(s){if(i.has(s))throw Error(`A Sprite already owns this target`);i.add(s);let c=ni(ka()),l=new Set,u={status:`empty`},d,f,p=0,m=!1,h,g,_,v=!1,y=!1,b=s.ownerDocument.defaultView?.matchMedia(`(prefers-reduced-motion: reduce)`),x=e=>{if(!(v&&e.status!==`destroyed`)){u=e;for(let t of l)try{t(e)}catch(e){console.error(`Sprite state observer failed`,e)}}},S=e=>{f?.controller.abort(),f?.holder.remove(),x({status:`error`,error:e}),T().catch(t=>{x({status:`error`,error:AggregateError([e,t],`Avatar failed and cleanup also failed`)})})},C=Zh(s),w=()=>{let e=y||s.ownerDocument.hidden||b?.matches===!0;C.still(e);try{f?.native?.pause(e)}catch(e){S(TT(e))}};ni(qa(c,Ur(()=>{s.ownerDocument.removeEventListener(`visibilitychange`,w),b?.removeEventListener(`change`,w),C.dispose()}))),s.ownerDocument.addEventListener(`visibilitychange`,w),b?.addEventListener(`change`,w);let T=async()=>{if(g)return g;let e=f;if(!e)return;f=void 0,e.controller.abort(),e.holder.remove();let t=Kr(Ra(e.scope,Na)).then(e=>{if(Mi(e))throw ET(e)});g=t;try{await t}finally{g===t&&(g=void 0)}},E=e=>{let t=e.native,n=e.document,r=d;if(!t||!n||!r||f!==e)return;let i=r.activity??`idle`,a=r.expression??t.expressions[0]??null,o,s;try{o=mo(n.controls,r.appearance),s=Th.parse(r.renderStyle??`plain`)}catch(e){let t=TT(e);u.status===`ready`?u.updateError?.message!==t.message&&x({...u,updateError:t}):S(t);return}let c={requestedActivity:i,requestedExpression:a,activity:t.activities.includes(i)?i:`idle`,expression:a!==null&&t.expressions.includes(a)?a:t.expressions[0]??null,appearance:o,renderStyle:s,fallback:!t.activities.includes(i)||a!==null&&!t.expressions.includes(a)},l=r.performance===void 0?c:{...c,performance:r.performance};r.timeMs!==void 0&&(l={...l,timeMs:r.timeMs});let p=JSON.stringify([l.activity,l.expression,l.appearance,l.timeMs]);if(C.set(s,e.holder),p!==e.appliedKey||r.performance!==e.appliedPerformance||u.status!==`ready`||u.presentation.renderStyle!==s||u.updateError!==void 0||u.presentation.requestedActivity!==i||u.presentation.requestedExpression!==a)try{if((p!==e.appliedKey||r.performance!==e.appliedPerformance)&&t.set(l),e.appliedKey=p,e.appliedPerformance=r.performance,w(),f===e){let t={status:`ready`,document:n,presentation:l};x(e.progress===void 0?t:{...t,progress:e.progress})}}catch(e){S(TT(e))}},ee=async(i,a,o)=>{let c=r(),l=ni(ka()),d=new AbortController,m=s.ownerDocument.createElement(`div`);m.style.cssText=`width:100%;height:100%;position:relative`;let h={key:a,scope:l,controller:d,holder:m};f=h,ni(qa(l,Ur(()=>{m.remove()}))),s.append(m);let g=qr(function*(){let r,a,o=n.baseURL,s=wT(i.src,n.baseURL);if(s.kind===`remote`){let t=yield*jr({try:()=>c(s.url,d.signal),catch:TT});o=t.url,r=fo.parse(JSON.parse(new TextDecoder().decode(t.bytes)));let n=e.renderers&&Object.hasOwn(e.renderers,r.renderer)?e.renderers[r.renderer]:void 0;if(!n)throw Error(`Renderer is not installed: ${r.renderer}`);a=(yield*jr({try:n,catch:TT})).default}else{let t=s.key,n=e.characters&&Object.hasOwn(e.characters,t)?e.characters[t]:void 0;if(!n)throw Error(`Character is not installed: ${t}`);let i=yield*jr({try:n,catch:TT});r=fo.parse(i.document),a=i.render}d.signal.throwIfAborted();let l=yield*a({target:m,document:r,signal:d.signal,maxPixels:t,reportError:e=>{f===h&&!d.signal.aborted&&S(e)},reportProgress:e=>{f!==h||d.signal.aborted||(h.progress=e,u.status===`ready`&&x({...u,progress:e}))},assetURL:e=>qr(function*(){let t=yield*jr({try:()=>c(e,d.signal,o),catch:TT});return yield*di(Ur(()=>URL.createObjectURL(new Blob([t.bytes],{type:t.contentType}))),e=>Ur(()=>{URL.revokeObjectURL(e)}))})});if(!l.activities.includes(`idle`))throw Error(`Character has no idle fallback`);return l.pause(!0),{native:l,document:r}}).pipe(no(l)),_=await Kr(g,{signal:d.signal});if(!(v||o!==p||f!==h)){if(Mi(_)){let e=ET(_);try{await T(),x({status:`error`,error:e})}catch(t){x({status:`error`,error:AggregateError([e,t],`Avatar load and cleanup failed`)})}return}h.native=_.value.native,h.document=_.value.document,E(h)}},D=async()=>{let e=e=>v||e!==p;for(;m&&!v;){m=!1;let t=p;if(await T(),e(t)||!d)continue;let n=await a.get(s);if(n?.kind===`failed`)throw n.error;e(t)||(x({status:`loading`}),await ee(d,o(d.src),t))}},O=()=>{m=!0,f?.controller.abort(),f?.holder.remove(),!h&&(h=D().catch(e=>{x({status:`error`,error:TT(e)})}).finally(()=>{h=void 0,m&&!v&&O()}))};return{get state(){return u},subscribe(e){return l.add(e),()=>l.delete(e)},set(e){if(v)throw Error(`Sprite is destroyed`);d=e;let t=o(e.src);f?.key===t&&u.status===`ready`?E(f):(f?.key!==t||u.status===`error`)&&(p+=1,O())},pause(e){if(v)throw Error(`Sprite is destroyed`);y=e,w()},dispose(){return _||(v=!0,p+=1,i.delete(s),f?.controller.abort(),f?.holder.remove(),x({status:`destroyed`}),_=(async()=>{await h,await T();let e=await Kr(Ra(c,Na));if(Mi(e))throw ET(e)})(),a.set(s,_.then(()=>({kind:`closed`}),e=>({kind:`failed`,error:TT(e)}))),_)}}}}}var OT=DT({characters:{mushroom:async()=>(await _o(async()=>{let{default:e}=await import(`./mushroom-Bm99-6Un.js`);return{default:e}},__vite__mapDeps([5,6,2,7,1,8]))).default,cat:async()=>(await _o(async()=>{let{default:e}=await import(`./cat-C7kQLCMI.js`);return{default:e}},__vite__mapDeps([9,6,2,7,1,8,10]))).default,burger:async()=>(await _o(async()=>{let{default:e}=await import(`./burger-DiSLBppO.js`);return{default:e}},__vite__mapDeps([11,6,2,7,1,8,10]))).default}}),kT=(0,q.memo)(function({activity:e=`idle`,avatar:t,className:n,name:r,size:i=24,timeMs:a}){let o=bT(a),[s,c]=(0,q.useState)(!1),l=(0,q.useMemo)(()=>ST(t),[t]);return(0,Y.jsxs)(`span`,{"aria-hidden":`true`,className:`relative inline-block shrink-0 ${n??``}`,"data-agent-head":s?`ready`:`loading`,style:{height:i,width:i},children:[s?null:(0,Y.jsx)(_T,{className:`absolute inset-0`,name:r,seed:r}),(0,Y.jsx)(xT,{activity:e,...o===void 0?{}:{timeMs:o},appearance:l.appearance,className:`absolute inset-0`,expression:l.expression,onState:e=>{c(e.status===`ready`)},paused:o!==void 0||e===`idle`,renderStyle:l.renderStyle,service:OT,src:l.src})]})}),AT=(0,q.memo)(function({avatar:e,className:t=`h-12 w-12 shrink-0`,service:n=OT,state:r}){let i=(0,q.useMemo)(()=>e?ST(e):void 0,[e]);return(0,Y.jsx)(xT,{"aria-hidden":`true`,className:t,service:n,src:i?.src??{local:`mushroom`},...i?{appearance:i.appearance,renderStyle:i.renderStyle}:{},...r})}),jT={needs_you:`Waiting for you`,running:`Working`,errored:`Failed`,done:`Done`},MT={needs_you:0,errored_unseen:1,running:2,recent:3};function NT(e){return e===`running`||e===`needs_you`}function PT(e,t){return e!==void 0&&(t===void 0||e>t)}function FT(e,t){switch(e){case`needs_you`:return`needs_you`;case`running`:return`running`;case`errored`:return t?`errored_unseen`:`recent`;case`done`:return`recent`}}function IT(e,t){return MT[e.tier]-MT[t.tier]||(t.settledAt??t.createdAt)-(e.settledAt??e.createdAt)||e.agentId.localeCompare(t.agentId)||e.sessionId.localeCompare(t.sessionId)}var LT=[`Needs you`,`Working`,`Ready`,`Finished`];function RT(e){return e.tier===`running`?`Working`:e.shelf===`active`?`Needs you`:e.ready?`Ready`:`Finished`}function zT(e){return{key:GT(e.agentId,e.sessionId),shelf:RT(e),attention:e.tier===`needs_you`||e.tier===`errored_unseen`?`${e.tier}:${String(e.settledAt??e.createdAt)}`:null}}function BT(e,t,n){let r=new Map(t.map(e=>[GT(e.agentId,e.sessionId),e]));if(e!==null&&e.length>0&&n.held)return e;let i=[...t].sort((e,t)=>(t.settledAt??t.createdAt)-(e.settledAt??e.createdAt)||e.agentId.localeCompare(t.agentId)||e.sessionId.localeCompare(t.sessionId)),a=new Map(e?.map(e=>[e.key,e])),o=i.map(zT).filter(e=>{let t=a.get(e.key);return t===void 0||e.key!==n.openKey&&e.attention!==null&&e.attention!==t.attention}),s=new Set(o.map(e=>e.key)),c=a.get(n.openKey??``),l=c===void 0?-1:(e??[]).filter(e=>e.shelf===c.shelf).findIndex(e=>e.key===c.key),u=LT.flatMap(t=>{let a;a=e===null||n.reorder?i.map(zT).filter(e=>e.shelf===t):[...o.filter(e=>e.shelf===t),...e.filter(e=>e.shelf===t&&!s.has(e.key)).flatMap(e=>{let t=r.get(e.key);return t===void 0?[]:[{...e,attention:zT(t).attention}]})];let u=c===void 0?void 0:r.get(c.key);return c!==void 0&&u!==void 0&&(a=a.filter(e=>e.key!==c.key),c.shelf===t&&a.splice(Math.min(l,a.length),0,{...c,attention:zT(u).attention})),a});return e!==null&&u.length===e.length&&u.every((t,n)=>t.key===e[n]?.key&&t.shelf===e[n]?.shelf&&t.attention===e[n]?.attention)?e:u}function VT(e){switch(e.kind){case`idle`:return`done`;case`waiting_for_you`:return`needs_you`;case`error`:return`errored`;default:return`running`}}function HT(e,t,n=null,r){let i=new Set(e.map(e=>e.agentId));return UT(t.filter(e=>!(`kind`in e)&&i.has(e.agentId)&&(n===null||e.agentId===n)),r)}function UT(e,t){let n=[],r=[];for(let i of e){if(`kind`in i)continue;if(i.state===`unavailable`){r.push({agentId:i.agentId,sessionId:i.sessionId});continue}let e=PT(i.settledAt,i.visitedAt),a=t?.agentId===i.agentId&&t.sessionId===i.sessionId?t.state:void 0,o=a?VT(a):i.state,s=a?a.kind===`idle`:o===`done`&&i.settledAt===void 0,c=FT(o,e);n.push({...i,state:o,ready:s,unseen:e,tier:c,shelf:c===`recent`?`settled`:`active`})}return n.sort(IT),{active:n.filter(e=>e.shelf===`active`),settled:n.filter(e=>e.shelf===`settled`),unavailable:r.sort((e,t)=>e.agentId.localeCompare(t.agentId)||e.sessionId.localeCompare(t.sessionId))}}function WT(e){return[...e.active,...e.settled].filter(e=>!(e.title===``&&e.ready))}function GT(e,t){return`${e}\u0000${t}`}function KT(e){return e.name}function qT({children:e}){return(0,Y.jsx)(`span`,{className:`grove-rail-mark grid size-full place-items-center`,children:e})}function JT({open:e,agents:t,agentActivity:n,agentFilterId:r,websitesSelected:i,websitesVisible:a,canCreate:o,createOpen:s,onAll:c,onWebsites:l,onAgent:u,onCreate:d}){let[f,p]=(0,q.useState)(null),m=`grove-rail-cell relative size-12 rounded-field p-0`,h=r===null&&!(i&&a);return(0,Y.jsxs)(`nav`,{id:`grove-agent-rail`,"aria-label":`Agents`,className:`grove-rail min-h-0 w-16 flex-none flex-col items-center gap-1 border-r border-base-300 py-2 ${e?`flex`:`flex min-[900px]:hidden`}`,children:[(0,Y.jsx)(Zt,{variant:`ghost`,"aria-label":`All Agents`,"aria-pressed":h,className:`${m} text-xs ${h?`bg-base-300`:``}`,onClick:c,children:(0,Y.jsx)(qT,{children:`All`})}),a?(0,Y.jsx)(Zt,{variant:`ghost`,"aria-label":`Websites`,"aria-pressed":i,className:`${m} ${i?`bg-base-300`:``}`,onClick:l,children:(0,Y.jsx)(qT,{children:(0,Y.jsx)(Cn,{name:`internet`,size:28})})}):null,(0,Y.jsx)(dx,{className:`w-full flex-1`,style:{width:`100%`},children:(0,Y.jsx)(`div`,{className:`flex flex-col items-center gap-1 py-1`,children:t.map(e=>(0,Y.jsx)(Zt,{variant:`ghost`,"aria-label":KT(e),title:KT(e),"aria-pressed":r===e.agentId&&!i,"data-agent-id":e.agentId,className:`${m} ${r===e.agentId&&!i?`bg-base-300`:``}`,onPointerEnter:()=>{p(e.agentId)},onPointerLeave:()=>{p(null)},onFocus:()=>{p(e.agentId)},onBlur:()=>{p(null)},onClick:()=>{u(e.agentId)},children:(0,Y.jsx)(qT,{children:(0,Y.jsx)(kT,{activity:n.get(e.agentId)??(f===e.agentId?`thinking`:`idle`),avatar:e.avatar,name:KT(e),size:32})})},e.agentId))})}),o?(0,Y.jsx)(Zt,{variant:`ghost`,"aria-label":`New Agent`,"aria-expanded":s,"aria-haspopup":`dialog`,className:`${m} mt-auto`,onClick:d,children:(0,Y.jsx)(`span`,{className:`grove-rail-mark grid size-full place-items-center`,children:(0,Y.jsx)(Oe,{size:20})})}):null]})}function YT({app:e}){let[t,n]=(0,q.useState)(null),r=qo({queryKey:Iy.of(e,`team-inbox-notices`,t),enabled:e!==null&&(e.capabilities.has(Ag)||e.capabilities.has(jg)),queryFn:async()=>{if(!e)throw Error(`No App connection`);let n=await Rg(e.capabilities);try{return await Ay(n,t)}finally{await n.close()}}});return!r.isError&&!r.data?.items.length?null:(0,Y.jsx)(`section`,{"aria-label":`Team notices`,className:`min-h-0 shrink-0`,children:(0,Y.jsxs)(dx,{className:`max-h-52 border-b border-base-300`,children:[r.isError?(0,Y.jsx)(`p`,{role:`alert`,className:`text-sm`,children:`Team notices unavailable.`}):(0,Y.jsx)(Rt,{density:`compact`,className:`px-3 py-2`,children:r.data.items.map(e=>(0,Y.jsx)(_e,{children:(0,Y.jsxs)(`div`,{className:`grid min-w-0 grid-cols-[auto_minmax(0,1fr)] gap-x-[var(--spacing-xs)]`,children:[(0,Y.jsx)(fe,{className:`col-span-2 grid grid-cols-subgrid`,size:`compact`,tone:`warning`,label:`kind`in e?`Seller closed`:`Installed App safety notice`}),(0,Y.jsx)(`p`,{className:`m-0 col-start-2 text-sm [overflow-wrap:anywhere]`,children:`kind`in e?`${e.sellerName} closed. Your installation of ${e.displayName} continues; no new purchases are available.`:`${e.displayName} was removed. Fungi will disable it on your Team.`})]})},e.dispositionId))}),r.data?.next?(0,Y.jsx)(Zt,{variant:`ghost`,size:`sm`,onClick:()=>{n(r.data.next)},children:`Older notices`}):null,t===null?null:(0,Y.jsx)(Zt,{variant:`ghost`,size:`sm`,onClick:()=>{n(null)},children:`Newest notices`})]})})}var XT=`(min-width: 900px)`;function ZT(e){let t=globalThis.matchMedia(XT);return t.addEventListener(`change`,e),()=>{t.removeEventListener(`change`,e)}}function QT(){return globalThis.matchMedia(XT).matches}function $T(){return(0,q.useSyncExternalStore)(ZT,QT,()=>!0)}function eE({open:e,onOpenChange:t,returnFocus:n,children:r}){let i=$T(),[a,o]=(0,q.useState)(null);return(0,Y.jsxs)(b,{open:i||e,modal:!i,disablePointerDismissal:i,onOpenChange:e=>{i||t(e)},children:[(0,Y.jsx)(`div`,{ref:o,className:`contents`}),(0,Y.jsxs)(ye,{container:a,keepMounted:!0,className:`contents`,children:[i?null:(0,Y.jsx)(v,{className:`grove-nav-scrim z-30 bg-base-200`}),(0,Y.jsx)(ge,{id:`grove-nav`,role:i?`presentation`:`dialog`,"aria-label":i?void 0:`Agents and conversations`,initialFocus:!i&&void 0,finalFocus:!i&&n,className:`grove-nav min-h-0 flex-none rounded-none p-0 overflow-visible max-w-none max-h-none ${i?`static flex w-auto shadow-none`:`fixed inset-y-0 left-0 z-40 w-[min(22rem,88vw)] data-[open]:flex`}`,children:r})]})]})}function tE({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0){n=e.nextSub;continue}for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}while(!0)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(!0)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function nE(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}var rE=[],iE=0,{link:aE,unlink:oE,propagate:sE,checkDirty:cE,shallowPropagate:lE}=tE({update(e){return e._update()},notify(e){rE[dE++]=e,e.flags&=-3},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=17,hE(e))}}),uE=0,dE=0,fE,pE=0;function mE(e){try{++pE,e()}finally{--pE||gE()}}function hE(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=oE(n,e)}function gE(){if(!(pE>0)){for(;uE<dE;){let e=rE[uE];rE[uE++]=void 0,e.notify()}uE=0,dE=0}}function _E(e,t){let n=typeof e==`function`,r=e,i={_snapshot:n?void 0:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:+!n,get(){return fE!==void 0&&aE(i,fE,iE),i._snapshot},subscribe(e){let t=nE(e),n={current:!1},r=vE(()=>{i.get(),n.current?t.next?.(i._snapshot):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=fE,o=t?.compare??Object.is;if(n)fE=i,++iE,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=5);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{fE=a,n&&(i.flags&=-5),hE(i)}}};return n?(i.flags=17,i.get=function(){let e=i.flags;if(e&16||e&32&&cE(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&lE(e)}}else e&32&&(i.flags=e&-33);return fE!==void 0&&aE(i,fE,iE),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(sE(e),lE(e),gE())}},i}function vE(e){let t=()=>{let t=fE;fE=n,++iE,n.depsTail=void 0,n.flags=6;try{return e()}finally{fE=t,n.flags&=-5,hE(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:6,notify(){let e=this.flags;e&16||e&32&&cE(this.deps,this)?t():this.flags=2},stop(){this.flags=0,this.depsTail=void 0,hE(this)}};return t(),n}var yE=class{constructor(e,t){this.atom=_E(e),this.get=this.get.bind(this),this.setState=this.setState.bind(this),this.subscribe=this.subscribe.bind(this),t&&(this.actions=t(this))}setState(e){this.atom.set(e)}get state(){return this.atom.get()}get(){return this.state}subscribe(e){return this.atom.subscribe(nE(e))}},bE=class{constructor(e){this.atom=_E(e)}get state(){return this.atom.get()}get(){return this.state}subscribe(e){return this.atom.subscribe(nE(e))}};function xE(e,t){return typeof e==`function`?new bE(e):t?new yE(e,t):new yE(e)}var SE=class{constructor(e,t){this.fn=e,this.options=t,this.lastExecutionTime=0,this.isPending=!1,this.maybeExecute=(...e)=>{let t=Date.now()-this.lastExecutionTime;if(this.options.leading&&t>=this.options.wait)this.execute(...e);else if(this.lastArgs=e,!this.timeoutId&&this.options.trailing){let e=this.options.wait-t;this.isPending=!0,this.timeoutId=setTimeout(()=>{this.lastArgs!==void 0&&this.execute(...this.lastArgs)},e)}},this.execute=(...e)=>{this.fn(...e),this.options.onExecute?.(e,this),this.lastExecutionTime=Date.now(),this.clearTimeout(),this.lastArgs=void 0,this.isPending=!1},this.flush=()=>{this.isPending&&this.lastArgs&&this.execute(...this.lastArgs)},this.cancel=()=>{this.clearTimeout(),this.lastArgs=void 0,this.isPending=!1},this.clearTimeout=()=>{this.timeoutId&&=(clearTimeout(this.timeoutId),void 0)},this.options.leading===void 0&&this.options.trailing===void 0&&(this.options.leading=!0,this.options.trailing=!0)}};function CE(e,t){return new SE(e,t).maybeExecute}var wE=class{#e=!0;#t;#n;#r;#i;#a;#o;#s;#c=0;#l=5;#u=!1;#d=!1;#f=null;#p=()=>{this.debugLog(`Connected to event bus`),this.#a=!0,this.#u=!1,this.debugLog(`Emitting queued events`,this.#i),this.#i.forEach(e=>this.emitEventToBus(e)),this.#i=[],this.stopConnectLoop(),this.#n().removeEventListener(`tanstack-connect-success`,this.#p)};#m=()=>{if(this.#c<this.#l){this.#c++,this.dispatchCustomEvent(`tanstack-connect`,{});return}this.#n().removeEventListener(`tanstack-connect`,this.#m),this.#d=!0,this.debugLog(`Max retries reached, giving up on connection`),this.stopConnectLoop()};#h=()=>{this.#u||(this.#u=!0,this.#n().addEventListener(`tanstack-connect-success`,this.#p),this.#m())};constructor({pluginId:e,debug:t=!1,enabled:n=!0,reconnectEveryMs:r=300}){this.#t=e,this.#e=n,this.#n=this.getGlobalTarget,this.#r=t,this.debugLog(` Initializing event subscription for plugin`,this.#t),this.#i=[],this.#a=!1,this.#d=!1,this.#o=null,this.#s=r}startConnectLoop(){this.#o!==null||this.#a||(this.debugLog(`Starting connect loop (every ${this.#s}ms)`),this.#o=setInterval(this.#m,this.#s))}stopConnectLoop(){this.#u=!1,this.#o!==null&&(clearInterval(this.#o),this.#o=null,this.#i=[],this.debugLog(`Stopped connect loop`))}debugLog(...e){this.#r&&console.log(`🌴 [tanstack-devtools:${this.#t}-plugin]`,...e)}getGlobalTarget(){if(typeof globalThis<`u`&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog(`Using global event target`),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<`u`&&window.addEventListener!==void 0)return this.debugLog(`Using window as event target`),window;let e=typeof EventTarget<`u`?new EventTarget:void 0;return e===void 0||e.addEventListener===void 0?(this.debugLog(`No event mechanism available, running in non-web environment`),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>!1}):(this.debugLog(`Using new EventTarget as fallback`),e)}getPluginId(){return this.#t}dispatchCustomEventShim(e,t){try{let n=new Event(e,{detail:t});this.#n().dispatchEvent(n)}catch{this.debugLog(`Failed to dispatch shim event`)}}dispatchCustomEvent(e,t){try{this.#n().dispatchEvent(new CustomEvent(e,{detail:t}))}catch{this.dispatchCustomEventShim(e,t)}}emitEventToBus(e){this.debugLog(`Emitting event to client bus`,e),this.dispatchCustomEvent(`tanstack-dispatch-event`,e)}createEventPayload(e,t){return{type:`${this.#t}:${e}`,payload:t,pluginId:this.#t}}emit(e,t){if(!this.#e){this.debugLog(`Event bus client is disabled, not emitting event`,e,t);return}if(this.#f&&(this.debugLog(`Emitting event to internal event target`,e,t),this.#f.dispatchEvent(new CustomEvent(`${this.#t}:${e}`,{detail:this.createEventPayload(e,t)}))),this.#d){this.debugLog(`Previously failed to connect, not emitting to bus`);return}if(!this.#a){this.debugLog(`Bus not available, will be pushed as soon as connected`),this.#i.push(this.createEventPayload(e,t)),typeof CustomEvent<`u`&&!this.#u&&(this.#h(),this.startConnectLoop());return}return this.emitEventToBus(this.createEventPayload(e,t))}on(e,t,n){let r=n?.withEventTarget??!1,i=`${this.#t}:${e}`;if(r&&(this.#f||=new EventTarget,this.#f.addEventListener(i,e=>{t(e.detail)})),!this.#e)return this.debugLog(`Event bus client is disabled, not registering event`,i),()=>{};let a=e=>{this.debugLog(`Received event from bus`,e.detail),t(e.detail)};return this.#n().addEventListener(i,a),this.debugLog(`Registered event to bus`,i),()=>{r&&this.#f?.removeEventListener(i,a),this.#n().removeEventListener(i,a)}}onAll(e){if(!this.#e)return this.debugLog(`Event bus client is disabled, not registering event`),()=>{};let t=t=>{let n=t.detail;e(n)};return this.#n().addEventListener(`tanstack-devtools-global`,t),()=>this.#n().removeEventListener(`tanstack-devtools-global`,t)}onAllPluginEvents(e){if(!this.#e)return this.debugLog(`Event bus client is disabled, not registering event`),()=>{};let t=t=>{let n=t.detail;this.#t&&n.pluginId!==this.#t||e(n)};return this.#n().addEventListener(`tanstack-devtools-global`,t),()=>this.#n().removeEventListener(`tanstack-devtools-global`,t)}},TE=new class extends wE{constructor(){super({pluginId:`form-devtools`,reconnectEveryMs:1e3})}};function EE(e,t){return typeof e==`function`?e(t):e}function DE(e,t){return FE(t).reduce((e,t)=>{if(e===null)return null;if(e!==void 0)return e[t]},e)}function OE(e,t,n){let r=FE(t);function i(e){if(!r.length)return EE(n,e);let t=r.shift();if(typeof t==`string`||typeof t==`number`&&!Array.isArray(e))return typeof e==`object`?(e===null&&(e={}),{...e,[t]:i(e[t])}):{[t]:i()};if(Array.isArray(e)&&typeof t==`number`){let n=e.slice(0,t);return[...n.length?n:Array(t),i(e[t]),...e.slice(t+1)]}return[...Array(t),i()]}return i(e)}function kE(e,t){let n=FE(t);function r(e){if(!e)return;if(n.length===1){let t=n[0];if(Array.isArray(e)&&typeof t==`number`)return e.filter((e,n)=>n!==t);let{[t]:r,...i}=e;return i}let t=n.shift();if((typeof t==`string`||typeof t==`number`&&!Array.isArray(e))&&typeof e==`object`)return{...e,[t]:r(e[t])};if(typeof t==`number`&&Array.isArray(e)){if(t>=e.length)return e;let n=e.slice(0,t);return[...n.length?n:Array(t),r(e[t]),...e.slice(t+1)]}throw Error(`It seems we have created an infinite loop in deleteBy. `)}return r(e)}var AE=46,jE=91,ME=93,NE=48,PE=57;function FE(e){if(Array.isArray(e))return[...e];if(typeof e!=`string`)throw Error(`Path must be a string.`);let t=e.length,n=[],r=+(t>0&&e.charCodeAt(0)===jE),i=!0,a=-1;for(let o=r;o<=t;o++){let s=o<t?e.charCodeAt(o):-1;if(o===t||s===AE||s===jE||s===ME){let t=o-r;if(t>0){let a=i&&(t===1||e.charCodeAt(r)!==NE),s=e.slice(r,o);if(a){let e=parseInt(s,10);t<=15||String(e)===s?n.push(e):n.push(s)}else n.push(s)}else a!==ME&&(a!==-1||s!==ME)&&(a!==s||s!==AE&&s!==jE)&&n.push(``);r=o+1,i=!0}else(s<NE||s>PE)&&(i=!1);a=s}return n.length||n.push(``),n}function IE(e){return!(Array.isArray(e)&&e.length===0)}function LE(e,t){return t.validationLogic({form:t.form,group:t.group,validators:t.validators,event:{type:e,fieldName:t.fieldName,async:!1},runValidation:e=>e.validators.filter(Boolean).map(e=>({cause:e.cause,validate:e.fn}))})}function RE(e,t){let{asyncDebounceMs:n}=t,{onBlurAsyncDebounceMs:r,onChangeAsyncDebounceMs:i,onDynamicAsyncDebounceMs:a}=t.validators||{},o=n??0;return t.validationLogic({form:t.form,group:t.group,validators:t.validators,event:{type:e,fieldName:t.fieldName,async:!0},runValidation:t=>t.validators.filter(Boolean).map(t=>{let n=t?.cause||e,s=o;switch(n){case`change`:s=i??o;break;case`blur`:s=r??o;break;case`dynamic`:s=a??o;break;case`submit`:s=0}return e===`submit`&&(s=0),{cause:n,validate:t.fn,debounceMs:s}})})}var zE=e=>!!e&&typeof e==`object`&&`fields`in e;function BE(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!t.has(n)||!Object.is(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length||n.length===0&&!Array.isArray(e)&&!Array.isArray(t)&&(Object.getPrototypeOf(e)!==Object.prototype||Object.getPrototypeOf(t)!==Object.prototype))return!1;for(let i of n)if(!r.includes(i)||!BE(e[i],t[i]))return!1;return!0}var VE=({newFormValidatorError:e,isPreviousErrorFromFormValidator:t,previousErrorValue:n})=>e?{newErrorValue:e,newSource:`form`}:t?{newErrorValue:void 0,newSource:void 0}:n?{newErrorValue:n,newSource:`field`}:{newErrorValue:void 0,newSource:void 0},HE=({formLevelError:e,fieldLevelError:t})=>t?{newErrorValue:t,newSource:`field`}:e?{newErrorValue:e,newSource:`form`}:{newErrorValue:void 0,newSource:void 0};function UE(e,t){return e==null?t:{...e,...t}}for(var WE=256,GE=[],KE;WE--;)GE[WE]=(WE+256).toString(16).substring(1);function qE(){let e=0,t,n=``;if(!KE||WE+16>256){for(KE=Array(256),e=256;e--;)KE[e]=256*Math.random()|0;e=0,WE=0}for(;e<16;e++)t=KE[WE+e],n+=e===6?GE[t&15|64]:e===8?GE[t&63|128]:GE[t],e&1&&e>1&&e<11&&(n+=`-`);return WE++,n}var JE=CE(e=>TE.emit(`form-state`,{id:e.formId,state:e.store.state}),{wait:300});function YE(e){if(typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e)){let t=[];for(let n=0;n<e.length;n++)t[n]=YE(e[n]);return t}if(e instanceof Map){let t=new Map;return e.forEach((e,n)=>{t.set(n,YE(e))}),t}if(e instanceof Set){let t=new Set;return e.forEach(e=>{t.add(YE(e))}),t}let t={};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=YE(e[n]));return t}function XE(e,t){return t===e||t.startsWith(`${e}.`)||t.startsWith(`${e}[`)}var ZE=e=>{if(!e.validators)return e.runValidation({validators:[],form:e.form});let t=e.event.async,n=t?void 0:{fn:e.validators.onMount,cause:`mount`},r={fn:t?e.validators.onChangeAsync:e.validators.onChange,cause:`change`},i={fn:t?e.validators.onBlurAsync:e.validators.onBlur,cause:`blur`},a={fn:t?e.validators.onSubmitAsync:e.validators.onSubmit,cause:`submit`},o=t?void 0:{fn:()=>void 0,cause:`server`};switch(e.event.type){case`mount`:return e.runValidation({validators:[n],form:e.form});case`submit`:return e.runValidation({validators:[r,i,a,o],form:e.form});case`server`:return e.runValidation({validators:[],form:e.form});case`blur`:return e.runValidation({validators:[i,o],form:e.form});case`change`:return e.runValidation({validators:[r,o],form:e.form});default:throw Error(`Unknown validation event type: ${e.event.type}`)}};function QE(e,t){let n=new Map;for(let r of e){let e=r.path??[],i=t,a=``;for(let t=0;t<e.length;t++){let n=e[t];if(n===void 0)continue;let r=typeof n==`object`?n.key:n,o=Number(r);a+=Array.isArray(i)&&!Number.isNaN(o)?`[${o}]`:(t>0?`.`:``)+String(r),i=typeof i==`object`&&i?i[r]:void 0}n.set(a,(n.get(a)??[]).concat(r))}return Object.fromEntries(n)}var $E=(e,t)=>{let n=QE(e,t);return{form:n,fields:n}},eD={validate({value:e,validationSource:t},n){let r=n[`~standard`].validate(e);if(r instanceof Promise)throw Error(`async function passed to sync validator`);if(r.issues)return t===`field`?r.issues:$E(r.issues,e)},async validateAsync({value:e,validationSource:t},n){let r=await n[`~standard`].validate(e);if(r.issues)return t===`field`?r.issues:$E(r.issues,e)}},tD=e=>!!e&&`~standard`in e,nD={isValidating:!1,isTouched:!1,isBlurred:!1,isDirty:!1,isPristine:!0,isValid:!0,isDefaultValue:!0,errors:[],errorMap:{},errorSourceMap:{},_arrayVersion:0,_pendingValidationsCount:0};function rD(e){function t(t){let n=e.getFieldMeta(t)??nD;e.setFieldMeta(t,{...n,_arrayVersion:(n._arrayVersion||0)+1})}function n(n,r,i){t(n);let a=s(n,r,`move`,i),c=Math.min(r,i),u=Math.max(r,i);for(let e=c;e<=u;e++)a.push(o(n,e));let d=Object.keys(e.fieldInfo).reduce((t,i)=>(i.startsWith(o(n,r))&&t.set(i,e.getFieldMeta(i)),t),new Map);l(a,r<i?`up`:`down`),Object.keys(e.fieldInfo).filter(e=>e.startsWith(o(n,i))).forEach(t=>{let a=t.replace(o(n,i),o(n,r)),s=d.get(a);s&&e.setFieldMeta(t,s)})}function r(e,n){t(e),l(s(e,n,`remove`),`up`)}function i(n,r,i){t(n),s(n,r,`swap`,i).forEach(t=>{if(!t.toString().startsWith(o(n,r)))return;let a=t.toString().replace(o(n,r),o(n,i)),[s,c]=[e.getFieldMeta(t),e.getFieldMeta(a)];s&&e.setFieldMeta(a,s),c&&e.setFieldMeta(t,c)})}function a(n,r){t(n);let i=s(n,r,`insert`);l(i,`down`),i.forEach(t=>{t.toString().startsWith(o(n,r))&&e.setFieldMeta(t,u())})}function o(e,t){return`${e}[${t}]`}function s(t,n,r,i){let a=[o(t,n)];switch(r){case`swap`:a.push(o(t,i));break;case`move`:{let[e,r]=[Math.min(n,i),Math.max(n,i)];for(let n=e;n<=r;n++)a.push(o(t,n));break}default:{let r=e.getFieldValue(t),i=Array.isArray(r)?r.length:0;for(let e=n+1;e<i;e++)a.push(o(t,e));break}}return Object.keys(e.fieldInfo).filter(e=>a.some(t=>e.startsWith(t)))}function c(e,t){return e.replace(/\[(\d+)\]/,(e,n)=>{let r=parseInt(n,10);return`[${t===`up`?r+1:Math.max(0,r-1)}]`})}function l(t,n){(n===`up`?t:[...t].reverse()).forEach(t=>{let r=c(t.toString(),n),i=e.getFieldMeta(r);i?e.setFieldMeta(t,i):e.setFieldMeta(t,u())})}let u=()=>nD;return{bumpArrayVersion:t,handleArrayMove:n,handleArrayRemove:r,handleArraySwap:i,handleArrayInsert:a}}function iD(e){return{values:e.values??{},errorMap:e.errorMap??{},fieldMetaBase:e.fieldMetaBase??{},formGroupStateBase:e.formGroupStateBase??{},isSubmitted:e.isSubmitted??!1,isSubmitting:e.isSubmitting??!1,isValidating:e.isValidating??!1,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??!1,validationMetaMap:e.validationMetaMap??{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}}}var aD=class{constructor(e){this.options={},this.fieldInfo={},this.formGroupApis=new Set,this.mount=()=>{let e=this.store.subscribe(()=>{JE(this)}),t=TE.on(`request-form-state`,e=>{e.payload.id===this._formId&&TE.emit(`form-api`,{id:this._formId,state:this.store.state,options:this.options})}),n=TE.on(`request-form-reset`,e=>{e.payload.id===this._formId&&this.reset()}),r=TE.on(`request-form-force-submit`,e=>{e.payload.id===this._formId&&(this._devtoolsSubmissionOverride=!0,this.handleSubmit(),this._devtoolsSubmissionOverride=!1)}),i=()=>{r(),n(),t(),e.unsubscribe(),TE.emit(`form-unmounted`,{id:this._formId})};this.options.listeners?.onMount?.({formApi:this});let{onMount:a}=this.options.validators||{};return TE.emit(`form-api`,{id:this._formId,state:this.store.state,options:this.options}),a&&this.validateSync(`mount`),i},this.update=e=>{if(!e)return;let t=this.options;this.options=e;let n=e.defaultValues&&!BE(e.defaultValues,t.defaultValues)&&!this.state.isTouched,r=!BE(e.defaultState,t.defaultState)&&!this.state.isTouched;if(!(!n&&!r)){if(mE(()=>{this.baseStore.setState(()=>iD(Object.assign({},this.state,r?e.defaultState:{},n?{values:e.defaultValues}:{})))}),n){let e=rD(this);for(let t of Object.keys(this.fieldInfo))Array.isArray(this.getFieldValue(t))&&e.bumpArrayVersion(t)}TE.emit(`form-api`,{id:this._formId,state:this.store.state,options:this.options})}},this.reset=(e,t)=>{let{fieldMeta:n}=this.state,r=this.resetFieldMeta(n);e&&!t?.keepDefaultValues&&(this.options={...this.options,defaultValues:e}),this.baseStore.setState(()=>{let t=e??this.options.defaultValues??this.options.defaultState?.values;return e||Object.values(this.fieldInfo).forEach(e=>{e.instance&&e.instance.options.defaultValue!==void 0&&(t=OE(t,e.instance.name,e.instance.options.defaultValue))}),iD({...this.options.defaultState,values:t,fieldMetaBase:r})})},this.validateAllFields=async e=>{let t=[];return mE(()=>{Object.values(this.fieldInfo).forEach(n=>{if(!n.instance)return;let r=n.instance;t.push(Promise.resolve().then(()=>r.validate(e,{skipFormValidation:!0,skipGroupValidation:!0}))),n.instance.store.state.meta.isTouched||n.instance.setMeta(e=>({...e,isTouched:!0}))})}),(await Promise.all(t)).flat()},this.validateArrayFieldsStartingFrom=async(e,t,n)=>{let r=this.getFieldValue(e),i=Array.isArray(r)?Math.max(r.length-1,0):null,a=[`${e}[${t}]`];for(let n=t+1;n<=(i??0);n++)a.push(`${e}[${n}]`);let o=Object.keys(this.fieldInfo).filter(e=>a.some(t=>e.startsWith(t))),s=[];return mE(()=>{o.forEach(e=>{s.push(Promise.resolve().then(()=>this.validateField(e,n)))})}),(await Promise.all(s)).flat()},this.validateField=(e,t)=>{let n=this.fieldInfo[e]?.instance;if(!n){let{hasErrored:n}=this.validateSync(t);return n&&!this.options.asyncAlways?this.getFieldMeta(e)?.errors??[]:this.validateAsync(t).then(()=>this.getFieldMeta(e)?.errors??[])}return n.store.state.meta.isTouched||n.setMeta(e=>({...e,isTouched:!0})),n.validate(t)},this.validateSync=(e,t)=>{let n=LE(e,{...this.options,form:this,group:t?.group,validationLogic:this.options.validationLogic||ZE}),r=!1,i={};return mE(()=>{for(let e of n){if(!e.validate)continue;let{formError:n,fieldErrors:a}=oD(this.runValidator({validate:e.validate,value:{value:this.state.values,formApi:this,validationSource:`form`},type:`validate`})),o=sD(e.cause),s=new Set([...Object.keys(this.state.fieldMeta),...Object.keys(a||{})]);t?.filterFieldNames&&(s=new Set([...s].filter(t.filterFieldNames)));for(let e of s){if(this.baseStore.state.fieldMetaBase[e]===void 0&&!a?.[e])continue;let{errorMap:t,errorSourceMap:n}=this.getFieldMeta(e)??nD,r=a?.[e],{newErrorValue:s,newSource:c}=VE({newFormValidatorError:r,isPreviousErrorFromFormValidator:n?.[o]===`form`,previousErrorValue:t?.[o]});c===`form`&&(i[e]={...i[e],[o]:r}),t?.[o]!==s&&this.setFieldMeta(e,(e=nD)=>({...e,errorMap:{...e.errorMap,[o]:s},errorSourceMap:{...e.errorSourceMap,[o]:c}}))}t?.dontUpdateFormErrorMap||this.state.errorMap?.[o]!==n&&this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[o]:n}})),(n||a)&&(r=!0)}if(t?.dontUpdateFormErrorMap)return;let a=sD(`submit`);this.state.errorMap?.[a]&&e!==`submit`&&!r&&this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[a]:void 0}}));let o=sD(`server`);this.state.errorMap?.[o]&&e!==`server`&&!r&&this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[o]:void 0}}))}),{hasErrored:r,fieldsErrorMap:i}},this.validateAsync=async(e,t)=>{let n=RE(e,{...this.options,form:this,group:t?.group,validationLogic:this.options.validationLogic||ZE});this.state.isFormValidating||this.baseStore.setState(e=>({...e,isFormValidating:!0}));let r=[],i;for(let e of n){if(!e.validate)continue;let n=sD(e.cause);this.state.validationMetaMap[n]?.lastAbortController.abort();let a=new AbortController;this.state.validationMetaMap[n]={lastAbortController:a},r.push(new Promise(async n=>{let r;try{r=await new Promise((t,n)=>{setTimeout(async()=>{if(a.signal.aborted)return t(void 0);try{t(await this.runValidator({validate:e.validate,value:{value:this.state.values,formApi:this,validationSource:`form`,signal:a.signal},type:`validateAsync`}))}catch(e){n(e)}},e.debounceMs)})}catch(e){r=e}let{formError:o,fieldErrors:s}=oD(r);s&&(i=i?{...i,...s}:s);let c=sD(e.cause),l=new Set([...Object.keys(this.state.fieldMeta),...Object.keys(i||{})]),u=Array.from(l);t?.filterFieldNames&&(u=u.filter(t.filterFieldNames));for(let e of u){if(this.baseStore.state.fieldMetaBase[e]===void 0&&!i?.[e])continue;let{errorMap:t,errorSourceMap:n}=this.getFieldMeta(e)??nD,r=i?.[e],{newErrorValue:a,newSource:o}=VE({newFormValidatorError:r,isPreviousErrorFromFormValidator:n?.[c]===`form`,previousErrorValue:t?.[c]});t?.[c]!==a&&this.setFieldMeta(e,(e=nD)=>({...e,errorMap:{...e.errorMap,[c]:a},errorSourceMap:{...e.errorSourceMap,[c]:o}}))}t?.dontUpdateFormErrorMap||this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[c]:o}})),n(i?{fieldErrors:i,errorMapKey:c}:void 0)}))}let a=[],o={};if(r.length){a=await Promise.all(r);for(let e of a)if(e?.fieldErrors){let{errorMapKey:t}=e;for(let[n,r]of Object.entries(e.fieldErrors))o[n]={...o[n]||{},[t]:r}}}return this.baseStore.setState(e=>({...e,isFormValidating:!1})),o},this.validate=(e,t)=>{let{hasErrored:n,fieldsErrorMap:r}=this.validateSync(e,t);return n&&!this.options.asyncAlways?r:this.validateAsync(e,t)},this._handleSubmit=async e=>{this.baseStore.setState(e=>({...e,isSubmitted:!1,submissionAttempts:e.submissionAttempts+1,isSubmitSuccessful:!1})),mE(()=>{Object.values(this.fieldInfo).forEach(e=>{e.instance&&(e.instance.store.state.meta.isTouched||e.instance.setMeta(e=>({...e,isTouched:!0})))})});let t=e??this.options.onSubmitMeta;if(!this.state.canSubmit&&!this._devtoolsSubmissionOverride&&this.baseStore.state.submissionAttempts<=1){this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t});return}this.baseStore.setState(e=>({...e,isSubmitting:!0}));let n=()=>{this.baseStore.setState(e=>({...e,isSubmitting:!1}))};if(await this.validateAllFields(`submit`),!this.state.isFieldsValid){n(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),TE.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:`validateAllFields`,errors:Object.values(this.state.fieldMeta).map(e=>e.errors).flat()});return}if(await this.validate(`submit`),!this.state.isValid){n(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),TE.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:`validate`,errors:this.state.errors});return}mE(()=>{Object.values(this.fieldInfo).forEach(e=>{e.instance?.triggerOnSubmitListener()})}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t}),mE(()=>{this.baseStore.setState(e=>({...e,isSubmitted:!0,isSubmitSuccessful:!0})),TE.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),n()})}catch(e){throw this.baseStore.setState(e=>({...e,isSubmitSuccessful:!1})),TE.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:`inflight`,onError:e}),n(),e}},this.getFieldValue=e=>DE(this.state.values,e),this.getFieldMeta=e=>this.state.fieldMeta[e],this.getFormGroupMeta=e=>this.formGroupMetaDerived.state[e],this.getFieldInfo=e=>this.fieldInfo[e]||={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}},this.setFieldMeta=(e,t)=>{this.baseStore.setState(n=>({...n,fieldMetaBase:{...n.fieldMetaBase,[e]:EE(t,n.fieldMetaBase[e])}}))},this.resetFieldMeta=e=>Object.keys(e).reduce((e,t)=>{let n=t;return e[n]=nD,e},{}),this.setFieldValue=(e,t,n)=>{let r=n?.dontUpdateMeta??!1,i=n?.dontRunListeners??!1,a=n?.dontValidate??!1;mE(()=>{r||this.setFieldMeta(e,e=>({...e,isTouched:!0,isDirty:!0,errorMap:{...e?.errorMap,onMount:void 0}})),this.baseStore.setState(n=>({...n,values:OE(n.values,e,t)}))}),i||this.getFieldInfo(e).instance?.triggerOnChangeListener(),a||this.validateField(e,`change`)},this.deleteField=e=>{let t=[...Object.keys(this.fieldInfo).filter(t=>{let n=e.toString();return t!==n&&t.startsWith(n)}),e];this.baseStore.setState(e=>{let n={...e};return t.forEach(e=>{n.values=kE(n.values,e),delete this.fieldInfo[e],delete n.fieldMetaBase[e]}),n})},this.pushFieldValue=(e,t,n)=>{this.setFieldValue(e,e=>[...Array.isArray(e)?e:[],t],n),rD(this).bumpArrayVersion(e)},this.insertFieldValue=async(e,t,n,r)=>{this.setFieldValue(e,e=>[...e.slice(0,t),n,...e.slice(t)],UE(r,{dontValidate:!0}));let i=r?.dontValidate??!1;i||await this.validateField(e,`change`),rD(this).handleArrayInsert(e,t),i||await this.validateArrayFieldsStartingFrom(e,t,`change`)},this.replaceFieldValue=async(e,t,n,r)=>{this.setFieldValue(e,e=>e.map((e,r)=>r===t?n:e),UE(r,{dontValidate:!0})),rD(this).bumpArrayVersion(e),(r?.dontValidate??!1)||(await this.validateField(e,`change`),await this.validateArrayFieldsStartingFrom(e,t,`change`))},this.removeFieldValue=async(e,t,n)=>{let r=this.getFieldValue(e),i=Array.isArray(r)?Math.max(r.length-1,0):null;if(this.setFieldValue(e,e=>e.filter((e,n)=>n!==t),UE(n,{dontValidate:!0})),rD(this).handleArrayRemove(e,t),i!==null){let t=`${e}[${i}]`;this.deleteField(t)}(n?.dontValidate??!1)||(await this.validateField(e,`change`),await this.validateArrayFieldsStartingFrom(e,t,`change`))},this.swapFieldValues=(e,t,n,r)=>{this.setFieldValue(e,e=>{let r=e[t],i=e[n];return OE(OE(e,`${t}`,i),`${n}`,r)},UE(r,{dontValidate:!0})),rD(this).handleArraySwap(e,t,n),(r?.dontValidate??!1)||(this.validateField(e,`change`),this.validateField(`${e}[${t}]`,`change`),this.validateField(`${e}[${n}]`,`change`))},this.moveFieldValues=(e,t,n,r)=>{this.setFieldValue(e,e=>{let r=[...e];return r.splice(n,0,r.splice(t,1)[0]),r},UE(r,{dontValidate:!0})),rD(this).handleArrayMove(e,t,n),(r?.dontValidate??!1)||(this.validateField(e,`change`),this.validateField(`${e}[${t}]`,`change`),this.validateField(`${e}[${n}]`,`change`))},this.clearFieldValues=(e,t)=>{let n=this.getFieldValue(e),r=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(e,[],UE(t,{dontValidate:!0})),rD(this).bumpArrayVersion(e),r!==null)for(let t=0;t<=r;t++){let n=`${e}[${t}]`;this.deleteField(n)}(t?.dontValidate??!1)||this.validateField(e,`change`)},this.resetField=e=>{this.baseStore.setState(t=>{let n=this.getFieldInfo(e).instance?.options.defaultValue,r=DE(this.options.defaultValues,e),i=n??r;return{...t,fieldMetaBase:{...t.fieldMetaBase,[e]:nD},values:i===void 0?t.values:OE(t.values,e,i)}})},this.setErrorMap=e=>{mE(()=>{Object.entries(e).forEach(([e,t])=>{let n=e;if(zE(t)){let{formError:e,fieldErrors:r}=oD(t);for(let e of Object.keys(this.fieldInfo))this.getFieldMeta(e)&&this.setFieldMeta(e,t=>({...t,errorMap:{...t.errorMap,[n]:r?.[e]},errorSourceMap:{...t.errorSourceMap,[n]:`form`}}));this.baseStore.setState(t=>({...t,errorMap:{...t.errorMap,[n]:e}}))}else this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[n]:t}}))})})},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((e,[t,n])=>(Object.keys(n).length&&n.errors.length&&(e[t]={errors:n.errors,errorMap:n.errorMap}),e),{})}),this.parseValuesWithSchema=e=>eD.validate({value:this.state.values,validationSource:`form`},e),this.parseValuesWithSchemaAsync=e=>eD.validateAsync({value:this.state.values,validationSource:`form`},e),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=e?.formId??qE(),this._devtoolsSubmissionOverride=!1;let t=iD({...e?.defaultState,values:e?.defaultValues??e?.defaultState?.values});if(e?.transform){t=e.transform({state:t}).state;for(let e of Object.keys(t.errorMap)){let n=t.errorMap[e];if(!(n===void 0||!zE(n)))for(let r of Object.keys(n.fields)){let i=n.fields[r];if(i===void 0)continue;let a=t.fieldMetaBase[r];t.fieldMetaBase[r]={isTouched:!1,isValidating:!1,isBlurred:!1,isDirty:!1,_arrayVersion:0,_pendingValidationsCount:0,...a??{},errorSourceMap:{...a?.errorSourceMap??{},onChange:`form`},errorMap:{...a?.errorMap??{},[e]:i}}}}}this.baseStore=xE(t);let n;this.fieldMetaDerived=xE(e=>{let t=this.baseStore.get(),r=0,i={};for(let a of Object.keys(t.fieldMetaBase)){let o=t.fieldMetaBase[a],s=n?.fieldMetaBase[a],c=e?.[a],l=DE(t.values,a),u=c?.errors;if(!s||o.errorMap!==s.errorMap){u=Object.values(o.errorMap??{}).filter(e=>e!==void 0);let e=this.getFieldInfo(a)?.instance;(!e||!e.options.disableErrorFlat)&&(u=u.flat(1))}let d=!IE(u),f=!o.isDirty,p=BE(l,this.getFieldInfo(a)?.instance?.options.defaultValue??DE(this.options.defaultValues,a));if(c&&c.isPristine===f&&c.isValid===d&&c.isDefaultValue===p&&c.errors===u&&o===s){i[a]=c,r++;continue}i[a]={...o,errors:u??[],isPristine:f,isValid:d,isDefaultValue:p}}return Object.keys(t.fieldMetaBase).length?e&&r===Object.keys(t.fieldMetaBase).length?e:(n=this.baseStore.get(),i):i}),this.formGroupMetaDerived=xE(e=>{let t=this.baseStore.get(),n=this.fieldMetaDerived.get(),r={};for(let i of this.formGroupApis){let a=i.name,o=t.formGroupStateBase[a]??{isSubmitted:!1,isSubmitting:!1,isValidating:!1,submissionAttempts:0,isSubmitSuccessful:!1},s=n[a],c=!1,l=!0,u=!1,d=!1,f=!0,p=!1;for(let e in n){if(e===a||!XE(a,e))continue;let t=n[e];t&&(t.isValidating&&(c=!0),t.isValid||(l=!1),t.isTouched&&(u=!0),t.isBlurred&&(d=!0),t.isDefaultValue||(f=!1),t.isDirty&&(p=!0))}let m=!p,h=!!c||o.isValidating,g=s?.errorMap??{},_=s?.errorSourceMap??{},v=!!(g.onMount||Object.entries(n).some(([e,t])=>t&&e!==a&&XE(a,e)&&t.errorMap.onMount)),y=e?.[a],b=y?.errors??[];(!y||y.__srcErrorMap!==g)&&(b=Object.values(g).reduce((e,t)=>{if(t===void 0)return e;if(t&&typeof t==`object`&&`fields`in t){let n=t.group;return n!==void 0&&e.push(n),e}return e.push(t),e},[]));let x=b.length===0,S=l&&x,C=i.options.canSubmitWhenInvalid??!1,w=o.submissionAttempts===0&&!u&&!v||!h&&!o.isSubmitting&&S||C;if(y&&y.errorMap===g&&y.errorSourceMap===_&&y.errors===b&&y.isFieldsValidating===c&&y.isFieldsValid===l&&y.isGroupValid===x&&y.isValid===S&&y.canSubmit===w&&y.isTouched===u&&y.isBlurred===d&&y.isPristine===m&&y.isDefaultValue===f&&y.isDirty===p&&y.isValidating===h&&y.isSubmitting===o.isSubmitting&&y.isSubmitted===o.isSubmitted&&y.submissionAttempts===o.submissionAttempts&&y.isSubmitSuccessful===o.isSubmitSuccessful){r[a]=y;continue}let T={...o,errorMap:g,errorSourceMap:_,_arrayVersion:s?._arrayVersion??0,isTouched:u,isBlurred:d,isDirty:p,isPristine:m,isDefaultValue:f,isValid:S,errors:b,isValidating:h,isFieldsValidating:c,isFieldsValid:l,isGroupValid:x,canSubmit:w};Object.defineProperty(T,"__srcErrorMap",{value:g,enumerable:!1,configurable:!0}),r[a]=T}return r});let r;this.store=xE(e=>{let t=this.baseStore.get(),n=this.fieldMetaDerived.get(),i=Object.values(n).filter(Boolean),a=i.some(e=>e.isValidating),o=i.every(e=>e.isValid),s=i.some(e=>e.isTouched),c=i.some(e=>e.isBlurred),l=i.every(e=>e.isDefaultValue),u=s&&t.errorMap?.onMount,d=i.some(e=>e.isDirty),f=!d,p=!!(t.errorMap?.onMount||i.some(e=>e?.errorMap?.onMount)),m=!!a,h=e?.errors??[];(!r||t.errorMap!==r.errorMap)&&(h=Object.values(t.errorMap).reduce((e,t)=>t===void 0?e:t&&zE(t)?(e.push(t.form),e):(e.push(t),e),[]));let g=h.length===0,_=o&&g,v=this.options.canSubmitWhenInvalid??!1,y=t.submissionAttempts===0&&!s&&!p||!m&&!t.isSubmitting&&_||v,b=t.errorMap;if(u&&(h=h.filter(e=>e!==t.errorMap.onMount),b=Object.assign(b,{onMount:void 0})),e&&r&&e.errorMap===b&&e.fieldMeta===this.fieldMetaDerived.state&&e.errors===h&&e.isFieldsValidating===a&&e.isFieldsValid===o&&e.isFormValid===g&&e.isValid===_&&e.canSubmit===y&&e.isTouched===s&&e.isBlurred===c&&e.isPristine===f&&e.isDefaultValue===l&&e.isDirty===d&&BE(r,t))return e;let x={...t,errorMap:b,fieldMeta:this.fieldMetaDerived.state,errors:h,isFieldsValidating:a,isFieldsValid:o,isFormValid:g,isValid:_,canSubmit:y,isTouched:s,isBlurred:c,isPristine:f,isDefaultValue:l,isDirty:d};return r=this.baseStore.get(),x}),this.handleSubmit=this.handleSubmit.bind(this),this.update(e||{})}get state(){return this.store.state}get formId(){return this._formId}runValidator(e){return tD(e.validate)?eD[e.type](e.value,e.validate):e.validate(e.value)}handleSubmit(e){return this._handleSubmit(e)}};function oD(e){return e?zE(e)?{formError:oD(e.form).formError,fieldErrors:e.fields}:{formError:e}:{formError:void 0}}function sD(e){switch(e){case`submit`:return`onSubmit`;case`blur`:return`onBlur`;case`mount`:return`onMount`;case`server`:return`onServer`;case`dynamic`:return`onDynamic`;default:return`onChange`}}var cD=class e{constructor(t){this.options={},this.mount=()=>{this.options.defaultValue!==void 0&&!this.getMeta().isTouched&&this.form.setFieldValue(this.name,this.options.defaultValue,{dontUpdateMeta:!0});let e=this.getInfo();e.instance=this,this.update(this.options);let{onMount:t}=this.options.validators||{};if(t){let e=this.runValidator({validate:t,value:{value:this.state.value,fieldApi:this,validationSource:`field`},type:`validate`});e&&this.setMeta(t=>({...t,errorMap:{...t?.errorMap,onMount:e},errorSourceMap:{...t?.errorSourceMap,onMount:`field`}}))}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),()=>{for(let[e,t]of Object.entries(this.timeoutIds.validations))t&&(clearTimeout(t),this.timeoutIds.validations[e]=null);for(let[e,t]of Object.entries(this.timeoutIds.listeners))t&&(clearTimeout(t),this.timeoutIds.listeners[e]=null);for(let[e,t]of Object.entries(this.timeoutIds.formListeners))t&&(clearTimeout(t),this.timeoutIds.formListeners[e]=null);let e=this.form.fieldInfo[this.name];if(e&&e.instance===this){for(let[t,n]of Object.entries(e.validationMetaMap))n?.lastAbortController.abort(),e.validationMetaMap[t]=void 0;this.form.baseStore.setState(e=>({...e,fieldMetaBase:{...e.fieldMetaBase,[this.name]:{...nD,isTouched:e.fieldMetaBase[this.name]?.isTouched??nD.isTouched,isBlurred:e.fieldMetaBase[this.name]?.isBlurred??nD.isBlurred,isDirty:e.fieldMetaBase[this.name]?.isDirty??nD.isDirty}}})),e.instance=null,this.options.listeners?.onUnmount?.({value:this.state.value,fieldApi:this}),this.form.options.listeners?.onFieldUnmount?.({formApi:this.form,fieldApi:this})}}},this.update=e=>{this.options=e,this.name=e.name,!this.state.meta.isTouched&&this.options.defaultValue!==void 0&&(BE(this.form.getFieldValue(this.name),e.defaultValue)||this.form.setFieldValue(this.name,e.defaultValue,{dontUpdateMeta:!0,dontValidate:!0,dontRunListeners:!0})),this.form.getFieldMeta(this.name)||this.form.setFieldMeta(this.name,this.state.meta)},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(e,t)=>{this.form.setFieldValue(this.name,e,UE(t,{dontRunListeners:!0,dontValidate:!0})),t?.dontRunListeners||this.triggerOnChangeListener(),t?.dontValidate||this.validate(`change`)},this.getMeta=()=>this.store.state.meta,this.setMeta=e=>this.form.setFieldMeta(this.name,e),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(e,t)=>{this.form.pushFieldValue(this.name,e,UE(t,{dontRunListeners:!0})),t?.dontRunListeners||this.triggerOnChangeListener()},this.insertValue=(e,t,n)=>{this.form.insertFieldValue(this.name,e,t,UE(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.replaceValue=(e,t,n)=>{this.form.replaceFieldValue(this.name,e,t,UE(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.removeValue=(e,t)=>{this.form.removeFieldValue(this.name,e,UE(t,{dontRunListeners:!0})),t?.dontRunListeners||this.triggerOnChangeListener()},this.swapValues=(e,t,n)=>{this.form.swapFieldValues(this.name,e,t,UE(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.moveValue=(e,t,n)=>{this.form.moveFieldValues(this.name,e,t,UE(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.clearValues=e=>{this.form.clearFieldValues(this.name,UE(e,{dontRunListeners:!0})),e?.dontRunListeners||this.triggerOnChangeListener()},this.getLinkedFields=t=>{let n=Object.values(this.form.fieldInfo),r=[];for(let i of n){if(!i.instance||!(i.instance instanceof e))continue;let{onChangeListenTo:n,onBlurListenTo:a}=i.instance.options.validators||{};t===`change`&&n?.includes(this.name)&&r.push(i.instance),t===`blur`&&a?.includes(this.name)&&r.push(i.instance)}return r},this.validateSync=(e,t)=>{let n=LE(e,{...this.options,form:this.form,fieldName:this.name,validationLogic:this.form.options.validationLogic||ZE}),r=this.getLinkedFields(e).reduce((t,n)=>{let r=LE(e,{...n.options,form:n.form,fieldName:n.name,validationLogic:n.form.options.validationLogic||ZE});return r.forEach(e=>{e.field=n}),t.concat(r)},[]),i=!1;mE(()=>{let e=(e,n)=>{let r=uD(n.cause),a=n.validate?lD(e.runValidator({validate:n.validate,value:{value:e.store.state.value,validationSource:`field`,fieldApi:e},type:`validate`})):void 0,o=t[r],{newErrorValue:s,newSource:c}=HE({formLevelError:o,fieldLevelError:a});e.state.meta.errorMap?.[r]!==s&&e.setMeta(e=>({...e,errorMap:{...e.errorMap,[r]:s},errorSourceMap:{...e.errorSourceMap,[r]:c}})),s&&(i=!0)};for(let t of n)e(this,t);for(let t of r)t.validate&&e(t.field,t)});let a=uD(`submit`);return this.state.meta.errorMap?.[a]&&e!==`submit`&&!i&&this.setMeta(e=>({...e,errorMap:{...e.errorMap,[a]:void 0},errorSourceMap:{...e.errorSourceMap,[a]:void 0}})),{hasErrored:i}},this.validateAsync=async(e,t)=>{let n=RE(e,{...this.options,form:this.form,fieldName:this.name,validationLogic:this.form.options.validationLogic||ZE}),r=await t,i=this.getLinkedFields(e).reduce((t,n)=>{let r=RE(e,{...n.options,form:n.form,fieldName:n.name,validationLogic:n.form.options.validationLogic||ZE});return r.forEach(e=>{e.field=n}),t.concat(r)},[]),a=[],o=[],s=n.some(e=>e.validate),c=Array.from(new Set(i.filter(e=>e.validate).map(e=>e.field)));mE(()=>{s&&this.startValidation();for(let e of c)e.startValidation()});let l=(e,t,n)=>{let i=uD(t.cause),a=e.getInfo();a.validationMetaMap[i]?.lastAbortController.abort();let o=new AbortController;a.validationMetaMap[i]={lastAbortController:o},n.push(new Promise(async n=>{let a;try{a=await new Promise((n,r)=>{e.timeoutIds.validations[t.cause]&&(clearTimeout(e.timeoutIds.validations[t.cause]),e.endValidation()),e.timeoutIds.validations[t.cause]=setTimeout(async()=>{if(o.signal.aborted)return n(void 0);try{n(await this.runValidator({validate:t.validate,value:{value:e.store.state.value,fieldApi:e,signal:o.signal,validationSource:`field`},type:`validateAsync`}))}catch(e){r(e)}},t.debounceMs)})}catch(e){a=e}if(o.signal.aborted)return n(void 0);let s=lD(a),c=r[e.name]?.[i],{newErrorValue:l,newSource:u}=HE({formLevelError:c,fieldLevelError:s});if(e.getInfo().instance!==e)return n(void 0);e.setMeta(e=>({...e,errorMap:{...e?.errorMap,[i]:l},errorSourceMap:{...e.errorSourceMap,[i]:u}})),n(l)}))};for(let e of n)e.validate&&l(this,e,a);for(let e of i)e.validate&&l(e.field,e,o);let u=[];return(a.length||o.length)&&(u=await Promise.all(a),await Promise.all(o)),mE(()=>{s&&this.endValidation();for(let e of c)e.endValidation()}),u.filter(Boolean)},this.validate=(e,t)=>{if(!this.state.meta.isTouched)return[];let n=t?.skipGroupValidation?[]:Array.from(this.form.formGroupApis).filter(e=>this.name.startsWith(e.name)),r=(t?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(e)).fieldsErrorMap[this.name]??{};if(!t?.skipFormValidation)for(let t of n){if(t.state.meta.submissionAttempts===0)continue;let{fieldsErrorMap:n}=this.form.validateSync(e,{group:t,dontUpdateFormErrorMap:!0,filterFieldNames:e=>XE(t.name,e)});r={...r,...n[this.name]??{}}}let{hasErrored:i}=this.validateSync(e,r),a=new WeakMap;for(let t of n){let{hasErrored:n}=t.validateSync(e,{},{skipRelatedFieldValidation:!0});a.set(t,n)}if(i&&!this.options.asyncAlways){this.getInfo().validationMetaMap[uD(e)]?.lastAbortController.abort();let t=[];for(let r of n)r.getInfo().validationMetaMap[uD(e)]?.lastAbortController.abort(),t.push(r.state.meta.errors);return[...this.state.meta.errors,...t.flat()]}let o=t?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(e),s=this.validateAsync(e,o),c=[];for(let t of n)a.get(t)&&!t.options.asyncAlways||c.push(t.validateAsync(e,o,{skipRelatedFieldValidation:!0}));return c.length===0?s:Promise.all([s,...c]).then(e=>e.flat())},this.handleChange=e=>{this.setValue(e)},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(e=>({...e,isTouched:!0})),this.state.meta.isBlurred||this.setMeta(e=>({...e,isBlurred:!0})),this.validate(`blur`),this.triggerOnBlurListener()},this.setErrorMap=e=>{this.setMeta(t=>({...t,errorMap:{...t.errorMap,...e}}))},this.parseValueWithSchema=e=>eD.validate({value:this.state.value,validationSource:`field`},e),this.parseValueWithSchemaAsync=e=>eD.validateAsync({value:this.state.value,validationSource:`field`},e),this.triggerOnBlurListener=()=>{let e=this.form.options.listeners?.onBlurDebounceMs;e&&e>0?(this.timeoutIds.formListeners.blur&&clearTimeout(this.timeoutIds.formListeners.blur),this.timeoutIds.formListeners.blur=setTimeout(()=>{this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this})},e)):this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onBlurDebounceMs;t&&t>0?(this.timeoutIds.listeners.blur&&clearTimeout(this.timeoutIds.listeners.blur),this.timeoutIds.listeners.blur=setTimeout(()=>{this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this})},t)):this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this})},this.triggerOnChangeListener=()=>{let e=this.form.options.listeners?.onChangeDebounceMs;e&&e>0?(this.timeoutIds.formListeners.change&&clearTimeout(this.timeoutIds.formListeners.change),this.timeoutIds.formListeners.change=setTimeout(()=>{this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this})},e)):this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onChangeDebounceMs;t&&t>0?(this.timeoutIds.listeners.change&&clearTimeout(this.timeoutIds.listeners.change),this.timeoutIds.listeners.change=setTimeout(()=>{this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this})},t)):this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});for(let e of this.form.formGroupApis)XE(e.name,this.name)&&e.triggerOnChangeListener()},this.triggerOnSubmitListener=()=>{this.options.listeners?.onSubmit?.({value:this.state.value,fieldApi:this})},this.form=t.form,this.name=t.name,this.options=t,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=xE(e=>{this.form.store.get();let n=this.form.getFieldMeta(this.name)??{...nD,...t.defaultMeta},r=this.form.getFieldValue(this.name);return!n.isTouched&&r===void 0&&this.options.defaultValue!==void 0&&!BE(r,this.options.defaultValue)&&(r=this.options.defaultValue),e&&e.value===r&&e.meta===n?e:{value:r,meta:n}})}get state(){return this.store.state}runValidator(e){return tD(e.validate)?eD[e.type](e.value,e.validate):e.validate(e.value)}startValidation(){this.setMeta(e=>{let t=e._pendingValidationsCount+1;return{...e,_pendingValidationsCount:t,isValidating:t>0&&!e.isValidating||e.isValidating}})}endValidation(){this.setMeta(e=>{let t=Math.max(0,e._pendingValidationsCount-1);return{...e,_pendingValidationsCount:t,isValidating:t===0&&e.isValidating?!1:e.isValidating}})}};function lD(e){if(e)return e}function uD(e){switch(e){case`submit`:return`onSubmit`;case`blur`:return`onBlur`;case`mount`:return`onMount`;case`server`:return`onServer`;case`dynamic`:return`onDynamic`;default:return`onChange`}}function dD(e){return{isSubmitted:e.isSubmitted??!1,isSubmitting:e.isSubmitting??!1,isValidating:e.isValidating??!1,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??!1}}function fD(e){return{...nD,...e,errors:[],isPristine:!0,isValid:!0,isDefaultValue:!0,isFieldsValidating:!1,isFieldsValid:!0,isGroupValid:!0,canSubmit:!0,isSubmitting:!1,isSubmitted:!1,isValidating:!1,submissionAttempts:0,isSubmitSuccessful:!1}}var pD=class e{constructor(t){this.options={},this.setFormGroupState=e=>{this.form.baseStore.setState(t=>{let n=t.formGroupStateBase[this.name]??dD({});return{...t,formGroupStateBase:{...t.formGroupStateBase,[this.name]:e(n)}}})},this._lastDistributedFieldNames={},this.update=e=>{this.options=e,this.name=e.name,!this.state.meta.isTouched&&this.options.defaultValue!==void 0&&(BE(this.form.getFieldValue(this.name),e.defaultValue)||this.form.setFieldValue(this.name,e.defaultValue,{dontUpdateMeta:!0,dontValidate:!0,dontRunListeners:!0})),this.form.getFieldMeta(this.name)||this.form.setFieldMeta(this.name,{...nD,...this.options.defaultMeta})},this.mount=()=>{this.update(this.options),this.form.formGroupApis.add(this),this.fieldInfo.instance=this,this.form.baseStore.setState(e=>({...e,formGroupStateBase:{...e.formGroupStateBase,[this.name]:e.formGroupStateBase[this.name]??dD({...this.options.defaultState})}}));let{onMount:e}=this.options.validators||{};if(e){let t=this.runValidator({validate:e,value:{value:this.state.value,groupApi:this,validationSource:`form`},type:`validate`}),n=t,r;hD(t)&&(n=t.group,r=t.fields);let i=mD(n);i&&this.setMeta(e=>({...e,errorMap:{...e.errorMap,onMount:i},errorSourceMap:{...e.errorSourceMap,onMount:`field`}})),this.distributeFieldErrors(`onMount`,r)}return this.options.listeners?.onMount?.({value:this.state.value,groupApi:this}),()=>{for(let[e,t]of Object.entries(this.timeoutIds.validations))t&&(clearTimeout(t),this.timeoutIds.validations[e]=null);for(let[e,t]of Object.entries(this.timeoutIds.listeners))t&&(clearTimeout(t),this.timeoutIds.listeners[e]=null);for(let[e,t]of Object.entries(this.timeoutIds.formListeners))t&&(clearTimeout(t),this.timeoutIds.formListeners[e]=null);if(this.fieldInfo.instance===this){for(let[e,t]of Object.entries(this.fieldInfo.validationMetaMap))t?.lastAbortController.abort(),this.fieldInfo.validationMetaMap[e]=void 0;this.form.formGroupApis.delete(this),this.form.baseStore.setState(e=>({...e,formGroupStateBase:{...e.formGroupStateBase,[this.name]:dD({})}})),this.fieldInfo.instance=null,this.options.listeners?.onUnmount?.({value:this.state.value,groupApi:this})}}},this.setValue=(e,t)=>{this.form.setFieldValue(this.name,e,UE(t,{dontRunListeners:!0,dontValidate:!0})),t?.dontRunListeners||this.triggerOnChangeListener(),t?.dontValidate||this.validate(`change`)},this.getMeta=()=>this.store.state.meta,this.setMeta=e=>this.form.setFieldMeta(this.name,e),this.getInfo=()=>this.fieldInfo,this.getRelatedFields=()=>{let e=Object.values(this.form.fieldInfo),t=[];for(let n of e)n.instance&&n.instance instanceof cD&&n.instance.name.startsWith(this.name)&&t.push(n.instance);return t},this.getRelatedFieldMetasDerived=()=>{let e=Object.entries(this.form.fieldMetaDerived.state),t=[];for(let[n,r]of e)n!==this.name&&XE(this.name,n)&&t.push({...r,name:n});return t},this.buildChildFieldName=e=>e===``?this.name:e.startsWith(`[`)?`${this.name}${e}`:`${this.name}.${e}`,this.distributeFieldErrors=(e,t)=>{let n=this._lastDistributedFieldNames[e]??new Set,r=new Set;if(t)for(let[e,n]of Object.entries(t))n!=null&&n!==!1&&r.add(this.buildChildFieldName(e));let i=new Set([...n,...r]),a=!1;for(let n of i){let r=n.startsWith(this.name+`[`)?n.slice(this.name.length):n.slice(this.name.length+1),i=t?.[r],o=this.form.getFieldMeta(n);if(!o&&!i)continue;let s=o?.errorMap[e],{newErrorValue:c,newSource:l}=VE({newFormValidatorError:i,isPreviousErrorFromFormValidator:o?.errorSourceMap[e]===`form`,previousErrorValue:s});c&&(a=!0),(s!==c||o?.errorSourceMap[e]!==l)&&this.form.setFieldMeta(n,(t=nD)=>({...t,errorMap:{...t.errorMap,[e]:c},errorSourceMap:{...t.errorSourceMap,[e]:l}}))}return this._lastDistributedFieldNames[e]=r,a},this.validateSync=(t,n,r={})=>{let i=LE(t,{...this.options,form:this.form,group:this,validationLogic:this.options.validationLogic||this.form.options.validationLogic||ZE}),a=(r.skipRelatedFieldValidation?[]:this.getRelatedFields()).reduce((e,n)=>{let r=LE(t,{...n.options,form:n.form,validationLogic:n.form.options.validationLogic||ZE});return r.forEach(e=>{e.field=n}),e.concat(r)},[]),o=!1;mE(()=>{let t=(t,r)=>{let i=_D(r.cause),a=t===this,s;r.validate&&(s=t.runValidator({validate:r.validate,value:{value:t.store.state.value,validationSource:a?`form`:`field`,...t instanceof e?{groupApi:t}:{fieldApi:t}},type:`validate`}));let c=s,l;a&&hD(s)&&(c=s.group,l=s.fields);let u=mD(c),d=n[i],{newErrorValue:f,newSource:p}=HE({formLevelError:d,fieldLevelError:u});t.state.meta.errorMap?.[i]!==f&&t.setMeta(e=>({...e,errorMap:{...e.errorMap,[i]:f},errorSourceMap:{...e.errorSourceMap,[i]:p}})),f&&(o=!0),a&&this.distributeFieldErrors(i,l)&&(o=!0)};for(let e of i)t(this,e);for(let e of a)e.validate&&t(e.field,e)});let s=_D(`submit`);return this.state.meta.errorMap?.[s]&&t!==`submit`&&!o&&this.setMeta(e=>({...e,errorMap:{...e.errorMap,[s]:void 0},errorSourceMap:{...e.errorSourceMap,[s]:void 0}})),{hasErrored:o}},this.validateAsync=async(t,n,r={})=>{let i=RE(t,{...this.options,form:this.form,group:this,validationLogic:this.options.validationLogic||this.form.options.validationLogic||ZE}),a=await n,o=r.skipRelatedFieldValidation?[]:this.getRelatedFields(),s=o.reduce((e,n)=>{let r=RE(t,{...n.options,form:n.form,validationLogic:n.form.options.validationLogic||ZE});return r.forEach(e=>{e.field=n}),e.concat(r)},[]),c=[],l=[],u=i.some(e=>e.validate)||s.some(e=>e.validate);if(u){this.state.meta.isValidating||this.setMeta(e=>({...e,isValidating:!0}));for(let e of o)e.setMeta(e=>({...e,isValidating:!0}))}let d=(t,n,r)=>{let i=_D(n.cause),o=t.getInfo();o.validationMetaMap[i]?.lastAbortController.abort();let s=new AbortController;o.validationMetaMap[i]={lastAbortController:s};let c=t===this;r.push(new Promise(async r=>{let o;try{o=await new Promise((r,i)=>{t.timeoutIds.validations[n.cause]&&clearTimeout(t.timeoutIds.validations[n.cause]),t.timeoutIds.validations[n.cause]=setTimeout(async()=>{if(s.signal.aborted)return r(void 0);try{r(await this.runValidator({validate:n.validate,value:{value:t.store.state.value,signal:s.signal,validationSource:c?`form`:`field`,...t instanceof e?{groupApi:t}:{fieldApi:t}},type:`validateAsync`}))}catch(e){i(e)}},n.debounceMs)})}catch(e){o=e}if(s.signal.aborted)return r(void 0);let l=o,u;c&&hD(o)&&(l=o.group,u=o.fields);let d=mD(l),f=a[t.name]?.[i],{newErrorValue:p,newSource:m}=HE({formLevelError:f,fieldLevelError:d});if(t.getInfo().instance!==t)return r(void 0);t.setMeta(e=>({...e,errorMap:{...e?.errorMap,[i]:p},errorSourceMap:{...e.errorSourceMap,[i]:m}})),c&&this.distributeFieldErrors(i,u),r(p)}))};for(let e of i)e.validate&&d(this,e,c);for(let e of s)e.validate&&d(e.field,e,l);let f=[];if((c.length||l.length)&&(f=await Promise.all(c),await Promise.all(l)),u){this.setMeta(e=>({...e,isValidating:!1}));for(let e of o)e.setMeta(e=>({...e,isValidating:!1}))}return f.filter(Boolean)},this.validateAllFields=async e=>{let t=[];return mE(()=>{Object.values(this.getRelatedFields()).forEach(n=>{t.push(Promise.resolve().then(()=>n.validate(e,{skipFormValidation:!0,skipGroupValidation:!0}))),n.store.state.meta.isTouched||n.setMeta(e=>({...e,isTouched:!0}))})}),(await Promise.all(t)).flat()},this.validateArrayFieldsStartingFrom=(e,t,n)=>this.form.validateArrayFieldsStartingFrom(e,t,n),this.validateField=(e,t)=>this.form.validateField(e,t),this.getFieldValue=e=>this.form.getFieldValue(e),this.getFieldMeta=e=>this.form.getFieldMeta(e),this.setFieldMeta=(e,t)=>this.form.setFieldMeta(e,t),this.setFieldValue=(e,t)=>this.form.setFieldValue(e,t),this.deleteField=e=>this.form.deleteField(e),this.pushFieldValue=(e,t)=>this.form.pushFieldValue(e,t),this.insertFieldValue=(e,t,n)=>this.form.insertFieldValue(e,t,n),this.replaceFieldValue=(e,t,n)=>this.form.replaceFieldValue(e,t,n),this.swapFieldValues=(e,t,n)=>this.form.swapFieldValues(e,t,n),this.moveFieldValues=(e,t,n)=>this.form.moveFieldValues(e,t,n),this.clearFieldValues=e=>this.form.clearFieldValues(e),this.resetField=e=>this.form.resetField(e),this.removeFieldValue=(e,t)=>this.form.removeFieldValue(e,t),this.areRelatedFieldsValid=()=>Object.values(this.getRelatedFields()).every(e=>e.state.meta.isValid),this.validate=(e,t)=>{let{fieldsErrorMap:n}=t?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(e,{dontUpdateFormErrorMap:!0,filterFieldNames:e=>XE(this.name,e)}),{hasErrored:r}=this.validateSync(e,n[this.name]??{},{skipRelatedFieldValidation:t?.skipRelatedFieldValidation});if(r&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[_D(e)]?.lastAbortController.abort(),this.state.meta.errors;let i=t?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(e,{dontUpdateFormErrorMap:!0,filterFieldNames:e=>XE(this.name,e)});return this.validateAsync(e,i,{skipRelatedFieldValidation:t?.skipRelatedFieldValidation})},this.triggerOnChangeListener=()=>{let e=this.form.options.listeners?.onChangeGroupDebounceMs;e&&e>0?(this.timeoutIds.formListeners.change&&clearTimeout(this.timeoutIds.formListeners.change),this.timeoutIds.formListeners.change=setTimeout(()=>{this.form.options.listeners?.onChangeGroup?.({formApi:this.form,groupApi:this})},e)):this.form.options.listeners?.onChangeGroup?.({formApi:this.form,groupApi:this});let t=this.options.listeners?.onChangeDebounceMs;t&&t>0?(this.timeoutIds.listeners.change&&clearTimeout(this.timeoutIds.listeners.change),this.timeoutIds.listeners.change=setTimeout(()=>{this.options.listeners?.onChange?.({value:this.state.value,groupApi:this})},t)):this.options.listeners?.onChange?.({value:this.state.value,groupApi:this})},this.triggerOnSubmitListener=()=>{this.options.listeners?.onSubmit?.({value:this.state.value,groupApi:this})},this._handleSubmit=async e=>{this.setFormGroupState(e=>({...e,isSubmitted:!1,submissionAttempts:e.submissionAttempts+1,isSubmitSuccessful:!1})),mE(()=>{Object.values(this.getRelatedFields()).forEach(e=>{e.state.meta.isTouched||e.setMeta(e=>({...e,isTouched:!0}))})});let t=e??this.options.onSubmitMeta;this.setFormGroupState(e=>({...e,isSubmitting:!0}));let n=()=>{this.setFormGroupState(e=>({...e,isSubmitting:!1}))};if(await this.validateAllFields(`submit`),!this.areRelatedFieldsValid()){n(),this.options.onGroupSubmitInvalid?.({value:this.state.value,groupApi:this,meta:t});return}if(await this.validate(`submit`,{skipRelatedFieldValidation:!0}),!this.areRelatedFieldsValid()||!this.state.meta.isValid){n(),this.options.onGroupSubmitInvalid?.({value:this.state.value,groupApi:this,meta:t});return}mE(()=>{Object.values(this.getRelatedFields()).forEach(e=>{e.options.listeners?.onGroupSubmit?.({value:e.state.value,fieldApi:e})})}),this.options.listeners?.onSubmit?.({groupApi:this,value:this.state.value});try{await this.options.onGroupSubmit?.({value:this.state.value,groupApi:this,meta:t}),mE(()=>{this.setFormGroupState(e=>({...e,isSubmitted:!0,isSubmitSuccessful:!0})),n()})}catch(e){throw this.setFormGroupState(e=>({...e,isSubmitSuccessful:!1})),n(),e}},this.form=t.form,this.name=t.name,this.options=t,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.fieldInfo={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}},this.store=xE(e=>{this.form.formGroupMetaDerived.get(),this.form.baseStore.get();let n=this.form.getFormGroupMeta(this.name)??fD(t.defaultMeta),r=this.form.getFieldValue(this.name);return!n.isTouched&&r===void 0&&this.options.defaultValue!==void 0&&!BE(r,this.options.defaultValue)&&(r=this.options.defaultValue),e&&e.value===r&&e.meta===n?e:{value:r,meta:n}}),this.handleSubmit=this.handleSubmit.bind(this)}get state(){return this.store.state}runValidator(e){if(tD(e.validate)){let t=eD[e.type](e.value,e.validate);return e.type===`validate`?gD(t):t.then(gD)}return e.validate(e.value)}handleSubmit(e){return this._handleSubmit(e)}};function mD(e){if(e)return e}function hD(e){return!!e&&typeof e==`object`&&`fields`in e}function gD(e){if(!e||typeof e!=`object`||!(`form`in e)&&!(`fields`in e))return e;let{form:t,fields:n,...r}=e;return{...r,group:t,fields:n}}function _D(e){switch(e){case`submit`:return`onSubmit`;case`blur`:return`onBlur`;case`mount`:return`onMount`;case`server`:return`onServer`;case`dynamic`:return`onDynamic`;default:return`onChange`}}function vD(e,t){if(!t)return;let n=Object.assign({},e,{state:YE(e.state)});t(n),n.fieldInfo!==e.fieldInfo&&(e.fieldInfo=n.fieldInfo),n.options!==e.options&&(e.options=n.options);let r=Object.keys({values:null,validationMetaMap:null,fieldMetaBase:null,formGroupStateBase:null,isSubmitting:null,isSubmitted:null,isValidating:null,submissionAttempts:null,isSubmitSuccessful:null,_force_re_eval:null}).reduce((t,r)=>(e.state[r]!==n.state[r]&&(t[r]=n.state[r]),t),{});return mE(()=>{Object.keys(r).length&&e.baseStore.setState(e=>({...e,...r})),n.state.errorMap!==e.state.errorMap&&e.setErrorMap(n.state.errorMap)}),n}var yD=Je();function bD(e,t){return e===t}function xD(e,t=e=>e,n){let r=n?.compare??bD,i=(0,q.useCallback)(t=>{let{unsubscribe:n}=e.subscribe(t);return n},[e]),a=(0,q.useCallback)(()=>e.get(),[e]);return(0,yD.useSyncExternalStoreWithSelector)(i,a,a,t,r)}var SD=typeof window<`u`?q.useLayoutEffect:q.useEffect;function CD(e){let[t,n]=(0,q.useState)(()=>({form:e.form,name:e.name})),[r,i]=(0,q.useState)(()=>new cD({...e})),a=r;(t.form!==e.form||t.name!==e.name)&&(a=new cD({...e}),i(a),n({form:e.form,name:e.name}));let o=xD(a.store,e.mode===`array`?e=>e.meta._arrayVersion||0:e=>e.value),s=xD(a.store,e=>e.meta.isTouched),c=xD(a.store,e=>e.meta.isBlurred),l=xD(a.store,e=>e.meta.isDirty),u=xD(a.store,e=>e.meta.errorMap),d=xD(a.store,e=>e.meta.errorSourceMap),f=xD(a.store,e=>e.meta.isValidating),p=(0,q.useMemo)(()=>({...a,get state(){return{value:e.mode===`array`?a.state.value:o,get meta(){return{...a.state.meta,isTouched:s,isBlurred:c,isDirty:l,errorMap:u,errorSourceMap:d,isValidating:f}}}}}),[a,e.mode,o,s,c,l,u,d,f]);return SD(a.mount,[a]),SD(()=>{a.update(e)}),p}var wD=(({children:e,...t})=>{let n=CD(t),r=(0,q.useMemo)(()=>EE(e,n),[e,n]);return(0,Y.jsx)(Y.Fragment,{children:r})});function TD(){return(0,q.useState)(()=>qE())[0]}var ED=q,DD=`18.3.1`.split(`.`)[0]===`17`?TD:ED.useId;function OD(e){let[t,n]=(0,q.useState)(()=>({form:e.form,name:e.name})),[r,i]=(0,q.useState)(()=>new pD({...e}));(t.form!==e.form||t.name!==e.name)&&(i(new pD({...e})),n({form:e.form,name:e.name}));let a=xD(r.store,e=>e.value),o=xD(r.store,e=>e.meta.isTouched),s=xD(r.store,e=>e.meta.isBlurred),c=xD(r.store,e=>e.meta.isDirty),l=xD(r.store,e=>e.meta.errorMap),u=xD(r.store,e=>e.meta.errorSourceMap),d=xD(r.store,e=>e.meta.isValidating),f=xD(r.store,e=>e.meta.isSubmitting),p=xD(r.store,e=>e.meta.isSubmitted),m=xD(r.store,e=>e.meta.submissionAttempts),h=xD(r.store,e=>e.meta.isSubmitSuccessful),g=xD(r.store,e=>e.meta.canSubmit),_=xD(r.store,e=>e.meta.isValid),v=xD(r.store,e=>e.meta.isFieldsValid),y=xD(r.store,e=>e.meta.isFieldsValidating),b=xD(r.store,e=>e.meta.isGroupValid),x=(0,q.useMemo)(()=>({...r,handleSubmit:((...e)=>r._handleSubmit(...e)),get state(){return{...r.state,value:a,get meta(){return{...r.state.meta,isTouched:o,isBlurred:s,isDirty:c,errorMap:l,errorSourceMap:u,isValidating:d,isSubmitting:f,isSubmitted:p,submissionAttempts:m,isSubmitSuccessful:h,canSubmit:g,isValid:_,isFieldsValid:v,isFieldsValidating:y,isGroupValid:b}}}}}),[r,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b]);return SD(r.mount,[r]),SD(()=>{r.update(e)}),x}var kD=(({children:e,...t})=>{let n=OD(t),r=(0,q.useMemo)(()=>EE(e,n),[e,n]);return(0,Y.jsx)(Y.Fragment,{children:r})});function AD({form:e,selector:t=e=>e,children:n}){let r=xD(e.store,t);return(0,Y.jsx)(Y.Fragment,{children:EE(n,r)})}function jD(e){let t=DD(),[n,r]=(0,q.useState)(e?.formId),[i,a]=(0,q.useState)(()=>new aD({...e,formId:e?.formId??t}));if(n!==e?.formId){let n=e?.formId??t;a(new aD({...e,formId:n})),r(n)}let o=(0,q.useMemo)(()=>{let e={...i,handleSubmit:((...e)=>i._handleSubmit(...e)),get formId(){return i._formId},get state(){return i.store.state}};return e.Field=function(e){return(0,Y.jsx)(wD,{...e,form:i})},e.FormGroup=function(e){return(0,Y.jsx)(kD,{...e,form:i})},e.Subscribe=function(e){return(0,Y.jsx)(AD,{form:i,selector:e.selector,children:e.children})},e},[i]);SD(i.mount,[]),SD(()=>{i.update(e)});let s=(0,q.useRef)(!1);return SD(()=>{s.current&&e?.transform&&vD(i,e.transform)},[i,e?.transform]),SD(()=>{s.current=!0}),o}var MD=Ti(V),ND=Ti(I({message:V}));function PD(e){for(let t of e.errors){let e=Gr(Lr(Zr(ND(t),e=>e.message),()=>MD(t)));if(e!==void 0&&e.length>0)return e}}var FD={neutral:`progress-neutral`,primary:`progress-primary`,secondary:`progress-secondary`,accent:`progress-accent`,success:`progress-success`,info:`progress-info`,warning:`progress-warning`,error:`progress-error`},ID=(0,q.forwardRef)(function({className:e,tone:t=`primary`,...n},r){return(0,Y.jsx)(`progress`,{...n,"data-complete":n.value!==void 0&&Number(n.value)>=Number(n.max??1)?`true`:void 0,className:E(`progress caps-gooey-motion caps-gooey-progress w-full`,FD[t],e),ref:r})});(0,q.forwardRef)(function({label:e,value:t,max:n,tone:r=`info`,className:i,...a},o){return(0,Y.jsxs)(`div`,{...a,ref:o,className:E(`caps-game-meter`,i),children:[(0,Y.jsxs)(`div`,{className:`caps-game-meter-readout`,children:[(0,Y.jsx)(`span`,{children:e}),(0,Y.jsxs)(`span`,{className:`caps-game-meter-value`,children:[t,` / `,n]})]}),(0,Y.jsx)(ID,{"aria-label":e,value:t,max:n,tone:r})]})});function LD({className:e,items:t,onCancel:n,onRemove:r,onRetry:i,rowClassName:a}){return t.length?(0,Y.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,Y.jsx)(BD,{item:e,onCancel:n,onRemove:r,onRetry:i,...a===void 0?{}:{rowClassName:a}},e.id))}):null}function RD({action:e,id:t,onAction:n,retry:r=!1}){return e?(0,Y.jsx)(Tt,{"aria-label":e.accessibleLabel,title:e.label,variant:`ghost`,size:`xs`,className:`motion-reduce:transition-none`,icon:r?(0,Y.jsx)(dT,{}):(0,Y.jsx)(Ln,{}),onClick:()=>void n(t),type:`button`}):null}function zD({item:e}){return(0,Y.jsxs)(`div`,{className:`min-w-0`,children:[(0,Y.jsx)(`span`,{className:`block min-w-0 truncate`,title:e.name,children:e.name}),(0,Y.jsx)(`div`,{className:`caps-upload-details`,children:(0,Y.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 BD({item:e,onCancel:t,onRemove:n,onRetry:r,rowClassName:i}){return(0,Y.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,Y.jsx)(`img`,{alt:``,className:`caps-upload-preview mask mask-squircle size-8 shrink-0 object-cover`,src:e.preview.url}):(0,Y.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,Y.jsx)(lT,{className:`size-4`})}),(0,Y.jsx)(zD,{item:e}),(0,Y.jsx)(VD,{actions:e.actions,id:e.id,onCancel:t,onRemove:n,onRetry:r}),(0,Y.jsx)(ID,{"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 VD({actions:e,id:t,onCancel:n,onRemove:r,onRetry:i}){return(0,Y.jsxs)(`div`,{className:`caps-upload-actions flex min-w-0 flex-wrap justify-end gap-xs`,children:[(0,Y.jsx)(RD,{action:e.retry,id:t,onAction:i,retry:!0}),(0,Y.jsx)(RD,{action:e.cancel,id:t,onAction:n}),(0,Y.jsx)(RD,{action:e.remove,id:t,onAction:r})]})}var HD=q.createContext(void 0);function UD(e){let t=q.useContext(HD);if(t===void 0&&!e)throw Error(on(47));return t}var WD={...D,disabled:e=>e.disabled,instantType:e=>e.instantType===`trigger-change`&&!D.open(e)?void 0:e.instantType,openMethod:e=>e.openMethod,openChangeReason:e=>e.openChangeReason,isPressOpenedByTrigger:(e,t)=>e.openChangeReason===`trigger-press`&&D.isOpenedByTrigger(e,t),isTouchPressOpen:(e,t)=>t&&e.openMethod===`touch`&&e.openChangeReason===`trigger-press`,hasTriggerFocusGuards:(e,t)=>D.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},GD=class extends se{constructor(e,t,n){let r=new Ke;super(KD(e,r,t,n),qD(r),WD)}setOpen=(e,t)=>{let r=t.reason===he,i=t.reason===`trigger-press`&&t.event.detail===0,a=!e&&(t.reason===`escape-key`||t.reason==null),o=n(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=En(this.state,e,t.trigger,o());n.openChangeReason=t.reason,this.update(n)};r?(this.context.stickIfOpen=!0,this.context.stickIfOpenTimeout.start(500,()=>{this.context.stickIfOpen=!1}),qC.flushSync(c)):c();let l;i?l=`click`:a?l=`dismiss`:t.reason===`focus-out`&&(l=`focus`),this.set(`instantType`,l)}};function KD(e,t,n,r=!1){let i={...Ue(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 qD(e){return{popupRef:q.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerFocusTargetRef:q.createRef(),beforeTriggerFocusGuardRef:q.createRef(),beforeContentFocusGuardRef:q.createRef(),stickIfOpenTimeout:new xn,stickIfOpen:!0,triggerElements:e}}var JD=fn(function({props:e}){let{children:t,open:n,defaultOpen:r=!1,onOpenChange:i,onOpenChangeComplete:a,modal:o=!1,handle:s,triggerId:l,defaultTriggerId:u=null}=e,d=XD(s,{modal:o,open:r,openProp:n,activeTriggerId:u,triggerIdProp:l});d.useControlledProp(`openProp`,n),d.useControlledProp(`triggerIdProp`,l);let f=d.useState(`open`),p=d.useState(`mounted`),m=d.useState(`payload`);d.useContextCallback(`onOpenChange`,i),d.useContextCallback(`onOpenChangeComplete`,a),sn(d,f),nn(d);let{forceUnmount:h}=_n(f,d,()=>{d.context.stickIfOpen=!0,d.set(`openChangeReason`,null)});d.useSyncedValues({modal:o}),q.useEffect(()=>{f||d.context.stickIfOpenTimeout.clear()},[d,f]),q.useImperativeHandle(e.actionsRef,()=>({unmount:h,close:()=>d.setOpen(!1,N(c))}),[h,d]);let g=f||p||s!=null;return(0,Y.jsxs)(HD.Provider,{value:d,children:[s&&(0,Y.jsx)(xe,{handle:s,store:d}),g&&(0,Y.jsx)(ZD,{store:d,modal:o}),typeof t==`function`?t({payload:m}):t]})});function YD(e){return UD(!0)?(0,Y.jsx)(JD,{props:e}):(0,Y.jsx)(Nt,{children:(0,Y.jsx)(JD,{props:e})})}function XD(e,t){let n=it((e,n)=>new GD(t,e,n));return q.useEffect(()=>n.context.stickIfOpenTimeout.disposeEffect(),[n]),n}function ZD({store:e,modal:t}){let n=e.useState(`floatingRootContext`),r=_t(n,{outsidePressEvent:{mouse:t===`trap-focus`?`sloppy`:`intentional`,touch:`sloppy`}}),i=r.reference,a=r.floating;return Ft(e,{activeTriggerProps:i,inactiveTriggerProps:i,popupProps:a}),null}function QD(e,t){function n(n,r,i){let a=n.currentTarget;qC.flushSync(()=>{e.setOpen(!1,N(Ht,n.nativeEvent,a))}),Rn(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&&ke(t,r)?e.context.beforeContentFocusGuardRef.current?.focus():n(t,1,r)}return{handlePreFocusGuardFocus:r,handleFocusTargetFocus:i}}var $D=ae(function(e,t){let{render:n,className:r,style:i,disabled:a=!1,nativeButton:s=!0,handle:c,payload:l,openOnHover:u=!1,delay:d=300,closeDelay:f=0,id:p,...m}=e,h=UD(!0),g=Ie(c)??h;if(!g)throw Error(on(74));let v=tn(p),y=g.useState(`isTriggerActive`,v),b=g.useState(`floatingRootContext`),x=g.useState(`isOpenedByTrigger`,v),S=g.useState(`triggerPopupId`,v),C=q.useRef(null),{registerTrigger:w,isMountedByThisTrigger:T}=Sn(v,C,g,{payload:l,disabled:a,openOnHover:u,closeDelay:f}),E=g.useState(`isPressOpenedByTrigger`,v),D=g.useState(`isTouchPressOpen`,u),O=g.useState(`hasTriggerFocusGuards`,v),k=YC(b,{enabled:!a&&u&&!D,mouseOnly:!0,move:!1,handleClose:rw(),restMs:d,delay:{close:f},triggerElementRef:C,isActiveTrigger:y,isClosing:()=>g.select(`transitionStatus`)===`ending`}),A=Ct(()=>g.context.stickIfOpen),j=wt(b,{stickIfOpen:A}),te=we(()=>g.select(`open`),e=>{g.set(`openMethod`,e)}),ne=g.useState(`triggerProps`,T),{getButtonProps:re,buttonRef:ie}=ee({disabled:a,native:s}),ae={open(e){return E?o.open(e):Lt.open(e)}},{handlePreFocusGuardFocus:oe,handleFocusTargetFocus:se}=QD(g,C),ce=gn(`button`,e,{state:{disabled:a,open:x},ref:[ie,t,w,C],props:[j.reference,k,ne,te,{[ct]:``,id:v,"aria-haspopup":`dialog`,"aria-expanded":x,"aria-controls":S},m,re],stateAttributesMapping:ae}),le=(0,Y.jsx)(q.Fragment,{children:ce},v);return O?(0,Y.jsxs)(q.Fragment,{children:[(0,Y.jsx)(_,{ref:g.context.beforeTriggerFocusGuardRef,onFocus:oe}),le,(0,Y.jsx)(_,{ref:g.context.triggerFocusTargetRef,onFocus:se})]}):le}),eO=q.createContext(void 0);function tO(){let e=q.useContext(eO);if(e===void 0)throw Error(on(45));return e}var nO=q.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e;return UD().useState(`mounted`)||n?(0,Y.jsx)(eO.Provider,{value:n,children:(0,Y.jsx)(Un,{ref:t,...r})}):null}),rO=q.createContext(void 0);function iO(){let e=q.useContext(rO);if(!e)throw Error(on(46));return e}function aO(e){let{nodeId:t,externalTree:n,rootContext:r}=e,i=r.useState(`referenceElement`),a=r.useState(`floatingElement`),o=r.useState(`domReferenceElement`),s=r.useState(`open`),c=r.useState(`floatingId`),[l,u]=q.useState(null),d=q.useRef(null),f=Mn(n),p=q.useMemo(()=>({reference:i,floating:a,domReference:o}),[i,a,o]),m=tT({...e,elements:{...p,...l&&{reference:l}}}),h=q.useCallback(e=>{let t=Ye(e)?{getBoundingClientRect:()=>e.getBoundingClientRect(),getClientRects:()=>e.getClientRects(),contextElement:e}:e;u(t),m.refs.setReference(t)},[m.refs]),g=q.useMemo(()=>({...m.refs,setPositionReference:h,domReference:d}),[m.refs,h]),_=q.useMemo(()=>({...m.elements,domReference:o}),[m.elements,o]),v=q.useMemo(()=>({...m,dataRef:r.context.dataRef,open:s,onOpenChange:r.setOpen,events:r.context.events,floatingId:c,refs:g,elements:_,nodeId:t,rootStore:r}),[m,g,_,t,r,s,c]);return ot(()=>{o&&(d.current=o)},[o]),ot(()=>{r.context.dataRef.current.floatingContext=v;let e=f?.nodesRef.current.find(e=>e.id===t);e&&(e.context=v)}),q.useMemo(()=>({...m,context:v,refs:g,elements:_,rootStore:r}),[m,g,_,v,r])}var oO=e=>({name:`arrow`,options:e,async fn(t){let{x:n,y:r,placement:i,rects:a,platform:o,elements:s,middlewareData:c}=t,{element:l,padding:u=0}=sb(e,t)||{};if(l==null)return{};let d=Tb(u),f={x:n,y:r},p=pb(i),m=db(p),h=await o.getDimensions(l),g=p===`y`,_=g?`top`:`left`,v=g?`bottom`:`right`,y=g?`clientHeight`:`clientWidth`,b=a.reference[m]+a.reference[p]-f[p]-a.floating[m],x=f[p]-a.reference[p],S=s.floating[y]||a.floating[m],C=b/2-x/2,w=S/2-h[m]/2-1,T=Math.min(d[_],w),E=Math.min(d[v],w),ee=T,D=S-h[m]-E,O=S/2-h[m]/2+C,k=ob(ee,O,D),A=!c.arrow&&lb(i)!=null&&O!==k&&a.reference[m]/2-(O<ee?T:E)-h[m]/2<0,j=A?O<ee?O-ee:O-D:0;return{[p]:f[p]+j,data:{[p]:k,centerOffset:O-k-j,...A&&{alignmentOffset:j}},reset:A}}}),sO=(e,t)=>{let{name:n,fn:r}=oO(e);return{name:n,fn:r,options:[e,t]}},cO={name:`hide`,async fn(e){let{width:t,height:n,x:r,y:i}=e.rects.reference,a=t===0&&n===0&&r===0&&i===0,o=await e.platform.detectOverflow(e,{elementContext:`reference`});return{data:{referenceHidden:o.top-n>=0||o.right-t>=0||o.bottom-n>=0||o.left-t>=0||a}}}},lO={sideX:`left`,sideY:`top`},uO=`--available-width`,dO=`--available-height`,fO=`--anchor-width`,pO=`--anchor-height`,mO=`--transform-origin`,hO=uO,gO=dO;function _O(e,t,n){let r=e===`inline-start`||e===`inline-end`;return{top:`top`,right:r?n?`inline-start`:`inline-end`:`right`,bottom:`bottom`,left:r?n?`inline-end`:`inline-start`:`left`}[t]}function vO(e,t,n){let{rects:r,placement:i}=e;return{side:_O(t,cb(i),n),align:lb(i)||`center`,anchor:{width:r.reference.width,height:r.reference.height},positioner:{width:r.floating.width,height:r.floating.height}}}function yO(e){return bO(e,aO)}function bO(e,t){let{anchor:n,positionMethod:r=`absolute`,side:i=`bottom`,sideOffset:a=0,align:o=`center`,alignOffset:s=0,collisionBoundary:c,collisionPadding:l=5,sticky:u=!1,arrowPadding:d=5,disableAnchorTracking:f=!1,inline:p,keepMounted:m=!1,floatingRootContext:g,mounted:_,collisionAvoidance:v,shift:y,nodeId:b,adaptiveOrigin:x,lazyFlip:S=!1,externalTree:C}=e,w=v.side||`flip`,T=v.align||`flip`,E=v.fallbackAxisSide||`end`,ee=y?.crossAxis??!1,D=y?.rootBoundary,O=typeof n==`function`?n:void 0,k=Ct(O),A=O?k:n,j=Fe(n),te=Fe(_),ne=Ub()===`rtl`,[re,ie]=q.useState(null);!_&&re!==null&&ie(null);let ae=S===`placement`,oe=re?cb(re):null,se=re&&ae?lb(re)||`center`:null,ce=oe||{top:`top`,right:`right`,bottom:`bottom`,left:`left`,"inline-end":ne?`left`:`right`,"inline-start":ne?`right`:`left`}[i],le=se||o,ue=le===`center`?ce:`${ce}-${le}`,M=l;typeof M==`number`?M={top:M,right:M,bottom:M,left:M}:M&&={top:M.top||0,right:M.right||0,bottom:M.bottom||0,left:M.left||0};let de=+(i===`bottom`),fe=+(i===`top`),pe=+(i===`right`),me=+(i===`left`),he={boundary:c===`clipping-ancestors`?`clippingAncestors`:c,padding:M},ge=q.useRef(null),_e=Fe(a),ve=Fe(s),ye=typeof a==`function`?0:a,be=typeof s==`function`?0:s,N=[];p&&N.push(p),N.push(nT(e=>{let t=vO(e,i,ne),n=typeof _e.current==`function`?_e.current(t):_e.current,r=typeof ve.current==`function`?ve.current(t):ve.current;return{mainAxis:n,crossAxis:r,alignmentAxis:r}},[ye,be,ne,i]));let xe=T===`none`&&w!==`shift`,Se=!xe&&(u||ee||w===`shift`),Ce=w===`none`?null:aT({...he,padding:{top:M.top+1+de,right:M.right+1+me,bottom:M.bottom+1+fe,left:M.left+1+pe},mainAxis:!ee&&w===`flip`,crossAxis:T===`flip`&&`alignment`,fallbackAxisSideDirection:E}),we=xe?null:rT({...he,rootBoundary:D,mainAxis:T!==`none`,crossAxis:Se,limiter:u||ee?void 0:iT(e=>{if(!ge.current)return{};let{width:t,height:n}=ge.current.getBoundingClientRect(),r=fb(cb(e.placement)),i=r===`y`?t:n,a=r===`y`?M.left+M.right:M.top+M.bottom;return{offset:i/2+a/2}})},[he,u,ee,D,M,T]);w===`shift`||T===`shift`||le===`center`?N.push(we,Ce):N.push(Ce,we),N.push(oT({...he,apply({elements:{floating:e},availableWidth:t,availableHeight:n,rects:r}){if(!te.current)return;let i=e.style;i.setProperty(hO,`${t}px`),i.setProperty(gO,`${n}px`);let a=pn(e).devicePixelRatio||1,{x:o,y:s,width:c,height:l}=r.reference,u=(Math.round((o+c)*a)-Math.round(o*a))/a,d=(Math.round((s+l)*a)-Math.round(s*a))/a;i.setProperty(fO,`${u}px`),i.setProperty(pO,`${d}px`)}}),sO(e=>({element:ge.current||h(e.elements.floating).createElement(`div`),padding:ge.current?d:0}),[d]),{name:`transformOrigin`,fn(e){let{elements:{floating:t},middlewareData:n,placement:r,platform:o,rects:s,y:c}=e,l=cb(r),u=lb(r),d=fb(l)===`y`,f=ge.current,p=typeof a==`function`?a(vO(e,i,ne)):a,m;m=!f&&u&&Math.abs(d?n.shift?.x||0:n.shift?.y||0)<=1?u===`start`===(d&&o.isRTL?.(t)===!0)?`100%`:`0%`:`${(d?n.arrow?.x||0:n.arrow?.y||0)+(d?f?.clientWidth||0:f?.clientHeight||0)/2}px`;let h=l===`top`||l===`left`?`calc(100% + ${p}px)`:`${-p}px`;return Se&&d&&Math.abs(n.shift?.y||0)>p&&(h=`${s.reference.y+s.reference.height/2-c}px`),t.style.setProperty(mO,d?`${m} ${h}`:`${h} ${m}`),{}}},cO,x),ot(()=>{!_&&g&&g.update({referenceElement:null,floatingElement:null,domReferenceElement:null,positionReference:null})},[_,g]);let Te=q.useMemo(()=>({ancestorScroll:!f,elementResize:!f&&typeof ResizeObserver<`u`,layoutShift:!f&&typeof IntersectionObserver<`u`}),[f]),{refs:Ee,elements:De,x:Oe,y:ke,middlewareData:Ae,update:je,placement:Me,context:Ne,isPositioned:Pe,floatingStyles:Ie}=t({rootContext:g,open:m?_:void 0,placement:ue,middleware:N,strategy:r,whileElementsMounted:m?void 0:(...e)=>Uw(...e,Te),nodeId:b,externalTree:C}),{sideX:Le,sideY:Re}=Ae.adaptiveOrigin||lO,ze=Pe?r:`fixed`,Be=q.useMemo(()=>{let e;return e=Pe?x?{position:ze,[Le]:Oe,[Re]:ke}:{...Ie,position:ze}:{position:ze,top:0,left:0},e[hO]=`100vw`,e[gO]=`100vh`,Pe||(e.opacity=0),e},[x,ze,Le,Oe,Re,ke,Ie,Pe]),Ve=q.useRef(null);ot(()=>{if(!_)return;let e=j.current,t=typeof e==`function`?e():e,n=(xO(t)?t.current:t)||null;n!==Ve.current&&(Ee.setPositionReference(n),Ve.current=n)},[_,Ee,A,j]),q.useEffect(()=>{if(!_)return;let e=j.current;typeof e!=`function`&&xO(e)&&e.current!==Ve.current&&(Ee.setPositionReference(e.current),Ve.current=e.current)},[_,Ee,A,j]),q.useEffect(()=>{if(m&&_&&De.reference&&De.floating)return Uw(De.reference,De.floating,je,Te)},[m,_,De,je,Te]);let He=cb(Me),Ue=_O(i,He,ne),We=lb(Me)||`center`,Ge=!!Ae.hide?.referenceHidden;ot(()=>{S&&_&&Pe&&(He!==ce||ae&&We!==le)&&ie(Me)},[S,ae,_,Pe,Me,He,We,ce,le]);let Ke=q.useMemo(()=>({position:`absolute`,top:Ae.arrow?.y,left:Ae.arrow?.x}),[Ae.arrow]),qe=Ae.arrow?.centerOffset!==0;return q.useMemo(()=>({positionerStyles:Be,arrowStyles:Ke,arrowRef:ge,arrowUncentered:qe,side:Ue,align:We,physicalSide:He,anchorHidden:Ge,refs:Ee,context:Ne,isPositioned:Pe,update:je}),[Be,Ke,ge,qe,Ue,We,He,Ge,Ee,Ne,Pe,je])}function xO(e){return e!=null&&`current`in e}function SO(e){let{store:t,domReference:n,positionerElement:r,open:i}=e,a=q.useRef(null),o=q.useRef(null),s=qt(r);ot(()=>{i||(o.current?.abort(),o.current=null,t.state.instantType===`trigger-change`&&t.set(`instantType`,void 0))},[i,t]),ot(()=>{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])}function CO(e){return e===`starting`?zn:On}function wO(e,t,{styles:n,transitionStatus:r,props:i,refs:a,hidden:o,inert:s=!1}){let c={...n};return s&&(c.pointerEvents=`none`),gn(`div`,e,{state:t,ref:a,props:[{role:`presentation`,hidden:o,style:c},CO(r),i],stateAttributesMapping:ve})}var TO=20;function EO(e,t,n,r){let[i,a]=q.useState(!1);ot(()=>{if(!e||!t||n==null){a(!1);return}let r=h(n).documentElement.clientWidth,i=n.offsetWidth;a(r>0&&i>0&&i>=r-TO)},[e,t,n]),Wn(e&&(!t||i),r)}var DO=q.forwardRef(function(e,t){let{render:n,className:r,style:i,anchor:a,positionMethod:o,side:s,align:c,sideOffset:u,alignOffset:d,collisionBoundary:f=`clipping-ancestors`,collisionPadding:p,arrowPadding:m,sticky:h,disableAnchorTracking:g=!1,collisionAvoidance:_=Ae,...v}=e,y=UD(),b=tO(),x=Ot(),S=y.useState(`floatingRootContext`),C=y.useState(`mounted`),w=y.useState(`open`),T=y.useState(`openChangeReason`),E=y.useState(`activeTriggerElement`),ee=y.useState(`modal`),D=y.useState(`openMethod`),O=y.useState(`positionerElement`),k=y.useState(`instantType`),A=y.useState(`transitionStatus`),j=yO({anchor:a,floatingRootContext:S,positionMethod:o,mounted:C,side:s,sideOffset:u,align:c,alignOffset:d,arrowPadding:m,collisionBoundary:f,collisionPadding:p,sticky:h,disableAnchorTracking:g,keepMounted:b,nodeId:x,collisionAvoidance:_,adaptiveOrigin:y.useState(`adaptiveOrigin`)});SO({store:y,domReference:S.useState(`domReferenceElement`),positionerElement:O,open:w});let te=ee===!0&&T!==`trigger-hover`;EO(w&&te,D===`touch`,O,E);let ne=y.useStateSetter(`positionerElement`),re=wO(e,{open:w,side:j.side,align:j.align,anchorHidden:j.anchorHidden,instant:k},{styles:j.positionerStyles,transitionStatus:A,props:v,refs:[t,ne],hidden:!C,inert:!w});return(0,Y.jsxs)(rO.Provider,{value:j,children:[C&&te&&(0,Y.jsx)(l,{inert:ze(!w),cutout:E}),(0,Y.jsx)(Qt,{id:x,children:re})]})}),OO=q.createContext(void 0);function kO(e){let t=q.useContext(OO);if(t===void 0&&!e)throw Error(on(69));return t}var AO=q.createContext(void 0);function jO(){let[e,t]=q.useState(0),n=Ct(()=>(t(e=>e+1),()=>{t(e=>Math.max(0,e-1))}));return{context:q.useMemo(()=>({register:n}),[n]),hasClosePart:e>0}}var MO=q.forwardRef(function(e,t){let{render:n,className:r,style:i,initialFocus:a,finalFocus:o,...s}=e,c=UD(),l=iO(),u=kO(!0)!=null,{context:d,hasClosePart:f}=jO(),p=c.useState(`open`),m=c.useState(`openMethod`),h=c.useState(`instantType`),g=c.useState(`transitionStatus`),_=c.useState(`popupProps`),v=c.useState(`titleElementId`),y=c.useState(`descriptionElementId`),b=c.useState(`modal`),x=c.useState(`mounted`),S=c.useState(`openChangeReason`),C=c.useState(`activeTriggerElement`),w=c.useState(`floatingRootContext`),T=w.useState(`floatingId`),E=c.useState(`disabled`),ee=c.useState(`openOnHover`),D=c.useState(`closeDelay`);pt({open:p,ref:c.context.popupRef,onComplete(){p&&c.context.onOpenChangeComplete?.(!0)}}),KC(w,{enabled:ee&&!E,closeDelay:D});let O=a===void 0?bt(c.context.popupRef):a,k=b!==!1&&f;c.useSyncedValue(`focusManagerModal`,k);let j=c.useStateSetter(`popupElement`),te={open:p,side:l.side,align:l.align,instant:h,transitionStatus:g},ne=gn(`div`,e,{state:te,ref:[t,c.context.popupRef,j],props:[_,{id:T,role:`dialog`,...Xe,"aria-labelledby":v,"aria-describedby":y,onKeyDown(e){u&&A.has(e.key)&&e.stopPropagation()}},CO(g),s],stateAttributesMapping:Vt});return(0,Y.jsx)(dn,{context:w,openInteractionType:m,modal:k,disabled:!x||S===`trigger-hover`,initialFocus:O,returnFocus:o,restoreFocus:`popup`,getInsideElements:()=>[c.context.beforeTriggerFocusGuardRef.current],previousFocusableElement:qe(C)?C:void 0,nextFocusableElement:c.context.triggerFocusTargetRef,beforeContentFocusGuardRef:c.context.beforeContentFocusGuardRef,children:(0,Y.jsx)(AO.Provider,{value:d,children:ne})})}),NO=(0,q.forwardRef)(function({children:e,className:t,type:n=`button`,...r},i){return(0,Y.jsxs)(`button`,{...r,ref:i,type:n,className:E(`select caps-select caps-combobox-trigger w-full`,t),children:[(0,Y.jsx)(`span`,{children:e}),(0,Y.jsx)(p,{className:`caps-select-chevron`,"aria-hidden":`true`})]})});function PO({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=mt({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 ee=e=>{v(!1),e||g(``),d===void 0&&S(e),c?.(e)},D=e=>`${m}-option-${encodeURIComponent(e)}`,O=e=>{let t=n(e);f===void 0&&b(t),l(e),p&&!u&&ee(!1)},k=e=>{v(!0),g(e.target.value),E.setActiveKey(null)},A=e=>{if($e(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(),O(E.activeItem))},j=(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:j,inputValue:h,listboxId:m,onInputChange:k,onInputKeyDown:A,optionId:D,open:w,commit:O,selectedKeys:C,setOpen:ee}}function FO(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:ee,rootRef:D,trigger:O,triggerRef:k,value:A,...j}=e,te=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)},re;C?re=A:A!==void 0&&(re=A===null?[]:[A]);let ie=(0,q.useId)(),ae=O?.props??_,oe=g??ae?.id??ie,se={id:oe,"aria-describedby":[t,ae?.[`aria-describedby`]].filter(Boolean).join(` `)||void 0,"aria-invalid":n??ae?.[`aria-invalid`],"aria-label":ae?.[`aria-label`]??r,"aria-labelledby":ae?.[`aria-labelledby`]??i,"aria-required":a??ae?.[`aria-required`]},{keyboardNavigation:ce,onPointerMove:le,activeItem:M,activeKey:de,commit:fe,groups:pe,inputValue:me,listboxId:he,onInputChange:ge,onInputKeyDown:_e,open:ve,optionId:ye,selectedKeys:be,setOpen:N}=PO({defaultOpen:l,defaultValue:u,getKey:f,getSearchText:m,groupBy:h,id:oe,isDisabled:y,items:b,onOpenChange:x,onCommit:te,multiple:C??!1,controlledOpen:w,controlledKeys:re,trigger:O});ne(()=>{O&&N(!1)});let xe=ue(`popover`),Se=s===void 0?xe:s,Ce=xt(`.caps-combobox-option[data-active="true"]:not(:disabled), [data-navigation="pointer"] .caps-combobox-option:hover:not(:disabled)`),we=(0,Y.jsx)(cn,{..._,...O?{}:se,"aria-activedescendant":M?ye(f(M)):void 0,"aria-autocomplete":`list`,"aria-controls":he,"aria-expanded":!0,className:E(`input-sm`,_?.className),id:O?_?.id??`${oe}-input`:oe,onChange:e=>{_?.onChange?.(e),ge(e)},onKeyDown:e=>{_?.onKeyDown?.(e),e.defaultPrevented||_e(e)},placeholder:_?.placeholder??T,ref:v,role:`combobox`,value:me}),Te=(0,Y.jsx)(`div`,{id:he,ref:Ce,className:`caps-combobox-list`,"data-navigation":ce?`keyboard`:`pointer`,onPointerMove:le,role:`listbox`,"aria-multiselectable":C??void 0,children:pe.every(e=>e.items.length===0)?(0,Y.jsx)(`div`,{className:`px-md py-md text-sm text-base-content`,children:d}):pe.map(e=>(0,Y.jsxs)(`div`,{"aria-label":e.label||void 0,role:e.label?`group`:void 0,children:[e.label?(0,Y.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=de===t,i={active:r,disabled:n,selected:be.includes(t)};return(0,Y.jsxs)(`button`,{"aria-disabled":n||void 0,"aria-selected":i.selected,className:`caps-combobox-option`,"data-active":r&&ce,disabled:n,id:ye(t),onClick:()=>{fe(e)},onMouseDown:e=>{e.preventDefault()},role:`option`,tabIndex:-1,type:`button`,children:[(0,Y.jsx)(`span`,{"aria-hidden":`true`,className:`caps-combobox-check`,children:i.selected?(0,Y.jsx)(Nn,{}):null}),ee?.(e,r,i)??p(e)]},t)})]},e.label))});return O?(0,Y.jsx)(`div`,{...j,className:E(j.className),ref:D,children:(0,Y.jsxs)(YD,{modal:!0,onOpenChange:N,open:ve,children:[(0,Y.jsx)($D,{...se,"aria-haspopup":`dialog`,className:`btn`,ref:k,render:O}),Se===null?null:(0,Y.jsx)(nO,{container:Se,children:(0,Y.jsx)(DO,{align:`start`,side:`bottom`,sideOffset:4,children:(0,Y.jsxs)(MO,{"data-active-tone":o,className:E(`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,Y.jsx)(`div`,{className:`caps-combobox-search`,children:we}),Te]})})})]})}):(0,Y.jsx)(`div`,{...j,className:E(j.className),ref:D,children:(0,Y.jsxs)(`div`,{className:E(`caps-combobox-panel`,c),"data-active-tone":o,children:[(0,Y.jsx)(`div`,{className:`caps-combobox-search`,children:we}),Te]})})}function IO({icon:e,caption:t}){return(0,Y.jsxs)(`span`,{className:`caps-icon-choice-mark`,"aria-hidden":`true`,children:[(0,Y.jsx)(`span`,{className:`caps-icon-choice-art`,children:e}),t?(0,Y.jsx)(`span`,{className:`caps-icon-choice-caption`,children:t}):null,(0,Y.jsx)(`span`,{className:`caps-icon-choice-lamp`})]})}var LO=(0,q.forwardRef)(function({label:e,icon:t,caption:n,appearance:r,className:i,...a},o){return(0,Y.jsx)(`label`,{className:`caps-icon-choice`,"data-appearance":r===`compact`?r:void 0,children:(0,Y.jsx)(Jt,{...a,appearance:r??`default`,"aria-label":e,className:E(`caps-icon-choice-input`,i),indicator:(0,Y.jsx)(IO,{icon:t,caption:n}),ref:o})})}),RO=(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,Y.jsx)(`label`,{className:`caps-check-key`,children:(0,Y.jsx)(Jt,{...i,"aria-label":e,"aria-describedby":s,className:E(`caps-check-key-input`,r),indicator:(0,Y.jsxs)(`span`,{className:`caps-check-key-face`,"aria-hidden":`true`,children:[t?(0,Y.jsx)(`span`,{className:`caps-check-key-icon`,children:t}):null,(0,Y.jsxs)(`span`,{className:`caps-check-key-copy`,children:[(0,Y.jsx)(`span`,{className:`caps-check-key-label`,children:e}),n?(0,Y.jsx)(`span`,{className:`caps-check-key-hint`,id:o,children:n}):null]}),(0,Y.jsx)(`span`,{className:`caps-check-key-lamp`})]}),ref:a})})});function zO({className:e,...t}){return(0,Y.jsx)(`div`,{...t,className:E(`caps-check-keys`,e)})}function BO({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=In(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=Dt(o,{ease:`outCubic`,duration:75}),c=e?et(o,{bounce:.65,duration:300}):Dt(o,{ease:`inCubic`,duration:100}),l=go(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,Y.jsxs)(`svg`,{ref:a,className:`caps-radio-visual`,width:`24`,height:`24`,viewBox:`0 0 12 12`,"aria-hidden":`true`,focusable:`false`,children:[(0,Y.jsxs)(`defs`,{children:[(0,Y.jsx)(Hn,{id:`${t}-surface`,transform:`matrix(1 0 0 1 6 6)`}),(0,Y.jsx)(jn,{id:`${t}-shadow`}),(0,Y.jsx)(tt,{id:`${t}-inset`}),(0,Y.jsx)(`clipPath`,{id:`${t}-well`,children:(0,Y.jsx)(`circle`,{cx:`6`,cy:`6`,r:`5`})})]}),(0,Y.jsx)(`circle`,{className:`caps-radio-track`,cx:`6`,cy:`6`,r:`5.5`,filter:`url(#${t}-inset)`}),(0,Y.jsx)(`g`,{clipPath:`url(#${t}-well)`,children:(0,Y.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 VO=(0,q.createContext)(null),HO=(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,Y.jsx)(VO.Provider,{value:{disabled:r,name:f,onValueChange:e=>{s===void 0&&m(e),a?.(e)},value:h},children:(0,Y.jsx)(`fieldset`,{...c,className:E(`flex gap-md`,o===`horizontal`?`flex-row flex-wrap`:`flex-col`,t),disabled:r,role:c.role??`radiogroup`,ref:d,children:e})})}),UO=(0,q.forwardRef)(function({className:e,indicator:t,onChange:n,onClick:r,value:i,...a},o){let s=(0,q.useContext)(VO);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,Y.jsxs)(`span`,{className:`caps-radio`,"data-checked":c,"data-custom-indicator":t!==void 0||void 0,children:[(0,Y.jsx)(`input`,{...a,"aria-checked":c,checked:c,className:E(`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,Y.jsx)(BO,{checked:c}):t]})}),WO=(0,q.forwardRef)(function({description:e,id:t,meta:n,title:r,...i},a){let o=(0,q.useContext)(VO),s=(0,q.useId)(),c=t??s,l=o?.value===i.value,u=o?.disabled===!0||i.disabled===!0;return(0,Y.jsxs)(`label`,{className:`caps-choice-card`,"data-checked":l,"data-disabled":u||void 0,htmlFor:c,children:[(0,Y.jsx)(UO,{...i,"aria-describedby":e?`${c}-description`:void 0,"aria-labelledby":`${c}-title`,id:c,ref:a}),(0,Y.jsxs)(`span`,{className:`caps-choice-card-copy`,children:[(0,Y.jsx)(`span`,{className:`caps-choice-card-title`,id:`${c}-title`,children:r}),e?(0,Y.jsx)(`span`,{className:`caps-choice-card-description`,id:`${c}-description`,children:e}):null]}),n?(0,Y.jsx)(`span`,{className:`caps-choice-card-meta`,children:n}):null]})}),GO=(0,q.forwardRef)(function({label:e,icon:t,caption:n,art:r=`dim`,className:i,...a},o){return(0,Y.jsx)(`label`,{className:`caps-icon-choice`,"data-art":r===`color`?r:void 0,children:(0,Y.jsx)(UO,{...a,"aria-label":e,className:E(`caps-icon-choice-input`,i),indicator:(0,Y.jsx)(IO,{icon:t,caption:n}),ref:o})})}),KO=(0,q.forwardRef)(function({label:e,color:t,className:n,...r},i){return(0,Y.jsx)(`label`,{className:`caps-icon-choice`,"data-art":`color`,"data-swatch":``,title:e,children:(0,Y.jsx)(UO,{...r,"aria-label":e,className:E(`caps-icon-choice-input`,n),indicator:(0,Y.jsx)(IO,{icon:(0,Y.jsx)(`span`,{className:`caps-swatch-dot`,style:{backgroundColor:t}})}),ref:i})})}),qO=(0,q.forwardRef)(function({className:e,invalid:t,...n},r){return(0,Y.jsxs)(`span`,{className:`caps-select-shell`,children:[(0,Y.jsx)(`select`,{...n,"aria-invalid":t?!0:n[`aria-invalid`]===!1?void 0:n[`aria-invalid`],className:E(`select select-bordered caps-select w-full`,t&&`select-error`,e),ref:r}),!n.multiple&&(!n.size||n.size<=1)?(0,Y.jsx)(p,{className:`caps-select-chevron`,"aria-hidden":`true`}):null]})});function JO({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=Pe();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=g(n.current),c=et(s,{bounce:.25,duration:440}),l=Dt(s,{ease:`inOutSine`,duration:100}),u=go(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=go(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,Y.jsxs)(`svg`,{className:`caps-switch-visual`,width:`40`,height:`24`,viewBox:`0 0 20 12`,"aria-hidden":`true`,focusable:`false`,children:[(0,Y.jsxs)(`defs`,{children:[(0,Y.jsx)(Hn,{ref:r,id:`${t}-surface`,transform:i?`matrix(2 0 0 1 10 6)`:`matrix(1 0 0 1 6 6)`}),(0,Y.jsx)(jn,{id:`${t}-shadow`}),(0,Y.jsx)(tt,{id:`${t}-inset`}),(0,Y.jsx)(`clipPath`,{id:`${t}-track`,children:(0,Y.jsx)(`rect`,{x:`1`,y:`1`,width:`18`,height:`10`,rx:`5`})})]}),(0,Y.jsx)(`rect`,{className:`caps-switch-track`,filter:`url(#${t}-inset)`,x:`0.5`,y:`0.5`,width:`19`,height:`11`,rx:`5.5`}),(0,Y.jsx)(`g`,{clipPath:`url(#${t}-track)`,children:(0,Y.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 YO=(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,Y.jsxs)(`span`,{className:`caps-switch`,"data-checked":u,children:[(0,Y.jsx)(`input`,{...a,checked:u,className:E(`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,Y.jsx)(JO,{checked:u})]})}),XO=Ti(V),ZO=Ti(Ua),QO=Ti(oo(Sa)),$O=Ti(W(V)),ek=W(ua(File)),tk=Ti(ek),nk=F([V,Sa,Ua,to,qi,W(V),ek]),rk=Ti(nk),ik=e=>si(XO(e.state.value),()=>``),ak=e=>si(ZO(e.state.value),()=>!1),ok=e=>si(QO(e.state.value),()=>null),sk=e=>si($O(e.state.value),()=>[]),ck=e=>si(tk(e.state.value),()=>[]),lk=e=>si(rk(e.state.value),()=>null);function uk({field:e,spec:t,locked:n,...r}){let[i,a]=(0,q.useState)(!1);return(0,Y.jsxs)(lt,{children:[(0,Y.jsx)(cn,{...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:ik(e),onBlur:e.handleBlur,onChange:t=>{e.handleChange(t.currentTarget.value)}}),(0,Y.jsx)(Zt,{type:`button`,variant:`outline`,size:`icon`,"aria-label":i?`Hide`:`Show`,"aria-pressed":i,disabled:n,onClick:()=>{a(e=>!e)},children:i?(0,Y.jsx)(sT,{"aria-hidden":`true`}):(0,Y.jsx)(cT,{"aria-hidden":`true`})})]})}var dk={text:`text`,email:`email`,url:`url`,tel:`tel`};function fk({spec:e,field:t,locked:n,...r}){let i=ck(t),a=n||e.readOnly===!0,o=(0,q.useRef)(null);return(0,Y.jsxs)(`div`,{className:`flex flex-col gap-sm`,children:[(0,Y.jsx)(st,{asChild:!0,children:(0,Y.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,Y.jsx)(Zt,{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,Y.jsx)(LD,{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 pk({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,Y.jsx)(cn,{...a,type:dk[e.kind],inputMode:e.kind===`text`?void 0:e.kind,autoComplete:e.autoComplete,placeholder:e.placeholder,maxLength:e.maxLength,readOnly:e.readOnly,value:ik(t),onChange:e=>{i(e.currentTarget.value)}});case`textarea`:return(0,Y.jsx)(kt,{...a,rows:e.rows??3,placeholder:e.placeholder,maxLength:e.maxLength,readOnly:e.readOnly,value:ik(t),onChange:e=>{i(e.currentTarget.value)}});case`secret`:return(0,Y.jsx)(uk,{...r,field:t,spec:e,locked:n});case`money`:return(0,Y.jsxs)(lt,{children:[(0,Y.jsx)(Ut,{className:`caps-field-currency`,children:e.currency??`USD`}),(0,Y.jsx)(cn,{...a,inputMode:`decimal`,autoComplete:`off`,className:`caps-field-amount`,placeholder:e.placeholder??`0.00`,readOnly:e.readOnly,value:ik(t),onChange:e=>{i(e.currentTarget.value)}})]});case`date`:return(0,Y.jsx)(cn,{...a,type:`date`,readOnly:e.readOnly,value:ik(t),onChange:e=>{i(e.currentTarget.value)}});case`number`:return(0,Y.jsx)(vn,{...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:ok(t),onValueChange:e=>{t.handleChange(e)}});case`select`:return(0,Y.jsxs)(qO,{...a,value:ik(t),onChange:e=>{i(e.currentTarget.value)},children:[e.placeholder===void 0?null:(0,Y.jsx)(`option`,{value:``,disabled:!0,children:e.placeholder}),e.options.map(e=>(0,Y.jsx)(`option`,{value:e.value,disabled:e.disabled,children:e.label},e.value))]});case`combobox`:return(0,Y.jsx)(FO,{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:ik(t),...e.placeholder===void 0?{}:{placeholder:e.placeholder},trigger:(0,Y.jsx)(NO,{name:e.name,disabled:n||e.readOnly===!0,onBlur:t.handleBlur,children:e.options.find(e=>e.value===ik(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,Y.jsx)(fk,{...r,spec:e,field:t,locked:n});case`checkbox`:return(0,Y.jsx)(Jt,{...a,disabled:n||e.readOnly===!0,checked:ak(t),onChange:e=>{t.handleChange(e.currentTarget.checked)}});case`switch`:return(0,Y.jsx)(YO,{...a,disabled:n||e.readOnly===!0,checked:ak(t),onCheckedChange:e=>{t.handleChange(e)}});case`radio`:case`icon-radio`:case`checkboxes`:case`icon-checkboxes`:return null}}var mk=new Set([`radio`,`icon-radio`,`checkboxes`,`icon-checkboxes`]);function hk({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=sk(t),s=(e,r)=>{t.handleChange(r?[...n,e]:n.filter(t=>t!==e))};return(0,Y.jsx)(hn,{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,Y.jsx)(`div`,{className:`caps-field-icon-choices`,children:e.options.map(r=>(0,Y.jsx)(LO,{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,Y.jsx)(zO,{children:e.options.map(r=>(0,Y.jsx)(RO,{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,Y.jsx)(hn,{legend:o,icon:e.icon,layout:i,...i===`columns`?{legendTitle:o}:{},description:e.help,disabled:a,error:r??null,children:(0,Y.jsx)(HO,{name:e.name,"aria-label":o,value:ik(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,Y.jsx)(GO,{value:t.value,label:t.label,...t.caption===void 0?{}:{caption:t.caption},icon:t.icon,disabled:t.disabled},t.value):s?(0,Y.jsx)(WO,{value:t.value,title:t.label,description:t.description,meta:t.meta,disabled:t.disabled},t.value):(0,Y.jsx)($t,{label:t.label,orientation:`inline`,children:(0,Y.jsx)(UO,{value:t.value,disabled:t.disabled})},t.value))})})}function gk({spec:e,field:t,locked:n,error:r,render:i,...a}){return i({name:e.name,label:e.label,help:e.help,value:lk(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 _k({form:e,spec:t,locked:n,layout:r}){let i=CD({form:e,name:t.name}),a=xD(e.store,e=>e.submissionAttempts>0),o=i.state.meta.isBlurred||a?PD(i.state.meta):void 0;if(t.render===void 0&&mk.has(t.kind))return(0,Y.jsx)(hk,{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,Y.jsx)($t,{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,Y.jsx)(pk,{spec:t,field:i,locked:n}):(0,Y.jsx)(gk,{spec:t,field:i,locked:n,error:o,render:t.render})})}var vk=Ti(io(V,nk));function yk({form:e,spec:t,locked:n,layout:r}){let i=t.when;return xD(e.store,e=>i===void 0||i(si(vk(e.values),()=>({}))))?(0,Y.jsx)(_k,{form:e,spec:t,locked:n,layout:r}):null}function bk({form:e,section:t,locked:n,layout:r}){let i=t.fields.map(t=>(0,Y.jsx)(yk,{form:e,spec:t,locked:n,layout:r},t.name));return t.title===void 0?i:(0,Y.jsx)(rn,{title:t.title,description:t.description,layout:r,children:i})}function xk({model:e,names:t,disabled:n=!1,layout:r}){let i=e.form;return t===void 0?e.description.sections.map(e=>(0,Y.jsx)(bk,{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,Y.jsx)(yk,{form:i,spec:a,locked:n,layout:r},t)})}var Sk=class{annotation;constructor(e){this.annotation=e}},Ck=class{sections;constructor(e){this.sections=e}},wk=`caps/form`,Tk=0;function Ek(e){Tk+=1;let t={[`${wk}:${String(Tk)}`]:new Sk(e)};return e.label!==void 0&&(t.title=e.label),e.help!==void 0&&(t.description=e.help),t}V.annotate(Ek({kind:`secret`})).pipe(Gi(`Secret`));var Dk=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 Ok(e){return Object.values(e??{}).reduce((e,t)=>t instanceof Sk?{...e,...t.annotation}:e,{})}function kk(e){return e.reduce((e,t)=>({...e,...Ok(t)}),{})}function Ak(e){let t=e?.[wk];return t instanceof Ck?t.sections:{}}var jk=Ti(V);function Mk(e){if(la(e))return pi(jk(e.literal),{onNone:()=>null,onSome:e=>[e]});if(!Qa(e))return null;let t=[];for(let n of e.types){if(Ea(n))continue;let e=Mk(n);if(e===null)return null;t.push(...e)}return t}function Nk(e){if(Si(e))return{type:`string`,literals:[]};if(pa(e))return{type:`number`,nullable:!1};if(Ya(e))return{type:`boolean`};let t=Mk(e);if(t!==null)return{type:`string`,literals:t};if(Hi(e)){let[t]=e.rest;if(t===void 0)return null;if(Si(t))return{type:`strings`,literals:[]};let n=Mk(t);return n===null?null:{type:`strings`,literals:n}}if(Qa(e)){let t=e.types.filter(e=>!Ea(e)&&!sa(e)),n=e.types.some(e=>sa(e)),[r]=t;if(t.length!==1||r===void 0)return null;let i=Nk(r);return i?.type===`number`?{type:`number`,nullable:n}:n?null:i}return null}function Pk(e){let t=e.ast;if(!Xi(t))throw Error(`A schema form needs a Schema.Struct.`);return{fields:t.propertySignatures.map(e=>{let t=String(e.name),n=va(e.type),r=kk([e.type.annotations,...(e.type.checks??[]).map(e=>e.annotations)]),i=r.kind===`file`?{type:`files`}:Nk(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:ja(e.type),description:Za(e.type)}}),sections:Ak(Va(t))}}function Fk(e){let t=e,n=!1,r=!1;for(;;)if(t instanceof cr)n=!0,t=t.unwrap();else if(t instanceof _r)r=!0,t=t.unwrap();else if(t instanceof Yn)t=t.unwrap();else if(t instanceof ai)t=t.in;else return{node:t,optional:n,nullable:r}}function Ik(e){if(e instanceof xr){let t=e.options.map(e=>Ik(e));return t.some(e=>e===null)?null:t.flatMap(e=>e??[])}let t=e instanceof yr?e.options:e instanceof rr?[...e.values]:null;if(t===null)return null;let n=t.map(e=>jk(e));return n.every(ui)?n.map(e=>e.value):null}function Lk(e){let{node:t,nullable:n}=Fk(e);if(t instanceof ar)return{type:`string`,literals:[]};if(t instanceof br)return{type:`number`,nullable:n};if(t instanceof xi)return{type:`boolean`};let r=Ik(t);if(r!==null)return{type:`string`,literals:r};if(t instanceof mr){let e=Fk(t.element).node;if(e instanceof ar)return{type:`strings`,literals:[]};let n=Ik(e);return n===null?null:{type:`strings`,literals:n}}return null}function Rk(e){let t=[e];for(;;){let e=t[t.length-1];if(e===void 0)break;let n=e instanceof cr||e instanceof _r||e instanceof Yn?e.unwrap():e instanceof ai?e.in:e;if(n===e)break;t.push(n)}return t.reverse().map(e=>tr.get(e))}function zk(e){return Rk(e).reduce((e,t)=>({...e,...t}),{})}function Bk(e){return Object.entries(e.shape)}function Vk(e){let t=Fk(e).node;if(!(t instanceof nr))throw Error(`A schema form needs a z.object.`);return{fields:Bk(t).map(([e,t])=>{let n=kk(Rk(t)),r=n.kind===`file`?{type:`files`}:Lk(t);if(r===null)throw Error(`Schema field "${e}" has no form control. Annotate it with field({ render }) or a kind.`);let i=zk(t);return{name:e,valueType:r,optional:Fk(t).optional,annotation:n,title:i.title,description:i.description}}),sections:Ak(zk(e))}}function Hk(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??Dk(e),description:r.description,meta:r.meta,icon:r.icon,caption:r.caption,disabled:r.disabled===!0}})}function Uk(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 Wk(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 Gk(e){let t=e instanceof Cr?Vk(e):Pk(e),n=t.fields.map((e,t)=>{let{kind:n,...r}=e.annotation,i=Hk(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??Dk(e.name),help:a,kind:n??Uk(e.valueType,i),options:i,optionalInSchema:e.optional,index:t}}),r={};t.fields.forEach((e,t)=>{let i=n[t];i&&(r[e.name]=Wk(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 Kk(e){let t=e instanceof Cr?e:ra(e);return{"~standard":{...t[`~standard`],validate:e=>{let n=t[`~standard`].validate(e);return n instanceof Promise?n.then(e=>qk(e)):qk(n)}}}}function qk(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 Jk=`onServer`;function Yk(e){let t=e.querySelector(`[aria-invalid="true"]`),n=t?.matches(`input, select, textarea, button, [tabindex]`)?t:t?.querySelector(`input, select, textarea, button`);return n?.focus(),n!=null}function Xk(e){if(Yk(e))return()=>void 0;let t=new MutationObserver(()=>{Yk(e)&&t.disconnect()});return t.observe(e,{subtree:!0,childList:!0,attributes:!0,attributeFilter:[`aria-invalid`]}),()=>{t.disconnect()}}function Zk(e){return e.state.meta.errorMap.onServer!==void 0}function Qk(e){e.setMeta(e=>({...e,errorMap:{...e.errorMap,[Jk]:void 0}}))}function $k(e,t,n){e.setFieldMeta(t,e=>({...e,isBlurred:!0,errorMap:{...e.errorMap,[Jk]:n}}))}function eA(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);BE(a,e.defaultValues)||(o(e.defaultValues),c(null));let{schema:l}=e,u=(0,q.useMemo)(()=>Gk(l),[l]),d=(0,q.useMemo)(()=>Kk(l),[l]),f=jD({defaultValues:s??a,validators:{onChange:d,onSubmit:d},listeners:{onChange:({fieldApi:e})=>{n(null),i(null),Zk(e)&&Qk(e)}},onSubmit:async({value:t,formApi:r})=>{n(null),i(null);let a=await Kk(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&&$k(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 tA(e){return{dirty:xD(e.form.store,e=>!e.isDefaultValue),submitting:xD(e.form.store,e=>e.isSubmitting),canSubmit:xD(e.form.store,e=>e.canSubmit)}}function nA({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}=tA(e),f=(0,q.useRef)(null),p=(0,q.useRef)(()=>void 0);return(0,q.useEffect)(()=>()=>{p.current()},[]),(0,Y.jsxs)(Pt,{...u,ref:f,layout:o,busy:d,noValidate:!0,onSubmit:t=>{t.preventDefault(),e.form.state.isSubmitting||e.submit().then(()=>{p.current();let t=f.current;t!==null&&!e.form.state.isValid&&(p.current=Xk(t))})},children:[c??(0,Y.jsx)(xk,{model:e,disabled:l,layout:o}),s===void 0?(0,Y.jsx)(aA,{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 rA({schema:e,defaultValues:t,onSubmit:n,onSaved:r,failure:i,...a}){let o=eA({schema:e,defaultValues:t,onSubmit:n,onSaved:r,failure:i});return(0,Y.jsx)(nA,{...a,model:o})}function iA(e){return`model`in e?(0,Y.jsx)(nA,{...e}):(0,Y.jsx)(rA,{...e})}function aA({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}=tA(e),d=u?null:e.saved&&!l?(0,Y.jsx)(fe,{tone:`success`,size:`compact`,label:e.saved}):l?(0,Y.jsx)(fe,{tone:`neutral`,size:`compact`,label:o}):null;return(0,Y.jsxs)(rt,{...c,error:e.error,status:d,children:[r?(0,Y.jsx)(Zt,{type:`button`,variant:`ghost`,disabled:u,onClick:r,children:i}):n&&l?(0,Y.jsx)(Zt,{type:`button`,variant:`ghost`,disabled:u,onClick:e.discard,children:n}):null,(0,Y.jsx)(Zt,{...s,type:`submit`,loading:u,disabled:u||!l&&!a,title:!l&&!a?`No changes to save`:void 0,children:t})]})}var oA=e=>e,sA=(e,t)=>{let n=e[t];if(!n)throw Error(`Missing burger path: ${t}`);return n},cA={apiVersion:1,name:`burger`,palette:{bottomBun:`#e9c46a`,bunSpot:`#d4a373`,cheese:`#f4d03f`,dead:`#636e72`,deadTongue:`#b2bec3`,eye:`#2d3436`,lettuce:`#7cb342`,mouth:`#2d3436`,patty:`#5d4037`,tomato:`#e74c3c`,topBun:`#f4a261`,blush:`#feaae4`,tongue:`#f98284`,sweat:`#accce4`,white:`#ffffff`},build({scene:e,color:t}){let n=e.group({name:`root`}),r=e.group({parent:n,name:`body`,updateSort:!0});e.cylinder({parent:r,name:`bottom-bun`,backface:t(`bottomBun`),color:t(`bottomBun`),diameter:34,frontFace:t(`bunSpot`),length:6,rotate:{x:Math.PI/2},stroke:!1,translate:{y:8}}),e.cylinder({parent:r,name:`patty`,color:t(`patty`),diameter:36,frontFace:t(`patty`),length:4,rotate:{x:Math.PI/2},stroke:!1,translate:{y:3}}),e.cylinder({parent:r,name:`tomato`,color:t(`tomato`),diameter:34,frontFace:t(`tomato`),length:2,rotate:{x:Math.PI/2},stroke:!1,translate:{y:-2}});let i=e.hemisphere({parent:r,name:`top-bun`,backface:t(`bunSpot`),color:t(`topBun`),diameter:38,rotate:{x:Math.PI/2},stroke:!1,translate:{y:-3}});for(let[n,r]of[{x:-8,y:-6,z:14},{x:6,y:-8,z:13},{x:0,y:-10,z:12},{x:10,y:-4,z:13},{x:-5,y:-2,z:15},{x:4,y:-12,z:11}].entries())e.path({parent:i,name:`seed.${String(n+1)}`,path:[{x:0,y:0}],color:t(`bunSpot`),stroke:1.2,translate:r});let a=e.group({parent:r,name:`face`,translate:{y:-5,z:16}}),o=xo(e,t,a,{blushMode:`medium-alias`,hideMouth:!0}),s=e.group({parent:r,name:`burger.mouth`,translate:{y:1,z:10}}),c=oA({angry:[{x:-13,y:2},{x:13,y:2},{x:13,y:5},{bezier:[{x:7,y:4},{x:0,y:5},{x:-7,y:4}]},{x:-13,y:5}],happy:[{x:-12,y:0},{bezier:[{x:-6,y:3},{x:0,y:5},{x:6,y:3}]},{x:12,y:0},{x:13,y:2},{bezier:[{x:7,y:5},{x:0,y:7},{x:-7,y:5}]},{x:-13,y:2}],open:[{x:-10,y:0},{bezier:[{x:-10,y:5},{x:-5,y:8},{x:0,y:8}]},{bezier:[{x:5,y:8},{x:10,y:5},{x:10,y:0}]},{x:10,y:1},{bezier:[{x:5,y:6},{x:-5,y:6},{x:-10,y:1}]}],pout:[{x:-8,y:2},{bezier:[{x:0,y:5},{x:8,y:2},{x:8,y:4}]},{x:0,y:6},{x:-8,y:4}],sad:[{x:-12,y:3},{bezier:[{x:-6,y:0},{x:0,y:-1},{x:6,y:0}]},{x:12,y:3},{x:13,y:5},{bezier:[{x:7,y:2},{x:0,y:1},{x:-7,y:2}]},{x:-13,y:5}],small:[{x:-6,y:1},{x:6,y:1},{x:7,y:3},{x:0,y:2},{x:-7,y:3}],surprised:[],worried:[{x:-11,y:1},{bezier:[{x:-6,y:3},{x:-3,y:1},{x:0,y:2}]},{bezier:[{x:3,y:1},{x:6,y:3},{x:11,y:1}]},{x:12,y:3},{x:0,y:4},{x:-12,y:3}],dead:[{x:-12,y:1},{x:12,y:1},{x:13,y:4},{bezier:[{x:7,y:3},{x:0,y:4},{x:-7,y:3}]},{x:-13,y:4}],normal:[{x:-12,y:1},{x:12,y:1},{x:13,y:4},{bezier:[{x:7,y:3},{x:0,y:4},{x:-7,y:3}]},{x:-13,y:4}]}),l=oA({angry:[{x:-13,y:0},{x:13,y:0},{x:13,y:2},{bezier:[{x:7,y:1},{x:0,y:2},{x:-7,y:1}]},{x:-13,y:2}],happy:[{x:-12,y:2},{bezier:[{x:-6,y:0},{x:0,y:-1},{x:6,y:0}]},{x:12,y:2},{x:13,y:3},{bezier:[{x:7,y:1},{x:0,y:0},{x:-7,y:1}]},{x:-13,y:3}],open:[{x:-10,y:2},{bezier:[{x:-10,y:-3},{x:-5,y:-6},{x:0,y:-6}]},{bezier:[{x:5,y:-6},{x:10,y:-3},{x:10,y:2}]},{x:10,y:1},{bezier:[{x:5,y:-4},{x:-5,y:-4},{x:-10,y:1}]}],pout:[{x:-8,y:0},{bezier:[{x:-4,y:-1},{x:0,y:0},{x:4,y:-1}]},{x:8,y:0},{x:9,y:1},{x:0,y:1},{x:-9,y:1}],sad:[{x:-12,y:0},{bezier:[{x:-6,y:2},{x:0,y:3},{x:6,y:2}]},{x:12,y:0},{x:13,y:1},{bezier:[{x:7,y:3},{x:0,y:4},{x:-7,y:3}]},{x:-13,y:1}],small:[{x:-6,y:0},{bezier:[{x:-3,y:1},{x:0,y:0},{x:3,y:1}]},{x:6,y:0},{x:7,y:1},{x:0,y:1},{x:-7,y:1}],surprised:[{x:-13,y:2},{bezier:[{x:-7,y:-2},{x:0,y:-3},{x:7,y:-2}]},{x:13,y:2},{x:14,y:3},{bezier:[{x:8,y:0},{x:0,y:-1},{x:-8,y:0}]},{x:-14,y:3}],worried:[{x:-11,y:1},{bezier:[{x:-6,y:0},{x:-3,y:1},{x:0,y:0}]},{bezier:[{x:3,y:2},{x:6,y:0},{x:11,y:1}]},{x:12,y:2},{bezier:[{x:7,y:1},{x:0,y:1},{x:-7,y:1}]},{x:-12,y:2}],dead:[{x:-12,y:1},{bezier:[{x:-6,y:0},{x:0,y:-.5},{x:6,y:0}]},{x:12,y:1},{x:13,y:2},{bezier:[{x:7,y:1},{x:0,y:.5},{x:-7,y:1}]},{x:-13,y:2}],normal:[{x:-12,y:1},{bezier:[{x:-6,y:0},{x:0,y:-.5},{x:6,y:0}]},{x:12,y:1},{x:13,y:2},{bezier:[{x:7,y:1},{x:0,y:.5},{x:-7,y:1}]},{x:-13,y:2}]}),u={};for(let n of[`normal`,`happy`,`sad`,`angry`,`surprised`,`dead`,`small`,`worried`,`pout`,`open`]){let r=e.group({parent:s,name:`burger.mouth.${n}`}),i={y:n===`open`?2:n===`small`?.5:1.5,z:+(n===`pout`)};n===`surprised`?e.ellipse({parent:r,name:`cheese.${n}`,color:t(`cheese`),fill:!0,height:8,stroke:2,translate:{y:2,z:0},width:6}):e.path({parent:r,name:`cheese.${n}`,color:t(`cheese`),fill:!0,path:sA(c,n),stroke:2,translate:i});let a={y:n===`open`?1:n===`surprised`?-1:-.5,z:n===`pout`?2:1};e.path({parent:r,name:`lettuce.${n}`,color:t(`lettuce`),fill:!0,path:sA(l,n),stroke:1.5,translate:a}),u[n]=r}return{root:n,variants:{eyes:o.eyes,mouth:u,blush:o.blush}}},expressions:bo,activities:So,defaultPresentation:{activity:`idle`,expression:`normal`}},lA=(e,t)=>{let n=e[t];if(!n)throw Error(`Missing cat face node: ${t}`);return n},uA=e=>e,dA={apiVersion:1,name:`cat`,palette:{body:`#ffe6c6`,eye:`#28282e`,mouth:`#28282e`,blush:`#feaae4`,dead:`#6c5671`,deadTongue:`#d9c8bf`,tongue:`#f98284`,stripes:`#dea38b`,sweat:`#accce4`,white:`#ffffff`},build({scene:e,color:t}){let n=e.group({name:`root`}),r=e.group({parent:n,name:`body`,updateSort:!0});e.path({parent:r,name:`body.sphere`,path:[{x:0,y:0}],color:t(`body`),stroke:32});for(let n of[-1,1])e.path({parent:r,name:`ear.${n<0?`left`:`right`}`,color:t(`body`),fill:!0,path:[{x:-6,y:0},{x:6,y:0},{x:0,y:-10}],rotate:{z:.6*n},stroke:3,translate:{x:9*n,y:-10}});let i=e.group({parent:r,name:`face`,translate:{z:20}}),a=xo(e,t,i,{hideMouth:!0}),o=e.group({parent:i,name:`cat.mouth`,translate:{y:6,z:2}}),s=(n,r,i)=>e.path({parent:o,name:`cat.mouth.${n}`,closed:!1,color:t(`mouth`),path:r,stroke:i}),c=uA({normal:s(`normal`,[{x:-2,y:-1},{x:0,y:0},{x:2,y:-1}],1.5),sad:s(`sad`,[{x:-2.5,y:2},{bezier:[{x:0,y:0},{x:2.5,y:2},{x:2.5,y:2}]}],1.5),angry:s(`angry`,[{x:-3,y:1},{x:3,y:1}],2),small:s(`small`,[{x:-1.5,y:0},{x:1.5,y:0}],1),worried:s(`worried`,[{x:-2,y:1},{bezier:[{x:-.5,y:.5},{x:.5,y:.5},{x:2,y:1}]}],1)}),l=e.group({parent:o,name:`cat.mouth.happy`,translate:{y:1}});e.path({parent:l,closed:!1,color:t(`mouth`),path:[{x:-2.5,y:1},{bezier:[{x:0,y:3},{x:2.5,y:1},{x:2.5,y:1}]}],stroke:1.5}),e.ellipse({parent:l,width:2,height:1.5,stroke:0,fill:!0,color:t(`tongue`),translate:{y:2}}),c.happy=l,c.surprised=e.ellipse({parent:o,name:`cat.mouth.surprised`,width:2.5,height:3,stroke:1.5,fill:!0,color:t(`mouth`),translate:{y:1}});let u=e.group({parent:o,name:`cat.mouth.dead`,translate:{y:3}});e.ellipse({parent:u,width:2.5,height:1.5,stroke:1.5,fill:!0,color:t(`dead`)}),e.ellipse({parent:u,width:1.2,height:.8,stroke:0,fill:!0,color:t(`deadTongue`),translate:{y:.5}}),c.dead=u,c.pout=e.ellipse({parent:o,name:`cat.mouth.pout`,width:2,height:2.5,stroke:1.5,fill:!0,color:t(`mouth`),translate:{y:1}}),c.open=e.ellipse({parent:o,name:`cat.mouth.open`,width:4,height:5,stroke:1.5,fill:!0,color:t(`mouth`),translate:{y:1}});let d=e.group({parent:i,name:`whiskers`,translate:{y:5,z:2}});for(let n of[-1,1]){let r=n*12;for(let[i,a]of[-2,0,2].entries())e.path({parent:d,name:`whisker.${n<0?`left`:`right`}.${String(i)}`,closed:!1,color:t(`eye`),path:[{x:0,y:a},{x:n*8,y:a+(i-1)*1.5}],stroke:.8,translate:{x:r,y:a*.5}})}let f={normal:lA(c,`normal`),happy:c.happy,sad:lA(c,`sad`),angry:lA(c,`angry`),surprised:c.surprised,dead:c.dead,small:lA(c,`small`),worried:lA(c,`worried`),pout:c.pout,open:c.open};return{root:n,variants:{eyes:a.eyes,mouth:f,blush:a.blush}}},expressions:bo,activities:{...So,listening:{motion:{target:`root`,rotate:{x:-.2},durationMs:300,repeat:`yoyo`},mouseInfluence:.3},thinking:{motion:{target:`root`,rotate:{z:.1},durationMs:800,repeat:`yoyo`},mouseInfluence:0}},defaultPresentation:{activity:`idle`,expression:`normal`}},fA={apiVersion:1,name:`mushroom`,palette:{body:`#fff7e4`,cap:`#f98284`,capSpot:`#ffe6c6`,eye:`#28282e`,mouth:`#28282e`,dead:`#6c5671`,deadTongue:`#d9c8bf`,tongue:`#f98284`,sweat:`#accce4`,white:`#ffffff`},build({scene:e,color:t}){let n=e.group({name:`root`}),r=e.group({parent:n,name:`body`,updateSort:!0});e.hemisphere({parent:r,name:`body.hemisphere`,backface:t(`cap`),color:t(`body`),diameter:32,rotate:{x:3*Math.PI/2},stroke:!1,translate:{y:2}});let i=e.hemisphere({parent:r,name:`cap.hemisphere`,backface:t(`capSpot`),color:t(`cap`),diameter:42,rotate:{x:Math.PI/2},stroke:!1,translate:{y:2}});e.path({parent:i,name:`cap.spot.front`,path:[{x:0,y:0}],color:t(`capSpot`),stroke:12,translate:{x:-8,y:8,z:12}}),e.path({parent:i,name:`cap.spot.top`,path:[{x:0,y:0}],color:t(`capSpot`),stroke:18,translate:{x:8,y:-4,z:13}});let a=e.group({parent:r,name:`face`,translate:{y:7,z:8}}),o=xo(e,t,a,{blushMode:`none`});return{root:n,variants:{eyes:o.eyes,mouth:o.mouth,blush:o.blush}}},expressions:bo,activities:{...So,error:{geometry:{eyes:`dead`,mouth:`dead`},motion:{target:`root`,rotate:{x:.9},durationMs:600,repeat:`none`},mouseInfluence:.1}},defaultPresentation:{activity:`idle`,expression:`sleepy`}},pA={mushroom:[`cap`,`capSpot`],cat:[`body`,`stripes`],burger:[`topBun`,`bottomBun`]},mA={mushroom:fA,cat:dA,burger:cA};function hA(e){let t=vo(yo(mA[e])),n=ho.parse(t.data);return{controls:t.controls,expressions:Object.keys(n.expressions),identitySlots:pA[e]}}var gA=new Map;function _A(e){let t=gA.get(e);return t||(t=hA(e),gA.set(e,t)),t}var vA=Object.freeze({get mushroom(){return _A(`mushroom`)},get cat(){return _A(`cat`)},get burger(){return _A(`burger`)}}),yA={mushroom:`Shiitake`,cat:`Cat`,burger:`Burger`},bA=[[`Rose`,`#f98284`,`#ffe6c6`],[`Peach`,`#f6a55c`,`#ffe9c9`],[`Gold`,`#f2d06b`,`#fff6d1`],[`Leaf`,`#9bd47a`,`#e6f8d8`],[`Mint`,`#5fc7b4`,`#d9f6ef`],[`Sky`,`#6aaee8`,`#dcefff`],[`Lilac`,`#9b8cf0`,`#ebe6ff`],[`Plum`,`#e58bd6`,`#fbe2f6`]];function xA(e,t){if(t===e.character)return e;let n=vA[e.character].identitySlots,r=vA[t].identitySlots,i=Object.fromEntries(r.flatMap((t,r)=>{let i=n[r];return Object.hasOwn(e.appearance,i)?[[t,e.appearance[i]]]:[]}));return{...e,character:t,appearance:i,expression:`normal`}}function SA(e,[,t,n]){let r=vA[e.character].identitySlots;return{...e,appearance:{...e.appearance,...Object.fromEntries(r.map((e,r)=>[e,r===0?t:n]))}}}function CA(e,t){let n=0;for(let e of t)n+=e.codePointAt(0)??0;return SA(e,bA[n%bA.length]??bA[0])}function wA({value:e,disabled:t=!1,onChange:n}){let r=vA[e.character].identitySlots,i=bA.find(([,t,n])=>r.every((r,i)=>e.appearance[r]===(i===0?t:n)))?.[0]??``;return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(hn,{legend:`Avatar`,icon:(0,Y.jsx)(Cn,{name:`agent`}),layout:`columns`,disabled:t,children:(0,Y.jsx)(HO,{"aria-label":`Character`,className:`caps-field-icon-choices`,disabled:t,orientation:`horizontal`,value:e.character,onValueChange:t=>{n(xA(e,ng.shape.character.parse(t)))},children:Qh.map(t=>(0,Y.jsx)(GO,{value:t,label:yA[t],caption:yA[t],art:`color`,icon:(0,Y.jsx)(kT,{avatar:xA(e,t),name:yA[t],size:32})},t))})}),(0,Y.jsx)(hn,{legend:`Colour`,icon:(0,Y.jsx)(Cn,{name:`prints`}),layout:`columns`,disabled:t,children:(0,Y.jsx)(HO,{"aria-label":`Colour`,className:`caps-field-icon-choices`,disabled:t,orientation:`horizontal`,value:i,onValueChange:t=>{let r=bA.find(([e])=>e===t);r&&n(SA(e,r))},children:bA.map(([e,t])=>(0,Y.jsx)(KO,{value:e,label:e,color:t},e))})})]})}var TA=ea.check(H(1,{message:`Give your Agent a name.`}),K(256,{message:`Use at most 256 characters.`})),EA=Ti(TA),DA=e=>e===`new`||e===`none`?e:e.computerId,OA=e=>e===`new`||e===`none`?e:{computerId:e},kA=e=>e?.[0]?.computerId??`none`;function AA(e,t){let n=Object.fromEntries(e.map(e=>[e.computerId,e.name]));n.new=`New Computer`,n.none=`No Computer`;let r={label:`Computer`,kind:`select`,icon:(0,Y.jsx)(Cn,{name:`computer`}),options:n};return V.check(L(e=>Object.hasOwn(n,e)||`Choose a Computer.`)).annotate(Ek(t===null?r:{...r,help:t}))}var jA=Ba({family:`grove-agent-create-request`,version:1,kinds:{request:{prefix:`request`}}});function MA({create:e,computers:t,computersUnavailable:n,inputRef:r,error:i,onCancel:a}){let o=(0,q.useRef)(null),[s,c]=(0,q.useState)(()=>{let e=jA.request.generate();return CA(og(e),e)}),l=(0,q.useMemo)(()=>I({name:TA.annotate(Ek({label:`Name`,icon:(0,Y.jsx)(Cn,{name:`write`}),render:e=>(0,Y.jsx)(cn,{ref:r,id:e.id,name:e.name,"aria-label":`New Agent name`,"aria-required":`true`,"aria-describedby":e[`aria-describedby`],"aria-invalid":e[`aria-invalid`],placeholder:`Name your Agent`,maxLength:256,disabled:e.disabled,value:e.value,onBlur:e.onBlur,onChange:t=>{e.onChange(t.currentTarget.value)}})})),computer:AA(t??[],n)}),[r,t,n]),u=t!==null,[d,f]=(0,q.useState)(!1),p={name:``,computer:kA(t)},m=eA({schema:l,defaultValues:p,onSubmit:async({name:t,computer:n})=>{let r=u?OA(n):void 0,i=o.current;if(i?.name!==t||(i.computer===void 0?void 0:DA(i.computer))!==(r===void 0?void 0:DA(r))||i.avatar!==s){let e={name:t,requestId:jA.request.generate(),avatar:s};i=r===void 0?e:{...e,computer:r}}return o.current=i,await e(i)?(o.current=null,{kind:`saved`,values:p}):{kind:`refused`}}}),{submitting:h,canSubmit:g,dirty:_}=tA(m);return(0,Y.jsxs)(iA,{model:m,layout:`columns`,"aria-label":`Create Agent`,footer:(0,Y.jsxs)(rt,{divider:!1,error:i,children:[(0,Y.jsx)(Zt,{type:`button`,variant:`ghost`,"aria-expanded":d,onClick:()=>{f(e=>!e)},children:d?`Fewer options`:`More options`}),(0,Y.jsx)(Zt,{type:`button`,variant:`ghost`,disabled:h,onClick:a,children:`Cancel`}),(0,Y.jsx)(Zt,{type:`submit`,className:`shrink-0 disabled:-outline-offset-1`,variant:`primary`,loading:h,disabled:h||!g||!_,children:`Create Agent`})]}),onSubmitCapture:e=>{kr(EA(m.form.state.values.name))&&e.currentTarget.querySelector(`input[name="name"]`)?.focus()},onChange:()=>{let e=m.form.state.values;(e.name.trim()!==o.current?.name||u&&o.current.computer!==void 0&&e.computer!==DA(o.current.computer))&&(o.current=null)},children:[(0,Y.jsx)(xk,{model:m,names:u&&d?[`name`,`computer`]:[`name`]}),d?(0,Y.jsx)(wA,{value:s,disabled:h,onChange:e=>{c(e),o.current=null}}):null]})}function NA({open:e,pending:t,error:n,computers:r,create:i,onClose:o,returnFocus:s}){let c=(0,q.useRef)(null);return(0,Y.jsx)(b,{open:e,onOpenChange:e=>{!e&&!t&&o()},children:(0,Y.jsxs)(zt,{className:`flex flex-col gap-lg`,initialFocus:c,finalFocus:s,keepMounted:!1,children:[(0,Y.jsxs)(pe,{children:[(0,Y.jsx)(w,{children:`New Agent`}),(0,Y.jsx)(a,{children:`Agents chat, write and make little games with you.`})]}),r.status===`loading`?(0,Y.jsx)(`p`,{role:`status`,children:`Loading your Computers…`}):(0,Y.jsx)(MA,{create:i,computers:r.status===`offered`?r.computers:r.status===`unavailable`?[]:null,computersUnavailable:r.status===`unavailable`?r.message:null,inputRef:c,error:n,onCancel:o})]})})}function PA({open:e,agents:t,defaultAgentId:n,start:r,pending:i,onClose:o,onNewAgent:s,returnFocus:c}){let l=eA({schema:(0,q.useMemo)(()=>I({agentId:V.check(L(e=>t.some(t=>t.agentId===e)||`Choose an Agent.`)).annotate(Ek({label:`Agent`,kind:`select`,options:Object.fromEntries(t.map(e=>[e.agentId,KT(e)]))}))}),[t]),defaultValues:{agentId:n??``},onSubmit:async({agentId:e})=>{let t=await r(e);if(t)return{kind:`refused`,error:t}}}),{submitting:u,canSubmit:d}=tA(l);return(0,Y.jsx)(b,{open:e,onOpenChange:e=>{!e&&!i&&!l.form.state.isSubmitting&&o()},children:(0,Y.jsxs)(zt,{className:`flex flex-col gap-lg`,keepMounted:!1,finalFocus:c,children:[(0,Y.jsxs)(pe,{children:[(0,Y.jsx)(w,{children:`New conversation`}),(0,Y.jsx)(a,{children:`Choose who to talk with.`})]}),t.length===0?(0,Y.jsxs)(`div`,{className:`grid gap-sm`,children:[(0,Y.jsx)(`p`,{children:`No Agent has conversation access yet.`}),s?(0,Y.jsx)(Zt,{onClick:s,children:`New Agent`}):null,(0,Y.jsx)(Zt,{variant:`ghost`,onClick:o,children:`Cancel`})]}):(0,Y.jsx)(iA,{model:l,"aria-label":`New conversation`,footer:(0,Y.jsxs)(rt,{divider:!1,error:l.error,children:[(0,Y.jsx)(Zt,{type:`button`,variant:`ghost`,disabled:u||i,onClick:o,children:`Cancel`}),(0,Y.jsx)(Zt,{type:`submit`,loading:u||i,disabled:!d||u||i,children:`Start`})]})})]})})}var FA=q.useLayoutEffect;function IA(e,t,n){q.useEffect(()=>{if(!e.current||n||typeof IntersectionObserver!=`function`)return()=>t();let r=new IntersectionObserver(e=>{t(e.pop())},{rootMargin:`100px`});return r.observe(e.current),()=>{r.disconnect(),t()}},[t,n,e])}function LA(e){let t=q.useRef(null);return q.useImperativeHandle(e,()=>t.current,[]),t}function RA(e){return e[e.length-1]}function zA(e){return typeof e==`function`}function BA(e,t){return zA(e)?e(t):e}var VA=Object.prototype.hasOwnProperty,HA=Object.prototype.propertyIsEnumerable;function UA(e){for(let t in e)if(VA.call(e,t))return!0;return!1}var WA=()=>Object.create(null),GA=(e,t)=>KA(e,t,WA);function KA(e,t,n=()=>({}),r=0){if(e===t)return e;if(r>500)return t;let i=t,a=XA(e)&&XA(i);if(!a&&!(JA(e)&&JA(i)))return i;let o=a?e:qA(e);if(!o)return i;let s=a?i:qA(i);if(!s)return i;let c=o.length,l=s.length,u=a?Array(l):n(),d=0;for(let t=0;t<l;t++){let o=a?t:s[t],l=e[o],f=i[o];if(l===f){u[o]=l,(a?t<c:VA.call(e,o))&&d++;continue}if(l===null||f===null||typeof l!=`object`||typeof f!=`object`){u[o]=f;continue}let p=KA(l,f,n,r+1);u[o]=p,p===l&&d++}return c===l&&d===c?e:u}function qA(e){let t=Object.keys(e);if(t.length!==Object.getOwnPropertyNames(e).length)return!1;let n=Object.getOwnPropertySymbols(e);if(n.length===0)return t;for(let r of n){if(!HA.call(e,r))return!1;t.push(r)}return t}function JA(e){if(!YA(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!YA(n)||!n.hasOwnProperty(`isPrototypeOf`))}function YA(e){return Object.prototype.toString.call(e)===`[object Object]`}function XA(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ZA(e,t,n){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0,i=e.length;r<i;r++)if(!ZA(e[r],t[r],n))return!1;return!0}if(JA(e)&&JA(t)){let r=n?.ignoreUndefined??!0;if(n?.partial){for(let i in t)if((!r||t[i]!==void 0)&&!ZA(e[i],t[i],n))return!1;return!0}let i=0;if(!r)i=Object.keys(e).length;else for(let t in e)e[t]!==void 0&&i++;let a=0;for(let o in t)if((!r||t[o]!==void 0)&&(a++,a>i||!ZA(e[o],t[o],n)))return!1;return i===a}return!1}var QA=/[\x00-\x1f\x7f"<>`{}]/g;function $A(e){return e.replace(QA,e=>`%`+e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`))}function ej(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,e=>{try{return decodeURI(e)}catch{return e}})}return $A(t)}var tj=[`http:`,`https:`,`mailto:`,`tel:`];function nj(e,t){if(!e)return!1;try{let n=new URL(e);return!t.has(n.protocol)}catch{return!1}}function rj(e){if(!e||!/[%\\\x00-\x1f\x7f]/.test(e)&&!e.startsWith(`//`))return{path:e,handledProtocolRelativeURL:!1};let t=/%25|%5C/gi,n=0,r=``,i;for(;(i=t.exec(e))!==null;)r+=ej(e.slice(n,i.index))+i[0],n=t.lastIndex;r+=ej(n?e.slice(n):e);let a=!1;return r.startsWith(`//`)&&(a=!0,r=`/`+r.replace(/^\/+/,``)),{path:r,handledProtocolRelativeURL:a}}function ij(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function aj(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function oj(){throw Error(`Invariant failed`)}function sj(e){let t=new Map,n,r,i=e=>{e.next&&(e.prev?(e.prev.next=e.next,e.next.prev=e.prev,e.next=void 0,r&&(r.next=e,e.prev=r)):(e.next.prev=void 0,n=e.next,e.next=void 0,r&&(e.prev=r,r.next=e)),r=e)};return{get(e){let n=t.get(e);if(n)return i(n),n.value},set(a,o){if(t.size>=e&&n){let e=n;t.delete(e.key),e.next&&(n=e.next,e.next.prev=void 0),e===r&&(r=void 0)}let s=t.get(a);if(s)s.value=o,i(s);else{let e={key:a,value:o,prev:r};r&&(r.next=e),r=e,n||=e,t.set(a,e)}},clear(){t.clear(),n=void 0,r=void 0}}}var cj=4,lj=5;function uj(e){let t=e.indexOf(`{`);if(t===-1)return null;let n=e.indexOf(`}`,t);return n===-1||t+1>=e.length?null:[t,n]}function dj(e,t,n=new Uint16Array(6)){let r=e.indexOf(`/`,t),i=r===-1?e.length:r,a=e.substring(t,i);if(!a||!a.includes(`$`))return n[0]=0,n[1]=t,n[2]=t,n[3]=i,n[4]=i,n[5]=i,n;if(a===`$`){let r=e.length;return n[0]=2,n[1]=t,n[2]=t,n[3]=r,n[4]=r,n[5]=r,n}if(a.charCodeAt(0)===36)return n[0]=1,n[1]=t,n[2]=t+1,n[3]=i,n[4]=i,n[5]=i,n;let o=uj(a);if(o){let[r,s]=o,c=a.charCodeAt(r+1);if(c===45){if(r+2<a.length&&a.charCodeAt(r+2)===36){let e=r+3,a=s;if(e<a)return n[0]=3,n[1]=t+r,n[2]=t+e,n[3]=t+a,n[4]=t+s+1,n[5]=i,n}}else if(c===36){let a=r+1,o=r+2;return o===s?(n[0]=2,n[1]=t+r,n[2]=t+a,n[3]=t+o,n[4]=t+s+1,n[5]=e.length,n):(n[0]=1,n[1]=t+r,n[2]=t+o,n[3]=t+s,n[4]=t+s+1,n[5]=i,n)}}return n[0]=0,n[1]=t,n[2]=t,n[3]=i,n[4]=i,n[5]=i,n}function fj(e,t,n,r,i,a,o,s){s?.(n);let c=r;{let r=n.fullPath??n.from,s=n.options,l=r.length,u=s?.caseSensitive??e,d=s?.params?.parse??s?.parseParams;for(;c<l;){let e=dj(r,c,t),n,s=c,l=e[5];c=l+1,a++;let f=e[0];switch(f){case 0:{let t=r.substring(e[2],e[3]),o=t,s;u?s=i.static??=new Map:(o=t.toLowerCase(),s=i.staticInsensitive??=new Map);let c=s.get(o);if(c)n=c;else{let e=mj(r);e.parent=i,e.depth=a,n=e,s.set(o,e)}break}case 1:case 3:case 2:{let t=r.substring(s,e[1]),c=r.substring(e[4],l),p=u&&!!(t||c),m=t?p?t:t.toLowerCase():void 0,h=c?p?c:c.toLowerCase():void 0,g=f===1?i.dynamic:f===3?i.optional:i.wildcard,_=f!==2&&!d&&g?.find(e=>!e.parse&&e.caseSensitive===p&&e.prefix===m&&e.suffix===h);if(_)n=_;else{let e=hj(f,r,p,m,h);n=e,e.parent=i,e.depth=a;let t;t=f===1?i.dynamic??=[]:f===3?i.optional??=[]:i.wildcard??=[],t.push(e),t.length===2&&o?.push(t)}break}}i=n}if(d&&n.children&&!n.isRoot&&n.id&&n.id.charCodeAt(n.id.lastIndexOf(`/`)+1)===95){let e=mj(r);e.kind=lj,e.parent=i,a++,e.depth=a,i.pathless??=[],i.pathless.push(e),i=e}let f=(n.path||!n.children)&&!n.isRoot;if(f&&r.endsWith(`/`)){let e=mj(r);e.kind=cj,e.parent=i,a++,e.depth=a,i.index=e,i=e}i.parse=d??null,i.priority=s?.params?.priority??0,f&&!i.route&&(i.route=n,i.fullPath=r)}if(n.children)for(let r of n.children)fj(e,t,r,c,i,a,o,s)}function pj(e,t){if(e.parse&&!t.parse)return-1;if(!e.parse&&t.parse)return 1;if(e.parse&&t.parse&&(e.priority||t.priority))return t.priority-e.priority;if(e.prefix&&t.prefix&&e.prefix!==t.prefix){if(e.prefix.startsWith(t.prefix))return-1;if(t.prefix.startsWith(e.prefix))return 1}if(e.suffix&&t.suffix&&e.suffix!==t.suffix){if(e.suffix.endsWith(t.suffix))return-1;if(t.suffix.endsWith(e.suffix))return 1}return e.prefix&&!t.prefix?-1:!e.prefix&&t.prefix?1:e.suffix&&!t.suffix?-1:!e.suffix&&t.suffix?1:e.caseSensitive&&!t.caseSensitive?-1:!e.caseSensitive&&t.caseSensitive?1:0}function mj(e){return{kind:0,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:e,parent:null,parse:null,priority:0}}function hj(e,t,n,r,i){return{kind:e,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:t,parent:null,parse:null,priority:0,caseSensitive:n,prefix:r,suffix:i}}function gj(e,t){let n=mj(`/`),r=new Uint16Array(6),i=[];for(let t of e)fj(!1,r,t,1,n,0,i);for(let e of i)e.sort(pj);t.masksTree=n,t.flatCache=sj(1e3)}function _j(e,t){e||=`/`;let n=t.flatCache.get(e);if(n)return n;let r=Sj(e,t.masksTree);return t.flatCache.set(e,r),r}function vj(e,t,n,r,i){e||=`/`,r||=`/`;let a=t?`case\0${e}`:e,o=i.singleCache.get(a);return o||(o=mj(`/`),fj(t,new Uint16Array(6),{from:e},1,o,0),i.singleCache.set(a,o)),Sj(r,o,n)}function yj(e,t,n=!1){let r=n?e:`nofuzz\0${e}`,i=t.matchCache.get(r);if(i!==void 0)return i;e||=`/`;let a;try{a=Sj(e,t.segmentTree,n)}catch(e){if(e instanceof URIError)a=null;else throw e}return a&&(a.branch=wj(a.route)),t.matchCache.set(r,a),a}function bj(e){return e===`/`?e:e.replace(/\/{1,}$/,``)}function xj(e,t=!1,n){let r=mj(e.fullPath),i=new Uint16Array(6),a=[],o={},s={},c=0;fj(t,i,e,1,r,0,a,e=>{if(n?.(e,c),e.id in o&&oj(),o[e.id]=e,c!==0&&e.path){let t=bj(e.fullPath);(!s[t]||e.fullPath.endsWith(`/`))&&(s[t]=e)}c++});for(let e of a)e.sort(pj);return{processedTree:{segmentTree:r,singleCache:sj(1e3),matchCache:sj(1e3),flatCache:null,masksTree:null},routesById:o,routesByPath:s}}function Sj(e,t,n=!1){let r=e.split(`/`),i=Ej(e,r,t,n);if(!i)return null;let[a]=Cj(e,r,i);return{route:i.node.route,rawParams:a}}function Cj(e,t,n){let r=Tj(n.node),i=null,a=Object.create(null),o=n.extract?.part??0,s=n.extract?.node??0,c=n.extract?.path??0,l=n.extract?.segment??0;for(;s<r.length;o++,s++,c++,l++){let u=r[s];if(u.kind===cj)break;if(u.kind===lj){l--,o--,c--;continue}let d=t[o],f=c;if(d&&(c+=d.length),u.kind===1){i??=n.node.fullPath.split(`/`);let e=i[l],t=u.prefix?.length??0;if(e.charCodeAt(t)===123){let n=u.suffix?.length??0,r=e.substring(t+2,e.length-n-1),i=d.substring(t,d.length-n);a[r]=decodeURIComponent(i)}else{let t=e.substring(1);a[t]=decodeURIComponent(d)}}else if(u.kind===3){if(n.skipped&1<<s){o--,c=f-1;continue}i??=n.node.fullPath.split(`/`);let e=i[l],t=u.prefix?.length??0,r=u.suffix?.length??0,p=e.substring(t+3,e.length-r-1),m=u.suffix||u.prefix?d.substring(t,d.length-r):d;m&&(a[p]=decodeURIComponent(m))}else if(u.kind===2){let t=u,n=e.substring(f+(t.prefix?.length??0),e.length-(t.suffix?.length??0)),r=decodeURIComponent(n);a[`*`]=r,a._splat=r;break}}return n.rawParams&&Object.assign(a,n.rawParams),[a,{part:o,node:s,path:c,segment:l}]}function wj(e){let t=[e];for(;e.parentRoute;)e=e.parentRoute,t.push(e);return t.reverse(),t}function Tj(e){let t=Array(e.depth+1);do t[e.depth]=e,e=e.parent;while(e);return t}function Ej(e,t,n,r){if(e===`/`&&n.index)return{node:n.index,skipped:0};let i=!RA(t),a=i&&e!==`/`,o=t.length-+!!i,s=[{node:n,index:1,skipped:0,statics:0,dynamics:0,optionals:0}],c=null,l=null;for(;s.length;){let n=s.pop(),{node:i,index:u,skipped:d,statics:f,dynamics:p,optionals:m}=n,{extract:h,rawParams:g}=n;if(i.kind===2&&i.route&&!Aj(l,n))continue;if(i.parse){if(!kj(e,t,n))continue;g=n.rawParams,h=n.extract}r&&i.route&&i.kind!==cj&&Aj(c,n)&&(c=n);let _=u===o;if(_&&(i.route&&(!a||i.kind===cj||i.kind===2)&&Aj(l,n)&&(l=n),!i.optional&&!i.wildcard&&!i.index&&!i.pathless))continue;let v=_?void 0:t[u],y;if(_&&i.index){let n={node:i.index,index:u,skipped:d,statics:f,dynamics:p,optionals:m,extract:h,rawParams:g},r=!0;if(i.index.parse&&(kj(e,t,n)||(r=!1)),r){if(!p&&!m&&!d&&Oj(f,o))return n;Aj(l,n)&&(l=n)}}if(i.wildcard)for(let e=i.wildcard.length-1;e>=0;e--){let n=i.wildcard[e],{prefix:r,suffix:a}=n;if(!(r&&(_||!(n.caseSensitive?v:y??=v.toLowerCase()).startsWith(r)))){if(a){if(_)continue;let e=t.slice(u).join(`/`).slice(-a.length);if((n.caseSensitive?e:e.toLowerCase())!==a)continue}s.push({node:n,index:o,skipped:d,statics:f,dynamics:p,optionals:m,extract:h,rawParams:g})}}if(i.optional){let e=d|1<<i.depth+1;for(let t=i.optional.length-1;t>=0;t--){let n=i.optional[t];s.push({node:n,index:u,skipped:e,statics:f,dynamics:p,optionals:m,extract:h,rawParams:g})}if(!_)for(let e=i.optional.length-1;e>=0;e--){let t=i.optional[e],{prefix:n,suffix:r}=t;if(n||r){let e=t.caseSensitive?v:y??=v.toLowerCase();if(n&&!e.startsWith(n)||r&&!e.endsWith(r))continue}s.push({node:t,index:u+1,skipped:d,statics:f,dynamics:p,optionals:m+Dj(o,u),extract:h,rawParams:g})}}if(!_&&i.dynamic&&v)for(let e=i.dynamic.length-1;e>=0;e--){let t=i.dynamic[e],{prefix:n,suffix:r}=t;if(n||r){let e=t.caseSensitive?v:y??=v.toLowerCase();if(n&&!e.startsWith(n)||r&&!e.endsWith(r))continue}s.push({node:t,index:u+1,skipped:d,statics:f,dynamics:p+Dj(o,u),optionals:m,extract:h,rawParams:g})}if(!_&&i.staticInsensitive){let e=i.staticInsensitive.get(y??=v.toLowerCase());e&&s.push({node:e,index:u+1,skipped:d,statics:f+Dj(o,u),dynamics:p,optionals:m,extract:h,rawParams:g})}if(!_&&i.static){let e=i.static.get(v);e&&s.push({node:e,index:u+1,skipped:d,statics:f+Dj(o,u),dynamics:p,optionals:m,extract:h,rawParams:g})}if(i.pathless)for(let e=i.pathless.length-1;e>=0;e--){let t=i.pathless[e];s.push({node:t,index:u,skipped:d,statics:f,dynamics:p,optionals:m,extract:h,rawParams:g})}}if(l)return l;if(r&&c){let n=c.index;for(let e=0;e<c.index;e++)n+=t[e].length;let r=n===e.length?`/`:e.slice(n);return c.rawParams??=Object.create(null),c.rawParams[`**`]=decodeURIComponent(r),c}return null}function Dj(e,t){return 2**(e-t-1)}function Oj(e,t){return e===2**(t-1)-1}function kj(e,t,n){let r,i;try{[r,i]=Cj(e,t,n)}catch{return null}if(n.rawParams=r,n.extract=i,!n.node.parse)return!0;try{if(n.node.parse(r)===!1)return null}catch{}return!0}function Aj(e,t){return!e||t.statics>e.statics||t.statics===e.statics&&(t.dynamics>e.dynamics||t.dynamics===e.dynamics&&(t.optionals>e.optionals||t.optionals===e.optionals&&((t.node.kind===cj)>(e.node.kind===cj)||t.node.kind===cj==(e.node.kind===cj)&&t.node.depth>e.node.depth)))}function jj(e){return Mj(e.filter(e=>e!==void 0).join(`/`))}function Mj(e){return e.replace(/\/{2,}/g,`/`)}function Nj(e){return e===`/`?e:e.replace(/^\/{1,}/,``)}function Pj(e){let t=e.length;return t>1&&e[t-1]===`/`?e.replace(/\/{1,}$/,``):e}function Fj(e){return Pj(Nj(e))}function Ij(e,t){return e?.endsWith(`/`)&&e!==`/`&&e!==`${t}/`?e.slice(0,-1):e}function Lj(e,t,n){return Ij(e,n)===Ij(t,n)}function Rj({base:e,to:t,trailingSlash:n=`never`,cache:r}){let i=t===`.`,a=t.startsWith(`/`),o;if(r){o=a?t:i?e:e+`\0`+t;let n=r.get(o);if(n)return n}let s;if(i)s=e.split(`/`);else if(a)s=t.split(`/`);else{for(s=e.split(`/`);s.length>1&&RA(s)===``;)s.pop();let n=t.split(`/`);for(let e=0,t=n.length;e<t;e++){let r=n[e];r===``?e?e===t-1&&s.push(r):s=[r]:r===`..`?s.length>1?s.pop():s=[``]:r===`.`||s.push(r)}}s.length>1&&(RA(s)===``?n===`never`&&s.pop():n===`always`&&s.push(``));let c=Mj(s.join(`/`))||`/`;return o&&r&&r.set(o,c),c}function zj(e){let t=new Map(e.map(e=>[encodeURIComponent(e),e])),n=Array.from(t.keys()).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`),r=new RegExp(n,`g`);return e=>e.replace(r,e=>t.get(e)??e)}function Bj(e,t,n){let r=t[e];return typeof r==`string`?e===`_splat`?/^[a-zA-Z0-9\-._~!/]*$/.test(r)?r:r.split(`/`).map(e=>Hj(e,n)).join(`/`):Hj(r,n):r}function Vj({path:e,params:t,decoder:n,...r}){let i=!1,a=Object.create(null);if(!e||e===`/`)return{interpolatedPath:`/`,usedParams:a,isMissingParams:i};if(!e.includes(`$`))return{interpolatedPath:e,usedParams:a,isMissingParams:i};let o=e.length,s=0,c,l=``;for(;s<o;){let r=s;c=dj(e,r,c);let o=c[5];if(s=o+1,r===o)continue;let u=c[0];if(u===0){l+=`/`+e.substring(r,o);continue}if(u===2){let s=t._splat;a._splat=s,a[`*`]=s;let u=e.substring(r,c[1]),d=e.substring(c[4],o);if(!s){i=!0,(u||d)&&(l+=`/`+u+d);continue}let f=Bj(`_splat`,t,n);l+=`/`+u+f+d;continue}if(u===1){let s=e.substring(c[2],c[3]);!i&&!(s in t)&&(i=!0),a[s]=t[s];let u=e.substring(r,c[1]),d=e.substring(c[4],o),f=Bj(s,t,n)??`undefined`;l+=`/`+u+f+d;continue}if(u===3){let i=e.substring(c[2],c[3]),s=t[i];if(s==null)continue;a[i]=s;let u=e.substring(r,c[1]),d=e.substring(c[4],o),f=Bj(i,t,n)??``;l+=`/`+u+f+d;continue}}return e.endsWith(`/`)&&(l+=`/`),{usedParams:a,interpolatedPath:l||`/`,isMissingParams:i}}function Hj(e,t){let n=encodeURIComponent(e);return t?.(n)??n}function Uj(e){return e?.isNotFound===!0}function Wj(){try{return sessionStorage}catch{return}}var Gj=`tsr-scroll-restoration-v1_3`,Kj=Wj();function qj(){try{return JSON.parse(Kj?.getItem(`tsr-scroll-restoration-v1_3`)||`{}`)}catch{return{}}}function Jj(){try{Kj?.setItem(Gj,JSON.stringify(Yj))}catch{}}var Yj=qj(),Xj=`data-scroll-restoration-id`,Zj=e=>e.state.__TSR_key||e.href;function Qj(e){let t=e.getAttribute(Xj);if(t)return`[${Xj}="${t}"]`;let n=``,r=e,i;for(;i=r.parentNode;){let e=1,t=r;for(;t=t.previousElementSibling;)e++;let a=`${r.localName}:nth-child(${e})`;n=n?`${a} > ${n}`:a,r=i}return n}var $j=!1,eM=`window`;function tM(e){try{return typeof e==`function`?e():document.querySelector(e)}catch{}}function nM(e){let t=new Set;for(let n of e){if(n===eM)continue;let e=tM(n);e&&t.add(e)}return t}function rM(e,t){let n=t??e.options.scrollRestoration,r=e._scroll;n&&(r.restoring=!0);let i=e.options.getScrollRestorationKey||Zj,a=new Set,o=e=>{let t=Yj[e]||={};for(let e of a)e===document?t[eM]={scrollX,scrollY}:e.isConnected&&(t[Qj(e)]={scrollX:e.scrollLeft,scrollY:e.scrollTop})};n&&!r.restoration&&(r.restoration=!0,$j=!1,history.scrollRestoration=`manual`,document.addEventListener(`scroll`,e=>{$j||a.add(e.target)},!0),e.subscribe(`onBeforeLoad`,e=>{e.fromLocation&&o(i(e.fromLocation)),a.clear()}),addEventListener(`pagehide`,()=>{o(i(e.stores.resolvedLocation.get()??e.stores.location.get())),Jj()})),!r.reset&&(r.reset=!0,e.subscribe(`onRendered`,t=>{let n=e.options.scrollRestorationBehavior,o=e.options.scrollToTopSelectors,s=r.next,c=r.hash,l;if(a.clear(),r.next=!0,r.hash=!1,typeof e.options.scrollRestoration==`function`&&!e.options.scrollRestoration({location:e.latestLocation}))return;let u=i(t.toLocation),d=t.fromLocation&&i(t.fromLocation);if(r.restoring&&d&&d!==u){let e=Yj[d];if(e){let t=Yj[u];for(let n in e){if(n===eM){if(s)continue}else{let e=tM(n);if(!e||s&&o&&(l??=nM(o),l.has(e)))continue}t||=Yj[u]={},t[n]??=e[n]}}}$j=!0;try{let e=t.toLocation.hash,i=t.toLocation.state.__hashScrollIntoViewOptions??!0,a=!1;if(s){!e&&o&&(l??=nM(o));let t=e&&i&&c,s=r.restoring?Yj[u]:void 0;if(s)for(let e in s){let{scrollX:r,scrollY:i}=s[e];if(e===eM){if(t)continue;scrollTo({top:i,left:r,behavior:n}),a=!0}else{let t=tM(e);t&&(t.scrollLeft=r,t.scrollTop=i,l?.delete(t))}}if(!e){let e={top:0,left:0,behavior:n};if(a||scrollTo(e),l)for(let t of l)t.scrollTo(e)}}!a&&e&&i&&document.getElementById(e)?.scrollIntoView(i)}finally{$j=!1}}))}function iM(e,t=String){let n=new URLSearchParams;for(let r in e){let i=e[r];i!==void 0&&n.set(r,t(i))}return n.toString()}function aM(e){return e?e===`false`?!1:e===`true`?!0:e*0==0&&+e+``===e?+e:e:``}function oM(e){let t=new URLSearchParams(e),n=Object.create(null);for(let[e,r]of t.entries()){let t=n[e];t==null?n[e]=aM(r):Array.isArray(t)?t.push(aM(r)):n[e]=[t,aM(r)]}return n}var sM=/^(?:\s|["[{\d-]|fa|nu|tr)/,cM=uM(JSON.parse),lM=dM(JSON.stringify,JSON.parse);function uM(e){return t=>{t[0]===`?`&&(t=t.substring(1));let n=oM(t);for(let t in n){let r=n[t];if(typeof r==`string`)try{n[t]=e(r)}catch{}}return n}}function dM(e,t){let n=t===JSON.parse;function r(r){if(r&&typeof r==`object`)try{return e(r)}catch{}else if(t&&typeof r==`string`){if(n&&!sM.test(r))return r;try{return t(r),e(r)}catch{}}return r}return e=>{let t=iM(e,r);return t?`?${t}`:``}}var fM=`__root__`;function pM(e){if(e.statusCode=e.statusCode||e.code||307,!e._builtLocation&&!e.reloadDocument&&typeof e.href==`string`)try{new URL(e.href),e.reloadDocument=!0}catch{}let t=new Headers(e.headers);e.href&&t.get(`Location`)===null&&t.set(`Location`,e.href);let n=new Response(null,{status:e.statusCode,headers:t});if(n.options=e,e.throw)throw n;return n}function mM(e){return e instanceof Response&&!!e.options}function hM(e){return{input:({url:t})=>{for(let n of e)t=_M(n,t);return t},output:({url:t})=>{for(let n=e.length-1;n>=0;n--)t=vM(e[n],t);return t}}}function gM(e){let t=Fj(e.basepath),n=`/${t}`,r=e.caseSensitive?n:n.toLowerCase(),i=`${r}/`;return{input:({url:t})=>{let a=e.caseSensitive?t.pathname:t.pathname.toLowerCase();return a===r?t.pathname=`/`:a.startsWith(i)&&(t.pathname=t.pathname.slice(n.length)),t},output:({url:e})=>(e.pathname=jj([`/`,t,e.pathname]),e)}}function _M(e,t){let n=e?.input?.({url:t});if(n){if(typeof n==`string`)return new URL(n);if(n instanceof URL)return n}return t}function vM(e,t){let n=e?.output?.({url:t});if(n){if(typeof n==`string`)return new URL(n);if(n instanceof URL)return n}return t}function yM(e,t){let{createMutableStore:n,createReadonlyStore:r,batch:i}=t,a=new Map,o=n(`idle`),s=n(e),c=n(void 0),l=n([]),u=r(()=>l.get().map(e=>a.get(e).get())),d=r(()=>({status:o.get(),isLoading:o.get()===`pending`,matches:u.get(),location:s.get(),resolvedLocation:c.get()}));function f(e){let t=a.get(e);return t||(t=n(void 0),a.set(e,t)),t}let p={status:o,location:s,resolvedLocation:c,ids:l,matches:u,byRoute:a,__store:d,getMatchStore:f,setMatches:m};function m(e){let t=l.get(),n=e.map(e=>e.routeId);i(()=>{aj(t,n)||l.set(n);for(let e of t)n.includes(e)||a.get(e).set(()=>void 0);for(let t of e){let e=f(t.routeId);e.get()!==t&&e.set(t)}})}return p}var bM=`__TSR_index`,xM=`popstate`,SM=`beforeunload`;function CM(e){let t=e.getLocation(),n=new Set,r=r=>{t=e.getLocation(),n.forEach(e=>e({location:t,action:r}))},i=n=>{e.notifyOnIndexChange??!0?r(n):t=e.getLocation()},a=async({task:n,navigateOpts:r,...i})=>{if(r?.ignoreBlocker??!1){n();return}let a=e.getBlockers?.()??[],o=i.type===`PUSH`||i.type===`REPLACE`;if(typeof document<`u`&&a.length&&o)for(let n of a){let r=OM(i.path,i.state);if(await n.blockerFn({currentLocation:t,nextLocation:r,action:i.type})){e.onBlocked?.();return}}n()};return{get location(){return t},get length(){return e.getLength()},subscribers:n,subscribe:e=>(n.add(e),()=>{n.delete(e)}),push:(n,i,o)=>{let s=t.state[bM];i=wM(s+1,i),a({task:()=>{e.pushState(n,i),r({type:`PUSH`})},navigateOpts:o,type:`PUSH`,path:n,state:i})},replace:(n,i,o)=>{let s=t.state[bM];i=wM(s,i),a({task:()=>{e.replaceState(n,i),r({type:`REPLACE`})},navigateOpts:o,type:`REPLACE`,path:n,state:i})},go:(t,n)=>{a({task:()=>{e.go(t),i({type:`GO`,index:t})},navigateOpts:n,type:`GO`})},back:t=>{a({task:()=>{e.back(t?.ignoreBlocker??!1),i({type:`BACK`})},navigateOpts:t,type:`BACK`})},forward:t=>{a({task:()=>{e.forward(t?.ignoreBlocker??!1),i({type:`FORWARD`})},navigateOpts:t,type:`FORWARD`})},canGoBack:()=>t.state[bM]!==0,createHref:t=>e.createHref(t),block:t=>{if(!e.setBlockers)return()=>{};let n=e.getBlockers?.()??[];return e.setBlockers([...n,t]),()=>{let n=e.getBlockers?.()??[];e.setBlockers?.(n.filter(e=>e!==t))}},flush:()=>e.flush?.(),destroy:()=>e.destroy?.(),notify:r}}function wM(e,t){t||={};let n=kM();return{...t,key:n,__TSR_key:n,[bM]:e}}function TM(e){let t=e?.window??(typeof document<`u`?window:void 0),n=t.history.pushState,r=t.history.replaceState,i=[],a=()=>i,o=e=>i=e,s=e?.createHref??(e=>e),c=e?.parseLocation??(()=>OM(`${t.location.pathname}${t.location.search}${t.location.hash}`,t.history.state));if(!t.history.state?.__TSR_key&&!t.history.state?.key){let e=kM();t.history.replaceState({[bM]:0,key:e,__TSR_key:e},``)}let l=c(),u,d=!1,f=!1,p=!1,m=!1,h=()=>l,g,_=()=>{g&&(S._ignoreSubscribers=!0,(g[2]?t.history.pushState:t.history.replaceState)(g[1],``,g[0]),S._ignoreSubscribers=!1,g=void 0,u=void 0)},v=(e,t,n)=>{let r=s(t),i=!!g;i||(u=l),l=OM(t,n),g=[r,n,g?.[2]||e],i||queueMicrotask(()=>_())},y=e=>{l=c(),S.notify({type:e})},b=async()=>{if(f){f=!1;return}let e=c(),n=e.state[bM]-l.state[bM],r=n===1,i=n===-1,o=!r&&!i||d;d=!1;let s=o?`GO`:i?`BACK`:`FORWARD`,u=o?{type:`GO`,index:n}:{type:i?`BACK`:`FORWARD`};if(p)p=!1;else{let n=a();if(typeof document<`u`&&n.length){for(let r of n)if(await r.blockerFn({currentLocation:l,nextLocation:e,action:s})){f=!0,t.history.go(1),S.notify(u);return}}}l=c(),S.notify(u)},x=e=>{if(m){m=!1;return}let t=!1,n=a();if(typeof document<`u`&&n.length)for(let e of n){let n=e.enableBeforeUnload??!0;if(n===!0){t=!0;break}if(typeof n==`function`&&n()===!0){t=!0;break}}if(t)return e.preventDefault(),e.returnValue=``},S=CM({getLocation:h,getLength:()=>t.history.length,pushState:(e,t)=>v(!0,e,t),replaceState:(e,t)=>v(!1,e,t),back:e=>(e&&(p=!0),m=!0,t.history.back()),forward:e=>{e&&(p=!0),m=!0,t.history.forward()},go:e=>{d=!0,t.history.go(e)},createHref:e=>s(e),flush:_,destroy:()=>{t.history.pushState=n,t.history.replaceState=r,t.removeEventListener(SM,x,{capture:!0}),t.removeEventListener(xM,b)},onBlocked:()=>{u&&l!==u&&(l=u)},getBlockers:a,setBlockers:o,notifyOnIndexChange:!1});return t.addEventListener(SM,x,{capture:!0}),t.addEventListener(xM,b),t.history.pushState=function(...e){let r=n.apply(t.history,e);return S._ignoreSubscribers||y(`PUSH`),r},t.history.replaceState=function(...e){let n=r.apply(t.history,e);return S._ignoreSubscribers||y(`REPLACE`),n},S}function EM(e={initialEntries:[`/`]}){let t=e.initialEntries,n=e.initialIndex?Math.min(Math.max(e.initialIndex,0),t.length-1):t.length-1,r=t.map((e,t)=>wM(t,void 0)),i=()=>OM(t[n],r[n]),a=[];return CM({getLocation:i,getLength:()=>t.length,pushState:(e,i)=>{n<t.length-1&&(t.splice(n+1),r.splice(n+1)),r.push(i),t.push(e),n=Math.max(t.length-1,0)},replaceState:(e,i)=>{r[n]=i,t[n]=e},back:()=>{n=Math.max(n-1,0)},forward:()=>{n=Math.min(n+1,t.length-1)},go:e=>{n=Math.min(Math.max(n+e,0),t.length-1)},createHref:e=>e,getBlockers:()=>a,setBlockers:e=>a=e})}function DM(e){let t=e.replace(/[\x00-\x1f\x7f]/g,``);return t.startsWith(`//`)&&(t=`/`+t.replace(/^\/+/,``)),t}function OM(e,t){let n=DM(e),r=n.indexOf(`#`),i=n.indexOf(`?`),a=kM();return{href:n,pathname:n.substring(0,r>0?i>0?Math.min(r,i):r:i>0?i:n.length),hash:r>-1?n.substring(r):``,search:i>-1?n.slice(i,r===-1?void 0:r):``,state:t||{[bM]:0,key:a,__TSR_key:a}}}function kM(){return(Math.random()+1).toString(36).substring(7)}function AM(e){return e.options.loader||e.options.beforeLoad||e.lazyFn||e.options.component?.preload||e.options.pendingComponent?.preload}function jM(e,t){return{fromLocation:t,toLocation:e,pathChanged:t?.pathname!==e.pathname,hrefChanged:t?.href!==e.href,hashChanged:t?.hash!==e.hash}}function MM({key:e,__TSR_key:t,__TSR_index:n,__hashScrollIntoViewOptions:r,...i}){return i}function NM(e,t,n,r){for(let i of t){if(r?.()===!1)return;n.some(e=>e.routeId===i.routeId)||e.routesById[i.routeId].options.onLeave?.(i)}for(let i of n){if(r?.()===!1)return;e.routesById[i.routeId].options[t.some(e=>e.routeId===i.routeId)?`onStay`:`onEnter`]?.(i)}}var PM=class{constructor(e,t){this.tempLocationKey=`${Math.round(Math.random()*1e7)}`,this._scroll={next:!0},this.subscribers=new Set,this._cache=new Map,this._committed=[],this.routeBranchCache=new WeakMap,this.lightweightCache=new WeakMap,this.startTransition=async e=>(e(),!1),this.update=e=>{let t=this.options,n=this.basepath??t?.basepath??`/`,r=this.basepath===void 0,i=t?.rewrite;if(this.options={...t,...e},this.isServer=this.options.isServer??!1??typeof document>`u`,this.protocolAllowlist=new Set(this.options.protocolAllowlist),this.options.pathParamsAllowedCharacters&&(this.pathParamsDecoder=zj(this.options.pathParamsAllowedCharacters)),(!this.history||this.options.history&&this.options.history!==this.history)&&(this.history=this.options.history?this.options.history:TM()),this.origin=this.options.origin,this.origin||=window?.origin&&window.origin!==`null`?window.origin:`http://localhost`,this.history&&this.updateLatestLocation(),this.options.routeTree!==this.routeTree){this.routeTree=this.options.routeTree;let e;this.resolvePathCache=sj(1e3),e=this.buildRouteTree(),this.setRoutes(e)}if(!this.stores&&this.latestLocation){let e=this.getStoreConfig(this);this.batch=e.batch,this.stores=yM(this.latestLocation,e),rM(this)}let a=this.options.basepath??`/`,o=this.options.rewrite;if(r||n!==a||i!==o){this.basepath=a;let e=[],t=Fj(a);t&&t!==`/`&&e.push(gM({basepath:a})),o&&e.push(o),this.rewrite=e.length===0?void 0:e.length===1?e[0]:hM(e),this.history&&this.updateLatestLocation(),this.stores&&this.stores.location.set(this.latestLocation)}},this.updateLatestLocation=()=>{this.latestLocation=this.parseLocation(this.history.location,this.latestLocation)},this.buildRouteTree=()=>{let e=xj(this.routeTree,this.options.caseSensitive,(e,t)=>{e.init({originalIndex:t})});return this.options.routeMasks&&gj(this.options.routeMasks,e.processedTree),e},this.subscribe=(e,t)=>{let n={eventType:e,fn:t};return this.subscribers.add(n),()=>{this.subscribers.delete(n)}},this.emit=e=>{for(let t of this.subscribers)if(t.eventType===e.type)try{t.fn(e)}catch(e){console.error(e)}},this.parseLocation=(e,t)=>{let n=({pathname:e,search:n,hash:r,href:i,state:a})=>{if(!this.rewrite&&!/[ \x00-\x1f\x7f\u0080-\uffff]/.test(e)){let i=this.options.parseSearch(n),o=this.options.stringifySearch(i);return{href:e+o+r,publicHref:e+o+r,pathname:rj(e).path,external:!1,searchStr:o,search:GA(t?.search,i),hash:rj(r.slice(1)).path,state:KA(t?.state,a)}}let o=new URL(i,this.origin),s=_M(this.rewrite,o),c=this.options.parseSearch(s.search),l=this.options.stringifySearch(c);return s.search=l,{href:s.href.replace(s.origin,``),publicHref:i,pathname:rj(s.pathname).path,external:!!this.rewrite&&s.origin!==this.origin,searchStr:l,search:GA(t?.search,c),hash:rj(s.hash.slice(1)).path,state:KA(t?.state,a)}},r=n(e),{__tempLocation:i,__tempKey:a}=r.state;if(i&&(!a||a===this.tempLocationKey)){let e=n(i);return e.state.key=r.state.key,e.state.__TSR_key=r.state.__TSR_key,delete e.state.__tempLocation,{...e,maskedLocation:r}}return r},this.resolvePathWithBase=(e,t)=>Rj({base:e,to:t.includes(`//`)?Mj(t):t,trailingSlash:this.options.trailingSlash,cache:this.resolvePathCache}),this.matchRoutes=(e,t,n)=>typeof e==`string`?this.matchRoutesInternal({pathname:e,search:t},n):this.matchRoutesInternal(e,t),this.getMatchedRoutes=e=>{let t=Object.create(null),n=yj(Pj(e),this.processedTree,!0);return n&&Object.assign(t,n.rawParams),[n?.branch||[this.routesById.__root__],t,n?.route]},this.buildLocation=e=>{let t=(t={})=>{let n=t._fromLocation||this._pendingLocation||this.latestLocation,r=this.matchRoutesLightweight(n);t.from;let i=t.unsafeRelative===`path`?n.pathname:t.from??r[1],a=t.to?`${t.to}`:void 0,o=r[2],s=Object.assign(Object.create(null),r[3]),c=a?.charCodeAt(0)===47?`/`:this.resolvePathWithBase(i,`.`),l=a?this.resolvePathWithBase(c,a):c,u=BM(t.params,s),d=this.routesByPath[Pj(l)],f;if(d)f=this.getRouteBranch(d);else if(l.includes(`$`))f=[];else{let[e,t,n]=this.getMatchedRoutes(l);f=e,this.options.notFoundRoute&&(!n||n.path!==`/`&&t[`**`])&&(f=[...f,this.options.notFoundRoute])}if(f.length&&UA(u))for(let e of f){let t=e.options.params?.stringify??e.options.stringifyParams;if(t)try{Object.assign(u,t(u))}catch{}}let p=e.leaveParams?l:rj(Vj({path:l,params:u,decoder:this.pathParamsDecoder,server:this.isServer}).interpolatedPath).path,m=o;if(e._includeValidateSearch&&this.options.search?.strict){let e={};f.forEach(t=>{if(t.options.validateSearch)try{Object.assign(e,LM(t.options.validateSearch,{...e,...m}))}catch{}}),m=e}m=RM(m,t,f,e._includeValidateSearch),m=GA(o,m);let h=this.options.stringifySearch(m),g=t.hash===!0?n.hash:t.hash?BA(t.hash,n.hash):void 0,_=g?`#${g}`:``,v=t.state===!0?n.state:t.state?BA(t.state,n.state):{};v=KA(n.state,v);let y=`${p}${h}${_}`,b,x,S=!1;if(this.rewrite){let e=new URL(y,this.origin),t=vM(this.rewrite,e);b=e.href.replace(e.origin,``),t.origin===this.origin?x=t.pathname+t.search+t.hash:(x=t.href,S=!0)}else b=ij(y),x=b;return{publicHref:x,href:b,pathname:p,search:m,searchStr:h,state:v,hash:g??``,external:S,unmaskOnReload:t.unmaskOnReload}},n=(n={},r)=>{let i=t(n),a=r?t(r):void 0;if(!a){let n=Object.create(null);if(this.options.routeMasks){let o=_j(i.pathname,this.processedTree);if(o){Object.assign(n,o.rawParams);let{from:i,params:s,...c}=o.route,l=BM(s,n);r={from:e.from,...c,params:l},a=t(r)}}}return a&&(i.maskedLocation=a),i};return e.mask?n(e,{from:e.from,...e.mask}):n(e)},this.commitLocation=async({viewTransition:e,ignoreBlocker:t,...n})=>{let r,i=Pj(this.latestLocation.href)===Pj(n.href)&&ZA(MM(n.state),MM(this.latestLocation.state)),a=this._commitPromise,o,s=new Promise(e=>{o=e});if(s.resolve=()=>{o(),a?.resolve()},this._commitPromise=s,i)this.load();else{let{maskedLocation:i,hashScrollIntoView:a,...o}=n;i&&(o={...i,state:{...i.state,__tempKey:void 0,__tempLocation:{...o,search:o.searchStr,state:{...o.state,__tempKey:void 0,__tempLocation:void 0,__TSR_key:void 0,key:void 0}}}},(o.unmaskOnReload??this.options.unmaskOnReload??!1)&&(o.state.__tempKey=this.tempLocationKey)),o.state.__hashScrollIntoViewOptions=a??this.options.defaultHashScrollIntoView??!0,this.shouldViewTransition=e,r=n.replace?`REPLACE`:`PUSH`,this.history[r===`REPLACE`?`replace`:`push`](o.publicHref,o.state,{ignoreBlocker:t}),this.history.subscribers.size||this.load({action:{type:r}})}return this._scroll.next=n.resetScroll??!0,this._commitPromise},this.buildAndCommitLocation=({replace:e,resetScroll:t,hashScrollIntoView:n,viewTransition:r,ignoreBlocker:i,_redirects:a,href:o,...s}={})=>{if(o){let t=this.history.location.state.__TSR_index,n=OM(o,{__TSR_index:e?t:t+1}),r=new URL(n.pathname,this.origin);s.to=_M(this.rewrite,r).pathname,s.search=this.options.parseSearch(n.search),s.hash=n.hash.slice(1)}let c=this.buildLocation({...s,_includeValidateSearch:!0});a&&(c._redirects=a),this._pendingLocation=c;let l=this.commitLocation({...c,viewTransition:r,replace:e,resetScroll:t,hashScrollIntoView:n,ignoreBlocker:i});return queueMicrotask(()=>{this._pendingLocation===c&&(this._pendingLocation=void 0)}),l},this.navigate=async({to:e,reloadDocument:t,href:n,publicHref:r,...i})=>{let a=!1;if(n)try{new URL(`${n}`),a=!0}catch{}if(a&&!t&&(t=!0),t){if(e!==void 0||!n){let t=this.buildLocation({to:e,...i});n??=t.publicHref,r??=t.publicHref}let t=!a&&r?r:n;if(nj(t,this.protocolAllowlist))return;if(!i.ignoreBlocker){let e=this.history.getBlockers?.()??[];for(let t of e)if(t?.blockerFn&&await t.blockerFn({currentLocation:this.latestLocation,nextLocation:this.latestLocation,action:`PUSH`}))return}i.replace?window.location.replace(t):window.location.href=t;return}return this.buildAndCommitLocation({...i,href:n,to:e,_isNavigate:!0})},this.load=async e=>{this.updateLatestLocation(),e?.action&&(this._scroll.hash=e.action.type===`PUSH`||e.action.type===`REPLACE`),await MN(this,e)},this.startViewTransition=e=>{let t=this.shouldViewTransition??this.options.defaultViewTransition;if(this.shouldViewTransition=void 0,t&&typeof document.startViewTransition==`function`){let n;if(typeof t==`object`&&window.CSS?.supports?.(`selector(:active-view-transition-type(a))`)){let r=this.latestLocation,i=this.stores.resolvedLocation.get(),a=typeof t.types==`function`?t.types(jM(r,i)):t.types;if(a===!1)return e();n={update:e,types:a}}else n=e;return document.startViewTransition(n).updateCallbackDone}return e()},this.invalidate=e=>{let t=this._committed,n=e?.filter,r=this._preloads,i=new Set([...t,...this._cache.values(),...[...r?.values()??[]].flat(),...this._tx?.[3]??[]].filter(e=>!n||n(e)).map(e=>e.id)),a=[];for(let[e,t]of r??[])t.some(e=>i.has(e.id))&&(r.delete(e),a.push(e));let o=t=>{if(i.has(t.id)){let n=this.routesById[t.routeId],r={...t,invalid:!0,...(e?.forcePending||t.status===`error`||t.status===`notFound`)&&AM(n)?{status:`pending`,error:void 0}:void 0};return t._flight=void 0,r}return t};this._committed=t.map(o);for(let[t,n]of this._cache)i.has(t)&&(n.invalid=!0,e?.forcePending&&(n.status=`pending`));for(let e of i)this._flights?.delete(e);for(let e of a)e.abort();return this.shouldViewTransition=!1,this.load({sync:e?.sync})},this.resolveRedirect=e=>{let t=e.headers.get(`Location`);if(!e.options.href||e.options._builtLocation){let t=(e.options._builtLocation??this.buildLocation(e.options)).publicHref||`/`;e.options.href=t,e.headers.set(`Location`,t)}else if(t)try{let n=new URL(t);if(this.origin&&n.origin===this.origin){let t=n.pathname+n.search+n.hash;e.options.href=t,e.headers.set(`Location`,t)}}catch{}if(e.options.href&&!e.options._builtLocation&&nj(e.options.href,this.protocolAllowlist))throw Error(`Redirect blocked: unsafe protocol`);return e.headers.get(`Location`)||e.headers.set(`Location`,e.options.href),e},this.clearCache=e=>{let t=this._cache,n=this._preloads,r=e?.filter,i=[],a=[];for(let[e,n]of t)(!r||r(n))&&(a.push(e),i.push(n));let o=[];for(let[e,t]of n??[])(!r||t.some(r))&&(o.push(e),i.push(...t));for(let e of a)t.delete(e);for(let e of o)n.delete(e);for(let e of i){let t=e._flight;e._flight=void 0,t&&!--t[2]&&(this._flights?.get(e.id)===t&&this._flights.delete(e.id),o.push(t[1]))}for(let e of o)e.abort()},this.loadRouteChunk=WM,this.preloadRoute=e=>NN(this,e),this.matchRoute=(e,t)=>{let n={...e,to:e.to?this.resolvePathWithBase(e.from||``,e.to):void 0,params:e.params||{},leaveParams:!0},r=this.buildLocation(n),i=this.stores.status.get()===`pending`;if(t?.pending&&!i)return!1;let a=t?.pending??!i?this.latestLocation:this.stores.resolvedLocation.get()||this.stores.location.get(),o=vj(r.pathname,t?.caseSensitive??!1,t?.fuzzy??!1,a.pathname,this.processedTree);return!o||e.params&&!ZA(o.rawParams,e.params,{partial:!0})?!1:t?.includeSearch??!0?ZA(a.search,r.search,{partial:!0})?o.rawParams:!1:o.rawParams},this.getStoreConfig=t,this.update({defaultPreloadDelay:50,defaultPendingMs:1e3,defaultPendingMinMs:500,context:void 0,...e,caseSensitive:e.caseSensitive??!1,notFoundMode:e.notFoundMode??`fuzzy`,stringifySearch:e.stringifySearch??lM,parseSearch:e.parseSearch??cM,protocolAllowlist:e.protocolAllowlist??tj}),self.__TSR_ROUTER__=this}isShell(){return!!this.options.isShell}get state(){return this.stores.__store.get()}setRoutes({routesById:e,routesByPath:t,processedTree:n}){this.routesById=e,this.routesByPath=t,this.processedTree=n;let r=this.options.notFoundRoute;r&&(r.init({originalIndex:99999999999}),this.routesById[r.id]=r)}getRouteBranch(e){let t=this.routeBranchCache.get(e);return t||(t=wj(e),this.routeBranchCache.set(e,t)),t}matchRoutesInternal(e,t){let[n,r,i]=this.getMatchedRoutes(e.pathname),a=n,o=!1;(i?i.path!==`/`&&r[`**`]:Pj(e.pathname))&&(this.options.notFoundRoute?a=[...a,this.options.notFoundRoute]:o=!0);let s=o?zM(this.options.notFoundMode,a):void 0,c=Array(a.length),l=this._committed,u=(e,t)=>{let n=l[t];return n?.routeId===e.id?n:e===this.options.notFoundRoute?l.find(t=>t.routeId===e.id):void 0},d;for(let n=0;n<a.length;n++){let i=a[n],o=c[n-1],l,f,p;{let n=o?.search??e.search,r=o?._strictSearch??void 0;try{let e=LM(i.options.validateSearch,{...n})??void 0;l={...n,...e},f={...r,...e}}catch(e){let r=e;if(e instanceof FM||(r=new FM(e.message,{cause:e})),t?.throwOnError)throw r;l=n,f={},p=r}}let m=``,h=``;try{m=i.options.loaderDeps?.({search:l})??``,h=m&&JSON.stringify(m)||``}catch(e){if(t?.throwOnError)throw e;p??=e}let{interpolatedPath:g,usedParams:_}=Vj({path:i.fullPath,params:r,decoder:this.pathParamsDecoder,server:this.isServer}),v=i.id+g+h,y=u(i,n),b=this._cache.get(v)??(y?.id===v?y:void 0);d=b?._strictParams??Object.assign(_,d);let x;if(!b)try{VM(i,d)}catch(e){if(x=Uj(e)||mM(e)?e:new IM(e.message,{cause:e}),t?.throwOnError)throw x}let S=y?`stay`:`enter`,C;if(b)C={...b,cause:S,search:GA(y?y.search:b.search,l),_strictSearch:f,searchError:p};else{let e=AM(i)?`pending`:`success`;C={id:v,ssr:i.options.ssr,index:n,routeId:i.id,params:y?.params??d,_strictParams:d,pathname:g,updatedAt:Date.now(),search:y?GA(y.search,l):l,_strictSearch:f,searchError:p,status:e,isFetching:!1,error:void 0,paramsError:x,context:{},abortController:t?._controller??new AbortController,cause:S,loaderDeps:y?KA(y.loaderDeps,m):m,invalid:!1,preload:!1,staticData:i.options.staticData||{},fullPath:i.fullPath}}let w=s===i.id;C._notFound&&!w&&(C.error=void 0),C._notFound=w,c[n]=C}for(let e=0;e<c.length;e++){let n=c[e];n.params=n.cause===`stay`?GA(n.params,d):d,t?._controller&&(n.context={})}return c}matchRoutesLightweight(e){let t=RA(this.stores.ids.get()),n=t?this.stores.byRoute.get(t).get():void 0,r=n?.id,i=this.lightweightCache.get(e);if(i&&i[0]===r)return i[1];let[a,o]=this.getMatchedRoutes(e.pathname),s=RA(a),c={...e.search};for(let e of a)try{Object.assign(c,LM(e.options.validateSearch,c))}catch{}let l=n&&n.routeId===s.id&&n.pathname===e.pathname,u;if(l)u=n.params;else{let e=Object.assign(Object.create(null),o);for(let t of a)try{VM(t,e)}catch{}u=e}let d=[a,s.fullPath,c,u];return this.lightweightCache.set(e,[r,d]),d}},FM=class extends Error{},IM=class extends Error{};function LM(e,t){if(e==null)return{};if(`~standard`in e){let n=e[`~standard`].validate(t);if(n instanceof Promise)throw new FM(`Async validation not supported`);if(n.issues)throw new FM(JSON.stringify(n.issues,void 0,2),{cause:n});return n.value}return`parse`in e?e.parse(t):typeof e==`function`?e(t):{}}function RM(e,t,n,r){let i=[];for(let e of n){let t=e.options;`search`in t?t.search?.middlewares&&i.push(...t.search.middlewares):(t.preSearchFilters||t.postSearchFilters)&&i.push(({search:e,next:n})=>{let r=n(t.preSearchFilters?t.preSearchFilters.reduce((e,t)=>t(e),e):e);return t.postSearchFilters?t.postSearchFilters.reduce((e,t)=>t(e),r):r});let n=t.validateSearch;n&&i.push(({search:e,next:t,meta:i})=>{let a=t(e);if(r)try{let e=LM(n,a);if(i&&e)for(let t in e)t in a||(i.defaulted||=new Map).set(t,e[t]);return{...a,...e}}catch{}return a})}let a=(e,n,r)=>{if(e>=i.length){if(!t.search)return{};if(t.search===!0)return n;let e=BA(t.search,n);return r&&(r.explicit=e),e}return i[e]({search:n,next:(t,n)=>{if(n){let n=r||{};return{search:a(e+1,t,n),meta:n}}return a(e+1,t,r)},meta:r})};return a(0,e)}function zM(e,t){if(e!==`root`){let e;for(let n=t.length-1;n>=0;n--){let r=t[n];if(r.options.notFoundComponent)return r.id;e||=r.children&&r.id}if(e)return e}return fM}function BM(e,t){return e===!1||e===null?Object.create(null):(e??!0)===!0?t:Object.assign(t,BA(e,t))}function VM(e,t){let n=e.options.params?.parse??e.options.parseParams;n&&Object.assign(t,n(t))}function HM(e,t){return e.options[t]?.preload?.()}function UM(e,t){let n=HM(e,`component`),r=HM(e,`pendingComponent`),i=t&&r?r.then(t):r;return t&&!r&&t(),n&&i?Promise.all([n,i]).then(()=>{}):n??i}function WM(e,t,n){let r=()=>t===!1?void 0:t?HM(e,t):UM(e,n),i=e._lazy;if(i)return i===!0?r():i.then(r);if(!e.lazyFn)return r();let a=e.lazyFn().then(t=>{{let{id:n,...r}=t.options;Object.assign(e.options,r),e._lazy=!0}},t=>{throw e._lazy=void 0,t});return e._lazy=a,a.then(r)}function GM(e){let t=e.findIndex(e=>e.status!==`success`||e._notFound)+1;return t&&t<e.length?e.slice(0,t):e}var KM=0,qM=1,JM=2,YM=3,XM=4;function ZM(e){return typeof e[0]==`number`}function QM(e,t){return t.aborted?Promise.race([Promise.reject(t),e]):new Promise((n,r)=>{let i=()=>r(t);t.addEventListener(`abort`,i,{once:!0}),Promise.resolve(e).then(n,r).finally(()=>t.removeEventListener(`abort`,i))})}function $M(e,t){return e.routesById[t.routeId]}function eN(e,t,n){return mM(e)?[YM,e]:Uj(e)?(e.routeId||=n,[JM,e]):(t&&typeof e?.then==`function`&&(e=Error(`A Promise was thrown`,{cause:e})),t?[qM,e]:[KM,e])}function tN(e,t){let n=eN(t,!0,e.id);if(n[0]!==qM)return n;try{e.options.onError?.(n[1])}catch(t){n=eN(t,!0,e.id)}return n}function nN(e,t,n){return n[0].signal.aborted||!n[2]()?(n[0].abort(),[XM]):tN(e,t)}function rN(e,t){return n=>e.navigate({...n,_fromLocation:t})}async function iN(e,t,n,r,i,a){let[o,s]=t,c=n[0].signal,l=!!n[4];for(let t=n[7]??0;t<r;t++){let r=s[t],i=$M(e,r);r.abortController=n[0];let u=s[t-1]?.context??e.options.context??{},d={params:r.params,location:o,navigate:rN(e,o),buildLocation:e.buildLocation,cause:l?`preload`:r.cause,abortController:n[0],preload:l,matches:s,routeId:i.id},f=u;try{let e=r._ctx;!e&&i.options.context&&(e=r._ctx=i.options.context({...d,deps:r.loaderDeps,context:u})||{}),f={...u,...e},r.context=f}catch(a){return oN(e,r),[t,nN(i,a,n)]}if(c.aborted||!n[2]())return n[0].abort(),[t,[XM]];let p=r.paramsError??r.searchError;if(p!==void 0)return oN(e,r),[t,nN(i,p,n)];let m=i.options.beforeLoad;if(!m)continue;let h={...d,search:r.search,context:f,...e.options.additionalContext},g=r.status;g===`success`&&t>=a&&(r.status=`pending`),n[8]?.();try{lN(e,r,`beforeLoad`,n[0]);let a=await QM(m(h),c);if(!n[2]())return n[0].abort(),[t,[XM]];let o=eN(a,!1,i.id);if(o[0]!==KM)return oN(e,r),[t,o];r.context={...f,...a}}catch(a){return oN(e,r),[t,nN(i,a,n)]}finally{g===`success`&&r.status===`pending`&&(r.status=`success`),lN(e,r,!1,n[0])}}i()}function aN(e,t,n){if(!(!n||--n[2])){if(e._flights?.get(t.id)===n){let n=e._tx;if(n&&!n[0].signal.aborted&&!n[3].includes(t)&&n[3].some(e=>e.id===t.id)&&n[3].some(e=>e.isFetching===`beforeLoad`))return;e._flights.delete(t.id)}return n[1]}}function oN(e,t){let n=t._flight;t._flight=void 0,aN(e,t,n)?.abort()}function sN(e,t,n,r){let i=[];for(let a of t)if(!n?.includes(a)){let t=a._flight;if(a._flight=void 0,r&&t?.[2]===1&&e._flights?.get(a.id)===t&&n?.some(e=>e.id===a.id))t[2]=0;else{let n=aN(e,a,t);n&&i.push(n)}}for(let e of i)e.abort()}function cN(e){for(let t of e){let e=t._flight;e&&e[2]++}}function lN(e,t,n,r){if(t.isFetching=n,r&&e._tx?.[0]!==r)return;let i=e.stores.byRoute.get(t.routeId),a=i?.get();a?.id===t.id&&i.set({...a,isFetching:n})}function uN(e,t,n,r,i,a,o){let s=t[0];return{params:n.params,location:s,navigate:rN(e,s),cause:o?`preload`:n.cause,abortController:i,preload:o,deps:n.loaderDeps,parentMatchPromise:a,context:n.context,route:r,...e.options.additionalContext}}async function dN(e,t,n,r,i,a,o,s){let c=s.signal;if(c.aborted)return[XM];if(!i)return[KM,void 0];let l=n._flight;lN(e,n,`loader`,s);try{if(!l){let s=new AbortController;l=[Promise.resolve().then(()=>i(uN(e,t,n,r,s,a,o))).then(e=>eN(e,!1,r.id),e=>eN(e,!0,r.id)).then(t=>(t[0]!==KM&&e._flights?.get(n.id)===l&&(e._flights.delete(n.id),l[2]||s.abort()),t[0]===qM&&l[2]?tN(r,t[1]):t)),s,1],(e._flights??=new Map).set(n.id,l)}return n._flight=l,n.abortController=l[1],await QM(l[0],c)}catch(t){if(t!==c)throw t;return oN(e,n),[XM]}finally{lN(e,n,!1,s)}}function fN(e,t,n){t[0]===KM?(e.loaderData=t[1],e.error=void 0,e.status=`success`,e.invalid=!1,e.updatedAt=Date.now(),e.preload=n):t[0]!==YM&&(e.status=`success`,e.error=void 0,e.invalid=!0)}function pN(e,t,n){let r=e._cache.get(t.id);if(r!==n||e._committed.some(e=>e.id===t.id&&e._flight===t._flight))return;let i={...t,_notFound:void 0,context:{}};i._flight&&i._flight[2]++,e._cache.set(t.id,i),r&&oN(e,r)}function mN(e,t){return t[0]===qM||t[0]===JM?{...e,status:t[0]===qM?`error`:`notFound`,error:t[1],_flight:void 0}:e}function hN(e,t,n,r,i,a,o){let s=t[1][n],c=$M(e,s),l=!!a[4],u=e._cache.get(s.id),d,f=!1,p;try{if(s.status===`success`&&(d=c.options.shouldReload,typeof d==`function`&&(d=d(uN(e,t,s,c,a[0],i,l))),a[2]()||(a[0].abort(),p=[XM])),!p){if(s.status!==`success`)f=!0;else{let t=a[4]||s.preload?c.options.preloadStaleTime??e.options.defaultPreloadStaleTime??3e4:c.options.staleTime??e.options.defaultStaleTime??0;f=!!(s.invalid||d||d===void 0&&Date.now()-s.updatedAt>=t&&(a[6]||s.cause===`enter`||a[3].some(e=>e.routeId===s.routeId&&e.id!==s.id)))}}}catch(t){s.invalid=!0,oN(e,s),p=nN(c,t,a)}let m=c.options.loader,h=typeof m==`function`?m:m?.handler,g=(!l||c.options.preload!==!1)&&m?e._flights?.get(s.id):void 0;g===s._flight||p?g=void 0:g&&!f&&!l&&d===void 0?f=!0:f||(g=void 0);let _=!!(m&&f&&s.status===`success`&&!l&&!a[5]&&((typeof m==`function`?void 0:m?.staleReloadMode)??e.options.defaultStaleReloadMode)!==`blocking`),v=f&&(!l||c.options.preload!==!1),y=v&&!_&&(s.status!==`success`||!!m),b=c.lazyFn&&c._lazy!==!0?a[8]:void 0;if(v&&!m&&(s.invalid=!1,s.updatedAt=Date.now()),g&&g[2]++,y){let t=s._flight;s._flight=g,aN(e,s,t)?.abort(),s.status===`success`&&n>=o&&(s.status=`pending`),a[8]?.()}v||(s.isFetching=!1);let x=(p?Promise.resolve(p):y?dN(e,t,s,c,h,i,l,a[0]):Promise.resolve([KM,s.loaderData])).then(t=>(y&&(fN(s,t,l),t[0]===KM&&(m&&!a[0].signal.aborted&&pN(e,s,u),s.status=`pending`)),t)),S=QM(Promise.resolve().then(()=>WM(c,void 0,b)),a[0].signal).then(()=>void 0,e=>[n,nN(c,e,a)]).then(e=>x.then(t=>(y&&!e&&t[0]===KM&&s.status===`pending`&&a[2]()&&(s.status=`success`,a[8]?.()),e)));if(r.push([n,x,S]),!_)return x.then(e=>mN(s,e));let C={...s,status:`pending`,preload:!1,_flight:g};s.invalid=!1,s.isFetching=`loader`;let w=dN(e,t,C,c,h,i,!1,a[0]).then(e=>(s.isFetching=!1,fN(C,e,!1),e));return(t[2]??=[]).push([n,w,S,C]),w.then(e=>mN(C,e))}async function gN(e,t,n,r,i=0){let a=n?.[1][1],o=a?.routeId?t.findIndex(e=>e.routeId===a.routeId):n?.[0]??t.length-1;o<0&&(o=0);for(let n=o;n>=0;n--){let i=$M(e,t[n]),a=WM(i,!1);if(a)try{await QM(a,r)}catch(e){if(e===r)throw e}if(i.options.notFoundComponent)return n}return a?.routeId?o:i}function _N(e,t){t[2]&&=(sN(e,t[2].map(e=>e[3])),void 0)}async function vN(e,t,n,r){let i;try{await Promise.all(e.map(e=>e[1].then(async t=>{let a=e[0];if(!(r&&a>=await r)){if(t[0]>=YM)throw[a,t];!i&&t[0]!==KM&&(i=[a,t],await Promise.all((n??[]).map(e=>{if(!(e[0]<=a))return e[1].then(t=>{if(t[0]===YM)throw[e[0],t]})})))}})))}catch(e){return e}return t??i}async function yN(e,t,n,r,i,a,o){let s=t[1],c=await a,l=!1,u=s.findIndex(e=>e._notFound),d=t=>t[1][0]===JM?gN(e,s,t,r.signal):t[0],f=u<0?s.length:u;if((c?.[1][0]??0)>=YM)f=0;else if(c){f=c[2]??=await d(c);for(let e of n){if(e[0]>=f)break;let t=await e[1];if(t[0]!==KM&&t[0]<YM&&!(`loaderData`in s[e[0]])){c=[e[0],t],f=c[2]=await d(c);break}}}for(let e of n){if(e[0]>=f)break;let t=await e[2];if(t){c=t;break}}if((c?.[1][0]??0)>=YM){let n=c[1];if(n[0]!==YM||n[1].options.reloadDocument||i<20)return _N(e,t),n;l=!0,c=[0,[qM,Error(`Too many redirects`)]]}let p=c?c[2]??await d(c):u;if(p>=0){let i=c?.[1],a=i?.[0],u=s[p],d=i?.[1],f=()=>{i&&(u._notFound=void 0,a===qM?u.status=`error`:(d.routeId=u.routeId,u.routeId===e.routeTree.id?(u.status=`success`,u._notFound=!0):u.status=`notFound`),u.error=d,u.isFetching=!1)};f();let m=$M(e,u);try{await QM(i?Promise.resolve().then(()=>WM(m,a===qM?`errorComponent`:`notFoundComponent`)):Promise.all([WM(m),WM(m,`notFoundComponent`)]),r.signal)}catch(n){if(n===r.signal)return _N(e,t),[XM]}i?l&&(r.abort(),await Promise.all([...n.map(e=>e[1]),...n.map(e=>e[2]),...(t[2]??[]).map(e=>e[1])]),_N(e,t),sN(e,s),f()):(u.status=`success`,o?.())}return t}async function bN(e,t,n,r=0,i=t[1].length){let a=t[1];for(let t=r;t<i;t++){let r=a[t],i=$M(e,r).options;if(i.head||i.scripts)try{let t={ssr:e.options.ssr,matches:a,match:r,params:r.params,loaderData:r.loaderData},[o,s]=await QM(Promise.all([i.head?.(t),i.scripts?.(t)]),n);r.meta=o?.meta,r.links=o?.links,r.headScripts=o?.scripts,r.styles=o?.styles,r.scripts=s}catch(e){if(e===n)break;console.error(e)}if(r.status!==`success`||r._notFound)break}return t}async function xN(e,t,n,r){let i=[t,n],a=e.stores.matches.get(),o=n.findIndex(e=>e._notFound);if(e.options.notFoundMode!==`root`&&o>=0){let t=await gN(e,i[1],void 0,r[0].signal,o);t!==o&&(n[o]._notFound=void 0,n[t]._notFound=!0),o=t}let s=o<0?n.length:o+1,c=0;for(;c<s&&c!==o;){let e=n[c],t=r[3][c],i=a[c];if(t?.id!==e.id||t.status!==`success`||t._notFound||e.preload||i?.id!==e.id||i.status!==`success`||i._notFound)break;c++}let l=[],u=r[7]??0,d=u?Promise.resolve(i[1][u-1]):void 0,f=()=>{for(let t=u;t<s&&!r[0].signal.aborted;t++)d=hN(e,i,t,l,d,r,c)},p=await iN(e,i,r,s,f,c);if(p&&(r[5]=!0,s=p[0],p[1][0]===JM?(p[2]=await gN(e,i[1],p,r[0].signal),s=Math.min(s,p[2]+1)):p[1][0]>=YM&&(s=0),f()),r[2]()&&!r[4]){let t=[];for(let[n,r]of e._flights??[])r[2]||(e._flights.delete(n),t.push(r[1]));for(let e of t)e.abort()}let m;try{let t=yN(e,i,l,r[0],r[1],vN(l,p,i[2]),r[8]);i[2]?.length&&(i[3]=vN(i[2],void 0,void 0,t.then(e=>ZM(e)?0:GM(e[1]).length,()=>0))),m=await t}catch(t){throw _N(e,i),t}return ZM(m)?m:bN(e,m,r[0].signal,r[7]===m[1].length?r[7]:0)}function SN(e,t){if(e._tx!==t)return;let n=e._pending,r=!1,i=n?.[0][3][n[1]]?.id;n?.[0]!==t&&(n&&t[3][n[1]]?.id===i?(n[0]=t,r=!0):(clearTimeout(n?.[3]),e._pending=n=void 0));let a=t[3],o=e.stores.matches.get(),s=-1,c,l,u,d=!1;for(let t=0;t<a.length;t++){let n=a[t],r=n.status===`success`;if(d=o[t]?.id===n.id&&o[t]?.status===`pending`,r&&!d)continue;let i=$M(e,n);if(c=r&&d||n.invalid?0:i.options.pendingMs??e.options.defaultPendingMs,u=i.options.pendingComponent??e.options.defaultPendingComponent,!u||typeof c!=`number`||c===1/0)return;s=t,l=i.options.pendingMinMs??e.options.defaultPendingMinMs??0;break}if(s<0)return;let f=a[s].id;if((!n||n[1]!==s||i!==f)&&(clearTimeout(n?.[3]),e._pending=n=[t,s,d?Date.now()+l:t[4]+c,void 0,d?Promise.resolve(!0):void 0,u]),n[4]&&!r&&n[5]===u)return;if(n[5]=u,!n[4]){clearTimeout(n[3]);let r=n[2]-Date.now();if(r>0){n[3]=setTimeout(()=>SN(e,t),r);return}n[2]=0}let p=a.map(e=>({...e,_flight:void 0}));p[s].status=`pending`;let m=e.startTransition(()=>e.stores.setMatches(p),p).then(t=>(t&&e._pending===n&&n[4]===m&&!n[2]&&(n[2]=Date.now()+l),t));n[4]=m}function CN(e,t){let n=e._pending;n?.[0]===t&&(clearTimeout(n[3]),e._pending=void 0)}function wN(e,t){e._committed=t,e.stores.setMatches(t)}function TN(e,t){sN(e,t[1]),_N(e,t)}function EN(e,t,n,r){let i=e._committed,a=e._cache;for(let e of n)e.preload=!1,r&&(e._assetEnd=void 0);let o=GM(n).length,s=new Map,c=Date.now();for(let t of[...i,...a.values()]){if(t.status!==`success`||n.some((e,n)=>e.id===t.id&&(n<o||e.status===`success`)))continue;let r=$M(e,t);!r.options.loader||c-t.updatedAt>=(t.preload?r.options.preloadGcTime??e.options.defaultPreloadGcTime??3e5:r.options.gcTime??e.options.defaultGcTime??3e5)||s.set(t.id,a.get(t.id)===t?t:{...t,_flight:void 0,isFetching:!1,context:{}})}t[3]=[],e._cache=s,wN(e,n),sN(e,[...a.values(),...i],[...n,...s.values()]),NM(e,i,n,()=>e._tx===t)}async function DN(e,t){let n=e._tx;for(;n&&n!==t;){if(await n[5],e._tx===n)return;n=e._tx}}async function ON(e,t,n){await e.navigate({...n.options,replace:!0,ignoreBlocker:!0,_redirects:t[1]+1})}function kN(e,t){CN(e,t),t[0].abort(),sN(e,t[3]),t[3]=[],e._tx===t&&(e.batch(()=>{e.stores.status.set(`idle`),e.stores.setMatches(e._committed)}),e._tx===t&&(e._commitPromise?.resolve(),e._commitPromise=void 0))}async function AN(e,t,n,r,i){let a=n.map(e=>({...e}));cN(a);for(let t of r)oN(e,a[t[0]]),a[t[0]]=t[3];let o=[t[2],a],s;try{s=await yN(e,o,r,t[0],t[1],i)}catch(t){throw sN(e,a),t}if(ZM(s)){sN(e,a),s[0]===YM&&e._tx===t&&e._committed===n&&await ON(e,t,s[1]);return}let c=await bN(e,s,t[0].signal);if(e._tx!==t||e._committed!==n){sN(e,c[1]);return}for(let t of c[1]){let n=e._cache.get(t.id);n?._flight&&n._flight===t._flight&&(e._cache.delete(t.id),oN(e,n))}wN(e,c[1]),sN(e,n,c[1])}async function jN(e,t,n,r,i,a){let o=[t[0],t[1],()=>e._tx===t&&!!t[3].length,e._committed,void 0,i,n,a,r],s=await xN(e,t[2],t[3],o);if(ZM(s)){s[0]===YM&&e._tx===t?(CN(e,t),sN(e,t[3]),t[3]=[],e._tx===t&&await ON(e,t,s[1])):kN(e,t);return}let c=e._pending;if(c?.[0]===t&&(clearTimeout(c[3]),c[4])){let n=t[0].signal,r=!1;try{r=await QM(c[4],n)}catch(e){if(e!==n)throw e}if(r&&e._pending===c&&c[0]===t){let e=c[2]-Date.now();if(e>0){try{await QM(new Promise(t=>{c[3]=setTimeout(t,e)}),n)}catch{}clearTimeout(c[3])}}}if(e._tx!==t){CN(e,t),TN(e,s);return}let l=t[2],u=jM(l,e.stores.resolvedLocation.get()),d=s[2];await e.startViewTransition(async()=>{if(e._tx!==t){TN(e,s);return}let n=await e.startTransition(()=>{CN(e,t),EN(e,t,s[1],a),e._tx===t&&(e.emit({type:`onLoad`,...u}),e._tx===t&&e.emit({type:`onBeforeRouteMount`,...u}))},s[1]);if(e._tx!==t){_N(e,s);return}d?.length&&AN(e,t,s[1],d,s[3]).catch(console.error),e.batch(()=>{e.stores.resolvedLocation.set(l),e.stores.status.set(`idle`),e._tx===t&&e.emit({type:`onResolved`,...u}),n&&e._tx===t&&e.emit({type:`onRendered`,...u})}),e._tx===t&&(e._commitPromise?.resolve(),e._commitPromise=void 0)})}async function MN(e,t){let n=e._tx,r=e.stores.resolvedLocation.get(),i=r??e.stores.location.get(),a=e.latestLocation,o=e._pendingLocation,s=o?.href===a.href?o._redirects??0:0,c=e._handoff,l=c?.[0](),u=new AbortController,d=e._preflight;if(e._preflight=u,l||c?.[1](),d?.abort(),u.signal.aborted){await DN(e,n);return}let f=jM(a,r);if(e.emit({type:`onBeforeNavigate`,...f}),u.signal.aborted||e.emit({type:`onBeforeLoad`,...f}),u.signal.aborted){await DN(e,n);return}let p=i.href===a.href,m,h=u;try{m=e.matchRoutes(a,{_controller:u}),cN(m)}catch(t){if(u.abort(),!mM(t)){await DN(e),e._commitPromise?.resolve(),e._commitPromise=void 0;return}await e.navigate({...t.options,replace:!0,ignoreBlocker:!0}),await DN(e,n);return}let g=l?c[1](m):void 0;if(g?h=l:l?.abort(),u.signal.aborted){sN(e,m),await DN(e,n);return}e._preflight=void 0;let _=[h,s,a,m,Date.now(),Promise.resolve().then(()=>jN(e,_,p,()=>SN(e,_),t?.sync,g)).catch(()=>{e._tx===_&&kN(e,_)})];if(e._tx=_,n){for(let t of e.stores.matches.get()){if(e._tx!==_)break;t.isFetching&&lN(e,t,!1)}n[0].abort(),sN(e,n[3],_[3],!0)}if(e._tx!==_){sN(e,_[3]),_[3]=[],await DN(e,_);return}e.batch(()=>{e.stores.status.set(`pending`),e.stores.location.set(a)}),!r&&!m.some(e=>e._notFound)&&SN(e,_);try{await _[5]}finally{await DN(e,_)}}async function NN(e,t,n=0){if(n>20)return;let r=t._builtLocation??e.buildLocation(t),i=e._committed,a=new AbortController,o;try{o=e.matchRoutes(r,{_controller:a}),cN(o)}catch(e){a.abort(),Uj(e)||console.error(e);return}(e._preloads??=new Map).set(a,o);let s;try{let t;try{t=await xN(e,r,o,[a,n,()=>!0,i,!0])}finally{s=e._preloads.delete(a),sN(e,o),a.abort()}if(!ZM(t))return t[1];if(s&&t[0]===YM&&!t[1].options.reloadDocument)return NN(e,{...t[1].options,_fromLocation:r},n+1)}catch(e){Uj(e)||console.error(e)}}var PN=`Error preloading route! ☝️`,FN=class{get to(){return this._to}get id(){return this._id}get path(){return this._path}get fullPath(){return this._fullPath}constructor(e){if(this.init=e=>{this.originalIndex=e.originalIndex;let t=this.options,n=!t?.path&&!t?.id;this.parentRoute=this.options.getParentRoute?.(),n?this._path=fM:this.parentRoute||oj();let r=n?fM:t?.path;r&&r!==`/`&&(r=Nj(r));let i=t?.id||r,a=n?fM:jj([this.parentRoute.id===`__root__`?``:this.parentRoute.id,i]);r===`__root__`&&(r=`/`),a!==`__root__`&&(a=jj([`/`,a]));let o=a===`__root__`?`/`:jj([this.parentRoute.fullPath,r]);this._path=r,this._id=a,this._fullPath=o,this._to=Pj(o)},this.addChildren=e=>this._addFileChildren(e),this._addFileChildren=e=>(Array.isArray(e)&&(this.children=e),typeof e==`object`&&e&&(this.children=Object.values(e)),this),this._addFileTypes=()=>this,this.updateLoader=e=>(Object.assign(this.options,e),this),this.update=e=>(Object.assign(this.options,e),this),this.lazy=e=>(this.lazyFn=e,this),this.redirect=e=>pM({from:this.fullPath,...e}),this.options=e||{},this.isRoot=!e?.getParentRoute,e?.id&&e?.path)throw Error(`Route cannot have both an 'id' and a 'path' option.`)}},IN=class extends FN{constructor(e){super(e)}};function LN(e){return(0,Y.jsx)(RN,{...e})}var RN=class extends q.Component{constructor(...e){super(...e),this.state={error:null},this.reset=()=>{this.setState({error:null})}}static getDerivedStateFromProps(e,t){let n=e.getResetKey();return t.error&&t.resetKey!==n?{resetKey:n,error:null}:{resetKey:n}}static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){this.props.onCatch?.(e,t)}render(){let e=this.state.error;return e?q.createElement(this.props.errorComponent??zN,{error:e,reset:this.reset}):this.props.children}};function zN({error:e}){let[t,n]=q.useState(!1);return(0,Y.jsxs)(`div`,{style:{padding:`.5rem`,maxWidth:`100%`},children:[(0,Y.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`.5rem`},children:[(0,Y.jsx)(`strong`,{style:{fontSize:`1rem`},children:`Something went wrong!`}),(0,Y.jsx)(`button`,{style:{appearance:`none`,fontSize:`.6em`,border:`1px solid currentColor`,padding:`.1rem .2rem`,fontWeight:`bold`,borderRadius:`.25rem`},onClick:()=>n(e=>!e),children:t?`Hide Error`:`Show Error`})]}),(0,Y.jsx)(`div`,{style:{height:`.25rem`}}),t?(0,Y.jsx)(`div`,{children:(0,Y.jsx)(`pre`,{style:{fontSize:`.7em`,border:`1px solid red`,borderRadius:`.25rem`,padding:`.3rem`,color:`red`,overflow:`auto`},children:e.message?(0,Y.jsx)(`code`,{children:e.message}):null})}):null]})}function BN({children:e,fallback:t=null}){return(0,Y.jsx)(q.Fragment,{children:VN()?e:t})}function VN(){return q.useSyncExternalStore(HN,()=>!0,()=>!1)}function HN(){return()=>{}}var UN=q.createContext(null);function WN(e){return q.useContext(UN)}var GN=q.createContext(void 0),KN=q.createContext(void 0),qN=(e=>(e[e.None=0]=`None`,e[e.Mutable=1]=`Mutable`,e[e.Watching=2]=`Watching`,e[e.RecursedCheck=4]=`RecursedCheck`,e[e.Recursed=8]=`Recursed`,e[e.Dirty=16]=`Dirty`,e[e.Pending=32]=`Pending`,e))(qN||{});function JN({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0){n=e.nextSub;continue}for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}while(!0)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(!0)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function YN(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}var XN=[],ZN=0,{link:QN,unlink:$N,propagate:eP,checkDirty:tP,shallowPropagate:nP}=JN({update(e){return e._update()},notify(e){XN[iP++]=e,e.flags&=~qN.Watching},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=qN.Mutable|qN.Dirty,cP(e))}}),rP=0,iP=0,aP,oP=0;function sP(e){try{++oP,e()}finally{--oP||lP()}}function cP(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=$N(n,e)}function lP(){if(!(oP>0)){for(;rP<iP;){let e=XN[rP];XN[rP++]=void 0,e.notify()}rP=0,iP=0}}function uP(e,t){let n=typeof e==`function`,r=e,i={_snapshot:n?void 0:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:n?qN.None:qN.Mutable,get(){return aP!==void 0&&QN(i,aP,ZN),i._snapshot},subscribe(e){let t=YN(e),n={current:!1},r=dP(()=>{i.get(),n.current?t.next?.(i._snapshot):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=aP,o=t?.compare??Object.is;if(n)aP=i,++ZN,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=qN.Mutable|qN.RecursedCheck);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{aP=a,n&&(i.flags&=~qN.RecursedCheck),cP(i)}}};return n?(i.flags=qN.Mutable|qN.Dirty,i.get=function(){let e=i.flags;if(e&qN.Dirty||e&qN.Pending&&tP(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&nP(e)}}else e&qN.Pending&&(i.flags=e&~qN.Pending);return aP!==void 0&&QN(i,aP,ZN),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(eP(e),nP(e),lP())}},i}function dP(e){let t=()=>{let t=aP;aP=n,++ZN,n.depsTail=void 0,n.flags=qN.Watching|qN.RecursedCheck;try{return e()}finally{aP=t,n.flags&=~qN.RecursedCheck,cP(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:qN.Watching|qN.RecursedCheck,notify(){let e=this.flags;e&qN.Dirty||e&qN.Pending&&tP(this.deps,this)?t():this.flags=qN.Watching},stop(){this.flags=qN.None,this.depsTail=void 0,cP(this)}};return t(),n}var fP=t((e=>{var t=Bt();function n(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var r=typeof Object.is==`function`?Object.is:n,i=t.useState,a=t.useEffect,o=t.useLayoutEffect,s=t.useDebugValue;function c(e,t){var n=t(),r=i({inst:{value:n,getSnapshot:t}}),c=r[0].inst,u=r[1];return o(function(){c.value=n,c.getSnapshot=t,l(c)&&u({inst:c})},[e,n,t]),a(function(){return l(c)&&u({inst:c}),e(function(){l(c)&&u({inst:c})})},[e]),s(n),n}function l(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!r(e,n)}catch{return!0}}function u(e,t){return t()}var d=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?u:c;e.useSyncExternalStore=t.useSyncExternalStore===void 0?d:t.useSyncExternalStore})),pP=t(((e,t)=>{t.exports=fP()})),mP=t((e=>{var t=Bt(),n=pP();function r(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var i=typeof Object.is==`function`?Object.is:r,a=n.useSyncExternalStore,o=t.useRef,s=t.useEffect,c=t.useMemo,l=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,u){var d=o(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=c(function(){function e(e){if(!a){if(a=!0,o=e,e=r(e),u!==void 0&&f.hasValue){var t=f.value;if(u(t,e))return s=t}return s=e}if(t=s,i(o,e))return t;var n=r(e);return u!==void 0&&u(t,n)?(o=e,t):(o=e,s=n)}var a=!1,o,s,c=n===void 0?null:n;return[function(){return e(t())},c===null?void 0:function(){return e(c())}]},[t,n,r,u]);var p=a(e,d[0],d[1]);return s(function(){f.hasValue=!0,f.value=p},[p]),l(p),p}})),hP=t(((e,t)=>{t.exports=mP()}))();function gP(e,t){return e===t}function _P(e,t,n=gP){let r=(0,q.useCallback)(t=>{if(!e)return()=>{};let{unsubscribe:n}=e.subscribe(t);return n},[e]),i=(0,q.useCallback)(()=>e?.get(),[e]);return(0,hP.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var vP={};function yP(e,t){let n=q.useRef();return r=>{let i=e?.select?e.select(r):r;return e?.structuralSharing??t.options.defaultStructuralSharing?n.current=KA(n.current,i):i}}function bP(e){let t=WN(),n=q.useContext(e.from?KN:GN),r=e.from??n,i=t.stores.getMatchStore(r),a=yP(e,t),o=_P(i,e=>e?a(e):vP);if(o!==vP)return o;(e.shouldThrow??!0)&&oj()}function xP(e){return bP({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function SP(e){let{select:t,...n}=e;return bP({...n,select:e=>t?t(e.loaderDeps):e.loaderDeps})}function CP(e){return bP({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{let n=e.strict===!1?t.params:t._strictParams;return e.select?e.select(n):n}})}function wP(e){return bP({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function TP(e){let t=WN();return q.useCallback(n=>t.navigate({...n,from:n.from??e?.from}),[e?.from,t])}function EP(e){return bP({...e,select:t=>e.select?e.select(t.context):t.context})}function DP(e){let t=q.useRef(e);return ZA(t.current,e,{ignoreUndefined:!1})||(t.current=e),t.current}function OP(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]}function kP(e,t,n){if(e?.external)return nj(e.href,n)?void 0:e.href;if(!BP(t)&&typeof t==`string`&&t.indexOf(`:`)!==-1)try{return new URL(t),nj(t,n)?void 0:t}catch{}}function AP(e,t,n,r,i,a){if(a)return!1;if(n?.exact){if(!Lj(e.pathname,t.pathname,r))return!1}else{let n=Ij(e.pathname,r),i=Ij(t.pathname,r);if(!(n.startsWith(i)&&(n.length===i.length||n[i.length]===`/`)))return!1}return(n?.includeSearch??!0)&&!ZA(e.search,t.search,{partial:!n?.exact,ignoreUndefined:!n?.explicitUndefined})?!1:!n?.includeHash||i&&e.hash===t.hash}function jP(e,t){let n=WN(),r=LA(t),{activeProps:i,inactiveProps:a,activeOptions:o,to:s,preload:c,preloadDelay:l,preloadIntentProximity:u,hashScrollIntoView:d,replace:f,startTransition:p,resetScroll:m,viewTransition:h,children:g,target:_,disabled:v,style:y,className:b,onClick:x,onBlur:S,onFocus:C,onMouseEnter:w,onMouseLeave:T,onTouchStart:E,ignoreBlocker:ee,params:D,search:O,hash:k,state:A,mask:j,reloadDocument:te,unsafeRelative:ne,from:re,_fromLocation:ie,...ae}=e,oe=VN(),se=DP(e.search),ce=DP(e.params),le=DP(o),ue=q.useMemo(()=>e,[n,e.from,e._fromLocation,e.hash,e.to,se,ce,e.state,e.mask,e.unsafeRelative]),M=q.useCallback(e=>{let t=n.buildLocation({_fromLocation:e,...ue}),r=zP(t.maskedLocation?t.maskedLocation.publicHref:t.publicHref,t.maskedLocation?t.maskedLocation.external:t.external,n.history,v),i=kP(r,s,n.protocolAllowlist);return[r?.href,i,AP(e,t,le,n.basepath,oe,i!==void 0)]},[le,v,oe,ue,n,s]),[de,fe,pe]=_P(n.stores.location,M,OP),me=pe?BA(i,{})??NP:MP,he=pe?MP:BA(a,{})??MP,ge=[b,me.className,he.className].filter(Boolean).join(` `),_e=(y||me.style||he.style)&&{...y,...me.style,...he.style},ve=q.useRef(!1),ye=e.reloadDocument||fe||v?!1:c??n.options.defaultPreload,be=l??n.options.defaultPreloadDelay??0,N=q.useCallback(()=>{n.preloadRoute(ue).catch(e=>{console.warn(e),console.warn(PN)})},[n,ue]),xe=q.useCallback(e=>{if(!e){LP(r);return}if(!(e.isIntersecting??ye===`intent`)){e.isIntersecting===!1&&LP(r);return}if(!be){N();return}IP.has(r)||IP.set(r,setTimeout(()=>{IP.delete(r),N()},be))},[N,r,ye,be]);IA(r,xe,ye!==`viewport`),q.useEffect(()=>{ve.current||ye===`render`&&(N(),ve.current=!0)},[N,ye]);let Se=e=>{let t=e.currentTarget.getAttribute(`target`),r=_===void 0?t:_;!v&&!HP(e)&&!e.defaultPrevented&&(!r||r===`_self`)&&e.button===0&&(e.preventDefault(),n.navigate({...ue,replace:f,resetScroll:m,hashScrollIntoView:d,startTransition:p,viewTransition:h,ignoreBlocker:ee}))};if(fe)return{...ae,ref:r,href:fe,...g&&{children:g},..._&&{target:_},...v&&{disabled:v},...y&&{style:y},...b&&{className:b},...x&&{onClick:x},...S&&{onBlur:S},...C&&{onFocus:C},...w&&{onMouseEnter:w},...T&&{onMouseLeave:T},...E&&{onTouchStart:E}};let Ce=()=>{ye===`intent`&&N()},we=()=>{ye===`intent`&&LP(r)};return{...ae,...me,...he,href:de,ref:r,onClick:RP([x,Se]),onBlur:RP([S,we]),onFocus:RP([C,xe]),onMouseEnter:RP([w,xe]),onMouseLeave:RP([T,we]),onTouchStart:RP([E,Ce]),disabled:!!v,target:_,..._e&&{style:_e},...ge&&{className:ge},...v&&PP,...pe&&FP}}var MP={},NP={className:`active`},PP={role:`link`,"aria-disabled":!0},FP={"data-status":`active`,"aria-current":`page`},IP=new WeakMap,LP=e=>{clearTimeout(IP.get(e)),IP.delete(e)},RP=e=>t=>{for(let n of e)if(n){if(t.defaultPrevented)return;n(t)}};function zP(e,t,n,r){if(!r)return t?{href:e,external:!0}:{href:n.createHref(e)||`/`,external:!1}}function BP(e){if(typeof e!=`string`)return!1;let t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}var VP=q.forwardRef((e,t)=>{let{_asChild:n,...r}=e,{type:i,...a}=jP(r,t),o=typeof r.children==`function`?r.children({isActive:a[`data-status`]===`active`}):r.children;if(!n){let{disabled:e,...t}=a;return q.createElement(`a`,t,o)}return q.createElement(n,a,o)});function HP(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}var UP=class extends FN{constructor(e){super(e),this.useMatch=e=>bP({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>EP({...e,from:this.id}),this.useSearch=e=>wP({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>CP({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>SP({...e,from:this.id}),this.useLoaderData=e=>xP({...e,from:this.id}),this.useNavigate=()=>TP({from:this.fullPath}),this.Link=q.forwardRef((e,t)=>(0,Y.jsx)(VP,{ref:t,from:this.fullPath,...e}))}};function WP(e){return new UP(e)}var GP=class extends IN{constructor(e){super(e),this.useMatch=e=>bP({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>EP({...e,from:this.id}),this.useSearch=e=>wP({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>CP({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>SP({...e,from:this.id}),this.useLoaderData=e=>xP({...e,from:this.id}),this.useNavigate=()=>TP({from:this.fullPath}),this.Link=q.forwardRef((e,t)=>(0,Y.jsx)(VP,{ref:t,from:this.fullPath,...e}))}};function KP(e){return new GP(e)}function qP(e){let t=WN(),n=`not-found-${_P(t.stores.location,e=>e.pathname)}-${_P(t.stores.status,e=>e)}`;return(0,Y.jsx)(LN,{getResetKey:()=>n,onCatch:(t,n)=>{if(Uj(t))e.onCatch?.(t,n);else throw t},errorComponent:({error:t})=>{if(Uj(t))return e.fallback?.(t);throw t},children:e.children})}function JP(){return(0,Y.jsx)(`p`,{children:`Not Found`})}function YP(e){return(0,Y.jsx)(Y.Fragment,{children:e.children})}function XP(e,t,n){return t.options.notFoundComponent?(0,Y.jsx)(t.options.notFoundComponent,{...n}):e.options.defaultNotFoundComponent?(0,Y.jsx)(e.options.defaultNotFoundComponent,{...n}):(0,Y.jsx)(JP,{})}function ZP(e,t){let n=t?.options.pendingComponent??e.options.defaultPendingComponent;return n?(0,Y.jsx)(n,{}):null}var QP=(e,t)=>e[0]===t[0]&&e[1]===t[1],$P=(e,t,n)=>!t.isRoot||t.options.shellComponent||t.options.wrapInSuspense||n===!1||n===`data-only`||!e.ssr,eF=q.memo(function({routeId:e}){let t=WN();return(0,Y.jsx)(tF,{router:t,match:_P(t.stores.getMatchStore(e),e=>e)})});function tF({router:e,match:t}){let n=e.routesById[t.routeId],r=ZP(e,n),i=n.options.errorComponent??e.options.defaultErrorComponent,a=n.options.onCatch??e.options.defaultOnCatch,o=n.isRoot?n.options.notFoundComponent??e.options.notFoundRoute?.options.component:n.options.notFoundComponent,s=t.ssr===!1||t.ssr===`data-only`,c=$P(e,n,t.ssr)&&(n.options.wrapInSuspense??r??(n.options.errorComponent?.preload||s))?q.Suspense:YP,l=i?LN:YP,u=o?qP:YP;return(0,Y.jsxs)(n.isRoot?n.options.shellComponent??YP:YP,{children:[(0,Y.jsx)(GN.Provider,{value:t.routeId,children:(0,Y.jsx)(c,{fallback:r,children:(0,Y.jsx)(l,{getResetKey:()=>t,errorComponent:i,onCatch:(e,n)=>{if(Uj(e))throw e.routeId??=t.routeId,e;a?.(e,n)},children:(0,Y.jsx)(u,{fallback:e=>{if(e.routeId??=t.routeId,e.routeId!==t.routeId)throw e;return q.createElement(o,e)},children:s?(0,Y.jsx)(BN,{fallback:r,children:(0,Y.jsx)(nF,{match:t})}):(0,Y.jsx)(nF,{match:t})})})})}),null]})}var nF=q.memo(function({match:e}){let t=WN(),n=e.routeId,r=t.routesById[n],i=q.useMemo(()=>{let i=(r.options.remountDeps??t.options.defaultRemountDeps)?.({routeId:n,loaderDeps:e.loaderDeps,params:e._strictParams,search:e._strictSearch});return i?JSON.stringify(i):void 0},[n,e.loaderDeps,e._strictParams,e._strictSearch,r.options.remountDeps,t.options.defaultRemountDeps]),a=q.useMemo(()=>{let e=r.options.component??t.options.defaultComponent;return e?(0,Y.jsx)(e,{},i):(0,Y.jsx)(rF,{})},[i,r.options.component,t.options.defaultComponent]);if(e.status===`pending`){if(t.ssr&&!$P(t,r,e.ssr))return a;if(t._tx)throw t._tx[5];return ZP(t,r)}if(e.status===`notFound`)return XP(t,r,e.error);if(e.status===`error`)throw e.error;return a}),rF=q.memo(function(){let e=WN(),t=q.useContext(GN),n,r,i;{let a=e.stores.getMatchStore(t);[n,r]=_P(a,e=>[!!e._notFound,e.error],QP),i=_P(e.stores.ids,e=>e[e.indexOf(t)+1])}if(n)return XP(e,e.routesById[t],r);if(!i)return null;let a=(0,Y.jsx)(eF,{routeId:i});return t===`__root__`?(0,Y.jsx)(q.Suspense,{fallback:ZP(e),children:a}):a});function iF(e,t){let n=e[1];e.length=0,n?.(t)}function aF({t:e}){let t=WN(),n=t._rendered??=[];return t.startTransition=(r,i)=>new Promise((a,o)=>{iF(n,!1),n.push(i,a),e(t),q.startTransition(()=>{try{r()}catch(e){n[1]===a&&(n.length=0),o(e)}})}),FA(()=>{let e=t.history.subscribe(t.load);t.updateLatestLocation();let r=t.latestLocation,i=t.buildLocation({to:r.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});if(Pj(r.publicHref)!==Pj(i.publicHref))return t.commitLocation({...i,replace:!0,ignoreBlocker:!0}),e;let a=t.stores.resolvedLocation.get();return a?.href===r.href&&a.state.__TSR_key===r.state.__TSR_key?n.push(t.stores.matches.get(),e=>{e&&t.emit({type:`onRendered`,...jM(a,a)})}):t._tx||t.load().catch(console.error),e},[t,t.history]),null}function oF(){let e=WN(),t=e.routesById[fM],n=ZP(e,t),r=e.ssr?YP:q.Suspense,i=(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(aF,{t:q.useState()[1]}),(0,Y.jsx)(r,{fallback:n,children:(0,Y.jsx)(sF,{})})]});return e.options.InnerWrap?(0,Y.jsx)(e.options.InnerWrap,{children:i}):i}function sF(){let e=WN(),t=e._rendered,n=_P(e.stores.matches,e=>t[0]??e),r=n[0],i=r?.routeId;FA(()=>{t[0]===n&&iF(t,!0)},[t,n]);let a=i?(0,Y.jsx)(eF,{routeId:i}):null;return(0,Y.jsx)(GN.Provider,{value:i,children:e.options.disableGlobalCatchBoundary?a:(0,Y.jsx)(LN,{getResetKey:()=>r,onCatch:void 0,children:a})})}var cF=e=>({createMutableStore:uP,createReadonlyStore:uP,batch:sP}),lF=e=>new uF(e),uF=class extends PM{constructor(e){super(e,cF)}};function dF({router:e,children:t,...n}){UA(n)&&e.update({...e.options,...n,context:{...e.options.context,...n.context}});let r=(0,Y.jsx)(UN.Provider,{value:e,children:t});return e.options.Wrap?(0,Y.jsx)(e.options.Wrap,{children:r}):r}function fF({router:e,...t}){return(0,Y.jsx)(dF,{router:e,...t,children:(0,Y.jsx)(oF,{})})}function pF(e){let t=WN({warn:e?.router===void 0}),n=e?.router||t;return _P(n.stores.__store,yP(e,n))}function mF(){return _P(WN().stores.location,e=>e.state.__TSR_index!==0)}var hF=(0,q.createContext)(null),gF=hF.Provider,_F=KP({validateSearch:Dr({agent:P().min(1).optional()}),component:()=>null}),vF=WP({getParentRoute:()=>_F,path:`/`}),yF=WP({getParentRoute:()=>_F,path:`/sessions/$agentId/$sessionId`,params:{parse:e=>Dr({agentId:P().min(1),sessionId:P().min(1)}).parse(e)}});function bF(){return lF({routeTree:_F.addChildren([vF,yF]),history:EM(),InnerWrap:({children:e})=>(0,Y.jsxs)(Y.Fragment,{children:[(0,q.useContext)(hF),e]}),defaultPendingMs:0,defaultPendingMinMs:0})}function xF(e,t){let n=pF({router:e,select:e=>e.location.search}),r=bP({from:yF.id,shouldThrow:!1});gh(t,{canGoBack:mF(),onBack:()=>e.history.canGoBack()?(e.history.back(),!0):!1});let i=(0,q.useCallback)(t=>{e.navigate({to:`.`,search:{agent:t??void 0},replace:!0})},[e]),a=(0,q.useCallback)((t,n)=>{e.navigate({to:`/sessions/$agentId/$sessionId`,params:{agentId:t,sessionId:n},search:!0})},[e]);return{agentFilterId:n.agent??null,setFilter:i,selection:r?.params,open:a}}var SF=ea.check(H(1,{message:`Give your Agent a name.`}),K(256,{message:`Use at most 256 characters.`}));function CF({agentId:e,name:t,rename:n}){let[r,i]=(0,q.useState)(!1),a=eA({schema:(0,q.useMemo)(()=>I({name:SF.annotate(Ek({label:`Agent name`,render:e=>(0,Y.jsx)(cn,{id:e.id,name:e.name,"aria-label":`Agent name`,"aria-invalid":e[`aria-invalid`],"aria-describedby":e[`aria-describedby`],autoFocus:!0,maxLength:256,disabled:e.disabled,value:e.value,onBlur:e.onBlur,onChange:t=>{e.onChange(t.currentTarget.value)}})}))}),[]),defaultValues:{name:t},onSubmit:async({name:r})=>r===t||await n(e,r)?(i(!1),{kind:`saved`,values:{name:r}}):{kind:`refused`}}),{submitting:o,canSubmit:s}=tA(a);return r?(0,Y.jsxs)(iA,{model:a,"aria-label":`Rename Agent`,footer:null,className:`flex min-w-0 items-center gap-1`,children:[(0,Y.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,Y.jsx)(xk,{model:a,names:[`name`]})}),(0,Y.jsx)(Zt,{type:`submit`,size:`sm`,loading:o,disabled:o||!s,children:`Save`}),(0,Y.jsx)(Tt,{"aria-label":`Cancel rename`,type:`button`,icon:(0,Y.jsx)(Ln,{size:14,"aria-hidden":`true`}),onClick:()=>{i(!1)}})]}):(0,Y.jsx)(Tt,{"aria-label":`Rename Agent`,icon:(0,Y.jsx)(uT,{size:14,"aria-hidden":`true`}),onClick:()=>{i(!0)}})}function wF({status:e,approving:t,onApprove:n}){return e?.status===`pending`?(0,Y.jsx)(Zt,{variant:`outline`,size:`sm`,className:`flex-none`,loading:t,disabled:t,onClick:n,children:`Allow App tools`}):null}Fi()([],()=>(e,t,n)=>vi({try:()=>M_(e,n.onExcessProperty===`error`),catch:()=>new eo(t,e,n)}));var TF={artifactRef:Dv,digest:Av,version:V.pipe(z(H(1))),byteLength:ya.pipe(z(Ka()),z(Ha(0)),z(L(Number.isSafeInteger)))},EF=I({...TF,mediaType:G([`text/html; charset=utf-8`,`application/vnd.fungi.app-assets+json`])}),DF=I({...TF,mediaType:U(`application/vnd.fungi.app-backend+json`)}),OF={declaration:B(pv)},kF=F([I({format:U(`fungi-app-v1`),ui:EF,backend:DF,...OF}),I({format:U(`fungi-app-v1`),ui:EF,...OF}),I({format:U(`fungi-app-v1`),backend:DF,...OF})]).pipe(z(L(e=>e.declaration?.api===void 0||`backend`in e,{message:`An App API requires a backend`})));Bi(kF);var AF=G([`invalid`,`undeclared_key`,`scope_not_declared`,`owner_required`,`too_large`,`quota_exceeded`,`conflict`,`unavailable`]),jF=class extends Error{code;constructor(e,t){super(e,t),this.code=e}},MF=Ia.check(Ha(0)),NF=I({value:$a,revision:MF}),PF=I({value:$a,source:G([`member`,`team`,`none`]),team:oo(NF),member:oo(NF),canWriteTeam:Ua}),FF={key:sv,scope:G(v_),basedOn:oo(MF)},IF=I({...FF,value:$a}),LF=I(FF),RF=I({revision:MF}),zF=I({appId:V,key:sv,scope:G(v_),revision:MF}),BF=F([I({kind:U(`accepted`),value:PF}),I({kind:U(`rejected`),code:AF})]),VF=F([I({kind:U(`accepted`),value:RF}),I({kind:U(`rejected`),code:AF})]),HF=I({error:V});F([BF,HF]),F([VF,HF]);var UF=e=>xh(gr().transform(t=>zi(e,{onExcessProperty:`error`})(t))),WF=bh({read:Sh(UF(BF)),write:Sh(UF(VF)),reset:Sh(UF(VF)),openEvents:Sh(wh)}),GF=e=>{if(e.kind===`rejected`)throw new jF(e.code);return e.value},KF=(e,t)=>{let n=ia(e,{onExcessProperty:`error`})(t);if(n._tag===`Failure`)throw new jF(`invalid`,{cause:n.failure});return n.success},qF=e=>KF(sv,e);function JF(e){let t=async t=>GF(await e.read(qF(t)));return{read:t,write:async t=>GF(await e.write(KF(IF,t))),reset:async t=>GF(await e.reset(KF(LF,t))),async watch(n){let r=qF(n),i=await e.openEvents(r),a=!1,o=()=>a,s,c=!1,l=()=>c&&!o(),u,d=()=>void 0,f=()=>void 0,p=new Promise((e,t)=>{d=e,f=t}),m=new e_(`https://app-storage.fungi.invalid/events`,{fetch:async(e,t)=>{let n=await i.fetch(new Request(e,t));if(!n.ok){let e=ia(BF)(await n.json()),t=new jF(e._tag===`Success`&&e.success.kind===`rejected`?e.success.code:`unavailable`);throw g(t),t}return n}}),h=()=>{a||(a=!0,m.close(),f(new jF(`unavailable`)),i.close().catch(e=>{Xo(`storage.watch.close`,e)}).finally(()=>{i[Symbol.dispose]()}))},g=e=>{f(e instanceof jF?e:new jF(`unavailable`,{cause:e})),!a&&u!==void 0&&Xo(`storage.watch`,e),h()},_=()=>{c=!0,!(s!==void 0||a)&&(s=(async()=>{for(;l();){c=!1;let e=await t(r);if(o())return;if(u===void 0){let t=cm(e);u=t,d({get:()=>t.get(),subscribe:e=>t.subscribe(e),close:h,[Symbol.dispose]:h})}else u.update(e)}})().catch(g).finally(()=>{s=void 0,c&&!a&&_()}))};return m.addEventListener(`ready`,_),m.addEventListener(`changed`,e=>{let t=ia(Bi(zF),{onExcessProperty:`error`})(e.data);t._tag===`Failure`?g(t.failure):t.success.key===r?_():g(new jF(`invalid`))}),m.onerror=e=>{(u===void 0||m.readyState===e_.CLOSED)&&g(e)},p}}}var YF=yh(`app.storage`,1,Ir(()=>WF.transform(JF))),XF=I({text:V}),ZF=Me(structuredClone(co(XF,{onExcessProperty:`error`}).schema));function QF(e){return[{id:`new-conversation`,title:`New conversation`,category:`Conversation`,description:`Start a new conversation with this Agent`,projections:{slash:{aliases:[`new`],order:20},palette:{}},handler:()=>{e().newConversation()}},{id:`permissions`,title:`App permissions`,category:`Conversation`,description:`Review what Grove may access`,projections:{slash:{aliases:[`permissions`],order:21},palette:{}},handler:()=>{e().openPermissions()}},{id:`set-draft`,title:`Set draft`,category:`Conversation`,description:`Replace the open writable Grove conversation's draft without sending it`,projections:{agent:{}},action:{inputSchema:ZF,presentation:{type:`action`}},handler:({arguments:t})=>{let{text:n}=zi(XF,{onExcessProperty:`error`})(t);return{accepted:e().setDraft(n)}}}]}function $F(e,t){let n=(0,q.useRef)(e);n.current=e;let r=(0,q.useMemo)(()=>QF(()=>n.current),[]),i=(0,q.useMemo)(()=>Et(),[]);return(0,q.useEffect)(()=>{let e=i.contribute({sourceId:`grove`,namespace:`grove`,commands:r});return()=>{e.dispose()}},[r,i]),(0,q.useEffect)(()=>t?Co(t,r):void 0,[r,t]),i}var eI=oi(Ar({providerId:P().min(1).max(256),providerName:P().min(1).max(256),id:P().min(1).max(256),name:P().min(1).max(256),reasoning:oi(Tr(Ni)).max(6).readonly()})).max(1024).readonly();async function tI(e,t,n,r=Ig){if(!e.has(Ag))throw Error(`Agent read authority is unavailable`);let i=await r(e,{agentId:t});try{let e=await i.fetch(new Request(`${i.baseUrl}/models`,{signal:n}));if(!e.ok)throw Error(`Agent model catalog is unavailable`);return eI.parse(await e.json())}finally{await i.close()}}function nI(e){let t=ln(),n=e?.capabilities.has(Ag)===!0||e?.capabilities.has(jg)===!0,r=By(n?e:null),i=e&&!n?{...r,status:`live`}:r,a=Iy.of(e,`agents`),o=qo({...zy(e,yg,a,e=>e.list()),enabled:e?.capabilities.has(yg)===!0}),s=new Set(o.data?.map(e=>e.agentId)),c=o.isSuccess?JSON.stringify([...new Set(i.items.filter(e=>!(`kind`in e)).map(e=>e.agentId))].filter(e=>!s.has(e)).sort()):`[]`,{refetch:l}=o;(0,q.useEffect)(()=>{c!==`[]`&&i.items.length>0&&l()},[c,i.items,l]);let u=Iy.of(e,`agent-computers`);return{directory:o,inbox:i,computerChoices:qo({...zy(e,bg,u,()=>{if(!e)throw Error(`No App connection`);return Ng(e.capabilities)}),enabled:e?.capabilities.has(bg)===!0}),createAgent:Jo({mutationFn:t=>{if(!e)throw Error(`No App connection`);return Mg(e.capabilities,t)},onMutate:()=>({directoryKey:a}),onSettled:(e,n,r)=>{r.computer===`new`&&t.invalidateQueries({queryKey:u})},onSuccess:(e,n,r)=>{t.setQueryData(r.directoryKey,(t=[])=>t.some(t=>t.agentId===e.agentId)?t:[...t,e])}}),renameAgent:Jo({mutationFn:t=>{if(!e)throw Error(`No App connection`);return Cg(e.capabilities,t)},onSuccess:e=>{t.setQueryData(a,(t=[])=>t.map(t=>t.agentId===e.agentId?e:t))}}),setAgentAvatar:Jo({mutationFn:t=>{if(!e)throw Error(`No App connection`);return Eg(e.capabilities,t)},onSuccess:e=>{t.setQueryData(a,(t=[])=>t.map(t=>t.agentId===e.agentId?e:t))}})}}function rI(e,t){let n=ln(),r=e?.capabilities.has(kg)===!0,i=Iy.of(e,`agent-tool-policy`,t??`none`);return{canRead:r,status:qo({...zy(e,kg,i,e=>t===null?Promise.resolve(null):e.status({agentId:t})),enabled:r&&t!==null}),approve:Jo({mutationFn:t=>{if(!e)throw Error(`No App connection`);return e.capabilities.require(kg).approve({agentId:t.agentId,level:`write`,expectedRevision:t.expectedRevision})},onSuccess:e=>{`error`in e||n.setQueryData(i,e)}})}}function iI({agentId:e,name:t,avatar:n,setAvatar:r}){let[i,o]=(0,q.useState)(null),[s,c]=(0,q.useState)(!1),l=(0,Y.jsx)(kT,{avatar:n,name:t,size:24});return r===void 0?(0,Y.jsx)(`span`,{className:`flex-none`,children:l}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(Zt,{variant:`ghost`,size:`sm`,"aria-label":`Change avatar`,className:`flex-none p-0`,onClick:()=>{o(n)},children:l}),(0,Y.jsx)(b,{open:i!==null,onOpenChange:e=>{!e&&!s&&o(null)},children:(0,Y.jsxs)(zt,{className:`flex flex-col gap-lg`,keepMounted:!1,children:[(0,Y.jsxs)(pe,{children:[(0,Y.jsxs)(w,{children:[t,`'s avatar`]}),(0,Y.jsxs)(a,{children:[`Every conversation with `,t,` shows this look.`]})]}),i===null?null:(0,Y.jsx)(wA,{value:i,disabled:s,onChange:o}),(0,Y.jsxs)(It,{children:[(0,Y.jsx)(Zt,{type:`button`,variant:`ghost`,disabled:s,onClick:()=>{o(null)},children:`Cancel`}),(0,Y.jsx)(Zt,{type:`button`,variant:`primary`,loading:s,disabled:s||i===null,onClick:()=>{i!==null&&(c(!0),r(e,i).then(e=>{c(!1),e&&o(null)}))},children:`Save`})]})]})})]})}var aI=(0,q.forwardRef)(function({className:e,orientation:t,variant:n=`grip`,value:r,min:i,max:a,onValueChange:o,onKeyDown:s,...c},l){return(0,Y.jsx)(`div`,{...c,ref:l,className:E(`caps-resize-handle`,e),"data-resize-variant":n,role:`separator`,"aria-orientation":t,"aria-valuemin":Math.round(i),"aria-valuemax":Math.round(a),"aria-valuenow":Math.round(r),tabIndex:c.tabIndex??0,onKeyDown:e=>{if(s?.(e),e.defaultPrevented)return;if(e.key===`Home`||e.key===`End`){e.preventDefault(),o(e.key===`Home`?i:a);return}let n=t===`horizontal`?e.key===`ArrowUp`?-32:e.key===`ArrowDown`?32:null:e.key===`ArrowLeft`?-32:e.key===`ArrowRight`?32:null;n!==null&&(e.preventDefault(),o(Math.min(a,Math.max(i,r+n))))},children:(0,Y.jsx)(`span`,{className:`caps-resize-grip`,"aria-hidden":`true`})})});Gt({frames:new Map,order:[],tiles:[],minima:new Map,participating:new Set,mainSize:void 0,zoomed:null,gesture:null,restore:new Map});function oI(e,t=!0,n){let r=(0,q.useRef)(e);r.current=e;let i=(0,q.useRef)(null);return(0,q.useEffect)(()=>(t||i.current?.release(!0),()=>i.current?.release(!0)),[t]),(0,q.useEffect)(()=>{let e=()=>{i.current?.release(!0)};return n?.addEventListener(`abort`,e),()=>{n?.removeEventListener(`abort`,e)}},[n]),{onPointerDown:e=>{if(!t||n?.aborted||i.current||e.pointerType===`mouse`&&e.button!==0)return;let{currentTarget:a,pointerId:o}=e;if(a.setPointerCapture(o),!r.current.begin(e)){a.releasePointerCapture(o);return}let s=r.current.end,c=()=>{l(!0)},l=e=>{a.removeEventListener(`lostpointercapture`,c),i.current=null,s(e),a.hasPointerCapture(o)&&a.releasePointerCapture(o)};i.current={id:o,element:a,x:e.clientX,y:e.clientY,release:l},a.addEventListener(`lostpointercapture`,c)},onPointerMove:e=>{let t=i.current;t?.id===e.pointerId&&(r.current.move(e.clientX-t.x,e.clientY-t.y,e),t.x=e.clientX,t.y=e.clientY)},onPointerUp:e=>{i.current?.id===e.pointerId&&i.current.release(!1)},onPointerCancel:e=>{i.current?.id===e.pointerId&&i.current.release(!0)}}}(0,q.createContext)(null);var sI=(0,q.createContext)(null);(0,q.forwardRef)(function({layer:e,style:t,children:n,...r},i){let a=(0,q.useContext)(sI),o=a?.update,s=a?.roots.get(`dialog`),[c,l]=(0,q.useState)(!1);(0,q.useEffect)(()=>{if(!s)return;let e=()=>{l(Array.from(s.querySelectorAll(`*`)).some(e=>{let t=e.getBoundingClientRect();return t.width>0&&t.height>0}))};e();let t=new MutationObserver(e);return t.observe(s,{childList:!0,subtree:!0,attributes:!0}),()=>{t.disconnect()}},[s]);let u=(0,q.useRef)(null);(0,q.useImperativeHandle)(i,()=>u.current);let d=(0,q.useCallback)(t=>{u.current=t,o?.(e,t)},[o,e]);return(0,q.createElement)(`div`,{...r,ref:d,onFocusCapture:t=>{e===`windows`&&t.target instanceof Node&&t.currentTarget.contains(t.target)&&a?.dismiss?.(),r.onFocusCapture?.(t)},"data-maosaico-layer":e,inert:e===`windows`&&c?``:void 0,style:{position:`relative`,...t,isolation:`isolate`,zIndex:`var(--stipe-layer-${e})`}},n)});var cI={min:224,max:480,initial:320},lI={agentRailOpen:!0,listRailOpen:!0,listWidth:cI.initial},uI=`layout`,dI=Ti(I({agentRailOpen:Ua,listRailOpen:Ua,listWidth:ya.pipe(z(_a()))}));function fI(e){return Math.round(Math.min(cI.max,Math.max(cI.min,e)))}async function pI(e){let t=await e.read(uI),n=dI(t.member?.value);return{layout:ui(n)?{...n.value,listWidth:fI(n.value.listWidth)}:lI,revision:t.member?.revision??null}}async function mI(e,t,n){let{revision:r}=await e.write({key:uI,scope:`member`,basedOn:n,value:t});return r}function hI(e){let[t,n]=(0,q.useState)(lI),r=(0,q.useRef)(null),i=(0,q.useRef)(!1),a=(0,q.useRef)(!1);return(0,q.useEffect)(()=>{if(e===void 0)return;let t=!1;return pI(e).then(e=>{t||(r.current=e.revision,i.current=!0,a.current||n(e.layout))},e=>{console.warn(`Grove could not read its saved rail layout`,e),i.current=!0}),()=>{t=!0}},[e]),(0,q.useEffect)(()=>{e===void 0||!a.current||!i.current||mI(e,t,r.current).then(e=>{r.current=e},e=>{console.warn(`Grove could not save its rail layout`,e)})},[e,t]),[t,(0,q.useCallback)(e=>{a.current=!0,n(e)},[])]}var gI=8e3,_I=(0,q.forwardRef)(function({className:e,detail:t,framed:n=!0,icon:r,message:i,onRetry:a,size:o=`md`,slowAfterMs:s=gI,variant:c=`line`,...l},u){let[d,f]=(0,q.useState)(!1);return(0,q.useEffect)(()=>{if(f(!1),!Number.isFinite(s))return;let e=globalThis.setTimeout(()=>{f(!0)},s);return()=>{globalThis.clearTimeout(e)}},[s,i]),(0,Y.jsxs)(`div`,{...l,className:E(`caps-loading-state`,e),"data-framed":n?void 0:`false`,"data-icon":r?``:void 0,"data-size":o,"data-slow":d||void 0,ref:u,role:`status`,children:[r?(0,Y.jsx)(`span`,{"aria-hidden":`true`,className:`caps-loading-state-icon`,children:r}):null,(0,Y.jsx)(Mt,{decorative:!0,size:o,variant:c}),(0,Y.jsxs)(`span`,{className:`caps-loading-state-copy`,children:[(0,Y.jsx)(`span`,{children:i}),t?(0,Y.jsx)(`span`,{className:`caps-loading-state-detail`,children:t}):null,d?(0,Y.jsx)(`span`,{className:`caps-loading-state-detail`,children:`Still working…`}):null]}),d&&a?(0,Y.jsx)(Zt,{className:`caps-loading-state-retry`,size:`sm`,variant:`outline`,onClick:a,children:`Retry`}):null]})}),vI=[`Make me a tiny game where a mushroom catches raindrops.`,`Write a short poem about a rainy morning.`,`What can you help me with?`];function yI({description:e,icon:t,label:n,density:r=`regular`,appearance:i=`plain`,iconSize:a=`default`,size:o,trailing:s,...c}){return(0,Y.jsxs)(Zt,{...c,className:E(`caps-action-row`,i===`card`&&`caps-action-row-card`,r===`compact`?`h-auto min-h-10 w-full justify-start gap-xs px-xs py-2xs text-left`:`h-auto min-h-14 w-full justify-start gap-sm px-sm py-xs text-left`,c.className),size:o??(r===`compact`?`default`:`lg`),variant:c.variant??`ghost`,children:[t?(0,Y.jsx)(`span`,{className:r===`compact`?`grid ${a===`lg`?`size-8`:`size-7`} shrink-0 place-items-center [&_:is(svg,.caps-monogram)]:size-5`:`grid ${a===`lg`?`size-12`:`size-10`} shrink-0 place-items-center [&_:is(svg,.caps-monogram)]:size-7`,children:t}):null,(0,Y.jsxs)(`span`,{className:`caps-action-row-copy`,children:[(0,Y.jsx)(`span`,{className:`caps-action-row-label max-w-full truncate`,children:n}),e?(0,Y.jsx)(`span`,{className:`caps-action-row-description max-w-full truncate`,children:e}):null]}),s?(0,Y.jsx)(`span`,{className:`caps-action-row-trailing`,children:s}):null]})}function bI(e,t,n,r,i,a){let o=[];r&&o.push({kind:`hint`,key:`loading`,loading:!0});let s=0,c=WT(e),l=new Map(c.map(e=>[GT(e.agentId,e.sessionId),e]));for(let e of[`Needs you`,`Working`,`Ready`,`Finished`]){let n=t.flatMap(t=>{let n=l.get(t.key),r=n?.state===`errored`?`Needs you`:t.shelf;return n===void 0||r!==e?[]:[n]});if(n.length!==0){o.push({kind:`heading`,key:e,title:e,gap:s++>0});for(let t of n)o.push({kind:`session`,key:GT(t.agentId,t.sessionId),shelf:e,session:t})}}if(e.unavailable.length>0){o.push({kind:`heading`,key:`Unavailable`,title:`Unavailable`,gap:s>0});for(let t of e.unavailable)o.push({kind:`unavailable`,key:GT(t.agentId,t.sessionId),session:t})}if(n.length>0){o.push({kind:`heading`,key:`Websites`,title:`Websites`,gap:o.length>0});for(let e of n)o.push({kind:`website`,key:`website:${e.bindingId}:${e.conversation.sessionId}`,website:e})}return o.length===0&&!i&&a&&o.push({kind:`hint`,key:`empty`,loading:!1}),o}function xI({viewport:e,view:t,agents:n,loading:r,failed:i,showEmptyState:a,pendingSelection:o,selectedAgentId:s,selectedSessionId:c,onSelect:l,onDelete:u,deleting:d,websites:f,selectedWebsite:p,onSelectWebsite:m}){let h=s!==null&&c!==null?GT(s,c):null,[g,_]=(0,q.useState)(!1),[v,y]=(0,q.useState)(!1),b=g||v,[x,S]=(0,q.useState)(0),[C,w]=(0,q.useState)({placements:null,openKey:h,reopened:x}),T=(0,q.useMemo)(()=>BT(C.placements,[...t.active,...t.settled],{openKey:C.openKey===h?h:null,held:b,reorder:C.openKey!==h||C.reopened!==x}),[C,t,h,b,x]);(0,q.useEffect)(()=>{!b&&(C.placements!==T||C.openKey!==h||C.reopened!==x)&&w({placements:T,openKey:h,reopened:x})},[b,C,T,h,x]),(0,q.useEffect)(()=>{let t=e.current;if(t===null)return;let n=t.clientWidth>0&&t.clientHeight>0,r=`ResizeObserver`in globalThis?new ResizeObserver(([e])=>{let t=e.contentRect.width>0&&e.contentRect.height>0;t&&!n&&S(e=>e+1),n=t}):void 0;r?.observe(t);let i=()=>{document.visibilityState===`visible`&&S(e=>e+1)};return document.addEventListener(`visibilitychange`,i),()=>{r?.disconnect(),document.removeEventListener(`visibilitychange`,i)}},[e]);let E=(0,q.useMemo)(()=>bI(t,T,f,r,i,a),[t,T,f,r,i,a]),ee=(0,q.useCallback)(e=>E[e]?.key??e,[E]),D=Bn({count:E.length,getScrollElement:()=>e.current,getItemKey:ee,estimateSize:e=>E[e]?.kind===`heading`?24:44,measureElement:(e,t,n)=>{let r=at(e,t,n);return r>0?r:at(e,void 0,n)||n.options.estimateSize(n.indexFromElement(e))},initialRect:{width:320,height:800},overscan:5,useFlushSync:!1});return(0,Y.jsx)(`div`,{className:`inbox-list px-1 py-1`,onPointerEnter:()=>{_(!0)},onPointerLeave:()=>{_(!1)},onFocusCapture:()=>{y(!0)},onBlurCapture:e=>{e.currentTarget.contains(e.relatedTarget)||y(!1)},children:(0,Y.jsx)(`div`,{style:{height:D.getTotalSize(),position:`relative`,width:`100%`},children:D.getVirtualItems().map(e=>{let t=E[e.index],r=t.kind===`session`||t.kind===`unavailable`?t.session:null,i=r?n.get(r.agentId):void 0;return(0,Y.jsx)(`div`,{"data-index":e.index,ref:D.measureElement,"data-inbox-shelf":t.kind===`session`?t.shelf:t.kind===`unavailable`?`Unavailable`:void 0,className:t.kind===`heading`?`inbox-shelf`:void 0,style:{position:`absolute`,top:0,left:0,width:`100%`,transform:`translateY(${String(e.start)}px)`,paddingTop:t.kind===`heading`&&t.gap?4:0},children:t.kind===`heading`?(0,Y.jsx)(me,{style:{paddingBottom:0},children:t.title}):t.kind===`hint`?t.loading?(0,Y.jsx)(_I,{className:`inbox-empty px-2 py-3 text-sm text-(--stipe-fg-muted)`,message:`Loading conversations…`}):(0,Y.jsx)(`p`,{className:`m-0 px-2 py-3 text-xs text-(--stipe-fg-muted)`,children:`No conversations yet.`}):t.kind===`website`?(0,Y.jsx)(yI,{appearance:`plain`,density:`compact`,className:`inbox-row${p?.bindingId===t.website.bindingId&&p.conversation.sessionId===t.website.conversation.sessionId?` is-selected bg-base-300`:``}`,"data-testid":`inbox-website-row`,label:t.website.conversation.label||`Website visitor`,description:(0,Y.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,Y.jsx)(Cn,{name:`internet`,size:14}),t.website.siteLabel]}),trailing:t.website.conversation.held?(0,Y.jsx)(`span`,{className:`text-xs`,children:t.website.conversation.heldByYou?`You're replying`:`With a teammate`}):t.website.conversation.needsYou?(0,Y.jsx)(fe,{size:`compact`,tone:`accent`,title:t.website.conversation.needsYou.reason}):null,onClick:()=>{m(t.website)},variant:`ghost`}):t.kind===`unavailable`?i?(0,Y.jsx)(CI,{agent:i,row:t.session}):null:i?(0,Y.jsx)(SI,{agent:i,session:t.session,attention:t.session.unseen,pending:o?.agentId===t.session.agentId&&o.sessionId===t.session.sessionId,selected:s===t.session.agentId&&c===t.session.sessionId,onDelete:u&&i.sessionOperations.includes(`agent.manage`)?()=>{u(t.session.agentId,t.session.sessionId)}:void 0,deleting:d?.agentId===t.session.agentId&&d.sessionId===t.session.sessionId,onSelect:()=>{l(t.session.agentId,t.session.sessionId)}}):null},e.key)})})})}function SI({agent:e,session:t,attention:n,pending:r,selected:i,onSelect:a,onDelete:o,deleting:s}){let c=NT(t.state),l=t.state===`errored`,u=(0,Y.jsxs)(`span`,{className:`inbox-row-activity inline-grid shrink-0 grid-cols-[1rem_7ch] items-center gap-1.5 text-[0.6875rem]`,children:[(0,Y.jsxs)(`span`,{className:`inbox-row-status flex items-center justify-center`,children:[r||c||l?(0,Y.jsx)(`span`,{className:`sr-only`,children:r?`Opening`:jT[t.state]}):null,r||c?(0,Y.jsx)(fe,{size:`compact`,title:r?`Opening`:jT[t.state],motion:t.state===`running`||r?`pulse`:`none`,tone:r?`neutral`:t.state===`needs_you`?`accent`:`info`}):l?(0,Y.jsx)(fe,{size:`compact`,title:jT.errored,tone:`error`}):n?(0,Y.jsx)(fe,{size:`compact`,title:`Finished since your last visit`,tone:`neutral`}):null]}),(0,Y.jsx)(`time`,{className:`inbox-row-age min-w-0 truncate text-right tabular-nums text-(--stipe-fg-muted)`,dateTime:new Date(t.lastActivityAt).toISOString(),children:wI(t.lastActivityAt)})]});return(0,Y.jsxs)(`div`,{className:`relative group`,children:[(0,Y.jsx)(yI,{"aria-current":i?`page`:void 0,"aria-label":`${t.title||`New conversation`} — ${KT(e)}${n?` — Finished since your last visit`:``}${t.ready?` — Ready`:c||l?` — ${jT[t.state]}`:``}`,"aria-busy":r||void 0,appearance:`plain`,className:`inbox-row pr-9${i?` is-selected bg-base-300`:``}`,"data-attention":n?`true`:`false`,"data-pending":r?`true`:`false`,"data-session-id":t.sessionId,"data-status":t.state,"data-testid":`inbox-session-row`,density:`compact`,description:KT(e),label:t.title||`New conversation`,onClick:a,trailing:u,variant:`ghost`}),o?(0,Y.jsx)(Tt,{"aria-label":`Delete conversation ${t.title||`New conversation`}`,title:`Delete conversation`,icon:(0,Y.jsx)(pT,{}),iconSize:`sm`,size:`sm`,className:`absolute right-1 top-1/2 -translate-y-1/2 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 max-[899px]:opacity-100`,disabled:c||s,onClick:o}):null]})}function CI({agent:e,row:t}){return(0,Y.jsxs)(`div`,{className:`inbox-row is-unavailable flex min-h-11 w-full items-center gap-2 rounded-field border-(length:--border) border-transparent px-2 py-1 pr-9 text-left text-base-content`,"data-session-id":t.sessionId,"data-testid":`inbox-unavailable-row`,role:`group`,children:[(0,Y.jsxs)(`span`,{className:`inbox-row-copy flex min-w-0 flex-1 flex-col`,children:[(0,Y.jsx)(`strong`,{className:`truncate text-sm font-medium`,children:`Conversation unavailable`}),(0,Y.jsxs)(`small`,{className:`truncate text-xs text-(--stipe-fg-muted)`,children:[KT(e),` `,(0,Y.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),` This saved conversation could not be read.`]})]}),(0,Y.jsx)(`span`,{className:`inbox-row-activity inline-grid shrink-0 grid-cols-[1rem_7ch] items-center gap-1.5 text-[0.6875rem]`,children:(0,Y.jsx)(`span`,{className:`inbox-row-status flex items-center justify-center`,children:(0,Y.jsx)(fe,{size:`compact`,tone:`error`,title:`This saved conversation could not be read`})})})]})}function wI(e){let t=Math.max(0,Date.now()-e);return t<6e4?`now`:t<36e5?`${String(Math.floor(t/6e4))}m`:t<864e5?`${String(Math.floor(t/36e5))}h`:new Date(e).toLocaleDateString(void 0,{month:`short`,day:`numeric`})}var TI=P().min(1).max(256),EI=zr().int().nonnegative();Mr(`state`,[Ar({state:ri(`agent`),version:EI}),Ar({state:ri(`requested`),version:EI,reason:P().max(4e3),at:zr().int().nonnegative()}),Ar({state:ri(`person`),version:EI,memberId:TI,memberName:P().min(1).max(128),since:zr().int().nonnegative()})]);var DI=Ar({bindingId:TI,agentId:TI,origins:oi(P().min(1).max(2048)).min(1).max(16),lifecycle:Tr([`active`,`suspended`])}),OI=Ar({sessionId:TI,label:P().max(4096),lastEventAt:zr().int().nonnegative(),needsYou:Ar({at:zr().int().nonnegative(),reason:P().max(4e3)}).nullable(),held:ti(),heldByYou:ti(),heldByName:P().min(1).max(128).nullable(),holdVersion:zr().int().nonnegative()}),kI=Ar({bindingId:TI}).extend({sessionId:TI});kI.extend({requestId:P().min(1).max(128),text:P().trim().min(1).max(4e3)});var AI=Ar({expectedVersion:EI,confirm:ti()});kI.extend(AI.shape),kI.extend({expectedVersion:EI});var jI=Ar({websites:oi(DI).max(1e3)}),MI=Ar({conversations:oi(OI).max(100)});Ar({conversation:OI});var NI=Ar({status:ri(`sent`)}),PI=yh(`channels.read`,1,Ir(()=>bh({list:Sh(xh(jI)),conversations:Sh(xh(MI))}))),FI=yh(`channels.personal.manage`,1,Ir(()=>bh({hold:Sh(xh(OI)),release:Sh(xh(OI)),dismiss:Sh(xh(OI)),reply:Sh(xh(NI))})));function II(e,t){let n=!1,r=async()=>{try{return await t.read()}catch(e){if(!(e instanceof Oi)||e.boundary!==`runtime`||e.cause!==`unavailable`)throw e;if(await new Promise(e=>setTimeout(e,150)),n)throw Error(`Conversation opening cancelled`,{cause:e});return t.read()}},i,a=new Promise((e,t)=>{i=()=>{t(Error(`Conversation opening cancelled`))}});return{ready:Promise.race([r(),a]).then(r=>{if(n)throw Error(`Conversation opening cancelled`);De(e,t,r)}),close:()=>{n=!0,i()}}}function LI(e){return class{#e;constructor(t){this.#e=new e_(t,{fetch:(t,n)=>e(t,n)})}get readyState(){return this.#e.readyState}addEventListener(e,t,n){this.#e.addEventListener(e,t,n)}close(){this.#e.close()}}}function RI(e){let{connection:t,queryClient:n,services:r}=e,i=null,a=null,o=null,s=!1,c=(e,t)=>e?.agentId===t.agentId&&e.sessionId===t.sessionId,l=e=>!s&&i===e,u=(u,d,f=!1)=>{if(s)return;let p={agentId:u,sessionId:d};if(c(i,p)||(i?.close(),i=null,e.onPending(null),e.onError(null),c(a,p)))return;let m=null,h=!1,g={...p,close:()=>{h||(h=!0,m?.())}};i=g,e.onPending(p),(async()=>{try{let s=await r.openAgent(t.capabilities,{agentId:u});if(!l(g)){await s.close();return}let c=r.createClient({baseUrl:s.baseUrl,eventSource:LI(s.fetch),fetch:s.fetch}),f=c.session(d),p=II(n,f);if(m=()=>{p.close(),Promise.allSettled([c.close(),s.close()])},await p.ready,e.reportsSelection!==!1&&await t.ui.reportAgentSessionSelection({agentId:u,sessionId:d}),!l(g))return;let h={agentId:u,sessionId:d,session:f},_=o;i=null,a=h,o=g.close,e.onConversation(h),e.onPending(null),_?.()}catch(t){console.error(`Chat Session opening failed`,t),g.close(),l(g)&&(i=null,e.onPending(null),e.onError(f?`That Session could not be opened. ${a?`The current conversation remains open.`:`Choose another Session from the list.`}`:`Could not open this Session${t instanceof Error?`: ${t.message}`:``}. ${a?`The previous conversation remains open.`:`Try opening it again.`}`))}})()},d=()=>{if(s)return;let n=i!==null||a!==null;i?.close(),i=null,o?.(),o=null,a=null,e.onPending(null),e.onConversation(null),e.onError(null),!(!n||e.reportsSelection===!1)&&t.ui.reportAgentSessionSelection(null).catch(e=>{console.error(`Chat Session selection could not be reported`,e)})};return{select:u,clear:d,close:()=>{d(),s=!0}}}function zI(e,t){async function n(e){if(e.type!==`prompt`||(e.images?.length??0)>0)throw new J(`Website conversations support text replies only`,{code:`COMMAND_NOT_DECLARED`,retryable:!1});if(!t.canReply())throw new J(`Use Take over to reply to this visitor`,{code:`CAPABILITY_DENIED`,retryable:!1});return await t.reply({bindingId:t.bindingId,sessionId:t.sessionId,requestId:e.requestId,text:e.text}),{status:`recorded`}}return{latestPending:()=>Promise.resolve(null),withdraw:t=>e.withdraw(t),address:e.address,read:t=>e.read(t),watch:t=>e.watch(t),extension:()=>({call:()=>Promise.reject(new J(`Website Session controls are unavailable`,{code:`COMMAND_NOT_DECLARED`,retryable:!1}))}),command:n}}function BI(e,t){(0,q.useSyncExternalStore)(t=>e?.capabilities.subscribe(t)??(()=>void 0),()=>e?.capabilities.version??0);let n=ln(),[r,i]=(0,q.useState)(null),[a,o]=(0,q.useState)(null),[s,c]=(0,q.useState)(null),l=e?.capabilities.has(PI)===!0,u=e?.capabilities.has(FI)===!0,d=qo({...zy(e,PI,Iy.of(e,`websites`),e=>e.list()),enabled:l}),f=l?d.data?.websites??[]:[],p=Go({queries:f.map(t=>({...zy(e,PI,Iy.of(e,`website-conversations`,t.bindingId),e=>e.conversations({bindingId:t.bindingId})),enabled:l}))}),m=f.flatMap((e,t)=>(p[t]?.data?.conversations??[]).map(t=>({bindingId:e.bindingId,agentId:e.agentId,siteLabel:e.origins.map(e=>new URL(e).host).join(`, `),conversation:t}))).sort((e,t)=>t.conversation.lastEventAt-e.conversation.lastEventAt),h=m.find(e=>e.bindingId===r?.bindingId&&e.conversation.sessionId===r.sessionId),g=(0,q.useMemo)(()=>e===null?null:RI({connection:e,queryClient:n,services:t,onPending:()=>void 0,onConversation:o,onError:c}),[e,n,t]);(0,q.useEffect)(()=>()=>{g?.close()},[g]),(0,q.useEffect)(()=>{l||g?.clear()},[l,g]);let _=Jo({mutationFn:t=>{if(e===null)throw Error(`No App connection`);let n=e.capabilities.require(FI);return t.kind===`hold`?n.hold({bindingId:t.bindingId,sessionId:t.sessionId,expectedVersion:t.expectedVersion,confirm:t.confirm}):n.release({bindingId:t.bindingId,sessionId:t.sessionId,expectedVersion:t.expectedVersion,confirm:t.confirm})},onSuccess:(t,r)=>{n.setQueryData(Iy.of(e,`website-conversations`,r.bindingId),e=>e===void 0?void 0:{conversations:e.conversations.map(e=>e.sessionId===t.sessionId?t:e)})}}),v=h?.bindingId,y=h?.conversation.sessionId,b=h?.conversation.heldByYou===!0,x=(0,q.useMemo)(()=>a===null||v===void 0||y===void 0||e===null?null:zI(a.session,{bindingId:v,sessionId:y,canReply:()=>b&&e.capabilities.has(FI),reply:t=>e.capabilities.require(FI).reply(t)}),[e,a,v,y,b]),S=(0,q.useCallback)(()=>{g?.clear(),i(null),o(null),_.reset()},[g,_.reset]);return{canRead:l,canManage:u,rows:m,selected:h,session:x,action:_,openingError:s,loading:l&&(d.isPending||p.some(e=>e.isPending)),failed:l&&(d.isError||p.some(e=>e.isError)),clear:S,select:e=>{l&&(h?.bindingId!==e.bindingId||h.conversation.sessionId!==e.conversation.sessionId||a===null)&&(i({bindingId:e.bindingId,sessionId:e.conversation.sessionId}),o(null),_.reset(),g?.select(e.agentId,e.conversation.sessionId))}}}var VI=(0,q.lazy)(async()=>({default:(await _o(()=>import(`./website-conversation-C1IWoELN.js`),__vite__mapDeps([12,1,13,2,3,4,8,14,15]))).WebsiteConversation})),HI=(0,q.lazy)(async()=>({default:(await _o(()=>import(`./parakeet-conversation-DTKcx8BS.js`),__vite__mapDeps([16,1,13,2,3,4,8,14,15,17]))).ParakeetConversation})),UI={openAgent:Ig,createClient:Ca,autoOpen:!0},WI=[`agent.list`,`agent.manage`,`agent.read`,`agent.send`],GI=[`agent.read`,`agent.send`,`agent.manage`],KI=Ba({family:`grove-session-create-request`,version:1,kinds:{request:{prefix:`request`}}});async function qI(e,t,n,r){let i=await n.openAgent(e.capabilities,{agentId:t}),a=n.createClient({baseUrl:i.baseUrl,eventSource:LI(i.fetch),fetch:i.fetch});try{return await r(a)}finally{Promise.allSettled([a.close(),i.close()])}}function JI({open:e,renderConversation:t,connection:n,commands:r,composeDraft:i,onPrefilled:a,onForked:o,onOpen:s,models:c,autoFocus:l,label:u=`Conversation`}){let d=e.session,[f,p]=(0,q.useState)({kind:`loading`});return(0,q.useEffect)(()=>{if(!n||t)return;let r=new AbortController;return p({kind:`loading`}),tI(n.capabilities,e.agentId,r.signal).then(e=>{r.signal.aborted||p({kind:`ready`,models:e})},()=>{r.signal.aborted||p({kind:`unavailable`})}),()=>{r.abort()}},[n,e.agentId,t]),(0,q.useEffect)(()=>{let i=r.contribute({sourceId:`grove-session`,namespace:`session`,commands:[...FC(d,{sourceId:`grove-session`,namespace:`session`,sessionResumeAvailable:!1,forkAvailable:!0,onForked:o}),...t?[]:jx(d,{sourceId:`grove-session`,namespace:`session`,models:f.kind===`ready`?f.models:[],refreshModels:t=>n?tI(n.capabilities,e.agentId,t):Promise.reject(Error(`Agent connection is unavailable`)),availability:()=>f.kind===`ready`&&f.models.length>0?{status:`available`}:{status:`unavailable`,reason:f.kind===`loading`?`Loading this Agent's models`:f.kind===`ready`?`This Agent has no available models`:`This Agent's model catalog is unavailable`}})]});return()=>{i.dispose()}},[r,d,o,t,f,n,e.agentId]),(0,Y.jsx)(`section`,{className:`inbox-conversation min-h-0 min-w-0 flex-1`,"data-inbox-conversation":!0,"aria-label":u,children:t?t(e,i,s):(0,Y.jsx)(q.Suspense,{fallback:(0,Y.jsx)(_I,{className:`m-auto`,framed:!1,message:`Opening conversation…`}),children:(0,Y.jsx)(HI,{session:d,draftIdentity:{agentId:e.agentId,sessionId:e.sessionId},connection:n,commands:r,prefill:i,onPrefilled:a,onOpen:s,models:c,autoFocus:l})})})}function YI(e){return mh(e.connection),(0,Y.jsx)(XI,{...e},JSON.stringify(Iy.of(e.connection)))}function XI(e){let t=(0,q.useMemo)(bF,[e.connection]);return(0,Y.jsx)(gF,{value:(0,Y.jsx)(ZI,{...e,router:t}),children:(0,Y.jsx)(fF,{router:t})})}function ZI({router:e,connection:t,services:n=UI}){let{agentFilterId:r,setFilter:i,selection:a,open:o}=xF(e,t?.window.navigation),c=ln(),l=BI(t,n),{directory:u,inbox:d,computerChoices:p,createAgent:m,renameAgent:h,setAgentAvatar:g}=nI(t),_=u.data??[],v=u.isPending&&(t?.capabilities.has(yg)??!0),y=u.error?.message??null,b=m.isPending,x=Jo({mutationFn:e=>{if(!t)throw Error(`No App connection`);return qI(t,e.agentId,n,t=>t.createSession(e.requestId))}}),S=Jo({mutationFn:e=>{if(!t)throw Error(`No App connection`);return qI(t,e.agentId,n,t=>t.deleteSession(e.sessionId))},onSuccess:(t,n)=>{a?.agentId===n.agentId&&a.sessionId===n.sessionId&&(je?.clear(),e.navigate({to:`/`,search:!0,replace:!0})),d.refresh()}}),C=x.isPending?x.variables.agentId:null,[w,T]=(0,q.useState)(null),[E,ee]=(0,q.useState)(null),[D,O]=(0,q.useState)(!1),k=E?.agentId??null,A=E?.sessionId??null,[j,te]=(0,q.useState)(null),ne=(0,q.useRef)(null),[re,ae]=hI((0,q.useMemo)(()=>t?.capabilities.has(YF)?t.capabilities.require(YF):void 0,[t])),{agentRailOpen:oe,listRailOpen:se,listWidth:ce}=re,le=e=>{ae(t=>({...t,agentRailOpen:e(t.agentRailOpen)}))},ue=e=>{ae(t=>({...t,listRailOpen:e(t.listRailOpen)}))},M=e=>{ae(t=>({...t,listWidth:fI(e(t.listWidth))}))},de=oI({begin:()=>!0,move:e=>{M(t=>t+e)},end:()=>void 0}),[fe,pe]=(0,q.useState)(!1),he=$T(),ge=(0,q.useRef)(null),[_e,ve]=(0,q.useState)(null),ye=m.error?.message??null,N=m.data,xe=(0,q.useRef)(null),[Se,Ce]=(0,q.useState)(null),[we,Te]=(0,q.useState)(null),Ee=mh(t),De=Ee?.openRequest??null,Oe=Ee?.setup?.models===`missing`,ke=(0,q.useCallback)(()=>{t?.ui.openSetup(`model`).catch(e=>{console.error(`Grove could not open model setup`,e)})},[t]),Ae=(0,q.useRef)(null),je=(0,q.useMemo)(()=>t===null?null:RI({connection:t,queryClient:c,services:n,onPending:T,onConversation:ee,onError:Ce}),[t,c,n]);(0,q.useEffect)(()=>{if(je!==null)return()=>{xe.current=null,je.close()}},[je]);let[Me,Ne]=(0,q.useState)(null),Pe=(0,q.useMemo)(()=>Et(),[]),Fe=(0,q.useMemo)(()=>t===null?null:RI({connection:t,queryClient:c,services:n,onPending:()=>void 0,onConversation:Ne,onError:Ce,reportsSelection:!1}),[t,c,n]);(0,q.useEffect)(()=>Fe===null?void 0:()=>{Fe.close()},[Fe]);let Ie=(0,q.useCallback)(e=>{let t=t=>e.params.find(e=>e.key===t)?.value,n=t(`agent`),r=t(`session`);n!==void 0&&r!==void 0&&Fe?.select(n,r)},[Fe]),Le=(0,q.useRef)(null),Re=(0,q.useCallback)((e,t,n=!1)=>{je!==null&&(x.isError&&x.reset(),l.clear(),O(!1),Le.current={agentId:e,sessionId:t},je.select(e,t,n),o(e,t))},[je,o,l.clear,x.isError,x.reset]),ze=a?.agentId,Be=a?.sessionId;(0,q.useEffect)(()=>{let e=Le.current;Le.current=null,ze===void 0||Be===void 0?je?.clear():(e?.agentId!==ze||e.sessionId!==Be)&&je?.select(ze,Be)},[je,ze,Be]);let Ve=(0,q.useCallback)(e=>{E&&(Re(E.agentId,e),d.refresh())},[E,Re,d.refresh]);(0,q.useEffect)(()=>{if(!t||De===null){De===null&&(Ae.current=null);return}if(De.kind!==`navigate`||Ae.current===De.requestId)return;let e=De.params.find(e=>e.key===`agent`)?.value,n=De.params.find(e=>e.key===`session`)?.value;!e||!n||(Ae.current=De.requestId,i(e),Re(e,n,!0))},[t,De,Re,i]);let He=(0,q.useCallback)(async e=>{if(!t||b||!t.capabilities.has(bg))return!1;try{let t=await m.mutateAsync(e);return i(t.agentId),ve(t.agentId),te(null),!0}catch{return!1}},[t,b,m.mutateAsync,i]),Ue=(0,q.useCallback)(async(e,n)=>{if(!t||C!==null)return`Conversation creation is unavailable.`;Ce(null);let r=xe.current?.agentId===e?xe.current:{agentId:e,requestId:KI.request.generate()};xe.current=r;try{let t=await x.mutateAsync(r);Re(e,t),n!==void 0&&Te({requestId:Tm(),text:n,send:!0}),d.refresh(),te(null),pe(!1),xe.current===r&&(xe.current=null);return}catch(e){return console.error(`Grove conversation creation failed`,e),e instanceof Error?e.message:`Couldn't start the conversation.`}},[t,Re,C,x.mutateAsync,d.refresh]);(0,q.useEffect)(()=>{if(!(!t||De?.kind!==`compose`)&&Ae.current!==De.requestId&&!(!E&&v)&&(Ae.current=De.requestId,Te({requestId:De.requestId,text:De.text}),!E)){let e=t.capabilities.has(jg)?_.find(e=>e.sessionOperations.includes(`agent.read`)&&e.sessionOperations.includes(`agent.send`)&&e.sessionOperations.includes(`agent.manage`)):void 0;e?Ue(e.agentId):te(`agent`)}},[_,t,v,E,De,Ue]);let We=$F({setDraft:e=>w!==null||!E||!t?.capabilities.has(jg)||!_.some(e=>e.agentId===E.agentId&&e.sessionOperations.includes(`agent.send`))?!1:(Te({requestId:Tm(),text:e}),!0),newConversation:()=>{E&&Ue(E.agentId)},openPermissions:()=>{t?.ui.requestAppPermissions({}).catch(e=>{console.error(`Chat inbox or permission request failed`,e)})}},t?.commands),Ge=new Set(l.rows.map(e=>`${e.agentId}:${e.conversation.sessionId}`)),Ke=d.items.filter(e=>!(`kind`in e)).filter(e=>!Ge.has(`${e.agentId}:${e.sessionId}`)),qe=Go({queries:(E?[E.session]:[]).map(e=>({...f(e),enabled:!1}))}).at(0)?.data?.snapshot,Je=(0,q.useMemo)(()=>E&&qe?{agentId:E.agentId,sessionId:E.sessionId,state:dt(qe)}:void 0,[E,qe]),Ye=(0,q.useMemo)(()=>HT(_,D&&l.canRead?[]:Ke,r,Je),[r,_,Ke,D,l.canRead,Je]),Xe=(0,q.useMemo)(()=>{let e=new Map;for(let t of Ke)`state`in t&&(t.state===`needs_you`?e.set(t.agentId,`speaking`):t.state===`running`&&!e.has(t.agentId)&&e.set(t.agentId,`thinking`));return e},[Ke]),Ze=(0,q.useMemo)(()=>new Map(_.map(e=>[e.agentId,e])),[_]),Qe=(0,q.useRef)(null),$e=Ke.find(e=>e.agentId===k&&e.sessionId===A),et=$e!==void 0&&$e.state!==`unavailable`,tt=$e!==void 0&&$e.state!==`unavailable`?$e.settledAt:void 0;(0,q.useEffect)(()=>{!et||k===null||A===null||d.visit(k,A).catch(e=>{console.error(`Chat inbox or permission request failed`,e)})},[et,tt,k,A,d.visit]);let nt=d.status===`loading`,rt=d.status===`error`,it=t?.capabilities.has(bg)??!1,at=t?.capabilities.has(jg)??!1,ot=_.filter(e=>e.sessionOperations.includes(`agent.read`)&&e.sessionOperations.includes(`agent.send`)&&e.sessionOperations.includes(`agent.manage`)),st=ot.find(e=>e.agentId===(_e??r))??ot.at(0),ct=at&&st!==void 0,lt=()=>{t?.ui.requestAppPermissions({agents:WI}).catch(e=>{console.error(`Chat inbox or permission request failed`,e)})},ut=N&&(!N.sessionOperations.includes(`agent.read`)||!N.sessionOperations.includes(`agent.send`)||!N.sessionOperations.includes(`agent.manage`))?`Agent created. Allow Grove to read, send messages and manage its sessions to start a conversation.`:we&&!E&&!ct&&m.isIdle?`Choose an Agent to compose your game idea.`:null,ft=(0,q.useMemo)(()=>HT(_,Ke,null,Je),[_,Ke,Je]),pt=(e,t)=>{pe(!1),Re(e,t)},mt=()=>{ge.current=document.activeElement instanceof HTMLElement?document.activeElement:null,pe(!0)};hh(t,[...he?[{kind:`button`,id:`agents`,text:`Agents`,expanded:oe,title:oe?`Hide Agents`:`Show Agents`},{kind:`button`,id:`conversations`,text:`Conversations`,expanded:se,title:se?`Hide conversations`:`Show conversations`}]:[{kind:`button`,id:`agents`,text:`Agents and conversations`,opens:`dialog`,expanded:fe}],...Me===null?[]:[{kind:`button`,id:`close-beside`,text:`Close beside`,title:`Close beside conversation`}]],e=>{if(j!==null)return!1;if(e.itemId===`close-beside`&&Me!==null)Fe?.clear();else if(he&&e.itemId===`agents`)le(e=>!e);else if(he&&e.itemId===`conversations`)ue(e=>!e);else if(!he&&e.itemId===`agents`)fe?pe(!1):mt();else return!1;return!0});let ht=e=>{i(e),ve(e);let t=[...ft.active,...ft.settled].filter(t=>t.agentId===e).sort((e,t)=>t.lastActivityAt-e.lastActivityAt).at(0);t&&pt(e,t.sessionId)},gt={"--grove-list-width":`${String(ce)}px`},_t=E?Ze.get(E.agentId):void 0,vt=r===null?void 0:Ze.get(r),yt=t?.capabilities.has(Sg)??!1,bt=_.length===1?_[0]:void 0,xt=vt??bt,St=t?.capabilities.has(Tg)??!1,Ct=rI(t,vt?.agentId??null),wt=WT(Ye).length,Dt=(0,q.useRef)(!1);(0,q.useEffect)(()=>{n.autoOpen!==!0||Dt.current||!t||E||De!==null||v||nt||rt||y||Oe||wt>0||st===void 0||!at||C!==null||(Dt.current=!0,Ue(st.agentId))},[at,t,v,y,rt,wt,nt,Oe,E,De,n.autoOpen,st,Ue,C]);let Ot=(0,q.useCallback)(async(e,n)=>{if(!t)return!1;try{return await h.mutateAsync({agentId:e,name:n}),!0}catch{return!1}},[t,h.mutateAsync]),kt=(0,q.useCallback)(async(e,n)=>{if(!t)return!1;try{return await g.mutateAsync({agentId:e,avatar:n}),!0}catch{return!1}},[t,g.mutateAsync]),At=(0,q.useCallback)(()=>{let e=Ct.status.data;!vt||e==null||Ct.approve.mutate({agentId:vt.agentId,expectedRevision:e.revision})},[vt,Ct.status.data,Ct.approve]),jt=(0,q.useCallback)(e=>{!t||b||C!==null||e===`agent`&&!it||(j===null&&(ne.current=fe?ge.current:document.activeElement instanceof HTMLElement?document.activeElement:null),pe(!1),e===`session`&&ve(_t?.agentId??r??ot.at(0)?.agentId??null),te(e))},[t,b,C,it,j,fe,_t?.agentId,r,ot]);(0,q.useEffect)(()=>{let e=e=>{e.defaultPrevented||e.repeat||!e.ctrlKey||e.altKey||e.metaKey||e.key.toLowerCase()!==`n`||!t||e.shiftKey&&!it||(e.preventDefault(),jt(e.shiftKey?`agent`:`session`))};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e)}},[t,it,jt]);let Mt=x.isError?x.variables:null,Nt=Mt&&j!==`session`?(0,Y.jsx)(be,{className:E||l.selected?`inbox-error m-2`:`inbox-empty m-auto max-w-[28rem]`,tone:`error`,title:`Couldn't start the conversation.`,description:x.error?.message,action:(0,Y.jsx)(Zt,{variant:`outline`,onClick:()=>void Ue(Mt.agentId),children:`Retry`})}):null;return(0,Y.jsxs)(`main`,{className:`inbox-app grove-shell relative flex h-dvh min-h-0 bg-base-200 font-sans text-base-content`,"data-inbox-app":!0,"data-conversation":!!E||l.selected!==void 0,children:[t?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(NA,{open:j===`agent`,pending:b,error:ye,computers:p.isError?{status:`unavailable`,message:`Your Computers could not be loaded. New Computer and No Computer still work.`}:p.isPending?{status:`loading`}:p.data===null?{status:`not-offered`}:{status:`offered`,computers:p.data},create:He,onClose:()=>{te(null)},returnFocus:ne}),j===`session`?(0,Y.jsx)(PA,{open:!0,agents:at?ot:[],defaultAgentId:st?.agentId??null,start:Ue,pending:C!==null,onClose:()=>{te(null)},onNewAgent:it?()=>{te(`agent`)}:void 0,returnFocus:ne}):null]}):null,(0,Y.jsxs)(eE,{open:fe,onOpenChange:pe,returnFocus:ge,children:[(0,Y.jsx)(JT,{open:oe,agents:_,agentActivity:Xe,agentFilterId:r,websitesSelected:D,websitesVisible:l.canRead,canCreate:t!==null&&it,createOpen:j===`agent`,onAll:()=>{i(null),O(!1)},onWebsites:()=>{i(null),O(!0)},onAgent:e=>{O(!1),ht(e)},onCreate:()=>{jt(`agent`)}}),(0,Y.jsxs)(`aside`,{id:`grove-list-rail`,className:`inbox-sidebar group relative min-h-0 min-w-0 flex-1 flex-col border-r border-base-300 min-[900px]:w-[var(--grove-list-width)] min-[900px]:flex-none ${se?`flex`:`flex min-[900px]:hidden`}`,style:gt,"aria-label":`Conversations`,children:[he?(0,Y.jsx)(aI,{"aria-label":`Conversation list width`,"aria-controls":`grove-list-rail`,className:`absolute right-0 top-1/2 z-10 translate-x-1/2 -translate-y-1/2`,orientation:`vertical`,value:ce,min:cI.min,max:cI.max,onValueChange:e=>{M(()=>e)},onDoubleClick:()=>{M(()=>cI.initial)},...de}):null,(0,Y.jsxs)(`header`,{className:`inbox-header flex h-10 flex-none items-center gap-1 border-b border-base-300 pl-3 pr-1`,children:[vt?(0,Y.jsx)(iI,{agentId:vt.agentId,name:KT(vt),avatar:vt.avatar,...St?{setAvatar:kt}:{}},vt.agentId):null,(0,Y.jsx)(me,{className:`min-w-0 flex-1 truncate`,children:D&&l.canRead?`Websites`:vt?KT(vt):`All Agents`}),xt&&yt?(0,Y.jsx)(CF,{agentId:xt.agentId,name:xt.name,rename:Ot},xt.agentId):null,t&&(ct||it)?(0,Y.jsx)(Tt,{"aria-label":`New conversation`,"aria-haspopup":`dialog`,icon:(0,Y.jsx)(fT,{}),iconSize:`sm`,size:`sm`,onClick:()=>{jt(`session`)}}):null]}),vt&&Ct.canRead?(0,Y.jsx)(wF,{status:Ct.status.data,approving:Ct.approve.isPending,onApprove:At}):null,ut?(0,Y.jsx)(be,{tone:`info`,title:ut,action:(0,Y.jsx)(Zt,{variant:`ghost`,onClick:()=>{t?.ui.requestAppPermissions({agents:GI}).catch(e=>{console.error(`Chat inbox or permission request failed`,e)})},children:`Allow conversation access`})}):null,t&&_.length>0&&!ct&&!it?(0,Y.jsxs)(`section`,{className:`inbox-create inbox-access flex flex-col items-start gap-3 border-b border-base-300 py-2`,"aria-labelledby":`inbox-agent-access-title`,children:[(0,Y.jsx)(s,{level:2,id:`inbox-agent-access-title`,className:`inbox-access-title m-0`,children:`Let Grove manage your Agents`}),(0,Y.jsx)(`p`,{children:`Grove creates Agents and carries their conversations. Your Team decides what it may do.`}),(0,Y.jsx)(Zt,{size:`sm`,onClick:lt,children:`Allow Agent access`})]}):null,S.error?(0,Y.jsx)(be,{tone:`error`,title:S.error.message}):null,y?(0,Y.jsx)(be,{className:`inbox-error`,tone:`error`,title:y,action:(0,Y.jsx)(Zt,{variant:`ghost`,size:`sm`,onClick:()=>{u.refetch()},children:`Try again`})}):null,rt?(0,Y.jsx)(be,{className:`inbox-error`,tone:`error`,title:`Conversations are unavailable.`,action:(0,Y.jsx)(Zt,{variant:`ghost`,size:`sm`,onClick:()=>{d.refresh()},children:`Retry conversations`})}):null,(0,Y.jsx)(dx,{ref:Qe,className:`inbox-surface min-h-0 flex-1`,"aria-label":`Conversations`,children:t?v?(0,Y.jsx)(`p`,{className:`inbox-empty m-0 px-2 py-3 text-sm text-(--stipe-fg-muted)`,role:`status`,children:`Loading Agents…`}):(0,Y.jsx)(xI,{viewport:Qe,view:Ye,agents:Ze,loading:nt||l.loading,failed:!!y||rt||l.failed,showEmptyState:!Oe,pendingSelection:w,selectedAgentId:k,selectedSessionId:A,onSelect:pt,onDelete:at?(e,t)=>{S.mutate({agentId:e,sessionId:t})}:void 0,deleting:S.isPending?S.variables:null,websites:l.rows.filter(e=>r===null||e.agentId===r),selectedWebsite:l.selected,onSelectWebsite:e=>{je?.clear(),pe(!1),l.select(e)}}):(0,Y.jsx)(`p`,{className:`inbox-empty m-0 px-2 py-3 text-sm text-(--stipe-fg-muted)`,children:`Connect to the host to browse Agents.`})},r)]})]}),(0,Y.jsxs)(`section`,{className:`inbox-conversation-shell flex min-h-0 min-w-0 flex-1 flex-col`,"aria-label":`Conversation`,children:[(0,Y.jsx)(YT,{app:t}),Se?(0,Y.jsx)(be,{className:`inbox-error m-2`,tone:`error`,title:Se}):null,E||l.selected?Nt:null,l.selected?(0,Y.jsx)(q.Suspense,{fallback:null,children:(0,Y.jsx)(VI,{inbox:l})}):E?(0,Y.jsx)(JI,{open:E,connection:t,commands:We,renderConversation:n.renderConversation,composeDraft:we,onPrefilled:()=>{Te(null)},onForked:Ve,onOpen:Ie,models:Ee?.setup?.models,autoFocus:he}):!t||v?null:_.length===0&&!y?(0,Y.jsx)(ie,{className:`inbox-empty m-auto max-w-[28rem]`,variant:`speech`,thinking:b,renderVisual:({speaking:e,thinking:t})=>(0,Y.jsx)(AT,{className:`h-full w-full`,state:{activity:t?`thinking`:e?`speaking`:`idle`,expression:`normal`}}),title:it?`No one's here yet.`:`Welcome to Grove`,description:it&&Oe?`Agents chat, write and make little games with you. Connect a model to start chatting.`:it?`Agents chat, write and make little games with you. Name someone?`:`Let Grove find your Agents, create new ones, and open conversations. Your Team controls this access.`,actions:it&&Oe?(0,Y.jsx)(Zt,{onClick:ke,children:`Add a model key`}):it?(0,Y.jsx)(Zt,{onClick:()=>{jt(`agent`)},children:`Name your first Agent`}):(0,Y.jsx)(Zt,{onClick:lt,children:`Allow Agent access`})}):Oe?(0,Y.jsx)(kn,{className:`inbox-empty m-auto max-w-[28rem]`,cause:`Chat, write and make little games with Agents. Connect a model to begin.`,visual:(0,Y.jsx)(AT,{state:{activity:`idle`,expression:`normal`}}),fix:{label:`Add a model key`,onSelect:ke},need:`Connect a model to start chatting`,variant:`panel`}):Nt??(0,Y.jsx)(ie,{className:`inbox-empty m-auto max-w-[28rem]`,variant:`panel`,title:wt>0?`Pick up a conversation`:st?`Say hello to ${KT(st)}`:`No conversations yet`,description:wt>0?`Choose one from the list, or ask for something new. A tiny game is a good start.`:`Ask for anything. Pick one to start.`,suggestions:wt===0&&ct?vI.map(e=>({label:e,disabled:C!==null,onSelect:()=>{Ue(st.agentId,e)}})):void 0,actions:(0,Y.jsxs)(Y.Fragment,{children:[he||wt===0?null:(0,Y.jsx)(Zt,{variant:`outline`,"aria-haspopup":`dialog`,"aria-controls":`grove-nav`,"aria-expanded":fe,onClick:mt,children:`Agents and conversations`}),ct?(0,Y.jsx)(Zt,{variant:`outline`,loading:C===st.agentId,disabled:C!==null,onClick:()=>void Ue(st.agentId),children:wt>0?`Ask ${KT(st)} something`:`Start a conversation`}):null]})})]}),Me===null?null:(0,Y.jsx)(`section`,{className:`inbox-conversation-shell flex min-h-0 min-w-0 flex-1 flex-col border-l border-base-300`,"aria-label":`Beside conversation`,"data-inbox-beside":!0,children:(0,Y.jsx)(JI,{open:Me,connection:t,commands:Pe,renderConversation:n.renderConversation,composeDraft:null,onPrefilled:()=>void 0,onForked:e=>{Fe?.select(Me.agentId,e)},onOpen:Ie,models:Ee?.setup?.models,label:`Beside conversation`})})]})}var QI=document.getElementById(`inbox-root`);if(!QI)throw Error(`Inbox root is missing`);dh(QI,{name:`Grove`,queryClient:Ry()},({app:e})=>(0,q.createElement)(YI,{connection:e}));export{Ch as _,YS as a,JS as c,BS as d,Rx as f,Sh as g,bh as h,nC as i,ZS as l,xh as m,dA as n,XS as o,Iy as p,cA as r,KS as s,vI as t,qS as u,yh as v,qo as y};
|
|
116
|
+
WHERE job_id = ? AND state = 'running' AND claim_token = ?`,a?`cancelled`:`interrupted`,o,n.job.jobId,n.claimToken);let s=fS(e,n.job.jobId)?.job;return s?.state===`settled`?(gS(e,t,s.queue,s),{status:`settled`,job:s}):{status:`conflict`}}))})};return Object.freeze({store:i(n),partition:i,transactional:r})}var wS=V.check(H(1),K(256)),TS=V.check(H(1),K(200)),ES=Ia.check(Fa(-(2**53-1)),ga(2**53-1)),DS=Ia.check(Fa(0),ga(2**53-1)),OS=I({maxRecoveries:DS,windowMs:B(Ia.check(Ha(0),ga(2**53-1)))}),kS={jobId:wS,queue:wS,lane:Ux,priority:ES,payload:Ma,notBefore:B(DS),recovery:R(OS)},AS=I({...kS,state:U(`queued`)}),jS=G([`completed`,`failed`,`cancelled`,`outcome_unknown`,`interrupted`]),MS={...kS,outcome:jS,failureReason:B(TS)},NS=I({...MS,state:U(`completing`)}),PS=I({...MS,state:U(`settled`)}),FS=I({...kS,state:U(`running`)}),IS=F([AS,FS,NS,PS]);F([I({kind:U(`retry`)}),I({kind:U(`completed`)}),I({kind:U(`failed`),reason:B(TS)}),I({kind:U(`cancelled`)}),I({kind:U(`outcome_unknown`)})]);var LS=I({jobId:wS,cancellationId:wS,onlyIfQueued:R(Ua)}),RS=F([I({status:U(`absent`)}),I({status:U(`present`),cancellation:LS})]);F([I({status:U(`found`),job:IS,cancellation:RS}),I({status:U(`missing`)})]),F([I({state:U(`idle`)}),I({state:G([`queued`,`running`]),jobId:wS,cancellationRequested:Ua})]),F([I({status:U(`queued`)}),I({status:U(`duplicate`)})]),F([I({status:U(`decided`),outcome:jS}),I({status:G([`recorded`,`replayed`])}),I({status:G([`conflict`,`missing`])})]);var zS=F([ua(ArrayBuffer),V,ya,to]);io(V,zS);function BS(e){return vi({try:()=>{let t=e.concurrentLane===void 0?void 0:zi(Ux)(e.concurrentLane),n=CS(e.owner,e.project,t===void 0?void 0:{lane:t,include:!1}),r=Vx(e,n.store),i={...r,transactional:n.transactional};if(t===void 0)return Object.freeze(i);let a=Vx(e,n.partition({lane:t,include:!0}));return Object.freeze({...i,tickConcurrent:a.tick,close:Wr([Hr(r.close),Hr(a.close)],{concurrency:2}).pipe(yi(e=>{let t=e.find(Mi);return t===void 0?gi:Er(t.cause)})),failLane:e=>e.lane===t?a.failLane(e):r.failLane(e),cancel:e=>r.read(e.jobId).pipe(yi(n=>n.status===`found`&&n.job.lane===t?a.cancel(e):r.cancel(e)))})},catch:e=>e instanceof Rx?e:new Rx(`store_unavailable`,e)})}var VS=e=>({owner:e.owner,project:e.project,isAlive:t=>jr({try:()=>e.isAlive(t),catch:e=>new Rx(`liveness_unavailable`,e)}),executor:{retryPolicy:t=>{let n=e.retryPolicy;return n===void 0?ii(void 0):jr({try:()=>n(t),catch:e=>new Rx(`execution_failed`,e)})},execute:(t,n)=>jr({try:r=>e.execute(t,r,n),catch:()=>new Rx(`execution_failed`)})},wake:{recompute:()=>jr({try:()=>e.wake.recompute(),catch:()=>new Rx(`wake_unavailable`)})}}),HS=e=>Kr(e).then(e=>{if(Ai(e))return e.value;let t=Gr(Ii(e.cause))??uo(e.cause);return Promise.reject(t instanceof Error?t:Error(String(t)))});function US(e){let t=VS(e);return e.concurrentLane===void 0?HS(BS(t)).then(WS):HS(BS({...t,concurrentLane:e.concurrentLane})).then(e=>Object.freeze({...WS(e),tickConcurrent:()=>HS(e.tickConcurrent())}))}function WS(e){return Object.freeze({wakeState:t=>HS(e.wakeState(t)),ingest:t=>HS(e.ingest(t)),read:t=>HS(e.read(t)),readQueueHead:t=>HS(e.readQueueHead(t)),tick:()=>HS(e.tick()),cancel:t=>HS(e.cancel(t)),failLane:t=>HS(e.failLane(t)),purge:t=>HS(e.purge(t)),transactional:e.transactional})}Object.freeze({make:US});function GS(e){return wr(()=>_o(()=>import(`./runtime-core-BZbN1OFo.js`).then(e=>e.t),__vite__mapDeps([0,1,2,3,4]))).pipe(yi(({openRuntimeCore:t})=>t(e)),ir(({agent:e})=>e))}Object.freeze({module:Oa,operation:Ja,gate:za}),Qi(Ci),zi(Bi(Ci));var KS=class extends ur()(`@fungi.computer/shiitake/ExtensionRead`){},qS=class extends ur()(`@fungi.computer/shiitake/ExtensionTx`){},JS=class extends Ei(`ExtensionStateError`){},YS=class extends Ei(`AdmissionError`){},XS=class extends Ei(`ExtensionCommandError`){},ZS=class extends Ei(`ExtensionStop`){};Ei(`ExtensionActivationError`),zi(Aa),zi(xa),ca(V);function QS(e){return e instanceof Oi?e:new Oi(`model`,`rejected`,`Model acquisition failed`,void 0,e)}function $S(e){return new Oi(`model`,`rejected`,`Model release failed`,void 0,e)}function eC(e){let t=jr({try:()=>e.release(),catch:$S}),n={model:e.model,release:t,retryable:e.retryable};return e.failureReason!==void 0&&(n={...n,failureReason:e.failureReason}),e.providerError!==void 0&&(n={...n,providerError:e.providerError}),e.rejection!==void 0&&(n={...n,rejection:e.rejection}),e.stream===void 0?e.retryAfterMs===void 0?Object.freeze(n):Object.freeze({...n,retryAfterMs:e.retryAfterMs}):e.retryAfterMs===void 0?Object.freeze({...n,stream:e.stream}):Object.freeze({...n,stream:e.stream,retryAfterMs:e.retryAfterMs})}function tC(e){return Xr((t,n)=>{if(n.aborted)return;let r;try{r=Promise.resolve(e(n))}catch(e){t(Rr(QS(e)));return}let i=r.then(e=>{if(n.aborted)return Promise.resolve(e.release()).then(()=>void 0);t(ii(eC(e)))},e=>{n.aborted?da(`late-model-acquisition`,e):t(Rr(QS(e)))});return jr({try:()=>i,catch:$S}).pipe(Sr)})}function nC(e){let t,n=Xn(n=>yi(n(e),e=>Ur(()=>(t=e,e))));return di(n,()=>t===void 0?gi:t.release.pipe(Sr),{interruptible:!0})}function rC(e){let t=({sessionId:t,preference:n})=>tC(r=>e.acquire({sessionId:t,preference:n,signal:r})),n=e.describe;return Object.freeze(n===void 0?{acquire:t}:{acquire:t,describe:({sessionId:e,preference:t})=>jr({try:r=>n({sessionId:e,preference:t,signal:r}),catch:QS})})}function iC(e,t){return new Oi(e,`rejected`,t)}var aC=V.pipe(z(H(1)),z(K(256))),oC=V.pipe(z(H(1)),z(L(e=>new TextEncoder().encode(e).byteLength<=32e3))),sC=I({revision:aC,text:oC,modules:B(Yi(e=>Array.isArray(e)&&e.every(_i)))}),cC=Yi(e=>Br(e)),lC=Yi(e=>Br(e)),uC=I({bind:cC}),dC=Yi(e=>Br(e)),fC=I({commit:dC,requestWake:lC,close:lC}),pC=I({close:lC}),mC=ia(sC),hC=ia(uC),gC=ia(fC),_C=ia(pC);function vC(e){return new Oi(`runtime`,`invalid`,`Runtime host is invalid`,void 0,e)}function yC(){return new Oi(`runtime`,`unavailable`,`Runtime host is unavailable`)}function bC(e,t){return vi({try:()=>t.call(e),catch:yC}).pipe(yi(e=>jr({try:()=>Promise.resolve(e),catch:yC})),yi(e=>e===void 0?gi:Rr(vC())))}function xC(e,t,n){let r=_C({close:t});return r._tag===`Failure`?Rr(vC(n)):hr(bC(e,r.success.close)).pipe(vr({onFailure:e=>Rr(vC({cause:n,cleanup:e})),onSuccess:()=>Rr(vC(n))}))}function SC(e){return $r(()=>{if(!_i(e))return Rr(vC());let t=e,n;try{n=t.close}catch(e){return Rr(vC(e))}let r;try{r=t.requestWake}catch(e){return xC(t,n,e)}let i=gC({commit:t.commit,requestWake:r,close:n});return i._tag===`Failure`?xC(t,n):ii(Object.freeze({commit:e=>jr({try:()=>t.commit(()=>Ga(e)),catch:e=>e instanceof Oi?e:yC()}),requestWake:bC(t,i.success.requestWake),close:bC(t,i.success.close)}))})}function CC(e){return vi({try:()=>{let t=e.runtime;if(!_i(t))throw vC();let n=hC(t);if(n._tag===`Failure`)throw vC();return{receiver:t,bind:n.success.bind}},catch:vC}).pipe(ir(({receiver:e,bind:t})=>Object.freeze({bind:({reconcile:n,reconcileHost:r,pendingWork:i})=>vi({try:()=>t.call(e,{reconcile:()=>Ga(n),reconcileHost:r===void 0?void 0:()=>Ga(r),pendingWork:()=>Ga(i)}),catch:yC}).pipe(yi(e=>jr({try:()=>Promise.resolve(e),catch:yC})),yi(SC))})))}function wC(e){return{lane:e.lane,open:t=>{let n=e.open({transactional:t.transactional,readJob:e=>Ga(t.read(e)),tickConcurrent:()=>Ga(t.tickConcurrent())});return{retryPolicy:e=>{let t=n.retryPolicy;return t===void 0?ii(void 0):jr({try:()=>t(e),catch:e=>new Rx(`execution_failed`,e)})},execute:(e,t)=>jr({try:r=>n.execute(e,r,t),catch:e=>new Rx(`execution_failed`,e)})}}}}function TC(e,t){let n={store:e.store,runtime:t,extensions:e.extensions,instructions:{load:({sessionId:t,commandId:n})=>jr({try:r=>e.instructions.load({sessionId:t,commandId:n,signal:r}),catch:()=>iC(`instructions`,`Instruction acquisition failed`)}).pipe(yi(e=>{let t=mC(e);return t._tag===`Success`?ii(t.success):Rr(new Oi(`contract`,`invalid`,`Instruction revision is invalid`))}))},model:rC(e.model)},r=e.recipientStatus,i=e.recipientParent;i!==void 0&&Object.assign(n,{recipientParent:e=>jr(()=>i(e)).pipe(Nr(e=>er(`recipient.parent_unavailable`,Ta(e)).pipe(Or(Rr(new JS({reason:`unavailable`,message:`Recipient parent is unavailable`}))))))}),r!==void 0&&Object.assign(n,{recipientStatus:e=>jr(()=>r(e)).pipe(Nr(e=>er(`recipient.status_unavailable`,Ta(e)).pipe(ci(`unknown`))))}),e.hostJobs!==void 0&&Object.assign(n,{hostJobs:wC(e.hostJobs)}),e.meta!==void 0&&Object.assign(n,{meta:e.meta}),e.storagePressure!==void 0&&Object.assign(n,{storagePressure:e.storagePressure}),e.admission!==void 0&&Object.assign(n,{admission:e.admission}),e.compaction!==void 0&&Object.assign(n,{compaction:e.compaction});let a=e.tools;return a===void 0?n:{...n,tools:Da(a)}}function EC(e,t){return Ga(CC(e).pipe(yi(n=>t(TC(e,n))))).then(La)}Object.freeze({make:e=>EC(e,GS)});var DC=200,OC=Ar({action:ri(`list`)}),kC=bi(P(),Pr()).parse(structuredClone(dr(OC))),AC=120,jC=Ar({title:P()}).optional().transform(e=>e?.title.trim().replaceAll(/\s+/gu,` `)??``),MC=4096,NC=Ar({instructions:P()}).optional().transform(e=>e?.instructions.trim()??``);function PC(e,t){return e?.notify({type:`info`,message:t}),t}function FC(e,t){let n=e=>{throw Error(`${e} is unavailable in this host.`)};return{sourceId:t.sourceId,namespace:t.namespace,commands:[{id:`session`,title:`Session status`,category:`Advanced`,projections:{help:{order:1},palette:{order:1},slash:{aliases:[`session`],order:1}},handler:async({interaction:t})=>{let n=await e.read();return PC(t,`Session ${n.sessionId} is ${bn(dt(n))}; ${String(n.pending.prompts.length)} queued prompt${n.pending.prompts.length===1?``:`s`}.`)}},{id:`queue`,title:`Queued prompts`,category:`Advanced`,projections:{help:{order:3},palette:{order:3},slash:{aliases:[`queue`],order:3,arguments:{hint:`list`,words:[{word:`list`,description:`List accepted queued prompts`,arguments:{action:`list`}}]}}},action:{inputSchema:kC},handler:async({arguments:t,interaction:n})=>{if(!OC.safeParse(t??{action:`list`}).success)throw Error(`/queue requires list.`);let r=await e.read(),i=r.pending.prompts,a=r.terminals.map(e=>`${e.outcome} · ${e.commandId}`);PC(n,i.length===0&&a.length===0?`No queued prompts.`:[...i.map((e,t)=>`${String(t+1)}. queued · accepted: ${e.text}`),...a,...r.pending.hasMore===!0?[`More accepted prompts are waiting outside this view.`]:[]].join(`
|
|
117
|
+
`))}},{id:`resume`,title:`Resume a conversation`,category:`Conversation`,projections:{help:{order:5},palette:{order:5},slash:{aliases:[`resume`],order:5}},handler:async()=>{if(!t.sessionResumeAvailable||t.sessionResume===void 0){n(`/resume`);return}await t.sessionResume()}},{id:`fork`,title:`Fork conversation`,category:`Conversation`,projections:{help:{order:7},palette:{order:7},slash:{aliases:[`fork`],order:7}},handler:async({interaction:r})=>{let i=t.onForked;if(!t.forkAvailable||i===void 0){n(`/fork`);return}let a=await e.read();if(bn(dt(a))!==`idle`)throw Error(`Wait for the current run to finish, then fork.`);let o=He(a.messages??[],a.compactions??[]).items.filter(e=>e.kind===`user_message`);if(o.length===0)throw Error(`No messages to fork from.`);if(r===void 0)throw Error(`Forking a Session needs a person.`);let s=[...o].reverse().slice(0,DC),c=Date.now(),l=await r.prompt({type:`choice`,message:`Fork from which message?`,summary:`Start a new conversation from your message.`,options:s.map(e=>({value:e.id,label:hx(e.text,44)||`(empty message)`,description:e.at===void 0?void 0:mx(e.at,c)}))}),u=await r.run(async()=>{try{return await e.command({type:`fork`,entryId:l})}catch(e){if(e instanceof Oi){if(e.boundary===`runtime`&&e.cause===`conflict`)throw Error(`Wait for the current run to finish, then fork.`,{cause:e});if(e.boundary===`store`&&e.cause===`unavailable`)throw Error(`That message is no longer available to fork from.`,{cause:e});if(e.boundary===`runtime`&&e.cause===`rejected`)throw Error(`This Session is bound to a channel and cannot be forked.`,{cause:e})}throw e}});await r.run(async()=>{await i(u.sessionId)})}},{id:`compact`,title:`Compact conversation`,category:`Conversation`,description:`Summarize older context now; optional text sets its focus`,projections:{help:{order:8},palette:{order:8},slash:{aliases:[`compact`],order:8,arguments:{hint:`[instructions]`,text:{field:`instructions`,arguments:{}}}}},handler:async({arguments:t})=>{let n=NC.safeParse(t);if(!n.success)throw Error(`Use /compact, or /compact <what to focus on>.`);let r=n.data;if(r.length>MC)throw Error(`Compaction instructions are at most ${String(MC)} characters.`);return await e.command(r.length===0?{type:`compact`,requestId:Xa()}:{type:`compact`,requestId:Xa(),instructions:r}),`Compaction queued; it runs after any current work.`}},{id:`name`,title:`Name conversation`,category:`Conversation`,description:`Set the conversation title; no text restores it`,projections:{help:{order:9},palette:{order:9},slash:{aliases:[`name`],order:9,arguments:{hint:`[title]`,text:{field:`title`,arguments:{}}}}},handler:async({arguments:n})=>{let r=jC.safeParse(n);if(!r.success)throw Error(`Use /name <title>, or /name to clear it.`);let i=r.data;if(Array.from(i).length>AC)throw Error(`A conversation title is at most ${String(AC)} characters.`);let a=i.length===0?null:i;return await e.command({type:`title`,title:a}),await t.onTitled?.(a),a===null?`Conversation title cleared; it follows the first prompt again.`:`Conversation named "${a}".`}}]}.commands}function IC(e,t){return t!=null&&!Fn(t)?0:typeof e==`function`?e():e}function LC(e,t,n){let r=IC(e,n);return typeof r==`number`?r:r?.[t]}function RC(e){return typeof e==`function`?e():e}function zC(e,t){return t||e===`click`||e===`mousedown`}function BC(e){return e?.includes(`mouse`)&&e!==`mousedown`}var VC=class e{pointerType=void 0;interactedInside=!1;handler=void 0;blockMouseMove=!0;performedPointerEventsMutation=!1;pointerEventsScopeElement=null;pointerEventsReferenceElement=null;pointerEventsFloatingElement=null;restTimeoutPending=!1;openChangeTimeout=new xn;restTimeout=new xn;handleCloseOptions=void 0;static create(){return new e}dispose=()=>{this.openChangeTimeout.clear(),this.restTimeout.clear()};disposeEffect=()=>this.dispose},HC=new WeakMap;function UC(e){if(!e.performedPointerEventsMutation)return;let t=e.pointerEventsScopeElement;t&&HC.get(t)===e&&(e.pointerEventsScopeElement?.style.removeProperty(`pointer-events`),e.pointerEventsReferenceElement?.style.removeProperty(`pointer-events`),e.pointerEventsFloatingElement?.style.removeProperty(`pointer-events`),HC.delete(t)),e.performedPointerEventsMutation=!1,e.pointerEventsScopeElement=null,e.pointerEventsReferenceElement=null,e.pointerEventsFloatingElement=null}function WC(e,t){let{scopeElement:n,referenceElement:r,floatingElement:i}=t,a=HC.get(n);a&&a!==e&&UC(a),UC(e),e.performedPointerEventsMutation=!0,e.pointerEventsScopeElement=n,e.pointerEventsReferenceElement=r,e.pointerEventsFloatingElement=i,HC.set(n,e),n.style.pointerEvents=`none`,r.style.pointerEvents=`auto`,i.style.pointerEvents=`auto`}function GC(e){let t=e.context.dataRef.current,n=un(()=>t.hoverInteractionState??VC.create()).current;return t.hoverInteractionState||=n,Kt(t.hoverInteractionState.disposeEffect),t.hoverInteractionState}function KC(e,t={}){let{enabled:n=!0,closeDelay:r=0,nodeId:i}=t,a=e.useState(`open`),o=e.useState(`floatingElement`),s=e.useState(`domReferenceElement`),{dataRef:c}=e.context,l=Mn(),u=nt(),d=GC(e),f=ft(),p=Ct(()=>zC(c.current.openEvent?.type,d.interactedInside)),m=Ct(()=>BC(c.current.openEvent?.type)),g=Ct(()=>{UC(d)});ot(()=>{a||(d.pointerType=void 0,d.restTimeoutPending=!1,d.interactedInside=!1,g())},[a,d,g]),q.useEffect(()=>g,[g]),ot(()=>{if(n&&a&&d.handleCloseOptions?.blockPointerEvents&&m()&&Ye(s)&&o){let e=s,t=o,n=h(o),r=l?.nodesRef.current.find(e=>e.id===u)?.context?.elements.floating;r&&(r.style.pointerEvents=``);let i=d.pointerEventsScopeElement===t?null:d.pointerEventsScopeElement,a=r===t?null:r,c=d.handleCloseOptions?.getScope?.()??i??a??T(e,`[data-rootownerid]`)??n.body;return WC(d,{scopeElement:c,referenceElement:e,floatingElement:t}),()=>{g()}}},[n,a,s,o,d,m,l,u,g]),q.useEffect(()=>{if(!n)return;function t(){return!!(l&&u&&Ne(l.nodesRef.current,u).length>0)}function a(t){let n=LC(r,`close`,d.pointerType),i=()=>{e.setOpen(!1,N(he,t)),l?.events.emit(`floating.closed`,t)};n?d.openChangeTimeout.start(n,i):(d.openChangeTimeout.clear(),i())}function s(e){let t=M(e);if(!S(t)){d.interactedInside=!1;return}d.interactedInside=T(t,`[aria-haspopup]`)!=null}function h(){d.openChangeTimeout.clear(),f.clear(),l?.events.off(`floating.closed`,v),g()}function _(n){if(t()&&l){l.events.on(`floating.closed`,v);return}if(y(n.relatedTarget,e.context.triggerElements))return;let r=c.current.floatingContext?.nodeId??i,o=n.relatedTarget;if(!(l&&r&&Ye(o)&&Ne(l.nodesRef.current,r,!1).some(e=>re(e.context?.elements.floating,o)))){if(d.handler){d.handler(n);return}g(),m()&&!p()&&a(n)}}function v(n){!l||!u||t()||f.start(0,()=>{l.events.off(`floating.closed`,v),e.setOpen(!1,N(he,n)),l.events.emit(`floating.closed`,n)})}let b=o;return C(b&&An(b,`mouseenter`,h),b&&An(b,`mouseleave`,_),b&&An(b,`pointerdown`,s,!0),()=>{l?.events.off(`floating.closed`,v)})},[n,o,e,c,r,i,m,p,g,d,l,u,f])}var qC=e(Qe(),1),JC={current:null};function YC(e,t={}){let{enabled:n=!0,delay:r=0,handleClose:i=null,mouseOnly:a=!1,restMs:o=0,move:s=!0,triggerElementRef:c=JC,externalTree:l,isActiveTrigger:u=!0,getHandleCloseContext:d,isClosing:f,shouldOpen:p,guardStaleOpen:m=!1}=t,{dataRef:g,events:_}=e.context,v=Mn(l),b=GC(e),x=q.useRef(!1),S=Fe(i),w=Fe(r),T=Fe(o),E=Fe(n),ee=Fe(p),D=Fe(f),O=Ct(()=>zC(g.current.openEvent?.type,b.interactedInside)),k=Ct(()=>ee.current?.()!==!1),A=Ct((t,n,r)=>{let i=e.context.triggerElements;if(i.hasElement(n))return!t||!re(t,n);if(!Ye(r))return!1;let a=r;return i.hasMatchingElement(e=>re(e,a))&&(!t||!re(t,a))}),j=Ct(()=>{b.handler&&=(h(e.select(`domReferenceElement`)).removeEventListener(`mousemove`,b.handler),void 0)}),te=Ct(()=>{UC(b)});return u&&(b.handleCloseOptions=i?.__options),q.useEffect(()=>j,[j]),q.useEffect(()=>{if(!n)return;function e(e){e.open?x.current=!1:(x.current=e.reason===he,j(),b.openChangeTimeout.clear(),b.restTimeout.clear(),b.blockMouseMove=!0,b.restTimeoutPending=!1)}return _.on(`openchange`,e),()=>{_.off(`openchange`,e)}},[n,_,b,j]),q.useEffect(()=>{if(!n)return;function t(t,n=!0){let r=LC(w.current,`close`,b.pointerType);r?b.openChangeTimeout.start(r,()=>{e.setOpen(!1,N(he,t)),v?.events.emit(`floating.closed`,t)}):n&&(b.openChangeTimeout.clear(),e.setOpen(!1,N(he,t)),v?.events.emit(`floating.closed`,t))}let r=c.current??(u?e.select(`domReferenceElement`):null);if(!Ye(r))return;function i(t){if(b.openChangeTimeout.clear(),b.blockMouseMove=!1,a&&!Fn(b.pointerType))return;let n=RC(T.current),r=LC(w.current,`open`,b.pointerType),i=M(t),o=t.currentTarget??null,s=e.select(`domReferenceElement`),c=o;if(Ye(i)&&!e.context.triggerElements.hasElement(i)){for(let t of e.context.triggerElements.elements())if(re(t,i)){c=t;break}}Ye(o)&&Ye(s)&&!e.context.triggerElements.hasElement(o)&&re(o,s)&&(c=s);let l=c!=null&&A(s,c,i),u=e.select(`open`),d=D.current?.()??e.select(`transitionStatus`)===`ending`,f=!u&&d&&x.current,p=!l&&Ye(c)&&Ye(s)&&re(s,c)&&f,m=n>0&&!r,h=l&&(u||f)||p,g=!u||l;if(h){k()&&e.setOpen(!0,N(he,t,c));return}m||(r?b.openChangeTimeout.start(r,()=>{g&&k()&&e.setOpen(!0,N(he,t,c))}):g&&k()&&e.setOpen(!0,N(he,t,c)))}function o(n){if(O()){te();return}j();let r=e.select(`domReferenceElement`),i=h(r);b.restTimeout.clear(),b.restTimeoutPending=!1;let a=g.current.floatingContext??d?.();if(!y(n.relatedTarget,e.context.triggerElements)){if(S.current&&a){e.select(`open`)||b.openChangeTimeout.clear();let r=c.current;b.handler=S.current({...a,tree:v,x:n.clientX,y:n.clientY,onClose(){te(),j(),E.current&&!O()&&r===e.select(`domReferenceElement`)&&t(n,!0)}}),i.addEventListener(`mousemove`,b.handler),b.handler(n);return}(b.pointerType!==`touch`||!re(e.select(`floatingElement`),n.relatedTarget))&&t(n)}}function l(e){re(r,e.relatedTarget)||(b.openChangeTimeout.clear(),b.restTimeout.clear(),b.restTimeoutPending=!1)}let f=m?An(r,`mouseout`,l):void 0;return s?C(An(r,`mousemove`,i,{once:!0}),An(r,`mouseenter`,i),An(r,`mouseleave`,o),f):C(An(r,`mouseenter`,i),An(r,`mouseleave`,o),f)},[j,te,g,w,e,n,S,b,u,A,O,a,s,T,c,v,E,d,D,k,m]),q.useMemo(()=>{if(!n)return;function t(e){b.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=A(i,r,t.target);if(a&&!Fn(b.pointerType))return;if(o&&s&&b.handleCloseOptions?.blockPointerEvents){let t=e.select(`floatingElement`);if(t){let e=b.handleCloseOptions?.getScope?.()??r.ownerDocument.body;WC(b,{scopeElement:e,referenceElement:r,floatingElement:t})}}let c=RC(T.current);if(o&&!s||c===0||!s&&b.restTimeoutPending&&t.movementX**2+t.movementY**2<2)return;b.restTimeout.clear();function l(){if(b.restTimeoutPending=!1,O())return;let t=e.select(`open`);!b.blockMouseMove&&(!t||s)&&k()&&e.setOpen(!0,N(he,n,r))}b.pointerType===`touch`?qC.flushSync(()=>{l()}):s&&o?l():(b.restTimeoutPending=!0,b.restTimeout.start(c,l))}}},[n,b,O,A,a,e,T,k])}var XC=.1,ZC=XC*XC,QC=.5;function $C(e,t,n,r,i,a){return r>=t!=a>=t&&e<=(i-n)*(t-r)/(a-r)+n}function ew(e,t,n,r,i,a,o,s,c,l){let u=!1;return $C(e,t,n,r,i,a)&&(u=!u),$C(e,t,i,a,o,s)&&(u=!u),$C(e,t,o,s,c,l)&&(u=!u),$C(e,t,c,l,n,r)&&(u=!u),u}function tw(e,t,n){return e>=n.x&&e<=n.x+n.width&&t>=n.y&&t<=n.y+n.height}function nw(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 rw(e={}){let{blockPointerEvents:t=!1}=e,n=new xn,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,f=typeof performance<`u`?performance.now():0;function p(e,t){let n=performance.now(),r=n-f;if(u===null||d===null||r===0)return u=e,d=t,f=n,!1;let i=e-u,a=t-d,o=i*i+a*a,s=r*r*ZC;return u=e,d=t,f=n,o<s}function m(){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:f}=r,h=M(r),g=r.type===`mouseleave`,_=re(u,h),v=re(a,h);if(_&&(l=!0,!g))return;if(v&&(l=!1,!g)){l=!0;return}if(g&&Ye(r.relatedTarget)&&re(u,r.relatedTarget))return;function y(){return!!(s&&Ne(s.nodesRef.current,o).length>0)}function b(){y()||m()}if(y())return;let x=a.getBoundingClientRect(),S=u.getBoundingClientRect(),C=e>S.right-S.width/2,w=t>S.bottom-S.height/2,T=S.width>x.width,E=S.height>x.height,ee=(T?x:S).left,D=(T?x:S).right,O=(E?x:S).top,k=(E?x:S).bottom;if(c===`top`&&t>=x.bottom-1||c===`bottom`&&t<=x.top+1||c===`left`&&e>=x.right-1||c===`right`&&e<=x.left+1){b();return}let A=!1;switch(c){case`top`:A=nw(d,f,ee,x.top+1,D,S.bottom-1);break;case`bottom`:A=nw(d,f,ee,S.top+1,D,x.bottom-1);break;case`left`:A=nw(d,f,S.right-1,k,x.left+1,O);break;case`right`:A=nw(d,f,x.right-1,k,S.left+1,O)}if(A)return;if(l&&!tw(d,f,x)){b();return}if(!g&&p(d,f)){b();return}let j=!1;switch(c){case`top`:{let n=T?QC/2:QC*4,r=T||C?e+n:e-n,i=T?e-n:C?e+n:e-n,a=t+QC+1,o=C||T?S.bottom-QC:S.top,s=C?T?S.bottom-QC:S.top:S.bottom-QC;j=ew(d,f,r,a,i,a,S.left,o,S.right,s);break}case`bottom`:{let n=T?QC/2:QC*4,r=T||C?e+n:e-n,i=T?e-n:C?e+n:e-n,a=t-QC,o=C||T?S.top+QC:S.bottom,s=C?T?S.top+QC:S.bottom:S.top+QC;j=ew(d,f,r,a,i,a,S.left,o,S.right,s);break}case`left`:{let n=E?QC/2:QC*4,r=E||w?t+n:t-n,i=E?t-n:w?t+n:t-n,a=e+QC+1,o=w||E?S.right-QC:S.left,s=w?E?S.right-QC:S.left:S.right-QC;j=ew(d,f,o,S.top,s,S.bottom,a,r,a,i);break}case`right`:{let n=E?QC/2:QC*4,r=E||w?t+n:t-n,i=E?t-n:w?t+n:t-n,a=e-QC,o=w||E?S.left+QC:S.right,s=w?E?S.left+QC:S.right:S.left+QC;j=ew(d,f,a,r,a,i,o,S.top,s,S.bottom);break}}j?l||n.start(40,b):b()}};return r.__options={...e,blockPointerEvents:t},r}function iw(e,t,n){let{reference:r,floating:i}=e,a=fb(t),o=pb(t),s=db(o),c=cb(t),l=a===`y`,u=r.x+r.width/2-i.width/2,d=r.y+r.height/2-i.height/2,f=r[s]/2-i[s]/2,p;switch(c){case`top`:p={x:u,y:r.y-i.height};break;case`bottom`:p={x:u,y:r.y+r.height};break;case`right`:p={x:r.x+r.width,y:d};break;case`left`:p={x:r.x-i.width,y:d};break;default:p={x:r.x,y:r.y}}let m=lb(t);return m&&(p[o]+=f*(m===`end`?1:-1)*(n&&l?-1:1)),p}async function aw(e,t){t===void 0&&(t={});let{x:n,y:r,platform:i,rects:a,elements:o,strategy:s}=e,{boundary:c=`clippingAncestors`,rootBoundary:l=`viewport`,elementContext:u=`floating`,altBoundary:d=!1,padding:f=0}=sb(t,e),p=Tb(f),m=o[d?u===`floating`?`reference`:`floating`:u],h=Eb(await i.getClippingRect({element:await(i.isElement==null?void 0:i.isElement(m))??!0?m:m.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(o.floating)),boundary:c,rootBoundary:l,strategy:s})),g=u===`floating`?{x:n,y:r,width:a.floating.width,height:a.floating.height}:a.reference,_=await(i.getOffsetParent==null?void 0:i.getOffsetParent(o.floating)),v=await(i.isElement==null?void 0:i.isElement(_))&&await(i.getScale==null?void 0:i.getScale(_))||{x:1,y:1},y=Eb(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:g,offsetParent:_,strategy:s}):g);return{top:(h.top-y.top+p.top)/v.y,bottom:(y.bottom-h.bottom+p.bottom)/v.y,left:(h.left-y.left+p.left)/v.x,right:(y.right-h.right+p.right)/v.x}}var ow=50,sw=async(e,t,n)=>{let{placement:r=`bottom`,strategy:i=`absolute`,middleware:a=[],platform:o}=n,s=o.detectOverflow?o:{...o,detectOverflow:aw},c=await(o.isRTL==null?void 0:o.isRTL(t)),l=await o.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:d}=iw(l,r,c),f=r,p=0,m={};for(let n=0;n<a.length;n++){let h=a[n];if(!h)continue;let{name:g,fn:_}=h,{x:v,y,data:b,reset:x}=await _({x:u,y:d,initialPlacement:r,placement:f,strategy:i,middlewareData:m,rects:l,platform:s,elements:{reference:e,floating:t}});u=v??u,d=y??d,m[g]={...m[g],...b},x&&p<ow&&(p++,typeof x==`object`&&(x.placement&&(f=x.placement),x.rects&&(l=x.rects===!0?await o.getElementRects({reference:e,floating:t,strategy:i}):x.rects),{x:u,y:d}=iw(l,f,c)),n=-1)}return{x:u,y:d,placement:f,strategy:i,middlewareData:m}},cw=function(e){return e===void 0&&(e={}),{name:`flip`,options:e,async fn(t){var n;let{placement:r,middlewareData:i,rects:a,initialPlacement:o,platform:s,elements:c}=t,{mainAxis:l=!0,crossAxis:u=!0,fallbackPlacements:d,fallbackStrategy:f=`bestFit`,fallbackAxisSideDirection:p=`none`,flipAlignment:m=!0,...h}=sb(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};let g=cb(r),_=fb(o),v=cb(o)===o,y=await(s.isRTL==null?void 0:s.isRTL(c.floating)),b=d||(v||!m?[Cb(o)]:hb(o)),x=p!==`none`;!d&&x&&b.push(...Sb(o,m,p,y));let S=[o,...b],C=await s.detectOverflow(t,h),w=[],T=i.flip?.overflows||[];if(l&&w.push(C[g]),u){let e=mb(r,a,y);w.push(C[e[0]],C[e[1]])}if(T=[...T,{placement:r,overflows:w}],!w.every(e=>e<=0)){let e=(i.flip?.index||0)+1,t=S[e];if(t&&(u!==`alignment`||_===fb(t)||T.every(e=>fb(e.placement)!==_||e.overflows[0]>0)))return{data:{index:e,overflows:T},reset:{placement:t}};let n=T.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0]?.placement;if(!n)switch(f){case`bestFit`:{let e=T.filter(e=>{if(x){let t=fb(e.placement);return t===_||t===`y`}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0]?.[0];e&&(n=e);break}case`initialPlacement`:n=o}if(r!==n)return{reset:{placement:n}}}return{}}}},lw=new Set([`left`,`top`]);async function uw(e,t){let{placement:n,platform:r,elements:i}=e,a=await(r.isRTL==null?void 0:r.isRTL(i.floating)),o=cb(n),s=lb(n),c=fb(n)===`y`,l=lw.has(o)?-1:1,u=a&&c?-1:1,d=sb(t,e),{mainAxis:f,crossAxis:p,alignmentAxis:m}=typeof d==`number`?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return s&&typeof m==`number`&&(p=s===`end`?m*-1:m),c?{x:p*u,y:f*l}:{x:f*l,y:p*u}}var dw=function(e){return e===void 0&&(e=0),{name:`offset`,options:e,async fn(t){var n;let{x:r,y:i,placement:a,middlewareData:o}=t,s=await uw(t,e);return a===o.offset?.placement&&(n=o.arrow)!=null&&n.alignmentOffset?{}:{x:r+s.x,y:i+s.y,data:{...s,placement:a}}}}},fw=function(e){return e===void 0&&(e={}),{name:`shift`,options:e,async fn(t){let{x:n,y:r,placement:i,platform:a}=t,{mainAxis:o=!0,crossAxis:s=!1,limiter:c={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...l}=sb(e,t),u={x:n,y:r},d=await a.detectOverflow(t,l),f=fb(i),p=ub(f),m=u[p],h=u[f],g=(e,t)=>ob(t+d[e===`y`?`top`:`left`],t,t-d[e===`y`?`bottom`:`right`]);o&&(m=g(p,m)),s&&(h=g(f,h));let _=c.fn({...t,[p]:m,[f]:h});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[p]:o,[f]:s}}}}}},pw=function(e){return e===void 0&&(e={}),{options:e,fn(t){let{x:n,y:r,placement:i,rects:a,middlewareData:o}=t,{offset:s=0,mainAxis:c=!0,crossAxis:l=!0}=sb(e,t),u={x:n,y:r},d=fb(i),f=ub(d),p=u[f],m=u[d],h=sb(s,t),g=typeof h==`number`?{mainAxis:h,crossAxis:0}:{mainAxis:h.mainAxis??0,crossAxis:h.crossAxis??0};if(c){let e=f===`y`?`height`:`width`,t=a.reference[f]-a.floating[e]+g.mainAxis,n=a.reference[f]+a.reference[e]-g.mainAxis;p<t?p=t:p>n&&(p=n)}if(l){let e=f===`y`?`width`:`height`,t=lw.has(cb(i)),n=a.reference[d]-a.floating[e]+(t&&o.offset?.[d]||0)+(t?0:g.crossAxis),r=a.reference[d]+a.reference[e]+(t?0:o.offset?.[d]||0)-(t?g.crossAxis:0);m<n?m=n:m>r&&(m=r)}return{[f]:p,[d]:m}}}},mw=function(e){return e===void 0&&(e={}),{name:`size`,options:e,async fn(t){let{placement:n,rects:r,platform:i,elements:a}=t,{apply:o=()=>{},...s}=sb(e,t),c=await i.detectOverflow(t,s),l=cb(n),u=lb(n),d=fb(n)===`y`,{width:f,height:p}=r.floating,m,h;l===`top`||l===`bottom`?(m=l,h=u===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?`start`:`end`)?`left`:`right`):(h=l,m=u===`end`?`top`:`bottom`);let g=p-c.top-c.bottom,_=f-c.left-c.right,v=eb(p-c[m],g),y=eb(f-c[h],_),b=t.middlewareData.shift,x=!b,S=v,C=y;b!=null&&b.enabled.x&&(C=_),b!=null&&b.enabled.y&&(S=g),x&&!u&&(d?C=f-2*tb(c.left,c.right):S=p-2*tb(c.top,c.bottom)),await o({...t,availableWidth:C,availableHeight:S});let w=await i.getDimensions(a.floating);return f!==w.width||p!==w.height?{reset:{rects:!0}}:{}}}};function hw(e){let t=Gn(e),n=parseFloat(t.width)||0,r=parseFloat(t.height)||0,i=qe(e),a=i?e.offsetWidth:n,o=i?e.offsetHeight:r,s=nb(n)!==a||nb(r)!==o;return s&&(n=a,r=o),{width:n,height:r,$:s}}function gw(e){return Ye(e)?e:e.contextElement}function _w(e){let t=gw(e);if(!qe(t))return ib(1);let n=t.getBoundingClientRect(),{width:r,height:i,$:a}=hw(t),o=(a?nb(n.width):n.width)/r,s=(a?nb(n.height):n.height)/i;return(!o||!Number.isFinite(o))&&(o=1),(!s||!Number.isFinite(s))&&(s=1),{x:o,y:s}}var vw=ib(0);function yw(e){let t=pn(e);return!Tn()||!t.visualViewport?vw:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function bw(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===pn(e)}function xw(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);let i=e.getBoundingClientRect(),a=gw(e),o=ib(1);t&&(r?Ye(r)&&(o=_w(r)):o=_w(e));let s=bw(a,n,r)?yw(a):ib(0),c=(i.left+s.x)/o.x,l=(i.top+s.y)/o.y,u=i.width/o.x,d=i.height/o.y;if(a&&r){let e=pn(a),t=Ye(r)?pn(r):r,n=e,i=j(n);for(;i&&t!==n;){let e=_w(i),t=i.getBoundingClientRect(),r=Gn(i),a=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,o=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;c*=e.x,l*=e.y,u*=e.x,d*=e.y,c+=a,l+=o,n=pn(i),i=j(n)}}return Eb({width:u,height:d,x:c,y:l})}function Sw(e,t){let n=We(e).scrollLeft;return t?t.left+n:xw(Be(e)).left+n}function Cw(e,t){let n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-Sw(e,n),y:n.top+t.scrollTop}}function ww(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e,a=i===`fixed`,o=Be(r),s=t?yt(t.floating):!1;if(r===o||s&&a)return n;let c={scrollLeft:0,scrollTop:0},l=ib(1),u=ib(0),d=qe(r);if((d||!a)&&((Le(r)!==`body`||Se(o))&&(c=We(r)),d)){let e=xw(r);l=_w(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}let f=o&&!d&&!a?Cw(o,c):ib(0);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+u.x+f.x,y:n.y*l.y-c.scrollTop*l.y+u.y+f.y}}function Tw(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function Ew(e){let t=We(e),n=e.ownerDocument.body,r=tb(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=tb(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight),a=-t.scrollLeft+Sw(e),o=-t.scrollTop;return Gn(n).direction===`rtl`&&(a+=tb(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:a,y:o}}var Dw=25;function Ow(e,t,n){n===void 0&&(n=`viewport`);let r=n===`layoutViewport`,i=pn(e),a=Be(e),o=i.visualViewport,s=a.clientWidth,c=a.clientHeight,l=0,u=0;if(o){let e=!Tn()||t===`fixed`;r?e||(l=-o.offsetLeft,u=-o.offsetTop):(s=o.width,c=o.height,e&&(l=o.offsetLeft,u=o.offsetTop))}if(Sw(a)<=0){let e=a.ownerDocument,t=e.body,n=getComputedStyle(t),r=e.compatMode===`CSS1Compat`&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(a.clientWidth-t.clientWidth-r),o=getComputedStyle(a).scrollbarGutter===`stable both-edges`?i/2:i;o<=Dw&&(s-=o)}return{width:s,height:c,x:l,y:u}}function kw(e,t){let n=xw(e,!0,t===`fixed`),r=n.top+e.clientTop,i=n.left+e.clientLeft,a=_w(e);return{width:e.clientWidth*a.x,height:e.clientHeight*a.y,x:i*a.x,y:r*a.y}}function Aw(e,t,n){let r;if(t===`viewport`||t===`layoutViewport`)r=Ow(e,n,t);else if(t===`document`)r=Ew(Be(e));else if(Ye(t))r=kw(t,n);else{let n=yw(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return Eb(r)}function jw(e,t){let n=t.get(e);if(n)return n;let r=O(e,[],!1).filter(e=>Ye(e)&&Le(e)!==`body`),i=null,a=Gn(e).position===`fixed`,o=a?ce(e):e;for(;Ye(o)&&!Ze(o);){let e=Gn(o),t=oe(o),n=i?i.position:a?`fixed`:``;!t&&(n===`fixed`||n===`absolute`&&e.position===`static`)?r=r.filter(e=>e!==o):i=e,o=ce(o)}return t.set(e,r),r}function Mw(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e,a=[...n===`clippingAncestors`?yt(t)?[]:jw(t,this._c):[].concat(n),r],o=Aw(t,a[0],i),s=o.top,c=o.right,l=o.bottom,u=o.left;for(let e=1;e<a.length;e++){let n=Aw(t,a[e],i);s=tb(n.top,s),c=eb(n.right,c),l=eb(n.bottom,l),u=tb(n.left,u)}return{width:c-u,height:l-s,x:u,y:s}}function Nw(e){let{width:t,height:n}=hw(e);return{width:t,height:n}}function Pw(e,t,n){let r=qe(t),i=Be(t),a=n===`fixed`,o=xw(e,!0,a,t),s={scrollLeft:0,scrollTop:0},c=ib(0);if((r||!a)&&((Le(t)!==`body`||Se(i))&&(s=We(t)),r)){let e=xw(t,!0,a,t);c.x=e.x+t.clientLeft,c.y=e.y+t.clientTop}!r&&i&&(c.x=Sw(i));let l=i&&!r&&!a?Cw(i,s):ib(0);return{x:o.left+s.scrollLeft-c.x-l.x,y:o.top+s.scrollTop-c.y-l.y,width:o.width,height:o.height}}function Fw(e){return Gn(e).position===`static`}function Iw(e,t){if(!qe(e)||Gn(e).position===`fixed`)return null;if(t)return t(e);let n=e.offsetParent;return Be(e)===n&&(n=n.ownerDocument.body),n}function Lw(e,t){let n=pn(e);if(yt(e))return n;if(!qe(e)){let t=ce(e);for(;t&&!Ze(t);){if(Ye(t)&&!Fw(t))return t;t=ce(t)}return n}let i=Iw(e,t);for(;i&&r(i)&&Fw(i);)i=Iw(i,t);return i&&Ze(i)&&Fw(i)&&!oe(i)?n:i||u(e)||n}var Rw=async function(e){let t=this.getOffsetParent||Lw,n=this.getDimensions,r=await n(e.floating);return{reference:Pw(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function zw(e){return Gn(e).direction===`rtl`}var Bw={convertOffsetParentRelativeRectToViewportRelativeRect:ww,getDocumentElement:Be,getClippingRect:Mw,getOffsetParent:Lw,getElementRects:Rw,getClientRects:Tw,getDimensions:Nw,getScale:_w,isElement:Ye,isRTL:zw};function Vw(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Hw(e,t,n){let r=null,i,a=Be(e);function o(){var e;clearTimeout(i),(e=r)==null||e.disconnect(),r=null}function s(n,c){n===void 0&&(n=!1),c===void 0&&(c=1),o();let l=e.getBoundingClientRect(),{left:u,top:d,width:f,height:p}=l;if(n||t(),!f||!p)return;let m=rb(d),h=rb(a.clientWidth-(u+f)),g=rb(a.clientHeight-(d+p)),_=rb(u),v={rootMargin:-m+`px `+-h+`px `+-g+`px `+-_+`px`,threshold:tb(0,eb(1,c))||1},y=!0;function b(t){let n=t[0].intersectionRatio;if(!Vw(l,e.getBoundingClientRect()))return s();if(n!==c){if(!y)return s();n?s(!1,n):i=setTimeout(()=>{s(!1,1e-7)},1e3)}y=!1}try{r=new IntersectionObserver(b,{...v,root:a.ownerDocument})}catch{r=new IntersectionObserver(b,v)}r.observe(e)}let c=pn(e),l=()=>s(n);return c.addEventListener(`resize`,l),s(!0),()=>{c.removeEventListener(`resize`,l),o()}}function Uw(e,t,n,r){r===void 0&&(r={});let{ancestorScroll:i=!0,ancestorResize:a=!0,elementResize:o=typeof ResizeObserver==`function`,layoutShift:s=typeof IntersectionObserver==`function`,animationFrame:c=!1}=r,l=gw(e),u=i||a?[...l?O(l):[],...t?O(t):[]]:[];u.forEach(e=>{i&&e.addEventListener(`scroll`,n),a&&e.addEventListener(`resize`,n)});let d=l&&s?Hw(l,n,a):null,f=-1,p=null;o&&(p=new ResizeObserver(e=>{let[r]=e;r&&r.target===l&&p&&t&&(p.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var e;(e=p)==null||e.observe(t)})),n()}),l&&!c&&p.observe(l),t&&p.observe(t));let m,h=c?xw(e):null;c&&g();function g(){let t=xw(e);h&&!Vw(h,t)&&n(),h=t,m=requestAnimationFrame(g)}return n(),()=>{var e;u.forEach(e=>{i&&e.removeEventListener(`scroll`,n),a&&e.removeEventListener(`resize`,n)}),d?.(),(e=p)==null||e.disconnect(),p=null,c&&cancelAnimationFrame(m)}}var Ww=dw,Gw=fw,Kw=cw,qw=mw,Jw=pw,Yw=(e,t,n)=>{let r=new Map,i=n??{},a={...Bw,...i.platform,_c:r};return sw(e,t,{...i,platform:a})},Xw=typeof document<`u`?q.useLayoutEffect:function(){};function Zw(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e==`function`&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e==`object`){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Zw(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){let n=i[r];if(!(n===`_owner`&&e.$$typeof)&&!Zw(e[n],t[n]))return!1}return!0}return e!==e&&t!==t}function Qw(e){return typeof window>`u`?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function $w(e,t){let n=Qw(e);return Math.round(t*n)/n}function eT(e){let t=q.useRef(e);return Xw(()=>{t.current=e}),t}function tT(e){e===void 0&&(e={});let{placement:t=`bottom`,strategy:n=`absolute`,middleware:r=[],platform:i,elements:{reference:a,floating:o}={},transform:s=!0,whileElementsMounted:c,open:l}=e,[u,d]=q.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,p]=q.useState(r);Zw(f,r)||p(r);let[m,h]=q.useState(null),[g,_]=q.useState(null),v=q.useCallback(e=>{e!==S.current&&(S.current=e,h(e))},[]),y=q.useCallback(e=>{e!==C.current&&(C.current=e,_(e))},[]),b=a||m,x=o||g,S=q.useRef(null),C=q.useRef(null),w=q.useRef(u),T=c!=null,E=eT(c),ee=eT(i),D=eT(l),O=q.useCallback(()=>{if(!S.current||!C.current)return;let e={placement:t,strategy:n,middleware:f};ee.current&&(e.platform=ee.current),Yw(S.current,C.current,e).then(e=>{let t={...e,isPositioned:D.current!==!1};k.current&&!Zw(w.current,t)&&(w.current=t,qC.flushSync(()=>{d(t)}))})},[f,t,n,ee,D]);Xw(()=>{l===!1&&w.current.isPositioned&&(w.current.isPositioned=!1,d(e=>({...e,isPositioned:!1})))},[l]);let k=q.useRef(!1);Xw(()=>(k.current=!0,()=>{k.current=!1}),[]),Xw(()=>{if(b&&(S.current=b),x&&(C.current=x),b&&x){if(E.current)return E.current(b,x,O);O()}},[b,x,O,E,T]);let A=q.useMemo(()=>({reference:S,floating:C,setReference:v,setFloating:y}),[v,y]),j=q.useMemo(()=>({reference:b,floating:x}),[b,x]),te=q.useMemo(()=>{let e={position:n,left:0,top:0};if(!j.floating)return e;let t=$w(j.floating,u.x),r=$w(j.floating,u.y);return s?{...e,transform:`translate(`+t+`px, `+r+`px)`,...Qw(j.floating)>=1.5&&{willChange:`transform`}}:{position:n,left:t,top:r}},[n,s,j.floating,u.x,u.y]);return q.useMemo(()=>({...u,update:O,refs:A,elements:j,floatingStyles:te}),[u,O,A,j,te])}var nT=(e,t)=>{let n=Ww(e);return{name:n.name,fn:n.fn,options:[e,t]}},rT=(e,t)=>{let n=Gw(e);return{name:n.name,fn:n.fn,options:[e,t]}},iT=(e,t)=>({fn:Jw(e).fn,options:[e,t]}),aT=(e,t)=>{let n=Kw(e);return{name:n.name,fn:n.fn,options:[e,t]}},oT=(e,t)=>{let n=qw(e);return{name:n.name,fn:n.fn,options:[e,t]}},sT=je(`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`}]]),cT=je(`Eye`,[[`path`,{d:`M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0`,key:`1nclc0`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),lT=je(`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`}]]),uT=je(`Pencil`,[[`path`,{d:`M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z`,key:`1a8usu`}],[`path`,{d:`m15 5 4 4`,key:`1mk7zo`}]]),dT=je(`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`}]]),fT=je(`SquarePen`,[[`path`,{d:`M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7`,key:`1m0v6g`}],[`path`,{d:`M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z`,key:`ohrbg2`}]]),pT=je(`Trash2`,[[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6`,key:`4alrt4`}],[`path`,{d:`M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2`,key:`v07s0e`}],[`line`,{x1:`10`,x2:`10`,y1:`11`,y2:`17`,key:`1uufr5`}],[`line`,{x1:`14`,x2:`14`,y1:`11`,y2:`17`,key:`xtxkd`}]]);function mT(e){let t=2166136261;for(let n of e)t^=n.codePointAt(0)??0,t=Math.imul(t,16777619)>>>0;return t}var hT=[`primary`,`secondary`,`accent`,`info`,`success`,`warning`];function gT(e){return hT[mT(e)%hT.length]??`primary`}var _T=(0,q.forwardRef)(function({className:e,name:t,seed:n,size:r=`default`,subject:i=`actor`,variant:a=`initial`,...o},s){let c=Array.from(t.trim())[0]?.toLocaleUpperCase()??`?`;return(0,Y.jsx)(`span`,{"aria-hidden":`true`,...o,className:E(`caps-monogram`,e),"data-subject":i===`actor`?void 0:i,"data-size":r==="default"?void 0:r,"data-tone":gT(n??t),ref:s,children:a===`specimen`?(0,Y.jsx)(`svg`,{viewBox:`0 0 48 48`,width:`80%`,height:`80%`,fill:`none`,"aria-hidden":`true`,children:(0,Y.jsxs)(`g`,{transform:`rotate(${String((n??t).split(``).reduce((e,t)=>e+(t.codePointAt(0)??0),0)%360)} 24 24)`,stroke:`currentColor`,strokeWidth:`1.5`,children:[Array.from({length:20},(e,t)=>(0,Y.jsx)(`path`,{d:`M24 19 Q19 12 24 5`,transform:`rotate(${String(t*18)} 24 24)`},t)),(0,Y.jsx)(`circle`,{cx:`24`,cy:`24`,r:`5`})]})}):c})}),vT=(0,q.createContext)(null),yT=(0,q.createContext)(void 0);function bT(e){let t=(0,q.useContext)(yT);return e??t}var xT=(0,q.forwardRef)(function({service:e,src:t,activity:n,expression:r,appearance:i,renderStyle:a,performance:o,timeMs:s,paused:c=!1,onState:l,...u},d){let f=bT(s),p=f!==void 0,m=(0,q.useContext)(vT),h=e??m;if(!h)throw Error(`Sprite needs a configured SpriteProvider or service`);let g=(0,q.useRef)(null),_=(0,q.useRef)(null),v=(0,q.useRef)(l);return v.current=l,(0,q.useImperativeHandle)(d,()=>{if(!g.current)throw Error(`Sprite host is not mounted`);return g.current}),(0,q.useEffect)(()=>{if(!g.current)return;let e=h.mount(g.current),t=e.subscribe(e=>{g.current&&(g.current.dataset.spriteStatus=e.status),v.current?.(e)});return _.current=e,()=>{t(),e.dispose().catch(e=>{console.error(`Sprite cleanup failed`,e)}),_.current=null}},[h]),(0,q.useEffect)(()=>{let e=_.current;if(!e)return;let s={src:t};n!==void 0&&(s={...s,activity:n}),r!==void 0&&(s={...s,expression:r}),i!==void 0&&(s={...s,appearance:i}),a!==void 0&&(s={...s,renderStyle:a}),o!==void 0&&(s={...s,performance:o}),f!==void 0&&(s={...s,timeMs:f}),e.set(s)},[h,t,n,r,i,a,o,f]),(0,q.useEffect)(()=>{_.current?.pause(c||p)},[h,c,p]),(0,Y.jsx)(`div`,{...u,ref:g})});function ST(e){return{src:{local:e.character},appearance:e.appearance,expression:e.expression,renderStyle:e.renderStyle}}function CT(e){for(let[t,n]of Object.entries({maxBytes:e.maxBytes,maxTotalBytes:e.maxTotalBytes,maxRequests:e.maxRequests}))if(!Number.isSafeInteger(n)||n<=0)throw Error(`Avatar ${t} must be a positive safe integer`);let t=new Set(e.allowedOrigins.map(e=>new URL(e).origin)),n=e.fetch??globalThis.fetch;return()=>{let r=0,i=0;return async(a,o,s=e.baseURL)=>{let c=new URL(a,s);if(![`http:`,`https:`].includes(c.protocol)||!t.has(c.origin)||c.username||c.password)throw Error(`Avatar asset is not admitted: ${c.origin}`);if(i+=1,i>e.maxRequests)throw Error(`Avatar asset request limit reached`);let l=await n(c.href,{signal:o,redirect:`error`});if(!l.ok)throw Error(`Avatar asset request failed: ${String(l.status)}`);let u=Number(l.headers.get(`content-length`));if(u>e.maxBytes||u>e.maxTotalBytes-r)throw await l.body?.cancel(),Error(`Avatar asset exceeds the byte limit`);let d=l.body?.getReader();if(!d)throw Error(`Avatar asset has no response body`);let f=[],p=0;try{for(;;){o.throwIfAborted();let t=await d.read();if(t.done)break;if(p+=t.value.byteLength,p>e.maxBytes)throw Error(`Avatar asset exceeds the byte limit`);if(t.value.byteLength>e.maxTotalBytes-r)throw Error(`Avatar selection exceeds the total byte limit`);r+=t.value.byteLength,f.push(t.value)}}catch(e){let t=await d.cancel().then(()=>({kind:`cancelled`}),e=>({kind:`failed`,error:e instanceof Error?e:Error(String(e))}));throw t.kind===`failed`?AggregateError([e,t.error],`Avatar asset read and cancellation failed`,{cause:e}):e}finally{d.releaseLock()}let m=new Uint8Array(p),h=0;for(let e of f)m.set(e,h),h+=e.byteLength;return{url:c.href,bytes:m,contentType:l.headers.get(`content-type`)??`application/octet-stream`}}}}var wT=(e,t)=>{let n=po.safeParse(e);return n.success?{kind:`local`,key:n.data.local}:{kind:`remote`,url:new URL(P().parse(e),t).href}},TT=e=>e instanceof Error?e:Error(String(e),{cause:e}),ET=e=>Mi(e)?TT(uo(e.cause)):Error(`Unexpected Sprite success`);function DT(e){let t=e.maxPixels??4194304;if(!Number.isSafeInteger(t)||t<=0)throw Error(`Sprite pixel limit must be a positive safe integer`);let n=e.assets??{baseURL:`https://sprite.invalid/`,allowedOrigins:[],maxBytes:1,maxTotalBytes:1,maxRequests:1},r=CT(n),i=new WeakSet,a=new WeakMap,o=e=>{let t=wT(e,n.baseURL);return t.kind===`remote`?t.url:`local:${t.key}`};return{mount(s){if(i.has(s))throw Error(`A Sprite already owns this target`);i.add(s);let c=ni(ka()),l=new Set,u={status:`empty`},d,f,p=0,m=!1,h,g,_,v=!1,y=!1,b=s.ownerDocument.defaultView?.matchMedia(`(prefers-reduced-motion: reduce)`),x=e=>{if(!(v&&e.status!==`destroyed`)){u=e;for(let t of l)try{t(e)}catch(e){console.error(`Sprite state observer failed`,e)}}},S=e=>{f?.controller.abort(),f?.holder.remove(),x({status:`error`,error:e}),T().catch(t=>{x({status:`error`,error:AggregateError([e,t],`Avatar failed and cleanup also failed`)})})},C=Zh(s),w=()=>{let e=y||s.ownerDocument.hidden||b?.matches===!0;C.still(e);try{f?.native?.pause(e)}catch(e){S(TT(e))}};ni(qa(c,Ur(()=>{s.ownerDocument.removeEventListener(`visibilitychange`,w),b?.removeEventListener(`change`,w),C.dispose()}))),s.ownerDocument.addEventListener(`visibilitychange`,w),b?.addEventListener(`change`,w);let T=async()=>{if(g)return g;let e=f;if(!e)return;f=void 0,e.controller.abort(),e.holder.remove();let t=Kr(Ra(e.scope,Na)).then(e=>{if(Mi(e))throw ET(e)});g=t;try{await t}finally{g===t&&(g=void 0)}},E=e=>{let t=e.native,n=e.document,r=d;if(!t||!n||!r||f!==e)return;let i=r.activity??`idle`,a=r.expression??t.expressions[0]??null,o,s;try{o=mo(n.controls,r.appearance),s=Th.parse(r.renderStyle??`plain`)}catch(e){let t=TT(e);u.status===`ready`?u.updateError?.message!==t.message&&x({...u,updateError:t}):S(t);return}let c={requestedActivity:i,requestedExpression:a,activity:t.activities.includes(i)?i:`idle`,expression:a!==null&&t.expressions.includes(a)?a:t.expressions[0]??null,appearance:o,renderStyle:s,fallback:!t.activities.includes(i)||a!==null&&!t.expressions.includes(a)},l=r.performance===void 0?c:{...c,performance:r.performance};r.timeMs!==void 0&&(l={...l,timeMs:r.timeMs});let p=JSON.stringify([l.activity,l.expression,l.appearance,l.timeMs]);if(C.set(s,e.holder),p!==e.appliedKey||r.performance!==e.appliedPerformance||u.status!==`ready`||u.presentation.renderStyle!==s||u.updateError!==void 0||u.presentation.requestedActivity!==i||u.presentation.requestedExpression!==a)try{if((p!==e.appliedKey||r.performance!==e.appliedPerformance)&&t.set(l),e.appliedKey=p,e.appliedPerformance=r.performance,w(),f===e){let t={status:`ready`,document:n,presentation:l};x(e.progress===void 0?t:{...t,progress:e.progress})}}catch(e){S(TT(e))}},ee=async(i,a,o)=>{let c=r(),l=ni(ka()),d=new AbortController,m=s.ownerDocument.createElement(`div`);m.style.cssText=`width:100%;height:100%;position:relative`;let h={key:a,scope:l,controller:d,holder:m};f=h,ni(qa(l,Ur(()=>{m.remove()}))),s.append(m);let g=qr(function*(){let r,a,o=n.baseURL,s=wT(i.src,n.baseURL);if(s.kind===`remote`){let t=yield*jr({try:()=>c(s.url,d.signal),catch:TT});o=t.url,r=fo.parse(JSON.parse(new TextDecoder().decode(t.bytes)));let n=e.renderers&&Object.hasOwn(e.renderers,r.renderer)?e.renderers[r.renderer]:void 0;if(!n)throw Error(`Renderer is not installed: ${r.renderer}`);a=(yield*jr({try:n,catch:TT})).default}else{let t=s.key,n=e.characters&&Object.hasOwn(e.characters,t)?e.characters[t]:void 0;if(!n)throw Error(`Character is not installed: ${t}`);let i=yield*jr({try:n,catch:TT});r=fo.parse(i.document),a=i.render}d.signal.throwIfAborted();let l=yield*a({target:m,document:r,signal:d.signal,maxPixels:t,reportError:e=>{f===h&&!d.signal.aborted&&S(e)},reportProgress:e=>{f!==h||d.signal.aborted||(h.progress=e,u.status===`ready`&&x({...u,progress:e}))},assetURL:e=>qr(function*(){let t=yield*jr({try:()=>c(e,d.signal,o),catch:TT});return yield*di(Ur(()=>URL.createObjectURL(new Blob([t.bytes],{type:t.contentType}))),e=>Ur(()=>{URL.revokeObjectURL(e)}))})});if(!l.activities.includes(`idle`))throw Error(`Character has no idle fallback`);return l.pause(!0),{native:l,document:r}}).pipe(no(l)),_=await Kr(g,{signal:d.signal});if(!(v||o!==p||f!==h)){if(Mi(_)){let e=ET(_);try{await T(),x({status:`error`,error:e})}catch(t){x({status:`error`,error:AggregateError([e,t],`Avatar load and cleanup failed`)})}return}h.native=_.value.native,h.document=_.value.document,E(h)}},D=async()=>{let e=e=>v||e!==p;for(;m&&!v;){m=!1;let t=p;if(await T(),e(t)||!d)continue;let n=await a.get(s);if(n?.kind===`failed`)throw n.error;e(t)||(x({status:`loading`}),await ee(d,o(d.src),t))}},O=()=>{m=!0,f?.controller.abort(),f?.holder.remove(),!h&&(h=D().catch(e=>{x({status:`error`,error:TT(e)})}).finally(()=>{h=void 0,m&&!v&&O()}))};return{get state(){return u},subscribe(e){return l.add(e),()=>l.delete(e)},set(e){if(v)throw Error(`Sprite is destroyed`);d=e;let t=o(e.src);f?.key===t&&u.status===`ready`?E(f):(f?.key!==t||u.status===`error`)&&(p+=1,O())},pause(e){if(v)throw Error(`Sprite is destroyed`);y=e,w()},dispose(){return _||(v=!0,p+=1,i.delete(s),f?.controller.abort(),f?.holder.remove(),x({status:`destroyed`}),_=(async()=>{await h,await T();let e=await Kr(Ra(c,Na));if(Mi(e))throw ET(e)})(),a.set(s,_.then(()=>({kind:`closed`}),e=>({kind:`failed`,error:TT(e)}))),_)}}}}}var OT=DT({characters:{mushroom:async()=>(await _o(async()=>{let{default:e}=await import(`./mushroom-Bm99-6Un.js`);return{default:e}},__vite__mapDeps([5,6,2,7,1,8]))).default,cat:async()=>(await _o(async()=>{let{default:e}=await import(`./cat-gQl6DJEL.js`);return{default:e}},__vite__mapDeps([9,6,2,7,1,8,10]))).default,burger:async()=>(await _o(async()=>{let{default:e}=await import(`./burger-BE3Gxp6Y.js`);return{default:e}},__vite__mapDeps([11,6,2,7,1,8,10]))).default}}),kT=(0,q.memo)(function({activity:e=`idle`,avatar:t,className:n,name:r,size:i=24,timeMs:a}){let o=bT(a),[s,c]=(0,q.useState)(!1),l=(0,q.useMemo)(()=>ST(t),[t]);return(0,Y.jsxs)(`span`,{"aria-hidden":`true`,className:`relative inline-block shrink-0 ${n??``}`,"data-agent-head":s?`ready`:`loading`,style:{height:i,width:i},children:[s?null:(0,Y.jsx)(_T,{className:`absolute inset-0`,name:r,seed:r}),(0,Y.jsx)(xT,{activity:e,...o===void 0?{}:{timeMs:o},appearance:l.appearance,className:`absolute inset-0`,expression:l.expression,onState:e=>{c(e.status===`ready`)},paused:o!==void 0||e===`idle`,renderStyle:l.renderStyle,service:OT,src:l.src})]})}),AT=(0,q.memo)(function({avatar:e,className:t=`h-12 w-12 shrink-0`,service:n=OT,state:r}){let i=(0,q.useMemo)(()=>e?ST(e):void 0,[e]);return(0,Y.jsx)(xT,{"aria-hidden":`true`,className:t,service:n,src:i?.src??{local:`mushroom`},...i?{appearance:i.appearance,renderStyle:i.renderStyle}:{},...r})}),jT={needs_you:`Waiting for you`,running:`Working`,errored:`Failed`,done:`Done`},MT={needs_you:0,errored_unseen:1,running:2,recent:3};function NT(e){return e===`running`||e===`needs_you`}function PT(e,t){return e!==void 0&&(t===void 0||e>t)}function FT(e,t){switch(e){case`needs_you`:return`needs_you`;case`running`:return`running`;case`errored`:return t?`errored_unseen`:`recent`;case`done`:return`recent`}}function IT(e,t){return MT[e.tier]-MT[t.tier]||(t.settledAt??t.createdAt)-(e.settledAt??e.createdAt)||e.agentId.localeCompare(t.agentId)||e.sessionId.localeCompare(t.sessionId)}var LT=[`Needs you`,`Working`,`Ready`,`Finished`];function RT(e){return e.tier===`running`?`Working`:e.shelf===`active`?`Needs you`:e.ready?`Ready`:`Finished`}function zT(e){return{key:GT(e.agentId,e.sessionId),shelf:RT(e),attention:e.tier===`needs_you`||e.tier===`errored_unseen`?`${e.tier}:${String(e.settledAt??e.createdAt)}`:null}}function BT(e,t,n){let r=new Map(t.map(e=>[GT(e.agentId,e.sessionId),e]));if(e!==null&&e.length>0&&n.held)return e;let i=[...t].sort((e,t)=>(t.settledAt??t.createdAt)-(e.settledAt??e.createdAt)||e.agentId.localeCompare(t.agentId)||e.sessionId.localeCompare(t.sessionId)),a=new Map(e?.map(e=>[e.key,e])),o=i.map(zT).filter(e=>{let t=a.get(e.key);return t===void 0||e.key!==n.openKey&&e.attention!==null&&e.attention!==t.attention}),s=new Set(o.map(e=>e.key)),c=a.get(n.openKey??``),l=c===void 0?-1:(e??[]).filter(e=>e.shelf===c.shelf).findIndex(e=>e.key===c.key),u=LT.flatMap(t=>{let a;a=e===null||n.reorder?i.map(zT).filter(e=>e.shelf===t):[...o.filter(e=>e.shelf===t),...e.filter(e=>e.shelf===t&&!s.has(e.key)).flatMap(e=>{let t=r.get(e.key);return t===void 0?[]:[{...e,attention:zT(t).attention}]})];let u=c===void 0?void 0:r.get(c.key);return c!==void 0&&u!==void 0&&(a=a.filter(e=>e.key!==c.key),c.shelf===t&&a.splice(Math.min(l,a.length),0,{...c,attention:zT(u).attention})),a});return e!==null&&u.length===e.length&&u.every((t,n)=>t.key===e[n]?.key&&t.shelf===e[n]?.shelf&&t.attention===e[n]?.attention)?e:u}function VT(e){switch(e.kind){case`idle`:return`done`;case`waiting_for_you`:return`needs_you`;case`error`:return`errored`;default:return`running`}}function HT(e,t,n=null,r){let i=new Set(e.map(e=>e.agentId));return UT(t.filter(e=>!(`kind`in e)&&i.has(e.agentId)&&(n===null||e.agentId===n)),r)}function UT(e,t){let n=[],r=[];for(let i of e){if(`kind`in i)continue;if(i.state===`unavailable`){r.push({agentId:i.agentId,sessionId:i.sessionId});continue}let e=PT(i.settledAt,i.visitedAt),a=t?.agentId===i.agentId&&t.sessionId===i.sessionId?t.state:void 0,o=a?VT(a):i.state,s=a?a.kind===`idle`:o===`done`&&i.settledAt===void 0,c=FT(o,e);n.push({...i,state:o,ready:s,unseen:e,tier:c,shelf:c===`recent`?`settled`:`active`})}return n.sort(IT),{active:n.filter(e=>e.shelf===`active`),settled:n.filter(e=>e.shelf===`settled`),unavailable:r.sort((e,t)=>e.agentId.localeCompare(t.agentId)||e.sessionId.localeCompare(t.sessionId))}}function WT(e){return[...e.active,...e.settled].filter(e=>!(e.title===``&&e.ready))}function GT(e,t){return`${e}\u0000${t}`}function KT(e){return e.name}function qT({children:e}){return(0,Y.jsx)(`span`,{className:`grove-rail-mark grid size-full place-items-center`,children:e})}function JT({open:e,agents:t,agentActivity:n,agentFilterId:r,websitesSelected:i,websitesVisible:a,canCreate:o,createOpen:s,onAll:c,onWebsites:l,onAgent:u,onCreate:d}){let[f,p]=(0,q.useState)(null),m=`grove-rail-cell relative size-12 rounded-field p-0`,h=r===null&&!(i&&a);return(0,Y.jsxs)(`nav`,{id:`grove-agent-rail`,"aria-label":`Agents`,className:`grove-rail min-h-0 w-16 flex-none flex-col items-center gap-1 border-r border-base-300 py-2 ${e?`flex`:`flex min-[900px]:hidden`}`,children:[(0,Y.jsx)(Zt,{variant:`ghost`,"aria-label":`All Agents`,"aria-pressed":h,className:`${m} text-xs ${h?`bg-base-300`:``}`,onClick:c,children:(0,Y.jsx)(qT,{children:`All`})}),a?(0,Y.jsx)(Zt,{variant:`ghost`,"aria-label":`Websites`,"aria-pressed":i,className:`${m} ${i?`bg-base-300`:``}`,onClick:l,children:(0,Y.jsx)(qT,{children:(0,Y.jsx)(Cn,{name:`internet`,size:28})})}):null,(0,Y.jsx)(dx,{className:`w-full flex-1`,style:{width:`100%`},children:(0,Y.jsx)(`div`,{className:`flex flex-col items-center gap-1 py-1`,children:t.map(e=>(0,Y.jsx)(Zt,{variant:`ghost`,"aria-label":KT(e),title:KT(e),"aria-pressed":r===e.agentId&&!i,"data-agent-id":e.agentId,className:`${m} ${r===e.agentId&&!i?`bg-base-300`:``}`,onPointerEnter:()=>{p(e.agentId)},onPointerLeave:()=>{p(null)},onFocus:()=>{p(e.agentId)},onBlur:()=>{p(null)},onClick:()=>{u(e.agentId)},children:(0,Y.jsx)(qT,{children:(0,Y.jsx)(kT,{activity:n.get(e.agentId)??(f===e.agentId?`thinking`:`idle`),avatar:e.avatar,name:KT(e),size:32})})},e.agentId))})}),o?(0,Y.jsx)(Zt,{variant:`ghost`,"aria-label":`New Agent`,"aria-expanded":s,"aria-haspopup":`dialog`,className:`${m} mt-auto`,onClick:d,children:(0,Y.jsx)(`span`,{className:`grove-rail-mark grid size-full place-items-center`,children:(0,Y.jsx)(Oe,{size:20})})}):null]})}function YT({app:e}){let[t,n]=(0,q.useState)(null),r=qo({queryKey:Iy.of(e,`team-inbox-notices`,t),enabled:e!==null&&(e.capabilities.has(Ag)||e.capabilities.has(jg)),queryFn:async()=>{if(!e)throw Error(`No App connection`);let n=await Rg(e.capabilities);try{return await Ay(n,t)}finally{await n.close()}}});return!r.isError&&!r.data?.items.length?null:(0,Y.jsx)(`section`,{"aria-label":`Team notices`,className:`min-h-0 shrink-0`,children:(0,Y.jsxs)(dx,{className:`max-h-52 border-b border-base-300`,children:[r.isError?(0,Y.jsx)(`p`,{role:`alert`,className:`text-sm`,children:`Team notices unavailable.`}):(0,Y.jsx)(Rt,{density:`compact`,className:`px-3 py-2`,children:r.data.items.map(e=>(0,Y.jsx)(_e,{children:(0,Y.jsxs)(`div`,{className:`grid min-w-0 grid-cols-[auto_minmax(0,1fr)] gap-x-[var(--spacing-xs)]`,children:[(0,Y.jsx)(fe,{className:`col-span-2 grid grid-cols-subgrid`,size:`compact`,tone:`warning`,label:`kind`in e?`Seller closed`:`Installed App safety notice`}),(0,Y.jsx)(`p`,{className:`m-0 col-start-2 text-sm [overflow-wrap:anywhere]`,children:`kind`in e?`${e.sellerName} closed. Your installation of ${e.displayName} continues; no new purchases are available.`:`${e.displayName} was removed. Fungi will disable it on your Team.`})]})},e.dispositionId))}),r.data?.next?(0,Y.jsx)(Zt,{variant:`ghost`,size:`sm`,onClick:()=>{n(r.data.next)},children:`Older notices`}):null,t===null?null:(0,Y.jsx)(Zt,{variant:`ghost`,size:`sm`,onClick:()=>{n(null)},children:`Newest notices`})]})})}var XT=`(min-width: 900px)`;function ZT(e){let t=globalThis.matchMedia(XT);return t.addEventListener(`change`,e),()=>{t.removeEventListener(`change`,e)}}function QT(){return globalThis.matchMedia(XT).matches}function $T(){return(0,q.useSyncExternalStore)(ZT,QT,()=>!0)}function eE({open:e,onOpenChange:t,returnFocus:n,children:r}){let i=$T(),[a,o]=(0,q.useState)(null);return(0,Y.jsxs)(b,{open:i||e,modal:!i,disablePointerDismissal:i,onOpenChange:e=>{i||t(e)},children:[(0,Y.jsx)(`div`,{ref:o,className:`contents`}),(0,Y.jsxs)(ye,{container:a,keepMounted:!0,className:`contents`,children:[i?null:(0,Y.jsx)(v,{className:`grove-nav-scrim z-30 bg-base-200`}),(0,Y.jsx)(ge,{id:`grove-nav`,role:i?`presentation`:`dialog`,"aria-label":i?void 0:`Agents and conversations`,initialFocus:!i&&void 0,finalFocus:!i&&n,className:`grove-nav min-h-0 flex-none rounded-none p-0 overflow-visible max-w-none max-h-none ${i?`static flex w-auto shadow-none`:`fixed inset-y-0 left-0 z-40 w-[min(22rem,88vw)] data-[open]:flex`}`,children:r})]})]})}function tE({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0){n=e.nextSub;continue}for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}while(!0)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(!0)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function nE(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}var rE=[],iE=0,{link:aE,unlink:oE,propagate:sE,checkDirty:cE,shallowPropagate:lE}=tE({update(e){return e._update()},notify(e){rE[dE++]=e,e.flags&=-3},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=17,hE(e))}}),uE=0,dE=0,fE,pE=0;function mE(e){try{++pE,e()}finally{--pE||gE()}}function hE(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=oE(n,e)}function gE(){if(!(pE>0)){for(;uE<dE;){let e=rE[uE];rE[uE++]=void 0,e.notify()}uE=0,dE=0}}function _E(e,t){let n=typeof e==`function`,r=e,i={_snapshot:n?void 0:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:+!n,get(){return fE!==void 0&&aE(i,fE,iE),i._snapshot},subscribe(e){let t=nE(e),n={current:!1},r=vE(()=>{i.get(),n.current?t.next?.(i._snapshot):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=fE,o=t?.compare??Object.is;if(n)fE=i,++iE,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=5);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{fE=a,n&&(i.flags&=-5),hE(i)}}};return n?(i.flags=17,i.get=function(){let e=i.flags;if(e&16||e&32&&cE(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&lE(e)}}else e&32&&(i.flags=e&-33);return fE!==void 0&&aE(i,fE,iE),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(sE(e),lE(e),gE())}},i}function vE(e){let t=()=>{let t=fE;fE=n,++iE,n.depsTail=void 0,n.flags=6;try{return e()}finally{fE=t,n.flags&=-5,hE(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:6,notify(){let e=this.flags;e&16||e&32&&cE(this.deps,this)?t():this.flags=2},stop(){this.flags=0,this.depsTail=void 0,hE(this)}};return t(),n}var yE=class{constructor(e,t){this.atom=_E(e),this.get=this.get.bind(this),this.setState=this.setState.bind(this),this.subscribe=this.subscribe.bind(this),t&&(this.actions=t(this))}setState(e){this.atom.set(e)}get state(){return this.atom.get()}get(){return this.state}subscribe(e){return this.atom.subscribe(nE(e))}},bE=class{constructor(e){this.atom=_E(e)}get state(){return this.atom.get()}get(){return this.state}subscribe(e){return this.atom.subscribe(nE(e))}};function xE(e,t){return typeof e==`function`?new bE(e):t?new yE(e,t):new yE(e)}var SE=class{constructor(e,t){this.fn=e,this.options=t,this.lastExecutionTime=0,this.isPending=!1,this.maybeExecute=(...e)=>{let t=Date.now()-this.lastExecutionTime;if(this.options.leading&&t>=this.options.wait)this.execute(...e);else if(this.lastArgs=e,!this.timeoutId&&this.options.trailing){let e=this.options.wait-t;this.isPending=!0,this.timeoutId=setTimeout(()=>{this.lastArgs!==void 0&&this.execute(...this.lastArgs)},e)}},this.execute=(...e)=>{this.fn(...e),this.options.onExecute?.(e,this),this.lastExecutionTime=Date.now(),this.clearTimeout(),this.lastArgs=void 0,this.isPending=!1},this.flush=()=>{this.isPending&&this.lastArgs&&this.execute(...this.lastArgs)},this.cancel=()=>{this.clearTimeout(),this.lastArgs=void 0,this.isPending=!1},this.clearTimeout=()=>{this.timeoutId&&=(clearTimeout(this.timeoutId),void 0)},this.options.leading===void 0&&this.options.trailing===void 0&&(this.options.leading=!0,this.options.trailing=!0)}};function CE(e,t){return new SE(e,t).maybeExecute}var wE=class{#e=!0;#t;#n;#r;#i;#a;#o;#s;#c=0;#l=5;#u=!1;#d=!1;#f=null;#p=()=>{this.debugLog(`Connected to event bus`),this.#a=!0,this.#u=!1,this.debugLog(`Emitting queued events`,this.#i),this.#i.forEach(e=>this.emitEventToBus(e)),this.#i=[],this.stopConnectLoop(),this.#n().removeEventListener(`tanstack-connect-success`,this.#p)};#m=()=>{if(this.#c<this.#l){this.#c++,this.dispatchCustomEvent(`tanstack-connect`,{});return}this.#n().removeEventListener(`tanstack-connect`,this.#m),this.#d=!0,this.debugLog(`Max retries reached, giving up on connection`),this.stopConnectLoop()};#h=()=>{this.#u||(this.#u=!0,this.#n().addEventListener(`tanstack-connect-success`,this.#p),this.#m())};constructor({pluginId:e,debug:t=!1,enabled:n=!0,reconnectEveryMs:r=300}){this.#t=e,this.#e=n,this.#n=this.getGlobalTarget,this.#r=t,this.debugLog(` Initializing event subscription for plugin`,this.#t),this.#i=[],this.#a=!1,this.#d=!1,this.#o=null,this.#s=r}startConnectLoop(){this.#o!==null||this.#a||(this.debugLog(`Starting connect loop (every ${this.#s}ms)`),this.#o=setInterval(this.#m,this.#s))}stopConnectLoop(){this.#u=!1,this.#o!==null&&(clearInterval(this.#o),this.#o=null,this.#i=[],this.debugLog(`Stopped connect loop`))}debugLog(...e){this.#r&&console.log(`🌴 [tanstack-devtools:${this.#t}-plugin]`,...e)}getGlobalTarget(){if(typeof globalThis<`u`&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog(`Using global event target`),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<`u`&&window.addEventListener!==void 0)return this.debugLog(`Using window as event target`),window;let e=typeof EventTarget<`u`?new EventTarget:void 0;return e===void 0||e.addEventListener===void 0?(this.debugLog(`No event mechanism available, running in non-web environment`),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>!1}):(this.debugLog(`Using new EventTarget as fallback`),e)}getPluginId(){return this.#t}dispatchCustomEventShim(e,t){try{let n=new Event(e,{detail:t});this.#n().dispatchEvent(n)}catch{this.debugLog(`Failed to dispatch shim event`)}}dispatchCustomEvent(e,t){try{this.#n().dispatchEvent(new CustomEvent(e,{detail:t}))}catch{this.dispatchCustomEventShim(e,t)}}emitEventToBus(e){this.debugLog(`Emitting event to client bus`,e),this.dispatchCustomEvent(`tanstack-dispatch-event`,e)}createEventPayload(e,t){return{type:`${this.#t}:${e}`,payload:t,pluginId:this.#t}}emit(e,t){if(!this.#e){this.debugLog(`Event bus client is disabled, not emitting event`,e,t);return}if(this.#f&&(this.debugLog(`Emitting event to internal event target`,e,t),this.#f.dispatchEvent(new CustomEvent(`${this.#t}:${e}`,{detail:this.createEventPayload(e,t)}))),this.#d){this.debugLog(`Previously failed to connect, not emitting to bus`);return}if(!this.#a){this.debugLog(`Bus not available, will be pushed as soon as connected`),this.#i.push(this.createEventPayload(e,t)),typeof CustomEvent<`u`&&!this.#u&&(this.#h(),this.startConnectLoop());return}return this.emitEventToBus(this.createEventPayload(e,t))}on(e,t,n){let r=n?.withEventTarget??!1,i=`${this.#t}:${e}`;if(r&&(this.#f||=new EventTarget,this.#f.addEventListener(i,e=>{t(e.detail)})),!this.#e)return this.debugLog(`Event bus client is disabled, not registering event`,i),()=>{};let a=e=>{this.debugLog(`Received event from bus`,e.detail),t(e.detail)};return this.#n().addEventListener(i,a),this.debugLog(`Registered event to bus`,i),()=>{r&&this.#f?.removeEventListener(i,a),this.#n().removeEventListener(i,a)}}onAll(e){if(!this.#e)return this.debugLog(`Event bus client is disabled, not registering event`),()=>{};let t=t=>{let n=t.detail;e(n)};return this.#n().addEventListener(`tanstack-devtools-global`,t),()=>this.#n().removeEventListener(`tanstack-devtools-global`,t)}onAllPluginEvents(e){if(!this.#e)return this.debugLog(`Event bus client is disabled, not registering event`),()=>{};let t=t=>{let n=t.detail;this.#t&&n.pluginId!==this.#t||e(n)};return this.#n().addEventListener(`tanstack-devtools-global`,t),()=>this.#n().removeEventListener(`tanstack-devtools-global`,t)}},TE=new class extends wE{constructor(){super({pluginId:`form-devtools`,reconnectEveryMs:1e3})}};function EE(e,t){return typeof e==`function`?e(t):e}function DE(e,t){return FE(t).reduce((e,t)=>{if(e===null)return null;if(e!==void 0)return e[t]},e)}function OE(e,t,n){let r=FE(t);function i(e){if(!r.length)return EE(n,e);let t=r.shift();if(typeof t==`string`||typeof t==`number`&&!Array.isArray(e))return typeof e==`object`?(e===null&&(e={}),{...e,[t]:i(e[t])}):{[t]:i()};if(Array.isArray(e)&&typeof t==`number`){let n=e.slice(0,t);return[...n.length?n:Array(t),i(e[t]),...e.slice(t+1)]}return[...Array(t),i()]}return i(e)}function kE(e,t){let n=FE(t);function r(e){if(!e)return;if(n.length===1){let t=n[0];if(Array.isArray(e)&&typeof t==`number`)return e.filter((e,n)=>n!==t);let{[t]:r,...i}=e;return i}let t=n.shift();if((typeof t==`string`||typeof t==`number`&&!Array.isArray(e))&&typeof e==`object`)return{...e,[t]:r(e[t])};if(typeof t==`number`&&Array.isArray(e)){if(t>=e.length)return e;let n=e.slice(0,t);return[...n.length?n:Array(t),r(e[t]),...e.slice(t+1)]}throw Error(`It seems we have created an infinite loop in deleteBy. `)}return r(e)}var AE=46,jE=91,ME=93,NE=48,PE=57;function FE(e){if(Array.isArray(e))return[...e];if(typeof e!=`string`)throw Error(`Path must be a string.`);let t=e.length,n=[],r=+(t>0&&e.charCodeAt(0)===jE),i=!0,a=-1;for(let o=r;o<=t;o++){let s=o<t?e.charCodeAt(o):-1;if(o===t||s===AE||s===jE||s===ME){let t=o-r;if(t>0){let a=i&&(t===1||e.charCodeAt(r)!==NE),s=e.slice(r,o);if(a){let e=parseInt(s,10);t<=15||String(e)===s?n.push(e):n.push(s)}else n.push(s)}else a!==ME&&(a!==-1||s!==ME)&&(a!==s||s!==AE&&s!==jE)&&n.push(``);r=o+1,i=!0}else(s<NE||s>PE)&&(i=!1);a=s}return n.length||n.push(``),n}function IE(e){return!(Array.isArray(e)&&e.length===0)}function LE(e,t){return t.validationLogic({form:t.form,group:t.group,validators:t.validators,event:{type:e,fieldName:t.fieldName,async:!1},runValidation:e=>e.validators.filter(Boolean).map(e=>({cause:e.cause,validate:e.fn}))})}function RE(e,t){let{asyncDebounceMs:n}=t,{onBlurAsyncDebounceMs:r,onChangeAsyncDebounceMs:i,onDynamicAsyncDebounceMs:a}=t.validators||{},o=n??0;return t.validationLogic({form:t.form,group:t.group,validators:t.validators,event:{type:e,fieldName:t.fieldName,async:!0},runValidation:t=>t.validators.filter(Boolean).map(t=>{let n=t?.cause||e,s=o;switch(n){case`change`:s=i??o;break;case`blur`:s=r??o;break;case`dynamic`:s=a??o;break;case`submit`:s=0}return e===`submit`&&(s=0),{cause:n,validate:t.fn,debounceMs:s}})})}var zE=e=>!!e&&typeof e==`object`&&`fields`in e;function BE(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!t.has(n)||!Object.is(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length||n.length===0&&!Array.isArray(e)&&!Array.isArray(t)&&(Object.getPrototypeOf(e)!==Object.prototype||Object.getPrototypeOf(t)!==Object.prototype))return!1;for(let i of n)if(!r.includes(i)||!BE(e[i],t[i]))return!1;return!0}var VE=({newFormValidatorError:e,isPreviousErrorFromFormValidator:t,previousErrorValue:n})=>e?{newErrorValue:e,newSource:`form`}:t?{newErrorValue:void 0,newSource:void 0}:n?{newErrorValue:n,newSource:`field`}:{newErrorValue:void 0,newSource:void 0},HE=({formLevelError:e,fieldLevelError:t})=>t?{newErrorValue:t,newSource:`field`}:e?{newErrorValue:e,newSource:`form`}:{newErrorValue:void 0,newSource:void 0};function UE(e,t){return e==null?t:{...e,...t}}for(var WE=256,GE=[],KE;WE--;)GE[WE]=(WE+256).toString(16).substring(1);function qE(){let e=0,t,n=``;if(!KE||WE+16>256){for(KE=Array(256),e=256;e--;)KE[e]=256*Math.random()|0;e=0,WE=0}for(;e<16;e++)t=KE[WE+e],n+=e===6?GE[t&15|64]:e===8?GE[t&63|128]:GE[t],e&1&&e>1&&e<11&&(n+=`-`);return WE++,n}var JE=CE(e=>TE.emit(`form-state`,{id:e.formId,state:e.store.state}),{wait:300});function YE(e){if(typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e)){let t=[];for(let n=0;n<e.length;n++)t[n]=YE(e[n]);return t}if(e instanceof Map){let t=new Map;return e.forEach((e,n)=>{t.set(n,YE(e))}),t}if(e instanceof Set){let t=new Set;return e.forEach(e=>{t.add(YE(e))}),t}let t={};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=YE(e[n]));return t}function XE(e,t){return t===e||t.startsWith(`${e}.`)||t.startsWith(`${e}[`)}var ZE=e=>{if(!e.validators)return e.runValidation({validators:[],form:e.form});let t=e.event.async,n=t?void 0:{fn:e.validators.onMount,cause:`mount`},r={fn:t?e.validators.onChangeAsync:e.validators.onChange,cause:`change`},i={fn:t?e.validators.onBlurAsync:e.validators.onBlur,cause:`blur`},a={fn:t?e.validators.onSubmitAsync:e.validators.onSubmit,cause:`submit`},o=t?void 0:{fn:()=>void 0,cause:`server`};switch(e.event.type){case`mount`:return e.runValidation({validators:[n],form:e.form});case`submit`:return e.runValidation({validators:[r,i,a,o],form:e.form});case`server`:return e.runValidation({validators:[],form:e.form});case`blur`:return e.runValidation({validators:[i,o],form:e.form});case`change`:return e.runValidation({validators:[r,o],form:e.form});default:throw Error(`Unknown validation event type: ${e.event.type}`)}};function QE(e,t){let n=new Map;for(let r of e){let e=r.path??[],i=t,a=``;for(let t=0;t<e.length;t++){let n=e[t];if(n===void 0)continue;let r=typeof n==`object`?n.key:n,o=Number(r);a+=Array.isArray(i)&&!Number.isNaN(o)?`[${o}]`:(t>0?`.`:``)+String(r),i=typeof i==`object`&&i?i[r]:void 0}n.set(a,(n.get(a)??[]).concat(r))}return Object.fromEntries(n)}var $E=(e,t)=>{let n=QE(e,t);return{form:n,fields:n}},eD={validate({value:e,validationSource:t},n){let r=n[`~standard`].validate(e);if(r instanceof Promise)throw Error(`async function passed to sync validator`);if(r.issues)return t===`field`?r.issues:$E(r.issues,e)},async validateAsync({value:e,validationSource:t},n){let r=await n[`~standard`].validate(e);if(r.issues)return t===`field`?r.issues:$E(r.issues,e)}},tD=e=>!!e&&`~standard`in e,nD={isValidating:!1,isTouched:!1,isBlurred:!1,isDirty:!1,isPristine:!0,isValid:!0,isDefaultValue:!0,errors:[],errorMap:{},errorSourceMap:{},_arrayVersion:0,_pendingValidationsCount:0};function rD(e){function t(t){let n=e.getFieldMeta(t)??nD;e.setFieldMeta(t,{...n,_arrayVersion:(n._arrayVersion||0)+1})}function n(n,r,i){t(n);let a=s(n,r,`move`,i),c=Math.min(r,i),u=Math.max(r,i);for(let e=c;e<=u;e++)a.push(o(n,e));let d=Object.keys(e.fieldInfo).reduce((t,i)=>(i.startsWith(o(n,r))&&t.set(i,e.getFieldMeta(i)),t),new Map);l(a,r<i?`up`:`down`),Object.keys(e.fieldInfo).filter(e=>e.startsWith(o(n,i))).forEach(t=>{let a=t.replace(o(n,i),o(n,r)),s=d.get(a);s&&e.setFieldMeta(t,s)})}function r(e,n){t(e),l(s(e,n,`remove`),`up`)}function i(n,r,i){t(n),s(n,r,`swap`,i).forEach(t=>{if(!t.toString().startsWith(o(n,r)))return;let a=t.toString().replace(o(n,r),o(n,i)),[s,c]=[e.getFieldMeta(t),e.getFieldMeta(a)];s&&e.setFieldMeta(a,s),c&&e.setFieldMeta(t,c)})}function a(n,r){t(n);let i=s(n,r,`insert`);l(i,`down`),i.forEach(t=>{t.toString().startsWith(o(n,r))&&e.setFieldMeta(t,u())})}function o(e,t){return`${e}[${t}]`}function s(t,n,r,i){let a=[o(t,n)];switch(r){case`swap`:a.push(o(t,i));break;case`move`:{let[e,r]=[Math.min(n,i),Math.max(n,i)];for(let n=e;n<=r;n++)a.push(o(t,n));break}default:{let r=e.getFieldValue(t),i=Array.isArray(r)?r.length:0;for(let e=n+1;e<i;e++)a.push(o(t,e));break}}return Object.keys(e.fieldInfo).filter(e=>a.some(t=>e.startsWith(t)))}function c(e,t){return e.replace(/\[(\d+)\]/,(e,n)=>{let r=parseInt(n,10);return`[${t===`up`?r+1:Math.max(0,r-1)}]`})}function l(t,n){(n===`up`?t:[...t].reverse()).forEach(t=>{let r=c(t.toString(),n),i=e.getFieldMeta(r);i?e.setFieldMeta(t,i):e.setFieldMeta(t,u())})}let u=()=>nD;return{bumpArrayVersion:t,handleArrayMove:n,handleArrayRemove:r,handleArraySwap:i,handleArrayInsert:a}}function iD(e){return{values:e.values??{},errorMap:e.errorMap??{},fieldMetaBase:e.fieldMetaBase??{},formGroupStateBase:e.formGroupStateBase??{},isSubmitted:e.isSubmitted??!1,isSubmitting:e.isSubmitting??!1,isValidating:e.isValidating??!1,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??!1,validationMetaMap:e.validationMetaMap??{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}}}var aD=class{constructor(e){this.options={},this.fieldInfo={},this.formGroupApis=new Set,this.mount=()=>{let e=this.store.subscribe(()=>{JE(this)}),t=TE.on(`request-form-state`,e=>{e.payload.id===this._formId&&TE.emit(`form-api`,{id:this._formId,state:this.store.state,options:this.options})}),n=TE.on(`request-form-reset`,e=>{e.payload.id===this._formId&&this.reset()}),r=TE.on(`request-form-force-submit`,e=>{e.payload.id===this._formId&&(this._devtoolsSubmissionOverride=!0,this.handleSubmit(),this._devtoolsSubmissionOverride=!1)}),i=()=>{r(),n(),t(),e.unsubscribe(),TE.emit(`form-unmounted`,{id:this._formId})};this.options.listeners?.onMount?.({formApi:this});let{onMount:a}=this.options.validators||{};return TE.emit(`form-api`,{id:this._formId,state:this.store.state,options:this.options}),a&&this.validateSync(`mount`),i},this.update=e=>{if(!e)return;let t=this.options;this.options=e;let n=e.defaultValues&&!BE(e.defaultValues,t.defaultValues)&&!this.state.isTouched,r=!BE(e.defaultState,t.defaultState)&&!this.state.isTouched;if(!(!n&&!r)){if(mE(()=>{this.baseStore.setState(()=>iD(Object.assign({},this.state,r?e.defaultState:{},n?{values:e.defaultValues}:{})))}),n){let e=rD(this);for(let t of Object.keys(this.fieldInfo))Array.isArray(this.getFieldValue(t))&&e.bumpArrayVersion(t)}TE.emit(`form-api`,{id:this._formId,state:this.store.state,options:this.options})}},this.reset=(e,t)=>{let{fieldMeta:n}=this.state,r=this.resetFieldMeta(n);e&&!t?.keepDefaultValues&&(this.options={...this.options,defaultValues:e}),this.baseStore.setState(()=>{let t=e??this.options.defaultValues??this.options.defaultState?.values;return e||Object.values(this.fieldInfo).forEach(e=>{e.instance&&e.instance.options.defaultValue!==void 0&&(t=OE(t,e.instance.name,e.instance.options.defaultValue))}),iD({...this.options.defaultState,values:t,fieldMetaBase:r})})},this.validateAllFields=async e=>{let t=[];return mE(()=>{Object.values(this.fieldInfo).forEach(n=>{if(!n.instance)return;let r=n.instance;t.push(Promise.resolve().then(()=>r.validate(e,{skipFormValidation:!0,skipGroupValidation:!0}))),n.instance.store.state.meta.isTouched||n.instance.setMeta(e=>({...e,isTouched:!0}))})}),(await Promise.all(t)).flat()},this.validateArrayFieldsStartingFrom=async(e,t,n)=>{let r=this.getFieldValue(e),i=Array.isArray(r)?Math.max(r.length-1,0):null,a=[`${e}[${t}]`];for(let n=t+1;n<=(i??0);n++)a.push(`${e}[${n}]`);let o=Object.keys(this.fieldInfo).filter(e=>a.some(t=>e.startsWith(t))),s=[];return mE(()=>{o.forEach(e=>{s.push(Promise.resolve().then(()=>this.validateField(e,n)))})}),(await Promise.all(s)).flat()},this.validateField=(e,t)=>{let n=this.fieldInfo[e]?.instance;if(!n){let{hasErrored:n}=this.validateSync(t);return n&&!this.options.asyncAlways?this.getFieldMeta(e)?.errors??[]:this.validateAsync(t).then(()=>this.getFieldMeta(e)?.errors??[])}return n.store.state.meta.isTouched||n.setMeta(e=>({...e,isTouched:!0})),n.validate(t)},this.validateSync=(e,t)=>{let n=LE(e,{...this.options,form:this,group:t?.group,validationLogic:this.options.validationLogic||ZE}),r=!1,i={};return mE(()=>{for(let e of n){if(!e.validate)continue;let{formError:n,fieldErrors:a}=oD(this.runValidator({validate:e.validate,value:{value:this.state.values,formApi:this,validationSource:`form`},type:`validate`})),o=sD(e.cause),s=new Set([...Object.keys(this.state.fieldMeta),...Object.keys(a||{})]);t?.filterFieldNames&&(s=new Set([...s].filter(t.filterFieldNames)));for(let e of s){if(this.baseStore.state.fieldMetaBase[e]===void 0&&!a?.[e])continue;let{errorMap:t,errorSourceMap:n}=this.getFieldMeta(e)??nD,r=a?.[e],{newErrorValue:s,newSource:c}=VE({newFormValidatorError:r,isPreviousErrorFromFormValidator:n?.[o]===`form`,previousErrorValue:t?.[o]});c===`form`&&(i[e]={...i[e],[o]:r}),t?.[o]!==s&&this.setFieldMeta(e,(e=nD)=>({...e,errorMap:{...e.errorMap,[o]:s},errorSourceMap:{...e.errorSourceMap,[o]:c}}))}t?.dontUpdateFormErrorMap||this.state.errorMap?.[o]!==n&&this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[o]:n}})),(n||a)&&(r=!0)}if(t?.dontUpdateFormErrorMap)return;let a=sD(`submit`);this.state.errorMap?.[a]&&e!==`submit`&&!r&&this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[a]:void 0}}));let o=sD(`server`);this.state.errorMap?.[o]&&e!==`server`&&!r&&this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[o]:void 0}}))}),{hasErrored:r,fieldsErrorMap:i}},this.validateAsync=async(e,t)=>{let n=RE(e,{...this.options,form:this,group:t?.group,validationLogic:this.options.validationLogic||ZE});this.state.isFormValidating||this.baseStore.setState(e=>({...e,isFormValidating:!0}));let r=[],i;for(let e of n){if(!e.validate)continue;let n=sD(e.cause);this.state.validationMetaMap[n]?.lastAbortController.abort();let a=new AbortController;this.state.validationMetaMap[n]={lastAbortController:a},r.push(new Promise(async n=>{let r;try{r=await new Promise((t,n)=>{setTimeout(async()=>{if(a.signal.aborted)return t(void 0);try{t(await this.runValidator({validate:e.validate,value:{value:this.state.values,formApi:this,validationSource:`form`,signal:a.signal},type:`validateAsync`}))}catch(e){n(e)}},e.debounceMs)})}catch(e){r=e}let{formError:o,fieldErrors:s}=oD(r);s&&(i=i?{...i,...s}:s);let c=sD(e.cause),l=new Set([...Object.keys(this.state.fieldMeta),...Object.keys(i||{})]),u=Array.from(l);t?.filterFieldNames&&(u=u.filter(t.filterFieldNames));for(let e of u){if(this.baseStore.state.fieldMetaBase[e]===void 0&&!i?.[e])continue;let{errorMap:t,errorSourceMap:n}=this.getFieldMeta(e)??nD,r=i?.[e],{newErrorValue:a,newSource:o}=VE({newFormValidatorError:r,isPreviousErrorFromFormValidator:n?.[c]===`form`,previousErrorValue:t?.[c]});t?.[c]!==a&&this.setFieldMeta(e,(e=nD)=>({...e,errorMap:{...e.errorMap,[c]:a},errorSourceMap:{...e.errorSourceMap,[c]:o}}))}t?.dontUpdateFormErrorMap||this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[c]:o}})),n(i?{fieldErrors:i,errorMapKey:c}:void 0)}))}let a=[],o={};if(r.length){a=await Promise.all(r);for(let e of a)if(e?.fieldErrors){let{errorMapKey:t}=e;for(let[n,r]of Object.entries(e.fieldErrors))o[n]={...o[n]||{},[t]:r}}}return this.baseStore.setState(e=>({...e,isFormValidating:!1})),o},this.validate=(e,t)=>{let{hasErrored:n,fieldsErrorMap:r}=this.validateSync(e,t);return n&&!this.options.asyncAlways?r:this.validateAsync(e,t)},this._handleSubmit=async e=>{this.baseStore.setState(e=>({...e,isSubmitted:!1,submissionAttempts:e.submissionAttempts+1,isSubmitSuccessful:!1})),mE(()=>{Object.values(this.fieldInfo).forEach(e=>{e.instance&&(e.instance.store.state.meta.isTouched||e.instance.setMeta(e=>({...e,isTouched:!0})))})});let t=e??this.options.onSubmitMeta;if(!this.state.canSubmit&&!this._devtoolsSubmissionOverride&&this.baseStore.state.submissionAttempts<=1){this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t});return}this.baseStore.setState(e=>({...e,isSubmitting:!0}));let n=()=>{this.baseStore.setState(e=>({...e,isSubmitting:!1}))};if(await this.validateAllFields(`submit`),!this.state.isFieldsValid){n(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),TE.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:`validateAllFields`,errors:Object.values(this.state.fieldMeta).map(e=>e.errors).flat()});return}if(await this.validate(`submit`),!this.state.isValid){n(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),TE.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:`validate`,errors:this.state.errors});return}mE(()=>{Object.values(this.fieldInfo).forEach(e=>{e.instance?.triggerOnSubmitListener()})}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t}),mE(()=>{this.baseStore.setState(e=>({...e,isSubmitted:!0,isSubmitSuccessful:!0})),TE.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),n()})}catch(e){throw this.baseStore.setState(e=>({...e,isSubmitSuccessful:!1})),TE.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:`inflight`,onError:e}),n(),e}},this.getFieldValue=e=>DE(this.state.values,e),this.getFieldMeta=e=>this.state.fieldMeta[e],this.getFormGroupMeta=e=>this.formGroupMetaDerived.state[e],this.getFieldInfo=e=>this.fieldInfo[e]||={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}},this.setFieldMeta=(e,t)=>{this.baseStore.setState(n=>({...n,fieldMetaBase:{...n.fieldMetaBase,[e]:EE(t,n.fieldMetaBase[e])}}))},this.resetFieldMeta=e=>Object.keys(e).reduce((e,t)=>{let n=t;return e[n]=nD,e},{}),this.setFieldValue=(e,t,n)=>{let r=n?.dontUpdateMeta??!1,i=n?.dontRunListeners??!1,a=n?.dontValidate??!1;mE(()=>{r||this.setFieldMeta(e,e=>({...e,isTouched:!0,isDirty:!0,errorMap:{...e?.errorMap,onMount:void 0}})),this.baseStore.setState(n=>({...n,values:OE(n.values,e,t)}))}),i||this.getFieldInfo(e).instance?.triggerOnChangeListener(),a||this.validateField(e,`change`)},this.deleteField=e=>{let t=[...Object.keys(this.fieldInfo).filter(t=>{let n=e.toString();return t!==n&&t.startsWith(n)}),e];this.baseStore.setState(e=>{let n={...e};return t.forEach(e=>{n.values=kE(n.values,e),delete this.fieldInfo[e],delete n.fieldMetaBase[e]}),n})},this.pushFieldValue=(e,t,n)=>{this.setFieldValue(e,e=>[...Array.isArray(e)?e:[],t],n),rD(this).bumpArrayVersion(e)},this.insertFieldValue=async(e,t,n,r)=>{this.setFieldValue(e,e=>[...e.slice(0,t),n,...e.slice(t)],UE(r,{dontValidate:!0}));let i=r?.dontValidate??!1;i||await this.validateField(e,`change`),rD(this).handleArrayInsert(e,t),i||await this.validateArrayFieldsStartingFrom(e,t,`change`)},this.replaceFieldValue=async(e,t,n,r)=>{this.setFieldValue(e,e=>e.map((e,r)=>r===t?n:e),UE(r,{dontValidate:!0})),rD(this).bumpArrayVersion(e),(r?.dontValidate??!1)||(await this.validateField(e,`change`),await this.validateArrayFieldsStartingFrom(e,t,`change`))},this.removeFieldValue=async(e,t,n)=>{let r=this.getFieldValue(e),i=Array.isArray(r)?Math.max(r.length-1,0):null;if(this.setFieldValue(e,e=>e.filter((e,n)=>n!==t),UE(n,{dontValidate:!0})),rD(this).handleArrayRemove(e,t),i!==null){let t=`${e}[${i}]`;this.deleteField(t)}(n?.dontValidate??!1)||(await this.validateField(e,`change`),await this.validateArrayFieldsStartingFrom(e,t,`change`))},this.swapFieldValues=(e,t,n,r)=>{this.setFieldValue(e,e=>{let r=e[t],i=e[n];return OE(OE(e,`${t}`,i),`${n}`,r)},UE(r,{dontValidate:!0})),rD(this).handleArraySwap(e,t,n),(r?.dontValidate??!1)||(this.validateField(e,`change`),this.validateField(`${e}[${t}]`,`change`),this.validateField(`${e}[${n}]`,`change`))},this.moveFieldValues=(e,t,n,r)=>{this.setFieldValue(e,e=>{let r=[...e];return r.splice(n,0,r.splice(t,1)[0]),r},UE(r,{dontValidate:!0})),rD(this).handleArrayMove(e,t,n),(r?.dontValidate??!1)||(this.validateField(e,`change`),this.validateField(`${e}[${t}]`,`change`),this.validateField(`${e}[${n}]`,`change`))},this.clearFieldValues=(e,t)=>{let n=this.getFieldValue(e),r=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(e,[],UE(t,{dontValidate:!0})),rD(this).bumpArrayVersion(e),r!==null)for(let t=0;t<=r;t++){let n=`${e}[${t}]`;this.deleteField(n)}(t?.dontValidate??!1)||this.validateField(e,`change`)},this.resetField=e=>{this.baseStore.setState(t=>{let n=this.getFieldInfo(e).instance?.options.defaultValue,r=DE(this.options.defaultValues,e),i=n??r;return{...t,fieldMetaBase:{...t.fieldMetaBase,[e]:nD},values:i===void 0?t.values:OE(t.values,e,i)}})},this.setErrorMap=e=>{mE(()=>{Object.entries(e).forEach(([e,t])=>{let n=e;if(zE(t)){let{formError:e,fieldErrors:r}=oD(t);for(let e of Object.keys(this.fieldInfo))this.getFieldMeta(e)&&this.setFieldMeta(e,t=>({...t,errorMap:{...t.errorMap,[n]:r?.[e]},errorSourceMap:{...t.errorSourceMap,[n]:`form`}}));this.baseStore.setState(t=>({...t,errorMap:{...t.errorMap,[n]:e}}))}else this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[n]:t}}))})})},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((e,[t,n])=>(Object.keys(n).length&&n.errors.length&&(e[t]={errors:n.errors,errorMap:n.errorMap}),e),{})}),this.parseValuesWithSchema=e=>eD.validate({value:this.state.values,validationSource:`form`},e),this.parseValuesWithSchemaAsync=e=>eD.validateAsync({value:this.state.values,validationSource:`form`},e),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=e?.formId??qE(),this._devtoolsSubmissionOverride=!1;let t=iD({...e?.defaultState,values:e?.defaultValues??e?.defaultState?.values});if(e?.transform){t=e.transform({state:t}).state;for(let e of Object.keys(t.errorMap)){let n=t.errorMap[e];if(!(n===void 0||!zE(n)))for(let r of Object.keys(n.fields)){let i=n.fields[r];if(i===void 0)continue;let a=t.fieldMetaBase[r];t.fieldMetaBase[r]={isTouched:!1,isValidating:!1,isBlurred:!1,isDirty:!1,_arrayVersion:0,_pendingValidationsCount:0,...a??{},errorSourceMap:{...a?.errorSourceMap??{},onChange:`form`},errorMap:{...a?.errorMap??{},[e]:i}}}}}this.baseStore=xE(t);let n;this.fieldMetaDerived=xE(e=>{let t=this.baseStore.get(),r=0,i={};for(let a of Object.keys(t.fieldMetaBase)){let o=t.fieldMetaBase[a],s=n?.fieldMetaBase[a],c=e?.[a],l=DE(t.values,a),u=c?.errors;if(!s||o.errorMap!==s.errorMap){u=Object.values(o.errorMap??{}).filter(e=>e!==void 0);let e=this.getFieldInfo(a)?.instance;(!e||!e.options.disableErrorFlat)&&(u=u.flat(1))}let d=!IE(u),f=!o.isDirty,p=BE(l,this.getFieldInfo(a)?.instance?.options.defaultValue??DE(this.options.defaultValues,a));if(c&&c.isPristine===f&&c.isValid===d&&c.isDefaultValue===p&&c.errors===u&&o===s){i[a]=c,r++;continue}i[a]={...o,errors:u??[],isPristine:f,isValid:d,isDefaultValue:p}}return Object.keys(t.fieldMetaBase).length?e&&r===Object.keys(t.fieldMetaBase).length?e:(n=this.baseStore.get(),i):i}),this.formGroupMetaDerived=xE(e=>{let t=this.baseStore.get(),n=this.fieldMetaDerived.get(),r={};for(let i of this.formGroupApis){let a=i.name,o=t.formGroupStateBase[a]??{isSubmitted:!1,isSubmitting:!1,isValidating:!1,submissionAttempts:0,isSubmitSuccessful:!1},s=n[a],c=!1,l=!0,u=!1,d=!1,f=!0,p=!1;for(let e in n){if(e===a||!XE(a,e))continue;let t=n[e];t&&(t.isValidating&&(c=!0),t.isValid||(l=!1),t.isTouched&&(u=!0),t.isBlurred&&(d=!0),t.isDefaultValue||(f=!1),t.isDirty&&(p=!0))}let m=!p,h=!!c||o.isValidating,g=s?.errorMap??{},_=s?.errorSourceMap??{},v=!!(g.onMount||Object.entries(n).some(([e,t])=>t&&e!==a&&XE(a,e)&&t.errorMap.onMount)),y=e?.[a],b=y?.errors??[];(!y||y.__srcErrorMap!==g)&&(b=Object.values(g).reduce((e,t)=>{if(t===void 0)return e;if(t&&typeof t==`object`&&`fields`in t){let n=t.group;return n!==void 0&&e.push(n),e}return e.push(t),e},[]));let x=b.length===0,S=l&&x,C=i.options.canSubmitWhenInvalid??!1,w=o.submissionAttempts===0&&!u&&!v||!h&&!o.isSubmitting&&S||C;if(y&&y.errorMap===g&&y.errorSourceMap===_&&y.errors===b&&y.isFieldsValidating===c&&y.isFieldsValid===l&&y.isGroupValid===x&&y.isValid===S&&y.canSubmit===w&&y.isTouched===u&&y.isBlurred===d&&y.isPristine===m&&y.isDefaultValue===f&&y.isDirty===p&&y.isValidating===h&&y.isSubmitting===o.isSubmitting&&y.isSubmitted===o.isSubmitted&&y.submissionAttempts===o.submissionAttempts&&y.isSubmitSuccessful===o.isSubmitSuccessful){r[a]=y;continue}let T={...o,errorMap:g,errorSourceMap:_,_arrayVersion:s?._arrayVersion??0,isTouched:u,isBlurred:d,isDirty:p,isPristine:m,isDefaultValue:f,isValid:S,errors:b,isValidating:h,isFieldsValidating:c,isFieldsValid:l,isGroupValid:x,canSubmit:w};Object.defineProperty(T,"__srcErrorMap",{value:g,enumerable:!1,configurable:!0}),r[a]=T}return r});let r;this.store=xE(e=>{let t=this.baseStore.get(),n=this.fieldMetaDerived.get(),i=Object.values(n).filter(Boolean),a=i.some(e=>e.isValidating),o=i.every(e=>e.isValid),s=i.some(e=>e.isTouched),c=i.some(e=>e.isBlurred),l=i.every(e=>e.isDefaultValue),u=s&&t.errorMap?.onMount,d=i.some(e=>e.isDirty),f=!d,p=!!(t.errorMap?.onMount||i.some(e=>e?.errorMap?.onMount)),m=!!a,h=e?.errors??[];(!r||t.errorMap!==r.errorMap)&&(h=Object.values(t.errorMap).reduce((e,t)=>t===void 0?e:t&&zE(t)?(e.push(t.form),e):(e.push(t),e),[]));let g=h.length===0,_=o&&g,v=this.options.canSubmitWhenInvalid??!1,y=t.submissionAttempts===0&&!s&&!p||!m&&!t.isSubmitting&&_||v,b=t.errorMap;if(u&&(h=h.filter(e=>e!==t.errorMap.onMount),b=Object.assign(b,{onMount:void 0})),e&&r&&e.errorMap===b&&e.fieldMeta===this.fieldMetaDerived.state&&e.errors===h&&e.isFieldsValidating===a&&e.isFieldsValid===o&&e.isFormValid===g&&e.isValid===_&&e.canSubmit===y&&e.isTouched===s&&e.isBlurred===c&&e.isPristine===f&&e.isDefaultValue===l&&e.isDirty===d&&BE(r,t))return e;let x={...t,errorMap:b,fieldMeta:this.fieldMetaDerived.state,errors:h,isFieldsValidating:a,isFieldsValid:o,isFormValid:g,isValid:_,canSubmit:y,isTouched:s,isBlurred:c,isPristine:f,isDefaultValue:l,isDirty:d};return r=this.baseStore.get(),x}),this.handleSubmit=this.handleSubmit.bind(this),this.update(e||{})}get state(){return this.store.state}get formId(){return this._formId}runValidator(e){return tD(e.validate)?eD[e.type](e.value,e.validate):e.validate(e.value)}handleSubmit(e){return this._handleSubmit(e)}};function oD(e){return e?zE(e)?{formError:oD(e.form).formError,fieldErrors:e.fields}:{formError:e}:{formError:void 0}}function sD(e){switch(e){case`submit`:return`onSubmit`;case`blur`:return`onBlur`;case`mount`:return`onMount`;case`server`:return`onServer`;case`dynamic`:return`onDynamic`;default:return`onChange`}}var cD=class e{constructor(t){this.options={},this.mount=()=>{this.options.defaultValue!==void 0&&!this.getMeta().isTouched&&this.form.setFieldValue(this.name,this.options.defaultValue,{dontUpdateMeta:!0});let e=this.getInfo();e.instance=this,this.update(this.options);let{onMount:t}=this.options.validators||{};if(t){let e=this.runValidator({validate:t,value:{value:this.state.value,fieldApi:this,validationSource:`field`},type:`validate`});e&&this.setMeta(t=>({...t,errorMap:{...t?.errorMap,onMount:e},errorSourceMap:{...t?.errorSourceMap,onMount:`field`}}))}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),()=>{for(let[e,t]of Object.entries(this.timeoutIds.validations))t&&(clearTimeout(t),this.timeoutIds.validations[e]=null);for(let[e,t]of Object.entries(this.timeoutIds.listeners))t&&(clearTimeout(t),this.timeoutIds.listeners[e]=null);for(let[e,t]of Object.entries(this.timeoutIds.formListeners))t&&(clearTimeout(t),this.timeoutIds.formListeners[e]=null);let e=this.form.fieldInfo[this.name];if(e&&e.instance===this){for(let[t,n]of Object.entries(e.validationMetaMap))n?.lastAbortController.abort(),e.validationMetaMap[t]=void 0;this.form.baseStore.setState(e=>({...e,fieldMetaBase:{...e.fieldMetaBase,[this.name]:{...nD,isTouched:e.fieldMetaBase[this.name]?.isTouched??nD.isTouched,isBlurred:e.fieldMetaBase[this.name]?.isBlurred??nD.isBlurred,isDirty:e.fieldMetaBase[this.name]?.isDirty??nD.isDirty}}})),e.instance=null,this.options.listeners?.onUnmount?.({value:this.state.value,fieldApi:this}),this.form.options.listeners?.onFieldUnmount?.({formApi:this.form,fieldApi:this})}}},this.update=e=>{this.options=e,this.name=e.name,!this.state.meta.isTouched&&this.options.defaultValue!==void 0&&(BE(this.form.getFieldValue(this.name),e.defaultValue)||this.form.setFieldValue(this.name,e.defaultValue,{dontUpdateMeta:!0,dontValidate:!0,dontRunListeners:!0})),this.form.getFieldMeta(this.name)||this.form.setFieldMeta(this.name,this.state.meta)},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(e,t)=>{this.form.setFieldValue(this.name,e,UE(t,{dontRunListeners:!0,dontValidate:!0})),t?.dontRunListeners||this.triggerOnChangeListener(),t?.dontValidate||this.validate(`change`)},this.getMeta=()=>this.store.state.meta,this.setMeta=e=>this.form.setFieldMeta(this.name,e),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(e,t)=>{this.form.pushFieldValue(this.name,e,UE(t,{dontRunListeners:!0})),t?.dontRunListeners||this.triggerOnChangeListener()},this.insertValue=(e,t,n)=>{this.form.insertFieldValue(this.name,e,t,UE(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.replaceValue=(e,t,n)=>{this.form.replaceFieldValue(this.name,e,t,UE(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.removeValue=(e,t)=>{this.form.removeFieldValue(this.name,e,UE(t,{dontRunListeners:!0})),t?.dontRunListeners||this.triggerOnChangeListener()},this.swapValues=(e,t,n)=>{this.form.swapFieldValues(this.name,e,t,UE(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.moveValue=(e,t,n)=>{this.form.moveFieldValues(this.name,e,t,UE(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.clearValues=e=>{this.form.clearFieldValues(this.name,UE(e,{dontRunListeners:!0})),e?.dontRunListeners||this.triggerOnChangeListener()},this.getLinkedFields=t=>{let n=Object.values(this.form.fieldInfo),r=[];for(let i of n){if(!i.instance||!(i.instance instanceof e))continue;let{onChangeListenTo:n,onBlurListenTo:a}=i.instance.options.validators||{};t===`change`&&n?.includes(this.name)&&r.push(i.instance),t===`blur`&&a?.includes(this.name)&&r.push(i.instance)}return r},this.validateSync=(e,t)=>{let n=LE(e,{...this.options,form:this.form,fieldName:this.name,validationLogic:this.form.options.validationLogic||ZE}),r=this.getLinkedFields(e).reduce((t,n)=>{let r=LE(e,{...n.options,form:n.form,fieldName:n.name,validationLogic:n.form.options.validationLogic||ZE});return r.forEach(e=>{e.field=n}),t.concat(r)},[]),i=!1;mE(()=>{let e=(e,n)=>{let r=uD(n.cause),a=n.validate?lD(e.runValidator({validate:n.validate,value:{value:e.store.state.value,validationSource:`field`,fieldApi:e},type:`validate`})):void 0,o=t[r],{newErrorValue:s,newSource:c}=HE({formLevelError:o,fieldLevelError:a});e.state.meta.errorMap?.[r]!==s&&e.setMeta(e=>({...e,errorMap:{...e.errorMap,[r]:s},errorSourceMap:{...e.errorSourceMap,[r]:c}})),s&&(i=!0)};for(let t of n)e(this,t);for(let t of r)t.validate&&e(t.field,t)});let a=uD(`submit`);return this.state.meta.errorMap?.[a]&&e!==`submit`&&!i&&this.setMeta(e=>({...e,errorMap:{...e.errorMap,[a]:void 0},errorSourceMap:{...e.errorSourceMap,[a]:void 0}})),{hasErrored:i}},this.validateAsync=async(e,t)=>{let n=RE(e,{...this.options,form:this.form,fieldName:this.name,validationLogic:this.form.options.validationLogic||ZE}),r=await t,i=this.getLinkedFields(e).reduce((t,n)=>{let r=RE(e,{...n.options,form:n.form,fieldName:n.name,validationLogic:n.form.options.validationLogic||ZE});return r.forEach(e=>{e.field=n}),t.concat(r)},[]),a=[],o=[],s=n.some(e=>e.validate),c=Array.from(new Set(i.filter(e=>e.validate).map(e=>e.field)));mE(()=>{s&&this.startValidation();for(let e of c)e.startValidation()});let l=(e,t,n)=>{let i=uD(t.cause),a=e.getInfo();a.validationMetaMap[i]?.lastAbortController.abort();let o=new AbortController;a.validationMetaMap[i]={lastAbortController:o},n.push(new Promise(async n=>{let a;try{a=await new Promise((n,r)=>{e.timeoutIds.validations[t.cause]&&(clearTimeout(e.timeoutIds.validations[t.cause]),e.endValidation()),e.timeoutIds.validations[t.cause]=setTimeout(async()=>{if(o.signal.aborted)return n(void 0);try{n(await this.runValidator({validate:t.validate,value:{value:e.store.state.value,fieldApi:e,signal:o.signal,validationSource:`field`},type:`validateAsync`}))}catch(e){r(e)}},t.debounceMs)})}catch(e){a=e}if(o.signal.aborted)return n(void 0);let s=lD(a),c=r[e.name]?.[i],{newErrorValue:l,newSource:u}=HE({formLevelError:c,fieldLevelError:s});if(e.getInfo().instance!==e)return n(void 0);e.setMeta(e=>({...e,errorMap:{...e?.errorMap,[i]:l},errorSourceMap:{...e.errorSourceMap,[i]:u}})),n(l)}))};for(let e of n)e.validate&&l(this,e,a);for(let e of i)e.validate&&l(e.field,e,o);let u=[];return(a.length||o.length)&&(u=await Promise.all(a),await Promise.all(o)),mE(()=>{s&&this.endValidation();for(let e of c)e.endValidation()}),u.filter(Boolean)},this.validate=(e,t)=>{if(!this.state.meta.isTouched)return[];let n=t?.skipGroupValidation?[]:Array.from(this.form.formGroupApis).filter(e=>this.name.startsWith(e.name)),r=(t?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(e)).fieldsErrorMap[this.name]??{};if(!t?.skipFormValidation)for(let t of n){if(t.state.meta.submissionAttempts===0)continue;let{fieldsErrorMap:n}=this.form.validateSync(e,{group:t,dontUpdateFormErrorMap:!0,filterFieldNames:e=>XE(t.name,e)});r={...r,...n[this.name]??{}}}let{hasErrored:i}=this.validateSync(e,r),a=new WeakMap;for(let t of n){let{hasErrored:n}=t.validateSync(e,{},{skipRelatedFieldValidation:!0});a.set(t,n)}if(i&&!this.options.asyncAlways){this.getInfo().validationMetaMap[uD(e)]?.lastAbortController.abort();let t=[];for(let r of n)r.getInfo().validationMetaMap[uD(e)]?.lastAbortController.abort(),t.push(r.state.meta.errors);return[...this.state.meta.errors,...t.flat()]}let o=t?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(e),s=this.validateAsync(e,o),c=[];for(let t of n)a.get(t)&&!t.options.asyncAlways||c.push(t.validateAsync(e,o,{skipRelatedFieldValidation:!0}));return c.length===0?s:Promise.all([s,...c]).then(e=>e.flat())},this.handleChange=e=>{this.setValue(e)},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(e=>({...e,isTouched:!0})),this.state.meta.isBlurred||this.setMeta(e=>({...e,isBlurred:!0})),this.validate(`blur`),this.triggerOnBlurListener()},this.setErrorMap=e=>{this.setMeta(t=>({...t,errorMap:{...t.errorMap,...e}}))},this.parseValueWithSchema=e=>eD.validate({value:this.state.value,validationSource:`field`},e),this.parseValueWithSchemaAsync=e=>eD.validateAsync({value:this.state.value,validationSource:`field`},e),this.triggerOnBlurListener=()=>{let e=this.form.options.listeners?.onBlurDebounceMs;e&&e>0?(this.timeoutIds.formListeners.blur&&clearTimeout(this.timeoutIds.formListeners.blur),this.timeoutIds.formListeners.blur=setTimeout(()=>{this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this})},e)):this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onBlurDebounceMs;t&&t>0?(this.timeoutIds.listeners.blur&&clearTimeout(this.timeoutIds.listeners.blur),this.timeoutIds.listeners.blur=setTimeout(()=>{this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this})},t)):this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this})},this.triggerOnChangeListener=()=>{let e=this.form.options.listeners?.onChangeDebounceMs;e&&e>0?(this.timeoutIds.formListeners.change&&clearTimeout(this.timeoutIds.formListeners.change),this.timeoutIds.formListeners.change=setTimeout(()=>{this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this})},e)):this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onChangeDebounceMs;t&&t>0?(this.timeoutIds.listeners.change&&clearTimeout(this.timeoutIds.listeners.change),this.timeoutIds.listeners.change=setTimeout(()=>{this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this})},t)):this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});for(let e of this.form.formGroupApis)XE(e.name,this.name)&&e.triggerOnChangeListener()},this.triggerOnSubmitListener=()=>{this.options.listeners?.onSubmit?.({value:this.state.value,fieldApi:this})},this.form=t.form,this.name=t.name,this.options=t,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=xE(e=>{this.form.store.get();let n=this.form.getFieldMeta(this.name)??{...nD,...t.defaultMeta},r=this.form.getFieldValue(this.name);return!n.isTouched&&r===void 0&&this.options.defaultValue!==void 0&&!BE(r,this.options.defaultValue)&&(r=this.options.defaultValue),e&&e.value===r&&e.meta===n?e:{value:r,meta:n}})}get state(){return this.store.state}runValidator(e){return tD(e.validate)?eD[e.type](e.value,e.validate):e.validate(e.value)}startValidation(){this.setMeta(e=>{let t=e._pendingValidationsCount+1;return{...e,_pendingValidationsCount:t,isValidating:t>0&&!e.isValidating||e.isValidating}})}endValidation(){this.setMeta(e=>{let t=Math.max(0,e._pendingValidationsCount-1);return{...e,_pendingValidationsCount:t,isValidating:t===0&&e.isValidating?!1:e.isValidating}})}};function lD(e){if(e)return e}function uD(e){switch(e){case`submit`:return`onSubmit`;case`blur`:return`onBlur`;case`mount`:return`onMount`;case`server`:return`onServer`;case`dynamic`:return`onDynamic`;default:return`onChange`}}function dD(e){return{isSubmitted:e.isSubmitted??!1,isSubmitting:e.isSubmitting??!1,isValidating:e.isValidating??!1,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??!1}}function fD(e){return{...nD,...e,errors:[],isPristine:!0,isValid:!0,isDefaultValue:!0,isFieldsValidating:!1,isFieldsValid:!0,isGroupValid:!0,canSubmit:!0,isSubmitting:!1,isSubmitted:!1,isValidating:!1,submissionAttempts:0,isSubmitSuccessful:!1}}var pD=class e{constructor(t){this.options={},this.setFormGroupState=e=>{this.form.baseStore.setState(t=>{let n=t.formGroupStateBase[this.name]??dD({});return{...t,formGroupStateBase:{...t.formGroupStateBase,[this.name]:e(n)}}})},this._lastDistributedFieldNames={},this.update=e=>{this.options=e,this.name=e.name,!this.state.meta.isTouched&&this.options.defaultValue!==void 0&&(BE(this.form.getFieldValue(this.name),e.defaultValue)||this.form.setFieldValue(this.name,e.defaultValue,{dontUpdateMeta:!0,dontValidate:!0,dontRunListeners:!0})),this.form.getFieldMeta(this.name)||this.form.setFieldMeta(this.name,{...nD,...this.options.defaultMeta})},this.mount=()=>{this.update(this.options),this.form.formGroupApis.add(this),this.fieldInfo.instance=this,this.form.baseStore.setState(e=>({...e,formGroupStateBase:{...e.formGroupStateBase,[this.name]:e.formGroupStateBase[this.name]??dD({...this.options.defaultState})}}));let{onMount:e}=this.options.validators||{};if(e){let t=this.runValidator({validate:e,value:{value:this.state.value,groupApi:this,validationSource:`form`},type:`validate`}),n=t,r;hD(t)&&(n=t.group,r=t.fields);let i=mD(n);i&&this.setMeta(e=>({...e,errorMap:{...e.errorMap,onMount:i},errorSourceMap:{...e.errorSourceMap,onMount:`field`}})),this.distributeFieldErrors(`onMount`,r)}return this.options.listeners?.onMount?.({value:this.state.value,groupApi:this}),()=>{for(let[e,t]of Object.entries(this.timeoutIds.validations))t&&(clearTimeout(t),this.timeoutIds.validations[e]=null);for(let[e,t]of Object.entries(this.timeoutIds.listeners))t&&(clearTimeout(t),this.timeoutIds.listeners[e]=null);for(let[e,t]of Object.entries(this.timeoutIds.formListeners))t&&(clearTimeout(t),this.timeoutIds.formListeners[e]=null);if(this.fieldInfo.instance===this){for(let[e,t]of Object.entries(this.fieldInfo.validationMetaMap))t?.lastAbortController.abort(),this.fieldInfo.validationMetaMap[e]=void 0;this.form.formGroupApis.delete(this),this.form.baseStore.setState(e=>({...e,formGroupStateBase:{...e.formGroupStateBase,[this.name]:dD({})}})),this.fieldInfo.instance=null,this.options.listeners?.onUnmount?.({value:this.state.value,groupApi:this})}}},this.setValue=(e,t)=>{this.form.setFieldValue(this.name,e,UE(t,{dontRunListeners:!0,dontValidate:!0})),t?.dontRunListeners||this.triggerOnChangeListener(),t?.dontValidate||this.validate(`change`)},this.getMeta=()=>this.store.state.meta,this.setMeta=e=>this.form.setFieldMeta(this.name,e),this.getInfo=()=>this.fieldInfo,this.getRelatedFields=()=>{let e=Object.values(this.form.fieldInfo),t=[];for(let n of e)n.instance&&n.instance instanceof cD&&n.instance.name.startsWith(this.name)&&t.push(n.instance);return t},this.getRelatedFieldMetasDerived=()=>{let e=Object.entries(this.form.fieldMetaDerived.state),t=[];for(let[n,r]of e)n!==this.name&&XE(this.name,n)&&t.push({...r,name:n});return t},this.buildChildFieldName=e=>e===``?this.name:e.startsWith(`[`)?`${this.name}${e}`:`${this.name}.${e}`,this.distributeFieldErrors=(e,t)=>{let n=this._lastDistributedFieldNames[e]??new Set,r=new Set;if(t)for(let[e,n]of Object.entries(t))n!=null&&n!==!1&&r.add(this.buildChildFieldName(e));let i=new Set([...n,...r]),a=!1;for(let n of i){let r=n.startsWith(this.name+`[`)?n.slice(this.name.length):n.slice(this.name.length+1),i=t?.[r],o=this.form.getFieldMeta(n);if(!o&&!i)continue;let s=o?.errorMap[e],{newErrorValue:c,newSource:l}=VE({newFormValidatorError:i,isPreviousErrorFromFormValidator:o?.errorSourceMap[e]===`form`,previousErrorValue:s});c&&(a=!0),(s!==c||o?.errorSourceMap[e]!==l)&&this.form.setFieldMeta(n,(t=nD)=>({...t,errorMap:{...t.errorMap,[e]:c},errorSourceMap:{...t.errorSourceMap,[e]:l}}))}return this._lastDistributedFieldNames[e]=r,a},this.validateSync=(t,n,r={})=>{let i=LE(t,{...this.options,form:this.form,group:this,validationLogic:this.options.validationLogic||this.form.options.validationLogic||ZE}),a=(r.skipRelatedFieldValidation?[]:this.getRelatedFields()).reduce((e,n)=>{let r=LE(t,{...n.options,form:n.form,validationLogic:n.form.options.validationLogic||ZE});return r.forEach(e=>{e.field=n}),e.concat(r)},[]),o=!1;mE(()=>{let t=(t,r)=>{let i=_D(r.cause),a=t===this,s;r.validate&&(s=t.runValidator({validate:r.validate,value:{value:t.store.state.value,validationSource:a?`form`:`field`,...t instanceof e?{groupApi:t}:{fieldApi:t}},type:`validate`}));let c=s,l;a&&hD(s)&&(c=s.group,l=s.fields);let u=mD(c),d=n[i],{newErrorValue:f,newSource:p}=HE({formLevelError:d,fieldLevelError:u});t.state.meta.errorMap?.[i]!==f&&t.setMeta(e=>({...e,errorMap:{...e.errorMap,[i]:f},errorSourceMap:{...e.errorSourceMap,[i]:p}})),f&&(o=!0),a&&this.distributeFieldErrors(i,l)&&(o=!0)};for(let e of i)t(this,e);for(let e of a)e.validate&&t(e.field,e)});let s=_D(`submit`);return this.state.meta.errorMap?.[s]&&t!==`submit`&&!o&&this.setMeta(e=>({...e,errorMap:{...e.errorMap,[s]:void 0},errorSourceMap:{...e.errorSourceMap,[s]:void 0}})),{hasErrored:o}},this.validateAsync=async(t,n,r={})=>{let i=RE(t,{...this.options,form:this.form,group:this,validationLogic:this.options.validationLogic||this.form.options.validationLogic||ZE}),a=await n,o=r.skipRelatedFieldValidation?[]:this.getRelatedFields(),s=o.reduce((e,n)=>{let r=RE(t,{...n.options,form:n.form,validationLogic:n.form.options.validationLogic||ZE});return r.forEach(e=>{e.field=n}),e.concat(r)},[]),c=[],l=[],u=i.some(e=>e.validate)||s.some(e=>e.validate);if(u){this.state.meta.isValidating||this.setMeta(e=>({...e,isValidating:!0}));for(let e of o)e.setMeta(e=>({...e,isValidating:!0}))}let d=(t,n,r)=>{let i=_D(n.cause),o=t.getInfo();o.validationMetaMap[i]?.lastAbortController.abort();let s=new AbortController;o.validationMetaMap[i]={lastAbortController:s};let c=t===this;r.push(new Promise(async r=>{let o;try{o=await new Promise((r,i)=>{t.timeoutIds.validations[n.cause]&&clearTimeout(t.timeoutIds.validations[n.cause]),t.timeoutIds.validations[n.cause]=setTimeout(async()=>{if(s.signal.aborted)return r(void 0);try{r(await this.runValidator({validate:n.validate,value:{value:t.store.state.value,signal:s.signal,validationSource:c?`form`:`field`,...t instanceof e?{groupApi:t}:{fieldApi:t}},type:`validateAsync`}))}catch(e){i(e)}},n.debounceMs)})}catch(e){o=e}if(s.signal.aborted)return r(void 0);let l=o,u;c&&hD(o)&&(l=o.group,u=o.fields);let d=mD(l),f=a[t.name]?.[i],{newErrorValue:p,newSource:m}=HE({formLevelError:f,fieldLevelError:d});if(t.getInfo().instance!==t)return r(void 0);t.setMeta(e=>({...e,errorMap:{...e?.errorMap,[i]:p},errorSourceMap:{...e.errorSourceMap,[i]:m}})),c&&this.distributeFieldErrors(i,u),r(p)}))};for(let e of i)e.validate&&d(this,e,c);for(let e of s)e.validate&&d(e.field,e,l);let f=[];if((c.length||l.length)&&(f=await Promise.all(c),await Promise.all(l)),u){this.setMeta(e=>({...e,isValidating:!1}));for(let e of o)e.setMeta(e=>({...e,isValidating:!1}))}return f.filter(Boolean)},this.validateAllFields=async e=>{let t=[];return mE(()=>{Object.values(this.getRelatedFields()).forEach(n=>{t.push(Promise.resolve().then(()=>n.validate(e,{skipFormValidation:!0,skipGroupValidation:!0}))),n.store.state.meta.isTouched||n.setMeta(e=>({...e,isTouched:!0}))})}),(await Promise.all(t)).flat()},this.validateArrayFieldsStartingFrom=(e,t,n)=>this.form.validateArrayFieldsStartingFrom(e,t,n),this.validateField=(e,t)=>this.form.validateField(e,t),this.getFieldValue=e=>this.form.getFieldValue(e),this.getFieldMeta=e=>this.form.getFieldMeta(e),this.setFieldMeta=(e,t)=>this.form.setFieldMeta(e,t),this.setFieldValue=(e,t)=>this.form.setFieldValue(e,t),this.deleteField=e=>this.form.deleteField(e),this.pushFieldValue=(e,t)=>this.form.pushFieldValue(e,t),this.insertFieldValue=(e,t,n)=>this.form.insertFieldValue(e,t,n),this.replaceFieldValue=(e,t,n)=>this.form.replaceFieldValue(e,t,n),this.swapFieldValues=(e,t,n)=>this.form.swapFieldValues(e,t,n),this.moveFieldValues=(e,t,n)=>this.form.moveFieldValues(e,t,n),this.clearFieldValues=e=>this.form.clearFieldValues(e),this.resetField=e=>this.form.resetField(e),this.removeFieldValue=(e,t)=>this.form.removeFieldValue(e,t),this.areRelatedFieldsValid=()=>Object.values(this.getRelatedFields()).every(e=>e.state.meta.isValid),this.validate=(e,t)=>{let{fieldsErrorMap:n}=t?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(e,{dontUpdateFormErrorMap:!0,filterFieldNames:e=>XE(this.name,e)}),{hasErrored:r}=this.validateSync(e,n[this.name]??{},{skipRelatedFieldValidation:t?.skipRelatedFieldValidation});if(r&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[_D(e)]?.lastAbortController.abort(),this.state.meta.errors;let i=t?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(e,{dontUpdateFormErrorMap:!0,filterFieldNames:e=>XE(this.name,e)});return this.validateAsync(e,i,{skipRelatedFieldValidation:t?.skipRelatedFieldValidation})},this.triggerOnChangeListener=()=>{let e=this.form.options.listeners?.onChangeGroupDebounceMs;e&&e>0?(this.timeoutIds.formListeners.change&&clearTimeout(this.timeoutIds.formListeners.change),this.timeoutIds.formListeners.change=setTimeout(()=>{this.form.options.listeners?.onChangeGroup?.({formApi:this.form,groupApi:this})},e)):this.form.options.listeners?.onChangeGroup?.({formApi:this.form,groupApi:this});let t=this.options.listeners?.onChangeDebounceMs;t&&t>0?(this.timeoutIds.listeners.change&&clearTimeout(this.timeoutIds.listeners.change),this.timeoutIds.listeners.change=setTimeout(()=>{this.options.listeners?.onChange?.({value:this.state.value,groupApi:this})},t)):this.options.listeners?.onChange?.({value:this.state.value,groupApi:this})},this.triggerOnSubmitListener=()=>{this.options.listeners?.onSubmit?.({value:this.state.value,groupApi:this})},this._handleSubmit=async e=>{this.setFormGroupState(e=>({...e,isSubmitted:!1,submissionAttempts:e.submissionAttempts+1,isSubmitSuccessful:!1})),mE(()=>{Object.values(this.getRelatedFields()).forEach(e=>{e.state.meta.isTouched||e.setMeta(e=>({...e,isTouched:!0}))})});let t=e??this.options.onSubmitMeta;this.setFormGroupState(e=>({...e,isSubmitting:!0}));let n=()=>{this.setFormGroupState(e=>({...e,isSubmitting:!1}))};if(await this.validateAllFields(`submit`),!this.areRelatedFieldsValid()){n(),this.options.onGroupSubmitInvalid?.({value:this.state.value,groupApi:this,meta:t});return}if(await this.validate(`submit`,{skipRelatedFieldValidation:!0}),!this.areRelatedFieldsValid()||!this.state.meta.isValid){n(),this.options.onGroupSubmitInvalid?.({value:this.state.value,groupApi:this,meta:t});return}mE(()=>{Object.values(this.getRelatedFields()).forEach(e=>{e.options.listeners?.onGroupSubmit?.({value:e.state.value,fieldApi:e})})}),this.options.listeners?.onSubmit?.({groupApi:this,value:this.state.value});try{await this.options.onGroupSubmit?.({value:this.state.value,groupApi:this,meta:t}),mE(()=>{this.setFormGroupState(e=>({...e,isSubmitted:!0,isSubmitSuccessful:!0})),n()})}catch(e){throw this.setFormGroupState(e=>({...e,isSubmitSuccessful:!1})),n(),e}},this.form=t.form,this.name=t.name,this.options=t,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.fieldInfo={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}},this.store=xE(e=>{this.form.formGroupMetaDerived.get(),this.form.baseStore.get();let n=this.form.getFormGroupMeta(this.name)??fD(t.defaultMeta),r=this.form.getFieldValue(this.name);return!n.isTouched&&r===void 0&&this.options.defaultValue!==void 0&&!BE(r,this.options.defaultValue)&&(r=this.options.defaultValue),e&&e.value===r&&e.meta===n?e:{value:r,meta:n}}),this.handleSubmit=this.handleSubmit.bind(this)}get state(){return this.store.state}runValidator(e){if(tD(e.validate)){let t=eD[e.type](e.value,e.validate);return e.type===`validate`?gD(t):t.then(gD)}return e.validate(e.value)}handleSubmit(e){return this._handleSubmit(e)}};function mD(e){if(e)return e}function hD(e){return!!e&&typeof e==`object`&&`fields`in e}function gD(e){if(!e||typeof e!=`object`||!(`form`in e)&&!(`fields`in e))return e;let{form:t,fields:n,...r}=e;return{...r,group:t,fields:n}}function _D(e){switch(e){case`submit`:return`onSubmit`;case`blur`:return`onBlur`;case`mount`:return`onMount`;case`server`:return`onServer`;case`dynamic`:return`onDynamic`;default:return`onChange`}}function vD(e,t){if(!t)return;let n=Object.assign({},e,{state:YE(e.state)});t(n),n.fieldInfo!==e.fieldInfo&&(e.fieldInfo=n.fieldInfo),n.options!==e.options&&(e.options=n.options);let r=Object.keys({values:null,validationMetaMap:null,fieldMetaBase:null,formGroupStateBase:null,isSubmitting:null,isSubmitted:null,isValidating:null,submissionAttempts:null,isSubmitSuccessful:null,_force_re_eval:null}).reduce((t,r)=>(e.state[r]!==n.state[r]&&(t[r]=n.state[r]),t),{});return mE(()=>{Object.keys(r).length&&e.baseStore.setState(e=>({...e,...r})),n.state.errorMap!==e.state.errorMap&&e.setErrorMap(n.state.errorMap)}),n}var yD=Je();function bD(e,t){return e===t}function xD(e,t=e=>e,n){let r=n?.compare??bD,i=(0,q.useCallback)(t=>{let{unsubscribe:n}=e.subscribe(t);return n},[e]),a=(0,q.useCallback)(()=>e.get(),[e]);return(0,yD.useSyncExternalStoreWithSelector)(i,a,a,t,r)}var SD=typeof window<`u`?q.useLayoutEffect:q.useEffect;function CD(e){let[t,n]=(0,q.useState)(()=>({form:e.form,name:e.name})),[r,i]=(0,q.useState)(()=>new cD({...e})),a=r;(t.form!==e.form||t.name!==e.name)&&(a=new cD({...e}),i(a),n({form:e.form,name:e.name}));let o=xD(a.store,e.mode===`array`?e=>e.meta._arrayVersion||0:e=>e.value),s=xD(a.store,e=>e.meta.isTouched),c=xD(a.store,e=>e.meta.isBlurred),l=xD(a.store,e=>e.meta.isDirty),u=xD(a.store,e=>e.meta.errorMap),d=xD(a.store,e=>e.meta.errorSourceMap),f=xD(a.store,e=>e.meta.isValidating),p=(0,q.useMemo)(()=>({...a,get state(){return{value:e.mode===`array`?a.state.value:o,get meta(){return{...a.state.meta,isTouched:s,isBlurred:c,isDirty:l,errorMap:u,errorSourceMap:d,isValidating:f}}}}}),[a,e.mode,o,s,c,l,u,d,f]);return SD(a.mount,[a]),SD(()=>{a.update(e)}),p}var wD=(({children:e,...t})=>{let n=CD(t),r=(0,q.useMemo)(()=>EE(e,n),[e,n]);return(0,Y.jsx)(Y.Fragment,{children:r})});function TD(){return(0,q.useState)(()=>qE())[0]}var ED=q,DD=`18.3.1`.split(`.`)[0]===`17`?TD:ED.useId;function OD(e){let[t,n]=(0,q.useState)(()=>({form:e.form,name:e.name})),[r,i]=(0,q.useState)(()=>new pD({...e}));(t.form!==e.form||t.name!==e.name)&&(i(new pD({...e})),n({form:e.form,name:e.name}));let a=xD(r.store,e=>e.value),o=xD(r.store,e=>e.meta.isTouched),s=xD(r.store,e=>e.meta.isBlurred),c=xD(r.store,e=>e.meta.isDirty),l=xD(r.store,e=>e.meta.errorMap),u=xD(r.store,e=>e.meta.errorSourceMap),d=xD(r.store,e=>e.meta.isValidating),f=xD(r.store,e=>e.meta.isSubmitting),p=xD(r.store,e=>e.meta.isSubmitted),m=xD(r.store,e=>e.meta.submissionAttempts),h=xD(r.store,e=>e.meta.isSubmitSuccessful),g=xD(r.store,e=>e.meta.canSubmit),_=xD(r.store,e=>e.meta.isValid),v=xD(r.store,e=>e.meta.isFieldsValid),y=xD(r.store,e=>e.meta.isFieldsValidating),b=xD(r.store,e=>e.meta.isGroupValid),x=(0,q.useMemo)(()=>({...r,handleSubmit:((...e)=>r._handleSubmit(...e)),get state(){return{...r.state,value:a,get meta(){return{...r.state.meta,isTouched:o,isBlurred:s,isDirty:c,errorMap:l,errorSourceMap:u,isValidating:d,isSubmitting:f,isSubmitted:p,submissionAttempts:m,isSubmitSuccessful:h,canSubmit:g,isValid:_,isFieldsValid:v,isFieldsValidating:y,isGroupValid:b}}}}}),[r,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b]);return SD(r.mount,[r]),SD(()=>{r.update(e)}),x}var kD=(({children:e,...t})=>{let n=OD(t),r=(0,q.useMemo)(()=>EE(e,n),[e,n]);return(0,Y.jsx)(Y.Fragment,{children:r})});function AD({form:e,selector:t=e=>e,children:n}){let r=xD(e.store,t);return(0,Y.jsx)(Y.Fragment,{children:EE(n,r)})}function jD(e){let t=DD(),[n,r]=(0,q.useState)(e?.formId),[i,a]=(0,q.useState)(()=>new aD({...e,formId:e?.formId??t}));if(n!==e?.formId){let n=e?.formId??t;a(new aD({...e,formId:n})),r(n)}let o=(0,q.useMemo)(()=>{let e={...i,handleSubmit:((...e)=>i._handleSubmit(...e)),get formId(){return i._formId},get state(){return i.store.state}};return e.Field=function(e){return(0,Y.jsx)(wD,{...e,form:i})},e.FormGroup=function(e){return(0,Y.jsx)(kD,{...e,form:i})},e.Subscribe=function(e){return(0,Y.jsx)(AD,{form:i,selector:e.selector,children:e.children})},e},[i]);SD(i.mount,[]),SD(()=>{i.update(e)});let s=(0,q.useRef)(!1);return SD(()=>{s.current&&e?.transform&&vD(i,e.transform)},[i,e?.transform]),SD(()=>{s.current=!0}),o}var MD=Ti(V),ND=Ti(I({message:V}));function PD(e){for(let t of e.errors){let e=Gr(Lr(Zr(ND(t),e=>e.message),()=>MD(t)));if(e!==void 0&&e.length>0)return e}}var FD={neutral:`progress-neutral`,primary:`progress-primary`,secondary:`progress-secondary`,accent:`progress-accent`,success:`progress-success`,info:`progress-info`,warning:`progress-warning`,error:`progress-error`},ID=(0,q.forwardRef)(function({className:e,tone:t=`primary`,...n},r){return(0,Y.jsx)(`progress`,{...n,"data-complete":n.value!==void 0&&Number(n.value)>=Number(n.max??1)?`true`:void 0,className:E(`progress caps-gooey-motion caps-gooey-progress w-full`,FD[t],e),ref:r})});(0,q.forwardRef)(function({label:e,value:t,max:n,tone:r=`info`,className:i,...a},o){return(0,Y.jsxs)(`div`,{...a,ref:o,className:E(`caps-game-meter`,i),children:[(0,Y.jsxs)(`div`,{className:`caps-game-meter-readout`,children:[(0,Y.jsx)(`span`,{children:e}),(0,Y.jsxs)(`span`,{className:`caps-game-meter-value`,children:[t,` / `,n]})]}),(0,Y.jsx)(ID,{"aria-label":e,value:t,max:n,tone:r})]})});function LD({className:e,items:t,onCancel:n,onRemove:r,onRetry:i,rowClassName:a}){return t.length?(0,Y.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,Y.jsx)(BD,{item:e,onCancel:n,onRemove:r,onRetry:i,...a===void 0?{}:{rowClassName:a}},e.id))}):null}function RD({action:e,id:t,onAction:n,retry:r=!1}){return e?(0,Y.jsx)(Tt,{"aria-label":e.accessibleLabel,title:e.label,variant:`ghost`,size:`xs`,className:`motion-reduce:transition-none`,icon:r?(0,Y.jsx)(dT,{}):(0,Y.jsx)(Ln,{}),onClick:()=>void n(t),type:`button`}):null}function zD({item:e}){return(0,Y.jsxs)(`div`,{className:`min-w-0`,children:[(0,Y.jsx)(`span`,{className:`block min-w-0 truncate`,title:e.name,children:e.name}),(0,Y.jsx)(`div`,{className:`caps-upload-details`,children:(0,Y.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 BD({item:e,onCancel:t,onRemove:n,onRetry:r,rowClassName:i}){return(0,Y.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,Y.jsx)(`img`,{alt:``,className:`caps-upload-preview mask mask-squircle size-8 shrink-0 object-cover`,src:e.preview.url}):(0,Y.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,Y.jsx)(lT,{className:`size-4`})}),(0,Y.jsx)(zD,{item:e}),(0,Y.jsx)(VD,{actions:e.actions,id:e.id,onCancel:t,onRemove:n,onRetry:r}),(0,Y.jsx)(ID,{"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 VD({actions:e,id:t,onCancel:n,onRemove:r,onRetry:i}){return(0,Y.jsxs)(`div`,{className:`caps-upload-actions flex min-w-0 flex-wrap justify-end gap-xs`,children:[(0,Y.jsx)(RD,{action:e.retry,id:t,onAction:i,retry:!0}),(0,Y.jsx)(RD,{action:e.cancel,id:t,onAction:n}),(0,Y.jsx)(RD,{action:e.remove,id:t,onAction:r})]})}var HD=q.createContext(void 0);function UD(e){let t=q.useContext(HD);if(t===void 0&&!e)throw Error(on(47));return t}var WD={...D,disabled:e=>e.disabled,instantType:e=>e.instantType===`trigger-change`&&!D.open(e)?void 0:e.instantType,openMethod:e=>e.openMethod,openChangeReason:e=>e.openChangeReason,isPressOpenedByTrigger:(e,t)=>e.openChangeReason===`trigger-press`&&D.isOpenedByTrigger(e,t),isTouchPressOpen:(e,t)=>t&&e.openMethod===`touch`&&e.openChangeReason===`trigger-press`,hasTriggerFocusGuards:(e,t)=>D.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},GD=class extends se{constructor(e,t,n){let r=new Ke;super(KD(e,r,t,n),qD(r),WD)}setOpen=(e,t)=>{let r=t.reason===he,i=t.reason===`trigger-press`&&t.event.detail===0,a=!e&&(t.reason===`escape-key`||t.reason==null),o=n(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=En(this.state,e,t.trigger,o());n.openChangeReason=t.reason,this.update(n)};r?(this.context.stickIfOpen=!0,this.context.stickIfOpenTimeout.start(500,()=>{this.context.stickIfOpen=!1}),qC.flushSync(c)):c();let l;i?l=`click`:a?l=`dismiss`:t.reason===`focus-out`&&(l=`focus`),this.set(`instantType`,l)}};function KD(e,t,n,r=!1){let i={...Ue(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 qD(e){return{popupRef:q.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerFocusTargetRef:q.createRef(),beforeTriggerFocusGuardRef:q.createRef(),beforeContentFocusGuardRef:q.createRef(),stickIfOpenTimeout:new xn,stickIfOpen:!0,triggerElements:e}}var JD=fn(function({props:e}){let{children:t,open:n,defaultOpen:r=!1,onOpenChange:i,onOpenChangeComplete:a,modal:o=!1,handle:s,triggerId:l,defaultTriggerId:u=null}=e,d=XD(s,{modal:o,open:r,openProp:n,activeTriggerId:u,triggerIdProp:l});d.useControlledProp(`openProp`,n),d.useControlledProp(`triggerIdProp`,l);let f=d.useState(`open`),p=d.useState(`mounted`),m=d.useState(`payload`);d.useContextCallback(`onOpenChange`,i),d.useContextCallback(`onOpenChangeComplete`,a),sn(d,f),nn(d);let{forceUnmount:h}=_n(f,d,()=>{d.context.stickIfOpen=!0,d.set(`openChangeReason`,null)});d.useSyncedValues({modal:o}),q.useEffect(()=>{f||d.context.stickIfOpenTimeout.clear()},[d,f]),q.useImperativeHandle(e.actionsRef,()=>({unmount:h,close:()=>d.setOpen(!1,N(c))}),[h,d]);let g=f||p||s!=null;return(0,Y.jsxs)(HD.Provider,{value:d,children:[s&&(0,Y.jsx)(xe,{handle:s,store:d}),g&&(0,Y.jsx)(ZD,{store:d,modal:o}),typeof t==`function`?t({payload:m}):t]})});function YD(e){return UD(!0)?(0,Y.jsx)(JD,{props:e}):(0,Y.jsx)(Nt,{children:(0,Y.jsx)(JD,{props:e})})}function XD(e,t){let n=it((e,n)=>new GD(t,e,n));return q.useEffect(()=>n.context.stickIfOpenTimeout.disposeEffect(),[n]),n}function ZD({store:e,modal:t}){let n=e.useState(`floatingRootContext`),r=_t(n,{outsidePressEvent:{mouse:t===`trap-focus`?`sloppy`:`intentional`,touch:`sloppy`}}),i=r.reference,a=r.floating;return Ft(e,{activeTriggerProps:i,inactiveTriggerProps:i,popupProps:a}),null}function QD(e,t){function n(n,r,i){let a=n.currentTarget;qC.flushSync(()=>{e.setOpen(!1,N(Ht,n.nativeEvent,a))}),Rn(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&&ke(t,r)?e.context.beforeContentFocusGuardRef.current?.focus():n(t,1,r)}return{handlePreFocusGuardFocus:r,handleFocusTargetFocus:i}}var $D=ae(function(e,t){let{render:n,className:r,style:i,disabled:a=!1,nativeButton:s=!0,handle:c,payload:l,openOnHover:u=!1,delay:d=300,closeDelay:f=0,id:p,...m}=e,h=UD(!0),g=Ie(c)??h;if(!g)throw Error(on(74));let v=tn(p),y=g.useState(`isTriggerActive`,v),b=g.useState(`floatingRootContext`),x=g.useState(`isOpenedByTrigger`,v),S=g.useState(`triggerPopupId`,v),C=q.useRef(null),{registerTrigger:w,isMountedByThisTrigger:T}=Sn(v,C,g,{payload:l,disabled:a,openOnHover:u,closeDelay:f}),E=g.useState(`isPressOpenedByTrigger`,v),D=g.useState(`isTouchPressOpen`,u),O=g.useState(`hasTriggerFocusGuards`,v),k=YC(b,{enabled:!a&&u&&!D,mouseOnly:!0,move:!1,handleClose:rw(),restMs:d,delay:{close:f},triggerElementRef:C,isActiveTrigger:y,isClosing:()=>g.select(`transitionStatus`)===`ending`}),A=Ct(()=>g.context.stickIfOpen),j=wt(b,{stickIfOpen:A}),te=we(()=>g.select(`open`),e=>{g.set(`openMethod`,e)}),ne=g.useState(`triggerProps`,T),{getButtonProps:re,buttonRef:ie}=ee({disabled:a,native:s}),ae={open(e){return E?o.open(e):Lt.open(e)}},{handlePreFocusGuardFocus:oe,handleFocusTargetFocus:se}=QD(g,C),ce=gn(`button`,e,{state:{disabled:a,open:x},ref:[ie,t,w,C],props:[j.reference,k,ne,te,{[ct]:``,id:v,"aria-haspopup":`dialog`,"aria-expanded":x,"aria-controls":S},m,re],stateAttributesMapping:ae}),le=(0,Y.jsx)(q.Fragment,{children:ce},v);return O?(0,Y.jsxs)(q.Fragment,{children:[(0,Y.jsx)(_,{ref:g.context.beforeTriggerFocusGuardRef,onFocus:oe}),le,(0,Y.jsx)(_,{ref:g.context.triggerFocusTargetRef,onFocus:se})]}):le}),eO=q.createContext(void 0);function tO(){let e=q.useContext(eO);if(e===void 0)throw Error(on(45));return e}var nO=q.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e;return UD().useState(`mounted`)||n?(0,Y.jsx)(eO.Provider,{value:n,children:(0,Y.jsx)(Un,{ref:t,...r})}):null}),rO=q.createContext(void 0);function iO(){let e=q.useContext(rO);if(!e)throw Error(on(46));return e}function aO(e){let{nodeId:t,externalTree:n,rootContext:r}=e,i=r.useState(`referenceElement`),a=r.useState(`floatingElement`),o=r.useState(`domReferenceElement`),s=r.useState(`open`),c=r.useState(`floatingId`),[l,u]=q.useState(null),d=q.useRef(null),f=Mn(n),p=q.useMemo(()=>({reference:i,floating:a,domReference:o}),[i,a,o]),m=tT({...e,elements:{...p,...l&&{reference:l}}}),h=q.useCallback(e=>{let t=Ye(e)?{getBoundingClientRect:()=>e.getBoundingClientRect(),getClientRects:()=>e.getClientRects(),contextElement:e}:e;u(t),m.refs.setReference(t)},[m.refs]),g=q.useMemo(()=>({...m.refs,setPositionReference:h,domReference:d}),[m.refs,h]),_=q.useMemo(()=>({...m.elements,domReference:o}),[m.elements,o]),v=q.useMemo(()=>({...m,dataRef:r.context.dataRef,open:s,onOpenChange:r.setOpen,events:r.context.events,floatingId:c,refs:g,elements:_,nodeId:t,rootStore:r}),[m,g,_,t,r,s,c]);return ot(()=>{o&&(d.current=o)},[o]),ot(()=>{r.context.dataRef.current.floatingContext=v;let e=f?.nodesRef.current.find(e=>e.id===t);e&&(e.context=v)}),q.useMemo(()=>({...m,context:v,refs:g,elements:_,rootStore:r}),[m,g,_,v,r])}var oO=e=>({name:`arrow`,options:e,async fn(t){let{x:n,y:r,placement:i,rects:a,platform:o,elements:s,middlewareData:c}=t,{element:l,padding:u=0}=sb(e,t)||{};if(l==null)return{};let d=Tb(u),f={x:n,y:r},p=pb(i),m=db(p),h=await o.getDimensions(l),g=p===`y`,_=g?`top`:`left`,v=g?`bottom`:`right`,y=g?`clientHeight`:`clientWidth`,b=a.reference[m]+a.reference[p]-f[p]-a.floating[m],x=f[p]-a.reference[p],S=s.floating[y]||a.floating[m],C=b/2-x/2,w=S/2-h[m]/2-1,T=Math.min(d[_],w),E=Math.min(d[v],w),ee=T,D=S-h[m]-E,O=S/2-h[m]/2+C,k=ob(ee,O,D),A=!c.arrow&&lb(i)!=null&&O!==k&&a.reference[m]/2-(O<ee?T:E)-h[m]/2<0,j=A?O<ee?O-ee:O-D:0;return{[p]:f[p]+j,data:{[p]:k,centerOffset:O-k-j,...A&&{alignmentOffset:j}},reset:A}}}),sO=(e,t)=>{let{name:n,fn:r}=oO(e);return{name:n,fn:r,options:[e,t]}},cO={name:`hide`,async fn(e){let{width:t,height:n,x:r,y:i}=e.rects.reference,a=t===0&&n===0&&r===0&&i===0,o=await e.platform.detectOverflow(e,{elementContext:`reference`});return{data:{referenceHidden:o.top-n>=0||o.right-t>=0||o.bottom-n>=0||o.left-t>=0||a}}}},lO={sideX:`left`,sideY:`top`},uO=`--available-width`,dO=`--available-height`,fO=`--anchor-width`,pO=`--anchor-height`,mO=`--transform-origin`,hO=uO,gO=dO;function _O(e,t,n){let r=e===`inline-start`||e===`inline-end`;return{top:`top`,right:r?n?`inline-start`:`inline-end`:`right`,bottom:`bottom`,left:r?n?`inline-end`:`inline-start`:`left`}[t]}function vO(e,t,n){let{rects:r,placement:i}=e;return{side:_O(t,cb(i),n),align:lb(i)||`center`,anchor:{width:r.reference.width,height:r.reference.height},positioner:{width:r.floating.width,height:r.floating.height}}}function yO(e){return bO(e,aO)}function bO(e,t){let{anchor:n,positionMethod:r=`absolute`,side:i=`bottom`,sideOffset:a=0,align:o=`center`,alignOffset:s=0,collisionBoundary:c,collisionPadding:l=5,sticky:u=!1,arrowPadding:d=5,disableAnchorTracking:f=!1,inline:p,keepMounted:m=!1,floatingRootContext:g,mounted:_,collisionAvoidance:v,shift:y,nodeId:b,adaptiveOrigin:x,lazyFlip:S=!1,externalTree:C}=e,w=v.side||`flip`,T=v.align||`flip`,E=v.fallbackAxisSide||`end`,ee=y?.crossAxis??!1,D=y?.rootBoundary,O=typeof n==`function`?n:void 0,k=Ct(O),A=O?k:n,j=Fe(n),te=Fe(_),ne=Ub()===`rtl`,[re,ie]=q.useState(null);!_&&re!==null&&ie(null);let ae=S===`placement`,oe=re?cb(re):null,se=re&&ae?lb(re)||`center`:null,ce=oe||{top:`top`,right:`right`,bottom:`bottom`,left:`left`,"inline-end":ne?`left`:`right`,"inline-start":ne?`right`:`left`}[i],le=se||o,ue=le===`center`?ce:`${ce}-${le}`,M=l;typeof M==`number`?M={top:M,right:M,bottom:M,left:M}:M&&={top:M.top||0,right:M.right||0,bottom:M.bottom||0,left:M.left||0};let de=+(i===`bottom`),fe=+(i===`top`),pe=+(i===`right`),me=+(i===`left`),he={boundary:c===`clipping-ancestors`?`clippingAncestors`:c,padding:M},ge=q.useRef(null),_e=Fe(a),ve=Fe(s),ye=typeof a==`function`?0:a,be=typeof s==`function`?0:s,N=[];p&&N.push(p),N.push(nT(e=>{let t=vO(e,i,ne),n=typeof _e.current==`function`?_e.current(t):_e.current,r=typeof ve.current==`function`?ve.current(t):ve.current;return{mainAxis:n,crossAxis:r,alignmentAxis:r}},[ye,be,ne,i]));let xe=T===`none`&&w!==`shift`,Se=!xe&&(u||ee||w===`shift`),Ce=w===`none`?null:aT({...he,padding:{top:M.top+1+de,right:M.right+1+me,bottom:M.bottom+1+fe,left:M.left+1+pe},mainAxis:!ee&&w===`flip`,crossAxis:T===`flip`&&`alignment`,fallbackAxisSideDirection:E}),we=xe?null:rT({...he,rootBoundary:D,mainAxis:T!==`none`,crossAxis:Se,limiter:u||ee?void 0:iT(e=>{if(!ge.current)return{};let{width:t,height:n}=ge.current.getBoundingClientRect(),r=fb(cb(e.placement)),i=r===`y`?t:n,a=r===`y`?M.left+M.right:M.top+M.bottom;return{offset:i/2+a/2}})},[he,u,ee,D,M,T]);w===`shift`||T===`shift`||le===`center`?N.push(we,Ce):N.push(Ce,we),N.push(oT({...he,apply({elements:{floating:e},availableWidth:t,availableHeight:n,rects:r}){if(!te.current)return;let i=e.style;i.setProperty(hO,`${t}px`),i.setProperty(gO,`${n}px`);let a=pn(e).devicePixelRatio||1,{x:o,y:s,width:c,height:l}=r.reference,u=(Math.round((o+c)*a)-Math.round(o*a))/a,d=(Math.round((s+l)*a)-Math.round(s*a))/a;i.setProperty(fO,`${u}px`),i.setProperty(pO,`${d}px`)}}),sO(e=>({element:ge.current||h(e.elements.floating).createElement(`div`),padding:ge.current?d:0}),[d]),{name:`transformOrigin`,fn(e){let{elements:{floating:t},middlewareData:n,placement:r,platform:o,rects:s,y:c}=e,l=cb(r),u=lb(r),d=fb(l)===`y`,f=ge.current,p=typeof a==`function`?a(vO(e,i,ne)):a,m;m=!f&&u&&Math.abs(d?n.shift?.x||0:n.shift?.y||0)<=1?u===`start`===(d&&o.isRTL?.(t)===!0)?`100%`:`0%`:`${(d?n.arrow?.x||0:n.arrow?.y||0)+(d?f?.clientWidth||0:f?.clientHeight||0)/2}px`;let h=l===`top`||l===`left`?`calc(100% + ${p}px)`:`${-p}px`;return Se&&d&&Math.abs(n.shift?.y||0)>p&&(h=`${s.reference.y+s.reference.height/2-c}px`),t.style.setProperty(mO,d?`${m} ${h}`:`${h} ${m}`),{}}},cO,x),ot(()=>{!_&&g&&g.update({referenceElement:null,floatingElement:null,domReferenceElement:null,positionReference:null})},[_,g]);let Te=q.useMemo(()=>({ancestorScroll:!f,elementResize:!f&&typeof ResizeObserver<`u`,layoutShift:!f&&typeof IntersectionObserver<`u`}),[f]),{refs:Ee,elements:De,x:Oe,y:ke,middlewareData:Ae,update:je,placement:Me,context:Ne,isPositioned:Pe,floatingStyles:Ie}=t({rootContext:g,open:m?_:void 0,placement:ue,middleware:N,strategy:r,whileElementsMounted:m?void 0:(...e)=>Uw(...e,Te),nodeId:b,externalTree:C}),{sideX:Le,sideY:Re}=Ae.adaptiveOrigin||lO,ze=Pe?r:`fixed`,Be=q.useMemo(()=>{let e;return e=Pe?x?{position:ze,[Le]:Oe,[Re]:ke}:{...Ie,position:ze}:{position:ze,top:0,left:0},e[hO]=`100vw`,e[gO]=`100vh`,Pe||(e.opacity=0),e},[x,ze,Le,Oe,Re,ke,Ie,Pe]),Ve=q.useRef(null);ot(()=>{if(!_)return;let e=j.current,t=typeof e==`function`?e():e,n=(xO(t)?t.current:t)||null;n!==Ve.current&&(Ee.setPositionReference(n),Ve.current=n)},[_,Ee,A,j]),q.useEffect(()=>{if(!_)return;let e=j.current;typeof e!=`function`&&xO(e)&&e.current!==Ve.current&&(Ee.setPositionReference(e.current),Ve.current=e.current)},[_,Ee,A,j]),q.useEffect(()=>{if(m&&_&&De.reference&&De.floating)return Uw(De.reference,De.floating,je,Te)},[m,_,De,je,Te]);let He=cb(Me),Ue=_O(i,He,ne),We=lb(Me)||`center`,Ge=!!Ae.hide?.referenceHidden;ot(()=>{S&&_&&Pe&&(He!==ce||ae&&We!==le)&&ie(Me)},[S,ae,_,Pe,Me,He,We,ce,le]);let Ke=q.useMemo(()=>({position:`absolute`,top:Ae.arrow?.y,left:Ae.arrow?.x}),[Ae.arrow]),qe=Ae.arrow?.centerOffset!==0;return q.useMemo(()=>({positionerStyles:Be,arrowStyles:Ke,arrowRef:ge,arrowUncentered:qe,side:Ue,align:We,physicalSide:He,anchorHidden:Ge,refs:Ee,context:Ne,isPositioned:Pe,update:je}),[Be,Ke,ge,qe,Ue,We,He,Ge,Ee,Ne,Pe,je])}function xO(e){return e!=null&&`current`in e}function SO(e){let{store:t,domReference:n,positionerElement:r,open:i}=e,a=q.useRef(null),o=q.useRef(null),s=qt(r);ot(()=>{i||(o.current?.abort(),o.current=null,t.state.instantType===`trigger-change`&&t.set(`instantType`,void 0))},[i,t]),ot(()=>{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])}function CO(e){return e===`starting`?zn:On}function wO(e,t,{styles:n,transitionStatus:r,props:i,refs:a,hidden:o,inert:s=!1}){let c={...n};return s&&(c.pointerEvents=`none`),gn(`div`,e,{state:t,ref:a,props:[{role:`presentation`,hidden:o,style:c},CO(r),i],stateAttributesMapping:ve})}var TO=20;function EO(e,t,n,r){let[i,a]=q.useState(!1);ot(()=>{if(!e||!t||n==null){a(!1);return}let r=h(n).documentElement.clientWidth,i=n.offsetWidth;a(r>0&&i>0&&i>=r-TO)},[e,t,n]),Wn(e&&(!t||i),r)}var DO=q.forwardRef(function(e,t){let{render:n,className:r,style:i,anchor:a,positionMethod:o,side:s,align:c,sideOffset:u,alignOffset:d,collisionBoundary:f=`clipping-ancestors`,collisionPadding:p,arrowPadding:m,sticky:h,disableAnchorTracking:g=!1,collisionAvoidance:_=Ae,...v}=e,y=UD(),b=tO(),x=Ot(),S=y.useState(`floatingRootContext`),C=y.useState(`mounted`),w=y.useState(`open`),T=y.useState(`openChangeReason`),E=y.useState(`activeTriggerElement`),ee=y.useState(`modal`),D=y.useState(`openMethod`),O=y.useState(`positionerElement`),k=y.useState(`instantType`),A=y.useState(`transitionStatus`),j=yO({anchor:a,floatingRootContext:S,positionMethod:o,mounted:C,side:s,sideOffset:u,align:c,alignOffset:d,arrowPadding:m,collisionBoundary:f,collisionPadding:p,sticky:h,disableAnchorTracking:g,keepMounted:b,nodeId:x,collisionAvoidance:_,adaptiveOrigin:y.useState(`adaptiveOrigin`)});SO({store:y,domReference:S.useState(`domReferenceElement`),positionerElement:O,open:w});let te=ee===!0&&T!==`trigger-hover`;EO(w&&te,D===`touch`,O,E);let ne=y.useStateSetter(`positionerElement`),re=wO(e,{open:w,side:j.side,align:j.align,anchorHidden:j.anchorHidden,instant:k},{styles:j.positionerStyles,transitionStatus:A,props:v,refs:[t,ne],hidden:!C,inert:!w});return(0,Y.jsxs)(rO.Provider,{value:j,children:[C&&te&&(0,Y.jsx)(l,{inert:ze(!w),cutout:E}),(0,Y.jsx)(Qt,{id:x,children:re})]})}),OO=q.createContext(void 0);function kO(e){let t=q.useContext(OO);if(t===void 0&&!e)throw Error(on(69));return t}var AO=q.createContext(void 0);function jO(){let[e,t]=q.useState(0),n=Ct(()=>(t(e=>e+1),()=>{t(e=>Math.max(0,e-1))}));return{context:q.useMemo(()=>({register:n}),[n]),hasClosePart:e>0}}var MO=q.forwardRef(function(e,t){let{render:n,className:r,style:i,initialFocus:a,finalFocus:o,...s}=e,c=UD(),l=iO(),u=kO(!0)!=null,{context:d,hasClosePart:f}=jO(),p=c.useState(`open`),m=c.useState(`openMethod`),h=c.useState(`instantType`),g=c.useState(`transitionStatus`),_=c.useState(`popupProps`),v=c.useState(`titleElementId`),y=c.useState(`descriptionElementId`),b=c.useState(`modal`),x=c.useState(`mounted`),S=c.useState(`openChangeReason`),C=c.useState(`activeTriggerElement`),w=c.useState(`floatingRootContext`),T=w.useState(`floatingId`),E=c.useState(`disabled`),ee=c.useState(`openOnHover`),D=c.useState(`closeDelay`);pt({open:p,ref:c.context.popupRef,onComplete(){p&&c.context.onOpenChangeComplete?.(!0)}}),KC(w,{enabled:ee&&!E,closeDelay:D});let O=a===void 0?bt(c.context.popupRef):a,k=b!==!1&&f;c.useSyncedValue(`focusManagerModal`,k);let j=c.useStateSetter(`popupElement`),te={open:p,side:l.side,align:l.align,instant:h,transitionStatus:g},ne=gn(`div`,e,{state:te,ref:[t,c.context.popupRef,j],props:[_,{id:T,role:`dialog`,...Xe,"aria-labelledby":v,"aria-describedby":y,onKeyDown(e){u&&A.has(e.key)&&e.stopPropagation()}},CO(g),s],stateAttributesMapping:Vt});return(0,Y.jsx)(dn,{context:w,openInteractionType:m,modal:k,disabled:!x||S===`trigger-hover`,initialFocus:O,returnFocus:o,restoreFocus:`popup`,getInsideElements:()=>[c.context.beforeTriggerFocusGuardRef.current],previousFocusableElement:qe(C)?C:void 0,nextFocusableElement:c.context.triggerFocusTargetRef,beforeContentFocusGuardRef:c.context.beforeContentFocusGuardRef,children:(0,Y.jsx)(AO.Provider,{value:d,children:ne})})}),NO=(0,q.forwardRef)(function({children:e,className:t,type:n=`button`,...r},i){return(0,Y.jsxs)(`button`,{...r,ref:i,type:n,className:E(`select caps-select caps-combobox-trigger w-full`,t),children:[(0,Y.jsx)(`span`,{children:e}),(0,Y.jsx)(p,{className:`caps-select-chevron`,"aria-hidden":`true`})]})});function PO({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=mt({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 ee=e=>{v(!1),e||g(``),d===void 0&&S(e),c?.(e)},D=e=>`${m}-option-${encodeURIComponent(e)}`,O=e=>{let t=n(e);f===void 0&&b(t),l(e),p&&!u&&ee(!1)},k=e=>{v(!0),g(e.target.value),E.setActiveKey(null)},A=e=>{if($e(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(),O(E.activeItem))},j=(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:j,inputValue:h,listboxId:m,onInputChange:k,onInputKeyDown:A,optionId:D,open:w,commit:O,selectedKeys:C,setOpen:ee}}function FO(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:ee,rootRef:D,trigger:O,triggerRef:k,value:A,...j}=e,te=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)},re;C?re=A:A!==void 0&&(re=A===null?[]:[A]);let ie=(0,q.useId)(),ae=O?.props??_,oe=g??ae?.id??ie,se={id:oe,"aria-describedby":[t,ae?.[`aria-describedby`]].filter(Boolean).join(` `)||void 0,"aria-invalid":n??ae?.[`aria-invalid`],"aria-label":ae?.[`aria-label`]??r,"aria-labelledby":ae?.[`aria-labelledby`]??i,"aria-required":a??ae?.[`aria-required`]},{keyboardNavigation:ce,onPointerMove:le,activeItem:M,activeKey:de,commit:fe,groups:pe,inputValue:me,listboxId:he,onInputChange:ge,onInputKeyDown:_e,open:ve,optionId:ye,selectedKeys:be,setOpen:N}=PO({defaultOpen:l,defaultValue:u,getKey:f,getSearchText:m,groupBy:h,id:oe,isDisabled:y,items:b,onOpenChange:x,onCommit:te,multiple:C??!1,controlledOpen:w,controlledKeys:re,trigger:O});ne(()=>{O&&N(!1)});let xe=ue(`popover`),Se=s===void 0?xe:s,Ce=xt(`.caps-combobox-option[data-active="true"]:not(:disabled), [data-navigation="pointer"] .caps-combobox-option:hover:not(:disabled)`),we=(0,Y.jsx)(cn,{..._,...O?{}:se,"aria-activedescendant":M?ye(f(M)):void 0,"aria-autocomplete":`list`,"aria-controls":he,"aria-expanded":!0,className:E(`input-sm`,_?.className),id:O?_?.id??`${oe}-input`:oe,onChange:e=>{_?.onChange?.(e),ge(e)},onKeyDown:e=>{_?.onKeyDown?.(e),e.defaultPrevented||_e(e)},placeholder:_?.placeholder??T,ref:v,role:`combobox`,value:me}),Te=(0,Y.jsx)(`div`,{id:he,ref:Ce,className:`caps-combobox-list`,"data-navigation":ce?`keyboard`:`pointer`,onPointerMove:le,role:`listbox`,"aria-multiselectable":C??void 0,children:pe.every(e=>e.items.length===0)?(0,Y.jsx)(`div`,{className:`px-md py-md text-sm text-base-content`,children:d}):pe.map(e=>(0,Y.jsxs)(`div`,{"aria-label":e.label||void 0,role:e.label?`group`:void 0,children:[e.label?(0,Y.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=de===t,i={active:r,disabled:n,selected:be.includes(t)};return(0,Y.jsxs)(`button`,{"aria-disabled":n||void 0,"aria-selected":i.selected,className:`caps-combobox-option`,"data-active":r&&ce,disabled:n,id:ye(t),onClick:()=>{fe(e)},onMouseDown:e=>{e.preventDefault()},role:`option`,tabIndex:-1,type:`button`,children:[(0,Y.jsx)(`span`,{"aria-hidden":`true`,className:`caps-combobox-check`,children:i.selected?(0,Y.jsx)(Nn,{}):null}),ee?.(e,r,i)??p(e)]},t)})]},e.label))});return O?(0,Y.jsx)(`div`,{...j,className:E(j.className),ref:D,children:(0,Y.jsxs)(YD,{modal:!0,onOpenChange:N,open:ve,children:[(0,Y.jsx)($D,{...se,"aria-haspopup":`dialog`,className:`btn`,ref:k,render:O}),Se===null?null:(0,Y.jsx)(nO,{container:Se,children:(0,Y.jsx)(DO,{align:`start`,side:`bottom`,sideOffset:4,children:(0,Y.jsxs)(MO,{"data-active-tone":o,className:E(`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,Y.jsx)(`div`,{className:`caps-combobox-search`,children:we}),Te]})})})]})}):(0,Y.jsx)(`div`,{...j,className:E(j.className),ref:D,children:(0,Y.jsxs)(`div`,{className:E(`caps-combobox-panel`,c),"data-active-tone":o,children:[(0,Y.jsx)(`div`,{className:`caps-combobox-search`,children:we}),Te]})})}function IO({icon:e,caption:t}){return(0,Y.jsxs)(`span`,{className:`caps-icon-choice-mark`,"aria-hidden":`true`,children:[(0,Y.jsx)(`span`,{className:`caps-icon-choice-art`,children:e}),t?(0,Y.jsx)(`span`,{className:`caps-icon-choice-caption`,children:t}):null,(0,Y.jsx)(`span`,{className:`caps-icon-choice-lamp`})]})}var LO=(0,q.forwardRef)(function({label:e,icon:t,caption:n,appearance:r,className:i,...a},o){return(0,Y.jsx)(`label`,{className:`caps-icon-choice`,"data-appearance":r===`compact`?r:void 0,children:(0,Y.jsx)(Jt,{...a,appearance:r??`default`,"aria-label":e,className:E(`caps-icon-choice-input`,i),indicator:(0,Y.jsx)(IO,{icon:t,caption:n}),ref:o})})}),RO=(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,Y.jsx)(`label`,{className:`caps-check-key`,children:(0,Y.jsx)(Jt,{...i,"aria-label":e,"aria-describedby":s,className:E(`caps-check-key-input`,r),indicator:(0,Y.jsxs)(`span`,{className:`caps-check-key-face`,"aria-hidden":`true`,children:[t?(0,Y.jsx)(`span`,{className:`caps-check-key-icon`,children:t}):null,(0,Y.jsxs)(`span`,{className:`caps-check-key-copy`,children:[(0,Y.jsx)(`span`,{className:`caps-check-key-label`,children:e}),n?(0,Y.jsx)(`span`,{className:`caps-check-key-hint`,id:o,children:n}):null]}),(0,Y.jsx)(`span`,{className:`caps-check-key-lamp`})]}),ref:a})})});function zO({className:e,...t}){return(0,Y.jsx)(`div`,{...t,className:E(`caps-check-keys`,e)})}function BO({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=In(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=Dt(o,{ease:`outCubic`,duration:75}),c=e?et(o,{bounce:.65,duration:300}):Dt(o,{ease:`inCubic`,duration:100}),l=go(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,Y.jsxs)(`svg`,{ref:a,className:`caps-radio-visual`,width:`24`,height:`24`,viewBox:`0 0 12 12`,"aria-hidden":`true`,focusable:`false`,children:[(0,Y.jsxs)(`defs`,{children:[(0,Y.jsx)(Hn,{id:`${t}-surface`,transform:`matrix(1 0 0 1 6 6)`}),(0,Y.jsx)(jn,{id:`${t}-shadow`}),(0,Y.jsx)(tt,{id:`${t}-inset`}),(0,Y.jsx)(`clipPath`,{id:`${t}-well`,children:(0,Y.jsx)(`circle`,{cx:`6`,cy:`6`,r:`5`})})]}),(0,Y.jsx)(`circle`,{className:`caps-radio-track`,cx:`6`,cy:`6`,r:`5.5`,filter:`url(#${t}-inset)`}),(0,Y.jsx)(`g`,{clipPath:`url(#${t}-well)`,children:(0,Y.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 VO=(0,q.createContext)(null),HO=(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,Y.jsx)(VO.Provider,{value:{disabled:r,name:f,onValueChange:e=>{s===void 0&&m(e),a?.(e)},value:h},children:(0,Y.jsx)(`fieldset`,{...c,className:E(`flex gap-md`,o===`horizontal`?`flex-row flex-wrap`:`flex-col`,t),disabled:r,role:c.role??`radiogroup`,ref:d,children:e})})}),UO=(0,q.forwardRef)(function({className:e,indicator:t,onChange:n,onClick:r,value:i,...a},o){let s=(0,q.useContext)(VO);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,Y.jsxs)(`span`,{className:`caps-radio`,"data-checked":c,"data-custom-indicator":t!==void 0||void 0,children:[(0,Y.jsx)(`input`,{...a,"aria-checked":c,checked:c,className:E(`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,Y.jsx)(BO,{checked:c}):t]})}),WO=(0,q.forwardRef)(function({description:e,id:t,meta:n,title:r,...i},a){let o=(0,q.useContext)(VO),s=(0,q.useId)(),c=t??s,l=o?.value===i.value,u=o?.disabled===!0||i.disabled===!0;return(0,Y.jsxs)(`label`,{className:`caps-choice-card`,"data-checked":l,"data-disabled":u||void 0,htmlFor:c,children:[(0,Y.jsx)(UO,{...i,"aria-describedby":e?`${c}-description`:void 0,"aria-labelledby":`${c}-title`,id:c,ref:a}),(0,Y.jsxs)(`span`,{className:`caps-choice-card-copy`,children:[(0,Y.jsx)(`span`,{className:`caps-choice-card-title`,id:`${c}-title`,children:r}),e?(0,Y.jsx)(`span`,{className:`caps-choice-card-description`,id:`${c}-description`,children:e}):null]}),n?(0,Y.jsx)(`span`,{className:`caps-choice-card-meta`,children:n}):null]})}),GO=(0,q.forwardRef)(function({label:e,icon:t,caption:n,art:r=`dim`,className:i,...a},o){return(0,Y.jsx)(`label`,{className:`caps-icon-choice`,"data-art":r===`color`?r:void 0,children:(0,Y.jsx)(UO,{...a,"aria-label":e,className:E(`caps-icon-choice-input`,i),indicator:(0,Y.jsx)(IO,{icon:t,caption:n}),ref:o})})}),KO=(0,q.forwardRef)(function({label:e,color:t,className:n,...r},i){return(0,Y.jsx)(`label`,{className:`caps-icon-choice`,"data-art":`color`,"data-swatch":``,title:e,children:(0,Y.jsx)(UO,{...r,"aria-label":e,className:E(`caps-icon-choice-input`,n),indicator:(0,Y.jsx)(IO,{icon:(0,Y.jsx)(`span`,{className:`caps-swatch-dot`,style:{backgroundColor:t}})}),ref:i})})}),qO=(0,q.forwardRef)(function({className:e,invalid:t,...n},r){return(0,Y.jsxs)(`span`,{className:`caps-select-shell`,children:[(0,Y.jsx)(`select`,{...n,"aria-invalid":t?!0:n[`aria-invalid`]===!1?void 0:n[`aria-invalid`],className:E(`select select-bordered caps-select w-full`,t&&`select-error`,e),ref:r}),!n.multiple&&(!n.size||n.size<=1)?(0,Y.jsx)(p,{className:`caps-select-chevron`,"aria-hidden":`true`}):null]})});function JO({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=Pe();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=g(n.current),c=et(s,{bounce:.25,duration:440}),l=Dt(s,{ease:`inOutSine`,duration:100}),u=go(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=go(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,Y.jsxs)(`svg`,{className:`caps-switch-visual`,width:`40`,height:`24`,viewBox:`0 0 20 12`,"aria-hidden":`true`,focusable:`false`,children:[(0,Y.jsxs)(`defs`,{children:[(0,Y.jsx)(Hn,{ref:r,id:`${t}-surface`,transform:i?`matrix(2 0 0 1 10 6)`:`matrix(1 0 0 1 6 6)`}),(0,Y.jsx)(jn,{id:`${t}-shadow`}),(0,Y.jsx)(tt,{id:`${t}-inset`}),(0,Y.jsx)(`clipPath`,{id:`${t}-track`,children:(0,Y.jsx)(`rect`,{x:`1`,y:`1`,width:`18`,height:`10`,rx:`5`})})]}),(0,Y.jsx)(`rect`,{className:`caps-switch-track`,filter:`url(#${t}-inset)`,x:`0.5`,y:`0.5`,width:`19`,height:`11`,rx:`5.5`}),(0,Y.jsx)(`g`,{clipPath:`url(#${t}-track)`,children:(0,Y.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 YO=(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,Y.jsxs)(`span`,{className:`caps-switch`,"data-checked":u,children:[(0,Y.jsx)(`input`,{...a,checked:u,className:E(`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,Y.jsx)(JO,{checked:u})]})}),XO=Ti(V),ZO=Ti(Ua),QO=Ti(oo(Sa)),$O=Ti(W(V)),ek=W(ua(File)),tk=Ti(ek),nk=F([V,Sa,Ua,to,qi,W(V),ek]),rk=Ti(nk),ik=e=>si(XO(e.state.value),()=>``),ak=e=>si(ZO(e.state.value),()=>!1),ok=e=>si(QO(e.state.value),()=>null),sk=e=>si($O(e.state.value),()=>[]),ck=e=>si(tk(e.state.value),()=>[]),lk=e=>si(rk(e.state.value),()=>null);function uk({field:e,spec:t,locked:n,...r}){let[i,a]=(0,q.useState)(!1);return(0,Y.jsxs)(lt,{children:[(0,Y.jsx)(cn,{...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:ik(e),onBlur:e.handleBlur,onChange:t=>{e.handleChange(t.currentTarget.value)}}),(0,Y.jsx)(Zt,{type:`button`,variant:`outline`,size:`icon`,"aria-label":i?`Hide`:`Show`,"aria-pressed":i,disabled:n,onClick:()=>{a(e=>!e)},children:i?(0,Y.jsx)(sT,{"aria-hidden":`true`}):(0,Y.jsx)(cT,{"aria-hidden":`true`})})]})}var dk={text:`text`,email:`email`,url:`url`,tel:`tel`};function fk({spec:e,field:t,locked:n,...r}){let i=ck(t),a=n||e.readOnly===!0,o=(0,q.useRef)(null);return(0,Y.jsxs)(`div`,{className:`flex flex-col gap-sm`,children:[(0,Y.jsx)(st,{asChild:!0,children:(0,Y.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,Y.jsx)(Zt,{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,Y.jsx)(LD,{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 pk({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,Y.jsx)(cn,{...a,type:dk[e.kind],inputMode:e.kind===`text`?void 0:e.kind,autoComplete:e.autoComplete,placeholder:e.placeholder,maxLength:e.maxLength,readOnly:e.readOnly,value:ik(t),onChange:e=>{i(e.currentTarget.value)}});case`textarea`:return(0,Y.jsx)(kt,{...a,rows:e.rows??3,placeholder:e.placeholder,maxLength:e.maxLength,readOnly:e.readOnly,value:ik(t),onChange:e=>{i(e.currentTarget.value)}});case`secret`:return(0,Y.jsx)(uk,{...r,field:t,spec:e,locked:n});case`money`:return(0,Y.jsxs)(lt,{children:[(0,Y.jsx)(Ut,{className:`caps-field-currency`,children:e.currency??`USD`}),(0,Y.jsx)(cn,{...a,inputMode:`decimal`,autoComplete:`off`,className:`caps-field-amount`,placeholder:e.placeholder??`0.00`,readOnly:e.readOnly,value:ik(t),onChange:e=>{i(e.currentTarget.value)}})]});case`date`:return(0,Y.jsx)(cn,{...a,type:`date`,readOnly:e.readOnly,value:ik(t),onChange:e=>{i(e.currentTarget.value)}});case`number`:return(0,Y.jsx)(vn,{...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:ok(t),onValueChange:e=>{t.handleChange(e)}});case`select`:return(0,Y.jsxs)(qO,{...a,value:ik(t),onChange:e=>{i(e.currentTarget.value)},children:[e.placeholder===void 0?null:(0,Y.jsx)(`option`,{value:``,disabled:!0,children:e.placeholder}),e.options.map(e=>(0,Y.jsx)(`option`,{value:e.value,disabled:e.disabled,children:e.label},e.value))]});case`combobox`:return(0,Y.jsx)(FO,{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:ik(t),...e.placeholder===void 0?{}:{placeholder:e.placeholder},trigger:(0,Y.jsx)(NO,{name:e.name,disabled:n||e.readOnly===!0,onBlur:t.handleBlur,children:e.options.find(e=>e.value===ik(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,Y.jsx)(fk,{...r,spec:e,field:t,locked:n});case`checkbox`:return(0,Y.jsx)(Jt,{...a,disabled:n||e.readOnly===!0,checked:ak(t),onChange:e=>{t.handleChange(e.currentTarget.checked)}});case`switch`:return(0,Y.jsx)(YO,{...a,disabled:n||e.readOnly===!0,checked:ak(t),onCheckedChange:e=>{t.handleChange(e)}});case`radio`:case`icon-radio`:case`checkboxes`:case`icon-checkboxes`:return null}}var mk=new Set([`radio`,`icon-radio`,`checkboxes`,`icon-checkboxes`]);function hk({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=sk(t),s=(e,r)=>{t.handleChange(r?[...n,e]:n.filter(t=>t!==e))};return(0,Y.jsx)(hn,{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,Y.jsx)(`div`,{className:`caps-field-icon-choices`,children:e.options.map(r=>(0,Y.jsx)(LO,{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,Y.jsx)(zO,{children:e.options.map(r=>(0,Y.jsx)(RO,{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,Y.jsx)(hn,{legend:o,icon:e.icon,layout:i,...i===`columns`?{legendTitle:o}:{},description:e.help,disabled:a,error:r??null,children:(0,Y.jsx)(HO,{name:e.name,"aria-label":o,value:ik(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,Y.jsx)(GO,{value:t.value,label:t.label,...t.caption===void 0?{}:{caption:t.caption},icon:t.icon,disabled:t.disabled},t.value):s?(0,Y.jsx)(WO,{value:t.value,title:t.label,description:t.description,meta:t.meta,disabled:t.disabled},t.value):(0,Y.jsx)($t,{label:t.label,orientation:`inline`,children:(0,Y.jsx)(UO,{value:t.value,disabled:t.disabled})},t.value))})})}function gk({spec:e,field:t,locked:n,error:r,render:i,...a}){return i({name:e.name,label:e.label,help:e.help,value:lk(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 _k({form:e,spec:t,locked:n,layout:r}){let i=CD({form:e,name:t.name}),a=xD(e.store,e=>e.submissionAttempts>0),o=i.state.meta.isBlurred||a?PD(i.state.meta):void 0;if(t.render===void 0&&mk.has(t.kind))return(0,Y.jsx)(hk,{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,Y.jsx)($t,{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,Y.jsx)(pk,{spec:t,field:i,locked:n}):(0,Y.jsx)(gk,{spec:t,field:i,locked:n,error:o,render:t.render})})}var vk=Ti(io(V,nk));function yk({form:e,spec:t,locked:n,layout:r}){let i=t.when;return xD(e.store,e=>i===void 0||i(si(vk(e.values),()=>({}))))?(0,Y.jsx)(_k,{form:e,spec:t,locked:n,layout:r}):null}function bk({form:e,section:t,locked:n,layout:r}){let i=t.fields.map(t=>(0,Y.jsx)(yk,{form:e,spec:t,locked:n,layout:r},t.name));return t.title===void 0?i:(0,Y.jsx)(rn,{title:t.title,description:t.description,layout:r,children:i})}function xk({model:e,names:t,disabled:n=!1,layout:r}){let i=e.form;return t===void 0?e.description.sections.map(e=>(0,Y.jsx)(bk,{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,Y.jsx)(yk,{form:i,spec:a,locked:n,layout:r},t)})}var Sk=class{annotation;constructor(e){this.annotation=e}},Ck=class{sections;constructor(e){this.sections=e}},wk=`caps/form`,Tk=0;function Ek(e){Tk+=1;let t={[`${wk}:${String(Tk)}`]:new Sk(e)};return e.label!==void 0&&(t.title=e.label),e.help!==void 0&&(t.description=e.help),t}V.annotate(Ek({kind:`secret`})).pipe(Gi(`Secret`));var Dk=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 Ok(e){return Object.values(e??{}).reduce((e,t)=>t instanceof Sk?{...e,...t.annotation}:e,{})}function kk(e){return e.reduce((e,t)=>({...e,...Ok(t)}),{})}function Ak(e){let t=e?.[wk];return t instanceof Ck?t.sections:{}}var jk=Ti(V);function Mk(e){if(la(e))return pi(jk(e.literal),{onNone:()=>null,onSome:e=>[e]});if(!Qa(e))return null;let t=[];for(let n of e.types){if(Ea(n))continue;let e=Mk(n);if(e===null)return null;t.push(...e)}return t}function Nk(e){if(Si(e))return{type:`string`,literals:[]};if(pa(e))return{type:`number`,nullable:!1};if(Ya(e))return{type:`boolean`};let t=Mk(e);if(t!==null)return{type:`string`,literals:t};if(Hi(e)){let[t]=e.rest;if(t===void 0)return null;if(Si(t))return{type:`strings`,literals:[]};let n=Mk(t);return n===null?null:{type:`strings`,literals:n}}if(Qa(e)){let t=e.types.filter(e=>!Ea(e)&&!sa(e)),n=e.types.some(e=>sa(e)),[r]=t;if(t.length!==1||r===void 0)return null;let i=Nk(r);return i?.type===`number`?{type:`number`,nullable:n}:n?null:i}return null}function Pk(e){let t=e.ast;if(!Xi(t))throw Error(`A schema form needs a Schema.Struct.`);return{fields:t.propertySignatures.map(e=>{let t=String(e.name),n=va(e.type),r=kk([e.type.annotations,...(e.type.checks??[]).map(e=>e.annotations)]),i=r.kind===`file`?{type:`files`}:Nk(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:ja(e.type),description:Za(e.type)}}),sections:Ak(Va(t))}}function Fk(e){let t=e,n=!1,r=!1;for(;;)if(t instanceof cr)n=!0,t=t.unwrap();else if(t instanceof _r)r=!0,t=t.unwrap();else if(t instanceof Yn)t=t.unwrap();else if(t instanceof ai)t=t.in;else return{node:t,optional:n,nullable:r}}function Ik(e){if(e instanceof xr){let t=e.options.map(e=>Ik(e));return t.some(e=>e===null)?null:t.flatMap(e=>e??[])}let t=e instanceof yr?e.options:e instanceof rr?[...e.values]:null;if(t===null)return null;let n=t.map(e=>jk(e));return n.every(ui)?n.map(e=>e.value):null}function Lk(e){let{node:t,nullable:n}=Fk(e);if(t instanceof ar)return{type:`string`,literals:[]};if(t instanceof br)return{type:`number`,nullable:n};if(t instanceof xi)return{type:`boolean`};let r=Ik(t);if(r!==null)return{type:`string`,literals:r};if(t instanceof mr){let e=Fk(t.element).node;if(e instanceof ar)return{type:`strings`,literals:[]};let n=Ik(e);return n===null?null:{type:`strings`,literals:n}}return null}function Rk(e){let t=[e];for(;;){let e=t[t.length-1];if(e===void 0)break;let n=e instanceof cr||e instanceof _r||e instanceof Yn?e.unwrap():e instanceof ai?e.in:e;if(n===e)break;t.push(n)}return t.reverse().map(e=>tr.get(e))}function zk(e){return Rk(e).reduce((e,t)=>({...e,...t}),{})}function Bk(e){return Object.entries(e.shape)}function Vk(e){let t=Fk(e).node;if(!(t instanceof nr))throw Error(`A schema form needs a z.object.`);return{fields:Bk(t).map(([e,t])=>{let n=kk(Rk(t)),r=n.kind===`file`?{type:`files`}:Lk(t);if(r===null)throw Error(`Schema field "${e}" has no form control. Annotate it with field({ render }) or a kind.`);let i=zk(t);return{name:e,valueType:r,optional:Fk(t).optional,annotation:n,title:i.title,description:i.description}}),sections:Ak(zk(e))}}function Hk(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??Dk(e),description:r.description,meta:r.meta,icon:r.icon,caption:r.caption,disabled:r.disabled===!0}})}function Uk(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 Wk(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 Gk(e){let t=e instanceof Cr?Vk(e):Pk(e),n=t.fields.map((e,t)=>{let{kind:n,...r}=e.annotation,i=Hk(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??Dk(e.name),help:a,kind:n??Uk(e.valueType,i),options:i,optionalInSchema:e.optional,index:t}}),r={};t.fields.forEach((e,t)=>{let i=n[t];i&&(r[e.name]=Wk(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 Kk(e){let t=e instanceof Cr?e:ra(e);return{"~standard":{...t[`~standard`],validate:e=>{let n=t[`~standard`].validate(e);return n instanceof Promise?n.then(e=>qk(e)):qk(n)}}}}function qk(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 Jk=`onServer`;function Yk(e){let t=e.querySelector(`[aria-invalid="true"]`),n=t?.matches(`input, select, textarea, button, [tabindex]`)?t:t?.querySelector(`input, select, textarea, button`);return n?.focus(),n!=null}function Xk(e){if(Yk(e))return()=>void 0;let t=new MutationObserver(()=>{Yk(e)&&t.disconnect()});return t.observe(e,{subtree:!0,childList:!0,attributes:!0,attributeFilter:[`aria-invalid`]}),()=>{t.disconnect()}}function Zk(e){return e.state.meta.errorMap.onServer!==void 0}function Qk(e){e.setMeta(e=>({...e,errorMap:{...e.errorMap,[Jk]:void 0}}))}function $k(e,t,n){e.setFieldMeta(t,e=>({...e,isBlurred:!0,errorMap:{...e.errorMap,[Jk]:n}}))}function eA(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);BE(a,e.defaultValues)||(o(e.defaultValues),c(null));let{schema:l}=e,u=(0,q.useMemo)(()=>Gk(l),[l]),d=(0,q.useMemo)(()=>Kk(l),[l]),f=jD({defaultValues:s??a,validators:{onChange:d,onSubmit:d},listeners:{onChange:({fieldApi:e})=>{n(null),i(null),Zk(e)&&Qk(e)}},onSubmit:async({value:t,formApi:r})=>{n(null),i(null);let a=await Kk(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&&$k(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 tA(e){return{dirty:xD(e.form.store,e=>!e.isDefaultValue),submitting:xD(e.form.store,e=>e.isSubmitting),canSubmit:xD(e.form.store,e=>e.canSubmit)}}function nA({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}=tA(e),f=(0,q.useRef)(null),p=(0,q.useRef)(()=>void 0);return(0,q.useEffect)(()=>()=>{p.current()},[]),(0,Y.jsxs)(Pt,{...u,ref:f,layout:o,busy:d,noValidate:!0,onSubmit:t=>{t.preventDefault(),e.form.state.isSubmitting||e.submit().then(()=>{p.current();let t=f.current;t!==null&&!e.form.state.isValid&&(p.current=Xk(t))})},children:[c??(0,Y.jsx)(xk,{model:e,disabled:l,layout:o}),s===void 0?(0,Y.jsx)(aA,{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 rA({schema:e,defaultValues:t,onSubmit:n,onSaved:r,failure:i,...a}){let o=eA({schema:e,defaultValues:t,onSubmit:n,onSaved:r,failure:i});return(0,Y.jsx)(nA,{...a,model:o})}function iA(e){return`model`in e?(0,Y.jsx)(nA,{...e}):(0,Y.jsx)(rA,{...e})}function aA({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}=tA(e),d=u?null:e.saved&&!l?(0,Y.jsx)(fe,{tone:`success`,size:`compact`,label:e.saved}):l?(0,Y.jsx)(fe,{tone:`neutral`,size:`compact`,label:o}):null;return(0,Y.jsxs)(rt,{...c,error:e.error,status:d,children:[r?(0,Y.jsx)(Zt,{type:`button`,variant:`ghost`,disabled:u,onClick:r,children:i}):n&&l?(0,Y.jsx)(Zt,{type:`button`,variant:`ghost`,disabled:u,onClick:e.discard,children:n}):null,(0,Y.jsx)(Zt,{...s,type:`submit`,loading:u,disabled:u||!l&&!a,title:!l&&!a?`No changes to save`:void 0,children:t})]})}var oA=e=>e,sA=(e,t)=>{let n=e[t];if(!n)throw Error(`Missing burger path: ${t}`);return n},cA={apiVersion:1,name:`burger`,palette:{bottomBun:`#e9c46a`,bunSpot:`#d4a373`,cheese:`#f4d03f`,dead:`#636e72`,deadTongue:`#b2bec3`,eye:`#2d3436`,lettuce:`#7cb342`,mouth:`#2d3436`,patty:`#5d4037`,tomato:`#e74c3c`,topBun:`#f4a261`,blush:`#feaae4`,tongue:`#f98284`,sweat:`#accce4`,white:`#ffffff`},build({scene:e,color:t}){let n=e.group({name:`root`}),r=e.group({parent:n,name:`body`,updateSort:!0});e.cylinder({parent:r,name:`bottom-bun`,backface:t(`bottomBun`),color:t(`bottomBun`),diameter:34,frontFace:t(`bunSpot`),length:6,rotate:{x:Math.PI/2},stroke:!1,translate:{y:8}}),e.cylinder({parent:r,name:`patty`,color:t(`patty`),diameter:36,frontFace:t(`patty`),length:4,rotate:{x:Math.PI/2},stroke:!1,translate:{y:3}}),e.cylinder({parent:r,name:`tomato`,color:t(`tomato`),diameter:34,frontFace:t(`tomato`),length:2,rotate:{x:Math.PI/2},stroke:!1,translate:{y:-2}});let i=e.hemisphere({parent:r,name:`top-bun`,backface:t(`bunSpot`),color:t(`topBun`),diameter:38,rotate:{x:Math.PI/2},stroke:!1,translate:{y:-3}});for(let[n,r]of[{x:-8,y:-6,z:14},{x:6,y:-8,z:13},{x:0,y:-10,z:12},{x:10,y:-4,z:13},{x:-5,y:-2,z:15},{x:4,y:-12,z:11}].entries())e.path({parent:i,name:`seed.${String(n+1)}`,path:[{x:0,y:0}],color:t(`bunSpot`),stroke:1.2,translate:r});let a=e.group({parent:r,name:`face`,translate:{y:-5,z:16}}),o=xo(e,t,a,{blushMode:`medium-alias`,hideMouth:!0}),s=e.group({parent:r,name:`burger.mouth`,translate:{y:1,z:10}}),c=oA({angry:[{x:-13,y:2},{x:13,y:2},{x:13,y:5},{bezier:[{x:7,y:4},{x:0,y:5},{x:-7,y:4}]},{x:-13,y:5}],happy:[{x:-12,y:0},{bezier:[{x:-6,y:3},{x:0,y:5},{x:6,y:3}]},{x:12,y:0},{x:13,y:2},{bezier:[{x:7,y:5},{x:0,y:7},{x:-7,y:5}]},{x:-13,y:2}],open:[{x:-10,y:0},{bezier:[{x:-10,y:5},{x:-5,y:8},{x:0,y:8}]},{bezier:[{x:5,y:8},{x:10,y:5},{x:10,y:0}]},{x:10,y:1},{bezier:[{x:5,y:6},{x:-5,y:6},{x:-10,y:1}]}],pout:[{x:-8,y:2},{bezier:[{x:0,y:5},{x:8,y:2},{x:8,y:4}]},{x:0,y:6},{x:-8,y:4}],sad:[{x:-12,y:3},{bezier:[{x:-6,y:0},{x:0,y:-1},{x:6,y:0}]},{x:12,y:3},{x:13,y:5},{bezier:[{x:7,y:2},{x:0,y:1},{x:-7,y:2}]},{x:-13,y:5}],small:[{x:-6,y:1},{x:6,y:1},{x:7,y:3},{x:0,y:2},{x:-7,y:3}],surprised:[],worried:[{x:-11,y:1},{bezier:[{x:-6,y:3},{x:-3,y:1},{x:0,y:2}]},{bezier:[{x:3,y:1},{x:6,y:3},{x:11,y:1}]},{x:12,y:3},{x:0,y:4},{x:-12,y:3}],dead:[{x:-12,y:1},{x:12,y:1},{x:13,y:4},{bezier:[{x:7,y:3},{x:0,y:4},{x:-7,y:3}]},{x:-13,y:4}],normal:[{x:-12,y:1},{x:12,y:1},{x:13,y:4},{bezier:[{x:7,y:3},{x:0,y:4},{x:-7,y:3}]},{x:-13,y:4}]}),l=oA({angry:[{x:-13,y:0},{x:13,y:0},{x:13,y:2},{bezier:[{x:7,y:1},{x:0,y:2},{x:-7,y:1}]},{x:-13,y:2}],happy:[{x:-12,y:2},{bezier:[{x:-6,y:0},{x:0,y:-1},{x:6,y:0}]},{x:12,y:2},{x:13,y:3},{bezier:[{x:7,y:1},{x:0,y:0},{x:-7,y:1}]},{x:-13,y:3}],open:[{x:-10,y:2},{bezier:[{x:-10,y:-3},{x:-5,y:-6},{x:0,y:-6}]},{bezier:[{x:5,y:-6},{x:10,y:-3},{x:10,y:2}]},{x:10,y:1},{bezier:[{x:5,y:-4},{x:-5,y:-4},{x:-10,y:1}]}],pout:[{x:-8,y:0},{bezier:[{x:-4,y:-1},{x:0,y:0},{x:4,y:-1}]},{x:8,y:0},{x:9,y:1},{x:0,y:1},{x:-9,y:1}],sad:[{x:-12,y:0},{bezier:[{x:-6,y:2},{x:0,y:3},{x:6,y:2}]},{x:12,y:0},{x:13,y:1},{bezier:[{x:7,y:3},{x:0,y:4},{x:-7,y:3}]},{x:-13,y:1}],small:[{x:-6,y:0},{bezier:[{x:-3,y:1},{x:0,y:0},{x:3,y:1}]},{x:6,y:0},{x:7,y:1},{x:0,y:1},{x:-7,y:1}],surprised:[{x:-13,y:2},{bezier:[{x:-7,y:-2},{x:0,y:-3},{x:7,y:-2}]},{x:13,y:2},{x:14,y:3},{bezier:[{x:8,y:0},{x:0,y:-1},{x:-8,y:0}]},{x:-14,y:3}],worried:[{x:-11,y:1},{bezier:[{x:-6,y:0},{x:-3,y:1},{x:0,y:0}]},{bezier:[{x:3,y:2},{x:6,y:0},{x:11,y:1}]},{x:12,y:2},{bezier:[{x:7,y:1},{x:0,y:1},{x:-7,y:1}]},{x:-12,y:2}],dead:[{x:-12,y:1},{bezier:[{x:-6,y:0},{x:0,y:-.5},{x:6,y:0}]},{x:12,y:1},{x:13,y:2},{bezier:[{x:7,y:1},{x:0,y:.5},{x:-7,y:1}]},{x:-13,y:2}],normal:[{x:-12,y:1},{bezier:[{x:-6,y:0},{x:0,y:-.5},{x:6,y:0}]},{x:12,y:1},{x:13,y:2},{bezier:[{x:7,y:1},{x:0,y:.5},{x:-7,y:1}]},{x:-13,y:2}]}),u={};for(let n of[`normal`,`happy`,`sad`,`angry`,`surprised`,`dead`,`small`,`worried`,`pout`,`open`]){let r=e.group({parent:s,name:`burger.mouth.${n}`}),i={y:n===`open`?2:n===`small`?.5:1.5,z:+(n===`pout`)};n===`surprised`?e.ellipse({parent:r,name:`cheese.${n}`,color:t(`cheese`),fill:!0,height:8,stroke:2,translate:{y:2,z:0},width:6}):e.path({parent:r,name:`cheese.${n}`,color:t(`cheese`),fill:!0,path:sA(c,n),stroke:2,translate:i});let a={y:n===`open`?1:n===`surprised`?-1:-.5,z:n===`pout`?2:1};e.path({parent:r,name:`lettuce.${n}`,color:t(`lettuce`),fill:!0,path:sA(l,n),stroke:1.5,translate:a}),u[n]=r}return{root:n,variants:{eyes:o.eyes,mouth:u,blush:o.blush}}},expressions:bo,activities:So,defaultPresentation:{activity:`idle`,expression:`normal`}},lA=(e,t)=>{let n=e[t];if(!n)throw Error(`Missing cat face node: ${t}`);return n},uA=e=>e,dA={apiVersion:1,name:`cat`,palette:{body:`#ffe6c6`,eye:`#28282e`,mouth:`#28282e`,blush:`#feaae4`,dead:`#6c5671`,deadTongue:`#d9c8bf`,tongue:`#f98284`,stripes:`#dea38b`,sweat:`#accce4`,white:`#ffffff`},build({scene:e,color:t}){let n=e.group({name:`root`}),r=e.group({parent:n,name:`body`,updateSort:!0});e.path({parent:r,name:`body.sphere`,path:[{x:0,y:0}],color:t(`body`),stroke:32});for(let n of[-1,1])e.path({parent:r,name:`ear.${n<0?`left`:`right`}`,color:t(`body`),fill:!0,path:[{x:-6,y:0},{x:6,y:0},{x:0,y:-10}],rotate:{z:.6*n},stroke:3,translate:{x:9*n,y:-10}});let i=e.group({parent:r,name:`face`,translate:{z:20}}),a=xo(e,t,i,{hideMouth:!0}),o=e.group({parent:i,name:`cat.mouth`,translate:{y:6,z:2}}),s=(n,r,i)=>e.path({parent:o,name:`cat.mouth.${n}`,closed:!1,color:t(`mouth`),path:r,stroke:i}),c=uA({normal:s(`normal`,[{x:-2,y:-1},{x:0,y:0},{x:2,y:-1}],1.5),sad:s(`sad`,[{x:-2.5,y:2},{bezier:[{x:0,y:0},{x:2.5,y:2},{x:2.5,y:2}]}],1.5),angry:s(`angry`,[{x:-3,y:1},{x:3,y:1}],2),small:s(`small`,[{x:-1.5,y:0},{x:1.5,y:0}],1),worried:s(`worried`,[{x:-2,y:1},{bezier:[{x:-.5,y:.5},{x:.5,y:.5},{x:2,y:1}]}],1)}),l=e.group({parent:o,name:`cat.mouth.happy`,translate:{y:1}});e.path({parent:l,closed:!1,color:t(`mouth`),path:[{x:-2.5,y:1},{bezier:[{x:0,y:3},{x:2.5,y:1},{x:2.5,y:1}]}],stroke:1.5}),e.ellipse({parent:l,width:2,height:1.5,stroke:0,fill:!0,color:t(`tongue`),translate:{y:2}}),c.happy=l,c.surprised=e.ellipse({parent:o,name:`cat.mouth.surprised`,width:2.5,height:3,stroke:1.5,fill:!0,color:t(`mouth`),translate:{y:1}});let u=e.group({parent:o,name:`cat.mouth.dead`,translate:{y:3}});e.ellipse({parent:u,width:2.5,height:1.5,stroke:1.5,fill:!0,color:t(`dead`)}),e.ellipse({parent:u,width:1.2,height:.8,stroke:0,fill:!0,color:t(`deadTongue`),translate:{y:.5}}),c.dead=u,c.pout=e.ellipse({parent:o,name:`cat.mouth.pout`,width:2,height:2.5,stroke:1.5,fill:!0,color:t(`mouth`),translate:{y:1}}),c.open=e.ellipse({parent:o,name:`cat.mouth.open`,width:4,height:5,stroke:1.5,fill:!0,color:t(`mouth`),translate:{y:1}});let d=e.group({parent:i,name:`whiskers`,translate:{y:5,z:2}});for(let n of[-1,1]){let r=n*12;for(let[i,a]of[-2,0,2].entries())e.path({parent:d,name:`whisker.${n<0?`left`:`right`}.${String(i)}`,closed:!1,color:t(`eye`),path:[{x:0,y:a},{x:n*8,y:a+(i-1)*1.5}],stroke:.8,translate:{x:r,y:a*.5}})}let f={normal:lA(c,`normal`),happy:c.happy,sad:lA(c,`sad`),angry:lA(c,`angry`),surprised:c.surprised,dead:c.dead,small:lA(c,`small`),worried:lA(c,`worried`),pout:c.pout,open:c.open};return{root:n,variants:{eyes:a.eyes,mouth:f,blush:a.blush}}},expressions:bo,activities:{...So,listening:{motion:{target:`root`,rotate:{x:-.2},durationMs:300,repeat:`yoyo`},mouseInfluence:.3},thinking:{motion:{target:`root`,rotate:{z:.1},durationMs:800,repeat:`yoyo`},mouseInfluence:0}},defaultPresentation:{activity:`idle`,expression:`normal`}},fA={apiVersion:1,name:`mushroom`,palette:{body:`#fff7e4`,cap:`#f98284`,capSpot:`#ffe6c6`,eye:`#28282e`,mouth:`#28282e`,dead:`#6c5671`,deadTongue:`#d9c8bf`,tongue:`#f98284`,sweat:`#accce4`,white:`#ffffff`},build({scene:e,color:t}){let n=e.group({name:`root`}),r=e.group({parent:n,name:`body`,updateSort:!0});e.hemisphere({parent:r,name:`body.hemisphere`,backface:t(`cap`),color:t(`body`),diameter:32,rotate:{x:3*Math.PI/2},stroke:!1,translate:{y:2}});let i=e.hemisphere({parent:r,name:`cap.hemisphere`,backface:t(`capSpot`),color:t(`cap`),diameter:42,rotate:{x:Math.PI/2},stroke:!1,translate:{y:2}});e.path({parent:i,name:`cap.spot.front`,path:[{x:0,y:0}],color:t(`capSpot`),stroke:12,translate:{x:-8,y:8,z:12}}),e.path({parent:i,name:`cap.spot.top`,path:[{x:0,y:0}],color:t(`capSpot`),stroke:18,translate:{x:8,y:-4,z:13}});let a=e.group({parent:r,name:`face`,translate:{y:7,z:8}}),o=xo(e,t,a,{blushMode:`none`});return{root:n,variants:{eyes:o.eyes,mouth:o.mouth,blush:o.blush}}},expressions:bo,activities:{...So,error:{geometry:{eyes:`dead`,mouth:`dead`},motion:{target:`root`,rotate:{x:.9},durationMs:600,repeat:`none`},mouseInfluence:.1}},defaultPresentation:{activity:`idle`,expression:`sleepy`}},pA={mushroom:[`cap`,`capSpot`],cat:[`body`,`stripes`],burger:[`topBun`,`bottomBun`]},mA={mushroom:fA,cat:dA,burger:cA};function hA(e){let t=vo(yo(mA[e])),n=ho.parse(t.data);return{controls:t.controls,expressions:Object.keys(n.expressions),identitySlots:pA[e]}}var gA=new Map;function _A(e){let t=gA.get(e);return t||(t=hA(e),gA.set(e,t)),t}var vA=Object.freeze({get mushroom(){return _A(`mushroom`)},get cat(){return _A(`cat`)},get burger(){return _A(`burger`)}}),yA={mushroom:`Shiitake`,cat:`Cat`,burger:`Burger`},bA=[[`Rose`,`#f98284`,`#ffe6c6`],[`Peach`,`#f6a55c`,`#ffe9c9`],[`Gold`,`#f2d06b`,`#fff6d1`],[`Leaf`,`#9bd47a`,`#e6f8d8`],[`Mint`,`#5fc7b4`,`#d9f6ef`],[`Sky`,`#6aaee8`,`#dcefff`],[`Lilac`,`#9b8cf0`,`#ebe6ff`],[`Plum`,`#e58bd6`,`#fbe2f6`]];function xA(e,t){if(t===e.character)return e;let n=vA[e.character].identitySlots,r=vA[t].identitySlots,i=Object.fromEntries(r.flatMap((t,r)=>{let i=n[r];return Object.hasOwn(e.appearance,i)?[[t,e.appearance[i]]]:[]}));return{...e,character:t,appearance:i,expression:`normal`}}function SA(e,[,t,n]){let r=vA[e.character].identitySlots;return{...e,appearance:{...e.appearance,...Object.fromEntries(r.map((e,r)=>[e,r===0?t:n]))}}}function CA(e,t){let n=0;for(let e of t)n+=e.codePointAt(0)??0;return SA(e,bA[n%bA.length]??bA[0])}function wA({value:e,disabled:t=!1,onChange:n}){let r=vA[e.character].identitySlots,i=bA.find(([,t,n])=>r.every((r,i)=>e.appearance[r]===(i===0?t:n)))?.[0]??``;return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(hn,{legend:`Avatar`,icon:(0,Y.jsx)(Cn,{name:`agent`}),layout:`columns`,disabled:t,children:(0,Y.jsx)(HO,{"aria-label":`Character`,className:`caps-field-icon-choices`,disabled:t,orientation:`horizontal`,value:e.character,onValueChange:t=>{n(xA(e,ng.shape.character.parse(t)))},children:Qh.map(t=>(0,Y.jsx)(GO,{value:t,label:yA[t],caption:yA[t],art:`color`,icon:(0,Y.jsx)(kT,{avatar:xA(e,t),name:yA[t],size:32})},t))})}),(0,Y.jsx)(hn,{legend:`Colour`,icon:(0,Y.jsx)(Cn,{name:`prints`}),layout:`columns`,disabled:t,children:(0,Y.jsx)(HO,{"aria-label":`Colour`,className:`caps-field-icon-choices`,disabled:t,orientation:`horizontal`,value:i,onValueChange:t=>{let r=bA.find(([e])=>e===t);r&&n(SA(e,r))},children:bA.map(([e,t])=>(0,Y.jsx)(KO,{value:e,label:e,color:t},e))})})]})}var TA=ea.check(H(1,{message:`Give your Agent a name.`}),K(256,{message:`Use at most 256 characters.`})),EA=Ti(TA),DA=e=>e===`new`||e===`none`?e:e.computerId,OA=e=>e===`new`||e===`none`?e:{computerId:e},kA=e=>e?.[0]?.computerId??`none`;function AA(e,t){let n=Object.fromEntries(e.map(e=>[e.computerId,e.name]));n.new=`New Computer`,n.none=`No Computer`;let r={label:`Computer`,kind:`select`,icon:(0,Y.jsx)(Cn,{name:`computer`}),options:n};return V.check(L(e=>Object.hasOwn(n,e)||`Choose a Computer.`)).annotate(Ek(t===null?r:{...r,help:t}))}var jA=Ba({family:`grove-agent-create-request`,version:1,kinds:{request:{prefix:`request`}}});function MA({create:e,computers:t,computersUnavailable:n,inputRef:r,error:i,onCancel:a}){let o=(0,q.useRef)(null),[s,c]=(0,q.useState)(()=>{let e=jA.request.generate();return CA(og(e),e)}),l=(0,q.useMemo)(()=>I({name:TA.annotate(Ek({label:`Name`,icon:(0,Y.jsx)(Cn,{name:`write`}),render:e=>(0,Y.jsx)(cn,{ref:r,id:e.id,name:e.name,"aria-label":`New Agent name`,"aria-required":`true`,"aria-describedby":e[`aria-describedby`],"aria-invalid":e[`aria-invalid`],placeholder:`Name your Agent`,maxLength:256,disabled:e.disabled,value:e.value,onBlur:e.onBlur,onChange:t=>{e.onChange(t.currentTarget.value)}})})),computer:AA(t??[],n)}),[r,t,n]),u=t!==null,[d,f]=(0,q.useState)(!1),p={name:``,computer:kA(t)},m=eA({schema:l,defaultValues:p,onSubmit:async({name:t,computer:n})=>{let r=u?OA(n):void 0,i=o.current;if(i?.name!==t||(i.computer===void 0?void 0:DA(i.computer))!==(r===void 0?void 0:DA(r))||i.avatar!==s){let e={name:t,requestId:jA.request.generate(),avatar:s};i=r===void 0?e:{...e,computer:r}}return o.current=i,await e(i)?(o.current=null,{kind:`saved`,values:p}):{kind:`refused`}}}),{submitting:h,canSubmit:g,dirty:_}=tA(m);return(0,Y.jsxs)(iA,{model:m,layout:`columns`,"aria-label":`Create Agent`,footer:(0,Y.jsxs)(rt,{divider:!1,error:i,children:[(0,Y.jsx)(Zt,{type:`button`,variant:`ghost`,"aria-expanded":d,onClick:()=>{f(e=>!e)},children:d?`Fewer options`:`More options`}),(0,Y.jsx)(Zt,{type:`button`,variant:`ghost`,disabled:h,onClick:a,children:`Cancel`}),(0,Y.jsx)(Zt,{type:`submit`,className:`shrink-0 disabled:-outline-offset-1`,variant:`primary`,loading:h,disabled:h||!g||!_,children:`Create Agent`})]}),onSubmitCapture:e=>{kr(EA(m.form.state.values.name))&&e.currentTarget.querySelector(`input[name="name"]`)?.focus()},onChange:()=>{let e=m.form.state.values;(e.name.trim()!==o.current?.name||u&&o.current.computer!==void 0&&e.computer!==DA(o.current.computer))&&(o.current=null)},children:[(0,Y.jsx)(xk,{model:m,names:u&&d?[`name`,`computer`]:[`name`]}),d?(0,Y.jsx)(wA,{value:s,disabled:h,onChange:e=>{c(e),o.current=null}}):null]})}function NA({open:e,pending:t,error:n,computers:r,create:i,onClose:o,returnFocus:s}){let c=(0,q.useRef)(null);return(0,Y.jsx)(b,{open:e,onOpenChange:e=>{!e&&!t&&o()},children:(0,Y.jsxs)(zt,{className:`flex flex-col gap-lg`,initialFocus:c,finalFocus:s,keepMounted:!1,children:[(0,Y.jsxs)(pe,{children:[(0,Y.jsx)(w,{children:`New Agent`}),(0,Y.jsx)(a,{children:`Agents chat, write and make little games with you.`})]}),r.status===`loading`?(0,Y.jsx)(`p`,{role:`status`,children:`Loading your Computers…`}):(0,Y.jsx)(MA,{create:i,computers:r.status===`offered`?r.computers:r.status===`unavailable`?[]:null,computersUnavailable:r.status===`unavailable`?r.message:null,inputRef:c,error:n,onCancel:o})]})})}function PA({open:e,agents:t,defaultAgentId:n,start:r,pending:i,onClose:o,onNewAgent:s,returnFocus:c}){let l=eA({schema:(0,q.useMemo)(()=>I({agentId:V.check(L(e=>t.some(t=>t.agentId===e)||`Choose an Agent.`)).annotate(Ek({label:`Agent`,kind:`select`,options:Object.fromEntries(t.map(e=>[e.agentId,KT(e)]))}))}),[t]),defaultValues:{agentId:n??``},onSubmit:async({agentId:e})=>{let t=await r(e);if(t)return{kind:`refused`,error:t}}}),{submitting:u,canSubmit:d}=tA(l);return(0,Y.jsx)(b,{open:e,onOpenChange:e=>{!e&&!i&&!l.form.state.isSubmitting&&o()},children:(0,Y.jsxs)(zt,{className:`flex flex-col gap-lg`,keepMounted:!1,finalFocus:c,children:[(0,Y.jsxs)(pe,{children:[(0,Y.jsx)(w,{children:`New conversation`}),(0,Y.jsx)(a,{children:`Choose who to talk with.`})]}),t.length===0?(0,Y.jsxs)(`div`,{className:`grid gap-sm`,children:[(0,Y.jsx)(`p`,{children:`No Agent has conversation access yet.`}),s?(0,Y.jsx)(Zt,{onClick:s,children:`New Agent`}):null,(0,Y.jsx)(Zt,{variant:`ghost`,onClick:o,children:`Cancel`})]}):(0,Y.jsx)(iA,{model:l,"aria-label":`New conversation`,footer:(0,Y.jsxs)(rt,{divider:!1,error:l.error,children:[(0,Y.jsx)(Zt,{type:`button`,variant:`ghost`,disabled:u||i,onClick:o,children:`Cancel`}),(0,Y.jsx)(Zt,{type:`submit`,loading:u||i,disabled:!d||u||i,children:`Start`})]})})]})})}var FA=q.useLayoutEffect;function IA(e,t,n){q.useEffect(()=>{if(!e.current||n||typeof IntersectionObserver!=`function`)return()=>t();let r=new IntersectionObserver(e=>{t(e.pop())},{rootMargin:`100px`});return r.observe(e.current),()=>{r.disconnect(),t()}},[t,n,e])}function LA(e){let t=q.useRef(null);return q.useImperativeHandle(e,()=>t.current,[]),t}function RA(e){return e[e.length-1]}function zA(e){return typeof e==`function`}function BA(e,t){return zA(e)?e(t):e}var VA=Object.prototype.hasOwnProperty,HA=Object.prototype.propertyIsEnumerable;function UA(e){for(let t in e)if(VA.call(e,t))return!0;return!1}var WA=()=>Object.create(null),GA=(e,t)=>KA(e,t,WA);function KA(e,t,n=()=>({}),r=0){if(e===t)return e;if(r>500)return t;let i=t,a=XA(e)&&XA(i);if(!a&&!(JA(e)&&JA(i)))return i;let o=a?e:qA(e);if(!o)return i;let s=a?i:qA(i);if(!s)return i;let c=o.length,l=s.length,u=a?Array(l):n(),d=0;for(let t=0;t<l;t++){let o=a?t:s[t],l=e[o],f=i[o];if(l===f){u[o]=l,(a?t<c:VA.call(e,o))&&d++;continue}if(l===null||f===null||typeof l!=`object`||typeof f!=`object`){u[o]=f;continue}let p=KA(l,f,n,r+1);u[o]=p,p===l&&d++}return c===l&&d===c?e:u}function qA(e){let t=Object.keys(e);if(t.length!==Object.getOwnPropertyNames(e).length)return!1;let n=Object.getOwnPropertySymbols(e);if(n.length===0)return t;for(let r of n){if(!HA.call(e,r))return!1;t.push(r)}return t}function JA(e){if(!YA(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!YA(n)||!n.hasOwnProperty(`isPrototypeOf`))}function YA(e){return Object.prototype.toString.call(e)===`[object Object]`}function XA(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ZA(e,t,n){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0,i=e.length;r<i;r++)if(!ZA(e[r],t[r],n))return!1;return!0}if(JA(e)&&JA(t)){let r=n?.ignoreUndefined??!0;if(n?.partial){for(let i in t)if((!r||t[i]!==void 0)&&!ZA(e[i],t[i],n))return!1;return!0}let i=0;if(!r)i=Object.keys(e).length;else for(let t in e)e[t]!==void 0&&i++;let a=0;for(let o in t)if((!r||t[o]!==void 0)&&(a++,a>i||!ZA(e[o],t[o],n)))return!1;return i===a}return!1}var QA=/[\x00-\x1f\x7f"<>`{}]/g;function $A(e){return e.replace(QA,e=>`%`+e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`))}function ej(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,e=>{try{return decodeURI(e)}catch{return e}})}return $A(t)}var tj=[`http:`,`https:`,`mailto:`,`tel:`];function nj(e,t){if(!e)return!1;try{let n=new URL(e);return!t.has(n.protocol)}catch{return!1}}function rj(e){if(!e||!/[%\\\x00-\x1f\x7f]/.test(e)&&!e.startsWith(`//`))return{path:e,handledProtocolRelativeURL:!1};let t=/%25|%5C/gi,n=0,r=``,i;for(;(i=t.exec(e))!==null;)r+=ej(e.slice(n,i.index))+i[0],n=t.lastIndex;r+=ej(n?e.slice(n):e);let a=!1;return r.startsWith(`//`)&&(a=!0,r=`/`+r.replace(/^\/+/,``)),{path:r,handledProtocolRelativeURL:a}}function ij(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function aj(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function oj(){throw Error(`Invariant failed`)}function sj(e){let t=new Map,n,r,i=e=>{e.next&&(e.prev?(e.prev.next=e.next,e.next.prev=e.prev,e.next=void 0,r&&(r.next=e,e.prev=r)):(e.next.prev=void 0,n=e.next,e.next=void 0,r&&(e.prev=r,r.next=e)),r=e)};return{get(e){let n=t.get(e);if(n)return i(n),n.value},set(a,o){if(t.size>=e&&n){let e=n;t.delete(e.key),e.next&&(n=e.next,e.next.prev=void 0),e===r&&(r=void 0)}let s=t.get(a);if(s)s.value=o,i(s);else{let e={key:a,value:o,prev:r};r&&(r.next=e),r=e,n||=e,t.set(a,e)}},clear(){t.clear(),n=void 0,r=void 0}}}var cj=4,lj=5;function uj(e){let t=e.indexOf(`{`);if(t===-1)return null;let n=e.indexOf(`}`,t);return n===-1||t+1>=e.length?null:[t,n]}function dj(e,t,n=new Uint16Array(6)){let r=e.indexOf(`/`,t),i=r===-1?e.length:r,a=e.substring(t,i);if(!a||!a.includes(`$`))return n[0]=0,n[1]=t,n[2]=t,n[3]=i,n[4]=i,n[5]=i,n;if(a===`$`){let r=e.length;return n[0]=2,n[1]=t,n[2]=t,n[3]=r,n[4]=r,n[5]=r,n}if(a.charCodeAt(0)===36)return n[0]=1,n[1]=t,n[2]=t+1,n[3]=i,n[4]=i,n[5]=i,n;let o=uj(a);if(o){let[r,s]=o,c=a.charCodeAt(r+1);if(c===45){if(r+2<a.length&&a.charCodeAt(r+2)===36){let e=r+3,a=s;if(e<a)return n[0]=3,n[1]=t+r,n[2]=t+e,n[3]=t+a,n[4]=t+s+1,n[5]=i,n}}else if(c===36){let a=r+1,o=r+2;return o===s?(n[0]=2,n[1]=t+r,n[2]=t+a,n[3]=t+o,n[4]=t+s+1,n[5]=e.length,n):(n[0]=1,n[1]=t+r,n[2]=t+o,n[3]=t+s,n[4]=t+s+1,n[5]=i,n)}}return n[0]=0,n[1]=t,n[2]=t,n[3]=i,n[4]=i,n[5]=i,n}function fj(e,t,n,r,i,a,o,s){s?.(n);let c=r;{let r=n.fullPath??n.from,s=n.options,l=r.length,u=s?.caseSensitive??e,d=s?.params?.parse??s?.parseParams;for(;c<l;){let e=dj(r,c,t),n,s=c,l=e[5];c=l+1,a++;let f=e[0];switch(f){case 0:{let t=r.substring(e[2],e[3]),o=t,s;u?s=i.static??=new Map:(o=t.toLowerCase(),s=i.staticInsensitive??=new Map);let c=s.get(o);if(c)n=c;else{let e=mj(r);e.parent=i,e.depth=a,n=e,s.set(o,e)}break}case 1:case 3:case 2:{let t=r.substring(s,e[1]),c=r.substring(e[4],l),p=u&&!!(t||c),m=t?p?t:t.toLowerCase():void 0,h=c?p?c:c.toLowerCase():void 0,g=f===1?i.dynamic:f===3?i.optional:i.wildcard,_=f!==2&&!d&&g?.find(e=>!e.parse&&e.caseSensitive===p&&e.prefix===m&&e.suffix===h);if(_)n=_;else{let e=hj(f,r,p,m,h);n=e,e.parent=i,e.depth=a;let t;t=f===1?i.dynamic??=[]:f===3?i.optional??=[]:i.wildcard??=[],t.push(e),t.length===2&&o?.push(t)}break}}i=n}if(d&&n.children&&!n.isRoot&&n.id&&n.id.charCodeAt(n.id.lastIndexOf(`/`)+1)===95){let e=mj(r);e.kind=lj,e.parent=i,a++,e.depth=a,i.pathless??=[],i.pathless.push(e),i=e}let f=(n.path||!n.children)&&!n.isRoot;if(f&&r.endsWith(`/`)){let e=mj(r);e.kind=cj,e.parent=i,a++,e.depth=a,i.index=e,i=e}i.parse=d??null,i.priority=s?.params?.priority??0,f&&!i.route&&(i.route=n,i.fullPath=r)}if(n.children)for(let r of n.children)fj(e,t,r,c,i,a,o,s)}function pj(e,t){if(e.parse&&!t.parse)return-1;if(!e.parse&&t.parse)return 1;if(e.parse&&t.parse&&(e.priority||t.priority))return t.priority-e.priority;if(e.prefix&&t.prefix&&e.prefix!==t.prefix){if(e.prefix.startsWith(t.prefix))return-1;if(t.prefix.startsWith(e.prefix))return 1}if(e.suffix&&t.suffix&&e.suffix!==t.suffix){if(e.suffix.endsWith(t.suffix))return-1;if(t.suffix.endsWith(e.suffix))return 1}return e.prefix&&!t.prefix?-1:!e.prefix&&t.prefix?1:e.suffix&&!t.suffix?-1:!e.suffix&&t.suffix?1:e.caseSensitive&&!t.caseSensitive?-1:!e.caseSensitive&&t.caseSensitive?1:0}function mj(e){return{kind:0,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:e,parent:null,parse:null,priority:0}}function hj(e,t,n,r,i){return{kind:e,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:t,parent:null,parse:null,priority:0,caseSensitive:n,prefix:r,suffix:i}}function gj(e,t){let n=mj(`/`),r=new Uint16Array(6),i=[];for(let t of e)fj(!1,r,t,1,n,0,i);for(let e of i)e.sort(pj);t.masksTree=n,t.flatCache=sj(1e3)}function _j(e,t){e||=`/`;let n=t.flatCache.get(e);if(n)return n;let r=Sj(e,t.masksTree);return t.flatCache.set(e,r),r}function vj(e,t,n,r,i){e||=`/`,r||=`/`;let a=t?`case\0${e}`:e,o=i.singleCache.get(a);return o||(o=mj(`/`),fj(t,new Uint16Array(6),{from:e},1,o,0),i.singleCache.set(a,o)),Sj(r,o,n)}function yj(e,t,n=!1){let r=n?e:`nofuzz\0${e}`,i=t.matchCache.get(r);if(i!==void 0)return i;e||=`/`;let a;try{a=Sj(e,t.segmentTree,n)}catch(e){if(e instanceof URIError)a=null;else throw e}return a&&(a.branch=wj(a.route)),t.matchCache.set(r,a),a}function bj(e){return e===`/`?e:e.replace(/\/{1,}$/,``)}function xj(e,t=!1,n){let r=mj(e.fullPath),i=new Uint16Array(6),a=[],o={},s={},c=0;fj(t,i,e,1,r,0,a,e=>{if(n?.(e,c),e.id in o&&oj(),o[e.id]=e,c!==0&&e.path){let t=bj(e.fullPath);(!s[t]||e.fullPath.endsWith(`/`))&&(s[t]=e)}c++});for(let e of a)e.sort(pj);return{processedTree:{segmentTree:r,singleCache:sj(1e3),matchCache:sj(1e3),flatCache:null,masksTree:null},routesById:o,routesByPath:s}}function Sj(e,t,n=!1){let r=e.split(`/`),i=Ej(e,r,t,n);if(!i)return null;let[a]=Cj(e,r,i);return{route:i.node.route,rawParams:a}}function Cj(e,t,n){let r=Tj(n.node),i=null,a=Object.create(null),o=n.extract?.part??0,s=n.extract?.node??0,c=n.extract?.path??0,l=n.extract?.segment??0;for(;s<r.length;o++,s++,c++,l++){let u=r[s];if(u.kind===cj)break;if(u.kind===lj){l--,o--,c--;continue}let d=t[o],f=c;if(d&&(c+=d.length),u.kind===1){i??=n.node.fullPath.split(`/`);let e=i[l],t=u.prefix?.length??0;if(e.charCodeAt(t)===123){let n=u.suffix?.length??0,r=e.substring(t+2,e.length-n-1),i=d.substring(t,d.length-n);a[r]=decodeURIComponent(i)}else{let t=e.substring(1);a[t]=decodeURIComponent(d)}}else if(u.kind===3){if(n.skipped&1<<s){o--,c=f-1;continue}i??=n.node.fullPath.split(`/`);let e=i[l],t=u.prefix?.length??0,r=u.suffix?.length??0,p=e.substring(t+3,e.length-r-1),m=u.suffix||u.prefix?d.substring(t,d.length-r):d;m&&(a[p]=decodeURIComponent(m))}else if(u.kind===2){let t=u,n=e.substring(f+(t.prefix?.length??0),e.length-(t.suffix?.length??0)),r=decodeURIComponent(n);a[`*`]=r,a._splat=r;break}}return n.rawParams&&Object.assign(a,n.rawParams),[a,{part:o,node:s,path:c,segment:l}]}function wj(e){let t=[e];for(;e.parentRoute;)e=e.parentRoute,t.push(e);return t.reverse(),t}function Tj(e){let t=Array(e.depth+1);do t[e.depth]=e,e=e.parent;while(e);return t}function Ej(e,t,n,r){if(e===`/`&&n.index)return{node:n.index,skipped:0};let i=!RA(t),a=i&&e!==`/`,o=t.length-+!!i,s=[{node:n,index:1,skipped:0,statics:0,dynamics:0,optionals:0}],c=null,l=null;for(;s.length;){let n=s.pop(),{node:i,index:u,skipped:d,statics:f,dynamics:p,optionals:m}=n,{extract:h,rawParams:g}=n;if(i.kind===2&&i.route&&!Aj(l,n))continue;if(i.parse){if(!kj(e,t,n))continue;g=n.rawParams,h=n.extract}r&&i.route&&i.kind!==cj&&Aj(c,n)&&(c=n);let _=u===o;if(_&&(i.route&&(!a||i.kind===cj||i.kind===2)&&Aj(l,n)&&(l=n),!i.optional&&!i.wildcard&&!i.index&&!i.pathless))continue;let v=_?void 0:t[u],y;if(_&&i.index){let n={node:i.index,index:u,skipped:d,statics:f,dynamics:p,optionals:m,extract:h,rawParams:g},r=!0;if(i.index.parse&&(kj(e,t,n)||(r=!1)),r){if(!p&&!m&&!d&&Oj(f,o))return n;Aj(l,n)&&(l=n)}}if(i.wildcard)for(let e=i.wildcard.length-1;e>=0;e--){let n=i.wildcard[e],{prefix:r,suffix:a}=n;if(!(r&&(_||!(n.caseSensitive?v:y??=v.toLowerCase()).startsWith(r)))){if(a){if(_)continue;let e=t.slice(u).join(`/`).slice(-a.length);if((n.caseSensitive?e:e.toLowerCase())!==a)continue}s.push({node:n,index:o,skipped:d,statics:f,dynamics:p,optionals:m,extract:h,rawParams:g})}}if(i.optional){let e=d|1<<i.depth+1;for(let t=i.optional.length-1;t>=0;t--){let n=i.optional[t];s.push({node:n,index:u,skipped:e,statics:f,dynamics:p,optionals:m,extract:h,rawParams:g})}if(!_)for(let e=i.optional.length-1;e>=0;e--){let t=i.optional[e],{prefix:n,suffix:r}=t;if(n||r){let e=t.caseSensitive?v:y??=v.toLowerCase();if(n&&!e.startsWith(n)||r&&!e.endsWith(r))continue}s.push({node:t,index:u+1,skipped:d,statics:f,dynamics:p,optionals:m+Dj(o,u),extract:h,rawParams:g})}}if(!_&&i.dynamic&&v)for(let e=i.dynamic.length-1;e>=0;e--){let t=i.dynamic[e],{prefix:n,suffix:r}=t;if(n||r){let e=t.caseSensitive?v:y??=v.toLowerCase();if(n&&!e.startsWith(n)||r&&!e.endsWith(r))continue}s.push({node:t,index:u+1,skipped:d,statics:f,dynamics:p+Dj(o,u),optionals:m,extract:h,rawParams:g})}if(!_&&i.staticInsensitive){let e=i.staticInsensitive.get(y??=v.toLowerCase());e&&s.push({node:e,index:u+1,skipped:d,statics:f+Dj(o,u),dynamics:p,optionals:m,extract:h,rawParams:g})}if(!_&&i.static){let e=i.static.get(v);e&&s.push({node:e,index:u+1,skipped:d,statics:f+Dj(o,u),dynamics:p,optionals:m,extract:h,rawParams:g})}if(i.pathless)for(let e=i.pathless.length-1;e>=0;e--){let t=i.pathless[e];s.push({node:t,index:u,skipped:d,statics:f,dynamics:p,optionals:m,extract:h,rawParams:g})}}if(l)return l;if(r&&c){let n=c.index;for(let e=0;e<c.index;e++)n+=t[e].length;let r=n===e.length?`/`:e.slice(n);return c.rawParams??=Object.create(null),c.rawParams[`**`]=decodeURIComponent(r),c}return null}function Dj(e,t){return 2**(e-t-1)}function Oj(e,t){return e===2**(t-1)-1}function kj(e,t,n){let r,i;try{[r,i]=Cj(e,t,n)}catch{return null}if(n.rawParams=r,n.extract=i,!n.node.parse)return!0;try{if(n.node.parse(r)===!1)return null}catch{}return!0}function Aj(e,t){return!e||t.statics>e.statics||t.statics===e.statics&&(t.dynamics>e.dynamics||t.dynamics===e.dynamics&&(t.optionals>e.optionals||t.optionals===e.optionals&&((t.node.kind===cj)>(e.node.kind===cj)||t.node.kind===cj==(e.node.kind===cj)&&t.node.depth>e.node.depth)))}function jj(e){return Mj(e.filter(e=>e!==void 0).join(`/`))}function Mj(e){return e.replace(/\/{2,}/g,`/`)}function Nj(e){return e===`/`?e:e.replace(/^\/{1,}/,``)}function Pj(e){let t=e.length;return t>1&&e[t-1]===`/`?e.replace(/\/{1,}$/,``):e}function Fj(e){return Pj(Nj(e))}function Ij(e,t){return e?.endsWith(`/`)&&e!==`/`&&e!==`${t}/`?e.slice(0,-1):e}function Lj(e,t,n){return Ij(e,n)===Ij(t,n)}function Rj({base:e,to:t,trailingSlash:n=`never`,cache:r}){let i=t===`.`,a=t.startsWith(`/`),o;if(r){o=a?t:i?e:e+`\0`+t;let n=r.get(o);if(n)return n}let s;if(i)s=e.split(`/`);else if(a)s=t.split(`/`);else{for(s=e.split(`/`);s.length>1&&RA(s)===``;)s.pop();let n=t.split(`/`);for(let e=0,t=n.length;e<t;e++){let r=n[e];r===``?e?e===t-1&&s.push(r):s=[r]:r===`..`?s.length>1?s.pop():s=[``]:r===`.`||s.push(r)}}s.length>1&&(RA(s)===``?n===`never`&&s.pop():n===`always`&&s.push(``));let c=Mj(s.join(`/`))||`/`;return o&&r&&r.set(o,c),c}function zj(e){let t=new Map(e.map(e=>[encodeURIComponent(e),e])),n=Array.from(t.keys()).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`),r=new RegExp(n,`g`);return e=>e.replace(r,e=>t.get(e)??e)}function Bj(e,t,n){let r=t[e];return typeof r==`string`?e===`_splat`?/^[a-zA-Z0-9\-._~!/]*$/.test(r)?r:r.split(`/`).map(e=>Hj(e,n)).join(`/`):Hj(r,n):r}function Vj({path:e,params:t,decoder:n,...r}){let i=!1,a=Object.create(null);if(!e||e===`/`)return{interpolatedPath:`/`,usedParams:a,isMissingParams:i};if(!e.includes(`$`))return{interpolatedPath:e,usedParams:a,isMissingParams:i};let o=e.length,s=0,c,l=``;for(;s<o;){let r=s;c=dj(e,r,c);let o=c[5];if(s=o+1,r===o)continue;let u=c[0];if(u===0){l+=`/`+e.substring(r,o);continue}if(u===2){let s=t._splat;a._splat=s,a[`*`]=s;let u=e.substring(r,c[1]),d=e.substring(c[4],o);if(!s){i=!0,(u||d)&&(l+=`/`+u+d);continue}let f=Bj(`_splat`,t,n);l+=`/`+u+f+d;continue}if(u===1){let s=e.substring(c[2],c[3]);!i&&!(s in t)&&(i=!0),a[s]=t[s];let u=e.substring(r,c[1]),d=e.substring(c[4],o),f=Bj(s,t,n)??`undefined`;l+=`/`+u+f+d;continue}if(u===3){let i=e.substring(c[2],c[3]),s=t[i];if(s==null)continue;a[i]=s;let u=e.substring(r,c[1]),d=e.substring(c[4],o),f=Bj(i,t,n)??``;l+=`/`+u+f+d;continue}}return e.endsWith(`/`)&&(l+=`/`),{usedParams:a,interpolatedPath:l||`/`,isMissingParams:i}}function Hj(e,t){let n=encodeURIComponent(e);return t?.(n)??n}function Uj(e){return e?.isNotFound===!0}function Wj(){try{return sessionStorage}catch{return}}var Gj=`tsr-scroll-restoration-v1_3`,Kj=Wj();function qj(){try{return JSON.parse(Kj?.getItem(`tsr-scroll-restoration-v1_3`)||`{}`)}catch{return{}}}function Jj(){try{Kj?.setItem(Gj,JSON.stringify(Yj))}catch{}}var Yj=qj(),Xj=`data-scroll-restoration-id`,Zj=e=>e.state.__TSR_key||e.href;function Qj(e){let t=e.getAttribute(Xj);if(t)return`[${Xj}="${t}"]`;let n=``,r=e,i;for(;i=r.parentNode;){let e=1,t=r;for(;t=t.previousElementSibling;)e++;let a=`${r.localName}:nth-child(${e})`;n=n?`${a} > ${n}`:a,r=i}return n}var $j=!1,eM=`window`;function tM(e){try{return typeof e==`function`?e():document.querySelector(e)}catch{}}function nM(e){let t=new Set;for(let n of e){if(n===eM)continue;let e=tM(n);e&&t.add(e)}return t}function rM(e,t){let n=t??e.options.scrollRestoration,r=e._scroll;n&&(r.restoring=!0);let i=e.options.getScrollRestorationKey||Zj,a=new Set,o=e=>{let t=Yj[e]||={};for(let e of a)e===document?t[eM]={scrollX,scrollY}:e.isConnected&&(t[Qj(e)]={scrollX:e.scrollLeft,scrollY:e.scrollTop})};n&&!r.restoration&&(r.restoration=!0,$j=!1,history.scrollRestoration=`manual`,document.addEventListener(`scroll`,e=>{$j||a.add(e.target)},!0),e.subscribe(`onBeforeLoad`,e=>{e.fromLocation&&o(i(e.fromLocation)),a.clear()}),addEventListener(`pagehide`,()=>{o(i(e.stores.resolvedLocation.get()??e.stores.location.get())),Jj()})),!r.reset&&(r.reset=!0,e.subscribe(`onRendered`,t=>{let n=e.options.scrollRestorationBehavior,o=e.options.scrollToTopSelectors,s=r.next,c=r.hash,l;if(a.clear(),r.next=!0,r.hash=!1,typeof e.options.scrollRestoration==`function`&&!e.options.scrollRestoration({location:e.latestLocation}))return;let u=i(t.toLocation),d=t.fromLocation&&i(t.fromLocation);if(r.restoring&&d&&d!==u){let e=Yj[d];if(e){let t=Yj[u];for(let n in e){if(n===eM){if(s)continue}else{let e=tM(n);if(!e||s&&o&&(l??=nM(o),l.has(e)))continue}t||=Yj[u]={},t[n]??=e[n]}}}$j=!0;try{let e=t.toLocation.hash,i=t.toLocation.state.__hashScrollIntoViewOptions??!0,a=!1;if(s){!e&&o&&(l??=nM(o));let t=e&&i&&c,s=r.restoring?Yj[u]:void 0;if(s)for(let e in s){let{scrollX:r,scrollY:i}=s[e];if(e===eM){if(t)continue;scrollTo({top:i,left:r,behavior:n}),a=!0}else{let t=tM(e);t&&(t.scrollLeft=r,t.scrollTop=i,l?.delete(t))}}if(!e){let e={top:0,left:0,behavior:n};if(a||scrollTo(e),l)for(let t of l)t.scrollTo(e)}}!a&&e&&i&&document.getElementById(e)?.scrollIntoView(i)}finally{$j=!1}}))}function iM(e,t=String){let n=new URLSearchParams;for(let r in e){let i=e[r];i!==void 0&&n.set(r,t(i))}return n.toString()}function aM(e){return e?e===`false`?!1:e===`true`?!0:e*0==0&&+e+``===e?+e:e:``}function oM(e){let t=new URLSearchParams(e),n=Object.create(null);for(let[e,r]of t.entries()){let t=n[e];t==null?n[e]=aM(r):Array.isArray(t)?t.push(aM(r)):n[e]=[t,aM(r)]}return n}var sM=/^(?:\s|["[{\d-]|fa|nu|tr)/,cM=uM(JSON.parse),lM=dM(JSON.stringify,JSON.parse);function uM(e){return t=>{t[0]===`?`&&(t=t.substring(1));let n=oM(t);for(let t in n){let r=n[t];if(typeof r==`string`)try{n[t]=e(r)}catch{}}return n}}function dM(e,t){let n=t===JSON.parse;function r(r){if(r&&typeof r==`object`)try{return e(r)}catch{}else if(t&&typeof r==`string`){if(n&&!sM.test(r))return r;try{return t(r),e(r)}catch{}}return r}return e=>{let t=iM(e,r);return t?`?${t}`:``}}var fM=`__root__`;function pM(e){if(e.statusCode=e.statusCode||e.code||307,!e._builtLocation&&!e.reloadDocument&&typeof e.href==`string`)try{new URL(e.href),e.reloadDocument=!0}catch{}let t=new Headers(e.headers);e.href&&t.get(`Location`)===null&&t.set(`Location`,e.href);let n=new Response(null,{status:e.statusCode,headers:t});if(n.options=e,e.throw)throw n;return n}function mM(e){return e instanceof Response&&!!e.options}function hM(e){return{input:({url:t})=>{for(let n of e)t=_M(n,t);return t},output:({url:t})=>{for(let n=e.length-1;n>=0;n--)t=vM(e[n],t);return t}}}function gM(e){let t=Fj(e.basepath),n=`/${t}`,r=e.caseSensitive?n:n.toLowerCase(),i=`${r}/`;return{input:({url:t})=>{let a=e.caseSensitive?t.pathname:t.pathname.toLowerCase();return a===r?t.pathname=`/`:a.startsWith(i)&&(t.pathname=t.pathname.slice(n.length)),t},output:({url:e})=>(e.pathname=jj([`/`,t,e.pathname]),e)}}function _M(e,t){let n=e?.input?.({url:t});if(n){if(typeof n==`string`)return new URL(n);if(n instanceof URL)return n}return t}function vM(e,t){let n=e?.output?.({url:t});if(n){if(typeof n==`string`)return new URL(n);if(n instanceof URL)return n}return t}function yM(e,t){let{createMutableStore:n,createReadonlyStore:r,batch:i}=t,a=new Map,o=n(`idle`),s=n(e),c=n(void 0),l=n([]),u=r(()=>l.get().map(e=>a.get(e).get())),d=r(()=>({status:o.get(),isLoading:o.get()===`pending`,matches:u.get(),location:s.get(),resolvedLocation:c.get()}));function f(e){let t=a.get(e);return t||(t=n(void 0),a.set(e,t)),t}let p={status:o,location:s,resolvedLocation:c,ids:l,matches:u,byRoute:a,__store:d,getMatchStore:f,setMatches:m};function m(e){let t=l.get(),n=e.map(e=>e.routeId);i(()=>{aj(t,n)||l.set(n);for(let e of t)n.includes(e)||a.get(e).set(()=>void 0);for(let t of e){let e=f(t.routeId);e.get()!==t&&e.set(t)}})}return p}var bM=`__TSR_index`,xM=`popstate`,SM=`beforeunload`;function CM(e){let t=e.getLocation(),n=new Set,r=r=>{t=e.getLocation(),n.forEach(e=>e({location:t,action:r}))},i=n=>{e.notifyOnIndexChange??!0?r(n):t=e.getLocation()},a=async({task:n,navigateOpts:r,...i})=>{if(r?.ignoreBlocker??!1){n();return}let a=e.getBlockers?.()??[],o=i.type===`PUSH`||i.type===`REPLACE`;if(typeof document<`u`&&a.length&&o)for(let n of a){let r=OM(i.path,i.state);if(await n.blockerFn({currentLocation:t,nextLocation:r,action:i.type})){e.onBlocked?.();return}}n()};return{get location(){return t},get length(){return e.getLength()},subscribers:n,subscribe:e=>(n.add(e),()=>{n.delete(e)}),push:(n,i,o)=>{let s=t.state[bM];i=wM(s+1,i),a({task:()=>{e.pushState(n,i),r({type:`PUSH`})},navigateOpts:o,type:`PUSH`,path:n,state:i})},replace:(n,i,o)=>{let s=t.state[bM];i=wM(s,i),a({task:()=>{e.replaceState(n,i),r({type:`REPLACE`})},navigateOpts:o,type:`REPLACE`,path:n,state:i})},go:(t,n)=>{a({task:()=>{e.go(t),i({type:`GO`,index:t})},navigateOpts:n,type:`GO`})},back:t=>{a({task:()=>{e.back(t?.ignoreBlocker??!1),i({type:`BACK`})},navigateOpts:t,type:`BACK`})},forward:t=>{a({task:()=>{e.forward(t?.ignoreBlocker??!1),i({type:`FORWARD`})},navigateOpts:t,type:`FORWARD`})},canGoBack:()=>t.state[bM]!==0,createHref:t=>e.createHref(t),block:t=>{if(!e.setBlockers)return()=>{};let n=e.getBlockers?.()??[];return e.setBlockers([...n,t]),()=>{let n=e.getBlockers?.()??[];e.setBlockers?.(n.filter(e=>e!==t))}},flush:()=>e.flush?.(),destroy:()=>e.destroy?.(),notify:r}}function wM(e,t){t||={};let n=kM();return{...t,key:n,__TSR_key:n,[bM]:e}}function TM(e){let t=e?.window??(typeof document<`u`?window:void 0),n=t.history.pushState,r=t.history.replaceState,i=[],a=()=>i,o=e=>i=e,s=e?.createHref??(e=>e),c=e?.parseLocation??(()=>OM(`${t.location.pathname}${t.location.search}${t.location.hash}`,t.history.state));if(!t.history.state?.__TSR_key&&!t.history.state?.key){let e=kM();t.history.replaceState({[bM]:0,key:e,__TSR_key:e},``)}let l=c(),u,d=!1,f=!1,p=!1,m=!1,h=()=>l,g,_=()=>{g&&(S._ignoreSubscribers=!0,(g[2]?t.history.pushState:t.history.replaceState)(g[1],``,g[0]),S._ignoreSubscribers=!1,g=void 0,u=void 0)},v=(e,t,n)=>{let r=s(t),i=!!g;i||(u=l),l=OM(t,n),g=[r,n,g?.[2]||e],i||queueMicrotask(()=>_())},y=e=>{l=c(),S.notify({type:e})},b=async()=>{if(f){f=!1;return}let e=c(),n=e.state[bM]-l.state[bM],r=n===1,i=n===-1,o=!r&&!i||d;d=!1;let s=o?`GO`:i?`BACK`:`FORWARD`,u=o?{type:`GO`,index:n}:{type:i?`BACK`:`FORWARD`};if(p)p=!1;else{let n=a();if(typeof document<`u`&&n.length){for(let r of n)if(await r.blockerFn({currentLocation:l,nextLocation:e,action:s})){f=!0,t.history.go(1),S.notify(u);return}}}l=c(),S.notify(u)},x=e=>{if(m){m=!1;return}let t=!1,n=a();if(typeof document<`u`&&n.length)for(let e of n){let n=e.enableBeforeUnload??!0;if(n===!0){t=!0;break}if(typeof n==`function`&&n()===!0){t=!0;break}}if(t)return e.preventDefault(),e.returnValue=``},S=CM({getLocation:h,getLength:()=>t.history.length,pushState:(e,t)=>v(!0,e,t),replaceState:(e,t)=>v(!1,e,t),back:e=>(e&&(p=!0),m=!0,t.history.back()),forward:e=>{e&&(p=!0),m=!0,t.history.forward()},go:e=>{d=!0,t.history.go(e)},createHref:e=>s(e),flush:_,destroy:()=>{t.history.pushState=n,t.history.replaceState=r,t.removeEventListener(SM,x,{capture:!0}),t.removeEventListener(xM,b)},onBlocked:()=>{u&&l!==u&&(l=u)},getBlockers:a,setBlockers:o,notifyOnIndexChange:!1});return t.addEventListener(SM,x,{capture:!0}),t.addEventListener(xM,b),t.history.pushState=function(...e){let r=n.apply(t.history,e);return S._ignoreSubscribers||y(`PUSH`),r},t.history.replaceState=function(...e){let n=r.apply(t.history,e);return S._ignoreSubscribers||y(`REPLACE`),n},S}function EM(e={initialEntries:[`/`]}){let t=e.initialEntries,n=e.initialIndex?Math.min(Math.max(e.initialIndex,0),t.length-1):t.length-1,r=t.map((e,t)=>wM(t,void 0)),i=()=>OM(t[n],r[n]),a=[];return CM({getLocation:i,getLength:()=>t.length,pushState:(e,i)=>{n<t.length-1&&(t.splice(n+1),r.splice(n+1)),r.push(i),t.push(e),n=Math.max(t.length-1,0)},replaceState:(e,i)=>{r[n]=i,t[n]=e},back:()=>{n=Math.max(n-1,0)},forward:()=>{n=Math.min(n+1,t.length-1)},go:e=>{n=Math.min(Math.max(n+e,0),t.length-1)},createHref:e=>e,getBlockers:()=>a,setBlockers:e=>a=e})}function DM(e){let t=e.replace(/[\x00-\x1f\x7f]/g,``);return t.startsWith(`//`)&&(t=`/`+t.replace(/^\/+/,``)),t}function OM(e,t){let n=DM(e),r=n.indexOf(`#`),i=n.indexOf(`?`),a=kM();return{href:n,pathname:n.substring(0,r>0?i>0?Math.min(r,i):r:i>0?i:n.length),hash:r>-1?n.substring(r):``,search:i>-1?n.slice(i,r===-1?void 0:r):``,state:t||{[bM]:0,key:a,__TSR_key:a}}}function kM(){return(Math.random()+1).toString(36).substring(7)}function AM(e){return e.options.loader||e.options.beforeLoad||e.lazyFn||e.options.component?.preload||e.options.pendingComponent?.preload}function jM(e,t){return{fromLocation:t,toLocation:e,pathChanged:t?.pathname!==e.pathname,hrefChanged:t?.href!==e.href,hashChanged:t?.hash!==e.hash}}function MM({key:e,__TSR_key:t,__TSR_index:n,__hashScrollIntoViewOptions:r,...i}){return i}function NM(e,t,n,r){for(let i of t){if(r?.()===!1)return;n.some(e=>e.routeId===i.routeId)||e.routesById[i.routeId].options.onLeave?.(i)}for(let i of n){if(r?.()===!1)return;e.routesById[i.routeId].options[t.some(e=>e.routeId===i.routeId)?`onStay`:`onEnter`]?.(i)}}var PM=class{constructor(e,t){this.tempLocationKey=`${Math.round(Math.random()*1e7)}`,this._scroll={next:!0},this.subscribers=new Set,this._cache=new Map,this._committed=[],this.routeBranchCache=new WeakMap,this.lightweightCache=new WeakMap,this.startTransition=async e=>(e(),!1),this.update=e=>{let t=this.options,n=this.basepath??t?.basepath??`/`,r=this.basepath===void 0,i=t?.rewrite;if(this.options={...t,...e},this.isServer=this.options.isServer??!1??typeof document>`u`,this.protocolAllowlist=new Set(this.options.protocolAllowlist),this.options.pathParamsAllowedCharacters&&(this.pathParamsDecoder=zj(this.options.pathParamsAllowedCharacters)),(!this.history||this.options.history&&this.options.history!==this.history)&&(this.history=this.options.history?this.options.history:TM()),this.origin=this.options.origin,this.origin||=window?.origin&&window.origin!==`null`?window.origin:`http://localhost`,this.history&&this.updateLatestLocation(),this.options.routeTree!==this.routeTree){this.routeTree=this.options.routeTree;let e;this.resolvePathCache=sj(1e3),e=this.buildRouteTree(),this.setRoutes(e)}if(!this.stores&&this.latestLocation){let e=this.getStoreConfig(this);this.batch=e.batch,this.stores=yM(this.latestLocation,e),rM(this)}let a=this.options.basepath??`/`,o=this.options.rewrite;if(r||n!==a||i!==o){this.basepath=a;let e=[],t=Fj(a);t&&t!==`/`&&e.push(gM({basepath:a})),o&&e.push(o),this.rewrite=e.length===0?void 0:e.length===1?e[0]:hM(e),this.history&&this.updateLatestLocation(),this.stores&&this.stores.location.set(this.latestLocation)}},this.updateLatestLocation=()=>{this.latestLocation=this.parseLocation(this.history.location,this.latestLocation)},this.buildRouteTree=()=>{let e=xj(this.routeTree,this.options.caseSensitive,(e,t)=>{e.init({originalIndex:t})});return this.options.routeMasks&&gj(this.options.routeMasks,e.processedTree),e},this.subscribe=(e,t)=>{let n={eventType:e,fn:t};return this.subscribers.add(n),()=>{this.subscribers.delete(n)}},this.emit=e=>{for(let t of this.subscribers)if(t.eventType===e.type)try{t.fn(e)}catch(e){console.error(e)}},this.parseLocation=(e,t)=>{let n=({pathname:e,search:n,hash:r,href:i,state:a})=>{if(!this.rewrite&&!/[ \x00-\x1f\x7f\u0080-\uffff]/.test(e)){let i=this.options.parseSearch(n),o=this.options.stringifySearch(i);return{href:e+o+r,publicHref:e+o+r,pathname:rj(e).path,external:!1,searchStr:o,search:GA(t?.search,i),hash:rj(r.slice(1)).path,state:KA(t?.state,a)}}let o=new URL(i,this.origin),s=_M(this.rewrite,o),c=this.options.parseSearch(s.search),l=this.options.stringifySearch(c);return s.search=l,{href:s.href.replace(s.origin,``),publicHref:i,pathname:rj(s.pathname).path,external:!!this.rewrite&&s.origin!==this.origin,searchStr:l,search:GA(t?.search,c),hash:rj(s.hash.slice(1)).path,state:KA(t?.state,a)}},r=n(e),{__tempLocation:i,__tempKey:a}=r.state;if(i&&(!a||a===this.tempLocationKey)){let e=n(i);return e.state.key=r.state.key,e.state.__TSR_key=r.state.__TSR_key,delete e.state.__tempLocation,{...e,maskedLocation:r}}return r},this.resolvePathWithBase=(e,t)=>Rj({base:e,to:t.includes(`//`)?Mj(t):t,trailingSlash:this.options.trailingSlash,cache:this.resolvePathCache}),this.matchRoutes=(e,t,n)=>typeof e==`string`?this.matchRoutesInternal({pathname:e,search:t},n):this.matchRoutesInternal(e,t),this.getMatchedRoutes=e=>{let t=Object.create(null),n=yj(Pj(e),this.processedTree,!0);return n&&Object.assign(t,n.rawParams),[n?.branch||[this.routesById.__root__],t,n?.route]},this.buildLocation=e=>{let t=(t={})=>{let n=t._fromLocation||this._pendingLocation||this.latestLocation,r=this.matchRoutesLightweight(n);t.from;let i=t.unsafeRelative===`path`?n.pathname:t.from??r[1],a=t.to?`${t.to}`:void 0,o=r[2],s=Object.assign(Object.create(null),r[3]),c=a?.charCodeAt(0)===47?`/`:this.resolvePathWithBase(i,`.`),l=a?this.resolvePathWithBase(c,a):c,u=BM(t.params,s),d=this.routesByPath[Pj(l)],f;if(d)f=this.getRouteBranch(d);else if(l.includes(`$`))f=[];else{let[e,t,n]=this.getMatchedRoutes(l);f=e,this.options.notFoundRoute&&(!n||n.path!==`/`&&t[`**`])&&(f=[...f,this.options.notFoundRoute])}if(f.length&&UA(u))for(let e of f){let t=e.options.params?.stringify??e.options.stringifyParams;if(t)try{Object.assign(u,t(u))}catch{}}let p=e.leaveParams?l:rj(Vj({path:l,params:u,decoder:this.pathParamsDecoder,server:this.isServer}).interpolatedPath).path,m=o;if(e._includeValidateSearch&&this.options.search?.strict){let e={};f.forEach(t=>{if(t.options.validateSearch)try{Object.assign(e,LM(t.options.validateSearch,{...e,...m}))}catch{}}),m=e}m=RM(m,t,f,e._includeValidateSearch),m=GA(o,m);let h=this.options.stringifySearch(m),g=t.hash===!0?n.hash:t.hash?BA(t.hash,n.hash):void 0,_=g?`#${g}`:``,v=t.state===!0?n.state:t.state?BA(t.state,n.state):{};v=KA(n.state,v);let y=`${p}${h}${_}`,b,x,S=!1;if(this.rewrite){let e=new URL(y,this.origin),t=vM(this.rewrite,e);b=e.href.replace(e.origin,``),t.origin===this.origin?x=t.pathname+t.search+t.hash:(x=t.href,S=!0)}else b=ij(y),x=b;return{publicHref:x,href:b,pathname:p,search:m,searchStr:h,state:v,hash:g??``,external:S,unmaskOnReload:t.unmaskOnReload}},n=(n={},r)=>{let i=t(n),a=r?t(r):void 0;if(!a){let n=Object.create(null);if(this.options.routeMasks){let o=_j(i.pathname,this.processedTree);if(o){Object.assign(n,o.rawParams);let{from:i,params:s,...c}=o.route,l=BM(s,n);r={from:e.from,...c,params:l},a=t(r)}}}return a&&(i.maskedLocation=a),i};return e.mask?n(e,{from:e.from,...e.mask}):n(e)},this.commitLocation=async({viewTransition:e,ignoreBlocker:t,...n})=>{let r,i=Pj(this.latestLocation.href)===Pj(n.href)&&ZA(MM(n.state),MM(this.latestLocation.state)),a=this._commitPromise,o,s=new Promise(e=>{o=e});if(s.resolve=()=>{o(),a?.resolve()},this._commitPromise=s,i)this.load();else{let{maskedLocation:i,hashScrollIntoView:a,...o}=n;i&&(o={...i,state:{...i.state,__tempKey:void 0,__tempLocation:{...o,search:o.searchStr,state:{...o.state,__tempKey:void 0,__tempLocation:void 0,__TSR_key:void 0,key:void 0}}}},(o.unmaskOnReload??this.options.unmaskOnReload??!1)&&(o.state.__tempKey=this.tempLocationKey)),o.state.__hashScrollIntoViewOptions=a??this.options.defaultHashScrollIntoView??!0,this.shouldViewTransition=e,r=n.replace?`REPLACE`:`PUSH`,this.history[r===`REPLACE`?`replace`:`push`](o.publicHref,o.state,{ignoreBlocker:t}),this.history.subscribers.size||this.load({action:{type:r}})}return this._scroll.next=n.resetScroll??!0,this._commitPromise},this.buildAndCommitLocation=({replace:e,resetScroll:t,hashScrollIntoView:n,viewTransition:r,ignoreBlocker:i,_redirects:a,href:o,...s}={})=>{if(o){let t=this.history.location.state.__TSR_index,n=OM(o,{__TSR_index:e?t:t+1}),r=new URL(n.pathname,this.origin);s.to=_M(this.rewrite,r).pathname,s.search=this.options.parseSearch(n.search),s.hash=n.hash.slice(1)}let c=this.buildLocation({...s,_includeValidateSearch:!0});a&&(c._redirects=a),this._pendingLocation=c;let l=this.commitLocation({...c,viewTransition:r,replace:e,resetScroll:t,hashScrollIntoView:n,ignoreBlocker:i});return queueMicrotask(()=>{this._pendingLocation===c&&(this._pendingLocation=void 0)}),l},this.navigate=async({to:e,reloadDocument:t,href:n,publicHref:r,...i})=>{let a=!1;if(n)try{new URL(`${n}`),a=!0}catch{}if(a&&!t&&(t=!0),t){if(e!==void 0||!n){let t=this.buildLocation({to:e,...i});n??=t.publicHref,r??=t.publicHref}let t=!a&&r?r:n;if(nj(t,this.protocolAllowlist))return;if(!i.ignoreBlocker){let e=this.history.getBlockers?.()??[];for(let t of e)if(t?.blockerFn&&await t.blockerFn({currentLocation:this.latestLocation,nextLocation:this.latestLocation,action:`PUSH`}))return}i.replace?window.location.replace(t):window.location.href=t;return}return this.buildAndCommitLocation({...i,href:n,to:e,_isNavigate:!0})},this.load=async e=>{this.updateLatestLocation(),e?.action&&(this._scroll.hash=e.action.type===`PUSH`||e.action.type===`REPLACE`),await MN(this,e)},this.startViewTransition=e=>{let t=this.shouldViewTransition??this.options.defaultViewTransition;if(this.shouldViewTransition=void 0,t&&typeof document.startViewTransition==`function`){let n;if(typeof t==`object`&&window.CSS?.supports?.(`selector(:active-view-transition-type(a))`)){let r=this.latestLocation,i=this.stores.resolvedLocation.get(),a=typeof t.types==`function`?t.types(jM(r,i)):t.types;if(a===!1)return e();n={update:e,types:a}}else n=e;return document.startViewTransition(n).updateCallbackDone}return e()},this.invalidate=e=>{let t=this._committed,n=e?.filter,r=this._preloads,i=new Set([...t,...this._cache.values(),...[...r?.values()??[]].flat(),...this._tx?.[3]??[]].filter(e=>!n||n(e)).map(e=>e.id)),a=[];for(let[e,t]of r??[])t.some(e=>i.has(e.id))&&(r.delete(e),a.push(e));let o=t=>{if(i.has(t.id)){let n=this.routesById[t.routeId],r={...t,invalid:!0,...(e?.forcePending||t.status===`error`||t.status===`notFound`)&&AM(n)?{status:`pending`,error:void 0}:void 0};return t._flight=void 0,r}return t};this._committed=t.map(o);for(let[t,n]of this._cache)i.has(t)&&(n.invalid=!0,e?.forcePending&&(n.status=`pending`));for(let e of i)this._flights?.delete(e);for(let e of a)e.abort();return this.shouldViewTransition=!1,this.load({sync:e?.sync})},this.resolveRedirect=e=>{let t=e.headers.get(`Location`);if(!e.options.href||e.options._builtLocation){let t=(e.options._builtLocation??this.buildLocation(e.options)).publicHref||`/`;e.options.href=t,e.headers.set(`Location`,t)}else if(t)try{let n=new URL(t);if(this.origin&&n.origin===this.origin){let t=n.pathname+n.search+n.hash;e.options.href=t,e.headers.set(`Location`,t)}}catch{}if(e.options.href&&!e.options._builtLocation&&nj(e.options.href,this.protocolAllowlist))throw Error(`Redirect blocked: unsafe protocol`);return e.headers.get(`Location`)||e.headers.set(`Location`,e.options.href),e},this.clearCache=e=>{let t=this._cache,n=this._preloads,r=e?.filter,i=[],a=[];for(let[e,n]of t)(!r||r(n))&&(a.push(e),i.push(n));let o=[];for(let[e,t]of n??[])(!r||t.some(r))&&(o.push(e),i.push(...t));for(let e of a)t.delete(e);for(let e of o)n.delete(e);for(let e of i){let t=e._flight;e._flight=void 0,t&&!--t[2]&&(this._flights?.get(e.id)===t&&this._flights.delete(e.id),o.push(t[1]))}for(let e of o)e.abort()},this.loadRouteChunk=WM,this.preloadRoute=e=>NN(this,e),this.matchRoute=(e,t)=>{let n={...e,to:e.to?this.resolvePathWithBase(e.from||``,e.to):void 0,params:e.params||{},leaveParams:!0},r=this.buildLocation(n),i=this.stores.status.get()===`pending`;if(t?.pending&&!i)return!1;let a=t?.pending??!i?this.latestLocation:this.stores.resolvedLocation.get()||this.stores.location.get(),o=vj(r.pathname,t?.caseSensitive??!1,t?.fuzzy??!1,a.pathname,this.processedTree);return!o||e.params&&!ZA(o.rawParams,e.params,{partial:!0})?!1:t?.includeSearch??!0?ZA(a.search,r.search,{partial:!0})?o.rawParams:!1:o.rawParams},this.getStoreConfig=t,this.update({defaultPreloadDelay:50,defaultPendingMs:1e3,defaultPendingMinMs:500,context:void 0,...e,caseSensitive:e.caseSensitive??!1,notFoundMode:e.notFoundMode??`fuzzy`,stringifySearch:e.stringifySearch??lM,parseSearch:e.parseSearch??cM,protocolAllowlist:e.protocolAllowlist??tj}),self.__TSR_ROUTER__=this}isShell(){return!!this.options.isShell}get state(){return this.stores.__store.get()}setRoutes({routesById:e,routesByPath:t,processedTree:n}){this.routesById=e,this.routesByPath=t,this.processedTree=n;let r=this.options.notFoundRoute;r&&(r.init({originalIndex:99999999999}),this.routesById[r.id]=r)}getRouteBranch(e){let t=this.routeBranchCache.get(e);return t||(t=wj(e),this.routeBranchCache.set(e,t)),t}matchRoutesInternal(e,t){let[n,r,i]=this.getMatchedRoutes(e.pathname),a=n,o=!1;(i?i.path!==`/`&&r[`**`]:Pj(e.pathname))&&(this.options.notFoundRoute?a=[...a,this.options.notFoundRoute]:o=!0);let s=o?zM(this.options.notFoundMode,a):void 0,c=Array(a.length),l=this._committed,u=(e,t)=>{let n=l[t];return n?.routeId===e.id?n:e===this.options.notFoundRoute?l.find(t=>t.routeId===e.id):void 0},d;for(let n=0;n<a.length;n++){let i=a[n],o=c[n-1],l,f,p;{let n=o?.search??e.search,r=o?._strictSearch??void 0;try{let e=LM(i.options.validateSearch,{...n})??void 0;l={...n,...e},f={...r,...e}}catch(e){let r=e;if(e instanceof FM||(r=new FM(e.message,{cause:e})),t?.throwOnError)throw r;l=n,f={},p=r}}let m=``,h=``;try{m=i.options.loaderDeps?.({search:l})??``,h=m&&JSON.stringify(m)||``}catch(e){if(t?.throwOnError)throw e;p??=e}let{interpolatedPath:g,usedParams:_}=Vj({path:i.fullPath,params:r,decoder:this.pathParamsDecoder,server:this.isServer}),v=i.id+g+h,y=u(i,n),b=this._cache.get(v)??(y?.id===v?y:void 0);d=b?._strictParams??Object.assign(_,d);let x;if(!b)try{VM(i,d)}catch(e){if(x=Uj(e)||mM(e)?e:new IM(e.message,{cause:e}),t?.throwOnError)throw x}let S=y?`stay`:`enter`,C;if(b)C={...b,cause:S,search:GA(y?y.search:b.search,l),_strictSearch:f,searchError:p};else{let e=AM(i)?`pending`:`success`;C={id:v,ssr:i.options.ssr,index:n,routeId:i.id,params:y?.params??d,_strictParams:d,pathname:g,updatedAt:Date.now(),search:y?GA(y.search,l):l,_strictSearch:f,searchError:p,status:e,isFetching:!1,error:void 0,paramsError:x,context:{},abortController:t?._controller??new AbortController,cause:S,loaderDeps:y?KA(y.loaderDeps,m):m,invalid:!1,preload:!1,staticData:i.options.staticData||{},fullPath:i.fullPath}}let w=s===i.id;C._notFound&&!w&&(C.error=void 0),C._notFound=w,c[n]=C}for(let e=0;e<c.length;e++){let n=c[e];n.params=n.cause===`stay`?GA(n.params,d):d,t?._controller&&(n.context={})}return c}matchRoutesLightweight(e){let t=RA(this.stores.ids.get()),n=t?this.stores.byRoute.get(t).get():void 0,r=n?.id,i=this.lightweightCache.get(e);if(i&&i[0]===r)return i[1];let[a,o]=this.getMatchedRoutes(e.pathname),s=RA(a),c={...e.search};for(let e of a)try{Object.assign(c,LM(e.options.validateSearch,c))}catch{}let l=n&&n.routeId===s.id&&n.pathname===e.pathname,u;if(l)u=n.params;else{let e=Object.assign(Object.create(null),o);for(let t of a)try{VM(t,e)}catch{}u=e}let d=[a,s.fullPath,c,u];return this.lightweightCache.set(e,[r,d]),d}},FM=class extends Error{},IM=class extends Error{};function LM(e,t){if(e==null)return{};if(`~standard`in e){let n=e[`~standard`].validate(t);if(n instanceof Promise)throw new FM(`Async validation not supported`);if(n.issues)throw new FM(JSON.stringify(n.issues,void 0,2),{cause:n});return n.value}return`parse`in e?e.parse(t):typeof e==`function`?e(t):{}}function RM(e,t,n,r){let i=[];for(let e of n){let t=e.options;`search`in t?t.search?.middlewares&&i.push(...t.search.middlewares):(t.preSearchFilters||t.postSearchFilters)&&i.push(({search:e,next:n})=>{let r=n(t.preSearchFilters?t.preSearchFilters.reduce((e,t)=>t(e),e):e);return t.postSearchFilters?t.postSearchFilters.reduce((e,t)=>t(e),r):r});let n=t.validateSearch;n&&i.push(({search:e,next:t,meta:i})=>{let a=t(e);if(r)try{let e=LM(n,a);if(i&&e)for(let t in e)t in a||(i.defaulted||=new Map).set(t,e[t]);return{...a,...e}}catch{}return a})}let a=(e,n,r)=>{if(e>=i.length){if(!t.search)return{};if(t.search===!0)return n;let e=BA(t.search,n);return r&&(r.explicit=e),e}return i[e]({search:n,next:(t,n)=>{if(n){let n=r||{};return{search:a(e+1,t,n),meta:n}}return a(e+1,t,r)},meta:r})};return a(0,e)}function zM(e,t){if(e!==`root`){let e;for(let n=t.length-1;n>=0;n--){let r=t[n];if(r.options.notFoundComponent)return r.id;e||=r.children&&r.id}if(e)return e}return fM}function BM(e,t){return e===!1||e===null?Object.create(null):(e??!0)===!0?t:Object.assign(t,BA(e,t))}function VM(e,t){let n=e.options.params?.parse??e.options.parseParams;n&&Object.assign(t,n(t))}function HM(e,t){return e.options[t]?.preload?.()}function UM(e,t){let n=HM(e,`component`),r=HM(e,`pendingComponent`),i=t&&r?r.then(t):r;return t&&!r&&t(),n&&i?Promise.all([n,i]).then(()=>{}):n??i}function WM(e,t,n){let r=()=>t===!1?void 0:t?HM(e,t):UM(e,n),i=e._lazy;if(i)return i===!0?r():i.then(r);if(!e.lazyFn)return r();let a=e.lazyFn().then(t=>{{let{id:n,...r}=t.options;Object.assign(e.options,r),e._lazy=!0}},t=>{throw e._lazy=void 0,t});return e._lazy=a,a.then(r)}function GM(e){let t=e.findIndex(e=>e.status!==`success`||e._notFound)+1;return t&&t<e.length?e.slice(0,t):e}var KM=0,qM=1,JM=2,YM=3,XM=4;function ZM(e){return typeof e[0]==`number`}function QM(e,t){return t.aborted?Promise.race([Promise.reject(t),e]):new Promise((n,r)=>{let i=()=>r(t);t.addEventListener(`abort`,i,{once:!0}),Promise.resolve(e).then(n,r).finally(()=>t.removeEventListener(`abort`,i))})}function $M(e,t){return e.routesById[t.routeId]}function eN(e,t,n){return mM(e)?[YM,e]:Uj(e)?(e.routeId||=n,[JM,e]):(t&&typeof e?.then==`function`&&(e=Error(`A Promise was thrown`,{cause:e})),t?[qM,e]:[KM,e])}function tN(e,t){let n=eN(t,!0,e.id);if(n[0]!==qM)return n;try{e.options.onError?.(n[1])}catch(t){n=eN(t,!0,e.id)}return n}function nN(e,t,n){return n[0].signal.aborted||!n[2]()?(n[0].abort(),[XM]):tN(e,t)}function rN(e,t){return n=>e.navigate({...n,_fromLocation:t})}async function iN(e,t,n,r,i,a){let[o,s]=t,c=n[0].signal,l=!!n[4];for(let t=n[7]??0;t<r;t++){let r=s[t],i=$M(e,r);r.abortController=n[0];let u=s[t-1]?.context??e.options.context??{},d={params:r.params,location:o,navigate:rN(e,o),buildLocation:e.buildLocation,cause:l?`preload`:r.cause,abortController:n[0],preload:l,matches:s,routeId:i.id},f=u;try{let e=r._ctx;!e&&i.options.context&&(e=r._ctx=i.options.context({...d,deps:r.loaderDeps,context:u})||{}),f={...u,...e},r.context=f}catch(a){return oN(e,r),[t,nN(i,a,n)]}if(c.aborted||!n[2]())return n[0].abort(),[t,[XM]];let p=r.paramsError??r.searchError;if(p!==void 0)return oN(e,r),[t,nN(i,p,n)];let m=i.options.beforeLoad;if(!m)continue;let h={...d,search:r.search,context:f,...e.options.additionalContext},g=r.status;g===`success`&&t>=a&&(r.status=`pending`),n[8]?.();try{lN(e,r,`beforeLoad`,n[0]);let a=await QM(m(h),c);if(!n[2]())return n[0].abort(),[t,[XM]];let o=eN(a,!1,i.id);if(o[0]!==KM)return oN(e,r),[t,o];r.context={...f,...a}}catch(a){return oN(e,r),[t,nN(i,a,n)]}finally{g===`success`&&r.status===`pending`&&(r.status=`success`),lN(e,r,!1,n[0])}}i()}function aN(e,t,n){if(!(!n||--n[2])){if(e._flights?.get(t.id)===n){let n=e._tx;if(n&&!n[0].signal.aborted&&!n[3].includes(t)&&n[3].some(e=>e.id===t.id)&&n[3].some(e=>e.isFetching===`beforeLoad`))return;e._flights.delete(t.id)}return n[1]}}function oN(e,t){let n=t._flight;t._flight=void 0,aN(e,t,n)?.abort()}function sN(e,t,n,r){let i=[];for(let a of t)if(!n?.includes(a)){let t=a._flight;if(a._flight=void 0,r&&t?.[2]===1&&e._flights?.get(a.id)===t&&n?.some(e=>e.id===a.id))t[2]=0;else{let n=aN(e,a,t);n&&i.push(n)}}for(let e of i)e.abort()}function cN(e){for(let t of e){let e=t._flight;e&&e[2]++}}function lN(e,t,n,r){if(t.isFetching=n,r&&e._tx?.[0]!==r)return;let i=e.stores.byRoute.get(t.routeId),a=i?.get();a?.id===t.id&&i.set({...a,isFetching:n})}function uN(e,t,n,r,i,a,o){let s=t[0];return{params:n.params,location:s,navigate:rN(e,s),cause:o?`preload`:n.cause,abortController:i,preload:o,deps:n.loaderDeps,parentMatchPromise:a,context:n.context,route:r,...e.options.additionalContext}}async function dN(e,t,n,r,i,a,o,s){let c=s.signal;if(c.aborted)return[XM];if(!i)return[KM,void 0];let l=n._flight;lN(e,n,`loader`,s);try{if(!l){let s=new AbortController;l=[Promise.resolve().then(()=>i(uN(e,t,n,r,s,a,o))).then(e=>eN(e,!1,r.id),e=>eN(e,!0,r.id)).then(t=>(t[0]!==KM&&e._flights?.get(n.id)===l&&(e._flights.delete(n.id),l[2]||s.abort()),t[0]===qM&&l[2]?tN(r,t[1]):t)),s,1],(e._flights??=new Map).set(n.id,l)}return n._flight=l,n.abortController=l[1],await QM(l[0],c)}catch(t){if(t!==c)throw t;return oN(e,n),[XM]}finally{lN(e,n,!1,s)}}function fN(e,t,n){t[0]===KM?(e.loaderData=t[1],e.error=void 0,e.status=`success`,e.invalid=!1,e.updatedAt=Date.now(),e.preload=n):t[0]!==YM&&(e.status=`success`,e.error=void 0,e.invalid=!0)}function pN(e,t,n){let r=e._cache.get(t.id);if(r!==n||e._committed.some(e=>e.id===t.id&&e._flight===t._flight))return;let i={...t,_notFound:void 0,context:{}};i._flight&&i._flight[2]++,e._cache.set(t.id,i),r&&oN(e,r)}function mN(e,t){return t[0]===qM||t[0]===JM?{...e,status:t[0]===qM?`error`:`notFound`,error:t[1],_flight:void 0}:e}function hN(e,t,n,r,i,a,o){let s=t[1][n],c=$M(e,s),l=!!a[4],u=e._cache.get(s.id),d,f=!1,p;try{if(s.status===`success`&&(d=c.options.shouldReload,typeof d==`function`&&(d=d(uN(e,t,s,c,a[0],i,l))),a[2]()||(a[0].abort(),p=[XM])),!p){if(s.status!==`success`)f=!0;else{let t=a[4]||s.preload?c.options.preloadStaleTime??e.options.defaultPreloadStaleTime??3e4:c.options.staleTime??e.options.defaultStaleTime??0;f=!!(s.invalid||d||d===void 0&&Date.now()-s.updatedAt>=t&&(a[6]||s.cause===`enter`||a[3].some(e=>e.routeId===s.routeId&&e.id!==s.id)))}}}catch(t){s.invalid=!0,oN(e,s),p=nN(c,t,a)}let m=c.options.loader,h=typeof m==`function`?m:m?.handler,g=(!l||c.options.preload!==!1)&&m?e._flights?.get(s.id):void 0;g===s._flight||p?g=void 0:g&&!f&&!l&&d===void 0?f=!0:f||(g=void 0);let _=!!(m&&f&&s.status===`success`&&!l&&!a[5]&&((typeof m==`function`?void 0:m?.staleReloadMode)??e.options.defaultStaleReloadMode)!==`blocking`),v=f&&(!l||c.options.preload!==!1),y=v&&!_&&(s.status!==`success`||!!m),b=c.lazyFn&&c._lazy!==!0?a[8]:void 0;if(v&&!m&&(s.invalid=!1,s.updatedAt=Date.now()),g&&g[2]++,y){let t=s._flight;s._flight=g,aN(e,s,t)?.abort(),s.status===`success`&&n>=o&&(s.status=`pending`),a[8]?.()}v||(s.isFetching=!1);let x=(p?Promise.resolve(p):y?dN(e,t,s,c,h,i,l,a[0]):Promise.resolve([KM,s.loaderData])).then(t=>(y&&(fN(s,t,l),t[0]===KM&&(m&&!a[0].signal.aborted&&pN(e,s,u),s.status=`pending`)),t)),S=QM(Promise.resolve().then(()=>WM(c,void 0,b)),a[0].signal).then(()=>void 0,e=>[n,nN(c,e,a)]).then(e=>x.then(t=>(y&&!e&&t[0]===KM&&s.status===`pending`&&a[2]()&&(s.status=`success`,a[8]?.()),e)));if(r.push([n,x,S]),!_)return x.then(e=>mN(s,e));let C={...s,status:`pending`,preload:!1,_flight:g};s.invalid=!1,s.isFetching=`loader`;let w=dN(e,t,C,c,h,i,!1,a[0]).then(e=>(s.isFetching=!1,fN(C,e,!1),e));return(t[2]??=[]).push([n,w,S,C]),w.then(e=>mN(C,e))}async function gN(e,t,n,r,i=0){let a=n?.[1][1],o=a?.routeId?t.findIndex(e=>e.routeId===a.routeId):n?.[0]??t.length-1;o<0&&(o=0);for(let n=o;n>=0;n--){let i=$M(e,t[n]),a=WM(i,!1);if(a)try{await QM(a,r)}catch(e){if(e===r)throw e}if(i.options.notFoundComponent)return n}return a?.routeId?o:i}function _N(e,t){t[2]&&=(sN(e,t[2].map(e=>e[3])),void 0)}async function vN(e,t,n,r){let i;try{await Promise.all(e.map(e=>e[1].then(async t=>{let a=e[0];if(!(r&&a>=await r)){if(t[0]>=YM)throw[a,t];!i&&t[0]!==KM&&(i=[a,t],await Promise.all((n??[]).map(e=>{if(!(e[0]<=a))return e[1].then(t=>{if(t[0]===YM)throw[e[0],t]})})))}})))}catch(e){return e}return t??i}async function yN(e,t,n,r,i,a,o){let s=t[1],c=await a,l=!1,u=s.findIndex(e=>e._notFound),d=t=>t[1][0]===JM?gN(e,s,t,r.signal):t[0],f=u<0?s.length:u;if((c?.[1][0]??0)>=YM)f=0;else if(c){f=c[2]??=await d(c);for(let e of n){if(e[0]>=f)break;let t=await e[1];if(t[0]!==KM&&t[0]<YM&&!(`loaderData`in s[e[0]])){c=[e[0],t],f=c[2]=await d(c);break}}}for(let e of n){if(e[0]>=f)break;let t=await e[2];if(t){c=t;break}}if((c?.[1][0]??0)>=YM){let n=c[1];if(n[0]!==YM||n[1].options.reloadDocument||i<20)return _N(e,t),n;l=!0,c=[0,[qM,Error(`Too many redirects`)]]}let p=c?c[2]??await d(c):u;if(p>=0){let i=c?.[1],a=i?.[0],u=s[p],d=i?.[1],f=()=>{i&&(u._notFound=void 0,a===qM?u.status=`error`:(d.routeId=u.routeId,u.routeId===e.routeTree.id?(u.status=`success`,u._notFound=!0):u.status=`notFound`),u.error=d,u.isFetching=!1)};f();let m=$M(e,u);try{await QM(i?Promise.resolve().then(()=>WM(m,a===qM?`errorComponent`:`notFoundComponent`)):Promise.all([WM(m),WM(m,`notFoundComponent`)]),r.signal)}catch(n){if(n===r.signal)return _N(e,t),[XM]}i?l&&(r.abort(),await Promise.all([...n.map(e=>e[1]),...n.map(e=>e[2]),...(t[2]??[]).map(e=>e[1])]),_N(e,t),sN(e,s),f()):(u.status=`success`,o?.())}return t}async function bN(e,t,n,r=0,i=t[1].length){let a=t[1];for(let t=r;t<i;t++){let r=a[t],i=$M(e,r).options;if(i.head||i.scripts)try{let t={ssr:e.options.ssr,matches:a,match:r,params:r.params,loaderData:r.loaderData},[o,s]=await QM(Promise.all([i.head?.(t),i.scripts?.(t)]),n);r.meta=o?.meta,r.links=o?.links,r.headScripts=o?.scripts,r.styles=o?.styles,r.scripts=s}catch(e){if(e===n)break;console.error(e)}if(r.status!==`success`||r._notFound)break}return t}async function xN(e,t,n,r){let i=[t,n],a=e.stores.matches.get(),o=n.findIndex(e=>e._notFound);if(e.options.notFoundMode!==`root`&&o>=0){let t=await gN(e,i[1],void 0,r[0].signal,o);t!==o&&(n[o]._notFound=void 0,n[t]._notFound=!0),o=t}let s=o<0?n.length:o+1,c=0;for(;c<s&&c!==o;){let e=n[c],t=r[3][c],i=a[c];if(t?.id!==e.id||t.status!==`success`||t._notFound||e.preload||i?.id!==e.id||i.status!==`success`||i._notFound)break;c++}let l=[],u=r[7]??0,d=u?Promise.resolve(i[1][u-1]):void 0,f=()=>{for(let t=u;t<s&&!r[0].signal.aborted;t++)d=hN(e,i,t,l,d,r,c)},p=await iN(e,i,r,s,f,c);if(p&&(r[5]=!0,s=p[0],p[1][0]===JM?(p[2]=await gN(e,i[1],p,r[0].signal),s=Math.min(s,p[2]+1)):p[1][0]>=YM&&(s=0),f()),r[2]()&&!r[4]){let t=[];for(let[n,r]of e._flights??[])r[2]||(e._flights.delete(n),t.push(r[1]));for(let e of t)e.abort()}let m;try{let t=yN(e,i,l,r[0],r[1],vN(l,p,i[2]),r[8]);i[2]?.length&&(i[3]=vN(i[2],void 0,void 0,t.then(e=>ZM(e)?0:GM(e[1]).length,()=>0))),m=await t}catch(t){throw _N(e,i),t}return ZM(m)?m:bN(e,m,r[0].signal,r[7]===m[1].length?r[7]:0)}function SN(e,t){if(e._tx!==t)return;let n=e._pending,r=!1,i=n?.[0][3][n[1]]?.id;n?.[0]!==t&&(n&&t[3][n[1]]?.id===i?(n[0]=t,r=!0):(clearTimeout(n?.[3]),e._pending=n=void 0));let a=t[3],o=e.stores.matches.get(),s=-1,c,l,u,d=!1;for(let t=0;t<a.length;t++){let n=a[t],r=n.status===`success`;if(d=o[t]?.id===n.id&&o[t]?.status===`pending`,r&&!d)continue;let i=$M(e,n);if(c=r&&d||n.invalid?0:i.options.pendingMs??e.options.defaultPendingMs,u=i.options.pendingComponent??e.options.defaultPendingComponent,!u||typeof c!=`number`||c===1/0)return;s=t,l=i.options.pendingMinMs??e.options.defaultPendingMinMs??0;break}if(s<0)return;let f=a[s].id;if((!n||n[1]!==s||i!==f)&&(clearTimeout(n?.[3]),e._pending=n=[t,s,d?Date.now()+l:t[4]+c,void 0,d?Promise.resolve(!0):void 0,u]),n[4]&&!r&&n[5]===u)return;if(n[5]=u,!n[4]){clearTimeout(n[3]);let r=n[2]-Date.now();if(r>0){n[3]=setTimeout(()=>SN(e,t),r);return}n[2]=0}let p=a.map(e=>({...e,_flight:void 0}));p[s].status=`pending`;let m=e.startTransition(()=>e.stores.setMatches(p),p).then(t=>(t&&e._pending===n&&n[4]===m&&!n[2]&&(n[2]=Date.now()+l),t));n[4]=m}function CN(e,t){let n=e._pending;n?.[0]===t&&(clearTimeout(n[3]),e._pending=void 0)}function wN(e,t){e._committed=t,e.stores.setMatches(t)}function TN(e,t){sN(e,t[1]),_N(e,t)}function EN(e,t,n,r){let i=e._committed,a=e._cache;for(let e of n)e.preload=!1,r&&(e._assetEnd=void 0);let o=GM(n).length,s=new Map,c=Date.now();for(let t of[...i,...a.values()]){if(t.status!==`success`||n.some((e,n)=>e.id===t.id&&(n<o||e.status===`success`)))continue;let r=$M(e,t);!r.options.loader||c-t.updatedAt>=(t.preload?r.options.preloadGcTime??e.options.defaultPreloadGcTime??3e5:r.options.gcTime??e.options.defaultGcTime??3e5)||s.set(t.id,a.get(t.id)===t?t:{...t,_flight:void 0,isFetching:!1,context:{}})}t[3]=[],e._cache=s,wN(e,n),sN(e,[...a.values(),...i],[...n,...s.values()]),NM(e,i,n,()=>e._tx===t)}async function DN(e,t){let n=e._tx;for(;n&&n!==t;){if(await n[5],e._tx===n)return;n=e._tx}}async function ON(e,t,n){await e.navigate({...n.options,replace:!0,ignoreBlocker:!0,_redirects:t[1]+1})}function kN(e,t){CN(e,t),t[0].abort(),sN(e,t[3]),t[3]=[],e._tx===t&&(e.batch(()=>{e.stores.status.set(`idle`),e.stores.setMatches(e._committed)}),e._tx===t&&(e._commitPromise?.resolve(),e._commitPromise=void 0))}async function AN(e,t,n,r,i){let a=n.map(e=>({...e}));cN(a);for(let t of r)oN(e,a[t[0]]),a[t[0]]=t[3];let o=[t[2],a],s;try{s=await yN(e,o,r,t[0],t[1],i)}catch(t){throw sN(e,a),t}if(ZM(s)){sN(e,a),s[0]===YM&&e._tx===t&&e._committed===n&&await ON(e,t,s[1]);return}let c=await bN(e,s,t[0].signal);if(e._tx!==t||e._committed!==n){sN(e,c[1]);return}for(let t of c[1]){let n=e._cache.get(t.id);n?._flight&&n._flight===t._flight&&(e._cache.delete(t.id),oN(e,n))}wN(e,c[1]),sN(e,n,c[1])}async function jN(e,t,n,r,i,a){let o=[t[0],t[1],()=>e._tx===t&&!!t[3].length,e._committed,void 0,i,n,a,r],s=await xN(e,t[2],t[3],o);if(ZM(s)){s[0]===YM&&e._tx===t?(CN(e,t),sN(e,t[3]),t[3]=[],e._tx===t&&await ON(e,t,s[1])):kN(e,t);return}let c=e._pending;if(c?.[0]===t&&(clearTimeout(c[3]),c[4])){let n=t[0].signal,r=!1;try{r=await QM(c[4],n)}catch(e){if(e!==n)throw e}if(r&&e._pending===c&&c[0]===t){let e=c[2]-Date.now();if(e>0){try{await QM(new Promise(t=>{c[3]=setTimeout(t,e)}),n)}catch{}clearTimeout(c[3])}}}if(e._tx!==t){CN(e,t),TN(e,s);return}let l=t[2],u=jM(l,e.stores.resolvedLocation.get()),d=s[2];await e.startViewTransition(async()=>{if(e._tx!==t){TN(e,s);return}let n=await e.startTransition(()=>{CN(e,t),EN(e,t,s[1],a),e._tx===t&&(e.emit({type:`onLoad`,...u}),e._tx===t&&e.emit({type:`onBeforeRouteMount`,...u}))},s[1]);if(e._tx!==t){_N(e,s);return}d?.length&&AN(e,t,s[1],d,s[3]).catch(console.error),e.batch(()=>{e.stores.resolvedLocation.set(l),e.stores.status.set(`idle`),e._tx===t&&e.emit({type:`onResolved`,...u}),n&&e._tx===t&&e.emit({type:`onRendered`,...u})}),e._tx===t&&(e._commitPromise?.resolve(),e._commitPromise=void 0)})}async function MN(e,t){let n=e._tx,r=e.stores.resolvedLocation.get(),i=r??e.stores.location.get(),a=e.latestLocation,o=e._pendingLocation,s=o?.href===a.href?o._redirects??0:0,c=e._handoff,l=c?.[0](),u=new AbortController,d=e._preflight;if(e._preflight=u,l||c?.[1](),d?.abort(),u.signal.aborted){await DN(e,n);return}let f=jM(a,r);if(e.emit({type:`onBeforeNavigate`,...f}),u.signal.aborted||e.emit({type:`onBeforeLoad`,...f}),u.signal.aborted){await DN(e,n);return}let p=i.href===a.href,m,h=u;try{m=e.matchRoutes(a,{_controller:u}),cN(m)}catch(t){if(u.abort(),!mM(t)){await DN(e),e._commitPromise?.resolve(),e._commitPromise=void 0;return}await e.navigate({...t.options,replace:!0,ignoreBlocker:!0}),await DN(e,n);return}let g=l?c[1](m):void 0;if(g?h=l:l?.abort(),u.signal.aborted){sN(e,m),await DN(e,n);return}e._preflight=void 0;let _=[h,s,a,m,Date.now(),Promise.resolve().then(()=>jN(e,_,p,()=>SN(e,_),t?.sync,g)).catch(()=>{e._tx===_&&kN(e,_)})];if(e._tx=_,n){for(let t of e.stores.matches.get()){if(e._tx!==_)break;t.isFetching&&lN(e,t,!1)}n[0].abort(),sN(e,n[3],_[3],!0)}if(e._tx!==_){sN(e,_[3]),_[3]=[],await DN(e,_);return}e.batch(()=>{e.stores.status.set(`pending`),e.stores.location.set(a)}),!r&&!m.some(e=>e._notFound)&&SN(e,_);try{await _[5]}finally{await DN(e,_)}}async function NN(e,t,n=0){if(n>20)return;let r=t._builtLocation??e.buildLocation(t),i=e._committed,a=new AbortController,o;try{o=e.matchRoutes(r,{_controller:a}),cN(o)}catch(e){a.abort(),Uj(e)||console.error(e);return}(e._preloads??=new Map).set(a,o);let s;try{let t;try{t=await xN(e,r,o,[a,n,()=>!0,i,!0])}finally{s=e._preloads.delete(a),sN(e,o),a.abort()}if(!ZM(t))return t[1];if(s&&t[0]===YM&&!t[1].options.reloadDocument)return NN(e,{...t[1].options,_fromLocation:r},n+1)}catch(e){Uj(e)||console.error(e)}}var PN=`Error preloading route! ☝️`,FN=class{get to(){return this._to}get id(){return this._id}get path(){return this._path}get fullPath(){return this._fullPath}constructor(e){if(this.init=e=>{this.originalIndex=e.originalIndex;let t=this.options,n=!t?.path&&!t?.id;this.parentRoute=this.options.getParentRoute?.(),n?this._path=fM:this.parentRoute||oj();let r=n?fM:t?.path;r&&r!==`/`&&(r=Nj(r));let i=t?.id||r,a=n?fM:jj([this.parentRoute.id===`__root__`?``:this.parentRoute.id,i]);r===`__root__`&&(r=`/`),a!==`__root__`&&(a=jj([`/`,a]));let o=a===`__root__`?`/`:jj([this.parentRoute.fullPath,r]);this._path=r,this._id=a,this._fullPath=o,this._to=Pj(o)},this.addChildren=e=>this._addFileChildren(e),this._addFileChildren=e=>(Array.isArray(e)&&(this.children=e),typeof e==`object`&&e&&(this.children=Object.values(e)),this),this._addFileTypes=()=>this,this.updateLoader=e=>(Object.assign(this.options,e),this),this.update=e=>(Object.assign(this.options,e),this),this.lazy=e=>(this.lazyFn=e,this),this.redirect=e=>pM({from:this.fullPath,...e}),this.options=e||{},this.isRoot=!e?.getParentRoute,e?.id&&e?.path)throw Error(`Route cannot have both an 'id' and a 'path' option.`)}},IN=class extends FN{constructor(e){super(e)}};function LN(e){return(0,Y.jsx)(RN,{...e})}var RN=class extends q.Component{constructor(...e){super(...e),this.state={error:null},this.reset=()=>{this.setState({error:null})}}static getDerivedStateFromProps(e,t){let n=e.getResetKey();return t.error&&t.resetKey!==n?{resetKey:n,error:null}:{resetKey:n}}static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){this.props.onCatch?.(e,t)}render(){let e=this.state.error;return e?q.createElement(this.props.errorComponent??zN,{error:e,reset:this.reset}):this.props.children}};function zN({error:e}){let[t,n]=q.useState(!1);return(0,Y.jsxs)(`div`,{style:{padding:`.5rem`,maxWidth:`100%`},children:[(0,Y.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`.5rem`},children:[(0,Y.jsx)(`strong`,{style:{fontSize:`1rem`},children:`Something went wrong!`}),(0,Y.jsx)(`button`,{style:{appearance:`none`,fontSize:`.6em`,border:`1px solid currentColor`,padding:`.1rem .2rem`,fontWeight:`bold`,borderRadius:`.25rem`},onClick:()=>n(e=>!e),children:t?`Hide Error`:`Show Error`})]}),(0,Y.jsx)(`div`,{style:{height:`.25rem`}}),t?(0,Y.jsx)(`div`,{children:(0,Y.jsx)(`pre`,{style:{fontSize:`.7em`,border:`1px solid red`,borderRadius:`.25rem`,padding:`.3rem`,color:`red`,overflow:`auto`},children:e.message?(0,Y.jsx)(`code`,{children:e.message}):null})}):null]})}function BN({children:e,fallback:t=null}){return(0,Y.jsx)(q.Fragment,{children:VN()?e:t})}function VN(){return q.useSyncExternalStore(HN,()=>!0,()=>!1)}function HN(){return()=>{}}var UN=q.createContext(null);function WN(e){return q.useContext(UN)}var GN=q.createContext(void 0),KN=q.createContext(void 0),qN=(e=>(e[e.None=0]=`None`,e[e.Mutable=1]=`Mutable`,e[e.Watching=2]=`Watching`,e[e.RecursedCheck=4]=`RecursedCheck`,e[e.Recursed=8]=`Recursed`,e[e.Dirty=16]=`Dirty`,e[e.Pending=32]=`Pending`,e))(qN||{});function JN({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0){n=e.nextSub;continue}for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}while(!0)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(!0)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function YN(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}var XN=[],ZN=0,{link:QN,unlink:$N,propagate:eP,checkDirty:tP,shallowPropagate:nP}=JN({update(e){return e._update()},notify(e){XN[iP++]=e,e.flags&=~qN.Watching},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=qN.Mutable|qN.Dirty,cP(e))}}),rP=0,iP=0,aP,oP=0;function sP(e){try{++oP,e()}finally{--oP||lP()}}function cP(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=$N(n,e)}function lP(){if(!(oP>0)){for(;rP<iP;){let e=XN[rP];XN[rP++]=void 0,e.notify()}rP=0,iP=0}}function uP(e,t){let n=typeof e==`function`,r=e,i={_snapshot:n?void 0:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:n?qN.None:qN.Mutable,get(){return aP!==void 0&&QN(i,aP,ZN),i._snapshot},subscribe(e){let t=YN(e),n={current:!1},r=dP(()=>{i.get(),n.current?t.next?.(i._snapshot):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=aP,o=t?.compare??Object.is;if(n)aP=i,++ZN,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=qN.Mutable|qN.RecursedCheck);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{aP=a,n&&(i.flags&=~qN.RecursedCheck),cP(i)}}};return n?(i.flags=qN.Mutable|qN.Dirty,i.get=function(){let e=i.flags;if(e&qN.Dirty||e&qN.Pending&&tP(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&nP(e)}}else e&qN.Pending&&(i.flags=e&~qN.Pending);return aP!==void 0&&QN(i,aP,ZN),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(eP(e),nP(e),lP())}},i}function dP(e){let t=()=>{let t=aP;aP=n,++ZN,n.depsTail=void 0,n.flags=qN.Watching|qN.RecursedCheck;try{return e()}finally{aP=t,n.flags&=~qN.RecursedCheck,cP(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:qN.Watching|qN.RecursedCheck,notify(){let e=this.flags;e&qN.Dirty||e&qN.Pending&&tP(this.deps,this)?t():this.flags=qN.Watching},stop(){this.flags=qN.None,this.depsTail=void 0,cP(this)}};return t(),n}var fP=t((e=>{var t=Bt();function n(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var r=typeof Object.is==`function`?Object.is:n,i=t.useState,a=t.useEffect,o=t.useLayoutEffect,s=t.useDebugValue;function c(e,t){var n=t(),r=i({inst:{value:n,getSnapshot:t}}),c=r[0].inst,u=r[1];return o(function(){c.value=n,c.getSnapshot=t,l(c)&&u({inst:c})},[e,n,t]),a(function(){return l(c)&&u({inst:c}),e(function(){l(c)&&u({inst:c})})},[e]),s(n),n}function l(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!r(e,n)}catch{return!0}}function u(e,t){return t()}var d=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?u:c;e.useSyncExternalStore=t.useSyncExternalStore===void 0?d:t.useSyncExternalStore})),pP=t(((e,t)=>{t.exports=fP()})),mP=t((e=>{var t=Bt(),n=pP();function r(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var i=typeof Object.is==`function`?Object.is:r,a=n.useSyncExternalStore,o=t.useRef,s=t.useEffect,c=t.useMemo,l=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,u){var d=o(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=c(function(){function e(e){if(!a){if(a=!0,o=e,e=r(e),u!==void 0&&f.hasValue){var t=f.value;if(u(t,e))return s=t}return s=e}if(t=s,i(o,e))return t;var n=r(e);return u!==void 0&&u(t,n)?(o=e,t):(o=e,s=n)}var a=!1,o,s,c=n===void 0?null:n;return[function(){return e(t())},c===null?void 0:function(){return e(c())}]},[t,n,r,u]);var p=a(e,d[0],d[1]);return s(function(){f.hasValue=!0,f.value=p},[p]),l(p),p}})),hP=t(((e,t)=>{t.exports=mP()}))();function gP(e,t){return e===t}function _P(e,t,n=gP){let r=(0,q.useCallback)(t=>{if(!e)return()=>{};let{unsubscribe:n}=e.subscribe(t);return n},[e]),i=(0,q.useCallback)(()=>e?.get(),[e]);return(0,hP.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var vP={};function yP(e,t){let n=q.useRef();return r=>{let i=e?.select?e.select(r):r;return e?.structuralSharing??t.options.defaultStructuralSharing?n.current=KA(n.current,i):i}}function bP(e){let t=WN(),n=q.useContext(e.from?KN:GN),r=e.from??n,i=t.stores.getMatchStore(r),a=yP(e,t),o=_P(i,e=>e?a(e):vP);if(o!==vP)return o;(e.shouldThrow??!0)&&oj()}function xP(e){return bP({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function SP(e){let{select:t,...n}=e;return bP({...n,select:e=>t?t(e.loaderDeps):e.loaderDeps})}function CP(e){return bP({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{let n=e.strict===!1?t.params:t._strictParams;return e.select?e.select(n):n}})}function wP(e){return bP({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function TP(e){let t=WN();return q.useCallback(n=>t.navigate({...n,from:n.from??e?.from}),[e?.from,t])}function EP(e){return bP({...e,select:t=>e.select?e.select(t.context):t.context})}function DP(e){let t=q.useRef(e);return ZA(t.current,e,{ignoreUndefined:!1})||(t.current=e),t.current}function OP(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]}function kP(e,t,n){if(e?.external)return nj(e.href,n)?void 0:e.href;if(!BP(t)&&typeof t==`string`&&t.indexOf(`:`)!==-1)try{return new URL(t),nj(t,n)?void 0:t}catch{}}function AP(e,t,n,r,i,a){if(a)return!1;if(n?.exact){if(!Lj(e.pathname,t.pathname,r))return!1}else{let n=Ij(e.pathname,r),i=Ij(t.pathname,r);if(!(n.startsWith(i)&&(n.length===i.length||n[i.length]===`/`)))return!1}return(n?.includeSearch??!0)&&!ZA(e.search,t.search,{partial:!n?.exact,ignoreUndefined:!n?.explicitUndefined})?!1:!n?.includeHash||i&&e.hash===t.hash}function jP(e,t){let n=WN(),r=LA(t),{activeProps:i,inactiveProps:a,activeOptions:o,to:s,preload:c,preloadDelay:l,preloadIntentProximity:u,hashScrollIntoView:d,replace:f,startTransition:p,resetScroll:m,viewTransition:h,children:g,target:_,disabled:v,style:y,className:b,onClick:x,onBlur:S,onFocus:C,onMouseEnter:w,onMouseLeave:T,onTouchStart:E,ignoreBlocker:ee,params:D,search:O,hash:k,state:A,mask:j,reloadDocument:te,unsafeRelative:ne,from:re,_fromLocation:ie,...ae}=e,oe=VN(),se=DP(e.search),ce=DP(e.params),le=DP(o),ue=q.useMemo(()=>e,[n,e.from,e._fromLocation,e.hash,e.to,se,ce,e.state,e.mask,e.unsafeRelative]),M=q.useCallback(e=>{let t=n.buildLocation({_fromLocation:e,...ue}),r=zP(t.maskedLocation?t.maskedLocation.publicHref:t.publicHref,t.maskedLocation?t.maskedLocation.external:t.external,n.history,v),i=kP(r,s,n.protocolAllowlist);return[r?.href,i,AP(e,t,le,n.basepath,oe,i!==void 0)]},[le,v,oe,ue,n,s]),[de,fe,pe]=_P(n.stores.location,M,OP),me=pe?BA(i,{})??NP:MP,he=pe?MP:BA(a,{})??MP,ge=[b,me.className,he.className].filter(Boolean).join(` `),_e=(y||me.style||he.style)&&{...y,...me.style,...he.style},ve=q.useRef(!1),ye=e.reloadDocument||fe||v?!1:c??n.options.defaultPreload,be=l??n.options.defaultPreloadDelay??0,N=q.useCallback(()=>{n.preloadRoute(ue).catch(e=>{console.warn(e),console.warn(PN)})},[n,ue]),xe=q.useCallback(e=>{if(!e){LP(r);return}if(!(e.isIntersecting??ye===`intent`)){e.isIntersecting===!1&&LP(r);return}if(!be){N();return}IP.has(r)||IP.set(r,setTimeout(()=>{IP.delete(r),N()},be))},[N,r,ye,be]);IA(r,xe,ye!==`viewport`),q.useEffect(()=>{ve.current||ye===`render`&&(N(),ve.current=!0)},[N,ye]);let Se=e=>{let t=e.currentTarget.getAttribute(`target`),r=_===void 0?t:_;!v&&!HP(e)&&!e.defaultPrevented&&(!r||r===`_self`)&&e.button===0&&(e.preventDefault(),n.navigate({...ue,replace:f,resetScroll:m,hashScrollIntoView:d,startTransition:p,viewTransition:h,ignoreBlocker:ee}))};if(fe)return{...ae,ref:r,href:fe,...g&&{children:g},..._&&{target:_},...v&&{disabled:v},...y&&{style:y},...b&&{className:b},...x&&{onClick:x},...S&&{onBlur:S},...C&&{onFocus:C},...w&&{onMouseEnter:w},...T&&{onMouseLeave:T},...E&&{onTouchStart:E}};let Ce=()=>{ye===`intent`&&N()},we=()=>{ye===`intent`&&LP(r)};return{...ae,...me,...he,href:de,ref:r,onClick:RP([x,Se]),onBlur:RP([S,we]),onFocus:RP([C,xe]),onMouseEnter:RP([w,xe]),onMouseLeave:RP([T,we]),onTouchStart:RP([E,Ce]),disabled:!!v,target:_,..._e&&{style:_e},...ge&&{className:ge},...v&&PP,...pe&&FP}}var MP={},NP={className:`active`},PP={role:`link`,"aria-disabled":!0},FP={"data-status":`active`,"aria-current":`page`},IP=new WeakMap,LP=e=>{clearTimeout(IP.get(e)),IP.delete(e)},RP=e=>t=>{for(let n of e)if(n){if(t.defaultPrevented)return;n(t)}};function zP(e,t,n,r){if(!r)return t?{href:e,external:!0}:{href:n.createHref(e)||`/`,external:!1}}function BP(e){if(typeof e!=`string`)return!1;let t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}var VP=q.forwardRef((e,t)=>{let{_asChild:n,...r}=e,{type:i,...a}=jP(r,t),o=typeof r.children==`function`?r.children({isActive:a[`data-status`]===`active`}):r.children;if(!n){let{disabled:e,...t}=a;return q.createElement(`a`,t,o)}return q.createElement(n,a,o)});function HP(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}var UP=class extends FN{constructor(e){super(e),this.useMatch=e=>bP({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>EP({...e,from:this.id}),this.useSearch=e=>wP({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>CP({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>SP({...e,from:this.id}),this.useLoaderData=e=>xP({...e,from:this.id}),this.useNavigate=()=>TP({from:this.fullPath}),this.Link=q.forwardRef((e,t)=>(0,Y.jsx)(VP,{ref:t,from:this.fullPath,...e}))}};function WP(e){return new UP(e)}var GP=class extends IN{constructor(e){super(e),this.useMatch=e=>bP({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>EP({...e,from:this.id}),this.useSearch=e=>wP({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>CP({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>SP({...e,from:this.id}),this.useLoaderData=e=>xP({...e,from:this.id}),this.useNavigate=()=>TP({from:this.fullPath}),this.Link=q.forwardRef((e,t)=>(0,Y.jsx)(VP,{ref:t,from:this.fullPath,...e}))}};function KP(e){return new GP(e)}function qP(e){let t=WN(),n=`not-found-${_P(t.stores.location,e=>e.pathname)}-${_P(t.stores.status,e=>e)}`;return(0,Y.jsx)(LN,{getResetKey:()=>n,onCatch:(t,n)=>{if(Uj(t))e.onCatch?.(t,n);else throw t},errorComponent:({error:t})=>{if(Uj(t))return e.fallback?.(t);throw t},children:e.children})}function JP(){return(0,Y.jsx)(`p`,{children:`Not Found`})}function YP(e){return(0,Y.jsx)(Y.Fragment,{children:e.children})}function XP(e,t,n){return t.options.notFoundComponent?(0,Y.jsx)(t.options.notFoundComponent,{...n}):e.options.defaultNotFoundComponent?(0,Y.jsx)(e.options.defaultNotFoundComponent,{...n}):(0,Y.jsx)(JP,{})}function ZP(e,t){let n=t?.options.pendingComponent??e.options.defaultPendingComponent;return n?(0,Y.jsx)(n,{}):null}var QP=(e,t)=>e[0]===t[0]&&e[1]===t[1],$P=(e,t,n)=>!t.isRoot||t.options.shellComponent||t.options.wrapInSuspense||n===!1||n===`data-only`||!e.ssr,eF=q.memo(function({routeId:e}){let t=WN();return(0,Y.jsx)(tF,{router:t,match:_P(t.stores.getMatchStore(e),e=>e)})});function tF({router:e,match:t}){let n=e.routesById[t.routeId],r=ZP(e,n),i=n.options.errorComponent??e.options.defaultErrorComponent,a=n.options.onCatch??e.options.defaultOnCatch,o=n.isRoot?n.options.notFoundComponent??e.options.notFoundRoute?.options.component:n.options.notFoundComponent,s=t.ssr===!1||t.ssr===`data-only`,c=$P(e,n,t.ssr)&&(n.options.wrapInSuspense??r??(n.options.errorComponent?.preload||s))?q.Suspense:YP,l=i?LN:YP,u=o?qP:YP;return(0,Y.jsxs)(n.isRoot?n.options.shellComponent??YP:YP,{children:[(0,Y.jsx)(GN.Provider,{value:t.routeId,children:(0,Y.jsx)(c,{fallback:r,children:(0,Y.jsx)(l,{getResetKey:()=>t,errorComponent:i,onCatch:(e,n)=>{if(Uj(e))throw e.routeId??=t.routeId,e;a?.(e,n)},children:(0,Y.jsx)(u,{fallback:e=>{if(e.routeId??=t.routeId,e.routeId!==t.routeId)throw e;return q.createElement(o,e)},children:s?(0,Y.jsx)(BN,{fallback:r,children:(0,Y.jsx)(nF,{match:t})}):(0,Y.jsx)(nF,{match:t})})})})}),null]})}var nF=q.memo(function({match:e}){let t=WN(),n=e.routeId,r=t.routesById[n],i=q.useMemo(()=>{let i=(r.options.remountDeps??t.options.defaultRemountDeps)?.({routeId:n,loaderDeps:e.loaderDeps,params:e._strictParams,search:e._strictSearch});return i?JSON.stringify(i):void 0},[n,e.loaderDeps,e._strictParams,e._strictSearch,r.options.remountDeps,t.options.defaultRemountDeps]),a=q.useMemo(()=>{let e=r.options.component??t.options.defaultComponent;return e?(0,Y.jsx)(e,{},i):(0,Y.jsx)(rF,{})},[i,r.options.component,t.options.defaultComponent]);if(e.status===`pending`){if(t.ssr&&!$P(t,r,e.ssr))return a;if(t._tx)throw t._tx[5];return ZP(t,r)}if(e.status===`notFound`)return XP(t,r,e.error);if(e.status===`error`)throw e.error;return a}),rF=q.memo(function(){let e=WN(),t=q.useContext(GN),n,r,i;{let a=e.stores.getMatchStore(t);[n,r]=_P(a,e=>[!!e._notFound,e.error],QP),i=_P(e.stores.ids,e=>e[e.indexOf(t)+1])}if(n)return XP(e,e.routesById[t],r);if(!i)return null;let a=(0,Y.jsx)(eF,{routeId:i});return t===`__root__`?(0,Y.jsx)(q.Suspense,{fallback:ZP(e),children:a}):a});function iF(e,t){let n=e[1];e.length=0,n?.(t)}function aF({t:e}){let t=WN(),n=t._rendered??=[];return t.startTransition=(r,i)=>new Promise((a,o)=>{iF(n,!1),n.push(i,a),e(t),q.startTransition(()=>{try{r()}catch(e){n[1]===a&&(n.length=0),o(e)}})}),FA(()=>{let e=t.history.subscribe(t.load);t.updateLatestLocation();let r=t.latestLocation,i=t.buildLocation({to:r.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});if(Pj(r.publicHref)!==Pj(i.publicHref))return t.commitLocation({...i,replace:!0,ignoreBlocker:!0}),e;let a=t.stores.resolvedLocation.get();return a?.href===r.href&&a.state.__TSR_key===r.state.__TSR_key?n.push(t.stores.matches.get(),e=>{e&&t.emit({type:`onRendered`,...jM(a,a)})}):t._tx||t.load().catch(console.error),e},[t,t.history]),null}function oF(){let e=WN(),t=e.routesById[fM],n=ZP(e,t),r=e.ssr?YP:q.Suspense,i=(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(aF,{t:q.useState()[1]}),(0,Y.jsx)(r,{fallback:n,children:(0,Y.jsx)(sF,{})})]});return e.options.InnerWrap?(0,Y.jsx)(e.options.InnerWrap,{children:i}):i}function sF(){let e=WN(),t=e._rendered,n=_P(e.stores.matches,e=>t[0]??e),r=n[0],i=r?.routeId;FA(()=>{t[0]===n&&iF(t,!0)},[t,n]);let a=i?(0,Y.jsx)(eF,{routeId:i}):null;return(0,Y.jsx)(GN.Provider,{value:i,children:e.options.disableGlobalCatchBoundary?a:(0,Y.jsx)(LN,{getResetKey:()=>r,onCatch:void 0,children:a})})}var cF=e=>({createMutableStore:uP,createReadonlyStore:uP,batch:sP}),lF=e=>new uF(e),uF=class extends PM{constructor(e){super(e,cF)}};function dF({router:e,children:t,...n}){UA(n)&&e.update({...e.options,...n,context:{...e.options.context,...n.context}});let r=(0,Y.jsx)(UN.Provider,{value:e,children:t});return e.options.Wrap?(0,Y.jsx)(e.options.Wrap,{children:r}):r}function fF({router:e,...t}){return(0,Y.jsx)(dF,{router:e,...t,children:(0,Y.jsx)(oF,{})})}function pF(e){let t=WN({warn:e?.router===void 0}),n=e?.router||t;return _P(n.stores.__store,yP(e,n))}function mF(){return _P(WN().stores.location,e=>e.state.__TSR_index!==0)}var hF=(0,q.createContext)(null),gF=hF.Provider,_F=KP({validateSearch:Dr({agent:P().min(1).optional()}),component:()=>null}),vF=WP({getParentRoute:()=>_F,path:`/`}),yF=WP({getParentRoute:()=>_F,path:`/sessions/$agentId/$sessionId`,params:{parse:e=>Dr({agentId:P().min(1),sessionId:P().min(1)}).parse(e)}});function bF(){return lF({routeTree:_F.addChildren([vF,yF]),history:EM(),InnerWrap:({children:e})=>(0,Y.jsxs)(Y.Fragment,{children:[(0,q.useContext)(hF),e]}),defaultPendingMs:0,defaultPendingMinMs:0})}function xF(e,t){let n=pF({router:e,select:e=>e.location.search}),r=bP({from:yF.id,shouldThrow:!1});gh(t,{canGoBack:mF(),onBack:()=>e.history.canGoBack()?(e.history.back(),!0):!1});let i=(0,q.useCallback)(t=>{e.navigate({to:`.`,search:{agent:t??void 0},replace:!0})},[e]),a=(0,q.useCallback)((t,n)=>{e.navigate({to:`/sessions/$agentId/$sessionId`,params:{agentId:t,sessionId:n},search:!0})},[e]);return{agentFilterId:n.agent??null,setFilter:i,selection:r?.params,open:a}}var SF=ea.check(H(1,{message:`Give your Agent a name.`}),K(256,{message:`Use at most 256 characters.`}));function CF({agentId:e,name:t,rename:n}){let[r,i]=(0,q.useState)(!1),a=eA({schema:(0,q.useMemo)(()=>I({name:SF.annotate(Ek({label:`Agent name`,render:e=>(0,Y.jsx)(cn,{id:e.id,name:e.name,"aria-label":`Agent name`,"aria-invalid":e[`aria-invalid`],"aria-describedby":e[`aria-describedby`],autoFocus:!0,maxLength:256,disabled:e.disabled,value:e.value,onBlur:e.onBlur,onChange:t=>{e.onChange(t.currentTarget.value)}})}))}),[]),defaultValues:{name:t},onSubmit:async({name:r})=>r===t||await n(e,r)?(i(!1),{kind:`saved`,values:{name:r}}):{kind:`refused`}}),{submitting:o,canSubmit:s}=tA(a);return r?(0,Y.jsxs)(iA,{model:a,"aria-label":`Rename Agent`,footer:null,className:`flex min-w-0 items-center gap-1`,children:[(0,Y.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,Y.jsx)(xk,{model:a,names:[`name`]})}),(0,Y.jsx)(Zt,{type:`submit`,size:`sm`,loading:o,disabled:o||!s,children:`Save`}),(0,Y.jsx)(Tt,{"aria-label":`Cancel rename`,type:`button`,icon:(0,Y.jsx)(Ln,{size:14,"aria-hidden":`true`}),onClick:()=>{i(!1)}})]}):(0,Y.jsx)(Tt,{"aria-label":`Rename Agent`,icon:(0,Y.jsx)(uT,{size:14,"aria-hidden":`true`}),onClick:()=>{i(!0)}})}function wF({status:e,approving:t,onApprove:n}){return e?.status===`pending`?(0,Y.jsx)(Zt,{variant:`outline`,size:`sm`,className:`flex-none`,loading:t,disabled:t,onClick:n,children:`Allow App tools`}):null}Fi()([],()=>(e,t,n)=>vi({try:()=>M_(e,n.onExcessProperty===`error`),catch:()=>new eo(t,e,n)}));var TF={artifactRef:Dv,digest:Av,version:V.pipe(z(H(1))),byteLength:ya.pipe(z(Ka()),z(Ha(0)),z(L(Number.isSafeInteger)))},EF=I({...TF,mediaType:G([`text/html; charset=utf-8`,`application/vnd.fungi.app-assets+json`])}),DF=I({...TF,mediaType:U(`application/vnd.fungi.app-backend+json`)}),OF={declaration:B(pv)},kF=F([I({format:U(`fungi-app-v1`),ui:EF,backend:DF,...OF}),I({format:U(`fungi-app-v1`),ui:EF,...OF}),I({format:U(`fungi-app-v1`),backend:DF,...OF})]).pipe(z(L(e=>e.declaration?.api===void 0||`backend`in e,{message:`An App API requires a backend`})));Bi(kF);var AF=G([`invalid`,`undeclared_key`,`scope_not_declared`,`owner_required`,`too_large`,`quota_exceeded`,`conflict`,`unavailable`]),jF=class extends Error{code;constructor(e,t){super(e,t),this.code=e}},MF=Ia.check(Ha(0)),NF=I({value:$a,revision:MF}),PF=I({value:$a,source:G([`member`,`team`,`none`]),team:oo(NF),member:oo(NF),canWriteTeam:Ua}),FF={key:sv,scope:G(v_),basedOn:oo(MF)},IF=I({...FF,value:$a}),LF=I(FF),RF=I({revision:MF}),zF=I({appId:V,key:sv,scope:G(v_),revision:MF}),BF=F([I({kind:U(`accepted`),value:PF}),I({kind:U(`rejected`),code:AF})]),VF=F([I({kind:U(`accepted`),value:RF}),I({kind:U(`rejected`),code:AF})]),HF=I({error:V});F([BF,HF]),F([VF,HF]);var UF=e=>xh(gr().transform(t=>zi(e,{onExcessProperty:`error`})(t))),WF=bh({read:Sh(UF(BF)),write:Sh(UF(VF)),reset:Sh(UF(VF)),openEvents:Sh(wh)}),GF=e=>{if(e.kind===`rejected`)throw new jF(e.code);return e.value},KF=(e,t)=>{let n=ia(e,{onExcessProperty:`error`})(t);if(n._tag===`Failure`)throw new jF(`invalid`,{cause:n.failure});return n.success},qF=e=>KF(sv,e);function JF(e){let t=async t=>GF(await e.read(qF(t)));return{read:t,write:async t=>GF(await e.write(KF(IF,t))),reset:async t=>GF(await e.reset(KF(LF,t))),async watch(n){let r=qF(n),i=await e.openEvents(r),a=!1,o=()=>a,s,c=!1,l=()=>c&&!o(),u,d=()=>void 0,f=()=>void 0,p=new Promise((e,t)=>{d=e,f=t}),m=new e_(`https://app-storage.fungi.invalid/events`,{fetch:async(e,t)=>{let n=await i.fetch(new Request(e,t));if(!n.ok){let e=ia(BF)(await n.json()),t=new jF(e._tag===`Success`&&e.success.kind===`rejected`?e.success.code:`unavailable`);throw g(t),t}return n}}),h=()=>{a||(a=!0,m.close(),f(new jF(`unavailable`)),i.close().catch(e=>{Xo(`storage.watch.close`,e)}).finally(()=>{i[Symbol.dispose]()}))},g=e=>{f(e instanceof jF?e:new jF(`unavailable`,{cause:e})),!a&&u!==void 0&&Xo(`storage.watch`,e),h()},_=()=>{c=!0,!(s!==void 0||a)&&(s=(async()=>{for(;l();){c=!1;let e=await t(r);if(o())return;if(u===void 0){let t=cm(e);u=t,d({get:()=>t.get(),subscribe:e=>t.subscribe(e),close:h,[Symbol.dispose]:h})}else u.update(e)}})().catch(g).finally(()=>{s=void 0,c&&!a&&_()}))};return m.addEventListener(`ready`,_),m.addEventListener(`changed`,e=>{let t=ia(Bi(zF),{onExcessProperty:`error`})(e.data);t._tag===`Failure`?g(t.failure):t.success.key===r?_():g(new jF(`invalid`))}),m.onerror=e=>{(u===void 0||m.readyState===e_.CLOSED)&&g(e)},p}}}var YF=yh(`app.storage`,1,Ir(()=>WF.transform(JF))),XF=I({text:V}),ZF=Me(structuredClone(co(XF,{onExcessProperty:`error`}).schema));function QF(e){return[{id:`new-conversation`,title:`New conversation`,category:`Conversation`,description:`Start a new conversation with this Agent`,projections:{slash:{aliases:[`new`],order:20},palette:{}},handler:()=>{e().newConversation()}},{id:`permissions`,title:`App permissions`,category:`Conversation`,description:`Review what Grove may access`,projections:{slash:{aliases:[`permissions`],order:21},palette:{}},handler:()=>{e().openPermissions()}},{id:`set-draft`,title:`Set draft`,category:`Conversation`,description:`Replace the open writable Grove conversation's draft without sending it`,projections:{agent:{}},action:{inputSchema:ZF,presentation:{type:`action`}},handler:({arguments:t})=>{let{text:n}=zi(XF,{onExcessProperty:`error`})(t);return{accepted:e().setDraft(n)}}}]}function $F(e,t){let n=(0,q.useRef)(e);n.current=e;let r=(0,q.useMemo)(()=>QF(()=>n.current),[]),i=(0,q.useMemo)(()=>Et(),[]);return(0,q.useEffect)(()=>{let e=i.contribute({sourceId:`grove`,namespace:`grove`,commands:r});return()=>{e.dispose()}},[r,i]),(0,q.useEffect)(()=>t?Co(t,r):void 0,[r,t]),i}var eI=oi(Ar({providerId:P().min(1).max(256),providerName:P().min(1).max(256),id:P().min(1).max(256),name:P().min(1).max(256),reasoning:oi(Tr(Ni)).max(6).readonly()})).max(1024).readonly();async function tI(e,t,n,r=Ig){if(!e.has(Ag))throw Error(`Agent read authority is unavailable`);let i=await r(e,{agentId:t});try{let e=await i.fetch(new Request(`${i.baseUrl}/models`,{signal:n}));if(!e.ok)throw Error(`Agent model catalog is unavailable`);return eI.parse(await e.json())}finally{await i.close()}}function nI(e){let t=ln(),n=e?.capabilities.has(Ag)===!0||e?.capabilities.has(jg)===!0,r=By(n?e:null),i=e&&!n?{...r,status:`live`}:r,a=Iy.of(e,`agents`),o=qo({...zy(e,yg,a,e=>e.list()),enabled:e?.capabilities.has(yg)===!0}),s=new Set(o.data?.map(e=>e.agentId)),c=o.isSuccess?JSON.stringify([...new Set(i.items.filter(e=>!(`kind`in e)).map(e=>e.agentId))].filter(e=>!s.has(e)).sort()):`[]`,{refetch:l}=o;(0,q.useEffect)(()=>{c!==`[]`&&i.items.length>0&&l()},[c,i.items,l]);let u=Iy.of(e,`agent-computers`);return{directory:o,inbox:i,computerChoices:qo({...zy(e,bg,u,()=>{if(!e)throw Error(`No App connection`);return Ng(e.capabilities)}),enabled:e?.capabilities.has(bg)===!0}),createAgent:Jo({mutationFn:t=>{if(!e)throw Error(`No App connection`);return Mg(e.capabilities,t)},onMutate:()=>({directoryKey:a}),onSettled:(e,n,r)=>{r.computer===`new`&&t.invalidateQueries({queryKey:u})},onSuccess:(e,n,r)=>{t.setQueryData(r.directoryKey,(t=[])=>t.some(t=>t.agentId===e.agentId)?t:[...t,e])}}),renameAgent:Jo({mutationFn:t=>{if(!e)throw Error(`No App connection`);return Cg(e.capabilities,t)},onSuccess:e=>{t.setQueryData(a,(t=[])=>t.map(t=>t.agentId===e.agentId?e:t))}}),setAgentAvatar:Jo({mutationFn:t=>{if(!e)throw Error(`No App connection`);return Eg(e.capabilities,t)},onSuccess:e=>{t.setQueryData(a,(t=[])=>t.map(t=>t.agentId===e.agentId?e:t))}})}}function rI(e,t){let n=ln(),r=e?.capabilities.has(kg)===!0,i=Iy.of(e,`agent-tool-policy`,t??`none`);return{canRead:r,status:qo({...zy(e,kg,i,e=>t===null?Promise.resolve(null):e.status({agentId:t})),enabled:r&&t!==null}),approve:Jo({mutationFn:t=>{if(!e)throw Error(`No App connection`);return e.capabilities.require(kg).approve({agentId:t.agentId,level:`write`,expectedRevision:t.expectedRevision})},onSuccess:e=>{`error`in e||n.setQueryData(i,e)}})}}function iI({agentId:e,name:t,avatar:n,setAvatar:r}){let[i,o]=(0,q.useState)(null),[s,c]=(0,q.useState)(!1),l=(0,Y.jsx)(kT,{avatar:n,name:t,size:24});return r===void 0?(0,Y.jsx)(`span`,{className:`flex-none`,children:l}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(Zt,{variant:`ghost`,size:`sm`,"aria-label":`Change avatar`,className:`flex-none p-0`,onClick:()=>{o(n)},children:l}),(0,Y.jsx)(b,{open:i!==null,onOpenChange:e=>{!e&&!s&&o(null)},children:(0,Y.jsxs)(zt,{className:`flex flex-col gap-lg`,keepMounted:!1,children:[(0,Y.jsxs)(pe,{children:[(0,Y.jsxs)(w,{children:[t,`'s avatar`]}),(0,Y.jsxs)(a,{children:[`Every conversation with `,t,` shows this look.`]})]}),i===null?null:(0,Y.jsx)(wA,{value:i,disabled:s,onChange:o}),(0,Y.jsxs)(It,{children:[(0,Y.jsx)(Zt,{type:`button`,variant:`ghost`,disabled:s,onClick:()=>{o(null)},children:`Cancel`}),(0,Y.jsx)(Zt,{type:`button`,variant:`primary`,loading:s,disabled:s||i===null,onClick:()=>{i!==null&&(c(!0),r(e,i).then(e=>{c(!1),e&&o(null)}))},children:`Save`})]})]})})]})}var aI=(0,q.forwardRef)(function({className:e,orientation:t,variant:n=`grip`,value:r,min:i,max:a,onValueChange:o,onKeyDown:s,...c},l){return(0,Y.jsx)(`div`,{...c,ref:l,className:E(`caps-resize-handle`,e),"data-resize-variant":n,role:`separator`,"aria-orientation":t,"aria-valuemin":Math.round(i),"aria-valuemax":Math.round(a),"aria-valuenow":Math.round(r),tabIndex:c.tabIndex??0,onKeyDown:e=>{if(s?.(e),e.defaultPrevented)return;if(e.key===`Home`||e.key===`End`){e.preventDefault(),o(e.key===`Home`?i:a);return}let n=t===`horizontal`?e.key===`ArrowUp`?-32:e.key===`ArrowDown`?32:null:e.key===`ArrowLeft`?-32:e.key===`ArrowRight`?32:null;n!==null&&(e.preventDefault(),o(Math.min(a,Math.max(i,r+n))))},children:(0,Y.jsx)(`span`,{className:`caps-resize-grip`,"aria-hidden":`true`})})});Gt({frames:new Map,order:[],tiles:[],minima:new Map,participating:new Set,mainSize:void 0,zoomed:null,gesture:null,restore:new Map});function oI(e,t=!0,n){let r=(0,q.useRef)(e);r.current=e;let i=(0,q.useRef)(null);return(0,q.useEffect)(()=>(t||i.current?.release(!0),()=>i.current?.release(!0)),[t]),(0,q.useEffect)(()=>{let e=()=>{i.current?.release(!0)};return n?.addEventListener(`abort`,e),()=>{n?.removeEventListener(`abort`,e)}},[n]),{onPointerDown:e=>{if(!t||n?.aborted||i.current||e.pointerType===`mouse`&&e.button!==0)return;let{currentTarget:a,pointerId:o}=e;if(a.setPointerCapture(o),!r.current.begin(e)){a.releasePointerCapture(o);return}let s=r.current.end,c=()=>{l(!0)},l=e=>{a.removeEventListener(`lostpointercapture`,c),i.current=null,s(e),a.hasPointerCapture(o)&&a.releasePointerCapture(o)};i.current={id:o,element:a,x:e.clientX,y:e.clientY,release:l},a.addEventListener(`lostpointercapture`,c)},onPointerMove:e=>{let t=i.current;t?.id===e.pointerId&&(r.current.move(e.clientX-t.x,e.clientY-t.y,e),t.x=e.clientX,t.y=e.clientY)},onPointerUp:e=>{i.current?.id===e.pointerId&&i.current.release(!1)},onPointerCancel:e=>{i.current?.id===e.pointerId&&i.current.release(!0)}}}(0,q.createContext)(null);var sI=(0,q.createContext)(null);(0,q.forwardRef)(function({layer:e,style:t,children:n,...r},i){let a=(0,q.useContext)(sI),o=a?.update,s=a?.roots.get(`dialog`),[c,l]=(0,q.useState)(!1);(0,q.useEffect)(()=>{if(!s)return;let e=()=>{l(Array.from(s.querySelectorAll(`*`)).some(e=>{let t=e.getBoundingClientRect();return t.width>0&&t.height>0}))};e();let t=new MutationObserver(e);return t.observe(s,{childList:!0,subtree:!0,attributes:!0}),()=>{t.disconnect()}},[s]);let u=(0,q.useRef)(null);(0,q.useImperativeHandle)(i,()=>u.current);let d=(0,q.useCallback)(t=>{u.current=t,o?.(e,t)},[o,e]);return(0,q.createElement)(`div`,{...r,ref:d,onFocusCapture:t=>{e===`windows`&&t.target instanceof Node&&t.currentTarget.contains(t.target)&&a?.dismiss?.(),r.onFocusCapture?.(t)},"data-maosaico-layer":e,inert:e===`windows`&&c?``:void 0,style:{position:`relative`,...t,isolation:`isolate`,zIndex:`var(--stipe-layer-${e})`}},n)});var cI={min:224,max:480,initial:320},lI={agentRailOpen:!0,listRailOpen:!0,listWidth:cI.initial},uI=`layout`,dI=Ti(I({agentRailOpen:Ua,listRailOpen:Ua,listWidth:ya.pipe(z(_a()))}));function fI(e){return Math.round(Math.min(cI.max,Math.max(cI.min,e)))}async function pI(e){let t=await e.read(uI),n=dI(t.member?.value);return{layout:ui(n)?{...n.value,listWidth:fI(n.value.listWidth)}:lI,revision:t.member?.revision??null}}async function mI(e,t,n){let{revision:r}=await e.write({key:uI,scope:`member`,basedOn:n,value:t});return r}function hI(e){let[t,n]=(0,q.useState)(lI),r=(0,q.useRef)(null),i=(0,q.useRef)(!1),a=(0,q.useRef)(!1);return(0,q.useEffect)(()=>{if(e===void 0)return;let t=!1;return pI(e).then(e=>{t||(r.current=e.revision,i.current=!0,a.current||n(e.layout))},e=>{console.warn(`Grove could not read its saved rail layout`,e),i.current=!0}),()=>{t=!0}},[e]),(0,q.useEffect)(()=>{e===void 0||!a.current||!i.current||mI(e,t,r.current).then(e=>{r.current=e},e=>{console.warn(`Grove could not save its rail layout`,e)})},[e,t]),[t,(0,q.useCallback)(e=>{a.current=!0,n(e)},[])]}var gI=8e3,_I=(0,q.forwardRef)(function({className:e,detail:t,framed:n=!0,icon:r,message:i,onRetry:a,size:o=`md`,slowAfterMs:s=gI,variant:c=`line`,...l},u){let[d,f]=(0,q.useState)(!1);return(0,q.useEffect)(()=>{if(f(!1),!Number.isFinite(s))return;let e=globalThis.setTimeout(()=>{f(!0)},s);return()=>{globalThis.clearTimeout(e)}},[s,i]),(0,Y.jsxs)(`div`,{...l,className:E(`caps-loading-state`,e),"data-framed":n?void 0:`false`,"data-icon":r?``:void 0,"data-size":o,"data-slow":d||void 0,ref:u,role:`status`,children:[r?(0,Y.jsx)(`span`,{"aria-hidden":`true`,className:`caps-loading-state-icon`,children:r}):null,(0,Y.jsx)(Mt,{decorative:!0,size:o,variant:c}),(0,Y.jsxs)(`span`,{className:`caps-loading-state-copy`,children:[(0,Y.jsx)(`span`,{children:i}),t?(0,Y.jsx)(`span`,{className:`caps-loading-state-detail`,children:t}):null,d?(0,Y.jsx)(`span`,{className:`caps-loading-state-detail`,children:`Still working…`}):null]}),d&&a?(0,Y.jsx)(Zt,{className:`caps-loading-state-retry`,size:`sm`,variant:`outline`,onClick:a,children:`Retry`}):null]})}),vI=[`Make me a tiny game where a mushroom catches raindrops.`,`Write a short poem about a rainy morning.`,`What can you help me with?`];function yI({description:e,icon:t,label:n,density:r=`regular`,appearance:i=`plain`,iconSize:a=`default`,size:o,trailing:s,...c}){return(0,Y.jsxs)(Zt,{...c,className:E(`caps-action-row`,i===`card`&&`caps-action-row-card`,r===`compact`?`h-auto min-h-10 w-full justify-start gap-xs px-xs py-2xs text-left`:`h-auto min-h-14 w-full justify-start gap-sm px-sm py-xs text-left`,c.className),size:o??(r===`compact`?`default`:`lg`),variant:c.variant??`ghost`,children:[t?(0,Y.jsx)(`span`,{className:r===`compact`?`grid ${a===`lg`?`size-8`:`size-7`} shrink-0 place-items-center [&_:is(svg,.caps-monogram)]:size-5`:`grid ${a===`lg`?`size-12`:`size-10`} shrink-0 place-items-center [&_:is(svg,.caps-monogram)]:size-7`,children:t}):null,(0,Y.jsxs)(`span`,{className:`caps-action-row-copy`,children:[(0,Y.jsx)(`span`,{className:`caps-action-row-label max-w-full truncate`,children:n}),e?(0,Y.jsx)(`span`,{className:`caps-action-row-description max-w-full truncate`,children:e}):null]}),s?(0,Y.jsx)(`span`,{className:`caps-action-row-trailing`,children:s}):null]})}function bI(e,t,n,r,i,a){let o=[];r&&o.push({kind:`hint`,key:`loading`,loading:!0});let s=0,c=WT(e),l=new Map(c.map(e=>[GT(e.agentId,e.sessionId),e]));for(let e of[`Needs you`,`Working`,`Ready`,`Finished`]){let n=t.flatMap(t=>{let n=l.get(t.key),r=n?.state===`errored`?`Needs you`:t.shelf;return n===void 0||r!==e?[]:[n]});if(n.length!==0){o.push({kind:`heading`,key:e,title:e,gap:s++>0});for(let t of n)o.push({kind:`session`,key:GT(t.agentId,t.sessionId),shelf:e,session:t})}}if(e.unavailable.length>0){o.push({kind:`heading`,key:`Unavailable`,title:`Unavailable`,gap:s>0});for(let t of e.unavailable)o.push({kind:`unavailable`,key:GT(t.agentId,t.sessionId),session:t})}if(n.length>0){o.push({kind:`heading`,key:`Websites`,title:`Websites`,gap:o.length>0});for(let e of n)o.push({kind:`website`,key:`website:${e.bindingId}:${e.conversation.sessionId}`,website:e})}return o.length===0&&!i&&a&&o.push({kind:`hint`,key:`empty`,loading:!1}),o}function xI({viewport:e,view:t,agents:n,loading:r,failed:i,showEmptyState:a,pendingSelection:o,selectedAgentId:s,selectedSessionId:c,onSelect:l,onDelete:u,deleting:d,websites:f,selectedWebsite:p,onSelectWebsite:m}){let h=s!==null&&c!==null?GT(s,c):null,[g,_]=(0,q.useState)(!1),[v,y]=(0,q.useState)(!1),b=g||v,[x,S]=(0,q.useState)(0),[C,w]=(0,q.useState)({placements:null,openKey:h,reopened:x}),T=(0,q.useMemo)(()=>BT(C.placements,[...t.active,...t.settled],{openKey:C.openKey===h?h:null,held:b,reorder:C.openKey!==h||C.reopened!==x}),[C,t,h,b,x]);(0,q.useEffect)(()=>{!b&&(C.placements!==T||C.openKey!==h||C.reopened!==x)&&w({placements:T,openKey:h,reopened:x})},[b,C,T,h,x]),(0,q.useEffect)(()=>{let t=e.current;if(t===null)return;let n=t.clientWidth>0&&t.clientHeight>0,r=`ResizeObserver`in globalThis?new ResizeObserver(([e])=>{let t=e.contentRect.width>0&&e.contentRect.height>0;t&&!n&&S(e=>e+1),n=t}):void 0;r?.observe(t);let i=()=>{document.visibilityState===`visible`&&S(e=>e+1)};return document.addEventListener(`visibilitychange`,i),()=>{r?.disconnect(),document.removeEventListener(`visibilitychange`,i)}},[e]);let E=(0,q.useMemo)(()=>bI(t,T,f,r,i,a),[t,T,f,r,i,a]),ee=(0,q.useCallback)(e=>E[e]?.key??e,[E]),D=Bn({count:E.length,getScrollElement:()=>e.current,getItemKey:ee,estimateSize:e=>E[e]?.kind===`heading`?24:44,measureElement:(e,t,n)=>{let r=at(e,t,n);return r>0?r:at(e,void 0,n)||n.options.estimateSize(n.indexFromElement(e))},initialRect:{width:320,height:800},overscan:5,useFlushSync:!1});return(0,Y.jsx)(`div`,{className:`inbox-list px-1 py-1`,onPointerEnter:()=>{_(!0)},onPointerLeave:()=>{_(!1)},onFocusCapture:()=>{y(!0)},onBlurCapture:e=>{e.currentTarget.contains(e.relatedTarget)||y(!1)},children:(0,Y.jsx)(`div`,{style:{height:D.getTotalSize(),position:`relative`,width:`100%`},children:D.getVirtualItems().map(e=>{let t=E[e.index],r=t.kind===`session`||t.kind===`unavailable`?t.session:null,i=r?n.get(r.agentId):void 0;return(0,Y.jsx)(`div`,{"data-index":e.index,ref:D.measureElement,"data-inbox-shelf":t.kind===`session`?t.shelf:t.kind===`unavailable`?`Unavailable`:void 0,className:t.kind===`heading`?`inbox-shelf`:void 0,style:{position:`absolute`,top:0,left:0,width:`100%`,transform:`translateY(${String(e.start)}px)`,paddingTop:t.kind===`heading`&&t.gap?4:0},children:t.kind===`heading`?(0,Y.jsx)(me,{style:{paddingBottom:0},children:t.title}):t.kind===`hint`?t.loading?(0,Y.jsx)(_I,{className:`inbox-empty px-2 py-3 text-sm text-(--stipe-fg-muted)`,message:`Loading conversations…`}):(0,Y.jsx)(`p`,{className:`m-0 px-2 py-3 text-xs text-(--stipe-fg-muted)`,children:`No conversations yet.`}):t.kind===`website`?(0,Y.jsx)(yI,{appearance:`plain`,density:`compact`,className:`inbox-row${p?.bindingId===t.website.bindingId&&p.conversation.sessionId===t.website.conversation.sessionId?` is-selected bg-base-300`:``}`,"data-testid":`inbox-website-row`,label:t.website.conversation.label||`Website visitor`,description:(0,Y.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,Y.jsx)(Cn,{name:`internet`,size:14}),t.website.siteLabel]}),trailing:t.website.conversation.held?(0,Y.jsx)(`span`,{className:`text-xs`,children:t.website.conversation.heldByYou?`You're replying`:`With a teammate`}):t.website.conversation.needsYou?(0,Y.jsx)(fe,{size:`compact`,tone:`accent`,title:t.website.conversation.needsYou.reason}):null,onClick:()=>{m(t.website)},variant:`ghost`}):t.kind===`unavailable`?i?(0,Y.jsx)(CI,{agent:i,row:t.session}):null:i?(0,Y.jsx)(SI,{agent:i,session:t.session,attention:t.session.unseen,pending:o?.agentId===t.session.agentId&&o.sessionId===t.session.sessionId,selected:s===t.session.agentId&&c===t.session.sessionId,onDelete:u&&i.sessionOperations.includes(`agent.manage`)?()=>{u(t.session.agentId,t.session.sessionId)}:void 0,deleting:d?.agentId===t.session.agentId&&d.sessionId===t.session.sessionId,onSelect:()=>{l(t.session.agentId,t.session.sessionId)}}):null},e.key)})})})}function SI({agent:e,session:t,attention:n,pending:r,selected:i,onSelect:a,onDelete:o,deleting:s}){let c=NT(t.state),l=t.state===`errored`,u=(0,Y.jsxs)(`span`,{className:`inbox-row-activity inline-grid shrink-0 grid-cols-[1rem_7ch] items-center gap-1.5 text-[0.6875rem]`,children:[(0,Y.jsxs)(`span`,{className:`inbox-row-status flex items-center justify-center`,children:[r||c||l?(0,Y.jsx)(`span`,{className:`sr-only`,children:r?`Opening`:jT[t.state]}):null,r||c?(0,Y.jsx)(fe,{size:`compact`,title:r?`Opening`:jT[t.state],motion:t.state===`running`||r?`pulse`:`none`,tone:r?`neutral`:t.state===`needs_you`?`accent`:`info`}):l?(0,Y.jsx)(fe,{size:`compact`,title:jT.errored,tone:`error`}):n?(0,Y.jsx)(fe,{size:`compact`,title:`Finished since your last visit`,tone:`neutral`}):null]}),(0,Y.jsx)(`time`,{className:`inbox-row-age min-w-0 truncate text-right tabular-nums text-(--stipe-fg-muted)`,dateTime:new Date(t.lastActivityAt).toISOString(),children:wI(t.lastActivityAt)})]});return(0,Y.jsxs)(`div`,{className:`relative group`,children:[(0,Y.jsx)(yI,{"aria-current":i?`page`:void 0,"aria-label":`${t.title||`New conversation`} — ${KT(e)}${n?` — Finished since your last visit`:``}${t.ready?` — Ready`:c||l?` — ${jT[t.state]}`:``}`,"aria-busy":r||void 0,appearance:`plain`,className:`inbox-row pr-9${i?` is-selected bg-base-300`:``}`,"data-attention":n?`true`:`false`,"data-pending":r?`true`:`false`,"data-session-id":t.sessionId,"data-status":t.state,"data-testid":`inbox-session-row`,density:`compact`,description:KT(e),label:t.title||`New conversation`,onClick:a,trailing:u,variant:`ghost`}),o?(0,Y.jsx)(Tt,{"aria-label":`Delete conversation ${t.title||`New conversation`}`,title:`Delete conversation`,icon:(0,Y.jsx)(pT,{}),iconSize:`sm`,size:`sm`,className:`absolute right-1 top-1/2 -translate-y-1/2 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 max-[899px]:opacity-100`,disabled:c||s,onClick:o}):null]})}function CI({agent:e,row:t}){return(0,Y.jsxs)(`div`,{className:`inbox-row is-unavailable flex min-h-11 w-full items-center gap-2 rounded-field border-(length:--border) border-transparent px-2 py-1 pr-9 text-left text-base-content`,"data-session-id":t.sessionId,"data-testid":`inbox-unavailable-row`,role:`group`,children:[(0,Y.jsxs)(`span`,{className:`inbox-row-copy flex min-w-0 flex-1 flex-col`,children:[(0,Y.jsx)(`strong`,{className:`truncate text-sm font-medium`,children:`Conversation unavailable`}),(0,Y.jsxs)(`small`,{className:`truncate text-xs text-(--stipe-fg-muted)`,children:[KT(e),` `,(0,Y.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),` This saved conversation could not be read.`]})]}),(0,Y.jsx)(`span`,{className:`inbox-row-activity inline-grid shrink-0 grid-cols-[1rem_7ch] items-center gap-1.5 text-[0.6875rem]`,children:(0,Y.jsx)(`span`,{className:`inbox-row-status flex items-center justify-center`,children:(0,Y.jsx)(fe,{size:`compact`,tone:`error`,title:`This saved conversation could not be read`})})})]})}function wI(e){let t=Math.max(0,Date.now()-e);return t<6e4?`now`:t<36e5?`${String(Math.floor(t/6e4))}m`:t<864e5?`${String(Math.floor(t/36e5))}h`:new Date(e).toLocaleDateString(void 0,{month:`short`,day:`numeric`})}var TI=P().min(1).max(256),EI=zr().int().nonnegative();Mr(`state`,[Ar({state:ri(`agent`),version:EI}),Ar({state:ri(`requested`),version:EI,reason:P().max(4e3),at:zr().int().nonnegative()}),Ar({state:ri(`person`),version:EI,memberId:TI,memberName:P().min(1).max(128),since:zr().int().nonnegative()})]);var DI=Ar({bindingId:TI,agentId:TI,origins:oi(P().min(1).max(2048)).min(1).max(16),lifecycle:Tr([`active`,`suspended`])}),OI=Ar({sessionId:TI,label:P().max(4096),lastEventAt:zr().int().nonnegative(),needsYou:Ar({at:zr().int().nonnegative(),reason:P().max(4e3)}).nullable(),held:ti(),heldByYou:ti(),heldByName:P().min(1).max(128).nullable(),holdVersion:zr().int().nonnegative()}),kI=Ar({bindingId:TI}).extend({sessionId:TI});kI.extend({requestId:P().min(1).max(128),text:P().trim().min(1).max(4e3)});var AI=Ar({expectedVersion:EI,confirm:ti()});kI.extend(AI.shape),kI.extend({expectedVersion:EI});var jI=Ar({websites:oi(DI).max(1e3)}),MI=Ar({conversations:oi(OI).max(100)});Ar({conversation:OI});var NI=Ar({status:ri(`sent`)}),PI=yh(`channels.read`,1,Ir(()=>bh({list:Sh(xh(jI)),conversations:Sh(xh(MI))}))),FI=yh(`channels.personal.manage`,1,Ir(()=>bh({hold:Sh(xh(OI)),release:Sh(xh(OI)),dismiss:Sh(xh(OI)),reply:Sh(xh(NI))})));function II(e,t){let n=!1,r=async()=>{try{return await t.read()}catch(e){if(!(e instanceof Oi)||e.boundary!==`runtime`||e.cause!==`unavailable`)throw e;if(await new Promise(e=>setTimeout(e,150)),n)throw Error(`Conversation opening cancelled`,{cause:e});return t.read()}},i,a=new Promise((e,t)=>{i=()=>{t(Error(`Conversation opening cancelled`))}});return{ready:Promise.race([r(),a]).then(r=>{if(n)throw Error(`Conversation opening cancelled`);De(e,t,r)}),close:()=>{n=!0,i()}}}function LI(e){return class{#e;constructor(t){this.#e=new e_(t,{fetch:(t,n)=>e(t,n)})}get readyState(){return this.#e.readyState}addEventListener(e,t,n){this.#e.addEventListener(e,t,n)}close(){this.#e.close()}}}function RI(e){let{connection:t,queryClient:n,services:r}=e,i=null,a=null,o=null,s=!1,c=(e,t)=>e?.agentId===t.agentId&&e.sessionId===t.sessionId,l=e=>!s&&i===e,u=(u,d,f=!1)=>{if(s)return;let p={agentId:u,sessionId:d};if(c(i,p)||(i?.close(),i=null,e.onPending(null),e.onError(null),c(a,p)))return;let m=null,h=!1,g={...p,close:()=>{h||(h=!0,m?.())}};i=g,e.onPending(p),(async()=>{try{let s=await r.openAgent(t.capabilities,{agentId:u});if(!l(g)){await s.close();return}let c=r.createClient({baseUrl:s.baseUrl,eventSource:LI(s.fetch),fetch:s.fetch}),f=c.session(d),p=II(n,f);if(m=()=>{p.close(),Promise.allSettled([c.close(),s.close()])},await p.ready,e.reportsSelection!==!1&&await t.ui.reportAgentSessionSelection({agentId:u,sessionId:d}),!l(g))return;let h={agentId:u,sessionId:d,session:f},_=o;i=null,a=h,o=g.close,e.onConversation(h),e.onPending(null),_?.()}catch(t){console.error(`Chat Session opening failed`,t),g.close(),l(g)&&(i=null,e.onPending(null),e.onError(f?`That Session could not be opened. ${a?`The current conversation remains open.`:`Choose another Session from the list.`}`:`Could not open this Session${t instanceof Error?`: ${t.message}`:``}. ${a?`The previous conversation remains open.`:`Try opening it again.`}`))}})()},d=()=>{if(s)return;let n=i!==null||a!==null;i?.close(),i=null,o?.(),o=null,a=null,e.onPending(null),e.onConversation(null),e.onError(null),!(!n||e.reportsSelection===!1)&&t.ui.reportAgentSessionSelection(null).catch(e=>{console.error(`Chat Session selection could not be reported`,e)})};return{select:u,clear:d,close:()=>{d(),s=!0}}}function zI(e,t){async function n(e){if(e.type!==`prompt`||(e.images?.length??0)>0)throw new J(`Website conversations support text replies only`,{code:`COMMAND_NOT_DECLARED`,retryable:!1});if(!t.canReply())throw new J(`Use Take over to reply to this visitor`,{code:`CAPABILITY_DENIED`,retryable:!1});return await t.reply({bindingId:t.bindingId,sessionId:t.sessionId,requestId:e.requestId,text:e.text}),{status:`recorded`}}return{latestPending:()=>Promise.resolve(null),withdraw:t=>e.withdraw(t),address:e.address,read:t=>e.read(t),watch:t=>e.watch(t),extension:()=>({call:()=>Promise.reject(new J(`Website Session controls are unavailable`,{code:`COMMAND_NOT_DECLARED`,retryable:!1}))}),command:n}}function BI(e,t){(0,q.useSyncExternalStore)(t=>e?.capabilities.subscribe(t)??(()=>void 0),()=>e?.capabilities.version??0);let n=ln(),[r,i]=(0,q.useState)(null),[a,o]=(0,q.useState)(null),[s,c]=(0,q.useState)(null),l=e?.capabilities.has(PI)===!0,u=e?.capabilities.has(FI)===!0,d=qo({...zy(e,PI,Iy.of(e,`websites`),e=>e.list()),enabled:l}),f=l?d.data?.websites??[]:[],p=Go({queries:f.map(t=>({...zy(e,PI,Iy.of(e,`website-conversations`,t.bindingId),e=>e.conversations({bindingId:t.bindingId})),enabled:l}))}),m=f.flatMap((e,t)=>(p[t]?.data?.conversations??[]).map(t=>({bindingId:e.bindingId,agentId:e.agentId,siteLabel:e.origins.map(e=>new URL(e).host).join(`, `),conversation:t}))).sort((e,t)=>t.conversation.lastEventAt-e.conversation.lastEventAt),h=m.find(e=>e.bindingId===r?.bindingId&&e.conversation.sessionId===r.sessionId),g=(0,q.useMemo)(()=>e===null?null:RI({connection:e,queryClient:n,services:t,onPending:()=>void 0,onConversation:o,onError:c}),[e,n,t]);(0,q.useEffect)(()=>()=>{g?.close()},[g]),(0,q.useEffect)(()=>{l||g?.clear()},[l,g]);let _=Jo({mutationFn:t=>{if(e===null)throw Error(`No App connection`);let n=e.capabilities.require(FI);return t.kind===`hold`?n.hold({bindingId:t.bindingId,sessionId:t.sessionId,expectedVersion:t.expectedVersion,confirm:t.confirm}):n.release({bindingId:t.bindingId,sessionId:t.sessionId,expectedVersion:t.expectedVersion,confirm:t.confirm})},onSuccess:(t,r)=>{n.setQueryData(Iy.of(e,`website-conversations`,r.bindingId),e=>e===void 0?void 0:{conversations:e.conversations.map(e=>e.sessionId===t.sessionId?t:e)})}}),v=h?.bindingId,y=h?.conversation.sessionId,b=h?.conversation.heldByYou===!0,x=(0,q.useMemo)(()=>a===null||v===void 0||y===void 0||e===null?null:zI(a.session,{bindingId:v,sessionId:y,canReply:()=>b&&e.capabilities.has(FI),reply:t=>e.capabilities.require(FI).reply(t)}),[e,a,v,y,b]),S=(0,q.useCallback)(()=>{g?.clear(),i(null),o(null),_.reset()},[g,_.reset]);return{canRead:l,canManage:u,rows:m,selected:h,session:x,action:_,openingError:s,loading:l&&(d.isPending||p.some(e=>e.isPending)),failed:l&&(d.isError||p.some(e=>e.isError)),clear:S,select:e=>{l&&(h?.bindingId!==e.bindingId||h.conversation.sessionId!==e.conversation.sessionId||a===null)&&(i({bindingId:e.bindingId,sessionId:e.conversation.sessionId}),o(null),_.reset(),g?.select(e.agentId,e.conversation.sessionId))}}}var VI=(0,q.lazy)(async()=>({default:(await _o(()=>import(`./website-conversation-CX0AUueJ.js`),__vite__mapDeps([12,1,13,2,3,4,8,14,15]))).WebsiteConversation})),HI=(0,q.lazy)(async()=>({default:(await _o(()=>import(`./parakeet-conversation-Cdiu-eyV.js`),__vite__mapDeps([16,1,13,2,3,4,8,14,15,17]))).ParakeetConversation})),UI={openAgent:Ig,createClient:Ca,autoOpen:!0},WI=[`agent.list`,`agent.manage`,`agent.read`,`agent.send`],GI=[`agent.read`,`agent.send`,`agent.manage`],KI=Ba({family:`grove-session-create-request`,version:1,kinds:{request:{prefix:`request`}}});async function qI(e,t,n,r){let i=await n.openAgent(e.capabilities,{agentId:t}),a=n.createClient({baseUrl:i.baseUrl,eventSource:LI(i.fetch),fetch:i.fetch});try{return await r(a)}finally{Promise.allSettled([a.close(),i.close()])}}function JI({open:e,renderConversation:t,connection:n,commands:r,composeDraft:i,onPrefilled:a,onForked:o,onOpen:s,models:c,autoFocus:l,label:u=`Conversation`}){let d=e.session,[f,p]=(0,q.useState)({kind:`loading`});return(0,q.useEffect)(()=>{if(!n||t)return;let r=new AbortController;return p({kind:`loading`}),tI(n.capabilities,e.agentId,r.signal).then(e=>{r.signal.aborted||p({kind:`ready`,models:e})},()=>{r.signal.aborted||p({kind:`unavailable`})}),()=>{r.abort()}},[n,e.agentId,t]),(0,q.useEffect)(()=>{let i=r.contribute({sourceId:`grove-session`,namespace:`session`,commands:[...FC(d,{sourceId:`grove-session`,namespace:`session`,sessionResumeAvailable:!1,forkAvailable:!0,onForked:o}),...t?[]:jx(d,{sourceId:`grove-session`,namespace:`session`,models:f.kind===`ready`?f.models:[],refreshModels:t=>n?tI(n.capabilities,e.agentId,t):Promise.reject(Error(`Agent connection is unavailable`)),availability:()=>f.kind===`ready`&&f.models.length>0?{status:`available`}:{status:`unavailable`,reason:f.kind===`loading`?`Loading this Agent's models`:f.kind===`ready`?`This Agent has no available models`:`This Agent's model catalog is unavailable`}})]});return()=>{i.dispose()}},[r,d,o,t,f,n,e.agentId]),(0,Y.jsx)(`section`,{className:`inbox-conversation min-h-0 min-w-0 flex-1`,"data-inbox-conversation":!0,"aria-label":u,children:t?t(e,i,s):(0,Y.jsx)(q.Suspense,{fallback:(0,Y.jsx)(_I,{className:`m-auto`,framed:!1,message:`Opening conversation…`}),children:(0,Y.jsx)(HI,{session:d,draftIdentity:{agentId:e.agentId,sessionId:e.sessionId},connection:n,commands:r,prefill:i,onPrefilled:a,onOpen:s,models:c,autoFocus:l})})})}function YI(e){return mh(e.connection),(0,Y.jsx)(XI,{...e},JSON.stringify(Iy.of(e.connection)))}function XI(e){let t=(0,q.useMemo)(bF,[e.connection]);return(0,Y.jsx)(gF,{value:(0,Y.jsx)(ZI,{...e,router:t}),children:(0,Y.jsx)(fF,{router:t})})}function ZI({router:e,connection:t,services:n=UI}){let{agentFilterId:r,setFilter:i,selection:a,open:o}=xF(e,t?.window.navigation),c=ln(),l=BI(t,n),{directory:u,inbox:d,computerChoices:p,createAgent:m,renameAgent:h,setAgentAvatar:g}=nI(t),_=u.data??[],v=u.isPending&&(t?.capabilities.has(yg)??!0),y=u.error?.message??null,b=m.isPending,x=Jo({mutationFn:e=>{if(!t)throw Error(`No App connection`);return qI(t,e.agentId,n,t=>t.createSession(e.requestId))}}),S=Jo({mutationFn:e=>{if(!t)throw Error(`No App connection`);return qI(t,e.agentId,n,t=>t.deleteSession(e.sessionId))},onSuccess:(t,n)=>{a?.agentId===n.agentId&&a.sessionId===n.sessionId&&(je?.clear(),e.navigate({to:`/`,search:!0,replace:!0})),d.refresh()}}),C=x.isPending?x.variables.agentId:null,[w,T]=(0,q.useState)(null),[E,ee]=(0,q.useState)(null),[D,O]=(0,q.useState)(!1),k=E?.agentId??null,A=E?.sessionId??null,[j,te]=(0,q.useState)(null),ne=(0,q.useRef)(null),[re,ae]=hI((0,q.useMemo)(()=>t?.capabilities.has(YF)?t.capabilities.require(YF):void 0,[t])),{agentRailOpen:oe,listRailOpen:se,listWidth:ce}=re,le=e=>{ae(t=>({...t,agentRailOpen:e(t.agentRailOpen)}))},ue=e=>{ae(t=>({...t,listRailOpen:e(t.listRailOpen)}))},M=e=>{ae(t=>({...t,listWidth:fI(e(t.listWidth))}))},de=oI({begin:()=>!0,move:e=>{M(t=>t+e)},end:()=>void 0}),[fe,pe]=(0,q.useState)(!1),he=$T(),ge=(0,q.useRef)(null),[_e,ve]=(0,q.useState)(null),ye=m.error?.message??null,N=m.data,xe=(0,q.useRef)(null),[Se,Ce]=(0,q.useState)(null),[we,Te]=(0,q.useState)(null),Ee=mh(t),De=Ee?.openRequest??null,Oe=Ee?.setup?.models===`missing`,ke=(0,q.useCallback)(()=>{t?.ui.openSetup(`model`).catch(e=>{console.error(`Grove could not open model setup`,e)})},[t]),Ae=(0,q.useRef)(null),je=(0,q.useMemo)(()=>t===null?null:RI({connection:t,queryClient:c,services:n,onPending:T,onConversation:ee,onError:Ce}),[t,c,n]);(0,q.useEffect)(()=>{if(je!==null)return()=>{xe.current=null,je.close()}},[je]);let[Me,Ne]=(0,q.useState)(null),Pe=(0,q.useMemo)(()=>Et(),[]),Fe=(0,q.useMemo)(()=>t===null?null:RI({connection:t,queryClient:c,services:n,onPending:()=>void 0,onConversation:Ne,onError:Ce,reportsSelection:!1}),[t,c,n]);(0,q.useEffect)(()=>Fe===null?void 0:()=>{Fe.close()},[Fe]);let Ie=(0,q.useCallback)(e=>{let t=t=>e.params.find(e=>e.key===t)?.value,n=t(`agent`),r=t(`session`);n!==void 0&&r!==void 0&&Fe?.select(n,r)},[Fe]),Le=(0,q.useRef)(null),Re=(0,q.useCallback)((e,t,n=!1)=>{je!==null&&(x.isError&&x.reset(),l.clear(),O(!1),Le.current={agentId:e,sessionId:t},je.select(e,t,n),o(e,t))},[je,o,l.clear,x.isError,x.reset]),ze=a?.agentId,Be=a?.sessionId;(0,q.useEffect)(()=>{let e=Le.current;Le.current=null,ze===void 0||Be===void 0?je?.clear():(e?.agentId!==ze||e.sessionId!==Be)&&je?.select(ze,Be)},[je,ze,Be]);let Ve=(0,q.useCallback)(e=>{E&&(Re(E.agentId,e),d.refresh())},[E,Re,d.refresh]);(0,q.useEffect)(()=>{if(!t||De===null){De===null&&(Ae.current=null);return}if(De.kind!==`navigate`||Ae.current===De.requestId)return;let e=De.params.find(e=>e.key===`agent`)?.value,n=De.params.find(e=>e.key===`session`)?.value;!e||!n||(Ae.current=De.requestId,i(e),Re(e,n,!0))},[t,De,Re,i]);let He=(0,q.useCallback)(async e=>{if(!t||b||!t.capabilities.has(bg))return!1;try{let t=await m.mutateAsync(e);return i(t.agentId),ve(t.agentId),te(null),!0}catch{return!1}},[t,b,m.mutateAsync,i]),Ue=(0,q.useCallback)(async(e,n)=>{if(!t||C!==null)return`Conversation creation is unavailable.`;Ce(null);let r=xe.current?.agentId===e?xe.current:{agentId:e,requestId:KI.request.generate()};xe.current=r;try{let t=await x.mutateAsync(r);Re(e,t),n!==void 0&&Te({requestId:Tm(),text:n,send:!0}),d.refresh(),te(null),pe(!1),xe.current===r&&(xe.current=null);return}catch(e){return console.error(`Grove conversation creation failed`,e),e instanceof Error?e.message:`Couldn't start the conversation.`}},[t,Re,C,x.mutateAsync,d.refresh]);(0,q.useEffect)(()=>{if(!(!t||De?.kind!==`compose`)&&Ae.current!==De.requestId&&!(!E&&v)&&(Ae.current=De.requestId,Te({requestId:De.requestId,text:De.text}),!E)){let e=t.capabilities.has(jg)?_.find(e=>e.sessionOperations.includes(`agent.read`)&&e.sessionOperations.includes(`agent.send`)&&e.sessionOperations.includes(`agent.manage`)):void 0;e?Ue(e.agentId):te(`agent`)}},[_,t,v,E,De,Ue]);let We=$F({setDraft:e=>w!==null||!E||!t?.capabilities.has(jg)||!_.some(e=>e.agentId===E.agentId&&e.sessionOperations.includes(`agent.send`))?!1:(Te({requestId:Tm(),text:e}),!0),newConversation:()=>{E&&Ue(E.agentId)},openPermissions:()=>{t?.ui.requestAppPermissions({}).catch(e=>{console.error(`Chat inbox or permission request failed`,e)})}},t?.commands),Ge=new Set(l.rows.map(e=>`${e.agentId}:${e.conversation.sessionId}`)),Ke=d.items.filter(e=>!(`kind`in e)).filter(e=>!Ge.has(`${e.agentId}:${e.sessionId}`)),qe=Go({queries:(E?[E.session]:[]).map(e=>({...f(e),enabled:!1}))}).at(0)?.data?.snapshot,Je=(0,q.useMemo)(()=>E&&qe?{agentId:E.agentId,sessionId:E.sessionId,state:dt(qe)}:void 0,[E,qe]),Ye=(0,q.useMemo)(()=>HT(_,D&&l.canRead?[]:Ke,r,Je),[r,_,Ke,D,l.canRead,Je]),Xe=(0,q.useMemo)(()=>{let e=new Map;for(let t of Ke)`state`in t&&(t.state===`needs_you`?e.set(t.agentId,`speaking`):t.state===`running`&&!e.has(t.agentId)&&e.set(t.agentId,`thinking`));return e},[Ke]),Ze=(0,q.useMemo)(()=>new Map(_.map(e=>[e.agentId,e])),[_]),Qe=(0,q.useRef)(null),$e=Ke.find(e=>e.agentId===k&&e.sessionId===A),et=$e!==void 0&&$e.state!==`unavailable`,tt=$e!==void 0&&$e.state!==`unavailable`?$e.settledAt:void 0;(0,q.useEffect)(()=>{!et||k===null||A===null||d.visit(k,A).catch(e=>{console.error(`Chat inbox or permission request failed`,e)})},[et,tt,k,A,d.visit]);let nt=d.status===`loading`,rt=d.status===`error`,it=t?.capabilities.has(bg)??!1,at=t?.capabilities.has(jg)??!1,ot=_.filter(e=>e.sessionOperations.includes(`agent.read`)&&e.sessionOperations.includes(`agent.send`)&&e.sessionOperations.includes(`agent.manage`)),st=ot.find(e=>e.agentId===(_e??r))??ot.at(0),ct=at&&st!==void 0,lt=()=>{t?.ui.requestAppPermissions({agents:WI}).catch(e=>{console.error(`Chat inbox or permission request failed`,e)})},ut=N&&(!N.sessionOperations.includes(`agent.read`)||!N.sessionOperations.includes(`agent.send`)||!N.sessionOperations.includes(`agent.manage`))?`Agent created. Allow Grove to read, send messages and manage its sessions to start a conversation.`:we&&!E&&!ct&&m.isIdle?`Choose an Agent to compose your game idea.`:null,ft=(0,q.useMemo)(()=>HT(_,Ke,null,Je),[_,Ke,Je]),pt=(e,t)=>{pe(!1),Re(e,t)},mt=()=>{ge.current=document.activeElement instanceof HTMLElement?document.activeElement:null,pe(!0)};hh(t,[...he?[{kind:`button`,id:`agents`,text:`Agents`,expanded:oe,title:oe?`Hide Agents`:`Show Agents`},{kind:`button`,id:`conversations`,text:`Conversations`,expanded:se,title:se?`Hide conversations`:`Show conversations`}]:[{kind:`button`,id:`agents`,text:`Agents and conversations`,opens:`dialog`,expanded:fe}],...Me===null?[]:[{kind:`button`,id:`close-beside`,text:`Close beside`,title:`Close beside conversation`}]],e=>{if(j!==null)return!1;if(e.itemId===`close-beside`&&Me!==null)Fe?.clear();else if(he&&e.itemId===`agents`)le(e=>!e);else if(he&&e.itemId===`conversations`)ue(e=>!e);else if(!he&&e.itemId===`agents`)fe?pe(!1):mt();else return!1;return!0});let ht=e=>{i(e),ve(e);let t=[...ft.active,...ft.settled].filter(t=>t.agentId===e).sort((e,t)=>t.lastActivityAt-e.lastActivityAt).at(0);t&&pt(e,t.sessionId)},gt={"--grove-list-width":`${String(ce)}px`},_t=E?Ze.get(E.agentId):void 0,vt=r===null?void 0:Ze.get(r),yt=t?.capabilities.has(Sg)??!1,bt=_.length===1?_[0]:void 0,xt=vt??bt,St=t?.capabilities.has(Tg)??!1,Ct=rI(t,vt?.agentId??null),wt=WT(Ye).length,Dt=(0,q.useRef)(!1);(0,q.useEffect)(()=>{n.autoOpen!==!0||Dt.current||!t||E||De!==null||v||nt||rt||y||Oe||wt>0||st===void 0||!at||C!==null||(Dt.current=!0,Ue(st.agentId))},[at,t,v,y,rt,wt,nt,Oe,E,De,n.autoOpen,st,Ue,C]);let Ot=(0,q.useCallback)(async(e,n)=>{if(!t)return!1;try{return await h.mutateAsync({agentId:e,name:n}),!0}catch{return!1}},[t,h.mutateAsync]),kt=(0,q.useCallback)(async(e,n)=>{if(!t)return!1;try{return await g.mutateAsync({agentId:e,avatar:n}),!0}catch{return!1}},[t,g.mutateAsync]),At=(0,q.useCallback)(()=>{let e=Ct.status.data;!vt||e==null||Ct.approve.mutate({agentId:vt.agentId,expectedRevision:e.revision})},[vt,Ct.status.data,Ct.approve]),jt=(0,q.useCallback)(e=>{!t||b||C!==null||e===`agent`&&!it||(j===null&&(ne.current=fe?ge.current:document.activeElement instanceof HTMLElement?document.activeElement:null),pe(!1),e===`session`&&ve(_t?.agentId??r??ot.at(0)?.agentId??null),te(e))},[t,b,C,it,j,fe,_t?.agentId,r,ot]);(0,q.useEffect)(()=>{let e=e=>{e.defaultPrevented||e.repeat||!e.ctrlKey||e.altKey||e.metaKey||e.key.toLowerCase()!==`n`||!t||e.shiftKey&&!it||(e.preventDefault(),jt(e.shiftKey?`agent`:`session`))};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e)}},[t,it,jt]);let Mt=x.isError?x.variables:null,Nt=Mt&&j!==`session`?(0,Y.jsx)(be,{className:E||l.selected?`inbox-error m-2`:`inbox-empty m-auto max-w-[28rem]`,tone:`error`,title:`Couldn't start the conversation.`,description:x.error?.message,action:(0,Y.jsx)(Zt,{variant:`outline`,onClick:()=>void Ue(Mt.agentId),children:`Retry`})}):null;return(0,Y.jsxs)(`main`,{className:`inbox-app grove-shell relative flex h-dvh min-h-0 bg-base-200 font-sans text-base-content`,"data-inbox-app":!0,"data-conversation":!!E||l.selected!==void 0,children:[t?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(NA,{open:j===`agent`,pending:b,error:ye,computers:p.isError?{status:`unavailable`,message:`Your Computers could not be loaded. New Computer and No Computer still work.`}:p.isPending?{status:`loading`}:p.data===null?{status:`not-offered`}:{status:`offered`,computers:p.data},create:He,onClose:()=>{te(null)},returnFocus:ne}),j===`session`?(0,Y.jsx)(PA,{open:!0,agents:at?ot:[],defaultAgentId:st?.agentId??null,start:Ue,pending:C!==null,onClose:()=>{te(null)},onNewAgent:it?()=>{te(`agent`)}:void 0,returnFocus:ne}):null]}):null,(0,Y.jsxs)(eE,{open:fe,onOpenChange:pe,returnFocus:ge,children:[(0,Y.jsx)(JT,{open:oe,agents:_,agentActivity:Xe,agentFilterId:r,websitesSelected:D,websitesVisible:l.canRead,canCreate:t!==null&&it,createOpen:j===`agent`,onAll:()=>{i(null),O(!1)},onWebsites:()=>{i(null),O(!0)},onAgent:e=>{O(!1),ht(e)},onCreate:()=>{jt(`agent`)}}),(0,Y.jsxs)(`aside`,{id:`grove-list-rail`,className:`inbox-sidebar group relative min-h-0 min-w-0 flex-1 flex-col border-r border-base-300 min-[900px]:w-[var(--grove-list-width)] min-[900px]:flex-none ${se?`flex`:`flex min-[900px]:hidden`}`,style:gt,"aria-label":`Conversations`,children:[he?(0,Y.jsx)(aI,{"aria-label":`Conversation list width`,"aria-controls":`grove-list-rail`,className:`absolute right-0 top-1/2 z-10 translate-x-1/2 -translate-y-1/2`,orientation:`vertical`,value:ce,min:cI.min,max:cI.max,onValueChange:e=>{M(()=>e)},onDoubleClick:()=>{M(()=>cI.initial)},...de}):null,(0,Y.jsxs)(`header`,{className:`inbox-header flex h-10 flex-none items-center gap-1 border-b border-base-300 pl-3 pr-1`,children:[vt?(0,Y.jsx)(iI,{agentId:vt.agentId,name:KT(vt),avatar:vt.avatar,...St?{setAvatar:kt}:{}},vt.agentId):null,(0,Y.jsx)(me,{className:`min-w-0 flex-1 truncate`,children:D&&l.canRead?`Websites`:vt?KT(vt):`All Agents`}),xt&&yt?(0,Y.jsx)(CF,{agentId:xt.agentId,name:xt.name,rename:Ot},xt.agentId):null,t&&(ct||it)?(0,Y.jsx)(Tt,{"aria-label":`New conversation`,"aria-haspopup":`dialog`,icon:(0,Y.jsx)(fT,{}),iconSize:`sm`,size:`sm`,onClick:()=>{jt(`session`)}}):null]}),vt&&Ct.canRead?(0,Y.jsx)(wF,{status:Ct.status.data,approving:Ct.approve.isPending,onApprove:At}):null,ut?(0,Y.jsx)(be,{tone:`info`,title:ut,action:(0,Y.jsx)(Zt,{variant:`ghost`,onClick:()=>{t?.ui.requestAppPermissions({agents:GI}).catch(e=>{console.error(`Chat inbox or permission request failed`,e)})},children:`Allow conversation access`})}):null,t&&_.length>0&&!ct&&!it?(0,Y.jsxs)(`section`,{className:`inbox-create inbox-access flex flex-col items-start gap-3 border-b border-base-300 py-2`,"aria-labelledby":`inbox-agent-access-title`,children:[(0,Y.jsx)(s,{level:2,id:`inbox-agent-access-title`,className:`inbox-access-title m-0`,children:`Let Grove manage your Agents`}),(0,Y.jsx)(`p`,{children:`Grove creates Agents and carries their conversations. Your Team decides what it may do.`}),(0,Y.jsx)(Zt,{size:`sm`,onClick:lt,children:`Allow Agent access`})]}):null,S.error?(0,Y.jsx)(be,{tone:`error`,title:S.error.message}):null,y?(0,Y.jsx)(be,{className:`inbox-error`,tone:`error`,title:y,action:(0,Y.jsx)(Zt,{variant:`ghost`,size:`sm`,onClick:()=>{u.refetch()},children:`Try again`})}):null,rt?(0,Y.jsx)(be,{className:`inbox-error`,tone:`error`,title:`Conversations are unavailable.`,action:(0,Y.jsx)(Zt,{variant:`ghost`,size:`sm`,onClick:()=>{d.refresh()},children:`Retry conversations`})}):null,(0,Y.jsx)(dx,{ref:Qe,className:`inbox-surface min-h-0 flex-1`,"aria-label":`Conversations`,children:t?v?(0,Y.jsx)(`p`,{className:`inbox-empty m-0 px-2 py-3 text-sm text-(--stipe-fg-muted)`,role:`status`,children:`Loading Agents…`}):(0,Y.jsx)(xI,{viewport:Qe,view:Ye,agents:Ze,loading:nt||l.loading,failed:!!y||rt||l.failed,showEmptyState:!Oe,pendingSelection:w,selectedAgentId:k,selectedSessionId:A,onSelect:pt,onDelete:at?(e,t)=>{S.mutate({agentId:e,sessionId:t})}:void 0,deleting:S.isPending?S.variables:null,websites:l.rows.filter(e=>r===null||e.agentId===r),selectedWebsite:l.selected,onSelectWebsite:e=>{je?.clear(),pe(!1),l.select(e)}}):(0,Y.jsx)(`p`,{className:`inbox-empty m-0 px-2 py-3 text-sm text-(--stipe-fg-muted)`,children:`Connect to the host to browse Agents.`})},r)]})]}),(0,Y.jsxs)(`section`,{className:`inbox-conversation-shell flex min-h-0 min-w-0 flex-1 flex-col`,"aria-label":`Conversation`,children:[(0,Y.jsx)(YT,{app:t}),Se?(0,Y.jsx)(be,{className:`inbox-error m-2`,tone:`error`,title:Se}):null,E||l.selected?Nt:null,l.selected?(0,Y.jsx)(q.Suspense,{fallback:null,children:(0,Y.jsx)(VI,{inbox:l})}):E?(0,Y.jsx)(JI,{open:E,connection:t,commands:We,renderConversation:n.renderConversation,composeDraft:we,onPrefilled:()=>{Te(null)},onForked:Ve,onOpen:Ie,models:Ee?.setup?.models,autoFocus:he}):!t||v?null:_.length===0&&!y?(0,Y.jsx)(ie,{className:`inbox-empty m-auto max-w-[28rem]`,variant:`speech`,thinking:b,renderVisual:({speaking:e,thinking:t})=>(0,Y.jsx)(AT,{className:`h-full w-full`,state:{activity:t?`thinking`:e?`speaking`:`idle`,expression:`normal`}}),title:it?`No one's here yet.`:`Welcome to Grove`,description:it&&Oe?`Agents chat, write and make little games with you. Connect a model to start chatting.`:it?`Agents chat, write and make little games with you. Name someone?`:`Let Grove find your Agents, create new ones, and open conversations. Your Team controls this access.`,actions:it&&Oe?(0,Y.jsx)(Zt,{onClick:ke,children:`Add a model key`}):it?(0,Y.jsx)(Zt,{onClick:()=>{jt(`agent`)},children:`Name your first Agent`}):(0,Y.jsx)(Zt,{onClick:lt,children:`Allow Agent access`})}):Oe?(0,Y.jsx)(kn,{className:`inbox-empty m-auto max-w-[28rem]`,cause:`Chat, write and make little games with Agents. Connect a model to begin.`,visual:(0,Y.jsx)(AT,{state:{activity:`idle`,expression:`normal`}}),fix:{label:`Add a model key`,onSelect:ke},need:`Connect a model to start chatting`,variant:`panel`}):Nt??(0,Y.jsx)(ie,{className:`inbox-empty m-auto max-w-[28rem]`,variant:`panel`,title:wt>0?`Pick up a conversation`:st?`Say hello to ${KT(st)}`:`No conversations yet`,description:wt>0?`Choose one from the list, or ask for something new. A tiny game is a good start.`:`Ask for anything. Pick one to start.`,suggestions:wt===0&&ct?vI.map(e=>({label:e,disabled:C!==null,onSelect:()=>{Ue(st.agentId,e)}})):void 0,actions:(0,Y.jsxs)(Y.Fragment,{children:[he||wt===0?null:(0,Y.jsx)(Zt,{variant:`outline`,"aria-haspopup":`dialog`,"aria-controls":`grove-nav`,"aria-expanded":fe,onClick:mt,children:`Agents and conversations`}),ct?(0,Y.jsx)(Zt,{variant:`outline`,loading:C===st.agentId,disabled:C!==null,onClick:()=>void Ue(st.agentId),children:wt>0?`Ask ${KT(st)} something`:`Start a conversation`}):null]})})]}),Me===null?null:(0,Y.jsx)(`section`,{className:`inbox-conversation-shell flex min-h-0 min-w-0 flex-1 flex-col border-l border-base-300`,"aria-label":`Beside conversation`,"data-inbox-beside":!0,children:(0,Y.jsx)(JI,{open:Me,connection:t,commands:Pe,renderConversation:n.renderConversation,composeDraft:null,onPrefilled:()=>void 0,onForked:e=>{Fe?.select(Me.agentId,e)},onOpen:Ie,models:Ee?.setup?.models,label:`Beside conversation`})})]})}var QI=document.getElementById(`inbox-root`);if(!QI)throw Error(`Inbox root is missing`);dh(QI,{name:`Grove`,queryClient:Ry()},({app:e})=>(0,q.createElement)(YI,{connection:e}));export{Ch as _,YS as a,JS as c,BS as d,Rx as f,Sh as g,bh as h,nC as i,ZS as l,xh as m,dA as n,XS as o,Iy as p,cA as r,KS as s,vI as t,qS as u,yh as v,qo as y};
|