@kaeawc/auto-mobile 0.0.92 → 0.0.93
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/schemas/test-plan.schema.json +370 -52
- package/dist/src/{chunk-jhnbfj19.js → chunk-00167wan.js} +5 -5
- package/dist/src/chunk-0jrrsnc9.js +6 -0
- package/dist/src/chunk-0n6swkwg.js +5 -0
- package/dist/src/chunk-0qsy1qsx.js +57 -0
- package/dist/src/chunk-11m8wj8j.js +237 -0
- package/dist/src/{chunk-4pfftt07.js → chunk-1p7xf5kb.js} +3 -3
- package/dist/src/chunk-23p5f095.js +4 -0
- package/dist/src/{chunk-a4k9rt7z.js → chunk-26k317v5.js} +3 -3
- package/dist/src/chunk-284ptqa4.js +7 -0
- package/dist/src/chunk-28re4xrg.js +4 -0
- package/dist/src/chunk-2f9rkmhx.js +5 -0
- package/dist/src/chunk-2fxdh48t.js +4 -0
- package/dist/src/chunk-2tbdrbt6.js +4 -0
- package/dist/src/chunk-2tqzq5qh.js +971 -0
- package/dist/src/chunk-32gvv9b4.js +21 -0
- package/dist/src/chunk-3f3t1x97.js +8 -0
- package/dist/src/chunk-3fspkbc7.js +4 -0
- package/dist/src/chunk-3qwrzxh0.js +11 -0
- package/dist/src/chunk-3sy6ahhz.js +26 -0
- package/dist/src/chunk-3vg455e6.js +4 -0
- package/dist/src/chunk-3xkpk44w.js +5 -0
- package/dist/src/chunk-3y6eykz9.js +4 -0
- package/dist/src/chunk-49bsqdx3.js +4 -0
- package/dist/src/chunk-4hw3665t.js +42 -0
- package/dist/src/chunk-58wzr3mt.js +5 -0
- package/dist/src/chunk-5d2hft6c.js +5 -0
- package/dist/src/chunk-5snsn9cf.js +4 -0
- package/dist/src/chunk-5tm9mn47.js +54 -0
- package/dist/src/chunk-5zc77a5t.js +4 -0
- package/dist/src/chunk-64j0majr.js +19 -0
- package/dist/src/chunk-65y8v4td.js +17 -0
- package/dist/src/chunk-6awz7vhq.js +5 -0
- package/dist/src/{chunk-stfzjr9y.js → chunk-6bznss4t.js} +5 -5
- package/dist/src/chunk-6ep7f5ge.js +4 -0
- package/dist/src/{chunk-0dfnyfkh.js → chunk-6wt9rgjf.js} +3 -3
- package/dist/src/chunk-6xmss8er.js +8 -0
- package/dist/src/chunk-710rxz9y.js +5 -0
- package/dist/src/chunk-7cs2da62.js +5 -0
- package/dist/src/chunk-7g103b54.js +4 -0
- package/dist/src/chunk-7j5vj4pa.js +4 -0
- package/dist/src/chunk-7rz9898k.js +5 -0
- package/dist/src/chunk-7tw8x05v.js +4 -0
- package/dist/src/chunk-7zy586cb.js +4 -0
- package/dist/src/{chunk-r0f1q783.js → chunk-8037tzzj.js} +3 -3
- package/dist/src/chunk-84nanf8s.js +5 -0
- package/dist/src/{chunk-950qcq1e.js → chunk-8g1922rp.js} +4 -4
- package/dist/src/chunk-8gvwcv2p.js +4 -0
- package/dist/src/{chunk-sz1a7p43.js → chunk-8ph29g99.js} +1 -1
- package/dist/src/chunk-8thrmfat.js +4 -0
- package/dist/src/chunk-8zgzzs7k.js +78 -0
- package/dist/src/chunk-97b1zmaq.js +4 -0
- package/dist/src/chunk-9fth9ayh.js +4 -0
- package/dist/src/chunk-9j6anhjr.js +4 -0
- package/dist/src/{chunk-w7zsh13a.js → chunk-aabchzxk.js} +4 -4
- package/dist/src/{chunk-wry6skrm.js → chunk-ayp07wbb.js} +1 -1
- package/dist/src/chunk-bfjwqk8q.js +4 -0
- package/dist/src/{chunk-jdqvcq0a.js → chunk-bfw6125s.js} +3 -3
- package/dist/src/chunk-bnhscm2n.js +4 -0
- package/dist/src/chunk-bxmsax22.js +5 -0
- package/dist/src/chunk-c1vs4g1n.js +4 -0
- package/dist/src/chunk-ct3e7yng.js +4 -0
- package/dist/src/{chunk-8en08r7q.js → chunk-cyy71ggq.js} +3 -3
- package/dist/src/chunk-ddzkz92z.js +4 -0
- package/dist/src/chunk-dgrbdpb7.js +9 -0
- package/dist/src/chunk-drdz8hee.js +5 -0
- package/dist/src/chunk-e98dqnc9.js +145 -0
- package/dist/src/chunk-eersndy7.js +5 -0
- package/dist/src/chunk-eggq53ks.js +4 -0
- package/dist/src/chunk-f2dya7cs.js +4 -0
- package/dist/src/chunk-fbakd6cw.js +4 -0
- package/dist/src/chunk-fgb98zjj.js +5 -0
- package/dist/src/chunk-fmpad823.js +5 -0
- package/dist/src/{chunk-v90es00d.js → chunk-g04bwyj3.js} +2 -2
- package/dist/src/chunk-g0xr8zw0.js +4 -0
- package/dist/src/chunk-g3rjs80x.js +4 -0
- package/dist/src/chunk-g78rtrfv.js +4 -0
- package/dist/src/{chunk-r20pe1nv.js → chunk-g7tmjbkt.js} +3 -3
- package/dist/src/chunk-gabgv3y5.js +4 -0
- package/dist/src/chunk-gmr45m8f.js +4 -0
- package/dist/src/chunk-gsyfebqj.js +4 -0
- package/dist/src/chunk-h5rpn9wr.js +247 -0
- package/dist/src/chunk-hb1x7v55.js +4 -0
- package/dist/src/chunk-hrfytkxh.js +168 -0
- package/dist/src/chunk-j4yjzbak.js +4 -0
- package/dist/src/chunk-jd6a5v6p.js +5 -0
- package/dist/src/chunk-jh6vhqzx.js +5 -0
- package/dist/src/chunk-kn5spq15.js +4 -0
- package/dist/src/{chunk-w2mwa0jk.js → chunk-m94qs0f0.js} +2 -2
- package/dist/src/chunk-mjrps0ac.js +7 -0
- package/dist/src/chunk-n03dmn5q.js +5 -0
- package/dist/src/chunk-n72qhwd9.js +4 -0
- package/dist/src/{chunk-km0dy5vc.js → chunk-ndt1ccxm.js} +9 -9
- package/dist/src/chunk-nr6y0n4y.js +5 -0
- package/dist/src/chunk-pcsen2vs.js +4 -0
- package/dist/src/chunk-ppfr0b8h.js +4 -0
- package/dist/src/chunk-q10bdnat.js +4 -0
- package/dist/src/chunk-q9xmq595.js +4 -0
- package/dist/src/{chunk-2v7tw1nj.js → chunk-qcxzr2my.js} +3 -3
- package/dist/src/chunk-qf6nynk6.js +7 -0
- package/dist/src/chunk-qyqypn28.js +5 -0
- package/dist/src/chunk-r2epb56s.js +4 -0
- package/dist/src/chunk-r5bxavdx.js +311 -0
- package/dist/src/{chunk-r14wwk37.js → chunk-r6z1eztj.js} +12 -12
- package/dist/src/{chunk-d57432wq.js → chunk-r7bpkgff.js} +2 -2
- package/dist/src/chunk-r8jf3d92.js +4 -0
- package/dist/src/{chunk-9rkfyt6q.js → chunk-rbpdk7m0.js} +3 -3
- package/dist/src/chunk-rc0dbypm.js +4 -0
- package/dist/src/chunk-rhcty4ms.js +4 -0
- package/dist/src/chunk-rpvckv3p.js +4 -0
- package/dist/src/{chunk-s1zq65ny.js → chunk-rqc9ap3x.js} +2 -2
- package/dist/src/chunk-rvvy1bte.js +7 -0
- package/dist/src/chunk-ry0mz41y.js +4 -0
- package/dist/src/{chunk-34zxqcmq.js → chunk-s3jc6cwp.js} +3 -3
- package/dist/src/chunk-sfv61xjb.js +6 -0
- package/dist/src/chunk-t6bfvfkg.js +4 -0
- package/dist/src/chunk-t6c8akcm.js +5 -0
- package/dist/src/chunk-t7w8rctc.js +4 -0
- package/dist/src/chunk-thbh3jew.js +5 -0
- package/dist/src/chunk-v2wd4n3e.js +5 -0
- package/dist/src/{chunk-zg67wjkh.js → chunk-v6pya0dm.js} +3 -3
- package/dist/src/chunk-vy3bwm1d.js +17 -0
- package/dist/src/chunk-w3vs79ex.js +27 -0
- package/dist/src/chunk-w4zga19f.js +4 -0
- package/dist/src/chunk-w5b2jwk3.js +14 -0
- package/dist/src/chunk-w7hkv422.js +5 -0
- package/dist/src/{chunk-qv2918jt.js → chunk-waqwcjyn.js} +2 -2
- package/dist/src/{chunk-b4cxdzwy.js → chunk-wbh8spm5.js} +7 -7
- package/dist/src/{chunk-ajsrz473.js → chunk-wyrkw6hw.js} +3 -3
- package/dist/src/chunk-xa73x2cx.js +5 -0
- package/dist/src/{chunk-eka89q3k.js → chunk-xgan0qqp.js} +1 -1
- package/dist/src/chunk-y2vs6jwg.js +4 -0
- package/dist/src/chunk-yattm52s.js +4 -0
- package/dist/src/{chunk-9y5bcy28.js → chunk-yb97j25b.js} +4 -4
- package/dist/src/{chunk-c9nk1r78.js → chunk-ybbtagbt.js} +3 -3
- package/dist/src/chunk-ycaj2sgf.js +9 -0
- package/dist/src/chunk-yf7ympyz.js +325 -0
- package/dist/src/chunk-yjawdzk8.js +4 -0
- package/dist/src/chunk-z637nqg8.js +11 -0
- package/dist/src/{chunk-0w1spptt.js → chunk-zgja5f3p.js} +4 -4
- package/dist/src/chunk-zs1sghs9.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/ios/CameraPosterInjection/Injection/CameraPosterInjection.m +466 -0
- package/package.json +3 -2
- package/schemas/test-plan.schema.json +370 -52
- package/dist/src/chunk-09442h7v.js +0 -4
- package/dist/src/chunk-0e4gm1kj.js +0 -5
- package/dist/src/chunk-0eb8576f.js +0 -4
- package/dist/src/chunk-0rjm4nx7.js +0 -5
- package/dist/src/chunk-1zmh2eak.js +0 -4
- package/dist/src/chunk-28k63ha3.js +0 -5
- package/dist/src/chunk-2d4wmp8b.js +0 -4
- package/dist/src/chunk-2e6s75qv.js +0 -78
- package/dist/src/chunk-32jpxz2y.js +0 -323
- package/dist/src/chunk-3jmvqygr.js +0 -238
- package/dist/src/chunk-3swvfhqt.js +0 -5
- package/dist/src/chunk-44bt78m9.js +0 -5
- package/dist/src/chunk-488vt2bp.js +0 -4
- package/dist/src/chunk-4fgdhcwx.js +0 -5
- package/dist/src/chunk-4jp2se4w.js +0 -4
- package/dist/src/chunk-4vhr9e4t.js +0 -4
- package/dist/src/chunk-4xd6zs3y.js +0 -15
- package/dist/src/chunk-51567pg8.js +0 -4
- package/dist/src/chunk-5agqsfev.js +0 -4
- package/dist/src/chunk-5d706gmr.js +0 -4
- package/dist/src/chunk-5kd4rqk7.js +0 -5
- package/dist/src/chunk-61t538bm.js +0 -4
- package/dist/src/chunk-6d3mmqxt.js +0 -54
- package/dist/src/chunk-6hyt398x.js +0 -5
- package/dist/src/chunk-6mnr8kpm.js +0 -4
- package/dist/src/chunk-79q5xsdc.js +0 -42
- package/dist/src/chunk-7bdgand3.js +0 -4
- package/dist/src/chunk-84cp9dw5.js +0 -4
- package/dist/src/chunk-86f2h5ww.js +0 -5
- package/dist/src/chunk-8cghfzb2.js +0 -19
- package/dist/src/chunk-9tf2p9y9.js +0 -5
- package/dist/src/chunk-a2sc4jm0.js +0 -5
- package/dist/src/chunk-aa5ng3d1.js +0 -4
- package/dist/src/chunk-b3h0a6ca.js +0 -4
- package/dist/src/chunk-b6a737qt.js +0 -4
- package/dist/src/chunk-bn64x5z5.js +0 -5
- package/dist/src/chunk-bvh649za.js +0 -12
- package/dist/src/chunk-c9tyfg4j.js +0 -26
- package/dist/src/chunk-cfsdfqnm.js +0 -4
- package/dist/src/chunk-cxyf04jc.js +0 -7
- package/dist/src/chunk-da08tx5v.js +0 -4
- package/dist/src/chunk-f2tc08m2.js +0 -4
- package/dist/src/chunk-f8tnk179.js +0 -5
- package/dist/src/chunk-f9s1kkhx.js +0 -5
- package/dist/src/chunk-fbp8a4rx.js +0 -4
- package/dist/src/chunk-fd2z0sze.js +0 -4
- package/dist/src/chunk-fk927f4q.js +0 -54
- package/dist/src/chunk-fxmr3a0f.js +0 -4
- package/dist/src/chunk-gaqwhd44.js +0 -4
- package/dist/src/chunk-ggtd5x5a.js +0 -5
- package/dist/src/chunk-gndcfrm7.js +0 -4
- package/dist/src/chunk-h3n4adc6.js +0 -310
- package/dist/src/chunk-h5pjbb83.js +0 -4
- package/dist/src/chunk-hgnnh302.js +0 -4
- package/dist/src/chunk-hmke8nhx.js +0 -5
- package/dist/src/chunk-j2bx12hn.js +0 -4
- package/dist/src/chunk-j70y1a2g.js +0 -4
- package/dist/src/chunk-js1jpyxp.js +0 -6
- package/dist/src/chunk-kbjq0qvb.js +0 -4
- package/dist/src/chunk-kfwx57xd.js +0 -4
- package/dist/src/chunk-kzwctna2.js +0 -4
- package/dist/src/chunk-m9ehyehy.js +0 -4
- package/dist/src/chunk-mct91p1f.js +0 -4
- package/dist/src/chunk-mf9spd4g.js +0 -5
- package/dist/src/chunk-mgrcansb.js +0 -4
- package/dist/src/chunk-mqc1d0eb.js +0 -6
- package/dist/src/chunk-n1zmpk0z.js +0 -4
- package/dist/src/chunk-ncyjf63g.js +0 -4
- package/dist/src/chunk-nr64d21q.js +0 -973
- package/dist/src/chunk-nwm2pq5v.js +0 -168
- package/dist/src/chunk-pm06b05d.js +0 -9
- package/dist/src/chunk-q50s00ry.js +0 -4
- package/dist/src/chunk-qwye1958.js +0 -14
- package/dist/src/chunk-r8z9pfve.js +0 -5
- package/dist/src/chunk-rdpgkjf6.js +0 -4
- package/dist/src/chunk-rkr0dks9.js +0 -5
- package/dist/src/chunk-rn84t3sf.js +0 -11
- package/dist/src/chunk-s123kn7n.js +0 -4
- package/dist/src/chunk-s73qn3fx.js +0 -4
- package/dist/src/chunk-sjn0nj4p.js +0 -5
- package/dist/src/chunk-sns0c35v.js +0 -7
- package/dist/src/chunk-t4dr5c8v.js +0 -8
- package/dist/src/chunk-tc8k9c1j.js +0 -4
- package/dist/src/chunk-teznhase.js +0 -4
- package/dist/src/chunk-ty9xgmz4.js +0 -4
- package/dist/src/chunk-tyazf3sk.js +0 -145
- package/dist/src/chunk-v6npjrjm.js +0 -5
- package/dist/src/chunk-vbvtzkwz.js +0 -5
- package/dist/src/chunk-vefd8qee.js +0 -8
- package/dist/src/chunk-vs9r72ta.js +0 -17
- package/dist/src/chunk-w88k0bgr.js +0 -4
- package/dist/src/chunk-wzdt0enk.js +0 -4
- package/dist/src/chunk-xhhv854c.js +0 -4
- package/dist/src/chunk-y58270hd.js +0 -4
- package/dist/src/chunk-yk0hmbex.js +0 -4
- package/dist/src/chunk-ympy4fdz.js +0 -28
- package/dist/src/chunk-yw436axy.js +0 -4
- package/dist/src/chunk-z04jrpjy.js +0 -5
- package/dist/src/chunk-z2xznczw.js +0 -4
- package/dist/src/chunk-z4xnrgps.js +0 -4
- package/dist/src/chunk-z7csyszv.js +0 -4
- package/dist/src/chunk-z8t0v07j.js +0 -11
- package/dist/src/chunk-z916af47.js +0 -228
- package/dist/src/chunk-zcr8he8q.js +0 -5
- package/dist/src/chunk-zd9vmkzn.js +0 -9
- package/dist/src/chunk-zj939v0h.js +0 -5
- package/dist/src/chunk-zkdjwtc1.js +0 -4
- package/dist/src/chunk-zkv5kzt6.js +0 -4
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{i,Wt,xd,cr,te,qt,l,e}from"./chunk-z637nqg8.js";import{ra,sr,TT,Rv,kT,_m,oa,Po,zi,vn,Cm,Dm,bc,bn,Ao,CT,Oa}from"./chunk-0qsy1qsx.js";import{rd,J,wn,z,L,ni,o,ao,ud,Jo,hR,pr,dt,gR,kn,$B,N,pa,ft,Tt,Mt,$t,wi,VB,pt,Us,nt,K,oj,Gne,lb,sj,tf,Eu,ve,md,Pl,ma,fd,Ri,ub,Ur,fr,BR,Ee,Zt,hr,O$,_l,aO,p9,un,qr,Wg,hf,As,Ji,ir,Vie,lO,zj,jj,zie,U$,jie,Zk,mO,eP,gf,tP,Eb,In,lr,w9,r2,n2,vO,i2,vf,x,Ce,E,Ws,Xi}from"./chunk-r5bxavdx.js";import{xV,Wee,KF,Am,Tm,rp,x5}from"./chunk-vy3bwm1d.js";import{Np}from"./chunk-4hw3665t.js";import{Oe,Kt,At}from"./chunk-3xkpk44w.js";import{IC,dL,lL,uL,pL,mL,wT,jV,ste,qh}from"./chunk-7rz9898k.js";import{Qc}from"./chunk-ycaj2sgf.js";import{Kc,IF,S5,uv,_F,SV,tp,xee,Gc,wV,Cee,So,xF,Dee,Pm,Oee,Mee,CF,cC,DF,OF,MF,NF,FF}from"./chunk-w7hkv422.js";import{lte}from"./chunk-qyqypn28.js";import{oW,ds,Ca,Wh,hte,vr,Wi,bL}from"./chunk-fgb98zjj.js";import{MT,wc,tg,rg,jte,Sn,kw,Ew,Iw,WL,yi,ca,ng,$W,Iv,zL,La}from"./chunk-rvvy1bte.js";import{r,t,u,St}from"./chunk-rbpdk7m0.js";import{AsyncLocalStorage as Dt}from"async_hooks";var Fe=new Dt;function dT(n,a){return n?Fe.run(n,a):a()}function aC(){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&&pt(d)>pt(s.bounds)?c:s},n)}function Nt(n,a){return Ve(n,a)||a.checkable==="true"&&Be(a,[n])===n}function re(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 Lt(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=_m(await n.hierarchy(s));s?.throwIfAborted();let p=new K().flattenViewHierarchy(d).map(({element:S})=>S),h=p.find((S)=>S.focused==="true"),m=Lt(p,h),f=c?p.filter((S)=>re(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:pt(S.bounds),order:O,interactive:!1})).sort(gf).map(({element:S})=>S),T=c?f[c.ordinal]:tP(b,(S)=>Be(S,y))[a.index??0];if(!T||c)return{focus:h,target:T,identity:c,signature:m};let v=re(T),g=p.filter((S)=>re(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 zt(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 Ut(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 Gt(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 zt(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 oa(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 Gt(f,v,p),{focus:O,target:R}=S;if(v=S.identity,Nt(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.`);Ut(g,d,R),await y.request({type:"request_press_button",action:A},s),T={signature:S.signature,direction:A}}}var jt=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)=>jt.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 Oa&&n.errorCode==="command_failed"&&n.message.startsWith("No focused text field")}async function Yt(n,a,s,c){await new wn(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=Po.require(n);if(s!==void 0)await xV(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 Qt(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 Qt(a),kT(n,s,()=>tr(n,a,s))}async function tr(n,a,s){let c=await Rv(n,s),d=TT(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 Rv(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 xV(n.deviceId,a,s);default:return}}function Eee(n,a,s,c={}){return(n.platform==="watchos"?We:n.platform==="visionos"?qe:lte)(n.deviceId,a,s,c)}var P=3;function V(n,a,s,c){let d=nt(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(In(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 wi(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&&wi(n.element.bounds,a.element.bounds,P)&&La(n.element)===La(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 VB(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)&&wi({...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&&In(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 dw=Symbol("tapFocusFailure"),TF=Symbol("tapResolvedLayer");function B(n,a,s){if(!ma(n))return;n=wV(a,n,s);let c=nt(a);if(!c)return;let d=new K;for(let p of["prototype","app"])if(d.flattenViewHierarchy(fd(n,p),{includeWindows:!0}).some((m)=>nt(m.element)===c))return p;return}function D(n,a){if(a!==void 0)Object.defineProperty(n,TF,{value:a,enumerable:!1,configurable:!0,writable:!0});return n}function I(n,a,s){if(n==="focus"&&s instanceof So)Object.defineProperty(a,dw,{value:s.reason});return a}class Rm 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,mL(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=uL(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(),Sn(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?yi(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,()=>jV(this.host.device(),{success:!0})),jV(this.host.device(),m),{success:m.success,error:m.error,warning:m.warning}}return{success:!1,error:St(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&&nr(s.filter((p)=>p["resource-id"]===d)).length===1}let c=yi(n);return c!==void 0&&s.filter((d)=>tf(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 nr(n){let a=n.filter((s)=>{let c=nt(s);return!c||!$B(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 So("Element not found on selected display","not-found");let f=this.host.buildSelectedElementMetadata(p),y=B(h,m,te(this.host.device().platform,"tapOn"));if(n.action==="focus"){if(!In(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(La(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 So("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(aC(),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?rg(n.displayId):void 0;if(c)throw c;return{enabled:s,warnings:a}}async androidDisplayDispatch(n,a){return WL(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&&!In(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)=>bL(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},{...Kt.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 Zt({...n,success:!1,error:void 0},new fr(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(BR(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 Wi(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 Zt(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 fr(n):n}rethrowKeyboardOcclusion(n,a,s){if(s?.throwOnKeyboardOcclusion&&this.host.strategy().rethrowsKeyboardOcclusion&&a==="focus"&&n instanceof Rm)throw e.debug(`Tap on element awaits IME recovery: ${r(n)}`,n),n}}function ar(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 or(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}=or(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 dr(n,a){if(!n?.bounds||!a.bounds||ar(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 ur(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=dr(a.matchedElement??a.element??void 0,s);return c?[c]:[]}function et(n,a){if(a&&n.effect?.screenChanged===!1)n.warnings=[...n.warnings??[],ur(a.matched,n.element)]}function mr(n,a,s){if(n.warnsOnDisabledElement&&xd(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 te(this.host.device().platform,"tapOn")}async executeWithReadScope(n,a={}){let{progress:s,signal:c,recovery:d,settlePostTapEffect:p}=a,h=zL(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},...Kt.selectorResolvedGesture,display:n.display,timeoutMs:At.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(Mee(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 fr)return Zt(this.host.createErrorResult(n.effectiveAction,h.message),h);let m=jte(a)?await KF(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 uv(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&&!Dm(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 uv(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(zi,p?.requestDeadlineMs===void 0?zi: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(!In(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(La(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;mr(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,...yr(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;aC(),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}},...Oee(n)},isTalkBackEnabled:a.isAccessibilityServiceEnabled})},ios:async()=>{let h=this.host.iosSdkBridgeTapper?.()??Wee(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")O$(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:kn(n.actions,"long_click")}}detectLongPressMetadata(n,a){return this.host.longPressMetadataDetector().detect(n,a)}}function yr(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 OF(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 ${cC}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 CF(()=>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(ds(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 Pm();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 tg({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=yi(n);if(!kn(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 kw(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 wc(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=tp(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(DF),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??[$W]:[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:ft(n?.resolvedHierarchy),reResolve:p?(h)=>{let m=this.host.finder().selectElementInHierarchy(n,Ri(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 wT(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 Iw(f,{x:a,y:s},{durationMs:m,options:{signal:h}}),x.getExistingInstance(this.host.device().deviceId)?.invalidateCache();else p?.assertCurrent(),await Ew(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 ste({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(pL(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=yi(c);if(f&&await this.host.trySemanticAndroidLongPress(c,f,d,h))return}await _F({adb:this.host.adb(),x:n,y:a,durationMs:s,signal:d,assertCurrent:m?()=>m.assertCurrent():void 0,logTag:"TapOnElement"})}throwIfLongPressInterrupted(n,a,s){IC(n,a,s)}semanticAndroidLongPressTargetError(n,a,s={}){let c=ft(s.resolvedHierarchy);return ng(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=ca(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 MT({advertised:kn(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 Tr=3,br=new ve;function rt(n){return typeof n==="string"&&n.trim()!==""?n.trim():void 0}function gr(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=rt(n.properties["hint-text"]),s=rt(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 it(n,a){if(!n)return[];let s=new Set;return br.project(n).filter((c)=>{if(s.has(c.source))return!1;return s.add(c.source),c.affordances.includes("input")&&!Eu(c)&&gr(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,Tr).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 lt=2500,ut=8,me=1e4,Rr=32,wr=1000,ct=12,Ar=150;function Pr(n,a,s){let c=s.viewHierarchy?n.findElementInHierarchy(a,s.viewHierarchy).selection:null;return c?.matchedElement??c?.element??null}function kr(n,a,s){if(++n.iterations>wr)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 xr(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 Cr(n,a,s){if(ot(s,n.elementParser)&&a.budgetMs<me)a.budgetMs=me,a.minProductivePolls=Rr,e.info(`[TapOnElement] Android pre-tap: loading/progress indicators present; extending refind budget to ${a.budgetMs}ms / ${a.minProductivePolls} polls`)}function Fr(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 Dr({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&&wi(n.prevBounds,p,P))n.consecutiveStable++;else n.consecutiveStable=1;n.prevBounds=p;let h=qr(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 Ir(n,a,s,c){s.consecutiveNoHierarchy=0,s.refindAttempt++,Cr(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=Fr(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 Dr({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=Pr(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:lt,minProductivePolls:ut,consecutiveNoHierarchy:0,refindAttempt:0,firstIteration:!0,iterations:0,deadlineGracePolls:m};while(!0){if(o(p),!kr(b,n.timer,m))break;if(!b.firstIteration){let S=b.consecutiveNoHierarchy>0,O=S?S5:Ar;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})(IF);if(!v){let S=xr(b,n.timer,T);if(S)return S;continue}let g=Ir(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 fe{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:un(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:un(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:un(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 Hr=1500,yt=50,Vr=1500,Br=100,Nr=12000;function Lr(n,a,s){let c=n.action==="focus"&&a?it(a.viewHierarchy,a.screenSize):[];return c.length>0?{baseError:`${s}. ${at(c)}`,reason:"not-found-inputs-listed"}:{baseError:s,reason:"not-found"}}class ye{host;constructor(n){this.host=n}getSearchUntilDuration(n){return dL(n.searchUntil?.duration,{defaultMs:Vr,minMs:Br,maxMs:Nr})}hashViewHierarchy(n){return bn(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=Ri(a,n.layer);try{return this.host.finder().selectElementInHierarchy(n,a)}catch(s){if(n.action!=="focus"||!(s instanceof t)||s instanceof So||!ds(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()+Hr;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(MF(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),As(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 hr(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 NF({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 ve,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=qr(a)?.captureId??"before-refresh",m=qr(s)?.captureId??(a===s?h:"after-refresh");return new lr().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&&!ma(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&&xF(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 Dee(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 FF({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))Ri(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=gR(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}=Lr(n,a,h);if(d?.onlyKeyboardKeyMatch)throw new So(`${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 Tm(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 So(y,f)}throw new So(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 SV(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)||kn(n.actions,"click")}isLongClickableElement(n){return dt(n["long-clickable"])||dt(n.longClickable)||kn(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 ve().project(a),p=Gc(d,n),h=p?Eb(p,d,{action:s==="longPress"?"long-press":"tap"}):null;if(h?.element)return{element:h.element,usedParent:!Mt(h.element.bounds,n.bounds)};return{element:n,usedParent:!1}}}var Mr={tap:"tap",doubleTap:"tap",longPress:"tap",focus:"focus-input"};class Te{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 So(s.message,"not-found");let d=c.element??c.matchedElement;if(c.totalMatches===1&&d&&In(d)&&this.deps.tapPoints.isElementTapTargetOffScreen(c,a,this.deps.tapPoints.getScreenSizeFromHierarchy(a,n.screenSizeOptions),n))throw new So(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":ds(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 So(SV(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 So(`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":Mr[n.action]}isContainerAvailable(n,a){return lL(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:oW(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 _r=25;function zr(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 Iee(n,a,s){let c=Qc(n,a,s,"hitTest");if("error"in c)throw new t(c.error);let d=a.viewHierarchy?_l(new ve().project(a.viewHierarchy)):[],p=aO(d,c).slice(0,_r).map(zr),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 Us,c=Pl(n).filter((h)=>h.hierarchy).flatMap((h)=>s.extractWindowRootGroups({hierarchy:{},windows:[h]})[0]),d=n.hierarchy.node&&sj(lb,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 Wr(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=Wr(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 be(n,a,s){let c=bt(n,!0);if(!a||!c?.visibilityKnown||!n.screenHeight||n.screenHeight<=0||c.top<=s.top)return s;return $t(s,{...s,top:Math.max(0,c.top)})}var Gr="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 $r(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:Gr}}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 $r(h,d);return{kind:"proceed",point:{x:d.x,y:Math.floor((f+y)/2)}}}function Kr({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=Gc(new ve().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:i2}),h=p.success?r2(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 md().collect(wV(n,a,c),c),p=d&&mO(d,n);return p&&c==="ios"?Zk(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=Gc(new ve().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=eP([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&&!tp(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 Rm(`Target ${O} is covered by the soft keyboard; dismiss the keyboard first.`)}isElementTapTargetOffScreen(n,a,s,c){if(!As(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 So(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=$t(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=xee(m)?h:p,y=hf(p.bounds,s,f.bounds);if(!y||!As(s)||this.deps.device.platform!=="ios")return y;let b=new ve().project(a),T=zj(b,s,a);if(T&&this.prototypeBarGuardHandlesLegacyInsets(a,Gc(b,p)?.source))T.statusBarTop=0;return jj({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=tp(d,s)?d:p?this.resolveImeSafeTapPoint(n,a,c,s):this.deps.geometry().getElementCenter({bounds:s}),A=p9(a,n,s,{point:w,imeBounds:p&&{left:p.bounds[0],top:p.bounds[1],right:p.bounds[2],bottom:p.bounds[3]},ownWindows:Cee(c.options.layer),views:!0});if(!A.point)throw new So(Kr(A),"no-visible-tap-area");return A.point}let h=new ve().project(a),m=Gc(h,n),f=this.barSafeIosVisibleBounds(a,m,s,d),y=f!==s,b=p?eP([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=zie(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=U$({nodes:h,target:m,matched:v.flatMap((w)=>{let A=Gc(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)&&tp(w,f)&&tp(w,n.bounds)&&(!O||!tp(w,O))&&(!As(c.screenSize)||!Vie({point:w,hierarchy:a,screen:c.screenSize,elements:v}))});if(this.assertBarClippedIosTapPoint(y,R.point,d),R.coveredBy)throw new So(jie(n,R.coveredBy,R.ownerInsideScrollContainer),"no-visible-tap-area");return R.point}getScreenSizeFromHierarchy(n,a={}){return Ji(n,{...a,platform:te(this.deps.device.platform,"tapOn"),iosMultiPanel:this.deps.device.platform==="ios"&&(this.deps.device.displays?.panels.length??0)>1})}hostControls(n){return new ve().project(n).flatMap((a)=>oj(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=Gne({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=be(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 ve().project(n),f=Gc(m,a),y=be(n,H(n,f?.source),s);if(y!==s){let b=y&&U$({nodes:m,target:f,matched:[Gc(m,X(c,a,d))].flatMap((T)=>T?[T]:[]),screen:p,visibleBounds:y,candidates:[h],isValid:(T)=>T!==null&&tp(T,y)&&tp(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&&tp(y,{left:b.bounds[0],top:b.bounds[1],right:b.bounds[2],bottom:b.bounds[3]}))throw new Rm("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)=>!oj(p["resource-id"])&&tp(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 ub(c,n.layer,v,"tap"),{tapPoint:v,...T.warning?{warning:T.warning}:{}}}}import{posix as Xr}from"path";var Et="Library/AutoMobile/prototype-endpoint.json";function jr(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)&&Object.getPrototypeOf(n)===Object.prototype}function Ot(n){let a;try{a=JSON.parse(n)}catch{throw new t("The viewer wrote an invalid endpoint file: expected JSON.")}if(!jr(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 Rt=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 rd(w9,{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===Rt)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 bV{viewer;injected;constructor(n,a){this.viewer=n;this.injected=a}get(n){return this.viewer.get(n)??this.injected.get(n)}}var{join:Yr}=Xr,lT=new Y;class wt{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(Yr(c,Et));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}=Ot(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(Np))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 _ee(n={}){let a=n.simctl??new L,s=n.files??new Ur,c=n.connector??new vO;return new wt({containers:{dataContainer:async(d,p)=>{try{return await Jo({...n.containerOwnership,deviceId:d,bundleId:p,run:(h)=>a.executeCommandArgs(h)})}catch(h){if(h instanceof ao)return e.debug("Simulator returned an empty prototype viewer data container path"),"";if(h instanceof ud)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 n2({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??lT})}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 Jr(n,a){return n.length===a.length&&n.every((s,c)=>s===a[c])}function Qr(n,a){for(let s=n.parentIndex;s!==void 0;s=a[s].parentIndex)if(a[s].className==="WKWebView")return!0;return!1}function Zr(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 ei(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&&wi(n.bounds,a.bounds,d))}function ti(n,a,s,c){let d=k(a.filter((f)=>f.element&&In(f.properties)&&!Qr(f,a))),p=d.filter((f)=>f.className===n.class);if(p.length!==1)return;let h=p[0].element;if(!Zr(n,h)&&!ei(n,h,a,s)||d.some((f)=>f.element!==h&&La(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&&In(m.properties)&&La(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))&&VB(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&&In(p.properties)&&La(p.element))),d=c.length===1?c[0].element:void 0;return d&&wi(n.bounds,d.bounds,P)&&!this.focusIdentitySignals(n,d,s).conflict?d:void 0}focusProjection=new ve;attachedFocusLabels=new WeakMap;attachedFocusLabel(n){let a=nt(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&&!In(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(!In(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&&In(A.properties)));if(h.filter((A)=>wi(A.element.bounds,a.bounds,P)).length!==1)return!1;let f=d?this.focusProjection.project(ft(d)):[],y=k(f.filter((A)=>A.element&&In(A.properties))),b=y.filter((A)=>A.source===nt(n)||A.className===n.class&&wi(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=wi(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&&nt(h),f=p.find((y)=>y.source===m);return Boolean(h&&In(h)&&f&&p.some((y)=>y.element&&In(y.properties)&&La(y.element)&&V(h,y.element,p,f))&&h[c.key]===c.value&&a.class===h.class&&VB(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?pt(m.bounds):1/0,order:m.index,interactive:!0});if(p)return s.filter((m)=>m.nodeKey===c.value&&!m.nativeId&&m.element&&In(m.properties)).sort((m,f)=>gf(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&&In(a.properties)&&La(a.element)&&V(n,a.element,s))}isRefoundFocusTarget(n,a,s){let c=this.deps.findElementInHierarchy(n,s).selection.element;return Boolean(c&&In(c)&&La(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=ft(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=nt(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&&In(T.properties)&&!this.focusIdentitySignals(n,T.element,s).conflict&&Jr(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&&In(T.properties)&&La(T.element));return k(y).length===1&&y.every((T)=>La(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(ft(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(ti(s,d,f,p));if(y)return d.some((v)=>v.element&&In(v.properties)&&La(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],ri=Wt(kt),ii=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})(cC);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()+ii,h=n();for(let m=1;this.host.timer.now()<p;m++){o(d);let f=Math.min(ri.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(cC,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=un(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=un(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=Kc,oi=150;class kF{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 CT(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=pr(a),c=a.class??a.className??"",d=Tt(qt(n)),p=d?`${d.left},${d.top},${d.right},${d.bottom}`:"",h=hR(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=pr(c).toLowerCase(),p=(c.class??c.className??"").toLowerCase(),h=hR(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=ni,c){this.device=n;this.adb=a;this.accessibilityDetector=s;this.featureFlags=c}prepareViewHierarchyForResponse(n,a,s){let c=a.filterViewHierarchy(n);return pa(c,n),c}clipNavigationTapBounds(n,a,s,c){return{bounds:n}}async isAccessibilityServiceEnabled(n){let{talkBack:a,unconfirmed:s}=await Wh(this.accessibilityDetector,this.device.deviceId,this.adb,this.featureFlags);if(s)n?.(Ca);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=bc(a,n.screenSize)}constructor(n,a=Ao,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 pa(c,n),c}clipNavigationTapBounds(n,a,s,c){if(!As(s))return{bounds:n};return lO({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 qh(c),f=n.talkBackStrategy??new Iv({timer:p,driverFactory:m}),y=n.iosVoiceOverDetector??Ao,b=n.featureFlags??sr.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}},li={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 cr(n)?ci[n]:li}class gc 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 ye({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)=>ra({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 St(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)=>ra({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 Te({device:this.device,elementSelector:()=>this.elementSelector,tapPoints:this.tapPoints});settler=new fe({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)=>lT.get(d,p)??vf.getRecord(d,p)?.client},this.waitForCondition=s.waitForCondition??new kF(this.observeScreen,this.timer),this.geometry=new ir,this.elementParser=new K,this.accessibilityService=Ws(n,this.adbFactory),this.visionConfig=s.visionConfig||Am,this.screenshotCapturer=s.screenshotCapturer??new rp(n,this.adbFactory),this.visionAnalyzer=s.visionAnalyzer,this.viewHierarchy=new Xi(n,this.adbFactory),this.hierarchyCapture=s.hierarchyCapture??new Wg(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 vn(n,{adbFactory:this.adbFactory,timer:this.timer}).capture(d)).hierarchy;let p=await this.readFreshHierarchy(d.timeoutMs??IF,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 x5({screenshotCapturer:this.screenshotCapturer}),this.accessibilityDetector=s.accessibilityDetector||ni,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 vr(void 0,void 0,{platform:ae(this.device.platform)?"ios":te(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 hte(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 Cm(()=>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{dT,aC,Eee,dw,TF,Rm,Iee,bV,lT,_ee,kF,gc};
|
|
7
|
+
|
|
8
|
+
//# debugId=A9D1B93F6A7CDA3664756E2164756E21
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{i,Ub,$O,_d,Ef,Zi,l,e}from"./chunk-z637nqg8.js";import{f,I,lt,Be,bU}from"./chunk-58wzr3mt.js";import"./chunk-yf7ympyz.js";import"./chunk-5d2hft6c.js";import{wA,GI,V7,ih,CS,Dt,c0,j7,K7,G7,DS,d0,Hc,i_,o_,v0,qc,R0,aQ,dm,dQ,lQ,P0,a_,Vc,A0,T0,Yu,k0,Vq,mQ,vQ,AQ,c_,TQ}from"./chunk-hrfytkxh.js";import{R,Nre,lD,Vv,Wv,Zw,zv,Zre,Qre,AB,tk,Q3,Pi,Hs,kk,xR,ZB}from"./chunk-r5bxavdx.js";import{Ol}from"./chunk-4hw3665t.js";import{D3}from"./chunk-v6pya0dm.js";import"./chunk-0qsy1qsx.js";import{r}from"./chunk-rbpdk7m0.js";function Q(t,o){return{refresh:()=>t.refresh({fresh:!0,requireCurrent:!0,refuseUpgradePending:!0}),isAutoMobileOwned:(n)=>t.stableIdsFor("ios").has(n)||(o()?.getAssignedDevices().has(n)??!1)}}V7(Q(wA(i),()=>R.sessionManager()));Zre({androidColdBootAdmitter:()=>ih().android,iosBootInstrumentation:()=>{let t=ih();return GI({timer:i,history:t.iosBootHistory,gate:t.ios})},assertBootCapacityAvailable:(t,o)=>CS(t,o)});var Ve=500;function U(t){return t.success&&!t.error?void 0:{code:t.errorCode??"restore_failed",reason:t.error??"Device refused saved prototype restore"}}async function $e(t,o){let n=t.assets.filter((a)=>a.bytes===void 0||a.mimeType===void 0);if(n.length>0)return{code:"asset_unavailable",reason:`Missing mirrored assets: ${n.map((a)=>a.id).join(", ")}`};for(let a of t.assets){if(a.bytes===void 0||a.mimeType===void 0)continue;let s=U(await o.putAsset({id:a.id,mimeType:a.mimeType,bytes:a.bytes}));if(s)return s}return U(await o.save({spec:t.spec,label:t.label,icon:t.icon}))}async function We(t,o){try{return await $e(t,o)}catch(n){return e.warn(`[PROTOTYPE] Restore failed for ${t.id}`,n),{code:"restore_failed",reason:r(n)}}}async function X(t,o,n){let a={restored:[],skipped:[],failed:[]};try{let s=await o.list(t);if(s.length===0)return a;let d=[];try{let u=await n.list();if(!U(u))d=(u.savedPrototypes??[]).filter((v)=>!v.hostOnly);else e.warn(`[PROTOTYPE] Device saved prototype list failed for ${t}`,u)}catch(u){e.warn(`[PROTOTYPE] Device saved prototype list failed for ${t}`,u)}let c=Q3(s,d),p=new Set(c.map((u)=>u.id));a.skipped=s.filter((u)=>!p.has(u.id)).map((u)=>u.id);for(let u of c){let v=await We(u,n);if(v)a.failed.push({id:u.id,...v}),e.warn(`[PROTOTYPE] Restore failed for ${u.id}`,v);else a.restored.push(u.id)}}catch(s){e.warn(`[PROTOTYPE] Saved prototype restore failed for ${t}`,s),a.failed.push({id:"*",code:"restore_failed",reason:r(s)})}return a}class V{device;timer;resolveClient;timeoutMs;ready;constructor(t,o=i,n=async()=>{let{AndroidCtrlProxyClient:s}=await import("./chunk-ppfr0b8h.js");return s.getExistingInstance(t.deviceId)??s.getInstance(t)},a=20000){this.device=t;this.timer=o;this.resolveClient=n;this.timeoutMs=a}async client(){if(this.ready)return{client:this.ready};let t=!1;try{let o=await l(async()=>{let n=await this.resolveClient();while(!t){let a=await n.ensureConnected().catch((s)=>(e.warn("[PROTOTYPE] Restore connection attempt failed",s),!1));if(t)break;if(a)return(await n.getSupportedCommands())?.includes(Ol)?{client:n}:{failure:this.unsupported()};await this.timer.sleep(Ve)}return{failure:this.unavailable()}},{timer:this.timer,timeoutMs:this.timeoutMs,label:"Saved prototype restore connection",onTimeout:()=>{t=!0}});if(o.client)this.ready=o.client;return o}catch(o){return e.warn("[PROTOTYPE] Restore connection unavailable",o),{failure:this.unavailable(r(o))}}}unavailable(t=`Saved prototype restore connection timed out after ${this.timeoutMs}ms`){return{success:!1,errorCode:"service_unavailable",error:t}}unsupported(){return{success:!1,errorCode:"device_unsupported",error:`Device does not advertise ${Ol}`}}async list(){let{client:t,failure:o}=await this.client();return t?t.requestListSavedPrototypes():o}async putAsset(t){let{client:o,failure:n}=await this.client();return o?o.requestPutPrototypeAsset(t):n}async save(t){let{client:o,failure:n}=await this.client();return o?o.requestSavePrototype(t):n}}Qre({createForeignForwardEvidence:(t)=>AB(t),savedPrototypes:()=>{let t=tk();return{list:(o)=>t.list(o),restore:(o,n)=>X(o.deviceId,t,new V(o,n))}}});function Z(t){let o=t.findIndex((a)=>["--cli","--daemon","--boot-device","--ios-network-filter","--ios-templates"].includes(a)),n=o>=0?t.slice(0,o):t;return n.includes("--help")||n.includes("-h")}function ee(t,o){if(!t)return!1;let[n]=o;return n===void 0||n==="help"||n==="--help"||n==="-h"}async function te(t){if(Z(t)){let{runCliCommand:s}=await import("./chunk-8zgzzs7k.js");await s(["help"]),process.exit(0)}let o=t.indexOf("--boot-device");if(o>=0){let{runBootDeviceCommand:s}=await import("./chunk-m94qs0f0.js");Dt.endPhase("moduleImports"),await s(t.slice(o+1)),process.exit(0)}let n=t.indexOf("--ios-templates");if(n>=0){let{runIosTemplatesCommand:s}=await import("./chunk-g04bwyj3.js");Dt.endPhase("moduleImports"),process.exit(await s(t.slice(n+1)))}let a=t.indexOf("--ios-network-filter");if(a>=0){let{runIosNetworkFilterCommand:s}=await import("./chunk-8ph29g99.js");Dt.endPhase("moduleImports"),process.exit(await s(t.slice(a+1)))}}async function oe(t){let{createStdioServerTransport:o}=await import("./chunk-3y6eykz9.js"),{OutputGatedTransport:n}=await import("./chunk-xgan0qqp.js"),{createMcpServer:a,registerMcpTools:s}=await import("./chunk-ddzkz92z.js"),{createDaemonMcpProxy:d,createProxyMcpServer:c}=await import("./chunk-7j5vj4pa.js"),{logger:p,LogLevel:u}=await import("./chunk-rpvckv3p.js");t(p);let{runCliCommand:v,cliCommandSkipsServerBootstrap:y}=await import("./chunk-8zgzzs7k.js"),{runDaemonCommand:w}=await import("./chunk-7zy586cb.js"),{startDaemon:g}=await import("./chunk-5tm9mn47.js"),{guardDatabaseStartup:h}=await import("./chunk-zs1sghs9.js"),{DefaultDatabaseInitializer:M}=await import("./chunk-r8jf3d92.js"),A=await import("./chunk-fbakd6cw.js"),m=await import("./chunk-c1vs4g1n.js"),P=await import("./chunk-pcsen2vs.js"),b=await import("./chunk-t7w8rctc.js"),C=await import("./chunk-rhcty4ms.js"),x=await import("./chunk-bfjwqk8q.js"),{FeatureFlagService:E}=await import("./chunk-q10bdnat.js"),{serverConfig:D}=await import("./chunk-t6bfvfkg.js"),{AndroidCtrlProxyManager:L}=await import("./chunk-eggq53ks.js"),{IosCtrlProxyBuilder:F}=await import("./chunk-j4yjzbak.js"),{IOSCtrlProxyManager:_}=await import("./chunk-6ep7f5ge.js"),{cleanupDaemonChildProcesses:N}=await import("./chunk-r2epb56s.js"),{stopManagedAdbServer:B}=await import("./chunk-w4zga19f.js");return Dt.endPhase("moduleImports"),{createStdioServerTransport:o,OutputGatedTransport:n,createMcpServer:a,registerMcpTools:s,createDaemonMcpProxy:d,createProxyMcpServer:c,logger:p,LogLevel:u,runCliCommand:v,cliCommandSkipsServerBootstrap:y,runDaemonCommand:w,startDaemon:g,guardDatabaseStartup:h,DefaultDatabaseInitializer:M,startVideoRecordingSocketServer:A.startVideoRecordingSocketServer,stopVideoRecordingSocketServer:A.stopVideoRecordingSocketServer,startDeviceGestureRecordingSocketServer:m.startDeviceGestureRecordingSocketServer,stopDeviceGestureRecordingSocketServer:m.stopDeviceGestureRecordingSocketServer,startDeviceSnapshotSocketServer:P.startDeviceSnapshotSocketServer,stopDeviceSnapshotSocketServer:P.stopDeviceSnapshotSocketServer,startAppearanceSocketServer:b.startAppearanceSocketServer,createDirectModeAppearanceDeviceSource:b.createDirectModeAppearanceDeviceSource,stopAppearanceSocketServer:b.stopAppearanceSocketServer,startWebRtcStreamSocketServer:C.startWebRtcStreamSocketServer,stopWebRtcStreamSocketServer:C.stopWebRtcStreamSocketServer,stopAppearanceSyncScheduler:x.stopAppearanceSyncScheduler,FeatureFlagService:E,serverConfig:D,AndroidCtrlProxyManager:L,IosCtrlProxyBuilder:F,IOSCtrlProxyManager:_,cleanupDaemonChildProcesses:N,stopManagedAdbServer:B}}import{readFileSync as Ge}from"fs";import{parseArgs as He}from"util";var Ke=Object.fromEntries(["cli","daemon-mode","no-proxy","direct","no-daemon","debug-perf","ui-perf-debug","debug","no-ui-perf-mode","mem-perf-audit","accessibility-audit","predictive","predictive-ui","raw-element-search","embedded-sdk","network-mockable","dismiss-keyboard-after-input","tool-call-recording","no-navigation-screenshots","no-waitfor-polling-overhead","no-include-not-important-views","no-report-view-ids","no-retrieve-interactive-windows","no-occlusion","strict-port","headless"].map((t)=>[t,{type:"boolean"}])),G={...Ke,"daemon-socket-path":{type:"string"},"enable-tool":{type:"string",multiple:!0},"disable-tool":{type:"string",multiple:!0}},qe=[...Object.entries(G).filter(([,t])=>t.type==="string").map(([t])=>`--${t}`),Vc,i_,o_];function ze(t,o){return t||Be(f.HEADLESS,o)}function re(t,o,n=process.env,a=(s)=>Ge(s,"utf8")){let{values:s}=He({args:t,options:G,allowPositionals:!0,strict:!1}),d=(J)=>{let O=s[J];if(O===void 0)return!1;let j=O===!0?!0:Hs(String(O));if(j===void 0)o.warn(`Invalid value for --${J}: ${String(O)}; expected true or false`);return j===!0},{enabledTools:c,disabledTools:p}=Ye(s,n),u=d("cli"),v=d("daemon-mode"),y=d("no-proxy")||d("direct"),w=d("no-daemon"),{daemonRequested:g,daemonCommand:h,daemonArgs:M}=ct(t),A=d("debug-perf")||d("ui-perf-debug")||Be(f.DEBUG_PERF,n),m=d("debug")||Be(f.DEBUG,n),P=d("strict-port"),b=ze(d("headless"),n),C=!d("no-ui-perf-mode"),x=d("mem-perf-audit"),E=d("accessibility-audit"),D=d("predictive")||d("predictive-ui"),L=d("raw-element-search"),F=ZB(t),_=d("embedded-sdk"),N=d("network-mockable"),B=d("dismiss-keyboard-after-input"),Ae=T0(t,process.env),Re=A0(t),Ce=d("tool-call-recording"),Me=!d("no-navigation-screenshots"),xe=d("no-waitfor-polling-overhead"),Oe=d("no-include-not-important-views"),ke=d("no-report-view-ids"),Te=d("no-retrieve-interactive-windows"),Ee=d("no-occlusion"),De=k0(t,process.env),Ie=v0(t,process.env,_d()),Le=dt(n,o),Y=Je(o),{videoRecordingDefaults:Fe}=Y,_e=t.indexOf("--cli"),Ne=u?t.slice(_e+1):[],S=je(t,o,Y,Le),Ue=dQ({flagValue:S.sessionConfigValue,envValue:u||v||g?void 0:n[aQ],readFile:a,hasInitialSessionUuid:S.initialSessionUuid!==void 0,noProxy:y});return{cliMode:u,cliArgs:Ne,invalidInvocation:S.invalidInvocation,daemonPort:S.daemonPort,daemonHost:S.daemonHost,initialSessionUuid:S.initialSessionUuid,livenessOwnerToken:S.livenessOwnerToken,sessionConfig:Ue,debugPerf:A,debug:m,strictPort:P,headless:b,uiPerfMode:C,memPerfAuditMode:x,a11yAuditMode:E,a11yLevel:S.a11yLevel,a11yFailureMode:S.a11yFailureMode,a11yMinSeverity:S.a11yMinSeverity,a11yUseBaseline:S.a11yUseBaseline,predictiveUi:D,rawElementSearch:L,planExecutionLockScope:S.planExecutionLockScope,planExecutionLockScopeExplicit:S.planExecutionLockScopeExplicit,videoRecordingDefaults:Fe,runnerReadinessTimeoutMs:S.runnerReadinessTimeoutMs,daemonMode:v,daemonRequested:g,daemonCommand:h,daemonArgs:M,skipCtrlProxyDownload:F,embeddedSdk:_,networkMockable:N,dismissKeyboardAfterInput:B,eventAllMarkers:Ae,eventAllMarkersCliOverride:Re,toolCallRecording:Ce,navigationScreenshots:Me,noWaitForPollingOverhead:xe,noProxy:y,noDaemon:w,noA11yIncludeNotImportantViews:Oe,noA11yReportViewIds:ke,noA11yRetrieveInteractiveWindows:Te,noOcclusion:Ee,outputReduction:De,toolOutputsDir:Ie,enabledTools:c,disabledTools:p}}function Ye(t,o){let n=Object.keys(o).find((m)=>bU(m));if(n)throw Error(`${n} is retired; use AUTOMOBILE_ENABLED_TOOLS or AUTOMOBILE_DISABLED_TOOLS.`);let a=(m)=>{let P=t[m];if(Array.isArray(P))return P.filter((b)=>typeof b==="string");return typeof P==="string"?[P]:[]},s=Array.from(new Set(a("enable-tool"))),d=Array.from(new Set(a("disable-tool"))),c=new Set(d),p=s.find((m)=>c.has(m));if(p)throw Error(`Tool '${p}' cannot be both enabled and disabled by CLI defaults.`);let u=(m)=>m?.split(",").map((P)=>P.trim()).filter(Boolean)??[],v=u(I(f.ENABLED_TOOLS,o)),y=u(I(f.DISABLED_TOOLS,o)),w=new Set(y),g=v.find((m)=>w.has(m));if(g)throw Error(`Tool '${g}' cannot be both enabled and disabled by environment defaults.`);let h=new Map([...v.map((m)=>[m,!0]),...y.map((m)=>[m,!1]),...s.map((m)=>[m,!0]),...d.map((m)=>[m,!1])]),M=Array.from(h).filter(([,m])=>m).map(([m])=>m),A=Array.from(h).filter(([,m])=>!m).map(([m])=>m);return{enabledTools:M,disabledTools:A}}function Je(t){let o={},n=(d,c)=>{if(!d)return;if(!new Set(["low","medium","high"]).has(d)){t.warn(`Invalid video quality preset (${c}): ${d}`);return}o.qualityPreset=d},a=(d,c)=>{if(!d)return;if(d!=="mp4"){t.warn(`Invalid video format (${c}): ${d}`);return}o.format=d};n(I(f.VIDEO_QUALITY_PRESET),"env");let s=[[I(f.VIDEO_TARGET_BITRATE_KBPS),"video target bitrate",!1,"targetBitrateKbps"],[I(f.VIDEO_MAX_THROUGHPUT_MBPS),"video max throughput",!0,"maxThroughputMbps"],[I(f.VIDEO_FPS),"video fps",!1,"fps"],[I(f.VIDEO_MAX_ARCHIVE_MB),"video max archive size",!0,"maxArchiveSizeMb"]];for(let[d,c,p,u]of s){let v=a_(d,c,p,t);if(v!==void 0)o[u]=v}return a(I(f.VIDEO_FORMAT),"env"),{videoRecordingDefaults:o,applyQualityPreset:n,applyFormat:a}}function je(t,o,n,a){let s={a11yUseBaseline:!1,planExecutionLockScope:"session",planExecutionLockScopeExplicit:!1,runnerReadinessTimeoutMs:a},d=t.indexOf("--daemon");for(let c=0;c<t.length;c++){if(["--cli","--boot-device","--"].includes(t[c]))break;let{flag:p,inlineValue:u}=Pi(t[c]),v=u!==void 0&&Qe.has(p),y=v?[p,u]:t,w=v?0:c;if(p==="--a11y-use-baseline"&&u!==void 0){let h=Hs(u);if(h===void 0)o.warn(`Invalid value for ${p}: ${u}; expected true or false`);else s.a11yUseBaseline=h;continue}let g=Xe(y,w,o,{options:s,video:n});if(g!==void 0){c=v?c:g;continue}c=Ze(t,c,d,s)}return s}var Qe=new Set(["--port","--host","--initial-session-uuid","--liveness-owner-token","--a11y-level","--a11y-failure-mode","--a11y-min-severity","--plan-execution-lock-scope",Vv,"--video-quality","--video-quality-preset","--video-target-bitrate-kbps","--video-max-throughput-mbps","--video-fps","--video-format","--video-archive-size-mb"]);function Xe(t,o,n,a){let{options:s,video:d}=a,c=ot(t,o,n,s);if(c!==void 0)return Math.max(c,W(t,o));return it(t,o,n,s)??st(t,o,n,s)??at(t,o,n,d)}function W(t,o){return t[o+1]!==void 0&&!t[o+1].startsWith("--")?o+1:o}function Ze(t,o,n,a){if(qe.includes(t[o]))return W(t,o);if(n>=0&&o>=n)return o;let s=et(t[o]);if(s)a.invalidInvocation??=s;else if(t[o]!==""&&!t[o].startsWith("-"))a.invalidInvocation??=`Unexpected argument: ${t[o]}; did you mean --cli ${t[o]}?`;return tt(t[o])?W(t,o):o}function et(t){if(t.startsWith("--cli="))return"Invalid CLI invocation. Use --cli <tool> instead of --cli=<tool>.";if(t.startsWith("--daemon=")||t.startsWith("--boot-device=")){let[o,...n]=t.split("=");return`Invalid invocation. Use ${o==="--boot-device"?"--boot-device --platform <android|ios>":`${o} ${n.join("=")}`} instead of ${t}.`}return}function tt(t){return t.startsWith("-")&&!t.includes("=")&&!Object.hasOwn(G,t.replace(/^-+/,""))&&!Yu.some((o)=>o.cli===t||o.disableCli===t)}function ot(t,o,n,a){let s=t[o];if(s==="--port"){let d=t[o+1],c=P0(d,n);if(c!==void 0)a.daemonPort=c,o++}else if(s==="--host"){let d=t[o+1];if(d&&!d.startsWith("--"))a.daemonHost=d,o++;else n.warn(`Invalid host: ${d}`)}else return rt(t,o,n,a);return o}function rt(t,o,n,a){let s=t[o],d=t[o+1]?.trim(),c=d!==void 0&&d.length>0&&!d.startsWith("--");if(s==="--initial-session-uuid"){if(!c)return n.warn(`Invalid initial session UUID: ${t[o+1]}`),o;return a.initialSessionUuid=t[o+1],o+1}let p=nt(t,o,a);if(p!==void 0)return p;if(s==="--liveness-owner-token"){if(!c)return n.warn("--liveness-owner-token requires a non-empty value"),o;return a.livenessOwnerToken=d,o+1}return}function nt(t,o,n){let a=t[o];if(a===R0){let s=t[o+1]?.trim();if(!s||s.startsWith("--")&&!s.startsWith("{"))throw new dm(`${R0} requires inline JSON or a file path`);return n.sessionConfigValue=s,o+1}if(a.startsWith(`${R0}=`))return n.sessionConfigValue=a.slice(R0.length+1),o;return}function it(t,o,n,a){let s=t[o];if(s==="--a11y-level")a.a11yLevel=t[++o];else if(s==="--a11y-failure-mode")a.a11yFailureMode=t[++o];else if(s==="--a11y-min-severity")a.a11yMinSeverity=t[++o];else if(s==="--a11y-use-baseline")a.a11yUseBaseline=!0;else return;return o}function st(t,o,n,a){let s=t[o];if(s==="--plan-execution-lock-scope"){let d=t[++o];if(d==="global"||d==="session")a.planExecutionLockScope=d,a.planExecutionLockScopeExplicit=!0;else n.warn(`Invalid plan execution lock scope: ${d}. Using default: ${a.planExecutionLockScope}`)}else if(s===Vv){let d=t[++o],c=zv(d);if(c!==void 0)a.runnerReadinessTimeoutMs=c;else n.warn(`Invalid runner readiness timeout: ${d}; expected an integer from ${Wv} to ${Zw}`)}else return;return o}function at(t,o,n,a){let s=t[o],{videoRecordingDefaults:d,applyQualityPreset:c,applyFormat:p}=a;if(s==="--video-quality"||s==="--video-quality-preset")c(t[++o],"cli");else if(s==="--video-target-bitrate-kbps")k(d,t[++o],n,{label:"video target bitrate",allowFloat:!1,key:"targetBitrateKbps"});else if(s==="--video-max-throughput-mbps")k(d,t[++o],n,{label:"video max throughput",allowFloat:!0,key:"maxThroughputMbps"});else if(s==="--video-fps")k(d,t[++o],n,{label:"video fps",allowFloat:!1,key:"fps"});else if(s==="--video-format")p(t[++o],"cli");else if(s==="--video-archive-size-mb")k(d,t[++o],n,{label:"video max archive size",allowFloat:!0,key:"maxArchiveSizeMb"});else return;return o}function k(t,o,n,a){let{label:s,allowFloat:d,key:c}=a,p=a_(o,s,d,n);if(p!==void 0)t[c]=p}function dt(t,o){let n=t[lD]??t.AUTO_MOBILE_RUNNER_READINESS_TIMEOUT_MS,a=zv(n),s=a;if(n!==void 0&&a===void 0)o.warn(`Invalid ${lD}: ${n}; expected an integer from ${Wv} to ${Zw}`);return s}function ct(t){let o=t.indexOf("--daemon"),n=o>=0,a=o>=0?t[o+1]||void 0:void 0,s=o>=0?t.slice(o+2):[];return{daemonRequested:n,daemonCommand:a,daemonArgs:s}}function ne(t,o){o.terminate(t.exitCode)}async function H(t){try{await t.closeAfterFlush()}catch(o){t.error(`Daemon command completed successfully, but logger teardown failed; exiting 0: ${r(o)}`),await t.flush()}}async function K(t,o){await H(t),o.exit(0)}var ut=new Set(["start","restart","restart-admitted","restart-acceptance-session"]);function ie(t){return!ut.has(t)}var se=5000;function de(t){let o=t.timer??i,n=t.logger??e;if(q("Android CtrlProxy prefetch cleanup",t.startAndroidSweep,o,n),q("native helper cleanup",t.startNativeHelperSweep,o,n),t.platform==="darwin")q("iOS CtrlProxy runner cleanup",t.startIosReap,o,n)}function q(t,o,n,a){let s;try{s=o()}catch(c){a.warn(`[STARTUP_MAINTENANCE] ${t} failed: ${ae(c)}`);return}let d=n.setTimeout(()=>{a.warn(`[STARTUP_MAINTENANCE] ${t} exceeded ${se}ms; continuing startup`)},se);d.unref?.(),s.catch((c)=>{a.warn(`[STARTUP_MAINTENANCE] ${t} failed: ${ae(c)}`)}).finally(()=>{n.clearTimeout(d)})}function ae(t){return r(t)}function ce(t,o,n){if(!n)de({platform:process.platform,startAndroidSweep:()=>t.AndroidCtrlProxyManager.sweepStalePrefetchDirsOnStartup(),startIosReap:()=>t.IOSCtrlProxyManager.startOrphanRunnerReapOnStartup(),startNativeHelperSweep:async()=>{await Nre()}});pt(t,o,n),mt(t,o,n),ft(t)}function pt(t,o,n){if(n)Dt.recordPhase("androidCtrlProxyPrefetch",0);else if(o)t.logger.info(`CtrlProxy downloads disabled (${kk} or ${xR})`),Dt.recordPhase("androidCtrlProxyPrefetch",0);else Dt.startPhase("androidCtrlProxyPrefetch"),t.AndroidCtrlProxyManager.prefetchApk().then(()=>{Dt.endPhase("androidCtrlProxyPrefetch")})}function mt(t,o,n){if(process.platform!=="darwin"||n)return;if(o){t.logger.info(`CtrlProxy iOS prefetch disabled (${kk} or ${xR})`),Dt.recordPhase("iosCtrlProxyPrefetch",0);return}Dt.startPhase("iosCtrlProxyPrefetch"),t.IosCtrlProxyBuilder.prefetchBuild().then(()=>{Dt.endPhase("iosCtrlProxyPrefetch")})}function ft(t){if(AQ(),process.platform==="darwin"&<(f.WEBRTC_WHIP_ENDPOINT)&&!I(f.IOS_SCREEN_CAPTURE_HELPER))qc.getInstance().ensure().catch((o)=>{t.logger.warn(`[SCREEN_CAPTURE_HELPER] Background prefetch failed: ${r(o)}`)})}function le(t){let{eventAllMarkers:o,eventAllMarkersCliOverride:n}=t;return o.length>0||n?{eventAllMarkers:o,eventAllMarkersCliOverride:n}:{}}function ue(t,o){let{videoRecordingDefaults:n,runnerReadinessTimeoutMs:a,daemonHost:s}=t;return{port:t.daemonPort,...s!==void 0?{host:s}:{},strictPort:t.strictPort,debug:t.debug,debugPerf:t.debugPerf,planExecutionLockScope:t.planExecutionLockScope,...a!==void 0?{runnerReadinessTimeoutMs:a}:{},videoQualityPreset:n.qualityPreset,videoTargetBitrateKbps:n.targetBitrateKbps,videoMaxThroughputMbps:n.maxThroughputMbps,videoFps:n.fps,videoFormat:n.format,videoMaxArchiveSizeMb:n.maxArchiveSizeMb,toolOutputsDir:t.toolOutputsDir,networkMockable:t.networkMockable,embeddedSdk:t.embeddedSdk,enabledTools:t.enabledTools,disabledTools:t.disabledTools,dismissKeyboardAfterInput:t.dismissKeyboardAfterInput,...o,noUiPerfMode:!t.uiPerfMode,memPerfAudit:t.memPerfAuditMode,accessibilityAudit:t.a11yAuditMode,accessibilityLevel:t.a11yLevel,accessibilityFailureMode:t.a11yFailureMode,accessibilityMinSeverity:t.a11yMinSeverity,accessibilityUseBaseline:t.a11yUseBaseline,predictiveUi:t.predictiveUi,rawElementSearch:t.rawElementSearch,skipCtrlProxyDownload:t.skipCtrlProxyDownload,toolCallRecording:t.toolCallRecording,noNavigationScreenshots:!t.navigationScreenshots,noWaitForPollingOverhead:t.noWaitForPollingOverhead,noA11yIncludeNotImportantViews:t.noA11yIncludeNotImportantViews,noA11yReportViewIds:t.noA11yReportViewIds,noA11yRetrieveInteractiveWindows:t.noA11yRetrieveInteractiveWindows,noOcclusion:t.noOcclusion,...t.outputReduction}}function pe(t,o,n){return{...vt(t),...St(t),...n,...yt(t),...gt(t,o),...t.outputReduction,toolResultsNoStructuredContent:t.outputReduction.toolResultsNoStructuredContent?!0:void 0}}function vt(t){let{daemonPort:o,daemonHost:n,runnerReadinessTimeoutMs:a}=t;return{...o!==void 0?{port:o}:{},...n!==void 0?{host:n}:{},...t.strictPort?{strictPort:!0}:{},...t.debug?{debug:!0}:{},...t.debugPerf?{debugPerf:!0}:{},...t.planExecutionLockScopeExplicit?{planExecutionLockScope:t.planExecutionLockScope}:{},...a!==void 0?{runnerReadinessTimeoutMs:a}:{},...t.toolCallRecording?{toolCallRecording:!0}:{}}}function St(t){let o=t.videoRecordingDefaults;return{videoQualityPreset:o.qualityPreset,videoTargetBitrateKbps:o.targetBitrateKbps,videoMaxThroughputMbps:o.maxThroughputMbps,videoFps:o.fps,videoFormat:o.format,videoMaxArchiveSizeMb:o.maxArchiveSizeMb,toolOutputsDir:t.toolOutputsDir,...t.networkMockable?{networkMockable:!0}:{},...t.embeddedSdk?{embeddedSdk:!0}:{},...t.enabledTools.length>0?{enabledTools:t.enabledTools}:{},...t.disabledTools.length>0?{disabledTools:t.disabledTools}:{},...t.dismissKeyboardAfterInput?{dismissKeyboardAfterInput:!0}:{}}}function yt(t){return{...!t.uiPerfMode?{noUiPerfMode:!0}:{},...!t.navigationScreenshots?{noNavigationScreenshots:!0}:{},...t.noWaitForPollingOverhead?{noWaitForPollingOverhead:!0}:{},...t.noA11yIncludeNotImportantViews?{noA11yIncludeNotImportantViews:!0}:{},...t.noA11yReportViewIds?{noA11yReportViewIds:!0}:{},...t.noA11yRetrieveInteractiveWindows?{noA11yRetrieveInteractiveWindows:!0}:{},...t.noOcclusion?{noOcclusion:!0}:{}}}function gt(t,o){return{...t.memPerfAuditMode?{memPerfAudit:!0}:{},...t.a11yAuditMode?{accessibilityAudit:!0}:{},...o?{accessibilityLevel:o.level,accessibilityFailureMode:o.failureMode,accessibilityMinSeverity:o.minSeverity,accessibilityUseBaseline:o.useBaseline}:{},...t.predictiveUi?{predictiveUi:!0}:{},...t.rawElementSearch?{rawElementSearch:!0}:{},...t.skipCtrlProxyDownload?{skipCtrlProxyDownload:!0}:{}}}function me(t){return Yu.filter((o)=>o.field!=="actionsCompactMetadata"&&t[o.field]===!0).map((o)=>({key:o.featureFlagKey,label:o.label}))}function fe(t){if(!t.a11yAuditMode)return null;return{level:t.a11yLevel||"AA",failureMode:t.a11yFailureMode||"report",minSeverity:t.a11yMinSeverity||(t.a11yFailureMode==="strict"?"error":"warning"),useBaseline:t.a11yUseBaseline}}function Pt(t,o){return[["debug",t.debug,"--debug"],["debug-perf",t.debugPerf,"--debug-perf/--ui-perf-debug"],["ui-perf-mode",t.uiPerfMode,"--ui-perf-mode"],["mem-perf-audit",t.memPerfAuditMode,"--mem-perf-audit"],["accessibility-audit",t.a11yAuditMode,"--accessibility-audit",o],["predictive-ui",t.predictiveUi,"--predictive/--predictive-ui"],["raw-element-search",t.rawElementSearch,"--raw-element-search"],["tool-call-recording",t.toolCallRecording,"--tool-call-recording"],...me(t.outputReduction).map(({key:n,label:a})=>[n,!0,a,void 0])]}function ve(t,o,n){let{logger:a,serverConfig:s}=o,d=o.FeatureFlagService.getInstance(),c=Pt(t,n);return async()=>{await d.initialize();for(let[p,u,v,y]of c){if(!u)continue;await d.setFlag(p,u,y),a.info(`Feature flag ${u?"enabled":"disabled"} (${v})`)}if(s.setActionsCompactMetadataEnabled(Vq(t.outputReduction.actionsCompactMetadata,d.isEnabled("actions-compact-metadata"))),!t.navigationScreenshots)await d.setFlag("navigation-screenshots",!1),a.info("Navigation screenshots disabled (--no-navigation-screenshots)")}}async function Se(t,o,n){await Dt.runPhase("databasePreflight",async()=>{if(t.daemonMode){await o.guardDatabaseStartup(async()=>{await new o.DefaultDatabaseInitializer().initialize(),await n()});return}let{runDirectModeStartup:a}=await import("./chunk-6pg7bqck.js");await a({noProxy:t.noProxy,assertDbOwnership:async()=>{let{assertDirectModeDbOwnership:s,createDefaultDirectModeGuardDeps:d}=await import("./chunk-9fth9ayh.js");s(d())},applyFeatureFlagStartup:n})})}function ye(t,o){let{serverConfig:n,logger:a,LogLevel:s}=o;if(t.debug)a.setLogLevel(s.DEBUG);if(n.setPlanExecutionLockScope(t.planExecutionLockScope),t.runnerReadinessTimeoutMs!==void 0)n.setRunnerReadinessTimeoutMs(t.runnerReadinessTimeoutMs);n.setActionsCompactMetadataEnabled(Vq(t.outputReduction.actionsCompactMetadata,n.isActionsCompactMetadataEnabled())),n.setVideoRecordingDefaults(t.videoRecordingDefaults),n.setToolOutputsDir(t.toolOutputsDir),n.setSkipCtrlProxyDownload(t.skipCtrlProxyDownload),n.setEmbeddedSdkEnabled(t.embeddedSdk),n.setNetworkMockableEnabled(t.networkMockable),n.setDismissKeyboardAfterInputEnabled(t.dismissKeyboardAfterInput),n.setEventAllMarkers(t.eventAllMarkers)}function ge(t,o){let n=[[!t.uiPerfMode,"UI perf mode disabled (--no-ui-perf-mode): skipping selection-state visual capture on taps and UI perf auditing"],[t.embeddedSdk,"Embedded SDK tools enabled (--embedded-sdk)"],[t.dismissKeyboardAfterInput,"Dismiss keyboard after internal text input enabled (--dismiss-keyboard-after-input)"],[t.noA11yIncludeNotImportantViews,"Accessibility includeNotImportantViews disabled (--no-include-not-important-views)"],[t.noA11yReportViewIds,"Accessibility reportViewIds disabled (--no-report-view-ids)"],[t.noA11yRetrieveInteractiveWindows,"Accessibility retrieveInteractiveWindows disabled (--no-retrieve-interactive-windows)"],[t.noOcclusion,"Observe occlusion pass disabled (--no-occlusion)"],[t.headless,"Headless prototype mode: prototype calls run on the virtual device (--headless)"]];for(let[a,s]of n)if(a)o.info(s);bt(t.eventAllMarkers,o)}function bt(t,o){if(t.length>0){o.info(`Internal text-input eventAll auto-promotion markers configured (--event-all-markers): ${JSON.stringify(t)}`);return}if(process.argv.slice(2).some((a)=>a===Vc||a.startsWith(`${Vc}=`)))o.warn(`${Vc} was provided but resolved to no markers; internal text-input eventAll auto-promotion stays disabled`)}async function Pe(t,o,n,a){let{logger:s}=o,d=!t.noProxy,c=d?void 0:Hc.createInstance();if(n.directModeActive=!d,d)s.info("Starting MCP server in proxy mode (connecting to daemon)");else s.info("Starting MCP server in direct mode (--no-proxy flag)"),await wt(o,c);let p=new o.OutputGatedTransport(o.createStdioServerTransport()),u=await ht(p),v=d&&t.sessionConfig?new(await import("./chunk-5s645vr4.js")).EarlyStartTransport(p):void 0;await v?.startEarly();let{server:y,proxyToClaimInitialSession:w}=await At(t,o,n,{launch:a,useProxyMode:d,deviceReadiness:c});try{s.info("Connecting MCP server to stdio transport"),Dt.startPhase("serverListening"),u.value=!0,await y.connect(v??p),Dt.endPhase("serverListening"),s.info("MCP server connected to stdio transport"),w?.claimInitialSession(),s.info(`AutoMobile MCP server running on stdio (${d?"proxy":"direct"} mode)`),Dt.emit("mcp-server",{transport:"stdio",mode:d?"proxy":"direct"})}catch(g){throw s.error("MCP server connect failed:",g),g}}async function wt(t,o){await t.startVideoRecordingSocketServer(),await t.startDeviceGestureRecordingSocketServer(o),await t.startDeviceSnapshotSocketServer(),await t.startAppearanceSocketServer(t.createDirectModeAppearanceDeviceSource(()=>{let n=o.getExplicitDevicePin();return n?[n]:[]})),await t.startWebRtcStreamSocketServer()}async function ht(t){let{MAX_CALLER_MCP_REQUEST_TIMEOUT_MS:o}=await import("./chunk-y2vs6jwg.js"),n={value:!1};return j7(process.stdin,()=>n.value?t.answerReceivedThenStop("stdin closed"):t.stopSending("stdin closed"),o),K7(process.stdout,()=>t.stopSending("stdout closed or write failed")),n}async function At(t,o,n,{launch:a,useProxyMode:s,deviceReadiness:d}){try{if(!s)return{server:o.createMcpServer({debug:t.debug,deviceReadiness:d}),proxyToClaimInitialSession:void 0};let{getDefaultSessionHeartbeatTimeoutMs:c}=await import("./chunk-g0xr8zw0.js"),p=o.createDaemonMcpProxy({autoStartDaemon:!t.noDaemon,lifecycleNamespaceEnv:process.env,daemonOptions:a.daemonStartupOptions,initialSessionUuid:t.initialSessionUuid,livenessOwnerToken:t.livenessOwnerToken,heartbeatTimeoutMs:c()});n.stdioProxy=p;let u=t.sessionConfig?await Rt(p,t.sessionConfig,{launchParentPid:a.launchParentPid,ownerGenerationToken:a.ownerGenerationToken,modules:o}):void 0,v=o.createProxyMcpServer({proxy:p,...u?{session:u}:{}});return{server:v.server,proxyToClaimInitialSession:v.proxy}}catch(c){throw o.logger.error("Failed to create MCP server:",c),c}}async function Rt(t,o,{launchParentPid:n,ownerGenerationToken:a,modules:s}){let d=await Ct(n,o.executionOwnerPid,a);t.setExecutionOwnerLossProbe(()=>d.check()!==void 0);let c=await t.acquireBrokerSession(o);return s.logger.info(`[SessionBroker] Acquisition ${c.outcome}`+(c.failure?` (${c.failure.code})`:"")),c}async function Ct(t,o,n){let[{ExecutionOwnerWatch:a},{isProcessRunning:s},{defaultTimer:d},{defaultLockOwnerGenerationProbe:c},{processGenerationReadIsCheap:p}]=await Promise.all([import("./chunk-ayp07wbb.js"),import("./chunk-g78rtrfv.js"),import("./chunk-gabgv3y5.js"),import("./chunk-2tbdrbt6.js"),import("./chunk-28re4xrg.js")]),u=new a({launchParentPid:t,ownerPid:o,ownerGenerationToken:n,generationCheckEvery:p()?1:void 0,onOwnerLost:()=>G7("execution-owner-lost")},{isProcessRunning:(v)=>s(v),currentParentPid:()=>process.ppid},d,c);return u.start(),u}async function be(t,o,n){let{logger:a}=t,s=re(process.argv.slice(2),a);if(s.invalidInvocation){console.error(s.invalidInvocation),process.exit(1);return}if(s.headless)mQ(process.env);let d=await Mt(s);if(await xt(s,t))return;if(await Ot(s,t))return;kt(s,t);let c=fe(s);if(await Se(s,t,ve(s,t,c)),s.noWaitForPollingOverhead)t.serverConfig.setWaitForPollingOverheadEnabled(!1),a.info("WaitFor polling overhead disabled (--no-waitfor-polling-overhead): back stack skipped during observe waitFor polling");ge(s,a);let p=le(s);if(s.daemonMode){await t.startDaemon(ue(s,p));return}if(s.daemonCommand){await Tt(s,s.daemonCommand,t);return}let u=pe(s,c,p);if(s.cliMode){await we(s,t,u);return}await Pe(s,t,o,{launchParentPid:n,ownerGenerationToken:d,daemonStartupOptions:u})}async function Mt(t){let{sessionConfig:o}=t;if(t.cliMode||t.daemonMode||t.daemonRequested||o?.executionOwnerPid===void 0)return;let[{isProcessRunning:n},{defaultLockOwnerGenerationProbe:a}]=await Promise.all([import("./chunk-g78rtrfv.js"),import("./chunk-2tbdrbt6.js")]);return lQ(o,{isProcessRunning:(s)=>n(s),probe:a})}async function xt(t,o){let{daemonCommand:n,daemonArgs:a}=t;if(t.daemonRequested&&n===void 0){let{printUnknownDaemonCommand:s}=await import("./chunk-49bsqdx3.js");return s(void 0),!0}if(n&&ie(n))return await o.runDaemonCommand(n,a,{namespaceEnv:process.env}),await K(o.logger,process),!0;return!1}async function Ot(t,o){if(!t.cliMode||!o.cliCommandSkipsServerBootstrap(t.cliArgs))return!1;return await we(t,o,void 0),!0}function kt(t,o){vQ(t.enabledTools,t.disabledTools),o.registerMcpTools(t.daemonMode),ye(t,o),ce(o,t.skipCtrlProxyDownload,ee(t.cliMode,t.cliArgs))}async function Tt(t,o,n){let{enabledTools:a,disabledTools:s}=t,d=a.length>0||I(f.ENABLED_TOOLS)!==void 0,c=s.length>0||I(f.DISABLED_TOOLS)!==void 0,p=d||c;await n.runDaemonCommand(o,t.daemonArgs,{namespaceEnv:process.env,...p?{startupToolDefaults:{...d?{enabledTools:a}:{},...c?{disabledTools:s}:{}}}:{}}),await K(n.logger,process)}async function we(t,o,n){let{logger:a}=o;a.info("Running in CLI mode");let s=await o.runCliCommand(t.cliArgs,n);if(await H(a),s){ne(s,{terminate:(d)=>process.exit(d)});return}process.exit(process.exitCode??0)}function he(t,o){let{logger:n}=t,a=!1;DS(async(s)=>{a=!1,n.info(`Received ${s} signal, shutting down`),await c_(TQ({directModeActive:()=>o.directModeActive,cleanupChildProcesses:()=>t.cleanupDaemonChildProcesses(),stopManagedAdbServer:()=>t.stopManagedAdbServer(),stopVideoRecordingSocketServer:()=>t.stopVideoRecordingSocketServer(),stopDeviceGestureRecordingSocketServer:()=>t.stopDeviceGestureRecordingSocketServer(),stopDeviceSnapshotSocketServer:()=>t.stopDeviceSnapshotSocketServer(),stopAppearanceSocketServer:()=>t.stopAppearanceSocketServer(),stopWebRtcStreamSocketServer:()=>t.stopWebRtcStreamSocketServer(),stopAppearanceSyncScheduler:()=>t.stopAppearanceSyncScheduler(),cleanupPrefetchedApk:()=>t.AndroidCtrlProxyManager.cleanupPrefetchedApk(),closeStdioProxy:()=>o.stdioProxy?.close({executionOwnerLost:s==="execution-owner-lost"}),drainDatabaseWrites:async(d)=>{let{getDbWriteBarrier:c}=await import("./chunk-g3rjs80x.js");if(!await c().drain(d))n.warn(`Timed out after ${d}ms draining in-flight DB writes; closing database anyway`)},settleMigrations:async(d)=>{let{awaitInFlightMigrations:c}=await import("./chunk-97b1zmaq.js");if(!await c(d))n.warn(`Timed out after ${d}ms awaiting in-flight startup migration; closing database anyway`)},closeDatabase:async()=>{let{closeDatabase:d}=await import("./chunk-97b1zmaq.js");await d({forShutdown:!0})},refusedDatabaseAccessCount:async()=>{let{refusedDatabaseAccessCountAfterShutdownClose:d}=await import("./chunk-97b1zmaq.js");return d()},closeLogger:()=>n.closeAfterFlush(),warn:(d)=>n.warn(d)}),(d,c)=>{a=!0,n.warn(d,c)},{timer:i})},async()=>(await n.closeAfterFlush(),a?{exitCode:1}:void 0))}D3();process.env[Ub]??=$O();var T;function z(t,o){let n=o instanceof Error?o.stack??o.message:String(o);if(T){if(T.error(`${t}: ${n}`),Ef()==="file")Zi(t,n)}else Zi(t,n)}c0();d0((t)=>{if(t.type==="uncaughtException"){z("Uncaught exception",t.error);return}z("Unhandled rejection",t.reason)});async function Et(){let t=process.ppid;Dt.mark("processEntry"),Dt.startPhase("moduleImports"),await te(process.argv.slice(2));let o=await oe((a)=>{T=a}),n={stdioProxy:void 0,directModeActive:!1};he(o,n);try{await be(o,n,t)}catch(a){throw o.logger.error("Error initializing server:",a),a}}function kr(){Et().catch(async(t)=>{z("Fatal error in main()",t),await T?.closeAfterFlush();let{resolveDaemonStartupExitCode:o}=await import("./chunk-zs1sghs9.js");process.exit(o(t))})}export{kr as runServerEntry};
|
|
3
|
+
|
|
4
|
+
//# debugId=855B6B6425F87B6564756E2164756E21
|