@fungi.computer/prints 0.10.21 → 0.10.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/data-list-CsUiEPAh.js +1 -0
- package/dist/assets/{index-LnnuRHur.css → index-Co_LYFGI.css} +1 -1
- package/dist/assets/index-D7siBqfv.js +3 -0
- package/dist/assets/log-event-GKCGl2Xo.js +8 -0
- package/dist/assets/media-BQCjwzlh.js +76 -0
- package/dist/assets/print-download-button-BxrQk-8w.js +8 -0
- package/dist/assets/print-info-drawer-BWbKKKdp.js +2 -0
- package/dist/index.html +5 -5
- package/package.json +7 -7
- package/dist/assets/data-list-CHxHx7uj.js +0 -1
- package/dist/assets/index--UfPDlvF.js +0 -10
- package/dist/assets/log-event-B3qOOBbh.js +0 -1
- package/dist/assets/media-DXNW7KSH.js +0 -76
- package/dist/assets/print-download-button-B6tCroD1.js +0 -8
- package/dist/assets/print-info-drawer-HknyLAui.js +0 -2
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./print-download-button-BxrQk-8w.js","./rolldown-runtime-hePW80VL.js","./media-BQCjwzlh.js","./modules-C4mfDnjH.js","./log-event-GKCGl2Xo.js","./print-info-drawer-BWbKKKdp.js","./data-list-CsUiEPAh.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as e,t}from"./rolldown-runtime-hePW80VL.js";import{$ as n,$n as r,$r as i,A as a,An as o,Ar as s,B as c,Br as l,Ct as u,D as d,Dn as f,Dr as p,E as m,En as h,Er as g,F as _,Fn as v,Fr as y,G as b,Gn as x,Gr as S,H as C,Hn as w,I as T,In as E,Ir as D,J as O,Jn as k,Jr as A,K as j,Kn as M,Kr as N,Kt as P,L as F,Ln as I,Lr as ee,M as L,Mn as R,Mr as te,Mt as ne,N as re,Nn as z,Nr as ie,O as B,On as V,Or as ae,P as H,Pr as U,Pt as W,Q as oe,Qn as se,Qr as G,R as ce,Rn as le,Rr as ue,S as de,Sn as fe,Sr as pe,St as me,T as he,Tn as ge,Tr as _e,Tt as ve,U as ye,Un as K,Ur as be,V as xe,Vn as Se,Vr as Ce,W as we,Wn as Te,Wr as Ee,X as De,Xn as Oe,Xr as ke,Y as Ae,Yn as je,Yr as q,Yt as Me,Z as Ne,Zn as Pe,Zr as Fe,Zt as Ie,_ as Le,_n as Re,_t as ze,ai as Be,an as J,at as Ve,b as He,bn as Ue,bt as We,c as Ge,ci as Ke,cn as qe,cr as Je,ct as Ye,d as Y,di as Xe,dn as Ze,dr as Qe,dt as $e,ei as et,er as tt,et as nt,f as rt,fi as it,fn as at,fr as ot,ft as st,g as ct,gn as lt,gt as ut,h as dt,hi as ft,hn as pt,ht as mt,i as ht,ii as gt,in as _t,ir as vt,it as yt,j as bt,jr as xt,k as St,kr as Ct,l as wt,li as Tt,ln as Et,lr as Dt,lt as Ot,m as kt,mi as At,mn as jt,mr as Mt,mt as Nt,n as Pt,ni as Ft,nn as It,nr as Lt,nt as Rt,oi as zt,on as Bt,ot as Vt,p as Ht,pi as Ut,pn as Wt,pr as Gt,pt as Kt,q as qt,qn as Jt,qr as Yt,r as Xt,ri as Zt,rn as Qt,rr as $t,rt as en,s as tn,si as nn,sn as rn,st as an,ti as on,tr as sn,tt as cn,u as ln,ui as un,un as dn,ur as fn,ut as pn,v as mn,vn as hn,vt as gn,w as _n,wn as vn,wr as yn,wt as bn,xn,xr as Sn,xt as Cn,y as wn,yn as Tn,yt as En,z as Dn,zn as On,zr as kn}from"./media-BQCjwzlh.js";import{$ as An,A as jn,At as Mn,B as Nn,Bt as Pn,C as Fn,D as In,Dt as Ln,E as Rn,Et as zn,F as Bn,G as Vn,H as Hn,Ht as Un,I as Wn,J as Gn,K as Kn,L as qn,Lt as Jn,M as Yn,Mt as Xn,N as Zn,O as Qn,Ot as $n,P as er,Q as tr,R as nr,Rt as rr,S as ir,St as ar,T as or,Tt as sr,U as cr,V as lr,Vt as ur,W as dr,X as fr,Y as pr,Z as mr,_ as hr,_t as gr,a as _r,at as vr,b as yr,c as br,ct as xr,d as Sr,dt as Cr,et as wr,f as Tr,ft as Er,g as Dr,gt as Or,h as kr,ht as Ar,i as jr,it as Mr,j as Nr,jt as Pr,k as Fr,kt as Ir,l as Lr,lt as Rr,m as zr,mt as Br,n as Vr,nt as Hr,o as Ur,ot as Wr,p as Gr,pt as Kr,q as qr,r as Jr,rt as Yr,s as Xr,st as Zr,t as Qr,tt as $r,u as ei,ut as ti,v as ni,vt as ri,w as ii,wt as ai,x as oi,xt as si,y as ci,z as li,zt as ui}from"./log-event-GKCGl2Xo.js";import{$ as di,A as fi,B as pi,C as mi,Ct as hi,D as gi,E as _i,Et as vi,F as yi,G as bi,H as xi,I as Si,J as Ci,K as wi,L as Ti,M as Ei,N as Di,P as Oi,Q as ki,R as Ai,S as ji,St as Mi,T as Ni,Tt as Pi,U as Fi,V as Ii,W as Li,X as Ri,Y as zi,Z as Bi,_ as Vi,_t as Hi,a as Ui,at as Wi,b as Gi,bt as Ki,ct as qi,d as Ji,dt as Yi,et as Xi,f as Zi,ft as Qi,g as $i,gt as ea,h as ta,ht as na,i as ra,it as ia,j as aa,l as oa,lt as sa,m as ca,mt as la,n as ua,nt as da,o as fa,ot as pa,p as ma,pt as ha,q as ga,rt as _a,s as va,st as ya,tt as ba,u as xa,ut as Sa,v as Ca,vt as wa,w as Ta,wt as Ea,x as Da,xt as Oa,y as ka,yt as Aa,z as ja}from"./data-list-CsUiEPAh.js";import{r as Ma}from"./modules-C4mfDnjH.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var X=e(ft(),1),Na=class extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name=`WhistleActionError`}},Pa=class extends Error{constructor(){super(`Whistle runtime is closed`),this.name=`WhistleClosedError`}};function Fa(){let e=!1,t=ho,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=ho,s(),o.clear())},contribute:t=>{if(Wa(t),e)throw new Pa;Ga(t,n),Ka(t,n);let r=Symbol(`whistle-contribution`);Ua(t)||(n=[...n,{contribution:qa(t),generation:r}],i=!0,s());let a=!0;return po(o=>{if(!a||e)return;let c={...t,commands:o};Wa(c);let l=n.findIndex(e=>e.generation===r),u=n.filter(e=>e.generation!==r);Ga(c,u),Ka(c,u);let d=qa(c);if(Ua(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=Ha(t,n);if(i===void 0)return{status:`missing`};let o;try{let e=_o(i);if(e.status===`unavailable`)return e;let n=a.at(-1)?.presenter;r.interaction===void 0&&n!==void 0&&Ia.has(r.origin)&&(o=n({commandId:Va(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=yo(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 ho;let a=n.flatMap(e=>e.contribution.commands.map(_o));return(i||a.some((e,t)=>!vo(e,r[t])))&&(t=bo(n,a),r=a,i=!1),t},subscribe:t=>e?()=>void 0:(o.add(t),()=>{o.delete(t)})})}var Ia=new Set([`browser`,`keyboard`,`menu`,`palette`,`slash`,`terminal`]),La=16,Ra=32,za=64,Ba=256;function Va(e,t){return _e.parse(`${e}:${t}`)}function Ha(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 Ua(e){return e.commands.length===0}function Wa(e){uo(e.sourceId,`source ID`),uo(e.namespace,`namespace`),e.scope!==void 0&&uo(e.scope,`scope`);for(let t of e.commands)ao(t)}function Ga(e,t){t.find(t=>t.contribution.namespace===e.namespace&&t.contribution.sourceId!==e.sourceId)!==void 0&&mo(`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(Va(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=Va(e.namespace,t.id);n.has(i)&&mo(`Canonical command ID is already registered`),n.add(i);for(let e of t.projections?.slash?.aliases??[])r.has(e)&&mo(`Slash alias is already registered`),r.add(e)}}function Ka(e,t){t.length>=za&&mo(`Live contribution capacity exceeded`),t.reduce((e,t)=>e+t.contribution.commands.length,0)+e.commands.length>Ba&&mo(`Live command capacity exceeded`)}function qa(e){let t={sourceId:e.sourceId,namespace:e.namespace,commands:e.commands.map(Ja)};return e.scope===void 0?t:{...t,scope:e.scope}}function Ja(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=Ya(e.action)),e.availability!==void 0&&(t.availability=e.availability),e.projections!==void 0&&(t.projections=$a(e.projections)),t}function Ya(e){let t={};return e.inputSchema!==void 0&&(t.inputSchema=Xa(e.inputSchema)),e.outputSchema!==void 0&&(t.outputSchema=Xa(e.outputSchema)),e.presentation!==void 0&&(t.presentation=Qa(e.presentation)),Object.freeze(t)}function Xa(e){return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Za(t)])))}function Za(e){return Array.isArray(e)?Object.freeze(e.map(Za)):e!==null&&e instanceof Object?Object.freeze(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Za(t)]))):e}function Qa(e){switch(e.type){case`action`:return Object.freeze({type:`action`});case`custom`:return Object.freeze({type:`custom`,data:Xa(e.data)});case`choice`:return Object.freeze({type:`choice`,options:Object.freeze(e.options.map(e=>Object.freeze({...e,value:Za(e.value)})))});case`form`:return Object.freeze({...e});case`confirmation`:return Object.freeze({...e})}}function $a(e){let t={};return e.bindings!==void 0&&(t.bindings=eo(e.bindings)),e.agent!==void 0&&(t.agent=to(e.agent)),e.help!==void 0&&(t.help=no(e.help.order)),e.menu!==void 0&&(t.menu=no(e.menu.order)),e.palette!==void 0&&(t.palette=no(e.palette.order)),e.slash!==void 0&&(t.slash=ro(e.slash)),t}function eo(e){let t={values:[...e.values]};return e.order!==void 0&&(t.order=e.order),t}function to(e){let t={};return e.keybind!==void 0&&(t.keybind=e.keybind),e.order!==void 0&&(t.order=e.order),t}function no(e){let t={};return e!==void 0&&(t.order=e),t}function ro(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=io(e.arguments)),t}function io(e){let t={hint:e.hint};return e.words!==void 0&&(t.words=Object.freeze(e.words.map(e=>Object.freeze({...e,arguments:Xa(e.arguments)})))),e.text!==void 0&&(t.text=Object.freeze({...e.text,arguments:Xa(e.text.arguments)})),Object.freeze(t)}function ao(e){uo(e.id,`command ID`,!0),uo(e.title,`title`),uo(e.category,`category`),oo(e.action),so(e.projections)}function oo(e){if(e?.presentation!==void 0)switch(e.presentation.type){case`action`:case`custom`:return;case`choice`:for(let t of e.presentation.options)uo(t.label,`choice label`),t.description!==void 0&&uo(t.description,`choice description`);return;case`form`:e.presentation.submitLabel!==void 0&&uo(e.presentation.submitLabel,`submit label`);return;case`confirmation`:uo(e.presentation.message,`confirmation message`),e.presentation.confirmLabel!==void 0&&uo(e.presentation.confirmLabel,`confirmation label`),e.presentation.cancelLabel!==void 0&&uo(e.presentation.cancelLabel,`cancellation label`)}}function so(e){if(e!==void 0){for(let t of[e.bindings,e.palette,e.slash,e.help,e.menu,e.agent])t!==void 0&&fo(t.order);if(e.bindings!==void 0&&lo(e.bindings.values,`binding`),e.slash!==void 0){lo(e.slash.aliases,`slash alias`);for(let t of e.slash.aliases)/\s/u.test(t)&&mo(`slash alias must not contain whitespace`);co(e.slash.arguments)}e.agent?.keybind!==void 0&&uo(e.agent.keybind,`agent keybind`)}}function co(e){if(e===void 0)return;uo(e.hint,`argument hint`),e.words===void 0&&e.text===void 0&&mo(`slash arguments need words or text`);let t=new Set;for(let n of e.words??[])uo(n.word,`argument word`),/\s/u.test(n.word)&&mo(`argument word must not contain whitespace`),t.has(n.word)&&mo(`argument word is repeated`),t.add(n.word),n.description!==void 0&&uo(n.description,`argument word description`);t.size>Ra&&mo(`argument word count exceeds 32`),e.text!==void 0&&(uo(e.text.field,`argument text field`),e.text.requestIdField!==void 0&&uo(e.text.requestIdField,`request id field`))}function lo(e,t){e.length>La&&mo(`${t} count exceeds 16`);for(let n of e)uo(n,t)}function uo(e,t,n=!1){e.trim().length===0&&mo(`${t} must not be blank`),n&&e.includes(`:`)&&mo(`${t} must not contain a colon`)}function fo(e){e!==void 0&&!Number.isSafeInteger(e)&&mo(`order must be a safe integer`)}function po(e=()=>void 0,t=()=>void 0){return Object.freeze({update:e,dispose:t})}function mo(e){throw Error(e)}var ho=Object.freeze({bindings:Object.freeze([]),palette:Object.freeze([]),slash:Object.freeze([]),help:Object.freeze([]),menu:Object.freeze([]),agent:Object.freeze([])}),go=Object.freeze({status:`available`});function _o(e){let t=e.availability?.()??go;return t.status===`available`?go:Object.freeze({status:`unavailable`,reason:t.reason})}function vo(e,t){return e.status===`available`?t?.status===`available`:t?.status===`unavailable`&&e.reason===t.reason}function yo(e){if(e instanceof Na){let t={code:e.code,message:e.message};return Object.freeze(e.details===void 0?t:{...t,details:Za(e.details)})}return Object.freeze({code:`command_failed`,message:e.message})}function bo(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++]??go;if(u?.bindings!==void 0)for(let t of u.bindings.values)n.push({...Do(e,l,u.bindings.order,d),binding:t});if(u?.palette!==void 0&&r.push({...Do(e,l,u.palette.order,d)}),u?.slash!==void 0)for(let t of u.slash.aliases){let n={...Do(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({...Do(e,l,u.help.order,d)}),u?.menu!==void 0&&o.push({...Do(e,l,u.menu.order,d)}),u?.agent!==void 0&&s.push(ko(e,l,u.agent,d))}}return wo(n),To(i),Co(r),Co(a),Co(o),Co(s),Object.freeze({bindings:Eo(n),palette:Eo(r),slash:Eo(i),help:Eo(a),menu:Eo(o),agent:Eo(s)})}var xo=new TextEncoder;function So(e,t){let n=xo.encode(e),r=xo.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 Co(e){e.sort((e,t)=>e.order-t.order||So(e.commandId,t.commandId))}function wo(e){e.sort((e,t)=>e.order-t.order||So(e.commandId,t.commandId)||So(e.binding,t.binding))}function To(e){e.sort((e,t)=>e.order-t.order||So(e.commandId,t.commandId)||So(e.alias,t.alias))}function Eo(e){return Object.freeze(e.map(e=>Object.freeze(e)))}function Do(e,t,n,r){let i=Oo(e,t,n,r);return e.scope===void 0?i:{...i,scope:e.scope}}function Oo(e,t,n,r){let i={commandId:Va(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 ko(e,t,n,r){let i=Do(e,t,n.order,r),a=i.action===void 0?i:{...i,action:Ao(i.action)};return n.keybind===void 0?a:{...a,keybind:n.keybind}}function Ao(e){let t={};return e.inputSchema!==void 0&&(t.inputSchema=e.inputSchema),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),Object.freeze(t)}var jo=new WeakMap;function Mo(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()},l=jo.get(e)??new Map;jo.set(e,l);let u=l.get(i.id),d=()=>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:p(r)}),f=(u?u.then(d):d()).then(e=>{n?e():r.push(e)},e=>{console.warn(`App command ${i.id} was not registered`,e)});l.set(i.id,f),f.finally(()=>{l.get(i.id)===f&&l.delete(i.id)})}return()=>{if(!n){n=!0;for(let e of r.splice(0))e()}}}Ce(`light.dark.latte.mocha.readout.readout-night.field-guide.field-guide-night.embed.embed-dark.phosphor.codec.paper.ember.tide.tape.sunrise.pirate-radio.pirate-radio-night.consulting.consulting-ink.consulting-night.consulting-night-ink.consulting-riso-latte.consulting-riso-latte-ink.consulting-riso-glomzy.consulting-riso-glomzy-ink.vishnu.coin.coin-night.chamfer`.split(`.`));var No=`data-theme`;function Po(e){return e||(globalThis.document?.documentElement??null)}function Fo(e){let t=e.trim();if(t.length===0)throw TypeError(`Theme must be a non-empty string`);return t}function Io(e,t){let n=Fo(e),r=Po(t);r&&r.setAttribute(No,n)}function Lo(e){return Po(e)?.getAttribute(No)??null}var Ro=class extends Ea{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type=`infinite`,super.setOptions(e)}getOptimisticResult(e){return e._type=`infinite`,super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:`forward`}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:`backward`}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:a,isError:o,isRefetchError:s}=r,c=n.fetchMeta?.fetchMore?.direction,l=o&&c===`forward`,u=i&&c===`forward`,d=o&&c===`backward`,f=i&&c===`backward`;return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Pi(t,n.data),hasPreviousPage:vi(t,n.data),isFetchNextPageError:l,isFetchingNextPage:u,isFetchPreviousPageError:d,isFetchingPreviousPage:f,isRefetchError:s&&!l&&!d,isRefetching:a&&!u&&!f}}};function zo(e,t){let n=new Set(t);return e.filter(e=>!n.has(e))}var Bo=class extends W{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l=[];constructor(e,t,n){super(),this.#e=e,this.#r=n,this.#n=[],this.#i=[],this.#t=[],this.setQueries(t)}onSubscribe(){this.listeners.size===1&&this.#i.forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#i.forEach(e=>{e.destroy()})}setQueries(e,t){this.#n=e,this.#r=t,ne.batch(()=>{let e=this.#i,t=this.#p(this.#n);t.forEach(e=>e.observer.setOptions(e.defaultedQueryOptions));let n=t.map(e=>e.observer),r=n.map(e=>e.getCurrentResult()),i=e.length!==n.length,a=n.some((t,n)=>t!==e[n]),o=i||a,s=o?!0:r.some((e,t)=>{let n=this.#t[t];return!n||!Ie(e,n)});!o&&!s||(o&&(this.#l=t,this.#i=n),this.#t=r,this.hasListeners()&&(o&&(zo(e,n).forEach(e=>{e.destroy()}),zo(n,e).forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})),this.#h()))})}getCurrentResult(){return this.#t}getQueries(){return this.#i.map(e=>e.getCurrentQuery())}getObservers(){return this.#i}getOptimisticResult(e,t){let n=this.#p(e),r=n.map(e=>e.observer.getOptimisticResult(e.defaultedQueryOptions)),i=n.map(e=>e.defaultedQueryOptions.queryHash);return[r,e=>this.#d(e??r,t,i),()=>this.#u(r,n)]}#u(e,t){let n=new Set;return t.map((r,i)=>{let a=e[i];return r.defaultedQueryOptions.notifyOnChangeProps?a:r.observer.trackResult(a,e=>{n.has(e)||(n.add(e),t.forEach(t=>{t.observer.trackProp(e)}))})})}#d(e,t,n){if(t){let r=this.#c,i=n!==void 0&&r!==void 0&&(r.length!==n.length||n.some((e,t)=>e!==r[t]));return(this.#t!==this.#s||i||t!==this.#o)&&(this.#o=t,this.#s=this.#t,n!==void 0&&(this.#c=n),this.#a=Me(this.#a,t(e))),this.#a}return e}#f(){return!this.#r?.combine||this.#i.some((e,t)=>e.options.suspense&&this.#t[t]?.data===void 0)}#p(e){let t=new Map;this.#i.forEach(e=>{let n=e.options.queryHash;if(!n)return;let r=t.get(n);r?r.push(e):t.set(n,[e])});let n=[];return e.forEach(e=>{let r=this.#e.defaultQueryOptions(e),i=t.get(r.queryHash)?.shift()??new Ea(this.#e,r);n.push({defaultedQueryOptions:r,observer:i})}),n}#m(e,t){let n=this.#i.indexOf(e);n!==-1&&(this.#t=this.#t.slice(),this.#t[n]=t,this.#h())}#h(){if(this.hasListeners()){let e=this.#f(),t=this.#a,n=e?t:this.#d(this.#u(this.#t,this.#l),this.#r?.combine);(e||t!==n)&&ne.batch(()=>{this.listeners.forEach(e=>{e(this.#t)})})}}};function Vo({queries:e,...t},n){let r=Qt(n),i=hi(),a=Mi(),o=t.subscribed!==!1,s=X.useMemo(()=>e.map(e=>{let t=r.defaultQueryOptions(e);return t._optimisticResults=i?`isRestoring`:o?`optimistic`:void 0,t}),[e,r,i,o]);s.forEach(e=>{ea(e);let t=r.getQueryCache().get(e.queryHash);Aa(e,a,t)}),Oa(a);let[c]=X.useState(()=>new Bo(r,s,t)),[l,u,d]=c.getOptimisticResult(s,t.combine),f=!i&&o;X.useSyncExternalStore(X.useCallback(e=>f?c.subscribe(ne.batchCalls(e)):P,[c,f]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),X.useEffect(()=>{c.setQueries(s,t)},[s,t,c]);let p=l.some((e,t)=>wa(s[t],e))?l.flatMap((e,t)=>{let n=s[t];if(n&&wa(n,e)){let e=new Ea(r,n);return Hi(n,e,a)}return[]}):[];if(p.length>0)throw Promise.all(p);let m=l.find((e,t)=>{let n=s[t];return n&&Ki({result:e,errorResetBoundary:a,throwOnError:n.throwOnError,query:r.getQueryCache().get(n.queryHash),suspense:n.suspense})});if(m)throw m.error;return u(d())}function Ho(e){return e}function Uo(e,t){return e.findAll(t.filters).map(e=>t.select?t.select(e):e.state)}function Wo(e={},t){let n=Qt(t).getMutationCache(),r=X.useRef(e),i=X.useRef(null);return i.current===null&&(i.current=Uo(n,e)),X.useEffect(()=>{r.current=e}),X.useSyncExternalStore(X.useCallback(e=>n.subscribe(()=>{let t=Me(i.current,Uo(n,r.current));i.current!==t&&(i.current=t,ne.schedule(e))}),[n]),()=>i.current,()=>i.current)}function Go(e,t){return na(e,Ro,t)}var Ko=t((e=>{var t=Un();e.createRoot=t.createRoot,e.hydrateRoot=t.hydrateRoot}))();function qo(e){let t=e.trim().toLowerCase();if(!t)throw Error(`Invalid keymap token: token cannot be empty`);return t}function Jo(e){let t=e.trim().toLowerCase();if(!t)throw Error(`Invalid key name: key name cannot be empty`);return t}function Yo(e){return{name:Jo(e.name),ctrl:e.ctrl??!1,shift:e.shift??!1,meta:e.meta??!1,super:e.super??!1,hyper:e.hyper||void 0}}function Xo(e){return{name:e.name,ctrl:e.ctrl,shift:e.shift,meta:e.meta,super:e.super,hyper:e.hyper||void 0}}function Zo(e,t){let n=Xo(Yo(e));return{stroke:n,display:t?.display??as(n),match:t?.match??ts(n),tokenName:t?.tokenName?qo(t.tokenName):void 0}}function Qo(e){return{stroke:Xo(e.stroke),display:e.display,match:e.match,tokenName:e.tokenName,patternName:e.patternName,payloadKey:e.payloadKey}}function $o(e){return e.map(e=>Qo(e))}function es(e){return`match`in e?e.match:`stroke`in e?ts(e.stroke):ts(e)}function ts(e){return`key:${os(Yo(e))}`}function ns(e){let t=e.trim();if(!t)throw Error(`Invalid keymap match id: id cannot be empty`);return`text:${t}`}function rs(e,t){return`stroke`in e?t?.preferDisplay&&e.display?e.display:as(e.stroke):as(Yo(e))}function is(e,t){return e.map(e=>rs(e,t)).join(t?.separator??``)}function as(e){let t=[];return e.ctrl&&t.push(`ctrl`),e.shift&&t.push(`shift`),e.meta&&t.push(`meta`),e.super&&t.push(`super`),e.hyper&&t.push(`hyper`),t.push(e.name===`return`?`enter`:e.name),t.join(`+`)}function os(e){return`${e.name}:${+!!e.ctrl}:${+!!e.shift}:${+!!e.meta}:${+!!e.super}:${+!!e.hyper}`}var ss=Symbol(`keymap-extension-context`);function cs(e){return e.isDestroyed?null:e.getFocusedTarget()}function ls(e,t,n){let r=t??e.rootTarget,i=t!==null;for(;r;){if(n(r,i)===!1)return;r=e.getParentTarget(r),i=!1}}function us(e,t){let n=new Set;return ls(e,t,e=>{n.add(e)}),n}function ds(e,t,n){let r=[],i=us(t,n),a=Array.isArray(e)?e:fs(e);for(let e of a)ps(t,e,n,i)&&r.push(e);return r}function fs(e){return[...e].sort((e,t)=>t.priority-e.priority||t.order-e.order)}function ps(e,t,n,r=us(e,n)){let i=t.target;return i?e.isTargetDestroyed(i)?!1:t.targetMode===`focus`?i===n:r.has(i):!0}function ms(e){let t=e.binding.sequence[e.index];if(!t?.patternName)return 0;let n=e.patterns?.at(-1);return n?.name===t.patternName?n.values.length:0}function hs(e,t,n=!0){let r=e.binding.sequence[e.index];if(!r?.patternName)return!0;let i=t.get(r.patternName);return i?ms(e)>=i.min:n}function gs(e,t,n=!0){let r=e.binding.sequence[e.index];if(r?.patternName){let n=t.get(r.patternName);if(n&&ms(e)<n.max)return!0}return hs(e,t,n)&&e.index+1<e.binding.sequence.length}function _s(e,t){return e.index===e.binding.sequence.length-1&&hs(e,t,!1)}function vs(e,t,n,r){return{parent:e,depth:e?e.depth+1:0,stroke:t,match:n,pattern:r,children:new Map,patternChildren:[],bindings:[],reachableBindings:[]}}function ys(e,t){let n=vs(null,null,null);for(let r of e){if(r.event!==`press`)continue;let e=n;for(let n of r.sequence){let i;if(n.patternName){let r=t.get(n.patternName);i=e.patternChildren.find(e=>e.pattern?.name===n.patternName),i||(i=vs(e,n.stroke,n.match,r),e.patternChildren.push(i))}else i=e.children.get(n.match),i||(i=vs(e,n.stroke,n.match),e.children.set(n.match,i));i.reachableBindings.push(r),e=i}e.bindings.push(r)}return n}function bs(e,t){let n=[];for(let r of e){if(!hs(r,t))continue;let e=r.index+1,i=r.binding.sequence[e];i&&n.push({part:i,binding:r.binding,index:e,exact:e===r.binding.sequence.length-1,continues:e<r.binding.sequence.length-1})}return n}function xs(e,t,n,r){let i=n.patternName;if(!i)return{...e,index:t};let a=[...e.patterns??[]],o=a.at(-1);return o?.name===i?a[a.length-1]={...o,values:[...o.values,r],parts:[...o.parts,n]}:a.push({name:i,payloadKey:n.payloadKey??i,values:[r],parts:[n]}),{layer:e.layer,binding:e.binding,index:t,parts:[...e.parts,n],patterns:a}}function Ss(e,t){let n=e.parts.at(-1);if(!n||n.patternName)return t.length;let r=t.indexOf(n.match);return r===-1?t.length:r}function Cs(e,t,n,r,i,a,o,s,c){let l=t.sequence[n];if(l){if(l.patternName){let a=s(l.patternName,o);if(!a)return;let u=c(o,l.patternName,a);return xs({layer:e,binding:t,index:n,parts:r,patterns:i},n,u,a.value??o.name)}if(a.includes(l.match))return{layer:e,binding:t,index:n,parts:[...r,l],patterns:i}}}function ws(e,t,n,r,i,a){let o=e.binding.sequence[e.index];if(o?.patternName){let s=r.get(o.patternName);if(s&&ms(e)<s.max){let t=i(s.name,n);if(t){let r=a(n,s.name,t);return xs(e,e.index,r,t.value??n.name)}}return hs(e,r,!1)?Cs(e.layer,e.binding,e.index+1,e.parts,e.patterns,t,n,i,a):void 0}return Cs(e.layer,e.binding,e.index+1,e.parts,e.patterns,t,n,i,a)}function Ts(e,t,n,r,i){let a=[],o=1/0;for(let s of e.bindings){if(s.event!==`press`)continue;let c=Cs(e,s,0,[],void 0,t,n,r,i);if(!c)continue;let l=Ss(c,t);l<o&&(o=l,a.length=0),l===o&&a.push(c)}return a}import.meta.require;function Es(e){let t=Object.create(null),n=(e,n)=>{let r=t[e];if(!r)return;let i=r.filter(e=>e!==n);i.length===0?delete t[e]:i.length!==r.length&&(t[e]=i)};return{hook(e,r){return t[e]=[...t[e]??[],r],()=>n(e,r)},has(e){return(t[e]?.length??0)>0},emit(n,...r){let i=t[n];if(i)for(let t of i)try{r.length===0?t():t(r[0])}catch(t){e(n,t)}}}}function Ds(){let e=[];return{get:()=>e,set:t=>{e=t},remove(t){e=e.filter(e=>e!==t)},has:()=>e.length>0,clear:()=>{e=[]}}}function Os(){let e=Ds();return{append(t){return e.set([...e.get(),t]),()=>e.remove(t)},prepend(t){return e.set([t,...e.get()]),()=>e.remove(t)},values:e.get,has:e.has,clear:e.clear}}function ks(){let e=Ds(),t=0;return{register(n,r){let i={...r,listener:n,order:t++};return e.set([...e.get(),i].sort((e,t)=>t.priority-e.priority||e.order-t.order)),()=>e.remove(i)},entries:e.get,has:e.has,clear:e.clear}}function As(e){return typeof e==`string`||!!e&&typeof e==`object`&&!Array.isArray(e)}function js(e){if(!Array.isArray(e))return{ok:!1,reason:`Invalid keymap bindings: expected an array of binding objects`};for(let[t,n]of e.entries()){if(!n||typeof n!=`object`||Array.isArray(n))return{ok:!1,reason:`Invalid keymap binding at index ${t}: expected a binding object`};if(!As(n.key))return{ok:!1,reason:`Invalid keymap binding at index ${t}: expected "key" to be a string or keystroke object`}}return{ok:!0}}function Ms(e){let t=js(e);if(!t.ok)throw Error(t.reason);return e.map(e=>({...e,key:typeof e.key==`string`?e.key:{...e.key}}))}function Ns(e){return{...e,sequence:$o(e.sequence)}}function Ps(e,t){let n=Os();return{prependLayerAnalyzer(e){return n.prepend(e)},appendLayerAnalyzer(e){return n.append(e)},clearLayerAnalyzers(){n.clear()},analyzeLayer(r){let i=n.values();if(i.length===0)return;let a=Fs(r.bindings),o={target:r.target,order:r.order,sourceBindings:r.sourceBindings,bindings:a,hasTokenBindings:r.hasTokenBindings,checkCommandResolution(e){return t.getCommandResolutionStatus(e,r.commands)},warn(t,n,r){e.emitWarning(t,n,r)},warnOnce(t,n,r,i){e.warnOnce(t,n,r,i)},error(t,n,r){e.emitError(t,n,r)}};for(let t of i)try{t(o)}catch(t){e.emitError(`layer-analyzer-error`,t,`[Keymap] Error in layer analyzer:`)}}}}function Fs(e){return e.map(t=>({sequence:$o(t.sequence),command:t.command,attrs:t.attrs,event:t.event,preventDefault:t.preventDefault,fallthrough:t.fallthrough,parsedBinding:Ns(t.parsedBinding),sourceTarget:t.sourceTarget,sourceLayerOrder:t.sourceLayerOrder,bindingIndex:t.bindingIndex,hasCommandAtSequence:e.some(e=>e.event===`press`&&e.command!==void 0&&Is(e,t)),hasContinuations:e.some(e=>e.event===`press`&&Ls(t,e))}))}function Is(e,t){return e.sequence.length===t.sequence.length&&e.sequence.every((e,n)=>e.match===t.sequence[n]?.match)}function Ls(e,t){return e.sequence.length<t.sequence.length&&e.sequence.every((e,n)=>e.match===t.sequence[n]?.match)}function Rs(){return{version:-1,notifyVersion:-1,focused:void 0,value:[],targets:new WeakMap}}function zs(){return{plain:Rs(),bindings:Rs(),metadata:Rs(),bindingsAndMetadata:Rs()}}function Bs(e,t){if(t===void 0)return e.plain;let n=t.includeBindings===!0,r=t.includeMetadata===!0;return n?r?e.bindingsAndMetadata:e.bindings:r?e.metadata:e.plain}function Vs(e,t,n){let r=n?e.targets.get(n):e.nullTarget;return r?.version===t?r:void 0}function Hs(e,t,n,r){let i={version:t,value:r};n?e.targets.set(n,i):e.nullTarget=i}function Us(e,t){if(e===t)return!0;if(!e||!t||e.captures.length!==t.captures.length)return!1;for(let n=0;n<e.captures.length;n+=1){let r=e.captures[n],i=t.captures[n];if(!r||!i||r.layer!==i.layer||r.binding!==i.binding||r.index!==i.index||r.parts.length!==i.parts.length)return!1;for(let e=0;e<r.parts.length;e+=1)if(r.parts[e]?.match!==i.parts[e]?.match)return!1;let a=r.patterns??[],o=i.patterns??[];if(a.length!==o.length)return!1;for(let e=0;e<a.length;e+=1){let t=a[e],n=o[e];if(!t||!n||t.name!==n.name||t.values.length!==n.values.length)return!1;for(let e=0;e<t.values.length;e+=1)if(!Object.is(t.values[e],n.values[e]))return!1}}return!0}function Ws(e){let t=e.parts.at(-1);if(!t||e.parts.length<=1)return;let n=e.index-1,r=e.patterns;if(t.patternName){let i=r?.at(-1);i?.name===t.patternName&&(i.values.length>1?(n=e.index,r=[...(r??[]).slice(0,-1),{...i,values:i.values.slice(0,-1),parts:i.parts.slice(0,-1)}]):r=(r??[]).slice(0,-1))}return{layer:e.layer,binding:e.binding,index:n,parts:e.parts.slice(0,-1),patterns:r}}function Gs(e){let t=e.captures[0];if(!t||t.parts.length===0)return[];let n=[];for(let r=0;r<t.parts.length;r+=1){let i=t.parts[r];if(!i)continue;let a,o,s=!1,c=!1;for(let t of e.captures){let e=t.parts[r];if(e){if(a===void 0){a=e.display,o=e.tokenName;continue}!s&&a!==e.display&&(s=!0),!c&&o!==e.tokenName&&(c=!0)}}(a===void 0||s)&&(a=rs(i.stroke)),c&&(o=void 0),n.push(Zo(i.stroke,{display:a,match:i.match,tokenName:o}))}return n}function Ks(e){if(e.isDestroyed)throw Error(`Cannot use a keymap after its host was destroyed`);return e}function qs(e,t,n,r,i,a,o={}){let s=zs(),c=-1,l=[],u=()=>Ks(t).getFocusedTarget(),d=()=>cs(t),f=t=>{let n=e.pending;Us(n,t)||(e.pending=t,o.onPendingSequenceChanged?.(n,t),B(),r.queueStateChange())},p=()=>{let t=e.pending;if(!t)return;let n=u(),r=a.getActiveCommandView(n),o=t.captures.filter(t=>e.layers.has(t.layer)&&C(t.layer,n)&&i.matchesConditions(t.layer)&&D(t.binding,n,r)&&gs(t,e.patterns));if(o.length===0){f(null);return}return o.length!==t.captures.length&&f({captures:o}),e.pending??void 0},m=()=>{t.isDestroyed||!e.pending||p()},h=()=>!t.isDestroyed&&e.pending!==null,g=()=>{if(c===e.cacheVersion)return l;let t=p(),n=t?Gs(t):[];return(!t||T())&&(c=e.cacheVersion,l=n),n},_=()=>{let e=p();if(!e)return!1;let t=e.captures[0];if(!t||t.parts.length<=1)return f(null),!0;let n=[];for(let t of e.captures){let e=Ws(t);e&&n.push(e)}return n.length===0?(f(null),!0):(f({captures:n}),!0)},v=t=>{let n=t?.includeBindings===!0,r=t?.includeMetadata===!0,i=Bs(s,t);return i.notifyVersion===e.derivedVersion?i.value:y(i,n,r)},y=(n,r,i)=>{t.isDestroyed&&Ks(t);let o=u(),s=Vs(n,e.cacheVersion,o);if(s)return n.notifyVersion=e.derivedVersion,n.version=e.cacheVersion,n.focused=o,n.value=s.value,s.value;let c=a.getActiveCommandView(o),l=p(),d=l?[]:S(o),f=l?F(l.captures,r,i,o,c):j(d,r,i,o,c);return(l?T():w(d))&&(n.version=e.cacheVersion,n.notifyVersion=e.derivedVersion,n.focused=o,n.value=f,Hs(n,e.cacheVersion,o,f)),f},b=(e,t)=>{let n=t?.includeBindings===!0,r=t?.includeMetadata===!0,i=u(),o=a.getActiveCommandView(i);return F(e,n,r,i,o)},x=(e,t)=>{let n=t?.includeBindings===!0,r=t?.includeMetadata===!0,i=e===d()?p():void 0,o=a.getActiveCommandView(e);return i?F(i.captures,n,r,e,o):j(S(e),n,r,e,o)},S=n=>e.activeLayersCacheVersion===e.cacheVersion&&e.activeLayersCacheFocused===n?e.activeLayersCache:(e.activeLayersCacheVersion=e.cacheVersion,e.activeLayersCacheFocused=n,e.activeLayersCache=ds(e.sortedLayers,t,n),e.activeLayersCache),C=(e,n)=>ps(t,e,n),w=t=>!e.commandResolvers.has()&&e.activeKeyCacheBlockers===0,T=()=>!e.commandResolvers.has()&&e.activeKeyCacheBlockers===0,E=(e,t,n)=>{let r=[];for(let o of e)i.matchesConditions(o)&&a.isBindingVisible(o,t,n)&&r.push(o);return r},D=(e,t,n)=>i.matchesConditions(e)&&a.isBindingVisible(e,t,n),O=(e,t)=>{let n,r,i=!1,a=!1;for(let o of e){let e=o.sequence[t];if(e){if(n===void 0){n=e.display,r=e.tokenName;continue}!i&&n!==e.display&&(i=!0),!a&&r!==e.tokenName&&(a=!0)}}if(n===void 0||i){let r=e[0]?.sequence[t]?.stroke;n=r?rs(r):``}return a&&(r=void 0),{display:n,tokenName:r}},k=(e,t,n)=>({sequence:e.sequence,command:e.command,commandAttrs:a.getBindingCommandAttrs(e,t,n),attrs:e.attrs,event:e.event,preventDefault:e.preventDefault,fallthrough:e.fallthrough}),A=(e,t,n)=>e.map(e=>k(e,t,n)),j=(e,t,n,r,a)=>{let o=new Map,s=new Set;for(let n of e)n.root.children.size===0&&n.root.patternChildren.length===0||!i.matchesConditions(n)||(M(n.root.children.values(),o,s,t,r,a),M(n.root.patternChildren,o,s,t,r,a));return L(o,t,n,r,a)},M=(e,t,n,r,i,a)=>{for(let o of e){let e=o.match;if(!e||n.has(e)||!o.stroke)continue;let s=N(o,r,i,a);if(!s)continue;let c=t.get(e);c?z(c,s,r):t.set(e,re(o.stroke,s,r)),s.stop&&n.add(e)}},N=(e,t,n,r)=>{if(!(e.children.size>0||e.patternChildren.length>0)){let i=ne(P(e)?E(e.bindings,n,r):e.bindings,n,r);if(!i)return;let a=O(i.bindings,e.depth-1);return{display:a.display,tokenName:a.tokenName,continues:!1,firstBinding:i.bindings[0],commandBinding:i.commandBinding,bindings:t?[...i.bindings]:void 0,stop:i.stop}}let i=E(e.reachableBindings,n,r);if(i.length===0)return;let a=ne(e.bindings,n,r),o=O(i,e.depth-1);return{display:o.display,tokenName:o.tokenName,continues:!0,firstBinding:a?.bindings[0],commandBinding:a?.commandBinding,bindings:t&&a?[...a.bindings]:void 0,stop:!0}},P=t=>{if(e.commandResolvers.has())return!0;for(let e of t.bindings)if(e.matchers.length>0)return!0;return!1},F=(t,n,r,i,a)=>{let o=new Map,s=new Set;return I(bs(t,e.patterns),o,s,n,i,a),L(o,n,r,i,a)},I=(e,t,n,r,i,a)=>{let o=new Set;for(let s of e)o.has(s.part.match)||(o.add(s.part.match),ee(s,e,t,n,r,i,a))},ee=(e,t,n,r,i,a,o)=>{let s=e.part.match;if(r.has(s))return;let c=R(e,t,i,a,o);if(!c)return;let l=n.get(s);l?z(l,c,i):n.set(s,re(e.part.stroke,c,i)),c.stop&&r.add(s)},L=(e,t,n,r,i)=>{let a=[];for(let o of e.values()){let e=ie(o,t,n,r,i);e&&a.push(e)}return a},R=(e,t,n,r,i)=>{let a=t.filter(t=>t.part.match===e.part.match),o=a.filter(e=>e.exact).map(e=>e.binding),s=ne(o,r,i),c=a.some(e=>e.continues);if(!c&&!s)return;let l=te(a);return{display:l.display,tokenName:l.tokenName,continues:c,firstBinding:s?.bindings[0],commandBinding:s?.commandBinding,bindings:n&&s?[...s.bindings]:void 0,stop:c||s?.stop===!0}},te=e=>{let t,n,r=!1,i=!1;for(let a of e){let e=a.part;if(t===void 0){t=e.display,n=e.tokenName;continue}!r&&t!==e.display&&(r=!0),!i&&n!==e.tokenName&&(i=!0)}let a=e[0]?.part;return(t===void 0||r)&&(t=a?rs(a.stroke):``),i&&(n=void 0),{display:t,tokenName:n}},ne=(e,t,n)=>{let r=[],o;for(let s of e)if(!(!i.matchesConditions(s)||!a.isBindingVisible(s,t,n))&&(r.push(s),s.command!==void 0&&(o??=s,!s.fallthrough)))return{bindings:r,commandBinding:o,stop:!0};if(r.length!==0)return{bindings:r,commandBinding:o,stop:!1}},re=(e,t,n)=>({stroke:e,display:t.display,tokenName:t.tokenName,continues:t.continues,firstBinding:t.firstBinding,commandBinding:t.commandBinding,bindings:n&&t.bindings?[...t.bindings]:void 0}),z=(e,t,n)=>{if(!e.firstBinding&&t.firstBinding&&(e.firstBinding=t.firstBinding),!e.commandBinding&&t.commandBinding&&(e.commandBinding=t.commandBinding),t.continues&&(e.continues=!0),!(!n||!t.bindings||t.bindings.length===0)){if(!e.bindings){e.bindings=[...t.bindings];return}e.bindings.push(...t.bindings)}},ie=(e,t,n,r,i)=>{if(!e.commandBinding&&!e.continues)return;let o={stroke:Xo(e.stroke),display:e.display,continues:e.continues};if(e.tokenName&&(o.tokenName=e.tokenName),e.commandBinding&&(o.command=e.commandBinding.command),t&&e.bindings&&e.bindings.length>0&&(o.bindings=e.bindings.length===1?[k(e.bindings[0],r,i)]:A(e.bindings,r,i)),n){e.firstBinding?.attrs&&(o.bindingAttrs=e.firstBinding.attrs);let t=e.commandBinding?a.getBindingCommandAttrs(e.commandBinding,r,i):void 0;t&&(o.commandAttrs=t)}return o},B=()=>{n.has(`pendingSequence`)&&n.emit(`pendingSequence`,e.pending?Gs(e.pending):[])};return{getFocusedTarget:u,getFocusedTargetIfAvailable:d,setPendingSequence:f,ensureValidPendingSequence:p,revalidatePendingSequenceIfNeeded:m,hasPendingSequenceState:h,getPendingSequence:g,popPendingSequence:_,getActiveKeys:v,getActiveKeysForCaptures:b,getActiveKeysForFocused:x,getActiveLayers:S,isLayerActiveForFocused:C,collectSequencePartsFromPending:Gs,collectMatchingBindings:E,collectActiveBindings:A}}var Js=new Set([`name`,`run`,`fields`,`attrs`,`rejectedResult`]),Ys=new Set([`key`,`cmd`,`event`,`preventDefault`,`fallthrough`]),Xs=new Set([`target`,`targetMode`,`priority`,`bindings`,`commands`]);function Zs(e){if(e===void 0||typeof e==`function`)return e;let t=e.trim();if(!t)throw Error(`Invalid keymap command: command cannot be empty`);return t}function Qs(e){let t=e.trim();if(!t)throw Error(`Invalid keymap command name: name cannot be empty`);if(/\s/.test(t))throw Error(`Invalid keymap command name "${e}": command names cannot contain whitespace`);return t}function $s(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function ec(e){let t=[],n=new Map;for(let r of e.layers)for(let e of r.commands){let i={layer:r,commandState:e};t.push(i),$s(n,e.command.name,i)}return{entries:t,chainsByName:n}}function tc(e,t,n){let r=[],i=[],a=new Map,o=new Map;for(let s of e)if(s.commands.length!==0&&!(n&&!t.matchesConditions(s)))for(let e of s.commands){if(!t.matchesConditions(e))continue;let n={layer:s,commandState:e};r.push(n),$s(o,e.command.name,n),a.has(e.command.name)||(a.set(e.command.name,n),i.push(n))}return{layers:e,entries:r,reachable:i,reachableByName:a,chainsByName:o}}function nc(e,t,n,r){return(e.activeLayersCacheVersion!==e.cacheVersion||e.activeLayersCacheFocused!==r)&&(e.activeLayersCacheVersion=e.cacheVersion,e.activeLayersCacheFocused=r,e.activeLayersCache=ds(e.sortedLayers,t,r)),tc(e.activeLayersCache,n,!0)}function rc(e,t,n,r){if(Object.prototype.hasOwnProperty.call(e,t)&&!Object.is(e[t],n))throw Error(`Conflicting keymap requirement for "${t}" from ${r}`);e[t]=n}function ic(e,t,n,r){if(Object.prototype.hasOwnProperty.call(e,t)&&!Object.is(e[t],n))throw Error(`Conflicting keymap attribute for "${t}" from ${r}`);e[t]=n}function ac(e){let t=`field ${e.fieldName}`;return{require(n,r){rc(e.requirements,n,r,t)},attr(n,r){if(!e.attrs)throw Error(`Keymap ${t} cannot publish attrs`);ic(e.attrs,n,r,t)},activeWhen(n){e.matchers.push(e.conditions.buildRuntimeMatcher(n,t))}}}function oc(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function sc(e,t){return e instanceof Error&&e.message?e.message:t}function cc(e){return!e||typeof e!=`object`&&typeof e!=`function`?!1:typeof e.then==`function`}function lc(e,t){let n=t?.deep===!0,r=t?.freeze===!0,i=t?.preserveNonPlainObjects===!0;if(Array.isArray(e)){let i=n?e.map(e=>lc(e,t)):[...e];return r?Object.freeze(i):i}if(e&&typeof e==`object`){if(i&&!oc(e))return e;let a={};for(let[r,i]of Object.entries(e))a[r]=n?lc(i,t):i;return r?Object.freeze(a):a}return e}var uc=[`name`],dc=Object.freeze({}),fc=new WeakMap;function pc(e,t,n,r,i){let a=-1,o,s=-1,c,l,u=-1,d,f,p=-1,m,h=-1,g=new Map,_=t=>hc({commands:t,commandFields:e.commandFields,conditions:r,onError:(e,t,r)=>{n.emitError(e,t,r)}}),v=t=>L(()=>e.commandResolvers.prepend(t),t),y=t=>L(()=>e.commandResolvers.append(t),t),b=()=>{e.commandResolvers.has()&&n.runWithStateChangeBatch(()=>{e.commandResolvers.clear(),i.onCommandResolversChanged(),n.queueStateChange()})},x=e=>ae(e).map(e=>mc(e.commandState)),S=e=>{let t=V(e),n=ae(e,t);if(n.length===0)return[];let r=n.map(e=>({entry:e,command:mc(e.commandState),commandAttrs:e.commandState.attrs,bindings:[]})),i=new Map;for(let[e,t]of r.entries()){let n=i.get(t.command.name);n?n.push(e):i.set(t.command.name,[e])}return i.size>0&&H(r,i,t),r.map(e=>({command:e.command,bindings:e.bindings}))},C=t=>{if(t.visibility===`registered`&&u===e.derivedVersion&&d===t.commands&&f)return f;let n=new Map;for(let e of t.commands)n.has(e)||n.set(e,[]);return n.size===0?n:(U(n,V(t)),t.visibility===`registered`&&(u=e.derivedVersion,d=t.commands,f=n),n)},w=(e,t,n)=>{let r=M(t);if(n){let i=[],a=r.chainsByName.get(e);if(a)for(let e of a)i.push({target:e.layer.target,command:e.commandState.command,attrs:e.commandState.attrs,payload:n.payload});let o=le(e,t,{mode:`active`,execution:n});return o.resolved&&i.push(o.resolved),{entries:i.length>0?i:void 0,hadError:o.hadError}}let i=[];for(let t of r.chainsByName.get(e)??[])i.push({target:t.layer.target,command:t.commandState.command,attrs:t.commandState.attrs});let a=le(e,t,{mode:`active`});return a.resolved&&i.push(a.resolved),{entries:i.length>0?i:void 0,hadError:a.hadError}},T=t=>{if(h!==e.derivedVersion&&(h=e.derivedVersion,g=new Map),g.has(t))return g.get(t)??void 0;let n=re(ne(t));return g.set(t,n??null),n},E=(e,t)=>re(M(t).chainsByName.get(e)),D=(e,t)=>le(e,null,{mode:`registered`,execution:t}),O=(e,t,n)=>le(e,t,{mode:`active`,execution:n}),k=(e,t)=>R(e,t)?.command,A=e=>te(e)?.commandState.command,j=(e,n,i)=>{let a=N().chainsByName.get(e);if(!a||a.length===0)return;let o,s;for(let e of a){if(!ps(t,e.layer,n)){o??=e;continue}(!r.matchesConditions(e.layer)||!r.matchesConditions(e.commandState))&&(s??=e)}let c=s??o;if(c)return{reason:s?`disabled`:`inactive`,command:i?c.commandState.command:void 0}},M=n=>{if(s===e.derivedVersion&&c===n&&l)return l;let i=nc(e,t,r,n);return P()&&(s=e.derivedVersion,c=n,l=i),i},N=()=>a===e.derivedVersion&&o?o:(a=e.derivedVersion,o=ec(e),o),P=()=>e.activeCommandViewCacheBlockers===0,F=(e,t,n)=>e.command===void 0||e.run?!0:typeof e.command==`string`?n.reachableByName.has(e.command)?!0:z(e.command,t,`active`)!==void 0:!1,I=(e,t,n)=>{if(typeof e.command!=`string`)return;let r=n.reachableByName.get(e.command);return r?r.commandState.attrs:z(e.command,t,`active`)?.attrs},ee=(e,n)=>{if(n?.some(t=>t.command.name===e)||N().chainsByName.has(e))return`resolved`;let r=le(e,cs(t));return r.resolved||r.hadError?r.resolved?`resolved`:`error`:`unresolved`},L=(t,r)=>n.runWithStateChangeBatch(()=>{let a=t();return i.onCommandResolversChanged(),n.queueStateChange(),()=>{n.runWithStateChangeBatch(()=>{a(),!e.commandResolvers.values().includes(r)&&(i.onCommandResolversChanged(),n.queueStateChange())})}}),R=(e,t)=>{let n=M(t).reachableByName.get(e);return n?{target:n.layer.target,command:n.commandState.command,attrs:n.commandState.attrs}:z(e,t,`active`)},te=e=>ne(e)?.[0],ne=t=>{let n=[];for(let r of e.sortedLayers)for(let e of r.commands)e.command.name===t&&n.push({layer:r,commandState:e});return n.length>0?n:void 0},re=e=>{if(e?.length)return e.map(e=>({target:e.layer.target,command:e.commandState.command,attrs:e.commandState.attrs}))},z=(e,t,n)=>le(e,t,{mode:n}).resolved,ie=()=>N().entries,B=()=>{if(p===e.derivedVersion&&m)return m;let t=new Map;for(let n of e.layers)for(let e of n.bindings){if(typeof e.command!=`string`)continue;let n=t.get(e.command);n?n.push(e):t.set(e.command,[e])}return p=e.derivedVersion,m=t,t},V=e=>{let n=e?.visibility??`reachable`,r=e&&Object.prototype.hasOwnProperty.call(e,`focused`)?e.focused??null:cs(t);return n===`registered`?{visibility:n,focused:r}:{visibility:n,focused:r,activeView:M(r)}},ae=(e,t=V(e))=>{let r;return r=t.visibility===`registered`?ie():t.visibility===`active`?t.activeView?.entries??[]:t.activeView?.reachable??[],bc({entries:r,query:e,getCommand:e=>mc(e),onFilterError:e=>{n.emitError(`command-query-filter-error`,e,`[Keymap] Error in command query filter:`)}})},H=(e,t,n)=>{W(n,n=>{oe(e,t,n)})},U=(e,t)=>{if(t.visibility===`registered`){let t=B();for(let[n,r]of e){let e=N().chainsByName.get(n)?.[0]?.commandState.attrs;for(let i of t.get(n)??[])r.push(G(i,e))}return}W(t,n=>{se(e,n,t)})},W=(t,n)=>{if(t.visibility===`registered`){for(let t of e.layers)for(let e of t.bindings)n(e);return}let i=t.activeView;if(i){for(let e of i.layers)if(!(e.bindings.length===0||!r.matchesConditions(e)))for(let a of e.bindings)r.matchesConditions(a)&&F(a,t.focused,i)&&n(a)}},oe=(e,t,n)=>{if(typeof n.command!=`string`)return;let r=t.get(n.command);if(!(!r||r.length===0))for(let t of r){let r=e[t];r&&r.bindings.push(G(n,r.commandAttrs))}},se=(e,t,n)=>{if(typeof t.command!=`string`)return;let r=e.get(t.command);r&&r.push(G(t,ce(t,n)))},G=(e,t)=>({sequence:e.sequence,command:e.command,commandAttrs:t,attrs:e.attrs,event:e.event,preventDefault:e.preventDefault,fallthrough:e.fallthrough}),ce=(e,t)=>{if(typeof e.command!=`string`)return;if(t.visibility===`registered`)return N().chainsByName.get(e.command)?.[0]?.commandState.attrs;let n=t.activeView;if(n)return I(e,t.focused,n)},le=(t,r,i)=>{let a=i?.mode??`active`,o=i?.execution??{input:t},s=gc(t,e.commandResolvers.values(),()=>fe(r,a,o),e=>{n.emitError(`command-resolver-error`,e,`[Keymap] Error in command resolver for "${t}":`)}),c=s.resolved;if(c){let e=de(c.command.name,r,a);e?.commandState.command===c.command&&c.target===void 0&&(c={...c,target:e.layer.target},s.resolved=c)}if(c&&!c.attrs){let e=ue(c.command.name,r,a)??yc(c.command);e&&(s.resolved={...c,attrs:e})}return s},ue=(e,t,n)=>n===`registered`?te(e)?.commandState.attrs:M(t).reachableByName.get(e)?.commandState.attrs,de=(e,t,n)=>n===`registered`?te(e):M(t).reachableByName.get(e),fe=(e,t,n)=>{let r=n.input,i=n.payload;return{context:{get input(){return r},get payload(){return i},setInput(e){r=e},setPayload(e){i=e},getCommand:n=>t===`registered`?A(n):k(n,e)},getExecutionFields(){return{input:r,payload:i}}}};return{normalizeCommands:_,prependCommandResolver:v,appendCommandResolver:y,clearCommandResolvers:b,getCommands:x,getCommandEntries:S,getCommandBindings:C,getResolvedCommandChain:w,getRegisteredResolvedEntries:T,getActiveRegisteredResolvedEntries:E,resolveRegisteredResolverFallback:D,resolveActiveResolverFallback:O,getTopCommand:k,getDispatchUnavailableCommandState:j,getActiveCommandView:M,isBindingVisible:F,getBindingCommandAttrs:I,getCommandResolutionStatus:ee}}function mc(e){return e.command}function hc(e){let t=[],n=new Set;for(let r of e.commands)try{let i={},a=[],o=Qs(r.name),s=_c(r),c={};if(n.has(o)){e.onError(`duplicate-command`,{command:o},`Duplicate keymap command "${o}" in the same layer`);continue}r.name=o;for(let[t,n]of Object.entries(s)){if(n===void 0)continue;let r=e.commandFields.get(t);r&&r(n,ac({fieldName:t,conditions:e.conditions,requirements:i,matchers:a,attrs:c}))}let l={command:r,fields:s,attrs:Object.keys(c).length===0?void 0:c,requires:Object.entries(i),matchers:a};n.add(l.command.name),t.push(l)}catch(t){e.onError(`register-command-failed`,t,sc(t,`Failed to register keymap command "${String(r.name)}"`));continue}return t}function gc(e,t,n,r){if(t.length===0)return{hadError:!1};let i=!1;for(let a of t){let t,o=n();try{t=a(e,o.context)}catch(e){i=!0,r(e);continue}if(t)return{hadError:i,resolved:vc(t,o.getExecutionFields())}}return{hadError:i}}function _c(e){let t={};for(let[n,r]of Object.entries(e))!Js.has(n)&&r!==void 0&&(t[n]=r);return Object.keys(t).length===0?dc:t}function vc(e,t){return{command:e,input:t.input,payload:t.payload}}function yc(e){let t=_c(e);return t===dc?void 0:t}function bc(e){let t=e.query?.namespace,n=xc(e.query?.limit);if(n===0)return[];let r=e.query?.search?.trim().toLowerCase()??``,i=uc;e.query?.searchIn&&e.query.searchIn.length>0&&(i=e.query.searchIn);let a=e.query?.filter,o,s,c;if(typeof a==`function`)s=a;else if(a){let e=Object.entries(a),t=[];for(let[n,r]of e){if(n===`name`){if(typeof r==`string`){c=new Set([r]);continue}if(Array.isArray(r)){let e=new Set;for(let t of r)typeof t==`string`&&e.add(t);c=e;continue}}t.push([n,r])}o=t.length>0?t:void 0}let l=[];for(let a of e.entries){let u=a.commandState;if(Cc(u,t)&&Sc(u,r,i)&&!(c&&!c.has(u.command.name))&&wc(u,o,e)){if(s){let t=!1;try{t=s(e.getCommand(u))}catch(t){e.onFilterError(t);continue}if(!t)continue}if(l.push(a),n!==void 0&&l.length>=n)break}}return l}function xc(e){if(e===void 0)return;let t=Math.floor(Number(e));return!Number.isFinite(t)||t<=0?0:t}function Sc(e,t,n){if(!t)return!0;for(let r of n)if(Tc(e,r,t))return!0;return!1}function Cc(e,t){if(t===void 0)return!0;let n=e.fields;return Object.prototype.hasOwnProperty.call(n,`namespace`)?Mc(n.namespace,t):!1}function wc(e,t,n){if(!t)return!0;for(let[r,i]of t)if(!kc(e,r,i,n))return!1;return!0}function Tc(e,t,n){return Ec(e,t)?.includes(n)===!0}function Ec(e,t){let n=fc.get(e);if(n||(n=new Map,fc.set(e,n)),n.has(t))return n.get(t);let r=e.fields,i=e.attrs,a;t===`name`?a=e.command.name:Object.prototype.hasOwnProperty.call(r,t)?a=r[t]:i&&Object.prototype.hasOwnProperty.call(i,t)&&(a=i[t]);let o=Dc(a);return n.set(t,o),o}function Dc(e){if(Array.isArray(e)){let t=[];for(let n of e){let e=Dc(n);e!==void 0&&t.push(e)}return t.length>0?t.join(`\0`):void 0}if(typeof e==`string`)return e.toLowerCase();if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e).toLowerCase()}function Oc(e,t,n,r){try{return e(t,n)}catch(e){return r(e),!1}}function kc(e,t,n,r){return typeof n==`function`?Ac(e,t,n,r):jc(e,t,n)}function Ac(e,t,n,r){let i=e.command,a=e.fields,o=e.attrs,s,c=!1,l=()=>s??=r.getCommand(e);return t===`name`&&(c=!0,Oc(n,i.name,l(),r.onFilterError))||Object.prototype.hasOwnProperty.call(a,t)&&(c=!0,Oc(n,a[t],l(),r.onFilterError))||o&&Object.prototype.hasOwnProperty.call(o,t)&&(c=!0,Oc(n,o[t],l(),r.onFilterError))?!0:!c&&Oc(n,void 0,l(),r.onFilterError)}function jc(e,t,n){let r=e.command,i=e.fields,a=e.attrs;return t===`name`&&Mc(r.name,n)||Object.prototype.hasOwnProperty.call(i,t)&&Mc(i[t],n)?!0:!!a&&Object.prototype.hasOwnProperty.call(a,t)&&Mc(a[t],n)}function Mc(e,t){return Array.isArray(t)?t.some(t=>Nc(e,t)):Nc(e,t)}function Nc(e,t){return Array.isArray(e)?e.some(e=>Nc(e,t)):Object.is(e,t)}function Pc(e,t,n,r,i){let a=(e,t,n,r,a,o)=>({keymap:i.keymap,event:e,focused:t,target:n,data:r,input:a,payload:o}),o=(t,n,r,i)=>{let a=typeof n==`function`?void 0:n,o=typeof n==`function`?n:n.run,s=i?a:void 0,c;try{c=o(a?{...r,command:a}:r)}catch(n){return e.emitError(`command-execution-error`,n,`[Keymap] Error running command "${t}":`),{status:`error`,result:s?{ok:!1,reason:`error`,command:s}:{ok:!1,reason:`error`}}}if(cc(c))return c.catch(n=>{e.emitError(`async-command-error`,n,`[Keymap] Async error in command "${t}":`)}),{status:`handled`,result:s?{ok:!0,command:s}:{ok:!0}};if(Fc(c)){let e=c;return(!c.ok&&c.reason!==`not-found`&&i&&a&&!c.command||c.ok&&i&&a&&!c.command)&&(e={...c,command:a}),{status:c.ok?`handled`:`rejected`,result:e}}return c===!1?{status:`rejected`,result:s?{ok:!1,reason:`rejected`,command:s}:{ok:!1,reason:`rejected`}}:{status:`handled`,result:s?{ok:!0,command:s}:{ok:!0}}},s=(e,t,n,r,i,s,c,l)=>{let u;for(let d of t??[]){let t=o(e,d.command,a(n,r,i??d.target??null,s,e,c),l);if(t.status===`handled`||t.status===`error`)return[t.result,u];u=t.result}return[void 0,u]},c=(e,c,l)=>{let u;try{u=Zs(e)}catch{return{ok:!1,reason:`invalid-args`}}if(typeof u!=`string`)return{ok:!1,reason:`not-found`};let d=c?.includeCommand===!0,f=c?.focused??n.getFocusedTargetIfAvailable(),p=c?.event??i.createCommandEvent(),m=t.getReadonlyData(),h=c?.payload,g=l===`registered`?r.getRegisteredResolvedEntries(u):r.getActiveRegisteredResolvedEntries(u,f),[_,v]=s(u,g,p,f,c?.target,m,h,d);if(_)return _;let y=v,b=l===`registered`?r.resolveRegisteredResolverFallback(u,{input:u,payload:h}):r.resolveActiveResolverFallback(u,f,{input:u,payload:h});if(b.resolved){let e=o(u,b.resolved.command,a(p,f,c?.target??b.resolved.target??null,m,b.resolved.input??u,b.resolved.payload),d);if(e.status===`handled`||e.status===`error`)return e.result;y=e.result}if(b.hadError)return{ok:!1,reason:`error`};if(l===`active`){let e=r.getDispatchUnavailableCommandState(u,f,d);if(e)return e.command?{ok:!1,reason:e.reason,command:e.command}:{ok:!1,reason:e.reason}}return y??{ok:!1,reason:`not-found`}};return{runCommand(e,t){return c(e,t,`registered`)},dispatchCommand(e,t){return c(e,t,`active`)},runBinding(e,n,i,s,c){let l=t.getReadonlyData();if(n.run)return o(typeof n.command==`string`?n.command:`<function>`,n.run,a(i,s,e.target??null,l,typeof n.command==`string`?n.command:`<function>`,c),!1).status!==`rejected`&&(Ic(n,i),!0);if(typeof n.command!=`string`)return!1;let u=r.getResolvedCommandChain(n.command,s,c===void 0?void 0:{input:n.command,payload:c}).entries;for(let t of u??[])if(o(n.command,t.command,a(i,s,t.target??e.target??null,l,t.input??n.command,t.payload),!1).status!==`rejected`)return Ic(n,i),!0;return!1}}}function Fc(e){return typeof e==`object`&&!!e&&`ok`in e}function Ic(e,t){e.preventDefault&&(t.preventDefault(),t.stopPropagation())}var Lc=Object.freeze({}),Rc=[],zc=[];function Bc(e){if(Object.keys(e).length!==0)return lc(e,{freeze:!0})}function Vc(e,t,n,r){let i=t=>qc(t,e.bindingParsers.values(),{tokens:e.tokens,patterns:e.patterns,layer:Lc,parseObjectKey:(e,t)=>c(e,t)}),a=t=>{if(typeof t!=`string`)return[c(t)];let n=Kc(t,e.bindingParsers.values(),{tokens:e.tokens,patterns:e.patterns,layer:Lc,parseObjectKey:(e,t)=>c(e,t)});for(let e of n.unknownTokens)r.warnUnknownToken(e,t);return n.unknownTokens.length>0?[]:n.parts},o=(e,t)=>is(a(e),t),s=(i,a,o,s,d)=>{let f=[],p=!1,m=e.bindingExpanders.values(),h=e.bindingParsers.values(),g=e.bindingFields,_=e.disambiguationResolvers.has(),v=r.warnUnknownField,y=r.warnUnknownToken;for(let[r,b]of i.entries()){let i;try{i=Wc(b.key,m,{layer:d})}catch(e){t.emitError(`binding-expand-error`,e,sc(e,`Failed to expand keymap binding`));continue}for(let m of i){let i=m.key,x;try{x=typeof i==`string`?Kc(i,h,{tokens:a,patterns:e.patterns,layer:d,parseObjectKey:(e,t)=>c(e,t)}):{parts:[c(i)],usedTokens:[],unknownTokens:[],hasTokenBindings:!1},x=Gc(x,m)}catch(e){t.emitError(`binding-parse-error`,e,sc(e,`Failed to parse keymap binding`));continue}let S=x.parts;p||=x.hasTokenBindings;for(let e of x.unknownTokens)y(e,typeof i==`string`?i:String(i.name));if(!(x.unknownTokens.length>0))for(let i of u(b,S,a,h,d))try{let t=l(i.event),a=i.sequence,c={},u={},d=[];for(let e in i){if(e===`sequence`||Ys.has(e))continue;let t=i[e];if(t===void 0)continue;let r=g.get(e);if(!r){v(`binding`,e);continue}r(t,ac({fieldName:e,conditions:n,requirements:c,matchers:d,attrs:u}))}let p=Object.keys(u).length>0?Bc(u):void 0,m=Zs(i.cmd),h={binding:b,sequence:a,command:m,event:t,parsedBinding:Ns(i),sourceTarget:o,sourceLayerOrder:s,bindingIndex:r,requires:Object.keys(c).length>0?Object.entries(c):Rc,matchers:d.length>0?d:zc,preventDefault:i.preventDefault!==!1,fallthrough:i.fallthrough??!1};if(p&&(h.attrs=p),typeof m==`function`&&(h.run=m),a.length===0)continue;if(t===`release`&&a.length>1)throw Error(`Keymap release bindings only support a single key stroke`);let y=a.at(-1);if(y?.patternName){let t=e.patterns.get(y.patternName);if(t&&t.max!==t.min)throw Error(`Keymap unbounded sequence patterns must be followed by a concrete continuation`)}t===`press`&&!_&&Uc(f,h),f.push(h)}catch(e){t.emitError(`binding-compile-error`,e,sc(e,`Failed to compile keymap binding`))}}}return{bindings:f,hasTokenBindings:p}},c=(e,t)=>Zo(e,t),l=e=>{if(e===void 0||e===`press`)return`press`;if(e===`release`)return`release`;throw Error(`Invalid keymap binding event "${String(e)}": expected "press" or "release"`)},u=(n,r,i,a,o)=>{let s=e.bindingTransformers.values();if(s.length===0)return[{...n,sequence:$o(r)}];let l={...n,sequence:$o(r)},u=[],d=!0,f=o??Lc;for(let n of s)try{n(l,{layer:f,parseKey:t=>qc(t,a,{tokens:i,patterns:e.patterns,layer:f,parseObjectKey:(e,t)=>c(e,t)}),add:e=>{u.push(Ns(e))},skipOriginal:()=>{d=!1}})}catch(e){t.emitError(`binding-transformer-error`,e,`[Keymap] Error in binding transformer:`)}return d?u.length===0?[l]:[l,...u]:u};return{parseTokenKey:i,parseKeySequence:a,formatKey:o,compileBindings:s}}function Hc(e,t){if(e.length>=t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]?.match!==t[n]?.match)return!1;return!0}function Uc(e,t){for(let n of e)if(n.event===`press`&&(n.command!==void 0&&Hc(n.sequence,t.sequence)||t.command!==void 0&&Hc(t.sequence,n.sequence)))throw Error(`Keymap bindings cannot use the same sequence as both an exact match and a prefix in the same layer`)}function Wc(e,t,n){if(typeof e!=`string`||t.length===0)return[{key:e}];let r=n?.layer??Lc,i=[{key:e}];for(let e of t){let t=[];for(let n of i){let i=e({input:n.key,displays:n.displays,layer:r});if(!i){t.push(n);continue}if(i.length===0)throw Error(`Keymap binding expander must return at least one key sequence for "${n.key}"`);for(let e of i){if(!e||typeof e!=`object`||Array.isArray(e)||typeof e.key!=`string`)throw Error(`Keymap binding expander must return expansion objects with string keys for "${n.key}"`);if(e.displays!==void 0){if(!Array.isArray(e.displays))throw Error(`Keymap binding expander displays must be an array of strings for "${n.key}"`);for(let t of e.displays)if(typeof t!=`string`)throw Error(`Keymap binding expander displays must be an array of strings for "${n.key}"`)}t.push(e)}}i=t}return i}function Gc(e,t){if(!t.displays)return e;if(t.displays.length!==e.parts.length)throw Error(`Keymap binding expansion displays length must match parsed sequence length for "${String(t.key)}"`);return{...e,parts:e.parts.map((e,n)=>({...e,display:t.displays[n]}))}}function Kc(e,t,n){if(e.length===0)throw Error(`Invalid key sequence: sequence cannot be empty`);if(t.length===0)throw Error(`No keymap binding parsers are registered`);let r=n.tokens??new Map,i=n.patterns??new Map,a=n.layer??Lc,o=n.parseObjectKey,s=[],c=new Set,l=new Set,u=0;for(;u<e.length;){let n=!1;for(let d of t){let t=d({input:e,index:u,layer:a,tokens:r,patterns:i,normalizeTokenName:qo,createMatch:ns,parseObjectKey:o});if(t){if(t.nextIndex<=u||t.nextIndex>e.length)throw Error(`Keymap binding parser must advance the input for "${e}" at index ${u}`);s.push(...t.parts);for(let e of t.usedTokens??[])c.add(e);for(let e of t.unknownTokens??[])l.add(e);u=t.nextIndex,n=!0;break}}if(!n)throw Error(`No keymap binding parser handled input at index ${u} in "${e}"`)}return{parts:s,usedTokens:[...c],unknownTokens:[...l],hasTokenBindings:c.size>0||l.size>0}}function qc(e,t,n){if(typeof e!=`string`)return n.parseObjectKey(e);let{parts:r}=Kc(e,t,n),[i]=r;if(!i||r.length!==1)throw Error(`Invalid key "${String(e)}": expected a single key stroke`);return i}function Jc(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.get==`function`&&typeof t.subscribe==`function`}function Yc(e,t){let n=e=>e.requires.length===0&&e.matchers.length===0,r=e=>{try{return e.match()}catch(n){return t.emitError(`runtime-matcher-error`,n,`[Keymap] Error evaluating runtime matcher from ${e.source}:`),!1}},i=e=>{if(e.matchers.length===0)return!0;if(e.matchers.length===1){let[t]=e.matchers;return!t||r(t)}for(let t of e.matchers)if(!r(t))return!1;return!0},a=t=>{if(t.length===0)return!0;for(let[n,r]of t)if(!Object.is(e.data[n],r))return!1;return!0};return{buildRuntimeMatcher(e,t){if(typeof e==`function`)return{source:t,match:e};if(Jc(e))return{source:t,match:()=>e.get(),subscribe:t=>e.subscribe(t)};throw Error(`Keymap ${t} expected a function or a reactive matcher`)},matchesConditions:e=>n(e)||a(e.requires)&&i(e)}}var Xc=Symbol(`keymap-disambiguation-decision`),Zc=Symbol(`keymap-deferred-disambiguation-decision`);function Qc(e,t){return{[Xc]:!0,action:e,handler:t}}function $c(e){return{[Zc]:!0,action:e}}function el(e){return!!e&&typeof e==`object`&&e[Xc]===!0}function tl(e){return!!e&&typeof e==`object`&&e[Zc]===!0}function nl(e,t){return t.aborted?Promise.resolve(!1):new Promise(n=>{let r=setTimeout(()=>{t.removeEventListener(`abort`,i),n(!0)},Math.max(0,e)),i=()=>{clearTimeout(r),t.removeEventListener(`abort`,i),n(!1)};t.addEventListener(`abort`,i,{once:!0})})}function rl(e,t,n,r){let i=e.get(n);if(i)try{return i.matcher(r)}catch(e){t.emitError(`sequence-pattern-match-error`,e,`[Keymap] Error matching sequence pattern "${i.name}":`);return}}function il(e,t,n,r){let i=e.get(n)?.payloadKey??n;return{...Zo({name:t.name,ctrl:t.ctrl,shift:t.shift,meta:t.meta,super:t.super??!1,hyper:t.hyper||void 0},{display:r.display??String(r.value??t.name)}),patternName:n,payloadKey:i}}function al(e,t,n){if(!n?.patterns||n.patterns.length===0)return;let r={},i=!1;for(let a of n.patterns){let n=e.get(a.name),o;try{o=n?.finalize?n.finalize(a.values):a.values.length===1?a.values[0]:[...a.values]}catch(e){t.emitError(`sequence-pattern-finalize-error`,e,`[Keymap] Error finalizing sequence pattern "${a.name}":`);continue}let s=r[a.payloadKey];s===void 0?(r[a.payloadKey]=o,i=!0):Array.isArray(s)?s.push(o):r[a.payloadKey]=[s,o]}return i?r:void 0}function ol(e,t,n,r,i,a,o,s,c,l){let u={resolveKey:e=>o.parseTokenKey(e).match},d=null,f=0;function p(t,n,r){if(t===`key`){let t=r;return e.keyHooks.register(n,{priority:t?.priority??0,release:t?.release??!1})}if(t===`key:after`){let t=r;return e.keyAfterHooks.register(n,{priority:t?.priority??0,release:t?.release??!1})}let i=r;return e.rawHooks.register(n,{priority:i?.priority??0})}function m(t){return e.eventMatchResolvers.prepend(t)}function h(t){return e.eventMatchResolvers.append(t)}function g(){e.eventMatchResolvers.clear()}function _(t){return ee(()=>e.disambiguationResolvers.prepend(t),t)}function v(t){return ee(()=>e.disambiguationResolvers.append(t),t)}function y(){e.disambiguationResolvers.has()&&t.runWithStateChangeBatch(()=>{e.disambiguationResolvers.clear(),c.recompileBindings()})}function b(e,t){d&&G()}function x(n){let r=e.rawHooks.entries();if(r.length===0)return!1;let i=!1,a={sequence:n,stop(){i=!0}};for(let e of r){try{e.listener(a)}catch(e){t.emitError(`raw-intercept-error`,e,`[Keymap] Error in raw intercept listener:`)}if(i)return!0}return!1}function S(e,t){return{sequence:$o(e.sequence),command:e.command,commandAttrs:s.getBindingCommandAttrs(e,t,s.getActiveCommandView(t)),attrs:e.attrs,event:e.event,preventDefault:e.preventDefault,fallthrough:e.fallthrough,sourceLayerOrder:e.sourceLayerOrder,bindingIndex:e.bindingIndex}}function C(e){l.has(`dispatch`)&&l.emit(`dispatch`,e)}function w(e,t,n,r){l.has(`dispatch`)&&C({phase:e,event:n.event,focused:r,layer:{order:t.order,priority:t.priority,target:t.target,targetMode:t.targetMode},binding:S(n,r),sequence:$o(n.sequence),command:n.command})}function T(e,t,n){if(!l.has(`dispatch`))return;let i=t[0],a=t.length>0?r.collectSequencePartsFromPending({captures:t}):[];C({phase:e,event:`press`,focused:n,layer:i?{order:i.layer.order,priority:i.layer.priority,target:i.layer.target,targetMode:i.layer.targetMode}:void 0,sequence:a})}function E(t){let n=e.keyAfterHooks.entries();for(let e of n)if(e.release===t)return n}function D(e){return e.sequence?$o(e.sequence):e.captures?r.collectSequencePartsFromPending({captures:e.captures}):[]}function O(e,t){return{handled:e!==`sequence-miss`,reason:e,captures:t}}function k(e,t){return{handled:t,reason:t?`binding-handled`:`binding-rejected`,sequence:e.sequence}}function A(e,t){return t.handled||e.reason===`no-match`?t:e}function j(e,i,a,o,s){let c={event:i,eventType:a?`release`:`press`,focused:o,handled:s.handled,reason:s.reason,sequence:D(s),pendingSequence:r.getPendingSequence(),setData:(e,t)=>{n.setData(e,t)},getData:e=>n.getData(e),consume:e=>{let t=e?.preventDefault??!0,n=e?.stopPropagation??!0;t&&i.preventDefault(),n&&i.stopPropagation()}};for(let n of e)if(n.release===a)try{n.listener(c)}catch(e){t.emitError(`key-after-intercept-error`,e,`[Keymap] Error in key:after intercept listener:`)}}function M(){return{handled:!1,reason:`no-match`}}function N(e){e.preventDefault(),e.stopPropagation()}function P(e,t,n,i){r.setPendingSequence({captures:t});let a=O(`sequence-pending`,t);return T(e,t,n),N(i),a}function F(e,t,n,i){let a=O(e,t);return T(`sequence-clear`,t,n),r.setPendingSequence(null),N(i),a}function I(i,a){a||G();let o=E(a),s=o?r.getFocusedTarget():null,c=e.keyHooks.entries(),l={event:i,setData:(e,t)=>{n.setData(e,t)},getData:e=>n.getData(e),consume:e=>{let t=e?.preventDefault??!0,n=e?.stopPropagation??!0;t&&i.preventDefault(),n&&i.stopPropagation()}};for(let e of c)if(e.release===a){try{e.listener(l)}catch(e){t.emitError(`key-intercept-error`,e,`[Keymap] Error in key intercept listener:`)}if(i.propagationStopped){o&&j(o,i,a,s,{handled:!0,reason:`intercept-consumed`,sequence:[]});return}}if(a){let e=L(i);o&&j(o,i,a,s,e);return}let u=R(i);o&&j(o,i,a,s,u)}function ee(n,r){return t.runWithStateChangeBatch(()=>{let i=e.disambiguationResolvers.has(),a=n();return!i&&e.disambiguationResolvers.has()&&c.recompileBindings(),()=>{t.runWithStateChangeBatch(()=>{let t=e.disambiguationResolvers.has();a(),!e.disambiguationResolvers.values().includes(r)&&t&&!e.disambiguationResolvers.has()&&c.recompileBindings()})}})}function L(e){let t=r.getFocusedTarget(),n=r.getActiveLayers(t),a=pe(e),o=M();for(let r of a)layerLoop:for(let a of n){if(a.bindings.length===0||!i.matchesConditions(a))continue;let n=me(a,r,e,t);if(o=A(o,n.outcome),n.handled){if(n.stop)return o;continue layerLoop}}return o}function R(e){let t=r.getFocusedTarget(),n=r.ensureValidPendingSequence(),i=pe(e);if(n)return te(n,i,e,t);let a=r.getActiveLayers(t),o=M();for(let n of i){let r=re(a,[n],e,t);if(o=A(o,r),r.handled)return o}return o}function te(t,n,i,a){let o=s.getActiveCommandView(a),c=[];for(let r of t.captures){let t=ws(r,n,i,e.patterns,he,ge);t&&c.push(t)}let l=c.reduce((e,t)=>Math.min(e,Ss(t,n)),1/0),u=c.filter(e=>Ss(e,n)===l);if(u.length===0||!u.some(e=>K(e,a,o))){let e=O(`sequence-miss`,t.captures);return T(`sequence-clear`,t.captures,a),r.setPendingSequence(null),e}return ne(u,0,!1,i,a)}function ne(t,n,i,a,o){let s=i,c=M(),l=new Set;for(let i=n;i<t.length;i+=1){let n=t[i];if(!n||l.has(n))continue;let u=de(t,i,n);if(u.length>0){if(s)continue;let e=fe(t,n);return B(t,i,u,e,a,o,s)||P(`sequence-advance`,u,o,a)}if(!_s(n,e.patterns))continue;let d=fe(t,n);for(let e of d)l.add(e);let f=be(n.layer,d,a,o);if(c=A(c,f.outcome),f.handled&&(s=!0,f.stop))return T(`sequence-clear`,t,o),r.setPendingSequence(null),c}return T(`sequence-clear`,t,o),r.setPendingSequence(null),c}function re(e,t,n,r){return z(e,0,t,n,r)}function z(t,n,r,a,o){let c=s.getActiveCommandView(o),l=M();for(let s=n;s<t.length;s+=1){let n=t[s];if(!n||!i.matchesConditions(n))continue;let u=_e(n,r,a,o,c);if(u.length===0)continue;if(u.filter(t=>gs(t,e.patterns,!1)).length>0){let n=u.filter(t=>_s(t,e.patterns)),i=ue(t,s,r,a,o);return ie(t,s,r,i,n,a,o)||P(`sequence-start`,i,o,a)}let d=be(n,u.filter(t=>_s(t,e.patterns)),a,o);if(l=A(l,d.outcome),d.handled&&d.stop)return l}return l}function ie(e,t,n,i,a,o,s){return V({event:o,focused:s,continuationCaptures:i,exactBindingsSource:a.map(e=>e.binding),sequencePhase:`sequence-start`,runExact:()=>{r.setPendingSequence(null);let i=a[0]?.layer;if(!i)return M();let c=be(i,a,o,s);return c.stop?c.outcome:A(c.outcome,z(e,t+1,n,o,s))}})}function B(e,t,n,i,a,o,s){return V({event:a,focused:o,continuationCaptures:n,exactBindingsSource:i.map(e=>e.binding),sequencePhase:`sequence-advance`,runExact:()=>{r.setPendingSequence(null);let n=i[0]?.layer;if(!n)return M();let c=be(n,i,a,o);return c.stop?c.outcome:A(c.outcome,ne(e,t+1,s||c.handled,a,o))}})}function V(t){let{event:n,focused:i,continuationCaptures:a,exactBindingsSource:o,sequencePhase:c,runExact:l}=t;if(!e.disambiguationResolvers.has()||a.length===0)return;let u=s.getActiveCommandView(i),d=r.collectMatchingBindings(o,i,u);if(!d.some(e=>e.command!==void 0))return;let f=()=>P(c,a,i,n),p=()=>F(`sequence-cleared`,a,i,n),m,h=()=>(m??=r.collectSequencePartsFromPending({captures:a}),m),g=H({event:n,focused:i,getSequence:h,exactBindings:d,continuationCaptures:a,activeView:u});return g?ae(g,a,l,f,p,i,h):(le(h()),f())}function ae(e,t,n,r,i,a,o){if(e.action===`run-exact`)return n();if(e.action===`continue-sequence`)return r();if(e.action===`clear`)return i();let s=r();return U(t,e.handler,a,o(),e=>{if(e){if(e.action===`run-exact`){n();return}if(e.action===`continue-sequence`){r();return}i()}}),s}function H(i){let a,o,s,c,l={event:i.event,focused:i.focused,get sequence(){return a??=$o(i.getSequence()),a},get stroke(){let e=i.getSequence().at(-1);if(!e)throw Error(`Disambiguation context expected a non-empty sequence`);return c??={...e,stroke:Xo(e.stroke)},c},get exact(){return o??=r.collectActiveBindings(i.exactBindings,i.focused,i.activeView).map(e=>({...e,sequence:$o(e.sequence)})),o},get continuations(){return s??=r.getActiveKeysForCaptures(i.continuationCaptures,{includeBindings:!0,includeMetadata:!0}),s},getData:e=>n.getData(e),setData:(e,t)=>{n.setData(e,t)},runExact:()=>Qc(`run-exact`),continueSequence:()=>Qc(`continue-sequence`),clear:()=>Qc(`clear`),defer:e=>Qc(`defer`,e)};for(let n of e.disambiguationResolvers.values()){let e;try{e=n(l)}catch(e){t.emitError(`disambiguation-resolver-error`,e,`[Keymap] Error in disambiguation resolver:`);continue}if(e!==void 0){if(cc(e)){t.emitError(`invalid-disambiguation-resolver-return`,e,`[Keymap] Disambiguation resolvers must return synchronously; use ctx.defer(...) for async handling`);continue}if(!el(e)){t.emitError(`invalid-disambiguation-decision`,e,`[Keymap] Invalid disambiguation decision returned by resolver:`);continue}return e}}}function U(e,t,n,r,i){G();let a=new AbortController,o={id:f++,controller:a,captures:e,apply:i};d=o,queueMicrotask(()=>{W(o,t,n,r)})}function W(e,n,r,i){if(!ce(e))return;let a={signal:e.controller.signal,sequence:$o(i),focused:r,sleep:t=>nl(t,e.controller.signal),runExact:()=>$c(`run-exact`),continueSequence:()=>$c(`continue-sequence`),clear:()=>$c(`clear`)},o;try{o=n(a)}catch(n){ce(e)&&(t.emitError(`deferred-disambiguation-error`,n,`[Keymap] Error in deferred disambiguation handler:`),se(e));return}if(cc(o)){o.then(t=>{oe(e,t)}).catch(n=>{ce(e)&&(t.emitError(`deferred-disambiguation-error`,n,`[Keymap] Error in deferred disambiguation handler:`),se(e))});return}oe(e,o)}function oe(e,n){if(ce(e)){if(n!==void 0&&!tl(n)){t.emitError(`invalid-deferred-disambiguation-decision`,n,`[Keymap] Invalid deferred disambiguation decision returned by handler:`),se(e);return}se(e),e.apply(n)}}function se(e){ce(e)&&(d=null)}function G(){let e=d;e&&(d=null,e.controller.abort())}function ce(e){return d===e}function le(e){let n=is(e,{preferDisplay:!0});t.warnOnce(`unresolved-disambiguation:${n}`,`unresolved-disambiguation`,{sequence:n},`[Keymap] Ambiguous exact/prefix sequence "${n}" fell back to prefix handling because no disambiguation resolver resolved it`)}function ue(t,n,r,a,o){let c=[],l=s.getActiveCommandView(o);for(let s=n;s<t.length;s+=1){let n=t[s];if(n&&i.matchesConditions(n))for(let t of _e(n,r,a,o,l))gs(t,e.patterns,!1)&&c.push(t)}return c}function de(t,n,r){return t.filter((t,i)=>i>=n&&gs(t,e.patterns,!1)&&cl(t.parts,r.parts))}function fe(t,n){return t.filter(t=>t.layer===n.layer&&_s(t,e.patterns)&&cl(t.parts,n.parts))}function pe(n){let r=e.eventMatchResolvers.values();if(r.length===0)return[];if(r.length===1)return sl(r[0],n,u,t);let i=[],a=new Set;for(let e of r){let r;try{r=e(n,u)}catch(e){t.emitError(`event-match-resolver-error`,e,`[Keymap] Error in event match resolver:`);continue}if(!(!r||r.length===0))for(let e of r){if(typeof e!=`string`){t.emitError(`invalid-event-match-resolver-candidate`,e,`[Keymap] Invalid event match resolver candidate:`);continue}a.has(e)||(a.add(e),i.push(e))}}return i}function me(e,t,n,r){let o=!1,s=M();for(let c of e.bindings){if(c.event!==`release`)continue;let l=c.sequence[0];if(!l||l.match!==t||!i.matchesConditions(c))continue;let u=a.runBinding(e,c,n,r);if(s=A(s,k(c,u)),!u){w(`binding-reject`,e,c,r);continue}if(w(`binding-execute`,e,c,r),o=!0,!c.fallthrough)return{handled:!0,stop:!0,outcome:s}}return{handled:o,stop:!1,outcome:s}}function he(n,r){return rl(e.patterns,t,n,r)}function ge(t,n,r){return il(e.patterns,t,n,r)}function _e(e,t,n,r,i){let a=Ts(e,t,n,he,ge);return a.some(e=>K(e,r,i))?a:[]}function ve(n){return al(e.patterns,t,n)}function ye(e,t,n){return i.matchesConditions(e)&&s.isBindingVisible(e,t,n)}function K(e,t,n){return ye(e.binding,t,n)}function be(e,t,n,r){let o=!1,s=M();for(let c of t){let t=c.binding;if(!i.matchesConditions(t))continue;let l=a.runBinding(e,t,n,r,ve(c));if(s=A(s,k(t,l)),!l){w(`binding-reject`,e,t,r);continue}if(w(`binding-execute`,e,t,r),o=!0,!t.fallthrough)return{handled:!0,stop:!0,outcome:s}}return{handled:o,stop:!1,outcome:s}}return{intercept:p,prependEventMatchResolver:m,appendEventMatchResolver:h,clearEventMatchResolvers:g,prependDisambiguationResolver:_,appendDisambiguationResolver:v,clearDisambiguationResolvers:y,handlePendingSequenceChange:b,handleRawSequence:x,handleKeyEvent:I}}function sl(e,t,n,r){let i;try{i=e(t,n)}catch(e){return r.emitError(`event-match-resolver-error`,e,`[Keymap] Error in event match resolver:`),[]}if(!i||i.length===0)return[];if(i.length===1){let[e]=i;return typeof e==`string`?[e]:(r.emitError(`invalid-event-match-resolver-candidate`,e,`[Keymap] Invalid event match resolver candidate:`),[])}let a=[],o=new Set;for(let e of i){if(typeof e!=`string`){r.emitError(`invalid-event-match-resolver-candidate`,e,`[Keymap] Invalid event match resolver candidate:`);continue}o.has(e)||(o.add(e),a.push(e))}return a}function cl(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]?.match!==t[n]?.match)return!1;return!0}var ll=()=>{};function ul(e,t,n,r){if(n===void 0)return r;if(typeof n!=`number`||!Number.isInteger(n)||n<0)throw Error(`Keymap sequence pattern "${e}" ${t} must be a non-negative integer`);return n}function dl(e,t){let{kind:n,reservedFields:r,registeredFields:i,emitError:a}=t,o=Object.entries(e),s=[];for(let[e,t]of o){if(r.has(e)){a(`reserved-${n}-field`,{field:e,kind:n},`Keymap ${n} field "${e}" is reserved`);continue}if(i.has(e)){a(`duplicate-${n}-field`,{field:e,kind:n},`Keymap ${n} field "${e}" is already registered`);continue}i.set(e,t),s.push([e,t])}return()=>{for(let[e,t]of s)i.get(e)===t&&i.delete(e)}}function fl(e,t,n,r,i){let a;try{a=qo(i.name)}catch(e){return t.emitError(`token-name-normalize-error`,e,sc(e,`Failed to register keymap token`)),ll}if(e.tokens.has(a)||e.patterns.has(a))return t.emitError(`duplicate-token`,{token:a},`Keymap token "${a}" is already registered`),ll;let o;try{if(o=n.parseTokenKey(i.key),o.patternName)throw Error(`Invalid key "${String(i.key)}": expected a concrete key stroke`)}catch(e){return t.emitError(`token-parse-error`,e,sc(e,`Failed to register keymap token "${a}"`)),ll}let s={stroke:o.stroke,match:o.match},c=new Map(e.tokens);c.set(a,s);try{r.applyTokenState(c)}catch(e){return t.emitError(`token-register-error`,e,sc(e,`Failed to register keymap token "${a}"`)),ll}return()=>{if(e.tokens.get(a)!==s)return;let n=new Map(e.tokens);n.delete(a);try{r.applyTokenState(n)}catch(e){t.emitError(`token-unregister-error`,e,sc(e,`Failed to unregister keymap token "${a}"`))}}}function pl(e,t,n,r){let i,a;try{i=qo(r.name);let e=ul(i,`min`,r.min,1),t=ul(i,`max`,r.max,2**53-1);if(t<e)throw Error(`Keymap sequence pattern "${i}" max must be greater than or equal to min`);a={name:i,display:r.display,payloadKey:r.payloadKey??i,match:ns(`pattern:${i}`),min:e,max:t,matcher:e=>r.match(e),finalize:r.finalize}}catch(e){return t.emitError(`sequence-pattern-register-error`,e,sc(e,`Failed to register keymap sequence pattern`)),ll}return e.tokens.has(i)||e.patterns.has(i)?(t.emitError(`duplicate-sequence-pattern`,{pattern:i},`Keymap sequence pattern "${i}" is already registered`),ll):(e.patterns.set(i,a),n.recompileBindings(),()=>{e.patterns.get(i)===a&&(e.patterns.delete(i),n.recompileBindings())})}function ml(e,t,n,r){return dl(r,{kind:n,reservedFields:n===`layer`?Xs:n===`binding`?Ys:Js,registeredFields:n===`layer`?e.layerFields:n===`binding`?e.bindingFields:e.commandFields,emitError:(e,n,r)=>t.emitError(e,n,r)})}var hl=()=>{};function gl(e,t){return t.priority-e.priority||t.order-e.order}function _l(e){if(e.matchers.length>0)return!0;for(let t of e.commands)if(t.matchers.length>0)return!0;for(let t of e.bindings)if(t.matchers.length>0)return!0;return!1}function vl(e){if(e.commands.length===0)return!1;if(e.matchers.length>0)return!0;for(let t of e.commands)if(t.matchers.length>0)return!0;return!1}function yl(e,t,n,r,i){let a=n=>t.runWithStateChangeBatch(()=>{let a=n.target;if(a&&i.host.isTargetDestroyed(a))return t.emitError(`destroyed-layer-target`,{target:a},`Cannot register a keymap layer for a destroyed keymap target`),hl;let o,s,c,p,m,v,y;try{y=l(n),o=u(Ms(n.bindings??[]),n);let e=d(n.commands??[],n);v=e.length===0?[]:i.commands.normalizeCommands(e),{requires:s,matchers:c,fields:p,attrs:m}=f(n)}catch(e){return t.emitError(`register-layer-failed`,e,sc(e,`Failed to register keymap layer`)),hl}let b=e.order++,x=i.compiler.compileBindings(o,e.tokens,a,b,p);if(x.bindings.length===0&&!x.hasTokenBindings&&v.length===0)return hl;i.diagnostics?.analyzeLayer({target:a,order:b,commands:v,sourceBindings:o,bindings:x.bindings,hasTokenBindings:x.hasTokenBindings});let S={order:b,target:a,targetMode:y,priority:n.priority??0,requires:s,matchers:c,fields:p,attrs:m,commands:v,sourceBindings:o,bindings:x.bindings,root:ys(x.bindings,e.patterns),hasTokenBindings:x.hasTokenBindings,activeKeyCacheBlocked:!1,activeCommandViewCacheBlocked:!1};_(S),e.layers.add(S),e.sortedLayers=[...e.sortedLayers,S].sort(gl),g(S);for(let e of S.commands)g(e);for(let e of S.bindings)g(e);return a&&(S.offTargetDestroy=i.host.onTargetDestroy(a,()=>{h(S)})),S.commands.length>0&&r.ensureValidPendingSequence(),t.queueStateChange(),()=>{h(S)}}),o=n=>{t.runWithStateChangeBatch(()=>{let i=new Map;for(let t of e.layers)t.hasTokenBindings&&i.set(t,p(t,n));e.tokens=n;let a=!1;for(let[e,t]of i)m(e,t)&&(a=!0);a&&r.setPendingSequence(null),i.size>0&&t.queueStateChange()})},s=()=>{t.runWithStateChangeBatch(()=>{let n=0,i=!1;for(let t of e.layers){if(t.sourceBindings.length===0)continue;let r=p(t,e.tokens);m(t,r)&&(i=!0),n+=1}i&&r.setPendingSequence(null),n>0&&t.queueStateChange()})},c=()=>{for(let t of e.layers){y(t);for(let e of t.commands)y(e);for(let e of t.bindings)y(e);t.offTargetDestroy?.(),t.offTargetDestroy=void 0}},l=e=>{if(e.targetMode){if(!e.target)throw Error(`Keymap targetMode "${e.targetMode}" requires a target`);return e.targetMode}return e.target?`focus-within`:void 0},u=(t,n)=>{let r=e.layerBindingsTransformers.values();if(r.length===0)return t;let i=t;for(let e of r){let t=e(i,{layer:n,validateBindings:e=>js(e)});t&&(i=Ms(t))}return i},d=(n,r)=>{let i=e.commandTransformers.values();if(n.length===0||i.length===0)return n;let a=[];for(let e of n){let n={...e},o=[],s=!0;for(let e of i)try{e(n,{layer:r,add(e){o.push({...e})},skipOriginal(){s=!1}})}catch(e){t.emitError(`command-transformer-error`,e,`[Keymap] Error in command transformer:`)}s&&a.push(n),a.push(...o)}return a},f=t=>{let r={},a=[],o=Object.create(null),s={};for(let[c,l]of Object.entries(t)){if(Xs.has(c)||l===void 0)continue;o[c]=lc(l);let t=e.layerFields.get(c);if(!t){i.warnUnknownField(`layer`,c);continue}t(l,ac({fieldName:c,conditions:n,requirements:r,matchers:a,attrs:s}))}return{requires:Object.entries(r),matchers:a,fields:Object.keys(o).length>0?Object.freeze(o):void 0,attrs:Object.keys(s).length>0?lc(s,{freeze:!0}):void 0}},p=(e,t)=>i.compiler.compileBindings(e.sourceBindings,t,e.target,e.order,e.fields),m=(t,n)=>{i.diagnostics?.analyzeLayer({target:t.target,order:t.order,commands:t.commands,sourceBindings:t.sourceBindings,bindings:n.bindings,hasTokenBindings:n.hasTokenBindings}),v(t);for(let e of t.bindings)y(e);t.bindings=n.bindings,t.root=ys(n.bindings,e.patterns),t.hasTokenBindings=n.hasTokenBindings,_(t);for(let e of t.bindings)g(e);return e.pending?.captures.some(e=>e.layer===t)??!1},h=n=>{t.runWithStateChangeBatch(()=>{if(e.layers.delete(n)){e.sortedLayers=e.sortedLayers.filter(e=>e!==n),v(n),y(n);for(let e of n.commands)y(e);for(let e of n.bindings)y(e);n.offTargetDestroy?.(),n.offTargetDestroy=void 0,e.pending?.captures.some(e=>e.layer===n)?r.setPendingSequence(null):n.commands.length>0&&!i.host.isDestroyed&&r.ensureValidPendingSequence(),t.queueStateChange()}})},g=e=>{for(let n of e.matchers)if(n.subscribe)try{n.dispose=n.subscribe(()=>{if(!r.hasPendingSequenceState()){t.queueStateChange();return}t.runWithStateChangeBatch(()=>{r.revalidatePendingSequenceIfNeeded(),t.queueStateChange()})})}catch(e){t.emitError(`reactive-matcher-subscribe-error`,e,sc(e,`Failed to subscribe to reactive matcher from ${n.source}`))}},_=t=>{let n=_l(t),r=vl(t);t.activeKeyCacheBlocked=n,t.activeCommandViewCacheBlocked=r,n&&(e.activeKeyCacheBlockers+=1),r&&(e.activeCommandViewCacheBlockers+=1)},v=t=>{t.activeKeyCacheBlocked&&=(--e.activeKeyCacheBlockers,!1),t.activeCommandViewCacheBlocked&&=(--e.activeCommandViewCacheBlockers,!1)},y=e=>{for(let n of e.matchers)if(n.dispose){try{n.dispose()}catch(e){t.emitError(`reactive-matcher-dispose-error`,e,sc(e,`Failed to dispose reactive matcher from ${n.source}`))}n.dispose=void 0}};return{registerLayer:a,applyTokenState:o,recompileBindings:s,cleanup:c}}var bl=1e3;function xl(e,t,n){let r=(e,n,r)=>{if(!t.has(`warning`)){let t=`[${e}] ${r}`;n instanceof Error?console.warn(t,n):console.warn(t);return}t.emit(`warning`,{code:e,message:r,warning:n})},i=(e,n,r)=>{if(!t.has(`error`)){let t=`[${e}] ${r}`;n instanceof Error?console.error(t,n):console.error(t);return}t.emit(`error`,{code:e,message:r,error:n})},a=()=>{if(!(!e.stateChangePending||e.stateChangeDepth>0||e.flushingStateChange)){e.flushingStateChange=!0;try{let t=0;for(;e.stateChangePending&&e.stateChangeDepth===0;){if(t>=bl){e.stateChangePending=!1,i(`state-change-feedback-loop`,{iterations:bl},`[Keymap] Possible infinite state listener feedback loop detected after ${bl} iterations; pending state notifications were dropped`);break}t+=1,e.stateChangePending=!1,n.emit(`state`)}}finally{e.flushingStateChange=!1}}};return{runWithStateChangeBatch(t){e.stateChangeDepth+=1;try{return t()}finally{--e.stateChangeDepth,e.stateChangeDepth===0&&a()}},queueStateChange(t){e.derivedVersion+=1,t?.invalidateCaches!==!1&&(e.cacheVersion+=1),n.has(`state`)&&(e.stateChangePending=!0,e.stateChangeDepth===0&&!e.flushingStateChange&&a())},emitWarning:r,emitError:i,reportListenerError(e,t){if(e===`state`){i(`state-listener-error`,t,`[Keymap] Error in state listener:`);return}if(e===`pendingSequence`){i(`pending-sequence-listener-error`,t,`[Keymap] Error in pending sequence listener:`);return}e===`dispatch`&&i(`dispatch-listener-error`,t,`[Keymap] Error in dispatch listener:`)},warnOnce(t,n,i,a){e.usedWarningKeys.has(t)||(e.usedWarningKeys.add(t),r(n,i,a))}}}function Sl(e,t,n){return{getData(t){return e.data[t]},setData(r,i){t.runWithStateChangeBatch(()=>{if(i===void 0){if(!(r in e.data))return;delete e.data[r],e.dataVersion+=1,n.ensureValidPendingSequence(),t.queueStateChange();return}Object.is(e.data[r],i)||(e.data[r]=i,e.dataVersion+=1,n.ensureValidPendingSequence(),t.queueStateChange())})},getReadonlyData(){return e.readonlyDataVersion===e.dataVersion?e.readonlyData:(e.readonlyData=Object.freeze({...e.data}),e.readonlyDataVersion=e.dataVersion,e.readonlyData)}}}var Cl=Object.freeze({});function wl(){return{order:0,tokens:new Map,patterns:new Map,layerFields:new Map,layerBindingsTransformers:Os(),bindingExpanders:Os(),bindingParsers:Os(),bindingTransformers:Os(),bindingFields:new Map,commandTransformers:Os(),commandFields:new Map,eventMatchResolvers:Os(),disambiguationResolvers:Os(),keyHooks:ks(),keyAfterHooks:ks(),rawHooks:ks(),layers:new Set,sortedLayers:[],activeLayersCacheVersion:-1,activeLayersCacheFocused:void 0,activeLayersCache:[],activeKeyCacheBlockers:0,activeCommandViewCacheBlockers:0,commandResolvers:Os(),pending:null,data:{},dataVersion:0,readonlyDataVersion:-1,readonlyData:Cl,cacheVersion:0,derivedVersion:0,stateChangeDepth:0,stateChangePending:!1,flushingStateChange:!1,usedWarningKeys:new Set}}function Tl(e){return es(e)}var El=class{#e=wl();#t=!1;#n=new Map;#r=[];#i=Es(()=>{});#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;getPendingSequence;getActiveKeys;constructor(e){if(this.#b=e,e.isDestroyed)throw Error(`Cannot create a keymap for a destroyed host`);this.#a=Es((e,t)=>{this.#o.reportListenerError(e,t)}),this.#o=xl(this.#e,this.#i,this.#a),this.#l=Yc(this.#e,this.#o),this.#u=pc(this.#e,this.#b,this.#o,this.#l,{onCommandResolversChanged:()=>{this.#s.ensureValidPendingSequence()}}),this.#s=qs(this.#e,this.#b,this.#a,this.#o,this.#l,this.#u,{onPendingSequenceChanged:(e,t)=>{this.#p?.handlePendingSequenceChange(e,t)}}),this.#c=Sl(this.#e,this.#o,this.#s),this.#d=Pc(this.#o,this.#c,this.#s,this.#u,{keymap:this,createCommandEvent:()=>this.#b.createCommandEvent()}),this.#f=Vc(this.#e,this.#o,this.#l,{warnUnknownField:(e,t)=>{this.#C(e,t)},warnUnknownToken:(e,t)=>{this.#w(e,t)}}),this.#h=Ps(this.#o,this.#u),this.#m=yl(this.#e,this.#o,this.#l,this.#s,{compiler:this.#f,commands:this.#u,host:this.#b,diagnostics:this.#h,warnUnknownField:(e,t)=>{this.#C(e,t)}}),this.#p=ol(this.#e,this.#o,this.#c,this.#s,this.#l,this.#d,this.#f,this.#u,this.#m,this.#a),this.getPendingSequence=this.#s.getPendingSequence,this.getActiveKeys=this.#s.getActiveKeys,this.#g=e=>{this.#p.handleKeyEvent(e,!1)},this.#_=e=>{this.#p.handleKeyEvent(e,!0)},this.#v=e=>this.#p.handleRawSequence(e),this.#y=e=>{this.#S(e)},this.#r.push(this.#b.onKeyPress(this.#g)),this.#r.push(this.#b.onKeyRelease(this.#_)),this.#b.onRawInput&&this.#r.push(this.#b.onRawInput(this.#v)),this.#r.push(this.#b.onFocusChange(this.#y)),this.#b.onDestroy&&this.#r.push(this.#b.onDestroy(()=>{this.#x()}))}[ss](){return{state:this.#e,host:this.#b,conditions:this.#l,catalog:this.#u,activation:this.#s}}#x(){if(!this.#t){this.#t=!0,this.#s.setPendingSequence(null);for(let e of this.#n.values())e.dispose();this.#n.clear(),this.#m.cleanup();for(let e of this.#r.splice(0))e()}}setData(e,t){this.#c.setData(e,t)}getData(e){return this.#c.getData(e)}getHostMetadata(){return this.#b.metadata}hasPendingSequence(){return this.#s.ensureValidPendingSequence()!==void 0}createKeyMatcher(e){let t=this.#f.parseTokenKey(e).match;return e=>e?Tl(e)===t:!1}parseKeySequence(e){return this.#f.parseKeySequence(e)}formatKey(e,t){return this.#f.formatKey(e,t)}clearPendingSequence(){this.#s.setPendingSequence(null)}popPendingSequence(){return this.#s.popPendingSequence()}getCommands(e){return this.#u.getCommands(e)}getCommandEntries(e){return this.#u.getCommandEntries(e)}getCommandBindings(e){return this.#u.getCommandBindings(e)}acquireResource(e,t){if(this.#t||this.#b.isDestroyed)throw Error(`Cannot use a keymap after its host was destroyed`);let n=this.#n.get(e);if(n)return n.count+=1,()=>{this.#T(e,n)};let r={count:1,dispose:t()};return this.#n.set(e,r),()=>{this.#T(e,r)}}runCommand(e,t){return this.#d.runCommand(e,t)}dispatchCommand(e,t){return this.#d.dispatchCommand(e,t)}on(e,t){return e===`warning`||e===`error`?this.#i.hook(e,t):this.#a.hook(e,t)}intercept(e,t,n){return this.#p.intercept(e,t,n)}registerLayer(e){return this.#m.registerLayer(e)}registerLayerFields(e){return ml(this.#e,this.#o,`layer`,e)}prependLayerBindingsTransformer(e){return this.#e.layerBindingsTransformers.prepend(e)}appendLayerBindingsTransformer(e){return this.#e.layerBindingsTransformers.append(e)}clearLayerBindingsTransformers(){this.#e.layerBindingsTransformers.clear()}prependBindingTransformer(e){return this.#e.bindingTransformers.prepend(e)}appendBindingTransformer(e){return this.#e.bindingTransformers.append(e)}clearBindingTransformers(){this.#e.bindingTransformers.clear()}prependCommandTransformer(e){return this.#e.commandTransformers.prepend(e)}appendCommandTransformer(e){return this.#e.commandTransformers.append(e)}clearCommandTransformers(){this.#e.commandTransformers.clear()}prependBindingParser(e){return this.#e.bindingParsers.prepend(e)}appendBindingParser(e){return this.#e.bindingParsers.append(e)}clearBindingParsers(){this.#e.bindingParsers.clear()}registerToken(e){return fl(this.#e,this.#o,this.#f,this.#m,e)}registerSequencePattern(e){return pl(this.#e,this.#o,this.#m,e)}prependBindingExpander(e){return this.#e.bindingExpanders.prepend(e)}appendBindingExpander(e){return this.#e.bindingExpanders.append(e)}clearBindingExpanders(){this.#e.bindingExpanders.clear()}registerBindingFields(e){return ml(this.#e,this.#o,`binding`,e)}registerCommandFields(e){return ml(this.#e,this.#o,`command`,e)}prependCommandResolver(e){return this.#u.prependCommandResolver(e)}appendCommandResolver(e){return this.#u.appendCommandResolver(e)}clearCommandResolvers(){this.#u.clearCommandResolvers()}prependLayerAnalyzer(e){return this.#h.prependLayerAnalyzer(e)}appendLayerAnalyzer(e){return this.#h.appendLayerAnalyzer(e)}clearLayerAnalyzers(){this.#h.clearLayerAnalyzers()}prependEventMatchResolver(e){return this.#p.prependEventMatchResolver(e)}appendEventMatchResolver(e){return this.#p.appendEventMatchResolver(e)}clearEventMatchResolvers(){this.#p.clearEventMatchResolvers()}prependDisambiguationResolver(e){return this.#p.prependDisambiguationResolver(e)}appendDisambiguationResolver(e){return this.#p.appendDisambiguationResolver(e)}clearDisambiguationResolvers(){this.#p.clearDisambiguationResolvers()}#S(e){this.#o.runWithStateChangeBatch(()=>{this.#s.setPendingSequence(null),this.#o.queueStateChange({invalidateCaches:!1})})}#C(e,t){this.#o.warnOnce(`${e}:${t}`,`unknown-${e}-field`,{field:t,kind:e},`[Keymap] Unknown ${e} field "${t}" was ignored`)}#w(e,t){this.#o.warnOnce(`token:${e}`,`unknown-token`,{token:e,sequence:t},`[Keymap] Unknown token "${e}" in key sequence "${t}"; binding was skipped until the token is registered`)}#T(e,t){this.#n.get(e)===t&&(--t.count,!(t.count>0)&&(t.dispose(),this.#n.delete(e)))}},Dl=new Set(`up.down.left.right.clear.escape.return.linefeed.enter.tab.backspace.delete.insert.home.end.pageup.pagedown.space.lt.gt.plus.minus.equal.comma.period.slash.backslash.semicolon.quote.backquote.leftbracket.rightbracket.capslock.numlock.scrolllock.printscreen.pause.menu.apps.kp0.kp1.kp2.kp3.kp4.kp5.kp6.kp7.kp8.kp9.kpdecimal.kpdivide.kpmultiply.kpminus.kpplus.kpenter.kpequal.kpseparator.kpleft.kpright.kpup.kpdown.kppageup.kppagedown.kphome.kpend.kpinsert.kpdelete.mediaplay.mediapause.mediaplaypause.mediareverse.mediastop.mediafastforward.mediarewind.medianext.mediaprev.mediarecord.volumedown.volumeup.mute.leftshift.leftctrl.leftalt.leftsuper.lefthyper.leftmeta.rightshift.rightctrl.rightalt.rightsuper.righthyper.rightmeta.iso_level3_shift.iso_level5_shift.option.alt.meta.super.hyper.control.ctrl.shift`.split(`.`)),Ol=new Set([`ctrl`,`control`,`shift`,`meta`,`alt`,`option`,`super`,`hyper`]),kl=jl(Dl),Al=jl(Ol);function jl(e){let t=new Map;for(let n of e){let e=n.charCodeAt(0);if(Number.isNaN(e))continue;let r=t.get(e);r||(r=[],t.set(e,r)),r.push(n)}for(let e of t.values())e.sort((e,t)=>t.length-e.length);return t}function Ml(e){return e>=65&&e<=90?e+32:e}function Nl(e){return e>=48&&e<=57}function Pl(e,t,n){if(e.startsWith(t,n))return!0;if(n+t.length>e.length)return!1;for(let r=0;r<t.length;r+=1)if(Ml(e.charCodeAt(n+r))!==t.charCodeAt(r))return!1;return!0}function Fl(e,t,n){let r=t.charCodeAt(n);if(Number.isNaN(r))return;let i=e.get(Ml(r));if(i){for(let e of i)if(Pl(t,e,n))return e}}function Il(e,t,n,r,i){return e.parseObjectKey(t,{display:n,match:r,tokenName:i})}function Ll(e,t){if(e===` `)return t.parseObjectKey({name:`space`},{display:`space`});if(e===`+`)return t.parseObjectKey({name:`+`},{display:`+`});let n=e.split(`+`),r=``,i=``,a=!1,o=!1,s=!1,c=!1,l=!1;for(let t of n){let n=t.trim();if(!n)continue;let u=n.toLowerCase();if(u===`ctrl`||u===`control`){a=!0;continue}if(u===`shift`){o=!0;continue}if(u===`meta`||u===`alt`||u===`option`){s=!0;continue}if(u===`super`){c=!0;continue}if(u===`hyper`){l=!0;continue}if(r)throw Error(`Invalid key "${e}": multiple key names are not supported`);r=n,i=u}if(!r)throw Error(`Invalid key "${e}": missing key name`);let u=[];return a&&u.push(`ctrl`),o&&u.push(`shift`),s&&u.push(`meta`),c&&u.push(`super`),l&&u.push(`hyper`),u.push(i),t.parseObjectKey({name:r,ctrl:a,shift:o,meta:s,super:c,hyper:l||void 0},{display:u.join(`+`)})}function Rl(e,t){let n=e.trim().toLowerCase();return t.parseObjectKey({name:n},{display:n})}function zl(e,t){let n=Fl(kl,e,t);if(n)return n;if(Ml(e.charCodeAt(t))!==102||!Nl(e.charCodeAt(t+1)))return;let r=Nl(e.charCodeAt(t+2))?t+3:t+2;return e.slice(t,r).toLowerCase()}function Bl(e,t){return Fl(Al,e,t)}function Vl(e,t,n){let r=t,i=!1,a=!1,o=!1,s=!1,c=!1;for(;r<e.length;){let t=Bl(e,r);if(!t)break;let n=r+t.length;if(e[n]!==`+`)break;t===`ctrl`||t===`control`?i=!0:t===`shift`?a=!0:t===`meta`||t===`alt`||t===`option`?o=!0:t===`super`?s=!0:t===`hyper`&&(c=!0),r=n+1}if(r===t)return;let l=e[r];if(l===void 0)throw Error(`Invalid key "${e.slice(t)}": missing key name`);let u=zl(e,r)??l,d=u===` `?`space`:u===`+`?`+`:u.toLowerCase(),f=[];return i&&f.push(`ctrl`),a&&f.push(`shift`),o&&f.push(`meta`),s&&f.push(`super`),c&&f.push(`hyper`),f.push(d),{part:n.parseObjectKey({name:u===` `?`space`:u,ctrl:i,shift:a,meta:o,super:s,hyper:c||void 0},{display:f.join(`+`)}),nextIndex:r+u.length}}var Hl=e=>{let{input:t,index:n,tokens:r,normalizeTokenName:i}=e;if(n===0&&t.includes(`+`)&&/\s/.test(t))return{parts:[Ll(t,e)],nextIndex:t.length};let a=t[n];if(a===void 0)return;if(a===`<`){let o=t.indexOf(`>`,n);if(o===-1)return{parts:[Ll(a,e)],nextIndex:n+1};let s=i(t.slice(n+1,o)),c=r.get(s);return c?{parts:[Il(e,c.stroke,`<${s}>`,c.match,s)],nextIndex:o+1,usedTokens:[s]}:{parts:[],nextIndex:o+1,unknownTokens:[s]}}if(a===`{`){let r=t.indexOf(`}`,n);if(r===-1)return{parts:[Ll(a,e)],nextIndex:n+1};let o=i(t.slice(n+1,r)),s=e.patterns.get(o);return s?{parts:[{...e.parseObjectKey({name:o,ctrl:!1,shift:!1,meta:!1,super:!1},{display:s.display??`{${o}}`,match:s.match}),patternName:s.name,payloadKey:s.payloadKey}],nextIndex:r+1,usedTokens:[o]}:{parts:[],nextIndex:r+1,unknownTokens:[o]}}let o=Vl(t,n,e);if(o)return{parts:[o.part],nextIndex:o.nextIndex};let s=zl(t,n);return s?{parts:[Rl(s,e)],nextIndex:n+s.length}:{parts:[Ll(a,e)],nextIndex:n+1}},Ul=(e,t)=>[t.resolveKey({name:e.name,ctrl:e.ctrl,shift:e.shift,meta:e.meta,super:e.super??!1,hyper:e.hyper||void 0})];function Wl(e){return e.appendBindingParser(e=>Hl(e))}function Gl(e){return e.appendEventMatchResolver((e,t)=>Ul(e,t))}function Kl(e){let t=Wl(e),n=Gl(e);return()=>{n(),t()}}var ql=Symbol(`keymap:mod-bindings`),Jl=/(^|[+,\s])mod(?=\s*\+)/i,Yl=/(^|[+,\s])mod(?=\s*\+)/gi;function Xl(e){let t=e.primaryModifier;return(t===`ctrl`||t===`super`)&&e.modifiers[t]!==`unsupported`?t:e.modifiers.ctrl===`unsupported`?`super`:`ctrl`}function Zl(e){if(e.includes(`,`))return[e];let t=e.trim();return t.includes(` `)?t.split(/\s+/):[e]}function Ql(e){return e.acquireResource(ql,()=>e.appendBindingExpander(({input:t,displays:n})=>{if(!Jl.test(t))return;let r=Xl(e.getHostMetadata());return[{key:t.replace(Yl,(e,t)=>`${t}${r}`),displays:n??Zl(t)}]}))}var $l=new Map([[` `,`space`],[`Spacebar`,`space`],[`ArrowUp`,`up`],[`ArrowDown`,`down`],[`ArrowLeft`,`left`],[`ArrowRight`,`right`],[`Escape`,`escape`],[`Esc`,`escape`],[`Enter`,`return`],[`Backspace`,`backspace`],[`Delete`,`delete`],[`Tab`,`tab`],[`Home`,`home`],[`End`,`end`],[`PageUp`,`pageup`],[`PageDown`,`pagedown`],[`Insert`,`insert`],[`CapsLock`,`capslock`],[`NumLock`,`numlock`],[`ScrollLock`,`scrolllock`],[`ContextMenu`,`menu`],[`Meta`,`super`],[`OS`,`super`],[`Alt`,`alt`],[`Control`,`control`],[`Shift`,`shift`]]);function eu(e){let t=e?.trim().toLowerCase();return t?t.includes(`mac`)||t.includes(`darwin`)?`macos`:t.includes(`win`)?`windows`:t.includes(`linux`)||t.includes(`x11`)?`linux`:`unknown`:`unknown`}function tu(){let e=globalThis.navigator,t=e?.userAgentData?.platform,n=eu(t);return n===`unknown`?eu(e?.platform??e?.userAgent):n}function nu(){let e=tu();return{platform:e,primaryModifier:e===`macos`?`super`:e===`unknown`?`unknown`:`ctrl`,modifiers:{ctrl:`supported`,shift:`supported`,meta:`supported`,super:`supported`,hyper:`unsupported`}}}function ru(e){return e.length===1&&!/^[a-z0-9]$/i.test(e)}function iu(e){let t={name:e.name,ctrl:e.ctrl,shift:e.shift,meta:e.meta,super:e.super??!1,hyper:e.hyper||void 0};return!t.shift||!ru(t.name)?[t]:[t,{...t,shift:!1}]}var au=class{name;ctrl;shift;meta;superKey;originalEvent;propagationStopped=!1;constructor(e,t,n,r,i,a){this.name=e,this.ctrl=t,this.shift=n,this.meta=r,this.superKey=i,this.originalEvent=a}get super(){return this.superKey}preventDefault(){this.originalEvent?.preventDefault()}stopPropagation(){this.propagationStopped=!0,this.originalEvent?.stopPropagation()}};function ou(){return globalThis.MutationObserver}function su(e){return $l.get(e)||(/^F\d{1,2}$/i.test(e)||e.length===1?e.toLowerCase():e.trim().toLowerCase().replace(/\s+/g,``))}function cu(e){if(!e)return new au(`command`,!1,!1,!1,!1);let t=globalThis.KeyboardEvent;return new au(su(e.key),e.ctrlKey,e.shiftKey,e.altKey,e.metaKey,t&&e instanceof t?e:void 0)}var lu=class{metadata=nu();rootTarget;isDestroyed=!1;observer;targetDestroyListeners=new Map;constructor(e){this.rootTarget=e}getFocusedTarget(){let e=this.rootTarget.ownerDocument.activeElement;return!e||typeof e!=`object`?null:e===this.rootTarget||this.rootTarget.contains(e)?e:null}getParentTarget(e){return e.parentElement}isTargetDestroyed(e){return e===this.rootTarget?!1:!e.isConnected||!this.rootTarget.contains(e)}onKeyPress(e){let t=t=>{e(cu(t))};return this.rootTarget.addEventListener(`keydown`,t,{capture:!0}),()=>{this.rootTarget.removeEventListener(`keydown`,t,{capture:!0})}}onKeyRelease(e){let t=t=>{e(cu(t))};return this.rootTarget.addEventListener(`keyup`,t,{capture:!0}),()=>{this.rootTarget.removeEventListener(`keyup`,t,{capture:!0})}}onFocusChange(e){let t=()=>{queueMicrotask(()=>{e(this.getFocusedTarget())})};return this.rootTarget.addEventListener(`focusin`,t,{capture:!0}),this.rootTarget.addEventListener(`focusout`,t,{capture:!0}),()=>{this.rootTarget.removeEventListener(`focusin`,t,{capture:!0}),this.rootTarget.removeEventListener(`focusout`,t,{capture:!0})}}onTargetDestroy(e,t){let n=this.targetDestroyListeners.get(e);return n||(n=new Set,this.targetDestroyListeners.set(e,n)),n.add(t),this.ensureObserver(),this.flushDisconnectedTargets(),()=>{let n=this.targetDestroyListeners.get(e);n&&(n.delete(t),n.size===0&&this.targetDestroyListeners.delete(e),this.targetDestroyListeners.size===0&&this.disconnectObserver())}}createCommandEvent(){return cu()}ensureObserver(){if(this.observer||this.targetDestroyListeners.size===0)return;let e=ou();e&&(this.observer=new e(()=>{this.flushDisconnectedTargets()}),this.observer.observe(this.rootTarget,{childList:!0,subtree:!0}))}disconnectObserver(){this.observer&&=(this.observer.disconnect(),void 0)}flushDisconnectedTargets(){for(let[e,t]of this.targetDestroyListeners)if(this.isTargetDestroyed(e)){this.targetDestroyListeners.delete(e);for(let e of[...t])e()}this.targetDestroyListeners.size===0&&this.disconnectObserver()}};function uu(e){return new lu(e)}var du=(e,t)=>iu(e).map(e=>t.resolveKey(e));function fu(e){return e instanceof J?{code:e.code,message:mu(e.message),retryable:e.retryable,...e.need!==void 0&&{need:e.need}}:{code:`HOST_FAILURE`,message:`Host operation failed`,retryable:!1}}function pu(e){try{let t=De(e);return new J(t.message,{code:t.code,retryable:t.retryable,...t.need!==void 0&&{need:t.need}})}catch(e){return new J(`The host returned a malformed error`,{cause:e,code:`PROTOCOL`,retryable:!1})}}function mu(e){return e.trim().slice(0,512)||`Host operation failed`}var hu=e=>({ok:!0,value:e}),gu=e=>({error:fu(e),ok:!1});async function _u(e,t){let n,r=new Set;try{return n=await e,vu(t(n))}catch(e){throw yu(e)&&bu(e,r),e instanceof J?e:new J(`The remote operation failed`,{cause:e,code:`HOST_FAILURE`,retryable:!0})}finally{n!==e&&yu(n)&&bu(n,r)}}function vu(e){if(e.ok)return e.value;throw pu(e.error)}function yu(e){return pe(e)&&Symbol.dispose in e&&Sn(e[Symbol.dispose])}function bu(e,t){if(!t.has(e)){t.add(e);try{e[Symbol.dispose]()}catch(e){console.warn(`RPC result disposal failed`,e)}}}function xu(){let e=[],t=new Set;return{get:()=>e,subscribe:e=>(t.add(e),()=>t.delete(e)),update:n=>{e=n;for(let e of Array.from(t))try{e()}catch(e){console.warn(`App binding subscriber failed`,e)}}}}function Su(e){let t=Ot(e),n=new Set;return{get:()=>t,subscribe:e=>(n.add(e),()=>n.delete(e)),update:e=>{t=Ot(e);for(let e of Array.from(n))try{e()}catch(e){console.warn(`Reserved chord subscriber failed`,e)}}}}function Cu(e){let t=!0,n,r=e.window.document.querySelector(`html`);if(!r)return()=>{t=!1};let i=uu(r),a=new El(i);Kl(a),Ql(a),a.prependEventMatchResolver(du);let o=Tu(e.onBroken),s=ku(a,e.chords,e.remote,o),c=wu(e,o,()=>t,e=>{n=e},()=>n),l=i.onFocusChange(()=>{queueMicrotask(c)}),u=()=>{queueMicrotask(c)};e.window.addEventListener(`focus`,u),e.window.addEventListener(`blur`,u);let d=e.bindings,f=()=>Eu(e.window.document,e.identity.surfaceId).editing,p=d===void 0?()=>void 0:Du(a,d,f),m=d===void 0?()=>void 0:d.subscribe(()=>{p(),p=Du(a,d,f)}),h=e.chords.subscribe(()=>{s(),s=ku(a,e.chords,e.remote,o)});return queueMicrotask(c),()=>{t&&(t=!1,l(),e.window.removeEventListener(`focus`,u),e.window.removeEventListener(`blur`,u),h(),s(),m(),p())}}function wu(e,t,n,r,i){return()=>{if(!n())return;let a=Eu(e.window.document,e.identity.surfaceId),o=i();(a.editing!==o?.editing||a.surface!==o.surface)&&(r(a),t(()=>e.remote.reportFocus(a)))}}function Tu(e){return t=>{try{_u(t(),ut).catch(t=>{ur(`browser-bridge.host-call`,t),e(t)})}catch(t){ur(`browser-bridge.host-call`,t),e(t)}}}function Eu(e,t){let n=e.activeElement;return oe({editing:!!(n?.matches(`input, textarea, select, [contenteditable='true']`)===!0||n?.closest(`[contenteditable='true']`)),surface:e.hasFocus()?t:null})}function Du(e,t,n){let r=t.get();return e.registerLayer({bindings:r.map((e,t)=>({cmd:`app/${String(t)}`,key:e.key})),commands:r.map((e,t)=>({name:`app/${String(t)}`,run:t=>{let r=t.event.originalEvent;if(r?.defaultPrevented||r?.isComposing||Ou(e.key)&&n())return!1;e.run()}})),priority:500})}function Ou(e){return!/(?:^|\+)(?:ctrl|control|super|meta|cmd|alt|option|mod)\+/iu.test(e)}function ku(e,t,n,r){let i=t.get();return e.registerLayer({bindings:i.map(e=>({cmd:`reserved/${e.id}`,key:{ctrl:e.ctrlKey,meta:e.altKey,name:su(e.key),shift:e.shiftKey,super:e.metaKey}})),commands:i.map(e=>({name:`reserved/${e.id}`,run:t=>{let i=t.event.originalEvent;if(i?.defaultPrevented||i?.isComposing)return!1;r(()=>n.invokeReservedChord(e.id,i?.repeat??!1))}})),priority:1e3})}function Au(e){let t=t=>{if(t.defaultPrevented||t.isComposing)return;let n=Nu(t,e.mac);n!==null&&(t.preventDefault(),!t.repeat&&(n===`back`&&e.canGoBack()&&e.back(),n===`forward`&&e.canGoForward()&&e.forward()))},n=t=>{let n=Mu(t.button);if(n===null)return;let r=t.defaultPrevented;t.preventDefault(),!(t.type!==`mouseup`||r)&&(n===`back`&&e.canGoBack()&&e.back(),n===`forward`&&e.canGoForward()&&e.forward())};e.window.addEventListener(`keydown`,t);for(let t of ju)e.window.addEventListener(t,n);return()=>{e.window.removeEventListener(`keydown`,t);for(let t of ju)e.window.removeEventListener(t,n)}}var ju=[`mousedown`,`mouseup`,`auxclick`];function Mu(e){return e===3?`back`:e===4?`forward`:null}function Nu(e,t){return e.shiftKey||e.ctrlKey?null:t?!e.metaKey||e.altKey?null:e.key===`[`?`back`:e.key===`]`?`forward`:Pu(e.target)?null:e.key===`ArrowLeft`?`back`:e.key===`ArrowRight`?`forward`:null:!e.altKey||e.metaKey?null:e.key===`ArrowLeft`?`back`:e.key===`ArrowRight`?`forward`:null}function Pu(e){return e instanceof HTMLElement?e.isContentEditable||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement:!1}function Fu(){return!yn(globalThis.navigator)&&/Mac|iPhone|iPad/u.test(globalThis.navigator.userAgent)}var Iu=[];for(let e=0;e<256;++e)Iu.push((e+256).toString(16).slice(1));function Lu(e,t=0){return(Iu[e[t+0]]+Iu[e[t+1]]+Iu[e[t+2]]+Iu[e[t+3]]+`-`+Iu[e[t+4]]+Iu[e[t+5]]+`-`+Iu[e[t+6]]+Iu[e[t+7]]+`-`+Iu[e[t+8]]+Iu[e[t+9]]+`-`+Iu[e[t+10]]+Iu[e[t+11]]+Iu[e[t+12]]+Iu[e[t+13]]+Iu[e[t+14]]+Iu[e[t+15]]).toLowerCase()}var Ru,zu=new Uint8Array(16);function Bu(){if(!Ru){if(typeof crypto>`u`||!crypto.getRandomValues)throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);Ru=crypto.getRandomValues.bind(crypto)}return Ru(zu)}var Vu={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Hu(e,t,n){if(Vu.randomUUID&&!t&&!e)return Vu.randomUUID();e||={};let r=e.random??e.rng?.()??Bu();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return Lu(r)}var Uu=Ft({version:`v7`}),Wu=i().regex(/^replay_[a-f0-9]{64}$/);S(e=>Wu.safeParse(e).success);var Gu=Ft({version:`v4`});S(e=>Uu.safeParse(e).success);var Ku=S(e=>Gu.safeParse(e).success);function qu(){return Ku.parse(Hu())}var Ju=class extends u{#e=!0;#t;#n=new Map;constructor(e){super(),this.#t=e}cancel(e){try{return this.#n.get(b(e))?.abort(),Promise.resolve(hu(void 0))}catch(e){return Promise.resolve(gu(e))}}dispose(){if(this.#e){this.#e=!1;for(let e of this.#n.values())e.abort();this.#n.clear()}}async invoke(e){try{if(!this.#e)throw new J(`The command is disposed`,{code:`DISCONNECTED`,retryable:!0});let t=j(e);if(this.#n.has(t.requestId))throw new J(`Duplicate command request`,{code:`PROTOCOL`,retryable:!1});if(this.#n.size>=64)throw new J(`Too many command requests`,{code:`HOST_FAILURE`,retryable:!0});let n=new AbortController;this.#n.set(t.requestId,n);try{let e=await this.#t(Dn(t,n.signal)),r=qt(e);return hu(r===void 0?{status:`handled`}:{status:`handled`,result:r})}finally{this.#n.delete(t.requestId)}}catch(e){if(e instanceof Na)try{let t={code:e.code,message:e.message,details:e.details};return hu({status:`failed`,error:g(t)})}catch(e){return gu(e)}return gu(e)}}[Symbol.dispose](){this.dispose()}};function Yu(e){let t=[];for(let n of e.values()){let{commandId:e,definition:r,target:i}=n;if(e===void 0)continue;let a=r.availability?.status!==`unavailable`;for(let n of r.projections?.bindings?.values??[])n.trim().includes(` `)||n.startsWith(`<`)||t.push({key:n,run:()=>{a&&Promise.resolve().then(async()=>{let t=vu(await i.invoke({commandId:e,origin:`keyboard`,requestId:qu()}));if(t.status===`failed`)throw new Na(t.error.code,t.error.message,t.error.details)}).catch(e=>{console.warn(`App key command failed`,e)})}})}return t}function Xu(e,t,n,r){let i=new Map,a=!1,o=()=>{r?.update(a?[]:Yu(i))},s=e=>{try{n()}catch(t){console.warn(`App command failure callback failed`,t,e)}},c=e=>{try{_u(e(),ut).catch(e=>{s(e)})}catch(e){console.warn(`App command RPC supervision failed`,e),s(e)}};return{commands:Qu(e,t,i,()=>a,t=>{let n=i.get(t);if(!n)return;i.delete(t),n.target.dispose(),o();let r=n.commandId;!a&&r!==void 0&&c(()=>e.unregisterCommand(r))},o),dispose(){if(!a){a=!0;for(let e of i.values())e.target[Symbol.dispose]();i.clear(),o()}}}}function Zu(e,t,n){let r=t.id;if(e.size>=128||e.has(r))throw n.dispose(),new J(`Command registration is unavailable`,{code:`INVALID_ARGUMENT`,retryable:!1});let i={commandId:void 0,definition:t,target:n};e.set(r,i);let a=!1;return{commit(e){a||(i.commandId=e)},release(){a||(a=!0,e.get(r)===i&&e.delete(r),n.dispose())},target:n}}function Qu(e,t,n,r,i,a){return Object.freeze({async register(o,s){if(t(),!Sn(s))throw new J(`Command handler must be a function`,{code:`INVALID_ARGUMENT`,retryable:!1});let c=we(o),l=new Ju(s),u=Zu(n,c,l);try{let t=await $u(e,c,u.target);r()&&await ed(e,t.commandId,l),u.commit(t.commandId),a()}catch(e){throw u.release(),e}let d=!0;return()=>{d&&(d=!1,i(c.id))}}})}async function $u(e,t,n){return _u(e.registerCommand(t,n),Ye)}async function ed(e,t,n){throw n.dispose(),await _u(e.unregisterCommand(t),ut),new J(`The command controller is disposed`,{code:`DISCONNECTED`,retryable:!0})}var td=f(e=>e instanceof me),nd=class extends u{#e=!1;#t;constructor(e){super(),this.#t=e}disconnect(e){try{if(this.#e)throw pd();let t=e===void 0?void 0:De(e);return setTimeout(()=>this.#t.disconnect?.(t??_d()),0),Promise.resolve(hu(void 0))}catch(e){return Promise.resolve(gu(e))}}async requestClose(){try{if(this.#e)throw pd();return hu(await(this.#t.beforeClose?.()??!0))}catch(e){return gu(e)}}async requestBack(){try{if(this.#e)throw pd();return hu(await(this.#t.back?.()??!1))}catch(e){return gu(e)}}async requestForward(){try{if(this.#e)throw pd();return hu(await(this.#t.forward?.()??!1))}catch(e){return gu(e)}}async activateNavigation(e){try{if(this.#e)throw pd();let t=en(e);return En(this.#t.navigation,t)?hu(await(this.#t.activate?.(t)??!1)):hu(!1)}catch(e){return gu(e)}}async activateStatus(e){try{if(this.#e)throw pd();let t=st(e);return We(this.#t.statusItems,t)?hu(await(this.#t.statusAction?.(t)??!1)):hu(!1)}catch(e){return gu(e)}}[Symbol.dispose](){this.#e=!0}async updateContext(e){return this.#e?gu(pd()):this.#n(e,`context`,Ae,e=>{this.#t.context.update(e)})}reconfigure(e){let t=[];try{if(this.#e)throw pd();let r=n(e);if(r.context.version<=this.#t.versions.context)return Promise.resolve(hu(void 0));for(let e of r.capabilities)t.push({...e,handle:o(td)(e.handle).dup()});if(!this.#t.capabilities)throw pd();return this.#t.capabilities.replace(t),t=[],this.#t.versions.context=r.context.version,this.#t.context.update(r.context.value),Promise.resolve(hu(void 0))}catch(e){for(let e of t)F(e.handle);return Promise.resolve(gu(e))}}updateLifecycle(e){try{if(this.#e)throw pd();let t=Ne(cn)(e);if(t.version<=this.#t.versions.lifecycle)return Promise.resolve(hu(void 0));if(!vd(this.#t.lifecycle.get(),t.value))throw new J(`The host sent an invalid lifecycle transition`,{code:`PROTOCOL`,retryable:!1});return this.#t.versions.lifecycle=t.version,this.#t.lifecycle.update(t.value),Promise.resolve(hu(void 0))}catch(e){return Promise.resolve(gu(e))}}async updateReservedChords(e){return this.#e?gu(pd()):this.#n(e,`chords`,Ot,e=>{this.#t.chords.update(e)})}async updateTheme(e){return this.#e?gu(pd()):this.#n(e,`theme`,Nt,e=>{this.#t.theme.update(e)})}#n(e,t,n,r){try{let i=Ne(n)(e);return i.version>this.#t.versions[t]&&(this.#t.versions[t]=i.version,r(i.value)),Promise.resolve(hu(void 0))}catch(e){return Promise.resolve(gu(e))}}};async function rd(e){let t=sd(),n=new nd(t),r=bn(e.port,n),i,a=od(r);try{performance.mark(`fungi.app-open.agar-rpc-connect-start`);let o=await Promise.race([r.connect({epoch:e.epoch,protocolVersion:2}),a]);performance.mark(`fungi.app-open.agar-rpc-connect-ready`),i=o;let s=vu(xe(o));if(!e.isActive())throw ad();let c=cd({bootstrap:s,bootstrapOwner:i,options:e,remote:r,state:t,target:n});return performance.mark(`fungi.app-open.agar-root-created`),i=void 0,c}catch(t){return bd(t,e,n,r,i)}}function id(e,t){e.context.update(t.context.value),e.theme.update(t.theme.value),e.lifecycle.update(t.lifecycle.value),e.chords.update(t.chords.value),e.versions.context=t.context.version,e.versions.theme=t.theme.version,e.versions.lifecycle=t.lifecycle.version,e.versions.chords=t.chords.version}function ad(){return new J(`App connection was cancelled`,{code:`CANCELLED`,retryable:!1})}function od(e){let t,n=new Promise((e,n)=>{t=n});return n.catch(e=>{ur(`app-session.rpc-disconnect`,e)}),e.onRpcBroken(()=>t?.(new J(`The app host disconnected`,{code:`DISCONNECTED`,retryable:!0}))),n}function sd(){return{statusItems:[],navigation:{canGoBack:!1,canGoForward:!1},bindings:xu(),chords:Su([]),context:ce({computerId:null,focus:{editing:!1,surface:null},openRequest:null,visibility:`hidden`}),lifecycle:ce(`connecting`),theme:ce(`default`),canGoBack:!1,canGoForward:!1,versions:{chords:-1,context:-1,lifecycle:-1,theme:-1}}}function cd(e){let t=nt(e.bootstrap.identity),n=yd(e.bootstrap);id(e.state,n);let r=T(e.bootstrap.capabilities);return e.state.capabilities=r,ud(e,t,r)}function ld(e,t,n){return Cu({bindings:e.state.bindings,chords:e.state.chords,identity:t,onBroken:e=>{n({code:`DISCONNECTED`,message:e instanceof J?e.message:`The app host rejected a browser bridge operation`,retryable:!0})},remote:e.remote,window:e.options.window})}function ud(e,t,n){let r=!1,i=t=>{r||(r=!0,hd([()=>{t&&e.state.lifecycle.update(`disconnected`)},()=>{e.state.lifecycle.update(`disposing`)},l,u,()=>{o.dispose()},()=>{e.state.beforeClose=void 0,e.state.back=void 0,e.state.forward=void 0,e.state.activate=void 0,e.state.statusAction=void 0},()=>{n.disconnect()},()=>{e.target[Symbol.dispose]()},()=>{F(e.bootstrapOwner)},()=>{F(e.remote)},()=>{e.options.port.close()},()=>{e.state.lifecycle.update(`disposed`)},e.options.onDisposed],`app connection disposal`))},a=()=>{if(r)throw new J(`The app connection is disposed`,{code:`DISCONNECTED`,retryable:!0})},o=Xu(e.remote,a,()=>{i({code:`DISCONNECTED`,message:`The app host rejected a terminal command operation`,retryable:!0})},e.state.bindings),s=fd(e.remote,a,e.state),c=dd(e.state,e.remote,a),l=ld(e,t,i),u=Au({window:e.options.window,mac:Fu(),canGoBack:()=>e.state.canGoBack&&e.state.back!==void 0,back:()=>{let t=e.state.back;t&&Promise.resolve().then(t).catch(e=>{ur(`app-window.back-input`,e)})},canGoForward:()=>e.state.canGoForward&&e.state.forward!==void 0,forward:()=>{let t=e.state.forward;t&&Promise.resolve().then(t).catch(e=>{ur(`app-window.forward-input`,e)})}});return e.state.disconnect=i,e.remote.onRpcBroken(()=>{md(i)}),gd({capabilities:n.directory,commands:o.commands,context:e.state.context,dispose:i,identity:t,lifecycle:e.state.lifecycle,theme:e.state.theme,ui:s,window:c})}function dd(e,t,n){let r=Object.freeze({async publish(r){n();let i=Ve(r);e.canGoBack=i.canGoBack,e.canGoForward=i.canGoForward,e.navigation=yt(i),await _u(t.reportNavigation(i),ut)},onActivate(t){if(n(),e.activate!==void 0)throw new J(`The App already owns navigation activations`,{code:`INVALID_ARGUMENT`,retryable:!1});e.activate=t;let r=!1;return()=>{r||(r=!0,e.activate===t&&(e.activate=void 0))}},onForward(t){if(n(),e.forward!==void 0)throw new J(`The App already owns Forward requests`,{code:`INVALID_ARGUMENT`,retryable:!1});e.forward=t;let r=!1;return()=>{r||(r=!0,e.forward===t&&(e.forward=void 0))}},onBack(t){if(n(),e.back!==void 0)throw new J(`The App already owns Back requests`,{code:`INVALID_ARGUMENT`,retryable:!1});e.back=t;let r=!1;return()=>{r||(r=!0,e.back===t&&(e.back=void 0))}}});return Object.freeze({navigation:r,onBeforeClose(t){if(n(),e.beforeClose!==void 0)throw new J(`The App already owns a close consultation`,{code:`INVALID_ARGUMENT`,retryable:!1});e.beforeClose=t;let r=!1;return()=>{r||(r=!0,e.beforeClose===t&&(e.beforeClose=void 0))}}})}function fd(e,t,n){return Object.freeze({async requestComputerChoice(){t(),await _u(e.requestComputerChoice(),ut)},async requestBrowserAction(n){t();let r=C(n);return r.kind===`refused`?r:await _u(e.requestBrowserAction(r),ye)},onStatusAction(e){if(t(),n.statusAction!==void 0)throw new J(`The App already owns its status actions`,{code:`INVALID_ARGUMENT`,retryable:!1});n.statusAction=e;let r=!1;return()=>{r||(r=!0,n.statusAction===e&&(n.statusAction=void 0))}},async requestAppPermissions(n){return t(),await _u(e.requestAppPermissions(an(n)),Vt)},async openDesktopSettings(){t(),await _u(e.openDesktopSettings(),ut)},async openSetup(n){return t(),await _u(e.openSetup(pn(n)),$e)},async openTeamBilling(){t(),await _u(e.openTeamBilling(),ut)},async openNavigation(n){t(),await _u(e.openNavigation(Rt(n)),ut)},async reportStatus(r){t();let i=Kt(r);n.statusItems=i,await _u(e.reportStatus(i),ut)},async reportAgentSessionSelection(n){t(),await _u(e.reportAgentSessionSelection(c(n)),ut)},async showToast(n){t(),await _u(e.showToast(mt(n)),ut)}})}function pd(){return new J(`The app connection is disposed`,{code:`DISCONNECTED`,retryable:!0})}function md(e){e({code:`DISCONNECTED`,message:`The app host disconnected`,retryable:!0})}function hd(e,t){for(let n of e)try{n()}catch(e){console.warn(`${t} cleanup failed`,e)}}function gd(e){return Object.freeze(e)}function _d(){return{code:`DISCONNECTED`,message:`The app host disconnected`,retryable:!1}}function vd(e,t){return e===t||e===`connected`&&t===`suspended`||e===`suspended`&&t===`connected`}function yd(e){let t=Ne(Ae)(e.context),n=Ne(Nt)(e.theme),r=Ne(cn)(e.lifecycle),i=Ne(Ot)(e.reservedChords);if(r.value!==`connected`&&r.value!==`suspended`)throw new J(`The bootstrap lifecycle is invalid`,{code:`PROTOCOL`,retryable:!1});return{chords:i,context:t,lifecycle:r,theme:n}}function bd(e,t,n,r,i){throw hd([()=>{n[Symbol.dispose]()},()=>{i&&F(i)},()=>{F(r)},()=>{t.port.close()},t.onDisposed],`app connection rejection`),e instanceof J?e:new J(`Unable to establish the app RPC session`,{cause:e,code:`PROTOCOL`,retryable:!1})}var xd=!1,Sd=class{options;#e;#t;#n=!1;#r;#i;constructor(e){this.options=e,this.#e=globalThis.window}start(){performance.mark(`fungi.app-open.agar-connect-start`);let e=this.#l();return e?Promise.reject(e):(xd=!0,this.#a())}#a(){return new Promise((e,t)=>{let n=(n,a)=>{this.#o(n,a,i,r,e,t)},r=()=>{n(wd())},i=e=>{this.#s(e,n,i)};this.#e.addEventListener(`message`,i),this.options.signal?.addEventListener(`abort`,r,{once:!0});let a=()=>{try{performance.mark(`fungi.app-open.agar-ready-sent`),this.#e.parent.postMessage({protocolVersion:2,type:gn},`*`)}catch(e){ur(`connect.notify-host`,e),n(Ad(e))}};this.#r=setInterval(a,200),this.#i=setTimeout(()=>{n(Ed())},1e4),a()})}#o(e,t,n,r,i,a){if(!this.#n){if(this.#n=!0,this.#c(),this.#e.removeEventListener(`message`,n),this.options.signal?.removeEventListener(`abort`,r),e||!t){this.#t?.close(),xd=!1,a(e??Ed());return}i(t)}}#s(e,t,n){if(!kd(e.data))return;if(performance.mark(`fungi.app-open.agar-connect-received`),e.source!==this.#e.parent||Dd(e.origin)===void 0){t(Od());return}let r=jd(e,t);if(!r)return;let i=e.ports.length===1?e.ports[0]:void 0;if(!i){t(Md(`The app host did not transfer exactly one port`));return}this.#t=i,this.#c(),this.#e.removeEventListener(`message`,n),rd({epoch:r.epoch,isActive:()=>!this.#n,onDisposed:()=>{xd=!1},port:i,window:this.#e}).then(e=>{performance.mark(`fungi.app-open.agar-root-ready`),t(void 0,e)},e=>{t(Td(e))})}#c(){clearInterval(this.#r),clearTimeout(this.#i),this.#r=void 0,this.#i=void 0}#l(){if(this.options.signal?.aborted)return wd();if(xd)return new J(`An app connection is already live`,{code:`IDENTITY`,retryable:!1});if(yn(globalThis.window)||this.#e.parent===this.#e)return new J(`The app host is unavailable`,{code:`DISCONNECTED`,retryable:!0})}};function Cd(e){return new Sd(e).start()}function wd(){return new J(`App connection was cancelled`,{code:`CANCELLED`,retryable:!1})}function Td(e){return e instanceof J?e:new J(`Unable to connect to the app host`,{cause:e,code:`PROTOCOL`,retryable:!1})}function Ed(){return new J(`The app host disconnected`,{code:`DISCONNECTED`,retryable:!0})}function Dd(e){if(!URL.canParse(e))return;let t=new URL(e).origin;return t===e?t:void 0}function Od(){return new J(`The app connection identity is invalid`,{code:`IDENTITY`,retryable:!1})}var kd=z(Ue({type:at(ze)}));function Ad(e){return new J(`Unable to notify the app host`,{cause:e,code:`DISCONNECTED`,retryable:!0})}function jd(e,t){try{return O(e.data)}catch(e){ur(`connect.decode-message`,e),t(e instanceof J?e:new J(`Malformed app connection`,{cause:e,code:`PROTOCOL`,retryable:!1}));return}}function Md(e){return new J(e,{code:`PROTOCOL`,retryable:!1})}function Nd(e,t,n){e.style.isolation=`isolate`;let r=(0,Ko.createRoot)(e),i=new AbortController,a=e.ownerDocument.documentElement,o=Lo(a),s,c,l,u=!1,d=e=>{let i=(0,X.createElement)(Pd,{state:e,render:n});r.render(t.queryClient?(0,X.createElement)(It,{client:t.queryClient},i):i)},f=()=>{l?.(),l=void 0,c?.(),c=void 0;let e=s;s=void 0,e?.dispose(),u&&=(o===null?a.removeAttribute(`data-theme`):Io(o,a),!1)},{defaultView:p}=e.ownerDocument;return performance.mark(`fungi.app-open.react-root-render-start`),p?p.parent===p?d({app:null,status:`standalone`}):(d({app:null,status:`connecting`}),Cd({host:`parent`,signal:i.signal}).then(e=>{if(i.signal.aborted){e.dispose();return}s=e;let t=()=>{let t=e.lifecycle.get();return t===`disposing`||t===`disconnected`||t===`disposed`?(f(),d({app:null,status:`ended`}),!0):!1};l=e.lifecycle.subscribe(t),!t()&&(u=!0,Io(e.theme.get(),a),c=e.theme.subscribe(e=>{Io(e,a)}),d({app:e,status:`live`}))}).catch(e=>{i.signal.aborted&&e instanceof J&&e.code===`CANCELLED`||(console.error(`${t.name} host connection failed`,e),f(),i.signal.aborted||d({app:null,status:`not-hosted`,error:e instanceof J?e:new J(`The App host is unavailable`,{cause:e,code:`HOST_FAILURE`,retryable:!0})}))})):d({app:null,status:`not-hosted`,error:new J(`The App document has no window`,{code:`DISCONNECTED`,retryable:!1})}),()=>{i.signal.aborted||(i.abort(),r.unmount(),f())}}function Pd({state:e,render:t}){return(0,X.useLayoutEffect)(()=>{performance.mark(`fungi.app-open.react-initial-commit`)},[]),(0,X.useLayoutEffect)(()=>{e.app&&performance.mark(`fungi.app-open.react-connected-commit`)},[e.app]),(0,X.createElement)(X.Fragment,null,e.status===`not-hosted`?(0,X.createElement)(`p`,{role:`alert`},`App host connection unavailable. Open this App through its host to try again.`):null,t(e))}function Fd(e){let t=(0,X.useCallback)(t=>e?.subscribe(t)??(()=>void 0),[e]),n=(0,X.useCallback)(()=>e?.get(),[e]);return(0,X.useSyncExternalStore)(t,n,n)}function Id(e){return Fd(e?.context)??null}function Ld(e){return Id(e)?.computerId??null}function Rd(e,t,n,r){let i=(0,X.useRef)(t);i.current=t;let a=(0,X.useRef)(n);a.current=n;let o=(0,X.useRef)(r);o.current=r;let s=JSON.stringify(t),c=n!==void 0;(0,X.useEffect)(()=>{e&&e.ui.reportStatus(i.current).catch(e=>{o.current?o.current(e):console.error(`Window status report failed`,e)})},[e,s]),(0,X.useEffect)(()=>{if(!(!e||!c))return e.ui.onStatusAction(e=>a.current?.(e)??!1)},[e,c]),(0,X.useEffect)(()=>()=>{e?.ui.reportStatus([]).catch(e=>{console.error(`Window status report failed`,e)})},[e])}function zd(e,{sourceId:t,namespace:n},r){let i=(0,X.useMemo)(()=>Fa(),[]),a=(0,X.useMemo)(r,[r]);return(0,X.useEffect)(()=>{let e=i.contribute({sourceId:t,namespace:n,commands:a});return()=>{e.dispose()}},[i,t,n,a]),(0,X.useEffect)(()=>e?Mo(e.commands,a):void 0,[e,a]),i}var Bd=At(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);zt.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>nn(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Tt(e,t,n),e.parseAsync=async(t,n)=>Ke(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>un(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>Xe(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),Vd=At(`ZodMiniObject`,(e,t)=>{Be.init(e,t),Bd.init(e,t),it(e,`shape`,()=>t.shape)});function Hd(e,t){return new Vd({type:`object`,shape:e??{},...Ut(t)})}var Ud=At(`ZodMiniLiteral`,(e,t)=>{gt.init(e,t),Bd.init(e,t)});function Wd(e,t){return new Ud({type:`literal`,values:Array.isArray(e)?e:[e],...Ut(t)})}var Gd=Ce({png:`png`,jpeg:`jpeg`,webp:`webp`}),Kd=Ce({draft:`draft`,balanced:`balanced`,premium:`premium`,max:`max`}),qd=Yt(()=>G({transport:Ce({json:`json`,multipart:`multipart`}),dimensions:Ce({none:`none`,own:`own`}),maxDimension:q().int().positive().nullable(),maxDimensionDocumented:Ee(),defaultWidth:q().int().positive(),defaultHeight:q().int().positive(),steps:Ce({steps:`steps`,num_steps:`num_steps`,fixed:`fixed`}),maxSteps:q().int().positive().nullable(),defaultSteps:q().int().nonnegative().nullable(),referenceField:i().min(1).max(256).nullable(),maxReferences:q().int().nonnegative()}).readonly()),Jd=Ce({seedance:`bytedance/seedance-2.0`,seedanceFast:`bytedance/seedance-2.0-fast`,seedanceMini:`bytedance/seedance-2.0-mini`,veo:`google/veo-3.1`,veoFast:`google/veo-3.1-fast`,minimaxH3Max:`minimax/h3-max`}),Yd=Ce({p480:`480p`,p720:`720p`,p768:`768p`,p1080:`1080p`,p4k:`4k`}),Xd=Ce({wide:`16:9`,landscape:`4:3`,square:`1:1`,portrait:`3:4`,tall:`9:16`,ultrawide:`21:9`,ultratall:`9:21`}),Zd=Ce({first:`first-frame`,last:`last-frame`,reference:`reference`}),Qd=Yt(()=>G({resolution:Yd,aspectRatio:Xd,width:q().int().positive(),height:q().int().positive()}).readonly()),$d=Yt(()=>G({minSeconds:q().int().positive(),maxSeconds:q().int().positive(),defaultSeconds:q().int().positive(),durations:be(q().int().positive()).readonly(),provider:Ce({seedance:`seedance`,veo:`veo`,minimax:`minimax`}),formats:be(Qd).readonly(),defaultResolution:Yd,defaultAspectRatio:Xd,supportsAudio:Ee(),defaultGenerateAudio:Ee().nullable(),referenceRoles:be(Zd).readonly(),maxReferenceImages:q().int().nonnegative(),referenceResolutions:be(Yd).readonly(),prices:be(G({resolution:Yd,silentMilliunitsPerSecond:q().int().positive(),audioMilliunitsPerSecond:q().int().positive()}).readonly()).readonly()}).readonly()),ef=32e3,tf=2048;G({id:i().min(1).max(256),label:i().min(1).max(512),kind:Ce({image:`image`,video:`video`}),tier:Kd,outputFormats:be(Gd).max(3).readonly(),maxPromptLength:q().int().positive().max(ef),input:qd,sizes:be(i().regex(/^\d+x\d+$/u)).readonly().nullable(),video:$d.nullable()}).readonly();var nf=e=>Object.freeze({kind:`image`,sizes:null,video:null,outputFormats:Object.freeze([]),...e,input:Object.freeze(e.input)}),rf={"480p":480,"720p":720,"768p":768,"1080p":1080,"4k":2160},af={"16:9":[16,9],"4:3":[4,3],"1:1":[1,1],"3:4":[3,4],"9:16":[9,16],"21:9":[21,9],"9:21":[9,21]};function of(e,t,n,r,i){let a=r===`seedance`,o=a?Xd.options:[Xd.enum.wide,Xd.enum.tall,Xd.enum.square],s=Object.freeze(i.flatMap(([e])=>o.map(t=>{let[n,r]=af[t],i=rf[e],a=Math.min(n,r);return Object.freeze({resolution:e,aspectRatio:t,width:Math.ceil(i*n/a/2)*2,height:Math.ceil(i*r/a/2)*2})}))),c=Object.freeze(a?[4,5,6,7,8,9,10,11,12]:[4,6,8]),l=Object.freeze({minSeconds:4,maxSeconds:a?12:8,defaultSeconds:a?5:6,durations:c,provider:r,formats:s,defaultResolution:`720p`,defaultAspectRatio:`16:9`,supportsAudio:!0,defaultGenerateAudio:!a||null,referenceRoles:Object.freeze(a?Zd.options:[Zd.enum.first]),maxReferenceImages:a?4:0,referenceResolutions:Object.freeze(a?i.map(([e])=>e).filter(e=>e!==`1080p`):[]),prices:Object.freeze(i.map(([e,t,n])=>Object.freeze({resolution:e,silentMilliunitsPerSecond:t,audioMilliunitsPerSecond:n})))});return nf({id:e,label:t,tier:n,maxPromptLength:a?2e3:tf,kind:`video`,video:l,sizes:Object.freeze(s.map(({width:e,height:t})=>`${String(e)}x${String(t)}`)),input:{transport:`json`,dimensions:`own`,maxDimension:Math.max(...s.map(({width:e,height:t})=>Math.max(e,t))),maxDimensionDocumented:!1,defaultWidth:1280,defaultHeight:720,steps:`fixed`,maxSteps:null,defaultSteps:null,referenceField:a?`image`:`image_input`,maxReferences:a?4:1}})}function sf(){let e=[`480p`,`768p`],t=[Xd.enum.wide,Xd.enum.landscape,Xd.enum.square,Xd.enum.portrait,Xd.enum.tall,Xd.enum.ultrawide],n=Object.freeze(e.flatMap(e=>t.map(t=>{let[n,r]=af[t],i=rf[e],a=Math.min(n,r);return Object.freeze({resolution:e,aspectRatio:t,width:Math.ceil(i*n/a/2)*2,height:Math.ceil(i*r/a/2)*2})}))),r=Yd.enum.p768,i=Xd.enum.wide,a=n.find(e=>e.resolution===r&&e.aspectRatio===i);if(a===void 0)throw Error(`minimax/h3-max is missing its default format`);let o=Object.freeze(Array.from({length:11},(e,t)=>t+5)),s=Object.freeze({minSeconds:5,maxSeconds:15,defaultSeconds:5,durations:o,provider:`minimax`,formats:n,defaultResolution:r,defaultAspectRatio:i,defaultGenerateAudio:null,supportsAudio:!1,referenceRoles:Object.freeze([Zd.enum.first,Zd.enum.reference]),maxReferenceImages:4,referenceResolutions:Object.freeze(e),prices:Object.freeze([{resolution:Yd.enum.p480,silentMilliunitsPerSecond:5e3,audioMilliunitsPerSecond:5e3},{resolution:Yd.enum.p768,silentMilliunitsPerSecond:8e3,audioMilliunitsPerSecond:8e3}])});return nf({id:Jd.enum.minimaxH3Max,label:`MiniMax H3 Max`,tier:`balanced`,maxPromptLength:7e3,kind:`video`,video:s,sizes:Object.freeze(n.map(({width:e,height:t})=>`${String(e)}x${String(t)}`)),input:{transport:`json`,dimensions:`own`,maxDimension:Math.max(...n.map(({width:e,height:t})=>Math.max(e,t))),maxDimensionDocumented:!1,defaultWidth:a.width,defaultHeight:a.height,steps:`fixed`,maxSteps:null,defaultSteps:null,referenceField:`image_url`,maxReferences:4}})}Object.freeze([nf({id:`@cf/black-forest-labs/flux-1-schnell`,maxPromptLength:2048,outputFormats:Object.freeze([`jpeg`]),tier:`draft`,label:`Flux 1 Schnell — cheap/fast sketches`,input:{transport:`json`,dimensions:`none`,maxDimension:null,maxDimensionDocumented:!1,defaultWidth:1024,defaultHeight:768,steps:`steps`,maxSteps:8,defaultSteps:4,referenceField:null,maxReferences:0}}),nf({id:`@cf/black-forest-labs/flux-2-klein-4b`,maxPromptLength:tf,tier:`balanced`,label:`Flux 2 Klein 4b — balanced default`,input:{transport:`multipart`,dimensions:`own`,maxDimension:1920,maxDimensionDocumented:!1,defaultWidth:1024,defaultHeight:768,steps:`fixed`,maxSteps:null,defaultSteps:4,referenceField:`input_image_`,maxReferences:4}}),nf({id:`@cf/black-forest-labs/flux-2-klein-9b`,maxPromptLength:tf,tier:`premium`,label:`Flux 2 Klein 9b — higher quality flux-2`,input:{transport:`multipart`,dimensions:`own`,maxDimension:1920,maxDimensionDocumented:!1,defaultWidth:1024,defaultHeight:768,steps:`fixed`,maxSteps:null,defaultSteps:4,referenceField:`input_image_`,maxReferences:4}}),nf({id:`@cf/black-forest-labs/flux-2-dev`,maxPromptLength:tf,tier:`max`,label:`Flux 2 Dev — best detailed quality, expensive`,input:{transport:`multipart`,dimensions:`own`,maxDimension:1920,maxDimensionDocumented:!1,defaultWidth:1024,defaultHeight:768,steps:`steps`,maxSteps:null,defaultSteps:20,referenceField:`input_image_`,maxReferences:4}}),nf({id:`@cf/leonardo/lucid-origin`,maxPromptLength:tf,tier:`premium`,label:`Leonardo Lucid Origin — premium prompt adherence`,input:{transport:`json`,dimensions:`own`,maxDimension:2500,maxDimensionDocumented:!0,defaultWidth:1120,defaultHeight:1120,steps:`num_steps`,maxSteps:40,defaultSteps:null,referenceField:null,maxReferences:0}}),nf({id:`@cf/leonardo/phoenix-1.0`,maxPromptLength:tf,tier:`balanced`,label:`Leonardo Phoenix 1.0 — best prompt adherence`,input:{transport:`json`,dimensions:`own`,maxDimension:2048,maxDimensionDocumented:!0,defaultWidth:1024,defaultHeight:1024,steps:`num_steps`,maxSteps:50,defaultSteps:25,referenceField:null,maxReferences:0}}),nf({id:`openai/gpt-image-2`,maxPromptLength:32e3,outputFormats:Object.freeze([`png`,`jpeg`,`webp`]),tier:`premium`,label:`GPT Image 2 — strong text and layout, premium`,sizes:Object.freeze([`1024x1024`,`1024x1536`,`1536x1024`]),input:{transport:`json`,dimensions:`own`,maxDimension:1536,maxDimensionDocumented:!1,defaultWidth:1024,defaultHeight:1024,steps:`fixed`,maxSteps:null,defaultSteps:null,referenceField:`images`,maxReferences:16}}),of(Jd.enum.seedance,`Seedance 2.0`,`balanced`,`seedance`,[[`480p`,7e3,7e3],[`720p`,15e3,15e3],[`1080p`,37e3,37e3],[`4k`,78e3,78e3]]),of(Jd.enum.seedanceFast,`Seedance 2.0 Fast`,`draft`,`seedance`,[[`480p`,6e3,6e3],[`720p`,12e3,12e3]]),of(Jd.enum.seedanceMini,`Seedance 2.0 Mini`,`draft`,`seedance`,[[`480p`,4e3,4e3],[`720p`,9e3,9e3]]),of(Jd.enum.veo,`Veo 3.1`,`premium`,`veo`,[[`720p`,2e4,4e4],[`1080p`,2e4,4e4]]),of(Jd.enum.veoFast,`Veo 3.1 Fast`,`balanced`,`veo`,[[`720p`,8e3,1e4],[`1080p`,1e4,12e3]]),sf()]);var cf=e=>i().min(1).max(e),lf=q().int().min(-(2**53-1)).max(2**53-1),uf=lf.positive(),df=lf.nonnegative(),ff=G({printId:cf(256),computerId:cf(256),kind:Ce([`image`,`video`]),prompt:cf(ef),model:cf(256),width:uf.nullable(),height:uf.nullable(),steps:df.nullable(),durationSeconds:df.nullable(),format:cf(32),bytes:uf,costMilliunits:df,actorKind:Ce([`member`,`agent`]),actorId:cf(256),derivedFrom:cf(256).nullable(),createdAt:df,source:Ce([`recorded`,`file`]),schemaVersion:uf}),pf=ke({printId:ff.shape.printId,path:i().startsWith(`/`).min(2).max(4096)});function mf(e,t){let n=e?.app??null,r=Id(n),i=r?.openRequest,a=r?.computerId,o=i?.kind===`navigate`?i.params.find(e=>e.key===`print`):void 0,s=ff.shape.printId.safeParse(o?.value),c=s.success?s.data:null,l=i?.kind===`navigate`?i.requestId:null,u=(0,X.useRef)({app:n,requestId:l,computerId:a});(u.current.app!==n||u.current.requestId!==l)&&(u.current={app:n,requestId:l,computerId:a});let d=u.current.computerId===a,f=la({...Sa(n,sa,ha.of(n,`prints`,`navigate`,a,l,c),async(e,t)=>{if(!n||!a||!c||!l)throw Error(`No print selected`);let r=await e.call(`openOutput`,JSON.stringify({printId:c,byteLength:1}));if(t.throwIfAborted(),n.context.get().computerId!==a)throw Error(`Computer selection changed`);let i=pf.parse(r);if(i.printId!==c)throw Error(`Print selection changed`);return{path:i.path,requestId:l,computerId:a}}),enabled:!!(n&&d&&a&&l&&c&&n.capabilities.has(sa)),retry:!1,staleTime:1/0}),p=(0,X.useRef)(t);p.current=t;let m=(0,X.useRef)(void 0);return(0,X.useEffect)(()=>{let t=f.data;!e||!t||m.current===t||e.app.context.get().computerId!==t.computerId||(m.current=t,p.current(t.path,e,t.computerId))},[e,f.data]),{target:f.data??null,error:f.error}}var hf=X.createContext(void 0);function gf(e){let t=X.useContext(hf);if(!e&&t===void 0)throw Error(Pn(27));return t}var _f=X.forwardRef(function(e,t){let{render:n,className:r,style:i,forceRender:a=!1,...o}=e,s=gf(),c=s.useState(`open`),l=s.useState(`nested`),u=s.useState(`mounted`),d={open:c,transitionStatus:s.useState(`transitionStatus`)};return rr(`div`,e,{state:d,ref:[s.context.backdropRef,t],stateAttributesMapping:Mn,props:[{role:`presentation`,hidden:!u,style:{userSelect:`none`,WebkitUserSelect:`none`}},o],enabled:a||!l})}),vf=X.forwardRef(function(e,t){let{render:n,className:r,style:i,disabled:a=!1,nativeButton:o=!0,...s}=e,c=gf(),l=c.useState(`open`),{getButtonProps:u,buttonRef:d}=sr({disabled:a,native:o}),f={disabled:a};function p(e){l&&c.setOpen(!1,ai(ri,e.nativeEvent))}return rr(`button`,e,{state:f,ref:[t,d],props:[{onClick:p},s,u]})}),yf=X.forwardRef(function(e,t){let{render:n,className:r,style:i,id:a,...o}=e,s=gf(),c=gr(a);return s.useSyncedValueWithCleanup(`descriptionElementId`,c),rr(`p`,e,{ref:t,props:[{id:c},o]})}),bf=X.createContext(void 0);function xf(){let e=X.useContext(bf);if(e===void 0)throw Error(Pn(26));return e}var Sf=`--nested-dialogs`,Cf=`data-nested-dialog-open`,wf={...Ir,...Jn,nestedDialogOpen(e){return e?{[Cf]:``}:null}},Z=_t(),Tf=X.forwardRef(function(e,t){let{render:n,className:r,style:i,finalFocus:a,initialFocus:o,...s}=e,c=gf(),l=c.useState(`descriptionElementId`),u=c.useState(`disablePointerDismissal`),d=c.useState(`floatingRootContext`),f=c.useState(`popupProps`),p=c.useState(`modal`),m=c.useState(`mounted`),h=c.useState(`nested`),g=c.useState(`nestedOpenDialogCount`),_=c.useState(`open`),v=c.useState(`openMethod`),y=c.useState(`titleElementId`),b=c.useState(`transitionStatus`),x=c.useState(`role`),S=d.useState(`floatingId`);xf(),An({open:_,ref:c.context.popupRef,onComplete(){_&&c.context.onOpenChangeComplete?.(!0)}});let C=o===void 0?Vn(c.context.popupRef):o,w=g>0,T=c.useStateSetter(`popupElement`),E=rr(`div`,e,{state:{open:_,nested:h,transitionStatus:b,nestedDialogOpen:w},props:[f,{id:S,"aria-labelledby":y,"aria-describedby":l,role:x,...Hn,hidden:!m,onKeyDown(e){jn.has(e.key)&&e.stopPropagation()},style:{[Sf]:g}},s],ref:[t,c.context.popupRef,T],stateAttributesMapping:wf});return(0,Z.jsx)(Yr,{context:d,openInteractionType:v,disabled:!m,closeOnFocusOut:!u,initialFocus:C,returnFocus:a,modal:p!==!1,restoreFocus:`popup`,children:E})}),Ef=X.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e,i=gf(),a=i.useState(`mounted`),o=i.useState(`modal`),s=i.useState(`open`);return a||n?(0,Z.jsx)(bf.Provider,{value:n,children:(0,Z.jsxs)(Zr,{ref:t,...r,children:[a&&o===!0&&(0,Z.jsx)(Qn,{ref:i.context.internalBackdropRef,inert:Fr(!s)}),e.children]})}):null});function Df({store:e,parentContext:t,isDrawer:n}){let r=e.useState(`open`),i=e.useState(`mounted`),a=e.useState(`disablePointerDismissal`),o=e.useState(`modal`),s=e.useState(`popupElement`),c=e.useState(`floatingRootContext`),[l,u]=X.useState(0),[d,f]=X.useState(0),p=l===0,m=$r(c,{outsidePressEvent(){return e.context.internalBackdropRef.current||e.context.backdropRef.current?`intentional`:{mouse:o===`trap-focus`?`sloppy`:`intentional`,touch:`sloppy`}},outsidePress(t){if(!e.context.outsidePressEnabledRef.current||`button`in t&&t.button!==0)return!1;if(`touches`in t){if(t.type===`touchend`){if(t.changedTouches.length!==1||t.touches.length!==0)return!1}else if(t.touches.length!==1)return!1}let n=Kr(t);if(p&&!a){if(o){let t=e.context.internalBackdropRef.current,r=e.context.backdropRef.current;return t||r?t===n||r===n||Er(n,s)&&!n?.hasAttribute(`data-base-ui-portal`):!0}return!0}return!1},escapeKey:p});return In(r&&o===!0,s),e.useContextCallback(`onNestedDialogOpen`,(t,n)=>{!e.select(`open`)&&!e.select(`mounted`)||(u(t),f(n))}),zn(()=>{!r&&!i&&(u(0),f(0))},[r,i]),zn(()=>(t?.onNestedDialogOpen&&r&&t.onNestedDialogOpen(l+1,d+ +!!n),()=>{t?.onNestedDialogOpen&&r&&t.onNestedDialogOpen(0,0)}),[n,r,l,d,t]),pr(e,{activeTriggerProps:m.reference,inactiveTriggerProps:m.trigger,popupProps:m.floating,nestedOpenDialogCount:l,nestedOpenDrawerCount:d}),null}var Of={...Wn,modal:e=>e.modal,nested:e=>e.nested,nestedOpenDialogCount:e=>e.nestedOpenDialogCount,nestedOpenDrawerCount:e=>e.nestedOpenDrawerCount,disablePointerDismissal:e=>e.disablePointerDismissal,openMethod:e=>e.openMethod,descriptionElementId:e=>e.descriptionElementId,titleElementId:e=>e.titleElementId,viewportElement:e=>e.viewportElement,role:e=>e.role},kf=class extends qn{constructor(e,t,n){let r=new lr,i=Af(e,r,t,n);super(i,jf(r),Of)}setOpen=(e,t)=>{t.preventUnmountOnClose=()=>{this.set(`preventUnmountingOnClose`,!0)},!e&&t.trigger==null&&this.state.activeTriggerId!=null&&(t.trigger=this.state.activeTriggerElement??void 0),this.context.onOpenChange?.(e,t),!t.isCanceled&&(this.state.floatingRootContext.dispatchOpenChange(e,t),this.update(Kn(this.state,e,t.trigger)))}};function Af(e,t,n,r=!1){return{...Bn(t,n,r),modal:!0,disablePointerDismissal:!1,viewportElement:null,descriptionElementId:void 0,titleElementId:void 0,openMethod:null,nested:!1,nestedOpenDialogCount:0,nestedOpenDrawerCount:0,role:`dialog`,...e}}function jf(e){return{popupRef:X.createRef(),backdropRef:X.createRef(),internalBackdropRef:X.createRef(),outsidePressEnabledRef:{current:!0},triggerElements:e,onOpenChange:void 0,onOpenChangeComplete:void 0}}function Mf(e,t){let{children:n,open:r,defaultOpen:i=!1,onOpenChange:a,onOpenChangeComplete:o,disablePointerDismissal:s=!1,modal:c=!0,actionsRef:l,handle:u,triggerId:d,defaultTriggerId:f=null}=t,p=e===`drawer`,m=e===`alert-dialog`,h=m?!0:c,g=m||s,_=m?`alertdialog`:`dialog`,v=gf(!0),y={modal:h,disablePointerDismissal:g,nested:v!=null,role:_},b=fr((e,t)=>new kf({open:i,openProp:r,activeTriggerId:f,triggerIdProp:d,...y},e,t),!0);b.useControlledProp(`openProp`,r),b.useControlledProp(`triggerIdProp`,d),b.useSyncedValues(y),b.useContextCallback(`onOpenChange`,a),b.useContextCallback(`onOpenChangeComplete`,o);let x=b.useState(`open`),S=b.useState(`mounted`),C=b.useState(`payload`);mr(b,x),qr(b);let{forceUnmount:w}=Gn(x,b);X.useImperativeHandle(l,()=>({unmount:w,close:()=>b.setOpen(!1,ai(si))}),[w,b]);let T=x||S||u!=null;return(0,Z.jsxs)(hf.Provider,{value:b,children:[u&&(0,Z.jsx)(cr,{handle:u,store:b}),T&&(0,Z.jsx)(Df,{store:b,parentContext:v?.context,isDrawer:p}),typeof n==`function`?n({payload:C}):n]})}var Nf=nr(function(e){return Mf(`dialog`,e)}),Pf=X.forwardRef(function(e,t){let{render:n,className:r,style:i,id:a,...o}=e,s=gf(),c=gr(a);return s.useSyncedValueWithCleanup(`titleElementId`,c),rr(`h2`,e,{ref:t,props:[{id:c},o]})}),Ff=li(function(e,t){let{render:n,className:r,style:i,disabled:a=!1,nativeButton:o=!0,id:s,payload:c,handle:l,...u}=e,d=gf(!0),f=er(l)??d;if(!f)throw Error(Pn(79));let p=gr(s),m=f.useState(`floatingRootContext`),h=f.useState(`isOpenedByTrigger`,p),g=f.useState(`triggerPopupId`,p),_=X.useRef(null),{registerTrigger:v,isMountedByThisTrigger:y}=tr(p,_,f,{payload:c}),{getButtonProps:b,buttonRef:x}=sr({disabled:a,native:o}),S=Hr(m),C=Rn(()=>f.select(`open`),e=>{f.set(`openMethod`,e)}),w={disabled:a,open:h},T=f.useState(`triggerProps`,y);return rr(`button`,e,{state:w,ref:[x,t,v,_],props:[S.reference,T,C,{[xr]:``,id:p,"aria-haspopup":`dialog`,"aria-expanded":h,"aria-controls":g},u,b],stateAttributesMapping:Xn})}),If=(0,X.createContext)(null);function Lf({children:e,interactionOwner:t=`local`,modal:n=!0,onOpenChange:r,...i}){return(0,Z.jsx)(If.Provider,{value:{interactionOwner:t,modal:n},children:(0,Z.jsx)(Nf,{...i,modal:n,onOpenChange:(e,n)=>{if(t===`host`&&!e&&n.reason===`escape-key`){n.cancel(),n.allowPropagation();return}r?.(e,n)},children:e})})}function Rf(){let e=(0,X.useContext)(If);if(!e)throw Error(`Dialog parts must be used inside <Dialog>`);return e}(0,X.forwardRef)(function({className:e,type:t=`button`,...n},r){return(0,Z.jsx)(Ff,{...n,className:t=>B(`btn`,St(e,t)),ref:r,type:t})});var zf=(0,X.forwardRef)(function({container:e,...t},n){let r=or(`dialog`);return e==null&&r===null?null:(0,Z.jsx)(Ef,{...t,container:e??r,ref:n})}),Bf=(0,X.forwardRef)(function({className:e,...t},n){return(0,Z.jsx)(_f,{...t,ref:n,className:t=>B(`caps-dialog-backdrop fixed inset-0 bg-black/40`,St(e,t))})}),Vf=(0,X.forwardRef)(function({className:e,finalFocus:t,size:n=`default`,...r},i){let a=Rf();return(0,Z.jsx)(Tf,{...r,"data-size":n,className:t=>B(`caps-dialog-popup overflow-y-auto overscroll-contain rounded-box bg-base-100 p-lg text-base-content shadow-xl`,n===`fill`?`fixed inset-0 h-full w-full max-w-none`:`caps-dialog-popup-default`,St(e,t)),finalFocus:a.interactionOwner===`host`?!1:t??!0,ref:i})}),Hf=(0,X.forwardRef)(function({container:e,keepMounted:t=!0,className:n,size:r=`default`,...i},a){let{modal:o}=Rf();return(0,Z.jsxs)(zf,{container:e,keepMounted:t,children:[o===!0?(0,Z.jsx)(Bf,{}):null,(0,Z.jsx)(Vf,{...i,size:r,className:e=>B(r==="default"&&`fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2`,St(n,e)),ref:a})]})});function Uf({className:e,...t}){return(0,Z.jsx)(`div`,{...t,className:B(`flex justify-end gap-sm`,e)})}function Wf({className:e,...t}){return(0,Z.jsx)(`div`,{...t,className:B(`flex flex-col gap-sm`,e)})}var Gf=(0,X.forwardRef)(function({className:e,...t},n){return(0,Z.jsx)(Pf,{...t,className:t=>B(`text-lg font-semibold`,St(e,t)),ref:n})});(0,X.forwardRef)(function({className:e,...t},n){return(0,Z.jsx)(yf,{...t,className:t=>B(`text-sm text-base-content`,St(e,t)),ref:n})});var Kf=(0,X.forwardRef)(function({className:e,type:t=`button`,...n},r){return(0,Z.jsx)(vf,{...n,className:t=>B(`btn btn-ghost`,St(e,t)),ref:r,type:t})}),qf={dot:{y:-4,height:8,cy:0},pill:{y:-16,height:32,cy:0},bang:{y:-16,height:20,cy:12}};function Jf({className:e,glyph:t,motion:n}){let r=`caps-status-${(0,X.useId)().replaceAll(`:`,``)}`,i=(0,X.useRef)(null),a=(0,X.useRef)(null),o=(0,X.useRef)(null),s=(0,X.useRef)(null),c=(0,X.useRef)(null),l=(0,X.useRef)(null),u=(0,X.useRef)(qf[t]).current,d=(0,X.useRef)(t===`dot`?1:4).current,f=(0,X.useRef)(+(t===`bang`)).current,p=(0,X.useRef)(t),h=m(s),{reduced:g}=h;return(0,X.useLayoutEffect)(()=>{if(!i.current||!a.current||!c.current||!l.current)return;let e=qf[t],n=g||p.current===t;p.current=t;let r=he(i.current),o=n?{duration:0}:Wi(r,{bounce:.3,duration:360}),s=Ma(i.current,{y:e.y,height:e.height,...o}),u=Ma(a.current,{cy:e.cy,...n?{duration:0}:{delay:_n(r,35),...Wi(r,{bounce:.3,duration:420})}}),d=Ma(c.current,{gradientTransform:`matrix(1 0 0 ${t===`dot`?`1`:`4`} 0 0)`,...o}),f=Ma(l.current,{opacity:+(t===`bang`),...n?_a:ia(r,{ease:`inOutSine`,duration:220})});return()=>{s.cancel(),u.cancel(),d.cancel(),f.cancel()}},[t,g]),(0,X.useLayoutEffect)(()=>{if(!o.current||!s.current||g||n===`none`)return;let e=n===`pulse`?Ma(o.current,{opacity:[1,.45],...ia(h,{ease:`inOutSine`,duration:750}),alternate:!0,loop:!0}):Ma(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}},...ia(h,{ease:`inOutSine`,duration:1e3}),loop:!0}),t=Ht(s.current,t=>{t?e.resume():e.pause()});return()=>{t(),e.revert()}},[n,g,h]),(0,Z.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,Z.jsxs)(`defs`,{children:[(0,Z.jsx)(kt,{id:r,values:mn}),(0,Z.jsx)(Le,{ref:c,id:`${r}-surface`,transform:`matrix(1 0 0 ${String(d)} 0 0)`}),(0,Z.jsxs)(`radialGradient`,{id:`${r}-drop-light`,gradientUnits:`userSpaceOnUse`,cx:`-1.2`,cy:`10.4`,r:`5.6`,children:[(0,Z.jsx)(`stop`,{offset:`0`,stopColor:`var(--color-white)`,style:{stopOpacity:`calc(var(--depth) * 0.5)`}}),(0,Z.jsx)(`stop`,{offset:`1`,stopColor:`var(--color-white)`,stopOpacity:`0`})]}),(0,Z.jsx)(ct,{id:`${r}-shadow`}),(0,Z.jsx)(`mask`,{id:`${r}-silhouette`,maskUnits:`userSpaceOnUse`,x:`-12`,y:`-24`,width:`24`,height:`48`,style:{maskType:`alpha`},children:(0,Z.jsxs)(`g`,{fill:`var(--color-white)`,filter:`url(#${r})`,children:[(0,Z.jsx)(`rect`,{ref:i,x:`-4`,y:u.y,width:`8`,height:u.height,rx:`4`}),(0,Z.jsx)(`circle`,{ref:a,cx:`0`,cy:u.cy,r:`4`})]})})]}),(0,Z.jsx)(`g`,{ref:o,filter:`url(#${r}-shadow)`,children:(0,Z.jsxs)(`g`,{mask:`url(#${r}-silhouette)`,children:[(0,Z.jsx)(`rect`,{x:`-12`,y:`-24`,width:`24`,height:`48`,fill:`url(#${r}-surface)`}),(0,Z.jsx)(`rect`,{ref:l,x:`-12`,y:`-24`,width:`24`,height:`48`,fill:`url(#${r}-drop-light)`,opacity:f})]})})]})}var Yf=.28;function Xf(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?Yf: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 Zf=7.25;function Qf({className:e,glyph:t,progress:n}){let r=`caps-status-mark-${(0,X.useId)().replaceAll(`:`,``)}`,i=(0,X.useRef)(null),a=(0,X.useRef)(null),o=(0,X.useRef)(null),s=(0,X.useRef)(null),c=(0,X.useRef)(null),l=(0,X.useRef)(null),u=(0,X.useRef)(null),f=(0,X.useRef)(null),p=(0,X.useRef)(Xf(t,n)).current,m=(0,X.useRef)(t),h=d();(0,X.useLayoutEffect)(()=>{let e=i.current,r=a.current,c=o.current,d=s.current,p=l.current,g=u.current,_=f.current;if(!e||!r||!c||!d||!p||!g||!_)return;let v=Xf(t,n),y=m.current;m.current=t;let b=he(e),x=h||y===t&&t!==`arc`,S=x?h?{ease:b.ease,duration:b.fast}:_a:ia(b,{ease:`outQuad`,duration:160}),C=(t===`check`||t===`cross`)&&!x,w=ia(b,{ease:`inOutSine`,duration:220}),T=[Ma(r,{opacity:v.dashes,...S}),Ma(c,{opacity:v.track*.28,...S}),Ma(d,{opacity:v.arc,"stroke-dasharray":`${String(v.sweep)} 1`,...x?h?_a:S:w}),Ma(p,{r:v.disc*Zf,...C?{delay:w.duration*.7,...Wi(b,{bounce:.35,duration:360})}:h?_a:ia(b,{ease:`inCubic`,duration:140})}),Ma(g,{"stroke-dashoffset":1-v.tick,...C&&v.tick>0?{delay:w.duration*.7+b.fast,...ia(b,{ease:`outCubic`,duration:240})}:_a}),Ma(_,{"stroke-dashoffset":1-v.cross,...C&&v.cross>0?{delay:w.duration*.7+b.fast,...ia(b,{ease:`outCubic`,duration:240})}:_a})];return t===`cross`&&C&&b.shake>0&&T.push(Ma(e,{translateX:[0,-b.shake,b.shake,-b.shake/2,0],delay:w.duration+b.fast,...ia(b,{ease:`linear`,duration:300})})),()=>{for(let e of T)e.cancel()}},[t,n,h]);let g=t===`arc`&&n===void 0&&!h;return(0,X.useLayoutEffect)(()=>{if(!g||!c.current||!i.current)return;let e=he(i.current),t=Ma(c.current,{rotate:[0,360],...ia(e,{ease:`linear`,duration:900}),loop:!0}),n=Ht(i.current,e=>{e?t.resume():t.pause()});return()=>{n(),t.revert()}},[g]),(0,Z.jsxs)(`svg`,{ref:i,"aria-hidden":`true`,className:`caps-status-mark ${e??``}`,viewBox:`0 0 16 16`,focusable:`false`,children:[(0,Z.jsxs)(`defs`,{children:[(0,Z.jsx)(Le,{id:`${r}-surface`,transform:`matrix(1.6 0 0 1.6 8 8)`}),(0,Z.jsxs)(`mask`,{id:`${r}-knock`,maskUnits:`userSpaceOnUse`,x:`0`,y:`0`,width:`16`,height:`16`,children:[(0,Z.jsx)(`rect`,{width:`16`,height:`16`,fill:`var(--color-white)`}),(0,Z.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-p.tick}),(0,Z.jsx)(`path`,{ref:f,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-p.cross})]})]}),(0,Z.jsx)(`circle`,{ref:a,cx:`8`,cy:`8`,r:`6.25`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeDasharray:`1.7 2.2`,opacity:p.dashes}),(0,Z.jsx)(`circle`,{ref:o,cx:`8`,cy:`8`,r:`6.25`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,opacity:p.track*.28}),(0,Z.jsx)(`g`,{ref:c,className:`caps-status-mark-spin`,children:(0,Z.jsx)(`circle`,{ref:s,cx:`8`,cy:`8`,r:`6.25`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,pathLength:1,strokeDasharray:`${String(p.sweep)} 1`,transform:`rotate(-90 8 8)`,opacity:p.arc})}),(0,Z.jsx)(`circle`,{ref:l,cx:`8`,cy:`8`,r:p.disc*Zf,fill:`url(#${r}-surface)`,mask:`url(#${r}-knock)`})]})}var $f=new Set([`ring`,`arc`,`check`,`cross`]);function ep(e){return $f.has(e)}var tp={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`},np=(0,X.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,Z.jsxs)(`span`,{...c,className:B(`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:[ep(n)?(0,Z.jsx)(Qf,{className:tp[i],glyph:n,progress:s}):(0,Z.jsx)(Jf,{className:tp[i],glyph:n,motion:r}),t===void 0?null:(0,Z.jsx)(`span`,{children:t})]})}),rp=(0,X.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,Z.jsxs)(`div`,{...d,className:B(`caps-failure-line`,e),"data-density":n,ref:f,role:u,children:[(0,Z.jsx)(np,{glyph:`dot`,tone:`error`}),(0,Z.jsxs)(`span`,{className:`caps-failure-line-copy`,children:[(0,Z.jsx)(`span`,{children:a}),t!==void 0&&t>1?(0,Z.jsxs)(`span`,{className:`caps-failure-line-count`,children:[`Failed `,t,` times`]}):null]}),s||o?(0,Z.jsxs)(`span`,{className:`caps-failure-line-actions`,children:[s?(0,Z.jsx)(Y,{"aria-label":c,size:`sm`,variant:`outline`,onClick:s,children:l}):null,o?(0,Z.jsx)(Y,{"aria-label":r,size:`sm`,variant:`ghost`,onClick:o,children:i}):null]}):null]})}),ip={queued:`Waiting to start`,generating:`Generating`,refining:`Refining`,done:void 0,failed:void 0},ap=(0,X.forwardRef)(function({status:e,children:t,aspectRatio:n,label:r,indicator:i,failure:a,className:o,style:s,...c},l){let u=(0,X.useRef)(null);(0,X.useImperativeHandle)(l,()=>u.current);let d=(0,X.useRef)(e),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(e);m!==e&&(h(e),p(e===`done`)),(0,X.useLayoutEffect)(()=>{let t=u.current,n=d.current;if(d.current=e,!t||n===e)return;if(!He(t)){p(!1);return}let r=he(t),i=de(r,r.ease),a=[],o=t.querySelector(`:scope > [data-layer="media"]`),s=t.querySelector(`:scope > [data-layer="placeholder"]`),c=t.querySelector(`:scope > [data-layer="failure"]`);if(e===`done`&&o){let e=o.animate(r.reduced?[{opacity:0},{opacity:1}]:[{opacity:0,filter:`blur(10px)`,transform:`scale(1.03)`},{opacity:1,filter:`blur(0px)`,transform:`none`}],{duration:r.reduced?r.fast:r.slow*2,easing:i,fill:`backwards`});e.addEventListener(`finish`,()=>{p(!1)}),a.push(e),s&&a.push(s.animate([{opacity:1},{opacity:0}],{duration:r.reduced?r.fast:r.slow,easing:i,fill:`forwards`}))}return e===`failed`&&c&&a.push(c.animate([{opacity:0,transform:`translateY(${String(r.distance)}px)`},{opacity:1,transform:`none`}],{duration:r.normal,easing:i})),n===`failed`&&s&&a.push(s.animate([{opacity:.4},{opacity:1}],{duration:r.normal,easing:i})),()=>{for(let e of a)e.cancel()}},[e]);let g=e===`queued`||e===`generating`||e===`refining`,_=r??ip[e],v=e===`done`||e===`refining`;return(0,Z.jsxs)(`div`,{...c,ref:u,className:B(`caps-generation-frame`,o),"data-status":e,"data-aspect":n===void 0?void 0:``,"aria-busy":g,style:n===void 0?s:{aspectRatio:n,...s},children:[e===`done`&&!f?null:(0,Z.jsxs)(`div`,{className:B(`caps-generation-placeholder`,e===`queued`&&`skeleton`),"data-layer":`placeholder`,role:e===`done`?void 0:`status`,"aria-hidden":e===`done`||void 0,children:[e===`generating`||e===`refining`||e===`done`?i??(0,Z.jsx)(rt,{decorative:!0,size:`lg`,variant:`bloom`}):null,_===void 0?null:(0,Z.jsx)(wn,{children:_})]}),v?(0,Z.jsx)(`div`,{className:`caps-generation-media`,"data-layer":`media`,children:t}):null,e===`failed`&&a!==void 0?(0,Z.jsx)(`div`,{className:`caps-generation-failure`,"data-layer":`failure`,role:`alert`,children:a}):null]})}),op=X.createContext(void 0);function sp(){let e=X.useContext(op);if(e===void 0)throw Error(Pn(53));return e}function cp(e,t,n){if(!e)return 0;let r=getComputedStyle(e),i=`${t}${n===`x`?`Inline`:`Block`}`,a=parseFloat(r[`${i}Start`]);return n===`x`&&t===`margin`?a*2:a+parseFloat(r[`${i}End`])}var lp=`base-ui-disable-scrollbar`,up={className:lp,getElement(e){return(0,Z.jsx)(`style`,{nonce:e,href:lp,precedence:`base-ui:low`,children:`.${lp}{scrollbar-width:none}.${lp}::-webkit-scrollbar{display:none}`})}},dp=`data-has-overflow-x`,fp=`data-has-overflow-y`,pp=`data-overflow-x-start`,mp=`data-overflow-x-end`,hp=`data-overflow-y-start`,gp=`data-overflow-y-end`,_p=e=>t=>t?{[e]:``}:null,vp={hasOverflowX:_p(dp),hasOverflowY:_p(fp),overflowXStart:_p(pp),overflowXEnd:_p(mp),overflowYStart:_p(hp),overflowYEnd:_p(gp),cornerHidden:()=>null},yp=X.createContext(void 0),bp={disableStyleElements:!1};function xp(){return X.useContext(yp)??bp}var Sp=`--scroll-area-corner-height`,Cp=`--scroll-area-corner-width`,wp=`data-orientation`,Tp={x:0,y:0},Ep={width:0,height:0},Dp={xStart:!1,xEnd:!1,yStart:!1,yEnd:!1},Op={x:!0,y:!0,corner:!0},kp=X.forwardRef(function(e,t){let{render:n,className:r,overflowEdgeThreshold:i,style:a,...o}=e,{xStart:s,xEnd:c,yStart:l,yEnd:u}=Ap(i),d=gr(),f=Or(),p=Or(),{nonce:m,disableStyleElements:h}=xp(),[g,_]=X.useState(!1),[v,y]=X.useState(!1),[b,x]=X.useState(!1),[S,C]=X.useState(!1),[w,T]=X.useState(!1),[E,D]=X.useState(Ep),[O,k]=X.useState(Ep),[A,j]=X.useState(Dp),[M,N]=X.useState(Op),P=X.useRef(null),F=X.useRef(null),I=X.useRef(null),ee=X.useRef(null),L=X.useRef(null),R=X.useRef(null),te=X.useRef(null),ne=X.useRef(null),re=X.useRef(0),z=X.useRef(0),ie=X.useRef(0),B=X.useRef(0),V=X.useRef(`vertical`),ae=X.useRef(Tp),H=X.useRef(null);function U(e){let t=e?x:y,n=e?f:p;t(!0),n.start(500,()=>{t(!1)})}let W=Ln(e=>{let t=e.x-ae.current.x,n=e.y-ae.current.y;ae.current=e,n!==0&&U(!0),t!==0&&U(!1)}),oe=Ln(()=>{let e=F.current;e&&H.current===null&&(H.current=e.style.scrollSnapType,e.style.scrollSnapType=`none`)}),se=Ln(e=>{if(e.button!==0||ne.current!==null&&(V.current===`vertical`?L.current:R.current)?.hasPointerCapture(ne.current))return;ne.current=e.pointerId,re.current=e.clientY,z.current=e.clientX,V.current=e.currentTarget.getAttribute(wp);let t=F.current;t&&(ie.current=t.scrollTop,B.current=t.scrollLeft,oe()),(V.current===`vertical`?L.current:R.current)?.setPointerCapture(e.pointerId)}),G=Ln(e=>{if(e.pointerId!==ne.current)return;ne.current=null,(V.current===`vertical`?x:y)(!1),H.current!==null&&(F.current&&(F.current.style.scrollSnapType=H.current),H.current=null);let t=V.current===`vertical`?L.current:R.current;t?.hasPointerCapture(e.pointerId)&&t.releasePointerCapture(e.pointerId)}),ce=Ln(e=>{if(e.pointerId!==ne.current)return;if(e.buttons%2==0){G(e);return}let t=F.current;if(!t)return;let n=V.current===`vertical`,r=n?L.current:R.current,i=n?I.current:ee.current;if(!r||!i)return;let a=n?`y`:`x`,o=cp(i,`padding`,a),s=cp(r,`margin`,a),c=n?r.offsetHeight:r.offsetWidth,l=(n?i.offsetHeight:i.offsetWidth)-c-o-s,u=n?e.clientY-re.current:e.clientX-z.current,d=l<=0?0:u/l,f=n?t.scrollHeight:t.scrollWidth,p=n?t.clientHeight:t.clientWidth,m=(n?ie.current:B.current)+d*(f-p);n?t.scrollTop=m:t.scrollLeft=m,e.preventDefault(),U(n)});function le(e){C(e.pointerType===`touch`)}function ue(e){if(le(e),e.pointerType!==`touch`){let t=Er(P.current,e.target);_(t)}}let de=X.useMemo(()=>({scrolling:v||b,hasOverflowX:!M.x,hasOverflowY:!M.y,overflowXStart:A.xStart,overflowXEnd:A.xEnd,overflowYStart:A.yStart,overflowYEnd:A.yEnd,cornerHidden:M.corner}),[v,b,M.x,M.y,M.corner,A]),fe={role:`presentation`,onPointerEnter:ue,onPointerMove:ue,onPointerDown:le,onPointerLeave(){_(!1)},style:{position:`relative`,[Sp]:`${E.height}px`,[Cp]:`${E.width}px`}},pe=rr(`div`,e,{state:de,ref:[t,P],props:[fe,o],stateAttributesMapping:vp}),me=X.useMemo(()=>({handlePointerDown:se,handlePointerMove:ce,handlePointerUp:G,handleScroll:W,disableViewportSnap:oe,cornerSize:E,setCornerSize:D,thumbSize:O,setThumbSize:k,hasMeasuredScrollbar:w,setHasMeasuredScrollbar:T,touchModality:S,cornerRef:te,scrollingX:v,scrollingY:b,hovering:g,setHovering:_,viewportRef:F,scrollbarYRef:I,scrollbarXRef:ee,thumbYRef:L,thumbXRef:R,rootId:d,hiddenState:M,setHiddenState:N,overflowEdges:A,setOverflowEdges:j,viewportState:de,overflowEdgeThreshold:{xStart:s,xEnd:c,yStart:l,yEnd:u}}),[se,ce,G,W,oe,E,O,w,S,v,b,g,d,M,A,de,s,c,l,u]);return(0,Z.jsxs)(op.Provider,{value:me,children:[!h&&up.getElement(m),pe]})});function Ap(e){let t=typeof e==`number`?{xStart:e,xEnd:e,yStart:e,yEnd:e}:e;return{xStart:Math.max(0,t?.xStart||0),xEnd:Math.max(0,t?.xEnd||0),yStart:Math.max(0,t?.yStart||0),yEnd:Math.max(0,t?.yEnd||0)}}function jp(e,t=-(2**53-1),n=2**53-1){return Math.max(t,Math.min(e,n))}var Mp=X.createContext(void 0);function Np(){let e=X.useContext(Mp);if(e===void 0)throw Error(Pn(55));return e}function Pp(e,t){if(t<=0)return 0;let n=jp(e,0,t),r=n,i=t-n,a=r<=1,o=i<=1;return a&&o?r<=i?0:t:a?0:o?t:n}var Fp=`--scroll-area-overflow-x-start`,Ip=`--scroll-area-overflow-x-end`,Lp=`--scroll-area-overflow-y-start`,Rp=`--scroll-area-overflow-y-end`,zp=`--scroll-area-thumb-height`,Bp=`--scroll-area-thumb-width`,Vp=[Fp,Ip,Lp,Rp],Hp=!1;function Up(){Hp||Br||(typeof CSS<`u`&&`registerProperty`in CSS&&Vp.forEach(e=>{try{CSS.registerProperty({name:e,syntax:`<length>`,inherits:!1,initialValue:`0px`})}catch{}}),Hp=!0)}var Wp=X.forwardRef(function(e,t){let{render:n,className:r,style:i,...a}=e,{viewportRef:o,scrollbarYRef:s,scrollbarXRef:c,thumbYRef:l,thumbXRef:u,cornerRef:d,cornerSize:f,setCornerSize:p,setThumbSize:m,rootId:h,setHiddenState:g,hiddenState:_,setHasMeasuredScrollbar:v,handleScroll:y,touchModality:b,setHovering:x,setOverflowEdges:S,overflowEdgeThreshold:C,viewportState:w}=sp(),T=oi(),E=X.useRef(!0),D=X.useRef([NaN,NaN,NaN,NaN]),O=Or(),k=Or(),A=Ln(()=>{let e=o.current,t=s.current,n=c.current,r=l.current,i=u.current,a=d.current;if(!e)return;let h=e.scrollHeight,_=e.scrollWidth,y=e.clientHeight,b=e.clientWidth,x=e.scrollTop,w=e.scrollLeft,E=D.current,O=Number.isNaN(E[0]);if(E[0]=y,E[1]=h,E[2]=b,E[3]=_,O&&v(!0),h===0||_===0)return;let k=Gp(e),A=k.y,j=k.x,M=b/_,N=y/h,P=Math.max(0,_-b),F=Math.max(0,h-y),I=0,ee=0;j||(I=Pp(T===`rtl`?-w:w,P),ee=P-I);let L=A?0:Pp(x,F),R=A?0:F-L,te=j?0:b,ne=A?0:y,re=0,z=0;!j&&!A&&(re=t?.offsetWidth||0,z=n?.offsetHeight||0);let ie=f.width===0&&f.height===0,B=ie?re:0,V=ie?z:0,ae=cp(n,`padding`,`x`),H=cp(t,`padding`,`y`),U=cp(i,`margin`,`x`),W=cp(r,`margin`,`y`),oe=te-ae-U,se=ne-H-W,G=n?Math.min(n.offsetWidth-B,oe):oe,ce=t?Math.min(t.offsetHeight-V,se):se,le=Math.max(16,G*M),ue=Math.max(16,ce*N);if(m(e=>Kp(e,{width:le,height:ue})),t&&r){let e=qp(r,zp,x,F,h,ue,t.offsetHeight-ue-H-W);r.style.transform=`translate3d(0,${e}px,0)`}if(n&&i){let e=n.offsetWidth-le-ae-U,t=qp(i,Bp,T===`rtl`?-w:w,P,_,le,e);i.style.transform=`translate3d(${T===`rtl`?-t:t}px,0,0)`}let de=[I,ee,L,R];Vp.forEach((t,n)=>{e.style.setProperty(t,`${de[n]}px`)}),a&&p(e=>Kp(e,{width:re,height:z})),g(e=>Kp(e,k));let fe={xStart:!j&&I>C.xStart,xEnd:!j&&ee>C.xEnd,yStart:!A&&L>C.yStart,yEnd:!A&&R>C.yEnd};S(e=>Kp(e,fe))});zn(()=>{Up()},[]),zn(()=>{queueMicrotask(A)},[A,_,T,C.xStart,C.xEnd,C.yStart,C.yEnd]),zn(()=>{o.current?.matches(`:hover`)&&x(!0)},[o,x]),zn(()=>{let e=o.current;if(typeof ResizeObserver>`u`||!e)return;let t=!1,n=new ResizeObserver(()=>{if(!t){t=!0;let n=D.current;if(n[0]===e.clientHeight&&n[1]===e.scrollHeight&&n[2]===e.clientWidth&&n[3]===e.scrollWidth)return}A()});return n.observe(e),k.start(0,()=>{let t=wr(e,{subtree:!0});t.length!==0&&Promise.allSettled(t.map(e=>e.finished.then(ui))).then(A).catch(()=>{})}),()=>{n.disconnect(),k.clear()}},[A,o,k]);function j(){E.current=!1}let M={...h&&{"data-id":`${h}-viewport`},tabIndex:_.x&&_.y?-1:0,className:up.className,style:{overflow:`scroll`},onScroll(){o.current&&(A(),(b||!E.current)&&y({x:o.current.scrollLeft,y:o.current.scrollTop}),O.start(100,()=>{E.current=!0}))},onWheel:j,onPointerMove:j,onPointerEnter:j,onKeyDown:j},N=rr(`div`,e,{ref:[t,o],state:w,props:[M,a],stateAttributesMapping:vp}),P=X.useMemo(()=>({computeThumbPosition:A}),[A]);return(0,Z.jsx)(Mp.Provider,{value:P,children:N})});function Gp(e){let t=e.clientHeight>=e.scrollHeight,n=e.clientWidth>=e.scrollWidth;return{y:t,x:n,corner:t||n}}function Kp(e,t){for(let n in t)if(e[n]!==t[n])return t;return e}function qp(e,t,n,r,i,a,o){let s=jp(n,0,r),c=n-s,l=Math.max(16,a*i/(i+Math.abs(c)));return e.style.setProperty(t,c?`${l}px`:``),(r?s/r*o:0)+(c>0?a-l:0)}var Jp=X.createContext(void 0);function Yp(){let e=X.useContext(Jp);if(e===void 0)throw Error(Pn(54));return e}var Xp=X.forwardRef(function(e,t){let{render:n,className:r,orientation:i=`vertical`,keepMounted:a=!1,style:o,...s}=e,{hovering:c,scrollingX:l,scrollingY:u,hiddenState:d,scrollbarYRef:f,scrollbarXRef:p,viewportRef:m,thumbYRef:h,thumbXRef:g,handlePointerDown:_,handlePointerUp:v,handleScroll:y,disableViewportSnap:b,rootId:x,thumbSize:S,hasMeasuredScrollbar:C,viewportState:w}=sp(),T=i===`vertical`,E={...w,hovering:c,scrolling:T?u:l,orientation:i},D=oi(),O=!C&&!a,k=T?d.y:d.x,A=a||!k;X.useEffect(()=>{if(!A)return;let e=m.current,t=T?f.current:p.current;if(!t)return;function n(t){if(!e||t.ctrlKey)return;let n=!T,r=n?`scrollLeft`:`scrollTop`,i=n?t.deltaX:t.deltaY;if(i===0)return;let a=n?e.scrollWidth-e.clientWidth:e.scrollHeight-e.clientHeight,o=n&&D===`rtl`?-a:0,s=n&&D===`rtl`?0:a,c=e[r];c<=o&&i<0||c>=s&&i>0||(t.preventDefault(),e[r]=Math.min(s,Math.max(o,c+i)),y({x:e.scrollLeft,y:e.scrollTop}))}return Cr(t,`wheel`,n,{passive:!1})},[D,y,T,p,f,A,m]);let j={...x&&{"data-id":`${x}-scrollbar`},"aria-hidden":!0,onPointerDown(e){if(e.button!==0)return;let t=Kr(e.nativeEvent),n=T?h.current:g.current;if(n&&Er(n,t))return;let r=m.current;if(!r)return;let i=T?f.current:p.current;if(!n||!i)return;let a=T?`y`:`x`,o=cp(n,`margin`,a),s=cp(i,`padding`,a),c=T?n.offsetHeight:n.offsetWidth,l=i.getBoundingClientRect(),u=T?e.clientY-l.top-c/2-s+o/2:e.clientX-l.left-c/2-s+o/2,d=T?r.scrollHeight:r.scrollWidth,v=T?r.clientHeight:r.clientWidth,x=(T?i.offsetHeight:i.offsetWidth)-c-s-o;if(x<=0)return;let S=u/x,C=d-v;b(),T?r.scrollTop=S*C:r.scrollLeft=D===`rtl`?-(1-S)*C:S*C,y({x:r.scrollLeft,y:r.scrollTop}),_(e)},onMouseDown(e){e.preventDefault()},onPointerUp:v,onPointerCancel:v,style:{position:`absolute`,touchAction:`none`,WebkitUserSelect:`none`,userSelect:`none`,visibility:O?`hidden`:void 0,...T?{top:0,bottom:`var(${Sp})`,insetInlineEnd:0,[zp]:`${S.height}px`}:{insetInlineStart:0,insetInlineEnd:`var(${Cp})`,bottom:0,[Bp]:`${S.width}px`}}},M=rr(`div`,e,{ref:[t,T?f:p],state:E,props:[j,s],stateAttributesMapping:vp});return A?(0,Z.jsx)(Jp.Provider,{value:i,children:M}):null}),Zp=X.forwardRef(function(e,t){let{render:n,className:r,style:i,...a}=e,{computeThumbPosition:o}=Np(),{hasMeasuredScrollbar:s,viewportState:c}=sp(),l=X.useRef(null),u=X.useRef(s);return zn(()=>{if(typeof ResizeObserver>`u`)return;let e=!1,t=new ResizeObserver(()=>{!e&&(e=!0,!u.current)||o()});return l.current&&t.observe(l.current),()=>{t.disconnect()}},[o]),rr(`div`,e,{ref:[t,l],state:c,stateAttributesMapping:vp,props:[{role:`presentation`,style:{minWidth:`fit-content`}},a]})}),Qp=X.forwardRef(function(e,t){let{render:n,className:r,style:i,...a}=e,{thumbYRef:o,thumbXRef:s,handlePointerDown:c,handlePointerMove:l,handlePointerUp:u,scrollingX:d,scrollingY:f,hasMeasuredScrollbar:p}=sp(),m=Yp(),h=m===`vertical`;return rr(`div`,e,{ref:[t,h?o:s],state:{scrolling:h?f:d,orientation:m},props:[{onPointerDown:c,onPointerMove:l,onPointerUp:u,onPointerCancel:u,style:{visibility:p?void 0:`hidden`,...h?{height:`var(--scroll-area-thumb-height)`}:{width:`var(--scroll-area-thumb-width)`}}},a]})});function $p(e,t,n){let r=(Math.abs(t)-Math.abs(e))/Math.max(16,n);if(Math.abs(r)<.035)return null;let i=Math.min(.04,Math.abs(r)*.3),a=r>0,o=Math.sign(t||e);return{scaleY:1+(a?i:-i),scaleX:1+(a?-i/2:i/2),origin:(a?o>0:o<0)?`center top`:`center bottom`}}function em(e,t,n){if(t<=0||Math.abs(n)<4)return null;let r=e<=0&&n<0,i=e>=t-1&&n>0;if(!r&&!i)return null;let a=Math.min(.06,Math.abs(n)/120*.06);return{scaleY:1-a,scaleX:1+a/2,origin:r?`center top`:`center bottom`}}var tm=(0,X.forwardRef)(function({children:e,className:t,surface:n=!1,surfaceSize:r,surfaceDepth:i,screen:a=!1,...o},s){let c=(0,X.useRef)(null),l=(0,X.useRef)(null),u=d();(0,X.useEffect)(()=>{let e=c.current,t=e?.querySelector(`.caps-scroll-viewport`);if(!t||!e)return;let n=null,r,i=t.scrollTop,a=performance.now(),o=0,s=e=>{let t=l.current;if(!e||u||!t)return;n?.cancel(),t.style.transformOrigin=e.origin;let r=he(t),i=ia(r,{ease:`outQuad`,duration:45}),a=Wi(r,{bounce:.18,duration:180});n=Ma(t,{scaleY:[{to:e.scaleY,...i},{to:1,...a}],scaleX:[{to:e.scaleX,...i},{to:1,...a}]})},d=(e,t)=>{let n=$p(o,e,t);o=e,s(n)},f=e=>{if(e.ctrlKey||Math.abs(e.deltaX)>Math.abs(e.deltaY))return;let n=e.deltaMode===1?16:e.deltaMode===2?t.clientHeight:1,i=em(t.scrollTop,t.scrollHeight-t.clientHeight,e.deltaY*n);i&&(clearTimeout(r),o=0,s(i))},p=()=>{let e=performance.now(),n=e-a,s=n>100?16:Math.max(16,n),c=t.scrollTop-i;n>100&&(o=0),d(c/s,s),i=t.scrollTop,a=e,clearTimeout(r),r=setTimeout(()=>{d(0,32)},64)};return t.addEventListener(`scroll`,p,{passive:!0}),e.addEventListener(`wheel`,f,{passive:!0}),()=>{clearTimeout(r),n?.cancel(),l.current&&(l.current.style.transform=`none`),t.removeEventListener(`scroll`,p),e.removeEventListener(`wheel`,f)}},[a,n,u]);let f=(0,Z.jsx)(Wp,{render:a?(0,Z.jsx)(pa,{}):(0,Z.jsx)(`div`,{}),...o,ref:s,className:`caps-scroll-viewport`,children:(0,Z.jsx)(Zp,{style:{minWidth:0},children:e})});return(0,Z.jsxs)(kp,{render:n?(0,Z.jsx)(ya,{size:r??`md`,depth:i??`shallow`}):(0,Z.jsx)(`div`,{}),ref:c,className:B(`caps-scroll-area`,t),children:[a?(0,Z.jsx)(`div`,{className:`caps-display-gasket caps-scroll-display`,children:f}):f,(0,Z.jsx)(ya,{size:`sm`,depth:`deep`,placement:`embedded`,className:`caps-scroll-track-surface`,children:(0,Z.jsx)(Xp,{className:`caps-scroll-track`,children:(0,Z.jsx)(Qp,{className:`caps-scroll-thumb`,children:(0,Z.jsx)(`span`,{className:`caps-scroll-thumb-surface`,ref:l})})})})]})}),nm=Ge(`ArrowLeft`,[[`path`,{d:`m12 19-7-7 7-7`,key:`1l729n`}],[`path`,{d:`M19 12H5`,key:`x3x0zl`}]]),rm=Ge(`ArrowRight`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`m12 5 7 7-7 7`,key:`xquz4c`}]]),im=Ge(`ArrowUp`,[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]),am=Ge(`ChevronDown`,[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]),om=Ge(`ExternalLink`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`M10 14 21 3`,key:`gplh6r`}],[`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`,key:`a6xqqp`}]]),sm=Ge(`EyeOff`,[[`path`,{d:`M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49`,key:`ct8e1f`}],[`path`,{d:`M14.084 14.158a3 3 0 0 1-4.242-4.242`,key:`151rxh`}],[`path`,{d:`M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143`,key:`13bj9a`}],[`path`,{d:`m2 2 20 20`,key:`1ooewy`}]]),cm=Ge(`Eye`,[[`path`,{d:`M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0`,key:`1nclc0`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),lm=Ge(`FileImage`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`circle`,{cx:`10`,cy:`12`,r:`2`,key:`737tya`}],[`path`,{d:`m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22`,key:`wt3hpn`}]]),um=Ge(`Folder`,[[`path`,{d:`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`,key:`1kt360`}]]),dm=Ge(`ImagePlus`,[[`path`,{d:`M16 5h6`,key:`1vod17`}],[`path`,{d:`M19 2v6`,key:`4bpg5p`}],[`path`,{d:`M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5`,key:`1ue2ih`}],[`path`,{d:`m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21`,key:`1xmnt7`}],[`circle`,{cx:`9`,cy:`9`,r:`2`,key:`af1f0g`}]]),fm=Ge(`Info`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 16v-4`,key:`1dtifu`}],[`path`,{d:`M12 8h.01`,key:`e9boi3`}]]),pm=Ge(`Maximize`,[[`path`,{d:`M8 3H5a2 2 0 0 0-2 2v3`,key:`1dcmit`}],[`path`,{d:`M21 8V5a2 2 0 0 0-2-2h-3`,key:`1e4gt3`}],[`path`,{d:`M3 16v3a2 2 0 0 0 2 2h3`,key:`wsl5sc`}],[`path`,{d:`M16 21h3a2 2 0 0 0 2-2v-3`,key:`18trek`}]]),mm=Ge(`Minus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}]]),hm=Ge(`Plus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`M12 5v14`,key:`s699le`}]]),gm=Ge(`SlidersHorizontal`,[[`line`,{x1:`21`,x2:`14`,y1:`4`,y2:`4`,key:`obuewd`}],[`line`,{x1:`10`,x2:`3`,y1:`4`,y2:`4`,key:`1q6298`}],[`line`,{x1:`21`,x2:`12`,y1:`12`,y2:`12`,key:`1iu8h1`}],[`line`,{x1:`8`,x2:`3`,y1:`12`,y2:`12`,key:`ntss68`}],[`line`,{x1:`21`,x2:`16`,y1:`20`,y2:`20`,key:`14d8ph`}],[`line`,{x1:`12`,x2:`3`,y1:`20`,y2:`20`,key:`m0wm8r`}],[`line`,{x1:`14`,x2:`14`,y1:`2`,y2:`6`,key:`14e1ph`}],[`line`,{x1:`8`,x2:`8`,y1:`10`,y2:`14`,key:`1i6ji0`}],[`line`,{x1:`16`,x2:`16`,y1:`18`,y2:`22`,key:`1lctlv`}]]),_m=Ge(`Square`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}]]),vm=Ge(`Upload`,[[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}],[`polyline`,{points:`17 8 12 3 7 8`,key:`t8dd8p`}],[`line`,{x1:`12`,x2:`12`,y1:`3`,y2:`15`,key:`widbto`}]]),ym=vn([Ue({kind:at(`compose`),text:Tn.pipe(h(On(1)),h(le(2e3)))}),Ue({kind:at(`navigate`),params:qe(Ue({key:Tn.pipe(h(On(1)),h(le(64))),value:Tn.pipe(h(le(1024)))})).pipe(h(le(16)))})]);vn([Ue({role:Tn.pipe(h(On(1)),h(le(80))),intent:ym}),Ue({appId:Tn.pipe(h(On(1)),h(le(128))),intent:ym})],{mode:`oneOf`});var bm=G({displayName:i().min(1).max(80).nullable()}).nullable(),xm=_(`apps.open`,1,Yt(()=>L({open:H,role:re(bt(bm))})));_(`apps.call`,1,Yt(()=>L({call:re(bt(on().transform(e=>p(e))))})));var Sm=i().regex(/^[a-zA-Z0-9._-]{1,128}$/).refine(e=>e!==`.`&&e!==`..`),Cm=i().regex(/^[0-9a-f]{40}$/);G({ref:i().startsWith(`refs/`).max(1024),before:Cm,after:Cm}),Yt(()=>i().min(1).max(512));var wm=`files`,Tm=G({name:i(),email:i()}),Em=G({hash:Cm,treeHash:Cm,message:i(),author:Tm,committer:Tm,parents:be(Cm),authoredAt:q(),committedAt:q()}),Dm=G({name:i(),mode:i(),hash:Cm,type:Ce([`blob`,`tree`,`commit`])});G({ref:i(),commit:Em,path:i(),entries:be(Dm)});var Om=65536,km=i().min(1).max(1024).refine(e=>!e.startsWith(`/`)&&!e.includes(`\\`)&&!e.includes(`\0`)&&e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`&&e!==`.git`),`Choose a relative repository file path.`),Am=i().min(1).max(256),jm={repo:Sm,branch:Am,path:km},Mm=Ce([`pending`,`synced`,`conflict`,`failed`]),Nm=G({text:i(),revision:q().int().positive(),state:Mm,theirs:G({blob:Cm.nullable(),commit:Cm}).optional(),failure:Ce([`branch_missing`,`access_changed`,`sync_failed`,`permanent_material`]).optional()});G({...jm,baseBlob:Cm.nullable(),baseCommit:Cm,text:i().max(Om),revision:q().int().positive().nullable()});var Pm=et([G({kind:A(`saved`),revision:q().int().positive(),state:A(`pending`)}),G({kind:A(`synced`),revision:q().int().positive(),commit:Cm}),G({kind:A(`conflict`),revision:q().int().nonnegative(),theirs:Nm.shape.theirs.optional()}),G({kind:A(`failed`),revision:q().int().positive(),reason:Ce([`branch_missing`,`access_changed`,`sync_failed`,`permanent_material`])}),G({kind:A(`refused`),reason:Ce([`not-source-writer`,`background-unavailable`])})]);G({...jm,revision:q().int().positive()}),et([G({kind:Ce([`discarded`,`not_found`])}),G({kind:A(`conflict`),revision:q().int().positive()})]),G({settled:be(G({...jm,result:Pm})),more:Ee()}),G({version:q().int().positive().nullable(),commit:Cm,blob:Cm.nullable(),pending:Nm.optional(),ref:i(),path:i(),size:q(),binary:Ee(),text:i().nullable()}),G({ref:i(),commits:be(G({commit:Em,agent:i().nullable()})),next:i().optional()}),G({ref:i(),commit:Em,paths:be(i()),truncated:Ee()}),G({kind:A(`rebuilding`)}),G({done:Ee(),cursor:i().nullable()}),et([G({repository:Sm,branch:Am,path:km}),G({path:i().min(1).max(1024)})]);var Fm=24,Im={all:e=>ha.of(e,`prints`,`gallery`),listings:e=>[...Im.all(e),`listing`],listing:(e,t)=>[...Im.listings(e),t],file:(e,t)=>[...Im.all(e),`file`,t]};function Lm(e,t){let n=e?.context.get().computerId;return Ho({queryKey:Im.listing(e,t),initialPageParam:0,enabled:!!(n&&t&&e.capabilities.has(jr)&&e.capabilities.has(_r)),queryFn:async({pageParam:r,signal:i})=>{if(!e||!n||!t)throw new J(`No Computer folder selected`,{code:`SELECTION_CHANGED`,retryable:!1});let a=[],o=r;do{if(i.throwIfAborted(),e.context.get().computerId!==n)throw new J(`Computer selection changed`,{code:`SELECTION_CHANGED`,retryable:!1});let r=await Xr(e.capabilities,{path:t,limit:Fm-a.length,offset:o});if(i.throwIfAborted(),r.nextOffset!==null&&r.nextOffset<=o)throw new J(`Directory pagination did not advance`,{code:`PROTOCOL`,retryable:!1});a.push(...r.entries.filter(e=>e.type===`file`&&/\.(avif|gif|jpe?g|png|svg|webp|mp4)$/i.test(e.name)).map(e=>({...e,path:`${r.path.replace(/\/$/,``)}/${e.name}`}))),o=r.nextOffset}while(a.length<Fm&&o!==null);return{entries:a,nextOffset:o}},getNextPageParam:e=>e.nextOffset})}function Rm(e,t,n){return{...Sa(e,_r,[...Im.file(e,t.path),t.modifiedAt,t.size],async(n,r)=>{if(!e)throw new J(`Prints disconnected`,{code:`DISCONNECTED`,retryable:!0});let i=await br(e.capabilities,{path:t.path},{signal:r});return new File([i],i.name,{type:i.type,lastModified:t.modifiedAt})}),enabled:!!(n&&e?.context.get().computerId&&e.capabilities.has(_r)),structuralSharing:!1}}function zm(e,t){let n=e?.app??null,r=Ld(n),i=Qt(),[a,o]=(0,X.useState)(()=>new Set),s=(0,X.useCallback)(e=>{if(!r)return;let t=`${r}:${e}`;o(e=>e.has(t)?e:new Set([...e,t]))},[r]),c=(0,X.useCallback)(e=>{s(e),i.resetQueries({queryKey:Im.file(n,e)})},[n,i,s]),l=Lm(n,t),u=Go(l),d=(0,X.useMemo)(()=>l.enabled?u.data?.pages.flatMap(e=>e.entries)??[]:[],[u.data,l.enabled]),f=(0,X.useCallback)(e=>({files:e.flatMap((e,t)=>e.data?[{path:d[t].path,file:e.data}]:[]),failures:e.flatMap((e,t)=>e.isError?[d[t].name]:[]),loading:e.some(e=>e.isLoading)}),[d]),p=Vo({queries:d.map(e=>Rm(n,e,!!(r&&a.has(`${r}:${e.path}`)))),combine:f});return(0,X.useEffect)(()=>{if(!n)return;let e=Im.all(n),t=Im.listings(n),a=!0;i.invalidateQueries({queryKey:e});let o=()=>{i.cancelQueries({queryKey:e})},s=n.context.subscribe(e=>{e.computerId!==r&&o()}),c=n.lifecycle.subscribe(e=>{(e===`disconnected`||e===`disposing`||e===`disposed`)&&o()}),l=n.capabilities.subscribe(()=>{queueMicrotask(()=>{!a||n.context.get().computerId!==r||i.resetQueries({queryKey:t})})});return()=>{a=!1,s(),c(),l(),o()}},[n,r,e,i]),{entries:d,loadFile:s,retryFile:c,files:p.files,failures:p.failures,error:u.error,loading:u.isFetching||p.loading,hasNextPage:u.hasNextPage,nextPageReady:u.hasNextPage&&!u.isFetching&&!u.error,refresh:()=>{u.refetch({cancelRefetch:!1})},loadMore:()=>{u.isFetching||u.fetchNextPage({cancelRefetch:!1})}}}function Bm(e){return e.replace(/\s/gu,` `).replace(/ +/g,` `).trim()}function Vm(e,t,n){let r=e.replace(/\/$/,``),i=t.lastIndexOf(`.`),a=i>0?t.slice(0,i):t,o=i>0?t.slice(i):``,s=`${r}/${t}`;for(let e=2;n(s);e+=1)s=`${r}/${a} ${String(e)}${o}`;return s}async function Hm(e,t){let n=e.replace(/\/$/,``),r=new Set,i=0;for(;i!==null;){let e=await t(i);if(e.nextOffset!==null&&e.nextOffset<=i)throw Error(`Directory pagination did not advance`);for(let t of e.entries)r.add(`${n}/${t.name}`);i=e.nextOffset}return r}function Um(e,t){let[n,r]=(0,X.useState)([]),i=(0,X.useRef)(new Map),a=(0,X.useRef)(Promise.resolve()),[o,s]=(0,X.useState)(null),c=(0,X.useRef)(new Map),l=(0,X.useRef)(e);l.current=e;let u=(0,X.useRef)(t);u.current=t;let d=(e,t,n)=>{let a=i.current.get(e);a&&i.current.set(e,{...a,status:t,message:n}),r([...i.current.values()])},f=(0,X.useCallback)(async(e,t)=>{let n=()=>t.signal.aborted;if(n()){d(e.id,`cancelled`,`Cancelled before sending`),c.current.delete(e.id);return}let r=e.dimensions;if(!r)try{let t=await Vr(e.file,e.previewUrl);r={width:t.width,height:t.height},e.dimensions=r;let n=i.current.get(e.id);n&&i.current.set(e.id,{...n,dimensions:r})}catch(t){Qr(`decode-upload-image`,t),d(e.id,`error`,`Could not decode this image. No upload was sent.`),c.current.delete(e.id);return}try{if(n()){d(e.id,`cancelled`,`Cancelled before sending`);return}if(e.app.context.get().computerId!==e.computerId){d(e.id,`error`,`Computer changed. Select the original Computer and retry. No upload was sent.`);return}u.current({id:e.id,path:e.path,computerId:e.computerId,app:e.app,width:r.width,height:r.height}),d(e.id,`sending`,`Sending; awaiting Computer completion`),await Lr(e.app.capabilities,{path:e.path,content:e.file.slice()},{signal:t.signal}),d(e.id,`complete`,`Written to Computer`);try{await l.current(e.path,e.app,e.computerId)}catch(t){Qr(`refresh-upload-preview`,t),d(e.id,`complete`,`Written; fresh preview unavailable`)}}catch(t){n()||Qr(`write-computer-upload`,t),d(e.id,n()?`cancelled`:`error`,n()?`Cancelled request; check Computer before retrying`:`Completion not confirmed; check Computer or retry`)}finally{c.current.delete(e.id)}},[]),p=e=>{let t=new AbortController;c.current.set(e.id,t),d(e.id,`queued`,`Queued`),a.current=a.current.then(()=>f(e,t))},m=(0,X.useCallback)(()=>{for(let e of c.current.values())e.abort()},[]);return(0,X.useEffect)(()=>()=>{m();for(let e of i.current.values())URL.revokeObjectURL(e.previewUrl)},[m]),{items:n,error:o,cancelAll:m,add(e,t,n,r=new Set){s(null);let a=[...i.current.values()].reduce((e,t)=>e+t.file.size,0);for(let o of e){if(!o.type.startsWith(`image/`)){s(`Only image files can be uploaded here`);continue}if(i.current.size>=8||a+o.size>67108864){s(`Upload queue limit: eight files and 64 MiB. Remove finished rows before adding more.`);break}let e=n.context.get().computerId;if(!e){s(`Select a Computer before uploading images.`);continue}let c=Vm(t,Bm(o.name),e=>r.has(e)||i.current.has(e)),l={computerId:e,id:c,file:o,previewUrl:URL.createObjectURL(o),app:n,path:c,status:`queued`,message:`Queued`};i.current.set(l.id,l),a+=o.size,p(l)}},cancel(e){c.current.get(e)?.abort()},retry(e){let t=n.find(t=>t.id===e);t&&!c.current.has(e)&&p(t)},remove(e){if(!c.current.has(e)){let t=i.current.get(e);t&&URL.revokeObjectURL(t.previewUrl),i.current.delete(e),r([...i.current.values()])}}}}function Wm(e){return e.source.kind===`computer`?`${e.source.computerId}:${e.source.path}`:e.file.name}function Gm(e){return e.connection.app.ui.openNavigation({computerId:e.computerId,path:e.path})}function Km(e){let[t,n]=(0,X.useState)(!1);return(0,X.useEffect)(()=>{if(n(!1),!e?.capabilities.has(xm))return;let t=!0;return e.capabilities.require(xm).role(wm).then(e=>{t&&n(e!==null)},e=>{Qr(`files-editor-role`,e)}),()=>{t=!1}},[e]),t}function qm(e,t){let n=t.path,r=Ld(e?.app),i=(0,X.useRef)(new Set),a=(0,X.useRef)(0),o=(0,X.useRef)(e);o.current=e;let s=e?.app.capabilities.has(jr)===!0,c=e?.app.capabilities.has(_r)===!0,l=e?.app.capabilities.has(Ur)===!0,u=zm(e,t.galleryPath),[d,f]=(0,X.useState)([]),[p,m]=(0,X.useState)([]),[h,g]=(0,X.useState)([]),[_,v]=(0,X.useState)([]);(0,X.useEffect)(()=>{v([])},[e]);let y=e=>{v(t=>t.some(t=>t.key===e.key)?t.map(t=>t.key===e.key?e:t):[...t,e])},[b,x]=(0,X.useState)(!1),S=(0,X.useMemo)(()=>[...u.error?[`Could not refresh the Media gallery`]:[],...u.failures],[u.error,u.failures]),C=(0,X.useRef)(new WeakMap),w=(0,X.useMemo)(()=>{if(!c||!s)return d.filter(e=>e.kind===`local`);let t=r?u.files.map(({file:t,path:n})=>({kind:`computer`,computerId:r,connection:e,file:t,path:n})):[],i=d.filter(t=>t.kind===`local`||t.computerId===r&&t.connection===e&&t.path.slice(0,t.path.lastIndexOf(`/`))===n?.replace(/\/$/,``));return[...t.filter(e=>!i.some(t=>t.kind===`computer`&&e.kind===`computer`&&t.path===e.path)),...i]},[e,r,n,u.files,d,c,s]),T=(0,X.useCallback)(()=>{a.current+=1;for(let e of i.current)e.abort();i.current.clear()},[]);(0,X.useEffect)(()=>{if(!e)return()=>{T()};let t=e.app.lifecycle.subscribe(e=>{(e===`disconnected`||e===`disposing`||e===`disposed`)&&T()});return()=>{t(),T()}},[e,T]),(0,X.useEffect)(()=>{if(e)return e.app.context.subscribe(e=>{e.computerId!==r&&T()})},[e,r,T]),(0,X.useEffect)(()=>{v([]),f(e=>e.filter(e=>e.kind===`local`))},[r]);let E=(0,X.useCallback)(async(e,t,n)=>{let r=n??t.app.context.get().computerId;if(!r){g([`The selected Computer is unavailable`]);return}if(o.current!==t){g([`Computer selection changed`]);return}if(t.app.context.get().computerId!==r){g([`Computer selection changed before the preview was loaded`]);return}let s=a.current,c=new AbortController;i.current.add(c);try{let n=await br(t.app.capabilities,{path:e},{signal:c.signal});if(c.signal.aborted||s!==a.current)return;v(t=>t.map(t=>t.key===`${r}:${e}`?{...t,previewFile:n}:t)),f(i=>[...i.filter(t=>t.kind!==`computer`||t.path!==e||t.computerId!==r),{kind:`computer`,computerId:r,file:n,path:e,connection:t}])}catch(t){c.signal.aborted||(Qr(`read-computer-file`,t),g([`Could not read ${e}`]),v(t=>t.map(t=>t.key===`${r}:${e}`?{...t,error:`Saved; preview unavailable. Retry loading it.`}:t)))}finally{i.current.delete(c)}},[]),D=(0,X.useCallback)(t=>{let n=d.find(n=>n.kind===`computer`&&n.connection===e&&n.computerId===r&&n.path===t);n?.kind===`computer`?E(t,n.connection,n.computerId):u.retryFile(t)},[d,e,r,E,u.retryFile]),O=(0,X.useRef)(new Set),k=(0,X.useRef)(new Set),A=(0,X.useCallback)(e=>{URL.revokeObjectURL(e),O.current.delete(e)},[]);(0,X.useEffect)(()=>{let e=!0,t=new Set,n=new Map,r=new Set,i=[...w].sort((e,t)=>t.file.lastModified-e.file.lastModified||e.file.name.localeCompare(t.file.name)).map(e=>{let t=URL.createObjectURL(e.file);return O.current.add(t),{source:e,file:e.file,url:t}}),a=i.length;return g(S),x(a>0),a===0&&m([]),i.forEach(({file:o,url:s,source:c},l)=>{let u=C.current.get(o);u||(u=(async()=>{let e=URL.createObjectURL(o);try{let{width:t,height:n}=await Vr(o,e);return{width:t,height:n}}finally{URL.revokeObjectURL(e)}})(),C.current.set(o,u)),u.then(r=>{e&&(n.set(l,{...r,file:o,url:s,source:c}),t.add(s),m(i.flatMap((e,t)=>{let r=n.get(t);return r?[r]:[]})),v(e=>e.map(e=>e.previewFile===o?{...e,resolved:!0,previewFile:void 0,error:void 0}:e)))}).catch(t=>{e&&(Qr(`decode-gallery-image`,t),A(s),r.add(o.name),g([...S,...r]),c.kind===`computer`&&v(e=>e.map(e=>e.key===`${c.computerId}:${c.path}`?{...e,error:`Could not decode the saved image.`}:e)))}).finally(()=>{--a,e&&a===0&&(x(!1),m(i.flatMap((e,t)=>{let r=n.get(t);return r?[r]:[]})))})}),()=>{e=!1;for(let{url:e}of i)t.has(e)||A(e)}},[w,S,A]),(0,X.useEffect)(()=>{let e=new Set(p.map(e=>e.url));for(let t of k.current)e.has(t)||A(t);k.current=e},[p,A]),(0,X.useEffect)(()=>{let e=O.current;return()=>{for(let t of e)URL.revokeObjectURL(t);e.clear()}},[]);let j=Um(async(e,t,n)=>{let r=o.current,i=r?.app===t&&t.context.get().computerId===n?r:null;i&&await E(e,i,n)},e=>{o.current?.app===e.app&&e.app.context.get().computerId===e.computerId&&y({key:`${e.computerId}:${e.path}`,path:e.path,computerId:e.computerId,width:e.width,height:e.height,uploadId:e.id})});return(0,X.useEffect)(()=>{let t=j.cancelAll,n=e?.app.lifecycle.subscribe(e=>{(e===`disposing`||e===`disconnected`||e===`disposed`)&&t()});return()=>{n?.(),t()}},[e,j.cancelAll]),{images:p,failed:h,loading:b,gallery:u,gallerySlots:_,canBrowse:s,canRead:c,canWrite:l,reserveSlot:y,addComputerFile:E,retryFile:D,uploads:j,uploadFiles:async i=>{if(!e||!l||n===null)return;let a=e,s=r,c=await t.ensureCreated();if(c){g([c]);return}if(o.current!==a||a.app.context.get().computerId!==s)return;let u;try{u=await Hm(n,e=>Xr(a.app.capabilities,{path:n,limit:500,offset:e}))}catch(e){Qr(`list-upload-destination`,e),g([`Could not check the Computer folder. No upload was sent.`]);return}o.current===a&&a.app.context.get().computerId===s&&j.add(i,n,a.app,u)},failSlot:(e,t)=>{v(n=>n.map(n=>n.key===e?{...n,error:t}:n))},clearSlotError:e=>{v(t=>t.map(t=>t.key===e?{...t,error:void 0}:t))},removeSlot:e=>{v(t=>t.filter(t=>t.key!==e))}}}function Jm(e){return e.map(e=>e.key)}function Ym(e,t,n){let r=e.indexOf(t);return r<0?null:e[r+n]??null}function Xm(e,t,n){if(e.includes(t))return t;let r=n.indexOf(t);if(r>=0){let t=new Set(e);for(let e=1;e<n.length;e+=1)for(let i of[e,-e]){let e=r+i;if(e<0||e>=n.length)continue;let a=n[e];if(t.has(a))return a}}return e[0]??null}var Zm=(0,X.lazy)(async()=>({default:(await ki(()=>import(`./print-download-button-BxrQk-8w.js`),__vite__mapDeps([0,1,2,3,4]),import.meta.url)).PrintDownloadButton}));function Qm({url:e,path:t,onError:n,autoPlay:r}){let i=(0,X.useRef)(null);return(0,X.useEffect)(()=>{let t=i.current;if(!t)return;let a=!1;return r&&t.play().catch(t=>{a||t instanceof DOMException&&(t.name===`NotAllowedError`||t.name===`AbortError`)||(Qr(`play-print-video`,t),n(e))}),()=>{a=!0,t.pause()}},[e,n,r]),(0,Z.jsx)(`video`,{ref:i,src:e,"aria-label":t,controls:!0,playsInline:!0,preload:`auto`,className:`block max-h-full max-w-full object-contain`,onError:()=>{n(e)}})}function $m({item:e,actualSize:t}){let[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(null),o=e.pending===!0&&!e.onVisible,[s,c]=(0,X.useState)(o);o&&!s&&c(!0);let l=e.pendingLabel??`Loading print…`,u=o?`Not saved`:`Prints can’t show this file`,d=(0,Z.jsx)(`img`,{src:e.url,alt:e.path,decoding:`async`,width:t?e.width:void 0,height:t?e.height:void 0,className:t?`block max-w-none`:`block max-h-full max-w-full object-contain`,onLoad:()=>{r(e.url)},onError:()=>{a(e.url)}},e.url);return(0,Z.jsx)(`div`,{className:`relative flex min-h-0 min-w-0 flex-1 items-center justify-center overflow-hidden`,"data-print-viewer-stage":!0,children:e.error||i===e.url?(0,Z.jsx)(ap,{status:`failed`,className:`h-full w-full`,failure:(0,Z.jsxs)(`div`,{className:`flex max-w-full flex-col items-center gap-sm px-md text-center`,children:[(0,Z.jsx)(`p`,{className:`max-w-full break-words text-sm`,children:e.path}),(0,Z.jsx)(rp,{density:`tile`,message:e.error?`${u}: ${e.error}`:u,onRetry:e.onRetry,onDismiss:e.onDismiss})]})}):Jr(e.path)&&e.url?(0,Z.jsx)(Qm,{url:e.url,path:e.path,onError:a,autoPlay:!s}):e.url?(0,Z.jsxs)(Z.Fragment,{children:[t?(0,Z.jsx)(tm,{className:`h-full w-full`,role:`region`,"aria-label":`Actual-size print`,tabIndex:0,"data-print-viewer-scroll":!0,children:d}):d,n===e.url?null:(0,Z.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center`,children:(0,Z.jsx)(rt,{label:`Loading print`,variant:`bloom`})})]}):(0,Z.jsx)(ap,{status:`generating`,label:l,className:`h-full w-full`,indicator:(0,Z.jsxs)(`div`,{"aria-hidden":`true`,className:`flex max-w-full flex-col items-center gap-sm px-md text-center`,children:[(0,Z.jsx)(rt,{decorative:!0,variant:`bloom`}),(0,Z.jsx)(`p`,{className:`text-sm`,children:l})]})})})}var eh=`(max-width: 640px)`;function th(){return(0,X.useSyncExternalStore)(e=>{let t=globalThis.matchMedia(eh);return t.addEventListener(`change`,e),()=>{t.removeEventListener(`change`,e)}},()=>globalThis.matchMedia(eh).matches,()=>!1)}function nh(e){let[t,n]=(0,X.useState)(!1),[r,i]=(0,X.useState)(!1);return{pending:t,failed:r,open:()=>{e&&(n(!0),i(!1),Gm(e).catch(e=>{Qr(`open-print-in-inkcap`,e),i(!0)}).finally(()=>{n(!1)}))}}}function rh({source:e}){return(0,Z.jsxs)(`p`,{role:`alert`,className:`text-sm`,children:[`Could not open `,e.path,` in Inkcap.`]})}function ih({source:e,app:t,inkcap:n,phone:r}){let i=e.kind===`computer`&&n?e:null,a=nh(i);return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(X.Suspense,{fallback:null,children:(0,Z.jsx)(Zm,{source:e,app:t,presentation:r?`menu`:`key`,menuItems:i?(0,Z.jsx)(Gr,{disabled:a.pending,onSelect:a.open,children:`Open in Inkcap`}):void 0})}),i&&!r?(0,Z.jsx)(wt,{label:`Open in Inkcap`,icon:(0,Z.jsx)(om,{}),disabled:a.pending,onClick:a.open}):null,i&&a.failed?(0,Z.jsx)(rh,{source:i}):null]})}function ah({items:e,images:t,viewerKey:n,app:r,onNavigate:i,onClose:a,renderInfo:o}){let s=(0,X.useRef)(null),c=Km(r),l=th(),u=Jm(e),d=(0,X.useRef)(u),f=n===null?null:Xm(u,n,d.current);(0,X.useEffect)(()=>{d.current=u,n!==null&&f!==n&&(f===null?a(n):i(f))},[u,f,n,a,i]),(0,X.useEffect)(()=>{if(f===null)return;let t=e.findIndex(e=>e.key===f);for(let n of e.slice(Math.max(0,t-1),t+2))n.onVisible?.()},[e,f]);let[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(null);(0,X.useEffect)(()=>{g(null)},[f]),(0,X.useEffect)(()=>{m(null)},[n]);let _=e.find(e=>e.key===f),v=t.find(e=>Wm(e)===f);if(!_||f===null)return null;let y=Ym(u,f,-1),b=Ym(u,f,1),x=_.path.split(`/`).at(-1)??_.path,S=()=>{a(f)},C=e=>{e!==null&&i(e)};return(0,Z.jsx)(Lf,{open:!0,onOpenChange:e=>{e||S()},children:(0,Z.jsxs)(zf,{children:[(0,Z.jsx)(Bf,{}),(0,Z.jsxs)(Vf,{ref:s,size:`fill`,initialFocus:s,finalFocus:!1,className:`flex min-h-0 flex-col gap-sm`,onKeyDown:e=>{e.altKey||e.ctrlKey||e.metaKey||e.target instanceof HTMLElement&&e.target.closest(`input, textarea, select, video, [data-print-viewer-scroll], [contenteditable=true]`)||(e.key===`ArrowLeft`||e.key===`ArrowRight`?(e.preventDefault(),C(e.key===`ArrowLeft`?y:b)):e.key.toLowerCase()===`i`&&v&&(e.preventDefault(),m(p===f?null:f)))},children:[(0,Z.jsx)(pa,{className:`prints-viewer-frame`,children:(0,Z.jsxs)(`div`,{className:`flex min-h-0 min-w-0 flex-1 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`prints-viewer-caption`,"data-print-viewer-caption":!0,children:[(0,Z.jsx)(Gf,{className:`prints-viewer-caption-name truncate text-xs font-normal`,children:x}),(0,Z.jsxs)(`span`,{className:`prints-viewer-caption-position`,"aria-live":`polite`,"aria-atomic":`true`,children:[(0,Z.jsxs)(`span`,{className:`sr-only`,children:[x,`, `]}),u.indexOf(f)+1,` of `,u.length]})]}),(0,Z.jsxs)(`div`,{className:`@container relative flex min-h-0 min-w-0 flex-1`,children:[(0,Z.jsx)($m,{item:_,actualSize:h===f},f),p===f&&v?o(v,()=>{m(null)}):null]})]})}),(0,Z.jsxs)(`div`,{className:`prints-viewer-actions`,children:[(0,Z.jsx)(ln,{size:`default`,iconSize:`md`,"aria-label":`Previous print`,title:`Previous print (Left arrow)`,"aria-keyshortcuts":`ArrowLeft`,icon:(0,Z.jsx)(nm,{}),disabled:y===null,onClick:()=>{C(y)}}),(0,Z.jsx)(ln,{size:`default`,iconSize:`md`,"aria-label":`Next print`,title:`Next print (Right arrow)`,"aria-keyshortcuts":`ArrowRight`,icon:(0,Z.jsx)(rm,{}),disabled:b===null,onClick:()=>{C(b)}}),(0,Z.jsx)(ln,{size:`default`,iconSize:`md`,"aria-label":`Image info`,title:`Image info (I)`,"aria-keyshortcuts":`i`,"aria-expanded":p===f,icon:(0,Z.jsx)(fm,{}),disabled:!v,onClick:()=>{m(p===f?null:f)}}),Jr(_.path)?null:(0,Z.jsx)(ln,{size:`default`,iconSize:`md`,"aria-label":`Actual size`,title:`Actual size`,"aria-pressed":h===f,active:h===f,icon:(0,Z.jsx)(pm,{}),disabled:!_.url||!!_.error,onClick:()=>{g(h===f?null:f)}}),v?(0,Z.jsx)(ih,{source:v.source,app:r,inkcap:c,phone:l},`${f}\n${v.url}`):null,(0,Z.jsx)(ln,{size:`default`,iconSize:`md`,"aria-label":`Close viewer`,title:`Close viewer (Escape)`,icon:(0,Z.jsx)(Xi,{}),onClick:S})]})]})]})})}var oh=e=>Tn.pipe(h(On(1)),h(le(e))),sh=Re.pipe(h(I()),h(Se(Number.isSafeInteger,{message:`Expected a safe integer`}))),ch=sh.pipe(h(v(0))),lh=sh.pipe(h(E(0))),uh=Ue({bytes:ch,costMilliunits:lh,destination:Ue({computerId:oh(256),path:oh(4096)}),format:Wt([`png`,`jpeg`,`gif`,`webp`,`mp4`]),height:ch,model:oh(256),width:ch}),dh=Ue({operation:at(`complete-generation`),reference:ht,result:uh,derivedFrom:w(oh(256)),references:w(qe(lt(oh(256))))}),fh=Ue({prompt:jt,references:Ze.pipe(h(E(0)))}),ph=Ue({reason:Wt([...Bt,`UNKNOWN`]),message:jt.pipe(h(le(512)))}),mh=Ue({reference:ht,input:Xt,typed:fh,style:w(Ni),characters:w(qe(ma)),failure:w(ph)});vn([Ue({operation:at(`remember-generation`),record:mh}),Ue({operation:at(`fail-generation`),reference:ht,failure:ph}),Ue({operation:at(`forget-generation`),reference:ht}),Ue({operation:at(`list-generations`),after:lt(Tn)})]);function hh(e){return{reference:e.reference,input:tn(e.input),typed:e.typed,style:e.style,characters:e.characters,failure:e.failure}}async function gh(e,t){let n=hh(o(mh,{onExcessProperty:`error`})(t)),r=hh(o(mh,{onExcessProperty:`error`})(await e.require(qi).request(JSON.stringify({operation:`remember-generation`,record:n}))));if(JSON.stringify(r)!==JSON.stringify(n))throw new J(`Prints did not confirm the original generation command`,{code:`PROTOCOL`,retryable:!1});return r}async function _h(e,t,n){o(mh,{onExcessProperty:`error`})(await e.require(qi).request(JSON.stringify({operation:`fail-generation`,reference:t,failure:n})))}async function vh(e,t){o(Ue({removed:Et}))(await e.require(qi).request(JSON.stringify({operation:`forget-generation`,reference:t})))}async function yh(e,t=null){let n=o(Ue({records:qe(mh),next:lt(Tn)}),{onExcessProperty:`error`})(await e.require(qi).request(JSON.stringify({operation:`list-generations`,after:t})));return{records:n.records.map(hh),next:n.next}}async function bh(e,t,n){let r=o(dh,{onExcessProperty:`error`})({operation:`complete-generation`,reference:t,result:n}),i=o(Ue({printId:Tn,computerId:Tn}))(await e.require(qi).request(JSON.stringify(r)));if(i.printId!==t.requestId||i.computerId!==t.computerId)throw new J(`Prints did not confirm the saved generation`,{code:`PROTOCOL`,retryable:!1})}var xh=V(Ue({reference:ht}));function Sh({connection:e,folder:t,effects:n,styles:r,characters:i}){let a=e?.app??null,o=Ld(a),s=(0,X.useRef)(e);s.current=e;let c=(0,X.useRef)(n);c.current=n;let l=Qt(),u=ha.of(a,`prints`,`generation`),d=[...u,`recovery`],f=la(fa(a)),p=f.isError?void 0:f.data,m=p?.models??[],h=a?.capabilities.has(Pt)===!0,g=p?.canGenerate??!1,_=f.error?rn(f.error).message:p?.models.length===0?`The granted Media model registry is empty.`:null,v=Go({queryKey:d,enabled:a!==null&&o!==null,initialPageParam:null,queryFn:async({pageParam:e,signal:t})=>{if(!a)throw new J(`Prints disconnected`,{code:`DISCONNECTED`,retryable:!0});if(a.context.get().computerId!==o)throw new J(`Computer selection changed`,{code:`SELECTION_CHANGED`,retryable:!1});let n=await yh(a.capabilities,e);return t.throwIfAborted(),n},getNextPageParam:e=>e.next}),y=(0,X.useMemo)(()=>Array.from(new Map(v.data?.pages.flatMap(e=>e.records).map(e=>[e.reference.requestId,e])??[]).values()),[v.data]),b=(0,X.useRef)(new Map),x=(0,X.useRef)(new Set),S=(0,X.useRef)(0),C=(0,X.useRef)(null),[w,T]=(0,X.useState)(null),[E,D]=(0,X.useState)(null),O=e=>{T(e),c.current.notifyFailure(e.message)},k=e=>{D(e),c.current.notifyFailure(e)},A=(0,X.useRef)(null);(0,X.useEffect)(()=>{A.current!==v.error&&(A.current=v.error,v.error&&c.current.notifyFailure(rn(v.error).message))},[v.error]);let j=e=>s.current===e.connection&&e.connection.app.context.get().computerId===e.reference.computerId,M=(e,t,n)=>{l.setQueryData(e,e=>e&&{...e,pages:e.pages.map(e=>({...e,records:e.records.map(e=>e.reference.requestId===t?{...e,failure:n}:e)}))})},N=(e,t)=>{l.setQueryData(e,e=>e&&{...e,pages:e.pages.map(e=>({...e,records:e.records.filter(e=>e.reference.requestId!==t)}))})},P=ve({mutationKey:[...u,`run`],mutationFn:async e=>{e.controller.signal.throwIfAborted();let t=hh({reference:e.reference,input:e.input,typed:e.typed,style:e.style,characters:e.characters});await gh(e.connection.app.capabilities,t),M(e.recoveryKey,e.reference.requestId,void 0),e.controller.signal.throwIfAborted();let n=await e.session.restoreAttempt(e.reference),r;try{r=await n.generate(t.input,{signal:e.controller.signal})}finally{n[Symbol.dispose]()}return await bh(e.connection.app.capabilities,t.reference,r),{input:e.input,result:r}},onMutate:e=>{if(!j(e)||e.controller.signal.aborted)return;let t=xi(e.session.models,e.input.settings.model),n={key:`${e.reference.computerId}:${e.input.destination.path}`,computerId:e.reference.computerId,path:e.input.destination.path,width:e.draft.width,height:e.draft.height,pendingLabel:pi(t)};t?.kind===`video`&&(n.startedAt=Date.now(),n.resumed=e.resumed===!0),c.current.reserve(n)},onSuccess:(e,t)=>{N(t.recoveryKey,t.reference.requestId),C.current?.reference.requestId===t.reference.requestId&&(C.current=null),!(!j(t)||t.controller.signal.aborted)&&c.current.saved(e,t.connection)},onError:(e,n)=>{if(Qr(`generate-media`,e),n.controller.signal.aborted)return;let r=Ai(e);_h(n.connection.app.capabilities,n.reference,r).catch(e=>{Qr(`fail-generation`,e)}),j(n)&&(M(n.recoveryKey,n.reference.requestId,r),t.recheck(),c.current.failed(`${n.reference.computerId}:${n.input.destination.path}`,r.message))},onSettled:(e,t,n)=>{b.current.get(n.reference.requestId)===n.controller&&b.current.delete(n.reference.requestId)}}),F=ve({mutationKey:[...u,`discard`],mutationFn:async e=>{await vh(e.connection.app.capabilities,e.reference)},onSuccess:(e,t)=>{N(t.recoveryKey,t.reference.requestId),C.current?.reference.requestId===t.reference.requestId&&(C.current=null)},onError:(e,t)=>{j(t)&&k(rn(e).message)},onSettled:(e,t,n)=>{b.current.get(n.reference.requestId)===n.controller&&b.current.delete(n.reference.requestId)}}),I=Wo({filters:{mutationKey:u,status:`pending`},select:e=>Dt(xh(e.state.variables))?.reference.requestId}),ee=new Set(I.filter(e=>e!==void 0));(0,X.useEffect)(()=>{x.current.clear(),T(null),D(null),C.current=null;let e=ha.of(a,`prints`,`generation`,`recovery`),t=a?.capabilities.subscribe(()=>{queueMicrotask(()=>{l.resetQueries({queryKey:e,exact:!0})})}),n=()=>{S.current+=1;for(let e of b.current.values())e.abort();b.current.clear(),l.cancelQueries({queryKey:e})},r=a?.context.subscribe(e=>{e.computerId!==o&&n()}),i=a?.lifecycle.subscribe(e=>{(e===`disposing`||e===`disposed`||e===`disconnected`)&&n()});return()=>{r?.(),i?.(),t?.(),n()}},[a,o,e,l]);let L=e=>{let t=e.reference.requestId;if(b.current.has(t))return!1;if(!j(e))return k(`Select the original Computer to retry this generation.`),!1;if(p?.computerId!==e.reference.computerId)return k(`Media access is unavailable for the original Computer.`),!1;let n=new AbortController;return b.current.set(t,n),C.current=e,T(null),D(null),S.current+=1,P.mutate({...e,session:p,controller:n,ticket:S.current,recoveryKey:d}),!0};(0,X.useEffect)(()=>{if(!(!e||!p||!v.isSuccess))for(let t of y){let n=t.reference.requestId;x.current.has(n)||t.reference.computerId!==o||xi(p.models,t.input.settings.model)?.kind!==`video`||L({connection:e,...t,resumed:!0,draft:{...t.input.settings,references:t.input.settings.references??[],destination:t.input.destination.path}})&&x.current.add(n)}},[e,o,p,v.isSuccess,y]);let R=async n=>{if(!e?.app.capabilities.has(Ur)||!g)return!1;if(t.path===null)return t.setEditing(!0),!1;C.current=null;let a=xi(m,n.model);if(a===void 0)return O({kind:`error`,mediaKind:null,message:`Choose a model from the granted registry.`}),!1;let c=Vi({prompt:n.prompt,saved:i,references:n.references,computerId:o,model:{label:a.label,maxReferences:a.input.maxReferences}});if(c.kind===`refused`)return O({kind:`error`,mediaKind:a.kind,message:c.message}),!1;let l=Bi({...n,references:c.references},a);if(l)return O({kind:`error`,mediaKind:a.kind,message:l}),!1;let u=n.style===void 0?void 0:r.find(e=>e.name===n.style);if(n.style!==void 0&&u===void 0)return O({kind:`error`,mediaKind:a.kind,message:`The "${n.style}" style no longer exists. Pick another or none.`}),!1;let d=c.characters.map(e=>e.name),f=Gi(u?.text,c.prompt),_=ji(f,mi(a),u?.name,d);if(_!==void 0)return O({kind:`error`,mediaKind:a.kind,message:_}),!1;if(!h||!p)return T(null),!1;let v=e,y=v.app.context.get().computerId,b=S.current,x={...n,prompt:f,references:c.references,destination:Ti(n,t.path,a)},w=ja(x,a),E;try{let e=await t.ensureCreated();if(e)return O({kind:`error`,mediaKind:a.kind,message:e}),!1;if(S.current!==b||s.current!==v||v.app.context.get().computerId!==y)return!1;let n=await p.createAttempt();E=n.reference,n[Symbol.dispose]()}catch(e){return S.current===b&&s.current===v&&v.app.context.get().computerId===y&&O({kind:`error`,mediaKind:a.kind,...Oi(e)}),!1}return S.current!==b||s.current!==v||v.app.context.get().computerId!==y?!1:L({connection:v,reference:E,input:w,draft:x,typed:{prompt:n.prompt.trim(),references:n.references.length},style:u?.name,characters:d})},te=P.variables;return{state:w??(te&&j(te)&&te.ticket===S.current?P.isPending?{kind:`pending`,draft:te.draft}:P.isError?{kind:`error`,mediaKind:xi(te.session.models,te.input.settings.model)?.kind??null,...Oi(P.error)}:{kind:`completed`,record:P.data}:null)??(!e||!h||o===null?{kind:`unavailable`,reason:`Image creation is unavailable for this Computer right now.`}:_?{kind:`unavailable`,reason:_}:p?{kind:`ready`}:{kind:`loading`}),models:m,modelsLoading:f.isFetching,modelsError:_,canGenerate:g,mediaCapability:h,retryModels:()=>{f.refetch()},submit:R,isRunning:()=>b.current.size>0,activeGenerations:ee,pendingGenerations:y,recoveryError:E??(v.error?rn(v.error).message:null),reportRecoveryError:e=>{k(rn(e).message)},hasMore:v.hasNextPage,loadMore:()=>{v.isFetching||v.fetchNextPage()},resume:t=>{if(!e||p?.computerId!==t.reference.computerId){k(`Select the original Computer to retry this generation.`);return}L({connection:e,...t,draft:{...t.input.settings,references:t.input.settings.references??[],destination:t.input.destination.path}})},discard:t=>{if(!e||b.current.has(t.reference.requestId))return;let n=new AbortController;b.current.set(t.reference.requestId,n),F.mutate({...t,connection:e,controller:n,draft:{...t.input.settings,references:t.input.settings.references??[]},recoveryKey:d})},retryPath:e=>{let t=C.current;return t?.input.destination.path!==e||!j(t)?!1:(L(t),!0)},retry:C.current&&j(C.current)?()=>{C.current&&L(C.current)}:void 0,failedPrompt:C.current?.typed.prompt,dismissFailed:()=>{let e=C.current;if(!e||b.current.has(e.reference.requestId)){P.reset();return}C.current=null,P.reset();let t=new AbortController;b.current.set(e.reference.requestId,t),F.mutate({...e,controller:t,recoveryKey:d})},errorKey:`generation:${C.current?.reference.requestId??`draft`}:${String(S.current)}`}}function Ch({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0){n=e.nextSub;continue}for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}while(!0)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(!0)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function wh(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}var Th=[],Eh=0,{link:Dh,unlink:Oh,propagate:kh,checkDirty:Ah,shallowPropagate:jh}=Ch({update(e){return e._update()},notify(e){Th[Nh++]=e,e.flags&=-3},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=17,Lh(e))}}),Mh=0,Nh=0,Ph,Fh=0;function Ih(e){try{++Fh,e()}finally{--Fh||Rh()}}function Lh(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=Oh(n,e)}function Rh(){if(!(Fh>0)){for(;Mh<Nh;){let e=Th[Mh];Th[Mh++]=void 0,e.notify()}Mh=0,Nh=0}}function zh(e,t){let n=typeof e==`function`,r=e,i={_snapshot:n?void 0:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:+!n,get(){return Ph!==void 0&&Dh(i,Ph,Eh),i._snapshot},subscribe(e){let t=wh(e),n={current:!1},r=Bh(()=>{i.get(),n.current?t.next?.(i._snapshot):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=Ph,o=t?.compare??Object.is;if(n)Ph=i,++Eh,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=5);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{Ph=a,n&&(i.flags&=-5),Lh(i)}}};return n?(i.flags=17,i.get=function(){let e=i.flags;if(e&16||e&32&&Ah(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&jh(e)}}else e&32&&(i.flags=e&-33);return Ph!==void 0&&Dh(i,Ph,Eh),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(kh(e),jh(e),Rh())}},i}function Bh(e){let t=()=>{let t=Ph;Ph=n,++Eh,n.depsTail=void 0,n.flags=6;try{return e()}finally{Ph=t,n.flags&=-5,Lh(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:6,notify(){let e=this.flags;e&16||e&32&&Ah(this.deps,this)?t():this.flags=2},stop(){this.flags=0,this.depsTail=void 0,Lh(this)}};return t(),n}var Vh=class{constructor(e,t){this.atom=zh(e),this.get=this.get.bind(this),this.setState=this.setState.bind(this),this.subscribe=this.subscribe.bind(this),t&&(this.actions=t(this))}setState(e){this.atom.set(e)}get state(){return this.atom.get()}get(){return this.state}subscribe(e){return this.atom.subscribe(wh(e))}},Hh=class{constructor(e){this.atom=zh(e)}get state(){return this.atom.get()}get(){return this.state}subscribe(e){return this.atom.subscribe(wh(e))}};function Uh(e,t){return typeof e==`function`?new Hh(e):t?new Vh(e,t):new Vh(e)}var Wh=class{constructor(e,t){this.fn=e,this.options=t,this.lastExecutionTime=0,this.isPending=!1,this.maybeExecute=(...e)=>{let t=Date.now()-this.lastExecutionTime;if(this.options.leading&&t>=this.options.wait)this.execute(...e);else if(this.lastArgs=e,!this.timeoutId&&this.options.trailing){let e=this.options.wait-t;this.isPending=!0,this.timeoutId=setTimeout(()=>{this.lastArgs!==void 0&&this.execute(...this.lastArgs)},e)}},this.execute=(...e)=>{this.fn(...e),this.options.onExecute?.(e,this),this.lastExecutionTime=Date.now(),this.clearTimeout(),this.lastArgs=void 0,this.isPending=!1},this.flush=()=>{this.isPending&&this.lastArgs&&this.execute(...this.lastArgs)},this.cancel=()=>{this.clearTimeout(),this.lastArgs=void 0,this.isPending=!1},this.clearTimeout=()=>{this.timeoutId&&=(clearTimeout(this.timeoutId),void 0)},this.options.leading===void 0&&this.options.trailing===void 0&&(this.options.leading=!0,this.options.trailing=!0)}};function Gh(e,t){return new Wh(e,t).maybeExecute}var Kh=class{#e=!0;#t;#n;#r;#i;#a;#o;#s;#c=0;#l=5;#u=!1;#d=!1;#f=null;#p=()=>{this.debugLog(`Connected to event bus`),this.#a=!0,this.#u=!1,this.debugLog(`Emitting queued events`,this.#i),this.#i.forEach(e=>this.emitEventToBus(e)),this.#i=[],this.stopConnectLoop(),this.#n().removeEventListener(`tanstack-connect-success`,this.#p)};#m=()=>{if(this.#c<this.#l){this.#c++,this.dispatchCustomEvent(`tanstack-connect`,{});return}this.#n().removeEventListener(`tanstack-connect`,this.#m),this.#d=!0,this.debugLog(`Max retries reached, giving up on connection`),this.stopConnectLoop()};#h=()=>{this.#u||(this.#u=!0,this.#n().addEventListener(`tanstack-connect-success`,this.#p),this.#m())};constructor({pluginId:e,debug:t=!1,enabled:n=!0,reconnectEveryMs:r=300}){this.#t=e,this.#e=n,this.#n=this.getGlobalTarget,this.#r=t,this.debugLog(` Initializing event subscription for plugin`,this.#t),this.#i=[],this.#a=!1,this.#d=!1,this.#o=null,this.#s=r}startConnectLoop(){this.#o!==null||this.#a||(this.debugLog(`Starting connect loop (every ${this.#s}ms)`),this.#o=setInterval(this.#m,this.#s))}stopConnectLoop(){this.#u=!1,this.#o!==null&&(clearInterval(this.#o),this.#o=null,this.#i=[],this.debugLog(`Stopped connect loop`))}debugLog(...e){this.#r&&console.log(`🌴 [tanstack-devtools:${this.#t}-plugin]`,...e)}getGlobalTarget(){if(typeof globalThis<`u`&&globalThis.__TANSTACK_EVENT_TARGET__)return this.debugLog(`Using global event target`),globalThis.__TANSTACK_EVENT_TARGET__;if(typeof window<`u`&&window.addEventListener!==void 0)return this.debugLog(`Using window as event target`),window;let e=typeof EventTarget<`u`?new EventTarget:void 0;return e===void 0||e.addEventListener===void 0?(this.debugLog(`No event mechanism available, running in non-web environment`),{addEventListener:()=>{},removeEventListener:()=>{},dispatchEvent:()=>!1}):(this.debugLog(`Using new EventTarget as fallback`),e)}getPluginId(){return this.#t}dispatchCustomEventShim(e,t){try{let n=new Event(e,{detail:t});this.#n().dispatchEvent(n)}catch{this.debugLog(`Failed to dispatch shim event`)}}dispatchCustomEvent(e,t){try{this.#n().dispatchEvent(new CustomEvent(e,{detail:t}))}catch{this.dispatchCustomEventShim(e,t)}}emitEventToBus(e){this.debugLog(`Emitting event to client bus`,e),this.dispatchCustomEvent(`tanstack-dispatch-event`,e)}createEventPayload(e,t){return{type:`${this.#t}:${e}`,payload:t,pluginId:this.#t}}emit(e,t){if(!this.#e){this.debugLog(`Event bus client is disabled, not emitting event`,e,t);return}if(this.#f&&(this.debugLog(`Emitting event to internal event target`,e,t),this.#f.dispatchEvent(new CustomEvent(`${this.#t}:${e}`,{detail:this.createEventPayload(e,t)}))),this.#d){this.debugLog(`Previously failed to connect, not emitting to bus`);return}if(!this.#a){this.debugLog(`Bus not available, will be pushed as soon as connected`),this.#i.push(this.createEventPayload(e,t)),typeof CustomEvent<`u`&&!this.#u&&(this.#h(),this.startConnectLoop());return}return this.emitEventToBus(this.createEventPayload(e,t))}on(e,t,n){let r=n?.withEventTarget??!1,i=`${this.#t}:${e}`;if(r&&(this.#f||=new EventTarget,this.#f.addEventListener(i,e=>{t(e.detail)})),!this.#e)return this.debugLog(`Event bus client is disabled, not registering event`,i),()=>{};let a=e=>{this.debugLog(`Received event from bus`,e.detail),t(e.detail)};return this.#n().addEventListener(i,a),this.debugLog(`Registered event to bus`,i),()=>{r&&this.#f?.removeEventListener(i,a),this.#n().removeEventListener(i,a)}}onAll(e){if(!this.#e)return this.debugLog(`Event bus client is disabled, not registering event`),()=>{};let t=t=>{let n=t.detail;e(n)};return this.#n().addEventListener(`tanstack-devtools-global`,t),()=>this.#n().removeEventListener(`tanstack-devtools-global`,t)}onAllPluginEvents(e){if(!this.#e)return this.debugLog(`Event bus client is disabled, not registering event`),()=>{};let t=t=>{let n=t.detail;this.#t&&n.pluginId!==this.#t||e(n)};return this.#n().addEventListener(`tanstack-devtools-global`,t),()=>this.#n().removeEventListener(`tanstack-devtools-global`,t)}},qh=new class extends Kh{constructor(){super({pluginId:`form-devtools`,reconnectEveryMs:1e3})}};function Jh(e,t){return typeof e==`function`?e(t):e}function Yh(e,t){return rg(t).reduce((e,t)=>{if(e===null)return null;if(e!==void 0)return e[t]},e)}function Xh(e,t,n){let r=rg(t);function i(e){if(!r.length)return Jh(n,e);let t=r.shift();if(typeof t==`string`||typeof t==`number`&&!Array.isArray(e))return typeof e==`object`?(e===null&&(e={}),{...e,[t]:i(e[t])}):{[t]:i()};if(Array.isArray(e)&&typeof t==`number`){let n=e.slice(0,t);return[...n.length?n:Array(t),i(e[t]),...e.slice(t+1)]}return[...Array(t),i()]}return i(e)}function Zh(e,t){let n=rg(t);function r(e){if(!e)return;if(n.length===1){let t=n[0];if(Array.isArray(e)&&typeof t==`number`)return e.filter((e,n)=>n!==t);let{[t]:r,...i}=e;return i}let t=n.shift();if((typeof t==`string`||typeof t==`number`&&!Array.isArray(e))&&typeof e==`object`)return{...e,[t]:r(e[t])};if(typeof t==`number`&&Array.isArray(e)){if(t>=e.length)return e;let n=e.slice(0,t);return[...n.length?n:Array(t),r(e[t]),...e.slice(t+1)]}throw Error(`It seems we have created an infinite loop in deleteBy. `)}return r(e)}var Qh=46,$h=91,eg=93,tg=48,ng=57;function rg(e){if(Array.isArray(e))return[...e];if(typeof e!=`string`)throw Error(`Path must be a string.`);let t=e.length,n=[],r=+(t>0&&e.charCodeAt(0)===$h),i=!0,a=-1;for(let o=r;o<=t;o++){let s=o<t?e.charCodeAt(o):-1;if(o===t||s===Qh||s===$h||s===eg){let t=o-r;if(t>0){let a=i&&(t===1||e.charCodeAt(r)!==tg),s=e.slice(r,o);if(a){let e=parseInt(s,10);t<=15||String(e)===s?n.push(e):n.push(s)}else n.push(s)}else a!==eg&&(a!==-1||s!==eg)&&(a!==s||s!==Qh&&s!==$h)&&n.push(``);r=o+1,i=!0}else(s<tg||s>ng)&&(i=!1);a=s}return n.length||n.push(``),n}function ig(e){return!(Array.isArray(e)&&e.length===0)}function ag(e,t){return t.validationLogic({form:t.form,group:t.group,validators:t.validators,event:{type:e,fieldName:t.fieldName,async:!1},runValidation:e=>e.validators.filter(Boolean).map(e=>({cause:e.cause,validate:e.fn}))})}function og(e,t){let{asyncDebounceMs:n}=t,{onBlurAsyncDebounceMs:r,onChangeAsyncDebounceMs:i,onDynamicAsyncDebounceMs:a}=t.validators||{},o=n??0;return t.validationLogic({form:t.form,group:t.group,validators:t.validators,event:{type:e,fieldName:t.fieldName,async:!0},runValidation:t=>t.validators.filter(Boolean).map(t=>{let n=t?.cause||e,s=o;switch(n){case`change`:s=i??o;break;case`blur`:s=r??o;break;case`dynamic`:s=a??o;break;case`submit`:s=0}return e===`submit`&&(s=0),{cause:n,validate:t.fn,debounceMs:s}})})}var sg=e=>!!e&&typeof e==`object`&&`fields`in e;function cg(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!t.has(n)||!Object.is(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length||n.length===0&&!Array.isArray(e)&&!Array.isArray(t)&&(Object.getPrototypeOf(e)!==Object.prototype||Object.getPrototypeOf(t)!==Object.prototype))return!1;for(let i of n)if(!r.includes(i)||!cg(e[i],t[i]))return!1;return!0}var lg=({newFormValidatorError:e,isPreviousErrorFromFormValidator:t,previousErrorValue:n})=>e?{newErrorValue:e,newSource:`form`}:t?{newErrorValue:void 0,newSource:void 0}:n?{newErrorValue:n,newSource:`field`}:{newErrorValue:void 0,newSource:void 0},ug=({formLevelError:e,fieldLevelError:t})=>t?{newErrorValue:t,newSource:`field`}:e?{newErrorValue:e,newSource:`form`}:{newErrorValue:void 0,newSource:void 0};function dg(e,t){return e==null?t:{...e,...t}}for(var fg=256,pg=[],mg;fg--;)pg[fg]=(fg+256).toString(16).substring(1);function hg(){let e=0,t,n=``;if(!mg||fg+16>256){for(mg=Array(256),e=256;e--;)mg[e]=256*Math.random()|0;e=0,fg=0}for(;e<16;e++)t=mg[fg+e],n+=e===6?pg[t&15|64]:e===8?pg[t&63|128]:pg[t],e&1&&e>1&&e<11&&(n+=`-`);return fg++,n}var gg=Gh(e=>qh.emit(`form-state`,{id:e.formId,state:e.store.state}),{wait:300});function _g(e){if(typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e)){let t=[];for(let n=0;n<e.length;n++)t[n]=_g(e[n]);return t}if(e instanceof Map){let t=new Map;return e.forEach((e,n)=>{t.set(n,_g(e))}),t}if(e instanceof Set){let t=new Set;return e.forEach(e=>{t.add(_g(e))}),t}let t={};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=_g(e[n]));return t}function vg(e,t){return t===e||t.startsWith(`${e}.`)||t.startsWith(`${e}[`)}var yg=e=>{if(!e.validators)return e.runValidation({validators:[],form:e.form});let t=e.event.async,n=t?void 0:{fn:e.validators.onMount,cause:`mount`},r={fn:t?e.validators.onChangeAsync:e.validators.onChange,cause:`change`},i={fn:t?e.validators.onBlurAsync:e.validators.onBlur,cause:`blur`},a={fn:t?e.validators.onSubmitAsync:e.validators.onSubmit,cause:`submit`},o=t?void 0:{fn:()=>void 0,cause:`server`};switch(e.event.type){case`mount`:return e.runValidation({validators:[n],form:e.form});case`submit`:return e.runValidation({validators:[r,i,a,o],form:e.form});case`server`:return e.runValidation({validators:[],form:e.form});case`blur`:return e.runValidation({validators:[i,o],form:e.form});case`change`:return e.runValidation({validators:[r,o],form:e.form});default:throw Error(`Unknown validation event type: ${e.event.type}`)}};function bg(e,t){let n=new Map;for(let r of e){let e=r.path??[],i=t,a=``;for(let t=0;t<e.length;t++){let n=e[t];if(n===void 0)continue;let r=typeof n==`object`?n.key:n,o=Number(r);a+=Array.isArray(i)&&!Number.isNaN(o)?`[${o}]`:(t>0?`.`:``)+String(r),i=typeof i==`object`&&i?i[r]:void 0}n.set(a,(n.get(a)??[]).concat(r))}return Object.fromEntries(n)}var xg=(e,t)=>{let n=bg(e,t);return{form:n,fields:n}},Sg={validate({value:e,validationSource:t},n){let r=n[`~standard`].validate(e);if(r instanceof Promise)throw Error(`async function passed to sync validator`);if(r.issues)return t===`field`?r.issues:xg(r.issues,e)},async validateAsync({value:e,validationSource:t},n){let r=await n[`~standard`].validate(e);if(r.issues)return t===`field`?r.issues:xg(r.issues,e)}},Cg=e=>!!e&&`~standard`in e,wg={isValidating:!1,isTouched:!1,isBlurred:!1,isDirty:!1,isPristine:!0,isValid:!0,isDefaultValue:!0,errors:[],errorMap:{},errorSourceMap:{},_arrayVersion:0,_pendingValidationsCount:0};function Tg(e){function t(t){let n=e.getFieldMeta(t)??wg;e.setFieldMeta(t,{...n,_arrayVersion:(n._arrayVersion||0)+1})}function n(n,r,i){t(n);let a=s(n,r,`move`,i),c=Math.min(r,i),u=Math.max(r,i);for(let e=c;e<=u;e++)a.push(o(n,e));let d=Object.keys(e.fieldInfo).reduce((t,i)=>(i.startsWith(o(n,r))&&t.set(i,e.getFieldMeta(i)),t),new Map);l(a,r<i?`up`:`down`),Object.keys(e.fieldInfo).filter(e=>e.startsWith(o(n,i))).forEach(t=>{let a=t.replace(o(n,i),o(n,r)),s=d.get(a);s&&e.setFieldMeta(t,s)})}function r(e,n){t(e),l(s(e,n,`remove`),`up`)}function i(n,r,i){t(n),s(n,r,`swap`,i).forEach(t=>{if(!t.toString().startsWith(o(n,r)))return;let a=t.toString().replace(o(n,r),o(n,i)),[s,c]=[e.getFieldMeta(t),e.getFieldMeta(a)];s&&e.setFieldMeta(a,s),c&&e.setFieldMeta(t,c)})}function a(n,r){t(n);let i=s(n,r,`insert`);l(i,`down`),i.forEach(t=>{t.toString().startsWith(o(n,r))&&e.setFieldMeta(t,u())})}function o(e,t){return`${e}[${t}]`}function s(t,n,r,i){let a=[o(t,n)];switch(r){case`swap`:a.push(o(t,i));break;case`move`:{let[e,r]=[Math.min(n,i),Math.max(n,i)];for(let n=e;n<=r;n++)a.push(o(t,n));break}default:{let r=e.getFieldValue(t),i=Array.isArray(r)?r.length:0;for(let e=n+1;e<i;e++)a.push(o(t,e));break}}return Object.keys(e.fieldInfo).filter(e=>a.some(t=>e.startsWith(t)))}function c(e,t){return e.replace(/\[(\d+)\]/,(e,n)=>{let r=parseInt(n,10);return`[${t===`up`?r+1:Math.max(0,r-1)}]`})}function l(t,n){(n===`up`?t:[...t].reverse()).forEach(t=>{let r=c(t.toString(),n),i=e.getFieldMeta(r);i?e.setFieldMeta(t,i):e.setFieldMeta(t,u())})}let u=()=>wg;return{bumpArrayVersion:t,handleArrayMove:n,handleArrayRemove:r,handleArraySwap:i,handleArrayInsert:a}}function Eg(e){return{values:e.values??{},errorMap:e.errorMap??{},fieldMetaBase:e.fieldMetaBase??{},formGroupStateBase:e.formGroupStateBase??{},isSubmitted:e.isSubmitted??!1,isSubmitting:e.isSubmitting??!1,isValidating:e.isValidating??!1,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??!1,validationMetaMap:e.validationMetaMap??{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}}}var Dg=class{constructor(e){this.options={},this.fieldInfo={},this.formGroupApis=new Set,this.mount=()=>{let e=this.store.subscribe(()=>{gg(this)}),t=qh.on(`request-form-state`,e=>{e.payload.id===this._formId&&qh.emit(`form-api`,{id:this._formId,state:this.store.state,options:this.options})}),n=qh.on(`request-form-reset`,e=>{e.payload.id===this._formId&&this.reset()}),r=qh.on(`request-form-force-submit`,e=>{e.payload.id===this._formId&&(this._devtoolsSubmissionOverride=!0,this.handleSubmit(),this._devtoolsSubmissionOverride=!1)}),i=()=>{r(),n(),t(),e.unsubscribe(),qh.emit(`form-unmounted`,{id:this._formId})};this.options.listeners?.onMount?.({formApi:this});let{onMount:a}=this.options.validators||{};return qh.emit(`form-api`,{id:this._formId,state:this.store.state,options:this.options}),a&&this.validateSync(`mount`),i},this.update=e=>{if(!e)return;let t=this.options;this.options=e;let n=e.defaultValues&&!cg(e.defaultValues,t.defaultValues)&&!this.state.isTouched,r=!cg(e.defaultState,t.defaultState)&&!this.state.isTouched;if(!(!n&&!r)){if(Ih(()=>{this.baseStore.setState(()=>Eg(Object.assign({},this.state,r?e.defaultState:{},n?{values:e.defaultValues}:{})))}),n){let e=Tg(this);for(let t of Object.keys(this.fieldInfo))Array.isArray(this.getFieldValue(t))&&e.bumpArrayVersion(t)}qh.emit(`form-api`,{id:this._formId,state:this.store.state,options:this.options})}},this.reset=(e,t)=>{let{fieldMeta:n}=this.state,r=this.resetFieldMeta(n);e&&!t?.keepDefaultValues&&(this.options={...this.options,defaultValues:e}),this.baseStore.setState(()=>{let t=e??this.options.defaultValues??this.options.defaultState?.values;return e||Object.values(this.fieldInfo).forEach(e=>{e.instance&&e.instance.options.defaultValue!==void 0&&(t=Xh(t,e.instance.name,e.instance.options.defaultValue))}),Eg({...this.options.defaultState,values:t,fieldMetaBase:r})})},this.validateAllFields=async e=>{let t=[];return Ih(()=>{Object.values(this.fieldInfo).forEach(n=>{if(!n.instance)return;let r=n.instance;t.push(Promise.resolve().then(()=>r.validate(e,{skipFormValidation:!0,skipGroupValidation:!0}))),n.instance.store.state.meta.isTouched||n.instance.setMeta(e=>({...e,isTouched:!0}))})}),(await Promise.all(t)).flat()},this.validateArrayFieldsStartingFrom=async(e,t,n)=>{let r=this.getFieldValue(e),i=Array.isArray(r)?Math.max(r.length-1,0):null,a=[`${e}[${t}]`];for(let n=t+1;n<=(i??0);n++)a.push(`${e}[${n}]`);let o=Object.keys(this.fieldInfo).filter(e=>a.some(t=>e.startsWith(t))),s=[];return Ih(()=>{o.forEach(e=>{s.push(Promise.resolve().then(()=>this.validateField(e,n)))})}),(await Promise.all(s)).flat()},this.validateField=(e,t)=>{let n=this.fieldInfo[e]?.instance;if(!n){let{hasErrored:n}=this.validateSync(t);return n&&!this.options.asyncAlways?this.getFieldMeta(e)?.errors??[]:this.validateAsync(t).then(()=>this.getFieldMeta(e)?.errors??[])}return n.store.state.meta.isTouched||n.setMeta(e=>({...e,isTouched:!0})),n.validate(t)},this.validateSync=(e,t)=>{let n=ag(e,{...this.options,form:this,group:t?.group,validationLogic:this.options.validationLogic||yg}),r=!1,i={};return Ih(()=>{for(let e of n){if(!e.validate)continue;let{formError:n,fieldErrors:a}=Og(this.runValidator({validate:e.validate,value:{value:this.state.values,formApi:this,validationSource:`form`},type:`validate`})),o=kg(e.cause),s=new Set([...Object.keys(this.state.fieldMeta),...Object.keys(a||{})]);t?.filterFieldNames&&(s=new Set([...s].filter(t.filterFieldNames)));for(let e of s){if(this.baseStore.state.fieldMetaBase[e]===void 0&&!a?.[e])continue;let{errorMap:t,errorSourceMap:n}=this.getFieldMeta(e)??wg,r=a?.[e],{newErrorValue:s,newSource:c}=lg({newFormValidatorError:r,isPreviousErrorFromFormValidator:n?.[o]===`form`,previousErrorValue:t?.[o]});c===`form`&&(i[e]={...i[e],[o]:r}),t?.[o]!==s&&this.setFieldMeta(e,(e=wg)=>({...e,errorMap:{...e.errorMap,[o]:s},errorSourceMap:{...e.errorSourceMap,[o]:c}}))}t?.dontUpdateFormErrorMap||this.state.errorMap?.[o]!==n&&this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[o]:n}})),(n||a)&&(r=!0)}if(t?.dontUpdateFormErrorMap)return;let a=kg(`submit`);this.state.errorMap?.[a]&&e!==`submit`&&!r&&this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[a]:void 0}}));let o=kg(`server`);this.state.errorMap?.[o]&&e!==`server`&&!r&&this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[o]:void 0}}))}),{hasErrored:r,fieldsErrorMap:i}},this.validateAsync=async(e,t)=>{let n=og(e,{...this.options,form:this,group:t?.group,validationLogic:this.options.validationLogic||yg});this.state.isFormValidating||this.baseStore.setState(e=>({...e,isFormValidating:!0}));let r=[],i;for(let e of n){if(!e.validate)continue;let n=kg(e.cause);this.state.validationMetaMap[n]?.lastAbortController.abort();let a=new AbortController;this.state.validationMetaMap[n]={lastAbortController:a},r.push(new Promise(async n=>{let r;try{r=await new Promise((t,n)=>{setTimeout(async()=>{if(a.signal.aborted)return t(void 0);try{t(await this.runValidator({validate:e.validate,value:{value:this.state.values,formApi:this,validationSource:`form`,signal:a.signal},type:`validateAsync`}))}catch(e){n(e)}},e.debounceMs)})}catch(e){r=e}let{formError:o,fieldErrors:s}=Og(r);s&&(i=i?{...i,...s}:s);let c=kg(e.cause),l=new Set([...Object.keys(this.state.fieldMeta),...Object.keys(i||{})]),u=Array.from(l);t?.filterFieldNames&&(u=u.filter(t.filterFieldNames));for(let e of u){if(this.baseStore.state.fieldMetaBase[e]===void 0&&!i?.[e])continue;let{errorMap:t,errorSourceMap:n}=this.getFieldMeta(e)??wg,r=i?.[e],{newErrorValue:a,newSource:o}=lg({newFormValidatorError:r,isPreviousErrorFromFormValidator:n?.[c]===`form`,previousErrorValue:t?.[c]});t?.[c]!==a&&this.setFieldMeta(e,(e=wg)=>({...e,errorMap:{...e.errorMap,[c]:a},errorSourceMap:{...e.errorSourceMap,[c]:o}}))}t?.dontUpdateFormErrorMap||this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[c]:o}})),n(i?{fieldErrors:i,errorMapKey:c}:void 0)}))}let a=[],o={};if(r.length){a=await Promise.all(r);for(let e of a)if(e?.fieldErrors){let{errorMapKey:t}=e;for(let[n,r]of Object.entries(e.fieldErrors))o[n]={...o[n]||{},[t]:r}}}return this.baseStore.setState(e=>({...e,isFormValidating:!1})),o},this.validate=(e,t)=>{let{hasErrored:n,fieldsErrorMap:r}=this.validateSync(e,t);return n&&!this.options.asyncAlways?r:this.validateAsync(e,t)},this._handleSubmit=async e=>{this.baseStore.setState(e=>({...e,isSubmitted:!1,submissionAttempts:e.submissionAttempts+1,isSubmitSuccessful:!1})),Ih(()=>{Object.values(this.fieldInfo).forEach(e=>{e.instance&&(e.instance.store.state.meta.isTouched||e.instance.setMeta(e=>({...e,isTouched:!0})))})});let t=e??this.options.onSubmitMeta;if(!this.state.canSubmit&&!this._devtoolsSubmissionOverride&&this.baseStore.state.submissionAttempts<=1){this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t});return}this.baseStore.setState(e=>({...e,isSubmitting:!0}));let n=()=>{this.baseStore.setState(e=>({...e,isSubmitting:!1}))};if(await this.validateAllFields(`submit`),!this.state.isFieldsValid){n(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),qh.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:`validateAllFields`,errors:Object.values(this.state.fieldMeta).map(e=>e.errors).flat()});return}if(await this.validate(`submit`),!this.state.isValid){n(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:t}),qh.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:`validate`,errors:this.state.errors});return}Ih(()=>{Object.values(this.fieldInfo).forEach(e=>{e.instance?.triggerOnSubmitListener()})}),this.options.listeners?.onSubmit?.({formApi:this,meta:t});try{await this.options.onSubmit?.({value:this.state.values,formApi:this,meta:t}),Ih(()=>{this.baseStore.setState(e=>({...e,isSubmitted:!0,isSubmitSuccessful:!0})),qh.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),n()})}catch(e){throw this.baseStore.setState(e=>({...e,isSubmitSuccessful:!1})),qh.emit(`form-submission`,{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:`inflight`,onError:e}),n(),e}},this.getFieldValue=e=>Yh(this.state.values,e),this.getFieldMeta=e=>this.state.fieldMeta[e],this.getFormGroupMeta=e=>this.formGroupMetaDerived.state[e],this.getFieldInfo=e=>this.fieldInfo[e]||={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}},this.setFieldMeta=(e,t)=>{this.baseStore.setState(n=>({...n,fieldMetaBase:{...n.fieldMetaBase,[e]:Jh(t,n.fieldMetaBase[e])}}))},this.resetFieldMeta=e=>Object.keys(e).reduce((e,t)=>{let n=t;return e[n]=wg,e},{}),this.setFieldValue=(e,t,n)=>{let r=n?.dontUpdateMeta??!1,i=n?.dontRunListeners??!1,a=n?.dontValidate??!1;Ih(()=>{r||this.setFieldMeta(e,e=>({...e,isTouched:!0,isDirty:!0,errorMap:{...e?.errorMap,onMount:void 0}})),this.baseStore.setState(n=>({...n,values:Xh(n.values,e,t)}))}),i||this.getFieldInfo(e).instance?.triggerOnChangeListener(),a||this.validateField(e,`change`)},this.deleteField=e=>{let t=[...Object.keys(this.fieldInfo).filter(t=>{let n=e.toString();return t!==n&&t.startsWith(n)}),e];this.baseStore.setState(e=>{let n={...e};return t.forEach(e=>{n.values=Zh(n.values,e),delete this.fieldInfo[e],delete n.fieldMetaBase[e]}),n})},this.pushFieldValue=(e,t,n)=>{this.setFieldValue(e,e=>[...Array.isArray(e)?e:[],t],n),Tg(this).bumpArrayVersion(e)},this.insertFieldValue=async(e,t,n,r)=>{this.setFieldValue(e,e=>[...e.slice(0,t),n,...e.slice(t)],dg(r,{dontValidate:!0}));let i=r?.dontValidate??!1;i||await this.validateField(e,`change`),Tg(this).handleArrayInsert(e,t),i||await this.validateArrayFieldsStartingFrom(e,t,`change`)},this.replaceFieldValue=async(e,t,n,r)=>{this.setFieldValue(e,e=>e.map((e,r)=>r===t?n:e),dg(r,{dontValidate:!0})),Tg(this).bumpArrayVersion(e),(r?.dontValidate??!1)||(await this.validateField(e,`change`),await this.validateArrayFieldsStartingFrom(e,t,`change`))},this.removeFieldValue=async(e,t,n)=>{let r=this.getFieldValue(e),i=Array.isArray(r)?Math.max(r.length-1,0):null;if(this.setFieldValue(e,e=>e.filter((e,n)=>n!==t),dg(n,{dontValidate:!0})),Tg(this).handleArrayRemove(e,t),i!==null){let t=`${e}[${i}]`;this.deleteField(t)}(n?.dontValidate??!1)||(await this.validateField(e,`change`),await this.validateArrayFieldsStartingFrom(e,t,`change`))},this.swapFieldValues=(e,t,n,r)=>{this.setFieldValue(e,e=>{let r=e[t],i=e[n];return Xh(Xh(e,`${t}`,i),`${n}`,r)},dg(r,{dontValidate:!0})),Tg(this).handleArraySwap(e,t,n),(r?.dontValidate??!1)||(this.validateField(e,`change`),this.validateField(`${e}[${t}]`,`change`),this.validateField(`${e}[${n}]`,`change`))},this.moveFieldValues=(e,t,n,r)=>{this.setFieldValue(e,e=>{let r=[...e];return r.splice(n,0,r.splice(t,1)[0]),r},dg(r,{dontValidate:!0})),Tg(this).handleArrayMove(e,t,n),(r?.dontValidate??!1)||(this.validateField(e,`change`),this.validateField(`${e}[${t}]`,`change`),this.validateField(`${e}[${n}]`,`change`))},this.clearFieldValues=(e,t)=>{let n=this.getFieldValue(e),r=Array.isArray(n)?Math.max(n.length-1,0):null;if(this.setFieldValue(e,[],dg(t,{dontValidate:!0})),Tg(this).bumpArrayVersion(e),r!==null)for(let t=0;t<=r;t++){let n=`${e}[${t}]`;this.deleteField(n)}(t?.dontValidate??!1)||this.validateField(e,`change`)},this.resetField=e=>{this.baseStore.setState(t=>{let n=this.getFieldInfo(e).instance?.options.defaultValue,r=Yh(this.options.defaultValues,e),i=n??r;return{...t,fieldMetaBase:{...t.fieldMetaBase,[e]:wg},values:i===void 0?t.values:Xh(t.values,e,i)}})},this.setErrorMap=e=>{Ih(()=>{Object.entries(e).forEach(([e,t])=>{let n=e;if(sg(t)){let{formError:e,fieldErrors:r}=Og(t);for(let e of Object.keys(this.fieldInfo))this.getFieldMeta(e)&&this.setFieldMeta(e,t=>({...t,errorMap:{...t.errorMap,[n]:r?.[e]},errorSourceMap:{...t.errorSourceMap,[n]:`form`}}));this.baseStore.setState(t=>({...t,errorMap:{...t.errorMap,[n]:e}}))}else this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[n]:t}}))})})},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((e,[t,n])=>(Object.keys(n).length&&n.errors.length&&(e[t]={errors:n.errors,errorMap:n.errorMap}),e),{})}),this.parseValuesWithSchema=e=>Sg.validate({value:this.state.values,validationSource:`form`},e),this.parseValuesWithSchemaAsync=e=>Sg.validateAsync({value:this.state.values,validationSource:`form`},e),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=e?.formId??hg(),this._devtoolsSubmissionOverride=!1;let t=Eg({...e?.defaultState,values:e?.defaultValues??e?.defaultState?.values});if(e?.transform){t=e.transform({state:t}).state;for(let e of Object.keys(t.errorMap)){let n=t.errorMap[e];if(!(n===void 0||!sg(n)))for(let r of Object.keys(n.fields)){let i=n.fields[r];if(i===void 0)continue;let a=t.fieldMetaBase[r];t.fieldMetaBase[r]={isTouched:!1,isValidating:!1,isBlurred:!1,isDirty:!1,_arrayVersion:0,_pendingValidationsCount:0,...a??{},errorSourceMap:{...a?.errorSourceMap??{},onChange:`form`},errorMap:{...a?.errorMap??{},[e]:i}}}}}this.baseStore=Uh(t);let n;this.fieldMetaDerived=Uh(e=>{let t=this.baseStore.get(),r=0,i={};for(let a of Object.keys(t.fieldMetaBase)){let o=t.fieldMetaBase[a],s=n?.fieldMetaBase[a],c=e?.[a],l=Yh(t.values,a),u=c?.errors;if(!s||o.errorMap!==s.errorMap){u=Object.values(o.errorMap??{}).filter(e=>e!==void 0);let e=this.getFieldInfo(a)?.instance;(!e||!e.options.disableErrorFlat)&&(u=u.flat(1))}let d=!ig(u),f=!o.isDirty,p=cg(l,this.getFieldInfo(a)?.instance?.options.defaultValue??Yh(this.options.defaultValues,a));if(c&&c.isPristine===f&&c.isValid===d&&c.isDefaultValue===p&&c.errors===u&&o===s){i[a]=c,r++;continue}i[a]={...o,errors:u??[],isPristine:f,isValid:d,isDefaultValue:p}}return Object.keys(t.fieldMetaBase).length?e&&r===Object.keys(t.fieldMetaBase).length?e:(n=this.baseStore.get(),i):i}),this.formGroupMetaDerived=Uh(e=>{let t=this.baseStore.get(),n=this.fieldMetaDerived.get(),r={};for(let i of this.formGroupApis){let a=i.name,o=t.formGroupStateBase[a]??{isSubmitted:!1,isSubmitting:!1,isValidating:!1,submissionAttempts:0,isSubmitSuccessful:!1},s=n[a],c=!1,l=!0,u=!1,d=!1,f=!0,p=!1;for(let e in n){if(e===a||!vg(a,e))continue;let t=n[e];t&&(t.isValidating&&(c=!0),t.isValid||(l=!1),t.isTouched&&(u=!0),t.isBlurred&&(d=!0),t.isDefaultValue||(f=!1),t.isDirty&&(p=!0))}let m=!p,h=!!c||o.isValidating,g=s?.errorMap??{},_=s?.errorSourceMap??{},v=!!(g.onMount||Object.entries(n).some(([e,t])=>t&&e!==a&&vg(a,e)&&t.errorMap.onMount)),y=e?.[a],b=y?.errors??[];(!y||y.__srcErrorMap!==g)&&(b=Object.values(g).reduce((e,t)=>{if(t===void 0)return e;if(t&&typeof t==`object`&&`fields`in t){let n=t.group;return n!==void 0&&e.push(n),e}return e.push(t),e},[]));let x=b.length===0,S=l&&x,C=i.options.canSubmitWhenInvalid??!1,w=o.submissionAttempts===0&&!u&&!v||!h&&!o.isSubmitting&&S||C;if(y&&y.errorMap===g&&y.errorSourceMap===_&&y.errors===b&&y.isFieldsValidating===c&&y.isFieldsValid===l&&y.isGroupValid===x&&y.isValid===S&&y.canSubmit===w&&y.isTouched===u&&y.isBlurred===d&&y.isPristine===m&&y.isDefaultValue===f&&y.isDirty===p&&y.isValidating===h&&y.isSubmitting===o.isSubmitting&&y.isSubmitted===o.isSubmitted&&y.submissionAttempts===o.submissionAttempts&&y.isSubmitSuccessful===o.isSubmitSuccessful){r[a]=y;continue}let T={...o,errorMap:g,errorSourceMap:_,_arrayVersion:s?._arrayVersion??0,isTouched:u,isBlurred:d,isDirty:p,isPristine:m,isDefaultValue:f,isValid:S,errors:b,isValidating:h,isFieldsValidating:c,isFieldsValid:l,isGroupValid:x,canSubmit:w};Object.defineProperty(T,"__srcErrorMap",{value:g,enumerable:!1,configurable:!0}),r[a]=T}return r});let r;this.store=Uh(e=>{let t=this.baseStore.get(),n=this.fieldMetaDerived.get(),i=Object.values(n).filter(Boolean),a=i.some(e=>e.isValidating),o=i.every(e=>e.isValid),s=i.some(e=>e.isTouched),c=i.some(e=>e.isBlurred),l=i.every(e=>e.isDefaultValue),u=s&&t.errorMap?.onMount,d=i.some(e=>e.isDirty),f=!d,p=!!(t.errorMap?.onMount||i.some(e=>e?.errorMap?.onMount)),m=!!a,h=e?.errors??[];(!r||t.errorMap!==r.errorMap)&&(h=Object.values(t.errorMap).reduce((e,t)=>t===void 0?e:t&&sg(t)?(e.push(t.form),e):(e.push(t),e),[]));let g=h.length===0,_=o&&g,v=this.options.canSubmitWhenInvalid??!1,y=t.submissionAttempts===0&&!s&&!p||!m&&!t.isSubmitting&&_||v,b=t.errorMap;if(u&&(h=h.filter(e=>e!==t.errorMap.onMount),b=Object.assign(b,{onMount:void 0})),e&&r&&e.errorMap===b&&e.fieldMeta===this.fieldMetaDerived.state&&e.errors===h&&e.isFieldsValidating===a&&e.isFieldsValid===o&&e.isFormValid===g&&e.isValid===_&&e.canSubmit===y&&e.isTouched===s&&e.isBlurred===c&&e.isPristine===f&&e.isDefaultValue===l&&e.isDirty===d&&cg(r,t))return e;let x={...t,errorMap:b,fieldMeta:this.fieldMetaDerived.state,errors:h,isFieldsValidating:a,isFieldsValid:o,isFormValid:g,isValid:_,canSubmit:y,isTouched:s,isBlurred:c,isPristine:f,isDefaultValue:l,isDirty:d};return r=this.baseStore.get(),x}),this.handleSubmit=this.handleSubmit.bind(this),this.update(e||{})}get state(){return this.store.state}get formId(){return this._formId}runValidator(e){return Cg(e.validate)?Sg[e.type](e.value,e.validate):e.validate(e.value)}handleSubmit(e){return this._handleSubmit(e)}};function Og(e){return e?sg(e)?{formError:Og(e.form).formError,fieldErrors:e.fields}:{formError:e}:{formError:void 0}}function kg(e){switch(e){case`submit`:return`onSubmit`;case`blur`:return`onBlur`;case`mount`:return`onMount`;case`server`:return`onServer`;case`dynamic`:return`onDynamic`;default:return`onChange`}}var Ag=class e{constructor(t){this.options={},this.mount=()=>{this.options.defaultValue!==void 0&&!this.getMeta().isTouched&&this.form.setFieldValue(this.name,this.options.defaultValue,{dontUpdateMeta:!0});let e=this.getInfo();e.instance=this,this.update(this.options);let{onMount:t}=this.options.validators||{};if(t){let e=this.runValidator({validate:t,value:{value:this.state.value,fieldApi:this,validationSource:`field`},type:`validate`});e&&this.setMeta(t=>({...t,errorMap:{...t?.errorMap,onMount:e},errorSourceMap:{...t?.errorSourceMap,onMount:`field`}}))}return this.options.listeners?.onMount?.({value:this.state.value,fieldApi:this}),()=>{for(let[e,t]of Object.entries(this.timeoutIds.validations))t&&(clearTimeout(t),this.timeoutIds.validations[e]=null);for(let[e,t]of Object.entries(this.timeoutIds.listeners))t&&(clearTimeout(t),this.timeoutIds.listeners[e]=null);for(let[e,t]of Object.entries(this.timeoutIds.formListeners))t&&(clearTimeout(t),this.timeoutIds.formListeners[e]=null);let e=this.form.fieldInfo[this.name];if(e&&e.instance===this){for(let[t,n]of Object.entries(e.validationMetaMap))n?.lastAbortController.abort(),e.validationMetaMap[t]=void 0;this.form.baseStore.setState(e=>({...e,fieldMetaBase:{...e.fieldMetaBase,[this.name]:{...wg,isTouched:e.fieldMetaBase[this.name]?.isTouched??wg.isTouched,isBlurred:e.fieldMetaBase[this.name]?.isBlurred??wg.isBlurred,isDirty:e.fieldMetaBase[this.name]?.isDirty??wg.isDirty}}})),e.instance=null,this.options.listeners?.onUnmount?.({value:this.state.value,fieldApi:this}),this.form.options.listeners?.onFieldUnmount?.({formApi:this.form,fieldApi:this})}}},this.update=e=>{this.options=e,this.name=e.name,!this.state.meta.isTouched&&this.options.defaultValue!==void 0&&(cg(this.form.getFieldValue(this.name),e.defaultValue)||this.form.setFieldValue(this.name,e.defaultValue,{dontUpdateMeta:!0,dontValidate:!0,dontRunListeners:!0})),this.form.getFieldMeta(this.name)||this.form.setFieldMeta(this.name,this.state.meta)},this.getValue=()=>this.form.getFieldValue(this.name),this.setValue=(e,t)=>{this.form.setFieldValue(this.name,e,dg(t,{dontRunListeners:!0,dontValidate:!0})),t?.dontRunListeners||this.triggerOnChangeListener(),t?.dontValidate||this.validate(`change`)},this.getMeta=()=>this.store.state.meta,this.setMeta=e=>this.form.setFieldMeta(this.name,e),this.getInfo=()=>this.form.getFieldInfo(this.name),this.pushValue=(e,t)=>{this.form.pushFieldValue(this.name,e,dg(t,{dontRunListeners:!0})),t?.dontRunListeners||this.triggerOnChangeListener()},this.insertValue=(e,t,n)=>{this.form.insertFieldValue(this.name,e,t,dg(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.replaceValue=(e,t,n)=>{this.form.replaceFieldValue(this.name,e,t,dg(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.removeValue=(e,t)=>{this.form.removeFieldValue(this.name,e,dg(t,{dontRunListeners:!0})),t?.dontRunListeners||this.triggerOnChangeListener()},this.swapValues=(e,t,n)=>{this.form.swapFieldValues(this.name,e,t,dg(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.moveValue=(e,t,n)=>{this.form.moveFieldValues(this.name,e,t,dg(n,{dontRunListeners:!0})),n?.dontRunListeners||this.triggerOnChangeListener()},this.clearValues=e=>{this.form.clearFieldValues(this.name,dg(e,{dontRunListeners:!0})),e?.dontRunListeners||this.triggerOnChangeListener()},this.getLinkedFields=t=>{let n=Object.values(this.form.fieldInfo),r=[];for(let i of n){if(!i.instance||!(i.instance instanceof e))continue;let{onChangeListenTo:n,onBlurListenTo:a}=i.instance.options.validators||{};t===`change`&&n?.includes(this.name)&&r.push(i.instance),t===`blur`&&a?.includes(this.name)&&r.push(i.instance)}return r},this.validateSync=(e,t)=>{let n=ag(e,{...this.options,form:this.form,fieldName:this.name,validationLogic:this.form.options.validationLogic||yg}),r=this.getLinkedFields(e).reduce((t,n)=>{let r=ag(e,{...n.options,form:n.form,fieldName:n.name,validationLogic:n.form.options.validationLogic||yg});return r.forEach(e=>{e.field=n}),t.concat(r)},[]),i=!1;Ih(()=>{let e=(e,n)=>{let r=Mg(n.cause),a=n.validate?jg(e.runValidator({validate:n.validate,value:{value:e.store.state.value,validationSource:`field`,fieldApi:e},type:`validate`})):void 0,o=t[r],{newErrorValue:s,newSource:c}=ug({formLevelError:o,fieldLevelError:a});e.state.meta.errorMap?.[r]!==s&&e.setMeta(e=>({...e,errorMap:{...e.errorMap,[r]:s},errorSourceMap:{...e.errorSourceMap,[r]:c}})),s&&(i=!0)};for(let t of n)e(this,t);for(let t of r)t.validate&&e(t.field,t)});let a=Mg(`submit`);return this.state.meta.errorMap?.[a]&&e!==`submit`&&!i&&this.setMeta(e=>({...e,errorMap:{...e.errorMap,[a]:void 0},errorSourceMap:{...e.errorSourceMap,[a]:void 0}})),{hasErrored:i}},this.validateAsync=async(e,t)=>{let n=og(e,{...this.options,form:this.form,fieldName:this.name,validationLogic:this.form.options.validationLogic||yg}),r=await t,i=this.getLinkedFields(e).reduce((t,n)=>{let r=og(e,{...n.options,form:n.form,fieldName:n.name,validationLogic:n.form.options.validationLogic||yg});return r.forEach(e=>{e.field=n}),t.concat(r)},[]),a=[],o=[],s=n.some(e=>e.validate),c=Array.from(new Set(i.filter(e=>e.validate).map(e=>e.field)));Ih(()=>{s&&this.startValidation();for(let e of c)e.startValidation()});let l=(e,t,n)=>{let i=Mg(t.cause),a=e.getInfo();a.validationMetaMap[i]?.lastAbortController.abort();let o=new AbortController;a.validationMetaMap[i]={lastAbortController:o},n.push(new Promise(async n=>{let a;try{a=await new Promise((n,r)=>{e.timeoutIds.validations[t.cause]&&(clearTimeout(e.timeoutIds.validations[t.cause]),e.endValidation()),e.timeoutIds.validations[t.cause]=setTimeout(async()=>{if(o.signal.aborted)return n(void 0);try{n(await this.runValidator({validate:t.validate,value:{value:e.store.state.value,fieldApi:e,signal:o.signal,validationSource:`field`},type:`validateAsync`}))}catch(e){r(e)}},t.debounceMs)})}catch(e){a=e}if(o.signal.aborted)return n(void 0);let s=jg(a),c=r[e.name]?.[i],{newErrorValue:l,newSource:u}=ug({formLevelError:c,fieldLevelError:s});if(e.getInfo().instance!==e)return n(void 0);e.setMeta(e=>({...e,errorMap:{...e?.errorMap,[i]:l},errorSourceMap:{...e.errorSourceMap,[i]:u}})),n(l)}))};for(let e of n)e.validate&&l(this,e,a);for(let e of i)e.validate&&l(e.field,e,o);let u=[];return(a.length||o.length)&&(u=await Promise.all(a),await Promise.all(o)),Ih(()=>{s&&this.endValidation();for(let e of c)e.endValidation()}),u.filter(Boolean)},this.validate=(e,t)=>{if(!this.state.meta.isTouched)return[];let n=t?.skipGroupValidation?[]:Array.from(this.form.formGroupApis).filter(e=>this.name.startsWith(e.name)),r=(t?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(e)).fieldsErrorMap[this.name]??{};if(!t?.skipFormValidation)for(let t of n){if(t.state.meta.submissionAttempts===0)continue;let{fieldsErrorMap:n}=this.form.validateSync(e,{group:t,dontUpdateFormErrorMap:!0,filterFieldNames:e=>vg(t.name,e)});r={...r,...n[this.name]??{}}}let{hasErrored:i}=this.validateSync(e,r),a=new WeakMap;for(let t of n){let{hasErrored:n}=t.validateSync(e,{},{skipRelatedFieldValidation:!0});a.set(t,n)}if(i&&!this.options.asyncAlways){this.getInfo().validationMetaMap[Mg(e)]?.lastAbortController.abort();let t=[];for(let r of n)r.getInfo().validationMetaMap[Mg(e)]?.lastAbortController.abort(),t.push(r.state.meta.errors);return[...this.state.meta.errors,...t.flat()]}let o=t?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(e),s=this.validateAsync(e,o),c=[];for(let t of n)a.get(t)&&!t.options.asyncAlways||c.push(t.validateAsync(e,o,{skipRelatedFieldValidation:!0}));return c.length===0?s:Promise.all([s,...c]).then(e=>e.flat())},this.handleChange=e=>{this.setValue(e)},this.handleBlur=()=>{this.state.meta.isTouched||this.setMeta(e=>({...e,isTouched:!0})),this.state.meta.isBlurred||this.setMeta(e=>({...e,isBlurred:!0})),this.validate(`blur`),this.triggerOnBlurListener()},this.setErrorMap=e=>{this.setMeta(t=>({...t,errorMap:{...t.errorMap,...e}}))},this.parseValueWithSchema=e=>Sg.validate({value:this.state.value,validationSource:`field`},e),this.parseValueWithSchemaAsync=e=>Sg.validateAsync({value:this.state.value,validationSource:`field`},e),this.triggerOnBlurListener=()=>{let e=this.form.options.listeners?.onBlurDebounceMs;e&&e>0?(this.timeoutIds.formListeners.blur&&clearTimeout(this.timeoutIds.formListeners.blur),this.timeoutIds.formListeners.blur=setTimeout(()=>{this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this})},e)):this.form.options.listeners?.onBlur?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onBlurDebounceMs;t&&t>0?(this.timeoutIds.listeners.blur&&clearTimeout(this.timeoutIds.listeners.blur),this.timeoutIds.listeners.blur=setTimeout(()=>{this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this})},t)):this.options.listeners?.onBlur?.({value:this.state.value,fieldApi:this})},this.triggerOnChangeListener=()=>{let e=this.form.options.listeners?.onChangeDebounceMs;e&&e>0?(this.timeoutIds.formListeners.change&&clearTimeout(this.timeoutIds.formListeners.change),this.timeoutIds.formListeners.change=setTimeout(()=>{this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this})},e)):this.form.options.listeners?.onChange?.({formApi:this.form,fieldApi:this});let t=this.options.listeners?.onChangeDebounceMs;t&&t>0?(this.timeoutIds.listeners.change&&clearTimeout(this.timeoutIds.listeners.change),this.timeoutIds.listeners.change=setTimeout(()=>{this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this})},t)):this.options.listeners?.onChange?.({value:this.state.value,fieldApi:this});for(let e of this.form.formGroupApis)vg(e.name,this.name)&&e.triggerOnChangeListener()},this.triggerOnSubmitListener=()=>{this.options.listeners?.onSubmit?.({value:this.state.value,fieldApi:this})},this.form=t.form,this.name=t.name,this.options=t,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.store=Uh(e=>{this.form.store.get();let n=this.form.getFieldMeta(this.name)??{...wg,...t.defaultMeta},r=this.form.getFieldValue(this.name);return!n.isTouched&&r===void 0&&this.options.defaultValue!==void 0&&!cg(r,this.options.defaultValue)&&(r=this.options.defaultValue),e&&e.value===r&&e.meta===n?e:{value:r,meta:n}})}get state(){return this.store.state}runValidator(e){return Cg(e.validate)?Sg[e.type](e.value,e.validate):e.validate(e.value)}startValidation(){this.setMeta(e=>{let t=e._pendingValidationsCount+1;return{...e,_pendingValidationsCount:t,isValidating:t>0&&!e.isValidating||e.isValidating}})}endValidation(){this.setMeta(e=>{let t=Math.max(0,e._pendingValidationsCount-1);return{...e,_pendingValidationsCount:t,isValidating:t===0&&e.isValidating?!1:e.isValidating}})}};function jg(e){if(e)return e}function Mg(e){switch(e){case`submit`:return`onSubmit`;case`blur`:return`onBlur`;case`mount`:return`onMount`;case`server`:return`onServer`;case`dynamic`:return`onDynamic`;default:return`onChange`}}function Ng(e){return{isSubmitted:e.isSubmitted??!1,isSubmitting:e.isSubmitting??!1,isValidating:e.isValidating??!1,submissionAttempts:e.submissionAttempts??0,isSubmitSuccessful:e.isSubmitSuccessful??!1}}function Pg(e){return{...wg,...e,errors:[],isPristine:!0,isValid:!0,isDefaultValue:!0,isFieldsValidating:!1,isFieldsValid:!0,isGroupValid:!0,canSubmit:!0,isSubmitting:!1,isSubmitted:!1,isValidating:!1,submissionAttempts:0,isSubmitSuccessful:!1}}var Fg=class e{constructor(t){this.options={},this.setFormGroupState=e=>{this.form.baseStore.setState(t=>{let n=t.formGroupStateBase[this.name]??Ng({});return{...t,formGroupStateBase:{...t.formGroupStateBase,[this.name]:e(n)}}})},this._lastDistributedFieldNames={},this.update=e=>{this.options=e,this.name=e.name,!this.state.meta.isTouched&&this.options.defaultValue!==void 0&&(cg(this.form.getFieldValue(this.name),e.defaultValue)||this.form.setFieldValue(this.name,e.defaultValue,{dontUpdateMeta:!0,dontValidate:!0,dontRunListeners:!0})),this.form.getFieldMeta(this.name)||this.form.setFieldMeta(this.name,{...wg,...this.options.defaultMeta})},this.mount=()=>{this.update(this.options),this.form.formGroupApis.add(this),this.fieldInfo.instance=this,this.form.baseStore.setState(e=>({...e,formGroupStateBase:{...e.formGroupStateBase,[this.name]:e.formGroupStateBase[this.name]??Ng({...this.options.defaultState})}}));let{onMount:e}=this.options.validators||{};if(e){let t=this.runValidator({validate:e,value:{value:this.state.value,groupApi:this,validationSource:`form`},type:`validate`}),n=t,r;Lg(t)&&(n=t.group,r=t.fields);let i=Ig(n);i&&this.setMeta(e=>({...e,errorMap:{...e.errorMap,onMount:i},errorSourceMap:{...e.errorSourceMap,onMount:`field`}})),this.distributeFieldErrors(`onMount`,r)}return this.options.listeners?.onMount?.({value:this.state.value,groupApi:this}),()=>{for(let[e,t]of Object.entries(this.timeoutIds.validations))t&&(clearTimeout(t),this.timeoutIds.validations[e]=null);for(let[e,t]of Object.entries(this.timeoutIds.listeners))t&&(clearTimeout(t),this.timeoutIds.listeners[e]=null);for(let[e,t]of Object.entries(this.timeoutIds.formListeners))t&&(clearTimeout(t),this.timeoutIds.formListeners[e]=null);if(this.fieldInfo.instance===this){for(let[e,t]of Object.entries(this.fieldInfo.validationMetaMap))t?.lastAbortController.abort(),this.fieldInfo.validationMetaMap[e]=void 0;this.form.formGroupApis.delete(this),this.form.baseStore.setState(e=>({...e,formGroupStateBase:{...e.formGroupStateBase,[this.name]:Ng({})}})),this.fieldInfo.instance=null,this.options.listeners?.onUnmount?.({value:this.state.value,groupApi:this})}}},this.setValue=(e,t)=>{this.form.setFieldValue(this.name,e,dg(t,{dontRunListeners:!0,dontValidate:!0})),t?.dontRunListeners||this.triggerOnChangeListener(),t?.dontValidate||this.validate(`change`)},this.getMeta=()=>this.store.state.meta,this.setMeta=e=>this.form.setFieldMeta(this.name,e),this.getInfo=()=>this.fieldInfo,this.getRelatedFields=()=>{let e=Object.values(this.form.fieldInfo),t=[];for(let n of e)n.instance&&n.instance instanceof Ag&&n.instance.name.startsWith(this.name)&&t.push(n.instance);return t},this.getRelatedFieldMetasDerived=()=>{let e=Object.entries(this.form.fieldMetaDerived.state),t=[];for(let[n,r]of e)n!==this.name&&vg(this.name,n)&&t.push({...r,name:n});return t},this.buildChildFieldName=e=>e===``?this.name:e.startsWith(`[`)?`${this.name}${e}`:`${this.name}.${e}`,this.distributeFieldErrors=(e,t)=>{let n=this._lastDistributedFieldNames[e]??new Set,r=new Set;if(t)for(let[e,n]of Object.entries(t))n!=null&&n!==!1&&r.add(this.buildChildFieldName(e));let i=new Set([...n,...r]),a=!1;for(let n of i){let r=n.startsWith(this.name+`[`)?n.slice(this.name.length):n.slice(this.name.length+1),i=t?.[r],o=this.form.getFieldMeta(n);if(!o&&!i)continue;let s=o?.errorMap[e],{newErrorValue:c,newSource:l}=lg({newFormValidatorError:i,isPreviousErrorFromFormValidator:o?.errorSourceMap[e]===`form`,previousErrorValue:s});c&&(a=!0),(s!==c||o?.errorSourceMap[e]!==l)&&this.form.setFieldMeta(n,(t=wg)=>({...t,errorMap:{...t.errorMap,[e]:c},errorSourceMap:{...t.errorSourceMap,[e]:l}}))}return this._lastDistributedFieldNames[e]=r,a},this.validateSync=(t,n,r={})=>{let i=ag(t,{...this.options,form:this.form,group:this,validationLogic:this.options.validationLogic||this.form.options.validationLogic||yg}),a=(r.skipRelatedFieldValidation?[]:this.getRelatedFields()).reduce((e,n)=>{let r=ag(t,{...n.options,form:n.form,validationLogic:n.form.options.validationLogic||yg});return r.forEach(e=>{e.field=n}),e.concat(r)},[]),o=!1;Ih(()=>{let t=(t,r)=>{let i=zg(r.cause),a=t===this,s;r.validate&&(s=t.runValidator({validate:r.validate,value:{value:t.store.state.value,validationSource:a?`form`:`field`,...t instanceof e?{groupApi:t}:{fieldApi:t}},type:`validate`}));let c=s,l;a&&Lg(s)&&(c=s.group,l=s.fields);let u=Ig(c),d=n[i],{newErrorValue:f,newSource:p}=ug({formLevelError:d,fieldLevelError:u});t.state.meta.errorMap?.[i]!==f&&t.setMeta(e=>({...e,errorMap:{...e.errorMap,[i]:f},errorSourceMap:{...e.errorSourceMap,[i]:p}})),f&&(o=!0),a&&this.distributeFieldErrors(i,l)&&(o=!0)};for(let e of i)t(this,e);for(let e of a)e.validate&&t(e.field,e)});let s=zg(`submit`);return this.state.meta.errorMap?.[s]&&t!==`submit`&&!o&&this.setMeta(e=>({...e,errorMap:{...e.errorMap,[s]:void 0},errorSourceMap:{...e.errorSourceMap,[s]:void 0}})),{hasErrored:o}},this.validateAsync=async(t,n,r={})=>{let i=og(t,{...this.options,form:this.form,group:this,validationLogic:this.options.validationLogic||this.form.options.validationLogic||yg}),a=await n,o=r.skipRelatedFieldValidation?[]:this.getRelatedFields(),s=o.reduce((e,n)=>{let r=og(t,{...n.options,form:n.form,validationLogic:n.form.options.validationLogic||yg});return r.forEach(e=>{e.field=n}),e.concat(r)},[]),c=[],l=[],u=i.some(e=>e.validate)||s.some(e=>e.validate);if(u){this.state.meta.isValidating||this.setMeta(e=>({...e,isValidating:!0}));for(let e of o)e.setMeta(e=>({...e,isValidating:!0}))}let d=(t,n,r)=>{let i=zg(n.cause),o=t.getInfo();o.validationMetaMap[i]?.lastAbortController.abort();let s=new AbortController;o.validationMetaMap[i]={lastAbortController:s};let c=t===this;r.push(new Promise(async r=>{let o;try{o=await new Promise((r,i)=>{t.timeoutIds.validations[n.cause]&&clearTimeout(t.timeoutIds.validations[n.cause]),t.timeoutIds.validations[n.cause]=setTimeout(async()=>{if(s.signal.aborted)return r(void 0);try{r(await this.runValidator({validate:n.validate,value:{value:t.store.state.value,signal:s.signal,validationSource:c?`form`:`field`,...t instanceof e?{groupApi:t}:{fieldApi:t}},type:`validateAsync`}))}catch(e){i(e)}},n.debounceMs)})}catch(e){o=e}if(s.signal.aborted)return r(void 0);let l=o,u;c&&Lg(o)&&(l=o.group,u=o.fields);let d=Ig(l),f=a[t.name]?.[i],{newErrorValue:p,newSource:m}=ug({formLevelError:f,fieldLevelError:d});if(t.getInfo().instance!==t)return r(void 0);t.setMeta(e=>({...e,errorMap:{...e?.errorMap,[i]:p},errorSourceMap:{...e.errorSourceMap,[i]:m}})),c&&this.distributeFieldErrors(i,u),r(p)}))};for(let e of i)e.validate&&d(this,e,c);for(let e of s)e.validate&&d(e.field,e,l);let f=[];if((c.length||l.length)&&(f=await Promise.all(c),await Promise.all(l)),u){this.setMeta(e=>({...e,isValidating:!1}));for(let e of o)e.setMeta(e=>({...e,isValidating:!1}))}return f.filter(Boolean)},this.validateAllFields=async e=>{let t=[];return Ih(()=>{Object.values(this.getRelatedFields()).forEach(n=>{t.push(Promise.resolve().then(()=>n.validate(e,{skipFormValidation:!0,skipGroupValidation:!0}))),n.store.state.meta.isTouched||n.setMeta(e=>({...e,isTouched:!0}))})}),(await Promise.all(t)).flat()},this.validateArrayFieldsStartingFrom=(e,t,n)=>this.form.validateArrayFieldsStartingFrom(e,t,n),this.validateField=(e,t)=>this.form.validateField(e,t),this.getFieldValue=e=>this.form.getFieldValue(e),this.getFieldMeta=e=>this.form.getFieldMeta(e),this.setFieldMeta=(e,t)=>this.form.setFieldMeta(e,t),this.setFieldValue=(e,t)=>this.form.setFieldValue(e,t),this.deleteField=e=>this.form.deleteField(e),this.pushFieldValue=(e,t)=>this.form.pushFieldValue(e,t),this.insertFieldValue=(e,t,n)=>this.form.insertFieldValue(e,t,n),this.replaceFieldValue=(e,t,n)=>this.form.replaceFieldValue(e,t,n),this.swapFieldValues=(e,t,n)=>this.form.swapFieldValues(e,t,n),this.moveFieldValues=(e,t,n)=>this.form.moveFieldValues(e,t,n),this.clearFieldValues=e=>this.form.clearFieldValues(e),this.resetField=e=>this.form.resetField(e),this.removeFieldValue=(e,t)=>this.form.removeFieldValue(e,t),this.areRelatedFieldsValid=()=>Object.values(this.getRelatedFields()).every(e=>e.state.meta.isValid),this.validate=(e,t)=>{let{fieldsErrorMap:n}=t?.skipFormValidation?{fieldsErrorMap:{}}:this.form.validateSync(e,{dontUpdateFormErrorMap:!0,filterFieldNames:e=>vg(this.name,e)}),{hasErrored:r}=this.validateSync(e,n[this.name]??{},{skipRelatedFieldValidation:t?.skipRelatedFieldValidation});if(r&&!this.options.asyncAlways)return this.getInfo().validationMetaMap[zg(e)]?.lastAbortController.abort(),this.state.meta.errors;let i=t?.skipFormValidation?Promise.resolve({}):this.form.validateAsync(e,{dontUpdateFormErrorMap:!0,filterFieldNames:e=>vg(this.name,e)});return this.validateAsync(e,i,{skipRelatedFieldValidation:t?.skipRelatedFieldValidation})},this.triggerOnChangeListener=()=>{let e=this.form.options.listeners?.onChangeGroupDebounceMs;e&&e>0?(this.timeoutIds.formListeners.change&&clearTimeout(this.timeoutIds.formListeners.change),this.timeoutIds.formListeners.change=setTimeout(()=>{this.form.options.listeners?.onChangeGroup?.({formApi:this.form,groupApi:this})},e)):this.form.options.listeners?.onChangeGroup?.({formApi:this.form,groupApi:this});let t=this.options.listeners?.onChangeDebounceMs;t&&t>0?(this.timeoutIds.listeners.change&&clearTimeout(this.timeoutIds.listeners.change),this.timeoutIds.listeners.change=setTimeout(()=>{this.options.listeners?.onChange?.({value:this.state.value,groupApi:this})},t)):this.options.listeners?.onChange?.({value:this.state.value,groupApi:this})},this.triggerOnSubmitListener=()=>{this.options.listeners?.onSubmit?.({value:this.state.value,groupApi:this})},this._handleSubmit=async e=>{this.setFormGroupState(e=>({...e,isSubmitted:!1,submissionAttempts:e.submissionAttempts+1,isSubmitSuccessful:!1})),Ih(()=>{Object.values(this.getRelatedFields()).forEach(e=>{e.state.meta.isTouched||e.setMeta(e=>({...e,isTouched:!0}))})});let t=e??this.options.onSubmitMeta;this.setFormGroupState(e=>({...e,isSubmitting:!0}));let n=()=>{this.setFormGroupState(e=>({...e,isSubmitting:!1}))};if(await this.validateAllFields(`submit`),!this.areRelatedFieldsValid()){n(),this.options.onGroupSubmitInvalid?.({value:this.state.value,groupApi:this,meta:t});return}if(await this.validate(`submit`,{skipRelatedFieldValidation:!0}),!this.areRelatedFieldsValid()||!this.state.meta.isValid){n(),this.options.onGroupSubmitInvalid?.({value:this.state.value,groupApi:this,meta:t});return}Ih(()=>{Object.values(this.getRelatedFields()).forEach(e=>{e.options.listeners?.onGroupSubmit?.({value:e.state.value,fieldApi:e})})}),this.options.listeners?.onSubmit?.({groupApi:this,value:this.state.value});try{await this.options.onGroupSubmit?.({value:this.state.value,groupApi:this,meta:t}),Ih(()=>{this.setFormGroupState(e=>({...e,isSubmitted:!0,isSubmitSuccessful:!0})),n()})}catch(e){throw this.setFormGroupState(e=>({...e,isSubmitSuccessful:!1})),n(),e}},this.form=t.form,this.name=t.name,this.options=t,this.timeoutIds={validations:{},listeners:{},formListeners:{}},this.fieldInfo={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}},this.store=Uh(e=>{this.form.formGroupMetaDerived.get(),this.form.baseStore.get();let n=this.form.getFormGroupMeta(this.name)??Pg(t.defaultMeta),r=this.form.getFieldValue(this.name);return!n.isTouched&&r===void 0&&this.options.defaultValue!==void 0&&!cg(r,this.options.defaultValue)&&(r=this.options.defaultValue),e&&e.value===r&&e.meta===n?e:{value:r,meta:n}}),this.handleSubmit=this.handleSubmit.bind(this)}get state(){return this.store.state}runValidator(e){if(Cg(e.validate)){let t=Sg[e.type](e.value,e.validate);return e.type===`validate`?Rg(t):t.then(Rg)}return e.validate(e.value)}handleSubmit(e){return this._handleSubmit(e)}};function Ig(e){if(e)return e}function Lg(e){return!!e&&typeof e==`object`&&`fields`in e}function Rg(e){if(!e||typeof e!=`object`||!(`form`in e)&&!(`fields`in e))return e;let{form:t,fields:n,...r}=e;return{...r,group:t,fields:n}}function zg(e){switch(e){case`submit`:return`onSubmit`;case`blur`:return`onBlur`;case`mount`:return`onMount`;case`server`:return`onServer`;case`dynamic`:return`onDynamic`;default:return`onChange`}}function Bg(e,t){if(!t)return;let n=Object.assign({},e,{state:_g(e.state)});t(n),n.fieldInfo!==e.fieldInfo&&(e.fieldInfo=n.fieldInfo),n.options!==e.options&&(e.options=n.options);let r=Object.keys({values:null,validationMetaMap:null,fieldMetaBase:null,formGroupStateBase:null,isSubmitting:null,isSubmitted:null,isValidating:null,submissionAttempts:null,isSubmitSuccessful:null,_force_re_eval:null}).reduce((t,r)=>(e.state[r]!==n.state[r]&&(t[r]=n.state[r]),t),{});return Ih(()=>{Object.keys(r).length&&e.baseStore.setState(e=>({...e,...r})),n.state.errorMap!==e.state.errorMap&&e.setErrorMap(n.state.errorMap)}),n}var Vg=Nn();function Hg(e,t){return e===t}function Q(e,t=e=>e,n){let r=n?.compare??Hg,i=(0,X.useCallback)(t=>{let{unsubscribe:n}=e.subscribe(t);return n},[e]),a=(0,X.useCallback)(()=>e.get(),[e]);return(0,Vg.useSyncExternalStoreWithSelector)(i,a,a,t,r)}var Ug=typeof window<`u`?X.useLayoutEffect:X.useEffect;function Wg(e){let[t,n]=(0,X.useState)(()=>({form:e.form,name:e.name})),[r,i]=(0,X.useState)(()=>new Ag({...e})),a=r;(t.form!==e.form||t.name!==e.name)&&(a=new Ag({...e}),i(a),n({form:e.form,name:e.name}));let o=Q(a.store,e.mode===`array`?e=>e.meta._arrayVersion||0:e=>e.value),s=Q(a.store,e=>e.meta.isTouched),c=Q(a.store,e=>e.meta.isBlurred),l=Q(a.store,e=>e.meta.isDirty),u=Q(a.store,e=>e.meta.errorMap),d=Q(a.store,e=>e.meta.errorSourceMap),f=Q(a.store,e=>e.meta.isValidating),p=(0,X.useMemo)(()=>({...a,get state(){return{value:e.mode===`array`?a.state.value:o,get meta(){return{...a.state.meta,isTouched:s,isBlurred:c,isDirty:l,errorMap:u,errorSourceMap:d,isValidating:f}}}}}),[a,e.mode,o,s,c,l,u,d,f]);return Ug(a.mount,[a]),Ug(()=>{a.update(e)}),p}var Gg=(({children:e,...t})=>{let n=Wg(t),r=(0,X.useMemo)(()=>Jh(e,n),[e,n]);return(0,Z.jsx)(Z.Fragment,{children:r})});function Kg(){return(0,X.useState)(()=>hg())[0]}var qg=X,Jg=`18.3.1`.split(`.`)[0]===`17`?Kg:qg.useId;function Yg(e){let[t,n]=(0,X.useState)(()=>({form:e.form,name:e.name})),[r,i]=(0,X.useState)(()=>new Fg({...e}));(t.form!==e.form||t.name!==e.name)&&(i(new Fg({...e})),n({form:e.form,name:e.name}));let a=Q(r.store,e=>e.value),o=Q(r.store,e=>e.meta.isTouched),s=Q(r.store,e=>e.meta.isBlurred),c=Q(r.store,e=>e.meta.isDirty),l=Q(r.store,e=>e.meta.errorMap),u=Q(r.store,e=>e.meta.errorSourceMap),d=Q(r.store,e=>e.meta.isValidating),f=Q(r.store,e=>e.meta.isSubmitting),p=Q(r.store,e=>e.meta.isSubmitted),m=Q(r.store,e=>e.meta.submissionAttempts),h=Q(r.store,e=>e.meta.isSubmitSuccessful),g=Q(r.store,e=>e.meta.canSubmit),_=Q(r.store,e=>e.meta.isValid),v=Q(r.store,e=>e.meta.isFieldsValid),y=Q(r.store,e=>e.meta.isFieldsValidating),b=Q(r.store,e=>e.meta.isGroupValid),x=(0,X.useMemo)(()=>({...r,handleSubmit:((...e)=>r._handleSubmit(...e)),get state(){return{...r.state,value:a,get meta(){return{...r.state.meta,isTouched:o,isBlurred:s,isDirty:c,errorMap:l,errorSourceMap:u,isValidating:d,isSubmitting:f,isSubmitted:p,submissionAttempts:m,isSubmitSuccessful:h,canSubmit:g,isValid:_,isFieldsValid:v,isFieldsValidating:y,isGroupValid:b}}}}}),[r,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b]);return Ug(r.mount,[r]),Ug(()=>{r.update(e)}),x}var Xg=(({children:e,...t})=>{let n=Yg(t),r=(0,X.useMemo)(()=>Jh(e,n),[e,n]);return(0,Z.jsx)(Z.Fragment,{children:r})});function Zg({form:e,selector:t=e=>e,children:n}){let r=Q(e.store,t);return(0,Z.jsx)(Z.Fragment,{children:Jh(n,r)})}function Qg(e){let t=Jg(),[n,r]=(0,X.useState)(e?.formId),[i,a]=(0,X.useState)(()=>new Dg({...e,formId:e?.formId??t}));if(n!==e?.formId){let n=e?.formId??t;a(new Dg({...e,formId:n})),r(n)}let o=(0,X.useMemo)(()=>{let e={...i,handleSubmit:((...e)=>i._handleSubmit(...e)),get formId(){return i._formId},get state(){return i.store.state}};return e.Field=function(e){return(0,Z.jsx)(Gg,{...e,form:i})},e.FormGroup=function(e){return(0,Z.jsx)(Xg,{...e,form:i})},e.Subscribe=function(e){return(0,Z.jsx)(Zg,{form:i,selector:e.selector,children:e.children})},e},[i]);Ug(i.mount,[]),Ug(()=>{i.update(e)});let s=(0,X.useRef)(!1);return Ug(()=>{s.current&&e?.transform&&Bg(i,e.transform)},[i,e?.transform]),Ug(()=>{s.current=!0}),o}var $g=(0,X.forwardRef)(function({className:e,invalid:t,...n},r){return(0,Z.jsx)(`input`,{...n,"aria-invalid":t?!0:n[`aria-invalid`]===!1?void 0:n[`aria-invalid`],className:B(`input caps-input w-full`,e),ref:r})});(0,X.forwardRef)(function({leading:e,className:t,...n},r){return(0,Z.jsxs)(`span`,{className:`caps-search-input`,"data-leading":e?`true`:void 0,children:[e?(0,Z.jsx)(`span`,{className:`caps-search-leading`,"aria-hidden":`true`,children:e}):null,(0,Z.jsx)($g,{...n,type:`search`,className:t,ref:r})]})});var e_=e(Un(),1);function t_(e){if(!e||typeof document>`u`)return;let t=document.head||document.getElementsByTagName(`head`)[0],n=document.createElement(`style`);n.type=`text/css`,t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}var n_=e=>{switch(e){case`success`:return a_;case`info`:return s_;case`warning`:return o_;case`error`:return c_;default:return null}},r_=Array(12).fill(0),i_=({visible:e,className:t})=>X.createElement(`div`,{className:[`sonner-loading-wrapper`,t].filter(Boolean).join(` `),"data-visible":e},X.createElement(`div`,{className:`sonner-spinner`},r_.map((e,t)=>X.createElement(`div`,{className:`sonner-loading-bar`,key:`spinner-bar-${t}`})))),a_=X.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`,"aria-hidden":`true`},X.createElement(`path`,{fillRule:`evenodd`,d:`M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z`,clipRule:`evenodd`})),o_=X.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 24 24`,fill:`currentColor`,height:`20`,width:`20`,"aria-hidden":`true`},X.createElement(`path`,{fillRule:`evenodd`,d:`M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z`,clipRule:`evenodd`})),s_=X.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`,"aria-hidden":`true`},X.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z`,clipRule:`evenodd`})),c_=X.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`,"aria-hidden":`true`},X.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z`,clipRule:`evenodd`})),l_=X.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`},X.createElement(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),X.createElement(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})),u_=()=>{let[e,t]=X.useState(document.hidden);return X.useEffect(()=>{let e=()=>{t(document.hidden)};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[]),e},d_=1,f_=100,p_=e=>typeof e?.id==`number`||e?.id?.length>0?e.id:d_++,m_=new class{constructor(){this.subscribe=e=>(this.subscribers.push(e),this.getActiveToasts().forEach(t=>e(t)),()=>{let t=this.subscribers.indexOf(e);this.subscribers.splice(t,1)}),this.publish=e=>{this.subscribers.forEach(t=>t(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e],this.trimHistory()},this.trimHistory=()=>{let e=this.toasts.length-f_;e<=0||(this.toasts=this.toasts.filter(t=>e>0&&this.dismissedToasts.has(t.id)?(this.dismissedToasts.delete(t.id),e--,!1):!0))},this.create=e=>{let{message:t,...n}=e,r=p_(e),i=this.pendingDismissals.get(r);i!==void 0&&(cancelAnimationFrame(i),this.pendingDismissals.delete(r),this.dismissedToasts.delete(r));let a=this.dismissedToasts.has(r),o=e.dismissible===void 0||e.dismissible;return a&&(this.dismissedToasts.delete(r),this.toasts=this.toasts.filter(e=>e.id!==r)),!a&&this.toasts.find(e=>e.id===r)?this.toasts=this.toasts.map(n=>n.id===r?(this.publish({...n,...e,id:r,title:t}),{...n,...e,id:r,dismissible:o,title:t}):n):this.addToast({title:t,...n,dismissible:o,id:r}),r},this.dismiss=e=>{if(e==null)return this.getActiveToasts().forEach(e=>{this.dismissedToasts.add(e.id),this.subscribers.forEach(t=>t({id:e.id,dismiss:!0}))}),e;this.dismissedToasts.add(e);let t=this.pendingDismissals.get(e);return t!==void 0&&cancelAnimationFrame(t),this.pendingDismissals.set(e,requestAnimationFrame(()=>{this.pendingDismissals.delete(e),this.subscribers.forEach(t=>t({id:e,dismiss:!0}))})),e},this.message=(e,t)=>this.create({...t,message:e,type:void 0}),this.error=(e,t)=>this.create({...t,message:e,type:`error`}),this.success=(e,t)=>this.create({...t,type:`success`,message:e}),this.info=(e,t)=>this.create({...t,type:`info`,message:e}),this.warning=(e,t)=>this.create({...t,type:`warning`,message:e}),this.loading=(e,t)=>this.create({...t,type:`loading`,message:e}),this.promise=(e,t)=>{if(!t)return;let n;t.loading!==void 0&&(n=this.create({...t,promise:e,type:`loading`,message:t.loading,description:typeof t.description==`function`?void 0:t.description}));let r=Promise.resolve(e instanceof Function?e():e),i=n!==void 0,a,o=r.then(async e=>{if(a=[`resolve`,e],X.isValidElement(e))i=!1,this.create({id:n,type:`default`,message:e});else if(g_(e)&&!e.ok){i=!1;let r=typeof t.error==`function`?await t.error(`HTTP error! status: ${e.status}`):t.error,a=typeof t.description==`function`?await t.description(`HTTP error! status: ${e.status}`):t.description,o=typeof r==`object`&&!X.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}else if(e instanceof Error){i=!1;let r=typeof t.error==`function`?await t.error(e):t.error,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!X.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}else if(t.success!==void 0){i=!1;let r=typeof t.success==`function`?await t.success(e):t.success,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!X.isValidElement(r)?r:{message:r};this.create({id:n,type:`success`,description:a,...o})}}).catch(async e=>{if(a=[`reject`,e],t.error!==void 0){i=!1;let r=typeof t.error==`function`?await t.error(e):t.error,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!X.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}}).finally(()=>{i&&(this.dismiss(n),n=void 0),t.finally==null||t.finally.call(t)}),s=()=>new Promise((e,t)=>o.then(()=>a[0]===`reject`?t(a[1]):e(a[1])).catch(t));return typeof n!=`string`&&typeof n!=`number`?{unwrap:s}:Object.assign(n,{unwrap:s})},this.custom=(e,t)=>{let n=p_(t);return this.create({...t,jsx:e(n),id:n,type:void 0}),n},this.getActiveToasts=()=>this.toasts.filter(e=>!this.dismissedToasts.has(e.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set,this.pendingDismissals=new Map}},h_=(e,t)=>m_.message(e,t),g_=e=>e&&typeof e==`object`&&`ok`in e&&typeof e.ok==`boolean`&&`status`in e&&typeof e.status==`number`,__=Object.assign(h_,{success:m_.success,info:m_.info,warning:m_.warning,error:m_.error,custom:m_.custom,message:m_.message,promise:m_.promise,dismiss:m_.dismiss,loading:m_.loading},{getHistory:()=>m_.toasts,getToasts:()=>m_.getActiveToasts()});t_(`[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px;flex:1;min-width:0}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--normal-text);background:var(--normal-bg);border:1px solid var(--normal-border);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{-webkit-user-select:none;user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}`);function v_(e){return e.label!==void 0}var y_=3,b_=`24px`,x_=`16px`,S_=4e3,C_=356,w_=14,T_=45,E_=200;function D_(...e){return e.filter(Boolean).join(` `)}function O_(e){let[t,n]=e.split(`-`),r=[];return t&&r.push(t),n&&r.push(n),r}var k_=e=>{let{invert:t,toast:n,unstyled:r,interacting:i,setHeights:a,visibleToasts:o,heights:s,index:c,toasts:l,expanded:u,removeToast:d,defaultRichColors:f,closeButton:p,style:m,cancelButtonStyle:h,actionButtonStyle:g,className:_=``,descriptionClassName:v=``,duration:y,position:b,gap:x,expandByDefault:S,classNames:C,icons:w,closeButtonAriaLabel:T=`Close toast`}=e,[E,D]=X.useState(null),[O,k]=X.useState(null),[A,j]=X.useState(!1),[M,N]=X.useState(!1),[P,F]=X.useState(!1),[I,ee]=X.useState(!1),[L,R]=X.useState(!1),[te,ne]=X.useState(0),[re,z]=X.useState(0),ie=X.useRef(n.duration||y||S_),B=X.useRef(null),V=X.useRef(null),ae=c===0,H=c+1<=o,U=n.type,W=U??`default`,oe=n.dismissible!==!1,se=n.className||``,G=n.descriptionClassName||``,ce=X.useMemo(()=>s.findIndex(e=>e.toastId===n.id)||0,[s,n.id]),le=X.useMemo(()=>n.closeButton??p,[n.closeButton,p]),ue=X.useMemo(()=>n.duration||y||S_,[n.duration,y]),de=X.useRef(0),fe=X.useRef(0),pe=X.useRef(0),me=X.useRef(null),[he,ge]=b.split(`-`),_e=X.useMemo(()=>s.reduce((e,t,n)=>n>=ce?e:e+t.height,0),[s,ce]),ve=u_(),ye=X.useMemo(()=>e.swipeDirections??O_(b),[e.swipeDirections,b]),K=n.invert||t,be=U===`loading`;fe.current=X.useMemo(()=>ce*x+_e,[ce,_e]),X.useEffect(()=>{ie.current=ue},[ue]),X.useEffect(()=>{j(!0)},[]),X.useEffect(()=>{let e=V.current;if(e){let t=e.getBoundingClientRect().height;return z(t),a(e=>[{toastId:n.id,height:t,position:n.position},...e]),()=>a(e=>e.filter(e=>e.toastId!==n.id))}},[a,n.id]),X.useLayoutEffect(()=>{if(!A)return;let e=V.current,t=e.style.height;e.style.height=`auto`;let r=e.getBoundingClientRect().height;e.style.height=t,z(r),a(e=>e.find(e=>e.toastId===n.id)?e.map(e=>e.toastId===n.id?{...e,height:r}:e):[{toastId:n.id,height:r,position:n.position},...e])},[A,n.title,n.description,a,n.id,n.jsx,n.action,n.cancel]);let xe=X.useCallback(()=>{N(!0),ne(fe.current),a(e=>e.filter(e=>e.toastId!==n.id)),setTimeout(()=>{d(n)},E_)},[n,d,a,fe]);X.useEffect(()=>{if(n.promise&&U===`loading`||n.duration===1/0||n.type===`loading`)return;let e;return u||i||ve?(()=>{if(pe.current<de.current){let e=new Date().getTime()-de.current;ie.current-=e}pe.current=new Date().getTime()})():ie.current!==1/0&&(de.current=new Date().getTime(),e=setTimeout(()=>{n.onAutoClose==null||n.onAutoClose.call(n,n),xe()},ie.current)),()=>clearTimeout(e)},[u,i,n,U,ve,xe]),X.useEffect(()=>{n.delete&&(xe(),n.onDismiss==null||n.onDismiss.call(n,n))},[xe,n.delete]);function Se(){return w?.loading?X.createElement(`div`,{className:D_(C?.loader,n?.classNames?.loader,`sonner-loader`),"data-visible":U===`loading`},w.loading):X.createElement(i_,{className:D_(C?.loader,n?.classNames?.loader),visible:U===`loading`})}let Ce=n.icon||w?.[U]||n_(U);return X.createElement(`li`,{tabIndex:0,ref:V,className:D_(_,se,C?.toast,n?.classNames?.toast,C?.[W],n?.classNames?.[W]),"data-sonner-toast":``,"data-rich-colors":n.richColors??f,"data-styled":!(n.jsx||n.unstyled||r),"data-mounted":A,"data-promise":!!n.promise,"data-swiped":L,"data-removed":M,"data-visible":H,"data-y-position":he,"data-x-position":ge,"data-index":c,"data-front":ae,"data-swiping":P,"data-dismissible":oe,"data-type":U,"data-invert":K,"data-swipe-out":I,"data-swipe-direction":O,"data-expanded":!!(u||S&&A),"data-testid":n.testId,style:{"--index":c,"--toasts-before":c,"--z-index":l.length-c,"--offset":`${M?te:fe.current}px`,"--initial-height":S?`auto`:`${re}px`,...m,...n.style},onDragEnd:()=>{F(!1),D(null),me.current=null},onPointerDown:e=>{e.button!==2&&(be||!oe||(B.current=new Date,ne(fe.current),e.target.setPointerCapture(e.pointerId),e.target.tagName!==`BUTTON`&&(F(!0),me.current={x:e.clientX,y:e.clientY})))},onPointerUp:()=>{if(I||!oe)return;me.current=null;let e=Number(V.current?.style.getPropertyValue(`--swipe-amount-x`).replace(`px`,``)||0),t=Number(V.current?.style.getPropertyValue(`--swipe-amount-y`).replace(`px`,``)||0),r=new Date().getTime()-B.current?.getTime(),i=E===`x`?e:t,a=Math.abs(i)/r;if((E===`x`?ye.includes(e>0?`right`:`left`):ye.includes(t>0?`bottom`:`top`))&&(Math.abs(i)>=T_||a>.11)){ne(fe.current),n.onDismiss==null||n.onDismiss.call(n,n),k(E===`x`?e>0?`right`:`left`:t>0?`down`:`up`),xe(),ee(!0);return}var o,s;(o=V.current)==null||o.style.setProperty(`--swipe-amount-x`,`0px`),(s=V.current)==null||s.style.setProperty(`--swipe-amount-y`,`0px`),R(!1),F(!1),D(null)},onPointerMove:e=>{var t,n;if(!me.current||!oe||window.getSelection()?.toString().length>0)return;let r=e.clientY-me.current.y,i=e.clientX-me.current.x;!E&&(Math.abs(i)>1||Math.abs(r)>1)&&D(Math.abs(i)>Math.abs(r)?`x`:`y`);let a={x:0,y:0},o=e=>1/(1.5+Math.abs(e)/20);if(E===`y`){if(ye.includes(`top`)||ye.includes(`bottom`)){if(ye.includes(`top`)&&r<0||ye.includes(`bottom`)&&r>0)a.y=r;else{let e=r*o(r);a.y=Math.abs(e)<Math.abs(r)?e:r}}}else if(E===`x`&&(ye.includes(`left`)||ye.includes(`right`))){if(ye.includes(`left`)&&i<0||ye.includes(`right`)&&i>0)a.x=i;else{let e=i*o(i);a.x=Math.abs(e)<Math.abs(i)?e:i}}(Math.abs(a.x)>0||Math.abs(a.y)>0)&&R(!0),(t=V.current)==null||t.style.setProperty(`--swipe-amount-x`,`${a.x}px`),(n=V.current)==null||n.style.setProperty(`--swipe-amount-y`,`${a.y}px`)}},le&&!n.jsx&&U!==`loading`?X.createElement(`button`,{"aria-label":T,"data-disabled":be,"data-close-button":!0,onClick:be||!oe?()=>{}:()=>{xe(),n.onDismiss==null||n.onDismiss.call(n,n)},className:D_(C?.closeButton,n?.classNames?.closeButton)},w?.close??l_):null,(U||n.icon||n.promise)&&n.icon!==null&&(w?.[U]!==null||n.icon)?X.createElement(`div`,{"data-icon":``,className:D_(C?.icon,n?.classNames?.icon)},U===`loading`?n.icon||Se():n.promise?Se():null,U===`loading`?null:Ce):null,X.createElement(`div`,{"data-content":``,className:D_(C?.content,n?.classNames?.content)},X.createElement(`div`,{"data-title":``,className:D_(C?.title,n?.classNames?.title)},n.jsx?n.jsx:typeof n.title==`function`?n.title():n.title),n.description?X.createElement(`div`,{"data-description":``,className:D_(v,G,C?.description,n?.classNames?.description)},typeof n.description==`function`?n.description():n.description):null),X.isValidElement(n.cancel)?n.cancel:n.cancel&&v_(n.cancel)?X.createElement(`button`,{"data-button":!0,"data-cancel":!0,style:n.cancelButtonStyle||h,onClick:e=>{v_(n.cancel)&&oe&&(n.cancel.onClick==null||n.cancel.onClick.call(n.cancel,e),xe())},className:D_(C?.cancelButton,n?.classNames?.cancelButton)},n.cancel.label):null,X.isValidElement(n.action)?n.action:n.action&&v_(n.action)?X.createElement(`button`,{"data-button":!0,"data-action":!0,style:n.actionButtonStyle||g,onClick:e=>{v_(n.action)&&(n.action.onClick==null||n.action.onClick.call(n.action,e),!e.defaultPrevented&&xe())},className:D_(C?.actionButton,n?.classNames?.actionButton)},n.action.label):null)};function A_(){if(typeof window>`u`||typeof document>`u`)return`ltr`;let e=document.documentElement.getAttribute(`dir`);return e===`auto`||!e?window.getComputedStyle(document.documentElement).direction:e}function j_(e,t){let n={};return[e,t].forEach((e,t)=>{let r=t===1,i=r?`--mobile-offset`:`--offset`,a=r?x_:b_;function o(e){[`top`,`right`,`bottom`,`left`].forEach(t=>{n[`${i}-${t}`]=typeof e==`number`?`${e}px`:e})}typeof e==`number`||typeof e==`string`?o(e):typeof e==`object`?[`top`,`right`,`bottom`,`left`].forEach(t=>{e[t]===void 0?n[`${i}-${t}`]=a:n[`${i}-${t}`]=typeof e[t]==`number`?`${e[t]}px`:e[t]}):o(a)}),n}var M_=X.forwardRef(function(e,t){let{id:n,invert:r,position:i=`bottom-right`,hotkey:a=[`altKey`,`KeyT`],expand:o,closeButton:s,className:c,offset:l,mobileOffset:u,theme:d=`light`,richColors:f,duration:p,style:m,visibleToasts:h=y_,toastOptions:g,dir:_=A_(),gap:v=w_,icons:y,customAriaLabel:b,containerAriaLabel:x=`Notifications`}=e,[S,C]=X.useState([]),w=X.useMemo(()=>n?S.filter(e=>e.toasterId===n):S.filter(e=>!e.toasterId),[S,n]),T=X.useMemo(()=>Array.from(new Set([i].concat(w.filter(e=>e.position).map(e=>e.position)))),[w,i]),[E,D]=X.useState([]),[O,k]=X.useState(!1),[A,j]=X.useState(!1),[M,N]=X.useState(d===`system`?typeof window<`u`&&window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`:d),P=X.useRef(null),F=a.join(`+`).replace(/Key/g,``).replace(/Digit/g,``),I=X.useRef(null),ee=X.useRef(!1),L=X.useCallback(e=>{C(t=>(t.find(t=>t.id===e.id)?.delete||m_.dismiss(e.id),t.filter(({id:t})=>t!==e.id)))},[]);return X.useEffect(()=>m_.subscribe(e=>{if(e.dismiss){requestAnimationFrame(()=>{C(t=>t.map(t=>t.id===e.id?{...t,delete:!0}:t))});return}setTimeout(()=>{e_.flushSync(()=>{C(t=>{let n=t.findIndex(t=>t.id===e.id);return n===-1?[e,...t]:[...t.slice(0,n),{...t[n],...e},...t.slice(n+1)]})})})}),[]),X.useEffect(()=>{if(d!==`system`){N(d);return}if(d===`system`&&(window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?N(`dark`):N(`light`)),typeof window>`u`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`);try{e.addEventListener(`change`,({matches:e})=>{N(e?`dark`:`light`)})}catch{e.addListener(({matches:e})=>{try{N(e?`dark`:`light`)}catch(e){console.error(e)}})}},[d]),X.useEffect(()=>{S.length<=1&&k(!1)},[S]),X.useEffect(()=>{let e=e=>{if(a.length>0&&a.every(t=>e[t]||e.code===t)){var t;k(!0),(t=P.current)==null||t.focus()}e.code===`Escape`&&(document.activeElement===P.current||P.current?.contains(document.activeElement))&&k(!1)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[a]),X.useEffect(()=>{if(P.current)return()=>{I.current&&(I.current.focus({preventScroll:!0}),I.current=null,ee.current=!1)}},[P.current]),X.createElement(`section`,{ref:t,"aria-label":b??`${x} ${F}`,tabIndex:-1,"aria-live":`polite`,"aria-relevant":`additions text`,"aria-atomic":`false`,suppressHydrationWarning:!0,"data-react-aria-top-layer":!0},T.map((t,n)=>{let[i,a]=t.split(`-`);return w.length?X.createElement(`ol`,{key:t,dir:_===`auto`?A_():_,tabIndex:-1,ref:P,className:c,"data-sonner-toaster":!0,"data-sonner-theme":M,"data-y-position":i,"data-x-position":a,style:{"--front-toast-height":`${E[0]?.height||0}px`,"--width":`${C_}px`,"--gap":`${v}px`,...m,...j_(l,u)},onBlur:e=>{ee.current&&!e.currentTarget.contains(e.relatedTarget)&&(ee.current=!1,I.current&&=(I.current.focus({preventScroll:!0}),null))},onFocus:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||ee.current||(ee.current=!0,I.current=e.relatedTarget)},onMouseEnter:()=>k(!0),onMouseMove:()=>k(!0),onMouseLeave:()=>{A||k(!1)},onDragEnd:()=>k(!1),onPointerDown:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||j(!0)},onPointerUp:()=>j(!1)},w.filter(e=>!e.position&&n===0||e.position===t).map((n,i)=>X.createElement(k_,{key:n.id,icons:y,index:i,toast:n,defaultRichColors:f,duration:g?.duration??p,className:g?.className,descriptionClassName:g?.descriptionClassName,invert:r,visibleToasts:h,closeButton:g?.closeButton??s,interacting:A,position:t,style:g?.style,unstyled:g?.unstyled,classNames:g?.classNames,cancelButtonStyle:g?.cancelButtonStyle,actionButtonStyle:g?.actionButtonStyle,closeButtonAriaLabel:g?.closeButtonAriaLabel,removeToast:L,toasts:w.filter(e=>e.position==n.position),heights:E.filter(e=>e.position==n.position),setHeights:D,expandByDefault:o,gap:v,expanded:O,swipeDirections:e.swipeDirections}))):null}))});function N_({className:e,...t}){let n=or(`toast`);return n?(0,e_.createPortal)((0,Z.jsx)(M_,{position:`top-right`,swipeDirections:[`right`,`top`],offset:16,gap:8,icons:{close:(0,Z.jsx)(Xi,{"aria-hidden":`true`,size:12}),success:(0,Z.jsx)(np,{glyph:`dot`,tone:`success`}),error:(0,Z.jsx)(np,{glyph:`dot`,tone:`error`}),warning:(0,Z.jsx)(np,{glyph:`dot`,tone:`warning`}),info:(0,Z.jsx)(np,{glyph:`dot`,tone:`info`}),loading:(0,Z.jsx)(rt,{decorative:!0,size:`sm`,tone:`current`,variant:`wander`})},className:B(`caps-toaster`,e),...t}),n):null}var P_=(0,X.forwardRef)(function({children:e,className:t,optional:n,required:r,...i},a){return(0,Z.jsxs)(`label`,{...i,className:B(`label caps-label cursor-pointer justify-start gap-sm text-sm font-semibold text-base-content`,t),ref:a,children:[e,r?(0,Z.jsx)(`span`,{"aria-hidden":`true`,className:`text-error`,children:`*`}):null,n&&!r?(0,Z.jsx)(`span`,{className:`caps-label-optional`,children:`Optional`}):null]})}),F_=(0,X.forwardRef)(function({children:e,className:t,...n},r){return(0,Z.jsx)(`div`,{...n,className:B(`caps-input-group join flex w-full items-stretch [&>*]:join-item [&>*:first-child]:rounded-e-none [&>*:last-child]:rounded-s-none [&>*:not(:first-child):not(:last-child)]:rounded-none [&>.btn]:shrink-0 [&>.input]:min-w-0 [&>.input]:flex-1 [&>.select]:min-w-0 [&>.select]:flex-1`,t),ref:r,children:X.Children.map(e,e=>(0,X.isValidElement)(e)?(0,X.cloneElement)(e,{className:B(`join-item caps-input-group-control`,e.props.className)}):e)})}),I_=(0,X.forwardRef)(function({className:e,...t},n){return(0,Z.jsx)(`div`,{...t,className:B(`join-item flex items-center border border-base-300 bg-base-200 px-md text-sm text-base-content`,e),ref:n})});function L_(e){let t=e.parentElement;if(!t||e.previousElementSibling===null)return 0;let n=getComputedStyle(t);if(!(n.display.includes(`grid`)||n.display.includes(`flex`)&&n.flexDirection.startsWith(`column`)))return 0;let r=Number.parseFloat(n.rowGap);return Number.isFinite(r)?r:0}(0,X.forwardRef)(function({show:e,appear:t=!1,children:n,className:r,...i},a){let o=(0,X.useRef)(null);(0,X.useImperativeHandle)(a,()=>o.current);let s=d(),[c,l]=(0,X.useState)(e),u=(0,X.useRef)(!0);return e&&!c&&l(!0),(0,X.useLayoutEffect)(()=>{let n=o.current,r=u.current;if(u.current=!1,!n||r&&!t)return;if(!He(n)){e||l(!1);return}let i=he(n),a=`translateY(${String(i.distance)}px)`,c=de(i,i.ease),d=n.getBoundingClientRect().height,f=L_(n),p=(e,t)=>{n.style.overflow=`clip`;let r=e=>({height:`${String(e)}px`,marginBlockStart:`${String(e===0?-f:0)}px`}),a=n.animate([r(e),r(t)],{duration:i.normal,easing:c}),o=()=>{n.style.removeProperty(`overflow`)};return a.addEventListener(`finish`,o),a.addEventListener(`cancel`,o),a};if(e){let e=[n.animate([{opacity:0,transform:a},{opacity:1,transform:`none`}],{duration:i.normal,easing:c})];return!s&&d>0&&e.push(p(0,d)),()=>{for(let t of e)t.cancel()}}let m=n.animate([{opacity:1,transform:`none`},{opacity:0,transform:a}],{duration:i.fast,easing:de(i,i.easeExit),fill:`forwards`}),h=!s&&d>0?p(d,0):m;return h!==m&&h.effect?.updateTiming({fill:`forwards`}),h.addEventListener(`finish`,()=>{l(!1)}),()=>{m.cancel(),h.cancel()}},[e,t,s]),c?(0,Z.jsx)(`div`,{...i,ref:o,className:B(`caps-presence`,r),"data-present":e,"aria-hidden":!e||void 0,children:n}):null});var R_=(0,X.forwardRef)(function({open:e,children:t,className:n,...r},i){return(0,Z.jsx)(`div`,{...r,ref:i,className:B(`caps-collapse`,n),"data-open":e,"aria-hidden":!e||void 0,children:(0,Z.jsx)(`div`,{className:`caps-collapse-clip`,children:t})})});(0,X.forwardRef)(function({swapKey:e,anchor:t=`start`,children:n,className:r,...i},a){let o=(0,X.useRef)(null);(0,X.useImperativeHandle)(a,()=>o.current);let s=d(),[c,l]=(0,X.useState)({key:e,content:n}),[u,f]=(0,X.useState)([]);c.key===e?c.content!==n&&l({key:e,content:n}):(f([...u.filter(t=>t.key!==e&&t.key!==c.key),c]),l({key:e,content:n}));let p=(0,X.useRef)(null);return(0,X.useLayoutEffect)(()=>{let e=o.current;if(!e||!(`ResizeObserver`in globalThis))return;p.current=e.getBoundingClientRect();let t=new ResizeObserver(()=>{e.getAnimations().length===0&&(p.current=e.getBoundingClientRect())});return t.observe(e),()=>{t.disconnect()}},[]),(0,X.useLayoutEffect)(()=>{let e=o.current;if(!e)return;let t=[...e.querySelectorAll(`:scope > [data-swap-leaving]`)],n=e.querySelector(`:scope > [data-swap-current]`);if(n===null||t.length===0)return;if(!He(e)){f([]);return}let r=p.current,i=e.getBoundingClientRect(),a=he(e),c=[n.animate([{opacity:0,filter:`blur(${String(a.blur)}px)`,transform:`translateY(${String(a.distance/2)}px)`},{opacity:1,filter:`blur(0px)`,transform:`none`}],{duration:a.normal,easing:de(a,a.ease)})];for(let e of t){let t=e.animate([{opacity:1,filter:`blur(0px)`,transform:`none`},{opacity:0,filter:`blur(${String(a.blur)}px)`,transform:`translateY(${String(-a.distance/2)}px)`}],{duration:a.fast,easing:de(a,a.easeExit),fill:`forwards`}),n=e.dataset.swapLeaving;t.onfinish=()=>{f(e=>e.filter(e=>e.key!==n))},c.push(t)}let l=r!==null&&(Math.abs(r.height-i.height)>.5||Math.abs(r.width-i.width)>.5);return!s&&l&&c.push(e.animate([{width:`${String(r.width)}px`,height:`${String(r.height)}px`},{width:`${String(i.width)}px`,height:`${String(i.height)}px`}],{duration:a.normal,easing:de(a,a.ease)})),()=>{for(let e of c)e.cancel()}},[e,s]),(0,Z.jsx)(`div`,{...i,ref:o,className:B(`caps-swap`,r),"data-anchor":t,children:[...u.map(e=>(0,Z.jsx)(`div`,{className:`caps-swap-layer`,"data-swap-leaving":e.key,"aria-hidden":`true`,children:e.content},e.key)),(0,Z.jsx)(`div`,{className:`caps-swap-layer`,"data-swap-current":``,children:n},e)]})});function z_({children:e,...t}){let[n,r]=(0,X.useState)(e);return e&&e!==n&&r(e),(0,Z.jsx)(R_,{...t,className:B(`caps-field-error-reveal`,t.className),open:!!e,children:(0,Z.jsx)(`div`,{className:`caps-field-error`,role:`alert`,"aria-hidden":!e,children:n})})}function B_({children:e,divider:t=!0,error:n,layout:r=`end`,status:i,...a}){return(0,Z.jsxs)(`footer`,{...a,className:B(`caps-form-footer`,a.className),"data-divider":t,"data-layout":r,children:[(0,Z.jsx)(z_,{children:n}),(0,Z.jsxs)(`div`,{className:`caps-form-footer-row`,children:[i?(0,Z.jsx)(`div`,{className:`caps-form-footer-status`,role:`status`,children:i}):null,(0,Z.jsx)(`div`,{className:`caps-form-footer-actions`,children:e})]})]})}var V_=(0,X.forwardRef)(function({busy:e=!1,children:t,className:n,layout:r,...i},a){return(0,Z.jsx)(`form`,{...i,"aria-busy":e||void 0,className:B(`caps-form`,n),"data-layout":r,ref:a,children:(0,Z.jsx)(`fieldset`,{className:`caps-form-body`,disabled:e,children:t})})}),H_={2:`h2`,3:`h3`,4:`h4`},U_=(0,X.forwardRef)(function({children:e,className:t,description:n,layout:r,level:i=3,title:a,...o},s){let c=(0,X.useId)(),l=H_[i];return(0,Z.jsxs)(`section`,{...o,"aria-labelledby":`${c}-title`,className:B(`caps-form-section`,t),"data-layout":r,ref:s,children:[(0,Z.jsxs)(`header`,{className:`caps-form-section-copy`,children:[(0,Z.jsx)(l,{className:`caps-form-section-title`,id:`${c}-title`,children:a}),n?(0,Z.jsx)(`p`,{className:`caps-form-section-description`,children:n}):null]}),(0,Z.jsx)(`div`,{className:`caps-form-section-fields`,children:e})]})}),W_=(0,X.forwardRef)(function({children:e,className:t,description:n,error:r,icon:i,layout:a,legend:o,legendTitle:s,...c},l){let u=(0,X.useId)(),d=[n?`${u}-description`:c[`aria-describedby`],r?`${u}-error`:null].filter(Boolean).join(` `)||void 0;return(0,Z.jsxs)(`fieldset`,{...c,"aria-describedby":d,"aria-invalid":r?!0:c[`aria-invalid`],className:B(`caps-fieldset`,t),"data-layout":a,ref:l,children:[(0,Z.jsxs)(`legend`,{className:`caps-fieldset-legend`,title:s,children:[i?(0,Z.jsx)(`span`,{className:`caps-field-icon`,"aria-hidden":`true`,children:i}):null,o]}),n?(0,Z.jsx)(`p`,{className:`caps-fieldset-description`,id:`${u}-description`,children:n}):null,(0,Z.jsx)(`div`,{className:`caps-fieldset-fields`,children:e}),r===void 0?null:(0,Z.jsx)(z_,{id:`${u}-error`,children:r})]})});function G_(e){let t=[];return X.Children.forEach(e.props.children,e=>{(0,X.isValidElement)(e)&&e.type!==I_&&t.push(e)}),t[0]??null}var K_=(0,X.forwardRef)(function({children:e,className:t,description:n,error:r,icon:i,label:a,labelTitle:o,optional:s,orientation:c=`vertical`,readout:l=!1,required:u,...d},f){let p=(0,X.useId)(),m=(0,X.isValidElement)(e)?e:null,h=m?.type===F_,g=h?G_(m):m,_=g?.props.id??p,v=`${_}-description`,y=`${_}-error`,b=[g?.props[`aria-describedby`],n?v:null,r?y:null].filter(Boolean).join(` `)||void 0,x=u===!0||g?.props.required,S=r?!0:g?.props[`aria-invalid`],C=u===!0||g?.props[`aria-required`],w={id:_};x!==void 0&&(w.required=x),b!==void 0&&(w[`aria-describedby`]=b),S!==void 0&&(w[`aria-invalid`]=S),C!==void 0&&(w[`aria-required`]=C);let T=m&&g&&!l?h?(0,X.cloneElement)(m,void 0,X.Children.map(m.props.children,e=>e===g?(0,X.cloneElement)(g,w):e)):(0,X.cloneElement)(m,w):e,E=a?(0,Z.jsx)(P_,{htmlFor:l?void 0:_,title:o,className:c===`inline`?`font-normal`:void 0,...u===void 0?{}:{required:u},...s===void 0?{}:{optional:s},children:a}):null,D=a||n?(0,Z.jsxs)(`div`,{className:`caps-field-copy`,children:[E,n?(0,Z.jsx)(`p`,{className:`caps-field-description`,id:v,children:n}):null]}):null,O=i?(0,Z.jsxs)(`div`,{className:`caps-field-lead`,children:[(0,Z.jsx)(`span`,{className:`caps-field-icon`,"aria-hidden":`true`,children:i}),D]}):D;return(0,Z.jsxs)(`div`,{...d,className:B(`caps-field`,t),"data-orientation":c,ref:f,children:[c===`horizontal`?(0,Z.jsxs)(`div`,{className:`caps-field-row`,children:[O,T]}):c===`inline`?(0,Z.jsxs)(`div`,{className:`caps-field-row`,children:[T,O]}):(0,Z.jsxs)(Z.Fragment,{children:[O,T]}),(0,Z.jsx)(z_,{id:y,children:r})]})});function q_(e){let t=String(e),n=t.indexOf(`.`);return n===-1?0:t.length-n-1}var J_=`M 9.86 38.14 A 20 20 0 1 1 38.14 38.14`,Y_=6,X_=new Map([[`ArrowUp`,1],[`ArrowDown`,-1],[`PageUp`,10],[`PageDown`,-10]]),Z_=(0,X.forwardRef)(function({className:e,decrementLabel:t=`Decrease`,defaultValue:n=null,disabled:r,incrementLabel:i=`Increase`,invalid:a,max:o,min:s,onBlur:c,onKeyDown:l,onValueChange:u,step:d=1,unit:f,value:p,wrap:m=!1,...h},g){let[_,v]=(0,X.useState)(n),[y,b]=(0,X.useState)(null),x=p===void 0?_:p,S=q_(d),C=e=>{let t=Number(e.toFixed(S));return s!==void 0&&t<s?s:o!==void 0&&t>o?o:t},w=e=>{let t=e===null?null:C(e);v(t),b(null),t!==x&&u?.(t)},T=()=>{if(y===null)return;let e=Number(y);w(y.trim()===``||!Number.isFinite(e)?null:e)},E=e=>{let t=(x??s??0)+e*d;if(m&&s!==void 0&&o!==void 0){if(t>o){w(s);return}if(t<s){w(o);return}}w(t)},D=s!==void 0&&x!==null&&x<=s,O=o!==void 0&&x!==null&&x>=o,k=r===!0,A=(0,X.useRef)(null),j=s!==void 0&&o!==void 0&&o>s?((x??s)-s)/(o-s):null,M=e=>{k||(e.currentTarget.setPointerCapture(e.pointerId),A.current={y:e.clientY,value:x??s??0})},N=e=>{if(!A.current)return;let t=Math.trunc((A.current.y-e.clientY)/Y_),n=C(A.current.value+t*d);n!==x&&w(n)},P=()=>{A.current=null};return(0,Z.jsxs)(`span`,{className:B(`caps-number-field`,e),"data-at-max":O||void 0,"data-at-min":D||void 0,"data-disabled":k||void 0,"data-wrap":m||void 0,children:[j===null?null:(0,Z.jsxs)(`svg`,{className:`caps-number-field-dial`,viewBox:`0 0 48 48`,"aria-hidden":`true`,focusable:`false`,onPointerDown:M,onPointerMove:N,onPointerUp:P,onPointerCancel:P,children:[(0,Z.jsx)(`path`,{className:`caps-number-field-dial-track`,d:J_,pathLength:100}),(0,Z.jsx)(`path`,{className:`caps-number-field-dial-level`,d:J_,pathLength:100,strokeDasharray:`${String(Math.max(.5,j*100))} 100`})]}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`icon`,className:`caps-number-field-decrement`,"aria-label":t,"aria-controls":h.id,tabIndex:-1,disabled:k||D&&!m,onClick:()=>{E(-1)},children:(0,Z.jsx)(mm,{"aria-hidden":`true`})}),(0,Z.jsxs)(`span`,{className:`caps-number-field-readout`,children:[(0,Z.jsx)(`input`,{...h,"aria-invalid":a?!0:h[`aria-invalid`]===!1?void 0:h[`aria-invalid`],className:`input caps-input caps-number-field-input`,disabled:r,inputMode:h.inputMode??(S>0?`decimal`:`numeric`),max:o,min:s,onBlur:e=>{T(),c?.(e)},onChange:e=>{b(e.target.value)},onKeyDown:e=>{if(l?.(e),e.defaultPrevented)return;let t=X_.get(e.key);t===void 0?e.key===`Home`&&s!==void 0?(e.preventDefault(),w(s)):e.key===`End`&&o!==void 0?(e.preventDefault(),w(o)):e.key===`Enter`&&T():(e.preventDefault(),E(t))},ref:g,step:d,type:`number`,value:y??(x===null?``:String(x))}),f?(0,Z.jsx)(`span`,{className:`caps-number-field-unit`,"aria-hidden":`true`,children:f}):null]}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`icon`,className:`caps-number-field-increment`,"aria-label":i,"aria-controls":h.id,tabIndex:-1,disabled:k||O&&!m,onClick:()=>{E(1)},children:(0,Z.jsx)(hm,{"aria-hidden":`true`})})]})}),Q_=(0,X.forwardRef)(function({className:e,invalid:t,...n},r){return(0,Z.jsxs)(`span`,{className:`caps-select-shell`,children:[(0,Z.jsx)(`select`,{...n,"aria-invalid":t?!0:n[`aria-invalid`]===!1?void 0:n[`aria-invalid`],className:B(`select select-bordered caps-select w-full`,t&&`select-error`,e),ref:r}),!n.multiple&&(!n.size||n.size<=1)?(0,Z.jsx)(am,{className:`caps-select-chevron`,"aria-hidden":`true`}):null]})}),$_={2:`h2`,3:`h3`,4:`h4`};function ev(e,t){let{reduced:n}=t,r=e&&!n,i=_n(t,600),[a,o]=(0,X.useState)(r);return(0,X.useEffect)(()=>{if(o(r),!r)return;let e=globalThis.setTimeout(()=>{o(!1)},i);return()=>{globalThis.clearTimeout(e)}},[r,i]),a}var tv=(0,Z.jsx)(rt,{decorative:!0,pace:`idle`,size:`md`,tone:`primary`,variant:`wander`}),nv=(0,X.forwardRef)(function({actions:e,secondaryAction:t,className:n,description:r,headingLevel:i=2,primaryAction:a,suggestions:o,thinking:s=!1,title:c,visual:l,renderVisual:u,variant:d=`plain`,...f},p){let h=(0,X.useId)(),g=(0,X.useRef)(null),_=m(g),v=ev(d===`speech`,_)&&!s,y=$_[i],b=l??(d===`panel`?`blobs`:void 0),x=u?u({speaking:v,thinking:s}):b===`blobs`?tv:b,S=`${h}-reason`,C=(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(y,{ref:g,className:`empty-state-title`,id:f[`aria-labelledby`]?void 0:h,children:c}),(0,Z.jsx)(`p`,{children:r}),a?(0,Z.jsxs)(`div`,{className:`empty-state-primary`,children:[(0,Z.jsxs)(`div`,{className:`empty-state-action-row`,children:[(0,Z.jsx)(Y,{"aria-describedby":a.disabled&&a.disabledReason?S:void 0,disabled:a.disabled,loading:a.pending===!0,onClick:a.onSelect,variant:`primary`,children:a.label}),t]}),a.disabled&&a.disabledReason?(0,Z.jsx)(`span`,{className:`empty-state-reason`,id:S,children:a.disabledReason}):null]}):null,o&&o.length>0?(0,Z.jsx)(`ul`,{"aria-label":`Try one of these`,className:`empty-state-suggestions`,children:o.map((e,t)=>(0,Z.jsx)(`li`,{children:(0,Z.jsx)(Y,{disabled:e.disabled,loading:e.pending===!0,size:`sm`,variant:`outline`,onClick:e.onSelect,children:e.label})},`${String(t)}:${e.label}`))}):null,e?(0,Z.jsx)(`div`,{className:`empty-state-actions`,children:e}):null]});return(0,Z.jsxs)(`section`,{...f,"aria-labelledby":f[`aria-labelledby`]??h,className:B(`empty-state`,d!==`plain`&&`empty-state-${d}`,n),ref:p,children:[x?(0,Z.jsx)(`div`,{"aria-hidden":`true`,className:`empty-state-visual`,children:x}):null,d===`speech`?(0,Z.jsx)(`div`,{className:`empty-state-bubble`,children:C}):C]})}),rv=8e3,iv=(0,X.forwardRef)(function({className:e,detail:t,framed:n=!0,icon:r,message:i,onRetry:a,size:o=`md`,slowAfterMs:s=rv,variant:c=`line`,...l},u){let[d,f]=(0,X.useState)(!1);return(0,X.useEffect)(()=>{if(f(!1),!Number.isFinite(s))return;let e=globalThis.setTimeout(()=>{f(!0)},s);return()=>{globalThis.clearTimeout(e)}},[s,i]),(0,Z.jsxs)(`div`,{...l,className:B(`caps-loading-state`,e),"data-framed":n?void 0:`false`,"data-icon":r?``:void 0,"data-size":o,"data-slow":d||void 0,ref:u,role:`status`,children:[r?(0,Z.jsx)(`span`,{"aria-hidden":`true`,className:`caps-loading-state-icon`,children:r}):null,(0,Z.jsx)(rt,{decorative:!0,size:o,variant:c}),(0,Z.jsxs)(`span`,{className:`caps-loading-state-copy`,children:[(0,Z.jsx)(`span`,{children:i}),t?(0,Z.jsx)(`span`,{className:`caps-loading-state-detail`,children:t}):null,d?(0,Z.jsx)(`span`,{className:`caps-loading-state-detail`,children:`Still working…`}):null]}),d&&a?(0,Z.jsx)(Y,{className:`caps-loading-state-retry`,size:`sm`,variant:`outline`,onClick:a,children:`Retry`}):null]})});function av(e,t){return{kind:`button`,id:`folder`,text:t.checking?`Checking…`:`prints`,icon:`folder`,title:e===null?`Choose where Prints saves images`:Cn(`Save prints to ${e}`,1024),opens:`dialog`,expanded:t.editing}}function ov(e,t=/Mac|iPhone|iPad/u.test(globalThis.navigator.userAgent)){if(e.startsWith(`<leader>`)){let t=e.replaceAll(`<leader>`,`Ctrl K `).trimEnd();return e.endsWith(` `)?`${t} Space`:t}return e.split(` `).map(e=>e.split(`+`).map(e=>e===`mod`?t?`⌘`:`Ctrl`:e===`escape`?`Esc`:e.length===1?e.toUpperCase():e.charAt(0).toUpperCase()+e.slice(1)).join(e===`ctrl+k`||e===`mod+k`?` `:`+`)).join(` `)}function sv(e){let t=new Map;for(let n of e.bindings)t.set(n.commandId,[...t.get(n.commandId)??[],ov(n.binding)]);return e.slash.map(e=>({alias:e.alias,commandId:e.commandId,command:e.command,title:e.title,description:e.description,category:e.category,order:e.order,grammar:e.arguments,consumesDraft:e.consumesDraft,keys:t.get(e.commandId)??[],availability:e.availability}))}function cv(e,t){let n=e.toLocaleLowerCase(),r=t.toLocaleLowerCase();if(r.length===0)return{tier:0,spread:0,indices:[]};let i=e=>Array.from({length:r.length},(t,n)=>e+n);if(n.startsWith(r))return{tier:0,spread:n.length-r.length,indices:i(0)};let a=n.search(RegExp(`[-_\\s]${r.replaceAll(/[.*+?^${}()|[\]\\]/gu,`\\$&`)}`,`u`));if(a>=0)return{tier:1,spread:a,indices:i(a+1)};let o=n.indexOf(r);if(o>=0)return{tier:2,spread:o,indices:i(o)};let s=[],c=0;for(let e of r){let t=n.indexOf(e,c);if(t<0)return;s.push(t),c=t+1}let l=s[0]??0;return{tier:3,spread:(s.at(-1)??0)-l-r.length+1,indices:s}}function lv(e,t,n,r){return e.map(e=>({entry:e,match:cv(t(e),n)})).filter(e=>e.match!==void 0).sort((e,n)=>e.match.tier-n.match.tier||e.match.spread-n.match.spread||r(e.entry)-r(n.entry)||t(e.entry).localeCompare(t(n.entry))).map(({entry:e,match:t})=>({entry:e,indices:t.indices}))}var uv=[`help`,`login`,`model`];function dv(e,t,n={}){if(!t.startsWith(`/`)||t.includes(`
|
|
3
|
+
`))return{kind:`none`};let r=t.search(/\s/u);if(r<0){let r=t.slice(1);return{kind:`commands`,query:r,items:lv(e.filter(e=>e.availability.status===`available`&&(r.length===0?e.category===(n.idleCategory??`Conversation`)||uv.includes(e.alias):e.category!==`Advanced`||e.alias.toLocaleLowerCase().startsWith(r.toLocaleLowerCase()))),e=>e.alias,r,e=>{let t=uv.indexOf(e.alias);return r.length===0&&t>=0?t-uv.length:e.order}).map(({entry:e,indices:t})=>({command:e,label:`/${e.alias}`,matches:t.map(e=>e+1),insert:e.grammar===void 0?`/${e.alias}`:`/${e.alias} `}))}}let i=t.slice(1,r),a=e.find(e=>e.alias===i);if(a?.grammar===void 0||a.availability.status!==`available`)return{kind:`none`};let o=t.slice(r).trimStart(),s=(o.includes(` `)?[]:a.grammar.words??[]).filter(e=>e.word.toLocaleLowerCase().startsWith(o.toLocaleLowerCase())).map(e=>({word:e,label:e.word,matches:Array.from({length:o.length},(e,t)=>t),insert:`/${i} ${e.word}`}));return{kind:`arguments`,command:a,query:o,hint:`/${i} ${a.grammar.hint}`,items:s}}var fv=Hd({keyCode:Wd(229)});function pv(e){return e.nativeEvent.isComposing||Tt(fv,e.nativeEvent).success}function mv(e,t){return e.animate(t.reduced?[{opacity:1},{opacity:0}]:[{opacity:1,transform:`none`},{opacity:0,transform:`translateY(-120%)`}],{duration:t.reduced?t.fast:t.normal,easing:de(t,t.easeExit),fill:`backwards`})}function hv(e,t){let n=-12*Math.min(1.5,t.bounce/.3);return e.animate(t.reduced?[{opacity:0},{opacity:1}]:[{opacity:0,transform:`translateY(70%)`},{opacity:1,transform:`translateY(${String(n)}%)`,offset:.6},{opacity:1,transform:`none`}],{duration:t.reduced?t.fast:t.springDuration,easing:de(t,t.ease),fill:`backwards`})}function gv(e,t,n){return e.animate([{opacity:1-n},{opacity:n}],{duration:t.reduced?t.fast:t.normal,delay:n===1&&!t.reduced?t.fast/2:0,easing:de(t,t.ease),fill:`backwards`})}function _v(e,t){let n=1+.05*Math.min(1.5,.4+t.bounce/.3);return e.animate([{transform:`scale(1)`},{transform:`scale(${String(n)})`,offset:.4},{transform:`scale(1)`}],{duration:t.springDuration,easing:de(t,`ease-out`)})}var vv=(0,X.forwardRef)(function({state:e,onStop:t,stopLabel:n=`Stop`,iconSize:r=20,onClick:i,disabled:a,className:o,tone:s=`primary`,"aria-label":c,...l},u){let d=(0,X.useRef)(null);(0,X.useImperativeHandle)(u,()=>d.current);let f=(0,X.useRef)(e);(0,X.useLayoutEffect)(()=>{let t=d.current,n=f.current;if(f.current=e,!t||n===e||!He(t))return;let r=t.querySelector(`[data-glyph="arrow"]`),i=t.querySelector(`[data-glyph="busy"]`);if(!r||!i)return;let a=he(t),o=[];return e===`busy`?o.push(mv(r,a),gv(i,a,1)):n===`busy`&&o.push(gv(i,a,0),hv(r,a)),n===`empty`&&e===`ready`&&!a.reduced&&o.push(_v(t,a)),()=>{for(let e of o)e.cancel()}},[e]);let p=e===`busy`,m=p&&t!==void 0;return(0,Z.jsx)(wt,{...l,ref:d,className:B(`caps-send-action`,o),tone:s,"aria-busy":p?!0:void 0,"aria-label":m?n:c,"data-send-state":e,disabled:a===!0||e===`empty`||p&&!m,onClick:m?t:i,label:null,icon:(0,Z.jsxs)(`span`,{className:`caps-send-glyph`,"data-state":e,children:[(0,Z.jsx)(`span`,{"data-glyph":`arrow`,children:(0,Z.jsx)(im,{"aria-hidden":`true`,size:r})}),(0,Z.jsx)(`span`,{"data-glyph":`busy`,children:t===void 0?(0,Z.jsx)(rt,{decorative:!0,size:`sm`}):(0,Z.jsx)(_m,{"aria-hidden":`true`,fill:`currentColor`,size:Math.round(r*.7)})})]})})}),yv=(0,X.forwardRef)(function({className:e,label:t,...n},r){return(0,Z.jsx)(wt,{...n,ref:r,className:B(`parakeet-composer-model-key`,e),label:t,readout:(0,Z.jsx)(am,{"aria-hidden":`true`,className:`size-[var(--stipe-icon-size-sm)] shrink-0`})})}),bv=(0,X.forwardRef)(function({className:e,...t},n){return(0,Z.jsx)(`div`,{...t,ref:n,className:B(`caps-popover-anchor`,e)})}),xv=(0,X.forwardRef)(function({className:e,open:t,side:n=`top`,...r},i){return t?(0,Z.jsx)(`div`,{...r,ref:i,className:B(`caps-popover`,e),"data-side":n}):null}),Sv=(0,X.forwardRef)(function({active:e,className:t,onMouseDown:n,...r},i){return(0,Z.jsx)(`div`,{role:`option`,"aria-selected":e,...r,ref:i,className:B(`caps-popover-option`,t),"data-active":e,onMouseDown:e=>{e.preventDefault(),n?.(e)}})});function Cv({items:e,openId:t,onOpenChange:n,leading:r,trailing:i,renderTrigger:a,placement:o=`housing`,align:s=`end`,hostInset:c,className:l,...u}){let d=(0,X.useId)(),f=(0,X.useRef)(null),p=(0,X.useRef)(null),m=(0,X.useRef)(new Map),h=e.find(e=>e.id===t&&!e.disabled),g=h?.id,_=()=>{g&&m.current.get(g)?.focus(),n(null)};return(0,X.useEffect)(()=>{g&&p.current?.focus()},[g]),(0,X.useEffect)(()=>{c===void 0?f.current?.style.removeProperty(`--caps-status-tray-host-inset`):f.current?.style.setProperty(`--caps-status-tray-host-inset`,`${String(Math.max(0,c))}px`)},[c]),(0,X.useEffect)(()=>{if(!g)return;let e=e=>{e.key!==`Escape`||e.defaultPrevented||(e.preventDefault(),m.current.get(g)?.focus(),n(null))},t=e=>{e.target instanceof Node&&!f.current?.contains(e.target)&&n(null)};return document.addEventListener(`keydown`,e),document.addEventListener(`pointerdown`,t),()=>{document.removeEventListener(`keydown`,e),document.removeEventListener(`pointerdown`,t)}},[g,n]),(0,Z.jsxs)(bv,{...u,ref:f,className:B(`caps-status-tray`,l),"data-placement":o,"data-align":s,children:[h?(0,Z.jsxs)(xv,{open:!0,ref:p,tabIndex:-1,side:`top`,id:`${d}-${h.id}`,role:`dialog`,"aria-labelledby":`${d}-title`,className:`caps-status-tray-panel`,"data-status-tray-panel":h.id,children:[(0,Z.jsxs)(`div`,{className:`caps-status-tray-head`,children:[h.tone?(0,Z.jsx)(np,{size:`compact`,tone:h.tone,glyph:h.glyph??`dot`}):null,(0,Z.jsx)(`span`,{id:`${d}-title`,className:`caps-status-tray-title`,children:h.title??h.label}),h.actions,(0,Z.jsx)(ln,{"aria-label":`Close tray`,icon:(0,Z.jsx)(Xi,{"aria-hidden":`true`}),onClick:_})]}),(0,Z.jsx)(`div`,{className:`caps-status-tray-body`,children:h.content})]}):null,o===`host`?null:(0,Z.jsxs)(`div`,{className:`caps-status-tray-row`,children:[r,(0,Z.jsx)(`div`,{className:`caps-status-tray-chips`,children:e.map(e=>{let r={ref:t=>{t?m.current.set(e.id,t):m.current.delete(e.id)},type:`button`,className:a?void 0:`caps-status-tray-chip`,"aria-expanded":g===e.id,"aria-controls":g===e.id?`${d}-${e.id}`:void 0,"aria-label":e.accessibleLabel,disabled:e.disabled,title:e.disabled?e.accessibleLabel:void 0,"aria-haspopup":`dialog`,"data-status-tray-chip":e.id,onClick:()=>{n(t===e.id?null:e.id)},children:(0,Z.jsxs)(Z.Fragment,{children:[e.tone?(0,Z.jsx)(np,{size:`compact`,glyph:e.glyph??`dot`,motion:e.motion??`none`,tone:e.tone}):null,(0,Z.jsx)(`span`,{className:`caps-status-tray-label`,children:e.label}),e.count!==void 0&&e.count>0?(0,Z.jsx)(`span`,{className:`caps-status-tray-count`,children:e.count}):null]})};return(0,Z.jsxs)(X.Fragment,{children:[a?a(r):(0,Z.jsx)(`button`,{...r}),e.after]},e.id)})}),i]})]})}function wv({children:e,className:t,...n}){return(0,Z.jsx)(`div`,{...n,className:B(`caps-status-tray-list`,t),children:e})}function Tv({icon:e,primary:t,secondary:n,actions:r,className:i,...a}){return(0,Z.jsxs)(`div`,{...a,className:B(`caps-status-tray-item`,i),children:[e?(0,Z.jsx)(`span`,{className:`caps-status-tray-icon`,children:e}):null,(0,Z.jsxs)(`span`,{className:`caps-status-tray-text`,children:[(0,Z.jsx)(`span`,{className:`caps-status-tray-primary`,children:t}),n?(0,Z.jsx)(`span`,{className:`caps-status-tray-secondary`,children:n}):null]}),r?(0,Z.jsx)(`span`,{className:`caps-status-tray-actions`,children:r}):null]})}function Ev({children:e=`All caught up.`,title:t}){return(0,Z.jsxs)(`div`,{className:`caps-status-tray-note`,children:[t?(0,Z.jsx)(`strong`,{className:`caps-status-tray-note-title`,children:t}):null,(0,Z.jsx)(`p`,{children:e})]})}var Dv=(0,X.forwardRef)(function({className:e,invalid:t,...n},r){return(0,Z.jsx)(`textarea`,{...n,"aria-invalid":t?!0:n[`aria-invalid`]===!1?void 0:n[`aria-invalid`],className:B(`textarea textarea-bordered w-full`,t&&`textarea-error`,e),ref:r})});function Ov(e,t){return`${e}-${String(t)}`}function kv(e){switch(e.key){case`ArrowDown`:return`next`;case`ArrowUp`:return`previous`;case`Enter`:return e.shiftKey?null:`accept`;case`Tab`:return`accept`;case`Escape`:return`dismiss`;default:return null}}function Av(e){return{role:`combobox`,"aria-autocomplete":`list`,"aria-expanded":e.open,"aria-controls":e.open?e.listId:void 0,"aria-activedescendant":e.open?Ov(e.listId,e.selected):void 0}}function jv({open:e,rows:t,selected:n,listId:r,label:i,kind:a,hint:o,empty:s,onHighlight:c,onChoose:l}){return(0,Z.jsx)(xv,{open:e,side:`top`,"data-parakeet-slash":``,children:(0,Z.jsxs)(`div`,{className:`parakeet-slash-menu`,"data-kind":a,children:[o===void 0?null:(0,Z.jsx)(`p`,{className:`parakeet-slash-hint`,children:o}),t.length===0?s===void 0?null:(0,Z.jsx)(`p`,{className:`parakeet-slash-hint`,children:s}):(0,Z.jsx)(`div`,{id:r,role:`listbox`,"aria-label":i,children:t.map((e,t)=>(0,Z.jsxs)(Sv,{id:Ov(r,t),active:t===n,"aria-disabled":e.disabled===!0||void 0,"data-disabled":e.disabled===!0,onMouseEnter:()=>{c(t)},onClick:()=>{l(t)},children:[e.media===void 0?null:(0,Z.jsx)(`span`,{"aria-hidden":`true`,className:`parakeet-slash-media`,children:e.media}),(0,Z.jsx)(`span`,{className:`parakeet-slash-label`,children:e.label}),(0,Z.jsx)(`span`,{className:`parakeet-slash-detail`,children:e.detail}),e.keys===void 0||e.keys.length===0?null:(0,Z.jsx)(`kbd`,{className:`parakeet-slash-keys`,children:e.keys})]},e.key))})]})})}var Mv={unchecked:`M3.25 5.9 L5.1 7.9 L8.8 3.8`,checked:`M3.25 5.9 L5.1 7.9 L8.8 3.8`,mixed:`M3.4 6 L6 6 L8.6 6`},Nv={blurStdDeviation:.22,alphaSlope:18,alphaIntercept:-8};function Pv({state:e}){let t=`caps-checkbox-${(0,X.useId)().replaceAll(`:`,``)}`,n=(0,X.useRef)(null),r=(0,X.useRef)(e).current,i=(0,X.useRef)(e),a=d();return(0,X.useLayoutEffect)(()=>{if(!n.current)return;let t=e!==`unchecked`,r=i.current!==`unchecked`,o=a||i.current===e;i.current=e;let s=he(n.current),c=ia(s,{ease:`inCubic`,duration:160}),l=Ma(n.current,{d:{to:Mv[e],...o?_a:ia(s,{ease:`outCubic`,duration:200})},"stroke-dashoffset":{to:+!t,...o?_a:t?ia(s,{ease:`inOutSine`,duration:260}):c},"stroke-width":o?{to:t?2.4:0,duration:0}:t&&!r?[{to:2.2,...ia(s,{ease:`outCubic`,duration:65})},{to:2.4,delay:_n(s,120),...Wi(s,{bounce:.35,duration:220})}]:{to:t?2.4:0,...c}});return()=>{l.cancel()}},[e,a]),(0,Z.jsxs)(`svg`,{className:`caps-checkbox-visual`,width:`24`,height:`24`,viewBox:`0 0 12 12`,"aria-hidden":`true`,focusable:`false`,children:[(0,Z.jsxs)(`defs`,{children:[(0,Z.jsx)(Le,{id:`${t}-surface`,transform:`matrix(1 0 0 1 6 6)`}),(0,Z.jsx)(ct,{id:`${t}-shadow`}),(0,Z.jsx)(dt,{id:`${t}-inset`}),(0,Z.jsx)(kt,{id:`${t}-goo`,values:Nv}),(0,Z.jsxs)(`filter`,{id:`${t}-relief`,x:`-25%`,y:`-25%`,width:`150%`,height:`150%`,colorInterpolationFilters:`sRGB`,children:[(0,Z.jsx)(`feGaussianBlur`,{in:`SourceAlpha`,stdDeviation:`0.28`,result:`relief`}),(0,Z.jsx)(`feSpecularLighting`,{in:`relief`,surfaceScale:`1.2`,specularConstant:`0.55`,specularExponent:`18`,lightingColor:`color-mix(in srgb, var(--color-white) calc(var(--depth) * 100%), var(--color-black))`,result:`light`,children:(0,Z.jsx)(`feDistantLight`,{azimuth:`225`,elevation:`55`})}),(0,Z.jsx)(`feComposite`,{in:`light`,in2:`SourceAlpha`,operator:`in`,result:`clipped-light`}),(0,Z.jsx)(`feBlend`,{in:`SourceGraphic`,in2:`clipped-light`,mode:`screen`})]}),(0,Z.jsx)(`mask`,{id:`${t}-contour`,maskUnits:`userSpaceOnUse`,x:`0`,y:`0`,width:`12`,height:`12`,style:{maskType:`alpha`},children:(0,Z.jsx)(`path`,{ref:n,d:Mv[r],fill:`none`,stroke:`var(--color-white)`,strokeWidth:r===`unchecked`?0:2.4,pathLength:`1`,strokeDasharray:`1`,strokeDashoffset:+(r===`unchecked`),strokeLinecap:`round`,strokeLinejoin:`round`,filter:e===`mixed`?void 0:`url(#${t}-goo)`})}),(0,Z.jsx)(`clipPath`,{id:`${t}-well`,children:(0,Z.jsx)(`rect`,{x:`1`,y:`1`,width:`10`,height:`10`,rx:`2.5`})})]}),(0,Z.jsx)(`rect`,{className:`caps-checkbox-track`,x:`0.5`,y:`0.5`,width:`11`,height:`11`,rx:`3`,filter:`url(#${t}-inset)`}),(0,Z.jsx)(`g`,{clipPath:`url(#${t}-well)`,children:(0,Z.jsx)(`g`,{filter:`url(#${t}-shadow)`,children:(0,Z.jsx)(`g`,{filter:`url(#${t}-relief)`,children:(0,Z.jsx)(`g`,{mask:`url(#${t}-contour)`,children:(0,Z.jsx)(`rect`,{x:`0`,y:`0`,width:`12`,height:`12`,fill:`url(#${t}-surface)`})})})})})]})}var Fv=(0,X.forwardRef)(function({className:e,appearance:t,indicator:n,invalid:r,indeterminate:i=!1,checked:a,defaultChecked:o=!1,onChange:s,...c},l){let u=(0,X.useRef)(null),[d,f]=(0,X.useState)(o),p=a??d,m=i?`mixed`:p?`checked`:`unchecked`;return(0,X.useImperativeHandle)(l,()=>{if(!u.current)throw Error(`Checkbox input is not mounted`);return u.current},[]),(0,X.useLayoutEffect)(()=>{u.current&&(u.current.indeterminate=i)},[i]),(0,X.useEffect)(()=>{let e=u.current?.form;if(!e||a!==void 0)return;let t=e=>{queueMicrotask(()=>{!e.defaultPrevented&&u.current&&f(o)})};return e.addEventListener(`reset`,t),()=>{e.removeEventListener(`reset`,t)}},[a,o,c.form]),(0,Z.jsxs)(`span`,{className:`caps-checkbox`,"data-appearance":t===`compact`?t:void 0,"data-state":m,"data-custom-indicator":n!==void 0||void 0,children:[(0,Z.jsx)(`input`,{...c,checked:p,"aria-checked":i?`mixed`:p,"aria-invalid":r?!0:c[`aria-invalid`]===!1?void 0:c[`aria-invalid`],className:B(`caps-checkbox-input`,e),onChange:e=>{a===void 0&&f(e.target.checked),s?.(e),e.currentTarget.indeterminate=i},ref:u,type:`checkbox`}),n===void 0?(0,Z.jsx)(Pv,{state:m}):n]})});function Iv({getKey:e,isDisabled:t=()=>!1,items:n}){let r=(0,X.useMemo)(()=>{let r=n.map(e);if(r.some(e=>!e))throw Error(`Selectable items require non-empty keys`);if(new Set(r).size!==r.length)throw Error(`Selectable items require unique keys`);return n.filter(e=>!t(e))},[e,t,n]),[i,a]=(0,X.useState)(null);(0,X.useEffect)(()=>{i!==null&&!r.some(t=>e(t)===i)&&a(null)},[i,r,e]);let o=r.find(t=>e(t)===i),s=o?r.findIndex(t=>e(t)===i):-1;return{activeIndex:s,activeItem:o,activeKey:i,enabledItems:r,move:(t,n)=>{if(r.length===0)return;let i=n?n===`start`?0:r.length-1:s<0?t>0?0:r.length-1:(s+t+r.length)%r.length,o=r[i];o&&a(e(o))},setActiveKey:a}}var Lv=a(`card caps-card`,{variants:{variant:{surface:`caps-card-surface`,outline:`caps-card-outline`,interactive:`caps-card-interactive`,game:`caps-card-game caps-card-interactive`,fit:`caps-card-fit`},density:{regular:``,compact:`caps-card-compact`}},defaultVariants:{variant:`surface`,density:`regular`}}),Rv=(0,X.forwardRef)(function({className:e,density:t,featured:n=!1,state:r,variant:i,...a},o){return(0,Z.jsx)(`div`,{...a,className:B(Lv({density:t,variant:i}),n&&`caps-card-featured`,e),"data-state":r,ref:o})});(0,X.forwardRef)(function({className:e,density:t,variant:n,width:r=`default`,...i},a){return(0,Z.jsx)(`main`,{className:`caps-centered-card-stage`,children:(0,Z.jsx)(Rv,{...i,className:B(`caps-centered-card`,r===`wide`&&`caps-centered-card-wide`,e),ref:a,variant:n??`surface`,...t?{density:t}:{}})})}),(0,X.forwardRef)(function({alignment:e=`start`,className:t,...n},r){return(0,Z.jsx)(`div`,{...n,className:B(`caps-card-header`,e===`center`&&`caps-card-header-centered`,t),ref:r})}),(0,X.forwardRef)(function({className:e,level:t=3,...n},r){return(0,Z.jsx)(t===2?`h2`:`h3`,{...n,className:B(`caps-card-title`,e),ref:r})}),(0,X.forwardRef)(function({className:e,...t},n){return(0,Z.jsx)(`p`,{...t,className:B(`caps-card-description`,e),ref:n})}),(0,X.forwardRef)(function({className:e,...t},n){return(0,Z.jsx)(`div`,{...t,className:B(`caps-card-content`,e),ref:n})}),(0,X.forwardRef)(function({className:e,...t},n){return(0,Z.jsx)(`div`,{...t,className:B(`caps-card-footer`,e),ref:n})});var zv=(0,X.forwardRef)(function({action:e,attachments:t,className:n,input:r,toolbar:i,...a},o){return(0,Z.jsxs)(`div`,{...a,ref:o,className:B(`caps-composer`,n),children:[t===void 0?null:(0,Z.jsx)(`div`,{className:`caps-composer-attachments`,children:t}),(0,Z.jsx)(`div`,{className:`caps-composer-input`,children:r}),i===void 0&&e===void 0?null:(0,Z.jsxs)(`div`,{className:`caps-composer-bar`,children:[(0,Z.jsx)(`div`,{className:`caps-composer-toolbar`,children:i}),e]})]})});function Bv({draft:e,hasAttachments:t=!1,busy:n,queueWhileBusy:r=!1,blocked:i=!1}){let a=!i&&(e.trim().length>0||t);return n&&(!r||!a)?`busy`:a?`ready`:`empty`}function Vv({attachments:e,action:t,children:n,className:r,input:i,menu:a,row:o,...s}){return(0,Z.jsxs)(bv,{className:`parakeet-composer-anchor`,children:[a,(0,Z.jsxs)(Rv,{...s,className:B(`parakeet-composer-shell`,r),children:[(0,Z.jsx)(zv,{action:t,attachments:e,input:i,toolbar:o===void 0?void 0:(0,Z.jsx)(Cv,{className:`parakeet-composer-row`,align:`start`,items:o.items,openId:o.openId,onOpenChange:o.onOpenChange,renderTrigger:({children:e,...t})=>(0,Z.jsx)(wt,{...t,label:e,expanded:t[`aria-expanded`]===!0}),leading:o.controls,trailing:(0,Z.jsxs)(`span`,{className:`parakeet-composer-trailing`,children:[o.status,o.readout==null?null:(0,Z.jsx)(`span`,{className:`parakeet-composer-readout`,children:o.readout}),(0,Z.jsx)(`span`,{className:`parakeet-composer-action`,children:o.action})]})})}),n]})]})}function Hv(e,t){(0,X.useLayoutEffect)(()=>{let t=e.current;t&&(t.style.height=`auto`,t.style.height=`${String(t.scrollHeight)}px`)},[e,t])}function Uv({disabled:e,emptyLabel:t,models:n,onChange:r,value:i}){let a=n.find(e=>e.id===i),[o,s]=(0,X.useState)(null);return(0,Z.jsx)(`span`,{className:`contents`,ref:s,children:(0,Z.jsxs)(ei,{children:[(0,Z.jsx)(zr,{"aria-label":`Generation model`,"data-generation-model":i,disabled:e||n.length===0,render:(e,n)=>(0,Z.jsx)(yv,{...e,expanded:n.open,label:a===void 0?t:Fi(a)})}),(0,Z.jsx)(Tr,{"data-generation-model-menu":!0,container:o,side:`top`,align:`start`,"aria-label":`Generation models`,children:n.map(e=>(0,Z.jsx)(Sr,{"data-generation-model-option":e.id,checked:e.id===i,closeOnClick:!0,onSelect:()=>{r(e.id)},children:Fi(e)},e.id))})]})})}function Wv(e){let t=Ld(e),n=(0,X.useRef)(e);n.current=e;let r=Qt(),i=la(Ui(e)),a=Go(Lm(e,i.data?.configured?i.data.path:null)),[o,s]=(0,X.useState)(null),c=n=>n?.app===e&&n.computerId===t,l=ve({mutationKey:oa.folder(e),mutationFn:async({owner:e,id:t,path:r,create:i})=>{let a=()=>{if(n.current!==e||e.context.get().computerId!==t)throw new J(`Computer selection changed`,{code:`SELECTION_CHANGED`,retryable:!1})};return a(),i&&await e.capabilities.require(Ur).mkdir({path:r}),a(),await Xr(e.capabilities,{path:r,limit:1,offset:0}),a(),gi(e.capabilities,{operation:`select-folder`,computerId:t,path:r})},onSuccess:(e,t)=>{t.owner===n.current&&t.owner.context.get().computerId===t.id&&s(null)},onSettled:(e,t,n)=>Promise.all([r.invalidateQueries({queryKey:n.queryKey,exact:!0}),r.invalidateQueries({queryKey:Im.listing(n.owner,n.path),exact:!0})])}),u=l.variables?.owner===e&&l.variables.id===t,d=i.isFetching||u&&l.isPending,f=async(n,r)=>{if(!e||!t||d)return`Computer selection changed. Try again.`;let i=n.trim();if(!z(di)(i))return`Enter an absolute Computer folder, such as /media.`;try{return await l.mutateAsync({owner:e,id:t,path:i,create:r,queryKey:oa.folder(e)}),null}catch{return`Could not use this folder. Check its location and your Computer permissions.`}},p=i.isError||a.isError;return{path:p?null:i.data?.path??null,galleryPath:p||!i.data?.configured?null:i.data.path,computerId:t,available:e?.capabilities.has(qi)===!0,writable:e?.capabilities.has(Ur)===!0,busy:d,error:p?`Your media folder is unavailable. Choose or create a folder.`:null,editing:c(o),setEditing:n=>{s(n?{app:e,computerId:t}:null)},choose:f,ensureCreated:async()=>i.data?i.data.configured?null:f(i.data.path,!0):`Your Prints library is still loading.`,recheck:()=>{r.invalidateQueries({queryKey:Im.listing(e,i.data?.path??null),exact:!0}),r.invalidateQueries({queryKey:oa.folder(e),exact:!0})}}}var Gv=V(Tn),Kv=V(Ue({message:Tn}));function qv(e){for(let t of e.errors){let e=fn(Mt(ot(Kv(t),e=>e.message),()=>Gv(t)));if(e!==void 0&&e.length>0)return e}}var Jv={neutral:`progress-neutral`,primary:`progress-primary`,secondary:`progress-secondary`,accent:`progress-accent`,success:`progress-success`,info:`progress-info`,warning:`progress-warning`,error:`progress-error`},Yv=(0,X.forwardRef)(function({className:e,tone:t=`primary`,...n},r){return(0,Z.jsx)(`progress`,{...n,"data-complete":n.value!==void 0&&Number(n.value)>=Number(n.max??1)?`true`:void 0,className:B(`progress caps-gooey-motion caps-gooey-progress w-full`,Jv[t],e),ref:r})});(0,X.forwardRef)(function({label:e,value:t,max:n,tone:r=`info`,className:i,...a},o){return(0,Z.jsxs)(`div`,{...a,ref:o,className:B(`caps-game-meter`,i),children:[(0,Z.jsxs)(`div`,{className:`caps-game-meter-readout`,children:[(0,Z.jsx)(`span`,{children:e}),(0,Z.jsxs)(`span`,{className:`caps-game-meter-value`,children:[t,` / `,n]})]}),(0,Z.jsx)(Yv,{"aria-label":e,value:t,max:n,tone:r})]})});function Xv({className:e,items:t,onCancel:n,onRemove:r,onRetry:i,rowClassName:a}){return t.length?(0,Z.jsx)(`div`,{"aria-live":`polite`,className:`caps-upload-queue flex w-full min-w-0 flex-col gap-sm ${e??``}`,"data-upload-rows":!0,children:t.map(e=>(0,Z.jsx)($v,{item:e,onCancel:n,onRemove:r,onRetry:i,...a===void 0?{}:{rowClassName:a}},e.id))}):null}function Zv({action:e,id:t,onAction:n,retry:r=!1}){return e?(0,Z.jsx)(ln,{"aria-label":e.accessibleLabel,title:e.label,variant:`ghost`,size:`xs`,className:`motion-reduce:transition-none`,icon:r?(0,Z.jsx)(ba,{}):(0,Z.jsx)(Xi,{}),onClick:()=>void n(t),type:`button`}):null}function Qv({item:e}){return(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`span`,{className:`block min-w-0 truncate`,title:e.name,children:e.name}),(0,Z.jsx)(`div`,{className:`caps-upload-details`,children:(0,Z.jsxs)(`span`,{"aria-live":e.alert?`assertive`:void 0,className:`caps-upload-status min-w-0 break-words`,"data-upload-status":!0,role:e.alert?`alert`:void 0,children:[e.alert??e.statusLabel,` `,e.progressLabel]})})]})}function $v({item:e,onCancel:t,onRemove:n,onRetry:r,rowClassName:i}){return(0,Z.jsxs)(`div`,{className:`caps-upload-row grid w-full min-w-0 max-w-full grid-cols-[2rem_minmax(0,1fr)_auto] items-center gap-sm p-sm text-xs ${i??``}`,children:[e.preview.kind===`image`?(0,Z.jsx)(`img`,{alt:``,className:`caps-upload-preview mask mask-squircle size-8 shrink-0 object-cover`,src:e.preview.url}):(0,Z.jsx)(`span`,{"aria-hidden":`true`,className:`caps-upload-preview mask mask-squircle flex size-8 shrink-0 items-center justify-center bg-base-300`,children:(0,Z.jsx)(lm,{className:`size-4`})}),(0,Z.jsx)(Qv,{item:e}),(0,Z.jsx)(ey,{actions:e.actions,id:e.id,onCancel:t,onRemove:n,onRetry:r}),(0,Z.jsx)(Yv,{"aria-label":`${e.name} progress`,className:`caps-upload-progress`,tone:e.alert?`error`:e.progress===100?`success`:`accent`,max:100,value:e.progress??(e.alert?0:void 0)})]})}function ey({actions:e,id:t,onCancel:n,onRemove:r,onRetry:i}){return(0,Z.jsxs)(`div`,{className:`caps-upload-actions flex min-w-0 flex-wrap justify-end gap-xs`,children:[(0,Z.jsx)(Zv,{action:e.retry,id:t,onAction:i,retry:!0}),(0,Z.jsx)(Zv,{action:e.cancel,id:t,onAction:n}),(0,Z.jsx)(Zv,{action:e.remove,id:t,onAction:r})]})}var ty=X.createContext(void 0);function ny(e){let t=X.useContext(ty);if(t===void 0&&!e)throw Error(Pn(47));return t}var ry={...Wn,disabled:e=>e.disabled,instantType:e=>e.instantType===`trigger-change`&&!Wn.open(e)?void 0:e.instantType,openMethod:e=>e.openMethod,openChangeReason:e=>e.openChangeReason,isPressOpenedByTrigger:(e,t)=>e.openChangeReason===`trigger-press`&&Wn.isOpenedByTrigger(e,t),isTouchPressOpen:(e,t)=>t&&e.openMethod===`touch`&&e.openChangeReason===`trigger-press`,hasTriggerFocusGuards:(e,t)=>Wn.isOpenedByTrigger(e,t)&&!e.focusManagerModal,modal:e=>e.modal,titleElementId:e=>e.titleElementId,descriptionElementId:e=>e.descriptionElementId,openOnHover:e=>e.openOnHover,closeDelay:e=>e.closeDelay,adaptiveOrigin:e=>e.adaptiveOrigin},iy=class extends qn{constructor(e,t,n){let r=new lr;super(ay(e,r,t,n),oy(r),ry)}setOpen=(e,t)=>{let n=t.reason===ar,r=t.reason===`trigger-press`&&t.event.detail===0,i=!e&&(t.reason===`escape-key`||t.reason==null),a=dr(t),o=this.select(`activeTriggerId`);if(!e&&t.reason===`close-press`&&t.trigger==null&&o!=null&&(t.trigger=this.context.triggerElements.getById(o)??this.select(`activeTriggerElement`)??void 0),this.context.onOpenChange?.(e,t),t.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(e,t);let s=()=>{let n=Kn(this.state,e,t.trigger,a());n.openChangeReason=t.reason,this.update(n)};n?(this.context.stickIfOpen=!0,this.context.stickIfOpenTimeout.start(500,()=>{this.context.stickIfOpen=!1}),e_.flushSync(s)):s();let c;r?c=`click`:i?c=`dismiss`:t.reason===`focus-out`&&(c=`focus`),this.set(`instantType`,c)}};function ay(e,t,n,r=!1){let i={...Bn(t,n,r),disabled:!1,modal:!1,focusManagerModal:!1,instantType:void 0,openMethod:null,openChangeReason:null,titleElementId:void 0,descriptionElementId:void 0,openOnHover:!1,closeDelay:0,adaptiveOrigin:void 0,...e};return i.open&&e?.mounted===void 0&&(i.mounted=!0),i}function oy(e){return{popupRef:X.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerFocusTargetRef:X.createRef(),beforeTriggerFocusGuardRef:X.createRef(),beforeContentFocusGuardRef:X.createRef(),stickIfOpenTimeout:new Ar,stickIfOpen:!0,triggerElements:e}}var sy=nr(function({props:e}){let{children:t,open:n,defaultOpen:r=!1,onOpenChange:i,onOpenChangeComplete:a,modal:o=!1,handle:s,triggerId:c,defaultTriggerId:l=null}=e,u=ly(s,{modal:o,open:r,openProp:n,activeTriggerId:l,triggerIdProp:c});u.useControlledProp(`openProp`,n),u.useControlledProp(`triggerIdProp`,c);let d=u.useState(`open`),f=u.useState(`mounted`),p=u.useState(`payload`);u.useContextCallback(`onOpenChange`,i),u.useContextCallback(`onOpenChangeComplete`,a),mr(u,d),qr(u);let{forceUnmount:m}=Gn(d,u,()=>{u.context.stickIfOpen=!0,u.set(`openChangeReason`,null)});u.useSyncedValues({modal:o}),X.useEffect(()=>{d||u.context.stickIfOpenTimeout.clear()},[u,d]),X.useImperativeHandle(e.actionsRef,()=>({unmount:m,close:()=>u.setOpen(!1,ai(si))}),[m,u]);let h=d||f||s!=null;return(0,Z.jsxs)(ty.Provider,{value:u,children:[s&&(0,Z.jsx)(cr,{handle:s,store:u}),h&&(0,Z.jsx)(uy,{store:u,modal:o}),typeof t==`function`?t({payload:p}):t]})});function cy(e){return ny(!0)?(0,Z.jsx)(sy,{props:e}):(0,Z.jsx)(vr,{children:(0,Z.jsx)(sy,{props:e})})}function ly(e,t){let n=fr((e,n)=>new iy(t,e,n));return X.useEffect(()=>n.context.stickIfOpenTimeout.disposeEffect(),[n]),n}function uy({store:e,modal:t}){let n=e.useState(`floatingRootContext`),r=$r(n,{outsidePressEvent:{mouse:t===`trap-focus`?`sloppy`:`intentional`,touch:`sloppy`}}),i=r.reference,a=r.floating;return pr(e,{activeTriggerProps:i,inactiveTriggerProps:i,popupProps:a}),null}var dy=li(function(e,t){let{render:n,className:r,style:i,disabled:a=!1,nativeButton:o=!0,handle:s,payload:c,openOnHover:l=!1,delay:u=300,closeDelay:d=0,id:f,...p}=e,m=ny(!0),h=er(s)??m;if(!h)throw Error(Pn(74));let g=gr(f),_=h.useState(`isTriggerActive`,g),v=h.useState(`floatingRootContext`),y=h.useState(`isOpenedByTrigger`,g),b=h.useState(`triggerPopupId`,g),x=X.useRef(null),{registerTrigger:S,isMountedByThisTrigger:C}=tr(g,x,h,{payload:c,disabled:a,openOnHover:l,closeDelay:d}),w=h.useState(`isPressOpenedByTrigger`,g),T=h.useState(`isTouchPressOpen`,l),E=h.useState(`hasTriggerFocusGuards`,g),D=Yn(v,{enabled:!a&&l&&!T,mouseOnly:!0,move:!1,handleClose:Nr(),restMs:u,delay:{close:d},triggerElementRef:x,isActiveTrigger:_,isClosing:()=>h.select(`transitionStatus`)===`ending`}),O=Ln(()=>h.context.stickIfOpen),k=Hr(v,{stickIfOpen:O}),A=Rn(()=>h.select(`open`),e=>{h.set(`openMethod`,e)}),j=h.useState(`triggerProps`,C),{getButtonProps:M,buttonRef:N}=sr({disabled:a,native:o}),P={open(e){return w?Pr.open(e):Xn.open(e)}},{handlePreFocusGuardFocus:F,handleFocusTargetFocus:I}=Dr(h,x),ee=rr(`button`,e,{state:{disabled:a,open:y},ref:[N,t,S,x],props:[k.reference,D,j,A,{[xr]:``,id:g,"aria-haspopup":`dialog`,"aria-expanded":y,"aria-controls":b},p,M],stateAttributesMapping:P}),L=(0,Z.jsx)(X.Fragment,{children:ee},g);return E?(0,Z.jsxs)(X.Fragment,{children:[(0,Z.jsx)(ti,{ref:h.context.beforeTriggerFocusGuardRef,onFocus:F}),L,(0,Z.jsx)(ti,{ref:h.context.triggerFocusTargetRef,onFocus:I})]}):L}),fy=X.createContext(void 0);function py(){let e=X.useContext(fy);if(e===void 0)throw Error(Pn(45));return e}var my=X.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e;return ny().useState(`mounted`)||n?(0,Z.jsx)(fy.Provider,{value:n,children:(0,Z.jsx)(Zr,{ref:t,...r})}):null}),hy=X.createContext(void 0);function gy(){let e=X.useContext(hy);if(!e)throw Error(Pn(46));return e}var _y=X.forwardRef(function(e,t){let{render:n,className:r,style:i,anchor:a,positionMethod:o,side:s,align:c,sideOffset:l,alignOffset:u,collisionBoundary:d=`clipping-ancestors`,collisionPadding:f,arrowPadding:p,sticky:m,disableAnchorTracking:h=!1,collisionAvoidance:g=Rr,..._}=e,v=ny(),y=py(),b=Wr(),x=v.useState(`floatingRootContext`),S=v.useState(`mounted`),C=v.useState(`open`),w=v.useState(`openChangeReason`),T=v.useState(`activeTriggerElement`),E=v.useState(`modal`),D=v.useState(`openMethod`),O=v.useState(`positionerElement`),k=v.useState(`instantType`),A=v.useState(`transitionStatus`),j=v.useState(`adaptiveOrigin`),M=yr({anchor:a,floatingRootContext:x,positionMethod:o,mounted:S,side:s,sideOffset:l,align:c,alignOffset:u,arrowPadding:p,collisionBoundary:d,collisionPadding:f,sticky:m,disableAnchorTracking:h,keepMounted:y,nodeId:b,collisionAvoidance:g,adaptiveOrigin:j}),N=x.useState(`domReferenceElement`);ci({store:v,domReference:N,positionerElement:O,open:C});let P=E===!0&&w!==`trigger-hover`;hr(C&&P,D===`touch`,O,T);let F=v.useStateSetter(`positionerElement`),I={open:C,side:M.side,align:M.align,anchorHidden:M.anchorHidden,instant:k},ee=ni(e,I,{styles:M.positionerStyles,transitionStatus:A,props:_,refs:[t,F],hidden:!S,inert:!C});return(0,Z.jsxs)(hy.Provider,{value:M,children:[S&&P&&(0,Z.jsx)(Qn,{inert:Fr(!C),cutout:T}),(0,Z.jsx)(Mr,{id:b,children:ee})]})}),vy=X.createContext(void 0);function yy(){let[e,t]=X.useState(0),n=Ln(()=>(t(e=>e+1),()=>{t(e=>Math.max(0,e-1))}));return{context:X.useMemo(()=>({register:n}),[n]),hasClosePart:e>0}}var by=X.forwardRef(function(e,t){let{render:n,className:r,style:i,initialFocus:a,finalFocus:o,...s}=e,c=ny(),l=gy(),u=Fn(!0)!=null,{context:d,hasClosePart:f}=yy(),p=c.useState(`open`),m=c.useState(`openMethod`),h=c.useState(`instantType`),g=c.useState(`transitionStatus`),_=c.useState(`popupProps`),v=c.useState(`titleElementId`),y=c.useState(`descriptionElementId`),b=c.useState(`modal`),x=c.useState(`mounted`),S=c.useState(`openChangeReason`),C=c.useState(`activeTriggerElement`),w=c.useState(`floatingRootContext`),T=w.useState(`floatingId`),E=c.useState(`disabled`),D=c.useState(`openOnHover`),O=c.useState(`closeDelay`);An({open:p,ref:c.context.popupRef,onComplete(){p&&c.context.onOpenChangeComplete?.(!0)}}),Zn(w,{enabled:D&&!E,closeDelay:O});let k=a===void 0?Vn(c.context.popupRef):a,A=b!==!1&&f;c.useSyncedValue(`focusManagerModal`,A);let j=c.useStateSetter(`popupElement`),M={open:p,side:l.side,align:l.align,instant:h,transitionStatus:g},N=rr(`div`,e,{state:M,ref:[t,c.context.popupRef,j],props:[_,{id:T,role:`dialog`,...Hn,"aria-labelledby":v,"aria-describedby":y,onKeyDown(e){u&&jn.has(e.key)&&e.stopPropagation()}},ir(g),s],stateAttributesMapping:Mn});return(0,Z.jsx)(Yr,{context:w,openInteractionType:m,modal:A,disabled:!x||S===`trigger-hover`,initialFocus:k,returnFocus:o,restoreFocus:`popup`,getInsideElements:()=>[c.context.beforeTriggerFocusGuardRef.current],previousFocusableElement:$n(C)?C:void 0,nextFocusableElement:c.context.triggerFocusTargetRef,beforeContentFocusGuardRef:c.context.beforeContentFocusGuardRef,children:(0,Z.jsx)(vy.Provider,{value:d,children:N})})}),xy=(0,X.forwardRef)(function({children:e,className:t,type:n=`button`,...r},i){return(0,Z.jsxs)(`button`,{...r,ref:i,type:n,className:B(`select caps-select caps-combobox-trigger w-full`,t),children:[(0,Z.jsx)(`span`,{children:e}),(0,Z.jsx)(am,{className:`caps-select-chevron`,"aria-hidden":`true`})]})});function Sy({defaultOpen:e,defaultValue:t,getKey:n,getSearchText:r,groupBy:i,id:a,isDisabled:o,items:s,onOpenChange:c,onCommit:l,multiple:u,controlledOpen:d,controlledKeys:f,trigger:p}){let m=`${a}-listbox`,[h,g]=(0,X.useState)(``),[_,v]=(0,X.useState)(!1),[y,b]=(0,X.useState)(t),[x,S]=(0,X.useState)(e),C=f??(y===null?[]:[y]),w=p?d??x:!0,T=(0,X.useMemo)(()=>{let e=h.trim().toLowerCase();return e?s.filter(t=>r(t).toLowerCase().includes(e)):s},[r,s,h]),E=Iv({getKey:n,isDisabled:o,items:T});(0,X.useEffect)(()=>{if(E.activeKey!==null)return;let e=E.enabledItems.find(e=>C.includes(n(e)))??E.enabledItems[0];e&&E.setActiveKey(n(e))},[E.activeKey,E.enabledItems,E.setActiveKey,n,C]);let D=e=>{v(!1),e||g(``),d===void 0&&S(e),c?.(e)},O=e=>`${m}-option-${encodeURIComponent(e)}`,k=e=>{let t=n(e);f===void 0&&b(t),l(e),p&&!u&&D(!1)},A=e=>{v(!0),g(e.target.value),E.setActiveKey(null)},j=e=>{if(pv(e))return;let t;switch(e.key){case`ArrowDown`:t=[1,void 0];break;case`ArrowUp`:t=[-1,void 0];break;case`End`:t=[1,`end`];break;case`Home`:t=[-1,`start`]}t?(v(!0),e.preventDefault(),E.move(t[0],t[1])):e.key===`Enter`&&E.activeItem&&(e.preventDefault(),k(E.activeItem))},M=(0,X.useMemo)(()=>{if(!i)return[{label:``,items:T}];let e=new Map;for(let t of T){let n=i(t),r=e.get(n);r?r.push(t):e.set(n,[t])}return[...e].map(([e,t])=>({label:e,items:t}))},[T,i]);return{keyboardNavigation:_,onPointerMove:()=>{v(!1)},activeKey:E.activeKey,activeItem:E.activeItem,groups:M,inputValue:h,listboxId:m,onInputChange:A,onInputKeyDown:j,optionId:O,open:w,commit:k,selectedKeys:C,setOpen:D}}function Cy(e){let{"aria-describedby":t,"aria-invalid":n,"aria-label":r,"aria-labelledby":i,"aria-required":a,activeTone:o=`neutral`,container:s,contentClassName:c,defaultOpen:l=!1,defaultValue:u=null,emptyMessage:d=`No matches`,getKey:f,getLabel:p,getSearchText:m=p,groupBy:h,id:g,inputProps:_,inputRef:v,isDisabled:y=()=>!1,items:b,onOpenChange:x,onValueChange:S,multiple:C,open:w,placeholder:T=`Search…`,renderItem:E,rootRef:D,trigger:O,triggerRef:k,value:A,...j}=e,M=e=>{let t=f(e);if(C){let e=A.includes(t)?A.filter(e=>e!==t):[...A,t];S?.(e,b.filter(t=>e.includes(f(t))))}else S?.(t,e)},N;C?N=A:A!==void 0&&(N=A===null?[]:[A]);let P=(0,X.useId)(),F=O?.props??_,I=g??F?.id??P,ee={id:I,"aria-describedby":[t,F?.[`aria-describedby`]].filter(Boolean).join(` `)||void 0,"aria-invalid":n??F?.[`aria-invalid`],"aria-label":F?.[`aria-label`]??r,"aria-labelledby":F?.[`aria-labelledby`]??i,"aria-required":a??F?.[`aria-required`]},{keyboardNavigation:L,onPointerMove:R,activeItem:te,activeKey:ne,commit:re,groups:z,inputValue:ie,listboxId:V,onInputChange:ae,onInputKeyDown:H,open:U,optionId:W,selectedKeys:oe,setOpen:se}=Sy({defaultOpen:l,defaultValue:u,getKey:f,getSearchText:m,groupBy:h,id:I,isDisabled:y,items:b,onOpenChange:x,onCommit:M,multiple:C??!1,controlledOpen:w,controlledKeys:N,trigger:O});ii(()=>{O&&se(!1)});let G=or(`popover`),ce=s===void 0?G:s,le=kr(`.caps-combobox-option[data-active="true"]:not(:disabled), [data-navigation="pointer"] .caps-combobox-option:hover:not(:disabled)`),ue=(0,Z.jsx)($g,{..._,...O?{}:ee,"aria-activedescendant":te?W(f(te)):void 0,"aria-autocomplete":`list`,"aria-controls":V,"aria-expanded":!0,className:B(`input-sm`,_?.className),id:O?_?.id??`${I}-input`:I,onChange:e=>{_?.onChange?.(e),ae(e)},onKeyDown:e=>{_?.onKeyDown?.(e),e.defaultPrevented||H(e)},placeholder:_?.placeholder??T,ref:v,role:`combobox`,value:ie}),de=(0,Z.jsx)(`div`,{id:V,ref:le,className:`caps-combobox-list`,"data-navigation":L?`keyboard`:`pointer`,onPointerMove:R,role:`listbox`,"aria-multiselectable":C??void 0,children:z.every(e=>e.items.length===0)?(0,Z.jsx)(`div`,{className:`px-md py-md text-sm text-base-content`,children:d}):z.map(e=>(0,Z.jsxs)(`div`,{"aria-label":e.label||void 0,role:e.label?`group`:void 0,children:[e.label?(0,Z.jsx)(`div`,{className:`px-md pb-xs pt-sm text-xs text-base-content uppercase tracking-wider`,children:e.label}):null,e.items.map(e=>{let t=f(e),n=y(e),r=ne===t,i={active:r,disabled:n,selected:oe.includes(t)};return(0,Z.jsxs)(`button`,{"aria-disabled":n||void 0,"aria-selected":i.selected,className:`caps-combobox-option`,"data-active":r&&L,disabled:n,id:W(t),onClick:()=>{re(e)},onMouseDown:e=>{e.preventDefault()},role:`option`,tabIndex:-1,type:`button`,children:[(0,Z.jsx)(`span`,{"aria-hidden":`true`,className:`caps-combobox-check`,children:i.selected?(0,Z.jsx)(da,{}):null}),E?.(e,r,i)??p(e)]},t)})]},e.label))});return O?(0,Z.jsx)(`div`,{...j,className:B(j.className),ref:D,children:(0,Z.jsxs)(cy,{modal:!0,onOpenChange:se,open:U,children:[(0,Z.jsx)(dy,{...ee,"aria-haspopup":`dialog`,className:`btn`,ref:k,render:O}),ce===null?null:(0,Z.jsx)(my,{container:ce,children:(0,Z.jsx)(_y,{align:`start`,side:`bottom`,sideOffset:4,children:(0,Z.jsxs)(by,{"data-active-tone":o,className:B(`min-w-40 rounded-box border border-base-300 bg-base-100 p-xs shadow-lg outline-none caps-combobox-panel caps-combobox-popup`,c),children:[(0,Z.jsx)(`div`,{className:`caps-combobox-search`,children:ue}),de]})})})]})}):(0,Z.jsx)(`div`,{...j,className:B(j.className),ref:D,children:(0,Z.jsxs)(`div`,{className:B(`caps-combobox-panel`,c),"data-active-tone":o,children:[(0,Z.jsx)(`div`,{className:`caps-combobox-search`,children:ue}),de]})})}function wy({icon:e,caption:t}){return(0,Z.jsxs)(`span`,{className:`caps-icon-choice-mark`,"aria-hidden":`true`,children:[(0,Z.jsx)(`span`,{className:`caps-icon-choice-art`,children:e}),t?(0,Z.jsx)(`span`,{className:`caps-icon-choice-caption`,children:t}):null,(0,Z.jsx)(`span`,{className:`caps-icon-choice-lamp`})]})}var Ty=(0,X.forwardRef)(function({label:e,icon:t,caption:n,appearance:r,className:i,...a},o){return(0,Z.jsx)(`label`,{className:`caps-icon-choice`,"data-appearance":r===`compact`?r:void 0,children:(0,Z.jsx)(Fv,{...a,appearance:r??`default`,"aria-label":e,className:B(`caps-icon-choice-input`,i),indicator:(0,Z.jsx)(wy,{icon:t,caption:n}),ref:o})})}),Ey=(0,X.forwardRef)(function({label:e,icon:t,hint:n,className:r,...i},a){let o=(0,X.useId)(),s=[i[`aria-describedby`],n?o:null].filter(Boolean).join(` `)||void 0;return(0,Z.jsx)(`label`,{className:`caps-check-key`,children:(0,Z.jsx)(Fv,{...i,"aria-label":e,"aria-describedby":s,className:B(`caps-check-key-input`,r),indicator:(0,Z.jsxs)(`span`,{className:`caps-check-key-face`,"aria-hidden":`true`,children:[t?(0,Z.jsx)(`span`,{className:`caps-check-key-icon`,children:t}):null,(0,Z.jsxs)(`span`,{className:`caps-check-key-copy`,children:[(0,Z.jsx)(`span`,{className:`caps-check-key-label`,children:e}),n?(0,Z.jsx)(`span`,{className:`caps-check-key-hint`,id:o,children:n}):null]}),(0,Z.jsx)(`span`,{className:`caps-check-key-lamp`})]}),ref:a})})});function Dy({className:e,...t}){return(0,Z.jsx)(`div`,{...t,className:B(`caps-check-keys`,e)})}function Oy({checked:e}){let t=`caps-radio-${(0,X.useId)().replaceAll(`:`,``)}`,n=(0,X.useRef)(null),r=(0,X.useRef)(e).current,i=(0,X.useRef)(e),a=(0,X.useRef)(null),o=m(a),{reduced:s}=o;return(0,X.useLayoutEffect)(()=>{if(!n.current)return;let t=s||i.current===e;i.current=e;let r=e?4:0,a=ia(o,{ease:`outCubic`,duration:75}),c=e?Wi(o,{bounce:.65,duration:300}):ia(o,{ease:`inCubic`,duration:100}),l=Ma(n.current,t?{rx:r,ry:r,cy:6,duration:0}:{rx:[{to:e?3.5:4.15,...a},{to:r,...c}],ry:[{to:e?4.5:3.85,...a},{to:r,...c}],cy:[{to:e?5.85:6.1,...a},{to:6,...c}]});return()=>{l.cancel()}},[e,s,o]),(0,Z.jsxs)(`svg`,{ref:a,className:`caps-radio-visual`,width:`24`,height:`24`,viewBox:`0 0 12 12`,"aria-hidden":`true`,focusable:`false`,children:[(0,Z.jsxs)(`defs`,{children:[(0,Z.jsx)(Le,{id:`${t}-surface`,transform:`matrix(1 0 0 1 6 6)`}),(0,Z.jsx)(ct,{id:`${t}-shadow`}),(0,Z.jsx)(dt,{id:`${t}-inset`}),(0,Z.jsx)(`clipPath`,{id:`${t}-well`,children:(0,Z.jsx)(`circle`,{cx:`6`,cy:`6`,r:`5`})})]}),(0,Z.jsx)(`circle`,{className:`caps-radio-track`,cx:`6`,cy:`6`,r:`5.5`,filter:`url(#${t}-inset)`}),(0,Z.jsx)(`g`,{clipPath:`url(#${t}-well)`,children:(0,Z.jsx)(`ellipse`,{ref:n,cx:`6`,cy:`6`,rx:r?4:0,ry:r?4:0,fill:`url(#${t}-surface)`,filter:`url(#${t}-shadow)`})})]})}var ky=(0,X.createContext)(null),Ay=(0,X.forwardRef)(function({children:e,className:t,defaultValue:n,disabled:r=!1,name:i,onValueChange:a,orientation:o=`vertical`,value:s,...c},l){let u=(0,X.useId)(),d=(0,X.useRef)(null);(0,X.useImperativeHandle)(l,()=>{if(!d.current)throw Error(`RadioGroup is not mounted`);return d.current},[]);let f=i??`radio-group-${u}`,[p,m]=(0,X.useState)(n),h=s??p;return(0,X.useEffect)(()=>{let e=d.current?.form;if(!e||s!==void 0)return;let t=e=>{queueMicrotask(()=>{e.defaultPrevented||m(n)})};return e.addEventListener(`reset`,t),()=>{e.removeEventListener(`reset`,t)}},[s,n,c.form]),(0,Z.jsx)(ky.Provider,{value:{disabled:r,name:f,onValueChange:e=>{s===void 0&&m(e),a?.(e)},value:h},children:(0,Z.jsx)(`fieldset`,{...c,className:B(`flex gap-md`,o===`horizontal`?`flex-row flex-wrap`:`flex-col`,t),disabled:r,role:c.role??`radiogroup`,ref:d,children:e})})}),jy=(0,X.forwardRef)(function({className:e,indicator:t,onChange:n,onClick:r,value:i,...a},o){let s=(0,X.useContext)(ky);if(!s)throw Error(`RadioGroupItem must be used inside <RadioGroup>`);let c=s.value===i,l=e=>{n?.(e),e.target.checked&&s.onValueChange?.(i)};return(0,Z.jsxs)(`span`,{className:`caps-radio`,"data-checked":c,"data-custom-indicator":t!==void 0||void 0,children:[(0,Z.jsx)(`input`,{...a,"aria-checked":c,checked:c,className:B(`caps-radio-input`,e),disabled:s.disabled||a.disabled,name:s.name,onChange:l,onClick:r,ref:o,type:`radio`,value:i}),t===void 0?(0,Z.jsx)(Oy,{checked:c}):t]})}),My=(0,X.forwardRef)(function({description:e,id:t,meta:n,title:r,...i},a){let o=(0,X.useContext)(ky),s=(0,X.useId)(),c=t??s,l=o?.value===i.value,u=o?.disabled===!0||i.disabled===!0;return(0,Z.jsxs)(`label`,{className:`caps-choice-card`,"data-checked":l,"data-disabled":u||void 0,htmlFor:c,children:[(0,Z.jsx)(jy,{...i,"aria-describedby":e?`${c}-description`:void 0,"aria-labelledby":`${c}-title`,id:c,ref:a}),(0,Z.jsxs)(`span`,{className:`caps-choice-card-copy`,children:[(0,Z.jsx)(`span`,{className:`caps-choice-card-title`,id:`${c}-title`,children:r}),e?(0,Z.jsx)(`span`,{className:`caps-choice-card-description`,id:`${c}-description`,children:e}):null]}),n?(0,Z.jsx)(`span`,{className:`caps-choice-card-meta`,children:n}):null]})}),Ny=(0,X.forwardRef)(function({label:e,icon:t,caption:n,art:r=`dim`,className:i,...a},o){return(0,Z.jsx)(`label`,{className:`caps-icon-choice`,"data-art":r===`color`?r:void 0,children:(0,Z.jsx)(jy,{...a,"aria-label":e,className:B(`caps-icon-choice-input`,i),indicator:(0,Z.jsx)(wy,{icon:t,caption:n}),ref:o})})});(0,X.forwardRef)(function({label:e,color:t,className:n,...r},i){return(0,Z.jsx)(`label`,{className:`caps-icon-choice`,"data-art":`color`,"data-swatch":``,title:e,children:(0,Z.jsx)(jy,{...r,"aria-label":e,className:B(`caps-icon-choice-input`,n),indicator:(0,Z.jsx)(wy,{icon:(0,Z.jsx)(`span`,{className:`caps-swatch-dot`,style:{backgroundColor:t}})}),ref:i})})});var Py=V(Tn),Fy=V(Et),Iy=V(lt(dn)),Ly=V(qe(Tn)),Ry=qe(R(File)),zy=V(Ry),By=vn([Tn,dn,Et,pt,fe,qe(Tn),Ry]),Vy=V(By),Hy=e=>Je(Py(e.state.value),()=>``),Uy=e=>Je(Fy(e.state.value),()=>!1),Wy=e=>Je(Iy(e.state.value),()=>null),Gy=e=>Je(Ly(e.state.value),()=>[]),Ky=e=>Je(zy(e.state.value),()=>[]),qy=e=>Je(Vy(e.state.value),()=>null);function Jy({field:e,spec:t,locked:n,...r}){let[i,a]=(0,X.useState)(!1);return(0,Z.jsxs)(F_,{children:[(0,Z.jsx)($g,{...r,name:t.name,disabled:n,type:i?`text`:`password`,autoComplete:`off`,spellCheck:!1,className:`caps-field-secret`,placeholder:t.placeholder,readOnly:t.readOnly,value:Hy(e),onBlur:e.handleBlur,onChange:t=>{e.handleChange(t.currentTarget.value)}}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`icon`,"aria-label":i?`Hide`:`Show`,"aria-pressed":i,disabled:n,onClick:()=>{a(e=>!e)},children:i?(0,Z.jsx)(sm,{"aria-hidden":`true`}):(0,Z.jsx)(cm,{"aria-hidden":`true`})})]})}var Yy={text:`text`,email:`email`,url:`url`,tel:`tel`};function Xy({spec:e,field:t,locked:n,...r}){let i=Ky(t),a=n||e.readOnly===!0,o=(0,X.useRef)(null);return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-sm`,children:[(0,Z.jsx)(wn,{asChild:!0,children:(0,Z.jsx)(`input`,{...r,ref:o,type:`file`,tabIndex:-1,required:r.required===!0&&i.length===0,name:e.name,accept:e.accept,multiple:e.multiple,disabled:a,onBlur:t.handleBlur,onChange:e=>{t.handleChange(Array.from(e.currentTarget.files??[])),e.currentTarget.value=``}})}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,"aria-label":`Choose files for ${e.label}`,"aria-describedby":r[`aria-describedby`],"aria-invalid":r[`aria-invalid`],disabled:a,onBlur:t.handleBlur,onClick:()=>{o.current?.click()},children:`Choose files`}),(0,Z.jsx)(Xv,{items:i.map((e,t)=>({id:String(t),name:e.name,preview:{kind:`file`},progress:0,progressLabel:`${String(e.size)} bytes`,statusLabel:`Selected`,actions:a?{}:{remove:{label:`Remove`,accessibleLabel:`Remove ${e.name}`}}})),onRemove:e=>{t.handleChange(i.filter((t,n)=>String(n)!==e))},onCancel:()=>void 0,onRetry:()=>void 0})]})}function Zy({spec:e,field:t,locked:n,...r}){let i=e=>{t.handleChange(e)},a={...r,name:e.name,disabled:n,onBlur:t.handleBlur};switch(e.kind){case`text`:case`email`:case`url`:case`tel`:return(0,Z.jsx)($g,{...a,type:Yy[e.kind],inputMode:e.kind===`text`?void 0:e.kind,autoComplete:e.autoComplete,placeholder:e.placeholder,maxLength:e.maxLength,readOnly:e.readOnly,value:Hy(t),onChange:e=>{i(e.currentTarget.value)}});case`textarea`:return(0,Z.jsx)(Dv,{...a,rows:e.rows??3,placeholder:e.placeholder,maxLength:e.maxLength,readOnly:e.readOnly,value:Hy(t),onChange:e=>{i(e.currentTarget.value)}});case`secret`:return(0,Z.jsx)(Jy,{...r,field:t,spec:e,locked:n});case`money`:return(0,Z.jsxs)(F_,{children:[(0,Z.jsx)(I_,{className:`caps-field-currency`,children:e.currency??`USD`}),(0,Z.jsx)($g,{...a,inputMode:`decimal`,autoComplete:`off`,className:`caps-field-amount`,placeholder:e.placeholder??`0.00`,readOnly:e.readOnly,value:Hy(t),onChange:e=>{i(e.currentTarget.value)}})]});case`date`:return(0,Z.jsx)($g,{...a,type:`date`,readOnly:e.readOnly,value:Hy(t),onChange:e=>{i(e.currentTarget.value)}});case`number`:return(0,Z.jsx)(Z_,{...a,...e.min===void 0?{}:{min:e.min},...e.max===void 0?{}:{max:e.max},...e.step===void 0?{}:{step:e.step},...e.unit===void 0?{}:{unit:e.unit},...e.wrap===void 0?{}:{wrap:e.wrap},disabled:n||e.readOnly===!0,decrementLabel:`Decrease ${e.label}`,incrementLabel:`Increase ${e.label}`,value:Wy(t),onValueChange:e=>{t.handleChange(e)}});case`select`:return(0,Z.jsxs)(Q_,{...a,value:Hy(t),onChange:e=>{i(e.currentTarget.value)},children:[e.placeholder===void 0?null:(0,Z.jsx)(`option`,{value:``,disabled:!0,children:e.placeholder}),e.options.map(e=>(0,Z.jsx)(`option`,{value:e.value,disabled:e.disabled,children:e.label},e.value))]});case`combobox`:return(0,Z.jsx)(Cy,{id:r.id??e.name,"aria-describedby":r[`aria-describedby`],"aria-invalid":r[`aria-invalid`],"aria-required":r[`aria-required`],items:e.options,getKey:e=>e.value,getLabel:e=>e.label,isDisabled:t=>t.disabled||n||e.readOnly===!0,value:Hy(t),...e.placeholder===void 0?{}:{placeholder:e.placeholder},trigger:(0,Z.jsx)(xy,{name:e.name,disabled:n||e.readOnly===!0,onBlur:t.handleBlur,children:e.options.find(e=>e.value===Hy(t))?.label??e.placeholder??`Choose…`}),inputProps:{"aria-label":`Search ${e.label}`,disabled:n||e.readOnly===!0},onValueChange:e=>{i(e??``),t.handleBlur()}});case`file`:return(0,Z.jsx)(Xy,{...r,spec:e,field:t,locked:n});case`checkbox`:return(0,Z.jsx)(Fv,{...a,disabled:n||e.readOnly===!0,checked:Uy(t),onChange:e=>{t.handleChange(e.currentTarget.checked)}});case`switch`:return(0,Z.jsx)(ra,{...a,disabled:n||e.readOnly===!0,checked:Uy(t),onCheckedChange:e=>{t.handleChange(e)}});case`radio`:case`icon-radio`:case`checkboxes`:case`icon-checkboxes`:return null}}var Qy=new Set([`radio`,`icon-radio`,`checkboxes`,`icon-checkboxes`]);function $y({spec:e,field:t,locked:n,error:r,layout:i}){let a=n||e.readOnly===!0,o=e.label;if(e.kind===`checkboxes`||e.kind===`icon-checkboxes`){let n=Gy(t),s=(e,r)=>{t.handleChange(r?[...n,e]:n.filter(t=>t!==e))};return(0,Z.jsx)(W_,{legend:o,icon:e.icon,layout:i,...i===`columns`?{legendTitle:o}:{},description:e.help,disabled:a,error:r??null,children:e.kind===`icon-checkboxes`?(0,Z.jsx)(`div`,{className:`caps-field-icon-choices`,children:e.options.map(r=>(0,Z.jsx)(Ty,{name:e.name,value:r.value,label:r.label,...r.caption===void 0?{}:{caption:r.caption},icon:r.icon,disabled:r.disabled,checked:n.includes(r.value),onBlur:t.handleBlur,onChange:e=>{s(r.value,e.currentTarget.checked)}},r.value))}):(0,Z.jsx)(Dy,{children:e.options.map(r=>(0,Z.jsx)(Ey,{name:e.name,value:r.value,label:r.label,icon:r.icon,hint:r.description,disabled:r.disabled,checked:n.includes(r.value),onBlur:t.handleBlur,onChange:e=>{s(r.value,e.currentTarget.checked)}},r.value))})})}let s=e.options.some(e=>e.description!==void 0||e.meta!==void 0);return(0,Z.jsx)(W_,{legend:o,icon:e.icon,layout:i,...i===`columns`?{legendTitle:o}:{},description:e.help,disabled:a,error:r??null,children:(0,Z.jsx)(Ay,{name:e.name,"aria-label":o,value:Hy(t),onValueChange:e=>{t.handleChange(e),t.handleBlur()},orientation:e.kind===`icon-radio`||s?`horizontal`:`vertical`,children:e.options.map(t=>e.kind===`icon-radio`?(0,Z.jsx)(Ny,{value:t.value,label:t.label,...t.caption===void 0?{}:{caption:t.caption},icon:t.icon,disabled:t.disabled},t.value):s?(0,Z.jsx)(My,{value:t.value,title:t.label,description:t.description,meta:t.meta,disabled:t.disabled},t.value):(0,Z.jsx)(K_,{label:t.label,orientation:`inline`,children:(0,Z.jsx)(jy,{value:t.value,disabled:t.disabled})},t.value))})})}function eb({spec:e,field:t,locked:n,error:r,render:i,...a}){return i({name:e.name,label:e.label,help:e.help,value:qy(t),onChange:e=>{t.handleChange(e)},onBlur:t.handleBlur,error:r,disabled:n,id:a.id??e.name,"aria-describedby":a[`aria-describedby`],"aria-invalid":r!==void 0})}function tb({form:e,spec:t,locked:n,layout:r}){let i=Wg({form:e,name:t.name}),a=Q(e.store,e=>e.submissionAttempts>0),o=i.state.meta.isBlurred||a?qv(i.state.meta):void 0;if(t.render===void 0&&Qy.has(t.kind))return(0,Z.jsx)($y,{spec:t,field:i,locked:n,error:o,layout:r});let s=r===`columns`?t.kind===`switch`||t.kind===`checkbox`?`horizontal`:`vertical`:t.kind===`checkbox`?`inline`:(t.layout??(t.kind===`switch`?`row`:`stacked`))===`row`?`horizontal`:`vertical`;return(0,Z.jsx)(K_,{label:t.label,...r===`columns`?{labelTitle:t.label}:{},description:t.help,icon:t.icon,orientation:s,error:o,...t.required===void 0?{}:{required:t.required},...t.optional===void 0?{}:{optional:t.optional},children:t.render===void 0?(0,Z.jsx)(Zy,{spec:t,field:i,locked:n}):(0,Z.jsx)(eb,{spec:t,field:i,locked:n,error:o,render:t.render})})}var nb=V(hn(Tn,By));function rb({form:e,spec:t,locked:n,layout:r}){let i=t.when;return Q(e.store,e=>i===void 0||i(Je(nb(e.values),()=>({}))))?(0,Z.jsx)(tb,{form:e,spec:t,locked:n,layout:r}):null}function ib({form:e,section:t,locked:n,layout:r}){let i=t.fields.map(t=>(0,Z.jsx)(rb,{form:e,spec:t,locked:n,layout:r},t.name));return t.title===void 0?i:(0,Z.jsx)(U_,{title:t.title,description:t.description,layout:r,children:i})}function ab({model:e,names:t,disabled:n=!1,layout:r}){let i=e.form;return t===void 0?e.description.sections.map(e=>(0,Z.jsx)(ib,{form:i,section:e,locked:n,layout:r},e.id??``)):t.map(t=>{let a=e.description.fields.find(e=>e.name===t);return a===void 0?null:(0,Z.jsx)(rb,{form:i,spec:a,locked:n,layout:r},t)})}var ob=class{annotation;constructor(e){this.annotation=e}},sb=class{sections;constructor(e){this.sections=e}},cb=`caps/form`,lb=0;function ub(e){lb+=1;let t={[`${cb}:${String(lb)}`]:new ob(e)};return e.label!==void 0&&(t.title=e.label),e.help!==void 0&&(t.description=e.help),t}Tn.annotate(ub({kind:`secret`})).pipe(ge(`Secret`));var db=e=>{let t=e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/[-_]+/g,` `).toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)};function fb(e){return Object.values(e??{}).reduce((e,t)=>t instanceof ob?{...e,...t.annotation}:e,{})}function pb(e){return e.reduce((e,t)=>({...e,...fb(t)}),{})}function mb(e){let t=e?.[cb];return t instanceof sb?t.sections:{}}var hb=V(Tn);function gb(e){if(k(e))return Gt(hb(e.literal),{onNone:()=>null,onSome:e=>[e]});if(!tt(e))return null;let t=[];for(let n of e.types){if(r(n))continue;let e=gb(n);if(e===null)return null;t.push(...e)}return t}function _b(e){if(se(e))return{type:`string`,literals:[]};if(Oe(e))return{type:`number`,nullable:!1};if(Jt(e))return{type:`boolean`};let t=gb(e);if(t!==null)return{type:`string`,literals:t};if(M(e)){let[t]=e.rest;if(t===void 0)return null;if(se(t))return{type:`strings`,literals:[]};let n=gb(t);return n===null?null:{type:`strings`,literals:n}}if(tt(e)){let t=e.types.filter(e=>!r(e)&&!je(e)),n=e.types.some(e=>je(e)),[i]=t;if(t.length!==1||i===void 0)return null;let a=_b(i);return a?.type===`number`?{type:`number`,nullable:n}:n?null:a}return null}function vb(e){let t=e.ast;if(!Pe(t))throw Error(`A schema form needs a Schema.Struct.`);return{fields:t.propertySignatures.map(e=>{let t=String(e.name),n=vt(e.type),r=pb([e.type.annotations,...(e.type.checks??[]).map(e=>e.annotations)]),i=r.kind===`file`?{type:`files`}:_b(n);if(i===null)throw Error(`Schema field "${t}" has no form control. Annotate it with field({ render }) or a kind.`);return{name:t,valueType:i,optional:e.type.context?.isOptional===!0,annotation:r,title:$t(e.type),description:Lt(e.type)}}),sections:mb(sn(t))}}function yb(e){let t=e,n=!1,r=!1;for(;;)if(t instanceof D)n=!0,t=t.unwrap();else if(t instanceof ie)r=!0,t=t.unwrap();else if(t instanceof s)t=t.unwrap();else if(t instanceof ee)t=t.in;else return{node:t,optional:n,nullable:r}}function bb(e){if(e instanceof l){let t=e.options.map(e=>bb(e));return t.some(e=>e===null)?null:t.flatMap(e=>e??[])}let t=e instanceof xt?e.options:e instanceof te?[...e.values]:null;if(t===null)return null;let n=t.map(e=>hb(e));return n.every(Qe)?n.map(e=>e.value):null}function xb(e){let{node:t,nullable:n}=yb(e);if(t instanceof ue)return{type:`string`,literals:[]};if(t instanceof U)return{type:`number`,nullable:n};if(t instanceof Ct)return{type:`boolean`};let r=bb(t);if(r!==null)return{type:`string`,literals:r};if(t instanceof ae){let e=yb(t.element).node;if(e instanceof ue)return{type:`strings`,literals:[]};let n=bb(e);return n===null?null:{type:`strings`,literals:n}}return null}function Sb(e){let t=[e];for(;;){let e=t[t.length-1];if(e===void 0)break;let n=e instanceof D||e instanceof ie||e instanceof s?e.unwrap():e instanceof ee?e.in:e;if(n===e)break;t.push(n)}return t.reverse().map(e=>Zt.get(e))}function Cb(e){return Sb(e).reduce((e,t)=>({...e,...t}),{})}function wb(e){return Object.entries(e.shape)}function Tb(e){let t=yb(e).node;if(!(t instanceof y))throw Error(`A schema form needs a z.object.`);return{fields:wb(t).map(([e,t])=>{let n=pb(Sb(t)),r=n.kind===`file`?{type:`files`}:xb(t);if(r===null)throw Error(`Schema field "${e}" has no form control. Annotate it with field({ render }) or a kind.`);let i=Cb(t);return{name:e,valueType:r,optional:yb(t).optional,annotation:n,title:i.title,description:i.description}}),sections:mb(Cb(e))}}function Eb(e,t){let n=t.options??{};return(e.length>0?e:Object.keys(n)).map(e=>{let t=n[e],r=t===void 0?{}:t instanceof Object?t:{label:t};return{value:e,label:r.label??db(e),description:r.description,meta:r.meta,icon:r.icon,caption:r.caption,disabled:r.disabled===!0}})}function Db(e,t){let n=t.some(e=>e.icon!==void 0);switch(e.type){case`boolean`:return`switch`;case`number`:return`number`;case`strings`:return n?`icon-checkboxes`:`checkboxes`;case`files`:return`file`;case`string`:return t.length===0?`text`:t.length>12?`combobox`:n?`icon-radio`:t.some(e=>e.description!==void 0||e.meta!==void 0)||t.length<=3?`radio`:`select`}}function Ob(e,t){switch(e.type){case`boolean`:return!1;case`number`:return e.nullable?null:0;case`strings`:case`files`:return[];case`string`:return t[0]?.value??``}}function kb(e){let t=e instanceof kn?Tb(e):vb(e),n=t.fields.map((e,t)=>{let{kind:n,...r}=e.annotation,i=Eb(e.valueType.type===`string`||e.valueType.type===`strings`?e.valueType.literals:[],e.annotation),a=r.help??e.description;return{...r,name:e.name,label:r.label??e.title??db(e.name),help:a,kind:n??Db(e.valueType,i),options:i,optionalInSchema:e.optional,index:t}}),r={};t.fields.forEach((e,t)=>{let i=n[t];i&&(r[e.name]=Ob(e.valueType,i.options))});let i=e=>e.order??e.index,a=e=>e.section!==void 0&&Object.hasOwn(t.sections,e.section)?e.section:null,o=e=>n.filter(t=>a(t)===e).sort((e,t)=>i(e)-i(t)),s=Object.entries(t.sections).map(([e,t])=>({id:e,title:t.title,description:t.description,fields:o(e)}));return{fields:n,sections:[{id:null,title:void 0,description:void 0,fields:o(null)},...s].filter(e=>e.fields.length>0),defaults:r}}function Ab(e){let t=e instanceof kn?e:x(e);return{"~standard":{...t[`~standard`],validate:e=>{let n=t[`~standard`].validate(e);return n instanceof Promise?n.then(e=>jb(e)):jb(n)}}}}function jb(e){return e.issues===void 0?e:{issues:e.issues.map(e=>e.path===void 0?e:{...e,path:e.path.slice(0,1)})}}var Mb=`onServer`;function Nb(e){let t=e.querySelector(`[aria-invalid="true"]`),n=t?.matches(`input, select, textarea, button, [tabindex]`)?t:t?.querySelector(`input, select, textarea, button`);return n?.focus(),n!=null}function Pb(e){if(Nb(e))return()=>void 0;let t=new MutationObserver(()=>{Nb(e)&&t.disconnect()});return t.observe(e,{subtree:!0,childList:!0,attributes:!0,attributeFilter:[`aria-invalid`]}),()=>{t.disconnect()}}function Fb(e){return e.state.meta.errorMap.onServer!==void 0}function Ib(e){e.setMeta(e=>({...e,errorMap:{...e.errorMap,[Mb]:void 0}}))}function Lb(e,t,n){e.setFieldMeta(t,e=>({...e,isBlurred:!0,errorMap:{...e.errorMap,[Mb]:n}}))}function Rb(e){let[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(null),[a,o]=(0,X.useState)(e.defaultValues),[s,c]=(0,X.useState)(null);cg(a,e.defaultValues)||(o(e.defaultValues),c(null));let{schema:l}=e,u=(0,X.useMemo)(()=>kb(l),[l]),d=(0,X.useMemo)(()=>Ab(l),[l]),f=Qg({defaultValues:s??a,validators:{onChange:d,onSubmit:d},listeners:{onChange:({fieldApi:e})=>{n(null),i(null),Fb(e)&&Ib(e)}},onSubmit:async({value:t,formApi:r})=>{n(null),i(null);let a=await Ab(l)[`~standard`].validate(t);if(a.issues){n(a.issues[0]?.message??`Check the form and try again.`);return}let o;try{o=await e.onSubmit(a.value,t)??{kind:`saved`}}catch(t){console.error(`SchemaForm submit failed`,t),n(e.failure??`Couldn't save changes. Try again.`);return}if(o.kind===`refused`){n(o.error??null);let e=r;for(let[t,n]of Object.entries(o.fields??{}))n!==void 0&&n.length>0&&Lb(e,t,n);return}let s=o.values??t;c(s),r.reset(s),i(o.message??`Saved`),e.onSaved?.(s)}});return{description:u,form:f,error:t,saved:r,discard:()=>{n(null),i(null),f.reset()},submit:()=>f.handleSubmit()}}function zb(e){return{dirty:Q(e.form.store,e=>!e.isDefaultValue),submitting:Q(e.form.store,e=>e.isSubmitting),canSubmit:Q(e.form.store,e=>e.canSubmit)}}function Bb({model:e,submitLabel:t=`Save changes`,discardLabel:n,onCancel:r,cancelLabel:i,allowClean:a,layout:o,footer:s,children:c,disabled:l=!1,...u}){let{submitting:d}=zb(e),f=(0,X.useRef)(null),p=(0,X.useRef)(()=>void 0);return(0,X.useEffect)(()=>()=>{p.current()},[]),(0,Z.jsxs)(V_,{...u,ref:f,layout:o,busy:d,noValidate:!0,onSubmit:t=>{t.preventDefault(),e.form.state.isSubmitting||e.submit().then(()=>{p.current();let t=f.current;t!==null&&!e.form.state.isValid&&(p.current=Pb(t))})},children:[c??(0,Z.jsx)(ab,{model:e,disabled:l,layout:o}),s===void 0?(0,Z.jsx)(Ub,{model:e,label:t,discardLabel:r===void 0?n:void 0,onCancel:r,cancelLabel:i,allowClean:a??r!==void 0,divider:r===void 0}):s]})}function Vb({schema:e,defaultValues:t,onSubmit:n,onSaved:r,failure:i,...a}){let o=Rb({schema:e,defaultValues:t,onSubmit:n,onSaved:r,failure:i});return(0,Z.jsx)(Bb,{...a,model:o})}function Hb(e){return`model`in e?(0,Z.jsx)(Bb,{...e}):(0,Z.jsx)(Vb,{...e})}function Ub({model:e,label:t,discardLabel:n,onCancel:r,cancelLabel:i=`Cancel`,allowClean:a=!1,dirtyLabel:o=`Unsaved changes`,buttonProps:s,...c}){let{dirty:l,submitting:u}=zb(e),d=u?null:e.saved&&!l?(0,Z.jsx)(np,{tone:`success`,size:`compact`,label:e.saved}):l?(0,Z.jsx)(np,{tone:`neutral`,size:`compact`,label:o}):null;return(0,Z.jsxs)(B_,{...c,error:e.error,status:d,children:[r?(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,disabled:u,onClick:r,children:i}):n&&l?(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,disabled:u,onClick:e.discard,children:n}):null,(0,Z.jsx)(Y,{...s,type:`submit`,loading:u,disabled:u||!l&&!a,title:!l&&!a?`No changes to save`:void 0,children:t})]})}var Wb={error:0,warning:1,info:2};function Gb(e,t){let n=t.generating+t.uploading>0;if(n)return{busy:n,tone:void 0,label:[t.generating?`Creating ${String(t.generating)}`:``,t.uploading?`Uploading ${String(t.uploading)}`:``].filter(Boolean).join(` · `)};let r=[...e].sort((e,t)=>Number(t.blocking??!1)-Number(e.blocking??!1)||Wb[e.tone]-Wb[t.tone]).at(0);return r?{busy:n,tone:r.tone===`info`?`neutral`:r.tone,label:r.short+(e.length>1?` +${String(e.length-1)}`:``)}:null}function Kb(e,t,n){let r=Gb(e,t);if(!r)return null;let i={kind:`button`,id:`activity`,text:`Activity`,count:e.length+t.generating+t.uploading,busy:r.busy,title:Cn(`Activity: ${r.label}`,1024),opens:`dialog`,expanded:n};return r.tone===void 0?i:{...i,tone:r.tone}}var qb={Setup:(0,Z.jsx)(gm,{"aria-hidden":`true`,className:`size-[var(--stipe-icon-size-sm)]`}),Images:(0,Z.jsx)(dm,{"aria-hidden":`true`,className:`size-[var(--stipe-icon-size-sm)]`}),Uploads:(0,Z.jsx)(vm,{"aria-hidden":`true`,className:`size-[var(--stipe-icon-size-sm)]`})};function Jb({notices:e,uploads:t,open:n,inset:r,onOpenChange:i,onDismiss:a,onDismissAll:o,onLoadMore:s}){return(0,Z.jsx)(Cv,{className:`prints-activity-tray`,placement:`host`,align:`start`,...r===void 0?{}:{hostInset:r},items:[{id:`activity`,label:`Activity`,title:`Activity`,content:(0,Z.jsx)(Yb,{notices:e,uploads:t,onDismiss:a,onDismissAll:o,onLoadMore:s})}],openId:n?`activity`:null,onOpenChange:e=>{i(e===`activity`)}})}function Yb({notices:e,uploads:t,onDismiss:n,onDismissAll:r,onLoadMore:i}){let a=[`Setup`,`Images`,`Uploads`].map(t=>({group:t,items:e.filter(e=>e.group===t)})).filter(e=>e.items.length);return(0,Z.jsxs)(`div`,{className:`prints-instrument`,children:[a.map(({group:e,items:t})=>(0,Z.jsxs)(`section`,{"aria-label":e,className:`prints-notice-group`,children:[(0,Z.jsx)(ua,{level:3,children:e}),(0,Z.jsx)(wv,{children:t.map(e=>(0,Z.jsx)(Tv,{icon:qb[e.group],primary:(0,Z.jsxs)(`span`,{className:`prints-notice-copy`,children:[(0,Z.jsx)(`span`,{children:e.title}),e.detail?(0,Z.jsx)(`span`,{className:`prints-notice-detail`,children:e.detail}):null]}),actions:(0,Z.jsxs)(`div`,{className:`prints-notice-actions`,"aria-label":`Actions for ${e.title}`,children:[e.actions?.map((e,t)=>(0,Z.jsx)(Y,{variant:t===0?`outline`:`ghost`,size:t===0?`sm`:`xs`,onClick:e.run,children:e.label},e.label)),e.blocking?null:(0,Z.jsx)(ln,{"aria-label":`Dismiss ${e.title}`,icon:(0,Z.jsx)(Xi,{"aria-hidden":`true`}),onClick:()=>{n(e.key)}})]})},e.key))})]},e)),e.length?null:(0,Z.jsx)(Ev,{children:`All caught up.`}),t&&t.items.length>0?(0,Z.jsxs)(`section`,{"aria-label":`Upload queue`,className:`prints-upload-bank`,children:[(0,Z.jsx)(ua,{level:3,children:`Uploading`}),(0,Z.jsx)(Xv,{...t})]}):null,(0,Z.jsxs)(`div`,{className:`prints-panel-footer`,children:[(0,Z.jsx)(`span`,{className:`prints-footer-note`,children:`Clear dismisses finished items`}),(0,Z.jsx)(Y,{variant:`ghost`,size:`xs`,disabled:!e.some(e=>!e.blocking),onClick:r,children:`Clear`}),i?(0,Z.jsx)(Y,{variant:`ghost`,size:`xs`,onClick:i,children:`Load more activity`}):null]})]})}function Xb({folder:e}){return(0,Z.jsx)(Lf,{open:e.editing,onOpenChange:e.setEditing,children:(0,Z.jsxs)(Hf,{children:[(0,Z.jsx)(Wf,{children:(0,Z.jsx)(Gf,{children:`Save prints to`})}),(0,Z.jsx)(Qb,{folder:e},e.computerId),(0,Z.jsx)(Uf,{children:(0,Z.jsx)(Kf,{render:(0,Z.jsx)(Y,{variant:`outline`,size:`sm`}),children:`Close`})})]})})}var Zb=Ue({path:xn.check(Se(z(di),{message:`Enter an absolute Computer folder, such as /media.`})).annotate(ub({label:`Folder`,placeholder:`/media`}))});function Qb({folder:e}){let t=(0,X.useRef)(!1),n=Rb({schema:Zb,defaultValues:{path:e.path??`/media`},onSubmit:async({path:n})=>{let r=await e.choose(n,t.current);return r?{kind:`refused`,fields:{path:r}}:{kind:`saved`}}}),r=e=>{t.current=e,n.form.setFieldMeta(`path`,e=>({...e,errorMap:{...e.errorMap,onServer:void 0}}))},i=e.busy||!e.writable;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Hb,{model:n,disabled:i,footer:(0,Z.jsxs)(B_,{divider:!1,children:[(0,Z.jsx)(wt,{className:`[--caps-keycap-width:auto]`,label:`Use`,type:`submit`,disabled:i,onClick:()=>{r(!1)}}),(0,Z.jsx)(wt,{className:`[--caps-keycap-width:auto]`,label:`Create`,type:`submit`,disabled:i,onClick:()=>{r(!0)}})]})}),e.error?(0,Z.jsx)(Tv,{role:`alert`,icon:(0,Z.jsx)(um,{"aria-hidden":`true`,className:`size-[var(--stipe-icon-size-sm)]`}),primary:e.error}):(0,Z.jsx)(Ev,{children:e.writable?`Prints saves new images and uploads here and shows this folder as your gallery.`:`This Computer is read-only for Prints, so the folder can’t change.`})]})}var $b={image:`Image`,video:`Video`,media:`Media`};function ex({connected:e,mediaCapability:t,modelsError:n,retryModels:r,modelsLoading:i,models:a,canGenerate:o,mediaSetupMissing:s,canWrite:c,generationError:l,recoveryError:u,pendingGenerations:d,activeGenerations:f,gallerySlots:p,computerId:m,failed:h,uploadError:g,uploads:_,permissions:v,resume:y,discard:b,retryUpload:x}){let S=[];if(e)m===null?S.push({key:`no-computer`,group:`Setup`,tone:`info`,blocking:!0,short:`Choose a Computer`,title:`No Computer selected`,detail:`Choose a Computer for this window, or create one in Grove.`}):t?n===null?!i&&!o&&!s&&S.push({key:`approval`,group:`Setup`,tone:`warning`,blocking:!0,short:`Generation not enabled`,title:`Media generation isn’t enabled`,detail:`Turn it on in this App’s Team permissions. Images already generated can still be saved.`,actions:[{label:`Permissions`,run:()=>{v()}}]}):S.push({key:`models:${n}`,group:`Setup`,tone:`warning`,blocking:!0,short:`Models unavailable`,title:`Couldn’t load image models`,detail:n,actions:[{label:`Retry`,run:r}]}):S.push({key:`no-media`,group:`Setup`,tone:`info`,blocking:!0,short:`Image creation off`,title:`Image creation is off for this Computer`,detail:`You can still browse and upload images.`});else{let e=rn(new J(`Prints disconnected`,{code:`DISCONNECTED`,retryable:!0}));S.push({key:`disconnected`,group:`Setup`,tone:`warning`,blocking:!0,short:e.title,title:e.title,detail:e.message})}if(e&&m!==null&&!c&&S.push({key:`read-only`,group:`Setup`,tone:`info`,blocking:!0,short:`Read-only`,title:`Read-only Computer`,detail:`Uploads and new prints are off.`}),l!==null){let e=`${$b[l.mediaKind??`media`]} failed`;S.push({key:l.key,group:`Images`,tone:`error`,short:e,title:`${e}: ${l.message}`,detail:l.prompt,blocking:l.dismiss!==void 0,actions:[...l.billing?[{label:`Open Billing`,run:l.billing}]:l.retry?[{label:`Retry`,run:l.retry}]:[],...l.dismiss?[{label:`Dismiss`,run:l.dismiss}]:[]]})}u!==null&&S.push({key:`recovery:${u}`,group:`Images`,tone:`error`,short:`Retry blocked`,title:u});for(let e of d){if(f.has(e.reference.requestId)||p.some(t=>t.computerId===e.reference.computerId&&t.path===e.input.destination.path))continue;let t=`${$b[xi(a,e.input.settings.model)?.kind??`media`]} failed`;S.push({key:`unfinished:${e.reference.requestId}`,group:`Images`,tone:`error`,blocking:!0,short:t,title:`${t}: ${e.failure?.message??`Stopped when Prints closed. Retry to run it again.`}`,detail:e.reference.computerId===m?e.typed.prompt:`${e.typed.prompt} · select the original Computer to retry`,actions:[...e.reference.computerId===m?[{label:`Retry`,run:()=>{y(e)}}]:[],{label:`Dismiss`,run:()=>{b(e)}}]})}h.length>0&&S.push({key:`files:${h.join(`|`)}`,group:`Images`,tone:`error`,short:`Couldn’t open images`,title:`Couldn’t open some images`,detail:h.join(`, `)}),g!==null&&S.push({key:`uploads:${g}`,group:`Uploads`,tone:`error`,short:`Upload failed`,title:`Couldn’t add images`,detail:g});for(let e of _)(e.status===`error`||e.status===`cancelled`)&&S.push({key:`upload:${e.id}:${e.status}`,group:`Uploads`,tone:e.status===`error`?`error`:`info`,short:`Upload failed`,title:`${e.file.name} wasn’t saved`,detail:e.message,actions:[{label:`Retry`,run:()=>{x(e.id)}}]});return S}function tx(e,t){let n=la(va(e)),r=ve(Qi({queryKey:oa.dismissals(e),mutationFn:({owner:e,id:t,keys:n})=>_i(e.capabilities,{operation:`dismiss-notices`,computerId:t,keys:n}),apply:(e,t)=>({keys:[...new Set([...e.keys,...t.keys])].slice(-200)})})),i=n=>{e&&t&&n.length>0&&r.mutate({owner:e,id:t,keys:n})};return{error:r.variables?.owner===e&&r.variables.id===t&&r.isError?`Could not dismiss activity. Please try again.`:n.isError?`Could not load dismissed activity. Notices may reappear.`:null,visible:e=>e.filter(e=>(e.blocking??!1)||!n.data?.keys.includes(e.key)),dismiss:e=>{i([e])},dismissAll:e=>{i(e.filter(e=>!e.blocking).map(e=>e.key).slice(-200))}}}var nx=0,rx=1,ix=2,ax=0,ox=1;function sx(e,t,n){let r=e.list,i;for(;r;){if(r.index===n)return!1;if(t>r.high)break;i=r,r=r.next}return i||(e.list={index:n,high:t,next:r}),i&&(i.next={index:n,high:t,next:i.next}),!0}function cx(e,t){let n=e.list;if(n.index===t)return n.next===null?ax:(e.list=n.next,ox);let r=n;for(n=n.next;n!==null;){if(n.index===t)return r.next=n.next,ox;r=n,n=n.next}}var $={low:0,max:0,high:0,C:ix,P:void 0,R:void 0,L:void 0,list:void 0};$.P=$,$.L=$,$.R=$;function lx(e){let t=e.high;e.max=e.L===$&&e.R===$?t:e.L===$?Math.max(e.R.max,t):e.R===$?Math.max(e.L.max,t):Math.max(Math.max(e.L.max,e.R.max),t)}function ux(e){let t=e;for(;t.P!==$;)lx(t.P),t=t.P}function dx(e,t){if(t.R===$)return;let n=t.R;t.R=n.L,n.L!==$&&(n.L.P=t),n.P=t.P,t.P===$?e.root=n:t===t.P.L?t.P.L=n:t.P.R=n,n.L=t,t.P=n,lx(t),lx(n)}function fx(e,t){if(t.L===$)return;let n=t.L;t.L=n.R,n.R!==$&&(n.R.P=t),n.P=t.P,t.P===$?e.root=n:t===t.P.R?t.P.R=n:t.P.L=n,n.R=t,t.P=n,lx(t),lx(n)}function px(e,t,n){t.P===$?e.root=n:t===t.P.L?t.P.L=n:t.P.R=n,n.P=t.P}function mx(e,t){let n;for(;t!==$&&t.C===rx;)t===t.P.L?(n=t.P.R,n.C===nx&&(n.C=rx,t.P.C=nx,dx(e,t.P),n=t.P.R),n.L.C===rx&&n.R.C===rx?(n.C=nx,t=t.P):(n.R.C===rx&&(n.L.C=rx,n.C=nx,fx(e,n),n=t.P.R),n.C=t.P.C,t.P.C=rx,n.R.C=rx,dx(e,t.P),t=e.root)):(n=t.P.L,n.C===nx&&(n.C=rx,t.P.C=nx,fx(e,t.P),n=t.P.L),n.R.C===rx&&n.L.C===rx?(n.C=nx,t=t.P):(n.L.C===rx&&(n.R.C=rx,n.C=nx,dx(e,n),n=t.P.L),n.C=t.P.C,t.P.C=rx,n.L.C=rx,fx(e,t.P),t=e.root));t.C=rx}function hx(e){for(;e.L!==$;)e=e.L;return e}function gx(e,t){let n;for(;t.P.C===nx;)t.P===t.P.P.L?(n=t.P.P.R,n.C===nx?(t.P.C=rx,n.C=rx,t.P.P.C=nx,t=t.P.P):(t===t.P.R&&(t=t.P,dx(e,t)),t.P.C=rx,t.P.P.C=nx,fx(e,t.P.P))):(n=t.P.P.L,n.C===nx?(t.P.C=rx,n.C=rx,t.P.P.C=nx,t=t.P.P):(t===t.P.L&&(t=t.P,fx(e,t)),t.P.C=rx,t.P.P.C=nx,dx(e,t.P.P)));e.root.C=rx}function _x(){let e={root:$,size:0},t={};return{insert(n,r,i){let a=e.root,o=$;for(;a!==$&&(o=a,n!==o.low);)a=n<a.low?a.L:a.R;if(n===o.low&&o!==$){if(!sx(o,r,i))return;o.high=Math.max(o.high,r),lx(o),ux(o),t[i]=o,e.size++;return}let s={low:n,high:r,max:r,C:nx,P:o,L:$,R:$,list:{index:i,high:r,next:null}};o===$?e.root=s:(s.low<o.low?o.L=s:o.R=s,ux(s)),gx(e,s),t[i]=s,e.size++},remove(n){let r=t[n];if(r===void 0)return;delete t[n];let i=cx(r,n);if(i===void 0)return;if(i===ox){r.high=r.list.high,lx(r),ux(r),e.size--;return}let a=r,o=a.C,s;r.L===$?(s=r.R,px(e,r,r.R)):r.R===$?(s=r.L,px(e,r,r.L)):(a=hx(r.R),o=a.C,s=a.R,a.P===r?s.P=a:(px(e,a,a.R),a.R=r.R,a.R.P=a),px(e,r,a),a.L=r.L,a.L.P=a,a.C=r.C),lx(s),ux(s),o===rx&&mx(e,s),e.size--},search(t,n,r){let i=[e.root];for(;i.length!==0;){let e=i.pop();if(!(e===$||t>e.max)&&(e.L!==$&&i.push(e.L),e.R!==$&&i.push(e.R),e.low<=n&&e.high>=t)){let n=e.list;for(;n!==null;)n.high>=t&&r(n.index,e.low),n=n.next}}},get size(){return e.size}}}var vx=e=>{let t=X.useRef(e);return X.useEffect(()=>{t.current=e}),t},yx=(e,t)=>{let n=t||bx,r,i;return function(){return r&&n(arguments,r)?i:i=e.apply(null,r=arguments)}},bx=(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3],xx=class{constructor(){this.set=void 0,this.get=void 0;let e,t;this.get=n=>n===e?t:void 0,this.set=(n,r)=>{e=n,t=r}}},Sx=e=>{try{return new e}catch{let e={};return{set(t,n){e[t]=n},get(t){return e[t]}}}},Cx=e=>{let t=e.length,n=Sx(e[0]),r,i,a,o,s=t===1;return t<3?{g:e=>(r=n.get(e[0]))===void 0||s?r:r.get(e[1]),s:(t,a)=>(s?n.set(t[0],a):(r=n.get(t[0]))===void 0?(i=Sx(e[1]),i.set(t[1],a),n.set(t[0],i)):r.set(t[1],a),a)}:{g:e=>{for(o=n,a=0;a<t;a++)if((o=o.get(e[a]))===void 0)return;return o},s:(r,s)=>{for(o=n,a=0;a<t-1;a++)(i=o.get(r[a]))===void 0?(i=Sx(e[a+1]),o.set(r[a],i),o=i):o=i;return o.set(r[t-1],s),s}}},wx=(e,t)=>{let n,{g:r,s:i}=Cx(e);return function(){return(n=r(arguments))===void 0?i(arguments,t.apply(null,arguments)):n}},Tx=new WeakMap;function Ex(){let e=X.useState(Dx)[1];return X.useRef(()=>e({})).current}var Dx={},Ox=X.createElement;function kx(e){let{positioner:t,resizeObserver:n,items:r,as:i=`div`,id:a,className:o,style:s,role:c=`grid`,tabIndex:l=0,containerRef:u,itemAs:d=`div`,itemStyle:f,itemHeightEstimate:p=300,itemKey:m=Fx,overscanBy:h=2,scrollTop:g,isScrolling:_,height:v,render:y,onRender:b}=e,x=0,S,C=Ex(),w=Lx(t,n),T=r.length,{columnWidth:E,columnCount:D,range:O,estimateHeight:k,size:A,shortestColumn:j}=t,M=A(),N=j(),P=[],F=c===`list`?`listitem`:c===`grid`?`gridcell`:void 0,I=vx(b);h=v*h;let ee=g+h,L=N<ee&&M<T;if(O(Math.max(0,g-h/2),ee,(e,t,n)=>{let i=r[e],a=m(i,e),o={top:n,left:t,width:E,writingMode:`horizontal-tb`,position:`absolute`};P.push(Ox(d,{key:a,ref:w(e),role:F,style:typeof f==`object`&&f?Object.assign({},o,f):o},jx(y,e,i,E))),S===void 0?(x=e,S=e):(x=Math.min(x,e),S=Math.max(S,e))}),L){let e=Math.min(T-M,Math.ceil((g+h-N)/p*D)),t=M,n=Ix(E);for(;t<M+e;t++){let e=r[t],i=m(e,t);P.push(Ox(d,{key:i,ref:w(t),role:F,style:typeof f==`object`?Object.assign({},n,f):n},jx(y,t,e,E)))}}X.useEffect(()=>{typeof I.current==`function`&&S!==void 0&&I.current(x,S,r),Ax=`1`},[x,S,r,I]),X.useEffect(()=>{L&&C()},[L,t]);let R=Mx(_,k(T,p));return Ox(i,{ref:u,key:Ax,id:a,role:c,className:o,tabIndex:l,style:typeof s==`object`?Px(R,s):R,children:P})}var Ax=`0`,jx=wx([xx,{},WeakMap,xx],(e,t,n,r)=>Ox(e,{index:t,data:n,width:r})),Mx=yx((e,t)=>({position:`relative`,width:`100%`,maxWidth:`100%`,height:Math.ceil(t),maxHeight:Math.ceil(t),willChange:e?`contents`:void 0,pointerEvents:e?`none`:void 0})),Nx=(e,t)=>e[0]===t[0]&&e[1]===t[1],Px=yx((e,t)=>Object.assign({},e,t),Nx);function Fx(e,t){return t}var Ix=yx(e=>({width:e,zIndex:-1e3,visibility:`hidden`,position:`absolute`,writingMode:`horizontal-tb`}),(e,t)=>e[0]===t[0]),Lx=yx((e,t)=>n=>r=>{r!==null&&(t&&(t.observe(r),Tx.set(r,n)),e.get(n)===void 0&&e.set(n,r.offsetHeight))},Nx),Rx=function(e,t,n,r){n===void 0&&(n=0),r===void 0&&(r=n);let i=_x(),a=Array(e),o=[],s=Array(e);for(let t=0;t<e;t++)a[t]=0,s[t]=[];return{columnCount:e,columnWidth:t,set:function(e,c){c===void 0&&(c=0);let l=0;for(let e=1;e<a.length;e++)a[e]<a[l]&&(l=e);let u=a[l]||0;a[l]=u+c+r,s[l].push(e),o[e]={left:l*(t+n),top:u,height:c,column:l},i.insert(u,u+c,e)},get:e=>o[e],update:t=>{let n=Array(e),c=0,l=0;for(;c<t.length-1;c++){let e=t[c],r=o[e];r.height=t[++c],i.remove(e),i.insert(r.top,r.top+r.height,e),n[r.column]=n[r.column]===void 0?e:Math.min(e,n[r.column])}for(c=0;c<n.length;c++){if(n[c]===void 0)continue;let e=s[c],t=zx(e,n[c]),u=s[c][t],d=o[u];for(a[c]=d.top+d.height+r,l=t+1;l<e.length;l++){let t=e[l],n=o[t];n.top=a[c],a[c]=n.top+n.height+r,i.remove(t),i.insert(n.top,n.top+n.height,t)}}},range:(e,t,n)=>i.search(e,t,(e,t)=>n(e,o[e].left,t)),estimateHeight:(t,n)=>{let r=Math.max(0,Math.max.apply(null,a));return t===i.size?r:r+Math.ceil((t-i.size)/e)*n},shortestColumn:()=>a.length>1?Math.min.apply(null,a):a[0]||0,size(){return i.size},all(){return o}}},zx=(e,t)=>{let n=0,r=e.length-1;for(;n<=r;){let i=n+r>>>1,a=e[i];if(a===t)return i;a<=t?n=i+1:r=i-1}return-1},Bx=0,Vx=320,Hx=656;function Ux(e,t){return e<=0||!Number.isFinite(t)||t<=0?0:e===1?1:e<=4?2:t>=1280?4:t>=Hx?3:2}function Wx({item:e}){return Jr(e.path)?(0,Z.jsx)(`video`,{"aria-label":e.path,className:`block h-full w-full object-cover`,"data-media-thumb":!0,loop:!0,muted:!0,playsInline:!0,src:e.url}):(0,Z.jsx)(`img`,{alt:e.path,className:`block h-full w-full object-cover`,"data-media-thumb":!0,src:e.url})}var Gx=(0,X.memo)(function({item:e}){let t=(0,X.useRef)(null);(0,X.useEffect)(()=>{e.onVisible?.()},[e.onVisible]);let[n,r]=(0,X.useState)(e.pending===!0&&!e.onVisible);return e.pending&&!e.onVisible&&!n&&r(!0),(0,X.useLayoutEffect)(()=>{let r=t.current;if(!r||e.pending||n)return;let i=window.matchMedia(`(prefers-reduced-motion: reduce)`);if(i.matches)return;let a=!0,o,s,c=()=>o?.();return ki(async()=>{let{animate:e,spring:t}=await import(`./modules-C4mfDnjH.js`).then(e=>e.t);return{animate:e,spring:t}},__vite__mapDeps([3,1]),import.meta.url).then(({animate:e,spring:t})=>{if(!a)return;let n=e(r,{opacity:{from:0,to:1,duration:160,ease:`outQuad`},translateY:{from:6,to:0,ease:t({bounce:.16,duration:320})},scale:{from:.985,to:1,ease:t({bounce:.16,duration:320})}});o=()=>{n.complete()},s=()=>{n.revert()}}),i.addEventListener(`change`,c),()=>{a=!1,i.removeEventListener(`change`,c),s?.()}},[e.key,e.pending,n]),(0,Z.jsxs)(`div`,{ref:t,className:`prints-gallery-tile`,"data-referenced":e.referenced?!0:void 0,children:[e.error?(0,Z.jsx)(`div`,{className:`block h-full w-full overflow-hidden bg-base-200`,"data-media-failed":!0,title:e.path,children:(0,Z.jsx)(ap,{status:`failed`,failure:(0,Z.jsxs)(`div`,{className:`flex max-w-full flex-col items-center gap-xs`,children:[e.prompt?(0,Z.jsx)(`p`,{className:`m-0 max-w-full truncate px-md text-xs text-(--stipe-fg-muted)`,children:e.prompt}):null,(0,Z.jsx)(rp,{density:`tile`,message:e.error,onRetry:e.onRetry,onDismiss:e.onDismiss})]})})}):(0,Z.jsx)(`button`,{className:`block h-full w-full overflow-hidden bg-base-200 p-0 text-left`,"data-media-thumb-wrap":!0,type:`button`,disabled:e.pending,onClick:()=>{e.onOpen(e.path)},onKeyDown:t=>{t.key.toLowerCase()===`i`&&!t.ctrlKey&&!t.metaKey&&!t.altKey&&e.onInfo&&(t.preventDefault(),e.onInfo())},title:e.path,children:(0,Z.jsx)(`div`,{className:`caps-item block! h-full w-full overflow-hidden rounded-none! border-0! bg-transparent! shadow-none! z-auto! -outline-offset-2!`,"data-selected":e.selected??!1,children:e.pending||n?(0,Z.jsx)(ap,{"data-media-pending":e.pending?`true`:void 0,indicator:(0,Z.jsx)(rt,{decorative:!0,size:`fill`,tone:`accent`,variant:`bloom`}),label:e.pendingLabel??`Preparing image…`,status:e.pending?`generating`:`done`,children:e.pending?null:(0,Z.jsx)(Wx,{item:e})}):(0,Z.jsx)(Wx,{item:e})})}),(0,Z.jsxs)(`div`,{className:`prints-gallery-tools`,children:[!e.pending&&e.onInfo?(0,Z.jsx)(ln,{"aria-label":`Image info: ${e.path}`,title:`Image info (I)`,"aria-keyshortcuts":`I`,onClick:e.onInfo,icon:(0,Z.jsx)(fm,{})}):null,!e.pending&&e.onToggleReference?(0,Z.jsx)(ln,{className:`prints-gallery-reference`,"aria-label":`${e.referenced?`Remove reference`:`Add reference`}: ${e.path}`,title:e.referenced?`Remove reference`:`Add reference`,"aria-pressed":e.referenced??!1,disabled:e.referenceDisabled,onClick:e.onToggleReference,icon:e.referenced?(0,Z.jsx)(da,{}):(0,Z.jsx)(dm,{})}):null]})]})}),Kx=(0,X.memo)(function({children:e,style:t,...n}){return(0,Z.jsx)(`div`,{"data-media-grid":!0,...n,style:t,children:e})});function qx(e,t){let[n,r]=(0,X.useState)({height:0,width:0});return(0,X.useEffect)(()=>{let t=e.current;if(!t)return;let n=()=>{r(e=>{let n={height:t.clientHeight,width:t.clientWidth};return n.width===e.width&&n.height===e.height?e:n})};n();let i=new ResizeObserver(n);return i.observe(t),window.addEventListener(`resize`,n),()=>{i.disconnect(),window.removeEventListener(`resize`,n)}},[e,t]),n}function Jx(e){let[t,n]=(0,X.useState)(0),[r,i]=(0,X.useState)(!1);return(0,X.useEffect)(()=>{let t=e.current;if(!t)return;let r=null,a=()=>{n(t.scrollTop),i(!0),r!==null&&clearTimeout(r),r=setTimeout(()=>{i(!1)},150)};return t.addEventListener(`scroll`,a,{passive:!0}),()=>{t.removeEventListener(`scroll`,a),r!==null&&clearTimeout(r)}},[e]),{isScrolling:r,scrollTop:t}}function Yx(e,t,n=1/0){let r=t.height>0?t.width/t.height:1;return Math.min(Math.round(e/r),n)}var Xx=640;function Zx(e){return e<Xx?16:24}function Qx(e,t){return e<=4&&t>0?t:1/0}function $x(e,t,n,r){let i=Math.floor((t-(n-1)*Bx)/n),a=e.length===1?e[0]:void 0;if(!a||r<=0)return i;let o=a.height>0?a.width/a.height:1;return Math.max(1,Math.min(i,Math.floor(r*o)))}function eS(e,t,n){let r=Math.max(1,Ux(e.length,t));return(0,X.useMemo)(()=>{let i=$x(e,t,r,n),a=Qx(e.length,n),o=Rx(r,i,Bx);return i>0&&e.forEach((e,t)=>{o.set(t,Yx(i,e,a))}),o},[e,t,r,n])}var tS=(0,X.memo)(function({data:e,width:t,maxHeight:n}){return(0,Z.jsx)(`div`,{"data-media-tile":e.key,style:{height:Yx(t,e,n),width:t},children:(0,Z.jsx)(Gx,{item:e})})});function nS(e,t){let n=Array.from(e.querySelectorAll(`[data-media-tile]`)).find(e=>e.dataset.mediaTile===t)?.querySelector(`[data-media-thumb-wrap]`);return!n||n.disabled?!1:(n.focus({preventScroll:!0}),!0)}function rS(e,t,n){let r=e.ownerDocument;(r.activeElement!==r.body||nS(e,t))&&n()}function iS(e,t,n){let r=n.top+t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop;return(r<e.scrollTop||r+n.height>e.scrollTop+e.clientHeight)&&e.scrollTo({top:r,behavior:`instant`}),r}var aS=(0,X.memo)(function({items:e,scrollRef:t,focus:n}){let r=qx(t,e.length),i=r.width||Vx,a=e.length<=4&&r.height>0,o=a?Zx(i):0,s=i-2*o,c=r.height-2*o,l=eS(e,s,a?c:r.height),u=e.length===1?$x(e,s,1,c):void 0,d=Qx(e.length,a?c:0),{isScrolling:f,scrollTop:p}=Jx(t),m=(0,X.useRef)(new Set),h=(0,X.useRef)(null),g=(0,X.useRef)(null);(0,X.useEffect)(()=>{if(!n)return;let a=h.current===n.requestId;if(a&&g.current===i)return;let o=t.current,s=e.findIndex(e=>e.key===n.key),c=l.get(s);if(!o||!c||r.height===0)return;let u=o.querySelector(`[data-media-grid]`);if(!u)return;let d=iS(o,u,c);if(a){rS(o,n.key,()=>{g.current=i});return}nS(o,n.key)?(h.current=n.requestId,g.current=i,n.onFocus()):o.scrollTo({top:d,behavior:`instant`})},[n,e,r.height,t,p,l,i]),(0,X.useEffect)(()=>{let n=t.current;if(!n||r.width===0||r.height===0)return;let i=e.reduce((e,t,n)=>t.pending&&!t.onVisible&&!m.current.has(t.key)?n:e,-1);if(m.current=new Set(e.map(e=>e.key)),i<0)return;let a=l.get(i),o=n.querySelector(`[data-media-grid]`);if(!a||!o)return;let s=o.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop+a.top,c=s+a.height;s>=n.scrollTop&&c<=n.scrollTop+n.clientHeight||n.scrollTo({top:Math.max(0,s-Math.max(0,(n.clientHeight-a.height)/2)),behavior:window.matchMedia(`(prefers-reduced-motion: reduce)`).matches?`instant`:`smooth`})},[e,r.width,r.height,t,l]);let _=(0,X.useCallback)(({data:e,width:t})=>(0,Z.jsx)(tS,{data:e,width:t,maxHeight:d}),[d]),v=kx({as:Kx,height:r.height,isScrolling:f,itemKey:e=>e.key,items:e,overscanBy:2,positioner:l,render:_,scrollTop:p});return(0,Z.jsx)(`div`,{"data-media-sparse":a?``:void 0,style:a?{display:`flex`,alignItems:i<Xx?`flex-start`:`center`,justifyContent:`center`,boxSizing:`border-box`,padding:o,minHeight:r.height}:void 0,children:(0,Z.jsx)(`div`,{style:{width:a?u??`100%`:`100%`},children:v})})});function oS({items:e,scrollRef:t,focus:n}){return(0,Z.jsx)(`section`,{"data-media-mosaic":!0,children:(0,Z.jsx)(aS,{items:e,scrollRef:t,focus:n})})}function sS(e,t,n){let r=new Map(e.map(e=>[e.key,e])),i=new Set(t.map(e=>e.key));return[...t.filter(e=>!e.resolved||r.has(e.key)).map(e=>{let t=r.get(e.key);return t&&e.resolved?t:n(e)}),...e.filter(e=>!i.has(e.key))]}var cS=`prints-prompt-counter`;function lS({busy:e,disabled:t,disabledReason:n,draft:r,label:i,onGenerate:a,promptOver:o}){return(0,Z.jsx)(vv,{"aria-describedby":o?cS:void 0,"aria-label":i,className:`prints-generate`,"data-generation-submit":!0,disabled:t||o,onClick:a,state:Bv({draft:r,busy:e}),title:t&&n?n:i})}function uS({caretRequest:e,disabled:t,maxLength:n,addedLength:r=0,menu:i,mentionCount:a,onCaret:o,onChange:s,onMentionDismiss:c,onMentionMove:l,onMentionPick:u,onSend:d,onSlashMove:f,onSlashPick:p,placeholder:m,slashCount:h,value:g}){let _=(0,X.useRef)(null),v=(0,X.useRef)(g),[y,b]=(0,X.useState)([]),[x,S]=(0,X.useState)(-1),[C,w]=(0,X.useState)(!1),T=(0,X.useRef)(!1),E=(0,X.useRef)(!1);v.current=g,(0,X.useLayoutEffect)(()=>{if(C||t||!E.current)return;E.current=!1;let e=_.current;e&&e.ownerDocument.activeElement===e.ownerDocument.body&&e.focus({preventScroll:!0})},[t,C]),(0,X.useLayoutEffect)(()=>{let t=_.current;!t||e?.value!==g||(t.setSelectionRange(e.caret,e.caret),t.focus({preventScroll:!0}))},[e,g]),Hv(_,g);let D=(0,X.useCallback)(async()=>{let e=v.current.trim();if(!(!e||t||T.current)&&!(n!==void 0&&e.length+r>n)){E.current=_.current===_.current?.ownerDocument.activeElement,T.current=!0,w(!0);try{if(!await d())return;b(t=>t.at(-1)===e?t:[...t,e].slice(-20)),S(-1)}finally{T.current=!1,w(!1)}}},[t,n,d,r]),O=g.trim().length,k=O>0?O+r:0,A=n!==void 0&&k>n;return(0,Z.jsxs)(`div`,{className:`relative min-w-0 flex-1`,children:[(0,Z.jsx)(Dv,{"aria-invalid":A?!0:void 0,"aria-label":`Image prompt`,className:`w-full`,"data-generation-prompt":!0,...Av(i),disabled:t===!0||C,onChange:e=>{s(e.currentTarget.value),o(e.currentTarget.selectionStart),S(-1)},onSelect:e=>{o(e.currentTarget.selectionStart)},onKeyDown:e=>{if(pv(e))return;let t=kv(e);if(a>0&&t!==null){e.preventDefault(),t===`next`?l(1):t===`previous`?l(-1):t===`accept`?u():c();return}if(g.startsWith(`/`)&&t!==null&&(h>0||t===`dismiss`||e.key===`Enter`)){if(e.preventDefault(),t===`dismiss`)s(g.slice(1));else if(h)t===`next`?f(1):t===`previous`?f(-1):p();else return;return}if(e.key===`Enter`&&!e.shiftKey){e.preventDefault(),D();return}if(e.key===`ArrowUp`&&_.current?.selectionStart===0&&y.length&&(x===-1||x>0)){e.preventDefault();let t=x===-1?y.length-1:x-1;S(t),s(y[t]);return}if(e.key===`ArrowDown`&&x!==-1){e.preventDefault();let t=x+1;t>=y.length?(S(-1),s(``)):(S(t),s(y[t]))}},placeholder:m,ref:_,rows:1,value:g}),n!==void 0&&k>0?(0,Z.jsx)(`p`,{className:`px-3 pb-1 text-xs tabular-nums ${A?`text-error`:`text-dim`}`,"data-prompt-counter":!0,id:cS,role:A?`alert`:`status`,children:A?`${String(k)} / ${String(n)} characters. This model accepts up to ${String(n)}; shorten the prompt${r>0?` or its style and characters`:``} by ${String(k-n)} or pick another model.`:`${String(k)} / ${String(n)}`}):null]})}function dS({index:e,listId:t,matches:n,onHighlight:r,onPick:i}){return(0,Z.jsx)(jv,{open:!0,rows:n.map(e=>({key:e.id,label:`/${e.slash}`,detail:e.description??e.title})),selected:e,listId:t,label:`Commands`,kind:`commands`,empty:`No matching commands`,onHighlight:r,onChoose:i})}function fS(e,t){let[n,r]=(0,X.useState)(0),i=t.startsWith(`/`),a=(0,X.useMemo)(()=>{if(!i)return[];let n=dv(e.map((e,t)=>({alias:e.slash,commandId:e.id,command:e.command,title:e.title,description:e.description,category:`Prompt`,order:t,keys:[],availability:{status:`available`}})),t,{idleCategory:`Prompt`});return n.kind===`commands`?n.items.flatMap(({command:t})=>e.find(e=>e.id===t.commandId)??[]):[]},[t,e,i]);return(0,X.useEffect)(()=>{r(0)},[t]),{moveSlash:e=>{r(t=>a.length?(t+e+a.length)%a.length:0)},highlightSlash:r,resetSlash:()=>{r(0)},slashIndex:n,slashMatches:a,slashOpen:i}}function pS({images:e,index:t,listId:n,matches:r,onHighlight:i,onPick:a}){return(0,Z.jsx)(jv,{open:!0,rows:r.map(t=>{let n=t.references.at(0)?.path,r=e.find(e=>e.path===n);return{key:String(t.id),label:`@${t.name}`,detail:t.description||void 0,media:(0,Z.jsx)(`span`,{className:`prints-character-thumb mask mask-squircle`,children:r?(0,Z.jsx)(`img`,{src:r.url,alt:``}):null})}}),selected:t,listId:n,label:`Characters`,kind:`characters`,onHighlight:i,onChoose:a})}function mS(e,t){let[n,r]=(0,X.useState)(0),[i,a]=(0,X.useState)(0),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(null),u=o===t?null:$i(t,n),d=u?ka(e,u.query):[];return(0,X.useEffect)(()=>{a(0)},[t]),{caretRequest:c,matches:d,index:i,setCaret:r,highlight:a,dismiss:()=>{s(t)},move:e=>{a(t=>d.length?(t+e+d.length)%d.length:0)},complete:e=>{let i=d.at(e);if(!u||!i)return null;let a=`${t.slice(0,u.start)}@${i.name} ${t.slice(n)}`,o=u.start+i.name.length+2;return l({value:a,caret:o}),r(o),a}}}function hS(e){let t=Qt(),n=la(xa(e)),r=n=>({mutationFn:t=>{let r=e?.context.get().computerId;if(!e||!r)throw Error(`No Computer selected`);return n(e,r,t)},onSuccess:n=>{t.setQueryData(oa.characters(e),n)}}),i=ve(r((e,t,n)=>Ca(e.capabilities,t,n))),a=ve(r((e,t,n)=>ca(e.capabilities,t,n))),o=i.error??a.error??n.error;return{characters:n.data?.characters??[],error:o?rn(o).message:null,busy:i.isPending||a.isPending,save:(e,t)=>{i.mutate(e,{onSuccess:t})},remove:(e,t)=>{a.mutate(e,{onSuccess:t})}}}var gS=z(ma),_S=e=>e.split(`/`).at(-1)??e;function vS({paths:e,images:t}){return(0,Z.jsx)(`span`,{className:`flex gap-xs`,children:e.map(e=>{let n=t.find(t=>t.path===e);return(0,Z.jsx)(`span`,{className:`prints-character-thumb mask mask-squircle`,title:e,children:n?(0,Z.jsx)(`img`,{src:n.url,alt:_S(e)}):null},e)})})}function yS({characters:e,images:t,open:n,onOpenChange:r,busy:i,error:a,canUpload:o,onUpload:s,onSave:c,onDelete:l}){let[u,d]=(0,X.useState)(null),f=(0,X.useId)(),p=u?.name.trim()??``,m=p.startsWith(`@`)?p.slice(1):p,h=[];m===``?h.push(`Enter a character name.`):m.length>32?h.push(`Use 32 characters or fewer for the name.`):gS(m)||h.push(`Use only letters, numbers, hyphens (-) and underscores (_).`),u?.references.length===0&&h.push(`Select at least one reference image.`),i&&h.push(`Wait for the current character change to finish, then save.`);let g=h.length>0,_=g?f:void 0;return(0,Z.jsx)(Lf,{open:n,onOpenChange:e=>{e||d(null),r(e)},children:(0,Z.jsxs)(Hf,{children:[(0,Z.jsx)(Wf,{children:(0,Z.jsx)(Gf,{children:`Characters`})}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-sm`,children:[e.length===0&&u===null?(0,Z.jsx)(`p`,{className:`text-sm`,children:`No characters yet. Save one, then type @name in a prompt to keep it the same in every image.`}):(0,Z.jsx)(`ul`,{className:`flex flex-col gap-sm`,"aria-label":`Saved characters`,children:e.map(e=>(0,Z.jsxs)(`li`,{className:`flex items-center justify-between gap-sm`,children:[(0,Z.jsxs)(`span`,{className:`flex min-w-0 items-center gap-sm`,children:[(0,Z.jsx)(vS,{paths:e.references.map(e=>e.path),images:t}),(0,Z.jsxs)(`span`,{className:`min-w-0 truncate`,children:[`@`,e.name]})]}),(0,Z.jsxs)(`span`,{className:`flex gap-xs`,children:[(0,Z.jsx)(Y,{size:`xs`,variant:`ghost`,type:`button`,onClick:()=>{d(e)},children:`Edit`}),(0,Z.jsx)(Y,{size:`xs`,variant:`ghost`,type:`button`,disabled:i,onClick:()=>{l(e,()=>{u?.id===e.id&&d(null)})},children:`Delete`})]})]},e.id))}),u===null?(0,Z.jsx)(Y,{size:`xs`,type:`button`,onClick:()=>{d({name:``,description:``,references:[]})},children:`New character`}):(0,Z.jsxs)(`div`,{className:`flex flex-col gap-sm`,children:[(0,Z.jsx)($g,{"aria-label":`Character name`,"aria-invalid":!gS(m),"aria-describedby":_,maxLength:33,placeholder:`Name, typed as @name`,value:u.name,onChange:e=>{d({...u,name:e.currentTarget.value})}}),(0,Z.jsx)(Dv,{"aria-label":`Character description`,maxLength:500,rows:4,placeholder:`Short description added to the prompt, e.g. a tall girl with silver hair and a red scarf`,value:u.description,onChange:e=>{d({...u,description:e.currentTarget.value})}}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-sm`,children:[(0,Z.jsxs)(`span`,{className:`text-xs`,children:[`Reference images · `,u.references.length,` selected, up to`,` `,8]}),(0,Z.jsxs)(Y,{size:`xs`,variant:`ghost`,type:`button`,disabled:!o,onClick:s,children:[(0,Z.jsx)(vm,{"aria-hidden":`true`,size:14}),`Upload`]})]}),t.length===0?(0,Z.jsx)(`p`,{className:`text-xs`,children:`No images in the Prints folder yet. Upload one to use it as a reference.`}):(0,Z.jsx)(`ul`,{className:`prints-character-picker`,"aria-label":`Reference images`,children:t.map(e=>{let t=u.references.some(t=>t.path===e.path);return(0,Z.jsx)(`li`,{title:e.path,children:(0,Z.jsxs)(`label`,{className:`prints-character-pick`,children:[(0,Z.jsx)(`img`,{src:e.url,alt:``}),(0,Z.jsx)(`span`,{className:`prints-character-check`,children:(0,Z.jsx)(Fv,{"aria-label":`Use ${_S(e.path)}`,checked:t,disabled:!t&&u.references.length>=8,onChange:()=>{d({...u,references:t?u.references.filter(t=>t.path!==e.path):[...u.references,{path:e.path}]})}})})]})},e.path)})}),g?(0,Z.jsx)(`p`,{id:f,role:`status`,className:`text-xs`,children:h.join(` `)}):null,(0,Z.jsxs)(`div`,{className:`flex gap-xs`,children:[(0,Z.jsx)(Y,{size:`xs`,variant:`primary`,type:`button`,disabled:g,"aria-describedby":_,onClick:()=>{c({id:u.id,name:m,description:u.description.trim(),references:u.references},()=>{d(null)})},children:`Save character`}),(0,Z.jsx)(Y,{size:`xs`,variant:`ghost`,type:`button`,onClick:()=>{d(null)},children:`Cancel`})]})]}),a?(0,Z.jsx)(`p`,{role:`alert`,className:`text-xs`,children:a}):null]}),(0,Z.jsx)(Uf,{children:(0,Z.jsx)(Kf,{render:(0,Z.jsx)(Y,{variant:`outline`,size:`sm`}),children:`Close`})})]})})}var bS=Ue({destination:K(lt(Tn)),height:K(Ze),model:K(Tn),prompt:K(Tn),references:K(qe(Ue({computerId:K(Tn),path:Tn,role:K(Wt([`first-frame`,`last-frame`,`reference`]))}))),generateAudio:K(lt(Et)),steps:K(lt(Ze)),style:K(lt(Tn)),width:K(Ze)}),xS=Fe(i(),N()).parse(structuredClone(Te(bS,{onExcessProperty:`error`}).schema)),SS=(e,t,n,r)=>({id:e,title:t,category:`Image generation`,description:n,projections:{agent:{}},action:r===void 0?{presentation:{type:`action`}}:{inputSchema:r,presentation:{type:`action`}}}),CS=SS(`inspect-generation-draft`,`Inspect image draft`,`Read the current Prints image form and available models`),wS=SS(`set-generation-draft`,`Edit image draft`,`Set selected Prints image form fields; this does not generate an image`,xS),TS=SS(`submit-generation-draft`,`Generate image`,`Submit the current Prints image form using the same action as the Send button`);function ES(e,t){let n=!1,r=new Set,i=(t,i)=>{e.commands.register(t,i).then(e=>{n?e():r.add(e)},()=>void 0)};return i(CS,()=>{if(n)return;let e=t.readDraft();return{draft:{destination:e.destination??null,height:e.height,model:e.model,prompt:e.prompt,generateAudio:e.generateAudio??null,references:e.references.map(e=>{let t={path:e.path,role:e.role??null};return e.computerId===void 0?t:{...t,computerId:e.computerId}}),steps:e.steps??null,style:e.style??null,width:e.width},models:t.readModels().map(e=>({id:e.id,label:e.label,defaultHeight:e.input.defaultHeight,defaultWidth:e.input.defaultWidth,maxReferences:e.input.maxReferences}))}}),i(wS,({arguments:e})=>{if(n)return;let r=o(bS,{onExcessProperty:`error`})(e);t.setDraft(r)}),i(TS,async()=>{if(!n)return{accepted:await t.submit()}}),()=>{if(!n){n=!0;for(let e of r)e();r.clear()}}}function DS(e){return[{id:`clear-prompt`,title:`Clear prompt`,category:`Prompt`,description:`Remove the current prompt`,projections:{slash:{aliases:[`clear`],order:0},palette:{}},handler:()=>{e().clear()}},...aa.map((t,n)=>({id:`size-${t}`,title:`Use ${t} size`,category:`Prompt`,description:`Use ${String(Ei[t].width)} × ${String(Ei[t].height)}`,projections:{slash:{aliases:[t],order:n+1},palette:{}},handler:()=>{e().useSize(t)}})),{id:`choose-style`,title:`Choose style`,category:`Prompt`,description:`Pick, create or edit a saved style`,projections:{slash:{aliases:[`style`],order:4},palette:{}},handler:()=>{e().openStyles()}},{id:`no-style`,title:`Use no style`,category:`Prompt`,description:`Send the prompt without a style`,projections:{slash:{aliases:[`nostyle`],order:5},palette:{}},handler:()=>{e().clearStyle()}}]}function OS(e,t){let n=(0,X.useRef)(e);n.current=e;let r=zd(t,{sourceId:`media-prompt`,namespace:`media`},(0,X.useCallback)(()=>DS(()=>n.current),[])),i=(0,X.useSyncExternalStore)(r.subscribe,r.snapshot,r.snapshot);return{items:(0,X.useMemo)(()=>sv(i).map(e=>({id:e.commandId,command:e.command,slash:e.alias,title:e.title,description:e.description})),[i]),run:e=>{r.execute(e,{origin:`slash`})}}}function kS(e){let t=Qt(),n=la(Ji(e)),r=n=>({mutationFn:t=>{let r=e?.context.get().computerId;if(!e||!r)throw Error(`No Computer selected`);return n(e,r,t)},onSuccess:n=>{t.setQueryData(oa.styles(e),n)}}),i=ve(r((e,t,n)=>Ta(e.capabilities,t,n))),a=ve(r((e,t,n)=>Da(e.capabilities,t,n))),o=i.error??a.error??n.error;return{styles:n.data?.styles??[],error:o?rn(o).message:null,busy:i.isPending||a.isPending,save:(e,t)=>{i.mutate(e,{onSuccess:n=>{t(n.styles.find(t=>t.name===e.name))}})},remove:(e,t)=>{a.mutate(e,{onSuccess:t})}}}function AS(e){let t=e.filter(e=>e.kind===`video`&&e.video!==null&&e.input.maxReferences>=1&&e.video.referenceRoles.includes(`first-frame`));return t.find(e=>e.video?.provider===`seedance`)??t.at(0)}function jS(e,t,n){let r=e.video;if(r===null)return;let i=Math.log(t/n),a=e=>Math.abs(Math.log(e.width/e.height)-i);return r.formats.filter(e=>e.resolution===r.defaultResolution).reduce((e,t)=>e===void 0||a(t)<a(e)?t:e,void 0)}function MS(e,t){let{lineage:n,printPath:r,models:i,current:a}=t,o=e===`animate`?AS(i):void 0;if(e===`animate`&&o===void 0)return{kind:`refused`,message:`No video model on this Computer takes a first frame.`};let s=xi(i,n.model),c=o??s??xi(i,a.model);if(c===void 0)return{kind:`refused`,message:`Choose a model from the granted registry.`};let l=o===void 0&&s===void 0?`This print was made with ${n.model}, which is no longer available. Loaded it with ${Fi(c)} instead.`:null,u=n.references.slice(0,n.typed.references),d=e===`animate`?{path:r,role:`first-frame`}:{path:r},f=[d,...u.filter(e=>!Ii(e,t.printComputerId)||e.path!==r)];if(e!==`reuse`&&c.input.maxReferences===0)return{kind:`refused`,message:`${c.label} does not take reference images.`};let p=e===`reuse`?u:e===`remix`?f:[d],m=yi(a,c),h={width:n.width??m.width,height:n.height??m.height},g=o===void 0?Ri(h,c,void 0):jS(c,h.width,h.height)??m,_=o===void 0&&c.input.steps!==`fixed`&&n.steps!==null&&c.id===n.model?n.steps:m.steps,v=n.style!==null&&t.styles.includes(n.style)?n.style:void 0;return{kind:`draft`,notice:l,draft:{...m,destination:void 0,prompt:n.typed.prompt,references:p,steps:_,style:v,width:g.width,height:g.height}}}function NS({id:e,styles:t,selected:n,disabled:r,onSelect:i}){let a=n===void 0||t.some(e=>e.name===n);return(0,Z.jsxs)(Q_,{id:e,"aria-label":`Prompt style`,"data-generation-style":!0,className:`select-sm`,disabled:r,onChange:e=>{i(e.currentTarget.value||void 0)},value:n??``,children:[(0,Z.jsx)(`option`,{value:``,children:`No style`}),a?null:(0,Z.jsx)(`option`,{value:n,children:n}),t.map(e=>(0,Z.jsx)(`option`,{value:e.name,children:e.name},e.id))]})}function PS({styles:e,selected:t,open:n,onOpenChange:r,busy:i,error:a,onSelect:o,onSave:s,onDelete:c}){let[l,u]=(0,X.useState)(null);return(0,Z.jsx)(Lf,{open:n,onOpenChange:r,children:(0,Z.jsxs)(Hf,{children:[(0,Z.jsx)(Wf,{children:(0,Z.jsx)(Gf,{children:`Styles`})}),(0,Z.jsx)(`ul`,{className:`space-y-1`,"aria-label":`Saved styles`,children:e.map(e=>(0,Z.jsxs)(`li`,{className:`flex items-center justify-between gap-sm`,children:[(0,Z.jsx)(`span`,{className:`min-w-0 truncate`,children:e.name}),(0,Z.jsxs)(`span`,{className:`flex gap-xs`,children:[(0,Z.jsx)(Y,{size:`xs`,variant:t===e.name?`primary`:`ghost`,type:`button`,"aria-pressed":t===e.name,onClick:()=>{o(e.name),r(!1)},children:`Use`}),e.builtIn?null:(0,Z.jsx)(Y,{size:`xs`,variant:`ghost`,type:`button`,onClick:()=>{u(e)},children:`Edit`}),(0,Z.jsx)(Y,{size:`xs`,variant:`ghost`,type:`button`,onClick:()=>{u({name:`${e.name} copy`.slice(0,64),text:e.text})},children:`Duplicate`}),e.builtIn?null:(0,Z.jsx)(Y,{size:`xs`,variant:`ghost`,type:`button`,disabled:i,onClick:()=>{c(e,()=>{t===e.name&&o(void 0),l?.id===e.id&&u(null)})},children:`Delete`})]})]},e.id))}),l===null?(0,Z.jsx)(Y,{size:`xs`,type:`button`,onClick:()=>{u({name:``,text:``})},children:`New style`}):(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)($g,{"aria-label":`Style name`,maxLength:64,value:l.name,onChange:e=>{u({...l,name:e.currentTarget.value})}}),(0,Z.jsx)(Dv,{"aria-label":`Style text`,maxLength:8e3,rows:6,value:l.text,onChange:e=>{u({...l,text:e.currentTarget.value})}}),(0,Z.jsxs)(`div`,{className:`flex gap-xs`,children:[(0,Z.jsx)(Y,{size:`xs`,variant:`primary`,type:`button`,disabled:i||l.name.trim()===``||l.text.trim()===``,onClick:()=>{let n=e.find(e=>e.id===l.id);s({id:l.id,name:l.name.trim(),text:l.text},e=>{n&&t===n.name&&e&&o(e.name),u(null)})},children:`Save style`}),(0,Z.jsx)(Y,{size:`xs`,variant:`ghost`,type:`button`,onClick:()=>{u(null)},children:`Cancel`})]})]}),a?(0,Z.jsx)(`p`,{role:`alert`,className:`text-xs`,children:a}):null,(0,Z.jsx)(Uf,{children:(0,Z.jsx)(Kf,{render:(0,Z.jsx)(Y,{variant:`outline`,size:`sm`}),children:`Close`})})]})})}var FS=(0,X.lazy)(async()=>({default:(await ki(()=>import(`./print-info-drawer-BWbKKKdp.js`),__vite__mapDeps([5,1,2,3,6]),import.meta.url)).PrintInfoDrawer})),IS=[`a mushroom knight`,`moss on a keyboard`,`a tiny house made of mushrooms`];function LS(e){__.error(e,{id:`prints-generation-error`,toasterId:`prints-generation-notices`})}function RS(e){let t=(0,X.useRef)(!1),n=Qg({defaultValues:Di(),onSubmit:async({value:n})=>{t.current=await e.current(n)}}),r=(0,X.useCallback)(async()=>(t.current=!1,await n.handleSubmit(),t.current),[n]);return Object.assign(n,{submitCurrent:r})}function zS({form:e,selected:t,stylePicker:n,sizeChoices:r,sizeMode:i,onCustomSize:a,onEditStyles:o,onEditCharacters:s}){let c=t?.input.dimensions===`none`,l=t!==void 0&&t.sizes!==null,u=t?.video??null;return(0,Z.jsxs)(`div`,{className:`prints-settings`,children:[(0,Z.jsx)(K_,{label:`Style`,orientation:`horizontal`,children:n}),(0,Z.jsx)(K_,{label:`Size`,orientation:`horizontal`,children:(0,Z.jsx)(Q_,{"aria-label":`Generation size`,"data-generation-size":!0,className:`select-sm`,disabled:c,title:c?`This model chooses the output size.`:void 0,onChange:t=>{let n=t.currentTarget.value;a(n===`custom`);let i=r.find(e=>e.value===n);i&&(e.setFieldValue(`width`,i.width),e.setFieldValue(`height`,i.height))},value:c?`provider`:i,children:c?(0,Z.jsx)(`option`,{value:`provider`,children:`Model default`}):(0,Z.jsxs)(Z.Fragment,{children:[l&&!r.some(e=>e.value===i)?(0,Z.jsx)(`option`,{value:i,disabled:!0,children:`Choose a supported resolution`}):null,r.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value)),l?null:(0,Z.jsx)(`option`,{value:`custom`,children:`Custom size`})]})})}),!c&&!l&&i===`custom`?(0,Z.jsxs)(`div`,{className:`prints-custom-size`,children:[(0,Z.jsx)(e.Field,{name:`width`,children:e=>(0,Z.jsx)(K_,{label:`Width`,children:(0,Z.jsx)($g,{"aria-label":`Generation width`,"data-generation-width":!0,max:4096,min:1,onChange:t=>{e.handleChange(Number(t.currentTarget.value)||1)},type:`number`,value:e.state.value})})}),(0,Z.jsx)(e.Field,{name:`height`,children:e=>(0,Z.jsx)(K_,{label:`Height`,children:(0,Z.jsx)($g,{"aria-label":`Generation height`,"data-generation-height":!0,max:4096,min:1,onChange:t=>{e.handleChange(Number(t.currentTarget.value)||1)},type:`number`,value:e.state.value})})})]}):null,u?(0,Z.jsx)(e.Field,{name:`durationSeconds`,children:e=>(0,Z.jsx)(K_,{label:`Length`,orientation:`horizontal`,children:(0,Z.jsx)(Q_,{"aria-label":`Video length in seconds`,className:`select-sm`,"data-generation-duration":!0,onChange:t=>{let n=t.currentTarget.value;e.handleChange(u.durations.find(e=>String(e)===n))},value:e.state.value===void 0?``:String(e.state.value),children:u.durations.map(e=>(0,Z.jsxs)(`option`,{value:String(e),children:[e,` seconds`]},e))})})}):null,u?.supportsAudio?(0,Z.jsx)(e.Field,{name:`generateAudio`,children:e=>u.defaultGenerateAudio===null?(0,Z.jsx)(K_,{label:`Audio`,orientation:`horizontal`,children:(0,Z.jsxs)(Q_,{"aria-label":`Video audio`,className:`select-sm`,"data-generation-audio":!0,onChange:t=>{let n=t.currentTarget.value;e.handleChange(n===``?void 0:n===`on`)},value:e.state.value===void 0?``:e.state.value?`on`:`off`,children:[(0,Z.jsx)(`option`,{value:``,children:`Model default`}),(0,Z.jsx)(`option`,{value:`on`,children:`On`}),(0,Z.jsx)(`option`,{value:`off`,children:`Off`})]})}):(0,Z.jsx)(K_,{label:`Audio`,orientation:`horizontal`,children:(0,Z.jsx)(ra,{"aria-label":`Video audio`,checked:e.state.value??!0,"data-generation-audio":!0,onCheckedChange:e.handleChange})})}):null,t&&t.input.steps!==`fixed`?(0,Z.jsx)(e.Field,{name:`steps`,children:e=>(0,Z.jsx)(K_,{label:`Steps`,optional:!0,orientation:`horizontal`,children:(0,Z.jsx)($g,{"aria-label":`Generation steps`,className:`input-sm`,"data-generation-steps":!0,max:t.input.maxSteps??void 0,min:1,onChange:t=>{e.handleChange(t.currentTarget.value===``?void 0:Number(t.currentTarget.value))},type:`number`,value:e.state.value??``})})}):null,(0,Z.jsxs)(`div`,{className:`prints-settings-library`,children:[(0,Z.jsx)(Y,{size:`xs`,variant:`ghost`,type:`button`,onClick:()=>{o()},children:`Edit styles…`}),(0,Z.jsx)(Y,{size:`xs`,variant:`ghost`,type:`button`,onClick:()=>{s()},children:`Characters…`})]})]})}function BS({actions:e,guidance:t,commandApp:n,form:r,models:i,modelsLoading:a,mediaCapability:o,submitting:s,values:c,computerId:l,mediaDirectory:u,referenceImages:d,characters:f,characterDialog:p,onSubmit:m,styleControls:h,addedLength:g}){let _=xi(i,c.model),v=c.prompt.trim().length,y=_!==void 0&&v>0&&v+g>_.maxPromptLength,b=wi(_),x=_?.video??null,S=ga(c.references,_),C=_===void 0?void 0:bi(S,_,x?.formats.find(e=>e.width===c.width&&e.height===c.height)?.resolution),w=_?.input.maxReferences??0,T=c.references.length>w,[E,D]=(0,X.useState)(!1),[O,k]=(0,X.useState)(!1),A=_!==void 0&&_.sizes!==null,j=zi(_),M=A?`${String(c.width)}x${String(c.height)}`:E?`custom`:j.find(e=>e.width===c.width&&e.height===c.height)?.value??`custom`,[N,P]=(0,X.useState)(!1),F=OS({clear:()=>{r.setFieldValue(`prompt`,``)},useSize:e=>{D(!1),r.setFieldValue(`width`,Ei[e].width),r.setFieldValue(`height`,Ei[e].height),r.setFieldValue(`prompt`,``)},openStyles:()=>{r.setFieldValue(`prompt`,``),P(!0)},clearStyle:()=>{r.setFieldValue(`style`,void 0),r.setFieldValue(`prompt`,``)}},n),[I,ee]=(0,X.useState)(!1),L=mS(f,c.prompt),R=fS(F.items,c.prompt),te=(0,X.useId)(),ne=`${te}-commands`,re=`${te}-characters`,z=Vi({computerId:l,prompt:c.prompt,saved:f,references:c.references,model:_===void 0?void 0:{label:_.label,maxReferences:_.input.maxReferences}}),ie=ta(c.prompt,f).characters,B=e=>{let t=R.slashMatches.at(e);t&&(R.resetSlash(),F.run(t.command))},V=h({open:N,onOpenChange:P}),ae=[c.style,Ci(_,c.width,c.height),x&&c.durationSeconds!==void 0?`${String(c.durationSeconds)}s`:void 0,x?.supportsAudio&&c.generateAudio===!1?`silent`:void 0].filter(e=>e!=null),H=(0,Z.jsx)(zS,{form:r,selected:_,stylePicker:V.picker,sizeChoices:j,sizeMode:M,onCustomSize:D,onEditStyles:()=>{k(!1),P(!0)},onEditCharacters:()=>{k(!1),ee(!0)}});return(0,Z.jsxs)(Vv,{"aria-label":`Image generation`,"data-generation-form":!0,attachments:c.references.length>0?(0,Z.jsx)(`div`,{className:`prints-reference-tray`,"aria-label":`Image references`,children:c.references.map((e,t)=>{let n=l!==null&&Ii(e,l)?d.find(t=>t.path===e.path):void 0,i=S[t]?.role,a=Li(b,S,t);return(0,Z.jsxs)(`div`,{className:`prints-reference-tile`,title:e.computerId===void 0?e.path:`${e.computerId}:${e.path}`,children:[(0,Z.jsx)(`div`,{className:`prints-reference-face mask mask-squircle`,children:n?(0,Z.jsx)(`img`,{src:n.url,alt:e.path.split(`/`).at(-1)}):(0,Z.jsxs)(`span`,{children:[`Ref `,t+1]})}),i===void 0?null:a===void 0?(0,Z.jsx)(`span`,{className:`prints-reference-role`,"data-reference-role":i,children:fi[i]}):(0,Z.jsx)(Y,{size:`xs`,variant:`ghost`,type:`button`,className:`prints-reference-role`,"data-reference-role":i,"aria-label":`Reference ${String(t+1)}: ${fi[i]}. Use as ${fi[a]}`,title:`Use as ${fi[a]}`,onClick:()=>{r.setFieldValue(`references`,S.map((e,n)=>n===t?{...e,role:a}:e))},children:fi[i]}),(0,Z.jsx)(ln,{icon:(0,Z.jsx)(Xi,{}),className:`prints-reference-remove`,"aria-label":`Remove reference ${String(t+1)}`,onClick:()=>{r.setFieldValue(`references`,c.references.filter((e,n)=>n!==t))}})]},JSON.stringify([e.computerId??l,e.path]))})}):void 0,input:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`form`,{"aria-busy":s,onSubmit:e=>{e.preventDefault(),m()},children:(0,Z.jsx)(r.Field,{name:`prompt`,children:e=>(0,Z.jsxs)(`div`,{className:`prints-prompt`,children:[R.slashOpen?(0,Z.jsx)(dS,{index:R.slashIndex,listId:ne,matches:R.slashMatches,onHighlight:R.highlightSlash,onPick:B}):null,!R.slashOpen&&L.matches.length>0?(0,Z.jsx)(pS,{images:d,index:L.index,listId:re,matches:L.matches,onHighlight:L.highlight,onPick:t=>{let n=L.complete(t);n!==null&&e.handleChange(n)}}):null,(0,Z.jsx)(uS,{caretRequest:L.caretRequest,menu:R.slashOpen?{open:R.slashMatches.length>0,listId:ne,selected:R.slashIndex}:{open:L.matches.length>0,listId:re,selected:L.index},mentionCount:R.slashOpen?0:L.matches.length,onCaret:L.setCaret,onMentionDismiss:L.dismiss,onMentionMove:L.move,onMentionPick:()=>{let t=L.complete(L.index);t!==null&&e.handleChange(t)},disabled:!o||a||i.length===0||s,maxLength:_?.maxPromptLength,addedLength:g,onChange:t=>{e.handleChange(t)},onSend:m,onSlashMove:R.moveSlash,onSlashPick:()=>{B(R.slashIndex)},placeholder:`What are we making?`,slashCount:R.slashMatches.length,value:e.state.value}),c.references.length>0||C!==void 0||ie.length>0?(0,Z.jsxs)(`div`,{className:`prints-composer-notes`,children:[c.references.length>0?(0,Z.jsxs)(`span`,{className:`prints-reference-count`,"data-generation-references":!0,"data-over-limit":T?``:void 0,role:T?`alert`:void 0,children:[c.references.length,` / `,w,` `,`references`,T?w===0?` — this model takes none; remove them or pick another model`:` — over this model's limit; remove some to generate`:null]}):null,C===void 0?null:(0,Z.jsx)(`span`,{className:`prints-reference-count`,"data-generation-reference-roles":!0,"data-over-limit":``,role:`alert`,children:C}),ie.length>0?(0,Z.jsx)(`span`,{className:`prints-reference-count`,"data-generation-characters":!0,"data-over-limit":z.kind===`refused`?``:void 0,role:z.kind===`refused`?`alert`:void 0,children:z.kind===`refused`?z.message:`Characters: ${ie.map(e=>e.name).join(`, `)}`}):null]}):null]})})}),t?(0,Z.jsxs)(`div`,{className:`prints-composer-guidance`,role:`status`,"data-composer-guidance":!0,children:[(0,Z.jsx)(`span`,{children:t.group===`Images`&&t.detail?t.detail:(0,Z.jsxs)(Z.Fragment,{children:[t.title,`. `,t.detail]})}),t.actions?.map(e=>(0,Z.jsx)(Y,{variant:`ghost`,size:`xs`,onClick:e.run,children:e.label},e.label))]}):null]}),row:{controls:(0,Z.jsxs)(Z.Fragment,{children:[e,(0,Z.jsx)(r.Field,{name:`model`,children:e=>(0,Z.jsx)(Uv,{models:i,emptyLabel:l===null?`Choose a Computer`:a?`Loading models…`:`Models unavailable`,disabled:a||!o,onChange:t=>{let n=xi(i,t);if(e.handleChange(t),!n)return;let a=r.store.state.fieldMeta,o=yi(c,n),s=Ri(c,n,_);(n.input.dimensions===`none`||n.sizes!==null)&&D(!1),r.setFieldValue(`width`,s.width),r.setFieldValue(`height`,s.height),r.setFieldValue(`durationSeconds`,o.durationSeconds),r.setFieldValue(`generateAudio`,o.generateAudio),(n.input.steps===`fixed`||!a.steps?.isTouched)&&r.setFieldValue(`steps`,o.steps)},value:e.state.value})}),l&&u?(0,Z.jsx)(`span`,{className:`sr-only`,"data-generation-computer":!0,title:`Where new prints are saved`,children:`Saved in your Prints folder`}):null]}),action:(0,Z.jsx)(lS,{busy:s,draft:c.prompt,disabled:!o||a||i.length===0||s,label:Si(_),onGenerate:()=>{m()},promptOver:y}),items:[{id:`settings`,accessibleLabel:`Generation settings`,title:`Settings`,label:(0,Z.jsxs)(`span`,{className:`prints-settings-chip`,children:[(0,Z.jsx)(gm,{"aria-hidden":`true`,className:`size-[var(--stipe-icon-size-sm)]`}),ae.length>0?ae.join(` · `):`Settings`]}),content:H}],openId:O?`settings`:null,onOpenChange:e=>{k(e===`settings`)}},children:[V.dialog,p({open:I,onOpenChange:ee})]})}function VS({connection:e}){let t=(0,X.useRef)(null),n=(0,X.useRef)(e);n.current=e;let r=Wv(e?.app??null),i=Id(e?.app??null)?.setup?.media===`missing`,[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(!1),l=()=>{let t=e?.app;t&&(o(!0),c(!1),t.ui.openSetup(`media`).then(e=>{o(!1),c(e===`unavailable`)},e=>{o(!1),c(!0),Qr(`open-media-setup`,e)}))},u=s?(0,Z.jsxs)(Z.Fragment,{children:[`Image setup couldn’t open.`,` `,(0,Z.jsx)(`a`,{href:`https://github.com/fungi-computer/oyster#deploy-to-cloudflare`,target:`_blank`,rel:`noreferrer`,children:`Open the image setup guide`}),`.`]}):`Image generation isn’t set up yet.`,[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(),h=tx(e?.app??null,r.computerId),[g,_]=(0,X.useState)(null),[v,y]=(0,X.useState)(null),[b,x]=(0,X.useState)(),S=(0,X.useRef)(0);(0,X.useEffect)(()=>{_(null),y(null),x(void 0)},[e,r.computerId,r.path]);let C=r.path,{gallery:w,images:T,failed:E,loading:D,gallerySlots:O,canBrowse:k,canRead:A,canWrite:j,reserveSlot:M,failSlot:N,clearSlotError:P,removeSlot:F,addComputerFile:I,retryFile:ee,uploads:L,uploadFiles:R}=qm(e,r),[te,ne]=(0,X.useState)(Date.now),re=O.some(e=>e.startedAt!==void 0&&!e.resolved&&!e.error);(0,X.useEffect)(()=>{if(!re)return;let e=setInterval(()=>{ne(Date.now())},1e3);return()=>{clearInterval(e)}},[re]);let z=mf(e,(e,t,n)=>(w.refresh(),I(e,t,n)));(0,X.useLayoutEffect)(()=>{x(void 0),z.target&&(_(null),y(null))},[z.target]);let ie=w.entries.some(e=>e.path===z.target?.path);(0,X.useEffect)(()=>{z.target&&!ie&&w.nextPageReady&&w.loadMore()},[z.target,ie,w.nextPageReady,w.loadMore]);let B=T.find(e=>e.source.kind===`computer`&&e.source.computerId===z.target?.computerId&&e.source.path===z.target.path),V=kS(e?.app??null),ae=hS(e?.app??null),H=Sh({connection:e,folder:r,styles:V.styles,characters:ae.characters,effects:{reserve:M,failed:N,notifyFailure:LS,saved:({result:e},t)=>{A?I(e.destination.path,t,e.destination.computerId):N(`${e.destination.computerId}:${e.destination.path}`,`Image saved, but this App cannot read its preview.`)}}}),{state:U,models:W,modelsLoading:oe,modelsError:se,canGenerate:G,mediaCapability:ce,pendingGenerations:le,activeGenerations:ue,recoveryError:de}=H,fe=(0,X.useRef)(W),pe=(0,X.useRef)(H);pe.current=H;let me=(0,X.useRef)(null),he=(0,X.useRef)(null),ge=(0,X.useRef)(0),[_e,ve]=(0,X.useState)(null),ye=(0,X.useRef)(H.submit);ye.current=async e=>{let t=await H.submit(e);return t&&ve(null),t};let K=RS(ye),be=e=>{K.setFieldValue(`model`,e.model),K.setFieldValue(`width`,e.width),K.setFieldValue(`height`,e.height),K.setFieldValue(`steps`,e.steps),K.setFieldValue(`durationSeconds`,e.durationSeconds),K.setFieldValue(`generateAudio`,e.generateAudio),K.setFieldValue(`prompt`,e.prompt),K.setFieldValue(`references`,e.references),K.setFieldValue(`style`,e.style),K.setFieldValue(`destination`,void 0)},xe=(0,X.useRef)(K);xe.current=K;let Se=Q(K.store,e=>e.values),Ce=Q(K.store,e=>e.isSubmitting),we=e?.app;(0,X.useEffect)(()=>{if(we)return ES(we,{readDraft:()=>xe.current.store.state.values,readModels:()=>fe.current,setDraft:e=>{let t=xe.current;if(e.model!==void 0){let n=xi(fe.current,e.model);if(!n)throw Error(`Choose a model from the granted registry.`);let r=yi(t.store.state.values,n),i=xi(fe.current,t.store.state.values.model),a=Ri(t.store.state.values,n,i);t.setFieldValue(`model`,r.model),t.setFieldValue(`width`,a.width),t.setFieldValue(`height`,a.height),t.setFieldValue(`steps`,r.steps),t.setFieldValue(`durationSeconds`,r.durationSeconds),t.setFieldValue(`generateAudio`,r.generateAudio)}e.generateAudio!==void 0&&t.setFieldValue(`generateAudio`,e.generateAudio??void 0),e.destination!==void 0&&t.setFieldValue(`destination`,e.destination??void 0),e.height!==void 0&&t.setFieldValue(`height`,e.height),e.prompt!==void 0&&t.setFieldValue(`prompt`,e.prompt),e.references!==void 0&&t.setFieldValue(`references`,e.references),e.steps!==void 0&&t.setFieldValue(`steps`,e.steps??void 0),e.style!==void 0&&t.setFieldValue(`style`,e.style??void 0),e.width!==void 0&&t.setFieldValue(`width`,e.width)},submit:()=>xe.current.store.state.isSubmitting||pe.current.isRunning()?Promise.resolve(!1):xe.current.submitCurrent()})},[we]),(0,X.useEffect)(()=>{fe.current=W},[W]),(0,X.useEffect)(()=>{if(W.length===0||se)return;let e=W.find(e=>e.id===`@cf/black-forest-labs/flux-2-klein-4b`)??W[0];if(!K.store.state.fieldMeta.model?.isTouched){let t=yi(K.store.state.values,e);K.setFieldValue(`model`,t.model),K.store.state.fieldMeta.width?.isTouched||K.setFieldValue(`width`,t.width),K.store.state.fieldMeta.height?.isTouched||K.setFieldValue(`height`,t.height),K.store.state.fieldMeta.steps?.isTouched||K.setFieldValue(`steps`,t.steps)}},[K,se,W]);let Te=xi(W,Se.model),Ee=Se.references,De=Te?.input.maxReferences??0,Oe=(0,X.useRef)({addComputerFile:I,retryPath:H.retryPath,uploads:L});Oe.current={addComputerFile:I,retryPath:H.retryPath,uploads:L};let ke=B?Wm(B):null,Ae=(0,X.useMemo)(()=>T.map(e=>({key:Wm(e),selected:Wm(e)===ke,path:e.source.kind===`computer`?e.source.path:e.file.name,referenced:Ee.some(t=>e.source.kind===`computer`&&Ii(t,e.source.computerId)&&t.path===e.source.path),referenceDisabled:Ee.length>=De&&!Ee.some(t=>e.source.kind===`computer`&&Ii(t,e.source.computerId)&&t.path===e.source.path),onToggleReference:e.source.kind===`computer`&&De>0?()=>{if(e.source.kind!==`computer`)return;let t=e.source.path,n=e.source.computerId,r=Ee.some(e=>Ii(e,n)&&e.path===t);K.setFieldValue(`references`,r?Ee.filter(e=>!Ii(e,n)||e.path!==t):[...Ee,{path:t}])}:void 0,onInfo:()=>{_(e)},url:e.url,width:e.width,height:e.height,onOpen:()=>{_(null),y(Wm(e))}})),[T,Ee,De,K,ke]),je=(0,X.useMemo)(()=>{let e=r.computerId;if(!e)return Ae;let t=new Map(Ae.map(e=>[e.key,e])),n=[...w.entries].sort((e,t)=>t.modifiedAt-e.modifiedAt||e.name.localeCompare(t.name)).map(n=>{let r=`${e}:${n.path}`;return{...t.get(r)??{key:r,path:n.path,width:1,height:1,url:``,pending:!0,pendingLabel:`Loading print…`,onOpen:()=>void 0,onVisible:()=>{w.loadFile(n.path)},error:E.includes(n.name)?`Could not load this print.`:void 0},onRetry:()=>{ee(n.path)}}}),i=new Set(n.map(e=>e.key));return[...n,...Ae.filter(e=>!i.has(e.key)&&e.key!==ke)]},[Ae,w.entries,w.loadFile,ee,E,r.computerId,ke]),q=U.kind===`pending`,Me=[...ue].sort().join(`|`),Ne=O.filter(e=>e.error!==void 0).length,Pe=(0,X.useMemo)(()=>le.filter(e=>e.reference.computerId===r.computerId&&!Me.split(`|`).includes(e.reference.requestId)&&!O.some(t=>t.computerId===e.reference.computerId&&t.path===e.input.destination.path)).map(e=>({key:`${e.reference.computerId}:${e.input.destination.path}`,path:e.input.destination.path,width:1024,height:1280,url:``,pending:!0,error:e.failure?.message??`Stopped when Prints closed. Retry to run it again.`,prompt:e.typed.prompt,onOpen:()=>void 0,onRetry:()=>{pe.current.resume(e)},onDismiss:()=>{pe.current.discard(e)}})),[le,r.computerId,Me,O]),Fe=(0,X.useMemo)(()=>[...Pe,...sS(je,O,e=>{let t=L.items.find(t=>t.id===e.uploadId),r=e.error??(t?.status===`error`||t?.status===`cancelled`?t.message:void 0);return{key:e.key,path:e.path,width:e.width,height:r===void 0?e.height:Math.max(e.height,e.width*1.25),url:``,pending:!0,error:r,prompt:r===void 0?void 0:le.find(t=>t.reference.computerId===e.computerId&&t.input.destination.path===e.path)?.typed.prompt??(Ne===1?H.failedPrompt:void 0),pendingLabel:t?.status===`complete`||U.kind===`completed`?`Loading preview…`:e.uploadId?`Uploading image…`:e.startedAt===void 0?e.pendingLabel:pi(W.find(e=>e.kind===`video`),te-e.startedAt,e.resumed),onOpen:()=>void 0,onRetry:r&&(A||t&&t.status!==`complete`)?()=>{if(P(e.key),t&&t.status!==`complete`){Oe.current.uploads.retry(t.id);return}!e.uploadId&&Oe.current.retryPath(e.path)||n.current&&Oe.current.addComputerFile(e.path,n.current,e.computerId)}:void 0,onDismiss:r?()=>{F(e.key),e.uploadId&&Oe.current.uploads.remove(e.uploadId)}:void 0}})],[Pe,le,Ne,H.failedPrompt,je,O,L.items,U.kind,A,W,te]),Ie=Ce||q,Le=!i&&ce&&G&&j&&C!==null&&U.kind===`ready`&&!oe&&W.length>0,Re=O.some(e=>e.error!==void 0),ze=L.items.filter(e=>e.computerId===r.computerId),Be=U.kind===`error`&&se===null?{key:H.errorKey,mediaKind:U.mediaKind,message:U.message,billing:U.action===`billing`&&e?()=>{e.app.ui.openTeamBilling().catch(t=>{Qr(`open-team-billing`,t),n.current===e&&H.reportRecoveryError(t)})}:void 0,prompt:H.failedPrompt,retry:Re?H.retry:void 0,dismiss:Re?()=>{for(let e of O)e.error!==void 0&&F(e.key);H.dismissFailed()}:void 0}:null,J=ex({connected:e!==null,mediaCapability:ce,modelsError:se,retryModels:H.retryModels,modelsLoading:oe,models:W,canGenerate:G,mediaSetupMissing:i,canWrite:j,generationError:Be,recoveryError:de,pendingGenerations:le,activeGenerations:ue,gallerySlots:O,computerId:r.computerId,failed:E,uploadError:L.error,uploads:ze,permissions:()=>{e?.app.ui.requestAppPermissions({}).catch(e=>{H.reportRecoveryError(e)})},resume:e=>{H.resume(e)},discard:e=>{H.discard(e)},retryUpload:e=>{L.retry(e)}});h.error&&J.push({key:`dismissal-storage`,group:`Setup`,tone:`warning`,blocking:!0,short:`Activity not saved`,title:`Activity not saved`,detail:h.error});let Ve=h.visible(J),He={generating:ue.size,uploading:ze.filter(e=>e.status===`sending`||e.status===`queued`).length},Ue={items:ze.filter(e=>e.status===`sending`||e.status===`queued`).map(e=>({id:e.id,name:e.file.name,preview:{kind:`image`,url:e.previewUrl},progress:null,progressLabel:``,statusLabel:e.message,actions:{cancel:{label:`Cancel`,accessibleLabel:`Cancel ${e.file.name}`}}})),onCancel:e=>{L.cancel(e)},onRetry:e=>{L.retry(e)},onRemove:e=>{L.remove(e)}},We=new Set([...w.entries.map(e=>`${r.computerId??``}:${e.path}`),...T.map(e=>e.source.kind===`computer`?`${e.source.computerId}:${e.source.path}`:e.file.name)]).size,Ge=Kb(Ve,He,d);Rd(e?.app,[...r.available?[av(r.path,{checking:r.busy&&r.path===null,editing:r.editing})]:[],...Ge===null?[]:[Ge],...k?[{kind:`text`,id:`prints`,text:`${String(We)} ${We===1?`print`:`prints`}`}]:[]],e=>e.itemId===`activity`?(m(e.anchor?.start),f(e=>!e),!0):e.itemId!==`folder`||!r.available?!1:(r.setEditing(!0),!0),t=>{Qr(`prints.status.report`,t),e?.app.ui.showToast({message:`Prints couldn't update its status bar.`,tone:`error`}).catch(e=>{Qr(`prints.status.toast`,e)})});let Ke=T.flatMap(e=>e.source.kind===`computer`?[{path:e.source.path,url:e.url}]:[]),qe=e=>{y(null),S.current+=1,x({key:e,requestId:`viewer-close-${String(S.current)}`,onFocus:()=>void 0})},Je=(t,n,r)=>(0,Z.jsx)(X.Suspense,{fallback:null,children:(0,Z.jsx)(FS,{image:t,app:e?.app??null,referenceImages:Ke,models:W,canAnimate:AS(W)!==void 0,download:r,onIterate:(e,n)=>{if(t.source.kind!==`computer`)return null;let r=MS(e,{lineage:n,printComputerId:t.source.computerId,printPath:t.source.path,models:W,styles:V.styles.map(e=>e.name),current:K.store.state.values});return r.kind===`refused`?r.message:(be(r.draft),ve(r.notice===null?null:{model:r.draft.model,message:r.notice}),_(null),v!==null&&qe(Wm(t)),null)},onClose:n},t.url)}),Ye={label:`Upload images`,onSelect:()=>he.current?.click(),disabled:!j||C===null,disabledReason:`Choose a writable Computer and folder to upload images.`},Xe=(0,Z.jsx)(Y,{variant:`ghost`,loading:a,onClick:l,children:`Set up image generation`});return(0,Z.jsxs)(`main`,{ref:t,className:`h-full w-full flex flex-col overflow-hidden`,"data-app-pane":`media`,"data-generation-state":U.kind,"data-computer-capability":k?`connected`:`absent`,onPaste:e=>{let t=Array.from(e.clipboardData.files);t.length&&j&&(e.preventDefault(),R(t.map(e=>(ge.current+=1,new File([e],`paste-${String(ge.current)}-${Bm(e.name)}`,{type:e.type,lastModified:e.lastModified})))))},children:[(0,Z.jsx)(N_,{id:`prints-generation-notices`}),(0,Z.jsxs)(`div`,{className:`prints-gallery-region`,children:[(0,Z.jsx)(tm,{screen:Fe.length>4,surface:Fe.length>4,surfaceSize:`lg`,surfaceDepth:`deep`,ref:me,className:`prints-gallery-scroll flex-1 min-h-0`,"data-media-scroll":!0,"aria-busy":D||w.loading,onDragOver:e=>{e.preventDefault()},onDrop:e=>{e.preventDefault();let t=Array.from(e.dataTransfer.files);t.length&&j&&R(t)},children:(0,Z.jsxs)(`div`,{className:`prints-gallery-content`,children:[Fe.length>0?(0,Z.jsx)(oS,{items:Fe,scrollRef:me,focus:v===null?b??(B&&z.target?{key:`${z.target.computerId}:${z.target.path}`,requestId:z.target.requestId,onFocus:()=>{_(null),y(Wm(B))}}:void 0):void 0}):D||w.loading?(0,Z.jsx)(iv,{"data-media-loading":!0,framed:!1,message:`Loading prints…`,detail:`Your library is on its way.`,variant:`wander`}):(0,Z.jsx)(nv,{"aria-live":`polite`,"data-absence":!0,"data-media-empty":!0,role:`status`,variant:`speech`,className:`prints-invitation`,visual:`blobs`,title:i?`Make and collect images`:`Make your first print`,description:i?`Upload images to start your collection. Open any image to view or download it.`:r.computerId===null?`Your images will appear here.`:r.available&&C===null?`Pick a folder in the composer below, then describe something or drop in images.`:`Describe something and it lands here, or drop in images from your Computer.`,primaryAction:i?Ye:void 0,actions:i?(0,Z.jsxs)(`div`,{className:`prints-image-setup`,children:[(0,Z.jsx)(`span`,{children:u}),Xe]}):(0,Z.jsx)(Y,{variant:`ghost`,size:`sm`,disabled:!j||C===null,onClick:()=>he.current?.click(),children:`Upload images`}),suggestions:i?void 0:IS.map(e=>({label:e,disabled:!Le,onSelect:()=>{K.setFieldValue(`prompt`,e),t.current?.querySelector(`[data-generation-prompt]`)?.focus()}}))}),w.hasNextPage&&(0,Z.jsx)(Y,{variant:`ghost`,disabled:w.loading,onClick:w.loadMore,children:w.loading?`Loading images…`:`Load more images`})]})}),z.error?(0,Z.jsx)(`p`,{role:`alert`,children:`Could not open this print. It may no longer be available on this Computer.`}):null,g&&(g.source.kind===`local`||g.source.connection===e&&g.source.computerId===r.computerId)?Je(g,()=>{_(null)}):null]}),(0,Z.jsx)(ah,{items:Fe,images:T,viewerKey:v,app:e?.app??null,onNavigate:y,onClose:qe,renderInfo:(e,t)=>Je(e,t,null)}),i&&Fe.length>0?(0,Z.jsxs)(`div`,{className:`prints-library-actions`,children:[(0,Z.jsx)(Y,{size:`sm`,onClick:Ye.onSelect,disabled:Ye.disabled,children:`Upload images`}),Xe,s?(0,Z.jsx)(`div`,{className:`prints-image-setup`,children:u}):null]}):null,(0,Z.jsxs)(`div`,{className:`prints-composer-dock`,children:[(0,Z.jsx)(`section`,{"aria-label":`Computer uploads`,className:`prints-uploads`,children:(0,Z.jsx)(`input`,{ref:he,type:`file`,disabled:!j||C===null,accept:`image/*`,multiple:!0,hidden:!0,"aria-label":`Choose images to upload`,onChange:e=>{R(Array.from(e.currentTarget.files??[])),e.currentTarget.value=``}})}),i?null:(0,Z.jsx)(BS,{addedLength:Zi(Se.prompt,V.styles.find(e=>e.name===Se.style)?.text,ae.characters),styleControls:e=>({picker:(0,Z.jsx)(NS,{styles:V.styles,selected:Se.style,disabled:!ce||oe||Ie,onSelect:e=>{K.setFieldValue(`style`,e)}}),dialog:(0,Z.jsx)(PS,{open:e.open,onOpenChange:e.onOpenChange,styles:V.styles,selected:Se.style,busy:V.busy,error:V.error,onSelect:e=>{K.setFieldValue(`style`,e)},onSave:V.save,onDelete:(e,t)=>{V.remove(e.id,t)}})}),characters:ae.characters,characterDialog:e=>(0,Z.jsx)(yS,{open:e.open,onOpenChange:e.onOpenChange,characters:ae.characters,images:Ke,busy:ae.busy,error:ae.error,canUpload:j&&C!==null,onUpload:()=>he.current?.click(),onSave:ae.save,onDelete:(e,t)=>{ae.remove(e.id,t)}}),guidance:Ve.find(e=>e.blocking&&e.group===`Setup`)??(_e!==null&&_e.model===Se.model?{key:`iteration-model`,group:`Images`,tone:`warning`,short:`Model changed`,title:`Model changed`,detail:_e.message,actions:[{label:`Dismiss`,run:()=>{ve(null)}}]}:void 0),commandApp:we,actions:(0,Z.jsx)(wt,{"aria-label":`Upload images`,title:j?`Upload images to Computer`:`Connect a writable Computer to upload`,icon:(0,Z.jsx)(vm,{}),label:null,className:`prints-upload-key`,disabled:!j||C===null,onClick:()=>he.current?.click()}),form:K,mediaCapability:ce&&G&&j&&C!==null,models:W,modelsLoading:oe,onSubmit:K.submitCurrent,submitting:Ie,values:Se,computerId:r.computerId,mediaDirectory:C,referenceImages:Ke}),Ge===null?null:(0,Z.jsx)(Jb,{notices:Ve,uploads:Ue,open:d,inset:p,onOpenChange:f,onDismiss:h.dismiss,onDismissAll:()=>{h.dismissAll(J)},onLoadMore:H.hasMore?H.loadMore:void 0})]}),(0,Z.jsx)(Xb,{folder:r})]})}var HS=document.getElementById(`media-root`);if(!HS)throw Error(`Media root is missing`);Nd(HS,{name:`Prints`,queryClient:Yi()},({app:e})=>(0,X.createElement)(VS,{connection:e?{app:e}:null}));
|