@deslop/auth 0.1.1310 → 0.1.1312

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-XKyaHtl9.js";import{a as t,n,o as r,t as i}from"./react-BPjvcVqE.js";import{$ as a,$a as o,$i as s,$n as c,$o as l,$r as u,$t as d,A as f,Aa as p,Ai as m,An as h,Ao as g,Ar as _,At as v,B as y,Ba as b,Bi as ee,Bn as te,Bo as x,Br as S,Bt as ne,C as re,Ca as ie,Ci as C,Cn as ae,D as oe,Da as se,Di as ce,Dn as le,Do as ue,Dt as de,E as fe,Ea as pe,Ei as me,En as he,Eo as ge,Er as _e,Et as ve,F as ye,Fa as be,Fi as xe,Fn as Se,Fo as Ce,Fr as we,Ft as Te,G as Ee,Ga as De,Gn as Oe,Gr as ke,Gt as Ae,H as je,Ha as w,Hi as Me,Hn as Ne,Ho as Pe,Hr as Fe,Ht as Ie,I as Le,Ia as Re,Ii as ze,In as Be,Io as Ve,Ir as He,It as Ue,J as We,Ja as Ge,Jn as Ke,Jo as qe,Jr as Je,Jt as Ye,K as Xe,Ki as Ze,Kn as Qe,Kr as $e,Kt as et,L as tt,La as nt,Li as rt,Ln as it,Lo as T,Lr as E,Lt as at,M as ot,Ma as st,Mi as D,Mn as ct,Mo as lt,Mr as ut,Mt as dt,N as ft,Na as pt,Ni as mt,Nn as ht,Nr as gt,Nt as _t,O as vt,Oa as yt,Oi as bt,Oo as xt,Or as St,Ot as Ct,P as wt,Pa as Tt,Pi as Et,Pn as O,Po as Dt,Pr as k,Pt as Ot,Q as kt,Qa as At,Qi as jt,Qn as Mt,Qr as Nt,Qt as Pt,R as Ft,Ra as It,Ri as Lt,Rn as Rt,Ro as zt,Rr as Bt,Rt as Vt,S as Ht,Sa as Ut,Si as A,Sn as Wt,St as Gt,T as Kt,Ta as qt,Ti as Jt,Tn as Yt,To as Xt,Tr as Zt,Tt as Qt,U as $t,Ua as en,Ui as tn,Un as nn,Uo as j,Ur as rn,Ut as an,V as on,Va as sn,Vi as cn,Vo as M,Vr as ln,Vt as un,W as dn,Wa as fn,Wi as pn,Wn as mn,Wo as hn,Wr as gn,Wt as _n,X as vn,Xa as yn,Xi as bn,Xn as xn,Xr as Sn,Xt as Cn,Y as wn,Ya as Tn,Yn as En,Yo as N,Yr as P,Yt as Dn,Z as On,Zi as kn,Zn as An,Zr as jn,Zt as Mn,_ as Nn,_a as Pn,_i as Fn,_n as F,_t as In,a as Ln,aa as Rn,ai as zn,an as Bn,ar as Vn,as as Hn,b as Un,ba as Wn,bi as Gn,bn as Kn,bt as qn,c as Jn,ca as Yn,ci as Xn,cn as I,co as Zn,cr as Qn,ct as $n,d as er,da as tr,dn as L,dr as nr,dt as rr,ei as ir,en as ar,eo as or,er as sr,es as cr,f as lr,fa as ur,fi as dr,fn as fr,fr as pr,ft as mr,g as hr,ga as gr,gi as _r,gn as R,gt as vr,h as yr,ha as br,hi as xr,hn as Sr,ht as Cr,i as wr,ia as Tr,ii as Er,in as Dr,ir as Or,is as z,it as kr,j as Ar,ja as jr,ji as Mr,jn as Nr,jr as Pr,jt as Fr,k as Ir,ka as Lr,ki as Rr,kn as zr,ko as Br,kt as Vr,l as Hr,la as Ur,li as Wr,ln as Gr,lr as Kr,m as qr,ma as Jr,mi as Yr,mn as Xr,mr as Zr,mt as Qr,n as $r,na as ei,ni as ti,nn as ni,nr as ri,ns as ii,nt as ai,o as oi,oa as si,oi as B,on as ci,or as li,ot as ui,p as di,pa as fi,pi,pn as mi,pt as hi,q as gi,qa as _i,qn as vi,qo as yi,qr as V,qt as bi,r as xi,ra as Si,ri as Ci,rn as wi,rr as Ti,rs as Ei,rt as Di,s as Oi,sa as ki,si as Ai,sn as ji,sr as Mi,st as Ni,t as Pi,ta as Fi,ti as Ii,tn as Li,to as Ri,tr as zi,u as Bi,ua as Vi,ui as Hi,un as Ui,ur as Wi,v as Gi,va as Ki,vi as qi,vn as Ji,vo as Yi,vt as Xi,w as Zi,wa as Qi,wi as H,wn as $i,wo as ea,wt as ta,x as na,xa as ra,xi as ia,xn as aa,xt as oa,y as sa,ya as ca,yi as la,yn as ua,yt as da,z as fa,za as pa,zi as ma,zn as U,zo as ha,zr as ga,zt as _a}from"./effect-BtIBG6mz.js";import{i as va,n as ya,t as ba,u as xa,z as Sa}from"./classes-DmROs80r.js";var W=e(r(),1),Ca=W.use,wa=W.useLayoutEffect,Ta=W.createContext(null);function Ea(e){return W.useContext(Ta)}function Da(e){let t=Ea();return W.useCallback(n=>t.navigate({...n,from:n.from??e?.from}),[e?.from,t])}function Oa(e){let t=Ea(),n=Da(),r=W.useRef(null);return wa(()=>{r.current!==e&&(n(e),r.current=e)},[t,e,n]),null}z(Li,$i(Cn,{decode:Or(e=>_e(Zt(0),()=>e)),encode:Or(_)})),z(Li,$i(ar)),z(Li,$i(Cn,{decode:Or(e=>_e(Zt(0),()=>e*1e3)),encode:Or(e=>_(e)/1e3)}));var ka=z(wi,$i(Cn,{decode:Or(e=>Zt(e*1e3)),encode:Or(Pr)})),Aa=z(Li,$i(d,{decode:Or(De),encode:Or(_i)})),G=class extends Ji()(`AuthError`,{cause:Rt(Pt()),error:U(ci([`invalid_request`,`invalid_client`,`invalid_client_metadata`,`invalid_redirect_uri`,`invalid_grant`,`invalid_scope`,`unsupported_grant_type`,`unsupported_response_type`,`access_denied`,`authorization_pending`,`expired_token`,`temporarily_unavailable`])),message:R}){get name(){return this.error===`temporarily_unavailable`?`AuthUnavailable`:`AuthError`}},ja=z(I,Wt(`UserId`)),Ma=z(I,Wt(`SignInFamily`)),Na=z(I,Wt(`SessionId`)),Pa=z(R,Wt(`ClientId`)),Fa=z(wi,Wt(`GitHubId`));z(ni,$i(Fa));var Ia=F({id:ja,name:I});F({aud:Bn(`deslop`),azp:I,exp:ka,iat:ka,iss:I,name:I,sid:Ma,sub:ja});var La=F({name:R,redirects:ji(I.check(Nr(200))).check(Nr(4))});F({client_id:Pa.check(ct()),code:I,code_verifier:I,redirect_uri:I}),F({session:Na}),F({access_token:I,expires_in:Aa,refresh_token:I});var Ra=`https://auth.mp281x.xyz`;fn(10),en(30),ja.make(`github:0`);function za(e){return`${new URL(e).origin}/auth/sign-in?${new URLSearchParams({next:e})}`}function Ba(e){return h(G)(e)&&e.error!==`temporarily_unavailable`&&e.error!==`access_denied`}function Va(e){return h(G)(e)&&e.error!==`temporarily_unavailable`}Ge()(`@deslop/runtime/shared/auth/CurrentUser`);var Ha=class extends lr()(`@deslop/runtime/shared/auth/RpcAuth`,{error:G}){},K=t(),Ua=R.check(Be(e=>xt(ea(ye(e)),e=>At([`http:`,`https:`],e.protocol)&&e.username===``&&e.password===``&&e.hash===``),{expected:`an HTTP(S) URL without credentials or a fragment`})).check(Be(e=>xt(ea(ye(e)),e=>e.pathname===`/`&&e.search===``),{expected:`an HTTP(S) origin without a path or query`}));Ua.check(Be(e=>xt(ea(ye(e)),e=>e.protocol===`https:`||At([`localhost`,`127.0.0.1`,`[::1]`],e.hostname)),{expected:`HTTPS outside loopback`})),R.check(ht(/^\d{1,5}$/u),Be(e=>xt(Fi(e),e=>e>=1&&e<=65535),{expected:`a port between 1 and 65535`}));var Wa=R.check(ht(/^0\.1\.\d+$/u)),Ga=`/api/runtime`,Ka=F({auth:L(Ua),name:R,traces:R,version:Wa}),qa=`/api/rpc`,Ja=F({...Ia.fields,signOut:Dn});F({config:F({port:wi}),name:R,version:Wa}),ci([`web`,`mobile`,`server`]);function Ya(e,t,n,r){return ei(Vi(Ii(function*(){let i=`${yield*jr}`,a=yield*Vn,o={attributes:{"scope.run.started_unix_nano":i,"scope.runtime":n,"service.instance.id":i},serviceName:e,serviceVersion:Ce(zt(r,e=>e!==`0.1.0`))};return si(Rn(yr({resource:o,url:new URL(`/v1/traces`,t).href}),hr({resource:o,url:new URL(`/v1/logs`,t).href}),Yn(Vn,[...a,`code`,`state`,`request`,`access_token`,`refresh_token`,`id_token`,`client_secret`,`client_assertion`,`code_verifier`,`session`,`token`])),[Nn,sa])})),e=>Re(e)?Si(ti):Si(zn(`Telemetry is unavailable`)))}function Xa(e){return Vi(Ii(function*(){let t=yield*z((yield*vt).get(Ga),P(Ar),P(ot(Ka)),ce(`3 seconds`),me(e=>zn(`Telemetry is off: the runtime config did not load`,e)),Hi);return x(t,{onNone:()=>Tr,onSome:t=>t.traces===``?Tr:Ya(`${e}-client`,t.traces,`web`,t.version)})}))}var Za=class extends lr()(`@deslop/runtime/shared/rpc/RpcStream`){};Yn(Za,Za.of((e,t)=>Kt(t.rpc.successSchema)?k(we(`rpc.stream`,!0),e):e));var Qa=di(Za,e=>Ii(function*(){return Kt(e.rpc.successSchema)&&(yield*we(`rpc.stream`,!0)),yield*e.next(e.request)}));function $a(e){return z(na({pingTimeout:`15 seconds`,retryTransientErrors:!0}),si(si(fe(e),oe)),ki(Ht()),ki(Qa))}var eo=Qn(M());ci([`route`,`caught`,`uncaught`]);var to=Ft(e=>{let t=Er(`Web error`,pt(e.error),...hn(lt(e.stack)));return x(li(eo),{onNone:()=>t,onSome:n=>dr(z(t,k(gn(e.error)),Et(`Web.error`,{attributes:{"web.error.source":e.source,"web.route.id":e.route},root:!0}),$e),n)})}),no=Ee(sa).atom(z(f(`/api/account`),P(Ar),P(ot(Ja)))),ro=$a(H(()=>`${location.origin}${qa}`));function io(e){Ee.addGlobalLayer(z(Xa(e),si(sa),Ur(e=>Ve(yn(e,Gi))?D:ut(H(()=>Kr(eo,j(e))),()=>H(()=>Wi(eo,Br(t=>t!==e)))))))}var ao=e(i(),1);function oo(e){let t=ao.unstable_scheduleCallback(4,e);return()=>ao.unstable_cancelCallback(t)}var so=W.createContext(a({scheduleTask:oo,defaultIdleTTL:400})),co=new WeakMap,lo=0,uo=new Set;function fo(e){lo++;try{return e()}finally{lo--}}function po(e){if(lo===0)return e();uo.size===0&&queueMicrotask(mo),uo.add(e)}function mo(){for(let e of uo)uo.delete(e),e()}function ho(e,t){let n=co.get(e);n===void 0&&(n=new WeakMap,co.set(e,n));let r=n.get(t);if(r!==void 0)return r;let i=0,a,o={subscribe(n){i++;let r=e.subscribe(t,()=>po(n));return()=>{i--,uo.delete(n),r()}},snapshot(){return fo(()=>e.get(t))},getServerSnapshot(){return(i===0||a===void 0)&&(a={value:fo(()=>fa(t,e))}),a.value}};return n.set(t,o),o}function go(e,t){let n=ho(e,t);return W.useEffect(mo),W.useSyncExternalStore(n.subscribe,n.snapshot,n.getServerSnapshot)}function _o(e,t,n){let r=ho(e,t),i=W.useMemo(()=>{let e;return t=>(e!==void 0&&Object.is(e.source,t)||(e={source:t,value:n(t)}),e.value)},[n]);return W.useEffect(mo),W.useSyncExternalStore(r.subscribe,()=>i(r.snapshot()),()=>i(r.getServerSnapshot()))}var vo=(e,t)=>{let n=W.useContext(so);return t?_o(n,e,t):go(n,e)};function yo(e,t){W.useEffect(()=>e.mount(t),[t,e])}function bo(e,t,n){return n?.mode===`promise`||n?.mode===`promiseExit`?W.useCallback(r=>{e.set(t,r);let i=_r(kt(e,t,{suspendOnWaiting:!0}));return n.mode===`promise`?i.then(xo):i},[e,t,n.mode]):W.useCallback(n=>{e.set(t,typeof n==`function`?n(e.get(t)):n)},[e,t])}var xo=e=>{if(yt(e))return e.value;throw sn(e.cause)},So=e=>{yo(W.useContext(so),e)},Co=(e,t)=>{let n=W.useContext(so);return yo(n,e),bo(n,e,t)},wo=e=>{let t=W.useContext(so);return yo(t,e),W.useCallback(()=>{t.refresh(e)},[t,e])},To=(e,t)=>{let n=W.useContext(so);return[go(n,e),bo(n,e,t)]},Eo={suspendOnWaiting:new WeakMap,default:new WeakMap};function Do(e,t,n){let r=n?Eo.suspendOnWaiting:Eo.default,i=r.get(e);i===void 0&&(i=new WeakMap,r.set(e,i));let a=i.get(t);return a===void 0&&(a=new Promise(r=>{let a=e.subscribe(t,e=>{e._tag===`Initial`||n&&e.waiting||(setTimeout(a,1e3),r(),i.delete(t))})}),i.set(t,a)),a}function Oo(e,t,n){let r=go(e,t);if(r._tag===`Initial`||n&&r.waiting)throw Do(e,t,n);return r}var ko=(e,t)=>{let n=Oo(W.useContext(so),e,t?.suspendOnWaiting??!1);if(n._tag===`Failure`&&!t?.includeFailure)throw sn(n.cause);return n},Ao=new Map([[`bold`,W.createElement(W.Fragment,null,W.createElement(`path`,{d:`M244,56v48a12,12,0,0,1-12,12H184a12,12,0,1,1,0-24H201.1l-19-17.38c-.13-.12-.26-.24-.38-.37A76,76,0,1,0,127,204h1a75.53,75.53,0,0,0,52.15-20.72,12,12,0,0,1,16.49,17.45A99.45,99.45,0,0,1,128,228h-1.37A100,100,0,1,1,198.51,57.06L220,76.72V56a12,12,0,0,1,24,0Z`}))],[`duotone`,W.createElement(W.Fragment,null,W.createElement(`path`,{d:`M216,128a88,88,0,1,1-88-88A88,88,0,0,1,216,128Z`,opacity:`0.2`}),W.createElement(`path`,{d:`M240,56v48a8,8,0,0,1-8,8H184a8,8,0,0,1,0-16H211.4L184.81,71.64l-.25-.24a80,80,0,1,0-1.67,114.78,8,8,0,0,1,11,11.63A95.44,95.44,0,0,1,128,224h-1.32A96,96,0,1,1,195.75,60L224,85.8V56a8,8,0,1,1,16,0Z`}))],[`fill`,W.createElement(W.Fragment,null,W.createElement(`path`,{d:`M240,56v48a8,8,0,0,1-8,8H184a8,8,0,0,1-5.66-13.66l17-17-10.55-9.65-.25-.24a80,80,0,1,0-1.67,114.78,8,8,0,1,1,11,11.63A95.44,95.44,0,0,1,128,224h-1.32A96,96,0,1,1,195.75,60l10.93,10L226.34,50.3A8,8,0,0,1,240,56Z`}))],[`light`,W.createElement(W.Fragment,null,W.createElement(`path`,{d:`M238,56v48a6,6,0,0,1-6,6H184a6,6,0,0,1,0-12h32.55l-30.38-27.8c-.06-.06-.12-.13-.19-.19a82,82,0,1,0-1.7,117.65,6,6,0,0,1,8.24,8.73A93.46,93.46,0,0,1,128,222h-1.28A94,94,0,1,1,194.37,61.4L226,90.35V56a6,6,0,1,1,12,0Z`}))],[`regular`,W.createElement(W.Fragment,null,W.createElement(`path`,{d:`M240,56v48a8,8,0,0,1-8,8H184a8,8,0,0,1,0-16H211.4L184.81,71.64l-.25-.24a80,80,0,1,0-1.67,114.78,8,8,0,0,1,11,11.63A95.44,95.44,0,0,1,128,224h-1.32A96,96,0,1,1,195.75,60L224,85.8V56a8,8,0,1,1,16,0Z`}))],[`thin`,W.createElement(W.Fragment,null,W.createElement(`path`,{d:`M236,56v48a4,4,0,0,1-4,4H184a4,4,0,0,1,0-8h37.7L187.53,68.69l-.13-.12a84,84,0,1,0-1.75,120.51,4,4,0,0,1,5.5,5.82A91.43,91.43,0,0,1,128,220h-1.26A92,92,0,1,1,193,62.84l35,32.05V56a4,4,0,1,1,8,0Z`}))]]),jo=W.forwardRef((e,t)=>W.createElement(Sa,{ref:t,...e,weights:Ao}));jo.displayName=`ArrowClockwiseIcon`;var Mo=new Map([[`bold`,W.createElement(W.Fragment,null,W.createElement(`path`,{d:`M222.14,105.85l-80-80a20,20,0,0,0-28.28,0l-80,80A19.86,19.86,0,0,0,28,120v96a12,12,0,0,0,12,12h64a12,12,0,0,0,12-12V164h24v52a12,12,0,0,0,12,12h64a12,12,0,0,0,12-12V120A19.86,19.86,0,0,0,222.14,105.85ZM204,204H164V152a12,12,0,0,0-12-12H104a12,12,0,0,0-12,12v52H52V121.65l76-76,76,76Z`}))],[`duotone`,W.createElement(W.Fragment,null,W.createElement(`path`,{d:`M216,120v96H152V152H104v64H40V120a8,8,0,0,1,2.34-5.66l80-80a8,8,0,0,1,11.32,0l80,80A8,8,0,0,1,216,120Z`,opacity:`0.2`}),W.createElement(`path`,{d:`M219.31,108.68l-80-80a16,16,0,0,0-22.62,0l-80,80A15.87,15.87,0,0,0,32,120v96a8,8,0,0,0,8,8h64a8,8,0,0,0,8-8V160h32v56a8,8,0,0,0,8,8h64a8,8,0,0,0,8-8V120A15.87,15.87,0,0,0,219.31,108.68ZM208,208H160V152a8,8,0,0,0-8-8H104a8,8,0,0,0-8,8v56H48V120l80-80,80,80Z`}))],[`fill`,W.createElement(W.Fragment,null,W.createElement(`path`,{d:`M224,120v96a8,8,0,0,1-8,8H160a8,8,0,0,1-8-8V164a4,4,0,0,0-4-4H108a4,4,0,0,0-4,4v52a8,8,0,0,1-8,8H40a8,8,0,0,1-8-8V120a16,16,0,0,1,4.69-11.31l80-80a16,16,0,0,1,22.62,0l80,80A16,16,0,0,1,224,120Z`}))],[`light`,W.createElement(W.Fragment,null,W.createElement(`path`,{d:`M217.9,110.1l-80-80a14,14,0,0,0-19.8,0l-80,80A13.92,13.92,0,0,0,34,120v96a6,6,0,0,0,6,6h64a6,6,0,0,0,6-6V158h36v58a6,6,0,0,0,6,6h64a6,6,0,0,0,6-6V120A13.92,13.92,0,0,0,217.9,110.1ZM210,210H158V152a6,6,0,0,0-6-6H104a6,6,0,0,0-6,6v58H46V120a2,2,0,0,1,.58-1.42l80-80a2,2,0,0,1,2.84,0l80,80A2,2,0,0,1,210,120Z`}))],[`regular`,W.createElement(W.Fragment,null,W.createElement(`path`,{d:`M219.31,108.68l-80-80a16,16,0,0,0-22.62,0l-80,80A15.87,15.87,0,0,0,32,120v96a8,8,0,0,0,8,8h64a8,8,0,0,0,8-8V160h32v56a8,8,0,0,0,8,8h64a8,8,0,0,0,8-8V120A15.87,15.87,0,0,0,219.31,108.68ZM208,208H160V152a8,8,0,0,0-8-8H104a8,8,0,0,0-8,8v56H48V120l80-80,80,80Z`}))],[`thin`,W.createElement(W.Fragment,null,W.createElement(`path`,{d:`M216.49,111.51l-80-80a12,12,0,0,0-17,0l-80,80A12,12,0,0,0,36,120v96a4,4,0,0,0,4,4h64a4,4,0,0,0,4-4V156h40v60a4,4,0,0,0,4,4h64a4,4,0,0,0,4-4V120A12,12,0,0,0,216.49,111.51ZM212,212H156V152a4,4,0,0,0-4-4H104a4,4,0,0,0-4,4v60H44V120a4,4,0,0,1,1.17-2.83l80-80a4,4,0,0,1,5.66,0l80,80A4,4,0,0,1,212,120Z`}))]]),No=W.forwardRef((e,t)=>W.createElement(Sa,{ref:t,...e,weights:Mo}));No.displayName=`HouseIcon`;var Po=new Map([[`bold`,W.createElement(W.Fragment,null,W.createElement(`path`,{d:`M208,76H180V56A52,52,0,0,0,76,56V76H48A20,20,0,0,0,28,96V208a20,20,0,0,0,20,20H208a20,20,0,0,0,20-20V96A20,20,0,0,0,208,76ZM100,56a28,28,0,0,1,56,0V76H100ZM204,204H52V100H204Zm-60-52a16,16,0,1,1-16-16A16,16,0,0,1,144,152Z`}))],[`duotone`,W.createElement(W.Fragment,null,W.createElement(`path`,{d:`M216,96V208a8,8,0,0,1-8,8H48a8,8,0,0,1-8-8V96a8,8,0,0,1,8-8H208A8,8,0,0,1,216,96Z`,opacity:`0.2`}),W.createElement(`path`,{d:`M208,80H176V56a48,48,0,0,0-96,0V80H48A16,16,0,0,0,32,96V208a16,16,0,0,0,16,16H208a16,16,0,0,0,16-16V96A16,16,0,0,0,208,80ZM96,56a32,32,0,0,1,64,0V80H96ZM208,208H48V96H208V208Zm-68-56a12,12,0,1,1-12-12A12,12,0,0,1,140,152Z`}))],[`fill`,W.createElement(W.Fragment,null,W.createElement(`path`,{d:`M208,80H176V56a48,48,0,0,0-96,0V80H48A16,16,0,0,0,32,96V208a16,16,0,0,0,16,16H208a16,16,0,0,0,16-16V96A16,16,0,0,0,208,80Zm-80,84a12,12,0,1,1,12-12A12,12,0,0,1,128,164Zm32-84H96V56a32,32,0,0,1,64,0Z`}))],[`light`,W.createElement(W.Fragment,null,W.createElement(`path`,{d:`M208,82H174V56a46,46,0,0,0-92,0V82H48A14,14,0,0,0,34,96V208a14,14,0,0,0,14,14H208a14,14,0,0,0,14-14V96A14,14,0,0,0,208,82ZM94,56a34,34,0,0,1,68,0V82H94ZM210,208a2,2,0,0,1-2,2H48a2,2,0,0,1-2-2V96a2,2,0,0,1,2-2H208a2,2,0,0,1,2,2Zm-72-56a10,10,0,1,1-10-10A10,10,0,0,1,138,152Z`}))],[`regular`,W.createElement(W.Fragment,null,W.createElement(`path`,{d:`M208,80H176V56a48,48,0,0,0-96,0V80H48A16,16,0,0,0,32,96V208a16,16,0,0,0,16,16H208a16,16,0,0,0,16-16V96A16,16,0,0,0,208,80ZM96,56a32,32,0,0,1,64,0V80H96ZM208,208H48V96H208V208Zm-68-56a12,12,0,1,1-12-12A12,12,0,0,1,140,152Z`}))],[`thin`,W.createElement(W.Fragment,null,W.createElement(`path`,{d:`M208,84H172V56a44,44,0,0,0-88,0V84H48A12,12,0,0,0,36,96V208a12,12,0,0,0,12,12H208a12,12,0,0,0,12-12V96A12,12,0,0,0,208,84ZM92,56a36,36,0,0,1,72,0V84H92ZM212,208a4,4,0,0,1-4,4H48a4,4,0,0,1-4-4V96a4,4,0,0,1,4-4H208a4,4,0,0,1,4,4Zm-76-56a8,8,0,1,1-8-8A8,8,0,0,1,136,152Z`}))]]),Fo=W.forwardRef((e,t)=>W.createElement(Sa,{ref:t,...e,weights:Po}));Fo.displayName=`LockIcon`;var Io=n();function Lo(e){return Yi(e.reasons,e=>It(e)&&Va(e.error))}function Ro(e){return!Ni(e)||!Lo(e.cause)&&T(e.previousSuccess)?M():j(e.cause)}function zo(e,t,n=Ei){function r(e){let t=Ri(e.reasons,e=>It(e)&&Va(e.error));return Zn(t)?M():j(be(t))}let i=Qn(z(e.self(),Br(Ni),g(e=>r(e.cause))));function a(e){return x(li(i),{onNone:()=>e,onSome:t=>be([...t.reasons,...Ri(e.reasons,e=>!It(e)||!Va(e.error))])})}let o=Qn(0),s=Ue(t,t=>H(()=>{Wi(i,e=>Pe(r(t),()=>e));let n=a(t);T(li(i))?e.setSelf(ai(n)):Mi(o)<2||e.setSelf(Di(n,{previous:e.self()}))}));return z(n(s),Te(()=>H(()=>{Kr(i,M()),Kr(o,0)})),Cr(e=>qn(a(e))),In(Ot(()=>x(li(i),{onNone:()=>Xi,onSome:qn}))))}function Bo(e){return Fr(e,e=>cn(e(ee(`1 second`)),e=>h(G)(e.input)?e.input.error===`temporarily_unavailable`:h(re)(e.input)&&e.input.reason._tag!==`RpcClientDefect`))}function Vo(e,t,n){return Vt(B(e,e=>e(t,n)))}function Ho(e,t,n){return e.runtime.atom(r=>zo(r,Vt(B(e,e=>e(t,n))),Bo))}var Uo=W.forwardRef(function(e,t){let{render:n,className:r,disabled:i=!1,focusableWhenDisabled:a=!1,nativeButton:o=!0,style:s,...c}=e,{getButtonProps:l,buttonRef:u}=xa({disabled:i,focusableWhenDisabled:a,native:o});return va(`button`,e,{state:{disabled:i},ref:[t,u],props:[c,l]})}),Wo=e=>typeof e==`boolean`?`${e}`:e===0?`0`:e,Go=ya,Ko=(e,t)=>n=>{if(t?.variants==null)return Go(e,n?.class,n?.className);let{variants:r,defaultVariants:i}=t,a=Object.keys(r).map(e=>{let t=n?.[e],a=i?.[e];if(t===null)return null;let o=Wo(t)||Wo(a);return r[e][o]}),o=n&&Object.entries(n).reduce((e,t)=>{let[n,r]=t;return r===void 0||(e[n]=r),e},{});return Go(e,a,t?.compoundVariants?.reduce((e,t)=>{let{class:n,className:r,...a}=t;return Object.entries(a).every(e=>{let[t,n]=e;return Array.isArray(n)?n.includes({...i,...o}[t]):{...i,...o}[t]===n})?[...e,n,r]:e},[]),n?.class,n?.className)},qo=Ko(`group/button inline-flex shrink-0 items-center justify-center rounded-none border border-transparent bg-clip-padding text-xs font-medium whitespace-nowrap outline-none select-none focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-1 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`,{variants:{variant:{default:`bg-primary text-primary-foreground hover:bg-primary/80`,outline:`border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50`,secondary:`bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground`,ghost:`hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50`,bare:`bg-transparent hover:bg-transparent dark:hover:bg-transparent`,destructive:`bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40`,link:`text-primary underline-offset-4 hover:underline`},size:{default:`h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2`,xs:`h-6 gap-1 rounded-none px-2 text-xs has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3`,sm:`h-7 gap-1 rounded-none px-2.5 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5`,lg:`h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2`,icon:`size-8`,"icon-xs":`size-6 rounded-none [&_svg:not([class*='size-'])]:size-3`,"icon-sm":`size-7 rounded-none`,"icon-lg":`size-9`}},defaultVariants:{variant:`default`,size:`default`}});function Jo(e){let t=(0,Io.c)(12),n,r,i,a;t[0]===e?(n=t[1],r=t[2],i=t[3],a=t[4]):({className:n,variant:i,size:a,...r}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i,t[4]=a);let o=i===void 0?`default`:i,s=a===void 0?`default`:a,c;t[5]!==n||t[6]!==s||t[7]!==o?(c=ba(qo({variant:o,size:s,className:n})),t[5]=n,t[6]=s,t[7]=o,t[8]=c):c=t[8];let l;return t[9]!==r||t[10]!==c?(l=(0,K.jsx)(Uo,{"data-slot":`button`,className:c,...r}),t[9]=r,t[10]=c,t[11]=l):l=t[11],l}function Yo(e){let t=(0,Io.c)(8),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=ba(`flex w-full min-w-0 flex-1 flex-col items-center justify-center gap-4 rounded-none border-dashed p-6 text-center text-balance`,n),t[3]=n,t[4]=i);let a;return t[5]!==r||t[6]!==i?(a=(0,K.jsx)(`div`,{"data-slot":`empty`,className:i,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}var Xo=Ko(`mb-2 flex shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg]:shrink-0`,{variants:{variant:{default:`bg-transparent`,icon:`flex size-8 shrink-0 items-center justify-center rounded-none bg-muted text-foreground [&_svg:not([class*='size-'])]:size-4`,symbol:`mb-0 text-muted-foreground [&_svg]:size-4`}},defaultVariants:{variant:`default`}});function Zo(e){let t=(0,Io.c)(11),n,r,i;t[0]===e?(n=t[1],r=t[2],i=t[3]):({className:n,variant:i,...r}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i);let a=i===void 0?`default`:i,o;t[4]!==n||t[5]!==a?(o=ba(Xo({variant:a,className:n})),t[4]=n,t[5]=a,t[6]=o):o=t[6];let s;return t[7]!==r||t[8]!==o||t[9]!==a?(s=(0,K.jsx)(`div`,{"data-slot":`empty-icon`,"data-variant":a,className:o,...r}),t[7]=r,t[8]=o,t[9]=a,t[10]=s):s=t[10],s}function Qo(e){let t=(0,Io.c)(6),n;t[0]!==e.action||t[1]!==e.icon?(n=e.action??(0,K.jsx)(Zo,{"aria-hidden":!0,variant:`symbol`,children:e.icon}),t[0]=e.action,t[1]=e.icon,t[2]=n):n=t[2];let r;return t[3]!==e.label||t[4]!==n?(r=(0,K.jsx)(Yo,{role:`status`,"aria-label":e.label,children:n}),t[3]=e.label,t[4]=n,t[5]=r):r=t[5],r}function $o(){let e=(0,Io.c)(2),t;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,K.jsx)(`a`,{href:`/`,"aria-label":`Home`}),e[0]=t):t=e[0];let n;return e[1]===Symbol.for(`react.memo_cache_sentinel`)?(n=(0,K.jsx)(Yo,{"aria-label":`Page not found`,children:(0,K.jsxs)(Jo,{variant:`outline`,size:`sm`,render:t,nativeButton:!1,children:[(0,K.jsx)(No,{}),`Home`]})}),e[1]=n):n=e[1],n}var es=tt(e=>on(H(()=>location.replace(e))));function ts(e){let t=(0,Io.c)(2),n;return t[0]===e.href?n=t[1]:(n=es(e.href),t[0]=e.href,t[1]=n),So(n),null}function ns(){let e=(0,Io.c)(1),t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,K.jsx)(Qo,{label:`Access denied`,icon:(0,K.jsx)(Fo,{weight:`light`})}),e[0]=t):t=e[0],t}function rs(e){let t=(0,Io.c)(4),n;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=(0,K.jsx)(jo,{}),t[0]=n):n=t[0];let r=e.label??`Can’t load this view`,i;return t[1]!==e.reset||t[2]!==r?(i=(0,K.jsx)(Yo,{role:`alert`,children:(0,K.jsxs)(Jo,{variant:`destructive`,size:`sm`,onClick:e.reset,children:[n,r]})}),t[1]=e.reset,t[2]=r,t[3]=i):i=t[3],i}function is(e){let t=(0,Io.c)(4);if(Ba(e.error)){let e;return t[0]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,K.jsx)(ts,{href:za(location.href)}),t[0]=e):e=t[0],e}if(Va(e.error)){let e;return t[1]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,K.jsx)(ns,{}),t[1]=e):e=t[1],e}let n;return t[2]===e.reset?n=t[3]:(n=(0,K.jsx)(rs,{reset:e.reset}),t[2]=e.reset,t[3]=n),n}function as(e){let t=(0,Io.c)(10),n;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(n={includeFailure:!0},t[0]=n):n=t[0];let r=ko(e.atom,n),i=wo(e.atom),a;if(t[1]!==e.children||t[2]!==i||t[3]!==r){let n;t[5]!==e.children||t[6]!==r?(n=()=>x(hi(r),{onNone:cr,onSome:e.children}),t[5]=e.children,t[6]=r,t[7]=n):n=t[7];let o;t[8]===i?o=t[9]:(o=e=>(0,K.jsx)(is,{error:sn(e),reset:i}),t[8]=i,t[9]=o),a=x(Ro(r),{onNone:n,onSome:o}),t[1]=e.children,t[2]=i,t[3]=r,t[4]=a}else a=t[4];return a}function os(e){let t=new Uint8Array(e),n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}function ss(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=(4-t.length%4)%4,r=t.padEnd(t.length+n,`=`),i=atob(r),a=new ArrayBuffer(i.length),o=new Uint8Array(a);for(let e=0;e<i.length;e++)o[e]=i.charCodeAt(e);return a}function cs(){return ls.stubThis(globalThis?.PublicKeyCredential!==void 0&&typeof globalThis.PublicKeyCredential==`function`)}var ls={stubThis:e=>e};function us(e){let{id:t}=e;return{...e,id:ss(t),transports:e.transports,type:e.type}}function ds(e){return e===`localhost`||/^((xn--[a-z0-9-]+|[a-z0-9]+(-[a-z0-9]+)*)\.)+([a-z]{2,}|xn--[a-z0-9-]+)$/i.test(e)}var q=class extends Error{constructor({message:e,code:t,cause:n,name:r}){super(e,{cause:n}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=r??n.name,this.code=t}};function fs({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(t.signal instanceof AbortSignal)return new q({message:`Registration ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`ConstraintError`){if(n.authenticatorSelection?.requireResidentKey===!0)return new q({message:`Discoverable credentials were required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT`,cause:e});if(t.mediation===`conditional`&&n.authenticatorSelection?.userVerification===`required`)return new q({message:`User verification was required during automatic registration but it could not be performed`,code:`ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE`,cause:e});if(n.authenticatorSelection?.userVerification===`required`)return new q({message:`User verification was required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT`,cause:e})}else if(e.name===`InvalidStateError`)return new q({message:`The authenticator was previously registered`,code:`ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED`,cause:e});else if(e.name===`NotAllowedError`)return new q({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`NotSupportedError`)return n.pubKeyCredParams.filter(e=>e.type===`public-key`).length===0?new q({message:`No entry in pubKeyCredParams was of type "public-key"`,code:`ERROR_MALFORMED_PUBKEYCREDPARAMS`,cause:e}):new q({message:`No available authenticator supported any of the specified pubKeyCredParams algorithms`,code:`ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG`,cause:e});else if(e.name===`SecurityError`){let t=globalThis.location.hostname;if(!ds(t))return new q({message:`${globalThis.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(n.rp.id!==t)return new q({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`TypeError`){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new q({message:`User ID was not between 1 and 64 characters`,code:`ERROR_INVALID_USER_ID_LENGTH`,cause:e})}else if(e.name===`UnknownError`)return new q({message:`The authenticator was unable to process the specified options, or could not create a new credential`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return e}var ps=new class{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){let e=Error(`Cancelling existing WebAuthn API call for new one`);e.name=`AbortError`,this.controller.abort(e)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=Error(`Manually cancelling existing WebAuthn API call`);e.name=`AbortError`,this.controller.abort(e),this.controller=void 0}}},ms=[`cross-platform`,`platform`];function hs(e){if(e&&!(ms.indexOf(e)<0))return e}async function gs(e){!e.optionsJSON&&e.challenge&&(console.warn(`startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.`),e={optionsJSON:e});let{optionsJSON:t,useAutoRegister:n=!1}=e;if(!cs())throw Error(`WebAuthn is not supported in this browser`);let r={...t,challenge:ss(t.challenge),user:{...t.user,id:ss(t.user.id)},excludeCredentials:t.excludeCredentials?.map(us)},i={};n&&(i.mediation=`conditional`),i.publicKey=r,i.signal=ps.createNewAbortSignal();let a;try{a=await navigator.credentials.create(i)}catch(e){throw fs({error:e,options:i})}if(!a)throw Error(`Registration was not completed`);let{id:o,rawId:s,response:c,type:l}=a,u;typeof c.getTransports==`function`&&(u=c.getTransports());let d;if(typeof c.getPublicKeyAlgorithm==`function`)try{d=c.getPublicKeyAlgorithm()}catch(e){_s(`getPublicKeyAlgorithm()`,e)}let f;if(typeof c.getPublicKey==`function`)try{let e=c.getPublicKey();e!==null&&(f=os(e))}catch(e){_s(`getPublicKey()`,e)}let p;if(typeof c.getAuthenticatorData==`function`)try{p=os(c.getAuthenticatorData())}catch(e){_s(`getAuthenticatorData()`,e)}return{id:o,rawId:os(s),response:{attestationObject:os(c.attestationObject),clientDataJSON:os(c.clientDataJSON),transports:u,publicKeyAlgorithm:d,publicKey:f,authenticatorData:p},type:l,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:hs(a.authenticatorAttachment)}}function _s(e,t){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${e}. You should report this error to them.\n`,t)}function vs(){if(!cs())return ys.stubThis(new Promise(e=>e(!1)));let e=globalThis.PublicKeyCredential;return e?.isConditionalMediationAvailable===void 0?ys.stubThis(new Promise(e=>e(!1))):ys.stubThis(e.isConditionalMediationAvailable())}var ys={stubThis:e=>e};function bs({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(t.signal instanceof AbortSignal)return new q({message:`Authentication ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`NotAllowedError`)return new q({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`SecurityError`){let t=globalThis.location.hostname;if(!ds(t))return new q({message:`${globalThis.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(n.rpId!==t)return new q({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`UnknownError`)return new q({message:`The authenticator was unable to process the specified options, or could not create a new assertion signature`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return e}async function xs(e){!e.optionsJSON&&e.challenge&&(console.warn(`startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.`),e={optionsJSON:e});let{optionsJSON:t,useBrowserAutofill:n=!1,verifyBrowserAutofillInput:r=!0}=e;if(!cs())throw Error(`WebAuthn is not supported in this browser`);let i;t.allowCredentials?.length!==0&&(i=t.allowCredentials?.map(us));let a={...t,challenge:ss(t.challenge),allowCredentials:i},o={};if(n){if(!await vs())throw Error(`Browser does not support WebAuthn autofill`);if(document.querySelectorAll(`input[autocomplete$='webauthn']`).length<1&&r)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');o.mediation=`conditional`,a.allowCredentials=[]}o.publicKey=a,o.signal=ps.createNewAbortSignal();let s;try{s=await navigator.credentials.get(o)}catch(e){throw bs({error:e,options:o})}if(!s)throw Error(`Authentication was not completed`);let{id:c,rawId:l,response:u,type:d}=s,f;return u.userHandle&&(f=os(u.userHandle)),{id:c,rawId:os(l),response:{authenticatorData:os(u.authenticatorData),clientDataJSON:os(u.clientDataJSON),signature:os(u.signature),userHandle:f},type:d,clientExtensionResults:s.getClientExtensionResults(),authenticatorAttachment:hs(s.authenticatorAttachment)}}w(`MachineSchemaEncodeError`);var J=class extends w(`MachineSchemaDecodeError`){},Ss=class extends w(`InfiniteTransitionError`){},Cs=class extends w(`StartupError`){},ws=class extends w(`ChildAlreadyExistsError`){};w(`ProcessLocalError`);var Ts=class extends w(`StoppedError`){},Es=e=>e instanceof Ss||e instanceof J,Ds=e=>Es(e)?V(e):gn(e),Os=e=>Es(e)||e instanceof Cs?e:new Cs({cause:st(e)}),Y=e=>e,ks=`~effect/Machine/Target`,As=Symbol(`effect/Machine/TargetSnapshot`),js=Symbol(`effect/Machine/StateInput`),Ms=Symbol(`effect/Machine/HistoryTarget`),Ns=Symbol(`effect/Machine/InitialTarget`),Ps=Symbol(`effect/Machine/ChoiceTarget`),Fs=Symbol(`effect/Machine/NoTarget`),Is=Symbol(`effect/Machine/Declined`),Ls=Symbol(`effect/Machine/TargetSelection`),Rs=Symbol(`effect/Machine/StateUpdate`),zs=Symbol(`effect/Machine/CombinedTarget`),Bs=Symbol(`effect/Machine/SelectedBranch`),Vs=(e,t,n,r)=>Object.freeze({[Ls]:Ls,kind:e,scope:n,path:t,...r===void 0?{}:{updatePath:r}}),Hs=Vs(`none`,void 0,`local`),Us=e=>N(e,Ls),Ws=(e,t)=>Object.freeze({[Rs]:Rs,path:e,value:t}),Gs=e=>N(e,Rs),Ks=(e,t)=>Object.freeze({[zs]:zs,target:e,update:t}),qs=e=>N(e,zs),Js=(e,t,n,r)=>Object.freeze({[Bs]:Bs,owner:e,branchIndex:t,branchKey:n,result:r}),Ys=e=>N(e,Bs),Xs=Object.freeze({[Fs]:Fs}),Zs=()=>Xs,Qs=e=>N(e,Fs),$s=Object.freeze({[Is]:Is}),ec=()=>$s,tc=e=>N(e,Is),nc=(e,t)=>({[Ms]:Ms,path:e,parent:t}),rc=e=>N(e,Ms),ic=(e,t,n)=>({[Ns]:Ns,_tag:`InitialTarget`,path:e,value:t,...n===void 0?{}:{values:n}}),ac=e=>N(e,Ns),oc=(e,t,n)=>({[Ps]:Ps,path:e,parent:t,...n===void 0?{}:{values:n}}),sc=e=>N(e,Ps),cc=(e,t)=>{if(!O(t)&&t.type===`history`)return{schema:void 0,output:void 0,annotations:t.annotations,type:`history`,history:t.history===`deep`?`deep`:`shallow`,initial:void 0,states:void 0};if(!O(t)&&t.type===`choice`)return{schema:void 0,output:void 0,annotations:t.annotations,type:`choice`,history:void 0,initial:void 0,states:void 0};if(O(t))return{schema:t,output:void 0,annotations:te(t),type:`atomic`,history:void 0,initial:void 0,states:void 0};let n=N(t,`schema`)&&O(t.schema)?t.schema:void 0,r=n===void 0?t.annotations:te(n);if(t.type===`parallel`&&!N(t,`states`))throw Error(`Machine.make expected parallel state "${e}" to declare child regions`);if(N(t,`states`)){if(t.type===`final`)throw Error(`Machine.make expected compound state "${e}" to be active`);if(t.type===`parallel`)return{schema:n,output:O(t.output)?t.output:void 0,annotations:r,type:`parallel`,history:void 0,initial:void 0,states:t.states};let i=`initial`in t?t.initial:void 0;if(typeof i!=`string`)throw Error(`Machine.make expected compound state "${e}" to declare an initial child`);return{schema:n,output:void 0,annotations:r,type:`compound`,history:void 0,initial:i,states:t.states}}let i=O(t.output)?t.output:void 0;return t.type===`final`?{schema:n,output:i,annotations:r,type:`final`,history:void 0,initial:void 0,states:void 0}:{schema:n,output:void 0,annotations:r,type:`atomic`,history:void 0,initial:void 0,states:void 0}},lc=e=>{let t=new Map,n=0,r=(e,i)=>{let a=[];for(let o of Object.keys(e)){if(o.includes(`.`))throw Error(`Machine state keys cannot contain ".": "${o}"`);let s=i===void 0||i===``?o:`${i}.${o}`,c=cc(s,e[o]),l,u,d={path:s,key:o,annotations:c.annotations,order:n};switch(c.type){case`atomic`:l={...d,type:`atomic`,schema:c.schema,output:void 0,history:void 0,parent:i,children:[],initial:void 0};break;case`compound`:l={...d,type:`compound`,schema:c.schema,output:void 0,history:void 0,parent:i,children:[],initial:s===``?c.initial:`${s}.${c.initial}`},u=c.states;break;case`parallel`:l={...d,type:`parallel`,schema:c.schema,output:c.output,history:void 0,parent:i,children:[],initial:void 0},u=c.states;break;case`final`:l={...d,type:`final`,schema:c.schema,output:c.output,history:void 0,parent:i,children:[],initial:void 0};break;case`history`:if(i===void 0)throw Error(`Machine history state "${s}" must belong to a parent state`);l={...d,type:`history`,schema:void 0,output:void 0,history:c.history,parent:i,children:[],initial:void 0};break;case`choice`:if(i===void 0)throw Error(`Machine choice state "${s}" must belong to a parent state`);l={...d,type:`choice`,schema:void 0,output:void 0,history:void 0,parent:i,children:[],initial:void 0}}if(t.set(s,l),n+=1,c.type!==`history`&&c.type!==`choice`&&(a.push(s),u!==void 0)){let e=r(u,s);if(l.type===`compound`){if(!e.includes(l.initial)&&t.get(l.initial)?.type!==`choice`)throw Error(`Machine.make expected compound state "${s}" initial child to exist`);l={...l,children:e}}else if(l.type===`parallel`)l={...l,children:e};else throw Error(`Machine state "${s}" cannot declare child states`);t.set(s,l)}}return a};return{byPath:t,roots:r(e,void 0)}},uc=e=>typeof e==`object`&&e&&`branches`in e&&Array.isArray(e.branches)?Array.from(e.branches):[],dc=e=>typeof e==`object`&&e&&`declinable`in e&&e.declinable===!0?`declinable`:`required`,fc=e=>{let t=[];for(let n of e.stateNodes.byPath.values()){let r=Y(e).handlers[n.path];if(r===void 0)continue;if(n.type===`choice`){let e=r.choice;e!==void 0&&t.push({source:n.path,trigger:{type:`choice`},reenter:!1,acceptance:`required`,branches:uc(e)});continue}for(let e of Reflect.ownKeys(r.on??{})){let i=r.on?.[e];t.push({source:n.path,trigger:{type:`event`,event:e},reenter:N(i,`reenter`)&&i.reenter===!0,acceptance:dc(i),branches:uc(i)})}r.always!==void 0&&t.push({source:n.path,trigger:{type:`always`},reenter:!1,acceptance:dc(r.always),branches:uc(r.always)}),r.onDone!==void 0&&t.push({source:n.path,trigger:{type:`done`},reenter:!1,acceptance:dc(r.onDone),branches:uc(r.onDone)});let i=r.invoke===void 0?[]:Array.isArray(r.invoke)?r.invoke:[r.invoke];for(let e of i){let r=`child`in e?String(e.child.id):String(e.id);for(let i of[`element`,`done`,`failure`,`snapshot`]){let a=i===`element`?e.onElement:i===`done`?e.onDone:i===`failure`?e.onFailure:e.onSnapshot;a!==void 0&&t.push({source:n.path,trigger:{type:`invoke`,id:r,outcome:i},reenter:typeof a==`object`&&!!a&&a.reenter===!0,acceptance:dc(a),branches:uc(a)})}}}return t},pc=(e,t,n)=>({[ks]:ks,[As]:n?.snapshot,path:e,value:t,values:n?.values}),mc=e=>N(e,ks),hc=e=>({[js]:js,input:e}),gc=e=>N(e,js),_c=e=>N(e,`path`)&&N(e,`value`),vc=(e,t,n)=>{if(e.path===t)return j(e);if(e.path!==``&&!t.startsWith(`${e.path}.`))return M();if(n!==void 0&&e.value!==void 0&&(n[e.path]=e.value),N(e,`state`)&&_c(e.state))return vc(e.state,t,n);if(N(e,`states`)&&typeof e.states==`object`&&e.states!==null){for(let r of Object.values(e.states))if(_c(r)){let e=vc(r,t,n);if(T(e))return e}}return M()},X=(e,t)=>{let n=e.stateNodes.byPath.get(t);if(n===void 0)throw Error(`Machine expected state path "${t}" to exist`);return n},yc=e=>{if(e.schema===void 0)throw Error(`Machine state "${e.path}" has no value schema`);return e.schema},bc=new WeakMap,xc=Symbol(`effect/Machine/EventConstruction`),Sc=new WeakMap,Cc=new WeakMap,wc=new WeakMap,Tc=e=>{let t=e,n=Cc.get(t);if(n!==void 0)return n;let r=Yt(nn(e));return Cc.set(t,r),r},Ec=e=>{let t=e,n=wc.get(t);if(n!==void 0)return n;let r=he(nn(e));return wc.set(t,r),r},Dc=Symbol.for(`effect/Machine/protocol`),Oc=e=>{let t=e[Dc];if(t===void 0)throw Error(`Machine protocol is unavailable`);return t},kc=(e,t)=>{Object.defineProperty(e,Dc,{value:t,enumerable:!1})},Ac=e=>{let t=new Set,n=e=>{let r=e;if(!t.has(r)&&(t.add(r),N(e,`cases`)&&typeof e.cases==`object`&&e.cases!==null))for(let t of Object.values(e.cases))(typeof t==`object`&&t||typeof t==`function`)&&N(t,`make`)&&n(t)};for(let t of e)n(t);return t},jc=(e,t)=>{let n=bc.get(e);if(n===void 0)throw Error(`Machine expected an event protocol created with Machine.events, Machine.internalEvents, or Machine.emittedEvents`);if(t!==void 0&&n.kind!==t)throw Error(`Machine expected a ${t} event protocol`);return n},Mc=e=>jc(e.events,`public`).schemas,Nc=e=>jc(e.internalEvents,`internal`).schemas,Pc=e=>jc(e.emittedEvents,`emitted`).schemas,Fc=e=>{let t=Mc(e),n=Nc(e),r=Pc(e),i=new Set(Reflect.ownKeys(e.events));for(let t of Reflect.ownKeys(e.internalEvents))if(i.has(t))throw Error(`Public and internal machine event tags must be disjoint: ${String(t)}`);let a=[...t,...n];kc(e,{event:aa(a),emit:aa(r),eventConstructors:Ac(a),emissionConstructors:Ac(r)})},Ic=(e,t)=>kc(t,Oc(e)),Lc=e=>N(e,`_tag`)?String(e._tag):void 0,Rc=(e,t,n,r)=>{let i=r,a;if(typeof r==`object`&&r)try{i={...r}}catch(e){i=void 0,a=e}let o={[xc]:xc,_tag:n};return Sc.set(o,{kind:e,schema:t,input:i,...a===void 0?{}:{inputError:a}}),Object.freeze(o)},zc=e=>typeof e==`object`&&!!e&&Sc.has(e),Bc=(e,t)=>{let n=[],r=e=>{if(N(e,`cases`)&&typeof e.cases==`object`&&e.cases!==null)for(let t of Reflect.ownKeys(e.cases))r(Reflect.get(e.cases,t));else if(N(e,`members`)&&Array.isArray(e.members))for(let t of e.members)r(t);else n.push(e)};for(let e of t)r(e);let i=Object.create(null),a=e=>vi(e)?typeof e.literal==`string`||typeof e.literal==`number`?[e.literal]:[]:ri(e)?[e.symbol]:Qe(e)?e.enums.map(([,e])=>e):zi(e)?e.types.flatMap(a):Mt(e)?a(e.thunk()):[],o=e=>{let t=Ti(e.ast);if(En(t)){let e=t.propertySignatures.find(({name:e})=>e===`_tag`),n=e===void 0?[]:a(e.type);if(n.length>0)return n}try{return aa([e]).pipe(Ne(`_tag`)).discriminants}catch{return[]}};for(let t of n){let n=o(t);if(n.length!==0)for(let r of n){if(N(i,r))throw Error(`Duplicate machine event constructor tag: ${String(r)}`);Object.defineProperty(i,r,{value:(...n)=>Rc(e,t,r,n.length===0?{}:n[0]),enumerable:!0})}}return i},Vc=(e,t)=>{let n=Object.freeze(Array.from(t)),r=Bc(e,n);return bc.set(r,{kind:e,schemas:n}),Object.freeze(r)},Hc=(e,t,n,r)=>Tc(t)(n).pipe(Ai(t=>new J({machineId:e.id,boundary:r.boundary,cause:t,...r.state===void 0?{}:{state:r.state},...r.event===void 0?{}:{event:r.event}}))),Uc=(e,t,n,r)=>{let i=Ec(t)(n);if(Xt(i))throw new J({machineId:e.id,boundary:r.boundary,cause:i.failure,...r.state===void 0?{}:{state:r.state},...r.event===void 0?{}:{event:r.event}});return i.success},Wc=(e,t,n,r)=>{try{return t.make(n)}catch(t){let n=t instanceof Error?t.cause:void 0;throw new J({machineId:e.id,boundary:r.boundary,cause:Se(t)?t:N(n,`~effect/SchemaIssue/Issue`)?new Sr(n):st(t),...r.state===void 0?{}:{state:r.state},...r.event===void 0?{}:{event:r.event}})}},Gc=(e,t,n)=>new J({machineId:e.id,boundary:n,event:String(t._tag),cause:st(Error(`Constructed ${n} schema does not belong to the machine ${n} protocol`))}),Kc=(e,t)=>{if(t.inputError!==void 0)throw t.inputError;return typeof t.input==`object`&&t.input!==null?{...t.input,_tag:e._tag}:{_tag:e._tag}},qc=(e,t,n,r)=>new J({machineId:e.id,boundary:n,event:String(t._tag),cause:st(r)}),Jc=(e,t,n,r)=>{let i=Sc.get(n),a=r===`event`?t.eventConstructors:t.emissionConstructors;return i===void 0||(r===`emission`?i.kind!==`emitted`:i.kind===`emitted`)||!a.has(i.schema)?V(Gc(e,n,r)):Rr({try:()=>Kc(n,i),catch:t=>qc(e,n,r,t)}).pipe(P(t=>i.schema.makeEffect(t).pipe(Ai(t=>new J({machineId:e.id,boundary:r,event:String(n._tag),cause:new Sr(t)})))))},Yc=(e,t,n,r)=>{let i=Sc.get(n),a=r===`event`?t.eventConstructors:t.emissionConstructors;if(i===void 0||(r===`emission`?i.kind!==`emitted`:i.kind===`emitted`)||!a.has(i.schema))throw Gc(e,n,r);let o;try{o=Kc(n,i)}catch(t){throw qc(e,n,r,t)}return Wc(e,i.schema,o,{boundary:r,event:String(n._tag)})},Xc=(e,t)=>{let n=Oc(e);if(zc(t))return Jc(e,n,t,`event`);let r=Lc(t);return Hc(e,n.event,t,r===void 0?{boundary:`event`}:{boundary:`event`,event:r})},Zc=(e,t)=>{let n=Oc(e);if(zc(t))return Yc(e,n,t,`event`);let r=Lc(t);return Uc(e,n.event,t,r===void 0?{boundary:`event`}:{boundary:`event`,event:r})},Qc=(e,t)=>{let n=Oc(e);if(zc(t))return Jc(e,n,t,`emission`);let r=Lc(t);return Hc(e,n.emit,t,r===void 0?{boundary:`emission`}:{boundary:`emission`,event:r})},$c=(e,t)=>{let n=Oc(e);if(zc(t))return Yc(e,n,t,`emission`);let r=Lc(t);return Uc(e,n.emit,t,r===void 0?{boundary:`emission`}:{boundary:`emission`,event:r})},el=(e,t,n)=>Uc(e,t,n,{boundary:`input`}),tl=(e,t,n)=>gc(n)?yc(t).makeEffect(n.input).pipe(Ai(n=>new J({machineId:e.id,boundary:`state`,state:t.path,cause:new Sr(n)}))):Hc(e,yc(t),n,{boundary:`state`,state:t.path}),Z=(e,t,n)=>gc(n)?Wc(e,yc(t),n.input,{boundary:`state`,state:t.path}):Uc(e,yc(t),n,{boundary:`state`,state:t.path}),nl=(e,t,n)=>t.output===void 0?A(n):Hc(e,t.output,n,{boundary:`output`,state:t.path}),rl=(e,t,n)=>t.output===void 0?n:Uc(e,t.output,n,{boundary:`output`,state:t.path}),il=(e,t)=>{let n=new Set(Q(e,t.parent)),r=n=>{let i=X(e,n);if(i.type===`compound`){let e=i.children.filter(e=>t.active.has(e));if(e.length!==1)throw Error(`Machine history expected compound state "${n}" to retain one active child`);t.mode===`deep`&&r(e[0])}else if(i.type===`parallel`)for(let e of i.children){if(!t.active.has(e))throw Error(`Machine history expected parallel state "${n}" to retain region "${e}"`);t.mode===`deep`&&r(e)}};r(t.parent);for(let r of t.active){if(!n.has(r)&&!pl(r,t.parent))throw Error(`Machine history contains state "${r}" outside parent "${t.parent}"`);if(t.mode===`shallow`&&fl(r,t.parent)&&X(e,r).parent!==t.parent)throw Error(`Machine shallow history contains deep descendant "${r}"`)}},al=(e,t)=>{let n=new Map;for(let[r,i]of Object.entries(t.history??{})){let t=X(e,r);if(t.type!==`history`||t.parent===void 0||t.history!==i.mode)throw Error(`Machine snapshot contains invalid history record "${r}"`);let a=new Set,o=new Map;for(let n of i.active){if(a.has(n))throw Error(`Machine snapshot contains invalid remembered state "${n}"`);let r=X(e,n);if(r.type===`history`||r.type===`choice`||!(pl(n,t.parent)||Q(e,t.parent).includes(n)))throw Error(`Machine snapshot contains invalid remembered value for "${n}"`);a.add(n);let s=Object.prototype.hasOwnProperty.call(i.values,n);if(r.schema===void 0){if(s)throw Error(`Machine snapshot contains a value for structural state "${n}"`)}else{if(!s)throw Error(`Machine snapshot omits remembered value for "${n}"`);o.set(n,Z(e,r,i.values[n]))}}if(!a.has(t.parent)||Object.keys(i.values).length!==o.size)throw Error(`Machine snapshot contains incomplete history record "${r}"`);n.set(r,{mode:i.mode,parent:t.parent,active:a,values:o}),il(e,n.get(r))}return n},ol=Sn(function*(e,t){let n=new Map;for(let[r,i]of Object.entries(t.history??{})){let t=e.stateNodes.byPath.get(r);if(t===void 0||t.type!==`history`||t.parent===void 0||t.history!==i.mode)return yield*V(new J({machineId:e.id,boundary:`history`,state:r,cause:st(Error(`Machine snapshot contains invalid history record "${r}"`))}));let a=new Set,o=new Map;for(let n of i.active){let r=e.stateNodes.byPath.get(n);if(a.has(n)||r===void 0||r.type===`history`||r.type===`choice`||!(pl(n,t.parent)||Q(e,t.parent).includes(n)))return yield*V(new J({machineId:e.id,boundary:`history`,state:n,cause:st(Error(`Machine snapshot contains invalid remembered state "${n}"`))}));a.add(n);let s=Object.prototype.hasOwnProperty.call(i.values,n);if(r.schema===void 0){if(s)return yield*V(new J({machineId:e.id,boundary:`history`,state:n,cause:st(Error(`Machine snapshot contains a value for structural state "${n}"`))}))}else{if(!s)return yield*V(new J({machineId:e.id,boundary:`history`,state:n,cause:st(Error(`Machine snapshot omits remembered value for "${n}"`))}));o.set(n,yield*Hc(e,yc(r),i.values[n],{boundary:`history`,state:n}))}}if(!a.has(t.parent)||Object.keys(i.values).length!==o.size)return yield*V(new J({machineId:e.id,boundary:`history`,state:r,cause:st(Error(`Machine snapshot contains incomplete history record "${r}"`))}));n.set(r,{mode:i.mode,parent:t.parent,active:a,values:o});try{il(e,n.get(r))}catch(t){return yield*V(new J({machineId:e.id,boundary:`history`,state:r,cause:st(t)}))}}return n}),sl=(e,t)=>{let n={};for(let[r,i]of t){let t=Array.from(i.active).sort((t,n)=>hl(e,t,n));n[r]={mode:i.mode,active:t,values:Object.fromEntries(i.values)}}return n},cl=(e,t)=>({...e,machineReferences:{self:t.self,parent:t.parent}}),ll=e=>e.machineReferences,ul=new WeakMap,dl=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),fl=(e,t)=>e!==t&&(t===``||e.startsWith(`${t}.`)),pl=(e,t)=>e===t||fl(e,t),Q=(e,t)=>{let n=ul.get(e.stateNodes);n===void 0&&(n=new Map,ul.set(e.stateNodes,n));let r=n.get(t);if(r!==void 0)return r;let i=[],a=t;for(;a!==void 0;)i.unshift(a),a=X(e,a).parent;return n.set(t,i),i},ml=(e,t)=>Q(e,t).length,hl=(e,t,n)=>X(e,t).order-X(e,n).order,gl=(e,t,n)=>X(e,n).children.some(e=>t.active.has(e)),_l=(e,t)=>{let n=Array.from(t.active).filter(n=>!gl(e,t,n)).sort((t,n)=>hl(e,t,n));if(n.length===0)throw Error(`Machine expected an active leaf state`);return n},vl=(e,t)=>_l(e,t)[0],yl=(e,t,n)=>{let r=_l(e,t).filter(e=>pl(e,n));if(r.length===0)throw Error(`Machine expected state "${n}" to have an active leaf state`);return r[0]},bl=(e,t)=>{for(let n of t.active)if(X(e,n).parent===void 0)return n;throw Error(`Machine expected an active root state`)},xl=(e,t,n)=>{let r={},i=Q(e,n);for(let e=0;e<i.length-1;e++){let n=i[e];t.values.has(n)&&(r[n]=t.values.get(n))}return r},Sl=(e,t,n)=>{let r=X(e,n).parent;return r===void 0?void 0:t.values.get(r)},Cl=(e,t)=>{let n=r=>t.active.has(r)?[r,...X(e,r).children.flatMap(n)]:[];return e.stateNodes.roots.flatMap(n)},wl=(e,t,n)=>{let r=X(e,n),i={path:n,value:t.values.get(n)};if(r.type===`compound`){let a=r.children.find(e=>t.active.has(e));if(a===void 0)throw Error(`Machine expected compound state "${n}" to have an active child`);i.state=wl(e,t,a)}if(r.type===`parallel`){let a={};for(let i of r.children){if(!t.active.has(i))throw Error(`Machine expected parallel state "${n}" to have active child region "${i}"`);let r=X(e,i);a[r.key]=wl(e,t,i)}i.states=a}return i},Tl=(e,t)=>{let n=wl(e,t,bl(e,t)),r=Array.from(t.outputs).map(([e,t])=>({path:e,output:t}));return r.length>0&&(n.completed=r),t.history.size>0&&Object.assign(n,{history:sl(e,t.history)}),n},El=(e,t,n)=>{let r=wl(e,t,n);return t.history.size>0&&Object.assign(r,{history:sl(e,t.history)}),r},Dl=(e,t,n)=>{if(!N(n,`state`)||!_c(n.state))throw Error(`Machine expected compound snapshot "${t.path}" to include an active child state`);let r=X(e,String(n.state.path));if(r.parent!==t.path)throw Error(`Machine expected snapshot "${r.path}" to be a child of "${t.path}"`);return n.state},Ol=(e,t)=>{if(!N(t,`states`)||typeof t.states!=`object`||t.states===null)throw Error(`Machine expected parallel snapshot "${e.path}" to include active child regions`);return t.states},kl=(e,t,n,r)=>{let i=X(e,n),a=r[i.key];if(!dl(r,i.key)||!_c(a))throw Error(`Machine expected parallel snapshot "${t.path}" to include region "${i.key}"`);let o=X(e,String(a.path));if(o.path!==i.path)throw Error(`Machine expected snapshot "${o.path}" to be region "${i.path}"`);return a},Al=(e,t)=>{let n=new Set,r=new Map,i=t.completed,a=t=>{let i=X(e,String(t.path));if(n.add(i.path),i.schema===void 0){if(t.value!==void 0)throw Error(`Machine structural snapshot "${i.path}" cannot contain a value`)}else r.set(i.path,Z(e,i,t.value));if(i.type===`compound`&&a(Dl(e,i,t)),i.type===`parallel`){let n=Ol(i,t);for(let t of i.children)a(kl(e,i,t,n))}};a(t);let o=new Map;if(i!==void 0)for(let{output:e,path:t}of i)n.has(t)&&o.set(t,e);return{active:n,values:r,outputs:o,history:al(e,t)}},jl=(e,t)=>Al(e,t),Ml=(e,t)=>{try{return Al(e,t)}catch(t){throw t instanceof J?t:new J({machineId:e.id,boundary:`configuration`,cause:st(t)})}},Nl=Sn(function*(e,t){let n=new Set,r=new Map,i=t.completed,a=Sn(function*(t){let i=X(e,String(t.path));if(n.add(i.path),i.schema===void 0){if(t.value!==void 0)throw Error(`Machine structural snapshot "${i.path}" cannot contain a value`)}else r.set(i.path,yield*tl(e,i,t.value));if(i.type===`compound`&&(yield*a(Dl(e,i,t))),i.type===`parallel`){let n=Ol(i,t);for(let t of i.children)yield*a(kl(e,i,t,n))}});yield*a(t);let o=new Map;if(i!==void 0)for(let{output:e,path:t}of i)n.has(t)&&o.set(t,e);return{active:n,values:r,outputs:o,history:yield*ol(e,t)}}),Pl=(e,t)=>Nl(e,t).pipe(S(t=>{if(Re(t))return Je(b(t,t=>t instanceof J?t:new J({machineId:e.id,boundary:`configuration`,cause:pt(t)})));let n=Tt(t);return T(n)&&n.value instanceof J?V(n.value):V(new J({machineId:e.id,boundary:`configuration`,cause:t}))})),Fl=(e,t,n,r)=>{if(r.length===0)return n;let i=new Set(r),a=new Map(n.history);for(let n of e.stateNodes.byPath.values()){if(n.type!==`history`||n.parent===void 0||!i.has(n.parent))continue;let r=n.history===`deep`?`deep`:`shallow`,o=new Set;for(let r of Q(e,n.parent))t.active.has(r)&&o.add(r);for(let i of t.active)(i===n.parent||r===`deep`&&fl(i,n.parent)||r===`shallow`&&X(e,i).parent===n.parent)&&o.add(i);let s=new Map;for(let e of o)t.values.has(e)&&s.set(e,t.values.get(e));a.set(n.path,{mode:r,parent:n.parent,active:o,values:s})}return{active:n.active,values:n.values,outputs:n.outputs,history:a}},Il=(e,t)=>e.history.get(t),Ll=(e,t,n)=>{let r=new Set(n.active),i=new Map(n.values),a=new Map,o=Q(e,n.parent),s=new Set(o);for(let c of o){let o=X(e,c);if(o.type===`parallel`){for(let e of o.children)if(!(s.has(e)||n.active.has(e)||!t.active.has(e)))for(let n of t.active)pl(n,e)&&(r.add(n),t.values.has(n)&&i.set(n,t.values.get(n)),t.outputs.has(n)&&a.set(n,t.outputs.get(n)))}}return{active:r,values:i,outputs:a,history:t.history}};Sn(function*(e,t,n,r,i){let a=X(e,n),o=new Set,s=new Map,c=new Map,l=Q(e,a.path),u=new Set(l);for(let n of l){let c=X(e,n);if(o.add(n),c.schema===void 0){if((n===a.path?r:i!==void 0&&dl(i,n)?i[n]:void 0)!==void 0)throw Error(`Machine structural target "${n}" cannot contain a value`)}else if(n===a.path)s.set(n,yield*tl(e,c,r));else if(i!==void 0&&dl(i,n))s.set(n,yield*tl(e,c,i[n]));else if(t.values.has(n))s.set(n,t.values.get(n));else throw Error(`Machine target "${a.path}" requires a value for ancestor state "${n}"`)}for(let n of l){let r=X(e,n);if(r.type===`parallel`){for(let e of r.children)if(!u.has(e)&&t.active.has(e))for(let n of t.active)pl(n,e)&&(o.add(n),t.values.has(n)&&s.set(n,t.values.get(n)),t.outputs.has(n)&&c.set(n,t.outputs.get(n)))}}if(a.type===`compound`||a.type===`parallel`)throw Error(`Machine target "${a.path}" must include an active child state`);return{active:o,values:s,outputs:c,history:t.history}}),Sn(function*(e,t,n,r){let i=yield*Nl(e,n),a=new Set(i.active),o=new Map(i.values),s=new Map(i.outputs),c=Q(e,String(n.path)),l=new Set(c);for(let i of c.slice(0,-1)){let s=X(e,i);if(a.add(i),s.schema===void 0){if(r!==void 0&&dl(r,i))throw Error(`Machine structural target "${i}" cannot contain a value`)}else if(r!==void 0&&dl(r,i))o.set(i,yield*tl(e,s,r[i]));else if(t.values.has(i))o.set(i,t.values.get(i));else throw Error(`Machine target "${n.path}" requires a value for ancestor state "${i}"`)}for(let n of c.slice(0,-1)){let i=X(e,n);if(i.type===`parallel`){for(let n of i.children)if(!l.has(n)){if(t.active.has(n))for(let e of t.active)pl(e,n)&&(a.add(e),t.values.has(e)&&o.set(e,t.values.get(e)),t.outputs.has(e)&&s.set(e,t.outputs.get(e)));else if(r!==void 0&&dl(r,n))for(let[t,i]of Object.entries(r)){if(!pl(t,n))continue;let r=X(e,t);if(a.add(t),r.schema===void 0)throw Error(`Machine structural target "${t}" cannot contain a value`);o.set(t,yield*tl(e,r,i))}}}}return{active:a,values:o,outputs:s,history:new Map([...t.history,...i.history])}});var Rl=(e,t,n,r,i,a=!1)=>{let o=X(e,n),s=new Set,c=new Map,l=new Map,u=Q(e,o.path),d=new Set(u);for(let n of u){let a=X(e,n);if(s.add(n),a.schema===void 0){if((n===o.path?r:i!==void 0&&dl(i,n)?i[n]:void 0)!==void 0)throw Error(`Machine structural target "${n}" cannot contain a value`)}else if(n===o.path)c.set(n,Z(e,a,r));else if(i!==void 0&&dl(i,n))c.set(n,Z(e,a,i[n]));else if(t.values.has(n))c.set(n,t.values.get(n));else throw Error(`Machine target "${o.path}" requires a value for ancestor state "${n}"`)}for(let n of u){let r=X(e,n);if(r.type===`parallel`&&n!==o.path){for(let e of r.children)if(!d.has(e)&&t.active.has(e))for(let n of t.active)pl(n,e)&&(s.add(n),t.values.has(n)&&c.set(n,t.values.get(n)),t.outputs.has(n)&&l.set(n,t.outputs.get(n)))}}if(!a&&(o.type===`compound`||o.type===`parallel`))throw Error(`Machine target "${o.path}" must include an active child state`);return{active:s,values:c,outputs:l,history:t.history}},zl=(e,t,n)=>{let r=Rl(e,t,n.path,n.value,n.values,!0);if(n.children===void 0)return r;let i=new Set(r.active),a=new Map(r.values);for(let[t,r]of n.children){let n=X(e,t);i.add(t),n.schema!==void 0&&a.set(t,Z(e,n,r))}return{...r,active:i,values:a}},Bl=(e,t,n,r)=>{let i=Al(e,n),a=new Set(i.active),o=new Map(i.values),s=new Map(i.outputs),c=Q(e,String(n.path)),l=new Set(c);for(let i of c.slice(0,-1)){let s=X(e,i);if(a.add(i),s.schema===void 0){if(r!==void 0&&dl(r,i))throw Error(`Machine structural target "${i}" cannot contain a value`)}else if(r!==void 0&&dl(r,i))o.set(i,Z(e,s,r[i]));else if(t.values.has(i))o.set(i,t.values.get(i));else throw Error(`Machine target "${n.path}" requires a value for ancestor state "${i}"`)}for(let n of c.slice(0,-1)){let i=X(e,n);if(i.type===`parallel`){for(let n of i.children)if(!l.has(n)){if(t.active.has(n))for(let e of t.active)pl(e,n)&&(a.add(e),t.values.has(e)&&o.set(e,t.values.get(e)),t.outputs.has(e)&&s.set(e,t.outputs.get(e)));else if(r!==void 0&&dl(r,n))for(let[t,i]of Object.entries(r)){if(!pl(t,n))continue;let r=X(e,t);if(a.add(t),r.schema===void 0)throw Error(`Machine structural target "${t}" cannot contain a value`);o.set(t,Z(e,r,i))}}}}return{active:a,values:o,outputs:s,history:new Map([...t.history,...i.history])}},Vl=(e,t,n)=>{if(mc(n)){let r=n[As];if(r!==void 0){if(String(r.path)!==String(n.path))throw Error(`Machine expected target snapshot path to be "${n.path}"`);return Bl(e,t,r,n.values)}return Rl(e,t,n.path,n.value,n.values)}if(_c(n)){let r=Ml(e,n);return{...r,history:new Map([...t.history,...r.history])}}throw Error(`Machine expected transition target to be a snapshot or target builder result`)},Hl=(e,t)=>Y(e).handlers[t],Ul=(e,t,n)=>X(e,n).children.find(e=>t.active.has(e)),Wl=(e,t)=>X(e,t).type===`final`,Gl=(e,t)=>Hl(e,t)?.onDone!==void 0,Kl=(e,t,n)=>{if(!t.active.has(n))return!1;let r=X(e,n);if(r.type===`compound`){let r=Ul(e,t,n);return r!==void 0&&(n===``?!Gl(e,r)&&Kl(e,t,r):Wl(e,r))}if(r.type===`parallel`){for(let n of r.children)if(!Kl(e,t,n))return!1;return!0}return Wl(e,n)},ql=(e,t)=>{let n=bl(e,t);return Kl(e,t,n)&&!Gl(e,n)},Jl=(e,t,n)=>e.has(t)?{path:t,output:e.get(t),isNew:!1}:(e.set(t,n),{path:t,output:n,isNew:!0}),Yl=Sn(function*(e,t,n,r,i){let a=X(e,n),o=Hl(e,n)?.output?.({state:t.values.get(n),containingState:Sl(e,t,n),ancestors:xl(e,t,n),event:r,outputs:i});return yield*nl(e,a,o)}),Xl=Sn(function*(e,t,n,r,i,a){if(!t.active.has(n))return;if(i.has(n))return{path:n,output:i.get(n),isNew:!1};let o=X(e,n);if(o.type===`compound`){let o=Ul(e,t,n);if(o===void 0||(n===``?Gl(e,o):!Wl(e,o)))return;let s=yield*Xl(e,t,o,r,i,a);if(s===void 0)return;let c=Jl(i,n,s.output);return c.isNew&&a.push(c),c}if(o.type===`parallel`){let s={},c=!0;for(let n of o.children){let o=yield*Xl(e,t,n,r,i,a);o===void 0?c=!1:s[X(e,n).key]=o.output}if(!c)return;let l=Jl(i,n,yield*Yl(e,t,n,r,s));return l.isNew&&a.push(l),l}if(!Wl(e,n))return;let s=Jl(i,n,yield*Yl(e,t,n,r));return s.isNew&&a.push(s),s}),Zl=Sn(function*(e,t,n){let r=new Map(t.outputs),i=[],a={active:t.active,values:t.values,outputs:r,history:t.history};for(let t of Array.from(a.active).sort((t,n)=>{let r=ml(e,n)-ml(e,t);return r===0?hl(e,t,n):r}))yield*Xl(e,a,t,n,r,i);return{configuration:a,completions:i}}),Ql=(e,t,n,r,i)=>{let a=X(e,n),o=Hl(e,n)?.output?.({state:t.values.get(n),containingState:Sl(e,t,n),ancestors:xl(e,t,n),event:r,outputs:i});return rl(e,a,o)},$l=(e,t,n,r,i,a)=>{if(!t.active.has(n))return;if(i.has(n))return{path:n,output:i.get(n),isNew:!1};let o=X(e,n);if(o.type===`compound`){let o=Ul(e,t,n);if(o===void 0||(n===``?Gl(e,o):!Wl(e,o)))return;let s=$l(e,t,o,r,i,a);if(s===void 0)return;let c=Jl(i,n,s.output);return c.isNew&&a.push(c),c}if(o.type===`parallel`){let s={},c=!0;for(let n of o.children){let o=$l(e,t,n,r,i,a);o===void 0?c=!1:s[X(e,n).key]=o.output}if(!c)return;let l=Jl(i,n,Ql(e,t,n,r,s));return l.isNew&&a.push(l),l}if(!Wl(e,n))return;let s=Jl(i,n,Ql(e,t,n,r));return s.isNew&&a.push(s),s},eu=(e,t,n)=>{let r=new Map(t.outputs),i=[],a={active:t.active,values:t.values,outputs:r,history:t.history};for(let t of Array.from(a.active).sort((t,n)=>{let r=ml(e,n)-ml(e,t);return r===0?hl(e,t,n):r}))$l(e,a,t,n,r,i);return{configuration:a,completions:i}},tu=e=>{if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Machine construction must be an object`);return e},nu=(e,t)=>{if(t.decoded!==void 0&&typeof t.decoded!=`boolean`)throw Error(`Machine decoded construction flag must be a boolean`);if(e.schema===void 0){if(Object.hasOwn(t,`data`)||Object.hasOwn(t,`decoded`))throw Error(`Machine structural state "${e.path}" cannot construct data`)}else{if(t.decoded===!0){if(!Object.hasOwn(t,`data`))throw Error(`Machine decoded construction requires data`);return t.data}return hc(Object.hasOwn(t,`data`)?t.data:{})}},ru=(e,t,n={},r)=>{let i=e.byPath.get(t);if(i?.type===`atomic`||i?.type===`final`){let e=tu(n);if(Reflect.ownKeys(e).some(e=>e!==`data`&&e!==`decoded`))throw Error(`Machine leaf construction accepts only data and decoded`);return pc(t,nu(i,e))}let a=new Map,o=(t,n)=>{let i=tu(n);if(Reflect.ownKeys(i).some(e=>e!==`data`&&e!==`decoded`&&e!==`states`))throw Error(`Machine state construction accepts only data, decoded, and states`);let s=e.byPath.get(t);if(s===void 0||s.type===`history`)throw Error(`Machine invalid construction state "${t}"`);let c=nu(s,i);if(Object.hasOwn(i,`states`)){if(s.type!==`compound`&&s.type!==`parallel`)throw Error(`Machine state "${t}" has no child construction`);let n=tu(i.states),c=Reflect.ownKeys(n),l=s.children.filter(t=>e.byPath.get(t)?.type!==`history`);if(s.type===`compound`?c.length!==1:c.length!==l.length&&(c.length!==1||r===void 0||r!==t&&!r.startsWith(`${t}.`)))throw Error(`Machine explicit states for "${t}" must select ${s.type===`compound`?`one child`:`every region`}`);for(let r of c){let i=t===``?String(r):`${t}.${String(r)}`;if(typeof r!=`string`||e.byPath.get(i)?.parent!==t||e.byPath.get(i)?.type===`history`)throw Error(`Machine unknown child "${String(r)}"`);a.set(i,o(i,n[r]))}}return c},s=o(t,n),c=new Map(a);c.set(t,s);let l=t,u=tu(n);for(;u.states!==void 0;){let t=e.byPath.get(l),n=tu(u.states),i=Object.keys(n);if(i.length!==1||t.type===`parallel`&&(r===void 0||r!==l&&!r.startsWith(`${l}.`)))break;let a=i[0];l=l===``?a:`${l}.${a}`,u=tu(n[a])}let d=e.byPath.get(l),f=c.get(l),p=Object.fromEntries([...c].filter(([e,t])=>t!==void 0&&e!==l&&!e.startsWith(`${l}.`)));if(d.type===`choice`)return oc(l,d.parent??``,p);if(d.type===`atomic`||d.type===`final`)return pc(l,f,{values:p});let m=new Map([...a].filter(([e])=>e.startsWith(`${l}.`)));return{...ic(l,f,p),...m.size===0?{}:{children:m}}},iu=(e,t,n)=>{let r=tu(n);if(Reflect.ownKeys(r).some(e=>e!==`data`&&e!==`decoded`))throw Error(`Machine update construction accepts only data and decoded`);let i=e.byPath.get(t);if(i?.schema===void 0)throw Error(`Machine update requires a valued state`);return Ws(t,nu(i,r))},au=(e,t,n=``)=>{let r=tu(t),i=e.byPath.get(n);ru(e,n,r);let a=nu(i,r);if(i.type===`choice`)return oc(n,i.parent);if(i.type===`atomic`||i.type===`final`)return{path:n,value:a};if(r.states===void 0)throw Error(`Machine history fallback requires a complete explicit tree`);let o=tu(r.states),s=Object.fromEntries(Object.entries(o).map(([t,r])=>[t,au(e,r,n===``?t:`${n}.${t}`)]));return i.type===`parallel`?{path:n,value:a,states:s}:{path:n,value:a,state:Object.values(s)[0]}},ou=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw Error(t);return e},su=`root`,cu=e=>{let t=new Map,n=(e,r)=>{let i=!O(e)&&`type`in e?e.type:void 0;if(t.set(r,i===`history`||i===`choice`?i:`state`),!O(e)&&`states`in e)for(let[t,i]of Object.entries(e.states))n(i,r===``?t:`${r}.${t}`)};if(n(e.node,``),t.has(`root`))throw Error(`Machine top-level state name "${su}" is reserved for the root`);return t},lu=(e,t)=>{let n=cu(e),r=t.input!==void 0,i=new Map;for(let e of[`effects`,`streams`,`timers`,`logic`,`children`])if(t[e]!==void 0)for(let[n,r]of Object.entries(ou(t[e],`Machine ${e} must be a source map`))){if(i.has(n))throw Error(`Machine source name "${n}" is registered more than once`);i.set(n,Object.freeze({kind:e,value:r}))}let a=new Map;if(t.branches!==void 0)for(let[o,s]of Object.entries(ou(t.branches,`Machine branches must be a map`))){let t=ou(s,`Machine branches "${o}" must be a branch record`);for(let e of Reflect.ownKeys(t)){if(typeof e!=`string`)throw Error(`Machine branches cannot use symbol keys`);if(e.length===0||String(Number(e))===e)throw Error(`Machine branches require non-index string branch keys`)}let c=Object.entries(t);if(c.length===0)throw Error(`Machine branches "${o}" requires a branch`);a.set(o,Object.freeze(Object.fromEntries(c.map(([t,s])=>{let c={...ou(s,`Machine branch "${o}.${t}" must be a declaration`)};for(let e of Reflect.ownKeys(c))if(typeof e!=`string`||![`target`,`update`,`history`,`none`,`initialize`,`title`].includes(e))throw Error(`Machine branch "${o}.${t}" contains an unknown declaration field`);if(c.initialize!==void 0&&c.initialize!==!0)throw Error(`Machine branch "${o}.${t}" declares initialize: true; its resolver supplies input`);if(c.title!==void 0&&(typeof c.title!=`string`||c.title.length===0))throw Error(`Machine branch title must be a non-empty string`);return du({root:e,input:r,paths:n,sources:i,branches:a},c),[t,Object.freeze(c)]}))))}return{root:e,input:r,paths:n,sources:i,branches:a}},uu=(e,t)=>{let n=e===`root`?``:typeof e==`string`&&e!==``?e:void 0,r=n===void 0?void 0:t.paths.get(n);if(n===void 0||r===void 0)throw Error(`Machine target ${String(e)} is not a declared state path`);return{path:n,kind:r}},du=(e,t)=>{let n=[`target`,`history`,`none`,`initialize`].filter(e=>t[e]!==void 0);if(n.length===0&&t.update!==void 0){let n=uu(t.update,e);if(n.kind!==`state`)throw Error(`Machine update requires an active state reference`);return Vs(`update`,n.path,`branch`)}if(n.length!==1)throw Error(`Machine transition must declare exactly one destination operation`);let r=n[0];if(r===`none`){if(t.none!==!0||t.update!==void 0)throw Error(`Machine targetless transition requires none: true`);return Hs}if(r===`initialize`){if(t.update!==void 0)throw Error(`Machine initialize cannot update a retained owner`);return Vs(`state`,``,`branch`)}let i=uu(t[r],e);if(r===`target`&&i.path===``)throw Error(`Machine root is not a destination; use initialize to reconstruct it from machine input`);if(r===`history`!=(i.kind===`history`))throw Error(`Machine history references require a history transition`);let a=t.update===void 0?void 0:uu(t.update,e).path;if(a!==void 0&&r!==`target`)throw Error(`Machine owner updates require an ordinary destination`);return Vs(i.kind,i.path,r===`history`?`full`:`branch`,a)},fu=(e,t,n,r)=>{let i=ou(t,`Machine invocation for "${n}" must be an object`),a=typeof i.src==`string`?e.sources.get(i.src):void 0;if(a===void 0)throw Error(`Machine invocation for "${n}" names an unknown source`);let{src:o,input:s,...c}=i,l=typeof s==`function`?e=>s(r(e)):s;if(a.kind===`children`)return{...c,child:a.value,...l===void 0?{}:{input:l}};let u=typeof a.value==`function`&&!(a.kind===`effects`&&Ci(a.value))&&!(a.kind===`streams`&&Qt(a.value));if(u!==(typeof l==`function`))throw Error(`Machine invocation "${o}" requires input exactly when its source takes an argument`);let d=u?e=>a.value(l(e)):()=>a.value,f={effects:`effect`,streams:`stream`,timers:`after`,logic:`logic`}[a.kind];return{...c,sourceName:o,id:c.id??o,[f]:!u&&(a.kind===`timers`||a.kind===`logic`)?a.value:d}},pu=Symbol(`effect/Machine/InitialEvent`),mu=Symbol(`effect/Machine/SnapshotBuilderState`),hu=Symbol(`effect/Machine/ChildMachineLogic`),gu=new WeakSet,_u=e=>gu.has(e),vu=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Machine ${t} must be an object`);return e},yu=e=>typeof e==`function`?e:()=>e,bu=e=>{if(typeof e==`object`&&e&&N(e,`decoded`)&&e.decoded===!0&&N(e,`data`)){let t=vu(e,`decoded construction`);if(Reflect.ownKeys(t).some(e=>e!==`decoded`&&e!==`data`))throw Error(`Machine decoded construction accepts only decoded and data`);return yu(t.data)}let t=yu(e);return n=>hc(e===void 0?{}:t(n))},xu=e=>{if(e.decoded!==void 0&&typeof e.decoded!=`boolean`)throw Error(`Machine decoded construction flag must be a boolean`);if(e.decoded===!0){if(!N(e,`data`))throw Error(`Machine decoded construction requires data`);return yu(e.data)}let t=yu(e.data);return n=>hc(N(e,`data`)?t(n):{})},Su=(e,t)=>{let n=(e,t,r)=>{if(N(t,`initialize`))throw Error(`Machine child construction belongs in initial declarations`);if(r!==``&&N(t,`root`))throw Error(`Machine root construction belongs at the root handler`);let{initial:i,root:a,states:o,...s}=t;if(O(e)||!(`states`in e)){if(i!==void 0)throw Error(`Machine state "${r}" cannot declare initial children`);if(o!==void 0)throw Error(`Machine state "${r}" has no children`);return{node:e,handlers:s}}let c=o===void 0?{}:vu(o,`child handlers`);for(let t of Object.keys(c))if(!Object.prototype.hasOwnProperty.call(e.states,t))throw Error(`Machine unknown child "${t}"`);let l=Object.create(null),u=Object.create(null),d=Object.create(null),f=e.type===`parallel`,p;if(f){let t=i===void 0?{}:vu(i,`parallel initial regions`);for(let[n,r]of Object.entries(t)){let t=e.states[n];if(t===void 0||!O(t)&&(t.type===`history`||t.type===`choice`))throw Error(`Machine invalid initial region "${n}"`);if(!O(t)&&(!(`schema`in t)||t.schema===void 0))throw Error(`Machine schema-less region "${n}" cannot construct data`);d[n]=bu(r)}}else{let t=vu(i,`initial edge for "${r}"`);if(Reflect.ownKeys(t).some(e=>![`target`,`data`,`decoded`].includes(String(e))))throw Error(`Machine initial edge accepts only target, data, and decoded`);let n=r===``?``:`${r}.`,a=typeof t.target==`string`&&t.target.startsWith(n)?t.target.slice(n.length):void 0,o=a===void 0||!Object.hasOwn(e.states,a)?void 0:e.states[a],s=o===void 0||O(o)?`state`:o.type;if(a===void 0||o===void 0||s===`history`)throw Error(`Machine initial target must be a direct child of "${r===``?`root`:r}"`);if(p=a,s===`choice`&&(N(t,`data`)||N(t,`decoded`)))throw Error(`Machine choice initial edges cannot construct data`);let c=xu(t),l=e.states[a];if(N(t,`data`)&&!O(l)&&(!(`schema`in l)||l.schema===void 0))throw Error(`Machine schema-less initial child "${a}" cannot construct data`);N(t,`data`)&&(d[a]=c)}for(let[t,i]of Object.entries(e.states)){let e=r===``?t:`${r}.${t}`,a=n(i,c[t]===void 0?{}:vu(c[t],`state handler`),e);l[t]=a.node,(O(i)||i.type!==`history`)&&(c[t]!==void 0||!O(i)&&`states`in i)&&(u[t]=a.handlers)}let m=Object.freeze({...e,states:Object.freeze(l),...f?{}:{initial:p}}),h=Object.entries(d),g=e=>{let t=typeof e.ancestors==`object`&&e.ancestors!==null?e.ancestors:{},n={...e,root:r===``?e.state:t[``]},i=Object.fromEntries(h.map(([e,t])=>[e,t(n)]));return{[mu]:i}};return gu.add(g),{node:m,handlers:{...s,...h.length===0?{}:{initialize:g},states:u}}};return n(e.node,t,``)},Cu=(e,t)=>{let n=[`effect`,`stream`,`after`,`logic`,`child`].filter(t=>t in e);if(n.length!==1)throw Error(`Machine invocation for state "${t}" must define exactly one source`);if(n[0]!==`child`&&typeof e.id!=`string`)throw Error(`Machine invocation for state "${t}" requires a string id`);if((n[0]===`effect`||n[0]===`stream`)&&typeof e[n[0]]!=`function`)throw Error(`Machine invocation for state "${t}" requires a source callback`);return Object.freeze(e)},wu=e=>`child`in e?e.child.id:e.id,Tu=(e,t)=>{let n=new Set;for(let r of e){let e=wu(r);if(n.has(e))throw Error(`Machine invocations for state "${t}" must have distinct ids; "${e}" is declared twice`);n.add(e)}},Eu=e=>e===void 0?[]:Array.isArray(e)?e:[e],Du=e=>{let t=[],n=[],r=[];return{commands:t,raisedEvents:n,emittedEvents:r,enqueue:{raise:t=>{n.push(Zc(e,t))},emit:t=>{r.push($c(e,t))},sendTo:(e,n)=>{t.push({_tag:`SendTo`,target:e,event:n})},stop:e=>{t.push({_tag:`Stop`,child:e})}}}},Ou=(e,t)=>{let n=e.stateNodes.byPath.get(t);if(n===void 0)throw Error(`Machine expected state path "${t}" to exist`);return n},ku=e=>{let t={};return Object.defineProperty(t,"decoded",{value:e,enumerable:!1}),Object.defineProperty(t,"from",{value:(...t)=>e(hc(t.length===0?{}:t[0])),enumerable:!1}),t},Au=e=>{let t={};return Object.defineProperty(t,mu,{value:e,enumerable:!1}),t},ju=(e,t,n)=>{let r=Au(n);for(let i of t.children){let a=Ou(e,i);a.schema===void 0||N(n,a.key)||(r[a.key]=ku(r=>{let i=Object.assign({},n);return i[a.key]=r,ju(e,t,i)}))}return r},Mu=(e,t)=>{let n=Ou(e,t);if(n.type===`parallel`)return ju(e,n,{});if(n.type!==`compound`)throw Error(`Machine state "${t}" cannot initialize child states`);let r=Ou(e,n.initial);if(r.schema===void 0)throw Error(`Machine state "${t}" has no schema-valued initial child`);return ku(e=>Au({[r.key]:e}))},Nu=(e,t)=>{if(typeof t!=`object`||!t||!N(t,mu))throw Error(`Machine initialize handler for "${e}" must return its builder result`);return t[mu]},Pu=Symbol(`effect/Machine/InvocationEvent`),Fu=(e,t,n)=>({[Pu]:!0,path:e,id:t,type:`done`,output:n}),Iu=(e,t,n)=>({[Pu]:!0,path:e,id:t,type:`element`,element:n}),Lu=(e,t,n)=>({[Pu]:!0,path:e,id:t,type:`failure`,error:n}),Ru=(e,t,n)=>({[Pu]:!0,path:e,id:t,type:`snapshot`,snapshot:n}),zu=e=>typeof e==`object`&&!!e&&Pu in e,Bu=new WeakMap,Vu=new WeakMap,Hu=(e,t)=>e.parent===void 0?{self:t.self}:{self:t.self,parent:t.parent},Uu=(e,t)=>{let n=Object.create(e);return Vu.set(n,Hu(e,t)),n},Wu=(e,t)=>{let n=t.machineReferences;if(n!==void 0)return Hu(e,n);let r=Vu.get(e);if(r!==void 0)return r;let i=Bu.get(e);if(i!==void 0)return i;let a=Hu(e,{self:{id:e.id??`Machine`,sessionId:`Machine.plan`,send:()=>V(new Ts)},parent:void 0});return Bu.set(e,a),a},Gu=e=>{if(e!==void 0)return typeof e==`function`?{reenter:!1,declinable:!1,targets:void 0,transition:e,evaluate:void 0}:{reenter:e.reenter===!0,declinable:e.declinable===!0,targets:e.targets,transition:e.transition,evaluate:e.evaluate}},Ku=(e,t,n)=>{let r=Du(e);return t===void 0||t(n,r.enqueue),{commands:r.commands,raisedEvents:r.raisedEvents,emittedEvents:r.emittedEvents}},qu=(e,t,n,r)=>{let i=Du(e),a=r===void 0?{result:t(n,i.enqueue),branchIndex:0,branchKey:void 0}:r(n,i.enqueue);return tc(a.result)?{declined:!0}:{declined:!1,state:Qs(a.result)?void 0:a.result,branchIndex:a.branchIndex,branchKey:a.branchKey,commands:i.commands,raisedEvents:i.raisedEvents,emittedEvents:i.emittedEvents}},Ju=(e,t,n)=>{let r=Du(e);return{value:t(n,r.enqueue),commands:r.commands,raisedEvents:r.raisedEvents,emittedEvents:r.emittedEvents}},Yu=(e,t,n,r)=>{let i=new Set(t.active),a=new Map(t.values),o=[],s=[],c=[],l=[],u=!0;for(;u;){u=!1;for(let d of Array.from(i).sort((t,n)=>hl(e,t,n))){let f=X(e,d);if(f.type===`compound`&&!f.children.some(e=>i.has(e))){if(f.initial===void 0)throw Error(`Machine shallow history expected compound state "${d}" to have an initial child`);let p=X(e,f.initial),m={active:i,values:a,outputs:t.outputs,history:t.history,machineReferences:t.machineReferences};if(p.type===`choice`){let t=Td(e,m,oc(p.path,d,Object.fromEntries(a)),n),r=m;for(let i of[t.target,...t.additionalTargets]){if(i===void 0)throw Error(`Machine initial choice "${p.path}" must resolve to an active state target`);let t=ac(i)?Zu(e,r,i,n):rc(i)?Qu(e,r,i,n):void 0;r=Vl(e,r,t?.target??i),t!==void 0&&(o.push(...t.commands),s.push(...t.raisedEvents),c.push(...t.emittedEvents),l.push(...t.transitions))}i.clear(),a.clear();for(let e of r.active)i.add(e);for(let[e,t]of r.values)a.set(e,t);o.push(...t.commands),s.push(...t.raisedEvents),c.push(...t.emittedEvents),l.push(...t.transitions),u=!0;continue}if(i.add(p.path),p.schema!==void 0){let t=Y(e).handlers[d]?.initialize;if(t===void 0){a.set(p.path,Z(e,p,hc({}))),u=!0;continue}let i=Ju(e,t,{...Wu(e,m),state:m.values.get(d),containingState:Sl(e,m,d),ancestors:xl(e,m,d),event:n,...d===``&&r!==void 0?{input:r.value}:{},..._u(t)?{}:{builder:Mu(e,d)}}),l=Nu(d,i.value);a.set(p.path,Z(e,p,l[p.key])),o.push(...i.commands),s.push(...i.raisedEvents),c.push(...i.emittedEvents)}u=!0}if(f.type===`parallel`){let l=f.children.filter(e=>!i.has(e));if(l.length>0){let f=l.filter(t=>X(e,t).schema!==void 0),p={active:i,values:a,outputs:t.outputs,history:t.history,machineReferences:t.machineReferences},m=f.length===0?void 0:Y(e).handlers[d]?.initialize,h=m===void 0?void 0:Ju(e,m,{...Wu(e,p),state:p.values.get(d),containingState:Sl(e,p,d),ancestors:xl(e,p,d),event:n,...d===``&&r!==void 0?{input:r.value}:{},..._u(m)?{}:{builder:Mu(e,d)}}),g=h===void 0?void 0:Nu(d,h.value);for(let t of l){let n=X(e,t);if(i.add(n.path),n.schema!==void 0){if(h===void 0){a.set(n.path,Z(e,n,hc({})));continue}if(g===void 0||!Object.prototype.hasOwnProperty.call(g,n.key)){if(m!==void 0&&_u(m)){a.set(n.path,Z(e,n,hc({})));continue}throw Error(`Machine parallel state initializer for "${d}" must return region "${n.key}"`)}a.set(n.path,Z(e,n,g[n.key]))}}h!==void 0&&(o.push(...h.commands),s.push(...h.raisedEvents),c.push(...h.emittedEvents)),u=!0}}}}return{configuration:{active:i,values:a,outputs:new Map,history:t.history},commands:o,raisedEvents:s,emittedEvents:c,transitions:l}};function Xu(e,t,n,r){let i=zl(e,t,n);if(n.children===void 0||![...n.children.keys()].some(t=>X(e,t).type===`choice`))return Yu(e,i,r,n.input);let a=[],o=[],s=[],c=[];for(let t of n.children?.keys()??[]){let n=X(e,t);if(n.type!==`choice`)continue;let l=Td(e,i,oc(t,n.parent),r);for(let t of[l.target,...l.additionalTargets]){let n=ac(t)?Zu(e,i,t,r):rc(t)?Qu(e,i,t,r):void 0;i=Vl(e,i,n?.target??t),n!==void 0&&(a.push(...n.commands),o.push(...n.raisedEvents),s.push(...n.emittedEvents),c.push(...n.transitions))}a.push(...l.commands),o.push(...l.raisedEvents),s.push(...l.emittedEvents),c.push(...l.transitions)}let l=Yu(e,i,r,n.input);return c.length===0?l:{...l,commands:[...a,...l.commands],raisedEvents:[...o,...l.raisedEvents],emittedEvents:[...s,...l.emittedEvents],transitions:[...c,...l.transitions]}}function Zu(e,t,n,r){let i=Xu(e,t,n,r),a=El(e,i.configuration,n.path);return{target:pc(n.path,a.value,{snapshot:a,values:n.values}),commands:i.commands,raisedEvents:i.raisedEvents,emittedEvents:i.emittedEvents,transitions:i.transitions}}function Qu(e,t,n,r){let i=X(e,n.path);if(i.type!==`history`||i.parent!==n.parent)throw Error(`Machine expected history target "${n.path}" to resolve to its declared parent`);let a=Il(t,n.path);if(a!==void 0){let i=Yu(e,Ll(e,t,a),r),o=El(e,i.configuration,n.parent),s=Object.fromEntries(i.configuration.values);return n.parent!==``&&t.active.has(``)&&delete s[``],{target:pc(n.parent,o.value,{snapshot:o,values:s}),commands:i.commands,raisedEvents:i.raisedEvents,emittedEvents:i.emittedEvents,transitions:i.transitions}}let o=i.key,s=Y(e).handlers[n.parent]?.history?.[o]?.default;if(s===void 0)throw Error(`Machine history state "${n.path}" requires a default implementation`);let c=qu(e,s,{event:r,target:t=>au(e.stateNodes,t),owner:n.parent});if(c.state===void 0||rc(c.state)||!_c(c.state))throw Error(`Machine history default for "${n.path}" must return a complete snapshot containing its owner`);let l=Cd(c.state)===void 0?void 0:Td(e,{active:new Set,values:new Map,outputs:new Map,history:t.history},c.state,r),u=l===void 0?Ml(e,c.state):Vl(e,{active:new Set,values:new Map,outputs:new Map,history:t.history},l.target);for(let t of l?.additionalTargets??[])u=Vl(e,u,t);if(!u.active.has(n.parent))throw Error(`Machine history default for "${n.path}" returned a configuration that does not contain owner state "${n.parent}"`);let d=El(e,u,n.parent),f=Object.fromEntries(u.values);return n.parent!==``&&t.active.has(``)&&delete f[``],{target:pc(n.parent,d.value,{snapshot:d,values:f}),commands:[...c.commands,...l?.commands??[]],raisedEvents:[...c.raisedEvents,...l?.raisedEvents??[]],emittedEvents:[...c.emittedEvents,...l?.emittedEvents??[]],transitions:l?.transitions??[]}}var $u=(e,t)=>{if(!t.transition.declinable)return t;let n=qu(e,t.transition.transition,t.context,t.transition.evaluate);return n.declined?void 0:{...t,collected:n}},ed=(e,t)=>[...Q(e,t)].reverse(),td=(e,t,n)=>{let r=Q(e,t),i=Q(e,n),a,o=Math.min(r.length,i.length);for(let e=0;e<o&&r[e]===i[e];e++)a=r[e];return a},nd=(e,t)=>{if(e!==void 0&&t!==void 0)return e===t||fl(e,t)?t:e},rd=(e,t,n)=>od(e,Array.from(t.active).filter(e=>n===void 0||fl(e,n))),id=(e,t,n)=>sd(e,Array.from(t.active).filter(e=>n===void 0||fl(e,n))),ad=(e,t)=>e.active.size===t.active.size&&Array.from(e.active).every(e=>t.active.has(e)),od=(e,t)=>Array.from(new Set(t)).sort((t,n)=>{let r=Q(e,n).length-Q(e,t).length;return r===0?X(e,n).order-X(e,t).order:r}),sd=(e,t)=>Array.from(new Set(t)).sort((t,n)=>{let r=Q(e,t).length-Q(e,n).length;return r===0?hl(e,t,n):r}),cd=(e,t,n,r)=>({...Wu(e,t),state:t.values.get(n),containingState:Sl(e,t,n),ancestors:xl(e,t,n),event:r}),ld=(e,t,n,r,i)=>({...Wu(e,t),state:t.values.get(n),containingState:Sl(e,t,n),ancestors:xl(e,t,n),event:r,snapshot:i}),ud=(e,t,n,r,i,a)=>({...Wu(e,t),state:t.values.get(n),containingState:Sl(e,t,n),ancestors:xl(e,t,n),event:r,output:i,snapshot:a}),dd=(e,t,n,r,i)=>{let a=[],o=[],s=[];for(let c of n){let n=Ku(e,Y(e).handlers[c]?.[i],cd(e,t,c,r));a.push(...n.commands),o.push(...n.raisedEvents),s.push(...n.emittedEvents)}return{commands:a,emittedEvents:s,raisedEvents:o}},fd=(e,t,n)=>{let r=[],i=new Set,a=new Map,o,s=()=>o??=Tl(e,t);for(let o of _l(e,t))for(let c of ed(e,o)){let l=Gu(Y(e).handlers[c]?.always);if(l!==void 0){let u=a.get(c);if(a.has(c)||(u=$u(e,{sourcePath:c,leafPath:o,trigger:{type:`always`},transition:l,context:{...Wu(e,t),state:t.values.get(c),containingState:Sl(e,t,c),ancestors:xl(e,t,c),event:n,snapshot:s()}}),a.set(c,u)),u===void 0)continue;i.has(c)||(i.add(c),r.push(u));break}}return r},pd=(e,t,n,r)=>{let i=[],a=new Set,o,s=()=>o??=Tl(e,t);for(let o of r){let r=Gu(Y(e).handlers[o.path]?.onDone);if(r!==void 0&&!a.has(o.path)){a.add(o.path);let c=$u(e,{sourcePath:o.path,leafPath:yl(e,t,o.path),trigger:{type:`done`},transition:r,context:ud(e,t,o.path,n,o.output,s())});c!==void 0&&i.push(c)}}return i},md=(e,t,n)=>{let r=[],i=new Set,a=new Map,o,s=()=>o??=Tl(e,t);for(let o of _l(e,t))for(let c of ed(e,o)){let l=Gu(Y(e).handlers[c]?.on?.[n._tag]);if(l!==void 0){let u=a.get(c);if(a.has(c)||(u=$u(e,{sourcePath:c,leafPath:o,trigger:{type:`event`,event:n._tag},transition:l,context:ld(e,t,c,n,s())}),a.set(c,u)),u===void 0)continue;i.has(c)||(i.add(c),r.push(u));break}}return r},hd=(e,t,n)=>{if(!t.active.has(n.path))return[];let r=Y(e).handlers[n.path],i=Eu(r?.invoke).find(e=>{let t=`child`in e?e.child?.id:e.id;return String(t)===n.id});if(i===void 0)return[];let a=Gu(n.type===`element`?i.onElement:n.type===`done`?i.onDone:n.type===`failure`?i.onFailure:i.onSnapshot);if(a===void 0)return[];let o=Tl(e,t),s={...Wu(e,t),state:t.values.get(n.path),containingState:Sl(e,t,n.path),ancestors:xl(e,t,n.path),snapshot:o,id:n.id,...n.type===`element`?{element:n.element}:n.type===`done`?{output:n.output}:n.type===`failure`?{error:n.error}:{snapshot:n.snapshot}},c=$u(e,{sourcePath:n.path,leafPath:yl(e,t,n.path),trigger:{type:`invoke`,id:n.id,outcome:n.type},transition:a,context:s});return c===void 0?[]:[c]},gd=e=>{if(rc(e)||sc(e)||mc(e)||_c(e))return String(e.path);throw Error(`Machine expected transition target to be a snapshot or target builder result`)},_d=(e,t,n,r)=>{if(n===void 0||r===void 0)return;let i=typeof r==`object`&&r&&`path`in r?String(r.path):`<unknown>`;if(!n.some(e=>i===e||e===``||i.startsWith(`${e}.`))){let r=t.type===`event`?String(t.event):t.type;throw Error(`Machine transition from "${e}" on "${r}" returned target "${i}" outside declared targets: ${n.length===0?`none`:n.map(e=>`"${e}"`).join(`, `)}`)}},vd=(e,t)=>{for(let n of e)if(t.includes(n))return!0;return!1},yd=(e,t)=>Array.from(t).sort((t,n)=>hl(e,t.selection.sourcePath,n.selection.sourcePath)),bd=e=>e.filter(t=>!e.some(e=>e.sourcePath!==t.sourcePath&&fl(e.sourcePath,t.sourcePath))),xd=(e,t)=>{let n=[];for(let r of yd(e,t)){let e=!1,t=new Set;for(let i of n){let n=r.update!==void 0&&i.update!==void 0&&r.update.path===i.update.path;if(vd(r.exitPaths,i.exitPaths)||n){if(fl(r.selection.sourcePath,i.selection.sourcePath))t.add(i);else{e=!0;break}}}if(!e){for(let e of t){let t=n.indexOf(e);t>=0&&n.splice(t,1)}n.push(r)}}return n},Sd=(e,t={})=>{let n={...t},r=[],i=e=>{if(sc(e))Object.assign(n,e.values??{}),r.push(e);else if(typeof e==`object`&&e&&`path`in e&&`value`in e&&(e.value!==void 0&&(n[String(e.path)]=e.value),`state`in e&&i(e.state),`states`in e&&typeof e.states==`object`&&e.states!==null))for(let t of Object.values(e.states))i(t)};return i(e),r.map(e=>({target:oc(e.path,e.parent,n),values:n}))},Cd=(e,t={})=>Sd(e,t)[0],wd=(e,t)=>{if(sc(e))return oc(e.path,e.parent,{...t,...e.values??{}});if(ac(e))return{...e,values:{...t,...e.values}};if(!mc(e)||Object.keys(t).length===0)return e;let n=e[As];return pc(e.path,e.value,{...n===void 0?{}:{snapshot:n},values:{...t,...e.values??{}}})};function Td(e,t,n,r){let i=[n],a=[],o=[],s=[],c=[],l=[],u=0;for(;i.length>0;){let n=i.shift();for(;;){let a=Sd(n),d=a[0];if(d===void 0)break;if(i.unshift(...a.slice(1).map(({target:e})=>e)),u+=1,u>1e3)throw new Ss({machineId:e.id,state:d.target.path,maxIterations:Dd});let f=X(e,d.target.path);if(f.type!==`choice`||f.parent!==d.target.parent)throw Error(`Machine expected choice target "${d.target.path}" to resolve to its declared parent`);let p=Y(e).handlers[f.path]?.choice;if(p===void 0||typeof p.transition!=`function`)throw Error(`Machine choice state "${f.path}" requires an implementation`);let m=new Map(t.values);for(let[t,n]of Object.entries(d.values)){let r=X(e,t);r.schema!==void 0&&m.set(t,Z(e,r,n))}let h={active:new Set([...t.active,...Object.keys(d.values)]),values:m,outputs:t.outputs,history:t.history,...t.machineReferences===void 0?{}:{machineReferences:t.machineReferences}},g=qu(e,p.transition,{...Wu(e,h),containingState:Sl(e,h,f.path),ancestors:xl(e,h,f.path),event:r},p.evaluate);if(g.state===void 0)throw Error(`Machine choice resolver for "${f.path}" must return a target`);_d(f.path,{type:`choice`},p.targets,g.state);let _=gd(g.state);n=wd(g.state,d.values);let v=Cd(n);l.push({source:f.path,trigger:{type:`choice`},reenter:!1,branchIndex:g.branchIndex,branchKey:g.branchKey,target:_,resolvedTarget:v?.target.path??_,updates:[]}),o.push(...g.commands),s.push(...g.raisedEvents),c.push(...g.emittedEvents)}if(!mc(n)&&!_c(n)&&!rc(n)&&!ac(n))throw Error(`Machine choice resolver must return a concrete typed target`);a.push(n)}return{target:a[0],additionalTargets:a.slice(1),commands:o,raisedEvents:s,emittedEvents:c,transitions:l}}var Ed=(e,t,n)=>{let r=n.leafPath,i=n.collected??qu(e,n.transition.transition,n.context,n.transition.evaluate);if(i.declined)throw Error(`Machine transition returned decline without declaring declinable: true`);let a=qs(i.state)?i.state:void 0,o=a?.target??i.state,s=o===void 0||Gs(o)?void 0:o;_d(n.sourcePath,n.trigger,n.transition.targets,s);let c=a?.update??(Gs(o)?o:void 0),l=c===void 0?void 0:(()=>{let n=X(e,c.path);if(!t.active.has(n.path)||n.schema===void 0)throw Error(`Machine state update owner "${n.path}" must be an active valued state`);return{path:n.path,value:Z(e,n,c.value)}})(),u=l!==void 0&&(ac(s)||sc(s))?{...t,values:new Map(t.values).set(l.path,l.value)}:t,d=s===void 0?void 0:Td(e,u,s,n.context.event),f=d?.target??s,p=f!==void 0&&ac(f)?Zu(e,u,f,n.context.event):void 0,m=p?.target??f,h,g=rc(m)&&n.transition.reenter&&t.active.has(m.parent)?m:void 0;if(m!==void 0&&rc(m)){let i=n.transition.reenter?X(e,n.sourcePath).parent:td(e,r,m.parent),a=g===void 0?rd(e,t,i):od(e,Array.from(t.active).filter(e=>pl(e,m.parent)));h=Qu(e,a.includes(m.parent)?Fl(e,t,t,a):t,m,n.context.event)}let _=h===void 0?m:h.target,v=[],y=[],b=[],ee=[],te=[];for(let r of d?.additionalTargets??[]){if(ac(r)){let i=Zu(e,t,r,n.context.event);te.push(i.target),v.push(...i.commands),y.push(...i.raisedEvents),b.push(...i.emittedEvents),ee.push(...i.transitions);continue}if(!rc(r)){te.push(r);continue}let i=Qu(e,t,r,n.context.event);te.push(i.target),v.push(...i.commands),y.push(...i.raisedEvents),b.push(...i.emittedEvents),ee.push(...i.transitions)}let x=_===void 0?void 0:te.length===0||s===void 0?gd(_):gd(s),S=_===void 0?l===void 0?t:{...t,values:new Map(t.values).set(l.path,l.value)}:Vl(e,t,_);for(let t of te)S=Vl(e,S,t);if(a!==void 0&&l!==void 0&&!S.active.has(l.path))throw Error(`Machine combined target exited its updating owner "${l.path}"`);l!==void 0&&(S={...S,values:new Map(S.values).set(l.path,l.value)});let ne=n.transition.reenter||!ad(t,S),re=ne||l!==void 0;if(!ne)return{selection:n,branchIndex:i.branchIndex,branchKey:i.branchKey,unresolvedTarget:s,target:_,update:l,commands:[...i.commands,...d?.commands??[],...p?.commands??[],...h?.commands??[],...v],raisedEvents:[...i.raisedEvents,...d?.raisedEvents??[],...p?.raisedEvents??[],...h?.raisedEvents??[],...y],emittedEvents:[...i.emittedEvents,...d?.emittedEvents??[],...p?.emittedEvents??[],...h?.emittedEvents??[],...b],changed:ne,stabilize:re,exitPaths:[],entryPaths:[],choiceTransitions:[...d?.transitions??[],...p?.transitions??[],...h?.transitions??[],...ee]};let ie=x===void 0?X(e,n.sourcePath).parent:td(e,r,x),C=X(e,n.sourcePath).parent,ae=n.transition.reenter?nd(ie,C):ie;return{selection:n,branchIndex:i.branchIndex,branchKey:i.branchKey,unresolvedTarget:s,target:_,update:l,commands:[...i.commands,...d?.commands??[],...p?.commands??[],...h?.commands??[],...v],raisedEvents:[...i.raisedEvents,...d?.raisedEvents??[],...p?.raisedEvents??[],...h?.raisedEvents??[],...y],emittedEvents:[...i.emittedEvents,...d?.emittedEvents??[],...p?.emittedEvents??[],...h?.emittedEvents??[],...b],changed:ne,stabilize:re,exitPaths:g===void 0?rd(e,t,ae):od(e,Array.from(t.active).filter(e=>pl(e,g.parent))),entryPaths:g===void 0?id(e,S,ae):sd(e,Array.from(S.active).filter(e=>pl(e,g.parent))),choiceTransitions:[...d?.transitions??[],...p?.transitions??[],...h?.transitions??[],...ee]}},Dd=1e3,Od={_tag:pu},kd=(e,t)=>ql(e,jl(e,t)),Ad=(e,t,n)=>Pl(e,t).pipe(P(t=>Zl(e,t,n)),P(t=>{let n=bl(e,t.configuration);return!ql(e,t.configuration)||!t.configuration.outputs.has(n)?gn(Error(`Machine attempted to read terminal output from a non-terminal configuration`)):A(t.configuration.outputs.get(n))})),jd=(e,...t)=>{let n=e.input===void 0?t:t.length===0?(el(e,e.input,void 0),t):[el(e,e.input,t[0])],r=e.initial(...n),i={active:new Set,values:new Map,outputs:new Map,history:new Map},a=Zu(e,i,r,Od),o=Vl(e,i,a.target),s=Tl(e,o),c=Cl(e,o),l=a.commands,u=a.raisedEvents,d=a.emittedEvents,f=dd(e,o,c,Od,`entry`),p=Nd(e,o,Od,[...f.commands],[...u,...f.raisedEvents],[...d,...f.emittedEvents],a.transitions.length===0?[]:[{next:o,event:Od,transitions:a.transitions,commands:l,raisedEvents:[...u],emittedEvents:d,exitPaths:[],entryPaths:[],changed:!1,stabilize:!1}]),m={startingState:s,initialEntryPaths:c,state:Tl(e,p.next),commands:[...l,...p.commands],emittedEvents:p.emittedEvents,microsteps:p.microsteps.map(t=>({next:Tl(e,t.next),event:t.event,transitions:t.transitions,commands:t.commands,raisedEvents:t.raisedEvents,emittedEvents:t.emittedEvents,exitPaths:t.exitPaths,entryPaths:t.entryPaths,changed:t.changed}))};return p.done?{...m,done:!0,output:p.output}:{...m,done:!1,output:void 0}},Md=(e,t,n,r)=>{if(r.length===0)return{next:t,event:n,transitions:[],commands:[],raisedEvents:[],emittedEvents:[],exitPaths:[],entryPaths:[],changed:!1,stabilize:!1};let i=bd(r),a=[];for(let n of i)a.push(Ed(e,t,n));let o=xd(e,a),s=yd(e,o),c=s.flatMap(e=>[{source:e.selection.sourcePath,trigger:e.selection.trigger,reenter:e.selection.transition.reenter,branchIndex:e.branchIndex,branchKey:e.branchKey,target:e.unresolvedTarget===void 0?void 0:gd(e.unresolvedTarget),resolvedTarget:e.target===void 0?void 0:gd(e.target),updates:e.update===void 0?[]:[e.update.path]},...e.choiceTransitions]),l=t;for(let e of s)e.update!==void 0&&(l={...l,values:new Map(l.values).set(e.update.path,e.update.value)});let u=[...s.filter(e=>!e.changed),...s.filter(e=>e.changed)];for(let t of u)t.target!==void 0&&(l=Vl(e,l,t.target));let d=o.some(e=>e.changed),f=o.some(e=>e.stabilize),p=s.flatMap(e=>e.commands),m=s.flatMap(e=>e.raisedEvents),h=s.flatMap(e=>e.emittedEvents);if(!d)return{next:l,event:n,transitions:c,commands:p,raisedEvents:m,emittedEvents:h,exitPaths:[],entryPaths:[],changed:!1,stabilize:f};let g=od(e,s.flatMap(e=>e.exitPaths)),_=sd(e,s.flatMap(e=>e.entryPaths));l=Fl(e,t,l,g);let v=dd(e,t,g,n,`exit`),y=dd(e,l,_,n,`entry`);return{next:l,event:n,transitions:c,commands:[...v.commands,...p,...y.commands],raisedEvents:[...v.raisedEvents,...m,...y.raisedEvents],emittedEvents:[...v.emittedEvents,...h,...y.emittedEvents],exitPaths:g,entryPaths:_,changed:!0,stabilize:f}},Nd=(e,t,n,r,i,a,o)=>{let s=t,c=n,l=!0,u=0,d=0,f=!1,p,m=[];for(;;){if(u+=1,u>1e3)throw new Ss({machineId:e.id,state:String(vl(e,s)),maxIterations:Dd});let t=eu(e,s,c);for(s=t.configuration,m.push(...t.completions.filter(t=>Y(e).handlers[t.path]?.onDone!==void 0));m.length>0&&!s.active.has(m[0].path);)m.shift();let n=pd(e,s,c,m.length===0?[]:[m.shift()]);if(n.length>0){let t=Md(e,s,c,n);r.push(...t.commands),i.push(...t.raisedEvents),a.push(...t.emittedEvents),o.push(t),s=t.next,l=t.stabilize;continue}if(ql(e,s)){let t=bl(e,s);if(!s.outputs.has(t))throw Error(`Machine reached a terminal configuration without a completed root output`);f=!0,p=s.outputs.get(t);break}let h=l?fd(e,s,c):[];if(h.length>0){let t=Md(e,s,c,h);r.push(...t.commands),i.push(...t.raisedEvents),a.push(...t.emittedEvents),o.push(t),s=t.next,l=t.stabilize;continue}let g=i[d];if(g===void 0)break;d+=1;let _=g;c=_;let v=md(e,s,_);if(v.length===0){l=!0;continue}let y=Md(e,s,_,v);r.push(...y.commands),i.push(...y.raisedEvents),a.push(...y.emittedEvents),o.push(y),s=y.next,l=!0}let h={next:s,commands:r,emittedEvents:a,microsteps:o};return f?{...h,done:!0,output:p}:{...h,done:!1,output:void 0}},Pd=(e,t,n)=>{let r=zu(n)?n:Zc(e,n);if(ql(e,t)){let n=eu(e,t,r),i=bl(e,n.configuration);if(!n.configuration.outputs.has(i))throw Error(`Machine reached a terminal configuration without a completed root output`);return{event:r,next:n.configuration,commands:[],emittedEvents:[],microsteps:[],done:!0,output:n.configuration.outputs.get(i)}}let i=zu(r)?hd(e,t,r):md(e,t,r);if(i.length===0)return{event:r,next:t,commands:[],emittedEvents:[],microsteps:[],done:!1,output:void 0};let a=Md(e,t,r,i),o=[...a.commands],s=[...a.raisedEvents],c=[...a.emittedEvents],l=[a];return{...Nd(e,a.next,r,o,s,c,l),event:r}},Fd=(e,...t)=>Rr({try:()=>jd(e,...t),catch:Os}),Id=(e,t)=>({raise:n=>Xc(e,n).pipe(P(e=>t.sendTo(t.self,e))),emit:n=>Qc(e,n).pipe(P(e=>t.emit(e)))}),Ld=(e,t)=>jn(e,e=>e._tag===`SendTo`?t.sendTo(e.target,e.event):t.stopChild(e.child),{discard:!0}),Rd=(e,t)=>gt(Array.from(e,e=>t.emit(e)),{discard:!0}),zd=new WeakMap,Bd=e=>{let t=zd.get(e);if(t!==void 0)return t;let n={self:{id:e.id??`Machine`,sessionId:`Machine.plan`,send:()=>V(new Ts)},parent:void 0};return zd.set(e,n),n},Vd=(e,t)=>{let n=t===void 0?Bd(e):t;return e.parent===void 0?{self:n.self}:{self:n.self,parent:n.parent}},Hd=new Set([`initialize`,`invoke`,`on`,`output`]),Ud=e=>{if(e===void 0)return!0;for(let t of Reflect.ownKeys(e))if(!Hd.has(t))return!1;return!0},Wd=e=>{let t=[],n=[],r=[],i=new Map;for(let a of e.stateNodes.byPath.values()){if(t.push(a),a.type===`choice`||a.type===`history`)return;(a.type===`atomic`||a.type===`final`)&&n.push(a.path),a.type===`final`&&r.push(a.path);let o=Y(e).handlers[a.path];if(!Ud(o))return;if(o?.on===void 0)continue;let s=new Map;for(let e of Reflect.ownKeys(o.on)){let t=Gu(o.on[e]);if(t!==void 0){if(t.declinable)return;s.set(e,t)}}s.size>0&&i.set(a.path,s)}n.sort((t,n)=>hl(e,t,n)),r.sort((t,n)=>hl(e,t,n)),t.sort((e,t)=>e.order-t.order);let a=new Map(t.map((e,t)=>[e.path,t])),o=e=>{let t=a.get(e);if(t===void 0)throw Error(`Machine expected compiled state path "${e}"`);return t},s=n.map(o),c=t.map(e=>e.parent===void 0?-1:o(e.parent)),l=t.map(e=>e.children.map(o)),u=t.map(t=>Q(e,t.path).slice(0,-1).map(o)),d=t.map(e=>i.get(e.path)),f=new Map;for(let e of s){let t=new Map,n=[e,...u[e].slice().reverse()];for(let e of n)for(let[n,r]of d[e]??[])t.has(n)||t.set(n,{sourceIndex:e,transition:r});f.set(e,t)}return{valued:Object.freeze(t.map(e=>e.schema!==void 0)),flat:t.every(e=>e.parent===void 0&&(e.type===`atomic`||e.type===`final`))||t[0]?.path===``&&t[0].type===`compound`&&t[0].schema===void 0&&(Y(e).handlers[``]===void 0||Reflect.ownKeys(Y(e).handlers[``]).every(e=>e===`initialize`))&&t.slice(1).every(e=>e.parent===``&&(e.type===`atomic`||e.type===`final`))&&[...i.values()].every(e=>[...e.values()].every(e=>e.targets!==void 0&&e.targets.every(e=>e!==``))),nodes:t,indexByPath:a,parentIndices:c,childIndices:l,ancestorIndices:u,rootIndices:t.flatMap((e,t)=>e.parent===void 0?[t]:[]),leafIndices:s,finalIndices:r.map(o),dispatchByLeaf:f}},Gd=e=>({active:e.active.slice(),activeLeaves:e.activeLeaves.slice(),values:e.values.slice(),completed:e.completed.slice(),outputs:e.outputs.slice(),completedOrder:e.completedOrder.slice()}),Kd=(e,t)=>t?{...e,next:Gd(e.next)}:e,qd=(e,t,n)=>{e.values[t]=n},Jd=(e,t)=>{let n=new Uint8Array(e.nodes.length),r=Array(e.nodes.length),i=new Uint8Array(e.nodes.length),a=Array(e.nodes.length),o=[];for(let i of t.active){let a=e.indexByPath.get(i);if(a===void 0)throw Error(`Machine expected indexed active path "${i}"`);n[a]=1,e.valued[a]&&(r[a]=t.values.get(i))}for(let[n,r]of t.outputs){let t=e.indexByPath.get(n);if(t===void 0)throw Error(`Machine expected indexed completed path "${n}"`);i[t]=1,a[t]=r,o.push(t)}return{active:n,activeLeaves:e.leafIndices.filter(e=>n[e]===1),values:r,completed:i,outputs:a,completedOrder:o}},Yd=(e,t)=>{let n=new Set,r=new Map,i=new Map;for(let i=0;i<e.nodes.length;i++){if(t.active[i]!==1)continue;let a=e.nodes[i].path;n.add(a),e.valued[i]&&r.set(a,t.values[i])}for(let n of t.completedOrder)t.completed[n]===1&&i.set(e.nodes[n].path,t.outputs[n]);return{active:n,values:r,outputs:i,history:new Map}},Xd=(e,t,n)=>{let r=e.nodes[n],i={path:r.path,value:e.valued[n]?t.values[n]:void 0};if(r.type===`compound`){let a=e.childIndices[n].find(e=>t.active[e]===1);if(a===void 0)throw Error(`Machine expected indexed compound state "${r.path}" to have an active child`);i.state=Xd(e,t,a)}else if(r.type===`parallel`){let a={};for(let i of e.childIndices[n]){if(t.active[i]!==1)throw Error(`Machine expected indexed parallel state "${r.path}" to have active region "${e.nodes[i].path}"`);a[e.nodes[i].key]=Xd(e,t,i)}i.states=a}return i},Zd=(e,t)=>{let n=e.rootIndices.find(e=>t.active[e]===1);if(n===void 0)throw Error(`Machine expected an active indexed root state`);let r=Xd(e,t,n);return t.completedOrder.length>0&&(r.completed=t.completedOrder.map(n=>({path:e.nodes[n].path,output:t.outputs[n]}))),r},Qd=(e,t,n,r,i,a)=>{let o=t.parentIndices[r],s={};for(let e of t.ancestorIndices[r])t.valued[e]&&(s[t.nodes[e].path]=n.values[e]);return{...Vd(e,a),state:n.values[r],containingState:o<0?void 0:n.values[o],ancestors:s,event:i,snapshot:Zd(t,n)}},$d=Object.freeze([]),ef=(e,t,n,r)=>{let i,a,o,s={raise:t=>{(a??=[]).push(Zc(e,t))},emit:t=>{(o??=[]).push($c(e,t))},sendTo:(e,t)=>{(i??=[]).push({_tag:`SendTo`,target:e,event:t})},stop:e=>{(i??=[]).push({_tag:`Stop`,child:e})}},c=r===void 0?{result:t(n,s),branchIndex:0,branchKey:void 0}:r(n,s);return{state:Qs(c.result)?void 0:c.result,branchIndex:c.branchIndex,branchKey:c.branchKey,commands:i??$d,raisedEvents:a??$d,emittedEvents:o??$d}},tf=(e,t,n,r,i)=>{let a=[];for(let o of n.activeLeaves){let s=t.dispatchByLeaf.get(o).get(r._tag);if(s!==void 0){let{sourceIndex:c,transition:l}=s;if(!a.some(e=>e.sourceIndex===c)){let s=t.nodes[c].path;a.push({sourceIndex:c,leafIndex:o,sourcePath:s,leafPath:t.nodes[o].path,trigger:{type:`event`,event:r._tag},transition:l,context:Qd(e,t,n,c,r,i)})}}}return a},nf=(e,t)=>{if(e.active===t.active)return!0;for(let n=0;n<e.active.length;n++)if(e.active[n]!==t.active[n])return!1;return!0},rf=(e,t,n,r,i)=>{if((mc(r)?t.indexByPath.get(String(r.path)):void 0)===i&&n.active[i]===1&&mc(r)&&r[As]===void 0&&r.values===void 0&&n.completedOrder.length===0&&t.valued[i]){let a=n.values.slice();return a[i]=Z(e,t.nodes[i],r.value),{...n,values:a}}return Jd(t,Vl(e,Yd(t,n),r))},af=(e,t,n,r)=>{let i=ef(e,r.transition.transition,r.context,r.transition.evaluate),a=qs(i.state)?i.state:void 0,o=a?.target??i.state,s=a?.update??(Gs(o)?o:void 0),c=s===void 0?void 0:(()=>{let r=t.indexByPath.get(s.path),i=r===void 0?void 0:t.nodes[r];if(r===void 0||i===void 0||n.active[r]!==1||i.schema===void 0)throw Error(`Machine state update owner "${s.path}" must be an active valued state`);return{path:i.path,value:Z(e,i,s.value)}})(),l=o===void 0||Gs(o)?void 0:o;_d(r.sourcePath,r.trigger,r.transition.targets,l);let u=l!==void 0&&ac(l)?Zu(e,(()=>{let e=Yd(t,n);return c===void 0?e:{...e,values:new Map(e.values).set(c.path,c.value)}})(),l,r.context.event):void 0,d=u?.target??l;if(d!==void 0&&!mc(d)&&!_c(d))throw Error(`Machine expected indexed transition target to be a snapshot or target builder result`);let f=d===void 0?c===void 0?n:(()=>{let e=Gd(n);return e.values[t.indexByPath.get(c.path)]=c.value,e})():rf(e,t,n,d,r.leafIndex);if(a!==void 0&&c!==void 0){let e=t.indexByPath.get(c.path);if(f.active[e]!==1)throw Error(`Machine combined target exited its updating owner "${c.path}"`);let n=f.values.slice();n[e]=c.value,f={...f,values:n}}let p=r.transition.reenter||!nf(n,f),m=p||c!==void 0;if(!p)return{selection:r,branchIndex:i.branchIndex,branchKey:i.branchKey,unresolvedTarget:l,target:d,update:c,next:f,commands:[...i.commands,...u?.commands??[]],raisedEvents:[...i.raisedEvents,...u?.raisedEvents??[]],emittedEvents:[...i.emittedEvents,...u?.emittedEvents??[]],changed:!1,stabilize:m,exitPaths:[],entryPaths:[],choiceTransitions:u?.transitions??[]};let h=d===void 0?void 0:gd(d),g=h===void 0?t.nodes[r.sourceIndex].parent:td(e,r.leafPath,h),_=t.nodes[r.sourceIndex].parent,v=r.transition.reenter?nd(g,_):g;return{selection:r,branchIndex:i.branchIndex,branchKey:i.branchKey,unresolvedTarget:l,target:d,update:c,next:f,commands:[...i.commands,...u?.commands??[]],raisedEvents:[...i.raisedEvents,...u?.raisedEvents??[]],emittedEvents:[...i.emittedEvents,...u?.emittedEvents??[]],changed:!0,stabilize:m,exitPaths:rd(e,Yd(t,n),v),entryPaths:id(e,Yd(t,f),v),choiceTransitions:u?.transitions??[]}},of=(e,t,n,r,i,a)=>{let o=e=>({source:e.selection.sourcePath,trigger:e.selection.trigger,reenter:e.selection.transition.reenter,branchIndex:e.branchIndex,branchKey:e.branchKey,target:e.unresolvedTarget===void 0?void 0:gd(e.unresolvedTarget),resolvedTarget:e.target===void 0?void 0:gd(e.target),updates:e.update===void 0?[]:[e.update.path]});if(i.length===1){let s=af(e,t,n,i[0]);return{next:s.next,event:r,...a?{transitions:[o(s)]}:void 0,commands:s.commands,raisedEvents:s.raisedEvents,emittedEvents:s.emittedEvents,exitPaths:s.exitPaths,entryPaths:s.entryPaths,changed:s.changed}}let s=yd(e,xd(e,i.filter(e=>!i.some(t=>t.sourceIndex!==e.sourceIndex&&fl(t.sourcePath,e.sourcePath))).map(r=>af(e,t,n,r)))),c=n;if(s.length===1)c=s[0].next;else{for(let e of s)if(e.update!==void 0){let n=c.values.slice();n[t.indexByPath.get(e.update.path)]=e.update.value,c={...c,values:n}}let n=[...s.filter(e=>!e.changed),...s.filter(e=>e.changed)];for(let r of n)r.target!==void 0&&(c=rf(e,t,c,r.target,r.selection.leafIndex))}let l=s.flatMap(e=>e.commands),u=s.flatMap(e=>e.raisedEvents),d=s.flatMap(e=>e.emittedEvents),f=s.some(e=>e.changed);return{next:c,event:r,...a?{transitions:s.map(o)}:void 0,commands:l,raisedEvents:u,emittedEvents:d,exitPaths:f?od(e,s.flatMap(e=>e.exitPaths)):[],entryPaths:f?sd(e,s.flatMap(e=>e.entryPaths)):[],changed:f}},sf=(e,t,n,r,i,a)=>{let o=n,s=r,c,l,u,d,f=0,p=0;for(;;){if(p+=1,p>1e3)throw new Ss({machineId:e.id,state:t.nodes[o.activeLeaves[0]].path,maxIterations:Dd});let n=o.activeLeaves[0];if(n===void 0)throw Error(`Machine expected an active indexed root state`);if(t.nodes[n].type===`final`){let n=eu(e,Yd(t,o),s).configuration,i=bl(e,n);if(!n.outputs.has(i))throw Error(`Machine reached a terminal indexed configuration without a completed root output`);return{event:r,next:Jd(t,n),commands:c??$d,emittedEvents:u??$d,microsteps:d??$d,done:!0,output:n.outputs.get(i)}}let m=t.nodes[n].path,h=Gu(Y(e).handlers[m]?.on?.[s._tag]);if(h!==void 0){let r=ef(e,h.transition,{...Vd(e,a),state:o.values[n],containingState:void 0,ancestors:{},event:s,snapshot:Zd(t,o)},h.evaluate),f=Gs(r.state)?r.state:void 0,p=f===void 0?r.state:void 0;if(f!==void 0){let r=t.nodes[n];if(f.path!==m||r.schema===void 0)throw Error(`Machine state update owner "${f.path}" must be the active valued state`);qd(o,n,Z(e,r,f.value))}if(_d(m,{type:`event`,event:s._tag},h.targets,p),p!==void 0&&!mc(p)&&!_c(p))throw Error(`Machine expected indexed transition target to be a snapshot or target builder result`);let g=o;if(p!==void 0){let r=t.indexByPath.get(String(p.path)),i=mc(p)?p[As]===void 0&&p.values===void 0:!(`state`in p)&&!(`states`in p)&&!(`completed`in p)&&!(`history`in p);r===n&&i&&o.completedOrder.length===0&&t.valued[n]?qd(o,n,Z(e,t.nodes[n],p.value)):g=rf(e,t,o,p,n)}let _=h.reenter||!nf(o,g),v=g.activeLeaves[0];if(v===void 0)throw Error(`Machine expected an active indexed transition target`);let y={next:g,event:s,...i?{transitions:[{source:m,trigger:{type:`event`,event:s._tag},reenter:h.reenter,branchIndex:r.branchIndex,branchKey:r.branchKey,target:p===void 0?void 0:gd(p),resolvedTarget:p===void 0?void 0:gd(p),updates:f===void 0?[]:[f.path]}]}:void 0,commands:r.commands,raisedEvents:r.raisedEvents,emittedEvents:r.emittedEvents,exitPaths:_?[m]:$d,entryPaths:_?[t.nodes[v].path]:$d,changed:_};o=g,(d??=[]).push(Kd(y,i)),r.commands.length>0&&(c??=[]).push(...r.commands),r.raisedEvents.length>0&&(l??=[]).push(...r.raisedEvents),r.emittedEvents.length>0&&(u??=[]).push(...r.emittedEvents)}if(t.nodes[o.activeLeaves[0]].type===`final`)continue;let g=l?.[f];if(g===void 0)return{event:r,next:o,commands:c??$d,emittedEvents:u??$d,microsteps:d??$d,done:!1,output:void 0};f+=1,s=g}},cf=(e,t,n,r,i,a)=>{if(zu(r)){let i=Pd(e,a===void 0?Yd(t,n):cl(Yd(t,n),a),r);return{event:i.event,next:Jd(t,i.next),commands:i.commands,emittedEvents:i.emittedEvents,microsteps:i.microsteps.map(e=>({next:Jd(t,e.next),event:e.event,transitions:e.transitions,commands:e.commands,raisedEvents:e.raisedEvents,emittedEvents:e.emittedEvents,exitPaths:e.exitPaths,entryPaths:e.entryPaths,changed:e.changed})),done:i.done,output:i.output}}let o=Zc(e,r);if(t.flat)return sf(e,t,n,o,i,a);if(t.finalIndices.some(e=>n.active[e]===1)){let r=Yd(t,n);if(ql(e,r)){let n=eu(e,r,o).configuration,i=bl(e,n);if(!n.outputs.has(i))throw Error(`Machine reached a terminal indexed configuration without a completed root output`);return{event:o,next:Jd(t,n),commands:[],emittedEvents:[],microsteps:[],done:!0,output:n.outputs.get(i)}}}let s=tf(e,t,n,o,a);if(s.length===0)return{event:o,next:n,commands:[],emittedEvents:[],microsteps:[],done:!1,output:void 0};let c=of(e,t,n,o,s,i),l=c.next,u=o,d=[...c.commands],f=[...c.raisedEvents],p=[...c.emittedEvents],m=[Kd(c,i)],h=0,g=0;for(;;){if(g+=1,g>1e3)throw new Ss({machineId:e.id,state:t.nodes[t.leafIndices.find(e=>l.active[e]===1)].path,maxIterations:Dd});if(t.finalIndices.some(e=>l.active[e]===1)){let n=eu(e,Yd(t,l),u).configuration;if(l=Jd(t,n),ql(e,n)){let t=bl(e,n);if(!n.outputs.has(t))throw Error(`Machine reached a terminal indexed configuration without a completed root output`);return{event:o,next:l,commands:d,emittedEvents:p,microsteps:m,done:!0,output:n.outputs.get(t)}}}let n=f[h];if(n===void 0)return{event:o,next:l,commands:d,emittedEvents:p,microsteps:m,done:!1,output:void 0};h+=1,u=n;let r=tf(e,t,l,n,a);if(r.length===0)continue;let s=of(e,t,l,n,r,i);l=s.next,d.push(...s.commands),f.push(...s.raisedEvents),p.push(...s.emittedEvents),m.push(Kd(s,i))}},lf=new WeakMap,uf=e=>({fromConfiguration:e=>e,toConfiguration:e=>e,snapshot:t=>Tl(e,t),plan:(t,n,r,i)=>Pd(e,i===void 0?t:cl(t,i),n)}),df=(e,t)=>({fromConfiguration:e=>Jd(t,e),toConfiguration:e=>Yd(t,e),snapshot:e=>Zd(t,e),plan:(n,r,i=!1,a)=>cf(e,t,n,r,i,a),...Object.values(Y(e).handlers).some(e=>e.initialize!==void 0&&!_u(e.initialize))?{}:{initial:(n,r)=>{let i=e.input===void 0?n:n.length===0?(el(e,e.input,void 0),n):[el(e,e.input,n[0])],a=e.initial(...i),o=ac(a)?Xu(e,{active:new Set,values:new Map,outputs:new Map,history:new Map,...r===void 0?{}:{machineReferences:r}},a,Od).configuration:Ml(e,a),s=eu(e,r===void 0?o:cl(o,r),Od).configuration,c=Jd(t,s),l=Zd(t,c);if(!ql(e,s))return{state:l,configuration:c,activeConfiguration:s,initialEntryPaths:Cl(e,s),done:!1,output:void 0};let u=bl(e,s);if(!s.outputs.has(u))throw Error(`Machine reached a terminal configuration without a completed root output`);return{state:l,configuration:c,activeConfiguration:s,initialEntryPaths:Cl(e,s),done:!0,output:s.outputs.get(u)}}}}),ff=e=>{let t=lf.get(e);if(t!==void 0)return t;let n=Wd(e),r=n===void 0?uf(e):df(e,n);return lf.set(e,r),r},pf=`Machine.invocation:`,mf=e=>e.startsWith(pf),hf=(e,t)=>{if(e.values===void 0?e.values=[t]:e.values.push(t),e.waiter!==void 0){let t=e.waiter;e.waiter=void 0,Ki(t,D)}},gf=e=>C(()=>{if(e.values!==void 0){let t=e.values;return e.values=void 0,A(t)}let t=Ut();return e.waiter=t,gr(t).pipe(k(gf(e)))}),_f=(e,t)=>e._tag===`Started`&&(typeof t==`string`||e.descriptor!==void 0&&e.descriptor.id===t.id&&e.descriptor.machine===t.machine),vf=(e,t,n)=>{if(e.closed)return M();let r=e.children.get(t);return r!==void 0&&_f(r,n)?j(r.ref):M()},yf=e=>{if(e.observers!==void 0)for(let t of e.observers)hf(t,vf(e,t.id,t.child))},bf=(e,t,n)=>{let r=e.children.get(t);r!==void 0&&r.token===n&&(e.children.delete(t),typeof t==`string`&&yf(e))},xf=(e,t,n,r,i)=>{let a=e.children.get(t);if(e.closed||a===void 0||a._tag!==`Starting`||a.token!==n)return!1;e.children.delete(t);let o=a.ownerKey===void 0?{_tag:`Started`,token:n,descriptor:i,ref:r}:{_tag:`Started`,token:n,descriptor:i,ref:r,ownerKey:a.ownerKey,ownerPath:a.ownerPath,ownerActive:a.ownerActive===!0};return e.children.set(t,o),typeof t==`string`&&yf(e),!0},Sf=e=>Ii(function*(){let t=yield*et(),n=0,r=0,i=0,a=0;return{rootSessionId:e,stream:ta(t).pipe(v(H(()=>{n+=1})),da(H(()=>{--n}))),isActive:()=>n>0,nextDeliveryId:()=>i++,nextMacrostepId:()=>a++,publishUnsafe:i=>{n!==0&&Ie(t,{...i,sequence:r++,rootSessionId:e})},close:an(t)}}),Cf=e=>({id:e.id,sessionId:e.sessionId}),wf=e=>e.flatMap(e=>{if(typeof e!=`object`||!e||!(`_tag`in e))return[];if(e._tag===`SendTo`&&`target`in e&&`event`in e){let t=e.target;return typeof t==`object`&&t&&`id`in t?[{_tag:`SendTo`,target:`sessionId`in t?Cf(t):{id:String(t.id)},event:e.event}]:[]}if(e._tag===`Stop`&&`child`in e){let t=e.child;return typeof t==`string`?[{_tag:`Stop`,target:{id:t}}]:typeof t==`object`&&t&&`id`in t?[{_tag:`Stop`,target:`sessionId`in t?Cf(t):{id:String(t.id)}}]:[]}return[]}),Tf=e=>typeof e!=`object`||!e||!(`microsteps`in e)||!Array.isArray(e.microsteps)?[]:e.microsteps.map(e=>({event:e.event,transitions:Array.isArray(e.transitions)?e.transitions:[],raisedEvents:Array.isArray(e.raisedEvents)?e.raisedEvents:[],emittedEvents:Array.isArray(e.emittedEvents)?e.emittedEvents:[],commands:wf(Array.isArray(e.commands)?e.commands:[]),exitPaths:Array.isArray(e.exitPaths)?e.exitPaths:[],entryPaths:Array.isArray(e.entryPaths)?e.entryPaths:[],changed:e.changed===!0})),Ef=Symbol.for(`effect/Machine/activeSnapshotObserver`),Df=Symbol.for(`effect/Machine/snapshotObserver`),Of=e=>typeof e==`object`&&!!e&&Df in e,kf=Symbol.for(`effect/Machine/sendParentOverride`),Af=Symbol.for(`effect/Machine/acknowledgedSend`),jf=Symbol(`effect/Machine/AcknowledgedMessage`),Mf=e=>typeof e==`object`&&!!e&&jf in e,Nf=e=>Mf(e)?e.event:e,Pf=(e,t)=>{e!==void 0&&Mf(e)&&(e.deferred!==void 0&&Ki(e.deferred,A(t)),e.inspection?.complete(t))},Ff=(e,t)=>{e!==void 0&&Mf(e)&&e.deferred!==void 0&&Ki(e.deferred,Je(t))},If=e=>{e!==void 0&&Mf(e)&&e.deferred!==void 0&&Ki(e.deferred,V(new Ts))},Lf=e=>typeof e==`object`&&!!e&&`send`in e&&typeof e.send==`function`,Rf=(e,t,n,r)=>`inspectionSubject`in e&&`sendInspected`in e&&typeof e.sendInspected==`function`?e.sendInspected(t,n,r):e.send(t),zf=e=>e?._tag===`Childless`||e?.childless===!0,Bf=(e,t)=>{let n=e.items??[];e.items=n,n.push(t)},Vf=e=>{if(e.items===void 0)return M();let t=e.items[e.index];return e.index+=1,e.index===e.items.length&&(e.items=void 0,e.index=0),j(t)},Hf=e=>{if(e.items!==void 0)for(let t=e.index;t<e.items.length;t+=1)If(e.items[t]);e.closed=!0,e.items=void 0,e.index=0},Uf=()=>({items:void 0,index:0,closed:!1,receivers:new Set}),Wf=(e,t,n)=>{if(e.closed)return!1;for(Bf(e,t),n?.();e.items!==void 0&&e.receivers.size>0;){let t=e.receivers.values().next().value;e.receivers.delete(t),t(D)}return!0},Gf=e=>C(()=>{let t=Vf(e);return T(t)?A(t.value):e.closed?ti:ga(t=>(e.receivers.add(t),H(()=>{e.receivers.delete(t)}))).pipe(k(Gf(e)))}),Kf=e=>{Hf(e);let t=Array.from(e.receivers);e.receivers.clear();for(let e of t)e(ti)},qf=class extends Ge()(`effect/Machine/MachineRuntime`){},Jf=(e,t)=>pi(e,qf,t),Yf=e=>{switch(e.status){case`active`:return;case`done`:return{_tag:`Done`,output:e.output,snapshot:e};case`error`:{let t=e.cause.reasons.find(It);if(t!==void 0)return{_tag:`Failure`,error:t.error,cause:e.cause,snapshot:e};let n=e.cause.reasons.find(nt);return n===void 0?e.cause.reasons.find(pa)===void 0?{_tag:`Cause`,cause:e.cause,snapshot:e}:{_tag:`Interrupted`,cause:e.cause,snapshot:e}:{_tag:`Defect`,defect:n.defect,cause:e.cause,snapshot:e}}case`stopped`:return{_tag:`Stopped`,snapshot:e}}},Xf=(e,t)=>C(()=>e(t)).pipe($e,E),Zf=(e,t)=>{class n{nextSessionId;constructor(){let e=0;this.nextSessionId=H(()=>`machine:${e++}`)}get start(){return e}get startCompiledSync(){return t}}return H(()=>new n)},Qf=(e,t,n)=>({id:t,sessionId:n,kind:e.inspection?.kind??`Logic`}),$f=(e,t)=>t?{_tag:`Initialization`}:e!==void 0&&Mf(e)&&e.inspection!==void 0?{_tag:`Macrostep`,macrostepId:e.inspection.macrostepId}:void 0,ep=(e,t,n,r,i,a)=>{let o=e.nextDeliveryId(),s=e.nextMacrostepId(),c={deliveryId:o,macrostepId:s,source:r,event:n,causedBy:i,complete:i=>{let a=Tf(i.plan);e.publishUnsafe({_tag:`EventProcessed`,subject:t,macrostepId:s,deliveryId:o,source:r,event:n,before:{status:`active`,state:i.before},after:{status:`active`,state:i.after},handled:a.some(e=>e.transitions.length>0),configurationChanged:a.some(e=>e.changed),microsteps:a})}};return{[jf]:!0,event:n,...a===void 0?void 0:{deferred:a},inspection:c}},tp=(e,t,n)=>{if(!Mf(n)||n.inspection===void 0)return;let r=n.inspection;e.publishUnsafe({_tag:`EventSent`,subject:t,deliveryId:r.deliveryId,source:r.source,target:Cf(t),event:r.event,causedBy:r.causedBy})},np=class{registry;self;runtime;services;sendAcknowledged;scopedServices;constructor(e,t,n,r,i){this.registry=e,this.self=t,this.runtime=n,this.services=r,this.sendAcknowledged=i}has(e){for(let t of this.registry.children.values())if(t.ownerActive&&t.ownerKey===e)return!0;return!1}stopEntry(e){return e.ownerActive=!1,e._tag===`Started`?e.ref.stop:D}spawn(e,t){let n=Symbol(),r,i=()=>{let e=this.registry.children.get(t.id);return e?.token===n&&e.ownerKey===t.key&&e.ownerActive===!0};return C(()=>{if(this.registry.closed)return ti;if(this.has(t.key)||this.registry.children.has(t.id))return V(new ws({id:t.duplicateId}));let a=e(),o=this.registry.scope??=Jr(`parallel`);this.registry.children.set(t.id,{_tag:`Starting`,token:n,ownerKey:t.key,ownerPath:t.path,ownerActive:!0});let s={...this.self,send:e=>t.sendParent(i,e),sendInspected:(e,t,n)=>i()?Rf(this.self,e,t,n):D,...this.sendAcknowledged===void 0?void 0:{[Af]:e=>i()?this.sendAcknowledged(e):ti}},c={detached:!0,id:t.id,sendParent:e=>t.sendParent(i,e),onOutcome:e=>t.onOutcome(i,e,r?.sessionId),...t.onSnapshot===void 0?void 0:{onSnapshot:e=>t.onSnapshot(i,e)},onReadySync:e=>(r=e,xf(this.registry,t.id,n,e,t.descriptor)),onStopSync:()=>bf(this.registry,t.id,n),skipStoppedOutcome:!0,parent:s,runtime:this.runtime,origin:{_tag:`Invoke`,ownerPath:t.path,invokeId:t.duplicateId},...t.activityKind===void 0||this.runtime.inspection===void 0||this.self.inspectionSubject===void 0?void 0:{activity:{id:t.duplicateId,owner:this.self.inspectionSubject,ownerPath:t.path,kind:t.activityKind}}},l=a.execution,u=this.services!==void 0&&t.onSnapshot===void 0&&l?._tag===`Compiled`&&l.childless&&l.drain._tag===`Owned`&&l.initialSync!==void 0,d=(u?P(this.runtime.nextSessionId,e=>this.runtime.startCompiledSync(a,c,this.scopedServices??=Tn(this.services,tr,o),e)):this.runtime.start(a,c)).pipe(Wr(e=>yt(e)?D:(bf(this.registry,t.id,n),r===void 0?D:r.stop)));return(u?d:br(d,o)).pipe(E)})}stopAll(){return C(()=>{let e=[];for(let t of this.registry.children.values())t.ownerActive&&e.push(this.stopEntry(t));return e.length===0?D:e.length===1?e[0]:gt(e,{concurrency:`unbounded`,discard:!0})})}stopPaths(e){if(e.length===0)return;let t=new Set(e),n=[];for(let e of this.registry.children.values())e.ownerActive&&e.ownerPath!==void 0&&t.has(e.ownerPath)&&n.push(this.stopEntry(e));return n.length===0?void 0:n.length===1?n[0]:gt(n,{concurrency:`unbounded`,discard:!0})}},rp=_t(M()).pipe(In(Vr)),ip=e=>D,ap=(e,t)=>{},op=()=>void 0,sp=Symbol(`effect/Machine/EmissionsClosed`),cp=()=>{let e,t=C(()=>{let t=e;return t===sp?A(void 0):t===void 0?et().pipe(P(t=>H(()=>{let n=e;return n===sp?[void 0,!0]:n===void 0?(e=t,[t,!1]):[n,!0]}).pipe(P(([e,n])=>n?an(t).pipe(He(e)):A(e))))):A(t)});return{emit:t=>C(()=>e===void 0||e===sp?D:un(e,t).pipe(E)),close:()=>{let t=e;return e=sp,t===void 0||t===sp?D:an(t)},stream:Vt(t.pipe(B(e=>e===void 0?Xi:ta(e))))}},lp={close:()=>D,spawn:(()=>gn(Error(`Childless machine logic cannot spawn a process`))),get:()=>A(M()),changes:()=>rp,sendTo:()=>D,stop:()=>D,owned:{spawn:()=>gn(Error(`Childless machine logic cannot spawn an owned process`)),stopAll:()=>D,stopPaths:()=>void 0}},up=(e,t,n,r)=>{let i={closed:!1,children:new Map,observers:void 0,scope:void 0},a=e=>C(()=>{if(i.closed||(i.closed=!0,i.scope===void 0))return D;let t=fi(i.scope,e),n,r;for(let e of i.children.values())e._tag===`Started`&&(n===void 0?n=e.ref.stop:(r??=[n],r.push(e.ref.stop)));t!==void 0&&(n===void 0?n=t:(r??=[n],r.push(t)));let a=r??n;return a===void 0?D:Array.isArray(a)?gt(a,{concurrency:`unbounded`,discard:!0}):a}),o=(e,t)=>H(()=>bf(i,e,t)),s=(e,t,n,r)=>H(()=>xf(i,e,t,n,r)),c=e=>{let t=typeof e==`string`?e:e.id;return H(()=>{if(i.closed)return M();let n=i.children.get(t);return n!==void 0&&_f(n,e)?j(n.ref):M()})},l=e=>{let t=typeof e==`string`?e:e.id;return Gt(ne((n,r)=>H(()=>({child:e,id:t,values:void 0,waiter:void 0})).pipe(P(n=>{let a=H(()=>{i.observers!==void 0&&(i.observers.delete(n),i.observers.size===0&&(i.observers=void 0)),n.values=void 0,n.waiter=void 0});return ur(r,a).pipe(k(H(()=>{!i.closed&&r.state._tag!==`Closed`&&(i.observers??=new Set,i.observers.add(n)),hf(n,vf(i,t,e))})),He(gf(n)))}))))},u=(e,t,n,r)=>{let a=typeof e==`string`?e:e.id;return C(()=>{if(i.closed)return D;let o=i.children.get(a);return o!==void 0&&_f(o,e)?Rf(o.ref,t,n,r):D})},d=e=>{let t=typeof e==`string`?e:e.id;return C(()=>{if(i.closed)return D;let n=i.children.get(t);return n!==void 0&&_f(n,e)?n.ref.stop:D})};function f(n,r){let a=typeof n==`object`&&n&&hu in n?n:void 0,c=a===void 0?n:a[hu](r?.input),l=a===void 0?r:{id:a.id,descriptor:a},u=Symbol(),d=l?.id??u,f;return C(()=>i.closed?ti:typeof d==`string`&&(i.children.has(d)||mf(d))?V(new ws({id:d})):(i.scope??=Jr(`parallel`),i.children.set(d,{_tag:`Starting`,token:u}),t.start(c,{detached:!0,...l?.id===void 0?void 0:{id:l.id},...l?.onOutcome===void 0?void 0:{onOutcome:l.onOutcome},...l?.[Ef]===void 0?void 0:{onSnapshot:l[Ef]},...l?.[kf]===void 0?void 0:{sendParent:l[kf]},onReady:(e,t)=>H(()=>{f=e}).pipe(k(s(d,u,e,l?.descriptor)),P(e=>e?D:t)),onStop:o(d,u),parent:e,runtime:t,origin:{_tag:`Spawn`,address:l?.id}}).pipe(Wr(e=>se(e)?o(d,u).pipe(k(f===void 0?D:f.stop)):D),br(i.scope))))}return{close:a,spawn:f,get:c,changes:l,sendTo:u,stop:d,owned:new np(i,e,t,n,r)}},dp=(e,t,n,r)=>H(()=>up(e,t,n,r)),fp=(e,t)=>`${e.length}:${e}${t}`,pp=(e,t)=>`${pf}${fp(e,t)}`,mp=e=>({initial:()=>D,run:()=>e}),hp=(e,t,n)=>({initial:()=>D,run:({parent:r})=>{let i=r?.[Af];return i===void 0?gn(Error(`Stream invocation requires an acknowledged parent machine`)):dt(e,e=>i(Iu(t,n,e)).pipe(E,S(()=>ti)))}}),gp=(e,t)=>typeof e==`function`?e(t):e,_p=e=>({spawn:((t,n)=>e.spawn(t,n)),sendTo:((t,n)=>e.sendTo(t,n)),stop:(t=>e.stopChild(t))}),vp=(e,t,n)=>{if(`effect`in e)return{id:String(e.id),sourceName:e.sourceName,src:()=>mp(e.effect(t)),onDone:e.onDone,onFailure:e.onFailure,onSnapshot:e.onSnapshot,activityKind:`Effect`};if(`after`in e)return{id:String(e.id),sourceName:e.sourceName,src:()=>mp(ia(gp(e.after,t))),onDone:e.onDone,activityKind:`Timer`};if(`stream`in e){let r=String(e.id);return{id:r,sourceName:e.sourceName,src:()=>hp(e.stream(t),n,r),onDone:e.onDone,onFailure:e.onFailure,activityKind:`Stream`}}if(`logic`in e)return{id:String(e.id),address:String(e.address),src:()=>gp(e.logic,t),onDone:e.onDone,onFailure:e.onFailure,onSnapshot:e.onSnapshot};if(`child`in e){let n=e.child;return{id:n.id,address:n.id,descriptor:n,src:()=>n[hu](`input`in e?gp(e.input,t):void 0),onDone:e.onDone,onFailure:e.onFailure,onSnapshot:e.onSnapshot}}throw Error(`Unsupported captured machine invocation: ${String(e)}`)},yp=e=>e.length===0?D:e.length===1?e[0]:gt(e,{discard:!0}),bp=(e,t,n)=>(n===void 0||e.self.sendInspected===void 0?e.self.send(t):e.self.sendInspected(t,e.self.inspectionSubject,{_tag:`Activity`,activitySessionId:n})).pipe(Fe(`StoppedError`,()=>D)),xp=e=>e instanceof Ss||e instanceof J||e instanceof Ts,Sp=(e,t,n,r,i,a,o,s,c,l,u,d)=>C(()=>{let f=fp(n,r),p=u===void 0?o:()=>{let t=o();return{...t,run:i=>Et(C(()=>t.run(i)),`Machine.invoke`,{attributes:{"machine.id":e.self.id,"machine.sessionId":e.self.sessionId,"machine.state.path":n,"machine.invoke.id":r,"machine.invoke.source":d??r,"machine.invoke.kind":u,"machine.invoke.sessionId":i.self.sessionId},captureStackTrace:!1})}};return t.spawn(p,{key:f,path:n,id:i,duplicateId:r,...a===void 0?void 0:{descriptor:a},...u===void 0?void 0:{activityKind:u},sendParent:(t,n)=>t()?e.self.send(n):D,onOutcome:(t,i,o)=>k(xe,C(()=>i._tag===`Stopped`||!t()?D:i._tag===`Done`?s===void 0?e.failCause(st(Error(`Invocation "${r}" completed without the required onDone handler`))):bp(e,Fu(n,r,i.output),u===void 0?void 0:o):i._tag===`Failure`&&c!==void 0&&(a===void 0||!xp(i.error))?bp(e,Lu(n,r,i.error),u===void 0?void 0:o):e.failCause(i.cause))),...l===void 0?void 0:{onSnapshot:(t,i)=>t()?bp(e,Ru(n,r,i)):D}})}),Cp=(e,t)=>mf(e)?V(new ws({id:t})):void 0,wp=(e,t,n,r)=>{let i=String(r.id),a=r.address===void 0?void 0:Cp(String(r.address),i);return a===void 0?Sp(e,t,n,i,r.address===void 0?pp(n,i):String(r.address),r.descriptor,r.src,r.onDone,r.onFailure,r.onSnapshot,r.activityKind,r.sourceName):a},Tp=(e,t,n,r)=>{let i=r.child,a=Cp(i.id,i.id);return a===void 0?Sp(e,t,n,i.id,i.id,i,i[hu],r.onDone,r.onFailure,r.onSnapshot,void 0):a},Ep=(e,t,n,r,i,a)=>{let o=_p(t),s=sd(e,i).filter(e=>r.active.has(e)).flatMap(i=>{let s={...ll(r)??{self:t.self,parent:t.parent},children:o,state:r.values.get(i),containingState:Sl(e,r,i),ancestors:xl(e,r,i),event:a};return Eu(Hl(e,i)?.invoke).map(e=>`child`in e&&!(`input`in e)?Tp(t,n,i,e):wp(t,n,i,vp(e,s,i)))});return s.length===0?void 0:yp(s)},Dp=Symbol(`effect/Machine/CompiledStoppedCompletion`),Op=class{logic;options;services;id;sessionId;inspectionSubject;send;sendInspected(e,t,n){return this.offerEvent(e,t,n)}[Af](e){return this.sendAcknowledgedEffect(e)}[Df](e){let t=this.snapshotObservers??=new Set;return t.add(e),()=>{t.delete(e)}}mailbox={items:void 0,index:0,closed:!1};address;childRuntime=lp;processScope;processContext;compiledContext;current;lifecycle=`Active`;runState=`Initializing`;completion;waiter;termination;terminationSnapshot;worker;interruptRequested=!1;offerRevision=0;snapshotObservers;changesFlushScheduled=!1;inFlightMessage;externalEmissions;emissionsPubSub;activity;initialEntryPaths;initialMicrosteps;initializing;constructor(e,t,n,r){this.logic=e,this.options=t,this.services=n,this.sessionId=r,this.id=t.id??r;let i=t.runtime.inspection;i!==void 0&&(this.inspectionSubject=Qf(e,this.id,r),this.initializing=!0,t.activity!==void 0&&(this.activity={...t.activity,sessionId:r})),this.externalEmissions=t.emissions,this.send=i===void 0?e=>this.offerMessage(e):e=>this.offerEvent(e,void 0,void 0),this.address={id:this.id,sessionId:r,stop:C(()=>this.stopFromProcess()),send:this.send,...i===void 0?void 0:{inspectionSubject:this.inspectionSubject,sendInspected:(e,t,n)=>this.offerEvent(e,t,n)}}}get inspector(){return this.options.runtime.inspection}causation(){return $f(this.inFlightMessage,this.initializing===!0)}publishCreated(){let e=this.inspector,t=this.inspectionSubject;e!==void 0&&t!==void 0&&e.publishUnsafe(this.activity===void 0?{_tag:`Created`,subject:t,parent:this.options.parent?.inspectionSubject,origin:this.options.origin??{_tag:`Root`},definition:this.logic.inspection?.definition}:{_tag:`ActivityStarted`,subject:this.activity.owner,activity:this.activity})}publishInitialized(e){if(this.initializing=!1,this.activity!==void 0)return;let t=this.inspector,n=this.inspectionSubject;t!==void 0&&n!==void 0&&t.publishUnsafe({_tag:`Initialized`,subject:n,snapshot:{status:`active`,state:e},initialEntryPaths:this.initialEntryPaths??[],microsteps:Tf({microsteps:this.initialMicrosteps??[]})})}publishStartFailed(e){this.initializing=!1;let t=this.inspector,n=this.inspectionSubject;t!==void 0&&n!==void 0&&t.publishUnsafe(this.activity===void 0?{_tag:`StartFailed`,subject:n,cause:e}:{_tag:`ActivityStopped`,subject:this.activity.owner,activity:this.activity,exit:qt(e)})}get execution(){return this.logic.execution}initializeCompiledSync(){this.publishCreated(),this.execution.childless||(this.childRuntime=up(this.address,this.options.runtime,this.services,e=>this.sendAcknowledgedEffect(e)));let e=this.options.parent,t=this.options.sendParent??(e===void 0?ip:this.inspector===void 0?e.send:t=>Rf(e,t,this.inspectionSubject,this.causation()));this.processScope={self:this.address,parent:e,spawn:this.childRuntime.spawn,sendParent:t,emit:e=>this.emitEvent(e),sendTo:((e,t)=>Lf(e)?this.inspector===void 0?e.send(t):Rf(e,t,this.inspectionSubject,this.causation()):this.childRuntime.sendTo(e,t,this.inspectionSubject,this.causation())),stopChild:this.childRuntime.stop,failCause:e=>this.failCause(e),inspectInitial:this.inspector===void 0?ap:(e,t=[])=>{this.initialEntryPaths=e,this.initialMicrosteps=t}};let n=this.execution.initialSync,r;try{r=n(this.processScope)}catch(e){return this.runState=`Idle`,this.publishStartFailed(pt(e)),V(e)}return this.runState=`Idle`,this.current={revision:0,terminalizing:!1,changes:void 0,snapshot:{status:`active`,state:r.state}},this.publishInitialized(r.state),this.compiledContext=new kp(this.processScope,this.childRuntime.owned,this),`executionState`in r&&(this.compiledContext.executionState=r.executionState),this.options.onReadySync!==void 0&&!this.options.onReadySync(this)&&this.requestTerminationSync({_tag:`Stopped`}),r.done===!0&&this.lifecycle===`Active`&&this.requestTerminationSync({_tag:`Done`,output:r.output}),r.done===!1&&this.execution.childless&&this.lifecycle===`Active`&&this.mailbox.items===void 0?A(this):(this.runState=`Draining`,dr(this.drainRuntime(),this.services).pipe(He(this)))}initialize(){let e=this;return Ii(function*(){e.publishCreated(),e.execution.childless||(e.childRuntime=yield*dp(e.address,e.options.runtime,e.services,t=>e.sendAcknowledgedEffect(t)));let t=e.options.parent,n=e.options.sendParent??(t===void 0?ip:e.inspector===void 0?t.send:n=>Rf(t,n,e.inspectionSubject,e.causation()));e.processScope={self:e.address,parent:t,spawn:e.childRuntime.spawn,sendParent:n,emit:t=>e.emitEvent(t),sendTo:((t,n)=>Lf(t)?e.inspector===void 0?t.send(n):Rf(t,n,e.inspectionSubject,e.causation()):e.childRuntime.sendTo(t,n,e.inspectionSubject,e.causation())),stopChild:e.childRuntime.stop,failCause:t=>e.failCause(t),inspectInitial:e.inspector===void 0?ap:(t,n=[])=>{e.initialEntryPaths=t,e.initialMicrosteps=n}};let r=t=>se(t)?e.childRuntime.close(t):D,i=e.execution.initial,a=yield*(i===void 0?e.logic.initial(e.processScope).pipe(B(e=>({state:e,done:void 0,output:void 0}))):i(e.processScope)).pipe(Wr(t=>(se(t)&&e.publishStartFailed(t.cause),r(t))),ke(H(()=>{e.runState=`Idle`}))),o=a.state;return e.current={revision:0,terminalizing:!1,changes:void 0,snapshot:{status:`active`,state:o}},e.publishInitialized(o),e.execution.drain._tag===`Process`?e.processContext={...e.processScope,receive:Xn,poll:H(()=>ha(Vf(e.mailbox),Nf)),receiveMessage:Xn,pollMessage:H(()=>e.pollCompiledMessage()),completeMessage:t=>e.completeCompiledMessage(t),state:H(()=>e.current.snapshot.state),setState:t=>e.setActiveState(t),updateState:t=>e.updateState(t)}:(e.compiledContext=new kp(e.processScope,e.childRuntime.owned,e),`executionState`in a&&(e.compiledContext.executionState=a.executionState)),e.options.onReadySync!==void 0&&!e.options.onReadySync(e)?yield*e.requestTermination({_tag:`Stopped`}):e.options.onReady!==void 0&&(yield*e.options.onReady(e,e.requestTermination({_tag:`Stopped`}).pipe(E))),e.options.onSnapshot!==void 0&&(yield*Xf(e.options.onSnapshot,{status:`active`,state:o})),a.done===!0&&e.lifecycle===`Active`&&(yield*e.requestTermination({_tag:`Done`,output:a.output})),a.done===!1&&e.execution.childless&&e.lifecycle===`Active`&&e.mailbox.items===void 0||(e.runState=`Draining`,yield*e.drainRuntime()),e})}get state(){return H(()=>this.current.snapshot.state)}get snapshot(){return H(()=>this.current.snapshot)}get changes(){return this.changesStream()}get emissions(){return this.externalEmissions?.stream??this.emissionsStream()}get join(){return C(()=>this.lifecycle===`Completed`?this.resolveCompletion(this.completion):(this.waiter??=Ut(),gr(this.waiter)))}get stop(){return m(this.stopEffect())}child(e){return this.childRuntime.get(e)}childChanges(e){return this.childRuntime.changes(e)}requestTermination(e){return H(()=>this.requestTerminationSync(e))}hasTerminationRequest(){return this.lifecycle===`TerminationRequested`}requestTerminationSync(e){return this.lifecycle===`Active`&&(this.lifecycle=`TerminationRequested`,this.termination=e,this.terminationSnapshot=this.reserveTermination(e),!0)}reserveTermination(e){let t=this.current;if(t===void 0||t.terminalizing||t.snapshot.status!==`active`)return;let n=e._tag===`Stopped`?{status:`stopped`,state:t.snapshot.state}:e._tag===`Done`?{status:`done`,state:t.snapshot.state,output:e.output}:{status:`error`,state:t.snapshot.state,cause:e.cause};return this.current={...t,terminalizing:!0},n}stopFromProcess(){let e=this.requestTermination({_tag:`Stopped`}).pipe(E);return this.runState===`Initializing`?e:e.pipe(k(ti))}failCause(e){let t={_tag:`Failure`,cause:e};return this.requestTermination(t).pipe(P(e=>e?u(this.settleRequestedTermination()).pipe(E):D))}sendAcknowledgedEffect(e){return Mr(t=>ra().pipe(P(n=>this.offerEvent(e,void 0,void 0,n).pipe(k(t(gr(n)))))))}offerEvent(e,t,n,r){return C(()=>{let i=this.inspector,a=this.inspectionSubject,o=i?.isActive()===!0&&a!==void 0?ep(i,a,e,t,n,r):r===void 0?e:{[jf]:!0,event:e,deferred:r};return this.offerMessage(o)})}offerMessage(e){return m(mt(t=>{if(this.mailbox.closed||this.lifecycle!==`Active`)return V(new Ts);let n=this.inspector,r=this.inspectionSubject;n!==void 0&&r!==void 0&&tp(n,r,e),this.offerRevision+=1;let i=this.execution.drain,a=this.compiledContext,o=this.runState===`Idle`&&a!==void 0&&i._tag===`Owned`?i.runSync:void 0;if(o===void 0&&Bf(this.mailbox,e),this.runState!==`Idle`)return D;if(this.runState=`Draining`,o!==void 0){let n;try{n=o(a,e)}catch(e){n=gn(e)}return n!==void 0||this.hasTerminationRequest()?this.startWorker(n):(this.runState=`Idle`,this.scheduleChangesFlush(t.currentDispatcher),D)}return this.startWorker(void 0)}))}startWorker(e){let t=dr(this.drainRuntime(e),this.services);return(this.options.detached===!0?u(t,{startImmediately:!0}):Nt(t,{startImmediately:!0})).pipe(P(e=>H(()=>(e.pollUnsafe()===void 0&&(this.worker=e),this.interruptRequested?(this.interruptRequested=!1,!0):!1)).pipe(P(t=>t?u(this.interruptAndFinish(e)):D))),E)}stopEffect(){return C(()=>this.lifecycle===`Completed`||this.finishIdleChildlessStop()?D:this.requestTermination({_tag:`Stopped`}).pipe(P(e=>e?this.settleRequestedTermination():this.awaitCompletion())))}finishIdleChildlessStop(){if(!this.execution.childless||this.runState!==`Idle`||this.worker!==void 0||this.lifecycle!==`Active`||this.options.onOutcome!==void 0&&this.options.skipStoppedOutcome!==!0||this.options.onStop!==void 0||this.inspector!==void 0||this.current.changes!==void 0||this.externalEmissions!==void 0||this.emissionsPubSub!==void 0&&this.emissionsPubSub!==sp||this.current.terminalizing||this.current.snapshot.status!==`active`)return!1;this.emissionsPubSub=sp;let e={status:`stopped`,state:this.current.snapshot.state};return this.lifecycle=`TerminationRequested`,this.termination={_tag:`Stopped`},this.terminationSnapshot=e,Hf(this.mailbox),this.current={revision:this.current.revision+1,terminalizing:!0,changes:void 0,snapshot:e},this.notifySnapshotObservers(),If(this.inFlightMessage),this.inFlightMessage=void 0,this.interruptRequested=!1,this.compiledContext!==void 0&&(this.compiledContext.executionState=void 0),this.options.onStopSync?.(this),this.completion=Dp,this.lifecycle=`Completed`,this.waiter!==void 0&&(Ki(this.waiter,this.resolveCompletion(Dp)),this.waiter=void 0),!0}settleRequestedTermination(){return C(()=>this.runState===`Draining`?this.worker===void 0?(this.interruptRequested=!0,this.awaitCompletion()):this.interruptAndFinish(this.worker).pipe(k(this.awaitCompletion())):this.finishRequestedTermination())}interruptAndFinish(e){return bi(e).pipe(k(C(()=>this.lifecycle===`Completed`?D:this.finishRequestedTermination())))}awaitCompletion(){return this.lifecycle===`Completed`?D:this.join.pipe($e,E)}resolveCompletion(e){if(e!==Dp)return e;let t=V(new Ts);return this.completion=t,t}drainRuntime(e){let t=this;return Mr(n=>Ii(function*(){let r=t.offerRevision,i=e;for(;;){if(t.hasTerminationRequest())return yield*t.finishRequestedTermination();let e=yield*n(C(()=>{if(i!==void 0){let e=i;return i=void 0,e}let e=t.execution.drain;return e._tag===`Process`?e.run(t.processContext):e.run(t.compiledContext)})).pipe($e);if(t.flushPendingChanges(),se(e))return t.lifecycle===`Active`&&(yield*t.requestTermination({_tag:`Failure`,cause:e.cause})),yield*t.finishRequestedTermination();if(T(e.value))return yield*t.requestTermination({_tag:`Done`,output:e.value.value}),yield*t.finishRequestedTermination();if(t.hasTerminationRequest())return yield*t.finishRequestedTermination();if(t.offerRevision!==r)r=t.offerRevision;else{t.runState=`Idle`,t.worker=void 0;return}}}))}finishRequestedTermination(){return C(()=>{if(this.lifecycle!==`TerminationRequested`)return D;let e=this.termination;if(e===void 0)return D;let t=this.terminationSnapshot??this.reserveTermination(e);if(t===void 0)return this.awaitCompletion();let n=e._tag===`Stopped`?p:e._tag===`Done`?Lr(e.output):qt(e.cause),r=e._tag===`Stopped`?Dp:e._tag===`Done`?A(e.output):Je(e.cause),i=this.options.onOutcome===void 0||e._tag===`Stopped`&&this.options.skipStoppedOutcome===!0?D:C(()=>this.options.onOutcome(Yf(t))).pipe($e,E),a=this.inspector,o=this.inspectionSubject,s=a===void 0||o===void 0?this.closeEmissions():this.closeEmissions().pipe(k(H(()=>a.publishUnsafe(this.activity===void 0?{_tag:`Terminated`,subject:o,snapshot:t}:{_tag:`ActivityStopped`,subject:this.activity.owner,activity:this.activity,exit:t.status===`stopped`?pe():n}))));return m(H(()=>{Hf(this.mailbox)}).pipe(k(this.childRuntime.close(n)),k(this.setAndPublishSnapshot(t)),k(s),k(H(()=>{e._tag===`Failure`?Ff(this.inFlightMessage,e.cause):If(this.inFlightMessage),this.inFlightMessage=void 0})),k(i),k(this.options.onStop??D),k(this.options.inspectionRoot===!0&&this.inspector!==void 0?this.inspector.close:D),k(H(()=>{this.options.onStopSync?.(this),this.runState=`Idle`,this.worker=void 0,this.interruptRequested=!1,this.compiledContext!==void 0&&(this.compiledContext.executionState=void 0),this.completion=r,this.lifecycle=`Completed`,this.waiter!==void 0&&(Ki(this.waiter,this.resolveCompletion(r)),this.waiter=void 0)}))))})}publishSnapshot(e){let t=e.changes===void 0?A(e):un(e.changes,[e]).pipe(He(e)),n=e.snapshot;return this.options.onSnapshot===void 0||n.status!==`active`?t:t.pipe(Jt(()=>Xf(this.options.onSnapshot,n)))}completeChanges(e){return e.changes===void 0?D:un(e.changes,Lr(void 0)).pipe(E)}emitEvent(e){let t=this.externalEmissions===void 0?C(()=>this.emissionsPubSub===void 0||this.emissionsPubSub===sp?D:un(this.emissionsPubSub,e).pipe(E)):this.externalEmissions.emit(e),n=this.inspector,r=this.inspectionSubject;return n===void 0||r===void 0?t:t.pipe(Jt(()=>H(()=>n.publishUnsafe({_tag:`Emitted`,subject:r,emission:e,causedBy:this.causation()}))))}shutdownEmissions(){return this.closeEmissions()}closeEmissions(){if(this.externalEmissions!==void 0)return this.externalEmissions.close();let e=this.emissionsPubSub;return this.emissionsPubSub=sp,e===void 0||e===sp?D:an(e)}getOrCreateEmissions(){return C(()=>{let e=this.emissionsPubSub;return e===sp?A(void 0):e===void 0?et().pipe(P(e=>H(()=>{let t=this.emissionsPubSub;return t===sp?[void 0,!0]:t===void 0?(this.emissionsPubSub=e,[e,!1]):[t,!0]}).pipe(P(([t,n])=>n?an(e).pipe(He(t)):A(t))))):A(e)})}emissionsStream(){return Vt(this.getOrCreateEmissions().pipe(B(e=>e===void 0?Xi:ta(e))))}setAndPublishSnapshot(e){return C(()=>{this.flushPendingChanges();let t={revision:this.current.revision+1,snapshot:e,terminalizing:!0,changes:this.current.changes};return this.current=t,this.notifySnapshotObservers(),this.publishSnapshot(t).pipe(P(e=>this.completeChanges(e)),E)})}setActiveState(e){return C(()=>this.commitActiveState(e)??D)}pollCompiledMessage(){let e=Vf(this.mailbox);return T(e)&&(this.inFlightMessage=Mf(e.value)?e.value:void 0),e}beginCompiledMessage(e){this.inFlightMessage=Mf(e)?e:void 0}completeCompiledMessage(e){Pf(this.inFlightMessage,e),this.inFlightMessage=void 0}compiledState(){return this.current.snapshot.state}commitCompiledState(e){return this.commitActiveState(e,!0)}commitActiveState(e,t=!1){let n=this.current;if(n.terminalizing||n.snapshot.status!==`active`)return;let r=n.pendingChanges;r!==void 0&&(n.pendingChanges=void 0);let i={status:`active`,state:e},a={revision:n.revision+1,snapshot:i,terminalizing:!1,changes:n.changes};return this.current=a,a.changes!==void 0&&(r===void 0?t?a.pendingChanges=[a]:Ie(a.changes,[a]):(r.push(a),t?a.pendingChanges=r:Ie(a.changes,r))),this.notifySnapshotObservers(),this.options.onSnapshot===void 0?void 0:Xf(this.options.onSnapshot,i)}notifySnapshotObservers(){if(this.snapshotObservers!==void 0)for(let e of this.snapshotObservers)e()}scheduleChangesFlush(e){this.changesFlushScheduled||this.current.pendingChanges===void 0||(this.changesFlushScheduled=!0,e.scheduleTask(()=>{this.changesFlushScheduled=!1,this.flushPendingChanges()},0))}flushPendingChanges(){let e=this.current,t=e?.pendingChanges;t!==void 0&&e.changes!==void 0&&(e.pendingChanges=void 0,Ie(e.changes,t))}updateState(e){return C(()=>{let t=this.current;return t.terminalizing||t.snapshot.status!==`active`?D:e(t.snapshot.state).pipe(P(e=>{let n=this.current;return n.terminalizing||n.revision!==t.revision?D:this.setActiveState(e)}))})}getOrCreateChanges(){return C(()=>{let e=this.current;return e.snapshot.status===`active`?e.changes===void 0?et({replay:1}).pipe(P(e=>H(()=>{let t=this.current;return t.snapshot.status===`active`?t.changes===void 0?(this.current={...t,changes:e},[e,!1]):[t.changes,!0]:[void 0,!0]}).pipe(P(([t,n])=>n?an(e).pipe(He(t)):A(t))))):A(e.changes):A(void 0)})}changesStream(){let e=this;return Vt(Ii(function*(){let t=yield*e.getOrCreateChanges();if(t===void 0)return _t(e.current.snapshot);let n=yield*_n(t),r=e.current;return r.snapshot.status===`active`?_t(r.snapshot).pipe(In(Gt(_a(Ae(n))).pipe(oa(e=>e.revision>r.revision),de(e=>e.snapshot)))):_t(r.snapshot)}))}},kp=class{scope;ownedChildren;process;executionState;constructor(e,t,n){this.scope=e,this.ownedChildren=t,this.process=n}poll(){return ha(this.process.pollCompiledMessage(),Nf)}pollMessage(){return this.process.pollCompiledMessage()}beginMessage(e){this.process.beginCompiledMessage(e)}state(){return this.process.compiledState()}completeMessage(e){this.process.completeCompiledMessage(e)}commit(e){return this.process.commitCompiledState(e)}runAfterChanges(e){return this.process.flushPendingChanges(),e}},Ap=Sn(function*(e,t){let n=t.sessionId??(yield*t.runtime.nextSessionId),r=yield*rn(),i=e.execution,a=new Op(e,t,r,n);return yield*(i.initialSync!==void 0&&t.onReady===void 0&&t.onSnapshot===void 0?a.initializeCompiledSync():a.initialize()).pipe(Wr(e=>se(e)?a.shutdownEmissions().pipe(k(t.inspectionRoot===!0&&t.runtime.inspection!==void 0?t.runtime.inspection.close:D)):D))}),jp=(e,t,n,r)=>new Op(e,t,n,r).initializeCompiledSync(),Mp=Sn(function*(e,t){let{detached:n,id:r,onOutcome:i,onReady:a,onReadySync:o,onSnapshot:s,onStop:c,onStopSync:l,parent:d,runtime:f,sendParent:h}=t,g=t.sessionId??(yield*f.nextSessionId),_=r??g,v=f.inspection,y=v===void 0?void 0:Qf(e,_,g),b=v===void 0||t.activity===void 0?void 0:{...t.activity,sessionId:g},ee,te,x=Uf(),S=t.emissions??cp(),ne=yield*ra(),re=yield*ra(),ae=gr(re).pipe($e,E),oe=!0,ce,le=Qi(ne,{_tag:`Stopped`}).pipe(E),ue=(e,t)=>C(()=>Wf(x,e,t)?D:V(new Ts)),fe=v===void 0?void 0:(e,t,n,r)=>C(()=>{let i=v.isActive()?ep(v,y,e,t,n,r):r===void 0?e:{[jf]:!0,event:e,deferred:r};return ue(i,()=>tp(v,y,i))}),me=e.execution?._tag===`Compiled`?e=>Mr(t=>ra().pipe(P(n=>(v===void 0?ue({[jf]:!0,event:e,deferred:n}):fe(e,void 0,void 0,n)).pipe(k(t(gr(n))))),B(e=>e))):void 0,he={id:_,sessionId:g,stop:C(()=>oe?le:le.pipe(k(Xn))),send:v===void 0?e=>ue(e):e=>fe(e,void 0,void 0),...v===void 0?void 0:{inspectionSubject:y,sendInspected:fe}},{changes:ge,close:_e,get:ve,owned:ye,sendTo:be,spawn:xe,stop:Se}=lp;zf(e.execution)||({changes:ge,close:_e,get:ve,owned:ye,sendTo:be,spawn:xe,stop:Se}=yield*dp(he,f,void 0,me===void 0?void 0:e=>me(e)));let Ce=e=>yt(e)?D:(v!==void 0&&v.publishUnsafe(b===void 0?{_tag:`StartFailed`,subject:y,cause:e.cause}:{_tag:`ActivityStopped`,subject:b.owner,activity:b,exit:e}),_e(e).pipe(k(S.close()),k(t.inspectionRoot===!0&&v!==void 0?v.close:D))),we=l===void 0?c??D:H(()=>l(at)),Te=v===void 0?op:()=>$f(ce,oe),Ee=h??(d===void 0?ip:v===void 0?d.send:e=>Rf(d,e,y,Te())),De=v===void 0?S.emit:e=>S.emit(e).pipe(Jt(()=>H(()=>v.publishUnsafe({_tag:`Emitted`,subject:y,emission:e,causedBy:Te()})))),Oe={self:he,parent:d,spawn:xe,sendParent:Ee,emit:De,sendTo:v===void 0?((e,t)=>Lf(e)?e.send(t):be(e,t)):((e,t)=>Lf(e)?Rf(e,t,y,Te()):be(e,t,y,Te())),stopChild:Se,failCause:e=>Qi(ne,{_tag:`Failure`,cause:e}).pipe(E),inspectInitial:v===void 0?ap:(e,t=[])=>{ee=e,te=t}};v!==void 0&&v.publishUnsafe(b===void 0?{_tag:`Created`,subject:y,parent:d?.inspectionSubject,origin:t.origin??{_tag:`Root`},definition:e.inspection?.definition}:{_tag:`ActivityStarted`,subject:b.owner,activity:b});let je=yield*e.initial(Oe).pipe(Wr(Ce),ke(H(()=>{oe=!1}))),w=yield*Jn({revision:0,terminalizing:!1,changes:void 0,snapshot:{status:`active`,state:je}});b===void 0&&v?.publishUnsafe({_tag:`Initialized`,subject:y,snapshot:{status:`active`,state:je},initialEntryPaths:ee??[],microsteps:Tf({microsteps:te??[]})});let Me=s===void 0?e=>e.changes===void 0?A(e):un(e.changes,[e]).pipe(He(e)):e=>{let t=e.changes===void 0?A(e):un(e.changes,[e]).pipe(He(e)),n=e.snapshot;return n.status===`active`?t.pipe(Jt(()=>Xf(s,n))):t},Ne=e=>e.changes===void 0?D:un(e.changes,Lr(void 0)).pipe(E),Pe=e=>e.snapshot.status===`active`?A(e):Ne(e).pipe(He(e)),Fe=e=>Oi(w).pipe(P(t=>t.revision===e.revision?Me(e).pipe(P(Pe)):A(void 0))),Ie=e=>Bi(w,t=>t.terminalizing?A([void 0,t]):B(e(t.snapshot),e=>{if(e===void 0)return[void 0,t];let n={revision:t.revision+1,snapshot:e,terminalizing:!1,changes:t.changes};return[n,n]})).pipe(P(e=>e===void 0?A(void 0):Fe(e)),B(e=>e?.snapshot)),Le=e=>Hr(w,t=>t.terminalizing||t.snapshot.status!==`active`?[void 0,t]:[{revision:t.revision+1,snapshot:e(t.snapshot),terminalizing:!0,changes:t.changes},{...t,terminalizing:!0}]).pipe(B(e=>e?.snapshot)),Re=e=>er(w,t=>({revision:t.revision+1,snapshot:e,terminalizing:!0,changes:t.changes})).pipe(P(Me),P(Pe),E),ze=v===void 0?e=>Ie(t=>A(t.status===`active`?{status:`active`,state:e}:void 0)).pipe(E):t=>Oi(w).pipe(P(n=>Ie(e=>A(e.status===`active`?{status:`active`,state:t}:void 0)).pipe(Jt(r=>H(()=>{e.inspection?.kind!==`Machine`&&r!==void 0&&v.publishUnsafe({_tag:`StateChanged`,subject:y,before:n.snapshot.state,after:t,causedByDeliveryId:ce!==void 0&&Mf(ce)?ce.inspection?.deliveryId:void 0})})))),E),Be=(e,n,r)=>{let a=i===void 0||e.status===`stopped`&&t.skipStoppedOutcome===!0?D:C(()=>i(Yf(e))).pipe($e,E),o=v===void 0?S.close():S.close().pipe(k(H(()=>v.publishUnsafe(b===void 0?{_tag:`Terminated`,subject:y,snapshot:e}:{_tag:`ActivityStopped`,subject:b.owner,activity:b,exit:e.status===`stopped`?pe():n}))));return m(H(()=>Kf(x)).pipe(k(_e(n)),k(Re(e)),k(o),k(H(()=>{se(n)?Ff(ce,n.cause):If(ce),ce=void 0})),k(a),k(we),k(t.inspectionRoot===!0&&v!==void 0?v.close:D),k(r)))},Ue=Le(e=>({status:`stopped`,state:e.state})),We=e=>Le(t=>({status:`error`,state:t.state,cause:e})),Ge=e=>Le(t=>({status:`done`,state:t.state,output:e})),Ke=e=>Be(e,p,ca(re,new Ts)),qe=(e,t)=>{let n=qt(t);return Be(e,n,Wn(re,t))},Je=(e,t)=>{let n=Lr(t);return Be(e,n,Qi(re,t))},Ye=m(le.pipe(k(ae))),Xe=e.execution?._tag===`Compiled`?{receiveMessage:Gf(x).pipe(Jt(e=>H(()=>{ce=Mf(e)?e:void 0}))),pollMessage:H(()=>Vf(x)).pipe(Jt(e=>H(()=>{T(e)&&(ce=Mf(e.value)?e.value:void 0)}))),completeMessage:e=>{Pf(ce,e),ce=void 0}}:void 0,Ze=v===void 0||e.execution?._tag===`Compiled`?Gf(x).pipe(B(Nf)):Gf(x).pipe(Jt(e=>H(()=>{ce=e})),B(Nf)),Qe=v===void 0||e.execution?._tag===`Compiled`?H(()=>Vf(x)).pipe(B(ha(Nf))):H(()=>Vf(x)).pipe(Jt(e=>H(()=>{T(e)&&(ce=e.value)})),B(ha(Nf))),tt=v===void 0?e=>Ie(t=>t.status===`active`?e(t.state).pipe(B(e=>({status:`active`,state:e}))):A(void 0)).pipe(E):t=>Oi(w).pipe(P(n=>Ie(e=>e.status===`active`?t(e.state).pipe(B(e=>({status:`active`,state:e}))):A(void 0)).pipe(Jt(t=>H(()=>{e.inspection?.kind!==`Machine`&&t?.status===`active`&&v.publishUnsafe({_tag:`StateChanged`,subject:y,before:n.snapshot.state,after:t.state,causedByDeliveryId:ce!==void 0&&Mf(ce)?ce.inspection?.deliveryId:void 0})})))),E),nt={...Oe,...e.execution?._tag===`Compiled`&&!e.execution.childless?{ownedChildren:ye}:void 0,...Xe,receive:Ze,poll:Qe,state:Oi(w).pipe(B(e=>e.snapshot.state)),setState:ze,updateState:tt},rt=Bi(w,e=>e.snapshot.status===`active`?e.changes===void 0?et({replay:1}).pipe(B(t=>[t,{...e,changes:t}])):A([e.changes,e]):A([void 0,e])),it=Vt(Ii(function*(){let e=yield*rt;if(e===void 0)return _t((yield*Oi(w)).snapshot);let t=yield*_n(e),n=yield*Oi(w);return n.snapshot.status===`active`?_t(n.snapshot).pipe(In(Gt(_a(Ae(t))).pipe(oa(e=>e.revision>n.revision),de(e=>e.snapshot)))):_t(n.snapshot)})),at={id:_,sessionId:g,...v===void 0?void 0:{inspectionSubject:y,sendInspected:fe},state:Oi(w).pipe(B(e=>e.snapshot.state)),snapshot:Oi(w).pipe(B(e=>e.snapshot)),changes:it,emissions:S.stream,join:gr(re),stop:Ye,send:he.send,...me===void 0?void 0:{[Af]:me},child:ve,childChanges:ge};o!==void 0&&!o(at)?yield*le:a!==void 0&&(yield*a(at,le)),s!==void 0&&(yield*Xf(s,{status:`active`,state:je}));let ot=e=>{switch(e._tag){case`Stopped`:return Ue;case`Done`:return Ge(e.output);case`Failure`:return We(e.cause)}},st=(e,t)=>{switch(e._tag){case`Stopped`:return Ke(t);case`Done`:return Je(t,e.output);case`Failure`:return qe(t,e.cause)}},ct=e=>n===!0?u(e,{startImmediately:!0}):Nt(e,{startImmediately:!0}),lt=yield*ie(ne),ut=Ve(lt)?yield*Mr(t=>t(C(()=>e.run(nt))).pipe($e,P(e=>Qi(ne,se(e)?{_tag:`Failure`,cause:e.cause}:{_tag:`Done`,output:e.value})))).pipe(ct):void 0;return yield*ct(Mr(e=>Ii(function*(){let t=T(lt)?yield*lt.value:yield*e(gr(ne)),n=yield*ot(t);return ut!==void 0&&(yield*bi(ut)),n===void 0?yield*ae:yield*st(t,n)}))),at}),Np=((e,t)=>e.execution?._tag===`Compiled`?Ap(e,t):Mp(e,t)),Pp=Zf(Np,jp),Fp=new WeakMap,Ip=e=>C(()=>{e.closed=!0;let t=Array.from(e.live).reverse();return e.live.clear(),jn(t,e=>e.stop,{discard:!0})}),Lp=()=>{let e=new Set,t={live:e,hooks:{onReadySync:n=>!t.closed&&(e.add(n),!0),onStopSync:t=>{e.delete(t)}},closed:!1};return t},Rp=e=>P(la,t=>{let n=Fp.get(t);if(n!==void 0)return e(n.hooks);let r=Lp();return Fp.set(t,r),k(ur(t,Ip(r)),e(r.hooks))});Sn(function*(e,t,n){let r=yield*Pp,i=n===void 0?{detached:!0,runtime:r}:{...n,detached:!0,runtime:r};return t===`generic`?yield*Rp(t=>Mp(e,{...i,...t})):t===`compiled`?e.execution?._tag===`Compiled`?yield*Rp(t=>Ap(e,{...i,...t})):yield*gn(Error(`Machine cannot force the compiled runtime for generic process logic`)):yield*Rp(t=>Np(e,{...i,...t}))});var zp=Sn(function*(e,t){let n=yield*Pp;return yield*Rp(r=>Np(e,t===void 0?{detached:!0,runtime:n,...r}:{...t,detached:!0,runtime:n,...r}))}),Bp=Sn(function*(e,t,n){let r=yield*Pp,i=yield*r.nextSessionId,a=yield*Sf(i);r.inspection=a;let o=cp(),s=yield*ra(),c=n===void 0?{detached:!0,emissions:o,runtime:r,sessionId:i,inspectionRoot:!0,origin:{_tag:`Root`}}:{...n,detached:!0,emissions:o,runtime:r,sessionId:i,inspectionRoot:!0,origin:{_tag:`Root`}},l=yield*Bt(Rp(n=>{let r={...c,...n};return t===`generic`?Mp(e,r):t===`compiled`?e.execution?._tag===`Compiled`?Ap(e,r):gn(Error(`Machine cannot force the compiled runtime for generic process logic`)):Np(e,r)}).pipe(Wr(e=>Pn(s,e))));return{id:n?.id??i,sessionId:i,changes:Vt(gr(s).pipe(B(e=>e.changes))),emissions:o.stream,inspection:a.stream,start:l}}),Vp=((e,t)=>Bp(e,`auto`,t));F({_tag:Bn(`MachineSnapshot`),version:Bn(2),active:Ye(F({path:R,value:U(Dr)})),completed:U(Ye(F({path:R,output:U(Dr)}))),history:U(mi(R,F({mode:ci([`shallow`,`deep`]),active:Ye(R),values:mi(R,Dr)})))});var Hp=(e,t,n)=>{let r=X(e,n);if(r.type===`compound`){let r=Ul(e,t,n);if(r===void 0)throw Error(`Machine expected completed state "${n}" to have an active child`);return Hp(e,t,r)}return r.output},Up=(e,t)=>Ii(function*(){let n=yield*Pl(e,t),r=new Map,i=new Set,a=t.completed??[];if(!Array.isArray(a))throw Error(`Machine snapshot completion metadata must be an array`);for(let t of a){if(typeof t!=`object`||!t||typeof t.path!=`string`)throw Error(`Machine snapshot contains malformed completion metadata`);let a=t.path;if(i.has(a))throw Error(`Machine snapshot contains duplicate completion "${a}"`);if(!n.active.has(a)||!Kl(e,n,a))throw Error(`Machine snapshot contains invalid completion "${a}"`);i.add(a);let o=Hp(e,n,a);if(o===void 0){if(t.output!==void 0)throw Error(`Machine snapshot contains an output for state "${a}" without an output schema`);r.set(a,void 0)}else r.set(a,yield*Hc(e,o,t.output,{boundary:`output`,state:a}))}return Tl(e,{...n,outputs:r})}).pipe(S(t=>Wp(e,t))),Wp=(e,t)=>{if(Re(t))return Je(b(t,t=>t instanceof J?t:new J({machineId:e.id,boundary:`configuration`,cause:pt(t)})));let n=Tt(t);return T(n)&&n.value instanceof J?V(n.value):V(new J({machineId:e.id,boundary:`configuration`,cause:t}))},Gp=e=>e.length===0?D:e.length===1?e[0]:gt(e,{discard:!0}),Kp=(e,t)=>({event:e.event,next:t(e.next),commands:e.commands,emittedEvents:e.emittedEvents,microsteps:e.microsteps.map(e=>({...e,transitions:e.transitions??[],next:t(e.next)})),done:e.done,output:e.output}),qp=new WeakMap,Jp=e=>{let t=qp.get(e);if(t!==void 0)return t;let n=Object.values(Y(e).handlers).some(e=>e.invoke!==void 0);return qp.set(e,n),n},Yp=A(M()),Xp=(e,t)=>{let n=ff(e),r=new WeakMap,i=t=>{let n=r.get(t.scope);return n===void 0&&(n=Id(e,t.scope),r.set(t.scope,n)),n},a=n=>{if(!t)return;let r=n.state();return kd(e,r)?Ad(e,r,Od).pipe(B(j)):void 0},o=e=>C(()=>c(e)??Yp),s=(e,t,r,a,s)=>{let c=a.commands.length===0?void 0:Ld(a.commands,e.scope),l=a.emittedEvents.length===0?void 0:Rd(a.emittedEvents,i(e)),u=()=>{let i=C(()=>(t&&e.completeMessage({before:r,plan:Kp(a,n.snapshot),after:s}),a.done?A(j(a.output)):o(e)));return l===void 0?i:l.pipe(k(i))},d=()=>{let t=e.commit(s),n=u(),r=t===void 0?n:t.pipe(k(n));return t===void 0&&l===void 0?r:e.runAfterChanges(r)};return c===void 0?d():e.runAfterChanges(c.pipe(k(C(d))))},c=(t,r)=>{let i=r;for(;;){let r;if(i!==void 0)r=i,i=void 0,t.beginMessage(r);else{let e=t.pollMessage();if(Ve(e))return;r=e.value}let a=Mf(r),c=a?r.event:r,l=t.state(),u;try{u=n.plan(t.executionState??n.fromConfiguration(Ml(e,l)),c,a,t.scope)}catch(e){return Ds(e)}if(t.executionState=u.next,u.microsteps.length===0){a&&t.completeMessage({before:l,plan:Kp(u,n.snapshot),after:l});continue}let d=n.snapshot(u.next);if(u.commands.length>0||u.emittedEvents.length>0||u.done)return s(t,a,l,u,d);let f=t.commit(d);if(f!==void 0)return t.runAfterChanges(f.pipe(k(C(()=>(a&&t.completeMessage({before:l,plan:Kp(u,n.snapshot),after:d}),o(t))))));a&&t.completeMessage({before:l,plan:Kp(u,n.snapshot),after:d})}};return{run:e=>Jf(a(e)??o(e),e.scope),runSync:(e,t)=>{let n=a(e);n!==void 0&&e.beginMessage(t);let r=n??c(e,t);return r===void 0?void 0:Jf(r,e.scope)}}},Zp=class{initialized=!1;initial;constructor(e){this.initial=e}},Qp=(e,t)=>{let n=ff(e);return r=>{let i=r.state();if(t&&kd(e,i))return Ad(e,i,Od).pipe(B(j));let a=r.scope,o=r.executionState,s=o instanceof Zp?o:new Zp;r.executionState=s;let c,l,u;return u=C(()=>{let t=r.pollMessage();if(Ve(t))return l=void 0,A(M());let o=t.value,s=Mf(o),d=s?o.event:o,f=i,p;try{p=n.plan(l??n.fromConfiguration(Ml(e,i)),d,s,a)}catch(e){return Ds(e)}if(l=p.next,p.microsteps.length===0)return s&&r.completeMessage({before:f,plan:Kp(p,n.snapshot),after:i}),u;let m=p.microsteps.some(e=>e.changed),h=m?p.microsteps.flatMap(e=>e.exitPaths):[],g=new Map;if(m){for(let e of p.microsteps)if(e.changed)for(let t of e.entryPaths)g.set(t,e.event)}let _=n.toConfiguration(p.next),v=n.snapshot(p.next),y=[];if(p.commands.length>0&&y.push(Ld(p.commands,a)),m){let e=r.ownedChildren.stopPaths(h);e!==void 0&&y.push(e)}let b=[];if(p.emittedEvents.length>0&&b.push(Rd(p.emittedEvents,c??=Id(e,a))),p.done)b.push(r.ownedChildren.stopAll());else if(m)for(let[t,n]of g){let i=Ep(e,a,r.ownedChildren,_,[t],n);i!==void 0&&b.push(i)}let ee=()=>{let e=r.commit(v);return i=v,e},te=()=>{let e=C(()=>(s&&r.completeMessage({before:f,plan:Kp(p,n.snapshot),after:v}),p.done?A(j(p.output)):u));return b.length===0?e:Gp(b).pipe(k(e))},x=()=>{let e=ee(),t=te(),n=e===void 0?t:e.pipe(k(t));return e===void 0&&b.length===0?n:r.runAfterChanges(n)};return y.length===0?x():r.runAfterChanges(Gp(y).pipe(k(C(x))))}),Jf(C(()=>{if(s.initialized)return u;let t=s.initial,o=t?.activeConfiguration??Ml(e,i);l=t?.configuration??n.fromConfiguration(o);let c=Ep(e,a,r.ownedChildren,o,t?.entryPaths??Cl(e,o),Od);return s.initial=void 0,s.initialized=!0,c===void 0?u:c.pipe(k(u))}),a)}},$p=e=>e.done?{state:e.state,done:!0,output:e.output}:{state:e.state,done:!1,output:void 0},em=(e,t)=>{let n=Jp(e),r=ff(e),i=t._tag===`Initial`?t.args:[],a=t._tag===`Initial`?r.initial:void 0,o=a===void 0?void 0:e=>{try{let t=a(i,e);e.inspectInitial(t.initialEntryPaths);let r=$p(t);return n?{...r,executionState:new Zp({configuration:t.configuration,activeConfiguration:t.activeConfiguration,entryPaths:t.initialEntryPaths})}:r}catch(e){throw Os(e)}},s=t=>a===void 0?Jf(Fd(Uu(e,t),...i).pipe(P(n=>{t.inspectInitial(n.initialEntryPaths,n.microsteps);let r=n.commands.length===0?void 0:Ld(n.commands,t),i=n.emittedEvents.length===0?void 0:Rd(n.emittedEvents,Id(e,t)),a=A($p(n));return r===void 0?i===void 0?a:i.pipe(k(a)):i===void 0?r.pipe(k(a)):r.pipe(k(i),k(a))})),t):Rr({try:()=>o(t),catch:Os});return{inspection:{kind:`Machine`,definition:e},execution:{_tag:`Compiled`,childless:!n,...t._tag===`Initial`?{initial:s}:{},...o===void 0?{}:{initialSync:o},drain:n?{_tag:`Owned`,run:Qp(e,t._tag===`Resume`)}:{_tag:`Owned`,...Xp(e,t._tag===`Resume`)}},initial:n=>t._tag===`Resume`?Jf(Up(e,t.snapshot),n):s(n).pipe(B(e=>e.state)),run:t=>Jf(Ii(function*(){let{completeMessage:r,pollMessage:i,receiveMessage:a,state:o,setState:s}=t;if(r===void 0||i===void 0||a===void 0)return yield*gn(Error(`Machine statechart started without acknowledged mailbox access`));let c,l=yield*o;if(kd(e,l))return yield*Ad(e,l,Od);if(!n){let n,o=M(),u;for(;c===void 0;){let d=T(o)?o.value:yield*a;o=M();let f=Mf(d),p=f?d.event:d,m=l,h;try{h=Pd(e,cl(n??Ml(e,l),t),p)}catch(e){return yield*Ds(e)}if(n=h.next,h.microsteps.length>0){let n=Tl(e,h.next);yield*Ld(h.commands,t),yield*s(n),l=n,h.emittedEvents.length>0&&(yield*Rd(h.emittedEvents,u??=Id(e,t))),h.done&&(c={output:h.output})}f&&r({before:m,plan:Kp(h,t=>Tl(e,t)),after:l}),c===void 0&&(o=yield*i,Ve(o)&&(n=void 0))}return c===void 0?yield*gn(Error(`Machine process stopped receiving events before reaching a terminal configuration`)):c.output}let u=t.ownedChildren;if(u===void 0)return yield*gn(Error(`Invoking statechart started without an owned child runtime`));let d=(n,r,i)=>Ep(e,t,u,n,r,i)??D,f=e=>u.stopPaths(e)??D;return yield*Ii(function*(){let n=yield*Pl(e,l);yield*d(n,Cl(e,n),Od),n=void 0;let o=M(),p;for(;c===void 0;){let m=T(o)?o.value:yield*a;o=M();let h=Mf(m),g=h?m.event:m,_=l,v;try{v=Pd(e,cl(n??Ml(e,l),t),g)}catch(e){return yield*Ds(e)}if(n=v.next,v.microsteps.length>0){let n=v.microsteps.some(e=>e.changed),r=v.microsteps.flatMap(e=>e.exitPaths),i=new Map;for(let e of v.microsteps)if(e.changed)for(let t of e.entryPaths)i.set(t,e.event);let a=Tl(e,v.next);if(yield*Ld(v.commands,t),n&&(yield*f(r)),yield*s(a),l=a,v.emittedEvents.length>0&&(yield*Rd(v.emittedEvents,p??=Id(e,t))),v.done)c={output:v.output},yield*u.stopAll();else if(n)for(let[e,t]of i)yield*d(v.next,[e],t)}h&&r({before:_,plan:Kp(v,t=>Tl(e,t)),after:l}),c===void 0&&(o=yield*i,Ve(o)&&(n=void 0))}return c===void 0?yield*gn(Error(`Machine process stopped receiving events before reaching a terminal configuration`)):c.output}).pipe(Wr(()=>u.stopAll()))}),t)}},tm=new WeakMap,nm=(e,...t)=>{if(t.length>0)return em(e,{_tag:`Initial`,args:t});let n=tm.get(e);if(n!==void 0)return n;let r=em(e,{_tag:`Initial`,args:t});return tm.set(e,r),r},rm=(e,t)=>em(e,{_tag:`Resume`,snapshot:t}),im=(e,...t)=>Vp(nm(e,...t),e.id===void 0?void 0:{id:e.id}),am=(e,t)=>zp(rm(e,t),e.id===void 0?void 0:{id:e.id}),om={atomic:[`schema`,`type`,`annotations`],final:[`schema`,`type`,`output`,`annotations`],compound:[`schema`,`type`,`states`,`annotations`],parallel:[`schema`,`type`,`output`,`states`,`annotations`],history:[`type`,`history`,`annotations`],choice:[`type`,`annotations`]},sm=[`title`,`description`,`documentation`],cm=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),lm=(e,t)=>{let n=typeof t==`symbol`?`[${String(t)}]`:t===``?`<empty>`:String(t);return e===``?n:`${e}.${n}`},$=(e,t,n)=>{throw Error(`${e} invalid state definition at "${t}": ${n}`)},um=e=>Number.isFinite(Number(e)),dm=e=>e.length===0||e.some(e=>e===`untagged`)?`untagged`:e.every(e=>e===`tagged`)?`tagged`:`opaque`,fm=(e,t)=>{if(t.has(e))return`opaque`;if(An(e)||Ke(e)||c(e)||sr(e)||ri(e)||Qe(e))return`tagged`;if(vi(e))return typeof e.literal==`string`||typeof e.literal==`number`?`tagged`:`untagged`;let n=new Set(t).add(e);return zi(e)?dm(e.types.map(e=>fm(e,n))):Mt(e)?fm(e.thunk(),n):Oe(e)?`opaque`:`untagged`},pm=(e,t=new Set)=>{if(t.has(e))return`opaque`;if(En(e)){let n=e.propertySignatures.find(({name:e})=>e===`_tag`)?.type;return n===void 0||xn(n)?`untagged`:fm(n,new Set(t).add(e))}let n=new Set(t).add(e);return zi(e)?dm(e.types.map(e=>pm(e,n))):Mt(e)?pm(e.thunk(),n):Oe(e)?`opaque`:`untagged`},mm=e=>O(e)&&pm(Ti(e.ast))!==`untagged`,hm=(e,t,n)=>{let r=lm(t,n);return typeof n==`symbol`?$(e,r,`state keys must be strings, not symbols`):typeof n==`number`?$(e,r,`state keys cannot use numeric forms`):n===``?$(e,r,`state keys cannot be empty`):n===`__proto__`?$(e,r,`the state key "__proto__" is not allowed`):n.includes(`.`)?$(e,r,`state keys cannot contain "."`):um(n)?$(e,r,`state keys cannot use numeric forms`):r},gm=(e,t,n,r)=>{(typeof n!=`object`||!n||Array.isArray(n))&&$(e,t,`${r} must be a plain record`);let i=Object.getPrototypeOf(n);i!==Object.prototype&&i!==null&&$(e,lm(t===`<root>`?``:t,`__proto__`),`${r} must not declare an implicit "__proto__" state key`)},_m=(e,t,n,r,i)=>{if(typeof n!=`object`||!n||Array.isArray(n)||!cm(n,r))return;let a=n[r];(typeof a!=`object`||!a||O(a)||a.type!==`history`)&&$(e,`${t}.${r}`,i)},vm=(e,t,n,r)=>{let i=om[r];for(let a of Reflect.ownKeys(n))i.includes(a)||$(e,t,`${r} states cannot declare property "${String(a)}"`)},ym=(e,t,n)=>{gm(e,`${t}.annotations`,n,`schema-less state annotations`);for(let r of Reflect.ownKeys(n))sm.includes(r)||$(e,`${t}.annotations`,`schema-less state annotations cannot declare property "${String(r)}"`),typeof n[r]!=`string`&&$(e,`${t}.annotations.${String(r)}`,`schema-less state annotation values must be strings`)},bm=(e,t,n,r,i=!1)=>{gm(e,n===``?`<root>`:n,t,`state trees`);for(let a of Reflect.ownKeys(t)){let o=i&&a===``?``:hm(e,n,a),s=t[a];if(O(s)){mm(s)||$(e,o,`state schemas must decode to an object with a required PropertyKey _tag`);continue}gm(e,o,s,`state nodes`);let c=s.type,l=c===`history`?`history`:c===`choice`?`choice`:c===`parallel`?`parallel`:c===`final`?`final`:cm(s,`states`)?`compound`:`atomic`;if(vm(e,o,s,l),l===`history`||l===`choice`){r||$(e,o,`${l} states must be declared below an active parent state`),cm(s,`annotations`)&&ym(e,o,s.annotations),l===`history`&&cm(s,`history`)&&s.history!==`shallow`&&s.history!==`deep`&&$(e,`${o}.history`,`history must be "shallow" or "deep"`);continue}let u=cm(s,`schema`);u&&!mm(s.schema)&&$(e,`${o}.schema`,`state schemas must decode to an object with a required PropertyKey _tag`),u&&cm(s,`annotations`)&&$(e,`${o}.annotations`,`schema-backed states must declare annotations on their schema`),!u&&cm(s,`annotations`)&&ym(e,o,s.annotations),l===`atomic`&&cm(s,`type`)&&s.type!==`active`&&$(e,`${o}.type`,`atomic state type must be "active"`),l===`final`&&s.type!==`final`&&$(e,`${o}.type`,`final state type must be "final"`),l===`compound`&&cm(s,`type`)&&s.type!==`active`&&$(e,`${o}.type`,`compound state type must be "active"`),l===`parallel`&&s.type!==`parallel`&&$(e,`${o}.type`,`parallel state type must be "parallel"`),(l===`final`||l===`parallel`)&&cm(s,`output`)&&!O(s.output)&&$(e,`${o}.output`,`state output must be an Effect Schema`),l===`compound`?(_m(e,o,s.states,`initial`,`active and choice child states cannot use the reserved target selector key "initial"`),u&&_m(e,o,s.states,`with`,`schema-backed compound child states cannot use the reserved local target selector key "with"`),bm(e,s.states,o,!0)):l===`parallel`&&(cm(s,`states`)||$(e,`${o}.states`,`parallel states must declare child regions`),_m(e,o,s.states,`initial`,`active and choice child states cannot use the reserved target selector key "initial"`),bm(e,s.states,o,!0))}},xm=e=>typeof e==`object`&&e?Object.freeze({...e}):e,Sm=e=>{let t={};for(let n of Object.keys(e)){let r=e[n];if(O(r)){Object.defineProperty(t,n,{value:r,enumerable:!0,configurable:!1,writable:!1});continue}let i=r,a={...i};`states`in i&&(a.states=Sm(i.states)),`annotations`in i&&(a.annotations=xm(i.annotations)),Object.defineProperty(t,n,{value:Object.freeze(a),enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(t)},Cm=e=>Sm(e),wm=(e,t=``)=>{if(O(e)||typeof e!=`object`||!e)return e;if(`~effect/Machine/State`in e&&e[`~effect/Machine/State`]===`~effect/Machine/State`&&`node`in e)return e.node;let n=e,r={...n};if(cm(n,`fields`)&&(cm(n,`schema`)&&$(`Machine.state`,t,`declare fields or schema, not both`),gm(`Machine.state`,t,n.fields,`state fields`),cm(n.fields,`_tag`)&&$(`Machine.state`,t,`state fields cannot declare _tag`),r.schema=ua(t,n.fields),delete r.fields),cm(n,`states`)){gm(`Machine.state`,t,n.states,`child states`);let e=Object.create(null);for(let r of Reflect.ownKeys(n.states))hm(`Machine.state`,t,r),e[r]=wm(n.states[r],r);r.states=e}return t===``?(bm(`Machine.state`,{"":r},``,!1,!0),Cm({"":r})[``]):r},Tm=`~effect/Machine`,Em=`~effect/Machine/ChildMachine`,Dm={...yi,...Hn,[Tm]:Tm,toJSON(){return{_id:`Machine`}}},Om=(e,t)=>{let n=Object.create(Dm);return n.states=e.states,n.root=e.root,n.events=e.events,n.internalEvents=e.internalEvents,n.emittedEvents=e.emittedEvents,n.parent=e.parent,n.input=e.input,n.id=e.id,n.initial=e.initial,n.initialDefinition=e.initialDefinition,n.stateNodes=e.stateNodes,n.handlers=t,Ic(e,n),n},km=e=>e.kind===`none`?Hs:Vs(e.kind,e.path,e.scope,e.updatePath),Am=e=>Object.freeze({path:e.path,kind:e.kind,scope:e.scope}),jm=e=>e.updatePath===void 0?e.kind===`update`&&e.path!==void 0?[e.path]:[]:[e.updatePath],Mm=(e,t,n,r,i)=>{if(typeof e!=`object`||!e||!N(e,`target`)||typeof e.target!=`function`)throw Error(`Machine transition for state "${r}" on "${String(i)}" requires a target selector`);let a=e.target(t);if(!Us(a))throw Error(`Machine transition for state "${r}" on "${String(i)}" must select exactly one target`);if(a.updatePath!==void 0){let e=n.byPath.get(a.updatePath);if(a.kind!==`state`&&a.kind!==`choice`||a.scope!==`local`&&a.scope!==`branch`||a.path===void 0||e===void 0||e.schema===void 0||e.type!==`compound`&&e.type!==`parallel`||!fl(r,e.path)||!fl(a.path,e.path))throw Error(`Machine updating owner "${a.updatePath}" must be a valued ancestor retained by source "${r}" and target "${a.path}"`)}return{...e,selection:a}},Nm=(e,t,n)=>{if(t.kind===`none`){if(e!==void 0)throw Error(`Machine targetless transition resolver must return undefined`);return}if(t.kind===`update`){if(!Gs(e)||e.path!==t.path)throw Error(`Machine state update for "${t.path}" must return its selected update builder`);return}if(t.updatePath!==void 0){if(!qs(e)||e.update.path!==t.updatePath)throw Error(`Machine target updating "${t.updatePath}" must return target construction .update(...)`)}else if(qs(e))throw Error(`Machine combined target requires an updating owner declaration`);if(e===void 0)return;let r=qs(e)?e.target:e,i=typeof r==`object`&&r&&N(r,`path`)&&typeof r.path==`string`?r.path:void 0,a=t.path===void 0?void 0:n.byPath.get(t.path),o=(t.scope===`local`||t.scope===`branch`)&&(a?.type===`compound`||a?.type===`parallel`);if(i===void 0||i!==t.path&&!(o&&fl(i,t.path)))throw Error(`Machine transition resolver selected "${t.path}" but constructed "${i??`<invalid>`}"`)},Pm=(e,t,n,r,i)=>{let a={...t,root:i===``?t.state:t.ancestors[``],decline:ec};delete a.target;let o=e.resolve(a,n);if(tc(o)){if(e.declinable!==!0)throw Error(`Machine transition for state "${i}" returned decline without declaring declinable: true`);return o}return Nm(o,e.selection,r),o},Fm=e=>e.kind===`update`?void 0:e.path,Im=e=>{let t=Number(e);return Number.isInteger(t)&&t>=0&&t<4294967295&&String(t)===e},Lm=(e,t,n)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Machine branching transition for state "${t}" on "${String(n)}" requires a branch record`);if(Object.getOwnPropertySymbols(e).length>0)throw Error(`Machine branching transition for state "${t}" on "${String(n)}" cannot use symbol keys`);let r=Object.keys(e);if(r.length===0)throw Error(`Machine branching transition for state "${t}" on "${String(n)}" requires a branch`);return Object.freeze(r.map(r=>{if(r.length===0||Im(r))throw Error(`Machine branching transition for state "${t}" on "${String(n)}" requires non-index string branch keys`);let i=e[r];if(typeof i!=`object`||!i||!N(i,`target`))throw Error(`Machine transition branch "${r}" requires a target selection`);let{target:a,title:o}=i;if(!Us(a))throw Error(`Machine transition branch "${r}" must select exactly one target`);if(o!==void 0&&(typeof o!=`string`||o.length===0))throw Error(`Machine transition branch "${r}" title must be a non-empty string`);return Object.freeze({key:r,title:o??r,selection:km(a)})}))},Rm=(e,t,n,r={},i)=>{let a=tu(r);if(e.kind===`choice`&&e.updatePath!==void 0){let{update:n,...r}=a;if(Reflect.ownKeys(r).length>0)throw Error(`Machine pseudo-state construction accepts no data`);let i=t.byPath.get(e.path);return Ks(oc(i.path,i.parent),iu(t,e.updatePath,n))}if(e.kind===`none`||e.kind===`history`||e.kind===`choice`){if(Reflect.ownKeys(a).length>0)throw Error(`Machine pseudo-state construction accepts no data`);if(e.kind===`none`)return;let n=t.byPath.get(e.path);return e.kind===`history`?nc(n.path,n.parent):oc(n.path,n.parent)}if(e.kind===`update`)return iu(t,e.path,a);if(e.path===``){if(Reflect.ownKeys(a).some(e=>e!==`input`))throw Error(`Machine initialize branches accept input only`);if(n.initialize===void 0)throw Error(`Machine root initialization is unavailable`);return n.initialize(a.input)}if(e.updatePath!==void 0){let{update:n,...r}=a;return Ks(ru(t,e.path,r,i),iu(t,e.updatePath,n))}return ru(t,e.path,a,i)},zm=(e,t,n,r,i)=>Object.freeze(Object.fromEntries(e.map((e,a)=>[e.key,o=>Js(t,a,e.key,e.selection.kind===`none`?Zs():Rm(e.selection,n,r,o,i))]))),Bm=(e,t,n)=>{if(t.kind===`none`){if(!Qs(e))throw Error(`Machine targetless branch must return its selected targetless builder`)}else{if(e===void 0)throw Error(`Machine transition branch selected "${t.path}" without constructing its target`);Nm(e,t,n)}},Vm=(e,t)=>({...e,root:t===``?e.state:e.ancestors[``]}),Hm=(e,t,n,r)=>{if(typeof e!=`object`||!e)throw Error(`Machine transition for "${n}" must be an object`);let i={...e},a=[`target`,`update`,`initialize`,`history`,`none`,`branches`,`data`,`decoded`,`resolve`,`guard`,`reenter`,`declinable`];for(let e of Reflect.ownKeys(i))if(typeof e!=`string`||!a.includes(e))throw Error(`Machine transition contains an unknown field`);for(let e of[`resolve`,`guard`])if(i[e]!==void 0&&typeof i[e]!=`function`)throw Error(`Machine transition ${e} must be a function`);let o=typeof i.guard==`function`?i.guard:void 0,s=typeof i.resolve==`function`?i.resolve:void 0;if(i.decoded!==void 0&&typeof i.decoded!=`boolean`)throw Error(`Machine decoded must be a boolean construction flag`);let c=Object.prototype.hasOwnProperty.call(i,`data`);if(i.decoded===!0&&!c)throw Error(`Machine decoded construction requires data`);if(c&&s!==void 0)throw Error(`Machine data and resolve are mutually exclusive`);let l=i.data,u=typeof l==`function`?l:()=>l,d=o!==void 0,f=d||i.declinable===!0;if(typeof i.branches==`string`){let e=t.branches.get(i.branches);if(e===void 0||s===void 0)throw Error(`Machine branching transition requires a registered group and resolver`);if([`target`,`update`,`initialize`,`history`,`none`,`data`,`decoded`].some(e=>i[e]!==void 0))throw Error(`Machine branching transition cannot redeclare its destination`);let a=Object.fromEntries(Object.entries(e).map(([e,i])=>[e,{title:i.title,target:Mm({target:()=>du(t,i)},void 0,r,n,e).selection}]));return{branches:()=>a,reenter:i.reenter,declinable:f,resolve:(e,t)=>d&&!o(e)?ec():s(e,t)}}let p=du(t,i);if(s!==void 0&&p.kind!==`none`)throw Error(`Machine advanced construction requires a declared branch group`);let m=i.initialize,h=m!==void 0;if(h&&(c||i.decoded!==void 0))throw Error(`Machine initialize accepts machine input instead of data`);if(h&&!t.input&&m!==!0)throw Error(`Machine initialize requires true when the machine declares no input`);let g=t.input?typeof m==`function`?m:()=>m:()=>void 0;return{target:()=>p,reenter:i.reenter,declinable:f,resolve:(e,a)=>{if(d&&!o(e))return ec();if(s!==void 0)return s(e,a);if(h)return Rm(p,r,t,{input:g(e)});let l=u(e);return Rm(p,r,t,p.updatePath===void 0?{...c?{data:l}:{},...i.decoded===void 0?{}:{decoded:i.decoded}}:p.kind===`choice`?{update:{data:l,decoded:i.decoded}}:{...l.target===void 0?{}:{data:l.target,decoded:i.decoded},update:{data:l.update,decoded:i.decoded}},n)}}},Um=(e,t,n,r,i)=>{let a=Hm(e,r,n,t);if(typeof a!=`object`||!a)throw Error(`Machine transition for state "${n}" on "${String(i)}" must be an object`);let o=a,s=o.reenter===!0,c=o.declinable===!0;if(N(o,`branches`)){let e=o;if(typeof e.branches!=`function`||typeof e.resolve!=`function`)throw Error(`Machine branching transition for state "${n}" on "${String(i)}" requires branches and resolve`);let a=e.resolve,l=Lm(e.branches(),n,i),u=Object.freeze({}),d=(e,o)=>{let s={...e,root:n===``?e.state:e.ancestors[``],decline:ec};delete s.target,s.select=zm(l,u,t,r,n);let d=a(s,o);if(tc(d)){if(!c)throw Error(`Machine branching transition for state "${n}" on "${String(i)}" returned decline without declaring declinable: true`);return{result:d,branchIndex:-1,branchKey:void 0}}if(!Ys(d)||d.owner!==u)throw Error(`Machine branching transition for state "${n}" on "${String(i)}" must select one declared branch`);let f=l[d.branchIndex];if(f===void 0||d.branchKey!==f.key)throw Error(`Machine branching transition returned invalid branch evidence`);return Bm(d.result,f.selection,t),{result:d.result,branchIndex:d.branchIndex,branchKey:d.branchKey}};return{reenter:s,declinable:c,targets:[...new Set(l.flatMap(e=>Fm(e.selection)===void 0?[]:[e.selection.path]))],branches:l.map(e=>Object.freeze({type:`branch`,key:e.key,title:e.title,target:Fm(e.selection),selection:Am(e.selection),updates:jm(e.selection)})),evaluate:d,transition:(e,t)=>d(e,t).result}}let l=Mm(a,void 0,t,n,i),u=(e,r)=>({result:Pm(l,e,r,t,n),branchIndex:0,branchKey:void 0});return{reenter:s,declinable:c,targets:Fm(l.selection)===void 0?[]:[l.selection.path],branches:[{type:`direct`,target:Fm(l.selection),selection:Am(l.selection),updates:jm(l.selection)}],evaluate:u,transition:(e,t)=>u(e,t).result}},Wm=(e,t,n,r)=>{let i=Object.create(null);for(let a of Reflect.ownKeys(e))i[a]=Um(e[a],t,n,r,a);return i},Gm=(e,t,n,r)=>{let i=(Array.isArray(e)?e:[e]).map(e=>{let i=fu(r,e,n,e=>Vm(e,n));for(let e of[`onElement`,`onDone`,`onFailure`,`onSnapshot`])i[e]!==void 0&&(i[e]=Um(i[e],t,n,r,e));return Cu(i,n)});return Tu(i,n),Array.isArray(e)?Object.freeze(i):i[0]},Km=(e,t,n,r,i,a)=>{for(let o of Object.keys(a)){let s=r===``?o:`${r}.${o}`;if(!N(n,o))throw Error(`Machine received handler for unknown state "${s}"`);let c=a[o];if(typeof c!=`object`||!c)throw Error(`Machine expected state "${s}" handler to be an object`);let{states:l,...u}=c;typeof u.history==`object`&&u.history!==null&&(u.history=Object.freeze(Object.fromEntries(Object.entries(u.history).map(([e,t])=>[e,typeof t==`object`&&t?Object.freeze({...t}):t]))));let d=u.on;if(typeof d==`object`&&d&&(u.on=Wm(d,t,s,i)),u.always!==void 0&&(u.always=Um(u.always,t,s,i,`always`)),u.onDone!==void 0&&(u.onDone=Um(u.onDone,t,s,i,`done`)),u.choice!==void 0&&(u.choice=Um(u.choice,t,s,i,`choice`)),u.invoke!==void 0&&(u.invoke=Gm(u.invoke,t,s,i)),t.byPath.get(s)?.type===`choice`&&(typeof u.choice!=`object`||u.choice===null||!N(u.choice,`transition`)||typeof u.choice.transition!=`function`||!N(u.choice,`targets`)||!Array.isArray(u.choice.targets)||u.choice.targets.length===0))throw Error(`Machine choice state "${s}" requires a transition`);if(e[s]=u,l!==void 0){let r=cc(s,n[o]);if(r.states===void 0)throw Error(`Machine expected state "${s}" to declare child states`);if(typeof l!=`object`||!l)throw Error(`Machine expected state "${s}" child handlers to be an object`);Km(e,t,r.states,s,i,l)}}},qm=e=>e===``?su:e,Jm=e=>{let t=!1;for(let n of e.stateNodes.byPath.values())if(n.type===`choice`){t=!0;break}if(!t)return;let n=fc(e),r=new Map;for(let e of n)e.trigger.type===`choice`&&r.set(e.source,e);for(let e of n)for(let t of e.branches){let n=t.updates[0],i=t.selection.path;if(t.selection.kind!==`choice`||n===void 0||i===void 0)continue;let a=[i],o=new Set;for(;a.length>0;){let t=a.shift();if(!o.has(t)){o.add(t);for(let i of r.get(t)?.branches??[]){let{kind:r,path:o}=i.selection;if(o!==void 0&&r!==`none`&&r!==`update`){if(r===`choice`)a.push(o);else if(!fl(o,n)){let r=i.type===`branch`?`branch "${i.key}"`:`transition`;throw Error(`Machine transition from "${qm(e.source)}" updates "${qm(n)}" before choice "${t}", whose ${r} targets "${qm(o)}" outside that owner`)}}}}}}},Ym=(e,t)=>(n=>{let r=Su(t.root,n),i=Object.assign(Object.create(Dm),e);if(Ic(e,i),i.states=Object.freeze({"":r.node}),i.stateNodes=lc(i.states),i.stateNodes.byPath.get(``).schema===void 0&&n.root!==void 0)throw Error(`Machine schema-less root cannot construct data`);let a=i.stateNodes.byPath.get(``).schema===void 0?()=>void 0:bu(n.root);i.initial=e=>({...ic(``,a({input:e})),input:{value:e}}),i.initialDefinition=Object.freeze({target:``,selection:Object.freeze({path:``,kind:`initial`,scope:`initial`})});let o=Object.create(null);Km(o,i.stateNodes,i.states,``,{...t,initialize:e=>i.initial(i.input===void 0?void 0:el(i,i.input,e))},{"":r.handlers});let s=Om(i,o);return Jm(s),s}),Xm=e=>{let t=wm(e),n=Zm();return Object.freeze({...n,"~effect/Machine/State":`~effect/Machine/State`,node:t})},Zm=()=>({path:(e=>e),get:((e,t)=>vc(e,t).pipe(ha(e=>e.value))),getWithParents:((e,t)=>{let n={};return vc(e,t,n).pipe(ha(e=>({value:e.value,parents:n})))}),getSnapshot:vc,matches:((e,t)=>T(vc(e,t)))}),Qm=e=>{if(Object.hasOwn(e,`initial`)||Object.hasOwn(e,`initialConfiguration`))throw Error(`Machine initial edges and root data belong in handle`);let t=Object.freeze({"":e.root.node}),n=Object.create(Hn);return n.states=t,n.root=e.root,n.events=e.events,n.internalEvents=e.internalEvents??Vc(`internal`,[]),n.emittedEvents=e.emittedEvents??Vc(`emitted`,[]),n.parent=e.parent,n.input=e.input,n.id=e.id,n.handlers=Object.create(null),n.handle=Ym(n,lu(e.root,e)),Fc(n),n},$m=e=>{for(let[t,n]of Object.entries(e))if(Object.hasOwn(n,`_tag`))throw Error(`Machine event "${t}" fields cannot declare _tag`);return Object.keys(e).length===0?[]:[Kn(e)]},eh=e=>Vc(`public`,$m(e)),th=(e,t)=>nh(e,t,e=>t.input===void 0?nm(t):nm(t,e)),nh=(e,t,n)=>({[Em]:Em,id:e,machine:t,[hu]:n}),rh=im,ih=am,ah=Xm,oh=Qm,sh=eh,ch=(e,t)=>{try{let n=jd(e,...t);return{machine:e,snapshot:n.done?{status:`done`,state:n.state,output:n.output}:{status:`active`,state:n.state}}}catch{return}},lh=(e,t)=>{try{let n=qi(Up(e,t));if(n._tag===`Failure`)return;let r=n.value;if(!kd(e,r))return{machine:e,snapshot:{status:`active`,state:r}};let i=qi(Ad(e,r,Od));return i._tag===`Success`?{machine:e,snapshot:{status:`done`,state:r,output:i.value}}:void 0}catch{return}},uh={spawn:()=>gn(Error(`Child operations are unavailable in a planned snapshot`)),sendTo:()=>V(new Ts),stop:()=>D},dh=(e,t)=>{if(e.snapshot.status!==`active`)return M();try{let n=e.machine,r=Ml(n,e.snapshot.state);for(let e of Cl(n,r)){let i=Hl(n,e);for(let a of Eu(i?.invoke)){if(!(`child`in a)||a.child.id!==t.id||a.child.machine!==t.machine)continue;let i=t.machine,o;`input`in a&&(o=typeof a.input==`function`?a.input({...ll(r)??Wu(n,r),children:uh,state:r.values.get(e),containingState:Sl(n,r,e),ancestors:xl(n,r,e),event:Od}):a.input);let s=ch(i,i.input===void 0?[]:[o]);return s===void 0?void 0:j(s)}}return M()}catch{return}},fh=class extends w(`ChildNotActiveError`){},ph=new WeakMap,mh=new WeakMap,hh=e=>{if(typeof WeakRef>`u`||typeof FinalizationRegistry>`u`)return tt(e);let t=ze(),n=new FinalizationRegistry(({entry:e,key:n})=>{let r=rt(t,n);T(r)&&r.value===e&&Lt(t,n)});return r=>{let i=rt(t,r);if(T(i)){let e=i.value.ref.deref();if(e!==void 0)return e}let a=e(r),o={ref:new WeakRef(a)};return ma(t,r,o),n.register(a,{key:r,entry:o}),a}},gh=(e,t)=>Gn(ut(t,e=>e.stop).pipe(Jt(t=>H(()=>e.setSelf(mr(t)))),P(()=>Xn))),_h=(e,t)=>gh(e,e.result(t).pipe(P(e=>e.start))),vh=(e,t,n)=>gh(e,ih(t,n)),yh=(e,t)=>`~effect-atom/atom/Atom/ServerValue`in e?e[Le](t):t(e),bh=(e,t)=>{let n;return r=>{let i=e(r);return n!==void 0&&n.inputs.length===i.length&&n.inputs.every((e,t)=>Object.is(e,i[t]))||(n={inputs:i,value:t(...i)}),n.value}},xh=e=>{let t;return()=>(t===void 0&&(t={value:e()}),t.value)},Sh=e=>e.snapshot,Ch=dn(e=>e.registry).pipe(y),wh=e=>C(()=>{let t=e.pending.shift();return t===void 0?(e.draining=!1,D):k(t,wh(e))}),Th=(e,t)=>{let n=e.get(t);return n===void 0&&(n={pending:[],draining:!1},e.set(t,n)),n},Eh=(e,t,n)=>On(n=>{let r=rr(n(e),()=>void 0),i=t.get(n.registry);return i===void 0||!i.draining?r:Dt(ha(n.self(),Qr),()=>ui(!0))},(r,i)=>{let a=r.get(e),o=r.get(Ch),s=Th(t,o);$n(a)||s.draining?(r.setSelf(ui(!0)),s.pending.push(kt(o,e).pipe(P(e=>n(e,i)),$e,B(e=>{let t=kr(e);r.setSelf(s.pending.length===0?t:Qr(t))}))),s.draining||(s.draining=!0,xr(wh(s)))):Ni(a)?r.setSelf(rr(a,()=>void 0)):Yr(n(a.value,i),{onExit:e=>r.setSelf(kr(e))})}).pipe(vn),Dh=e=>dn(t=>{let n=t(e);return $n(n)?ui(n.waiting):Ni(n)?Di(n.cause,{previous:t.self(),waiting:n.waiting}):n.value.status===`error`?Di(n.value.cause,{previous:t.self(),waiting:n.waiting}):mr(n.value.state,{waiting:n.waiting})}).pipe(gi(qe),wn(bh(t=>[yh(e,t)],e=>rr(e,e=>e.state)))),Oh=e=>dn(t=>{let n=t(e);if($n(n))return ui(n.waiting);if(Ni(n))return Di(n.cause,{previous:t.self(),waiting:n.waiting});if(Ve(n.value)){let e=t.self();return T(e)&&Ni(e.value)?e.value:mr(M(),{waiting:n.waiting})}return n.value.value.status===`error`?Di(n.value.value.cause,{previous:t.self(),waiting:n.waiting}):mr(j(n.value.value.state),{waiting:n.waiting})}).pipe(gi(qe),wn(bh(t=>[yh(e,t)],e=>rr(e,ha(e=>e.state))))),kh=(e,t)=>dn(n=>{let r=n(e);if($n(r))return ui(r.waiting);if(Ni(r))return Di(r.cause,{previous:n.self(),waiting:r.waiting});if(Ve(r.value))return mr(M());let i=r.value.value,a=Fn(i.child(t)),o=Yr(xe.pipe(k(i.childChanges(t).pipe(dt(e=>H(()=>n.setSelf(mr(e))))))));return n.addFinalizer(o),mr(a)}).pipe(vn),Ah=(e,t)=>Of(e)?e[Df](()=>t(Fn(e.snapshot))):Yr(e.changes.pipe(dt(e=>H(()=>t(e))))),jh=(e,t,n)=>{let r=dn(t=>{let n=t(e);if($n(n))return ui(n.waiting);if(Ni(n))return Di(n.cause,{previous:t.self(),waiting:n.waiting});if(Ve(n.value))return mr(M());let r=n.value.value;return t.addFinalizer(Ah(r,e=>t.setSelf(mr(j(e))))),mr(j(Fn(r.snapshot)))}).pipe(wn(bh(()=>[],()=>{let e=n();return e===void 0?ui(!0):mr(ha(e,Sh),{waiting:!0})}))),i=new WeakMap,a=e=>T(e)?A(e.value):V(new fh({id:t.id})),o=Eh(e,i,(e,t)=>P(a(e),e=>e.send(t))),s=Eh(e,i,(e,t)=>P(a(e),e=>e.stop)),c=Mh(e,n);return{ref:e,snapshot:r,result:Oh(r),send:o,stop:s,child:c}},Mh=(e,t)=>{let n=new WeakMap;return r=>{let i=n.get(r.machine);if(i===void 0){let a=r.machine,o=tt(n=>{let r=th(n,a);return jh(kh(e,r),r,xh(()=>{let e=t();return e===void 0||Ve(e)?e:dh(e.value,r)}))});i=e=>o(e),n.set(a,i)}return i(r.id)}},Nh=(e,t,n)=>{let r=vn(e),i=dn(e=>{let t=e(r);if($n(t))return ui(t.waiting);if(Ni(t))return Di(t.cause,{previous:e.self(),waiting:t.waiting});let n=t.value;e.addFinalizer(Ah(n,t=>e.setSelf(mr(t,{waiting:t.status===`active`}))));let i=Fn(n.snapshot);return mr(i,{waiting:i.status===`active`})}).pipe(wn(bh(()=>[],()=>{let e=n();return e===void 0?ui(!0):mr(Sh(e),{waiting:!0})}))),a=new WeakMap,o=Eh(r,a,(e,t)=>e.send(t)),s=Eh(r,a,(e,t)=>e.stop),c=Mh($t(r,j),()=>{let e=n();return e===void 0?void 0:j(e)}),l={ref:r,snapshot:i,result:Dh(i),send:o,stop:s,child:c};return mh.set(l,t),l},Ph=(e,t)=>vc(e,t).pipe(ha(e=>e.value)),Fh=(e,t)=>vc(e,t),Ih=(e,t)=>$t(e,t).pipe(gi(qe),wn(bh(t=>[yh(e,t)],e=>rr(e,t)))),Lh=new WeakMap,Rh=(e,t,n,r)=>{let i=Lh.get(e);i===void 0&&(i=new Map,Lh.set(e,i));let a=i.get(t);a===void 0&&(a=new Map,i.set(t,a));let o=a.get(n);if(o!==void 0)return o;let s=r();return a.set(n,s),s},zh=(e,t)=>Rh(e,`select`,t,()=>Ih(e.result,e=>Ph(e,t))),Bh=(e,t)=>Rh(e,`selectSnapshot`,t,()=>Ih(e.result,e=>Fh(e,t))),Vh=(e,t)=>Rh(e,`selectChild`,t,()=>Ih(e.result,g(e=>Ph(e,t)))),Hh=(e,t)=>Rh(e,`selectSnapshotChild`,t,()=>Ih(e.result,g(e=>Fh(e,t)))),Uh=(e,t)=>Rh(e,`matches`,t,()=>Ih(e.result,e=>T(vc(e,t)))),Wh=(e,t)=>Rh(e,`matchesChild`,t,()=>Ih(e.result,xt(e=>T(vc(e,t))))),Gh=(e,t,n)=>{let r=e.atom(()=>rh(t,...n)),i=Nh(e.atom(e=>_h(e,r)),t,xh(()=>ch(t,n)));return ph.set(i,r),i},Kh=(e,t,n)=>Nh(e.atom(e=>vh(e,t,n)),t,xh(()=>lh(t,n))),qh=(e,t,n)=>{let r={owner:e,source:t},i=Xe(t,e=>e(r.source),{initialValueTarget:t}).pipe(gi((e,t)=>r.source.equals(e,t)),wn(e=>yh(r.source,e)));return n!==void 0&&(i=i.pipe(We(n))),i},Jh=(e,t)=>{let n=hh(t=>({bridge:e(t)})),r={};for(let e of Object.keys(t.atoms)){let i=t.atoms[e];r[e]=hh(r=>{let a=n(r);return qh(a,i(a.bridge),t.label?.(r,e))})}return r},Yh=e=>{let t=((t,...n)=>Gh(e,t,n));return{make:t,factory:(e=>(...n)=>t(e,...n)),resume:((t,n)=>Kh(e,t,n)),family:((t,n)=>Jh(n=>Gh(e,t,[n]),n))}};ii(2,zh),ii(2,Bh),ii(2,Vh),ii(2,Hh),ii(2,Uh),ii(2,Wh);var Xh=Yh;F({family:Ma,generation:Ui(ni),secret:I});var Zh=z(I,Wt(`IncarnationId`)),Qh=F({incarnation:Zh,user:Ia});Ge()(`@deslop/auth/services/tokens/schema/CurrentOwner`),F({client_name:L(R.check(Nr(100))),redirect_uris:La.fields.redirects,token_endpoint_auth_method:U(Bn(`none`))}),F({client_id:Pa.check(ct(),Nr(2048)),redirect_uri:L(R),state:L(R)}),F({code_challenge:L(I),code_challenge_method:L(R),response_type:L(R),scope:L(R)});var $h=F({challenge:I,clientId:Pa.check(ct()),clientName:R,parent:L(Ma),redirectUri:I,state:L(I)});Kn({Fresh:{owner:Qh,request:$h},Used:{family:Ma}});var eg=F({clientId:Pa.check(ct()),clientName:R});F({client_id:Pa.check(ct(),Nr(2048)),scope:L(R)}),F({client_id:Pa.check(ct()),device_code:I,grant_type:Bn(`urn:ietf:params:oauth:grant-type:device_code`)}),F({grant_type:R}),aa([F({client_id:Pa.check(ct()),code:I,code_verifier:I,grant_type:Bn(`authorization_code`),redirect_uri:L(R)}),F({client_id:L(Pa),grant_type:Bn(`refresh_token`),refresh_token:I})]);var tg=F({access_token:I,expires_in:Aa,refresh_token:I,scope:Bn(`deslop`),token_type:Bn(`Bearer`)});Kn({Granted:{tokens:tg},Replayed:{message:R}}),F({address:L(R),userAgent:L(R)});var ng=ci([`Code`,`GitHub`,`Passkey`]),rg={address:wr(R),client:R,device:R,expiresAt:Mn,family:Ma,hash:Ln(R),incarnation:Ln(Qh.fields.incarnation),lastActive:Mn,userId:Ia.fields.id,userName:Ia.fields.name},ig=class extends xi(`BrowserSession`)({...rg,via:ng}){static table=`browser_sessions`},ag=class extends xi(`AppGrant`)({...rg,clientId:Pa.check(ct()),generation:wi,parent:wr(ig.fields.family)}){static table=`app_grants`};xi(`SpentRefreshToken`)({family:ag.fields.family,hash:Ln(R)}),xi(`SigningKey`)({privateJwk:Ln(zr(Xr(Pi)))}),F({family:Ma,now:Mn}),F({now:Mn,owner:Qh});var og=class extends xi(`SignedInApp`)({...mn(oi(ag),[`address`,`client`,`device`,`family`,`lastActive`,`parent`]),icon:wr(R),kind:ci([`App`,`Browser`])}){};F({client_id:Pa.check(ct()),token:I});var sg=z(R,Wt(`PasskeyId`)),cg=z(R,Wt(`WebAuthnUserHandle`)),lg=z(R,Wt(`RelyingPartyId`)),ug=ci([`ble`,`cable`,`hybrid`,`internal`,`nfc`,`smart-card`,`usb`]),dg=Bn(`public-key`),fg=ci([`required`,`preferred`,`discouraged`]),pg=F({id:sg,transports:U(it(Ye(ug))),type:dg}),mg=F({attestation:U(ci([`direct`,`enterprise`,`indirect`,`none`])),authenticatorSelection:U(F({authenticatorAttachment:U(ci([`cross-platform`,`platform`])),requireResidentKey:U(Dn),residentKey:U(ci([`discouraged`,`preferred`,`required`])),userVerification:U(fg)})),challenge:R,excludeCredentials:U(it(Ye(pg))),pubKeyCredParams:it(Ye(F({alg:Li,type:dg}))),rp:F({id:U(lg),name:R}),timeout:L(z(Li,$i(ar))),user:F({displayName:R,id:cg,name:R})}),hg=F({allowCredentials:U(it(Ye(pg))),challenge:R,rpId:U(lg),timeout:L(z(Li,$i(ar))),userVerification:U(fg)}),gg=U(ci([`cross-platform`,`platform`])),_g=F({authenticatorAttachment:gg,clientExtensionResults:F({}),id:sg,rawId:sg,response:F({attestationObject:R,clientDataJSON:R,transports:L(Ye(R))}),type:dg}),vg=F({authenticatorAttachment:gg,clientExtensionResults:F({}),id:sg,rawId:sg,response:F({authenticatorData:R,clientDataJSON:R,signature:R,userHandle:U(cg)}),type:dg});F({challenge:R});var yg=class extends xi(`Passkey`)({addedFrom:R,counter:Ln(wi),id:sg.check(ct()),incarnation:Ln(Qh.fields.incarnation),publicKey:Ln(I),synced:$r,transports:Ln(zr(Ye(ug))),userId:Ln(Ia.fields.id),userName:Ln(Ia.fields.name)}){static table=`passkeys`};F({id:yg.fields.id});var bg=F({response:_g}),xg=F({next:L(I.check(Nr(2048))),response:vg}),Sg=ci([`Admin`,`Member`,`Waiting`]),Cg=F({...Ia.fields,fullName:L(R),role:Sg}),wg=F({...Cg.fields,via:ng}),Tg=F({...Cg.fields,since:z(Li,$i(Gr(Cn),{decode:Or(e=>z(e,zt(e=>e!==0),ha(Zt))),encode:Or(e=>x(e,{onNone:()=>0,onSome:_}))}))}),Eg=ci([`Waiting`,`Allowed`]);xi(`Member`)({fullName:wr(R),id:Ia.fields.id,incarnation:Ln(Qh.fields.incarnation),name:Ia.fields.name,since:Mn,status:Eg}),F({id:Fa,login:I,name:fr(R)});var Dg=F({allow:Dn,id:ja});ci([`Session`,`Token`]);var Og=ci([`App`,`Browser`]),kg=z(R,Wt(`SignInCode`)),Ag=F({address:L(R),clientName:R,device:R,expiresAt:Mn,icon:L(R),id:kg.check(ct()),kind:Og}),jg=Kn({Decided:{},Expired:{},Waiting:{request:Ag}});Kn({Browser:{next:L(R)},Client:{request:$h},Device:{request:eg}}),Kn({Denied:{},Granted:{tokens:tg},Redirect:{url:I},Session:{next:L(R),seconds:Aa,token:I}}),F({next:L(I.check(Nr(2048)))});var Mg=F({request:kg.check(ct(),Nr(20))}),Ng=F({code:kg.check(ct(),Nr(20))}),Pg=F({...Mg.fields,accept:Dn}),Fg=class extends lr()(`@deslop/auth/rpcs/RpcOwner`,{error:G}){},Ig=class extends qr(Zi(`sign-ins.lookup`,{error:G,payload:Ng,stream:!0,success:Gr(Ag)}),Zi(`sign-ins.answer`,{error:G,payload:Pg}),Zi(`people.watch`,{error:G,stream:!0,success:Ye(Tg)}),Zi(`people.admit`,{error:G,payload:Dg,success:Tg}),Zi(`tokens.watchApps`,{error:G,stream:!0,success:Ye(og.json)}),Zi(`passkeys.watch`,{error:G,stream:!0,success:Ye(yg.json)}),Zi(`passkeys.registration`,{error:G,success:mg}),Zi(`passkeys.add`,{error:G,payload:bg})).middleware(Ha).middleware(Fg).merge(qr(Zi(`people.account`,{error:G,stream:!0,success:wg}),Zi(`sign-ins.status`,{error:G,payload:Mg,stream:!0,success:jg}))){};fn(10);function Lg(e){return s(bn(/[^a-z]/giu,``)(e))}function Rg(e){return Br(e,pn)}Sn(function*(e,t,n){return Ve(Rg(n.response_type))?yield*G.make({message:`Send response_type=code`}):ue(n.response_type,`code`)?Ve(n.code_challenge)||!ue(n.code_challenge_method,`S256`)?yield*G.make({message:`Send a PKCE code_challenge with code_challenge_method=S256`}):z(n.scope,x({onNone:o,onSome:jt(` `)}),Ri(pn),or(e=>e===`deslop`||e===`offline_access`))?$h.make({challenge:yield*ir(n.code_challenge),clientId:e.client_id,clientName:t.clientName,parent:M(),redirectUri:t.redirectUri,state:Rg(e.state)}):yield*G.make({error:`invalid_scope`,message:`Only the deslop scope is supported`}):yield*G.make({error:`unsupported_response_type`,message:`Only response_type=code is supported`})});function zg(e,t){let n=`mp281x.xyz`;return ge(ye(e),{onFailure:l,onSuccess:e=>(e.origin===new URL(t).origin||e.protocol===`https:`&&(e.hostname===n||Me(`.${n}`)(e.hostname)))&&tn(e.username)&&tn(e.password)})}var Bg=`adding-passkey`,Vg=Ee(sa),Hg=F({code:L(R),error:L(R),next:L(R),request:L(kg),"sign-out":L(R)});io(`@deslop/auth`);var Ug=class extends Un()(`@deslop/auth/lib/auth/RpcClient`,{group:Ig.middleware(Za),protocol:ro}){},Wg=y(Ug.runtime.atom(z(Vo(Ug,`people.account`),Bo,de(j),vr(`AuthError`,()=>ve(M()))))),Gg={accept:Dn,request:Ag},Kg=Xh(Ug.runtime).make(oh({branches:{looked:{found:{target:`Code.Found`},missing:{target:`Code.Missing`}}},events:sh({Answered:Gg,Typed:{typed:R}}),root:ah({states:{Code:{fields:{code:kg},states:{Failed:{fields:{message:R}},Found:{fields:{request:Ag}},Looking:{},Missing:{}}},Typing:{fields:{answered:L(F(Gg)),typed:R}}}}),streams:{lookup:e=>Bo(Vo(Ug,`sign-ins.lookup`,{code:e}))}}).handle({initial:{data:{answered:M(),typed:``},target:`Typing`},on:{Answered:{data:e=>({answered:j({accept:e.event.accept,request:e.event.request}),typed:``}),target:`Typing`},Typed:{data:e=>({answered:M(),typed:e.event.typed}),target:`Typing`}},states:{Code:{initial:{target:`Code.Looking`},invoke:{input:e=>e.state.code,onDone:{none:!0},onElement:{branches:`looked`,resolve:e=>x(e.element,{onNone:()=>e.select.missing(),onSome:t=>e.select.found({data:{request:t}})})},onFailure:{data:e=>({message:e.error.message}),target:`Code.Failed`},src:`lookup`},states:{Failed:{},Found:{},Looking:{},Missing:{}}},Typing:{always:{data:e=>({code:kg.make(e.state.typed)}),guard:e=>Ze(e.state.typed)>=8,target:`Code`}}}}));Kn({Checking:{},Failed:{message:R},Found:{},Missing:{},Typing:{}});var qg=je(Kg.result,rr(e=>{if(e.state.path===`Typing`)return{answered:e.state.value.answered,pending:M(),state:{_tag:`Typing`},typed:e.state.value.typed};let t={answered:M(),pending:M(),typed:e.state.value.code};return e.state.state.path===`Code.Found`?{...t,pending:j(e.state.state.value.request),state:{_tag:`Found`}}:e.state.state.path===`Code.Failed`?{...t,state:{_tag:`Failed`,message:e.state.state.value.message}}:e.state.state.path===`Code.Looking`?{...t,state:{_tag:`Checking`}}:{...t,state:{_tag:`Missing`}}})),Jg=tt(e=>on(t=>{t.set(Kg.send,{_tag:`Typed`,typed:Lg(e)})})),Yg=y(Ho(Ug,`people.watch`)),Xg=y(Ho(Ug,`tokens.watchApps`)),Zg=tt(e=>Ug.runtime.fn(t=>P(Ug,n=>n(`people.admit`,{allow:t,id:e})))),Qg=tt(e=>Ug.runtime.atom(z(Vo(Ug,`sign-ins.status`,{request:e}),Bo,Te(t=>z(Zr(t),pr(`Decided`,()=>H(()=>location.assign(`/auth/continue?${new URLSearchParams({request:e})}`))),nr(()=>D))))));function $g(e){return`${kn(0,4)(e)}-${kn(4)(e)}`}function e_(e){return`${location.origin}/?code=${e}`}var t_=on(Ct(at(`1 minute`),()=>St)),n_=on(Ct(at(`1 second`),()=>St));function r_(e,t){return`${e} · ${t}`}var i_=Ug.runtime.fn((e,t)=>z(Ug,P(t=>t(`sign-ins.answer`,{accept:e.accept,request:e.request.id})),k(H(()=>t.set(Kg.send,{_tag:`Answered`,...e})))));function a_(e){return N(e.cause,`name`)&&e.cause.name===`NotAllowedError`}var o_=Sn(function*(e){return e.status===429?yield*G.make({message:`Too many tries; wait a minute and try again`}):yield*G.make({message:(yield*ot(F({error_description:R}))(e)).error_description})}),s_=Vg.fn(e=>Ai(Ii(function*(){let t=yield*vt,n=yield*t.get(`/auth/passkey`);if(n.status!==200)return yield*o_(n);let r=yield*ot(hg)(n),i=yield*le(hg)(r),a=yield*ln(bt({catch:e=>G.make({cause:e,message:`No passkey was used`}),try:()=>xs({optionsJSON:i})}),a_,()=>ti),o=yield*z(ft(`/auth/passkey`),wt(xg)({next:e,response:yield*ae(xg.fields.response)(a)}),P(e=>t.execute(e)),P(Sn(function*(e){return e.status===200?yield*ot(F({next:L(R)}))(e):yield*o_(e)})));yield*H(()=>x(o.next,{onNone:()=>location.reload(),onSome:e=>location.assign(e)}))}),e=>h(G)(e)?e:G.make({cause:e,message:`Cannot sign in with a passkey`}))),c_=y(Ho(Ug,`passkeys.watch`)),l_=y(Ug.runtime.fn(Sn(function*(){let e=yield*Ug,t=yield*e(`passkeys.registration`,void 0),n=yield*le(mg)(t);yield*e(`passkeys.add`,{response:yield*z(bt({catch:e=>G.make({cause:e,message:`No passkey was added`}),try:()=>gs({optionsJSON:n})}),ln(a_,()=>ti),P(Yt(_g)))})}))),u_=on(!1),d_=tt(e=>on(t=>{sessionStorage.getItem(Bg)!==null&&(sessionStorage.removeItem(Bg),e!==`Code`&&(t.set(u_,!0),t.set(l_,void 0)))})),f_=Ft(()=>Rr({catch:e=>G.make({cause:e,message:`Cannot start GitHub sign-in`}),try:()=>{sessionStorage.setItem(Bg,`true`),location.assign(`/auth/github`)}})),p_=Ft(()=>Rr({catch:e=>G.make({cause:e,message:`Cannot start GitHub sign-in`}),try:()=>location.assign(`/auth/github${location.search}`)})),m_=Ft(e=>Rr({catch:e=>G.make({cause:e,message:`Cannot start the sign-in`}),try:()=>location.assign(x(e,{onNone:()=>`/auth/code`,onSome:e=>`/auth/code?${new URLSearchParams({next:e})}`}))}));function h_(e){return z(vt.use(e=>Ir(e).post(`/auth/sign-out`)),k(H(()=>location.replace(z(e,Br(e=>zg(e,Ra)),Dt(()=>location.pathname))))),Ai(e=>G.make({cause:e,message:`Cannot sign out: ${e.message}`})))}var g_=tt(e=>Vg.atom(h_(e))),__=Vg.fn(h_);export{$o as A,vo as B,p_ as C,Qo as D,Lg as E,To as F,Da as G,to as H,So as I,Ca as J,Ea as K,wo as L,Jo as M,Ko as N,rs as O,jo as P,Co as R,n_ as S,g_ as T,Ja as U,no as V,Oa as W,wa as Y,c_ as _,Zg as a,$g as b,Kg as c,f_ as d,i_ as f,s_ as g,t_ as h,l_ as i,is as j,as as k,m_ as l,__ as m,Wg as n,e_ as o,Jg as p,Ta as q,u_ as r,Xg as s,Hg as t,qg as u,Yg as v,r_ as w,d_ as x,Qg as y,ko as z};