@fungi.computer/inkcap 0.8.8 → 0.8.9

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.
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{$r as t,An as n,Br as r,Ci as i,Cn as a,Cr as o,Dn as s,En as c,Fn as l,Gr as u,Hr as d,In as f,Ji as ee,Jr as p,Ki as m,Kn as te,Kr as h,Ln as ne,Nn as re,On as ie,Qr as g,Ri as ae,Rn as oe,Si as _,Sn as se,Sr as v,Tn as ce,Tr as le,Un as y,Ur as b,Vn as ue,Vr as de,Wn as fe,Xi as pe,Xr as x,Yi as me,Yr as he,Zi as ge,_i as _e,_n as ve,_r as ye,an as be,bi as xe,bn as Se,br as Ce,ci as we,cn as Te,cr as Ee,di as De,dn as Oe,dr as ke,ea as Ae,fi as je,fn as Me,gi as Ne,gn as Pe,gr as S,hi as Fe,hn as Ie,hr as C,ii as w,in as Le,kn as Re,li as ze,lr as Be,mi as Ve,mn as He,mr as Ue,na as We,ni as Ge,oi as T,pn as E,pr as Ke,qi as qe,qr as Je,ri as D,sn as Ye,sr as Xe,ti as Ze,ui as O,un as Qe,ur as $e,vi as k,vn as A,vr as j,wn as et,wr as M,xi as tt,xn as nt,yi as rt,yn as it,yr as at,zi as ot,zn as st}from"./tree-path-D47zLaQq.js";var ct=new WeakMap,lt=`~effect/Redacted`,ut=e=>ge(e,lt),dt=(e,t)=>{let n=Object.create(ft);return t?.label&&(n.label=t.label),ct.set(n,e),n},ft={[lt]:{_A:e=>e},label:void 0,...m,toJSON(){return this.toString()},toString(){return`<redacted${Ae(this.label)?`:`+this.label:``}>`},[pe](){return me(ct.get(this))},[ee](e){return ut(e)&&qe(ct.get(this),ct.get(e))}},N=e(de(),1),P=r(),pt=N.createContext(void 0),mt=e=>{let t=N.useContext(pt);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},ht=({client:e,children:t})=>(N.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,P.jsx)(pt.Provider,{value:e,children:t})),gt={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},_t=new class{#e=gt;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function vt(e){setTimeout(e,0)}var yt=typeof window>`u`||`Deno`in globalThis;function F(){}function bt(e,t){return typeof e==`function`?e(t):e}function xt(e){return typeof e==`number`&&e>=0&&e!==1/0}function St(e,t){return Math.max(e+(t||0)-Date.now(),0)}function I(e,t){return typeof e==`function`?e(t):e}function Ct(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==Tt(o,t.options))return!1}else if(!Dt(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function wt(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(Et(t.options.mutationKey)!==Et(a))return!1}else if(!Dt(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Tt(e,t){return(t?.queryKeyHashFn||Et)(e)}function Et(e){return JSON.stringify(e,(e,t)=>Mt(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function Dt(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){for(let n=0;n<t.length;n++)if(!Dt(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!Dt(e[r],t[r]))return!1;return!0}return!1}var Ot=Object.prototype.hasOwnProperty;function kt(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=jt(e)&&jt(t);if(!r&&!(Mt(e)&&Mt(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:Ot.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=kt(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function At(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function jt(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Mt(e){if(!Nt(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Nt(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function Nt(e){return Object.prototype.toString.call(e)===`[object Object]`}function Pt(e){return new Promise(t=>{_t.setTimeout(t,e)})}function Ft(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:kt(e,t)}function It(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function Lt(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Rt=Symbol();function zt(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Rt?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Bt(e,t){return typeof e==`function`?e(...t):!!e}function Vt(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var Ht=()=>yt,Ut=()=>Ht(),Wt=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Gt=new class extends Wt{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},Kt=vt;function qt(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=Kt,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var L=qt(),Jt=new class extends Wt{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function Yt(e){return Math.min(1e3*2**e,3e4)}function Xt(e){return(e??`online`)!==`online`||Jt.isOnline()}var Zt=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function Qt(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(F);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new Zt(t);m(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>Gt.isFocused()&&(e.networkMode===`always`||Jt.isOnline())&&e.canRun(),ee=()=>Xt(e.networkMode)&&e.canRun(),p=e=>{c()||(r?.(),i=`resolved`,a(e))},m=e=>{c()||(r?.(),i=`rejected`,o(e))},te=()=>new Promise(t=>{r=e=>{(c()||f())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),h=()=>{if(c())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(p).catch(r=>{if(c())return;let i=e.retry??(Ut()?0:3),a=e.retryDelay??Yt,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);if(t||!s){m(r);return}n++,e.onFail?.(n,r),Pt(o).then(()=>f()?void 0:te()).then(()=>{t?m(r):h()})})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:ee,start:()=>(ee()?h():te().then(h),s)}}var $t=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),xt(this.gcTime)&&(this.#e=_t.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ut()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(_t.clearTimeout(this.#e),this.#e=void 0)}};function en(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{Vt(e,()=>t.signal,()=>n=!0)},u=zt(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?Lt:It;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?nn:tn,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:tn(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function tn(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function nn(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var rn=class extends $t{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=sn(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=sn(this.options);e.data!==void 0&&(this.setState(on(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=Ft(this.state.data,e,this.options);return this.#c({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#c({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(F).catch(F):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>I(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Rt||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>I(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!St(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#s||this.state.fetchStatus===`paused`&&this.state.status===`pending`?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#c({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=zt(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?en(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=Qt({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof Zt&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#c({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#c({type:`pause`})},onContinue:()=>{this.#c({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await o.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof Zt){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#c({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0),this.scheduleGc()}}#c(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...an(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...on(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),L.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function an(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Xt(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function on(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function sn(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var cn=class extends Wt{#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),un(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return dn(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return dn(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof I(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!At(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&fn(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||I(this.options.enabled,this.#t)!==I(t.enabled,this.#t)||I(this.options.staleTime,this.#t)!==I(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||I(this.options.enabled,this.#t)!==I(t.enabled,this.#t)||i!==this.#f)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return At(this.getCurrentResult(),n)||(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t),r=()=>{},i,a=new Promise(e=>{i=e,r=this.#e.getQueryCache().subscribe(i=>{i.type===`updated`&&i.query.queryHash===n.queryHash&&n.state.data!==void 0&&(r(),e(this.createResult(n,t)))})});return Promise.race([n.fetch().then(()=>{let e=this.createResult(n,t);return i?.(e),e}).finally(()=>{r()}),a])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(F)),t}#h(e){return!Ut()&&I(this.options.enabled,this.#t)!==!1&&xt(e)}#g(){this.#b();let e=I(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=St(this.#r.dataUpdatedAt,e)+1;this.#u=_t.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return(typeof this.options.refetchInterval==`function`?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(e){this.#x(),this.#f=e,!(this.#f===0||!this.#h(this.#f))&&(this.#d=_t.setInterval(()=>{(this.options.refetchIntervalInBackground||Gt.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(_t.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(_t.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&un(e,t),o=i&&fn(e,n,t,r);(a||o)&&(l={...l,...an(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:ee,status:p}=l;d=l.data;let m=!1;if(t.placeholderData!==void 0&&d===void 0&&p===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,m=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(p=`success`,d=Ft(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!m){if(i&&d===a?.data&&t.select===this.#s)d=this.#c;else try{this.#s=t.select,d=t.select(d),d=Ft(i?.data,d,t),this.#c=d,this.#o=null}catch(e){this.#o=e}}else d===void 0&&(this.#o=null);this.#o&&(f=this.#o,d=this.#c,ee=Date.now(),p=`error`,u=!1);let te=l.fetchStatus===`fetching`,h=p===`pending`,ne=p===`error`,re=h&&te,ie=d!==void 0;return{status:p,fetchStatus:l.fetchStatus,isPending:h,isSuccess:p===`success`,isError:ne,isInitialLoading:re,isLoading:re,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:ee,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:te,isRefetching:te&&!h,isLoadingError:ne&&!ie,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:ne&&ie,isStale:pn(e,t),refetch:this.refetch,isEnabled:I(t.enabled,e)!==!1}}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#l=this.#t),At(t,e))return;this.#r=t;let n=(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#p.size)return!0;let r=new Set(n??this.#p);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})();L.batch(()=>{n&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function ln(e,t){return I(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||I(t.retryOnMount,e)!==!1)}function un(e,t){return ln(e,t)||e.state.data!==void 0&&dn(e,t,t.refetchOnMount)}function dn(e,t,n){if(I(t.enabled,e)!==!1&&I(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&pn(e,t)}return!1}function fn(e,t,n,r){return(e!==t||I(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&pn(e,n)}function pn(e,t){return I(t.enabled,e)!==!1&&e.isStaleByTime(I(t.staleTime,e))}var mn=class extends $t{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||hn(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??(this.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},r=this.#r=Qt({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),i=this.state.status===`pending`,a=!r.canStart();try{if(i)t();else{this.#i({type:`pending`,variables:e,isPaused:a}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:a})}let o=await r.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#i({type:`success`,data:o}),o}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#r===r&&(this.#r=void 0),this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),L.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function hn(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var gn=class extends Wt{#e;#t;#n;constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}build(e,t,n){let r=new mn({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=_n(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=_n(e);if(typeof t==`string`){let n=this.#t.get(t);if(n){if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=_n(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}return!0}runNext(e){let t=_n(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){L.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>wt(t,e))}findAll(e={}){return this.getAll().filter(t=>wt(e,t))}notify(e){L.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return L.batch(()=>Promise.all(e.map(e=>e.continue().catch(F))))}};function _n(e){return e.options.scope?.id}var vn=class extends Wt{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){let r=t.queryKey,i=t.queryHash??Tt(r,t),a=this.get(i);return a||(a=new rn({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){L.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>Ct(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>Ct(e,t)):t}notify(e){L.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){L.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){L.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},yn=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new vn,this.#t=e.mutationCache||new gn,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=Gt.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=Jt.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(I(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=bt(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return L.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;L.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return L.batch(()=>{let r=n.findAll(e),i=new Set(r);return r.forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,predicate:e=>i.has(e)},t)})}cancelQueries(e,t={}){let n={revert:!0,...t},r=L.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(F).catch(F)}invalidateQueries(e,t={}){return L.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=L.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(F)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(F)}async query(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t),r=n.isStaleByTime(I(t.staleTime,n))?await n.fetch(t):n.state.data,i=t.select;return i?i(r):r}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(I(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(F).catch(F)}infiniteQuery(e){return e._type=`infinite`,this.query(e)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(F).catch(F)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return Jt.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(Et(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{Dt(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(Et(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{Dt(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=Tt(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===Rt&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},bn=N.createContext(!1),xn=()=>N.useContext(bn);bn.Provider;function Sn(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Cn=N.createContext(Sn()),wn=()=>N.useContext(Cn),Tn=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?Bt(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},En=e=>{N.useEffect(()=>{e.clearReset()},[e])},Dn=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Bt(n,[e.error,r])),On=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))}},kn=(e,t)=>e?.suspense&&t.isPending,An=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function jn(e){return e}var Mn=Ue(),Nn=C(()=>Ke(`status`,[j({status:S(`available`)}).strict(),j({status:S(`unavailable`),reason:v()}).strict()])),Pn=Mn,Fn=C(()=>Ce(v(),Pn)),In=e=>Pn.parse(e),Ln=C(()=>j({code:v().min(1).max(160),message:v().min(1).max(512),details:Pn.optional()}).strict()),Rn=e=>Ln.parse(e),zn=Fn,R=C(()=>v().refine(e=>e.trim().length>0)),Bn=Nn,Vn=C(()=>o([j({type:S(`action`)}).strict(),j({type:S(`custom`),data:Fn}).strict(),j({type:S(`choice`),options:$e(j({value:Pn,label:R,description:R.optional()}))}).strict(),j({type:S(`form`),submitLabel:R.optional()}).strict(),j({type:S(`confirmation`),message:R,confirmLabel:R.optional(),cancelLabel:R.optional()}).strict()])),Hn=C(()=>j({inputSchema:zn.optional(),outputSchema:zn.optional(),presentation:Vn.optional()}).strict()),Un=C(()=>ye().int().refine(e=>Number.isSafeInteger(e))),Wn=C(()=>j({hint:R.pipe(v().max(120)),words:$e(j({word:v().regex(/^\S{1,64}$/u),description:R.pipe(v().max(512)).optional(),arguments:Fn}).strict()).max(32).optional(),text:j({field:R.pipe(v().max(120)),arguments:Fn,requestIdField:R.pipe(v().max(120)).optional()}).strict().optional()}).strict().refine(e=>e.words!==void 0||e.text!==void 0,`slash arguments need words or text`)),Gn=C(()=>j({order:Un.optional()}).strict()),Kn=C(()=>j({bindings:j({order:Un.optional(),values:$e(R).max(16)}).strict().optional(),agent:j({keybind:R.optional(),order:Un.optional()}).strict().optional(),help:Gn.optional(),menu:Gn.optional(),palette:Gn.optional(),slash:j({aliases:$e(R).max(16),consumesDraft:ke().optional(),order:Un.optional(),arguments:Wn.optional()}).strict().optional()}).strict()),qn=C(()=>j({id:R.refine(e=>!e.includes(`:`)),title:R,category:R,description:R.optional(),projections:Kn.optional(),action:Hn.optional(),availability:Bn.optional()}).strict()),Jn=e=>qn.parse(e),Yn=C(()=>j({inputSchema:zn.optional(),outputSchema:zn.optional()}).strict()),Xn=v().min(1).brand(),Zn=C(()=>j({commandId:Xn,command:j({namespace:v(),id:v()}).strict(),sourceId:v(),scope:v().optional(),title:v(),category:v(),description:v().optional(),order:ye(),availability:Nn,action:Yn.optional(),keybind:v().optional()}).strict());$e(Zn);var Qn=8192,z=R.pipe(v().max(Qn)),$n=R.pipe(v().max(60)),er=le({protocol:/^https?$/u}),tr=j({label:z,value:z}).strict(),nr={summary:z.optional(),facts:$e(tr).max(4).optional(),body:z.optional(),bodyLabel:z.optional(),details:$e(tr).max(24).optional()};Ke(`type`,[j({type:S(`choice`),message:$n,...nr,current:z.optional(),collapsedGroup:z.optional(),options:$e(j({value:z,label:z,description:z.optional(),group:z.optional(),destructive:S(!0).optional()}).strict()).min(1).max(256)}).strict(),j({type:S(`text`),message:$n,...nr,placeholder:z.optional(),secret:ke().optional()}).strict(),j({type:S(`confirmation`),message:$n,...nr,confirmLabel:z.optional(),cancelLabel:z.optional(),destructive:S(!0).optional()}).strict(),j({type:S(`decision`),message:$n,...nr,options:$e(j({value:z,label:z,description:z.optional(),destructive:S(!0).optional()}).strict()).min(1).max(8).refine(e=>new Set(e.map(e=>e.value)).size===e.length,`Decision option values must be unique`),multiple:ke().optional(),other:j({label:z,placeholder:z.optional(),maxLength:ye().int().min(1).max(Qn),blank:z.optional()}).strict().optional(),escape:z.optional()}).strict().refine(e=>[e.escape,e.other?.blank].every(t=>t===void 0||e.options.some(e=>e.value===t)),`A decision's escape and blank answers must be offered options`)]),C(()=>Ke(`type`,[j({type:S(`info`),message:z,links:$e(j({url:er,label:z.optional()}).strict()).max(16).optional()}).strict(),j({type:S(`progress`),message:z}).strict(),j({type:S(`handoff`),url:er,code:z.optional(),message:z.optional()}).strict(),j({type:S(`success`),message:z}).strict()]));var rr=class extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name=`WhistleActionError`}},ir=class extends Error{constructor(){super(`Whistle runtime is closed`),this.name=`WhistleClosedError`}};function ar(){let e=!1,t=Ir,n=[],r=[],i=!1,a=[],o=new Set,s=()=>{for(let e of o)e()};return Object.freeze({close:()=>{e||(e=!0,n=[],a=[],r=[],t=Ir,s(),o.clear())},contribute:t=>{if(mr(t),e)throw new ir;hr(t,n),gr(t,n);let r=Symbol(`whistle-contribution`);pr(t)||(n=[...n,{contribution:_r(t),generation:r}],i=!0,s());let a=!0;return Fr(o=>{if(!a||e)return;let c={...t,commands:o};mr(c);let l=n.findIndex(e=>e.generation===r),u=n.filter(e=>e.generation!==r);hr(c,u),gr(c,u);let d=_r(c);if(pr(c)){if(l<0)return;n=u}else n=l<0?[...n,{contribution:d,generation:r}]:n.map(e=>e.generation===r?{contribution:d,generation:r}:e);i=!0,s()},()=>{a&&(a=!1,n.find(e=>e.generation===r)!==void 0&&(n=n.filter(e=>e.generation!==r),i=!0,s()))})},execute:async(t,r)=>{if(t.namespace.trim().length===0||t.id.trim().length===0)return{status:`invalid`};if(e)return{status:`closed`};let i=fr(t,n);if(i===void 0)return{status:`missing`};let o;try{let e=Rr(i);if(e.status===`unavailable`)return e;let n=a.at(-1)?.presenter;r.interaction===void 0&&n!==void 0&&or.has(r.origin)&&(o=n({commandId:dr(t.namespace,t.id),title:i.title}));let s={...r,signal:r.signal??new AbortController().signal};o!==void 0&&(s.interaction=o.interaction,s.signal=AbortSignal.any([s.signal,o.interaction.signal]));let c=await i.handler(s);return o?.settle({status:`handled`}),c===void 0?{status:`handled`}:{status:`handled`,result:c}}catch(e){let t=Br(e instanceof Error?e:Error(`Command handler threw a non-Error value`));return o?.settle(o.interaction.signal.aborted?{status:`cancelled`}:{status:`failed`,message:t.message}),{status:`failed`,error:t}}},present:t=>{let n={presenter:t};return e||(a=[...a,n]),()=>{a=a.filter(e=>e!==n)}},snapshot:()=>{if(e)return Ir;let a=n.flatMap(e=>e.contribution.commands.map(Rr));return(i||a.some((e,t)=>!zr(e,r[t])))&&(t=Vr(n,a),r=a,i=!1),t},subscribe:t=>e?()=>void 0:(o.add(t),()=>{o.delete(t)})})}var or=new Set([`browser`,`keyboard`,`menu`,`palette`,`slash`,`terminal`]),sr=16,cr=32,lr=64,ur=256;function dr(e,t){return Xn.parse(`${e}:${t}`)}function fr(e,t){for(let n of t)if(n.contribution.namespace===e.namespace){for(let t of n.contribution.commands)if(t.id===e.id)return t}}function pr(e){return e.commands.length===0}function mr(e){B(e.sourceId,`source ID`),B(e.namespace,`namespace`),e.scope!==void 0&&B(e.scope,`scope`);for(let t of e.commands)kr(t)}function hr(e,t){t.find(t=>t.contribution.namespace===e.namespace&&t.contribution.sourceId!==e.sourceId)!==void 0&&V(`Namespace is already owned by another source`);let n=new Set,r=new Set;for(let i of t){let t=i.contribution.scope===e.scope;for(let e of i.contribution.commands)if(n.add(dr(i.contribution.namespace,e.id)),t)for(let t of e.projections?.slash?.aliases??[])r.add(t)}for(let t of e.commands){let i=dr(e.namespace,t.id);n.has(i)&&V(`Canonical command ID is already registered`),n.add(i);for(let e of t.projections?.slash?.aliases??[])r.has(e)&&V(`Slash alias is already registered`),r.add(e)}}function gr(e,t){t.length>=lr&&V(`Live contribution capacity exceeded`),t.reduce((e,t)=>e+t.contribution.commands.length,0)+e.commands.length>ur&&V(`Live command capacity exceeded`)}function _r(e){let t={sourceId:e.sourceId,namespace:e.namespace,commands:e.commands.map(vr)};return e.scope===void 0?t:{...t,scope:e.scope}}function vr(e){let t={id:e.id,title:e.title,category:e.category,handler:e.handler};return e.description!==void 0&&(t.description=e.description),e.action!==void 0&&(t.action=yr(e.action)),e.availability!==void 0&&(t.availability=e.availability),e.projections!==void 0&&(t.projections=Cr(e.projections)),t}function yr(e){let t={};return e.inputSchema!==void 0&&(t.inputSchema=br(e.inputSchema)),e.outputSchema!==void 0&&(t.outputSchema=br(e.outputSchema)),e.presentation!==void 0&&(t.presentation=Sr(e.presentation)),Object.freeze(t)}function br(e){return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,xr(t)])))}function xr(e){return Array.isArray(e)?Object.freeze(e.map(xr)):e!==null&&e instanceof Object?Object.freeze(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,xr(t)]))):e}function Sr(e){switch(e.type){case`action`:return Object.freeze({type:`action`});case`custom`:return Object.freeze({type:`custom`,data:br(e.data)});case`choice`:return Object.freeze({type:`choice`,options:Object.freeze(e.options.map(e=>Object.freeze({...e,value:xr(e.value)})))});case`form`:return Object.freeze({...e});case`confirmation`:return Object.freeze({...e})}}function Cr(e){let t={};return e.bindings!==void 0&&(t.bindings=wr(e.bindings)),e.agent!==void 0&&(t.agent=Tr(e.agent)),e.help!==void 0&&(t.help=Er(e.help.order)),e.menu!==void 0&&(t.menu=Er(e.menu.order)),e.palette!==void 0&&(t.palette=Er(e.palette.order)),e.slash!==void 0&&(t.slash=Dr(e.slash)),t}function wr(e){let t={values:[...e.values]};return e.order!==void 0&&(t.order=e.order),t}function Tr(e){let t={};return e.keybind!==void 0&&(t.keybind=e.keybind),e.order!==void 0&&(t.order=e.order),t}function Er(e){let t={};return e!==void 0&&(t.order=e),t}function Dr(e){let t={aliases:[...e.aliases]};return e.order!==void 0&&(t.order=e.order),e.consumesDraft!==void 0&&(t.consumesDraft=e.consumesDraft),e.arguments!==void 0&&(t.arguments=Or(e.arguments)),t}function Or(e){let t={hint:e.hint};return e.words!==void 0&&(t.words=Object.freeze(e.words.map(e=>Object.freeze({...e,arguments:br(e.arguments)})))),e.text!==void 0&&(t.text=Object.freeze({...e.text,arguments:br(e.text.arguments)})),Object.freeze(t)}function kr(e){B(e.id,`command ID`,!0),B(e.title,`title`),B(e.category,`category`),Ar(e.action),jr(e.projections)}function Ar(e){if(e?.presentation!==void 0)switch(e.presentation.type){case`action`:case`custom`:return;case`choice`:for(let t of e.presentation.options)B(t.label,`choice label`),t.description!==void 0&&B(t.description,`choice description`);return;case`form`:e.presentation.submitLabel!==void 0&&B(e.presentation.submitLabel,`submit label`);return;case`confirmation`:B(e.presentation.message,`confirmation message`),e.presentation.confirmLabel!==void 0&&B(e.presentation.confirmLabel,`confirmation label`),e.presentation.cancelLabel!==void 0&&B(e.presentation.cancelLabel,`cancellation label`)}}function jr(e){if(e!==void 0){for(let t of[e.bindings,e.palette,e.slash,e.help,e.menu,e.agent])t!==void 0&&Pr(t.order);if(e.bindings!==void 0&&Nr(e.bindings.values,`binding`),e.slash!==void 0){Nr(e.slash.aliases,`slash alias`);for(let t of e.slash.aliases)/\s/u.test(t)&&V(`slash alias must not contain whitespace`);Mr(e.slash.arguments)}e.agent?.keybind!==void 0&&B(e.agent.keybind,`agent keybind`)}}function Mr(e){if(e===void 0)return;B(e.hint,`argument hint`),e.words===void 0&&e.text===void 0&&V(`slash arguments need words or text`);let t=new Set;for(let n of e.words??[])B(n.word,`argument word`),/\s/u.test(n.word)&&V(`argument word must not contain whitespace`),t.has(n.word)&&V(`argument word is repeated`),t.add(n.word),n.description!==void 0&&B(n.description,`argument word description`);t.size>cr&&V(`argument word count exceeds 32`),e.text!==void 0&&(B(e.text.field,`argument text field`),e.text.requestIdField!==void 0&&B(e.text.requestIdField,`request id field`))}function Nr(e,t){e.length>sr&&V(`${t} count exceeds 16`);for(let n of e)B(n,t)}function B(e,t,n=!1){e.trim().length===0&&V(`${t} must not be blank`),n&&e.includes(`:`)&&V(`${t} must not contain a colon`)}function Pr(e){e!==void 0&&!Number.isSafeInteger(e)&&V(`order must be a safe integer`)}function Fr(e=()=>void 0,t=()=>void 0){return Object.freeze({update:e,dispose:t})}function V(e){throw Error(e)}var Ir=Object.freeze({bindings:Object.freeze([]),palette:Object.freeze([]),slash:Object.freeze([]),help:Object.freeze([]),menu:Object.freeze([]),agent:Object.freeze([])}),Lr=Object.freeze({status:`available`});function Rr(e){let t=e.availability?.()??Lr;return t.status===`available`?Lr:Object.freeze({status:`unavailable`,reason:t.reason})}function zr(e,t){return e.status===`available`?t?.status===`available`:t?.status===`unavailable`&&e.reason===t.reason}function Br(e){if(e instanceof rr){let t={code:e.code,message:e.message};return Object.freeze(e.details===void 0?t:{...t,details:xr(e.details)})}return Object.freeze({code:`command_failed`,message:e.message})}function Vr(e,t){let n=[],r=[],i=[],a=[],o=[],s=[],c=0;for(let l of e){let e=l.contribution;for(let l of e.commands){let u=l.projections,d=t[c++]??Lr;if(u?.bindings!==void 0)for(let t of u.bindings.values)n.push({...Jr(e,l,u.bindings.order,d),binding:t});if(u?.palette!==void 0&&r.push({...Jr(e,l,u.palette.order,d)}),u?.slash!==void 0)for(let t of u.slash.aliases){let n={...Jr(e,l,u.slash.order,d),alias:t};u.slash.consumesDraft!==void 0&&(n={...n,consumesDraft:u.slash.consumesDraft}),u.slash.arguments!==void 0&&(n={...n,arguments:u.slash.arguments}),i.push(n)}u?.help!==void 0&&a.push({...Jr(e,l,u.help.order,d)}),u?.menu!==void 0&&o.push({...Jr(e,l,u.menu.order,d)}),u?.agent!==void 0&&s.push(Xr(e,l,u.agent,d))}}return Gr(n),Kr(i),Wr(r),Wr(a),Wr(o),Wr(s),Object.freeze({bindings:qr(n),palette:qr(r),slash:qr(i),help:qr(a),menu:qr(o),agent:qr(s)})}var Hr=new TextEncoder;function Ur(e,t){let n=Hr.encode(e),r=Hr.encode(t),i=Math.min(n.length,r.length);for(let e=0;e<i;e+=1){let t=n[e]??0,i=r[e]??0;if(t!==i)return t<i?-1:1}return n.length<r.length?-1:+(n.length>r.length)}function Wr(e){e.sort((e,t)=>e.order-t.order||Ur(e.commandId,t.commandId))}function Gr(e){e.sort((e,t)=>e.order-t.order||Ur(e.commandId,t.commandId)||Ur(e.binding,t.binding))}function Kr(e){e.sort((e,t)=>e.order-t.order||Ur(e.commandId,t.commandId)||Ur(e.alias,t.alias))}function qr(e){return Object.freeze(e.map(e=>Object.freeze(e)))}function Jr(e,t,n,r){let i=Yr(e,t,n,r);return e.scope===void 0?i:{...i,scope:e.scope}}function Yr(e,t,n,r){let i={commandId:dr(e.namespace,t.id),command:Object.freeze({namespace:e.namespace,id:t.id}),sourceId:e.sourceId,title:t.title,category:t.category,order:n??0,availability:r},a=t.description===void 0?i:{...i,description:t.description};return t.action===void 0?a:{...a,action:t.action}}function Xr(e,t,n,r){let i=Jr(e,t,n.order,r),a=i.action===void 0?i:{...i,action:Zr(i.action)};return n.keybind===void 0?a:{...a,keybind:n.keybind}}function Zr(e){let t={};return e.inputSchema!==void 0&&(t.inputSchema=e.inputSchema),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),Object.freeze(t)}function Qr(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:In(r)}).then(e=>{n?e():r.push(e)},e=>{console.warn(`App command ${i.id} was not registered`,e)})}return()=>{if(!n){n=!0;for(let e of r.splice(0))e()}}}function $r(e,t){console.error(JSON.stringify({source:`agar`,operation:e,failureKind:t instanceof Error?`Error`:`NonErrorThrown`}),dt(t))}var ei=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 ti=globalThis[ei],ni=ti?ti.RpcTarget:class{},ri=async function(){}.constructor,ii=typeof Buffer<`u`?Buffer.prototype:void 0;function ai(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 ri.prototype:return`function`;case Array.prototype:return`array`;case Date.prototype:return`date`;case Uint8Array.prototype:case ii: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 hi.prototype:return`stub`;case W.prototype:return`rpc-promise`;default:if(ti){if(t==ti.RpcStub.prototype||e instanceof ti.ServiceStub)return`rpc-target`;if(t==ti.RpcPromise.prototype||t==ti.RpcProperty.prototype)return`rpc-thenable`}return e instanceof ni?`rpc-target`:e instanceof Error?`error`:`unsupported`}}function oi(){throw Error(`RPC map() implementation was not loaded.`)}var si={applyMap:oi,sendMap:oi};function ci(){throw Error(`Stream implementation was not loaded.`)}var H={createWritableStreamHook:ci,createWritableStreamFromHook:ci,createReadableStreamHook:ci},li=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}}},U=class extends li{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)}}},ui=new U(Error(`Attempted to use RPC stub after it has been disposed.`)),di=(e,t,n)=>e.call(t,n);function fi(e,t){let n=di;di=e;try{return t()}finally{di=n}}var pi=Symbol(`realStub`),mi={apply(e,t,n){let r=e.raw;return new W(di(r.hook,r.pathIfPromise||[],G.fromAppParams(n)),[])},get(e,t,n){let r=e.raw;if(t===pi)return r;if(t in W.prototype)return r[t];if(typeof t==`string`)return new W(r.hook,r.pathIfPromise?[...r.pathIfPromise,t]:[t]);if(t===Symbol.dispose&&(!r.pathIfPromise||r.pathIfPromise.length==0))return()=>{r.hook.dispose(),r.hook=ui}},has(e,t){let n=e.raw;return t===pi?!0:t in W.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.`)}},hi=class e extends ni{constructor(e,t){if(super(),!(e instanceof li)){let n=e;if(e=n instanceof ni||n instanceof Function?Ti.create(n,void 0):new K(G.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,mi)}hook;pathIfPromise;dup(){let t=this[pi];return t.pathIfPromise?new e(t.hook.get(t.pathIfPromise)):new e(t.hook.dup())}onRpcBroken(e){this[pi].hook.onBroken(e)}map(e){let{hook:t,pathIfPromise:n}=this[pi];return si.sendMap(t,n||[],e)}toString(){return`[object RpcStub]`}},W=class extends hi{constructor(e,t){if(e instanceof li)super(e,t??[]);else{if(t!==void 0)throw TypeError(`RpcPromise constructor expected one argument, received two.`);let n=ai(e);if(n===`rpc-promise`){let t=bi(e);if(t.pathIfPromise.length>0)super(t.hook,t.pathIfPromise);else{let e=t.hook;t.hook=ui,super(e,[])}}else if(n===`rpc-thenable`)super(Ti.create(e,void 0),[]);else{let t=new Ei(Promise.resolve(e).then(e=>new K(G.fromAppReturn(e))));t.ignoreUnhandledRejections(),super(t,[])}}}then(e,t){return xi(this).then(...arguments)}catch(e){return xi(this).catch(...arguments)}finally(e){return xi(this).finally(...arguments)}toString(){return`[object RpcPromise]`}};function gi(e){let{hook:t,pathIfPromise:n}=e[pi];return n&&n.length>0?t.get(n):t}function _i(e){let{hook:t,pathIfPromise:n}=e[pi];return n?t.get(n):t.dup()}function vi(e){let{hook:t,pathIfPromise:n}=e[pi];if(!(n&&n.length>0))return t}function yi(e){return e[pi].hook}function bi(e){return e[pi]}async function xi(e){let{hook:t,pathIfPromise:n}=e[pi];return n.length>0&&(t=t.get(n)),(await t.pull()).deliverResolve()}var G=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 Ti.create(e,t)}if(this.source===`return`){let r=this.rpcTargets?.get(e);return r?n?r.dup():(this.rpcTargets?.delete(e),r):(r=Ti.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 H.createWritableStreamHook(e);if(this.source===`return`){let t=this.rpcTargets?.get(e);return t?n?t.dup():(this.rpcTargets?.delete(e),t):(t=H.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 H.createReadableStreamHook(e);if(this.source===`return`){let t=this.rpcTargets?.get(e);return t?n?t.dup():(this.rpcTargets?.delete(e),t):(t=H.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(ai(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?_i(t):gi(t),t instanceof W){let e=new W(a,[]);return this.promises.push({parent:r,property:n,promise:e}),e}return this.hooks.push(a),new hi(a)}case`function`:case`rpc-target`:{let n=e,r;return r=a?a.getHookForRpcTarget(n,t,i):Ti.create(n,t),this.hooks.push(r),new hi(r)}case`rpc-thenable`:{let o=e,s;return s=a?new W(a.getHookForRpcTarget(o,t,i),[]):new W(Ti.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):H.createWritableStreamHook(n),this.hooks.push(r),n}case`readable`:{let n=e,r;return r=a?a.getHookForReadableStream(n,t,i):H.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 W)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=vi(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 W?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(ai(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=vi(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)):wi(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=H.createWritableStreamHook(t),n.dispose();return}case`readable`:{let t=e,n=this.rpcTargets?.get(t);n?this.rpcTargets.delete(t):n=H.createReadableStreamHook(t),n.dispose();return}default:return}}ignoreUnhandledRejections(){this.hooks?(this.hooks.forEach(e=>{e.ignoreUnhandledRejections()}),this.promises.forEach(e=>yi(e.promise).ignoreUnhandledRejections())):this.ignoreUnhandledRejectionsImpl(this.value)}ignoreUnhandledRejectionsImpl(e){switch(ai(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`:yi(e).ignoreUnhandledRejections();return;case`rpc-thenable`:e.then(e=>{},e=>{});return;default:return}}};function Si(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(ai(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}=bi(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 W){let{hook:t,pathIfPromise:n}=bi(e);return{hook:t,remainingPath:n||[]}}return{value:e,parent:t,owner:r}}var Ci=class extends li{call(e,t){let n;try{let{value:t,owner:r}=this.getValue();n=Si(t,void 0,e,r)}catch(e){return t.dispose(),new U(e)}return n.hook?n.hook.call(n.remainingPath,t):typeof n.value==`function`?new Ei(t.deliverCall(n.value,n.parent).then(e=>new K(e))):(t.dispose(),new U(TypeError(`'${e.join(`.`)}' is not a function.`)))}map(e,t,n){try{let r;try{let{value:t,owner:n}=this.getValue();r=Si(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):si.applyMap(r.value,r.parent,r.owner,t,n)}catch(e){return new U(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=Si(t,void 0,e,n);return r.hook?r.hook.get(r.remainingPath):new K(G.deepCopyFrom(r.value,r.parent,r.owner))}catch(e){return new U(e)}}},K=class e extends Ci{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(G.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 hi&&this.payload.value.onRpcBroken(e)}};function wi(e){if(Symbol.dispose in e)try{e[Symbol.dispose]()}catch(e){Promise.reject(e)}}var Ti=class e extends Ci{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=>G.fromAppReturn(e)):Promise.reject(Error(`Tried to resolve a non-promise stub.`))}ignoreUnhandledRejections(){}dispose(){this.target&&=(this.refcount&&--this.refcount.count==0&&wi(this.target),void 0)}onBroken(e){let t=this.target;t&&`then`in t&&Promise.resolve(t).then(()=>{},e)}},Ei=class e extends li{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)}},Di={maxBigIntDigits:16384,maxDepth:256,maxMessageSize:33554432},Oi=new Uint8Array(new Uint16Array([1]).buffer)[0]===1,ki=[`ArrayBuffer`,`DataView`,`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`Int16Array`,`Uint16Array`,`Int32Array`,`Uint32Array`,`BigInt64Array`,`BigUint64Array`,`Float32Array`,`Float64Array`];function Ai(e){return ki.includes(e)}var ji={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},Mi={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},Ni=new Map;for(let e of Object.keys(Mi))Ni.set(Mi[e],e);function Pi(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 Fi=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 Ii(e,t){let n=await new Response(e).blob();return n.type===t?n:n.slice(0,n.size,t)}var Li={__proto__:null,Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError},Ri=class e{exporter;source;encodingLevel;constructor(e,t,n){this.exporter=e,this.source=t,this.encodingLevel=n}static devaluate(t,n,r=Fi,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(ai(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=Ni.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=ji[t];!Oi&&i&&(n=n.slice(),Pi(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=H.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=H.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}=bi(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 Di}};function zi(e,t){return new W(new Ei(new Response(t).arrayBuffer().then(t=>{let n=new Uint8Array(t),r=new Request(e,{body:n});return new K(G.fromAppReturn(r))})),[])}function Bi(e,t){return new W(new Ei(Ii(e,t).then(e=>new K(G.fromAppReturn(e)))),[])}var Vi=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=G.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(!Ai(t[2])){let e=t[2].slice(0,64);throw TypeError(`Unknown bytes type marker: ${e}`)}let n=t[2],r=ji[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(!Oi&&r!==void 0&&Pi(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=Li[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=zi(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=Bi(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 W(e,[]);return this.promises.push({promise:t,parent:n,property:r}),t}return this.hooks.push(e),new W(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 W(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 W(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 hi(e)}}break;case`writable`:if(typeof t[1]==`number`){let e=this.importer.importStub(t[1]),n=H.createWritableStreamFromHook(e);return this.hooks.push(e),n}break;case`readable`:if(typeof t[1]==`number`){let e=this.importer.getPipeReadable(t[1]),n=H.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}},Hi=16,Ui=8,Wi=16,Gi=64;function Ki(e){return 2+e.length*3}function qi(e,t,n=0){if(n>=Gi)return Ui;switch(typeof e){case`string`:return Ki(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 Wi+e.byteLength;if(typeof Blob<`u`&&e instanceof Blob)return Wi+e.size;if(e instanceof Date)return 16;if(t??=new WeakSet,t.has(e))return Ui;if(t.add(e),e instanceof Array){let r=Hi;for(let i of e)r+=Ui+qi(i,t,n+1);return r}if(e instanceof Error){let r=Hi+Ki(e.name)+Ki(e.message)+Ki(e.stack??``);for(let i of Object.keys(e))r+=Ui+Ki(i)+qi(e[i],t,n+1);return r}let r=Hi;for(let i of Object.keys(e))r+=Ui+Ki(i)+qi(e[i],t,n+1);return r}default:return 16}}var Ji=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 U(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)}},Yi=class e extends li{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)}},Xi=class extends Yi{session;constructor(e){super(!1,e),this.session=e.session}dispose(){if(this.session){let e=this.session;this.session=void 0,e.shutdown()}}},Zi=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={...Di,...n.limits},this.exports.push({hook:t,refcount:1}),this.imports.push(new Ji(this,0,!1)),this.readLoop().catch(e=>this.abort(e))}getMainImport(){return new Xi(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,Ri.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 hi){let{hook:n,pathIfPromise:r}=bi(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=Ri.devaluate(t.value,void 0,this,t,this.encodingLevel);this.send([`resolve`,e,n]),r&&this.releaseExport(e,1)},t=>{this.send([`reject`,e,Ri.devaluate(t,void 0,this,void 0,this.encodingLevel)]),r&&this.releaseExport(e,1)}).catch(t=>{try{this.send([`reject`,e,Ri.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 Yi&&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 Ji(this,e,!1),this.imports[e]=t),new Yi(!1,t)}importPromise(e){if(this.abortReason)throw this.abortReason;if(this.imports[e])return new U(Error(`Bug in RPC system: The peer sent a promise reusing an existing export ID.`));let t=new Ji(this,e,!0);return this.imports[e]=t,new Yi(!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 Ji(this,n,!1);this.imports.push(r);let i=new Yi(!1,r),a=H.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=Ri.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 Ji(this,this.imports.length,!1);return this.imports.push(i),new Yi(!0,i)}sendStream(e,t,n){if(this.abortReason)throw n.dispose(),this.abortReason;let r=[`pipeline`,e,t],i;try{i=Ri.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=qi(a));let s=this.imports.length,c=new Ji(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 Ji(this,this.imports.length,!1);return this.imports.push(a),new Yi(!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`,Ri.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 K(new Vi(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 K(new Vi(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=H.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 K(new Vi(this,this.encodingLevel).evaluate(n[2])));else{let e=new Vi(this,this.encodingLevel).evaluate(n[2]);e.dispose(),t.resolve(new U(e.value))}}else n[0]==`resolve`&&new Vi(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 Vi(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}},Qi=class{#e;#t;constructor(e,t,n={}){let r;r=t?new K(G.fromAppReturn(t)):new U(Error(`This connection has no main object.`)),this.#e=new Zi(e,r,n),this.#t=new hi(this.#e.getMainImport())}getRemoteMain(){return this.#t}getStats(){return this.#e.getStats()}drain(){return this.#e.drain()}};function $i(e,t,n){return new Qi(new ea(e),t,n).getRemoteMain()}var ea=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))}},ta,na=class{context;captureMap=new Map;instructions=[];constructor(e,t){this.context=ta?{parent:ta,captures:[],subject:ta.capture(e),path:t}:{parent:void 0,captures:[],subject:e,path:t},ta=this}unregister(){ta=this.context.parent}makeInput(){return new ia(this,0)}makeOutput(e){let t;try{t=Ri.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 ia(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=Ri.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 ia(this,this.instructions.length)}pushGet(e,t){let n=this.capture(e.dup());return this.instructions.push([`pipeline`,n,t]),new ia(this,this.instructions.length)}capture(e){if(e instanceof ia&&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){}};si.sendMap=(e,t,n)=>{let r=new na(e,t),i;try{i=G.fromAppReturn(fi(r.pushCall.bind(r),()=>n(new W(r.makeInput(),[]))))}finally{r.unregister()}if(i instanceof Promise)throw i.catch(e=>{}),Error(`RPC map() callbacks cannot be async.`);return new W(r.makeOutput(i),[])};function ra(){throw Error(`Attempted to use an abstract placeholder from a mapper function. Please make sure your map function has no side effects.`)}var ia=class extends li{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(ta)return ta.pushGet(this,e);ra()}call(e,t){t.dispose(),ra()}map(e,t,n){for(let e of t)e.dispose();ra()}pull(){ra()}ignoreUnhandledRejections(){}onBroken(e){ra()}},aa=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 Vi(this).evaluateCopy(t);if(e.value instanceof hi){let t=vi(e.value);if(t){this.variables.push(t);continue}}this.variables.push(new K(e))}return new Vi(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 Di}};function oa(e,t,n,r,i){let a=new aa(r,new K(G.deepCopyFrom(e,t,n)));try{return a.apply(i)}finally{a.dispose()}}si.applyMap=(e,t,n,r,i)=>{try{let a;if(e instanceof W)throw Error(`applyMap() can't be called on RpcPromise`);if(e instanceof Array){let t=[];try{for(let a of e)t.push(oa(a,e,n,r,i))}catch(e){for(let e of t)e.dispose();throw e}a=G.fromArray(t)}else a=e==null?G.fromAppReturn(e):oa(e,t,n,r,i);return new K(a)}finally{for(let e of r)e.dispose()}};var sa=class e extends li{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 Ei((r===`write`?t.deliverStreamWrite(n.writer):t.deliverCall(n.writer[r],n.writer)).then(e=>new K(e)))}catch(e){return t.dispose(),new U(e)}}map(e,t,n){for(let e of t)e.dispose();return new U(Error(`Cannot use map() on a WritableStream`))}get(e){return new U(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)}},ca=262144,la=1073741824,ua=65536,da=2,fa=1.25,pa=.9,ma=3,ha=class{now;window=ca;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?da:fa,s=a*this.minRtt*o;s=Math.min(s,e.windowAtSend*o),s=e.windowFullAtSend?Math.max(s,e.windowAtSend*pa):Math.max(s,this.window),this.window=Math.max(Math.min(s,la),ua),this.inStartupPhase&&e.sentTime>=this.roundStartTime&&(this.window>this.lastRoundWindow*fa?this.roundsWithoutIncrease=0:++this.roundsWithoutIncrease>=ma&&(this.inStartupPhase=!1),this.roundStartTime=t,this.lastRoundWindow=this.window)}return this.bytesInFlight<this.window}};function ga(e){let t,n=!1,r=new ha(()=>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=G.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`],G.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`],G.fromAppParams([n]));r.then(()=>o(),()=>o())}})}var _a=class e extends li{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 U(Error(`Cannot call methods on a ReadableStream stub`))}map(e,t,n){for(let e of t)e.dispose();return new U(Error(`Cannot use map() on a ReadableStream`))}get(e){return new U(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){}};H.createWritableStreamHook=sa.create,H.createWritableStreamFromHook=ga,H.createReadableStreamHook=_a.create;var va=hi,ya=ni,ba=$i;function xa(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 Sa(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 Ca(e,t){if(t.kind===`action`){let n=[...e.primary??[],...e.menu??[]].find(e=>e.id===t.actionId);return n!==void 0&&n.disabled!==!0}let n=e.crumbs?.find(e=>e.id===t.crumbId);return n===void 0?!1:t.siblingId===void 0||n.siblings?.some(e=>e.id===t.siblingId)===!0}var wa=`fungi.app.ready`,Ta=`fungi.app.connect`,q=e=>g.pipe(T(rt(1)),T(k(e))),Ea=e=>_(q(e)),Da=x.pipe(T(_e()),T(tt(Number.isSafeInteger,{message:`Expected a safe integer`}))),Oa=Da.pipe(T(Ne(0))),ka=Da.pipe(T(Fe(0))),Aa=t({appId:q(160),releaseId:q(160),surfaceId:q(160)}),ja=t({editing:b,surface:D([q(160),p])}),Ma=D([t({kind:u(`compose`),requestId:q(160),text:q(2e3)}),t({kind:u(`navigate`),requestId:q(160),params:d(t({key:q(64),value:q(4096)})).pipe(T(k(16)))})]),J=i(h([`granted`,`missing`])),Na=t({"agent.list":J,"agent.manage":J,"agent.read":J,"agent.send":J,"computer.list":J,"computer.readFile":J,"computer.writeFile":J,"computer.execute":J,"git.repository":J,"workflow.publish":J,"workflow.arm":J,"workflow.run":J,"app.events.emit":J,"llm.generation":J,"media.generation":J,"media.share":J}),Pa=h([`ready`,`missing`,`unknown`]),Fa=t({models:Pa,media:Pa,git:Pa,terminal:h([`ready`,`exec-only`,`missing`,`unknown`]),terminalReason:_(g)}),Ia=h([`model`,`media`,`git`,`computer`]),La=h([`opened`,`unavailable`]),Ra=t({computerId:D([q(256),p]),teamHasComputers:_(he(b)),computerAccessGranted:_(b),setup:_(Fa),permissions:_(Na),focus:ja,openRequest:D([p,Ma]),visibility:h([`visible`,`hidden`])}),za=h([`connecting`,`connected`,`suspended`,`disconnected`,`disposing`,`disposed`]),Ba=t({altKey:b,ctrlKey:b,id:q(160),key:q(64),metaKey:b,shiftKey:b}),Va=t({action:_(w),availability:_(w),category:q(160),description:Ea(512),id:q(160),projections:_(w),title:q(160)}),Ha=t({arguments:_(w),commandId:q(321),origin:h([`agent`,`browser`,`keyboard`,`menu`,`palette`,`programmatic`,`slash`,`terminal`]),requestId:q(160)}),Ua=D([t({result:_(w),status:u(`handled`)}),t({error:w,status:u(`failed`)})]),Wa=e=>q(e).pipe(T(tt(e=>{for(let t=0;t<e.length;t+=1)if(xa(e.charCodeAt(t)))return!1;return!0},{message:`Expected one line of plain text`}))),Ga={id:q(64),text:Wa(80),end:i(b),priority:i(u(`low`))},Ka=i(x.pipe(T(_e()),T(Ve({minimum:0,maximum:9999})))),qa=d(D([t({...Ga,kind:u(`text`),tone:i(h([`neutral`,`success`,`warning`,`error`]))}),t({...Ga,kind:u(`button`),icon:i(h([`folder`,`ports`,`processes`,`access`])),count:Ka,tone:i(h([`neutral`,`success`,`warning`,`error`])),busy:i(b),title:i(Wa(1024)),disabled:i(b),opens:i(u(`dialog`)),expanded:i(b)}),t({...Ga,kind:u(`toggle`),pressed:b}),t({...Ga,kind:u(`menu`),count:Ka,title:i(Wa(1024)),options:d(t({id:q(64),text:Wa(80),checked:i(b),disabled:i(b)})).pipe(T(k(16)),T(tt(e=>new Set(e.map(e=>e.id)).size===e.length,{message:`Expected unique status option ids`})))})])).pipe(T(k(6)),T(tt(e=>new Set(e.map(e=>e.id)).size===e.length,{message:`Expected unique status item ids`}))),Ja=t({computerId:q(256),path:q(1024)}),Ya=q(80).pipe(T(tt(e=>e.trim()===e,{message:`Expected a trimmed title`}))),Xa=q(64),Za=q(80),Qa=e=>new Set(e.map(e=>e.id)).size===e.length,$a=t({id:Xa,label:Za,siblings:_(d(t({id:Xa,label:Za})).pipe(T(k(16)),T(tt(Qa,{message:`Expected unique crumb sibling ids`}))))}),eo=t({id:Xa,label:Za,icon:_(u(`play`)),variant:_(h([`primary`,`outline`,`ghost`])),tone:_(u(`destructive`)),disabled:_(b)}),to=e=>d(eo).pipe(T(k(e)),T(tt(Qa,{message:`Expected unique header command ids`}))),no=t({id:Xa,label:Za,presentation:_(u(`bead`)),tone:_(h([`neutral`,`info`,`warning`,`success`,`error`]))}),ro={status:_(d(no).pipe(T(k(4)),T(tt(Qa,{message:`Expected unique header status ids`})))),crumbs:_(d($a).pipe(T(k(8)),T(tt(Qa,{message:`Expected unique crumb ids`})))),primary:_(to(3)),menu:_(to(12))},io=t({contractVersion:u(1),canGoBack:b,title:_(Ya),...ro}),ao=t({canGoBack:b,title:_(g),...ro}),oo=D([t({kind:u(`crumb`),crumbId:Xa,siblingId:_(Xa)}),t({kind:u(`action`),actionId:Xa})]),so=he(t({agentId:q(256),sessionId:q(256)})),co=e=>_(d(h(e)).pipe(T(k(e.length)))),lo=t({agents:_(d(h([`agent.list`,`agent.manage`,`agent.read`,`agent.send`])).pipe(T(k(4)))),computers:_(d(h([`computer.list`,`computer.readFile`,`computer.writeFile`,`computer.execute`])).pipe(T(k(4)))),git:co([`git.repository`]),workflows:co([`workflow.publish`,`workflow.arm`,`workflow.run`]),events:co([`app.events.emit`]),generation:co([`llm.generation`,`media.generation`,`media.share`])}),uo=h([`granted`,`declined`,`customize`]),fo=t({message:q(512),tone:_(h([`info`,`success`,`warning`,`error`]))}),po=h(fe);t({code:po.pick([`DELIVERY_PENDING`])});var mo=t({code:po,message:q(512),retryable:b,need:i(te)}),ho=t({protocolVersion:u(2),type:u(wa)}),go=t({epoch:q(160),protocolVersion:u(2),type:u(Ta)}),_o=t({epoch:q(160),protocolVersion:u(2)}),vo={[Symbol.dispose]:_(w)},yo=D([t({...vo,ok:u(!0),value:w}),t({...vo,error:mo,ok:u(!1)})]);function Y(e,t,n=`PROTOCOL`){return We(ze(e,{onExcessProperty:`error`}),ot({onFailure:e=>{throw new y(`The peer sent malformed protocol data`,{cause:e,code:n,retryable:!1})},onSuccess:t}))}function X(e){return Object.freeze(e)}function bo(e,t){let n=e.arguments===void 0?void 0:In(e.arguments),r={origin:e.origin,signal:t};return n!==void 0&&Object.assign(r,{arguments:n}),X(r)}var xo=Y(Va,e=>{let t={category:e.category,id:e.id,title:e.title};return e.action!==void 0&&Object.assign(t,{action:e.action}),e.availability!==void 0&&Object.assign(t,{availability:e.availability}),e.description!==void 0&&Object.assign(t,{description:e.description}),e.projections!==void 0&&Object.assign(t,{projections:e.projections}),X(fs(()=>Jn(t)))},`INVALID_ARGUMENT`),So=Y(q(321),e=>e),Co=Y(Ha,e=>{let t=e.arguments===void 0?void 0:In(e.arguments),n={commandId:e.commandId,origin:e.origin,requestId:e.requestId};return t!==void 0&&Object.assign(n,{arguments:t}),X(n)}),wo=Y(D([Ge,w]),e=>e===void 0?void 0:In(e)),To=Y(go,e=>X(e));Y(_o,e=>X(e));var Eo=Y(Ra,e=>{let t={computerId:e.computerId,focus:X({...e.focus}),openRequest:e.openRequest===null?null:X({...e.openRequest}),visibility:e.visibility};return e.teamHasComputers!==void 0&&(t.teamHasComputers=e.teamHasComputers),e.computerAccessGranted!==void 0&&(t.computerAccessGranted=e.computerAccessGranted),e.setup!==void 0&&(t.setup=X({...e.setup})),e.permissions!==void 0&&(t.permissions=X({...e.permissions})),X(t)}),Do=Y(mo,e=>X({...e})),Oo=Y(ja,e=>X({...e}),`INVALID_ARGUMENT`),ko=Y(Aa,e=>X({...e})),Ao=Y(za,e=>e),jo=Y(qa,e=>X(e.map(e=>e.kind===`menu`?X({...e,options:X(e.options.map(e=>X(e)))}):X(e))),`INVALID_ARGUMENT`),Mo=Y(t({itemId:q(64),optionId:i(q(64)),anchor:i(t({start:x.pipe(T(Ve({minimum:0,maximum:1e5}))),width:x.pipe(T(Ve({minimum:0,maximum:1e5})))}))}),e=>X(e.anchor===void 0?{...e}:{...e,anchor:X({...e.anchor})}),`INVALID_ARGUMENT`),No=Y(Ja,e=>X({...e}),`INVALID_ARGUMENT`);function Po(e){let t={id:e.id,label:e.label};return e.presentation!==void 0&&(t={...t,presentation:e.presentation}),e.tone!==void 0&&(t={...t,tone:e.tone}),X(t)}function Fo(e){let t={id:e.id,label:e.label};return e.siblings===void 0?X(t):X({...t,siblings:X(e.siblings.map(e=>X({...e})))})}function Io(e){let t={id:e.id,label:e.label};return e.icon!==void 0&&(t={...t,icon:e.icon}),e.variant!==void 0&&(t={...t,variant:e.variant}),e.tone!==void 0&&(t={...t,tone:e.tone}),e.disabled!==void 0&&(t={...t,disabled:e.disabled}),X(t)}function Lo(e){let t={canGoBack:e.canGoBack};return e.title!==void 0&&(t={...t,title:e.title}),e.crumbs!==void 0&&(t={...t,crumbs:X(e.crumbs.map(Fo))}),e.primary!==void 0&&(t={...t,primary:X(e.primary.map(Io))}),e.menu!==void 0&&(t={...t,menu:X(e.menu.map(Io))}),e.status!==void 0&&(t={...t,status:X(e.status.map(Po))}),X(t)}var Ro=Y(io,Lo,`INVALID_ARGUMENT`),zo=Y(ao,e=>{let t=e.title?.trim();return Bo({...Lo({...e,title:t===void 0||t.length===0?void 0:t}),contractVersion:1})},`INVALID_ARGUMENT`),Bo=Y(io,e=>X({...Lo(e),contractVersion:1}),`INVALID_ARGUMENT`),Vo=Y(oo,e=>e.kind===`action`?X({...e}):X(e.siblingId===void 0?{kind:e.kind,crumbId:e.crumbId}:e),`INVALID_ARGUMENT`),Ho=Y(so,e=>e===null?null:X({...e}),`INVALID_ARGUMENT`),Uo=Y(lo,e=>X({agents:X([...new Set(e.agents??[])]),computers:X([...new Set(e.computers??[])]),...e.git&&{git:X([...new Set(e.git)])},...e.workflows&&{workflows:X([...new Set(e.workflows)])},...e.events&&{events:X([...new Set(e.events)])},...e.generation&&{generation:X([...new Set(e.generation)])}}),`INVALID_ARGUMENT`),Wo=Y(Ia,e=>e,`INVALID_ARGUMENT`);Y(ho,e=>X(e));var Go=Y(q(512),e=>e),Ko=Y(fo,e=>X({...e}),`INVALID_ARGUMENT`);Y(t({id:q(160),repeat:b}),e=>X(e));var qo=Y(d(Ba).pipe(T(k(64))),e=>{if(new Set(e.map(e=>e.id)).size!==e.length)throw new y(`Reserved chords are invalid`,{code:`PROTOCOL`,retryable:!1});return X(e.map(e=>X({...e})))});function Jo(e){return Y(t({value:w,version:Oa}),t=>X({value:e(t.value),version:t.version}))}var Yo=Jo(Eo),Xo=Y(t({capabilities:d(w).pipe(T(k(128))),context:w}),e=>X({capabilities:X(e.capabilities.map(e=>ns(e))),context:Yo(e.context)})),Zo=Jo(Ao),Qo=Jo(qo),$o=Jo(Go),es=We(Zo,e=>{if(e.value!==`connected`&&e.value!==`suspended`)throw new y(`The host lifecycle is invalid`,{code:`PROTOCOL`,retryable:!1});return X({value:e.value,version:e.version})});function ts(e){return Y(t({handle:w,id:q(160),version:ka}),t=>{if(!(t.handle instanceof va)&&!(e&&t.handle instanceof ya))throw new y(`A capability handle is invalid`,{code:`PROTOCOL`,retryable:!1});return X({handle:t.handle,id:t.id,version:t.version})})}var ns=ts(!1),rs=ts(!0);function is(e){let n=e?rs:ns;return Y(t({capabilities:d(w).pipe(T(k(128))),context:w,identity:w,lifecycle:w,reservedChords:w,theme:w}),e=>X({capabilities:X(e.capabilities.map(e=>n(e))),context:Yo(e.context),identity:ko(e.identity),lifecycle:es(e.lifecycle),reservedChords:Qo(e.reservedChords),theme:$o(e.theme)}))}var as=is(!1);is(!0);function os(e){return Y(yo,t=>t.ok?X({ok:!0,value:e(t.value)}):X({ok:!1,error:Do(t.error)}))}var ss=os(as),cs=os(Y(t({commandId:q(321)}),e=>X(e)));os(Y(Ua,e=>{if(e.status===`failed`)return X({status:`failed`,error:fs(()=>Rn(e.error))});let t=e.result===void 0?void 0:In(e.result);return X(t===void 0?{status:`handled`}:{status:`handled`,result:t})}));var ls=os(Y(Ge,()=>void 0)),us=os(Y(uo,e=>e)),ds=os(Y(La,e=>e));os(Y(b,e=>e)),os(Y(b,e=>e));function fs(e){try{return e()}catch(e){throw new y(`The command metadata is invalid`,{cause:e,code:`INVALID_ARGUMENT`,retryable:!1})}}var ps=D([t({kind:u(`saveFile`),name:q(255).pipe(T(xe(/^[^\p{Cc}/\\]+$/u))),mime:q(255),bytes:Ze}),t({kind:u(`copyText`),text:g})]);function ms(e){let t=ze(ps,{onExcessProperty:`error`})(e);if(ae(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 hs=os(Y(D([t({kind:u(`saved`)}),t({kind:u(`copied`)}),t({kind:u(`refused`),reason:h([`no-user-gesture`,`too-large`,`invalid-request`,`unavailable`,`denied`,`busy`])})]),e=>X(e)));function gs(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 _s(e){let t=new Map,n=gs(0),r=!1,i=e=>{let t=new Map;try{for(let n of e){let e=ns(n),r=xs(e.id,e.version);if(t.has(r))throw ys(e.handle),new y(`Duplicate capability grant`,{code:`PROTOCOL`,retryable:!1});t.set(r,e.handle)}}catch(e){for(let e of t.values())ys(e);throw e}return t};for(let[n,r]of i(e))t.set(n,r);let a=e=>{for(let t of e)ys(t)},o=e=>{if(r)throw new y(`The app connection is disposed`,{code:`DISCONNECTED`,retryable:!0});let n=xs(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 y(`The capability is not granted`,{code:`CAPABILITY_DENIED`,retryable:!1});try{return e.schema.parse(t)}catch(e){throw new y(`The capability interface is malformed`,{cause:e,code:`PROTOCOL`,retryable:!1})}}}),replace(e){if(r)throw new y(`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 vs=M().transform(e=>{let n=Ee(Object).safeParse(e);if(!n.success)return;let r=Object.create(n.data),i=O(t({[Symbol.dispose]:_(je(Function))}))(r);return{owner:n.data,dispose:i[Symbol.dispose]}});function ys(e){try{let t=vs.parse(e);if(t===void 0||bs.has(t.owner))return;bs.add(t.owner),t.dispose?.call(t.owner)}catch(e){console.warn(`RPC value disposal failed`,e)}}var bs=new WeakSet;function xs(e,t){return`${e}@${String(t)}`}function Ss(e){let t=(0,N.useCallback)(t=>e?.subscribe(t)??(()=>void 0),[e]),n=(0,N.useCallback)(()=>e?.get(),[e]);return(0,N.useSyncExternalStore)(t,n,n)}function Cs(e){return Ss(e?.context)??null}function ws(e){return Cs(e)?.computerId??null}function Ts(e,t,n,r){let i=(0,N.useRef)(t);i.current=t;let a=(0,N.useRef)(n);a.current=n;let o=(0,N.useRef)(r);o.current=r;let s=JSON.stringify(t),c=n!==void 0;(0,N.useEffect)(()=>{e&&e.ui.reportStatus(i.current).catch(e=>{o.current?o.current(e):console.error(`Window status report failed`,e)})},[e,s]),(0,N.useEffect)(()=>{if(!(!e||!c))return e.ui.onStatusAction(e=>a.current?.(e)??!1)},[e,c]),(0,N.useEffect)(()=>()=>{e?.ui.reportStatus([]).catch(e=>{console.error(`Window status report failed`,e)})},[e])}function Es(e,{sourceId:t,namespace:n},r){let i=(0,N.useMemo)(()=>ar(),[]),a=(0,N.useMemo)(r,[r]);return(0,N.useEffect)(()=>{let e=i.contribute({sourceId:t,namespace:n,commands:a});return()=>{e.dispose()}},[i,t,n,a]),(0,N.useEffect)(()=>e?Qr(e.commands,a):void 0,[e,a]),i}function Ds(e,{canGoBack:t,title:n,crumbs:r,primary:i,menu:a,status:o,onBack:s,onCrumb:c,onAction:l}){let u=(0,N.useRef)(s),d=(0,N.useRef)(c),f=(0,N.useRef)(l);(0,N.useEffect)(()=>{u.current=s,d.current=c,f.current=l},[s,c,l]),(0,N.useEffect)(()=>{if(!e)return;let t=e.onBack(()=>u.current()),n=e.onActivate(e=>{if(e.kind===`action`){let t=f.current;return t?.(e.actionId),t!==void 0}let t=d.current;return e.siblingId===void 0?t?.(e.crumbId):t?.(e.crumbId,e.siblingId),t!==void 0});return()=>{t(),n(),Os(e,{canGoBack:!1})}},[e]);let ee=JSON.stringify([r,i,a,o]),p=(0,N.useRef)({crumbs:r,primary:i,menu:a,status:o});(0,N.useEffect)(()=>{p.current={crumbs:r,primary:i,menu:a,status:o}},[r,i,a,o]),(0,N.useEffect)(()=>{if(!e)return;let r={canGoBack:t};n!==void 0&&(r={...r,title:n});let i=p.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}),Os(e,r)},[e,t,n,ee])}function Os(e,t){e.publish(t).catch(e=>{e instanceof y&&e.code===`DISCONNECTED`||console.warn(`App navigation report failed`,e)})}var ks=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 As(e,t,n){return new ks(e,t,n)}function js(e){let t=j(e),n=Ee(Object),r=j(Object.fromEntries(Object.keys(e).map(e=>[e,M().optional()])));return M().transform(e=>{let i=n.parse(e),a=Object.create(i),o=r.parse(a),s=Object.fromEntries(Object.entries(o).map(([e,t])=>[e,Xe().parse(t).bind(i)]));return{...t.parse(s),[Symbol.dispose](){ys(e)}}})}function Z(e){return M().transform(t=>{try{return e.parse(t)}catch(e){throw e instanceof y?e:new y(`The capability returned malformed data`,{cause:e,code:`PROTOCOL`,retryable:!1})}finally{ys(t)}})}function Q(e){return Xe({output:at(M().transform(t=>{try{return e.parse(t)}catch(e){throw ys(t),e instanceof y?e:new y(`The capability returned a malformed result`,{cause:e,code:`PROTOCOL`,retryable:!1})}}))})}var Ms=Q(Z(Be()));js({fetch:Q(Ee(Response)),close:Ms});function Ns(e){return e instanceof y?e:new y(`App operation failed`,{cause:e,code:`HOST_FAILURE`,retryable:!1})}var Ps=new WeakMap,Fs={of(e,...t){return[e?.identity.surfaceId??null,e?.context.get().computerId??null,...t]}};function Is(e){let t={};return e&&Ps.set(t,e),t}function Ls(){let e=new yn({defaultOptions:{queries:{retry:!1,staleTime:3e4,refetchOnWindowFocus:!1},mutations:{retry:!1}}}),t=new Map;return e.getQueryCache().subscribe(n=>{let r=n.query;if(n.type===`removed`){t.get(r.queryHash)?.release(),t.delete(r.queryHash);return}let i=r.meta&&Ps.get(r.meta),a=t.get(r.queryHash);if(a?.app===i||(a?.release(),t.delete(r.queryHash),!i))return;let o=()=>{queueMicrotask(()=>{e.getQueryCache().get(r.queryHash)===r&&t.get(r.queryHash)?.app===i&&e.resetQueries({predicate:e=>e===r})})},s=i.capabilities.subscribe(o);t.set(r.queryHash,{app:i,release:s}),a&&o()}),e}function Rs(e,t,n,r){let i=e?.context.get().computerId;return jn({queryKey:n,meta:Is(e),enabled:e!==null,retry:!1,queryFn:async({signal:n})=>{try{if(!e)throw new y(`No App connection`,{code:`DISCONNECTED`,retryable:!0});if(e.context.get().computerId!==i)throw new y(`The selected Computer changed`,{code:`SELECTION_CHANGED`,retryable:!1});return await r(e.capabilities.require(t),n)}catch(e){throw Ns(e)}}})}var zs=we(De(t({error:u(`too_large`)})));async function Bs(e,t){let n,r=()=>n??=e.close(),i=()=>{r().catch(e=>{$r(`files.read.abort-close`,e)})};t.signal?.addEventListener(`abort`,i,{once:!0});try{t.signal?.throwIfAborted();let n=await e.response();try{let e=O(je(Response))(n);if(e.status===413){let t=zs(await e.text());throw new y(`App file exceeds the read bound`,{code:t._tag===`Some`?`FILE_TOO_LARGE`:`PROTOCOL`,retryable:!1})}if(!e.ok)throw Error(`App file unavailable (${String(e.status)})`);let r=await e.blob();return t.signal?.throwIfAborted(),new File([r],t.name,{type:r.type,lastModified:0})}finally{ys(n)}}finally{t.signal?.removeEventListener(`abort`,i);try{await r()}finally{e[Symbol.dispose]()}}}async function Vs(e,t,n){let r,i=()=>r??=e.close(),a=()=>{i().catch(e=>{$r(`files.write.abort-close`,e)})};n.signal?.addEventListener(`abort`,a,{once:!0});try{n.signal?.throwIfAborted(),await e.write(t.stream())}finally{n.signal?.removeEventListener(`abort`,a);try{await i()}catch(e){$r(`files.write.remote-close`,e)}try{e[Symbol.dispose]()}catch(e){$r(`files.write.local-dispose`,e)}}}var Hs=t({path:g,entries:d(t({name:g,type:h([`file`,`directory`,`symlink`]),size:x,modifiedAt:x})),nextOffset:he(x)}),Us=As(`computer.list`,1,C(()=>js({list:Q(Z(M().transform(e=>O(Hs)(e))))}))),Ws=D([t({state:h([`running`,`sleeping`,`starting`,`start_failed`])}),t({state:u(`queued`),position:x.pipe(T(_e()),T(Fe(0)))})]),Gs=t({enabled:b,effective:b,blockedBy:he(h([`team`,`global`]))}),Ks=t({computerId:Je,name:Je,runtime:Ws,backends:d(t({id:Je,kind:h([`platform-container`,`on-box-vm`,`local`]),status:h([`ready`,`queued`,`online`,`offline`]),queuePosition:he(x.pipe(T(_e()),T(Fe(0)))),hostId:he(g),hostLabel:he(g),folderLabel:he(g),detachable:b})),internet:Gs});As(`computer.instrument.read`,1,C(()=>js({read:Q(Z(M().transform(e=>O(Ks)(e))))}))),As(`computer.instrument.control`,1,C(()=>js({start:Q(Z(M().transform(e=>O(Ws)(e)))),setInternetAccess:Q(Z(M().transform(e=>O(Gs)(e)))),detachLocal:Q(Z(M().transform(e=>O(t({detached:b}))(e))))})));var qs=t({ports:d(t({port:x.pipe(T(_e()),T(Ve({minimum:1,maximum:65535}))),previewUrl:Je,openMode:h([`inline`,`external-only`]),expiresAt:x.pipe(T(_e()),T(Fe(0)))})).pipe(T(k(64)))}),Js=D([qs,t({error:u(`port_previews_not_configured`)})]),Ys=t({port:x.annotate({message:`Use a port from 1 to 65535.`}).check(_e({message:`Use a port from 1 to 65535.`}),Ve({minimum:1,maximum:65535},{message:`Use a port from 1 to 65535.`})),exposed:b}),Xs=t({port:x.pipe(T(_e()),T(Ve({minimum:1,maximum:65535}))),removed:b});As(`computer.ports`,2,C(()=>js({list:Q(Z(M().transform(e=>O(Js)(e)))),expose:Q(Z(M().transform(e=>O(Ys)(e)))),unexpose:Q(Z(M().transform(e=>O(Xs)(e))))})));var Zs=h([`synced`,`pending`,`unknown`]),Qs=t({port:he(Ys.fields.port),id:Je,command:Je,cwd:he(g),startedAt:x.pipe(T(_e()),T(Ne(0))),state:h([`running`,`exited`,`uncertain`]),exitCode:he(x.pipe(T(_e()))),sync:Zs,endedAt:he(x.pipe(T(_e()),T(Ne(0))))}),$s=t({processes:d(Qs)}),ec=t({process:Qs,signalled:b}),tc=t({process:Qs,lines:d(g.pipe(T(k(2e3)))).pipe(T(k(200))),truncated:b});t({requestId:Je.pipe(T(k(256))),command:Je.pipe(T(k(16384))),cwd:i(g),port:i(Ys.fields.port)}),As(`computer.processes`,1,C(()=>js({start:Q(Z(M().transform(e=>O(Qs)(e)))),list:Q(Z(M().transform(e=>O($s)(e)))),kill:Q(Z(M().transform(e=>O(ec)(e)))),logs:Q(Z(M().transform(e=>O(tc)(e))))})));var nc=As(`computer.readFile`,1,C(()=>js({open:Q(js({response:Q(Ee(Response)),close:Ms}))})));async function rc(e,t,n){return await Bs(await e.require(nc).open(t),{...n,name:t.path.split(`/`).at(-1)??`file`})}async function ic(e,t){return O(Hs)(await e.require(Us).list(t))}var ac=As(`computer.writeFile`,3,C(()=>js({open:Q(js({write:Ms,close:Ms})),mkdir:Ms,replace:Q(Z(M().transform(e=>O(oc)(e))))}))),oc=D([t({kind:u(`replaced`),path:Je,bytes:x.pipe(T(_e()),T(Ne(0)))}),t({kind:u(`conflict`)})]);async function sc(e,t,n){n.signal?.throwIfAborted();let r=await e.require(ac).replace(t);if(r.kind===`conflict`)throw new y(`Computer file changed since it was opened`,{code:`CONFLICT`,retryable:!1});return{path:r.path,bytes:r.bytes}}var cc=t({computerName:Je.pipe(T(k(256))),teamName:Je.pipe(T(k(256))),modelDoor:Je.pipe(T(k(256))),uptimeSeconds:x.pipe(T(_e()),T(Ne(0))),version:Je.pipe(T(k(64)))});As(`computer.terminal`,2,C(()=>js({open:Q(js({information:Q(Z(M().transform(e=>O(cc)(e)))),output:Q(Ee(ReadableStream).transform(e=>e.pipeThrough(new TransformStream({transform(e,t){t.enqueue(Ee(Uint8Array).parse(e))}})))),input:Q(Ee(WritableStream)),resize:Ms,close:Ms}))})));async function lc(e,t,n){await Vs(await e.require(ac).open({path:t.path}),t.content,n)}var $=ie*10,uc=class{constructor(e={}){let t=!se(e.bounce)||!se(e.duration);this.timeStep=.02,this.restThreshold=5e-4,this.restDuration=200,this.maxDuration=6e4,this.maxRestSteps=this.restDuration/this.timeStep/ie,this.maxIterations=this.maxDuration/this.timeStep/ie,this.bn=A(He(e.bounce,.5),-1,1),this.pd=A(He(e.duration,628),10*s.timeScale,$*s.timeScale),this.m=A(He(e.mass,1),1,$),this.s=A(He(e.stiffness,100),Re,$),this.d=A(He(e.damping,10),Re,$),this.v=A(He(e.velocity,0),-$,$),this.w0=0,this.zeta=0,this.wd=0,this.b=0,this.completed=!1,this.solverDuration=0,this.settlingDuration=0,this.parent=null,this.onComplete=e.onComplete||n,t&&this.calculateSDFromBD(),this.compute(),this.ease=e=>{let t=e*this.settlingDuration,n=this.completed,r=this.pd;return t>=r&&!n&&(this.completed=!0,this.onComplete(this.parent)),t<r&&n&&(this.completed=!1),e===0||e===1?e:this.solve(e*this.solverDuration)}}solve(e){let{zeta:t,w0:n,wd:r,b:i}=this,a=e;return a=t<1?Se(-a*t*n)*(1*it(r*a)+i*ce(r*a)):t===1?(1+i*a)*Se(-a*n):((1+i)*Se((-t*n+r)*a)+(1-i)*Se((-t*n-r)*a))/2,1-a}calculateSDFromBD(){let e=s.timeScale===1?this.pd/ie:this.pd;this.m=1,this.v=0,this.s=a(2*Ie/e,2),this.d=this.bn>=0?(1-this.bn)*4*Ie/e:4*Ie/(e*(1+this.bn)),this.s=et(A(this.s,Re,$),3),this.d=et(A(this.d,Re,300),3)}calculateBDFromSD(){let e=2*Ie/c(this.s);this.pd=e*(s.timeScale===1?ie:1),this.bn=this.d/(2*c(this.s))<=1?1-this.d*e/(4*Ie):4*Ie/(this.d*e)-1,this.bn=et(A(this.bn,-1,1),3),this.pd=et(A(this.pd,10*s.timeScale,$*s.timeScale),3)}compute(){let{maxRestSteps:e,maxIterations:t,restThreshold:n,timeStep:r,m:i,d:a,s:o,v:l}=this,u=this.w0=A(c(o/i),Re,ie),d=this.zeta=a/(2*c(o*i));d<1?(this.wd=u*c(1-d*d),this.b=(d*u+-l)/this.wd):d===1?(this.wd=0,this.b=-l+u):(this.wd=u*c(d*d-1),this.b=(d*u+-l)/this.wd);let f=0,ee=0,p=0;for(;ee<=e&&p<=t;)Pe(1-this.solve(f))<n?ee++:ee=0,this.solverDuration=f,f+=r,p++;this.settlingDuration=et(this.solverDuration*ie,0)*s.timeScale}get bounce(){return this.bn}set bounce(e){this.bn=A(He(e,1),-1,1),this.calculateSDFromBD(),this.compute()}get duration(){return this.pd}set duration(e){this.pd=A(He(e,1),10*s.timeScale,$*s.timeScale),this.calculateSDFromBD(),this.compute()}get stiffness(){return this.s}set stiffness(e){this.s=A(He(e,100),Re,$),this.calculateBDFromSD(),this.compute()}get damping(){return this.d}set damping(e){this.d=A(He(e,10),Re,$),this.calculateBDFromSD(),this.compute()}get mass(){return this.m}set mass(e){this.m=A(He(e,1),1,$),this.compute()}get velocity(){return this.v}set velocity(e){this.v=A(He(e,0),-$,$),this.compute()}},dc=e=>new uc(e),fc=(e=10,t)=>{let n=t?ve:nt;return t=>n(A(t,0,1)*e)*(1/e)},pc=Object.freeze({ease:`linear`,duration:0});function mc(e,t){let n=l(e,t.duration);return n<=0?pc:e.steps>0?{ease:fc(e.steps),duration:n}:{ease:dc({bounce:re(e,t.bounce),duration:n}),duration:n}}function hc(e,t){let n=f(e,t.duration);return{ease:e.steps>0?fc(e.steps):t.ease,duration:n}}var gc={dot:{y:-4,height:8,cy:0},pill:{y:-16,height:32,cy:0},bang:{y:-16,height:20,cy:12}};function _c({className:e,glyph:t,motion:n}){let r=`caps-status-${(0,N.useId)().replaceAll(`:`,``)}`,i=(0,N.useRef)(null),a=(0,N.useRef)(null),o=(0,N.useRef)(null),s=(0,N.useRef)(null),c=(0,N.useRef)(null),l=(0,N.useRef)(null),u=(0,N.useRef)(gc[t]).current,d=(0,N.useRef)(t===`dot`?1:4).current,ee=(0,N.useRef)(+(t===`bang`)).current,p=(0,N.useRef)(t),m=oe(s),{reduced:te}=m;return(0,N.useLayoutEffect)(()=>{if(!i.current||!a.current||!c.current||!l.current)return;let e=gc[t],n=te||p.current===t;p.current=t;let r=ne(i.current),o=n?{duration:0}:mc(r,{bounce:.3,duration:360}),s=E(i.current,{y:e.y,height:e.height,...o}),u=E(a.current,{cy:e.cy,...n?{duration:0}:{delay:f(r,35),...mc(r,{bounce:.3,duration:420})}}),d=E(c.current,{gradientTransform:`matrix(1 0 0 ${t===`dot`?`1`:`4`} 0 0)`,...o}),ee=E(l.current,{opacity:+(t===`bang`),...n?pc:hc(r,{ease:`inOutSine`,duration:220})});return()=>{s.cancel(),u.cancel(),d.cancel(),ee.cancel()}},[t,te]),(0,N.useLayoutEffect)(()=>{if(!o.current||!s.current||te||n===`none`)return;let e=n===`pulse`?E(o.current,{opacity:[1,.45],...hc(m,{ease:`inOutSine`,duration:750}),alternate:!0,loop:!0}):E(o.current,{keyframes:{"0%":{translateY:0,scaleX:1,scaleY:1},"18%":{translateY:.25,scaleX:1.1,scaleY:.91},"42%":{translateY:-1.3,scaleX:.94,scaleY:1.06},"62%":{translateY:-1.65,scaleX:1,scaleY:1},"82%":{translateY:.15,scaleX:1.06,scaleY:.95},"100%":{translateY:0,scaleX:1,scaleY:1}},...hc(m,{ease:`inOutSine`,duration:1e3}),loop:!0}),t=Ye(s.current,t=>{t?e.resume():e.pause()});return()=>{t(),e.revert()}},[n,te,m]),(0,P.jsxs)(`svg`,{ref:s,"aria-hidden":`true`,className:`caps-status-bead ${e??``}`,width:`8`,height:`8`,viewBox:`-4 -4 8 8`,focusable:`false`,children:[(0,P.jsxs)(`defs`,{children:[(0,P.jsx)(Te,{id:r,values:Me}),(0,P.jsx)(Oe,{ref:c,id:`${r}-surface`,transform:`matrix(1 0 0 ${String(d)} 0 0)`}),(0,P.jsxs)(`radialGradient`,{id:`${r}-drop-light`,gradientUnits:`userSpaceOnUse`,cx:`-1.2`,cy:`10.4`,r:`5.6`,children:[(0,P.jsx)(`stop`,{offset:`0`,stopColor:`var(--color-white)`,style:{stopOpacity:`calc(var(--depth) * 0.5)`}}),(0,P.jsx)(`stop`,{offset:`1`,stopColor:`var(--color-white)`,stopOpacity:`0`})]}),(0,P.jsx)(Qe,{id:`${r}-shadow`}),(0,P.jsx)(`mask`,{id:`${r}-silhouette`,maskUnits:`userSpaceOnUse`,x:`-12`,y:`-24`,width:`24`,height:`48`,style:{maskType:`alpha`},children:(0,P.jsxs)(`g`,{fill:`var(--color-white)`,filter:`url(#${r})`,children:[(0,P.jsx)(`rect`,{ref:i,x:`-4`,y:u.y,width:`8`,height:u.height,rx:`4`}),(0,P.jsx)(`circle`,{ref:a,cx:`0`,cy:u.cy,r:`4`})]})})]}),(0,P.jsx)(`g`,{ref:o,filter:`url(#${r}-shadow)`,children:(0,P.jsxs)(`g`,{mask:`url(#${r}-silhouette)`,children:[(0,P.jsx)(`rect`,{x:`-12`,y:`-24`,width:`24`,height:`48`,fill:`url(#${r}-surface)`}),(0,P.jsx)(`rect`,{ref:l,x:`-12`,y:`-24`,width:`24`,height:`48`,fill:`url(#${r}-drop-light)`,opacity:ee})]})})]})}var vc=.28;function yc(e,t){switch(e){case`ring`:return{dashes:1,track:0,arc:0,sweep:0,disc:0,tick:0,cross:0};case`arc`:return{dashes:0,track:1,arc:1,sweep:t===void 0?vc:Math.min(1,Math.max(0,t)),disc:0,tick:0,cross:0};case`check`:return{dashes:0,track:0,arc:1,sweep:1,disc:1,tick:1,cross:0};case`cross`:return{dashes:0,track:0,arc:1,sweep:1,disc:1,tick:0,cross:1}}}var bc=7.25;function xc({className:e,glyph:t,progress:n}){let r=`caps-status-mark-${(0,N.useId)().replaceAll(`:`,``)}`,i=(0,N.useRef)(null),a=(0,N.useRef)(null),o=(0,N.useRef)(null),s=(0,N.useRef)(null),c=(0,N.useRef)(null),l=(0,N.useRef)(null),u=(0,N.useRef)(null),d=(0,N.useRef)(null),f=(0,N.useRef)(yc(t,n)).current,ee=(0,N.useRef)(t),p=st();(0,N.useLayoutEffect)(()=>{let e=i.current,r=a.current,c=o.current,f=s.current,m=l.current,te=u.current,h=d.current;if(!e||!r||!c||!f||!m||!te||!h)return;let re=yc(t,n),ie=ee.current;ee.current=t;let g=ne(e),ae=p||ie===t&&t!==`arc`,oe=ae?p?{ease:g.ease,duration:g.fast}:pc:hc(g,{ease:`outQuad`,duration:160}),_=(t===`check`||t===`cross`)&&!ae,se=hc(g,{ease:`inOutSine`,duration:220}),v=[E(r,{opacity:re.dashes,...oe}),E(c,{opacity:re.track*.28,...oe}),E(f,{opacity:re.arc,"stroke-dasharray":`${String(re.sweep)} 1`,...ae?p?pc:oe:se}),E(m,{r:re.disc*bc,..._?{delay:se.duration*.7,...mc(g,{bounce:.35,duration:360})}:p?pc:hc(g,{ease:`inCubic`,duration:140})}),E(te,{"stroke-dashoffset":1-re.tick,..._&&re.tick>0?{delay:se.duration*.7+g.fast,...hc(g,{ease:`outCubic`,duration:240})}:pc}),E(h,{"stroke-dashoffset":1-re.cross,..._&&re.cross>0?{delay:se.duration*.7+g.fast,...hc(g,{ease:`outCubic`,duration:240})}:pc})];return t===`cross`&&_&&g.shake>0&&v.push(E(e,{translateX:[0,-g.shake,g.shake,-g.shake/2,0],delay:se.duration+g.fast,...hc(g,{ease:`linear`,duration:300})})),()=>{for(let e of v)e.cancel()}},[t,n,p]);let m=t===`arc`&&n===void 0&&!p;return(0,N.useLayoutEffect)(()=>{if(!m||!c.current||!i.current)return;let e=ne(i.current),t=E(c.current,{rotate:[0,360],...hc(e,{ease:`linear`,duration:900}),loop:!0}),n=Ye(i.current,e=>{e?t.resume():t.pause()});return()=>{n(),t.revert()}},[m]),(0,P.jsxs)(`svg`,{ref:i,"aria-hidden":`true`,className:`caps-status-mark ${e??``}`,viewBox:`0 0 16 16`,focusable:`false`,children:[(0,P.jsxs)(`defs`,{children:[(0,P.jsx)(Oe,{id:`${r}-surface`,transform:`matrix(1.6 0 0 1.6 8 8)`}),(0,P.jsxs)(`mask`,{id:`${r}-knock`,maskUnits:`userSpaceOnUse`,x:`0`,y:`0`,width:`16`,height:`16`,children:[(0,P.jsx)(`rect`,{width:`16`,height:`16`,fill:`var(--color-white)`}),(0,P.jsx)(`path`,{ref:u,d:`M4.9 8.3 7.1 10.5 11.2 5.9`,fill:`none`,stroke:`var(--color-black)`,strokeWidth:`1.9`,strokeLinecap:`round`,strokeLinejoin:`round`,pathLength:1,strokeDasharray:`1 1`,strokeDashoffset:1-f.tick}),(0,P.jsx)(`path`,{ref:d,d:`M5.4 5.4 10.6 10.6 M10.6 5.4 5.4 10.6`,fill:`none`,stroke:`var(--color-black)`,strokeWidth:`1.9`,strokeLinecap:`round`,pathLength:1,strokeDasharray:`1 1`,strokeDashoffset:1-f.cross})]})]}),(0,P.jsx)(`circle`,{ref:a,cx:`8`,cy:`8`,r:`6.25`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeDasharray:`1.7 2.2`,opacity:f.dashes}),(0,P.jsx)(`circle`,{ref:o,cx:`8`,cy:`8`,r:`6.25`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,opacity:f.track*.28}),(0,P.jsx)(`g`,{ref:c,className:`caps-status-mark-spin`,children:(0,P.jsx)(`circle`,{ref:s,cx:`8`,cy:`8`,r:`6.25`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,pathLength:1,strokeDasharray:`${String(f.sweep)} 1`,transform:`rotate(-90 8 8)`,opacity:f.arc})}),(0,P.jsx)(`circle`,{ref:l,cx:`8`,cy:`8`,r:f.disc*bc,fill:`url(#${r}-surface)`,mask:`url(#${r}-knock)`})]})}var Sc=new Set([`ring`,`arc`,`check`,`cross`]);function Cc(e){return Sc.has(e)}var wc={neutral:`text-base-content`,primary:`text-primary`,secondary:`text-secondary`,accent:`text-accent`,success:`text-success`,info:`text-info`,warning:`text-warning`,error:`text-error`},Tc=(0,N.forwardRef)(function({className:e,label:t,glyph:n=`dot`,motion:r=`none`,tone:i=`neutral`,size:a=`default`,appearance:o=`plain`,progress:s,...c},l){return(0,P.jsxs)(`span`,{...c,className:ue(`caps-status`,a===`compact`&&`caps-status-compact`,o===`chip`&&`caps-status-chip`,e),"data-tone":o===`chip`?i:void 0,"data-glyph":n,"data-motion":r,ref:l,children:[Cc(n)?(0,P.jsx)(xc,{className:wc[i],glyph:n,progress:s}):(0,P.jsx)(_c,{className:wc[i],glyph:n,motion:r}),t===void 0?null:(0,P.jsx)(`span`,{children:t})]})}),Ec=(0,N.forwardRef)(function({className:e,count:t,density:n=`row`,dismissAriaLabel:r,dismissLabel:i=`Dismiss`,message:a,onDismiss:o,onRetry:s,retryAriaLabel:c,retryLabel:l=`Retry`,role:u=`status`,...d},f){return(0,P.jsxs)(`div`,{...d,className:ue(`caps-failure-line`,e),"data-density":n,ref:f,role:u,children:[(0,P.jsx)(Tc,{glyph:`dot`,tone:`error`}),(0,P.jsxs)(`span`,{className:`caps-failure-line-copy`,children:[(0,P.jsx)(`span`,{children:a}),t!==void 0&&t>1?(0,P.jsxs)(`span`,{className:`caps-failure-line-count`,children:[`Failed `,t,` times`]}):null]}),s||o?(0,P.jsxs)(`span`,{className:`caps-failure-line-actions`,children:[s?(0,P.jsx)(be,{"aria-label":c,size:`sm`,variant:`outline`,onClick:s,children:l}):null,o?(0,P.jsx)(be,{"aria-label":r,size:`sm`,variant:`ghost`,onClick:o,children:i}):null]}):null]})});function Dc(e,t,n=0){return Rs(e,Us,Fs.of(e,`tree`,e?.capabilities.version??0,t,n),async(e,r)=>{let i=await e.list({path:t,offset:n,limit:256});return r.throwIfAborted(),i})}var Oc=Le(`FilePlus2`,[[`path`,{d:`M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4`,key:`1pf5j1`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M3 15h6`,key:`4e2qda`}],[`path`,{d:`M6 12v6`,key:`1u72j0`}]]),kc=Le(`FolderOpen`,[[`path`,{d:`m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2`,key:`usdka0`}]]);export{cs as $,bo as A,F as At,Eo as B,Cs as C,Dn as Ct,_s as D,cn as Dt,Ts as E,xn as Et,xo as F,dt as Ft,ko as G,Jo as H,So as I,Vo as J,Ao as K,Co as L,ss as M,At as Mt,ms as N,ht as Nt,ys as O,L as Ot,hs as P,mt as Pt,Uo as Q,wo as R,Es as S,Tn as St,Ds as T,wn as Tt,Oo as U,Do as V,Xo as W,zo as X,Ro as Y,us as Z,Z as _,Rn as _t,Tc as a,Go as at,Ms as b,An as bt,mc as c,Ta as ct,ic as d,Sa as dt,qo as et,rc as f,va as ft,Fs as g,rr as gt,Ls as h,$r as ht,Ec as i,jo as it,Ho as j,kt as jt,gs as k,Wt as kt,Us as l,wa as lt,lc as m,ba as mt,Oc as n,ds as nt,pc as o,Ko as ot,sc as p,ya as pt,No as q,Dc as r,Mo as rt,hc as s,ls as st,kc as t,Wo as tt,ac as u,Ca as ut,js as v,In as vt,ws as w,En as wt,As as x,kn as xt,Q as y,On as yt,To as z};
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{$r as t,An as n,Br as r,Ci as i,Cn as a,Cr as o,Dn as s,En as c,Fn as l,Gr as u,Hr as d,In as f,Ji as ee,Jr as p,Ki as m,Kn as te,Kr as h,Ln as ne,Nn as re,On as ie,Qr as g,Ri as ae,Rn as oe,Si as _,Sn as se,Sr as v,Tn as ce,Tr as le,Un as y,Ur as b,Vn as ue,Vr as de,Wn as fe,Xi as pe,Xr as x,Yi as me,Yr as he,Zi as ge,_i as _e,_n as ve,_r as ye,an as be,bi as xe,bn as Se,br as Ce,ci as we,cn as Te,cr as Ee,di as De,dn as Oe,dr as ke,ea as Ae,fi as je,fn as Me,gi as Ne,gn as Pe,gr as S,hi as Fe,hn as Ie,hr as C,ii as w,in as Le,kn as Re,li as ze,lr as Be,mi as Ve,mn as He,mr as Ue,na as We,ni as Ge,oi as T,pn as E,pr as Ke,qi as qe,qr as Je,ri as D,sn as Ye,sr as Xe,ti as Ze,ui as O,un as Qe,ur as $e,vi as k,vn as A,vr as j,wn as et,wr as M,xi as tt,xn as nt,yi as rt,yn as it,yr as at,zi as ot,zn as st}from"./tree-path-C6dPmEG1.js";var ct=new WeakMap,lt=`~effect/Redacted`,ut=e=>ge(e,lt),dt=(e,t)=>{let n=Object.create(ft);return t?.label&&(n.label=t.label),ct.set(n,e),n},ft={[lt]:{_A:e=>e},label:void 0,...m,toJSON(){return this.toString()},toString(){return`<redacted${Ae(this.label)?`:`+this.label:``}>`},[pe](){return me(ct.get(this))},[ee](e){return ut(e)&&qe(ct.get(this),ct.get(e))}},N=e(de(),1),P=r(),pt=N.createContext(void 0),mt=e=>{let t=N.useContext(pt);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},ht=({client:e,children:t})=>(N.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,P.jsx)(pt.Provider,{value:e,children:t})),gt={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},_t=new class{#e=gt;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function vt(e){setTimeout(e,0)}var yt=typeof window>`u`||`Deno`in globalThis;function F(){}function bt(e,t){return typeof e==`function`?e(t):e}function xt(e){return typeof e==`number`&&e>=0&&e!==1/0}function St(e,t){return Math.max(e+(t||0)-Date.now(),0)}function I(e,t){return typeof e==`function`?e(t):e}function Ct(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==Tt(o,t.options))return!1}else if(!Dt(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function wt(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(Et(t.options.mutationKey)!==Et(a))return!1}else if(!Dt(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Tt(e,t){return(t?.queryKeyHashFn||Et)(e)}function Et(e){return JSON.stringify(e,(e,t)=>Mt(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function Dt(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){for(let n=0;n<t.length;n++)if(!Dt(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!Dt(e[r],t[r]))return!1;return!0}return!1}var Ot=Object.prototype.hasOwnProperty;function kt(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=jt(e)&&jt(t);if(!r&&!(Mt(e)&&Mt(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:Ot.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=kt(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function At(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function jt(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Mt(e){if(!Nt(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Nt(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function Nt(e){return Object.prototype.toString.call(e)===`[object Object]`}function Pt(e){return new Promise(t=>{_t.setTimeout(t,e)})}function Ft(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:kt(e,t)}function It(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function Lt(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Rt=Symbol();function zt(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Rt?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Bt(e,t){return typeof e==`function`?e(...t):!!e}function Vt(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var Ht=()=>yt,Ut=()=>Ht(),Wt=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Gt=new class extends Wt{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},Kt=vt;function qt(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=Kt,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var L=qt(),Jt=new class extends Wt{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function Yt(e){return Math.min(1e3*2**e,3e4)}function Xt(e){return(e??`online`)!==`online`||Jt.isOnline()}var Zt=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function Qt(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(F);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new Zt(t);m(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>Gt.isFocused()&&(e.networkMode===`always`||Jt.isOnline())&&e.canRun(),ee=()=>Xt(e.networkMode)&&e.canRun(),p=e=>{c()||(r?.(),i=`resolved`,a(e))},m=e=>{c()||(r?.(),i=`rejected`,o(e))},te=()=>new Promise(t=>{r=e=>{(c()||f())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),h=()=>{if(c())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(p).catch(r=>{if(c())return;let i=e.retry??(Ut()?0:3),a=e.retryDelay??Yt,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);if(t||!s){m(r);return}n++,e.onFail?.(n,r),Pt(o).then(()=>f()?void 0:te()).then(()=>{t?m(r):h()})})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:ee,start:()=>(ee()?h():te().then(h),s)}}var $t=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),xt(this.gcTime)&&(this.#e=_t.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ut()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(_t.clearTimeout(this.#e),this.#e=void 0)}};function en(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{Vt(e,()=>t.signal,()=>n=!0)},u=zt(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?Lt:It;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?nn:tn,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:tn(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function tn(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function nn(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var rn=class extends $t{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=sn(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=sn(this.options);e.data!==void 0&&(this.setState(on(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=Ft(this.state.data,e,this.options);return this.#c({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#c({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(F).catch(F):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>I(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Rt||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>I(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!St(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#s||this.state.fetchStatus===`paused`&&this.state.status===`pending`?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#c({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=zt(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?en(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=Qt({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof Zt&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#c({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#c({type:`pause`})},onContinue:()=>{this.#c({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await o.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof Zt){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#c({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0),this.scheduleGc()}}#c(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...an(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...on(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),L.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function an(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Xt(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function on(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function sn(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var cn=class extends Wt{#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),un(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return dn(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return dn(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof I(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!At(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&fn(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||I(this.options.enabled,this.#t)!==I(t.enabled,this.#t)||I(this.options.staleTime,this.#t)!==I(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||I(this.options.enabled,this.#t)!==I(t.enabled,this.#t)||i!==this.#f)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return At(this.getCurrentResult(),n)||(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t),r=()=>{},i,a=new Promise(e=>{i=e,r=this.#e.getQueryCache().subscribe(i=>{i.type===`updated`&&i.query.queryHash===n.queryHash&&n.state.data!==void 0&&(r(),e(this.createResult(n,t)))})});return Promise.race([n.fetch().then(()=>{let e=this.createResult(n,t);return i?.(e),e}).finally(()=>{r()}),a])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(F)),t}#h(e){return!Ut()&&I(this.options.enabled,this.#t)!==!1&&xt(e)}#g(){this.#b();let e=I(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=St(this.#r.dataUpdatedAt,e)+1;this.#u=_t.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return(typeof this.options.refetchInterval==`function`?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(e){this.#x(),this.#f=e,!(this.#f===0||!this.#h(this.#f))&&(this.#d=_t.setInterval(()=>{(this.options.refetchIntervalInBackground||Gt.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(_t.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(_t.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&un(e,t),o=i&&fn(e,n,t,r);(a||o)&&(l={...l,...an(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:ee,status:p}=l;d=l.data;let m=!1;if(t.placeholderData!==void 0&&d===void 0&&p===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,m=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(p=`success`,d=Ft(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!m){if(i&&d===a?.data&&t.select===this.#s)d=this.#c;else try{this.#s=t.select,d=t.select(d),d=Ft(i?.data,d,t),this.#c=d,this.#o=null}catch(e){this.#o=e}}else d===void 0&&(this.#o=null);this.#o&&(f=this.#o,d=this.#c,ee=Date.now(),p=`error`,u=!1);let te=l.fetchStatus===`fetching`,h=p===`pending`,ne=p===`error`,re=h&&te,ie=d!==void 0;return{status:p,fetchStatus:l.fetchStatus,isPending:h,isSuccess:p===`success`,isError:ne,isInitialLoading:re,isLoading:re,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:ee,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:te,isRefetching:te&&!h,isLoadingError:ne&&!ie,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:ne&&ie,isStale:pn(e,t),refetch:this.refetch,isEnabled:I(t.enabled,e)!==!1}}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#l=this.#t),At(t,e))return;this.#r=t;let n=(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#p.size)return!0;let r=new Set(n??this.#p);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})();L.batch(()=>{n&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function ln(e,t){return I(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||I(t.retryOnMount,e)!==!1)}function un(e,t){return ln(e,t)||e.state.data!==void 0&&dn(e,t,t.refetchOnMount)}function dn(e,t,n){if(I(t.enabled,e)!==!1&&I(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&pn(e,t)}return!1}function fn(e,t,n,r){return(e!==t||I(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&pn(e,n)}function pn(e,t){return I(t.enabled,e)!==!1&&e.isStaleByTime(I(t.staleTime,e))}var mn=class extends $t{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||hn(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??(this.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},r=this.#r=Qt({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),i=this.state.status===`pending`,a=!r.canStart();try{if(i)t();else{this.#i({type:`pending`,variables:e,isPaused:a}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:a})}let o=await r.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#i({type:`success`,data:o}),o}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#r===r&&(this.#r=void 0),this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),L.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function hn(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var gn=class extends Wt{#e;#t;#n;constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}build(e,t,n){let r=new mn({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=_n(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=_n(e);if(typeof t==`string`){let n=this.#t.get(t);if(n){if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=_n(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}return!0}runNext(e){let t=_n(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){L.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>wt(t,e))}findAll(e={}){return this.getAll().filter(t=>wt(e,t))}notify(e){L.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return L.batch(()=>Promise.all(e.map(e=>e.continue().catch(F))))}};function _n(e){return e.options.scope?.id}var vn=class extends Wt{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){let r=t.queryKey,i=t.queryHash??Tt(r,t),a=this.get(i);return a||(a=new rn({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){L.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>Ct(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>Ct(e,t)):t}notify(e){L.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){L.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){L.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},yn=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new vn,this.#t=e.mutationCache||new gn,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=Gt.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=Jt.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(I(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=bt(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return L.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;L.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return L.batch(()=>{let r=n.findAll(e),i=new Set(r);return r.forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,predicate:e=>i.has(e)},t)})}cancelQueries(e,t={}){let n={revert:!0,...t},r=L.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(F).catch(F)}invalidateQueries(e,t={}){return L.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=L.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(F)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(F)}async query(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t),r=n.isStaleByTime(I(t.staleTime,n))?await n.fetch(t):n.state.data,i=t.select;return i?i(r):r}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(I(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(F).catch(F)}infiniteQuery(e){return e._type=`infinite`,this.query(e)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(F).catch(F)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return Jt.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(Et(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{Dt(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(Et(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{Dt(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=Tt(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===Rt&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},bn=N.createContext(!1),xn=()=>N.useContext(bn);bn.Provider;function Sn(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Cn=N.createContext(Sn()),wn=()=>N.useContext(Cn),Tn=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?Bt(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},En=e=>{N.useEffect(()=>{e.clearReset()},[e])},Dn=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Bt(n,[e.error,r])),On=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))}},kn=(e,t)=>e?.suspense&&t.isPending,An=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function jn(e){return e}var Mn=Ue(),Nn=C(()=>Ke(`status`,[j({status:S(`available`)}).strict(),j({status:S(`unavailable`),reason:v()}).strict()])),Pn=Mn,Fn=C(()=>Ce(v(),Pn)),In=e=>Pn.parse(e),Ln=C(()=>j({code:v().min(1).max(160),message:v().min(1).max(512),details:Pn.optional()}).strict()),Rn=e=>Ln.parse(e),zn=Fn,R=C(()=>v().refine(e=>e.trim().length>0)),Bn=Nn,Vn=C(()=>o([j({type:S(`action`)}).strict(),j({type:S(`custom`),data:Fn}).strict(),j({type:S(`choice`),options:$e(j({value:Pn,label:R,description:R.optional()}))}).strict(),j({type:S(`form`),submitLabel:R.optional()}).strict(),j({type:S(`confirmation`),message:R,confirmLabel:R.optional(),cancelLabel:R.optional()}).strict()])),Hn=C(()=>j({inputSchema:zn.optional(),outputSchema:zn.optional(),presentation:Vn.optional()}).strict()),Un=C(()=>ye().int().refine(e=>Number.isSafeInteger(e))),Wn=C(()=>j({hint:R.pipe(v().max(120)),words:$e(j({word:v().regex(/^\S{1,64}$/u),description:R.pipe(v().max(512)).optional(),arguments:Fn}).strict()).max(32).optional(),text:j({field:R.pipe(v().max(120)),arguments:Fn,requestIdField:R.pipe(v().max(120)).optional()}).strict().optional()}).strict().refine(e=>e.words!==void 0||e.text!==void 0,`slash arguments need words or text`)),Gn=C(()=>j({order:Un.optional()}).strict()),Kn=C(()=>j({bindings:j({order:Un.optional(),values:$e(R).max(16)}).strict().optional(),agent:j({keybind:R.optional(),order:Un.optional()}).strict().optional(),help:Gn.optional(),menu:Gn.optional(),palette:Gn.optional(),slash:j({aliases:$e(R).max(16),consumesDraft:ke().optional(),order:Un.optional(),arguments:Wn.optional()}).strict().optional()}).strict()),qn=C(()=>j({id:R.refine(e=>!e.includes(`:`)),title:R,category:R,description:R.optional(),projections:Kn.optional(),action:Hn.optional(),availability:Bn.optional()}).strict()),Jn=e=>qn.parse(e),Yn=C(()=>j({inputSchema:zn.optional(),outputSchema:zn.optional()}).strict()),Xn=v().min(1).brand(),Zn=C(()=>j({commandId:Xn,command:j({namespace:v(),id:v()}).strict(),sourceId:v(),scope:v().optional(),title:v(),category:v(),description:v().optional(),order:ye(),availability:Nn,action:Yn.optional(),keybind:v().optional()}).strict());$e(Zn);var Qn=8192,z=R.pipe(v().max(Qn)),$n=R.pipe(v().max(60)),er=le({protocol:/^https?$/u}),tr=j({label:z,value:z}).strict(),nr={summary:z.optional(),facts:$e(tr).max(4).optional(),body:z.optional(),bodyLabel:z.optional(),details:$e(tr).max(24).optional()};Ke(`type`,[j({type:S(`choice`),message:$n,...nr,current:z.optional(),collapsedGroup:z.optional(),options:$e(j({value:z,label:z,description:z.optional(),group:z.optional(),destructive:S(!0).optional()}).strict()).min(1).max(256)}).strict(),j({type:S(`text`),message:$n,...nr,placeholder:z.optional(),secret:ke().optional()}).strict(),j({type:S(`confirmation`),message:$n,...nr,confirmLabel:z.optional(),cancelLabel:z.optional(),destructive:S(!0).optional()}).strict(),j({type:S(`decision`),message:$n,...nr,options:$e(j({value:z,label:z,description:z.optional(),destructive:S(!0).optional()}).strict()).min(1).max(8).refine(e=>new Set(e.map(e=>e.value)).size===e.length,`Decision option values must be unique`),multiple:ke().optional(),other:j({label:z,placeholder:z.optional(),maxLength:ye().int().min(1).max(Qn),blank:z.optional()}).strict().optional(),escape:z.optional()}).strict().refine(e=>[e.escape,e.other?.blank].every(t=>t===void 0||e.options.some(e=>e.value===t)),`A decision's escape and blank answers must be offered options`)]),C(()=>Ke(`type`,[j({type:S(`info`),message:z,links:$e(j({url:er,label:z.optional()}).strict()).max(16).optional()}).strict(),j({type:S(`progress`),message:z}).strict(),j({type:S(`handoff`),url:er,code:z.optional(),message:z.optional()}).strict(),j({type:S(`success`),message:z}).strict()]));var rr=class extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name=`WhistleActionError`}},ir=class extends Error{constructor(){super(`Whistle runtime is closed`),this.name=`WhistleClosedError`}};function ar(){let e=!1,t=Ir,n=[],r=[],i=!1,a=[],o=new Set,s=()=>{for(let e of o)e()};return Object.freeze({close:()=>{e||(e=!0,n=[],a=[],r=[],t=Ir,s(),o.clear())},contribute:t=>{if(mr(t),e)throw new ir;hr(t,n),gr(t,n);let r=Symbol(`whistle-contribution`);pr(t)||(n=[...n,{contribution:_r(t),generation:r}],i=!0,s());let a=!0;return Fr(o=>{if(!a||e)return;let c={...t,commands:o};mr(c);let l=n.findIndex(e=>e.generation===r),u=n.filter(e=>e.generation!==r);hr(c,u),gr(c,u);let d=_r(c);if(pr(c)){if(l<0)return;n=u}else n=l<0?[...n,{contribution:d,generation:r}]:n.map(e=>e.generation===r?{contribution:d,generation:r}:e);i=!0,s()},()=>{a&&(a=!1,n.find(e=>e.generation===r)!==void 0&&(n=n.filter(e=>e.generation!==r),i=!0,s()))})},execute:async(t,r)=>{if(t.namespace.trim().length===0||t.id.trim().length===0)return{status:`invalid`};if(e)return{status:`closed`};let i=fr(t,n);if(i===void 0)return{status:`missing`};let o;try{let e=Rr(i);if(e.status===`unavailable`)return e;let n=a.at(-1)?.presenter;r.interaction===void 0&&n!==void 0&&or.has(r.origin)&&(o=n({commandId:dr(t.namespace,t.id),title:i.title}));let s={...r,signal:r.signal??new AbortController().signal};o!==void 0&&(s.interaction=o.interaction,s.signal=AbortSignal.any([s.signal,o.interaction.signal]));let c=await i.handler(s);return o?.settle({status:`handled`}),c===void 0?{status:`handled`}:{status:`handled`,result:c}}catch(e){let t=Br(e instanceof Error?e:Error(`Command handler threw a non-Error value`));return o?.settle(o.interaction.signal.aborted?{status:`cancelled`}:{status:`failed`,message:t.message}),{status:`failed`,error:t}}},present:t=>{let n={presenter:t};return e||(a=[...a,n]),()=>{a=a.filter(e=>e!==n)}},snapshot:()=>{if(e)return Ir;let a=n.flatMap(e=>e.contribution.commands.map(Rr));return(i||a.some((e,t)=>!zr(e,r[t])))&&(t=Vr(n,a),r=a,i=!1),t},subscribe:t=>e?()=>void 0:(o.add(t),()=>{o.delete(t)})})}var or=new Set([`browser`,`keyboard`,`menu`,`palette`,`slash`,`terminal`]),sr=16,cr=32,lr=64,ur=256;function dr(e,t){return Xn.parse(`${e}:${t}`)}function fr(e,t){for(let n of t)if(n.contribution.namespace===e.namespace){for(let t of n.contribution.commands)if(t.id===e.id)return t}}function pr(e){return e.commands.length===0}function mr(e){B(e.sourceId,`source ID`),B(e.namespace,`namespace`),e.scope!==void 0&&B(e.scope,`scope`);for(let t of e.commands)kr(t)}function hr(e,t){t.find(t=>t.contribution.namespace===e.namespace&&t.contribution.sourceId!==e.sourceId)!==void 0&&V(`Namespace is already owned by another source`);let n=new Set,r=new Set;for(let i of t){let t=i.contribution.scope===e.scope;for(let e of i.contribution.commands)if(n.add(dr(i.contribution.namespace,e.id)),t)for(let t of e.projections?.slash?.aliases??[])r.add(t)}for(let t of e.commands){let i=dr(e.namespace,t.id);n.has(i)&&V(`Canonical command ID is already registered`),n.add(i);for(let e of t.projections?.slash?.aliases??[])r.has(e)&&V(`Slash alias is already registered`),r.add(e)}}function gr(e,t){t.length>=lr&&V(`Live contribution capacity exceeded`),t.reduce((e,t)=>e+t.contribution.commands.length,0)+e.commands.length>ur&&V(`Live command capacity exceeded`)}function _r(e){let t={sourceId:e.sourceId,namespace:e.namespace,commands:e.commands.map(vr)};return e.scope===void 0?t:{...t,scope:e.scope}}function vr(e){let t={id:e.id,title:e.title,category:e.category,handler:e.handler};return e.description!==void 0&&(t.description=e.description),e.action!==void 0&&(t.action=yr(e.action)),e.availability!==void 0&&(t.availability=e.availability),e.projections!==void 0&&(t.projections=Cr(e.projections)),t}function yr(e){let t={};return e.inputSchema!==void 0&&(t.inputSchema=br(e.inputSchema)),e.outputSchema!==void 0&&(t.outputSchema=br(e.outputSchema)),e.presentation!==void 0&&(t.presentation=Sr(e.presentation)),Object.freeze(t)}function br(e){return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,xr(t)])))}function xr(e){return Array.isArray(e)?Object.freeze(e.map(xr)):e!==null&&e instanceof Object?Object.freeze(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,xr(t)]))):e}function Sr(e){switch(e.type){case`action`:return Object.freeze({type:`action`});case`custom`:return Object.freeze({type:`custom`,data:br(e.data)});case`choice`:return Object.freeze({type:`choice`,options:Object.freeze(e.options.map(e=>Object.freeze({...e,value:xr(e.value)})))});case`form`:return Object.freeze({...e});case`confirmation`:return Object.freeze({...e})}}function Cr(e){let t={};return e.bindings!==void 0&&(t.bindings=wr(e.bindings)),e.agent!==void 0&&(t.agent=Tr(e.agent)),e.help!==void 0&&(t.help=Er(e.help.order)),e.menu!==void 0&&(t.menu=Er(e.menu.order)),e.palette!==void 0&&(t.palette=Er(e.palette.order)),e.slash!==void 0&&(t.slash=Dr(e.slash)),t}function wr(e){let t={values:[...e.values]};return e.order!==void 0&&(t.order=e.order),t}function Tr(e){let t={};return e.keybind!==void 0&&(t.keybind=e.keybind),e.order!==void 0&&(t.order=e.order),t}function Er(e){let t={};return e!==void 0&&(t.order=e),t}function Dr(e){let t={aliases:[...e.aliases]};return e.order!==void 0&&(t.order=e.order),e.consumesDraft!==void 0&&(t.consumesDraft=e.consumesDraft),e.arguments!==void 0&&(t.arguments=Or(e.arguments)),t}function Or(e){let t={hint:e.hint};return e.words!==void 0&&(t.words=Object.freeze(e.words.map(e=>Object.freeze({...e,arguments:br(e.arguments)})))),e.text!==void 0&&(t.text=Object.freeze({...e.text,arguments:br(e.text.arguments)})),Object.freeze(t)}function kr(e){B(e.id,`command ID`,!0),B(e.title,`title`),B(e.category,`category`),Ar(e.action),jr(e.projections)}function Ar(e){if(e?.presentation!==void 0)switch(e.presentation.type){case`action`:case`custom`:return;case`choice`:for(let t of e.presentation.options)B(t.label,`choice label`),t.description!==void 0&&B(t.description,`choice description`);return;case`form`:e.presentation.submitLabel!==void 0&&B(e.presentation.submitLabel,`submit label`);return;case`confirmation`:B(e.presentation.message,`confirmation message`),e.presentation.confirmLabel!==void 0&&B(e.presentation.confirmLabel,`confirmation label`),e.presentation.cancelLabel!==void 0&&B(e.presentation.cancelLabel,`cancellation label`)}}function jr(e){if(e!==void 0){for(let t of[e.bindings,e.palette,e.slash,e.help,e.menu,e.agent])t!==void 0&&Pr(t.order);if(e.bindings!==void 0&&Nr(e.bindings.values,`binding`),e.slash!==void 0){Nr(e.slash.aliases,`slash alias`);for(let t of e.slash.aliases)/\s/u.test(t)&&V(`slash alias must not contain whitespace`);Mr(e.slash.arguments)}e.agent?.keybind!==void 0&&B(e.agent.keybind,`agent keybind`)}}function Mr(e){if(e===void 0)return;B(e.hint,`argument hint`),e.words===void 0&&e.text===void 0&&V(`slash arguments need words or text`);let t=new Set;for(let n of e.words??[])B(n.word,`argument word`),/\s/u.test(n.word)&&V(`argument word must not contain whitespace`),t.has(n.word)&&V(`argument word is repeated`),t.add(n.word),n.description!==void 0&&B(n.description,`argument word description`);t.size>cr&&V(`argument word count exceeds 32`),e.text!==void 0&&(B(e.text.field,`argument text field`),e.text.requestIdField!==void 0&&B(e.text.requestIdField,`request id field`))}function Nr(e,t){e.length>sr&&V(`${t} count exceeds 16`);for(let n of e)B(n,t)}function B(e,t,n=!1){e.trim().length===0&&V(`${t} must not be blank`),n&&e.includes(`:`)&&V(`${t} must not contain a colon`)}function Pr(e){e!==void 0&&!Number.isSafeInteger(e)&&V(`order must be a safe integer`)}function Fr(e=()=>void 0,t=()=>void 0){return Object.freeze({update:e,dispose:t})}function V(e){throw Error(e)}var Ir=Object.freeze({bindings:Object.freeze([]),palette:Object.freeze([]),slash:Object.freeze([]),help:Object.freeze([]),menu:Object.freeze([]),agent:Object.freeze([])}),Lr=Object.freeze({status:`available`});function Rr(e){let t=e.availability?.()??Lr;return t.status===`available`?Lr:Object.freeze({status:`unavailable`,reason:t.reason})}function zr(e,t){return e.status===`available`?t?.status===`available`:t?.status===`unavailable`&&e.reason===t.reason}function Br(e){if(e instanceof rr){let t={code:e.code,message:e.message};return Object.freeze(e.details===void 0?t:{...t,details:xr(e.details)})}return Object.freeze({code:`command_failed`,message:e.message})}function Vr(e,t){let n=[],r=[],i=[],a=[],o=[],s=[],c=0;for(let l of e){let e=l.contribution;for(let l of e.commands){let u=l.projections,d=t[c++]??Lr;if(u?.bindings!==void 0)for(let t of u.bindings.values)n.push({...Jr(e,l,u.bindings.order,d),binding:t});if(u?.palette!==void 0&&r.push({...Jr(e,l,u.palette.order,d)}),u?.slash!==void 0)for(let t of u.slash.aliases){let n={...Jr(e,l,u.slash.order,d),alias:t};u.slash.consumesDraft!==void 0&&(n={...n,consumesDraft:u.slash.consumesDraft}),u.slash.arguments!==void 0&&(n={...n,arguments:u.slash.arguments}),i.push(n)}u?.help!==void 0&&a.push({...Jr(e,l,u.help.order,d)}),u?.menu!==void 0&&o.push({...Jr(e,l,u.menu.order,d)}),u?.agent!==void 0&&s.push(Xr(e,l,u.agent,d))}}return Gr(n),Kr(i),Wr(r),Wr(a),Wr(o),Wr(s),Object.freeze({bindings:qr(n),palette:qr(r),slash:qr(i),help:qr(a),menu:qr(o),agent:qr(s)})}var Hr=new TextEncoder;function Ur(e,t){let n=Hr.encode(e),r=Hr.encode(t),i=Math.min(n.length,r.length);for(let e=0;e<i;e+=1){let t=n[e]??0,i=r[e]??0;if(t!==i)return t<i?-1:1}return n.length<r.length?-1:+(n.length>r.length)}function Wr(e){e.sort((e,t)=>e.order-t.order||Ur(e.commandId,t.commandId))}function Gr(e){e.sort((e,t)=>e.order-t.order||Ur(e.commandId,t.commandId)||Ur(e.binding,t.binding))}function Kr(e){e.sort((e,t)=>e.order-t.order||Ur(e.commandId,t.commandId)||Ur(e.alias,t.alias))}function qr(e){return Object.freeze(e.map(e=>Object.freeze(e)))}function Jr(e,t,n,r){let i=Yr(e,t,n,r);return e.scope===void 0?i:{...i,scope:e.scope}}function Yr(e,t,n,r){let i={commandId:dr(e.namespace,t.id),command:Object.freeze({namespace:e.namespace,id:t.id}),sourceId:e.sourceId,title:t.title,category:t.category,order:n??0,availability:r},a=t.description===void 0?i:{...i,description:t.description};return t.action===void 0?a:{...a,action:t.action}}function Xr(e,t,n,r){let i=Jr(e,t,n.order,r),a=i.action===void 0?i:{...i,action:Zr(i.action)};return n.keybind===void 0?a:{...a,keybind:n.keybind}}function Zr(e){let t={};return e.inputSchema!==void 0&&(t.inputSchema=e.inputSchema),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),Object.freeze(t)}function Qr(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:In(r)}).then(e=>{n?e():r.push(e)},e=>{console.warn(`App command ${i.id} was not registered`,e)})}return()=>{if(!n){n=!0;for(let e of r.splice(0))e()}}}function $r(e,t){console.error(JSON.stringify({source:`agar`,operation:e,failureKind:t instanceof Error?`Error`:`NonErrorThrown`}),dt(t))}var ei=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 ti=globalThis[ei],ni=ti?ti.RpcTarget:class{},ri=async function(){}.constructor,ii=typeof Buffer<`u`?Buffer.prototype:void 0;function ai(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 ri.prototype:return`function`;case Array.prototype:return`array`;case Date.prototype:return`date`;case Uint8Array.prototype:case ii: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 hi.prototype:return`stub`;case W.prototype:return`rpc-promise`;default:if(ti){if(t==ti.RpcStub.prototype||e instanceof ti.ServiceStub)return`rpc-target`;if(t==ti.RpcPromise.prototype||t==ti.RpcProperty.prototype)return`rpc-thenable`}return e instanceof ni?`rpc-target`:e instanceof Error?`error`:`unsupported`}}function oi(){throw Error(`RPC map() implementation was not loaded.`)}var si={applyMap:oi,sendMap:oi};function ci(){throw Error(`Stream implementation was not loaded.`)}var H={createWritableStreamHook:ci,createWritableStreamFromHook:ci,createReadableStreamHook:ci},li=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}}},U=class extends li{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)}}},ui=new U(Error(`Attempted to use RPC stub after it has been disposed.`)),di=(e,t,n)=>e.call(t,n);function fi(e,t){let n=di;di=e;try{return t()}finally{di=n}}var pi=Symbol(`realStub`),mi={apply(e,t,n){let r=e.raw;return new W(di(r.hook,r.pathIfPromise||[],G.fromAppParams(n)),[])},get(e,t,n){let r=e.raw;if(t===pi)return r;if(t in W.prototype)return r[t];if(typeof t==`string`)return new W(r.hook,r.pathIfPromise?[...r.pathIfPromise,t]:[t]);if(t===Symbol.dispose&&(!r.pathIfPromise||r.pathIfPromise.length==0))return()=>{r.hook.dispose(),r.hook=ui}},has(e,t){let n=e.raw;return t===pi?!0:t in W.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.`)}},hi=class e extends ni{constructor(e,t){if(super(),!(e instanceof li)){let n=e;if(e=n instanceof ni||n instanceof Function?Ti.create(n,void 0):new K(G.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,mi)}hook;pathIfPromise;dup(){let t=this[pi];return t.pathIfPromise?new e(t.hook.get(t.pathIfPromise)):new e(t.hook.dup())}onRpcBroken(e){this[pi].hook.onBroken(e)}map(e){let{hook:t,pathIfPromise:n}=this[pi];return si.sendMap(t,n||[],e)}toString(){return`[object RpcStub]`}},W=class extends hi{constructor(e,t){if(e instanceof li)super(e,t??[]);else{if(t!==void 0)throw TypeError(`RpcPromise constructor expected one argument, received two.`);let n=ai(e);if(n===`rpc-promise`){let t=bi(e);if(t.pathIfPromise.length>0)super(t.hook,t.pathIfPromise);else{let e=t.hook;t.hook=ui,super(e,[])}}else if(n===`rpc-thenable`)super(Ti.create(e,void 0),[]);else{let t=new Ei(Promise.resolve(e).then(e=>new K(G.fromAppReturn(e))));t.ignoreUnhandledRejections(),super(t,[])}}}then(e,t){return xi(this).then(...arguments)}catch(e){return xi(this).catch(...arguments)}finally(e){return xi(this).finally(...arguments)}toString(){return`[object RpcPromise]`}};function gi(e){let{hook:t,pathIfPromise:n}=e[pi];return n&&n.length>0?t.get(n):t}function _i(e){let{hook:t,pathIfPromise:n}=e[pi];return n?t.get(n):t.dup()}function vi(e){let{hook:t,pathIfPromise:n}=e[pi];if(!(n&&n.length>0))return t}function yi(e){return e[pi].hook}function bi(e){return e[pi]}async function xi(e){let{hook:t,pathIfPromise:n}=e[pi];return n.length>0&&(t=t.get(n)),(await t.pull()).deliverResolve()}var G=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 Ti.create(e,t)}if(this.source===`return`){let r=this.rpcTargets?.get(e);return r?n?r.dup():(this.rpcTargets?.delete(e),r):(r=Ti.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 H.createWritableStreamHook(e);if(this.source===`return`){let t=this.rpcTargets?.get(e);return t?n?t.dup():(this.rpcTargets?.delete(e),t):(t=H.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 H.createReadableStreamHook(e);if(this.source===`return`){let t=this.rpcTargets?.get(e);return t?n?t.dup():(this.rpcTargets?.delete(e),t):(t=H.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(ai(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?_i(t):gi(t),t instanceof W){let e=new W(a,[]);return this.promises.push({parent:r,property:n,promise:e}),e}return this.hooks.push(a),new hi(a)}case`function`:case`rpc-target`:{let n=e,r;return r=a?a.getHookForRpcTarget(n,t,i):Ti.create(n,t),this.hooks.push(r),new hi(r)}case`rpc-thenable`:{let o=e,s;return s=a?new W(a.getHookForRpcTarget(o,t,i),[]):new W(Ti.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):H.createWritableStreamHook(n),this.hooks.push(r),n}case`readable`:{let n=e,r;return r=a?a.getHookForReadableStream(n,t,i):H.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 W)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=vi(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 W?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(ai(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=vi(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)):wi(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=H.createWritableStreamHook(t),n.dispose();return}case`readable`:{let t=e,n=this.rpcTargets?.get(t);n?this.rpcTargets.delete(t):n=H.createReadableStreamHook(t),n.dispose();return}default:return}}ignoreUnhandledRejections(){this.hooks?(this.hooks.forEach(e=>{e.ignoreUnhandledRejections()}),this.promises.forEach(e=>yi(e.promise).ignoreUnhandledRejections())):this.ignoreUnhandledRejectionsImpl(this.value)}ignoreUnhandledRejectionsImpl(e){switch(ai(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`:yi(e).ignoreUnhandledRejections();return;case`rpc-thenable`:e.then(e=>{},e=>{});return;default:return}}};function Si(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(ai(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}=bi(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 W){let{hook:t,pathIfPromise:n}=bi(e);return{hook:t,remainingPath:n||[]}}return{value:e,parent:t,owner:r}}var Ci=class extends li{call(e,t){let n;try{let{value:t,owner:r}=this.getValue();n=Si(t,void 0,e,r)}catch(e){return t.dispose(),new U(e)}return n.hook?n.hook.call(n.remainingPath,t):typeof n.value==`function`?new Ei(t.deliverCall(n.value,n.parent).then(e=>new K(e))):(t.dispose(),new U(TypeError(`'${e.join(`.`)}' is not a function.`)))}map(e,t,n){try{let r;try{let{value:t,owner:n}=this.getValue();r=Si(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):si.applyMap(r.value,r.parent,r.owner,t,n)}catch(e){return new U(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=Si(t,void 0,e,n);return r.hook?r.hook.get(r.remainingPath):new K(G.deepCopyFrom(r.value,r.parent,r.owner))}catch(e){return new U(e)}}},K=class e extends Ci{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(G.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 hi&&this.payload.value.onRpcBroken(e)}};function wi(e){if(Symbol.dispose in e)try{e[Symbol.dispose]()}catch(e){Promise.reject(e)}}var Ti=class e extends Ci{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=>G.fromAppReturn(e)):Promise.reject(Error(`Tried to resolve a non-promise stub.`))}ignoreUnhandledRejections(){}dispose(){this.target&&=(this.refcount&&--this.refcount.count==0&&wi(this.target),void 0)}onBroken(e){let t=this.target;t&&`then`in t&&Promise.resolve(t).then(()=>{},e)}},Ei=class e extends li{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)}},Di={maxBigIntDigits:16384,maxDepth:256,maxMessageSize:33554432},Oi=new Uint8Array(new Uint16Array([1]).buffer)[0]===1,ki=[`ArrayBuffer`,`DataView`,`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`Int16Array`,`Uint16Array`,`Int32Array`,`Uint32Array`,`BigInt64Array`,`BigUint64Array`,`Float32Array`,`Float64Array`];function Ai(e){return ki.includes(e)}var ji={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},Mi={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},Ni=new Map;for(let e of Object.keys(Mi))Ni.set(Mi[e],e);function Pi(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 Fi=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 Ii(e,t){let n=await new Response(e).blob();return n.type===t?n:n.slice(0,n.size,t)}var Li={__proto__:null,Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError},Ri=class e{exporter;source;encodingLevel;constructor(e,t,n){this.exporter=e,this.source=t,this.encodingLevel=n}static devaluate(t,n,r=Fi,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(ai(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=Ni.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=ji[t];!Oi&&i&&(n=n.slice(),Pi(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=H.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=H.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}=bi(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 Di}};function zi(e,t){return new W(new Ei(new Response(t).arrayBuffer().then(t=>{let n=new Uint8Array(t),r=new Request(e,{body:n});return new K(G.fromAppReturn(r))})),[])}function Bi(e,t){return new W(new Ei(Ii(e,t).then(e=>new K(G.fromAppReturn(e)))),[])}var Vi=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=G.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(!Ai(t[2])){let e=t[2].slice(0,64);throw TypeError(`Unknown bytes type marker: ${e}`)}let n=t[2],r=ji[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(!Oi&&r!==void 0&&Pi(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=Li[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=zi(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=Bi(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 W(e,[]);return this.promises.push({promise:t,parent:n,property:r}),t}return this.hooks.push(e),new W(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 W(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 W(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 hi(e)}}break;case`writable`:if(typeof t[1]==`number`){let e=this.importer.importStub(t[1]),n=H.createWritableStreamFromHook(e);return this.hooks.push(e),n}break;case`readable`:if(typeof t[1]==`number`){let e=this.importer.getPipeReadable(t[1]),n=H.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}},Hi=16,Ui=8,Wi=16,Gi=64;function Ki(e){return 2+e.length*3}function qi(e,t,n=0){if(n>=Gi)return Ui;switch(typeof e){case`string`:return Ki(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 Wi+e.byteLength;if(typeof Blob<`u`&&e instanceof Blob)return Wi+e.size;if(e instanceof Date)return 16;if(t??=new WeakSet,t.has(e))return Ui;if(t.add(e),e instanceof Array){let r=Hi;for(let i of e)r+=Ui+qi(i,t,n+1);return r}if(e instanceof Error){let r=Hi+Ki(e.name)+Ki(e.message)+Ki(e.stack??``);for(let i of Object.keys(e))r+=Ui+Ki(i)+qi(e[i],t,n+1);return r}let r=Hi;for(let i of Object.keys(e))r+=Ui+Ki(i)+qi(e[i],t,n+1);return r}default:return 16}}var Ji=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 U(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)}},Yi=class e extends li{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)}},Xi=class extends Yi{session;constructor(e){super(!1,e),this.session=e.session}dispose(){if(this.session){let e=this.session;this.session=void 0,e.shutdown()}}},Zi=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={...Di,...n.limits},this.exports.push({hook:t,refcount:1}),this.imports.push(new Ji(this,0,!1)),this.readLoop().catch(e=>this.abort(e))}getMainImport(){return new Xi(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,Ri.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 hi){let{hook:n,pathIfPromise:r}=bi(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=Ri.devaluate(t.value,void 0,this,t,this.encodingLevel);this.send([`resolve`,e,n]),r&&this.releaseExport(e,1)},t=>{this.send([`reject`,e,Ri.devaluate(t,void 0,this,void 0,this.encodingLevel)]),r&&this.releaseExport(e,1)}).catch(t=>{try{this.send([`reject`,e,Ri.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 Yi&&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 Ji(this,e,!1),this.imports[e]=t),new Yi(!1,t)}importPromise(e){if(this.abortReason)throw this.abortReason;if(this.imports[e])return new U(Error(`Bug in RPC system: The peer sent a promise reusing an existing export ID.`));let t=new Ji(this,e,!0);return this.imports[e]=t,new Yi(!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 Ji(this,n,!1);this.imports.push(r);let i=new Yi(!1,r),a=H.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=Ri.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 Ji(this,this.imports.length,!1);return this.imports.push(i),new Yi(!0,i)}sendStream(e,t,n){if(this.abortReason)throw n.dispose(),this.abortReason;let r=[`pipeline`,e,t],i;try{i=Ri.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=qi(a));let s=this.imports.length,c=new Ji(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 Ji(this,this.imports.length,!1);return this.imports.push(a),new Yi(!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`,Ri.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 K(new Vi(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 K(new Vi(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=H.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 K(new Vi(this,this.encodingLevel).evaluate(n[2])));else{let e=new Vi(this,this.encodingLevel).evaluate(n[2]);e.dispose(),t.resolve(new U(e.value))}}else n[0]==`resolve`&&new Vi(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 Vi(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}},Qi=class{#e;#t;constructor(e,t,n={}){let r;r=t?new K(G.fromAppReturn(t)):new U(Error(`This connection has no main object.`)),this.#e=new Zi(e,r,n),this.#t=new hi(this.#e.getMainImport())}getRemoteMain(){return this.#t}getStats(){return this.#e.getStats()}drain(){return this.#e.drain()}};function $i(e,t,n){return new Qi(new ea(e),t,n).getRemoteMain()}var ea=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))}},ta,na=class{context;captureMap=new Map;instructions=[];constructor(e,t){this.context=ta?{parent:ta,captures:[],subject:ta.capture(e),path:t}:{parent:void 0,captures:[],subject:e,path:t},ta=this}unregister(){ta=this.context.parent}makeInput(){return new ia(this,0)}makeOutput(e){let t;try{t=Ri.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 ia(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=Ri.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 ia(this,this.instructions.length)}pushGet(e,t){let n=this.capture(e.dup());return this.instructions.push([`pipeline`,n,t]),new ia(this,this.instructions.length)}capture(e){if(e instanceof ia&&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){}};si.sendMap=(e,t,n)=>{let r=new na(e,t),i;try{i=G.fromAppReturn(fi(r.pushCall.bind(r),()=>n(new W(r.makeInput(),[]))))}finally{r.unregister()}if(i instanceof Promise)throw i.catch(e=>{}),Error(`RPC map() callbacks cannot be async.`);return new W(r.makeOutput(i),[])};function ra(){throw Error(`Attempted to use an abstract placeholder from a mapper function. Please make sure your map function has no side effects.`)}var ia=class extends li{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(ta)return ta.pushGet(this,e);ra()}call(e,t){t.dispose(),ra()}map(e,t,n){for(let e of t)e.dispose();ra()}pull(){ra()}ignoreUnhandledRejections(){}onBroken(e){ra()}},aa=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 Vi(this).evaluateCopy(t);if(e.value instanceof hi){let t=vi(e.value);if(t){this.variables.push(t);continue}}this.variables.push(new K(e))}return new Vi(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 Di}};function oa(e,t,n,r,i){let a=new aa(r,new K(G.deepCopyFrom(e,t,n)));try{return a.apply(i)}finally{a.dispose()}}si.applyMap=(e,t,n,r,i)=>{try{let a;if(e instanceof W)throw Error(`applyMap() can't be called on RpcPromise`);if(e instanceof Array){let t=[];try{for(let a of e)t.push(oa(a,e,n,r,i))}catch(e){for(let e of t)e.dispose();throw e}a=G.fromArray(t)}else a=e==null?G.fromAppReturn(e):oa(e,t,n,r,i);return new K(a)}finally{for(let e of r)e.dispose()}};var sa=class e extends li{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 Ei((r===`write`?t.deliverStreamWrite(n.writer):t.deliverCall(n.writer[r],n.writer)).then(e=>new K(e)))}catch(e){return t.dispose(),new U(e)}}map(e,t,n){for(let e of t)e.dispose();return new U(Error(`Cannot use map() on a WritableStream`))}get(e){return new U(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)}},ca=262144,la=1073741824,ua=65536,da=2,fa=1.25,pa=.9,ma=3,ha=class{now;window=ca;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?da:fa,s=a*this.minRtt*o;s=Math.min(s,e.windowAtSend*o),s=e.windowFullAtSend?Math.max(s,e.windowAtSend*pa):Math.max(s,this.window),this.window=Math.max(Math.min(s,la),ua),this.inStartupPhase&&e.sentTime>=this.roundStartTime&&(this.window>this.lastRoundWindow*fa?this.roundsWithoutIncrease=0:++this.roundsWithoutIncrease>=ma&&(this.inStartupPhase=!1),this.roundStartTime=t,this.lastRoundWindow=this.window)}return this.bytesInFlight<this.window}};function ga(e){let t,n=!1,r=new ha(()=>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=G.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`],G.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`],G.fromAppParams([n]));r.then(()=>o(),()=>o())}})}var _a=class e extends li{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 U(Error(`Cannot call methods on a ReadableStream stub`))}map(e,t,n){for(let e of t)e.dispose();return new U(Error(`Cannot use map() on a ReadableStream`))}get(e){return new U(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){}};H.createWritableStreamHook=sa.create,H.createWritableStreamFromHook=ga,H.createReadableStreamHook=_a.create;var va=hi,ya=ni,ba=$i;function xa(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 Sa(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 Ca(e,t){if(t.kind===`action`){let n=[...e.primary??[],...e.menu??[]].find(e=>e.id===t.actionId);return n!==void 0&&n.disabled!==!0}let n=e.crumbs?.find(e=>e.id===t.crumbId);return n===void 0?!1:t.siblingId===void 0||n.siblings?.some(e=>e.id===t.siblingId)===!0}var wa=`fungi.app.ready`,Ta=`fungi.app.connect`,q=e=>g.pipe(T(rt(1)),T(k(e))),Ea=e=>_(q(e)),Da=x.pipe(T(_e()),T(tt(Number.isSafeInteger,{message:`Expected a safe integer`}))),Oa=Da.pipe(T(Ne(0))),ka=Da.pipe(T(Fe(0))),Aa=t({appId:q(160),releaseId:q(160),surfaceId:q(160)}),ja=t({editing:b,surface:D([q(160),p])}),Ma=D([t({kind:u(`compose`),requestId:q(160),text:q(2e3)}),t({kind:u(`navigate`),requestId:q(160),params:d(t({key:q(64),value:q(4096)})).pipe(T(k(16)))})]),J=i(h([`granted`,`missing`])),Na=t({"agent.list":J,"agent.manage":J,"agent.read":J,"agent.send":J,"computer.list":J,"computer.readFile":J,"computer.writeFile":J,"computer.execute":J,"git.repository":J,"workflow.publish":J,"workflow.arm":J,"workflow.run":J,"app.events.emit":J,"llm.generation":J,"media.generation":J,"media.share":J}),Pa=h([`ready`,`missing`,`unknown`]),Fa=t({models:Pa,media:Pa,git:Pa,terminal:h([`ready`,`exec-only`,`missing`,`unknown`]),terminalReason:_(g)}),Ia=h([`model`,`media`,`git`,`computer`]),La=h([`opened`,`unavailable`]),Ra=t({computerId:D([q(256),p]),teamHasComputers:_(he(b)),computerAccessGranted:_(b),setup:_(Fa),permissions:_(Na),focus:ja,openRequest:D([p,Ma]),visibility:h([`visible`,`hidden`])}),za=h([`connecting`,`connected`,`suspended`,`disconnected`,`disposing`,`disposed`]),Ba=t({altKey:b,ctrlKey:b,id:q(160),key:q(64),metaKey:b,shiftKey:b}),Va=t({action:_(w),availability:_(w),category:q(160),description:Ea(512),id:q(160),projections:_(w),title:q(160)}),Ha=t({arguments:_(w),commandId:q(321),origin:h([`agent`,`browser`,`keyboard`,`menu`,`palette`,`programmatic`,`slash`,`terminal`]),requestId:q(160)}),Ua=D([t({result:_(w),status:u(`handled`)}),t({error:w,status:u(`failed`)})]),Wa=e=>q(e).pipe(T(tt(e=>{for(let t=0;t<e.length;t+=1)if(xa(e.charCodeAt(t)))return!1;return!0},{message:`Expected one line of plain text`}))),Ga={id:q(64),text:Wa(80),end:i(b),priority:i(u(`low`))},Ka=i(x.pipe(T(_e()),T(Ve({minimum:0,maximum:9999})))),qa=d(D([t({...Ga,kind:u(`text`),tone:i(h([`neutral`,`success`,`warning`,`error`]))}),t({...Ga,kind:u(`button`),icon:i(h([`folder`,`ports`,`processes`,`access`])),count:Ka,tone:i(h([`neutral`,`success`,`warning`,`error`])),busy:i(b),title:i(Wa(1024)),disabled:i(b),opens:i(u(`dialog`)),expanded:i(b)}),t({...Ga,kind:u(`toggle`),pressed:b}),t({...Ga,kind:u(`menu`),count:Ka,title:i(Wa(1024)),options:d(t({id:q(64),text:Wa(80),checked:i(b),disabled:i(b)})).pipe(T(k(16)),T(tt(e=>new Set(e.map(e=>e.id)).size===e.length,{message:`Expected unique status option ids`})))})])).pipe(T(k(6)),T(tt(e=>new Set(e.map(e=>e.id)).size===e.length,{message:`Expected unique status item ids`}))),Ja=t({computerId:q(256),path:q(1024)}),Ya=q(80).pipe(T(tt(e=>e.trim()===e,{message:`Expected a trimmed title`}))),Xa=q(64),Za=q(80),Qa=e=>new Set(e.map(e=>e.id)).size===e.length,$a=t({id:Xa,label:Za,siblings:_(d(t({id:Xa,label:Za})).pipe(T(k(16)),T(tt(Qa,{message:`Expected unique crumb sibling ids`}))))}),eo=t({id:Xa,label:Za,icon:_(u(`play`)),variant:_(h([`primary`,`outline`,`ghost`])),tone:_(u(`destructive`)),disabled:_(b)}),to=e=>d(eo).pipe(T(k(e)),T(tt(Qa,{message:`Expected unique header command ids`}))),no=t({id:Xa,label:Za,presentation:_(u(`bead`)),tone:_(h([`neutral`,`info`,`warning`,`success`,`error`]))}),ro={status:_(d(no).pipe(T(k(4)),T(tt(Qa,{message:`Expected unique header status ids`})))),crumbs:_(d($a).pipe(T(k(8)),T(tt(Qa,{message:`Expected unique crumb ids`})))),primary:_(to(3)),menu:_(to(12))},io=t({contractVersion:u(1),canGoBack:b,title:_(Ya),...ro}),ao=t({canGoBack:b,title:_(g),...ro}),oo=D([t({kind:u(`crumb`),crumbId:Xa,siblingId:_(Xa)}),t({kind:u(`action`),actionId:Xa})]),so=he(t({agentId:q(256),sessionId:q(256)})),co=e=>_(d(h(e)).pipe(T(k(e.length)))),lo=t({agents:_(d(h([`agent.list`,`agent.manage`,`agent.read`,`agent.send`])).pipe(T(k(4)))),computers:_(d(h([`computer.list`,`computer.readFile`,`computer.writeFile`,`computer.execute`])).pipe(T(k(4)))),git:co([`git.repository`]),workflows:co([`workflow.publish`,`workflow.arm`,`workflow.run`]),events:co([`app.events.emit`]),generation:co([`llm.generation`,`media.generation`,`media.share`])}),uo=h([`granted`,`declined`,`customize`]),fo=t({message:q(512),tone:_(h([`info`,`success`,`warning`,`error`]))}),po=h(fe);t({code:po.pick([`DELIVERY_PENDING`])});var mo=t({code:po,message:q(512),retryable:b,need:i(te)}),ho=t({protocolVersion:u(2),type:u(wa)}),go=t({epoch:q(160),protocolVersion:u(2),type:u(Ta)}),_o=t({epoch:q(160),protocolVersion:u(2)}),vo={[Symbol.dispose]:_(w)},yo=D([t({...vo,ok:u(!0),value:w}),t({...vo,error:mo,ok:u(!1)})]);function Y(e,t,n=`PROTOCOL`){return We(ze(e,{onExcessProperty:`error`}),ot({onFailure:e=>{throw new y(`The peer sent malformed protocol data`,{cause:e,code:n,retryable:!1})},onSuccess:t}))}function X(e){return Object.freeze(e)}function bo(e,t){let n=e.arguments===void 0?void 0:In(e.arguments),r={origin:e.origin,signal:t};return n!==void 0&&Object.assign(r,{arguments:n}),X(r)}var xo=Y(Va,e=>{let t={category:e.category,id:e.id,title:e.title};return e.action!==void 0&&Object.assign(t,{action:e.action}),e.availability!==void 0&&Object.assign(t,{availability:e.availability}),e.description!==void 0&&Object.assign(t,{description:e.description}),e.projections!==void 0&&Object.assign(t,{projections:e.projections}),X(fs(()=>Jn(t)))},`INVALID_ARGUMENT`),So=Y(q(321),e=>e),Co=Y(Ha,e=>{let t=e.arguments===void 0?void 0:In(e.arguments),n={commandId:e.commandId,origin:e.origin,requestId:e.requestId};return t!==void 0&&Object.assign(n,{arguments:t}),X(n)}),wo=Y(D([Ge,w]),e=>e===void 0?void 0:In(e)),To=Y(go,e=>X(e));Y(_o,e=>X(e));var Eo=Y(Ra,e=>{let t={computerId:e.computerId,focus:X({...e.focus}),openRequest:e.openRequest===null?null:X({...e.openRequest}),visibility:e.visibility};return e.teamHasComputers!==void 0&&(t.teamHasComputers=e.teamHasComputers),e.computerAccessGranted!==void 0&&(t.computerAccessGranted=e.computerAccessGranted),e.setup!==void 0&&(t.setup=X({...e.setup})),e.permissions!==void 0&&(t.permissions=X({...e.permissions})),X(t)}),Do=Y(mo,e=>X({...e})),Oo=Y(ja,e=>X({...e}),`INVALID_ARGUMENT`),ko=Y(Aa,e=>X({...e})),Ao=Y(za,e=>e),jo=Y(qa,e=>X(e.map(e=>e.kind===`menu`?X({...e,options:X(e.options.map(e=>X(e)))}):X(e))),`INVALID_ARGUMENT`),Mo=Y(t({itemId:q(64),optionId:i(q(64)),anchor:i(t({start:x.pipe(T(Ve({minimum:0,maximum:1e5}))),width:x.pipe(T(Ve({minimum:0,maximum:1e5})))}))}),e=>X(e.anchor===void 0?{...e}:{...e,anchor:X({...e.anchor})}),`INVALID_ARGUMENT`),No=Y(Ja,e=>X({...e}),`INVALID_ARGUMENT`);function Po(e){let t={id:e.id,label:e.label};return e.presentation!==void 0&&(t={...t,presentation:e.presentation}),e.tone!==void 0&&(t={...t,tone:e.tone}),X(t)}function Fo(e){let t={id:e.id,label:e.label};return e.siblings===void 0?X(t):X({...t,siblings:X(e.siblings.map(e=>X({...e})))})}function Io(e){let t={id:e.id,label:e.label};return e.icon!==void 0&&(t={...t,icon:e.icon}),e.variant!==void 0&&(t={...t,variant:e.variant}),e.tone!==void 0&&(t={...t,tone:e.tone}),e.disabled!==void 0&&(t={...t,disabled:e.disabled}),X(t)}function Lo(e){let t={canGoBack:e.canGoBack};return e.title!==void 0&&(t={...t,title:e.title}),e.crumbs!==void 0&&(t={...t,crumbs:X(e.crumbs.map(Fo))}),e.primary!==void 0&&(t={...t,primary:X(e.primary.map(Io))}),e.menu!==void 0&&(t={...t,menu:X(e.menu.map(Io))}),e.status!==void 0&&(t={...t,status:X(e.status.map(Po))}),X(t)}var Ro=Y(io,Lo,`INVALID_ARGUMENT`),zo=Y(ao,e=>{let t=e.title?.trim();return Bo({...Lo({...e,title:t===void 0||t.length===0?void 0:t}),contractVersion:1})},`INVALID_ARGUMENT`),Bo=Y(io,e=>X({...Lo(e),contractVersion:1}),`INVALID_ARGUMENT`),Vo=Y(oo,e=>e.kind===`action`?X({...e}):X(e.siblingId===void 0?{kind:e.kind,crumbId:e.crumbId}:e),`INVALID_ARGUMENT`),Ho=Y(so,e=>e===null?null:X({...e}),`INVALID_ARGUMENT`),Uo=Y(lo,e=>X({agents:X([...new Set(e.agents??[])]),computers:X([...new Set(e.computers??[])]),...e.git&&{git:X([...new Set(e.git)])},...e.workflows&&{workflows:X([...new Set(e.workflows)])},...e.events&&{events:X([...new Set(e.events)])},...e.generation&&{generation:X([...new Set(e.generation)])}}),`INVALID_ARGUMENT`),Wo=Y(Ia,e=>e,`INVALID_ARGUMENT`);Y(ho,e=>X(e));var Go=Y(q(512),e=>e),Ko=Y(fo,e=>X({...e}),`INVALID_ARGUMENT`);Y(t({id:q(160),repeat:b}),e=>X(e));var qo=Y(d(Ba).pipe(T(k(64))),e=>{if(new Set(e.map(e=>e.id)).size!==e.length)throw new y(`Reserved chords are invalid`,{code:`PROTOCOL`,retryable:!1});return X(e.map(e=>X({...e})))});function Jo(e){return Y(t({value:w,version:Oa}),t=>X({value:e(t.value),version:t.version}))}var Yo=Jo(Eo),Xo=Y(t({capabilities:d(w).pipe(T(k(128))),context:w}),e=>X({capabilities:X(e.capabilities.map(e=>ns(e))),context:Yo(e.context)})),Zo=Jo(Ao),Qo=Jo(qo),$o=Jo(Go),es=We(Zo,e=>{if(e.value!==`connected`&&e.value!==`suspended`)throw new y(`The host lifecycle is invalid`,{code:`PROTOCOL`,retryable:!1});return X({value:e.value,version:e.version})});function ts(e){return Y(t({handle:w,id:q(160),version:ka}),t=>{if(!(t.handle instanceof va)&&!(e&&t.handle instanceof ya))throw new y(`A capability handle is invalid`,{code:`PROTOCOL`,retryable:!1});return X({handle:t.handle,id:t.id,version:t.version})})}var ns=ts(!1),rs=ts(!0);function is(e){let n=e?rs:ns;return Y(t({capabilities:d(w).pipe(T(k(128))),context:w,identity:w,lifecycle:w,reservedChords:w,theme:w}),e=>X({capabilities:X(e.capabilities.map(e=>n(e))),context:Yo(e.context),identity:ko(e.identity),lifecycle:es(e.lifecycle),reservedChords:Qo(e.reservedChords),theme:$o(e.theme)}))}var as=is(!1);is(!0);function os(e){return Y(yo,t=>t.ok?X({ok:!0,value:e(t.value)}):X({ok:!1,error:Do(t.error)}))}var ss=os(as),cs=os(Y(t({commandId:q(321)}),e=>X(e)));os(Y(Ua,e=>{if(e.status===`failed`)return X({status:`failed`,error:fs(()=>Rn(e.error))});let t=e.result===void 0?void 0:In(e.result);return X(t===void 0?{status:`handled`}:{status:`handled`,result:t})}));var ls=os(Y(Ge,()=>void 0)),us=os(Y(uo,e=>e)),ds=os(Y(La,e=>e));os(Y(b,e=>e)),os(Y(b,e=>e));function fs(e){try{return e()}catch(e){throw new y(`The command metadata is invalid`,{cause:e,code:`INVALID_ARGUMENT`,retryable:!1})}}var ps=D([t({kind:u(`saveFile`),name:q(255).pipe(T(xe(/^[^\p{Cc}/\\]+$/u))),mime:q(255),bytes:Ze}),t({kind:u(`copyText`),text:g})]);function ms(e){let t=ze(ps,{onExcessProperty:`error`})(e);if(ae(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 hs=os(Y(D([t({kind:u(`saved`)}),t({kind:u(`copied`)}),t({kind:u(`refused`),reason:h([`no-user-gesture`,`too-large`,`invalid-request`,`unavailable`,`denied`,`busy`])})]),e=>X(e)));function gs(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 _s(e){let t=new Map,n=gs(0),r=!1,i=e=>{let t=new Map;try{for(let n of e){let e=ns(n),r=xs(e.id,e.version);if(t.has(r))throw ys(e.handle),new y(`Duplicate capability grant`,{code:`PROTOCOL`,retryable:!1});t.set(r,e.handle)}}catch(e){for(let e of t.values())ys(e);throw e}return t};for(let[n,r]of i(e))t.set(n,r);let a=e=>{for(let t of e)ys(t)},o=e=>{if(r)throw new y(`The app connection is disposed`,{code:`DISCONNECTED`,retryable:!0});let n=xs(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 y(`The capability is not granted`,{code:`CAPABILITY_DENIED`,retryable:!1});try{return e.schema.parse(t)}catch(e){throw new y(`The capability interface is malformed`,{cause:e,code:`PROTOCOL`,retryable:!1})}}}),replace(e){if(r)throw new y(`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 vs=M().transform(e=>{let n=Ee(Object).safeParse(e);if(!n.success)return;let r=Object.create(n.data),i=O(t({[Symbol.dispose]:_(je(Function))}))(r);return{owner:n.data,dispose:i[Symbol.dispose]}});function ys(e){try{let t=vs.parse(e);if(t===void 0||bs.has(t.owner))return;bs.add(t.owner),t.dispose?.call(t.owner)}catch(e){console.warn(`RPC value disposal failed`,e)}}var bs=new WeakSet;function xs(e,t){return`${e}@${String(t)}`}function Ss(e){let t=(0,N.useCallback)(t=>e?.subscribe(t)??(()=>void 0),[e]),n=(0,N.useCallback)(()=>e?.get(),[e]);return(0,N.useSyncExternalStore)(t,n,n)}function Cs(e){return Ss(e?.context)??null}function ws(e){return Cs(e)?.computerId??null}function Ts(e,t,n,r){let i=(0,N.useRef)(t);i.current=t;let a=(0,N.useRef)(n);a.current=n;let o=(0,N.useRef)(r);o.current=r;let s=JSON.stringify(t),c=n!==void 0;(0,N.useEffect)(()=>{e&&e.ui.reportStatus(i.current).catch(e=>{o.current?o.current(e):console.error(`Window status report failed`,e)})},[e,s]),(0,N.useEffect)(()=>{if(!(!e||!c))return e.ui.onStatusAction(e=>a.current?.(e)??!1)},[e,c]),(0,N.useEffect)(()=>()=>{e?.ui.reportStatus([]).catch(e=>{console.error(`Window status report failed`,e)})},[e])}function Es(e,{sourceId:t,namespace:n},r){let i=(0,N.useMemo)(()=>ar(),[]),a=(0,N.useMemo)(r,[r]);return(0,N.useEffect)(()=>{let e=i.contribute({sourceId:t,namespace:n,commands:a});return()=>{e.dispose()}},[i,t,n,a]),(0,N.useEffect)(()=>e?Qr(e.commands,a):void 0,[e,a]),i}function Ds(e,{canGoBack:t,title:n,crumbs:r,primary:i,menu:a,status:o,onBack:s,onCrumb:c,onAction:l}){let u=(0,N.useRef)(s),d=(0,N.useRef)(c),f=(0,N.useRef)(l);(0,N.useEffect)(()=>{u.current=s,d.current=c,f.current=l},[s,c,l]),(0,N.useEffect)(()=>{if(!e)return;let t=e.onBack(()=>u.current()),n=e.onActivate(e=>{if(e.kind===`action`){let t=f.current;return t?.(e.actionId),t!==void 0}let t=d.current;return e.siblingId===void 0?t?.(e.crumbId):t?.(e.crumbId,e.siblingId),t!==void 0});return()=>{t(),n(),Os(e,{canGoBack:!1})}},[e]);let ee=JSON.stringify([r,i,a,o]),p=(0,N.useRef)({crumbs:r,primary:i,menu:a,status:o});(0,N.useEffect)(()=>{p.current={crumbs:r,primary:i,menu:a,status:o}},[r,i,a,o]),(0,N.useEffect)(()=>{if(!e)return;let r={canGoBack:t};n!==void 0&&(r={...r,title:n});let i=p.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}),Os(e,r)},[e,t,n,ee])}function Os(e,t){e.publish(t).catch(e=>{e instanceof y&&e.code===`DISCONNECTED`||console.warn(`App navigation report failed`,e)})}var ks=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 As(e,t,n){return new ks(e,t,n)}function js(e){let t=j(e),n=Ee(Object),r=j(Object.fromEntries(Object.keys(e).map(e=>[e,M().optional()])));return M().transform(e=>{let i=n.parse(e),a=Object.create(i),o=r.parse(a),s=Object.fromEntries(Object.entries(o).map(([e,t])=>[e,Xe().parse(t).bind(i)]));return{...t.parse(s),[Symbol.dispose](){ys(e)}}})}function Z(e){return M().transform(t=>{try{return e.parse(t)}catch(e){throw e instanceof y?e:new y(`The capability returned malformed data`,{cause:e,code:`PROTOCOL`,retryable:!1})}finally{ys(t)}})}function Q(e){return Xe({output:at(M().transform(t=>{try{return e.parse(t)}catch(e){throw ys(t),e instanceof y?e:new y(`The capability returned a malformed result`,{cause:e,code:`PROTOCOL`,retryable:!1})}}))})}var Ms=Q(Z(Be()));js({fetch:Q(Ee(Response)),close:Ms});function Ns(e){return e instanceof y?e:new y(`App operation failed`,{cause:e,code:`HOST_FAILURE`,retryable:!1})}var Ps=new WeakMap,Fs={of(e,...t){return[e?.identity.surfaceId??null,e?.context.get().computerId??null,...t]}};function Is(e){let t={};return e&&Ps.set(t,e),t}function Ls(){let e=new yn({defaultOptions:{queries:{retry:!1,staleTime:3e4,refetchOnWindowFocus:!1},mutations:{retry:!1}}}),t=new Map;return e.getQueryCache().subscribe(n=>{let r=n.query;if(n.type===`removed`){t.get(r.queryHash)?.release(),t.delete(r.queryHash);return}let i=r.meta&&Ps.get(r.meta),a=t.get(r.queryHash);if(a?.app===i||(a?.release(),t.delete(r.queryHash),!i))return;let o=()=>{queueMicrotask(()=>{e.getQueryCache().get(r.queryHash)===r&&t.get(r.queryHash)?.app===i&&e.resetQueries({predicate:e=>e===r})})},s=i.capabilities.subscribe(o);t.set(r.queryHash,{app:i,release:s}),a&&o()}),e}function Rs(e,t,n,r){let i=e?.context.get().computerId;return jn({queryKey:n,meta:Is(e),enabled:e!==null,retry:!1,queryFn:async({signal:n})=>{try{if(!e)throw new y(`No App connection`,{code:`DISCONNECTED`,retryable:!0});if(e.context.get().computerId!==i)throw new y(`The selected Computer changed`,{code:`SELECTION_CHANGED`,retryable:!1});return await r(e.capabilities.require(t),n)}catch(e){throw Ns(e)}}})}var zs=we(De(t({error:u(`too_large`)})));async function Bs(e,t){let n,r=()=>n??=e.close(),i=()=>{r().catch(e=>{$r(`files.read.abort-close`,e)})};t.signal?.addEventListener(`abort`,i,{once:!0});try{t.signal?.throwIfAborted();let n=await e.response();try{let e=O(je(Response))(n);if(e.status===413){let t=zs(await e.text());throw new y(`App file exceeds the read bound`,{code:t._tag===`Some`?`FILE_TOO_LARGE`:`PROTOCOL`,retryable:!1})}if(!e.ok)throw Error(`App file unavailable (${String(e.status)})`);let r=await e.blob();return t.signal?.throwIfAborted(),new File([r],t.name,{type:r.type,lastModified:0})}finally{ys(n)}}finally{t.signal?.removeEventListener(`abort`,i);try{await r()}finally{e[Symbol.dispose]()}}}async function Vs(e,t,n){let r,i=()=>r??=e.close(),a=()=>{i().catch(e=>{$r(`files.write.abort-close`,e)})};n.signal?.addEventListener(`abort`,a,{once:!0});try{n.signal?.throwIfAborted(),await e.write(t.stream())}finally{n.signal?.removeEventListener(`abort`,a);try{await i()}catch(e){$r(`files.write.remote-close`,e)}try{e[Symbol.dispose]()}catch(e){$r(`files.write.local-dispose`,e)}}}var Hs=t({path:g,entries:d(t({name:g,type:h([`file`,`directory`,`symlink`]),size:x,modifiedAt:x})),nextOffset:he(x)}),Us=As(`computer.list`,1,C(()=>js({list:Q(Z(M().transform(e=>O(Hs)(e))))}))),Ws=D([t({state:h([`running`,`sleeping`,`starting`,`start_failed`])}),t({state:u(`queued`),position:x.pipe(T(_e()),T(Fe(0)))})]),Gs=t({enabled:b,effective:b,blockedBy:he(h([`team`,`global`]))}),Ks=t({computerId:Je,name:Je,runtime:Ws,backends:d(t({id:Je,kind:h([`platform-container`,`on-box-vm`,`local`]),status:h([`ready`,`queued`,`online`,`offline`]),queuePosition:he(x.pipe(T(_e()),T(Fe(0)))),hostId:he(g),hostLabel:he(g),folderLabel:he(g),detachable:b})),internet:Gs});As(`computer.instrument.read`,1,C(()=>js({read:Q(Z(M().transform(e=>O(Ks)(e))))}))),As(`computer.instrument.control`,1,C(()=>js({start:Q(Z(M().transform(e=>O(Ws)(e)))),setInternetAccess:Q(Z(M().transform(e=>O(Gs)(e)))),detachLocal:Q(Z(M().transform(e=>O(t({detached:b}))(e))))})));var qs=t({ports:d(t({port:x.pipe(T(_e()),T(Ve({minimum:1,maximum:65535}))),previewUrl:Je,openMode:h([`inline`,`external-only`]),expiresAt:x.pipe(T(_e()),T(Fe(0)))})).pipe(T(k(64)))}),Js=D([qs,t({error:u(`port_previews_not_configured`)})]),Ys=t({port:x.annotate({message:`Use a port from 1 to 65535.`}).check(_e({message:`Use a port from 1 to 65535.`}),Ve({minimum:1,maximum:65535},{message:`Use a port from 1 to 65535.`})),exposed:b}),Xs=t({port:x.pipe(T(_e()),T(Ve({minimum:1,maximum:65535}))),removed:b});As(`computer.ports`,2,C(()=>js({list:Q(Z(M().transform(e=>O(Js)(e)))),expose:Q(Z(M().transform(e=>O(Ys)(e)))),unexpose:Q(Z(M().transform(e=>O(Xs)(e))))})));var Zs=h([`synced`,`pending`,`unknown`]),Qs=t({port:he(Ys.fields.port),id:Je,command:Je,cwd:he(g),startedAt:x.pipe(T(_e()),T(Ne(0))),state:h([`running`,`exited`,`uncertain`]),exitCode:he(x.pipe(T(_e()))),sync:Zs,endedAt:he(x.pipe(T(_e()),T(Ne(0))))}),$s=t({processes:d(Qs)}),ec=t({process:Qs,signalled:b}),tc=t({process:Qs,lines:d(g.pipe(T(k(2e3)))).pipe(T(k(200))),truncated:b});t({requestId:Je.pipe(T(k(256))),command:Je.pipe(T(k(16384))),cwd:i(g),port:i(Ys.fields.port)}),As(`computer.processes`,1,C(()=>js({start:Q(Z(M().transform(e=>O(Qs)(e)))),list:Q(Z(M().transform(e=>O($s)(e)))),kill:Q(Z(M().transform(e=>O(ec)(e)))),logs:Q(Z(M().transform(e=>O(tc)(e))))})));var nc=As(`computer.readFile`,1,C(()=>js({open:Q(js({response:Q(Ee(Response)),close:Ms}))})));async function rc(e,t,n){return await Bs(await e.require(nc).open(t),{...n,name:t.path.split(`/`).at(-1)??`file`})}async function ic(e,t){return O(Hs)(await e.require(Us).list(t))}var ac=As(`computer.writeFile`,3,C(()=>js({open:Q(js({write:Ms,close:Ms})),mkdir:Ms,replace:Q(Z(M().transform(e=>O(oc)(e))))}))),oc=D([t({kind:u(`replaced`),path:Je,bytes:x.pipe(T(_e()),T(Ne(0)))}),t({kind:u(`conflict`)})]);async function sc(e,t,n){n.signal?.throwIfAborted();let r=await e.require(ac).replace(t);if(r.kind===`conflict`)throw new y(`Computer file changed since it was opened`,{code:`CONFLICT`,retryable:!1});return{path:r.path,bytes:r.bytes}}var cc=t({computerName:Je.pipe(T(k(256))),teamName:Je.pipe(T(k(256))),modelDoor:Je.pipe(T(k(256))),uptimeSeconds:x.pipe(T(_e()),T(Ne(0))),version:Je.pipe(T(k(64)))});As(`computer.terminal`,2,C(()=>js({open:Q(js({information:Q(Z(M().transform(e=>O(cc)(e)))),output:Q(Ee(ReadableStream).transform(e=>e.pipeThrough(new TransformStream({transform(e,t){t.enqueue(Ee(Uint8Array).parse(e))}})))),input:Q(Ee(WritableStream)),resize:Ms,close:Ms}))})));async function lc(e,t,n){await Vs(await e.require(ac).open({path:t.path}),t.content,n)}var $=ie*10,uc=class{constructor(e={}){let t=!se(e.bounce)||!se(e.duration);this.timeStep=.02,this.restThreshold=5e-4,this.restDuration=200,this.maxDuration=6e4,this.maxRestSteps=this.restDuration/this.timeStep/ie,this.maxIterations=this.maxDuration/this.timeStep/ie,this.bn=A(He(e.bounce,.5),-1,1),this.pd=A(He(e.duration,628),10*s.timeScale,$*s.timeScale),this.m=A(He(e.mass,1),1,$),this.s=A(He(e.stiffness,100),Re,$),this.d=A(He(e.damping,10),Re,$),this.v=A(He(e.velocity,0),-$,$),this.w0=0,this.zeta=0,this.wd=0,this.b=0,this.completed=!1,this.solverDuration=0,this.settlingDuration=0,this.parent=null,this.onComplete=e.onComplete||n,t&&this.calculateSDFromBD(),this.compute(),this.ease=e=>{let t=e*this.settlingDuration,n=this.completed,r=this.pd;return t>=r&&!n&&(this.completed=!0,this.onComplete(this.parent)),t<r&&n&&(this.completed=!1),e===0||e===1?e:this.solve(e*this.solverDuration)}}solve(e){let{zeta:t,w0:n,wd:r,b:i}=this,a=e;return a=t<1?Se(-a*t*n)*(1*it(r*a)+i*ce(r*a)):t===1?(1+i*a)*Se(-a*n):((1+i)*Se((-t*n+r)*a)+(1-i)*Se((-t*n-r)*a))/2,1-a}calculateSDFromBD(){let e=s.timeScale===1?this.pd/ie:this.pd;this.m=1,this.v=0,this.s=a(2*Ie/e,2),this.d=this.bn>=0?(1-this.bn)*4*Ie/e:4*Ie/(e*(1+this.bn)),this.s=et(A(this.s,Re,$),3),this.d=et(A(this.d,Re,300),3)}calculateBDFromSD(){let e=2*Ie/c(this.s);this.pd=e*(s.timeScale===1?ie:1),this.bn=this.d/(2*c(this.s))<=1?1-this.d*e/(4*Ie):4*Ie/(this.d*e)-1,this.bn=et(A(this.bn,-1,1),3),this.pd=et(A(this.pd,10*s.timeScale,$*s.timeScale),3)}compute(){let{maxRestSteps:e,maxIterations:t,restThreshold:n,timeStep:r,m:i,d:a,s:o,v:l}=this,u=this.w0=A(c(o/i),Re,ie),d=this.zeta=a/(2*c(o*i));d<1?(this.wd=u*c(1-d*d),this.b=(d*u+-l)/this.wd):d===1?(this.wd=0,this.b=-l+u):(this.wd=u*c(d*d-1),this.b=(d*u+-l)/this.wd);let f=0,ee=0,p=0;for(;ee<=e&&p<=t;)Pe(1-this.solve(f))<n?ee++:ee=0,this.solverDuration=f,f+=r,p++;this.settlingDuration=et(this.solverDuration*ie,0)*s.timeScale}get bounce(){return this.bn}set bounce(e){this.bn=A(He(e,1),-1,1),this.calculateSDFromBD(),this.compute()}get duration(){return this.pd}set duration(e){this.pd=A(He(e,1),10*s.timeScale,$*s.timeScale),this.calculateSDFromBD(),this.compute()}get stiffness(){return this.s}set stiffness(e){this.s=A(He(e,100),Re,$),this.calculateBDFromSD(),this.compute()}get damping(){return this.d}set damping(e){this.d=A(He(e,10),Re,$),this.calculateBDFromSD(),this.compute()}get mass(){return this.m}set mass(e){this.m=A(He(e,1),1,$),this.compute()}get velocity(){return this.v}set velocity(e){this.v=A(He(e,0),-$,$),this.compute()}},dc=e=>new uc(e),fc=(e=10,t)=>{let n=t?ve:nt;return t=>n(A(t,0,1)*e)*(1/e)},pc=Object.freeze({ease:`linear`,duration:0});function mc(e,t){let n=l(e,t.duration);return n<=0?pc:e.steps>0?{ease:fc(e.steps),duration:n}:{ease:dc({bounce:re(e,t.bounce),duration:n}),duration:n}}function hc(e,t){let n=f(e,t.duration);return{ease:e.steps>0?fc(e.steps):t.ease,duration:n}}var gc={dot:{y:-4,height:8,cy:0},pill:{y:-16,height:32,cy:0},bang:{y:-16,height:20,cy:12}};function _c({className:e,glyph:t,motion:n}){let r=`caps-status-${(0,N.useId)().replaceAll(`:`,``)}`,i=(0,N.useRef)(null),a=(0,N.useRef)(null),o=(0,N.useRef)(null),s=(0,N.useRef)(null),c=(0,N.useRef)(null),l=(0,N.useRef)(null),u=(0,N.useRef)(gc[t]).current,d=(0,N.useRef)(t===`dot`?1:4).current,ee=(0,N.useRef)(+(t===`bang`)).current,p=(0,N.useRef)(t),m=oe(s),{reduced:te}=m;return(0,N.useLayoutEffect)(()=>{if(!i.current||!a.current||!c.current||!l.current)return;let e=gc[t],n=te||p.current===t;p.current=t;let r=ne(i.current),o=n?{duration:0}:mc(r,{bounce:.3,duration:360}),s=E(i.current,{y:e.y,height:e.height,...o}),u=E(a.current,{cy:e.cy,...n?{duration:0}:{delay:f(r,35),...mc(r,{bounce:.3,duration:420})}}),d=E(c.current,{gradientTransform:`matrix(1 0 0 ${t===`dot`?`1`:`4`} 0 0)`,...o}),ee=E(l.current,{opacity:+(t===`bang`),...n?pc:hc(r,{ease:`inOutSine`,duration:220})});return()=>{s.cancel(),u.cancel(),d.cancel(),ee.cancel()}},[t,te]),(0,N.useLayoutEffect)(()=>{if(!o.current||!s.current||te||n===`none`)return;let e=n===`pulse`?E(o.current,{opacity:[1,.45],...hc(m,{ease:`inOutSine`,duration:750}),alternate:!0,loop:!0}):E(o.current,{keyframes:{"0%":{translateY:0,scaleX:1,scaleY:1},"18%":{translateY:.25,scaleX:1.1,scaleY:.91},"42%":{translateY:-1.3,scaleX:.94,scaleY:1.06},"62%":{translateY:-1.65,scaleX:1,scaleY:1},"82%":{translateY:.15,scaleX:1.06,scaleY:.95},"100%":{translateY:0,scaleX:1,scaleY:1}},...hc(m,{ease:`inOutSine`,duration:1e3}),loop:!0}),t=Ye(s.current,t=>{t?e.resume():e.pause()});return()=>{t(),e.revert()}},[n,te,m]),(0,P.jsxs)(`svg`,{ref:s,"aria-hidden":`true`,className:`caps-status-bead ${e??``}`,width:`8`,height:`8`,viewBox:`-4 -4 8 8`,focusable:`false`,children:[(0,P.jsxs)(`defs`,{children:[(0,P.jsx)(Te,{id:r,values:Me}),(0,P.jsx)(Oe,{ref:c,id:`${r}-surface`,transform:`matrix(1 0 0 ${String(d)} 0 0)`}),(0,P.jsxs)(`radialGradient`,{id:`${r}-drop-light`,gradientUnits:`userSpaceOnUse`,cx:`-1.2`,cy:`10.4`,r:`5.6`,children:[(0,P.jsx)(`stop`,{offset:`0`,stopColor:`var(--color-white)`,style:{stopOpacity:`calc(var(--depth) * 0.5)`}}),(0,P.jsx)(`stop`,{offset:`1`,stopColor:`var(--color-white)`,stopOpacity:`0`})]}),(0,P.jsx)(Qe,{id:`${r}-shadow`}),(0,P.jsx)(`mask`,{id:`${r}-silhouette`,maskUnits:`userSpaceOnUse`,x:`-12`,y:`-24`,width:`24`,height:`48`,style:{maskType:`alpha`},children:(0,P.jsxs)(`g`,{fill:`var(--color-white)`,filter:`url(#${r})`,children:[(0,P.jsx)(`rect`,{ref:i,x:`-4`,y:u.y,width:`8`,height:u.height,rx:`4`}),(0,P.jsx)(`circle`,{ref:a,cx:`0`,cy:u.cy,r:`4`})]})})]}),(0,P.jsx)(`g`,{ref:o,filter:`url(#${r}-shadow)`,children:(0,P.jsxs)(`g`,{mask:`url(#${r}-silhouette)`,children:[(0,P.jsx)(`rect`,{x:`-12`,y:`-24`,width:`24`,height:`48`,fill:`url(#${r}-surface)`}),(0,P.jsx)(`rect`,{ref:l,x:`-12`,y:`-24`,width:`24`,height:`48`,fill:`url(#${r}-drop-light)`,opacity:ee})]})})]})}var vc=.28;function yc(e,t){switch(e){case`ring`:return{dashes:1,track:0,arc:0,sweep:0,disc:0,tick:0,cross:0};case`arc`:return{dashes:0,track:1,arc:1,sweep:t===void 0?vc:Math.min(1,Math.max(0,t)),disc:0,tick:0,cross:0};case`check`:return{dashes:0,track:0,arc:1,sweep:1,disc:1,tick:1,cross:0};case`cross`:return{dashes:0,track:0,arc:1,sweep:1,disc:1,tick:0,cross:1}}}var bc=7.25;function xc({className:e,glyph:t,progress:n}){let r=`caps-status-mark-${(0,N.useId)().replaceAll(`:`,``)}`,i=(0,N.useRef)(null),a=(0,N.useRef)(null),o=(0,N.useRef)(null),s=(0,N.useRef)(null),c=(0,N.useRef)(null),l=(0,N.useRef)(null),u=(0,N.useRef)(null),d=(0,N.useRef)(null),f=(0,N.useRef)(yc(t,n)).current,ee=(0,N.useRef)(t),p=st();(0,N.useLayoutEffect)(()=>{let e=i.current,r=a.current,c=o.current,f=s.current,m=l.current,te=u.current,h=d.current;if(!e||!r||!c||!f||!m||!te||!h)return;let re=yc(t,n),ie=ee.current;ee.current=t;let g=ne(e),ae=p||ie===t&&t!==`arc`,oe=ae?p?{ease:g.ease,duration:g.fast}:pc:hc(g,{ease:`outQuad`,duration:160}),_=(t===`check`||t===`cross`)&&!ae,se=hc(g,{ease:`inOutSine`,duration:220}),v=[E(r,{opacity:re.dashes,...oe}),E(c,{opacity:re.track*.28,...oe}),E(f,{opacity:re.arc,"stroke-dasharray":`${String(re.sweep)} 1`,...ae?p?pc:oe:se}),E(m,{r:re.disc*bc,..._?{delay:se.duration*.7,...mc(g,{bounce:.35,duration:360})}:p?pc:hc(g,{ease:`inCubic`,duration:140})}),E(te,{"stroke-dashoffset":1-re.tick,..._&&re.tick>0?{delay:se.duration*.7+g.fast,...hc(g,{ease:`outCubic`,duration:240})}:pc}),E(h,{"stroke-dashoffset":1-re.cross,..._&&re.cross>0?{delay:se.duration*.7+g.fast,...hc(g,{ease:`outCubic`,duration:240})}:pc})];return t===`cross`&&_&&g.shake>0&&v.push(E(e,{translateX:[0,-g.shake,g.shake,-g.shake/2,0],delay:se.duration+g.fast,...hc(g,{ease:`linear`,duration:300})})),()=>{for(let e of v)e.cancel()}},[t,n,p]);let m=t===`arc`&&n===void 0&&!p;return(0,N.useLayoutEffect)(()=>{if(!m||!c.current||!i.current)return;let e=ne(i.current),t=E(c.current,{rotate:[0,360],...hc(e,{ease:`linear`,duration:900}),loop:!0}),n=Ye(i.current,e=>{e?t.resume():t.pause()});return()=>{n(),t.revert()}},[m]),(0,P.jsxs)(`svg`,{ref:i,"aria-hidden":`true`,className:`caps-status-mark ${e??``}`,viewBox:`0 0 16 16`,focusable:`false`,children:[(0,P.jsxs)(`defs`,{children:[(0,P.jsx)(Oe,{id:`${r}-surface`,transform:`matrix(1.6 0 0 1.6 8 8)`}),(0,P.jsxs)(`mask`,{id:`${r}-knock`,maskUnits:`userSpaceOnUse`,x:`0`,y:`0`,width:`16`,height:`16`,children:[(0,P.jsx)(`rect`,{width:`16`,height:`16`,fill:`var(--color-white)`}),(0,P.jsx)(`path`,{ref:u,d:`M4.9 8.3 7.1 10.5 11.2 5.9`,fill:`none`,stroke:`var(--color-black)`,strokeWidth:`1.9`,strokeLinecap:`round`,strokeLinejoin:`round`,pathLength:1,strokeDasharray:`1 1`,strokeDashoffset:1-f.tick}),(0,P.jsx)(`path`,{ref:d,d:`M5.4 5.4 10.6 10.6 M10.6 5.4 5.4 10.6`,fill:`none`,stroke:`var(--color-black)`,strokeWidth:`1.9`,strokeLinecap:`round`,pathLength:1,strokeDasharray:`1 1`,strokeDashoffset:1-f.cross})]})]}),(0,P.jsx)(`circle`,{ref:a,cx:`8`,cy:`8`,r:`6.25`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeDasharray:`1.7 2.2`,opacity:f.dashes}),(0,P.jsx)(`circle`,{ref:o,cx:`8`,cy:`8`,r:`6.25`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,opacity:f.track*.28}),(0,P.jsx)(`g`,{ref:c,className:`caps-status-mark-spin`,children:(0,P.jsx)(`circle`,{ref:s,cx:`8`,cy:`8`,r:`6.25`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,pathLength:1,strokeDasharray:`${String(f.sweep)} 1`,transform:`rotate(-90 8 8)`,opacity:f.arc})}),(0,P.jsx)(`circle`,{ref:l,cx:`8`,cy:`8`,r:f.disc*bc,fill:`url(#${r}-surface)`,mask:`url(#${r}-knock)`})]})}var Sc=new Set([`ring`,`arc`,`check`,`cross`]);function Cc(e){return Sc.has(e)}var wc={neutral:`text-base-content`,primary:`text-primary`,secondary:`text-secondary`,accent:`text-accent`,success:`text-success`,info:`text-info`,warning:`text-warning`,error:`text-error`},Tc=(0,N.forwardRef)(function({className:e,label:t,glyph:n=`dot`,motion:r=`none`,tone:i=`neutral`,size:a=`default`,appearance:o=`plain`,progress:s,...c},l){return(0,P.jsxs)(`span`,{...c,className:ue(`caps-status`,a===`compact`&&`caps-status-compact`,o===`chip`&&`caps-status-chip`,e),"data-tone":o===`chip`?i:void 0,"data-glyph":n,"data-motion":r,ref:l,children:[Cc(n)?(0,P.jsx)(xc,{className:wc[i],glyph:n,progress:s}):(0,P.jsx)(_c,{className:wc[i],glyph:n,motion:r}),t===void 0?null:(0,P.jsx)(`span`,{children:t})]})}),Ec=(0,N.forwardRef)(function({className:e,count:t,density:n=`row`,dismissAriaLabel:r,dismissLabel:i=`Dismiss`,message:a,onDismiss:o,onRetry:s,retryAriaLabel:c,retryLabel:l=`Retry`,role:u=`status`,...d},f){return(0,P.jsxs)(`div`,{...d,className:ue(`caps-failure-line`,e),"data-density":n,ref:f,role:u,children:[(0,P.jsx)(Tc,{glyph:`dot`,tone:`error`}),(0,P.jsxs)(`span`,{className:`caps-failure-line-copy`,children:[(0,P.jsx)(`span`,{children:a}),t!==void 0&&t>1?(0,P.jsxs)(`span`,{className:`caps-failure-line-count`,children:[`Failed `,t,` times`]}):null]}),s||o?(0,P.jsxs)(`span`,{className:`caps-failure-line-actions`,children:[s?(0,P.jsx)(be,{"aria-label":c,size:`sm`,variant:`outline`,onClick:s,children:l}):null,o?(0,P.jsx)(be,{"aria-label":r,size:`sm`,variant:`ghost`,onClick:o,children:i}):null]}):null]})});function Dc(e,t,n=0){return Rs(e,Us,Fs.of(e,`tree`,e?.capabilities.version??0,t,n),async(e,r)=>{let i=await e.list({path:t,offset:n,limit:256});return r.throwIfAborted(),i})}var Oc=Le(`FilePlus2`,[[`path`,{d:`M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4`,key:`1pf5j1`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M3 15h6`,key:`4e2qda`}],[`path`,{d:`M6 12v6`,key:`1u72j0`}]]),kc=Le(`FolderOpen`,[[`path`,{d:`m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2`,key:`usdka0`}]]);export{cs as $,bo as A,F as At,Eo as B,Cs as C,Dn as Ct,_s as D,cn as Dt,Ts as E,xn as Et,xo as F,dt as Ft,ko as G,Jo as H,So as I,Vo as J,Ao as K,Co as L,ss as M,At as Mt,ms as N,ht as Nt,ys as O,L as Ot,hs as P,mt as Pt,Uo as Q,wo as R,Es as S,Tn as St,Ds as T,wn as Tt,Oo as U,Do as V,Xo as W,zo as X,Ro as Y,us as Z,Z as _,Rn as _t,Tc as a,Go as at,Ms as b,An as bt,mc as c,Ta as ct,ic as d,Sa as dt,qo as et,rc as f,va as ft,Fs as g,rr as gt,Ls as h,$r as ht,Ec as i,jo as it,Ho as j,kt as jt,gs as k,Wt as kt,Us as l,wa as lt,lc as m,ba as mt,Oc as n,ds as nt,pc as o,Ko as ot,sc as p,ya as pt,No as q,Dc as r,Mo as rt,hc as s,ls as st,kc as t,Wo as tt,ac as u,Ca as ut,js as v,In as vt,ws as w,En as wt,As as x,kn as xt,Q as y,On as yt,To as z};