@kaeawc/auto-mobile 0.0.93 → 0.0.94
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/build-info.json +12 -12
- package/dist/src/ble-peripheral.py +153 -0
- package/dist/src/{chunk-r6z1eztj.js → chunk-026y62r9.js} +11 -11
- package/dist/src/chunk-0jyfg947.js +4 -0
- package/dist/src/{chunk-8g1922rp.js → chunk-0zfpp1wh.js} +4 -4
- package/dist/src/{chunk-qf6nynk6.js → chunk-13qxf7ym.js} +5 -5
- package/dist/src/chunk-1scenrk7.js +4 -0
- package/dist/src/chunk-1vb5ph1k.js +4 -0
- package/dist/src/{chunk-710rxz9y.js → chunk-20g565q7.js} +3 -3
- package/dist/src/chunk-21h6dhdm.js +5 -0
- package/dist/src/chunk-25mfpthk.js +78 -0
- package/dist/src/{chunk-rbpdk7m0.js → chunk-2b39zyxc.js} +3 -3
- package/dist/src/chunk-2gzd6wbd.js +4 -0
- package/dist/src/{chunk-xgan0qqp.js → chunk-3dntffy9.js} +1 -1
- package/dist/src/chunk-3gfczcsn.js +4 -0
- package/dist/src/{chunk-dgrbdpb7.js → chunk-3h5jz1vb.js} +6 -6
- package/dist/src/{chunk-t6c8akcm.js → chunk-41zcy6b3.js} +3 -3
- package/dist/src/chunk-47n9m2de.js +4 -0
- package/dist/src/chunk-4vxeq0vd.js +58 -0
- package/dist/src/chunk-59dx6qaf.js +4 -0
- package/dist/src/chunk-5sdf9y92.js +4 -0
- package/dist/src/{chunk-58wzr3mt.js → chunk-5wk1t46v.js} +3 -3
- package/dist/src/{chunk-vy3bwm1d.js → chunk-661c50hh.js} +5 -5
- package/dist/src/chunk-68n6bjjd.js +21 -0
- package/dist/src/{chunk-v6pya0dm.js → chunk-69pmjdf2.js} +3 -3
- package/dist/src/{chunk-e98dqnc9.js → chunk-6hrj3jt6.js} +20 -20
- package/dist/src/{chunk-wbh8spm5.js → chunk-6myr26wx.js} +8 -8
- package/dist/src/chunk-6n96k09n.js +4 -0
- package/dist/src/chunk-6vwrbkre.js +4 -0
- package/dist/src/chunk-6wk0yrab.js +4 -0
- package/dist/src/chunk-6yhm9een.js +4 -0
- package/dist/src/{chunk-mjrps0ac.js → chunk-7k7gjg2t.js} +5 -5
- package/dist/src/chunk-7n5fz68h.js +4 -0
- package/dist/src/chunk-8cvnpnbp.js +4 -0
- package/dist/src/chunk-8kzv7rk7.js +4 -0
- package/dist/src/chunk-8nj68t1v.js +167 -0
- package/dist/src/{chunk-g7tmjbkt.js → chunk-96r3bpg7.js} +3 -3
- package/dist/src/chunk-97x887te.js +4 -0
- package/dist/src/{chunk-8ph29g99.js → chunk-99a6tbvd.js} +1 -1
- package/dist/src/chunk-9p5d2994.js +5 -0
- package/dist/src/{chunk-aabchzxk.js → chunk-9q265er0.js} +4 -4
- package/dist/src/{chunk-jh6vhqzx.js → chunk-9xgnrv5w.js} +3 -3
- package/dist/src/chunk-9xgsmshb.js +5 -0
- package/dist/src/chunk-a02d1wgv.js +4 -0
- package/dist/src/{chunk-ndt1ccxm.js → chunk-a9ps00a1.js} +10 -10
- package/dist/src/{chunk-5d2hft6c.js → chunk-aewdveet.js} +3 -3
- package/dist/src/{chunk-ycaj2sgf.js → chunk-b3tdtq7r.js} +6 -6
- package/dist/src/chunk-bn7jx7a2.js +4 -0
- package/dist/src/{chunk-3y6eykz9.js → chunk-bnyw27ja.js} +2 -2
- package/dist/src/{chunk-rqc9ap3x.js → chunk-bpwsg76p.js} +2 -2
- package/dist/src/chunk-bvranw3g.js +4 -0
- package/dist/src/chunk-c25a84zb.js +4 -0
- package/dist/src/chunk-c27yv1dx.js +5 -0
- package/dist/src/chunk-c3ewxm4x.js +5 -0
- package/dist/src/{chunk-rvvy1bte.js → chunk-cb1ga9rd.js} +5 -5
- package/dist/src/chunk-cn7fwy7k.js +4 -0
- package/dist/src/chunk-cnvy4a64.js +4 -0
- package/dist/src/{chunk-7rz9898k.js → chunk-cqhw4yr6.js} +3 -3
- package/dist/src/{chunk-g04bwyj3.js → chunk-ctmfshjc.js} +2 -2
- package/dist/src/chunk-ctwmhz13.js +4 -0
- package/dist/src/{chunk-waqwcjyn.js → chunk-d3jx9bz5.js} +2 -2
- package/dist/src/{chunk-ayp07wbb.js → chunk-d6rb08ga.js} +1 -1
- package/dist/src/chunk-ddqhj4eg.js +5 -0
- package/dist/src/{chunk-r7bpkgff.js → chunk-ddrhs1c3.js} +2 -2
- package/dist/src/chunk-dnjnh9p6.js +4 -0
- package/dist/src/{chunk-wyrkw6hw.js → chunk-dw5rwgya.js} +3 -3
- package/dist/src/{chunk-3xkpk44w.js → chunk-e0870khr.js} +3 -3
- package/dist/src/chunk-ea3k10kj.js +4 -0
- package/dist/src/chunk-emv82m1w.js +7 -0
- package/dist/src/chunk-f3m6pdnx.js +4 -0
- package/dist/src/chunk-f84z32cb.js +4 -0
- package/dist/src/chunk-fpczgf0z.js +4 -0
- package/dist/src/{chunk-2tqzq5qh.js → chunk-g2js4c2v.js} +18 -18
- package/dist/src/chunk-g3af2qbk.js +5 -0
- package/dist/src/{chunk-3qwrzxh0.js → chunk-gadtna7s.js} +6 -6
- package/dist/src/{chunk-ybbtagbt.js → chunk-gcyx407v.js} +3 -3
- package/dist/src/{chunk-bfw6125s.js → chunk-gfpntwc1.js} +3 -3
- package/dist/src/chunk-gmnm5e3e.js +4 -0
- package/dist/src/chunk-gp6vb5gf.js +4 -0
- package/dist/src/chunk-gppgy7pa.js +4 -0
- package/dist/src/chunk-hegfz0ae.js +5 -0
- package/dist/src/chunk-hpzxdp1k.js +17 -0
- package/dist/src/{chunk-qcxzr2my.js → chunk-j69g8b50.js} +3 -3
- package/dist/src/chunk-jvstjnqm.js +19 -0
- package/dist/src/chunk-jzqrv78s.js +4 -0
- package/dist/src/chunk-k2948b8d.js +4 -0
- package/dist/src/chunk-k4ftd40d.js +4 -0
- package/dist/src/{chunk-bxmsax22.js → chunk-kd9vfaxh.js} +3 -3
- package/dist/src/{chunk-s3jc6cwp.js → chunk-kdczmgwk.js} +3 -3
- package/dist/src/{chunk-t6bfvfkg.js → chunk-ke3wn14v.js} +1 -1
- package/dist/src/chunk-kh5n7m6w.js +4 -0
- package/dist/src/{chunk-6wt9rgjf.js → chunk-khejfph4.js} +3 -3
- package/dist/src/chunk-kny2xemh.js +4 -0
- package/dist/src/chunk-knyzw9md.js +4 -0
- package/dist/src/chunk-mbzpt2hp.js +4 -0
- package/dist/src/chunk-mm8rcxad.js +4 -0
- package/dist/src/chunk-nc4516tx.js +4 -0
- package/dist/src/{chunk-6bznss4t.js → chunk-ntfrqrqn.js} +5 -5
- package/dist/src/chunk-nz5h2j52.js +4 -0
- package/dist/src/chunk-p22s97qy.js +4 -0
- package/dist/src/chunk-p9kt1sgr.js +6 -0
- package/dist/src/{chunk-yb97j25b.js → chunk-pf282r5g.js} +4 -4
- package/dist/src/chunk-pnd4mrxy.js +4 -0
- package/dist/src/chunk-pqqteyj6.js +4 -0
- package/dist/src/{chunk-6xmss8er.js → chunk-qj1tbnv2.js} +6 -6
- package/dist/src/chunk-qnh9egwr.js +4 -0
- package/dist/src/chunk-qy3khhf8.js +8 -0
- package/dist/src/{chunk-z637nqg8.js → chunk-r0vp315h.js} +6 -6
- package/dist/src/chunk-r4j43b9s.js +237 -0
- package/dist/src/{chunk-1p7xf5kb.js → chunk-r54cxxze.js} +3 -3
- package/dist/src/{chunk-yf7ympyz.js → chunk-r6pvhj33.js} +92 -92
- package/dist/src/chunk-rb7aa5gr.js +54 -0
- package/dist/src/chunk-rdj50kb4.js +4 -0
- package/dist/src/chunk-rnd4vcas.js +4 -0
- package/dist/src/{chunk-w5b2jwk3.js → chunk-s3y3zfcx.js} +8 -8
- package/dist/src/chunk-s4g43k75.js +5 -0
- package/dist/src/chunk-sfqe223f.js +311 -0
- package/dist/src/{chunk-284ptqa4.js → chunk-sqdrxjw5.js} +5 -5
- package/dist/src/{chunk-zgja5f3p.js → chunk-t54k47em.js} +4 -4
- package/dist/src/{chunk-3sy6ahhz.js → chunk-tek4pnvv.js} +10 -10
- package/dist/src/chunk-tn74y7af.js +4 -0
- package/dist/src/{chunk-thbh3jew.js → chunk-tvq0nzam.js} +3 -3
- package/dist/src/{chunk-0jrrsnc9.js → chunk-tx4f0h9c.js} +4 -4
- package/dist/src/chunk-vdqag3fj.js +5 -0
- package/dist/src/chunk-vz5zzs57.js +4 -0
- package/dist/src/chunk-w4s2vfpj.js +4 -0
- package/dist/src/{chunk-4hw3665t.js → chunk-w5yypt53.js} +11 -11
- package/dist/src/{chunk-8037tzzj.js → chunk-w68v64vh.js} +3 -3
- package/dist/src/chunk-whwj0pdk.js +5 -0
- package/dist/src/chunk-wnmqt1dc.js +4 -0
- package/dist/src/{chunk-cyy71ggq.js → chunk-wpe46vsa.js} +3 -3
- package/dist/src/{chunk-w3vs79ex.js → chunk-wxdjeb4k.js} +19 -19
- package/dist/src/chunk-xcqzwf9j.js +247 -0
- package/dist/src/chunk-xezekwwn.js +5 -0
- package/dist/src/chunk-xf19m15s.js +4 -0
- package/dist/src/chunk-xghbxha4.js +4 -0
- package/dist/src/{chunk-00167wan.js → chunk-xn9m3xc2.js} +5 -5
- package/dist/src/{chunk-26k317v5.js → chunk-yqfz4vts.js} +3 -3
- package/dist/src/chunk-z8tvs8nk.js +5 -0
- package/dist/src/chunk-zm2rehqb.js +5 -0
- package/dist/src/chunk-zs6dqm35.js +4 -0
- package/dist/src/daemon/processEntry.js +2 -2
- package/dist/src/index.js +4 -4
- package/dist/src/runtime/bunRuntimeGuard.js +2 -2
- package/dist/src/utils/workers/iosBundleExtractWorker.js +2 -2
- package/package.json +2 -2
- package/dist/src/chunk-0n6swkwg.js +0 -5
- package/dist/src/chunk-0qsy1qsx.js +0 -57
- package/dist/src/chunk-11m8wj8j.js +0 -237
- package/dist/src/chunk-23p5f095.js +0 -4
- package/dist/src/chunk-28re4xrg.js +0 -4
- package/dist/src/chunk-2f9rkmhx.js +0 -5
- package/dist/src/chunk-2fxdh48t.js +0 -4
- package/dist/src/chunk-2tbdrbt6.js +0 -4
- package/dist/src/chunk-32gvv9b4.js +0 -21
- package/dist/src/chunk-3f3t1x97.js +0 -8
- package/dist/src/chunk-3fspkbc7.js +0 -4
- package/dist/src/chunk-3vg455e6.js +0 -4
- package/dist/src/chunk-49bsqdx3.js +0 -4
- package/dist/src/chunk-5snsn9cf.js +0 -4
- package/dist/src/chunk-5tm9mn47.js +0 -54
- package/dist/src/chunk-5zc77a5t.js +0 -4
- package/dist/src/chunk-64j0majr.js +0 -19
- package/dist/src/chunk-65y8v4td.js +0 -17
- package/dist/src/chunk-6awz7vhq.js +0 -5
- package/dist/src/chunk-6ep7f5ge.js +0 -4
- package/dist/src/chunk-7cs2da62.js +0 -5
- package/dist/src/chunk-7g103b54.js +0 -4
- package/dist/src/chunk-7j5vj4pa.js +0 -4
- package/dist/src/chunk-7tw8x05v.js +0 -4
- package/dist/src/chunk-7zy586cb.js +0 -4
- package/dist/src/chunk-84nanf8s.js +0 -5
- package/dist/src/chunk-8gvwcv2p.js +0 -4
- package/dist/src/chunk-8thrmfat.js +0 -4
- package/dist/src/chunk-8zgzzs7k.js +0 -78
- package/dist/src/chunk-97b1zmaq.js +0 -4
- package/dist/src/chunk-9fth9ayh.js +0 -4
- package/dist/src/chunk-9j6anhjr.js +0 -4
- package/dist/src/chunk-bfjwqk8q.js +0 -4
- package/dist/src/chunk-bnhscm2n.js +0 -4
- package/dist/src/chunk-c1vs4g1n.js +0 -4
- package/dist/src/chunk-ct3e7yng.js +0 -4
- package/dist/src/chunk-ddzkz92z.js +0 -4
- package/dist/src/chunk-drdz8hee.js +0 -5
- package/dist/src/chunk-eersndy7.js +0 -5
- package/dist/src/chunk-eggq53ks.js +0 -4
- package/dist/src/chunk-f2dya7cs.js +0 -4
- package/dist/src/chunk-fbakd6cw.js +0 -4
- package/dist/src/chunk-fgb98zjj.js +0 -5
- package/dist/src/chunk-fmpad823.js +0 -5
- package/dist/src/chunk-g0xr8zw0.js +0 -4
- package/dist/src/chunk-g3rjs80x.js +0 -4
- package/dist/src/chunk-g78rtrfv.js +0 -4
- package/dist/src/chunk-gabgv3y5.js +0 -4
- package/dist/src/chunk-gmr45m8f.js +0 -4
- package/dist/src/chunk-gsyfebqj.js +0 -4
- package/dist/src/chunk-h5rpn9wr.js +0 -247
- package/dist/src/chunk-hb1x7v55.js +0 -4
- package/dist/src/chunk-hrfytkxh.js +0 -168
- package/dist/src/chunk-j4yjzbak.js +0 -4
- package/dist/src/chunk-jd6a5v6p.js +0 -5
- package/dist/src/chunk-kn5spq15.js +0 -4
- package/dist/src/chunk-m94qs0f0.js +0 -4
- package/dist/src/chunk-n03dmn5q.js +0 -5
- package/dist/src/chunk-n72qhwd9.js +0 -4
- package/dist/src/chunk-nr6y0n4y.js +0 -5
- package/dist/src/chunk-pcsen2vs.js +0 -4
- package/dist/src/chunk-ppfr0b8h.js +0 -4
- package/dist/src/chunk-q10bdnat.js +0 -4
- package/dist/src/chunk-q9xmq595.js +0 -4
- package/dist/src/chunk-qyqypn28.js +0 -5
- package/dist/src/chunk-r2epb56s.js +0 -4
- package/dist/src/chunk-r5bxavdx.js +0 -311
- package/dist/src/chunk-r8jf3d92.js +0 -4
- package/dist/src/chunk-rc0dbypm.js +0 -4
- package/dist/src/chunk-rhcty4ms.js +0 -4
- package/dist/src/chunk-rpvckv3p.js +0 -4
- package/dist/src/chunk-ry0mz41y.js +0 -4
- package/dist/src/chunk-sfv61xjb.js +0 -6
- package/dist/src/chunk-t7w8rctc.js +0 -4
- package/dist/src/chunk-v2wd4n3e.js +0 -5
- package/dist/src/chunk-w4zga19f.js +0 -4
- package/dist/src/chunk-w7hkv422.js +0 -5
- package/dist/src/chunk-xa73x2cx.js +0 -5
- package/dist/src/chunk-y2vs6jwg.js +0 -4
- package/dist/src/chunk-yattm52s.js +0 -4
- package/dist/src/chunk-yjawdzk8.js +0 -4
- package/dist/src/chunk-zs1sghs9.js +0 -4
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{i,zt,Bd,dr,re,qt,l,e}from"./chunk-r0vp315h.js";import{da,ar,LT,Bv,BT,qm,ua,To,ji,Pn,Km,Gm,Tc,An,ko,KT,La}from"./chunk-4vxeq0vd.js";import{dd,J,kn,z,L,li,o,lo,bd,Qo,OR,mr,dt,MR,Rr,n$,N,va,lt,wt,Nt,Ut,mn,a$,ft,js,rt,K,Ej,Eie,Ib,Ij,Dl,$u,fe,Sd,Ol,ba,wd,Ti,_b,Pr,hr,nP,Ee,Qt,gr,J$,Td,EO,M9,hn,zr,dy,xf,Ts,Zi,or,Poe,xO,p2,m2,Toe,nU,koe,hE,OO,bP,Cf,SP,qb,Dn,ur,V9,P2,A2,BO,T2,Of,x,Ce,E,Xs,Qi}from"./chunk-sfqe223f.js";import{HV,ite,sL,Lm,Bm,gp,z5}from"./chunk-661c50hh.js";import{Xp}from"./chunk-w5yypt53.js";import{Oe,jt,Tt}from"./chunk-e0870khr.js";import{FC,bL,SL,wL,RL,PL,CT,nW,vte,eg}from"./chunk-cqhw4yr6.js";import{od}from"./chunk-b3tdtq7r.js";import{Qc,HF,N5,Ev,qF,CV,hp,Wee,ed,DV,zee,wo,VF,jee,Fm,Kee,Gee,WF,vC,zF,jF,KF,GF,YF}from"./chunk-c27yv1dx.js";import{pW,ls,Na,rg,Rte,br,zi,EL,Ate}from"./chunk-vdqag3fj.js";import{XT,Ec,yg,vg,Tre,Tn,jw,Kw,Gw,cB,Kn,fa,bg,az,Wv,dB,Ha}from"./chunk-cb1ga9rd.js";import{r,t,u,Rt}from"./chunk-2b39zyxc.js";import{AsyncLocalStorage as Dt}from"async_hooks";var Fe=new Dt;function ST(n,a){return n?Fe.run(n,a):a()}function yC(){Fe.getStore()?.()}var He="Nothing is focused on tvOS; use pressButton to establish focus and observe before retrying tapOn.";function ie(n){let{left:a,top:s,right:c,bottom:d}=n.bounds;return JSON.stringify([n["resource-id"],a,s,c,d])}function Ve(n,a){return n.bounds.left===a.bounds.left&&n.bounds.top===a.bounds.top&&n.bounds.right===a.bounds.right&&n.bounds.bottom===a.bounds.bottom}function It(n,a){let s=n.bounds,c=a.bounds,d=(c.left+c.right-s.left-s.right)/2,p=(c.top+c.bottom-s.top-s.bottom)/2,h=d===0?[]:[d>0?"right":"left"],m=p===0?[]:[p>0?"down":"up"],f=s.left<c.right&&c.left<s.right;return(s.top<c.bottom&&c.top<s.bottom?!0:f?!1:Math.abs(d)>=Math.abs(p))?[...h,...m]:[...m,...h]}function Ht({maxMoves:n=30,maxSearchMoves:a=60,focusTimeoutMs:s=3000,focusPollIntervalMs:c=200}){for(let[d,p]of Object.entries({maxMoves:n,maxSearchMoves:a,focusTimeoutMs:s}))if(!Number.isInteger(p)||p<0)throw new t(`tvOS ${d} must be a non-negative integer.`);if(!Number.isInteger(c)||c<=0)throw new t("tvOS focusPollIntervalMs must be a positive integer.");return{maxMoves:n,maxSearchMoves:a,focusTimeoutMs:s,focusPollIntervalMs:c}}function Vt(n,a){let s=Object.entries(n).filter(([c,d])=>d!==void 0&&(d!==!1||c==="ensureChecked")&&!["action","elementId","text","index"].includes(c));if(n.action!=="tap"||s.length)throw new t(`tvOS tapOn supports only action tap and elementId, text, index; unsupported: ${n.action!=="tap"?n.action:s.map(([c])=>c).join(", ")}.`);if(n.index!==void 0&&(!Number.isInteger(n.index)||n.index<0))throw new t("tvOS tap index must be a non-negative integer.");return Ht(a)}function Bt(n,a){return(a.elementId!==void 0||a.text!==void 0)&&(a.elementId===void 0||n["resource-id"]===a.elementId||n["view-id"]===a.elementId)&&(a.text===void 0||n.text===a.text)}function Be(n,a){return a.reduce((s,c)=>{let d=c.bounds,p=n.bounds;return d.left<=p.left&&d.top<=p.top&&d.right>=p.right&&d.bottom>=p.bottom&&ft(d)>ft(s.bounds)?c:s},n)}function Lt(n,a){return Ve(n,a)||a.checkable==="true"&&Be(a,[n])===n}function te(n){return JSON.stringify([n["resource-id"],n["view-id"],n.text,n.class])}function De(n){return JSON.stringify([n["resource-id"],n["view-id"],n.class])}function Mt(n,a){if(!a)return"[]";let s=De(a);return JSON.stringify([ie(a),n.filter((c)=>De(c)===s).map((c)=>[ie(c),c.text])])}function _t(n,a,s){let{left:c,top:d,right:p,bottom:h}=n.bounds;return c>=0&&d>=0&&p<=a&&h<=s}async function Ie(n,a,s,c){let d=qm(await n.hierarchy(s));s?.throwIfAborted();let p=new K().flattenViewHierarchy(d).map(({element:S})=>S),h=p.find((S)=>S.focused==="true"),m=Mt(p,h),f=c?p.filter((S)=>te(S)===c.key):[];if(h&&c&&f.length!==c.count)throw new t("The tvOS tapOn target disappeared or became ambiguous; observe and retry with its current identifier or exact text.");let y=p.filter((S)=>S.bounds.right>S.bounds.left&&S.bounds.bottom>S.bounds.top&&Bt(S,a)),b=y.map((S,O)=>({element:S,windowRank:_t(S,d.screenWidth,d.screenHeight)?0:1,area:ft(S.bounds),order:O,interactive:!1})).sort(Cf).map(({element:S})=>S),T=c?f[c.ordinal]:SP(b,(S)=>Be(S,y))[a.index??0];if(!T||c)return{focus:h,target:T,identity:c,signature:m};let v=te(T),g=p.filter((S)=>te(S)===v);return{focus:h,target:T,identity:{key:v,ordinal:g.indexOf(T),count:g.length},signature:m}}function Ne(n){if(!n.focus)throw new t(He);return n.focus}async function Le({client:n,options:a,signal:s,timer:c,focusTimeoutMs:d,focusPollIntervalMs:p},h){s?.throwIfAborted();let m=await Ie(n,a,s,h),f=c.now()+d;while(!m.focus&&c.now()<f)await l(()=>c.sleep(Math.min(p,f-c.now())),{timer:c,signal:s,label:"tvOS focus settling"}),s?.throwIfAborted(),m=await l(()=>Ie(n,a,s,h),{timer:c,signal:s,timeoutMs:Math.max(0,f-c.now()),timeoutError:()=>new t(He),label:"tvOS focus settling"});return Ne(m),m}async function Wt(n,a,s){let{client:c,signal:d}=n,p=a,h=0,m=async(y)=>{if(h>=s)throw new t(`No tvOS element matched after searching ${s} focus moves; observe and check the identifier, exact text or index, or move closer with pressButton before retrying.`);h++,await c.request({type:"request_press_button",action:y},d),d?.throwIfAborted();let b=await Le(n),T=b.signature!==p.signature;return p=b,T},f=async(y)=>{while(!p.target&&await m(y));return Boolean(p.target)};for(let y of["down","up"]){do if(await f("right")||await f("left"))return p;while(await m(y));if(p.target)return p}throw new t("No tvOS element matched after searching the screen with focus moves; observe and check the identifier, exact text or index.")}function ne(n){return n["resource-id"]||n.text||ie(n)}function Gt(n,a,s){if(n>=a)throw new t(`tvOS tapOn exceeded maxMoves (${a}) before reaching ${ne(s)}; observe and move closer with pressButton before retrying.`)}async function $t(n,a,s){let{options:c}=n,d=await Le(n,a);if(!d.target&&!a){if(c.elementId===void 0&&c.text===void 0)throw new t("No tvOS element matched; observe and check the identifier, exact text or index.");d=await Wt(n,d,s)}return{focus:Ne(d),target:d.target,identity:d.identity,signature:d.signature}}async function Me(n,a,s,c={}){let{maxMoves:d,maxSearchMoves:p,focusTimeoutMs:h,focusPollIntervalMs:m}=Vt(a,c);s?.throwIfAborted();let f={client:await ua(n,s),options:a,signal:s,timer:c.timer??i,focusTimeoutMs:h,focusPollIntervalMs:m},{client:y}=f,b=new Map,T,v;for(let g=0;;g++){s?.throwIfAborted();let S=await $t(f,v,p),{focus:O,target:R}=S;if(v=S.identity,Lt(O,R))return await y.request({type:"request_press_button",action:"select"},s),{success:!0,action:"tap",element:R,...Ve(O,R)?{}:{debug:{activatedAncestor:O}}};let w=b.get(S.signature)??new Set;if(T?.signature===S.signature)w.add(T.direction),b.set(S.signature,w);let A=It(O,R).find((Q)=>!w.has(Q));if(!A)throw new t(`tvOS focus stopped making progress from ${ne(O)} toward ${ne(R)}; the target may be unreachable or in a focus trap. Observe and navigate with pressButton before retrying.`);Gt(g,d,R),await y.request({type:"request_press_button",action:A},s),T={signature:S.signature,direction:A}}}var Kt=new Set(["\b","\x7F","\uF728"]);function Xt(n,a,s){if(s.container!==void 0||s.selectionStrategy!==void 0||s.layer!==void 0||s.display!==void 0||n.length===0)throw new t("watchOS sendKeys supports only type commands into the focused field; focus it with tapOn first.");if(a!==void 0&&(a.testTag!==void 0||a.textAny!==void 0||a.elementId===void 0&&a.text===void 0))throw new t("watchOS sendKeys selector supports only exact elementId or text; focus the field with tapOn first.");return n.map((c)=>{if(c.action!=="type"||!c.text||c.operation==="replace"||c.mode!==void 0&&c.mode!=="auto"||c.keyboardProfile!==void 0)throw new t("watchOS sendKeys supports only non-empty append type commands; focus the field with tapOn first.");if([...c.text].some((d)=>Kt.has(d)))throw new t("watchOS sendKeys appends text only; text containing a delete key would erase existing content.");return c})}var _e=[50,100,200,250,250,250,250];function ze(n){return n instanceof La&&n.errorCode==="command_failed"&&n.message.startsWith("No focused text field")}async function Yt(n,a,s,c){await new kn(s).executeOrThrow(()=>n.request({type:"type",text:a},c).then(()=>{return}),{maxAttempts:_e.length+1,delays:_e,signal:c,shouldRetry:ze,expectedFailure:{reason:"sendKeys reports the focus refusal as a failed command",matches:ze}})}async function We(n,a,s,c={}){let d=Xt(a,s,c),{signal:p,timer:h}=c;p?.throwIfAborted();let m=To.require(n);if(s!==void 0)await HV(n,{action:"tap",...s},p,!0);let f=[];for(let[y,b]of d.entries()){p?.throwIfAborted();try{if(y===0&&s!==void 0)await Yt(m,b.text,h,p);else await m.request({type:"type",text:b.text},p)}catch(T){p?.throwIfAborted();let v=u(T,"watchOS text entry failed; focus a text field with tapOn first");return e.warn(v.message,T),f.push({index:y,action:"type",success:!1,resolvedMode:"xcuiTypeText",error:v.message}),{success:!1,completedCommands:y,failedIndex:y,commands:f,error:v.message}}f.push({index:y,action:"type",success:!0,textLength:[...b.text].length,resolvedMode:"xcuiTypeText"})}return{success:!0,completedCommands:f.length,commands:f}}var Jt=new Set(["\b","\x7F","\uF728"]);function Zt(n){let a=Object.entries(n).filter(([s,c])=>c!==void 0&&(c!==!1||s==="ensureChecked")&&!["action","elementId","text","index"].includes(s));if(n.action!=="tap"||a.length||n.elementId===void 0&&n.text===void 0)throw new t("visionOS tapOn supports only action tap with elementId, exact text and optional index in a window or ornament.");if(n.index!==void 0&&(!Number.isInteger(n.index)||n.index<0))throw new t("visionOS tap index must be a non-negative integer.")}function Ue(n){if(n.enabled==="false")return 4;if(n["resource-id"])return n.clickable==="true"?0:1;return n.clickable==="true"?2:3}function er(n){if(!n["resource-id"]&&!n.text)throw new t("The matched visionOS element has no accessibility identifier or text; add an accessibility label or identifier to the control, then observe again.");if(n.enabled==="false")throw new t("The matched visionOS element is disabled; observe and select an enabled control.")}async function Ge(n,a,s){return Zt(a),BT(n,s,()=>tr(n,a,s))}async function tr(n,a,s){let c=await Bv(n,s),d=LT(await c.hierarchy(s)),p=new K().flattenViewHierarchy(d).map(({element:v})=>v),m=p.filter((v)=>(a.elementId===void 0||v["resource-id"]===a.elementId||v["view-id"]===a.elementId)&&(a.text===void 0||v.text===a.text)).sort((v,g)=>Ue(v)-Ue(g))[a.index??0];if(!m)throw new t("No visionOS element matched the selector and index; observe and use its identifier or exact text.");er(m);let f=m["resource-id"]??"",y=m.text??"",b=p.filter((v)=>(v["resource-id"]??"")===f),T=b.filter((v)=>v.enabled!=="false"&&v.class===m.class&&(v.text??"")===y);if(T.length>1){let v=T.map((g)=>`className=${g.class}, text=${JSON.stringify(g.text??"")}, bounds=${JSON.stringify(g.bounds)}`);throw new t(f?`The visionOS match was ambiguous for identifier '${f}'; candidates: ${v.join("; ")}. Pass index or a distinct text/elementId to select a distinguishable target.`:`The visionOS match was ambiguous for type ${m.class} and label ${JSON.stringify(y)}; candidates: ${v.join("; ")}. Pass index to select a distinguishable type/label or add an accessibility identifier; identical type/label matches cannot be distinguished by index.`)}return s?.throwIfAborted(),await c.request({type:"request_tap_element",identifier:f,...!f||b.length>1?{label:y,elementType:Number(m.class)}:{}},s),{success:!0,action:"tap",element:m}}async function qe(n,a,s,c={}){if(s!==void 0||c.container!==void 0||c.selectionStrategy!==void 0||c.layer!==void 0||c.display!==void 0||a.length===0)throw new t("visionOS sendKeys supports only type commands into the focused field; focus it with tapOn first.");let d=a.map((f)=>{if(f.action!=="type"||!f.text||f.operation==="replace")throw new t("visionOS sendKeys supports only non-empty append type commands; focus the field with tapOn first.");if([...f.text].some((y)=>Jt.has(y)))throw new t("visionOS sendKeys appends text only; text containing a delete key would erase existing content.");return f}),{signal:p}=c,h=await Bv(n,p),m=[];for(let[f,y]of d.entries()){p?.throwIfAborted();try{await h.request({type:"request_append_text",text:y.text},p)}catch(b){p?.throwIfAborted();let T=u(b,"visionOS text entry failed; focus a text field with tapOn first");return e.warn(T.message,b),m.push({index:f,action:"type",success:!1,error:T.message}),{success:!1,completedCommands:f,failedIndex:f,commands:m,error:T.message}}m.push({index:f,action:"type",success:!0,textLength:[...y.text].length})}return{success:!0,completedCommands:m.length,commands:m}}function ae(n){return n==="watchos"||n==="tvos"||n==="visionos"}function $e(n,a,s){switch(n.platform){case"visionos":return Ge(n.deviceId,a,s);case"tvos":return Me(n.deviceId,a,s);case"watchos":return HV(n.deviceId,a,s);default:return}}function Hee(n,a,s,c={}){return(n.platform==="watchos"?We:n.platform==="visionos"?qe:Ate)(n.deviceId,a,s,c)}var P=3;function V(n,a,s,c){let d=rt(a);if(c&&d===c.source)return!0;if(!c&&Ke(n,a))return!0;if(!s||!d)return!1;let p=c?[c]:s.filter((h)=>h.element&&Ke(n,h.element));return s.some((h)=>{if(h.source!==d||!h.element)return!1;return p.some((m)=>{for(let[f,y]of[[h,m],[m,h]]){let b=f.parentIndex;while(b!==void 0){let T=s[b];if(T===y)return!0;if(Dn(T.properties))break;b=T.parentIndex}}return!1})})}function Ke(n,a){for(let s of["resource-id","view-id","test-tag"]){let c=n[s],d=a[s];if(s==="view-id"&&c!==d&&[c,d].some((p)=>String(p).startsWith("s2-")))continue;if(typeof c==="string"&&c.length>0&&typeof d==="string"&&d.length>0)return c===d}return mn(n.bounds,a.bounds,P)&&se(n,a)}function C(n,a){let s=n.text??n["content-desc"]??n["ios-accessibility-label"]??a.text??a.textAny?.[0];return typeof s==="string"&&s.length>0?JSON.stringify(s):"the matched element"}function se(n,a,s){if(n.class!==a.class)return!1;let c=["resource-id","test-tag"].filter((m)=>{let f=n[m];return typeof f==="string"&&f.length>0});if(c.length>0)return c.every((m)=>n[m]===a[m]);let d=n.text??n["content-desc"]??n["ios-accessibility-label"],p=a.text??a["content-desc"]??a["ios-accessibility-label"],h=typeof d==="string"&&d.length>0?d:s;return typeof h==="string"&&h.length>0&&h===p}function k(n){let a=[];for(let s of n){let c=a.find((d)=>d.every((p)=>p.rootGroup!==s.rootGroup&&rr(p,s)));if(c)c.push(s);else a.push([s])}return a.map((s)=>s[0])}function rr(n,a){return Boolean(n.element&&a.element&&n.className===a.className&&mn(n.element.bounds,a.element.bounds,P)&&Ha(n.element)===Ha(a.element)&&["resource-id","test-tag","view-id","text","content-desc","ios-accessibility-label"].every((s)=>n.element[s]===a.element[s]))}function oe(n,a){let s=P;return a$(n.bounds,a.bounds,s)&&Math.abs(n.bounds.right-n.bounds.left-(a.bounds.right-a.bounds.left))<=s&&Math.abs(n.bounds.bottom-n.bounds.top-(a.bounds.bottom-a.bounds.top))<=s}function je(n,a){if(!n.length||n.length!==a.length)return;let s=a[0].element.bounds.top-n[0].element.bounds.top;return n.every((d,p)=>{let h=d.element,m=a[p].element;return h.class===m.class&&oe(h,m)&&mn({...h.bounds,top:h.bounds.top+s,bottom:h.bounds.bottom+s},m.bounds,P)})?s:void 0}function Xe(n,a){let s;for(let c of["resource-id","test-tag","view-id"]){let d=n[c];if(typeof d!=="string"||d.length===0)continue;let p=k(a.filter((h)=>h.element&&Dn(h.properties)&&h.element[c]===d));if(p.length===1)return{key:c,value:d,shared:!1};if(p.length>1)s??={key:c,value:d,shared:!0}}return s}function Ye(n){if(!n.testTag)throw new t("tapOn requires non-blank text, textAny, elementId, or testTag to interact with");return n.testTag}var Rw=Symbol("tapFocusFailure"),BF=Symbol("tapResolvedLayer");function B(n,a,s){if(!ba(n))return;n=DV(a,n,s);let c=rt(a);if(!c)return;let d=new K;for(let p of["prototype","app"])if(d.flattenViewHierarchy(wd(n,p),{includeWindows:!0}).some((m)=>rt(m.element)===c))return p;return}function D(n,a){if(a!==void 0)Object.defineProperty(n,BF,{value:a,enumerable:!1,configurable:!0,writable:!0});return n}function I(n,a,s){if(n==="focus"&&s instanceof wo)Object.defineProperty(a,Rw,{value:s.reason});return a}class Nm extends t{}function U(n){return n.length?{warnings:n}:{}}function Je(n,a){return a?[...n,a]:n}class ce{host;constructor(n){this.host=n}createErrorResult(n,a,s){return I(n,PL(n,a),s)}validateOptions(n){if(n.ensureChecked!==void 0&&n.action!=="tap")return'tapOn ensureChecked requires action "tap"';if(n.ensureChecked!==void 0&&n.selectionStrategy==="random")return"tapOn ensureChecked cannot use random selection; use a unique selector or index";if([n.text,n.elementId,n.testTag,n.textAny,n.accessibilityLink].filter(Boolean).length!==1)return"tapOn requires exactly one of text, textAny, elementId, testTag, or accessibilityLink";if(n.textAny&&n.textAny.length===0)return"tapOn textAny selector must be non-empty";let s=wL(n.container,"tapOn");if(s)return s;return this.validateSemanticLinkOptions(n)}validateSemanticLinkOptions(n){if(n.layer!==void 0&&this.hasSemanticLinkTarget(n))return"tapOn layer cannot be used with accessibilityLink or subtext";if(n.selectionStrategy==="unique"&&(n.sibling||n.accessibilityLink))return"tapOn unique selection cannot use sibling or direct accessibilityLink; select a unique owner with subtext instead";if(n.relativePosition!==void 0)return"tapOn relativePosition is no longer supported; use accessibilityLink or subtext";if(!this.hasSemanticLinkTarget(n))return null;return this.semanticLinkValidationErrors(n).find(({invalid:a})=>a)?.error??null}hasSemanticLinkTarget(n){return[n.accessibilityLink,n.subtext].some((a)=>a!==void 0)}semanticLinkValidationErrors(n){return[{invalid:[n.accessibilityLink,n.subtext].every((a)=>a!==void 0),error:"tapOn accessibilityLink and subtext cannot be used together"},{invalid:n.action!=="tap",error:"tapOn semantic link activation supports only the tap action"},{invalid:n.sibling,error:"tapOn semantic link activation cannot use sibling"},{invalid:Boolean(n.retryIfNoChange??n.ensureTap),error:"tapOn semantic link activation cannot retry an acknowledged link activation"},{invalid:n.ensureChecked!==void 0,error:"tapOn semantic link activation cannot ensure checked state"},{invalid:n.searchUntil,error:"tapOn semantic link activation cannot use searchUntil"},{invalid:this.semanticLinkTextIsBlank(n),error:"tapOn semantic link text must be non-empty"},{invalid:this.semanticLinkOccurrenceIsInvalid(n),error:"tapOn semantic link occurrence must be a non-negative integer"},{invalid:n.subtext?n.index!==void 0:!1,error:"tapOn owner-scoped semantic link activation cannot use index; use a unique owner selector"},{invalid:n.subtext?n.selectionStrategy==="random":!1,error:"tapOn owner-scoped semantic link activation cannot use random selection; use a unique owner selector"}]}semanticLinkTextIsBlank(n){return(n.subtext?.text??n.accessibilityLink)?.trim().length===0}semanticLinkOccurrenceIsInvalid(n){let a=n.subtext?.occurrence??n.index??0;return![Number.isInteger(a),a>=0].every(Boolean)}async activateSemanticLink(n,a,{owner:s,viewHierarchy:c,signal:d}){let p=(h,m)=>{if(h.dispatched&&h.acknowledged!==!0)throw m(),Tn(h.error)};if(s&&!this.host.hasUniqueSemanticLinkOwner(s,c))return{success:!1,error:"Container-scoped semantic link activation requires a unique resource-id owner identity"};if(this.host.usesAndroidLinkActivation()){let h=s?Kn(s):void 0;if(s&&!h)return{success:!1,error:"Container-scoped semantic link activation requires a stable native owner identity"};let m=await this.host.accessibilityService().requestActivateAccessibilityLink({text:n,occurrence:a,selector:h,signal:d});return p(m,()=>{E.getExistingInstance(this.host.device().deviceId)?.invalidateCache()}),{success:m.success,error:m.error}}if(this.host.usesIosLinkActivation()){let h=s?.["resource-id"];if(s&&(typeof h!=="string"||h.length===0))return{success:!1,error:"Container-scoped semantic link activation requires a stable native owner identity"};let m=await x.getInstance(this.host.device()).requestActivateAccessibilityLink({text:n,occurrence:a,ownerResourceId:h,signal:d});return p(m,()=>nW(this.host.device(),{success:!0})),nW(this.host.device(),m),{success:m.success,error:m.error,warning:m.warning}}return{success:!1,error:Rt(this.host.device().platform,"tap on elements").message}}hasUniqueSemanticLinkOwner(n,a){if(!a)return!1;let s=this.host.elementParser().flattenViewHierarchy(a,{includeWindows:!0}).map(({element:d})=>d);if(this.host.usesCapturedOwnerIdentity()){let d=n["resource-id"];return typeof d==="string"&&d.length>0&&ir(s.filter((p)=>p["resource-id"]===d)).length===1}let c=Kn(n);return c!==void 0&&s.filter((d)=>Dl(d,c)).length===1}async activateAccessibilityLinkPhase(n,a,{observeResult:s,viewHierarchy:c,activationWarnings:d,signal:p}){let h=n.index??0,m=this.host.resolveContainerElement(c,this.host.withObservationScreenSize(n,s));if(n.container&&!m)return{success:!1,error:"Semantic link container is no longer present"};let f=await this.host.activateSemanticLink(a,h,{owner:m,viewHierarchy:c,signal:p});if(!f.success)return{success:!1,error:f.error};return{success:!0,action:n.action,element:{text:a,bounds:{left:0,top:0,right:0,bottom:0}},activatedSubtext:{text:a,occurrence:h},...U(Je(d,f.warning))}}async activateSubtextPhase({options:n,subtext:a,element:s,viewHierarchy:c,selectedElement:d,searchUntil:p,activationWarnings:h,signal:m}){let f=a.occurrence??0,y=await this.host.activateSemanticLink(a.text,f,{owner:s,viewHierarchy:c,signal:m});if(!y.success)return{success:!1,error:y.error};return{success:!0,action:n.action,element:s,selectedElement:d,searchUntil:p,activatedSubtext:{text:a.text,occurrence:f},...U(Je(h,y.warning))}}}function ir(n){let a=n.filter((s)=>{let c=rt(s);return!c||!n$(c)});return a.length>0?a:n}class le{host;constructor(n){this.host=n}async prepareAndroidDisplaySelection(n,a){let{target:s,signal:c}=a,d=a.selection,p=s.observation.viewHierarchy;if(!p)throw new t("Selected display has no view hierarchy");let h=await this.host.refreshEnsureCheckedSelection(n,s.observation,d,c);d=h.selection,p=h.viewHierarchy;let m={durationMs:0,requestCount:0,changeCount:0},f=d.element&&this.host.ensureCheckedBeforeTap(n,d.element,this.host.buildSelectedElementMetadata(d),m);if(f)return{result:f};if(this.host.strategy().shouldRunPreTapStability(n)){let y=await this.host.resolveAndroidStableTapTargetAfterRefreshes(n,s.observation,n.action,{requireResourceId:!1,signal:c});if(!y.ok)return{result:{success:!1,error:y.error}};this.host.replaceObservationHierarchy(s.observation,y.viewHierarchy,!0),p=y.viewHierarchy,d={...y.selection,element:y.tapElement};let b=this.host.ensureCheckedBeforeTap(n,y.selection.element??y.tapElement,this.host.buildSelectedElementMetadata(d),m);if(b)return{result:b}}return{selection:d,hierarchy:p}}async executeOnAndroidDisplay(n,a){let{target:s,signal:c}=a,d=await this.prepareAndroidDisplaySelection(n,a);if("result"in d)return d.result;let{selection:p,hierarchy:h}=d,m=p.element;if(!m?.bounds)throw new wo("Element not found on selected display","not-found");let f=this.host.buildSelectedElementMetadata(p),y=B(h,m,re(this.host.device().platform,"tapOn"));if(n.action==="focus"){if(!Dn(m))return{success:!1,action:n.action,element:m,selectedElement:f,error:`Cannot focus ${C(m,n)} because it is not an editable input`};if(Ha(m))return D({success:!0,action:n.action,element:m,selectedElement:f,wasAlreadyFocused:!0,focusChanged:!1,focusVerified:!0,...this.host.geometry().getElementCenter(m)},y)}let b=this.host.visibleTapBounds(p,h,{screenSize:s.observation.screenSize,options:n}),T=b&&this.host.resolveVisibleTapPoint(m,h,b,{options:n,screenSize:s.observation.screenSize});if(!T)throw new wo("Matched element has no visible tap area on selected display",this.host.tapPoints().visibilityFailureReason(p,h,s.observation.screenSize));let v=n.retryIfNoChange?this.host.hashViewHierarchy(h):null,g=[...a.talkBack.warnings],S=await this.androidDisplayDispatch(n,{...a,onWarning:(O)=>g.push(O)});if(yC(),await S(T),v&&this.host.strategy().retryTapIfNoChange)await this.host.retryTapIfNoChange(v,T,n.action,{longPressDuration:this.host.strategy().longPressDurationMs,tapElement:m,options:{...this.host.withObservationScreenSize(n,s.observation),verification:{refresh:n.verification.refresh,dispatch:S}},isTalkBackEnabled:!1,screenSize:s.observation.screenSize,signal:c,selection:p});return D({success:!0,action:n.action,element:m,selectedElement:f,...U(g)},y)}async resolveAndroidDisplayTalkBack(n){let a=[],s=await this.host.strategy().isAccessibilityServiceEnabled((d)=>a.push(d)),c=s?vg(n.displayId):void 0;if(c)throw c;return{enabled:s,warnings:a}}async androidDisplayDispatch(n,a){return cB(this.host.accessibilityService(),this.host.adb(),{action:n.action==="focus"?"tap":n.action,duration:n.duration},{target:a.target,signal:a.signal,onDispatched:a.onDispatched,timer:this.host.timer(),onWarning:a.onWarning,talkBack:a.talkBack.enabled?{strategy:this.host.talkBackStrategy(),driver:this.host.talkBackDriverFactory().createDriver(this.host.device())}:void 0})}selectElementOnDisplay(n,a){if(n.action==="focus"){let s=this.host.findElementInHierarchy(n,a).selection;if(s.element)return s;let c=this.host.findElementInHierarchy({...n,action:"tap"},a).selection;return c.element&&!Dn(c.element)?c:s}return this.host.findElementInHierarchy(n,a).selection}async resolveAndroidDisplaySelection(n,a,s){if(!a.viewHierarchy)throw new t("Selected display has no view hierarchy");if(n.action==="focus"){let d=this.selectElementOnDisplay(this.host.withObservationScreenSize(n,a),a.viewHierarchy);if(d.element)return{selection:d,stats:{durationMs:0,requestCount:0,changeCount:0}}}let c=await this.host.searchForElement(n,a,s);if(this.host.replaceObservationHierarchy(a,c.viewHierarchy,c.refreshedFromDevice),!c.selection.element)try{if(c.visibilityError)throw c.visibilityError;await this.host.handleElementNotFound(n,{containerFound:c.containerFound,signal:s,selection:c.selection})}catch(d){return e.warn(`tapOn display resolution failed: ${r(d)}`,d),{result:I(n.action,{...this.host.createErrorResult(n.action,r(d)),searchUntil:c.stats},d)}}return c}async observedAndroidDisplayInteraction(n,a){let{target:s,signal:c}=a,d=await this.resolveAndroidDisplayTalkBack(s),h={...n,verification:{refresh:(v)=>EL(s,this.host.hierarchyCapture(),v,{stale:()=>this.host.staleDisplay(s.observation.display.generation??this.host.displayTransitionReader().identityRevision(this.host.device().deviceId)),signal:c})}},m=await this.resolveAndroidDisplaySelection(h,s.observation,c);if("result"in m)return m.result;let{selection:f,stats:y}=m,b,T=await this.host.observedInteraction(async()=>{let v=await this.executeOnAndroidDisplay(h,{target:s,selection:f,signal:c,talkBack:d,onDispatched:()=>{b=this.host.timer().now()}});if(b!==void 0)a.onDispatchCompleted();return v},{...jt.rawCoordinateGesture,display:s.followUpDisplay,previousObservation:s.observation,signal:c,...n.ensureChecked!==void 0?{observationHostTimestampProvider:()=>b}:{}});if(T.searchUntil=y,b===void 0)s.assertCurrent();else if(this.host.checkPostActionDisplay(T,s.assertCurrent,c),T.staleDisplay)return this.host.unverifiableDisplayPostState(T,n);if(T.success&&T.skipped!=="already-checked")await this.host.applyEnsureCheckedResult(T,h,c);return this.finalizeDisplayFocusResult(T,n,f,s.observation)}unverifiableDisplayPostState(n,a){if(!n.staleDisplay||a.action!=="focus"&&a.ensureChecked===void 0)return n;return Qt({...n,success:!1,error:void 0},new hr(new Ee(n.staleDisplay)))}finalizeDisplayFocusResult(n,a,s,c){if(a.action!=="focus"||!n.success||n.wasAlreadyFocused)return n;let d=s.matchedElement!==n.element?s.matchedElement?.text:void 0;if(n.focusVerified=this.host.verifyFocusedInputTarget(a,n.element,n.observation,{labelText:d,selectedIndex:n.selectedElement?.indexInMatches,preTapHierarchy:c.viewHierarchy}),!n.focusVerified)n.success=!1,n.error=`Failed to confirm focus on editable input ${C(n.element,a)}: the focused field could not be matched to the target`;return n}async executeOnDisplay(n,a,s){let c=n.display,d=!1;if(c!==void 0)try{let p=["subtext","accessibilityLink","focusFirst","screenReaderNavigation"].find((y)=>n[y]!==void 0);if(p)throw new t(nP(p));if(n.ensureTap)n={...n,preTapStability:!0,retryIfNoChange:!0};let m=n.ensureChecked!==void 0||n.sibling!==void 0||n.textAny!==void 0||n.searchUntil!==void 0?this.host.validateOptions(n):null;if(m)return this.host.createErrorResult(n.action,m);if(n.searchUntil!==void 0)this.host.getSearchUntilDuration(n);let f=await zi(this.host.device(),c,this.host.observeScreen(),{adb:this.host.adb(),lastRenderedObservation:this.host.lastRenderedObservation(),signal:a,transitions:this.host.displayTransitionReader()});if(this.host.routesAndroidDisplay())return await this.observedAndroidDisplayInteraction(n,{target:f,signal:a,onDispatchCompleted:()=>{d=!0}})}catch(p){this.host.rethrowObservationAbort(p,a,d),this.host.rethrowKeyboardOcclusion(p,n.action,s),e.warn(`tapOn display routing failed: ${r(p)}`,p);let h=this.host.completedDisplayFailure(p,d);return Qt(this.host.createErrorResult(n.action,r(h),h),h)}return}didCompleteDisplayGesture(n,a){return a!==void 0&&n.success&&!n.skipped&&!n.wasAlreadyFocused}completedDisplayFailure(n,a){return a&&n instanceof Ee?new hr(n):n}rethrowKeyboardOcclusion(n,a,s){if(s?.throwOnKeyboardOcclusion&&this.host.strategy().rethrowsKeyboardOcclusion&&a==="focus"&&n instanceof Nm)throw e.debug(`Tap on element awaits IME recovery: ${r(n)}`,n),n}}function nr(n,a){return n.left<=a.left&&n.top<=a.top&&n.right>=a.right&&n.bottom>=a.bottom}function de(n){return`[${n.left},${n.top}][${n.right},${n.bottom}]`}function sr(n){return{x:Math.round((n.left+n.right)/2),y:Math.round((n.top+n.bottom)/2)}}function M(n){let a=n["resource-id"]??n["content-desc"]??n.text,s=[a===void 0?void 0:`"${a}"`,n.bounds?de(n.bounds):void 0].filter((c)=>c!==void 0);return s.length?s.join(" "):"(unlabelled)"}function Qe(n){if(!n.bounds)return"Observe the screen before retrying.";let{x:a,y:s}=sr(n.bounds);return`Observe the screen; if the intended control was not activated, use tapAt {x: ${a}, y: ${s}} (the matched element's center).`}function cr(n,a){if(!n?.bounds||!a.bounds||nr(a.bounds,n.bounds))return;return`The activated element ${M(a)} does not contain the matched element ${M(n)}, so a different control may have been activated. ${Qe(n)}`}function lr(n,a){let s=n??a;return`TalkBack activation is unconfirmed: the screen did not change after activating ${!!n?.bounds&&!!a.bounds&&de(n.bounds)!==de(a.bounds)&&n?`${M(a)} for the matched element ${M(n)}`:`the matched element ${M(s)}`}. `+Qe(s)}function Ze(n,a,s){if(n==="focus")return[];let c=cr(a.matchedElement??a.element??void 0,s);return c?[c]:[]}function et(n,a){if(a&&n.effect?.screenChanged===!1)n.warnings=[...n.warnings??[],lr(a.matched,n.element)]}function pr(n,a,s){if(n.warnsOnDisabledElement&&Bd(a.enabled))s.push("The matched element is disabled; the tap may have no effect.")}class pe{host;constructor(n){this.host=n}platform(){return re(this.host.device().platform,"tapOn")}async executeWithReadScope(n,a={}){let{progress:s,signal:c,recovery:d,settlePostTapEffect:p}=a,h=dB(a.deadlineMs);if(this.host.assertLongPressWithinRequestBudget(n,h),n.display!==void 0){let T=await this.host.executeOnDisplay(n,c,d);if(T)return T}if(!n.action)return this.host.createErrorResult(n.action,"tap on action is required");let m=n.action;if(n.ensureTap)n={...n,preTapStability:!0,retryIfNoChange:!0};let f=this.host.validateOptions(n);if(f)return this.host.createErrorResult(n.action,f);let y=J();y.serial("tapOnElement");let b={options:n,requestedAction:m,effectiveAction:m,signal:c,recovery:d,request:h,perf:y,previousObserveResult:null,selectionCapture:null,completedDisplayGesture:!1,settlePostTapEffect:p};try{o(c);let T=await this.host.observedInteraction((v,g)=>this.executeObservedTap(b,v,g),{queryOptions:{text:n.text??n.textAny?.[0],elementId:n.elementId,containerElementId:n.container?.elementId},...jt.selectorResolvedGesture,display:n.display,timeoutMs:Tt.gesture,progress:s,perf:y,signal:c,deferPredictionOutcome:!0,deferPostActionScreenshot:!0,...n.ensureChecked!==void 0?{observationHostTimestampProvider:()=>b.ensureCheckedTapTimestamp}:{},predictionContext:{toolName:"tapOn",toolArgs:this.host.predictionToolArgs(n)}});return await this.finalizeResult(b,T)}catch(T){return this.failureResult(b,T)}}async finalizeResult(n,a){let{options:s,requestedAction:c,signal:d,perf:p}=n;if(n.completedDisplayGesture=this.host.didCompleteDisplayGesture(a,s.display),s.display!==void 0&&a.staleDisplay)return this.host.unverifiableDisplayPostState(a,s);let h=!1;if(a.success&&a.observation&&a.element){h=!0;let m=await this.host.deriveTapEffectAfterPostTapObservation(n.previousObserveResult,a.observation,d,{settlePostTapEffect:n.settlePostTapEffect});a.effect=m.effect,a.observation=m.observation,await this.host.applyEnsureCheckedResult(a,s,d),await this.host.captureTerminalObservationScreenshot(a.observation,p,d),await this.host.recordDeferredPredictionOutcome(a,a.observation);let f=await this.host.selectionStateTracker().finalize({action:n.effectiveAction,selectionState:n.selectionCapture,currentObservation:a.observation,previousObservation:n.previousObserveResult,element:a.element,effect:m.effect,signal:d});if(f.length>0)a.observation.selectedElements=f;this.host.enforceFreshnessConsistencyWithEffect(n.previousObserveResult,a)}if(await this.host.confirmFocusAfterTap({result:a,options:s,requestedAction:c,focusTarget:n.focusTarget,focusLabelText:n.focusLabelText,preTapHierarchy:n.preTapHierarchy,signal:d}),h&&(c!=="focus"||a.focusVerified!==!0))et(a,n.screenReaderActivation);if(Gee(a,n.xrClick),n.effectiveAction==="longPress"){let m=this.host.detectLongPressMetadata(n.previousObserveResult,a.observation);return{...a,...m,...this.longClickAdvertisement(a.element)}}return a}async failureResult(n,a){let{options:s,requestedAction:c,recovery:d,perf:p}=n;p.end(),this.host.rethrowKeyboardOcclusion(a,c,d),e.warn(`Tap on element failed: ${r(a)}`,a);let h=this.host.completedDisplayFailure(a,n.completedDisplayGesture);if(h instanceof Ee||h instanceof hr)return Qt(this.host.createErrorResult(n.effectiveAction,h.message),h);let m=Tre(a)?await sL(this.host.device(),{text:s.text,resourceId:s.elementId,container:s.container}):void 0;return this.host.readScopeFailureResult(c,n.effectiveAction,a,{searchUntilStats:n.searchUntilStats,debugContext:m})}async executeObservedTap(n,a,s){let{options:c,signal:d,perf:p}=n;if(n.previousObserveResult=a,n.preTapHierarchy=a.viewHierarchy,o(d),!a.viewHierarchy)return p.end(),{success:!1,error:"Unable to get view hierarchy, cannot tap on element"};let h={observeResult:a,viewHierarchy:a.viewHierarchy,activationWarnings:[],isAccessibilityServiceEnabled:void 0};if(await this.prepareHierarchy(n,h),c.accessibilityLink)return this.host.activateAccessibilityLinkPhase(c,c.accessibilityLink,{observeResult:a,viewHierarchy:h.viewHierarchy,activationWarnings:h.activationWarnings,signal:d});let m=await this.searchCurrentTarget(n,h),f=await this.prepareSelection(n,h,m);if("result"in f)return f.result;let y=f.target,b=await this.stabilizeTarget(n,y);if(b)return b;return this.dispatchTarget(n,y,s)}async prepareHierarchy(n,a){let{signal:s}=n,{observeResult:c}=a;if(a.isAccessibilityServiceEnabled=this.host.detectsAccessibilityBeforeSearch()?await this.host.strategy().isAccessibilityServiceEnabled((d)=>a.activationWarnings.push(d)):void 0,this.host.refreshesAccessibilityHierarchyBeforeSearch()&&a.isAccessibilityServiceEnabled){let d=await Ev(this.host.tapVerificationRefresh({screenSize:c.screenSize,signal:s}),this.host.timer(),s);n.preTapHierarchy=d,this.host.replaceObservationHierarchy(c,d,!0),a.viewHierarchy=d}}async shouldRevalidateCachedTarget(n,a,s){let{options:c}=n;return Boolean(this.host.revalidatesCachedTargets()&&!a.isAccessibilityServiceEnabled&&s.selection.element&&!Gm(a.viewHierarchy)&&s.stats.requestCount===0&&c.ensureChecked===void 0&&!this.host.strategy().shouldRunPreTapStability(c)&&(this.host.canReuseAccessibilityState()||!(a.isAccessibilityServiceEnabled??=await this.host.strategy().isAccessibilityServiceEnabled())))}async searchCurrentTarget(n,a){let{options:s,signal:c,perf:d,request:p}=n,{observeResult:h}=a,m=await d.track("findElement",()=>this.host.searchForElement(s,h,c));if(await this.shouldRevalidateCachedTarget(n,a,m)){let f=await Ev(this.host.requiresFreshExtractionForCachedTarget()?(y)=>this.host.refreshViewHierarchy(y,h.screenSize,c,!0):this.host.tapVerificationRefresh({screenSize:h.screenSize,signal:c}),this.host.timer(),c,{timeoutMs:Math.min(ji,p?.requestDeadlineMs===void 0?ji:p.requestDeadlineMs-this.host.timer().now()),context:"while revalidating a cached observation",platform:this.platform()});this.host.replaceObservationHierarchy(h,f,!0),m=await this.host.searchForElement(s,h,c)}if(n.searchUntilStats=m.stats,this.host.replaceObservationHierarchy(h,m.viewHierarchy,m.refreshedFromDevice),a.viewHierarchy=m.viewHierarchy,!m.selection.element){if(m.visibilityError)throw m.visibilityError;await this.host.handleElementNotFound(s,{observeResult:h,containerFound:m.containerFound,signal:c,selection:m.selection})}return m}async prepareSelection(n,a,s){let{options:c,signal:d,perf:p}=n,{observeResult:h,activationWarnings:m}=a,f=await this.host.refreshEnsureCheckedSelection(c,h,s.selection,d);a.viewHierarchy=f.viewHierarchy,n.preTapHierarchy=a.viewHierarchy;let y=f.selection,b=y.element,T=this.host.buildSelectedElementMetadata(y),v=this.host.ensureCheckedBeforeTap(c,b,T,s.stats);if(v)return p.end(),{result:v};if(c.subtext)return{result:await this.host.activateSubtextPhase({options:c,subtext:c.subtext,element:b,viewHierarchy:a.viewHierarchy,selectedElement:T,searchUntil:s.stats,activationWarnings:m,signal:d})};let g=c.action,S=this.host.geometry().getElementCenter(b),O=this.host.getLongPressDuration(c),R={...a,searchOutcome:s,element:b,finalSelection:y,selectedElementMetadata:T,action:g,initialTapPoint:S,longPressDuration:O,tapOptions:{...c,action:g},tapElement:b,usedParent:!1},w=this.prepareFocusTarget(n,R);if(w)return{result:w};return R.tapOptions={...c,action:R.action},{target:R}}prepareFocusTarget(n,a){let{options:s,perf:c}=n,{searchOutcome:d}=a,{initialTapPoint:p}=a;if(a.action==="focus"){if(!Dn(a.element))return c.end(),{success:!1,action:a.action,element:a.element,selectedElement:a.selectedElementMetadata,searchUntil:d.stats,error:`Cannot focus ${C(a.element,s)} because it is not an editable input`};n.focusTarget=a.element;let h=d.selection.matchedElement;if(h&&h!==a.element)n.focusLabelText=h.text;if(Ha(a.element))return e.info("Element is already focused, no action needed"),c.end(),D({success:!0,action:a.action,element:a.element,selectedElement:a.selectedElementMetadata,searchUntil:d.stats,wasAlreadyFocused:!0,focusChanged:!1,focusVerified:!0,x:p.x,y:p.y},B(a.viewHierarchy,a.element,this.platform()));a.action="tap",n.effectiveAction="tap"}return}async stabilizeTarget(n,a){let{options:s,signal:c,perf:d,requestedAction:p}=n,{observeResult:h,activationWarnings:m,searchOutcome:f}=a;a.isAccessibilityServiceEnabled??=await this.host.strategy().isAccessibilityServiceEnabled((T)=>m.push(T));let y=a.isAccessibilityServiceEnabled,b=this.host.resolveTapTargetElement(a.element,a.viewHierarchy,a.action,{requireResourceId:y,scoped:s.container!==void 0});if(a.tapElement=b.element,a.usedParent=b.usedParent,this.host.strategy().shouldRunPreTapStability(s)){let T=await this.host.resolveAndroidStableTapTargetAfterRefreshes(s,h,a.action,{requireResourceId:y,signal:c});if(!T.ok)return d.end(),{success:!1,error:T.error};if(this.host.replaceObservationHierarchy(h,T.viewHierarchy,!0),T.selection.captureId)h.observationId=T.selection.captureId;a.viewHierarchy=T.viewHierarchy,n.preTapHierarchy=a.viewHierarchy,a.tapElement=T.tapElement,a.finalSelection=T.selection,a.usedParent=T.usedParent,a.selectedElementMetadata=this.host.rebuildSelectedElementMetadataAfterStability(a.selectedElementMetadata,T.selection);let v=T.selection.element;if(!v)return d.end(),{success:!1,error:"Android tap aborted: refreshed stable target selection was empty"};if(p==="focus")n.focusTarget=v,n.focusLabelText=T.selection.matchedElement!==v?T.selection.matchedElement?.text:void 0;let g=this.host.ensureCheckedBeforeTap(s,v,a.selectedElementMetadata,f.stats);if(g)return d.end(),g}return}async dispatchTarget(n,a,s){let{options:c,requestedAction:d,signal:p,perf:h}=n,{observeResult:m}=a;pr(this.host.strategy(),a.tapElement,a.activationWarnings),this.host.logClickableParentSelection(a.usedParent),a.activationWarnings.push(...Ze(d,a.finalSelection,a.tapElement));let f=await this.host.tapPoints().prototypeTapHierarchy(a.viewHierarchy,a.tapElement,d),{tapPoint:y,warning:b}=this.host.tapPoints().planVisibleTapPoint({options:a.tapOptions,requestedAction:d,observeResult:m,viewHierarchy:f,finalSelection:a.finalSelection,tapElement:a.tapElement});if(b)a.activationWarnings.push(b);let T=a.tapElement.bounds;e.info(`[TapOnElement] Tapping (${y.x}, ${y.y}) on element: text=${JSON.stringify(a.tapElement.text??c.text)}, bounds=${JSON.stringify(T)}, clickable=${a.tapElement.clickable}, usedParent=${a.usedParent}`),n.selectionCapture=await this.host.prepareSelectionCapture(a.action,m,a.tapElement,p);let v=c.retryIfNoChange?this.host.hashViewHierarchy(a.viewHierarchy):null;if(await h.track("executeTap",()=>this.dispatchPlatform(n,a,y,s)),c.ensureChecked!==void 0)n.ensureCheckedTapTimestamp=this.host.timer().now();if(v&&this.host.strategy().retryTapIfNoChange&&a.iosBackend?.backend!=="sdk")await this.host.retryTapIfNoChange(v,y,a.action,{longPressDuration:a.longPressDuration,tapElement:a.tapElement,options:{...this.host.withObservationScreenSize(a.tapOptions,m),displayFence:s},isTalkBackEnabled:a.isAccessibilityServiceEnabled,screenSize:m.screenSize,signal:p,selection:a.finalSelection});return h.end(),D({success:!0,action:a.action,element:a.tapElement,selectedElement:a.selectedElementMetadata,...fr(a.iosBackend),searchUntil:a.searchOutcome.stats,...a.screenReaderNavigation?{screenReaderNavigation:a.screenReaderNavigation}:{},...a.activationWarnings.length?{warnings:a.activationWarnings}:{}},B(a.viewHierarchy,n.focusTarget??a.tapElement,this.platform()))}async dispatchPlatform(n,a,s,c){let{signal:d}=n,{observeResult:p}=a;yC(),await this.host.runPlatformTap({android:async()=>{a.screenReaderNavigation=await this.host.executeAndroidTap(a.action,s,a.longPressDuration,{element:a.tapElement,signal:d,options:{...a.tapOptions,displayFence:c,resolvedHierarchy:a.viewHierarchy,onResolvedElement:(h,m,f)=>{if(a.tapElement=h,a.finalSelection=m??{...a.finalSelection,element:h,matchedElement:h},f)a.viewHierarchy=f,n.preTapHierarchy=f,this.host.replaceObservationHierarchy(p,f,!0);a.selectedElementMetadata=this.host.buildSelectedElementMetadata(a.finalSelection),Object.assign(s,this.host.geometry().getElementCenter(h))},onActivationWarning:(h)=>a.activationWarnings.push(h),onTalkBackActivation:()=>{n.screenReaderActivation={matched:a.finalSelection.matchedElement}},...Kee(n)},isTalkBackEnabled:a.isAccessibilityServiceEnabled})},ios:async()=>{let h=this.host.iosSdkBridgeTapper?.()??ite(this.host.device());if(a.iosBackend=await h.tap({action:n.requestedAction==="focus"?"focus":a.action,element:a.tapElement,longPressDurationMs:a.longPressDuration,signal:d})??void 0,a.iosBackend?.backend==="sdk")return;await this.host.executeiOSTap(a.action,s,a.longPressDuration,{element:a.tapElement,isVoiceOverEnabled:a.isAccessibilityServiceEnabled,displayFence:c,signal:d})}})}async confirmFocusAfterTap({result:n,options:a,requestedAction:s,focusTarget:c,focusLabelText:d,preTapHierarchy:p,signal:h}){if(s!=="focus"||!n.success||n.wasAlreadyFocused)return;let m=c??n.element;if(n.focusVerified=await this.host.verifyFocusAfterTap(n,(f)=>this.host.verifyFocusedInputTarget(a,m,f,{labelText:d,selectedIndex:n.selectedElement?.indexInMatches,preTapHierarchy:p}),h),!n.focusVerified)n.success=!1,n.error=`Failed to confirm focus on editable input ${C(m,a)}: the focused field could not be matched to the target`}assertLongPressWithinRequestBudget(n,a){if(n.action==="longPress")J$(this.host.getLongPressDuration(n),a?.requestDeadlineMs===void 0?void 0:a.requestDeadlineMs-this.host.timer().now())}predictionToolArgs(n){return{text:n.text,textAny:n.textAny,id:n.elementId,action:n.action,duration:n.duration,container:n.container,searchUntil:n.searchUntil,selectionStrategy:n.selectionStrategy,accessibilityLink:n.accessibilityLink,subtext:n.subtext,platform:this.host.device().platform}}readScopeFailureResult(n,a,s,{searchUntilStats:c,debugContext:d}){let p=r(s);return I(n,{success:!1,action:a,error:`Failed to perform tap on element: ${p}`,element:{bounds:{left:0,top:0,right:0,bottom:0}},...c?{searchUntil:c}:{},...s instanceof t&&s.containerFailure?{containerFailure:s.containerFailure}:{},...d?{debug:{elementSearch:d}}:{}},s)}longClickAdvertisement(n){if(this.host.device().platform!=="android"||!Array.isArray(n?.actions))return{};return{longClickAdvertised:Rr(n.actions,"long_click")}}detectLongPressMetadata(n,a){return this.host.longPressMetadataDetector().detect(n,a)}}function fr(n){if(!n)return{};return n.backend==="sdk"?{backend:"sdk"}:{backend:"xctest",fallbackReason:n.fallbackReason}}function _(n){return n["resource-id"]==="com.android.documentsui:id/item_root"||n["resource-id"]==="com.google.android.documentsui:id/item_root"}async function tt(n,a,{options:s,screenSize:c,signal:d}){if(await n.isAndroidXr(d))return e.info("[TapOnElement][retryIfNoChange] XR node click; skipping ghost-tap retry"),null;let p=await jF(n.timer(),n.tapVerificationRefresh({refresh:s.verification?.refresh,screenSize:c,signal:d}),(h)=>n.hashViewHierarchy(h),{preTapHash:a,signal:d});if(p.status==="unavailable")return e.warn(`[TapOnElement][retryIfNoChange] Tap hierarchy unreadable or could not be fingerprinted (post-tap refresh budget ${vC}ms) \u2014 skipping retry`),null;if(p.status==="changed")return e.info("[TapOnElement][retryIfNoChange] Hierarchy changed after tap \u2014 tap registered"),null;return p.hierarchy}function G(n,a,s){if(n.success&&s!=="longPress")a?.onTalkBackActivation?.()}class ue{host;constructor(n){this.host=n}async executeAndroidTap(n,a,s,{element:c,signal:d,options:p,isTalkBackEnabled:h}){if(await this.host.isAndroidXr(d)){await WF(()=>this.host.accessibilityService(),{action:n,element:c,signal:d,options:p,resolveContainer:(g,S)=>this.host.finder().resolveContainerElement(g,S)});return}let{x:m,y:f}=a,{displayFence:y,resolvedHierarchy:b,onActivationWarning:T}=p??{},v=typeof h==="boolean"?h:await this.host.strategy().isAccessibilityServiceEnabled(p?.onActivationWarning);if(c["hierarchy-source"]==="uiautomator"){await this.host.executeAndroidTapWithCoordinates(n,m,f,s,c,d,!0,{displayFence:y,onActivationWarning:T});return}if(ls(p)){await this.host.executeScopedAndroidTap({action:n,x:m,y:f,durationMs:s,element:c,signal:d,talkBackEnabled:v,fence:y,onActivationWarning:p?.onActivationWarning,onTalkBackActivation:p?.onTalkBackActivation});return}if(v)return this.host.executeAndroidTapWithAccessibility(n,m,f,c,s,p,d);await this.host.executeAndroidTapWithCoordinates(n,m,f,s,c,d,!1,{displayFence:y,resolvedHierarchy:b,onActivationWarning:T});return}async executeScopedAndroidTap(n){let{action:a,x:s,y:c,durationMs:d,element:p,signal:h,talkBackEnabled:m,fence:f}=n;if(m){let y=this.host.talkBackDriverFactory().createDriver(this.host.device()),b=a==="tap"?await this.host.talkBackStrategy().executePreciseTap(s,c,y,f):await this.host.talkBackStrategy().executeCoordinateFallback({x:s,y:c},a,d,{driver:y,fenceOptions:{displayFence:f}});if(b.success){G(b,n,a),this.host.reportTalkBackActivationWarning(b,n,a);return}await this.host.executeAndroidTapWithCoordinates(a,s,c,d,p,h,!0,{displayFence:f,onActivationWarning:n.onActivationWarning}),this.host.reportTalkBackActivationWarning(b,n,a);return}await this.host.executeAndroidTapWithCoordinates(a,s,c,d,p,h,!0,{displayFence:f,onActivationWarning:n.onActivationWarning})}async executeAndroidTapWithCoordinates(...[n,a,s,c,d,p,h=!1,m={}]){if(await this.host.isAndroidXr(p))throw Fm();let f=m.displayFence;if(n==="tap"){if(!h&&_(d)&&await this.host.tryDocumentsUiRowActivation(d,p))return;await this.host.dispatchCoordinateTapOrAdbFallback(a,s,d,{signal:p,fenceOptions:{displayFence:f}})}else if(n==="longPress")await this.host.executeAndroidLongPress(a,s,c,{element:d,signal:p,skipSemanticAction:h,...m});else if(n==="doubleTap")await yg({client:_(d)?void 0:this.host.accessibilityService(),point:{x:a,y:s},timer:this.host.timer(),signal:p,assertCurrent:()=>f?.assertCurrent(),onWarning:m.onActivationWarning,tap:()=>this.host.dispatchCoordinateTapOrAdbFallback(a,s,d,{signal:p,fenceOptions:{displayFence:f}})})}async tryDocumentsUiRowActivation(n,a){o(a);let s=Kn(n);if(!Rr(n.actions,"click")||!s||s.uniqueId===void 0&&(s.collectionRow===void 0||s.collectionColumn===void 0))return!1;try{if(!await this.host.accessibilityService().supportsNodeActionSelectors(void 0,a))return!1;o(a);let c=await this.host.accessibilityService().requestNodeAction("click",s,{signal:a});return o(a),c.success}catch(c){if(c instanceof Ee)throw c;return o(a),e.warn(`[TapOnElement] DocumentsUI row activation failed: ${c}`),!1}}async dispatchCoordinateTapOrAdbFallback(n,a,s,{signal:c,fenceOptions:d={}}={}){let p=d.displayFence;if(o(c),!_(s)){p?.assertCurrent(),await jw(this.host.accessibilityService(),this.host.adb(),{x:n,y:a},{durationMs:10,options:{signal:c}});return}e.info(`[TapOnElement] Using ADB input recovery for DocumentsUI row at (${n}, ${a})`),p?.assertCurrent(),await Ec(this.host.adb(),`tap ${n} ${a}`,void 0,{signal:c})}resolveEnsureCheckedRetryTarget(n,a,s,c){let d=this.host.findElementInHierarchy(n,a).selection.element;if(!d||!dt(d.checkable))return e.warn("[TapOnElement][retryIfNoChange] Toggle not found in fresh hierarchy; skipping retry"),null;if(dt(d.checked)===n.ensureChecked)return e.info("[TapOnElement][retryIfNoChange] Toggle reached requested checked state"),null;return this.host.resolveTapTargetElement(d,a,s,{requireResourceId:c,scoped:n.container!==void 0}).element}withRetryScreenSize(n,a){return{...n,screenSizeOptions:n.screenSizeOptions??{observationScreenSize:a}}}refreshedRetrySelection(n,a,s,c){if(n.text||n.textAny?.length||n.elementId||n.testTag)return this.host.findElementInHierarchy(n,a).selection;return c??{element:s,indexInMatches:-1,totalMatches:1,strategy:"first"}}resolveRefreshedRetryTarget(n,a,s,c){let{isTalkBackEnabled:d,selection:p,previousTarget:h}=c;if(n.ensureChecked!==void 0)return this.host.resolveEnsureCheckedRetryTarget(n,a,s,d);if(p.element)return this.host.resolveTapTargetElement(p.element,a,s,{requireResourceId:d,scoped:n.container!==void 0}).element;if(n.text||n.textAny?.length||n.elementId||n.testTag)return e.warn("[TapOnElement][retryIfNoChange] Target not found in refreshed hierarchy; skipping retry"),null;return h}async retryTapIfNoChange(n,a,s,{longPressDuration:c,tapElement:d,options:p,isTalkBackEnabled:h,screenSize:m,signal:f,selection:y}){let b=await tt(this.host,n,{options:p,screenSize:m,signal:f});if(!b)return;let T=this.host.withRetryScreenSize(p,m),v=this.host.refreshedRetrySelection(T,b,d,y),g=this.host.resolveRefreshedRetryTarget(T,b,s,{isTalkBackEnabled:h,selection:v,previousTarget:d});if(!g)return;let S=this.host.getScreenSizeFromHierarchy(b,T.screenSizeOptions),O=this.host.visibleTapBounds(v.element?v:y??{...v,element:g},b,{screenSize:S,options:T,tapTarget:g});if(!O){e.warn("[TapOnElement][retryIfNoChange] Refreshed target has no visible tap area; skipping retry");return}let R=hp(a,O)?a:this.host.resolveVisibleTapPoint(g,b,O,{options:p,screenSize:S});if(!R){e.warn("[TapOnElement][retryIfNoChange] Refreshed target has no unobstructed tap point; skipping retry");return}if(e.warn(`[TapOnElement][retryIfNoChange] Hierarchy unchanged after tap at (${R.x}, ${R.y}) \u2014 ghost tap detected, retrying`),await this.host.timer().sleep(zF),p.verification?.dispatch){await p.verification.dispatch(R);return}await this.host.executeAndroidTap(s,R,c,{element:g,signal:f,options:{...p,resolvedHierarchy:b},isTalkBackEnabled:h})}isScreenReaderNavigationEnabled(n){return Boolean(n?.screenReaderNavigation)||this.host.featureFlags().isEnabled("screen-reader-navigation")}reportTalkBackActivationWarning(n,a,s="tap"){if(s==="longPress"||n.method==="accessibility-action")return;let c=n.success?n.warnings??[az]:[n.unsupportedCapability==="tap_double_v1"?"TalkBack activation is unconfirmed: the connected device service does not support the single-gesture double tap (tap_double_v1). Update CtrlProxy. The plain coordinate tap path was used instead. Observe the result before retrying.":"TalkBack activation is unconfirmed: the TalkBack gesture failed, so the plain coordinate tap path was used instead. Observe the result before retrying."];for(let d of c)a?.onActivationWarning?.(d)}talkBackTargetContext(n,a,s){let c,d,p=n&&[n.text,n.textAny,n.elementId,n.testTag].some(Boolean);return{hierarchy:lt(n?.resolvedHierarchy),reResolve:p?(h)=>{let m=this.host.finder().selectElementInHierarchy(n,Ti(h,n.layer)).selection;return c=m,d=h,m.element?this.host.resolveTapTargetElement(m.element,h,a,{requireResourceId:!0,scoped:n.container!==void 0}).element:null}:void 0,onResolvedElement:(h)=>s(h,c,d)}}async executeAndroidTapWithAccessibility(...[n,a,s,c,d,p,h]){let m=this.host.readOptionalDisplayFence(p),f=this.host.talkBackDriverFactory().createDriver(this.host.device()),y,b=this.host.talkBackTargetContext(p,n,(g,S,O)=>{c=g;let R=this.host.geometry().getElementCenter(g);a=R.x,s=R.y,p?.onResolvedElement?.(g,S,O)});if(n==="longPress"){let g=await this.host.talkBackStrategy().executeLongPress({x:a,y:s},d,c,{driver:f,fenceOptions:{displayFence:m,...b}});if(!g.success){if(g.semanticActionFailure)throw new t(`Semantic long press failed for the selected element: ${g.error??"unknown error"}`);e.warn(`[TapOnElement] Long press accessibility methods failed (${g.error}), falling back to ADB tap at (${a}, ${s})`),await this.host.executeAndroidTapWithCoordinates(n,a,s,d,c,h,!0,{displayFence:m})}return}if(this.host.isScreenReaderNavigationEnabled(p)){let g=await this.host.talkBackStrategy().executeTap(this.host.device().deviceId,c,f,{fence:m,signal:h});if(g.success)return G(g,p,n),this.host.reportTalkBackActivationWarning(g,p,n),g.screenReaderNavigation;e.warn(`[TapOnElement] Focus navigation unavailable (${g.error}); nothing was dispatched, falling back to coordinate-based tap at (${a}, ${s})`),y=g.screenReaderNavigation}else if(n==="tap"){let g=await this.host.talkBackStrategy().executeDirectActivation(c,f,b);if(g.success){G(g,p,n);return}e.warn(`[TapOnElement] Direct accessibility activation failed (${g.error}), falling back to coordinate-based tap at (${a}, ${s})`)}if(_(c))return await this.host.executeAndroidTapWithCoordinates(n,a,s,d,c,h,!1,{displayFence:m}),y;let T=n,v=T==="tap"?await this.host.talkBackStrategy().executePreciseTap(a,s,f,m):await this.host.talkBackStrategy().executeCoordinateFallback({x:a,y:s},T,d,{driver:f,fenceOptions:{displayFence:m}});if(!v.success)e.warn(`[TapOnElement] Accessibility coordinate tap failed (${v.error}), falling back to ADB tap at (${a}, ${s})`),await this.host.executeAndroidTapWithCoordinates(n,a,s,d,c,h,!1,{displayFence:m});return G(v,p,n),this.host.reportTalkBackActivationWarning(v,p,n),y}async executeiOSTap(n,a,s,{element:c,isVoiceOverEnabled:d,...p}={}){let{x:h,y:m}=a;if(d&&c){await this.host.executeIOSTapWithVoiceOver(n,c,{x:h,y:m},{durationMs:s,fenceOptions:p});return}let f=()=>this.host.executeiOSTapWithCoordinates(n,h,m,{durationMs:s,fenceOptions:p});if(d)await CT(f);else await f()}async executeiOSTapWithCoordinates(n,a,s,{durationMs:c,fenceOptions:d={}}){let{displayFence:p,signal:h}=d,m=n==="longPress"?c:50,f=x.getInstance(this.host.device());if(n==="doubleTap")p?.assertCurrent(),await Gw(f,{x:a,y:s},{durationMs:m,options:{signal:h}}),x.getExistingInstance(this.host.device().deviceId)?.invalidateCache();else p?.assertCurrent(),await Kw(f,{x:a,y:s},{durationMs:m,options:{signal:h}}),x.getExistingInstance(this.host.device().deviceId)?.invalidateCache()}executeIOSTapWithVoiceOver(n,a,s,{durationMs:c,fenceOptions:d}){let{x:p,y:h}=s;return vte({device:this.host.device(),action:n,element:a,point:{x:p,y:h},durationMs:c,fenceOptions:d??{},coordinateTap:(m)=>this.host.executeiOSTapWithCoordinates(n,p,h,{durationMs:c,fenceOptions:m})})}readOptionalDisplayFence(n){return n?.displayFence}getLongPressDuration(n){if(RL(n.duration),typeof n.duration==="number"&&n.duration>0)return n.duration;return this.host.strategy().longPressDurationMs}async executeAndroidLongPress(n,a,s,{element:c,signal:d,skipSemanticAction:p=!1,...h}){let m=h.displayFence;if(o(d),!p){let f=Kn(c);if(f&&await this.host.trySemanticAndroidLongPress(c,f,d,h))return}await qF({adb:this.host.adb(),x:n,y:a,durationMs:s,signal:d,assertCurrent:m?()=>m.assertCurrent():void 0,logTag:"TapOnElement"})}throwIfLongPressInterrupted(n,a,s){FC(n,a,s)}semanticAndroidLongPressTargetError(n,a,s={}){let c=lt(s.resolvedHierarchy);return bg(n,{supportsNodeActionSelectors:()=>this.host.accessibilityService().supportsNodeActionSelectors(),getAccessibilityHierarchy:()=>c?Promise.resolve(c):this.host.accessibilityService().getAccessibilityHierarchy(void 0,{skipWaitForFresh:!0,disableAllFiltering:!0,signal:a})})}async trySemanticAndroidLongPress(n,a,s,c={}){let d=fa(a),p=await this.host.semanticAndroidLongPressTargetError(a,s,c);if(o(s),p)return e.info(`[TapOnElement] ${p}; using coordinate long press`),!1;try{let h=d?await this.host.accessibilityService().requestNodeAction("long_click",a):await this.host.accessibilityService().requestAction("long_click",a.resourceId);if(h.success)return!0;let m=await XT({advertised:Rr(n.actions,"long_click"),error:h.error,needsNodeSelector:d,selected:n,readHierarchy:()=>this.host.accessibilityService().getAccessibilityHierarchy(void 0,{skipWaitForFresh:!0,disableAllFiltering:!0,signal:s})});if(o(s),m)throw new t(`Semantic long press failed for the selected element: ${h.error??"unknown error"}`);e.warn(`[TapOnElement] Accessibility long click failed: ${h.error}`)}catch(h){if(h instanceof t)throw h;e.warn(`[TapOnElement] Accessibility long click error: ${h}`)}return!1}}var yr=3,Tr=new fe;function it(n){return typeof n==="string"&&n.trim()!==""?n.trim():void 0}function vr(n,a){let s=n.bounds;if(!s||s.right<=s.left||s.bottom<=s.top)return!1;if(!a||a.width<=0||a.height<=0)return!0;return s.right>0&&s.bottom>0&&s.left<a.width&&s.top<a.height}function Sr(n){let a=it(n.properties["hint-text"]),s=it(n.displayedLabel),c=s??a,d=s!==void 0&&a!==void 0&&a!==s?a:void 0;return{...n.elementId!==void 0?{elementId:n.elementId}:{},...c!==void 0?{label:c}:{},...d!==void 0?{sublabel:d}:{}}}function nt(n,a){if(!n)return[];let s=new Set;return Tr.project(n).filter((c)=>{if(s.has(c.source))return!1;return s.add(c.source),c.affordances.includes("input")&&!$u(c)&&vr(c,a)}).toSorted((c,d)=>c.windowRank-d.windowRank||(c.bounds?.top??0)-(d.bounds?.top??0)||(c.bounds?.left??0)-(d.bounds?.left??0)).slice(0,yr).map(Sr)}function he(n,a){return a===void 0?void 0:`${n} ${JSON.stringify(a)}`}function at(n){return`On-screen inputs: ${n.map((s)=>`{${[he("elementId",s.elementId),he("label",s.label),he("sublabel",s.sublabel)].filter((c)=>c!==void 0).join(", ")}}`).join("; ")}. Select one by its elementId or label.`}function st(n){return 2}var Er=/progress_bar|loading_indicator|progress_indicator|shimmer|content_loading/i,Or=/ProgressBar$|ProgressIndicator|ShimmerFrameLayout|ContentLoadingProgressBar/i;function ot(n,a){let s=[...a.extractRootNodes(n),...a.extractWindowRootNodes(n,"topmost-first")],c=!1;for(let d of s)if(a.traverseNode(d,(p)=>{if(c)return;let h=a.extractNodeProperties(p),m=String(h["resource-id"]??h.resourceId??""),f=String(h.class??h.className??"");if(m.length>0&&Er.test(m)){c=!0;return}if(f.length>0&&Or.test(f))c=!0}),c)break;return c}var pt=2500,ut=8,me=1e4,wr=32,Ar=1000,ct=12,kr=150;function xr(n,a,s){let c=s.viewHierarchy?n.findElementInHierarchy(a,s.viewHierarchy).selection:null;return c?.matchedElement??c?.element??null}function Cr(n,a,s){if(++n.iterations>Ar)return!1;let c=a.now()-n.startTime-n.noHierarchyTimeMs,d=n.refindAttempt>=n.minProductivePolls&&c>=n.budgetMs,p=n.best!==null&&n.consecutiveStable>0&&n.consecutiveStable<s;if(!n.firstIteration&&n.consecutiveNoHierarchy===0&&d)if(p&&n.deadlineGracePolls>0)n.deadlineGracePolls--;else return!1;return!0}function Fr(n,a,s){if(n.noHierarchyTimeMs+=a.now()-s,n.consecutiveNoHierarchy++,e.warn(`[TapOnElement] Android pre-tap refresh returned no hierarchy (consecutive: ${n.consecutiveNoHierarchy}/${ct}, refind attempt: ${n.refindAttempt})`),n.consecutiveNoHierarchy>=ct)return{ok:!1,error:`Android tap aborted: accessibility service was unreachable for ${n.consecutiveNoHierarchy} consecutive attempts (ctrl-proxy WebSocket unresponsive). The device may be under heavy load or the accessibility service may need reconnection.`};n.consecutiveStable=0,n.prevBounds=null;return}function Dr(n,a,s){if(ot(s,n.elementParser)&&a.budgetMs<me)a.budgetMs=me,a.minProductivePolls=wr,e.info(`[TapOnElement] Android pre-tap: loading/progress indicators present; extending refind budget to ${a.budgetMs}ms / ${a.minProductivePolls} polls`)}function Ir(n,a,s,{selection:c,element:d}){let{original:p,options:h,observeResult:m}=a;if(p?.["resource-id"]&&p["resource-id"]!==(c.matchedElement??d)["resource-id"])return"Stale tap target: the fresh capture matched a different native ID. Observe again before acting.";return h.elementId!==void 0&&h.elementId===p?.["view-id"]?n.staleSyntheticTarget(p,m.viewHierarchy,s):void 0}function Hr({state:n,freshHierarchy:a,selection:s,refreshed:c,stableMatchesRequired:d}){let p=c.element.bounds;if(p===void 0||p===null){n.consecutiveStable=0,n.prevBounds=null;return}if(n.prevBounds!==null&&mn(n.prevBounds,p,P))n.consecutiveStable++;else n.consecutiveStable=1;n.prevBounds=p;let h=zr(a)?.captureId;if(n.best={viewHierarchy:a,tapElement:c.element,usedParent:c.usedParent,selection:h?{...s,captureId:h}:s},n.consecutiveStable>=d)return e.info(`[TapOnElement] Android tap target stable after ${n.refindAttempt} refresh(es) (bounds matched on last ${d} consecutive re-find(s), \u03B5=${P}px)`),{ok:!0,...n.best};return}function Vr(n,a,s,c){s.consecutiveNoHierarchy=0,s.refindAttempt++,Dr(n,s,c);let d=n.findElementInHierarchy(a.options,c);if(!d.selection.element){e.warn(`[TapOnElement] Android pre-tap refresh attempt ${s.refindAttempt} did not re-find tap target`),s.consecutiveStable=0,s.prevBounds=null;return}let p=Ir(n,a,c,{selection:d.selection,element:d.selection.element});if(p)return{ok:!1,error:p};let h=n.resolveTapTargetElement(d.selection.element,c,a.action,{requireResourceId:a.requireResourceId,scoped:a.options.container!==void 0});return Hr({state:s,freshHierarchy:c,selection:d.selection,refreshed:h,stableMatchesRequired:a.stableMatchesRequired})}async function ht(n,a){let{observeResult:s,action:c,requireResourceId:d,signal:p}=a,h=n.withObservationScreenSize(a.options,s),m=st(h),f=xr(n,h,s),y={options:h,observeResult:s,action:c,requireResourceId:d,original:f,stableMatchesRequired:m},b={prevBounds:null,consecutiveStable:0,best:null,startTime:n.timer.now(),noHierarchyTimeMs:0,budgetMs:pt,minProductivePolls:ut,consecutiveNoHierarchy:0,refindAttempt:0,firstIteration:!0,iterations:0,deadlineGracePolls:m};while(!0){if(o(p),!Cr(b,n.timer,m))break;if(!b.firstIteration){let S=b.consecutiveNoHierarchy>0,O=S?N5:kr;if(await n.timer.sleep(O),S)b.noHierarchyTimeMs+=O}b.firstIteration=!1;let T=n.timer.now(),v=await n.tapVerificationRefresh({refresh:h.verification?.refresh,screenSize:s.screenSize,signal:p})(HF);if(!v){let S=Fr(b,n.timer,T);if(S)return S;continue}let g=Vr(n,y,b,v);if(g)return g}return{ok:!1,error:"Android tap aborted: could not re-find the target in the accessibility hierarchy with stable bounds after repeated refreshes (refusing tap using pre-observe coordinates). The UI may still be updating (list, keyboard, loading overlay, or animation)."}}var q=2500,j=150,mt=1000;class ye{deps;constructor(n){this.deps=n}async waitForPostTapChange(n,a,s){let c=this.deps.timer.now(),d=null,p=0,h={},m=(g)=>{let S=this.deps.deriveTapEffect(n,g);if(S?.screenChanged===!0&&S.basis!=="viewHierarchy changed")return{matched:!0};let O=this.deps.timer.now();if(S?.screenChanged===!0&&h.seenAt===void 0)h.observation=g,h.seenAt=O;if(h.seenAt===void 0)return{matched:!1};let R=this.deps.hashViewHierarchy(g.viewHierarchy??null);if(R===null||R!==d)return d=R,p=O,{matched:!1};return{matched:O-p>=mt}},f={readBackStackEachPoll:!0,timeoutMs:q,pollMs:j,signal:s,initialMinTimestampMs:hn(a.viewHierarchy),skipWaitForFresh:!0,requireFreshExtraction:!0},y=await this.deps.waitForCondition().execute(m,f),b=h.observation??a;if(y.timedOut&&!y.screenOff&&h.seenAt!==void 0){let S=Math.min(c+2*q,h.seenAt+q)-this.deps.timer.now();if(S>0)o(s),y=await this.deps.waitForCondition().execute(m,{...f,timeoutMs:S,initialMinTimestampMs:hn(this.resolveSettleTimeoutObservation(n,b,y).viewHierarchy)})}let T=this.resolveSettleTimeoutObservation(n,b,y),v=this.deps.deriveTapEffect(n,y.screenOff?b:T);if(!y.matched&&v?.screenChanged!==!0)return{effect:v,observation:a};return{effect:v,observation:{...T,gfxMetrics:T.gfxMetrics??a.gfxMetrics,perfTiming:T.perfTiming??a.perfTiming}}}async settleHierarchyOnlyChange(n,a,s){let c=null,d=0,p=await this.deps.waitForCondition().execute((y)=>{let b=this.deps.deriveTapEffect(n,y);if(this.deps.compareActiveWindow(n,y)?.screenChanged===!0||b?.basis==="screenIdentity changed")return{matched:!0};let T=this.deps.hashViewHierarchy(y.viewHierarchy??null),v=this.deps.timer.now();if(T===null)return c=null,{matched:!1};if(T!==c)return c=T,d=v,{matched:!1};return{matched:v-d>=mt}},{readBackStackEachPoll:!0,timeoutMs:q,pollMs:j,signal:s,initialMinTimestampMs:hn(a.viewHierarchy),skipWaitForFresh:!0,requireFreshExtraction:!0}),h=this.resolveSettleTimeoutObservation(n,a,p);return{effect:p.screenOff===!0?{screenChanged:!0,basis:"viewHierarchy changed"}:this.deps.deriveTapEffect(n,h),observation:{...h,gfxMetrics:h.gfxMetrics??a.gfxMetrics,perfTiming:h.perfTiming??a.perfTiming}}}resolveSettleTimeoutObservation(n,a,s){let c=s.observation,d=s.screenOff===!0;if(!s.timedOut||d)return c;let p=a.freshness?.isFresh!==!1&&this.deps.deriveTapEffect(n,a)?.screenChanged===!0,h=c.freshness?.isFresh===!1||this.deps.hashViewHierarchy(c.viewHierarchy??null)===null;return p&&h?a:c}}var Br=1500,yt=50,Nr=1500,Lr=100,Mr=12000;function _r(n,a,s){let c=n.action==="focus"&&a?nt(a.viewHierarchy,a.screenSize):[];return c.length>0?{baseError:`${s}. ${at(c)}`,reason:"not-found-inputs-listed"}:{baseError:s,reason:"not-found"}}class Te{host;constructor(n){this.host=n}getSearchUntilDuration(n){return bL(n.searchUntil?.duration,{defaultMs:Nr,minMs:Lr,maxMs:Mr})}hashViewHierarchy(n){return An(n)}deriveTapEffect(n,a){return this.host.deriveInteractionEffect(n,a)}async deriveTapEffectAfterPostTapObservation(n,a,s,c){return this.host.postTapEffect().deriveEffectAfterPostTapObservation(n,a,s,c)}enforceFreshnessConsistencyWithEffect(n,a){this.host.postTapEffect().enforceFreshnessConsistency(n,a)}replaceObservationHierarchy(n,a,s){this.host.postTapEffect().replaceObservationHierarchy(n,a,s)}logClickableParentSelection(n){if(n)e.info("[TapOnElement] Using clickable parent for non-clickable element")}async prepareSelectionCapture(n,a,s,c){return this.host.selectionStateTracker().prepare({action:n,observation:a,element:s,signal:c})}withObservationScreenSize(n,a){return{...n,screenSizeOptions:{observationScreenSize:a.screenSize,display:a.viewHierarchy}}}findElementInHierarchy(n,a){a=Ti(a,n.layer);try{return this.host.finder().selectElementInHierarchy(n,a)}catch(s){if(n.action!=="focus"||!(s instanceof t)||s instanceof wo||!ls(n)&&n.index===void 0||!this.host.finder().isContainerAvailable(a,n.container))throw s;return this.host.finder().classifyFocusSelectionFailure(n,a,s)}}verifyFocusedInputTarget(n,a,s,c={}){return this.host.focusVerifier().verify(n,a,s,c)}invisibleMatchFailure(...n){return this.host.tapPoints().invisibleMatchFailure(...n)}resolveTapPoint(...n){return this.host.tapPoints().resolveTapPoint(...n)}resolveContainerElement(...n){return this.host.finder().resolveContainerElement(...n)}visibleTapBounds(...n){return this.host.tapPoints().visibleTapBounds(...n)}resolveVisibleTapPoint(...n){return this.host.tapPoints().resolveVisibleTapPoint(...n)}async verifyFocusAfterTap(n,a,s){if(a(n.observation))return!0;let c=n.observation;if(!this.host.strategy().settlesFocusChangeAfterTap||!c)return!1;let d=this.host.timer().now()+Br;while(this.host.timer().now()<d){await this.host.timer().sleep(j),o(s);let p=await this.host.refreshViewHierarchy(d-this.host.timer().now(),c.screenSize,s,!0);if(!p)continue;let h={...c};if(this.host.replaceObservationHierarchy(h,p,!0),a(h))return n.observation=h,!0}return!1}prepareViewHierarchyForResponse(n,a){if(KF(N.isRawElementSearchEnabled(),n))return n;return this.host.strategy().prepareViewHierarchyForResponse(n,this.host.viewHierarchy(),a)??n}async refreshViewHierarchy(n,a,s,c=!1){if(o(s),n<=0)return null;let d=this.host.renderedDisplayGeneration()(this.host.device().deviceId)??this.host.displayTransitionReader().identityRevision(this.host.device().deviceId),p;try{p=(await this.host.hierarchyCapture().capture({freshness:"fresh",...c?{requireFreshExtraction:!0}:{},searchRaw:N.isRawElementSearchEnabled(),timeoutMs:n,signal:s})).hierarchy}catch(h){if(h instanceof Ee)throw h;return o(s),e.warn(`[TapOnElement] Fresh capture failed: ${r(h)}`),null}if(await this.correctXrHierarchySize(p,s),Ts(a)&&this.host.strategy().verifiesRefreshedDisplay)await this.checkRefreshedDisplay(p,a,d,s);return p}tapVerificationRefresh(n){return n.refresh??((a)=>this.host.refreshViewHierarchy(a,n.screenSize,n.signal))}async correctXrHierarchySize(n,a,s){let c=this.host.xrDisplaySize?.();if(!c||this.host.device().platform!=="android")return;await c.prime(s??{},n,a);let d=s??{screenSize:{width:0,height:0}};c.applyCached(d,n)}async checkRefreshedDisplay(n,a,s,c){let d=this.host.getScreenSizeFromHierarchy(n);if(!d||d.width===a.width&&d.height===a.height&&(this.host.device().displays?.panels.length??0)<2)return;let p=await this.refreshedDisplay(n,c),h=this.host.refreshedDisplayTransitions().checkIdentity(this.host.device().deviceId,p),m=this.host.refreshedDisplayTransitions().record(this.host.device().deviceId,{display:p,screenSize:d});if(h||m)throw this.host.staleDisplay(s)}async refreshedDisplay(n,a){let s=new gr(this.host.timer()),c=await s.panelForLogicalId(this.host.device(),this.host.adb(),n.displayId,{signal:a,identity:{panelUniqueId:n.panelUniqueId,panelFingerprint:n.panelFingerprint},allowProbe:!1}),d=await s.resolve(this.host.device(),this.host.adb(),a),p=c??this.host.device().displays?.panels.find((h)=>h.key===d.display.key);return{...d.display,key:p?.key??d.display.key,role:p?.role??d.display.role,posture:await s.posture(this.host.device(),this.host.adb(),a)}}async readFreshHierarchy(n,a,s,c=!1){o(s);let d=Math.max(0,n);if(d===0)return null;return GF({device:this.host.device(),adb:this.host.adb(),timer:this.host.timer(),androidService:this.host.accessibilityService(),viewHierarchy:this.host.viewHierarchy(),prepareForResponse:(p,h)=>this.prepareViewHierarchyForResponse(p,h),actionLabel:"tap on elements"},{timeoutMs:d,screenSize:a,signal:s,forceCapture:c})}resolveAndroidStableTapTargetAfterRefreshes(n,a,s,{requireResourceId:c,signal:d}){return ht({timer:this.host.timer(),elementParser:this.host.elementParser(),findElementInHierarchy:(p,h)=>this.host.findElementInHierarchy(p,h),resolveTapTargetElement:(p,h,m,f)=>this.host.resolveTapTargetElement(p,h,m,f),staleSyntheticTarget:(p,h,m)=>this.host.staleSyntheticTarget(p,h,m),tapVerificationRefresh:(p)=>this.host.tapVerificationRefresh(p),withObservationScreenSize:(p,h)=>this.host.withObservationScreenSize(p,h)},{options:n,observeResult:a,action:s,requireResourceId:c,signal:d})}staleSyntheticTarget(n,a,s){if(!n||n["resource-id"]||!n["view-id"]||!a)return;let c=new fe,d=n["view-id"],p=c.project(a).find((y)=>y.nodeKey===d);if(!p)return"Stale tap target: the observed reference is no longer identifiable.";let h=zr(a)?.captureId??"before-refresh",m=zr(s)?.captureId??(a===s?h:"after-refresh");return new ur().resolve({id:m,nodes:c.project(s)},{elementId:d},{action:"inspect",ref:{snapshotId:h,nodeKey:d,bounds:p.bounds,label:p.label,nativeId:p.nativeId}}).error}isPrototypeWindowPending(n,a){return n.layer==="prototype"&&a.prototypeSuspended!==!0&&!ba(a)}xrChromeSearch(n){let a=this.host.device().platform==="android"?void 0:!1;return{get enabled(){return a??!1},detect:async(s)=>{if(a===void 0&&VF(s).hiddenNodes.size>0)a=await this.host.isAndroidXr(n)}}}async refreshForChromeSearch(n,a,s){let c=await this.host.tapVerificationRefresh(n)(a);if(c)await s(c);return c}findElementForSearch(n,a,s=!1){if(this.isPrototypeWindowPending(n,a))return{selection:{element:null,indexInMatches:-1,totalMatches:0,strategy:"first"},containerFound:!1};if(!s)return this.host.findElementInHierarchy(n,a);return jee(n,a,(c,d)=>this.host.findElementInHierarchy(c,d))}async searchForElement(n,a,s){let c=a.viewHierarchy;if(!c)throw new t("Unable to get view hierarchy, cannot tap on element");await this.correctXrHierarchySize(c,s,a);let d=this.xrChromeSearch(s);await d.detect(c);let p=this.host.getSearchUntilDuration(n),h=this.host.timer().now(),m=0,f=0,y=0,b,T=this.host.hashViewHierarchy(c),v=c,g=this.host.getScreenSizeFromHierarchy(v,{observationScreenSize:a.screenSize,display:a.viewHierarchy}),S=this.findElementForSearch(this.host.withObservationScreenSize(n,a),v,d.enabled);b=S.visibilityError;let O=S.selection,R=()=>this.host.invisibleMatchFailure(O,n,v,{screenSize:g}),w=O.element,A=S.containerFound;if(!w&&O.matchedElement)b=R();if(!w||this.host.isElementTapTargetOffScreen(O,v,g,n)){if(w)b=R(),e.warn(`[TapOnElement] Element found but tap target is off-screen, will retry. bounds=${JSON.stringify(w.bounds)}, screen=${g?.width}x${g?.height}`),O={...O,element:null},w=null,y+=1;m=(await YF({timer:this.host.timer(),startTime:h,durationMs:p,intervalMs:yt,pacing:"cadence",maxRequests:Math.ceil(p/yt),discardLateResult:!1,signal:s,fetch:(F)=>this.refreshForChromeSearch({refresh:n.verification?.refresh,screenSize:g,signal:s},F,d.detect),accept:(F)=>{g=this.host.getScreenSizeFromHierarchy(F,{observationScreenSize:g,display:v}),v=F;let Z=this.host.hashViewHierarchy(F);if(Z&&Z!==T)f+=1,T=Z;let ee=this.findElementForSearch({...n,screenSizeOptions:{observationScreenSize:g,display:v}},F,d.enabled);if(b=ee.visibilityError??b,O=ee.selection,w=O.element,A=A||ee.containerFound,!w&&O.matchedElement)b=R();if(w&&this.host.isElementTapTargetOffScreen(O,F,g,n))return b=R(),e.warn(`[TapOnElement] Element found but tap target is off-screen, retrying. bounds=${JSON.stringify(w.bounds)}`),O={...O,element:null},w=null,y+=1,!1;return w!==null}})).requestCount}if(this.isPrototypeWindowPending(n,v))Ti(v,n.layer);this.reportOffScreenRejections(y,w);let Q={durationMs:Math.max(0,Math.round(this.host.timer().now()-h)),requestCount:m,changeCount:f};return{selection:O,viewHierarchy:v,containerFound:A,stats:Q,refreshedFromDevice:v!==c,...b&&!w?{visibilityError:b}:{}}}reportOffScreenRejections(n,a){if(n>0&&!a)e.warn(`[TapOnElement] Element was found ${n} time(s) but had no visible tap area. Scroll it into view before retrying.`)}buildSelectedElementMetadata(n){if(!n.element)return;let a=n.element.bounds,s=this.host.geometry().getElementCenter(n.element),c=MR(n.element)??(typeof n.element.text==="string"&&n.element.text.length>0?n.element.text:typeof n.element["content-desc"]==="string"?n.element["content-desc"]:typeof n.element["ios-accessibility-label"]==="string"?n.element["ios-accessibility-label"]:""),d=typeof n.element["resource-id"]==="string"?n.element["resource-id"]:"",p=typeof n.element["test-tag"]==="string"?n.element["test-tag"]:void 0;return{...n.matchedElement?{matchedElement:n.matchedElement}:{},...n.captureId?{captureId:n.captureId}:{},text:c,resourceId:d,...p?{testTag:p}:{},bounds:{left:a.left,top:a.top,right:a.right,bottom:a.bottom,centerX:s.x,centerY:s.y},indexInMatches:n.indexInMatches,totalMatches:n.totalMatches,selectionStrategy:n.strategy}}rebuildSelectedElementMetadataAfterStability(n,a){return this.host.buildSelectedElementMetadata(a)??n}async handleElementNotFound(n,{observeResult:a,containerFound:s=!0,signal:c,selection:d}={}){this.assertContainerFound(n,s);let p=this.containerHint(n),h=this.elementNotFoundMessage(n,p),{baseError:m,reason:f}=_r(n,a,h);if(d?.onlyKeyboardKeyMatch)throw new wo(`${h}. The only match is a soft-keyboard key, which observe does not list; use sendKeys or pressButton to drive the keyboard, or dismiss the keyboard first.`,"not-found");if(this.host.visionConfig().enabled&&a){e.info("\uD83D\uDD0D Element not found after polling, trying vision fallback...");let y=await Bm(this.host.screenshotCapturer(),a.viewHierarchy,{text:n.text??n.textAny?.join(" | "),resourceId:n.elementId,description:`Interactive element for tapping (action: ${n.action})`},{visionConfig:this.host.visionConfig(),baseError:m,signal:c,visionAnalyzer:this.host.visionAnalyzer()});throw new wo(y,f)}throw new wo(m,f)}assertContainerFound(n,a){if(n.container&&!a){let s=n.container.elementId?`elementId '${n.container.elementId}'`:`text '${n.container.text}'`;throw new t(n.container.elementId?.startsWith("s2-")?`Container element id '${n.container.elementId}' is stale; re-observe and use the id from the new observation.`:`Container element not found with provided ${s}`)}}containerHint(n){return n.container?` within container ${n.container.elementId?`elementId '${n.container.elementId}'`:`text '${n.container.text}'`}`:""}siblingNotFoundMessage(n,a){if(n.sibling&&n.text)return`No clickable sibling found next to element with text '${n.text}'${a}`;else if(n.sibling&&n.elementId)return`No clickable sibling found next to element with elementId '${n.elementId}'${a}`;return}elementNotFoundMessage(n,a){let s=this.siblingNotFoundMessage(n,a);if(s!==void 0)return s;if(n.text&&n.exactText===!0)return CV(n.text,a);else if(n.text)return`Element not found with provided text '${n.text}'${a}`;else if(n.textAny)return`Element not found with any provided text '${n.textAny.join("', '")}'${a}`;else if(n.testTag)return`Element not found with provided testTag '${n.testTag}'${a}`;else if(n.accessibilityLink)return`Element not found with provided accessibilityLink '${n.accessibilityLink}'${a}`;else return n.elementId?.startsWith("s2-")?`Element id '${n.elementId}' is stale; re-observe and use the id from the new observation.${a}`:`Element not found with provided elementId '${n.elementId}'${a}`}isClickableElement(n){return dt(n.clickable)||Rr(n.actions,"click")}isLongClickableElement(n){return dt(n["long-clickable"])||dt(n.longClickable)||Rr(n.actions,"long_click")}elementAffordances(n){let a=[];if(this.host.isClickableElement(n))a.push("tap");if(this.host.isLongClickableElement(n))a.push("long-press");let s=typeof n.class==="string"?n.class:"";if(dt(n.focusable)&&(s.includes("EditText")||typeof n["input-type"]==="string"&&n["input-type"].trim()!==""))a.push("input");if(dt(n.scrollable))a.push("scroll");if(dt(n.checkable))a.push("toggle");return a}elementIdentity(n){return n.text??n["resource-id"]??n.testTag??n["test-tag"]??n["content-desc"]??"unidentified element"}ensureCheckedBeforeTap(n,a,s,c){return this.host.ensureChecked().beforeTap(n,a,s,c)}refreshEnsureCheckedSelection(n,a,s,c){return this.host.ensureChecked().refreshSelection(n,a,s,c)}applyEnsureCheckedResult(n,a,s){return this.host.ensureChecked().applyResult(n,a,s)}resolveTapTargetElement(n,a,s,c){if(typeof c!=="boolean"&&c.scoped)return{element:n,usedParent:!1};if(!a||!this.host.strategy().promotesClickableAncestor)return{element:n,usedParent:!1};let d=new fe().project(a),p=ed(d,n),h=p?qb(p,d,{action:s==="longPress"?"long-press":"tap"}):null;if(h?.element)return{element:h.element,usedParent:!Nt(h.element.bounds,n.bounds)};return{element:n,usedParent:!1}}}var Wr={tap:"tap",doubleTap:"tap",longPress:"tap",focus:"focus-input"};class be{deps;constructor(n){this.deps=n}selectVariantOrSiblingOrMiss(n,a){try{return a()}catch(s){if(!(s instanceof t))throw s;if(!(n.verification!==void 0&&s.message==="Sibling row not found"||n.textAny!==void 0&&n.selectionStrategy==="unique"&&s.message.startsWith("Target not found")))throw s;return e.debug("[TapOnElement] Text variant or display sibling not found yet",s),{element:null,totalMatches:0,indexInMatches:-1,strategy:n.selectionStrategy??"first"}}}classifyFocusSelectionFailure(n,a,s){let c=this.selectElementInHierarchy({...n,selectionStrategy:"first",index:void 0},a).selection;if(c.totalMatches===0&&!c.matchedElement)throw new wo(s.message,"not-found");let d=c.element??c.matchedElement;if(c.totalMatches===1&&d&&Dn(d)&&this.deps.tapPoints.isElementTapTargetOffScreen(c,a,this.deps.tapPoints.getScreenSizeFromHierarchy(a,n.screenSizeOptions),n))throw new wo(s.message,this.deps.tapPoints.isCoveredByNavigationBar(c,a,this.deps.tapPoints.getScreenSizeFromHierarchy(a,n.screenSizeOptions))?"navigation-bar":"no-visible-tap-area");throw s}selectElementInHierarchy(n,a){let s=this.isContainerAvailable(a,n.container),c=this.selectionContext(n),{text:d,elementId:p}=n,h=(m)=>({selection:m,containerFound:s});if(d)return h(n.sibling?this.selectVariantOrSiblingOrMiss(n,()=>this.selectSiblingText(n,a,d,c)):this.selectPartialText(n,a,d,c));if(n.textAny){let m=this.selectTextAny(n,a,c);if(m)return h(m)}if(p)return h(n.sibling?this.selectVariantOrSiblingOrMiss(n,()=>this.selectSiblingElementId(n,a,p,c)):this.selectElementId(n,a,p,c));return h(this.deps.elementSelector().select(a,{testTag:Ye(n)},{container:n.container,screenSizeOptions:n.screenSizeOptions,strategy:n.selectionStrategy,intentAction:c.lookupAction,selectionIntent:c.selectionIntent,index:n.index}))}selectionContext(n){let a=n.action==="longPress"?"long-press":n.action==="focus"?"focus-input":"tap",s=n.subtext?"inspect":ls(n)?a:n.action==="focus"?"focus-input":"inspect";return{intentAction:a,lookupAction:s,selectionIntent:this.selectionIntentFor(n)}}selectSiblingText(n,a,s,c){return this.deps.elementSelector().select(a,{sibling:{text:s}},{container:n.container,screenSizeOptions:n.screenSizeOptions,fuzzyMatch:!0,caseSensitive:!1,strategy:n.selectionStrategy,intentAction:c.intentAction,selectionIntent:c.selectionIntent,index:n.index})}selectPartialText(n,a,s,c){if(!(n.exactText===!0&&n.text===s))return this.selectText(n,a,{text:s,partialMatch:!0},c);try{return this.selectText(n,a,{text:s,partialMatch:!1},c)}catch(p){if(p instanceof t&&p.message.startsWith("Target not found"))throw new wo(CV(s,n.container?" within container":""),"not-found");throw p}}selectText(n,a,{text:s,partialMatch:c},d){return this.deps.elementSelector().select(a,{text:s},{container:n.container,screenSizeOptions:n.screenSizeOptions,partialMatch:c,caseSensitive:!1,strategy:n.selectionStrategy,intentAction:d.lookupAction,allowHintFallback:n.action==="tap"||n.action==="focus",index:n.index,selectionIntent:d.selectionIntent})}selectSiblingElementId(n,a,s,c){return this.deps.elementSelector().select(a,{sibling:{elementId:s}},{container:n.container,screenSizeOptions:n.screenSizeOptions,partialMatch:!1,strategy:n.selectionStrategy,intentAction:c.intentAction,index:n.index})}selectElementId(n,a,s,c){return this.deps.elementSelector().select(a,{elementId:s},{container:n.container,screenSizeOptions:n.screenSizeOptions,partialMatch:!1,strategy:n.selectionStrategy,intentAction:c.lookupAction,index:n.index})}selectTextAny(n,a,s){let c=null,d=null,p=this.deps.tapPoints.getScreenSizeFromHierarchy(a,n.screenSizeOptions);for(let h of n.textAny??[]){let m=this.selectVariantOrSiblingOrMiss(n,()=>n.sibling?this.selectSiblingText(n,a,h,s):this.selectPartialText(n,a,h,s));if(c=m,!m.element)continue;if(this.deps.tapPoints.isElementTapTargetOffScreen(m,a,p,n)){d=m;continue}return m}if(d)return{...d,element:null};if(c&&n.selectionStrategy==="unique")throw new wo(`Target not found${n.container?" within container":""}: no textAny variant matched`,"not-found");return c}selectionIntentFor(n){return n.ensureChecked!==void 0&&n.index===void 0&&!n.elementId?"toggle":Wr[n.action]}isContainerAvailable(n,a){return SL(this.deps.elementSelector(),n,a)}resolveContainerElement(n,a){let s=a.container;if(!s)return;let c=this.deps.elementSelector();if(c.resolveContainer)return c.resolveContainer(n,s,a.selectionStrategy);let d={container:s.container,index:s.index,strategy:pW(s,a.selectionStrategy).selectionStrategy};if(s.elementId)return this.deps.elementSelector().select(n,{elementId:s.elementId},{...d,intentAction:"inspect",screenSizeOptions:a.screenSizeOptions}).element;if(s.text)return this.deps.elementSelector().select(n,{text:s.text},{...d,intentAction:"inspect",screenSizeOptions:a.screenSizeOptions,caseSensitive:!1}).element;return}}function X(n,a,s){return s?.sibling||s?.action==="focus"?a:n.matchedElement??a}var Ur=25;function Gr(n){return{elementId:n.elementId??null,label:n.displayedLabel??n.label??null,className:n.className??null,bounds:n.bounds,clickable:n.categories.clickable,actionable:n.actionable,depth:n.depth,windowRank:n.windowRank}}function qee(n,a,s){let c=od(n,a,s,"hitTest");if("error"in c)throw new t(c.error);let d=a.viewHierarchy?Td(new fe().project(a.viewHierarchy)):[],p=EO(d,c).slice(0,Ur).map(Gr),h=a.screenSize,m=s==="ios"?"points":"pixels";return{method:"hierarchy-bounds",dispatchGuaranteed:!1,point:c,screenSize:{width:h.width,height:h.height,unit:m},reference:{kind:"screen",bounds:{left:0,top:0,right:h.width,bottom:h.height},unit:m,display:a.display},firstCandidate:p[0]??null,candidates:p}}function H(n,a){if(!n||!a)return!1;let s=new js,c=Ol(n).filter((h)=>h.hierarchy).flatMap((h)=>s.extractWindowRootGroups({hierarchy:{},windows:[h]})[0]),d=n.hierarchy.node&&Ij(Ib,n.hierarchy.node);for(let[h,m]of d??[])if(m)c.push(h);let p=!1;for(let h of c)s.traverseNode(h,(m)=>{p||=m===a});return p}function qr(n){if(n?.source==="ios-sdk-safe-area"&&n.safeArea){let a=n.systemChrome?.statusBar;return{top:a==="hidden"?0:n.safeArea.top,bottom:0,visibilityKnown:a==="visible"||a==="hidden"}}return}function bt(n,a=!1){let s=n.insets?.available===!1?void 0:n.insets;if(s?.systemBars){let{systemBars:p,tappableElement:h}=s;return{top:p.visible.top,bottom:p.visible.bottom,visibilityKnown:!0,...h?{bottomConsumesTouches:h.bottom>0}:{}}}let c=qr(s);if(c)return c;let d=n.systemInsets;if(a&&d?.top===0)return;return d?{top:d.top,bottom:d.bottom,visibilityKnown:!1}:void 0}function ve(n,a,s){let c=bt(n,!0);if(!a||!c?.visibilityKnown||!n.screenHeight||n.screenHeight<=0||c.top<=s.top)return s;return Ut(s,{...s,top:Math.max(0,c.top)})}var $r="The tap point is inside the gesture navigation bar area. The thin gesture bar does not consume touches, so the tap is sent, but the system's own swipe gestures can claim it: confirm the prototype control reacted (awaitEvent for its page_changed / selected event) before relying on it.",vt="The tap point is inside the system bar area and the capture does not say whether the bars are showing, so the AutoMobile prototype control there may not receive the touch.";function Kr(n,a){if(a.y<n.top)return{kind:"refuse",bar:"status bar"};if(n.bottomConsumesTouches===void 0)return{kind:"proceed",point:a,warning:vt};return n.bottomConsumesTouches?{kind:"refuse",bar:"navigation bar"}:{kind:"proceed",point:a,warning:$r}}function gt(n){let{hierarchy:a,ownedByPrototype:s,bounds:c,point:d}=n,p=a?.screenHeight,h=a&&bt(a,n.warnIfUnknown);if(!s)return{kind:"proceed",point:d};if(!h||!p||p<=0)return{kind:"proceed",point:d,...n.warnIfUnknown?{warning:"The capture does not say whether the bars are showing or where the status bar ends, so the AutoMobile prototype control may not receive the touch."}:{}};let m=p-Math.max(0,h.bottom);if(d.y>=Math.max(0,h.top)&&d.y<m)return{kind:"proceed",point:d};if(!h.visibilityKnown)return{kind:"proceed",point:d,warning:vt};let f=Math.max(c.top,h.top),y=Math.min(c.bottom,m);if(y<=f)return Kr(h,d);return{kind:"proceed",point:{x:d.x,y:Math.floor((f+y)/2)}}}function jr({coveredBy:n,coveredByKind:a}){return a==="view"?`Target is covered by ${JSON.stringify(n)} drawn over it at its only visible tap area; scroll the target clear of it with swipeOn, then retry tapOn.`:`Target is covered by ${n}; dismiss the covering window, then retry tapOn.`}class ge{deps;prototypeAgents;constructor(n){this.deps=n;this.prototypeAgents=n.prototypeAgents??{get:()=>{return}}}async prototypeTapHierarchy(n,a,s){if(s!=="tap"||this.deps.device.platform!=="ios"||!n.packageName)return n;let c=ed(new fe().project(n),a)?.source;if(!H(n,c))return n;let d=this.prototypeAgents.get(this.deps.device.deviceId,n.packageName);if(!d)return n;try{let p=await d.request("get_prototype_status",void 0,{timeoutMs:T2}),h=p.success?P2(p.status)?.safeAreaTop:void 0;if(h===void 0)return n;return{...n,insets:{available:!0,source:"ios-sdk-safe-area",units:"points",safeArea:{top:h,left:0,right:0,bottom:0},systemChrome:{visibility:"visible",statusBar:h>0?"visible":"hidden",source:"ios-status-bar-manager"}}}}catch(p){return e.debug("Prototype tap safe-area status unavailable",p),n}}resolveTapPoint(n){return this.deps.geometry().getElementCenter(n)}getImeOccluderForTap(n,a,s){let c=this.deps.device.platform;if(c!=="android"&&c!=="ios")return;let d=new Sd().collect(DV(n,a,c),c),p=d&&OO(d,n);return p&&c==="ios"?hE(p,s):p}prototypeBarTapDecision(n,a,s,c=a.bounds){if(this.deps.device.platform!=="android"&&this.deps.device.platform!=="ios")return{kind:"proceed",point:s};let d=ed(new fe().project(n),a)?.source;return gt({hierarchy:n,ownedByPrototype:H(n,d),bounds:c,point:s,warnIfUnknown:this.deps.device.platform==="ios"})}resolveImeSafeTapPoint(n,a,{options:s,screenSize:c},d=n.bounds){let p=this.getImeOccluderForTap(n,a,c);if(!p)return this.resolveTapPoint(n);let{left:h,top:m,right:f,bottom:y}=d,b=bP([h,m,f,y],p.bounds),T={left:p.bounds[0],top:p.bounds[1],right:p.bounds[2],bottom:p.bounds[3]};if(b&&!hp(b,T))return b;let v=n.text??n["content-desc"]??n["resource-id"],g=C(n,s),S=g!=="the matched element"?g:JSON.stringify(s.elementId??s.testTag??s.accessibilityLink??"element"),O=JSON.stringify(v)??S;throw new Nm(`Target ${O} is covered by the soft keyboard; dismiss the keyboard first.`)}isElementTapTargetOffScreen(n,a,s,c){if(!Ts(s))return!1;return!this.visibleTapBounds(n,a,{screenSize:s,options:c})}invisibleMatchError(n,a,s,c){let d=n.matchedElement??n.element;if(this.isCoveredByNavigationBar(n,s,c))return`Target ${JSON.stringify(d?.text??a.text??a.elementId??"target")} is covered by the navigation bar; scroll it into view with swipeOn, then retry tapOn.`;return`Matched element ${JSON.stringify(d?.text??a.text??a.elementId??"target")} has no visible tap area (bounds ${JSON.stringify(d?.bounds)}). Scroll it into view with swipeOn, then retry tapOn.`}visibilityFailureReason(n,a,s){return this.isCoveredByNavigationBar(n,a,s)?"navigation-bar":"no-visible-tap-area"}invisibleMatchFailure(n,a,s,{screenSize:c,fallback:d}={}){let p=this.visibilityFailureReason(n,s,c);return new wo(p==="navigation-bar"||!d?this.invisibleMatchError(n,a,s,c):d,p)}navigationTapBounds(n,a,s,c){return this.deps.strategy().clipNavigationTapBounds(n,a,s,c)}isCoveredByNavigationBar(n,a,s){let c=n.element??n.matchedElement;if(!c)return!1;let d=n.matchedElement??c,p=Ut(c.bounds,d.bounds);return!!p&&!!this.navigationTapBounds(p,a,s,[d,c]).coveredBy}visibleTapBounds(n,a,{screenSize:s,options:c,tapTarget:d}={}){let p=d??n.element;if(!p?.bounds)return null;let h=X(n,p,c),m=h.bounds,f=Wee(m)?h:p,y=xf(p.bounds,s,f.bounds);if(!y||!Ts(s)||this.deps.device.platform!=="ios")return y;let b=new fe().project(a),T=p2(b,s,a);if(T&&this.prototypeBarGuardHandlesLegacyInsets(a,ed(b,p)?.source))T.statusBarTop=0;return m2({bounds:y,matched:f,target:p,nodes:b,context:T})}prototypeBarGuardHandlesLegacyInsets(n,a){return!!n.systemInsets&&(n.screenHeight??0)>0&&H(n,a)}resolveVisibleTapPoint(n,a,s,c){let d=this.resolveImeSafeTapPoint(n,a,c),p=this.getImeOccluderForTap(n,a,c.screenSize);if(this.deps.device.platform!=="ios"){let w=hp(d,s)?d:p?this.resolveImeSafeTapPoint(n,a,c,s):this.deps.geometry().getElementCenter({bounds:s}),A=M9(a,n,s,{point:w,imeBounds:p&&{left:p.bounds[0],top:p.bounds[1],right:p.bounds[2],bottom:p.bounds[3]},ownWindows:zee(c.options.layer),views:!0});if(!A.point)throw new wo(jr(A),"no-visible-tap-area");return A.point}let h=new fe().project(a),m=ed(h,n),f=this.barSafeIosVisibleBounds(a,m,s,d),y=f!==s,b=p?bP([f.left,f.top,f.right,f.bottom],p.bounds):null,T=this.deps.geometry().getElementCenter({bounds:f}),v=c.chromeElements??[n],g=this.navigationTapBounds(n.bounds,a,c.screenSize,v).bounds;if(!g)return null;let S=Toe(h,m,n.bounds,g)?[b,T,d]:[d,b,T],O=p&&{left:p.bounds[0],top:p.bounds[1],right:p.bounds[2],bottom:p.bounds[3]},R=nU({nodes:h,target:m,matched:v.flatMap((w)=>{let A=ed(h,w);return A?[A]:[]}),screen:c.screenSize,visibleBounds:f,candidates:S,imeBounds:O,isValid:(w)=>w!==null&&Number.isInteger(w.x)&&Number.isInteger(w.y)&&hp(w,f)&&hp(w,n.bounds)&&(!O||!hp(w,O))&&(!Ts(c.screenSize)||!Poe({point:w,hierarchy:a,screen:c.screenSize,elements:v}))});if(this.assertBarClippedIosTapPoint(y,R.point,d),R.coveredBy)throw new wo(koe(n,R.coveredBy,R.ownerInsideScrollContainer),"no-visible-tap-area");return R.point}getScreenSizeFromHierarchy(n,a={}){return Zi(n,{...a,platform:re(this.deps.device.platform,"tapOn"),iosMultiPanel:this.deps.device.platform==="ios"&&(this.deps.device.displays?.panels.length??0)>1})}hostControls(n){return new fe().project(n).flatMap((a)=>Ej(a.nativeId)&&a.bounds?[{id:a.nativeId,bounds:a.bounds}]:[])}pointClearOfHostControls(n,a,s,c){let d=this.hostControls(n);if(d.length===0)return c;let p=Eie({controls:d,targetId:a["resource-id"],visibleBounds:s,point:c});if(p.kind==="refuse")throw new t(`Cannot tap (${c.x}, ${c.y}): the AutoMobile prototype control ${p.control} covers the whole visible target and a touch there would dismiss the prototype. Move the target away from the top-end corner (or the top-centre escape pill), then retry.`);return p.point}barSafeIosVisibleBounds(n,a,s,c){let d=ve(n,H(n,a?.source),s);if(!d)throw this.prototypeBarRefusal(c,"status bar");return d}assertBarClippedIosTapPoint(n,a,s){if(n&&!a)throw this.prototypeBarRefusal(s,"status bar")}revalidateBarAdjustedIosTapPoint({viewHierarchy:n,tapElement:a,visibleBounds:s,finalSelection:c,options:d,screenSize:p,tapPoint:h}){if(this.deps.device.platform==="ios"){let m=new fe().project(n),f=ed(m,a),y=ve(n,H(n,f?.source),s);if(y!==s){let b=y&&nU({nodes:m,target:f,matched:[ed(m,X(c,a,d))].flatMap((T)=>T?[T]:[]),screen:p,visibleBounds:y,candidates:[h],isValid:(T)=>T!==null&&hp(T,y)&&hp(T,a.bounds)});if(!b?.point||b.point.x!==h.x||b.point.y!==h.y)throw this.prototypeBarRefusal(h,"status bar")}}}prototypeBarRefusal(n,a){return new t(`Cannot tap (${n.x}, ${n.y}): the AutoMobile prototype control is under the ${a} and the touch would not reach it. Move the control inside the safe area (safeAreaPadding on the node, or an offset in the floating placement), then retry.`)}planVisibleTapPoint({options:n,requestedAction:a,observeResult:s,viewHierarchy:c,finalSelection:d,tapElement:p}){let h=this.getScreenSizeFromHierarchy(c,{observationScreenSize:s.screenSize,display:s.viewHierarchy}),m=this.visibleTapBounds(d,c,{screenSize:h,options:a==="focus"?{...n,action:"focus"}:n,tapTarget:p});if(!m)throw this.invisibleMatchFailure(d,n,c,{screenSize:h,fallback:"Matched element has no visible tap area on this screen. Scroll it into view with swipeOn, then retry tapOn."});let f=this.resolveVisibleTapPoint(p,c,m,{options:n,screenSize:h,chromeElements:[X(d,p,a==="focus"?{...n,action:"focus"}:n),p]});if(!f)throw this.invisibleMatchFailure(d,n,c,{screenSize:h,fallback:"Matched element has no unobstructed visible tap area. Dismiss the keyboard or scroll it into view, then retry tapOn."});let y=this.pointClearOfHostControls(c,p,m,f),b=this.getImeOccluderForTap(p,c,h);if(b&&y!==f&&hp(y,{left:b.bounds[0],top:b.bounds[1],right:b.bounds[2],bottom:b.bounds[3]}))throw new Nm("Target is covered by the soft keyboard and a host dismiss control; dismiss the keyboard first.");let T=this.prototypeBarTapDecision(c,p,y,m);if(T.kind==="refuse")throw this.prototypeBarRefusal(y,T.bar);let v=T.point;this.revalidateBarAdjustedIosTapPoint({viewHierarchy:c,tapElement:p,visibleBounds:m,finalSelection:d,options:n,screenSize:h,tapPoint:v});let g=this.hostControls(c).find((S)=>!Ej(p["resource-id"])&&hp(v,S.bounds));if(g)throw new t(`Cannot tap (${v.x}, ${v.y}): the AutoMobile prototype control ${g.id} covers the visible target once the system bars are avoided and a touch there would dismiss the prototype. Move the target away from the top-end corner (or the top-centre escape pill), then retry.`);return _b(c,n.layer,v,"tap"),{tapPoint:v,...T.warning?{warning:T.warning}:{}}}}import{posix as Yr}from"path";var St="Library/AutoMobile/prototype-endpoint.json";function Xr(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)&&Object.getPrototypeOf(n)===Object.prototype}function Et(n){let a;try{a=JSON.parse(n)}catch{throw new t("The viewer wrote an invalid endpoint file: expected JSON.")}if(!Xr(a))throw new t("The viewer wrote an invalid endpoint file: expected a plain object.");if(typeof a.port!=="number"||!Number.isInteger(a.port)||a.port<1||a.port>65535)throw new t("The viewer wrote an invalid endpoint file: port must be an integer in 1..65535.");if(typeof a.token!=="string"||a.token.length<16||a.token.length>256||/[\s\p{Cc}]/u.test(a.token))throw new t("The viewer wrote an invalid endpoint file: token must contain 16..256 characters without whitespace or control characters.");return{port:a.port,token:a.token}}class Y{records=new Map;get(n,a){let s=this.records.get(n);return a===void 0||s?.bundleId===a?s?.client:void 0}release(n,a){let s=this.get(n,a);if(s!==void 0)this.records.delete(n),s.close()}releaseDevice(n){this.release(n)}record(n,a){let s=this.records.get(n);if(this.records.set(n,a),a.client.onClosed(()=>{if(this.records.get(n)===a)this.records.delete(n)}),s!==void 0&&s.client!==a.client)s.client.close()}}var Ot=256;class W{client;events=[];listeners=new Set;buffering=!0;replayDelivered=!1;closedError;closedListeners=new Set;constructor(n){this.client=n;let a=n.onEvent((s)=>{if(this.buffering){if(this.events.length===256)this.events.shift();this.events.push(s)}else this.listeners.forEach((c)=>c(s))});n.onClosed((s)=>{this.closedError=s,a(),this.events.length=0,this.listeners.clear(),this.closedListeners.forEach((c)=>c(s)),this.closedListeners.clear()})}get handshake(){return this.client.handshake}request(n,a,s){return this.client.request(n,a,s)}onEvent(n){if(this.listeners.add(n),!this.replayDelivered){this.replayDelivered=!0;while(this.events.length>0)n(this.events.shift());this.buffering=!1}return()=>this.listeners.delete(n)}onClosed(n){if(this.closedError!==void 0)n(this.closedError);else this.closedListeners.add(n);return()=>this.closedListeners.delete(n)}attachRequestHost(n){this.client.attachRequestHost?.(n)}attachChannelHost(n){this.client.attachChannelHost?.(n)}close(){this.client.close()}}class Se{socket;lines=[];firstFrame=!0;released=!1;dataListener;closeListener;failure;framer=new dd(V9,{onLine:(n)=>{if(this.failure!==void 0||!n.trim())return;if(this.firstFrame||this.released)this.firstFrame=!1,this.dataListener?.(`${n}
|
|
3
|
+
`);else{if(this.lines.length===Ot)this.lines.shift();this.lines.push(n)}},onOverflow:()=>{this.failure=new t("Prototype viewer response frame exceeded the client limit; reconnect to the viewer."),this.lines.length=0,this.socket.end(),this.closeListener?.(this.failure)}});constructor(n){this.socket=n}write(n){this.socket.write(n)}end(){this.lines.length=0,this.socket.end()}onData(n){this.dataListener=n,this.socket.onData((a)=>this.framer.push(a))}onClose(n){this.closeListener=n,this.socket.onClose((a)=>{this.failure=a??new t("Prototype viewer closed the connection."),this.lines.length=0,n(this.failure)})}release(){if(this.failure!==void 0)throw this.failure;while(this.lines.length>0)this.dataListener?.(`${this.lines.shift()}
|
|
4
|
+
`);this.released=!0}}class xV{viewer;injected;constructor(n,a){this.viewer=n;this.injected=a}get(n){return this.viewer.get(n)??this.injected.get(n)}}var{join:Jr}=Yr,wT=new Y;class At{deps;inFlight=new Map;constructor(n){this.deps=n}attach(n,a){let s=JSON.stringify([n.deviceId,a]),c=this.inFlight.get(s);if(c!==void 0)return c;let d=this.attachViewer(n,a).finally(()=>this.inFlight.delete(s));return this.inFlight.set(s,d),d}async attachViewer(n,a){if(n.platform!=="ios"||z(n)!=="simulator")throw new t("Prototype viewers run on simulators only; choose a booted iOS simulator.");let s=this.deps.connections.get(n.deviceId,a);if(s!==void 0)return s;let c=(await this.deps.containers.dataContainer(n.deviceId,a)).trim();if(!c)throw new t("No data container for the prototype viewer; install it on this simulator and retry.");let d=await this.deps.files.readText(Jr(c,St));if(d===void 0)throw new t("no endpoint file: the viewer is not running or has exited cleanly; open it from the home screen (launchApp) and retry");let{port:p,token:h}=Et(d);this.deps.connections.releaseDevice(n.deviceId);let m;try{m=await this.deps.connect(p,h)}catch(y){throw new t("Could not attach to the prototype viewer: the token may be stale (viewer relaunched) or another host is already attached (the viewer accepts one host at a time). Open the viewer and retry.",{cause:y})}if(!m.handshake.capabilities.includes(Xp))throw m.close(),new t("The endpoint is not a prototype viewer: missing prototype_persistence_replay_v1; open the viewer and retry.");let f=m instanceof W?m:new W(m);return this.deps.connections.record(n.deviceId,{bundleId:a,client:f}),f}}function Vee(n={}){let a=n.simctl??new L,s=n.files??new Pr,c=n.connector??new BO;return new At({containers:{dataContainer:async(d,p)=>{try{return await Qo({...n.containerOwnership,deviceId:d,bundleId:p,run:(h)=>a.executeCommandArgs(h)})}catch(h){if(h instanceof lo)return e.debug("Simulator returned an empty prototype viewer data container path"),"";if(h instanceof bd)throw h;throw new t("Could not resolve the prototype viewer data container; check that it is installed on this simulator.",{cause:h})}}},files:{readText:async(d)=>{if(!s.existsSync(d))return;try{return await s.readFile(d,"utf8")}catch(p){if(p instanceof Error&&"code"in p&&p.code==="ENOENT"){e.debug("Prototype viewer endpoint disappeared before it could be read.");return}throw new t("Could not read the prototype viewer endpoint file; check its permissions and retry.",{cause:p})}}},connect:async(d,p)=>{let h=new Se(await c.connect(d));try{let m=await A2({port:d,token:p,connector:{connect:async()=>h},timer:n.timer??i}),f=new W(m);return h.release(),f}catch(m){throw h.end(),new t("Prototype viewer authentication failed; reopen the viewer and retry.",{cause:m})}},connections:n.connections??wT})}function Pt(n,a){let s=[];for(let c=n.parentIndex;c!==void 0;c=a[c].parentIndex){let d=a[c].properties,p=d["resource-id"]||d["test-tag"];if(p&&s[0]!==p)s.unshift(p)}return s}function Qr(n,a){return n.length===a.length&&n.every((s,c)=>s===a[c])}function Zr(n,a){for(let s=n.parentIndex;s!==void 0;s=a[s].parentIndex)if(a[s].className==="WKWebView")return!0;return!1}function ei(n,a){let s=P,c=n.bounds,d=a.bounds;return d.left<=c.left+s&&d.top<=c.top+s&&d.right>=c.right-s&&d.bottom>=c.bottom-s&&(d.right-d.left>c.right-c.left+s||d.bottom-d.top>c.bottom-c.top+s)}function ti(n,a,s,c){let d=P,p=c!==void 0&&s.some((m)=>m.className==="UIKeyboard"&&m.bounds!==void 0&&m.bounds.top<c&&a.bounds.bottom<=m.bounds.top+d),h=["resource-id","view-id"].some((m)=>{let f=n[m];return f&&!(m==="view-id"&&f.startsWith("s2-"))&&f===a[m]});return p&&(a.bounds.right-a.bounds.left>n.bounds.right-n.bounds.left+d||h&&mn(n.bounds,a.bounds,d))}function ri(n,a,s,c){let d=k(a.filter((f)=>f.element&&Dn(f.properties)&&!Zr(f,a))),p=d.filter((f)=>f.className===n.class);if(p.length!==1)return;let h=p[0].element;if(!ei(n,h)&&!ti(n,h,a,s)||d.some((f)=>f.element!==h&&Ha(f.element)))return;let m=c??n.text;return typeof m==="string"&&m.length>0&&typeof h.text==="string"&&h.text.length>0&&m!==h.text?void 0:h}class Re{deps;constructor(n){this.deps=n}preTapProjections=new WeakMap;findSoleFocusedFieldByStableIdentity(n,a,s,c){let d=a.filter((m)=>m.element&&Dn(m.properties)&&Ha(m.element)),p=k(d);if(p.length!==1)return;let h=p[0].element;return h&&(this.deps.device.platform==="android"&&!h.text?this.hasEmptyTextFocusIdentity(n,h,a,{labelText:s,preTapHierarchy:c}):se(n,h,s))&&a$(n.bounds,h.bounds,P)?h:void 0}findSoleFocusedFieldAtTargetBounds(n,a,s){if(this.deps.device.platform!=="ios")return;let c=k(a.filter((p)=>p.element&&Dn(p.properties)&&Ha(p.element))),d=c.length===1?c[0].element:void 0;return d&&mn(n.bounds,d.bounds,P)&&!this.focusIdentitySignals(n,d,s).conflict?d:void 0}focusProjection=new fe;attachedFocusLabels=new WeakMap;attachedFocusLabel(n){let a=rt(n);if(!a)return;if(this.attachedFocusLabels.has(a))return this.attachedFocusLabels.get(a);let s=this.focusProjection.project({hierarchy:{node:a}}).filter((d)=>d.parentIndex===0&&!Dn(d.properties)).map((d)=>d.textSources.text).filter((d)=>typeof d==="string"&&d.trim().length>0),c=s.length?s.join(`
|
|
5
|
+
`):void 0;return this.attachedFocusLabels.set(a,c),c}focusIdentitySignals(n,a,s){if(!Dn(n)||n.class!==a.class||!oe(n,a)||["resource-id","test-tag","view-id"].some((d)=>[n[d],a[d]].some((p)=>p&&!(d==="view-id"&&p.startsWith("s2-")))&&n[d]!==a[d]))return{conflict:!0,matched:!1};let c=[...["hint-text","hint","placeholder","content-desc","test-tag"].map((d)=>[n[d],a[d]]),[this.attachedFocusLabel(n)??s??n.text,this.attachedFocusLabel(a)]].filter((d)=>d.every((p)=>typeof p==="string"&&p.trim().length>0));return{conflict:c.some(([d,p])=>d!==p),matched:c.some(([d,p])=>d===p)}}hasEmptyTextFocusIdentity(n,a,s,{labelText:c,preTapHierarchy:d}){let p=this.focusIdentitySignals(n,a,c);if(p.conflict)return!1;let h=k(s.filter((A)=>A.element&&Dn(A.properties)));if(h.filter((A)=>mn(A.element.bounds,a.bounds,P)).length!==1)return!1;let f=d?this.focusProjection.project(lt(d)):[],y=k(f.filter((A)=>A.element&&Dn(A.properties))),b=y.filter((A)=>A.source===rt(n)||A.className===n.class&&mn(A.element.bounds,n.bounds,P)),T=b.length===1?y.indexOf(b[0]):-1,v=h.findIndex((A)=>A.element===a);if(T>=0&&T!==v)return!1;let g=je(y,h),S=g??0,O={...n.bounds,top:n.bounds.top+S,bottom:n.bounds.bottom+S},R=mn(O,a.bounds,P),w=h.filter((A)=>A.className===n.class&&!A.element.text);return p.matched||R&&(w.length===1||T>=0&&g!==void 0)}verifyIndexedFocusTarget(n,a,s,{identifier:c,selectedIndex:d}){let p=this.focusProjection.project(s),h=this.findIndexedFocusSelection(n,s,p,{identifier:c,selectedIndex:d}),m=h&&rt(h),f=p.find((y)=>y.source===m);return Boolean(h&&Dn(h)&&f&&p.some((y)=>y.element&&Dn(y.properties)&&Ha(y.element)&&V(h,y.element,p,f))&&h[c.key]===c.value&&a.class===h.class&&a$(a.bounds,h.bounds,P))}findIndexedFocusSelection(n,a,s,{identifier:c,selectedIndex:d}){let p=c.key==="view-id"&&n.elementId===c.value&&s.filter((m)=>m.nodeKey===c.value&&!m.nativeId).length>1,h=(m)=>({windowRank:m.windowRank,area:m.bounds?ft(m.bounds):1/0,order:m.index,interactive:!0});if(p)return s.filter((m)=>m.nodeKey===c.value&&!m.nativeId&&m.element&&Dn(m.properties)).sort((m,f)=>Cf(h(m),h(f)))[n.index??d??0]?.element??null;return this.deps.findElementInHierarchy({...n,index:n.index??(n.selectionStrategy==="unique"?void 0:d)},a).selection.element}isFocusedMatchingNode(n,a,s){return Boolean(a.element&&Dn(a.properties)&&Ha(a.element)&&V(n,a.element,s))}isRefoundFocusTarget(n,a,s){let c=this.deps.findElementInHierarchy(n,s).selection.element;return Boolean(c&&Dn(c)&&Ha(c)&&V(a,c,this.focusProjection.project(s)))}verify(n,a,s,c={}){let{labelText:d,selectedIndex:p,preTapHierarchy:h}=c;if(!s?.viewHierarchy)return!1;let m=lt(s.viewHierarchy)??s.viewHierarchy,f=this.focusProjection.project(m);if(this.isFocusedInPreTapScope(a,f,d,h))return!0;try{return this.matchFocusedInputTarget(n,this.deps.withObservationScreenSize(n,s),a,{viewHierarchy:s.viewHierarchy,nodes:f,labelText:d,selectedIndex:p,preTapHierarchy:h,screenHeight:s.screenSize?.height??s.viewHierarchy.screenHeight})}catch(y){return e.debug(`[TapOnElement] focus check could not resolve the target: ${r(y)}`),!1}}isFocusedInPreTapScope(n,a,s,c){let d=rt(n);if(!c||!d)return!1;let p=this.projectPreTapHierarchy(c),h=p.find((T)=>T.source===d),m=h?Pt(h,p):[];if(m.length===0)return!1;let f=(T,v)=>Boolean(T.element&&Dn(T.properties)&&!this.focusIdentitySignals(n,T.element,s).conflict&&Qr(Pt(T,v),m));if(k(p.filter((T)=>f(T,p))).length!==1)return!1;let y=a.filter((T)=>f(T,a)),b=a.filter((T)=>T.element&&Dn(T.properties)&&Ha(T.element));return k(y).length===1&&y.every((T)=>Ha(T.element))&&b.every((T)=>y.includes(T))}projectPreTapHierarchy(n){let a=this.preTapProjections.get(n);if(a)return a;let s=this.focusProjection.project(lt(n)??n);return this.preTapProjections.set(n,s),s}matchFocusedInputTarget(n,a,s,{viewHierarchy:c,nodes:d,labelText:p,selectedIndex:h,preTapHierarchy:m,screenHeight:f}){let y=Xe(s,d);if(y?.shared)return this.verifyIndexedFocusTarget(a,s,c,{identifier:y,selectedIndex:h});let b=()=>this.deps.device.platform==="ios"&&Boolean(ri(s,d,f,p));if(y)return d.some((v)=>v.element&&Dn(v.properties)&&Ha(v.element)&&v.element[y.key]===y.value&&V(s,v.element,d))||b();if(d.find((v)=>this.isFocusedMatchingNode(s,v,d)))return!0;if(this.findSoleFocusedFieldByStableIdentity(s,d,p,m))return!0;if(this.findSoleFocusedFieldAtTargetBounds(s,d,p))return!0;if(b())return!0;if(!n.testTag&&!(n.elementId&&s["resource-id"]))return!1;return this.isRefoundFocusTarget(a,s,c)}}var kt=[50,100,200,400],ii=zt(kt),ni=kt.reduce((n,a)=>n+a,0);class we{host;constructor(n){this.host=n}beforeTap(n,a,s,c){if(n.ensureChecked===void 0)return;if(!dt(a.checkable)){let d=this.host.elementAffordances(a);throw new t(`tapOn ensureChecked requires a toggle element; ${this.host.elementIdentity(a)} has affordances: ${d.join(", ")||"none"}`)}if(dt(a.checked)!==n.ensureChecked)return;return{success:!0,action:n.action,element:a,selectedElement:s,searchUntil:c,skipped:"already-checked"}}async refreshSelection(n,a,s,c){if(n.ensureChecked===void 0)return{selection:s,viewHierarchy:a.viewHierarchy};let d=await this.host.tapVerificationRefresh({refresh:n.verification?.refresh,screenSize:a.screenSize,signal:c})(vC);if(!d)throw new t("tapOn ensureChecked: unable to refresh toggle before tapping");let p=this.host.findElementInHierarchy(this.host.withObservationScreenSize(n,a),d).selection;if(!p.element)throw new t("tapOn ensureChecked: toggle not found in fresh hierarchy");return this.host.replaceObservationHierarchy(a,d,!0),{selection:p,viewHierarchy:d}}async afterTap(n,a,s){if(n.ensureChecked===void 0)return;let c=()=>{let p=a.viewHierarchy?this.host.findElementInHierarchy(this.host.withObservationScreenSize(n,a),a.viewHierarchy).selection.element:void 0;return p?dt(p.checked):"not found"},d=c();if(d!==n.ensureChecked)d=await this.pollAfterTap(c,n.ensureChecked,a,{signal:s,refresh:n.verification?.refresh});return d===n.ensureChecked?void 0:`tapOn ensureChecked: tapped element but checked is now ${d} (expected ${n.ensureChecked})`}async applyResult(n,a,s){if(a.ensureChecked===void 0)return;let c=n.observation;if(c===void 0)return;let d=await this.afterTap(a,c,s);if(d!==void 0)n.success=!1,n.error=d}async pollAfterTap(n,a,s,c={}){let{signal:d}=c,p=this.host.timer.now()+ni,h=n();for(let m=1;this.host.timer.now()<p;m++){o(d);let f=Math.min(ii.delayForAttempt(m),p-this.host.timer.now());await this.host.timer.sleep(f);let y=p-this.host.timer.now();if(y<=0)break;let b=await this.host.tapVerificationRefresh({refresh:c.refresh,screenSize:s.screenSize,signal:d})(Math.min(vC,y));if(!b)continue;if(this.host.replaceObservationHierarchy(s,b,!0),h=n(),h===a)return h}return h}}function ai(n){let{freshness:a,viewHierarchy:s}=n,c=hn(s);if(s!==void 0&&typeof s.hierarchy==="object"&&s.hierarchy!==null&&!("error"in s.hierarchy)&&s.ctrlProxyIncomplete!==!0&&s.fresh!==!1&&c!==void 0&&a?.isFresh===!1&&a.category==="cache_age")n.freshness={...a,isFresh:!0,verified:!0,actualTimestamp:c,ageMs:0,staleDurationMs:void 0,warning:void 0,category:void 0}}class Ae{host;constructor(n){this.host=n}async deriveEffectAfterPostTapObservation(n,a,s,c){let d=this.host.deriveTapEffect(n,a);if(c?.settlePostTapEffect===!1||!this.host.settlesPostTapChange()||!n)return{effect:d,observation:a};if(d?.screenChanged!==!0)return this.host.settler().waitForPostTapChange(n,a,s);if(d.basis!=="viewHierarchy changed")return{effect:d,observation:a};return this.host.settler().settleHierarchyOnlyChange(n,a,s)}enforceFreshnessConsistency(n,a){if(!n||!a.observation||a.effect?.screenChanged!==!0)return;if(a.observation.wakefulness==="Asleep")return;if(this.host.deriveTapEffect(n,a.observation)?.screenChanged===!0)return;let c=a.observation.freshness;a.observation.freshness={...c??{isFresh:!0},verified:!1,isFresh:!1,category:"effect_inconsistent",warning:"effect.screenChanged is true, but this observation's own capture still matches the "+"pre-action screen \u2014 it predates the detected transition. Call observe again for the "+"current, post-action state."}}replaceObservationHierarchy(n,a,s){let c=this.host.getScreenSizeFromHierarchy(a,{observationScreenSize:n.screenSize,display:n.viewHierarchy});n.viewHierarchy=a;let d=hn(a);if(d!==void 0)n.updatedAt=d;if(c)n.screenSize=c;else if(n.screenSize)n.screenSize={width:0,height:0};if(this.host.applyRefreshedObservationRotation(n,a.rotation),s)ai(n)}}var si=Qc,oi=150;class $F{observeScreen;timer;constructor(n,a=i){this.observeScreen=n;this.timer=a}async execute(n,a={}){let s=a.timeoutMs??si,c=a.pollMs??oi,d={matched:!1,candidates:[]},p=await KT(this.observeScreen,this.timer,{timeoutMs:s,pollMs:c,signal:a.signal,initialMinTimestampMs:a.initialMinTimestampMs,skipWaitForFresh:a.skipWaitForFresh,requireFreshExtraction:a.requireFreshExtraction,readBackStackEachPoll:a.readBackStackEachPoll},(h)=>(d=n(h),d.matched));if(p.stopped)return{matched:!0,matchedElement:d.matchedElement,candidates:[],observation:p.observation,polls:p.polls,waitMs:p.waitMs,timedOut:!1};return{matched:!1,matchedElement:void 0,candidates:d.candidates??[],...d.diagnostic?{diagnostic:d.diagnostic}:{},observation:p.observation,polls:p.polls,waitMs:p.waitMs,timedOut:!0,screenOff:p.terminalReason==="screen_off"?!0:void 0}}}class Pe{elementParser;constructor(n){this.elementParser=n}detect(n,a){let s=n?.viewHierarchy,c=a?.viewHierarchy,d=this.detectContextMenuOpened(s,c),p=this.detectSelectionStarted(c),h=this.detectNewWindow(s,c);return{pressRecognized:d||p||h,contextMenuOpened:d,selectionStarted:p}}detectContextMenuOpened(n,a){if(!a)return!1;let s=this.getRootSignatures(n),c=this.elementParser.extractRootNodes(a);for(let d of c){let p=this.getRootSignature(d);if(s.has(p))continue;if(this.containsMenuIndicators(d))return!0}return!1}detectNewWindow(n,a){if(!a)return!1;let s=this.getRootSignatures(n),c=this.elementParser.extractRootNodes(a);if(c.length===0)return!1;return c.some((d)=>!s.has(this.getRootSignature(d)))}detectSelectionStarted(n){if(!n)return!1;let a=this.elementParser.extractRootNodes(n),s=!1,c=[["textSelectionStart","textSelectionEnd"],["selectionStart","selectionEnd"]];for(let d of a)if(this.elementParser.traverseNode(d,(p)=>{if(s)return;let h=this.elementParser.extractNodeProperties(p);for(let[m,f]of c){let y=h?.[m]??h?.[m.toLowerCase()],b=h?.[f]??h?.[f.toLowerCase()];if(!this.isActiveSelectionRange(y,b))continue;s=!0;return}}),s)break;return s}isActiveSelectionRange(n,a){if(n===void 0||a===void 0)return!1;let s=typeof n==="string"?parseInt(n,10):Number(n),c=typeof a==="string"?parseInt(a,10):Number(a);return!Number.isNaN(s)&&!Number.isNaN(c)&&c>s}getRootSignatures(n){if(!n)return new Set;let a=this.elementParser.extractRootNodes(n);return new Set(a.map((s)=>this.getRootSignature(s)))}getRootSignature(n){let a=this.elementParser.extractNodeProperties(n),s=mr(a),c=a.class??a.className??"",d=wt(qt(n)),p=d?`${d.left},${d.top},${d.right},${d.bottom}`:"",h=OR(a,["text","content-desc"]);return`${s}|${c}|${p}|${h}`}containsMenuIndicators(n){let a=!1;return this.elementParser.traverseNode(n,(s)=>{if(a)return;let c=this.elementParser.extractNodeProperties(s),d=mr(c).toLowerCase(),p=(c.class??c.className??"").toLowerCase(),h=OR(c,["text","content-desc"]).toLowerCase();if(this.hasMenuIndicator(d,p,h))a=!0}),a}hasMenuIndicator(n,a,s){return n.includes("menu")||n.includes("popup")||a.includes("menu")||a.includes("popup")||s.includes("menu")||s.includes("popup")}}class ke{device;adb;accessibilityDetector;featureFlags;longPressDurationMs=500;retryTapIfNoChange=!0;warnsOnDisabledElement=!0;settlesPostTapChange=!0;verifiesRefreshedDisplay=!0;promotesClickableAncestor=!0;settlesFocusChangeAfterTap=!1;rethrowsKeyboardOcclusion=!0;applyRefreshedObservationRotation(){}constructor(n,a,s=li,c){this.device=n;this.adb=a;this.accessibilityDetector=s;this.featureFlags=c}prepareViewHierarchyForResponse(n,a,s){let c=a.filterViewHierarchy(n);return va(c,n),c}clipNavigationTapBounds(n,a,s,c){return{bounds:n}}async isAccessibilityServiceEnabled(n){let{talkBack:a,unconfirmed:s}=await rg(this.accessibilityDetector,this.device.deviceId,this.adb,this.featureFlags);if(s)n?.(Na);return a===!0}shouldRunPreTapStability(n){return Boolean(n.preTapStability)}}class xe{device;iosVoiceOverDetector;featureFlags;longPressDurationMs=1000;retryTapIfNoChange=!1;warnsOnDisabledElement=!1;settlesPostTapChange=!1;verifiesRefreshedDisplay=!1;promotesClickableAncestor=!1;settlesFocusChangeAfterTap=!0;rethrowsKeyboardOcclusion=!1;applyRefreshedObservationRotation(n,a){n.rotation=Tc(a,n.screenSize)}constructor(n,a=ko,s){this.device=n;this.iosVoiceOverDetector=a;this.featureFlags=s}prepareViewHierarchyForResponse(n,a,s){if(!s?.width||!s?.height)return null;let c=a.filterOffscreenNodes(n,s.width,s.height);return va(c,n),c}clipNavigationTapBounds(n,a,s,c){if(!Ts(s))return{bounds:n};return xO({bounds:n,hierarchy:a,screen:s,elements:c,regions:["navigation bar"],forTapTarget:!0})}async isAccessibilityServiceEnabled(){let n=x.getInstance(this.device);return this.iosVoiceOverDetector.isVoiceOverActiveOrUnknown(this.device.deviceId,n,{featureFlags:this.featureFlags})}shouldRunPreTapStability(n){return!1}}function xt(n,a,s,{iosVoiceOverDetector:c,featureFlags:d}){if(n.platform==="ios")return new xe(n,c,d);return new ke(n,a,s,d)}function Ct(n,a){let{device:s,adbFactory:c,adb:d,timer:p,accessibilityDetector:h}=a,m=n.talkBackDriverFactory??new eg(c),f=n.talkBackStrategy??new Wv({timer:p,driverFactory:m}),y=n.iosVoiceOverDetector??ko,b=n.featureFlags??ar.getInstance(),T=n.tapStrategy??xt(s,d,h,{iosVoiceOverDetector:y,featureFlags:b});return{talkBackDriverFactory:m,talkBackStrategy:f,iosVoiceOverDetector:y,featureFlags:b,strategy:T}}var ci={android:{tapDispatch:"android",androidLinkActivation:!0,iosLinkActivation:!1,capturedOwnerIdentity:!1,routesAndroidDisplay:!0,detectsAccessibilityBeforeSearch:!0,refreshesAccessibilityHierarchyBeforeSearch:!0,revalidatesCachedTargets:!0,canReuseAccessibilityState:!0,requiresFreshExtractionForCachedTarget:!1,panelAwareSelection:!1},ios:{tapDispatch:"ios",androidLinkActivation:!1,iosLinkActivation:!0,capturedOwnerIdentity:!0,routesAndroidDisplay:!1,detectsAccessibilityBeforeSearch:!1,refreshesAccessibilityHierarchyBeforeSearch:!1,revalidatesCachedTargets:!0,canReuseAccessibilityState:!1,requiresFreshExtractionForCachedTarget:!0,panelAwareSelection:!0}},di={tapDispatch:void 0,androidLinkActivation:!1,iosLinkActivation:!1,capturedOwnerIdentity:!1,routesAndroidDisplay:!1,detectsAccessibilityBeforeSearch:!1,refreshesAccessibilityHierarchyBeforeSearch:!1,revalidatesCachedTargets:!1,canReuseAccessibilityState:!0,requiresFreshExtractionForCachedTarget:!1,panelAwareSelection:!1};function Ft(n){return dr(n)?ci[n]:di}class bc extends Oe{semanticLinks=new ce({usesAndroidLinkActivation:()=>this.platformTraits.androidLinkActivation,usesIosLinkActivation:()=>this.platformTraits.iosLinkActivation,usesCapturedOwnerIdentity:()=>this.platformTraits.capturedOwnerIdentity,accessibilityService:()=>this.accessibilityService,activateSemanticLink:(...n)=>this.activateSemanticLink(...n),device:()=>this.device,elementParser:()=>this.elementParser,hasUniqueSemanticLinkOwner:(...n)=>this.hasUniqueSemanticLinkOwner(...n),resolveContainerElement:(...n)=>this.resolveContainerElement(...n),withObservationScreenSize:(...n)=>this.withObservationScreenSize(...n)});targets=new Te({xrDisplaySize:()=>this.xrDisplaySize??this.observeScreen.xrDisplaySize,accessibilityService:()=>this.accessibilityService,adb:()=>this.adb,buildSelectedElementMetadata:(...n)=>this.buildSelectedElementMetadata(...n),deriveInteractionEffect:(...n)=>this.deriveInteractionEffect(...n),device:()=>this.device,displayTransitionReader:()=>this.displayTransitionReader,elementParser:()=>this.elementParser,ensureChecked:()=>this.ensureChecked,findElementInHierarchy:(...n)=>this.findElementInHierarchy(...n),finder:()=>this.finder,focusVerifier:()=>this.focusVerifier,geometry:()=>this.geometry,getScreenSizeFromHierarchy:(...n)=>this.getScreenSizeFromHierarchy(...n),getSearchUntilDuration:(...n)=>this.getSearchUntilDuration(...n),hashViewHierarchy:(...n)=>this.hashViewHierarchy(...n),hierarchyCapture:()=>this.hierarchyCapture,invisibleMatchFailure:(...n)=>this.invisibleMatchFailure(...n),isAndroidXr:(n)=>da({device:this.device,adb:this.adb,signal:n},this.xrDetector),isClickableElement:(...n)=>this.isClickableElement(...n),isElementTapTargetOffScreen:(...n)=>this.isElementTapTargetOffScreen(...n),isLongClickableElement:(...n)=>this.isLongClickableElement(...n),postTapEffect:()=>this.postTapEffect,refreshViewHierarchy:(...n)=>this.refreshViewHierarchy(...n),refreshedDisplayTransitions:()=>this.refreshedDisplayTransitions,renderedDisplayGeneration:()=>this.renderedDisplayGeneration,replaceObservationHierarchy:(...n)=>this.replaceObservationHierarchy(...n),resolveTapTargetElement:(...n)=>this.resolveTapTargetElement(...n),screenshotCapturer:()=>this.screenshotCapturer,selectionStateTracker:()=>this.selectionStateTracker,staleDisplay:(...n)=>this.staleDisplay(...n),staleSyntheticTarget:(...n)=>this.staleSyntheticTarget(...n),strategy:()=>this.strategy,tapPoints:()=>this.tapPoints,tapVerificationRefresh:(...n)=>this.tapVerificationRefresh(...n),timer:()=>this.timer,viewHierarchy:()=>this.viewHierarchy,visionAnalyzer:()=>this.visionAnalyzer,visionConfig:()=>this.visionConfig,withObservationScreenSize:(...n)=>this.withObservationScreenSize(...n)});displayRouter=new le({routesAndroidDisplay:()=>this.platformTraits.routesAndroidDisplay,accessibilityService:()=>this.accessibilityService,adb:()=>this.adb,applyEnsureCheckedResult:(...n)=>this.applyEnsureCheckedResult(...n),buildSelectedElementMetadata:(...n)=>this.buildSelectedElementMetadata(...n),checkPostActionDisplay:(...n)=>this.checkPostActionDisplay(...n),completedDisplayFailure:(...n)=>this.completedDisplayFailure(...n),createErrorResult:(...n)=>this.createErrorResult(...n),device:()=>this.device,displayTransitionReader:()=>this.displayTransitionReader,ensureCheckedBeforeTap:(...n)=>this.ensureCheckedBeforeTap(...n),findElementInHierarchy:(...n)=>this.findElementInHierarchy(...n),geometry:()=>this.geometry,getSearchUntilDuration:(...n)=>this.getSearchUntilDuration(...n),handleElementNotFound:(...n)=>this.handleElementNotFound(...n),hashViewHierarchy:(...n)=>this.hashViewHierarchy(...n),hierarchyCapture:()=>this.hierarchyCapture,lastRenderedObservation:()=>this.lastRenderedObservation,observeScreen:()=>this.observeScreen,observedInteraction:(...n)=>this.observedInteraction(...n),refreshEnsureCheckedSelection:(...n)=>this.refreshEnsureCheckedSelection(...n),replaceObservationHierarchy:(...n)=>this.replaceObservationHierarchy(...n),resolveAndroidStableTapTargetAfterRefreshes:(...n)=>this.resolveAndroidStableTapTargetAfterRefreshes(...n),resolveVisibleTapPoint:(...n)=>this.resolveVisibleTapPoint(...n),rethrowKeyboardOcclusion:(...n)=>this.rethrowKeyboardOcclusion(...n),rethrowObservationAbort:(...n)=>this.rethrowObservationAbort(...n),retryTapIfNoChange:(...n)=>this.retryTapIfNoChange(...n),searchForElement:(...n)=>this.searchForElement(...n),staleDisplay:(...n)=>this.staleDisplay(...n),strategy:()=>this.strategy,talkBackDriverFactory:()=>this.talkBackDriverFactory,talkBackStrategy:()=>this.talkBackStrategy,tapPoints:()=>this.tapPoints,timer:()=>this.timer,unverifiableDisplayPostState:(...n)=>this.unverifiableDisplayPostState(...n),validateOptions:(...n)=>this.validateOptions(...n),verifyFocusedInputTarget:(...n)=>this.verifyFocusedInputTarget(...n),visibleTapBounds:(...n)=>this.visibleTapBounds(...n),withObservationScreenSize:(...n)=>this.withObservationScreenSize(...n)});execution=new pe({runPlatformTap:async(n)=>{let a=this.platformTraits.tapDispatch;if(a===void 0)throw Rt(this.device.platform,"tap on elements");return n[a]()},detectsAccessibilityBeforeSearch:()=>this.platformTraits.detectsAccessibilityBeforeSearch,refreshesAccessibilityHierarchyBeforeSearch:()=>this.platformTraits.refreshesAccessibilityHierarchyBeforeSearch,revalidatesCachedTargets:()=>this.platformTraits.revalidatesCachedTargets,canReuseAccessibilityState:()=>this.platformTraits.canReuseAccessibilityState,requiresFreshExtractionForCachedTarget:()=>this.platformTraits.requiresFreshExtractionForCachedTarget,activateAccessibilityLinkPhase:(...n)=>this.activateAccessibilityLinkPhase(...n),activateSubtextPhase:(...n)=>this.activateSubtextPhase(...n),applyEnsureCheckedResult:(...n)=>this.applyEnsureCheckedResult(...n),assertLongPressWithinRequestBudget:(...n)=>this.assertLongPressWithinRequestBudget(...n),buildSelectedElementMetadata:(...n)=>this.buildSelectedElementMetadata(...n),captureTerminalObservationScreenshot:(...n)=>this.captureTerminalObservationScreenshot(...n),completedDisplayFailure:(...n)=>this.completedDisplayFailure(...n),confirmFocusAfterTap:(...n)=>this.confirmFocusAfterTap(...n),createErrorResult:(...n)=>this.createErrorResult(...n),deriveTapEffectAfterPostTapObservation:(...n)=>this.deriveTapEffectAfterPostTapObservation(...n),detectLongPressMetadata:(...n)=>this.detectLongPressMetadata(...n),device:()=>this.device,didCompleteDisplayGesture:(...n)=>this.didCompleteDisplayGesture(...n),enforceFreshnessConsistencyWithEffect:(...n)=>this.enforceFreshnessConsistencyWithEffect(...n),ensureCheckedBeforeTap:(...n)=>this.ensureCheckedBeforeTap(...n),executeAndroidTap:(...n)=>this.executeAndroidTap(...n),executeOnDisplay:(...n)=>this.executeOnDisplay(...n),executeiOSTap:(...n)=>this.executeiOSTap(...n),geometry:()=>this.geometry,getLongPressDuration:(...n)=>this.getLongPressDuration(...n),handleElementNotFound:(...n)=>this.handleElementNotFound(...n),hashViewHierarchy:(...n)=>this.hashViewHierarchy(...n),logClickableParentSelection:(...n)=>this.logClickableParentSelection(...n),longPressMetadataDetector:()=>this.longPressMetadataDetector,observedInteraction:(...n)=>this.observedInteraction(...n),predictionToolArgs:(...n)=>this.predictionToolArgs(...n),prepareSelectionCapture:(...n)=>this.prepareSelectionCapture(...n),readScopeFailureResult:(...n)=>this.readScopeFailureResult(...n),rebuildSelectedElementMetadataAfterStability:(...n)=>this.rebuildSelectedElementMetadataAfterStability(...n),recordDeferredPredictionOutcome:(...n)=>this.recordDeferredPredictionOutcome(...n),refreshEnsureCheckedSelection:(...n)=>this.refreshEnsureCheckedSelection(...n),refreshViewHierarchy:(...n)=>this.refreshViewHierarchy(...n),replaceObservationHierarchy:(...n)=>this.replaceObservationHierarchy(...n),resolveAndroidStableTapTargetAfterRefreshes:(...n)=>this.resolveAndroidStableTapTargetAfterRefreshes(...n),resolveTapTargetElement:(...n)=>this.resolveTapTargetElement(...n),rethrowKeyboardOcclusion:(...n)=>this.rethrowKeyboardOcclusion(...n),retryTapIfNoChange:(...n)=>this.retryTapIfNoChange(...n),searchForElement:(...n)=>this.searchForElement(...n),selectionStateTracker:()=>this.selectionStateTracker,strategy:()=>this.strategy,tapPoints:()=>this.tapPoints,tapVerificationRefresh:(...n)=>this.tapVerificationRefresh(...n),timer:()=>this.timer,unverifiableDisplayPostState:(...n)=>this.unverifiableDisplayPostState(...n),validateOptions:(...n)=>this.validateOptions(...n),verifyFocusAfterTap:(...n)=>this.verifyFocusAfterTap(...n),verifyFocusedInputTarget:(...n)=>this.verifyFocusedInputTarget(...n),withObservationScreenSize:(...n)=>this.withObservationScreenSize(...n)});gestureDispatcher=new ue({accessibilityService:()=>this.accessibilityService,adb:()=>this.adb,device:()=>this.device,isAndroidXr:(n)=>da({device:this.device,adb:this.adb,signal:n},this.xrDetector),dispatchCoordinateTapOrAdbFallback:(...n)=>this.dispatchCoordinateTapOrAdbFallback(...n),executeAndroidLongPress:(...n)=>this.executeAndroidLongPress(...n),executeAndroidTap:(...n)=>this.executeAndroidTap(...n),executeAndroidTapWithAccessibility:(...n)=>this.executeAndroidTapWithAccessibility(...n),executeAndroidTapWithCoordinates:(...n)=>this.executeAndroidTapWithCoordinates(...n),executeIOSTapWithVoiceOver:(...n)=>this.executeIOSTapWithVoiceOver(...n),executeScopedAndroidTap:(...n)=>this.executeScopedAndroidTap(...n),executeiOSTapWithCoordinates:(...n)=>this.executeiOSTapWithCoordinates(...n),featureFlags:()=>this.featureFlags,findElementInHierarchy:(...n)=>this.findElementInHierarchy(...n),finder:()=>this.finder,geometry:()=>this.geometry,getScreenSizeFromHierarchy:(...n)=>this.getScreenSizeFromHierarchy(...n),hashViewHierarchy:(...n)=>this.hashViewHierarchy(...n),isScreenReaderNavigationEnabled:(...n)=>this.isScreenReaderNavigationEnabled(...n),readOptionalDisplayFence:(...n)=>this.readOptionalDisplayFence(...n),refreshedRetrySelection:(...n)=>this.refreshedRetrySelection(...n),reportTalkBackActivationWarning:(...n)=>this.reportTalkBackActivationWarning(...n),resolveEnsureCheckedRetryTarget:(...n)=>this.resolveEnsureCheckedRetryTarget(...n),resolveRefreshedRetryTarget:(...n)=>this.resolveRefreshedRetryTarget(...n),resolveTapTargetElement:(...n)=>this.resolveTapTargetElement(...n),resolveVisibleTapPoint:(...n)=>this.resolveVisibleTapPoint(...n),semanticAndroidLongPressTargetError:(...n)=>this.semanticAndroidLongPressTargetError(...n),strategy:()=>this.strategy,talkBackDriverFactory:()=>this.talkBackDriverFactory,talkBackStrategy:()=>this.talkBackStrategy,talkBackTargetContext:(...n)=>this.talkBackTargetContext(...n),tapVerificationRefresh:(...n)=>this.tapVerificationRefresh(...n),timer:()=>this.timer,tryDocumentsUiRowActivation:(...n)=>this.tryDocumentsUiRowActivation(...n),trySemanticAndroidLongPress:(...n)=>this.trySemanticAndroidLongPress(...n),visibleTapBounds:(...n)=>this.visibleTapBounds(...n),withRetryScreenSize:(...n)=>this.withRetryScreenSize(...n)});refreshedDisplayTransitions;lastRenderedObservation;focusVerifier=new Re({device:this.device,findElementInHierarchy:(n,a)=>this.findElementInHierarchy(n,a),withObservationScreenSize:(n,a)=>this.withObservationScreenSize(n,a)});tapPoints=new ge({device:this.device,geometry:()=>this.geometry,strategy:()=>this.strategy,prototypeAgents:{get:(n,a)=>this.prototypeAgents.get(n,a)}});prototypeAgents;finder=new be({device:this.device,elementSelector:()=>this.elementSelector,tapPoints:this.tapPoints});settler=new ye({timer:this.timer,waitForCondition:()=>this.waitForCondition,hashViewHierarchy:(n)=>this.hashViewHierarchy(n),deriveTapEffect:(n,a)=>this.deriveTapEffect(n,a),compareActiveWindow:(n,a)=>this.compareActiveWindow(n,a)});postTapEffect=new Ae({applyRefreshedObservationRotation:(n,a)=>this.strategy.applyRefreshedObservationRotation(n,a),settlesPostTapChange:()=>this.strategy.settlesPostTapChange,settler:()=>this.settler,deriveTapEffect:(n,a)=>this.deriveTapEffect(n,a),getScreenSizeFromHierarchy:(n,a)=>this.getScreenSizeFromHierarchy(n,a)});ensureChecked=new we({timer:this.timer,tapVerificationRefresh:(n)=>this.tapVerificationRefresh(n),findElementInHierarchy:(n,a)=>this.findElementInHierarchy(n,a),withObservationScreenSize:(n,a)=>this.withObservationScreenSize(n,a),replaceObservationHierarchy:(n,a,s)=>this.replaceObservationHierarchy(n,a,s),elementAffordances:(n)=>this.elementAffordances(n),elementIdentity:(n)=>this.elementIdentity(n)});geometry;elementParser;accessibilityService;visionConfig;screenshotCapturer;visionAnalyzer;selectionStateTracker;accessibilityDetector;elementSelector;viewHierarchy;hierarchyCapture;talkBackStrategy;featureFlags;talkBackDriverFactory;iosVoiceOverDetector;strategy;longPressMetadataDetector;waitForCondition;xrDisplaySize;xrDetector;constructor(n,a=null,s={}){super(n,{adb:a,timer:s.timer,displayFence:s});this.xrDisplaySize=s.xrDisplaySize,this.refreshedDisplayTransitions=s.displayTransitions??Ce,this.lastRenderedObservation=s.lastRenderedObservation,this.prototypeAgents=s.prototypeAgents??{get:(d,p)=>wT.get(d,p)??Of.getRecord(d,p)?.client},this.waitForCondition=s.waitForCondition??new $F(this.observeScreen,this.timer),this.geometry=new or,this.elementParser=new K,this.accessibilityService=Xs(n,this.adbFactory),this.visionConfig=s.visionConfig||Lm,this.screenshotCapturer=s.screenshotCapturer??new gp(n,this.adbFactory),this.visionAnalyzer=s.visionAnalyzer,this.viewHierarchy=new Qi(n,this.adbFactory),this.hierarchyCapture=s.hierarchyCapture??new dy(n.platform,{readCached:(d)=>this.viewHierarchy.getViewHierarchy({},{skipWaitForFresh:!0,minTimestamp:d.minTimestamp,signal:d.signal,timeoutMs:d.timeoutMs}),readFresh:async(d)=>{if(d.displayId!==void 0)return(await Pn(n,{adbFactory:this.adbFactory,timer:this.timer}).capture(d)).hierarchy;let p=await this.readFreshHierarchy(d.timeoutMs??HF,void 0,d.signal,d.requireFreshExtraction);if(!p)throw new t("Unable to retrieve a fresh tap hierarchy");return p},projectVisible:(d)=>this.viewHierarchy.projectActionableHierarchy(d)},this.timer),this.selectionStateTracker=s.selectionStateTracker??new z5({screenshotCapturer:this.screenshotCapturer}),this.accessibilityDetector=s.accessibilityDetector||li,this.xrDetector=s.xrDetector,this.elementSelector=this.createElementSelector(s);let c=Ct(s,{device:n,adbFactory:this.adbFactory,adb:this.adb,timer:this.timer,accessibilityDetector:this.accessibilityDetector});this.talkBackDriverFactory=c.talkBackDriverFactory,this.talkBackStrategy=c.talkBackStrategy,this.iosVoiceOverDetector=c.iosVoiceOverDetector,this.featureFlags=c.featureFlags,this.strategy=c.strategy,this.longPressMetadataDetector=new Pe(this.elementParser)}get platformTraits(){return Ft(this.device.platform)}createElementSelector(n){return n.elementSelector??new br(void 0,void 0,{platform:ae(this.device.platform)?"ios":re(this.device.platform,"tapOn"),iosMultiPanel:!ae(this.device.platform)&&this.platformTraits.panelAwareSelection&&(this.device.displays?.panels.length??0)>1})}get testHooks(){return{validateOptions:this.validateOptions.bind(this),hasUniqueSemanticLinkOwner:this.hasUniqueSemanticLinkOwner.bind(this),hashViewHierarchy:this.hashViewHierarchy.bind(this),replaceObservationHierarchy:this.replaceObservationHierarchy.bind(this),verifyFocusedInputTarget:this.verifyFocusedInputTarget.bind(this),handleElementNotFound:this.handleElementNotFound.bind(this),executeAndroidLongPress:this.executeAndroidLongPress.bind(this),executeiOSTap:this.executeiOSTap.bind(this),executeiOSTapWithCoordinates:this.executeiOSTapWithCoordinates.bind(this),executeIOSTapWithVoiceOver:this.executeIOSTapWithVoiceOver.bind(this),setValidateOptions:(n)=>{this.validateOptions=n},setIosCoordinateTap:(n)=>{this.executeiOSTapWithCoordinates=n},setTerminalScreenshotCapture:(n)=>{this.captureTerminalObservationScreenshot=n},setDeferredPredictionRecorder:(n)=>{this.recordDeferredPredictionOutcome=n}}}createErrorResult(...n){return this.semanticLinks.createErrorResult(...n)}validateOptions(...n){return this.semanticLinks.validateOptions(...n)}activateSemanticLink(...n){return this.semanticLinks.activateSemanticLink(...n)}hasUniqueSemanticLinkOwner(...n){return this.semanticLinks.hasUniqueSemanticLinkOwner(...n)}getSearchUntilDuration(...n){return this.targets.getSearchUntilDuration(...n)}hashViewHierarchy(...n){return this.targets.hashViewHierarchy(...n)}deriveTapEffect(...n){return this.targets.deriveTapEffect(...n)}deriveTapEffectAfterPostTapObservation(...n){return this.targets.deriveTapEffectAfterPostTapObservation(...n)}enforceFreshnessConsistencyWithEffect(...n){return this.targets.enforceFreshnessConsistencyWithEffect(...n)}replaceObservationHierarchy(...n){return this.targets.replaceObservationHierarchy(...n)}logClickableParentSelection(...n){return this.targets.logClickableParentSelection(...n)}prepareSelectionCapture(...n){return this.targets.prepareSelectionCapture(...n)}withObservationScreenSize(...n){return this.targets.withObservationScreenSize(...n)}findElementInHierarchy(...n){return this.targets.findElementInHierarchy(...n)}verifyFocusedInputTarget(...n){return this.targets.verifyFocusedInputTarget(...n)}invisibleMatchFailure(...n){return this.targets.invisibleMatchFailure(...n)}resolveTapPoint(...n){return this.targets.resolveTapPoint(...n)}resolveContainerElement(...n){return this.targets.resolveContainerElement(...n)}isElementTapTargetOffScreen=(...n)=>this.tapPoints.isElementTapTargetOffScreen(...n);visibleTapBounds=(...n)=>this.targets.visibleTapBounds(...n);resolveVisibleTapPoint=(...n)=>this.targets.resolveVisibleTapPoint(...n);getScreenSizeFromHierarchy=(...n)=>this.tapPoints.getScreenSizeFromHierarchy(...n);verifyFocusAfterTap=(...n)=>this.targets.verifyFocusAfterTap(...n);refreshViewHierarchy(...n){return this.targets.refreshViewHierarchy(...n)}tapVerificationRefresh(...n){return this.targets.tapVerificationRefresh(...n)}readFreshHierarchy(...n){return this.targets.readFreshHierarchy(...n)}resolveAndroidStableTapTargetAfterRefreshes(...n){return this.targets.resolveAndroidStableTapTargetAfterRefreshes(...n)}staleSyntheticTarget(...n){return this.targets.staleSyntheticTarget(...n)}searchForElement(...n){return this.targets.searchForElement(...n)}buildSelectedElementMetadata(...n){let a=this.targets.buildSelectedElementMetadata(...n);return Rte(this.device.platform,n[0],a)}rebuildSelectedElementMetadataAfterStability(...n){return this.targets.rebuildSelectedElementMetadataAfterStability(...n)}handleElementNotFound(...n){return this.targets.handleElementNotFound(...n)}isClickableElement(...n){return this.targets.isClickableElement(...n)}isLongClickableElement(...n){return this.targets.isLongClickableElement(...n)}elementAffordances(...n){return this.targets.elementAffordances(...n)}elementIdentity(...n){return this.targets.elementIdentity(...n)}ensureCheckedBeforeTap(...n){return this.targets.ensureCheckedBeforeTap(...n)}refreshEnsureCheckedSelection(...n){return this.targets.refreshEnsureCheckedSelection(...n)}applyEnsureCheckedResult(...n){return this.targets.applyEnsureCheckedResult(...n)}resolveTapTargetElement(...n){return this.targets.resolveTapTargetElement(...n)}unverifiableDisplayPostState(...n){return this.displayRouter.unverifiableDisplayPostState(...n)}executeOnDisplay(...n){return this.displayRouter.executeOnDisplay(...n)}didCompleteDisplayGesture(...n){return this.displayRouter.didCompleteDisplayGesture(...n)}completedDisplayFailure(...n){return this.displayRouter.completedDisplayFailure(...n)}rethrowKeyboardOcclusion(...n){return this.displayRouter.rethrowKeyboardOcclusion(...n)}async execute(n,a={}){let s=$e(this.device,n,a.signal);if(s)return s;return Km(()=>this.executeWithReadScope(n,a))}executeWithReadScope(...n){return this.execution.executeWithReadScope(...n)}activateAccessibilityLinkPhase(...n){return this.semanticLinks.activateAccessibilityLinkPhase(...n)}activateSubtextPhase(...n){return this.semanticLinks.activateSubtextPhase(...n)}confirmFocusAfterTap(...n){return this.execution.confirmFocusAfterTap(...n)}assertLongPressWithinRequestBudget(...n){return this.execution.assertLongPressWithinRequestBudget(...n)}predictionToolArgs(...n){return this.execution.predictionToolArgs(...n)}readScopeFailureResult(...n){return this.execution.readScopeFailureResult(...n)}executeAndroidTap(...n){return this.gestureDispatcher.executeAndroidTap(...n)}executeScopedAndroidTap(...n){return this.gestureDispatcher.executeScopedAndroidTap(...n)}executeAndroidTapWithCoordinates(...n){return this.gestureDispatcher.executeAndroidTapWithCoordinates(...n)}tryDocumentsUiRowActivation(...n){return this.gestureDispatcher.tryDocumentsUiRowActivation(...n)}dispatchCoordinateTapOrAdbFallback(...n){return this.gestureDispatcher.dispatchCoordinateTapOrAdbFallback(...n)}resolveEnsureCheckedRetryTarget(...n){return this.gestureDispatcher.resolveEnsureCheckedRetryTarget(...n)}withRetryScreenSize(...n){return this.gestureDispatcher.withRetryScreenSize(...n)}refreshedRetrySelection(...n){return this.gestureDispatcher.refreshedRetrySelection(...n)}resolveRefreshedRetryTarget(...n){return this.gestureDispatcher.resolveRefreshedRetryTarget(...n)}retryTapIfNoChange(...n){return this.gestureDispatcher.retryTapIfNoChange(...n)}isScreenReaderNavigationEnabled(...n){return this.gestureDispatcher.isScreenReaderNavigationEnabled(...n)}reportTalkBackActivationWarning(...n){return this.gestureDispatcher.reportTalkBackActivationWarning(...n)}talkBackTargetContext(...n){return this.gestureDispatcher.talkBackTargetContext(...n)}executeAndroidTapWithAccessibility(...n){return this.gestureDispatcher.executeAndroidTapWithAccessibility(...n)}executeiOSTap(...n){return this.gestureDispatcher.executeiOSTap(...n)}executeiOSTapWithCoordinates(...n){return this.gestureDispatcher.executeiOSTapWithCoordinates(...n)}executeIOSTapWithVoiceOver(...n){return this.gestureDispatcher.executeIOSTapWithVoiceOver(...n)}readOptionalDisplayFence(...n){return this.gestureDispatcher.readOptionalDisplayFence(...n)}getLongPressDuration(...n){return this.gestureDispatcher.getLongPressDuration(...n)}executeAndroidLongPress(...n){return this.gestureDispatcher.executeAndroidLongPress(...n)}throwIfLongPressInterrupted(...n){return this.gestureDispatcher.throwIfLongPressInterrupted(...n)}semanticAndroidLongPressTargetError(...n){return this.gestureDispatcher.semanticAndroidLongPressTargetError(...n)}trySemanticAndroidLongPress(...n){return this.gestureDispatcher.trySemanticAndroidLongPress(...n)}detectLongPressMetadata(...n){return this.execution.detectLongPressMetadata(...n)}}
|
|
6
|
+
export{ST,yC,Hee,Rw,BF,Nm,qee,xV,wT,Vee,$F,bc};
|
|
7
|
+
|
|
8
|
+
//# debugId=44E25F102E98B43464756E2164756E21
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{f,Y,I,lt}from"./chunk-58wzr3mt.js";import{t,u}from"./chunk-rbpdk7m0.js";import{Bl,Tae}from"./chunk-qcxzr2my.js";var ke;function mae(r){ke=r}function Le(){return ke?.()}import{setTimeout as it}from"timers/promises";class SP{timer;offsetMs;leadHighWaterMs=0;wallReportOffsetMs;constructor(r){this.timer=r}now(){let r=this.timer.now(),n=this.timer.monotonicNow?.();if(n===void 0)return r;let o=r-n;if(this.offsetMs===void 0)this.offsetMs=o,this.leadHighWaterMs=o;else if(o>this.leadHighWaterMs){if(this.timer.monotonicIncludesHostSleep!==!0)this.offsetMs+=o-this.leadHighWaterMs;this.leadHighWaterMs=o}else if(o<this.leadHighWaterMs-1000)this.leadHighWaterMs=o;return Math.round(n+this.offsetMs)}toWall(r){let n=this.timer.now()-this.now();if(this.wallReportOffsetMs===void 0||Math.abs(n-this.wallReportOffsetMs)>50)this.wallReportOffsetMs=n;return r+this.wallReportOffsetMs}}var Fr=2147483647;function st(r){return r!=="darwin"&&r!=="linux"}var Oe="1.4";function hJ(r){if(r===void 0)return;if(r.split(".").slice(0,2).join(".")===Oe)return;return`Bun ${r} is not the release line (${Oe}.x) whose monotonic clock semantics were verified; whether performance.now() runs through host sleep may have changed, so host sleep and daemon stalls may be judged wrongly (#10962)`}class Af{monotonicIncludesHostSleep;constructor(r=process.platform){this.monotonicIncludesHostSleep=st(r)}async sleep(r){return it(r)}setTimeout(r,n){return global.setTimeout(r,n)}clearTimeout(r){global.clearTimeout(r)}setInterval(r,n){return global.setInterval(r,n)}clearInterval(r){global.clearInterval(r)}now(){return Date.now()}monotonicNow(){return performance.now()}}var i=new Af;var j=5000;function K(r,n=i,o=j){if(r.closed)return Promise.resolve();return new Promise((s,a)=>{let c=!1,d,y=n.setTimeout(()=>{b(()=>{r.destroy?.(),a(u(d??Error("Log stream close stalled"),`Log stream did not emit 'close' within ${o}ms \u2014 the file descriptor may still be held`))})},o),b=(p)=>{if(c)return;c=!0,r.off("error",v),r.off("close",S),n.clearTimeout(y),p()},v=(p)=>{d=p,queueMicrotask(()=>{if(!c)r.destroy?.(p)})},S=()=>b(()=>d?a(d):s());r.once("error",v),r.once("close",S),r.end()})}var{setTimeout:ct,clearTimeout:ut}=globalThis,dt=Date.now,_e={setTimeout:(r,n)=>ct(r,n),clearTimeout:(r)=>ut(r),now:()=>dt()};var Qa={DEBUG:0,INFO:1,WARN:2,ERROR:3,NONE:4};function pe(r){if(r===void 0)return null;let n=r.trim().toLowerCase();if(n.length===0)return null;switch(n){case"debug":return Qa.DEBUG;case"info":return Qa.INFO;case"warn":case"warning":return Qa.WARN;case"error":return Qa.ERROR;case"none":case"silent":return Qa.NONE;default:return null}}function me(r,n){return r.includes("--daemon-mode")?"daemon":`stdio-${n}`}var Me=new Set(["PASSWORD","TOKEN","SECRET","KEY","CREDENTIAL","AUTH","API_KEY","PRIVATE_KEY","ACCESS_TOKEN","REFRESH_TOKEN","CLIENT_SECRET","DATABASE_URL","DB_PASSWORD","GITHUB_TOKEN","NPM_TOKEN","AWS_SECRET_ACCESS_KEY"]),Ce=(r)=>{if(typeof r!=="object"||r===null)return String(r);let n=[];try{return JSON.stringify(r,function(o,s){if(typeof s==="object"&&s!==null){while(n.length>0&&n[n.length-1].holder!==this)n.pop();if(n.some((c)=>c.original===s))return"[circular]";let a={};for(let[c,d]of Object.entries(s))if(!Me.has(c.toUpperCase()))a[c]=d;return n.push({holder:a,original:s}),a}if(typeof s==="number"&&!Number.isFinite(s))return String(s);return s})}catch(o){return"[unserializable]"}},B=(r)=>r.replace(/[\r\n\t]/g," "),ge=(r,n,o,{message:s,args:a})=>{let c=new Date().toISOString(),d=B(s),y=a.length>0?` ${a.map((S)=>B(typeof S==="object"?Ce(S):String(S))).join(" ")}`:"",b=`${d}${y}`,v=b.length>1000?`${b.substring(0,1000)}... (truncated)`:b;if(r==="json")return JSON.stringify({timestamp:c,level:o.toLowerCase(),component:n,event:"log",message:v});return`${c} [${o}] ${v}`};var mn={hostLoad:void 0,gitMetadataClient:void 0,hostPortAvailabilityChecker:void 0,emulatorGrpcPortRegistry:void 0,deviceReadinessProxyDriverProvider:null,telemetryNoOpDefault:!1,auxSocketDir:void 0,bootAdmissionGatesDisabled:!1,processGenerationCaptureDisabled:void 0,logSinksDisabled:void 0};import oe from"fs";import Xe from"path";import{promises as H,readdirSync as Ne}from"fs";var Tf=H.readFile,fae=H.writeFile,kf=H.stat,fK=H.unlink;function BO(r,n){if(r===n)return 0;return r<n?-1:1}async function Qt(r){return(await H.readdir(r)).sort(BO)}async function Rr(r){return(await H.readdir(r,{withFileTypes:!0})).sort((n,o)=>BO(n.name,o.name))}function Li(r){return Ne(r).sort(BO)}function hU(r){return Ne(r,{withFileTypes:!0}).sort((n,o)=>BO(n.name,o.name))}import be from"fs";import k from"os";import h from"path";import{existsSync as pt}from"fs";import{homedir as mt}from"os";import fe from"path";var Ub=f.DAEMON_LAUNCH_CWD.name,hK="CORESIMULATOR_DEVICE_SET_PATH";function $O(r="/"){return Bl(()=>process.cwd(),()=>r)}function gU(r=mt()){if(r.length>0&&pt(r))return r;return"/"}function _d(r=$O(),n=process.env){let o=n[Ub]?.trim();return o&&fe.isAbsolute(o)?o:r}function Se(r,n=process.env){if(fe.isAbsolute(r))return r;return fe.resolve(_d(void 0,n),r)}function hae(r=process.env){let n=r[hK]?.trim();if(n)r[hK]=Se(n,r)}var Fe=448;function $p(r=process.env,n=k.homedir(),o=_d(void 0,r)){let s=lt(f.DATA_DIR,r);if(s&&s.length>0)return h.resolve(o,s);if(n&&n.length>0)return h.resolve(o,n,".auto-mobile");return h.join(k.tmpdir(),"auto-mobile")}function gK(r=process.env,n=k.homedir(),o=_d(void 0,r)){let s=lt(f.LOG_DIR,r);if(s&&s.length>0)return h.resolve(o,s);return h.join($p(r,n,o),fn.LOGS)}function gae(r=process.env){if(I(Y.NODE_ENV,r)!=="test")return;if([I(f.LOG_DIR,r),I(f.DATA_DIR,r)].some((o)=>o!==void 0&&o.trim().length>0))return;throw new t(`Unit test is about to write to the real AutoMobile logs directory (${gK(r)}). Unit tests must never touch the user's ~/.auto-mobile: point AUTOMOBILE_DATA_DIR (or AUTOMOBILE_LOG_DIR) at a temp directory the test removes.`)}function Qe(r){return h.join($p(),r)}function wP(r,n=k.userInfo().homedir,o=process.env){let s=lt(f.COORDINATION_DIR,o);if(s&&s.length>0){if(!h.isAbsolute(s))throw Error("AUTOMOBILE_COORDINATION_DIR must be an absolute path so all agents share one coordination directory.");return h.join(s,r)}if(n.length===0)throw Error("Unable to resolve a shared AutoMobile directory without a home directory. Set AUTOMOBILE_COORDINATION_DIR to a writable shared directory.");return h.join(h.resolve(n),".auto-mobile",r)}function yK(r,n=k.userInfo().homedir){if(n.length===0)throw Error("Unable to resolve a host-global AutoMobile directory without an OS account home directory.");return h.join(h.resolve(n),".auto-mobile",r)}function $u(r,n,o=process.env,s=k.userInfo().homedir){let a=lt(f.ADB_SERVER_COORDINATION_DIR,o);if(a&&a.length>0){if(!h.isAbsolute(a))throw Error("AUTOMOBILE_ADB_SERVER_COORDINATION_DIR must be an absolute path so every daemon on one ADB server shares it.");return h.join(a,r,n)}if(s.length===0)throw Error("Unable to resolve the ADB-server coordination directory without an OS account home directory. Set AUTOMOBILE_ADB_SERVER_COORDINATION_DIR to a writable shared directory.");return h.join(h.resolve(s),".auto-mobile","adb-servers",r,n)}function ec(r){if(be.mkdirSync(r,{recursive:!0,mode:Fe}),be.lstatSync(r).isSymbolicLink())throw Error(`Refusing to use symbolic-link directory: ${r}`);if(process.platform!=="win32")be.chmodSync(r,Fe);return r}function di(r,n=process.env){return ec(h.join($p(n),r))}function yae(r){return ec(wP(r))}function vK(r=process.env,n=k.homedir()){try{return ec(gK(r,n))}catch(o){if(o instanceof Error&&o.message.includes("symbolic-link directory"))throw u(o,"Refusing to use symbolic-link directory for AutoMobile logs");throw u(o,"Unable to initialize the AutoMobile log directory. Set AUTOMOBILE_LOG_DIR to a writable directory.")}}var fn={LOGS:"logs",TOOL_LOGS:"tool_logs",SCREENSHOTS:"screenshots",SNAPSHOTS:"snapshots",VIDEO_ARCHIVE:"video-archive",PERFORMANCE_TRACES:"performance-traces",NAVIGATION_SCREENSHOTS:"navigation-screenshots",VIEW_HIERARCHY:"view_hierarchy",OBSERVE_RESULTS:"observe_results",TOOL_OUTPUTS:"tool_outputs",WINDOW:"window",CACHE:"cache",STATE:"state"};import J from"path";var li=(r)=>{let n=U(r);return{delayForAttempt(o){return q(o),n}}},Wt=(r)=>{if(r.length===0)throw Error("sequenceBackoff requires at least one delay");let n=r.map(U);return{delayForAttempt(o){return q(o),n[Math.min(o-1,n.length-1)]}}},Q=(r)=>{let n=U(r.initialDelayMs),o=r.multiplier??2,s=r.maxDelayMs===void 0?Number.POSITIVE_INFINITY:U(r.maxDelayMs);if(!Number.isFinite(o)||o<1)throw Error(`exponentialBackoff multiplier must be >= 1, got ${o}`);return{delayForAttempt(a){return q(a),U(Math.min(n*o**(a-1),s))}}},No=(r)=>{if(typeof r==="number")return li(r);if(gt(r))return Wt(r);if(typeof r==="function")return{delayForAttempt(n){return q(n),U(r(n))}};return r},gt=(r)=>Array.isArray(r),RP=(r,n)=>No(r).delayForAttempt(n),q=(r)=>{if(!Number.isInteger(r)||r<1)throw Error(`Backoff attempt must be a positive integer, got ${r}`)},U=(r)=>{if(!Number.isFinite(r))throw Error(`Backoff delay must be finite, got ${r}`);return Math.max(0,Math.floor(r))};var ft=new Set(["EBUSY","EPERM"]),ye=4,bt=Wt([10,25,50]);async function yt(r,n){try{return await r.unlink(n),"removed"}catch(o){let s=o?.code;if(s==="ENOENT")return"removed";if(s!==void 0&&ft.has(s))return"transient";return r.logger?.debug(`log pruning could not remove ${n}: ${o}`,o),"failed"}}async function he(r,n){for(let o=1;o<=ye;o++){let s=await yt(r,n);if(s==="removed")return!0;if(s==="failed")return!1;if(o===ye)return r.logger?.debug(`log pruning gave up on ${n} after ${ye} transient unlink failures`),!1;await r.sleep(bt.delayForAttempt(o))}return!1}function vt(r){try{return process.kill(r,0),!0}catch(n){return n?.code!=="ESRCH"}}function Be(r,n){if(r===`${n}.log`)return!0;if(!r.startsWith(`${n}-`))return!1;let o=r.slice(n.length+1);return!/^launch-\d+\.log$/.test(o)}function St(r){let n=/^(?:stdio|server|daemon-launch)-(\d+)(?:-.*)?\.log$/.exec(r);return n?Number(n[1]):void 0}function He(r){return/^daemon-launch-\d+(?:-.*)?\.log$/.test(r)}function xt(r){return{unlink:r.unlink??fK,sleep:r.sleep??((n)=>i.sleep(n)),logger:r.logger}}async function Rt(r,n){await he(r,`${n}.owner`)}async function At(r,n,o,{now:s,abandonedMaxAgeMs:a}){await Tae(async()=>{let c=await kf(n);if(s-c.mtimeMs<=a)return;if(await he(r,n)&&He(o))await Rt(r,n)},()=>{return})}async function Ue(r){let n=r.now??Date.now(),o=r.isProcessAlive??vt,s=r.isDaemonRunning??(()=>!1),a=xt(r),c,d=()=>{if(c!==void 0)return c;let{daemonPidFiles:p,readDaemonOwner:x}=r;if(p&&x){try{let{pidFiles:R,uncertain:D}=p();c={owners:R.flatMap((A)=>{let g=x(A);return g===void 0?[]:[g]}),uncertain:D}}catch(R){r.logger?.debug(`daemon pidfile enumeration for log pruning failed: ${R}`,R),c={owners:[],uncertain:!0}}return c}return c={owners:[],uncertain:s()},c},y=(p)=>{let{owners:x,uncertain:R}=d(),D=J.resolve(r.dir,p),A=x.filter((g)=>typeof g.launchLogPath==="string"&&J.resolve(g.launchLogPath)===D);try{let g=r.readDaemonLaunchLogOwnerTombstone?.(D);if(g!==void 0&&!R)A.push(g)}catch(g){return r.logger?.debug(`launch-log ownership tombstone read failed: ${g}`,g),"unknown"}if(A.length>0)return A.some((g)=>Number.isInteger(g.pid)&&g.pid>0&&o(g.pid))?"alive":"dead";if(R)return"unknown";return x.some((g)=>g.launchLogPath===void 0)?"unknown":"dead"},b;try{b=await Qt(r.dir)}catch(p){r.logger?.debug(`log pruning skipped because the log directory could not be read: ${p}`,p);return}let v=b.filter((p)=>p.endsWith(".log")),S=v.filter((p)=>Be(p,r.ownPrefix)).sort();if(S.length>r.maxOwnFiles)for(let p of S.slice(0,S.length-r.maxOwnFiles))await he(a,J.join(r.dir,p));for(let p of v){if(!Pt(p,r.ownPrefix,o,y))continue;await At(a,J.join(r.dir,p),p,{now:n,abandonedMaxAgeMs:r.abandonedMaxAgeMs})}}function Pt(r,n,o,s){if(Be(r,n))return!1;let a=St(r);if(a===void 0)return!1;if(o(a))return!1;if(He(r)){if(s(r)!=="dead")return!1}return!0}import wt from"fs";var Ve={create(r,n){return wt.createWriteStream(r,n)}};function We(r){let n=r?.trim().toLowerCase();return n==="text"||n==="json"?n:null}function Ge(r){let n=r?.trim().toLowerCase();return n==="file"||n==="stderr"||n==="both"?n:null}function gE(r=process.env){return We(I(f.LOG_FORMAT,r))??"text"}function Ef(r=process.env){return Ge(I(f.LOG_SINK,r))??"file"}function Tt(r,n){if(n===void 0)return r;try{return`${r}: ${n instanceof Error?n.stack??n.message:String(n)}`}catch(o){return r}}function Zi(r,n){let o=Tt(r,n);if(gE()==="json"){process.stderr.write(`${JSON.stringify({timestamp:new Date().toISOString(),level:"error",component:"process",event:"log.emergency",message:o})}
|
|
2
|
+
import{h,Y,I,pt}from"./chunk-5wk1t46v.js";import{t,u}from"./chunk-2b39zyxc.js";import{Kl,oce}from"./chunk-j69g8b50.js";var ke;function Kae(r){ke=r}function Le(){return ke?.()}import{setTimeout as it}from"timers/promises";class UP{timer;offsetMs;leadHighWaterMs=0;wallReportOffsetMs;constructor(r){this.timer=r}now(){let r=this.timer.now(),n=this.timer.monotonicNow?.();if(n===void 0)return r;let o=r-n;if(this.offsetMs===void 0)this.offsetMs=o,this.leadHighWaterMs=o;else if(o>this.leadHighWaterMs){if(this.timer.monotonicIncludesHostSleep!==!0)this.offsetMs+=o-this.leadHighWaterMs;this.leadHighWaterMs=o}else if(o<this.leadHighWaterMs-1000)this.leadHighWaterMs=o;return Math.round(n+this.offsetMs)}toWall(r){let n=this.timer.now()-this.now();if(this.wallReportOffsetMs===void 0||Math.abs(n-this.wallReportOffsetMs)>50)this.wallReportOffsetMs=n;return r+this.wallReportOffsetMs}}var Ur=2147483647;function at(r){return r!=="darwin"&&r!=="linux"}var Oe="1.4";function L8(r){if(r===void 0)return;if(r.split(".").slice(0,2).join(".")===Oe)return;return`Bun ${r} is not the release line (${Oe}.x) whose monotonic clock semantics were verified; whether performance.now() runs through host sleep may have changed, so host sleep and daemon stalls may be judged wrongly (#10962)`}class $f{monotonicIncludesHostSleep;constructor(r=process.platform){this.monotonicIncludesHostSleep=at(r)}async sleep(r){return it(r)}setTimeout(r,n){return global.setTimeout(r,n)}clearTimeout(r){global.clearTimeout(r)}setInterval(r,n){return global.setInterval(r,n)}clearInterval(r){global.clearInterval(r)}now(){return Date.now()}monotonicNow(){return performance.now()}}var i=new $f;var j=5000;function K(r,n=i,o=j){if(r.closed)return Promise.resolve();return new Promise((s,a)=>{let c=!1,d,b=n.setTimeout(()=>{f(()=>{r.destroy?.(),a(u(d??Error("Log stream close stalled"),`Log stream did not emit 'close' within ${o}ms \u2014 the file descriptor may still be held`))})},o),f=(p)=>{if(c)return;c=!0,r.off("error",v),r.off("close",S),n.clearTimeout(b),p()},v=(p)=>{d=p,queueMicrotask(()=>{if(!c)r.destroy?.(p)})},S=()=>f(()=>d?a(d):s());r.once("error",v),r.once("close",S),r.end()})}var{setTimeout:lt,clearTimeout:ct}=globalThis,dt=Date.now,_e={setTimeout:(r,n)=>lt(r,n),clearTimeout:(r)=>ct(r),now:()=>dt()};var rc={DEBUG:0,INFO:1,WARN:2,ERROR:3,NONE:4};function pe(r){if(r===void 0)return null;let n=r.trim().toLowerCase();if(n.length===0)return null;switch(n){case"debug":return rc.DEBUG;case"info":return rc.INFO;case"warn":case"warning":return rc.WARN;case"error":return rc.ERROR;case"none":case"silent":return rc.NONE;default:return null}}function me(r,n){return r.includes("--daemon-mode")?"daemon":`stdio-${n}`}var Me=new Set(["PASSWORD","TOKEN","SECRET","KEY","CREDENTIAL","AUTH","API_KEY","PRIVATE_KEY","ACCESS_TOKEN","REFRESH_TOKEN","CLIENT_SECRET","DATABASE_URL","DB_PASSWORD","GITHUB_TOKEN","NPM_TOKEN","AWS_SECRET_ACCESS_KEY"]),Ce=(r)=>{if(typeof r!=="object"||r===null)return String(r);let n=[];try{return JSON.stringify(r,function(o,s){if(typeof s==="object"&&s!==null){while(n.length>0&&n[n.length-1].holder!==this)n.pop();if(n.some((c)=>c.original===s))return"[circular]";let a={};for(let[c,d]of Object.entries(s))if(!Me.has(c.toUpperCase()))a[c]=d;return n.push({holder:a,original:s}),a}if(typeof s==="number"&&!Number.isFinite(s))return String(s);return s})}catch(o){return"[unserializable]"}},B=(r)=>r.replace(/[\r\n\t]/g," "),ge=(r,n,o,{message:s,args:a})=>{let c=new Date().toISOString(),d=B(s),b=a.length>0?` ${a.map((S)=>B(typeof S==="object"?Ce(S):String(S))).join(" ")}`:"",f=`${d}${b}`,v=f.length>1000?`${f.substring(0,1000)}... (truncated)`:f;if(r==="json")return JSON.stringify({timestamp:c,level:o.toLowerCase(),component:n,event:"log",message:v});return`${c} [${o}] ${v}`};var yn={hostLoad:void 0,gitMetadataClient:void 0,hostPortAvailabilityChecker:void 0,emulatorGrpcPortRegistry:void 0,deviceReadinessProxyDriverProvider:null,telemetryNoOpDefault:!1,auxSocketDir:void 0,bootAdmissionGatesDisabled:!1,processGenerationCaptureDisabled:void 0,logSinksDisabled:void 0};import oe from"fs";import Qe from"path";import{promises as H,readdirSync as Ne}from"fs";var Uf=H.readFile,Gae=H.writeFile,Hf=H.stat,NK=H.unlink;function iM(r,n){if(r===n)return 0;return r<n?-1:1}async function er(r){return(await H.readdir(r)).sort(iM)}async function Tr(r){return(await H.readdir(r,{withFileTypes:!0})).sort((n,o)=>iM(n.name,o.name))}function $i(r){return Ne(r).sort(iM)}function DU(r){return Ne(r,{withFileTypes:!0}).sort((n,o)=>iM(n.name,o.name))}import be from"fs";import k from"os";import y from"path";import{existsSync as mt}from"fs";import{homedir as gt}from"os";import fe from"path";var tS=h.DAEMON_LAUNCH_CWD.name,FK="CORESIMULATOR_DEVICE_SET_PATH";function oM(r="/"){return Kl(()=>process.cwd(),()=>r)}function OU(r=gt()){if(r.length>0&&mt(r))return r;return"/"}function Ld(r=oM(),n=process.env){let o=n[tS]?.trim();return o&&fe.isAbsolute(o)?o:r}function Se(r,n=process.env){if(fe.isAbsolute(r))return r;return fe.resolve(Ld(void 0,n),r)}function Yae(r=process.env){let n=r[FK]?.trim();if(n)r[FK]=Se(n,r)}var Fe=448;function tm(r=process.env,n=k.homedir(),o=Ld(void 0,r)){let s=pt(h.DATA_DIR,r);if(s&&s.length>0)return y.resolve(o,s);if(n&&n.length>0)return y.resolve(o,n,".auto-mobile");return y.join(k.tmpdir(),"auto-mobile")}function LK(r=process.env,n=k.homedir(),o=Ld(void 0,r)){let s=pt(h.LOG_DIR,r);if(s&&s.length>0)return y.resolve(o,s);return y.join(tm(r,n,o),vn.LOGS)}function Jae(r=process.env){if(I(Y.NODE_ENV,r)!=="test")return;if([I(h.LOG_DIR,r),I(h.DATA_DIR,r)].some((o)=>o!==void 0&&o.trim().length>0))return;throw new t(`Unit test is about to write to the real AutoMobile logs directory (${LK(r)}). Unit tests must never touch the user's ~/.auto-mobile: point AUTOMOBILE_DATA_DIR (or AUTOMOBILE_LOG_DIR) at a temp directory the test removes.`)}function Je(r){return y.join(tm(),r)}function HP(r,n=k.userInfo().homedir,o=process.env){let s=pt(h.COORDINATION_DIR,o);if(s&&s.length>0){if(!y.isAbsolute(s))throw Error("AUTOMOBILE_COORDINATION_DIR must be an absolute path so all agents share one coordination directory.");return y.join(s,r)}if(n.length===0)throw Error("Unable to resolve a shared AutoMobile directory without a home directory. Set AUTOMOBILE_COORDINATION_DIR to a writable shared directory.");return y.join(y.resolve(n),".auto-mobile",r)}function BK(r,n=k.userInfo().homedir){if(n.length===0)throw Error("Unable to resolve a host-global AutoMobile directory without an OS account home directory.");return y.join(y.resolve(n),".auto-mobile",r)}function Xu(r,n,o=process.env,s=k.userInfo().homedir){let a=pt(h.ADB_SERVER_COORDINATION_DIR,o);if(a&&a.length>0){if(!y.isAbsolute(a))throw Error("AUTOMOBILE_ADB_SERVER_COORDINATION_DIR must be an absolute path so every daemon on one ADB server shares it.");return y.join(a,r,n)}if(s.length===0)throw Error("Unable to resolve the ADB-server coordination directory without an OS account home directory. Set AUTOMOBILE_ADB_SERVER_COORDINATION_DIR to a writable shared directory.");return y.join(y.resolve(s),".auto-mobile","adb-servers",r,n)}function nc(r){if(be.mkdirSync(r,{recursive:!0,mode:Fe}),be.lstatSync(r).isSymbolicLink())throw Error(`Refusing to use symbolic-link directory: ${r}`);if(process.platform!=="win32")be.chmodSync(r,Fe);return r}function hi(r,n=process.env){return nc(y.join(tm(n),r))}function Xae(r){return nc(HP(r))}function $K(r=process.env,n=k.homedir()){try{return nc(LK(r,n))}catch(o){if(o instanceof Error&&o.message.includes("symbolic-link directory"))throw u(o,"Refusing to use symbolic-link directory for AutoMobile logs");throw u(o,"Unable to initialize the AutoMobile log directory. Set AUTOMOBILE_LOG_DIR to a writable directory.")}}var vn={LOGS:"logs",TOOL_LOGS:"tool_logs",SCREENSHOTS:"screenshots",SNAPSHOTS:"snapshots",VIDEO_ARCHIVE:"video-archive",PERFORMANCE_TRACES:"performance-traces",NAVIGATION_SCREENSHOTS:"navigation-screenshots",VIEW_HIERARCHY:"view_hierarchy",OBSERVE_RESULTS:"observe_results",TOOL_OUTPUTS:"tool_outputs",WINDOW:"window",CACHE:"cache",STATE:"state"};import J from"path";var gi=(r)=>{let n=U(r);return{delayForAttempt(o){return q(o),n}}},zt=(r)=>{if(r.length===0)throw Error("sequenceBackoff requires at least one delay");let n=r.map(U);return{delayForAttempt(o){return q(o),n[Math.min(o-1,n.length-1)]}}},Q=(r)=>{let n=U(r.initialDelayMs),o=r.multiplier??2,s=r.maxDelayMs===void 0?Number.POSITIVE_INFINITY:U(r.maxDelayMs);if(!Number.isFinite(o)||o<1)throw Error(`exponentialBackoff multiplier must be >= 1, got ${o}`);return{delayForAttempt(a){return q(a),U(Math.min(n*o**(a-1),s))}}},Lo=(r)=>{if(typeof r==="number")return gi(r);if(ft(r))return zt(r);if(typeof r==="function")return{delayForAttempt(n){return q(n),U(r(n))}};return r},ft=(r)=>Array.isArray(r),qP=(r,n)=>Lo(r).delayForAttempt(n),q=(r)=>{if(!Number.isInteger(r)||r<1)throw Error(`Backoff attempt must be a positive integer, got ${r}`)},U=(r)=>{if(!Number.isFinite(r))throw Error(`Backoff delay must be finite, got ${r}`);return Math.max(0,Math.floor(r))};var bt=new Set(["EBUSY","EPERM"]),ye=4,yt=zt([10,25,50]);async function ht(r,n){try{return await r.unlink(n),"removed"}catch(o){let s=o?.code;if(s==="ENOENT")return"removed";if(s!==void 0&&bt.has(s))return"transient";return r.logger?.debug(`log pruning could not remove ${n}: ${o}`,o),"failed"}}async function he(r,n){for(let o=1;o<=ye;o++){let s=await ht(r,n);if(s==="removed")return!0;if(s==="failed")return!1;if(o===ye)return r.logger?.debug(`log pruning gave up on ${n} after ${ye} transient unlink failures`),!1;await r.sleep(yt.delayForAttempt(o))}return!1}function vt(r){try{return process.kill(r,0),!0}catch(n){return n?.code!=="ESRCH"}}function Be(r,n){if(r===`${n}.log`)return!0;if(!r.startsWith(`${n}-`))return!1;let o=r.slice(n.length+1);return!/^launch-\d+\.log$/.test(o)}function St(r){let n=/^(?:stdio|server|daemon-launch)-(\d+)(?:-.*)?\.log$/.exec(r);return n?Number(n[1]):void 0}function He(r){return/^daemon-launch-\d+(?:-.*)?\.log$/.test(r)}function xt(r){return{unlink:r.unlink??NK,sleep:r.sleep??((n)=>i.sleep(n)),logger:r.logger}}async function Rt(r,n){await he(r,`${n}.owner`)}async function At(r,n,o,{now:s,abandonedMaxAgeMs:a}){await oce(async()=>{let c=await Hf(n);if(s-c.mtimeMs<=a)return;if(await he(r,n)&&He(o))await Rt(r,n)},()=>{return})}async function Ue(r){let n=r.now??Date.now(),o=r.isProcessAlive??vt,s=r.isDaemonRunning??(()=>!1),a=xt(r),c,d=()=>{if(c!==void 0)return c;let{daemonPidFiles:p,readDaemonOwner:x}=r;if(p&&x){try{let{pidFiles:R,uncertain:D}=p();c={owners:R.flatMap((A)=>{let g=x(A);return g===void 0?[]:[g]}),uncertain:D}}catch(R){r.logger?.debug(`daemon pidfile enumeration for log pruning failed: ${R}`,R),c={owners:[],uncertain:!0}}return c}return c={owners:[],uncertain:s()},c},b=(p)=>{let{owners:x,uncertain:R}=d(),D=J.resolve(r.dir,p),A=x.filter((g)=>typeof g.launchLogPath==="string"&&J.resolve(g.launchLogPath)===D);try{let g=r.readDaemonLaunchLogOwnerTombstone?.(D);if(g!==void 0&&!R)A.push(g)}catch(g){return r.logger?.debug(`launch-log ownership tombstone read failed: ${g}`,g),"unknown"}if(A.length>0)return A.some((g)=>Number.isInteger(g.pid)&&g.pid>0&&o(g.pid))?"alive":"dead";if(R)return"unknown";return x.some((g)=>g.launchLogPath===void 0)?"unknown":"dead"},f;try{f=await er(r.dir)}catch(p){r.logger?.debug(`log pruning skipped because the log directory could not be read: ${p}`,p);return}let v=f.filter((p)=>p.endsWith(".log")),S=v.filter((p)=>Be(p,r.ownPrefix)).sort();if(S.length>r.maxOwnFiles)for(let p of S.slice(0,S.length-r.maxOwnFiles))await he(a,J.join(r.dir,p));for(let p of v){if(!Pt(p,r.ownPrefix,o,b))continue;await At(a,J.join(r.dir,p),p,{now:n,abandonedMaxAgeMs:r.abandonedMaxAgeMs})}}function Pt(r,n,o,s){if(Be(r,n))return!1;let a=St(r);if(a===void 0)return!1;if(o(a))return!1;if(He(r)){if(s(r)!=="dead")return!1}return!0}import wt from"fs";var Ve={create(r,n){return wt.createWriteStream(r,n)}};function We(r){let n=r?.trim().toLowerCase();return n==="text"||n==="json"?n:null}function Ge(r){let n=r?.trim().toLowerCase();return n==="file"||n==="stderr"||n==="both"?n:null}function DE(r=process.env){return We(I(h.LOG_FORMAT,r))??"text"}function qf(r=process.env){return Ge(I(h.LOG_SINK,r))??"file"}function Tt(r,n){if(n===void 0)return r;try{return`${r}: ${n instanceof Error?n.stack??n.message:String(n)}`}catch(o){return r}}function eo(r,n){let o=Tt(r,n);if(DE()==="json"){process.stderr.write(`${JSON.stringify({timestamp:new Date().toISOString(),level:"error",component:"process",event:"log.emergency",message:o})}
|
|
3
3
|
`);return}process.stderr.write(`${o}
|
|
4
|
-
`)}class PP extends t{}function Fl(r){if((r&32)!==0)return"managed";if((r&16384)!==0||(r&1)!==0)return"primary";if((r&1024)!==0)return"secondary";return"unknown"}var bK=["RUNNING_MODERATE","RUNNING_LOW","RUNNING_CRITICAL","UI_HIDDEN","BACKGROUND","MODERATE","COMPLETE"];var SK={wallpaperRendering:"Home and Lock Screen wallpaper rendering; excludes widgets and Live Activities.",widgets:"Widget refresh, including app widgets; excludes wallpaper and Live Activities.",liveActivities:"Live Activities and Dynamic Island updates; excludes wallpaper and widgets.",healthServices:"HealthKit data and Health app background work. Health integrations become unavailable.",homeServices:"HomeKit accessories and automations. Home integrations become unavailable.",fitnessServices:"Apple Fitness, coaching, activity awards, and activity sharing.",familyServices:"Family Sharing, family approvals, and parental controls. Changes restriction behavior.",screenTime:"Screen Time limits and usage tracking. Changes restriction behavior.",newsServices:"Apple News background content.",weatherServices:"Apple Weather background forecasts.",tipsServices:"Apple Tips background content.",gameServices:"Game Center and saved-game synchronization; excludes controller input.",mapsSync:"Maps favorites, history, background updates, and suggested destinations; excludes MapKit rendering and location services.",advertising:"Promoted Apple content; excludes advertising privacy preferences and app integrity services.",diagnosticReporting:"Diagnostic collectors, feedback, location analytics, and call-quality reporting; reduces diagnostic evidence, not call transport.",siriAndAppIntents:"iOS Simulator Siri requests, Shortcuts actions, and App Intents; excludes speech services and proactive suggestions.",speechServices:"iOS Simulator speech recognition, dictation, and Siri speech synthesis; excludes Siri requests and App Intents orchestration.",mediaTranscoding:"iOS Simulator Photos image and video conversion; media imports and photo-picker conversions may fail.",photoAnalysis:"Background Photos analysis; may reduce photo search and recognition. Preserves library access, cloud transfers, and shared media-analysis infrastructure.",assistantSuggestions:"Siri inference, knowledge, and proactive suggestions; preserves speech, system voices, and shared language/model infrastructure.",appleIntelligence:"Apple Intelligence orchestration and generative experiences; system writing tools and intelligence integrations may become unavailable. Preserves shared model and speech services.",searchIndexing:"Spotlight and Settings search, including app-provided system indexes; excludes an app's own search service.",appStoreServices:"App Store installation/update services; excludes push and StoreKit payment services.",appleMediaSync:"Apple Music and subscribed/purchased media background services; excludes generic audio/video playback and StoreKit payments.",mailServices:"Apple Mail background services. Mail-based sign-in email workflows may be unavailable.",calendarServices:"Local Calendar database access; excludes server-side calendar integrations in apps.",reminderServices:"Apple Reminders database and background work; excludes reminders maintained by other apps.",personalDataSync:"Exchange, CalDAV, and CardDAV synchronization; preserves local Contacts database access.",safariSync:"Safari bookmark/history synchronization; preserves associated domains, shared credentials, browsing protections, and WebKit.",icloudSettingsSync:"iCloud system-settings synchronization and storage-plan recommendations; preserves accounts, credentials, CloudKit data, Drive, and Photos transfers.",messagingMaintenance:"Apple Messages history cleanup, attachment transfer, and FaceTime message storage; preserves identity, message database XPC helpers, and system calling services.",watchConnectivity:"Paired Watch and companion-device communication.",carPlay:"CarPlay vehicle connectivity.",tvRemote:"Apple TV discovery and remote control.",findMy:"Find My device-location services; excludes general location APIs.",continuity:"Nearby-device Continuity discovery; cross-device workflows may stop working. Preserves system share sheets.",walletServices:"Wallet, Apple Pay, digital identity, and merchant services. Payment sheets, including dependent StoreKit workflows, may fail.",businessServices:"Apple business messaging services; excludes ordinary app messaging.",backgroundSync:"General OS background app scheduling. Control is unsupported to preserve application behavior.",animations:"Android system animation scales: disabled sets all three to zero; enabled sets them to one. Excludes app-owned animation.",screensavers:"Android dream/screensaver activation; excludes wallpaper and widgets.",backup:"Android Backup Manager scheduling for the current user; disables backup and restore test behavior.",mailApp:"Android optional mail apps, including Gmail. Removes mail intent handlers; preserves other apps' messaging.",calendarApp:"Android Calendar app availability; preserves CalendarProvider.",contactsApp:"Android Contacts app availability; preserves ContactsProvider.",mapsApp:"Android Google Maps app; external navigation intents become unavailable.",videoApp:"Android YouTube app; native video links become unavailable.",musicApp:"Android YouTube Music app; preserves shared audio playback.",photosApp:"Android Google Photos app; changes cloud photo sources and choosers. Preserves MediaProvider and DocumentsUI.",assistantApp:"Android Google Search/Assistant app, including voice and home-search integrations.",digitalWellbeing:"Android Digital Wellbeing usage tracking, focus, and app limits.",printing:"Android print spooler and print recommendations; printing becomes unavailable.",accessibilityApps:"Optional Android accessibility apps. Active accessibility services are protected.",textToSpeech:"Android Google speech synthesis; speech-dependent functionality becomes unavailable.",storeApp:"Android Play Store app; installation, updates, billing and licensing may fail.",healthConnect:"Android Health Connect controller and backup app; health integrations become unavailable.",adServices:"Android AdServices API package; advertising/privacy APIs may fail. Does not remove mainline/APEX infrastructure.",onDevicePersonalization:"Android on-device personalization service package; dependent APIs may fail.",wallpaperApps:"Android wallpaper picker and optional live-wallpaper apps; changes wallpaper selection. Does not disable the shared wallpaper framework or widgets.",dialerApp:"Optional Android dialer apps. Default role holders remain protected.",messagesApp:"Optional Android SMS/Messages apps. Default role holders remain protected; excludes other apps' messaging.",googleServicesFramework:"Android Google Services Framework; aggressive control that can break Google account and push integrations.",googlePlayServices:"Android Google Play services; aggressive control that breaks dependent push, authentication, location and other integrations. Keep enabled for workflows that depend on those services.",icloudSync:"Broad iCloud/account synchronization. Control is unsupported; use the narrower icloudSettingsSync setting."};var yE="value-redacted";function ht(r){return r===!0||r==="true"}function xd(r){return r===!1||r==="false"}var vae=["first","random","unique"];var Fo=Symbol("displayInventoryOutcome");var Hb=[["closed","cover"],["opened","inner"],["rear_display","inner"]];function Cd(r){return r.role!=="overlay"&&r.role!=="virtual"}function Up(r){return r?.panels?.length?r.panels:[{key:"0",role:"unknown",sizePx:{width:0,height:0}}]}function AP(r,n,o,s){let{hasPostures:a,pinned:c}=s,d=o.map(({key:p,role:x})=>x?`${p} (${x})`:p).join(", "),y=Hb.find(([,p])=>p===n)?.[0],b=a&&n!=="cluster"?`; to make this panel available, change the device posture with ${y?`setPosture {posture: "${y}"}`:"setPosture using a supported posture"}`:"";return`Display "${r}" (${n}) ${n==="cluster"?"is not currently connected":"is not connected in the current posture"}. Connected panels: ${d}. Target a connected panel, omit display, or use display: "active"${b}.${c?" Clear the pin with setActiveDevice {display: null} (include deviceId and sessionUuid), or select another display explicitly.":""}`}function yU(r){if(typeof r!=="object"||r===null)return;let n=r;if(typeof n.width!=="number"||typeof n.height!=="number"||!Number.isInteger(n.width)||n.width<=0||!Number.isInteger(n.height)||n.height<=0)return;return{width:n.width,height:n.height}}function wK(r,n){if(!n)return;let o=r?.filter((s)=>s.sizePx.width===n.width&&s.sizePx.height===n.height);return o?.length===1?o[0].key:void 0}var ze=["tv","watch","automotive","xr-headset","xr-glasses"],X={tv:{systemImageTags:["android-tv","google-tv","google-tv-ps16k"],profileIdPattern:/^tv_/i,defaultProfileId:"tv_1080p"},watch:{systemImageTags:["android-wear-signed","android-wear","android-wear-cn"],profileIdPattern:/^wear(?:os)?_/i,defaultProfileId:"wearos_small_round"},automotive:{systemImageTags:["android-automotive-playstore","android-automotive"],profileIdPattern:/^automotive_/i,defaultProfileId:"automotive_1024p_landscape"},"xr-headset":{systemImageTags:["google-xr","android-xr-v3-playstore","android-xr-preview-playstore"],profileIdPattern:/^xr_headset/i,defaultProfileId:"xr_headset_device"},"xr-glasses":{systemImageTags:["ai-glasses"],profileIdPattern:/^(?:xr_glasses|ai_glasses)_/i,defaultProfileId:"ai_glasses_device"}},$e=ze.map((r)=>({formFactor:r,...X[r]}));function bae(r){return ze.includes(r)}function Dd(r){return X[r].systemImageTags}function Ll(r,n){if(r==="watch"&&n===!1)return"wearos_square";return X[r].defaultProfileId}function Sae(r){let n=r?.trim()??"";if(!X.watch.profileIdPattern.test(n))return;if(/round/i.test(n))return!0;return/square|rect/i.test(n)?!1:void 0}function It(r){let n=r.systemImageTag?.trim().toLowerCase(),o=r.profileId?.trim(),s=$e.find((a)=>n?a.systemImageTags.includes(n):!1);if(s)return s.formFactor;return $e.find((a)=>o?a.profileIdPattern.test(o):!1)?.formFactor}function If(r){let n=/pixel[_ ]tablet|nexus (?:9|10)/i.test(r.profileId??"")?"tablet":void 0;return qb({...r,hint:n,deviceType:r.profileId})}function ve(r){return typeof r==="number"&&Number.isFinite(r)&&r>0}function qb(r){let n=It({systemImageTag:r.systemImageTag,profileId:r.deviceType});if(n)return n;let o=`${r.deviceType??""} ${r.hint??""}`;if(/fold|flip/i.test(o))return"foldable";let s=r.hint?.trim().toLowerCase();if(s!==void 0&&Dt.has(s))return s;return Et(r)}var Dt=new Set(["phone","tablet","tv","watch","automotive","xr-headset","xr-glasses"]);function Et(r){let{width:n,height:o,density:s}=r;if(!ve(n)||!ve(o)||!ve(s))return"unknown";return Math.hypot(n,o)/s>=7?"tablet":"phone"}var Bi={watchos:"watchOS",tvos:"tvOS",visionos:"visionOS"},Od={android:"Android",ios:"iOS",...Bi};function cr(r){return r==="android"||r==="ios"}function Hp(r,n){return n===void 0?cr(r):r===n}function te(r,n){if(cr(r))return r;throw kt(n,r)}function gJ(r,n){return r==="either"?r:te(r,n)}function kt(r,n){return new t(`${r} is not supported on ${Bi[n]} yet. Target an Android or iOS device instead.`)}var UO=1,HO=1798000,qO=1,VO=1000;function vE(r){return r!==void 0&&(r.toolType==="eraser"||r.pressure!==void 0&&r.pressure!==1||r.tilt!==void 0||r.orientation!==void 0||(r.buttons?.length??0)>0)}function wae(r){return(r??[]).reduce((n,o)=>n|(o==="primary"?32:64),0)}function yJ(r){return r==="window_read_skipped"||r==="window_list_skipped"}function WO(r){return r.ctrlProxyIncomplete===!0&&!yJ(r.ctrlProxyIncompleteReason)}function we(r){return r.$??r}function Ra(r){let n=r.node;if(Array.isArray(n))return n;return n&&typeof n==="object"?[n]:[]}function qt(r){return r.bounds??we(r).bounds}function je(r){return r!==null&&typeof r==="object"&&!Array.isArray(r)}function Rae(r){return je(r)&&"hierarchy"in r&&je(r.hierarchy)}function Uu(r){if(!r)return null;let{nativeScale:n,pixelWidth:o,pixelHeight:s}=r;if(typeof n!=="number"||!Number.isFinite(n)||n<=0||typeof o!=="number"||!Number.isFinite(o)||o<=0||typeof s!=="number"||!Number.isFinite(s)||s<=0)return null;return{nativeScale:n,pixelWidth:o,pixelHeight:s}}function vU(r){return Uu(r)??{}}var vJ="immediate";var Lt="device_service_disabled";class zO extends t{code=Lt;retryable=!1;tool;resource;labels;disabledLabels;unavailable;howToEnable;deviceId;constructor(r){let n=`Call setDeviceResources with {resources:{${r.resource}:"enabled"}} (enable this default-disabled tool with setToolEnabled or --enable-tool setDeviceResources), or provision/start the simulator without {resources:{${r.resource}:"disabled"}}.`;super(`${r.tool} requires resource ${r.resource} (${r.labels.join(", ")}); disabled labels: ${r.disabledLabels.join(", ")}. Unavailable: ${r.unavailable}. ${n}`);this.name="DeviceServiceDisabledError",this.tool=r.tool,this.resource=r.resource,this.labels=[...r.labels],this.disabledLabels=[...r.disabledLabels],this.unavailable=r.unavailable,this.howToEnable=n,this.deviceId=r.deviceId}toPayload(){return{code:this.code,tool:this.tool,resource:this.resource,labels:this.labels,disabledLabels:this.disabledLabels,unavailable:this.unavailable,howToEnable:this.howToEnable,retryable:this.retryable,deviceId:this.deviceId}}}var Ot="unsafe_device_resource_combination";class qp extends t{code=Ot;retryable=!1;hazards;howToProceed;constructor(r){super(`Unsafe iOS device resource combination: ${r.map((o)=>`${o.id} (${o.resources.join(", ")}): ${o.reason}`).join("; ")}. Drop or re-enable at least one of the listed resources in each unsafe combination before retrying.`);this.name="UnsafeDeviceResourceCombinationError",this.hazards=r.map((o)=>({...o,resources:[...o.resources],appliesTo:[...o.appliesTo]})),this.howToProceed="Drop or re-enable at least one of the listed resources in each unsafe combination before retrying."}toPayload(){return{code:this.code,retryable:this.retryable,hazards:this.hazards,howToProceed:this.howToProceed}}}function _t(r){return typeof r==="object"&&r!==null&&"unref"in r&&typeof r.unref==="function"}function Mt(r){let{timer:n,timeoutMs:o,deadline:s,unref:a,label:c,timeoutError:d,onTimeout:y}=r;if(s===void 0&&o===void 0)return;let b=o??0,v=()=>{};return{promise:new Promise((p,x)=>{let R=(g)=>{x(d?.()??new t(g)),y?.()},D=(g)=>{if(a&&_t(g))g.unref()};if(s){v=s.whenExpired(n,()=>R(`${c} timed out`),D);return}let A=n.setTimeout(()=>R(`${c} timed out after ${b}ms`),b);D(A),v=()=>n.clearTimeout(A)}),cancel:()=>v()}}function Ke(r,n,o){let s=r.reason;if(o&&(s===void 0||s instanceof DOMException&&s.name==="AbortError"))return new t(`${n} cancelled`);return s===void 0?new DOMException("The operation was aborted.","AbortError"):s}function Ct(r){return Array.isArray(r)}function Je(r){return Ct(r)?r:[r]}function Nt(r){return typeof r==="function"?[r()]:Je(r)}function qe(r){for(let n of r)n.then(void 0,()=>{})}async function l(r,{timer:n,timeoutMs:o,deadline:s,unref:a=!1,signal:c,label:d,relabelDefaultAbort:y=!1,timeoutError:b,onTimeout:v}){if(typeof r!=="function")qe(Je(r));if(c?.aborted)throw Ke(c,d,y);let S,p=c?new Promise((R,D)=>{let A=()=>D(Ke(c,d,y));if(c.addEventListener("abort",A,{once:!0}),S=()=>c.removeEventListener("abort",A),c.aborted)A()}):void 0,x=Mt({timer:n,timeoutMs:o,deadline:s,unref:a,label:d,timeoutError:b,onTimeout:v});try{let R=Nt(r);return qe(R),await Promise.race([...R,...p?[p]:[],...x?[x.promise]:[]])}finally{x?.cancel(),S?.()}}import{readFileSync as Ft}from"fs";function xe(r,n,o){try{r?.(n,o)}catch(s){}}var Bt=50;function Ht(r,n){let o=`${r} (`,s=n.lastIndexOf(")");if(!n.startsWith(o)||s<o.length)return;let a=n.slice(s+1);if(!/^\s/.test(a))return;let c=a.trim().split(/\s+/),[d,...y]=c;if(c.length<Bt||d?.length!==1||y.some((b)=>!/^-?\d+$/.test(b)))return;return d}function Ut(r){return r?.code==="ESRCH"}function at(r,n={}){if(!Number.isInteger(r)||r<=0)return!1;let o=n.signalProcess??((c)=>{process.kill(c,0)});try{o(r)}catch(c){return xe(n.debugLog,`src/daemon/daemonFiles.ts liveness check failed: ${c}`,c),!Ut(c)}if((n.platform??process.platform)!=="linux")return!0;let s;try{s=(n.readProcStat??((d)=>Ft(`/proc/${d}/stat`,"utf-8")))(r)}catch(c){return xe(n.debugLog,`src/daemon/daemonFiles.ts procfs liveness check failed: ${c}`,c),!0}let a=Ht(r,s);if(a===void 0)return xe(n.debugLog,`src/daemon/daemonFiles.ts could not parse /proc/${r}/stat`,s),!0;return a!=="Z"&&a!=="X"}class Z{policy;pending=new Set;timeout;episode;observing=!0;constructor(r){this.policy=r}get stalled(){return this.episode!==void 0}divert(){if(this.episode)this.episode.diverted++}track(r){return new Promise((n,o)=>{let s={issuedAt:this.policy.timer.now(),settle:n,fail:o};this.pending.add(s),this.armOldest();try{r((a)=>this.complete(s,a))}catch(a){this.complete(s,a)}})}suspend(){this.observing=!1,this.clearTimeout()}retire(r){this.suspend();for(let n of this.pending)if(r)n.fail(r);else n.settle(!1);this.pending.clear(),this.episode=void 0}complete(r,n){if(!this.pending.delete(r))return;if(n){if(this.episode)this.episode.failed++;r.fail(n)}else r.settle(!0);if(!this.observing)return;if(this.episode&&!n&&!this.oldestExpired())this.resume();if(this.pending.size===0&&!this.episode)this.clearTimeout();this.armOldest()}oldest(){return this.pending.values().next().value}oldestExpired(){let r=this.oldest();return r!==void 0&&this.policy.timer.now()-r.issuedAt>=this.policy.timeoutMs}resume(){let r=this.episode;if(this.episode=void 0,this.clearTimeout(),r)this.policy.resumed(this.policy.timer.now()-r.detectedAt,r.diverted)}armOldest(){let r=this.oldest();if(!this.observing||this.timeout!==void 0||this.episode||!r)return;this.arm(Math.max(0,this.policy.timeoutMs-(this.policy.timer.now()-r.issuedAt)))}arm(r){if(this.timeout=this.policy.timer.setTimeout(()=>{this.timeout=void 0,this.onDeadline()},r),typeof this.timeout==="object"&&typeof this.timeout.unref==="function")this.timeout.unref()}onDeadline(){if(this.episode){let r=this.policy.timer.now()-this.episode.detectedAt,n=this.pending.size+this.episode.failed;this.retire(),this.policy.abandoned?.(r,n);return}if(!this.oldestExpired()){this.armOldest();return}this.episode={detectedAt:this.policy.timer.now(),diverted:0,failed:0},this.policy.stalled(this.pending.size);for(let r of this.pending)r.settle(!1);if(this.policy.abandonMs!==void 0)this.arm(this.policy.abandonMs)}clearTimeout(){if(this.timeout!==void 0)this.policy.timer.clearTimeout(this.timeout);this.timeout=void 0}}function bJ(){return N==="json"}var V=pe(I(f.LOG_LEVEL))??Qa.INFO,N=gE(),_=Ef(),Re=!1,z=Promise.resolve(),W=(r)=>{z=z.then(()=>r)},M=_==="stderr"?void 0:vK(),F=me(process.argv,process.pid),T=M?Xe.join(M,`${F}.log`):void 0,Vt=(r,n)=>{r.on("error",(o)=>{try{Zi(`Log stream error on ${n}`,o)}catch(s){}if(m===r)m=void 0;w.get(r)?.retire(o),C(r),queueMicrotask(()=>r.destroy?.())})},L=new Map,C=(r,n=i)=>{if(r.closed)return;let o=L.get(r);if(o)o.timer.clearTimeout(o.timeoutHandle),r.off("close",o.onClose);let s=o&&n===i?o.timer:n,a=()=>{let d=L.get(r);if(d?.onClose===a)d.timer.clearTimeout(d.timeoutHandle),r.off("close",a),L.delete(r)},c=s.setTimeout(a,j);L.set(r,{timer:s,timeoutHandle:c,onClose:a}),r.once("close",a)},ue=(r)=>{for(let[n,o]of L)if(n.closed)o.onClose();if(L.size>0)return;try{let n=Ve.create(r,{flags:"a"});return Vt(n,r),n}catch(n){Zi(`Failed to open log stream ${r}`,n);return}},m=T?ue(T):void 0;function Te(){if(!M||!T)return;return{dir:M,path:T}}var Ye=20000,ie=5000,Gt=30000,Ie=_e,w=new WeakMap,se=0,P;var $t=10485760,zt=10,jt=86400000,ae;function SJ(r){if(ae=r,re&&!re.registeredSweepStarted)et(re)}function de(){if(!ae)throw Error("Log retention namespace source is not registered");return ae}var Kt=()=>{try{let r=de(),{pidFiles:n,uncertain:o}=r.listDaemonPidFilesSync();if(o)return!0;return n.some((s)=>{let a=r.readPidFileDataSync(s);return a?at(a.pid):!1})}catch(r){return e.debug(`daemon liveness probe for log pruning failed: ${r}`,r),!0}},Jt=()=>{try{return de().listDaemonPidFilesSync()}catch(r){return e.debug(`daemon pidfile enumeration for log pruning failed: ${r}`,r),{pidFiles:[],uncertain:!0}}},Yt=(r)=>de().readDaemonOwnerForRetentionSync(r),Xt=(r)=>de().readDaemonLaunchLogOwnerTombstoneSync(r),Zt={daemonPidFiles:Jt,readDaemonOwner:Yt,readDaemonLaunchLogOwnerTombstone:Xt,isDaemonRunning:Kt},Ze=()=>{if(!M)return Promise.resolve();return Ue({dir:M,ownPrefix:F,maxOwnFiles:zt,abandonedMaxAgeMs:jt,...Zt})};function et(r){if(r.timeout!==void 0)return;r.timeout=r.timer.setTimeout(()=>{r.timeout=void 0,r.pending=r.pending.then(async()=>{if(r!==re||r.registeredSweepStarted)return;let n=ae!==void 0;if(r.fallbackStarted&&!n)return;r.fallbackStarted=!0,r.registeredSweepStarted=n;try{await r.prune()}catch(o){e.warn("Startup log pruning failed",o)}})},0)}function er(r,n){let o={timer:r,prune:n,pending:Promise.resolve(),fallbackStarted:!1,registeredSweepStarted:!1};return et(o),o}var re=M?er(i,Ze):void 0,tr=async(r)=>{w.get(r)?.suspend();try{return await K(r),!0}catch(n){let o=r.closed===!0;if(!o)C(r);return await E("Failed to close log stream before rotation",n),o}},rr=async(r)=>{let n=m;if(m=void 0,n){if(!await tr(n)){ne=Number.POSITIVE_INFINITY;return}}let o=new Date().toISOString().replace(/:/g,"-"),s=Xe.join(r.dir,`${F}-${o}.log`);if(oe.existsSync(r.path))await oe.promises.rename(r.path,s);m=ue(r.path),await Ze()},O,nr=async(r)=>{if(!oe.existsSync(r.path))return;if((await kf(r.path)).size>=$t)await rr(r)},or=(r)=>{if(!O)O=nr(r).finally(()=>{O=void 0});return O},De=async(r,n)=>{if(L.size===0&&(m?.destroyed||!m?.writable))m=ue(r.path);await E("Log rotation failed",n)},ne=Number.POSITIVE_INFINITY,ir=32768,sr=async(r)=>{if(ne+=r,ne<ir)return!0;ne=0;let n=Te();if(!n||!m)return!0;try{return await nt(or(n))}catch(o){return await De(n,o),!0}};var le=(r)=>new Promise((n,o)=>{process.stderr.write(`${r}
|
|
4
|
+
`)}class VP extends t{}function zl(r){if((r&32)!==0)return"managed";if((r&16384)!==0||(r&1)!==0)return"primary";if((r&1024)!==0)return"secondary";return"unknown"}var UK=["RUNNING_MODERATE","RUNNING_LOW","RUNNING_CRITICAL","UI_HIDDEN","BACKGROUND","MODERATE","COMPLETE"];var HK={wallpaperRendering:"Home and Lock Screen wallpaper rendering; excludes widgets and Live Activities.",widgets:"Widget refresh, including app widgets; excludes wallpaper and Live Activities.",liveActivities:"Live Activities and Dynamic Island updates; excludes wallpaper and widgets.",healthServices:"HealthKit data and Health app background work. Health integrations become unavailable.",homeServices:"HomeKit accessories and automations. Home integrations become unavailable.",fitnessServices:"Apple Fitness, coaching, activity awards, and activity sharing.",familyServices:"Family Sharing, family approvals, and parental controls. Changes restriction behavior.",screenTime:"Screen Time limits and usage tracking. Changes restriction behavior.",newsServices:"Apple News background content.",weatherServices:"Apple Weather background forecasts.",tipsServices:"Apple Tips background content.",gameServices:"Game Center and saved-game synchronization; excludes controller input.",mapsSync:"Maps favorites, history, background updates, and suggested destinations; excludes MapKit rendering and location services.",advertising:"Promoted Apple content; excludes advertising privacy preferences and app integrity services.",diagnosticReporting:"Diagnostic collectors, feedback, location analytics, and call-quality reporting; reduces diagnostic evidence, not call transport.",siriAndAppIntents:"iOS Simulator Siri requests, Shortcuts actions, and App Intents; excludes speech services and proactive suggestions.",speechServices:"iOS Simulator speech recognition, dictation, and Siri speech synthesis; excludes Siri requests and App Intents orchestration.",mediaTranscoding:"iOS Simulator Photos image and video conversion; media imports and photo-picker conversions may fail.",photoAnalysis:"Background Photos analysis; may reduce photo search and recognition. Preserves library access, cloud transfers, and shared media-analysis infrastructure.",assistantSuggestions:"Siri inference, knowledge, and proactive suggestions; preserves speech, system voices, and shared language/model infrastructure.",appleIntelligence:"Apple Intelligence orchestration and generative experiences; system writing tools and intelligence integrations may become unavailable. Preserves shared model and speech services.",searchIndexing:"Spotlight and Settings search, including app-provided system indexes; excludes an app's own search service.",appStoreServices:"App Store installation/update services; excludes push and StoreKit payment services.",appleMediaSync:"Apple Music and subscribed/purchased media background services; excludes generic audio/video playback and StoreKit payments.",mailServices:"Apple Mail background services. Mail-based sign-in email workflows may be unavailable.",calendarServices:"Local Calendar database access; excludes server-side calendar integrations in apps.",reminderServices:"Apple Reminders database and background work; excludes reminders maintained by other apps.",personalDataSync:"Exchange, CalDAV, and CardDAV synchronization; preserves local Contacts database access.",safariSync:"Safari bookmark/history synchronization; preserves associated domains, shared credentials, browsing protections, and WebKit.",icloudSettingsSync:"iCloud system-settings synchronization and storage-plan recommendations; preserves accounts, credentials, CloudKit data, Drive, and Photos transfers.",messagingMaintenance:"Apple Messages history cleanup, attachment transfer, and FaceTime message storage; preserves identity, message database XPC helpers, and system calling services.",watchConnectivity:"Paired Watch and companion-device communication.",carPlay:"CarPlay vehicle connectivity.",tvRemote:"Apple TV discovery and remote control.",findMy:"Find My device-location services; excludes general location APIs.",continuity:"Nearby-device Continuity discovery; cross-device workflows may stop working. Preserves system share sheets.",walletServices:"Wallet, Apple Pay, digital identity, and merchant services. Payment sheets, including dependent StoreKit workflows, may fail.",businessServices:"Apple business messaging services; excludes ordinary app messaging.",backgroundSync:"General OS background app scheduling. Control is unsupported to preserve application behavior.",animations:"Android system animation scales: disabled sets all three to zero; enabled sets them to one. Excludes app-owned animation.",screensavers:"Android dream/screensaver activation; excludes wallpaper and widgets.",backup:"Android Backup Manager scheduling for the current user; disables backup and restore test behavior.",mailApp:"Android optional mail apps, including Gmail. Removes mail intent handlers; preserves other apps' messaging.",calendarApp:"Android Calendar app availability; preserves CalendarProvider.",contactsApp:"Android Contacts app availability; preserves ContactsProvider.",mapsApp:"Android Google Maps app; external navigation intents become unavailable.",videoApp:"Android YouTube app; native video links become unavailable.",musicApp:"Android YouTube Music app; preserves shared audio playback.",photosApp:"Android Google Photos app; changes cloud photo sources and choosers. Preserves MediaProvider and DocumentsUI.",assistantApp:"Android Google Search/Assistant app, including voice and home-search integrations.",digitalWellbeing:"Android Digital Wellbeing usage tracking, focus, and app limits.",printing:"Android print spooler and print recommendations; printing becomes unavailable.",accessibilityApps:"Optional Android accessibility apps. Active accessibility services are protected.",textToSpeech:"Android Google speech synthesis; speech-dependent functionality becomes unavailable.",storeApp:"Android Play Store app; installation, updates, billing and licensing may fail.",healthConnect:"Android Health Connect controller and backup app; health integrations become unavailable.",adServices:"Android AdServices API package; advertising/privacy APIs may fail. Does not remove mainline/APEX infrastructure.",onDevicePersonalization:"Android on-device personalization service package; dependent APIs may fail.",wallpaperApps:"Android wallpaper picker and optional live-wallpaper apps; changes wallpaper selection. Does not disable the shared wallpaper framework or widgets.",dialerApp:"Optional Android dialer apps. Default role holders remain protected.",messagesApp:"Optional Android SMS/Messages apps. Default role holders remain protected; excludes other apps' messaging.",googleServicesFramework:"Android Google Services Framework; aggressive control that can break Google account and push integrations.",googlePlayServices:"Android Google Play services; aggressive control that breaks dependent push, authentication, location and other integrations. Keep enabled for workflows that depend on those services.",icloudSync:"Broad iCloud/account synchronization. Control is unsupported; use the narrower icloudSettingsSync setting."};var OE="value-redacted";function ut(r){return r===!0||r==="true"}function Bd(r){return r===!1||r==="false"}var Zae=["first","random","unique"];var Bo=Symbol("displayInventoryOutcome");var rS=[["closed","cover"],["opened","inner"],["rear_display","inner"]];function $d(r){return r.role!=="overlay"&&r.role!=="virtual"}function rm(r){return r?.panels?.length?r.panels:[{key:"0",role:"unknown",sizePx:{width:0,height:0}}]}function WP(r,n,o,s){let{hasPostures:a,pinned:c}=s,d=o.map(({key:p,role:x})=>x?`${p} (${x})`:p).join(", "),b=rS.find(([,p])=>p===n)?.[0],f=a&&n!=="cluster"?`; to make this panel available, change the device posture with ${b?`setPosture {posture: "${b}"}`:"setPosture using a supported posture"}`:"";return`Display "${r}" (${n}) ${n==="cluster"?"is not currently connected":"is not connected in the current posture"}. Connected panels: ${d}. Target a connected panel, omit display, or use display: "active"${f}.${c?" Clear the pin with setActiveDevice {display: null} (include deviceId and sessionUuid), or select another display explicitly.":""}`}function MU(r){if(typeof r!=="object"||r===null)return;let n=r;if(typeof n.width!=="number"||typeof n.height!=="number"||!Number.isInteger(n.width)||n.width<=0||!Number.isInteger(n.height)||n.height<=0)return;return{width:n.width,height:n.height}}function qK(r,n){if(!n)return;let o=r?.filter((s)=>s.sizePx.width===n.width&&s.sizePx.height===n.height);return o?.length===1?o[0].key:void 0}var ze=["tv","watch","automotive","xr-headset","xr-glasses"],X={tv:{systemImageTags:["android-tv","google-tv","google-tv-ps16k"],profileIdPattern:/^tv_/i,defaultProfileId:"tv_1080p"},watch:{systemImageTags:["android-wear-signed","android-wear","android-wear-cn"],profileIdPattern:/^wear(?:os)?_/i,defaultProfileId:"wearos_small_round"},automotive:{systemImageTags:["android-automotive-playstore","android-automotive"],profileIdPattern:/^automotive_/i,defaultProfileId:"automotive_1024p_landscape"},"xr-headset":{systemImageTags:["google-xr","android-xr-v3-playstore","android-xr-preview-playstore"],profileIdPattern:/^xr_headset/i,defaultProfileId:"xr_headset_device"},"xr-glasses":{systemImageTags:["ai-glasses"],profileIdPattern:/^(?:xr_glasses|ai_glasses)_/i,defaultProfileId:"ai_glasses_device"}},$e=ze.map((r)=>({formFactor:r,...X[r]}));function Qae(r){return ze.includes(r)}function Ud(r){return X[r].systemImageTags}function jl(r,n){if(r==="watch"&&n===!1)return"wearos_square";return X[r].defaultProfileId}function ece(r){let n=r?.trim()??"";if(!X.watch.profileIdPattern.test(n))return;if(/round/i.test(n))return!0;return/square|rect/i.test(n)?!1:void 0}function It(r){let n=r.systemImageTag?.trim().toLowerCase(),o=r.profileId?.trim(),s=$e.find((a)=>n?a.systemImageTags.includes(n):!1);if(s)return s.formFactor;return $e.find((a)=>o?a.profileIdPattern.test(o):!1)?.formFactor}function Vf(r){let n=/pixel[_ ]tablet|nexus (?:9|10)/i.test(r.profileId??"")?"tablet":void 0;return nS({...r,hint:n,deviceType:r.profileId})}function ve(r){return typeof r==="number"&&Number.isFinite(r)&&r>0}function nS(r){let n=It({systemImageTag:r.systemImageTag,profileId:r.deviceType});if(n)return n;let o=`${r.deviceType??""} ${r.hint??""}`;if(/fold|flip/i.test(o))return"foldable";let s=r.hint?.trim().toLowerCase();if(s!==void 0&&Dt.has(s))return s;return Et(r)}var Dt=new Set(["phone","tablet","tv","watch","automotive","xr-headset","xr-glasses"]);function Et(r){let{width:n,height:o,density:s}=r;if(!ve(n)||!ve(o)||!ve(s))return"unknown";return Math.hypot(n,o)/s>=7?"tablet":"phone"}var Ui={watchos:"watchOS",tvos:"tvOS",visionos:"visionOS"},Hd={android:"Android",ios:"iOS",...Ui};function dr(r){return r==="android"||r==="ios"}function nm(r,n){return n===void 0?dr(r):r===n}function re(r,n){if(dr(r))return r;throw kt(n,r)}function B8(r,n){return r==="either"?r:re(r,n)}function kt(r,n){return new t(`${r} is not supported on ${Ui[n]} yet. Target an Android or iOS device instead.`)}var sM=1,aM=1798000,cM=1,dM=1000;function ME(r){return r!==void 0&&(r.toolType==="eraser"||r.pressure!==void 0&&r.pressure!==1||r.tilt!==void 0||r.orientation!==void 0||(r.buttons?.length??0)>0)}function tce(r){return(r??[]).reduce((n,o)=>n|(o==="primary"?32:64),0)}function $8(r){return r==="window_read_skipped"||r==="window_list_skipped"}function lM(r){return r.ctrlProxyIncomplete===!0&&!$8(r.ctrlProxyIncompleteReason)}function we(r){return r.$??r}function Ea(r){let n=r.node;if(Array.isArray(n))return n;return n&&typeof n==="object"?[n]:[]}function qt(r){return r.bounds??we(r).bounds}function je(r){return r!==null&&typeof r==="object"&&!Array.isArray(r)}function rce(r){return je(r)&&"hierarchy"in r&&je(r.hierarchy)}function Zu(r){if(!r)return null;let{nativeScale:n,pixelWidth:o,pixelHeight:s}=r;if(typeof n!=="number"||!Number.isFinite(n)||n<=0||typeof o!=="number"||!Number.isFinite(o)||o<=0||typeof s!=="number"||!Number.isFinite(s)||s<=0)return null;return{nativeScale:n,pixelWidth:o,pixelHeight:s}}function NU(r){return Zu(r)??{}}var U8="immediate";var Lt="device_service_disabled";class uM extends t{code=Lt;retryable=!1;tool;resource;labels;disabledLabels;unavailable;howToEnable;deviceId;constructor(r){let n=`Call setDeviceResources with {resources:{${r.resource}:"enabled"}} (enable this default-disabled tool with setToolEnabled or --enable-tool setDeviceResources), or provision/start the simulator without {resources:{${r.resource}:"disabled"}}.`;super(`${r.tool} requires resource ${r.resource} (${r.labels.join(", ")}); disabled labels: ${r.disabledLabels.join(", ")}. Unavailable: ${r.unavailable}. ${n}`);this.name="DeviceServiceDisabledError",this.tool=r.tool,this.resource=r.resource,this.labels=[...r.labels],this.disabledLabels=[...r.disabledLabels],this.unavailable=r.unavailable,this.howToEnable=n,this.deviceId=r.deviceId}toPayload(){return{code:this.code,tool:this.tool,resource:this.resource,labels:this.labels,disabledLabels:this.disabledLabels,unavailable:this.unavailable,howToEnable:this.howToEnable,retryable:this.retryable,deviceId:this.deviceId}}}var Ot="unsafe_device_resource_combination";class Qu extends t{code=Ot;retryable=!1;hazards;howToProceed;constructor(r){super(`Unsafe iOS device resource combination: ${r.map((o)=>`${o.id} (${o.resources.join(", ")}): ${o.reason}`).join("; ")}. Drop or re-enable at least one of the listed resources in each unsafe combination before retrying.`);this.name="UnsafeDeviceResourceCombinationError",this.hazards=r.map((o)=>({...o,resources:[...o.resources],appliesTo:[...o.appliesTo]})),this.howToProceed="Drop or re-enable at least one of the listed resources in each unsafe combination before retrying."}toPayload(){return{code:this.code,retryable:this.retryable,hazards:this.hazards,howToProceed:this.howToProceed}}}function _t(r){return typeof r==="object"&&r!==null&&"unref"in r&&typeof r.unref==="function"}function Mt(r){let{timer:n,timeoutMs:o,deadline:s,unref:a,label:c,timeoutError:d,onTimeout:b}=r;if(s===void 0&&o===void 0)return;let f=o??0,v=()=>{};return{promise:new Promise((p,x)=>{let R=(g)=>{x(d?.()??new t(g)),b?.()},D=(g)=>{if(a&&_t(g))g.unref()};if(s){v=s.whenExpired(n,()=>R(`${c} timed out`),D);return}let A=n.setTimeout(()=>R(`${c} timed out after ${f}ms`),f);D(A),v=()=>n.clearTimeout(A)}),cancel:()=>v()}}function Ke(r,n,o){let s=r.reason;if(o&&(s===void 0||s instanceof DOMException&&s.name==="AbortError"))return new t(`${n} cancelled`);return s===void 0?new DOMException("The operation was aborted.","AbortError"):s}function Ct(r){return Array.isArray(r)}function Ye(r){return Ct(r)?r:[r]}function Nt(r){return typeof r==="function"?[r()]:Ye(r)}function qe(r){for(let n of r)n.then(void 0,()=>{})}async function l(r,{timer:n,timeoutMs:o,deadline:s,unref:a=!1,signal:c,label:d,relabelDefaultAbort:b=!1,timeoutError:f,onTimeout:v}){if(typeof r!=="function")qe(Ye(r));if(c?.aborted)throw Ke(c,d,b);let S,p=c?new Promise((R,D)=>{let A=()=>D(Ke(c,d,b));if(c.addEventListener("abort",A,{once:!0}),S=()=>c.removeEventListener("abort",A),c.aborted)A()}):void 0,x=Mt({timer:n,timeoutMs:o,deadline:s,unref:a,label:d,timeoutError:f,onTimeout:v});try{let R=Nt(r);return qe(R),await Promise.race([...R,...p?[p]:[],...x?[x.promise]:[]])}finally{x?.cancel(),S?.()}}import{readFileSync as Ft}from"fs";function xe(r,n,o){try{r?.(n,o)}catch(s){}}var Bt=50;function Ht(r,n){let o=`${r} (`,s=n.lastIndexOf(")");if(!n.startsWith(o)||s<o.length)return;let a=n.slice(s+1);if(!/^\s/.test(a))return;let c=a.trim().split(/\s+/),[d,...b]=c;if(c.length<Bt||d?.length!==1||b.some((f)=>!/^-?\d+$/.test(f)))return;return d}function Ut(r){return r?.code==="ESRCH"}function st(r,n={}){if(!Number.isInteger(r)||r<=0)return!1;let o=n.signalProcess??((c)=>{process.kill(c,0)});try{o(r)}catch(c){return xe(n.debugLog,`src/daemon/daemonFiles.ts liveness check failed: ${c}`,c),!Ut(c)}if((n.platform??process.platform)!=="linux")return!0;let s;try{s=(n.readProcStat??((d)=>Ft(`/proc/${d}/stat`,"utf-8")))(r)}catch(c){return xe(n.debugLog,`src/daemon/daemonFiles.ts procfs liveness check failed: ${c}`,c),!0}let a=Ht(r,s);if(a===void 0)return xe(n.debugLog,`src/daemon/daemonFiles.ts could not parse /proc/${r}/stat`,s),!0;return a!=="Z"&&a!=="X"}class Z{policy;pending=new Set;timeout;episode;observing=!0;constructor(r){this.policy=r}get stalled(){return this.episode!==void 0}divert(){if(this.episode)this.episode.diverted++}track(r){return new Promise((n,o)=>{let s={issuedAt:this.policy.timer.now(),settle:n,fail:o};this.pending.add(s),this.armOldest();try{r((a)=>this.complete(s,a))}catch(a){this.complete(s,a)}})}suspend(){this.observing=!1,this.clearTimeout()}retire(r){this.suspend();for(let n of this.pending)if(r)n.fail(r);else n.settle(!1);this.pending.clear(),this.episode=void 0}complete(r,n){if(!this.pending.delete(r))return;if(n){if(this.episode)this.episode.failed++;r.fail(n)}else r.settle(!0);if(!this.observing)return;if(this.episode&&!n&&!this.oldestExpired())this.resume();if(this.pending.size===0&&!this.episode)this.clearTimeout();this.armOldest()}oldest(){return this.pending.values().next().value}oldestExpired(){let r=this.oldest();return r!==void 0&&this.policy.timer.now()-r.issuedAt>=this.policy.timeoutMs}resume(){let r=this.episode;if(this.episode=void 0,this.clearTimeout(),r)this.policy.resumed(this.policy.timer.now()-r.detectedAt,r.diverted)}armOldest(){let r=this.oldest();if(!this.observing||this.timeout!==void 0||this.episode||!r)return;this.arm(Math.max(0,this.policy.timeoutMs-(this.policy.timer.now()-r.issuedAt)))}arm(r){if(this.timeout=this.policy.timer.setTimeout(()=>{this.timeout=void 0,this.onDeadline()},r),typeof this.timeout==="object"&&typeof this.timeout.unref==="function")this.timeout.unref()}onDeadline(){if(this.episode){let r=this.policy.timer.now()-this.episode.detectedAt,n=this.pending.size+this.episode.failed;this.retire(),this.policy.abandoned?.(r,n);return}if(!this.oldestExpired()){this.armOldest();return}this.episode={detectedAt:this.policy.timer.now(),diverted:0,failed:0},this.policy.stalled(this.pending.size);for(let r of this.pending)r.settle(!1);if(this.policy.abandonMs!==void 0)this.arm(this.policy.abandonMs)}clearTimeout(){if(this.timeout!==void 0)this.policy.timer.clearTimeout(this.timeout);this.timeout=void 0}}function H8(){return N==="json"}var V=pe(I(h.LOG_LEVEL))??rc.INFO,N=DE(),_=qf(),Re=!1,z=Promise.resolve(),W=(r)=>{z=z.then(()=>r)},M=_==="stderr"?void 0:$K(),F=me(process.argv,process.pid),T=M?Qe.join(M,`${F}.log`):void 0,Vt=(r,n)=>{r.on("error",(o)=>{try{eo(`Log stream error on ${n}`,o)}catch(s){}if(m===r)m=void 0;w.get(r)?.retire(o),C(r),queueMicrotask(()=>r.destroy?.())})},L=new Map,C=(r,n=i)=>{if(r.closed)return;let o=L.get(r);if(o)o.timer.clearTimeout(o.timeoutHandle),r.off("close",o.onClose);let s=o&&n===i?o.timer:n,a=()=>{let d=L.get(r);if(d?.onClose===a)d.timer.clearTimeout(d.timeoutHandle),r.off("close",a),L.delete(r)},c=s.setTimeout(a,j);L.set(r,{timer:s,timeoutHandle:c,onClose:a}),r.once("close",a)},ue=(r)=>{for(let[n,o]of L)if(n.closed)o.onClose();if(L.size>0)return;try{let n=Ve.create(r,{flags:"a"});return Vt(n,r),n}catch(n){eo(`Failed to open log stream ${r}`,n);return}},m=T?ue(T):void 0;function Te(){if(!M||!T)return;return{dir:M,path:T}}var Xe=20000,ie=5000,Wt=30000,Ie=_e,w=new WeakMap,se=0,P;var Gt=10485760,$t=10,jt=86400000,ae;function q8(r){if(ae=r,te&&!te.registeredSweepStarted)et(te)}function de(){if(!ae)throw Error("Log retention namespace source is not registered");return ae}var Kt=()=>{try{let r=de(),{pidFiles:n,uncertain:o}=r.listDaemonPidFilesSync();if(o)return!0;return n.some((s)=>{let a=r.readPidFileDataSync(s);return a?st(a.pid):!1})}catch(r){return e.debug(`daemon liveness probe for log pruning failed: ${r}`,r),!0}},Jt=()=>{try{return de().listDaemonPidFilesSync()}catch(r){return e.debug(`daemon pidfile enumeration for log pruning failed: ${r}`,r),{pidFiles:[],uncertain:!0}}},Yt=(r)=>de().readDaemonOwnerForRetentionSync(r),Xt=(r)=>de().readDaemonLaunchLogOwnerTombstoneSync(r),Qt={daemonPidFiles:Jt,readDaemonOwner:Yt,readDaemonLaunchLogOwnerTombstone:Xt,isDaemonRunning:Kt},Ze=()=>{if(!M)return Promise.resolve();return Ue({dir:M,ownPrefix:F,maxOwnFiles:$t,abandonedMaxAgeMs:jt,...Qt})};function et(r){if(r.timeout!==void 0)return;r.timeout=r.timer.setTimeout(()=>{r.timeout=void 0,r.pending=r.pending.then(async()=>{if(r!==te||r.registeredSweepStarted)return;let n=ae!==void 0;if(r.fallbackStarted&&!n)return;r.fallbackStarted=!0,r.registeredSweepStarted=n;try{await r.prune()}catch(o){e.warn("Startup log pruning failed",o)}})},0)}function Zt(r,n){let o={timer:r,prune:n,pending:Promise.resolve(),fallbackStarted:!1,registeredSweepStarted:!1};return et(o),o}var te=M?Zt(i,Ze):void 0,tr=async(r)=>{w.get(r)?.suspend();try{return await K(r),!0}catch(n){let o=r.closed===!0;if(!o)C(r);return await E("Failed to close log stream before rotation",n),o}},rr=async(r)=>{let n=m;if(m=void 0,n){if(!await tr(n)){ne=Number.POSITIVE_INFINITY;return}}let o=new Date().toISOString().replace(/:/g,"-"),s=Qe.join(r.dir,`${F}-${o}.log`);if(oe.existsSync(r.path))await oe.promises.rename(r.path,s);m=ue(r.path),await Ze()},O,nr=async(r)=>{if(!oe.existsSync(r.path))return;if((await Hf(r.path)).size>=Gt)await rr(r)},or=(r)=>{if(!O)O=nr(r).finally(()=>{O=void 0});return O},De=async(r,n)=>{if(L.size===0&&(m?.destroyed||!m?.writable))m=ue(r.path);await E("Log rotation failed",n)},ne=Number.POSITIVE_INFINITY,ir=32768,sr=async(r)=>{if(ne+=r,ne<ir)return!0;ne=0;let n=Te();if(!n||!m)return!0;try{return await nt(or(n))}catch(o){return await De(n,o),!0}};var le=(r)=>new Promise((n,o)=>{process.stderr.write(`${r}
|
|
5
5
|
`,(s)=>{if(s)o(s);else n()})}),E=async(r,n)=>{if(_==="file")return;let o=`${r}: ${B(String(n))}`,s=N==="json"?JSON.stringify({timestamp:new Date().toISOString(),level:"error",component:F,event:"log.write_failed",message:o}):o;try{await le(s)}catch(a){}},tt=(r)=>{try{oe.writeSync(process.stderr.fd,`${r}
|
|
6
|
-
`)}catch(n){}},Ee=(r,n,o)=>{Pe=r.now(),tt(N==="json"?JSON.stringify({timestamp:new Date(r.now()).toISOString(),level:"error",component:F,event:n,message:B(o)}):B(o))},rt=(r,n)=>{W(ot(ge(N,F,"WARN",{message:`Log sink ${T} resumed after ${r}ms; ${n} line(s) were diverted while it was stalled`,args:[]})).catch((o)=>E("Failed to write log sink recovery",o)))},ar=(r,n,o,s)=>{if(Ee(n,"log.sink_abandoned",`Log sink ${T} abandoned after ${o}ms stalled; ${s} line(s) dropped`),m===r)m=void 0;C(r,n);try{r.destroy?.()}catch(a){}},lr=(r)=>{let n=w.get(r);if(!n){let o=Ie;if(n=new Z({timer:o,timeoutMs:ie,abandonMs:
|
|
6
|
+
`)}catch(n){}},Ee=(r,n,o)=>{Pe=r.now(),tt(N==="json"?JSON.stringify({timestamp:new Date(r.now()).toISOString(),level:"error",component:F,event:n,message:B(o)}):B(o))},rt=(r,n)=>{W(ot(ge(N,F,"WARN",{message:`Log sink ${T} resumed after ${r}ms; ${n} line(s) were diverted while it was stalled`,args:[]})).catch((o)=>E("Failed to write log sink recovery",o)))},ar=(r,n,o,s)=>{if(Ee(n,"log.sink_abandoned",`Log sink ${T} abandoned after ${o}ms stalled; ${s} line(s) dropped`),m===r)m=void 0;C(r,n);try{r.destroy?.()}catch(a){}},lr=(r)=>{let n=w.get(r);if(!n){let o=Ie;if(n=new Z({timer:o,timeoutMs:ie,abandonMs:Wt,stalled:(s)=>Ee(o,"log.sink_stalled",`Logging to ${T} stalled: no write completed within ${ie}ms; ${s} line(s) pending`),resumed:rt,abandoned:(s,a)=>ar(r,o,s,a)}),se>0)n.suspend();w.set(r,n)}return n},nt=(r)=>{if(P?.operation===r)return P.completion;let n=Ie,o=new Z({timer:n,timeoutMs:ie,stalled:()=>Ee(n,"log.sink_stalled",`Logging to ${T} stalled: log rotation did not finish within ${ie}ms`),resumed:rt});if(se>0)o.suspend();let s=o.track((a)=>{let c=(d)=>{if(a(d),P?.guard===o)P=void 0};r.then(()=>c(),async(d)=>{let b=o.stalled;c(d);let f=Te();if(b&&f)await De(f,d)}).catch((d)=>E("Failed to recover log rotation",d))});return P={operation:r,guard:o,completion:s},s},Ae=(r=!1)=>{if(r)P?.guard.retire();else P?.guard.suspend();P=void 0},G=(r)=>{if(P?.guard.divert(),m)w.get(m)?.divert();if(_==="file")tt(r)},ce=()=>P?.guard.stalled===!0||m!==void 0&&w.get(m)?.stalled===!0,Pe,V8=(r)=>ce()||Pe!==void 0&&Ie.now()-Pe<=r,cr=async()=>{while(O)try{if(!await nt(O))return!1}catch(r){let n=Te();if(n)await De(n,r)}return!0},ur=async(r)=>{if(!T)return!1;if(ce())return G(r),!1;if(O&&!await cr())return G(r),!1;if(!m)m=ue(T);if(m&&!await sr(Buffer.byteLength(r)+1))return G(r),!1;if(ce())return G(r),!1;return!0},ot=async(r)=>{if(!await ur(r))return;if(ce()){G(r);return}let n=m;if(!n){if(_==="file")await le(r);return}try{await lr(n).track((o)=>{n.write(r+`
|
|
7
7
|
`,o)})}catch(o){if(_==="file"){await le(r);return}throw o}},pr=async(r)=>{if(_==="stderr"||_==="both")await le(r)},mr=(r)=>{if(Re&&N==="text")try{process.stdout.write(`${r}
|
|
8
|
-
`)}catch(n){}},ee=async(r,n,o)=>{if(
|
|
9
|
-
export{
|
|
8
|
+
`)}catch(n){}},ee=async(r,n,o)=>{if(yn.logSinksDisabled?.())return;try{let s=Le(),a=s?`trace=${s.traceId} ${n}`:n,c=ge(N,F,r,{message:a,args:o}).replace(/[\r\n\t]/g," ");mr(c),await Promise.all([ot(c),pr(c)])}catch(s){await E("Failed to write log",s)}},gr=async(r=i)=>{if(Ae(),m){let n=m;w.get(n)?.suspend(),m=void 0,C(n,r);try{await K(n,r)}finally{C(n,r)}}},e={setLogLevel(r){V=r},getLogLevel(){return V},enableStdoutLogging(){Re=N==="text"},disableStdoutLogging(){Re=!1},debug(r,...n){if(V<=rc.DEBUG)W(ee("DEBUG",r,n).catch((o)=>E("Failed to write debug log",o)))},info(r,...n){if(V<=rc.INFO)W(ee("INFO",r,n).catch((o)=>E("Failed to write info log",o)))},warn(r,...n){if(V<=rc.WARN)W(ee("WARN",r,n).catch((o)=>E("Failed to write warn log",o)))},error(r,...n){if(V<=rc.ERROR)W(ee("ERROR",r,n).catch((o)=>E("Failed to write error log",o)))},async flush(){await z},close(){Ae();let r=m;if(m=void 0,r)w.get(r)?.suspend(),C(r),r.end()},async closeAfterFlush(r=i){if(se++,P?.guard.suspend(),m)w.get(m)?.suspend();let n,o=new AbortController;try{n=r.setTimeout(()=>{Ae(!0);let s=m;if(s)w.get(s)?.retire(),m=void 0,C(s,r),s.destroy?.();z=Promise.resolve(),o.abort(u(Error("Pending log writes stalled"),`Log writes did not flush within ${Xe}ms`))},Xe),await l(z,{timer:r,signal:o.signal,label:"Log writes"})}finally{if(se--,n!==void 0)r.clearTimeout(n)}await gr(r)}};
|
|
9
|
+
export{yn,Kae,UP,Ur,L8,$f,i,rc,Uf,Gae,Hf,NK,iM,er,Tr,$i,DU,tS,FK,oM,OU,Ld,Se,Yae,tm,LK,Jae,Je,HP,BK,Xu,nc,hi,Xae,$K,vn,gi,zt,Q,Lo,qP,DE,qf,eo,VP,zl,UK,HK,OE,ut,Bd,Zae,Bo,rS,$d,rm,WP,MU,qK,Qae,Ud,jl,ece,Vf,nS,Ui,Hd,dr,nm,re,B8,sM,aM,cM,dM,ME,tce,$8,lM,we,Ea,qt,rce,Zu,NU,U8,uM,Qu,l,st,H8,q8,V8,e};
|
|
10
10
|
|
|
11
|
-
//# debugId=
|
|
11
|
+
//# debugId=A83413083C254EB464756E2164756E21
|