@rizom/brain 0.2.0-alpha.698 → 0.2.0-alpha.699

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.
Files changed (21) hide show
  1. package/dist/brain.js +10 -9
  2. package/dist/chunks/{app-7hfapsb7.js → app-v4c23vsz.js} +2 -2
  3. package/dist/chunks/{index-g6z07jvd.js → index-24kr1bk2.js} +2 -2
  4. package/dist/chunks/{index-cq4t2sgx.js → index-xtt5r7ac.js} +3 -3
  5. package/dist/chunks/{index-cq4t2sgx.js.map → index-xtt5r7ac.js.map} +1 -1
  6. package/dist/chunks/{package-nq1w69ja.js → package-pq77nhmn.js} +3 -3
  7. package/dist/chunks/{package-nq1w69ja.js.map → package-pq77nhmn.js.map} +1 -1
  8. package/dist/model.js +9 -8
  9. package/dist/model.js.map +3 -3
  10. package/dist/testing.js +1 -1
  11. package/dist/ui/{studio-app-facf8334864f215a6915e667bb79ae1abc1854920910d6006574890ee8febb1c.css → studio-app-0068b5da5df918279108df063912cabe667a349d3750660b4198df5b66931453.css} +1 -0
  12. package/dist/ui/{studio-app-fcvgp0a0.js → studio-app-rzcewqfr.js} +2 -2
  13. package/dist/ui/studio-asset-manifest.json +9 -9
  14. package/dist/ui/studio-chunks/{account-view-qfahm2ry.js → account-view-dhdr1svz.js} +1 -1
  15. package/dist/ui/studio-chunks/{main-7e9nhfhz.js → main-b3t0xyrg.js} +2 -2
  16. package/dist/ui/studio-chunks/{main-7e9nhfhz.js.map → main-b3t0xyrg.js.map} +3 -3
  17. package/package.json +1 -1
  18. /package/dist/chunks/{app-7hfapsb7.js.map → app-v4c23vsz.js.map} +0 -0
  19. /package/dist/chunks/{index-g6z07jvd.js.map → index-24kr1bk2.js.map} +0 -0
  20. /package/dist/ui/{studio-app-fcvgp0a0.js.map → studio-app-rzcewqfr.js.map} +0 -0
  21. /package/dist/ui/studio-chunks/{account-view-qfahm2ry.js.map → account-view-dhdr1svz.js.map} +0 -0
package/dist/model.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import"./chunks/index-g6z07jvd.js";import{C as G3,D as $ni,F as pni,H as $ke}from"./chunks/index-me2q3y9y.js";import{J as Ine,K as hD}from"./chunks/index-8cpdhssj.js";import{L as Zle}from"./chunks/index-9deh2vm3.js";import"./chunks/index-77mhdfp8.js";import"./chunks/index-66v76w4h.js";import"./chunks/index-624fhq2j.js";import"./chunks/index-z0k97qgd.js";import"./chunks/index-x8e40qwv.js";import{Q as uw}from"./chunks/index-cq4t2sgx.js";import{$ as wq,Ha as fj,S as dMe,T as gj,V as Oa,W as Xw,X as Ude,Y as Hde,Z as yy,_ as vq,aa as Sq,ba as v$e,ca as kq,da as y9,ea as aHe,fa as jd,ga as JQt,ha as rki,ka as rOe,la as tv,ma as ZO,na as dst,oa as RX,pa as FAi,qa as FX,ra as zx,sa as MX,ta as OAi,ua as ug,va as iD,wa as BPe,xa as CPe,ya as z8i,za as vri}from"./chunks/index-36wtttkh.js";import"./chunks/index-5c9ar9m2.js";import{$a as t$,$b as xn,$c as Hat,$d as kQ,$e as B2i,$g as B9,$i as Pge,Ac as RJ,Ad as Wn,Af as Kse,Ah as hae,Ai as Mge,Aj as Iw,Bc as FJ,Bd as rm,Bf as Yse,Bh as xi,Bi as gat,Cc as MJ,Cd as JJ,Cf as Jse,Cg as g2i,Ch as Sf,Ci as yat,Db as m5i,Dc as OJ,Dd as CJt,Df as AI,Dh as IJ,Di as c5,Ec as kJt,Ed as _1i,Ef as Qse,Eh as _J,Fb as h5i,Fc as BJt,Fd as F3,Fe as u5i,Ff as Xse,Fh as _c,Fi as qde,Fj as RMe,Gb as sBe,Gc as B6e,Gd as Uh,Gf as eae,Gh as Co,Gj as gae,Hc as VM,Hd as Zst,Hf as tae,Hg as Cm,Hh as avi,Hi as l0,Hj as qE,Id as XE,If as iae,Ih as Xo,Ij as wf,Jc as Kn,Jd as jp,Jf as rae,Jg as sp,Jh as Toe,Jj as yae,Kc as Yat,Kd as ct,Kf as nae,Kg as rce,Kh as Poe,Kj as II,Lc as Ie,Ld as Ll,Lg as nce,Lj as cvi,Ma as Jae,Mc as Ah,Md as _Fe,Me as TE,Mg as oce,Na as Qae,Nb as Uu,Nc as Sn,Nd as ice,Ne as q2i,Ng as sce,Nh as $2i,Ni as fae,Oa as Pt,Ob as yI,Oc as UW,Oe as y9i,Og as ace,Pa as Ci,Pb as Xr,Pc as Vat,Pd as xj,Pe as MFe,Pf as ev,Pg as Pw,Qb as qg,Qc as l5,Qe as K9i,Qf as RXt,Qg as cce,Qi as RW,Qj as HE,Ra as he,Rb as Tm,Rc as IB,Rd as AXt,Re as Y9i,Rf as DQ,Rg as Ln,Rj as vy,Sa as EA,Sb as Mi,Sc as jW,Sd as yQ,Se as FO,Sg as _a,Sj as kf,Ta as bt,Tb as lu,Tc as Mat,Td as FJt,Te as Am,Tf as vI,Tg as lce,Tj as u0,Ua as e$,Ub as Ja,Uc as d5,Ud as g3,Ue as J6,Uf as $E,Ug as Qi,Uj as uQt,Va as jc,Vb as d0,Vc,Vd as SPe,Ve as n9i,Vf as QE,Vg as uce,Vh as tC,Vi as dat,Vj as rc,Wa as DWe,Wb as Zse,Wc as gv,Wd as hMe,We as o9i,Wf as If,Wg as dce,Wh as d4e,Wi as pat,Xa as f_,Xc as nR,Xd as b5i,Xe as woe,Xf as Nj,Xg as Pm,Xh as u4e,Xi as m9i,Ya as x_,Yc as xv,Yd as wW,Ye as J9i,Yg as ii,Yh as Wsi,Yi as h9i,Za as gi,Zb as VXt,Zc as vh,Zd as SQ,Ze as Q9i,Zf as Tw,Zg as Nn,Zh as iC,Zi as mat,_a as _9,_b as fn,_c as uye,_d as Ene,_e as k2i,_g as Go,_h as Ovi,_i as hat,ab as n_,ac as xst,ad as Gat,ae as Cre,af as C2i,ah as BI,aj as rat,bd as KY,be as pst,bf as D2i,bg as oae,bh as boi,bj as aat,cb as e_,cd as Jat,ce as ow,cf as I2i,cg as GE,ch as Es,cj as QP,db as Kde,dc as TI,dd as kat,de as v3,df as X9i,dg as jg,dh as zt,dj as fat,eb as i$,ec as PI,ed as Bat,ee as w3,ef as Z2i,eg as Sw,ej as tR,fb as is,fc as Bj,fe as Vxe,ff as V2i,fg as wI,fi as Kre,fj as xoe,gb as ai,gc as Xae,gd as zW,ge as gni,gf as Q2i,gg as sae,gj as xat,hb as et,hc as $g,hd as Qat,he as k0,hf as s9i,hg as Cj,hh as un,hj as wat,ib as Po,ic as RI,id as fye,ie as mI,if as a9i,ig as SI,ih as PQe,ij as M2i,jb as Ns,jc as FI,je as vPe,jf as c9i,jg as aae,jh as Qvi,jj as R2i,kb as Ym,kc as MI,kd as Avi,ke as tz,kf as voe,kg as cae,kh as NL,kj as nat,lb as Zde,lc as OI,le as Q9e,lf as iki,lg as T2,lh as Yvi,li as YP,lj as BJ,mc as NI,md as Ia,mf as t9i,mg as lae,mh as pae,mi as iat,mj as WM,nb as wHe,nc as ece,nd as B3,ne as gA,nf as x2i,nh as qi,ni as PW,nj as rJt,ob as SHe,oc as R2,oe as fMe,og as uae,oh as x1i,oi as fJt,oj as Rm,pc as ZE,pe as LQe,ph as U6i,pi as xJt,pj as Rw,qc as f0,qd as Lg,qe as zQe,qg as Ms,qi as cat,qj as Hg,rb as kHe,rc as Gg,rd as tce,rf as PE,ri as XP,rj as Wg,sc as JE,sf as ww,si as eR,sj as Zg,tb as BHe,tc as XA,td as ic,tf as Vse,tg as kw,th as Ug,ti as NW,tj as Bw,uc as EAi,ud as jt,uf as Bf,uh as Gt,ui as lat,uj as xae,vc as VWe,vd as TQ,vh as Cf,vi as F2i,vj as Cw,wc as qpe,wd as M2,wh as Tc,wi as d2i,wj as Dj,xc as DB,xd as Mm,xg as kI,xh as uu,xi as p2i,yc as _ee,yd as Ta,yg as dae,yh as DI,yi as iR,zd as dx,ze as zg,zf as EI,zh as mae,zi as Fge,zj as Dw}from"./chunks/index-j40q3yws.js";import{$j as Fb,$k as _9i,$l as EB,$m as t1i,Ak as Goi,Al as LHe,Am as rne,Bk as Hoi,Bl as _Qe,Bm as XTe,Bn as kse,Ck as Q6i,Cl as dn,Cm as zL,Dk as hoe,Dl as Qm,Dm as jL,Ek as X6i,El as J1,Em as lz,Fk as Koi,Fl as Yie,Fm as VSi,Gk as e2i,Gl as nAi,Gm as uz,Hk as OBe,Hl as Jie,Hm as nQ,Ik as NBe,Il as jn,Im as jQt,Jk as lN,Jl as fu,Jm as qQt,Kk as LBe,Kl as sr,Km as VQt,Lk as Yoi,Ll as Yde,Lm as $Qt,Mk as zBe,Ml as Yq,Mm as GQt,Nk as Joi,Nn as nd,Ok as Qoi,Ol as hv,Om as Ore,On as np,Pk as hee,Pl as Ee,Pm as Hvi,Pn as op,Qk as fee,Qm as Wvi,Rk as Xoi,Rl as _s,Rm as Xk,Sk as xee,Sm as Xne,Sn as CI,Tk as Oh,Tm as eoe,Uk as W$e,Um as Mre,Vk as Lh,Vl as Ni,Vm as tD,Wj as rsi,Wk as Rx,Wl as Iq,Wm as xTe,Xj as rSi,Xk as gl,Xl as L9i,Xm as yTe,Yk as boe,Yl as _2,Ym as v1i,Zl as HJ,Zm as e1i,_j as Ba,_k as I9i,_l as AW,_m as w1i,ak as Sr,an as o1i,bk as kr,bn as QJ,ck as p3,cl as PD,cm as HQ,cn as eB,dk as Nne,dm as zei,dn as XG,ek as One,em as uJt,en as eH,fk as z6,fm as DJ,fn as LJ,gk as SL,gl as gI,gm as CJ,gn as TQe,hk as Un,hl as K1i,hm as ZGe,ik as j6,in as Xti,jk as w_e,jn as Gxe,kl as V9i,lk as UBe,lm as fvi,ln as Jb,mk as Zb,ml as nwi,mm as bA,mn as NAi,nk as lee,nl as Hse,nm as rO,nn as P6,ok as uee,ol as wj,on as SS,pk as J6i,pl as Sj,pn as Ase,qk as uX,ql as kj,qm as GJ,qn as Ic,rk as cN,rm as WJ,rn as qd,sk as gee,sl as ine,sm as gr,sn as x0,tk as yee,tl as wti,tm as p5i,tn as du,uk as bee,ul as jQ,um as Mq,un as nt,vk as U7,vl as X1i,vm as ym,wk as mee,wl as ewi,xk as QS,xl as QG,xm as Sne,xn as bI,yk as pee,ym as See,yn as Dm,zk as T1,zl as NHe,zm as VL,zn as vse}from"./chunks/index-pe6t04tc.js";import"./chunks/index-7qxdq0pn.js";import{Av as Je,Bs as bs,Hv as Sat,Kp as pge,Ov as a0,Pv as L9,Rv as Ya,Tv as Ud,Uv as QXt,Vv as Nr,Wv as eki,_r as xl,as as z9,ms as Da,wt as LW}from"./chunks/index-3cwkjys1.js";import{mx as l}from"./chunks/index-pmtqnhch.js";import"./chunks/index-sekjw9v9.js";import{qx as Al,rx as tTi,sx as E,tx as Qg,ux as Ho,vx as ce}from"./chunks/index-rdf7wcrz.js";function PNe(e){return e===0||e>=55296&&e<=57343||e>1114111}function RNe(e){if(PNe(e))return 65533;if(e>=128&&e<=159)return MCi[e-128]||e;return e}function FNe(e){return PNe(e)?65533:e}var MCi;var MNe=Ho(()=>{MCi=[8364,0,8218,402,8222,8230,8224,8225,710,8240,352,8249,338,0,381,0,0,8216,8217,8220,8221,8226,8211,8212,732,8482,353,8250,339,0,382,376]});function ONe(e,t,i,r,n,o){let a=e.length,c=o*90,u=0,d=()=>{let L=Nm[e.charCodeAt(u++)];return L<o?L:L*91-c+Nm[e.charCodeAt(u++)]},p=i-r,m=i+n,h=new Int32Array(m);h.fill(-1,r,o),h.fill(-1,o+p,m);let f=new Int32Array(m),g=new Int32Array(m);function y(L,q){let K=0,ue=q,G=q+L;while(ue<G){let S=Nm[e.charCodeAt(u++)];if(S<89)K+=S,h[ue++]=K;else if(S===89){let P=Nm[e.charCodeAt(u++)]+2;while(P--)h[ue++]=++K}else{let P=Nm[e.charCodeAt(u++)];K+=89+(P<90?P*91+Nm[e.charCodeAt(u++)]:Nm[e.charCodeAt(u++)]*8281+Nm[e.charCodeAt(u++)]*91+Nm[e.charCodeAt(u++)]),h[ue++]=K}}}y(r,0),y(p,o);let b=new Int32Array(n*2),v=0,w=0;function D(L,q){for(let K=0;K<L;K++){let ue=q+K,G=d(),S=d();b[w*2]=G,b[w*2+1]=S,w+=1,f[ue]=v;let P=(h[G]<0?g[G]:1)+(h[S]<0?g[S]:1);g[ue]=P,v+=P}}D(n-o+r,o+p),D(o-r,r);let R=new Uint16Array(v),O=0;for(let L=0;L<w;L++)for(let q=0;q<2;q++){let K=b[L*2+q],ue=h[K];if(ue<0){let G=f[K],S=G+g[K];while(G<S)R[O++]=R[G++]}else R[O++]=ue}let k=new Uint16Array(t),j=0;while(u<a){let L=Nm[e.charCodeAt(u++)];if(L>=o)L=L*91-c+Nm[e.charCodeAt(u++)];let q=h[L];if(q<0){let K=f[L],ue=K+g[L];while(K<ue)k[j++]=R[K++]}else k[j++]=q}return k}var Nm;var NNe=Ho(()=>{Nm=(()=>{let e=new Uint8Array(127),t=0;for(let i=33;i<=126;i++)if(i!==34&&i!==36&&i!==92)e[i]=t++;return e})()});var Mce;var LNe=Ho(()=>{NNe();Mce=ONe("!}.&u%}'&}*'~!6*)%&,~!J~!J~%L~y<~!R,~~%Lu~~#GD~~#|)1#%}^%}2%+#.##%##%}&%##%'#%##&%#%#'%#&#%#&#'#%%#&#%##%#)%''%&%#%#'%#%%#%%}%%%#%#&(23#%%#&-%0%('1#(##%#'##+%'*.:1}#%#6-+(%'%%#%%%}#L'2351&('%}&/N'(0(/*-%(%%}#'+&T%7.2}#&%&#%#36/5##%&%%#&#%%#))2%%##%&&'0~!#*+&'%1~!%).'3q?&%'1~!.##%6(~!+%%%(Gw'rT~!E#<nA%#jZ~!H%(~!42##~!*31&~!G%U~#)5~#`3~!J~!Z~%]~%Y~%C~!q~!u~#kz~%#~!6'~!D~!U~!?~#T~!c%~!G#'~%7|~!G~!J~!G&~#pb~(Df}#%}*&}#%##%##%##&#-}&'#'&%#.++}%mI,#,@&(}*%}*'%&##&#%##%}&0}#.},U},%}+%}&%}#%##&}B%(}(%}+%)})%##%#&}&%##%&}<%}>%#%&}*%}(%}9%}/%})%}*%}*%}?&}&%}3%}&*#%})%#%#)}#&#-#+*%E%%'%'#%}#*V##&##I}#&&##%&%#&&Qf%%))w/0+&%#(#.%-''''++++7}>%4'',##1,#%#&%##&#'##&#*#9)%&%}#*}%,#+P(%A&%#'&##wSD',9E00#y#@}(+}&%&>~!#~!X}#*}(&&}(&}(,%}%&#+&}#&}I%#%}%)#(},'%#*}4%%#%}(''}#/##(##),%-##%%)#&}(.}&%#&}%%}*&#%},&&}&%}#%*'#%})%}D&}&%}-&}6&#&}-,%}#%})-(~+`~,=?~I9'9%~!,#%})%})%}@%}?%}(~!?~#<~#pP~#BG~#=1#%K+~#?#~%;)~#A~#mF1~#A'~'X%'~#lR~#N~'N~#r~#m#-~#i'?%#'%~#B%##%,%#~#_%#0%~#]732~,w~2+#:&#%&'0%&>%}#>##F+)#%&&#(+_}4&}-%}(&}@&}O7Fdf0@+/v4}&WU##&/0#&'('B#%}.%}'+#%}#%%&#&%#%##+#&#)#6#'#.},%}c%},%#%##%&#&%#&~#>'*-.%##%##%}#%%}%'~#)D1}#%*&~#_%%'(~#S2%'.}#~#=##*'*-%}&'%'##&&~'E%.#&~#M4}%%##&'%#~#O1##%&#'+~#<B%##%%'%+~#;#@%}#&%#&&%#(~#H1}'%'##&&~#?A}&'~#D#%32}'&&&&~#[}'(#%}'~#;C})&}%%#%~#=&%,3}%'(#%%~#^'#&&)#%'~#Y%-~#d-%'~#^%%&#&&&}#~#b~2t*&'~&(~&@~0%~e~3}%*''0})&}+~!9##-}#%-hD*)1fC#%/&/fB#40~!+#)*4~!+~!K'&:~!/*7~!.#~!H~!L':~%x&~!H#~!*~%1~!I#~!+A~#p'~!F~~#-#~,,(~.Z~!V~%;'B'mq-W~!N~%I%#&&#&}#%},%%}'%}+X#%}#&}(%}'%}<%}#%}%%'}'%}:~![)9@~%>~#UA%-%##&~!C%~!-.9:~!1~!-^2/:a~!y,D*J#-5)/4~%23,~#G~!L1~!0X3`~!2+~!!0-~&E~!W~!o,>Y&]~%cZx_&~#O*9#A#'#+I'%#)~!0B*-5A+-((F&*M#)(-7-5+'-3a5Vi~!Y~!?+[)%3),ERHm~!+:D,VG.+)?fB%%*(%)'(#&80%1'8`K8?`+'Z#&O&'H5#*9)A%%5&3))0%39+.*7#()&&*=4@**L)<'_&*+..;(#*+)./&0#3)%')-8(4ixD(&.}%,('aI:,)%,k2231T)I'#/-W7,/'Q#.'Y24+h')37</31&83##&0#),H(?'&?/1##%#&&#%''-%&&&#(&''&#.-'%#%%(,')*'&#&#'##%(%(#%('#&##%%%%('%#%#%%#%#&%##h>w+v<ayvyvcg.uuhKr}g/v|g>u9i[~>g5uI~=RvdwEg;v/g;uk!!TTSx]@RT!U!#!@VBRUU!'UTe-d0c`e&gSdicedFcrdTaqb.kYcAohdYd@a3e+d}dMdtd.aJ#bqcK`dle/e.e'dwdPdodddjbEb}ogd^ofdpduc6j?l%d{drdqc)d7bacOdQ%T#Y)X.sR[yH>6Vyv3[xwLu>vo'!*.[yBacahoj>6Rew3[xqdZa#!a&#^(X-[yG>6Vyu3[xvg3sEr|g.u/Ri9db0T#^(Xa)!-[y;>6Vylg4wKs{JwNZt3@3r=c4Z([xlg;wKt!cpq's@v7A'*a(a+!-a#[y<3Dt?3Dt'>6Vym3[xmg9rxsNJwLZt4~?r?db1T#`-!(Xa,!0[yS>6Vz%NuQs.g4wKtnJwNZtS@3r>c4Z([y%g;wKtrdga8!a(!#&T*Y-Xa#!a0<or[yc3Dtq>6Vz43[y3JwNZtf@3s!Ju}!%Dti:pm3c_%X#tjB5pkd6q!r]u?voC'*-a.a2!0a&a+[yI3DtI3Ds~3DtH>6Vyw3[xx;:s#~<5pKJwNZtE@3r~d`a)!a2T#a.(!+U.X1[yT3Dt`3Dtv>6Vz&3[y&g9rxwzcxstPu.<rAJwLZtT~?r@dZa%!a.&^*Za(/Reu[ya>6Vz23[y1g3sEr}wkg{NuQRg{ci(U#5@b`~,cg#U(2WnH5wugcRh7dX#T(Y,a'Ta!!a,[yZ<]mj>6Vz,3[y+Pv#5ReZKu+=,%!H}7ABwkaS?Rh:BcW(X#<]mrj:ubv/ARekdg%!(!a.*Ta(Y.X1!#sP>Rl*Dt6[y>>6Vyo3Wf*jOvuumvuRgRJuq*!:9<B@bX~3jVv&v@s@5Re[d/rQt{uAvo&a&a*)a2!,0Wf!3Dt0=Bs'>6Re}3[xy~<5s%JwJZt1~Gs)c;&!#2sJkNuXvzq7rxu,Re8dka4!a8(aEZ+a@Y.X1Xa)[yd=Bs(3DtP>6Vz53[y4cX#X&Re:avRe9~<5s&JwJZtQ~Gs*i^rzvdRg+Jv{%!2sbB@bX}kdga,!Za?&^*T1/!a'Dt+[y6>6Vyf3Wf%g/u;s4hGu6?Rh-JvZ,!c%#&RoX54Rivj7uyvf8RgTKvZB%*!2sGh<vu5Rgq<=C::9bb~#dZ#T&Ta6Y.X*Dt>[y93Wf)coZ(T,6VyifluvRgC@95@B@bX~/hFu34cC#T,k/unq8w8Q5RkUklwQuzunq8w8Q5Rk8d/rJu?v8w9)-&!a0a;a&aIWejg3sEr/h1s<DtDJvyZqY5aws3Jvy!&Wei~Hr1:au5@Bag>23E~5c:Z&bX};kKv?w&unuVu5Rjc;>bs)#~@:Rh.=ay<a]C;b`}Vd6s/t{uAvoaxa()!a,a7%-a#a2Dt,[yF2Wo[>6Vyt3[xuNuPRi&NuPwpi#RoWh?vf8Ri%Jv]!%Ri:KvxD!.'2WeAjZu`q9rxu,Re7woeAg-unLq(qA_/*2Wg_g3u5q^9:4E}/jTrxrzv=Wkkd~0UX#^^Xa-a1a5T&a=U1a'*aEa]!a*aPaA-adok[y54Rn>;:p3~Dp5g9rpsFNvZqjg3uJp4~<5p0Pw;5qlJwNZt*@3p1Pw:5p/Ou!5p2JvG'!6Vye=<qnJvh_[xhg3v,Rh3kOwOw-sDuev/Re^dha[a%!%!a+#Ta7)-5TaCaO!aka!a)sf[yb2>Rl!9ARiq5E}Qg=ucRkBE|oJrJ_@Wk~@Wk{JrJ_@Wk|@WkyJrJ_@Wk}@WkzJvO_[y2g-vMRmiKuYC!)&>Ri;>Ri<@3RkNc](X#@9Rk=g5vuRmhKvDB!+'=]meg3u4Rmgd)#Y'Vz3CARmfd`a+!%T'!+#Ta1Ta6TaM-sTDt9[yA9sYd'%Y#s[[xpj:ueunaXRgEjRq,v-vuqdd2'`#6Rev<32@5>:2<E}5xIo9a*X#Y(;5RePJvD_g>vyRgNj8w)v8<wggs:RgXiZt|vjx,hSq3ah!-(~@:Ro/Ou!5RhWj^v(pyw8unRhUdx-UY#^Ua.a3a70!)%UX1TaDa)'omRiRRhE[y:3Dsz=Br,>6Vyj3[xkg6ruwjcqsrPw;5r*Ku]D'Zt-@3r(~?r.i[vwv]dU1a--U#`a4(g/vsRhPOu!5RhLj:rmu9Wo!~@:wdh@g/vsRiTjXuvvNr}:RhBj^v(pyw8unRn]dz1UYa'a+^Y(!aETZalaRY.Ta?a4[yDJw1!#qLsW>6Vyrfzq-pLflpwRe|Js>%!Dt@3Dt&Jvy_[xs~HrnjMuwpsw'RecKu+D#'!t<~Grl~?rjg5u-x,gwp{ah!-(~@:Rg~Ou!5Rh'jXuvvNr}:Rh#cW#X/c;&!#2sLi[v7u7RgpJv)(!iLrxu,Re6j7v@s@5Se[e7d`aW!Za(a`T.a#!a3!&aDa-!9)Dt_=6s+3[x~~DR|h~DS6avhGun5RkZj3w)v-]mkKunB!&*]kb97R|i<ARk<c:Z(6Vy}Juh'!wziMRoS:F|vkLuauJv5vtvQRh1d='T+Y#VyO~DR|jcF#T'7R|g97R|kJv3'!ay<Rj,Jvh&!:ReXcsa6*a+#a#_aIRf9aLRf?c,Z&Rf5Rf7c.Z&Rf;Rf>cQ#%T'p-Rf8Rf=ct#%'(*!,p,Rf4p+Rf6Rf:Rf<d~'Ua%U*^UYa(!a,-!#a4YaTalaEX0a8a<Weo3Dt/3Dsx=Br93Wen~Dr;~<5p<JwNZt2@3p=Pw:5p;Ou!5r3c7&!#:p>3Ds}KvGB)_6Vyk2sM=<r7x'eovA(!hFu1ARf}cV#X&@r5j6rvwQa^Rf3c=Za'wkghJv__g;unRggA53B9=b^}%j6uduo5Jq;!(hIv%2Re`Ou4ARe_e%a#^^^Xa&!a*a2!&a6YaP!*ad!#a:aE/5Rn?[y@>6Vyp;:pE~DrY~<5pBJwNZt8@3pCh=rt3rWPw:5pAJup_[xoNuPpF9c!#'45pD5ARn)d8#X'X*3@rU72s]h>v<<sSjJpqvewOJq/(!hNw'5ReBk0s2u3w/w'5ReE5@Jq.!a+JQ!&WeU23d(#Y&RjG5]jBk!u7w&u0udARjEe#+^^^Ub#!a2/a`Z(agT1!a-a;|@TaG!aS[yV=Re~fow'RguNuPRe?bz#'>RoUWeL>:Cbb|?JwPZtVg6ruRmzJvD'!6Vz(g/vmRh~Jvy_[y(g9voRgyx*cy(#2>Ri2B9b]~9kIw9u7rluJu3Rg]dI#a%UY'@=p%CAx.gQZ&RhwwygtRm{x5g_Z'+ABqR9Woa=Bp&dV#^*Xa'!&@o{g4v]Rk;Jv{!%Rk[wkkiA5RkiwwfUB=x,fUuqC&*!>RfTg8v0RfV~ARfSd;rJsAuAv9wR'ae+/aO!a@aza/a#[yQ@Wg!2Wemg3sEr0JvB_g>uvReWg2v+Re=KupB_+[y!2AbY~-~Hr2AJwD!(h<~El>h<~El?Kun@+_:9b`}Kg-v/Ri3g;vtwyk_9]k_d=&T#*U.6qh@Ab`|K9:H|CJv[!&3Dtex'fDwC%!Rf[9WlMd[(^X,!a%Z06Vz!@WgBg=v~Rgvg,QRe@awd,#Y+jTv|Q~EfWj]uNr|~FRfXdy#Y&^Ua%!aO.!(a)Ua;=!a@aKap!a-,a!Ta]a[rSa]p?[y82sK=Bq~;:p:~<5p8Pw:5p7d'#Y'Wf(;RnRi[u4w&RgJJvG'!6Vyh=<r#ijuuv/sIKuYD'ZtG@3p9~Gr&d2#`(g<vtRgFj`u5w&rqpxRf2CJuY!+:wfnTOu!5Rg}jNs1ucv&RfwJvA!&3@q|BDcC#T,k/unq8w8Q5RkTklwQuzunq8w8Q5Rk9dga#!a'!a=#a0!:+Tb*b@aO.a4!aba8aFJv^}?!VyR~Dr<g;u%Rn.~<5p[x'e`wNZtR@3p]Pw:5pZhNvjBp.woe_g5u-r4JwF!%DtO3:ooc7&!#:p^3DtpLuGw(!+%)Dtk6Vz#2sd=<r8d'#Y([y#<x3gJt`w@!)%}MRiowzikRij=]ilxAf3,U(#B2Rf#g0v-Rm[ck{`U#]giKv3>)!&6Ri154s,KuGB_%@r68r:dJ|t`#X(9<E|u2@H|rx3gJu?w'!+'1Nu7Reg4=H~+9<wxgY95Rm]xLggZ-`(X}U2:Ri4h<uOawRmsJv__5@bb{jbV~3dka#a'a]!,#a+U=a>b6a3b%!/aKa/)!arwve^VyJ;:pR~DpTg3uJpS~<5pOPw;5qmPw:5pNOu!5pQJvG'!6Vyx=<qoJvA!{~Jup!%@qk7Rn/KvyD!}''[xz;>wkh'?Rh,x8gyt`w5D!&),(SgyccRgztJ@3pPB5p#d'(Y#<]mmifubw&RgoJvE&!82s^JvF&!8Rf,ADb]~;x=h'rNu]vK!,%'*0RnORh)4Rh*AqQg-vaRnNg;wHwkh'ba~4cE#Ta*x3gctyw@'!+%RnFRnD<4Rn@hFvK5RnCxWg[#`&a0Ua()`1Rm75Rg[c]%X#qi8Rg^NvdRj>BwzgZauwji7Rm6A4wgg]d1#&(*,.0a#Rm;Rm<Rm=Rm>Rm?Rm@RmARmBe%#^^^Xaea?aC/b+(,!a+a#!a/!>a&Ta<aKbD!2wphBRnk[yPw}hE|.=Br-3Dtm>6Vy~g6urRf.x,hPrNav!%'RnqRo%Ro#Nu;q[Pw;5r+JwNZtM@3r)d'#Y'Weh;xChL#`&RnmRnoKu}>%(!Rne~Bs-;2wjcussJv+'!aYSO}6@B<5?ba~8LrNvj!.%*ROwungw~ng~:9;Ri^>wtnig;wHRnixDh@|(UZ.x1h@|)!#:2<H|*xHn]#-UX'3Ro)z=iT}6ARns=Bwsn_wpnaRncw]aR(#UXa&Ua*a/=]iPd'#Y&Ro'WnXf{QRm2hNvj]nZd`'T~&1`{|`#9b]{}c:'!#Wl{>@=be}]?cl{{U#:5Abb}Jds#^YaF!a*b4a#a3aPa>&Tb!bH!*a_!Eau?/a&RjY<]gj>6Vz*;:pe~DrZg,QRj1JwNZtX@wihspcJvZ&!VyX9WmOJu|!|N2WmHJvh&!]ht~Bpbcn&T(!#RmQ<s7Nu;padH#X'`+WmJ@>RmKCARhnKup=!)&Wf+:RhqNuPpf9c!#'45pd5AwghpARn(Ls@w!%,)!RmP@Wfe<E|IJva!&WmNg8vsRmLd`*.`#Y'Xa!axRn*]hrA8Rhug5s@rXg8u!RmMd8#X'X*3@rV72smdI*#UY&RmICARho~GsgxVgd)Ta'U-Y&Xa!T#RnEWnA@Wffg1uDRi0hFvK5RnBxGnG&#`%owp)@wsf+bX}Ze-*1!a*^^^Ua|!#a.aq&Ya2!a>.a6!a:aO`aJDtL[y`@Wg#>6Vz12@wzoYRoZNuPRi!NuPRhzg=ucRi,@=b`{Yg=ucRi-ACJvB!&Sh[ebSh]ebi`wUuFRm4Jw2_[y0JvB!.<Ju(!&SoG}6Shd}6<Ju(!&SoH}6She}6Kur@._g5vHRieJvx!{L2G{Kx6gd'T#?Rh82Wi5cZ#X(g1w)Rm5dW-Y(Ta#!a)!#aYa=wnfE=su2>>bU{0j9udv:<svj8uQv-7RgHdE%#^'sq9sp=>Bb_{TJv`!&g/r|snj6v(us5d,#Y(56H}[978H}]Jw5!&g1rushJvB!+j;v{u5?zDhd}6}bj;v{u5?zDhe}6}ce*#`(^^^a[aea!=!a6a*aoXb1a.!aAbL!b>,b'aL!aV@Wf|2Wlg3[y/JwNZt^@3piPw:5pgJunZou3@rsJva&!Vy_g<v~Rm#JvG'!6Vz0=<r{Ju{%!:pj@WfsiXuJu3Rm:JvZ&!WfA~Bph@c4Z&Dtwax5rubx(#:awRk1@d,#Y&RfjRfid1#,Y(@Wfp2Wlrg5s@ryKu[@!,'=]ig9wlk?Rk>g5u-rqJvy'!@9RkQcH(T#=>Ri~@<wkj(Wj(KuZB*!&<7rw@9RkRcH(T#=>Ri}@<wkj)Wj)dg(Ta2Xa9X#`-!a*CARhg@@=I}d9x;c~#X%so=<sj>2@@=aybb}XjWv0Q~EfEj3vLv;<d,#Y(56H}`978H}_dgaPaFa'a/!#a3Y0a_a;a|!1(a7-[yE3[xt;:pJNvZrrg3uJrvJwNZt=@3pIh=rt3rxPw:5pGOu!5rpJvG'!6Vys=<rz@c4Z&Dt(ax5rtJvZ!&~BpH@wsfNg-vaRlNci*U#=<wei<F}a5@Jq.!a*JQ!%@qZ23d(#Y&RjH5]jCk!u7w&u0udARjFd/prq=tyvpaEa(a:.!a1aZ(@@=I}:9wpd%=<sX55w_h}@@=I{t=ay<aU@@=I}T=ay<2@@=I})?C9:9au@9Cb]}DP~=x-fAZ(2Wl1=ay<aU@@=I}>5@d##Y+jTv|vV~EfFj]uNpn~FRfGdgaK!Z2&!a8a-Tb({E!acTbM*!a(DtY[yYd'%Y#sl[y*hHvh>Re5x2c{Z}.j4uCvcawRiMd+#X+_x&d!},<5RkX;2Hzw@x,gavfB-!{CcF&T#Roe;RodwWbBg5urRgaKvHC*_6Vz+<4opieuew&Rmq@d]&Y)X,T#X0Rh}<BqP=4qS9:ReMg/ujReNJw0!/<Jui%!bd{kawwnemRelAxUa?a3#*.&UX(Ya+a/RhvRnQ<o}9Wmtd-#Y&RgSRmw9;Rmxay=Rmyg-vaRmuxEhSrNu,v-voC!%(aR.a(a7+1Ro1>Ro5CE{A9b]{@;5x#eO{:g;urRi+KrNA!%(Ro3>Ro79;Ri_Ku@>{;&!x%gX|{KunA_+g5QRj/g3u5Rj#g>uERj%wio/xRhS&!,!#^1U}wba{8>>@=be}qC@:D5ba{7Ku+A&!}x?ba}t>>@=be}se(aA^^^Uat!b0#{pa+awUazbGa#aLb9bgaWac'a5TbS=Br!d1#`%scp_Jvl!#rT>Re0JvX&!VyN=H{Fcm#U&:pY=ReaJv2&!]h0=]nUJvG'!6Vy|=<r%JrM_=]h2@Wlud'#)U'Wf'b]{i=]h/Jvh!&~BpWg=v]RnMx+ny#'Nu;pVwjnu=]nwxJnx,T#`&Reqwjnt=]nvieu9vrRjLLuYwP(#+!th@wih5pX~Gr'g5v/Rh4KunA'!-CARnP@wwiN:Rm_9x'cvw>!|l=<saKvAA!0&3@q}>w^e1bp#&Re2Re3BDx7gH#T|f5H|eKuZ>!%(:qNAH{]Jv6!+3B2B9=b^{X<5<B92:E{ZLvhwA(a;a%!igQuyRmad+#Y}m@3Rh5d8#X'X*:AqUAHzmaxwbh<aXRnVcF}RT#Nw&cj#U(BWnug/vsRntdka)(a3+.Zb7aYYan1!bVa@Xa}[y^@b[{G=H{+hFu73Rj&Pv#5ReQcK%T#sig1v{Rj'Ku+D#'!t]~Grm~?rkKuMB!01d5#`'Vy.ta3Dtu~Hroc8#'{^45s85AwZbP&!#Rn!wghxWn#KvEA!)&2RlA2RlBx:h|#(T,=]j09Wobz>x]z/@awRoTd+#Y(az]hFhCrm4d,#Y+jTv|Q~EfMj]uNr|~FRfOdCa!Xa9_X#@<plJvf!%b`{(9;Rgwc;.!#2x7cw#T|UDb]|T5Ju={(!=@E{&Jv)&!Ab`{'awJvf!~*>>@=be{#KuY>!+&4Ezyi[ugv&RjIdea+T)#UXa&T-T&a!Rh9auRmW=]kLg5vuRn+g3u4Rn-Ow6ARn,hHus5xNk?#UX(U~)/g8v0RkD~AwkkF?Ri.OuNBwkkA?Ri/d|a2`a*^UYa.!aBTZaTa'Xa;!(!2!-a#b2[yC>6Vyq3[xr2Wi?g1rusVh%s?DtF~<5rbJs;%!DtBfswKtCj[uvuSsEu3RgVx3o:u+wN'*Zt;@3rd~Grh~?rfg8w)Lq)qE&-a%!>bI|`jWv0vV~EfCjTv|vV~Ef@j]uNpn~FRfBcK#T']gWNu7x,k7q4ai(0!hHv8<RhmkMu9vrsBuev/RhlCJvB!,g<v{wchh~@:Rhji[vrv{wchi~@:RhkdS&a5UY#Ta!RgPwwiI5BwciI~@:Rh`x'iJvj'!5]iJPu8Bwch]~@:Rhach)U#h3rp]gLh@t|Ax,hTq3ah!-(~@:Ro0Ou!5RhXj^v(pyw8unRhVd|)`,^UYas!a?/a2Z'a^Ta{Tb7Ta(a#!a,Wf&9sZ3DtAadamov=Bqt3[xig8vsRm~>waiL2b`{QJv*_Ouv2qgj<v]v2BqfdR'X*X#Y-@3qr~Gqv~?p6hHv-]glPup5Lq+q?_%*b_{qF{n9b^{rOu4ARhpKvCD!+&~Bqp:5Dbb}nwoiKl&unuTuBv]v+ueunaXRf0=Jvh!0nKufu8v1w&w7q%w&uHrz:Rgnj5w,uxDJq/(!hNw'5ReCk0s2u3w/w'5ReFd>Za&!*UaA=<wkgsRnSJv^!%Refifw3vyRgOKu_B'!,<]gkiiu:w&Rh<=C@a^<B57@2F{[<B5@aW:=3away9A5aW=<B=C@a^<B57@2F{Ie-#`(^^^bCara.b8aza6!/bZ,!adTbnTbOb+aFaS!aAT9@Wf~2Wli3Dtl2@d,#Y&RfnRfmJwJZtN~GqyJva&!VyMg<v~Rm%iXuJu3Rm9Jv[_=]ih9wlkDRkCd1#`(@Wg>2Wls3cH#T(@<Rj*=>Ri|b~'#23s9h<~El.d'#Y&Dtxi^rzvdRl#d*#U%(o|B2s`hJwSaxRmDKv4B&!1:Rmdd5#`'Vx}to~Hq{x'f1v3(!BA5ba|bJv_&!Wfug1v]ReIdO+U/Y#&G}-8wze=Rh{g1v]ReHg/uQRf/by#)ibQwERl/cH#T(@<Rj+=>Ri{cNu+vlax-!(#a0qa9<Rii2;;bU{H;x<i=&X#Rk`<4wwi=C9H~8xAI(Y#<azRi@45wXI<B9;5bb~7dL(X#Xa(+!aL6Vy{g5QqOau:5au2@ay547EzbxOcU(UX-T#Ta#:Cbb|A?wjh/b_|SOw6ARgtihr}u7Rhy<d1#T)X1@@=I|~=ay<2@@=aybb}Sj3vLv;<d,#Y(56H}A978H}@dGpvs@uAu`vcw9*!aFa+ai%(b!aXa8.a?a[ozWey=sU2@G}Nch&U#Rf_WexKu+D#'!t:~Gr`~?r^j]uNr|~FRg*j^psurwJt|RmcKv)@&!)7Rkv~Br[@wxfO:Rl3co#U'6Rezj_q#vIuavjRltwzeyh@vr5JqD0!>aY?C9:9au@9Cb]}9cl#U*5;5<H||jbuus1ucv&Rfvg1v~d/pppzqFr^a--a~!aMat1(hFv;Wiz@@=Izoj5uuv-7Rix~Cw`fk2WlVcZ#X,k)u3vWs@u2]ktg;wEx'fBq(_2Wg/jTv|vV~EfoJv]!15x'hzqG!(P~EfU~CRl_j6v(us5x4i-#T(2WmZ?C2F|d>Kq<aj1!*jTqIsBv=Wl`~Cw`fi2WlWj`v0u*~>RlR=c>Z,k#u3vWs@u2]kr<c1Z+jTqIsBv=Wla~Cw`fm2WlXdmb3!a{(arZa`bkTa%TbQTa-a9+c'!aM!/[yL=Bqug.w'RifhFvyDRj.g>vgwyk^9]k^Jv3_@WfbAARkhJw2_[x|JvB_wkoIRoKwkoJRoLd'(Y#<]gm=<9<H|yd'%_X#skDtb3awwqkgNulRkgdB#^',9:p'hJwSaxRmEBwVb8@4=H|qLu+w50&!)@3qs~?pU>Awwn;;Rn=c:Z'ARn<=<qwKvC@!/&~BqqJv6!&]eVb^z^xRge'/a%+^`#Sge}6<4Rn3=]n0Pw2>Rn8Jw0!&>Rn:>Rn6cY#a7+!a&=<wkaNw~h3z_c5Z{=wjh#=]nLKv^D!&)Vyz=bW|swYb<WetcG#T(2wxa@qVx@gD#Y&b^|V5JwG&!5bb|pg/w&RgD@x=kHs=uAvn!a%%/'+RmSRh694Ro`g-vaRmRhHv-]mlxCcS#`&ba~.5cD#Ta)P~=d,#Y(56H{>978H{Dd_#{2^Y%_+qbbb{6g3sERhsbU{?dfa.,`a(Xa<!aiX#(55RiG54RiHcI#T'WiU3RiVNvdwtfcRlKNvdd,#Y&RlHRlExQgf.1*^T'X#Sgf}6Wn4=]hfPrk>Rn7Jw0!&>Rn5>Rn9Lunw?&a2!,5<oq@@wqfdRlJj5Q~=d,#Y(~ARfcOuN]fdDKw;ay(}i!547E}j?cI#T(@5bV}iCbV}hdv(^^Tb?a40,b##Tbo!a*bR!a<b|a/!aKai!aU[yK=]o^g:v>ReGJwPZtK<7Rh+h<~El,Pv#5ReR@awwxjCg,ulRjDJv6&!]j!z?aQeeg>w=Sh<eeJw;!&axEzOg,Qosc!#*:wkeJ]eJ>x'h-u(!%Ro.w~h.zPdNZ(X,Ya![x{;9ReY;wkgxRiF:x?ap#Y&RmUg<s2Rkod]+UY0TZ'!a&A9sw<=bczLNvuw{gqzNhJwSaxRmCKuLay!#&s_Rf-55b^{uJvZa!!c%#(55Ri654wmiu5RiuawLu,vp!+}^%b_}Y9;wkgxba}o>A9:=b^}zKuh=a''!3awRk3c*'!#aHRk6c+Z&Rk5Rk4Jv)&!awRjSawd9*`#0?C2@EzMj8u<uJ5RmbjQrquJu3x,k>uq@_+=ayb^|W~ARkEOuN]k@7dhzV^X/X&a-#zRzSb`zXcJzTT#2WkVKvDBzW!%FzY9;5bbzWjQrquJu3Jw3%!b`zU=ayb^zQd:#X(T-a!6Vyywxh}=b]{Jg=u1RiAdGp~qHtzv!w(wA+a+a;<!aJaYai'anasb(=azRmV:Cbb{MLq2vb!%')RjuRjrRjtRjqx3jnqCw3!%')Rk(Rk+Rk&Rk)Lq2vb!%')Rj{RjxRjzRjwLq2vb!%')RjsRjpRjfRjex3jcqCw3!%')Rk'Rk*RjkRjl9<CbbzfOu4ARhxLq2vb!%')RjyRjvRjhRjgx=joq*uKvb!%')+-Rk.Rk%Rj~Rk-Rk#Rj}x=jdq*uKvb!%')+-Rk,Rk!Rj|RjmRjjRjidAq&qKs@uAv8Aa.'*-a@a&0!aM@a5[y73Dsy3Ds|3Dt):wxgI2sHJwJZt.~Gqxwsf0ikrzt}Rl0Jvy_[xj~HqzKv_A|D!&WfP8axRoVcf,U#k(v]v+ueunaXRf1Ju}'!g8u#Ri=jQw!sCunLprq>!,')~<5qeGzq9F{W=c##%s5au:5aU3CBE|;d4#X(D!a&6Vygx(b;#(=]ed?C2F{N<capoq2r[a&!aPa9,'Pw;5s:@@=I|,55w_h|@@=IzcP~=x'fCqB_2Wl2>aU@@=I|1OuNBc1Z+jTqIsBv=Wlc~Cw`fl2WlZ~AcTa%!Z+jTqIsBv=Wlb~Cw`fh2WlYk+uNqJsBv=WlSg,u3dca3#UXaMYa)TaB-=cM|7T#<bI}l5@B932:aV2G{BOuNBJq:|M!5Ezt=<B=C@a^<B57@2F{v>cB{/T#=ay<bI{3Jv6!a.6BKq0ah&+!5E}HP~Ef{978BaU@@=Iza<7d#.Y#978BaU@@=IzH~AJq0!(@@=IzG978BaU@@=IzFe,aU*Y&^^^bvJb,b:bFad!a,c2Ta>aL.bo6!a#CbTa'T#Re{2Wlh2@G{yg6t~Ro_NvdRfticuRQRllJv3&!x&c|zs@Jw3!%RflwpfkRlpKuL;%(!Re<@G|C2GzdhIvuBwgjAg-u0RjAKQB%!(GzZ@G|5NuuRl7d='T+Y#Vy[g<v~Rm!==G|>JvA!)@wma=]m1ifuaw&RmnLs@vT'!|/+[y,g:v>ReTJw1!#qX=x!eC{bLu+wT&)ZtZauq_~Graci&U#F|89:r_Lupvq!.)&2RlG8RfaC=x!eF{_h?rpWlmd&'!#X|&]k::xJey#`'T|+<E|&2@H|%dE#(^,g;u.RiEg6vjRiC9xCkA{O|zY#g=ucRmXKs0@!&*@G|m@awRknJuh!,3d(}gY}eJvj!%Rm):Jw3!%Rm+Rm-Ls0w(&!a(a#@b[|6cZ#X'7RkxWgAOu4ARn'dH'U#Y*Vz-Wm'CARm}d]*#a%^a*T'aK!a<9bV{PC=p*Jw4!&SgxcbB5r]idw(wBRmF7xFkt#&`(Rm/Rm8E|!JuY_9:Rl5=wrgr2:bbxd@xXfB(a*#T+!.X0X1Ta/a'T&RlDRfL>RlyARl9b[z[>RfZ:RlL:RfRwlg/ARl;9;RlxKv,A/!%7s69<74=BA5ba{-8Bde#`a<XaKYa1,a'P~=wxfB2bZ}}?C972@@=I}r8@55B9;5bb}G978B2@@=aybb}3j3vLv;<Jw3&!>Rfk=ayb^}4~Ad1#`*@@=aybb{w2@>==<bbz]dx+UY#^UaF!a9!bB'Ya1.!ajXa#%olRhD[y=3Dt#Ov5BrHKuMB%!(Rf^Wep~HrJwkiQjKr|~FRg)Ku+D#'!t5~GrF~?rDdV)UY,Z/_7RkuG{<~BrBg,rlsO:235B@bX}|d?a1!#`(6Vyn5@d##Y+jTv|vV~EfIj]uNpn~FRfH7Lq2vb1!a9-978BaU@@=Iz9978BbU}#~AJq0!(@@=Iz8978BaU@@=Iz7~AJQ|}!978BbU}!JvkaK!AdUa21-U#`a+(g/vsRn~Ou!5RPj:rmu9WhOjXuvvNr}:RhAj^v(pyw8unRn[kPr}p|u7vwv]RiSBd;pppzq@qHQa?(b.!a.a`@.|xa(hFv;Wiyj5uuv-7Riw~Cw`fg2WlU978BbU|wOuNBJqG!(P~EfD~CRlQcZ#X,k)u3vWs@u2]ksg;wEx'f@q1_2Wg.j]uNpn~FRfqJv]!15x'h{qG!(@@=IzK~CRl^j6v(us5x4i,#T(2WmY?C2F{1>Kq<aj1!*jTqIsBv=Wld~Cw`fj2Wl[j`v0u*~>RlT=c>Z,k#u3vWs@u2]kq<c1Z+jTqIsBv=Wle~Cw`fn2Wl]dn1#c(a(b^a2!b/bAT(bj!aDa7bu,a_a{c0!2T0g:v>ReD2@G{42@G{5~DpM~<5rc=Bx6i>{RT#RnI@zCx]y]z:2Jv[!zr5Awyk]9]k]dD(Y+X#6Vz.g=wKtgwhaCwgmTWj2Lu,w%_+/[y-B;b^xeg3u3Rj-2@bX{*KrJ<!+'@Wg(g?QRlC@Jv`!%b[zIwsfII}8JQ_@w|kW|=Jv(%!AqcOuNBJvEzh!bYzjLs@wP#(0!oy@>RkdJwMZtc3Dtd@BcG#T'9bWxg2@2Fznd*#Y+;2x'c}w<zizixNgwa#Z'U+!/!a'!a+w~g~z6wcn{Rn}wcnzRn|5Rh%=]nJg5vuRmvNvdRlvcprJu}w*az*a#!%.a.'Bot9qT]kj@Wg'ay2Gzv@Jv`!%b[zEwsfHI}1;ck#Ux`<Cbbx_Lu+w!a&0*!wko*wwo,So,}6Juqxf!E}PigQuyRm`d3(`#8>Rn%:A5B;bZ~%KvhCa!a2!x>k7#Uxb@b{#xaRk7Jw0!)>wwhlShl}6>wwhmShm}6CJvB!.x'hhvj{!!5Bwkhhbaz}x'hivjz~!5Bwkhibaz|xEhTrNu,v-vpD!a%&/)a3a.,%Ro2t[CE{)@3re9b]{%wjo09:rgc:Z&Ro6=<riifuaw&RmoKrNA!%(Ro4>Ro89;Ri`dSaL'UYzxZb)7Rka3xRhT&!,!#^1U}vbaz{>>@=be}yC@:D5bazzKu+A&!}{?ba}y>>@=be}wxBh[t`u~vJvr!%a!a()a,a0a4RoC=]o;Ju(!%RoGRhdwjh`=]oAg>w#Ro?g5vuRo=NvdRl|Ku]C.!&;RoEJvB!%RoORoMBx'h[v+_?w~h`}~5?w~hd~!xKh]oiptu-utv.vp!#%&a30a@a'a+(a/aOp(o~p!RoDJu(!%RoHRhewjha=]oBNvdRl}g>w#Ro@g5vuRo>c[#X']o<CauRoRAd-#Y':RkpauRoQKu]C.!&;RoFJvB!%RoNRoPBx'h]v+_?w~ha}t5?w~he}ue!/UbhYacXaW^Tc&a;b:a-c/#b&aja1(!cL+!bKbt!bmcRc9aIc?8[yW3Dtt94Rg`Jv}!&SiRMzBhEebShEMNuPRe>x7gL#TzuwjirRipc<Z&>on;>z=h-MSh.Mwqczx'a7vj&!>Re4@=ResJt__NuPRi*NuPRi)j]uNr|~FRfzKrJ>_+@Wfy@Wf]2WocKrJ<!+'@Wg%g/QRl@@Jv`!&awRl<wsfFIzgLu(w*!.*&ShBMwvhIRhI9;RhNx1hK'!#Sn]Mx1hK~0!#:2<H~7cNu+w7D*'1ZtW>Rn1~?rOc:Z&Rn2=<rQ<7wjh&=BSnLMc]#X(6Vz)w[b=a!U#9wzgMc3#&(RgMRitRis<x,gKt`ax!&+SioM=BSilMc3#&(RgKRinRimKurB,!&SiQMzBhDebShDM6BJQ!(P~Efx978B2@@=I}WLrJw!!,a*&@G}O@9wkibRid@@x'fKwC!&SlDMSfLMjUv~Q~EfKKv3@a+!(hFv-]mpx/hYZ(C5RiWz<o/MwkhY?So/M@x,gbvfB*&!SgEM:SoeeehFu3:Rgbda(,^TZa)X/7Sg[eb:2RgI~BrMC@wgkc:wwkcRerx3h(uUvK!&*,SnOM4Sh*MArRg;wHRh(x=h;rJvPwI!a4',a'0@Wg&=BSh/Mg>w=Rh=g3w*wwgGRgGcW(X#;Sg}M2Gzk@Jv`!&awRl=wsfGIz`dKZ*T'Y-:RhR7RhQg5u-p`j6v(us5d,#Y+~Awkia?RicOuNBwkibba}Ld6p~tyu_vbAa'a+!a/'a3aEa8a!>Sh,ebJv{!&Sh@ebSaReb9;SgwebNuPRi(NvdRl)NuPRi'hHu^<Rm^Jvv_@Wl(g;u1Si/ebKu'B&!*Sh?eb@Wl'z@aPeb95Si.ebcpputyvjB)!,&a+0a%ShAMWeK@G}C@WfJ9;RhMwvhH9w{ia}ix,hJvRA1(!zAn[MRhHx1hJ~*!#hFv(BSn[MBJQ!(@@=I~'978B2@@=I}2db.Ua<'X}+T#a0XaG2G}E;wkg|wuh!Rh!x,hZu,@)!&So0MVy)C5RiXACJvB!&5RiY5RiZg8w)cG}*T#2@bU}=KsA>(!a.3wkhZba~(x,h^u(A!&(SoCMRhb5Bz=h[eb?w~hb~6x,h_u(A!&(SoDMRhc5Bz=h]eb?w~hc~6e)aA1T#T,^^^c-bMb&blcPaP(a/!0!bA=b5c@a(!bfbrc#2afwmhARnjwchORnp2Wlf3DtsNvdRl-2@wpa<]m0bx(#:awRk2@Jw3!%RfhwpfgRlnKQB%!(G{V@G|'NuuRl6d='T+Y#VyUg<v~Rl~==G|<Jv+'!aYShC}6@B<5?ba~8@Jw3'!g2QRljhLrpWlOd+#Y'g.w'rIg>w*wgj@g-u0Rj@Lu+wT&)ZtUauq]~GrGci&U#F|39:rELrNvj!.%*RhCwunfw~nf~:9;Ri]>wtnhg;wHRnhx3hDs@v~!/+'@Wfr@9RkSNu&Rlo=@<5GzoKs0@_+@Wl+@awRkmJuh!-3d(}pY#qWJvj!%Rm(:Jw3!%Rm,Rm*de&!1U-U#`)Re;@G|.@9Ri82@wjfvRlq=@<5GzpLvOvr!).&2RlF8Rf`C=x!eE{.Jw3_g2QRlkhLrpWlPde(!#U{s,UXa*Ta'[y'g:v>ReS;x0PZ&RnlRnn~HrKJw1}f!=x!eB|2w]aP(#Xa&a*Ta.Ua2a7=]iOd'#Y&Ro&WnWg;u.RiDg6vjRiBNvdRlzhNvj]nYJuW_2Wm3x)kFze{9d])!a.!,Y01!#&aC!a3RndC=ox~BrC@2b^{pg,rlse7x'ksuq!%Rm.E{xidw(wBRmGx9o+)X#wwo-So-}69:Rl4@xSf@a#XZ'X)X,Ta(/ARl8b[xc>RfY:RlI:RfQwlg.ARl:9;Rlwdn'#^XafaQa1X1TaHTa)@b[{zcZ#X'7RkwWg@Ou4ARn&x)kG#{,g7u/RkGdH'U#Y*Vz'Wm&CARm|bx#(A]gUbUzJj9Q~=d,#Y(56H}l978H{U7d,0#U*2>ABb_xZ978BbU{e~AJQ{g!978BbU{hxMh?ad{oUYZ.x1h?{l!#:2<H{mx3n[t{vl!,&a%3Ro(z=iS}6ARnr=Bwsn^wvn`Rnbd`*T}B0!#^X'BG{c9b]{a>>@=be}F?JvS!&BG{d7BG}(Bde#`a1X,Ya@!a'P~=wxf@2bZ}I56B2@@=aybb}08@55B9;5bb}<j3vLv;<Jw3&!>Rfg=ayb^}&OuNBKuLA!)a!P~=x#fD{f2@>==<bbzl?C972@@=Ix^d6rSu,v7w*C(0a)a6#B+a%!sQ[y?3Dt%3[xn~<5rLOu!5p@Ku+D#'!t7~GrP~?rNKvlaya7'!h+v-5qMg=t|cd,U#5AAaa5Abb{S@52B5@a[@52B5Gx[iXueu;d<#`a(!/549C;ag>23ExY5@Dah89b^~689Jv)!~2b[~1Lv'w(%*!a#bX|aPrmawRe]keu7uhv-q6rxu,q`xTo]/a5aU!bNaDXbi!b-!ao!b<bwA!#5@B932:aV2G|:d-)Y#hJrL>RhG<7@C5<H|_=Cau:5aj5@B932:bJ|ng>vIbs)#?C2F|9jPv0w.vISh-MKvUaz(.!9ABbb|[5;5<H|Eg>unwfh;9:4E|YjQsBt|vjx'hYq3!(?C2F|J:2<BaY?C2F|GOu!5x,g|p{ah!-(?C2F|c9:4E|OjXuvvNr}:Rh&i[w*t|cd+U#jJvsu)vsSn~Mkfrmu9p}u7vwv]So!McW#Xa!ax5@A5aY:5;5<H|>kJv~vYrquJu3x4ib#T)2@SmZM?C2F|Bj:rmu9@xPhI(a*a#U#`a3-5Abb|L~@:RhK9:4E|0@52B5G|#C::aY?C2F|-:2<BaY?C2F|.5Jvk!a)javYrquJu3x4ia#T)2@SmYM?C2F|HAxPhH(!a#U#`a*-5Abb|4~@:RhJ9:4E|R@52B5G|F:2<BaY?C2F|Sc^#Xa2j=Qq5CJvB!-g<v{z;hhM?C2F|Zi[vrv{z;hiM?C2F|XKsA>!a)-g<v{z;h[eb?C2F|]i[vrv{z;h]eb?C2F|^iZu.vix,hZq3ah!.(?C2F|QOu!5ShXM:2<BaY?C2F|P",13494,2713,49,25,61)});var VI;var Oce=Ho(()=>{VI=new Uint16Array([512,26465,29036,7,0,2,4,116,24638,116,24636,8693,29807,24610,621,1,0,0,3,112,24614,111,115,24615])});var ec;var zNe=Ho(()=>{(function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.FLAG13=8192]="FLAG13",e[e.BRANCH_LENGTH=8064]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE",e[e.VALUE_MASK=8191]="VALUE_MASK"})(ec||(ec={}))});function jNe(e){return e-bl.ZERO>>>0<=9}function OCi(e){return(e|Kj)-bl.LOWER_A>>>0<=5}function NCi(e){return(e|Kj)-bl.LOWER_A>>>0<=25}function LCi(e){return e===bl.EQUALS||NCi(e)||jNe(e)}class Nce{decodeTree;emitCodePoint;errors;state=yl.EntityStart;consumed=1;result=0;treeIndex=0;excess=1;decodeMode=Lm.Strict;runConsumed=0;constructor(e,t,i){this.decodeTree=e,this.emitCodePoint=t,this.errors=i}startEntity(e){this.decodeMode=e,this.state=yl.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0}write(e,t){switch(this.state){case yl.EntityStart:{if(e.charCodeAt(t)===bl.NUM)return this.state=yl.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1);return this.state=yl.NamedEntity,this.stateNamedEntity(e,t)}case yl.NumericStart:return this.stateNumericStart(e,t);case yl.NumericDecimal:return this.stateNumericDecimal(e,t);case yl.NumericHex:return this.stateNumericHex(e,t);default:return this.stateNamedEntity(e,t)}}stateNumericStart(e,t){if(t>=e.length)return-1;if((e.charCodeAt(t)|Kj)===bl.LOWER_X)return this.state=yl.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1);return this.state=yl.NumericDecimal,this.stateNumericDecimal(e,t)}stateNumericHex(e,t){let i=e.length,{result:r}=this,{consumed:n}=this;while(t<i){let o=e.charCodeAt(t);if(jNe(o)||OCi(o)){let s=o<=bl.NINE?o-bl.ZERO:(o|Kj)-bl.LOWER_A+10;r=r*16+s,n+=1,t+=1}else return this.result=r,this.consumed=n,this.emitNumericEntity(o,3)}return this.result=r,this.consumed=n,-1}stateNumericDecimal(e,t){let i=e.length,{result:r}=this,{consumed:n}=this;while(t<i){let o=e.charCodeAt(t)-bl.ZERO;if(o>>>0>9)return this.result=r,this.consumed=n,this.emitNumericEntity(o+bl.ZERO,2);r=r*10+o,n+=1,t+=1}return this.result=r,this.consumed=n,-1}emitNumericEntity(e,t){if(this.consumed<=t)return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(e===bl.SEMI)this.consumed+=1;else if(this.decodeMode===Lm.Strict)return 0;if(this.emitCodePoint((this.decodeTree===VI?FNe:RNe)(this.result),this.consumed),this.errors){if(e!==bl.SEMI)this.errors.missingSemicolonAfterCharacterReference();this.errors.validateNumericCharacterReference(this.result)}return this.consumed}flushAndEmitLegacyOrReject(e,t,i,r){return this.consumed=e,this.excess=t,this.result===0||this.decodeMode===Lm.Attribute&&(r===0||t>1||LCi(i))?0:this.emitNotTerminatedNamedEntity()}stateNamedEntity(e,t){let{decodeTree:i}=this,r=e.length,n=this.decodeMode===Lm.Strict,{treeIndex:o}=this,{excess:s}=this,{consumed:a}=this,c=i[o];while(t<r){while((c&(ec.VALUE_LENGTH|ec.FLAG13))===0&&(c&ec.JUMP_TABLE)!==0){let m=e.charCodeAt(t),h=c&ec.JUMP_TABLE,f=(c&ec.BRANCH_LENGTH)>>7;if(f===0){if(m!==h)return this.flushAndEmitLegacyOrReject(a,s,m,0);o+=1}else{let g=m-h;if(g>>>0>=f)return this.flushAndEmitLegacyOrReject(a,s,m,0);let y=i[o+1+g];if(y===0)return this.flushAndEmitLegacyOrReject(a,s,m,0);o=o+f+y&65535}if(c=i[o],t+=1,s+=1,t>=r)break}if(t>=r)break;if((c&(ec.VALUE_LENGTH|ec.FLAG13))===ec.FLAG13){let m=(c&ec.BRANCH_LENGTH)>>7,{runConsumed:h}=this;if(h===0){let f=e.charCodeAt(t);if(f!==(c&ec.JUMP_TABLE))return this.flushAndEmitLegacyOrReject(a,s,f,0);t+=1,s+=1,h=1}while(h<m){if(t>=r)return this.treeIndex=o,this.excess=s,this.consumed=a,this.runConsumed=h,-1;let f=h-1,y=i[o+1+(f>>1)]>>((f&1)<<3)&255,b=e.charCodeAt(t);if(b!==y)return this.runConsumed=0,this.flushAndEmitLegacyOrReject(a,s,b,0);t+=1,s+=1,h+=1}this.runConsumed=0,o+=1+(m>>1),c=i[o];continue}let u=c>>>14,d=e.charCodeAt(t);if(u!==0){if(!n&&(c&ec.FLAG13)===0)this.result=o,a+=s-1,s=1;if(d===bl.SEMI)return this.emitNamedEntityData(o,u,a+s);if(u===1)return this.flushAndEmitLegacyOrReject(a,s,d,u)}let p=zCi(i,c,o+(u||1),d);if(p<0)return this.flushAndEmitLegacyOrReject(a,s,d,u);o=p,c=i[o],t+=1,s+=1}if(!n&&c>>>14!==0&&(c&ec.FLAG13)===0)this.result=o,a+=s-1,s=1;return this.treeIndex=o,this.excess=s,this.consumed=a,-1}emitNotTerminatedNamedEntity(){let{result:e,decodeTree:t}=this,i=t[e]>>>14;return this.emitNamedEntityData(e,i,this.consumed),this.errors?.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(e,t,i){let{decodeTree:r}=this;if(this.emitCodePoint(t===1?r[e]&ec.VALUE_MASK:r[e+1],i),t===3)this.emitCodePoint(r[e+2],i);return i}end(){switch(this.state){case yl.NamedEntity:return this.result!==0&&(this.decodeMode!==Lm.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case yl.NumericDecimal:return this.emitNumericEntity(0,2);case yl.NumericHex:return this.emitNumericEntity(0,3);case yl.NumericStart:return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;default:return 0}}}function zCi(e,t,i,r){let n=(t&ec.BRANCH_LENGTH)>>7,o=t&ec.JUMP_TABLE;if(o){if(n===0)return r===o?i:-1;let c=r-o;if(c>>>0>=n)return-1;let u=e[i+c];return u===0?-1:i+n+u-1&65535}if(n===0)return-1;let s=n+1>>1,a=i+s+n;for(let c=0;c<n;c++){let d=e[i+(c>>1)]>>((c&1)<<3)&255;if(d===r){let p=i+s+c;return a+e[p]&65535}if(d>r)return-1}return-1}var bl,Kj=32,yl,Lm;var UNe=Ho(()=>{MNe();Oce();zNe();LNe();Oce();(function(e){e[e.AMP=38]="AMP",e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_X=120]="LOWER_X"})(bl||(bl={}));(function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity"})(yl||(yl={}));(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(Lm||(Lm={}))});function Nw(e){return e===hi.Space||e===hi.NewLine||e===hi.Tab||e===hi.FormFeed||e===hi.CarriageReturn}function U2(e){return e===hi.Slash||e===hi.Gt||Nw(e)}function jCi(e){return e>=hi.LowerA&&e<=hi.LowerZ||e>=hi.UpperA&&e<=hi.UpperZ}class q2{cbs;state=He.Text;buffer="";sectionStart=0;index=0;entityStart=0;baseState=He.Text;isSpecial=!1;running=!0;offset=0;xmlMode;decodeEntities;recognizeSelfClosing;entityDecoder;constructor({xmlMode:e=!1,decodeEntities:t=!0,recognizeSelfClosing:i=e},r){this.cbs=r,this.xmlMode=e,this.decodeEntities=t,this.recognizeSelfClosing=i,this.entityDecoder=new Nce(e?VI:Mce,(n,o)=>this.emitCodePoint(n,o))}reset(){this.state=He.Text,this.buffer="",this.sectionStart=0,this.index=0,this.baseState=He.Text,this.isSpecial=!1,this.currentSequence=Xi.Empty,this.sequenceIndex=0,this.running=!0,this.offset=0}write(e){this.offset+=this.buffer.length,this.buffer=e,this.parse()}end(){if(this.running)this.finish()}pause(){this.running=!1}resume(){if(this.running=!0,this.index<this.buffer.length+this.offset)this.parse()}stateText(e){if(e===hi.Lt||!this.decodeEntities&&this.fastForwardTo(hi.Lt)){if(this.index>this.sectionStart)this.cbs.ontext(this.sectionStart,this.index);this.state=He.BeforeTagName,this.sectionStart=this.index}else if(this.decodeEntities&&e===hi.Amp)this.startEntity()}currentSequence=Xi.Empty;sequenceIndex=0;enterTagBody(){if(this.currentSequence===Xi.Plaintext)this.currentSequence=Xi.Empty,this.state=He.InPlainText;else if(this.isSpecial)this.state=He.InSpecialTag,this.sequenceIndex=0;else this.state=He.Text}stateSpecialStartSequence(e){let t=e|32;if(this.sequenceIndex<this.currentSequence.length){if(t===this.currentSequence[this.sequenceIndex]){this.sequenceIndex++;return}if(this.sequenceIndex===3){if(this.currentSequence===Xi.ScriptEnd&&t===Xi.StyleEnd[3]){this.currentSequence=Xi.StyleEnd,this.sequenceIndex=4;return}if(this.currentSequence===Xi.TitleEnd&&t===Xi.TextareaEnd[3]){this.currentSequence=Xi.TextareaEnd,this.sequenceIndex=4;return}}else if(this.sequenceIndex===4&&this.currentSequence===Xi.NoembedEnd&&t===Xi.NoframesEnd[4]){this.currentSequence=Xi.NoframesEnd,this.sequenceIndex=5;return}}else if(U2(e)){this.sequenceIndex=0,this.state=He.InTagName,this.stateInTagName(e);return}this.isSpecial=!1,this.currentSequence=Xi.Empty,this.sequenceIndex=0,this.state=He.InTagName,this.stateInTagName(e)}stateCDATASequence(e){if(e===Xi.Cdata[this.sequenceIndex]){if(++this.sequenceIndex===Xi.Cdata.length)this.state=He.InCommentLike,this.currentSequence=Xi.CdataEnd,this.sequenceIndex=0,this.sectionStart=this.index+1}else if(this.sequenceIndex=0,this.xmlMode)this.state=He.InDeclaration,this.stateInDeclaration(e);else this.state=He.InSpecialComment,this.stateInSpecialComment(e)}fastForwardTo(e){while(++this.index<this.buffer.length+this.offset)if(this.buffer.charCodeAt(this.index-this.offset)===e)return!0;return this.index=this.buffer.length+this.offset-1,!1}emitComment(e){this.cbs.oncomment(this.sectionStart,this.index,e),this.sequenceIndex=0,this.sectionStart=this.index+1,this.state=He.Text}stateInCommentLike(e){if(!this.xmlMode&&this.currentSequence===Xi.CommentEnd&&this.sequenceIndex<=1&&this.index===this.sectionStart+this.sequenceIndex&&e===hi.Gt)this.emitComment(this.sequenceIndex);else if(this.currentSequence===Xi.CommentEnd&&this.sequenceIndex===2&&e===hi.Gt)this.emitComment(2);else if(this.currentSequence===Xi.CommentEnd&&this.sequenceIndex===this.currentSequence.length-1&&e!==hi.Gt)this.sequenceIndex=Number(e===hi.Dash);else if(e===this.currentSequence[this.sequenceIndex]){if(++this.sequenceIndex===this.currentSequence.length){if(this.currentSequence===Xi.CdataEnd)this.cbs.oncdata(this.sectionStart,this.index,2);else this.cbs.oncomment(this.sectionStart,this.index,3);this.sequenceIndex=0,this.sectionStart=this.index+1,this.state=He.Text}}else if(this.sequenceIndex===0){if(this.fastForwardTo(this.currentSequence[0]))this.sequenceIndex=1}else if(e!==this.currentSequence[this.sequenceIndex-1])this.sequenceIndex=0}isTagStartChar(e){return this.xmlMode?!U2(e):jCi(e)}stateInSpecialTag(e){if(this.sequenceIndex===this.currentSequence.length){if(U2(e)){let t=this.index-this.currentSequence.length;if(this.sectionStart<t){let i=this.index;this.index=t,this.cbs.ontext(this.sectionStart,t),this.index=i}this.isSpecial=!1,this.sectionStart=t+2,this.stateInClosingTagName(e);return}this.sequenceIndex=0}if((e|32)===this.currentSequence[this.sequenceIndex])this.sequenceIndex+=1;else if(this.sequenceIndex===0){if(this.currentSequence===Xi.TitleEnd||this.currentSequence===Xi.TextareaEnd){if(this.decodeEntities&&e===hi.Amp)this.startEntity()}else if(this.fastForwardTo(hi.Lt))this.sequenceIndex=1}else this.sequenceIndex=Number(e===hi.Lt)}stateBeforeTagName(e){if(e===hi.ExclamationMark)this.state=He.BeforeDeclaration,this.sectionStart=this.index+1;else if(e===hi.Questionmark)if(this.xmlMode)this.state=He.InProcessingInstruction,this.sequenceIndex=0,this.sectionStart=this.index+1;else this.state=He.InSpecialComment,this.sectionStart=this.index;else if(this.isTagStartChar(e)){this.sectionStart=this.index;let t=this.xmlMode||this.cbs.isInForeignContext?.()?void 0:UCi.get(e|32);if(t===void 0)this.state=He.InTagName;else this.isSpecial=!0,this.currentSequence=t,this.sequenceIndex=3,this.state=He.SpecialStartSequence}else if(e===hi.Slash)this.state=He.BeforeClosingTagName;else this.state=He.Text,this.stateText(e)}stateInTagName(e){if(U2(e))this.cbs.onopentagname(this.sectionStart,this.index),this.sectionStart=-1,this.state=He.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateBeforeClosingTagName(e){if(Nw(e))if(this.xmlMode);else this.state=He.InSpecialComment,this.sectionStart=this.index;else if(e===hi.Gt){if(this.state=He.Text,!this.xmlMode)this.sectionStart=this.index+1}else this.state=this.isTagStartChar(e)?He.InClosingTagName:He.InSpecialComment,this.sectionStart=this.index}stateInClosingTagName(e){if(U2(e))this.cbs.onclosetag(this.sectionStart,this.index),this.sectionStart=-1,this.state=He.AfterClosingTagName,this.stateAfterClosingTagName(e)}stateAfterClosingTagName(e){if(e===hi.Gt||this.fastForwardTo(hi.Gt))this.state=He.Text,this.sectionStart=this.index+1}stateBeforeAttributeName(e){if(e===hi.Gt)this.cbs.onopentagend(this.index),this.enterTagBody(),this.sectionStart=this.index+1;else if(e===hi.Slash)this.state=He.InSelfClosingTag;else if(!Nw(e))this.state=He.InAttributeName,this.sectionStart=this.index}stateInSelfClosingTag(e){if(e===hi.Gt){if(this.cbs.onselfclosingtag(this.index),this.sectionStart=this.index+1,!this.recognizeSelfClosing){this.enterTagBody();return}this.state=He.Text,this.isSpecial=!1,this.currentSequence=Xi.Empty}else if(!Nw(e))this.state=He.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateInAttributeName(e){if(e===hi.Eq||U2(e))this.cbs.onattribname(this.sectionStart,this.index),this.sectionStart=this.index,this.state=He.AfterAttributeName,this.stateAfterAttributeName(e)}stateAfterAttributeName(e){if(e===hi.Eq)this.state=He.BeforeAttributeValue;else if(e===hi.Slash||e===hi.Gt)this.cbs.onattribend(ap.NoValue,this.sectionStart),this.sectionStart=-1,this.state=He.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(!Nw(e))this.cbs.onattribend(ap.NoValue,this.sectionStart),this.state=He.InAttributeName,this.sectionStart=this.index}stateBeforeAttributeValue(e){if(e===hi.DoubleQuote)this.state=He.InAttributeValueDq,this.sectionStart=this.index+1;else if(e===hi.SingleQuote)this.state=He.InAttributeValueSq,this.sectionStart=this.index+1;else if(!Nw(e))this.sectionStart=this.index,this.state=He.InAttributeValueNq,this.stateInAttributeValueNoQuotes(e)}handleInAttributeValue(e,t){if(e===t||!this.decodeEntities&&this.fastForwardTo(t))this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(t===hi.DoubleQuote?ap.Double:ap.Single,this.index+1),this.state=He.BeforeAttributeName;else if(this.decodeEntities&&e===hi.Amp)this.startEntity()}stateInAttributeValueDoubleQuotes(e){this.handleInAttributeValue(e,hi.DoubleQuote)}stateInAttributeValueSingleQuotes(e){this.handleInAttributeValue(e,hi.SingleQuote)}stateInAttributeValueNoQuotes(e){if(Nw(e)||e===hi.Gt)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(ap.Unquoted,this.index),this.state=He.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(this.decodeEntities&&e===hi.Amp)this.startEntity()}stateBeforeDeclaration(e){if(e===hi.OpeningSquareBracket)this.state=He.CDATASequence,this.sequenceIndex=0;else if(this.xmlMode)this.state=e===hi.Dash?He.BeforeComment:He.InDeclaration;else if((e|32)===Xi.Doctype[0])this.state=He.DeclarationSequence,this.currentSequence=Xi.Doctype,this.sequenceIndex=1;else if(e===hi.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=He.Text,this.sectionStart=this.index+1;else if(e===hi.Dash)this.state=He.BeforeComment;else this.state=He.InSpecialComment}stateDeclarationSequence(e){if(this.sequenceIndex===this.currentSequence.length)this.state=He.InDeclaration,this.stateInDeclaration(e);else if((e|32)===this.currentSequence[this.sequenceIndex])this.sequenceIndex+=1;else if(e===hi.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=He.Text,this.sectionStart=this.index+1;else this.state=He.InSpecialComment}stateInDeclaration(e){if(e===hi.Gt||this.fastForwardTo(hi.Gt))this.cbs.ondeclaration(this.sectionStart,this.index),this.state=He.Text,this.sectionStart=this.index+1}stateInProcessingInstruction(e){if(e===hi.Questionmark)this.sequenceIndex=1;else if(e===hi.Gt&&this.sequenceIndex===1)this.cbs.onprocessinginstruction(this.sectionStart,this.index-1),this.sequenceIndex=0,this.state=He.Text,this.sectionStart=this.index+1;else this.sequenceIndex=Number(this.fastForwardTo(hi.Questionmark))}stateBeforeComment(e){if(e===hi.Dash)this.state=He.InCommentLike,this.currentSequence=Xi.CommentEnd,this.sequenceIndex=0,this.sectionStart=this.index+1;else if(this.xmlMode)this.state=He.InDeclaration;else if(e===hi.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=He.Text,this.sectionStart=this.index+1;else this.state=He.InSpecialComment}stateInSpecialComment(e){if(e===hi.Gt||this.fastForwardTo(hi.Gt))this.cbs.oncomment(this.sectionStart,this.index,0),this.state=He.Text,this.sectionStart=this.index+1}startEntity(){this.baseState=this.state,this.state=He.InEntity,this.entityStart=this.index,this.entityDecoder.startEntity(this.xmlMode?Lm.Strict:this.baseState===He.Text||this.baseState===He.InSpecialTag?Lm.Legacy:Lm.Attribute)}stateInEntity(){let e=this.index-this.offset,t=this.entityDecoder.write(this.buffer,e);if(t>=0){if(this.state=this.baseState,t===0)this.index-=1}else{if(e<this.buffer.length&&this.buffer.charCodeAt(e)===hi.Amp){this.state=this.baseState,this.index-=1;return}this.index=this.offset+this.buffer.length-1}}cleanup(){if(this.running&&this.sectionStart!==this.index){if(this.state===He.Text||this.state===He.InPlainText||this.state===He.InSpecialTag&&this.sequenceIndex===0)this.cbs.ontext(this.sectionStart,this.index),this.sectionStart=this.index;else if(this.state===He.InAttributeValueDq||this.state===He.InAttributeValueSq||this.state===He.InAttributeValueNq)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=this.index}}shouldContinue(){return this.index<this.buffer.length+this.offset&&this.running}parse(){while(this.shouldContinue()){let e=this.buffer.charCodeAt(this.index-this.offset);switch(this.state){case He.Text:{this.stateText(e);break}case He.InPlainText:{this.index=this.buffer.length+this.offset-1;break}case He.SpecialStartSequence:{this.stateSpecialStartSequence(e);break}case He.InSpecialTag:{this.stateInSpecialTag(e);break}case He.CDATASequence:{this.stateCDATASequence(e);break}case He.DeclarationSequence:{this.stateDeclarationSequence(e);break}case He.InAttributeValueDq:{this.stateInAttributeValueDoubleQuotes(e);break}case He.InAttributeName:{this.stateInAttributeName(e);break}case He.InCommentLike:{this.stateInCommentLike(e);break}case He.InSpecialComment:{this.stateInSpecialComment(e);break}case He.BeforeAttributeName:{this.stateBeforeAttributeName(e);break}case He.InTagName:{this.stateInTagName(e);break}case He.InClosingTagName:{this.stateInClosingTagName(e);break}case He.BeforeTagName:{this.stateBeforeTagName(e);break}case He.AfterAttributeName:{this.stateAfterAttributeName(e);break}case He.InAttributeValueSq:{this.stateInAttributeValueSingleQuotes(e);break}case He.BeforeAttributeValue:{this.stateBeforeAttributeValue(e);break}case He.BeforeClosingTagName:{this.stateBeforeClosingTagName(e);break}case He.AfterClosingTagName:{this.stateAfterClosingTagName(e);break}case He.InAttributeValueNq:{this.stateInAttributeValueNoQuotes(e);break}case He.InSelfClosingTag:{this.stateInSelfClosingTag(e);break}case He.InDeclaration:{this.stateInDeclaration(e);break}case He.BeforeDeclaration:{this.stateBeforeDeclaration(e);break}case He.BeforeComment:{this.stateBeforeComment(e);break}case He.InProcessingInstruction:{this.stateInProcessingInstruction(e);break}case He.InEntity:{this.stateInEntity();break}}this.index++}this.cleanup()}finish(){if(this.state===He.InEntity)this.entityDecoder.end(),this.state=this.baseState;this.handleTrailingData(),this.cbs.onend()}handleTrailingCommentLikeData(e){if(this.state!==He.InCommentLike)return!1;if(this.currentSequence===Xi.CdataEnd)if(this.xmlMode){if(this.sectionStart<e)this.cbs.oncdata(this.sectionStart,e,0)}else{let t=this.sectionStart-Xi.Cdata.length-1;this.cbs.oncomment(t,e,0)}else{let t=this.xmlMode?0:Math.min(this.sequenceIndex,Xi.CommentEnd.length-1);this.cbs.oncomment(this.sectionStart,e,t)}return!0}handleTrailingMarkupDeclaration(e){if(this.xmlMode)switch(this.state){case He.InSpecialComment:case He.BeforeComment:case He.CDATASequence:case He.DeclarationSequence:case He.InDeclaration:return this.cbs.ontext(this.sectionStart,e),!0;default:return!1}switch(this.state){case He.BeforeDeclaration:case He.InSpecialComment:case He.BeforeComment:case He.CDATASequence:return this.cbs.oncomment(this.sectionStart,e,0),!0;case He.DeclarationSequence:{if(this.sequenceIndex!==Xi.Doctype.length)this.cbs.oncomment(this.sectionStart,e,0);return!0}case He.InDeclaration:return!0;default:return!1}}handleTrailingData(){let e=this.buffer.length+this.offset;if(this.handleTrailingCommentLikeData(e)||this.handleTrailingMarkupDeclaration(e))return;if(this.sectionStart>=e)return;switch(this.state){case He.InTagName:case He.BeforeAttributeName:case He.BeforeAttributeValue:case He.AfterAttributeName:case He.InAttributeName:case He.InAttributeValueSq:case He.InAttributeValueDq:case He.InAttributeValueNq:case He.InClosingTagName:break;default:this.cbs.ontext(this.sectionStart,e)}}emitCodePoint(e,t){if(this.baseState!==He.Text&&this.baseState!==He.InSpecialTag){if(this.sectionStart<this.entityStart)this.cbs.onattribdata(this.sectionStart,this.entityStart);this.sectionStart=this.entityStart+t,this.index=this.sectionStart-1,this.cbs.onattribentity(e)}else{if(this.sectionStart<this.entityStart)this.cbs.ontext(this.sectionStart,this.entityStart);this.sectionStart=this.entityStart+t,this.index=this.sectionStart-1,this.cbs.ontextentity(e,this.sectionStart)}}}var hi,He,ap,Xi,UCi;var Lce=Ho(()=>{UNe();(function(e){e[e.Tab=9]="Tab",e[e.NewLine=10]="NewLine",e[e.FormFeed=12]="FormFeed",e[e.CarriageReturn=13]="CarriageReturn",e[e.Space=32]="Space",e[e.ExclamationMark=33]="ExclamationMark",e[e.Number=35]="Number",e[e.Amp=38]="Amp",e[e.SingleQuote=39]="SingleQuote",e[e.DoubleQuote=34]="DoubleQuote",e[e.Dash=45]="Dash",e[e.Slash=47]="Slash",e[e.Zero=48]="Zero",e[e.Nine=57]="Nine",e[e.Semi=59]="Semi",e[e.Lt=60]="Lt",e[e.Eq=61]="Eq",e[e.Gt=62]="Gt",e[e.Questionmark=63]="Questionmark",e[e.UpperA=65]="UpperA",e[e.LowerA=97]="LowerA",e[e.UpperF=70]="UpperF",e[e.LowerF=102]="LowerF",e[e.UpperZ=90]="UpperZ",e[e.LowerZ=122]="LowerZ",e[e.LowerX=120]="LowerX",e[e.OpeningSquareBracket=91]="OpeningSquareBracket"})(hi||(hi={}));(function(e){e[e.Text=1]="Text",e[e.BeforeTagName=2]="BeforeTagName",e[e.InTagName=3]="InTagName",e[e.InSelfClosingTag=4]="InSelfClosingTag",e[e.BeforeClosingTagName=5]="BeforeClosingTagName",e[e.InClosingTagName=6]="InClosingTagName",e[e.AfterClosingTagName=7]="AfterClosingTagName",e[e.BeforeAttributeName=8]="BeforeAttributeName",e[e.InAttributeName=9]="InAttributeName",e[e.AfterAttributeName=10]="AfterAttributeName",e[e.BeforeAttributeValue=11]="BeforeAttributeValue",e[e.InAttributeValueDq=12]="InAttributeValueDq",e[e.InAttributeValueSq=13]="InAttributeValueSq",e[e.InAttributeValueNq=14]="InAttributeValueNq",e[e.BeforeDeclaration=15]="BeforeDeclaration",e[e.InDeclaration=16]="InDeclaration",e[e.InProcessingInstruction=17]="InProcessingInstruction",e[e.BeforeComment=18]="BeforeComment",e[e.CDATASequence=19]="CDATASequence",e[e.DeclarationSequence=20]="DeclarationSequence",e[e.InSpecialComment=21]="InSpecialComment",e[e.InCommentLike=22]="InCommentLike",e[e.SpecialStartSequence=23]="SpecialStartSequence",e[e.InSpecialTag=24]="InSpecialTag",e[e.InPlainText=25]="InPlainText",e[e.InEntity=26]="InEntity"})(He||(He={}));(function(e){e[e.NoValue=0]="NoValue",e[e.Unquoted=1]="Unquoted",e[e.Single=2]="Single",e[e.Double=3]="Double"})(ap||(ap={}));Xi={Empty:new Uint8Array(0),Cdata:new Uint8Array([67,68,65,84,65,91]),CdataEnd:new Uint8Array([93,93,62]),CommentEnd:new Uint8Array([45,45,33,62]),Doctype:new Uint8Array([100,111,99,116,121,112,101]),IframeEnd:new Uint8Array([60,47,105,102,114,97,109,101]),NoembedEnd:new Uint8Array([60,47,110,111,101,109,98,101,100]),NoframesEnd:new Uint8Array([60,47,110,111,102,114,97,109,101,115]),Plaintext:new Uint8Array([60,47,112,108,97,105,110,116,101,120,116]),ScriptEnd:new Uint8Array([60,47,115,99,114,105,112,116]),StyleEnd:new Uint8Array([60,47,115,116,121,108,101]),TitleEnd:new Uint8Array([60,47,116,105,116,108,101]),TextareaEnd:new Uint8Array([60,47,116,101,120,116,97,114,101,97]),XmpEnd:new Uint8Array([60,47,120,109,112])},UCi=new Map([[Xi.IframeEnd[2],Xi.IframeEnd],[Xi.NoembedEnd[2],Xi.NoembedEnd],[Xi.Plaintext[2],Xi.Plaintext],[Xi.ScriptEnd[2],Xi.ScriptEnd],[Xi.TitleEnd[2],Xi.TitleEnd],[Xi.XmpEnd[2],Xi.XmpEnd]])});class H2{options;startIndex=0;endIndex=0;openTagStart=0;tagname="";attribname="";attribvalue="";attribs=null;stack=[];foreignContext;cbs;lowerCaseTagNames;lowerCaseAttributeNames;recognizeSelfClosing;htmlMode;tokenizer;buffers=[];bufferOffset=0;writeIndex=0;ended=!1;constructor(e,t={}){this.options=t,this.cbs=e??{},this.htmlMode=!this.options.xmlMode,this.lowerCaseTagNames=t.lowerCaseTags??this.htmlMode,this.lowerCaseAttributeNames=t.lowerCaseAttributeNames??this.htmlMode,this.recognizeSelfClosing=t.recognizeSelfClosing??!this.htmlMode,this.tokenizer=new(t.Tokenizer??q2)(this.options,this),this.foreignContext=[Jg.None],this.cbs.onparserinit?.(this)}ontext(e,t){let i=this.getSlice(e,t);this.endIndex=t-1,this.cbs.ontext?.(i),this.startIndex=t}ontextentity(e,t){this.endIndex=t-1,this.cbs.ontext?.(qNe(e)),this.startIndex=t}isInForeignContext(){return this.foreignContext[0]!==Jg.None}isVoidElement(e){return this.htmlMode&&$Ci.has(e)}readTagName(e,t){let i=this.lowerCaseTagNames?this.getSlice(e,t).toLowerCase():this.getSlice(e,t);if(!(this.lowerCaseTagNames&&this.htmlMode))return i;if(this.foreignContext[0]===Jg.Svg)return VNe.get(i)??i;if(this.foreignContext.length>1){let r=VNe.get(i);if(r!==void 0&&this.stack.includes(r))return r}if(!this.isInForeignContext())return i==="image"?"img":i;return i}onopentagname(e,t){this.endIndex=t,this.emitOpenTag(this.readTagName(e,t))}emitOpenTag(e){if(this.openTagStart=this.startIndex,this.tagname=e,this.htmlMode&&e==="form"&&this.stack.includes("form")){this.tagname="";return}let t=this.htmlMode&&qCi.get(e);if(t)while(this.stack.length>0&&t.has(this.stack[0]))this.popElement(!0);if(!this.isVoidElement(e)){if(this.stack.unshift(e),this.htmlMode){if(e==="svg")this.foreignContext.unshift(Jg.Svg);else if(e==="math")this.foreignContext.unshift(Jg.MathML);else if(ZNe.has(e))this.foreignContext.unshift(Jg.None)}}if(this.cbs.onopentagname?.(e),this.cbs.onopentag)this.attribs={}}endOpenTag(e){if(this.startIndex=this.openTagStart,this.attribs)this.cbs.onopentag?.(this.tagname,this.attribs,e),this.attribs=null;if(this.cbs.onclosetag&&this.isVoidElement(this.tagname))this.cbs.onclosetag(this.tagname,!0);this.tagname=""}onopentagend(e){this.endIndex=e,this.endOpenTag(!1),this.startIndex=e+1}onclosetag(e,t){this.endIndex=t;let i=this.readTagName(e,t);if(!this.isVoidElement(i)){let r=this.stack.indexOf(i);if(r!==-1){for(let n=0;n<r;n++)this.popElement(!0);this.popElement(!1)}else if(this.htmlMode&&i==="p")this.emitOpenTag("p"),this.closeCurrentTag(!0)}else if(this.htmlMode&&i==="br")this.cbs.onopentagname?.("br"),this.cbs.onopentag?.("br",{},!0),this.cbs.onclosetag?.("br",!1);this.startIndex=t+1}onselfclosingtag(e){if(this.endIndex=e,this.recognizeSelfClosing||this.isInForeignContext())this.closeCurrentTag(!1),this.startIndex=e+1;else this.onopentagend(e)}popElement(e){let t=this.stack.shift();if(this.htmlMode&&(GCi.has(t)||ZNe.has(t)))this.foreignContext.shift();this.cbs.onclosetag?.(t,e)}closeCurrentTag(e){let t=this.tagname;if(this.endOpenTag(e),this.stack[0]===t)this.popElement(!e)}onattribname(e,t){this.startIndex=e;let i=this.getSlice(e,t);this.attribname=this.lowerCaseAttributeNames?i.toLowerCase():i}onattribdata(e,t){this.attribvalue+=this.getSlice(e,t)}onattribentity(e){this.attribvalue+=qNe(e)}onattribend(e,t){if(this.endIndex=t,this.cbs.onattribute?.(this.attribname,this.attribvalue,e===ap.Double?'"':e===ap.Single?"'":e===ap.NoValue?void 0:null),this.attribs&&!Object.hasOwn(this.attribs,this.attribname))this.attribs[this.attribname]=this.attribvalue;this.attribvalue=""}getInstructionName(e){let t=e.search(HCi),i=t<0?e:e.substr(0,t);if(this.lowerCaseTagNames)i=i.toLowerCase();return i}ondeclaration(e,t){this.endIndex=t;let i=this.getSlice(e,t);if(this.cbs.onprocessinginstruction){let r=this.htmlMode?this.lowerCaseTagNames?WNe:i.slice(0,WNe.length):this.getInstructionName(i);this.cbs.onprocessinginstruction(`!${r}`,`!${i}`)}this.startIndex=t+1}onprocessinginstruction(e,t){this.endIndex=t;let i=this.getSlice(e,t);if(this.cbs.onprocessinginstruction){let r=this.getInstructionName(i);this.cbs.onprocessinginstruction(`?${r}`,`?${i}`)}this.startIndex=t+1}oncomment(e,t,i){this.endIndex=t,this.cbs.oncomment?.(this.getSlice(e,t-i)),this.cbs.oncommentend?.(),this.startIndex=t+1}oncdata(e,t,i){this.endIndex=t;let r=this.getSlice(e,t-i);if(!this.htmlMode||this.options.recognizeCDATA)this.cbs.oncdatastart?.(),this.cbs.ontext?.(r),this.cbs.oncdataend?.();else if(this.isInForeignContext())this.cbs.ontext?.(r);else this.cbs.oncomment?.(`[CDATA[${r}]]`),this.cbs.oncommentend?.();this.startIndex=t+1}onend(){if(this.cbs.onclosetag){this.endIndex=this.startIndex;for(let e=0;e<this.stack.length;e++)this.cbs.onclosetag(this.stack[e],!0)}this.cbs.onend?.()}reset(){this.cbs.onreset?.(),this.tokenizer.reset(),this.tagname="",this.attribname="",this.attribvalue="",this.attribs=null,this.stack.length=0,this.startIndex=0,this.endIndex=0,this.cbs.onparserinit?.(this),this.buffers.length=0,this.foreignContext.length=0,this.foreignContext.unshift(Jg.None),this.bufferOffset=0,this.writeIndex=0,this.ended=!1}parseComplete(e){this.reset(),this.end(e)}getSlice(e,t){if(e===t)return"";while(e-this.bufferOffset>=this.buffers[0].length)this.shiftBuffer();let i=this.buffers[0].slice(e-this.bufferOffset,t-this.bufferOffset);while(t-this.bufferOffset>this.buffers[0].length)this.shiftBuffer(),i+=this.buffers[0].slice(0,t-this.bufferOffset);return i}shiftBuffer(){this.bufferOffset+=this.buffers[0].length,this.writeIndex--,this.buffers.shift()}write(e){if(this.ended){this.cbs.onerror?.(Error(".write() after done!"));return}if(this.buffers.push(e),this.tokenizer.running)this.tokenizer.write(e),this.writeIndex++}end(e){if(this.ended){this.cbs.onerror?.(Error(".end() after done!"));return}if(e)this.write(e);this.ended=!0,this.tokenizer.end()}pause(){this.tokenizer.pause()}resume(){this.tokenizer.resume();while(this.tokenizer.running&&this.writeIndex<this.buffers.length)this.tokenizer.write(this.buffers[this.writeIndex++]);if(this.ended)this.tokenizer.end()}}var qNe,$2,As,G2,$Ne,GNe,HNe,qCi,WNe="doctype",$Ci,GCi,ZNe,VNe,Jg,HCi;var zce=Ho(()=>{Lce();({fromCodePoint:qNe}=String),$2=new Set(["input","option","optgroup","select","button","datalist","textarea"]),As=new Set(["p"]),G2=new Set(["h1","h2","h3","h4","h5","h6","p"]),$Ne=new Set(["thead","tbody"]),GNe=new Set(["dd","dt"]),HNe=new Set(["rt","rp"]),qCi=new Map([["tr",new Set(["tr","th","td"])],["th",new Set(["th"])],["td",new Set(["thead","th","td"])],["body",new Set(["head","link","script"])],["a",new Set(["a"])],["li",new Set(["li"])],["p",As],["h1",G2],["h2",G2],["h3",G2],["h4",G2],["h5",G2],["h6",G2],["select",$2],["input",$2],["output",$2],["button",$2],["datalist",$2],["textarea",$2],["option",new Set(["option"])],["optgroup",new Set(["optgroup","option"])],["dd",GNe],["dt",GNe],["address",As],["article",As],["aside",As],["blockquote",As],["details",As],["div",As],["dl",As],["fieldset",As],["figcaption",As],["figure",As],["footer",As],["form",As],["header",As],["hr",As],["main",As],["nav",As],["ol",As],["pre",As],["section",As],["table",As],["ul",As],["rt",HNe],["rp",HNe],["tbody",$Ne],["tfoot",$Ne]]),$Ci=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]),GCi=new Set(["math","svg"]),ZNe=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignObject","desc","title"]),VNe=new Map([["altglyph","altGlyph"],["altglyphdef","altGlyphDef"],["altglyphitem","altGlyphItem"],["animatecolor","animateColor"],["animatemotion","animateMotion"],["animatetransform","animateTransform"],["clippath","clipPath"],["feblend","feBlend"],["fecolormatrix","feColorMatrix"],["fecomponenttransfer","feComponentTransfer"],["fecomposite","feComposite"],["feconvolvematrix","feConvolveMatrix"],["fediffuselighting","feDiffuseLighting"],["fedisplacementmap","feDisplacementMap"],["fedistantlight","feDistantLight"],["fedropshadow","feDropShadow"],["feflood","feFlood"],["fefunca","feFuncA"],["fefuncb","feFuncB"],["fefuncg","feFuncG"],["fefuncr","feFuncR"],["fegaussianblur","feGaussianBlur"],["feimage","feImage"],["femerge","feMerge"],["femergenode","feMergeNode"],["femorphology","feMorphology"],["feoffset","feOffset"],["fepointlight","fePointLight"],["fespecularlighting","feSpecularLighting"],["fespotlight","feSpotLight"],["fetile","feTile"],["feturbulence","feTurbulence"],["foreignobject","foreignObject"],["glyphref","glyphRef"],["lineargradient","linearGradient"],["radialgradient","radialGradient"],["textpath","textPath"]]);(function(e){e[e.None=0]="None",e[e.Svg=1]="Svg",e[e.MathML=2]="MathML"})(Jg||(Jg={}));HCi=/\s|\//});var Yj={};Qg(Yj,{CDATA:()=>Vce,Comment:()=>Gce,Directive:()=>$ce,Doctype:()=>WCi,ElementType:()=>en,Root:()=>Uce,Script:()=>Hce,Style:()=>Wce,Tag:()=>Zce,Text:()=>qce,isTag:()=>jce});function jce(e){return e.type===en.Tag||e.type===en.Script||e.type===en.Style}var en,Uce,qce,$ce,Gce,Hce,Wce,Zce,Vce,WCi;var W2=Ho(()=>{(function(e){e.Root="root",e.Text="text",e.Directive="directive",e.Comment="comment",e.Script="script",e.Style="style",e.Tag="tag",e.CDATA="cdata",e.Doctype="doctype"})(en||(en={}));Uce=en.Root,qce=en.Text,$ce=en.Directive,Gce=en.Comment,Hce=en.Script,Wce=en.Style,Zce=en.Tag,Vce=en.CDATA,WCi=en.Doctype});class Yce{parent=null;prev=null;next=null;startIndex=null;endIndex=null;get parentNode(){return this.parent}set parentNode(e){this.parent=e}get previousSibling(){return this.prev}set previousSibling(e){this.prev=e}get nextSibling(){return this.next}set nextSibling(e){this.next=e}cloneNode(e=!1){return KNe(this,e)}}function El(e){return jce(e)}function rU(e){return e.type===en.CDATA}function rA(e){return e.type===en.Text}function Jce(e){return e.type===en.Comment}function ZCi(e){return e.type===en.Directive}function VCi(e){return e.type===en.Root}function sd(e){return Object.hasOwn(e,"children")}function KNe(e,t=!1){let i;if(rA(e))i=new KI(e.data);else if(Jce(e))i=new Qj(e.data);else if(El(e)){let r=t?Kce(e.children):[],n=new iU(e.name,{...e.attribs},r);for(let o of r)o.parent=n;if(e.namespace!=null)n.namespace=e.namespace;if(e["x-attribsNamespace"])n["x-attribsNamespace"]={...e["x-attribsNamespace"]};if(e["x-attribsPrefix"])n["x-attribsPrefix"]={...e["x-attribsPrefix"]};i=n}else if(rU(e)){let r=t?Kce(e.children):[],n=new tU(r);for(let o of r)o.parent=n;i=n}else if(VCi(e)){let r=t?Kce(e.children):[],n=new YI(r);for(let o of r)o.parent=n;if(e["x-mode"])n["x-mode"]=e["x-mode"];i=n}else if(ZCi(e)){let r=new Xj(e.name,e.data);if(e["x-name"]!=null)r["x-name"]=e["x-name"],r["x-publicId"]=e["x-publicId"],r["x-systemId"]=e["x-systemId"];i=r}else throw Error(`Not implemented yet: ${e.type}`);if(i.startIndex=e.startIndex,i.endIndex=e.endIndex,e.sourceCodeLocation!=null)i.sourceCodeLocation=e.sourceCodeLocation;return i}function Kce(e){let t=e.map((i)=>KNe(i,!0));for(let i=1;i<t.length;i++)t[i].prev=t[i-1],t[i-1].next=t[i];return t}var Jj,KI,Qj,Xj,eU,tU,YI,iU;var Qce=Ho(()=>{W2();Jj=class Jj extends Yce{data;constructor(e){super();this.data=e}get nodeValue(){return this.data}set nodeValue(e){this.data=e}};KI=class KI extends Jj{type=en.Text;get nodeType(){return 3}};Qj=class Qj extends Jj{type=en.Comment;get nodeType(){return 8}};Xj=class Xj extends Jj{type=en.Directive;name;constructor(e,t){super(t);this.name=e}get nodeType(){return 1}"x-name";"x-publicId";"x-systemId"};eU=class eU extends Yce{children;constructor(e){super();this.children=e}get firstChild(){return this.children[0]??null}get lastChild(){return this.children.length>0?this.children[this.children.length-1]:null}get childNodes(){return this.children}set childNodes(e){this.children=e}};tU=class tU extends eU{type=en.CDATA;get nodeType(){return 4}};YI=class YI extends eU{type=en.Root;get nodeType(){return 9}};iU=class iU extends eU{name;attribs;type;constructor(e,t,i=[],r=e==="script"?en.Script:e==="style"?en.Style:en.Tag){super(i);this.name=e,this.attribs=t,this.type=r}get nodeType(){return 1}get tagName(){return this.name}set tagName(e){this.name=e}get attributes(){return Object.keys(this.attribs).map((e)=>({name:e,value:this.attribs[e],namespace:this["x-attribsNamespace"]?.[e],prefix:this["x-attribsPrefix"]?.[e]}))}namespace;"x-attribsNamespace";"x-attribsPrefix"}});class Lw{dom=[];root=new YI(this.dom);callback;options;elementCB;done=!1;tagStack=[this.root];lastNode=null;parser=null;constructor(e,t,i){if(typeof t==="function")i=t,t=YNe;if(typeof e==="object")t=e,e=void 0;this.callback=e??null,this.options=t??YNe,this.elementCB=i??null}onparserinit(e){this.parser=e}onreset(){this.dom=[],this.root=new YI(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null}onend(){if(this.done)return;this.done=!0,this.parser=null,this.handleCallback(null)}onerror(e){this.handleCallback(e)}onclosetag(){this.lastNode=null;let e=this.tagStack.pop();if(this.options.withEndIndices&&this.parser)e.endIndex=this.parser.endIndex;if(this.elementCB)this.elementCB(e)}onopentag(e,t){let i=this.options.xmlMode?en.Tag:void 0,r=new iU(e,t,void 0,i);this.addNode(r),this.tagStack.push(r)}ontext(e){let{lastNode:t}=this;if(t&&t.type===en.Text){if(t.data+=e,this.options.withEndIndices&&this.parser)t.endIndex=this.parser.endIndex}else{let i=new KI(e);this.addNode(i),this.lastNode=i}}oncomment(e){if(this.lastNode&&this.lastNode.type===en.Comment){this.lastNode.data+=e;return}let t=new Qj(e);this.addNode(t),this.lastNode=t}oncommentend(){this.lastNode=null}oncdatastart(){let e=new KI(""),t=new tU([e]);this.addNode(t),e.parent=t,this.lastNode=e}oncdataend(){this.lastNode=null}onprocessinginstruction(e,t){let i=new Xj(e,t);this.addNode(i)}handleCallback(e){if(typeof this.callback==="function")this.callback(e,this.dom);else if(e)throw e}addNode(e){let t=this.tagStack[this.tagStack.length-1],i=t.children[t.children.length-1];if(this.options.withStartIndices&&this.parser)e.startIndex=this.parser.startIndex;if(this.options.withEndIndices&&this.parser)e.endIndex=this.parser.endIndex;if(t.children.push(e),i)e.prev=i,i.next=e;e.parent=t,this.lastNode=null}}var YNe;var nA=Ho(()=>{W2();Qce();Qce();YNe={withStartIndices:!1,withEndIndices:!1,xmlMode:!1}});function Z2(e,t,i=!0,r=Number.POSITIVE_INFINITY){return JNe(e,Array.isArray(t)?t:[t],i,r)}function JNe(e,t,i,r){let n=[],o=[Array.isArray(t)?t:[t]],s=[0];for(;;){if(s[0]>=o[0].length){if(s.length===1)return n;o.shift(),s.shift();continue}let a=o[0][s[0]++];if(e(a)){if(n.push(a),--r<=0)return n}if(i&&sd(a)&&a.children.length>0)s.unshift(0),o.unshift(a.children)}}function nU(e,t,i=!0){let r=Array.isArray(t)?t:[t];for(let n of r){if(El(n)&&e(n))return n;if(i&&sd(n)&&n.children.length>0){let o=nU(e,n.children,!0);if(o)return o}}return null}function QNe(e,t){return(Array.isArray(t)?t:[t]).some((i)=>El(i)&&e(i)||sd(i)&&QNe(e,i.children))}function KCi(e,t){let i=[],r=[Array.isArray(t)?t:[t]],n=[0];for(;;){if(n[0]>=r[0].length){if(r.length===1)return i;r.shift(),n.shift();continue}let o=r[0][n[0]++];if(El(o)&&e(o))i.push(o);if(sd(o)&&o.children.length>0)n.unshift(0),r.unshift(o.children)}}var Xce=Ho(()=>{nA()});function ele(e,t){if(typeof t==="function")return(i)=>El(i)&&t(i.attribs[e]);return(i)=>El(i)&&i.attribs[e]===t}function YCi(e,t){return(i)=>e(i)||t(i)}function XNe(e){let t=Object.keys(e).map((i)=>{let r=e[i];return Object.hasOwn(oU,i)?oU[i](r):ele(i,r)});return t.length===0?null:t.reduce(YCi)}function JCi(e,t){let i=XNe(e);return i?i(t):!0}function QCi(e,t,i,r=Number.POSITIVE_INFINITY){let n=XNe(e);return n?Z2(n,t,i,r):[]}function XCi(e,t,i=!0){if(!Array.isArray(t))t=[t];return nU(ele("id",e),t,i)}function zw(e,t,i=!0,r=Number.POSITIVE_INFINITY){return Z2(oU.tag_name(e),t,i,r)}function eDi(e,t,i=!0,r=Number.POSITIVE_INFINITY){return Z2(ele("class",e),t,i,r)}function tDi(e,t,i=!0,r=Number.POSITIVE_INFINITY){return Z2(oU.tag_type(e),t,i,r)}var oU;var tle=Ho(()=>{nA();Xce();oU={tag_name(e){if(typeof e==="function")return(t)=>El(t)&&e(t.name);if(e==="*")return El;return(t)=>El(t)&&t.name===e},tag_type(e){if(typeof e==="function")return(t)=>e(t.type);return(t)=>t.type===e},tag_contains(e){if(typeof e==="function")return(t)=>rA(t)&&e(t.data);return(t)=>rA(t)&&t.data===e}}});function tLe(e){return e===34?"&quot;":e===38?"&amp;":e===39?"&apos;":e===60?"&lt;":e===62?"&gt;":"&nbsp;"}function eLe(e){return e>=128||e>=32&&e<64&&(iDi>>>e&1)===1}function sU(e){let{length:t}=e,i,r=0,n=0;while(n<t){let o=e.charCodeAt(n);if(!eLe(o)){let a=Math.min(n+32,t),c=n+1;while(c<a&&!eLe(e.charCodeAt(c)))c++;if(c<a){n=c;continue}if(c>=t)break;if(ile.lastIndex=c,!ile.test(e))break;n=ile.lastIndex-1;continue}if(i===void 0)i=e.substring(0,n);else if(r!==n)i+=e.substring(r,n);if(o<64){i+=tLe(o),r=n+=1;continue}let s=e.codePointAt(n);if(i+=`&#x${s.toString(16)};`,s!==o)n++;r=n+=1}if(i===void 0)return e;if(r<t)i+=e.substr(r);return i}function iLe(e,t){if(e.lastIndex=0,!e.test(t))return t;let i="",r=0;do{let n=e.lastIndex-1;if(r!==n)i+=t.substring(r,n);let o=t.charCodeAt(n);i+=tLe(o),r=n+1}while(e.test(t));return i+t.substring(r)}function rle(e){return iLe(rDi,e)}function nle(e){return iLe(nDi,e)}var iDi=1342177476,ile,rDi,nDi;var rLe=Ho(()=>{ile=/["&'<>\u0080-\uFFFF]/g;rDi=/["&\u{A0}]/gu;nDi=/[&<>\u{A0}]/gu});var nLe,oLe;var sLe=Ho(()=>{rLe();(function(e){e[e.XML=0]="XML",e[e.HTML=1]="HTML"})(nLe||(nLe={}));(function(e){e[e.UTF8=0]="UTF8",e[e.ASCII=1]="ASCII",e[e.Extensive=2]="Extensive",e[e.Attribute=3]="Attribute",e[e.Text=4]="Text"})(oLe||(oLe={}))});var aLe,cLe;var lLe=Ho(()=>{aLe=new Map("altGlyph altGlyphDef altGlyphItem animateColor animateMotion animateTransform clipPath feBlend feColorMatrix feComponentTransfer feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feDropShadow feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feImage feMerge feMergeNode feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile feTurbulence foreignObject glyphRef linearGradient radialGradient textPath".split(" ").map((e)=>[e.toLowerCase(),e])),cLe=new Map("definitionURL attributeName attributeType baseFrequency baseProfile calcMode clipPathUnits diffuseConstant edgeMode filterUnits glyphRef gradientTransform gradientUnits kernelMatrix kernelUnitLength keyPoints keySplines keyTimes lengthAdjust limitingConeAngle markerHeight markerUnits markerWidth maskContentUnits maskUnits numOctaves pathLength patternContentUnits patternTransform patternUnits pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits refX refY repeatCount repeatDur requiredExtensions requiredFeatures specularConstant specularExponent spreadMethod startOffset stdDeviation stitchTiles surfaceScale systemLanguage tableValues targetX targetY textLength viewBox viewTarget xChannelSelector yChannelSelector zoomAndPan".split(" ").map((e)=>[e.toLowerCase(),e]))});function lDi(e,t={}){let i="length"in e?e:[e],r=t.xmlMode??!1,n="";for(let o=0;o<i.length;o++)n+=dLe(i[o],t,r);return n}function uLe(e,t,i){let r="";for(let n=0;n<e.length;n++)r+=dLe(e[n],t,i);return r}function dLe(e,t,i){switch(e.type){case Uce:return uLe(e.children,t,i);case $ce:return`<${e.data}>`;case Gce:return`<!--${e.data}-->`;case Vce:return`<![CDATA[${e.children[0].data}]]>`;case Hce:case Wce:case Zce:return uDi(e,t,i);case qce:{let r=e,n=r.data||"";if((t.encodeEntities??t.decodeEntities)!==!1&&!(!i&&r.parent&&oDi.has(r.parent.name)))return i||t.encodeEntities!=="utf8"?sU(n):nle(n);return n}}}function uDi(e,t,i){if(i==="foreign"){if(e.name=aLe.get(e.name)??e.name,e.parent&&cDi.has(e.parent.name))i=!1}if(!i&&aDi.has(e.name))i="foreign";let{name:r,children:n}=e,o=!i&&sDi.has(r),s=`<${r}${pDi(e.attribs,t,i)}`;if(n.length===0&&(i?t.selfClosingTags!==!1:t.selfClosingTags&&o))s+=i?"/>":" />";else{if(s+=">",n.length>0)s+=uLe(n,t,i);if(!o)s+=`</${r}>`}return s}function dDi(e){return e.replaceAll('"',"&quot;")}function pDi(e,t,i){if(!e)return"";let r=(t.encodeEntities??t.decodeEntities)===!1?dDi:i||t.encodeEntities!=="utf8"?sU:rle,n=i==="foreign",o=!!(t.emptyAttrs??i),s="";for(let a in e){if(!Object.hasOwn(e,a))continue;let c=e[a],u=n?cLe.get(a)??a:a;s+=!o&&(c==null||c==="")?` ${u}`:` ${u}="${r(c==null?"":String(c))}"`}return s}var oDi,sDi,aDi,cDi,pLe;var mLe=Ho(()=>{W2();sLe();lLe();oDi=new Set("style script xmp iframe noembed noframes plaintext noscript".split(" ")),sDi=new Set("area base basefont br col command embed frame hr img input isindex keygen link meta param source track wbr".split(" ")),aDi=new Set(["svg","math"]),cDi=new Set("mi mo mn ms mtext annotation-xml foreignObject desc title".split(" "));pLe=lDi});function hLe(e,t){return pLe(e,t)}function mDi(e,t){return sd(e)?e.children.map((i)=>hLe(i,t)).join(""):""}function aU(e){if(Array.isArray(e))return e.map(aU).join("");if(El(e))return e.name==="br"?`
2
+ import"./chunks/index-24kr1bk2.js";import{C as G3,D as $ni,F as pni,H as $ke}from"./chunks/index-me2q3y9y.js";import{J as Ine,K as hD}from"./chunks/index-8cpdhssj.js";import{L as Zle}from"./chunks/index-9deh2vm3.js";import"./chunks/index-77mhdfp8.js";import"./chunks/index-66v76w4h.js";import"./chunks/index-624fhq2j.js";import"./chunks/index-z0k97qgd.js";import"./chunks/index-x8e40qwv.js";import{Q as uw}from"./chunks/index-xtt5r7ac.js";import{$ as wq,Ha as fj,S as dMe,T as gj,V as Oa,W as Xw,X as Ude,Y as Hde,Z as yy,_ as vq,aa as Sq,ba as v$e,ca as kq,da as y9,ea as aHe,fa as jd,ga as JQt,ha as rki,ka as rOe,la as tv,ma as ZO,na as dst,oa as RX,pa as FAi,qa as FX,ra as zx,sa as MX,ta as OAi,ua as ug,va as iD,wa as BPe,xa as CPe,ya as z8i,za as vri}from"./chunks/index-36wtttkh.js";import"./chunks/index-5c9ar9m2.js";import{$a as t$,$b as xn,$c as Hat,$d as kQ,$e as B2i,$g as B9,$i as Pge,Ac as RJ,Ad as Wn,Af as Kse,Ah as hae,Ai as Mge,Aj as Iw,Bc as FJ,Bd as rm,Bf as Yse,Bh as xi,Bi as gat,Cc as MJ,Cd as JJ,Cf as Jse,Cg as g2i,Ch as Sf,Ci as yat,Db as m5i,Dc as OJ,Dd as CJt,Df as AI,Dh as IJ,Di as c5,Ec as kJt,Ed as _1i,Ef as Qse,Eh as _J,Fb as h5i,Fc as BJt,Fd as F3,Fe as u5i,Ff as Xse,Fh as _c,Fi as qde,Fj as RMe,Gb as sBe,Gc as B6e,Gd as Uh,Gf as eae,Gh as Co,Gj as gae,Hc as VM,Hd as Zst,Hf as tae,Hg as Cm,Hh as avi,Hi as l0,Hj as qE,Id as XE,If as iae,Ih as Xo,Ij as wf,Jc as Kn,Jd as jp,Jf as rae,Jg as sp,Jh as Toe,Jj as yae,Kc as Yat,Kd as ct,Kf as nae,Kg as rce,Kh as Poe,Kj as II,Lc as Ie,Ld as Ll,Lg as nce,Lj as cvi,Ma as Jae,Mc as Ah,Md as _Fe,Me as TE,Mg as oce,Na as Qae,Nb as Uu,Nc as Sn,Nd as ice,Ne as q2i,Ng as sce,Nh as $2i,Ni as fae,Oa as Pt,Ob as yI,Oc as UW,Oe as y9i,Og as ace,Pa as Ci,Pb as Xr,Pc as Vat,Pd as xj,Pe as MFe,Pf as ev,Pg as Pw,Qb as qg,Qc as l5,Qe as K9i,Qf as RXt,Qg as cce,Qi as RW,Qj as HE,Ra as he,Rb as Tm,Rc as IB,Rd as AXt,Re as Y9i,Rf as DQ,Rg as Ln,Rj as vy,Sa as EA,Sb as Mi,Sc as jW,Sd as yQ,Se as FO,Sg as _a,Sj as kf,Ta as bt,Tb as lu,Tc as Mat,Td as FJt,Te as Am,Tf as vI,Tg as lce,Tj as u0,Ua as e$,Ub as Ja,Uc as d5,Ud as g3,Ue as J6,Uf as $E,Ug as Qi,Uj as uQt,Va as jc,Vb as d0,Vc,Vd as SPe,Ve as n9i,Vf as QE,Vg as uce,Vh as tC,Vi as dat,Vj as rc,Wa as DWe,Wb as Zse,Wc as gv,Wd as hMe,We as o9i,Wf as If,Wg as dce,Wh as d4e,Wi as pat,Xa as f_,Xc as nR,Xd as b5i,Xe as woe,Xf as Nj,Xg as Pm,Xh as u4e,Xi as m9i,Ya as x_,Yc as xv,Yd as wW,Ye as J9i,Yg as ii,Yh as Wsi,Yi as h9i,Za as gi,Zb as VXt,Zc as vh,Zd as SQ,Ze as Q9i,Zf as Tw,Zg as Nn,Zh as iC,Zi as mat,_a as _9,_b as fn,_c as uye,_d as Ene,_e as k2i,_g as Go,_h as Ovi,_i as hat,ab as n_,ac as xst,ad as Gat,ae as Cre,af as C2i,ah as BI,aj as rat,bd as KY,be as pst,bf as D2i,bg as oae,bh as boi,bj as aat,cb as e_,cd as Jat,ce as ow,cf as I2i,cg as GE,ch as Es,cj as QP,db as Kde,dc as TI,dd as kat,de as v3,df as X9i,dg as jg,dh as zt,dj as fat,eb as i$,ec as PI,ed as Bat,ee as w3,ef as Z2i,eg as Sw,ej as tR,fb as is,fc as Bj,fe as Vxe,ff as V2i,fg as wI,fi as Kre,fj as xoe,gb as ai,gc as Xae,gd as zW,ge as gni,gf as Q2i,gg as sae,gj as xat,hb as et,hc as $g,hd as Qat,he as k0,hf as s9i,hg as Cj,hh as un,hj as wat,ib as Po,ic as RI,id as fye,ie as mI,if as a9i,ig as SI,ih as PQe,ij as M2i,jb as Ns,jc as FI,je as vPe,jf as c9i,jg as aae,jh as Qvi,jj as R2i,kb as Ym,kc as MI,kd as Avi,ke as tz,kf as voe,kg as cae,kh as NL,kj as nat,lb as Zde,lc as OI,le as Q9e,lf as iki,lg as T2,lh as Yvi,li as YP,lj as BJ,mc as NI,md as Ia,mf as t9i,mg as lae,mh as pae,mi as iat,mj as WM,nb as wHe,nc as ece,nd as B3,ne as gA,nf as x2i,nh as qi,ni as PW,nj as rJt,ob as SHe,oc as R2,oe as fMe,og as uae,oh as x1i,oi as fJt,oj as Rm,pc as ZE,pe as LQe,ph as U6i,pi as xJt,pj as Rw,qc as f0,qd as Lg,qe as zQe,qg as Ms,qi as cat,qj as Hg,rb as kHe,rc as Gg,rd as tce,rf as PE,ri as XP,rj as Wg,sc as JE,sf as ww,si as eR,sj as Zg,tb as BHe,tc as XA,td as ic,tf as Vse,tg as kw,th as Ug,ti as NW,tj as Bw,uc as EAi,ud as jt,uf as Bf,uh as Gt,ui as lat,uj as xae,vc as VWe,vd as TQ,vh as Cf,vi as F2i,vj as Cw,wc as qpe,wd as M2,wh as Tc,wi as d2i,wj as Dj,xc as DB,xd as Mm,xg as kI,xh as uu,xi as p2i,yc as _ee,yd as Ta,yg as dae,yh as DI,yi as iR,zd as dx,ze as zg,zf as EI,zh as mae,zi as Fge,zj as Dw}from"./chunks/index-j40q3yws.js";import{$j as Fb,$k as _9i,$l as EB,$m as t1i,Ak as Goi,Al as LHe,Am as rne,Bk as Hoi,Bl as _Qe,Bm as XTe,Bn as kse,Ck as Q6i,Cl as dn,Cm as zL,Dk as hoe,Dl as Qm,Dm as jL,Ek as X6i,El as J1,Em as lz,Fk as Koi,Fl as Yie,Fm as VSi,Gk as e2i,Gl as nAi,Gm as uz,Hk as OBe,Hl as Jie,Hm as nQ,Ik as NBe,Il as jn,Im as jQt,Jk as lN,Jl as fu,Jm as qQt,Kk as LBe,Kl as sr,Km as VQt,Lk as Yoi,Ll as Yde,Lm as $Qt,Mk as zBe,Ml as Yq,Mm as GQt,Nk as Joi,Nn as nd,Ok as Qoi,Ol as hv,Om as Ore,On as np,Pk as hee,Pl as Ee,Pm as Hvi,Pn as op,Qk as fee,Qm as Wvi,Rk as Xoi,Rl as _s,Rm as Xk,Sk as xee,Sm as Xne,Sn as CI,Tk as Oh,Tm as eoe,Uk as W$e,Um as Mre,Vk as Lh,Vl as Ni,Vm as tD,Wj as rsi,Wk as Rx,Wl as Iq,Wm as xTe,Xj as rSi,Xk as gl,Xl as L9i,Xm as yTe,Yk as boe,Yl as _2,Ym as v1i,Zl as HJ,Zm as e1i,_j as Ba,_k as I9i,_l as AW,_m as w1i,ak as Sr,an as o1i,bk as kr,bn as QJ,ck as p3,cl as PD,cm as HQ,cn as eB,dk as Nne,dm as zei,dn as XG,ek as One,em as uJt,en as eH,fk as z6,fm as DJ,fn as LJ,gk as SL,gl as gI,gm as CJ,gn as TQe,hk as Un,hl as K1i,hm as ZGe,ik as j6,in as Xti,jk as w_e,jn as Gxe,kl as V9i,lk as UBe,lm as fvi,ln as Jb,mk as Zb,ml as nwi,mm as bA,mn as NAi,nk as lee,nl as Hse,nm as rO,nn as P6,ok as uee,ol as wj,on as SS,pk as J6i,pl as Sj,pn as Ase,qk as uX,ql as kj,qm as GJ,qn as Ic,rk as cN,rm as WJ,rn as qd,sk as gee,sl as ine,sm as gr,sn as x0,tk as yee,tl as wti,tm as p5i,tn as du,uk as bee,ul as jQ,um as Mq,un as nt,vk as U7,vl as X1i,vm as ym,wk as mee,wl as ewi,xk as QS,xl as QG,xm as Sne,xn as bI,yk as pee,ym as See,yn as Dm,zk as T1,zl as NHe,zm as VL,zn as vse}from"./chunks/index-pe6t04tc.js";import"./chunks/index-7qxdq0pn.js";import{Av as Je,Bs as bs,Hv as Sat,Kp as pge,Ov as a0,Pv as L9,Rv as Ya,Tv as Ud,Uv as QXt,Vv as Nr,Wv as eki,_r as xl,as as z9,ms as Da,wt as LW}from"./chunks/index-3cwkjys1.js";import{mx as l}from"./chunks/index-pmtqnhch.js";import"./chunks/index-sekjw9v9.js";import{qx as Al,rx as tTi,sx as E,tx as Qg,ux as Ho,vx as ce}from"./chunks/index-rdf7wcrz.js";function PNe(e){return e===0||e>=55296&&e<=57343||e>1114111}function RNe(e){if(PNe(e))return 65533;if(e>=128&&e<=159)return MCi[e-128]||e;return e}function FNe(e){return PNe(e)?65533:e}var MCi;var MNe=Ho(()=>{MCi=[8364,0,8218,402,8222,8230,8224,8225,710,8240,352,8249,338,0,381,0,0,8216,8217,8220,8221,8226,8211,8212,732,8482,353,8250,339,0,382,376]});function ONe(e,t,i,r,n,o){let a=e.length,c=o*90,u=0,d=()=>{let L=Nm[e.charCodeAt(u++)];return L<o?L:L*91-c+Nm[e.charCodeAt(u++)]},p=i-r,m=i+n,h=new Int32Array(m);h.fill(-1,r,o),h.fill(-1,o+p,m);let f=new Int32Array(m),g=new Int32Array(m);function y(L,q){let K=0,ue=q,G=q+L;while(ue<G){let S=Nm[e.charCodeAt(u++)];if(S<89)K+=S,h[ue++]=K;else if(S===89){let P=Nm[e.charCodeAt(u++)]+2;while(P--)h[ue++]=++K}else{let P=Nm[e.charCodeAt(u++)];K+=89+(P<90?P*91+Nm[e.charCodeAt(u++)]:Nm[e.charCodeAt(u++)]*8281+Nm[e.charCodeAt(u++)]*91+Nm[e.charCodeAt(u++)]),h[ue++]=K}}}y(r,0),y(p,o);let b=new Int32Array(n*2),v=0,w=0;function D(L,q){for(let K=0;K<L;K++){let ue=q+K,G=d(),S=d();b[w*2]=G,b[w*2+1]=S,w+=1,f[ue]=v;let P=(h[G]<0?g[G]:1)+(h[S]<0?g[S]:1);g[ue]=P,v+=P}}D(n-o+r,o+p),D(o-r,r);let R=new Uint16Array(v),O=0;for(let L=0;L<w;L++)for(let q=0;q<2;q++){let K=b[L*2+q],ue=h[K];if(ue<0){let G=f[K],S=G+g[K];while(G<S)R[O++]=R[G++]}else R[O++]=ue}let k=new Uint16Array(t),j=0;while(u<a){let L=Nm[e.charCodeAt(u++)];if(L>=o)L=L*91-c+Nm[e.charCodeAt(u++)];let q=h[L];if(q<0){let K=f[L],ue=K+g[L];while(K<ue)k[j++]=R[K++]}else k[j++]=q}return k}var Nm;var NNe=Ho(()=>{Nm=(()=>{let e=new Uint8Array(127),t=0;for(let i=33;i<=126;i++)if(i!==34&&i!==36&&i!==92)e[i]=t++;return e})()});var Mce;var LNe=Ho(()=>{NNe();Mce=ONe("!}.&u%}'&}*'~!6*)%&,~!J~!J~%L~y<~!R,~~%Lu~~#GD~~#|)1#%}^%}2%+#.##%##%}&%##%'#%##&%#%#'%#&#%#&#'#%%#&#%##%#)%''%&%#%#'%#%%#%%}%%%#%#&(23#%%#&-%0%('1#(##%#'##+%'*.:1}#%#6-+(%'%%#%%%}#L'2351&('%}&/N'(0(/*-%(%%}#'+&T%7.2}#&%&#%#36/5##%&%%#&#%%#))2%%##%&&'0~!#*+&'%1~!%).'3q?&%'1~!.##%6(~!+%%%(Gw'rT~!E#<nA%#jZ~!H%(~!42##~!*31&~!G%U~#)5~#`3~!J~!Z~%]~%Y~%C~!q~!u~#kz~%#~!6'~!D~!U~!?~#T~!c%~!G#'~%7|~!G~!J~!G&~#pb~(Df}#%}*&}#%##%##%##&#-}&'#'&%#.++}%mI,#,@&(}*%}*'%&##&#%##%}&0}#.},U},%}+%}&%}#%##&}B%(}(%}+%)})%##%#&}&%##%&}<%}>%#%&}*%}(%}9%}/%})%}*%}*%}?&}&%}3%}&*#%})%#%#)}#&#-#+*%E%%'%'#%}#*V##&##I}#&&##%&%#&&Qf%%))w/0+&%#(#.%-''''++++7}>%4'',##1,#%#&%##&#'##&#*#9)%&%}#*}%,#+P(%A&%#'&##wSD',9E00#y#@}(+}&%&>~!#~!X}#*}(&&}(&}(,%}%&#+&}#&}I%#%}%)#(},'%#*}4%%#%}(''}#/##(##),%-##%%)#&}(.}&%#&}%%}*&#%},&&}&%}#%*'#%})%}D&}&%}-&}6&#&}-,%}#%})-(~+`~,=?~I9'9%~!,#%})%})%}@%}?%}(~!?~#<~#pP~#BG~#=1#%K+~#?#~%;)~#A~#mF1~#A'~'X%'~#lR~#N~'N~#r~#m#-~#i'?%#'%~#B%##%,%#~#_%#0%~#]732~,w~2+#:&#%&'0%&>%}#>##F+)#%&&#(+_}4&}-%}(&}@&}O7Fdf0@+/v4}&WU##&/0#&'('B#%}.%}'+#%}#%%&#&%#%##+#&#)#6#'#.},%}c%},%#%##%&#&%#&~#>'*-.%##%##%}#%%}%'~#)D1}#%*&~#_%%'(~#S2%'.}#~#=##*'*-%}&'%'##&&~'E%.#&~#M4}%%##&'%#~#O1##%&#'+~#<B%##%%'%+~#;#@%}#&%#&&%#(~#H1}'%'##&&~#?A}&'~#D#%32}'&&&&~#[}'(#%}'~#;C})&}%%#%~#=&%,3}%'(#%%~#^'#&&)#%'~#Y%-~#d-%'~#^%%&#&&&}#~#b~2t*&'~&(~&@~0%~e~3}%*''0})&}+~!9##-}#%-hD*)1fC#%/&/fB#40~!+#)*4~!+~!K'&:~!/*7~!.#~!H~!L':~%x&~!H#~!*~%1~!I#~!+A~#p'~!F~~#-#~,,(~.Z~!V~%;'B'mq-W~!N~%I%#&&#&}#%},%%}'%}+X#%}#&}(%}'%}<%}#%}%%'}'%}:~![)9@~%>~#UA%-%##&~!C%~!-.9:~!1~!-^2/:a~!y,D*J#-5)/4~%23,~#G~!L1~!0X3`~!2+~!!0-~&E~!W~!o,>Y&]~%cZx_&~#O*9#A#'#+I'%#)~!0B*-5A+-((F&*M#)(-7-5+'-3a5Vi~!Y~!?+[)%3),ERHm~!+:D,VG.+)?fB%%*(%)'(#&80%1'8`K8?`+'Z#&O&'H5#*9)A%%5&3))0%39+.*7#()&&*=4@**L)<'_&*+..;(#*+)./&0#3)%')-8(4ixD(&.}%,('aI:,)%,k2231T)I'#/-W7,/'Q#.'Y24+h')37</31&83##&0#),H(?'&?/1##%#&&#%''-%&&&#(&''&#.-'%#%%(,')*'&#&#'##%(%(#%('#&##%%%%('%#%#%%#%#&%##h>w+v<ayvyvcg.uuhKr}g/v|g>u9i[~>g5uI~=RvdwEg;v/g;uk!!TTSx]@RT!U!#!@VBRUU!'UTe-d0c`e&gSdicedFcrdTaqb.kYcAohdYd@a3e+d}dMdtd.aJ#bqcK`dle/e.e'dwdPdodddjbEb}ogd^ofdpduc6j?l%d{drdqc)d7bacOdQ%T#Y)X.sR[yH>6Vyv3[xwLu>vo'!*.[yBacahoj>6Rew3[xqdZa#!a&#^(X-[yG>6Vyu3[xvg3sEr|g.u/Ri9db0T#^(Xa)!-[y;>6Vylg4wKs{JwNZt3@3r=c4Z([xlg;wKt!cpq's@v7A'*a(a+!-a#[y<3Dt?3Dt'>6Vym3[xmg9rxsNJwLZt4~?r?db1T#`-!(Xa,!0[yS>6Vz%NuQs.g4wKtnJwNZtS@3r>c4Z([y%g;wKtrdga8!a(!#&T*Y-Xa#!a0<or[yc3Dtq>6Vz43[y3JwNZtf@3s!Ju}!%Dti:pm3c_%X#tjB5pkd6q!r]u?voC'*-a.a2!0a&a+[yI3DtI3Ds~3DtH>6Vyw3[xx;:s#~<5pKJwNZtE@3r~d`a)!a2T#a.(!+U.X1[yT3Dt`3Dtv>6Vz&3[y&g9rxwzcxstPu.<rAJwLZtT~?r@dZa%!a.&^*Za(/Reu[ya>6Vz23[y1g3sEr}wkg{NuQRg{ci(U#5@b`~,cg#U(2WnH5wugcRh7dX#T(Y,a'Ta!!a,[yZ<]mj>6Vz,3[y+Pv#5ReZKu+=,%!H}7ABwkaS?Rh:BcW(X#<]mrj:ubv/ARekdg%!(!a.*Ta(Y.X1!#sP>Rl*Dt6[y>>6Vyo3Wf*jOvuumvuRgRJuq*!:9<B@bX~3jVv&v@s@5Re[d/rQt{uAvo&a&a*)a2!,0Wf!3Dt0=Bs'>6Re}3[xy~<5s%JwJZt1~Gs)c;&!#2sJkNuXvzq7rxu,Re8dka4!a8(aEZ+a@Y.X1Xa)[yd=Bs(3DtP>6Vz53[y4cX#X&Re:avRe9~<5s&JwJZtQ~Gs*i^rzvdRg+Jv{%!2sbB@bX}kdga,!Za?&^*T1/!a'Dt+[y6>6Vyf3Wf%g/u;s4hGu6?Rh-JvZ,!c%#&RoX54Rivj7uyvf8RgTKvZB%*!2sGh<vu5Rgq<=C::9bb~#dZ#T&Ta6Y.X*Dt>[y93Wf)coZ(T,6VyifluvRgC@95@B@bX~/hFu34cC#T,k/unq8w8Q5RkUklwQuzunq8w8Q5Rk8d/rJu?v8w9)-&!a0a;a&aIWejg3sEr/h1s<DtDJvyZqY5aws3Jvy!&Wei~Hr1:au5@Bag>23E~5c:Z&bX};kKv?w&unuVu5Rjc;>bs)#~@:Rh.=ay<a]C;b`}Vd6s/t{uAvoaxa()!a,a7%-a#a2Dt,[yF2Wo[>6Vyt3[xuNuPRi&NuPwpi#RoWh?vf8Ri%Jv]!%Ri:KvxD!.'2WeAjZu`q9rxu,Re7woeAg-unLq(qA_/*2Wg_g3u5q^9:4E}/jTrxrzv=Wkkd~0UX#^^Xa-a1a5T&a=U1a'*aEa]!a*aPaA-adok[y54Rn>;:p3~Dp5g9rpsFNvZqjg3uJp4~<5p0Pw;5qlJwNZt*@3p1Pw:5p/Ou!5p2JvG'!6Vye=<qnJvh_[xhg3v,Rh3kOwOw-sDuev/Re^dha[a%!%!a+#Ta7)-5TaCaO!aka!a)sf[yb2>Rl!9ARiq5E}Qg=ucRkBE|oJrJ_@Wk~@Wk{JrJ_@Wk|@WkyJrJ_@Wk}@WkzJvO_[y2g-vMRmiKuYC!)&>Ri;>Ri<@3RkNc](X#@9Rk=g5vuRmhKvDB!+'=]meg3u4Rmgd)#Y'Vz3CARmfd`a+!%T'!+#Ta1Ta6TaM-sTDt9[yA9sYd'%Y#s[[xpj:ueunaXRgEjRq,v-vuqdd2'`#6Rev<32@5>:2<E}5xIo9a*X#Y(;5RePJvD_g>vyRgNj8w)v8<wggs:RgXiZt|vjx,hSq3ah!-(~@:Ro/Ou!5RhWj^v(pyw8unRhUdx-UY#^Ua.a3a70!)%UX1TaDa)'omRiRRhE[y:3Dsz=Br,>6Vyj3[xkg6ruwjcqsrPw;5r*Ku]D'Zt-@3r(~?r.i[vwv]dU1a--U#`a4(g/vsRhPOu!5RhLj:rmu9Wo!~@:wdh@g/vsRiTjXuvvNr}:RhBj^v(pyw8unRn]dz1UYa'a+^Y(!aETZalaRY.Ta?a4[yDJw1!#qLsW>6Vyrfzq-pLflpwRe|Js>%!Dt@3Dt&Jvy_[xs~HrnjMuwpsw'RecKu+D#'!t<~Grl~?rjg5u-x,gwp{ah!-(~@:Rg~Ou!5Rh'jXuvvNr}:Rh#cW#X/c;&!#2sLi[v7u7RgpJv)(!iLrxu,Re6j7v@s@5Se[e7d`aW!Za(a`T.a#!a3!&aDa-!9)Dt_=6s+3[x~~DR|h~DS6avhGun5RkZj3w)v-]mkKunB!&*]kb97R|i<ARk<c:Z(6Vy}Juh'!wziMRoS:F|vkLuauJv5vtvQRh1d='T+Y#VyO~DR|jcF#T'7R|g97R|kJv3'!ay<Rj,Jvh&!:ReXcsa6*a+#a#_aIRf9aLRf?c,Z&Rf5Rf7c.Z&Rf;Rf>cQ#%T'p-Rf8Rf=ct#%'(*!,p,Rf4p+Rf6Rf:Rf<d~'Ua%U*^UYa(!a,-!#a4YaTalaEX0a8a<Weo3Dt/3Dsx=Br93Wen~Dr;~<5p<JwNZt2@3p=Pw:5p;Ou!5r3c7&!#:p>3Ds}KvGB)_6Vyk2sM=<r7x'eovA(!hFu1ARf}cV#X&@r5j6rvwQa^Rf3c=Za'wkghJv__g;unRggA53B9=b^}%j6uduo5Jq;!(hIv%2Re`Ou4ARe_e%a#^^^Xa&!a*a2!&a6YaP!*ad!#a:aE/5Rn?[y@>6Vyp;:pE~DrY~<5pBJwNZt8@3pCh=rt3rWPw:5pAJup_[xoNuPpF9c!#'45pD5ARn)d8#X'X*3@rU72s]h>v<<sSjJpqvewOJq/(!hNw'5ReBk0s2u3w/w'5ReE5@Jq.!a+JQ!&WeU23d(#Y&RjG5]jBk!u7w&u0udARjEe#+^^^Ub#!a2/a`Z(agT1!a-a;|@TaG!aS[yV=Re~fow'RguNuPRe?bz#'>RoUWeL>:Cbb|?JwPZtVg6ruRmzJvD'!6Vz(g/vmRh~Jvy_[y(g9voRgyx*cy(#2>Ri2B9b]~9kIw9u7rluJu3Rg]dI#a%UY'@=p%CAx.gQZ&RhwwygtRm{x5g_Z'+ABqR9Woa=Bp&dV#^*Xa'!&@o{g4v]Rk;Jv{!%Rk[wkkiA5RkiwwfUB=x,fUuqC&*!>RfTg8v0RfV~ARfSd;rJsAuAv9wR'ae+/aO!a@aza/a#[yQ@Wg!2Wemg3sEr0JvB_g>uvReWg2v+Re=KupB_+[y!2AbY~-~Hr2AJwD!(h<~El>h<~El?Kun@+_:9b`}Kg-v/Ri3g;vtwyk_9]k_d=&T#*U.6qh@Ab`|K9:H|CJv[!&3Dtex'fDwC%!Rf[9WlMd[(^X,!a%Z06Vz!@WgBg=v~Rgvg,QRe@awd,#Y+jTv|Q~EfWj]uNr|~FRfXdy#Y&^Ua%!aO.!(a)Ua;=!a@aKap!a-,a!Ta]a[rSa]p?[y82sK=Bq~;:p:~<5p8Pw:5p7d'#Y'Wf(;RnRi[u4w&RgJJvG'!6Vyh=<r#ijuuv/sIKuYD'ZtG@3p9~Gr&d2#`(g<vtRgFj`u5w&rqpxRf2CJuY!+:wfnTOu!5Rg}jNs1ucv&RfwJvA!&3@q|BDcC#T,k/unq8w8Q5RkTklwQuzunq8w8Q5Rk9dga#!a'!a=#a0!:+Tb*b@aO.a4!aba8aFJv^}?!VyR~Dr<g;u%Rn.~<5p[x'e`wNZtR@3p]Pw:5pZhNvjBp.woe_g5u-r4JwF!%DtO3:ooc7&!#:p^3DtpLuGw(!+%)Dtk6Vz#2sd=<r8d'#Y([y#<x3gJt`w@!)%}MRiowzikRij=]ilxAf3,U(#B2Rf#g0v-Rm[ck{`U#]giKv3>)!&6Ri154s,KuGB_%@r68r:dJ|t`#X(9<E|u2@H|rx3gJu?w'!+'1Nu7Reg4=H~+9<wxgY95Rm]xLggZ-`(X}U2:Ri4h<uOawRmsJv__5@bb{jbV~3dka#a'a]!,#a+U=a>b6a3b%!/aKa/)!arwve^VyJ;:pR~DpTg3uJpS~<5pOPw;5qmPw:5pNOu!5pQJvG'!6Vyx=<qoJvA!{~Jup!%@qk7Rn/KvyD!}''[xz;>wkh'?Rh,x8gyt`w5D!&),(SgyccRgztJ@3pPB5p#d'(Y#<]mmifubw&RgoJvE&!82s^JvF&!8Rf,ADb]~;x=h'rNu]vK!,%'*0RnORh)4Rh*AqQg-vaRnNg;wHwkh'ba~4cE#Ta*x3gctyw@'!+%RnFRnD<4Rn@hFvK5RnCxWg[#`&a0Ua()`1Rm75Rg[c]%X#qi8Rg^NvdRj>BwzgZauwji7Rm6A4wgg]d1#&(*,.0a#Rm;Rm<Rm=Rm>Rm?Rm@RmARmBe%#^^^Xaea?aC/b+(,!a+a#!a/!>a&Ta<aKbD!2wphBRnk[yPw}hE|.=Br-3Dtm>6Vy~g6urRf.x,hPrNav!%'RnqRo%Ro#Nu;q[Pw;5r+JwNZtM@3r)d'#Y'Weh;xChL#`&RnmRnoKu}>%(!Rne~Bs-;2wjcussJv+'!aYSO}6@B<5?ba~8LrNvj!.%*ROwungw~ng~:9;Ri^>wtnig;wHRnixDh@|(UZ.x1h@|)!#:2<H|*xHn]#-UX'3Ro)z=iT}6ARns=Bwsn_wpnaRncw]aR(#UXa&Ua*a/=]iPd'#Y&Ro'WnXf{QRm2hNvj]nZd`'T~&1`{|`#9b]{}c:'!#Wl{>@=be}]?cl{{U#:5Abb}Jds#^YaF!a*b4a#a3aPa>&Tb!bH!*a_!Eau?/a&RjY<]gj>6Vz*;:pe~DrZg,QRj1JwNZtX@wihspcJvZ&!VyX9WmOJu|!|N2WmHJvh&!]ht~Bpbcn&T(!#RmQ<s7Nu;padH#X'`+WmJ@>RmKCARhnKup=!)&Wf+:RhqNuPpf9c!#'45pd5AwghpARn(Ls@w!%,)!RmP@Wfe<E|IJva!&WmNg8vsRmLd`*.`#Y'Xa!axRn*]hrA8Rhug5s@rXg8u!RmMd8#X'X*3@rV72smdI*#UY&RmICARho~GsgxVgd)Ta'U-Y&Xa!T#RnEWnA@Wffg1uDRi0hFvK5RnBxGnG&#`%owp)@wsf+bX}Ze-*1!a*^^^Ua|!#a.aq&Ya2!a>.a6!a:aO`aJDtL[y`@Wg#>6Vz12@wzoYRoZNuPRi!NuPRhzg=ucRi,@=b`{Yg=ucRi-ACJvB!&Sh[ebSh]ebi`wUuFRm4Jw2_[y0JvB!.<Ju(!&SoG}6Shd}6<Ju(!&SoH}6She}6Kur@._g5vHRieJvx!{L2G{Kx6gd'T#?Rh82Wi5cZ#X(g1w)Rm5dW-Y(Ta#!a)!#aYa=wnfE=su2>>bU{0j9udv:<svj8uQv-7RgHdE%#^'sq9sp=>Bb_{TJv`!&g/r|snj6v(us5d,#Y(56H}[978H}]Jw5!&g1rushJvB!+j;v{u5?zDhd}6}bj;v{u5?zDhe}6}ce*#`(^^^a[aea!=!a6a*aoXb1a.!aAbL!b>,b'aL!aV@Wf|2Wlg3[y/JwNZt^@3piPw:5pgJunZou3@rsJva&!Vy_g<v~Rm#JvG'!6Vz0=<r{Ju{%!:pj@WfsiXuJu3Rm:JvZ&!WfA~Bph@c4Z&Dtwax5rubx(#:awRk1@d,#Y&RfjRfid1#,Y(@Wfp2Wlrg5s@ryKu[@!,'=]ig9wlk?Rk>g5u-rqJvy'!@9RkQcH(T#=>Ri~@<wkj(Wj(KuZB*!&<7rw@9RkRcH(T#=>Ri}@<wkj)Wj)dg(Ta2Xa9X#`-!a*CARhg@@=I}d9x;c~#X%so=<sj>2@@=aybb}XjWv0Q~EfEj3vLv;<d,#Y(56H}`978H}_dgaPaFa'a/!#a3Y0a_a;a|!1(a7-[yE3[xt;:pJNvZrrg3uJrvJwNZt=@3pIh=rt3rxPw:5pGOu!5rpJvG'!6Vys=<rz@c4Z&Dt(ax5rtJvZ!&~BpH@wsfNg-vaRlNci*U#=<wei<F}a5@Jq.!a*JQ!%@qZ23d(#Y&RjH5]jCk!u7w&u0udARjFd/prq=tyvpaEa(a:.!a1aZ(@@=I}:9wpd%=<sX55w_h}@@=I{t=ay<aU@@=I}T=ay<2@@=I})?C9:9au@9Cb]}DP~=x-fAZ(2Wl1=ay<aU@@=I}>5@d##Y+jTv|vV~EfFj]uNpn~FRfGdgaK!Z2&!a8a-Tb({E!acTbM*!a(DtY[yYd'%Y#sl[y*hHvh>Re5x2c{Z}.j4uCvcawRiMd+#X+_x&d!},<5RkX;2Hzw@x,gavfB-!{CcF&T#Roe;RodwWbBg5urRgaKvHC*_6Vz+<4opieuew&Rmq@d]&Y)X,T#X0Rh}<BqP=4qS9:ReMg/ujReNJw0!/<Jui%!bd{kawwnemRelAxUa?a3#*.&UX(Ya+a/RhvRnQ<o}9Wmtd-#Y&RgSRmw9;Rmxay=Rmyg-vaRmuxEhSrNu,v-voC!%(aR.a(a7+1Ro1>Ro5CE{A9b]{@;5x#eO{:g;urRi+KrNA!%(Ro3>Ro79;Ri_Ku@>{;&!x%gX|{KunA_+g5QRj/g3u5Rj#g>uERj%wio/xRhS&!,!#^1U}wba{8>>@=be}qC@:D5ba{7Ku+A&!}x?ba}t>>@=be}se(aA^^^Uat!b0#{pa+awUazbGa#aLb9bgaWac'a5TbS=Br!d1#`%scp_Jvl!#rT>Re0JvX&!VyN=H{Fcm#U&:pY=ReaJv2&!]h0=]nUJvG'!6Vy|=<r%JrM_=]h2@Wlud'#)U'Wf'b]{i=]h/Jvh!&~BpWg=v]RnMx+ny#'Nu;pVwjnu=]nwxJnx,T#`&Reqwjnt=]nvieu9vrRjLLuYwP(#+!th@wih5pX~Gr'g5v/Rh4KunA'!-CARnP@wwiN:Rm_9x'cvw>!|l=<saKvAA!0&3@q}>w^e1bp#&Re2Re3BDx7gH#T|f5H|eKuZ>!%(:qNAH{]Jv6!+3B2B9=b^{X<5<B92:E{ZLvhwA(a;a%!igQuyRmad+#Y}m@3Rh5d8#X'X*:AqUAHzmaxwbh<aXRnVcF}RT#Nw&cj#U(BWnug/vsRntdka)(a3+.Zb7aYYan1!bVa@Xa}[y^@b[{G=H{+hFu73Rj&Pv#5ReQcK%T#sig1v{Rj'Ku+D#'!t]~Grm~?rkKuMB!01d5#`'Vy.ta3Dtu~Hroc8#'{^45s85AwZbP&!#Rn!wghxWn#KvEA!)&2RlA2RlBx:h|#(T,=]j09Wobz>x]z/@awRoTd+#Y(az]hFhCrm4d,#Y+jTv|Q~EfMj]uNr|~FRfOdCa!Xa9_X#@<plJvf!%b`{(9;Rgwc;.!#2x7cw#T|UDb]|T5Ju={(!=@E{&Jv)&!Ab`{'awJvf!~*>>@=be{#KuY>!+&4Ezyi[ugv&RjIdea+T)#UXa&T-T&a!Rh9auRmW=]kLg5vuRn+g3u4Rn-Ow6ARn,hHus5xNk?#UX(U~)/g8v0RkD~AwkkF?Ri.OuNBwkkA?Ri/d|a2`a*^UYa.!aBTZaTa'Xa;!(!2!-a#b2[yC>6Vyq3[xr2Wi?g1rusVh%s?DtF~<5rbJs;%!DtBfswKtCj[uvuSsEu3RgVx3o:u+wN'*Zt;@3rd~Grh~?rfg8w)Lq)qE&-a%!>bI|`jWv0vV~EfCjTv|vV~Ef@j]uNpn~FRfBcK#T']gWNu7x,k7q4ai(0!hHv8<RhmkMu9vrsBuev/RhlCJvB!,g<v{wchh~@:Rhji[vrv{wchi~@:RhkdS&a5UY#Ta!RgPwwiI5BwciI~@:Rh`x'iJvj'!5]iJPu8Bwch]~@:Rhach)U#h3rp]gLh@t|Ax,hTq3ah!-(~@:Ro0Ou!5RhXj^v(pyw8unRhVd|)`,^UYas!a?/a2Z'a^Ta{Tb7Ta(a#!a,Wf&9sZ3DtAadamov=Bqt3[xig8vsRm~>waiL2b`{QJv*_Ouv2qgj<v]v2BqfdR'X*X#Y-@3qr~Gqv~?p6hHv-]glPup5Lq+q?_%*b_{qF{n9b^{rOu4ARhpKvCD!+&~Bqp:5Dbb}nwoiKl&unuTuBv]v+ueunaXRf0=Jvh!0nKufu8v1w&w7q%w&uHrz:Rgnj5w,uxDJq/(!hNw'5ReCk0s2u3w/w'5ReFd>Za&!*UaA=<wkgsRnSJv^!%Refifw3vyRgOKu_B'!,<]gkiiu:w&Rh<=C@a^<B57@2F{[<B5@aW:=3away9A5aW=<B=C@a^<B57@2F{Ie-#`(^^^bCara.b8aza6!/bZ,!adTbnTbOb+aFaS!aAT9@Wf~2Wli3Dtl2@d,#Y&RfnRfmJwJZtN~GqyJva&!VyMg<v~Rm%iXuJu3Rm9Jv[_=]ih9wlkDRkCd1#`(@Wg>2Wls3cH#T(@<Rj*=>Ri|b~'#23s9h<~El.d'#Y&Dtxi^rzvdRl#d*#U%(o|B2s`hJwSaxRmDKv4B&!1:Rmdd5#`'Vx}to~Hq{x'f1v3(!BA5ba|bJv_&!Wfug1v]ReIdO+U/Y#&G}-8wze=Rh{g1v]ReHg/uQRf/by#)ibQwERl/cH#T(@<Rj+=>Ri{cNu+vlax-!(#a0qa9<Rii2;;bU{H;x<i=&X#Rk`<4wwi=C9H~8xAI(Y#<azRi@45wXI<B9;5bb~7dL(X#Xa(+!aL6Vy{g5QqOau:5au2@ay547EzbxOcU(UX-T#Ta#:Cbb|A?wjh/b_|SOw6ARgtihr}u7Rhy<d1#T)X1@@=I|~=ay<2@@=aybb}Sj3vLv;<d,#Y(56H}A978H}@dGpvs@uAu`vcw9*!aFa+ai%(b!aXa8.a?a[ozWey=sU2@G}Nch&U#Rf_WexKu+D#'!t:~Gr`~?r^j]uNr|~FRg*j^psurwJt|RmcKv)@&!)7Rkv~Br[@wxfO:Rl3co#U'6Rezj_q#vIuavjRltwzeyh@vr5JqD0!>aY?C9:9au@9Cb]}9cl#U*5;5<H||jbuus1ucv&Rfvg1v~d/pppzqFr^a--a~!aMat1(hFv;Wiz@@=Izoj5uuv-7Rix~Cw`fk2WlVcZ#X,k)u3vWs@u2]ktg;wEx'fBq(_2Wg/jTv|vV~EfoJv]!15x'hzqG!(P~EfU~CRl_j6v(us5x4i-#T(2WmZ?C2F|d>Kq<aj1!*jTqIsBv=Wl`~Cw`fi2WlWj`v0u*~>RlR=c>Z,k#u3vWs@u2]kr<c1Z+jTqIsBv=Wla~Cw`fm2WlXdmb3!a{(arZa`bkTa%TbQTa-a9+c'!aM!/[yL=Bqug.w'RifhFvyDRj.g>vgwyk^9]k^Jv3_@WfbAARkhJw2_[x|JvB_wkoIRoKwkoJRoLd'(Y#<]gm=<9<H|yd'%_X#skDtb3awwqkgNulRkgdB#^',9:p'hJwSaxRmEBwVb8@4=H|qLu+w50&!)@3qs~?pU>Awwn;;Rn=c:Z'ARn<=<qwKvC@!/&~BqqJv6!&]eVb^z^xRge'/a%+^`#Sge}6<4Rn3=]n0Pw2>Rn8Jw0!&>Rn:>Rn6cY#a7+!a&=<wkaNw~h3z_c5Z{=wjh#=]nLKv^D!&)Vyz=bW|swYb<WetcG#T(2wxa@qVx@gD#Y&b^|V5JwG&!5bb|pg/w&RgD@x=kHs=uAvn!a%%/'+RmSRh694Ro`g-vaRmRhHv-]mlxCcS#`&ba~.5cD#Ta)P~=d,#Y(56H{>978H{Dd_#{2^Y%_+qbbb{6g3sERhsbU{?dfa.,`a(Xa<!aiX#(55RiG54RiHcI#T'WiU3RiVNvdwtfcRlKNvdd,#Y&RlHRlExQgf.1*^T'X#Sgf}6Wn4=]hfPrk>Rn7Jw0!&>Rn5>Rn9Lunw?&a2!,5<oq@@wqfdRlJj5Q~=d,#Y(~ARfcOuN]fdDKw;ay(}i!547E}j?cI#T(@5bV}iCbV}hdv(^^Tb?a40,b##Tbo!a*bR!a<b|a/!aKai!aU[yK=]o^g:v>ReGJwPZtK<7Rh+h<~El,Pv#5ReR@awwxjCg,ulRjDJv6&!]j!z?aQeeg>w=Sh<eeJw;!&axEzOg,Qosc!#*:wkeJ]eJ>x'h-u(!%Ro.w~h.zPdNZ(X,Ya![x{;9ReY;wkgxRiF:x?ap#Y&RmUg<s2Rkod]+UY0TZ'!a&A9sw<=bczLNvuw{gqzNhJwSaxRmCKuLay!#&s_Rf-55b^{uJvZa!!c%#(55Ri654wmiu5RiuawLu,vp!+}^%b_}Y9;wkgxba}o>A9:=b^}zKuh=a''!3awRk3c*'!#aHRk6c+Z&Rk5Rk4Jv)&!awRjSawd9*`#0?C2@EzMj8u<uJ5RmbjQrquJu3x,k>uq@_+=ayb^|W~ARkEOuN]k@7dhzV^X/X&a-#zRzSb`zXcJzTT#2WkVKvDBzW!%FzY9;5bbzWjQrquJu3Jw3%!b`zU=ayb^zQd:#X(T-a!6Vyywxh}=b]{Jg=u1RiAdGp~qHtzv!w(wA+a+a;<!aJaYai'anasb(=azRmV:Cbb{MLq2vb!%')RjuRjrRjtRjqx3jnqCw3!%')Rk(Rk+Rk&Rk)Lq2vb!%')Rj{RjxRjzRjwLq2vb!%')RjsRjpRjfRjex3jcqCw3!%')Rk'Rk*RjkRjl9<CbbzfOu4ARhxLq2vb!%')RjyRjvRjhRjgx=joq*uKvb!%')+-Rk.Rk%Rj~Rk-Rk#Rj}x=jdq*uKvb!%')+-Rk,Rk!Rj|RjmRjjRjidAq&qKs@uAv8Aa.'*-a@a&0!aM@a5[y73Dsy3Ds|3Dt):wxgI2sHJwJZt.~Gqxwsf0ikrzt}Rl0Jvy_[xj~HqzKv_A|D!&WfP8axRoVcf,U#k(v]v+ueunaXRf1Ju}'!g8u#Ri=jQw!sCunLprq>!,')~<5qeGzq9F{W=c##%s5au:5aU3CBE|;d4#X(D!a&6Vygx(b;#(=]ed?C2F{N<capoq2r[a&!aPa9,'Pw;5s:@@=I|,55w_h|@@=IzcP~=x'fCqB_2Wl2>aU@@=I|1OuNBc1Z+jTqIsBv=Wlc~Cw`fl2WlZ~AcTa%!Z+jTqIsBv=Wlb~Cw`fh2WlYk+uNqJsBv=WlSg,u3dca3#UXaMYa)TaB-=cM|7T#<bI}l5@B932:aV2G{BOuNBJq:|M!5Ezt=<B=C@a^<B57@2F{v>cB{/T#=ay<bI{3Jv6!a.6BKq0ah&+!5E}HP~Ef{978BaU@@=Iza<7d#.Y#978BaU@@=IzH~AJq0!(@@=IzG978BaU@@=IzFe,aU*Y&^^^bvJb,b:bFad!a,c2Ta>aL.bo6!a#CbTa'T#Re{2Wlh2@G{yg6t~Ro_NvdRfticuRQRllJv3&!x&c|zs@Jw3!%RflwpfkRlpKuL;%(!Re<@G|C2GzdhIvuBwgjAg-u0RjAKQB%!(GzZ@G|5NuuRl7d='T+Y#Vy[g<v~Rm!==G|>JvA!)@wma=]m1ifuaw&RmnLs@vT'!|/+[y,g:v>ReTJw1!#qX=x!eC{bLu+wT&)ZtZauq_~Graci&U#F|89:r_Lupvq!.)&2RlG8RfaC=x!eF{_h?rpWlmd&'!#X|&]k::xJey#`'T|+<E|&2@H|%dE#(^,g;u.RiEg6vjRiC9xCkA{O|zY#g=ucRmXKs0@!&*@G|m@awRknJuh!,3d(}gY}eJvj!%Rm):Jw3!%Rm+Rm-Ls0w(&!a(a#@b[|6cZ#X'7RkxWgAOu4ARn'dH'U#Y*Vz-Wm'CARm}d]*#a%^a*T'aK!a<9bV{PC=p*Jw4!&SgxcbB5r]idw(wBRmF7xFkt#&`(Rm/Rm8E|!JuY_9:Rl5=wrgr2:bbxd@xXfB(a*#T+!.X0X1Ta/a'T&RlDRfL>RlyARl9b[z[>RfZ:RlL:RfRwlg/ARl;9;RlxKv,A/!%7s69<74=BA5ba{-8Bde#`a<XaKYa1,a'P~=wxfB2bZ}}?C972@@=I}r8@55B9;5bb}G978B2@@=aybb}3j3vLv;<Jw3&!>Rfk=ayb^}4~Ad1#`*@@=aybb{w2@>==<bbz]dx+UY#^UaF!a9!bB'Ya1.!ajXa#%olRhD[y=3Dt#Ov5BrHKuMB%!(Rf^Wep~HrJwkiQjKr|~FRg)Ku+D#'!t5~GrF~?rDdV)UY,Z/_7RkuG{<~BrBg,rlsO:235B@bX}|d?a1!#`(6Vyn5@d##Y+jTv|vV~EfIj]uNpn~FRfH7Lq2vb1!a9-978BaU@@=Iz9978BbU}#~AJq0!(@@=Iz8978BaU@@=Iz7~AJQ|}!978BbU}!JvkaK!AdUa21-U#`a+(g/vsRn~Ou!5RPj:rmu9WhOjXuvvNr}:RhAj^v(pyw8unRn[kPr}p|u7vwv]RiSBd;pppzq@qHQa?(b.!a.a`@.|xa(hFv;Wiyj5uuv-7Riw~Cw`fg2WlU978BbU|wOuNBJqG!(P~EfD~CRlQcZ#X,k)u3vWs@u2]ksg;wEx'f@q1_2Wg.j]uNpn~FRfqJv]!15x'h{qG!(@@=IzK~CRl^j6v(us5x4i,#T(2WmY?C2F{1>Kq<aj1!*jTqIsBv=Wld~Cw`fj2Wl[j`v0u*~>RlT=c>Z,k#u3vWs@u2]kq<c1Z+jTqIsBv=Wle~Cw`fn2Wl]dn1#c(a(b^a2!b/bAT(bj!aDa7bu,a_a{c0!2T0g:v>ReD2@G{42@G{5~DpM~<5rc=Bx6i>{RT#RnI@zCx]y]z:2Jv[!zr5Awyk]9]k]dD(Y+X#6Vz.g=wKtgwhaCwgmTWj2Lu,w%_+/[y-B;b^xeg3u3Rj-2@bX{*KrJ<!+'@Wg(g?QRlC@Jv`!%b[zIwsfII}8JQ_@w|kW|=Jv(%!AqcOuNBJvEzh!bYzjLs@wP#(0!oy@>RkdJwMZtc3Dtd@BcG#T'9bWxg2@2Fznd*#Y+;2x'c}w<zizixNgwa#Z'U+!/!a'!a+w~g~z6wcn{Rn}wcnzRn|5Rh%=]nJg5vuRmvNvdRlvcprJu}w*az*a#!%.a.'Bot9qT]kj@Wg'ay2Gzv@Jv`!%b[zEwsfHI}1;ck#Ux`<Cbbx_Lu+w!a&0*!wko*wwo,So,}6Juqxf!E}PigQuyRm`d3(`#8>Rn%:A5B;bZ~%KvhCa!a2!x>k7#Uxb@b{#xaRk7Jw0!)>wwhlShl}6>wwhmShm}6CJvB!.x'hhvj{!!5Bwkhhbaz}x'hivjz~!5Bwkhibaz|xEhTrNu,v-vpD!a%&/)a3a.,%Ro2t[CE{)@3re9b]{%wjo09:rgc:Z&Ro6=<riifuaw&RmoKrNA!%(Ro4>Ro89;Ri`dSaL'UYzxZb)7Rka3xRhT&!,!#^1U}vbaz{>>@=be}yC@:D5bazzKu+A&!}{?ba}y>>@=be}wxBh[t`u~vJvr!%a!a()a,a0a4RoC=]o;Ju(!%RoGRhdwjh`=]oAg>w#Ro?g5vuRo=NvdRl|Ku]C.!&;RoEJvB!%RoORoMBx'h[v+_?w~h`}~5?w~hd~!xKh]oiptu-utv.vp!#%&a30a@a'a+(a/aOp(o~p!RoDJu(!%RoHRhewjha=]oBNvdRl}g>w#Ro@g5vuRo>c[#X']o<CauRoRAd-#Y':RkpauRoQKu]C.!&;RoFJvB!%RoNRoPBx'h]v+_?w~ha}t5?w~he}ue!/UbhYacXaW^Tc&a;b:a-c/#b&aja1(!cL+!bKbt!bmcRc9aIc?8[yW3Dtt94Rg`Jv}!&SiRMzBhEebShEMNuPRe>x7gL#TzuwjirRipc<Z&>on;>z=h-MSh.Mwqczx'a7vj&!>Re4@=ResJt__NuPRi*NuPRi)j]uNr|~FRfzKrJ>_+@Wfy@Wf]2WocKrJ<!+'@Wg%g/QRl@@Jv`!&awRl<wsfFIzgLu(w*!.*&ShBMwvhIRhI9;RhNx1hK'!#Sn]Mx1hK~0!#:2<H~7cNu+w7D*'1ZtW>Rn1~?rOc:Z&Rn2=<rQ<7wjh&=BSnLMc]#X(6Vz)w[b=a!U#9wzgMc3#&(RgMRitRis<x,gKt`ax!&+SioM=BSilMc3#&(RgKRinRimKurB,!&SiQMzBhDebShDM6BJQ!(P~Efx978B2@@=I}WLrJw!!,a*&@G}O@9wkibRid@@x'fKwC!&SlDMSfLMjUv~Q~EfKKv3@a+!(hFv-]mpx/hYZ(C5RiWz<o/MwkhY?So/M@x,gbvfB*&!SgEM:SoeeehFu3:Rgbda(,^TZa)X/7Sg[eb:2RgI~BrMC@wgkc:wwkcRerx3h(uUvK!&*,SnOM4Sh*MArRg;wHRh(x=h;rJvPwI!a4',a'0@Wg&=BSh/Mg>w=Rh=g3w*wwgGRgGcW(X#;Sg}M2Gzk@Jv`!&awRl=wsfGIz`dKZ*T'Y-:RhR7RhQg5u-p`j6v(us5d,#Y+~Awkia?RicOuNBwkibba}Ld6p~tyu_vbAa'a+!a/'a3aEa8a!>Sh,ebJv{!&Sh@ebSaReb9;SgwebNuPRi(NvdRl)NuPRi'hHu^<Rm^Jvv_@Wl(g;u1Si/ebKu'B&!*Sh?eb@Wl'z@aPeb95Si.ebcpputyvjB)!,&a+0a%ShAMWeK@G}C@WfJ9;RhMwvhH9w{ia}ix,hJvRA1(!zAn[MRhHx1hJ~*!#hFv(BSn[MBJQ!(@@=I~'978B2@@=I}2db.Ua<'X}+T#a0XaG2G}E;wkg|wuh!Rh!x,hZu,@)!&So0MVy)C5RiXACJvB!&5RiY5RiZg8w)cG}*T#2@bU}=KsA>(!a.3wkhZba~(x,h^u(A!&(SoCMRhb5Bz=h[eb?w~hb~6x,h_u(A!&(SoDMRhc5Bz=h]eb?w~hc~6e)aA1T#T,^^^c-bMb&blcPaP(a/!0!bA=b5c@a(!bfbrc#2afwmhARnjwchORnp2Wlf3DtsNvdRl-2@wpa<]m0bx(#:awRk2@Jw3!%RfhwpfgRlnKQB%!(G{V@G|'NuuRl6d='T+Y#VyUg<v~Rl~==G|<Jv+'!aYShC}6@B<5?ba~8@Jw3'!g2QRljhLrpWlOd+#Y'g.w'rIg>w*wgj@g-u0Rj@Lu+wT&)ZtUauq]~GrGci&U#F|39:rELrNvj!.%*RhCwunfw~nf~:9;Ri]>wtnhg;wHRnhx3hDs@v~!/+'@Wfr@9RkSNu&Rlo=@<5GzoKs0@_+@Wl+@awRkmJuh!-3d(}pY#qWJvj!%Rm(:Jw3!%Rm,Rm*de&!1U-U#`)Re;@G|.@9Ri82@wjfvRlq=@<5GzpLvOvr!).&2RlF8Rf`C=x!eE{.Jw3_g2QRlkhLrpWlPde(!#U{s,UXa*Ta'[y'g:v>ReS;x0PZ&RnlRnn~HrKJw1}f!=x!eB|2w]aP(#Xa&a*Ta.Ua2a7=]iOd'#Y&Ro&WnWg;u.RiDg6vjRiBNvdRlzhNvj]nYJuW_2Wm3x)kFze{9d])!a.!,Y01!#&aC!a3RndC=ox~BrC@2b^{pg,rlse7x'ksuq!%Rm.E{xidw(wBRmGx9o+)X#wwo-So-}69:Rl4@xSf@a#XZ'X)X,Ta(/ARl8b[xc>RfY:RlI:RfQwlg.ARl:9;Rlwdn'#^XafaQa1X1TaHTa)@b[{zcZ#X'7RkwWg@Ou4ARn&x)kG#{,g7u/RkGdH'U#Y*Vz'Wm&CARm|bx#(A]gUbUzJj9Q~=d,#Y(56H}l978H{U7d,0#U*2>ABb_xZ978BbU{e~AJQ{g!978BbU{hxMh?ad{oUYZ.x1h?{l!#:2<H{mx3n[t{vl!,&a%3Ro(z=iS}6ARnr=Bwsn^wvn`Rnbd`*T}B0!#^X'BG{c9b]{a>>@=be}F?JvS!&BG{d7BG}(Bde#`a1X,Ya@!a'P~=wxf@2bZ}I56B2@@=aybb}08@55B9;5bb}<j3vLv;<Jw3&!>Rfg=ayb^}&OuNBKuLA!)a!P~=x#fD{f2@>==<bbzl?C972@@=Ix^d6rSu,v7w*C(0a)a6#B+a%!sQ[y?3Dt%3[xn~<5rLOu!5p@Ku+D#'!t7~GrP~?rNKvlaya7'!h+v-5qMg=t|cd,U#5AAaa5Abb{S@52B5@a[@52B5Gx[iXueu;d<#`a(!/549C;ag>23ExY5@Dah89b^~689Jv)!~2b[~1Lv'w(%*!a#bX|aPrmawRe]keu7uhv-q6rxu,q`xTo]/a5aU!bNaDXbi!b-!ao!b<bwA!#5@B932:aV2G|:d-)Y#hJrL>RhG<7@C5<H|_=Cau:5aj5@B932:bJ|ng>vIbs)#?C2F|9jPv0w.vISh-MKvUaz(.!9ABbb|[5;5<H|Eg>unwfh;9:4E|YjQsBt|vjx'hYq3!(?C2F|J:2<BaY?C2F|GOu!5x,g|p{ah!-(?C2F|c9:4E|OjXuvvNr}:Rh&i[w*t|cd+U#jJvsu)vsSn~Mkfrmu9p}u7vwv]So!McW#Xa!ax5@A5aY:5;5<H|>kJv~vYrquJu3x4ib#T)2@SmZM?C2F|Bj:rmu9@xPhI(a*a#U#`a3-5Abb|L~@:RhK9:4E|0@52B5G|#C::aY?C2F|-:2<BaY?C2F|.5Jvk!a)javYrquJu3x4ia#T)2@SmYM?C2F|HAxPhH(!a#U#`a*-5Abb|4~@:RhJ9:4E|R@52B5G|F:2<BaY?C2F|Sc^#Xa2j=Qq5CJvB!-g<v{z;hhM?C2F|Zi[vrv{z;hiM?C2F|XKsA>!a)-g<v{z;h[eb?C2F|]i[vrv{z;h]eb?C2F|^iZu.vix,hZq3ah!.(?C2F|QOu!5ShXM:2<BaY?C2F|P",13494,2713,49,25,61)});var VI;var Oce=Ho(()=>{VI=new Uint16Array([512,26465,29036,7,0,2,4,116,24638,116,24636,8693,29807,24610,621,1,0,0,3,112,24614,111,115,24615])});var ec;var zNe=Ho(()=>{(function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.FLAG13=8192]="FLAG13",e[e.BRANCH_LENGTH=8064]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE",e[e.VALUE_MASK=8191]="VALUE_MASK"})(ec||(ec={}))});function jNe(e){return e-bl.ZERO>>>0<=9}function OCi(e){return(e|Kj)-bl.LOWER_A>>>0<=5}function NCi(e){return(e|Kj)-bl.LOWER_A>>>0<=25}function LCi(e){return e===bl.EQUALS||NCi(e)||jNe(e)}class Nce{decodeTree;emitCodePoint;errors;state=yl.EntityStart;consumed=1;result=0;treeIndex=0;excess=1;decodeMode=Lm.Strict;runConsumed=0;constructor(e,t,i){this.decodeTree=e,this.emitCodePoint=t,this.errors=i}startEntity(e){this.decodeMode=e,this.state=yl.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0}write(e,t){switch(this.state){case yl.EntityStart:{if(e.charCodeAt(t)===bl.NUM)return this.state=yl.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1);return this.state=yl.NamedEntity,this.stateNamedEntity(e,t)}case yl.NumericStart:return this.stateNumericStart(e,t);case yl.NumericDecimal:return this.stateNumericDecimal(e,t);case yl.NumericHex:return this.stateNumericHex(e,t);default:return this.stateNamedEntity(e,t)}}stateNumericStart(e,t){if(t>=e.length)return-1;if((e.charCodeAt(t)|Kj)===bl.LOWER_X)return this.state=yl.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1);return this.state=yl.NumericDecimal,this.stateNumericDecimal(e,t)}stateNumericHex(e,t){let i=e.length,{result:r}=this,{consumed:n}=this;while(t<i){let o=e.charCodeAt(t);if(jNe(o)||OCi(o)){let s=o<=bl.NINE?o-bl.ZERO:(o|Kj)-bl.LOWER_A+10;r=r*16+s,n+=1,t+=1}else return this.result=r,this.consumed=n,this.emitNumericEntity(o,3)}return this.result=r,this.consumed=n,-1}stateNumericDecimal(e,t){let i=e.length,{result:r}=this,{consumed:n}=this;while(t<i){let o=e.charCodeAt(t)-bl.ZERO;if(o>>>0>9)return this.result=r,this.consumed=n,this.emitNumericEntity(o+bl.ZERO,2);r=r*10+o,n+=1,t+=1}return this.result=r,this.consumed=n,-1}emitNumericEntity(e,t){if(this.consumed<=t)return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(e===bl.SEMI)this.consumed+=1;else if(this.decodeMode===Lm.Strict)return 0;if(this.emitCodePoint((this.decodeTree===VI?FNe:RNe)(this.result),this.consumed),this.errors){if(e!==bl.SEMI)this.errors.missingSemicolonAfterCharacterReference();this.errors.validateNumericCharacterReference(this.result)}return this.consumed}flushAndEmitLegacyOrReject(e,t,i,r){return this.consumed=e,this.excess=t,this.result===0||this.decodeMode===Lm.Attribute&&(r===0||t>1||LCi(i))?0:this.emitNotTerminatedNamedEntity()}stateNamedEntity(e,t){let{decodeTree:i}=this,r=e.length,n=this.decodeMode===Lm.Strict,{treeIndex:o}=this,{excess:s}=this,{consumed:a}=this,c=i[o];while(t<r){while((c&(ec.VALUE_LENGTH|ec.FLAG13))===0&&(c&ec.JUMP_TABLE)!==0){let m=e.charCodeAt(t),h=c&ec.JUMP_TABLE,f=(c&ec.BRANCH_LENGTH)>>7;if(f===0){if(m!==h)return this.flushAndEmitLegacyOrReject(a,s,m,0);o+=1}else{let g=m-h;if(g>>>0>=f)return this.flushAndEmitLegacyOrReject(a,s,m,0);let y=i[o+1+g];if(y===0)return this.flushAndEmitLegacyOrReject(a,s,m,0);o=o+f+y&65535}if(c=i[o],t+=1,s+=1,t>=r)break}if(t>=r)break;if((c&(ec.VALUE_LENGTH|ec.FLAG13))===ec.FLAG13){let m=(c&ec.BRANCH_LENGTH)>>7,{runConsumed:h}=this;if(h===0){let f=e.charCodeAt(t);if(f!==(c&ec.JUMP_TABLE))return this.flushAndEmitLegacyOrReject(a,s,f,0);t+=1,s+=1,h=1}while(h<m){if(t>=r)return this.treeIndex=o,this.excess=s,this.consumed=a,this.runConsumed=h,-1;let f=h-1,y=i[o+1+(f>>1)]>>((f&1)<<3)&255,b=e.charCodeAt(t);if(b!==y)return this.runConsumed=0,this.flushAndEmitLegacyOrReject(a,s,b,0);t+=1,s+=1,h+=1}this.runConsumed=0,o+=1+(m>>1),c=i[o];continue}let u=c>>>14,d=e.charCodeAt(t);if(u!==0){if(!n&&(c&ec.FLAG13)===0)this.result=o,a+=s-1,s=1;if(d===bl.SEMI)return this.emitNamedEntityData(o,u,a+s);if(u===1)return this.flushAndEmitLegacyOrReject(a,s,d,u)}let p=zCi(i,c,o+(u||1),d);if(p<0)return this.flushAndEmitLegacyOrReject(a,s,d,u);o=p,c=i[o],t+=1,s+=1}if(!n&&c>>>14!==0&&(c&ec.FLAG13)===0)this.result=o,a+=s-1,s=1;return this.treeIndex=o,this.excess=s,this.consumed=a,-1}emitNotTerminatedNamedEntity(){let{result:e,decodeTree:t}=this,i=t[e]>>>14;return this.emitNamedEntityData(e,i,this.consumed),this.errors?.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(e,t,i){let{decodeTree:r}=this;if(this.emitCodePoint(t===1?r[e]&ec.VALUE_MASK:r[e+1],i),t===3)this.emitCodePoint(r[e+2],i);return i}end(){switch(this.state){case yl.NamedEntity:return this.result!==0&&(this.decodeMode!==Lm.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case yl.NumericDecimal:return this.emitNumericEntity(0,2);case yl.NumericHex:return this.emitNumericEntity(0,3);case yl.NumericStart:return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;default:return 0}}}function zCi(e,t,i,r){let n=(t&ec.BRANCH_LENGTH)>>7,o=t&ec.JUMP_TABLE;if(o){if(n===0)return r===o?i:-1;let c=r-o;if(c>>>0>=n)return-1;let u=e[i+c];return u===0?-1:i+n+u-1&65535}if(n===0)return-1;let s=n+1>>1,a=i+s+n;for(let c=0;c<n;c++){let d=e[i+(c>>1)]>>((c&1)<<3)&255;if(d===r){let p=i+s+c;return a+e[p]&65535}if(d>r)return-1}return-1}var bl,Kj=32,yl,Lm;var UNe=Ho(()=>{MNe();Oce();zNe();LNe();Oce();(function(e){e[e.AMP=38]="AMP",e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_X=120]="LOWER_X"})(bl||(bl={}));(function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity"})(yl||(yl={}));(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(Lm||(Lm={}))});function Nw(e){return e===hi.Space||e===hi.NewLine||e===hi.Tab||e===hi.FormFeed||e===hi.CarriageReturn}function U2(e){return e===hi.Slash||e===hi.Gt||Nw(e)}function jCi(e){return e>=hi.LowerA&&e<=hi.LowerZ||e>=hi.UpperA&&e<=hi.UpperZ}class q2{cbs;state=He.Text;buffer="";sectionStart=0;index=0;entityStart=0;baseState=He.Text;isSpecial=!1;running=!0;offset=0;xmlMode;decodeEntities;recognizeSelfClosing;entityDecoder;constructor({xmlMode:e=!1,decodeEntities:t=!0,recognizeSelfClosing:i=e},r){this.cbs=r,this.xmlMode=e,this.decodeEntities=t,this.recognizeSelfClosing=i,this.entityDecoder=new Nce(e?VI:Mce,(n,o)=>this.emitCodePoint(n,o))}reset(){this.state=He.Text,this.buffer="",this.sectionStart=0,this.index=0,this.baseState=He.Text,this.isSpecial=!1,this.currentSequence=Xi.Empty,this.sequenceIndex=0,this.running=!0,this.offset=0}write(e){this.offset+=this.buffer.length,this.buffer=e,this.parse()}end(){if(this.running)this.finish()}pause(){this.running=!1}resume(){if(this.running=!0,this.index<this.buffer.length+this.offset)this.parse()}stateText(e){if(e===hi.Lt||!this.decodeEntities&&this.fastForwardTo(hi.Lt)){if(this.index>this.sectionStart)this.cbs.ontext(this.sectionStart,this.index);this.state=He.BeforeTagName,this.sectionStart=this.index}else if(this.decodeEntities&&e===hi.Amp)this.startEntity()}currentSequence=Xi.Empty;sequenceIndex=0;enterTagBody(){if(this.currentSequence===Xi.Plaintext)this.currentSequence=Xi.Empty,this.state=He.InPlainText;else if(this.isSpecial)this.state=He.InSpecialTag,this.sequenceIndex=0;else this.state=He.Text}stateSpecialStartSequence(e){let t=e|32;if(this.sequenceIndex<this.currentSequence.length){if(t===this.currentSequence[this.sequenceIndex]){this.sequenceIndex++;return}if(this.sequenceIndex===3){if(this.currentSequence===Xi.ScriptEnd&&t===Xi.StyleEnd[3]){this.currentSequence=Xi.StyleEnd,this.sequenceIndex=4;return}if(this.currentSequence===Xi.TitleEnd&&t===Xi.TextareaEnd[3]){this.currentSequence=Xi.TextareaEnd,this.sequenceIndex=4;return}}else if(this.sequenceIndex===4&&this.currentSequence===Xi.NoembedEnd&&t===Xi.NoframesEnd[4]){this.currentSequence=Xi.NoframesEnd,this.sequenceIndex=5;return}}else if(U2(e)){this.sequenceIndex=0,this.state=He.InTagName,this.stateInTagName(e);return}this.isSpecial=!1,this.currentSequence=Xi.Empty,this.sequenceIndex=0,this.state=He.InTagName,this.stateInTagName(e)}stateCDATASequence(e){if(e===Xi.Cdata[this.sequenceIndex]){if(++this.sequenceIndex===Xi.Cdata.length)this.state=He.InCommentLike,this.currentSequence=Xi.CdataEnd,this.sequenceIndex=0,this.sectionStart=this.index+1}else if(this.sequenceIndex=0,this.xmlMode)this.state=He.InDeclaration,this.stateInDeclaration(e);else this.state=He.InSpecialComment,this.stateInSpecialComment(e)}fastForwardTo(e){while(++this.index<this.buffer.length+this.offset)if(this.buffer.charCodeAt(this.index-this.offset)===e)return!0;return this.index=this.buffer.length+this.offset-1,!1}emitComment(e){this.cbs.oncomment(this.sectionStart,this.index,e),this.sequenceIndex=0,this.sectionStart=this.index+1,this.state=He.Text}stateInCommentLike(e){if(!this.xmlMode&&this.currentSequence===Xi.CommentEnd&&this.sequenceIndex<=1&&this.index===this.sectionStart+this.sequenceIndex&&e===hi.Gt)this.emitComment(this.sequenceIndex);else if(this.currentSequence===Xi.CommentEnd&&this.sequenceIndex===2&&e===hi.Gt)this.emitComment(2);else if(this.currentSequence===Xi.CommentEnd&&this.sequenceIndex===this.currentSequence.length-1&&e!==hi.Gt)this.sequenceIndex=Number(e===hi.Dash);else if(e===this.currentSequence[this.sequenceIndex]){if(++this.sequenceIndex===this.currentSequence.length){if(this.currentSequence===Xi.CdataEnd)this.cbs.oncdata(this.sectionStart,this.index,2);else this.cbs.oncomment(this.sectionStart,this.index,3);this.sequenceIndex=0,this.sectionStart=this.index+1,this.state=He.Text}}else if(this.sequenceIndex===0){if(this.fastForwardTo(this.currentSequence[0]))this.sequenceIndex=1}else if(e!==this.currentSequence[this.sequenceIndex-1])this.sequenceIndex=0}isTagStartChar(e){return this.xmlMode?!U2(e):jCi(e)}stateInSpecialTag(e){if(this.sequenceIndex===this.currentSequence.length){if(U2(e)){let t=this.index-this.currentSequence.length;if(this.sectionStart<t){let i=this.index;this.index=t,this.cbs.ontext(this.sectionStart,t),this.index=i}this.isSpecial=!1,this.sectionStart=t+2,this.stateInClosingTagName(e);return}this.sequenceIndex=0}if((e|32)===this.currentSequence[this.sequenceIndex])this.sequenceIndex+=1;else if(this.sequenceIndex===0){if(this.currentSequence===Xi.TitleEnd||this.currentSequence===Xi.TextareaEnd){if(this.decodeEntities&&e===hi.Amp)this.startEntity()}else if(this.fastForwardTo(hi.Lt))this.sequenceIndex=1}else this.sequenceIndex=Number(e===hi.Lt)}stateBeforeTagName(e){if(e===hi.ExclamationMark)this.state=He.BeforeDeclaration,this.sectionStart=this.index+1;else if(e===hi.Questionmark)if(this.xmlMode)this.state=He.InProcessingInstruction,this.sequenceIndex=0,this.sectionStart=this.index+1;else this.state=He.InSpecialComment,this.sectionStart=this.index;else if(this.isTagStartChar(e)){this.sectionStart=this.index;let t=this.xmlMode||this.cbs.isInForeignContext?.()?void 0:UCi.get(e|32);if(t===void 0)this.state=He.InTagName;else this.isSpecial=!0,this.currentSequence=t,this.sequenceIndex=3,this.state=He.SpecialStartSequence}else if(e===hi.Slash)this.state=He.BeforeClosingTagName;else this.state=He.Text,this.stateText(e)}stateInTagName(e){if(U2(e))this.cbs.onopentagname(this.sectionStart,this.index),this.sectionStart=-1,this.state=He.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateBeforeClosingTagName(e){if(Nw(e))if(this.xmlMode);else this.state=He.InSpecialComment,this.sectionStart=this.index;else if(e===hi.Gt){if(this.state=He.Text,!this.xmlMode)this.sectionStart=this.index+1}else this.state=this.isTagStartChar(e)?He.InClosingTagName:He.InSpecialComment,this.sectionStart=this.index}stateInClosingTagName(e){if(U2(e))this.cbs.onclosetag(this.sectionStart,this.index),this.sectionStart=-1,this.state=He.AfterClosingTagName,this.stateAfterClosingTagName(e)}stateAfterClosingTagName(e){if(e===hi.Gt||this.fastForwardTo(hi.Gt))this.state=He.Text,this.sectionStart=this.index+1}stateBeforeAttributeName(e){if(e===hi.Gt)this.cbs.onopentagend(this.index),this.enterTagBody(),this.sectionStart=this.index+1;else if(e===hi.Slash)this.state=He.InSelfClosingTag;else if(!Nw(e))this.state=He.InAttributeName,this.sectionStart=this.index}stateInSelfClosingTag(e){if(e===hi.Gt){if(this.cbs.onselfclosingtag(this.index),this.sectionStart=this.index+1,!this.recognizeSelfClosing){this.enterTagBody();return}this.state=He.Text,this.isSpecial=!1,this.currentSequence=Xi.Empty}else if(!Nw(e))this.state=He.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateInAttributeName(e){if(e===hi.Eq||U2(e))this.cbs.onattribname(this.sectionStart,this.index),this.sectionStart=this.index,this.state=He.AfterAttributeName,this.stateAfterAttributeName(e)}stateAfterAttributeName(e){if(e===hi.Eq)this.state=He.BeforeAttributeValue;else if(e===hi.Slash||e===hi.Gt)this.cbs.onattribend(ap.NoValue,this.sectionStart),this.sectionStart=-1,this.state=He.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(!Nw(e))this.cbs.onattribend(ap.NoValue,this.sectionStart),this.state=He.InAttributeName,this.sectionStart=this.index}stateBeforeAttributeValue(e){if(e===hi.DoubleQuote)this.state=He.InAttributeValueDq,this.sectionStart=this.index+1;else if(e===hi.SingleQuote)this.state=He.InAttributeValueSq,this.sectionStart=this.index+1;else if(!Nw(e))this.sectionStart=this.index,this.state=He.InAttributeValueNq,this.stateInAttributeValueNoQuotes(e)}handleInAttributeValue(e,t){if(e===t||!this.decodeEntities&&this.fastForwardTo(t))this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(t===hi.DoubleQuote?ap.Double:ap.Single,this.index+1),this.state=He.BeforeAttributeName;else if(this.decodeEntities&&e===hi.Amp)this.startEntity()}stateInAttributeValueDoubleQuotes(e){this.handleInAttributeValue(e,hi.DoubleQuote)}stateInAttributeValueSingleQuotes(e){this.handleInAttributeValue(e,hi.SingleQuote)}stateInAttributeValueNoQuotes(e){if(Nw(e)||e===hi.Gt)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(ap.Unquoted,this.index),this.state=He.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(this.decodeEntities&&e===hi.Amp)this.startEntity()}stateBeforeDeclaration(e){if(e===hi.OpeningSquareBracket)this.state=He.CDATASequence,this.sequenceIndex=0;else if(this.xmlMode)this.state=e===hi.Dash?He.BeforeComment:He.InDeclaration;else if((e|32)===Xi.Doctype[0])this.state=He.DeclarationSequence,this.currentSequence=Xi.Doctype,this.sequenceIndex=1;else if(e===hi.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=He.Text,this.sectionStart=this.index+1;else if(e===hi.Dash)this.state=He.BeforeComment;else this.state=He.InSpecialComment}stateDeclarationSequence(e){if(this.sequenceIndex===this.currentSequence.length)this.state=He.InDeclaration,this.stateInDeclaration(e);else if((e|32)===this.currentSequence[this.sequenceIndex])this.sequenceIndex+=1;else if(e===hi.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=He.Text,this.sectionStart=this.index+1;else this.state=He.InSpecialComment}stateInDeclaration(e){if(e===hi.Gt||this.fastForwardTo(hi.Gt))this.cbs.ondeclaration(this.sectionStart,this.index),this.state=He.Text,this.sectionStart=this.index+1}stateInProcessingInstruction(e){if(e===hi.Questionmark)this.sequenceIndex=1;else if(e===hi.Gt&&this.sequenceIndex===1)this.cbs.onprocessinginstruction(this.sectionStart,this.index-1),this.sequenceIndex=0,this.state=He.Text,this.sectionStart=this.index+1;else this.sequenceIndex=Number(this.fastForwardTo(hi.Questionmark))}stateBeforeComment(e){if(e===hi.Dash)this.state=He.InCommentLike,this.currentSequence=Xi.CommentEnd,this.sequenceIndex=0,this.sectionStart=this.index+1;else if(this.xmlMode)this.state=He.InDeclaration;else if(e===hi.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=He.Text,this.sectionStart=this.index+1;else this.state=He.InSpecialComment}stateInSpecialComment(e){if(e===hi.Gt||this.fastForwardTo(hi.Gt))this.cbs.oncomment(this.sectionStart,this.index,0),this.state=He.Text,this.sectionStart=this.index+1}startEntity(){this.baseState=this.state,this.state=He.InEntity,this.entityStart=this.index,this.entityDecoder.startEntity(this.xmlMode?Lm.Strict:this.baseState===He.Text||this.baseState===He.InSpecialTag?Lm.Legacy:Lm.Attribute)}stateInEntity(){let e=this.index-this.offset,t=this.entityDecoder.write(this.buffer,e);if(t>=0){if(this.state=this.baseState,t===0)this.index-=1}else{if(e<this.buffer.length&&this.buffer.charCodeAt(e)===hi.Amp){this.state=this.baseState,this.index-=1;return}this.index=this.offset+this.buffer.length-1}}cleanup(){if(this.running&&this.sectionStart!==this.index){if(this.state===He.Text||this.state===He.InPlainText||this.state===He.InSpecialTag&&this.sequenceIndex===0)this.cbs.ontext(this.sectionStart,this.index),this.sectionStart=this.index;else if(this.state===He.InAttributeValueDq||this.state===He.InAttributeValueSq||this.state===He.InAttributeValueNq)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=this.index}}shouldContinue(){return this.index<this.buffer.length+this.offset&&this.running}parse(){while(this.shouldContinue()){let e=this.buffer.charCodeAt(this.index-this.offset);switch(this.state){case He.Text:{this.stateText(e);break}case He.InPlainText:{this.index=this.buffer.length+this.offset-1;break}case He.SpecialStartSequence:{this.stateSpecialStartSequence(e);break}case He.InSpecialTag:{this.stateInSpecialTag(e);break}case He.CDATASequence:{this.stateCDATASequence(e);break}case He.DeclarationSequence:{this.stateDeclarationSequence(e);break}case He.InAttributeValueDq:{this.stateInAttributeValueDoubleQuotes(e);break}case He.InAttributeName:{this.stateInAttributeName(e);break}case He.InCommentLike:{this.stateInCommentLike(e);break}case He.InSpecialComment:{this.stateInSpecialComment(e);break}case He.BeforeAttributeName:{this.stateBeforeAttributeName(e);break}case He.InTagName:{this.stateInTagName(e);break}case He.InClosingTagName:{this.stateInClosingTagName(e);break}case He.BeforeTagName:{this.stateBeforeTagName(e);break}case He.AfterAttributeName:{this.stateAfterAttributeName(e);break}case He.InAttributeValueSq:{this.stateInAttributeValueSingleQuotes(e);break}case He.BeforeAttributeValue:{this.stateBeforeAttributeValue(e);break}case He.BeforeClosingTagName:{this.stateBeforeClosingTagName(e);break}case He.AfterClosingTagName:{this.stateAfterClosingTagName(e);break}case He.InAttributeValueNq:{this.stateInAttributeValueNoQuotes(e);break}case He.InSelfClosingTag:{this.stateInSelfClosingTag(e);break}case He.InDeclaration:{this.stateInDeclaration(e);break}case He.BeforeDeclaration:{this.stateBeforeDeclaration(e);break}case He.BeforeComment:{this.stateBeforeComment(e);break}case He.InProcessingInstruction:{this.stateInProcessingInstruction(e);break}case He.InEntity:{this.stateInEntity();break}}this.index++}this.cleanup()}finish(){if(this.state===He.InEntity)this.entityDecoder.end(),this.state=this.baseState;this.handleTrailingData(),this.cbs.onend()}handleTrailingCommentLikeData(e){if(this.state!==He.InCommentLike)return!1;if(this.currentSequence===Xi.CdataEnd)if(this.xmlMode){if(this.sectionStart<e)this.cbs.oncdata(this.sectionStart,e,0)}else{let t=this.sectionStart-Xi.Cdata.length-1;this.cbs.oncomment(t,e,0)}else{let t=this.xmlMode?0:Math.min(this.sequenceIndex,Xi.CommentEnd.length-1);this.cbs.oncomment(this.sectionStart,e,t)}return!0}handleTrailingMarkupDeclaration(e){if(this.xmlMode)switch(this.state){case He.InSpecialComment:case He.BeforeComment:case He.CDATASequence:case He.DeclarationSequence:case He.InDeclaration:return this.cbs.ontext(this.sectionStart,e),!0;default:return!1}switch(this.state){case He.BeforeDeclaration:case He.InSpecialComment:case He.BeforeComment:case He.CDATASequence:return this.cbs.oncomment(this.sectionStart,e,0),!0;case He.DeclarationSequence:{if(this.sequenceIndex!==Xi.Doctype.length)this.cbs.oncomment(this.sectionStart,e,0);return!0}case He.InDeclaration:return!0;default:return!1}}handleTrailingData(){let e=this.buffer.length+this.offset;if(this.handleTrailingCommentLikeData(e)||this.handleTrailingMarkupDeclaration(e))return;if(this.sectionStart>=e)return;switch(this.state){case He.InTagName:case He.BeforeAttributeName:case He.BeforeAttributeValue:case He.AfterAttributeName:case He.InAttributeName:case He.InAttributeValueSq:case He.InAttributeValueDq:case He.InAttributeValueNq:case He.InClosingTagName:break;default:this.cbs.ontext(this.sectionStart,e)}}emitCodePoint(e,t){if(this.baseState!==He.Text&&this.baseState!==He.InSpecialTag){if(this.sectionStart<this.entityStart)this.cbs.onattribdata(this.sectionStart,this.entityStart);this.sectionStart=this.entityStart+t,this.index=this.sectionStart-1,this.cbs.onattribentity(e)}else{if(this.sectionStart<this.entityStart)this.cbs.ontext(this.sectionStart,this.entityStart);this.sectionStart=this.entityStart+t,this.index=this.sectionStart-1,this.cbs.ontextentity(e,this.sectionStart)}}}var hi,He,ap,Xi,UCi;var Lce=Ho(()=>{UNe();(function(e){e[e.Tab=9]="Tab",e[e.NewLine=10]="NewLine",e[e.FormFeed=12]="FormFeed",e[e.CarriageReturn=13]="CarriageReturn",e[e.Space=32]="Space",e[e.ExclamationMark=33]="ExclamationMark",e[e.Number=35]="Number",e[e.Amp=38]="Amp",e[e.SingleQuote=39]="SingleQuote",e[e.DoubleQuote=34]="DoubleQuote",e[e.Dash=45]="Dash",e[e.Slash=47]="Slash",e[e.Zero=48]="Zero",e[e.Nine=57]="Nine",e[e.Semi=59]="Semi",e[e.Lt=60]="Lt",e[e.Eq=61]="Eq",e[e.Gt=62]="Gt",e[e.Questionmark=63]="Questionmark",e[e.UpperA=65]="UpperA",e[e.LowerA=97]="LowerA",e[e.UpperF=70]="UpperF",e[e.LowerF=102]="LowerF",e[e.UpperZ=90]="UpperZ",e[e.LowerZ=122]="LowerZ",e[e.LowerX=120]="LowerX",e[e.OpeningSquareBracket=91]="OpeningSquareBracket"})(hi||(hi={}));(function(e){e[e.Text=1]="Text",e[e.BeforeTagName=2]="BeforeTagName",e[e.InTagName=3]="InTagName",e[e.InSelfClosingTag=4]="InSelfClosingTag",e[e.BeforeClosingTagName=5]="BeforeClosingTagName",e[e.InClosingTagName=6]="InClosingTagName",e[e.AfterClosingTagName=7]="AfterClosingTagName",e[e.BeforeAttributeName=8]="BeforeAttributeName",e[e.InAttributeName=9]="InAttributeName",e[e.AfterAttributeName=10]="AfterAttributeName",e[e.BeforeAttributeValue=11]="BeforeAttributeValue",e[e.InAttributeValueDq=12]="InAttributeValueDq",e[e.InAttributeValueSq=13]="InAttributeValueSq",e[e.InAttributeValueNq=14]="InAttributeValueNq",e[e.BeforeDeclaration=15]="BeforeDeclaration",e[e.InDeclaration=16]="InDeclaration",e[e.InProcessingInstruction=17]="InProcessingInstruction",e[e.BeforeComment=18]="BeforeComment",e[e.CDATASequence=19]="CDATASequence",e[e.DeclarationSequence=20]="DeclarationSequence",e[e.InSpecialComment=21]="InSpecialComment",e[e.InCommentLike=22]="InCommentLike",e[e.SpecialStartSequence=23]="SpecialStartSequence",e[e.InSpecialTag=24]="InSpecialTag",e[e.InPlainText=25]="InPlainText",e[e.InEntity=26]="InEntity"})(He||(He={}));(function(e){e[e.NoValue=0]="NoValue",e[e.Unquoted=1]="Unquoted",e[e.Single=2]="Single",e[e.Double=3]="Double"})(ap||(ap={}));Xi={Empty:new Uint8Array(0),Cdata:new Uint8Array([67,68,65,84,65,91]),CdataEnd:new Uint8Array([93,93,62]),CommentEnd:new Uint8Array([45,45,33,62]),Doctype:new Uint8Array([100,111,99,116,121,112,101]),IframeEnd:new Uint8Array([60,47,105,102,114,97,109,101]),NoembedEnd:new Uint8Array([60,47,110,111,101,109,98,101,100]),NoframesEnd:new Uint8Array([60,47,110,111,102,114,97,109,101,115]),Plaintext:new Uint8Array([60,47,112,108,97,105,110,116,101,120,116]),ScriptEnd:new Uint8Array([60,47,115,99,114,105,112,116]),StyleEnd:new Uint8Array([60,47,115,116,121,108,101]),TitleEnd:new Uint8Array([60,47,116,105,116,108,101]),TextareaEnd:new Uint8Array([60,47,116,101,120,116,97,114,101,97]),XmpEnd:new Uint8Array([60,47,120,109,112])},UCi=new Map([[Xi.IframeEnd[2],Xi.IframeEnd],[Xi.NoembedEnd[2],Xi.NoembedEnd],[Xi.Plaintext[2],Xi.Plaintext],[Xi.ScriptEnd[2],Xi.ScriptEnd],[Xi.TitleEnd[2],Xi.TitleEnd],[Xi.XmpEnd[2],Xi.XmpEnd]])});class H2{options;startIndex=0;endIndex=0;openTagStart=0;tagname="";attribname="";attribvalue="";attribs=null;stack=[];foreignContext;cbs;lowerCaseTagNames;lowerCaseAttributeNames;recognizeSelfClosing;htmlMode;tokenizer;buffers=[];bufferOffset=0;writeIndex=0;ended=!1;constructor(e,t={}){this.options=t,this.cbs=e??{},this.htmlMode=!this.options.xmlMode,this.lowerCaseTagNames=t.lowerCaseTags??this.htmlMode,this.lowerCaseAttributeNames=t.lowerCaseAttributeNames??this.htmlMode,this.recognizeSelfClosing=t.recognizeSelfClosing??!this.htmlMode,this.tokenizer=new(t.Tokenizer??q2)(this.options,this),this.foreignContext=[Jg.None],this.cbs.onparserinit?.(this)}ontext(e,t){let i=this.getSlice(e,t);this.endIndex=t-1,this.cbs.ontext?.(i),this.startIndex=t}ontextentity(e,t){this.endIndex=t-1,this.cbs.ontext?.(qNe(e)),this.startIndex=t}isInForeignContext(){return this.foreignContext[0]!==Jg.None}isVoidElement(e){return this.htmlMode&&$Ci.has(e)}readTagName(e,t){let i=this.lowerCaseTagNames?this.getSlice(e,t).toLowerCase():this.getSlice(e,t);if(!(this.lowerCaseTagNames&&this.htmlMode))return i;if(this.foreignContext[0]===Jg.Svg)return VNe.get(i)??i;if(this.foreignContext.length>1){let r=VNe.get(i);if(r!==void 0&&this.stack.includes(r))return r}if(!this.isInForeignContext())return i==="image"?"img":i;return i}onopentagname(e,t){this.endIndex=t,this.emitOpenTag(this.readTagName(e,t))}emitOpenTag(e){if(this.openTagStart=this.startIndex,this.tagname=e,this.htmlMode&&e==="form"&&this.stack.includes("form")){this.tagname="";return}let t=this.htmlMode&&qCi.get(e);if(t)while(this.stack.length>0&&t.has(this.stack[0]))this.popElement(!0);if(!this.isVoidElement(e)){if(this.stack.unshift(e),this.htmlMode){if(e==="svg")this.foreignContext.unshift(Jg.Svg);else if(e==="math")this.foreignContext.unshift(Jg.MathML);else if(ZNe.has(e))this.foreignContext.unshift(Jg.None)}}if(this.cbs.onopentagname?.(e),this.cbs.onopentag)this.attribs={}}endOpenTag(e){if(this.startIndex=this.openTagStart,this.attribs)this.cbs.onopentag?.(this.tagname,this.attribs,e),this.attribs=null;if(this.cbs.onclosetag&&this.isVoidElement(this.tagname))this.cbs.onclosetag(this.tagname,!0);this.tagname=""}onopentagend(e){this.endIndex=e,this.endOpenTag(!1),this.startIndex=e+1}onclosetag(e,t){this.endIndex=t;let i=this.readTagName(e,t);if(!this.isVoidElement(i)){let r=this.stack.indexOf(i);if(r!==-1){for(let n=0;n<r;n++)this.popElement(!0);this.popElement(!1)}else if(this.htmlMode&&i==="p")this.emitOpenTag("p"),this.closeCurrentTag(!0)}else if(this.htmlMode&&i==="br")this.cbs.onopentagname?.("br"),this.cbs.onopentag?.("br",{},!0),this.cbs.onclosetag?.("br",!1);this.startIndex=t+1}onselfclosingtag(e){if(this.endIndex=e,this.recognizeSelfClosing||this.isInForeignContext())this.closeCurrentTag(!1),this.startIndex=e+1;else this.onopentagend(e)}popElement(e){let t=this.stack.shift();if(this.htmlMode&&(GCi.has(t)||ZNe.has(t)))this.foreignContext.shift();this.cbs.onclosetag?.(t,e)}closeCurrentTag(e){let t=this.tagname;if(this.endOpenTag(e),this.stack[0]===t)this.popElement(!e)}onattribname(e,t){this.startIndex=e;let i=this.getSlice(e,t);this.attribname=this.lowerCaseAttributeNames?i.toLowerCase():i}onattribdata(e,t){this.attribvalue+=this.getSlice(e,t)}onattribentity(e){this.attribvalue+=qNe(e)}onattribend(e,t){if(this.endIndex=t,this.cbs.onattribute?.(this.attribname,this.attribvalue,e===ap.Double?'"':e===ap.Single?"'":e===ap.NoValue?void 0:null),this.attribs&&!Object.hasOwn(this.attribs,this.attribname))this.attribs[this.attribname]=this.attribvalue;this.attribvalue=""}getInstructionName(e){let t=e.search(HCi),i=t<0?e:e.substr(0,t);if(this.lowerCaseTagNames)i=i.toLowerCase();return i}ondeclaration(e,t){this.endIndex=t;let i=this.getSlice(e,t);if(this.cbs.onprocessinginstruction){let r=this.htmlMode?this.lowerCaseTagNames?WNe:i.slice(0,WNe.length):this.getInstructionName(i);this.cbs.onprocessinginstruction(`!${r}`,`!${i}`)}this.startIndex=t+1}onprocessinginstruction(e,t){this.endIndex=t;let i=this.getSlice(e,t);if(this.cbs.onprocessinginstruction){let r=this.getInstructionName(i);this.cbs.onprocessinginstruction(`?${r}`,`?${i}`)}this.startIndex=t+1}oncomment(e,t,i){this.endIndex=t,this.cbs.oncomment?.(this.getSlice(e,t-i)),this.cbs.oncommentend?.(),this.startIndex=t+1}oncdata(e,t,i){this.endIndex=t;let r=this.getSlice(e,t-i);if(!this.htmlMode||this.options.recognizeCDATA)this.cbs.oncdatastart?.(),this.cbs.ontext?.(r),this.cbs.oncdataend?.();else if(this.isInForeignContext())this.cbs.ontext?.(r);else this.cbs.oncomment?.(`[CDATA[${r}]]`),this.cbs.oncommentend?.();this.startIndex=t+1}onend(){if(this.cbs.onclosetag){this.endIndex=this.startIndex;for(let e=0;e<this.stack.length;e++)this.cbs.onclosetag(this.stack[e],!0)}this.cbs.onend?.()}reset(){this.cbs.onreset?.(),this.tokenizer.reset(),this.tagname="",this.attribname="",this.attribvalue="",this.attribs=null,this.stack.length=0,this.startIndex=0,this.endIndex=0,this.cbs.onparserinit?.(this),this.buffers.length=0,this.foreignContext.length=0,this.foreignContext.unshift(Jg.None),this.bufferOffset=0,this.writeIndex=0,this.ended=!1}parseComplete(e){this.reset(),this.end(e)}getSlice(e,t){if(e===t)return"";while(e-this.bufferOffset>=this.buffers[0].length)this.shiftBuffer();let i=this.buffers[0].slice(e-this.bufferOffset,t-this.bufferOffset);while(t-this.bufferOffset>this.buffers[0].length)this.shiftBuffer(),i+=this.buffers[0].slice(0,t-this.bufferOffset);return i}shiftBuffer(){this.bufferOffset+=this.buffers[0].length,this.writeIndex--,this.buffers.shift()}write(e){if(this.ended){this.cbs.onerror?.(Error(".write() after done!"));return}if(this.buffers.push(e),this.tokenizer.running)this.tokenizer.write(e),this.writeIndex++}end(e){if(this.ended){this.cbs.onerror?.(Error(".end() after done!"));return}if(e)this.write(e);this.ended=!0,this.tokenizer.end()}pause(){this.tokenizer.pause()}resume(){this.tokenizer.resume();while(this.tokenizer.running&&this.writeIndex<this.buffers.length)this.tokenizer.write(this.buffers[this.writeIndex++]);if(this.ended)this.tokenizer.end()}}var qNe,$2,As,G2,$Ne,GNe,HNe,qCi,WNe="doctype",$Ci,GCi,ZNe,VNe,Jg,HCi;var zce=Ho(()=>{Lce();({fromCodePoint:qNe}=String),$2=new Set(["input","option","optgroup","select","button","datalist","textarea"]),As=new Set(["p"]),G2=new Set(["h1","h2","h3","h4","h5","h6","p"]),$Ne=new Set(["thead","tbody"]),GNe=new Set(["dd","dt"]),HNe=new Set(["rt","rp"]),qCi=new Map([["tr",new Set(["tr","th","td"])],["th",new Set(["th"])],["td",new Set(["thead","th","td"])],["body",new Set(["head","link","script"])],["a",new Set(["a"])],["li",new Set(["li"])],["p",As],["h1",G2],["h2",G2],["h3",G2],["h4",G2],["h5",G2],["h6",G2],["select",$2],["input",$2],["output",$2],["button",$2],["datalist",$2],["textarea",$2],["option",new Set(["option"])],["optgroup",new Set(["optgroup","option"])],["dd",GNe],["dt",GNe],["address",As],["article",As],["aside",As],["blockquote",As],["details",As],["div",As],["dl",As],["fieldset",As],["figcaption",As],["figure",As],["footer",As],["form",As],["header",As],["hr",As],["main",As],["nav",As],["ol",As],["pre",As],["section",As],["table",As],["ul",As],["rt",HNe],["rp",HNe],["tbody",$Ne],["tfoot",$Ne]]),$Ci=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]),GCi=new Set(["math","svg"]),ZNe=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignObject","desc","title"]),VNe=new Map([["altglyph","altGlyph"],["altglyphdef","altGlyphDef"],["altglyphitem","altGlyphItem"],["animatecolor","animateColor"],["animatemotion","animateMotion"],["animatetransform","animateTransform"],["clippath","clipPath"],["feblend","feBlend"],["fecolormatrix","feColorMatrix"],["fecomponenttransfer","feComponentTransfer"],["fecomposite","feComposite"],["feconvolvematrix","feConvolveMatrix"],["fediffuselighting","feDiffuseLighting"],["fedisplacementmap","feDisplacementMap"],["fedistantlight","feDistantLight"],["fedropshadow","feDropShadow"],["feflood","feFlood"],["fefunca","feFuncA"],["fefuncb","feFuncB"],["fefuncg","feFuncG"],["fefuncr","feFuncR"],["fegaussianblur","feGaussianBlur"],["feimage","feImage"],["femerge","feMerge"],["femergenode","feMergeNode"],["femorphology","feMorphology"],["feoffset","feOffset"],["fepointlight","fePointLight"],["fespecularlighting","feSpecularLighting"],["fespotlight","feSpotLight"],["fetile","feTile"],["feturbulence","feTurbulence"],["foreignobject","foreignObject"],["glyphref","glyphRef"],["lineargradient","linearGradient"],["radialgradient","radialGradient"],["textpath","textPath"]]);(function(e){e[e.None=0]="None",e[e.Svg=1]="Svg",e[e.MathML=2]="MathML"})(Jg||(Jg={}));HCi=/\s|\//});var Yj={};Qg(Yj,{CDATA:()=>Vce,Comment:()=>Gce,Directive:()=>$ce,Doctype:()=>WCi,ElementType:()=>en,Root:()=>Uce,Script:()=>Hce,Style:()=>Wce,Tag:()=>Zce,Text:()=>qce,isTag:()=>jce});function jce(e){return e.type===en.Tag||e.type===en.Script||e.type===en.Style}var en,Uce,qce,$ce,Gce,Hce,Wce,Zce,Vce,WCi;var W2=Ho(()=>{(function(e){e.Root="root",e.Text="text",e.Directive="directive",e.Comment="comment",e.Script="script",e.Style="style",e.Tag="tag",e.CDATA="cdata",e.Doctype="doctype"})(en||(en={}));Uce=en.Root,qce=en.Text,$ce=en.Directive,Gce=en.Comment,Hce=en.Script,Wce=en.Style,Zce=en.Tag,Vce=en.CDATA,WCi=en.Doctype});class Yce{parent=null;prev=null;next=null;startIndex=null;endIndex=null;get parentNode(){return this.parent}set parentNode(e){this.parent=e}get previousSibling(){return this.prev}set previousSibling(e){this.prev=e}get nextSibling(){return this.next}set nextSibling(e){this.next=e}cloneNode(e=!1){return KNe(this,e)}}function El(e){return jce(e)}function rU(e){return e.type===en.CDATA}function rA(e){return e.type===en.Text}function Jce(e){return e.type===en.Comment}function ZCi(e){return e.type===en.Directive}function VCi(e){return e.type===en.Root}function sd(e){return Object.hasOwn(e,"children")}function KNe(e,t=!1){let i;if(rA(e))i=new KI(e.data);else if(Jce(e))i=new Qj(e.data);else if(El(e)){let r=t?Kce(e.children):[],n=new iU(e.name,{...e.attribs},r);for(let o of r)o.parent=n;if(e.namespace!=null)n.namespace=e.namespace;if(e["x-attribsNamespace"])n["x-attribsNamespace"]={...e["x-attribsNamespace"]};if(e["x-attribsPrefix"])n["x-attribsPrefix"]={...e["x-attribsPrefix"]};i=n}else if(rU(e)){let r=t?Kce(e.children):[],n=new tU(r);for(let o of r)o.parent=n;i=n}else if(VCi(e)){let r=t?Kce(e.children):[],n=new YI(r);for(let o of r)o.parent=n;if(e["x-mode"])n["x-mode"]=e["x-mode"];i=n}else if(ZCi(e)){let r=new Xj(e.name,e.data);if(e["x-name"]!=null)r["x-name"]=e["x-name"],r["x-publicId"]=e["x-publicId"],r["x-systemId"]=e["x-systemId"];i=r}else throw Error(`Not implemented yet: ${e.type}`);if(i.startIndex=e.startIndex,i.endIndex=e.endIndex,e.sourceCodeLocation!=null)i.sourceCodeLocation=e.sourceCodeLocation;return i}function Kce(e){let t=e.map((i)=>KNe(i,!0));for(let i=1;i<t.length;i++)t[i].prev=t[i-1],t[i-1].next=t[i];return t}var Jj,KI,Qj,Xj,eU,tU,YI,iU;var Qce=Ho(()=>{W2();Jj=class Jj extends Yce{data;constructor(e){super();this.data=e}get nodeValue(){return this.data}set nodeValue(e){this.data=e}};KI=class KI extends Jj{type=en.Text;get nodeType(){return 3}};Qj=class Qj extends Jj{type=en.Comment;get nodeType(){return 8}};Xj=class Xj extends Jj{type=en.Directive;name;constructor(e,t){super(t);this.name=e}get nodeType(){return 1}"x-name";"x-publicId";"x-systemId"};eU=class eU extends Yce{children;constructor(e){super();this.children=e}get firstChild(){return this.children[0]??null}get lastChild(){return this.children.length>0?this.children[this.children.length-1]:null}get childNodes(){return this.children}set childNodes(e){this.children=e}};tU=class tU extends eU{type=en.CDATA;get nodeType(){return 4}};YI=class YI extends eU{type=en.Root;get nodeType(){return 9}};iU=class iU extends eU{name;attribs;type;constructor(e,t,i=[],r=e==="script"?en.Script:e==="style"?en.Style:en.Tag){super(i);this.name=e,this.attribs=t,this.type=r}get nodeType(){return 1}get tagName(){return this.name}set tagName(e){this.name=e}get attributes(){return Object.keys(this.attribs).map((e)=>({name:e,value:this.attribs[e],namespace:this["x-attribsNamespace"]?.[e],prefix:this["x-attribsPrefix"]?.[e]}))}namespace;"x-attribsNamespace";"x-attribsPrefix"}});class Lw{dom=[];root=new YI(this.dom);callback;options;elementCB;done=!1;tagStack=[this.root];lastNode=null;parser=null;constructor(e,t,i){if(typeof t==="function")i=t,t=YNe;if(typeof e==="object")t=e,e=void 0;this.callback=e??null,this.options=t??YNe,this.elementCB=i??null}onparserinit(e){this.parser=e}onreset(){this.dom=[],this.root=new YI(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null}onend(){if(this.done)return;this.done=!0,this.parser=null,this.handleCallback(null)}onerror(e){this.handleCallback(e)}onclosetag(){this.lastNode=null;let e=this.tagStack.pop();if(this.options.withEndIndices&&this.parser)e.endIndex=this.parser.endIndex;if(this.elementCB)this.elementCB(e)}onopentag(e,t){let i=this.options.xmlMode?en.Tag:void 0,r=new iU(e,t,void 0,i);this.addNode(r),this.tagStack.push(r)}ontext(e){let{lastNode:t}=this;if(t&&t.type===en.Text){if(t.data+=e,this.options.withEndIndices&&this.parser)t.endIndex=this.parser.endIndex}else{let i=new KI(e);this.addNode(i),this.lastNode=i}}oncomment(e){if(this.lastNode&&this.lastNode.type===en.Comment){this.lastNode.data+=e;return}let t=new Qj(e);this.addNode(t),this.lastNode=t}oncommentend(){this.lastNode=null}oncdatastart(){let e=new KI(""),t=new tU([e]);this.addNode(t),e.parent=t,this.lastNode=e}oncdataend(){this.lastNode=null}onprocessinginstruction(e,t){let i=new Xj(e,t);this.addNode(i)}handleCallback(e){if(typeof this.callback==="function")this.callback(e,this.dom);else if(e)throw e}addNode(e){let t=this.tagStack[this.tagStack.length-1],i=t.children[t.children.length-1];if(this.options.withStartIndices&&this.parser)e.startIndex=this.parser.startIndex;if(this.options.withEndIndices&&this.parser)e.endIndex=this.parser.endIndex;if(t.children.push(e),i)e.prev=i,i.next=e;e.parent=t,this.lastNode=null}}var YNe;var nA=Ho(()=>{W2();Qce();Qce();YNe={withStartIndices:!1,withEndIndices:!1,xmlMode:!1}});function Z2(e,t,i=!0,r=Number.POSITIVE_INFINITY){return JNe(e,Array.isArray(t)?t:[t],i,r)}function JNe(e,t,i,r){let n=[],o=[Array.isArray(t)?t:[t]],s=[0];for(;;){if(s[0]>=o[0].length){if(s.length===1)return n;o.shift(),s.shift();continue}let a=o[0][s[0]++];if(e(a)){if(n.push(a),--r<=0)return n}if(i&&sd(a)&&a.children.length>0)s.unshift(0),o.unshift(a.children)}}function nU(e,t,i=!0){let r=Array.isArray(t)?t:[t];for(let n of r){if(El(n)&&e(n))return n;if(i&&sd(n)&&n.children.length>0){let o=nU(e,n.children,!0);if(o)return o}}return null}function QNe(e,t){return(Array.isArray(t)?t:[t]).some((i)=>El(i)&&e(i)||sd(i)&&QNe(e,i.children))}function KCi(e,t){let i=[],r=[Array.isArray(t)?t:[t]],n=[0];for(;;){if(n[0]>=r[0].length){if(r.length===1)return i;r.shift(),n.shift();continue}let o=r[0][n[0]++];if(El(o)&&e(o))i.push(o);if(sd(o)&&o.children.length>0)n.unshift(0),r.unshift(o.children)}}var Xce=Ho(()=>{nA()});function ele(e,t){if(typeof t==="function")return(i)=>El(i)&&t(i.attribs[e]);return(i)=>El(i)&&i.attribs[e]===t}function YCi(e,t){return(i)=>e(i)||t(i)}function XNe(e){let t=Object.keys(e).map((i)=>{let r=e[i];return Object.hasOwn(oU,i)?oU[i](r):ele(i,r)});return t.length===0?null:t.reduce(YCi)}function JCi(e,t){let i=XNe(e);return i?i(t):!0}function QCi(e,t,i,r=Number.POSITIVE_INFINITY){let n=XNe(e);return n?Z2(n,t,i,r):[]}function XCi(e,t,i=!0){if(!Array.isArray(t))t=[t];return nU(ele("id",e),t,i)}function zw(e,t,i=!0,r=Number.POSITIVE_INFINITY){return Z2(oU.tag_name(e),t,i,r)}function eDi(e,t,i=!0,r=Number.POSITIVE_INFINITY){return Z2(ele("class",e),t,i,r)}function tDi(e,t,i=!0,r=Number.POSITIVE_INFINITY){return Z2(oU.tag_type(e),t,i,r)}var oU;var tle=Ho(()=>{nA();Xce();oU={tag_name(e){if(typeof e==="function")return(t)=>El(t)&&e(t.name);if(e==="*")return El;return(t)=>El(t)&&t.name===e},tag_type(e){if(typeof e==="function")return(t)=>e(t.type);return(t)=>t.type===e},tag_contains(e){if(typeof e==="function")return(t)=>rA(t)&&e(t.data);return(t)=>rA(t)&&t.data===e}}});function tLe(e){return e===34?"&quot;":e===38?"&amp;":e===39?"&apos;":e===60?"&lt;":e===62?"&gt;":"&nbsp;"}function eLe(e){return e>=128||e>=32&&e<64&&(iDi>>>e&1)===1}function sU(e){let{length:t}=e,i,r=0,n=0;while(n<t){let o=e.charCodeAt(n);if(!eLe(o)){let a=Math.min(n+32,t),c=n+1;while(c<a&&!eLe(e.charCodeAt(c)))c++;if(c<a){n=c;continue}if(c>=t)break;if(ile.lastIndex=c,!ile.test(e))break;n=ile.lastIndex-1;continue}if(i===void 0)i=e.substring(0,n);else if(r!==n)i+=e.substring(r,n);if(o<64){i+=tLe(o),r=n+=1;continue}let s=e.codePointAt(n);if(i+=`&#x${s.toString(16)};`,s!==o)n++;r=n+=1}if(i===void 0)return e;if(r<t)i+=e.substr(r);return i}function iLe(e,t){if(e.lastIndex=0,!e.test(t))return t;let i="",r=0;do{let n=e.lastIndex-1;if(r!==n)i+=t.substring(r,n);let o=t.charCodeAt(n);i+=tLe(o),r=n+1}while(e.test(t));return i+t.substring(r)}function rle(e){return iLe(rDi,e)}function nle(e){return iLe(nDi,e)}var iDi=1342177476,ile,rDi,nDi;var rLe=Ho(()=>{ile=/["&'<>\u0080-\uFFFF]/g;rDi=/["&\u{A0}]/gu;nDi=/[&<>\u{A0}]/gu});var nLe,oLe;var sLe=Ho(()=>{rLe();(function(e){e[e.XML=0]="XML",e[e.HTML=1]="HTML"})(nLe||(nLe={}));(function(e){e[e.UTF8=0]="UTF8",e[e.ASCII=1]="ASCII",e[e.Extensive=2]="Extensive",e[e.Attribute=3]="Attribute",e[e.Text=4]="Text"})(oLe||(oLe={}))});var aLe,cLe;var lLe=Ho(()=>{aLe=new Map("altGlyph altGlyphDef altGlyphItem animateColor animateMotion animateTransform clipPath feBlend feColorMatrix feComponentTransfer feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feDropShadow feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feImage feMerge feMergeNode feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile feTurbulence foreignObject glyphRef linearGradient radialGradient textPath".split(" ").map((e)=>[e.toLowerCase(),e])),cLe=new Map("definitionURL attributeName attributeType baseFrequency baseProfile calcMode clipPathUnits diffuseConstant edgeMode filterUnits glyphRef gradientTransform gradientUnits kernelMatrix kernelUnitLength keyPoints keySplines keyTimes lengthAdjust limitingConeAngle markerHeight markerUnits markerWidth maskContentUnits maskUnits numOctaves pathLength patternContentUnits patternTransform patternUnits pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits refX refY repeatCount repeatDur requiredExtensions requiredFeatures specularConstant specularExponent spreadMethod startOffset stdDeviation stitchTiles surfaceScale systemLanguage tableValues targetX targetY textLength viewBox viewTarget xChannelSelector yChannelSelector zoomAndPan".split(" ").map((e)=>[e.toLowerCase(),e]))});function lDi(e,t={}){let i="length"in e?e:[e],r=t.xmlMode??!1,n="";for(let o=0;o<i.length;o++)n+=dLe(i[o],t,r);return n}function uLe(e,t,i){let r="";for(let n=0;n<e.length;n++)r+=dLe(e[n],t,i);return r}function dLe(e,t,i){switch(e.type){case Uce:return uLe(e.children,t,i);case $ce:return`<${e.data}>`;case Gce:return`<!--${e.data}-->`;case Vce:return`<![CDATA[${e.children[0].data}]]>`;case Hce:case Wce:case Zce:return uDi(e,t,i);case qce:{let r=e,n=r.data||"";if((t.encodeEntities??t.decodeEntities)!==!1&&!(!i&&r.parent&&oDi.has(r.parent.name)))return i||t.encodeEntities!=="utf8"?sU(n):nle(n);return n}}}function uDi(e,t,i){if(i==="foreign"){if(e.name=aLe.get(e.name)??e.name,e.parent&&cDi.has(e.parent.name))i=!1}if(!i&&aDi.has(e.name))i="foreign";let{name:r,children:n}=e,o=!i&&sDi.has(r),s=`<${r}${pDi(e.attribs,t,i)}`;if(n.length===0&&(i?t.selfClosingTags!==!1:t.selfClosingTags&&o))s+=i?"/>":" />";else{if(s+=">",n.length>0)s+=uLe(n,t,i);if(!o)s+=`</${r}>`}return s}function dDi(e){return e.replaceAll('"',"&quot;")}function pDi(e,t,i){if(!e)return"";let r=(t.encodeEntities??t.decodeEntities)===!1?dDi:i||t.encodeEntities!=="utf8"?sU:rle,n=i==="foreign",o=!!(t.emptyAttrs??i),s="";for(let a in e){if(!Object.hasOwn(e,a))continue;let c=e[a],u=n?cLe.get(a)??a:a;s+=!o&&(c==null||c==="")?` ${u}`:` ${u}="${r(c==null?"":String(c))}"`}return s}var oDi,sDi,aDi,cDi,pLe;var mLe=Ho(()=>{W2();sLe();lLe();oDi=new Set("style script xmp iframe noembed noframes plaintext noscript".split(" ")),sDi=new Set("area base basefont br col command embed frame hr img input isindex keygen link meta param source track wbr".split(" ")),aDi=new Set(["svg","math"]),cDi=new Set("mi mo mn ms mtext annotation-xml foreignObject desc title".split(" "));pLe=lDi});function hLe(e,t){return pLe(e,t)}function mDi(e,t){return sd(e)?e.children.map((i)=>hLe(i,t)).join(""):""}function aU(e){if(Array.isArray(e))return e.map(aU).join("");if(El(e))return e.name==="br"?`
3
3
  `:aU(e.children);if(rU(e))return aU(e.children);if(rA(e))return e.data;return""}function JI(e){if(Array.isArray(e))return e.map(JI).join("");if(sd(e)&&!Jce(e))return JI(e.children);if(rA(e))return e.data;return""}function ole(e){if(Array.isArray(e))return e.map(ole).join("");if(sd(e)&&(e.type===en.Tag||rU(e)))return ole(e.children);if(rA(e))return e.data;return""}var sle=Ho(()=>{mLe();W2();nA()});function QI(e){let t=cU(yDi,e);return t?t.name==="feed"?hDi(t):fDi(t):null}function hDi(e){let t=e.children,i={type:"atom",items:zw("entry",t).map((o)=>{let{children:s}=o,a={media:fLe(s)};ad(a,"id","id",s),ad(a,"title","title",s);let c=cU("link",s)?.attribs.href;if(c)a.link=c;let u=oA("summary",s)||oA("content",s);if(u)a.description=u;let d=oA("updated",s);if(d)a.pubDate=new Date(d);return a})};ad(i,"id","id",t),ad(i,"title","title",t);let r=cU("link",t)?.attribs.href;if(r)i.link=r;ad(i,"description","subtitle",t);let n=oA("updated",t);if(n)i.updated=new Date(n);return ad(i,"author","email",t,!0),i}function fDi(e){let t=cU("channel",e.children)?.children??[],i={type:e.name.substr(0,3),id:"",items:zw("item",e.children).map((n)=>{let{children:o}=n,s={media:fLe(o)};ad(s,"id","guid",o),ad(s,"title","title",o),ad(s,"link","link",o),ad(s,"description","description",o);let a=oA("pubDate",o)||oA("dc:date",o);if(a)s.pubDate=new Date(a);return s})};ad(i,"title","title",t),ad(i,"link","link",t),ad(i,"description","description",t);let r=oA("lastBuildDate",t);if(r)i.updated=new Date(r);return ad(i,"author","managingEditor",t,!0),i}function fLe(e){return zw("media:content",e).map((t)=>{let{attribs:i}=t,r={medium:i.medium,isDefault:!!i.isDefault};for(let n of xDi)if(i[n])r[n]=i[n];for(let n of gDi)if(i[n])r[n]=Number.parseInt(i[n],10);if(i.expression)r.expression=i.expression;return r})}function cU(e,t){return zw(e,t,!0,1)[0]}function oA(e,t,i=!1){return JI(zw(e,t,i,1)).trim()}function ad(e,t,i,r,n=!1){let o=oA(i,r,n);if(o)e[t]=o}function yDi(e){return e==="rss"||e==="feed"||e==="rdf:RDF"}var xDi,gDi;var xLe=Ho(()=>{tle();sle();xDi=["url","type","lang"],gDi=["fileSize","bitrate","framerate","samplingrate","channels","duration","height","width"]});function bDi(e){let t=e.length;while(--t>=0){let i=e[t];if(t>0&&e.lastIndexOf(i,t-1)>=0){e.splice(t,1);continue}for(let r=i.parent;r;r=r.parent)if(e.includes(r)){e.splice(t,1);break}}return e}function gLe(e,t){let i=[],r=[];if(e===t)return 0;let n=sd(e)?e:e.parent;while(n)i.unshift(n),n=n.parent;n=sd(t)?t:t.parent;while(n)r.unshift(n),n=n.parent;let o=Math.min(i.length,r.length),s=0;while(s<o&&i[s]===r[s])s++;if(s===0)return g0.DISCONNECTED;let a=i[s-1],c=a.children,u=i[s],d=r[s];if(c.indexOf(u)>c.indexOf(d)){if(a===t)return g0.FOLLOWING|g0.CONTAINED_BY;return g0.FOLLOWING}if(a===e)return g0.PRECEDING|g0.CONTAINS;return g0.PRECEDING}function EDi(e){return e=e.filter((t,i,r)=>!r.includes(t,i+1)),e.sort((t,i)=>{let r=gLe(t,i);if(r&g0.PRECEDING)return-1;if(r&g0.FOLLOWING)return 1;return 0}),e}var g0;var yLe=Ho(()=>{nA();(function(e){e[e.DISCONNECTED=1]="DISCONNECTED",e[e.PRECEDING=2]="PRECEDING",e[e.FOLLOWING=4]="FOLLOWING",e[e.CONTAINS=8]="CONTAINS",e[e.CONTAINED_BY=16]="CONTAINED_BY"})(g0||(g0={}))});function XI(e){if(e.prev)e.prev.next=e.next;if(e.next)e.next.prev=e.prev;if(e.parent){let t=e.parent.children,i=t.lastIndexOf(e);if(i!==-1)t.splice(i,1)}e.next=null,e.prev=null,e.parent=null}function ADi(e,t){if(t.prev=e.prev,t.prev)t.prev.next=t;if(t.next=e.next,t.next)t.next.prev=t;if(t.parent=e.parent,t.parent){let{children:i}=t.parent,r=i.lastIndexOf(e);if(r===-1)return;i[r]=t,e.parent=null}}function vDi(e,t){if(XI(t),t.next=null,t.parent=e,e.children.push(t)>1){let i=e.children[e.children.length-2];i.next=t,t.prev=i}else t.prev=null}function wDi(e,t){XI(t);let{parent:i}=e,r=e.next;if(t.next=r,t.prev=e,e.next=t,t.parent=i,r){if(r.prev=t,i){let n=i.children;n.splice(n.lastIndexOf(r),0,t)}}else if(i)i.children.push(t)}function SDi(e,t){if(XI(t),t.parent=e,t.prev=null,e.children.unshift(t)===1)t.next=null;else{let i=e.children[1];i.prev=t,t.next=i}}function kDi(e,t){XI(t);let{parent:i}=e;if(i){let r=i.children;r.splice(r.indexOf(e),0,t)}if(e.prev)e.prev.next=t;t.parent=i,t.prev=e.prev,t.next=e,e.prev=t}var bLe=()=>{};function ELe(e){return sd(e)?e.children:[]}function ALe(e){return e.parent||null}function BDi(e){let t=ALe(e);if(t!=null)return ELe(t);let i=[e],{prev:r,next:n}=e;while(r!=null)i.unshift(r),{prev:r}=r;while(n!=null)i.push(n),{next:n}=n;return i}function CDi(e,t){let{attribs:i}=e;return i?.[t]}function DDi(e,t){let{attribs:i}=e;return i!=null&&Object.hasOwn(i,t)&&i[t]!=null}function IDi(e){return e.name}function _Di(e){let{next:t}=e;while(t!==null&&!El(t))({next:t}=t);return t}function TDi(e){let{prev:t}=e;while(t!==null&&!El(t))({prev:t}=t);return t}var vLe=Ho(()=>{nA()});var ale={};Qg(ale,{DocumentPosition:()=>g0,append:()=>wDi,appendChild:()=>vDi,compareDocumentPosition:()=>gLe,existsOne:()=>QNe,filter:()=>Z2,find:()=>JNe,findAll:()=>KCi,findOne:()=>nU,getAttributeValue:()=>CDi,getChildren:()=>ELe,getElementById:()=>XCi,getElements:()=>QCi,getElementsByClassName:()=>eDi,getElementsByTagName:()=>zw,getElementsByTagType:()=>tDi,getFeed:()=>QI,getInnerHTML:()=>mDi,getName:()=>IDi,getOuterHTML:()=>hLe,getParent:()=>ALe,getSiblings:()=>BDi,getText:()=>aU,hasAttrib:()=>DDi,innerText:()=>ole,nextElementSibling:()=>_Di,prepend:()=>kDi,prependChild:()=>SDi,prevElementSibling:()=>TDi,removeElement:()=>XI,removeSubsets:()=>bDi,replaceElement:()=>ADi,testElement:()=>JCi,textContent:()=>JI,uniqueSort:()=>EDi});var lU=Ho(()=>{xLe();yLe();tle();bLe();Xce();sle();vLe()});var SLe={};Qg(SLe,{DefaultHandler:()=>Lw,DomHandler:()=>Lw,DomUtils:()=>ale,ElementType:()=>Yj,Parser:()=>H2,QuoteType:()=>ap,Tokenizer:()=>q2,createDocumentStream:()=>PDi,getFeed:()=>QI,parseDocument:()=>wLe,parseFeed:()=>FDi});function wLe(e,t){let i=new Lw(void 0,t);return new H2(i,t).end(e),i.root}function PDi(e,t,i){let r=new Lw((n)=>e(n,r.root),t,i);return new H2(r,t)}function FDi(e,t=RDi){return QI(wLe(e,t).children)}var RDi;var kLe=Ho(()=>{zce();zce();nA();nA();W2();Lce();lU();lU();lU();RDi={xmlMode:!0}});var CLe=E(function(seo,BLe){BLe.exports=(e)=>{if(typeof e!=="string")throw TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}});var ILe=E(function(ODi){/*!
4
4
  * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
5
5
  *
@@ -1021,7 +1021,7 @@ ${mE(e.cont)}`}}function D4n(e,t){return t.map((i,r,{length:n})=>I4n(e,i,r===n-1
1021
1021
  `).find((b)=>b.startsWith("data: "));if(!d)continue;let p;try{let b=GBi.safeParse(JSON.parse(d.slice(6)));if(!b.success)continue;p=b.data}catch{return await qse(r),{success:!1,error:"Malformed SSE event from remote agent"}}let m=p.result;if(m?.kind==="artifact-update"&&m.artifact)a.push(m.artifact);if(!m?.final)continue;await qse(r);let h=m.status,f=h?.state??"unknown",y=(h?.message?.parts??[]).filter((b)=>b.kind==="text"&&typeof b.text==="string").map((b)=>b.text).join(`
1022
1022
  `)||"No response text";return{success:!0,data:{state:f,response:y,sources:qBi(a)}}}s=await YMe(r,t,i)}return{success:!1,error:"Stream ended without a terminal event"}}class Gse extends Error{timeoutMs;constructor(e){super(`request timed out after ${e}ms`);this.timeoutMs=e,this.name="A2ARequestTimeoutError"}}class xI extends Error{timeoutMs;constructor(e){super(`A2A stream stalled waiting for final event after ${e}ms`);this.timeoutMs=e,this.name="A2AStreamIdleTimeoutError"}}async function QBi(e,t,i,r,n){return jse((o)=>e(t,{...i,signal:o}),{timeoutMs:r,onTimeout:()=>new Gse(r),signal:n})}async function YMe(e,t,i){try{return await jse(()=>e.read(),{timeoutMs:t,onTimeout:()=>new xI(t),signal:i})}catch(r){if(r instanceof xI||i?.aborted)await qse(e,r);throw r}}async function qse(e,t){try{await e.cancel(t)}catch{}}function XBi(e){if(e instanceof Gse||e instanceof xI)return!1;return e instanceof Error}function Use(e,t){let i=t>1?` after ${t} attempts`:"";if(e instanceof xI)return`${e.message}${i}`;let r=Ee(e,"Unknown network error");return`Failed to reach remote agent${i}: ${r}`}async function vj(e,t={},i={}){let r=t.fetch??globalThis.fetch,n=i.signal;n?.throwIfAborted();let o={requestTimeoutMs:t.requestTimeoutMs??HBi,streamIdleTimeoutMs:t.streamIdleTimeoutMs??WBi,maxNetworkAttempts:t.maxNetworkAttempts??ZBi},s=YBi(e.agent),a=Xr(i.userPermissionLevel);if(!s.ok){let p=t.entityService?await ZMe(t.entityService,e.agent,a):void 0;if(typeof p==="string")return{success:!1,error:p};if(!p)return{success:!1,error:s.error}}if(!t.entityService)return{success:!1,error:"Agent directory is unavailable. Add the agent first, then try again."};let c=s.ok?s.agentId:e.agent.trim(),u=s.ok?await t.entityService.getEntity({entityType:"agent",id:c,visibilityScope:a}):null;if(n?.throwIfAborted(),!u&&!VMe(c)){let p=await ZMe(t.entityService,e.agent,a);if(n?.throwIfAborted(),typeof p==="string")return{success:!1,error:p};if(p)u=p,c=p.id}if(!u){if(i.requireSaved)return{success:!1,error:`Agent ${c} is not saved or approved.`,code:"agent_not_saved"};if(!VMe(c))return{success:!1,error:`Agent ${e.agent} is not an exact domain-like id and is not saved. Connect or clarify the agent first.`,code:"agent_not_saved"};let p=await wf(c,{fetch:r,timeoutMs:o.requestTimeoutMs,signal:n});if(!p.ok){if(qE(p.reason))return{success:!1,error:p.error};return{success:!1,error:`Could not verify an A2A Agent Card for ${c}. Connect/save it first if you want to add it to the directory.`,code:"agent_card_unavailable"}}let m=await KMe(p.card.url,e.message,r,t.requestSigner,o,n);if("success"in m&&m.success===!0){let h=typeof m.data==="object"&&m.data!==null?m.data:{};return{...m,data:{...h,agentCall:{mode:"one-shot",agent:c},agentContactCandidate:{source:{kind:"url",url:(s.ok?s.sourceUrl:void 0)??c}}}}}return m}if(u.metadata.status==="archived")return{success:!1,error:`Agent ${c} is archived and cannot be contacted until it is restored and approved.`,code:"agent_archived"};if(u.metadata.status!=="approved")return{success:!1,error:`Agent ${c} is discovered but not approved yet. Approve it first.`,code:"agent_not_approved"};let d=await wf(c,{fetch:r,timeoutMs:o.requestTimeoutMs,signal:n});if(!d.ok){if(qE(d.reason))return{success:!1,error:d.error};return{success:!1,error:`Could not fetch Agent Card from https://${c}`}}return KMe(d.card.url,e.message,r,t.requestSigner,o,n)}function QMe(e={}){return{name:"agent_call",description:"Call a remote A2A agent by exact domain-like target, saved local agent id, or the name of a saved contact as the user calls it, such as Yeehaa. A domain-like id is bare text with a dot and no slash/protocol, such as partner-brain.example or save-it-regression.example; .example test domains are exact domain-like ids. When the user asks to ask, message, talk to, or contact that id, asks what it has to say, or asks that agent for its skills/capabilities, call this tool directly in the same turn with no system_list/system_get preflight: the tool reports structured errors such as invalid Agent Card, not approved, or archived. Do not stop after listing the agent, drafting the question, searching local content, or reading its saved entity. If the user provides an HTTPS URL such as https://docs.example/a2a, pass only the hostname docs.example. Never pass a full URL, a brain's display name like Brain, or a non-HTTPS URL; for a non-HTTPS URL, ask for the HTTPS agent URL or exact id instead. For saved agents, the tool enforces approved/not-archived status before network contact; a discovered but not approved agent must be approved first, so do not call it. For unsaved exact domains, the tool verifies the A2A Agent Card over HTTPS and may perform a one-shot call without saving; after success you may offer to save/connect it, but never auto-save. Answer from the agent's response without supplementing it with reads of the agent entity unless the user asks for its directory/profile details, and never save the user's question as a note in the same turn. If the call fails (auth, network, an invalid or unverifiable Agent Card, an unavailable agent), report that failure directly: do not say the agent was saved or connected, do not answer from memory, local docs, or general knowledge, and do not create a wish, reminder, todo, note, or other entity; you may offer to add the contact using the word add. Each new turn that asks the same id something, including short follow-ups like 'tell me more' and even after a refusal or error, needs its own fresh call with that same id. If a name matches several saved agents, ask a concise clarification naming their ids and end the turn without calling; never choose the first match.",inputSchema:VBi,visibility:"trusted",sideEffects:"external",handler:async(t,i)=>{let r=KBi.safeParse(t);if(!r.success)return{success:!1,error:`Invalid input: ${r.error.message}`};return vj(r.data,e,{userPermissionLevel:i.userPermissionLevel,...i.signal?{signal:i.signal}:{}})}}}var e4i=new Set(["agent_not_saved","agent_not_approved","agent_archived"]);function XMe(e,t){let i="code"in e&&e4i.has(e.code??"")?"permission_denied":"handler_failed",r="error"in e?e.error:t;return new Ni(i,{publicMessage:_2(r)})}function t4i(e){return[e,"","Asked on behalf of a visitor to another brain's site. Answer briefly, from your own public content, and cite what you draw on."].join(`
1023
1023
  `)}function eOe(e,t,i={networkAskTimeoutMs:30000}){e.answer(wj,async({request:{agent:r,question:n}})=>{let o=i.networkAskTimeoutMs,s=AbortSignal.timeout(o),a=(d)=>new Ni("deadline_exceeded",{publicMessage:`${r} did not answer within ${o} ms`,cause:d}),c;try{c=await vj({agent:r,message:t4i(n)},{...t,maxNetworkAttempts:1},{requireSaved:!0,signal:s})}catch(d){if(s.aborted)throw a(d);throw new Ni("handler_failed",{message:Ee(d,`${r} did not answer`),publicMessage:`${r} did not answer`,cause:d})}if(s.aborted)throw a();if(!("success"in c)||c.success!==!0)throw XMe(c,`${r} did not answer`);let u=Hse.safeParse(c.data);if(!u.success)throw new Ni("handler_failed",{publicMessage:`${r} gave no readable answer`});if(u.data.state!=="completed")throw new Ni("handler_failed",{publicMessage:_2(`${r} did not answer: ${u.data.response}`)});return u.data}),e.answer(Sj,async({request:{agent:r,instruction:n,selection:o,userPermissionLevel:s}})=>{let a=await vj({agent:r,message:["A Studio author is asking about selected markdown.",`Instruction: ${n}`,"","Selected markdown:",o].join(`
1024
- `)},t,{requireSaved:!0,userPermissionLevel:s});if(!("success"in a)||a.success!==!0)throw XMe(a,"Agent call failed");let c=Hse.safeParse(a.data);if(!c.success)throw new Ni("handler_failed",{publicMessage:"Invalid response from agent"});return c.data}),e.answer(kj,async({request:{userPermissionLevel:r}})=>{if(!e.entityReads.hasEntityType("agent"))return{agents:[]};return{agents:(await e.entityReads.listEntities({entityType:"agent",options:{filter:{visibilityScope:Xr(r)}}})).filter((s)=>s.metadata.status==="approved").map((s)=>{let a=s.metadata.name;return{id:s.id,label:typeof a==="string"&&a.length>0?a:s.id}}).sort((s,a)=>s.label.localeCompare(a.label))}})}var tOe={name:"@brains/a2a",license:"AGPL-3.0-only",version:"0.2.0-alpha.698",dependencies:{"@a2a-js/sdk":"^0.3.13","@brains/contracts":"workspace:*","@brains/http-signatures":"workspace:*","@brains/sdk":"workspace:*","@brains/utils":"workspace:*",hono:"^4.13.13"},devDependencies:{"@brains/auth-service":"workspace:*","@brains/entity-service":"workspace:*","@brains/eslint-config":"workspace:*","@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},files:["src"],main:"./src/index.ts",module:"./src/index.ts",private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"};var r4i={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Signature, Signature-Input, Content-Digest, Date","X-Content-Type-Options":"nosniff"};function c0(e){let t=new Headers(e.headers);for(let[i,r]of Object.entries(r4i))t.set(i,r);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}function n4i(e){let t=e.auth();if(!t)return;let i=t.getIssuer();if(kf(i)||new URL(i).protocol!=="https:")return;return async(r)=>{let n=await t.getA2ASigningKey();await wMe(r,n.privateJwk,n.keyId)}}function iOe(e,t,i){let r=n4i(e);return{...r?{requestSigner:r}:{},...i.fetch?{fetch:i.fetch}:{},requestTimeoutMs:t.requestTimeoutMs,streamIdleTimeoutMs:t.streamIdleTimeoutMs,maxNetworkAttempts:t.maxNetworkAttempts,entityService:e.entityReads}}async function o4i(e,t,i){if(!i.cardReady)return;return FMe({character:e.identity.get(),profile:e.identity.getProfile(),version:tOe.version,...e.domain?{domain:e.domain}:{},...t.organization?{organization:t.organization}:{},profileKind:e.profileKinds.getResolved(),tools:e.tools.listForPermissionLevel("public"),skills:await e.publicSkills.list(),authEnabled:!1})}async function s4i(e,t,i,r){let n=new URL(i.url),o=new URL(`${n.pathname}${n.search}`,u0(i)),s=await SMe({method:i.method,url:o.toString(),headers:i.headers,body:r},t.jwksResolver);if(s){let a=await e.auth()?.getA2APeerTrust(s.domain);return{permissionLevel:a?.keyFingerprint===s.keyFingerprint?a.grantedLevel:"public",isAnchor:e.permissions.isAnchor("a2a",s.domain),callerDomain:s.domain}}return{permissionLevel:"public",isAnchor:!1,callerDomain:null}}function a4i(e,t,i){let r=new rOe,n=e.agent;return r.get("/.well-known/agent-card.json",async(o)=>{let s=await o4i(e,t,i);if(!s)return c0(o.json({error:"Agent Card not ready"},503));return c0(o.json(s))}),r.get("/.well-known/agent-directory.json",async(o)=>{let s=await MMe(e.entityReads);return c0(o.json(s))}),r.get("/a2a",(o)=>c0(o.json({error:"Use POST with JSON-RPC 2.0 requests.",agentCard:"/.well-known/agent-card.json"},405))),r.options("/a2a",()=>c0(new Response(null,{status:204}))),r.post("/a2a",async(o)=>{let s=await o.req.text(),a;try{a=await s4i(e,i,o.req.raw,s)}catch{return c0(o.json({error:"Invalid HTTP signature"},401))}let c;try{c=JSON.parse(s)}catch{return c0(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}))}let u=LMe.safeParse(c);if(!u.success)return c0(o.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid request"},id:null}));if(u.data.method==="message/stream"){let p=GMe.safeParse(u.data.params??{});if(!p.success)return c0(o.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${p.error.message}`},id:u.data.id}));let m=HMe(u.data.id,p.data.message,{taskManager:i.taskManager,turnSupervisor:i.turnSupervisor,agentService:n,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:i.publicAsks});if("error"in m)return c0(o.json(m));return c0(new Response(m.stream,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let d=await UMe(u.data,{taskManager:i.taskManager,turnSupervisor:i.turnSupervisor,agentService:n,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:i.publicAsks});return c0(o.json(d))}),r}function Wse(e={}){let t=l0({id:"a2a",config:PMe,setup:(n)=>{let{config:o}=n,s=Xo(n),{servesHttp:a}=s,c=iOe(s,o,e),u={cardReady:!1,servesHttp:a,taskManager:new Lse,turnSupervisor:new zse,jwksResolver:new Fse(e.fetch?{fetch:e.fetch}:{}),clientDeps:c,publicAsks:new Nse(o.publicAsks,s.classRuntimeState)};if(eOe(s,c,{networkAskTimeoutMs:o.networkAskTimeoutMs}),a)s.endpoint({label:"A2A",url:"/a2a",priority:25}),s.interaction({id:"a2a",label:"A2A",description:"Let other agents discover and talk to this brain.",href:"/a2a",kind:"agent",priority:25}),s.logger.info("A2A interface registered",{domain:s.domain});else s.logger.info("A2A interface registered in tool-only mode",{domain:s.domain});return s.ready(()=>{u.cardReady=!0}),u}}),i=_c(t,(n)=>{let{config:o,state:s}=n;if(!s.servesHttp)return[];let a=Xo(n),c=a4i(a,o,s),u=(p)=>Promise.resolve(c.fetch(p)),d=(p,m)=>({path:p,method:m,public:!0,handler:u});return[d("/.well-known/agent-card.json","GET"),d("/.well-known/agent-directory.json","GET"),d("/a2a","GET"),d("/a2a","POST"),d("/a2a","OPTIONS")]}),r=Sf(i,(n)=>{let{state:o}=n,{logger:s}=Xo(n);return{id:"a2a",start:async()=>{if(o.servesHttp)s.info("A2A mounted on shared webserver host");else s.info("A2A running without webserver routes")},stop:async()=>{await o.turnSupervisor.close(),s.info("A2A server stopped")}}});return Co(r,(n)=>{let{config:o}=n,s=Xo(n),a=()=>QMe(iOe(s,o,e));return[{...a(),handler:(c,u)=>a().handler(c,u)}]})}var c4i=Wse(),nOe=c4i;function p0(e){if(typeof e!=="string"||!/^\d+$/u.test(e))return e;return Number(e)}function WE(e,t){return{registration:e,actionIds:t.map((i)=>i.name)}}var l4i=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"});function m0(e){return l4i.format(new Date(e))}function h0(e){let t=e.auth();if(!t)throw Error("Administration workspace requires auth-service");return t}function Qa(e){if(!e)throw Error("Administration action requires a signed-in actor");return{actorUserId:e.actor.id}}function Ij(e){return e.flatMap((t)=>t.status==="invited"?[]:[{userId:t.userId,displayName:t.displayName}])}function _w(e){if(!e)return"This brain";let t="did:web:";if(!e.startsWith(t))return e;let i=e.slice(t.length);if(i.length===0)return e;return i.split(":").map(decodeURIComponent).join("/")}var u4i={"auth.a2a_peer_trust.granted":"Trusted an A2A peer","auth.a2a_peer_trust.revoked":"Revoked A2A peer trust","auth.access.reinitialized":"Reinitialized access from configuration","auth.external_peer.invited":"Invited a person from an external peer","auth.external_peer.linked":"Linked an external peer","auth.external_peer.unlinked":"Unlinked an external peer","auth.invitation.created":"Person invited","auth.invitation.cancelled":"Invitation cancelled","auth.invitation.manual_delivery_confirmed":"Manual delivery confirmed","auth.invitation.resent":"Invitation resent","auth.identity.attached":"Connected an identity","auth.identity.detached":"Disconnected an identity","auth.identity.delivery_bound":"Bound a verified delivery channel","auth.passkey.authentication_failed":"Recorded a failed passkey sign-in","auth.passkey.migrated":"Migrated a passkey","auth.passkey.registered":"Registered a passkey","auth.passkey.registration_failed":"Recorded a failed passkey registration","auth.passkey.registration_started":"Created a passkey setup link","auth.passkey.revoked":"Revoked a passkey","auth.setup_token.generated":"Generated a setup token","auth.user.created":"Created an account","auth.user.deleted":"Deleted a suspended account","auth.user.grants_revoked":"Revoked account grants","auth.user.role_updated":"Role changed","auth.user.status_updated":"Changed account status"};function Eae(e){let t=u4i[e];if(t)return t;let i=e.replaceAll(/[._-]+/g," ").trim();return i.length===0?e:Wn(i)}var Aae=l.strictObject({actorUserId:l.string().trim().min(1).max(120).optional(),action:l.string().trim().min(1).max(200).optional(),selected:l.string().trim().min(1).max(120).optional(),offset:l.preprocess(p0,l.number().int().min(0).max(1e5)).default(0),limit:l.preprocess(p0,l.number().int().min(1).max(100)).default(25)}),oOe=l.strictObject({id:l.string().min(1),actorUserId:l.string().min(1).optional(),action:l.string().min(1),targetType:l.string().min(1).optional(),targetId:l.string().min(1).optional(),targetUserId:l.string().min(1).optional(),createdAt:l.number().int().nonnegative()}),d4i=l.strictObject({userId:l.string().min(1),displayName:l.string().min(1)}),p4i=l.strictObject({query:Aae,events:l.array(oOe),selectedEvent:oOe.optional(),users:l.array(d4i),actions:l.array(l.strictObject({value:l.string().min(1),label:l.string().min(1),count:l.number().int().nonnegative()})),total:l.number().int().nonnegative()});function sOe(e){let t=e.metadata?.userId;return{...typeof t==="string"&&t?{targetUserId:t}:{},id:e.id,...e.actorUserId?{actorUserId:e.actorUserId}:{},action:e.action,...e.targetType?{targetType:e.targetType}:{},...e.targetId?{targetId:e.targetId}:{},createdAt:e.createdAt}}function aOe(e,t){return e?t.get(e)??"Former Admin":"System"}function cOe(e,t){if(e.targetId)return t.get(e.targetId)??(e.targetUserId?t.get(e.targetUserId):void 0)??e.targetType??e.targetId;return e.targetType??"Access"}var bae=Go({id:"audit",label:"Audit",priority:90,permission:"admin",query:Aae,data:p4i,actions:[],view:({data:e})=>{let t=new Map(e.users.map((o)=>[o.userId,o.displayName])),i=e.selectedEvent,n=[{type:"query",id:"audit-filters",...{controls:[{key:"actorUserId",label:"Actor",value:e.query.actorUserId,allLabel:"All actors",options:e.users.map((o)=>({value:o.userId,label:o.displayName}))},{key:"action",label:"Action",value:e.query.action,allLabel:"All actions",options:e.actions}],...e.total>e.query.limit||e.query.offset>0?{pagination:{offset:e.query.offset,limit:e.query.limit,total:e.total}}:{}}},{type:"detail",id:"audit-detail",queryKey:"selected",empty:"Select an event to inspect its audit record.",...i?{open:{forId:i.id,title:Eae(i.action),blocks:[{type:"key-values",id:"audit-event-fields",items:[{label:"Actor",value:aOe(i.actorUserId,t)},{label:"Action",value:i.action},{label:"Target",value:cOe(i,t)},{label:"Occurred",value:m0(i.createdAt)},{label:"Event ID",value:i.id},{label:"Action ID",value:i.action},...i.targetId?[{label:"Target ID",value:i.targetId}]:[],...i.actorUserId?[{label:"Actor ID",value:i.actorUserId}]:[]]}]}}:{},master:{type:"list",id:"audit-events",presentation:"standard",empty:"No audit events match these filters.",items:e.events.map((o)=>({id:o.id,title:Eae(o.action),description:`${aOe(o.actorUserId,t)} \u2192 ${cOe(o,t)}`,metadata:[new Date(o.createdAt).toISOString()],links:[{label:"Details",target:{detail:{itemId:o.id}}}]}))}}];return{kicker:"Security history",title:"Audit",description:"Who changed access, what changed, and when.",status:{label:`${e.total} matching ${e.total===1?"event":"events"}`,tone:"neutral"},blocks:n}}});function lOe(e){let t=e.studio.source({definition:bae,bind:(i)=>bae.bind(i,{load:async({query:r})=>{let n=h0(e),o=r.get(Aae),[s,a]=await Promise.all([n.queryAuditEvents({...o.actorUserId?{actorUserId:o.actorUserId}:{},...o.action?{action:o.action}:{},...o.selected?{selectedId:o.selected}:{},offset:o.offset,limit:o.limit}),n.listUsers()]);return{query:o,events:s.events.map(sOe),...s.selectedEvent?{selectedEvent:sOe(s.selectedEvent)}:{},users:Ij(a),actions:s.actions.map(({action:c,count:u})=>({value:c,label:Eae(c),count:u})).sort((c,u)=>c.label.localeCompare(u.label)),total:s.total}},actions:[]})});return WE(t,bae.actions)}var _m=l.strictObject({status:l.string()}),_j=l.strictObject({status:l.string(),setupUrl:l.url(),expiresAt:l.string()});function P2(e){return{title:e,fields:{status:{label:"Status"},setupUrl:{label:"Single-use setup URL",copyable:!0,sensitive:!0},expiresAt:{label:"Expires"}}}}var Tj=l.strictObject({type:l.string(),displayName:l.string(),subjectLabel:l.string(),deliveryModes:l.array(l.enum(["automatic","manual"]))});function Pj(e){return Array.from(new Set(e.flatMap((t)=>t.deliveryModes)))}function Rj(e){return{label:e,control:"select",options:[{value:"trusted",label:"Trusted"},{value:"admin",label:"Admin"}]}}function Fj(e,t){return{deliveryType:{label:"Delivery channel",control:"select",options:e.map((i)=>({value:i.type,label:i.displayName}))},deliverySubject:{label:"Delivery destination",labelBy:{field:"deliveryType",values:e.map((i)=>({value:i.type,label:i.subjectLabel}))},control:"text"},deliveryLabel:{label:"Delivery label (optional)",control:"text"},deliveryMode:{label:"Delivery mode",control:"select",options:t.map((i)=>({value:i,label:i==="automatic"?"Automatic":"Manual"}))}}}import{randomUUID as m4i}from"crypto";var uOe=new Set(["claimed","expired","cancelled"]),h4i=new Set(["claimed","cancelled"]),Bae=l.strictObject({state:l.enum(["pending","history"]).optional().default("pending"),selected:l.string().trim().min(1).max(200).optional(),offset:l.preprocess(p0,l.number().int().min(0)).optional().default(0),limit:l.preprocess(p0,l.number().int().min(1).max(100)).optional().default(25)}),hOe=l.strictObject({status:l.string(),setupUrl:l.url().nullable(),expiresAt:l.string().nullable()}),f4i=l.strictObject({idempotencyKey:l.string().min(1),displayName:l.string().trim().min(1).max(200),role:l.enum(["admin","trusted"]),deliveryType:l.string().trim().min(1).max(100),deliverySubject:l.string().trim().min(1).max(500),deliveryLabel:l.string().trim().max(200).optional(),deliveryMode:l.enum(["automatic","manual"])}),fOe=l.strictObject({invitationId:l.string().min(1)}),x4i=l.strictObject({invitationId:l.string().min(1),deliveryAttemptId:l.string().min(1)}),xOe=l.strictObject({invitationId:l.string(),state:l.string()}),Sae=qi({name:"create-invitation",label:"Add a person",permission:"admin",input:f4i,output:hOe}),Cae=qi({name:"resend-invitation",label:"Resend",permission:"admin",catalog:!0,confirmation:{kind:"static",message:"Create a new single-use setup link for this invitation?"},input:fOe,output:hOe}),Dae=qi({name:"cancel-invitation",label:"Cancel",permission:"admin",confirmation:{kind:"prepared"},input:fOe,output:xOe}),Iae=qi({name:"confirm-manual-delivery",label:"Confirm delivered",permission:"admin",input:x4i,output:xOe}),dOe=l.strictObject({id:l.string(),displayName:l.string(),role:l.string(),state:l.string(),destination:l.string(),updatedAt:l.number(),deliveryAttemptId:l.string().optional()}),g4i=l.strictObject({query:Bae,idempotencyKey:l.string(),channels:l.array(Tj),invitations:l.array(dOe),selectedInvitation:dOe.optional(),selectedTotal:l.number().int().nonnegative(),pendingCount:l.number().int().nonnegative(),historyCount:l.number().int().nonnegative(),failureCount:l.number().int().nonnegative()});function kae(e,t){let i=e.filter((r)=>r.id===t);if(i.length!==1||!i[0])throw Error(`Invitations tab composition requires block "${t}" exactly once`);return i[0]}function vae(e,t){let i=kae(e,t);switch(i.type){case"tabs":case"detail":case"columns":throw Error(`Invitations tab composition block "${t}" must be a region`);default:return i}}function gOe(e,t){let i=kae(e,"invitation-totals");if(i.type!=="stats")throw Error('Invitations tab composition block "invitation-totals" must be stats');let r=e.some((a)=>a.id==="create-invitation-unavailable")?[vae(e,"create-invitation-unavailable")]:[],n=kae(e,"invitations");if(n.type!=="detail")throw Error("Invitations composition requires a detail collection");let o=vae(e,"invitation-delivery");if(o.type!=="card")throw Error("Invitations composition requires delivery capabilities");let s=t.flatMap((a)=>a.type==="card"?[...a.blocks]:[a]);return{blocks:[...r,vae(e,"invitation-filters"),n,{...o,presentation:"disclosure",blocks:[...o.blocks,i,...s]}]}}var yOe=P2("Invitation setup");function y4i(e){if(h4i.has(e.state))return[];return[...e.deliveryAttemptId?[{action:Iae,input:{invitationId:e.id,deliveryAttemptId:e.deliveryAttemptId}}]:[],...e.state!=="sending"?[{action:Cae,input:{invitationId:e.id},capability:{id:e.state==="failed"?"retry-invitation":"resend-invitation",label:e.state==="failed"?"Retry":"Resend"},result:yOe}]:[],...e.state!=="expired"?[{action:Dae,input:{invitationId:e.id}}]:[]]}function pOe(e){if(e.state==="pending"&&e.deliveryAttemptId)return"Manual delivery pending";if(e.state==="failed")return"Delivery failed";return Wn(e.state)}var wae=Go({id:"invitations",label:"Invitations",priority:11,permission:"admin",query:Bae,data:g4i,actions:[Sae,Cae,Dae,Iae],badge:({data:e})=>e.pendingCount,view:({data:e})=>{let t=[{type:"stats",id:"invitation-totals",items:[{label:"Pending",value:e.pendingCount},{label:"History",value:e.historyCount},{label:"Delivery failures",value:e.failureCount,tone:e.failureCount>0?"warn":"neutral"}]}],i=Pj(e.channels),r;if(e.channels.length>0&&i.length>0)r={action:Sae,input:{idempotencyKey:e.idempotencyKey},form:{presentation:"disclosure",submitLabel:"Create invitation",fields:{displayName:{label:"Display name",control:"text"},role:Rj("Role"),...Fj(e.channels,i)}},result:yOe};else t.push({type:"notice",id:"create-invitation-unavailable",tone:"warn",text:"No invitation delivery channel is currently available."});let n=e.selectedInvitation;return t.push({type:"query",id:"invitation-filters",controls:[{key:"state",label:"View",value:e.query.state,options:[{value:"pending",label:"Pending",count:e.pendingCount},{value:"history",label:"History",count:e.historyCount}]}],...e.selectedTotal>e.query.limit||e.query.offset>0?{pagination:{offset:e.query.offset,limit:e.query.limit,total:e.selectedTotal}}:{}},{type:"detail",id:"invitations",queryKey:"selected",empty:"Select an invitation to review its delivery.",master:{type:"list",id:"invitation-records",presentation:"standard",empty:e.query.state==="pending"?"No pending invitations.":"No invitation history yet.",items:e.invitations.map((o)=>({id:o.id,title:o.displayName,description:`${Wn(o.role)} \xB7 ${pOe(o)}`,metadata:[o.destination,`Updated ${new Date(o.updatedAt).toISOString()}`],links:[{label:"Review",target:{detail:{itemId:o.id}}}]}))},...n?{open:{forId:n.id,title:n.displayName,blocks:[{type:"key-values",id:"invitation-fields",items:[{label:"Role",value:Wn(n.role)},{label:"Delivery",value:pOe(n)},{label:"Destination",value:n.destination},{label:"Updated",value:m0(n.updatedAt)}]},{type:"actions",id:"invitation-actions",items:y4i(n)}]}}:e.query.selected?{open:{forId:e.query.selected,title:"Invitation unavailable",blocks:[{type:"notice",tone:"neutral",text:"This invitation is no longer available. Return to the list to choose another."}]}}:{}},{type:"card",id:"invitation-delivery",label:"Delivery capabilities",blocks:[{type:"key-values",items:e.channels.map((o)=>({label:o.displayName,value:o.deliveryModes.map(Wn).join(" \xB7 ")}))}]}),{kicker:"Access administration",title:"Invitations",description:"Create, deliver, retry, and revoke passkey invitations without moving auth authority into Studio.",status:{label:`${e.pendingCount} pending`,tone:e.failureCount>0?"warn":"neutral"},...r?{primaryAction:r}:{},blocks:t}}});function mOe(e){return{status:e.invitation.state==="sent"?"Delivery provider accepted the invitation.":e.invitation.state==="failed"?"Invitation saved, but delivery failed.":"Manual delivery is waiting for confirmation.",setupUrl:e.registration?.setupUrl??null,expiresAt:e.registration?new Date(e.registration.expiresAt*1000).toISOString():null}}function bOe(e){let t=h0(e),i=new Map,r=e.studio.source({definition:wae,bind:(n)=>{let o=Sae.bind(n,async({input:u,caller:d})=>{let p=await t.createInvitation({idempotencyKey:u.idempotencyKey,displayName:u.displayName,role:u.role,delivery:{type:u.deliveryType,subject:u.deliverySubject,...u.deliveryLabel?{label:u.deliveryLabel}:{},mode:u.deliveryMode}},Qa(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)i.set(p.invitation.id,p.registration.deliveryAttemptId);return mOe(p)}),s=Cae.bind(n,async({input:u,caller:d})=>{let p=await t.resendInvitation(u.invitationId,Qa(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)i.set(p.invitation.id,p.registration.deliveryAttemptId);return mOe(p)}),a=Dae.bind(n,async({input:u,caller:d})=>{let p=await t.cancelInvitation(u.invitationId,Qa(d));return i.delete(u.invitationId),{invitationId:p.id,state:p.state}},({input:u})=>({summary:"Cancel this invitation and revoke its pending setup link?",revision:u.invitationId})),c=Iae.bind(n,async({input:u,caller:d})=>{let p=await t.confirmManualInvitationDelivery(u.invitationId,u.deliveryAttemptId,Qa(d));return i.delete(u.invitationId),{invitationId:p.id,state:p.state}});return wae.bind(n,{actions:[o,s,a,c],load:async({query:u})=>{let d=u.get(Bae),[p,m]=await Promise.all([t.listAdminUsers(),t.listInvitationChannels()]),h=m.filter((R)=>R.deliveryModes.length>0),f=p.filter((R)=>R.invitation!==void 0),g=f.filter((R)=>R.invitation&&!uOe.has(R.invitation.state)),y=f.filter((R)=>R.invitation&&uOe.has(R.invitation.state)),b=d.state==="pending"?g:y,v=f.flatMap((R)=>{let O=R.invitation;if(!O)return[];let k=R.identities.find((L)=>L.type!=="passkey")?.label??R.externalPeers[0]?.peerId??"Not recorded",j=i.get(O.id);return[{id:O.id,displayName:R.displayName,role:R.role,state:O.state,destination:k,updatedAt:O.claimedAt??O.cancelledAt??O.expiredAt??O.sentAt??O.updatedAt,...j?{deliveryAttemptId:j}:{}}]}),w=new Map(v.map((R)=>[R.id,R])),D=d.selected?w.get(d.selected):void 0;return{query:d,idempotencyKey:m4i(),channels:h.map((R)=>({type:R.type,displayName:R.displayName,subjectLabel:R.subjectLabel,deliveryModes:R.deliveryModes})),invitations:b.slice(d.offset,d.offset+d.limit).flatMap((R)=>{let O=R.invitation?w.get(R.invitation.id):void 0;return O?[O]:[]}),...D?{selectedInvitation:D}:{},selectedTotal:b.length,pendingCount:g.length,historyCount:y.length,failureCount:g.filter((R)=>R.invitation?.state==="failed").length}}})}});return WE(r,wae.actions)}var Rae=l.strictObject({peerId:l.string().trim().max(2000).optional(),displayName:l.string().trim().max(200).optional()}),b4i=l.strictObject({peerId:l.string().trim().min(1).max(2000),displayName:l.string().trim().min(1).max(200),role:l.enum(["admin","trusted"]),deliveryType:l.string().trim().min(1).max(64),deliverySubject:l.string().trim().min(1).max(1000),deliveryLabel:l.string().trim().min(1).max(200).optional(),deliveryMode:l.enum(["automatic","manual"])}),E4i=l.strictObject({peerId:l.string().trim().min(1).max(2000),userId:l.string().min(1)}),Tae=qi({name:"invite-external-peer-person",label:"Invite peer person",permission:"admin",confirmation:{kind:"static",message:"Create this local member and bind them to the external peer?"},input:b4i,output:_j}),Pae=qi({name:"link-external-peer",label:"Link an existing person",permission:"admin",confirmation:{kind:"prepared"},input:E4i,output:_m}),A4i=l.strictObject({query:Rae,peers:l.array(l.strictObject({peerId:l.string(),displayName:l.string(),role:l.enum(["admin","trusted","public"]),verificationStatus:l.enum(["unverified","verified"]),createdAt:l.number()})),people:l.array(l.strictObject({userId:l.string(),displayName:l.string()})),channels:l.array(Tj)});function Mj(e,t){let i=e.filter((n)=>n.id===t);if(i.length!==1)throw Error(`Peer tab composition requires block "${t}" exactly once`);let r=i[0];if(!r)throw Error(`Peer tab composition requires block "${t}" exactly once`);switch(r.type){case"tabs":case"detail":case"columns":throw Error(`Peer tab composition block "${t}" must be a region`);default:return r}}function Fae(e){let t=e.some((i)=>i.id==="invite-peer")?"invite-peer":"invite-peer-unavailable";return{people:[Mj(e,"peers"),Mj(e,"link-peer"),Mj(e,t)],invitations:[Mj(e,t)]}}var v4i=P2("Peer invitation setup"),_ae=Go({id:"peers",label:"Peers",priority:12,permission:"admin",query:Rae,data:A4i,actions:[Tae,Pae],view:({data:e})=>{let t=Pj(e.channels),i=[{type:"stats",id:"peer-summary",items:[{label:"Linked peers",value:e.peers.length},{label:"Verified",value:e.peers.filter((r)=>r.verificationStatus==="verified").length},{label:"Available people",value:e.people.length}]}];if(e.channels.length>0&&t.length>0)i.push({type:"card",id:"invite-peer",label:"Peer-first invitation",blocks:[{type:"text",text:"Create a local member for a person known first through another brain, then issue their single-use passkey setup link."},{type:"action",action:Tae,input:{...e.query.peerId?{peerId:e.query.peerId}:{},...e.query.displayName?{displayName:e.query.displayName}:{}},form:{presentation:"disclosure",submitLabel:"Invite peer person",fields:{peerId:{label:"External peer ID",control:"text"},displayName:{label:"Display name",control:"text"},role:Rj("Local role"),...Fj(e.channels,t)}},result:v4i}]});else i.push({type:"notice",id:"invite-peer-unavailable",tone:"warn",text:"No invitation delivery channel is currently available."});return i.push({type:"card",id:"link-peer",label:"Link an existing person",blocks:[{type:"action",action:Pae,input:{...e.query.peerId?{peerId:e.query.peerId}:{}},form:{submitLabel:"Link peer",fields:{peerId:{label:"External peer ID",control:"text"},userId:{label:"Local person",control:"select",options:e.people.map((r)=>({value:r.userId,label:r.displayName}))}}}}]},{type:"table",id:"peers",empty:"No external peers linked.",columns:[{key:"peer",label:"Peer"},{key:"person",label:"Local person"},{key:"role",label:"Local role"},{key:"verification",label:"Verification"},{key:"linked",label:"Linked"}],rows:e.peers.map((r)=>({id:`${r.peerId}:${r.displayName}`,cells:{peer:_w(r.peerId),person:r.displayName,role:r.role,verification:r.verificationStatus,linked:m0(r.createdAt)},compact:{title:_w(r.peerId),metadata:[r.displayName,Wn(r.role),m0(r.createdAt)],badges:[{label:Wn(r.verificationStatus),tone:r.verificationStatus==="verified"?"good":"warn"}]}}))}),{kicker:"Network administration",title:"Peers",description:"List external brain relationships, invite peer-first people, and link known peers to existing members.",status:{label:`${e.peers.length} linked`},blocks:i}}});function EOe(e){let t=h0(e),i=e.studio.source({definition:_ae,bind:(r)=>{let n=Tae.bind(r,async({input:s,caller:a})=>{let c=await t.inviteExternalPeerPerson({peerId:s.peerId,displayName:s.displayName,role:s.role,delivery:{type:s.deliveryType,subject:s.deliverySubject,...s.deliveryLabel?{label:s.deliveryLabel}:{},mode:s.deliveryMode}},Qa(a));return{status:`Created ${c.user.displayName} and linked ${c.peer.peerId}. Deliver only through ${c.registration.delivery.label}.`,setupUrl:c.registration.setupUrl,expiresAt:new Date(c.registration.expiresAt*1000).toISOString()}}),o=Pae.bind(r,async({input:s,caller:a})=>(await t.linkExternalPeer({peerId:s.peerId,userId:s.userId},Qa(a)),{status:"External peer linked to the local person."}),async({input:s})=>{let c=(await t.listAdminUsers()).find((u)=>u.userId===s.userId)?.displayName??"person";return{summary:`Link ${s.peerId} to ${c}? Local access does not change.`,revision:`${s.peerId}:${s.userId}`}});return _ae.bind(r,{actions:[n,o],load:async({query:s})=>{let a=s.get(Rae),[c,u]=await Promise.all([t.listAdminUsers(),t.listInvitationChannels()]),d=c.filter((p)=>p.status!=="invited");return{query:a,peers:c.flatMap((p)=>p.externalPeers.map((m)=>({peerId:m.peerId,displayName:p.displayName,role:p.role,verificationStatus:m.verificationStatus,createdAt:m.createdAt}))),people:Ij(d),channels:u.filter((p)=>p.deliveryModes.length>0).map((p)=>({type:p.type,displayName:p.displayName,subjectLabel:p.subjectLabel,deliveryModes:p.deliveryModes}))}}})}});return WE(i,_ae.actions)}function Mae(e,t){let i=e.filter((r)=>r.id===t);if(i.length!==1||!i[0])throw Error(`People tab composition requires block "${t}" exactly once`);return i[0]}function AOe(e,t,i){let r=Mae(e,"people-summary");if(r.type!=="stats")throw Error('People tab composition block "people-summary" must be stats');let n=Mae(e,"people");if(n.type!=="detail")throw Error('People tab composition block "people" must be a detail');let o=Mae(e,"brain-anchor");if(o.type!=="card")throw Error('People tab composition block "brain-anchor" must be a card');let s=[t,...i].flatMap((a)=>a.type==="card"?[...a.blocks]:[a]);return{blocks:[n,{type:"card",id:"people-peers",label:"External brains",presentation:"disclosure",blocks:s},{...o,label:"Access reference",presentation:"disclosure",blocks:[r,...o.blocks]}]}}var Hae=l.strictObject({selected:l.string().trim().min(1).max(200).optional()}),Wae=l.strictObject({userId:l.string().min(1)}),w4i=l.strictObject({userId:l.string().min(1),role:l.enum(["admin","trusted","public"])}),S4i=l.strictObject({userId:l.string().min(1),status:l.enum(["active","suspended"])});function k4i(e){return e.revokedAt===void 0&&e.type!=="passkey"}function B4i(e){return e.credentialBackedUp?"Synced passkey":"Device passkey"}var C4i=l.strictObject({userId:l.string().min(1),credentialId:l.string().min(1)}),D4i=l.strictObject({userId:l.string().min(1),type:l.string().trim().min(1).max(64),subject:l.string().trim().min(1).max(2000),issuer:l.string().trim().min(1).max(2000).optional(),label:l.string().trim().min(1).max(200).optional()}),I4i=l.strictObject({userId:l.string().min(1),identityId:l.string().min(1)}),_4i=l.strictObject({userId:l.string().min(1),peerId:l.string().trim().min(1).max(2000)}),Lae=qi({name:"update-person-role",label:"Change role",permission:"admin",confirmation:{kind:"prepared"},input:w4i,output:_m}),zae=qi({name:"update-person-status",label:"Suspend person",permission:"admin",catalog:!0,confirmation:{kind:"prepared"},input:S4i,output:_m}),jae=qi({name:"delete-person",label:"Delete person",permission:"admin",confirmation:{kind:"prepared"},input:Wae,output:_m}),Uae=qi({name:"revoke-person-passkey",label:"Revoke passkey",permission:"admin",confirmation:{kind:"prepared"},input:C4i,output:_m}),Zae=qi({name:"start-person-passkey-registration",label:"Create setup link",permission:"admin",confirmation:{kind:"static",message:"Create a single-use passkey setup link for this person?"},input:Wae,output:_j}),qae=qi({name:"revoke-person-sessions",label:"Revoke all sessions",permission:"admin",confirmation:{kind:"prepared"},input:Wae,output:_m}),Vae=qi({name:"attach-person-identity",label:"Attach channel",permission:"admin",confirmation:{kind:"static",message:"Attach this verified channel identity to the selected person?"},input:D4i,output:_m}),$ae=qi({name:"detach-person-identity",label:"Detach channel",permission:"admin",confirmation:{kind:"prepared"},input:I4i,output:_m}),Gae=qi({name:"unlink-external-peer",label:"Unlink peer",permission:"admin",confirmation:{kind:"prepared"},input:_4i,output:_m}),T4i=l.strictObject({userId:l.string(),displayName:l.string(),role:l.enum(["admin","trusted","public"]),status:l.enum(["active","suspended"]),isAnchor:l.boolean(),isSelf:l.boolean(),profileEntityId:l.string().optional(),passkeys:l.array(l.strictObject({id:l.string(),kind:l.string(),createdAt:l.number()})),identities:l.array(l.strictObject({id:l.string(),type:l.string(),displayName:l.string(),label:l.string(),verified:l.boolean()})),peers:l.array(l.strictObject({peerId:l.string(),verificationStatus:l.enum(["unverified","verified"])}))}),P4i=l.strictObject({query:Hae,anchor:l.strictObject({kind:l.enum(["person","collective"]),configuredKind:l.enum(["person","team","organization"]),displayName:l.string(),administeredBy:l.number().int().nonnegative()}),people:l.array(T4i),activeCount:l.number().int().nonnegative(),activeAdminCount:l.number().int().nonnegative(),suspendedCount:l.number().int().nonnegative(),channelTypes:l.array(l.strictObject({type:l.string(),displayName:l.string()}))}),R4i=P2("Passkey setup");function F4i(){return{type:"links",items:[{label:"Manage your own credentials and sessions",target:{launch:{target:"account-settings"}}}]}}function Oae(e){return{type:"notice",tone:"warn",text:e}}function M4i(e){return{type:"action",action:Zae,input:{userId:e},result:R4i}}function O4i(e,t){return{type:"action",action:Vae,input:{userId:e},form:{submitLabel:"Attach channel",fields:{type:{label:"Channel type",control:"select",options:t.map((i)=>({value:i.type,label:i.displayName}))},subject:{label:"Channel subject",control:"text"},issuer:{label:"Issuer (optional)",control:"url"},label:{label:"Display label (optional)",control:"text"}}}}}function N4i(e,t){return{kind:"person",configuredKind:"person",displayName:e,administeredBy:t}}var Nae=Go({id:"people",label:"People",priority:10,permission:"admin",query:Hae,data:P4i,actions:[Lae,zae,jae,Uae,Zae,qae,Vae,$ae,Gae],badge:({data:e})=>e.suspendedCount,view:({data:e})=>{let t=e.people.find((n)=>n.userId===e.query.selected),i=[];if(t){let n=t.role==="admin"&&t.status==="active"&&e.activeAdminCount<=1,o=t.isAnchor?"The protected brain identity must remain an active Admin.":t.status==="suspended"?"Reactivate this person before changing access.":n?"Add another active Admin before changing this role.":void 0,s=t.isAnchor?"The protected brain identity cannot be suspended.":n?"Add another active Admin before suspending this person.":void 0;if(i.push({type:"key-values",id:"person-summary",items:[{label:"Role",value:Wn(t.role)},{label:"Status",value:Wn(t.status)},{label:"Protected brain identity",value:t.isAnchor},{label:"Brain relationship",value:t.peers.length>0?"External peer + local member":"Hosted member"}]}),o)i.push({type:"notice",tone:"warn",text:o});else i.push({type:"card",id:"person-role",label:"Permission role",blocks:[{type:"action",action:Lae,input:{userId:t.userId,role:t.role},form:{submitLabel:"Change role",fields:{role:{label:"Role",control:"select",options:[{value:"admin",label:"Admin"},{value:"trusted",label:"Trusted"},{value:"public",label:"Public"}]}}}}]});i.push({type:"card",id:"person-access",label:"Access",blocks:[{type:"actions",items:[{action:zae,input:{userId:t.userId,status:t.status==="suspended"?"active":"suspended"},capability:{id:t.status==="suspended"?"reactivate-person":"suspend-person",label:t.status==="suspended"?"Reactivate person":"Suspend person"},disabled:t.status==="active"&&s!==void 0},...t.status==="active"&&!t.isSelf?[{action:qae,input:{userId:t.userId}}]:[],...t.status==="suspended"?[{action:jae,input:{userId:t.userId}}]:[]]},...t.isSelf?[F4i()]:[],...s&&t.status==="active"?[Oae(s)]:[]]}),i.push({type:"card",id:"person-sign-in",label:"Sign-in",blocks:[{type:"table",id:"person-passkeys",empty:"No passkeys registered.",columns:[{key:"kind",label:"Passkey"},{key:"created",label:"Added"}],rows:t.passkeys.map((a)=>({id:a.id,cells:{kind:a.kind,created:m0(a.createdAt)},compact:{title:a.kind,metadata:[`Added ${m0(a.createdAt)}`]},actions:t.status==="active"&&!t.isSelf?[{action:Uae,input:{userId:t.userId,credentialId:a.id}}]:[]}))},...t.status==="active"&&!t.isSelf?t.identities.some((a)=>a.verified)?[M4i(t.userId)]:[Oae("A verified channel is required for setup delivery.")]:[]]}),i.push({type:"card",id:"person-channels",label:"Linked identities",blocks:[{type:"table",id:"person-identities",empty:"No linked identity.",columns:[{key:"channel",label:"Channel"},{key:"identity",label:"Identity"},{key:"assurance",label:"Assurance"}],rows:t.identities.map((a)=>({id:a.id,cells:{channel:a.displayName,identity:a.label,assurance:a.verified?"Verified":"Asserted"},compact:{title:a.label,metadata:[a.displayName],badges:[{label:a.verified?"Verified":"Asserted",tone:a.verified?"good":"neutral"}]},actions:[{action:$ae,input:{userId:t.userId,identityId:a.id}}]}))},...e.channelTypes.length>0?[O4i(t.userId,e.channelTypes)]:[Oae("No attachable channel type is configured.")]]}),i.push({type:"notice",tone:"neutral",text:"External peer links record provenance from another brain. They do not grant or change this person's local access."}),i.push({type:"list",id:"person-peers",empty:"No external peer linked; this person is hosted locally.",items:t.peers.map((a)=>({id:a.peerId,title:_w(a.peerId),description:`Vouched in by ${_w(a.peerId)} \xB7 ${a.peerId}`,metadata:[Wn(a.verificationStatus)],actions:[{action:Gae,input:{userId:t.userId,peerId:a.peerId}}]}))})}let r=[{type:"stats",id:"people-summary",items:[{label:"Active members",value:e.activeCount},{label:"Active Admins",value:e.activeAdminCount},{label:"Suspended",value:e.suspendedCount,tone:e.suspendedCount>0?"warn":"neutral"}]},{type:"card",id:"brain-anchor",label:"Brain identity",blocks:[{type:"key-values",items:[{label:"Name",value:e.anchor.displayName},{label:"Kind",value:e.anchor.configuredKind},{label:"Ownership",value:e.anchor.kind},{label:"Administered by",value:e.anchor.administeredBy}]}]},{type:"detail",id:"people",queryKey:"selected",empty:"Select a person to inspect their access.",master:{type:"list",id:"people-roster",presentation:"standard",empty:"No people are available.",items:[...e.people].sort((n,o)=>Number(o.isSelf)-Number(n.isSelf)||Number(n.isAnchor)-Number(o.isAnchor)||n.displayName.localeCompare(o.displayName)).map((n)=>({id:n.userId,title:n.displayName,description:[Wn(n.role),Wn(n.status),...n.isSelf?["You"]:[],...n.isAnchor?["Protected brain identity"]:[]].join(" \xB7 "),metadata:[n.identities.length===0?"No linked identities":n.identities.length===1?"One linked identity":`${n.identities.length} linked identities`,...n.peers.length>0?[`Arrived via ${_w(n.peers[0]?.peerId)}`]:[]],...n.isSelf?{link:{detail:{itemId:n.userId}}}:{},links:[{label:n.isSelf?"Account \u2192":n.isAnchor?"View protection":"Manage person",target:n.isSelf?{launch:{target:"account-settings"}}:{detail:{itemId:n.userId}}}]}))},...t?{open:{forId:t.userId,title:t.displayName,blocks:i}}:{}}];return{kicker:"Access administration",title:"People",description:"Manage people\u2019s access to this brain, linked identities, and account recovery. Use Account for your own profile and sign-in settings.",status:{label:`${e.activeCount} active`,tone:e.suspendedCount>0?"warn":"neutral"},blocks:r}}});function Oj(e,t){return e.find((i)=>i.userId===t)?.displayName??"person"}async function L4i(e){try{return await e.getBrainAnchor()}catch(t){if(t instanceof Error&&t.message==="Brain anchor is not configured")return;throw t}}function vOe(e){let t=h0(e),i=e.studio.source({definition:Nae,bind:(r)=>{let n=Lae.bind(r,async({input:h,caller:f})=>(await t.updateUserRole(h.userId,h.role,Qa(f)),{status:`Role changed to ${Wn(h.role)}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Change ${Oj(f,h.userId)}\u2019s role to ${Wn(h.role)}?`,revision:`${h.userId}:${h.role}`}}),o=zae.bind(r,async({input:h,caller:f})=>(await t.updateUserStatus(h.userId,h.status,Qa(f)),{status:`Person ${h.status}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`${h.status==="active"?"Reactivate":"Suspend"} ${Oj(f,h.userId)}?`,revision:`${h.userId}:${h.status}`}}),s=jae.bind(r,async({input:h,caller:f})=>(await t.deleteSuspendedUser(h.userId,Qa(f)),{status:"Suspended person permanently deleted."}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Permanently delete ${Oj(f,h.userId)}? Audit history is retained.`,revision:h.userId}}),a=Uae.bind(r,async({input:h,caller:f})=>(await t.revokePasskey(h.credentialId,Qa(f)),{status:"Passkey revoked."}),({input:h})=>({summary:"Revoke this passkey immediately?",revision:`${h.userId}:${h.credentialId}`})),c=Zae.bind(r,async({input:h,caller:f})=>{let g=await t.startPasskeyRegistrationForUser(h.userId,Qa(f));return{status:`Bound to ${g.delivery.label}. Deliver only through that confirmed private channel.`,setupUrl:g.setupUrl,expiresAt:new Date(g.expiresAt*1000).toISOString()}}),u=qae.bind(r,async({input:h,caller:f})=>{let g=await t.revokeUserSessionsAndRefreshTokens(h.userId,Qa(f));return{status:`Revoked ${g.sessions} sessions and ${g.refreshTokens} refresh tokens.`}},async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Sign ${Oj(f,h.userId)} out everywhere?`,revision:h.userId}}),d=Vae.bind(r,async({input:h,caller:f})=>(await t.attachIdentity({userId:h.userId,type:h.type,subject:h.subject,...h.issuer?{issuer:h.issuer}:{},...h.label?{label:h.label}:{},verifiedAt:Date.now(),source:{kind:"admin"}},Qa(f)),{status:"Verified channel attached."})),p=$ae.bind(r,async({input:h,caller:f})=>(await t.detachIdentity(h.identityId,Qa(f)),{status:"Channel detached."}),({input:h})=>({summary:"Detach this channel identity?",revision:`${h.userId}:${h.identityId}`})),m=Gae.bind(r,async({input:h,caller:f})=>(await t.unlinkExternalPeer(h,Qa(f)),{status:"External peer unlinked from the local person."}),({input:h})=>({summary:`Unlink ${h.peerId}? Local access will not change.`,revision:`${h.peerId}:${h.userId}`}));return Nae.bind(r,{actions:[n,o,s,a,c,u,d,p,m],load:async({query:h,caller:f})=>{let g=h.get(Hae),[y,b,v]=await Promise.all([L4i(t),t.listAdminUsers(),t.listInvitationChannels()]),w=b.filter((j)=>j.status!=="invited"),D=w.find((j)=>j.isAnchor)??w.find((j)=>j.role==="admin"&&j.status==="active"),R=y??N4i(D?.displayName??"Brain owner",w.filter((j)=>j.role==="admin"&&j.status==="active").length),O=w.filter((j)=>j.status==="active"),k=new Map(v.map((j)=>[j.type,j.displayName]));return{query:g,anchor:{kind:R.kind,configuredKind:R.configuredKind,displayName:R.displayName,administeredBy:R.administeredBy},people:w.flatMap((j)=>{if(j.status==="invited")return[];return[{userId:j.userId,displayName:j.displayName,role:j.role,status:j.status,isAnchor:j.isAnchor,isSelf:f?.actor.id===j.userId,...j.profileEntityId?{profileEntityId:j.profileEntityId}:{},passkeys:j.passkeys.map((L)=>({id:L.id,kind:B4i(L),createdAt:L.createdAt})),identities:j.identities.filter(k4i).map((L)=>({id:L.id,type:L.type,displayName:k.get(L.type)??Wn(L.type),label:L.label??"Connected identity",verified:L.verifiedAt!==void 0})),peers:j.externalPeers.map((L)=>({peerId:L.peerId,verificationStatus:L.verificationStatus}))}]}),activeCount:O.length,activeAdminCount:O.filter((j)=>j.role==="admin").length,suspendedCount:w.length-O.length,channelTypes:v.map((j)=>({type:j.type,displayName:j.displayName}))}}})}});return WE(i,Nae.actions)}var z4i=l.strictObject({tab:l.enum(["people","invitations","audit"]).default("people"),selected:l.string().trim().min(1).max(200).optional(),state:l.enum(["pending","history"]).optional(),offset:l.preprocess(p0,l.number().int().min(0).max(1e5)).optional(),limit:l.preprocess(p0,l.number().int().min(1).max(100)).optional(),peerId:l.string().trim().max(2000).optional(),displayName:l.string().trim().max(200).optional(),actorUserId:l.string().trim().min(1).max(120).optional(),action:l.string().trim().min(1).max(200).optional()});function j4i(e){if(e===null||typeof e!=="object")return;let t=Reflect.get(e,"actionId");return typeof t==="string"?t:void 0}function U4i(e){if(e===null||typeof e!=="object")return!1;let t=Reflect.get(e,"view");if(t===null||typeof t!=="object")return!1;return Array.isArray(Reflect.get(t,"blocks"))}function q4i(e,t){if(!U4i(e))throw Error(`${t} tab returned invalid workspace data`);return e}function wOe(e,t){let i=[];for(let r of e){if(r.type==="tabs")throw Error(`${t} tab cannot contribute nested tabs`);i.push(r)}return i}function Kae(e){return[{type:"text",text:`${e} loads when this tab is opened.`}]}async function _I(e,t,i,r){return q4i(await e.dataProvider(t,i,r),e.label)}async function $4i(e,t,i,r){if(!e.actionHandler)throw Error(`${e.label} does not provide actions`);return e.actionHandler(t,i,r)}function G4i(e){let t=new Map;for(let i of e)for(let r of i.actionIds){if(t.has(r))throw Error(`Administration action "${r}" is declared by more than one source`);if(!i.registration.actionHandler)throw Error(`Administration source "${i.registration.label}" declares actions without a handler`);t.set(r,i.registration)}return t}function H4i(e){let t=e.filter((r)=>r.status==="suspended").length,i=e.filter((r)=>r.invitation!==void 0&&!["claimed","expired","cancelled"].includes(r.invitation.state)).length;return t+i}async function SOe(e){if(!e.studio.isAvailable())return;let t=vOe(e),i=bOe(e),r=EOe(e),n=lOe(e),o=G4i([t,i,r,n]),s=t.registration,a=i.registration,c=r.registration,u=n.registration;return e.studio.register({id:"admin:administration",label:"Administration",rendererName:EI,priority:10,permission:"admin",urlQuery:!0,aliases:[{id:"admin:people",query:{tab:"people"}},{id:"admin:invitations",query:{tab:"invitations"}},{id:"admin:peers",query:{tab:"people"}},{id:"admin:audit",query:{tab:"audit"}}],entityTypes:[],accessHandler:(d)=>s.accessHandler(d),dataProvider:async(d,p,m)=>{let h=z4i.parse(p??{}),f,g=Kae("People"),y=Kae("Invitations"),b=Kae("Audit");if(h.tab==="people"){let[v,w]=await Promise.all([_I(s,d,{...h.selected?{selected:h.selected}:{}},m),_I(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),D=Fae(w.view.blocks);g=[...AOe(wOe(v.view.blocks,"People"),{type:"notice",id:"people-peer-note",tone:"neutral",title:"External brain relationships",text:"A peer link records how a locally administered person relates to another brain. It does not grant or change local access."},D.people).blocks]}else if(h.tab==="invitations"){let[v,w]=await Promise.all([_I(a,d,{...h.state?{state:h.state}:{},...h.selected?{selected:h.selected}:{},...gl({offset:h.offset,limit:h.limit})},m),_I(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),D=Fae(w.view.blocks),R=gOe(v.view.blocks,D.invitations);f=v.view.primaryAction,y=[...R.blocks]}else{let v=await _I(u,d,{...h.actorUserId?{actorUserId:h.actorUserId}:{},...h.action?{action:h.action}:{},...h.selected?{selected:h.selected}:{},...gl({offset:h.offset,limit:h.limit})},m);b=wOe(v.view.blocks,"Audit")}return{view:{kicker:"Access administration",title:"Administration",description:"Manage people, invitations, and access to this brain. Use Account for your own profile, sign-in security, and personal settings.",...f?{primaryAction:f}:{},blocks:[{type:"tabs",id:"administration-tabs",label:"Administration sections",defaultTab:h.tab,queryKey:"tab",tabs:[{id:"people",label:"People",blocks:g},{id:"invitations",label:"Invitations",blocks:y},{id:"audit",label:"Access activity",blocks:b}]}]}}},actionHandler:async(d,p,m)=>{let h=j4i(d);if(!h)throw new Ni("invalid_input",{publicMessage:"Administration action id is required"});let f=o.get(h);if(!f)throw new Ni("not_found",{publicMessage:`Unknown Administration action: ${h}`});return $4i(f,d,p,m)},badgeProvider:async()=>H4i(await h0(e).listAdminUsers())})}var W4i=259200000,Z4i=l.strictObject({id:l.string(),displayName:l.string(),state:l.string(),reason:l.enum(["expiring","delivery-failed"]),expiresAt:l.number().optional()}),V4i=l.strictObject({invitations:l.array(Z4i),expiringCount:l.number().int().nonnegative(),failureCount:l.number().int().nonnegative()}),kOe=Nn({id:"expiring-invitations",title:"Invitations",description:"Setup links that expire soon or need delivery attention",group:"access",placement:"primary",priority:5,permission:"admin",data:V4i,digest:({data:e})=>({items:[{label:"Expiring soon",value:String(e.expiringCount),...e.expiringCount>0?{tone:"warn"}:{}},{label:"Delivery failures",value:String(e.failureCount),...e.failureCount>0?{tone:"warn"}:{}}],attention:e.invitations.length}),view:({data:e})=>({blocks:[{type:"stats",items:[{label:"Expiring soon",value:e.expiringCount,tone:e.expiringCount>0?"warn":"good"},{label:"Delivery failures",value:e.failureCount,tone:e.failureCount>0?"warn":"good"}]},{type:"list",id:"invitation-attention",empty:"No invitation setup links need attention.",items:e.invitations.map((t)=>({id:t.id,title:t.displayName,description:t.reason==="delivery-failed"?"Invitation delivery failed. Resend or cancel it.":"The single-use setup link expires soon.",metadata:[t.state,...t.expiresAt!==void 0?[`Expires ${m0(t.expiresAt)}`]:[]],tone:t.reason==="delivery-failed"?"error":"warn",link:{launch:{target:"invitations"}}}))},{type:"links",items:[{label:"Open Invitations",target:{launch:{target:"invitations"}}}]}]})});function K4i(e,t){let i=e.flatMap((r)=>{let n=r.invitation;if(!n)return[];if(n.state==="failed")return[{id:n.id,displayName:r.displayName,state:n.state,reason:"delivery-failed",...n.expiresAt!==void 0?{expiresAt:n.expiresAt}:{}}];if(!["pending","sending","sent"].includes(n.state)||n.expiresAt===void 0||n.expiresAt<=t||n.expiresAt>t+W4i)return[];return[{id:n.id,displayName:r.displayName,state:n.state,reason:"expiring",expiresAt:n.expiresAt}]});return i.sort((r,n)=>(r.expiresAt??Number.MAX_SAFE_INTEGER)-(n.expiresAt??Number.MAX_SAFE_INTEGER)||r.displayName.localeCompare(n.displayName)),{invitations:i,expiringCount:i.filter((r)=>r.reason==="expiring").length,failureCount:i.filter((r)=>r.reason==="delivery-failed").length}}async function BOe(e,t){t.throwIfAborted();let i=await h0(e).listAdminUsers();return t.throwIfAborted(),K4i(i,Date.now())}var Y4i=l.strictObject({}),J4i=xi({id:"admin",config:Y4i},{subscriptions:(e)=>{let t=Gt(e);return t.registered(async()=>{await SOe(t)}),[]},dashboardWidgets:(e)=>{let t=Gt(e);return[kOe.bind(e,({signal:i})=>BOe(t,i))]}}),Yae=J4i;var nn="agent";var COe="agent-network",DOe="agent-proximity",pce="agent-discovery:entities",IOe="agent-discovery:proximity-map",mce="proximity-map",hce="agent-list",fce="agent-detail",Xa="skill",_Oe=30,TOe=120;var Lj="skill-derivation",POe="skill-derivation",xce="skill:skill-derivation",ROe="skills";var Q4i=l.string().trim().min(1).max(TOe),gce=l.array(Q4i).max(_Oe),VE=l.object({name:l.string(),description:l.string(),tags:gce,examples:l.array(l.string())}),F2=VE,KE=Tm.extend({entityType:l.literal(Xa),metadata:F2});var zj=l.object({name:l.string(),description:l.string(),tags:gce}),Vg=l.enum(["discovered","approved","archived"]).describe("Discovered for review, approved for calling, or archived"),X4i=Dw,Fm=l.object({name:l.string(),kind:X4i,organization:l.string().optional(),brainName:l.string().describe("Name of the brain instance"),url:l.string().url().describe("Brain endpoint URL"),repoDid:l.string().optional().meta({description:"ATProto repo DID",studioWidget:"provenance"}),brainDid:l.string().optional().meta({description:"ATProto brain DID",studioWidget:"provenance"}),cardUri:l.string().optional().meta({description:"ATProto brain card URI",studioWidget:"provenance"}),cardCid:l.string().optional().meta({description:"ATProto brain card CID",studioWidget:"provenance"}),cardLastError:l.string().optional().meta({description:"Last ATProto brain card refresh error",studioWidget:"hidden"}),cardFailureCount:l.number().int().nonnegative().optional().meta({description:"Consecutive ATProto brain card refresh failures",studioWidget:"hidden"}),cardUnavailableAt:l.string().datetime().optional().meta({description:"When the remote ATProto brain card became unavailable",studioWidget:"hidden"}),cardStaleAfter:l.string().datetime().optional().meta({description:"When a never-approved unavailable card may be archived",studioWidget:"hidden"}),status:Vg,discoveredAt:l.string().datetime().meta({description:"When this agent was first discovered",studioWidget:"provenance"}),introducedBy:l.array(l.string()).optional().meta({description:"Agent ids of the peers whose directories reported this agent",studioWidget:"provenance"}),hops:l.number().int().min(2).optional().meta({description:"Discovery order: 2 = sighted through a first-order peer",studioWidget:"provenance"})}),LI=l.object({name:l.string(),url:l.string().url(),status:Vg,discoveredAt:l.string().datetime().optional(),slug:l.string(),repoDid:l.string().optional(),brainDid:l.string().optional(),cardUri:l.string().optional(),cardCid:l.string().optional(),cardLastError:l.string().optional(),cardFailureCount:l.number().int().nonnegative().optional(),cardUnavailableAt:l.string().datetime().optional(),cardStaleAfter:l.string().datetime().optional()}),Do=Tm.extend({entityType:l.literal(nn),metadata:LI}),e3i=Mi.extend({entityType:l.literal(nn),metadata:LI}),zI=e3i.extend({frontmatter:Fm,about:l.string(),skills:l.array(zj),notes:l.string()}),t3i=zI.extend({url:l.string().optional(),typeLabel:l.string().optional()}),i3i=zI.extend({url:l.string(),typeLabel:l.string()});var r3i=l.record(l.string(),l.unknown());function n3i(e){try{return xn(e,r3i).content}catch{return e}}function yce(e){return{name:e.name,url:e.url,status:e.status,discoveredAt:e.discoveredAt,slug:M2(e.url),...e.repoDid&&{repoDid:e.repoDid},...e.brainDid&&{brainDid:e.brainDid},...e.cardUri&&{cardUri:e.cardUri},...e.cardCid&&{cardCid:e.cardCid},...e.cardLastError&&{cardLastError:e.cardLastError},...e.cardFailureCount!==void 0&&{cardFailureCount:e.cardFailureCount},...e.cardUnavailableAt&&{cardUnavailableAt:e.cardUnavailableAt},...e.cardStaleAfter&&{cardStaleAfter:e.cardStaleAfter}}}function FOe(e){return Ia(nn,e,Fm)}function jI(e){return{content:e,metadata:yce(FOe(e))}}function O2(e){let t={name:e.name,kind:e.kind,...e.organization&&{organization:e.organization},brainName:e.brainName,url:e.url,...e.repoDid&&{repoDid:e.repoDid},...e.brainDid&&{brainDid:e.brainDid},...e.cardUri&&{cardUri:e.cardUri},...e.cardCid&&{cardCid:e.cardCid},...e.cardLastError&&{cardLastError:e.cardLastError},...e.cardFailureCount!==void 0&&{cardFailureCount:e.cardFailureCount},...e.cardUnavailableAt&&{cardUnavailableAt:e.cardUnavailableAt},...e.cardStaleAfter&&{cardStaleAfter:e.cardStaleAfter},status:Vg.parse(e.status),discoveredAt:e.discoveredAt,...e.introducedBy?.length&&{introducedBy:e.introducedBy},...e.hops!==void 0&&{hops:e.hops}},i=yae({about:e.about,skills:e.skills,notes:e.notes});return fn(i,t)}function Fw(e,t={}){return O2({...e.frontmatter,...e.body,...t})}function UI(e){return II(n3i(e))}function od(e){return{frontmatter:FOe(e.content),body:UI(e.content)}}function bce(e){return fn("",e)}function s3i(e,t){if(t.count!==e.count)return t.count-e.count;return e.tag.localeCompare(t.tag)}function MOe(e,t,i={}){let r=i.minCount??1,n=i.topN??12,o=new Map,s=(a)=>{for(let c of Ta(a))o.set(c,(o.get(c)??0)+1)};for(let a of e)s(a.metadata.tags);for(let a of t){let c=UI(a.content);s(c.skills.flatMap((u)=>u.tags))}return Array.from(o.entries()).map(([a,c])=>({tag:a,count:c})).filter((a)=>a.count>=r).sort(s3i).slice(0,n)}function OOe(e){if(e.length===0)return"";return["Current agent-directory tag vocabulary (reuse existing tags where they fit; propose new only when nothing does):",...e.map(({tag:t,count:i})=>`- ${t} (${i})`)].join(`
1024
+ `)},t,{requireSaved:!0,userPermissionLevel:s});if(!("success"in a)||a.success!==!0)throw XMe(a,"Agent call failed");let c=Hse.safeParse(a.data);if(!c.success)throw new Ni("handler_failed",{publicMessage:"Invalid response from agent"});return c.data}),e.answer(kj,async({request:{userPermissionLevel:r}})=>{if(!e.entityReads.hasEntityType("agent"))return{agents:[]};return{agents:(await e.entityReads.listEntities({entityType:"agent",options:{filter:{visibilityScope:Xr(r)}}})).filter((s)=>s.metadata.status==="approved").map((s)=>{let a=s.metadata.name;return{id:s.id,label:typeof a==="string"&&a.length>0?a:s.id}}).sort((s,a)=>s.label.localeCompare(a.label))}})}var tOe={name:"@brains/a2a",license:"AGPL-3.0-only",version:"0.2.0-alpha.699",dependencies:{"@a2a-js/sdk":"^0.3.13","@brains/contracts":"workspace:*","@brains/http-signatures":"workspace:*","@brains/sdk":"workspace:*","@brains/utils":"workspace:*",hono:"^4.13.13"},devDependencies:{"@brains/auth-service":"workspace:*","@brains/entity-service":"workspace:*","@brains/eslint-config":"workspace:*","@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},files:["src"],main:"./src/index.ts",module:"./src/index.ts",private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"};var r4i={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Signature, Signature-Input, Content-Digest, Date","X-Content-Type-Options":"nosniff"};function c0(e){let t=new Headers(e.headers);for(let[i,r]of Object.entries(r4i))t.set(i,r);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}function n4i(e){let t=e.auth();if(!t)return;let i=t.getIssuer();if(kf(i)||new URL(i).protocol!=="https:")return;return async(r)=>{let n=await t.getA2ASigningKey();await wMe(r,n.privateJwk,n.keyId)}}function iOe(e,t,i){let r=n4i(e);return{...r?{requestSigner:r}:{},...i.fetch?{fetch:i.fetch}:{},requestTimeoutMs:t.requestTimeoutMs,streamIdleTimeoutMs:t.streamIdleTimeoutMs,maxNetworkAttempts:t.maxNetworkAttempts,entityService:e.entityReads}}async function o4i(e,t,i){if(!i.cardReady)return;return FMe({character:e.identity.get(),profile:e.identity.getProfile(),version:tOe.version,...e.domain?{domain:e.domain}:{},...t.organization?{organization:t.organization}:{},profileKind:e.profileKinds.getResolved(),tools:e.tools.listForPermissionLevel("public"),skills:await e.publicSkills.list(),authEnabled:!1})}async function s4i(e,t,i,r){let n=new URL(i.url),o=new URL(`${n.pathname}${n.search}`,u0(i)),s=await SMe({method:i.method,url:o.toString(),headers:i.headers,body:r},t.jwksResolver);if(s){let a=await e.auth()?.getA2APeerTrust(s.domain);return{permissionLevel:a?.keyFingerprint===s.keyFingerprint?a.grantedLevel:"public",isAnchor:e.permissions.isAnchor("a2a",s.domain),callerDomain:s.domain}}return{permissionLevel:"public",isAnchor:!1,callerDomain:null}}function a4i(e,t,i){let r=new rOe,n=e.agent;return r.get("/.well-known/agent-card.json",async(o)=>{let s=await o4i(e,t,i);if(!s)return c0(o.json({error:"Agent Card not ready"},503));return c0(o.json(s))}),r.get("/.well-known/agent-directory.json",async(o)=>{let s=await MMe(e.entityReads);return c0(o.json(s))}),r.get("/a2a",(o)=>c0(o.json({error:"Use POST with JSON-RPC 2.0 requests.",agentCard:"/.well-known/agent-card.json"},405))),r.options("/a2a",()=>c0(new Response(null,{status:204}))),r.post("/a2a",async(o)=>{let s=await o.req.text(),a;try{a=await s4i(e,i,o.req.raw,s)}catch{return c0(o.json({error:"Invalid HTTP signature"},401))}let c;try{c=JSON.parse(s)}catch{return c0(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}))}let u=LMe.safeParse(c);if(!u.success)return c0(o.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid request"},id:null}));if(u.data.method==="message/stream"){let p=GMe.safeParse(u.data.params??{});if(!p.success)return c0(o.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${p.error.message}`},id:u.data.id}));let m=HMe(u.data.id,p.data.message,{taskManager:i.taskManager,turnSupervisor:i.turnSupervisor,agentService:n,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:i.publicAsks});if("error"in m)return c0(o.json(m));return c0(new Response(m.stream,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let d=await UMe(u.data,{taskManager:i.taskManager,turnSupervisor:i.turnSupervisor,agentService:n,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:i.publicAsks});return c0(o.json(d))}),r}function Wse(e={}){let t=l0({id:"a2a",config:PMe,setup:(n)=>{let{config:o}=n,s=Xo(n),{servesHttp:a}=s,c=iOe(s,o,e),u={cardReady:!1,servesHttp:a,taskManager:new Lse,turnSupervisor:new zse,jwksResolver:new Fse(e.fetch?{fetch:e.fetch}:{}),clientDeps:c,publicAsks:new Nse(o.publicAsks,s.classRuntimeState)};if(eOe(s,c,{networkAskTimeoutMs:o.networkAskTimeoutMs}),a)s.endpoint({label:"A2A",url:"/a2a",priority:25}),s.interaction({id:"a2a",label:"A2A",description:"Let other agents discover and talk to this brain.",href:"/a2a",kind:"agent",priority:25}),s.logger.info("A2A interface registered",{domain:s.domain});else s.logger.info("A2A interface registered in tool-only mode",{domain:s.domain});return s.ready(()=>{u.cardReady=!0}),u}}),i=_c(t,(n)=>{let{config:o,state:s}=n;if(!s.servesHttp)return[];let a=Xo(n),c=a4i(a,o,s),u=(p)=>Promise.resolve(c.fetch(p)),d=(p,m)=>({path:p,method:m,public:!0,handler:u});return[d("/.well-known/agent-card.json","GET"),d("/.well-known/agent-directory.json","GET"),d("/a2a","GET"),d("/a2a","POST"),d("/a2a","OPTIONS")]}),r=Sf(i,(n)=>{let{state:o}=n,{logger:s}=Xo(n);return{id:"a2a",start:async()=>{if(o.servesHttp)s.info("A2A mounted on shared webserver host");else s.info("A2A running without webserver routes")},stop:async()=>{await o.turnSupervisor.close(),s.info("A2A server stopped")}}});return Co(r,(n)=>{let{config:o}=n,s=Xo(n),a=()=>QMe(iOe(s,o,e));return[{...a(),handler:(c,u)=>a().handler(c,u)}]})}var c4i=Wse(),nOe=c4i;function p0(e){if(typeof e!=="string"||!/^\d+$/u.test(e))return e;return Number(e)}function WE(e,t){return{registration:e,actionIds:t.map((i)=>i.name)}}var l4i=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"});function m0(e){return l4i.format(new Date(e))}function h0(e){let t=e.auth();if(!t)throw Error("Administration workspace requires auth-service");return t}function Qa(e){if(!e)throw Error("Administration action requires a signed-in actor");return{actorUserId:e.actor.id}}function Ij(e){return e.flatMap((t)=>t.status==="invited"?[]:[{userId:t.userId,displayName:t.displayName}])}function _w(e){if(!e)return"This brain";let t="did:web:";if(!e.startsWith(t))return e;let i=e.slice(t.length);if(i.length===0)return e;return i.split(":").map(decodeURIComponent).join("/")}var u4i={"auth.a2a_peer_trust.granted":"Trusted an A2A peer","auth.a2a_peer_trust.revoked":"Revoked A2A peer trust","auth.access.reinitialized":"Reinitialized access from configuration","auth.external_peer.invited":"Invited a person from an external peer","auth.external_peer.linked":"Linked an external peer","auth.external_peer.unlinked":"Unlinked an external peer","auth.invitation.created":"Person invited","auth.invitation.cancelled":"Invitation cancelled","auth.invitation.manual_delivery_confirmed":"Manual delivery confirmed","auth.invitation.resent":"Invitation resent","auth.identity.attached":"Connected an identity","auth.identity.detached":"Disconnected an identity","auth.identity.delivery_bound":"Bound a verified delivery channel","auth.passkey.authentication_failed":"Recorded a failed passkey sign-in","auth.passkey.migrated":"Migrated a passkey","auth.passkey.registered":"Registered a passkey","auth.passkey.registration_failed":"Recorded a failed passkey registration","auth.passkey.registration_started":"Created a passkey setup link","auth.passkey.revoked":"Revoked a passkey","auth.setup_token.generated":"Generated a setup token","auth.user.created":"Created an account","auth.user.deleted":"Deleted a suspended account","auth.user.grants_revoked":"Revoked account grants","auth.user.role_updated":"Role changed","auth.user.status_updated":"Changed account status"};function Eae(e){let t=u4i[e];if(t)return t;let i=e.replaceAll(/[._-]+/g," ").trim();return i.length===0?e:Wn(i)}var Aae=l.strictObject({actorUserId:l.string().trim().min(1).max(120).optional(),action:l.string().trim().min(1).max(200).optional(),selected:l.string().trim().min(1).max(120).optional(),offset:l.preprocess(p0,l.number().int().min(0).max(1e5)).default(0),limit:l.preprocess(p0,l.number().int().min(1).max(100)).default(25)}),oOe=l.strictObject({id:l.string().min(1),actorUserId:l.string().min(1).optional(),action:l.string().min(1),targetType:l.string().min(1).optional(),targetId:l.string().min(1).optional(),targetUserId:l.string().min(1).optional(),createdAt:l.number().int().nonnegative()}),d4i=l.strictObject({userId:l.string().min(1),displayName:l.string().min(1)}),p4i=l.strictObject({query:Aae,events:l.array(oOe),selectedEvent:oOe.optional(),users:l.array(d4i),actions:l.array(l.strictObject({value:l.string().min(1),label:l.string().min(1),count:l.number().int().nonnegative()})),total:l.number().int().nonnegative()});function sOe(e){let t=e.metadata?.userId;return{...typeof t==="string"&&t?{targetUserId:t}:{},id:e.id,...e.actorUserId?{actorUserId:e.actorUserId}:{},action:e.action,...e.targetType?{targetType:e.targetType}:{},...e.targetId?{targetId:e.targetId}:{},createdAt:e.createdAt}}function aOe(e,t){return e?t.get(e)??"Former Admin":"System"}function cOe(e,t){if(e.targetId)return t.get(e.targetId)??(e.targetUserId?t.get(e.targetUserId):void 0)??e.targetType??e.targetId;return e.targetType??"Access"}var bae=Go({id:"audit",label:"Audit",priority:90,permission:"admin",query:Aae,data:p4i,actions:[],view:({data:e})=>{let t=new Map(e.users.map((o)=>[o.userId,o.displayName])),i=e.selectedEvent,n=[{type:"query",id:"audit-filters",...{controls:[{key:"actorUserId",label:"Actor",value:e.query.actorUserId,allLabel:"All actors",options:e.users.map((o)=>({value:o.userId,label:o.displayName}))},{key:"action",label:"Action",value:e.query.action,allLabel:"All actions",options:e.actions}],...e.total>e.query.limit||e.query.offset>0?{pagination:{offset:e.query.offset,limit:e.query.limit,total:e.total}}:{}}},{type:"detail",id:"audit-detail",queryKey:"selected",empty:"Select an event to inspect its audit record.",...i?{open:{forId:i.id,title:Eae(i.action),blocks:[{type:"key-values",id:"audit-event-fields",items:[{label:"Actor",value:aOe(i.actorUserId,t)},{label:"Action",value:i.action},{label:"Target",value:cOe(i,t)},{label:"Occurred",value:m0(i.createdAt)},{label:"Event ID",value:i.id},{label:"Action ID",value:i.action},...i.targetId?[{label:"Target ID",value:i.targetId}]:[],...i.actorUserId?[{label:"Actor ID",value:i.actorUserId}]:[]]}]}}:{},master:{type:"list",id:"audit-events",presentation:"standard",empty:"No audit events match these filters.",items:e.events.map((o)=>({id:o.id,title:Eae(o.action),description:`${aOe(o.actorUserId,t)} \u2192 ${cOe(o,t)}`,metadata:[new Date(o.createdAt).toISOString()],links:[{label:"Details",target:{detail:{itemId:o.id}}}]}))}}];return{kicker:"Security history",title:"Audit",description:"Who changed access, what changed, and when.",status:{label:`${e.total} matching ${e.total===1?"event":"events"}`,tone:"neutral"},blocks:n}}});function lOe(e){let t=e.studio.source({definition:bae,bind:(i)=>bae.bind(i,{load:async({query:r})=>{let n=h0(e),o=r.get(Aae),[s,a]=await Promise.all([n.queryAuditEvents({...o.actorUserId?{actorUserId:o.actorUserId}:{},...o.action?{action:o.action}:{},...o.selected?{selectedId:o.selected}:{},offset:o.offset,limit:o.limit}),n.listUsers()]);return{query:o,events:s.events.map(sOe),...s.selectedEvent?{selectedEvent:sOe(s.selectedEvent)}:{},users:Ij(a),actions:s.actions.map(({action:c,count:u})=>({value:c,label:Eae(c),count:u})).sort((c,u)=>c.label.localeCompare(u.label)),total:s.total}},actions:[]})});return WE(t,bae.actions)}var _m=l.strictObject({status:l.string()}),_j=l.strictObject({status:l.string(),setupUrl:l.url(),expiresAt:l.string()});function P2(e){return{title:e,fields:{status:{label:"Status"},setupUrl:{label:"Single-use setup URL",copyable:!0,sensitive:!0},expiresAt:{label:"Expires"}}}}var Tj=l.strictObject({type:l.string(),displayName:l.string(),subjectLabel:l.string(),deliveryModes:l.array(l.enum(["automatic","manual"]))});function Pj(e){return Array.from(new Set(e.flatMap((t)=>t.deliveryModes)))}function Rj(e){return{label:e,control:"select",options:[{value:"trusted",label:"Trusted"},{value:"admin",label:"Admin"}]}}function Fj(e,t){return{deliveryType:{label:"Delivery channel",control:"select",options:e.map((i)=>({value:i.type,label:i.displayName}))},deliverySubject:{label:"Delivery destination",labelBy:{field:"deliveryType",values:e.map((i)=>({value:i.type,label:i.subjectLabel}))},control:"text"},deliveryLabel:{label:"Delivery label (optional)",control:"text"},deliveryMode:{label:"Delivery mode",control:"select",options:t.map((i)=>({value:i,label:i==="automatic"?"Automatic":"Manual"}))}}}import{randomUUID as m4i}from"crypto";var uOe=new Set(["claimed","expired","cancelled"]),h4i=new Set(["claimed","cancelled"]),Bae=l.strictObject({state:l.enum(["pending","history"]).optional().default("pending"),selected:l.string().trim().min(1).max(200).optional(),offset:l.preprocess(p0,l.number().int().min(0)).optional().default(0),limit:l.preprocess(p0,l.number().int().min(1).max(100)).optional().default(25)}),hOe=l.strictObject({status:l.string(),setupUrl:l.url().nullable(),expiresAt:l.string().nullable()}),f4i=l.strictObject({idempotencyKey:l.string().min(1),displayName:l.string().trim().min(1).max(200),role:l.enum(["admin","trusted"]),deliveryType:l.string().trim().min(1).max(100),deliverySubject:l.string().trim().min(1).max(500),deliveryLabel:l.string().trim().max(200).optional(),deliveryMode:l.enum(["automatic","manual"])}),fOe=l.strictObject({invitationId:l.string().min(1)}),x4i=l.strictObject({invitationId:l.string().min(1),deliveryAttemptId:l.string().min(1)}),xOe=l.strictObject({invitationId:l.string(),state:l.string()}),Sae=qi({name:"create-invitation",label:"Add a person",permission:"admin",input:f4i,output:hOe}),Cae=qi({name:"resend-invitation",label:"Resend",permission:"admin",catalog:!0,confirmation:{kind:"static",message:"Create a new single-use setup link for this invitation?"},input:fOe,output:hOe}),Dae=qi({name:"cancel-invitation",label:"Cancel",permission:"admin",confirmation:{kind:"prepared"},input:fOe,output:xOe}),Iae=qi({name:"confirm-manual-delivery",label:"Confirm delivered",permission:"admin",input:x4i,output:xOe}),dOe=l.strictObject({id:l.string(),displayName:l.string(),role:l.string(),state:l.string(),destination:l.string(),updatedAt:l.number(),deliveryAttemptId:l.string().optional()}),g4i=l.strictObject({query:Bae,idempotencyKey:l.string(),channels:l.array(Tj),invitations:l.array(dOe),selectedInvitation:dOe.optional(),selectedTotal:l.number().int().nonnegative(),pendingCount:l.number().int().nonnegative(),historyCount:l.number().int().nonnegative(),failureCount:l.number().int().nonnegative()});function kae(e,t){let i=e.filter((r)=>r.id===t);if(i.length!==1||!i[0])throw Error(`Invitations tab composition requires block "${t}" exactly once`);return i[0]}function vae(e,t){let i=kae(e,t);switch(i.type){case"tabs":case"detail":case"columns":throw Error(`Invitations tab composition block "${t}" must be a region`);default:return i}}function gOe(e,t){let i=kae(e,"invitation-totals");if(i.type!=="stats")throw Error('Invitations tab composition block "invitation-totals" must be stats');let r=e.some((a)=>a.id==="create-invitation-unavailable")?[vae(e,"create-invitation-unavailable")]:[],n=kae(e,"invitations");if(n.type!=="detail")throw Error("Invitations composition requires a detail collection");let o=vae(e,"invitation-delivery");if(o.type!=="card")throw Error("Invitations composition requires delivery capabilities");let s=t.flatMap((a)=>a.type==="card"?[...a.blocks]:[a]);return{blocks:[...r,vae(e,"invitation-filters"),n,{...o,presentation:"disclosure",blocks:[...o.blocks,i,...s]}]}}var yOe=P2("Invitation setup");function y4i(e){if(h4i.has(e.state))return[];return[...e.deliveryAttemptId?[{action:Iae,input:{invitationId:e.id,deliveryAttemptId:e.deliveryAttemptId}}]:[],...e.state!=="sending"?[{action:Cae,input:{invitationId:e.id},capability:{id:e.state==="failed"?"retry-invitation":"resend-invitation",label:e.state==="failed"?"Retry":"Resend"},result:yOe}]:[],...e.state!=="expired"?[{action:Dae,input:{invitationId:e.id}}]:[]]}function pOe(e){if(e.state==="pending"&&e.deliveryAttemptId)return"Manual delivery pending";if(e.state==="failed")return"Delivery failed";return Wn(e.state)}var wae=Go({id:"invitations",label:"Invitations",priority:11,permission:"admin",query:Bae,data:g4i,actions:[Sae,Cae,Dae,Iae],badge:({data:e})=>e.pendingCount,view:({data:e})=>{let t=[{type:"stats",id:"invitation-totals",items:[{label:"Pending",value:e.pendingCount},{label:"History",value:e.historyCount},{label:"Delivery failures",value:e.failureCount,tone:e.failureCount>0?"warn":"neutral"}]}],i=Pj(e.channels),r;if(e.channels.length>0&&i.length>0)r={action:Sae,input:{idempotencyKey:e.idempotencyKey},form:{presentation:"disclosure",submitLabel:"Create invitation",fields:{displayName:{label:"Display name",control:"text"},role:Rj("Role"),...Fj(e.channels,i)}},result:yOe};else t.push({type:"notice",id:"create-invitation-unavailable",tone:"warn",text:"No invitation delivery channel is currently available."});let n=e.selectedInvitation;return t.push({type:"query",id:"invitation-filters",controls:[{key:"state",label:"View",value:e.query.state,options:[{value:"pending",label:"Pending",count:e.pendingCount},{value:"history",label:"History",count:e.historyCount}]}],...e.selectedTotal>e.query.limit||e.query.offset>0?{pagination:{offset:e.query.offset,limit:e.query.limit,total:e.selectedTotal}}:{}},{type:"detail",id:"invitations",queryKey:"selected",empty:"Select an invitation to review its delivery.",master:{type:"list",id:"invitation-records",presentation:"standard",empty:e.query.state==="pending"?"No pending invitations.":"No invitation history yet.",items:e.invitations.map((o)=>({id:o.id,title:o.displayName,description:`${Wn(o.role)} \xB7 ${pOe(o)}`,metadata:[o.destination,`Updated ${new Date(o.updatedAt).toISOString()}`],links:[{label:"Review",target:{detail:{itemId:o.id}}}]}))},...n?{open:{forId:n.id,title:n.displayName,blocks:[{type:"key-values",id:"invitation-fields",items:[{label:"Role",value:Wn(n.role)},{label:"Delivery",value:pOe(n)},{label:"Destination",value:n.destination},{label:"Updated",value:m0(n.updatedAt)}]},{type:"actions",id:"invitation-actions",items:y4i(n)}]}}:e.query.selected?{open:{forId:e.query.selected,title:"Invitation unavailable",blocks:[{type:"notice",tone:"neutral",text:"This invitation is no longer available. Return to the list to choose another."}]}}:{}},{type:"card",id:"invitation-delivery",label:"Delivery capabilities",blocks:[{type:"key-values",items:e.channels.map((o)=>({label:o.displayName,value:o.deliveryModes.map(Wn).join(" \xB7 ")}))}]}),{kicker:"Access administration",title:"Invitations",description:"Create, deliver, retry, and revoke passkey invitations without moving auth authority into Studio.",status:{label:`${e.pendingCount} pending`,tone:e.failureCount>0?"warn":"neutral"},...r?{primaryAction:r}:{},blocks:t}}});function mOe(e){return{status:e.invitation.state==="sent"?"Delivery provider accepted the invitation.":e.invitation.state==="failed"?"Invitation saved, but delivery failed.":"Manual delivery is waiting for confirmation.",setupUrl:e.registration?.setupUrl??null,expiresAt:e.registration?new Date(e.registration.expiresAt*1000).toISOString():null}}function bOe(e){let t=h0(e),i=new Map,r=e.studio.source({definition:wae,bind:(n)=>{let o=Sae.bind(n,async({input:u,caller:d})=>{let p=await t.createInvitation({idempotencyKey:u.idempotencyKey,displayName:u.displayName,role:u.role,delivery:{type:u.deliveryType,subject:u.deliverySubject,...u.deliveryLabel?{label:u.deliveryLabel}:{},mode:u.deliveryMode}},Qa(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)i.set(p.invitation.id,p.registration.deliveryAttemptId);return mOe(p)}),s=Cae.bind(n,async({input:u,caller:d})=>{let p=await t.resendInvitation(u.invitationId,Qa(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)i.set(p.invitation.id,p.registration.deliveryAttemptId);return mOe(p)}),a=Dae.bind(n,async({input:u,caller:d})=>{let p=await t.cancelInvitation(u.invitationId,Qa(d));return i.delete(u.invitationId),{invitationId:p.id,state:p.state}},({input:u})=>({summary:"Cancel this invitation and revoke its pending setup link?",revision:u.invitationId})),c=Iae.bind(n,async({input:u,caller:d})=>{let p=await t.confirmManualInvitationDelivery(u.invitationId,u.deliveryAttemptId,Qa(d));return i.delete(u.invitationId),{invitationId:p.id,state:p.state}});return wae.bind(n,{actions:[o,s,a,c],load:async({query:u})=>{let d=u.get(Bae),[p,m]=await Promise.all([t.listAdminUsers(),t.listInvitationChannels()]),h=m.filter((R)=>R.deliveryModes.length>0),f=p.filter((R)=>R.invitation!==void 0),g=f.filter((R)=>R.invitation&&!uOe.has(R.invitation.state)),y=f.filter((R)=>R.invitation&&uOe.has(R.invitation.state)),b=d.state==="pending"?g:y,v=f.flatMap((R)=>{let O=R.invitation;if(!O)return[];let k=R.identities.find((L)=>L.type!=="passkey")?.label??R.externalPeers[0]?.peerId??"Not recorded",j=i.get(O.id);return[{id:O.id,displayName:R.displayName,role:R.role,state:O.state,destination:k,updatedAt:O.claimedAt??O.cancelledAt??O.expiredAt??O.sentAt??O.updatedAt,...j?{deliveryAttemptId:j}:{}}]}),w=new Map(v.map((R)=>[R.id,R])),D=d.selected?w.get(d.selected):void 0;return{query:d,idempotencyKey:m4i(),channels:h.map((R)=>({type:R.type,displayName:R.displayName,subjectLabel:R.subjectLabel,deliveryModes:R.deliveryModes})),invitations:b.slice(d.offset,d.offset+d.limit).flatMap((R)=>{let O=R.invitation?w.get(R.invitation.id):void 0;return O?[O]:[]}),...D?{selectedInvitation:D}:{},selectedTotal:b.length,pendingCount:g.length,historyCount:y.length,failureCount:g.filter((R)=>R.invitation?.state==="failed").length}}})}});return WE(r,wae.actions)}var Rae=l.strictObject({peerId:l.string().trim().max(2000).optional(),displayName:l.string().trim().max(200).optional()}),b4i=l.strictObject({peerId:l.string().trim().min(1).max(2000),displayName:l.string().trim().min(1).max(200),role:l.enum(["admin","trusted"]),deliveryType:l.string().trim().min(1).max(64),deliverySubject:l.string().trim().min(1).max(1000),deliveryLabel:l.string().trim().min(1).max(200).optional(),deliveryMode:l.enum(["automatic","manual"])}),E4i=l.strictObject({peerId:l.string().trim().min(1).max(2000),userId:l.string().min(1)}),Tae=qi({name:"invite-external-peer-person",label:"Invite peer person",permission:"admin",confirmation:{kind:"static",message:"Create this local member and bind them to the external peer?"},input:b4i,output:_j}),Pae=qi({name:"link-external-peer",label:"Link an existing person",permission:"admin",confirmation:{kind:"prepared"},input:E4i,output:_m}),A4i=l.strictObject({query:Rae,peers:l.array(l.strictObject({peerId:l.string(),displayName:l.string(),role:l.enum(["admin","trusted","public"]),verificationStatus:l.enum(["unverified","verified"]),createdAt:l.number()})),people:l.array(l.strictObject({userId:l.string(),displayName:l.string()})),channels:l.array(Tj)});function Mj(e,t){let i=e.filter((n)=>n.id===t);if(i.length!==1)throw Error(`Peer tab composition requires block "${t}" exactly once`);let r=i[0];if(!r)throw Error(`Peer tab composition requires block "${t}" exactly once`);switch(r.type){case"tabs":case"detail":case"columns":throw Error(`Peer tab composition block "${t}" must be a region`);default:return r}}function Fae(e){let t=e.some((i)=>i.id==="invite-peer")?"invite-peer":"invite-peer-unavailable";return{people:[Mj(e,"peers"),Mj(e,"link-peer"),Mj(e,t)],invitations:[Mj(e,t)]}}var v4i=P2("Peer invitation setup"),_ae=Go({id:"peers",label:"Peers",priority:12,permission:"admin",query:Rae,data:A4i,actions:[Tae,Pae],view:({data:e})=>{let t=Pj(e.channels),i=[{type:"stats",id:"peer-summary",items:[{label:"Linked peers",value:e.peers.length},{label:"Verified",value:e.peers.filter((r)=>r.verificationStatus==="verified").length},{label:"Available people",value:e.people.length}]}];if(e.channels.length>0&&t.length>0)i.push({type:"card",id:"invite-peer",label:"Peer-first invitation",blocks:[{type:"text",text:"Create a local member for a person known first through another brain, then issue their single-use passkey setup link."},{type:"action",action:Tae,input:{...e.query.peerId?{peerId:e.query.peerId}:{},...e.query.displayName?{displayName:e.query.displayName}:{}},form:{presentation:"disclosure",submitLabel:"Invite peer person",fields:{peerId:{label:"External peer ID",control:"text"},displayName:{label:"Display name",control:"text"},role:Rj("Local role"),...Fj(e.channels,t)}},result:v4i}]});else i.push({type:"notice",id:"invite-peer-unavailable",tone:"warn",text:"No invitation delivery channel is currently available."});return i.push({type:"card",id:"link-peer",label:"Link an existing person",blocks:[{type:"action",action:Pae,input:{...e.query.peerId?{peerId:e.query.peerId}:{}},form:{submitLabel:"Link peer",fields:{peerId:{label:"External peer ID",control:"text"},userId:{label:"Local person",control:"select",options:e.people.map((r)=>({value:r.userId,label:r.displayName}))}}}}]},{type:"table",id:"peers",empty:"No external peers linked.",columns:[{key:"peer",label:"Peer"},{key:"person",label:"Local person"},{key:"role",label:"Local role"},{key:"verification",label:"Verification"},{key:"linked",label:"Linked"}],rows:e.peers.map((r)=>({id:`${r.peerId}:${r.displayName}`,cells:{peer:_w(r.peerId),person:r.displayName,role:r.role,verification:r.verificationStatus,linked:m0(r.createdAt)},compact:{title:_w(r.peerId),metadata:[r.displayName,Wn(r.role),m0(r.createdAt)],badges:[{label:Wn(r.verificationStatus),tone:r.verificationStatus==="verified"?"good":"warn"}]}}))}),{kicker:"Network administration",title:"Peers",description:"List external brain relationships, invite peer-first people, and link known peers to existing members.",status:{label:`${e.peers.length} linked`},blocks:i}}});function EOe(e){let t=h0(e),i=e.studio.source({definition:_ae,bind:(r)=>{let n=Tae.bind(r,async({input:s,caller:a})=>{let c=await t.inviteExternalPeerPerson({peerId:s.peerId,displayName:s.displayName,role:s.role,delivery:{type:s.deliveryType,subject:s.deliverySubject,...s.deliveryLabel?{label:s.deliveryLabel}:{},mode:s.deliveryMode}},Qa(a));return{status:`Created ${c.user.displayName} and linked ${c.peer.peerId}. Deliver only through ${c.registration.delivery.label}.`,setupUrl:c.registration.setupUrl,expiresAt:new Date(c.registration.expiresAt*1000).toISOString()}}),o=Pae.bind(r,async({input:s,caller:a})=>(await t.linkExternalPeer({peerId:s.peerId,userId:s.userId},Qa(a)),{status:"External peer linked to the local person."}),async({input:s})=>{let c=(await t.listAdminUsers()).find((u)=>u.userId===s.userId)?.displayName??"person";return{summary:`Link ${s.peerId} to ${c}? Local access does not change.`,revision:`${s.peerId}:${s.userId}`}});return _ae.bind(r,{actions:[n,o],load:async({query:s})=>{let a=s.get(Rae),[c,u]=await Promise.all([t.listAdminUsers(),t.listInvitationChannels()]),d=c.filter((p)=>p.status!=="invited");return{query:a,peers:c.flatMap((p)=>p.externalPeers.map((m)=>({peerId:m.peerId,displayName:p.displayName,role:p.role,verificationStatus:m.verificationStatus,createdAt:m.createdAt}))),people:Ij(d),channels:u.filter((p)=>p.deliveryModes.length>0).map((p)=>({type:p.type,displayName:p.displayName,subjectLabel:p.subjectLabel,deliveryModes:p.deliveryModes}))}}})}});return WE(i,_ae.actions)}function Mae(e,t){let i=e.filter((r)=>r.id===t);if(i.length!==1||!i[0])throw Error(`People tab composition requires block "${t}" exactly once`);return i[0]}function AOe(e,t,i){let r=Mae(e,"people-summary");if(r.type!=="stats")throw Error('People tab composition block "people-summary" must be stats');let n=Mae(e,"people");if(n.type!=="detail")throw Error('People tab composition block "people" must be a detail');let o=Mae(e,"brain-anchor");if(o.type!=="card")throw Error('People tab composition block "brain-anchor" must be a card');let s=[t,...i].flatMap((a)=>a.type==="card"?[...a.blocks]:[a]);return{blocks:[n,{type:"card",id:"people-peers",label:"External brains",presentation:"disclosure",blocks:s},{...o,label:"Access reference",presentation:"disclosure",blocks:[r,...o.blocks]}]}}var Hae=l.strictObject({selected:l.string().trim().min(1).max(200).optional()}),Wae=l.strictObject({userId:l.string().min(1)}),w4i=l.strictObject({userId:l.string().min(1),role:l.enum(["admin","trusted","public"])}),S4i=l.strictObject({userId:l.string().min(1),status:l.enum(["active","suspended"])});function k4i(e){return e.revokedAt===void 0&&e.type!=="passkey"}function B4i(e){return e.credentialBackedUp?"Synced passkey":"Device passkey"}var C4i=l.strictObject({userId:l.string().min(1),credentialId:l.string().min(1)}),D4i=l.strictObject({userId:l.string().min(1),type:l.string().trim().min(1).max(64),subject:l.string().trim().min(1).max(2000),issuer:l.string().trim().min(1).max(2000).optional(),label:l.string().trim().min(1).max(200).optional()}),I4i=l.strictObject({userId:l.string().min(1),identityId:l.string().min(1)}),_4i=l.strictObject({userId:l.string().min(1),peerId:l.string().trim().min(1).max(2000)}),Lae=qi({name:"update-person-role",label:"Change role",permission:"admin",confirmation:{kind:"prepared"},input:w4i,output:_m}),zae=qi({name:"update-person-status",label:"Suspend person",permission:"admin",catalog:!0,confirmation:{kind:"prepared"},input:S4i,output:_m}),jae=qi({name:"delete-person",label:"Delete person",permission:"admin",confirmation:{kind:"prepared"},input:Wae,output:_m}),Uae=qi({name:"revoke-person-passkey",label:"Revoke passkey",permission:"admin",confirmation:{kind:"prepared"},input:C4i,output:_m}),Zae=qi({name:"start-person-passkey-registration",label:"Create setup link",permission:"admin",confirmation:{kind:"static",message:"Create a single-use passkey setup link for this person?"},input:Wae,output:_j}),qae=qi({name:"revoke-person-sessions",label:"Revoke all sessions",permission:"admin",confirmation:{kind:"prepared"},input:Wae,output:_m}),Vae=qi({name:"attach-person-identity",label:"Attach channel",permission:"admin",confirmation:{kind:"static",message:"Attach this verified channel identity to the selected person?"},input:D4i,output:_m}),$ae=qi({name:"detach-person-identity",label:"Detach channel",permission:"admin",confirmation:{kind:"prepared"},input:I4i,output:_m}),Gae=qi({name:"unlink-external-peer",label:"Unlink peer",permission:"admin",confirmation:{kind:"prepared"},input:_4i,output:_m}),T4i=l.strictObject({userId:l.string(),displayName:l.string(),role:l.enum(["admin","trusted","public"]),status:l.enum(["active","suspended"]),isAnchor:l.boolean(),isSelf:l.boolean(),profileEntityId:l.string().optional(),passkeys:l.array(l.strictObject({id:l.string(),kind:l.string(),createdAt:l.number()})),identities:l.array(l.strictObject({id:l.string(),type:l.string(),displayName:l.string(),label:l.string(),verified:l.boolean()})),peers:l.array(l.strictObject({peerId:l.string(),verificationStatus:l.enum(["unverified","verified"])}))}),P4i=l.strictObject({query:Hae,anchor:l.strictObject({kind:l.enum(["person","collective"]),configuredKind:l.enum(["person","team","organization"]),displayName:l.string(),administeredBy:l.number().int().nonnegative()}),people:l.array(T4i),activeCount:l.number().int().nonnegative(),activeAdminCount:l.number().int().nonnegative(),suspendedCount:l.number().int().nonnegative(),channelTypes:l.array(l.strictObject({type:l.string(),displayName:l.string()}))}),R4i=P2("Passkey setup");function F4i(){return{type:"links",items:[{label:"Manage your own credentials and sessions",target:{launch:{target:"account-settings"}}}]}}function Oae(e){return{type:"notice",tone:"warn",text:e}}function M4i(e){return{type:"action",action:Zae,input:{userId:e},result:R4i}}function O4i(e,t){return{type:"action",action:Vae,input:{userId:e},form:{submitLabel:"Attach channel",fields:{type:{label:"Channel type",control:"select",options:t.map((i)=>({value:i.type,label:i.displayName}))},subject:{label:"Channel subject",control:"text"},issuer:{label:"Issuer (optional)",control:"url"},label:{label:"Display label (optional)",control:"text"}}}}}function N4i(e,t){return{kind:"person",configuredKind:"person",displayName:e,administeredBy:t}}var Nae=Go({id:"people",label:"People",priority:10,permission:"admin",query:Hae,data:P4i,actions:[Lae,zae,jae,Uae,Zae,qae,Vae,$ae,Gae],badge:({data:e})=>e.suspendedCount,view:({data:e})=>{let t=e.people.find((n)=>n.userId===e.query.selected),i=[];if(t){let n=t.role==="admin"&&t.status==="active"&&e.activeAdminCount<=1,o=t.isAnchor?"The protected brain identity must remain an active Admin.":t.status==="suspended"?"Reactivate this person before changing access.":n?"Add another active Admin before changing this role.":void 0,s=t.isAnchor?"The protected brain identity cannot be suspended.":n?"Add another active Admin before suspending this person.":void 0;if(i.push({type:"key-values",id:"person-summary",items:[{label:"Role",value:Wn(t.role)},{label:"Status",value:Wn(t.status)},{label:"Protected brain identity",value:t.isAnchor},{label:"Brain relationship",value:t.peers.length>0?"External peer + local member":"Hosted member"}]}),o)i.push({type:"notice",tone:"warn",text:o});else i.push({type:"card",id:"person-role",label:"Permission role",blocks:[{type:"action",action:Lae,input:{userId:t.userId,role:t.role},form:{submitLabel:"Change role",fields:{role:{label:"Role",control:"select",options:[{value:"admin",label:"Admin"},{value:"trusted",label:"Trusted"},{value:"public",label:"Public"}]}}}}]});i.push({type:"card",id:"person-access",label:"Access",blocks:[{type:"actions",items:[{action:zae,input:{userId:t.userId,status:t.status==="suspended"?"active":"suspended"},capability:{id:t.status==="suspended"?"reactivate-person":"suspend-person",label:t.status==="suspended"?"Reactivate person":"Suspend person"},disabled:t.status==="active"&&s!==void 0},...t.status==="active"&&!t.isSelf?[{action:qae,input:{userId:t.userId}}]:[],...t.status==="suspended"?[{action:jae,input:{userId:t.userId}}]:[]]},...t.isSelf?[F4i()]:[],...s&&t.status==="active"?[Oae(s)]:[]]}),i.push({type:"card",id:"person-sign-in",label:"Sign-in",blocks:[{type:"table",id:"person-passkeys",empty:"No passkeys registered.",columns:[{key:"kind",label:"Passkey"},{key:"created",label:"Added"}],rows:t.passkeys.map((a)=>({id:a.id,cells:{kind:a.kind,created:m0(a.createdAt)},compact:{title:a.kind,metadata:[`Added ${m0(a.createdAt)}`]},actions:t.status==="active"&&!t.isSelf?[{action:Uae,input:{userId:t.userId,credentialId:a.id}}]:[]}))},...t.status==="active"&&!t.isSelf?t.identities.some((a)=>a.verified)?[M4i(t.userId)]:[Oae("A verified channel is required for setup delivery.")]:[]]}),i.push({type:"card",id:"person-channels",label:"Linked identities",blocks:[{type:"table",id:"person-identities",empty:"No linked identity.",columns:[{key:"channel",label:"Channel"},{key:"identity",label:"Identity"},{key:"assurance",label:"Assurance"}],rows:t.identities.map((a)=>({id:a.id,cells:{channel:a.displayName,identity:a.label,assurance:a.verified?"Verified":"Asserted"},compact:{title:a.label,metadata:[a.displayName],badges:[{label:a.verified?"Verified":"Asserted",tone:a.verified?"good":"neutral"}]},actions:[{action:$ae,input:{userId:t.userId,identityId:a.id}}]}))},...e.channelTypes.length>0?[O4i(t.userId,e.channelTypes)]:[Oae("No attachable channel type is configured.")]]}),i.push({type:"notice",tone:"neutral",text:"External peer links record provenance from another brain. They do not grant or change this person's local access."}),i.push({type:"list",id:"person-peers",empty:"No external peer linked; this person is hosted locally.",items:t.peers.map((a)=>({id:a.peerId,title:_w(a.peerId),description:`Vouched in by ${_w(a.peerId)} \xB7 ${a.peerId}`,metadata:[Wn(a.verificationStatus)],actions:[{action:Gae,input:{userId:t.userId,peerId:a.peerId}}]}))})}let r=[{type:"stats",id:"people-summary",items:[{label:"Active members",value:e.activeCount},{label:"Active Admins",value:e.activeAdminCount},{label:"Suspended",value:e.suspendedCount,tone:e.suspendedCount>0?"warn":"neutral"}]},{type:"card",id:"brain-anchor",label:"Brain identity",blocks:[{type:"key-values",items:[{label:"Name",value:e.anchor.displayName},{label:"Kind",value:e.anchor.configuredKind},{label:"Ownership",value:e.anchor.kind},{label:"Administered by",value:e.anchor.administeredBy}]}]},{type:"detail",id:"people",queryKey:"selected",empty:"Select a person to inspect their access.",master:{type:"list",id:"people-roster",presentation:"standard",empty:"No people are available.",items:[...e.people].sort((n,o)=>Number(o.isSelf)-Number(n.isSelf)||Number(n.isAnchor)-Number(o.isAnchor)||n.displayName.localeCompare(o.displayName)).map((n)=>({id:n.userId,title:n.displayName,description:[Wn(n.role),Wn(n.status),...n.isSelf?["You"]:[],...n.isAnchor?["Protected brain identity"]:[]].join(" \xB7 "),metadata:[n.identities.length===0?"No linked identities":n.identities.length===1?"One linked identity":`${n.identities.length} linked identities`,...n.peers.length>0?[`Arrived via ${_w(n.peers[0]?.peerId)}`]:[]],...n.isSelf?{link:{detail:{itemId:n.userId}}}:{},links:[{label:n.isSelf?"Account \u2192":n.isAnchor?"View protection":"Manage person",target:n.isSelf?{launch:{target:"account-settings"}}:{detail:{itemId:n.userId}}}]}))},...t?{open:{forId:t.userId,title:t.displayName,blocks:i}}:{}}];return{kicker:"Access administration",title:"People",description:"Manage people\u2019s access to this brain, linked identities, and account recovery. Use Account for your own profile and sign-in settings.",status:{label:`${e.activeCount} active`,tone:e.suspendedCount>0?"warn":"neutral"},blocks:r}}});function Oj(e,t){return e.find((i)=>i.userId===t)?.displayName??"person"}async function L4i(e){try{return await e.getBrainAnchor()}catch(t){if(t instanceof Error&&t.message==="Brain anchor is not configured")return;throw t}}function vOe(e){let t=h0(e),i=e.studio.source({definition:Nae,bind:(r)=>{let n=Lae.bind(r,async({input:h,caller:f})=>(await t.updateUserRole(h.userId,h.role,Qa(f)),{status:`Role changed to ${Wn(h.role)}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Change ${Oj(f,h.userId)}\u2019s role to ${Wn(h.role)}?`,revision:`${h.userId}:${h.role}`}}),o=zae.bind(r,async({input:h,caller:f})=>(await t.updateUserStatus(h.userId,h.status,Qa(f)),{status:`Person ${h.status}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`${h.status==="active"?"Reactivate":"Suspend"} ${Oj(f,h.userId)}?`,revision:`${h.userId}:${h.status}`}}),s=jae.bind(r,async({input:h,caller:f})=>(await t.deleteSuspendedUser(h.userId,Qa(f)),{status:"Suspended person permanently deleted."}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Permanently delete ${Oj(f,h.userId)}? Audit history is retained.`,revision:h.userId}}),a=Uae.bind(r,async({input:h,caller:f})=>(await t.revokePasskey(h.credentialId,Qa(f)),{status:"Passkey revoked."}),({input:h})=>({summary:"Revoke this passkey immediately?",revision:`${h.userId}:${h.credentialId}`})),c=Zae.bind(r,async({input:h,caller:f})=>{let g=await t.startPasskeyRegistrationForUser(h.userId,Qa(f));return{status:`Bound to ${g.delivery.label}. Deliver only through that confirmed private channel.`,setupUrl:g.setupUrl,expiresAt:new Date(g.expiresAt*1000).toISOString()}}),u=qae.bind(r,async({input:h,caller:f})=>{let g=await t.revokeUserSessionsAndRefreshTokens(h.userId,Qa(f));return{status:`Revoked ${g.sessions} sessions and ${g.refreshTokens} refresh tokens.`}},async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Sign ${Oj(f,h.userId)} out everywhere?`,revision:h.userId}}),d=Vae.bind(r,async({input:h,caller:f})=>(await t.attachIdentity({userId:h.userId,type:h.type,subject:h.subject,...h.issuer?{issuer:h.issuer}:{},...h.label?{label:h.label}:{},verifiedAt:Date.now(),source:{kind:"admin"}},Qa(f)),{status:"Verified channel attached."})),p=$ae.bind(r,async({input:h,caller:f})=>(await t.detachIdentity(h.identityId,Qa(f)),{status:"Channel detached."}),({input:h})=>({summary:"Detach this channel identity?",revision:`${h.userId}:${h.identityId}`})),m=Gae.bind(r,async({input:h,caller:f})=>(await t.unlinkExternalPeer(h,Qa(f)),{status:"External peer unlinked from the local person."}),({input:h})=>({summary:`Unlink ${h.peerId}? Local access will not change.`,revision:`${h.peerId}:${h.userId}`}));return Nae.bind(r,{actions:[n,o,s,a,c,u,d,p,m],load:async({query:h,caller:f})=>{let g=h.get(Hae),[y,b,v]=await Promise.all([L4i(t),t.listAdminUsers(),t.listInvitationChannels()]),w=b.filter((j)=>j.status!=="invited"),D=w.find((j)=>j.isAnchor)??w.find((j)=>j.role==="admin"&&j.status==="active"),R=y??N4i(D?.displayName??"Brain owner",w.filter((j)=>j.role==="admin"&&j.status==="active").length),O=w.filter((j)=>j.status==="active"),k=new Map(v.map((j)=>[j.type,j.displayName]));return{query:g,anchor:{kind:R.kind,configuredKind:R.configuredKind,displayName:R.displayName,administeredBy:R.administeredBy},people:w.flatMap((j)=>{if(j.status==="invited")return[];return[{userId:j.userId,displayName:j.displayName,role:j.role,status:j.status,isAnchor:j.isAnchor,isSelf:f?.actor.id===j.userId,...j.profileEntityId?{profileEntityId:j.profileEntityId}:{},passkeys:j.passkeys.map((L)=>({id:L.id,kind:B4i(L),createdAt:L.createdAt})),identities:j.identities.filter(k4i).map((L)=>({id:L.id,type:L.type,displayName:k.get(L.type)??Wn(L.type),label:L.label??"Connected identity",verified:L.verifiedAt!==void 0})),peers:j.externalPeers.map((L)=>({peerId:L.peerId,verificationStatus:L.verificationStatus}))}]}),activeCount:O.length,activeAdminCount:O.filter((j)=>j.role==="admin").length,suspendedCount:w.length-O.length,channelTypes:v.map((j)=>({type:j.type,displayName:j.displayName}))}}})}});return WE(i,Nae.actions)}var z4i=l.strictObject({tab:l.enum(["people","invitations","audit"]).default("people"),selected:l.string().trim().min(1).max(200).optional(),state:l.enum(["pending","history"]).optional(),offset:l.preprocess(p0,l.number().int().min(0).max(1e5)).optional(),limit:l.preprocess(p0,l.number().int().min(1).max(100)).optional(),peerId:l.string().trim().max(2000).optional(),displayName:l.string().trim().max(200).optional(),actorUserId:l.string().trim().min(1).max(120).optional(),action:l.string().trim().min(1).max(200).optional()});function j4i(e){if(e===null||typeof e!=="object")return;let t=Reflect.get(e,"actionId");return typeof t==="string"?t:void 0}function U4i(e){if(e===null||typeof e!=="object")return!1;let t=Reflect.get(e,"view");if(t===null||typeof t!=="object")return!1;return Array.isArray(Reflect.get(t,"blocks"))}function q4i(e,t){if(!U4i(e))throw Error(`${t} tab returned invalid workspace data`);return e}function wOe(e,t){let i=[];for(let r of e){if(r.type==="tabs")throw Error(`${t} tab cannot contribute nested tabs`);i.push(r)}return i}function Kae(e){return[{type:"text",text:`${e} loads when this tab is opened.`}]}async function _I(e,t,i,r){return q4i(await e.dataProvider(t,i,r),e.label)}async function $4i(e,t,i,r){if(!e.actionHandler)throw Error(`${e.label} does not provide actions`);return e.actionHandler(t,i,r)}function G4i(e){let t=new Map;for(let i of e)for(let r of i.actionIds){if(t.has(r))throw Error(`Administration action "${r}" is declared by more than one source`);if(!i.registration.actionHandler)throw Error(`Administration source "${i.registration.label}" declares actions without a handler`);t.set(r,i.registration)}return t}function H4i(e){let t=e.filter((r)=>r.status==="suspended").length,i=e.filter((r)=>r.invitation!==void 0&&!["claimed","expired","cancelled"].includes(r.invitation.state)).length;return t+i}async function SOe(e){if(!e.studio.isAvailable())return;let t=vOe(e),i=bOe(e),r=EOe(e),n=lOe(e),o=G4i([t,i,r,n]),s=t.registration,a=i.registration,c=r.registration,u=n.registration;return e.studio.register({id:"admin:administration",label:"Administration",rendererName:EI,priority:10,permission:"admin",urlQuery:!0,aliases:[{id:"admin:people",query:{tab:"people"}},{id:"admin:invitations",query:{tab:"invitations"}},{id:"admin:peers",query:{tab:"people"}},{id:"admin:audit",query:{tab:"audit"}}],entityTypes:[],accessHandler:(d)=>s.accessHandler(d),dataProvider:async(d,p,m)=>{let h=z4i.parse(p??{}),f,g=Kae("People"),y=Kae("Invitations"),b=Kae("Audit");if(h.tab==="people"){let[v,w]=await Promise.all([_I(s,d,{...h.selected?{selected:h.selected}:{}},m),_I(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),D=Fae(w.view.blocks);g=[...AOe(wOe(v.view.blocks,"People"),{type:"notice",id:"people-peer-note",tone:"neutral",title:"External brain relationships",text:"A peer link records how a locally administered person relates to another brain. It does not grant or change local access."},D.people).blocks]}else if(h.tab==="invitations"){let[v,w]=await Promise.all([_I(a,d,{...h.state?{state:h.state}:{},...h.selected?{selected:h.selected}:{},...gl({offset:h.offset,limit:h.limit})},m),_I(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),D=Fae(w.view.blocks),R=gOe(v.view.blocks,D.invitations);f=v.view.primaryAction,y=[...R.blocks]}else{let v=await _I(u,d,{...h.actorUserId?{actorUserId:h.actorUserId}:{},...h.action?{action:h.action}:{},...h.selected?{selected:h.selected}:{},...gl({offset:h.offset,limit:h.limit})},m);b=wOe(v.view.blocks,"Audit")}return{view:{kicker:"Access administration",title:"Administration",description:"Manage people, invitations, and access to this brain. Use Account for your own profile, sign-in security, and personal settings.",...f?{primaryAction:f}:{},blocks:[{type:"tabs",id:"administration-tabs",label:"Administration sections",defaultTab:h.tab,queryKey:"tab",tabs:[{id:"people",label:"People",blocks:g},{id:"invitations",label:"Invitations",blocks:y},{id:"audit",label:"Access activity",blocks:b}]}]}}},actionHandler:async(d,p,m)=>{let h=j4i(d);if(!h)throw new Ni("invalid_input",{publicMessage:"Administration action id is required"});let f=o.get(h);if(!f)throw new Ni("not_found",{publicMessage:`Unknown Administration action: ${h}`});return $4i(f,d,p,m)},badgeProvider:async()=>H4i(await h0(e).listAdminUsers())})}var W4i=259200000,Z4i=l.strictObject({id:l.string(),displayName:l.string(),state:l.string(),reason:l.enum(["expiring","delivery-failed"]),expiresAt:l.number().optional()}),V4i=l.strictObject({invitations:l.array(Z4i),expiringCount:l.number().int().nonnegative(),failureCount:l.number().int().nonnegative()}),kOe=Nn({id:"expiring-invitations",title:"Invitations",description:"Setup links that expire soon or need delivery attention",group:"access",placement:"primary",priority:5,permission:"admin",data:V4i,digest:({data:e})=>({items:[{label:"Expiring soon",value:String(e.expiringCount),...e.expiringCount>0?{tone:"warn"}:{}},{label:"Delivery failures",value:String(e.failureCount),...e.failureCount>0?{tone:"warn"}:{}}],attention:e.invitations.length}),view:({data:e})=>({blocks:[{type:"stats",items:[{label:"Expiring soon",value:e.expiringCount,tone:e.expiringCount>0?"warn":"good"},{label:"Delivery failures",value:e.failureCount,tone:e.failureCount>0?"warn":"good"}]},{type:"list",id:"invitation-attention",empty:"No invitation setup links need attention.",items:e.invitations.map((t)=>({id:t.id,title:t.displayName,description:t.reason==="delivery-failed"?"Invitation delivery failed. Resend or cancel it.":"The single-use setup link expires soon.",metadata:[t.state,...t.expiresAt!==void 0?[`Expires ${m0(t.expiresAt)}`]:[]],tone:t.reason==="delivery-failed"?"error":"warn",link:{launch:{target:"invitations"}}}))},{type:"links",items:[{label:"Open Invitations",target:{launch:{target:"invitations"}}}]}]})});function K4i(e,t){let i=e.flatMap((r)=>{let n=r.invitation;if(!n)return[];if(n.state==="failed")return[{id:n.id,displayName:r.displayName,state:n.state,reason:"delivery-failed",...n.expiresAt!==void 0?{expiresAt:n.expiresAt}:{}}];if(!["pending","sending","sent"].includes(n.state)||n.expiresAt===void 0||n.expiresAt<=t||n.expiresAt>t+W4i)return[];return[{id:n.id,displayName:r.displayName,state:n.state,reason:"expiring",expiresAt:n.expiresAt}]});return i.sort((r,n)=>(r.expiresAt??Number.MAX_SAFE_INTEGER)-(n.expiresAt??Number.MAX_SAFE_INTEGER)||r.displayName.localeCompare(n.displayName)),{invitations:i,expiringCount:i.filter((r)=>r.reason==="expiring").length,failureCount:i.filter((r)=>r.reason==="delivery-failed").length}}async function BOe(e,t){t.throwIfAborted();let i=await h0(e).listAdminUsers();return t.throwIfAborted(),K4i(i,Date.now())}var Y4i=l.strictObject({}),J4i=xi({id:"admin",config:Y4i},{subscriptions:(e)=>{let t=Gt(e);return t.registered(async()=>{await SOe(t)}),[]},dashboardWidgets:(e)=>{let t=Gt(e);return[kOe.bind(e,({signal:i})=>BOe(t,i))]}}),Yae=J4i;var nn="agent";var COe="agent-network",DOe="agent-proximity",pce="agent-discovery:entities",IOe="agent-discovery:proximity-map",mce="proximity-map",hce="agent-list",fce="agent-detail",Xa="skill",_Oe=30,TOe=120;var Lj="skill-derivation",POe="skill-derivation",xce="skill:skill-derivation",ROe="skills";var Q4i=l.string().trim().min(1).max(TOe),gce=l.array(Q4i).max(_Oe),VE=l.object({name:l.string(),description:l.string(),tags:gce,examples:l.array(l.string())}),F2=VE,KE=Tm.extend({entityType:l.literal(Xa),metadata:F2});var zj=l.object({name:l.string(),description:l.string(),tags:gce}),Vg=l.enum(["discovered","approved","archived"]).describe("Discovered for review, approved for calling, or archived"),X4i=Dw,Fm=l.object({name:l.string(),kind:X4i,organization:l.string().optional(),brainName:l.string().describe("Name of the brain instance"),url:l.string().url().describe("Brain endpoint URL"),repoDid:l.string().optional().meta({description:"ATProto repo DID",studioWidget:"provenance"}),brainDid:l.string().optional().meta({description:"ATProto brain DID",studioWidget:"provenance"}),cardUri:l.string().optional().meta({description:"ATProto brain card URI",studioWidget:"provenance"}),cardCid:l.string().optional().meta({description:"ATProto brain card CID",studioWidget:"provenance"}),cardLastError:l.string().optional().meta({description:"Last ATProto brain card refresh error",studioWidget:"hidden"}),cardFailureCount:l.number().int().nonnegative().optional().meta({description:"Consecutive ATProto brain card refresh failures",studioWidget:"hidden"}),cardUnavailableAt:l.string().datetime().optional().meta({description:"When the remote ATProto brain card became unavailable",studioWidget:"hidden"}),cardStaleAfter:l.string().datetime().optional().meta({description:"When a never-approved unavailable card may be archived",studioWidget:"hidden"}),status:Vg,discoveredAt:l.string().datetime().meta({description:"When this agent was first discovered",studioWidget:"provenance"}),introducedBy:l.array(l.string()).optional().meta({description:"Agent ids of the peers whose directories reported this agent",studioWidget:"provenance"}),hops:l.number().int().min(2).optional().meta({description:"Discovery order: 2 = sighted through a first-order peer",studioWidget:"provenance"})}),LI=l.object({name:l.string(),url:l.string().url(),status:Vg,discoveredAt:l.string().datetime().optional(),slug:l.string(),repoDid:l.string().optional(),brainDid:l.string().optional(),cardUri:l.string().optional(),cardCid:l.string().optional(),cardLastError:l.string().optional(),cardFailureCount:l.number().int().nonnegative().optional(),cardUnavailableAt:l.string().datetime().optional(),cardStaleAfter:l.string().datetime().optional()}),Do=Tm.extend({entityType:l.literal(nn),metadata:LI}),e3i=Mi.extend({entityType:l.literal(nn),metadata:LI}),zI=e3i.extend({frontmatter:Fm,about:l.string(),skills:l.array(zj),notes:l.string()}),t3i=zI.extend({url:l.string().optional(),typeLabel:l.string().optional()}),i3i=zI.extend({url:l.string(),typeLabel:l.string()});var r3i=l.record(l.string(),l.unknown());function n3i(e){try{return xn(e,r3i).content}catch{return e}}function yce(e){return{name:e.name,url:e.url,status:e.status,discoveredAt:e.discoveredAt,slug:M2(e.url),...e.repoDid&&{repoDid:e.repoDid},...e.brainDid&&{brainDid:e.brainDid},...e.cardUri&&{cardUri:e.cardUri},...e.cardCid&&{cardCid:e.cardCid},...e.cardLastError&&{cardLastError:e.cardLastError},...e.cardFailureCount!==void 0&&{cardFailureCount:e.cardFailureCount},...e.cardUnavailableAt&&{cardUnavailableAt:e.cardUnavailableAt},...e.cardStaleAfter&&{cardStaleAfter:e.cardStaleAfter}}}function FOe(e){return Ia(nn,e,Fm)}function jI(e){return{content:e,metadata:yce(FOe(e))}}function O2(e){let t={name:e.name,kind:e.kind,...e.organization&&{organization:e.organization},brainName:e.brainName,url:e.url,...e.repoDid&&{repoDid:e.repoDid},...e.brainDid&&{brainDid:e.brainDid},...e.cardUri&&{cardUri:e.cardUri},...e.cardCid&&{cardCid:e.cardCid},...e.cardLastError&&{cardLastError:e.cardLastError},...e.cardFailureCount!==void 0&&{cardFailureCount:e.cardFailureCount},...e.cardUnavailableAt&&{cardUnavailableAt:e.cardUnavailableAt},...e.cardStaleAfter&&{cardStaleAfter:e.cardStaleAfter},status:Vg.parse(e.status),discoveredAt:e.discoveredAt,...e.introducedBy?.length&&{introducedBy:e.introducedBy},...e.hops!==void 0&&{hops:e.hops}},i=yae({about:e.about,skills:e.skills,notes:e.notes});return fn(i,t)}function Fw(e,t={}){return O2({...e.frontmatter,...e.body,...t})}function UI(e){return II(n3i(e))}function od(e){return{frontmatter:FOe(e.content),body:UI(e.content)}}function bce(e){return fn("",e)}function s3i(e,t){if(t.count!==e.count)return t.count-e.count;return e.tag.localeCompare(t.tag)}function MOe(e,t,i={}){let r=i.minCount??1,n=i.topN??12,o=new Map,s=(a)=>{for(let c of Ta(a))o.set(c,(o.get(c)??0)+1)};for(let a of e)s(a.metadata.tags);for(let a of t){let c=UI(a.content);s(c.skills.flatMap((u)=>u.tags))}return Array.from(o.entries()).map(([a,c])=>({tag:a,count:c})).filter((a)=>a.count>=r).sort(s3i).slice(0,n)}function OOe(e){if(e.length===0)return"";return["Current agent-directory tag vocabulary (reuse existing tags where they fit; propose new only when nothing does):",...e.map(({tag:t,count:i})=>`- ${t} (${i})`)].join(`
1025
1025
  `)}function N2(e,t={}){let i=e.anchor?.name??e.brainName,r=e.anchor?.category??"person",n=[];if(e.anchor?.description)n.push(e.anchor.description);if(e.description)n.push(e.description);let o=t.status??"discovered",s=new Date().toISOString();return{content:O2({name:i,kind:r,...e.anchor?.organization&&{organization:e.anchor.organization},brainName:e.brainName,url:e.url,status:o,discoveredAt:s,...t.provenance&&{introducedBy:t.provenance.introducedBy,hops:t.provenance.hops},about:n.join(`
1026
1026
 
1027
1027
  `),skills:e.skills.map((c)=>({name:c.name,description:c.description,tags:Ta(c.tags)})),notes:""}),metadata:{name:i,url:e.url,status:o,discoveredAt:s,slug:M2(e.url)},anchorName:i}}function YE(e){let t=e.trim();if(t.startsWith("http://")||t.startsWith("https://"))try{return new URL(t).hostname}catch{return t}let i=t.match(/https?:\/\/[^\s]+?(?=[.,;:!?)]*(?:\s|$))/);if(i)try{return new URL(i[0]).hostname}catch{return i[0]}if(/^[^\s]+\.[^\s]+$/.test(t))return t;return""}var a3i=l.object({prompt:l.string().optional(),url:l.string().optional(),content:l.string().optional(),skipAi:l.boolean().optional(),status:l.enum(["discovered","approved","archived"]).optional()});function NOe(e){return{input:a3i,generate:async({input:t})=>{let i=YE(t.url??t.prompt??"");if(!i)return{success:!1,error:"No URL or domain provided. Use: system_create agent with a domain like yeehaa.io"};let r=await wf(i,{fetch:e??globalThis.fetch});if(!r.ok)return{success:!1,error:qE(r.reason)?r.error:`Could not fetch Agent Card from ${i}. Make sure the agent is running and accessible.`};let{content:n,metadata:o}=N2(r.card,{...t.status!==void 0?{status:t.status}:{}});return{success:!0,id:i,content:n,metadata:o}}}}var Ece=_a({header:Fm,deriveMetadata:yce,readAsWritten:!0}),c3i=Ece.decode;Object.assign(Ece,{decode:(e)=>c3i({...e,content:e.content.replace(/^\n+/u,"")})});function Ace(e){return Ln(lce(Qi(zt({type:nn,classification:"system",purpose:"A saved remote peer-brain contact in the local agent directory.",metadata:LI,markdown:Ece,config:{projectionSourceRole:"supporting",retiredFields:["cardObservedAt","cardLastCheckedAt","a2aEndpoint","did","anchorDid"]},generation:NOe(e)}),Fm),["approved"]))}var l3i=l.object({skills:l.array(VE).max(8)}),jj=nt({name:"skill:skill-derivation",description:"Derive skills from topic titles and brain capabilities",dataSourceId:"shell:ai-content",schema:l3i,useKnowledgeContext:!0,basePrompt:`You are analyzing a brain's content to identify its high-level capabilities.
@@ -2951,6 +2951,7 @@ See https://react.dev/link/invalid-hook-call for tips about how to debug and fix
2951
2951
  .x6jxa94:not(#\\#):not(#\\#):not(#\\#):not(#\\#){width:14px}
2952
2952
  .x1kky2od:not(#\\#):not(#\\#):not(#\\#):not(#\\#){width:16px}
2953
2953
  .x1xp8n7a:not(#\\#):not(#\\#):not(#\\#):not(#\\#){width:18px}
2954
+ .xvy4d1p:not(#\\#):not(#\\#):not(#\\#):not(#\\#){width:24px}
2954
2955
  .xgd8bvy:not(#\\#):not(#\\#):not(#\\#):not(#\\#){width:28px}
2955
2956
  .xfo62xy:not(#\\#):not(#\\#):not(#\\#):not(#\\#){width:2px}
2956
2957
  .x1td3qas:not(#\\#):not(#\\#):not(#\\#):not(#\\#){width:32px}
@@ -4716,7 +4717,7 @@ Mx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7rkpeDMdmztcpH
4716
4717
  WD9f
4717
4718
  -----END CERTIFICATE-----
4718
4719
  `;class $Je{constructor(){Object.defineProperty(this,"pemCertificates",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.pemCertificates=new Map}setRootCertificates(e){let{identifier:t,certificates:i}=e,r=[];for(let n of i)if(n instanceof Uint8Array)r.push(oa(n));else r.push(n);this.pemCertificates.set(t,r)}getRootCertificates(e){let{identifier:t}=e;return this.pemCertificates.get(t)??[]}}var YA=new $Je;YA.setRootCertificates({identifier:"android-key",certificates:[NJe,LJe,zJe,jJe]});YA.setRootCertificates({identifier:"android-safetynet",certificates:[OJe]});YA.setRootCertificates({identifier:"apple",certificates:[UJe]});YA.setRootCertificates({identifier:"mds",certificates:[qJe]});async function GJe(e){let t=RJe(e),i=t[0],r=t[1],n=i.x5c.map(oa);try{let m=YA.getRootCertificates({identifier:"mds"});await Fl(n,m)}catch(m){throw Error("BLOB certificate path could not be validated",{cause:m})}let o=n[0];if(!await FJe(e,MJe(o)))throw Error("BLOB signature could not be verified");let a=[];for(let m of r.entries)if(m.aaguid&&m.metadataStatement)a.push(m.metadataStatement);let[c,u,d]=r.nextUpdate.split("-"),p=new Date(parseInt(c,10),parseInt(u,10)-1,parseInt(d,10));return{statements:a,parsedNextUpdate:p,payload:r}}async function HJe(e){let{cosePublicKey:t,signature:i,data:r}=e,n=await I0(),o=t.get(Di.alg),s=t.get(Di.crv),a=t.get(Di.x);if(!o)throw Error("Public key was missing alg (OKP)");if(!Gf(o))throw Error(`Public key had invalid alg ${o} (OKP)`);if(!s)throw Error("Public key was missing crv (OKP)");if(!a)throw Error("Public key was missing x (OKP)");let c;if(s===_l.ED25519)c="Ed25519";else throw Error(`Unexpected COSE crv value of ${s} (OKP)`);let u={kty:"OKP",crv:c,alg:"EdDSA",x:Ti.fromBuffer(a),ext:!1},p=await q9({keyData:u,algorithm:{name:c,namedCurve:c}}),m={name:c};return n.subtle.verify(m,p,i,r)}function ZJe(e,t){let i=Mo.parse(e,UA),r=new Uint8Array(i.r),n=new Uint8Array(i.s),o=p$i(t),s=WJe(r,o),a=WJe(n,o);return li.concat([s,a])}function p$i(e){switch(e){case _l.P256:return 32;case _l.P384:return 48;case _l.P521:return 66;default:throw Error(`Unexpected COSE crv value of ${e} (EC2)`)}}function WJe(e,t){let i;if(e.length<t)i=new Uint8Array(t),i.set(e,t-e.length);else if(e.length===t)i=e;else if(e.length===t+1&&e[0]===0&&(e[1]&128)===128)i=e.subarray(1);else throw Error(`Invalid signature component length ${e.length}, expected ${t}`);return i}function VJe(e){let{cosePublicKey:t,signature:i,data:r,shaHashOverride:n}=e;if(kA(t)){let s=t.get(Di.crv);if(!hZe(s))throw Error(`unknown COSE curve ${s}`);let a=ZJe(i,s);return v$({cosePublicKey:t,signature:a,data:r,shaHashOverride:n})}else if(U9(t))return w$({cosePublicKey:t,signature:i,data:r,shaHashOverride:n});else if(mZe(t))return HJe({cosePublicKey:t,signature:i,data:r});let o=t.get(Di.kty);throw Error(`Signature verification with public key of kty ${o} is not supported by this method`)}var li={};Qg(li,{areEqual:()=>m$i,concat:()=>x$i,fromASCIIString:()=>b$i,fromHex:()=>f$i,fromUTF8String:()=>y$i,toDataView:()=>E$i,toHex:()=>h$i,toUTF8String:()=>g$i});function m$i(e,t){if(e.length!=t.length)return!1;return e.every((i,r)=>i===t[r])}function h$i(e){return Array.from(e,(i)=>i.toString(16).padStart(2,"0")).join("")}function f$i(e){if(!e)return Uint8Array.from([]);if(!(e.length!==0&&e.length%2===0&&!/[^a-fA-F0-9]/u.test(e)))throw Error("Invalid hex string");let i=e.match(/.{1,2}/g)??[];return Uint8Array.from(i.map((r)=>parseInt(r,16)))}function x$i(e){let t=0,i=e.reduce((n,o)=>n+o.length,0),r=new Uint8Array(i);return e.forEach((n)=>{r.set(n,t),t+=n.length}),r}function g$i(e){return new globalThis.TextDecoder("utf-8").decode(e)}function y$i(e){return new globalThis.TextEncoder().encode(e)}function b$i(e){return Uint8Array.from(e.split("").map((t)=>t.charCodeAt(0)))}function E$i(e){return new DataView(e.buffer,e.byteOffset,e.length)}async function UG(){let e=new Uint8Array(32);return await Hf.getRandomValues(e),A$i.stubThis(e)}var A$i={stubThis:(e)=>e};var KJe=[-8,-7,-36,-37,-38,-39,-257,-258,-259,-65535],v$i={residentKey:"preferred",userVerification:"preferred"},w$i=[-8,-7,-257];async function YJe(e){let{rpName:t,rpID:i,userName:r,userID:n,challenge:o=await UG(),userDisplayName:s="",timeout:a=60000,attestationType:c="none",excludeCredentials:u=[],authenticatorSelection:d=v$i,extensions:p,supportedAlgorithmIDs:m=w$i,preferredAuthenticatorType:h}=e,f=m.map((v)=>({alg:v,type:"public-key"}));if(d.residentKey===void 0){if(d.requireResidentKey)d.residentKey="required"}else d.requireResidentKey=d.residentKey==="required";let g=o;if(typeof g==="string")g=li.fromUTF8String(g);if(typeof n==="string")throw Error("String values for `userID` are no longer supported. See https://simplewebauthn.dev/docs/advanced/server/custom-user-ids");let y=n;if(!y)y=await bZe();let b=[];if(h){if(h==="securityKey")b.push("security-key"),d.authenticatorAttachment="cross-platform";else if(h==="localDevice")b.push("client-device"),d.authenticatorAttachment="platform";else if(h==="remoteDevice")b.push("hybrid"),d.authenticatorAttachment="cross-platform"}return{challenge:Ti.fromBuffer(g),rp:{name:t,id:i},user:{id:Ti.fromBuffer(y),name:r,displayName:s},pubKeyCredParams:f,timeout:a,attestation:c,excludeCredentials:u.map((v)=>{if(!Ti.isBase64URL(v.id))throw Error(`excludeCredential id "${v.id}" is not a valid base64url string`);return{...v,id:Ti.trimPadding(v.id),type:"public-key"}}),authenticatorSelection:d,extensions:{...p,credProps:!0},hints:b}}function qG({be:e,bs:t}){let i=t,r="singleDevice";if(e)r="multiDevice";if(r==="singleDevice"&&i)throw new JJe("Single-device credential indicated that it was backed up, which should be impossible.");return{credentialDeviceType:r,credentialBackedUp:i}}class JJe extends Error{constructor(e){super(e);this.name="InvalidBackupFlags"}}async function $G(e,t){try{return await Promise.any(t.map((r)=>new Promise((n,o)=>{xp(li.fromASCIIString(r)).then((s)=>{if(li.areEqual(e,s))n(r);else o()})})))}catch(i){if(i.name==="AggregateError")throw new QJe;throw i}}class QJe extends Error{constructor(){super("Unexpected RP ID hash");this.name="UnexpectedRPIDHash"}}async function XJe(e){let{attStmt:t,clientDataHash:i,rpIdHash:r,credentialID:n,credentialPublicKey:o,aaguid:s,rootCertificates:a}=e,c=Uint8Array.from([0]),u=$9(o),d=li.concat([c,r,i,n,u]),p=t.get("sig"),m=t.get("x5c");if(!m)throw Error("No attestation certificate provided in attestation statement (FIDOU2F)");if(!p)throw Error("No attestation signature provided in attestation statement (FIDOU2F)");let h=Number.parseInt(li.toHex(s),16);if(h!==0)throw Error(`AAGUID "${h}" was not expected value`);try{await Fl(m.map(oa),a)}catch(f){throw Error(`${f.message} (FIDOU2F)`)}return gp({signature:p,data:d,x509Certificate:m[0],hashAlgorithm:Vi.ES256})}var eQe="1.3.6.1.4.1.45724.1.1.4";function GG(e,t){if(!e)return!0;let i=e.find((s)=>s.extnID===eQe);if(!i)return!0;let r=Mo.parse(i.extnValue,At),n=new Uint8Array(r.buffer);if(!li.areEqual(t,n)){let s=li.toHex(n),a=li.toHex(t);throw Error(`Certificate extension id-fido-gen-ce-aaguid (${eQe}) value of "${s}" was present but not equal to attestation statement AAGUID value of "${a}"`)}return!0}function tQe(e){return(t,...i)=>{}}var S$i={url:"",no:0,nextUpdate:new Date(0)},k$i="https://mds.fidoalliance.org/",yp;(function(e){e[e.DISABLED=0]="DISABLED",e[e.REFRESHING=1]="REFRESHING",e[e.READY=2]="READY"})(yp||(yp={}));var U8=tQe("MetadataService");class iQe{constructor(){Object.defineProperty(this,"mdsCache",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"statementCache",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:yp.DISABLED}),Object.defineProperty(this,"verificationMode",{enumerable:!0,configurable:!0,writable:!0,value:"strict"})}async initialize(e={}){this.statementCache={};let{mdsServers:t=[k$i],statements:i,verificationMode:r}=e;if(this.setState(yp.REFRESHING),i?.length){let n=0;i.forEach((o)=>{if(o.aaguid)this.statementCache[o.aaguid]={entry:{metadataStatement:o,statusReports:[],timeOfLastStatusChange:"1970-01-01"},url:S$i.url},n+=1}),U8(`Cached ${n} local statements`)}if(t?.length){let n=Object.keys(this.statementCache).length,o=t.length;for(let c of t)try{let u={url:c,no:0,nextUpdate:new Date(0)},d=await this.downloadBlob(u);await this.verifyBlob(d,u)}catch(u){U8(`Could not download BLOB from ${c}:`,u),o-=1}let a=Object.keys(this.statementCache).length-n;U8(`Cached ${a} statements from ${o} metadata server(s)`)}if(r)this.verificationMode=r;this.setState(yp.READY)}async getStatement(e){if(this.state===yp.DISABLED)return;if(!e)return;if(e instanceof Uint8Array)e=S$(e);await this.pauseUntilReady();let t=this.statementCache[e];if(!t){if(this.verificationMode==="strict")throw Error(`No metadata statement found for aaguid "${e}"`);return}if(t.url){let r=this.mdsCache[t.url];if(new Date>r.nextUpdate)try{this.setState(yp.REFRESHING);let o=await this.downloadBlob(r);await this.verifyBlob(o,r)}finally{this.setState(yp.READY)}}let{entry:i}=t;for(let r of i.statusReports){let{status:n}=r;if(n==="USER_VERIFICATION_BYPASS"||n==="ATTESTATION_KEY_COMPROMISE"||n==="USER_KEY_REMOTE_COMPROMISE"||n==="USER_KEY_PHYSICAL_COMPROMISE")throw Error(`Detected compromised aaguid "${e}"`)}return i.metadataStatement}async downloadBlob(e){let{url:t}=e;return await(await LG(t)).text()}async verifyBlob(e,t){let{url:i,no:r}=t,{payload:n,parsedNextUpdate:o}=await GJe(e);if(n.no<=r)throw Error(`Latest BLOB no. ${n.no} is not greater than previous no. ${r}`);for(let s of n.entries)if(s.aaguid)this.statementCache[s.aaguid]={entry:s,url:i};if(i)this.mdsCache[i]={...t,no:n.no,nextUpdate:o};else if(o<new Date)U8(`\u26A0\uFE0F This MDS blob (serial: ${n.no}) contains stale data as of ${o.toISOString()}. Please consider re-initializing MetadataService with a newer MDS blob.`)}pauseUntilReady(){if(this.state===yp.READY)return new Promise((t)=>{t()});return new Promise((t,i)=>{let o=700,s=globalThis.setInterval(()=>{if(o<1)clearInterval(s),i("State did not become ready in 70 seconds");else if(this.state===yp.READY)clearInterval(s),t();o-=1},100)})}setState(e){if(this.state=e,e===yp.DISABLED)U8("MetadataService is DISABLED");else if(e===yp.REFRESHING)U8("MetadataService is REFRESHING");else if(e===yp.READY)U8("MetadataService is READY")}}var JA=new iQe;async function QA({statement:e,credentialPublicKey:t,x5c:i,attestationStatementAlg:r}){let{authenticationAlgorithms:n,authenticatorGetInfo:o,attestationRootCertificates:s}=e,a=new Set;n.forEach((y)=>{let b=rQe[y];if(b)a.add(b)});let c=CA(t),u=c.get(Di.kty),d=c.get(Di.alg);if(!u)throw Error("Credential public key was missing kty");if(!d)throw Error("Credential public key was missing alg");if(!u)throw Error("Credential public key was missing kty");let p={kty:u,alg:d};if(kA(c)){let y=c.get(Di.crv);p.crv=y}let m=!1;for(let y of a){if(y.alg===p.alg&&y.kty===p.kty)if((y.kty===up.EC2||y.kty===up.OKP)&&y.crv===p.crv)m=!0;else m=!0;if(m)break}if(!m){let y=n.map((w)=>`'${w}' (COSE info: ${nQe(rQe[w])})`),b=JSON.stringify(y,null,2).replace(/"/g,""),v=nQe(p);throw Error(`Public key parameters ${v} did not match any of the following metadata algorithms:
4719
- ${b}`)}if(r!==void 0&&o?.algorithms!==void 0){let y=o.algorithms.map((b)=>b.alg);if(y.indexOf(r)<0)throw Error(`Attestation statement alg ${r} did not match one of ${y}`)}let h=i.map(oa),f=s.map(oa),g=!1;if(h.length===1&&f.indexOf(h[0])>=0)g=!0;if(!g)try{await Fl(h,f)}catch(y){throw Error(`Could not validate certificate path with any metadata root certificates: ${y.message}`)}return!0}var rQe={secp256r1_ecdsa_sha256_raw:{kty:2,alg:-7,crv:1},secp256r1_ecdsa_sha256_der:{kty:2,alg:-7,crv:1},rsassa_pss_sha256_raw:{kty:3,alg:-37},rsassa_pss_sha256_der:{kty:3,alg:-37},secp256k1_ecdsa_sha256_raw:{kty:2,alg:-47,crv:8},secp256k1_ecdsa_sha256_der:{kty:2,alg:-47,crv:8},rsassa_pss_sha384_raw:{kty:3,alg:-38},rsassa_pkcsv15_sha256_raw:{kty:3,alg:-257},rsassa_pkcsv15_sha384_raw:{kty:3,alg:-258},rsassa_pkcsv15_sha512_raw:{kty:3,alg:-259},rsassa_pkcsv15_sha1_raw:{kty:3,alg:-65535},secp384r1_ecdsa_sha384_raw:{kty:2,alg:-35,crv:2},secp512r1_ecdsa_sha256_raw:{kty:2,alg:-36,crv:3},ed25519_eddsa_sha512_raw:{kty:1,alg:-8,crv:6}};function nQe(e){let{kty:t,alg:i,crv:r}=e,n="";if(t!==up.RSA)n=`{ kty: ${t}, alg: ${i}, crv: ${r} }`;else n=`{ kty: ${t}, alg: ${i} }`;return n}async function oQe(e){let{attStmt:t,clientDataHash:i,authData:r,credentialPublicKey:n,aaguid:o,rootCertificates:s}=e,a=t.get("sig"),c=t.get("x5c"),u=t.get("alg");if(!a)throw Error("No attestation signature provided in attestation statement (Packed)");if(!u)throw Error("Attestation statement did not contain alg (Packed)");if(!Gf(u))throw Error(`Attestation statement contained invalid alg ${u} (Packed)`);let d=li.concat([r,i]),p=!1;if(c){let{subject:m,basicConstraintsCA:h,version:f,notBefore:g,notAfter:y,parsedCertificate:b}=yk(c[0]),{OU:v,CN:w,O:D,C:R}=m;if(v!=="Authenticator Attestation")throw Error('Certificate OU was not "Authenticator Attestation" (Packed|Full)');if(!w)throw Error("Certificate CN was empty (Packed|Full)");if(!D)throw Error("Certificate O was empty (Packed|Full)");if(!R||R.length!==2)throw Error("Certificate C was not two-character ISO 3166 code (Packed|Full)");if(h)throw Error("Certificate basic constraints CA was not `false` (Packed|Full)");if(f!==2)throw Error("Certificate version was not `3` (ASN.1 value of 2) (Packed|Full)");let O=new Date;if(g>O)throw Error(`Certificate not good before "${g.toString()}" (Packed|Full)`);if(O=new Date,y<O)throw Error(`Certificate not good after "${y.toString()}" (Packed|Full)`);try{await GG(b.tbsCertificate.extensions,o)}catch(j){throw Error(`${j.message} (Packed|Full)`)}let k=await JA.getStatement(o);if(k){if(k.attestationTypes.indexOf("basic_full")<0)throw Error("Metadata does not indicate support for full attestations (Packed|Full)");try{await QA({statement:k,credentialPublicKey:n,x5c:c,attestationStatementAlg:u})}catch(j){throw Error(`${j.message} (Packed|Full)`)}}else try{await Fl(c.map(oa),s)}catch(j){throw Error(`${j.message} (Packed|Full)`)}p=await gp({signature:a,data:d,x509Certificate:c[0],hashAlgorithm:u})}else p=await gp({signature:a,data:d,credentialPublicKey:n,hashAlgorithm:u});return p}async function sQe(e){let{attStmt:t,clientDataHash:i,authData:r,aaguid:n,rootCertificates:o,verifyTimestampMS:s=!0,credentialPublicKey:a,attestationSafetyNetEnforceCTSCheck:c}=e,u=t.get("alg"),d=t.get("response");if(!t.get("ver"))throw Error("No ver value in attestation (SafetyNet)");if(!d)throw Error("No response was included in attStmt by authenticator (SafetyNet)");let h=li.toUTF8String(d).split("."),f=JSON.parse(Ti.toUTF8String(h[0])),g=JSON.parse(Ti.toUTF8String(h[1])),y=h[2],{nonce:b,ctsProfileMatch:v,timestampMs:w}=g;if(s){let S=Date.now();if(w>Date.now())throw Error(`Payload timestamp "${w}" was later than "${S}" (SafetyNet)`);let P=w+60000;if(S=Date.now(),P<S)throw Error(`Payload timestamp "${P}" has expired (SafetyNet)`)}let D=li.concat([r,i]),R=await xp(D),O=Ti.fromBuffer(R,"base64");if(b!==O)throw Error("Could not verify payload nonce (SafetyNet)");if(c&&!v)throw Error("Could not verify device integrity (SafetyNet)");let k=Ti.toBuffer(f.x5c[0],"base64"),j=yk(k),{subject:L}=j;if(L.CN!=="attest.android.com")throw Error('Certificate common name was not "attest.android.com" (SafetyNet)');let q=await JA.getStatement(n);if(q)try{await QA({statement:q,credentialPublicKey:a,x5c:f.x5c,attestationStatementAlg:u})}catch(S){throw Error(`${S.message} (SafetyNet)`)}else try{await Fl(f.x5c.map(oa),o)}catch(S){throw Error(`${S.message} (SafetyNet)`)}let K=li.fromUTF8String(`${h[0]}.${h[1]}`),ue=Ti.toBuffer(y);return await gp({signature:ue,data:K,x509Certificate:k,hashAlgorithm:u})}var aQe={196:"TPM_ST_RSP_COMMAND",32768:"TPM_ST_NULL",32769:"TPM_ST_NO_SESSIONS",32770:"TPM_ST_SESSIONS",32788:"TPM_ST_ATTEST_NV",32789:"TPM_ST_ATTEST_COMMAND_AUDIT",32790:"TPM_ST_ATTEST_SESSION_AUDIT",32791:"TPM_ST_ATTEST_CERTIFY",32792:"TPM_ST_ATTEST_QUOTE",32793:"TPM_ST_ATTEST_TIME",32794:"TPM_ST_ATTEST_CREATION",32801:"TPM_ST_CREATION",32802:"TPM_ST_VERIFIED",32803:"TPM_ST_AUTH_SECRET",32804:"TPM_ST_HASHCHECK",32805:"TPM_ST_AUTH_SIGNED",32809:"TPM_ST_FU_MANIFEST"},rx={0:"TPM_ALG_ERROR",1:"TPM_ALG_RSA",4:"TPM_ALG_SHA",4:"TPM_ALG_SHA1",5:"TPM_ALG_HMAC",6:"TPM_ALG_AES",7:"TPM_ALG_MGF1",8:"TPM_ALG_KEYEDHASH",10:"TPM_ALG_XOR",11:"TPM_ALG_SHA256",12:"TPM_ALG_SHA384",13:"TPM_ALG_SHA512",16:"TPM_ALG_NULL",18:"TPM_ALG_SM3_256",19:"TPM_ALG_SM4",20:"TPM_ALG_RSASSA",21:"TPM_ALG_RSAES",22:"TPM_ALG_RSAPSS",23:"TPM_ALG_OAEP",24:"TPM_ALG_ECDSA",25:"TPM_ALG_ECDH",26:"TPM_ALG_ECDAA",27:"TPM_ALG_SM2",28:"TPM_ALG_ECSCHNORR",29:"TPM_ALG_ECMQV",32:"TPM_ALG_KDF1_SP800_56A",33:"TPM_ALG_KDF2",34:"TPM_ALG_KDF1_SP800_108",35:"TPM_ALG_ECC",37:"TPM_ALG_SYMCIPHER",38:"TPM_ALG_CAMELLIA",64:"TPM_ALG_CTR",65:"TPM_ALG_OFB",66:"TPM_ALG_CBC",67:"TPM_ALG_CFB",68:"TPM_ALG_ECB"},cQe={0:"TPM_ECC_NONE",1:"TPM_ECC_NIST_P192",2:"TPM_ECC_NIST_P224",3:"TPM_ECC_NIST_P256",4:"TPM_ECC_NIST_P384",5:"TPM_ECC_NIST_P521",16:"TPM_ECC_BN_P256",17:"TPM_ECC_BN_P638",32:"TPM_ECC_SM2_P256"},lQe={"id:414D4400":{name:"AMD",id:"AMD"},"id:414E5400":{name:"Ant Group",id:"ANT"},"id:41544D4C":{name:"Atmel",id:"ATML"},"id:4252434D":{name:"Broadcom",id:"BRCM"},"id:4353434F":{name:"Cisco",id:"CSCO"},"id:464C5953":{name:"Flyslice Technologies",id:"FLYS"},"id:524F4343":{name:"Fuzhou Rockchip",id:"ROCC"},"id:474F4F47":{name:"Google",id:"GOOG"},"id:48504900":{name:"HPI",id:"HPI"},"id:48504500":{name:"HPE",id:"HPE"},"id:48495349":{name:"Huawei",id:"HISI"},"id:49424d00":{name:"IBM",id:"IBM"},"id:49424D00":{name:"IBM",id:"IBM"},"id:49465800":{name:"Infineon",id:"IFX"},"id:494E5443":{name:"Intel",id:"INTC"},"id:4C454E00":{name:"Lenovo",id:"LEN"},"id:4D534654":{name:"Microsoft",id:"MSFT"},"id:4E534D20":{name:"National Semiconductor",id:"NSM"},"id:4E545A00":{name:"Nationz",id:"NTZ"},"id:4E534700":{name:"NSING",id:"NSG"},"id:4E544300":{name:"Nuvoton Technology",id:"NTC"},"id:51434F4D":{name:"Qualcomm",id:"QCOM"},"id:534D534E":{name:"Samsung",id:"SMSN"},"id:53454345":{name:"SecEdge",id:"SECE"},"id:534E5300":{name:"Sinosun",id:"SNS"},"id:534D5343":{name:"SMSC",id:"SMSC"},"id:53544D20":{name:"STMicroelectronics",id:"STM"},"id:54584E00":{name:"Texas Instruments",id:"TXN"},"id:57454300":{name:"Winbond",id:"WEC"},"id:5345414C":{name:"Wisekey",id:"SEAL"},"id:FFFFF1D0":{name:"FIDO Alliance",id:"FIDO"}},uQe={TPM_ECC_NIST_P256:1,TPM_ECC_NIST_P384:2,TPM_ECC_NIST_P521:3,TPM_ECC_BN_P256:1,TPM_ECC_SM2_P256:1};function dQe(e){let t=0,i=li.toDataView(e),r=i.getUint32(t);t+=4;let n=i.getUint16(t);t+=2;let o=aQe[n],s=i.getUint16(t);t+=2;let a=e.slice(t,t+=s),c=i.getUint16(t);t+=2;let u=e.slice(t,t+=c),d=e.slice(t,t+=8),p=i.getUint32(t);t+=4;let m=i.getUint32(t);t+=4;let h=!!e.slice(t,t+=1),f={clock:d,resetCount:p,restartCount:m,safe:h},g=e.slice(t,t+=8),y=i.getUint16(t);t+=2;let b=e.slice(t,t+=y),v=li.toDataView(b),w=i.getUint16(t);t+=2;let D=e.slice(t,t+=w),R={nameAlg:rx[v.getUint16(0)],nameAlgBuffer:b.slice(0,2),name:b,qualifiedName:D};return{magic:r,type:o,qualifiedSigner:a,extraData:u,clockInfo:f,firmwareVersion:g,attested:R}}function pQe(e){let t=0,i=li.toDataView(e),r=rx[i.getUint16(t)];t+=2;let n=rx[i.getUint16(t)];t+=2;let o=i.getUint32(t);t+=4;let s={fixedTPM:!!(o&1),stClear:!!(o&2),fixedParent:!!(o&8),sensitiveDataOrigin:!!(o&16),userWithAuth:!!(o&32),adminWithPolicy:!!(o&64),noDA:!!(o&512),encryptedDuplication:!!(o&1024),restricted:!!(o&32768),decrypt:!!(o&65536),signOrEncrypt:!!(o&131072)},a=i.getUint16(t);t+=2;let c=e.slice(t,t+=a),u={},d=Uint8Array.from([]);if(r==="TPM_ALG_RSA"){let p=rx[i.getUint16(t)];t+=2;let m=rx[i.getUint16(t)];t+=2;let h=i.getUint16(t);t+=2;let f=i.getUint32(t);t+=4,u.rsa={symmetric:p,scheme:m,keyBits:h,exponent:f};let g=i.getUint16(t);t+=2,d=e.slice(t,t+=g)}else if(r==="TPM_ALG_ECC"){let p=rx[i.getUint16(t)];t+=2;let m=rx[i.getUint16(t)];t+=2;let h=cQe[i.getUint16(t)];t+=2;let f=rx[i.getUint16(t)];t+=2,u.ecc={symmetric:p,scheme:m,curveID:h,kdf:f};let g=i.getUint16(t);t+=2;let y=e.slice(t,t+=g),b=i.getUint16(t);t+=2;let v=e.slice(t,t+=b);d=li.concat([y,v])}else throw Error(`Unexpected type "${r}" (TPM)`);return{type:r,nameAlg:n,objectAttributes:s,authPolicy:c,parameters:u,unique:d}}async function mQe(e){let{aaguid:t,attStmt:i,authData:r,credentialPublicKey:n,clientDataHash:o,rootCertificates:s}=e,a=i.get("ver"),c=i.get("sig"),u=i.get("alg"),d=i.get("x5c"),p=i.get("pubArea"),m=i.get("certInfo");if(a!=="2.0")throw Error(`Unexpected ver "${a}", expected "2.0" (TPM)`);if(!c)throw Error("No attestation signature provided in attestation statement (TPM)");if(!u)throw Error("Attestation statement did not contain alg (TPM)");if(!Gf(u))throw Error(`Attestation statement contained invalid alg ${u} (TPM)`);if(!d)throw Error("No attestation certificate provided in attestation statement (TPM)");if(!p)throw Error("Attestation statement did not contain pubArea (TPM)");if(!m)throw Error("Attestation statement did not contain certInfo (TPM)");let h=pQe(p),{unique:f,type:g,parameters:y}=h,b=CA(n);if(g==="TPM_ALG_RSA"){if(!U9(b))throw Error(`Credential public key with kty ${b.get(Di.kty)} did not match ${g}`);let se=b.get(Di.n),Se=b.get(Di.e);if(!se)throw Error("COSE public key missing n (TPM|RSA)");if(!Se)throw Error("COSE public key missing e (TPM|RSA)");if(!li.areEqual(f,se))throw Error("PubArea unique is not same as credentialPublicKey (TPM|RSA)");if(!y.rsa)throw Error("Parsed pubArea type is RSA, but missing parameters.rsa (TPM|RSA)");let fe=Se,ze=y.rsa.exponent||65537,Ye=fe[0]+(fe[1]<<8)+(fe[2]<<16);if(ze!==Ye)throw Error(`Unexpected public key exp ${Ye}, expected ${ze} (TPM|RSA)`)}else if(g==="TPM_ALG_ECC"){if(!kA(b))throw Error(`Credential public key with kty ${b.get(Di.kty)} did not match ${g}`);let se=b.get(Di.crv),Se=b.get(Di.x),fe=b.get(Di.y);if(!se)throw Error("COSE public key missing crv (TPM|ECC)");if(!Se)throw Error("COSE public key missing x (TPM|ECC)");if(!fe)throw Error("COSE public key missing y (TPM|ECC)");if(!li.areEqual(f,li.concat([Se,fe])))throw Error("PubArea unique is not same as public key x and y (TPM|ECC)");if(!y.ecc)throw Error("Parsed pubArea type is ECC, but missing parameters.ecc (TPM|ECC)");let ze=y.ecc.curveID,Ye=uQe[ze];if(Ye!==se)throw Error(`Public area key curve ID "${ze}" mapped to "${Ye}" which did not match public key crv of "${se}" (TPM|ECC)`)}else throw Error(`Unsupported pubArea.type "${g}"`);let v=dQe(m),{magic:w,type:D,attested:R,extraData:O}=v;if(w!==4283712327)throw Error(`Unexpected magic value "${w}", expected "0xff544347" (TPM)`);if(D!=="TPM_ST_ATTEST_CERTIFY")throw Error(`Unexpected type "${D}", expected "TPM_ST_ATTEST_CERTIFY" (TPM)`);let k=await xp(p,C$i(R.nameAlg)),j=li.concat([R.nameAlgBuffer,k]);if(!li.areEqual(R.name,j))throw Error("Attested name comparison failed (TPM)");let L=li.concat([r,o]),q=await xp(L,u);if(!li.areEqual(O,q))throw Error("CertInfo extra data did not equal hashed attestation (TPM)");if(d.length<1)throw Error("No certificates present in x5c array (TPM)");let K=yk(d[0]),{basicConstraintsCA:ue,version:G,subject:S,notAfter:P,notBefore:M}=K;if(ue)throw Error("Certificate basic constraints CA was not `false` (TPM)");if(G!==2)throw Error("Certificate version was not `3` (ASN.1 value of 2) (TPM)");if(S.combined.length>0)throw Error("Certificate subject was not empty (TPM)");let H=new Date;if(M>H)throw Error(`Certificate not good before "${M.toString()}" (TPM)`);if(H=new Date,P<H)throw Error(`Certificate not good after "${P.toString()}" (TPM)`);let V=Mo.parse(d[0],Us);if(!V.tbsCertificate.extensions)throw Error("Certificate was missing extensions (TPM)");let W,Y;if(V.tbsCertificate.extensions.forEach((se)=>{if(se.extnID===gk)W=Mo.parse(se.extnValue,xk);else if(se.extnID===hk)Y=Mo.parse(se.extnValue,m8)}),!W)throw Error("Certificate did not contain subjectAltName extension (TPM)");if(!W[0].directoryName?.[0].length)throw Error("Certificate subjectAltName extension directoryName was empty (TPM)");let{tcgAtTpmManufacturer:X,tcgAtTpmModel:te,tcgAtTpmVersion:Ce}=B$i(W[0].directoryName);if(!X||!te||!Ce)throw Error("Certificate contained incomplete subjectAltName data (TPM)");if(!Y)throw Error("Certificate did not contain ExtendedKeyUsage extension (TPM)");if(!lQe[X])throw Error(`Could not match TPM manufacturer "${X}" (TPM)`);if(Y[0]!=="2.23.133.8.3")throw Error(`Unexpected extKeyUsage "${Y[0]}", expected "2.23.133.8.3" (TPM)`);try{await GG(V.tbsCertificate.extensions,t)}catch(se){throw Error(`${se.message} (TPM)`)}let pe=await JA.getStatement(t);if(pe)try{await QA({statement:pe,credentialPublicKey:n,x5c:d,attestationStatementAlg:u})}catch(se){throw Error(`${se.message} (TPM)`)}else try{await Fl(d.map(oa),s)}catch(se){throw Error(`${se.message} (TPM)`)}return gp({signature:c,data:m,x509Certificate:d[0],hashAlgorithm:u})}function B$i(e){let n,o,s;return e.forEach((a)=>{a.forEach((c)=>{if(c.type==="2.23.133.2.1")n=c.value.toString();else if(c.type==="2.23.133.2.2")o=c.value.toString();else if(c.type==="2.23.133.2.3")s=c.value.toString()})}),{tcgAtTpmManufacturer:n,tcgAtTpmModel:o,tcgAtTpmVersion:s}}function C$i(e){if(e==="TPM_ALG_SHA256")return Vi.ES256;else if(e==="TPM_ALG_SHA384")return Vi.ES384;else if(e==="TPM_ALG_SHA512")return Vi.ES512;throw Error(`Unexpected TPM attested name alg ${e}`)}var Ohe,hQe="1.3.6.1.4.1.11129.2.1.17",Nhe;(function(e){e[e.verified=0]="verified",e[e.selfSigned=1]="selfSigned",e[e.unverified=2]="unverified",e[e.failed=3]="failed"})(Nhe||(Nhe={}));class Jk{verifiedBootKey=new At;deviceLocked=!1;verifiedBootState=Nhe.verified;verifiedBootHash;constructor(e={}){Object.assign(this,e)}}T([N({type:At})],Jk.prototype,"verifiedBootKey",void 0);T([N({type:Q.Boolean})],Jk.prototype,"deviceLocked",void 0);T([N({type:Q.Enumerated})],Jk.prototype,"verifiedBootState",void 0);T([N({type:At,optional:!0})],Jk.prototype,"verifiedBootHash",void 0);var Kk=Ohe=class extends ni{constructor(t){super(t);Object.setPrototypeOf(this,Ohe.prototype)}};Kk=Ohe=T([_e({type:ke.Set,itemType:Q.Integer})],Kk);class vi{purpose;algorithm;keySize;digest;padding;ecCurve;rsaPublicExponent;mgfDigest;rollbackResistance;earlyBootOnly;activeDateTime;originationExpireDateTime;usageExpireDateTime;usageCountLimit;noAuthRequired;userAuthType;authTimeout;allowWhileOnBody;trustedUserPresenceRequired;trustedConfirmationRequired;unlockedDeviceRequired;allApplications;applicationId;creationDateTime;origin;rollbackResistant;rootOfTrust;osVersion;osPatchLevel;attestationApplicationId;attestationIdBrand;attestationIdDevice;attestationIdProduct;attestationIdSerial;attestationIdImei;attestationIdMeid;attestationIdManufacturer;attestationIdModel;vendorPatchLevel;bootPatchLevel;deviceUniqueAttestation;attestationIdSecondImei;moduleHash;constructor(e={}){Object.assign(this,e)}}T([N({context:1,type:Kk,optional:!0})],vi.prototype,"purpose",void 0);T([N({context:2,type:Q.Integer,optional:!0})],vi.prototype,"algorithm",void 0);T([N({context:3,type:Q.Integer,optional:!0})],vi.prototype,"keySize",void 0);T([N({context:5,type:Kk,optional:!0})],vi.prototype,"digest",void 0);T([N({context:6,type:Kk,optional:!0})],vi.prototype,"padding",void 0);T([N({context:10,type:Q.Integer,optional:!0})],vi.prototype,"ecCurve",void 0);T([N({context:200,type:Q.Integer,optional:!0})],vi.prototype,"rsaPublicExponent",void 0);T([N({context:203,type:Kk,optional:!0})],vi.prototype,"mgfDigest",void 0);T([N({context:303,type:Q.Null,optional:!0})],vi.prototype,"rollbackResistance",void 0);T([N({context:305,type:Q.Null,optional:!0})],vi.prototype,"earlyBootOnly",void 0);T([N({context:400,type:Q.Integer,optional:!0})],vi.prototype,"activeDateTime",void 0);T([N({context:401,type:Q.Integer,optional:!0})],vi.prototype,"originationExpireDateTime",void 0);T([N({context:402,type:Q.Integer,optional:!0})],vi.prototype,"usageExpireDateTime",void 0);T([N({context:405,type:Q.Integer,optional:!0})],vi.prototype,"usageCountLimit",void 0);T([N({context:503,type:Q.Null,optional:!0})],vi.prototype,"noAuthRequired",void 0);T([N({context:504,type:Q.Integer,optional:!0})],vi.prototype,"userAuthType",void 0);T([N({context:505,type:Q.Integer,optional:!0})],vi.prototype,"authTimeout",void 0);T([N({context:506,type:Q.Null,optional:!0})],vi.prototype,"allowWhileOnBody",void 0);T([N({context:507,type:Q.Null,optional:!0})],vi.prototype,"trustedUserPresenceRequired",void 0);T([N({context:508,type:Q.Null,optional:!0})],vi.prototype,"trustedConfirmationRequired",void 0);T([N({context:509,type:Q.Null,optional:!0})],vi.prototype,"unlockedDeviceRequired",void 0);T([N({context:600,type:Q.Null,optional:!0})],vi.prototype,"allApplications",void 0);T([N({context:601,type:At,optional:!0})],vi.prototype,"applicationId",void 0);T([N({context:701,type:Q.Integer,optional:!0})],vi.prototype,"creationDateTime",void 0);T([N({context:702,type:Q.Integer,optional:!0})],vi.prototype,"origin",void 0);T([N({context:703,type:Q.Null,optional:!0})],vi.prototype,"rollbackResistant",void 0);T([N({context:704,type:Jk,optional:!0})],vi.prototype,"rootOfTrust",void 0);T([N({context:705,type:Q.Integer,optional:!0})],vi.prototype,"osVersion",void 0);T([N({context:706,type:Q.Integer,optional:!0})],vi.prototype,"osPatchLevel",void 0);T([N({context:709,type:At,optional:!0})],vi.prototype,"attestationApplicationId",void 0);T([N({context:710,type:At,optional:!0})],vi.prototype,"attestationIdBrand",void 0);T([N({context:711,type:At,optional:!0})],vi.prototype,"attestationIdDevice",void 0);T([N({context:712,type:At,optional:!0})],vi.prototype,"attestationIdProduct",void 0);T([N({context:713,type:At,optional:!0})],vi.prototype,"attestationIdSerial",void 0);T([N({context:714,type:At,optional:!0})],vi.prototype,"attestationIdImei",void 0);T([N({context:715,type:At,optional:!0})],vi.prototype,"attestationIdMeid",void 0);T([N({context:716,type:At,optional:!0})],vi.prototype,"attestationIdManufacturer",void 0);T([N({context:717,type:At,optional:!0})],vi.prototype,"attestationIdModel",void 0);T([N({context:718,type:Q.Integer,optional:!0})],vi.prototype,"vendorPatchLevel",void 0);T([N({context:719,type:Q.Integer,optional:!0})],vi.prototype,"bootPatchLevel",void 0);T([N({context:720,type:Q.Null,optional:!0})],vi.prototype,"deviceUniqueAttestation",void 0);T([N({context:723,type:At,optional:!0})],vi.prototype,"attestationIdSecondImei",void 0);T([N({context:724,type:At,optional:!0})],vi.prototype,"moduleHash",void 0);var Ky;(function(e){e[e.software=0]="software",e[e.trustedEnvironment=1]="trustedEnvironment",e[e.strongBox=2]="strongBox"})(Ky||(Ky={}));var Yk;(function(e){e[e.KM2=1]="KM2",e[e.KM3=2]="KM3",e[e.KM4=3]="KM4",e[e.KM4_1=4]="KM4_1",e[e.keyMint1=100]="keyMint1",e[e.keyMint2=200]="keyMint2",e[e.keyMint3=300]="keyMint3",e[e.keyMint4=400]="keyMint4"})(Yk||(Yk={}));class L0{attestationVersion=Yk.KM4;attestationSecurityLevel=Ky.software;keymasterVersion=0;keymasterSecurityLevel=Ky.software;attestationChallenge=new At;uniqueId=new At;softwareEnforced=new vi;teeEnforced=new vi;constructor(e={}){Object.assign(this,e)}}T([N({type:Q.Integer})],L0.prototype,"attestationVersion",void 0);T([N({type:Q.Enumerated})],L0.prototype,"attestationSecurityLevel",void 0);T([N({type:Q.Integer})],L0.prototype,"keymasterVersion",void 0);T([N({type:Q.Enumerated})],L0.prototype,"keymasterSecurityLevel",void 0);T([N({type:At})],L0.prototype,"attestationChallenge",void 0);T([N({type:At})],L0.prototype,"uniqueId",void 0);T([N({type:vi})],L0.prototype,"softwareEnforced",void 0);T([N({type:vi})],L0.prototype,"teeEnforced",void 0);class nx{attestationVersion=Yk.keyMint4;attestationSecurityLevel=Ky.software;keyMintVersion=0;keyMintSecurityLevel=Ky.software;attestationChallenge=new At;uniqueId=new At;softwareEnforced=new vi;hardwareEnforced=new vi;constructor(e={}){Object.assign(this,e)}toLegacyKeyDescription(){return new L0({attestationVersion:this.attestationVersion,attestationSecurityLevel:this.attestationSecurityLevel,keymasterVersion:this.keyMintVersion,keymasterSecurityLevel:this.keyMintSecurityLevel,attestationChallenge:this.attestationChallenge,uniqueId:this.uniqueId,softwareEnforced:this.softwareEnforced,teeEnforced:this.hardwareEnforced})}static fromLegacyKeyDescription(e){return new nx({attestationVersion:e.attestationVersion,attestationSecurityLevel:e.attestationSecurityLevel,keyMintVersion:e.keymasterVersion,keyMintSecurityLevel:e.keymasterSecurityLevel,attestationChallenge:e.attestationChallenge,uniqueId:e.uniqueId,softwareEnforced:e.softwareEnforced,hardwareEnforced:e.teeEnforced})}}T([N({type:Q.Integer})],nx.prototype,"attestationVersion",void 0);T([N({type:Q.Enumerated})],nx.prototype,"attestationSecurityLevel",void 0);T([N({type:Q.Integer})],nx.prototype,"keyMintVersion",void 0);T([N({type:Q.Enumerated})],nx.prototype,"keyMintSecurityLevel",void 0);T([N({type:At})],nx.prototype,"attestationChallenge",void 0);T([N({type:At})],nx.prototype,"uniqueId",void 0);T([N({type:vi})],nx.prototype,"softwareEnforced",void 0);T([N({type:vi})],nx.prototype,"hardwareEnforced",void 0);var Lhe,zhe=class extends vi{};zhe=T([_e({type:ke.Choice})],zhe);var Qk=Lhe=class extends ni{constructor(t){super(t);Object.setPrototypeOf(this,Lhe.prototype)}findProperty(t){let i=this.find((r)=>r[t]!==void 0);if(i)return i[t];return}};Qk=Lhe=T([_e({type:ke.Sequence,itemType:zhe})],Qk);class ox{attestationVersion=Yk.KM4;attestationSecurityLevel=Ky.software;keymasterVersion=0;keymasterSecurityLevel=Ky.software;attestationChallenge=new At;uniqueId=new At;softwareEnforced=new Qk;teeEnforced=new Qk;get keyMintVersion(){return this.keymasterVersion}set keyMintVersion(e){this.keymasterVersion=e}get keyMintSecurityLevel(){return this.keymasterSecurityLevel}set keyMintSecurityLevel(e){this.keymasterSecurityLevel=e}get hardwareEnforced(){return this.teeEnforced}set hardwareEnforced(e){this.teeEnforced=e}constructor(e={}){Object.assign(this,e)}}T([N({type:Q.Integer})],ox.prototype,"attestationVersion",void 0);T([N({type:Q.Enumerated})],ox.prototype,"attestationSecurityLevel",void 0);T([N({type:Q.Integer})],ox.prototype,"keymasterVersion",void 0);T([N({type:Q.Enumerated})],ox.prototype,"keymasterSecurityLevel",void 0);T([N({type:At})],ox.prototype,"attestationChallenge",void 0);T([N({type:At})],ox.prototype,"uniqueId",void 0);T([N({type:Qk})],ox.prototype,"softwareEnforced",void 0);T([N({type:Qk})],ox.prototype,"teeEnforced",void 0);var fQe=class extends ox{constructor(t={}){if("keymasterVersion"in t&&!("keyMintVersion"in t))t.keyMintVersion=t.keymasterVersion;if("keymasterSecurityLevel"in t&&!("keyMintSecurityLevel"in t))t.keyMintSecurityLevel=t.keymasterSecurityLevel;if("teeEnforced"in t&&!("hardwareEnforced"in t))t.hardwareEnforced=t.teeEnforced;super(t)}};fQe=T([_e({type:ke.Sequence})],fQe);class HG{packageName;version;constructor(e={}){Object.assign(this,e)}}T([N({type:Q.OctetString})],HG.prototype,"packageName",void 0);T([N({type:Q.Integer})],HG.prototype,"version",void 0);class jhe{packageInfos;signatureDigests;constructor(e={}){Object.assign(this,e)}}T([N({type:HG,repeated:"set"})],jhe.prototype,"packageInfos",void 0);T([N({type:Q.OctetString,repeated:"set"})],jhe.prototype,"signatureDigests",void 0);async function xQe(e){let{authData:t,clientDataHash:i,attStmt:r,credentialPublicKey:n,aaguid:o,rootCertificates:s}=e,a=r.get("x5c"),c=r.get("sig"),u=r.get("alg");if(!a)throw Error("No attestation certificate provided in attestation statement (Android Key)");if(!c)throw Error("No attestation signature provided in attestation statement (Android Key)");if(!u)throw Error("Attestation statement did not contain alg (Android Key)");if(!Gf(u))throw Error(`Attestation statement contained invalid alg ${u} (Android Key)`);let d=Mo.parse(a[0],Us),p=new Uint8Array(d.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey),m=$9(n);if(!li.areEqual(m,p))throw Error("Credential public key does not equal leaf cert public key (Android Key)");let h=d.tbsCertificate.extensions?.find((D)=>D.extnID===hQe);if(!h)throw Error("Certificate did not contain extKeyStore (Android Key)");let f=Mo.parse(h.extnValue,L0),{attestationChallenge:g,teeEnforced:y,softwareEnforced:b}=f;if(!li.areEqual(new Uint8Array(g.buffer),i))throw Error("Attestation challenge was not equal to client data hash (Android Key)");if(y.allApplications!==void 0)throw Error('teeEnforced contained "allApplications [600]" tag (Android Key)');if(b.allApplications!==void 0)throw Error('teeEnforced contained "allApplications [600]" tag (Android Key)');let v=await JA.getStatement(o);if(v)try{await QA({statement:v,credentialPublicKey:n,x5c:a,attestationStatementAlg:u})}catch(D){let R=D;throw Error(`${R.message} (Android Key)`,{cause:R})}else{let D=a.slice(0,-1).map(oa),R=a.slice(-1).map(oa);try{await Fl(D,R)}catch(O){let k=O;throw Error(`${k.message} (Android Key)`,{cause:k})}if(s.length>0&&s.indexOf(R[0])<0)throw Error("x5c root certificate was not a known root certificate (Android Key)")}let w=li.concat([t,i]);return gp({signature:c,data:w,x509Certificate:a[0],hashAlgorithm:u})}async function gQe(e){let{attStmt:t,authData:i,clientDataHash:r,credentialPublicKey:n,rootCertificates:o}=e,s=t.get("x5c");if(!s)throw Error("No attestation certificate provided in attestation statement (Apple)");try{await Fl(s.map(oa),o)}catch(y){throw Error(`${y.message} (Apple)`)}let a=Mo.parse(s[0],Us),{extensions:c,subjectPublicKeyInfo:u}=a.tbsCertificate;if(!c)throw Error("credCert missing extensions (Apple)");let d=c.find((y)=>y.extnID==="1.2.840.113635.100.8.2");if(!d)throw Error('credCert missing "1.2.840.113635.100.8.2" extension (Apple)');let p=li.concat([i,r]),m=await xp(p),h=new Uint8Array(d.extnValue.buffer).slice(6);if(!li.areEqual(m,h))throw Error("credCert nonce was not expected value (Apple)");let f=$9(n),g=new Uint8Array(u.subjectPublicKey);if(!li.areEqual(f,g))throw Error("Credential public key does not equal credCert public key (Apple)");return!0}async function yQe(e){let{response:t,expectedChallenge:i,expectedOrigin:r,expectedRPID:n,expectedType:o,requireUserPresence:s=!0,requireUserVerification:a=!0,supportedAlgorithmIDs:c=KJe,attestationSafetyNetEnforceCTSCheck:u=!0}=e,{id:d,rawId:p,type:m,response:h}=t;if(!d)throw Error("Missing credential ID");if(d!==p)throw Error("Credential ID was not base64url-encoded");if(m!=="public-key")throw Error(`Unexpected credential type ${m}, expected "public-key"`);let f=k$(h.clientDataJSON),{type:g,origin:y,challenge:b,tokenBinding:v}=f;if(Array.isArray(o)){if(!o.includes(g)){let se=o.join(", ");throw Error(`Unexpected registration response type "${g}", expected one of: ${se}`)}}else if(o){if(g!==o)throw Error(`Unexpected registration response type "${g}", expected "${o}"`)}else if(g!=="webauthn.create")throw Error(`Unexpected registration response type: ${g}`);if(typeof i==="function"){if(!await i(b))throw Error(`Custom challenge verifier returned false for registration response challenge "${b}"`)}else if(b!==i)throw Error(`Unexpected registration response challenge "${b}", expected "${i}"`);if(Array.isArray(r)){if(!r.includes(y))throw Error(`Unexpected registration response origin "${y}", expected one of: ${r.join(", ")}`)}else if(y!==r)throw Error(`Unexpected registration response origin "${y}", expected "${r}"`);if(v){if(typeof v!=="object")throw Error(`Unexpected value for TokenBinding "${v}"`);if(["present","supported","not-supported"].indexOf(v.status)<0)throw Error(`Unexpected tokenBinding.status value of "${v.status}"`)}let w=Ti.toBuffer(h.attestationObject),D=yZe(w),R=D.get("fmt"),O=D.get("authData"),k=D.get("attStmt"),j=zG(O),{aaguid:L,rpIdHash:q,flags:K,credentialID:ue,counter:G,credentialPublicKey:S,extensionsData:P}=j,M;if(n){let se=[];if(typeof n==="string")se=[n];else se=n;M=await $G(q,se)}if(s&&!K.up)throw Error("User presence was required, but user was not present");if(a&&!K.uv)throw Error("User verification was required, but user could not be verified");if(!ue)throw Error("No credential ID was provided by authenticator");if(!S)throw Error("No public key was provided by authenticator");if(!L)throw Error("No AAGUID was present during registration");let V=CA(S).get(Di.alg);if(typeof V!=="number")throw Error("Credential public key was missing numeric alg");if(!c.includes(V)){let se=c.join(", ");throw Error(`Unexpected public key alg "${V}", expected one of "${se}"`)}let W=await xp(Ti.toBuffer(h.clientDataJSON)),Y=YA.getRootCertificates({identifier:R}),X={aaguid:L,attStmt:k,authData:O,clientDataHash:W,credentialID:ue,credentialPublicKey:S,rootCertificates:Y,rpIdHash:q,attestationSafetyNetEnforceCTSCheck:u},te=!1;if(R==="fido-u2f")te=await XJe(X);else if(R==="packed")te=await oQe(X);else if(R==="android-safetynet")te=await sQe(X);else if(R==="android-key")te=await xQe(X);else if(R==="tpm")te=await mQe(X);else if(R==="apple")te=await gQe(X);else if(R==="none"){if(k.size>0)throw Error("None attestation had unexpected attestation statement");te=!0}else throw Error(`Unsupported Attestation Format: ${R}`);if(!te)return{verified:!1};let{credentialDeviceType:Ce,credentialBackedUp:pe}=qG(K);return{verified:!0,registrationInfo:{fmt:R,aaguid:S$(L),credentialType:m,credential:{id:Ti.fromBuffer(ue),publicKey:S,counter:G,transports:t.response.transports},attestationObject:w,userVerified:K.uv,credentialDeviceType:Ce,credentialBackedUp:pe,origin:f.origin,rpID:M,authenticatorExtensionResults:P}}}async function bQe(e){let{allowCredentials:t,challenge:i=await UG(),timeout:r=60000,userVerification:n="preferred",extensions:o,rpID:s}=e,a=i;if(typeof a==="string")a=li.fromUTF8String(a);return{rpId:s,challenge:Ti.fromBuffer(a),allowCredentials:t?.map((c)=>{if(!Ti.isBase64URL(c.id))throw Error(`allowCredential id "${c.id}" is not a valid base64url string`);return{...c,id:Ti.trimPadding(c.id),type:"public-key"}}),timeout:r,userVerification:n,extensions:o}}async function EQe(e){let{response:t,expectedChallenge:i,expectedOrigin:r,expectedRPID:n,expectedType:o,credential:s,requireUserVerification:a=!0,advancedFIDOConfig:c}=e,{id:u,rawId:d,type:p,response:m}=t;if(!u)throw Error("Missing credential ID");if(u!==d)throw Error("Credential ID was not base64url-encoded");if(p!=="public-key")throw Error(`Unexpected credential type ${p}, expected "public-key"`);if(!t)throw Error("Credential missing response");if(typeof m?.clientDataJSON!=="string")throw Error("Credential response clientDataJSON was not a string");let h=k$(m.clientDataJSON),{type:f,origin:g,challenge:y,tokenBinding:b}=h;if(Array.isArray(o)){if(!o.includes(f)){let M=o.join(", ");throw Error(`Unexpected authentication response type "${f}", expected one of: ${M}`)}}else if(o){if(f!==o)throw Error(`Unexpected authentication response type "${f}", expected "${o}"`)}else if(f!=="webauthn.get")throw Error(`Unexpected authentication response type: ${f}`);if(typeof i==="function"){if(!await i(y))throw Error(`Custom challenge verifier returned false for registration response challenge "${y}"`)}else if(y!==i)throw Error(`Unexpected authentication response challenge "${y}", expected "${i}"`);if(Array.isArray(r)){if(!r.includes(g)){let M=r.join(", ");throw Error(`Unexpected authentication response origin "${g}", expected one of: ${M}`)}}else if(g!==r)throw Error(`Unexpected authentication response origin "${g}", expected "${r}"`);if(!Ti.isBase64URL(m.authenticatorData))throw Error("Credential response authenticatorData was not a base64url string");if(!Ti.isBase64URL(m.signature))throw Error("Credential response signature was not a base64url string");if(m.userHandle&&typeof m.userHandle!=="string")throw Error("Credential response userHandle was not a string");if(b){if(typeof b!=="object")throw Error("ClientDataJSON tokenBinding was not an object");if(["present","supported","notSupported"].indexOf(b.status)<0)throw Error(`Unexpected tokenBinding status ${b.status}`)}let v=Ti.toBuffer(m.authenticatorData),w=zG(v),{rpIdHash:D,flags:R,counter:O,extensionsData:k}=w,j=[];if(typeof n==="string")j=[n];else j=n;let L=await $G(D,j);if(c!==void 0){let{userVerification:M}=c;if(M==="required"){if(!R.uv)throw Error("User verification required, but user could not be verified")}}else{if(!R.up)throw Error("User not present during authentication");if(a&&!R.uv)throw Error("User verification required, but user could not be verified")}let q=await xp(Ti.toBuffer(m.clientDataJSON)),K=li.concat([v,q]),ue=Ti.toBuffer(m.signature);if((O>0||s.counter>0)&&O<=s.counter)throw Error(`Response counter value ${O} was lower than expected ${s.counter}`);let{credentialDeviceType:G,credentialBackedUp:S}=qG(R);return{verified:await gp({signature:ue,data:K,credentialPublicKey:s.publicKey}),authenticationInfo:{newCounter:O,credentialID:s.id,userVerified:R.uv,credentialDeviceType:G,credentialBackedUp:S,authenticatorExtensionResults:k,origin:h.origin,rpID:L}}}var D$i="Anchor",I$i="Brain",_$i=l.looseObject({challenge:l.string().optional()});class WG{store;rpName;logger;constructor(e){this.store=new Rpe(e.runtimeDatabase),this.rpName=e.rpName??I$i,this.logger=e.logger}async hasCredentials(){return this.store.hasCredentials()}async generateRegistrationOptions(e,t){let i=await this.store.listCredentials(t.subject),r=t.userName??D$i,n=t.userDisplayName??r,o=await YJe({rpName:this.rpName,rpID:e.rpID,userName:r,userDisplayName:n,attestationType:"none",authenticatorSelection:{residentKey:"required",userVerification:"required"},excludeCredentials:i.map((s)=>({id:s.id,...s.transports?{transports:s.transports}:{}}))});return await this.store.saveRegistrationChallenge(o.challenge,t.subject),o}async verifyRegistrationResponse(e,t,i){let r=e.response.clientDataJSON?AQe(e.response.clientDataJSON):void 0;if(!r)return{verified:!1};let o=(await this.store.consumeRegistrationChallenge(r))?.userId;if(o===void 0||i!==void 0&&o!==i)return{verified:!1};let s=await yQe({response:e,expectedChallenge:r,expectedOrigin:t.origin,expectedRPID:t.rpID,requireUserVerification:!0});if(!s.verified)return{verified:!1};let a=s.registrationInfo.credential;return await this.store.addCredential({id:a.id,userId:o,publicKey:T$i(a.publicKey),counter:a.counter,...a.transports?{transports:a.transports}:{},credentialDeviceType:s.registrationInfo.credentialDeviceType,credentialBackedUp:s.registrationInfo.credentialBackedUp}),this.logger?.info("Registered passkey credential",{credentialId:a.id}),{verified:!0,subject:o}}async listCredentials(){return this.store.listCredentials()}async generateAuthenticationOptions(e){let t=await bQe({rpID:e.rpID,userVerification:"required"});return await this.store.saveAuthenticationChallenge(t.challenge),t}async verifyAuthenticationResponse(e,t){let i=e.response.clientDataJSON?AQe(e.response.clientDataJSON):void 0;if(!i)return{verified:!1};if(!await this.store.consumeAuthenticationChallenge(i))return{verified:!1};let n=await this.store.getCredential(e.id);if(!n)return{verified:!1};let o=await EQe({response:e,expectedChallenge:i,expectedOrigin:t.origin,expectedRPID:t.rpID,credential:R$i(n),requireUserVerification:!0});if(!o.verified)return{verified:!1};return await this.store.updateCredentialCounter(o.authenticationInfo.credentialID,o.authenticationInfo.newCounter),{verified:!0,subject:n.userId}}}function T$i(e){return Buffer.from(e).toString("base64url")}function P$i(e){let t=Buffer.from(e,"base64url"),i=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);return new Uint8Array(i)}function R$i(e){return{id:e.id,publicKey:P$i(e.publicKey),counter:e.counter,...e.transports?{transports:e.transports}:{}}}function AQe(e){try{return _$i.parse(JSON.parse(Buffer.from(e,"base64url").toString("utf8"))).challenge}catch{return}}class Uhe{issuer;users;identities;audit;setupFlow;targetedSetup;getChannelDescriptor;constructor(e){this.issuer=e.issuer,this.users=e.users,this.identities=e.identities,this.audit=e.audit,this.setupFlow=e.setupFlow,this.targetedSetup=e.targetedSetup,this.getChannelDescriptor=e.getChannelDescriptor}getSetupUrl(e=this.issuer){return this.setupFlow.getSetupUrl(e)}async startRegistration(e,t={},i){let r=await this.users.getUser(e);if(!r||r.status==="suspended")throw Error(`Eligible auth user not found: ${e}`);let n=i?await this.prepareDeliveryIdentity(e,i):await this.resolveStoredDeliveryIdentity(e),o=await this.setupFlow.createUserPasskeySetup(e,this.issuer,{deliveryClaimId:n.id});return await this.setupFlow.recordSetupDelivery(o.setupTokenId,n.deliverySubject),await this.audit.append({...xu(t),action:"auth.passkey.registration_started",targetType:"user",targetId:e,metadata:{expiresAt:o.expiresAt,deliveryType:n.type}}),{setupUrl:o.setupUrl,expiresAt:o.expiresAt,delivery:{type:n.type,label:this.getChannelDescriptor?.(n.type)?.subjectLabel??"Delivery channel"}}}async validateTargetedRegistration(e){await this.targetedSetup.validate({userId:e.targetUserId,setupTokenId:Uc(e.token)})}async completeTargetedRegistration(e){let t=await this.users.getUser(e.targetUserId),i=await this.targetedSetup.complete({userId:e.targetUserId,setupTokenId:Uc(e.token)});if(t?.status==="invited"&&i.user.status==="active")await this.audit.append({actorUserId:i.user.id,action:"auth.user.status_updated",targetType:"user",targetId:i.user.id,metadata:{status:"active"}});if(i.boundIdentity)await this.audit.append({actorUserId:i.user.id,action:"auth.identity.delivery_bound",targetType:"user",targetId:i.user.id,metadata:{type:i.boundIdentity.type}})}getPasskeySetupRequired(e=this.issuer){return this.setupFlow.getPasskeySetupRequired(e,{rotateHidden:!0})}getPasskeySetupRequiredForDelivery(e=this.issuer){return this.setupFlow.getPasskeySetupRequired(e)}hasSetupEmailDelivery(e,t){return this.setupFlow.hasSetupEmailDelivery(e,t)}recordSetupEmailDelivery(e,t,i={}){return this.setupFlow.recordSetupEmailDelivery(e,t,i)}async resolveStoredDeliveryIdentity(e){let i=(await this.identities.listIdentities(e)).filter((r)=>r.revokedAt===null&&Boolean(r.deliverySubject)&&r.evidence.some((n)=>n.sourceKind==="admin"||n.assurance==="verified"&&n.verifiedAt!==null)).at(-1);if(!i)throw Error("A confirmed delivery channel is required");return i}async prepareDeliveryIdentity(e,t){let i=t.subject.trim(),r=t.label?.trim(),{identity:n}=await this.identities.ensureIdentity({userId:e,type:t.type,subject:i,deliverySubject:i,label:r&&r.length>0?r:i,source:{kind:"admin"}});if(!n.deliverySubject)throw Error("Delivery identity subject was not persisted");return{...n,deliverySubject:n.deliverySubject}}}class VG{db;constructor(e){this.db=e}async invitePeerPerson(e){let t=ZG(e.peerId);return this.db.transaction(async(i)=>{await qhe(i,e.createdByUserId);let[r]=await i.select({peerId:on.peerId}).from(on).where(he(on.peerId,t)).limit(1);if(r)throw Error("External peer is already linked");let n=Date.now(),o={id:Nr("prsn"),displayName:e.displayName,profileEntityId:null,createdAt:n,updatedAt:n},s=Nr("usr"),a={id:s,personId:o.id,displayName:e.displayName,role:e.role,status:"invited",canonicalId:`user:${s.slice(4)}`,createdAt:n,updatedAt:n},c={peerId:t,personId:o.id,verificationStatus:"unverified",createdByUserId:e.createdByUserId,createdAt:n,updatedAt:n};return await i.insert(En).values(o),await i.insert(St).values(a),await i.insert(on).values(c),{person:o,user:a,peer:c}})}async linkPeer(e){let t=ZG(e.peerId);return this.db.transaction(async(i)=>{await qhe(i,e.createdByUserId);let[r]=await i.select().from(on).where(he(on.peerId,t)).limit(1);if(r){if(r.personId!==e.personId)throw Error("External peer is already linked to another person");return r}let[n]=await i.select({id:En.id}).from(En).where(he(En.id,e.personId)).limit(1);if(!n)throw Error(`Auth person not found: ${e.personId}`);let o=Date.now(),s={peerId:t,personId:n.id,verificationStatus:"unverified",createdByUserId:e.createdByUserId,createdAt:o,updatedAt:o};return await i.insert(on).values(s),s})}async unlinkPeer(e){let t=ZG(e.peerId);return this.db.transaction(async(i)=>{await qhe(i,e.actorUserId);let[r]=await i.select().from(on).where(bt(he(on.peerId,t),he(on.personId,e.personId))).limit(1);if(!r)throw Error("External peer link was not found");return await i.delete(on).where(bt(he(on.peerId,t),he(on.personId,e.personId))),r})}async getByPeerId(e){let[t]=await this.db.select().from(on).where(he(on.peerId,ZG(e))).limit(1);return t}async listByPersonId(e){return this.db.select().from(on).where(he(on.personId,e)).orderBy(on.createdAt,Ci`rowid`)}async listAll(){return this.db.select().from(on).orderBy(on.createdAt,Ci`rowid`)}}function ZG(e){let t=e.trim();if(!t)throw Error("External peer id is required");return t}async function qhe(e,t){let[i]=await e.select().from(St).where(he(St.id,t)).limit(1);if(i?.role!=="admin"||i.status!=="active")throw Error("An active Admin is required to link an external peer");return i}class KG{database;constructor(e){this.database=e}async get(e){let[t]=await this.database.db.select().from(Ey).where(he(Ey.domain,$he(e))).limit(1);return t?{domain:t.domain,keyFingerprint:t.keyFingerprint,grantedLevel:t.grantedLevel}:void 0}async grant(e,t={}){if(e.grantedLevel==="admin")throw Error("A2A peer trust grants must be trusted or public");let i={domain:$he(e.domain),keyFingerprint:e.keyFingerprint,grantedLevel:e.grantedLevel},r=Date.now();return await this.database.db.insert(Ey).values({domain:i.domain,keyFingerprint:i.keyFingerprint,grantedLevel:i.grantedLevel,createdAt:r,updatedAt:r}).onConflictDoUpdate({target:Ey.domain,set:{keyFingerprint:i.keyFingerprint,grantedLevel:i.grantedLevel,updatedAt:r}}),await new C0(this.database.db).append({...t.actorUserId?{actorUserId:t.actorUserId}:{},action:"auth.a2a_peer_trust.granted",targetType:"a2a_peer",targetId:i.domain,metadata:{keyFingerprint:i.keyFingerprint,grantedLevel:i.grantedLevel}}),i}async revoke(e,t={}){let i=$he(e);if((await this.database.db.delete(Ey).where(he(Ey.domain,i)).returning({domain:Ey.domain})).length>0)await new C0(this.database.db).append({...t.actorUserId?{actorUserId:t.actorUserId}:{},action:"auth.a2a_peer_trust.revoked",targetType:"a2a_peer",targetId:i})}}function $he(e){let t=e.trim().toLowerCase();if(!t||t.includes(":")||t.includes("/"))throw Error("A2A peer trust domain must be a bare domain");return t}import{randomUUID as vQe}from"crypto";var eP=86400;class Ghe{setupStateStore;passkeyService;setupTokenTtlSeconds;resolveSessionUserId;setupOperations=new XA;resolveHomePath;setupToken;constructor(e){this.setupStateStore=e.setupStateStore,this.passkeyService=e.passkeyService,this.setupTokenTtlSeconds=e.setupTokenTtlSeconds??eP,this.resolveSessionUserId=e.resolveSessionUserId,this.resolveHomePath=e.resolveHomePath??(()=>"/")}ensureSetupToken(){return this.setupOperations.run(()=>this.ensureSetupTokenInternal())}async ensureSetupTokenInternal(){let e=await this.getActiveSetupToken();if(e)return e;let t=Math.floor(Date.now()/1000);if(await this.setupStateStore.hasActiveSetupToken(t))return await this.setupStateStore.hasActiveSetupDelivery(t)?void 0:this.createSetupToken();return this.createSetupToken()}async createSetupToken(){let e={token:`setup_${vQe()}`,expiresAt:Math.floor(Date.now()/1000)+this.setupTokenTtlSeconds};return await this.setupStateStore.saveSetupToken(e),this.setupToken=e,e}async getActiveSetupToken(){return this.setupToken=await this.setupStateStore.getValidSetupToken(Math.floor(Date.now()/1000)),this.setupToken}getValidSetupToken(){if(!this.setupToken)return;if(this.setupToken.expiresAt<=Math.floor(Date.now()/1000)){this.setupToken=void 0;return}return this.setupToken}async resolveSetupToken(e){let t=new URL(e.url),i=t.searchParams.get("setup_token")??t.searchParams.get("token");if(!i)return;let r=await this.setupStateStore.getSetupTokenTarget(i,Math.floor(Date.now()/1000));return r?{token:i,...r}:void 0}async hasValidSetupToken(e){return Boolean(await this.resolveSetupToken(e))}async hasConflictingAccountSession(e,t){if(!t.targetUserId||!this.resolveSessionUserId)return!1;let i=await this.resolveSessionUserId(e);return i!==void 0&&i!==t.targetUserId}consumeSetupToken(e){return this.setupOperations.run(async()=>{if(this.setupToken?.token===e)this.setupToken=void 0;await this.setupStateStore.consumeSetupToken(e)})}clearSetupState(){return this.setupOperations.run(async()=>{this.setupToken=void 0,await this.setupStateStore.clearSetupState()})}getSetupUrl(e){let t=this.getValidSetupToken();if(!t)return;return Dl(e,`/setup?token=${encodeURIComponent(t.token)}`)}getPasskeySetupRequired(e,t={}){return this.setupOperations.run(async()=>{if(await this.passkeyService.hasCredentials())return;let i=await this.getActiveSetupToken();if(!i&&t.rotateHidden){let r=Math.floor(Date.now()/1000);if(await this.setupStateStore.hasActiveSetupDelivery(r))return;i=await this.createSetupToken()}if(!i)return;return{setupUrl:Dl(e,`/setup?token=${encodeURIComponent(i.token)}`),expiresAt:i.expiresAt,setupTokenId:Uc(i.token)}})}async createUserPasskeySetup(e,t,i={}){let r={token:`setup_${vQe()}`,expiresAt:Math.floor(Date.now()/1000)+this.setupTokenTtlSeconds};return await this.setupStateStore.saveTargetedSetupToken(r,e,i),{setupUrl:Dl(t,`/setup?token=${encodeURIComponent(r.token)}`),expiresAt:r.expiresAt,setupTokenId:Uc(r.token)}}consumeTargetedSetupTokensForUser(e){return this.setupStateStore.consumeTargetedSetupTokensForUser(e)}async handleSetupPage(e){let t=await this.resolveSetupToken(e);if(await this.passkeyService.hasCredentials()&&t?.targetUserId==null)return vA(qHe(),404);if(!t)return new Response("Not Found",{status:404});if(await this.hasConflictingAccountSession(e,t)){let i=new URL(e.url);return vA($He(`${i.pathname}${i.search}`),409)}return vA(GHe(t.token,this.resolveHomePath()))}async hasSetupDelivery(e,t){return this.setupStateStore.hasDelivery(e,t)}async recordSetupDelivery(e,t,i={}){await this.setupStateStore.recordDelivery(e,t,i)}async hasSetupEmailDelivery(e,t){return this.hasSetupDelivery(e,t)}async recordSetupEmailDelivery(e,t,i={}){await this.recordSetupDelivery(e,t,i)}}class Hhe{db;identityStore;constructor(e,t){this.db=e,this.identityStore=t}async validate(e){await wQe(this.db,e)}async complete(e){let t=Math.floor(Date.now()/1000),i=Date.now(),r=await this.db.transaction(async(n)=>{let o=await wQe(n,e),s=o.deliveryClaim;if(s){let[c]=await n.select({id:rs.id}).from(rs).where(bt(he(rs.claimId,s.id),he(rs.assurance,"verified"),_9(rs.verifiedAt))).limit(1);if(!c)await n.insert(rs).values({id:Nr("aev"),claimId:s.id,sourceKind:"provider",sourceId:null,assurance:"verified",verifiedAt:i,createdAt:i})}if(o.user.status==="invited")await n.update(St).set({status:"active",updatedAt:i}).where(he(St.id,o.user.id));if((await n.update(ut).set({consumedAt:t}).where(bt(he(ut.tokenHash,e.setupTokenId),gi(ut.consumedAt))).returning({tokenHash:ut.tokenHash})).length!==1)throw Error("Invalid or consumed setup token");return await n.update(ci).set({state:"claimed",claimedAt:i,updatedAt:i}).where(he(ci.currentSetupTokenHash,e.setupTokenId)),s?.id});return{user:await this.requireUser(e.userId),...r?{boundIdentity:await this.identityStore.getIdentity(r)}:{}}}async requireUser(e){let[t]=await this.db.select().from(St).where(he(St.id,e)).limit(1);if(!t)throw Error(`Auth user not found: ${e}`);return t}}class Yy extends Error{reason;constructor(e,t){super(t);this.name="TargetedSetupError",this.reason=e}}async function wQe(e,t){let i=Math.floor(Date.now()/1000),[r]=await e.select().from(ut).where(bt(he(ut.tokenHash,t.setupTokenId),he(ut.purpose,"passkey_setup"),he(ut.targetUserId,t.userId),gi(ut.consumedAt),jc(ut.expiresAt,i))).limit(1);if(!r)throw new Yy("token-invalid","Invalid or consumed setup token");let[n]=await e.select().from(St).where(he(St.id,t.userId)).limit(1);if(!n||n.status==="suspended")throw new Yy("user-unavailable","Passkey registration user is unavailable");if(!r.deliveryClaimId)return{user:n};let[o]=await e.select().from(pi).where(bt(he(pi.id,r.deliveryClaimId),gi(pi.revokedAt))).limit(1);if(!o)throw new Yy("delivery-identity-unavailable","Setup delivery identity is unavailable");if(o.personId!==n.personId)throw new Yy("delivery-identity-unavailable","Setup delivery identity does not belong to target user");if(o.type!=="email"&&o.type!=="discord"||!o.deliverySubject)throw new Yy("delivery-identity-unavailable","Setup delivery identity is unavailable");let[s]=await e.select({tokenHash:zc.tokenHash}).from(zc).where(bt(he(zc.tokenHash,t.setupTokenId),he(zc.recipientHash,n8(o.deliverySubject)))).limit(1);if(!s)throw new Yy("delivery-unconfirmed","Setup delivery was not confirmed");return{user:n,deliveryClaim:o}}class Whe{users;audit;sessions;refreshTokens;consumeTargetedSetupTokensForUser;onUserDeleted;constructor(e){this.users=e.users,this.audit=e.audit,this.sessions=e.sessions,this.refreshTokens=e.refreshTokens,this.consumeTargetedSetupTokensForUser=e.consumeTargetedSetupTokensForUser,this.onUserDeleted=e.onUserDeleted}async createUser(e,t={}){let i=await this.users.createUser(e);return await this.audit.append({...xu(t),action:"auth.user.created",targetType:"user",targetId:i.id,metadata:{role:i.role,status:i.status}}),i}async updateRole(e,t,i={}){let r=await this.users.getUser(e),n=await this.users.updateUserRole(e,t);if(r&&r.role!==n.role)await this.revokeGrants(e),await this.audit.append({...xu(i),action:"auth.user.role_updated",targetType:"user",targetId:e,metadata:{from:r.role,to:n.role}});return n}async updateStatus(e,t,i={}){let r=await this.users.getUser(e),n=await this.users.updateUserStatus(e,t);if(r&&r.status!==n.status){let o=n.status==="suspended"?await this.consumeTargetedSetupTokensForUser(e):0;await this.revokeGrants(e),await this.audit.append({...xu(i),action:"auth.user.status_updated",targetType:"user",targetId:e,metadata:{from:r.status,to:n.status,...o>0?{consumedSetupTokens:o}:{}}})}return n}async deleteSuspendedUser(e,t={}){let i=await this.users.deleteSuspendedUser(e);return this.onUserDeleted?.(e),await this.audit.append({...xu(t),action:"auth.user.deleted",targetType:"user",targetId:e,metadata:{role:i.role,status:i.status}}),i}async revokeGrants(e,t={}){let[i,r]=await Promise.all([this.sessions.revokeSessionsForSubject(e),this.refreshTokens.revokeTokensForSubject(e)]);if(t.actorUserId)await this.audit.append({...xu(t),action:"auth.user.grants_revoked",targetType:"user",targetId:e,metadata:{sessions:i,refreshTokens:r}});return{sessions:i,refreshTokens:r}}}class Zhe{passkeyService;sessionStore;setupFlow;registrationUserProvider;validateTargetedRegistration;completeTargetedRegistration;recordAuditEvent;constructor(e){this.passkeyService=e.passkeyService,this.sessionStore=e.sessionStore,this.setupFlow=e.setupFlow,this.registrationUserProvider=e.registrationUserProvider,this.validateTargetedRegistration=e.validateTargetedRegistration,this.completeTargetedRegistration=e.completeTargetedRegistration,this.recordAuditEvent=e.recordAuditEvent}async handleRegistrationOptions(e){let t=await this.resolveRegistrationSetup(e);if(t instanceof Response)return t;try{let i=await this.passkeyService.generateRegistrationOptions(YG(e),await this.registrationUserProvider(t.targetUserId??void 0));return dd(i)}catch{return Vn("access_denied","Passkey registration user is unavailable")}}async handleRegistrationVerify(e){let t=await this.resolveRegistrationSetup(e);if(t instanceof Response)return t;if(t.targetUserId)try{await this.registrationUserProvider(t.targetUserId),await this.validateTargetedRegistration?.({...t,targetUserId:t.targetUserId})}catch(o){return await this.recordRegistrationFailure(t.targetUserId),Vn("access_denied",kQe(o))}let i=s$.safeParse(await e.json());if(!i.success)return await this.recordRegistrationFailure(t.targetUserId),Vn("access_denied","Passkey registration failed");let r=await this.passkeyService.verifyRegistrationResponse(i.data,YG(e),t.targetUserId??void 0);if(!r.verified||t.targetUserId!==null&&r.subject!==t.targetUserId)return await this.recordRegistrationFailure(t.targetUserId),Vn("access_denied","Passkey registration failed");if(t.targetUserId&&this.completeTargetedRegistration)try{await this.completeTargetedRegistration({...t,targetUserId:t.targetUserId})}catch(o){return await this.recordRegistrationFailure(t.targetUserId),Vn("access_denied",kQe(o))}else await this.setupFlow.consumeSetupToken(t.token);let n=await this.sessionStore.createSession(r.subject,{secure:e8(e)});return dd({verified:!0},200,{"Set-Cookie":n.cookie})}async resolveRegistrationSetup(e){let t=await this.setupFlow.resolveSetupToken(e);if(await this.passkeyService.hasCredentials()&&t?.targetUserId==null)return Vn("access_denied","Passkey setup already completed");if(!t)return Vn("access_denied","Invalid setup token");if(await this.setupFlow.hasConflictingAccountSession(e,t))return Vn("access_denied","Sign out before using a setup link for another account");return t}async recordRegistrationFailure(e){await this.recordAuditEvent?.({action:"auth.passkey.registration_failed",...e?{targetType:"user",targetId:e}:{}})}async handleAuthenticationOptions(e){if(!await this.passkeyService.hasCredentials())return Vn("access_denied","No passkey registered");let t=await this.passkeyService.generateAuthenticationOptions(YG(e));return dd(t)}async handleAuthenticationVerify(e){let t=PHe.safeParse(await e.json());if(!t.success)return await this.recordAuditEvent?.({action:"auth.passkey.authentication_failed"}),Vn("access_denied","Passkey authentication failed");let i=await this.passkeyService.verifyAuthenticationResponse(t.data,YG(e));if(!i.verified)return await this.recordAuditEvent?.({action:"auth.passkey.authentication_failed"}),Vn("access_denied","Passkey authentication failed");let r=await this.sessionStore.createSession(i.subject,{secure:e8(e)});return dd({verified:!0},200,{"Set-Cookie":r.cookie})}}function YG(e){let t=u0(e),i=new URL(t);return{origin:i.origin,rpID:i.hostname}}var SQe={"token-invalid":"Invalid setup token","user-unavailable":"Passkey registration user is unavailable","delivery-identity-unavailable":"This setup link's delivery address is no longer valid; ask an admin for a new link","delivery-unconfirmed":"This setup link has not been confirmed as delivered; ask an admin to confirm it"};function kQe(e){return e instanceof Yy?SQe[e.reason]:SQe["user-unavailable"]}class Vhe{keyStore;a2aKeyStore;clientStore;authCodeStore;sessionStore;peerTrustStore;passkeyService;setupFlow;oauthEndpoints;webauthnEndpoints;runtimeDatabase;runBackgroundOperation;refreshTokenStore;issuer;trustedIssuers;allowLocalhostIssuers;anchor;anchorProfileEntityId;setupTokenTtlSeconds;issuesSetupLinks;getOnboardingDetails;getInvitationDeliveryProvider;getChannelDescriptor;isChannelTypeRegistered;autoStartInvitationDeliveryRecovery;invitationDeliveryRecoveryIntervalMs;invitationDeliveryRecoveryStaleMs;resolveProfileDisplayName;accountSettingsEncryptionKey;onAccountDeleted;logger;accountSettingsStore;userStore;identityReconciliationService;passkeySetupCoordinator;userManagementService;principalService;administrationService;accountService;invitationService;invitationDeliverySupervisor;interfacePrincipalStore;auditStore;lifecycleTail=Promise.resolve();initialization;firstAdminInitialization;closePromise;constructor(e){this.runBackgroundOperation=e.runBackgroundOperation,this.issuer=e.issuer,this.trustedIssuers=e.trustedIssuers,this.allowLocalhostIssuers=e.allowLocalhostIssuers,this.anchor=e.anchor,this.anchorProfileEntityId=e.anchorProfileEntityId,this.setupTokenTtlSeconds=e.setupTokenTtlSeconds??eP,this.issuesSetupLinks=e.issuesSetupLinks??!0,this.getInvitationDeliveryProvider=e.getInvitationDeliveryProvider,this.getOnboardingDetails=e.getOnboardingDetails,this.getChannelDescriptor=e.getChannelDescriptor,this.isChannelTypeRegistered=e.isChannelTypeRegistered,this.autoStartInvitationDeliveryRecovery=e.autoStartInvitationDeliveryRecovery??!0,this.invitationDeliveryRecoveryIntervalMs=e.invitationDeliveryRecoveryIntervalMs??KWe,this.invitationDeliveryRecoveryStaleMs=e.invitationDeliveryRecoveryStaleMs??$pe,this.resolveProfileDisplayName=e.resolveProfileDisplayName,this.accountSettingsEncryptionKey=e.accountSettingsEncryptionKey,this.onAccountDeleted=e.onAccountDeleted,this.logger=e.logger,this.runtimeDatabase=new I9({storageDir:e.storageDir,...e.replica?{replica:e.replica}:{}}),this.keyStore=new g$(this.runtimeDatabase),this.a2aKeyStore=new Hpe(this.runtimeDatabase),this.clientStore=new h$(this.runtimeDatabase,this.issuer),this.authCodeStore=new o$(this.runtimeDatabase),this.sessionStore=new r_(this.runtimeDatabase),this.refreshTokenStore=new t_(this.runtimeDatabase),this.peerTrustStore=new KG(this.runtimeDatabase),this.passkeyService=new WG({runtimeDatabase:this.runtimeDatabase,...e.logger?{logger:e.logger}:{}});let t=new jpe(this.runtimeDatabase);this.setupFlow=new Ghe({...e.resolveHomePath?{resolveHomePath:e.resolveHomePath}:{},setupStateStore:t,passkeyService:this.passkeyService,setupTokenTtlSeconds:this.setupTokenTtlSeconds,resolveSessionUserId:async(i)=>(await this.resolveActiveSession(i))?.user.id}),this.oauthEndpoints=new Vpe({clientStore:this.clientStore,authCodeStore:this.authCodeStore,refreshTokenStore:this.refreshTokenStore,resolveSession:async(i)=>(await this.resolveActiveSession(i))?.session,keyStore:this.keyStore,...e.clientMetadataDocumentResolver?{clientMetadataDocumentResolver:e.clientMetadataDocumentResolver}:{},...e.oauthClientMaintenanceIntervalMs!==void 0?{clientMaintenanceIntervalMs:e.oauthClientMaintenanceIntervalMs}:{},runClientMaintenance:this.runBackgroundOperation,onClientMaintenanceError:(i)=>{this.logger?.warn("Failed to prune stale OAuth clients",{error:i})}}),this.webauthnEndpoints=new Zhe({passkeyService:this.passkeyService,sessionStore:this.sessionStore,setupFlow:this.setupFlow,recordAuditEvent:async(i)=>{await this.getAuditStore().append(i)},validateTargetedRegistration:async(i)=>{await this.getPasskeySetupCoordinator().validateTargetedRegistration(i)},completeTargetedRegistration:async(i)=>{await this.getPasskeySetupCoordinator().completeTargetedRegistration(i)},registrationUserProvider:async(i)=>{let r=i?await this.getUserStore().getUser(i):await this.ensureFirstAdminUser();if(!r||r.status==="suspended")throw Error("Passkey registration user is unavailable");return{subject:r.id,userName:r.displayName,userDisplayName:r.displayName}}})}async initialize(){if(this.initialization)return this.initialization;let e=this.startLifecycle(()=>this.initializeInternal());this.initialization=e;try{await e}catch(t){if(this.initialization===e)this.initialization=void 0;throw t}}close(){if(!this.closePromise)this.initialization=void 0,this.closePromise=this.enqueueLifecycle(()=>this.closeInternal());return this.closePromise}ensureStarted(){return this.startLifecycle(()=>this.ensureStartedInternal())}enqueueLifecycle(e){let t=this.lifecycleTail.then(e);return this.lifecycleTail=t.then(()=>{return}).catch(()=>{}),t}startLifecycle(e){this.closePromise=void 0;let t=this.initialization;return this.enqueueLifecycle(async()=>{try{return await e()}catch(i){if(this.initialization===t)this.initialization=void 0;try{await this.closeInternal()}catch(r){throw AggregateError([i,r],"Auth startup and rollback failed",{cause:r})}throw i}})}async ensureStartedInternal(){if(this.userStore)return;await this.runtimeDatabase.start();let e=new O9(this.runtimeDatabase.db,{...this.isChannelTypeRegistered?{isChannelTypeRegistered:this.isChannelTypeRegistered}:{}});this.userStore=new o_(this.runtimeDatabase.db),this.identityReconciliationService=new Fpe({identities:e,users:this.userStore});let t=new Hhe(this.runtimeDatabase.db,e);this.interfacePrincipalStore=new Jq(this.runtimeDatabase.db);let i=new VG(this.runtimeDatabase.db);this.auditStore=new C0(this.runtimeDatabase.db),this.invitationService=new x$({db:this.runtimeDatabase.db,issuer:this.issuer,setupTokenTtlSeconds:this.setupTokenTtlSeconds,deliveryRecoveryStaleMs:this.invitationDeliveryRecoveryStaleMs,audit:this.auditStore,...this.getInvitationDeliveryProvider?{getDeliveryProvider:this.getInvitationDeliveryProvider}:{},...this.getChannelDescriptor?{getChannelDescriptor:this.getChannelDescriptor}:{},getOnboardingContext:async()=>{let[n,o]=await Promise.all([this.profileDisplayName(this.anchorProfileEntityId),this.getOnboardingDetails?.()]);return{links:o?.links??{},...o?.purpose?{purpose:o.purpose}:{},...n?{brainName:n}:{}}}}),this.invitationDeliverySupervisor=new Gpe(this.invitationDeliveryRecoveryIntervalMs,(n)=>this.runBackgroundOperation(async()=>{await this.getInvitationService().recoverInterruptedDeliveries(n)}),{onError:(n)=>{this.logger?.warn("Failed to recover invitation delivery",{error:n})}}),this.passkeySetupCoordinator=new Uhe({issuer:this.issuer,users:this.userStore,identities:e,audit:this.auditStore,setupFlow:this.setupFlow,targetedSetup:t,...this.getChannelDescriptor?{getChannelDescriptor:this.getChannelDescriptor}:{}}),this.userManagementService=new Whe({users:this.userStore,audit:this.auditStore,sessions:this.sessionStore,refreshTokens:this.refreshTokenStore,consumeTargetedSetupTokensForUser:(n)=>this.setupFlow.consumeTargetedSetupTokensForUser(n),...this.onAccountDeleted?{onUserDeleted:this.onAccountDeleted}:{}}),this.principalService=new _pe({issuer:this.issuer,trustedIssuers:this.trustedIssuers,allowLocalhostIssuers:this.allowLocalhostIssuers,users:this.userStore,identities:e,sessions:this.sessionStore,ensureFirstAdminUser:()=>this.ensureFirstAdminUser(),getJwks:()=>this.getJwks()});let r=new m_(this.runtimeDatabase.db);this.accountService=new dpe({users:this.userStore,identities:e,credentials:r,sessions:this.sessionStore,refreshTokens:this.refreshTokenStore,passkeys:this.passkeyService,audit:this.auditStore,...this.isChannelTypeRegistered?{isChannelTypeRegistered:this.isChannelTypeRegistered}:{}}),this.administrationService=new Tpe({configuredAnchorKind:this.anchor,...this.resolveProfileDisplayName?{resolveProfileDisplayName:this.resolveProfileDisplayName}:{},users:this.userStore,identities:e,credentials:r,externalPeers:i,invitations:this.getInvitationService(),audit:this.auditStore,management:this.getUserManagementService(),...this.getChannelDescriptor?{getChannelDescriptor:this.getChannelDescriptor}:{},startPasskeyRegistration:(n,o,s)=>this.getPasskeySetupCoordinator().startRegistration(n,o,s)})}getUserStore(){return sx(this.userStore)}getIdentityReconciliationService(){return sx(this.identityReconciliationService)}getPasskeySetupCoordinator(){return sx(this.passkeySetupCoordinator)}getPrincipalService(){return sx(this.principalService)}getAdministrationService(){return sx(this.administrationService)}getAccountService(){return sx(this.accountService)}getInvitationService(){return sx(this.invitationService)}startInvitationDeliveryRecovery(){return this.startLifecycle(async()=>{await this.ensureStartedInternal(),await this.invitationDeliverySupervisor?.start()})}getInterfacePrincipalStore(){return sx(this.interfacePrincipalStore)}getAuditStore(){return sx(this.auditStore)}getAccountSettingsStore(){if(!this.accountSettingsEncryptionKey)return;return this.accountSettingsStore??=new mpe(this.runtimeDatabase.db,this.accountSettingsEncryptionKey),this.accountSettingsStore}hasPasskeyCredentials(){return this.startLifecycle(async()=>(await this.ensureStartedInternal(),this.passkeyService.hasCredentials()))}getSetupUrl(e=this.issuer){return this.setupFlow.getSetupUrl(e)}getJwks(){return this.startLifecycle(async()=>{await this.loadSigningKeys();let[e,t]=await Promise.all([this.keyStore.getPublicJwk(),this.a2aKeyStore.getPublicJwk()]);return{keys:[e,t]}})}getA2APrivateJwk(){return this.startLifecycle(()=>this.a2aKeyStore.getPrivateJwk())}async loadSigningKeys(){let e=await Promise.allSettled([this.keyStore.getPrivateJwk(),this.a2aKeyStore.getPrivateJwk()]);for(let t of e)if(t.status==="rejected")throw t.reason}getUserManagementService(){return sx(this.userManagementService)}async initializeInternal(){if(await this.ensureStartedInternal(),this.autoStartInvitationDeliveryRecovery)await this.invitationDeliverySupervisor?.start();if(await this.projectConfiguredBrainAnchor(),await this.loadSigningKeys(),this.logger?.debug("Auth service signing keys loaded"),this.issuesSetupLinks&&!await this.passkeyService.hasCredentials()){await this.setupFlow.ensureSetupToken();let e=this.getSetupUrl();if(e)if(kf(this.issuer))this.logger?.warn(`Passkey setup required: ${e}`);else this.logger?.warn("Passkey setup required. Ask through an Admin interface for the setup URL.")}await this.oauthEndpoints.startClientMaintenance()}async closeInternal(){let e=[];for(let t of[()=>this.oauthEndpoints.stopClientMaintenance(),()=>this.invitationDeliverySupervisor?.close()??Promise.resolve()])try{await t()}catch(i){e.push(i)}this.invitationDeliverySupervisor=void 0,this.accountSettingsStore=void 0,this.userStore=void 0,this.identityReconciliationService=void 0,this.passkeySetupCoordinator=void 0,this.userManagementService=void 0,this.principalService=void 0,this.administrationService=void 0,this.accountService=void 0,this.invitationService=void 0,this.interfacePrincipalStore=void 0,this.auditStore=void 0,this.firstAdminInitialization=void 0;try{await this.runtimeDatabase.stop()}catch(t){e.push(t)}if(e.length===1)throw e[0];if(e.length>1)throw AggregateError(e,"Auth runtime shutdown failed")}profileDisplayName(e){return p$(this.resolveProfileDisplayName,e,this.logger)}async projectConfiguredBrainAnchor(){let e=await this.getUserStore().getBrainAnchor(),t=await this.profileDisplayName(this.anchorProfileEntityId),i=t??e?.displayName??(this.anchor==="person"?"Admin":this.anchor==="team"?"Team":"Organization");await this.getUserStore().configureBrainAnchor({kind:this.anchor==="person"?"person":"collective",displayName:i,profileEntityId:this.anchorProfileEntityId,...t?{subjectDisplayName:t}:{}})}async ensureFirstAdminUser(){if(this.firstAdminInitialization)return this.firstAdminInitialization;let e=(async()=>{let t=await this.getUserStore().listUsers(),i=await this.getUserStore().ensureFirstAdminUser();if(await this.projectConfiguredBrainAnchor(),!t.some((r)=>r.id===i.id))await this.getAuditStore().append({action:"auth.user.created",targetType:"user",targetId:i.id,metadata:{role:i.role,status:i.status}});return i})();this.firstAdminInitialization=e;try{return await e}finally{if(this.firstAdminInitialization===e)this.firstAdminInitialization=void 0}}async resolveActiveSession(e){return await this.ensureStarted(),this.getPrincipalService().resolveActiveSession(e)}}function sx(e){if(!e)throw Error("Auth service has not been initialized");return e}import{AsyncLocalStorage as F$i}from"async_hooks";class Khe{admission=new XA;context=new F$i;active=new Set;closePromise;pendingCloses=0;backgroundOpen=!0;run(e){if(this.context.getStore()?.active)return this.admit(e).result;return this.closePromise=void 0,this.admission.run(()=>{if(this.pendingCloses===0)this.backgroundOpen=!0;return this.admit(e)}).then(({result:t})=>t)}runBackground(e){if(this.backgroundOpen)return this.admit(e).result;return Promise.resolve()}close(e){if(this.context.getStore()?.active)return Promise.reject(Error("Cannot close auth service from an active auth operation"));if(!this.closePromise)this.pendingCloses+=1,this.backgroundOpen=!1,this.closePromise=this.admission.run(async()=>{try{while(this.active.size>0)await Promise.all([...this.active]);await e()}finally{this.context.disable(),this.pendingCloses-=1}});return this.closePromise}admit(e){let t={active:!0},i=Promise.resolve().then(()=>this.context.run(t,e)),r=()=>{t.active=!1,this.active.delete(n)},n=i.then(r,r);return this.active.add(n),{result:i}}}var M$i="anchor-profile/anchor-profile";class JG{issuer;runtime;operations=new Khe;requestRouter;getInvitationDeliveryProvider;getChannelDescriptor;listChannelDescriptors;accountSettingsRegistry;logger;constructor(e){this.issuer=vy(e.issuer),this.getInvitationDeliveryProvider=e.getInvitationDeliveryProvider,this.getChannelDescriptor=e.getChannelDescriptor,this.listChannelDescriptors=e.listChannelDescriptors,this.accountSettingsRegistry=e.accountSettingsRegistry,this.logger=e.logger;let t=e.isChannelTypeRegistered??(e.getChannelDescriptor?(i)=>Boolean(e.getChannelDescriptor?.(i)):void 0);this.runtime=new Vhe({storageDir:e.storageDir,runBackgroundOperation:(i)=>this.operations.runBackground(i),...e.replica?{replica:e.replica}:{},issuer:this.issuer,trustedIssuers:new Set([this.issuer,...(e.trustedIssuers??[]).map((i)=>vy(i))]),allowLocalhostIssuers:e.allowLocalhostIssuers??kf(this.issuer),anchor:e.anchor??"person",anchorProfileEntityId:e.anchorProfileEntityId??M$i,...e.resolveProfileDisplayName?{resolveProfileDisplayName:e.resolveProfileDisplayName}:{},...e.resolveHomePath?{resolveHomePath:e.resolveHomePath}:{},...e.setupTokenTtlSeconds!==void 0?{setupTokenTtlSeconds:e.setupTokenTtlSeconds}:{},...e.issuesSetupLinks!==void 0?{issuesSetupLinks:e.issuesSetupLinks}:{},...e.getOnboardingDetails?{getOnboardingDetails:e.getOnboardingDetails}:{},...e.getInvitationDeliveryProvider?{getInvitationDeliveryProvider:e.getInvitationDeliveryProvider}:{},...e.getChannelDescriptor?{getChannelDescriptor:e.getChannelDescriptor}:{},...t?{isChannelTypeRegistered:t}:{},...e.autoStartInvitationDeliveryRecovery!==void 0?{autoStartInvitationDeliveryRecovery:e.autoStartInvitationDeliveryRecovery}:{},...e.invitationDeliveryRecoveryIntervalMs!==void 0?{invitationDeliveryRecoveryIntervalMs:e.invitationDeliveryRecoveryIntervalMs}:{},...e.invitationDeliveryRecoveryStaleMs!==void 0?{invitationDeliveryRecoveryStaleMs:e.invitationDeliveryRecoveryStaleMs}:{},...e.oauthClientMaintenanceIntervalMs!==void 0?{oauthClientMaintenanceIntervalMs:e.oauthClientMaintenanceIntervalMs}:{},...e.clientMetadataDocumentResolver?{clientMetadataDocumentResolver:e.clientMetadataDocumentResolver}:{},...e.accountSettingsEncryptionKey?{accountSettingsEncryptionKey:e.accountSettingsEncryptionKey}:{},...e.onAccountDeleted?{onAccountDeleted:e.onAccountDeleted}:{},...e.logger?{logger:e.logger}:{}}),this.requestRouter=new upe({setupFlow:this.runtime.setupFlow,oauthEndpoints:this.runtime.oauthEndpoints,webauthnEndpoints:this.runtime.webauthnEndpoints,handleAdminRequest:(i)=>this.handleAdminRequest(i),handleAccountRequest:(i)=>this.handleAccountRequest(i),revokeSession:async(i)=>{await this.runtime.sessionStore.revokeSessionFromRequest(i)},getAuthorizationServerMetadata:(i)=>this.getAuthorizationServerMetadata(i),getProtectedResourceMetadata:(i,r)=>this.getProtectedResourceMetadata(i,r),getJwks:()=>this.getJwks()})}getIssuer(){return this.issuer}initialize(){return this.operations.run(()=>this.runtime.initialize())}startInvitationDeliveryRecovery(){return this.operations.run(()=>this.runtime.startInvitationDeliveryRecovery())}close(){return this.operations.close(()=>this.runtime.close())}async initializeConfiguredInterfacePrincipals(e){return this.operations.run(async()=>{await this.initialize();let t=this.runtime.getInterfacePrincipalStore();return await t.seedConfigOnce(e),t.listActiveState()})}async resolveInterfacePrincipal(e,t){return this.operations.run(async()=>(await this.initialize(),this.runtime.getInterfacePrincipalStore().resolve(e,t)))}getAccountSettingsBackend(){return this.runtime.getAccountSettingsStore()}hasPasskeyCredentials(){return this.operations.run(()=>this.runtime.hasPasskeyCredentials())}async revokePasskey(e,t={}){return this.operations.run(async()=>{await this.runtime.ensureStarted(),await this.runtime.getAdministrationService().revokePasskey(e,t)})}getJwks(){return this.operations.run(()=>this.runtime.getJwks())}async getA2ASigningKey(){return this.operations.run(async()=>{let e=await this.runtime.getA2APrivateJwk();return{privateJwk:e,keyId:Dl(this.issuer,`/.well-known/jwks.json#${e.kid}`)}})}async grantA2APeerTrust(e,t={}){return this.operations.run(async()=>(await this.initialize(),this.runtime.peerTrustStore.grant(e,t)))}async getA2APeerTrust(e){return this.operations.run(async()=>(await this.initialize(),this.runtime.peerTrustStore.get(e)))}async revokeA2APeerTrust(e,t={}){return this.operations.run(async()=>(await this.initialize(),this.runtime.peerTrustStore.revoke(e,t)))}getAuthorizationServerMetadata(e=this.issuer){let t=vy(e);return{issuer:t,authorization_endpoint:Dl(t,"/authorize"),token_endpoint:Dl(t,"/token"),registration_endpoint:Dl(t,"/register"),revocation_endpoint:Dl(t,"/revoke"),jwks_uri:Dl(t,"/.well-known/jwks.json"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"],token_endpoint_auth_methods_supported:["none","client_secret_basic","client_secret_post"],client_id_metadata_document_supported:!0,scopes_supported:["openid","profile","email","offline_access","mcp"],subject_types_supported:["public"],id_token_signing_alg_values_supported:["ES256"]}}getProtectedResourceMetadata(e,t=this.issuer){return{resource:e,authorization_servers:[vy(t)],bearer_methods_supported:["header"],resource_signing_alg_values_supported:["ES256"],scopes_supported:["mcp"]}}async registerClient(e){return this.operations.run(async()=>(await this.initialize(),this.runtime.clientStore.registerClient(e)))}async getRegisteredClient(e){return this.operations.run(async()=>(await this.initialize(),this.runtime.clientStore.getClient(e)))}async createUser(e,t={}){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().createUser(e,t)))}async cancelInvitation(e,t){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().cancelInvitation(e,t)))}async confirmManualInvitationDelivery(e,t,i){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().confirmManualInvitationDelivery(e,t,i)))}async createInvitation(e,t){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().createInvitation(e,t)))}async resendInvitation(e,t){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().resendInvitation(e,t)))}async inviteExternalPeerPerson(e,t){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().inviteExternalPeerPerson(e,t)))}async linkExternalPeer(e,t){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().linkExternalPeer(e,t)))}async unlinkExternalPeer(e,t){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().unlinkExternalPeer(e,t)))}async getBrainAnchor(){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().getBrainAnchor()))}async listUsers(){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().listUsers()))}async listAdminUsers(){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().listAdminUsers()))}async listInvitationChannels(){return this.operations.run(async()=>{await this.runtime.ensureStarted();let e=this.listChannelDescriptors?.()??[];return await Promise.all(e.map(async(i)=>{let r=[];try{let n=this.getInvitationDeliveryProvider?.(i.type);if(n&&await n.isAvailable())r.push("automatic")}catch{}if(i.manualDelivery===!0)r.push("manual");return{type:i.type,displayName:i.displayName,subjectLabel:i.subjectLabel,...i.subjectPattern?{subjectPattern:i.subjectPattern}:{},deliveryModes:r}}))})}async reconcileIdentityProposals(e){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getIdentityReconciliationService().reconcile(e)))}async listPersonExternalPeers(e){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().listPersonExternalPeers(e)))}async listUserIdentities(e){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().listUserIdentities(e)))}async listUserPasskeys(e){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().listUserPasskeys(e)))}async updateUserRole(e,t,i={}){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().updateUserRole(e,t,i)))}async updateUserStatus(e,t,i={}){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().updateUserStatus(e,t,i)))}suspendUser(e,t={}){return this.updateUserStatus(e,"suspended",t)}async deleteSuspendedUser(e,t={}){return this.operations.run(async()=>{await this.runtime.ensureStarted(),await this.runtime.getAdministrationService().deleteSuspendedUser(e,t)})}async revokeUserSessionsAndRefreshTokens(e,t={}){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().revokeUserGrants(e,t)))}async attachIdentity(e,t={}){return this.operations.run(async()=>{await this.runtime.ensureStarted();let i=this.validateChannelSubject(e.type,e.subject);return this.runtime.getAdministrationService().attachIdentity({...e,...i&&!e.deliverySubject?{deliverySubject:e.subject}:{}},t)})}async detachIdentity(e,t={}){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().detachIdentity(e,t)))}async recordAuditEvent(e){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAuditStore().append(e)))}async listAuditEvents(){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().listAuditEvents()))}async queryAuditEvents(e){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAuditStore().query(e)))}async resolveActorPrincipal(e){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getPrincipalService().resolveActor(e)))}async resolveIdentityAccess(e){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getPrincipalService().resolveIdentityAccess(e)))}async createAuthSession(e,t={}){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getPrincipalService().createSession(e,t)))}async getAuthSession(e){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getPrincipalService().getSession(e)))}async resolveSession(e){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getPrincipalService().resolveSession(e)))}createAuthLoginResponse(e){return a_(e)}async verifyBearerToken(e,t={}){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getPrincipalService().verifyBearerToken(e,t)))}async resolveBearerGrant(e,t={}){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getPrincipalService().resolveBearerGrant(e,t)))}async resolveBearerToken(e,t={}){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getPrincipalService().resolveBearerToken(e,t)))}getSetupUrl(e=this.issuer){return this.runtime.setupFlow.getSetupUrl(e)}async startPasskeyRegistrationForUser(e,t={},i){return this.operations.run(async()=>{if(await this.runtime.ensureStarted(),i)this.validateChannelSubject(i.type,i.subject);return this.runtime.getPasskeySetupCoordinator().startRegistration(e,t,i)})}async getPasskeySetupRequired(e=this.issuer){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getPasskeySetupCoordinator().getPasskeySetupRequired(e)))}async getPasskeySetupRequiredForDelivery(e=this.issuer){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getPasskeySetupCoordinator().getPasskeySetupRequiredForDelivery(e)))}async hasSetupEmailDelivery(e,t){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getPasskeySetupCoordinator().hasSetupEmailDelivery(e,t)))}async recordSetupEmailDelivery(e,t,i={}){return this.operations.run(async()=>{await this.runtime.ensureStarted(),await this.runtime.getPasskeySetupCoordinator().recordSetupEmailDelivery(e,t,i)})}async handleRequest(e){return this.operations.run(async()=>{await this.initialize();let t;try{t=this.resolveRequestIssuer(e)}catch(i){return this.logger?.warn("Rejected OAuth request from untrusted issuer",{error:Ee(i)}),new Response("Untrusted OAuth issuer",{status:400})}return this.requestRouter.handle(e,t)})}async handleWellKnownRequest(e){return this.handleRequest(e)}handleAccountRequest(e){return RHe(e,{resolveSession:async(t)=>{let i=await this.runtime.resolveActiveSession(t);return i?{userId:i.user.id,sessionId:i.session.id}:void 0},account:this.runtime.getAccountService(),...this.accountSettingsRegistry?{accountSettings:this.accountSettingsRegistry}:{}})}handleAdminRequest(e){return jHe(e,{resolveSession:(t)=>this.resolveSession(t),listUsers:()=>this.listUsers(),getBrainAnchor:()=>this.getBrainAnchor(),listAuditEvents:()=>this.listAuditEvents(),listInvitationChannels:()=>this.listInvitationChannels(),listAdminUsers:()=>this.listAdminUsers(),reconcileIdentityProposals:(t)=>this.reconcileIdentityProposals(t),listPersonExternalPeers:(t)=>this.listPersonExternalPeers(t),listUserIdentities:(t)=>this.listUserIdentities(t),listUserPasskeys:(t)=>this.listUserPasskeys(t),cancelInvitation:(t,i)=>this.cancelInvitation(t,{actorUserId:i}),confirmManualInvitationDelivery:(t,i,r)=>this.confirmManualInvitationDelivery(t,i,{actorUserId:r}),createInvitation:(t,i)=>this.createInvitation(t,{actorUserId:i}),createUser:(t,i)=>this.createUser(t,{actorUserId:i}),inviteExternalPeerPerson:(t,i)=>this.inviteExternalPeerPerson(t,{actorUserId:i}),resendInvitation:(t,i)=>this.resendInvitation(t,{actorUserId:i}),linkExternalPeer:(t,i)=>this.linkExternalPeer(t,{actorUserId:i}),unlinkExternalPeer:(t,i)=>this.unlinkExternalPeer(t,{actorUserId:i}),updateUserRole:(t,i,r)=>this.updateUserRole(t,i,{actorUserId:r}),updateUserStatus:(t,i,r)=>this.updateUserStatus(t,i,{actorUserId:r}),deleteUser:(t,i)=>this.deleteSuspendedUser(t,{actorUserId:i}),attachIdentity:async(t,i)=>BQe(await this.attachIdentity(t,{actorUserId:i}),t.userId,this.getChannelDescriptor),detachIdentity:async(t,i)=>{let r=await this.detachIdentity(t,{actorUserId:i}),n=await this.runtime.getUserStore().getUserByPersonId(r.personId);if(!n)throw Error("Identity person has no auth user");return BQe(r,n.id,this.getChannelDescriptor)},revokePasskey:(t,i)=>this.revokePasskey(t,{actorUserId:i}),startPasskeyRegistration:(t,i,r)=>this.startPasskeyRegistrationForUser(t,{actorUserId:i},r),revokeUserSessionsAndRefreshTokens:(t,i)=>this.revokeUserSessionsAndRefreshTokens(t,{actorUserId:i})})}validateChannelSubject(e,t){let i=this.getChannelDescriptor?.(e);if(i?.subjectPattern&&!new RegExp(i.subjectPattern.source,i.subjectPattern.flags).test(t.trim()))throw Error(`Identity subject is invalid for channel: "${e}"`);return i}resolveRequestIssuer(e){return this.runtime.getPrincipalService().resolveRequestIssuer(e)}}function BQe(e,t,i){let r=e.label?.trim(),n=e.deliverySubject?.trim(),o=r&&r.length>0&&r!==i?.(e.type)?.subjectLabel?r:n;return{id:e.id,personId:e.personId,userId:t,type:e.type,visibility:e.visibility,evidence:e.evidence.map((s)=>({sourceKind:s.sourceKind,...s.sourceId?{sourceId:s.sourceId}:{},assurance:s.assurance,...s.verifiedAt!==null?{verifiedAt:s.verifiedAt}:{}})),...e.issuer?{issuer:e.issuer}:{},...o?{label:o}:{},...e.verifiedAt!==null?{verifiedAt:e.verifiedAt}:{},...e.revokedAt!==null?{revokedAt:e.revokedAt}:{},createdAt:e.createdAt}}import{join as N$i}from"path";var CQe={name:"@brains/auth-service",license:"AGPL-3.0-only",version:"0.2.0-alpha.698",description:"Embedded OAuth/OIDC authentication service for brain users",dependencies:{"@brains/contracts":"workspace:*","@brains/db":"workspace:*","@brains/notifications":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*","@libsql/client":"^0.17.4","@simplewebauthn/server":"^13.3.1","drizzle-orm":"^0.45.2",jose:"^6.2.3"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/templates":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0","@types/node":"^24.13.3","drizzle-kit":"^0.31.10",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./env-schema":"./src/env-schema.ts","./admin-contracts":"./src/admin-contracts.ts"},files:["src"],main:"./src/index.ts",private:!0,scripts:{"db:generate":"drizzle-kit generate","db:studio":"drizzle-kit studio",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"};var L$i=l.string().email(),z$i=l.object({syncUrl:l.string().url().regex(/^(?:libsql|https):\/\//),authToken:l.string().min(1),syncIntervalMs:l.number().int().positive().optional()}).strict();var j$i=l.object({issuer:l.string().optional(),anchor:l.enum(_Qe).default("person"),trustedIssuers:l.array(l.string()).default([]),allowLocalhostIssuers:l.boolean().optional(),storageDir:l.string().optional(),replica:z$i.optional(),setupTokenTtlSeconds:l.number().int().positive().default(eP),setupEmail:L$i.optional(),accountSettingsEncryptionKey:l.string().min(32).optional()});function U$i(e){return e??N$i(".","data","auth")}async function DQe(e){let t=e.identity.get().purpose.trim(),i=(await e.identity.getAppInfo().catch(()=>{return}))?.interactions??[],r=(a)=>i.find((c)=>c.id===a&&c.href.startsWith("/"))?.href,n=r(eH),o=r(XG),s=o&&r(eB)?TQe(o):void 0;return{...t?{purpose:t}:{},links:{...n?{chat:n}:{},...o?{studio:o}:{},...s?{aiTools:s}:{}}}}async function IQe(e,t){if(t==="anchor-profile/anchor-profile"){let o=e.identity.getProfile().name.trim();return o&&o!=="Unknown"?o:void 0}let i=t.indexOf("/");if(i<=0||i===t.length-1)return;let n=(await e.entityService.getEntity({entityType:t.slice(0,i),id:t.slice(i+1),visibilityScope:Pt("profile display name for auth admin")}))?.metadata.name;return typeof n==="string"?n:void 0}function q$i(e){return PQe(e,{activeId:"auth-service",permissionLevel:"admin",hasActiveSession:!0}).find((t)=>t.id==="studio")?.href??"/"}class Yhe extends ev{service;unbindAccountSettings;unbindAuth;unsubscribePrincipalResolver;constructor(e={}){super("auth-service",CQe,e,j$i)}async onRegister(e){await super.onRegister(e);let t=this.config.issuer??(e.preferLocalUrls?e.localSiteUrl??e.siteUrl:e.siteUrl??e.localSiteUrl);this.service=new JG({storageDir:U$i(this.config.storageDir),...this.config.replica?{replica:this.config.replica}:{},anchor:this.config.anchor,anchorProfileEntityId:"anchor-profile/anchor-profile",resolveProfileDisplayName:(n)=>IQe(e,n),...t?{issuer:t}:{},trustedIssuers:this.config.trustedIssuers,...this.config.allowLocalhostIssuers!==void 0?{allowLocalhostIssuers:this.config.allowLocalhostIssuers}:{},setupTokenTtlSeconds:this.config.setupTokenTtlSeconds,resolveHomePath:()=>q$i(e.webRoutes.getRoutes()),...this.config.accountSettingsEncryptionKey?{accountSettingsEncryptionKey:this.config.accountSettingsEncryptionKey}:{},onAccountDeleted:(n)=>{e.accountSettings.accountDeleted(n)},accountSettingsRegistry:e.accountSettings,autoStartInvitationDeliveryRecovery:!1,issuesSetupLinks:!e.executionOnly,getInvitationDeliveryProvider:(n)=>e.channels.getDeliveryProvider(n),getChannelDescriptor:(n)=>e.channels.getDescriptor(n),listChannelDescriptors:()=>e.channels.listDescriptors(),isChannelTypeRegistered:(n)=>Boolean(e.channels.getDescriptor(n)),getOnboardingDetails:()=>DQe(e),logger:e.logger}),await this.service.initialize();let i=this.service.getAccountSettingsBackend();if(i)this.unbindAccountSettings=e.accountSettings.bindBackend(i);let r=await this.service.initializeConfiguredInterfacePrincipals(e.permissions.getConfiguredPrincipalSeeds());e.permissions.replaceRuntimePrincipalState(r),this.unbindAuth=e.auth.bindBackend(this.service),this.unsubscribePrincipalResolver=e.messaging.answer(QG,async({actor:n})=>{let o=await this.getService().resolveActorPrincipal(n);return{principal:o?{userId:o.userId,personId:o.personId,...o.canonicalId?{canonicalId:o.canonicalId}:{},displayName:o.displayName,permissionLevel:o.permissionLevel}:null}})}async onRegistrationComplete(){await this.getService().startInvitationDeliveryRecovery()}async onReady(e){await this.requestSetupEmailIfNeeded(e)}async onShutdown(){this.unsubscribePrincipalResolver?.(),this.unsubscribePrincipalResolver=void 0,this.unbindAuth?.(),this.unbindAuth=void 0,this.unbindAccountSettings?.(),this.unbindAccountSettings=void 0,await this.service?.close(),this.service=void 0}async getTools(){let e=await this.getService().hasPasskeyCredentials();return[{name:`${this.id}_get_passkey_setup_url`,description:"Get the first-passkey setup URL when passkey setup is required. Admin-only.",inputSchema:{},visibility:"admin",...e?{agentTool:!1}:{},handler:async()=>{let t=this.getService();if(await t.hasPasskeyCredentials())return{success:!0,data:{status:"complete"}};let i=await t.getPasskeySetupRequired();if(i)return{success:!0,data:{status:"setup_required",setupUrl:i.setupUrl,expiresAt:i.expiresAt}};return{success:!0,data:{status:"unavailable",reason:"Passkey setup URL is not available."}}},sideEffects:"none"}]}getWebRoutes(){let e=(t)=>this.getService().handleRequest(t);return[{path:"/.well-known/oauth-authorization-server",method:"GET",public:!0,handler:e},{path:"/.well-known/oauth-authorization-server",method:"OPTIONS",public:!0,handler:e},{path:"/.well-known/jwks.json",method:"GET",public:!0,handler:e},{path:"/.well-known/jwks.json",method:"OPTIONS",public:!0,handler:e},{path:"/.well-known/oauth-protected-resource",method:"GET",public:!0,handler:e},{path:"/.well-known/oauth-protected-resource",method:"OPTIONS",public:!0,handler:e},{path:"/setup",method:"GET",public:!0,handler:e},{path:"/login",method:"GET",public:!0,handler:e},{path:"/logout",method:"GET",public:!0,handler:e},{path:"/logout",method:"POST",public:!0,handler:e},{path:"/authorize",method:"GET",public:!0,handler:e},{path:"/authorize",method:"POST",public:!0,handler:e},{path:"/register",method:"POST",public:!0,handler:e},{path:"/register",method:"OPTIONS",public:!0,handler:e},{path:"/token",method:"POST",public:!0,handler:e},{path:"/token",method:"OPTIONS",public:!0,handler:e},{path:"/revoke",method:"POST",public:!0,handler:e},{path:"/revoke",method:"OPTIONS",public:!0,handler:e},{path:"/auth/account",method:"GET",public:!0,handler:e},{path:"/auth/account/mutations",method:"POST",public:!0,handler:e},{path:"/auth/account/plugin-settings",method:"POST",public:!0,handler:e},{path:"/auth/account/passkeys/options",method:"POST",public:!0,handler:e},{path:"/auth/account/passkeys/verify",method:"POST",public:!0,handler:e},{path:"/auth/admin/anchor",method:"GET",public:!0,handler:e},{path:"/auth/admin/users",method:"GET",public:!0,handler:e},{path:"/auth/admin/audit",method:"GET",public:!0,handler:e},{path:"/auth/admin/channels",method:"GET",public:!0,handler:e},{path:"/auth/admin/mutations",method:"POST",public:!0,handler:e},{path:"/auth/admin/reconciliation",method:"POST",public:!0,handler:e},{path:"/webauthn/register/options",method:"POST",public:!0,handler:e},{path:"/webauthn/register/verify",method:"POST",public:!0,handler:e},{path:"/webauthn/auth/options",method:"POST",public:!0,handler:e},{path:"/webauthn/auth/verify",method:"POST",public:!0,handler:e}]}getService(){if(!this.service)throw Error("AuthServicePlugin has not been registered");return this.service}async requestSetupEmailIfNeeded(e){if(!this.config.setupEmail)return;let t=this.getService();if(await t.hasPasskeyCredentials())return;let i=await t.getPasskeySetupRequiredForDelivery();if(!i)return;let r=this.config.setupEmail;if(await t.hasSetupEmailDelivery(i.setupTokenId,r))return;let n=this.config.anchor==="person"?await IQe(e,"anchor-profile/anchor-profile"):void 0,{links:o}=await DQe(e),s=f$({kind:"anchor-setup",setupUrl:i.setupUrl,expiresAt:i.expiresAt,links:o,...n?{greetingName:n}:{}}),a=await e.messaging.request(Xk,{recipient:{type:"email",address:r},title:s.subject,body:s.text,html:s.html,sensitivity:"secret"});if(a.status!=="answered"||a.data.status!=="sent"){e.logger.warn("Passkey setup email delivery was not confirmed");return}await t.recordSetupEmailDelivery(i.setupTokenId,r,a.data.deliveryId?{deliveryId:a.data.deliveryId}:{})}}function Jhe(e={}){return new Yhe(e)}var Qhe=l.object({defaultPrompt:l.string().default("Write a blog post about my recent work and insights"),paginate:l.boolean().default(!0),pageSize:l.number().default(10)});var tH=l.enum(["generating","draft","queued","published","failed"]),ax=l.object({title:l.string(),slug:l.string().optional(),status:tH,publishedAt:l.string().datetime().optional(),excerpt:l.string(),author:l.string(),coverImageId:l.string().optional(),ogImageId:l.string().optional(),seriesName:l.string().optional(),seriesIndex:l.number().optional(),ogImage:l.string().url().optional(),canonicalUrl:l.string().url().optional()}),iH=ax.extend({slug:l.string(),error:l.string().optional().meta({studioWidget:"hidden"}),authoredSlug:l.boolean().optional().meta({studioWidget:"hidden"})}),tB=Mi.extend({entityType:l.literal("post"),metadata:iH}),tP=tB.extend({frontmatter:ax,body:l.string(),coverImageUrl:l.string().optional()}),$$i=tP.extend({url:l.string().optional(),typeLabel:l.string().optional(),listUrl:l.string().optional(),listLabel:l.string().optional(),seriesUrl:l.string().optional(),coverImageUrl:l.string().optional(),ogImageUrl:l.string().optional(),coverImageWidth:l.number().optional(),coverImageHeight:l.number().optional(),coverImageSrcset:l.string().optional(),coverImageSizes:l.string().optional()}),BFo=tP.extend({url:l.string(),typeLabel:l.string(),listUrl:l.string(),listLabel:l.string(),seriesUrl:l.string().optional(),coverImageUrl:l.string().optional(),ogImageUrl:l.string().optional(),coverImageWidth:l.number().optional(),coverImageHeight:l.number().optional(),coverImageSrcset:l.string().optional(),coverImageSizes:l.string().optional()});function RQe(e){let t=e.authoredSlug===!0;return Object.fromEntries(Object.entries({title:e.title,...t&&{slug:e.slug},status:e.status,publishedAt:e.publishedAt,excerpt:e.excerpt,author:e.author,coverImageId:e.coverImageId,ogImageId:e.ogImageId,seriesName:e.seriesName,seriesIndex:e.seriesIndex,ogImage:e.ogImage,canonicalUrl:e.canonicalUrl,...!t&&{slug:e.slug},error:e.error}).filter(([,i])=>i!==void 0))}function FQe(e){return kr(RQe(e.metadata),e.content)}var MQe={decode:({content:e,frontmatter:t})=>{let i=ax.parse(t),r=t.error;return{content:e,metadata:{...i,slug:i.slug??jt(i.title),...i.slug!==void 0&&{authoredSlug:!0},...typeof r==="string"&&{error:r}}}},encode:({content:e,metadata:t})=>({content:Sr(e).content,frontmatter:RQe(t)})};function Xhe(e){let{fields:t,body:i}=Un(e),r=Object.keys(Sr(e.content).frontmatter).length>0;return tP.parse({...e,content:r?e.content:FQe(e),frontmatter:ax.parse(t),body:i})}function rH(e){return{content:"",metadata:{title:e.title,slug:e.id,authoredSlug:!0,status:"generating",excerpt:"",author:"AI"}}}var wu=l.string().nullable().default(null),nH=l.number().nullable().default(null),G$i=l.object({title:l.string(),status:tH,publishedAt:wu,seriesName:wu,seriesIndex:nH,slug:l.string(),error:wu}),H$i=l.object({title:l.string(),slug:wu,status:tH,publishedAt:wu,excerpt:l.string(),author:l.string(),coverImageId:wu,ogImageId:wu,seriesName:wu,seriesIndex:nH,ogImage:wu,canonicalUrl:wu}),Su=l.object({...If("post",G$i,H$i),body:l.string(),...du,seriesUrl:wu,coverImageUrl:wu,ogImageUrl:wu,coverImageWidth:nH,coverImageHeight:nH,coverImageSrcset:wu,coverImageSizes:wu}),lh=Su.extend(x0);var W$i=1000,Z$i=100;function OQe(e){let t=Xhe(e),i=t.frontmatter.seriesName,r=i?`/series/${jt(i)}`:void 0;return{...t,...r&&{seriesUrl:r}}}async function V$i(e,t,i){return(await t.list(e,{limit:W$i,sort:[{field:"seriesIndex",direction:"asc"}]})).filter((n)=>n.metadata.seriesName===i).slice(0,Z$i).map(OQe)}function NQe(e){return Es({id:"entities",name:"Blog Entity DataSource",description:"Fetches and transforms blog post entities for rendering",entity:e,defaultSort:[{field:"publishedAt",direction:"desc"}],defaultLimit:10,enableNavigation:!0,transform:OQe,list:(t,i,r)=>({posts:t.map((n)=>Su.parse(n)),pagination:i,baseUrl:r.baseUrl??null}),detail:async({item:t,navigation:i,entities:r})=>({post:t,prevPost:i?.prev??null,nextPost:i?.next??null,seriesPosts:t.frontmatter.seriesName?await V$i(e,r,t.frontmatter.seriesName):null})})}function oH(e,{environment:t}){let{metadata:i}=e;if(t==="production"&&(i.status!=="published"||!i.publishedAt))return null;return{title:i.title,slug:i.slug,description:i.excerpt,content:e.content,author:i.author,publishedAt:i.publishedAt??e.created,...i.seriesName&&{category:i.seriesName}}}var efe={path:"feed.xml",title:"Blog",description:"Latest blog posts",toItem:oH};var K$i=l.object({siteUrl:l.url(),title:l.string(),description:l.string(),language:l.string().optional(),copyright:l.string().optional()});function jQe(e){return Es({id:"rss",name:"Blog RSS Feed DataSource",description:"Generates RSS 2.0 feed XML from published blog posts",fetch:async(t,i)=>{let r=K$i.parse(t),o=(await i.list(e,{limit:1000,sort:[{field:"publishedAt",direction:"desc"}]})).flatMap((a)=>{let c=oH(a,{environment:"production"});return c?[LQe.parse(c)]:[]}),s=r.siteUrl.replace(/\/+$/u,"");return{xml:zQe(o,{title:r.title,description:r.description,link:r.siteUrl,selfLink:`${r.siteUrl}/feed.xml`,language:r.language??"en-us",copyright:r.copyright},(a)=>`${s}/posts/${a.slug}`)}}})}var Y$i=zt({type:"image",purpose:"An image a post shows as its cover.",metadata:tv});function J$i(e){let t=/^data:([^;,]+);base64,(.*)$/.exec(e.trim());if(!t?.[1]||!t[2])throw Error("Cover image must be a base64 data URL");return{data:Buffer.from(t[2],"base64"),mimeType:t[1]}}async function Q$i({entity:e,entities:t,uploadBlob:i}){let r=e.metadata.coverImageId;if(!r)return;let n=await t.get(Y$i,r);if(!n)return;let o=await i(J$i(n.content)),{alt:s,width:a,height:c}=n.metadata;return{blob:o,...s&&{alt:s},width:a,height:c}}async function UQe(e){let{entity:t,config:i,topics:r,pageUrl:n}=e,{metadata:o}=t,s=await Q$i(e),a=o.canonicalUrl??n;return{$type:"ai.rizom.brain.post",title:o.title,summary:o.excerpt,body:t.content,format:"text/markdown",...i.brainDid&&{brainDid:i.brainDid},...i.anchorDid&&{anchorDid:i.anchorDid},...a&&{canonicalUrl:a},...r&&r.length>0&&{topics:[...r]},...s&&{coverImage:s},...o.seriesName&&{series:o.seriesName},...o.seriesIndex!==void 0&&{seriesIndex:o.seriesIndex},sourceEntityType:"post",sourceEntityId:t.id,createdAt:t.created,...o.publishedAt&&{publishedAt:o.publishedAt}}}var tfe={lexicon:Oa["ai.rizom.brain.post"],validate:!1,isPublishable:(e)=>e.metadata.status==="published",buildRecord:UQe};import{createElement as sge}from"react";import{renderToStaticMarkup as etr}from"react-dom/server";import{join as qxe,relative as Ner,sep as Ler}from"path";import{promises as ost}from"fs";var xo=Al(qle(),1),qQe=xo.default,QFo=xo.default.stringify,XFo=xo.default.fromJSON,eMo=xo.default.plugin,tMo=xo.default.parse,iMo=xo.default.list,rMo=xo.default.document,nMo=xo.default.comment,oMo=xo.default.atRule,sMo=xo.default.rule,aMo=xo.default.decl,cMo=xo.default.root,lMo=xo.default.CssSyntaxError,uMo=xo.default.Declaration,dMo=xo.default.Container,pMo=xo.default.Processor,mMo=xo.default.Document,hMo=xo.default.Comment,fMo=xo.default.Warning,xMo=xo.default.AtRule,gMo=xo.default.Result,yMo=xo.default.Input,bMo=xo.default.Rule,EMo=xo.default.Root,AMo=xo.default.Node;var Xot=Al(HQe(),1);var e5=Al(Dit(),1);import*as X8 from"module";import{pathToFileURL as EQi}from"url";import{isBuiltin as vQi}from"module";var Pit=Al(_it(),1);import{createRequire as Tit}from"module";function QZi(e){throw e}var XZi=(e)=>import(e),Lfe;function eVi(...e){if(!Lfe)Lfe=Tit(import.meta.url)("../dist/babel.cjs");return Lfe(...e)}function Rit(e,t={}){if(!t.transform)t={...t,transform:eVi};return Pit.default(e,t,{onError:QZi,nativeImport:XZi,createRequire:Tit})}import Pxe from"fs";import Sot from"fs/promises";import OP from"path";import{pathToFileURL as eot}from"url";var xH={inherit:"inherit",current:"currentcolor",transparent:"transparent",black:"#000",white:"#fff",slate:{50:"oklch(98.4% 0.003 247.858)",100:"oklch(96.8% 0.007 247.896)",200:"oklch(92.9% 0.013 255.508)",300:"oklch(86.9% 0.022 252.894)",400:"oklch(70.4% 0.04 256.788)",500:"oklch(55.4% 0.046 257.417)",600:"oklch(44.6% 0.043 257.281)",700:"oklch(37.2% 0.044 257.287)",800:"oklch(27.9% 0.041 260.031)",900:"oklch(20.8% 0.042 265.755)",950:"oklch(12.9% 0.042 264.695)"},gray:{50:"oklch(98.5% 0.002 247.839)",100:"oklch(96.7% 0.003 264.542)",200:"oklch(92.8% 0.006 264.531)",300:"oklch(87.2% 0.01 258.338)",400:"oklch(70.7% 0.022 261.325)",500:"oklch(55.1% 0.027 264.364)",600:"oklch(44.6% 0.03 256.802)",700:"oklch(37.3% 0.034 259.733)",800:"oklch(27.8% 0.033 256.848)",900:"oklch(21% 0.034 264.665)",950:"oklch(13% 0.028 261.692)"},zinc:{50:"oklch(98.5% 0 0)",100:"oklch(96.7% 0.001 286.375)",200:"oklch(92% 0.004 286.32)",300:"oklch(87.1% 0.006 286.286)",400:"oklch(70.5% 0.015 286.067)",500:"oklch(55.2% 0.016 285.938)",600:"oklch(44.2% 0.017 285.786)",700:"oklch(37% 0.013 285.805)",800:"oklch(27.4% 0.006 286.033)",900:"oklch(21% 0.006 285.885)",950:"oklch(14.1% 0.005 285.823)"},neutral:{50:"oklch(98.5% 0 0)",100:"oklch(97% 0 0)",200:"oklch(92.2% 0 0)",300:"oklch(87% 0 0)",400:"oklch(70.8% 0 0)",500:"oklch(55.6% 0 0)",600:"oklch(43.9% 0 0)",700:"oklch(37.1% 0 0)",800:"oklch(26.9% 0 0)",900:"oklch(20.5% 0 0)",950:"oklch(14.5% 0 0)"},stone:{50:"oklch(98.5% 0.001 106.423)",100:"oklch(97% 0.001 106.424)",200:"oklch(92.3% 0.003 48.717)",300:"oklch(86.9% 0.005 56.366)",400:"oklch(70.9% 0.01 56.259)",500:"oklch(55.3% 0.013 58.071)",600:"oklch(44.4% 0.011 73.639)",700:"oklch(37.4% 0.01 67.558)",800:"oklch(26.8% 0.007 34.298)",900:"oklch(21.6% 0.006 56.043)",950:"oklch(14.7% 0.004 49.25)"},mauve:{50:"oklch(98.5% 0 0)",100:"oklch(96% 0.003 325.6)",200:"oklch(92.2% 0.005 325.62)",300:"oklch(86.5% 0.012 325.68)",400:"oklch(71.1% 0.019 323.02)",500:"oklch(54.2% 0.034 322.5)",600:"oklch(43.5% 0.029 321.78)",700:"oklch(36.4% 0.029 323.89)",800:"oklch(26.3% 0.024 320.12)",900:"oklch(21.2% 0.019 322.12)",950:"oklch(14.5% 0.008 326)"},olive:{50:"oklch(98.8% 0.003 106.5)",100:"oklch(96.6% 0.005 106.5)",200:"oklch(93% 0.007 106.5)",300:"oklch(88% 0.011 106.6)",400:"oklch(73.7% 0.021 106.9)",500:"oklch(58% 0.031 107.3)",600:"oklch(46.6% 0.025 107.3)",700:"oklch(39.4% 0.023 107.4)",800:"oklch(28.6% 0.016 107.4)",900:"oklch(22.8% 0.013 107.4)",950:"oklch(15.3% 0.006 107.1)"},mist:{50:"oklch(98.7% 0.002 197.1)",100:"oklch(96.3% 0.002 197.1)",200:"oklch(92.5% 0.005 214.3)",300:"oklch(87.2% 0.007 219.6)",400:"oklch(72.3% 0.014 214.4)",500:"oklch(56% 0.021 213.5)",600:"oklch(45% 0.017 213.2)",700:"oklch(37.8% 0.015 216)",800:"oklch(27.5% 0.011 216.9)",900:"oklch(21.8% 0.008 223.9)",950:"oklch(14.8% 0.004 228.8)"},taupe:{50:"oklch(98.6% 0.002 67.8)",100:"oklch(96% 0.002 17.2)",200:"oklch(92.2% 0.005 34.3)",300:"oklch(86.8% 0.007 39.5)",400:"oklch(71.4% 0.014 41.2)",500:"oklch(54.7% 0.021 43.1)",600:"oklch(43.8% 0.017 39.3)",700:"oklch(36.7% 0.016 35.7)",800:"oklch(26.8% 0.011 36.5)",900:"oklch(21.4% 0.009 43.1)",950:"oklch(14.7% 0.004 49.3)"},red:{50:"oklch(97.1% 0.013 17.38)",100:"oklch(93.6% 0.032 17.717)",200:"oklch(88.5% 0.062 18.334)",300:"oklch(80.8% 0.114 19.571)",400:"oklch(70.4% 0.191 22.216)",500:"oklch(63.7% 0.237 25.331)",600:"oklch(57.7% 0.245 27.325)",700:"oklch(50.5% 0.213 27.518)",800:"oklch(44.4% 0.177 26.899)",900:"oklch(39.6% 0.141 25.723)",950:"oklch(25.8% 0.092 26.042)"},orange:{50:"oklch(98% 0.016 73.684)",100:"oklch(95.4% 0.038 75.164)",200:"oklch(90.1% 0.076 70.697)",300:"oklch(83.7% 0.128 66.29)",400:"oklch(75% 0.183 55.934)",500:"oklch(70.5% 0.213 47.604)",600:"oklch(64.6% 0.222 41.116)",700:"oklch(55.3% 0.195 38.402)",800:"oklch(47% 0.157 37.304)",900:"oklch(40.8% 0.123 38.172)",950:"oklch(26.6% 0.079 36.259)"},amber:{50:"oklch(98.7% 0.022 95.277)",100:"oklch(96.2% 0.059 95.617)",200:"oklch(92.4% 0.12 95.746)",300:"oklch(87.9% 0.169 91.605)",400:"oklch(82.8% 0.189 84.429)",500:"oklch(76.9% 0.188 70.08)",600:"oklch(66.6% 0.179 58.318)",700:"oklch(55.5% 0.163 48.998)",800:"oklch(47.3% 0.137 46.201)",900:"oklch(41.4% 0.112 45.904)",950:"oklch(27.9% 0.077 45.635)"},yellow:{50:"oklch(98.7% 0.026 102.212)",100:"oklch(97.3% 0.071 103.193)",200:"oklch(94.5% 0.129 101.54)",300:"oklch(90.5% 0.182 98.111)",400:"oklch(85.2% 0.199 91.936)",500:"oklch(79.5% 0.184 86.047)",600:"oklch(68.1% 0.162 75.834)",700:"oklch(55.4% 0.135 66.442)",800:"oklch(47.6% 0.114 61.907)",900:"oklch(42.1% 0.095 57.708)",950:"oklch(28.6% 0.066 53.813)"},lime:{50:"oklch(98.6% 0.031 120.757)",100:"oklch(96.7% 0.067 122.328)",200:"oklch(93.8% 0.127 124.321)",300:"oklch(89.7% 0.196 126.665)",400:"oklch(84.1% 0.238 128.85)",500:"oklch(76.8% 0.233 130.85)",600:"oklch(64.8% 0.2 131.684)",700:"oklch(53.2% 0.157 131.589)",800:"oklch(45.3% 0.124 130.933)",900:"oklch(40.5% 0.101 131.063)",950:"oklch(27.4% 0.072 132.109)"},green:{50:"oklch(98.2% 0.018 155.826)",100:"oklch(96.2% 0.044 156.743)",200:"oklch(92.5% 0.084 155.995)",300:"oklch(87.1% 0.15 154.449)",400:"oklch(79.2% 0.209 151.711)",500:"oklch(72.3% 0.219 149.579)",600:"oklch(62.7% 0.194 149.214)",700:"oklch(52.7% 0.154 150.069)",800:"oklch(44.8% 0.119 151.328)",900:"oklch(39.3% 0.095 152.535)",950:"oklch(26.6% 0.065 152.934)"},emerald:{50:"oklch(97.9% 0.021 166.113)",100:"oklch(95% 0.052 163.051)",200:"oklch(90.5% 0.093 164.15)",300:"oklch(84.5% 0.143 164.978)",400:"oklch(76.5% 0.177 163.223)",500:"oklch(69.6% 0.17 162.48)",600:"oklch(59.6% 0.145 163.225)",700:"oklch(50.8% 0.118 165.612)",800:"oklch(43.2% 0.095 166.913)",900:"oklch(37.8% 0.077 168.94)",950:"oklch(26.2% 0.051 172.552)"},teal:{50:"oklch(98.4% 0.014 180.72)",100:"oklch(95.3% 0.051 180.801)",200:"oklch(91% 0.096 180.426)",300:"oklch(85.5% 0.138 181.071)",400:"oklch(77.7% 0.152 181.912)",500:"oklch(70.4% 0.14 182.503)",600:"oklch(60% 0.118 184.704)",700:"oklch(51.1% 0.096 186.391)",800:"oklch(43.7% 0.078 188.216)",900:"oklch(38.6% 0.063 188.416)",950:"oklch(27.7% 0.046 192.524)"},cyan:{50:"oklch(98.4% 0.019 200.873)",100:"oklch(95.6% 0.045 203.388)",200:"oklch(91.7% 0.08 205.041)",300:"oklch(86.5% 0.127 207.078)",400:"oklch(78.9% 0.154 211.53)",500:"oklch(71.5% 0.143 215.221)",600:"oklch(60.9% 0.126 221.723)",700:"oklch(52% 0.105 223.128)",800:"oklch(45% 0.085 224.283)",900:"oklch(39.8% 0.07 227.392)",950:"oklch(30.2% 0.056 229.695)"},sky:{50:"oklch(97.7% 0.013 236.62)",100:"oklch(95.1% 0.026 236.824)",200:"oklch(90.1% 0.058 230.902)",300:"oklch(82.8% 0.111 230.318)",400:"oklch(74.6% 0.16 232.661)",500:"oklch(68.5% 0.169 237.323)",600:"oklch(58.8% 0.158 241.966)",700:"oklch(50% 0.134 242.749)",800:"oklch(44.3% 0.11 240.79)",900:"oklch(39.1% 0.09 240.876)",950:"oklch(29.3% 0.066 243.157)"},blue:{50:"oklch(97% 0.014 254.604)",100:"oklch(93.2% 0.032 255.585)",200:"oklch(88.2% 0.059 254.128)",300:"oklch(80.9% 0.105 251.813)",400:"oklch(70.7% 0.165 254.624)",500:"oklch(62.3% 0.214 259.815)",600:"oklch(54.6% 0.245 262.881)",700:"oklch(48.8% 0.243 264.376)",800:"oklch(42.4% 0.199 265.638)",900:"oklch(37.9% 0.146 265.522)",950:"oklch(28.2% 0.091 267.935)"},indigo:{50:"oklch(96.2% 0.018 272.314)",100:"oklch(93% 0.034 272.788)",200:"oklch(87% 0.065 274.039)",300:"oklch(78.5% 0.115 274.713)",400:"oklch(67.3% 0.182 276.935)",500:"oklch(58.5% 0.233 277.117)",600:"oklch(51.1% 0.262 276.966)",700:"oklch(45.7% 0.24 277.023)",800:"oklch(39.8% 0.195 277.366)",900:"oklch(35.9% 0.144 278.697)",950:"oklch(25.7% 0.09 281.288)"},violet:{50:"oklch(96.9% 0.016 293.756)",100:"oklch(94.3% 0.029 294.588)",200:"oklch(89.4% 0.057 293.283)",300:"oklch(81.1% 0.111 293.571)",400:"oklch(70.2% 0.183 293.541)",500:"oklch(60.6% 0.25 292.717)",600:"oklch(54.1% 0.281 293.009)",700:"oklch(49.1% 0.27 292.581)",800:"oklch(43.2% 0.232 292.759)",900:"oklch(38% 0.189 293.745)",950:"oklch(28.3% 0.141 291.089)"},purple:{50:"oklch(97.7% 0.014 308.299)",100:"oklch(94.6% 0.033 307.174)",200:"oklch(90.2% 0.063 306.703)",300:"oklch(82.7% 0.119 306.383)",400:"oklch(71.4% 0.203 305.504)",500:"oklch(62.7% 0.265 303.9)",600:"oklch(55.8% 0.288 302.321)",700:"oklch(49.6% 0.265 301.924)",800:"oklch(43.8% 0.218 303.724)",900:"oklch(38.1% 0.176 304.987)",950:"oklch(29.1% 0.149 302.717)"},fuchsia:{50:"oklch(97.7% 0.017 320.058)",100:"oklch(95.2% 0.037 318.852)",200:"oklch(90.3% 0.076 319.62)",300:"oklch(83.3% 0.145 321.434)",400:"oklch(74% 0.238 322.16)",500:"oklch(66.7% 0.295 322.15)",600:"oklch(59.1% 0.293 322.896)",700:"oklch(51.8% 0.253 323.949)",800:"oklch(45.2% 0.211 324.591)",900:"oklch(40.1% 0.17 325.612)",950:"oklch(29.3% 0.136 325.661)"},pink:{50:"oklch(97.1% 0.014 343.198)",100:"oklch(94.8% 0.028 342.258)",200:"oklch(89.9% 0.061 343.231)",300:"oklch(82.3% 0.12 346.018)",400:"oklch(71.8% 0.202 349.761)",500:"oklch(65.6% 0.241 354.308)",600:"oklch(59.2% 0.249 0.584)",700:"oklch(52.5% 0.223 3.958)",800:"oklch(45.9% 0.187 3.815)",900:"oklch(40.8% 0.153 2.432)",950:"oklch(28.4% 0.109 3.907)"},rose:{50:"oklch(96.9% 0.015 12.422)",100:"oklch(94.1% 0.03 12.58)",200:"oklch(89.2% 0.058 10.001)",300:"oklch(81% 0.117 11.638)",400:"oklch(71.2% 0.194 13.428)",500:"oklch(64.5% 0.246 16.439)",600:"oklch(58.6% 0.253 17.585)",700:"oklch(51.4% 0.222 16.935)",800:"oklch(45.5% 0.188 13.697)",900:"oklch(41% 0.159 10.272)",950:"oklch(27.1% 0.105 12.094)"}};var Oit=new Set(["black","silver","gray","white","maroon","red","purple","fuchsia","green","lime","olive","yellow","navy","blue","teal","aqua","aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen","transparent","currentcolor","canvas","canvastext","linktext","visitedtext","activetext","buttonface","buttontext","buttonborder","field","fieldtext","highlight","highlighttext","selecteditem","selecteditemtext","mark","marktext","graytext","accentcolor","accentcolortext"]),tVi=/^(rgba?|hsla?|hwb|color|(ok)?(lab|lch)|light-dark|color-mix|--alpha)\(/i;function iVi(e){return e.charCodeAt(0)===35||tVi.test(e)||Oit.has(e.toLowerCase())}function Nit(e){return Oit.has(e.toLowerCase())}var zfe=["calc","min","max","clamp","mod","rem","sin","cos","tan","asin","acos","atan","atan2","pow","sqrt","hypot","log","exp","round"];function bH(e){return e.indexOf("(")!==-1&&zfe.some((t)=>e.includes(`${t}(`))}function jfe(e){if(!zfe.some((o)=>e.includes(o)))return e;let t="",i=[],r=null,n=null;for(let o=0;o<e.length;o++){let s=e.charCodeAt(o);if(s>=48&&s<=57||r!==null&&(s===37||s>=97&&s<=122||s>=65&&s<=90)?r=o:(n=r,r=null),s===40){t+=e[o];let a=o;for(let u=o-1;u>=0;u--){let d=e.charCodeAt(u);if(d>=48&&d<=57)a=u;else if(d>=97&&d<=122)a=u;else break}let c=e.slice(a,o);if(zfe.includes(c)){i.unshift(!0);continue}else if(i[0]&&c===""){i.unshift(!0);continue}i.unshift(!1);continue}else if(s===41)t+=e[o],i.shift();else if(s===44&&i[0]){t+=", ";continue}else{if(s===32&&i[0]&&t.charCodeAt(t.length-1)===32)continue;if((s===43||s===42||s===47||s===45)&&i[0]){let a=t.trimEnd(),c=a.charCodeAt(a.length-1),u=a.charCodeAt(a.length-2),d=e.charCodeAt(o+1);if((c===101||c===69)&&u>=48&&u<=57){t+=e[o];continue}else if(c===43||c===42||c===47||c===45){t+=e[o];continue}else if(c===40||c===44){t+=e[o];continue}else e.charCodeAt(o-1)===32?t+=`${e[o]} `:c>=48&&c<=57||d>=48&&d<=57||c===41||d===40||d===43||d===42||d===47||d===45||n!==null&&n===o-1?t+=` ${e[o]} `:t+=e[o]}else t+=e[o]}}return t}var gH=new Uint8Array(256);function Si(e,t){let i=0,r=[],n=0,o=e.length,s=t.charCodeAt(0);for(let a=0;a<o;a++){let c=e.charCodeAt(a);if(i===0&&c===s){r.push(e.slice(n,a)),n=a+1;continue}switch(c){case 92:a+=1;break;case 39:case 34:for(;++a<o;){let u=e.charCodeAt(a);if(u===92){a+=1;continue}if(u===c)break}break;case 40:gH[i]=41,i++;break;case 91:gH[i]=93,i++;break;case 123:gH[i]=125,i++;break;case 93:case 125:case 41:i>0&&c===gH[i-1]&&i--;break}}return r.push(e.slice(n)),r}var rVi={color:iVi,length:nv,percentage:Ufe,ratio:xVi,number:zit,integer:pt,url:Lit,position:EVi,"bg-size":AVi,"line-width":oVi,image:cVi,"family-name":uVi,"generic-name":lVi,"absolute-size":dVi,"relative-size":pVi,angle:SVi,vector:BVi};function Wo(e,t){if(e.startsWith("var("))return null;for(let i of t)if(rVi[i]?.(e))return i;return null}var nVi=/^url\(.*\)$/;function Lit(e){return nVi.test(e)}function oVi(e){return Si(e," ").every((t)=>nv(t)||zit(t)||t==="thin"||t==="medium"||t==="thick")}var sVi=/^(?:element|image|cross-fade|image-set)\(/,aVi=/^(repeating-)?(conic|linear|radial)-gradient\(/;function cVi(e){let t=0;for(let i of Si(e,","))if(!i.startsWith("var(")){if(Lit(i)){t+=1;continue}if(aVi.test(i)){t+=1;continue}if(sVi.test(i)){t+=1;continue}return!1}return t>0}function lVi(e){return e==="serif"||e==="sans-serif"||e==="monospace"||e==="cursive"||e==="fantasy"||e==="system-ui"||e==="ui-serif"||e==="ui-sans-serif"||e==="ui-monospace"||e==="ui-rounded"||e==="math"||e==="emoji"||e==="fangsong"}function uVi(e){let t=0;for(let i of Si(e,",")){let r=i.charCodeAt(0);if(r>=48&&r<=57)return!1;i.startsWith("var(")||(t+=1)}return t>0}function dVi(e){return e==="xx-small"||e==="x-small"||e==="small"||e==="medium"||e==="large"||e==="x-large"||e==="xx-large"||e==="xxx-large"}function pVi(e){return e==="larger"||e==="smaller"}var Jy=/[+-]?\d*\.?\d+(?:[eE][+-]?\d+)?/,mVi=new RegExp(`^${Jy.source}$`);function zit(e){return mVi.test(e)||bH(e)}var hVi=new RegExp(`^${Jy.source}%$`);function Ufe(e){return hVi.test(e)||bH(e)}var fVi=new RegExp(`^${Jy.source}\\s*/\\s*${Jy.source}$`);function xVi(e){return fVi.test(e)||bH(e)}var gVi=["cm","mm","Q","in","pc","pt","px","em","ex","ch","rem","lh","rlh","vw","vh","vmin","vmax","vb","vi","svw","svh","lvw","lvh","dvw","dvh","cqw","cqh","cqi","cqb","cqmin","cqmax"],yVi=new RegExp(`^${Jy.source}(${gVi.join("|")})$`),bVi=/^(--spacing)\(/i;function nv(e){return yVi.test(e)||bVi.test(e)||bH(e)}function EVi(e){let t=0;for(let i of Si(e," ")){if(i==="center"||i==="top"||i==="right"||i==="bottom"||i==="left"){t+=1;continue}if(!i.startsWith("var(")){if(nv(i)||Ufe(i)){t+=1;continue}return!1}}return t>0}function AVi(e){let t=0;for(let i of Si(e,",")){if(i==="cover"||i==="contain"){t+=1;continue}let r=Si(i," ");if(r.length!==1&&r.length!==2)return!1;if(r.every((n)=>n==="auto"||nv(n)||Ufe(n))){t+=1;continue}}return t>0}var vVi=["deg","rad","grad","turn"],wVi=new RegExp(`^${Jy.source}(${vVi.join("|")})$`);function SVi(e){return wVi.test(e)}var kVi=new RegExp(`^${Jy.source} +${Jy.source} +${Jy.source}$`);function BVi(e){return kVi.test(e)}function pt(e){let t=Number(e);return Number.isInteger(t)&&t>=0&&String(t)===String(e)}function qfe(e){let t=Number(e);return Number.isInteger(t)&&t>0&&String(t)===String(e)}function ua(e){return jit(e,0.25)}function EH(e){return jit(e,0.25)}function jit(e,t){let i=Number(e);return i>=0&&i%t===0&&String(i)===String(e)}function Z8(e){return{__BARE_VALUE__:e}}var ph=Z8((e)=>{if(pt(e.value))return e.value}),Ml=Z8((e)=>{if(pt(e.value))return`${e.value}%`}),rv=Z8((e)=>{if(pt(e.value))return`${e.value}px`}),Fit=Z8((e)=>{if(pt(e.value))return`${e.value}ms`}),yH=Z8((e)=>{if(pt(e.value))return`${e.value}deg`}),CVi=Z8((e)=>{if(e.fraction===null)return;let[t,i]=Si(e.fraction,"/");if(!(!pt(t)||!pt(i)))return e.fraction}),Mit=Z8((e)=>{if(pt(Number(e.value)))return`repeat(${e.value}, minmax(0, 1fr))`}),Uit={accentColor:({theme:e})=>e("colors"),animation:{none:"none",spin:"spin 1s linear infinite",ping:"ping 1s cubic-bezier(0, 0, 0.2, 1) infinite",pulse:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",bounce:"bounce 1s infinite"},aria:{busy:'busy="true"',checked:'checked="true"',disabled:'disabled="true"',expanded:'expanded="true"',hidden:'hidden="true"',pressed:'pressed="true"',readonly:'readonly="true"',required:'required="true"',selected:'selected="true"'},aspectRatio:{auto:"auto",square:"1 / 1",video:"16 / 9",...CVi},backdropBlur:({theme:e})=>e("blur"),backdropBrightness:({theme:e})=>({...e("brightness"),...Ml}),backdropContrast:({theme:e})=>({...e("contrast"),...Ml}),backdropGrayscale:({theme:e})=>({...e("grayscale"),...Ml}),backdropHueRotate:({theme:e})=>({...e("hueRotate"),...yH}),backdropInvert:({theme:e})=>({...e("invert"),...Ml}),backdropOpacity:({theme:e})=>({...e("opacity"),...Ml}),backdropSaturate:({theme:e})=>({...e("saturate"),...Ml}),backdropSepia:({theme:e})=>({...e("sepia"),...Ml}),backgroundColor:({theme:e})=>e("colors"),backgroundImage:{none:"none","gradient-to-t":"linear-gradient(to top, var(--tw-gradient-stops))","gradient-to-tr":"linear-gradient(to top right, var(--tw-gradient-stops))","gradient-to-r":"linear-gradient(to right, var(--tw-gradient-stops))","gradient-to-br":"linear-gradient(to bottom right, var(--tw-gradient-stops))","gradient-to-b":"linear-gradient(to bottom, var(--tw-gradient-stops))","gradient-to-bl":"linear-gradient(to bottom left, var(--tw-gradient-stops))","gradient-to-l":"linear-gradient(to left, var(--tw-gradient-stops))","gradient-to-tl":"linear-gradient(to top left, var(--tw-gradient-stops))"},backgroundOpacity:({theme:e})=>e("opacity"),backgroundPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},backgroundSize:{auto:"auto",cover:"cover",contain:"contain"},blur:{0:"0",none:"",sm:"4px",DEFAULT:"8px",md:"12px",lg:"16px",xl:"24px","2xl":"40px","3xl":"64px"},borderColor:({theme:e})=>({DEFAULT:"currentcolor",...e("colors")}),borderOpacity:({theme:e})=>e("opacity"),borderRadius:{none:"0px",sm:"0.125rem",DEFAULT:"0.25rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem","3xl":"1.5rem",full:"9999px"},borderSpacing:({theme:e})=>e("spacing"),borderWidth:{DEFAULT:"1px",0:"0px",2:"2px",4:"4px",8:"8px",...rv},boxShadow:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",DEFAULT:"0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)",inner:"inset 0 2px 4px 0 rgb(0 0 0 / 0.05)",none:"none"},boxShadowColor:({theme:e})=>e("colors"),brightness:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",200:"2",...Ml},caretColor:({theme:e})=>e("colors"),colors:()=>({...xH}),columns:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12","3xs":"16rem","2xs":"18rem",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",...ph},container:{},content:{none:"none"},contrast:{0:"0",50:".5",75:".75",100:"1",125:"1.25",150:"1.5",200:"2",...Ml},cursor:{auto:"auto",default:"default",pointer:"pointer",wait:"wait",text:"text",move:"move",help:"help","not-allowed":"not-allowed",none:"none","context-menu":"context-menu",progress:"progress",cell:"cell",crosshair:"crosshair","vertical-text":"vertical-text",alias:"alias",copy:"copy","no-drop":"no-drop",grab:"grab",grabbing:"grabbing","all-scroll":"all-scroll","col-resize":"col-resize","row-resize":"row-resize","n-resize":"n-resize","e-resize":"e-resize","s-resize":"s-resize","w-resize":"w-resize","ne-resize":"ne-resize","nw-resize":"nw-resize","se-resize":"se-resize","sw-resize":"sw-resize","ew-resize":"ew-resize","ns-resize":"ns-resize","nesw-resize":"nesw-resize","nwse-resize":"nwse-resize","zoom-in":"zoom-in","zoom-out":"zoom-out"},divideColor:({theme:e})=>e("borderColor"),divideOpacity:({theme:e})=>e("borderOpacity"),divideWidth:({theme:e})=>({...e("borderWidth"),...rv}),dropShadow:{sm:"0 1px 1px rgb(0 0 0 / 0.05)",DEFAULT:["0 1px 2px rgb(0 0 0 / 0.1)","0 1px 1px rgb(0 0 0 / 0.06)"],md:["0 4px 3px rgb(0 0 0 / 0.07)","0 2px 2px rgb(0 0 0 / 0.06)"],lg:["0 10px 8px rgb(0 0 0 / 0.04)","0 4px 3px rgb(0 0 0 / 0.1)"],xl:["0 20px 13px rgb(0 0 0 / 0.03)","0 8px 5px rgb(0 0 0 / 0.08)"],"2xl":"0 25px 25px rgb(0 0 0 / 0.15)",none:"0 0 #0000"},fill:({theme:e})=>e("colors"),flex:{1:"1 1 0%",auto:"1 1 auto",initial:"0 1 auto",none:"none"},flexBasis:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",...e("spacing")}),flexGrow:{0:"0",DEFAULT:"1",...ph},flexShrink:{0:"0",DEFAULT:"1",...ph},fontFamily:{sans:["ui-sans-serif","system-ui","sans-serif",'"Apple Color Emoji"','"Segoe UI Emoji"','"Segoe UI Symbol"','"Noto Color Emoji"'],serif:["ui-serif","Georgia","Cambria",'"Times New Roman"',"Times","serif"],mono:["ui-monospace","SFMono-Regular","Menlo","Monaco","Consolas",'"Liberation Mono"','"Courier New"',"monospace"]},fontSize:{xs:["0.75rem",{lineHeight:"1rem"}],sm:["0.875rem",{lineHeight:"1.25rem"}],base:["1rem",{lineHeight:"1.5rem"}],lg:["1.125rem",{lineHeight:"1.75rem"}],xl:["1.25rem",{lineHeight:"1.75rem"}],"2xl":["1.5rem",{lineHeight:"2rem"}],"3xl":["1.875rem",{lineHeight:"2.25rem"}],"4xl":["2.25rem",{lineHeight:"2.5rem"}],"5xl":["3rem",{lineHeight:"1"}],"6xl":["3.75rem",{lineHeight:"1"}],"7xl":["4.5rem",{lineHeight:"1"}],"8xl":["6rem",{lineHeight:"1"}],"9xl":["8rem",{lineHeight:"1"}]},fontWeight:{thin:"100",extralight:"200",light:"300",normal:"400",medium:"500",semibold:"600",bold:"700",extrabold:"800",black:"900"},gap:({theme:e})=>e("spacing"),gradientColorStops:({theme:e})=>e("colors"),gradientColorStopPositions:{"0%":"0%","5%":"5%","10%":"10%","15%":"15%","20%":"20%","25%":"25%","30%":"30%","35%":"35%","40%":"40%","45%":"45%","50%":"50%","55%":"55%","60%":"60%","65%":"65%","70%":"70%","75%":"75%","80%":"80%","85%":"85%","90%":"90%","95%":"95%","100%":"100%",...Ml},grayscale:{0:"0",DEFAULT:"100%",...Ml},gridAutoColumns:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridAutoRows:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridColumn:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridColumnEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...ph},gridColumnStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...ph},gridRow:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridRowEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...ph},gridRowStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...ph},gridTemplateColumns:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))",...Mit},gridTemplateRows:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))",...Mit},height:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),hueRotate:{0:"0deg",15:"15deg",30:"30deg",60:"60deg",90:"90deg",180:"180deg",...yH},inset:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%",...e("spacing")}),invert:{0:"0",DEFAULT:"100%",...Ml},keyframes:{spin:{to:{transform:"rotate(360deg)"}},ping:{"75%, 100%":{transform:"scale(2)",opacity:"0"}},pulse:{"50%":{opacity:".5"}},bounce:{"0%, 100%":{transform:"translateY(-25%)",animationTimingFunction:"cubic-bezier(0.8,0,1,1)"},"50%":{transform:"none",animationTimingFunction:"cubic-bezier(0,0,0.2,1)"}}},letterSpacing:{tighter:"-0.05em",tight:"-0.025em",normal:"0em",wide:"0.025em",wider:"0.05em",widest:"0.1em"},lineHeight:{none:"1",tight:"1.25",snug:"1.375",normal:"1.5",relaxed:"1.625",loose:"2",3:".75rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem"},listStyleType:{none:"none",disc:"disc",decimal:"decimal"},listStyleImage:{none:"none"},margin:({theme:e})=>({auto:"auto",...e("spacing")}),lineClamp:{1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",...ph},maxHeight:({theme:e})=>({none:"none",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),maxWidth:({theme:e})=>({none:"none",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",prose:"65ch",...e("spacing")}),minHeight:({theme:e})=>({full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),minWidth:({theme:e})=>({full:"100%",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),objectPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},opacity:{0:"0",5:"0.05",10:"0.1",15:"0.15",20:"0.2",25:"0.25",30:"0.3",35:"0.35",40:"0.4",45:"0.45",50:"0.5",55:"0.55",60:"0.6",65:"0.65",70:"0.7",75:"0.75",80:"0.8",85:"0.85",90:"0.9",95:"0.95",100:"1",...Ml},order:{first:"-9999",last:"9999",none:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",...ph},outlineColor:({theme:e})=>e("colors"),outlineOffset:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...rv},outlineWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...rv},padding:({theme:e})=>e("spacing"),placeholderColor:({theme:e})=>e("colors"),placeholderOpacity:({theme:e})=>e("opacity"),ringColor:({theme:e})=>({DEFAULT:"currentcolor",...e("colors")}),ringOffsetColor:({theme:e})=>e("colors"),ringOffsetWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...rv},ringOpacity:({theme:e})=>({DEFAULT:"0.5",...e("opacity")}),ringWidth:{DEFAULT:"3px",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...rv},rotate:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",45:"45deg",90:"90deg",180:"180deg",...yH},saturate:{0:"0",50:".5",100:"1",150:"1.5",200:"2",...Ml},scale:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",...Ml},screens:{sm:"40rem",md:"48rem",lg:"64rem",xl:"80rem","2xl":"96rem"},scrollMargin:({theme:e})=>e("spacing"),scrollPadding:({theme:e})=>e("spacing"),sepia:{0:"0",DEFAULT:"100%",...Ml},skew:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",...yH},space:({theme:e})=>e("spacing"),spacing:{px:"1px",0:"0px",0.5:"0.125rem",1:"0.25rem",1.5:"0.375rem",2:"0.5rem",2.5:"0.625rem",3:"0.75rem",3.5:"0.875rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem",11:"2.75rem",12:"3rem",14:"3.5rem",16:"4rem",20:"5rem",24:"6rem",28:"7rem",32:"8rem",36:"9rem",40:"10rem",44:"11rem",48:"12rem",52:"13rem",56:"14rem",60:"15rem",64:"16rem",72:"18rem",80:"20rem",96:"24rem"},stroke:({theme:e})=>({none:"none",...e("colors")}),strokeWidth:{0:"0",1:"1",2:"2",...ph},supports:{},data:{},textColor:({theme:e})=>e("colors"),textDecorationColor:({theme:e})=>e("colors"),textDecorationThickness:{auto:"auto","from-font":"from-font",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...rv},textIndent:({theme:e})=>e("spacing"),textOpacity:({theme:e})=>e("opacity"),textUnderlineOffset:{auto:"auto",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...rv},transformOrigin:{center:"center",top:"top","top-right":"top right",right:"right","bottom-right":"bottom right",bottom:"bottom","bottom-left":"bottom left",left:"left","top-left":"top left"},transitionDelay:{0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1000:"1000ms",...Fit},transitionDuration:{DEFAULT:"150ms",0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1000:"1000ms",...Fit},transitionProperty:{none:"none",all:"all",DEFAULT:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter",colors:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke",opacity:"opacity",shadow:"box-shadow",transform:"transform"},transitionTimingFunction:{DEFAULT:"cubic-bezier(0.4, 0, 0.2, 1)",linear:"linear",in:"cubic-bezier(0.4, 0, 1, 1)",out:"cubic-bezier(0, 0, 0.2, 1)","in-out":"cubic-bezier(0.4, 0, 0.2, 1)"},translate:({theme:e})=>({"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%",...e("spacing")}),size:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),width:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",screen:"100vw",svw:"100svw",lvw:"100lvw",dvw:"100dvw",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),willChange:{auto:"auto",scroll:"scroll-position",contents:"contents",transform:"transform"},zIndex:{auto:"auto",0:"0",10:"10",20:"20",30:"30",40:"40",50:"50",...ph}};function lP(e){if(arguments.length===0)throw TypeError("`CSS.escape` requires an argument.");let t=String(e),i=t.length,r=-1,n,o="",s=t.charCodeAt(0);if(i===1&&s===45)return"\\"+t;for(;++r<i;){if(n=t.charCodeAt(r),n===0){o+="\uFFFD";continue}if(n>=1&&n<=31||n===127||r===0&&n>=48&&n<=57||r===1&&n>=48&&n<=57&&s===45){o+="\\"+n.toString(16)+" ";continue}if(n>=128||n===45||n===95||n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122){o+=t.charAt(r);continue}o+="\\"+t.charAt(r)}return o}function cB(e){return e.replace(/\\([\dA-Fa-f]{1,6}[\t\n\f\r ]?|[\S\s])/g,(t)=>{if(t.length<=2)return t[1];let i=Number.parseInt(t.slice(1).trim(),16);return i===0||i>1114111||i>=55296&&i<=57343?"\uFFFD":String.fromCodePoint(i)})}var $it=new Map([["--font",["--font-weight","--font-size"]],["--inset",["--inset-shadow","--inset-ring"]],["--text",["--text-color","--text-decoration-color","--text-decoration-thickness","--text-indent","--text-shadow","--text-underline-offset"]],["--grid-column",["--grid-column-start","--grid-column-end"]],["--grid-row",["--grid-row-start","--grid-row-end"]]]);function qit(e,t){return($it.get(t)??[]).some((i)=>e===i||e.startsWith(`${i}-`))}var Git=class{constructor(e=new Map,t=new Set([])){this.values=e,this.keyframes=t}values;keyframes;prefix=null;get size(){return this.values.size}add(e,t,i=0,r){if(e.endsWith("-*")){if(t!=="initial")throw Error(`Invalid theme value \`${t}\` for namespace \`${e}\``);e==="--*"?this.values.clear():this.clearNamespace(e.slice(0,-2),0)}if(i&4){let n=this.values.get(e);if(n&&!(n.options&4))return}t==="initial"?this.values.delete(e):this.values.set(e,{value:t,options:i,src:r})}keysInNamespaces(e){let t=[];for(let i of e){let r=`${i}-`;for(let n of this.values.keys())n.startsWith(r)&&n.indexOf("--",2)===-1&&(qit(n,i)||t.push(n.slice(r.length)))}return t}get(e){for(let t of e){let i=this.values.get(t);if(i)return i.value}return null}hasDefault(e){return(this.getOptions(e)&4)===4}getOptions(e){return e=cB(this.#e(e)),this.values.get(e)?.options??0}entries(){return this.prefix?Array.from(this.values,(e)=>(e[0]=this.prefixKey(e[0]),e)):this.values.entries()}prefixKey(e){return this.prefix?`--${this.prefix}-${e.slice(2)}`:e}#e(e){return this.prefix?`--${e.slice(3+this.prefix.length)}`:e}clearNamespace(e,t){let i=$it.get(e)??[];e:for(let r of this.values.keys())if(r.startsWith(e)){if(t!==0&&(this.getOptions(r)&t)!==t)continue;for(let n of i)if(r.startsWith(n))continue e;this.values.delete(r)}}#t(e,t){for(let i of t){let r=e!==null?`${i}-${e}`:i;if(!this.values.has(r))if(e!==null&&e.includes(".")){if(r=`${i}-${e.replaceAll(".","_")}`,!this.values.has(r))continue}else continue;if(!qit(r,i))return r}return null}#i(e){let t=this.values.get(e);if(!t)return null;let i=null;return t.options&2&&(i=t.value),`var(${lP(this.prefixKey(e))}${i?`, ${i}`:""})`}markUsedVariable(e){let t=cB(this.#e(e)),i=this.values.get(t);if(!i)return!1;let r=i.options&16;return i.options|=16,!r}resolve(e,t,i=0){let r=this.#t(e,t);if(!r)return null;let n=this.values.get(r);return(i|n.options)&1?n.value:this.#i(r)}resolveValue(e,t){let i=this.#t(e,t);return i?this.values.get(i).value:null}resolveWith(e,t,i=[]){let r=this.#t(e,t);if(!r)return null;let n={};for(let s of i){let a=`${r}${s}`,c=this.values.get(a);c&&(c.options&1?n[s]=c.value:n[s]=this.#i(a))}let o=this.values.get(r);return o.options&1?[o.value,n]:[this.#i(r),n]}namespace(e){let t=new Map,i=`${e}-`;for(let[r,n]of this.values)r===e?t.set(null,n.value):r.startsWith(`${i}-`)?t.set(r.slice(e.length),n.value):r.startsWith(i)&&t.set(r.slice(i.length),n.value);return t}addKeyframes(e){this.keyframes.add(e)}getKeyframes(){return Array.from(this.keyframes)}};var DVi="4.3.2";function IVi(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);function i(n){let o=0,s=t.length;for(;s>0;){let c=(s|0)>>1,u=o+c;t[u]<=n?(o=u+1,s=s-c-1):s=c}o-=1;let a=n-t[o];return{line:o+1,column:a}}function r({line:n,column:o}){n-=1,n=Math.min(Math.max(n,0),t.length-1);let s=t[n],a=t[n+1]??s;return Math.min(Math.max(s+o,0),a)}return{find:i,findOffset:r}}var dP=92,AH=47,vH=42,Hit=34,Wit=39,_Vi=58,DH=59,hh=10,_H=13,pP=32,mP=9,Zit=123,$fe=125,Jfe=40,Vit=41,TVi=91,PVi=93,Kit=45,Gfe=64,RVi=33,Xy=class e extends Error{loc;constructor(t,i){if(i){let r=i[0],n=IVi(r.code).find(i[1]);t=`${r.file}:${n.line}:${n.column+1}: ${t}`}super(t),this.name="CssSyntaxError",this.loc=i,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};function Grt(e,t){let i=t?.from?{file:t.from,code:e}:null;e[0]==="\uFEFF"&&(e=" "+e.slice(1));let r=[],n=[],o=[],s=null,a=null,c="",u="",d=0,p;for(let m=0;m<e.length;m++){let h=e.charCodeAt(m);if(!(h===_H&&(p=e.charCodeAt(m+1),p===hh)))if(h===dP)c===""&&(d=m),c+=e.slice(m,m+2),m+=1;else if(h===AH&&e.charCodeAt(m+1)===vH){let f=m;for(let y=m+2;y<e.length;y++)if(p=e.charCodeAt(y),p===dP)y+=1;else if(p===vH&&e.charCodeAt(y+1)===AH){m=y+1;break}let g=e.slice(f,m+1);if(g.charCodeAt(2)===RVi){let y=Wrt(g.slice(2,-2));n.push(y),i&&(y.src=[i,f,m+1],y.dst=[i,f,m+1])}}else if(h===Wit||h===Hit){let f=Yit(e,m,h,i);c+=e.slice(m,f+1),m=f}else{if((h===pP||h===hh||h===mP)&&(p=e.charCodeAt(m+1))&&(p===pP||p===hh||p===mP||p===_H&&(p=e.charCodeAt(m+2))&&p==hh))continue;if(h===hh){if(c.length===0)continue;p=c.charCodeAt(c.length-1),p!==pP&&p!==hh&&p!==mP&&(c+=" ")}else if(h===Kit&&e.charCodeAt(m+1)===Kit&&c.length===0){let f="",g=m,y=-1;for(let v=m+2;v<e.length;v++)if(p=e.charCodeAt(v),p===dP)v+=1;else if(p===Wit||p===Hit)v=Yit(e,v,p,i);else if(p===AH&&e.charCodeAt(v+1)===vH){for(let w=v+2;w<e.length;w++)if(p=e.charCodeAt(w),p===dP)w+=1;else if(p===vH&&e.charCodeAt(w+1)===AH){v=w+1;break}}else if(y===-1&&p===_Vi)y=c.length+v-g;else if(p===DH&&f.length===0){c+=e.slice(g,v),m=v;break}else if(p===Jfe)f+=")";else if(p===TVi)f+="]";else if(p===Zit)f+="}";else if((p===$fe||e.length-1===v)&&f.length===0){m=v-1,c+=e.slice(g,v);break}else(p===Vit||p===PVi||p===$fe)&&f.length>0&&e[v]===f[f.length-1]&&(f=f.slice(0,-1));let b=Hfe(c,y);if(!b)throw new Xy("Invalid custom property, expected a value",i?[i,g,m]:null);i&&(b.src=[i,g,m],b.dst=[i,g,m]),s?s.nodes.push(b):r.push(b),c=""}else if(h===DH&&c.charCodeAt(0)===Gfe)a=IH(c),i&&(a.src=[i,d,m],a.dst=[i,d,m]),s?s.nodes.push(a):r.push(a),c="",a=null;else if(h===DH&&u[u.length-1]!==")"){let f=Hfe(c);if(!f){if(c.length===0)continue;throw new Xy(`Invalid declaration: \`${c.trim()}\``,i?[i,d,m]:null)}i&&(f.src=[i,d,m],f.dst=[i,d,m]),s?s.nodes.push(f):r.push(f),c=""}else if(h===Zit&&u[u.length-1]!==")")u+="}",a=oc(c.trim()),i&&(a.src=[i,d,m],a.dst=[i,d,m]),s&&s.nodes.push(a),o.push(s),s=a,c="",a=null;else if(h===$fe&&u[u.length-1]!==")"){if(u==="")throw new Xy("Missing opening {",i?[i,m,m]:null);if(u=u.slice(0,-1),c.length>0)if(c.charCodeAt(0)===Gfe)a=IH(c),i&&(a.src=[i,d,m],a.dst=[i,d,m]),s?s.nodes.push(a):r.push(a),c="",a=null;else{let g=c.indexOf(":");if(s){let y=Hfe(c,g);if(!y)throw new Xy(`Invalid declaration: \`${c.trim()}\``,i?[i,d,m]:null);i&&(y.src=[i,d,m],y.dst=[i,d,m]),s.nodes.push(y)}}let f=o.pop()??null;f===null&&s&&r.push(s),s=f,c="",a=null}else if(h===Jfe)u+=")",c+="(";else if(h===Vit){if(u[u.length-1]!==")")throw new Xy("Missing opening (",i?[i,m,m]:null);u=u.slice(0,-1),c+=")"}else{if(c.length===0&&(h===pP||h===hh||h===mP))continue;c===""&&(d=m),c+=String.fromCharCode(h)}}}if(c.charCodeAt(0)===Gfe){let m=IH(c);i&&(m.src=[i,d,e.length],m.dst=[i,d,e.length]),r.push(m)}if(u.length>0&&s){if(s.kind==="rule")throw new Xy(`Missing closing } at ${s.selector}`,s.src?[s.src[0],s.src[1],s.src[1]]:null);if(s.kind==="at-rule")throw new Xy(`Missing closing } at ${s.name} ${s.params}`,s.src?[s.src[0],s.src[1],s.src[1]]:null)}return n.length>0?n.concat(r):r}function IH(e,t=[]){let i=e,r="";for(let n=5;n<e.length;n++){let o=e.charCodeAt(n);if(o===pP||o===mP||o===Jfe){i=e.slice(0,n),r=e.slice(n);break}}return sn(i.trim(),r.trim(),t)}function Hfe(e,t=e.indexOf(":")){if(t===-1)return null;let i=e.indexOf("!important",t+1);return I(e.slice(0,t).trim(),e.slice(t+1,i===-1?e.length:i).trim(),i!==-1)}function Yit(e,t,i,r=null){let n;for(let o=t+1;o<e.length;o++)if(n=e.charCodeAt(o),n===dP)o+=1;else{if(n===i)return o;if(n===DH&&(e.charCodeAt(o+1)===hh||e.charCodeAt(o+1)===_H&&e.charCodeAt(o+2)===hh))throw new Xy(`Unterminated string: ${e.slice(t,o+1)+String.fromCharCode(i)}`,r?[r,t,o+1]:null);if(n===hh||n===_H&&e.charCodeAt(o+1)===hh)throw new Xy(`Unterminated string: ${e.slice(t,o)+String.fromCharCode(i)}`,r?[r,t,o+1]:null)}return t}var ki=class extends Map{constructor(e){super();this.factory=e}factory;get(e){let t=super.get(e);return t===void 0&&(t=this.factory(e,this),this.set(e,t)),t}};function Wc(e){return{kind:"word",value:e}}function FVi(e,t){return{kind:"function",value:e,nodes:t}}function MVi(e){return{kind:"separator",value:e}}function Cr(e){let t="";for(let i of e)switch(i.kind){case"word":case"separator":{t+=i.value;break}case"function":t+=i.value+"("+Cr(i.nodes)+")"}return t}var Jit=92,OVi=41,Qit=58,Xit=44,NVi=34,ert=61,trt=62,irt=60,rrt=10,LVi=40,zVi=39,jVi=47,nrt=32,ort=9;function Br(e){e=e.replaceAll(`\r
4720
+ ${b}`)}if(r!==void 0&&o?.algorithms!==void 0){let y=o.algorithms.map((b)=>b.alg);if(y.indexOf(r)<0)throw Error(`Attestation statement alg ${r} did not match one of ${y}`)}let h=i.map(oa),f=s.map(oa),g=!1;if(h.length===1&&f.indexOf(h[0])>=0)g=!0;if(!g)try{await Fl(h,f)}catch(y){throw Error(`Could not validate certificate path with any metadata root certificates: ${y.message}`)}return!0}var rQe={secp256r1_ecdsa_sha256_raw:{kty:2,alg:-7,crv:1},secp256r1_ecdsa_sha256_der:{kty:2,alg:-7,crv:1},rsassa_pss_sha256_raw:{kty:3,alg:-37},rsassa_pss_sha256_der:{kty:3,alg:-37},secp256k1_ecdsa_sha256_raw:{kty:2,alg:-47,crv:8},secp256k1_ecdsa_sha256_der:{kty:2,alg:-47,crv:8},rsassa_pss_sha384_raw:{kty:3,alg:-38},rsassa_pkcsv15_sha256_raw:{kty:3,alg:-257},rsassa_pkcsv15_sha384_raw:{kty:3,alg:-258},rsassa_pkcsv15_sha512_raw:{kty:3,alg:-259},rsassa_pkcsv15_sha1_raw:{kty:3,alg:-65535},secp384r1_ecdsa_sha384_raw:{kty:2,alg:-35,crv:2},secp512r1_ecdsa_sha256_raw:{kty:2,alg:-36,crv:3},ed25519_eddsa_sha512_raw:{kty:1,alg:-8,crv:6}};function nQe(e){let{kty:t,alg:i,crv:r}=e,n="";if(t!==up.RSA)n=`{ kty: ${t}, alg: ${i}, crv: ${r} }`;else n=`{ kty: ${t}, alg: ${i} }`;return n}async function oQe(e){let{attStmt:t,clientDataHash:i,authData:r,credentialPublicKey:n,aaguid:o,rootCertificates:s}=e,a=t.get("sig"),c=t.get("x5c"),u=t.get("alg");if(!a)throw Error("No attestation signature provided in attestation statement (Packed)");if(!u)throw Error("Attestation statement did not contain alg (Packed)");if(!Gf(u))throw Error(`Attestation statement contained invalid alg ${u} (Packed)`);let d=li.concat([r,i]),p=!1;if(c){let{subject:m,basicConstraintsCA:h,version:f,notBefore:g,notAfter:y,parsedCertificate:b}=yk(c[0]),{OU:v,CN:w,O:D,C:R}=m;if(v!=="Authenticator Attestation")throw Error('Certificate OU was not "Authenticator Attestation" (Packed|Full)');if(!w)throw Error("Certificate CN was empty (Packed|Full)");if(!D)throw Error("Certificate O was empty (Packed|Full)");if(!R||R.length!==2)throw Error("Certificate C was not two-character ISO 3166 code (Packed|Full)");if(h)throw Error("Certificate basic constraints CA was not `false` (Packed|Full)");if(f!==2)throw Error("Certificate version was not `3` (ASN.1 value of 2) (Packed|Full)");let O=new Date;if(g>O)throw Error(`Certificate not good before "${g.toString()}" (Packed|Full)`);if(O=new Date,y<O)throw Error(`Certificate not good after "${y.toString()}" (Packed|Full)`);try{await GG(b.tbsCertificate.extensions,o)}catch(j){throw Error(`${j.message} (Packed|Full)`)}let k=await JA.getStatement(o);if(k){if(k.attestationTypes.indexOf("basic_full")<0)throw Error("Metadata does not indicate support for full attestations (Packed|Full)");try{await QA({statement:k,credentialPublicKey:n,x5c:c,attestationStatementAlg:u})}catch(j){throw Error(`${j.message} (Packed|Full)`)}}else try{await Fl(c.map(oa),s)}catch(j){throw Error(`${j.message} (Packed|Full)`)}p=await gp({signature:a,data:d,x509Certificate:c[0],hashAlgorithm:u})}else p=await gp({signature:a,data:d,credentialPublicKey:n,hashAlgorithm:u});return p}async function sQe(e){let{attStmt:t,clientDataHash:i,authData:r,aaguid:n,rootCertificates:o,verifyTimestampMS:s=!0,credentialPublicKey:a,attestationSafetyNetEnforceCTSCheck:c}=e,u=t.get("alg"),d=t.get("response");if(!t.get("ver"))throw Error("No ver value in attestation (SafetyNet)");if(!d)throw Error("No response was included in attStmt by authenticator (SafetyNet)");let h=li.toUTF8String(d).split("."),f=JSON.parse(Ti.toUTF8String(h[0])),g=JSON.parse(Ti.toUTF8String(h[1])),y=h[2],{nonce:b,ctsProfileMatch:v,timestampMs:w}=g;if(s){let S=Date.now();if(w>Date.now())throw Error(`Payload timestamp "${w}" was later than "${S}" (SafetyNet)`);let P=w+60000;if(S=Date.now(),P<S)throw Error(`Payload timestamp "${P}" has expired (SafetyNet)`)}let D=li.concat([r,i]),R=await xp(D),O=Ti.fromBuffer(R,"base64");if(b!==O)throw Error("Could not verify payload nonce (SafetyNet)");if(c&&!v)throw Error("Could not verify device integrity (SafetyNet)");let k=Ti.toBuffer(f.x5c[0],"base64"),j=yk(k),{subject:L}=j;if(L.CN!=="attest.android.com")throw Error('Certificate common name was not "attest.android.com" (SafetyNet)');let q=await JA.getStatement(n);if(q)try{await QA({statement:q,credentialPublicKey:a,x5c:f.x5c,attestationStatementAlg:u})}catch(S){throw Error(`${S.message} (SafetyNet)`)}else try{await Fl(f.x5c.map(oa),o)}catch(S){throw Error(`${S.message} (SafetyNet)`)}let K=li.fromUTF8String(`${h[0]}.${h[1]}`),ue=Ti.toBuffer(y);return await gp({signature:ue,data:K,x509Certificate:k,hashAlgorithm:u})}var aQe={196:"TPM_ST_RSP_COMMAND",32768:"TPM_ST_NULL",32769:"TPM_ST_NO_SESSIONS",32770:"TPM_ST_SESSIONS",32788:"TPM_ST_ATTEST_NV",32789:"TPM_ST_ATTEST_COMMAND_AUDIT",32790:"TPM_ST_ATTEST_SESSION_AUDIT",32791:"TPM_ST_ATTEST_CERTIFY",32792:"TPM_ST_ATTEST_QUOTE",32793:"TPM_ST_ATTEST_TIME",32794:"TPM_ST_ATTEST_CREATION",32801:"TPM_ST_CREATION",32802:"TPM_ST_VERIFIED",32803:"TPM_ST_AUTH_SECRET",32804:"TPM_ST_HASHCHECK",32805:"TPM_ST_AUTH_SIGNED",32809:"TPM_ST_FU_MANIFEST"},rx={0:"TPM_ALG_ERROR",1:"TPM_ALG_RSA",4:"TPM_ALG_SHA",4:"TPM_ALG_SHA1",5:"TPM_ALG_HMAC",6:"TPM_ALG_AES",7:"TPM_ALG_MGF1",8:"TPM_ALG_KEYEDHASH",10:"TPM_ALG_XOR",11:"TPM_ALG_SHA256",12:"TPM_ALG_SHA384",13:"TPM_ALG_SHA512",16:"TPM_ALG_NULL",18:"TPM_ALG_SM3_256",19:"TPM_ALG_SM4",20:"TPM_ALG_RSASSA",21:"TPM_ALG_RSAES",22:"TPM_ALG_RSAPSS",23:"TPM_ALG_OAEP",24:"TPM_ALG_ECDSA",25:"TPM_ALG_ECDH",26:"TPM_ALG_ECDAA",27:"TPM_ALG_SM2",28:"TPM_ALG_ECSCHNORR",29:"TPM_ALG_ECMQV",32:"TPM_ALG_KDF1_SP800_56A",33:"TPM_ALG_KDF2",34:"TPM_ALG_KDF1_SP800_108",35:"TPM_ALG_ECC",37:"TPM_ALG_SYMCIPHER",38:"TPM_ALG_CAMELLIA",64:"TPM_ALG_CTR",65:"TPM_ALG_OFB",66:"TPM_ALG_CBC",67:"TPM_ALG_CFB",68:"TPM_ALG_ECB"},cQe={0:"TPM_ECC_NONE",1:"TPM_ECC_NIST_P192",2:"TPM_ECC_NIST_P224",3:"TPM_ECC_NIST_P256",4:"TPM_ECC_NIST_P384",5:"TPM_ECC_NIST_P521",16:"TPM_ECC_BN_P256",17:"TPM_ECC_BN_P638",32:"TPM_ECC_SM2_P256"},lQe={"id:414D4400":{name:"AMD",id:"AMD"},"id:414E5400":{name:"Ant Group",id:"ANT"},"id:41544D4C":{name:"Atmel",id:"ATML"},"id:4252434D":{name:"Broadcom",id:"BRCM"},"id:4353434F":{name:"Cisco",id:"CSCO"},"id:464C5953":{name:"Flyslice Technologies",id:"FLYS"},"id:524F4343":{name:"Fuzhou Rockchip",id:"ROCC"},"id:474F4F47":{name:"Google",id:"GOOG"},"id:48504900":{name:"HPI",id:"HPI"},"id:48504500":{name:"HPE",id:"HPE"},"id:48495349":{name:"Huawei",id:"HISI"},"id:49424d00":{name:"IBM",id:"IBM"},"id:49424D00":{name:"IBM",id:"IBM"},"id:49465800":{name:"Infineon",id:"IFX"},"id:494E5443":{name:"Intel",id:"INTC"},"id:4C454E00":{name:"Lenovo",id:"LEN"},"id:4D534654":{name:"Microsoft",id:"MSFT"},"id:4E534D20":{name:"National Semiconductor",id:"NSM"},"id:4E545A00":{name:"Nationz",id:"NTZ"},"id:4E534700":{name:"NSING",id:"NSG"},"id:4E544300":{name:"Nuvoton Technology",id:"NTC"},"id:51434F4D":{name:"Qualcomm",id:"QCOM"},"id:534D534E":{name:"Samsung",id:"SMSN"},"id:53454345":{name:"SecEdge",id:"SECE"},"id:534E5300":{name:"Sinosun",id:"SNS"},"id:534D5343":{name:"SMSC",id:"SMSC"},"id:53544D20":{name:"STMicroelectronics",id:"STM"},"id:54584E00":{name:"Texas Instruments",id:"TXN"},"id:57454300":{name:"Winbond",id:"WEC"},"id:5345414C":{name:"Wisekey",id:"SEAL"},"id:FFFFF1D0":{name:"FIDO Alliance",id:"FIDO"}},uQe={TPM_ECC_NIST_P256:1,TPM_ECC_NIST_P384:2,TPM_ECC_NIST_P521:3,TPM_ECC_BN_P256:1,TPM_ECC_SM2_P256:1};function dQe(e){let t=0,i=li.toDataView(e),r=i.getUint32(t);t+=4;let n=i.getUint16(t);t+=2;let o=aQe[n],s=i.getUint16(t);t+=2;let a=e.slice(t,t+=s),c=i.getUint16(t);t+=2;let u=e.slice(t,t+=c),d=e.slice(t,t+=8),p=i.getUint32(t);t+=4;let m=i.getUint32(t);t+=4;let h=!!e.slice(t,t+=1),f={clock:d,resetCount:p,restartCount:m,safe:h},g=e.slice(t,t+=8),y=i.getUint16(t);t+=2;let b=e.slice(t,t+=y),v=li.toDataView(b),w=i.getUint16(t);t+=2;let D=e.slice(t,t+=w),R={nameAlg:rx[v.getUint16(0)],nameAlgBuffer:b.slice(0,2),name:b,qualifiedName:D};return{magic:r,type:o,qualifiedSigner:a,extraData:u,clockInfo:f,firmwareVersion:g,attested:R}}function pQe(e){let t=0,i=li.toDataView(e),r=rx[i.getUint16(t)];t+=2;let n=rx[i.getUint16(t)];t+=2;let o=i.getUint32(t);t+=4;let s={fixedTPM:!!(o&1),stClear:!!(o&2),fixedParent:!!(o&8),sensitiveDataOrigin:!!(o&16),userWithAuth:!!(o&32),adminWithPolicy:!!(o&64),noDA:!!(o&512),encryptedDuplication:!!(o&1024),restricted:!!(o&32768),decrypt:!!(o&65536),signOrEncrypt:!!(o&131072)},a=i.getUint16(t);t+=2;let c=e.slice(t,t+=a),u={},d=Uint8Array.from([]);if(r==="TPM_ALG_RSA"){let p=rx[i.getUint16(t)];t+=2;let m=rx[i.getUint16(t)];t+=2;let h=i.getUint16(t);t+=2;let f=i.getUint32(t);t+=4,u.rsa={symmetric:p,scheme:m,keyBits:h,exponent:f};let g=i.getUint16(t);t+=2,d=e.slice(t,t+=g)}else if(r==="TPM_ALG_ECC"){let p=rx[i.getUint16(t)];t+=2;let m=rx[i.getUint16(t)];t+=2;let h=cQe[i.getUint16(t)];t+=2;let f=rx[i.getUint16(t)];t+=2,u.ecc={symmetric:p,scheme:m,curveID:h,kdf:f};let g=i.getUint16(t);t+=2;let y=e.slice(t,t+=g),b=i.getUint16(t);t+=2;let v=e.slice(t,t+=b);d=li.concat([y,v])}else throw Error(`Unexpected type "${r}" (TPM)`);return{type:r,nameAlg:n,objectAttributes:s,authPolicy:c,parameters:u,unique:d}}async function mQe(e){let{aaguid:t,attStmt:i,authData:r,credentialPublicKey:n,clientDataHash:o,rootCertificates:s}=e,a=i.get("ver"),c=i.get("sig"),u=i.get("alg"),d=i.get("x5c"),p=i.get("pubArea"),m=i.get("certInfo");if(a!=="2.0")throw Error(`Unexpected ver "${a}", expected "2.0" (TPM)`);if(!c)throw Error("No attestation signature provided in attestation statement (TPM)");if(!u)throw Error("Attestation statement did not contain alg (TPM)");if(!Gf(u))throw Error(`Attestation statement contained invalid alg ${u} (TPM)`);if(!d)throw Error("No attestation certificate provided in attestation statement (TPM)");if(!p)throw Error("Attestation statement did not contain pubArea (TPM)");if(!m)throw Error("Attestation statement did not contain certInfo (TPM)");let h=pQe(p),{unique:f,type:g,parameters:y}=h,b=CA(n);if(g==="TPM_ALG_RSA"){if(!U9(b))throw Error(`Credential public key with kty ${b.get(Di.kty)} did not match ${g}`);let se=b.get(Di.n),Se=b.get(Di.e);if(!se)throw Error("COSE public key missing n (TPM|RSA)");if(!Se)throw Error("COSE public key missing e (TPM|RSA)");if(!li.areEqual(f,se))throw Error("PubArea unique is not same as credentialPublicKey (TPM|RSA)");if(!y.rsa)throw Error("Parsed pubArea type is RSA, but missing parameters.rsa (TPM|RSA)");let fe=Se,ze=y.rsa.exponent||65537,Ye=fe[0]+(fe[1]<<8)+(fe[2]<<16);if(ze!==Ye)throw Error(`Unexpected public key exp ${Ye}, expected ${ze} (TPM|RSA)`)}else if(g==="TPM_ALG_ECC"){if(!kA(b))throw Error(`Credential public key with kty ${b.get(Di.kty)} did not match ${g}`);let se=b.get(Di.crv),Se=b.get(Di.x),fe=b.get(Di.y);if(!se)throw Error("COSE public key missing crv (TPM|ECC)");if(!Se)throw Error("COSE public key missing x (TPM|ECC)");if(!fe)throw Error("COSE public key missing y (TPM|ECC)");if(!li.areEqual(f,li.concat([Se,fe])))throw Error("PubArea unique is not same as public key x and y (TPM|ECC)");if(!y.ecc)throw Error("Parsed pubArea type is ECC, but missing parameters.ecc (TPM|ECC)");let ze=y.ecc.curveID,Ye=uQe[ze];if(Ye!==se)throw Error(`Public area key curve ID "${ze}" mapped to "${Ye}" which did not match public key crv of "${se}" (TPM|ECC)`)}else throw Error(`Unsupported pubArea.type "${g}"`);let v=dQe(m),{magic:w,type:D,attested:R,extraData:O}=v;if(w!==4283712327)throw Error(`Unexpected magic value "${w}", expected "0xff544347" (TPM)`);if(D!=="TPM_ST_ATTEST_CERTIFY")throw Error(`Unexpected type "${D}", expected "TPM_ST_ATTEST_CERTIFY" (TPM)`);let k=await xp(p,C$i(R.nameAlg)),j=li.concat([R.nameAlgBuffer,k]);if(!li.areEqual(R.name,j))throw Error("Attested name comparison failed (TPM)");let L=li.concat([r,o]),q=await xp(L,u);if(!li.areEqual(O,q))throw Error("CertInfo extra data did not equal hashed attestation (TPM)");if(d.length<1)throw Error("No certificates present in x5c array (TPM)");let K=yk(d[0]),{basicConstraintsCA:ue,version:G,subject:S,notAfter:P,notBefore:M}=K;if(ue)throw Error("Certificate basic constraints CA was not `false` (TPM)");if(G!==2)throw Error("Certificate version was not `3` (ASN.1 value of 2) (TPM)");if(S.combined.length>0)throw Error("Certificate subject was not empty (TPM)");let H=new Date;if(M>H)throw Error(`Certificate not good before "${M.toString()}" (TPM)`);if(H=new Date,P<H)throw Error(`Certificate not good after "${P.toString()}" (TPM)`);let V=Mo.parse(d[0],Us);if(!V.tbsCertificate.extensions)throw Error("Certificate was missing extensions (TPM)");let W,Y;if(V.tbsCertificate.extensions.forEach((se)=>{if(se.extnID===gk)W=Mo.parse(se.extnValue,xk);else if(se.extnID===hk)Y=Mo.parse(se.extnValue,m8)}),!W)throw Error("Certificate did not contain subjectAltName extension (TPM)");if(!W[0].directoryName?.[0].length)throw Error("Certificate subjectAltName extension directoryName was empty (TPM)");let{tcgAtTpmManufacturer:X,tcgAtTpmModel:te,tcgAtTpmVersion:Ce}=B$i(W[0].directoryName);if(!X||!te||!Ce)throw Error("Certificate contained incomplete subjectAltName data (TPM)");if(!Y)throw Error("Certificate did not contain ExtendedKeyUsage extension (TPM)");if(!lQe[X])throw Error(`Could not match TPM manufacturer "${X}" (TPM)`);if(Y[0]!=="2.23.133.8.3")throw Error(`Unexpected extKeyUsage "${Y[0]}", expected "2.23.133.8.3" (TPM)`);try{await GG(V.tbsCertificate.extensions,t)}catch(se){throw Error(`${se.message} (TPM)`)}let pe=await JA.getStatement(t);if(pe)try{await QA({statement:pe,credentialPublicKey:n,x5c:d,attestationStatementAlg:u})}catch(se){throw Error(`${se.message} (TPM)`)}else try{await Fl(d.map(oa),s)}catch(se){throw Error(`${se.message} (TPM)`)}return gp({signature:c,data:m,x509Certificate:d[0],hashAlgorithm:u})}function B$i(e){let n,o,s;return e.forEach((a)=>{a.forEach((c)=>{if(c.type==="2.23.133.2.1")n=c.value.toString();else if(c.type==="2.23.133.2.2")o=c.value.toString();else if(c.type==="2.23.133.2.3")s=c.value.toString()})}),{tcgAtTpmManufacturer:n,tcgAtTpmModel:o,tcgAtTpmVersion:s}}function C$i(e){if(e==="TPM_ALG_SHA256")return Vi.ES256;else if(e==="TPM_ALG_SHA384")return Vi.ES384;else if(e==="TPM_ALG_SHA512")return Vi.ES512;throw Error(`Unexpected TPM attested name alg ${e}`)}var Ohe,hQe="1.3.6.1.4.1.11129.2.1.17",Nhe;(function(e){e[e.verified=0]="verified",e[e.selfSigned=1]="selfSigned",e[e.unverified=2]="unverified",e[e.failed=3]="failed"})(Nhe||(Nhe={}));class Jk{verifiedBootKey=new At;deviceLocked=!1;verifiedBootState=Nhe.verified;verifiedBootHash;constructor(e={}){Object.assign(this,e)}}T([N({type:At})],Jk.prototype,"verifiedBootKey",void 0);T([N({type:Q.Boolean})],Jk.prototype,"deviceLocked",void 0);T([N({type:Q.Enumerated})],Jk.prototype,"verifiedBootState",void 0);T([N({type:At,optional:!0})],Jk.prototype,"verifiedBootHash",void 0);var Kk=Ohe=class extends ni{constructor(t){super(t);Object.setPrototypeOf(this,Ohe.prototype)}};Kk=Ohe=T([_e({type:ke.Set,itemType:Q.Integer})],Kk);class vi{purpose;algorithm;keySize;digest;padding;ecCurve;rsaPublicExponent;mgfDigest;rollbackResistance;earlyBootOnly;activeDateTime;originationExpireDateTime;usageExpireDateTime;usageCountLimit;noAuthRequired;userAuthType;authTimeout;allowWhileOnBody;trustedUserPresenceRequired;trustedConfirmationRequired;unlockedDeviceRequired;allApplications;applicationId;creationDateTime;origin;rollbackResistant;rootOfTrust;osVersion;osPatchLevel;attestationApplicationId;attestationIdBrand;attestationIdDevice;attestationIdProduct;attestationIdSerial;attestationIdImei;attestationIdMeid;attestationIdManufacturer;attestationIdModel;vendorPatchLevel;bootPatchLevel;deviceUniqueAttestation;attestationIdSecondImei;moduleHash;constructor(e={}){Object.assign(this,e)}}T([N({context:1,type:Kk,optional:!0})],vi.prototype,"purpose",void 0);T([N({context:2,type:Q.Integer,optional:!0})],vi.prototype,"algorithm",void 0);T([N({context:3,type:Q.Integer,optional:!0})],vi.prototype,"keySize",void 0);T([N({context:5,type:Kk,optional:!0})],vi.prototype,"digest",void 0);T([N({context:6,type:Kk,optional:!0})],vi.prototype,"padding",void 0);T([N({context:10,type:Q.Integer,optional:!0})],vi.prototype,"ecCurve",void 0);T([N({context:200,type:Q.Integer,optional:!0})],vi.prototype,"rsaPublicExponent",void 0);T([N({context:203,type:Kk,optional:!0})],vi.prototype,"mgfDigest",void 0);T([N({context:303,type:Q.Null,optional:!0})],vi.prototype,"rollbackResistance",void 0);T([N({context:305,type:Q.Null,optional:!0})],vi.prototype,"earlyBootOnly",void 0);T([N({context:400,type:Q.Integer,optional:!0})],vi.prototype,"activeDateTime",void 0);T([N({context:401,type:Q.Integer,optional:!0})],vi.prototype,"originationExpireDateTime",void 0);T([N({context:402,type:Q.Integer,optional:!0})],vi.prototype,"usageExpireDateTime",void 0);T([N({context:405,type:Q.Integer,optional:!0})],vi.prototype,"usageCountLimit",void 0);T([N({context:503,type:Q.Null,optional:!0})],vi.prototype,"noAuthRequired",void 0);T([N({context:504,type:Q.Integer,optional:!0})],vi.prototype,"userAuthType",void 0);T([N({context:505,type:Q.Integer,optional:!0})],vi.prototype,"authTimeout",void 0);T([N({context:506,type:Q.Null,optional:!0})],vi.prototype,"allowWhileOnBody",void 0);T([N({context:507,type:Q.Null,optional:!0})],vi.prototype,"trustedUserPresenceRequired",void 0);T([N({context:508,type:Q.Null,optional:!0})],vi.prototype,"trustedConfirmationRequired",void 0);T([N({context:509,type:Q.Null,optional:!0})],vi.prototype,"unlockedDeviceRequired",void 0);T([N({context:600,type:Q.Null,optional:!0})],vi.prototype,"allApplications",void 0);T([N({context:601,type:At,optional:!0})],vi.prototype,"applicationId",void 0);T([N({context:701,type:Q.Integer,optional:!0})],vi.prototype,"creationDateTime",void 0);T([N({context:702,type:Q.Integer,optional:!0})],vi.prototype,"origin",void 0);T([N({context:703,type:Q.Null,optional:!0})],vi.prototype,"rollbackResistant",void 0);T([N({context:704,type:Jk,optional:!0})],vi.prototype,"rootOfTrust",void 0);T([N({context:705,type:Q.Integer,optional:!0})],vi.prototype,"osVersion",void 0);T([N({context:706,type:Q.Integer,optional:!0})],vi.prototype,"osPatchLevel",void 0);T([N({context:709,type:At,optional:!0})],vi.prototype,"attestationApplicationId",void 0);T([N({context:710,type:At,optional:!0})],vi.prototype,"attestationIdBrand",void 0);T([N({context:711,type:At,optional:!0})],vi.prototype,"attestationIdDevice",void 0);T([N({context:712,type:At,optional:!0})],vi.prototype,"attestationIdProduct",void 0);T([N({context:713,type:At,optional:!0})],vi.prototype,"attestationIdSerial",void 0);T([N({context:714,type:At,optional:!0})],vi.prototype,"attestationIdImei",void 0);T([N({context:715,type:At,optional:!0})],vi.prototype,"attestationIdMeid",void 0);T([N({context:716,type:At,optional:!0})],vi.prototype,"attestationIdManufacturer",void 0);T([N({context:717,type:At,optional:!0})],vi.prototype,"attestationIdModel",void 0);T([N({context:718,type:Q.Integer,optional:!0})],vi.prototype,"vendorPatchLevel",void 0);T([N({context:719,type:Q.Integer,optional:!0})],vi.prototype,"bootPatchLevel",void 0);T([N({context:720,type:Q.Null,optional:!0})],vi.prototype,"deviceUniqueAttestation",void 0);T([N({context:723,type:At,optional:!0})],vi.prototype,"attestationIdSecondImei",void 0);T([N({context:724,type:At,optional:!0})],vi.prototype,"moduleHash",void 0);var Ky;(function(e){e[e.software=0]="software",e[e.trustedEnvironment=1]="trustedEnvironment",e[e.strongBox=2]="strongBox"})(Ky||(Ky={}));var Yk;(function(e){e[e.KM2=1]="KM2",e[e.KM3=2]="KM3",e[e.KM4=3]="KM4",e[e.KM4_1=4]="KM4_1",e[e.keyMint1=100]="keyMint1",e[e.keyMint2=200]="keyMint2",e[e.keyMint3=300]="keyMint3",e[e.keyMint4=400]="keyMint4"})(Yk||(Yk={}));class L0{attestationVersion=Yk.KM4;attestationSecurityLevel=Ky.software;keymasterVersion=0;keymasterSecurityLevel=Ky.software;attestationChallenge=new At;uniqueId=new At;softwareEnforced=new vi;teeEnforced=new vi;constructor(e={}){Object.assign(this,e)}}T([N({type:Q.Integer})],L0.prototype,"attestationVersion",void 0);T([N({type:Q.Enumerated})],L0.prototype,"attestationSecurityLevel",void 0);T([N({type:Q.Integer})],L0.prototype,"keymasterVersion",void 0);T([N({type:Q.Enumerated})],L0.prototype,"keymasterSecurityLevel",void 0);T([N({type:At})],L0.prototype,"attestationChallenge",void 0);T([N({type:At})],L0.prototype,"uniqueId",void 0);T([N({type:vi})],L0.prototype,"softwareEnforced",void 0);T([N({type:vi})],L0.prototype,"teeEnforced",void 0);class nx{attestationVersion=Yk.keyMint4;attestationSecurityLevel=Ky.software;keyMintVersion=0;keyMintSecurityLevel=Ky.software;attestationChallenge=new At;uniqueId=new At;softwareEnforced=new vi;hardwareEnforced=new vi;constructor(e={}){Object.assign(this,e)}toLegacyKeyDescription(){return new L0({attestationVersion:this.attestationVersion,attestationSecurityLevel:this.attestationSecurityLevel,keymasterVersion:this.keyMintVersion,keymasterSecurityLevel:this.keyMintSecurityLevel,attestationChallenge:this.attestationChallenge,uniqueId:this.uniqueId,softwareEnforced:this.softwareEnforced,teeEnforced:this.hardwareEnforced})}static fromLegacyKeyDescription(e){return new nx({attestationVersion:e.attestationVersion,attestationSecurityLevel:e.attestationSecurityLevel,keyMintVersion:e.keymasterVersion,keyMintSecurityLevel:e.keymasterSecurityLevel,attestationChallenge:e.attestationChallenge,uniqueId:e.uniqueId,softwareEnforced:e.softwareEnforced,hardwareEnforced:e.teeEnforced})}}T([N({type:Q.Integer})],nx.prototype,"attestationVersion",void 0);T([N({type:Q.Enumerated})],nx.prototype,"attestationSecurityLevel",void 0);T([N({type:Q.Integer})],nx.prototype,"keyMintVersion",void 0);T([N({type:Q.Enumerated})],nx.prototype,"keyMintSecurityLevel",void 0);T([N({type:At})],nx.prototype,"attestationChallenge",void 0);T([N({type:At})],nx.prototype,"uniqueId",void 0);T([N({type:vi})],nx.prototype,"softwareEnforced",void 0);T([N({type:vi})],nx.prototype,"hardwareEnforced",void 0);var Lhe,zhe=class extends vi{};zhe=T([_e({type:ke.Choice})],zhe);var Qk=Lhe=class extends ni{constructor(t){super(t);Object.setPrototypeOf(this,Lhe.prototype)}findProperty(t){let i=this.find((r)=>r[t]!==void 0);if(i)return i[t];return}};Qk=Lhe=T([_e({type:ke.Sequence,itemType:zhe})],Qk);class ox{attestationVersion=Yk.KM4;attestationSecurityLevel=Ky.software;keymasterVersion=0;keymasterSecurityLevel=Ky.software;attestationChallenge=new At;uniqueId=new At;softwareEnforced=new Qk;teeEnforced=new Qk;get keyMintVersion(){return this.keymasterVersion}set keyMintVersion(e){this.keymasterVersion=e}get keyMintSecurityLevel(){return this.keymasterSecurityLevel}set keyMintSecurityLevel(e){this.keymasterSecurityLevel=e}get hardwareEnforced(){return this.teeEnforced}set hardwareEnforced(e){this.teeEnforced=e}constructor(e={}){Object.assign(this,e)}}T([N({type:Q.Integer})],ox.prototype,"attestationVersion",void 0);T([N({type:Q.Enumerated})],ox.prototype,"attestationSecurityLevel",void 0);T([N({type:Q.Integer})],ox.prototype,"keymasterVersion",void 0);T([N({type:Q.Enumerated})],ox.prototype,"keymasterSecurityLevel",void 0);T([N({type:At})],ox.prototype,"attestationChallenge",void 0);T([N({type:At})],ox.prototype,"uniqueId",void 0);T([N({type:Qk})],ox.prototype,"softwareEnforced",void 0);T([N({type:Qk})],ox.prototype,"teeEnforced",void 0);var fQe=class extends ox{constructor(t={}){if("keymasterVersion"in t&&!("keyMintVersion"in t))t.keyMintVersion=t.keymasterVersion;if("keymasterSecurityLevel"in t&&!("keyMintSecurityLevel"in t))t.keyMintSecurityLevel=t.keymasterSecurityLevel;if("teeEnforced"in t&&!("hardwareEnforced"in t))t.hardwareEnforced=t.teeEnforced;super(t)}};fQe=T([_e({type:ke.Sequence})],fQe);class HG{packageName;version;constructor(e={}){Object.assign(this,e)}}T([N({type:Q.OctetString})],HG.prototype,"packageName",void 0);T([N({type:Q.Integer})],HG.prototype,"version",void 0);class jhe{packageInfos;signatureDigests;constructor(e={}){Object.assign(this,e)}}T([N({type:HG,repeated:"set"})],jhe.prototype,"packageInfos",void 0);T([N({type:Q.OctetString,repeated:"set"})],jhe.prototype,"signatureDigests",void 0);async function xQe(e){let{authData:t,clientDataHash:i,attStmt:r,credentialPublicKey:n,aaguid:o,rootCertificates:s}=e,a=r.get("x5c"),c=r.get("sig"),u=r.get("alg");if(!a)throw Error("No attestation certificate provided in attestation statement (Android Key)");if(!c)throw Error("No attestation signature provided in attestation statement (Android Key)");if(!u)throw Error("Attestation statement did not contain alg (Android Key)");if(!Gf(u))throw Error(`Attestation statement contained invalid alg ${u} (Android Key)`);let d=Mo.parse(a[0],Us),p=new Uint8Array(d.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey),m=$9(n);if(!li.areEqual(m,p))throw Error("Credential public key does not equal leaf cert public key (Android Key)");let h=d.tbsCertificate.extensions?.find((D)=>D.extnID===hQe);if(!h)throw Error("Certificate did not contain extKeyStore (Android Key)");let f=Mo.parse(h.extnValue,L0),{attestationChallenge:g,teeEnforced:y,softwareEnforced:b}=f;if(!li.areEqual(new Uint8Array(g.buffer),i))throw Error("Attestation challenge was not equal to client data hash (Android Key)");if(y.allApplications!==void 0)throw Error('teeEnforced contained "allApplications [600]" tag (Android Key)');if(b.allApplications!==void 0)throw Error('teeEnforced contained "allApplications [600]" tag (Android Key)');let v=await JA.getStatement(o);if(v)try{await QA({statement:v,credentialPublicKey:n,x5c:a,attestationStatementAlg:u})}catch(D){let R=D;throw Error(`${R.message} (Android Key)`,{cause:R})}else{let D=a.slice(0,-1).map(oa),R=a.slice(-1).map(oa);try{await Fl(D,R)}catch(O){let k=O;throw Error(`${k.message} (Android Key)`,{cause:k})}if(s.length>0&&s.indexOf(R[0])<0)throw Error("x5c root certificate was not a known root certificate (Android Key)")}let w=li.concat([t,i]);return gp({signature:c,data:w,x509Certificate:a[0],hashAlgorithm:u})}async function gQe(e){let{attStmt:t,authData:i,clientDataHash:r,credentialPublicKey:n,rootCertificates:o}=e,s=t.get("x5c");if(!s)throw Error("No attestation certificate provided in attestation statement (Apple)");try{await Fl(s.map(oa),o)}catch(y){throw Error(`${y.message} (Apple)`)}let a=Mo.parse(s[0],Us),{extensions:c,subjectPublicKeyInfo:u}=a.tbsCertificate;if(!c)throw Error("credCert missing extensions (Apple)");let d=c.find((y)=>y.extnID==="1.2.840.113635.100.8.2");if(!d)throw Error('credCert missing "1.2.840.113635.100.8.2" extension (Apple)');let p=li.concat([i,r]),m=await xp(p),h=new Uint8Array(d.extnValue.buffer).slice(6);if(!li.areEqual(m,h))throw Error("credCert nonce was not expected value (Apple)");let f=$9(n),g=new Uint8Array(u.subjectPublicKey);if(!li.areEqual(f,g))throw Error("Credential public key does not equal credCert public key (Apple)");return!0}async function yQe(e){let{response:t,expectedChallenge:i,expectedOrigin:r,expectedRPID:n,expectedType:o,requireUserPresence:s=!0,requireUserVerification:a=!0,supportedAlgorithmIDs:c=KJe,attestationSafetyNetEnforceCTSCheck:u=!0}=e,{id:d,rawId:p,type:m,response:h}=t;if(!d)throw Error("Missing credential ID");if(d!==p)throw Error("Credential ID was not base64url-encoded");if(m!=="public-key")throw Error(`Unexpected credential type ${m}, expected "public-key"`);let f=k$(h.clientDataJSON),{type:g,origin:y,challenge:b,tokenBinding:v}=f;if(Array.isArray(o)){if(!o.includes(g)){let se=o.join(", ");throw Error(`Unexpected registration response type "${g}", expected one of: ${se}`)}}else if(o){if(g!==o)throw Error(`Unexpected registration response type "${g}", expected "${o}"`)}else if(g!=="webauthn.create")throw Error(`Unexpected registration response type: ${g}`);if(typeof i==="function"){if(!await i(b))throw Error(`Custom challenge verifier returned false for registration response challenge "${b}"`)}else if(b!==i)throw Error(`Unexpected registration response challenge "${b}", expected "${i}"`);if(Array.isArray(r)){if(!r.includes(y))throw Error(`Unexpected registration response origin "${y}", expected one of: ${r.join(", ")}`)}else if(y!==r)throw Error(`Unexpected registration response origin "${y}", expected "${r}"`);if(v){if(typeof v!=="object")throw Error(`Unexpected value for TokenBinding "${v}"`);if(["present","supported","not-supported"].indexOf(v.status)<0)throw Error(`Unexpected tokenBinding.status value of "${v.status}"`)}let w=Ti.toBuffer(h.attestationObject),D=yZe(w),R=D.get("fmt"),O=D.get("authData"),k=D.get("attStmt"),j=zG(O),{aaguid:L,rpIdHash:q,flags:K,credentialID:ue,counter:G,credentialPublicKey:S,extensionsData:P}=j,M;if(n){let se=[];if(typeof n==="string")se=[n];else se=n;M=await $G(q,se)}if(s&&!K.up)throw Error("User presence was required, but user was not present");if(a&&!K.uv)throw Error("User verification was required, but user could not be verified");if(!ue)throw Error("No credential ID was provided by authenticator");if(!S)throw Error("No public key was provided by authenticator");if(!L)throw Error("No AAGUID was present during registration");let V=CA(S).get(Di.alg);if(typeof V!=="number")throw Error("Credential public key was missing numeric alg");if(!c.includes(V)){let se=c.join(", ");throw Error(`Unexpected public key alg "${V}", expected one of "${se}"`)}let W=await xp(Ti.toBuffer(h.clientDataJSON)),Y=YA.getRootCertificates({identifier:R}),X={aaguid:L,attStmt:k,authData:O,clientDataHash:W,credentialID:ue,credentialPublicKey:S,rootCertificates:Y,rpIdHash:q,attestationSafetyNetEnforceCTSCheck:u},te=!1;if(R==="fido-u2f")te=await XJe(X);else if(R==="packed")te=await oQe(X);else if(R==="android-safetynet")te=await sQe(X);else if(R==="android-key")te=await xQe(X);else if(R==="tpm")te=await mQe(X);else if(R==="apple")te=await gQe(X);else if(R==="none"){if(k.size>0)throw Error("None attestation had unexpected attestation statement");te=!0}else throw Error(`Unsupported Attestation Format: ${R}`);if(!te)return{verified:!1};let{credentialDeviceType:Ce,credentialBackedUp:pe}=qG(K);return{verified:!0,registrationInfo:{fmt:R,aaguid:S$(L),credentialType:m,credential:{id:Ti.fromBuffer(ue),publicKey:S,counter:G,transports:t.response.transports},attestationObject:w,userVerified:K.uv,credentialDeviceType:Ce,credentialBackedUp:pe,origin:f.origin,rpID:M,authenticatorExtensionResults:P}}}async function bQe(e){let{allowCredentials:t,challenge:i=await UG(),timeout:r=60000,userVerification:n="preferred",extensions:o,rpID:s}=e,a=i;if(typeof a==="string")a=li.fromUTF8String(a);return{rpId:s,challenge:Ti.fromBuffer(a),allowCredentials:t?.map((c)=>{if(!Ti.isBase64URL(c.id))throw Error(`allowCredential id "${c.id}" is not a valid base64url string`);return{...c,id:Ti.trimPadding(c.id),type:"public-key"}}),timeout:r,userVerification:n,extensions:o}}async function EQe(e){let{response:t,expectedChallenge:i,expectedOrigin:r,expectedRPID:n,expectedType:o,credential:s,requireUserVerification:a=!0,advancedFIDOConfig:c}=e,{id:u,rawId:d,type:p,response:m}=t;if(!u)throw Error("Missing credential ID");if(u!==d)throw Error("Credential ID was not base64url-encoded");if(p!=="public-key")throw Error(`Unexpected credential type ${p}, expected "public-key"`);if(!t)throw Error("Credential missing response");if(typeof m?.clientDataJSON!=="string")throw Error("Credential response clientDataJSON was not a string");let h=k$(m.clientDataJSON),{type:f,origin:g,challenge:y,tokenBinding:b}=h;if(Array.isArray(o)){if(!o.includes(f)){let M=o.join(", ");throw Error(`Unexpected authentication response type "${f}", expected one of: ${M}`)}}else if(o){if(f!==o)throw Error(`Unexpected authentication response type "${f}", expected "${o}"`)}else if(f!=="webauthn.get")throw Error(`Unexpected authentication response type: ${f}`);if(typeof i==="function"){if(!await i(y))throw Error(`Custom challenge verifier returned false for registration response challenge "${y}"`)}else if(y!==i)throw Error(`Unexpected authentication response challenge "${y}", expected "${i}"`);if(Array.isArray(r)){if(!r.includes(g)){let M=r.join(", ");throw Error(`Unexpected authentication response origin "${g}", expected one of: ${M}`)}}else if(g!==r)throw Error(`Unexpected authentication response origin "${g}", expected "${r}"`);if(!Ti.isBase64URL(m.authenticatorData))throw Error("Credential response authenticatorData was not a base64url string");if(!Ti.isBase64URL(m.signature))throw Error("Credential response signature was not a base64url string");if(m.userHandle&&typeof m.userHandle!=="string")throw Error("Credential response userHandle was not a string");if(b){if(typeof b!=="object")throw Error("ClientDataJSON tokenBinding was not an object");if(["present","supported","notSupported"].indexOf(b.status)<0)throw Error(`Unexpected tokenBinding status ${b.status}`)}let v=Ti.toBuffer(m.authenticatorData),w=zG(v),{rpIdHash:D,flags:R,counter:O,extensionsData:k}=w,j=[];if(typeof n==="string")j=[n];else j=n;let L=await $G(D,j);if(c!==void 0){let{userVerification:M}=c;if(M==="required"){if(!R.uv)throw Error("User verification required, but user could not be verified")}}else{if(!R.up)throw Error("User not present during authentication");if(a&&!R.uv)throw Error("User verification required, but user could not be verified")}let q=await xp(Ti.toBuffer(m.clientDataJSON)),K=li.concat([v,q]),ue=Ti.toBuffer(m.signature);if((O>0||s.counter>0)&&O<=s.counter)throw Error(`Response counter value ${O} was lower than expected ${s.counter}`);let{credentialDeviceType:G,credentialBackedUp:S}=qG(R);return{verified:await gp({signature:ue,data:K,credentialPublicKey:s.publicKey}),authenticationInfo:{newCounter:O,credentialID:s.id,userVerified:R.uv,credentialDeviceType:G,credentialBackedUp:S,authenticatorExtensionResults:k,origin:h.origin,rpID:L}}}var D$i="Anchor",I$i="Brain",_$i=l.looseObject({challenge:l.string().optional()});class WG{store;rpName;logger;constructor(e){this.store=new Rpe(e.runtimeDatabase),this.rpName=e.rpName??I$i,this.logger=e.logger}async hasCredentials(){return this.store.hasCredentials()}async generateRegistrationOptions(e,t){let i=await this.store.listCredentials(t.subject),r=t.userName??D$i,n=t.userDisplayName??r,o=await YJe({rpName:this.rpName,rpID:e.rpID,userName:r,userDisplayName:n,attestationType:"none",authenticatorSelection:{residentKey:"required",userVerification:"required"},excludeCredentials:i.map((s)=>({id:s.id,...s.transports?{transports:s.transports}:{}}))});return await this.store.saveRegistrationChallenge(o.challenge,t.subject),o}async verifyRegistrationResponse(e,t,i){let r=e.response.clientDataJSON?AQe(e.response.clientDataJSON):void 0;if(!r)return{verified:!1};let o=(await this.store.consumeRegistrationChallenge(r))?.userId;if(o===void 0||i!==void 0&&o!==i)return{verified:!1};let s=await yQe({response:e,expectedChallenge:r,expectedOrigin:t.origin,expectedRPID:t.rpID,requireUserVerification:!0});if(!s.verified)return{verified:!1};let a=s.registrationInfo.credential;return await this.store.addCredential({id:a.id,userId:o,publicKey:T$i(a.publicKey),counter:a.counter,...a.transports?{transports:a.transports}:{},credentialDeviceType:s.registrationInfo.credentialDeviceType,credentialBackedUp:s.registrationInfo.credentialBackedUp}),this.logger?.info("Registered passkey credential",{credentialId:a.id}),{verified:!0,subject:o}}async listCredentials(){return this.store.listCredentials()}async generateAuthenticationOptions(e){let t=await bQe({rpID:e.rpID,userVerification:"required"});return await this.store.saveAuthenticationChallenge(t.challenge),t}async verifyAuthenticationResponse(e,t){let i=e.response.clientDataJSON?AQe(e.response.clientDataJSON):void 0;if(!i)return{verified:!1};if(!await this.store.consumeAuthenticationChallenge(i))return{verified:!1};let n=await this.store.getCredential(e.id);if(!n)return{verified:!1};let o=await EQe({response:e,expectedChallenge:i,expectedOrigin:t.origin,expectedRPID:t.rpID,credential:R$i(n),requireUserVerification:!0});if(!o.verified)return{verified:!1};return await this.store.updateCredentialCounter(o.authenticationInfo.credentialID,o.authenticationInfo.newCounter),{verified:!0,subject:n.userId}}}function T$i(e){return Buffer.from(e).toString("base64url")}function P$i(e){let t=Buffer.from(e,"base64url"),i=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);return new Uint8Array(i)}function R$i(e){return{id:e.id,publicKey:P$i(e.publicKey),counter:e.counter,...e.transports?{transports:e.transports}:{}}}function AQe(e){try{return _$i.parse(JSON.parse(Buffer.from(e,"base64url").toString("utf8"))).challenge}catch{return}}class Uhe{issuer;users;identities;audit;setupFlow;targetedSetup;getChannelDescriptor;constructor(e){this.issuer=e.issuer,this.users=e.users,this.identities=e.identities,this.audit=e.audit,this.setupFlow=e.setupFlow,this.targetedSetup=e.targetedSetup,this.getChannelDescriptor=e.getChannelDescriptor}getSetupUrl(e=this.issuer){return this.setupFlow.getSetupUrl(e)}async startRegistration(e,t={},i){let r=await this.users.getUser(e);if(!r||r.status==="suspended")throw Error(`Eligible auth user not found: ${e}`);let n=i?await this.prepareDeliveryIdentity(e,i):await this.resolveStoredDeliveryIdentity(e),o=await this.setupFlow.createUserPasskeySetup(e,this.issuer,{deliveryClaimId:n.id});return await this.setupFlow.recordSetupDelivery(o.setupTokenId,n.deliverySubject),await this.audit.append({...xu(t),action:"auth.passkey.registration_started",targetType:"user",targetId:e,metadata:{expiresAt:o.expiresAt,deliveryType:n.type}}),{setupUrl:o.setupUrl,expiresAt:o.expiresAt,delivery:{type:n.type,label:this.getChannelDescriptor?.(n.type)?.subjectLabel??"Delivery channel"}}}async validateTargetedRegistration(e){await this.targetedSetup.validate({userId:e.targetUserId,setupTokenId:Uc(e.token)})}async completeTargetedRegistration(e){let t=await this.users.getUser(e.targetUserId),i=await this.targetedSetup.complete({userId:e.targetUserId,setupTokenId:Uc(e.token)});if(t?.status==="invited"&&i.user.status==="active")await this.audit.append({actorUserId:i.user.id,action:"auth.user.status_updated",targetType:"user",targetId:i.user.id,metadata:{status:"active"}});if(i.boundIdentity)await this.audit.append({actorUserId:i.user.id,action:"auth.identity.delivery_bound",targetType:"user",targetId:i.user.id,metadata:{type:i.boundIdentity.type}})}getPasskeySetupRequired(e=this.issuer){return this.setupFlow.getPasskeySetupRequired(e,{rotateHidden:!0})}getPasskeySetupRequiredForDelivery(e=this.issuer){return this.setupFlow.getPasskeySetupRequired(e)}hasSetupEmailDelivery(e,t){return this.setupFlow.hasSetupEmailDelivery(e,t)}recordSetupEmailDelivery(e,t,i={}){return this.setupFlow.recordSetupEmailDelivery(e,t,i)}async resolveStoredDeliveryIdentity(e){let i=(await this.identities.listIdentities(e)).filter((r)=>r.revokedAt===null&&Boolean(r.deliverySubject)&&r.evidence.some((n)=>n.sourceKind==="admin"||n.assurance==="verified"&&n.verifiedAt!==null)).at(-1);if(!i)throw Error("A confirmed delivery channel is required");return i}async prepareDeliveryIdentity(e,t){let i=t.subject.trim(),r=t.label?.trim(),{identity:n}=await this.identities.ensureIdentity({userId:e,type:t.type,subject:i,deliverySubject:i,label:r&&r.length>0?r:i,source:{kind:"admin"}});if(!n.deliverySubject)throw Error("Delivery identity subject was not persisted");return{...n,deliverySubject:n.deliverySubject}}}class VG{db;constructor(e){this.db=e}async invitePeerPerson(e){let t=ZG(e.peerId);return this.db.transaction(async(i)=>{await qhe(i,e.createdByUserId);let[r]=await i.select({peerId:on.peerId}).from(on).where(he(on.peerId,t)).limit(1);if(r)throw Error("External peer is already linked");let n=Date.now(),o={id:Nr("prsn"),displayName:e.displayName,profileEntityId:null,createdAt:n,updatedAt:n},s=Nr("usr"),a={id:s,personId:o.id,displayName:e.displayName,role:e.role,status:"invited",canonicalId:`user:${s.slice(4)}`,createdAt:n,updatedAt:n},c={peerId:t,personId:o.id,verificationStatus:"unverified",createdByUserId:e.createdByUserId,createdAt:n,updatedAt:n};return await i.insert(En).values(o),await i.insert(St).values(a),await i.insert(on).values(c),{person:o,user:a,peer:c}})}async linkPeer(e){let t=ZG(e.peerId);return this.db.transaction(async(i)=>{await qhe(i,e.createdByUserId);let[r]=await i.select().from(on).where(he(on.peerId,t)).limit(1);if(r){if(r.personId!==e.personId)throw Error("External peer is already linked to another person");return r}let[n]=await i.select({id:En.id}).from(En).where(he(En.id,e.personId)).limit(1);if(!n)throw Error(`Auth person not found: ${e.personId}`);let o=Date.now(),s={peerId:t,personId:n.id,verificationStatus:"unverified",createdByUserId:e.createdByUserId,createdAt:o,updatedAt:o};return await i.insert(on).values(s),s})}async unlinkPeer(e){let t=ZG(e.peerId);return this.db.transaction(async(i)=>{await qhe(i,e.actorUserId);let[r]=await i.select().from(on).where(bt(he(on.peerId,t),he(on.personId,e.personId))).limit(1);if(!r)throw Error("External peer link was not found");return await i.delete(on).where(bt(he(on.peerId,t),he(on.personId,e.personId))),r})}async getByPeerId(e){let[t]=await this.db.select().from(on).where(he(on.peerId,ZG(e))).limit(1);return t}async listByPersonId(e){return this.db.select().from(on).where(he(on.personId,e)).orderBy(on.createdAt,Ci`rowid`)}async listAll(){return this.db.select().from(on).orderBy(on.createdAt,Ci`rowid`)}}function ZG(e){let t=e.trim();if(!t)throw Error("External peer id is required");return t}async function qhe(e,t){let[i]=await e.select().from(St).where(he(St.id,t)).limit(1);if(i?.role!=="admin"||i.status!=="active")throw Error("An active Admin is required to link an external peer");return i}class KG{database;constructor(e){this.database=e}async get(e){let[t]=await this.database.db.select().from(Ey).where(he(Ey.domain,$he(e))).limit(1);return t?{domain:t.domain,keyFingerprint:t.keyFingerprint,grantedLevel:t.grantedLevel}:void 0}async grant(e,t={}){if(e.grantedLevel==="admin")throw Error("A2A peer trust grants must be trusted or public");let i={domain:$he(e.domain),keyFingerprint:e.keyFingerprint,grantedLevel:e.grantedLevel},r=Date.now();return await this.database.db.insert(Ey).values({domain:i.domain,keyFingerprint:i.keyFingerprint,grantedLevel:i.grantedLevel,createdAt:r,updatedAt:r}).onConflictDoUpdate({target:Ey.domain,set:{keyFingerprint:i.keyFingerprint,grantedLevel:i.grantedLevel,updatedAt:r}}),await new C0(this.database.db).append({...t.actorUserId?{actorUserId:t.actorUserId}:{},action:"auth.a2a_peer_trust.granted",targetType:"a2a_peer",targetId:i.domain,metadata:{keyFingerprint:i.keyFingerprint,grantedLevel:i.grantedLevel}}),i}async revoke(e,t={}){let i=$he(e);if((await this.database.db.delete(Ey).where(he(Ey.domain,i)).returning({domain:Ey.domain})).length>0)await new C0(this.database.db).append({...t.actorUserId?{actorUserId:t.actorUserId}:{},action:"auth.a2a_peer_trust.revoked",targetType:"a2a_peer",targetId:i})}}function $he(e){let t=e.trim().toLowerCase();if(!t||t.includes(":")||t.includes("/"))throw Error("A2A peer trust domain must be a bare domain");return t}import{randomUUID as vQe}from"crypto";var eP=86400;class Ghe{setupStateStore;passkeyService;setupTokenTtlSeconds;resolveSessionUserId;setupOperations=new XA;resolveHomePath;setupToken;constructor(e){this.setupStateStore=e.setupStateStore,this.passkeyService=e.passkeyService,this.setupTokenTtlSeconds=e.setupTokenTtlSeconds??eP,this.resolveSessionUserId=e.resolveSessionUserId,this.resolveHomePath=e.resolveHomePath??(()=>"/")}ensureSetupToken(){return this.setupOperations.run(()=>this.ensureSetupTokenInternal())}async ensureSetupTokenInternal(){let e=await this.getActiveSetupToken();if(e)return e;let t=Math.floor(Date.now()/1000);if(await this.setupStateStore.hasActiveSetupToken(t))return await this.setupStateStore.hasActiveSetupDelivery(t)?void 0:this.createSetupToken();return this.createSetupToken()}async createSetupToken(){let e={token:`setup_${vQe()}`,expiresAt:Math.floor(Date.now()/1000)+this.setupTokenTtlSeconds};return await this.setupStateStore.saveSetupToken(e),this.setupToken=e,e}async getActiveSetupToken(){return this.setupToken=await this.setupStateStore.getValidSetupToken(Math.floor(Date.now()/1000)),this.setupToken}getValidSetupToken(){if(!this.setupToken)return;if(this.setupToken.expiresAt<=Math.floor(Date.now()/1000)){this.setupToken=void 0;return}return this.setupToken}async resolveSetupToken(e){let t=new URL(e.url),i=t.searchParams.get("setup_token")??t.searchParams.get("token");if(!i)return;let r=await this.setupStateStore.getSetupTokenTarget(i,Math.floor(Date.now()/1000));return r?{token:i,...r}:void 0}async hasValidSetupToken(e){return Boolean(await this.resolveSetupToken(e))}async hasConflictingAccountSession(e,t){if(!t.targetUserId||!this.resolveSessionUserId)return!1;let i=await this.resolveSessionUserId(e);return i!==void 0&&i!==t.targetUserId}consumeSetupToken(e){return this.setupOperations.run(async()=>{if(this.setupToken?.token===e)this.setupToken=void 0;await this.setupStateStore.consumeSetupToken(e)})}clearSetupState(){return this.setupOperations.run(async()=>{this.setupToken=void 0,await this.setupStateStore.clearSetupState()})}getSetupUrl(e){let t=this.getValidSetupToken();if(!t)return;return Dl(e,`/setup?token=${encodeURIComponent(t.token)}`)}getPasskeySetupRequired(e,t={}){return this.setupOperations.run(async()=>{if(await this.passkeyService.hasCredentials())return;let i=await this.getActiveSetupToken();if(!i&&t.rotateHidden){let r=Math.floor(Date.now()/1000);if(await this.setupStateStore.hasActiveSetupDelivery(r))return;i=await this.createSetupToken()}if(!i)return;return{setupUrl:Dl(e,`/setup?token=${encodeURIComponent(i.token)}`),expiresAt:i.expiresAt,setupTokenId:Uc(i.token)}})}async createUserPasskeySetup(e,t,i={}){let r={token:`setup_${vQe()}`,expiresAt:Math.floor(Date.now()/1000)+this.setupTokenTtlSeconds};return await this.setupStateStore.saveTargetedSetupToken(r,e,i),{setupUrl:Dl(t,`/setup?token=${encodeURIComponent(r.token)}`),expiresAt:r.expiresAt,setupTokenId:Uc(r.token)}}consumeTargetedSetupTokensForUser(e){return this.setupStateStore.consumeTargetedSetupTokensForUser(e)}async handleSetupPage(e){let t=await this.resolveSetupToken(e);if(await this.passkeyService.hasCredentials()&&t?.targetUserId==null)return vA(qHe(),404);if(!t)return new Response("Not Found",{status:404});if(await this.hasConflictingAccountSession(e,t)){let i=new URL(e.url);return vA($He(`${i.pathname}${i.search}`),409)}return vA(GHe(t.token,this.resolveHomePath()))}async hasSetupDelivery(e,t){return this.setupStateStore.hasDelivery(e,t)}async recordSetupDelivery(e,t,i={}){await this.setupStateStore.recordDelivery(e,t,i)}async hasSetupEmailDelivery(e,t){return this.hasSetupDelivery(e,t)}async recordSetupEmailDelivery(e,t,i={}){await this.recordSetupDelivery(e,t,i)}}class Hhe{db;identityStore;constructor(e,t){this.db=e,this.identityStore=t}async validate(e){await wQe(this.db,e)}async complete(e){let t=Math.floor(Date.now()/1000),i=Date.now(),r=await this.db.transaction(async(n)=>{let o=await wQe(n,e),s=o.deliveryClaim;if(s){let[c]=await n.select({id:rs.id}).from(rs).where(bt(he(rs.claimId,s.id),he(rs.assurance,"verified"),_9(rs.verifiedAt))).limit(1);if(!c)await n.insert(rs).values({id:Nr("aev"),claimId:s.id,sourceKind:"provider",sourceId:null,assurance:"verified",verifiedAt:i,createdAt:i})}if(o.user.status==="invited")await n.update(St).set({status:"active",updatedAt:i}).where(he(St.id,o.user.id));if((await n.update(ut).set({consumedAt:t}).where(bt(he(ut.tokenHash,e.setupTokenId),gi(ut.consumedAt))).returning({tokenHash:ut.tokenHash})).length!==1)throw Error("Invalid or consumed setup token");return await n.update(ci).set({state:"claimed",claimedAt:i,updatedAt:i}).where(he(ci.currentSetupTokenHash,e.setupTokenId)),s?.id});return{user:await this.requireUser(e.userId),...r?{boundIdentity:await this.identityStore.getIdentity(r)}:{}}}async requireUser(e){let[t]=await this.db.select().from(St).where(he(St.id,e)).limit(1);if(!t)throw Error(`Auth user not found: ${e}`);return t}}class Yy extends Error{reason;constructor(e,t){super(t);this.name="TargetedSetupError",this.reason=e}}async function wQe(e,t){let i=Math.floor(Date.now()/1000),[r]=await e.select().from(ut).where(bt(he(ut.tokenHash,t.setupTokenId),he(ut.purpose,"passkey_setup"),he(ut.targetUserId,t.userId),gi(ut.consumedAt),jc(ut.expiresAt,i))).limit(1);if(!r)throw new Yy("token-invalid","Invalid or consumed setup token");let[n]=await e.select().from(St).where(he(St.id,t.userId)).limit(1);if(!n||n.status==="suspended")throw new Yy("user-unavailable","Passkey registration user is unavailable");if(!r.deliveryClaimId)return{user:n};let[o]=await e.select().from(pi).where(bt(he(pi.id,r.deliveryClaimId),gi(pi.revokedAt))).limit(1);if(!o)throw new Yy("delivery-identity-unavailable","Setup delivery identity is unavailable");if(o.personId!==n.personId)throw new Yy("delivery-identity-unavailable","Setup delivery identity does not belong to target user");if(o.type!=="email"&&o.type!=="discord"||!o.deliverySubject)throw new Yy("delivery-identity-unavailable","Setup delivery identity is unavailable");let[s]=await e.select({tokenHash:zc.tokenHash}).from(zc).where(bt(he(zc.tokenHash,t.setupTokenId),he(zc.recipientHash,n8(o.deliverySubject)))).limit(1);if(!s)throw new Yy("delivery-unconfirmed","Setup delivery was not confirmed");return{user:n,deliveryClaim:o}}class Whe{users;audit;sessions;refreshTokens;consumeTargetedSetupTokensForUser;onUserDeleted;constructor(e){this.users=e.users,this.audit=e.audit,this.sessions=e.sessions,this.refreshTokens=e.refreshTokens,this.consumeTargetedSetupTokensForUser=e.consumeTargetedSetupTokensForUser,this.onUserDeleted=e.onUserDeleted}async createUser(e,t={}){let i=await this.users.createUser(e);return await this.audit.append({...xu(t),action:"auth.user.created",targetType:"user",targetId:i.id,metadata:{role:i.role,status:i.status}}),i}async updateRole(e,t,i={}){let r=await this.users.getUser(e),n=await this.users.updateUserRole(e,t);if(r&&r.role!==n.role)await this.revokeGrants(e),await this.audit.append({...xu(i),action:"auth.user.role_updated",targetType:"user",targetId:e,metadata:{from:r.role,to:n.role}});return n}async updateStatus(e,t,i={}){let r=await this.users.getUser(e),n=await this.users.updateUserStatus(e,t);if(r&&r.status!==n.status){let o=n.status==="suspended"?await this.consumeTargetedSetupTokensForUser(e):0;await this.revokeGrants(e),await this.audit.append({...xu(i),action:"auth.user.status_updated",targetType:"user",targetId:e,metadata:{from:r.status,to:n.status,...o>0?{consumedSetupTokens:o}:{}}})}return n}async deleteSuspendedUser(e,t={}){let i=await this.users.deleteSuspendedUser(e);return this.onUserDeleted?.(e),await this.audit.append({...xu(t),action:"auth.user.deleted",targetType:"user",targetId:e,metadata:{role:i.role,status:i.status}}),i}async revokeGrants(e,t={}){let[i,r]=await Promise.all([this.sessions.revokeSessionsForSubject(e),this.refreshTokens.revokeTokensForSubject(e)]);if(t.actorUserId)await this.audit.append({...xu(t),action:"auth.user.grants_revoked",targetType:"user",targetId:e,metadata:{sessions:i,refreshTokens:r}});return{sessions:i,refreshTokens:r}}}class Zhe{passkeyService;sessionStore;setupFlow;registrationUserProvider;validateTargetedRegistration;completeTargetedRegistration;recordAuditEvent;constructor(e){this.passkeyService=e.passkeyService,this.sessionStore=e.sessionStore,this.setupFlow=e.setupFlow,this.registrationUserProvider=e.registrationUserProvider,this.validateTargetedRegistration=e.validateTargetedRegistration,this.completeTargetedRegistration=e.completeTargetedRegistration,this.recordAuditEvent=e.recordAuditEvent}async handleRegistrationOptions(e){let t=await this.resolveRegistrationSetup(e);if(t instanceof Response)return t;try{let i=await this.passkeyService.generateRegistrationOptions(YG(e),await this.registrationUserProvider(t.targetUserId??void 0));return dd(i)}catch{return Vn("access_denied","Passkey registration user is unavailable")}}async handleRegistrationVerify(e){let t=await this.resolveRegistrationSetup(e);if(t instanceof Response)return t;if(t.targetUserId)try{await this.registrationUserProvider(t.targetUserId),await this.validateTargetedRegistration?.({...t,targetUserId:t.targetUserId})}catch(o){return await this.recordRegistrationFailure(t.targetUserId),Vn("access_denied",kQe(o))}let i=s$.safeParse(await e.json());if(!i.success)return await this.recordRegistrationFailure(t.targetUserId),Vn("access_denied","Passkey registration failed");let r=await this.passkeyService.verifyRegistrationResponse(i.data,YG(e),t.targetUserId??void 0);if(!r.verified||t.targetUserId!==null&&r.subject!==t.targetUserId)return await this.recordRegistrationFailure(t.targetUserId),Vn("access_denied","Passkey registration failed");if(t.targetUserId&&this.completeTargetedRegistration)try{await this.completeTargetedRegistration({...t,targetUserId:t.targetUserId})}catch(o){return await this.recordRegistrationFailure(t.targetUserId),Vn("access_denied",kQe(o))}else await this.setupFlow.consumeSetupToken(t.token);let n=await this.sessionStore.createSession(r.subject,{secure:e8(e)});return dd({verified:!0},200,{"Set-Cookie":n.cookie})}async resolveRegistrationSetup(e){let t=await this.setupFlow.resolveSetupToken(e);if(await this.passkeyService.hasCredentials()&&t?.targetUserId==null)return Vn("access_denied","Passkey setup already completed");if(!t)return Vn("access_denied","Invalid setup token");if(await this.setupFlow.hasConflictingAccountSession(e,t))return Vn("access_denied","Sign out before using a setup link for another account");return t}async recordRegistrationFailure(e){await this.recordAuditEvent?.({action:"auth.passkey.registration_failed",...e?{targetType:"user",targetId:e}:{}})}async handleAuthenticationOptions(e){if(!await this.passkeyService.hasCredentials())return Vn("access_denied","No passkey registered");let t=await this.passkeyService.generateAuthenticationOptions(YG(e));return dd(t)}async handleAuthenticationVerify(e){let t=PHe.safeParse(await e.json());if(!t.success)return await this.recordAuditEvent?.({action:"auth.passkey.authentication_failed"}),Vn("access_denied","Passkey authentication failed");let i=await this.passkeyService.verifyAuthenticationResponse(t.data,YG(e));if(!i.verified)return await this.recordAuditEvent?.({action:"auth.passkey.authentication_failed"}),Vn("access_denied","Passkey authentication failed");let r=await this.sessionStore.createSession(i.subject,{secure:e8(e)});return dd({verified:!0},200,{"Set-Cookie":r.cookie})}}function YG(e){let t=u0(e),i=new URL(t);return{origin:i.origin,rpID:i.hostname}}var SQe={"token-invalid":"Invalid setup token","user-unavailable":"Passkey registration user is unavailable","delivery-identity-unavailable":"This setup link's delivery address is no longer valid; ask an admin for a new link","delivery-unconfirmed":"This setup link has not been confirmed as delivered; ask an admin to confirm it"};function kQe(e){return e instanceof Yy?SQe[e.reason]:SQe["user-unavailable"]}class Vhe{keyStore;a2aKeyStore;clientStore;authCodeStore;sessionStore;peerTrustStore;passkeyService;setupFlow;oauthEndpoints;webauthnEndpoints;runtimeDatabase;runBackgroundOperation;refreshTokenStore;issuer;trustedIssuers;allowLocalhostIssuers;anchor;anchorProfileEntityId;setupTokenTtlSeconds;issuesSetupLinks;getOnboardingDetails;getInvitationDeliveryProvider;getChannelDescriptor;isChannelTypeRegistered;autoStartInvitationDeliveryRecovery;invitationDeliveryRecoveryIntervalMs;invitationDeliveryRecoveryStaleMs;resolveProfileDisplayName;accountSettingsEncryptionKey;onAccountDeleted;logger;accountSettingsStore;userStore;identityReconciliationService;passkeySetupCoordinator;userManagementService;principalService;administrationService;accountService;invitationService;invitationDeliverySupervisor;interfacePrincipalStore;auditStore;lifecycleTail=Promise.resolve();initialization;firstAdminInitialization;closePromise;constructor(e){this.runBackgroundOperation=e.runBackgroundOperation,this.issuer=e.issuer,this.trustedIssuers=e.trustedIssuers,this.allowLocalhostIssuers=e.allowLocalhostIssuers,this.anchor=e.anchor,this.anchorProfileEntityId=e.anchorProfileEntityId,this.setupTokenTtlSeconds=e.setupTokenTtlSeconds??eP,this.issuesSetupLinks=e.issuesSetupLinks??!0,this.getInvitationDeliveryProvider=e.getInvitationDeliveryProvider,this.getOnboardingDetails=e.getOnboardingDetails,this.getChannelDescriptor=e.getChannelDescriptor,this.isChannelTypeRegistered=e.isChannelTypeRegistered,this.autoStartInvitationDeliveryRecovery=e.autoStartInvitationDeliveryRecovery??!0,this.invitationDeliveryRecoveryIntervalMs=e.invitationDeliveryRecoveryIntervalMs??KWe,this.invitationDeliveryRecoveryStaleMs=e.invitationDeliveryRecoveryStaleMs??$pe,this.resolveProfileDisplayName=e.resolveProfileDisplayName,this.accountSettingsEncryptionKey=e.accountSettingsEncryptionKey,this.onAccountDeleted=e.onAccountDeleted,this.logger=e.logger,this.runtimeDatabase=new I9({storageDir:e.storageDir,...e.replica?{replica:e.replica}:{}}),this.keyStore=new g$(this.runtimeDatabase),this.a2aKeyStore=new Hpe(this.runtimeDatabase),this.clientStore=new h$(this.runtimeDatabase,this.issuer),this.authCodeStore=new o$(this.runtimeDatabase),this.sessionStore=new r_(this.runtimeDatabase),this.refreshTokenStore=new t_(this.runtimeDatabase),this.peerTrustStore=new KG(this.runtimeDatabase),this.passkeyService=new WG({runtimeDatabase:this.runtimeDatabase,...e.logger?{logger:e.logger}:{}});let t=new jpe(this.runtimeDatabase);this.setupFlow=new Ghe({...e.resolveHomePath?{resolveHomePath:e.resolveHomePath}:{},setupStateStore:t,passkeyService:this.passkeyService,setupTokenTtlSeconds:this.setupTokenTtlSeconds,resolveSessionUserId:async(i)=>(await this.resolveActiveSession(i))?.user.id}),this.oauthEndpoints=new Vpe({clientStore:this.clientStore,authCodeStore:this.authCodeStore,refreshTokenStore:this.refreshTokenStore,resolveSession:async(i)=>(await this.resolveActiveSession(i))?.session,keyStore:this.keyStore,...e.clientMetadataDocumentResolver?{clientMetadataDocumentResolver:e.clientMetadataDocumentResolver}:{},...e.oauthClientMaintenanceIntervalMs!==void 0?{clientMaintenanceIntervalMs:e.oauthClientMaintenanceIntervalMs}:{},runClientMaintenance:this.runBackgroundOperation,onClientMaintenanceError:(i)=>{this.logger?.warn("Failed to prune stale OAuth clients",{error:i})}}),this.webauthnEndpoints=new Zhe({passkeyService:this.passkeyService,sessionStore:this.sessionStore,setupFlow:this.setupFlow,recordAuditEvent:async(i)=>{await this.getAuditStore().append(i)},validateTargetedRegistration:async(i)=>{await this.getPasskeySetupCoordinator().validateTargetedRegistration(i)},completeTargetedRegistration:async(i)=>{await this.getPasskeySetupCoordinator().completeTargetedRegistration(i)},registrationUserProvider:async(i)=>{let r=i?await this.getUserStore().getUser(i):await this.ensureFirstAdminUser();if(!r||r.status==="suspended")throw Error("Passkey registration user is unavailable");return{subject:r.id,userName:r.displayName,userDisplayName:r.displayName}}})}async initialize(){if(this.initialization)return this.initialization;let e=this.startLifecycle(()=>this.initializeInternal());this.initialization=e;try{await e}catch(t){if(this.initialization===e)this.initialization=void 0;throw t}}close(){if(!this.closePromise)this.initialization=void 0,this.closePromise=this.enqueueLifecycle(()=>this.closeInternal());return this.closePromise}ensureStarted(){return this.startLifecycle(()=>this.ensureStartedInternal())}enqueueLifecycle(e){let t=this.lifecycleTail.then(e);return this.lifecycleTail=t.then(()=>{return}).catch(()=>{}),t}startLifecycle(e){this.closePromise=void 0;let t=this.initialization;return this.enqueueLifecycle(async()=>{try{return await e()}catch(i){if(this.initialization===t)this.initialization=void 0;try{await this.closeInternal()}catch(r){throw AggregateError([i,r],"Auth startup and rollback failed",{cause:r})}throw i}})}async ensureStartedInternal(){if(this.userStore)return;await this.runtimeDatabase.start();let e=new O9(this.runtimeDatabase.db,{...this.isChannelTypeRegistered?{isChannelTypeRegistered:this.isChannelTypeRegistered}:{}});this.userStore=new o_(this.runtimeDatabase.db),this.identityReconciliationService=new Fpe({identities:e,users:this.userStore});let t=new Hhe(this.runtimeDatabase.db,e);this.interfacePrincipalStore=new Jq(this.runtimeDatabase.db);let i=new VG(this.runtimeDatabase.db);this.auditStore=new C0(this.runtimeDatabase.db),this.invitationService=new x$({db:this.runtimeDatabase.db,issuer:this.issuer,setupTokenTtlSeconds:this.setupTokenTtlSeconds,deliveryRecoveryStaleMs:this.invitationDeliveryRecoveryStaleMs,audit:this.auditStore,...this.getInvitationDeliveryProvider?{getDeliveryProvider:this.getInvitationDeliveryProvider}:{},...this.getChannelDescriptor?{getChannelDescriptor:this.getChannelDescriptor}:{},getOnboardingContext:async()=>{let[n,o]=await Promise.all([this.profileDisplayName(this.anchorProfileEntityId),this.getOnboardingDetails?.()]);return{links:o?.links??{},...o?.purpose?{purpose:o.purpose}:{},...n?{brainName:n}:{}}}}),this.invitationDeliverySupervisor=new Gpe(this.invitationDeliveryRecoveryIntervalMs,(n)=>this.runBackgroundOperation(async()=>{await this.getInvitationService().recoverInterruptedDeliveries(n)}),{onError:(n)=>{this.logger?.warn("Failed to recover invitation delivery",{error:n})}}),this.passkeySetupCoordinator=new Uhe({issuer:this.issuer,users:this.userStore,identities:e,audit:this.auditStore,setupFlow:this.setupFlow,targetedSetup:t,...this.getChannelDescriptor?{getChannelDescriptor:this.getChannelDescriptor}:{}}),this.userManagementService=new Whe({users:this.userStore,audit:this.auditStore,sessions:this.sessionStore,refreshTokens:this.refreshTokenStore,consumeTargetedSetupTokensForUser:(n)=>this.setupFlow.consumeTargetedSetupTokensForUser(n),...this.onAccountDeleted?{onUserDeleted:this.onAccountDeleted}:{}}),this.principalService=new _pe({issuer:this.issuer,trustedIssuers:this.trustedIssuers,allowLocalhostIssuers:this.allowLocalhostIssuers,users:this.userStore,identities:e,sessions:this.sessionStore,ensureFirstAdminUser:()=>this.ensureFirstAdminUser(),getJwks:()=>this.getJwks()});let r=new m_(this.runtimeDatabase.db);this.accountService=new dpe({users:this.userStore,identities:e,credentials:r,sessions:this.sessionStore,refreshTokens:this.refreshTokenStore,passkeys:this.passkeyService,audit:this.auditStore,...this.isChannelTypeRegistered?{isChannelTypeRegistered:this.isChannelTypeRegistered}:{}}),this.administrationService=new Tpe({configuredAnchorKind:this.anchor,...this.resolveProfileDisplayName?{resolveProfileDisplayName:this.resolveProfileDisplayName}:{},users:this.userStore,identities:e,credentials:r,externalPeers:i,invitations:this.getInvitationService(),audit:this.auditStore,management:this.getUserManagementService(),...this.getChannelDescriptor?{getChannelDescriptor:this.getChannelDescriptor}:{},startPasskeyRegistration:(n,o,s)=>this.getPasskeySetupCoordinator().startRegistration(n,o,s)})}getUserStore(){return sx(this.userStore)}getIdentityReconciliationService(){return sx(this.identityReconciliationService)}getPasskeySetupCoordinator(){return sx(this.passkeySetupCoordinator)}getPrincipalService(){return sx(this.principalService)}getAdministrationService(){return sx(this.administrationService)}getAccountService(){return sx(this.accountService)}getInvitationService(){return sx(this.invitationService)}startInvitationDeliveryRecovery(){return this.startLifecycle(async()=>{await this.ensureStartedInternal(),await this.invitationDeliverySupervisor?.start()})}getInterfacePrincipalStore(){return sx(this.interfacePrincipalStore)}getAuditStore(){return sx(this.auditStore)}getAccountSettingsStore(){if(!this.accountSettingsEncryptionKey)return;return this.accountSettingsStore??=new mpe(this.runtimeDatabase.db,this.accountSettingsEncryptionKey),this.accountSettingsStore}hasPasskeyCredentials(){return this.startLifecycle(async()=>(await this.ensureStartedInternal(),this.passkeyService.hasCredentials()))}getSetupUrl(e=this.issuer){return this.setupFlow.getSetupUrl(e)}getJwks(){return this.startLifecycle(async()=>{await this.loadSigningKeys();let[e,t]=await Promise.all([this.keyStore.getPublicJwk(),this.a2aKeyStore.getPublicJwk()]);return{keys:[e,t]}})}getA2APrivateJwk(){return this.startLifecycle(()=>this.a2aKeyStore.getPrivateJwk())}async loadSigningKeys(){let e=await Promise.allSettled([this.keyStore.getPrivateJwk(),this.a2aKeyStore.getPrivateJwk()]);for(let t of e)if(t.status==="rejected")throw t.reason}getUserManagementService(){return sx(this.userManagementService)}async initializeInternal(){if(await this.ensureStartedInternal(),this.autoStartInvitationDeliveryRecovery)await this.invitationDeliverySupervisor?.start();if(await this.projectConfiguredBrainAnchor(),await this.loadSigningKeys(),this.logger?.debug("Auth service signing keys loaded"),this.issuesSetupLinks&&!await this.passkeyService.hasCredentials()){await this.setupFlow.ensureSetupToken();let e=this.getSetupUrl();if(e)if(kf(this.issuer))this.logger?.warn(`Passkey setup required: ${e}`);else this.logger?.warn("Passkey setup required. Ask through an Admin interface for the setup URL.")}await this.oauthEndpoints.startClientMaintenance()}async closeInternal(){let e=[];for(let t of[()=>this.oauthEndpoints.stopClientMaintenance(),()=>this.invitationDeliverySupervisor?.close()??Promise.resolve()])try{await t()}catch(i){e.push(i)}this.invitationDeliverySupervisor=void 0,this.accountSettingsStore=void 0,this.userStore=void 0,this.identityReconciliationService=void 0,this.passkeySetupCoordinator=void 0,this.userManagementService=void 0,this.principalService=void 0,this.administrationService=void 0,this.accountService=void 0,this.invitationService=void 0,this.interfacePrincipalStore=void 0,this.auditStore=void 0,this.firstAdminInitialization=void 0;try{await this.runtimeDatabase.stop()}catch(t){e.push(t)}if(e.length===1)throw e[0];if(e.length>1)throw AggregateError(e,"Auth runtime shutdown failed")}profileDisplayName(e){return p$(this.resolveProfileDisplayName,e,this.logger)}async projectConfiguredBrainAnchor(){let e=await this.getUserStore().getBrainAnchor(),t=await this.profileDisplayName(this.anchorProfileEntityId),i=t??e?.displayName??(this.anchor==="person"?"Admin":this.anchor==="team"?"Team":"Organization");await this.getUserStore().configureBrainAnchor({kind:this.anchor==="person"?"person":"collective",displayName:i,profileEntityId:this.anchorProfileEntityId,...t?{subjectDisplayName:t}:{}})}async ensureFirstAdminUser(){if(this.firstAdminInitialization)return this.firstAdminInitialization;let e=(async()=>{let t=await this.getUserStore().listUsers(),i=await this.getUserStore().ensureFirstAdminUser();if(await this.projectConfiguredBrainAnchor(),!t.some((r)=>r.id===i.id))await this.getAuditStore().append({action:"auth.user.created",targetType:"user",targetId:i.id,metadata:{role:i.role,status:i.status}});return i})();this.firstAdminInitialization=e;try{return await e}finally{if(this.firstAdminInitialization===e)this.firstAdminInitialization=void 0}}async resolveActiveSession(e){return await this.ensureStarted(),this.getPrincipalService().resolveActiveSession(e)}}function sx(e){if(!e)throw Error("Auth service has not been initialized");return e}import{AsyncLocalStorage as F$i}from"async_hooks";class Khe{admission=new XA;context=new F$i;active=new Set;closePromise;pendingCloses=0;backgroundOpen=!0;run(e){if(this.context.getStore()?.active)return this.admit(e).result;return this.closePromise=void 0,this.admission.run(()=>{if(this.pendingCloses===0)this.backgroundOpen=!0;return this.admit(e)}).then(({result:t})=>t)}runBackground(e){if(this.backgroundOpen)return this.admit(e).result;return Promise.resolve()}close(e){if(this.context.getStore()?.active)return Promise.reject(Error("Cannot close auth service from an active auth operation"));if(!this.closePromise)this.pendingCloses+=1,this.backgroundOpen=!1,this.closePromise=this.admission.run(async()=>{try{while(this.active.size>0)await Promise.all([...this.active]);await e()}finally{this.context.disable(),this.pendingCloses-=1}});return this.closePromise}admit(e){let t={active:!0},i=Promise.resolve().then(()=>this.context.run(t,e)),r=()=>{t.active=!1,this.active.delete(n)},n=i.then(r,r);return this.active.add(n),{result:i}}}var M$i="anchor-profile/anchor-profile";class JG{issuer;runtime;operations=new Khe;requestRouter;getInvitationDeliveryProvider;getChannelDescriptor;listChannelDescriptors;accountSettingsRegistry;logger;constructor(e){this.issuer=vy(e.issuer),this.getInvitationDeliveryProvider=e.getInvitationDeliveryProvider,this.getChannelDescriptor=e.getChannelDescriptor,this.listChannelDescriptors=e.listChannelDescriptors,this.accountSettingsRegistry=e.accountSettingsRegistry,this.logger=e.logger;let t=e.isChannelTypeRegistered??(e.getChannelDescriptor?(i)=>Boolean(e.getChannelDescriptor?.(i)):void 0);this.runtime=new Vhe({storageDir:e.storageDir,runBackgroundOperation:(i)=>this.operations.runBackground(i),...e.replica?{replica:e.replica}:{},issuer:this.issuer,trustedIssuers:new Set([this.issuer,...(e.trustedIssuers??[]).map((i)=>vy(i))]),allowLocalhostIssuers:e.allowLocalhostIssuers??kf(this.issuer),anchor:e.anchor??"person",anchorProfileEntityId:e.anchorProfileEntityId??M$i,...e.resolveProfileDisplayName?{resolveProfileDisplayName:e.resolveProfileDisplayName}:{},...e.resolveHomePath?{resolveHomePath:e.resolveHomePath}:{},...e.setupTokenTtlSeconds!==void 0?{setupTokenTtlSeconds:e.setupTokenTtlSeconds}:{},...e.issuesSetupLinks!==void 0?{issuesSetupLinks:e.issuesSetupLinks}:{},...e.getOnboardingDetails?{getOnboardingDetails:e.getOnboardingDetails}:{},...e.getInvitationDeliveryProvider?{getInvitationDeliveryProvider:e.getInvitationDeliveryProvider}:{},...e.getChannelDescriptor?{getChannelDescriptor:e.getChannelDescriptor}:{},...t?{isChannelTypeRegistered:t}:{},...e.autoStartInvitationDeliveryRecovery!==void 0?{autoStartInvitationDeliveryRecovery:e.autoStartInvitationDeliveryRecovery}:{},...e.invitationDeliveryRecoveryIntervalMs!==void 0?{invitationDeliveryRecoveryIntervalMs:e.invitationDeliveryRecoveryIntervalMs}:{},...e.invitationDeliveryRecoveryStaleMs!==void 0?{invitationDeliveryRecoveryStaleMs:e.invitationDeliveryRecoveryStaleMs}:{},...e.oauthClientMaintenanceIntervalMs!==void 0?{oauthClientMaintenanceIntervalMs:e.oauthClientMaintenanceIntervalMs}:{},...e.clientMetadataDocumentResolver?{clientMetadataDocumentResolver:e.clientMetadataDocumentResolver}:{},...e.accountSettingsEncryptionKey?{accountSettingsEncryptionKey:e.accountSettingsEncryptionKey}:{},...e.onAccountDeleted?{onAccountDeleted:e.onAccountDeleted}:{},...e.logger?{logger:e.logger}:{}}),this.requestRouter=new upe({setupFlow:this.runtime.setupFlow,oauthEndpoints:this.runtime.oauthEndpoints,webauthnEndpoints:this.runtime.webauthnEndpoints,handleAdminRequest:(i)=>this.handleAdminRequest(i),handleAccountRequest:(i)=>this.handleAccountRequest(i),revokeSession:async(i)=>{await this.runtime.sessionStore.revokeSessionFromRequest(i)},getAuthorizationServerMetadata:(i)=>this.getAuthorizationServerMetadata(i),getProtectedResourceMetadata:(i,r)=>this.getProtectedResourceMetadata(i,r),getJwks:()=>this.getJwks()})}getIssuer(){return this.issuer}initialize(){return this.operations.run(()=>this.runtime.initialize())}startInvitationDeliveryRecovery(){return this.operations.run(()=>this.runtime.startInvitationDeliveryRecovery())}close(){return this.operations.close(()=>this.runtime.close())}async initializeConfiguredInterfacePrincipals(e){return this.operations.run(async()=>{await this.initialize();let t=this.runtime.getInterfacePrincipalStore();return await t.seedConfigOnce(e),t.listActiveState()})}async resolveInterfacePrincipal(e,t){return this.operations.run(async()=>(await this.initialize(),this.runtime.getInterfacePrincipalStore().resolve(e,t)))}getAccountSettingsBackend(){return this.runtime.getAccountSettingsStore()}hasPasskeyCredentials(){return this.operations.run(()=>this.runtime.hasPasskeyCredentials())}async revokePasskey(e,t={}){return this.operations.run(async()=>{await this.runtime.ensureStarted(),await this.runtime.getAdministrationService().revokePasskey(e,t)})}getJwks(){return this.operations.run(()=>this.runtime.getJwks())}async getA2ASigningKey(){return this.operations.run(async()=>{let e=await this.runtime.getA2APrivateJwk();return{privateJwk:e,keyId:Dl(this.issuer,`/.well-known/jwks.json#${e.kid}`)}})}async grantA2APeerTrust(e,t={}){return this.operations.run(async()=>(await this.initialize(),this.runtime.peerTrustStore.grant(e,t)))}async getA2APeerTrust(e){return this.operations.run(async()=>(await this.initialize(),this.runtime.peerTrustStore.get(e)))}async revokeA2APeerTrust(e,t={}){return this.operations.run(async()=>(await this.initialize(),this.runtime.peerTrustStore.revoke(e,t)))}getAuthorizationServerMetadata(e=this.issuer){let t=vy(e);return{issuer:t,authorization_endpoint:Dl(t,"/authorize"),token_endpoint:Dl(t,"/token"),registration_endpoint:Dl(t,"/register"),revocation_endpoint:Dl(t,"/revoke"),jwks_uri:Dl(t,"/.well-known/jwks.json"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"],token_endpoint_auth_methods_supported:["none","client_secret_basic","client_secret_post"],client_id_metadata_document_supported:!0,scopes_supported:["openid","profile","email","offline_access","mcp"],subject_types_supported:["public"],id_token_signing_alg_values_supported:["ES256"]}}getProtectedResourceMetadata(e,t=this.issuer){return{resource:e,authorization_servers:[vy(t)],bearer_methods_supported:["header"],resource_signing_alg_values_supported:["ES256"],scopes_supported:["mcp"]}}async registerClient(e){return this.operations.run(async()=>(await this.initialize(),this.runtime.clientStore.registerClient(e)))}async getRegisteredClient(e){return this.operations.run(async()=>(await this.initialize(),this.runtime.clientStore.getClient(e)))}async createUser(e,t={}){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().createUser(e,t)))}async cancelInvitation(e,t){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().cancelInvitation(e,t)))}async confirmManualInvitationDelivery(e,t,i){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().confirmManualInvitationDelivery(e,t,i)))}async createInvitation(e,t){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().createInvitation(e,t)))}async resendInvitation(e,t){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().resendInvitation(e,t)))}async inviteExternalPeerPerson(e,t){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().inviteExternalPeerPerson(e,t)))}async linkExternalPeer(e,t){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().linkExternalPeer(e,t)))}async unlinkExternalPeer(e,t){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().unlinkExternalPeer(e,t)))}async getBrainAnchor(){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().getBrainAnchor()))}async listUsers(){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().listUsers()))}async listAdminUsers(){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().listAdminUsers()))}async listInvitationChannels(){return this.operations.run(async()=>{await this.runtime.ensureStarted();let e=this.listChannelDescriptors?.()??[];return await Promise.all(e.map(async(i)=>{let r=[];try{let n=this.getInvitationDeliveryProvider?.(i.type);if(n&&await n.isAvailable())r.push("automatic")}catch{}if(i.manualDelivery===!0)r.push("manual");return{type:i.type,displayName:i.displayName,subjectLabel:i.subjectLabel,...i.subjectPattern?{subjectPattern:i.subjectPattern}:{},deliveryModes:r}}))})}async reconcileIdentityProposals(e){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getIdentityReconciliationService().reconcile(e)))}async listPersonExternalPeers(e){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().listPersonExternalPeers(e)))}async listUserIdentities(e){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().listUserIdentities(e)))}async listUserPasskeys(e){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().listUserPasskeys(e)))}async updateUserRole(e,t,i={}){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().updateUserRole(e,t,i)))}async updateUserStatus(e,t,i={}){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().updateUserStatus(e,t,i)))}suspendUser(e,t={}){return this.updateUserStatus(e,"suspended",t)}async deleteSuspendedUser(e,t={}){return this.operations.run(async()=>{await this.runtime.ensureStarted(),await this.runtime.getAdministrationService().deleteSuspendedUser(e,t)})}async revokeUserSessionsAndRefreshTokens(e,t={}){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().revokeUserGrants(e,t)))}async attachIdentity(e,t={}){return this.operations.run(async()=>{await this.runtime.ensureStarted();let i=this.validateChannelSubject(e.type,e.subject);return this.runtime.getAdministrationService().attachIdentity({...e,...i&&!e.deliverySubject?{deliverySubject:e.subject}:{}},t)})}async detachIdentity(e,t={}){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().detachIdentity(e,t)))}async recordAuditEvent(e){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAuditStore().append(e)))}async listAuditEvents(){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAdministrationService().listAuditEvents()))}async queryAuditEvents(e){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getAuditStore().query(e)))}async resolveActorPrincipal(e){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getPrincipalService().resolveActor(e)))}async resolveIdentityAccess(e){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getPrincipalService().resolveIdentityAccess(e)))}async createAuthSession(e,t={}){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getPrincipalService().createSession(e,t)))}async getAuthSession(e){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getPrincipalService().getSession(e)))}async resolveSession(e){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getPrincipalService().resolveSession(e)))}createAuthLoginResponse(e){return a_(e)}async verifyBearerToken(e,t={}){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getPrincipalService().verifyBearerToken(e,t)))}async resolveBearerGrant(e,t={}){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getPrincipalService().resolveBearerGrant(e,t)))}async resolveBearerToken(e,t={}){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getPrincipalService().resolveBearerToken(e,t)))}getSetupUrl(e=this.issuer){return this.runtime.setupFlow.getSetupUrl(e)}async startPasskeyRegistrationForUser(e,t={},i){return this.operations.run(async()=>{if(await this.runtime.ensureStarted(),i)this.validateChannelSubject(i.type,i.subject);return this.runtime.getPasskeySetupCoordinator().startRegistration(e,t,i)})}async getPasskeySetupRequired(e=this.issuer){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getPasskeySetupCoordinator().getPasskeySetupRequired(e)))}async getPasskeySetupRequiredForDelivery(e=this.issuer){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getPasskeySetupCoordinator().getPasskeySetupRequiredForDelivery(e)))}async hasSetupEmailDelivery(e,t){return this.operations.run(async()=>(await this.runtime.ensureStarted(),this.runtime.getPasskeySetupCoordinator().hasSetupEmailDelivery(e,t)))}async recordSetupEmailDelivery(e,t,i={}){return this.operations.run(async()=>{await this.runtime.ensureStarted(),await this.runtime.getPasskeySetupCoordinator().recordSetupEmailDelivery(e,t,i)})}async handleRequest(e){return this.operations.run(async()=>{await this.initialize();let t;try{t=this.resolveRequestIssuer(e)}catch(i){return this.logger?.warn("Rejected OAuth request from untrusted issuer",{error:Ee(i)}),new Response("Untrusted OAuth issuer",{status:400})}return this.requestRouter.handle(e,t)})}async handleWellKnownRequest(e){return this.handleRequest(e)}handleAccountRequest(e){return RHe(e,{resolveSession:async(t)=>{let i=await this.runtime.resolveActiveSession(t);return i?{userId:i.user.id,sessionId:i.session.id}:void 0},account:this.runtime.getAccountService(),...this.accountSettingsRegistry?{accountSettings:this.accountSettingsRegistry}:{}})}handleAdminRequest(e){return jHe(e,{resolveSession:(t)=>this.resolveSession(t),listUsers:()=>this.listUsers(),getBrainAnchor:()=>this.getBrainAnchor(),listAuditEvents:()=>this.listAuditEvents(),listInvitationChannels:()=>this.listInvitationChannels(),listAdminUsers:()=>this.listAdminUsers(),reconcileIdentityProposals:(t)=>this.reconcileIdentityProposals(t),listPersonExternalPeers:(t)=>this.listPersonExternalPeers(t),listUserIdentities:(t)=>this.listUserIdentities(t),listUserPasskeys:(t)=>this.listUserPasskeys(t),cancelInvitation:(t,i)=>this.cancelInvitation(t,{actorUserId:i}),confirmManualInvitationDelivery:(t,i,r)=>this.confirmManualInvitationDelivery(t,i,{actorUserId:r}),createInvitation:(t,i)=>this.createInvitation(t,{actorUserId:i}),createUser:(t,i)=>this.createUser(t,{actorUserId:i}),inviteExternalPeerPerson:(t,i)=>this.inviteExternalPeerPerson(t,{actorUserId:i}),resendInvitation:(t,i)=>this.resendInvitation(t,{actorUserId:i}),linkExternalPeer:(t,i)=>this.linkExternalPeer(t,{actorUserId:i}),unlinkExternalPeer:(t,i)=>this.unlinkExternalPeer(t,{actorUserId:i}),updateUserRole:(t,i,r)=>this.updateUserRole(t,i,{actorUserId:r}),updateUserStatus:(t,i,r)=>this.updateUserStatus(t,i,{actorUserId:r}),deleteUser:(t,i)=>this.deleteSuspendedUser(t,{actorUserId:i}),attachIdentity:async(t,i)=>BQe(await this.attachIdentity(t,{actorUserId:i}),t.userId,this.getChannelDescriptor),detachIdentity:async(t,i)=>{let r=await this.detachIdentity(t,{actorUserId:i}),n=await this.runtime.getUserStore().getUserByPersonId(r.personId);if(!n)throw Error("Identity person has no auth user");return BQe(r,n.id,this.getChannelDescriptor)},revokePasskey:(t,i)=>this.revokePasskey(t,{actorUserId:i}),startPasskeyRegistration:(t,i,r)=>this.startPasskeyRegistrationForUser(t,{actorUserId:i},r),revokeUserSessionsAndRefreshTokens:(t,i)=>this.revokeUserSessionsAndRefreshTokens(t,{actorUserId:i})})}validateChannelSubject(e,t){let i=this.getChannelDescriptor?.(e);if(i?.subjectPattern&&!new RegExp(i.subjectPattern.source,i.subjectPattern.flags).test(t.trim()))throw Error(`Identity subject is invalid for channel: "${e}"`);return i}resolveRequestIssuer(e){return this.runtime.getPrincipalService().resolveRequestIssuer(e)}}function BQe(e,t,i){let r=e.label?.trim(),n=e.deliverySubject?.trim(),o=r&&r.length>0&&r!==i?.(e.type)?.subjectLabel?r:n;return{id:e.id,personId:e.personId,userId:t,type:e.type,visibility:e.visibility,evidence:e.evidence.map((s)=>({sourceKind:s.sourceKind,...s.sourceId?{sourceId:s.sourceId}:{},assurance:s.assurance,...s.verifiedAt!==null?{verifiedAt:s.verifiedAt}:{}})),...e.issuer?{issuer:e.issuer}:{},...o?{label:o}:{},...e.verifiedAt!==null?{verifiedAt:e.verifiedAt}:{},...e.revokedAt!==null?{revokedAt:e.revokedAt}:{},createdAt:e.createdAt}}import{join as N$i}from"path";var CQe={name:"@brains/auth-service",license:"AGPL-3.0-only",version:"0.2.0-alpha.699",description:"Embedded OAuth/OIDC authentication service for brain users",dependencies:{"@brains/contracts":"workspace:*","@brains/db":"workspace:*","@brains/notifications":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*","@libsql/client":"^0.17.4","@simplewebauthn/server":"^13.3.1","drizzle-orm":"^0.45.2",jose:"^6.2.3"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/templates":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0","@types/node":"^24.13.3","drizzle-kit":"^0.31.10",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./env-schema":"./src/env-schema.ts","./admin-contracts":"./src/admin-contracts.ts"},files:["src"],main:"./src/index.ts",private:!0,scripts:{"db:generate":"drizzle-kit generate","db:studio":"drizzle-kit studio",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"};var L$i=l.string().email(),z$i=l.object({syncUrl:l.string().url().regex(/^(?:libsql|https):\/\//),authToken:l.string().min(1),syncIntervalMs:l.number().int().positive().optional()}).strict();var j$i=l.object({issuer:l.string().optional(),anchor:l.enum(_Qe).default("person"),trustedIssuers:l.array(l.string()).default([]),allowLocalhostIssuers:l.boolean().optional(),storageDir:l.string().optional(),replica:z$i.optional(),setupTokenTtlSeconds:l.number().int().positive().default(eP),setupEmail:L$i.optional(),accountSettingsEncryptionKey:l.string().min(32).optional()});function U$i(e){return e??N$i(".","data","auth")}async function DQe(e){let t=e.identity.get().purpose.trim(),i=(await e.identity.getAppInfo().catch(()=>{return}))?.interactions??[],r=(a)=>i.find((c)=>c.id===a&&c.href.startsWith("/"))?.href,n=r(eH),o=r(XG),s=o&&r(eB)?TQe(o):void 0;return{...t?{purpose:t}:{},links:{...n?{chat:n}:{},...o?{studio:o}:{},...s?{aiTools:s}:{}}}}async function IQe(e,t){if(t==="anchor-profile/anchor-profile"){let o=e.identity.getProfile().name.trim();return o&&o!=="Unknown"?o:void 0}let i=t.indexOf("/");if(i<=0||i===t.length-1)return;let n=(await e.entityService.getEntity({entityType:t.slice(0,i),id:t.slice(i+1),visibilityScope:Pt("profile display name for auth admin")}))?.metadata.name;return typeof n==="string"?n:void 0}function q$i(e){return PQe(e,{activeId:"auth-service",permissionLevel:"admin",hasActiveSession:!0}).find((t)=>t.id==="studio")?.href??"/"}class Yhe extends ev{service;unbindAccountSettings;unbindAuth;unsubscribePrincipalResolver;constructor(e={}){super("auth-service",CQe,e,j$i)}async onRegister(e){await super.onRegister(e);let t=this.config.issuer??(e.preferLocalUrls?e.localSiteUrl??e.siteUrl:e.siteUrl??e.localSiteUrl);this.service=new JG({storageDir:U$i(this.config.storageDir),...this.config.replica?{replica:this.config.replica}:{},anchor:this.config.anchor,anchorProfileEntityId:"anchor-profile/anchor-profile",resolveProfileDisplayName:(n)=>IQe(e,n),...t?{issuer:t}:{},trustedIssuers:this.config.trustedIssuers,...this.config.allowLocalhostIssuers!==void 0?{allowLocalhostIssuers:this.config.allowLocalhostIssuers}:{},setupTokenTtlSeconds:this.config.setupTokenTtlSeconds,resolveHomePath:()=>q$i(e.webRoutes.getRoutes()),...this.config.accountSettingsEncryptionKey?{accountSettingsEncryptionKey:this.config.accountSettingsEncryptionKey}:{},onAccountDeleted:(n)=>{e.accountSettings.accountDeleted(n)},accountSettingsRegistry:e.accountSettings,autoStartInvitationDeliveryRecovery:!1,issuesSetupLinks:!e.executionOnly,getInvitationDeliveryProvider:(n)=>e.channels.getDeliveryProvider(n),getChannelDescriptor:(n)=>e.channels.getDescriptor(n),listChannelDescriptors:()=>e.channels.listDescriptors(),isChannelTypeRegistered:(n)=>Boolean(e.channels.getDescriptor(n)),getOnboardingDetails:()=>DQe(e),logger:e.logger}),await this.service.initialize();let i=this.service.getAccountSettingsBackend();if(i)this.unbindAccountSettings=e.accountSettings.bindBackend(i);let r=await this.service.initializeConfiguredInterfacePrincipals(e.permissions.getConfiguredPrincipalSeeds());e.permissions.replaceRuntimePrincipalState(r),this.unbindAuth=e.auth.bindBackend(this.service),this.unsubscribePrincipalResolver=e.messaging.answer(QG,async({actor:n})=>{let o=await this.getService().resolveActorPrincipal(n);return{principal:o?{userId:o.userId,personId:o.personId,...o.canonicalId?{canonicalId:o.canonicalId}:{},displayName:o.displayName,permissionLevel:o.permissionLevel}:null}})}async onRegistrationComplete(){await this.getService().startInvitationDeliveryRecovery()}async onReady(e){await this.requestSetupEmailIfNeeded(e)}async onShutdown(){this.unsubscribePrincipalResolver?.(),this.unsubscribePrincipalResolver=void 0,this.unbindAuth?.(),this.unbindAuth=void 0,this.unbindAccountSettings?.(),this.unbindAccountSettings=void 0,await this.service?.close(),this.service=void 0}async getTools(){let e=await this.getService().hasPasskeyCredentials();return[{name:`${this.id}_get_passkey_setup_url`,description:"Get the first-passkey setup URL when passkey setup is required. Admin-only.",inputSchema:{},visibility:"admin",...e?{agentTool:!1}:{},handler:async()=>{let t=this.getService();if(await t.hasPasskeyCredentials())return{success:!0,data:{status:"complete"}};let i=await t.getPasskeySetupRequired();if(i)return{success:!0,data:{status:"setup_required",setupUrl:i.setupUrl,expiresAt:i.expiresAt}};return{success:!0,data:{status:"unavailable",reason:"Passkey setup URL is not available."}}},sideEffects:"none"}]}getWebRoutes(){let e=(t)=>this.getService().handleRequest(t);return[{path:"/.well-known/oauth-authorization-server",method:"GET",public:!0,handler:e},{path:"/.well-known/oauth-authorization-server",method:"OPTIONS",public:!0,handler:e},{path:"/.well-known/jwks.json",method:"GET",public:!0,handler:e},{path:"/.well-known/jwks.json",method:"OPTIONS",public:!0,handler:e},{path:"/.well-known/oauth-protected-resource",method:"GET",public:!0,handler:e},{path:"/.well-known/oauth-protected-resource",method:"OPTIONS",public:!0,handler:e},{path:"/setup",method:"GET",public:!0,handler:e},{path:"/login",method:"GET",public:!0,handler:e},{path:"/logout",method:"GET",public:!0,handler:e},{path:"/logout",method:"POST",public:!0,handler:e},{path:"/authorize",method:"GET",public:!0,handler:e},{path:"/authorize",method:"POST",public:!0,handler:e},{path:"/register",method:"POST",public:!0,handler:e},{path:"/register",method:"OPTIONS",public:!0,handler:e},{path:"/token",method:"POST",public:!0,handler:e},{path:"/token",method:"OPTIONS",public:!0,handler:e},{path:"/revoke",method:"POST",public:!0,handler:e},{path:"/revoke",method:"OPTIONS",public:!0,handler:e},{path:"/auth/account",method:"GET",public:!0,handler:e},{path:"/auth/account/mutations",method:"POST",public:!0,handler:e},{path:"/auth/account/plugin-settings",method:"POST",public:!0,handler:e},{path:"/auth/account/passkeys/options",method:"POST",public:!0,handler:e},{path:"/auth/account/passkeys/verify",method:"POST",public:!0,handler:e},{path:"/auth/admin/anchor",method:"GET",public:!0,handler:e},{path:"/auth/admin/users",method:"GET",public:!0,handler:e},{path:"/auth/admin/audit",method:"GET",public:!0,handler:e},{path:"/auth/admin/channels",method:"GET",public:!0,handler:e},{path:"/auth/admin/mutations",method:"POST",public:!0,handler:e},{path:"/auth/admin/reconciliation",method:"POST",public:!0,handler:e},{path:"/webauthn/register/options",method:"POST",public:!0,handler:e},{path:"/webauthn/register/verify",method:"POST",public:!0,handler:e},{path:"/webauthn/auth/options",method:"POST",public:!0,handler:e},{path:"/webauthn/auth/verify",method:"POST",public:!0,handler:e}]}getService(){if(!this.service)throw Error("AuthServicePlugin has not been registered");return this.service}async requestSetupEmailIfNeeded(e){if(!this.config.setupEmail)return;let t=this.getService();if(await t.hasPasskeyCredentials())return;let i=await t.getPasskeySetupRequiredForDelivery();if(!i)return;let r=this.config.setupEmail;if(await t.hasSetupEmailDelivery(i.setupTokenId,r))return;let n=this.config.anchor==="person"?await IQe(e,"anchor-profile/anchor-profile"):void 0,{links:o}=await DQe(e),s=f$({kind:"anchor-setup",setupUrl:i.setupUrl,expiresAt:i.expiresAt,links:o,...n?{greetingName:n}:{}}),a=await e.messaging.request(Xk,{recipient:{type:"email",address:r},title:s.subject,body:s.text,html:s.html,sensitivity:"secret"});if(a.status!=="answered"||a.data.status!=="sent"){e.logger.warn("Passkey setup email delivery was not confirmed");return}await t.recordSetupEmailDelivery(i.setupTokenId,r,a.data.deliveryId?{deliveryId:a.data.deliveryId}:{})}}function Jhe(e={}){return new Yhe(e)}var Qhe=l.object({defaultPrompt:l.string().default("Write a blog post about my recent work and insights"),paginate:l.boolean().default(!0),pageSize:l.number().default(10)});var tH=l.enum(["generating","draft","queued","published","failed"]),ax=l.object({title:l.string(),slug:l.string().optional(),status:tH,publishedAt:l.string().datetime().optional(),excerpt:l.string(),author:l.string(),coverImageId:l.string().optional(),ogImageId:l.string().optional(),seriesName:l.string().optional(),seriesIndex:l.number().optional(),ogImage:l.string().url().optional(),canonicalUrl:l.string().url().optional()}),iH=ax.extend({slug:l.string(),error:l.string().optional().meta({studioWidget:"hidden"}),authoredSlug:l.boolean().optional().meta({studioWidget:"hidden"})}),tB=Mi.extend({entityType:l.literal("post"),metadata:iH}),tP=tB.extend({frontmatter:ax,body:l.string(),coverImageUrl:l.string().optional()}),$$i=tP.extend({url:l.string().optional(),typeLabel:l.string().optional(),listUrl:l.string().optional(),listLabel:l.string().optional(),seriesUrl:l.string().optional(),coverImageUrl:l.string().optional(),ogImageUrl:l.string().optional(),coverImageWidth:l.number().optional(),coverImageHeight:l.number().optional(),coverImageSrcset:l.string().optional(),coverImageSizes:l.string().optional()}),BFo=tP.extend({url:l.string(),typeLabel:l.string(),listUrl:l.string(),listLabel:l.string(),seriesUrl:l.string().optional(),coverImageUrl:l.string().optional(),ogImageUrl:l.string().optional(),coverImageWidth:l.number().optional(),coverImageHeight:l.number().optional(),coverImageSrcset:l.string().optional(),coverImageSizes:l.string().optional()});function RQe(e){let t=e.authoredSlug===!0;return Object.fromEntries(Object.entries({title:e.title,...t&&{slug:e.slug},status:e.status,publishedAt:e.publishedAt,excerpt:e.excerpt,author:e.author,coverImageId:e.coverImageId,ogImageId:e.ogImageId,seriesName:e.seriesName,seriesIndex:e.seriesIndex,ogImage:e.ogImage,canonicalUrl:e.canonicalUrl,...!t&&{slug:e.slug},error:e.error}).filter(([,i])=>i!==void 0))}function FQe(e){return kr(RQe(e.metadata),e.content)}var MQe={decode:({content:e,frontmatter:t})=>{let i=ax.parse(t),r=t.error;return{content:e,metadata:{...i,slug:i.slug??jt(i.title),...i.slug!==void 0&&{authoredSlug:!0},...typeof r==="string"&&{error:r}}}},encode:({content:e,metadata:t})=>({content:Sr(e).content,frontmatter:RQe(t)})};function Xhe(e){let{fields:t,body:i}=Un(e),r=Object.keys(Sr(e.content).frontmatter).length>0;return tP.parse({...e,content:r?e.content:FQe(e),frontmatter:ax.parse(t),body:i})}function rH(e){return{content:"",metadata:{title:e.title,slug:e.id,authoredSlug:!0,status:"generating",excerpt:"",author:"AI"}}}var wu=l.string().nullable().default(null),nH=l.number().nullable().default(null),G$i=l.object({title:l.string(),status:tH,publishedAt:wu,seriesName:wu,seriesIndex:nH,slug:l.string(),error:wu}),H$i=l.object({title:l.string(),slug:wu,status:tH,publishedAt:wu,excerpt:l.string(),author:l.string(),coverImageId:wu,ogImageId:wu,seriesName:wu,seriesIndex:nH,ogImage:wu,canonicalUrl:wu}),Su=l.object({...If("post",G$i,H$i),body:l.string(),...du,seriesUrl:wu,coverImageUrl:wu,ogImageUrl:wu,coverImageWidth:nH,coverImageHeight:nH,coverImageSrcset:wu,coverImageSizes:wu}),lh=Su.extend(x0);var W$i=1000,Z$i=100;function OQe(e){let t=Xhe(e),i=t.frontmatter.seriesName,r=i?`/series/${jt(i)}`:void 0;return{...t,...r&&{seriesUrl:r}}}async function V$i(e,t,i){return(await t.list(e,{limit:W$i,sort:[{field:"seriesIndex",direction:"asc"}]})).filter((n)=>n.metadata.seriesName===i).slice(0,Z$i).map(OQe)}function NQe(e){return Es({id:"entities",name:"Blog Entity DataSource",description:"Fetches and transforms blog post entities for rendering",entity:e,defaultSort:[{field:"publishedAt",direction:"desc"}],defaultLimit:10,enableNavigation:!0,transform:OQe,list:(t,i,r)=>({posts:t.map((n)=>Su.parse(n)),pagination:i,baseUrl:r.baseUrl??null}),detail:async({item:t,navigation:i,entities:r})=>({post:t,prevPost:i?.prev??null,nextPost:i?.next??null,seriesPosts:t.frontmatter.seriesName?await V$i(e,r,t.frontmatter.seriesName):null})})}function oH(e,{environment:t}){let{metadata:i}=e;if(t==="production"&&(i.status!=="published"||!i.publishedAt))return null;return{title:i.title,slug:i.slug,description:i.excerpt,content:e.content,author:i.author,publishedAt:i.publishedAt??e.created,...i.seriesName&&{category:i.seriesName}}}var efe={path:"feed.xml",title:"Blog",description:"Latest blog posts",toItem:oH};var K$i=l.object({siteUrl:l.url(),title:l.string(),description:l.string(),language:l.string().optional(),copyright:l.string().optional()});function jQe(e){return Es({id:"rss",name:"Blog RSS Feed DataSource",description:"Generates RSS 2.0 feed XML from published blog posts",fetch:async(t,i)=>{let r=K$i.parse(t),o=(await i.list(e,{limit:1000,sort:[{field:"publishedAt",direction:"desc"}]})).flatMap((a)=>{let c=oH(a,{environment:"production"});return c?[LQe.parse(c)]:[]}),s=r.siteUrl.replace(/\/+$/u,"");return{xml:zQe(o,{title:r.title,description:r.description,link:r.siteUrl,selfLink:`${r.siteUrl}/feed.xml`,language:r.language??"en-us",copyright:r.copyright},(a)=>`${s}/posts/${a.slug}`)}}})}var Y$i=zt({type:"image",purpose:"An image a post shows as its cover.",metadata:tv});function J$i(e){let t=/^data:([^;,]+);base64,(.*)$/.exec(e.trim());if(!t?.[1]||!t[2])throw Error("Cover image must be a base64 data URL");return{data:Buffer.from(t[2],"base64"),mimeType:t[1]}}async function Q$i({entity:e,entities:t,uploadBlob:i}){let r=e.metadata.coverImageId;if(!r)return;let n=await t.get(Y$i,r);if(!n)return;let o=await i(J$i(n.content)),{alt:s,width:a,height:c}=n.metadata;return{blob:o,...s&&{alt:s},width:a,height:c}}async function UQe(e){let{entity:t,config:i,topics:r,pageUrl:n}=e,{metadata:o}=t,s=await Q$i(e),a=o.canonicalUrl??n;return{$type:"ai.rizom.brain.post",title:o.title,summary:o.excerpt,body:t.content,format:"text/markdown",...i.brainDid&&{brainDid:i.brainDid},...i.anchorDid&&{anchorDid:i.anchorDid},...a&&{canonicalUrl:a},...r&&r.length>0&&{topics:[...r]},...s&&{coverImage:s},...o.seriesName&&{series:o.seriesName},...o.seriesIndex!==void 0&&{seriesIndex:o.seriesIndex},sourceEntityType:"post",sourceEntityId:t.id,createdAt:t.created,...o.publishedAt&&{publishedAt:o.publishedAt}}}var tfe={lexicon:Oa["ai.rizom.brain.post"],validate:!1,isPublishable:(e)=>e.metadata.status==="published",buildRecord:UQe};import{createElement as sge}from"react";import{renderToStaticMarkup as etr}from"react-dom/server";import{join as qxe,relative as Ner,sep as Ler}from"path";import{promises as ost}from"fs";var xo=Al(qle(),1),qQe=xo.default,QFo=xo.default.stringify,XFo=xo.default.fromJSON,eMo=xo.default.plugin,tMo=xo.default.parse,iMo=xo.default.list,rMo=xo.default.document,nMo=xo.default.comment,oMo=xo.default.atRule,sMo=xo.default.rule,aMo=xo.default.decl,cMo=xo.default.root,lMo=xo.default.CssSyntaxError,uMo=xo.default.Declaration,dMo=xo.default.Container,pMo=xo.default.Processor,mMo=xo.default.Document,hMo=xo.default.Comment,fMo=xo.default.Warning,xMo=xo.default.AtRule,gMo=xo.default.Result,yMo=xo.default.Input,bMo=xo.default.Rule,EMo=xo.default.Root,AMo=xo.default.Node;var Xot=Al(HQe(),1);var e5=Al(Dit(),1);import*as X8 from"module";import{pathToFileURL as EQi}from"url";import{isBuiltin as vQi}from"module";var Pit=Al(_it(),1);import{createRequire as Tit}from"module";function QZi(e){throw e}var XZi=(e)=>import(e),Lfe;function eVi(...e){if(!Lfe)Lfe=Tit(import.meta.url)("../dist/babel.cjs");return Lfe(...e)}function Rit(e,t={}){if(!t.transform)t={...t,transform:eVi};return Pit.default(e,t,{onError:QZi,nativeImport:XZi,createRequire:Tit})}import Pxe from"fs";import Sot from"fs/promises";import OP from"path";import{pathToFileURL as eot}from"url";var xH={inherit:"inherit",current:"currentcolor",transparent:"transparent",black:"#000",white:"#fff",slate:{50:"oklch(98.4% 0.003 247.858)",100:"oklch(96.8% 0.007 247.896)",200:"oklch(92.9% 0.013 255.508)",300:"oklch(86.9% 0.022 252.894)",400:"oklch(70.4% 0.04 256.788)",500:"oklch(55.4% 0.046 257.417)",600:"oklch(44.6% 0.043 257.281)",700:"oklch(37.2% 0.044 257.287)",800:"oklch(27.9% 0.041 260.031)",900:"oklch(20.8% 0.042 265.755)",950:"oklch(12.9% 0.042 264.695)"},gray:{50:"oklch(98.5% 0.002 247.839)",100:"oklch(96.7% 0.003 264.542)",200:"oklch(92.8% 0.006 264.531)",300:"oklch(87.2% 0.01 258.338)",400:"oklch(70.7% 0.022 261.325)",500:"oklch(55.1% 0.027 264.364)",600:"oklch(44.6% 0.03 256.802)",700:"oklch(37.3% 0.034 259.733)",800:"oklch(27.8% 0.033 256.848)",900:"oklch(21% 0.034 264.665)",950:"oklch(13% 0.028 261.692)"},zinc:{50:"oklch(98.5% 0 0)",100:"oklch(96.7% 0.001 286.375)",200:"oklch(92% 0.004 286.32)",300:"oklch(87.1% 0.006 286.286)",400:"oklch(70.5% 0.015 286.067)",500:"oklch(55.2% 0.016 285.938)",600:"oklch(44.2% 0.017 285.786)",700:"oklch(37% 0.013 285.805)",800:"oklch(27.4% 0.006 286.033)",900:"oklch(21% 0.006 285.885)",950:"oklch(14.1% 0.005 285.823)"},neutral:{50:"oklch(98.5% 0 0)",100:"oklch(97% 0 0)",200:"oklch(92.2% 0 0)",300:"oklch(87% 0 0)",400:"oklch(70.8% 0 0)",500:"oklch(55.6% 0 0)",600:"oklch(43.9% 0 0)",700:"oklch(37.1% 0 0)",800:"oklch(26.9% 0 0)",900:"oklch(20.5% 0 0)",950:"oklch(14.5% 0 0)"},stone:{50:"oklch(98.5% 0.001 106.423)",100:"oklch(97% 0.001 106.424)",200:"oklch(92.3% 0.003 48.717)",300:"oklch(86.9% 0.005 56.366)",400:"oklch(70.9% 0.01 56.259)",500:"oklch(55.3% 0.013 58.071)",600:"oklch(44.4% 0.011 73.639)",700:"oklch(37.4% 0.01 67.558)",800:"oklch(26.8% 0.007 34.298)",900:"oklch(21.6% 0.006 56.043)",950:"oklch(14.7% 0.004 49.25)"},mauve:{50:"oklch(98.5% 0 0)",100:"oklch(96% 0.003 325.6)",200:"oklch(92.2% 0.005 325.62)",300:"oklch(86.5% 0.012 325.68)",400:"oklch(71.1% 0.019 323.02)",500:"oklch(54.2% 0.034 322.5)",600:"oklch(43.5% 0.029 321.78)",700:"oklch(36.4% 0.029 323.89)",800:"oklch(26.3% 0.024 320.12)",900:"oklch(21.2% 0.019 322.12)",950:"oklch(14.5% 0.008 326)"},olive:{50:"oklch(98.8% 0.003 106.5)",100:"oklch(96.6% 0.005 106.5)",200:"oklch(93% 0.007 106.5)",300:"oklch(88% 0.011 106.6)",400:"oklch(73.7% 0.021 106.9)",500:"oklch(58% 0.031 107.3)",600:"oklch(46.6% 0.025 107.3)",700:"oklch(39.4% 0.023 107.4)",800:"oklch(28.6% 0.016 107.4)",900:"oklch(22.8% 0.013 107.4)",950:"oklch(15.3% 0.006 107.1)"},mist:{50:"oklch(98.7% 0.002 197.1)",100:"oklch(96.3% 0.002 197.1)",200:"oklch(92.5% 0.005 214.3)",300:"oklch(87.2% 0.007 219.6)",400:"oklch(72.3% 0.014 214.4)",500:"oklch(56% 0.021 213.5)",600:"oklch(45% 0.017 213.2)",700:"oklch(37.8% 0.015 216)",800:"oklch(27.5% 0.011 216.9)",900:"oklch(21.8% 0.008 223.9)",950:"oklch(14.8% 0.004 228.8)"},taupe:{50:"oklch(98.6% 0.002 67.8)",100:"oklch(96% 0.002 17.2)",200:"oklch(92.2% 0.005 34.3)",300:"oklch(86.8% 0.007 39.5)",400:"oklch(71.4% 0.014 41.2)",500:"oklch(54.7% 0.021 43.1)",600:"oklch(43.8% 0.017 39.3)",700:"oklch(36.7% 0.016 35.7)",800:"oklch(26.8% 0.011 36.5)",900:"oklch(21.4% 0.009 43.1)",950:"oklch(14.7% 0.004 49.3)"},red:{50:"oklch(97.1% 0.013 17.38)",100:"oklch(93.6% 0.032 17.717)",200:"oklch(88.5% 0.062 18.334)",300:"oklch(80.8% 0.114 19.571)",400:"oklch(70.4% 0.191 22.216)",500:"oklch(63.7% 0.237 25.331)",600:"oklch(57.7% 0.245 27.325)",700:"oklch(50.5% 0.213 27.518)",800:"oklch(44.4% 0.177 26.899)",900:"oklch(39.6% 0.141 25.723)",950:"oklch(25.8% 0.092 26.042)"},orange:{50:"oklch(98% 0.016 73.684)",100:"oklch(95.4% 0.038 75.164)",200:"oklch(90.1% 0.076 70.697)",300:"oklch(83.7% 0.128 66.29)",400:"oklch(75% 0.183 55.934)",500:"oklch(70.5% 0.213 47.604)",600:"oklch(64.6% 0.222 41.116)",700:"oklch(55.3% 0.195 38.402)",800:"oklch(47% 0.157 37.304)",900:"oklch(40.8% 0.123 38.172)",950:"oklch(26.6% 0.079 36.259)"},amber:{50:"oklch(98.7% 0.022 95.277)",100:"oklch(96.2% 0.059 95.617)",200:"oklch(92.4% 0.12 95.746)",300:"oklch(87.9% 0.169 91.605)",400:"oklch(82.8% 0.189 84.429)",500:"oklch(76.9% 0.188 70.08)",600:"oklch(66.6% 0.179 58.318)",700:"oklch(55.5% 0.163 48.998)",800:"oklch(47.3% 0.137 46.201)",900:"oklch(41.4% 0.112 45.904)",950:"oklch(27.9% 0.077 45.635)"},yellow:{50:"oklch(98.7% 0.026 102.212)",100:"oklch(97.3% 0.071 103.193)",200:"oklch(94.5% 0.129 101.54)",300:"oklch(90.5% 0.182 98.111)",400:"oklch(85.2% 0.199 91.936)",500:"oklch(79.5% 0.184 86.047)",600:"oklch(68.1% 0.162 75.834)",700:"oklch(55.4% 0.135 66.442)",800:"oklch(47.6% 0.114 61.907)",900:"oklch(42.1% 0.095 57.708)",950:"oklch(28.6% 0.066 53.813)"},lime:{50:"oklch(98.6% 0.031 120.757)",100:"oklch(96.7% 0.067 122.328)",200:"oklch(93.8% 0.127 124.321)",300:"oklch(89.7% 0.196 126.665)",400:"oklch(84.1% 0.238 128.85)",500:"oklch(76.8% 0.233 130.85)",600:"oklch(64.8% 0.2 131.684)",700:"oklch(53.2% 0.157 131.589)",800:"oklch(45.3% 0.124 130.933)",900:"oklch(40.5% 0.101 131.063)",950:"oklch(27.4% 0.072 132.109)"},green:{50:"oklch(98.2% 0.018 155.826)",100:"oklch(96.2% 0.044 156.743)",200:"oklch(92.5% 0.084 155.995)",300:"oklch(87.1% 0.15 154.449)",400:"oklch(79.2% 0.209 151.711)",500:"oklch(72.3% 0.219 149.579)",600:"oklch(62.7% 0.194 149.214)",700:"oklch(52.7% 0.154 150.069)",800:"oklch(44.8% 0.119 151.328)",900:"oklch(39.3% 0.095 152.535)",950:"oklch(26.6% 0.065 152.934)"},emerald:{50:"oklch(97.9% 0.021 166.113)",100:"oklch(95% 0.052 163.051)",200:"oklch(90.5% 0.093 164.15)",300:"oklch(84.5% 0.143 164.978)",400:"oklch(76.5% 0.177 163.223)",500:"oklch(69.6% 0.17 162.48)",600:"oklch(59.6% 0.145 163.225)",700:"oklch(50.8% 0.118 165.612)",800:"oklch(43.2% 0.095 166.913)",900:"oklch(37.8% 0.077 168.94)",950:"oklch(26.2% 0.051 172.552)"},teal:{50:"oklch(98.4% 0.014 180.72)",100:"oklch(95.3% 0.051 180.801)",200:"oklch(91% 0.096 180.426)",300:"oklch(85.5% 0.138 181.071)",400:"oklch(77.7% 0.152 181.912)",500:"oklch(70.4% 0.14 182.503)",600:"oklch(60% 0.118 184.704)",700:"oklch(51.1% 0.096 186.391)",800:"oklch(43.7% 0.078 188.216)",900:"oklch(38.6% 0.063 188.416)",950:"oklch(27.7% 0.046 192.524)"},cyan:{50:"oklch(98.4% 0.019 200.873)",100:"oklch(95.6% 0.045 203.388)",200:"oklch(91.7% 0.08 205.041)",300:"oklch(86.5% 0.127 207.078)",400:"oklch(78.9% 0.154 211.53)",500:"oklch(71.5% 0.143 215.221)",600:"oklch(60.9% 0.126 221.723)",700:"oklch(52% 0.105 223.128)",800:"oklch(45% 0.085 224.283)",900:"oklch(39.8% 0.07 227.392)",950:"oklch(30.2% 0.056 229.695)"},sky:{50:"oklch(97.7% 0.013 236.62)",100:"oklch(95.1% 0.026 236.824)",200:"oklch(90.1% 0.058 230.902)",300:"oklch(82.8% 0.111 230.318)",400:"oklch(74.6% 0.16 232.661)",500:"oklch(68.5% 0.169 237.323)",600:"oklch(58.8% 0.158 241.966)",700:"oklch(50% 0.134 242.749)",800:"oklch(44.3% 0.11 240.79)",900:"oklch(39.1% 0.09 240.876)",950:"oklch(29.3% 0.066 243.157)"},blue:{50:"oklch(97% 0.014 254.604)",100:"oklch(93.2% 0.032 255.585)",200:"oklch(88.2% 0.059 254.128)",300:"oklch(80.9% 0.105 251.813)",400:"oklch(70.7% 0.165 254.624)",500:"oklch(62.3% 0.214 259.815)",600:"oklch(54.6% 0.245 262.881)",700:"oklch(48.8% 0.243 264.376)",800:"oklch(42.4% 0.199 265.638)",900:"oklch(37.9% 0.146 265.522)",950:"oklch(28.2% 0.091 267.935)"},indigo:{50:"oklch(96.2% 0.018 272.314)",100:"oklch(93% 0.034 272.788)",200:"oklch(87% 0.065 274.039)",300:"oklch(78.5% 0.115 274.713)",400:"oklch(67.3% 0.182 276.935)",500:"oklch(58.5% 0.233 277.117)",600:"oklch(51.1% 0.262 276.966)",700:"oklch(45.7% 0.24 277.023)",800:"oklch(39.8% 0.195 277.366)",900:"oklch(35.9% 0.144 278.697)",950:"oklch(25.7% 0.09 281.288)"},violet:{50:"oklch(96.9% 0.016 293.756)",100:"oklch(94.3% 0.029 294.588)",200:"oklch(89.4% 0.057 293.283)",300:"oklch(81.1% 0.111 293.571)",400:"oklch(70.2% 0.183 293.541)",500:"oklch(60.6% 0.25 292.717)",600:"oklch(54.1% 0.281 293.009)",700:"oklch(49.1% 0.27 292.581)",800:"oklch(43.2% 0.232 292.759)",900:"oklch(38% 0.189 293.745)",950:"oklch(28.3% 0.141 291.089)"},purple:{50:"oklch(97.7% 0.014 308.299)",100:"oklch(94.6% 0.033 307.174)",200:"oklch(90.2% 0.063 306.703)",300:"oklch(82.7% 0.119 306.383)",400:"oklch(71.4% 0.203 305.504)",500:"oklch(62.7% 0.265 303.9)",600:"oklch(55.8% 0.288 302.321)",700:"oklch(49.6% 0.265 301.924)",800:"oklch(43.8% 0.218 303.724)",900:"oklch(38.1% 0.176 304.987)",950:"oklch(29.1% 0.149 302.717)"},fuchsia:{50:"oklch(97.7% 0.017 320.058)",100:"oklch(95.2% 0.037 318.852)",200:"oklch(90.3% 0.076 319.62)",300:"oklch(83.3% 0.145 321.434)",400:"oklch(74% 0.238 322.16)",500:"oklch(66.7% 0.295 322.15)",600:"oklch(59.1% 0.293 322.896)",700:"oklch(51.8% 0.253 323.949)",800:"oklch(45.2% 0.211 324.591)",900:"oklch(40.1% 0.17 325.612)",950:"oklch(29.3% 0.136 325.661)"},pink:{50:"oklch(97.1% 0.014 343.198)",100:"oklch(94.8% 0.028 342.258)",200:"oklch(89.9% 0.061 343.231)",300:"oklch(82.3% 0.12 346.018)",400:"oklch(71.8% 0.202 349.761)",500:"oklch(65.6% 0.241 354.308)",600:"oklch(59.2% 0.249 0.584)",700:"oklch(52.5% 0.223 3.958)",800:"oklch(45.9% 0.187 3.815)",900:"oklch(40.8% 0.153 2.432)",950:"oklch(28.4% 0.109 3.907)"},rose:{50:"oklch(96.9% 0.015 12.422)",100:"oklch(94.1% 0.03 12.58)",200:"oklch(89.2% 0.058 10.001)",300:"oklch(81% 0.117 11.638)",400:"oklch(71.2% 0.194 13.428)",500:"oklch(64.5% 0.246 16.439)",600:"oklch(58.6% 0.253 17.585)",700:"oklch(51.4% 0.222 16.935)",800:"oklch(45.5% 0.188 13.697)",900:"oklch(41% 0.159 10.272)",950:"oklch(27.1% 0.105 12.094)"}};var Oit=new Set(["black","silver","gray","white","maroon","red","purple","fuchsia","green","lime","olive","yellow","navy","blue","teal","aqua","aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen","transparent","currentcolor","canvas","canvastext","linktext","visitedtext","activetext","buttonface","buttontext","buttonborder","field","fieldtext","highlight","highlighttext","selecteditem","selecteditemtext","mark","marktext","graytext","accentcolor","accentcolortext"]),tVi=/^(rgba?|hsla?|hwb|color|(ok)?(lab|lch)|light-dark|color-mix|--alpha)\(/i;function iVi(e){return e.charCodeAt(0)===35||tVi.test(e)||Oit.has(e.toLowerCase())}function Nit(e){return Oit.has(e.toLowerCase())}var zfe=["calc","min","max","clamp","mod","rem","sin","cos","tan","asin","acos","atan","atan2","pow","sqrt","hypot","log","exp","round"];function bH(e){return e.indexOf("(")!==-1&&zfe.some((t)=>e.includes(`${t}(`))}function jfe(e){if(!zfe.some((o)=>e.includes(o)))return e;let t="",i=[],r=null,n=null;for(let o=0;o<e.length;o++){let s=e.charCodeAt(o);if(s>=48&&s<=57||r!==null&&(s===37||s>=97&&s<=122||s>=65&&s<=90)?r=o:(n=r,r=null),s===40){t+=e[o];let a=o;for(let u=o-1;u>=0;u--){let d=e.charCodeAt(u);if(d>=48&&d<=57)a=u;else if(d>=97&&d<=122)a=u;else break}let c=e.slice(a,o);if(zfe.includes(c)){i.unshift(!0);continue}else if(i[0]&&c===""){i.unshift(!0);continue}i.unshift(!1);continue}else if(s===41)t+=e[o],i.shift();else if(s===44&&i[0]){t+=", ";continue}else{if(s===32&&i[0]&&t.charCodeAt(t.length-1)===32)continue;if((s===43||s===42||s===47||s===45)&&i[0]){let a=t.trimEnd(),c=a.charCodeAt(a.length-1),u=a.charCodeAt(a.length-2),d=e.charCodeAt(o+1);if((c===101||c===69)&&u>=48&&u<=57){t+=e[o];continue}else if(c===43||c===42||c===47||c===45){t+=e[o];continue}else if(c===40||c===44){t+=e[o];continue}else e.charCodeAt(o-1)===32?t+=`${e[o]} `:c>=48&&c<=57||d>=48&&d<=57||c===41||d===40||d===43||d===42||d===47||d===45||n!==null&&n===o-1?t+=` ${e[o]} `:t+=e[o]}else t+=e[o]}}return t}var gH=new Uint8Array(256);function Si(e,t){let i=0,r=[],n=0,o=e.length,s=t.charCodeAt(0);for(let a=0;a<o;a++){let c=e.charCodeAt(a);if(i===0&&c===s){r.push(e.slice(n,a)),n=a+1;continue}switch(c){case 92:a+=1;break;case 39:case 34:for(;++a<o;){let u=e.charCodeAt(a);if(u===92){a+=1;continue}if(u===c)break}break;case 40:gH[i]=41,i++;break;case 91:gH[i]=93,i++;break;case 123:gH[i]=125,i++;break;case 93:case 125:case 41:i>0&&c===gH[i-1]&&i--;break}}return r.push(e.slice(n)),r}var rVi={color:iVi,length:nv,percentage:Ufe,ratio:xVi,number:zit,integer:pt,url:Lit,position:EVi,"bg-size":AVi,"line-width":oVi,image:cVi,"family-name":uVi,"generic-name":lVi,"absolute-size":dVi,"relative-size":pVi,angle:SVi,vector:BVi};function Wo(e,t){if(e.startsWith("var("))return null;for(let i of t)if(rVi[i]?.(e))return i;return null}var nVi=/^url\(.*\)$/;function Lit(e){return nVi.test(e)}function oVi(e){return Si(e," ").every((t)=>nv(t)||zit(t)||t==="thin"||t==="medium"||t==="thick")}var sVi=/^(?:element|image|cross-fade|image-set)\(/,aVi=/^(repeating-)?(conic|linear|radial)-gradient\(/;function cVi(e){let t=0;for(let i of Si(e,","))if(!i.startsWith("var(")){if(Lit(i)){t+=1;continue}if(aVi.test(i)){t+=1;continue}if(sVi.test(i)){t+=1;continue}return!1}return t>0}function lVi(e){return e==="serif"||e==="sans-serif"||e==="monospace"||e==="cursive"||e==="fantasy"||e==="system-ui"||e==="ui-serif"||e==="ui-sans-serif"||e==="ui-monospace"||e==="ui-rounded"||e==="math"||e==="emoji"||e==="fangsong"}function uVi(e){let t=0;for(let i of Si(e,",")){let r=i.charCodeAt(0);if(r>=48&&r<=57)return!1;i.startsWith("var(")||(t+=1)}return t>0}function dVi(e){return e==="xx-small"||e==="x-small"||e==="small"||e==="medium"||e==="large"||e==="x-large"||e==="xx-large"||e==="xxx-large"}function pVi(e){return e==="larger"||e==="smaller"}var Jy=/[+-]?\d*\.?\d+(?:[eE][+-]?\d+)?/,mVi=new RegExp(`^${Jy.source}$`);function zit(e){return mVi.test(e)||bH(e)}var hVi=new RegExp(`^${Jy.source}%$`);function Ufe(e){return hVi.test(e)||bH(e)}var fVi=new RegExp(`^${Jy.source}\\s*/\\s*${Jy.source}$`);function xVi(e){return fVi.test(e)||bH(e)}var gVi=["cm","mm","Q","in","pc","pt","px","em","ex","ch","rem","lh","rlh","vw","vh","vmin","vmax","vb","vi","svw","svh","lvw","lvh","dvw","dvh","cqw","cqh","cqi","cqb","cqmin","cqmax"],yVi=new RegExp(`^${Jy.source}(${gVi.join("|")})$`),bVi=/^(--spacing)\(/i;function nv(e){return yVi.test(e)||bVi.test(e)||bH(e)}function EVi(e){let t=0;for(let i of Si(e," ")){if(i==="center"||i==="top"||i==="right"||i==="bottom"||i==="left"){t+=1;continue}if(!i.startsWith("var(")){if(nv(i)||Ufe(i)){t+=1;continue}return!1}}return t>0}function AVi(e){let t=0;for(let i of Si(e,",")){if(i==="cover"||i==="contain"){t+=1;continue}let r=Si(i," ");if(r.length!==1&&r.length!==2)return!1;if(r.every((n)=>n==="auto"||nv(n)||Ufe(n))){t+=1;continue}}return t>0}var vVi=["deg","rad","grad","turn"],wVi=new RegExp(`^${Jy.source}(${vVi.join("|")})$`);function SVi(e){return wVi.test(e)}var kVi=new RegExp(`^${Jy.source} +${Jy.source} +${Jy.source}$`);function BVi(e){return kVi.test(e)}function pt(e){let t=Number(e);return Number.isInteger(t)&&t>=0&&String(t)===String(e)}function qfe(e){let t=Number(e);return Number.isInteger(t)&&t>0&&String(t)===String(e)}function ua(e){return jit(e,0.25)}function EH(e){return jit(e,0.25)}function jit(e,t){let i=Number(e);return i>=0&&i%t===0&&String(i)===String(e)}function Z8(e){return{__BARE_VALUE__:e}}var ph=Z8((e)=>{if(pt(e.value))return e.value}),Ml=Z8((e)=>{if(pt(e.value))return`${e.value}%`}),rv=Z8((e)=>{if(pt(e.value))return`${e.value}px`}),Fit=Z8((e)=>{if(pt(e.value))return`${e.value}ms`}),yH=Z8((e)=>{if(pt(e.value))return`${e.value}deg`}),CVi=Z8((e)=>{if(e.fraction===null)return;let[t,i]=Si(e.fraction,"/");if(!(!pt(t)||!pt(i)))return e.fraction}),Mit=Z8((e)=>{if(pt(Number(e.value)))return`repeat(${e.value}, minmax(0, 1fr))`}),Uit={accentColor:({theme:e})=>e("colors"),animation:{none:"none",spin:"spin 1s linear infinite",ping:"ping 1s cubic-bezier(0, 0, 0.2, 1) infinite",pulse:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",bounce:"bounce 1s infinite"},aria:{busy:'busy="true"',checked:'checked="true"',disabled:'disabled="true"',expanded:'expanded="true"',hidden:'hidden="true"',pressed:'pressed="true"',readonly:'readonly="true"',required:'required="true"',selected:'selected="true"'},aspectRatio:{auto:"auto",square:"1 / 1",video:"16 / 9",...CVi},backdropBlur:({theme:e})=>e("blur"),backdropBrightness:({theme:e})=>({...e("brightness"),...Ml}),backdropContrast:({theme:e})=>({...e("contrast"),...Ml}),backdropGrayscale:({theme:e})=>({...e("grayscale"),...Ml}),backdropHueRotate:({theme:e})=>({...e("hueRotate"),...yH}),backdropInvert:({theme:e})=>({...e("invert"),...Ml}),backdropOpacity:({theme:e})=>({...e("opacity"),...Ml}),backdropSaturate:({theme:e})=>({...e("saturate"),...Ml}),backdropSepia:({theme:e})=>({...e("sepia"),...Ml}),backgroundColor:({theme:e})=>e("colors"),backgroundImage:{none:"none","gradient-to-t":"linear-gradient(to top, var(--tw-gradient-stops))","gradient-to-tr":"linear-gradient(to top right, var(--tw-gradient-stops))","gradient-to-r":"linear-gradient(to right, var(--tw-gradient-stops))","gradient-to-br":"linear-gradient(to bottom right, var(--tw-gradient-stops))","gradient-to-b":"linear-gradient(to bottom, var(--tw-gradient-stops))","gradient-to-bl":"linear-gradient(to bottom left, var(--tw-gradient-stops))","gradient-to-l":"linear-gradient(to left, var(--tw-gradient-stops))","gradient-to-tl":"linear-gradient(to top left, var(--tw-gradient-stops))"},backgroundOpacity:({theme:e})=>e("opacity"),backgroundPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},backgroundSize:{auto:"auto",cover:"cover",contain:"contain"},blur:{0:"0",none:"",sm:"4px",DEFAULT:"8px",md:"12px",lg:"16px",xl:"24px","2xl":"40px","3xl":"64px"},borderColor:({theme:e})=>({DEFAULT:"currentcolor",...e("colors")}),borderOpacity:({theme:e})=>e("opacity"),borderRadius:{none:"0px",sm:"0.125rem",DEFAULT:"0.25rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem","3xl":"1.5rem",full:"9999px"},borderSpacing:({theme:e})=>e("spacing"),borderWidth:{DEFAULT:"1px",0:"0px",2:"2px",4:"4px",8:"8px",...rv},boxShadow:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",DEFAULT:"0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)",inner:"inset 0 2px 4px 0 rgb(0 0 0 / 0.05)",none:"none"},boxShadowColor:({theme:e})=>e("colors"),brightness:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",200:"2",...Ml},caretColor:({theme:e})=>e("colors"),colors:()=>({...xH}),columns:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12","3xs":"16rem","2xs":"18rem",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",...ph},container:{},content:{none:"none"},contrast:{0:"0",50:".5",75:".75",100:"1",125:"1.25",150:"1.5",200:"2",...Ml},cursor:{auto:"auto",default:"default",pointer:"pointer",wait:"wait",text:"text",move:"move",help:"help","not-allowed":"not-allowed",none:"none","context-menu":"context-menu",progress:"progress",cell:"cell",crosshair:"crosshair","vertical-text":"vertical-text",alias:"alias",copy:"copy","no-drop":"no-drop",grab:"grab",grabbing:"grabbing","all-scroll":"all-scroll","col-resize":"col-resize","row-resize":"row-resize","n-resize":"n-resize","e-resize":"e-resize","s-resize":"s-resize","w-resize":"w-resize","ne-resize":"ne-resize","nw-resize":"nw-resize","se-resize":"se-resize","sw-resize":"sw-resize","ew-resize":"ew-resize","ns-resize":"ns-resize","nesw-resize":"nesw-resize","nwse-resize":"nwse-resize","zoom-in":"zoom-in","zoom-out":"zoom-out"},divideColor:({theme:e})=>e("borderColor"),divideOpacity:({theme:e})=>e("borderOpacity"),divideWidth:({theme:e})=>({...e("borderWidth"),...rv}),dropShadow:{sm:"0 1px 1px rgb(0 0 0 / 0.05)",DEFAULT:["0 1px 2px rgb(0 0 0 / 0.1)","0 1px 1px rgb(0 0 0 / 0.06)"],md:["0 4px 3px rgb(0 0 0 / 0.07)","0 2px 2px rgb(0 0 0 / 0.06)"],lg:["0 10px 8px rgb(0 0 0 / 0.04)","0 4px 3px rgb(0 0 0 / 0.1)"],xl:["0 20px 13px rgb(0 0 0 / 0.03)","0 8px 5px rgb(0 0 0 / 0.08)"],"2xl":"0 25px 25px rgb(0 0 0 / 0.15)",none:"0 0 #0000"},fill:({theme:e})=>e("colors"),flex:{1:"1 1 0%",auto:"1 1 auto",initial:"0 1 auto",none:"none"},flexBasis:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",...e("spacing")}),flexGrow:{0:"0",DEFAULT:"1",...ph},flexShrink:{0:"0",DEFAULT:"1",...ph},fontFamily:{sans:["ui-sans-serif","system-ui","sans-serif",'"Apple Color Emoji"','"Segoe UI Emoji"','"Segoe UI Symbol"','"Noto Color Emoji"'],serif:["ui-serif","Georgia","Cambria",'"Times New Roman"',"Times","serif"],mono:["ui-monospace","SFMono-Regular","Menlo","Monaco","Consolas",'"Liberation Mono"','"Courier New"',"monospace"]},fontSize:{xs:["0.75rem",{lineHeight:"1rem"}],sm:["0.875rem",{lineHeight:"1.25rem"}],base:["1rem",{lineHeight:"1.5rem"}],lg:["1.125rem",{lineHeight:"1.75rem"}],xl:["1.25rem",{lineHeight:"1.75rem"}],"2xl":["1.5rem",{lineHeight:"2rem"}],"3xl":["1.875rem",{lineHeight:"2.25rem"}],"4xl":["2.25rem",{lineHeight:"2.5rem"}],"5xl":["3rem",{lineHeight:"1"}],"6xl":["3.75rem",{lineHeight:"1"}],"7xl":["4.5rem",{lineHeight:"1"}],"8xl":["6rem",{lineHeight:"1"}],"9xl":["8rem",{lineHeight:"1"}]},fontWeight:{thin:"100",extralight:"200",light:"300",normal:"400",medium:"500",semibold:"600",bold:"700",extrabold:"800",black:"900"},gap:({theme:e})=>e("spacing"),gradientColorStops:({theme:e})=>e("colors"),gradientColorStopPositions:{"0%":"0%","5%":"5%","10%":"10%","15%":"15%","20%":"20%","25%":"25%","30%":"30%","35%":"35%","40%":"40%","45%":"45%","50%":"50%","55%":"55%","60%":"60%","65%":"65%","70%":"70%","75%":"75%","80%":"80%","85%":"85%","90%":"90%","95%":"95%","100%":"100%",...Ml},grayscale:{0:"0",DEFAULT:"100%",...Ml},gridAutoColumns:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridAutoRows:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridColumn:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridColumnEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...ph},gridColumnStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...ph},gridRow:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridRowEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...ph},gridRowStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...ph},gridTemplateColumns:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))",...Mit},gridTemplateRows:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))",...Mit},height:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),hueRotate:{0:"0deg",15:"15deg",30:"30deg",60:"60deg",90:"90deg",180:"180deg",...yH},inset:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%",...e("spacing")}),invert:{0:"0",DEFAULT:"100%",...Ml},keyframes:{spin:{to:{transform:"rotate(360deg)"}},ping:{"75%, 100%":{transform:"scale(2)",opacity:"0"}},pulse:{"50%":{opacity:".5"}},bounce:{"0%, 100%":{transform:"translateY(-25%)",animationTimingFunction:"cubic-bezier(0.8,0,1,1)"},"50%":{transform:"none",animationTimingFunction:"cubic-bezier(0,0,0.2,1)"}}},letterSpacing:{tighter:"-0.05em",tight:"-0.025em",normal:"0em",wide:"0.025em",wider:"0.05em",widest:"0.1em"},lineHeight:{none:"1",tight:"1.25",snug:"1.375",normal:"1.5",relaxed:"1.625",loose:"2",3:".75rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem"},listStyleType:{none:"none",disc:"disc",decimal:"decimal"},listStyleImage:{none:"none"},margin:({theme:e})=>({auto:"auto",...e("spacing")}),lineClamp:{1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",...ph},maxHeight:({theme:e})=>({none:"none",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),maxWidth:({theme:e})=>({none:"none",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",prose:"65ch",...e("spacing")}),minHeight:({theme:e})=>({full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),minWidth:({theme:e})=>({full:"100%",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),objectPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},opacity:{0:"0",5:"0.05",10:"0.1",15:"0.15",20:"0.2",25:"0.25",30:"0.3",35:"0.35",40:"0.4",45:"0.45",50:"0.5",55:"0.55",60:"0.6",65:"0.65",70:"0.7",75:"0.75",80:"0.8",85:"0.85",90:"0.9",95:"0.95",100:"1",...Ml},order:{first:"-9999",last:"9999",none:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",...ph},outlineColor:({theme:e})=>e("colors"),outlineOffset:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...rv},outlineWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...rv},padding:({theme:e})=>e("spacing"),placeholderColor:({theme:e})=>e("colors"),placeholderOpacity:({theme:e})=>e("opacity"),ringColor:({theme:e})=>({DEFAULT:"currentcolor",...e("colors")}),ringOffsetColor:({theme:e})=>e("colors"),ringOffsetWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...rv},ringOpacity:({theme:e})=>({DEFAULT:"0.5",...e("opacity")}),ringWidth:{DEFAULT:"3px",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...rv},rotate:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",45:"45deg",90:"90deg",180:"180deg",...yH},saturate:{0:"0",50:".5",100:"1",150:"1.5",200:"2",...Ml},scale:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",...Ml},screens:{sm:"40rem",md:"48rem",lg:"64rem",xl:"80rem","2xl":"96rem"},scrollMargin:({theme:e})=>e("spacing"),scrollPadding:({theme:e})=>e("spacing"),sepia:{0:"0",DEFAULT:"100%",...Ml},skew:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",...yH},space:({theme:e})=>e("spacing"),spacing:{px:"1px",0:"0px",0.5:"0.125rem",1:"0.25rem",1.5:"0.375rem",2:"0.5rem",2.5:"0.625rem",3:"0.75rem",3.5:"0.875rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem",11:"2.75rem",12:"3rem",14:"3.5rem",16:"4rem",20:"5rem",24:"6rem",28:"7rem",32:"8rem",36:"9rem",40:"10rem",44:"11rem",48:"12rem",52:"13rem",56:"14rem",60:"15rem",64:"16rem",72:"18rem",80:"20rem",96:"24rem"},stroke:({theme:e})=>({none:"none",...e("colors")}),strokeWidth:{0:"0",1:"1",2:"2",...ph},supports:{},data:{},textColor:({theme:e})=>e("colors"),textDecorationColor:({theme:e})=>e("colors"),textDecorationThickness:{auto:"auto","from-font":"from-font",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...rv},textIndent:({theme:e})=>e("spacing"),textOpacity:({theme:e})=>e("opacity"),textUnderlineOffset:{auto:"auto",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...rv},transformOrigin:{center:"center",top:"top","top-right":"top right",right:"right","bottom-right":"bottom right",bottom:"bottom","bottom-left":"bottom left",left:"left","top-left":"top left"},transitionDelay:{0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1000:"1000ms",...Fit},transitionDuration:{DEFAULT:"150ms",0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1000:"1000ms",...Fit},transitionProperty:{none:"none",all:"all",DEFAULT:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter",colors:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke",opacity:"opacity",shadow:"box-shadow",transform:"transform"},transitionTimingFunction:{DEFAULT:"cubic-bezier(0.4, 0, 0.2, 1)",linear:"linear",in:"cubic-bezier(0.4, 0, 1, 1)",out:"cubic-bezier(0, 0, 0.2, 1)","in-out":"cubic-bezier(0.4, 0, 0.2, 1)"},translate:({theme:e})=>({"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%",...e("spacing")}),size:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),width:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",screen:"100vw",svw:"100svw",lvw:"100lvw",dvw:"100dvw",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),willChange:{auto:"auto",scroll:"scroll-position",contents:"contents",transform:"transform"},zIndex:{auto:"auto",0:"0",10:"10",20:"20",30:"30",40:"40",50:"50",...ph}};function lP(e){if(arguments.length===0)throw TypeError("`CSS.escape` requires an argument.");let t=String(e),i=t.length,r=-1,n,o="",s=t.charCodeAt(0);if(i===1&&s===45)return"\\"+t;for(;++r<i;){if(n=t.charCodeAt(r),n===0){o+="\uFFFD";continue}if(n>=1&&n<=31||n===127||r===0&&n>=48&&n<=57||r===1&&n>=48&&n<=57&&s===45){o+="\\"+n.toString(16)+" ";continue}if(n>=128||n===45||n===95||n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122){o+=t.charAt(r);continue}o+="\\"+t.charAt(r)}return o}function cB(e){return e.replace(/\\([\dA-Fa-f]{1,6}[\t\n\f\r ]?|[\S\s])/g,(t)=>{if(t.length<=2)return t[1];let i=Number.parseInt(t.slice(1).trim(),16);return i===0||i>1114111||i>=55296&&i<=57343?"\uFFFD":String.fromCodePoint(i)})}var $it=new Map([["--font",["--font-weight","--font-size"]],["--inset",["--inset-shadow","--inset-ring"]],["--text",["--text-color","--text-decoration-color","--text-decoration-thickness","--text-indent","--text-shadow","--text-underline-offset"]],["--grid-column",["--grid-column-start","--grid-column-end"]],["--grid-row",["--grid-row-start","--grid-row-end"]]]);function qit(e,t){return($it.get(t)??[]).some((i)=>e===i||e.startsWith(`${i}-`))}var Git=class{constructor(e=new Map,t=new Set([])){this.values=e,this.keyframes=t}values;keyframes;prefix=null;get size(){return this.values.size}add(e,t,i=0,r){if(e.endsWith("-*")){if(t!=="initial")throw Error(`Invalid theme value \`${t}\` for namespace \`${e}\``);e==="--*"?this.values.clear():this.clearNamespace(e.slice(0,-2),0)}if(i&4){let n=this.values.get(e);if(n&&!(n.options&4))return}t==="initial"?this.values.delete(e):this.values.set(e,{value:t,options:i,src:r})}keysInNamespaces(e){let t=[];for(let i of e){let r=`${i}-`;for(let n of this.values.keys())n.startsWith(r)&&n.indexOf("--",2)===-1&&(qit(n,i)||t.push(n.slice(r.length)))}return t}get(e){for(let t of e){let i=this.values.get(t);if(i)return i.value}return null}hasDefault(e){return(this.getOptions(e)&4)===4}getOptions(e){return e=cB(this.#e(e)),this.values.get(e)?.options??0}entries(){return this.prefix?Array.from(this.values,(e)=>(e[0]=this.prefixKey(e[0]),e)):this.values.entries()}prefixKey(e){return this.prefix?`--${this.prefix}-${e.slice(2)}`:e}#e(e){return this.prefix?`--${e.slice(3+this.prefix.length)}`:e}clearNamespace(e,t){let i=$it.get(e)??[];e:for(let r of this.values.keys())if(r.startsWith(e)){if(t!==0&&(this.getOptions(r)&t)!==t)continue;for(let n of i)if(r.startsWith(n))continue e;this.values.delete(r)}}#t(e,t){for(let i of t){let r=e!==null?`${i}-${e}`:i;if(!this.values.has(r))if(e!==null&&e.includes(".")){if(r=`${i}-${e.replaceAll(".","_")}`,!this.values.has(r))continue}else continue;if(!qit(r,i))return r}return null}#i(e){let t=this.values.get(e);if(!t)return null;let i=null;return t.options&2&&(i=t.value),`var(${lP(this.prefixKey(e))}${i?`, ${i}`:""})`}markUsedVariable(e){let t=cB(this.#e(e)),i=this.values.get(t);if(!i)return!1;let r=i.options&16;return i.options|=16,!r}resolve(e,t,i=0){let r=this.#t(e,t);if(!r)return null;let n=this.values.get(r);return(i|n.options)&1?n.value:this.#i(r)}resolveValue(e,t){let i=this.#t(e,t);return i?this.values.get(i).value:null}resolveWith(e,t,i=[]){let r=this.#t(e,t);if(!r)return null;let n={};for(let s of i){let a=`${r}${s}`,c=this.values.get(a);c&&(c.options&1?n[s]=c.value:n[s]=this.#i(a))}let o=this.values.get(r);return o.options&1?[o.value,n]:[this.#i(r),n]}namespace(e){let t=new Map,i=`${e}-`;for(let[r,n]of this.values)r===e?t.set(null,n.value):r.startsWith(`${i}-`)?t.set(r.slice(e.length),n.value):r.startsWith(i)&&t.set(r.slice(i.length),n.value);return t}addKeyframes(e){this.keyframes.add(e)}getKeyframes(){return Array.from(this.keyframes)}};var DVi="4.3.2";function IVi(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);function i(n){let o=0,s=t.length;for(;s>0;){let c=(s|0)>>1,u=o+c;t[u]<=n?(o=u+1,s=s-c-1):s=c}o-=1;let a=n-t[o];return{line:o+1,column:a}}function r({line:n,column:o}){n-=1,n=Math.min(Math.max(n,0),t.length-1);let s=t[n],a=t[n+1]??s;return Math.min(Math.max(s+o,0),a)}return{find:i,findOffset:r}}var dP=92,AH=47,vH=42,Hit=34,Wit=39,_Vi=58,DH=59,hh=10,_H=13,pP=32,mP=9,Zit=123,$fe=125,Jfe=40,Vit=41,TVi=91,PVi=93,Kit=45,Gfe=64,RVi=33,Xy=class e extends Error{loc;constructor(t,i){if(i){let r=i[0],n=IVi(r.code).find(i[1]);t=`${r.file}:${n.line}:${n.column+1}: ${t}`}super(t),this.name="CssSyntaxError",this.loc=i,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};function Grt(e,t){let i=t?.from?{file:t.from,code:e}:null;e[0]==="\uFEFF"&&(e=" "+e.slice(1));let r=[],n=[],o=[],s=null,a=null,c="",u="",d=0,p;for(let m=0;m<e.length;m++){let h=e.charCodeAt(m);if(!(h===_H&&(p=e.charCodeAt(m+1),p===hh)))if(h===dP)c===""&&(d=m),c+=e.slice(m,m+2),m+=1;else if(h===AH&&e.charCodeAt(m+1)===vH){let f=m;for(let y=m+2;y<e.length;y++)if(p=e.charCodeAt(y),p===dP)y+=1;else if(p===vH&&e.charCodeAt(y+1)===AH){m=y+1;break}let g=e.slice(f,m+1);if(g.charCodeAt(2)===RVi){let y=Wrt(g.slice(2,-2));n.push(y),i&&(y.src=[i,f,m+1],y.dst=[i,f,m+1])}}else if(h===Wit||h===Hit){let f=Yit(e,m,h,i);c+=e.slice(m,f+1),m=f}else{if((h===pP||h===hh||h===mP)&&(p=e.charCodeAt(m+1))&&(p===pP||p===hh||p===mP||p===_H&&(p=e.charCodeAt(m+2))&&p==hh))continue;if(h===hh){if(c.length===0)continue;p=c.charCodeAt(c.length-1),p!==pP&&p!==hh&&p!==mP&&(c+=" ")}else if(h===Kit&&e.charCodeAt(m+1)===Kit&&c.length===0){let f="",g=m,y=-1;for(let v=m+2;v<e.length;v++)if(p=e.charCodeAt(v),p===dP)v+=1;else if(p===Wit||p===Hit)v=Yit(e,v,p,i);else if(p===AH&&e.charCodeAt(v+1)===vH){for(let w=v+2;w<e.length;w++)if(p=e.charCodeAt(w),p===dP)w+=1;else if(p===vH&&e.charCodeAt(w+1)===AH){v=w+1;break}}else if(y===-1&&p===_Vi)y=c.length+v-g;else if(p===DH&&f.length===0){c+=e.slice(g,v),m=v;break}else if(p===Jfe)f+=")";else if(p===TVi)f+="]";else if(p===Zit)f+="}";else if((p===$fe||e.length-1===v)&&f.length===0){m=v-1,c+=e.slice(g,v);break}else(p===Vit||p===PVi||p===$fe)&&f.length>0&&e[v]===f[f.length-1]&&(f=f.slice(0,-1));let b=Hfe(c,y);if(!b)throw new Xy("Invalid custom property, expected a value",i?[i,g,m]:null);i&&(b.src=[i,g,m],b.dst=[i,g,m]),s?s.nodes.push(b):r.push(b),c=""}else if(h===DH&&c.charCodeAt(0)===Gfe)a=IH(c),i&&(a.src=[i,d,m],a.dst=[i,d,m]),s?s.nodes.push(a):r.push(a),c="",a=null;else if(h===DH&&u[u.length-1]!==")"){let f=Hfe(c);if(!f){if(c.length===0)continue;throw new Xy(`Invalid declaration: \`${c.trim()}\``,i?[i,d,m]:null)}i&&(f.src=[i,d,m],f.dst=[i,d,m]),s?s.nodes.push(f):r.push(f),c=""}else if(h===Zit&&u[u.length-1]!==")")u+="}",a=oc(c.trim()),i&&(a.src=[i,d,m],a.dst=[i,d,m]),s&&s.nodes.push(a),o.push(s),s=a,c="",a=null;else if(h===$fe&&u[u.length-1]!==")"){if(u==="")throw new Xy("Missing opening {",i?[i,m,m]:null);if(u=u.slice(0,-1),c.length>0)if(c.charCodeAt(0)===Gfe)a=IH(c),i&&(a.src=[i,d,m],a.dst=[i,d,m]),s?s.nodes.push(a):r.push(a),c="",a=null;else{let g=c.indexOf(":");if(s){let y=Hfe(c,g);if(!y)throw new Xy(`Invalid declaration: \`${c.trim()}\``,i?[i,d,m]:null);i&&(y.src=[i,d,m],y.dst=[i,d,m]),s.nodes.push(y)}}let f=o.pop()??null;f===null&&s&&r.push(s),s=f,c="",a=null}else if(h===Jfe)u+=")",c+="(";else if(h===Vit){if(u[u.length-1]!==")")throw new Xy("Missing opening (",i?[i,m,m]:null);u=u.slice(0,-1),c+=")"}else{if(c.length===0&&(h===pP||h===hh||h===mP))continue;c===""&&(d=m),c+=String.fromCharCode(h)}}}if(c.charCodeAt(0)===Gfe){let m=IH(c);i&&(m.src=[i,d,e.length],m.dst=[i,d,e.length]),r.push(m)}if(u.length>0&&s){if(s.kind==="rule")throw new Xy(`Missing closing } at ${s.selector}`,s.src?[s.src[0],s.src[1],s.src[1]]:null);if(s.kind==="at-rule")throw new Xy(`Missing closing } at ${s.name} ${s.params}`,s.src?[s.src[0],s.src[1],s.src[1]]:null)}return n.length>0?n.concat(r):r}function IH(e,t=[]){let i=e,r="";for(let n=5;n<e.length;n++){let o=e.charCodeAt(n);if(o===pP||o===mP||o===Jfe){i=e.slice(0,n),r=e.slice(n);break}}return sn(i.trim(),r.trim(),t)}function Hfe(e,t=e.indexOf(":")){if(t===-1)return null;let i=e.indexOf("!important",t+1);return I(e.slice(0,t).trim(),e.slice(t+1,i===-1?e.length:i).trim(),i!==-1)}function Yit(e,t,i,r=null){let n;for(let o=t+1;o<e.length;o++)if(n=e.charCodeAt(o),n===dP)o+=1;else{if(n===i)return o;if(n===DH&&(e.charCodeAt(o+1)===hh||e.charCodeAt(o+1)===_H&&e.charCodeAt(o+2)===hh))throw new Xy(`Unterminated string: ${e.slice(t,o+1)+String.fromCharCode(i)}`,r?[r,t,o+1]:null);if(n===hh||n===_H&&e.charCodeAt(o+1)===hh)throw new Xy(`Unterminated string: ${e.slice(t,o)+String.fromCharCode(i)}`,r?[r,t,o+1]:null)}return t}var ki=class extends Map{constructor(e){super();this.factory=e}factory;get(e){let t=super.get(e);return t===void 0&&(t=this.factory(e,this),this.set(e,t)),t}};function Wc(e){return{kind:"word",value:e}}function FVi(e,t){return{kind:"function",value:e,nodes:t}}function MVi(e){return{kind:"separator",value:e}}function Cr(e){let t="";for(let i of e)switch(i.kind){case"word":case"separator":{t+=i.value;break}case"function":t+=i.value+"("+Cr(i.nodes)+")"}return t}var Jit=92,OVi=41,Qit=58,Xit=44,NVi=34,ert=61,trt=62,irt=60,rrt=10,LVi=40,zVi=39,jVi=47,nrt=32,ort=9;function Br(e){e=e.replaceAll(`\r
4720
4721
  `,`
4721
4722
  `);let t=[],i=[],r=null,n="",o;for(let s=0;s<e.length;s++){let a=e.charCodeAt(s);switch(a){case Jit:{n+=e[s]+e[s+1],s++;break}case jVi:{if(n.length>0){let u=Wc(n);r?r.nodes.push(u):t.push(u),n=""}let c=Wc(e[s]);r?r.nodes.push(c):t.push(c);break}case Qit:case Xit:case ert:case trt:case irt:case rrt:case nrt:case ort:{if(n.length>0){let p=Wc(n);r?r.nodes.push(p):t.push(p),n=""}let c=s,u=s+1;for(;u<e.length&&(o=e.charCodeAt(u),!(o!==Qit&&o!==Xit&&o!==ert&&o!==trt&&o!==irt&&o!==rrt&&o!==nrt&&o!==ort));u++);s=u-1;let d=MVi(e.slice(c,u));r?r.nodes.push(d):t.push(d);break}case zVi:case NVi:{let c=s;for(let u=s+1;u<e.length;u++)if(o=e.charCodeAt(u),o===Jit)u+=1;else if(o===a){s=u;break}n+=e.slice(c,s+1);break}case LVi:{let c=FVi(n,[]);n="",r?r.nodes.push(c):t.push(c),i.push(c),r=c;break}case OVi:{let c=i.pop();if(n.length>0){let u=Wc(n);c?.nodes.push(u),n=""}i.length>0?r=i[i.length-1]:r=null;break}default:n+=String.fromCharCode(a)}}return n.length>0&&t.push(Wc(n)),t}var Qfe=((e)=>(e[e.Continue=0]="Continue",e[e.Skip=1]="Skip",e[e.Stop=2]="Stop",e[e.Replace=3]="Replace",e[e.ReplaceSkip=4]="ReplaceSkip",e[e.ReplaceStop=5]="ReplaceStop",e))(Qfe||{}),tt={Continue:{kind:0},Skip:{kind:1},Stop:{kind:2},Replace:(e)=>({kind:3,nodes:Array.isArray(e)?e:[e]}),ReplaceSkip:(e)=>({kind:4,nodes:Array.isArray(e)?e:[e]}),ReplaceStop:(e)=>({kind:5,nodes:Array.isArray(e)?e:[e]})};function Ut(e,t){typeof t=="function"?srt(e,t):srt(e,t.enter,t.exit)}function srt(e,t=()=>tt.Continue,i=()=>tt.Continue){let r={value:[e,0,null],prev:null},n={parent:null,depth:0,index:0,siblings:e,path(){let o=[],s=r;for(;s;){let a=s.value[2];a&&o.push(a),s=s.prev}return o.reverse(),o}};for(;r!==null;){let o=r.value,s=o[0],a=o[1],c=o[2];if(a>=s.length){r=r.prev,n.depth-=1;continue}if(n.parent=c,n.siblings=s,a>=0){n.index=a;let m=s[a],h=t(m,n)??tt.Continue;switch(h.kind){case 0:{m.nodes&&m.nodes.length>0&&(n.depth+=1,r={value:[m.nodes,0,m],prev:r}),o[1]=~a;continue}case 2:return;case 1:{o[1]=~a;continue}case 3:{s.splice(a,1,...h.nodes);continue}case 5:{s.splice(a,1,...h.nodes);return}case 4:{s.splice(a,1,...h.nodes),o[1]+=h.nodes.length;continue}default:throw Error(`Invalid \`WalkAction.${Qfe[h.kind]??`Unknown(${h.kind})`}\` in enter.`)}}let u=~a;n.index=u;let d=s[u],p=i(d,n)??tt.Continue;switch(p.kind){case 0:o[1]=u+1;continue;case 2:return;case 3:{s.splice(u,1,...p.nodes),o[1]=u+p.nodes.length;continue}case 5:{s.splice(u,1,...p.nodes);return}case 4:{s.splice(u,1,...p.nodes),o[1]=u+p.nodes.length;continue}default:throw Error(`Invalid \`WalkAction.${Qfe[p.kind]??`Unknown(${p.kind})`}\` in exit.`)}}}function Hrt(e){let t=[];return Ut(Br(e),(i)=>{if(!(i.kind!=="function"||i.value!=="var"))return Ut(i.nodes,(r)=>{r.kind!=="word"||r.value[0]!=="-"||r.value[1]!=="-"||t.push(r.value)}),tt.Skip}),t}var UVi=64;function wn(e,t=[]){return{kind:"rule",selector:e,nodes:t}}function sn(e,t="",i=[]){return{kind:"at-rule",name:e,params:t,nodes:i}}function oc(e,t=[]){return e.charCodeAt(0)===UVi?IH(e,t):wn(e,t)}function I(e,t,i=!1){return{kind:"declaration",property:e,value:t,important:i}}function Wrt(e){return{kind:"comment",value:e}}function K8(e,t){return{kind:"context",context:e,nodes:t}}function tr(e){return{kind:"at-root",nodes:e}}function vp(e){switch(e.kind){case"rule":return{kind:e.kind,selector:e.selector,nodes:e.nodes.map(vp),src:e.src,dst:e.dst};case"at-rule":return{kind:e.kind,name:e.name,params:e.params,nodes:e.nodes.map(vp),src:e.src,dst:e.dst};case"at-root":return{kind:e.kind,nodes:e.nodes.map(vp),src:e.src,dst:e.dst};case"context":return{kind:e.kind,context:{...e.context},nodes:e.nodes.map(vp),src:e.src,dst:e.dst};case"declaration":return{kind:e.kind,property:e.property,value:e.value,important:e.important,src:e.src,dst:e.dst};case"comment":return{kind:e.kind,value:e.value,src:e.src,dst:e.dst};default:throw Error(`Unknown node kind: ${e.kind}`)}}function axe(e){return{depth:e.depth,index:e.index,siblings:e.siblings,get context(){let t={};for(let i of e.path())i.kind==="context"&&Object.assign(t,i.context);return Object.defineProperty(this,"context",{value:t}),t},get parent(){let t=this.path().pop()??null;return Object.defineProperty(this,"parent",{value:t}),t},path(){return e.path().filter((t)=>t.kind!=="context")}}}function hP(e,t,i=3){let r=[],n=new Set,o=new ki(()=>new Set),s=new ki(()=>new Set),a=new Set,c=new Set,u=[],d=[],p=new ki(()=>new Set);function m(f,g,y={},b=0){if(f.kind==="declaration"){if(f.property==="--tw-sort"||f.value===void 0||f.value===null)return;if(y.theme&&f.property[0]==="-"&&f.property[1]==="-"){if(f.value==="initial"){f.value=void 0;return}y.keyframes||o.get(g).add(f)}if(f.value.includes("var("))if(y.theme&&f.property[0]==="-"&&f.property[1]==="-")for(let v of Hrt(f.value))p.get(v).add(f.property);else t.trackUsedVariables(f.value);if(f.property==="animation")for(let v of art(f.value))c.add(v);i&2&&f.value.includes("color-mix(")&&!y.supportsColorMix&&!y.keyframes&&s.get(g).add(f),g.push(f)}else if(f.kind==="rule"){let v=[];for(let R of f.nodes)m(R,v,y,b+1);let w={},D=new Set;for(let R of v){if(R.kind!=="declaration")continue;let O=`${R.property}:${R.value}:${R.important}`;w[O]??=[],w[O].push(R)}for(let R in w)for(let O=0;O<w[R].length-1;++O)D.add(w[R][O]);if(D.size>0&&(v=v.filter((R)=>!D.has(R))),v.length===0)return;f.selector==="&"?g.push(...v):g.push({...f,nodes:v})}else if(f.kind==="at-rule"&&f.name==="@property"&&b===0){if(n.has(f.params))return;if(i&1){let w=f.params,D=null,R=!1;for(let k of f.nodes)k.kind==="declaration"&&(k.property==="initial-value"?D=k.value:k.property==="inherits"&&(R=k.value==="true"));let O=I(w,D??"initial");O.src=f.src,R?u.push(O):d.push(O)}n.add(f.params);let v={...f,nodes:[]};for(let w of f.nodes)m(w,v.nodes,y,b+1);g.push(v)}else if(f.kind==="at-rule"){f.name==="@keyframes"?y={...y,keyframes:!0}:f.name==="@supports"&&f.params.includes("color-mix(")&&(y={...y,supportsColorMix:!0});let v={...f,nodes:[]};for(let w of f.nodes)m(w,v.nodes,y,b+1);f.name==="@keyframes"&&y.theme&&a.add(v),(v.nodes.length>0||v.name==="@layer"||v.name==="@charset"||v.name==="@custom-media"||v.name==="@namespace"||v.name==="@import"||v.name==="@apply")&&g.push(v)}else if(f.kind==="at-root")for(let v of f.nodes){let w=[];m(v,w,y,0);for(let D of w)r.push(D)}else if(f.kind==="context"){if(f.context.reference)return;for(let v of f.nodes)m(v,g,{...y,...f.context},b)}else f.kind==="comment"&&g.push(f)}let h=[];for(let f of e)m(f,h,{},0);e:for(let[f,g]of o)for(let y of g){if(Zrt(y.property,t.theme,p)){if(y.property.startsWith(t.theme.prefixKey("--animate-")))for(let v of art(y.value))c.add(v);continue}let b=f.indexOf(y);if(f.splice(b,1),f.length===0){let v=qVi(h,(w)=>w.kind==="rule"&&w.nodes===f);if(!v||v.length===0)continue e;v.unshift({kind:"at-root",nodes:h});do{let w=v.pop();if(!w)break;let D=v[v.length-1];if(!D||D.kind!=="at-root"&&D.kind!=="at-rule")break;let R=D.nodes.indexOf(w);if(R===-1)break;D.nodes.splice(R,1)}while(!0);continue e}}for(let f of a)if(!c.has(f.params)){let g=r.indexOf(f);r.splice(g,1)}if(h=h.concat(r),i&2)for(let[f,g]of s)for(let y of g){let b=f.indexOf(y);if(b===-1||y.value==null)continue;let v=Br(y.value),w=!1;if(Ut(v,(O)=>{if(O.kind!=="function"||O.value!=="color-mix")return;let k=!1,j=!1;if(Ut(O.nodes,(L)=>{if(L.kind=="word"&&L.value.toLowerCase()==="currentcolor"){j=!0,w=!0;return}let q=L,K=null,ue=new Set;do{if(q.kind!=="function"||q.value!=="var")return;let G=q.nodes[0];if(!G||G.kind!=="word")return;let S=G.value;if(ue.has(S)){k=!0;return}if(ue.add(S),w=!0,K=t.theme.resolveValue(null,[G.value]),!K){k=!0;return}if(K.toLowerCase()==="currentcolor"){j=!0;return}K.startsWith("var(")?q=Br(K)[0]:q=null}while(q);return tt.Replace({kind:"word",value:K})}),k||j){let L=O.nodes.findIndex((K)=>K.kind==="separator"&&K.value.trim().includes(","));if(L===-1)return;let q=O.nodes.length>L?O.nodes[L+1]:null;return q?tt.Replace(q):void 0}else if(w){let L=O.nodes[2];L.kind==="word"&&(L.value==="oklab"||L.value==="oklch"||L.value==="lab"||L.value==="lch")&&(L.value="srgb")}}),!w)continue;let D={...y,value:Cr(v)},R=oc("@supports (color: color-mix(in lab, red, red))",[y]);R.src=y.src,f.splice(b,1,D,R)}if(i&1){let f=[];if(u.length>0){let g=oc(":root, :host",u);g.src=u[0].src,f.push(g)}if(d.length>0){let g=oc("*, ::before, ::after, ::backdrop",d);g.src=d[0].src,f.push(g)}if(f.length>0){let g=h.findIndex((v)=>!(v.kind==="comment"||v.kind==="at-rule"&&(v.name==="@charset"||v.name==="@import"))),y=sn("@layer","properties",[]);y.src=f[0].src,h.splice(g<0?h.length:g,0,y);let b=oc("@layer properties",[sn("@supports","((-webkit-hyphens: none) and (not (margin-trim: inline))) or ((-moz-orient: inline) and (not (color:rgb(from red r g b))))",f)]);b.src=f[0].src,b.nodes[0].src=f[0].src,h.push(b)}}return h}function tb(e,t){let i=0,r={file:null,code:""};function n(s,a=0){let c="",u=" ".repeat(a);if(s.kind==="declaration"){if(c+=`${u}${s.property}: ${s.value}${s.important?" !important":""};
4722
4723
  `,t){i+=u.length;let d=i;i+=s.property.length,i+=2,i+=s.value?.length??0,s.important&&(i+=11);let p=i;i+=2,s.dst=[r,d,p]}}else if(s.kind==="rule"){if(c+=`${u}${s.selector} {
@@ -6045,7 +6046,7 @@ It stays saved even if the alert to {owner} is delayed, so there\u2019s no need
6045
6046
  Email: ${t.email}
6046
6047
  Notification: ${t.notification}
6047
6048
 
6048
- ${i}`},withHandled(e){let{frontmatter:t,message:i}=Ql.parseContent(e.content);return{content:Ql.createContent({...t,status:"handled"},i),metadata:{...e.metadata,status:"handled"}}}}};function j2e(){return xO({id:"contact",label:"Contact",entity:F2e,target:z2e,forms:[N2e]})}var ken=j2e(),TXt=ken,_Xt=Object.freeze(fO("contact-request"));var PXt={name:"@brains/form",license:"AGPL-3.0-only",version:"0.2.0-alpha.698",description:"Forms defined in a Brain's content, served by the package their submissions belong to",dependencies:{"@brains/forms":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0","bun-types":"^1.4.0",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var Cen=l.object({title:l.string(),target:l.string(),path:l.string()}),FXt=Mi.extend({entityType:l.literal("form"),metadata:Cen});class MXt extends B3{constructor(){super({entityType:"form",purpose:"A public form on the brain's site: its fields, copy and what its submissions become. Served by the package that stores them; never knowledge or model input.",schema:FXt,frontmatterSchema:b3,hasBody:!0})}fromMarkdown(e){let t=this.parseFrontMatter(e,b3);return{entityType:"form",content:e,metadata:{title:t.title,target:t.target,path:t.path??""}}}}var Den=new MXt;class OXt extends DQ{entityType="form";schema=FXt;adapter=Den;constructor(){super("form",PXt,{},RXt)}getEntityTypeConfig(){return{embeddable:!1,fullTextSearchable:!1,projectionSource:!1,projectionSourceRole:"excluded"}}async onRegister(e){await super.onRegister(e),e.entities.registerPersistValidator(this.entityType,async(t)=>{try{hO(t.id,t.content)}catch{throw Error("Invalid form")}})}}function NXt(){return new OXt}var Ien=l.strictObject({dimension:l.string(),title:l.string(),outcome:l.string(),outcomeTitle:l.string()}),_en=l.strictObject({field:l.string(),label:l.string(),value:l.union([l.string(),l.array(l.string())])}),LXt=l.enum(["new","handled"]),zXt=l.enum(["pending","sent","failed","none"]),IS=l.strictObject({quiz:l.string().meta({studioWidget:"provenance"}),quizTitle:l.string().optional().meta({studioWidget:"provenance"}),language:l.string().optional().meta({studioWidget:"provenance"}),receivedAt:l.iso.datetime().meta({studioWidget:"provenance"}),status:LXt,notification:zXt.meta({studioWidget:"provenance"}),name:l.string().max(200).optional().meta({studioWidget:"provenance"}),email:l.email().max(254).optional().meta({studioWidget:"provenance"}),results:l.array(Ien).max(20).meta({studioWidget:"provenance"}),answers:l.array(_en).max(200).meta({studioWidget:"provenance"})}),A1=l.object({title:l.string(),quiz:l.string(),receivedAt:l.iso.datetime(),status:LXt,notification:zXt,contact:l.boolean()}),U2e=Mi.extend({entityType:l.literal("quiz-result"),visibility:l.literal("restricted"),metadata:A1});var om=Object.freeze({createContent(e){try{return fn("",IS.parse(e))}catch{throw Error("Invalid quiz result")}},parseContent(e){try{return{frontmatter:Ia("quiz-result",e,IS)}}catch{throw Error("Invalid quiz result")}},metadataFor(e){return{title:e.quizTitle??e.quiz,quiz:e.quiz,receivedAt:e.receivedAt,status:e.status,notification:e.notification,contact:e.email!==void 0}},fromMarkdown(e){let{frontmatter:t}=om.parseContent(e);return{entityType:"quiz-result",visibility:"restricted",content:e,metadata:om.metadataFor(t)}}});var q2e=Qi(Ln(zt({type:"quiz-result",purpose:"A restricted record of one quiz taken on the brain's site: what was asked and answered, and the results shown. Never public knowledge or model input.",metadata:A1,markdown:_a({header:IS,deriveMetadata:(e)=>om.metadataFor(e)}),config:{embeddable:!1,fullTextSearchable:!1,projectionSource:!1,projectionSourceRole:"excluded"},validatePersist:({content:e,visibility:t})=>{if(t!=="restricted")throw Error("Quiz results must have restricted visibility");om.parseContent(e)}})),IS);var $2e=new Map([["name","text"],["email","email"]]);function Ten(e,t){return Nd(e).flatMap((i)=>{if($2e.has(i.id))return[];let r=t[i.id];if(!("options"in i)){let s=typeof r==="string"?r:"";return s?[{field:i.id,label:i.label,value:s}]:[]}let o=(r===void 0?[]:Array.isArray(r)?r:[r]).flatMap((s)=>{let a=i.options.find((c)=>c.value===s);return a?[a.label]:[]});if(o.length===0)return[];return[{field:i.id,label:i.label,value:i.kind==="choice"?o[0]??"":o}]})}function jXt(e){let{form:t,answers:i,receivedAt:r,notify:n,results:o,language:s}=e,a=Nh(i,"name"),c=Nh(i,"email");return{quiz:t.id,quizTitle:t.title,...s?{language:s}:{},receivedAt:new Date(r).toISOString(),status:"new",notification:n?"pending":"none",...a?{name:a}:{},...c?{email:c}:{},results:o.flatMap((u)=>{let d=t.scoring?.dimensions.find((m)=>m.id===u.dimension),p=d?.outcomes.find((m)=>m.id===u.outcome);return d&&p?[{dimension:d.id,title:d.title,outcome:p.id,outcomeTitle:p.title}]:[]}),answers:Ten(t,i)}}function Pen(e){return{content:om.createContent(e),metadata:A1.parse(om.metadataFor(e))}}function v1(e){return om.parseContent(e.content).frontmatter}function Ren(e){return[`Quiz: ${e.quiz}`,...e.name?[`Name: ${e.name}`]:[],...e.email?[`Email: ${e.email}`]:[],...e.language?[`Language: ${e.language}`]:[],"",...e.results.map((i)=>`${i.title}: ${i.outcomeTitle}`),"",...e.answers.map((i)=>`${i.label}: ${Array.isArray(i.value)?i.value.join(", "):i.value}`)].join(`
6049
+ ${i}`},withHandled(e){let{frontmatter:t,message:i}=Ql.parseContent(e.content);return{content:Ql.createContent({...t,status:"handled"},i),metadata:{...e.metadata,status:"handled"}}}}};function j2e(){return xO({id:"contact",label:"Contact",entity:F2e,target:z2e,forms:[N2e]})}var ken=j2e(),TXt=ken,_Xt=Object.freeze(fO("contact-request"));var PXt={name:"@brains/form",license:"AGPL-3.0-only",version:"0.2.0-alpha.699",description:"Forms defined in a Brain's content, served by the package their submissions belong to",dependencies:{"@brains/forms":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0","bun-types":"^1.4.0",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var Cen=l.object({title:l.string(),target:l.string(),path:l.string()}),FXt=Mi.extend({entityType:l.literal("form"),metadata:Cen});class MXt extends B3{constructor(){super({entityType:"form",purpose:"A public form on the brain's site: its fields, copy and what its submissions become. Served by the package that stores them; never knowledge or model input.",schema:FXt,frontmatterSchema:b3,hasBody:!0})}fromMarkdown(e){let t=this.parseFrontMatter(e,b3);return{entityType:"form",content:e,metadata:{title:t.title,target:t.target,path:t.path??""}}}}var Den=new MXt;class OXt extends DQ{entityType="form";schema=FXt;adapter=Den;constructor(){super("form",PXt,{},RXt)}getEntityTypeConfig(){return{embeddable:!1,fullTextSearchable:!1,projectionSource:!1,projectionSourceRole:"excluded"}}async onRegister(e){await super.onRegister(e),e.entities.registerPersistValidator(this.entityType,async(t)=>{try{hO(t.id,t.content)}catch{throw Error("Invalid form")}})}}function NXt(){return new OXt}var Ien=l.strictObject({dimension:l.string(),title:l.string(),outcome:l.string(),outcomeTitle:l.string()}),_en=l.strictObject({field:l.string(),label:l.string(),value:l.union([l.string(),l.array(l.string())])}),LXt=l.enum(["new","handled"]),zXt=l.enum(["pending","sent","failed","none"]),IS=l.strictObject({quiz:l.string().meta({studioWidget:"provenance"}),quizTitle:l.string().optional().meta({studioWidget:"provenance"}),language:l.string().optional().meta({studioWidget:"provenance"}),receivedAt:l.iso.datetime().meta({studioWidget:"provenance"}),status:LXt,notification:zXt.meta({studioWidget:"provenance"}),name:l.string().max(200).optional().meta({studioWidget:"provenance"}),email:l.email().max(254).optional().meta({studioWidget:"provenance"}),results:l.array(Ien).max(20).meta({studioWidget:"provenance"}),answers:l.array(_en).max(200).meta({studioWidget:"provenance"})}),A1=l.object({title:l.string(),quiz:l.string(),receivedAt:l.iso.datetime(),status:LXt,notification:zXt,contact:l.boolean()}),U2e=Mi.extend({entityType:l.literal("quiz-result"),visibility:l.literal("restricted"),metadata:A1});var om=Object.freeze({createContent(e){try{return fn("",IS.parse(e))}catch{throw Error("Invalid quiz result")}},parseContent(e){try{return{frontmatter:Ia("quiz-result",e,IS)}}catch{throw Error("Invalid quiz result")}},metadataFor(e){return{title:e.quizTitle??e.quiz,quiz:e.quiz,receivedAt:e.receivedAt,status:e.status,notification:e.notification,contact:e.email!==void 0}},fromMarkdown(e){let{frontmatter:t}=om.parseContent(e);return{entityType:"quiz-result",visibility:"restricted",content:e,metadata:om.metadataFor(t)}}});var q2e=Qi(Ln(zt({type:"quiz-result",purpose:"A restricted record of one quiz taken on the brain's site: what was asked and answered, and the results shown. Never public knowledge or model input.",metadata:A1,markdown:_a({header:IS,deriveMetadata:(e)=>om.metadataFor(e)}),config:{embeddable:!1,fullTextSearchable:!1,projectionSource:!1,projectionSourceRole:"excluded"},validatePersist:({content:e,visibility:t})=>{if(t!=="restricted")throw Error("Quiz results must have restricted visibility");om.parseContent(e)}})),IS);var $2e=new Map([["name","text"],["email","email"]]);function Ten(e,t){return Nd(e).flatMap((i)=>{if($2e.has(i.id))return[];let r=t[i.id];if(!("options"in i)){let s=typeof r==="string"?r:"";return s?[{field:i.id,label:i.label,value:s}]:[]}let o=(r===void 0?[]:Array.isArray(r)?r:[r]).flatMap((s)=>{let a=i.options.find((c)=>c.value===s);return a?[a.label]:[]});if(o.length===0)return[];return[{field:i.id,label:i.label,value:i.kind==="choice"?o[0]??"":o}]})}function jXt(e){let{form:t,answers:i,receivedAt:r,notify:n,results:o,language:s}=e,a=Nh(i,"name"),c=Nh(i,"email");return{quiz:t.id,quizTitle:t.title,...s?{language:s}:{},receivedAt:new Date(r).toISOString(),status:"new",notification:n?"pending":"none",...a?{name:a}:{},...c?{email:c}:{},results:o.flatMap((u)=>{let d=t.scoring?.dimensions.find((m)=>m.id===u.dimension),p=d?.outcomes.find((m)=>m.id===u.outcome);return d&&p?[{dimension:d.id,title:d.title,outcome:p.id,outcomeTitle:p.title}]:[]}),answers:Ten(t,i)}}function Pen(e){return{content:om.createContent(e),metadata:A1.parse(om.metadataFor(e))}}function v1(e){return om.parseContent(e.content).frontmatter}function Ren(e){return[`Quiz: ${e.quiz}`,...e.name?[`Name: ${e.name}`]:[],...e.email?[`Email: ${e.email}`]:[],...e.language?[`Language: ${e.language}`]:[],"",...e.results.map((i)=>`${i.title}: ${i.outcomeTitle}`),"",...e.answers.map((i)=>`${i.label}: ${Array.isArray(i.value)?i.value.join(", "):i.value}`)].join(`
6049
6050
  `)}var G2e={entityType:"quiz-result",idSeparator:":",schema:U2e,refuse(e){let t=Nd(e).find((i)=>{let r=$2e.get(i.id);return r!==void 0&&r!==i.kind});return t?`Form "${e.id}": a quiz result takes "${t.id}" as an ${$2e.get(t.id)} field`:void 0},record(e){return Pen(jXt(e))},matches(e,t){let i=v1(e),r=jXt(t);return i.quiz===r.quiz&&i.receivedAt===r.receivedAt&&i.name===r.name&&i.email===r.email&&JSON.stringify(i.answers)===JSON.stringify(r.answers)},notification(e){return v1(e).notification},withNotification(e,t){let i=v1(e);return{content:om.createContent({...i,notification:t}),metadata:A1.parse({...e.metadata,notification:t})}},handled(e){return v1(e).status==="handled"},alert(e){let t=v1(e);return{answers:t.answers.map((i)=>({label:i.label,value:Array.isArray(i.value)?i.value.join(", "):i.value})),outcomes:t.results.map((i)=>({label:i.title,value:i.outcomeTitle})),...t.email?{replyTo:t.email}:{}}},inbox:{sourceId:"quiz-results",displayName:"Quiz results",label:"Quiz",recordLabel:"Quiz result",listFilter:{contact:!0},item(e){let t=v1(e);if(!t.email)return;return{title:`${e.metadata.title} result`,summary:t.results.map((i)=>`${i.title}: ${i.outcomeTitle}`).join(" \xB7 "),receivedAt:t.receivedAt}},detail(e){return Ren(v1(e))},withHandled(e){return{content:om.createContent({...v1(e),status:"handled"}),metadata:A1.parse({...e.metadata,status:"handled"})}}}};function H2e(){return xO({id:"quiz",label:"Quiz",entity:q2e,target:G2e,forms:[]})}var Fen=H2e(),qXt=Fen,UXt=Object.freeze(fO("quiz-result"));var Men=l.union([l.enum(["public","shared","restricted"]),l.literal("private")]).optional().transform((e)=>{if(e===void 0||e==="private")return"restricted";return e}),W2e=l.object({memoryVisibility:Men.describe("Visibility applied to the memory the plugin writes: action items found in channels")});var _r="action-item",gO="summary";var yO=["spaceId","sourceSummaryId","sourceMessageCount","projectionVersion"],bO=["timeRange"],Oen=l.strictObject({identity:l.unknown().optional(),identityAliases:l.unknown().optional(),displayName:l.unknown().optional()});function Z2e(e){if(!Ba(e)||!Oen.safeParse(e).success)return e;let t=Oh.safeParse(e.identity),i=t.success?Lh(t.data):void 0,r=l.array(Oh).catch([]).parse(e.identityAliases??[]).map(Lh).filter((o)=>o!==i),n=e.displayName;return{...typeof n==="string"&&n.length>0?{name:n}:{},...i?{id:i}:{},...r.length>0?{aliases:r}:{}}}function $Xt(e){if(!Ba(e)||e.capturedAt!==void 0)return e;let t=e.timeRange,i=Ba(t)?t.end:void 0;return typeof i==="string"?{...e,capturedAt:i}:e}var V2e=l.object({start:l.string().datetime(),end:l.string().datetime()}),Rb=l.object({identity:Oh,identityAliases:l.array(Oh).optional(),displayName:l.string().optional()}),IQ=l.string().regex(/^(user|external|agent|service):.+$/),AO=l.object({name:l.string().min(1),id:IQ.optional(),aliases:l.array(IQ).optional()}),vO=l.object({name:l.string().min(1).optional(),id:IQ,aliases:l.array(IQ).optional()}),Nen=l.preprocess(Z2e,AO),Len=l.preprocess(Z2e,vO),zd=l.enum(["open","doing","blocked","done","dropped"]),HXt=l.object({sourceId:l.string().min(1),entityType:l.string().min(1),entityId:l.string().min(1)}),zen=["conversationId","interfaceType","channelId"];function WXt(e,t){if(e.origin==="board")return;let i=e.origin==="inbox"?["sourceRef"]:zen;for(let r of i)if(e[r]===void 0)t.addIssue({code:"custom",path:[r],message:e.origin==="inbox"?`An action item tracked from the Inbox needs ${r}`:`An action item from a conversation needs ${r}`})}var EO={studioWidget:"provenance"},GXt={studioWidget:"hidden"},ZXt={origin:l.enum(["conversation","inbox","board"]).optional().meta(EO),conversationId:l.string().optional().meta(GXt),interfaceType:l.string().optional().meta(EO),channelId:l.string().optional().meta(GXt),channelName:l.string().optional().meta(EO),sourceRef:HXt.optional().meta(EO),capturedAt:l.iso.datetime().meta(EO)},_S=l.object({...ZXt,status:zd,assignedTo:l.array(AO).optional().meta({studioWidget:"members"}),requestedBy:l.array(vO).optional().meta({studioWidget:"people"}),dueDate:l.iso.date().optional(),projectedBodyHash:l.string().optional().meta({studioWidget:"hidden"}),projectedAssigneeHash:l.string().optional().meta({studioWidget:"hidden"}),projectedDueDate:l.iso.date().optional().meta({studioWidget:"hidden"})}).superRefine(WXt),TS=l.preprocess($Xt,l.object({...ZXt,status:zd,assignedTo:l.array(Nen).optional(),requestedBy:l.array(Len).optional(),dueDate:l.iso.date().optional(),projectedBodyHash:l.string().optional().meta({studioWidget:"hidden"}),projectedAssigneeHash:l.string().optional().meta({studioWidget:"hidden"}),projectedDueDate:l.iso.date().optional().meta({studioWidget:"hidden"})}).superRefine(WXt));function C3(e){if(e.origin==="board")return{kind:"board",capturedAt:e.capturedAt};if(e.origin==="inbox"&&e.sourceRef)return{kind:"inbox",sourceRef:e.sourceRef,capturedAt:e.capturedAt};if(e.conversationId!==void 0&&e.interfaceType!==void 0&&e.channelId!==void 0)return{kind:"conversation",conversationId:e.conversationId,interfaceType:e.interfaceType,channelId:e.channelId,...e.channelName?{channelName:e.channelName}:{},capturedAt:e.capturedAt};throw Error("Action item metadata names no complete origin")}var eo=Mi.extend({entityType:l.literal("action-item"),metadata:TS});var jen=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function zh(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return e;return`${jen[t.getUTCMonth()]} ${t.getUTCDate()}`}function wO(e,t=new Date){let i=new Date(e);if(Number.isNaN(i.getTime()))return"";let r=Math.max(0,t.getTime()-i.getTime()),n=Math.floor(r/60000);if(n<1)return"now";if(n<60)return`${n}m`;let o=Math.floor(n/60);if(o<24)return`${o}h`;return`${Math.floor(o/24)}d`}function PS(e,t){let i=e?.trim();if(i&&i!==t)return`#${i}`;let[r,...n]=t.split(":");return r&&n.length>0?Wn(r):`#${t}`}var KXt=new Set(Object.keys(_S.shape)),YXt=new Set([...yO,...bO]),Uen=new Set(VXt);class K2e extends Error{current;expected;constructor(e,t){super(`Action item is ${e}, not ${t}`);this.name="StaleActionItemStatusError",this.current=e,this.expected=t}}function JXt(e){let{data:t}=Fb(e);return typeof t==="object"&&t!==null?Object.fromEntries(Object.entries(t)):{}}function RS(e){let t=Object.entries(e.metadata).filter(([,r])=>r!==void 0),i=Object.entries(JXt(e.content)).filter(([r])=>!KXt.has(r)&&!YXt.has(r));return Object.fromEntries([...t,...i])}function Up(e){return Fb(e).content}function SO(e){return sr(Up(e))}function kO(e){return sr(JSON.stringify((e??[]).map((t)=>t.id).sort()))}function D3(e){if(e.metadata.status!=="open")return!0;if(Object.keys(JXt(e.content)).some((n)=>!KXt.has(n)&&!YXt.has(n)&&!Uen.has(n)))return!0;let i=e.metadata.projectedAssigneeHash;if(i!==void 0&&(kO(e.metadata.assignedTo)!==i||e.metadata.dueDate!==e.metadata.projectedDueDate))return!0;let r=e.metadata.projectedBodyHash;return r!==void 0&&SO(e.content)!==r}function Y2e(e,t){let i=e.metadata.status;if(i!==t.from)throw new K2e(i,t.from);if(t.to===t.from)throw Error(`Action item is already ${t.to}`);let r=kr({...RS(e),status:t.to},Up(e.content));return{...e,content:r,contentHash:sr(r),metadata:{...e.metadata,status:t.to}}}function Xl(e){let i=e.content.match(/^#\s+(.+)$/m)?.[1]?.trim()?.replace(/^Action item:\s*/,"");return i!==void 0&&i.length>0?i:e.id}function J2e(e){return Up(e.content).replace(/^#[^\n]*\n/,"").trim()}function Q2e(e,t){let i=t.text.replace(/\s+/g," ").trim();if(i.length===0)throw Error("A note needs text");let r=`- ${t.at.slice(0,10)} \xB7 ${t.actorName??"A team member"} \u2014 ${i}
6050
6051
  `,n=Up(e.content),o=n.endsWith(`
6051
6052
  `)?n:`${n}
@@ -8214,7 +8215,7 @@ When to use directives:
8214
8215
  .guide-sections__more summary:hover {
8215
8216
  color: var(--docs-text);
8216
8217
  }
8217
- `;import{jsx as eu,jsxs as JS,Fragment as TBe}from"react/jsx-runtime";var Noi=4;function vcn(e){return`guide-section-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`}var Loi=({docs:e})=>eu("ul",{className:"guide-sections__docs",children:e.map((t)=>eu("li",{children:eu("a",{href:`/docs/${t.slug}`,children:t.title})},t.id))}),wcn=({guides:e})=>eu("ul",{className:"guide-sections__guides",children:e.map((t)=>eu("li",{children:JS("a",{href:iN(t),children:[eu("span",{className:"guide-sections__persona",children:t.metadata.persona}),t.frontmatter.summary&&eu("span",{className:"guide-sections__summary",children:t.frontmatter.summary})]})},t.id))}),PBe=({sections:e})=>{if(e.length===0)return eu(TBe,{});return JS(VS,{children:[eu("style",{children:Ooi}),eu("div",{className:"guide-sections",children:e.map((t)=>{let i=vcn(t.name),r=t.docs.slice(0,Noi),n=t.docs.slice(Noi);return JS("section",{className:"guide-sections__column","aria-labelledby":i,children:[eu("h2",{className:"guide-sections__name",id:i,children:t.name}),t.guides.length>0&&JS(TBe,{children:[eu("h3",{className:"guide-sections__label",children:t.guides.length>1?"Which one are you?":"Walk it through"}),eu(wcn,{guides:t.guides})]}),r.length>0&&JS(TBe,{children:[eu("h3",{className:"guide-sections__label",children:"Reference"}),eu(Loi,{docs:r})]}),n.length>0&&JS("details",{className:"guide-sections__more",children:[JS("summary",{children:[n.length," more reference"," ",n.length===1?"doc":"docs"]}),eu(Loi,{docs:n})]})]},t.name)})})]})};var cee=l.object({id:l.string(),entityType:l.literal("guide"),content:l.string(),created:l.string(),updated:l.string(),visibility:Uu,contentHash:l.string(),metadata:eee,frontmatter:am,body:l.string()}),zoi=l.object({guides:l.array(cee),chrome:Yh.nullable().default(null)}),Scn=l.object({sections:l.array(l.object({name:l.string(),guides:l.array(cee),docs:l.array(rN)}))}),kcn=l.object({guide:cee,otherGuides:l.array(cee),chrome:Yh.nullable().default(null)});function joi(){return{"guide-list":nt({name:"guide-list",description:"Index of moving-in guides",schema:zoi,dataSourceId:"guides:entities",requiredPermission:"public",layout:{component:IBe}}),"guide-band":nt({name:"guide-band",description:"The guides as a band on a composed docs page, such as the docs home",schema:zoi,dataSourceId:"guides:entities",requiredPermission:"public",layout:{component:_Be}}),"guide-sections":nt({name:"guide-sections",description:"Each docs section's guides and reference docs as columns, under a site's own section introductions",schema:Scn,dataSourceId:"guides:sections",requiredPermission:"public",layout:{component:PBe}}),"guide-detail":nt({name:"guide-detail",description:"A moving-in guide for one kind of user",schema:kcn,dataSourceId:"guides:entities",requiredPermission:"public",runtimeScripts:[{src:DBe,defer:!0}],staticAssets:{[DBe]:Moi},layout:{component:CBe}})}}var Uoi={name:"@brains/guide",license:"AGPL-3.0-only",version:"0.2.0-alpha.698",description:"Guide entity type \u2014 moving-in walkthroughs for kinds of brain users",dependencies:{"@brains/docs-chrome":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*","@rizom/brain-ui":"workspace:*",react:"^19.2.7"},devDependencies:{"@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/react":"^19.2.17","bun-types":"^1.4.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./frontmatter":"./src/schemas/guide-frontmatter.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};class RBe extends DQ{entityType=tee.entityType;schema=jx;adapter=tee;constructor(e={}){super("guides",Uoi,e,gBe)}getEntityTypeConfig(){return{projectionSourceRole:"primary"}}async getInstructions(){return['Guides (entityType "guide") walk one kind of user through moving into a brain: a writer, researcher, consultant, team, or someone running their own brain.',"A question from someone who describes themselves, their material or how they work, and asks where to start, how to bring their material in, how to run a brain of their own, such as on their own server, or what a brain would do for them, is a guide question, even when it names no guide. A guide question is answered from its guide alone, without searching the docs: the guide links the docs for the details.",`For a guide question, first run system_list with entityType "guide", before asking the network or answering from general knowledge: each guide's metadata says who it is for (persona, for) and what material it moves in. Read the guide that fits the person with system_get, and answer from its stages.`,'Name the guide you answer from by its title, such as "Moving in as a writer", so the reply links to it.'].join(`
8218
+ `;import{jsx as eu,jsxs as JS,Fragment as TBe}from"react/jsx-runtime";var Noi=4;function vcn(e){return`guide-section-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`}var Loi=({docs:e})=>eu("ul",{className:"guide-sections__docs",children:e.map((t)=>eu("li",{children:eu("a",{href:`/docs/${t.slug}`,children:t.title})},t.id))}),wcn=({guides:e})=>eu("ul",{className:"guide-sections__guides",children:e.map((t)=>eu("li",{children:JS("a",{href:iN(t),children:[eu("span",{className:"guide-sections__persona",children:t.metadata.persona}),t.frontmatter.summary&&eu("span",{className:"guide-sections__summary",children:t.frontmatter.summary})]})},t.id))}),PBe=({sections:e})=>{if(e.length===0)return eu(TBe,{});return JS(VS,{children:[eu("style",{children:Ooi}),eu("div",{className:"guide-sections",children:e.map((t)=>{let i=vcn(t.name),r=t.docs.slice(0,Noi),n=t.docs.slice(Noi);return JS("section",{className:"guide-sections__column","aria-labelledby":i,children:[eu("h2",{className:"guide-sections__name",id:i,children:t.name}),t.guides.length>0&&JS(TBe,{children:[eu("h3",{className:"guide-sections__label",children:t.guides.length>1?"Which one are you?":"Walk it through"}),eu(wcn,{guides:t.guides})]}),r.length>0&&JS(TBe,{children:[eu("h3",{className:"guide-sections__label",children:"Reference"}),eu(Loi,{docs:r})]}),n.length>0&&JS("details",{className:"guide-sections__more",children:[JS("summary",{children:[n.length," more reference"," ",n.length===1?"doc":"docs"]}),eu(Loi,{docs:n})]})]},t.name)})})]})};var cee=l.object({id:l.string(),entityType:l.literal("guide"),content:l.string(),created:l.string(),updated:l.string(),visibility:Uu,contentHash:l.string(),metadata:eee,frontmatter:am,body:l.string()}),zoi=l.object({guides:l.array(cee),chrome:Yh.nullable().default(null)}),Scn=l.object({sections:l.array(l.object({name:l.string(),guides:l.array(cee),docs:l.array(rN)}))}),kcn=l.object({guide:cee,otherGuides:l.array(cee),chrome:Yh.nullable().default(null)});function joi(){return{"guide-list":nt({name:"guide-list",description:"Index of moving-in guides",schema:zoi,dataSourceId:"guides:entities",requiredPermission:"public",layout:{component:IBe}}),"guide-band":nt({name:"guide-band",description:"The guides as a band on a composed docs page, such as the docs home",schema:zoi,dataSourceId:"guides:entities",requiredPermission:"public",layout:{component:_Be}}),"guide-sections":nt({name:"guide-sections",description:"Each docs section's guides and reference docs as columns, under a site's own section introductions",schema:Scn,dataSourceId:"guides:sections",requiredPermission:"public",layout:{component:PBe}}),"guide-detail":nt({name:"guide-detail",description:"A moving-in guide for one kind of user",schema:kcn,dataSourceId:"guides:entities",requiredPermission:"public",runtimeScripts:[{src:DBe,defer:!0}],staticAssets:{[DBe]:Moi},layout:{component:CBe}})}}var Uoi={name:"@brains/guide",license:"AGPL-3.0-only",version:"0.2.0-alpha.699",description:"Guide entity type \u2014 moving-in walkthroughs for kinds of brain users",dependencies:{"@brains/docs-chrome":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*","@rizom/brain-ui":"workspace:*",react:"^19.2.7"},devDependencies:{"@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/react":"^19.2.17","bun-types":"^1.4.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./frontmatter":"./src/schemas/guide-frontmatter.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};class RBe extends DQ{entityType=tee.entityType;schema=jx;adapter=tee;constructor(e={}){super("guides",Uoi,e,gBe)}getEntityTypeConfig(){return{projectionSourceRole:"primary"}}async getInstructions(){return['Guides (entityType "guide") walk one kind of user through moving into a brain: a writer, researcher, consultant, team, or someone running their own brain.',"A question from someone who describes themselves, their material or how they work, and asks where to start, how to bring their material in, how to run a brain of their own, such as on their own server, or what a brain would do for them, is a guide question, even when it names no guide. A guide question is answered from its guide alone, without searching the docs: the guide links the docs for the details.",`For a guide question, first run system_list with entityType "guide", before asking the network or answering from general knowledge: each guide's metadata says who it is for (persona, for) and what material it moves in. Read the guide that fits the person with system_get, and answer from its stages.`,'Name the guide you answer from by its title, such as "Moving in as a writer", so the reply links to it.'].join(`
8218
8219
  `)}getTemplates(){return joi()}getDataSources(){return[new ree(this.logger.child("GuideDataSource"),this.config),new nee]}}function FBe(e){return new RBe(e)}var qoi=6,Icn=12,LPs=100-2*qoi,zPs=100-qoi-Icn;import{jsx as aN,jsxs as $oi}from"react/jsx-runtime";function dee({prefix:e,name:t,placeholder:i}){return $oi("div",{className:`${e}__ask`,...{[Zb]:"",[uX]:"",...t?{[Goi]:t}:{},...i?{[Hoi]:i}:{}},children:[aN("p",{className:`${e}__ask-status`,role:"status",...{[uee]:""}}),$oi("div",{className:`${e}__composer`,children:[aN("textarea",{rows:1,disabled:!0,"aria-label":"Your question",placeholder:i}),aN("button",{type:"button",className:`${e}__send`,disabled:!0,"aria-label":"Send question",...{[lee]:""},children:aN("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:aN("path",{d:"M12 19V5M5.5 11.5 12 5l6.5 6.5"})})})]})]})}var MBe=String.raw`
8219
8220
  /* On a wide screen the text column is the one scroller beside the drawing,
8220
8221
  and the conversation grows in it instead of scrolling inside a band. */
@@ -9382,7 +9383,7 @@ Guidelines:
9382
9383
  3. Depth: Provide enough detail to be useful as a reference, but stay focused on the topic.
9383
9384
  4. Style: Informative and educational. Write as if explaining to yourself for future reference.
9384
9385
  5. Length: Adjust based on topic complexity - concise for simple topics, more detailed for complex ones.
9385
- 6. No meta-commentary: Just provide the content directly without phrases like "Here is..." or "This note covers..."`});var RRn="Note entities are editable markdown notes. Use them for durable text captures, summaries, and imported markdown; raw files remain document or image entities instead of notes.",eD=Qi(nce(zt({type:"note",purpose:"A short, free-form captured thought, reference, or snippet the user wants to keep.",metadata:Pre,markdown:Rre,config:{projectionSourceRole:"primary",markdownImport:!0},instructions:RRn,displayTitle:({content:e,metadata:t})=>t.titleStated===!0||t.title.trim()&&t.title!=="Untitled"?t.title:K_e(void 0,e),stub:({title:e})=>({content:"",metadata:{title:e,status:"generating",titleStated:!0}}),templates:{generation:X_e},generation:Y_e,create:{fromUpload:qvi},jobs:{"upload-import":Uvi(()=>eD)},evals:{generateNote:async(e,{ai:t})=>t.generate({template:"generation",prompt:l.object({prompt:l.string()}).parse(e).prompt,representedIdentity:"none"},l.object({title:l.string(),body:l.string()}))},atproto:V_e}),[rce(Mre,async({request:e,entities:t})=>{let{id:i,title:r,body:n}=e;if(await t.get(eD,i))return{noteId:i,created:!1};return await t.create(eD,{id:i,content:n,metadata:{title:r,titleStated:!0},visibility:"restricted"}),{noteId:i,created:!0}})]),XC);var FRn=un({id:"note",config:Z_e,entities:[eD]}),Gvi=FRn;var MRn=l.object({type:l.literal("email"),address:l.string().max(0).optional()}).transform(()=>{return}),ORn=l.looseObject({defaultRecipient:MRn.or(Hvi).optional()}),NRn=xi({id:"notifications",config:ORn},{subscriptions:(e)=>{let{config:t}=e,i=Gt(e),{logger:r}=i;return i.answer(Xk,async({request:n})=>{let o=n.recipient??t.defaultRecipient;if(!o)return r.warn(Ore.recipientMissing),{status:"failed",failure:"recipient-missing"};let s=i.deliveryProvider(o.type);if(!s||!await s.isAvailable())return r.warn(Ore.transportMissing,{channelType:o.type}),{status:"failed",failure:"transport-missing"};let a=await s.send({recipient:o.address,subject:n.title,text:n.body,...n.html?{html:n.html}:{},...n.replyTo?{replyTo:n.replyTo}:{},sensitivity:n.sensitivity,idempotencyKey:n.idempotencyKey??crypto.randomUUID()});if(a.status!=="sent"){r.warn(Ore.deliveryFailed,{transportCode:a.failureCode});let c=Wvi.safeParse(a.failureCode);return{status:"failed",failure:"delivery-failed",...c.success&&{transportCode:c.data}}}return a.providerDeliveryId?{status:"sent",deliveryId:a.providerDeliveryId}:{status:"sent"}},{everyProcess:!0}),[]}}),Zvi=NRn;var Kvi=["SKILLS","POSITIONS","EDUCATION","CERTIFICATIONS"],LRn=l.looseObject({elements:l.array(l.looseObject({snapshotDomain:l.string(),snapshotData:l.array(l.record(l.string(),l.unknown()))})),paging:l.looseObject({links:l.array(l.looseObject({rel:l.string().optional(),href:l.string().optional()})).optional()}).optional()}),zRn="https://api.linkedin.com/rest",jRn="202312",Vvi=1000,URn=1000;function qRn(e){return e.toLowerCase().includes("no data found for this memberid")}function $Rn(e,t){let i=e.paging?.links?.find((n)=>n.rel==="next")?.href,r=i?Number(new URL(i,"https://api.linkedin.com").searchParams.get("start")):Number.NaN;return Number.isInteger(r)&&r>t?r:t+1}class OL{accessToken;fetchFn;constructor(e,t=globalThis.fetch){this.accessToken=e,this.fetchFn=t}fetchProfile(){return this.fetchDomain("PROFILE")}fetchDomain(e){return this.fetchPages(e,0,0)}async fetchPages(e,t,i){if(i===Vvi)throw Error(`LinkedIn snapshot exceeded ${Vvi} pages`);let r=await this.fetchPage(e,t),n=(r?.elements??[]).filter((o)=>o.snapshotDomain===e).flatMap((o)=>o.snapshotData);if(!r||n.length===0)return n;return[...n,...await this.fetchPages(e,$Rn(r,t),i+1)]}async fetchPage(e,t){let i=new URL(`${zRn}/memberSnapshotData`);i.searchParams.set("q","criteria"),i.searchParams.set("domain",e),i.searchParams.set("start",String(t));let r=await this.fetchFn(i,{headers:{Authorization:`Bearer ${this.accessToken}`,"Linkedin-Version":jRn}});if(r.ok)return LRn.parse(await r.json());let n=await r.text();if(r.status<500&&qRn(n))return null;throw new Nre(r.status,n.slice(0,URn))}}class Nre extends Error{status;constructor(e,t){super(`LinkedIn snapshot API error: ${e} - ${t}`);this.status=e,this.name="LinkedInApiError"}}var GRn=Yvi({title:"LinkedIn",description:"The LinkedIn connection the LinkedIn import reads your profile with. Connect from the LinkedIn workspace, or paste a member token with the r_dma_portability_3rd_party scope.",schema:l.object({accessToken:l.string().trim().min(1),expiresAt:l.iso.datetime().optional()}),fields:{accessToken:{label:"Access token",secret:!0},expiresAt:{label:"Expires (ISO date and time)"}}});class eTe{registry;registration;constructor(e,t){this.registry=e,this.registration=e.register({ownerPluginId:t.pluginId,packageName:t.packageName,definitionId:"linkedin",definition:GRn})}async get(e){return this.registry.getForActor(this.registration,e)}async save(e,t){await this.registry.save(this.registration.id,e,{accessToken:t.accessToken,expiresAt:t.expiresAt})}async forget(e){await this.registry.delete(this.registration.id,e)}}function tTe(e,t=Date.now()){return e.expiresAt!==void 0&&Date.parse(e.expiresAt)<=t}var HRn="https://www.linkedin.com/oauth/v2/authorization",WRn="https://www.linkedin.com/oauth/v2/accessToken",Jvi="r_dma_portability_3rd_party",ZRn=500,VRn=l.looseObject({access_token:l.string().min(1),expires_in:l.number().int().positive(),scope:l.string().optional()}),KRn=l.looseObject({error:l.string().optional(),error_description:l.string().optional()});async function YRn(e){try{return await e.json()}catch{return null}}class LL{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}authorizationUrl(e){let t=new URL(HRn);return t.searchParams.set("response_type","code"),t.searchParams.set("client_id",this.config.clientId),t.searchParams.set("redirect_uri",this.config.redirectUri),t.searchParams.set("state",e),t.searchParams.set("scope",Jvi),t}async exchange(e,t){let i=await this.fetchFn(WRn,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:e,client_id:this.config.clientId,client_secret:this.config.clientSecret,redirect_uri:this.config.redirectUri}).toString()}),r=await YRn(i);if(!i.ok){let o=KRn.safeParse(r),s=o.success?[o.data.error,o.data.error_description].filter(Boolean).join(": "):"";throw Error(`LinkedIn refused the code (${i.status})${s?`: ${s.slice(0,ZRn)}`:""}`)}let n=VRn.parse(r);if(n.scope!==void 0&&n.scope!==Jvi)throw Error("LinkedIn granted a token without the portability scope");return{accessToken:n.access_token,expiresAt:new Date(t+n.expires_in*1000).toISOString()}}}function Xvi(e){return new NL({...Qvi,now:e})}var Lre="linkedin",JRn=l.strictObject({accessToken:l.string().min(1),expiresAt:l.iso.datetime()});function iTe(e,t={}){let i=(n)=>new LL({...e,redirectUri:n},t.fetch),r=t.now??Date.now;return{id:Lre,authorizationUrl:({redirectUri:n,state:o})=>i(n).authorizationUrl(o),exchange:async({code:n,redirectUri:o})=>{let s=await i(o).exchange(n,r());return{accessToken:s.accessToken,expiresAt:s.expiresAt}}}}class rTe{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}async authorize(e){let t=await this.post(tD.authorizations,{provider:Lre,brainState:e},"the connection");return new URL(e1i.parse(t).authorizationUrl)}async redeem(e){let t=t1i.parse(await this.post(tD.redeem,{provider:Lre,grant:e},"grant redemption"));if(t.provider!==Lre)throw Error("OAuth broker redeemed a grant for another provider");return JRn.parse(t.credential)}async post(e,t,i){let{instanceId:r,secret:n}=this.config,o=await this.fetchFn(new URL(e,this.config.url),{method:"POST",headers:{Accept:"application/json",Authorization:`Basic ${Buffer.from(`${r}:${n}`).toString("base64")}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok)throw Error(`OAuth broker refused ${i} (${o.status})`);return o.json()}}function QRn(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function R6(e,t){return e.map((i)=>QRn(i[t])).find(Boolean)}function i1i(e){let t=[R6(e,"First Name"),R6(e,"Last Name")].filter(Boolean).join(" ")||void 0,i=R6(e,"Websites")?.match(/https?:\/\/[^\s,;]+/)?.[0],r={name:t,headline:R6(e,"Headline"),industry:R6(e,"Industry"),location:R6(e,"Geo Location"),website:i,story:R6(e,"Summary")};return Object.fromEntries(Object.entries(r).filter(([,n])=>n!==void 0))}function r1i(e){if(e.status==="answered")return e.data;if(e.status==="failed")throw new Ni(e.error.code,{message:e.error.message,publicMessage:e.error.message});throw new Ni("no_handler",{message:"No package keeps the anchor profile",publicMessage:"This brain keeps no anchor profile to import into."})}class nTe{messaging;fetchFn;constructor(e,t){this.messaging=e,this.fetchFn=t}async preview(e){return this.previewFields(await this.imported(e))}async apply(e){let t=await this.imported(e),{revision:i}=await this.previewFields(t);return r1i(await this.messaging.request(jL,{fields:t,revision:i}))}async previewFields(e){return r1i(await this.messaging.request(zL,{fields:e}))}async imported(e){let t=new OL(e,this.fetchFn);return i1i(await t.fetchProfile())}}var oTe="/linkedin/oauth/start",qL="/linkedin/oauth/callback",$L="/linkedin/oauth/broker/return";function n1i(e){return e?.permissionLevel==="admin"&&e.isAnchor}function UL(e,t){return new Response(null,{status:e,headers:{"Cache-Control":"no-store",...t?{Location:t}:{}}})}function s1i(e){let t=(c)=>{let u=e.workspaceUrl(),d=u.includes("?")?"&":"?";return UL(303,`${u}${d}connection=${c}`)},i=async(c,u)=>{let d=e.states.take(u),p=await e.resolveSession(c);return d&&n1i(p)&&p?.userId===d?d:null},r=async(c,u)=>{try{return await e.connections.save(c,await u()),t("connected")}catch(d){return e.logger.warn(`LinkedIn connection failed: ${Ee(d)}`),t("failed")}},n=async(c)=>{let u=await e.resolveSession(c);if(!u)return UL(401);if(!n1i(u))return UL(403);let d=e.states.issue(u.userId),{mode:p}=e;if(p.kind==="direct")return UL(302,p.oauth.authorizationUrl(d).toString());try{return UL(302,(await p.broker.authorize(d)).toString())}catch(m){return e.logger.warn(`LinkedIn broker connection failed: ${Ee(m)}`),t("failed")}},o=(c)=>async(u)=>{let d=new URL(u.url).searchParams,p=await i(u,d.get("state")??"");if(!p)return t("failed");if(d.has("error"))return t("declined");let m=d.get("code");if(!m)return t("failed");return r(p,()=>c.exchange(m,e.now()))},s=(c)=>async(u)=>{let d=new URL(u.url).searchParams,p=await i(u,d.get("state")??""),m=o1i.safeParse(Object.fromEntries(d));if(!p||!m.success)return t("failed");if("error"in m.data)return t(m.data.error==="provider_denied"?"declined":"failed");let{grant:h}=m.data;return r(p,()=>c.redeem(h))},{mode:a}=e;return[{path:oTe,method:"GET",public:!0,handler:n},a.kind==="direct"?{path:qL,method:"GET",public:!0,handler:o(a.oauth)}:{path:$L,method:"GET",public:!0,handler:s(a.broker)}]}var XRn=/^(?:jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?|aug(?:ust)?|sep(?:tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)\s+\d{4}$/i,eFn=[[/^$/,"<empty-string>"],[/^urn:/i,"<urn>"],[/^[^\s@]+@[^\s@]+\.[^\s@]+$/,"<email>"],[/^https?:\/\//i,"<url>"],[/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/,"<timestamp>"],[/^\d{4}-\d{2}-\d{2}$/,"<year-month-day>"],[/^\d{4}-\d{2}$/,"<year-month>"],[/^\d{4}$/,"<year>"],[XRn,"<month-year>"]];function l1i(e){if(e===null)return"null";if(Array.isArray(e))return"array";let t=typeof e;return t==="boolean"||t==="number"||t==="object"?t:"string"}function a1i(e){if(typeof e!=="string")return`<${l1i(e)}>`;let t=e.trim();return eFn.find(([i])=>i.test(t))?.[1]??"<string>"}function tFn(e){if(e===null)return null;if(Array.isArray(e))return[...new Set(e.map(a1i))].sort();return a1i(e)}function c1i([e],[t]){return e.localeCompare(t)}function iFn(e){let t=e.flatMap((o)=>Object.entries(o)),r=[...new Set(t.map(([o])=>o))].sort().map((o)=>{let s=t.filter(([a])=>a===o);return{name:o,types:[...new Set(s.map(([,a])=>l1i(a)))].sort(),presentCount:s.length}}),n=new Map(e.map((o)=>{let s=Object.fromEntries(Object.entries(o).sort(c1i).map(([a,c])=>[a,tFn(c)]));return[JSON.stringify(s),s]}));return{recordsRead:e.length,fields:r,recordShapes:[...n].sort(c1i).map(([,o])=>o)}}async function u1i(e){let t=await Promise.all(Kvi.map(async(i)=>[i,iFn(await e.fetchDomain(i))]));return Object.fromEntries(t)}var g1i={name:"Name",headline:"Headline",industry:"Industry",location:"Location",website:"Website",story:"Story"},rFn={fill:"Fill",preserve:"Keep yours",unchanged:"Same"},nFn={connected:{tone:"good",text:"LinkedIn is connected."},declined:{tone:"neutral",text:"LinkedIn connection was declined. Connect again when you are ready."},failed:{tone:"warn",text:"LinkedIn could not be connected. Start the connection again."}},d1i=200,lTe=qi({name:"import-profile",label:"Import from LinkedIn",permission:"admin",confirmation:{kind:"prepared"},input:l.object({}),output:l.object({filled:l.array(l.string()),kept:l.array(l.string())})}),zre=qi({name:"disconnect",label:"Disconnect LinkedIn",permission:"admin",confirmation:{kind:"static",message:"Forget the LinkedIn token? Imported profile values stay; importing again needs a new connection."},input:l.object({}),output:l.object({disconnected:l.boolean()})}),uTe=qi({name:"inspect-shapes",label:"Inspect LinkedIn data shapes",permission:"admin",input:l.object({}),output:l.object({shapes:l.string()})}),dTe=l.object({connection:l.enum(["connected","declined","failed"]).optional()}),oFn=l.object({field:l.enum(["name","headline","industry","location","website","story"]),current:l.string().nullable(),imported:l.string(),outcome:l.enum(["fill","preserve","unchanged"])}),sTe=dTe.shape.connection,sFn=l.discriminatedUnion("status",[l.object({status:l.literal("disconnected"),expired:l.boolean(),startUrl:l.string(),connection:sTe}),l.object({status:l.literal("unavailable"),message:l.string(),startUrl:l.string(),connection:sTe}),l.object({status:l.literal("ready"),fields:l.array(oFn),connection:sTe})]);function p1i(e){if(e===null)return"\u2014";return e.length>d1i?`${e.slice(0,d1i-1)}\u2026`:e}function m1i(e){return e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e.at(-1)}`}function h1i(e,t){return{type:"links",items:[{label:t,target:{external:e}}]}}function aTe(e){let t=e.connection?nFn[e.connection]:null;return t?[{type:"notice",...t}]:[]}var f1i=Go({id:"linkedin",label:"LinkedIn",description:"Fill your profile from LinkedIn without touching what you wrote.",priority:70,permission:"admin",query:dTe,data:sFn,actions:[lTe,zre,uTe],view:({data:e})=>{if(e.status==="disconnected")return{kicker:"Profile import",title:"LinkedIn",description:"Connect your LinkedIn account to fill your profile from it. Only members in the European Economic Area can connect.",status:{label:"Not connected",tone:"neutral"},blocks:[...aTe(e),...e.expired?[{type:"notice",tone:"warn",text:"Your LinkedIn connection expired. Connect again to import."}]:[],h1i(e.startUrl,"Connect LinkedIn")]};if(e.status==="unavailable")return{kicker:"Profile import",title:"LinkedIn",status:{label:"Connection needs attention",tone:"warn"},blocks:[...aTe(e),{type:"notice",tone:"warn",text:e.message},h1i(e.startUrl,"Connect LinkedIn again"),{type:"action",action:zre,input:{}}]};let t=e.fields.some((i)=>i.outcome==="fill");return{kicker:"Profile import",title:"LinkedIn",description:"What LinkedIn holds for each profile field, and what an import would do with it.",status:{label:t?"Ready to import":"Profile already complete",tone:t?"good":"neutral"},...t?{primaryAction:{action:lTe,input:{}}}:{},blocks:[...aTe(e),{type:"table",id:"linkedin-fields",empty:"LinkedIn holds no profile fields for this account.",columns:[{key:"field",label:"Field"},{key:"current",label:"Your profile"},{key:"imported",label:"LinkedIn"},{key:"outcome",label:"Import"}],rows:e.fields.map((i)=>({id:i.field,cells:{field:g1i[i.field],current:p1i(i.current),imported:p1i(i.imported),outcome:rFn[i.outcome]}}))},{type:"card",id:"linkedin-shapes",label:"Data shapes",blocks:[{type:"text",text:"Field names, value types and record forms of your skills, positions, education and certifications on LinkedIn, with every value replaced, for writing import fixtures."},{type:"action",action:uTe,input:{},result:{title:"LinkedIn data shapes",fields:{shapes:{label:"Shapes (JSON)",copyable:!0}}}}]},{type:"action",action:zre,input:{}}]}}});function cTe(e){if(e?.permission!=="admin"||!e.isAnchor)throw new Ni("permission_denied",{publicMessage:"The LinkedIn import belongs to the Anchor alone"});return e.actor.id}function aFn(e){if(e instanceof Nre&&[401,403].includes(e.status))return"LinkedIn refused the connection. It may have been revoked; connect again.";return`LinkedIn could not be read: ${Ee(e)}`}async function y1i(e,t){if(e.executionOnly||!e.studio.isAvailable())return;let i=async(o)=>{let s=await t.connections.get(cTe(o));if(!s||tTe(s))throw new Ni("conflict",{publicMessage:"Connect LinkedIn before importing."});return s},r=x1i({context:e,definition:f1i,bind:(o)=>f1i.bind(o,{load:async({caller:s,query:a})=>{let c=cTe(s),{connection:u}=a.get(dTe),d=await t.connections.get(c);if(!d||tTe(d))return{status:"disconnected",expired:d!==null,startUrl:t.startUrl,connection:u};try{return{status:"ready",fields:(await t.profileImport.preview(d.accessToken)).fields,connection:u}}catch(p){return{status:"unavailable",message:aFn(p),startUrl:t.startUrl,connection:u}}},actions:[lTe.bind(o,async({caller:s})=>t.profileImport.apply((await i(s)).accessToken),async({caller:s})=>{let a=await t.profileImport.preview((await i(s)).accessToken),c=(p)=>a.fields.filter((m)=>m.outcome===p).map((m)=>g1i[m.field].toLowerCase()),u=c("fill"),d=c("preserve");if(u.length===0)throw new Ni("conflict",{publicMessage:"Your profile already has everything LinkedIn holds."});return{summary:`Fill your ${m1i(u)} from LinkedIn?${d.length>0?` Your ${m1i(d)} stay as you wrote them.`:""}`,revision:a.revision}}),uTe.bind(o,async({caller:s})=>{let a=await u1i(t.clientFor((await i(s)).accessToken));return{shapes:JSON.stringify(a,null,2)}}),zre.bind(o,async({caller:s})=>(await t.connections.forget(cTe(s)),{disconnected:!0}))]})}),n=await e.studio.registerWorkspace({...r,accessHandler:async(o)=>o.isAnchor&&await r.accessHandler(o)});return n?n.workspaceUrl:void 0}var pTe={name:"@brains/linkedin-import",license:"AGPL-3.0-only",version:"0.2.0-alpha.698",description:"Import the owner's LinkedIn profile into the anchor profile from Studio",dependencies:{"@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/entity-service":"workspace:*","@brains/eslint-config":"workspace:*","@brains/profile":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0","bun-types":"^1.4.0",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./broker-provider":"./src/broker-provider.ts","./env-schema":"./src/env-schema.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var lFn="/studio",uFn=l.object({clientId:l.string().trim().min(1).describe("LinkedIn app client ID"),clientSecret:l.string().trim().min(1).describe("LinkedIn app client secret"),redirectUri:l.url({protocol:/^https?$/}).describe(`This brain's callback URL ending at ${qL}, registered with the LinkedIn app`)}),dFn=l.object({url:l.url({protocol:/^https$/}).describe("The managed broker's origin"),instanceId:l.string().trim().min(1).describe("This brain's broker instance"),secret:l.string().min(32).describe("This brain's broker instance secret"),returnUri:l.url({protocol:/^https?$/}).describe(`This brain's return URL ending at ${$L}, registered with the broker`)}),pFn=l.object({oauth:uFn.optional().describe("The instance's own LinkedIn app, for direct-mode OAuth"),broker:dFn.optional().describe("The managed broker holding the shared LinkedIn app")});class mTe extends ev{deps;states=Xvi();connections;workspaceUrl=lFn;constructor(e={},t={}){super("linkedin-import",pTe,e,pFn);this.deps=t}async onRegister(e){let{oauth:t,broker:i}=this.config;if(t&&i)throw Error("linkedin-import: configure either oauth (direct) or broker, not both");if(!t&&!i)return;if(t&&new URL(t.redirectUri).pathname!==qL)throw Error(`linkedin-import: oauth.redirectUri must end at ${qL}`);if(i&&new URL(i.returnUri).pathname!==$L)throw Error(`linkedin-import: broker.returnUri must end at ${$L}`);this.connections=new eTe(e.accountSettings,{pluginId:this.id,packageName:pTe.name})}async onRegistrationComplete(e){let t=this.config.oauth?.redirectUri??this.config.broker?.returnUri;if(!t||!this.connections)return;let i=await y1i(e,{profileImport:new nTe(e.messaging,this.deps.fetch),clientFor:(r)=>new OL(r,this.deps.fetch),connections:this.connections,startUrl:new URL(oTe,t).toString()});if(i)this.workspaceUrl=i}getWebRoutes(){let e=this.consentMode(),t=this.connections;if(!e||!t)return[];return s1i({mode:e,states:this.states,connections:t,resolveSession:async(i)=>this.getContext().auth.get()?.resolveSession(i),workspaceUrl:()=>this.workspaceUrl,now:this.deps.now??Date.now,logger:this.logger})}consentMode(){let{oauth:e,broker:t}=this.config;if(e)return{kind:"direct",oauth:new LL(e,this.deps.fetch)};if(t)return{kind:"broker",broker:new rTe(t,this.deps.fetch)};return null}}function hTe(e={},t={}){return new mTe(e,t)}import{createHash as mFn,timingSafeEqual as hFn}from"crypto";function b1i(e){return mFn("sha256").update(e).digest()}function fFn(e){if(!e?.startsWith("Basic "))return null;let t=Buffer.from(e.slice(6),"base64").toString("utf8"),i=t.indexOf(":");if(i<=0||i===t.length-1)return null;return{id:t.slice(0,i),secret:t.slice(i+1)}}class fTe{instances;constructor(e){this.instances=new Map(e.map((t)=>[t.id,{id:t.id,returnUris:{...t.returnUris},secretHash:b1i(t.secret)}]))}authenticate(e){let t=fFn(e.headers.get("authorization")),i=t?this.instances.get(t.id):void 0;if(!t||!i)return null;return hFn(b1i(t.secret),i.secretHash)?{id:i.id,returnUris:i.returnUris}:null}}var xFn=10,gFn=600000,gTe={"Cache-Control":"no-store","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff"};function iw(e,t=200){return Response.json(e,{status:t,headers:gTe})}function E1i(){return Response.json({error:"Broker instance authentication required"},{status:401,headers:{...gTe,"WWW-Authenticate":'Basic realm="oauth-broker"'}})}async function A1i(e){if(!e.headers.get("content-type")?.startsWith("application/json"))return;try{return await e.json()}catch{return}}function jre(e,t){let i=new URL(e.returnUri);return i.searchParams.set("provider",e.provider),i.searchParams.set("state",e.brainState),Object.entries(t).forEach(([r,n])=>i.searchParams.set(r,n)),new Response(null,{status:303,headers:{...gTe,Location:i.toString()}})}function S1i(e){let t=new Map(e.providers.map((c)=>[c.id,c])),i=new Map,r=(c)=>{let u=e.now(),d=(i.get(c)??[]).filter((m)=>m>u-gFn),p=d.length<xFn;return i.set(c,p?[...d,u]:d),p},n=(c)=>new URL(xTe(c),e.publicUrl).toString(),o=async(c)=>{let u=e.instances.authenticate(c);if(!u)return E1i();let d=v1i.safeParse(await A1i(c));if(!d.success)return iw({error:"Invalid authorization request"},400);let p=t.get(d.data.provider),m=u.returnUris[d.data.provider];if(!p||!m)return iw({error:"Provider is unavailable for this instance"},400);if(!r(u.id))return iw({error:"Too many connections started; try later"},429);let h=e.authorizations.issue({provider:p.id,instanceId:u.id,returnUri:m,brainState:d.data.brainState}),f=p.authorizationUrl({redirectUri:n(p.id),state:h}).toString();return iw({authorizationUrl:f})},s=async(c)=>{let u=e.instances.authenticate(c);if(!u)return E1i();let d=w1i.safeParse(await A1i(c));if(!d.success)return iw({error:"Invalid grant redemption request"},400);let{provider:p}=d.data,m=e.grants.take(d.data.grant,(h)=>h.provider===p&&h.instanceId===u.id);if(!m)return iw({error:"Invalid or expired grant"},400);return iw({provider:p,credential:m.credential})},a=(c)=>async(u)=>{let d=new URL(u.url).searchParams,p=e.authorizations.take(d.get("state")??"",(h)=>h.provider===c.id);if(!p)return iw({error:"Invalid, expired or used authorization"},400);if(d.has("error"))return jre(p,{error:"provider_denied"});let m=d.get("code")?.trim();if(!m)return jre(p,{error:"authorization_incomplete"});try{let h=await c.exchange({code:m,redirectUri:n(c.id)}),f=e.grants.issue({provider:c.id,instanceId:p.instanceId,credential:h});return jre(p,{grant:f})}catch(h){return e.logger.warn(`OAuth broker exchange for ${c.id} failed: ${Ee(h)}`),jre(p,{error:"credential_exchange_failed"})}};return[{path:tD.authorizations,method:"POST",public:!0,handler:o},{path:tD.redeem,method:"POST",public:!0,handler:s},...e.providers.map((c)=>({path:xTe(c.id),method:"GET",public:!0,handler:a(c)}))]}var k1i={name:"@brains/oauth-broker",license:"AGPL-3.0-only",version:"0.2.0-alpha.698",description:"Managed OAuth broker: one central callback per provider, one-time grants for instance brains",dependencies:{"@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0","bun-types":"^1.4.0",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var bFn=600000,EFn=120000,B1i=1000,AFn=l.object({clientId:l.string().trim().min(1),clientSecret:l.string().trim().min(1)}),vFn=l.object({id:l.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/),secret:l.string().min(32).describe("Revocable instance secret"),returnUris:l.record(yTe,l.url({protocol:/^https?$/})).describe("Per provider, the one address the browser returns to")}),wFn=l.object({publicUrl:l.url({protocol:/^https?$/}).describe("The broker's public origin, where provider callbacks land"),providers:l.record(yTe,AFn).default({}).describe("Per provider, the shared app the broker holds"),instances:l.array(vFn).default([])});class bTe extends ev{deps;routes=[];authorizations;grants;constructor(e,t){super("oauth-broker",k1i,e,wFn);this.deps=t,this.authorizations=new NL({ttlMs:bFn,maxPending:B1i,now:t.now}),this.grants=new NL({ttlMs:EFn,maxPending:B1i,now:t.now})}async onRegister(e){let t=Object.entries(this.config.providers).map(([i,r])=>{let n=this.deps.providers[i];if(!n)throw Error(`oauth-broker: no adapter for provider "${i}"`);let o=n(r);if(o.id!==i)throw Error(`oauth-broker: adapter for "${i}" reports provider "${o.id}"`);return o});if(this.config.instances.length===0||t.length===0)return;this.routes=S1i({publicUrl:this.config.publicUrl,providers:t,instances:new fTe(this.config.instances),authorizations:this.authorizations,grants:this.grants,now:this.deps.now??Date.now,logger:this.logger})}getWebRoutes(){return this.routes}}function ETe(e,t){return new bTe(e,t)}import{existsSync as RFn,mkdirSync as FFn,readFileSync as MFn,renameSync as OFn,rmSync as NFn,writeFileSync as LFn}from"fs";import{join as mg}from"path";var ATe=l.object({baseFolder:l.string().default("_obsidian")});function SFn(e){let t=RJ(e);if(t==="enum"){let i=MJ(e);return i?{type:"enum",enumValues:i}:{type:"enum"}}if(t==="literal")return{type:"string",defaultValue:OJ(e)};if(t==="string")return{type:"string"};if(t==="number")return{type:"number"};if(t==="boolean")return{type:"boolean"};if(t==="array")return{type:"array"};if(t==="date")return{type:"date"};return{type:"unknown"}}function C1i(e){let t=[];for(let[i,r]of Object.entries(e.shape)){if(VM(r)?.studioWidget==="hidden")continue;let{inner:n,required:o,defaultValue:s}=FJ(r),a=SFn(n),c={name:i,type:a.type,required:o},u=s!==void 0?s:a.defaultValue;if(u!==void 0)c.defaultValue=u;if(a.enumValues)c.enumValues=a.enumValues;t.push(c)}return t}function kFn(e,t){if(e.name==="entityType")return String(e.defaultValue??t);if(e.name==="title")return'"{{title}}"';if(e.type==="date"&&(e.name==="created"||e.name==="updated"))return'"{{date}}"';if(e.defaultValue!==void 0){if(Array.isArray(e.defaultValue))return"[]";if(typeof e.defaultValue==="boolean")return String(e.defaultValue);if(typeof e.defaultValue==="number")return String(e.defaultValue);return String(e.defaultValue)}if(e.type==="enum"&&e.enumValues&&e.enumValues.length>0)return e.enumValues[0]??"";switch(e.type){case"string":return'""';case"number":return"";case"boolean":return"false";case"array":return"[]";case"date":return'""';default:return'""'}}function D1i(e,t,i=""){let r=["---"];for(let n of t){let o=kFn(n,e);if(o==="")r.push(`${n.name}:`);else r.push(`${n.name}: ${o}`)}if(r.push("---"),r.push(""),i)r.push(i);else r.push("<!-- Write your content here -->"),r.push("");return r.join(`
9386
+ 6. No meta-commentary: Just provide the content directly without phrases like "Here is..." or "This note covers..."`});var RRn="Note entities are editable markdown notes. Use them for durable text captures, summaries, and imported markdown; raw files remain document or image entities instead of notes.",eD=Qi(nce(zt({type:"note",purpose:"A short, free-form captured thought, reference, or snippet the user wants to keep.",metadata:Pre,markdown:Rre,config:{projectionSourceRole:"primary",markdownImport:!0},instructions:RRn,displayTitle:({content:e,metadata:t})=>t.titleStated===!0||t.title.trim()&&t.title!=="Untitled"?t.title:K_e(void 0,e),stub:({title:e})=>({content:"",metadata:{title:e,status:"generating",titleStated:!0}}),templates:{generation:X_e},generation:Y_e,create:{fromUpload:qvi},jobs:{"upload-import":Uvi(()=>eD)},evals:{generateNote:async(e,{ai:t})=>t.generate({template:"generation",prompt:l.object({prompt:l.string()}).parse(e).prompt,representedIdentity:"none"},l.object({title:l.string(),body:l.string()}))},atproto:V_e}),[rce(Mre,async({request:e,entities:t})=>{let{id:i,title:r,body:n}=e;if(await t.get(eD,i))return{noteId:i,created:!1};return await t.create(eD,{id:i,content:n,metadata:{title:r,titleStated:!0},visibility:"restricted"}),{noteId:i,created:!0}})]),XC);var FRn=un({id:"note",config:Z_e,entities:[eD]}),Gvi=FRn;var MRn=l.object({type:l.literal("email"),address:l.string().max(0).optional()}).transform(()=>{return}),ORn=l.looseObject({defaultRecipient:MRn.or(Hvi).optional()}),NRn=xi({id:"notifications",config:ORn},{subscriptions:(e)=>{let{config:t}=e,i=Gt(e),{logger:r}=i;return i.answer(Xk,async({request:n})=>{let o=n.recipient??t.defaultRecipient;if(!o)return r.warn(Ore.recipientMissing),{status:"failed",failure:"recipient-missing"};let s=i.deliveryProvider(o.type);if(!s||!await s.isAvailable())return r.warn(Ore.transportMissing,{channelType:o.type}),{status:"failed",failure:"transport-missing"};let a=await s.send({recipient:o.address,subject:n.title,text:n.body,...n.html?{html:n.html}:{},...n.replyTo?{replyTo:n.replyTo}:{},sensitivity:n.sensitivity,idempotencyKey:n.idempotencyKey??crypto.randomUUID()});if(a.status!=="sent"){r.warn(Ore.deliveryFailed,{transportCode:a.failureCode});let c=Wvi.safeParse(a.failureCode);return{status:"failed",failure:"delivery-failed",...c.success&&{transportCode:c.data}}}return a.providerDeliveryId?{status:"sent",deliveryId:a.providerDeliveryId}:{status:"sent"}},{everyProcess:!0}),[]}}),Zvi=NRn;var Kvi=["SKILLS","POSITIONS","EDUCATION","CERTIFICATIONS"],LRn=l.looseObject({elements:l.array(l.looseObject({snapshotDomain:l.string(),snapshotData:l.array(l.record(l.string(),l.unknown()))})),paging:l.looseObject({links:l.array(l.looseObject({rel:l.string().optional(),href:l.string().optional()})).optional()}).optional()}),zRn="https://api.linkedin.com/rest",jRn="202312",Vvi=1000,URn=1000;function qRn(e){return e.toLowerCase().includes("no data found for this memberid")}function $Rn(e,t){let i=e.paging?.links?.find((n)=>n.rel==="next")?.href,r=i?Number(new URL(i,"https://api.linkedin.com").searchParams.get("start")):Number.NaN;return Number.isInteger(r)&&r>t?r:t+1}class OL{accessToken;fetchFn;constructor(e,t=globalThis.fetch){this.accessToken=e,this.fetchFn=t}fetchProfile(){return this.fetchDomain("PROFILE")}fetchDomain(e){return this.fetchPages(e,0,0)}async fetchPages(e,t,i){if(i===Vvi)throw Error(`LinkedIn snapshot exceeded ${Vvi} pages`);let r=await this.fetchPage(e,t),n=(r?.elements??[]).filter((o)=>o.snapshotDomain===e).flatMap((o)=>o.snapshotData);if(!r||n.length===0)return n;return[...n,...await this.fetchPages(e,$Rn(r,t),i+1)]}async fetchPage(e,t){let i=new URL(`${zRn}/memberSnapshotData`);i.searchParams.set("q","criteria"),i.searchParams.set("domain",e),i.searchParams.set("start",String(t));let r=await this.fetchFn(i,{headers:{Authorization:`Bearer ${this.accessToken}`,"Linkedin-Version":jRn}});if(r.ok)return LRn.parse(await r.json());let n=await r.text();if(r.status<500&&qRn(n))return null;throw new Nre(r.status,n.slice(0,URn))}}class Nre extends Error{status;constructor(e,t){super(`LinkedIn snapshot API error: ${e} - ${t}`);this.status=e,this.name="LinkedInApiError"}}var GRn=Yvi({title:"LinkedIn",description:"The LinkedIn connection the LinkedIn import reads your profile with. Connect from the LinkedIn workspace, or paste a member token with the r_dma_portability_3rd_party scope.",schema:l.object({accessToken:l.string().trim().min(1),expiresAt:l.iso.datetime().optional()}),fields:{accessToken:{label:"Access token",secret:!0},expiresAt:{label:"Expires (ISO date and time)"}}});class eTe{registry;registration;constructor(e,t){this.registry=e,this.registration=e.register({ownerPluginId:t.pluginId,packageName:t.packageName,definitionId:"linkedin",definition:GRn})}async get(e){return this.registry.getForActor(this.registration,e)}async save(e,t){await this.registry.save(this.registration.id,e,{accessToken:t.accessToken,expiresAt:t.expiresAt})}async forget(e){await this.registry.delete(this.registration.id,e)}}function tTe(e,t=Date.now()){return e.expiresAt!==void 0&&Date.parse(e.expiresAt)<=t}var HRn="https://www.linkedin.com/oauth/v2/authorization",WRn="https://www.linkedin.com/oauth/v2/accessToken",Jvi="r_dma_portability_3rd_party",ZRn=500,VRn=l.looseObject({access_token:l.string().min(1),expires_in:l.number().int().positive(),scope:l.string().optional()}),KRn=l.looseObject({error:l.string().optional(),error_description:l.string().optional()});async function YRn(e){try{return await e.json()}catch{return null}}class LL{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}authorizationUrl(e){let t=new URL(HRn);return t.searchParams.set("response_type","code"),t.searchParams.set("client_id",this.config.clientId),t.searchParams.set("redirect_uri",this.config.redirectUri),t.searchParams.set("state",e),t.searchParams.set("scope",Jvi),t}async exchange(e,t){let i=await this.fetchFn(WRn,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:e,client_id:this.config.clientId,client_secret:this.config.clientSecret,redirect_uri:this.config.redirectUri}).toString()}),r=await YRn(i);if(!i.ok){let o=KRn.safeParse(r),s=o.success?[o.data.error,o.data.error_description].filter(Boolean).join(": "):"";throw Error(`LinkedIn refused the code (${i.status})${s?`: ${s.slice(0,ZRn)}`:""}`)}let n=VRn.parse(r);if(n.scope!==void 0&&n.scope!==Jvi)throw Error("LinkedIn granted a token without the portability scope");return{accessToken:n.access_token,expiresAt:new Date(t+n.expires_in*1000).toISOString()}}}function Xvi(e){return new NL({...Qvi,now:e})}var Lre="linkedin",JRn=l.strictObject({accessToken:l.string().min(1),expiresAt:l.iso.datetime()});function iTe(e,t={}){let i=(n)=>new LL({...e,redirectUri:n},t.fetch),r=t.now??Date.now;return{id:Lre,authorizationUrl:({redirectUri:n,state:o})=>i(n).authorizationUrl(o),exchange:async({code:n,redirectUri:o})=>{let s=await i(o).exchange(n,r());return{accessToken:s.accessToken,expiresAt:s.expiresAt}}}}class rTe{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}async authorize(e){let t=await this.post(tD.authorizations,{provider:Lre,brainState:e},"the connection");return new URL(e1i.parse(t).authorizationUrl)}async redeem(e){let t=t1i.parse(await this.post(tD.redeem,{provider:Lre,grant:e},"grant redemption"));if(t.provider!==Lre)throw Error("OAuth broker redeemed a grant for another provider");return JRn.parse(t.credential)}async post(e,t,i){let{instanceId:r,secret:n}=this.config,o=await this.fetchFn(new URL(e,this.config.url),{method:"POST",headers:{Accept:"application/json",Authorization:`Basic ${Buffer.from(`${r}:${n}`).toString("base64")}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok)throw Error(`OAuth broker refused ${i} (${o.status})`);return o.json()}}function QRn(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function R6(e,t){return e.map((i)=>QRn(i[t])).find(Boolean)}function i1i(e){let t=[R6(e,"First Name"),R6(e,"Last Name")].filter(Boolean).join(" ")||void 0,i=R6(e,"Websites")?.match(/https?:\/\/[^\s,;]+/)?.[0],r={name:t,headline:R6(e,"Headline"),industry:R6(e,"Industry"),location:R6(e,"Geo Location"),website:i,story:R6(e,"Summary")};return Object.fromEntries(Object.entries(r).filter(([,n])=>n!==void 0))}function r1i(e){if(e.status==="answered")return e.data;if(e.status==="failed")throw new Ni(e.error.code,{message:e.error.message,publicMessage:e.error.message});throw new Ni("no_handler",{message:"No package keeps the anchor profile",publicMessage:"This brain keeps no anchor profile to import into."})}class nTe{messaging;fetchFn;constructor(e,t){this.messaging=e,this.fetchFn=t}async preview(e){return this.previewFields(await this.imported(e))}async apply(e){let t=await this.imported(e),{revision:i}=await this.previewFields(t);return r1i(await this.messaging.request(jL,{fields:t,revision:i}))}async previewFields(e){return r1i(await this.messaging.request(zL,{fields:e}))}async imported(e){let t=new OL(e,this.fetchFn);return i1i(await t.fetchProfile())}}var oTe="/linkedin/oauth/start",qL="/linkedin/oauth/callback",$L="/linkedin/oauth/broker/return";function n1i(e){return e?.permissionLevel==="admin"&&e.isAnchor}function UL(e,t){return new Response(null,{status:e,headers:{"Cache-Control":"no-store",...t?{Location:t}:{}}})}function s1i(e){let t=(c)=>{let u=e.workspaceUrl(),d=u.includes("?")?"&":"?";return UL(303,`${u}${d}connection=${c}`)},i=async(c,u)=>{let d=e.states.take(u),p=await e.resolveSession(c);return d&&n1i(p)&&p?.userId===d?d:null},r=async(c,u)=>{try{return await e.connections.save(c,await u()),t("connected")}catch(d){return e.logger.warn(`LinkedIn connection failed: ${Ee(d)}`),t("failed")}},n=async(c)=>{let u=await e.resolveSession(c);if(!u)return UL(401);if(!n1i(u))return UL(403);let d=e.states.issue(u.userId),{mode:p}=e;if(p.kind==="direct")return UL(302,p.oauth.authorizationUrl(d).toString());try{return UL(302,(await p.broker.authorize(d)).toString())}catch(m){return e.logger.warn(`LinkedIn broker connection failed: ${Ee(m)}`),t("failed")}},o=(c)=>async(u)=>{let d=new URL(u.url).searchParams,p=await i(u,d.get("state")??"");if(!p)return t("failed");if(d.has("error"))return t("declined");let m=d.get("code");if(!m)return t("failed");return r(p,()=>c.exchange(m,e.now()))},s=(c)=>async(u)=>{let d=new URL(u.url).searchParams,p=await i(u,d.get("state")??""),m=o1i.safeParse(Object.fromEntries(d));if(!p||!m.success)return t("failed");if("error"in m.data)return t(m.data.error==="provider_denied"?"declined":"failed");let{grant:h}=m.data;return r(p,()=>c.redeem(h))},{mode:a}=e;return[{path:oTe,method:"GET",public:!0,handler:n},a.kind==="direct"?{path:qL,method:"GET",public:!0,handler:o(a.oauth)}:{path:$L,method:"GET",public:!0,handler:s(a.broker)}]}var XRn=/^(?:jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?|aug(?:ust)?|sep(?:tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)\s+\d{4}$/i,eFn=[[/^$/,"<empty-string>"],[/^urn:/i,"<urn>"],[/^[^\s@]+@[^\s@]+\.[^\s@]+$/,"<email>"],[/^https?:\/\//i,"<url>"],[/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/,"<timestamp>"],[/^\d{4}-\d{2}-\d{2}$/,"<year-month-day>"],[/^\d{4}-\d{2}$/,"<year-month>"],[/^\d{4}$/,"<year>"],[XRn,"<month-year>"]];function l1i(e){if(e===null)return"null";if(Array.isArray(e))return"array";let t=typeof e;return t==="boolean"||t==="number"||t==="object"?t:"string"}function a1i(e){if(typeof e!=="string")return`<${l1i(e)}>`;let t=e.trim();return eFn.find(([i])=>i.test(t))?.[1]??"<string>"}function tFn(e){if(e===null)return null;if(Array.isArray(e))return[...new Set(e.map(a1i))].sort();return a1i(e)}function c1i([e],[t]){return e.localeCompare(t)}function iFn(e){let t=e.flatMap((o)=>Object.entries(o)),r=[...new Set(t.map(([o])=>o))].sort().map((o)=>{let s=t.filter(([a])=>a===o);return{name:o,types:[...new Set(s.map(([,a])=>l1i(a)))].sort(),presentCount:s.length}}),n=new Map(e.map((o)=>{let s=Object.fromEntries(Object.entries(o).sort(c1i).map(([a,c])=>[a,tFn(c)]));return[JSON.stringify(s),s]}));return{recordsRead:e.length,fields:r,recordShapes:[...n].sort(c1i).map(([,o])=>o)}}async function u1i(e){let t=await Promise.all(Kvi.map(async(i)=>[i,iFn(await e.fetchDomain(i))]));return Object.fromEntries(t)}var g1i={name:"Name",headline:"Headline",industry:"Industry",location:"Location",website:"Website",story:"Story"},rFn={fill:"Fill",preserve:"Keep yours",unchanged:"Same"},nFn={connected:{tone:"good",text:"LinkedIn is connected."},declined:{tone:"neutral",text:"LinkedIn connection was declined. Connect again when you are ready."},failed:{tone:"warn",text:"LinkedIn could not be connected. Start the connection again."}},d1i=200,lTe=qi({name:"import-profile",label:"Import from LinkedIn",permission:"admin",confirmation:{kind:"prepared"},input:l.object({}),output:l.object({filled:l.array(l.string()),kept:l.array(l.string())})}),zre=qi({name:"disconnect",label:"Disconnect LinkedIn",permission:"admin",confirmation:{kind:"static",message:"Forget the LinkedIn token? Imported profile values stay; importing again needs a new connection."},input:l.object({}),output:l.object({disconnected:l.boolean()})}),uTe=qi({name:"inspect-shapes",label:"Inspect LinkedIn data shapes",permission:"admin",input:l.object({}),output:l.object({shapes:l.string()})}),dTe=l.object({connection:l.enum(["connected","declined","failed"]).optional()}),oFn=l.object({field:l.enum(["name","headline","industry","location","website","story"]),current:l.string().nullable(),imported:l.string(),outcome:l.enum(["fill","preserve","unchanged"])}),sTe=dTe.shape.connection,sFn=l.discriminatedUnion("status",[l.object({status:l.literal("disconnected"),expired:l.boolean(),startUrl:l.string(),connection:sTe}),l.object({status:l.literal("unavailable"),message:l.string(),startUrl:l.string(),connection:sTe}),l.object({status:l.literal("ready"),fields:l.array(oFn),connection:sTe})]);function p1i(e){if(e===null)return"\u2014";return e.length>d1i?`${e.slice(0,d1i-1)}\u2026`:e}function m1i(e){return e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e.at(-1)}`}function h1i(e,t){return{type:"links",items:[{label:t,target:{external:e}}]}}function aTe(e){let t=e.connection?nFn[e.connection]:null;return t?[{type:"notice",...t}]:[]}var f1i=Go({id:"linkedin",label:"LinkedIn",description:"Fill your profile from LinkedIn without touching what you wrote.",priority:70,permission:"admin",query:dTe,data:sFn,actions:[lTe,zre,uTe],view:({data:e})=>{if(e.status==="disconnected")return{kicker:"Profile import",title:"LinkedIn",description:"Connect your LinkedIn account to fill your profile from it. Only members in the European Economic Area can connect.",status:{label:"Not connected",tone:"neutral"},blocks:[...aTe(e),...e.expired?[{type:"notice",tone:"warn",text:"Your LinkedIn connection expired. Connect again to import."}]:[],h1i(e.startUrl,"Connect LinkedIn")]};if(e.status==="unavailable")return{kicker:"Profile import",title:"LinkedIn",status:{label:"Connection needs attention",tone:"warn"},blocks:[...aTe(e),{type:"notice",tone:"warn",text:e.message},h1i(e.startUrl,"Connect LinkedIn again"),{type:"action",action:zre,input:{}}]};let t=e.fields.some((i)=>i.outcome==="fill");return{kicker:"Profile import",title:"LinkedIn",description:"What LinkedIn holds for each profile field, and what an import would do with it.",status:{label:t?"Ready to import":"Profile already complete",tone:t?"good":"neutral"},...t?{primaryAction:{action:lTe,input:{}}}:{},blocks:[...aTe(e),{type:"table",id:"linkedin-fields",empty:"LinkedIn holds no profile fields for this account.",columns:[{key:"field",label:"Field"},{key:"current",label:"Your profile"},{key:"imported",label:"LinkedIn"},{key:"outcome",label:"Import"}],rows:e.fields.map((i)=>({id:i.field,cells:{field:g1i[i.field],current:p1i(i.current),imported:p1i(i.imported),outcome:rFn[i.outcome]}}))},{type:"card",id:"linkedin-shapes",label:"Data shapes",blocks:[{type:"text",text:"Field names, value types and record forms of your skills, positions, education and certifications on LinkedIn, with every value replaced, for writing import fixtures."},{type:"action",action:uTe,input:{},result:{title:"LinkedIn data shapes",fields:{shapes:{label:"Shapes (JSON)",copyable:!0}}}}]},{type:"action",action:zre,input:{}}]}}});function cTe(e){if(e?.permission!=="admin"||!e.isAnchor)throw new Ni("permission_denied",{publicMessage:"The LinkedIn import belongs to the Anchor alone"});return e.actor.id}function aFn(e){if(e instanceof Nre&&[401,403].includes(e.status))return"LinkedIn refused the connection. It may have been revoked; connect again.";return`LinkedIn could not be read: ${Ee(e)}`}async function y1i(e,t){if(e.executionOnly||!e.studio.isAvailable())return;let i=async(o)=>{let s=await t.connections.get(cTe(o));if(!s||tTe(s))throw new Ni("conflict",{publicMessage:"Connect LinkedIn before importing."});return s},r=x1i({context:e,definition:f1i,bind:(o)=>f1i.bind(o,{load:async({caller:s,query:a})=>{let c=cTe(s),{connection:u}=a.get(dTe),d=await t.connections.get(c);if(!d||tTe(d))return{status:"disconnected",expired:d!==null,startUrl:t.startUrl,connection:u};try{return{status:"ready",fields:(await t.profileImport.preview(d.accessToken)).fields,connection:u}}catch(p){return{status:"unavailable",message:aFn(p),startUrl:t.startUrl,connection:u}}},actions:[lTe.bind(o,async({caller:s})=>t.profileImport.apply((await i(s)).accessToken),async({caller:s})=>{let a=await t.profileImport.preview((await i(s)).accessToken),c=(p)=>a.fields.filter((m)=>m.outcome===p).map((m)=>g1i[m.field].toLowerCase()),u=c("fill"),d=c("preserve");if(u.length===0)throw new Ni("conflict",{publicMessage:"Your profile already has everything LinkedIn holds."});return{summary:`Fill your ${m1i(u)} from LinkedIn?${d.length>0?` Your ${m1i(d)} stay as you wrote them.`:""}`,revision:a.revision}}),uTe.bind(o,async({caller:s})=>{let a=await u1i(t.clientFor((await i(s)).accessToken));return{shapes:JSON.stringify(a,null,2)}}),zre.bind(o,async({caller:s})=>(await t.connections.forget(cTe(s)),{disconnected:!0}))]})}),n=await e.studio.registerWorkspace({...r,accessHandler:async(o)=>o.isAnchor&&await r.accessHandler(o)});return n?n.workspaceUrl:void 0}var pTe={name:"@brains/linkedin-import",license:"AGPL-3.0-only",version:"0.2.0-alpha.699",description:"Import the owner's LinkedIn profile into the anchor profile from Studio",dependencies:{"@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/entity-service":"workspace:*","@brains/eslint-config":"workspace:*","@brains/profile":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0","bun-types":"^1.4.0",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./broker-provider":"./src/broker-provider.ts","./env-schema":"./src/env-schema.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var lFn="/studio",uFn=l.object({clientId:l.string().trim().min(1).describe("LinkedIn app client ID"),clientSecret:l.string().trim().min(1).describe("LinkedIn app client secret"),redirectUri:l.url({protocol:/^https?$/}).describe(`This brain's callback URL ending at ${qL}, registered with the LinkedIn app`)}),dFn=l.object({url:l.url({protocol:/^https$/}).describe("The managed broker's origin"),instanceId:l.string().trim().min(1).describe("This brain's broker instance"),secret:l.string().min(32).describe("This brain's broker instance secret"),returnUri:l.url({protocol:/^https?$/}).describe(`This brain's return URL ending at ${$L}, registered with the broker`)}),pFn=l.object({oauth:uFn.optional().describe("The instance's own LinkedIn app, for direct-mode OAuth"),broker:dFn.optional().describe("The managed broker holding the shared LinkedIn app")});class mTe extends ev{deps;states=Xvi();connections;workspaceUrl=lFn;constructor(e={},t={}){super("linkedin-import",pTe,e,pFn);this.deps=t}async onRegister(e){let{oauth:t,broker:i}=this.config;if(t&&i)throw Error("linkedin-import: configure either oauth (direct) or broker, not both");if(!t&&!i)return;if(t&&new URL(t.redirectUri).pathname!==qL)throw Error(`linkedin-import: oauth.redirectUri must end at ${qL}`);if(i&&new URL(i.returnUri).pathname!==$L)throw Error(`linkedin-import: broker.returnUri must end at ${$L}`);this.connections=new eTe(e.accountSettings,{pluginId:this.id,packageName:pTe.name})}async onRegistrationComplete(e){let t=this.config.oauth?.redirectUri??this.config.broker?.returnUri;if(!t||!this.connections)return;let i=await y1i(e,{profileImport:new nTe(e.messaging,this.deps.fetch),clientFor:(r)=>new OL(r,this.deps.fetch),connections:this.connections,startUrl:new URL(oTe,t).toString()});if(i)this.workspaceUrl=i}getWebRoutes(){let e=this.consentMode(),t=this.connections;if(!e||!t)return[];return s1i({mode:e,states:this.states,connections:t,resolveSession:async(i)=>this.getContext().auth.get()?.resolveSession(i),workspaceUrl:()=>this.workspaceUrl,now:this.deps.now??Date.now,logger:this.logger})}consentMode(){let{oauth:e,broker:t}=this.config;if(e)return{kind:"direct",oauth:new LL(e,this.deps.fetch)};if(t)return{kind:"broker",broker:new rTe(t,this.deps.fetch)};return null}}function hTe(e={},t={}){return new mTe(e,t)}import{createHash as mFn,timingSafeEqual as hFn}from"crypto";function b1i(e){return mFn("sha256").update(e).digest()}function fFn(e){if(!e?.startsWith("Basic "))return null;let t=Buffer.from(e.slice(6),"base64").toString("utf8"),i=t.indexOf(":");if(i<=0||i===t.length-1)return null;return{id:t.slice(0,i),secret:t.slice(i+1)}}class fTe{instances;constructor(e){this.instances=new Map(e.map((t)=>[t.id,{id:t.id,returnUris:{...t.returnUris},secretHash:b1i(t.secret)}]))}authenticate(e){let t=fFn(e.headers.get("authorization")),i=t?this.instances.get(t.id):void 0;if(!t||!i)return null;return hFn(b1i(t.secret),i.secretHash)?{id:i.id,returnUris:i.returnUris}:null}}var xFn=10,gFn=600000,gTe={"Cache-Control":"no-store","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff"};function iw(e,t=200){return Response.json(e,{status:t,headers:gTe})}function E1i(){return Response.json({error:"Broker instance authentication required"},{status:401,headers:{...gTe,"WWW-Authenticate":'Basic realm="oauth-broker"'}})}async function A1i(e){if(!e.headers.get("content-type")?.startsWith("application/json"))return;try{return await e.json()}catch{return}}function jre(e,t){let i=new URL(e.returnUri);return i.searchParams.set("provider",e.provider),i.searchParams.set("state",e.brainState),Object.entries(t).forEach(([r,n])=>i.searchParams.set(r,n)),new Response(null,{status:303,headers:{...gTe,Location:i.toString()}})}function S1i(e){let t=new Map(e.providers.map((c)=>[c.id,c])),i=new Map,r=(c)=>{let u=e.now(),d=(i.get(c)??[]).filter((m)=>m>u-gFn),p=d.length<xFn;return i.set(c,p?[...d,u]:d),p},n=(c)=>new URL(xTe(c),e.publicUrl).toString(),o=async(c)=>{let u=e.instances.authenticate(c);if(!u)return E1i();let d=v1i.safeParse(await A1i(c));if(!d.success)return iw({error:"Invalid authorization request"},400);let p=t.get(d.data.provider),m=u.returnUris[d.data.provider];if(!p||!m)return iw({error:"Provider is unavailable for this instance"},400);if(!r(u.id))return iw({error:"Too many connections started; try later"},429);let h=e.authorizations.issue({provider:p.id,instanceId:u.id,returnUri:m,brainState:d.data.brainState}),f=p.authorizationUrl({redirectUri:n(p.id),state:h}).toString();return iw({authorizationUrl:f})},s=async(c)=>{let u=e.instances.authenticate(c);if(!u)return E1i();let d=w1i.safeParse(await A1i(c));if(!d.success)return iw({error:"Invalid grant redemption request"},400);let{provider:p}=d.data,m=e.grants.take(d.data.grant,(h)=>h.provider===p&&h.instanceId===u.id);if(!m)return iw({error:"Invalid or expired grant"},400);return iw({provider:p,credential:m.credential})},a=(c)=>async(u)=>{let d=new URL(u.url).searchParams,p=e.authorizations.take(d.get("state")??"",(h)=>h.provider===c.id);if(!p)return iw({error:"Invalid, expired or used authorization"},400);if(d.has("error"))return jre(p,{error:"provider_denied"});let m=d.get("code")?.trim();if(!m)return jre(p,{error:"authorization_incomplete"});try{let h=await c.exchange({code:m,redirectUri:n(c.id)}),f=e.grants.issue({provider:c.id,instanceId:p.instanceId,credential:h});return jre(p,{grant:f})}catch(h){return e.logger.warn(`OAuth broker exchange for ${c.id} failed: ${Ee(h)}`),jre(p,{error:"credential_exchange_failed"})}};return[{path:tD.authorizations,method:"POST",public:!0,handler:o},{path:tD.redeem,method:"POST",public:!0,handler:s},...e.providers.map((c)=>({path:xTe(c.id),method:"GET",public:!0,handler:a(c)}))]}var k1i={name:"@brains/oauth-broker",license:"AGPL-3.0-only",version:"0.2.0-alpha.699",description:"Managed OAuth broker: one central callback per provider, one-time grants for instance brains",dependencies:{"@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0","bun-types":"^1.4.0",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var bFn=600000,EFn=120000,B1i=1000,AFn=l.object({clientId:l.string().trim().min(1),clientSecret:l.string().trim().min(1)}),vFn=l.object({id:l.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/),secret:l.string().min(32).describe("Revocable instance secret"),returnUris:l.record(yTe,l.url({protocol:/^https?$/})).describe("Per provider, the one address the browser returns to")}),wFn=l.object({publicUrl:l.url({protocol:/^https?$/}).describe("The broker's public origin, where provider callbacks land"),providers:l.record(yTe,AFn).default({}).describe("Per provider, the shared app the broker holds"),instances:l.array(vFn).default([])});class bTe extends ev{deps;routes=[];authorizations;grants;constructor(e,t){super("oauth-broker",k1i,e,wFn);this.deps=t,this.authorizations=new NL({ttlMs:bFn,maxPending:B1i,now:t.now}),this.grants=new NL({ttlMs:EFn,maxPending:B1i,now:t.now})}async onRegister(e){let t=Object.entries(this.config.providers).map(([i,r])=>{let n=this.deps.providers[i];if(!n)throw Error(`oauth-broker: no adapter for provider "${i}"`);let o=n(r);if(o.id!==i)throw Error(`oauth-broker: adapter for "${i}" reports provider "${o.id}"`);return o});if(this.config.instances.length===0||t.length===0)return;this.routes=S1i({publicUrl:this.config.publicUrl,providers:t,instances:new fTe(this.config.instances),authorizations:this.authorizations,grants:this.grants,now:this.deps.now??Date.now,logger:this.logger})}getWebRoutes(){return this.routes}}function ETe(e,t){return new bTe(e,t)}import{existsSync as RFn,mkdirSync as FFn,readFileSync as MFn,renameSync as OFn,rmSync as NFn,writeFileSync as LFn}from"fs";import{join as mg}from"path";var ATe=l.object({baseFolder:l.string().default("_obsidian")});function SFn(e){let t=RJ(e);if(t==="enum"){let i=MJ(e);return i?{type:"enum",enumValues:i}:{type:"enum"}}if(t==="literal")return{type:"string",defaultValue:OJ(e)};if(t==="string")return{type:"string"};if(t==="number")return{type:"number"};if(t==="boolean")return{type:"boolean"};if(t==="array")return{type:"array"};if(t==="date")return{type:"date"};return{type:"unknown"}}function C1i(e){let t=[];for(let[i,r]of Object.entries(e.shape)){if(VM(r)?.studioWidget==="hidden")continue;let{inner:n,required:o,defaultValue:s}=FJ(r),a=SFn(n),c={name:i,type:a.type,required:o},u=s!==void 0?s:a.defaultValue;if(u!==void 0)c.defaultValue=u;if(a.enumValues)c.enumValues=a.enumValues;t.push(c)}return t}function kFn(e,t){if(e.name==="entityType")return String(e.defaultValue??t);if(e.name==="title")return'"{{title}}"';if(e.type==="date"&&(e.name==="created"||e.name==="updated"))return'"{{date}}"';if(e.defaultValue!==void 0){if(Array.isArray(e.defaultValue))return"[]";if(typeof e.defaultValue==="boolean")return String(e.defaultValue);if(typeof e.defaultValue==="number")return String(e.defaultValue);return String(e.defaultValue)}if(e.type==="enum"&&e.enumValues&&e.enumValues.length>0)return e.enumValues[0]??"";switch(e.type){case"string":return'""';case"number":return"";case"boolean":return"false";case"array":return"[]";case"date":return'""';default:return'""'}}function D1i(e,t,i=""){let r=["---"];for(let n of t){let o=kFn(n,e);if(o==="")r.push(`${n.name}:`);else r.push(`${n.name}: ${o}`)}if(r.push("---"),r.push(""),i)r.push(i);else r.push("<!-- Write your content here -->"),r.push("");return r.join(`
9386
9387
  `)}var BFn={string:"Input",number:"Number",boolean:"Boolean",date:"Date",enum:"Select",array:"Multi",unknown:"Input"};function CFn(e){let t={name:e.name,id:e.name,type:BFn[e.type]};if(e.type==="enum"&&e.enumValues){let i={};e.enumValues.forEach((r,n)=>{i[String(n)]=r}),t.options=i}return t}function I1i(e,t){let i={filesPaths:e,fields:t.map(CFn)};return`---
9387
9388
  ${iD(i)}---
9388
9389
  `}var DFn=new Set(["entityType"]),T1i={base:"Notes"};function IFn(e){return T1i[e]??_1i(e)}function P1i(e){let t=T1i[e];if(t)return t;let i=e.split("-").map((n)=>n.charAt(0).toUpperCase()+n.slice(1)),r=i.pop();return[...i,...r?[dx(r)]:[]].join(" ")}var _Fn=new Set(["note"]);function TFn(e){let t=["file.name"];for(let i of e)if(!DFn.has(i.name))t.push(i.name);return t}function PFn(e){return e.some((t)=>t.name==="status"&&t.type==="enum")}function Ure(e,t,i=IFn(e)){let r=PFn(t),n=TFn(t),o=[{type:"table",name:`All ${i}`,order:n}];if(r)o.push({type:"table",name:"By Status",groupBy:{property:"status",direction:"ASC"},order:n});let a={filters:{and:[_Fn.has(e)?'file.folder == "/"':`file.inFolder("${e}")`]},views:o};return{filename:`${i}.base`,content:iD(a),hasStatus:r}}function R1i(e){if(e.length===0)return null;let t=e.map((r)=>`file.inFolder("${r}")`),i={filters:{and:[t.length===1?t[0]:{or:t}]},views:[{type:"table",name:"Settings",order:["file.name","file.folder"]}]};return iD(i)}function F1i(e){if(e.length===0)return null;let t=e.map((r)=>`file.inFolder("${r.entityType}")`),i={filters:{and:[t.length===1?t[0]:{or:t},'status != "published"']},views:[{type:"table",name:"Pipeline",groupBy:{property:"status",direction:"ASC"},order:["file.name","file.folder","status"]}]};return iD(i)}var zFn={mkdir:FFn,writeFile:LFn,existsFile:RFn,readFile:(e)=>MFn(e,"utf8"),renameFile:OFn,removeFile:(e)=>NFn(e,{force:!0})};function jFn(e,t,i,r,n){let{deps:o,logger:s}=e,a=Ure(t,i,P1i(t)),c=mg(r,a.filename);if(c===n||!o.existsFile(c)||o.existsFile(n))return;if(o.readFile(c)===a.content)o.writeFile(n,Ure(t,i).content),o.removeFile(c);else o.renameFile(c,n);s.info(`Renamed base ${a.filename} to its current name`)}function M1i(e){let{shapes:t,dataDir:i,config:r,deps:n,logger:o,filterTypes:s}=e,a=t.types(),c=s?a.filter((R)=>s.includes(R)):a,u=mg(i,r.baseFolder),d=mg(u,"templates"),p=mg(u,"fileClasses"),m=mg(u,"bases");n.mkdir(d,{recursive:!0}),n.mkdir(p,{recursive:!0}),n.mkdir(m,{recursive:!0});let h=[],f=[],g=[],y=[],b=[],v=[];for(let R of c){let O=t.frontmatterSchema(R);if(!O){o.debug(`Skipping ${R}: no frontmatter schema`),f.push(R);continue}let k=C1i(O),j=I1i(R,k);if(n.writeFile(mg(p,`${R}.md`),j),g.push(R),t.isSingleton(R)){b.push(R),o.debug(`Generated fileClass (singleton): ${R}`);continue}let L=D1i(R,k,t.bodyTemplate(R));n.writeFile(mg(d,`${R}.md`),L),h.push(R);let q=Ure(R,k),K=mg(m,q.filename);if(jFn(e,R,k,m,K),!n.existsFile(K))n.writeFile(K,q.content),y.push(R),o.debug(`Generated base: ${q.filename}`);if(q.hasStatus)v.push({entityType:R,fields:k});o.debug(`Generated template + fileClass: ${R}`)}let w=R1i(b);if(w){let R=mg(m,"Settings.base");if(!n.existsFile(R))n.writeFile(R,w),y.push("Settings"),o.debug("Generated Settings.base")}let D=F1i(v);if(D){let R=mg(m,"Pipeline.base");if(!n.existsFile(R))n.writeFile(R,D),y.push("Pipeline"),o.debug("Generated Pipeline.base")}return o.info(`Synced ${h.length} templates, ${g.length} fileClasses, ${y.length} bases (${f.length} skipped)`),{generated:h,skipped:f,fileClasses:g,bases:y}}function O1i(e={}){let t={...zFn,...e};return xi({id:"obsidian-vault",config:ATe},{subscriptions:(i)=>{let{config:r}=i,{logger:n,entityShapes:o,dataDir:s,ready:a}=Gt(i);return a(()=>{n.info("Auto-syncing Obsidian templates, fileClasses, and bases");try{M1i({shapes:o,dataDir:s,config:r,deps:t,logger:n})}catch(c){n.error("Failed to sync",{error:c})}}),[]}})}var UFn=O1i(),vTe=UFn;var rD=l.enum(["draft","active","archived"]),nD=l.enum(["admin","trusted","public"]),qre=l.enum(["agent-confirmed","manual"]),qFn=l.enum(["draft","active","archived"]),$Fn=l.enum(["admin","trusted","public"]),GFn=l.enum(["agent-confirmed","manual"]);function N1i(){return l.codec(l.string().optional(),l.string().min(1).optional(),{decode:(e)=>e?.trim().length===0?void 0:e,encode:(e)=>e})}var hg=N1i(),EE=N1i(),wTe=l.object({event:l.string().min(1),target:l.string().min(1),operatorAction:l.boolean().optional(),label:EE,description:EE,operatorDescription:EE}),$re=l.enum(["reply"]),GL=l.object({id:l.string().min(1),title:l.string().min(1),prompt:EE,requiredDetails:l.array(l.string().min(1)).default([]),instructions:l.array(l.string().min(1)).default([]),doneWhen:l.array(l.string().min(1)).default([]),provenBy:l.array($re).min(1).optional(),transitions:l.array(wTe).default([])}),Gre=l.object({purpose:l.string().min(1),operatingRules:l.array(l.string().min(1)).default([]),initialState:l.string().min(1),states:l.array(GL).min(1),finalStates:l.array(l.string().min(1)).min(1),nextPrompts:l.array(l.string().min(1)).default([])}),AE=l.object({title:l.string(),status:rD.default("active"),audience:nD.default("admin"),trigger:hg.optional(),lifecycle:hg.optional(),once:l.boolean().optional(),starterText:hg.optional(),description:hg.optional(),starterPrompt:hg.optional(),completionMode:qre.default("agent-confirmed")}),Hre=l.object({title:l.string(),status:rD,audience:nD,trigger:hg.optional(),lifecycle:hg.optional(),once:l.boolean().optional(),starterText:hg.optional(),description:hg.optional(),starterPrompt:hg.optional(),completionMode:qre}),HFn=l.object({title:l.string(),status:qFn,audience:$Fn,trigger:EE.optional(),lifecycle:EE.optional(),once:l.boolean().optional(),starterText:EE.optional(),description:EE.optional(),starterPrompt:EE.optional(),completionMode:GFn}),L1i=Mi.extend({entityType:l.literal("playbook"),metadata:HFn});class Wre extends k0{constructor(){super(Gre,{title:"Playbook",mappings:[{key:"purpose",label:"Purpose",type:"string"},{key:"operatingRules",label:"Operating Rules",type:"array",itemType:"string"},{key:"initialState",label:"Initial State",type:"string"},{key:"states",label:"States",type:"array",itemType:"object",itemMappings:[{key:"id",label:"ID",type:"string"},{key:"title",label:"Title",type:"string"},{key:"prompt",label:"Prompt",type:"custom",formatter:STe,parser:kTe},{key:"requiredDetails",label:"Required Details",type:"array",itemType:"string"},{key:"instructions",label:"Instructions",type:"array",itemType:"string"},{key:"doneWhen",label:"Done When",type:"array",itemType:"string"},{key:"provenBy",label:"Proven By",type:"custom",formatter:WFn,parser:ZFn},{key:"transitions",label:"Transitions",type:"array",itemType:"object",itemMappings:[{key:"event",label:"Event",type:"string"},{key:"target",label:"Target",type:"string"},{key:"operatorAction",label:"User Choice",type:"custom",formatter:VFn,parser:KFn},{key:"label",label:"Label",type:"custom",formatter:STe,parser:kTe},{key:"description",label:"Description",type:"string"},{key:"operatorDescription",label:"Operator Description",type:"custom",formatter:STe,parser:kTe}]}]},{key:"finalStates",label:"Final States",type:"array",itemType:"string"},{key:"nextPrompts",label:"Next Prompts",type:"array",itemType:"string"}]})}}var Zre=new Wre;function STe(e){return typeof e==="string"?e:""}function kTe(e){let t=e.trim();return t.length>0?t:void 0}function WFn(e){return Array.isArray(e)?e.join(", "):""}function ZFn(e){let t=e.split(",").map((i)=>i.trim()).filter((i)=>i.length>0);return t.length>0?t:void 0}function VFn(e){return typeof e==="boolean"?String(e):""}function KFn(e){let t=e.trim().toLowerCase();if(t==="true")return!0;if(t==="false")return!1;return}function BTe(e){let t=[],i=new Set,r=new Set;for(let n of e.states){if(i.has(n.id))r.add(n.id);i.add(n.id)}if(!i.has(e.initialState))t.push(`Playbook initial state '${e.initialState}' is not defined.`);for(let n of r)t.push(`Duplicate playbook state id '${n}'.`);for(let n of e.finalStates)if(!i.has(n))t.push(`Playbook final state '${n}' is not defined.`);for(let n of e.states)for(let o of n.transitions)if(!i.has(o.target))t.push(`Playbook transition '${n.id}' -> '${o.target}' targets an undefined state.`);for(let n of YFn(e,i))t.push(`Playbook state '${n}' is unreachable.`);return{valid:t.length===0,errors:t}}function oD(e){let t=BTe(e);if(!t.valid)throw Error(t.errors.join(`
@@ -10186,7 +10187,7 @@ html[data-theme="light"] .kmap-label--zone {
10186
10187
  .knowledge-map-site__links a:hover { color: var(--console-accent); }
10187
10188
  .knowledge-map-site__links a:last-child { color: var(--console-accent); }
10188
10189
  `;function LUn(e){let t=e.cap??Y6.cap,i=e.headingLead??Y6.headingLead,r=e.headingAccent??Y6.headingAccent,n=e.intro??Y6.intro,o=e.primaryCta??Y6.primaryCta,s=e.secondaryCta??Y6.secondaryCta,a=e.proofLinks??Y6.proofLinks,c={points:e.points,zones:e.zones,counts:e.counts};return aw("section",{className:"knowledge-map-site",id:"knowledge",children:[ff("style",{children:NUn+BD}),aw("div",{className:"knowledge-map-site__grid",children:[aw("div",{children:[ff("p",{className:"knowledge-map-site__cap",children:t}),aw("h2",{className:"knowledge-map-site__heading",children:[i," ",ff("em",{children:r})]}),ff("p",{className:"knowledge-map-site__intro",children:n}),aw("div",{className:"knowledge-map-site__ctas",children:[ff("a",{className:"knowledge-map-site__cta",href:o.href,children:o.label}),ff("a",{className:"knowledge-map-site__cta--quiet",href:s.href,children:s.label})]})]}),aw("div",{children:[ff(coe,{data:c,surface:"site"}),aw("div",{className:"knowledge-map-site__foot",children:[aw("span",{children:[ff("b",{children:e.counts.entities})," entities \xB7"," ",ff("b",{children:e.counts.topics})," topics"]}),ff("span",{className:"knowledge-map-site__links",children:a.map((u)=>ff("a",{href:u.href,children:u.label},u.href))})]})]})]})]})}var zUn=new k0(a6i,{title:"Knowledge",mappings:[{key:"cap",label:"Cap",type:"string"},{key:"headingLead",label:"Heading Lead",type:"string"},{key:"headingAccent",label:"Heading Accent",type:"string"},{key:"intro",label:"Intro",type:"string"},{key:"primaryCta",label:"Primary Cta",type:"object",children:[{key:"label",label:"Label",type:"string"},{key:"href",label:"Href",type:"string"}]},{key:"secondaryCta",label:"Secondary Cta",type:"object",children:[{key:"label",label:"Label",type:"string"},{key:"href",label:"Href",type:"string"}]},{key:"proofLinks",label:"Links",type:"array",itemType:"object",itemMappings:[{key:"label",label:"Label",type:"string"},{key:"href",label:"Href",type:"string"}]}]});function URe(){return nt({name:"knowledge-map",description:"The brain's corpus in semantic space \u2014 topic territories, published lights, honest counts",schema:OUn,dataSourceId:LRe,overlayFormatter:zUn,requiredPermission:"public",layout:{component:LUn}})}var jUn=120,c6i=160;function DD(e,t){let i=`${e}:${t}`;return i.length<=jUn?i:`${e}:${sr(t).slice(0,24)}`}function l6i(e){return e.length<=c6i?e:`${e.slice(0,c6i-1)}\u2026`}var qRe=Nn({id:zRe,title:"Knowledge Map",group:"knowledge",placement:"primary",priority:30,permission:"public",data:K6,digest:({data:e})=>({items:[{label:"Entities",value:String(e.counts.entities)},{label:"Topics",value:String(e.counts.topics)}]}),view:({data:e})=>({blocks:[{type:"spatial",layout:"cartesian",id:"knowledge-map",label:"Knowledge map",description:`${e.counts.entities} projected entities arranged around ${e.counts.topics} topic zones. Published work, skills, high-signal knowledge, and background sources remain available in the text detail for this map.`,points:e.points.map((t)=>({id:DD(t.entityType,t.id),label:l6i(t.title),category:t.kind==="pearl"?"high-signal":t.kind,x:t.x,y:t.y,...t.zoneId?{zoneId:DD("topic",t.zoneId)}:{},tone:t.kind==="published"?"good":t.kind==="pearl"?"warn":"neutral",details:[t.entityType]})),zones:e.zones.map((t)=>({id:DD("topic",t.id),label:l6i(t.name),x:t.x,y:t.y,memberIds:e.points.filter((i)=>t.memberIds.includes(i.id)).map((i)=>DD(i.entityType,i.id))})),relationships:e.zones.flatMap((t)=>e.points.filter((i)=>i.zoneId===t.id).map((i)=>({sourceId:DD("topic",t.id),targetId:DD(i.entityType,i.id),tone:"neutral"}))),legend:[{label:"Published",tone:"good"},{label:"Skill",tone:"neutral"},{label:"High signal",tone:"warn"},{label:"Background",tone:"neutral"},{label:"Topic zone",tone:"neutral"}]}]})});var UUn=l.object({});function u6i(e,t){return{entityService:e,semantic:{project:(i)=>e.projectSemanticSpace(i)},sourceTypes:t}}var qUn=xi({id:"knowledge-map",config:UUn},{subscriptions:(e)=>{let{messaging:t}=e,i=Gt(e),r=async()=>{let n=await t.request(eoe,{});return n.status==="answered"?n.data.types:[]};return i.dataSource({id:toe,name:"Knowledge Map DataSource",description:"Builds the public knowledge map: the corpus in semantic space with topic territories",fetch:async(n,{corpus:o})=>roe(u6i(o,r),"public")}),i.template(toe,URe()),i.dashboardWidget({definition:qRe,render:{component:s6i,clientStyles:BD},load:async({corpus:n,visibilityScope:o,signal:s})=>{s.throwIfAborted();let a=await roe(u6i(n,r),o);return s.throwIfAborted(),a}}),[]}}),$Re=qUn;var $Un=l.strictObject({source:T2,item:Cj}),HRe=l.strictObject({source:T2,error:l.literal("Source unavailable")}),WRe=l.strictObject({entries:l.array($Un).max(1e4),errors:l.array(HRe).max(1000)}),loe={sourceId:GE.optional(),urgency:Sw.optional(),facets:wI.optional(),limit:l.number().int().min(1).max(100).default(50)},ZRe=l.strictObject(loe).superRefine((e,t)=>{if(e.facets!==void 0&&e.sourceId===void 0)t.addIssue({code:"custom",path:["sourceId"],message:"Inbox facet filters require a source"})}),p6i=l.strictObject({title:l.string().trim().min(1).max(160),summary:l.string().trim().min(1).max(1000).optional(),contact:sae.optional(),receivedAt:l.iso.datetime(),urgency:Sw}),m6i=l.strictObject({source:T2,item:p6i}),uoe=l.strictObject({entries:l.array(m6i).max(100),errors:l.array(HRe).max(1000),total:l.number().int().nonnegative()});function mz(e,t){return`${e}:${t}`}function ID(e){let t=e.indexOf(":");if(t<=0||t===e.length-1)return;return{sourceId:e.slice(0,t),itemId:e.slice(t+1)}}var h6i=l.preprocess(p0,l.number().int().min(0).max(1e4)),f6i=l.preprocess(p0,l.number().int().min(1).max(100)),x6i=l.string().trim().min(3).max(400),hz=l.strictObject({sourceId:GE.optional(),urgency:Sw.optional(),facets:wI.optional(),selected:x6i.optional(),offset:h6i.default(0),limit:f6i.default(10)}).superRefine((e,t)=>{if(e.selected!==void 0&&!ID(e.selected))t.addIssue({code:"custom",path:["selected"],message:"Inbox selection must be a sourceId:itemId row key"})});function d6i(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)?Object.fromEntries(Object.entries(e)):{}}function g6i(e,t){let i=d6i(e),r=GE.safeParse(i.sourceId),n=r.success?t.find((g)=>g.sourceId===r.data):void 0,o=Sw.safeParse(i.urgency),s=h6i.safeParse(i.offset),a=f6i.safeParse(i.limit),c=x6i.safeParse(i.selected),u=c.success?ID(c.data):void 0,d=u?t.find((g)=>g.sourceId===u.sourceId):void 0,p=u?jg.safeParse(u.itemId):void 0,m=Object.fromEntries(Object.entries(i).flatMap(([g,y])=>g.startsWith("facet.")?[[g.slice(6),y]]:[])),h=d6i(i.facets),f=n?b6i(Object.keys(h).length>0?h:m,n):void 0;return hz.parse({...n?{sourceId:n.sourceId}:{},...o.success?{urgency:o.data}:{},...f?{facets:f}:{},...d&&p?.success?{selected:mz(d.sourceId,p.data)}:{},offset:s.success?s.data:0,limit:a.success?a.data:10})}function y6i(e,t){let i=e.sourceId?t.find((n)=>n.sourceId===e.sourceId):void 0,r=i&&e.facets?b6i(e.facets,i):void 0;return{...e.sourceId?{sourceId:e.sourceId}:{},...e.urgency?{urgency:e.urgency}:{},...r?{facets:r}:{},limit:e.limit}}var GUn=l.strictObject({source:lae,open:l.number().int().nonnegative(),high:l.number().int().nonnegative(),available:l.boolean()}),HUn=Cj.transform(({followUps:e,...t})=>t),WUn=l.string().trim().min(1).max(2048).refine(tqn,{message:"Invalid contact target"}),GRe=l.strictObject({source:T2,item:HUn,detailAvailable:l.boolean(),contactHref:WUn.optional(),followUps:l.array(uae).max(100)}),VRe=l.strictObject({summary:l.strictObject({open:l.number().int().nonnegative(),high:l.number().int().nonnegative()}),sources:l.array(GUn).max(1000),entries:l.array(GRe).max(100),selectedEntry:GRe.optional(),errors:l.array(HRe).max(1000),total:l.number().int().nonnegative(),offset:l.number().int().nonnegative(),limit:l.number().int().min(1).max(100)}),ZUn=l.strictObject({sourceLabel:l.string().trim().min(1).max(200),urgency:Sw,title:l.string().trim().min(1).max(500),receivedAt:l.iso.datetime()}),KRe=l.strictObject({summary:l.strictObject({open:l.number().int().nonnegative(),high:l.number().int().nonnegative(),availableSources:l.number().int().nonnegative(),unavailableSources:l.number().int().nonnegative()}),entries:l.array(ZUn).max(5)}),VUn=l.strictObject({sourceId:GE,itemId:jg,actionId:GE,confirmed:l.boolean().default(!1)}),KUn=l.strictObject({type:l.literal("detail"),sourceId:GE,itemId:jg}),YRe=l.discriminatedUnion("kind",[l.strictObject({kind:l.literal("detail"),detail:cae}),l.strictObject({kind:l.literal("detail-unavailable"),error:l.literal("Original content is unavailable")})]),YUn=l.strictObject({kind:l.literal("confirmation"),summary:l.string().min(1).max(300)}),JUn=l.strictObject({kind:l.literal("completed")}),QUn=l.strictObject({kind:l.literal("error"),error:l.enum(["Invalid inbox action","Inbox action failed"])}),XUn=l.union([YUn,JUn,QUn]),eqn=kI(uoe);function b6i(e,t){let i=Object.fromEntries((t.facets??[]).flatMap((r)=>{let n=e[r.key];return typeof n==="string"&&r.values.some((o)=>o.value===n)?[[r.key,n]]:[]}));return Object.keys(i).length>0?wI.parse(i):void 0}function tqn(e){if(!e.startsWith("/")||e.startsWith("//")||e.includes("\\")||/[\p{Cc}\p{Cf}]/u.test(e))return!1;try{return new URL(e,"https://brains.invalid").origin==="https://brains.invalid"}catch{return!1}}function iqn(e){return e>0?[{type:"notice",tone:"warn",text:`${e} ${e===1?"source is":"sources are"} temporarily unavailable.`}]:[]}var JRe=Nn({id:"inbox",title:"Inbox",description:"Live attention across source-owned workflows",group:"communication",placement:"primary",priority:10,permission:"admin",data:KRe,digest:({data:e})=>({items:[{label:"Open",value:String(e.summary.open),...e.summary.open>0?{tone:"warn"}:{}},{label:"High priority",value:String(e.summary.high),...e.summary.high>0?{tone:"warn"}:{}},{label:"Sources online",value:`${e.summary.availableSources}/${e.summary.availableSources+e.summary.unavailableSources}`}],attention:e.summary.high}),view:({data:e})=>({blocks:[{type:"stats",items:[{label:"Open",value:e.summary.open},{label:"High priority",value:e.summary.high,tone:e.summary.high>0?"warn":"neutral"},{label:"Sources online",value:e.summary.availableSources},{label:"Sources unavailable",value:e.summary.unavailableSources,tone:e.summary.unavailableSources>0?"warn":"good"}]},{type:"list",id:"inbox-entries",empty:"Inbox clear \u2014 no source needs attention.",items:e.entries.map((t,i)=>({id:`${i}:${t.receivedAt}:${t.sourceLabel.slice(0,70)}`,title:t.title,metadata:[t.sourceLabel,t.receivedAt],badges:[{label:t.urgency,tone:t.urgency==="high"?"warn":"neutral"}]}))},...iqn(e.summary.unavailableSources),{type:"links",items:[{label:"Open Inbox",target:{launch:{target:"inbox"}}}]}]})});async function QRe(e,t){t.throwIfAborted();let i=await e.dashboard();return t.throwIfAborted(),i}class doe{registry;inFlight;constructor(e){this.registry=e}async getInboxData(){return this.inFlight??=this.loadProjection().finally(()=>{this.inFlight=void 0}),this.inFlight}async loadProjection(){let e=this.registry.listSources(),t=await Promise.allSettled(e.map(async(n)=>({source:n,items:await n.list()}))),i=[],r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n];if(!o||!s)continue;let a=XRe(s);if(o.status==="rejected"){r.push({source:a,error:"Source unavailable"});continue}for(let c of o.value.items)i.push({source:a,item:c})}return i.sort(rqn),r.sort((n,o)=>n.source.sourceId.localeCompare(o.source.sourceId)),WRe.parse({entries:i,errors:r})}}function XRe(e){return{sourceId:e.sourceId,displayName:e.displayName}}function rqn(e,t){return E6i(e.item.urgency)-E6i(t.item.urgency)||t.item.receivedAt.localeCompare(e.item.receivedAt)||e.source.sourceId.localeCompare(t.source.sourceId)||e.item.id.localeCompare(t.item.id)}function E6i(e){return e==="high"?0:1}var nqn=3,oqn=10;function A6i(e,t){if(e.entries.length===0)return;let i=e.entries.filter((u)=>u.item.urgency==="high").length,r=sqn(e.entries),n=r.slice(0,oqn),o=[`${e.entries.length} open attention ${eFe(e.entries.length,"item")} \xB7 ${i} high priority`];for(let u of n){let d=u.entries.filter((p)=>p.item.urgency==="high");o.push("",`${u.displayName} \u2014 ${u.entries.length} open \xB7 ${d.length} high`,...d.slice(0,nqn).map((p)=>`- ${p.item.title}`))}let s=r.length-n.length;if(s>0)o.push("",`+${s} more ${eFe(s,"source")}`);let a=e.errors.length;return o.push("",`${a>0?`${a} ${eFe(a,"source")} unavailable. `:""}Open Inbox: ${t.destinationUrl}`),{dedupeKey:`unified-inbox:daily-digest:${(t.now?.()??new Date).toISOString().slice(0,10)}`,title:`Inbox digest \u2014 ${e.entries.length} open`,body:o.join(`
10189
- `)}}function tFe(e,t,i={}){e.recurringCheck({id:"daily-digest",cadence:"daily",includeInInbox:!1,run:async({signal:r})=>{r.throwIfAborted();let n=await t.getInboxData();r.throwIfAborted();let o=typeof i.workspaceUrl==="function"?i.workspaceUrl():i.workspaceUrl,s=A6i(n,{destinationUrl:aqn(e,o),...i.now?{now:i.now}:{}});return{alerts:s?[s]:[]}}})}function sqn(e){let t=new Map;for(let i of e){let r=i.source.sourceId,n=t.get(r)??{displayName:i.source.displayName,entries:[]};n.entries.push(i),t.set(r,n)}return[...t.values()]}function eFe(e,t){return e===1?t:dx(t)}function aqn(e,t){let i=t??e.routeByRole("dashboard")?.fullPath??"/dashboard";return Uh(i,e.siteUrl)}var cqn=l.looseObject(loe);function iFe(e,t){return Ug({name:"inbox_list",description:"List live content-safe operator attention across registered inbox sources, optionally filtered by source, urgency, or source-declared facets",input:cqn,output:uoe,permission:"admin",sideEffects:"none",execute:async({input:i})=>{if(t.toolCall()?.userPermissionLevel!=="admin")throw new Ni("permission_denied",{publicMessage:"Unified inbox requires admin permission"});let r=ZRe.safeParse(i);if(!r.success)throw new Ni("invalid_input",{publicMessage:"Invalid unified inbox filters"});try{return await e.list(r.data)}catch(n){throw new Ni("handler_failed",{publicMessage:"Unified inbox list failed",cause:n})}}},{bareName:!0})}var lqn=l.object({id:l.string().trim().min(1).max(120),label:l.string().trim().min(1).max(200),confirmation:l.literal("prepared").optional()}),uqn=l.object({sourceId:l.string().trim().min(1).max(120),itemId:l.string().trim().min(1).max(500),capability:lqn}),dqn=l.object({kind:l.literal("completed")}),fz=qi({name:"run-inbox-action",label:"Run inbox action",catalog:!0,permission:"admin",confirmation:{kind:"prepared",conditional:!0},input:uqn,output:dqn}),v6i=4000,pqn=zt({type:"person",purpose:"A known person associated with operator work",metadata:l.object({})});function mqn(e){if(typeof e!=="object"||e===null||Array.isArray(e))return e;let t={},i={};for(let[r,n]of Object.entries(e))if(r.startsWith("facet."))i[r.slice(6)]=n;else t[r]=n;return{...t,...Object.keys(i).length>0?{facets:i}:{}}}var S6i=l.preprocess(mqn,hz),hqn=l.object({query:hz,snapshot:VRe,detail:YRe.optional()});function fqn(e){let t=e.source.displayName;if(!e.available)return`${t} \xB7 unavailable`;return e.high>0?`${t} \xB7 ${e.high} high`:t}function w6i(e){return e.item.actions.map((t)=>{let i={id:t.id,label:t.label,...t.confirm===!0?{confirmation:"prepared"}:{}};return{action:fz,capability:i,input:{sourceId:e.source.sourceId,itemId:e.item.id,capability:i}}})}function xqn(e){let t=e.item.entityRef,i=[];if(e.item.contact?.personId)i.push({label:`Open contact ${e.item.contact.label}`,target:{entity:pqn,id:e.item.contact.personId}});for(let r of e.followUps)if(r.kind==="discuss-in-chat")i.push({label:r.label,target:{launch:{target:"inbox-discuss-in-chat",sourceId:e.source.sourceId,itemId:e.item.id,label:e.item.title}}});else if(r.kind==="open-entity"&&t)i.push({label:r.label,target:{launch:{target:"inbox-open-entity",entityType:t.entityType,entityId:t.entityId}}});else if(r.kind==="capture-as-note"&&t)i.push({label:r.label,target:{launch:{target:"inbox-capture-note",title:e.item.title,...e.item.summary?{summary:e.item.summary}:{},entityType:t.entityType,entityId:t.entityId}}});return i}function gqn(e){return{type:"card",id:"inbox-detail-follow-ups",label:"Follow up",blocks:[{type:"links",id:"inbox-follow-up-links",items:e}]}}function yqn(e){return{type:"card",id:"inbox-detail-actions",label:"Available actions",blocks:[{type:"actions",id:"inbox-action-controls",items:e}]}}function bqn(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return e;return t.toISOString()}var xz=Go({id:"inbox",label:"Inbox",priority:20,permission:"admin",query:S6i,data:hqn,actions:[fz],badge:({data:e})=>e.snapshot.summary.open,view:({data:e})=>{let{query:t,snapshot:i}=e,r=i.sources.filter((f)=>f.available).length,n=i.sources.find((f)=>f.source.sourceId===t.sourceId),o=[{key:"sourceId",label:"Source",value:t.sourceId,allLabel:"All sources",options:i.sources.map((f)=>({value:f.source.sourceId,label:fqn(f),count:f.open}))},{key:"urgency",label:"Urgency",value:t.urgency,allLabel:"All urgency",options:[{value:"high",label:"High priority",count:i.summary.high},{value:"normal",label:"Normal"}]},...(n?.source.facets??[]).map((f)=>({key:`facet.${f.key}`,label:f.label,value:t.facets?.[f.key],allLabel:"All",options:f.values}))],s=i.errors.map((f,g)=>({type:"notice",id:`source-error-${g+1}`,title:f.source.displayName,text:"This inbox source is temporarily unavailable.",tone:"warn"})),a=e.detail?e.detail.kind==="detail"?[{type:"text",id:"inbox-detail-text",label:"Original content",text:e.detail.detail.text.slice(0,v6i),truncated:e.detail.detail.truncated||e.detail.detail.text.length>v6i}]:[{type:"notice",id:"inbox-detail-unavailable",title:"Original content",text:e.detail.error,tone:"warn"}]:void 0,c=t.selected?i.selectedEntry??i.entries.find((f)=>mz(f.source.sourceId,f.item.id)===t.selected):void 0,u=c?.item.title,d=c?xqn(c):[],p=[...a??[]];if(d.length>0)p.push(gqn(d));let m=c?w6i(c):[];if(m.length>0)p.push(yqn(m));return{kicker:"Live source-owned attention",title:"Inbox",description:"Triage incoming work without creating a second copy of source state.",blocks:[{type:"stats",id:"inbox-summary",items:[{label:"Open",value:i.summary.open},{label:"High priority",value:i.summary.high,tone:i.summary.high>0?"warn":"good"},{label:"Matching",value:i.total},{label:"Sources online",value:`${r} of ${i.sources.length}`,tone:r<i.sources.length?"warn":"neutral"}]},...s,{type:"query",id:"inbox-query",controls:o},...i.total===0&&!t.selected?[{type:"notice",id:"inbox-empty",...i.errors.length>0?{text:"No matching items from available sources. Unavailable sources are not an all-clear."}:{title:"Nothing needs attention for these filters.",text:"Change Source or Urgency to inspect other incoming work."}}]:[{type:"detail",id:"inbox-detail",queryKey:"selected",empty:"Select an item to read its source content.",...t.selected&&p.length>0?{open:{forId:t.selected,title:u??"Original content",blocks:p}}:{},master:{type:"list",id:"inbox-items",presentation:"editorial",empty:i.errors.length>0?"No matching items from available sources. Unavailable sources are not an all-clear.":"Nothing needs attention for these filters.",items:i.entries.map((f)=>({id:mz(f.source.sourceId,f.item.id),title:f.item.title,link:{detail:{itemId:mz(f.source.sourceId,f.item.id)}},description:f.item.summary,metadata:[f.source.displayName,bqn(f.item.receivedAt),`${f.item.urgency} priority`,...f.item.threadOrdinal===void 0?[]:[`Message ${f.item.threadOrdinal} in thread`]],actions:w6i(f)}))}}],...i.total>0?[{type:"query",id:"inbox-pagination",controls:[],pagination:{offset:i.offset,limit:i.limit,total:i.total}}]:[]]}}});async function rFe(e,{query:t,caller:i,signal:r}){if(!i)throw Error("Unified inbox requires authentication");let n=t.get(S6i),o={permissionLevel:i.permission},s=await e.workspace(n,o),a=n.selected?ID(n.selected):void 0,c=a?s.selectedEntry??s.entries.find((d)=>d.source.sourceId===a.sourceId&&d.item.id===a.itemId):void 0,u=!a?void 0:c?.detailAvailable===!1?{kind:"detail-unavailable",error:"Original content is unavailable"}:await e.detail({type:"detail",sourceId:a.sourceId,itemId:a.itemId},o,r);return{query:n,snapshot:s,...u?{detail:u}:{}}}async function nFe(e,{input:t,caller:i}){if(!i)throw Error("Unified inbox requires authentication");let r=await e.act({sourceId:t.sourceId,itemId:t.itemId,actionId:t.capability.id,confirmed:!0},{permissionLevel:i.permission});if(r.kind!=="completed")throw Error("Inbox action did not complete");return r}async function oFe(e,{input:t}){return e.prepareAction({sourceId:t.sourceId,itemId:t.itemId,actionId:t.capability.id})}import{createHash as Eqn}from"crypto";class poe{registry;dataSource;followUps;constructor(e,t,i){this.registry=e,this.dataSource=t,this.followUps=i}async list(e){let t=await this.dataSource.getInboxData(),i=y6i(e,this.registry.listSources()),r=B6i(t,i);return{entries:r.slice(0,i.limit).map(Aqn),errors:C6i(t,i.sourceId),total:r.length}}async workspace(e,t){let i=g6i(e,this.registry.listSources()),r=await this.dataSource.getInboxData(),n=k6i(r.entries),o=B6i(r,i),s=o.slice(i.offset,i.offset+i.limit),a=async(h)=>({...h,detailAvailable:this.registry.getSource(h.source.sourceId)?.resolveDetail!==void 0,followUps:await this.followUps.resolve({sourceId:h.source.sourceId,item:h.item,actor:t})}),c=await Promise.all(s.map(a)),u=i.selected?ID(i.selected):void 0,d=u?r.entries.find((h)=>h.source.sourceId===u.sourceId&&h.item.id===u.itemId):void 0,m=(u?c.find((h)=>h.source.sourceId===u.sourceId&&h.item.id===u.itemId):void 0)??(d?await a(d):void 0);return{summary:D6i(r,n),sources:this.sourceAvailability(r,n),entries:c,...m?{selectedEntry:m}:{},errors:C6i(r,i.sourceId),total:o.length,offset:i.offset,limit:i.limit}}async dashboard(){let e=await this.dataSource.getInboxData(),t=k6i(e.entries),i=this.sourceAvailability(e,t),r=i.filter((n)=>n.available).length;return{summary:{...D6i(e,t),availableSources:r,unavailableSources:i.length-r},entries:e.entries.slice(0,5).map((n)=>({sourceLabel:n.source.displayName,urgency:n.item.urgency,title:n.item.title,receivedAt:n.item.receivedAt}))}}async badge(){return(await this.dataSource.getInboxData()).entries.length}async detail(e,t,i){if(t.permissionLevel!=="admin")return gz();let r=this.registry.getSource(e.sourceId);if(!r?.resolveDetail)return gz();try{if(!(await r.list()).some((c)=>c.id===e.itemId))return gz();let o=AbortSignal.timeout(1e4),s=i?AbortSignal.any([i,o]):o;if(s.aborted)return gz();return{kind:"detail",detail:await r.resolveDetail(e.itemId,t,s)}}catch{return gz()}}async prepareAction(e){let t=this.registry.getSource(e.sourceId),i=t?await I6i(t,e.itemId,e.actionId):void 0;if(!t||!i)throw new Ni("not_found",{publicMessage:"Inbox item or action not found"});return{summary:`${i.action.label} "${i.title}"?`,revision:Eqn("sha256").update(JSON.stringify({sourceId:e.sourceId,itemId:e.itemId,actionId:i.action.id,actionLabel:i.action.label,confirm:i.action.confirm===!0,title:i.title})).digest("hex")}}async act(e,t){let i=this.registry.getSource(e.sourceId),r=i?await I6i(i,e.itemId,e.actionId):void 0;if(!i||!r)throw Error("Inbox item or action not found");if(r.action.confirm===!0&&!e.confirmed)return{kind:"confirmation",summary:`${r.action.label} "${r.title}"?`};return await i.act(e.itemId,e.actionId,t),{kind:"completed"}}sourceAvailability(e,t){let i=new Set(e.errors.map((r)=>r.source.sourceId));return this.registry.listSources().map((r)=>({source:{...XRe(r),...r.facets?{facets:r.facets}:{}},...t.get(r.sourceId)??{open:0,high:0},available:!i.has(r.sourceId)}))}}function gz(){return{kind:"detail-unavailable",error:"Original content is unavailable"}}function k6i(e){return e.reduce((t,i)=>{let r=t.get(i.source.sourceId)??{open:0,high:0};if(r.open+=1,i.item.urgency==="high")r.high+=1;return t.set(i.source.sourceId,r)},new Map)}function B6i(e,t){return e.entries.filter((i)=>(t.sourceId===void 0||i.source.sourceId===t.sourceId)&&(t.urgency===void 0||i.item.urgency===t.urgency)&&Object.entries(t.facets??{}).every(([r,n])=>i.item.facets?.[r]===n))}function Aqn(e){return{source:e.source,item:{title:e.item.title,...e.item.summary?{summary:e.item.summary}:{},...e.item.contact?{contact:e.item.contact}:{},receivedAt:e.item.receivedAt,urgency:e.item.urgency}}}function C6i(e,t){return e.errors.filter((i)=>t===void 0||i.source.sourceId===t)}function D6i(e,t){return{open:e.entries.length,high:[...t.values()].reduce((i,r)=>i+r.high,0)}}async function I6i(e,t,i){let r=(await e.list()).find((o)=>o.id===t),n=r?.actions.find((o)=>o.id===i);return r&&n?{title:r.title,action:n}:void 0}var vqn=l.strictObject({}),wqn=xi({id:"unified-inbox",config:vqn,setup:()=>{let e;return{services:(t)=>{if(e)return e;let i=new doe(t.inbox);return e={dataSource:i,operator:new poe(t.inbox,i,t.inboxFollowUps)},e}}}},{subscriptions:(e)=>{let t=Gt(e),{dataSource:i}=e.state.services(t);return tFe(t,i,{workspaceUrl:()=>t.workspaceUrl(xz)}),t.ready(()=>{let r=oae(t.workspaceUrl(xz));if(!r)return;t.interaction({id:"unified-inbox",label:"Inbox",description:"Review source-owned items that need operator attention.",href:r,kind:"admin",priority:20,visibility:"admin"})}),[]},tools:(e)=>{let t=Gt(e);return[iFe(e.state.services(t).operator,t)]},dashboardWidgets:(e)=>{let{operator:t}=e.state.services(Gt(e));return[JRe.bind(e,({signal:i})=>QRe(t,i))]},studioWorkspaces:(e)=>{let{operator:t}=e.state.services(Gt(e));return[xz.bind(e,{load:(i)=>rFe(t,i),actions:[fz.bind(e,(i)=>nFe(t,i),(i)=>oFe(t,i))]})]}}),sFe=wqn;var _6i={name:"@brains/action-board",license:"AGPL-3.0-only",version:"0.2.0-alpha.698",description:"The team's Board over action items, blocked items in the Inbox, and moves from chat",dependencies:{"@brains/action-items":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/entity-service":"workspace:*","@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0","bun-types":"^1.4.0",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var T6i=100,kqn=160;async function P6i(e,t){return await e.entities.ensureGroupingsCurrent(),e.entities.getGroupings().some((i)=>i.key===t&&i.types.includes(_r))?t:void 0}async function R6i(e,t,i){return(await e.entityService.queryGroupingCatalog({grouping:t,entityTypes:[_r],visibilityScope:i,limit:T6i})).values.filter(({value:n})=>n.length>0&&n.length<=kqn&&n.trim()===n).map(({value:n,count:o})=>({value:n,label:n,count:o}))}async function aFe(e,t,i=0){let r=await e.entityService.queryGroupingMembers({grouping:t.grouping,value:t.value,entityTypes:[_r],visibilityScope:t.visibilityScope,limit:T6i,offset:i,sort:"updated-desc"}),n=r.entities.map((s)=>eo.parse(s)),o=i+r.entities.length;return r.entities.length>0&&o<r.total?[...n,...await aFe(e,t,o)]:n}var moe=[{status:"open",label:"To do",empty:"Nothing waiting to start."},{status:"doing",label:"Doing",empty:"Nobody is on anything yet."},{status:"blocked",label:"Blocked",empty:"Nothing is blocked."},{status:"done",label:"Done",empty:"Nothing finished in the last 14 days."}],F6i=100,Bqn=20,M6i=120,Cqn={open:[{to:"doing",label:"Start"},{to:"blocked",label:"Block"},{to:"done",label:"Done"}],doing:[{to:"blocked",label:"Block"},{to:"done",label:"Done"},{to:"open",label:"To do"}],blocked:[{to:"doing",label:"Resume"},{to:"done",label:"Done"}],done:[{to:"open",label:"Reopen"}],dropped:[]},q6i={open:"To do",doing:"Doing",blocked:"Blocked",done:"Done",dropped:"Dropped"},Dqn=l.object({id:l.string(),title:l.string(),status:zd,assignees:l.array(l.string()),dueDate:l.string().optional(),overdue:l.boolean(),age:l.string(),place:l.string(),source:l.object({label:l.string(),entityType:l.string(),id:l.string()}).optional()}),Iqn=l.object({id:l.string(),title:l.string(),text:l.string(),status:zd,assignees:l.array(l.string()),requesters:l.array(l.string()),dueDate:l.string().optional(),channel:l.string(),notes:l.string().optional()}),_qn=l.object({sourceId:l.string(),entityType:l.string(),entityId:l.string(),title:l.string(),summary:l.string(),tracked:l.boolean()}),Tqn=l.object({name:l.string(),counts:l.array(l.object({status:zd,label:l.string(),count:l.number()})),blocked:l.array(l.object({id:l.string(),title:l.string()}))}),Pqn=l.object({options:l.array(l.object({value:l.string(),label:l.string(),count:l.number()})),selected:Tqn.optional()}),Rqn=l.object({id:l.string(),name:l.string()}),Fqn=l.object({cards:l.array(Dqn),members:l.array(Rqn),open:Iqn.optional(),track:_qn.optional(),projects:Pqn.optional()}),$6i=l.object({card:l.string().optional(),project:l.string().optional(),trackSource:l.string().optional(),trackType:l.string().optional(),trackId:l.string().optional(),trackTitle:l.string().optional(),trackSummary:l.string().optional()}),cFe=B9({id:"board-sources",label:"Action items and their sources"}),yz=l.object({status:l.string().optional()}),O6i={title:"Move",fields:{status:{label:"Outcome"}}},dFe=qi({name:"move",label:"Move",input:l.object({id:l.string(),from:zd,to:zd}),output:yz}),pFe=qi({name:"note",label:"Add a note",input:l.object({id:l.string(),text:l.string().trim().min(1).max(2000)}),output:yz}),Mqn={title:"Note",fields:{status:{label:"Outcome"}}},lFe=qi({name:"track",label:"Track as action item",input:l.object({sourceId:l.string().min(1),entityType:l.string().min(1),entityId:l.string().min(1),title:l.string().trim().min(1).max(500),text:l.string().max(4000),assigneeId:l.string().max(200).optional()}),output:yz}),uFe=qi({name:"create",label:"New card",input:l.object({title:l.string().trim().min(1).max(500),text:l.string().max(4000).optional(),assigneeId:l.string().max(200).optional()}),output:yz}),Oqn={title:"New card",fields:{status:{label:"Outcome"}}},Nqn={title:"Track",fields:{status:{label:"Outcome"}}},mFe=qi({name:"drop",label:"Drop",confirmation:{kind:"static",message:"Drop this action item? It leaves the board; the Library keeps it."},input:l.object({id:l.string(),from:zd}),output:yz});function Lqn(e){let t=e.selected;return[{type:"query",id:"board-projects",controls:[{key:"project",label:"Project",allLabel:"All projects",...t?{value:t.name}:{},options:e.options}]},...t?[{type:"card",id:"project-rollup",label:t.name,presentation:"section",blocks:[{type:"stats",id:"project-counts",items:t.counts.map(({status:i,label:r,count:n})=>({label:r,value:n,...i==="blocked"&&n>0?{tone:"warn"}:{}}))},{type:"list",id:"project-blocked",presentation:"attention",empty:"Nothing in this project is blocked.",items:t.blocked.map((i)=>({id:i.id,title:i.title}))}]}]:[]]}function zqn(e){return[{type:"text",id:"card-text",text:e.text},{type:"key-values",id:"card-facts",items:[{label:"Status",value:q6i[e.status]},...e.assignees.length>0?[{label:"Assigned to",value:e.assignees.join(", ")}]:[],...e.requesters.length>0?[{label:"Requested by",value:e.requesters.join(", ")}]:[],...e.dueDate?[{label:"Due",value:zh(e.dueDate)}]:[],{label:"From",value:e.channel}]},...e.notes?[{type:"text",id:"card-notes",label:"Notes",text:e.notes}]:[],{type:"action",id:"card-note",action:pFe,label:"Add a note",input:{id:e.id},form:{presentation:"inline",submitLabel:"Add note",fields:{text:{label:"Note",control:"text"}}},result:Mqn}]}var N6i=Go({id:"board",label:"Board",description:"The team's action items, by where they stand.",priority:15,permission:"trusted",entityCatalog:cFe,query:$6i,data:Fqn,actions:[dFe,mFe,pFe,lFe,uFe],view:({data:e})=>({title:"Board",description:"Action items from the team's conversations.",blocks:[...e.projects?Lqn(e.projects):[],...e.track?[{type:"card",id:"track",label:"Track as action item",presentation:"feature",blocks:e.track.tracked?[{type:"text",id:"track-done",text:"This Inbox item is on the board."}]:[{type:"text",id:"track-source",text:`From the Inbox: ${e.track.title}`},{type:"action",id:"track-form",action:lFe,label:"Track on the board",input:{...z6i(e.members),sourceId:e.track.sourceId,entityType:e.track.entityType,entityId:e.track.entityId,title:e.track.title,text:e.track.summary},form:{presentation:"inline",submitLabel:"Track on the board",fields:{title:{label:"Title",control:"text"},text:{label:"Details",control:"textarea"},...L6i(e.members)}},result:Nqn}]}]:[],{type:"action",id:"new-card",action:uFe,label:"New card",input:z6i(e.members),form:{presentation:"disclosure",submitLabel:"Add to To do",fields:{title:{label:"Title",control:"text"},text:{label:"Details",control:"textarea"},...L6i(e.members)}},result:Oqn},{type:"detail",id:"board-detail",queryKey:"card",empty:"Select a card to read it.",master:{type:"matrix",id:"board",columns:4,cells:moe.map((t)=>({id:t.status,label:t.label,...t.status==="blocked"?{tone:"warn"}:{},empty:t.empty,items:e.cards.filter((i)=>i.status===t.status).map(jqn)}))},...e.open?{open:{forId:e.open.id,title:e.open.title,blocks:zqn(e.open)}}:{}}]})});function L6i(e){if(e.length===0)return{};return{assigneeId:{label:"Assign to",control:"select",options:e.map((t)=>({value:t.id,label:t.name}))}}}function z6i(e){return e.length===0?{assigneeId:""}:{}}function jqn(e){return{id:e.id,title:e.title,metadata:[...e.assignees,e.dueDate?`due ${zh(e.dueDate)}`:"",e.age,e.place].filter((t)=>t.length>0),...e.overdue?{badges:[{label:"Overdue",tone:"warn"}]}:{},link:{detail:{itemId:e.id}},links:[...e.id.length<=M6i?[{label:"Open in editor",target:{catalog:cFe,entityType:_r,id:e.id}}]:[],...e.source&&e.source.id.length<=M6i?[{label:e.source.label,target:{catalog:cFe,entityType:e.source.entityType,id:e.source.id}}]:[]],actionsLabel:"Move",actions:[...Cqn[e.status].map((t)=>({action:dFe,label:t.label,input:{id:e.id,from:e.status,to:t.to},result:O6i,dropTarget:t.to})),{action:mFe,label:"Drop",input:{id:e.id,from:e.status},result:O6i}]}}function Uqn(e,t){let i=e.metadata.dueDate,r=e.metadata.status==="done"||e.metadata.status==="dropped";return!!i&&!r&&i<t.toISOString().slice(0,10)}function qqn(e,t){let i=w1(e);return{id:e.id,title:Xl(e),status:e.metadata.status,assignees:(e.metadata.assignedTo??[]).map((r)=>r.name),...e.metadata.dueDate?{dueDate:e.metadata.dueDate}:{},overdue:Uqn(e,t),age:wO(FS(e),t),place:i.place,...i.link?{source:{label:i.link.label,entityType:i.link.entityType,id:i.link.entityId}}:{}}}function $qn(e){let t=Up(e.content).trimStart().replace(/^#\s+.+\n+/,""),[i="",r]=t.split(/^## Notes\s*$/m),n=r?.trim();return{text:i.trim(),...n?{notes:n}:{}}}function Gqn(e){let{text:t,notes:i}=$qn(e);return{id:e.id,title:Xl(e),text:t.length>0?t:Xl(e),status:e.metadata.status,assignees:(e.metadata.assignedTo??[]).map((r)=>r.name),requesters:(e.metadata.requestedBy??[]).flatMap((r)=>r.name?[r.name]:[]),...e.metadata.dueDate?{dueDate:e.metadata.dueDate}:{},channel:w1(e).place,...i?{notes:i}:{}}}function Hqn(e){return moe.map(({status:t})=>e.filter((i)=>i.metadata.status===t))}var j6i="That person is not a member of this brain.";async function hFe(e,t){let i=()=>t.now?.()??new Date,r=async()=>[...await t.members?.()??[]],n=async(a)=>{if(!a)return;let c=(await r()).find(({id:u})=>u===a);return c?{name:c.name,id:`user:${c.id}`}:!1},o=async(a,c)=>{if(!a)throw Error("Moving a card requires a signed-in member");let u=await MS({entityService:e.entityService,visibilityScope:Xr(a.permission),now:i},c);switch(u.status){case"moved":return{};case"not-found":return{status:"This card is no longer on the board."};case"conflict":return{status:`This card is now ${q6i[u.current]}; your move was not applied.`}}},s=await U6i({context:e,definition:N6i,bind:(a)=>N6i.bind(a,{listEntityTypes:()=>e.entityService.getEntityTypes(),load:async({caller:c,query:u})=>{if(!c)throw Error("The board requires a signed-in member");let d=Xr(c.permission),p=i(),m=u.get($6i),h=t.projectGrouping?await P6i(e,t.projectGrouping):void 0,f=h?await R6i(e,h,d):[],g=f.find((q)=>q.value===m.project)?.value,y=h&&g?Hqn(await aFe(e,{grouping:h,value:g,visibilityScope:d})):await Promise.all(moe.map(({status:q})=>e.entityService.listEntities({entityType:_r,options:{filter:{metadata:{status:q},visibilityScope:d},sortFields:[{field:"updated",direction:"desc"}],limit:F6i}},eo))),[b=[],v=[],w=[],D=[]]=y,R=D.slice(0,Bqn),O=[b,v,w,R],k=m.card,j=m.trackSource&&m.trackType&&m.trackId?{sourceId:m.trackSource,entityType:m.trackType,entityId:m.trackId,title:m.trackTitle??"",summary:m.trackSummary??"",tracked:await e.entityService.getEntity({entityType:_r,id:PQ({sourceId:m.trackSource,entityType:m.trackType,entityId:m.trackId}),visibilityScope:d})!==null}:void 0,L=k?await e.entityService.getEntity({entityType:_r,id:k,visibilityScope:d},eo):null;return{members:await r(),cards:O.flatMap((q)=>q.slice(0,F6i)).map((q)=>qqn(q,p)),...L?{open:Gqn(L)}:{},...j?{track:j}:{},...h?{projects:{options:f,...g?{selected:{name:g,counts:moe.map((q,K)=>({status:q.status,label:q.label,count:O[K]?.length??0})),blocked:w.map((q)=>({id:q.id,title:Xl(q)}))}}:{}}}:{}}},actions:[dFe.bind(a,({caller:c,input:u})=>o(c,u)),mFe.bind(a,({caller:c,input:u})=>o(c,{...u,to:"dropped"})),lFe.bind(a,async({caller:c,input:u})=>{if(!c)throw Error("Tracking requires a signed-in member");let d=await n(u.assigneeId);if(d===!1)return{status:j6i};return(await t9e({entityService:e.entityService,visibility:t.visibility,now:i},{sourceRef:{sourceId:u.sourceId,entityType:u.entityType,entityId:u.entityId},title:u.title,text:u.text,assignee:d,actor:{kind:"user",userId:c.actor.id},actorName:c.actor.displayName})).status==="tracked"?{}:{status:"This Inbox item is already on the board."}}),uFe.bind(a,async({caller:c,input:u})=>{if(!c)throw Error("Adding a card requires a signed-in member");let d=await n(u.assigneeId);if(d===!1)return{status:j6i};return await S1({entityService:e.entityService,visibility:t.visibility,now:i},{title:u.title,text:u.text??"",assignee:d,actor:{kind:"user",userId:c.actor.id},actorName:c.actor.displayName,origin:{kind:"board"}}),{}}),pFe.bind(a,async({caller:c,input:u})=>{if(!c)throw Error("Adding a note requires a signed-in member");let d=await BO({entityService:e.entityService,visibilityScope:Xr(c.permission),now:i},{id:u.id,text:u.text,actorName:c.actor.displayName});return d.status==="noted"?{}:{status:d.status==="not-found"?"This card is no longer on the board.":"This card changed while you wrote; add the note again."}})]})});return s===!1?void 0:s.workspaceUrl}var fFe="action-board:board";function G6i(e,t,i){if(!i.entityRef)return;let r=new URLSearchParams({trackSource:t,trackType:i.entityRef.entityType,trackId:i.entityRef.entityId,trackTitle:i.title.slice(0,160),trackSummary:(i.summary??"").slice(0,500)});return`${e}?${r.toString()}`}var Wqn={resume:"doing",done:"done",drop:"dropped"};function H6i(e){if(e.permissionLevel!=="admin")throw Error("Action items inbox requires admin permission")}var Zqn=100;class xFe{sourceId="action-items";displayName="Action items";context;constructor(e){this.context=e}async list(){return(await this.context.entityService.listEntities({entityType:_r,options:{filter:{metadata:{status:"blocked"},visibilityScope:Pt("action items inbox is admin-only")},sortFields:[{field:"updated",direction:"desc"}],limit:Zqn}},eo)).map((t)=>{let i=[...(t.metadata.assignedTo??[]).map((r)=>r.name),w1(t).place].filter((r)=>r.length>0);return{id:t.id,title:jp(Xl(t),160),summary:i.join(" \xB7 "),receivedAt:t.updated,urgency:"normal",entityRef:{entityType:_r,entityId:t.id},actions:[{id:"resume",label:"Resume"},{id:"done",label:"Done"},{id:"drop",label:"Drop",confirm:!0}]}})}async resolveDetail(e,t,i){H6i(t),i.throwIfAborted();let r=await this.context.entityService.getEntity({entityType:_r,id:e,visibilityScope:Xr(t.permissionLevel)},eo);if(i.throwIfAborted(),!r)throw Error("Action item unavailable");return{kind:"plain",text:Up(r.content).trimStart().replace(/^#\s+.+\n+/,"").trim(),truncated:!1}}async act(e,t,i){H6i(i);let r=Wqn[t];if(!r)throw Error("Invalid action-items inbox action");if((await MS({entityService:this.context.entityService,visibilityScope:Xr(i.permissionLevel)},{id:e,from:"blocked",to:r})).status!=="moved")throw Error("Action item unavailable")}}var W6i=l.object({title:l.string().trim().min(1).max(200).describe("What needs doing, as a short card title"),details:l.string().trim().max(2000).optional().describe("More about it, when the request says more than the title"),assignee:l.string().trim().min(1).describe(`Who should do it: "nobody" unless the request names someone; a member's name when it does; "me" only when the caller says they will do it themselves.`),due:l.string().trim().min(1).describe('When it is due, as YYYY-MM-DD, when the request names a date (resolve "Friday" from today); "none" when it names none. Never guess a date.')}),Z6i="none";function Vqn(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return;let t=new Date(`${e}T00:00:00Z`);return Number.isNaN(t.getTime())||t.toISOString().slice(0,10)!==e?void 0:e}function Kqn(e){let{conversationId:t,channelId:i,channelName:r,interfaceType:n}=e;if(!t||!i)return{kind:"board"};return{kind:"conversation",conversationId:t,interfaceType:n,channelId:i,...r?{channelName:r}:{}}}var Yqn="nobody";async function Jqn(e,t,i){let r=e.toLowerCase();if(r===Yqn)return;let n=await i(),o=t.actor,s=r==="me"?n.find((c)=>o.kind==="user"&&c.id===o.userId):n.find((c)=>c.name.toLowerCase()===r);if(s)return{name:s.name,id:`user:${s.id}`};let a=n.map((c)=>c.name).join(", ");return{error:r==="me"?"You are not a member of this brain, so the card cannot be assigned to you.":`${e} is not a member of this brain${a?`; members are ${a}`:""}.`}}function V6i(e,t){return{name:"action_item_create",description:"Add an action item (a card on the board) when someone asks for one, recorded as requested by the caller. Use this, not system_create, for action items.",inputSchema:W6i.shape,visibility:"trusted",sideEffects:"writes",handler:async(i,r)=>{let n=W6i.safeParse(i);if(!n.success)return{success:!1,error:`Invalid input: ${n.error.issues.map((m)=>m.message).join(", ")}`};let{title:o,details:s,assignee:a,due:c}=n.data,u=c.toLowerCase()===Z6i?void 0:Vqn(c);if(c.toLowerCase()!==Z6i&&!u){let m=(t.now?.()??new Date).toISOString().slice(0,10);return{success:!1,error:`"${c}" is not a date. Give the due date as YYYY-MM-DD (today is ${m}), or "none".`}}let d=await Jqn(a,r,t.members);if(d&&"error"in d)return{success:!1,error:d.error};let{id:p}=await S1({entityService:e.entityService,visibility:t.visibility,...t.now?{now:t.now}:{}},{title:o,text:s??"",assignee:d,dueDate:u,actor:r.actor,actorName:r.displayName,origin:Kqn(r)});return{success:!0,data:{id:p},message:`Added "${o}"${d?` for ${d.name}`:""}${u?`, due ${u}`:""}.`}}}}var K6i=l.object({id:l.string().min(1).describe("The action item's id or its title"),status:zd.optional().describe("Where the card goes: open (to do), doing, blocked, done, or dropped"),note:l.string().trim().min(1).max(2000).optional().describe("A one-line note to add to the card")});async function Qqn(e,t,i){let r=await e.getEntity({entityType:_r,id:t,visibilityScope:i},eo);if(r)return r;let o=(await e.listEntities({entityType:_r,options:{limit:500,filter:{visibilityScope:i}}},eo)).filter((c)=>jt(Xl(c))===jt(t)),[s,...a]=o;if(!s)return`No action item ${t}.`;if(a.length>0)return`More than one action item is called "${t}": ${o.map((c)=>c.id).sort().join(", ")}. Give its id.`;return s}function Y6i(e,t=()=>new Date){return{name:"action_item_update",description:"Move an action item to open, doing, blocked, done or dropped, and/or add a note to it. The change is recorded under the caller's name. Use this, not system_update, for an action item's status or notes.",inputSchema:K6i.shape,visibility:"trusted",sideEffects:"writes",handler:async(i,r)=>{let n=K6i.safeParse(i);if(!n.success)return{success:!1,error:`Invalid input: ${n.error.issues.map((m)=>m.message).join(", ")}`};let{id:o,status:s,note:a}=n.data;if(s===void 0&&a===void 0)return{success:!1,error:"Give a status, a note, or both."};let c={entityService:e.entityService,visibilityScope:Xr(r.userPermissionLevel??"public"),now:t},u={actor:r.actor,actorName:r.displayName},d=await Qqn(e.entityService,o,c.visibilityScope);if(typeof d==="string")return{success:!1,error:d};let p=[];if(s!==void 0&&s!==d.metadata.status){let m=await MS(c,{id:d.id,from:d.metadata.status,to:s,...u});if(m.status!=="moved")return{success:!1,error:`The card changed while moving it; it is now ${m.status==="conflict"?m.current:"gone"}.`};p.push(`moved to ${s}`)}if(a!==void 0){if((await BO(c,{id:d.id,text:a,...u})).status!=="noted")return{success:!1,error:"The note could not be added."};p.push("noted")}return{success:!0,data:{id:d.id,status:s??d.metadata.status},message:p.length>0?`Action item ${p.join(" and ")}.`:`Action item is already ${d.metadata.status}.`}}}}var Xqn=l.object({cardVisibility:Uu.default("restricted"),projectGrouping:$g.shape.key.default("projects")});class gFe extends ev{boardUrl;constructor(e={}){super("action-board",_6i,e,Xqn)}async onRegister(e){if(e.executionOnly)return;let t=new xFe(e);e.inbox.registerSource(t),e.inboxFollowUps.registerKind({kind:"track-as-action-item",label:"Track as action item",priority:15,mode:"universal",permissionLevel:"trusted",applies:({sourceId:i,item:r})=>this.boardUrl!==void 0&&r.entityRef!==void 0&&i!==t.sourceId,resolve:({sourceId:i,item:r})=>{let n=this.boardUrl?G6i(this.boardUrl,i,r):void 0;return n?{href:n}:void 0}})}async getTools(){let e=this.getContext();return[V6i(e,{visibility:this.config.cardVisibility,members:()=>e.auth.listAssignableMembers()}),Y6i(e)]}async onReady(e){this.boardUrl=await hFe(e,{visibility:this.config.cardVisibility,projectGrouping:this.config.projectGrouping,members:()=>e.auth.listAssignableMembers()})}async onShutdown(){if(this.boardUrl===void 0)return;this.boardUrl=void 0,await this.getContext().studio.unregisterWorkspace(fFe)}}function yFe(e={}){return new gFe(e)}import{join as FD}from"path";var foe="/ask/assets/boot.js",bFe="/ask/assets/version",t2i=`(function () {
10190
+ `)}}function tFe(e,t,i={}){e.recurringCheck({id:"daily-digest",cadence:"daily",includeInInbox:!1,run:async({signal:r})=>{r.throwIfAborted();let n=await t.getInboxData();r.throwIfAborted();let o=typeof i.workspaceUrl==="function"?i.workspaceUrl():i.workspaceUrl,s=A6i(n,{destinationUrl:aqn(e,o),...i.now?{now:i.now}:{}});return{alerts:s?[s]:[]}}})}function sqn(e){let t=new Map;for(let i of e){let r=i.source.sourceId,n=t.get(r)??{displayName:i.source.displayName,entries:[]};n.entries.push(i),t.set(r,n)}return[...t.values()]}function eFe(e,t){return e===1?t:dx(t)}function aqn(e,t){let i=t??e.routeByRole("dashboard")?.fullPath??"/dashboard";return Uh(i,e.siteUrl)}var cqn=l.looseObject(loe);function iFe(e,t){return Ug({name:"inbox_list",description:"List live content-safe operator attention across registered inbox sources, optionally filtered by source, urgency, or source-declared facets",input:cqn,output:uoe,permission:"admin",sideEffects:"none",execute:async({input:i})=>{if(t.toolCall()?.userPermissionLevel!=="admin")throw new Ni("permission_denied",{publicMessage:"Unified inbox requires admin permission"});let r=ZRe.safeParse(i);if(!r.success)throw new Ni("invalid_input",{publicMessage:"Invalid unified inbox filters"});try{return await e.list(r.data)}catch(n){throw new Ni("handler_failed",{publicMessage:"Unified inbox list failed",cause:n})}}},{bareName:!0})}var lqn=l.object({id:l.string().trim().min(1).max(120),label:l.string().trim().min(1).max(200),confirmation:l.literal("prepared").optional()}),uqn=l.object({sourceId:l.string().trim().min(1).max(120),itemId:l.string().trim().min(1).max(500),capability:lqn}),dqn=l.object({kind:l.literal("completed")}),fz=qi({name:"run-inbox-action",label:"Run inbox action",catalog:!0,permission:"admin",confirmation:{kind:"prepared",conditional:!0},input:uqn,output:dqn}),v6i=4000,pqn=zt({type:"person",purpose:"A known person associated with operator work",metadata:l.object({})});function mqn(e){if(typeof e!=="object"||e===null||Array.isArray(e))return e;let t={},i={};for(let[r,n]of Object.entries(e))if(r.startsWith("facet."))i[r.slice(6)]=n;else t[r]=n;return{...t,...Object.keys(i).length>0?{facets:i}:{}}}var S6i=l.preprocess(mqn,hz),hqn=l.object({query:hz,snapshot:VRe,detail:YRe.optional()});function fqn(e){let t=e.source.displayName;if(!e.available)return`${t} \xB7 unavailable`;return e.high>0?`${t} \xB7 ${e.high} high`:t}function w6i(e){return e.item.actions.map((t)=>{let i={id:t.id,label:t.label,...t.confirm===!0?{confirmation:"prepared"}:{}};return{action:fz,capability:i,input:{sourceId:e.source.sourceId,itemId:e.item.id,capability:i}}})}function xqn(e){let t=e.item.entityRef,i=[];if(e.item.contact?.personId)i.push({label:`Open contact ${e.item.contact.label}`,target:{entity:pqn,id:e.item.contact.personId}});for(let r of e.followUps)if(r.kind==="discuss-in-chat")i.push({label:r.label,target:{launch:{target:"inbox-discuss-in-chat",sourceId:e.source.sourceId,itemId:e.item.id,label:e.item.title}}});else if(r.kind==="open-entity"&&t)i.push({label:r.label,target:{launch:{target:"inbox-open-entity",entityType:t.entityType,entityId:t.entityId}}});else if(r.kind==="capture-as-note"&&t)i.push({label:r.label,target:{launch:{target:"inbox-capture-note",title:e.item.title,...e.item.summary?{summary:e.item.summary}:{},entityType:t.entityType,entityId:t.entityId}}});return i}function gqn(e){return{type:"card",id:"inbox-detail-follow-ups",label:"Follow up",blocks:[{type:"links",id:"inbox-follow-up-links",items:e}]}}function yqn(e){return{type:"card",id:"inbox-detail-actions",label:"Available actions",blocks:[{type:"actions",id:"inbox-action-controls",items:e}]}}function bqn(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return e;return t.toISOString()}var xz=Go({id:"inbox",label:"Inbox",priority:20,permission:"admin",query:S6i,data:hqn,actions:[fz],badge:({data:e})=>e.snapshot.summary.open,view:({data:e})=>{let{query:t,snapshot:i}=e,r=i.sources.filter((f)=>f.available).length,n=i.sources.find((f)=>f.source.sourceId===t.sourceId),o=[{key:"sourceId",label:"Source",value:t.sourceId,allLabel:"All sources",options:i.sources.map((f)=>({value:f.source.sourceId,label:fqn(f),count:f.open}))},{key:"urgency",label:"Urgency",value:t.urgency,allLabel:"All urgency",options:[{value:"high",label:"High priority",count:i.summary.high},{value:"normal",label:"Normal"}]},...(n?.source.facets??[]).map((f)=>({key:`facet.${f.key}`,label:f.label,value:t.facets?.[f.key],allLabel:"All",options:f.values}))],s=i.errors.map((f,g)=>({type:"notice",id:`source-error-${g+1}`,title:f.source.displayName,text:"This inbox source is temporarily unavailable.",tone:"warn"})),a=e.detail?e.detail.kind==="detail"?[{type:"text",id:"inbox-detail-text",label:"Original content",text:e.detail.detail.text.slice(0,v6i),truncated:e.detail.detail.truncated||e.detail.detail.text.length>v6i}]:[{type:"notice",id:"inbox-detail-unavailable",title:"Original content",text:e.detail.error,tone:"warn"}]:void 0,c=t.selected?i.selectedEntry??i.entries.find((f)=>mz(f.source.sourceId,f.item.id)===t.selected):void 0,u=c?.item.title,d=c?xqn(c):[],p=[...a??[]];if(d.length>0)p.push(gqn(d));let m=c?w6i(c):[];if(m.length>0)p.push(yqn(m));return{kicker:"Live source-owned attention",title:"Inbox",description:"Triage incoming work without creating a second copy of source state.",blocks:[{type:"stats",id:"inbox-summary",items:[{label:"Open",value:i.summary.open},{label:"High priority",value:i.summary.high,tone:i.summary.high>0?"warn":"good"},{label:"Matching",value:i.total},{label:"Sources online",value:`${r} of ${i.sources.length}`,tone:r<i.sources.length?"warn":"neutral"}]},...s,{type:"query",id:"inbox-query",controls:o},...i.total===0&&!t.selected?[{type:"notice",id:"inbox-empty",...i.errors.length>0?{text:"No matching items from available sources. Unavailable sources are not an all-clear."}:{title:"Nothing needs attention for these filters.",text:"Change Source or Urgency to inspect other incoming work."}}]:[{type:"detail",id:"inbox-detail",queryKey:"selected",empty:"Select an item to read its source content.",...t.selected&&p.length>0?{open:{forId:t.selected,title:u??"Original content",blocks:p}}:{},master:{type:"list",id:"inbox-items",presentation:"editorial",empty:i.errors.length>0?"No matching items from available sources. Unavailable sources are not an all-clear.":"Nothing needs attention for these filters.",items:i.entries.map((f)=>({id:mz(f.source.sourceId,f.item.id),title:f.item.title,link:{detail:{itemId:mz(f.source.sourceId,f.item.id)}},description:f.item.summary,metadata:[f.source.displayName,bqn(f.item.receivedAt),`${f.item.urgency} priority`,...f.item.threadOrdinal===void 0?[]:[`Message ${f.item.threadOrdinal} in thread`]],actions:w6i(f)}))}}],...i.total>0?[{type:"query",id:"inbox-pagination",controls:[],pagination:{offset:i.offset,limit:i.limit,total:i.total}}]:[]]}}});async function rFe(e,{query:t,caller:i,signal:r}){if(!i)throw Error("Unified inbox requires authentication");let n=t.get(S6i),o={permissionLevel:i.permission},s=await e.workspace(n,o),a=n.selected?ID(n.selected):void 0,c=a?s.selectedEntry??s.entries.find((d)=>d.source.sourceId===a.sourceId&&d.item.id===a.itemId):void 0,u=!a?void 0:c?.detailAvailable===!1?{kind:"detail-unavailable",error:"Original content is unavailable"}:await e.detail({type:"detail",sourceId:a.sourceId,itemId:a.itemId},o,r);return{query:n,snapshot:s,...u?{detail:u}:{}}}async function nFe(e,{input:t,caller:i}){if(!i)throw Error("Unified inbox requires authentication");let r=await e.act({sourceId:t.sourceId,itemId:t.itemId,actionId:t.capability.id,confirmed:!0},{permissionLevel:i.permission});if(r.kind!=="completed")throw Error("Inbox action did not complete");return r}async function oFe(e,{input:t}){return e.prepareAction({sourceId:t.sourceId,itemId:t.itemId,actionId:t.capability.id})}import{createHash as Eqn}from"crypto";class poe{registry;dataSource;followUps;constructor(e,t,i){this.registry=e,this.dataSource=t,this.followUps=i}async list(e){let t=await this.dataSource.getInboxData(),i=y6i(e,this.registry.listSources()),r=B6i(t,i);return{entries:r.slice(0,i.limit).map(Aqn),errors:C6i(t,i.sourceId),total:r.length}}async workspace(e,t){let i=g6i(e,this.registry.listSources()),r=await this.dataSource.getInboxData(),n=k6i(r.entries),o=B6i(r,i),s=o.slice(i.offset,i.offset+i.limit),a=async(h)=>({...h,detailAvailable:this.registry.getSource(h.source.sourceId)?.resolveDetail!==void 0,followUps:await this.followUps.resolve({sourceId:h.source.sourceId,item:h.item,actor:t})}),c=await Promise.all(s.map(a)),u=i.selected?ID(i.selected):void 0,d=u?r.entries.find((h)=>h.source.sourceId===u.sourceId&&h.item.id===u.itemId):void 0,m=(u?c.find((h)=>h.source.sourceId===u.sourceId&&h.item.id===u.itemId):void 0)??(d?await a(d):void 0);return{summary:D6i(r,n),sources:this.sourceAvailability(r,n),entries:c,...m?{selectedEntry:m}:{},errors:C6i(r,i.sourceId),total:o.length,offset:i.offset,limit:i.limit}}async dashboard(){let e=await this.dataSource.getInboxData(),t=k6i(e.entries),i=this.sourceAvailability(e,t),r=i.filter((n)=>n.available).length;return{summary:{...D6i(e,t),availableSources:r,unavailableSources:i.length-r},entries:e.entries.slice(0,5).map((n)=>({sourceLabel:n.source.displayName,urgency:n.item.urgency,title:n.item.title,receivedAt:n.item.receivedAt}))}}async badge(){return(await this.dataSource.getInboxData()).entries.length}async detail(e,t,i){if(t.permissionLevel!=="admin")return gz();let r=this.registry.getSource(e.sourceId);if(!r?.resolveDetail)return gz();try{if(!(await r.list()).some((c)=>c.id===e.itemId))return gz();let o=AbortSignal.timeout(1e4),s=i?AbortSignal.any([i,o]):o;if(s.aborted)return gz();return{kind:"detail",detail:await r.resolveDetail(e.itemId,t,s)}}catch{return gz()}}async prepareAction(e){let t=this.registry.getSource(e.sourceId),i=t?await I6i(t,e.itemId,e.actionId):void 0;if(!t||!i)throw new Ni("not_found",{publicMessage:"Inbox item or action not found"});return{summary:`${i.action.label} "${i.title}"?`,revision:Eqn("sha256").update(JSON.stringify({sourceId:e.sourceId,itemId:e.itemId,actionId:i.action.id,actionLabel:i.action.label,confirm:i.action.confirm===!0,title:i.title})).digest("hex")}}async act(e,t){let i=this.registry.getSource(e.sourceId),r=i?await I6i(i,e.itemId,e.actionId):void 0;if(!i||!r)throw Error("Inbox item or action not found");if(r.action.confirm===!0&&!e.confirmed)return{kind:"confirmation",summary:`${r.action.label} "${r.title}"?`};return await i.act(e.itemId,e.actionId,t),{kind:"completed"}}sourceAvailability(e,t){let i=new Set(e.errors.map((r)=>r.source.sourceId));return this.registry.listSources().map((r)=>({source:{...XRe(r),...r.facets?{facets:r.facets}:{}},...t.get(r.sourceId)??{open:0,high:0},available:!i.has(r.sourceId)}))}}function gz(){return{kind:"detail-unavailable",error:"Original content is unavailable"}}function k6i(e){return e.reduce((t,i)=>{let r=t.get(i.source.sourceId)??{open:0,high:0};if(r.open+=1,i.item.urgency==="high")r.high+=1;return t.set(i.source.sourceId,r)},new Map)}function B6i(e,t){return e.entries.filter((i)=>(t.sourceId===void 0||i.source.sourceId===t.sourceId)&&(t.urgency===void 0||i.item.urgency===t.urgency)&&Object.entries(t.facets??{}).every(([r,n])=>i.item.facets?.[r]===n))}function Aqn(e){return{source:e.source,item:{title:e.item.title,...e.item.summary?{summary:e.item.summary}:{},...e.item.contact?{contact:e.item.contact}:{},receivedAt:e.item.receivedAt,urgency:e.item.urgency}}}function C6i(e,t){return e.errors.filter((i)=>t===void 0||i.source.sourceId===t)}function D6i(e,t){return{open:e.entries.length,high:[...t.values()].reduce((i,r)=>i+r.high,0)}}async function I6i(e,t,i){let r=(await e.list()).find((o)=>o.id===t),n=r?.actions.find((o)=>o.id===i);return r&&n?{title:r.title,action:n}:void 0}var vqn=l.strictObject({}),wqn=xi({id:"unified-inbox",config:vqn,setup:()=>{let e;return{services:(t)=>{if(e)return e;let i=new doe(t.inbox);return e={dataSource:i,operator:new poe(t.inbox,i,t.inboxFollowUps)},e}}}},{subscriptions:(e)=>{let t=Gt(e),{dataSource:i}=e.state.services(t);return tFe(t,i,{workspaceUrl:()=>t.workspaceUrl(xz)}),t.ready(()=>{let r=oae(t.workspaceUrl(xz));if(!r)return;t.interaction({id:"unified-inbox",label:"Inbox",description:"Review source-owned items that need operator attention.",href:r,kind:"admin",priority:20,visibility:"admin"})}),[]},tools:(e)=>{let t=Gt(e);return[iFe(e.state.services(t).operator,t)]},dashboardWidgets:(e)=>{let{operator:t}=e.state.services(Gt(e));return[JRe.bind(e,({signal:i})=>QRe(t,i))]},studioWorkspaces:(e)=>{let{operator:t}=e.state.services(Gt(e));return[xz.bind(e,{load:(i)=>rFe(t,i),actions:[fz.bind(e,(i)=>nFe(t,i),(i)=>oFe(t,i))]})]}}),sFe=wqn;var _6i={name:"@brains/action-board",license:"AGPL-3.0-only",version:"0.2.0-alpha.699",description:"The team's Board over action items, blocked items in the Inbox, and moves from chat",dependencies:{"@brains/action-items":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/entity-service":"workspace:*","@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0","bun-types":"^1.4.0",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var T6i=100,kqn=160;async function P6i(e,t){return await e.entities.ensureGroupingsCurrent(),e.entities.getGroupings().some((i)=>i.key===t&&i.types.includes(_r))?t:void 0}async function R6i(e,t,i){return(await e.entityService.queryGroupingCatalog({grouping:t,entityTypes:[_r],visibilityScope:i,limit:T6i})).values.filter(({value:n})=>n.length>0&&n.length<=kqn&&n.trim()===n).map(({value:n,count:o})=>({value:n,label:n,count:o}))}async function aFe(e,t,i=0){let r=await e.entityService.queryGroupingMembers({grouping:t.grouping,value:t.value,entityTypes:[_r],visibilityScope:t.visibilityScope,limit:T6i,offset:i,sort:"updated-desc"}),n=r.entities.map((s)=>eo.parse(s)),o=i+r.entities.length;return r.entities.length>0&&o<r.total?[...n,...await aFe(e,t,o)]:n}var moe=[{status:"open",label:"To do",empty:"Nothing waiting to start."},{status:"doing",label:"Doing",empty:"Nobody is on anything yet."},{status:"blocked",label:"Blocked",empty:"Nothing is blocked."},{status:"done",label:"Done",empty:"Nothing finished in the last 14 days."}],F6i=100,Bqn=20,M6i=120,Cqn={open:[{to:"doing",label:"Start"},{to:"blocked",label:"Block"},{to:"done",label:"Done"}],doing:[{to:"blocked",label:"Block"},{to:"done",label:"Done"},{to:"open",label:"To do"}],blocked:[{to:"doing",label:"Resume"},{to:"done",label:"Done"}],done:[{to:"open",label:"Reopen"}],dropped:[]},q6i={open:"To do",doing:"Doing",blocked:"Blocked",done:"Done",dropped:"Dropped"},Dqn=l.object({id:l.string(),title:l.string(),status:zd,assignees:l.array(l.string()),dueDate:l.string().optional(),overdue:l.boolean(),age:l.string(),place:l.string(),source:l.object({label:l.string(),entityType:l.string(),id:l.string()}).optional()}),Iqn=l.object({id:l.string(),title:l.string(),text:l.string(),status:zd,assignees:l.array(l.string()),requesters:l.array(l.string()),dueDate:l.string().optional(),channel:l.string(),notes:l.string().optional()}),_qn=l.object({sourceId:l.string(),entityType:l.string(),entityId:l.string(),title:l.string(),summary:l.string(),tracked:l.boolean()}),Tqn=l.object({name:l.string(),counts:l.array(l.object({status:zd,label:l.string(),count:l.number()})),blocked:l.array(l.object({id:l.string(),title:l.string()}))}),Pqn=l.object({options:l.array(l.object({value:l.string(),label:l.string(),count:l.number()})),selected:Tqn.optional()}),Rqn=l.object({id:l.string(),name:l.string()}),Fqn=l.object({cards:l.array(Dqn),members:l.array(Rqn),open:Iqn.optional(),track:_qn.optional(),projects:Pqn.optional()}),$6i=l.object({card:l.string().optional(),project:l.string().optional(),trackSource:l.string().optional(),trackType:l.string().optional(),trackId:l.string().optional(),trackTitle:l.string().optional(),trackSummary:l.string().optional()}),cFe=B9({id:"board-sources",label:"Action items and their sources"}),yz=l.object({status:l.string().optional()}),O6i={title:"Move",fields:{status:{label:"Outcome"}}},dFe=qi({name:"move",label:"Move",input:l.object({id:l.string(),from:zd,to:zd}),output:yz}),pFe=qi({name:"note",label:"Add a note",input:l.object({id:l.string(),text:l.string().trim().min(1).max(2000)}),output:yz}),Mqn={title:"Note",fields:{status:{label:"Outcome"}}},lFe=qi({name:"track",label:"Track as action item",input:l.object({sourceId:l.string().min(1),entityType:l.string().min(1),entityId:l.string().min(1),title:l.string().trim().min(1).max(500),text:l.string().max(4000),assigneeId:l.string().max(200).optional()}),output:yz}),uFe=qi({name:"create",label:"New card",input:l.object({title:l.string().trim().min(1).max(500),text:l.string().max(4000).optional(),assigneeId:l.string().max(200).optional()}),output:yz}),Oqn={title:"New card",fields:{status:{label:"Outcome"}}},Nqn={title:"Track",fields:{status:{label:"Outcome"}}},mFe=qi({name:"drop",label:"Drop",confirmation:{kind:"static",message:"Drop this action item? It leaves the board; the Library keeps it."},input:l.object({id:l.string(),from:zd}),output:yz});function Lqn(e){let t=e.selected;return[{type:"query",id:"board-projects",controls:[{key:"project",label:"Project",allLabel:"All projects",...t?{value:t.name}:{},options:e.options}]},...t?[{type:"card",id:"project-rollup",label:t.name,presentation:"section",blocks:[{type:"stats",id:"project-counts",items:t.counts.map(({status:i,label:r,count:n})=>({label:r,value:n,...i==="blocked"&&n>0?{tone:"warn"}:{}}))},{type:"list",id:"project-blocked",presentation:"attention",empty:"Nothing in this project is blocked.",items:t.blocked.map((i)=>({id:i.id,title:i.title}))}]}]:[]]}function zqn(e){return[{type:"text",id:"card-text",text:e.text},{type:"key-values",id:"card-facts",items:[{label:"Status",value:q6i[e.status]},...e.assignees.length>0?[{label:"Assigned to",value:e.assignees.join(", ")}]:[],...e.requesters.length>0?[{label:"Requested by",value:e.requesters.join(", ")}]:[],...e.dueDate?[{label:"Due",value:zh(e.dueDate)}]:[],{label:"From",value:e.channel}]},...e.notes?[{type:"text",id:"card-notes",label:"Notes",text:e.notes}]:[],{type:"action",id:"card-note",action:pFe,label:"Add a note",input:{id:e.id},form:{presentation:"inline",submitLabel:"Add note",fields:{text:{label:"Note",control:"text"}}},result:Mqn}]}var N6i=Go({id:"board",label:"Board",description:"The team's action items, by where they stand.",priority:15,permission:"trusted",entityCatalog:cFe,query:$6i,data:Fqn,actions:[dFe,mFe,pFe,lFe,uFe],view:({data:e})=>({title:"Board",description:"Action items from the team's conversations.",blocks:[...e.projects?Lqn(e.projects):[],...e.track?[{type:"card",id:"track",label:"Track as action item",presentation:"feature",blocks:e.track.tracked?[{type:"text",id:"track-done",text:"This Inbox item is on the board."}]:[{type:"text",id:"track-source",text:`From the Inbox: ${e.track.title}`},{type:"action",id:"track-form",action:lFe,label:"Track on the board",input:{...z6i(e.members),sourceId:e.track.sourceId,entityType:e.track.entityType,entityId:e.track.entityId,title:e.track.title,text:e.track.summary},form:{presentation:"inline",submitLabel:"Track on the board",fields:{title:{label:"Title",control:"text"},text:{label:"Details",control:"textarea"},...L6i(e.members)}},result:Nqn}]}]:[],{type:"action",id:"new-card",action:uFe,label:"New card",input:z6i(e.members),form:{presentation:"disclosure",submitLabel:"Add to To do",fields:{title:{label:"Title",control:"text"},text:{label:"Details",control:"textarea"},...L6i(e.members)}},result:Oqn},{type:"detail",id:"board-detail",queryKey:"card",empty:"Select a card to read it.",master:{type:"matrix",id:"board",columns:4,cells:moe.map((t)=>({id:t.status,label:t.label,...t.status==="blocked"?{tone:"warn"}:{},empty:t.empty,items:e.cards.filter((i)=>i.status===t.status).map(jqn)}))},...e.open?{open:{forId:e.open.id,title:e.open.title,blocks:zqn(e.open)}}:{}}]})});function L6i(e){if(e.length===0)return{};return{assigneeId:{label:"Assign to",control:"select",options:e.map((t)=>({value:t.id,label:t.name}))}}}function z6i(e){return e.length===0?{assigneeId:""}:{}}function jqn(e){return{id:e.id,title:e.title,metadata:[...e.assignees,e.dueDate?`due ${zh(e.dueDate)}`:"",e.age,e.place].filter((t)=>t.length>0),...e.overdue?{badges:[{label:"Overdue",tone:"warn"}]}:{},link:{detail:{itemId:e.id}},links:[...e.id.length<=M6i?[{label:"Open in editor",target:{catalog:cFe,entityType:_r,id:e.id}}]:[],...e.source&&e.source.id.length<=M6i?[{label:e.source.label,target:{catalog:cFe,entityType:e.source.entityType,id:e.source.id}}]:[]],actionsLabel:"Move",actions:[...Cqn[e.status].map((t)=>({action:dFe,label:t.label,input:{id:e.id,from:e.status,to:t.to},result:O6i,dropTarget:t.to})),{action:mFe,label:"Drop",input:{id:e.id,from:e.status},result:O6i}]}}function Uqn(e,t){let i=e.metadata.dueDate,r=e.metadata.status==="done"||e.metadata.status==="dropped";return!!i&&!r&&i<t.toISOString().slice(0,10)}function qqn(e,t){let i=w1(e);return{id:e.id,title:Xl(e),status:e.metadata.status,assignees:(e.metadata.assignedTo??[]).map((r)=>r.name),...e.metadata.dueDate?{dueDate:e.metadata.dueDate}:{},overdue:Uqn(e,t),age:wO(FS(e),t),place:i.place,...i.link?{source:{label:i.link.label,entityType:i.link.entityType,id:i.link.entityId}}:{}}}function $qn(e){let t=Up(e.content).trimStart().replace(/^#\s+.+\n+/,""),[i="",r]=t.split(/^## Notes\s*$/m),n=r?.trim();return{text:i.trim(),...n?{notes:n}:{}}}function Gqn(e){let{text:t,notes:i}=$qn(e);return{id:e.id,title:Xl(e),text:t.length>0?t:Xl(e),status:e.metadata.status,assignees:(e.metadata.assignedTo??[]).map((r)=>r.name),requesters:(e.metadata.requestedBy??[]).flatMap((r)=>r.name?[r.name]:[]),...e.metadata.dueDate?{dueDate:e.metadata.dueDate}:{},channel:w1(e).place,...i?{notes:i}:{}}}function Hqn(e){return moe.map(({status:t})=>e.filter((i)=>i.metadata.status===t))}var j6i="That person is not a member of this brain.";async function hFe(e,t){let i=()=>t.now?.()??new Date,r=async()=>[...await t.members?.()??[]],n=async(a)=>{if(!a)return;let c=(await r()).find(({id:u})=>u===a);return c?{name:c.name,id:`user:${c.id}`}:!1},o=async(a,c)=>{if(!a)throw Error("Moving a card requires a signed-in member");let u=await MS({entityService:e.entityService,visibilityScope:Xr(a.permission),now:i},c);switch(u.status){case"moved":return{};case"not-found":return{status:"This card is no longer on the board."};case"conflict":return{status:`This card is now ${q6i[u.current]}; your move was not applied.`}}},s=await U6i({context:e,definition:N6i,bind:(a)=>N6i.bind(a,{listEntityTypes:()=>e.entityService.getEntityTypes(),load:async({caller:c,query:u})=>{if(!c)throw Error("The board requires a signed-in member");let d=Xr(c.permission),p=i(),m=u.get($6i),h=t.projectGrouping?await P6i(e,t.projectGrouping):void 0,f=h?await R6i(e,h,d):[],g=f.find((q)=>q.value===m.project)?.value,y=h&&g?Hqn(await aFe(e,{grouping:h,value:g,visibilityScope:d})):await Promise.all(moe.map(({status:q})=>e.entityService.listEntities({entityType:_r,options:{filter:{metadata:{status:q},visibilityScope:d},sortFields:[{field:"updated",direction:"desc"}],limit:F6i}},eo))),[b=[],v=[],w=[],D=[]]=y,R=D.slice(0,Bqn),O=[b,v,w,R],k=m.card,j=m.trackSource&&m.trackType&&m.trackId?{sourceId:m.trackSource,entityType:m.trackType,entityId:m.trackId,title:m.trackTitle??"",summary:m.trackSummary??"",tracked:await e.entityService.getEntity({entityType:_r,id:PQ({sourceId:m.trackSource,entityType:m.trackType,entityId:m.trackId}),visibilityScope:d})!==null}:void 0,L=k?await e.entityService.getEntity({entityType:_r,id:k,visibilityScope:d},eo):null;return{members:await r(),cards:O.flatMap((q)=>q.slice(0,F6i)).map((q)=>qqn(q,p)),...L?{open:Gqn(L)}:{},...j?{track:j}:{},...h?{projects:{options:f,...g?{selected:{name:g,counts:moe.map((q,K)=>({status:q.status,label:q.label,count:O[K]?.length??0})),blocked:w.map((q)=>({id:q.id,title:Xl(q)}))}}:{}}}:{}}},actions:[dFe.bind(a,({caller:c,input:u})=>o(c,u)),mFe.bind(a,({caller:c,input:u})=>o(c,{...u,to:"dropped"})),lFe.bind(a,async({caller:c,input:u})=>{if(!c)throw Error("Tracking requires a signed-in member");let d=await n(u.assigneeId);if(d===!1)return{status:j6i};return(await t9e({entityService:e.entityService,visibility:t.visibility,now:i},{sourceRef:{sourceId:u.sourceId,entityType:u.entityType,entityId:u.entityId},title:u.title,text:u.text,assignee:d,actor:{kind:"user",userId:c.actor.id},actorName:c.actor.displayName})).status==="tracked"?{}:{status:"This Inbox item is already on the board."}}),uFe.bind(a,async({caller:c,input:u})=>{if(!c)throw Error("Adding a card requires a signed-in member");let d=await n(u.assigneeId);if(d===!1)return{status:j6i};return await S1({entityService:e.entityService,visibility:t.visibility,now:i},{title:u.title,text:u.text??"",assignee:d,actor:{kind:"user",userId:c.actor.id},actorName:c.actor.displayName,origin:{kind:"board"}}),{}}),pFe.bind(a,async({caller:c,input:u})=>{if(!c)throw Error("Adding a note requires a signed-in member");let d=await BO({entityService:e.entityService,visibilityScope:Xr(c.permission),now:i},{id:u.id,text:u.text,actorName:c.actor.displayName});return d.status==="noted"?{}:{status:d.status==="not-found"?"This card is no longer on the board.":"This card changed while you wrote; add the note again."}})]})});return s===!1?void 0:s.workspaceUrl}var fFe="action-board:board";function G6i(e,t,i){if(!i.entityRef)return;let r=new URLSearchParams({trackSource:t,trackType:i.entityRef.entityType,trackId:i.entityRef.entityId,trackTitle:i.title.slice(0,160),trackSummary:(i.summary??"").slice(0,500)});return`${e}?${r.toString()}`}var Wqn={resume:"doing",done:"done",drop:"dropped"};function H6i(e){if(e.permissionLevel!=="admin")throw Error("Action items inbox requires admin permission")}var Zqn=100;class xFe{sourceId="action-items";displayName="Action items";context;constructor(e){this.context=e}async list(){return(await this.context.entityService.listEntities({entityType:_r,options:{filter:{metadata:{status:"blocked"},visibilityScope:Pt("action items inbox is admin-only")},sortFields:[{field:"updated",direction:"desc"}],limit:Zqn}},eo)).map((t)=>{let i=[...(t.metadata.assignedTo??[]).map((r)=>r.name),w1(t).place].filter((r)=>r.length>0);return{id:t.id,title:jp(Xl(t),160),summary:i.join(" \xB7 "),receivedAt:t.updated,urgency:"normal",entityRef:{entityType:_r,entityId:t.id},actions:[{id:"resume",label:"Resume"},{id:"done",label:"Done"},{id:"drop",label:"Drop",confirm:!0}]}})}async resolveDetail(e,t,i){H6i(t),i.throwIfAborted();let r=await this.context.entityService.getEntity({entityType:_r,id:e,visibilityScope:Xr(t.permissionLevel)},eo);if(i.throwIfAborted(),!r)throw Error("Action item unavailable");return{kind:"plain",text:Up(r.content).trimStart().replace(/^#\s+.+\n+/,"").trim(),truncated:!1}}async act(e,t,i){H6i(i);let r=Wqn[t];if(!r)throw Error("Invalid action-items inbox action");if((await MS({entityService:this.context.entityService,visibilityScope:Xr(i.permissionLevel)},{id:e,from:"blocked",to:r})).status!=="moved")throw Error("Action item unavailable")}}var W6i=l.object({title:l.string().trim().min(1).max(200).describe("What needs doing, as a short card title"),details:l.string().trim().max(2000).optional().describe("More about it, when the request says more than the title"),assignee:l.string().trim().min(1).describe(`Who should do it: "nobody" unless the request names someone; a member's name when it does; "me" only when the caller says they will do it themselves.`),due:l.string().trim().min(1).describe('When it is due, as YYYY-MM-DD, when the request names a date (resolve "Friday" from today); "none" when it names none. Never guess a date.')}),Z6i="none";function Vqn(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return;let t=new Date(`${e}T00:00:00Z`);return Number.isNaN(t.getTime())||t.toISOString().slice(0,10)!==e?void 0:e}function Kqn(e){let{conversationId:t,channelId:i,channelName:r,interfaceType:n}=e;if(!t||!i)return{kind:"board"};return{kind:"conversation",conversationId:t,interfaceType:n,channelId:i,...r?{channelName:r}:{}}}var Yqn="nobody";async function Jqn(e,t,i){let r=e.toLowerCase();if(r===Yqn)return;let n=await i(),o=t.actor,s=r==="me"?n.find((c)=>o.kind==="user"&&c.id===o.userId):n.find((c)=>c.name.toLowerCase()===r);if(s)return{name:s.name,id:`user:${s.id}`};let a=n.map((c)=>c.name).join(", ");return{error:r==="me"?"You are not a member of this brain, so the card cannot be assigned to you.":`${e} is not a member of this brain${a?`; members are ${a}`:""}.`}}function V6i(e,t){return{name:"action_item_create",description:"Add an action item (a card on the board) when someone asks for one, recorded as requested by the caller. Use this, not system_create, for action items.",inputSchema:W6i.shape,visibility:"trusted",sideEffects:"writes",handler:async(i,r)=>{let n=W6i.safeParse(i);if(!n.success)return{success:!1,error:`Invalid input: ${n.error.issues.map((m)=>m.message).join(", ")}`};let{title:o,details:s,assignee:a,due:c}=n.data,u=c.toLowerCase()===Z6i?void 0:Vqn(c);if(c.toLowerCase()!==Z6i&&!u){let m=(t.now?.()??new Date).toISOString().slice(0,10);return{success:!1,error:`"${c}" is not a date. Give the due date as YYYY-MM-DD (today is ${m}), or "none".`}}let d=await Jqn(a,r,t.members);if(d&&"error"in d)return{success:!1,error:d.error};let{id:p}=await S1({entityService:e.entityService,visibility:t.visibility,...t.now?{now:t.now}:{}},{title:o,text:s??"",assignee:d,dueDate:u,actor:r.actor,actorName:r.displayName,origin:Kqn(r)});return{success:!0,data:{id:p},message:`Added "${o}"${d?` for ${d.name}`:""}${u?`, due ${u}`:""}.`}}}}var K6i=l.object({id:l.string().min(1).describe("The action item's id or its title"),status:zd.optional().describe("Where the card goes: open (to do), doing, blocked, done, or dropped"),note:l.string().trim().min(1).max(2000).optional().describe("A one-line note to add to the card")});async function Qqn(e,t,i){let r=await e.getEntity({entityType:_r,id:t,visibilityScope:i},eo);if(r)return r;let o=(await e.listEntities({entityType:_r,options:{limit:500,filter:{visibilityScope:i}}},eo)).filter((c)=>jt(Xl(c))===jt(t)),[s,...a]=o;if(!s)return`No action item ${t}.`;if(a.length>0)return`More than one action item is called "${t}": ${o.map((c)=>c.id).sort().join(", ")}. Give its id.`;return s}function Y6i(e,t=()=>new Date){return{name:"action_item_update",description:"Move an action item to open, doing, blocked, done or dropped, and/or add a note to it. The change is recorded under the caller's name. Use this, not system_update, for an action item's status or notes.",inputSchema:K6i.shape,visibility:"trusted",sideEffects:"writes",handler:async(i,r)=>{let n=K6i.safeParse(i);if(!n.success)return{success:!1,error:`Invalid input: ${n.error.issues.map((m)=>m.message).join(", ")}`};let{id:o,status:s,note:a}=n.data;if(s===void 0&&a===void 0)return{success:!1,error:"Give a status, a note, or both."};let c={entityService:e.entityService,visibilityScope:Xr(r.userPermissionLevel??"public"),now:t},u={actor:r.actor,actorName:r.displayName},d=await Qqn(e.entityService,o,c.visibilityScope);if(typeof d==="string")return{success:!1,error:d};let p=[];if(s!==void 0&&s!==d.metadata.status){let m=await MS(c,{id:d.id,from:d.metadata.status,to:s,...u});if(m.status!=="moved")return{success:!1,error:`The card changed while moving it; it is now ${m.status==="conflict"?m.current:"gone"}.`};p.push(`moved to ${s}`)}if(a!==void 0){if((await BO(c,{id:d.id,text:a,...u})).status!=="noted")return{success:!1,error:"The note could not be added."};p.push("noted")}return{success:!0,data:{id:d.id,status:s??d.metadata.status},message:p.length>0?`Action item ${p.join(" and ")}.`:`Action item is already ${d.metadata.status}.`}}}}var Xqn=l.object({cardVisibility:Uu.default("restricted"),projectGrouping:$g.shape.key.default("projects")});class gFe extends ev{boardUrl;constructor(e={}){super("action-board",_6i,e,Xqn)}async onRegister(e){if(e.executionOnly)return;let t=new xFe(e);e.inbox.registerSource(t),e.inboxFollowUps.registerKind({kind:"track-as-action-item",label:"Track as action item",priority:15,mode:"universal",permissionLevel:"trusted",applies:({sourceId:i,item:r})=>this.boardUrl!==void 0&&r.entityRef!==void 0&&i!==t.sourceId,resolve:({sourceId:i,item:r})=>{let n=this.boardUrl?G6i(this.boardUrl,i,r):void 0;return n?{href:n}:void 0}})}async getTools(){let e=this.getContext();return[V6i(e,{visibility:this.config.cardVisibility,members:()=>e.auth.listAssignableMembers()}),Y6i(e)]}async onReady(e){this.boardUrl=await hFe(e,{visibility:this.config.cardVisibility,projectGrouping:this.config.projectGrouping,members:()=>e.auth.listAssignableMembers()})}async onShutdown(){if(this.boardUrl===void 0)return;this.boardUrl=void 0,await this.getContext().studio.unregisterWorkspace(fFe)}}function yFe(e={}){return new gFe(e)}import{join as FD}from"path";var foe="/ask/assets/boot.js",bFe="/ask/assets/version",t2i=`(function () {
10190
10191
  function boot(src) {
10191
10192
  var script = document.createElement("script");
10192
10193
  script.src = src;
@@ -10875,5 +10876,5 @@ ${Aoe}</style><link rel="stylesheet" href="${w$n}"></head><body class="guest-pag
10875
10876
  `);return{kind:"text",filename:"inbox-source.txt",mediaType:"text/plain",content:u,sizeBytes:new TextEncoder().encode(u).byteLength}}catch{return tki()}}async handleContextSessionRequest(e){let t=rc(e);if(t)return t;return X2i(e,{conversations:this.runtime.conversations,resolveAccess:(i)=>this.resolveConversationAccess(i),interfaceType:Jd,authorizeSource:async({sourceId:i,itemId:r,permissionLevel:n,signal:o})=>{let s=this.runtime.inbox.getSource(i);if(!s?.resolveDetail)return!1;return await s.resolveDetail(r,{permissionLevel:n},o),!0}})}async handleSessionsRequest(e){return l9i(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:Jd})}async handleDeleteSessionRequest(e){return u9i(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:Jd})}async handleRenameSessionRequest(e){return d9i(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:Jd})}async handleArchiveSessionRequest(e){return p9i(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:Jd})}async handleDocumentAttachmentRequest(e){return a2i(e,{resolvePermissionLevel:(t)=>this.resolveAttachmentPermissionLevel(t),createAuthLoginRequiredResponse:(t)=>this.createAuthLoginRequiredResponse(t),entityService:this.runtime.entityReads})}async handleImageAttachmentRequest(e){return c2i(e,{resolvePermissionLevel:(t)=>this.resolveAttachmentPermissionLevel(t),createAuthLoginRequiredResponse:(t)=>this.createAuthLoginRequiredResponse(t),entityService:this.runtime.entityReads})}async handleJobStatusRequest(e){return i9i(e,{resolveAuthSession:this.resolveAuthSession,createAuthLoginRequiredResponse:(t)=>this.createAuthLoginRequiredResponse(t),jobs:this.runtime.jobs})}async handleMessagesRequest(e){return f9i(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:Jd})}async resolveConversationAccess(e){let t=await this.resolveBrowserAccess(e);return this.toConversationAccess(t.permissionLevel,t.principal)}toConversationAccess(e,t){return{permissionLevel:e,...t?{personId:t.personId}:{}}}requireExistingWebChatConversation(e,t){return this.requireExistingBrowserConversation(e,Jd,t)}ensureWebChatConversation(e,t){return this.ensureBrowserConversation(e,Jd,"Web Chat",t)}async requireExistingBrowserConversation(e,t,i){let r=await this.runtime.conversations.get(e);return bg(r,i,t)?void 0:new Response("Conversation not found",{status:404})}async ensureBrowserConversation(e,t,i,r){let n=await this.runtime.conversations.get(e);if(n)return bg(n,r,t)?void 0:new Response("Conversation not found",{status:404});if(r.permissionLevel==="trusted"&&!r.personId)return new Response("Forbidden",{status:403});await this.runtime.conversations.start({sessionId:e,interfaceType:t,channelId:e,...r.personId?{personId:r.personId}:{},metadata:{channelName:i,interfaceType:t,channelId:e}});let o=await this.runtime.conversations.get(e);return bg(o,r,t)?void 0:new Response("Conversation not found",{status:404})}getActiveStream(e){if(!e)return;return this.activeStreams.get(e)}async resolveBrowserAccess(e){let t=await this.resolveAuthPrincipal(e);if(t){let r=t.status==="active"&&(t.permissionLevel==="admin"||t.permissionLevel==="trusted");return{principal:t,permissionLevel:r?t.permissionLevel:"public",hasChatAccess:r}}if(this.resolveCallerPermissionLevel){let r=await this.resolveCallerPermissionLevel(e);return{permissionLevel:r,hasChatAccess:r==="admin"||r==="trusted"}}let i=this.resolveAuthSessionOverride?await this.resolveAuthSessionOverride(e):!1;return{permissionLevel:i?"admin":"public",hasChatAccess:i}}async resolvePermissionLevel(e){return(await this.resolveBrowserAccess(e)).permissionLevel}async resolveAttachmentPermissionLevel(e){return this.resolvePermissionLevel(e)}createAuthLoginRequiredResponse(e){let t=this.runtime.auth();if(t)return t.createAuthLoginResponse(e);return new Response("Authentication required",{status:401,headers:{"Content-Type":"text/plain; charset=utf-8"}})}writeText(e,t,i){return yoe(e,t,i,(r)=>this.createId(r))}createId(e){return`${e}-${crypto.randomUUID()}`}}function tki(){return new Response("Inbox context is unavailable",{status:409})}function LFe(e={}){let t=l0({id:Jd,config:wFe,setup:async(n)=>{let o=Xo(n),s=new nki(n.config,e,o);return await s.register(),o.ready(()=>s.onReady()),s}}),i=_c(t,({state:n})=>n.webRoutes()),r=Sf(i,({state:n})=>{let o=n.maintenanceDaemon();return{id:"guest-maintenance",start:()=>o.start(),stop:()=>o.stop(),healthCheck:()=>o.healthCheck()}});return IJ(r,({state:n})=>n.transport())}var mGn=LFe(),oki=mGn;var zFe='Mandatory unmet-request routing: Wish entities record requested capabilities or desired end states whose literal completion is outside the available toolset. When the user asks for an unavailable product, capability, or real-world outcome no installed tool can perform, explain the limitation and call system_create with entityType "wish" unless the user declines. Availability is determined by the callable tool surface: an installed interface or transport that exposes no tool for the requested action cannot fulfill it. Authorization and ownership boundaries are not missing capabilities: when the current caller permission level, visibility policy, confirmation requirements, or system-maintained record ownership blocks an operation, explain that boundary and MUST NOT call system_create for a wish. A tool withheld from the current caller because of their permission level is also an authorization boundary, not an unmet product request. Do not search durable content to discover executable capabilities or permission workarounds; the callable tool surface and current permission context are authoritative. If you recognize that no callable tool can perform the action and no authorization or ownership boundary applies, do not end the turn after explaining the limitation; in that same turn you MUST call system_create with entityType "wish". The unmet request itself is concrete source material; do not merely decline, offer alternatives, or wait for a separate save verb. Do not invent or look for a dedicated wishlist tool; wishlist entries use the generic entity tools. They track demand, priority, and status for future capability planning; they are not a substitute for first-class entities that already support the requested action. To show the whole wishlist, call system_list once with entityType wish and omit status; only include status when the user asks for a specific wish status.';var ski={critical:0,high:1,medium:2,low:3};function aki(e){return[...e].sort((t,i)=>{let r=i.metadata.requested-t.metadata.requested;if(r!==0)return r;return ski[t.metadata.priority]-ski[i.metadata.priority]})}var Rz=l.enum(["new","planned","in-progress","done","declined"]),Fz=l.enum(["low","medium","high","critical"]),Roe=l.object({title:l.string(),status:Rz,priority:Fz.default("medium"),requested:l.number().int().default(1).meta({studioWidget:"provenance"}),declinedReason:l.string().optional()}),jFe=l.object({title:l.string(),status:Rz,priority:Fz,requested:l.number().int().meta({studioWidget:"provenance"}),slug:l.string().optional().meta({studioWidget:"hidden"}),declinedReason:l.string().optional()});var hGn=l.object({items:l.array(l.object({id:l.string(),name:l.string(),count:l.number().int().nonnegative(),priority:Fz,status:Rz}))});function fGn(e){if(e==="critical")return"error";if(e==="high")return"warn";return"neutral"}var UFe=Nn({id:"top-wishes",title:"Top Wishes",group:"knowledge",placement:"secondary",priority:30,permission:"public",data:hGn,digest:({data:e})=>{let t=e.items[0];return{items:t?[{label:"Top wish",value:`${t.name} \xB7 \xD7${t.count}`}]:[{label:"Wishes",value:"none yet"}]}},view:({data:e})=>({blocks:[{type:"list",id:"wishes",empty:"No wishes yet.",items:e.items.map((t)=>({id:t.id,title:t.name,count:t.count,badges:[{label:t.priority,tone:fGn(t.priority)},{label:t.status,tone:t.status==="done"?"good":"neutral"}]}))}]})});function xGn(e){return UFe.bind(e,async({entities:t,signal:i})=>(i.throwIfAborted(),{items:aki(await t.list(Ag,{limit:10})).map((n)=>({id:n.id,name:n.metadata.title,count:n.metadata.requested,priority:n.metadata.priority,status:n.metadata.status}))}))}var Ag=Qi(zt({type:"wish",purpose:"A demand record the assistant proactively creates when a user requests a capability or outcome no installed tool can fulfill, unless the user declines.",metadata:jFe,markdown:{decode:({content:e,frontmatter:t})=>{let i=Roe.parse(t);return{content:e,metadata:{title:i.title,status:i.status,priority:i.priority,requested:i.requested,slug:jt(i.title),...i.declinedReason!==void 0&&{declinedReason:i.declinedReason}}}},encode:({content:e,metadata:t})=>({content:e,frontmatter:{title:t.title,status:t.status,priority:t.priority,requested:t.requested,...t.declinedReason!==void 0&&{declinedReason:t.declinedReason}}})},config:{projectionSource:!1,projectionSourceRole:"excluded"},instructions:zFe,dashboardWidgets:(e)=>[xGn(e)]}),Roe);var cki=0.3,gGn="Do these two wishes ask for the same thing?",yGn=l.object({same:l.boolean().describe("True only when delivering one would fulfil the other.")});async function bGn(e,t,i){let{same:r}=await e.generateObject([gGn,"Answer yes when both ask for the same capability, even if wording, timing or detail differ (weekly vs every Monday, calendar sync vs Google Calendar integration).","Opposite or different capabilities are different wishes, even when worded almost alike: send emails vs stop sending emails, add vs remove.","","New wish:",t,"","Existing wish:",i].join(`
10876
10877
  `),yGn);return r}function Foe(e,t,i){return{nearest:(r,n)=>e.nearest(Ag,r,{maxDistance:n}),getEntity:(r)=>t.get(Ag,r),maxDistance:i,ai:e}}async function Moe(e,t){let i=(await e.nearest(t.content,e.maxDistance)).flatMap(({entity:s})=>s.visibility==="public"?[s]:[]),r=async(s)=>{let a=i[s];if(!a)return;return await bGn(e.ai,t.content,EGn(a))?a:r(s+1)},n=await r(0);if(n)return n;let o=await e.getEntity(jt(t.title));return o?.visibility==="public"?o:null}function EGn(e){let{title:t,status:i,priority:r,requested:n,declinedReason:o}=e.metadata;return Mz({title:t,status:i,priority:r,requested:n,declinedReason:o},e.content)}function Mz(e,t){let i=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0&&r!==null));return Object.keys(i).length>0?kr(i,t):t}var lki=l.object({title:l.string(),description:l.string()}),AGn=l.object({stored:lki,incoming:lki}),qFe="eval-stored-wish";function uki(e){return Mz({title:e.title,status:"new",priority:"medium",requested:1},e.description)}function dki(e){return{sameWish:async(t,i)=>{let{stored:r,incoming:n}=AGn.parse(t),{fixtures:o}=i;await o.reset(),await o.seed({id:qFe,entityType:"wish",content:uki(r),metadata:{title:r.title,status:"new",priority:"medium",requested:1,slug:jt(r.title)}}),await o.settleEmbeddings();let s=ii(i),a=uki(n),c=(await s.nearest(Ag,a,{maxDistance:2})).find(({entity:d})=>d.id===qFe)?.distance;if(c===void 0)throw Error("The stored wish was not embedded");let u=await Moe(Foe(s,i.entities,e),{title:n.title,content:a});return{distance:c,shortlisted:c<=e,sameWish:u?.id===qFe}}}}async function vGn(e,t){let{input:i}=e;if(i.visibility!==void 0&&i.visibility!=="public")return{refuse:"Wish creation currently supports public visibility only; use a note for shared or restricted capture."};let r=i.title??i.prompt??"Untitled wish",n=i.content??i.prompt??"",o={title:r,status:"new",priority:"medium",requested:1},s=await Moe(Foe(ii(e),e.entities,t),{title:r,content:Mz(o,n)});if(s)return{update:{id:s.id,content:s.content.trim(),metadata:{...s.metadata,requested:s.metadata.requested+1}}};let a=jt(r);return{create:{id:a,content:n,metadata:{...o,slug:a}}}}function pki(e){let t={resolve:(i)=>vGn(i,e)};return{fromPrompt:t,fromContent:t,fromUpload:t}}var $Fe=l.object({sameWishDistance:l.number().min(0).max(1).default(cki)});var wGn=un({id:"wishlist",config:$Fe,entities:[Ag],configure:({config:e})=>({entities:[{entity:Ag,create:pki(e.sameWishDistance),evals:dki(e.sameWishDistance)}]})}),mki=wGn;var hki="gpt-6-luna";var e2={create:"trusted",update:"trusted",delete:"admin",extract:"admin",publish:"admin"},fki=[{member:"content-pipeline",value:{generationSchedules:{newsletter:"0 9 * * 1","social-post":"0 10 * * *"},generationConditions:{newsletter:{skipIfDraftExists:!0,minSourceEntities:1,sourceEntityType:"post"},"social-post":{skipIfDraftExists:!0,maxUnpublishedDrafts:5}}}},{member:"social-media",value:{autoGenerateOnBlogPublish:!0}}],xki=["Use the installed publishing capabilities for professional website content, essays, projects, decks, newsletters, and social distribution workflows. Treat publishing requests as production and distribution work rather than generic shared-memory capture.",`When answering questions like "what have I written about X" or "which posts relate to this deck/source", search first and use semantic search results as candidates, not proof. Summarize only clearly relevant entities whose title or content directly matches the asked topic or has substantial overlap with the source's main themes; omit weak/tangential candidates rather than presenting them as definite matches. A match based on only an isolated shared term or pattern is not enough; when one candidate is clearly stronger than the rest, list only the strongest clear match and say the others were tangential rather than naming them as matches.`,'Draft blog posts are only post entities with status draft. If the user asks whether draft blog posts exist, call only system_list for entityType post with status draft; do not also list social-post, newsletter, deck, or other draft entity types. After telling the user there are no draft blog posts, treat follow-ups like "make one draft" or "make one a draft" as requests to change an existing published post back to draft: ask which existing published post they want changed; do not offer to create a brand-new post and do not call system_generate to create a fresh draft from that ambiguous follow-up.'],gki=[{member:"topics",value:{extractableStatuses:["published","draft"]}},{member:"conversation-memory",value:{memoryVisibility:"shared"}},{member:"action-board",value:{cardVisibility:"shared"}}],yki=["This is a collaborative team-memory and synthesis posture. Optimize for capturing shared context, finding what the team already knows, summarizing cross-source evidence with attribution, and coordinating with peer brains.","Do not default to personal publishing, personal branding, blog, newsletter, social-media, portfolio, or marketing workflows unless the installed capabilities and the user's request explicitly support them."];var lw="capability-bundles-v1",GFe="core",HFe="media",WFe="automation",Oz="web",ZFe="chat",VFe="site",KFe="publishing",YFe="federation",JFe="team",Ooe=s0({id:GFe,members:["profile","prompt","style-guide","directory-sync","note","link","topics","unified-inbox","mcp","a2a","agents"],evalDisable:["mcp"]}),Noe=s0({id:HFe,members:["document","image"]}),Loe=s0({id:WFe,members:["playbooks","onboarding"]}),zoe=s0({id:Oz,members:["auth-service","admin","dashboard","studio"],http:!0,config:[{member:"dashboard",value:{routePath:"/"}}],permissions:[{member:"mcp",config:{rules:[{pattern:"mcp:http",level:"public"}]}},{member:"studio",config:{entityActions:{"grouping-definitions":{create:"admin",update:"admin",delete:"admin",publish:"never"}}}}],evalDisable:["dashboard"]}),joe=s0({id:ZFe,members:["chat","web-chat","ask-content","email","notifications","conversation-memory","faq"],permissions:[{member:"chat",config:{rules:[{pattern:"discord:*",level:"public"}]}},{member:"web-chat",config:{rules:[{pattern:"web-chat:*",level:"admin"}]}}],evalDisable:["chat","web-chat","email","faq"]}),Uoe=s0({id:VFe,members:["site-info","site-content","site-builder","form","analytics"],config:[{member:"dashboard",value:{routePath:"/dashboard"},overrides:Oz}]}),qoe=s0({id:KFe,members:["blog","series","portfolio","decks","content-pipeline","social-media","newsletter","stock-photo"],config:fki,agentInstructions:xki}),$oe=s0({id:YFe,members:["atproto","atproto-registry"],evalDisable:["atproto"]}),Goe=s0({id:JFe,members:[],config:gki,permissions:[{member:"note",config:{entityActions:{note:e2}}},{member:"link",config:{entityActions:{link:e2}}},{member:"image",config:{entityActions:{image:e2}}},{member:"docs",config:{entityActions:{doc:e2}}},{member:"conversation-memory",config:{entityActions:{decision:e2,"action-item":e2}}},{member:"mcp",config:{rules:[{pattern:"mcp:http",level:"admin"}]},overrides:Oz}],agentInstructions:yki}),bki=[Ooe,Noe,Loe,zoe,joe,Uoe,qoe,$oe,Goe];function QFe(e,t,i){let r={name:e,version:uw.version};return(n)=>Cm(t,n,r,i)}function SGn(e){let{entity:t,provider:i}=Ivi(e),r={name:"@brains/newsletter",version:uw.version};return[...Cm(t.definition,t.config,r,{pluginId:"newsletter"}),...i?Cm(i.definition,i.config,r,{pluginId:i.kind}):[]]}function $r(e,t,i,r={},n=void 0){return[e,QFe(t,i,r),n]}function Nz(e,t,i,r,n={}){return[e,QFe(t,i,n),r]}var Eki=gse({name:"brain",version:uw.version,bundleContract:lw,model:hki,reasoningEffort:"low",capabilities:[$r("prompt","@brains/prompt",i8i,{pluginId:"prompt"}),$r("profile","@brains/profile",fPe,{pluginId:"profile"}),$r("style-guide","@brains/style-guide",iSi,{pluginId:"style-guide"}),$r("ask-content","@brains/ask-content",nSi,{pluginId:"ask-content"}),$r("image","@brains/image-plugin",LAi,{pluginId:"image"}),$r("document","@brains/document-plugin",Ysi,{pluginId:"document"}),$r("note","@brains/note",Gvi,{pluginId:"note"}),$r("link","@brains/link",tvi,{pluginId:"link"}),$r("wishlist","@brains/wishlist",mki,{pluginId:"wishlist"}),["topics",(e)=>[...Cm(i6i,e,{name:"@brains/topics",version:uw.version},{pluginId:"topics"}),...Cm($Re,{},{name:"@brains/knowledge-map",version:uw.version},{pluginId:"knowledge-map"})],void 0],$r("decks","@brains/decks",Pii,{pluginId:"decks"}),$r("directory-sync","@brains/directory-sync",Kni,{pluginId:"directory-sync"},{seedContent:!0,seedContentPath:"./seed-content",initialSync:!0}),$r("atproto-registry","@brains/atproto-registry",Wde,{pluginId:"atproto-registry"}),["agents",(e)=>{let{enableSkillDerivation:t,notifyOnNewAgents:i}=sGe.parse(e),r={name:"@brains/agent-discovery",version:uw.version};return[...Cm(Que,{},r,{pluginId:"agent-discovery",ownedTypePluginId:"agent-entity"}),...Cm(Xue,{notifyOnNewAgents:i},r,{pluginId:"agent"}),...Cm(t?ede:tde,{},r,{pluginId:"skill",ownedTypePluginId:"skill-entity"})]},void 0],["assessment",(e)=>Cm(Bde.parse(e).enableSwotDerivation?Cde:Dde,{},{name:"@brains/assessment",version:uw.version},{pluginId:"swot"}),void 0],["auth-service",Jhe,void 0],$r("notifications","@brains/notifications",Zvi,{pluginId:"notifications"}),$r("contact","@brains/contact",TXt,{pluginId:"contact",dependencies:_Xt}),$r("quiz","@brains/quiz",qXt,{pluginId:"quiz",dependencies:UXt}),$r("playbooks","@brains/playbooks",jTe,{pluginId:"playbooks"}),$r("onboarding","@brains/onboarding",s8i,{pluginId:"onboarding",dependencies:["playbook","playbooks"]}),$r("studio","@brains/studio",TQt,{pluginId:"studio"}),$r("dashboard","@brains/dashboard",nii,{pluginId:"dashboard"}),$r("admin","@brains/admin",Yae,{pluginId:"admin"}),$r("site-info","@brains/site-info",tRe,{pluginId:"site-metadata"}),$r("site-content","@brains/site-content",M5i,{pluginId:"site-content",ownedTypePluginId:"site-content-entity"}),$r("site-builder","@brains/site-builder-plugin",P5i,{pluginId:"site-builder"}),["form",NXt,void 0],$r("analytics","@brains/analytics",DGe,{pluginId:"analytics"}),$r("blog","@brains/blog",Jst,{pluginId:"blog"}),$r("series","@brains/series",w8i,{pluginId:"series"}),$r("portfolio","@brains/portfolio",Twi,{pluginId:"portfolio"}),$r("content-pipeline","@brains/content-pipeline",uXt,{pluginId:"content-pipeline"}),$r("social-media","@brains/social-media",Y5i,{pluginId:"social-media"}),["newsletter",SGn,void 0],$r("stock-photo","@brains/stock-photo",eSi,{pluginId:"stock-photo"}),["atproto",QFe("@brains/atproto",lHe,{pluginId:"atproto"}),(e)=>({...e.ATPROTO_APP_PASSWORD?{appPassword:e.ATPROTO_APP_PASSWORD}:{}})],$r("conversation-memory","@brains/conversation-memory",E9e,{pluginId:"conversation-memory"}),["action-board",yFe,void 0],$r("faq","@brains/faq",kti,{pluginId:"faq",ownedTypePluginId:"faq-entity"}),$r("docs","@brains/doc",xoi,{pluginId:"docs"}),["guides",FBe,void 0],$r("book","@brains/book",qsi,{pluginId:"book",ownedTypePluginId:"book-entity"}),$r("obsidian-vault","@brains/obsidian-vault",vTe,{pluginId:"obsidian-vault"},{autoSync:!0}),$r("email-workflows","@brains/email-workflows",SAi,{pluginId:"email-workflows"}),$r("unified-inbox","@brains/unified-inbox",sFe,{pluginId:"unified-inbox"}),["linkedin-import",hTe,void 0],["oauth-broker",(e)=>ETe(e,{providers:{linkedin:iTe}}),void 0]],interfaces:[Nz("mcp","@brains/mcp",uvi,(e)=>({...e.MCP_AUTH_TOKEN?{authToken:e.MCP_AUTH_TOKEN}:{}}),{pluginId:"mcp"}),Nz("email","@brains/email",uAi,()=>({}),{pluginId:"email"}),Nz("web-chat","@brains/web-chat",oki,()=>({}),{pluginId:"web-chat"}),Nz("chat","@brains/chat",gJt,(e)=>k6e(e,{captureUrls:!0}),{pluginId:"chat"}),Nz("a2a","@brains/a2a",nOe,()=>({}),{pluginId:"a2a"})],bundles:bki,permissions:{rules:[{pattern:"cli:*",level:"admin"},{pattern:"mcp:stdio",level:"admin"}]},deployment:{cdn:{enabled:!0,provider:"bunny"},dns:{enabled:!0,provider:"bunny"}}});var kGn=["headless","personal","professional","team"];var BGn={headless:{bundleContract:lw,bundles:["core"]},personal:{bundleContract:lw,anchor:"person",kind:"professional",bundles:["core","media","web","chat"],plugins:{"directory-sync":{seedContentPath:"./seed-content"}}},professional:{bundleContract:lw,anchor:"person",kind:"professional",bundles:["core","media","automation","web","chat","site","publishing","federation"],site:{package:"@brains/site-default",theme:"@rizom/theme-default"},plugins:{"directory-sync":{seedContentPath:"./seed-content"}}},team:{bundleContract:lw,anchor:"team",kind:"team",bundles:["core","media","automation","web","chat","site","team"],add:["docs","action-board"],site:{package:"@brains/site-organization",theme:"@brains/theme-rizom"},plugins:{"directory-sync":{seedContentPath:"./seed-content"}}}};function CGn(e){return structuredClone(e)}function DGn(e){return CGn(BGn[e])}var IGn=Eki,LAa=Ooe,zAa=Noe,jAa=Loe,UAa=zoe,qAa=joe,$Aa=Uoe,GAa=qoe,HAa=$oe,WAa=Goe,VAa=IGn;export{WFe as AUTOMATION_BUNDLE_ID,kGn as BRAIN_RECIPE_NAMES,lw as CANONICAL_BUNDLE_CONTRACT,ZFe as CHAT_BUNDLE_ID,GFe as CORE_BUNDLE_ID,YFe as FEDERATION_BUNDLE_ID,HFe as MEDIA_BUNDLE_ID,KFe as PUBLISHING_BUNDLE_ID,VFe as SITE_BUNDLE_ID,JFe as TEAM_BUNDLE_ID,Oz as WEB_BUNDLE_ID,jAa as automationBundle,IGn as canonicalBrain,qAa as chatBundle,LAa as coreBundle,VAa as default,DGn as expandBrainRecipe,HAa as federationBundle,zAa as mediaBundle,GAa as publishingBundle,$Aa as siteBundle,WAa as teamBundle,UAa as webBundle};
10877
10878
 
10878
- //# debugId=D7503E75A4DFFB9864756E2164756E21
10879
+ //# debugId=49766AE7E322475F64756E2164756E21
10879
10880
  //# sourceMappingURL=model.js.map