sootsim 0.1.173 → 0.1.175

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/dist-cli/bin.js +3 -3
  2. package/dist-cli/chunks/{agent-C2E22ESN.js → agent-A4WFJEFV.js} +2 -2
  3. package/dist-cli/chunks/{agent-wrapper-IQUZ3DT6.js → agent-wrapper-EOZBE6UT.js} +2 -2
  4. package/dist-cli/chunks/{app-fonts-EL3GCMOF.js → app-fonts-H2I7IV7N.js} +2 -2
  5. package/dist-cli/chunks/{assert-UFDQWVKU.js → assert-36QXQUCE.js} +2 -2
  6. package/dist-cli/chunks/beta-7FRVMDBH.js +2 -0
  7. package/dist-cli/chunks/{camera-YR4LF62J.js → camera-7HK2Y3PY.js} +2 -2
  8. package/dist-cli/chunks/{chunk-7O64AC44.js → chunk-2J67UJXT.js} +1 -1
  9. package/dist-cli/chunks/{chunk-M2GYHZES.js → chunk-2QTAUBZX.js} +3 -3
  10. package/dist-cli/chunks/chunk-3G5EE3ST.js +2 -0
  11. package/dist-cli/chunks/{chunk-7LCS6UB7.js → chunk-3SUIAUIY.js} +1 -1
  12. package/dist-cli/chunks/{chunk-GTIQVAJP.js → chunk-46S56FJJ.js} +1 -1
  13. package/dist-cli/chunks/{chunk-4NEHOYQH.js → chunk-4PQ36DTJ.js} +3 -3
  14. package/dist-cli/chunks/{chunk-KHMFZHHP.js → chunk-4UATZVHM.js} +2 -2
  15. package/dist-cli/chunks/{chunk-MJQCN4PS.js → chunk-4UGD4KJM.js} +2 -2
  16. package/dist-cli/chunks/{chunk-BUCN4NOE.js → chunk-5D4PHINP.js} +1 -1
  17. package/dist-cli/chunks/{chunk-RXB7KMHB.js → chunk-5QLWXLML.js} +2 -2
  18. package/dist-cli/chunks/{chunk-HGUPRH7F.js → chunk-7F2LH7U5.js} +2 -2
  19. package/dist-cli/chunks/{chunk-TYCNPLOA.js → chunk-DV6SWCY7.js} +1 -1
  20. package/dist-cli/chunks/{chunk-2IUYPQC6.js → chunk-EEIUS5AS.js} +2 -2
  21. package/dist-cli/chunks/{chunk-CO42HSYV.js → chunk-GJQGKFLY.js} +1 -1
  22. package/dist-cli/chunks/{chunk-FLKV4YHL.js → chunk-H2J4Z7LY.js} +2 -2
  23. package/dist-cli/chunks/{chunk-KBTADP77.js → chunk-HCKTFQLK.js} +1 -1
  24. package/dist-cli/chunks/{chunk-I3UUCR2A.js → chunk-HWJ52K4J.js} +1 -1
  25. package/dist-cli/chunks/{chunk-5RLVAUSR.js → chunk-HWUFW3IP.js} +2 -2
  26. package/dist-cli/chunks/{chunk-6PQ4KSCP.js → chunk-IISA6UXR.js} +1 -1
  27. package/dist-cli/chunks/{chunk-QYHBVPQH.js → chunk-IKJSGKUB.js} +2 -2
  28. package/dist-cli/chunks/{chunk-VQQVVMNO.js → chunk-JCQEG4R6.js} +2 -2
  29. package/dist-cli/chunks/{chunk-LOP35MNF.js → chunk-KSF72FPP.js} +2 -2
  30. package/dist-cli/chunks/{chunk-FX3YWIDK.js → chunk-LYZXARZO.js} +2 -2
  31. package/dist-cli/chunks/{chunk-MPJX3BCR.js → chunk-MLLINRL2.js} +1 -1
  32. package/dist-cli/chunks/{chunk-A43ZSZMJ.js → chunk-NPZPBSZD.js} +1 -1
  33. package/dist-cli/chunks/chunk-ODISDSXU.js +1 -0
  34. package/dist-cli/chunks/{chunk-HSACKNHS.js → chunk-OMJ2DTQJ.js} +2 -2
  35. package/dist-cli/chunks/{chunk-QGQSKDXQ.js → chunk-P2WO5LMI.js} +2 -2
  36. package/dist-cli/chunks/{chunk-ODWORXXD.js → chunk-QK76RK6J.js} +1 -1
  37. package/dist-cli/chunks/{chunk-6D2B6YM5.js → chunk-RAESCYIA.js} +1 -1
  38. package/dist-cli/chunks/{chunk-N7HUNHH6.js → chunk-RCPMRHTK.js} +1 -1
  39. package/dist-cli/chunks/{chunk-WS4M3ANJ.js → chunk-SV3SRWN5.js} +1 -1
  40. package/dist-cli/chunks/{chunk-WYGYIQOE.js → chunk-UMJDCX2P.js} +2 -2
  41. package/dist-cli/chunks/chunk-URQSBUTU.js +1 -0
  42. package/dist-cli/chunks/{chunk-DFP5BKYL.js → chunk-UXZRHPX6.js} +2 -2
  43. package/dist-cli/chunks/{chunk-X4A5YX56.js → chunk-V7AGBG2P.js} +2 -2
  44. package/dist-cli/chunks/{chunk-AOFD6E2Z.js → chunk-VW643HG5.js} +2 -2
  45. package/dist-cli/chunks/{chunk-HYCJ7HUJ.js → chunk-WM73SGMM.js} +2 -2
  46. package/dist-cli/chunks/{chunk-3N4T6ZCZ.js → chunk-XBK3XAKL.js} +2 -2
  47. package/dist-cli/chunks/{chunk-MPVUKE2L.js → chunk-XDDO46ZW.js} +1 -1
  48. package/dist-cli/chunks/{chunk-TAFDTRBK.js → chunk-Y3OHYOFS.js} +2 -2
  49. package/dist-cli/chunks/{chunk-PPDVP56P.js → chunk-YMBQBKKA.js} +12 -12
  50. package/dist-cli/chunks/{chunk-Q6VYTVCL.js → chunk-ZG2A6LCL.js} +2 -2
  51. package/dist-cli/chunks/{chunk-D5MW3FJE.js → chunk-ZPQY5DBY.js} +2 -2
  52. package/dist-cli/chunks/{chunk-HTCJBVQD.js → chunk-ZZWAHZ37.js} +1 -1
  53. package/dist-cli/chunks/cli-version-HCYSKPJO.js +2 -0
  54. package/dist-cli/chunks/{compat-K733FE26.js → compat-KWM6HXJD.js} +3 -3
  55. package/dist-cli/chunks/{control-PAVODRG5.js → control-PVZRPH57.js} +2 -2
  56. package/dist-cli/chunks/{cpu-profile-OGUUHMAT.js → cpu-profile-3YLLRNVG.js} +2 -2
  57. package/dist-cli/chunks/daemon-2DT4QAJ4.js +2 -0
  58. package/dist-cli/chunks/{debug-7DNEARGS.js → debug-TD4EVFT7.js} +3 -3
  59. package/dist-cli/chunks/{detox-JAIVH44U.js → detox-S7M5WN3L.js} +2 -2
  60. package/dist-cli/chunks/{device-DLTVU6ZI.js → device-WR7GA4RN.js} +2 -2
  61. package/dist-cli/chunks/{diagnose-3D5ISUJP.js → diagnose-JZMNR25X.js} +2 -2
  62. package/dist-cli/chunks/drivers-UMQTPEMU.js +2 -0
  63. package/dist-cli/chunks/{electron-HYOT74T7.js → electron-V2YDDVKJ.js} +3 -3
  64. package/dist-cli/chunks/flow-CKXTFJJ7.js +2 -0
  65. package/dist-cli/chunks/help-OEMLUQMD.js +2 -0
  66. package/dist-cli/chunks/{hints-5RUWD6KL.js → hints-OK373YOJ.js} +2 -2
  67. package/dist-cli/chunks/{home-paths-YXPZJSA5.js → home-paths-IFY5UTLL.js} +2 -2
  68. package/dist-cli/chunks/inspect-LRIJ7MQT.js +987 -0
  69. package/dist-cli/chunks/{install-desktop-AXOXLY57.js → install-desktop-ESQL2Q2T.js} +3 -3
  70. package/dist-cli/chunks/{keys-OS55YM3T.js → keys-IHG2YEL3.js} +2 -2
  71. package/dist-cli/chunks/{login-CE3ATU7H.js → login-CYIWYJGG.js} +4 -4
  72. package/dist-cli/chunks/{logout-55RMHZIG.js → logout-NALFLZWI.js} +2 -2
  73. package/dist-cli/chunks/{maestro-BWH4Y3OO.js → maestro-QKSXVPWG.js} +2 -2
  74. package/dist-cli/chunks/optional-demo-registry-CIEW2ET7.js +2 -0
  75. package/dist-cli/chunks/{preview-YZCH5SS4.js → preview-XCQGBN2I.js} +2 -2
  76. package/dist-cli/chunks/{profile-Q6CC3BOS.js → profile-RDAPVU7K.js} +2 -2
  77. package/dist-cli/chunks/{react-43Y6I63U.js → react-MM373YNE.js} +2 -2
  78. package/dist-cli/chunks/{record-OAW5IIQH.js → record-SQA376Z7.js} +4 -4
  79. package/dist-cli/chunks/runtime-CUNVH66R.js +2 -0
  80. package/dist-cli/chunks/{screenshot-JEXBD4GJ.js → screenshot-FCKW6JV6.js} +2 -2
  81. package/dist-cli/chunks/{screenshot-mode-AOS3ROPL.js → screenshot-mode-QVRUJXZ3.js} +2 -2
  82. package/dist-cli/chunks/{screenshots-CYTHIJ5W.js → screenshots-ITBCSBZS.js} +2 -2
  83. package/dist-cli/chunks/{screenshots-capture-YAEYGEHY.js → screenshots-capture-H4EAYFH3.js} +2 -2
  84. package/dist-cli/chunks/{serve-OYNG5IHK.js → serve-3GHYSGJR.js} +10 -10
  85. package/dist-cli/chunks/{setup-6O7GJF73.js → setup-ME5SRHWD.js} +2 -2
  86. package/dist-cli/chunks/skills-E5JE3SAI.js +48 -0
  87. package/dist-cli/chunks/{slides-DSY2GHZZ.js → slides-D37ML4LI.js} +2 -2
  88. package/dist-cli/chunks/store-UW5HH6DW.js +2 -0
  89. package/dist-cli/chunks/telemetry-KSBNWXNE.js +2 -0
  90. package/dist-cli/chunks/{test-DVS4LMCY.js → test-CWWQJG5K.js} +3 -3
  91. package/dist-cli/chunks/{three-mode-6KCLSSPS.js → three-mode-WESGARG5.js} +2 -2
  92. package/dist-cli/chunks/{timeline-ZWPBF46N.js → timeline-RUVZASG4.js} +2 -2
  93. package/dist-cli/chunks/{upgrade-ZV77D7SC.js → upgrade-DKWD6TSY.js} +2 -2
  94. package/dist-cli/chunks/upload-LYANGCPB.js +2 -0
  95. package/dist-cli/chunks/{version-WAJ3YX4U.js → version-G45RLONC.js} +2 -2
  96. package/dist-cli/chunks/{web-KVDTMF6L.js → web-X2HCJQQE.js} +2 -2
  97. package/dist-cli/chunks/{what-happened-GUIQ3GXK.js → what-happened-5DBVOXKC.js} +2 -2
  98. package/dist-cli/chunks/{whoami-U6J5UL6X.js → whoami-ZDT3RQOC.js} +2 -2
  99. package/dist-lib/agent-daemon-client.cjs +1 -1
  100. package/dist-lib/agent-events.cjs +1 -1
  101. package/dist-lib/agent-sessions.cjs +1 -1
  102. package/dist-lib/attached-projects.cjs +1 -1
  103. package/dist-lib/auth/shared-session.cjs +1 -1
  104. package/dist-lib/backend-origin.cjs +1 -1
  105. package/dist-lib/beta.cjs +1 -1
  106. package/dist-lib/beta.mjs +1 -1
  107. package/dist-lib/bridge-constants.cjs +1 -1
  108. package/dist-lib/cli-constants.cjs +1 -1
  109. package/dist-lib/config.cjs +1 -1
  110. package/dist-lib/detox/index.cjs +1 -1
  111. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  112. package/dist-lib/home-paths.cjs +1 -1
  113. package/dist-lib/host/bridge-host.cjs +3 -2
  114. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  115. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  116. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  117. package/dist-lib/host/websocket-proxy.cjs +1 -1
  118. package/dist-lib/index.cjs +1 -1
  119. package/dist-lib/jump-to-source-babel.cjs +1 -1
  120. package/dist-lib/menu.cjs +1 -1
  121. package/dist-lib/menu.mjs +1 -1
  122. package/dist-lib/metro.cjs +1 -1
  123. package/dist-lib/profiles.cjs +1 -1
  124. package/dist-lib/render-mode.cjs +1 -1
  125. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  126. package/dist-lib/sdk.cjs +28 -1
  127. package/dist-lib/sdk.mjs +27 -1
  128. package/dist-lib/skills.cjs +4 -3
  129. package/dist-lib/vite.cjs +1 -1
  130. package/package.json +1 -1
  131. package/skills/soot.md +1 -1
  132. package/skills/sootsim-debug.md +23 -1
  133. package/src/host/bridge-host.ts +7 -4
  134. package/dist-cli/chunks/beta-3VFRMFCE.js +0 -2
  135. package/dist-cli/chunks/chunk-4UNCEOKE.js +0 -2
  136. package/dist-cli/chunks/chunk-F2VINQ62.js +0 -1
  137. package/dist-cli/chunks/chunk-M4TI3GFJ.js +0 -1
  138. package/dist-cli/chunks/cli-version-7EPWQ5XZ.js +0 -2
  139. package/dist-cli/chunks/daemon-ITK6NXMP.js +0 -2
  140. package/dist-cli/chunks/drivers-VFK56EQO.js +0 -2
  141. package/dist-cli/chunks/flow-AHIM2QYC.js +0 -2
  142. package/dist-cli/chunks/help-7JOCVVN6.js +0 -2
  143. package/dist-cli/chunks/inspect-D476ZLEK.js +0 -978
  144. package/dist-cli/chunks/optional-demo-registry-4IEF2MIB.js +0 -2
  145. package/dist-cli/chunks/runtime-C2EIPLM6.js +0 -2
  146. package/dist-cli/chunks/skills-XJOVDRCF.js +0 -40
  147. package/dist-cli/chunks/store-DSH2KPUH.js +0 -2
  148. package/dist-cli/chunks/telemetry-PJHHQYHR.js +0 -2
  149. package/dist-cli/chunks/upload-STOKBIDT.js +0 -2
@@ -0,0 +1,987 @@
1
+ /*! sootsim v0.1.175 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as Mt,b as It}from"./chunk-MLLINRL2.js";import{a as Re,g as Ie,j as oe}from"./chunk-4UGD4KJM.js";import{b as Nt,c as Ft,j as _t}from"./chunk-EEIUS5AS.js";import"./chunk-KSF72FPP.js";import{a as te,b as A,c as E,d as Le,e as ae,f as Y,g as ue,h as ge,i as vt,j as kt,k as Me,l as Tt}from"./chunk-H2J4Z7LY.js";import{A as pt,B as ft,E as gt,G as yt,I as de,J as bt,P as ht,a as ve,b as Qe,c as Ze,d as et,e as tt,f as ot,g as st,h as nt,i as rt,j as it,k as De,l as Ce,q as Be,r as at,s as lt,t as fe,u as ct,v as ke,w as je,x as dt,y as ut,z as mt}from"./chunk-YMBQBKKA.js";import"./chunk-46S56FJJ.js";import"./chunk-4UATZVHM.js";import"./chunk-NPZPBSZD.js";import"./chunk-VW643HG5.js";import"./chunk-2J67UJXT.js";import"./chunk-RCPMRHTK.js";import{c as wt,e as xt,f as $t,g as St,h as Te}from"./chunk-OMJ2DTQJ.js";import"./chunk-HWJ52K4J.js";import{a as Ye}from"./chunk-GJQGKFLY.js";import{a as Ee,c as Pe}from"./chunk-DV6SWCY7.js";import{a as X}from"./chunk-UMJDCX2P.js";import{a as Xe}from"./chunk-3G5EE3ST.js";import"./chunk-HCKTFQLK.js";import{b as Ve}from"./chunk-RAESCYIA.js";import"./chunk-3SUIAUIY.js";import"./chunk-ZZWAHZ37.js";import{existsSync as ho,mkdirSync as wo,readFileSync as xo,rmSync as Ot,writeFileSync as $o}from"fs";import{tmpdir as So}from"os";import{dirname as vo,join as ko,resolve as To}from"path";var ye=1,Mo="SOOTSIM_INSPECT_NOTICE_PATH",Io=300*1e3,No=15e3;function At(){return To(process.env[Mo]||ko(So(),"sootsim-inspect-notice-state.json"))}function Fo(e,a){return Object.fromEntries(Object.entries(e).filter(([,r])=>typeof r?.signature=="string"&&Number.isFinite(r?.updatedAt)&&a-r.updatedAt<=Io))}function _o(e){let a=At();if(!ho(a))return{version:ye,entries:{}};try{let r=JSON.parse(xo(a,"utf8"));return r.version!==ye||!r.entries||typeof r.entries!="object"?(Ot(a,{force:!0}),{version:ye,entries:{}}):{version:ye,entries:Fo(r.entries,e)}}catch{return Ot(a,{force:!0}),{version:ye,entries:{}}}}function Oo(e){let a=At();wo(vo(a),{recursive:!0}),$o(a,JSON.stringify(e,null,2)+`
3
+ `)}function Ao(e,a){let r=a.trim()||"default";return`${e}:${r}`}function Je(e,a,r,l={}){let m=l.nowMs??Date.now(),i=l.cooldownMs??No,g=_o(m),y=Ao(e,a),M=g.entries[y];return M&&M.signature===r&&m-M.updatedAt<i?!1:(g.entries[y]={signature:r,updatedAt:m},Oo(g),!0)}var Eo={initialWaitMs:3e3,deadlineMs:5e3,retryWaitMs:700},Po={initialWaitMs:1200,deadlineMs:2500,retryWaitMs:700};function Ro(e,a={}){return{...e?Eo:Po,...a}}function me(e){return!(!e||e.hit===!1||e.ok===!1||e.pointerTapHandled===!1&&!e.keyboardOpened&&!e.isTextInput)}function Do(e,a){return{id:e.target?.id??e.match?.id??e.node?.id??null,testID:e.target?.testID??e.match?.testID??e.node?.testID??null,text:e.target?.text??e.target?.accessibilityLabel??e.match?.text??e.match?.accessibilityLabel??e.node?.text??a??null,type:e.target?.type??e.match?.type??e.node?.type??null}}async function be(e,a){let r=Ro(!!a.agent,a.timing),l=0,m=null,i=null;try{await oe({bridge:e,maxMs:r.initialWaitMs,pollMs:32,stablePolls:2})}catch{}let g=Date.now()+r.deadlineMs;for(;Date.now()<=g||l===0;){l++;let y=await a.resolve();if(m=y,y?.error==="bridge-not-ready"||y?.ambiguous||y?.nthOutOfRange)return{payload:y,result:null,attempts:l,failure:"special"};if(y&&typeof y.cx=="number"&&typeof y.cy=="number"){let I=await e.send({type:"tap",x:y.cx,y:y.cy,target:Do(y,a.textFallback)});if(i=I,me(I))return{payload:y,result:I,attempts:l}}let M=g-Date.now();if(M<=0)break;try{await oe({bridge:e,maxMs:Math.min(M,r.retryWaitMs),pollMs:32,stablePolls:2})}catch{await new Promise(I=>setTimeout(I,Math.min(120,M)))}}return{payload:m,result:i,attempts:l,failure:m&&typeof m.cx=="number"?"missed":"not-found"}}async function Et(e,a,r,l){return e.send({type:"tap",x:a,y:r,...l?{target:l}:{}})}async function Pt(e,a,r={}){let l=JSON.stringify(a);return be(e,{agent:r.agent,timing:r.timing,resolve:()=>e.send({type:"evaluate",code:`(async () => {
4
+ const t = window.__sootsimTest
5
+ if (!t) return null
6
+ const n = (await t.findByTestId(${l})) || (await t.findById(${l}))
7
+ if (!n || !n.absolutePosition || !n.layout) return { cx: null }
8
+ const resolved =
9
+ typeof n.nodeId === 'number' && typeof t.resolveTapTarget === 'function'
10
+ ? await t.resolveTapTarget(n.nodeId)
11
+ : null
12
+ const target = (resolved && resolved.target) || n
13
+ const cx =
14
+ resolved && typeof resolved.cx === 'number'
15
+ ? resolved.cx
16
+ : n.absolutePosition.x + (n.layout.width || 0) / 2
17
+ const cy =
18
+ resolved && typeof resolved.cy === 'number'
19
+ ? resolved.cy
20
+ : n.absolutePosition.y + (n.layout.height || 0) / 2
21
+ return {
22
+ cx,
23
+ cy,
24
+ match: {
25
+ nodeId: n.nodeId ?? null,
26
+ id: n.id,
27
+ testID: n.testID,
28
+ text: n.text ?? n.accessibilityLabel ?? null,
29
+ type: n.type,
30
+ },
31
+ target: {
32
+ nodeId: target.nodeId ?? null,
33
+ id: target.id,
34
+ testID: target.testID,
35
+ text:
36
+ target.text ??
37
+ target.accessibilityLabel ??
38
+ n.text ??
39
+ n.accessibilityLabel ??
40
+ null,
41
+ type: target.type,
42
+ },
43
+ strategy: (resolved && resolved.strategy) || 'matched-node',
44
+ }
45
+ })()`})})}async function Rt(e,a,r={},l={}){let m=JSON.stringify({query:a,exact:!!r.exact,role:r.role??null,within:r.within??null,minX:r.minX??null,maxX:r.maxX??null,minY:r.minY??null,maxY:r.maxY??null,near:r.near??null,nth:r.nth??null,first:!!r.first});return be(e,{agent:l.agent,timing:l.timing,textFallback:a,resolve:()=>e.send({type:"evaluate",code:`(async () => {
46
+ const t = window.__sootsimTest
47
+ if (!t) return { error: 'bridge-not-ready' }
48
+ const F = ${m}
49
+
50
+ const res = await t.queryTextCandidates({
51
+ query: F.query,
52
+ exact: !!F.exact,
53
+ ...(F.role ? { role: F.role } : {}),
54
+ })
55
+
56
+ let candidates = res.candidates || []
57
+
58
+ candidates = candidates.filter((c) => {
59
+ const ax = c.info.absolutePosition && c.info.absolutePosition.x
60
+ const ay = c.info.absolutePosition && c.info.absolutePosition.y
61
+ if (F.minX !== null && !(ax >= F.minX)) return false
62
+ if (F.maxX !== null && !(ax <= F.maxX)) return false
63
+ if (F.minY !== null && !(ay >= F.minY)) return false
64
+ if (F.maxY !== null && !(ay <= F.maxY)) return false
65
+ if (F.within && !c.ancestorTestIDs.includes(F.within)) return false
66
+ return true
67
+ })
68
+
69
+ if (F.near) {
70
+ candidates.sort((a, b) => {
71
+ const ax = (a.info.absolutePosition && a.info.absolutePosition.x) || 0
72
+ const ay = (a.info.absolutePosition && a.info.absolutePosition.y) || 0
73
+ const bx = (b.info.absolutePosition && b.info.absolutePosition.x) || 0
74
+ const by = (b.info.absolutePosition && b.info.absolutePosition.y) || 0
75
+ return (
76
+ Math.hypot(ax - F.near.x, ay - F.near.y) -
77
+ Math.hypot(bx - F.near.x, by - F.near.y)
78
+ )
79
+ })
80
+ } else {
81
+ candidates.sort((a, b) => {
82
+ const ay = (a.info.absolutePosition && a.info.absolutePosition.y) || 0
83
+ const by = (b.info.absolutePosition && b.info.absolutePosition.y) || 0
84
+ if (Math.abs(ay - by) > 2) return ay - by
85
+ const ax = (a.info.absolutePosition && a.info.absolutePosition.x) || 0
86
+ const bx = (b.info.absolutePosition && b.info.absolutePosition.x) || 0
87
+ return ax - bx
88
+ })
89
+ }
90
+
91
+ const total = candidates.length
92
+ if (total === 0) return { matched: 0, total: 0 }
93
+
94
+ let idx = 0
95
+ if (F.nth !== null) {
96
+ idx = F.nth < 0 ? total + F.nth : F.nth
97
+ if (idx < 0 || idx >= total) {
98
+ return { matched: 0, total, nthOutOfRange: true, nth: F.nth }
99
+ }
100
+ } else if (total > 1 && !F.first && !F.near) {
101
+ return {
102
+ ambiguous: true,
103
+ total,
104
+ candidates: candidates.slice(0, 10).map((c, i) => ({
105
+ idx: i,
106
+ nodeId: c.info.nodeId,
107
+ type: c.info.type,
108
+ testID: c.info.testID,
109
+ text: (c.info.text || '').slice(0, 60),
110
+ abs: c.info.absolutePosition,
111
+ layout: c.info.layout
112
+ ? {
113
+ width: Math.round(c.info.layout.width || 0),
114
+ height: Math.round(c.info.layout.height || 0),
115
+ }
116
+ : null,
117
+ ancestorTestIDs: (c.ancestorTestIDs || []).slice(0, 5),
118
+ })),
119
+ }
120
+ }
121
+
122
+ const picked = candidates[idx]
123
+ const n = picked.info
124
+ if (!n.absolutePosition || !n.layout) return { matched: 0, total }
125
+
126
+ const resolved =
127
+ typeof n.nodeId === 'number' &&
128
+ typeof t.resolveTapTarget === 'function'
129
+ ? await t.resolveTapTarget(n.nodeId)
130
+ : null
131
+ const target = (resolved && resolved.target) || n
132
+ const cx =
133
+ resolved && typeof resolved.cx === 'number'
134
+ ? resolved.cx
135
+ : n.absolutePosition.x + (n.layout.width || 0) / 2
136
+ const cy =
137
+ resolved && typeof resolved.cy === 'number'
138
+ ? resolved.cy
139
+ : n.absolutePosition.y + (n.layout.height || 0) / 2
140
+ return {
141
+ cx,
142
+ cy,
143
+ match: {
144
+ nodeId: n.nodeId ?? null,
145
+ id: n.id,
146
+ testID: n.testID,
147
+ type: n.type,
148
+ },
149
+ target: {
150
+ nodeId: target.nodeId ?? null,
151
+ id: target.id,
152
+ testID: target.testID,
153
+ text:
154
+ target.text ??
155
+ target.accessibilityLabel ??
156
+ n.text ??
157
+ n.accessibilityLabel ??
158
+ null,
159
+ type: target.type,
160
+ },
161
+ strategy: (resolved && resolved.strategy) || 'matched-node',
162
+ total,
163
+ idx,
164
+ }
165
+ })()`})})}async function Dt(e,a,r={}){let l=JSON.stringify(a);return be(e,{agent:r.agent,timing:r.timing,textFallback:a,resolve:async()=>{let m=await e.send({type:"evaluate",code:`(async () => {
166
+ const t = window.__sootsimTest
167
+ if (!t) return { error: 'bridge-not-ready' }
168
+ const byTestId =
169
+ (await t.findByTestId(${l})) || (await t.findById(${l}))
170
+ if (byTestId && byTestId.absolutePosition && byTestId.layout) {
171
+ return {
172
+ strategy: 'testid',
173
+ node: {
174
+ nodeId: byTestId.nodeId ?? null,
175
+ id: byTestId.id,
176
+ testID: byTestId.testID,
177
+ type: byTestId.type,
178
+ text: byTestId.text,
179
+ absolutePosition: byTestId.absolutePosition,
180
+ layout: byTestId.layout,
181
+ },
182
+ }
183
+ }
184
+ const byText = await t.findByText(${l})
185
+ if (byText && byText.absolutePosition && byText.layout) {
186
+ return {
187
+ strategy: 'text',
188
+ node: {
189
+ nodeId: byText.nodeId ?? null,
190
+ id: byText.id,
191
+ testID: byText.testID,
192
+ type: byText.type,
193
+ text: byText.text,
194
+ absolutePosition: byText.absolutePosition,
195
+ layout: byText.layout,
196
+ },
197
+ }
198
+ }
199
+ return { strategy: 'none' }
200
+ })()`});if(!m||!("node"in m))return m;let i=m.node,g=i.absolutePosition.x+i.layout.width/2,y=i.absolutePosition.y+i.layout.height/2;return{...m,cx:g,cy:y,target:{id:i.id,testID:i.testID,text:m.strategy==="text"?a:i.text,type:i.type}}}})}async function Ct(e,a={args:[]}){let r=await Ze(e);if(A(a.args)){E(r);return}console.log(` nodes: ${r.nodes}`)}function We(e,a){let r=e.indexOf(a);return r>=0&&r+1<e.length?e[r+1]:null}async function Bt(e){let{bridge:a,args:r,positional:l}=e,m=r.includes("--verbose")||r.includes("-v"),i=A(r),g=m&&!i,y=r.includes("--watch")||r.includes("-w"),M=1e3,I=r.includes("--compact"),b=r.includes("--no-xy"),T=r.includes("--no-clipped"),O=r.includes("--include-occluded"),N=We(r,"--testid-like"),P=We(r,"--only"),L=We(r,"--subtree"),d=l[1]&&!l[1].startsWith("-")?l[1]:void 0,G=d?/[*?]/.test(d):!1,j=!G&&!P?d:void 0,B=P??(G?d:void 0),Z=async()=>{await ue(a,{verbose:g});let v=await ot(a,{describe:!0,verbose:m,filter:j||"",testIdLike:N||void 0,onlyGlob:B||void 0,subtreeRoot:L||void 0,compact:I,hideXy:b,includeOccluded:O}),F=v?.tree,W=v?.shell,q=v?.keyboard;if(i){E({shell:W,tree:F??"",keyboard:q});return}if(W&&typeof W=="object"){let C=[W.state?`state=${W.state}`:null,W.activeApp?`app=${W.activeApp}`:null,W.showSwitcher?"switcher":null,W.switcherPhase&&W.switcherPhase!=="idle"?`phase=${W.switcherPhase}`:null].filter(Boolean);C.length>0&&console.log(` shell: ${C.join(" ")}`)}if(typeof F=="string"&&F.startsWith("__SUBTREE_NOT_FOUND__:")){let C=F.slice(22);console.log(` subtree root not found: ${C}`),X("subtree-root-not-found",C);return}if(!F){let C=v?.nodeCount??0;console.log(" no matching nodes found"),!(j||N||B||L)&&C<10&&X("app-still-loading",C);return}let Q=F,ee=0;if(T&&typeof Q=="string"){let C=Q.split(`
201
+ `),ce=[];for(let $e of C){if($e.includes("(clipped:")){ee+=1;continue}ce.push($e)}Q=ce.join(`
202
+ `)}console.log(Q),ee>0&&console.log(` ${ee} clipped row(s) hidden (omit --no-clipped to see)`);let ie=j||N||B||L;if((j||N||B)&&!y&&X("describe-filter-context"),!ie&&!y&&F.split(`
203
+ `).length>=80&&X("describe-use-filters"),q&&q.visible){let C=q.spec,ce=[C?.keyboardType?`type=${C.keyboardType}`:null,C?.returnKeyType&&C.returnKeyType!=="default"?`return=${C.returnKeyType}`:null,q.mode!=="letters"?`mode=${q.mode}`:null,q.shifted?"shift":null,q.capsLock?"caps":null,C?.autoCapitalize&&C.autoCapitalize!=="sentences"?`autoCap=${C.autoCapitalize}`:null,q.accessoryBarId?`accessory=${q.accessoryBarId}`:null].filter(Boolean);console.log(`
204
+ keyboard: ${ce.join(" ")||"visible"}`)}};if(y)for(console.log(` watching... (Ctrl+C to stop)
205
+ `);;)console.clear(),await Z(),await te(M);else await Z()}var Co=["SOOTSIM_AGENT","CLAUDECODE","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_SESSION_ID","CODEX_THREAD_ID","CURSOR_TRACE_ID","AIDER_MODEL"];function pe(){if(process.env.SOOTSIM_AGENT==="0")return!1;for(let e of Co){let a=process.env[e];if(a&&a.trim()&&a!=="0")return!0}return!1}async function jt(e){let{bridge:a,args:r,effectiveArgs:l,positional:m,inspectUsage:i}=e,g=v=>{let F=l.indexOf(v);return F>=0&&F+1<l.length?l[F+1]:null},y=v=>l.includes(v),M=g("--testid")||g("--test-id"),I=g("--role"),b=g("--type"),T=g("--text"),O=y("--pressable"),N=y("--visible"),P=y("--interactive-targets")||y("--actions"),L=!M&&!I&&!b&&!T&&!O&&!N&&!P?m[1]:null,d=T??L,G=await it(a,{testId:M,role:I,type:b,text:d,pressable:O,visible:N,interactive:P});G||(console.error(i("find","<text> | --text <t> | --testid <id> | --role <r> | --type <t> | --pressable | --visible | --interactive-targets")),process.exit(1));let{mode:j,result:B}=G,Z=A(r),se=r.includes("--verbose")||r.includes("--dump");if(Z)j==="interactive-targets"&&Array.isArray(B)?E(De(B).map(v=>({...v,tap:Ce(v)}))):E(B??null);else if(Array.isArray(B))if(B.length===0){console.log(` no ${j} nodes found`);let v=await a.send({type:"evaluate",code:"(async () => (await window.__sootsimTest?.getNodeCount?.()) || 0)()"});typeof v=="number"&&v<10&&X("app-still-loading",v)}else if(j==="interactive-targets"){let v=De(B);console.log(` found ${v.length} interactive target${v.length===1?"":"s"} (sorted by score):`);for(let F of v.slice(0,20)){let W=F.absolutePosition?`@(${Math.round(F.absolutePosition.x)},${Math.round(F.absolutePosition.y)})`:"",q=F.layout?`${Math.round(F.layout.width)}x${Math.round(F.layout.height)}`:"?x?",Q=F.text?` "${F.text.slice(0,30)}"`:"",ee=F.testID?` #${F.testID}`:"",ie=F.accessibilityLabel?` \u24D8"${String(F.accessibilityLabel).slice(0,24)}"`:"",xe=F.accessibilityRole?`[${F.accessibilityRole}]`:F.type,C=Ce(F);console.log(` ${xe}${Q}${ie}${ee} ${q} ${W}`),console.log(` \u2192 ${C}`),se&&console.log(qe(JSON.stringify(F,null,2)," "))}v.length>20&&console.log(` ... and ${v.length-20} more`)}else{console.log(` found ${B.length} node${B.length===1?"":"s"} (${j}):`);for(let v of B.slice(0,20)){let F=v.absolutePosition?`@(${Math.round(v.absolutePosition.x)},${Math.round(v.absolutePosition.y)})`:"",W=v.layout?`${Math.round(v.layout.width)}x${Math.round(v.layout.height)}`:"?x?",q=v.text?` "${v.text.slice(0,30)}"`:"",Q=v.testID?` #${v.testID}`:"",ee=v.pressable?" (tap)":"",ie=v.accessibilityRole?`[${v.accessibilityRole}]`:v.type;console.log(` ${ie}${q}${Q} ${W} ${F}${ee}`),se&&console.log(qe(JSON.stringify(v,null,2)," "))}B.length>20&&console.log(` ... and ${B.length-20} more`)}else if(B==null)console.log(` not found: ${d||M||I||b||""||j}`),M&&X("wait-selector-for-missing-testid",M);else{let v=B;if(v.type&&v.absolutePosition){let F=`@(${Math.round(v.absolutePosition.x)},${Math.round(v.absolutePosition.y)})`,W=v.layout?`${Math.round(v.layout.width)}x${Math.round(v.layout.height)}`:"?x?",q=v.text?` "${v.text.slice(0,40)}"`:"",Q=v.testID?` #${v.testID}`:"",ee=v.pressable?" (tap)":"",ie=v.accessibilityRole?`[${v.accessibilityRole}]`:v.type;console.log(` ${ie}${q}${Q} ${W} ${F}${ee}`),se&&console.log(qe(JSON.stringify(v,null,2)," "))}else console.log(JSON.stringify(B,null,2))}}function qe(e,a){return e.split(`
206
+ `).map(r=>a+r).join(`
207
+ `)}async function Lt(e){let{bridge:a,args:r}=e,l=A(r);await ue(a,{verbose:!l});let m=r.includes("--styling"),i=await st(a,{styling:m});if(l){E({count:i.length,elements:i});return}console.log(` layout (${i.length} element${i.length===1?"":"s"}):
208
+ `),console.log(nt(i,{styling:m}))}async function Jt(e,a={}){let r=await yt(e);if("error"in r&&(console.error(r.error),process.exit(1)),a.json){console.log(JSON.stringify(r,null,2));return}let{visible:l,spec:m,mode:i,shifted:g,capsLock:y,accessoryBarId:M}=r,I=[];I.push(`keyboard: ${l?"visible":"hidden"}`),m?(I.push(` type: ${m.keyboardType}`),I.push(` returnKey: ${m.returnKeyType}`),I.push(` autoCap: ${m.autoCapitalize}`),I.push(` autoCorrect: ${m.autoCorrect?"on":"off"}`),I.push(` appearance: ${m.keyboardAppearance}`),m.secureTextEntry&&I.push(" secureTextEntry: true"),m.enablesReturnKeyAutomatically&&I.push(` return: ${m.currentTextIsEmpty?"disabled (empty)":"enabled"}`)):I.push(" spec: <none> (shown via dev-tools with no TextInput)"),I.push(` mode: ${i}${g?" (shifted)":""}${y?" (caps)":""}`),M&&I.push(` accessoryBar: ${M}`),console.log(I.join(`
209
+ `))}async function Wt(e){let a=await e.bridge.listSims(),r=e.args.includes("--all"),l=e.args.find((y,M)=>e.args[M-1]==="--bundle"),m=e.args.find((y,M)=>e.args[M-1]==="--app-port"),i=e.args.includes("--primary"),g=a.filter(y=>!(i&&!y.isPrimary||l&&!(y.url??"").includes(l)||m&&!(y.url??"").includes(`/rn/${m}`)||!r&&!l&&!m&&!i&&!(y.url&&(y.url.includes("bundle=")||y.url.includes("/index.bundle")))&&y.id!==e.simId));if(A(e.args)){E(g.map(y=>({...y,active:y.id===e.simId})));return}_t(g,e.simId),g.length<a.length&&!A(e.args)&&console.log(` (${a.length-g.length} more hidden \u2014 pass --all to show)`)}function le(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function Ne(e,a){return a<=0?"?":`${(e/a*100).toFixed(0)}%`}async function qt(e,a={args:[]}){let r=await ht(e);if(A(a.args)){E(r);return}if(console.log(" memory:"),r.imageLoader){let l=r.imageLoader;console.log(" image-loader cache"),console.log(` entries: ${l.cacheEntries} / ${l.cacheMaxEntries} (${Ne(l.cacheEntries,l.cacheMaxEntries)})`),console.log(` pixel bytes: ${le(l.cachePixelBytes)} / ${le(l.cachePixelBudget)} (${Ne(l.cachePixelBytes,l.cachePixelBudget)})`),console.log(` pending: ${l.pendingFetches} fetches, ${l.pendingBytes} bytes`),console.log(` failed uris: ${l.failedUris}`),console.log(` snapshots: ${l.snapshots}`),console.log(` live frames: ${l.liveFrames}`)}else console.log(" image-loader cache: not available (engine pre-rebuild?)");if(r.workerHeap){let l=r.workerHeap;console.log(" worker heap (chrome only)"),console.log(` used: ${le(l.usedJSHeapSize)} / ${le(l.jsHeapSizeLimit)} (${Ne(l.usedJSHeapSize,l.jsHeapSizeLimit)})`),console.log(` total: ${le(l.totalJSHeapSize)}`)}if(r.hostHeap){let l=r.hostHeap;console.log(" host heap (chrome only)"),console.log(` used: ${le(l.usedJSHeapSize)} / ${le(l.jsHeapSizeLimit)} (${Ne(l.usedJSHeapSize,l.jsHeapSizeLimit)})`),console.log(` total: ${le(l.totalJSHeapSize)}`)}}var V="<redacted secure text>";function he(e){let a=e?.layout?.spec??e?.spec??null;return!!a?.secureTextEntry&&a.keyboardType!=="visible-password"}function He(e,a){return he(a)?V:e}function Ke(e){if(!e||!he(e))return e;let a=e.focusedInput;return!a||typeof a!="object"?e:{...e,focusedInput:{...a,secureTextEntry:!0,text:typeof a.text=="string"?V:a.text}}}function we(e){let a=e.indexOf("--testid");if(a>=0&&e[a+1])return{mode:"testid",value:e[a+1]};let r=e.indexOf("--test-id");if(r>=0&&e[r+1])return{mode:"testid",value:e[r+1]};let l=e.indexOf("--text");return l>=0&&e[l+1]?{mode:"text",value:e[l+1]}:null}async function Fe(e,a){let r=JSON.stringify(a.value),l=a.mode==="testid"?`(await t.findByTestId(${r})) || (await t.findById(${r}))`:`await t.findByText(${r})`;return await e.send({type:"evaluate",code:`(async () => {
210
+ const t = window.__sootsimTest
211
+ if (!t) return null
212
+ const n = ${l}
213
+ if (!n || !n.absolutePosition || !n.layout) return null
214
+ const resolved =
215
+ typeof n.nodeId === 'number' && typeof t.resolveTapTarget === 'function'
216
+ ? await t.resolveTapTarget(n.nodeId)
217
+ : null
218
+ const cx =
219
+ typeof resolved?.cx === 'number'
220
+ ? resolved.cx
221
+ : n.absolutePosition.x + (n.layout.width || 0) / 2
222
+ const cy =
223
+ typeof resolved?.cy === 'number'
224
+ ? resolved.cy
225
+ : n.absolutePosition.y + (n.layout.height || 0) / 2
226
+ return {
227
+ x: cx,
228
+ y: cy,
229
+ id: n.id ?? null,
230
+ testID: n.testID ?? null,
231
+ text: ${JSON.stringify(a.mode==="text")} ? ${r} : (n.text ?? n.accessibilityLabel ?? null),
232
+ type: n.type ?? null,
233
+ }
234
+ })()`})??null}async function Ht(e,a={}){let{nav:r,keyboard:l,shell:m}=await bt(e);if(a.json){console.log(JSON.stringify({shell:m??null,nav:r,keyboard:l},null,2));return}let i=[];if(m){let g=m.activeApp??m.state??"<none>",y=m.showSwitcher?" (app switcher open)":"",M=typeof m.launchProgress=="number"&&m.launchProgress<.98?` launching (${Math.round(m.launchProgress*100)}%)`:"";i.push(`shell: ${g}${y}${M}`)}else i.push("shell: <unavailable>");if(r){let g=r.transitionPhase!=="idle"?` (${r.transitionPhase}, ${r.activeTransitionCount} active)`:"";if(i.push(`nav: phase=${r.transitionPhase}${g}`),r.screens.length===0)i.push(" <no registered screens \u2014 app may not use react-native-screens>");else for(let y of r.screens){let M=y.isActive?"\u25B6":" ",I=y.routeName?` ${y.routeName}`:"",b=y.headerHeight>0?` header=${y.headerHeight}`:"",T=y.largeTitleState&&y.largeTitleState!=="expanded"?` large-title=${y.largeTitleState}`:"";i.push(` ${M} #${y.id}${I}${b}${T}`)}}else i.push("nav: <runtime not available>");if(l&&l.visible){let g=l.spec?.keyboardType??"default",y=l.spec?.returnKeyType??"default";i.push(`keyboard: visible (${g}, return=${y}, mode=${l.mode??"?"})`)}else i.push("keyboard: hidden");console.log(i.join(`
235
+ `))}async function Kt(e){let{bridge:a,args:r,positional:l}=e,m=l[1]?Number(l[1])*1e3:3e3,i=r.includes("--strict"),{elapsed:g,settled:y}=await oe({bridge:a,maxMs:m,strict:i});console.log(y?` settled in ${g}ms`:` timed out after ${g}ms (may still be animating)`)}async function Ut(e){let a=e.positional[1]?Number(e.positional[1]):.5;(!Number.isFinite(a)||a<0)&&(console.error(e.inspectUsage("sleep","[seconds]")),process.exit(1)),await te(a*1e3),console.log(` slept ${a}s`)}async function zt(e){let{bridge:a,args:r,positional:l}=e,m=l[1]?Number(l[1]):5,{tree:i}=await et(a,m);if(A(r)){E({depth:m,tree:i??null});return}console.log(typeof i=="string"?i:JSON.stringify(i,null,2))}async function Gt(e,a={args:[]}){let r=await tt(e);if(A(a.args)){E(r);return}console.log(r.url)}async function Yt(e){let{wsPort:a,commandTimeoutMs:r,simId:l,simIdSource:m,positional:i}=e,g=i[1]?Number(i[1]):30,y=Math.max(1e3,(Number.isFinite(g)?g:30)*1e3),M=Math.max(1,Math.ceil(y/500));console.log(" waiting for sim reconnect...");let I=await vt(a,r,l,{attempts:M,simIdSource:m});I||(console.error(" timed out waiting for sim reconnect"),process.exit(1)),I.bridge.close(),Ie({source:"inspect wait",step:{wait:y},summary:`wait ${Math.round(y/1e3)}s`}),console.log(` ready: ${I.count} nodes`)}var Xt=new Set(["app-launch","toast","keyboard","screen","route","alert","actionsheet","picker","notification","fetch","console","shell","scroll","gesture","text-input","react-commit","animation","reanimated"]);function _e(e,a){let r=e.indexOf(a);if(r>=0&&r+1<e.length)return e[r+1]}function Bo(e,a){if(!a.filter&&!a.equals)return!0;let r=e.data,l=[];if(r&&typeof r=="object")for(let i of["url","displayUrl","message","name","activeName","path","pathname","title","phase","event","type","kind"]){let g=r[i];typeof g=="string"&&g.length>0&&l.push(g)}let m=l.join(" ");return a.equals?l.some(i=>i===a.equals):a.filter?m.toLowerCase().includes(a.filter.toLowerCase()):!0}async function Vt(e){let{bridge:a,args:r,positional:l,inspectUsage:m}=e,i=l[1];i||(console.error(m("wait event","<kind> [--max-ms 5000] [--filter <substring>] [--equals <exact>] [--since now|cursor]")),process.exit(1)),Xt.has(i)||console.error(` warning: '${i}' is not a known timeline kind \u2014 waiting anyway. known: ${[...Xt].sort().join(", ")}`);let g=_e(r,"--max-ms"),y=g&&Number.isFinite(Number(g))?Math.max(100,Number(g)):5e3,M=_e(r,"--filter"),I=_e(r,"--equals"),b=_e(r,"--since")??"now",T=r.includes("--json"),O=Date.now(),N=O+y,P=200,L=O;for(;Date.now()<N;){let G={kinds:[i],since:b==="cursor"?void 0:L,limit:50},j=await a.send({type:"evaluate",code:`(async () => {
236
+ const t = window.SootSim?.bridges?.timeline
237
+ if (!t) return { ok: false, error: 'timeline bridge missing' }
238
+ return { ok: true, result: await t.recent(${JSON.stringify(G)}) }
239
+ })()`});(!j||!j.ok)&&(console.error(` could not query timeline: ${j&&"error"in j?j.error:"unknown"}`),process.exit(1));let B=j.result.events??[];for(let Z of B)if(Bo(Z,{filter:M,equals:I})){let se=Date.now()-O;console.log(T?JSON.stringify({found:!0,elapsedMs:se,event:Z}):` ${i} event after ${se}ms${M?` (filter: ${M})`:""}${I?` (equals: ${I})`:""}`);return}j.result.watermark&&j.result.watermark>L&&(L=j.result.watermark),await new Promise(Z=>setTimeout(Z,P))}let d=Date.now()-O;T?console.log(JSON.stringify({found:!1,elapsedMs:d,kind:i,filter:M,equals:I})):console.error(` \u26A0 wait event ${i} timed out after ${d}ms${M?` (filter: ${M})`:""}${I?` (equals: ${I})`:""}`),process.exit(1)}async function Qt(e){let{bridge:a,args:r}=e,l=r.includes("--strict"),m=ve(r,3e3),{elapsed:i,settled:g}=await oe({bridge:a,maxMs:m,strict:l});g?console.log(` idle in ${i}ms`):(console.error(` \u26A0 wait idle timed out after ${i}ms (may still be animating)`),process.exit(1))}async function Zt(e){let{bridge:a,args:r}=e,l=ve(r,2e4),{ready:m,elapsedMs:i,nodes:g,targets:y,flag:M,loadingText:I,externalReady:b,externalError:T,errors:O}=await at(a,l,{onProgress(P){console.error(` still waiting after ${P.elapsedMs}ms \u2014 ${Be(P)} (nodes: ${P.nodes}, targets: ${P.targets}, errors: ${P.errors})`)}});if(m){let P=l-i,L=Math.max(100,Math.min(1e4,P)),d=await oe({bridge:a,maxMs:L,pollMs:32,stablePolls:2});d.settled||(console.error(` \u26A0 wait ready timed out after ${i+d.elapsed}ms \u2014 app mounted but did not settle (nodes: ${g}, targets: ${y})`),process.exit(1)),console.log(` ready in ${i+d.elapsed}ms: ${g} nodes, ${y} targets`);return}let N=Be({externalError:T,loadingText:I,externalReady:b,flag:M,targets:y});console.error(` \u26A0 wait ready timed out after ${i}ms \u2014 ${N} (nodes: ${g}, targets: ${y}, errors: ${O})`),process.exit(1)}async function eo(e){let{bridge:a,args:r,positional:l,inspectUsage:m}=e,i=l[1];i||(console.error(m("wait selector","<testid> [--max-ms 5000] [--gone]")),process.exit(1));let g=r.indexOf("--max-ms"),y=g>=0&&r[g+1]?Math.max(100,Number(r[g+1])):5e3,M=r.includes("--gone"),{found:I,node:b,elapsed:T}=await lt(a,i,y,{gone:M});if(M){I?console.log(` #${i} gone after ${T}ms`):(console.error(` \u26A0 wait selector #${i} --gone timed out after ${T??y}ms (still present)`),process.exit(1));return}if(I&&b){let O=b.absolutePosition?`@(${Math.round(b.absolutePosition.x)},${Math.round(b.absolutePosition.y)})`:"",N=b.layout?`${Math.round(b.layout.width)}x${Math.round(b.layout.height)}`:"?x?";console.log(` found #${i} in ${T}ms ${N} ${O}`)}else console.error(` \u26A0 wait selector #${i} timed out after ${T??y}ms`),process.exit(1)}function co(e){return e==null?"\u2014":e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}K`:`${(e/1024/1024).toFixed(1)}M`}function uo(e){return e==null?" \u2026":e<1e3?`${e}ms`.padStart(5):`${(e/1e3).toFixed(2)}s`.padStart(5)}function to(){process.stderr.write(` the sim is not responding. recover it with:
240
+ sootsim close --sim <id> # force-close the wedged sim
241
+ sootsim list # confirm it's gone
242
+ `)}async function Lo(e){try{return await e.send({type:"evaluate",code:"1"},{timeoutMs:3e3}),!0}catch{return!1}}async function Jo(e,a){try{let r=await e.send({type:"evaluate",code:`(async () => {
243
+ const t = window.__sootsimTest
244
+ if (!t || typeof t.queryAll !== 'function') return []
245
+ try {
246
+ // queryAll is async in render-worker mode (the canonical mode now)
247
+ // because the call has to round-trip the worker \u2014 must await it.
248
+ // a sync result is still handled fine since await on a non-Promise
249
+ // is a no-op.
250
+ const nodes = await t.queryAll({})
251
+ if (!Array.isArray(nodes)) return []
252
+ const out = new Set()
253
+ for (const n of nodes) {
254
+ const id = n && (n.testID || n.id)
255
+ if (typeof id === 'string' && id) out.add(id)
256
+ }
257
+ return Array.from(out)
258
+ } catch {
259
+ return []
260
+ }
261
+ })()`});if(!Array.isArray(r)||r.length===0)return;let l=a.toLowerCase(),m=r.map(i=>({id:i,score:Wo(l,i.toLowerCase())})).filter(i=>i.score<l.length+4).sort((i,g)=>i.score-g.score).slice(0,5);if(m.length===0)return;console.error(" similar testIDs:");for(let i of m)console.error(` ${i.id}`)}catch{}}function Wo(e,a){if(a===e)return 0;if(a.includes(e))return 1;if(e.includes(a))return 2;let r=0;for(;r<e.length&&r<a.length&&e[r]===a[r];)r+=1;return qo(e,a)-r}function qo(e,a){if(e===a)return 0;if(!e.length)return a.length;if(!a.length)return e.length;let r=new Array(a.length+1),l=new Array(a.length+1);for(let m=0;m<=a.length;m++)r[m]=m;for(let m=1;m<=e.length;m++){l[0]=m;for(let g=1;g<=a.length;g++)l[g]=Math.min(r[g]+1,l[g-1]+1,r[g-1]+(e[m-1]===a[g-1]?0:1));let i=r;r=l,l=i}return r[a.length]}function Ho(e){return e.error?"err":e.status==null?" \u2026 ":String(e.status)}function oo(e){return e.externalError?`guest app errored: ${e.externalError}`:e.loadingText?`still showing "${e.loadingText}"`:e.externalReady===!1?"guest app is still loading":e.flag!==!0?"guest app has not emitted sootsim:externalAppReady":e.targets<=0?"ready flag emitted but no visible app content is inspectable yet":"node tree is still changing"}function so(e){let a=ae(e.startTs),r=Ho(e).padEnd(3),l=e.method.padEnd(5),m=co(e.size).padStart(6),i=uo(e.durationMs);console.log(` [${a}] ${r} ${l} ${m} ${i} ${e.displayUrl}`),e.error&&console.log(` error: ${e.error}`)}function Ko(e){let a=[["id",e.id],["source",e.source],["kind",e.kind],["method",e.method],["status",e.error?`error: ${e.error}`:`${e.status??"\u2014"} ${e.statusText??""}`.trim()],["url",e.url],["started",ae(e.startTs)],["duration",uo(e.durationMs).trim()],["size",co(e.size)],["content-type",e.type??"\u2014"]];for(let[r,l]of a)console.log(` ${r.padEnd(13)} ${l}`)}var Uo={error:"\x1B[31m",warn:"\x1B[33m",info:"\x1B[36m",debug:"\x1B[35m",log:"\x1B[37m"},no="\x1B[0m",zo="\x1B[2m";function ro(e,a){let r=ae(e.ts),l=e.level.toUpperCase().padEnd(5),m=e.args.join(" ");if(a){let i=Uo[e.level];console.log(` ${zo}[${r}]${no} ${i}${l}${no} ${m}`)}else console.log(` [${r}] ${l} ${m}`);if(e.stack&&e.level==="error"){let i=e.stack.split(`
262
+ `).slice(0,5);for(let g of i)console.log(` ${g.trim()}`)}}var re="__sootsimCliPerf",Go=120;async function io(e,a){let r=e.find((O,N)=>e[N-1]==="--id"),l=e.find((O,N)=>e[N-1]==="--text");if(r||l){let O=await a.send({type:"evaluate",code:Mt({id:r,text:l})});if(!O)throw new Error(r?`no node with id "${r}"`:`no node matching text "${l}"`);let{x:N,y:P,w:L,h:d}=O;return{x:N,y:P,w:L,h:d}}let m=e.find((O,N)=>e[N-1]==="--area");if(m){let O=m.split(",").map(G=>Number(G.trim()));if(O.length!==4||O.some(G=>!Number.isFinite(G)))throw new Error(`--area expects x,y,w,h (got "${m}")`);let[N,P,L,d]=O;return{x:N,y:P,w:L,h:d}}let i=O=>{let N=e.find((L,d)=>e[d-1]===O);if(N==null)return null;let P=Number(N);return Number.isFinite(P)?P:null},g=i("--x"),y=i("--y"),M=i("--w"),I=i("--h");if(g!=null||y!=null||M!=null||I!=null)return{x:g??0,y:y??0,w:M??1,h:I??1};let T=e.filter((O,N)=>N>0&&!O.startsWith("-")&&e[N-1]!=="--output"&&e[N-1]!=="--area"&&e[N-1]!=="--id"&&e[N-1]!=="--text"&&e[N-1]!=="--x"&&e[N-1]!=="--y"&&e[N-1]!=="--w"&&e[N-1]!=="--h").map(Number).filter(O=>Number.isFinite(O));if(T.length>=2){let[O,N,P=1,L=1]=T;return{x:O,y:N,w:P,h:L}}return null}function Ue(e){let a={"<8":0,"8-12":0,"12-16":0,"16-20":0,"20-33":0,">33":0};for(let r of e)r<8?a["<8"]++:r<12?a["8-12"]++:r<16?a["12-16"]++:r<20?a["16-20"]++:r<33?a["20-33"]++:a[">33"]++;console.log(" histogram:");for(let[r,l]of Object.entries(a)){let m="\u2588".repeat(Math.ceil(l/e.length*40));console.log(` ${r.padEnd(6)} ${m} ${l}`)}}async function Oe(e,a,r){let l=Date.now()+a,m=await de(e,a);for(;;){if(r(m))return{settled:!0,state:m};if(Date.now()>=l)return{settled:!1,state:m};await te(16),m=await de(e)}}async function Ge(e){return e.send({type:"evaluate",code:`(async () => {
263
+ const kb = window.__sootsimKeyboard
264
+ const test = window.__sootsimTest
265
+ if (!kb) return { error: 'keyboard bridge not available' }
266
+ const layout = typeof kb.getLayout === 'function' ? kb.getLayout() : null
267
+ const secureTextEntry =
268
+ !!layout?.spec?.secureTextEntry && layout?.spec?.keyboardType !== 'visible-password'
269
+ const visible = kb.isVisible()
270
+ const mode = kb.getMode()
271
+ let focused = null
272
+ if (test && typeof test.getFocusedNode === 'function') {
273
+ try {
274
+ focused = await test.getFocusedNode()
275
+ } catch {}
276
+ }
277
+ let runtimeSnapshot = null
278
+ if (test && typeof test.getFocusKeyboardSnapshot === 'function') {
279
+ try {
280
+ runtimeSnapshot = await test.getFocusKeyboardSnapshot()
281
+ } catch {}
282
+ }
283
+ return {
284
+ visible,
285
+ mode,
286
+ layout,
287
+ focusedInput: focused ? {
288
+ nodeId: focused.nodeId ?? null,
289
+ testID: focused.testID || null,
290
+ id: focused.id || null,
291
+ placeholder: focused.placeholder || null,
292
+ secureTextEntry,
293
+ text: secureTextEntry ? ${JSON.stringify(V)} : (focused.text || null),
294
+ } : null,
295
+ phase: runtimeSnapshot?.keyboard?.phase ?? null,
296
+ frame: runtimeSnapshot?.keyboard?.frame ?? null,
297
+ focusedRect: runtimeSnapshot?.focused?.rect ?? null,
298
+ }
299
+ })()`}).then(a=>Ke(a))}function Yo(e,a,r){if(!e.visible)return!1;let l=e.focusedInput;return!(a&&l&&!(l.testID===a||l.id===a)||r!==null&&he(e)!==r)}async function Xo(e,a=600,r={}){let l=Date.now()+a;for(;Date.now()<=l;){let m=await Ge(e);if(Yo(m,r.targetId??null,r.secureTextEntry??null))return m;await te(30)}return Ge(e)}async function Ae(e,a){let r=await Ge(e);if(r.visible)return r;console.error(` ${a} requires the iOS keyboard to be visible. focus an input first with sootsim do tap-id/tap-text or sootsim do type-into.`),process.exit(1)}async function ao(e,a,r){return a==="appearance"?e.send({type:"evaluate",code:`(async () => {
300
+ const requested = ${JSON.stringify(r??"toggle")}
301
+ // the engine owns toggle + auto resolution (settingsStore is the single
302
+ // source of truth). never infer the current scheme client-side \u2014 the old
303
+ // documentElement '#333333' sniff is never set in embedded / shell-chrome
304
+ // contexts, so 'toggle' read 'light' forever and stuck on the boot scheme.
305
+ window.postMessage({ type: 'soot-action', action: 'set-appearance', value: requested }, '*')
306
+ // let the engine's message handler apply + publish window.__sootsimColorScheme
307
+ await new Promise((r) => setTimeout(r, 60))
308
+ const applied = window.__sootsimColorScheme?.resolved
309
+ ?? (window.matchMedia?.('(prefers-color-scheme: dark)')?.matches ? 'dark' : 'light')
310
+ const setting = window.__sootsimColorScheme?.setting ?? requested
311
+ return { ok: true, requested, setting, applied }
312
+ })()`}):a==="lock"?e.send({type:"evaluate",code:`(async () => {
313
+ const toggleLock = window.SootSim?.bridges?.mainShell?.toggleLock
314
+ if (typeof toggleLock !== 'function') {
315
+ throw new Error('SootSim mainShell.toggleLock bridge unavailable')
316
+ }
317
+ await toggleLock()
318
+ return { ok: true, action: 'lock' }
319
+ })()`}):e.send({type:"evaluate",code:`(async () => {
320
+ window.dispatchEvent(new CustomEvent('sootsim:shake'))
321
+ return { ok: true, action: 'shake' }
322
+ })()`})}function Vo(e){let a={Enter:"return",NumpadEnter:"return",Backspace:"delete",Delete:"delete",Space:"space",ShiftLeft:"shift",ShiftRight:"shift"};if(a[e])return a[e];let r=e.match(/^Digit([0-9])$/);if(r)return r[1];let l=e.match(/^Key([A-Z])$/);return l?l[1].toLowerCase():null}function Qo(e){if(typeof e!="string")return null;let a=e.replace(/\s+/g," ").trim();return a?a.slice(0,80):null}function mo(...e){for(let a of e){if(typeof a!="string")continue;let r=a.trim();if(r)return r}return null}function Zo(e){let a=e.indexOf("--node-id");if(a<0)return null;let r=e[a+1];if(!r)return null;let l=Number(r);return Number.isInteger(l)&&l>0?l:null}async function J(e,a,r){let l=Ie({source:e,step:a,summary:r});l.active&&(l.replaced?console.error(` draft: replaced unkept action "${l.replaced.summary}" \u2014 \`flow keep\` commits one action at a time`):console.error(" draft: action pending \u2014 `sootsim flow keep` to commit"))}function lo(e,a,r){if(!r||r.hit===!1)return null;let l=mo(r.responderTestID,r.testID);if(l)return{step:{tapOn:{id:l}},summary:`tap #${l}`};let m=Qo(r.text);return m?{step:{tapOn:m},summary:`tap "${m}"`}:{step:{tapAtCoords:{x:e,y:a}},summary:`tap @${Math.round(e)},${Math.round(a)}`}}function ze(e,a,r){let l=mo(a?.testID,a?.id);return l?{step:{tapOn:{id:l}},summary:`tap #${l}`}:r==="id"?{step:{tapOn:{id:e}},summary:`tap #${e}`}:{step:{tapOn:e},summary:`tap "${e}"`}}async function Hn(e,a){let r=e[0]==="get"||e[0]==="do"||e[0]==="debug"||e[0]==="wait"?e[0]:null,l=r?e.slice(1):e,m=wt(l,{port:a.port,commandTimeoutMs:a.timeoutMs,stripBooleanFlags:["--verbose","-v","--help","-h","--clear-state","--json","--all","--watch","-w","--strict","--no-wait","--dump","--failed","--slow","--tail","-f","--interactive-targets","--actions","--internal","--compact","--no-xy","--no-clipped","--include-occluded"],stripValueFlags:["--output","--nth","--index","--testid","--test-id","--text","--node-id","--max-ms","--filter","--limit","--level","--threshold","--equals","--since","--testid-like","--only","--subtree"]}),i=m.positional,g=i[0],y=r==="get"||r==="do"||r==="debug"||r==="wait"?r:"inspect",M=typeof l[0]=="string"&&Ye.has(l[0]),I=M?l[0]:null,b=$=>M&&$===l[0]?`sootsim ${$}`:`sootsim ${y} ${$}`,T=($,o)=>` usage: ${b($)}${o?` ${o}`:""}`;if(!g||e.includes("--help")||e.includes("-h")){let $={bridgePort:7668,defaultShellUrl:Xe};if(y==="do"||y==="get"||y==="debug"||y==="wait"){let s=Ee(y,$);s&&(console.log(`${s}
323
+ `),process.exit(0))}if(I==="shell"){let s=Pe("shell",$);s&&(console.log(`${s}
324
+ `),process.exit(0))}let o=Pe("inspect",$),t=["do","get","debug","wait"].map(s=>Ee(s,$)).filter(s=>s!=null).join(`
325
+
326
+ `);console.log(`${o??""}
327
+
328
+ ${t}
329
+ `),process.exit(0)}let O=m.wsPort,N=m.simId,P=m.simIdSource,L=m.commandTimeoutMs;if(g==="list"&&l.some($=>$==="--drivers"||$==="-D")){let{buildDriverListRows:$}=await import("./drivers-UMQTPEMU.js"),o=$();console.log(` available drivers (${o.length}):
330
+ `);let t=Math.max(...o.map(n=>n.id.length),6),s=Math.max(...o.map(n=>n.kind.length),4);for(let n of o){let c=n.available?"\u2713":"\u2717",u=n.id.padEnd(t),p=n.kind.padEnd(s);console.log(` ${c} ${u} ${p} ${n.description}`),n.available&&n.detail?console.log(` ${n.detail}`):!n.available&&n.reason&&console.log(` unavailable: ${n.reason}`)}return}let d=xt(m),G=N||"default",j=new Set(["errors","warnings","requests","js","eval","reload","globals","perf","storage-clear","list","wait","sleep"]),B=200;function Z($){let o=$.replace(/\s+/g," ").trim();if(!o)return"";if(/^<(!doctype html|html|\?xml)|<body[\s>]/i.test(o)){let s=/<title[^>]*>([^<]+)<\/title>/i.exec($)?.[1]?.trim(),n=/<body[^>]*>([\s\S]*?)<\//i.exec($)?.[1]?.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().slice(0,80),c=s||n||"html error page";return`<html ${$.length}B> "${c}" (body elided \u2014 add --json for the full payload)`}return o.length<=B?o:`${o.slice(0,B)}\u2026 (+${o.length-B} more bytes)`}function se($){let o=$.displayUrl||$.url;return $.status!=null?`${$.method} ${o} -> ${$.status}${$.statusText?` ${$.statusText}`:""}`:$.error?`${$.method} ${o} -> ${$.error}`:`${$.method} ${o}`}async function v($){let o=pe()?5e3:1500;try{let{settled:t,elapsed:s}=await oe({bridge:$,maxMs:o,pollMs:32,stablePolls:2});t||process.stderr.write(` \u26A0 auto-wait timed out after ${s??o}ms \u2014 next command may see mid-animation state. use \`sootsim do settle\` for a longer wait.
331
+ `)}catch{}}function F($,o){console.error(` tap failed: ${$} stayed visible but did not receive a hittable press after ${o.attempts} attempt${o.attempts===1?"":"s"}`),o.result&&console.error(` last result: ${JSON.stringify(o.result)}`)}async function W(){try{return await d.send({type:"evaluate",code:`(() => ({
332
+ console: ${ke},
333
+ requests: window.__sootsimTest?.getRequestCounts?.() || null,
334
+ }))()`})||{console:null,requests:null}}catch{return{console:null,requests:null}}}async function q($={}){let o=$.counts!==void 0?$.counts:await Y(d,"getRequestCounts");if(!o||typeof o!="object")return;let t=Math.max(0,Number(o.failed)||0);if(t===0||!$.includeTail&&!Je("requests",G,String(t))||(console.log(`
335
+ network: ${t} failed request${t===1?"":"s"}`),console.log(` inspect: ${b("requests")} 5`),!$.includeTail))return;let s=await Y(d,"getFailedRequests",5);if(!(!Array.isArray(s)||s.length===0)){console.log(`
336
+ recent failed requests:
337
+ `);for(let n of s){let c=ae(n.timestamp);console.log(` [${c}] ${se(n)}`),n.responseBody?console.log(` ${Z(n.responseBody)}`):n.error&&console.log(` ${n.error}`)}}}function Q($){for(let o of $){let t=o.title?` (\u201C${o.title}\u201D)`:"";console.log(`
338
+ note: ${o.label} is open${t} \u2014 taps/drags hit it, not the app`)}}async function ee($={}){let o=$.counts!==void 0?$.counts:await d.send({type:"evaluate",code:ke});if(!o||typeof o!="object")return;let t=o,s=Math.max(0,Number(t.errors)||0),n=Math.max(0,Number(t.warnings)||0);if(s===0&&n===0||!$.includeTail&&!Je("console",G,`${s}:${n}`))return;let c=[];if(s>0&&c.push(`${s} console error${s===1?"":"s"}`),n>0&&c.push(`${n} console warning${n===1?"":"s"}`),console.log(`
339
+ console: ${c.join(", ")}`),console.log(` inspect: ${b("errors")} 5`),n>0&&console.log(` inspect: ${b("warnings")} 5`),!$.includeTail||s===0)return;let u=await fe(d,5);if(!(!Array.isArray(u)||u.length===0)){console.log(`
340
+ recent console errors:
341
+ `);for(let p of u){let h=ae(p.timestamp),f=Array.isArray(p.args)?p.args.map(x=>typeof x=="object"?JSON.stringify(x):String(x)).join(" "):String(p);console.log(` [${h}] ${f}`)}}}let ie=["console","fetch","toast","alert","notification","screen","app-launch","keyboard","route","actionsheet","picker","shell","scroll","gesture","text-input","animation","reanimated"];async function xe($){let o=Ve(),t=null;try{t=await St($,`(() => {
342
+ const tl = window.SootSim && window.SootSim.bridges && window.SootSim.bridges.timeline
343
+ if (!tl || typeof tl.summary !== 'function') return null
344
+ const cursorKey = ${JSON.stringify(o)}
345
+ const summary = tl.summary({ sinceCursor: cursorKey })
346
+ let consoleSplit = null
347
+ if (summary && summary.byKind && summary.byKind.console) {
348
+ const events = tl.recent({ sinceCursor: cursorKey, kinds: 'console', limit: 100000 }).events
349
+ consoleSplit = { error: 0, warn: 0 }
350
+ for (const ev of events) {
351
+ const lvl = ev && ev.data && ev.data.level
352
+ if (lvl === 'error') consoleSplit.error++
353
+ else if (lvl === 'warn') consoleSplit.warn++
354
+ }
355
+ }
356
+ return summary ? { summary, consoleSplit } : null
357
+ })()`)}catch{return}if(!t||!t.summary||!t.summary.total)return;let s=t.summary.byKind??{},n=[],c=new Set;for(let u of ie){let p=s[u];if(p)if(c.add(u),u==="console"&&t.consoleSplit){let{error:h,warn:f}=t.consoleSplit;h>0&&n.push(`${h} error${h===1?"":"s"}`),f>0&&n.push(`${f} warning${f===1?"":"s"}`)}else n.push(`${p} ${u}${p===1?"":"s"}`)}for(let[u,p]of Object.entries(s))!c.has(u)&&p&&n.push(`${p} ${u}${p===1?"":"s"}`);if(n.length!==0&&(console.log(`
358
+ since last: ${n.join(" \xB7 ")} \u2014 sootsim what-happened`),t.summary.lastAt))try{await Te($,"SootSim.bridges.timeline.cursorAdvance",o,t.summary.lastAt)}catch{}}let C=new Set(["tap","double-tap","tap-text","tap-id","type","type-into","key","key-sequence","keycode","drag","swipe","long-press","touch","gesture","pinch","scroll","shell","storage-clear"]),ce=new Set(["a11y","capture","count","double-tap","drag","find","gesture","layout","long-press","node","pinch","sample-color","scroll","screenshot","swipe","tap","tap-id","tap-text","touch","tree","type-into"]),$e=(e.includes("--verbose")||e.includes("-v"))&&!e.includes("--json");y==="do"&&g==="shell"&&(console.error(" `sootsim do shell` was removed. use `sootsim shell ...` instead."),process.exit(1)),C.has(g)&&await $t(d),ce.has(g)&&await ue(d,{verbose:$e});try{let $=C.has(g)&&!A(l)?await gt(d):[];switch(g){case"list":{await Wt({bridge:d,simId:N,args:l});break}case"tree":{await zt({bridge:d,args:l,positional:i});break}case"a11y":{let o=await rt(d);if(!Array.isArray(o)||o.length===0){console.log(" no accessible nodes found");break}if(e.includes("--json"))console.log(JSON.stringify(o,null,2));else{console.log(` accessibility tree (${o.length} nodes):
359
+ `);for(let t of o){let s=[];if(s.push(`[${t.role}]`),t.label){let n=t.label.length>50?t.label.slice(0,47)+"...":t.label;s.push(`"${n}"`)}if(t.hint&&s.push(`(hint: "${t.hint}")`),t.testID&&s.push(`#${t.testID}`),t.state){let n=[];t.state.disabled&&n.push("disabled"),t.state.selected&&n.push("selected"),t.state.checked===!0&&n.push("checked"),t.state.checked==="mixed"&&n.push("mixed"),t.state.busy&&n.push("busy"),t.state.expanded===!0&&n.push("expanded"),t.state.expanded===!1&&n.push("collapsed"),n.length&&s.push(`{${n.join(", ")}}`)}t.position&&s.push(`@(${t.position.x},${t.position.y})`),t.size&&s.push(`${t.size.w}x${t.size.h}`),console.log(" "+s.join(" "))}}break}case"find":{await jt({bridge:d,args:e,effectiveArgs:l,positional:i,inspectUsage:T});break}case"count":{await Ct(d,{args:l});break}case"keyboard":{await Jt(d,{json:e.includes("--json")});break}case"screens":{await Ht(d,{json:e.includes("--json")});break}case"memory":{await qt(d,{args:l});break}case"wait":{await Yt({wsPort:O,commandTimeoutMs:L,simId:N,simIdSource:P,positional:i});break}case"sleep":{await Ut({positional:i,inspectUsage:T});break}case"settle":{await Kt({bridge:d,args:e,positional:i});break}case"ready":{await Zt({bridge:d,args:e});break}case"idle":{await Qt({bridge:d,args:e,positional:i});break}case"selector":{await eo({bridge:d,args:e,positional:i,inspectUsage:T});break}case"event":{await Vt({bridge:d,args:e,positional:i,inspectUsage:T});break}case"layout":{let o=i[1];if(!o){await Lt({bridge:d,args:l});break}let t=await d.send({type:"evaluate",code:`(async () => await window.__sootsimTest.getLayout(${JSON.stringify(o)}))()`});console.log(JSON.stringify(t,null,2));break}case"capture":case"screenshot":{let t=e.find((h,f)=>e[f-1]==="--output")||"/tmp/sootsim-inspect.png",s=await io(e,d),n={type:"screenshot"};s&&(n.crop=s);let u=(await d.send(n)).replace(/^data:image\/png;base64,/,"");s&&console.log(` area: x=${s.x} y=${s.y} w=${s.w} h=${s.h}`),(await import("fs")).writeFileSync(t,Buffer.from(u,"base64")),console.log(` saved: ${t}`);break}case"sample-color":{let o=await io(e,d);o||(console.error(T("sample-color","<x> <y> [w] [h] | --id <testID> | --text <text>")),console.error(" samples an averaged color from the canvas. coords are logical sootsim units."),process.exit(1));let t=await d.send({type:"evaluate",code:It(o)});if(e.includes("--json"))console.log(JSON.stringify(t,null,2));else{let{r:s,g:n,b:c,a:u,hex:p,samples:h}=t,f=o.w===1&&o.h===1?`@(${o.x},${o.y})`:`@(${o.x},${o.y}) ${o.w}x${o.h}`;console.log(` ${p} rgba(${s}, ${n}, ${c}, ${u}) ${f} ${h} samples`)}break}case"node":{let o=i[1];o||(console.error(T("node","<matcher>")),console.error(" resolves testID, id, then text \u2014 dumps full node info as JSON"),process.exit(1));let t=await d.send({type:"evaluate",code:`(async () => {
360
+ const t = window.__sootsimTest
361
+ const q = ${JSON.stringify(o)}
362
+ let node = null
363
+ let via = null
364
+ if (t.findByTestId) { node = await t.findByTestId(q); if (node) via = 'testID' }
365
+ if (!node && t.findById) { node = await t.findById(q); if (node) via = 'id' }
366
+ if (!node && t.findByText) { node = await t.findByText(q); if (node) via = 'text' }
367
+ if (!node) return { matcher: q, found: false }
368
+
369
+ // read the resolved transform (if any) off the style \u2014 useful
370
+ // because canvas nodes often animate via transform and describe
371
+ // output strips that.
372
+ const transform =
373
+ node.style && Array.isArray(node.style.transform)
374
+ ? node.style.transform
375
+ : node.style && node.style.transform
376
+ ? node.style.transform
377
+ : null
378
+
379
+ // parent chain \u2014 walk up from the node so the JSON dump is
380
+ // self-describing.
381
+ const parentChain = []
382
+ const root = window.__sootsimRoot
383
+ if (root && node.id != null) {
384
+ const findPath = (n, targetId, path) => {
385
+ if (!n) return null
386
+ if (n.id === targetId) return path
387
+ if (n.children) {
388
+ for (const child of n.children) {
389
+ const nextPath = [
390
+ ...path,
391
+ {
392
+ type: n.type || 'view',
393
+ testID: n.props?.testID || null,
394
+ text: n.text || null,
395
+ },
396
+ ]
397
+ const found = findPath(child, targetId, nextPath)
398
+ if (found) return found
399
+ }
400
+ }
401
+ return null
402
+ }
403
+ const chain = findPath(root, node.id, [])
404
+ if (chain) parentChain.push(...chain)
405
+ }
406
+
407
+ return {
408
+ matcher: q,
409
+ found: true,
410
+ resolvedVia: via,
411
+ node,
412
+ transform,
413
+ parentChain,
414
+ }
415
+ })()`});console.log(JSON.stringify(t,null,2));break}case"tap":{let o=Number(i[1]),t=Number(i[2]),s=we(e);if(s){let u=await be(d,{agent:pe(),textFallback:s.mode==="text"?s.value:void 0,resolve:async()=>{let f=await Fe(d,s);return f?{cx:f.x,cy:f.y,match:{id:s.mode==="testid"?s.value:f.id??null,testID:s.mode==="testid"?s.value:f.testID??null,text:s.mode==="text"?s.value:f.text??null,type:f.type??null},target:{id:f.id??null,testID:f.testID??null,text:f.text??null,type:f.type??null}}:null}}),p=u.payload;(!p||typeof p.cx!="number")&&(console.error(` not found: ${s.value}`),s.mode==="testid"&&X("wait-selector-for-missing-testid",s.value),process.exit(1)),me(u.result)||(F(`${s.mode} "${s.value}"`,u),process.exit(1));let h=lo(p.cx,p.cy,u.result);h&&await J("inspect tap",h.step,h.summary),console.log(JSON.stringify({...u.attempts>1?{attempts:u.attempts}:{},...u.result},null,2));break}(!Number.isFinite(o)||!Number.isFinite(t))&&(console.error(T("tap","<x> <y> | --testid <id> | --text <t>")),process.exit(1));let n=await Et(d,o,t),c=lo(o,t,n);c&&await J("inspect tap",c.step,c.summary),console.log(JSON.stringify(n,null,2));break}case"drag":case"swipe":{let o=Number(i[1]),t=Number(i[2]),s=Number(i[3]),n=Number(i[4]),c=g==="swipe"?10:12,u=g==="swipe"?8:16,p=i[5]?Number(i[5]):c,h=i[6]?Number(i[6]):u;(!Number.isFinite(o)||!Number.isFinite(t)||!Number.isFinite(s)||!Number.isFinite(n)||!Number.isFinite(p)||!Number.isFinite(h))&&(console.error(T(g,"<x1> <y1> <x2> <y2> [steps] [stepMs]")),process.exit(1));let f=await d.send({type:"evaluate",code:`(async () => {
416
+ const interact = window.__sootsimInteract
417
+ if (!interact?.drag) return { ok: false, reason: 'no interact.drag' }
418
+ const value = await interact.drag(${o}, ${t}, ${s}, ${n}, ${Math.max(1,Math.round(p))}, ${Math.max(0,Math.round(h))})
419
+ return { ok: !!value, value }
420
+ })()`});if(f?.ok){let x=Math.max(1,Math.round(Math.max(1,p)*Math.max(0,h)));await J(`inspect ${g}`,{swipe:{start:`${o}, ${t}`,end:`${s}, ${n}`,duration:x}},`${g} ${o},${t} -> ${s},${n}`)}console.log(JSON.stringify(f,null,2));break}case"pinch":{let o=Number(i[1]),t=Number(i[2]),s=Number(i[3]),n=Number(i[4]),c=Number(i[5]),u=Number(i[6]),p=Number(i[7]),h=Number(i[8]),f=i[9]?Number(i[9]):12,x=i[10]?Number(i[10]):16;(!Number.isFinite(o)||!Number.isFinite(t)||!Number.isFinite(s)||!Number.isFinite(n)||!Number.isFinite(c)||!Number.isFinite(u)||!Number.isFinite(p)||!Number.isFinite(h)||!Number.isFinite(f)||!Number.isFinite(x))&&(console.error(T("pinch","<x1> <y1> <x2> <y2> <x1'> <y1'> <x2'> <y2'> [steps] [stepMs]")),process.exit(1));let R=await d.send({type:"evaluate",code:`(async () => {
421
+ const interact = window.__sootsimInteract
422
+ if (!interact?.pinch) return { ok: false, reason: 'no interact.pinch' }
423
+ const value = await interact.pinch(${o}, ${t}, ${s}, ${n}, ${c}, ${u}, ${p}, ${h}, ${Math.max(1,Math.round(f))}, ${Math.max(0,Math.round(x))})
424
+ return { ok: !!value, value }
425
+ })()`});R?.ok&&await J("inspect pinch",{pinch:{from:[o,t,s,n],to:[c,u,p,h],steps:Math.max(1,Math.round(f)),stepMs:Math.max(0,Math.round(x))}},`pinch (${o},${t}) (${s},${n}) -> (${c},${u}) (${p},${h})`),console.log(JSON.stringify(R,null,2));break}case"tap-text":{let o=i[1];o||(console.error(T("tap-text","<text>")),process.exit(1));let t=z=>{let D=e.indexOf(z);return D>=0&&D+1<e.length?e[D+1]:null},s=z=>e.includes(z),n=t("--nth")??t("--index"),c=n!==null?Number(n):null;c!==null&&!Number.isFinite(c)&&(console.error(` --nth/--index requires an integer, got: ${n}`),process.exit(1));let u=t("--within"),p=t("--role"),h=s("--exact"),f=s("--first"),x=t("--min-y"),R=t("--max-y"),H=t("--min-x"),K=t("--max-x");for(let[z,D]of[["--min-y",x],["--max-y",R],["--min-x",H],["--max-x",K]])D!==null&&!Number.isFinite(Number(D))&&(console.error(` ${z} requires a number, got: ${D}`),process.exit(1));let U=e.indexOf("--near"),_=null;if(U>=0){let z=Number(e[U+1]),D=Number(e[U+2]);(!Number.isFinite(z)||!Number.isFinite(D))&&(console.error(" --near requires two numbers: --near <x> <y>"),process.exit(1)),_={x:z,y:D}}let w={exact:h,role:p,within:u,minX:H!==null?Number(H):null,maxX:K!==null?Number(K):null,minY:x!==null?Number(x):null,maxY:R!==null?Number(R):null,near:_,nth:c,first:f},S=await Rt(d,o,w,{agent:pe()}),k=S.payload;if(k?.error==="bridge-not-ready"&&(console.error(" sootsim test bridge not ready"),process.exit(1)),k?.ambiguous){let z=k.candidates;console.error(` ambiguous: ${k.total} matches for "${o}"`);for(let D of z){let Se=D.abs?`@(${Math.round(D.abs.x)},${Math.round(D.abs.y)})`:"",po=D.layout?` ${D.layout.width}x${D.layout.height}`:"",fo=D.testID?` #${D.testID}`:"",go=D.text?` "${D.text}"`:"",yo=D.ancestorTestIDs.length>0?` within ${D.ancestorTestIDs.slice(0,3).map(bo=>`#${bo}`).join(" > ")}`:"";console.error(` [${D.idx}] <${D.type}>${go}${fo} ${Se}${po}${yo}`)}k.total>z.length&&console.error(` ... and ${k.total-z.length} more`),console.error(" pick one:"),console.error(" --nth <index> pick the nth match (top-to-bottom, left-to-right; negatives from end)"),console.error(" --within <testID> narrow to descendants of a node"),console.error(" --min-y / --max-y geometric filter (pixels, absolute)"),console.error(" --min-x / --max-x geometric filter (pixels, absolute)"),console.error(" --near <x> <y> pick the closest match to a point"),console.error(" --exact exact text match (default is substring)"),console.error(" --role <role> narrow to accessibilityRole"),console.error(" --first keep the old pick-first-silently behavior"),process.exit(2)}k?.nthOutOfRange&&(console.error(` not found: nth ${k.nth} of ${k.total} match${k.total===1?"":"es"} for "${o}"`),process.exit(1)),(!k||typeof k.cx!="number")&&(console.error(` not found: ${o}`),process.exit(1)),me(S.result)||(F(`text "${o}"`,S),process.exit(1));let ne=ze(o,{id:k.target?.id??null,testID:k.target?.testID??null,type:k.target?.type??null,cx:k.cx,cy:k.cy},"text");await J("inspect tap-text",ne.step,ne.summary),console.log(JSON.stringify({matched:k.match,tapped:{nodeId:k.target?.nodeId??null,id:k.target?.id??null,testID:k.target?.testID??null,type:k.target?.type??null,cx:k.cx,cy:k.cy},...k.strategy&&k.strategy!=="matched-node"?{strategy:k.strategy}:{},...k.total>1||c!==null?{nth:{index:k.idx,total:k.total}}:{},...S.attempts>1?{attempts:S.attempts}:{},result:S.result},null,2));break}case"tap-best":{let o=i[1];o||(console.error(T("tap-best","<query>")),process.exit(1));let t=await Dt(d,o,{agent:pe()}),s=t.payload;s||(console.error(` tap-best: no testID or visible text matched "${o}". try \`sootsim find --interactive-targets\` to list candidates.`),process.exit(1)),"error"in s&&(console.error(` ${s.error}`),process.exit(1)),s.strategy==="none"&&(console.error(` tap-best: no testID or visible text matched "${o}". try \`sootsim find --interactive-targets\` to list candidates.`),process.exit(1));let n=s.node;me(t.result)||(F(`best "${o}"`,t),process.exit(1));let c=ze(o,{id:n.id,testID:n.testID,type:n.type,cx:s.cx,cy:s.cy},s.strategy==="testid"?"id":"text");await J("inspect tap-best",c.step,c.summary),console.log(JSON.stringify({matched:{strategy:s.strategy,nodeId:n.nodeId,id:n.id,testID:n.testID,type:n.type,text:n.text},tapped:{cx:s.cx,cy:s.cy},...t.attempts>1?{attempts:t.attempts}:{},result:t.result},null,2));break}case"tap-id":{let o=i[1];o||(console.error(T("tap-id","<id>")),process.exit(1));let t=await Pt(d,o,{agent:pe()}),s=t.payload;(!s||typeof s.cx!="number")&&(console.error(` not found: ${o}`),await Jo(d,o),process.exit(1)),me(t.result)||(F(`id "${o}"`,t),process.exit(1));let n=ze(o,{id:s.target?.id??null,testID:s.target?.testID??null,type:s.target?.type??null,cx:s.cx,cy:s.cy},"id");await J("inspect tap-id",n.step,n.summary),console.log(JSON.stringify({matched:s.match,tapped:{nodeId:s.target?.nodeId??null,id:s.target?.id??null,testID:s.target?.testID??null,type:s.target?.type??null,cx:s.cx,cy:s.cy},...s.strategy&&s.strategy!=="matched-node"?{strategy:s.strategy}:{},...t.attempts>1?{attempts:t.attempts}:{},result:t.result},null,2));break}case"type-into":{let o=i[1],t=i.slice(2).join(" ");(!o||!t)&&(console.error(T("type-into","<id> <text>")),process.exit(1));let s=JSON.stringify(o),n=await d.send({type:"evaluate",code:`(async () => {
426
+ const t = window.__sootsimTest
427
+ if (!t) return null
428
+ const n = await (t.findByTestId(${s}) || t.findById(${s}))
429
+ if (!n || !n.absolutePosition || !n.layout) return null
430
+ return {
431
+ cx: n.absolutePosition.x + (n.layout.width || 0) / 2,
432
+ cy: n.absolutePosition.y + (n.layout.height || 0) / 2,
433
+ id: n.id,
434
+ testID: n.testID,
435
+ type: n.type,
436
+ isTextInput: !!n.isTextInput,
437
+ secureTextEntry: !!n.secureTextEntry,
438
+ placeholder: n.placeholder || null,
439
+ }
440
+ })()`});(!n||typeof n.cx!="number")&&(console.error(` not found: ${o}`),process.exit(1)),n.isTextInput||console.error(` warning: ${o} is not a text input (isTextInput: false)`);let c=await d.send({type:"tap",x:n.cx,y:n.cy,target:{id:n.id??o,testID:n.testID??o,text:null,type:n.type??null}}),u=n.secureTextEntry===!0,p=await Xo(d,1e3,{targetId:o,secureTextEntry:u});p.visible||(console.error(` keyboard did not open after tapping ${o}`),process.exit(1));let h=p.focusedInput;h&&(h.testID===o||h.id===o||(console.error(` focus routing mismatch after tap: requested ${JSON.stringify(o)} but focus is on ${JSON.stringify(h.testID??h.id??null)}. did the tap land on an outer Pressable wrapper?`),process.exit(1))),await d.send({type:"keyboard",action:"type",text:t});let f=u||he(p),x=f?V:He(t,p),R=f&&p.focusedInput?{...p.focusedInput,secureTextEntry:!0,text:typeof p.focusedInput.text=="string"?V:p.focusedInput.text}:p.focusedInput??null;await J("inspect type-into",{tapOn:{id:o},inputText:x},x===V?`type-into #${o} ${V}`:`type-into #${o} ${JSON.stringify(t)}`),console.log(JSON.stringify({target:o,isTextInput:n.isTextInput,secureTextEntry:f,keyboardOpened:p.visible??c?.keyboardOpened??!1,focusedInput:R,typed:x},null,2));break}case"type":{let o=i.slice(1).join(" ");o||(console.error(T("type","<text>")),process.exit(1));let t=await Ae(d,"type");await d.send({type:"keyboard",action:"type",text:o});let s=He(o,t);await J("inspect type",{inputText:s},s===V?`type ${V}`:`type ${JSON.stringify(o)}`),console.log(s===V?` typed: ${V}`:` typed: ${JSON.stringify(o)}`);break}case"key":{let o=i[1];o||(console.error(T("key","<name>")),process.exit(1)),await Ae(d,"key"),await d.send({type:"keyboard",action:"press",text:o}),await J("inspect key",{pressKey:o},`key ${o}`),console.log(` pressed: ${o}`);break}case"key-sequence":{let o=i.slice(1);o.length===0&&(console.error(T("key-sequence","<key> [<key> ...]")),process.exit(1)),await Ae(d,"key-sequence");for(let t of o)await d.send({type:"keyboard",action:"press",text:t});await J("inspect key-sequence",{pressKey:o.join(" ")},`key-sequence ${o.join(" ")}`),console.log(` pressed: ${o.join(", ")}`);break}case"keycode":{let o=i.slice(1);o.length===0&&(console.error(T("keycode","<code> [<code> ...]")),process.exit(1));let t=o.map(n=>({code:n,key:Vo(n)})),s=t.filter(n=>!n.key);s.length>0&&(console.error(` unsupported keycode(s): ${s.map(n=>n.code).join(", ")}`),process.exit(1)),await Ae(d,"keycode");for(let n of t)await d.send({type:"keyboard",action:"press",text:n.key});await J("inspect keycode",{pressKey:t.map(n=>n.key).join(" ")},`keycode ${o.join(" ")}`),console.log(` pressed: ${o.join(", ")}`);break}case"dispatch":{let o=i[1];o||(console.error(T("dispatch","<char>")),process.exit(1)),await d.send({type:"keyboard",action:"dispatchKey",text:o}),await J("inspect dispatch",{dispatchKey:o},`dispatch ${JSON.stringify(o)}`),console.log(` dispatched: ${o}`);break}case"dismiss":{await d.send({type:"keyboard",action:"dismiss"}),await J("inspect dismiss",{hideKeyboard:!0},"dismiss keyboard"),console.log(" keyboard dismissed");break}case"double-tap":{let o=Number(i[1]),t=Number(i[2]),s=we(e);if(s){let p=await Fe(d,s);p||(console.error(` not found: ${s.value}`),s.mode==="testid"&&X("wait-selector-for-missing-testid",s.value),process.exit(1)),o=p.x,t=p.y}let n=i[3]?Number(i[3]):80;(!Number.isFinite(o)||!Number.isFinite(t)||!Number.isFinite(n))&&(console.error(T("double-tap","<x> <y> [gapMs] | --testid <id>")),process.exit(1));let c=Math.max(0,Math.round(n)),u=await d.send({type:"evaluate",code:`(async () => {
441
+ const interact = window.__sootsimInteract
442
+ if (interact?.doubleTap) {
443
+ return {
444
+ ok: !!(await interact.doubleTap(${o}, ${t}, ${c})),
445
+ gapMs: ${c},
446
+ }
447
+ }
448
+ if (!interact?.tap) {
449
+ return { ok: false, reason: 'no interact.tap', gapMs: ${c} }
450
+ }
451
+ const first = await interact.tap(${o}, ${t})
452
+ if (!first || first.hit === false) {
453
+ return { ok: false, reason: 'first tap missed', gapMs: ${c}, first }
454
+ }
455
+ await new Promise((resolve) => setTimeout(resolve, ${c}))
456
+ const second = await interact.tap(${o}, ${t})
457
+ return {
458
+ ok: !!second && second.hit !== false,
459
+ gapMs: ${c},
460
+ first,
461
+ second,
462
+ }
463
+ })()`});u?.ok&&await J("inspect double-tap",{doubleTapAtCoords:{x:o,y:t,gapMs:c}},`double-tap @${o},${t}`),console.log(JSON.stringify(u,null,2));break}case"long-press":{let o=Number(i[1]),t=Number(i[2]),s=we(e),n=null;if(s){let f=await Fe(d,s);f||(console.error(` not found: ${s.value}`),s.mode==="testid"&&X("wait-selector-for-missing-testid",s.value),process.exit(1)),o=f.x,t=f.y,n={id:f.id??null,testID:f.testID??null,text:f.text??null,type:f.type??null}}let c=s?i[1]:i[3],u=c?Number(c):600;(!Number.isFinite(o)||!Number.isFinite(t)||!Number.isFinite(u))&&(console.error(T("long-press","<x> <y> [durationMs] | --testid <id>")),process.exit(1));let p=Math.max(0,Math.round(u)),h=await d.send({type:"longPress",x:o,y:t,durationMs:p,target:n});h?.ok&&await J("inspect long-press",{tapAtCoords:{x:o,y:t}},`long-press @${o},${t}`),console.log(JSON.stringify(h,null,2));break}case"touch":{let o=i[1],t=Number(i[2]),s=Number(i[3]),n=i[4]?Number(i[4]):999,c=o==="down"?"touchDown":o==="move"?"touchMove":o==="up"?"touchUp":o==="cancel"?"touchCancel":null;c||(console.error(T("touch","<down|move|up|cancel> <x> <y> [pointerId]")),process.exit(1)),o!=="cancel"&&(!Number.isFinite(t)||!Number.isFinite(s))&&(console.error(T("touch","<down|move|up|cancel> <x> <y> [pointerId]")),process.exit(1));let u=o==="down"?"tap":o==="move"?"move":null,p=u&&Number.isFinite(t)&&Number.isFinite(s)?`window.dispatchEvent(new CustomEvent('sootsim:agentAction', { detail: { type: '${u}', x: ${t}, y: ${s} } }));`:"",h=await d.send({type:"evaluate",code:`(async () => {
464
+ ${p}
465
+ const interact = window.__sootsimInteract
466
+ if (!interact?.${c}) return { ok: false, reason: 'no interact.${c}' }
467
+ const value = ${o==="cancel"?`await interact.${c}(${Math.max(1,Math.round(n))})`:`await interact.${c}(${t}, ${s}, ${Math.max(1,Math.round(n))})`}
468
+ return { ok: !!value, value }
469
+ })()`});h?.ok&&o!=="cancel"&&await J("inspect touch",{tapAtCoords:{x:t,y:s}},`touch ${o} @${t},${s}`),console.log(JSON.stringify(h,null,2));break}case"gesture":{let o=["scroll-up","scroll-down","scroll-left","scroll-right","swipe-from-left-edge","swipe-from-right-edge","swipe-from-top-edge","swipe-from-bottom-edge"],t=i[1],s=i[2]?Number(i[2]):220;(!t||!Number.isFinite(s))&&(console.error(T("gesture","<preset> [durationMs]")),console.error(` presets: ${o.join(", ")}`),process.exit(1)),o.includes(t)||(console.error(` unknown gesture preset: ${t}`),console.error(` presets: ${o.join(", ")}`),process.exit(1));let n=await d.send({type:"evaluate",code:`(async () => {
470
+ const spec = globalThis.__sootsimDeviceSpec || {}
471
+ return {
472
+ width: spec.width || window.innerWidth || 393,
473
+ height: spec.height || window.innerHeight || 852,
474
+ statusBarHeight: spec.statusBarHeight || 0,
475
+ homeIndicatorHeight: spec.homeIndicatorHeight || 0,
476
+ }
477
+ })()`}),c=Number(n?.width)||393,u=Number(n?.height)||852,p=Number(n?.statusBarHeight)||0,h=Number(n?.homeIndicatorHeight)||0,f=Math.round(c/2),x=Math.round(u/2),R=Math.max(24,p+18),H=Math.max(24,h+18),K=18,U=Math.min(220,Math.round(u*.24)),_=Math.min(180,Math.round(c*.32)),w=f,S=x,k=f,ne=x;switch(t){case"scroll-up":S=x+Math.round(U/2),ne=x-Math.round(U/2);break;case"scroll-down":S=x-Math.round(U/2),ne=x+Math.round(U/2);break;case"scroll-left":w=f+Math.round(_/2),k=f-Math.round(_/2);break;case"scroll-right":w=f-Math.round(_/2),k=f+Math.round(_/2);break;case"swipe-from-left-edge":w=K,S=x,k=Math.min(c-K,K+_);break;case"swipe-from-right-edge":w=c-K,S=x,k=Math.max(K,c-K-_);break;case"swipe-from-top-edge":w=f,S=R,ne=Math.min(u-H,R+U);break;case"swipe-from-bottom-edge":w=f,S=u-H,ne=Math.max(R,u-H-U);break}let z=Math.max(8,Math.round(s/16)),D=Math.max(1,Math.round(s/z)),Se=await d.send({type:"evaluate",code:`(async () => {
478
+ const interact = window.__sootsimInteract
479
+ if (!interact?.drag) return { ok: false, reason: 'no interact.drag' }
480
+ const value = await interact.drag(${w}, ${S}, ${k}, ${ne}, ${z}, ${D})
481
+ return { ok: !!value, value }
482
+ })()`});Se?.ok&&await J("inspect gesture",{swipe:{start:`${w}, ${S}`,end:`${k}, ${ne}`,duration:Math.max(1,Math.round(s))}},`gesture ${t}`),console.log(JSON.stringify({preset:t,from:{x:w,y:S},to:{x:k,y:ne},result:Se},null,2));break}case"scroll":{let o=we(e),t=Zo(e),s=o?.mode==="testid"?o.value:t==null?i[1]:null,n=o||t!=null?1:2,c=Number(i[n]),u=Number(i[n+1]);(!s&&t==null||!Number.isFinite(c)||!Number.isFinite(u))&&(console.error(T("scroll","<id> <x> <y> | --testid <id> <x> <y> | --node-id <nodeId> <x> <y>")),process.exit(1));let p=await d.send({type:"evaluate",code:`(async () => {
483
+ const t = window.__sootsimTest
484
+ if (!t) return null
485
+ const n = ${t!=null?`await t.inspectByNodeId(${JSON.stringify(t)})`:`await t.findByTestId(${JSON.stringify(s)})
486
+ || await t.findById(${JSON.stringify(s)})`}
487
+ if (!n || !n.absolutePosition || !n.layout) return null
488
+ return {
489
+ cx: n.absolutePosition.x + (n.layout.width || 0) / 2,
490
+ cy: n.absolutePosition.y + (n.layout.height || 0) / 2,
491
+ }
492
+ })()`}),h=await Y(d,"scrollTo",t!=null?{nodeId:t}:s,c,u,!1);if(h?.ok){let f=t!=null?`node ${t}`:`#${s}`;await J("inspect scroll",{scrollTo:{...t!=null?{nodeId:t}:{id:s},x:c,y:u}},`scroll ${f} -> ${c},${u}`)}console.log(JSON.stringify({...h,...p?{at:{x:p.cx,y:p.cy}}:{}},null,2));break}case"state":{let o=i[1];if(r==="get"&&!o){let s=await Y(d,"getRuntimeState"),n=await d.send({type:"evaluate",code:ke});if(s&&typeof s=="object"&&s.diagnostics&&(s.diagnostics.errors=n?.errors??0,s.diagnostics.warnings=n?.warnings??0),s&&typeof s=="object"&&s.shell==null)try{let c=await de(d);c&&(s.shell=c)}catch{}console.log(JSON.stringify(s,null,2));break}if(!o||o==="--help"||o==="-h"){console.log(`
493
+ ${b("state")} \u2014 dump raw runtime state
494
+
495
+ subcommands:
496
+ shell dump shell transition/layout state
497
+ worker dump render-worker host/animation state
498
+ keyboard dump keyboard visibility, mode, and focused input
499
+ ownership dump surface ownership + pointerOnSurface delivery stats
500
+ node <id> dump raw node info by id or testID
501
+ scroll <id> dump scroll metrics and runtime state
502
+ scroll-hit <x> <y> dump the nearest scroll ancestor at coordinates
503
+ hit <x> <y> dump the hit-test ancestry at coordinates
504
+ gesture <x> <y> dump gesture routing/debug info at coordinates
505
+ gesture-seam dump shell-hosted gesture recognizer state/events
506
+
507
+ examples:
508
+ ${b("state")} shell
509
+ ${b("state")} worker
510
+ ${b("state")} keyboard
511
+ ${b("state")} ownership
512
+ ${b("state")} node photos
513
+ ${b("state")} scroll feed
514
+ ${b("state")} scroll-hit 360 420
515
+ ${b("state")} hit 200 720
516
+ `);break}let t;switch(o){case"shell":t=await de(d,500);break;case"worker":t=await Te(d,"__sootsimRenderHost.queryStats");break;case"ownership":t=await d.send({type:"evaluate",code:`(() => {
517
+ const h = window.__sootsimRenderHost
518
+ if (!h || typeof h.getOwnershipSnapshot !== 'function') {
519
+ return { error: 'getOwnershipSnapshot not available' }
520
+ }
521
+ return h.getOwnershipSnapshot()
522
+ })()`});break;case"keyboard":t=await d.send({type:"evaluate",code:`(async () => {
523
+ const kb = window.__sootsimKeyboard
524
+ const test = window.__sootsimTest
525
+ if (!kb) return { error: 'keyboard bridge not available' }
526
+ const layout = typeof kb.getLayout === 'function' ? kb.getLayout() : null
527
+ const secureTextEntry =
528
+ !!layout?.spec?.secureTextEntry && layout?.spec?.keyboardType !== 'visible-password'
529
+ const visible = kb.isVisible()
530
+ const mode = kb.getMode()
531
+ let focused = null
532
+ if (test && typeof test.getFocusedNode === 'function') {
533
+ try {
534
+ focused = await test.getFocusedNode()
535
+ } catch {}
536
+ }
537
+ return {
538
+ visible,
539
+ mode,
540
+ layout,
541
+ focusedInput: focused ? {
542
+ nodeId: focused.nodeId ?? null,
543
+ testID: focused.testID || null,
544
+ id: focused.id || null,
545
+ placeholder: focused.placeholder || null,
546
+ secureTextEntry,
547
+ text: secureTextEntry ? ${JSON.stringify(V)} : (focused.text || null),
548
+ } : null,
549
+ }
550
+ })()`}),t=Ke(t);break;case"node":{let s=i[2];s||(console.error(` usage: ${b("state")} node <id>`),process.exit(1)),t=await Y(d,"findByTestId",s)||await Y(d,"findById",s);break}case"scroll":{let s=i[2];s||(console.error(` usage: ${b("state")} scroll <id>`),process.exit(1)),t=await Y(d,"getScrollState",s);break}case"scroll-hit":{let s=Number(i[2]),n=Number(i[3]);(!Number.isFinite(s)||!Number.isFinite(n))&&(console.error(` usage: ${b("state")} scroll-hit <x> <y>`),process.exit(1)),t=await Y(d,"getScrollStateAt",s,n);break}case"hit":{let s=Number(i[2]),n=Number(i[3]);(!Number.isFinite(s)||!Number.isFinite(n))&&(console.error(` usage: ${b("state")} hit <x> <y>`),process.exit(1)),t=await Y(d,"debugHitAt",s,n);break}case"gesture":{let s=Number(i[2]),n=Number(i[3]);(!Number.isFinite(s)||!Number.isFinite(n))&&(console.error(` usage: ${b("state")} gesture <x> <y>`),process.exit(1)),t=await Y(d,"debugGestureAt",s,n);break}case"gesture-seam":t=await Te(d,"SootSim.bridges.mainShell.callTestBridge","getShellGestureSeamDebug");break;default:console.error(` unknown state subcommand: ${o}`),process.exit(1)}console.log(JSON.stringify(t,null,2));break}case"shell":{let o=i[1];if(!o||o==="--help"||o==="-h"){console.log(`
551
+ ${b("shell")} \u2014 run built-in shell commands
552
+
553
+ subcommands:
554
+ launch <appId> [waitMs] [--clear-state]
555
+ launch app and wait for settled shell state
556
+ home [waitMs] go home and wait for settled shell state
557
+ switcher [waitMs] open switcher and wait for settled shell state
558
+ open-card <appId> [waitMs]
559
+ open a specific switcher card and wait for app settle
560
+ appearance <light|dark|auto|toggle>
561
+ update simulator appearance
562
+ lock toggle device lock state
563
+ shake trigger the simulator shake gesture
564
+
565
+ examples:
566
+ ${b("shell")} launch photos
567
+ ${b("shell")} launch rn --clear-state
568
+ ${b("shell")} launch photos 1500
569
+ ${b("shell")} home 500
570
+ ${b("shell")} switcher 800
571
+ ${b("shell")} open-card clock 800
572
+ ${b("shell")} appearance dark
573
+ ${b("shell")} lock
574
+ `);break}let t=o==="launch"||o==="open-card"||o==="home"||o==="switcher",s=o==="launch"||o==="open-card"?i[3]:i[2],n=s?Number(s):350;t&&(!Number.isFinite(n)||n<0)&&(console.error(T("shell",o==="launch"||o==="open-card"?"<launch|open-card> <appId> [settleMs]":"<home|switcher> [settleMs]")),process.exit(1));let c=!1,u=!1,p=null,h=e.includes("--clear-state");if(o==="launch"){let f=i[2];f||(console.error(T("shell","launch <appId> [settleMs] [--clear-state]")),process.exit(1)),h&&await d.send({type:"evaluate",code:Re(!0)}),c=!!await ge(d,"launchApp",n,f),{settled:u,state:p}=await Oe(d,Math.round(n),x=>!!x&&x.state==="app"&&x.activeApp===f&&x.showSwitcher===!1&&x.switcherPhase==="idle"&&typeof x.launchProgress=="number"&&x.launchProgress>=.98),c&&await J("inspect shell launch",h?{launchApp:{clearState:!0}}:{launchApp:{}},h?"launch app (clear state)":"launch app")}else if(o==="home")c=!!await ge(d,"goHome",n),{settled:u,state:p}=await Oe(d,Math.round(n),f=>!!f&&f.state==="home"&&f.activeApp==null&&f.showSwitcher===!1&&f.switcherPhase==="idle"&&typeof f.launchProgress=="number"&&f.launchProgress>=.98);else if(o==="switcher")c=!!await ge(d,"openSwitcher",n),{settled:u,state:p}=await Oe(d,Math.round(n),f=>!!f&&f.state==="app"&&f.showSwitcher===!0&&f.switcherPhase==="idle"&&typeof f.zoomLevel=="number"&&Math.abs(f.zoomLevel)<=.02&&typeof f.horizontalZoom=="number"&&Math.abs(f.horizontalZoom)<=.02),u&&(await te(Go),p=await de(d));else if(o==="open-card"){let f=i[2];f||(console.error(T("shell","open-card <appId> [settleMs]")),process.exit(1)),c=!!await ge(d,"openSwitcherCard",n,f),{settled:u,state:p}=await Oe(d,Math.round(n),x=>!!x&&x.state==="app"&&x.activeApp===f&&x.showSwitcher===!1&&x.switcherPhase==="idle"&&typeof x.zoomLevel=="number"&&x.zoomLevel>=.98&&typeof x.horizontalZoom=="number"&&x.horizontalZoom>=.98),c&&await J("inspect shell open-card",{openSwitcherCard:{appId:f}},`open switcher card ${f}`)}else if(o==="appearance"){let f=i[2];(!f||!["light","dark","auto","toggle"].includes(f))&&(console.error(T("shell","appearance <light|dark|auto|toggle>")),process.exit(1));let x=await ao(d,"appearance",f);if(c=!!x?.ok,p={appearance:x},c){let R=x?.applied??f;console.log(` appearance: ${R}`)}}else if(o==="lock"||o==="shake"){let f=await ao(d,o);c=!!f?.ok,p={[o]:f}}else console.error(` unknown shell subcommand: ${o}`),process.exit(1);console.log(JSON.stringify({ok:c,settled:u,state:p},null,2));break}case"url":{await Gt(d,{args:l});break}case"reload":{let s=!1,n=!1;try{await d.send({type:"evaluate",code:"window.__sootsimConsole?.clear()"});let p=await d.send({type:"evaluate",code:`;(() => {
575
+ const reloadExternalApp = window.SootSim?.bridges?.hotRemount?.reloadExternalApp
576
+ if (typeof reloadExternalApp === 'function') {
577
+ reloadExternalApp()
578
+ return { kind: 'external-app' }
579
+ }
580
+ window.location.reload()
581
+ return { kind: 'page' }
582
+ })()`});n=!!p&&p.kind==="external-app",s=!0}catch{}console.log(" reloading...");let c=d,u=null;if(n)u=await Me(d,{timeoutMs:1e4,errorGraceMs:3e3});else{s&&await te(300);let p=await kt(O,L,N,{timeoutMs:1e4,simIdSource:P});p?(c=p,u=await Me(p,{timeoutMs:1e4,errorGraceMs:3e3})):(console.log(" \u26A0 reload: bridge never reconnected within 10000ms"),c=null)}if(u)if(u.ready){let p=u.source==="nodes-fallback"?" (no ready signal, node-count fallback)":"";console.log(` ready in ${u.elapsedMs}ms: ${u.nodes} nodes${p}`)}else if(u.source==="error-bail")console.log(` \u26A0 reload bailed after ${u.elapsedMs}ms: ${u.errors} console error(s), ready signal never fired`);else{let p=oo(u);console.log(` \u26A0 reload timed out after ${u.elapsedMs}ms \u2014 ${p} (nodes: ${u.nodes}, targets: ${u.targets}, errors: ${u.errors})`)}if(c)try{let p=await fe(c,10);if(c!==d&&c.close(),Array.isArray(p)&&p.length>0){console.log(`
583
+ \u26A0 ${p.length} error(s) during mount:
584
+ `);for(let h of p){let f=h.args.map(x=>typeof x=="object"?JSON.stringify(x):x).join(" ");if(console.log(` ${f}`),h.stack){let x=h.stack.split(`
585
+ `).slice(0,2);for(let R of x)console.log(` ${R.trim()}`)}}}}catch{}u&&!u.ready&&(process.exitCode=1);break}case"storage-clear":{if(await je(d),await d.send({type:"evaluate",code:Re(!0)})!==!0){A(l)?E({cleared:!1,ready:!1,error:"external app reload bridge is unavailable"}):console.error(" storage clear failed: external app reload bridge is unavailable"),process.exitCode=1;break}let n=await Me(d,{timeoutMs:1e4,errorGraceMs:3e3});if(A(l)){E({cleared:!0,ready:n.ready,reload:n}),n.ready||(process.exitCode=1);break}if(n.ready){let c=n.source==="nodes-fallback"?" (no ready signal, node-count fallback)":"";console.log(` cleared tenant storage; ready in ${n.elapsedMs}ms: ${n.nodes} nodes${c}`)}else if(n.source==="error-bail")console.log(` \u26A0 storage clear reloaded but bailed after ${n.elapsedMs}ms: ${n.errors} console error(s), ready signal never fired`);else{let c=oo(n);console.log(` \u26A0 storage clear reloaded but timed out after ${n.elapsedMs}ms \u2014 ${c} (nodes: ${n.nodes}, targets: ${n.targets}, errors: ${n.errors})`)}try{let c=await fe(d,10);if(Array.isArray(c)&&c.length>0){console.log(`
586
+ \u26A0 ${c.length} error(s) during mount:
587
+ `);for(let u of c){let p=u.args.map(h=>typeof h=="object"?JSON.stringify(h):h).join(" ");if(console.log(` ${p}`),u.stack){let h=u.stack.split(`
588
+ `).slice(0,2);for(let f of h)console.log(` ${f.trim()}`)}}}}catch{}n.ready||(process.exitCode=1);break}case"eval":case"js":{let o=i.slice(1).join(" ");o||(console.error(T("js","<javascript>")),console.error(""),console.error(" runs the snippet in the engine realm. SootSim is the"),console.error(" canonical state surface \u2014 reach into it directly."),console.error(""),console.error(" examples:"),console.error(` ${b("js")} SootSim.bridges.test.findByText("Sign in")`),console.error(` ${b("js")} SootSim.bridges.debug.snapshot("before")`),console.error(` ${b("js")} SootSim.bridges.keyboard.type("hello")`),console.error(` ${b("js")} SootSim.state.root.children.length`),process.exit(1));let t=o;t.startsWith("(async")||(t=`(async () => ${t})()`);let s=await d.send({type:"evaluate",code:t});console.log(JSON.stringify(s,null,2));let n=o.toLowerCase(),c=[];(n.includes("sootsim:gohome")||n.includes("gohome"))&&c.push("sootsim shell home"),(n.includes("sootsim:appswitcher")||n.includes("appswitcher"))&&c.push("sootsim shell switcher"),(n.includes("keyboard.isvisible")||n.includes("keyboard.getmode"))&&c.push("sootsim debug state keyboard"),n.includes("interact.tap")&&c.push("sootsim do tap <x> <y>"),n.includes("keyboard.type")&&c.push("sootsim do type <text>"),(n.includes("keyboard.press")||n.includes("keyboard.dispatchkey"))&&c.push("sootsim do key <name>"),n.includes("keyboard.dismiss")&&c.push("sootsim do dismiss"),n.includes("dumptree")&&c.push("sootsim get tree"),n.includes("dumpaccessibilitytree")&&c.push("sootsim get a11y"),n.includes("getnodecount")&&c.push("sootsim get count"),n.includes("findbytext")&&c.push("sootsim find <text>"),(n.includes("findbytestid")||n.includes("findbyid"))&&c.push("sootsim find --testid <id>"),n.includes("document.hidden")&&c.push("sootsim debug state keyboard (includes tab health)"),c.length>0&&X("prefer-cli-over-eval",c);break}case"globals":{let o=await d.send({type:"evaluate",code:`(async () => {
589
+ const globals = {}
590
+
591
+ // test bridge (proxy in worker mode)
592
+ const testMethods = [
593
+ 'findById', 'findByTestId', 'findByText', 'findByLabel', 'findByRole',
594
+ 'findAllByRole', 'findByA11yState', 'findAllByA11yState', 'findByHint',
595
+ 'findPressable', 'getStyle', 'getLayout', 'getAbsolutePosition', 'isVisible',
596
+ 'queryAll', 'dumpTree', 'dumpAccessibilityTree', 'getNodeCount', 'getShellState',
597
+ 'getScrollState', 'getScrollStateAt', 'scrollTo', 'waitForTree',
598
+ 'waitForScreenTransitions', 'debugByText', 'debugByTestId', 'debugHitAt',
599
+ 'debugGestureAt'
600
+ ]
601
+ globals['test (\u2192 __sootsimTest)'] = testMethods
602
+
603
+ // debug
604
+ if (window.__sootsimDebug) {
605
+ globals['debug (\u2192 __sootsimDebug)'] = Object.keys(window.__sootsimDebug)
606
+ }
607
+
608
+ // interact
609
+ if (window.__sootsimInteract) {
610
+ globals['interact (\u2192 __sootsimInteract)'] = Object.keys(window.__sootsimInteract)
611
+ }
612
+
613
+ // keyboard
614
+ if (window.__sootsimKeyboard) {
615
+ globals['keyboard (\u2192 __sootsimKeyboard)'] = Object.keys(window.__sootsimKeyboard)
616
+ }
617
+
618
+ // other globals
619
+ globals['other'] = [
620
+ 'root (\u2192 __sootsimRoot) - live node tree',
621
+ 'render() (\u2192 __sootsimForceRender) - force re-render'
622
+ ]
623
+
624
+ return globals
625
+ })()`});console.log(` sootsim JS API:
626
+ `);for(let[t,s]of Object.entries(o)){console.log(` ${t}:`);for(let n of s)console.log(` .${n}`);console.log("")}console.log(` use: ${b("js")} <expression>`),console.log(` example: ${b("js")} test.findByText("Sign in")`);break}case"describe":{await Bt({bridge:d,args:e,positional:i});break}case"perf":{let o=i[1];if(!o||o==="--help"||o==="-h"){console.log(`
627
+ ${b("perf")} \u2014 performance profiling
628
+
629
+ subcommands:
630
+ stats one-shot stats (zero overhead query)
631
+ start begin recording frame times (also clears prior frames)
632
+ stop stop recording and report results
633
+ frames [n] get last N frame times (default: 50)
634
+ worst [n] get the N slowest frames (default: 20)
635
+ transition <e> profile a shell transition (goHome, appSwitcher, lockScreen)
636
+
637
+ the read subcommands (stats, stop, frames, worst, transition) accept
638
+ --json for a machine-readable payload on stdout.
639
+
640
+ examples:
641
+ ${b("perf")} stats
642
+ ${b("perf")} start
643
+ # ... interact with the app ...
644
+ ${b("perf")} stop
645
+ ${b("perf")} stop --json
646
+ ${b("perf")} transition goHome
647
+ `);break}switch(o){case"stats":{let t=await d.send({type:"evaluate",code:`(async () => {
648
+ // worker mode (host exposes these)
649
+ if (window.__sootsimPerfStats) {
650
+ return await window.__sootsimPerfStats()
651
+ }
652
+ // main-thread mode
653
+ const perf = window.__sootsimPerf
654
+ const a11y = window.__sootsimA11y
655
+ if (!perf && !a11y) return { error: 'no perf globals available' }
656
+
657
+ const frameStats = perf?.getFrameStats?.() || {}
658
+ const profile = a11y?.profile?.() || {}
659
+ const nodeCount = await window.__sootsimTest?.getNodeCount?.() || 0
660
+
661
+ return {
662
+ frames: frameStats.frames || profile.syncCount || 0,
663
+ avgMs: frameStats.totalMs && frameStats.frames
664
+ ? (frameStats.totalMs / frameStats.frames).toFixed(2)
665
+ : profile.avgSyncMs?.toFixed(2) || '?',
666
+ maxMs: frameStats.maxMs?.toFixed(2) || profile.maxSyncMs?.toFixed(2) || '?',
667
+ layoutMs: frameStats.layoutTotalMs?.toFixed(2) || '?',
668
+ nodeCount,
669
+ jankFrames: frameStats.recentFrames?.filter(f => f > 16.67).length || 0,
670
+ recentCount: frameStats.recentFrames?.length || 0,
671
+ }
672
+ })()`});if(t.error&&(console.error(` error: ${t.error}`),process.exit(1)),A(l)){E(t);break}let s=t.avgMs==="?"&&t.maxMs==="?",n=t.avgMs!=="?"?(1e3/parseFloat(t.avgMs)).toFixed(1):"?";console.log(" perf stats:"),console.log(` frames: ${t.frames}`),console.log(` avg: ${t.avgMs}ms (${n} fps)`),console.log(` max: ${t.maxMs}ms`),console.log(` layout: ${t.layoutMs}ms total`),console.log(` nodes: ${t.nodeCount}`),t.recentCount>0&&console.log(` jank: ${t.jankFrames}/${t.recentCount} frames >16.67ms`),s&&process.stderr.write(`
673
+ \u26A0 frame timings are zero \u2014 enable them first:
674
+ sootsim debug perf start # begin recording
675
+ # \u2026 interact / run a flow / wait for the transition \u2026
676
+ sootsim debug perf stop # full report
677
+ sootsim debug perf stats # one-shot snapshot
678
+ `);break}case"start":{await d.send({type:"evaluate",code:`(async () => {
679
+ // worker mode
680
+ if (window.__sootsimPerfStart && window.__sootsimRenderHost) {
681
+ const result = window.__sootsimPerfStart()
682
+ window.${re} = {
683
+ active: true,
684
+ mode: 'render-worker',
685
+ lastSamples: [],
686
+ startedAt: performance.now(),
687
+ }
688
+ return result
689
+ }
690
+ // main-thread mode
691
+ window.__sootsimPerf?.enableFrameStats?.(true)
692
+ window.__sootsimA11y?.resetProfile?.()
693
+ window.${re} = {
694
+ active: true,
695
+ mode: 'main-thread',
696
+ lastSamples: [],
697
+ startedAt: performance.now(),
698
+ }
699
+ return { started: true }
700
+ })()`}),console.log(` profiling started \u2014 interact with the app, then run '${b("perf")} stop'`);break}case"stop":{let t=await d.send({type:"evaluate",code:`(async () => {
701
+ // worker mode
702
+ if (window.__sootsimRenderHost) {
703
+ const session = window.${re} || {}
704
+ const priorSamples = session.active && Array.isArray(session.lastSamples)
705
+ ? session.lastSamples
706
+ : []
707
+ const flushedSamples = await window.__sootsimRenderHost.flushSamples()
708
+ const samples = priorSamples.concat(flushedSamples)
709
+ window.${re} = {
710
+ ...session,
711
+ active: false,
712
+ mode: 'render-worker',
713
+ lastSamples: samples,
714
+ stoppedAt: performance.now(),
715
+ }
716
+
717
+ const frameTimes = samples.map(sample => sample[1])
718
+ const layoutTimes = samples.map(sample => sample[2])
719
+ const renderTimes = samples.map(sample => sample[3])
720
+ const copyTimes = samples.map(sample => sample[4])
721
+ const auxTimes = samples.map(sample => sample[5] || 0)
722
+ const otherTimes = samples.map(sample => sample[6] || 0)
723
+ const sorted = [...frameTimes].sort((a, b) => a - b)
724
+ const total = frameTimes.reduce((a, b) => a + b, 0)
725
+ const avg = frameTimes.length > 0 ? total / frameTimes.length : 0
726
+ const max = Math.max(...frameTimes, 0)
727
+ const layoutTotal = layoutTimes.reduce((a, b) => a + b, 0)
728
+ const renderTotal = renderTimes.reduce((a, b) => a + b, 0)
729
+ const copyTotal = copyTimes.reduce((a, b) => a + b, 0)
730
+ const auxTotal = auxTimes.reduce((a, b) => a + b, 0)
731
+ const otherTotal = otherTimes.reduce((a, b) => a + b, 0)
732
+
733
+ return {
734
+ mode: 'render-worker',
735
+ frames: frameTimes.length,
736
+ totalMs: total,
737
+ avgMs: avg,
738
+ maxMs: max,
739
+ layoutTotalMs: layoutTotal,
740
+ renderTotalMs: renderTotal,
741
+ copyTotalMs: copyTotal,
742
+ auxTotalMs: auxTotal,
743
+ otherTotalMs: otherTotal,
744
+ layoutAvgMs: frameTimes.length > 0 ? layoutTotal / frameTimes.length : 0,
745
+ renderAvgMs: frameTimes.length > 0 ? renderTotal / frameTimes.length : 0,
746
+ copyAvgMs: frameTimes.length > 0 ? copyTotal / frameTimes.length : 0,
747
+ auxAvgMs: frameTimes.length > 0 ? auxTotal / frameTimes.length : 0,
748
+ otherAvgMs: frameTimes.length > 0 ? otherTotal / frameTimes.length : 0,
749
+ p50: sorted[Math.floor(sorted.length * 0.5)] || 0,
750
+ p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
751
+ p99: sorted[Math.floor(sorted.length * 0.99)] || 0,
752
+ jankFrames: frameTimes.filter((f) => f > 16.67).length,
753
+ sampleCount: frameTimes.length,
754
+ }
755
+ }
756
+ // main-thread mode
757
+ const perf = window.__sootsimPerf
758
+ const a11y = window.__sootsimA11y
759
+ if (!perf && !a11y) return { error: 'no perf globals' }
760
+
761
+ const frameStats = perf?.getFrameStats?.() || {}
762
+ const profile = a11y?.profile?.() || {}
763
+
764
+ // calculate distribution
765
+ const recent = frameStats.recentFrames || []
766
+ const sorted = [...recent].sort((a, b) => a - b)
767
+ const p50 = sorted[Math.floor(sorted.length * 0.5)] || 0
768
+ const p95 = sorted[Math.floor(sorted.length * 0.95)] || 0
769
+ const p99 = sorted[Math.floor(sorted.length * 0.99)] || 0
770
+
771
+ // disable collection
772
+ perf?.disableFrameStats?.()
773
+ window.${re} = {
774
+ ...(window.${re} || {}),
775
+ active: false,
776
+ mode: 'main-thread',
777
+ lastSamples: recent.map((ms, index) => [index, ms, 0, 0, 0, 0, 0]),
778
+ stoppedAt: performance.now(),
779
+ }
780
+
781
+ return {
782
+ mode: 'main-thread',
783
+ frames: frameStats.frames || profile.syncCount || 0,
784
+ totalMs: frameStats.totalMs || 0,
785
+ avgMs: frameStats.totalMs && frameStats.frames
786
+ ? frameStats.totalMs / frameStats.frames
787
+ : profile.avgSyncMs || 0,
788
+ maxMs: frameStats.maxMs || profile.maxSyncMs || 0,
789
+ layoutTotalMs: frameStats.layoutTotalMs || 0,
790
+ p50, p95, p99,
791
+ jankFrames: recent.filter(f => f > 16.67).length,
792
+ sampleCount: recent.length,
793
+ }
794
+ })()`});if(t.error&&(console.error(` error: ${t.error}`),process.exit(1)),A(l)){E(t);break}let s=t.avgMs>0?(1e3/t.avgMs).toFixed(1):"?",n=t.sampleCount>0?(t.jankFrames/t.sampleCount*100).toFixed(1):"0";console.log(` profiling stopped:
795
+ `),console.log(` frames: ${t.frames}`),console.log(` total: ${t.totalMs.toFixed(1)}ms`),console.log(` avg: ${t.avgMs.toFixed(2)}ms (${s} fps)`),console.log(` max: ${t.maxMs.toFixed(2)}ms`),console.log(""),t.layoutAvgMs!==void 0&&(console.log(" breakdown (avg per frame):"),console.log(` layout: ${t.layoutAvgMs.toFixed(2)}ms`),console.log(` render: ${t.renderAvgMs.toFixed(2)}ms`),console.log(` copy: ${t.copyAvgMs.toFixed(2)}ms`),t.auxAvgMs!==void 0&&console.log(` aux: ${t.auxAvgMs.toFixed(2)}ms`),t.otherAvgMs!==void 0&&console.log(` other: ${t.otherAvgMs.toFixed(2)}ms`),console.log("")),console.log(` distribution (${t.sampleCount} samples):`),console.log(` p50: ${t.p50.toFixed(2)}ms`),console.log(` p95: ${t.p95.toFixed(2)}ms`),console.log(` p99: ${t.p99.toFixed(2)}ms`),console.log(` jank: ${t.jankFrames} frames (${n}%) >16.67ms`);break}case"frames":{let t=i[2]?Number(i[2]):50;(!Number.isFinite(t)||t<=0)&&(console.error(` error: expected a positive frame count, got "${i[2]}"`),process.exit(1));let s=await d.send({type:"evaluate",code:`(async () => {
796
+ if (window.__sootsimRenderHost) {
797
+ const session = window.${re} || {}
798
+ if (session.active) {
799
+ const priorSamples = Array.isArray(session.lastSamples) ? session.lastSamples : []
800
+ const flushedSamples = await window.__sootsimRenderHost.flushSamples()
801
+ const samples = priorSamples.concat(flushedSamples)
802
+ window.__sootsimRenderHost.startSampling()
803
+ window.${re} = {
804
+ ...session,
805
+ active: true,
806
+ mode: 'render-worker',
807
+ lastSamples: samples,
808
+ lastFlushAt: performance.now(),
809
+ }
810
+ return {
811
+ mode: 'render-worker',
812
+ live: true,
813
+ samples: samples.slice(-${t}),
814
+ }
815
+ }
816
+ return {
817
+ mode: 'render-worker',
818
+ live: false,
819
+ samples: (session.lastSamples || []).slice(-${t}),
820
+ }
821
+ }
822
+ // main-thread mode
823
+ const perf = window.__sootsimPerf
824
+ if (!perf) return { error: 'no __sootsimPerf (try "perf start" first)' }
825
+ const stats = perf.getFrameStats?.() || {}
826
+ return {
827
+ mode: 'main-thread',
828
+ frames: (stats.recentFrames || []).slice(-${t}),
829
+ }
830
+ })()`});if(s.error&&(console.error(` error: ${s.error}`),process.exit(1)),A(l)){E(s);break}if(s.mode==="render-worker"){let c=Array.isArray(s.samples)?s.samples:[];if(c.length===0){console.log(` no frame data \u2014 run '${b("perf")} start' first`);break}console.log(` last ${c.length} sampled frames (ms):`),console.log(" total layout render copy aux other t+");for(let[u,p,h,f,x,R,H]of c)console.log(` ${p.toFixed(2).padStart(7)} ${h.toFixed(2).padStart(7)} ${f.toFixed(2).padStart(7)} ${x.toFixed(2).padStart(7)} ${R.toFixed(2).padStart(6)} ${H.toFixed(2).padStart(7)} ${String(u).padStart(5)}`);console.log(""),Ue(c.map(u=>u[1])),s.live&&console.log(" sampling continues");break}let n=Array.isArray(s.frames)?s.frames:Array.isArray(s)?s:[];if(n.length===0){console.log(` no frame data \u2014 run '${b("perf")} start' first`);break}console.log(` last ${n.length} frame times (ms):`),console.log(` ${n.map(c=>c.toFixed(2)).join(", ")}`),Ue(n);break}case"worst":{let t=i[2]?Number(i[2]):20;(!Number.isFinite(t)||t<=0)&&(console.error(` error: expected a positive frame count, got "${i[2]}"`),process.exit(1));let s=await d.send({type:"evaluate",code:`(async () => {
831
+ if (window.__sootsimRenderHost) {
832
+ const session = window.${re} || {}
833
+ if (session.active) {
834
+ const priorSamples = Array.isArray(session.lastSamples) ? session.lastSamples : []
835
+ const flushedSamples = await window.__sootsimRenderHost.flushSamples()
836
+ const samples = priorSamples.concat(flushedSamples)
837
+ window.__sootsimRenderHost.startSampling()
838
+ window.${re} = {
839
+ ...session,
840
+ active: true,
841
+ mode: 'render-worker',
842
+ lastSamples: samples,
843
+ lastFlushAt: performance.now(),
844
+ }
845
+ return {
846
+ mode: 'render-worker',
847
+ live: true,
848
+ samples: samples
849
+ .slice()
850
+ .sort((a, b) => b[1] - a[1])
851
+ .slice(0, ${t}),
852
+ }
853
+ }
854
+ const samples = Array.isArray(session.lastSamples) ? session.lastSamples : []
855
+ return {
856
+ mode: 'render-worker',
857
+ live: false,
858
+ samples: samples
859
+ .slice()
860
+ .sort((a, b) => b[1] - a[1])
861
+ .slice(0, ${t}),
862
+ }
863
+ }
864
+ const perf = window.__sootsimPerf
865
+ if (!perf) return { error: 'no __sootsimPerf (try "perf start" first)' }
866
+ const stats = perf.getFrameStats?.() || {}
867
+ const recent = Array.isArray(stats.recentFrames) ? stats.recentFrames : []
868
+ return {
869
+ mode: 'main-thread',
870
+ frames: recent.slice().sort((a, b) => b - a).slice(0, ${t}),
871
+ }
872
+ })()`});if(s.error&&(console.error(` error: ${s.error}`),process.exit(1)),A(l)){E(s);break}if(s.mode==="render-worker"){let c=Array.isArray(s.samples)?s.samples:[];if(c.length===0){console.log(` no frame data \u2014 run '${b("perf")} start' first`);break}console.log(` worst ${c.length} sampled frames (ms):`),console.log(" total layout render copy aux other t+");for(let[u,p,h,f,x,R,H]of c)console.log(` ${p.toFixed(2).padStart(7)} ${h.toFixed(2).padStart(7)} ${f.toFixed(2).padStart(7)} ${x.toFixed(2).padStart(7)} ${R.toFixed(2).padStart(6)} ${H.toFixed(2).padStart(7)} ${String(u).padStart(5)}`);s.live&&(console.log(""),console.log(" sampling continues"));break}let n=Array.isArray(s.frames)?s.frames:Array.isArray(s)?s:[];if(n.length===0){console.log(` no frame data \u2014 run '${b("perf")} start' first`);break}console.log(` worst ${n.length} frame times (ms):`),console.log(` ${n.map(c=>c.toFixed(2)).join(", ")}`);break}case"transition":{let t=i[2];if(!t||!["goHome","appSwitcher","lockScreen"].includes(t)){console.log(`
873
+ ${b("perf")} transition <event> \u2014 profile a shell transition
874
+
875
+ events:
876
+ goHome swipe-to-home animation
877
+ appSwitcher app switcher card animation
878
+ lockScreen lock screen transition
879
+
880
+ note: uses 600ms capture window \u2014 may need --timeout 10000 flag
881
+
882
+ examples:
883
+ ${b("perf")} transition goHome --timeout 10000
884
+ ${b("perf")} transition appSwitcher
885
+ `);break}let n=`sootsim:${t}`;Le(` profiling ${t} transition...`),Le(" (use --timeout 10000 if this times out)");let c=await d.send({type:"evaluate",code:`(async () => {
886
+ // only supported in render-worker mode
887
+ if (!window.__sootsimRenderHost) {
888
+ return { error: 'transition profiling requires render-worker mode' }
889
+ }
890
+
891
+ // start sampling
892
+ window.__sootsimRenderHost.startSampling()
893
+
894
+ // give a frame for sampling to start
895
+ await new Promise(r => requestAnimationFrame(() => r(undefined)))
896
+
897
+ // dispatch the shell event
898
+ window.dispatchEvent(new Event('${n}'))
899
+
900
+ // wait 600ms for transition to complete (shell animations are ~300-500ms)
901
+ // using fixed timing avoids complex animation-end detection
902
+ await new Promise(r => setTimeout(r, 600))
903
+
904
+ // flush samples and compute stats
905
+ const samples = await window.__sootsimRenderHost.flushSamples()
906
+ const frameTimes = samples.map(s => s[1])
907
+ const layoutTimes = samples.map(s => s[2])
908
+ const renderTimes = samples.map(s => s[3])
909
+ const copyTimes = samples.map(s => s[4])
910
+ const auxTimes = samples.map(s => s[5] || 0)
911
+ const otherTimes = samples.map(s => s[6] || 0)
912
+ const sorted = [...frameTimes].sort((a, b) => a - b)
913
+ const total = frameTimes.reduce((a, b) => a + b, 0)
914
+ const avg = frameTimes.length > 0 ? total / frameTimes.length : 0
915
+ const max = Math.max(...frameTimes, 0)
916
+ const layoutTotal = layoutTimes.reduce((a, b) => a + b, 0)
917
+ const renderTotal = renderTimes.reduce((a, b) => a + b, 0)
918
+ const copyTotal = copyTimes.reduce((a, b) => a + b, 0)
919
+ const auxTotal = auxTimes.reduce((a, b) => a + b, 0)
920
+ const otherTotal = otherTimes.reduce((a, b) => a + b, 0)
921
+
922
+ return {
923
+ event: '${t}',
924
+ frames: frameTimes.length,
925
+ totalMs: total,
926
+ avgMs: avg,
927
+ maxMs: max,
928
+ layoutTotalMs: layoutTotal,
929
+ renderTotalMs: renderTotal,
930
+ copyTotalMs: copyTotal,
931
+ auxTotalMs: auxTotal,
932
+ otherTotalMs: otherTotal,
933
+ layoutAvgMs: frameTimes.length > 0 ? layoutTotal / frameTimes.length : 0,
934
+ renderAvgMs: frameTimes.length > 0 ? renderTotal / frameTimes.length : 0,
935
+ copyAvgMs: frameTimes.length > 0 ? copyTotal / frameTimes.length : 0,
936
+ auxAvgMs: frameTimes.length > 0 ? auxTotal / frameTimes.length : 0,
937
+ otherAvgMs: frameTimes.length > 0 ? otherTotal / frameTimes.length : 0,
938
+ p50: sorted[Math.floor(sorted.length * 0.5)] || 0,
939
+ p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
940
+ p99: sorted[Math.floor(sorted.length * 0.99)] || 0,
941
+ jankFrames: frameTimes.filter(f => f > 16.67).length,
942
+ samples,
943
+ }
944
+ })()`});if(c.error&&(console.error(` error: ${c.error}`),process.exit(1)),A(l)){E(c);break}if(c.warning&&console.log(` warning: ${c.warning}`),c.frames===0){console.log(" no frames captured");break}let u=c.avgMs>0?(1e3/c.avgMs).toFixed(1):"?",p=c.frames>0?(c.jankFrames/c.frames*100).toFixed(1):"0";console.log(` ${t} transition profiled:
945
+
946
+ frames: ${c.frames}
947
+ total: ${c.totalMs.toFixed(1)}ms
948
+ avg: ${c.avgMs.toFixed(2)}ms (${u} fps)
949
+ max: ${c.maxMs.toFixed(2)}ms
950
+
951
+ breakdown (avg per frame):
952
+ layout: ${c.layoutAvgMs?.toFixed(2)||"?"}ms
953
+ render: ${c.renderAvgMs?.toFixed(2)||"?"}ms
954
+ copy: ${c.copyAvgMs?.toFixed(2)||"?"}ms
955
+ aux: ${c.auxAvgMs?.toFixed(2)||"?"}ms
956
+ other: ${c.otherAvgMs?.toFixed(2)||"?"}ms
957
+
958
+ distribution (${c.frames} samples):
959
+ p50: ${c.p50.toFixed(2)}ms
960
+ p95: ${c.p95.toFixed(2)}ms
961
+ p99: ${c.p99.toFixed(2)}ms
962
+ jank: ${c.jankFrames} frames (${p}%) >16.67ms`),Array.isArray(c.samples)&&c.samples.length>0&&(console.log(""),Ue(c.samples.map(h=>h[1])));break}default:console.error(` unknown perf subcommand: ${o}`),console.error(" valid: stats, start, stop, frames, worst, transition"),/^--?reset$/.test(o)&&console.error(" note: 'perf start' already clears prior frames \u2014 no reset needed"),process.exit(1)}break}case"errors":{let o=i[1];if(o==="clear"){await je(d),A(l)?E({cleared:!0}):console.log(" error buffer cleared");break}let t=o?Number(o):20,s=await fe(d,t);if(A(l)){E(s);break}if(s.length===0){console.log(" no errors captured");break}console.log(` ${s.length} error(s):
963
+ `);for(let n of s){let c=ae(n.timestamp),u=n.args.map(p=>typeof p=="object"?JSON.stringify(p):p).join(" ");if(console.log(` [${c}] ${u}`),n.stack){let p=n.stack.split(`
964
+ `).slice(0,3);for(let h of p)console.log(` ${h.trim()}`)}}break}case"warnings":{let o=i[1]?Number(i[1]):20,t=await ct(d,o);if(A(l)){E(t);break}if(t.length===0){console.log(" no warnings captured");break}console.log(` ${t.length} warning(s):
965
+ `);for(let s of t){let n=ae(s.timestamp),c=s.args.map(u=>typeof u=="object"?JSON.stringify(u):u).join(" ");console.log(` [${n}] ${c}`)}break}case"animations":{let o=await Y(d,"listAnimations")??[];if(e.includes("--json")){console.log(JSON.stringify(o,null,2));break}if(o.length===0){console.log(" no active animations");break}console.log(` ${o.length} active animation(s):
966
+ `);for(let t of o){let s=String(t.kind).padEnd(6),n=`${Number(t.from).toFixed(2)}\u2192${Number(t.to).toFixed(2)}`,c=Number(t.current??0).toFixed(2),u=`${Math.round((t.progress??0)*100)}%`,p=`${Math.round(t.elapsedMs??0)}ms`,h=t.loop?" loop":"",f=t.layoutBound?" layout":"";console.log(` #${t.id} ${s} ${n.padEnd(14)} cur=${c.padEnd(7)} ${u.padStart(4)} ${p}${h}${f}`)}break}case"animation":{let o=i[1];(!o||o==="--help"||o==="-h")&&(console.error(` usage: ${b("animation")} <id>`),process.exit(1));let t=Number(o);Number.isFinite(t)||(console.error(` invalid id: ${o}`),process.exit(1));let s=await Y(d,"getAnimation",t);console.log(JSON.stringify(s,null,2));break}case"stop-animation":{let o=i[1];(!o||o==="--help"||o==="-h")&&(console.error(` usage: ${b("stop-animation")} <id|all>`),process.exit(1));let t=o==="all"?"all":Number(o);t!=="all"&&!Number.isFinite(t)&&(console.error(` invalid id: ${o}`),process.exit(1));let s=await Y(d,"stopAnimation",t);console.log(` stopped ${s??0} animation(s)`);break}case"requests":{let o=i[1];if(o==="clear"){await ut(d),A(l)?E({cleared:!0}):console.log(" request buffer cleared");break}let t=o==="all",s=t?i[2]:o,n=s?Number(s):20,c=await dt(d,{failed:!t,limit:n});if(A(l)){E(c);break}if(c.length===0){console.log(t?" no requests captured":" no failed requests captured");break}console.log(` ${c.length} ${t?"request(s)":"failed request(s)"}:
967
+ `);for(let u of c){let p=ae(u.timestamp);console.log(` [${p}] ${se(u)}`),u.responseBody?console.log(` ${u.responseBody}`):u.error&&console.log(` ${u.error}`)}break}case"network":{let o=i[1],t=null,s=null,n=!1,c=!1,u=1e3,p=!1,h=!1;for(let _=0;_<l.length;_++){let w=l[_];if(w==="--filter")t=l[_+1]??null,_++;else if(w==="--limit"){let S=Number(l[_+1]);Number.isFinite(S)&&(s=S),_++}else if(w==="--threshold"){let S=Number(l[_+1]);Number.isFinite(S)&&S>0&&(u=S),_++}else w==="--failed"?n=!0:w==="--slow"?c=!0:w==="--tail"||w==="-f"?p=!0:w==="--json"&&(h=!0)}if(o==="clear"){await d.send({type:"evaluate",code:'window.__sootsimObservability?.network.clear(); "cleared"'}),console.log(" network buffer cleared");break}if(o==="get"){let _=i[2];_||(console.error(" usage: sootsim network get <id>"),process.exit(1));let w=await d.send({type:"evaluate",code:`(() => {
968
+ const obs = window.__sootsimObservability;
969
+ if (!obs) return null;
970
+ return obs.network.getSnapshot().find(e => e.id === ${JSON.stringify(_)}) || null;
971
+ })()`});w||(console.error(` no entry with id ${_}`),process.exit(1)),h?console.log(JSON.stringify(w,null,2)):Ko(w);break}let f=s??(p?200:o?Number(o):20);Number.isFinite(f)||(console.error(` invalid limit: ${o} \u2014 \`network\` takes a numeric count (e.g. ${b("network")} 100).
972
+ to target a specific sim, use \`--sim ${o}\` instead.`),process.exit(1));let x=async()=>{let _=await d.send({type:"evaluate",code:`(() => {
973
+ const obs = window.__sootsimObservability;
974
+ if (!obs) return { ok: false };
975
+ return { ok: true, entries: obs.network.getSnapshot() };
976
+ })()`});if(!_||!_.ok)throw new Error("observability bridge not installed \u2014 is the engine running?");return _.entries??[]},R=_=>{let w=_;if(n&&(w=w.filter(S=>!!S.error||S.status!=null&&S.status>=400)),c&&(w=w.filter(S=>S.durationMs!=null&&S.durationMs>=u)),t){let S=t.toLowerCase();w=w.filter(k=>(k.displayUrl||k.url).toLowerCase().includes(S))}return c&&!p&&(w=[...w].sort((S,k)=>(k.durationMs??0)-(S.durationMs??0))),w};if(!p){let _=await x(),w=R(_).slice(-f);if(h){console.log(JSON.stringify(w,null,2));break}if(w.length===0){_.length===0?console.log(" no network requests captured"):console.log(c?` no requests slower than ${u}ms (${_.length} total \u2014 try --threshold <ms>)`:" no matching requests");break}console.log(c?` ${w.length} request(s) slower than ${u}ms (sorted by duration desc):
977
+ `:` ${w.length} request(s):
978
+ `);for(let S of w)so(S);break}console.log(` tailing network (ctrl-c to stop)...
979
+ `);let H=new Set,K=!0,U=()=>{K=!1};process.on("SIGINT",U);try{for(;K;){let _=await x(),w=R(_);for(let S of w)S.durationMs!=null&&(H.has(S.id)||(H.add(S.id),h?console.log(JSON.stringify(S)):so(S)));await te(250)}}finally{process.off("SIGINT",U)}break}case"logs":{let o=i[1],t=null,s=null,n=null,c=!1,u=!1,p=!1;for(let w=0;w<l.length;w++){let S=l[w];if(S==="--filter")t=l[w+1]??null,w++;else if(S==="--limit"){let k=Number(l[w+1]);Number.isFinite(k)&&(s=k),w++}else S==="--level"?(n=l[w+1]??null,w++):S==="--tail"||S==="-f"?c=!0:S==="--json"?u=!0:(S==="--internal"||S==="--all")&&(p=!0)}let h=n?new Set(n.split(",").map(w=>w.trim()).filter(w=>w==="log"||w==="info"||w==="warn"||w==="error"||w==="debug")):null;if(o==="clear"){await pt(d),console.log(" log buffer cleared");break}let f=!u&&process.stdout.isTTY===!0,x=s??(c?500:o?Number(o):50);Number.isFinite(x)||(console.error(` invalid limit: ${o} \u2014 \`logs\` takes a numeric count (e.g. ${b("logs")} 100).
980
+ to target a specific sim, use \`--sim ${o}\` instead.`),process.exit(1));let R=()=>mt(d),H=w=>ft(w,{level:h,filter:t,showInternal:p});if(!c){let w=await R(),S=H(w).slice(-x);if(u){console.log(JSON.stringify(S,null,2));break}if(S.length===0){console.log(w.length===0?" no logs captured":" no matching logs");break}console.log(` ${S.length} log(s):
981
+ `);for(let k of S)ro(k,f);break}console.log(` tailing logs (ctrl-c to stop)...
982
+ `);let K=new Set,U=!0,_=()=>{U=!1};process.on("SIGINT",_);try{for(;U;){let w=await R(),S=H(w);for(let k of S)K.has(k.id)||(K.add(k.id),u?console.log(JSON.stringify(k)):ro(k,f));await te(250)}}finally{process.off("SIGINT",_)}break}default:console.error(` unknown subcommand: ${g}`),process.exit(1)}if(C.has(g)&&!e.includes("--no-wait")&&process.env.SOOTSIM_NO_AUTO_WAIT!=="1"&&!await Qe(d,g)&&await v(d),$.length>0&&Q($),!j.has(g)&&!A(l))try{await xe(d)}catch{}}catch($){let o=$ instanceof Error?$.message:String($);console.error(` ${g??"inspect"} failed: ${o}`);let t=/^no sim connected with id (.+)$/.exec(o),s=/^command timed out after (\d+)s$/.exec(o),n=o.startsWith("sim disconnected:")||o.startsWith("bridge never reconnected")||o.startsWith("could not connect to ws://");if(t)await Ft(d,O,t[1]);else if(/^no sim connected$/.test(o))Nt(O);else if(s)if(await Lo(d)){let u=g??"describe";process.stderr.write(` the sim is still responsive \u2014 '${u}' just exceeded the ${s[1]}s command budget.
983
+ the screen's node tree is large; narrow the query or raise the budget:
984
+ sootsim ${u} --testid <id> # scope to one subtree
985
+ sootsim find --testid <id> # targeted single-node lookup
986
+ sootsim ${u} --timeout 60000 # raise per-command budget (ms)
987
+ `)}else to();else if(n)to();else{try{await Tt(d)}catch{}try{await ee({includeTail:!0})}catch{}try{await q({includeTail:!0})}catch{}}process.exit(1)}finally{d.close()}}export{Hn as runInspect};