rnxsim 0.0.0 → 0.1.313

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 (228) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +512 -0
  3. package/detox/colors.ts +54 -0
  4. package/detox/config-loader.ts +135 -0
  5. package/detox/element-types.ts +39 -0
  6. package/detox/expectations.ts +537 -0
  7. package/detox/gestures.ts +480 -0
  8. package/detox/index.ts +2118 -0
  9. package/detox/jest-preset.cjs +51 -0
  10. package/detox/jest-setup-after-env.cjs +18 -0
  11. package/detox/matchers.ts +30 -0
  12. package/detox/motion-change.cjs +109 -0
  13. package/detox/motion-change.d.cts +35 -0
  14. package/detox/navigation.ts +43 -0
  15. package/detox/screenshots/animated-color-test-rest-norngh.png +0 -0
  16. package/detox/screenshots/color-test-after-drag-norngh.png +0 -0
  17. package/detox/screenshots/color-test-rest-norngh.png +0 -0
  18. package/detox/screenshots/theme-blue-toggle.png +0 -0
  19. package/detox/screenshots/theme-blue.png +0 -0
  20. package/detox/screenshots/theme-red-toggle.png +0 -0
  21. package/detox/screenshots/theme-red.png +0 -0
  22. package/dist-cli/bin.js +15 -0
  23. package/dist-cli/chunks/agent-XZ2KTPCU.js +48 -0
  24. package/dist-cli/chunks/agent-wrapper-JJYYW2WH.js +17 -0
  25. package/dist-cli/chunks/app-fonts-IXRNQG6B.js +4 -0
  26. package/dist-cli/chunks/assert-54T5SK5F.js +49 -0
  27. package/dist-cli/chunks/auth-FI5UDI45.js +12 -0
  28. package/dist-cli/chunks/beta-JV6UKADW.js +4 -0
  29. package/dist-cli/chunks/camera-VL73YIKP.js +22 -0
  30. package/dist-cli/chunks/chunk-2D2UPBBR.js +4 -0
  31. package/dist-cli/chunks/chunk-2YR5BGA5.js +5 -0
  32. package/dist-cli/chunks/chunk-3NV2NCNX.js +4 -0
  33. package/dist-cli/chunks/chunk-46EUUFJ5.js +4 -0
  34. package/dist-cli/chunks/chunk-4NPPOV2N.js +5 -0
  35. package/dist-cli/chunks/chunk-5DHC6KHQ.js +7 -0
  36. package/dist-cli/chunks/chunk-5TEF3ET3.js +74 -0
  37. package/dist-cli/chunks/chunk-5TPRP5QT.js +4 -0
  38. package/dist-cli/chunks/chunk-5YJCOWCH.js +4 -0
  39. package/dist-cli/chunks/chunk-7GN3LVWB.js +4 -0
  40. package/dist-cli/chunks/chunk-BBULZ7CG.js +568 -0
  41. package/dist-cli/chunks/chunk-BTWORNNG.js +71 -0
  42. package/dist-cli/chunks/chunk-D4FFVGI5.js +5 -0
  43. package/dist-cli/chunks/chunk-DCEMHR2Y.js +4 -0
  44. package/dist-cli/chunks/chunk-DZS6WPUI.js +4 -0
  45. package/dist-cli/chunks/chunk-F5ZRSS3C.js +3 -0
  46. package/dist-cli/chunks/chunk-FSUYIVJ6.js +9 -0
  47. package/dist-cli/chunks/chunk-G2WW6L2C.js +23 -0
  48. package/dist-cli/chunks/chunk-GASE6UBA.js +4 -0
  49. package/dist-cli/chunks/chunk-GGRX24GF.js +142 -0
  50. package/dist-cli/chunks/chunk-HI5TFJWN.js +5 -0
  51. package/dist-cli/chunks/chunk-IJ5CAZZC.js +5 -0
  52. package/dist-cli/chunks/chunk-IJO63TDP.js +4 -0
  53. package/dist-cli/chunks/chunk-KTHV3RUS.js +26 -0
  54. package/dist-cli/chunks/chunk-LF2ZVT7O.js +6 -0
  55. package/dist-cli/chunks/chunk-MJRLLB4R.js +38 -0
  56. package/dist-cli/chunks/chunk-NFK7T35W.js +4 -0
  57. package/dist-cli/chunks/chunk-NMF2ZMZQ.js +15 -0
  58. package/dist-cli/chunks/chunk-OHAZNXLK.js +4 -0
  59. package/dist-cli/chunks/chunk-OVFJFXUD.js +101 -0
  60. package/dist-cli/chunks/chunk-OZSSI4WN.js +28 -0
  61. package/dist-cli/chunks/chunk-QKDWYITG.js +25 -0
  62. package/dist-cli/chunks/chunk-RSZWCKNT.js +30 -0
  63. package/dist-cli/chunks/chunk-RTN5C5RL.js +4 -0
  64. package/dist-cli/chunks/chunk-TIVZIMMW.js +4 -0
  65. package/dist-cli/chunks/chunk-TZFFR3SD.js +7 -0
  66. package/dist-cli/chunks/chunk-UC6U3MML.js +5 -0
  67. package/dist-cli/chunks/chunk-VFCMSYZK.js +6 -0
  68. package/dist-cli/chunks/chunk-VNQEB4L7.js +5 -0
  69. package/dist-cli/chunks/chunk-VZXWHRUZ.js +983 -0
  70. package/dist-cli/chunks/chunk-W6K4EFPH.js +107 -0
  71. package/dist-cli/chunks/chunk-WEXDAC74.js +4 -0
  72. package/dist-cli/chunks/chunk-WF3T4SVI.js +14 -0
  73. package/dist-cli/chunks/chunk-WINYQ44O.js +4 -0
  74. package/dist-cli/chunks/chunk-WMIIKMGK.js +10 -0
  75. package/dist-cli/chunks/chunk-WUSWBCWA.js +507 -0
  76. package/dist-cli/chunks/chunk-WWZIXIRD.js +4 -0
  77. package/dist-cli/chunks/chunk-XEVZYVIW.js +766 -0
  78. package/dist-cli/chunks/chunk-YDGQTMQL.js +4 -0
  79. package/dist-cli/chunks/chunk-YIFT42WN.js +4 -0
  80. package/dist-cli/chunks/chunk-ZMJD5GEC.js +125 -0
  81. package/dist-cli/chunks/cleanup-P27PA6JI.js +25 -0
  82. package/dist-cli/chunks/cli-version-WWLPBDQ7.js +4 -0
  83. package/dist-cli/chunks/compat-ZD65FED3.js +20 -0
  84. package/dist-cli/chunks/config-XMJRNM2A.js +13 -0
  85. package/dist-cli/chunks/control-KMIQT3QP.js +4 -0
  86. package/dist-cli/chunks/daemon-G2ME7NLB.js +4 -0
  87. package/dist-cli/chunks/debug-PT4HOP7N.js +200 -0
  88. package/dist-cli/chunks/desktop-S3FG72AK.js +31 -0
  89. package/dist-cli/chunks/detox-B3D4IFCN.js +52 -0
  90. package/dist-cli/chunks/device-XBNDSB2R.js +18 -0
  91. package/dist-cli/chunks/diagnose-HMQXJE5N.js +43 -0
  92. package/dist-cli/chunks/disk-cleanup-BLCZ5BSZ.js +4 -0
  93. package/dist-cli/chunks/drivers-LDECZGP2.js +4 -0
  94. package/dist-cli/chunks/film-BJGTBYZB.js +74 -0
  95. package/dist-cli/chunks/flow-UEQNVTU7.js +4 -0
  96. package/dist-cli/chunks/help-T5FYSVGB.js +4 -0
  97. package/dist-cli/chunks/hidden-runtime-alias-ANOYADHM.js +4 -0
  98. package/dist-cli/chunks/home-paths-GT3LFNOR.js +4 -0
  99. package/dist-cli/chunks/inspect-ZA6XF5LD.js +4 -0
  100. package/dist-cli/chunks/install-desktop-TIMUDHPL.js +4 -0
  101. package/dist-cli/chunks/login-FJ737MWG.js +28 -0
  102. package/dist-cli/chunks/logout-ZCNMMHMY.js +4 -0
  103. package/dist-cli/chunks/maestro-SZTNKLDF.js +104 -0
  104. package/dist-cli/chunks/maestro-generate-DCFAIZ4H.js +36 -0
  105. package/dist-cli/chunks/mode-GRMQCRXR.js +26 -0
  106. package/dist-cli/chunks/optional-demo-registry-W36EWFFB.js +4 -0
  107. package/dist-cli/chunks/perf-QYBAAUZG.js +48 -0
  108. package/dist-cli/chunks/permissions-3QCQ6VF4.js +13 -0
  109. package/dist-cli/chunks/record-QPPC2S4E.js +72 -0
  110. package/dist-cli/chunks/report-issue-7NMFP4HK.js +29 -0
  111. package/dist-cli/chunks/runtime-XOAXMSTU.js +4 -0
  112. package/dist-cli/chunks/screenshot-command-67AECJFB.js +159 -0
  113. package/dist-cli/chunks/screenshot-layers-ASWBYPJL.js +20 -0
  114. package/dist-cli/chunks/screenshots-capture-PXA3HFQK.js +42 -0
  115. package/dist-cli/chunks/serve-BI2NBAXG.js +44 -0
  116. package/dist-cli/chunks/setup-7DWPMRSB.js +32 -0
  117. package/dist-cli/chunks/skills-S3Y22TUA.js +50 -0
  118. package/dist-cli/chunks/storage-XUIMJWAJ.js +37 -0
  119. package/dist-cli/chunks/store-JTHEJLAZ.js +4 -0
  120. package/dist-cli/chunks/telemetry-ZYJGD2DB.js +4 -0
  121. package/dist-cli/chunks/timeline-TMPLQPSP.js +24 -0
  122. package/dist-cli/chunks/upgrade-7HDSIM7K.js +7 -0
  123. package/dist-cli/chunks/upload-GMSZPWM6.js +4 -0
  124. package/dist-cli/chunks/version-HOCHZ37L.js +6 -0
  125. package/dist-cli/chunks/web-DG3WBYD3.js +4 -0
  126. package/dist-cli/chunks/what-happened-XFVUTZR7.js +25 -0
  127. package/dist-lib/agent-daemon-client.cjs +468 -0
  128. package/dist-lib/agent-events.cjs +48 -0
  129. package/dist-lib/agent-identity.cjs +53 -0
  130. package/dist-lib/agent-sessions.cjs +725 -0
  131. package/dist-lib/attached-projects.cjs +526 -0
  132. package/dist-lib/auth/shared-session.cjs +195 -0
  133. package/dist-lib/backend-origin.cjs +70 -0
  134. package/dist-lib/beta.cjs +41 -0
  135. package/dist-lib/beta.mjs +13 -0
  136. package/dist-lib/bridge-constants.cjs +161 -0
  137. package/dist-lib/cli-constants.cjs +32 -0
  138. package/dist-lib/config.cjs +96 -0
  139. package/dist-lib/detox/index.cjs +2863 -0
  140. package/dist-lib/detox/jest-preset.cjs +51 -0
  141. package/dist-lib/dev-bundle-resolution.cjs +223 -0
  142. package/dist-lib/home-paths.cjs +421 -0
  143. package/dist-lib/host/bridge-host.cjs +5600 -0
  144. package/dist-lib/host/fetch-proxy-handler.cjs +373 -0
  145. package/dist-lib/host/fetch-proxy-overrides.cjs +63 -0
  146. package/dist-lib/host/fetch-proxy-overrides.mjs +37 -0
  147. package/dist-lib/host/websocket-proxy.cjs +214 -0
  148. package/dist-lib/index.cjs +513 -0
  149. package/dist-lib/jump-to-source-babel.cjs +93 -0
  150. package/dist-lib/menu.cjs +620 -0
  151. package/dist-lib/menu.mjs +581 -0
  152. package/dist-lib/metro.cjs +297 -0
  153. package/dist-lib/profiles.cjs +246 -0
  154. package/dist-lib/public-brand.cjs +39 -0
  155. package/dist-lib/render-mode.cjs +54 -0
  156. package/dist-lib/scripts/dev-server-scanner.cjs +1034 -0
  157. package/dist-lib/sdk.cjs +2333 -0
  158. package/dist-lib/sdk.mjs +2240 -0
  159. package/dist-lib/skills.cjs +23922 -0
  160. package/dist-lib/vite.cjs +358 -0
  161. package/package.json +189 -18
  162. package/scripts/dev-server-scanner.ts +941 -0
  163. package/scripts/optional-demo-registry.ts +113 -0
  164. package/scripts/postinstall.cjs +3 -0
  165. package/scripts/preuninstall.cjs +118 -0
  166. package/skills/contrast/SKILL.md +171 -0
  167. package/skills/rnx-debug/SKILL.md +425 -0
  168. package/skills/rnx-perf/SKILL.md +295 -0
  169. package/skills/rnx-setup/SKILL.md +160 -0
  170. package/skills/rnx-test/SKILL.md +292 -0
  171. package/skills/rnx-visual/SKILL.md +122 -0
  172. package/src/agent-daemon-client.ts +410 -0
  173. package/src/agent-events.ts +71 -0
  174. package/src/agent-identity.ts +23 -0
  175. package/src/agent-prompt.ts +71 -0
  176. package/src/agent-sessions.ts +573 -0
  177. package/src/attached-projects.ts +539 -0
  178. package/src/auth/shared-session.ts +204 -0
  179. package/src/backend-origin.ts +49 -0
  180. package/src/beta.ts +19 -0
  181. package/src/bridge-constants.ts +171 -0
  182. package/src/browser-cache.ts +16 -0
  183. package/src/cli-constants.ts +1 -0
  184. package/src/cli-version.ts +32 -0
  185. package/src/codex-client.ts +215 -0
  186. package/src/config.ts +134 -0
  187. package/src/dev-bundle-resolution.ts +236 -0
  188. package/src/disk-cleanup.ts +466 -0
  189. package/src/home-paths.ts +552 -0
  190. package/src/host/agent-host.ts +666 -0
  191. package/src/host/bridge-host.ts +2626 -0
  192. package/src/host/fetch-proxy-handler.ts +397 -0
  193. package/src/host/fetch-proxy-overrides.ts +51 -0
  194. package/src/host/open-url.ts +89 -0
  195. package/src/host/websocket-proxy.ts +210 -0
  196. package/src/index.ts +12 -705
  197. package/src/jump-to-source-babel.ts +135 -0
  198. package/src/menu.ts +734 -0
  199. package/src/metro-plugin.ts +139 -0
  200. package/src/native-dev-bundle-url.ts +96 -0
  201. package/src/native-seam-manifest.ts +341 -0
  202. package/src/plist.ts +27 -0
  203. package/src/poll-until.ts +92 -0
  204. package/src/profiles.ts +179 -0
  205. package/src/public-brand.ts +9 -0
  206. package/src/render-mode.ts +27 -0
  207. package/src/runtime-assets.ts +228 -0
  208. package/src/runtime-delivery.ts +54 -0
  209. package/src/screenshots/compose.ts +422 -0
  210. package/src/screenshots/frame-compose.ts +454 -0
  211. package/src/screenshots/orchestrate.ts +256 -0
  212. package/src/screenshots/org-deck.ts +91 -0
  213. package/src/screenshots/registry.ts +58 -0
  214. package/src/screenshots/schema.ts +364 -0
  215. package/src/sdk.ts +7 -0
  216. package/src/settings-bundle.ts +418 -0
  217. package/src/skills/builtin/a11y-review.ts +132 -0
  218. package/src/skills/builtin/compat-check.ts +71 -0
  219. package/src/skills/builtin/maestro-test.ts +121 -0
  220. package/src/skills/builtin/perf-profile.ts +90 -0
  221. package/src/skills/builtin/screenshot-all.ts +52 -0
  222. package/src/skills/builtin/visual-diff.ts +100 -0
  223. package/src/skills/registry.ts +107 -0
  224. package/src/skills/types.ts +41 -0
  225. package/src/team-machine-prompt.ts +73 -0
  226. package/src/vite-plugin-one.ts +190 -0
  227. package/src/vite-plugin.ts +1750 -0
  228. package/src/worklets-babel.ts +134 -0
@@ -0,0 +1,983 @@
1
+ /*! rnx v0.1.313 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import { createRequire as __sootsimCreateRequire } from 'node:module'
3
+ var require = __sootsimCreateRequire(import.meta.url)
4
+ import{b as Bt,c as Ct}from"./chunk-OHAZNXLK.js";import{a as de}from"./chunk-GGRX24GF.js";import{a as Et,b as At}from"./chunk-BTWORNNG.js";import{k as Dt}from"./chunk-NMF2ZMZQ.js";import{a as oe,b as D,c as A,d as Te,e as ae,f as X,g as pe,h as ye,i as Rt,j as Pt,k as Me,l as _t}from"./chunk-MJRLLB4R.js";import{A as $t,B as xt,C as St,F as vt,H as kt,J as ue,K as It,Q as We,a as ke,b as it,c as at,d as lt,e as ct,f as dt,g as ut,h as pt,i as mt,j as ft,k as Ce,l as je,r as qe,s as gt,t as yt,u as ge,v as ht,w as Ie,x as Le,y as bt,z as wt}from"./chunk-XEVZYVIW.js";import{a as rt,f as Tt,h as Mt,j as Nt,k as Ft,l as Ot,m as ce}from"./chunk-KTHV3RUS.js";import{a as st}from"./chunk-NFK7T35W.js";import{a as Q}from"./chunk-VNQEB4L7.js";import{f as nt}from"./chunk-4NPPOV2N.js";import{c as De,e as Be}from"./chunk-ZMJD5GEC.js";function Je(e){return`(async () => {
5
+ const bridge = globalThis.SootSim && globalThis.SootSim.bridges && globalThis.SootSim.bridges.hotRemount
6
+ if (!bridge || typeof bridge.reloadExternalApp !== 'function') return false
7
+ await bridge.reloadExternalApp({ resetStorage: ${e?"true":"false"} })
8
+ return true
9
+ })()`}import{existsSync as Ao,mkdirSync as qt,readFileSync as Do,rmSync as Ke,writeFileSync as Lt}from"fs";import{tmpdir as Bo}from"os";import{dirname as Wt,join as Co,resolve as Jt}from"path";import*as Ne from"fs";function Eo(e){let t={},s=e,i=f=>Array.isArray(f)?f:[],c=e.match(/^---\n([\s\S]*?)\n---\n?/);if(c){try{t=de.parse(c[1])??{}}catch(p){console.warn(` warn: could not parse frontmatter: ${p.message}`)}s=e.slice(c[0].length);let f=de.parse(s);return{frontmatter:t,steps:i(f)}}if(/\n---\s*\n/.test(e))try{let f=de.parseAllDocuments(e);if(f.length>=2){let p=f[0].toJS(),h=f[f.length-1].toJS();return{frontmatter:p&&typeof p=="object"?p:{},steps:i(h)}}}catch(f){console.warn(` warn: could not parse multi-doc flow: ${f.message}`)}let l=de.parse(s);return{frontmatter:t,steps:i(l)}}var jt=new Set(["tapOn","inputText","pressKey","dispatchKey","hideKeyboard","swipe","pinch","scroll","scrollUntilVisible"]);function He(e){let t=[];if(!Array.isArray(e)||e.length===0)return t.push("flow body must be a non-empty YAML array of steps"),t;let s=0;for(let i of e)i&&typeof i=="object"?Object.keys(i).some(l=>jt.has(l))&&(s+=1):typeof i=="string"&&jt.has(i)&&(s+=1);return s===0&&t.push("no interaction steps found (expected at least one tapOn / inputText / pressKey / swipe / scroll)"),t}function Fs(e){if(!Ne.existsSync(e))return[`file not found: ${e}`];let t;try{t=Ne.readFileSync(e,"utf8")}catch(s){return[`cannot read file: ${s.message}`]}if(t.trim().length===0)return["file is empty"];try{let s=Eo(t);return He(s.steps)}catch(s){return[`yaml parse error: ${s.message}`]}}var Ue=1;function Fe(){return Jt(process.env.SOOTSIM_FLOW_SESSION_PATH||Co(Bo(),"sootsim-flow-session.json"))}function Ge(e){let t=Fe();qt(Wt(t),{recursive:!0}),Lt(t,JSON.stringify(e,null,2)+`
10
+ `)}function Ye(){let e=Fe();if(!Ao(e))return null;try{let t=JSON.parse(Do(e,"utf8"));return t.version!==Ue||!Array.isArray(t.steps)||typeof t.startedAt!="string"||typeof t.updatedAt!="string"?(Ke(e,{force:!0}),null):{version:Ue,startedAt:t.startedAt,updatedAt:t.updatedAt,steps:t.steps,candidate:t.candidate??null}}catch{return Ke(e,{force:!0}),null}}function Ds(){let e=new Date().toISOString(),t={version:Ue,startedAt:e,updatedAt:e,steps:[],candidate:null};return Ge(t),{path:Fe(),state:t}}function jo(){Ke(Fe(),{force:!0})}function Bs(){jo()}function Oe(e){let t=Ye();if(!t)return{active:!1};let s=t.candidate,i={...t,updatedAt:new Date().toISOString(),candidate:{step:e.step,summary:e.summary,source:e.source,recordedAt:new Date().toISOString()}};return Ge(i),{active:!0,candidate:i.candidate,replaced:s}}function Cs(){let e=Ye();if(!e)return{active:!1,kept:!1,reason:"no-session"};if(!e.candidate)return{active:!0,kept:!1,reason:"no-candidate"};let t=e.candidate,s={...e,updatedAt:new Date().toISOString(),steps:[...e.steps,t.step],candidate:null};return Ge(s),{active:!0,kept:!0,candidate:t,stepCount:s.steps.length}}function qo(e){return de.stringify(e).trimEnd()+`
11
+ `}function js(e){let t=Ye();if(!t)return{active:!1};let s=qo(t.steps),i=He(t.steps);if(i.length>0)return{active:!0,valid:!1,issues:i,yaml:s,stepCount:t.steps.length,outputPath:null};let c=null;return e&&(c=Jt(e),qt(Wt(c),{recursive:!0}),Lt(c,s)),{active:!0,valid:!0,issues:[],yaml:s,stepCount:t.steps.length,outputPath:c}}import{existsSync as Lo,mkdirSync as Wo,readFileSync as Jo,rmSync as Ht,writeFileSync as Ho}from"fs";import{tmpdir as Ko}from"os";import{dirname as Uo,join as Go,resolve as Yo}from"path";var he=1,zo="SOOTSIM_INSPECT_NOTICE_PATH",Xo=300*1e3,Vo=15e3;function Kt(){return Yo(process.env[zo]||Go(Ko(),"sootsim-inspect-notice-state.json"))}function Qo(e,t){return Object.fromEntries(Object.entries(e).filter(([,s])=>typeof s?.signature=="string"&&Number.isFinite(s?.updatedAt)&&t-s.updatedAt<=Xo))}function Zo(e){let t=Kt();if(!Lo(t))return{version:he,entries:{}};try{let s=JSON.parse(Jo(t,"utf8"));return s.version!==he||!s.entries||typeof s.entries!="object"?(Ht(t,{force:!0}),{version:he,entries:{}}):{version:he,entries:Qo(s.entries,e)}}catch{return Ht(t,{force:!0}),{version:he,entries:{}}}}function es(e){let t=Kt();Wo(Uo(t),{recursive:!0}),Ho(t,JSON.stringify(e,null,2)+`
12
+ `)}function ts(e,t){let s=t.trim()||"default";return`${e}:${s}`}function ze(e,t,s,i={}){let c=i.nowMs??Date.now(),l=i.cooldownMs??Vo,f=Zo(c),p=ts(e,t),h=f.entries[p];return h&&h.signature===s&&c-h.updatedAt<l?!1:(f.entries[p]={signature:s,updatedAt:c},es(f),!0)}async function se({bridge:e,simId:t,maxMs:s,pollMs:i=50,stablePolls:c=3,strict:l=!1}){let f=await e.send({type:"evaluate",simId:t,code:`(async () => {
13
+ const start = Date.now()
14
+ const deadline = start + ${Math.max(0,Math.round(s))}
15
+ const pollMs = ${Math.max(1,Math.round(i))}
16
+ const requiredStablePolls = ${Math.max(1,Math.round(c))}
17
+ const strict = ${l?"true":"false"}
18
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
19
+
20
+ // route-aware settle: a tap that pushes/pops a screen is async \u2014 the
21
+ // old screen still renders for a moment, then the new one mounts and
22
+ // its content loads. a pure layout-hash check reports "idle" on the
23
+ // outgoing screen or on the incoming skeleton, so a driver re-taps
24
+ // and stacks duplicate navigations. drain any in-flight screen
25
+ // transition FIRST, bounded by the overall budget. when no
26
+ // transition is happening this returns in ~80ms (startWindowMs), so
27
+ // a plain button tap barely pays for it.
28
+ try {
29
+ const wfst = window.__sootsimTest?.waitForScreenTransitions
30
+ if (typeof wfst === 'function') {
31
+ const remaining = deadline - Date.now()
32
+ if (remaining > 120) {
33
+ await wfst({
34
+ timeoutMs: Math.min(remaining - 80, 4000),
35
+ settleMs: 64,
36
+ startWindowMs: 80,
37
+ })
38
+ }
39
+ }
40
+ } catch {}
41
+
42
+ const readSnapshot = async () => {
43
+ let animating = false
44
+ let pendingFetches = 0
45
+ let requestTotal = 0
46
+ let requestInFlight = 0
47
+ try {
48
+ const stats = await window.__sootsimRenderHost?.queryStats?.()
49
+ if (stats) {
50
+ animating =
51
+ stats.hasActiveAnims === true ||
52
+ stats.hasActiveNativeAnimations === true ||
53
+ stats.hasPendingAnimationFrames === true
54
+ // a freshly-pushed screen showing a skeleton is layout-stable
55
+ // but not actually settled \u2014 its data/images are still in
56
+ // flight. treat bounded image-loader fetches as not-idle so
57
+ // settle waits for real content, capped by the budget.
58
+ const pf = stats.memory && stats.memory.imageLoader
59
+ ? stats.memory.imageLoader.pendingFetches
60
+ : 0
61
+ pendingFetches = typeof pf === 'number' ? pf : 0
62
+ }
63
+ } catch {}
64
+ try {
65
+ const counts = await window.__sootsimTest?.getRequestCounts?.()
66
+ requestTotal = typeof counts?.total === 'number' ? counts.total : 0
67
+ requestInFlight = typeof counts?.inFlight === 'number' ? counts.inFlight : 0
68
+ } catch {}
69
+ const root = window.__sootsimRoot
70
+ const nodes = []
71
+ if (root) {
72
+ const walk = (n) => {
73
+ if (n.layout && n.layout.width > 0) {
74
+ nodes.push(Math.round(n.layout.x) + ',' + Math.round(n.layout.y) + ',' + Math.round(n.layout.width))
75
+ }
76
+ for (const c of n.children || []) walk(c)
77
+ }
78
+ walk(root)
79
+ }
80
+ return { layout: nodes.join(';'), animating, pendingFetches, requestTotal, requestInFlight }
81
+ }
82
+
83
+ // how long generic background network is allowed to keep us waiting AFTER
84
+ // the screen is otherwise visually settled. apps with continuous traffic
85
+ // (polling, realtime sockets, a tap that fires 20-50 fetches) never reach
86
+ // requestInFlight===0 / a stable requestTotal, so requiring full network
87
+ // quiet burns the ENTIRE budget on every command \u2014 the leading idle that
88
+ // failed PR-preview recordings for network-heavy apps (3pc fight-pulse).
89
+ // layout-stability + the image-loader already prove visible content
90
+ // loaded (a data load changes layout; an image load shows in the loader),
91
+ // so the generic request counters are a courtesy, not a gate: honor them
92
+ // only within this grace once the screen is visually still.
93
+ const networkQuietGraceMs = 1200
94
+ let lastLayout = ''
95
+ let lastRequestTotal = -1
96
+ let stable = 0
97
+ let visuallyStillSince = 0
98
+ while (Date.now() < deadline) {
99
+ const snapshot = await readSnapshot()
100
+ const strictOk = !strict || !snapshot.animating
101
+ // visually settled: no animations, no image content loading, layout
102
+ // unchanged since the last poll.
103
+ const visuallyStill =
104
+ strictOk && snapshot.pendingFetches === 0 && snapshot.layout === lastLayout
105
+ // generic network quiet: nothing in flight and no new requests issued.
106
+ const networkQuiet =
107
+ snapshot.requestInFlight === 0 && snapshot.requestTotal === lastRequestTotal
108
+ if (visuallyStill) {
109
+ stable++
110
+ if (visuallyStillSince === 0) visuallyStillSince = Date.now()
111
+ // settle once the screen has held still long enough AND either the
112
+ // network is genuinely quiet OR it has refused to quiet within the
113
+ // grace (continuous background traffic must not block forever).
114
+ if (
115
+ stable >= requiredStablePolls &&
116
+ (networkQuiet || Date.now() - visuallyStillSince >= networkQuietGraceMs)
117
+ ) {
118
+ return { settled: true, elapsed: Date.now() - start }
119
+ }
120
+ } else {
121
+ stable = 0
122
+ visuallyStillSince = 0
123
+ }
124
+ lastLayout = snapshot.layout
125
+ lastRequestTotal = snapshot.requestTotal
126
+ await sleep(pollMs)
127
+ }
128
+ return { settled: false, elapsed: Date.now() - start }
129
+ })()`},{timeoutMs:s+1e3}),{elapsed:p,settled:h}=f??{};return{elapsed:typeof p=="number"?p:s,settled:h===!0}}var Re=`(() => {
130
+ const spec = window.SootSim?.state?.engineSnapshot?.windowState?.deviceSpec
131
+ return spec && spec.width > 0 && spec.height > 0
132
+ ? { width: spec.width, height: spec.height }
133
+ : null
134
+ })()`,os={initialWaitMs:3e3,deadlineMs:5e3,retryWaitMs:700},ss={initialWaitMs:1200,deadlineMs:2500,retryWaitMs:700};function ns(e,t={}){return{...e?os:ss,...t}}function me(e){return!(!e||e.hit===!1||e.ok===!1||e.requestedTargetMatched===!1||e.pointerTapHandled===!1&&!e.keyboardOpened&&!e.isTextInput)}function rs(e,t){return{nodeId:e.target?.nodeId??e.match?.nodeId??e.node?.nodeId??null,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??t??null,type:e.target?.type??e.match?.type??e.node?.type??null}}async function be(e,t){let s=ns(!!t.agent,t.timing),i=0,c=null,l=null;try{await se({bridge:e,maxMs:s.initialWaitMs,pollMs:32,stablePolls:2})}catch{}let f=Date.now()+s.deadlineMs,p=null;for(;Date.now()<=f||i===0;){i++;let h=await t.resolve();if(c=h,h?.error==="bridge-not-ready"||h?.ambiguous||h?.nthOutOfRange)return{payload:h,result:null,attempts:i,failure:"special"};if(h&&typeof h.cx=="number"&&typeof h.cy=="number")if(h.offscreen){l={hit:!1,reason:"offscreen",x:h.cx,y:h.cy,screen:h.screen};let b=`${Math.round(h.cx)},${Math.round(h.cy)}`;if(p===b)return{payload:h,result:l,attempts:i,failure:"missed"};p=b}else{p=null;let b=rs(h,t.textFallback),v=await e.send({type:"evaluate",code:`(async () => {
135
+ const t = window.__sootsimTest
136
+ if (
137
+ !t ||
138
+ typeof t.inspectAt !== 'function' ||
139
+ typeof t.resolveTapTarget !== 'function'
140
+ ) {
141
+ return { error: 'tap-target-inspection-unavailable' }
142
+ }
143
+ const requestedTarget = ${JSON.stringify(b)}
144
+ const inspected = await t.inspectAt(${h.cx}, ${h.cy})
145
+ const resolved =
146
+ inspected && typeof inspected.nodeId === 'number'
147
+ ? await t.resolveTapTarget(inspected.nodeId)
148
+ : null
149
+ const node = (resolved && resolved.target) || inspected
150
+ const coordinateTarget = node
151
+ ? {
152
+ nodeId: node.nodeId ?? null,
153
+ id: node.id ?? null,
154
+ testID: node.testID ?? null,
155
+ text: node.text ?? node.accessibilityLabel ?? null,
156
+ type: node.type ?? null,
157
+ }
158
+ : null
159
+ const coordinateAncestors = Array.isArray(inspected?.ancestors)
160
+ ? inspected.ancestors
161
+ : []
162
+ const ancestorMatchesRequested = coordinateAncestors.some(
163
+ (ancestor) =>
164
+ (typeof requestedTarget.nodeId === 'number' &&
165
+ ancestor?.nodeId === requestedTarget.nodeId) ||
166
+ (requestedTarget.testID &&
167
+ ancestor?.testID === requestedTarget.testID) ||
168
+ (requestedTarget.id && ancestor?.id === requestedTarget.id),
169
+ )
170
+ const requestedTargetMatched =
171
+ coordinateTarget === null
172
+ ? false
173
+ : typeof requestedTarget.nodeId === 'number' &&
174
+ typeof coordinateTarget.nodeId === 'number'
175
+ ? requestedTarget.nodeId === coordinateTarget.nodeId ||
176
+ ancestorMatchesRequested
177
+ : requestedTarget.testID && coordinateTarget.testID
178
+ ? requestedTarget.testID === coordinateTarget.testID
179
+ || ancestorMatchesRequested
180
+ : requestedTarget.id && coordinateTarget.id
181
+ ? requestedTarget.id === coordinateTarget.id
182
+ || ancestorMatchesRequested
183
+ : ancestorMatchesRequested
184
+ if (!requestedTargetMatched) {
185
+ return {
186
+ requestedTargetMatched,
187
+ requestedTarget,
188
+ coordinateTarget,
189
+ }
190
+ }
191
+ if (typeof t.activatePressAt !== 'function') {
192
+ return { error: 'tap-target-activation-unavailable' }
193
+ }
194
+ const activation = await t.activatePressAt(
195
+ ${h.cx},
196
+ ${h.cy},
197
+ requestedTarget.nodeId,
198
+ )
199
+ if (activation?.ok) {
200
+ window.dispatchEvent(
201
+ new CustomEvent('sootsim:agentAction', {
202
+ detail: {
203
+ type: 'tap',
204
+ x: ${h.cx},
205
+ y: ${h.cy},
206
+ target: requestedTarget,
207
+ },
208
+ }),
209
+ )
210
+ }
211
+ return {
212
+ activation,
213
+ requestedTargetMatched,
214
+ requestedTarget,
215
+ coordinateTarget,
216
+ }
217
+ })()`});if(v?.error)return{payload:h,result:{hit:!1,reason:v.error,requestedTarget:b},attempts:i,failure:"special"};if(v?.requestedTargetMatched===!1)return{payload:h,result:{hit:!1,reason:"target-covered",...v},attempts:i,failure:"missed"};let F=v?.activation?.tap??v?.activation,N=F&&typeof F=="object"?{...F,...v?.activation,...v}:{hit:!!F,...v};if(l=N,me(N))return{payload:h,result:N,attempts:i}}let $=f-Date.now();if($<=0)break;try{await se({bridge:e,maxMs:Math.min($,s.retryWaitMs),pollMs:32,stablePolls:2})}catch{await new Promise(b=>setTimeout(b,Math.min(120,$)))}}return{payload:c,result:l,attempts:i,failure:c&&typeof c.cx=="number"?"missed":"not-found"}}async function Ut(e,t,s,i){return e.send({type:"tap",x:t,y:s,...i?{target:i}:{}})}async function Gt(e,t,s={}){let i=JSON.stringify(t);return be(e,{agent:s.agent,timing:s.timing,resolve:()=>e.send({type:"evaluate",code:`(async () => {
218
+ const t = window.__sootsimTest
219
+ if (!t) return null
220
+ const n = (await t.findByTestId(${i})) || (await t.findById(${i}))
221
+ if (!n || !n.absolutePosition || !n.layout) return { cx: null }
222
+ const resolved =
223
+ typeof n.nodeId === 'number' && typeof t.resolveTapTarget === 'function'
224
+ ? await t.resolveTapTarget(n.nodeId)
225
+ : null
226
+ const target = (resolved && resolved.target) || n
227
+ const cx =
228
+ resolved && typeof resolved.cx === 'number'
229
+ ? resolved.cx
230
+ : n.absolutePosition.x + (n.layout.width || 0) / 2
231
+ const cy =
232
+ resolved && typeof resolved.cy === 'number'
233
+ ? resolved.cy
234
+ : n.absolutePosition.y + (n.layout.height || 0) / 2
235
+ const scr = ${Re}
236
+ const offscreen =
237
+ !!scr && (cx < 0 || cy < 0 || cx > scr.width || cy > scr.height)
238
+ return {
239
+ cx,
240
+ cy,
241
+ ...(offscreen ? { offscreen: true, screen: scr } : {}),
242
+ match: {
243
+ nodeId: n.nodeId ?? null,
244
+ id: n.id,
245
+ testID: n.testID,
246
+ text: n.text ?? n.accessibilityLabel ?? null,
247
+ type: n.type,
248
+ },
249
+ target: {
250
+ nodeId: target.nodeId ?? null,
251
+ id: target.id,
252
+ testID: target.testID,
253
+ text:
254
+ target.text ??
255
+ target.accessibilityLabel ??
256
+ n.text ??
257
+ n.accessibilityLabel ??
258
+ null,
259
+ type: target.type,
260
+ },
261
+ strategy: (resolved && resolved.strategy) || 'matched-node',
262
+ }
263
+ })()`})})}async function Yt(e,t,s={},i={}){let c=JSON.stringify({query:t,exact:!!s.exact,role:s.role??null,within:s.within??null,minX:s.minX??null,maxX:s.maxX??null,minY:s.minY??null,maxY:s.maxY??null,near:s.near??null,nth:s.nth??null,first:!!s.first});return be(e,{agent:i.agent,timing:i.timing,textFallback:t,resolve:()=>e.send({type:"evaluate",code:`(async () => {
264
+ const t = window.__sootsimTest
265
+ if (!t) return { error: 'bridge-not-ready' }
266
+ const F = ${c}
267
+
268
+ const res = await t.queryTextCandidates({
269
+ query: F.query,
270
+ exact: !!F.exact,
271
+ ...(F.role ? { role: F.role } : {}),
272
+ })
273
+
274
+ let candidates = res.candidates || []
275
+
276
+ candidates = candidates.filter((c) => {
277
+ const ax = c.info.absolutePosition && c.info.absolutePosition.x
278
+ const ay = c.info.absolutePosition && c.info.absolutePosition.y
279
+ if (F.minX !== null && !(ax >= F.minX)) return false
280
+ if (F.maxX !== null && !(ax <= F.maxX)) return false
281
+ if (F.minY !== null && !(ay >= F.minY)) return false
282
+ if (F.maxY !== null && !(ay <= F.maxY)) return false
283
+ if (F.within && !c.ancestorTestIDs.includes(F.within)) return false
284
+ return true
285
+ })
286
+
287
+ if (F.near) {
288
+ candidates.sort((a, b) => {
289
+ const ax = (a.info.absolutePosition && a.info.absolutePosition.x) || 0
290
+ const ay = (a.info.absolutePosition && a.info.absolutePosition.y) || 0
291
+ const bx = (b.info.absolutePosition && b.info.absolutePosition.x) || 0
292
+ const by = (b.info.absolutePosition && b.info.absolutePosition.y) || 0
293
+ return (
294
+ Math.hypot(ax - F.near.x, ay - F.near.y) -
295
+ Math.hypot(bx - F.near.x, by - F.near.y)
296
+ )
297
+ })
298
+ } else {
299
+ candidates.sort((a, b) => {
300
+ const ay = (a.info.absolutePosition && a.info.absolutePosition.y) || 0
301
+ const by = (b.info.absolutePosition && b.info.absolutePosition.y) || 0
302
+ if (Math.abs(ay - by) > 2) return ay - by
303
+ const ax = (a.info.absolutePosition && a.info.absolutePosition.x) || 0
304
+ const bx = (b.info.absolutePosition && b.info.absolutePosition.x) || 0
305
+ return ax - bx
306
+ })
307
+ }
308
+
309
+ const total = candidates.length
310
+ if (total === 0) return { matched: 0, total: 0 }
311
+
312
+ let idx = 0
313
+ if (F.nth !== null) {
314
+ idx = F.nth < 0 ? total + F.nth : F.nth
315
+ if (idx < 0 || idx >= total) {
316
+ return { matched: 0, total, nthOutOfRange: true, nth: F.nth }
317
+ }
318
+ } else if (total > 1 && !F.first && !F.near) {
319
+ return {
320
+ ambiguous: true,
321
+ total,
322
+ candidates: candidates.slice(0, 10).map((c, i) => ({
323
+ idx: i,
324
+ nodeId: c.info.nodeId,
325
+ type: c.info.type,
326
+ testID: c.info.testID,
327
+ text: (c.info.text || '').slice(0, 60),
328
+ abs: c.info.absolutePosition,
329
+ layout: c.info.layout
330
+ ? {
331
+ width: Math.round(c.info.layout.width || 0),
332
+ height: Math.round(c.info.layout.height || 0),
333
+ }
334
+ : null,
335
+ ancestorTestIDs: (c.ancestorTestIDs || []).slice(0, 5),
336
+ })),
337
+ }
338
+ }
339
+
340
+ const picked = candidates[idx]
341
+ const n = picked.info
342
+ if (!n.absolutePosition || !n.layout) return { matched: 0, total }
343
+
344
+ const resolved =
345
+ typeof n.nodeId === 'number' &&
346
+ typeof t.resolveTapTarget === 'function'
347
+ ? await t.resolveTapTarget(n.nodeId)
348
+ : null
349
+ const target = (resolved && resolved.target) || n
350
+ const cx =
351
+ resolved && typeof resolved.cx === 'number'
352
+ ? resolved.cx
353
+ : n.absolutePosition.x + (n.layout.width || 0) / 2
354
+ const cy =
355
+ resolved && typeof resolved.cy === 'number'
356
+ ? resolved.cy
357
+ : n.absolutePosition.y + (n.layout.height || 0) / 2
358
+ const scr = ${Re}
359
+ const offscreen =
360
+ !!scr && (cx < 0 || cy < 0 || cx > scr.width || cy > scr.height)
361
+ return {
362
+ cx,
363
+ cy,
364
+ ...(offscreen ? { offscreen: true, screen: scr } : {}),
365
+ match: {
366
+ nodeId: n.nodeId ?? null,
367
+ id: n.id,
368
+ testID: n.testID,
369
+ type: n.type,
370
+ },
371
+ target: {
372
+ nodeId: target.nodeId ?? null,
373
+ id: target.id,
374
+ testID: target.testID,
375
+ text:
376
+ target.text ??
377
+ target.accessibilityLabel ??
378
+ n.text ??
379
+ n.accessibilityLabel ??
380
+ null,
381
+ type: target.type,
382
+ },
383
+ strategy: (resolved && resolved.strategy) || 'matched-node',
384
+ total,
385
+ idx,
386
+ }
387
+ })()`})})}async function zt(e,t,s={}){let i=JSON.stringify(t);return be(e,{agent:s.agent,timing:s.timing,textFallback:t,resolve:async()=>{let c=await e.send({type:"evaluate",code:`(async () => {
388
+ const t = window.__sootsimTest
389
+ if (!t) return { error: 'bridge-not-ready' }
390
+ const byTestId =
391
+ (await t.findByTestId(${i})) || (await t.findById(${i}))
392
+ if (byTestId && byTestId.absolutePosition && byTestId.layout) {
393
+ return {
394
+ strategy: 'testid',
395
+ node: {
396
+ nodeId: byTestId.nodeId ?? null,
397
+ id: byTestId.id,
398
+ testID: byTestId.testID,
399
+ type: byTestId.type,
400
+ text: byTestId.text,
401
+ absolutePosition: byTestId.absolutePosition,
402
+ layout: byTestId.layout,
403
+ },
404
+ screen: ${Re},
405
+ }
406
+ }
407
+ const byText = await t.findByText(${i})
408
+ if (byText && byText.absolutePosition && byText.layout) {
409
+ return {
410
+ strategy: 'text',
411
+ node: {
412
+ nodeId: byText.nodeId ?? null,
413
+ id: byText.id,
414
+ testID: byText.testID,
415
+ type: byText.type,
416
+ text: byText.text,
417
+ absolutePosition: byText.absolutePosition,
418
+ layout: byText.layout,
419
+ },
420
+ screen: ${Re},
421
+ }
422
+ }
423
+ return { strategy: 'none' }
424
+ })()`});if(!c||!("node"in c))return c;let l=c.node,f=l.absolutePosition.x+l.layout.width/2,p=l.absolutePosition.y+l.layout.height/2,h=c.screen??null,$=!!h&&(f<0||p<0||f>h.width||p>h.height);return{...c,cx:f,cy:p,...$?{offscreen:!0,screen:h}:{},target:{id:l.id,testID:l.testID,text:c.strategy==="text"?t:l.text,type:l.type}}}})}async function Xt(e,t={args:[]}){let s=await at(e);if(D(t.args)){A(s);return}console.log(` nodes: ${s.nodes}`)}function Xe(e,t){let s=e.indexOf(t);return s>=0&&s+1<e.length?e[s+1]:null}async function Vt(e){let{bridge:t,args:s,positional:i}=e,c=s.includes("--verbose")||s.includes("-v"),l=D(s),f=c&&!l,p=s.includes("--watch")||s.includes("-w"),h=1e3,$=s.includes("--compact"),b=s.includes("--no-xy"),v=s.includes("--no-clipped"),F=s.includes("--include-occluded"),N=Xe(s,"--testid-like"),j=Xe(s,"--only"),R=Xe(s,"--subtree"),d=i[1]&&!i[1].startsWith("-")?i[1]:void 0,q=d?/[*?]/.test(d):!1,P=!q&&!j?d:void 0,E=j??(q?d:void 0),J=async()=>{await pe(t,{verbose:f});let I=await dt(t,{describe:!0,verbose:c,filter:P||"",testIdLike:N||void 0,onlyGlob:E||void 0,subtreeRoot:R||void 0,compact:$,hideXy:b,includeOccluded:F,fullText:l}),O=I?.tree,H=I?.shell,K=I?.keyboard;if(l){A({shell:H,tree:O??"",keyboard:K});return}if(H&&typeof H=="object"){let C=[H.state?`state=${H.state}`:null,H.activeApp?`app=${H.activeApp}`:null,H.showSwitcher?"switcher":null,H.switcherPhase&&H.switcherPhase!=="idle"?`phase=${H.switcherPhase}`:null].filter(Boolean);C.length>0&&console.log(` shell: ${C.join(" ")}`)}if(typeof O=="string"&&O.startsWith("__SUBTREE_NOT_FOUND__:")){let C=O.slice(22);console.log(` subtree root not found: ${C}`),Q("subtree-root-not-found",C);return}if(!O){let C=I?.nodeCount??0;console.log(" no matching nodes found"),!(P||N||E||R)&&C<10&&Q("app-still-loading",C);return}let ee=O,te=0;if(v&&typeof ee=="string"){let C=ee.split(`
425
+ `),le=[];for(let Se of C){if(Se.includes("(clipped:")){te+=1;continue}le.push(Se)}ee=le.join(`
426
+ `)}console.log(ee),te>0&&console.log(` ${te} clipped row(s) hidden (omit --no-clipped to see)`);let ie=P||N||E||R;if((P||N||E)&&!p&&Q("describe-filter-context"),!ie&&!p&&O.split(`
427
+ `).length>=80&&Q("describe-use-filters"),K&&K.visible){let C=K.spec,le=[C?.keyboardType?`type=${C.keyboardType}`:null,C?.returnKeyType&&C.returnKeyType!=="default"?`return=${C.returnKeyType}`:null,K.mode!=="letters"?`mode=${K.mode}`:null,K.shifted?"shift":null,K.capsLock?"caps":null,C?.autoCapitalize&&C.autoCapitalize!=="sentences"?`autoCap=${C.autoCapitalize}`:null,K.accessoryBarId?`accessory=${K.accessoryBarId}`:null].filter(Boolean);console.log(`
428
+ keyboard: ${le.join(" ")||"visible"}`)}};if(p)for(console.log(` watching... (Ctrl+C to stop)
429
+ `);;)console.clear(),await J(),await oe(h);else await J()}var is=["SOOTSIM_AGENT","TM_SESSION","CLAUDECODE","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_SESSION_ID","CODEX_THREAD_ID","CURSOR_TRACE_ID","AIDER_MODEL"];function fe(){if(process.env.SOOTSIM_AGENT==="0")return!1;for(let e of is){let t=process.env[e];if(t&&t.trim()&&t!=="0")return!0}return!1}async function Qt(e){let{bridge:t,args:s,effectiveArgs:i,positional:c,inspectUsage:l}=e,f=I=>{let O=i.indexOf(I);return O>=0&&O+1<i.length?i[O+1]:null},p=I=>i.includes(I),h=f("--testid")||f("--test-id"),$=f("--role"),b=f("--type"),v=f("--text"),F=p("--pressable"),N=p("--visible"),j=p("--interactive-targets")||p("--actions"),R=!h&&!$&&!b&&!v&&!F&&!N&&!j?c[1]:null,d=v??R,q=await ft(t,{testId:h,role:$,type:b,text:d,pressable:F,visible:N,interactive:j});q||(console.error(l("find","<text> | --text <t> | --testid <id> | --role <r> | --type <t> | --pressable | --visible | --interactive-targets")),process.exit(1));let{mode:P,result:E}=q,J=D(s),U=s.includes("--verbose")||s.includes("--dump");if(J)P==="interactive-targets"&&Array.isArray(E)?A(Ce(E).map(I=>({...I,tap:je(I)}))):A(E??null);else if(Array.isArray(E))if(E.length===0){console.log(` no ${P} nodes found`);let I=await t.send({type:"evaluate",code:"(async () => (await window.__sootsimTest?.getNodeCount?.()) || 0)()"});typeof I=="number"&&I<10&&Q("app-still-loading",I)}else if(P==="interactive-targets"){let I=Ce(E);console.log(` found ${I.length} interactive target${I.length===1?"":"s"} (sorted by score):`);for(let O of I.slice(0,20)){let H=O.absolutePosition?`@(${Math.round(O.absolutePosition.x)},${Math.round(O.absolutePosition.y)})`:"",K=O.layout?`${Math.round(O.layout.width)}x${Math.round(O.layout.height)}`:"?x?",ee=O.text?` "${O.text.slice(0,30)}"`:"",te=O.testID?` #${O.testID}`:"",ie=O.accessibilityLabel?` \u24D8"${String(O.accessibilityLabel).slice(0,24)}"`:"",xe=O.accessibilityRole?`[${O.accessibilityRole}]`:O.type,C=je(O);console.log(` ${xe}${ee}${ie}${te} ${K} ${H}`),console.log(` \u2192 ${C}`),U&&console.log(Ve(JSON.stringify(O,null,2)," "))}I.length>20&&console.log(` ... and ${I.length-20} more`)}else{console.log(` found ${E.length} node${E.length===1?"":"s"} (${P}):`);for(let I of E.slice(0,20)){let O=I.absolutePosition?`@(${Math.round(I.absolutePosition.x)},${Math.round(I.absolutePosition.y)})`:"",H=I.layout?`${Math.round(I.layout.width)}x${Math.round(I.layout.height)}`:"?x?",K=I.text?` "${I.text.slice(0,30)}"`:"",ee=I.testID?` #${I.testID}`:"",te=I.pressable?" (tap)":"",ie=I.accessibilityRole?`[${I.accessibilityRole}]`:I.type;console.log(` ${ie}${K}${ee} ${H} ${O}${te}`),U&&console.log(Ve(JSON.stringify(I,null,2)," "))}E.length>20&&console.log(` ... and ${E.length-20} more`)}else if(E==null)console.log(` not found: ${d||h||$||b||""||P}`),h&&Q("wait-selector-for-missing-testid",h);else{let I=E;if(I.type&&I.absolutePosition){let O=`@(${Math.round(I.absolutePosition.x)},${Math.round(I.absolutePosition.y)})`,H=I.layout?`${Math.round(I.layout.width)}x${Math.round(I.layout.height)}`:"?x?",K=I.text?` "${I.text.slice(0,40)}"`:"",ee=I.testID?` #${I.testID}`:"",te=I.pressable?" (tap)":"",ie=I.accessibilityRole?`[${I.accessibilityRole}]`:I.type;console.log(` ${ie}${K}${ee} ${H} ${O}${te}`),U&&console.log(Ve(JSON.stringify(I,null,2)," "))}else console.log(JSON.stringify(E,null,2))}}function Ve(e,t){return e.split(`
430
+ `).map(s=>t+s).join(`
431
+ `)}async function Zt(e){let{bridge:t,args:s}=e,i=D(s);await pe(t,{verbose:!i});let c=s.includes("--styling"),l=s.indexOf("--filter"),f=l>=0?s[l+1]:void 0,p=await ut(t,{styling:c,filter:f});if(i){A({count:p.length,elements:p});return}console.log(` layout (${p.length} element${p.length===1?"":"s"}):
432
+ `),console.log(pt(p,{styling:c}))}async function eo(e,t={}){let s=await kt(e);if("error"in s&&(console.error(s.error),process.exit(1)),t.json){console.log(JSON.stringify(s,null,2));return}let{visible:i,spec:c,mode:l,shifted:f,capsLock:p,accessoryBarId:h}=s,$=[];$.push(`keyboard: ${i?"visible":"hidden"}`),c?($.push(` type: ${c.keyboardType}`),$.push(` returnKey: ${c.returnKeyType}`),$.push(` autoCap: ${c.autoCapitalize}`),$.push(` autoCorrect: ${c.autoCorrect?"on":"off"}`),$.push(` appearance: ${c.keyboardAppearance}`),c.secureTextEntry&&$.push(" secureTextEntry: true"),c.enablesReturnKeyAutomatically&&$.push(` return: ${c.currentTextIsEmpty?"disabled (empty)":"enabled"}`)):$.push(" spec: <none> (shown via dev-tools with no TextInput)"),$.push(` mode: ${l}${f?" (shifted)":""}${p?" (caps)":""}`),h&&$.push(` accessoryBar: ${h}`),console.log($.join(`
433
+ `))}async function to(e){let t=await e.bridge.listSims(),s=e.args.includes("--all"),i=e.args.find((p,h)=>e.args[h-1]==="--bundle"),c=e.args.find((p,h)=>e.args[h-1]==="--app-port"),l=e.args.includes("--primary"),f=t.filter(p=>!(l&&!p.isPrimary||i&&!(p.url??"").includes(i)||c&&!(p.url??"").includes(`/rn/${c}`)||!s&&!i&&!c&&!l&&!(p.url&&(p.url.includes("bundle=")||p.url.includes("/index.bundle")))&&p.id!==e.simId));if(D(e.args)){A(f.map(p=>({...p,active:p.id===e.simId})));return}Dt(f,e.simId),f.length<t.length&&!D(e.args)&&console.log(` (${t.length-f.length} more hidden \u2014 pass --all to show)`)}function re(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function as(e,t){return t<=0?"?":`${(e/t*100).toFixed(0)}%`}function ls(e){let t={},s=(i,c)=>{c&&(c.nodesRegistered!=null&&(t[`${i}.nodes`]=c.nodesRegistered),c.nodesDetached!=null&&(t[`${i}.detached`]=c.nodesDetached),c.objects&&(t[`${i}.paragraphs`]=c.objects.paragraphs,t[`${i}.yogaNodes`]=c.objects.yogaNodes,t[`${i}.pictures`]=c.objects.pictures,t[`${i}.rasterImages`]=c.objects.rasterImages),c.imageLoader&&(t[`${i}.imageCacheEntries`]=c.imageLoader.cacheEntries,t[`${i}.imagePixelBytes`]=c.imageLoader.cachePixelBytes),c.workerHeap&&(t[`${i}.heapBytes`]=c.workerHeap.usedJSHeapSize),c.wasmHeapBytes!=null&&(t[`${i}.wasmHeapBytes`]=c.wasmHeapBytes))};return s("tenant",e.tenant),s("shell",e.shell),s("compositor",e.compositor),e.hostHeap&&(t["host.heapBytes"]=e.hostHeap.usedJSHeapSize),t}function oo(e,t){return e.endsWith("Bytes")?re(t):String(t)}function Qe(e,t){if(!t){console.log(` ${e}: not available`);return}let s=t.objects;if(console.log(` ${e}`),t.nodesRegistered!=null&&console.log(` nodes registered: ${t.nodesRegistered}`),t.nodesDetached!=null){let i=Object.entries(t.detachedTypes??{}).map(([c,l])=>`${c}:${l}`).join(" ");console.log(` nodes detached: ${t.nodesDetached}${i?` (${i})`:""}`)}if(s&&(console.log(` paragraphs: ${s.paragraphs}`),console.log(` yoga nodes: ${s.yogaNodes}`),console.log(` pictures: ${s.pictures}`),console.log(` raster images: ${s.rasterImages}`)),t.activeNativeAnimations!=null&&console.log(` native anims: ${t.activeNativeAnimations}`),t.imageLoader){let i=t.imageLoader;console.log(` image cache: ${i.cacheEntries}/${i.cacheMaxEntries} entries, ${re(i.cachePixelBytes)}/${re(i.cachePixelBudget)} (${as(i.cachePixelBytes,i.cachePixelBudget)})`)}t.workerHeap&&console.log(` js heap: ${re(t.workerHeap.usedJSHeapSize)} used / ${re(t.workerHeap.totalJSHeapSize)} total`),t.wasmHeapBytes!=null&&console.log(` canvaskit wasm: ${re(t.wasmHeapBytes)}`)}function cs(e){console.log(" memory:"),Qe("tenant worker",e.tenant),Qe("shell worker",e.shell),Qe("compositor worker",e.compositor),e.hostHeap?(console.log(" host"),console.log(` js heap: ${re(e.hostHeap.usedJSHeapSize)} used / ${re(e.hostHeap.totalJSHeapSize)} total`)):console.log(" host js heap: not available (chrome only)")}function ds(e,t,s){let i=e.indexOf(t);if(i===-1)return s;let c=Number(e[i+1]);return Number.isFinite(c)&&c>0?c:s}async function so(e,t={args:[]}){let s=D(t.args),i=t.args.indexOf("--watch");if(i===-1){let R=await We(e);if(s){A(R);return}cs(R);return}let c=Number(t.args[i+1]),l=Number.isFinite(c)&&c>0?c:60,f=ds(t.args,"--interval",5),p=[],h=Date.now(),$=null;for(s||console.log(` sampling every ${f}s for ${l}s \u2014 deltas per tick:`);;){let R=await We(e),d=(Date.now()-h)/1e3,q=ls(R);if(p.push({tSec:d,counters:q}),!s){let P=[];for(let[E,J]of Object.entries(q)){let U=$&&E in $?J-$[E]:null;if(U===null||U===0)continue;let I=U>0?"+":"-",O=E.endsWith("Bytes")?`${I}${re(Math.abs(U))}`:`${I}${Math.abs(U)}`;P.push(`${E} ${oo(E,J)} (${O})`)}console.log(` t+${d.toFixed(0)}s ${P.length?P.join(" "):$?"no change":Object.entries(q).map(([E,J])=>`${E} ${oo(E,J)}`).join(" ")}`)}if($=q,d>=l)break;await new Promise(P=>setTimeout(P,f*1e3))}let b=p[0],v=p[p.length-1],F=Math.max(v.tSec-b.tSec,.001),N={};for(let R of Object.keys(v.counters))R in b.counters&&(N[R]=(v.counters[R]-b.counters[R])/F);if(s){A({samples:p,perSecond:N,elapsedSec:F});return}console.log(`
434
+ slope over ${F.toFixed(0)}s:`);let j=Object.entries(N).filter(([,R])=>R!==0).sort((R,d)=>Math.abs(d[1])-Math.abs(R[1]));if(j.length===0){console.log(" all counters flat");return}for(let[R,d]of j){let q=R.endsWith("Bytes")?`${re(Math.abs(d))}/s${d<0?" (shrinking)":""}`:`${d>0?"+":""}${d.toFixed(2)}/s`;console.log(` ${R.padEnd(28)}${q}`)}}var Z="<redacted secure text>";function we(e){let t=e?.layout?.spec??e?.spec??null;return!!t?.secureTextEntry&&t.keyboardType!=="visible-password"}function Ze(e,t){return we(t)?Z:e}function et(e){if(!e||!we(e))return e;let t=e.focusedInput;return!t||typeof t!="object"?e:{...e,focusedInput:{...t,secureTextEntry:!0,text:typeof t.text=="string"?Z:t.text}}}function $e(e,t){let s=e.indexOf("--testid");if(s>=0&&e[s+1])return{mode:"testid",value:e[s+1]};let i=e.indexOf("--test-id");if(i>=0&&e[i+1])return{mode:"testid",value:e[i+1]};let c=e.indexOf("--text");if(c>=0&&e[c+1])return{mode:"text",value:e[c+1]};let l=t?.[1];return l&&!l.startsWith("-")&&!Number.isFinite(Number(l))?{mode:"testid",value:l}:null}async function Pe(e,t){let s=JSON.stringify(t.value),i=t.mode==="testid"?`(await t.findByTestId(${s})) || (await t.findById(${s}))`:`await t.findByText(${s})`;return await e.send({type:"evaluate",code:`(async () => {
435
+ const t = window.__sootsimTest
436
+ if (!t) return null
437
+ const n = ${i}
438
+ if (!n || !n.absolutePosition || !n.layout) return null
439
+ const resolved =
440
+ typeof n.nodeId === 'number' && typeof t.resolveTapTarget === 'function'
441
+ ? await t.resolveTapTarget(n.nodeId)
442
+ : null
443
+ const cx =
444
+ typeof resolved?.cx === 'number'
445
+ ? resolved.cx
446
+ : n.absolutePosition.x + (n.layout.width || 0) / 2
447
+ const cy =
448
+ typeof resolved?.cy === 'number'
449
+ ? resolved.cy
450
+ : n.absolutePosition.y + (n.layout.height || 0) / 2
451
+ return {
452
+ x: cx,
453
+ y: cy,
454
+ id: n.id ?? null,
455
+ testID: n.testID ?? null,
456
+ text: ${JSON.stringify(t.mode==="text")} ? ${s} : (n.text ?? n.accessibilityLabel ?? null),
457
+ type: n.type ?? null,
458
+ }
459
+ })()`})??null}async function no(e,t={}){let{nav:s,route:i,keyboard:c,shell:l}=await It(e);if(t.json){console.log(JSON.stringify({shell:l??null,nav:s,route:i,keyboard:c},null,2));return}let f=[];if(l){let p=l.activeApp??l.state??"<none>",h=l.showSwitcher?" (app switcher open)":"",$=typeof l.launchProgress=="number"&&l.launchProgress<.98?` launching (${Math.round(l.launchProgress*100)}%)`:"";f.push(`shell: ${p}${h}${$}`)}else f.push("shell: <unavailable>");if(s){let p=s.transitionPhase!=="idle"?` (${s.transitionPhase}, ${s.activeTransitionCount} active)`:"";if(f.push(`nav: phase=${s.transitionPhase}${p}`),s.screens.length===0)f.push(" <no registered screens \u2014 app may not use react-native-screens>");else for(let h of s.screens){let $=h.isActive?"\u25B6":" ",b=h.routeName?` ${h.routeName}`:"",v=h.headerHeight>0?` header=${h.headerHeight}`:"",F=h.largeTitleState&&h.largeTitleState!=="expanded"?` large-title=${h.largeTitleState}`:"";f.push(` ${$} #${h.id}${b}${v}${F}`)}}else f.push("nav: <runtime not available>");if(f.push(`route: ${i?.currentPath??"<unavailable>"}`),i?.coveringPath&&f.push(`covered: a presented screen (${i.coveringPath}) is above this route`),c&&c.visible){let p=c.spec?.keyboardType??"default",h=c.spec?.returnKeyType??"default";f.push(`keyboard: visible (${p}, return=${h}, mode=${c.mode??"?"})`)}else f.push("keyboard: hidden");console.log(f.join(`
460
+ `))}async function ro(e){let{bridge:t,args:s,positional:i}=e,c=i[1]?Number(i[1])*1e3:3e3,l=s.includes("--strict"),{elapsed:f,settled:p}=await se({bridge:t,maxMs:c,strict:l});console.log(p?` settled in ${f}ms`:` timed out after ${f}ms (may still be animating)`)}async function io(e){let t=e.positional[1]?Number(e.positional[1]):.5;(!Number.isFinite(t)||t<0)&&(console.error(e.inspectUsage("sleep","[seconds]")),process.exit(1)),await oe(t*1e3),console.log(` slept ${t}s`)}async function ao(e){let{bridge:t,args:s,positional:i}=e,c=s.includes("--boxes"),l=i[1]?Number(i[1]):c?50:5,{tree:f}=await lt(t,l,c?{format:"boxes"}:void 0);if(D(s)){A({depth:l,tree:f??null});return}console.log(typeof f=="string"?f:JSON.stringify(f,null,2))}async function lo(e,t={args:[]}){let s=await ct(e);if(D(t.args)){A(s);return}console.log(s.url)}async function co(e){let{wsPort:t,commandTimeoutMs:s,simId:i,simIdSource:c,positional:l}=e,f=l[1]?Number(l[1]):30,p=Math.max(1e3,(Number.isFinite(f)?f:30)*1e3),h=Math.max(1,Math.ceil(p/500));console.log(" waiting for sim reconnect...");let $=await Rt(t,s,i,{attempts:h,simIdSource:c});$||(console.error(" timed out waiting for sim reconnect"),process.exit(1)),$.bridge.close(),Oe({source:"inspect wait",step:{wait:p},summary:`wait ${Math.round(p/1e3)}s`}),console.log(` ready: ${$.count} nodes`)}var uo=new Set(["app-launch","toast","keyboard","screen","flow-step","route","alert","actionsheet","picker","notification","fetch","console","shell","scroll","gesture","text-input","react-commit","animation","reanimated"]);function _e(e,t){let s=e.indexOf(t);if(s>=0&&s+1<e.length)return e[s+1]}function us(e,t){if(!t.filter&&!t.equals)return!0;let s=e.data,i=[];if(s&&typeof s=="object")for(let l of["url","displayUrl","message","name","activeName","path","pathname","title","phase","event","type","kind"]){let f=s[l];typeof f=="string"&&f.length>0&&i.push(f)}let c=i.join(" ");return t.equals?i.some(l=>l===t.equals):t.filter?c.toLowerCase().includes(t.filter.toLowerCase()):!0}async function po(e){let{bridge:t,args:s,positional:i,inspectUsage:c}=e,l=i[1];l||(console.error(c("wait event","<kind> [--max-ms 5000] [--filter <substring>] [--equals <exact>] [--since now|cursor]")),process.exit(1)),uo.has(l)||console.error(` warning: '${l}' is not a known timeline kind \u2014 waiting anyway. known: ${[...uo].sort().join(", ")}`);let f=_e(s,"--max-ms"),p=f&&Number.isFinite(Number(f))?Math.max(100,Number(f)):5e3,h=_e(s,"--filter"),$=_e(s,"--equals"),b=_e(s,"--since")??"now",v=s.includes("--json"),F=Date.now(),N=F+p,j=200,R=F;for(;Date.now()<N;){let q={kinds:[l],since:b==="cursor"?void 0:R,limit:50},P=await t.send({type:"evaluate",code:`(async () => {
461
+ const t = window.SootSim?.bridges?.timeline
462
+ if (!t) return { ok: false, error: 'timeline bridge missing' }
463
+ return { ok: true, result: await t.recent(${JSON.stringify(q)}) }
464
+ })()`});(!P||!P.ok)&&(console.error(` could not query timeline: ${P&&"error"in P?P.error:"unknown"}`),process.exit(1));let E=P.result.events??[];for(let J of E)if(us(J,{filter:h,equals:$})){let U=Date.now()-F;console.log(v?JSON.stringify({found:!0,elapsedMs:U,event:J}):` ${l} event after ${U}ms${h?` (filter: ${h})`:""}${$?` (equals: ${$})`:""}`);return}P.result.watermark&&P.result.watermark>R&&(R=P.result.watermark),await new Promise(J=>setTimeout(J,j))}let d=Date.now()-F;v?console.log(JSON.stringify({found:!1,elapsedMs:d,kind:l,filter:h,equals:$})):console.error(` \u26A0 wait event ${l} timed out after ${d}ms${h?` (filter: ${h})`:""}${$?` (equals: ${$})`:""}`),process.exit(1)}async function mo(e){let{bridge:t,args:s}=e,i=s.includes("--strict"),c=ke(s,3e3),{elapsed:l,settled:f}=await se({bridge:t,maxMs:c,strict:i});f?console.log(` idle in ${l}ms`):(console.error(` \u26A0 wait idle timed out after ${l}ms (may still be animating)`),process.exit(1))}async function fo(e){let{bridge:t,args:s}=e,i=ke(s,2e4),{ready:c,elapsedMs:l,nodes:f,targets:p,liveFrameActive:h,liveFrameChannels:$,flag:b,loadingText:v,externalReady:F,externalError:N,suppressedEntryError:j,errors:R,bridgeError:d}=await gt(t,i,{onProgress(P){console.error(` still waiting after ${P.elapsedMs}ms \u2014 ${qe(P)} (nodes: ${P.nodes}, targets: ${P.targets}, live surfaces: ${P.liveFrameActive?P.liveFrameChannels:0}, errors: ${P.errors})`)}});if(c){let P=i-l,E=Math.max(100,Math.min(1e4,P)),J=await se({bridge:t,maxMs:E,pollMs:32,stablePolls:2});J.settled||(console.error(` \u26A0 wait ready timed out after ${l+J.elapsed}ms \u2014 app mounted but did not settle (nodes: ${f}, targets: ${p})`),process.exit(1)),console.log(` ready in ${l+J.elapsed}ms: ${f} nodes, ${p} targets${h?`, ${$} live surfaces`:""}`);return}let q=qe({externalError:N,loadingText:v,externalReady:F,flag:b,targets:p,suppressedEntryError:j,bridgeError:d});console.error(` \u26A0 wait ready timed out after ${l}ms \u2014 ${q} (nodes: ${f}, targets: ${p}, live surfaces: ${h?$:0}, errors: ${R})`),process.exit(1)}async function go(e){let{bridge:t,args:s,positional:i,inspectUsage:c}=e,l=i[1];l||(console.error(c("wait selector","<testid> [--max-ms 5000] [--gone]")),process.exit(1));let f=s.indexOf("--max-ms"),p=f>=0&&s[f+1]?Math.max(100,Number(s[f+1])):5e3,h=s.includes("--gone"),{found:$,node:b,elapsed:v}=await yt(t,l,p,{gone:h});if(h){$?console.log(` #${l} gone after ${v}ms`):(console.error(` \u26A0 wait selector #${l} --gone timed out after ${v??p}ms (still present)`),process.exit(1));return}if($&&b){let F=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 #${l} in ${v}ms ${N} ${F}`)}else console.error(` \u26A0 wait selector #${l} timed out after ${v??p}ms`),process.exit(1)}function To(e){return e==null?"\u2014":e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}K`:`${(e/1024/1024).toFixed(1)}M`}function Mo(e){return e==null?" \u2026":e<1e3?`${e}ms`.padStart(5):`${(e/1e3).toFixed(2)}s`.padStart(5)}function yo(){process.stderr.write(` the sim is not responding. recover it with:
465
+ rnxsim close --sim <id> # force-close the wedged sim
466
+ rnxsim list # confirm it's gone
467
+ `)}async function ms(e){try{return await e.send({type:"evaluate",code:"1"},{timeoutMs:3e3}),!0}catch{return!1}}async function fs(e,t){try{let s=await e.send({type:"evaluate",code:`(async () => {
468
+ const t = window.__sootsimTest
469
+ if (!t || typeof t.queryAll !== 'function') return []
470
+ try {
471
+ // queryAll is async in render-worker mode (the canonical mode now)
472
+ // because the call has to round-trip the worker \u2014 must await it.
473
+ // a sync result is still handled fine since await on a non-Promise
474
+ // is a no-op.
475
+ const nodes = await t.queryAll({})
476
+ if (!Array.isArray(nodes)) return []
477
+ const out = new Set()
478
+ for (const n of nodes) {
479
+ const id = n && (n.testID || n.id)
480
+ if (typeof id === 'string' && id) out.add(id)
481
+ }
482
+ return Array.from(out)
483
+ } catch {
484
+ return []
485
+ }
486
+ })()`});if(!Array.isArray(s)||s.length===0)return;let i=t.toLowerCase(),c=s.map(l=>({id:l,score:gs(i,l.toLowerCase())})).filter(l=>l.score<i.length+4).sort((l,f)=>l.score-f.score).slice(0,5);if(c.length===0)return;console.error(" similar testIDs:");for(let l of c)console.error(` ${l.id}`)}catch{}}function gs(e,t){if(t===e)return 0;if(t.includes(e))return 1;if(e.includes(t))return 2;let s=0;for(;s<e.length&&s<t.length&&e[s]===t[s];)s+=1;return ys(e,t)-s}function ys(e,t){if(e===t)return 0;if(!e.length)return t.length;if(!t.length)return e.length;let s=new Array(t.length+1),i=new Array(t.length+1);for(let c=0;c<=t.length;c++)s[c]=c;for(let c=1;c<=e.length;c++){i[0]=c;for(let f=1;f<=t.length;f++)i[f]=Math.min(s[f]+1,i[f-1]+1,s[f-1]+(e[c-1]===t[f-1]?0:1));let l=s;s=i,i=l}return s[t.length]}function hs(e){return e.error?"err":e.status==null?" \u2026 ":String(e.status)}function ho(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 bo(e){let t=ae(e.startTs),s=hs(e).padEnd(3),i=e.method.padEnd(5),c=To(e.size).padStart(6),l=Mo(e.durationMs);console.log(` [${t}] ${s} ${i} ${c} ${l} ${e.displayUrl}`),e.error&&console.log(` error: ${e.error}`)}function bs(e){let t=[["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",Mo(e.durationMs).trim()],["size",To(e.size)],["content-type",e.type??"\u2014"]];for(let[s,i]of t)console.log(` ${s.padEnd(13)} ${i}`)}var ws={error:"\x1B[31m",warn:"\x1B[33m",info:"\x1B[36m",debug:"\x1B[35m",log:"\x1B[37m"},wo="\x1B[0m",$s="\x1B[2m";function $o(e,t){let s=ae(e.ts),i=e.level.toUpperCase().padEnd(5),c=e.args.join(" ");if(t){let l=ws[e.level];console.log(` ${$s}[${s}]${wo} ${l}${i}${wo} ${c}`)}else console.log(` [${s}] ${i} ${c}`);if(e.stack&&e.level==="error"){let l=e.stack.split(`
487
+ `).slice(0,5);for(let f of l)console.log(` ${f.trim()}`)}}var xs=120;async function xo(e,t){let s=e.find((F,N)=>e[N-1]==="--id"),i=e.find((F,N)=>e[N-1]==="--text");if(s||i){let F=await t.send({type:"evaluate",code:Et({id:s,text:i})});if(!F)throw new Error(s?`no node with id "${s}"`:`no node matching text "${i}"`);let{x:N,y:j,w:R,h:d}=F;return{x:N,y:j,w:R,h:d}}let c=e.find((F,N)=>e[N-1]==="--area");if(c){let F=c.split(",").map(q=>Number(q.trim()));if(F.length!==4||F.some(q=>!Number.isFinite(q)))throw new Error(`--area expects x,y,w,h (got "${c}")`);let[N,j,R,d]=F;return{x:N,y:j,w:R,h:d}}let l=F=>{let N=e.find((R,d)=>e[d-1]===F);if(N==null)return null;let j=Number(N);return Number.isFinite(j)?j:null},f=l("--x"),p=l("--y"),h=l("--w"),$=l("--h");if(f!=null||p!=null||h!=null||$!=null)return{x:f??0,y:p??0,w:h??1,h:$??1};let v=e.filter((F,N)=>N>0&&!F.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(F=>Number.isFinite(F));if(v.length>=2){let[F,N,j=1,R=1]=v;return{x:F,y:N,w:j,h:R}}return null}function So(e,t){if(!t||typeof t!="object")return;console.log(""),console.log(` render profile \u2014 ${e} (per painted frame):`),console.log(` node visits: ${t.nodeVisitsPerFrame}`),console.log(` boundaries: ${t.recordsPerFrame} records (${t.avgBoundaryRecordMs}ms) / ${t.replaysPerFrame} replays`);let s=[t.boundaryRecordsInvalidated?`invalidated ${t.boundaryRecordsInvalidated}`:"",t.boundaryRecordsOrigin?`moved ${t.boundaryRecordsOrigin}`:"",t.boundaryRecordsScheme?`first-record ${t.boundaryRecordsScheme}`:""].filter(Boolean).join(" \xB7 ");s&&console.log(` why recorded: ${s}`),t.prewarmRecords&&console.log(` pre-recorded: ${t.prewarmRecords} boundaries at idle (${Number(t.prewarmRecordMs).toFixed(1)}ms total)`),console.log(` raster tier: ${t.rasterPromotionsPerFrame} promotions / ${t.rasterBlitsPerFrame} blits`);let i=[t.rasterRejectRebuild?`rebuild ${t.rasterRejectRebuild}`:"",t.rasterRejectLinear?`linear ${t.rasterRejectLinear}`:"",t.rasterRejectAnimated?`animated ${t.rasterRejectAnimated}`:"",t.rasterRejectTransform?`transform ${t.rasterRejectTransform}`:"",t.rasterRejectOpacity?`opacity ${t.rasterRejectOpacity}`:"",t.rasterRejectCacheable?`cacheable ${t.rasterRejectCacheable}`:"",t.rasterRejectBounds?`bounds ${t.rasterRejectBounds}`:"",t.rasterRejectPixels?`pixels ${t.rasterRejectPixels}`:"",t.rasterRejectBudget?`budget ${t.rasterRejectBudget}`:"",t.rasterWarming?`warming ${t.rasterWarming}`:""].filter(Boolean).join(" \xB7 ");i&&(console.log(` raster skips: ${i} (total across run)`),t.rasterRejectAlsoBlocked&&console.log(` ${"".padEnd(12)} ${t.rasterRejectAlsoBlocked} of those also fail a later gate \u2014 widening the named gate cannot promote them`)),console.log(` blur: ${t.avgBlurMs}ms`),(t.glassDownsampleActive||t.glassBackdropCacheMisses)&&console.log(` glass: ${t.glassDownsampleFactor}x downsample (${t.glassDownsampledDraws} draws) \xB7 cache ${t.glassBackdropCacheHits} hits / ${t.glassBackdropCacheMisses} misses / ${t.glassBackdropCacheInvalidations} invalidations`),console.log(` draw calls: text ${t.textDrawsPerFrame} \xB7 image ${t.imageDrawsPerFrame} \xB7 path ${t.pathDrawsPerFrame} \xB7 saveLayer ${t.saveLayersPerFrame}`)}function vo(e){let t=e.avgMs>0?(1e3/e.avgMs).toFixed(1):"?",s=e.jank&&typeof e.jank=="object"?e.jank:null;if(console.log(` shell frame profile:
488
+ `),s){let h=(Array.isArray(s.compositor)?s.compositor:[]).reduce(($,b)=>$+(b.jankPaints??0),0);console.log(` health: ${s.detected?"jank or cadence gaps observed":"no jank or cadence gaps observed"} \xB7 shell ${s.shell?.jankFrames??0} \xB7 compositor ${h} \xB7 host clock gaps ${s.hostGaps??0}`),console.log(" series: independent worker clocks, no per-frame pairing")}if(console.log(` painted frames: ${e.frames}${e.skippedFrames?` (+${e.skippedFrames} skipped idle ticks)`:""}`),console.log(` shell work avg: ${e.avgMs}ms (${t} fps) \xB7 worst observed ${e.maxMs}ms`),console.log(` shell p50/95/99:${e.p50} / ${e.p95} / ${e.p99} ms`),s){console.log(` shell jank: ${s.shell?.jankFrames??0}/${s.shell?.sampledFrames??0} (${s.shell?.jankPct??0}%) >16.67ms \xB7 max ${s.shell?.maxMs??0}ms`);for(let p of Array.isArray(s.compositor)?s.compositor:[])console.log(` ${String(p.surfaceId).padEnd(12)} ${p.jankPaints}/${p.sampledPaints} compositor paints (${p.jankPct}%) >16.67ms \xB7 max ${p.maxMs}ms`)}else console.log(` jank: ${e.jankFrames} frames (${e.jankPct}%) >16.67ms`);console.log(` avg per frame: overlay ${e.avgOverlayMs}ms \xB7 aux ${e.avgAuxMs}ms \xB7 layout ${e.avgLayoutMs}ms`);let i=e.cadence;i&&typeof i=="object"&&(console.log(""),console.log(` cadence (frame delivery, ${i.vsyncTicks} vsync ticks):`),console.log(` display clock: ${i.displayHz}hz \xB7 host rAF interval p50 ${i.hostIntervalP50} / p95 ${i.hostIntervalP95} / max ${i.hostIntervalMax} ms${i.hostGaps?` \xB7 ${i.hostGaps} gaps >1.5x (host rAF starved)`:""}`),console.log(` delivery lag: p50 ${i.deliveryLagP50} / p95 ${i.deliveryLagP95} / max ${i.deliveryLagMax} ms (vsync postMessage \u2192 shell receipt)`),console.log(` paint interval: p50 ${i.paintIntervalP50} / p95 ${i.paintIntervalP95} / max ${i.paintIntervalMax} ms${i.idleBreaks?` \xB7 ${i.idleBreaks} idle breaks excluded`:""}`));let c=e.compositorCadence;if(c&&typeof c=="object"){console.log(` compositor rAF: p50 ${c.p50} / p95 ${c.p95} / max ${c.max} ms \xB7 ${c.gaps} gaps >1.5x`);let p=(h,$)=>{$?.count&&console.log(` ${h}: ${$.count} samples \xB7 p50 ${$.p50.toFixed(2)} / p95 ${$.p95.toFixed(2)} / max ${$.max.toFixed(2)} ms`)};p("engine-empty rAF",c.phases?.uninterruptedEngineEmpty),p("rAF with CanvasKit flush",c.phases?.withCanvaskitFlush),p("rAF after CanvasKit flush",c.phases?.afterCanvaskitFlush),p("CanvasKit submission",c.canvaskitSubmission)}let l=Array.isArray(e.auxSurfaces)?e.auxSurfaces:[];if(l.length>0){console.log(""),console.log(" surfaces (last 100 frames):");for(let p of l)console.log(` ${String(p.surfaceId).padEnd(10)} ${String(p.frames).padStart(4)} paints avg ${p.avgMs}ms (layout ${p.avgLayoutMs}, render ${p.avgRenderMs}, flush ${p.avgFlushMs}) max ${p.maxMs}ms`),typeof p.gpuCacheBytes=="number"&&typeof p.gpuCacheLimitBytes=="number"&&console.log(` ${"".padEnd(10)} gpu cache ${(p.gpuCacheBytes/1024/1024).toFixed(1)}MB/${(p.gpuCacheLimitBytes/1024/1024).toFixed(1)}MB`)}So("shell worker",e.renderProfile),So("compositor worker",e.compositorRenderProfile);let f=Array.isArray(e.worstFrames)?e.worstFrames:[];if(f.length>0){console.log(""),console.log(" worst observations (shell and compositor series are unpaired):");for(let p of f){if(p.source==="compositor"){console.log(` ${String(p.totalMs).padStart(7)}ms compositor ${p.surfaceId} paint ${p.paint} \xB7 layout ${p.layoutMs} \xB7 render ${p.renderMs} \xB7 flush ${p.flushMs}`);continue}let h=(p.auxSurfaces??[]).map($=>`${$.surfaceId} ${$.totalMs}ms (layout ${$.layoutMs}, render ${$.renderMs})`).join(" \xB7 ");console.log(` ${String(p.totalMs).padStart(7)}ms overlay ${p.overlayMs} \xB7 aux ${p.auxMs} \xB7 layout ${p.layoutMs}${h?` [${h}]`:""}`)}}}async function Ee(e,t,s){let i=Date.now()+t,c=await ue(e,t);for(;;){if(s(c))return{settled:!0,state:c};if(Date.now()>=i)return{settled:!1,state:c};await oe(16),c=await ue(e)}}async function ot(e){return e.send({type:"evaluate",code:`(async () => {
489
+ const kb = window.__sootsimKeyboard
490
+ const test = window.__sootsimTest
491
+ if (!kb) return { error: 'keyboard bridge not available' }
492
+ const layout = typeof kb.getLayout === 'function' ? kb.getLayout() : null
493
+ const secureTextEntry =
494
+ !!layout?.spec?.secureTextEntry && layout?.spec?.keyboardType !== 'visible-password'
495
+ const visible = kb.isVisible()
496
+ const mode = kb.getMode()
497
+ let focused = null
498
+ if (test && typeof test.getFocusedNode === 'function') {
499
+ try {
500
+ focused = await test.getFocusedNode()
501
+ } catch {}
502
+ }
503
+ let runtimeSnapshot = null
504
+ if (test && typeof test.getFocusKeyboardSnapshot === 'function') {
505
+ try {
506
+ runtimeSnapshot = await test.getFocusKeyboardSnapshot()
507
+ } catch {}
508
+ }
509
+ return {
510
+ visible,
511
+ mode,
512
+ layout,
513
+ hostedEditorFocused:
514
+ typeof kb.hasHostedEditorFocus === 'function' && kb.hasHostedEditorFocus(),
515
+ focusedInput: focused ? {
516
+ nodeId: focused.nodeId ?? null,
517
+ testID: focused.testID || null,
518
+ id: focused.id || null,
519
+ placeholder: focused.placeholder || null,
520
+ secureTextEntry,
521
+ text: secureTextEntry ? ${JSON.stringify(Z)} : (focused.text || null),
522
+ } : null,
523
+ phase: runtimeSnapshot?.keyboard?.phase ?? null,
524
+ frame: runtimeSnapshot?.keyboard?.frame ?? null,
525
+ focusedRect: runtimeSnapshot?.focused?.rect ?? null,
526
+ }
527
+ })()`}).then(t=>et(t))}function Ss(e,t,s){if(!e.visible)return!1;let i=e.focusedInput;return!(t&&i&&!(i.testID===t||i.id===t)||s!==null&&we(e)!==s)}async function vs(e,t=600,s={}){let i=Date.now()+t;for(;Date.now()<=i;){let c=await ot(e);if(Ss(c,s.targetId??null,s.secureTextEntry??null))return c;await oe(30)}return ot(e)}async function Ae(e,t){let s=await ot(e);if(s.visible&&(s.focusedInput||s.hostedEditorFocused))return s;s.visible&&(console.error(` ${t} requires a focused editable control. the iOS keyboard is visible, but no input owns focus.`),process.exit(1)),console.error(` ${t} requires the iOS keyboard to be visible. focus an input first with rnxsim do tap-id/tap-text or rnxsim do type-into.`),process.exit(1)}async function ko(e,t,s){return t==="appearance"?e.send({type:"evaluate",code:`(async () => {
528
+ const requested = ${JSON.stringify(s??"toggle")}
529
+ // the engine owns toggle + auto resolution (settingsStore is the single
530
+ // source of truth). never infer the current scheme client-side \u2014 the old
531
+ // documentElement '#333333' sniff is never set in embedded / shell-chrome
532
+ // contexts, so 'toggle' read 'light' forever and stuck on the boot scheme.
533
+ window.postMessage({ type: 'contrast-action', action: 'set-appearance', value: requested }, '*')
534
+ // let the engine's message handler apply + publish window.__sootsimColorScheme
535
+ await new Promise((r) => setTimeout(r, 60))
536
+ const applied = window.__sootsimColorScheme?.resolved
537
+ ?? (window.matchMedia?.('(prefers-color-scheme: dark)')?.matches ? 'dark' : 'light')
538
+ const setting = window.__sootsimColorScheme?.setting ?? requested
539
+ return { ok: true, requested, setting, applied }
540
+ })()`}):t==="lock"?e.send({type:"evaluate",code:`(async () => {
541
+ const toggleLock = window.SootSim?.bridges?.mainShell?.toggleLock
542
+ if (typeof toggleLock !== 'function') {
543
+ throw new Error('rnx mainShell.toggleLock bridge unavailable')
544
+ }
545
+ await toggleLock()
546
+ return { ok: true, action: 'lock' }
547
+ })()`}):e.send({type:"evaluate",code:`(async () => {
548
+ window.dispatchEvent(new CustomEvent('sootsim:shake'))
549
+ return { ok: true, action: 'shake' }
550
+ })()`})}function ks(e){let t={Enter:"return",NumpadEnter:"return",Backspace:"delete",Delete:"delete",Space:"space",ShiftLeft:"shift",ShiftRight:"shift"};if(t[e])return t[e];let s=e.match(/^Digit([0-9])$/);if(s)return s[1];let i=e.match(/^Key([A-Z])$/);return i?i[1].toLowerCase():null}function Is(e){if(typeof e!="string")return null;let t=e.replace(/\s+/g," ").trim();return t?t.slice(0,80):null}function No(...e){for(let t of e){if(typeof t!="string")continue;let s=t.trim();if(s)return s}return null}function Ts(e){let t=e.indexOf("--node-id");if(t<0)return null;let s=e[t+1];if(!s)return null;let i=Number(s);return Number.isInteger(i)&&i>0?i:null}async function W(e,t,s){let i=Oe({source:e,step:t,summary:s});i.active&&(i.replaced?console.error(` draft: replaced unkept action "${i.replaced.summary}" \u2014 \`maestro keep\` commits one action at a time`):console.error(" draft: action pending \u2014 `rnxsim maestro keep` to commit"))}function Io(e,t,s){if(!s||s.hit===!1)return null;let i=No(s.responderTestID,s.testID);if(i)return{step:{tapOn:{id:i}},summary:`tap #${i}`};let c=Is(s.text);return c?{step:{tapOn:c},summary:`tap "${c}"`}:{step:{tapAtCoords:{x:e,y:t}},summary:`tap @${Math.round(e)},${Math.round(t)}`}}function tt(e,t,s){let i=No(t?.testID,t?.id);return i?{step:{tapOn:{id:i}},summary:`tap #${i}`}:s==="id"?{step:{tapOn:{id:e}},summary:`tap #${e}`}:{step:{tapOn:e},summary:`tap "${e}"`}}async function Pr(e,t){let s=e[0]==="get"||e[0]==="do"||e[0]==="debug"||e[0]==="wait"?e[0]:null,i=s?e.slice(1):e,c=Mt(i,{port:t.port,commandTimeoutMs:t.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"]}),l=c.positional,f=l[0],p=s==="get"||s==="do"||s==="debug"||s==="wait"?s:"inspect",h=typeof i[0]=="string"&&st.has(i[0]),$=h?i[0]:null,b=x=>t.internalPerfCommand&&x==="perf"?`rnxsim perf ${t.internalPerfCommand}`:h&&x===i[0]?`rnxsim ${x}`:`rnxsim ${p} ${x}`,v=(x,o)=>` usage: ${b(x)}${o?` ${o}`:""}`;if(!f||e.includes("--help")||e.includes("-h")){let x={bridgePort:7668,defaultShellUrl:rt};if(p==="do"||p==="get"||p==="debug"||p==="wait"){let r=De(p,x);r&&(console.log(`${r}
551
+ `),process.exit(0))}if($==="shell"){let r=Be("shell",x);r&&(console.log(`${r}
552
+ `),process.exit(0))}let o=Be("inspect",x),n=["do","get","debug","wait"].map(r=>De(r,x)).filter(r=>r!=null).join(`
553
+
554
+ `);console.log(`${o??""}
555
+
556
+ ${n}
557
+ `),process.exit(0)}let F=c.wsPort,N=c.simId,j=c.simIdSource,R=c.commandTimeoutMs;if(p==="get"&&f==="diagnosis"){let x=i.indexOf("diagnosis"),o=x>=0?[...i.slice(0,x),...i.slice(x+1)]:i,{runDiagnose:n}=await import("./diagnose-HMQXJE5N.js"),r=await n(["recent",...o],t);process.exitCode=r;return}if(p==="do"&&f==="scan"){let{runCamera:x}=await import("./camera-VL73YIKP.js");await x(i,{port:t.port});return}if(f==="list"&&i.some(x=>x==="--drivers"||x==="-D")){let{buildDriverListRows:x}=await import("./drivers-LDECZGP2.js"),o=x();console.log(` available drivers (${o.length}):
558
+ `);let n=Math.max(...o.map(a=>a.id.length),6),r=Math.max(...o.map(a=>a.kind.length),4);for(let a of o){let u=a.available?"\u2713":"\u2717",m=a.id.padEnd(n),g=a.kind.padEnd(r);console.log(` ${u} ${m} ${g} ${a.description}`),a.available&&a.detail?console.log(` ${a.detail}`):!a.available&&a.reason&&console.log(` unavailable: ${a.reason}`)}return}let d=Nt(c),q=N||"default",P=new Set(["errors","warnings","requests","js","eval","reload","globals","perf","storage-clear","list","wait","sleep"]),E=200;function J(x){let o=x.replace(/\s+/g," ").trim();if(!o)return"";if(/^<(!doctype html|html|\?xml)|<body[\s>]/i.test(o)){let r=/<title[^>]*>([^<]+)<\/title>/i.exec(x)?.[1]?.trim(),a=/<body[^>]*>([\s\S]*?)<\//i.exec(x)?.[1]?.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().slice(0,80),u=r||a||"html error page";return`<html ${x.length}B> "${u}" (body elided \u2014 add --json for the full payload)`}return o.length<=E?o:`${o.slice(0,E)}\u2026 (+${o.length-E} more bytes)`}function U(x){let o=x.displayUrl||x.url;return x.status!=null?`${x.method} ${o} -> ${x.status}${x.statusText?` ${x.statusText}`:""}`:x.error?`${x.method} ${o} -> ${x.error}`:`${x.method} ${o}`}async function I(x){let o=fe()?400:200;try{let{settled:n,elapsed:r}=await se({bridge:x,maxMs:o,pollMs:32,stablePolls:2});n||process.stderr.write(` \u26A0 auto-wait timed out after ${r??o}ms \u2014 next command may see mid-animation state. use \`rnxsim do settle\` for a longer wait.
559
+ `)}catch{}}function O(x,o){if(o.result?.reason==="offscreen"){let{x:n,y:r,screen:a}=o.result;console.error(` tap failed: ${x} resolved to (${Math.round(n)},${Math.round(r)}), outside the ${a?.width}x${a?.height} screen`),console.error(" the node exists but is scrolled out of view \u2014 scroll it on-screen first (rnxsim do scroll / swipe), then tap.");return}console.error(` tap failed: ${x} 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 H(){try{return await d.send({type:"evaluate",code:`(() => ({
560
+ console: ${Ie},
561
+ requests: window.__sootsimTest?.getRequestCounts?.() || null,
562
+ }))()`})||{console:null,requests:null}}catch{return{console:null,requests:null}}}async function K(x={}){let o=x.counts!==void 0?x.counts:await X(d,"getRequestCounts");if(!o||typeof o!="object")return;let n=Math.max(0,Number(o.failed)||0);if(n===0||!x.includeTail&&!ze("requests",q,String(n))||(console.log(`
563
+ network: ${n} failed request${n===1?"":"s"}`),console.log(` inspect: ${b("requests")} 5`),!x.includeTail))return;let r=await X(d,"getFailedRequests",5);if(!(!Array.isArray(r)||r.length===0)){console.log(`
564
+ recent failed requests:
565
+ `);for(let a of r){let u=ae(a.timestamp);console.log(` [${u}] ${U(a)}`),a.responseBody?console.log(` ${J(a.responseBody)}`):a.error&&console.log(` ${a.error}`)}}}function ee(x){for(let o of x){let n=o.title?` (\u201C${o.title}\u201D)`:"";console.error(`
566
+ note: ${o.label} is open${n} \u2014 taps/drags hit it, not the app`)}}async function te(x={}){let o=x.counts!==void 0?x.counts:await d.send({type:"evaluate",code:Ie});if(!o||typeof o!="object")return;let n=o,r=Math.max(0,Number(n.errors)||0),a=Math.max(0,Number(n.warnings)||0);if(r===0&&a===0||!x.includeTail&&!ze("console",q,`${r}:${a}`))return;let u=[];if(r>0&&u.push(`${r} console error${r===1?"":"s"}`),a>0&&u.push(`${a} console warning${a===1?"":"s"}`),console.error(`
567
+ console: ${u.join(", ")}`),console.error(` inspect: ${b("errors")} 5`),a>0&&console.error(` inspect: ${b("warnings")} 5`),!x.includeTail||r===0)return;let m=await ge(d,5);if(!(!Array.isArray(m)||m.length===0)){console.error(`
568
+ recent console errors:
569
+ `);for(let g of m){let w=ae(g.timestamp),y=Array.isArray(g.args)?g.args.map(k=>typeof k=="object"?JSON.stringify(k):String(k)).join(" "):String(g);console.error(` [${w}] ${y}`)}}}let ie=["console","fetch","toast","alert","notification","screen","app-launch","keyboard","route","actionsheet","picker","shell","scroll","gesture","text-input","animation","reanimated"];async function xe(x){let o=nt(),n=null;try{n=await Ot(x,`(() => {
570
+ const tl = window.SootSim && window.SootSim.bridges && window.SootSim.bridges.timeline
571
+ if (!tl || typeof tl.summary !== 'function') return null
572
+ const cursorKey = ${JSON.stringify(o)}
573
+ const summary = tl.summary({ sinceCursor: cursorKey })
574
+ let consoleSplit = null
575
+ if (summary && summary.byKind && summary.byKind.console) {
576
+ const events = tl.recent({ sinceCursor: cursorKey, kinds: 'console', limit: 100000 }).events
577
+ consoleSplit = { error: 0, warn: 0 }
578
+ for (const ev of events) {
579
+ const lvl = ev && ev.data && ev.data.level
580
+ if (lvl === 'error') consoleSplit.error++
581
+ else if (lvl === 'warn') consoleSplit.warn++
582
+ }
583
+ }
584
+ return summary ? { summary, consoleSplit } : null
585
+ })()`)}catch{return}if(!n||!n.summary||!n.summary.total)return;let r=n.summary.byKind??{},a=[],u=new Set;for(let m of ie){let g=r[m];if(g)if(u.add(m),m==="console"&&n.consoleSplit){let{error:w,warn:y}=n.consoleSplit;w>0&&a.push(`${w} error${w===1?"":"s"}`),y>0&&a.push(`${y} warning${y===1?"":"s"}`)}else a.push(`${g} ${m}${g===1?"":"s"}`)}for(let[m,g]of Object.entries(r))!u.has(m)&&g&&a.push(`${g} ${m}${g===1?"":"s"}`);if(a.length!==0&&(console.error(`
586
+ since last: ${a.join(" \xB7 ")} \u2014 rnxsim what-happened`),n.summary.lastAt))try{await ce(x,"SootSim.bridges.timeline.cursorAdvance",o,n.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"]),le=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"]),Se=(e.includes("--verbose")||e.includes("-v"))&&!e.includes("--json");p==="do"&&f==="shell"&&(console.error(" `rnxsim do shell` was removed. use `rnxsim shell ...` instead."),process.exit(1)),C.has(f)&&await Ft(d),le.has(f)&&await pe(d,{verbose:Se});try{let x=C.has(f)?await vt(d):[];switch(f){case"list":{Tt(c.wsPort),await to({bridge:d,simId:N,args:i});break}case"tree":{await ao({bridge:d,args:i,positional:l});break}case"a11y":{let o=await mt(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):
587
+ `);for(let n of o){let r=[];if(r.push(`[${n.role}]`),n.label){let a=n.label.length>50?n.label.slice(0,47)+"...":n.label;r.push(`"${a}"`)}if(n.hint&&r.push(`(hint: "${n.hint}")`),n.testID&&r.push(`#${n.testID}`),n.state){let a=[];n.state.disabled&&a.push("disabled"),n.state.selected&&a.push("selected"),n.state.checked===!0&&a.push("checked"),n.state.checked==="mixed"&&a.push("mixed"),n.state.busy&&a.push("busy"),n.state.expanded===!0&&a.push("expanded"),n.state.expanded===!1&&a.push("collapsed"),a.length&&r.push(`{${a.join(", ")}}`)}n.position&&r.push(`@(${n.position.x},${n.position.y})`),n.size&&r.push(`${n.size.w}x${n.size.h}`),console.log(" "+r.join(" "))}}break}case"find":{await Qt({bridge:d,args:e,effectiveArgs:i,positional:l,inspectUsage:v});break}case"count":{await Xt(d,{args:i});break}case"keyboard":{await eo(d,{json:e.includes("--json")});break}case"screens":{await no(d,{json:e.includes("--json")});break}case"memory":{await so(d,{args:i});break}case"wait":{await co({wsPort:F,commandTimeoutMs:R,simId:N,simIdSource:j,positional:l});break}case"sleep":{await io({positional:l,inspectUsage:v});break}case"settle":{await ro({bridge:d,args:e,positional:l});break}case"ready":{await fo({bridge:d,args:e});break}case"idle":{await mo({bridge:d,args:e,positional:l});break}case"selector":{await go({bridge:d,args:e,positional:l,inspectUsage:v});break}case"event":{await po({bridge:d,args:e,positional:l,inspectUsage:v});break}case"layout":{let o=l[1];if(!o){await Zt({bridge:d,args:i});break}let n=await d.send({type:"evaluate",code:`(async () => await window.__sootsimTest.getLayout(${JSON.stringify(o)}))()`});console.log(JSON.stringify(n,null,2));break}case"capture":case"screenshot":{let n=e.find((w,y)=>e[y-1]==="--output")||"/tmp/sootsim-inspect.png",r=await xo(e,d),a={type:"screenshot"};r&&(a.crop=r);let m=(await d.send(a)).replace(/^data:image\/png;base64,/,"");r&&console.log(` area: x=${r.x} y=${r.y} w=${r.w} h=${r.h}`),(await import("fs")).writeFileSync(n,Buffer.from(m,"base64")),console.log(` saved: ${n}`);break}case"sample-color":{let o=await xo(e,d);o||(console.error(v("sample-color","<x> <y> [w] [h] | --id <testID> | --text <text>")),console.error(" samples an averaged color from the canvas. coords are logical rnx units."),process.exit(1));let n=await d.send({type:"evaluate",code:At(o)});if(e.includes("--json"))console.log(JSON.stringify(n,null,2));else{let{r,g:a,b:u,a:m,hex:g,samples:w}=n,y=o.w===1&&o.h===1?`@(${o.x},${o.y})`:`@(${o.x},${o.y}) ${o.w}x${o.h}`;console.log(` ${g} rgba(${r}, ${a}, ${u}, ${m}) ${y} ${w} samples`)}break}case"node":{let o=l[1];o||(console.error(v("node","<matcher>")),console.error(" resolves testID, id, then text \u2014 dumps full node info as JSON"),process.exit(1));let n=await d.send({type:"evaluate",code:`(async () => {
588
+ const t = window.__sootsimTest
589
+ const q = ${JSON.stringify(o)}
590
+ let node = null
591
+ let via = null
592
+ if (t.findByTestId) { node = await t.findByTestId(q); if (node) via = 'testID' }
593
+ if (!node && t.findById) { node = await t.findById(q); if (node) via = 'id' }
594
+ if (!node && t.findByText) { node = await t.findByText(q); if (node) via = 'text' }
595
+ if (!node) return { matcher: q, found: false }
596
+
597
+ // read the resolved transform (if any) off the style \u2014 useful
598
+ // because canvas nodes often animate via transform and describe
599
+ // output strips that.
600
+ const transform =
601
+ node.style && Array.isArray(node.style.transform)
602
+ ? node.style.transform
603
+ : node.style && node.style.transform
604
+ ? node.style.transform
605
+ : null
606
+
607
+ // parent chain \u2014 walk up from the node so the JSON dump is
608
+ // self-describing.
609
+ const parentChain = []
610
+ const root = window.__sootsimRoot
611
+ if (root && node.id != null) {
612
+ const findPath = (n, targetId, path) => {
613
+ if (!n) return null
614
+ if (n.id === targetId) return path
615
+ if (n.children) {
616
+ for (const child of n.children) {
617
+ const nextPath = [
618
+ ...path,
619
+ {
620
+ type: n.type || 'view',
621
+ testID: n.props?.testID || null,
622
+ text: n.text || null,
623
+ },
624
+ ]
625
+ const found = findPath(child, targetId, nextPath)
626
+ if (found) return found
627
+ }
628
+ }
629
+ return null
630
+ }
631
+ const chain = findPath(root, node.id, [])
632
+ if (chain) parentChain.push(...chain)
633
+ }
634
+
635
+ return {
636
+ matcher: q,
637
+ found: true,
638
+ resolvedVia: via,
639
+ node,
640
+ transform,
641
+ parentChain,
642
+ }
643
+ })()`});console.log(JSON.stringify(n,null,2));break}case"tap":{let o=Number(l[1]),n=Number(l[2]),r=$e(e,l);if(r){let m=await be(d,{agent:fe(),textFallback:r.mode==="text"?r.value:void 0,resolve:async()=>{let y=await Pe(d,r);return y?{cx:y.x,cy:y.y,match:{id:r.mode==="testid"?r.value:y.id??null,testID:r.mode==="testid"?r.value:y.testID??null,text:r.mode==="text"?r.value:y.text??null,type:y.type??null},target:{id:y.id??null,testID:y.testID??null,text:y.text??null,type:y.type??null}}:null}}),g=m.payload;(!g||typeof g.cx!="number")&&(console.error(` not found: ${r.value}`),r.mode==="testid"&&Q("wait-selector-for-missing-testid",r.value),process.exit(1)),me(m.result)||(O(`${r.mode} "${r.value}"`,m),process.exit(1));let w=Io(g.cx,g.cy,m.result);w&&await W("inspect tap",w.step,w.summary),console.log(JSON.stringify({...m.attempts>1?{attempts:m.attempts}:{},...m.result},null,2));break}(!Number.isFinite(o)||!Number.isFinite(n))&&(console.error(v("tap","<testid> | <x> <y> | --testid <id> | --text <t>")),process.exit(1));let a=await Ut(d,o,n),u=Io(o,n,a);u&&await W("inspect tap",u.step,u.summary),console.log(JSON.stringify(a,null,2));break}case"drag":case"swipe":{let o=Number(l[1]),n=Number(l[2]),r=Number(l[3]),a=Number(l[4]),u=f==="swipe"?10:12,m=f==="swipe"?8:16,g=l[5]?Number(l[5]):u,w=l[6]?Number(l[6]):m;(!Number.isFinite(o)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(a)||!Number.isFinite(g)||!Number.isFinite(w))&&(console.error(v(f,"<x1> <y1> <x2> <y2> [steps] [stepMs]")),process.exit(1));let y=await d.send({type:"evaluate",code:`(async () => {
644
+ const interact = window.__sootsimInteract
645
+ if (!interact?.drag) return { ok: false, reason: 'no interact.drag' }
646
+ const value = await interact.drag(${o}, ${n}, ${r}, ${a}, ${Math.max(1,Math.round(g))}, ${Math.max(0,Math.round(w))})
647
+ return { ok: !!value, value }
648
+ })()`});if(y?.ok){let k=Math.max(1,Math.round(Math.max(1,g)*Math.max(0,w)));await W(`inspect ${f}`,{swipe:{start:`${o}, ${n}`,end:`${r}, ${a}`,duration:k}},`${f} ${o},${n} -> ${r},${a}`)}console.log(JSON.stringify(y,null,2));break}case"pinch":{let o=Number(l[1]),n=Number(l[2]),r=Number(l[3]),a=Number(l[4]),u=Number(l[5]),m=Number(l[6]),g=Number(l[7]),w=Number(l[8]),y=l[9]?Number(l[9]):12,k=l[10]?Number(l[10]):16;(!Number.isFinite(o)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(a)||!Number.isFinite(u)||!Number.isFinite(m)||!Number.isFinite(g)||!Number.isFinite(w)||!Number.isFinite(y)||!Number.isFinite(k))&&(console.error(v("pinch","<x1> <y1> <x2> <y2> <x1'> <y1'> <x2'> <y2'> [steps] [stepMs]")),process.exit(1));let L=await d.send({type:"evaluate",code:`(async () => {
649
+ const interact = window.__sootsimInteract
650
+ if (!interact?.pinch) return { ok: false, reason: 'no interact.pinch' }
651
+ const value = await interact.pinch(${o}, ${n}, ${r}, ${a}, ${u}, ${m}, ${g}, ${w}, ${Math.max(1,Math.round(y))}, ${Math.max(0,Math.round(k))})
652
+ return { ok: !!value, value }
653
+ })()`});L?.ok&&await W("inspect pinch",{pinch:{from:[o,n,r,a],to:[u,m,g,w],steps:Math.max(1,Math.round(y)),stepMs:Math.max(0,Math.round(k))}},`pinch (${o},${n}) (${r},${a}) -> (${u},${m}) (${g},${w})`),console.log(JSON.stringify(L,null,2));break}case"tap-text":{let o=l[1];o||(console.error(v("tap-text","<text>")),process.exit(1));let n=z=>{let B=e.indexOf(z);return B>=0&&B+1<e.length?e[B+1]:null},r=z=>e.includes(z),a=n("--nth")??n("--index"),u=a!==null?Number(a):null;u!==null&&!Number.isFinite(u)&&(console.error(` --nth/--index requires an integer, got: ${a}`),process.exit(1));let m=n("--within"),g=n("--role"),w=r("--exact"),y=r("--first"),k=n("--min-y"),L=n("--max-y"),V=n("--min-x"),G=n("--max-x");for(let[z,B]of[["--min-y",k],["--max-y",L],["--min-x",V],["--max-x",G]])B!==null&&!Number.isFinite(Number(B))&&(console.error(` ${z} requires a number, got: ${B}`),process.exit(1));let Y=e.indexOf("--near"),_=null;if(Y>=0){let z=Number(e[Y+1]),B=Number(e[Y+2]);(!Number.isFinite(z)||!Number.isFinite(B))&&(console.error(" --near requires two numbers: --near <x> <y>"),process.exit(1)),_={x:z,y:B}}let S={exact:w,role:g,within:m,minX:V!==null?Number(V):null,maxX:G!==null?Number(G):null,minY:k!==null?Number(k):null,maxY:L!==null?Number(L):null,near:_,nth:u,first:y},T=await Yt(d,o,S,{agent:fe()}),M=T.payload;if(M?.error==="bridge-not-ready"&&(console.error(" rnxsim test bridge not ready"),process.exit(1)),M?.ambiguous){let z=M.candidates;console.error(` ambiguous: ${M.total} matches for "${o}"`);for(let B of z){let ve=B.abs?`@(${Math.round(B.abs.x)},${Math.round(B.abs.y)})`:"",Fo=B.layout?` ${B.layout.width}x${B.layout.height}`:"",Oo=B.testID?` #${B.testID}`:"",Ro=B.text?` "${B.text}"`:"",Po=B.ancestorTestIDs.length>0?` within ${B.ancestorTestIDs.slice(0,3).map(_o=>`#${_o}`).join(" > ")}`:"";console.error(` [${B.idx}] <${B.type}>${Ro}${Oo} ${ve}${Fo}${Po}`)}M.total>z.length&&console.error(` ... and ${M.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)}M?.nthOutOfRange&&(console.error(` not found: nth ${M.nth} of ${M.total} match${M.total===1?"":"es"} for "${o}"`),process.exit(1)),(!M||typeof M.cx!="number")&&(console.error(` not found: ${o}`),process.exit(1)),me(T.result)||(O(`text "${o}"`,T),process.exit(1));let ne=tt(o,{id:M.target?.id??null,testID:M.target?.testID??null,type:M.target?.type??null,cx:M.cx,cy:M.cy},"text");await W("inspect tap-text",ne.step,ne.summary),console.log(JSON.stringify({matched:M.match,tapped:{nodeId:M.target?.nodeId??null,id:M.target?.id??null,testID:M.target?.testID??null,type:M.target?.type??null,cx:M.cx,cy:M.cy},...M.strategy&&M.strategy!=="matched-node"?{strategy:M.strategy}:{},...M.total>1||u!==null?{nth:{index:M.idx,total:M.total}}:{},...T.attempts>1?{attempts:T.attempts}:{},result:T.result},null,2));break}case"tap-best":{let o=l[1];o||(console.error(v("tap-best","<query>")),process.exit(1));let n=await zt(d,o,{agent:fe()}),r=n.payload;r||(console.error(` tap-best: no testID or visible text matched "${o}". try \`rnxsim find --interactive-targets\` to list candidates.`),process.exit(1)),"error"in r&&(console.error(` ${r.error}`),process.exit(1)),r.strategy==="none"&&(console.error(` tap-best: no testID or visible text matched "${o}". try \`rnxsim find --interactive-targets\` to list candidates.`),process.exit(1));let a=r.node;me(n.result)||(O(`best "${o}"`,n),process.exit(1));let u=tt(o,{id:a.id,testID:a.testID,type:a.type,cx:r.cx,cy:r.cy},r.strategy==="testid"?"id":"text");await W("inspect tap-best",u.step,u.summary),console.log(JSON.stringify({matched:{strategy:r.strategy,nodeId:a.nodeId,id:a.id,testID:a.testID,type:a.type,text:a.text},tapped:{cx:r.cx,cy:r.cy},...n.attempts>1?{attempts:n.attempts}:{},result:n.result},null,2));break}case"tap-id":{let o=l[1];o||(console.error(v("tap-id","<id>")),process.exit(1));let n=await Gt(d,o,{agent:fe()}),r=n.payload;(!r||typeof r.cx!="number")&&(console.error(` not found: ${o}`),await fs(d,o),process.exit(1)),me(n.result)||(O(`id "${o}"`,n),process.exit(1));let a=tt(o,{id:r.target?.id??null,testID:r.target?.testID??null,type:r.target?.type??null,cx:r.cx,cy:r.cy},"id");await W("inspect tap-id",a.step,a.summary),console.log(JSON.stringify({matched:r.match,tapped:{nodeId:r.target?.nodeId??null,id:r.target?.id??null,testID:r.target?.testID??null,type:r.target?.type??null,cx:r.cx,cy:r.cy},...r.strategy&&r.strategy!=="matched-node"?{strategy:r.strategy}:{},...n.attempts>1?{attempts:n.attempts}:{},result:n.result},null,2));break}case"type-into":{let o=l[1],n=l.slice(2).join(" ");(!o||!n)&&(console.error(v("type-into","<id> <text>")),process.exit(1));let r=JSON.stringify(o),a=await d.send({type:"evaluate",code:`(async () => {
654
+ const t = window.__sootsimTest
655
+ if (!t) return null
656
+ const n = await (t.findByTestId(${r}) || t.findById(${r}))
657
+ if (!n || !n.absolutePosition || !n.layout) return null
658
+ return {
659
+ cx: n.absolutePosition.x + (n.layout.width || 0) / 2,
660
+ cy: n.absolutePosition.y + (n.layout.height || 0) / 2,
661
+ id: n.id,
662
+ testID: n.testID,
663
+ type: n.type,
664
+ isTextInput: !!n.isTextInput,
665
+ secureTextEntry: !!n.secureTextEntry,
666
+ placeholder: n.placeholder || null,
667
+ }
668
+ })()`});(!a||typeof a.cx!="number")&&(console.error(` not found: ${o}`),process.exit(1)),a.isTextInput||console.error(` warning: ${o} is not a text input (isTextInput: false)`);let u=await d.send({type:"tap",x:a.cx,y:a.cy,target:{id:a.id??o,testID:a.testID??o,text:null,type:a.type??null}}),m=a.secureTextEntry===!0,g=await vs(d,1e3,{targetId:o,secureTextEntry:m});g.visible||(console.error(` keyboard did not open after tapping ${o}`),process.exit(1));let w=g.focusedInput;w&&(w.testID===o||w.id===o||(console.error(` focus routing mismatch after tap: requested ${JSON.stringify(o)} but focus is on ${JSON.stringify(w.testID??w.id??null)}. did the tap land on an outer Pressable wrapper?`),process.exit(1))),await d.send({type:"keyboard",action:"type",text:n});let y=m||we(g),k=y?Z:Ze(n,g),L=y&&g.focusedInput?{...g.focusedInput,secureTextEntry:!0,text:typeof g.focusedInput.text=="string"?Z:g.focusedInput.text}:g.focusedInput??null;await W("inspect type-into",{tapOn:{id:o},inputText:k},k===Z?`type-into #${o} ${Z}`:`type-into #${o} ${JSON.stringify(n)}`),console.log(JSON.stringify({target:o,isTextInput:a.isTextInput,secureTextEntry:y,keyboardOpened:g.visible??u?.keyboardOpened??!1,focusedInput:L,typed:k},null,2));break}case"type":{let o=l.slice(1).join(" ");o||(console.error(v("type","<text>")),process.exit(1));let n=await Ae(d,"type");await d.send({type:"keyboard",action:"type",text:o});let r=Ze(o,n);await W("inspect type",{inputText:r},r===Z?`type ${Z}`:`type ${JSON.stringify(o)}`),console.log(r===Z?` typed: ${Z}`:` typed: ${JSON.stringify(o)}`);break}case"key":{let o=l[1];o||(console.error(v("key","<name>")),process.exit(1)),await Ae(d,"key"),await d.send({type:"keyboard",action:"press",text:o}),await W("inspect key",{pressKey:o},`key ${o}`),console.log(` pressed: ${o}`);break}case"key-sequence":{let o=l.slice(1);o.length===0&&(console.error(v("key-sequence","<key> [<key> ...]")),process.exit(1)),await Ae(d,"key-sequence");for(let n of o)await d.send({type:"keyboard",action:"press",text:n});await W("inspect key-sequence",{pressKey:o.join(" ")},`key-sequence ${o.join(" ")}`),console.log(` pressed: ${o.join(", ")}`);break}case"keycode":{let o=l.slice(1);o.length===0&&(console.error(v("keycode","<code> [<code> ...]")),process.exit(1));let n=o.map(a=>({code:a,key:ks(a)})),r=n.filter(a=>!a.key);r.length>0&&(console.error(` unsupported keycode(s): ${r.map(a=>a.code).join(", ")}`),process.exit(1)),await Ae(d,"keycode");for(let a of n)await d.send({type:"keyboard",action:"press",text:a.key});await W("inspect keycode",{pressKey:n.map(a=>a.key).join(" ")},`keycode ${o.join(" ")}`),console.log(` pressed: ${o.join(", ")}`);break}case"dispatch":{let o=l[1];o||(console.error(v("dispatch","<char>")),process.exit(1)),await d.send({type:"keyboard",action:"dispatchKey",text:o}),await W("inspect dispatch",{dispatchKey:o},`dispatch ${JSON.stringify(o)}`),console.log(` dispatched: ${o}`);break}case"dismiss":{await d.send({type:"keyboard",action:"dismiss"}),await W("inspect dismiss",{hideKeyboard:!0},"dismiss keyboard"),console.log(" keyboard dismissed");break}case"double-tap":{let o=Number(l[1]),n=Number(l[2]),r=$e(e,l);if(r){let g=await Pe(d,r);g||(console.error(` not found: ${r.value}`),r.mode==="testid"&&Q("wait-selector-for-missing-testid",r.value),process.exit(1)),o=g.x,n=g.y}let a=l[3]?Number(l[3]):80;(!Number.isFinite(o)||!Number.isFinite(n)||!Number.isFinite(a))&&(console.error(v("double-tap","<testid> | <x> <y> [gapMs] | --testid <id>")),process.exit(1));let u=Math.max(0,Math.round(a)),m=await d.send({type:"evaluate",code:`(async () => {
669
+ const interact = window.__sootsimInteract
670
+ if (interact?.doubleTap) {
671
+ return {
672
+ ok: !!(await interact.doubleTap(${o}, ${n}, ${u})),
673
+ gapMs: ${u},
674
+ }
675
+ }
676
+ if (!interact?.tap) {
677
+ return { ok: false, reason: 'no interact.tap', gapMs: ${u} }
678
+ }
679
+ const first = await interact.tap(${o}, ${n})
680
+ if (!first || first.hit === false) {
681
+ return { ok: false, reason: 'first tap missed', gapMs: ${u}, first }
682
+ }
683
+ await new Promise((resolve) => setTimeout(resolve, ${u}))
684
+ const second = await interact.tap(${o}, ${n})
685
+ return {
686
+ ok: !!second && second.hit !== false,
687
+ gapMs: ${u},
688
+ first,
689
+ second,
690
+ }
691
+ })()`});m?.ok&&await W("inspect double-tap",{doubleTapAtCoords:{x:o,y:n,gapMs:u}},`double-tap @${o},${n}`),console.log(JSON.stringify(m,null,2));break}case"long-press":{let o=Number(l[1]),n=Number(l[2]),r=$e(e,l),a=null;if(r){let y=await Pe(d,r);y||(console.error(` not found: ${r.value}`),r.mode==="testid"&&Q("wait-selector-for-missing-testid",r.value),process.exit(1)),o=y.x,n=y.y,a={id:y.id??null,testID:y.testID??null,text:y.text??null,type:y.type??null}}let u=r?l[1]:l[3],m=u?Number(u):600;(!Number.isFinite(o)||!Number.isFinite(n)||!Number.isFinite(m))&&(console.error(v("long-press","<testid> | <x> <y> [durationMs] | --testid <id>")),process.exit(1));let g=Math.max(0,Math.round(m)),w=await d.send({type:"longPress",x:o,y:n,durationMs:g,target:a});w?.ok&&await W("inspect long-press",{tapAtCoords:{x:o,y:n}},`long-press @${o},${n}`),console.log(JSON.stringify(w,null,2));break}case"touch":{let o=l[1],n=Number(l[2]),r=Number(l[3]),a=l[4]?Number(l[4]):999,u=o==="down"?"touchDown":o==="move"?"touchMove":o==="up"?"touchUp":o==="cancel"?"touchCancel":null;u||(console.error(v("touch","<down|move|up|cancel> <x> <y> [pointerId]")),process.exit(1)),o!=="cancel"&&(!Number.isFinite(n)||!Number.isFinite(r))&&(console.error(v("touch","<down|move|up|cancel> <x> <y> [pointerId]")),process.exit(1));let m=o==="down"?"tap":o==="move"?"move":null,g=m&&Number.isFinite(n)&&Number.isFinite(r)?`window.dispatchEvent(new CustomEvent('sootsim:agentAction', { detail: { type: '${m}', x: ${n}, y: ${r} } }));`:"",w=await d.send({type:"evaluate",code:`(async () => {
692
+ ${g}
693
+ const interact = window.__sootsimInteract
694
+ if (!interact?.${u}) return { ok: false, reason: 'no interact.${u}' }
695
+ const value = ${o==="cancel"?`await interact.${u}(${Math.max(1,Math.round(a))})`:`await interact.${u}(${n}, ${r}, ${Math.max(1,Math.round(a))})`}
696
+ return { ok: !!value, value }
697
+ })()`});w?.ok&&o!=="cancel"&&await W("inspect touch",{tapAtCoords:{x:n,y:r}},`touch ${o} @${n},${r}`),console.log(JSON.stringify(w,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"],n=l[1],r=l[2]?Number(l[2]):220;(!n||!Number.isFinite(r))&&(console.error(v("gesture","<preset> [durationMs]")),console.error(` presets: ${o.join(", ")}`),process.exit(1)),o.includes(n)||(console.error(` unknown gesture preset: ${n}`),console.error(` presets: ${o.join(", ")}`),process.exit(1));let a=await d.send({type:"evaluate",code:`(async () => {
698
+ const spec = globalThis.__sootsimDeviceSpec || {}
699
+ return {
700
+ width: spec.width || window.innerWidth || 393,
701
+ height: spec.height || window.innerHeight || 852,
702
+ statusBarHeight: spec.statusBarHeight || 0,
703
+ homeIndicatorHeight: spec.homeIndicatorHeight || 0,
704
+ }
705
+ })()`}),u=Number(a?.width)||393,m=Number(a?.height)||852,g=Number(a?.statusBarHeight)||0,w=Number(a?.homeIndicatorHeight)||0,y=Math.round(u/2),k=Math.round(m/2),L=Math.max(24,g+18),V=Math.max(24,w+18),G=18,Y=Math.min(220,Math.round(m*.24)),_=Math.min(180,Math.round(u*.32)),S=y,T=k,M=y,ne=k;switch(n){case"scroll-up":T=k+Math.round(Y/2),ne=k-Math.round(Y/2);break;case"scroll-down":T=k-Math.round(Y/2),ne=k+Math.round(Y/2);break;case"scroll-left":S=y+Math.round(_/2),M=y-Math.round(_/2);break;case"scroll-right":S=y-Math.round(_/2),M=y+Math.round(_/2);break;case"swipe-from-left-edge":S=G,T=k,M=Math.min(u-G,G+_);break;case"swipe-from-right-edge":S=u-G,T=k,M=Math.max(G,u-G-_);break;case"swipe-from-top-edge":S=y,T=L,ne=Math.min(m-V,L+Y);break;case"swipe-from-bottom-edge":S=y,T=m-V,ne=Math.max(L,m-V-Y);break}let z=Math.max(8,Math.round(r/16)),B=Math.max(1,Math.round(r/z)),ve=await d.send({type:"evaluate",code:`(async () => {
706
+ const interact = window.__sootsimInteract
707
+ if (!interact?.drag) return { ok: false, reason: 'no interact.drag' }
708
+ const value = await interact.drag(${S}, ${T}, ${M}, ${ne}, ${z}, ${B})
709
+ return { ok: !!value, value }
710
+ })()`});ve?.ok&&await W("inspect gesture",{swipe:{start:`${S}, ${T}`,end:`${M}, ${ne}`,duration:Math.max(1,Math.round(r))}},`gesture ${n}`),console.log(JSON.stringify({preset:n,from:{x:S,y:T},to:{x:M,y:ne},result:ve},null,2));break}case"scroll":{let o=$e(e),n=Ts(e),r=o?.mode==="testid"?o.value:n==null?l[1]:null,a=o||n!=null?1:2,u=Number(l[a]),m=Number(l[a+1]);(!r&&n==null||!Number.isFinite(u)||!Number.isFinite(m))&&(console.error(v("scroll","<id> <x> <y> | --testid <id> <x> <y> | --node-id <nodeId> <x> <y>")),process.exit(1));let g=await d.send({type:"evaluate",code:`(async () => {
711
+ const t = window.__sootsimTest
712
+ if (!t) return null
713
+ const n = ${n!=null?`await t.inspectByNodeId(${JSON.stringify(n)})`:`await t.findByTestId(${JSON.stringify(r)})
714
+ || await t.findById(${JSON.stringify(r)})`}
715
+ if (!n || !n.absolutePosition || !n.layout) return null
716
+ return {
717
+ cx: n.absolutePosition.x + (n.layout.width || 0) / 2,
718
+ cy: n.absolutePosition.y + (n.layout.height || 0) / 2,
719
+ }
720
+ })()`}),w=await X(d,"scrollTo",n!=null?{nodeId:n}:r,u,m,!1);if(w?.ok){let y=n!=null?`node ${n}`:`#${r}`;await W("inspect scroll",{scrollTo:{...n!=null?{nodeId:n}:{id:r},x:u,y:m}},`scroll ${y} -> ${u},${m}`)}console.log(JSON.stringify({...w,...g?{at:{x:g.cx,y:g.cy}}:{}},null,2));break}case"state":{let o=l[1];if(s==="get"&&!o){let r=await X(d,"getRuntimeState"),a=await d.send({type:"evaluate",code:Ie});if(r&&typeof r=="object"&&r.diagnostics&&(r.diagnostics.errors=a?.errors??0,r.diagnostics.warnings=a?.warnings??0),r&&typeof r=="object"&&r.shell==null)try{let u=await ue(d);u&&(r.shell=u)}catch{}console.log(JSON.stringify(r,null,2));break}if(!o||o==="--help"||o==="-h"){console.log(`
721
+ ${b("state")} \u2014 dump raw runtime state
722
+
723
+ subcommands:
724
+ shell dump shell transition/layout state
725
+ worker dump render-worker host/animation state
726
+ keyboard dump keyboard visibility, mode, and focused input
727
+ ownership dump surface ownership + pointerOnSurface delivery stats
728
+ worklets dump tenant + shell worklet-runtime slot/handler counts
729
+ scroll-input dump shell-owned scroll gesture and momentum state
730
+ scroll-mirror dump shell scroll registry entries and offsets
731
+ node <id> dump raw node info by id or testID
732
+ scroll <id> dump scroll metrics and runtime state
733
+ scroll-hit <x> <y> dump the nearest scroll ancestor at coordinates
734
+ hit <x> <y> dump the hit-test ancestry at coordinates
735
+ gesture <x> <y> dump gesture routing/debug info at coordinates
736
+ gesture-seam dump shell-hosted gesture recognizer state/events
737
+
738
+ examples:
739
+ ${b("state")} shell
740
+ ${b("state")} worker
741
+ ${b("state")} keyboard
742
+ ${b("state")} ownership
743
+ ${b("state")} worklets
744
+ ${b("state")} scroll-input
745
+ ${b("state")} scroll-mirror
746
+ ${b("state")} node photos
747
+ ${b("state")} scroll feed
748
+ ${b("state")} scroll-hit 360 420
749
+ ${b("state")} hit 200 720
750
+ `);break}let n;switch(o){case"shell":n=await ue(d,500);break;case"worker":n=await ce(d,"__sootsimRenderHost.queryStats");break;case"ownership":n=await d.send({type:"evaluate",code:`(() => {
751
+ const h = window.__sootsimRenderHost
752
+ if (!h || typeof h.getOwnershipSnapshot !== 'function') {
753
+ return { error: 'getOwnershipSnapshot not available' }
754
+ }
755
+ return h.getOwnershipSnapshot()
756
+ })()`});break;case"keyboard":n=await d.send({type:"evaluate",code:`(async () => {
757
+ const kb = window.__sootsimKeyboard
758
+ const test = window.__sootsimTest
759
+ if (!kb) return { error: 'keyboard bridge not available' }
760
+ const layout = typeof kb.getLayout === 'function' ? kb.getLayout() : null
761
+ const secureTextEntry =
762
+ !!layout?.spec?.secureTextEntry && layout?.spec?.keyboardType !== 'visible-password'
763
+ const visible = kb.isVisible()
764
+ const mode = kb.getMode()
765
+ let focused = null
766
+ if (test && typeof test.getFocusedNode === 'function') {
767
+ try {
768
+ focused = await test.getFocusedNode()
769
+ } catch {}
770
+ }
771
+ return {
772
+ visible,
773
+ mode,
774
+ layout,
775
+ focusedInput: focused ? {
776
+ nodeId: focused.nodeId ?? null,
777
+ testID: focused.testID || null,
778
+ id: focused.id || null,
779
+ placeholder: focused.placeholder || null,
780
+ secureTextEntry,
781
+ text: secureTextEntry ? ${JSON.stringify(Z)} : (focused.text || null),
782
+ } : null,
783
+ }
784
+ })()`}),n=et(n);break;case"node":{let r=l[2];r||(console.error(` usage: ${b("state")} node <id>`),process.exit(1)),n=await X(d,"findByTestId",r)||await X(d,"findById",r);break}case"scroll":{let r=l[2];r||(console.error(` usage: ${b("state")} scroll <id>`),process.exit(1)),n=await X(d,"getScrollState",r);break}case"scroll-hit":{let r=Number(l[2]),a=Number(l[3]);(!Number.isFinite(r)||!Number.isFinite(a))&&(console.error(` usage: ${b("state")} scroll-hit <x> <y>`),process.exit(1)),n=await X(d,"getScrollStateAt",r,a);break}case"hit":{let r=Number(l[2]),a=Number(l[3]);(!Number.isFinite(r)||!Number.isFinite(a))&&(console.error(` usage: ${b("state")} hit <x> <y>`),process.exit(1)),n=await X(d,"debugHitAt",r,a);break}case"gesture":{let r=Number(l[2]),a=Number(l[3]);(!Number.isFinite(r)||!Number.isFinite(a))&&(console.error(` usage: ${b("state")} gesture <x> <y>`),process.exit(1)),n=await X(d,"debugGestureAt",r,a);break}case"gesture-seam":n=await ce(d,"SootSim.bridges.mainShell.callTestBridge","getShellGestureSeamDebug");break;case"worklets":{let[r,a]=await Promise.all([X(d,"getWorkletSlotStats"),ce(d,"SootSim.bridges.mainShell.callTestBridge","getWorkletSlotStats")]);n={tenant:r,shell:a};break}case"scroll-input":n=await ce(d,"SootSim.bridges.mainShell.callTestBridge","getShellScrollInputDebug");break;case"scroll-mirror":n=await ce(d,"SootSim.bridges.mainShell.callTestBridge","getScrollMirrorDebug");break;default:console.error(` unknown state subcommand: ${o}`),process.exit(1)}console.log(JSON.stringify(n,null,2));break}case"shell":{let o=l[1];if(!o||o==="--help"||o==="-h"){console.log(`
785
+ ${b("shell")} \u2014 run built-in shell commands
786
+
787
+ subcommands:
788
+ launch <appId> [waitMs] [--clear-state]
789
+ launch app and wait for settled shell state
790
+ home [waitMs] go home and wait for settled shell state
791
+ switcher [waitMs] open switcher and wait for settled shell state
792
+ open-card <appId> [waitMs]
793
+ open a specific switcher card and wait for app settle
794
+ appearance <light|dark|auto|toggle>
795
+ update simulator appearance
796
+ lock toggle device lock state
797
+ shake trigger the simulator shake gesture
798
+
799
+ examples:
800
+ ${b("shell")} launch photos
801
+ ${b("shell")} launch rn --clear-state
802
+ ${b("shell")} launch photos 1500
803
+ ${b("shell")} home 500
804
+ ${b("shell")} switcher 800
805
+ ${b("shell")} open-card clock 800
806
+ ${b("shell")} appearance dark
807
+ ${b("shell")} lock
808
+ `);break}let n=o==="launch"||o==="open-card"||o==="home"||o==="switcher",r=o==="launch"||o==="open-card"?l[3]:l[2],a=r?Number(r):350;n&&(!Number.isFinite(a)||a<0)&&(console.error(v("shell",o==="launch"||o==="open-card"?"<launch|open-card> <appId> [settleMs]":"<home|switcher> [settleMs]")),process.exit(1));let u=!1,m=!1,g=null,w=e.includes("--clear-state");if(o==="launch"){let y=l[2];y||(console.error(v("shell","launch <appId> [settleMs] [--clear-state]")),process.exit(1)),w&&await d.send({type:"evaluate",code:Je(!0)}),u=!!await ye(d,"launchApp",a,y),{settled:m,state:g}=await Ee(d,Math.round(a),k=>!!k&&k.state==="app"&&k.activeApp===y&&k.showSwitcher===!1&&k.switcherPhase==="idle"&&typeof k.launchProgress=="number"&&k.launchProgress>=.98),u&&await W("inspect shell launch",w?{launchApp:{clearState:!0}}:{launchApp:{}},w?"launch app (clear state)":"launch app")}else if(o==="home")u=!!await ye(d,"goHome",a),{settled:m,state:g}=await Ee(d,Math.round(a),y=>!!y&&y.state==="home"&&y.activeApp==null&&y.showSwitcher===!1&&y.switcherPhase==="idle"&&typeof y.launchProgress=="number"&&y.launchProgress>=.98);else if(o==="switcher")u=!!await ye(d,"openSwitcher",a),{settled:m,state:g}=await Ee(d,Math.round(a),y=>!!y&&y.state==="app"&&y.showSwitcher===!0&&y.switcherPhase==="idle"&&typeof y.zoomLevel=="number"&&Math.abs(y.zoomLevel)<=.02&&typeof y.horizontalZoom=="number"&&Math.abs(y.horizontalZoom)<=.02),m&&(await oe(xs),g=await ue(d));else if(o==="open-card"){let y=l[2];y||(console.error(v("shell","open-card <appId> [settleMs]")),process.exit(1)),u=!!await ye(d,"openSwitcherCard",a,y),{settled:m,state:g}=await Ee(d,Math.round(a),k=>!!k&&k.state==="app"&&k.activeApp===y&&k.showSwitcher===!1&&k.switcherPhase==="idle"&&typeof k.zoomLevel=="number"&&k.zoomLevel>=.98&&typeof k.horizontalZoom=="number"&&k.horizontalZoom>=.98),u&&await W("inspect shell open-card",{openSwitcherCard:{appId:y}},`open switcher card ${y}`)}else if(o==="appearance"){let y=l[2];(!y||!["light","dark","auto","toggle"].includes(y))&&(console.error(v("shell","appearance <light|dark|auto|toggle>")),process.exit(1));let k=await ko(d,"appearance",y);if(u=!!k?.ok,g={appearance:k},u){let L=k?.applied??y;console.log(` appearance: ${L}`)}}else if(o==="lock"||o==="shake"){let y=await ko(d,o);u=!!y?.ok,g={[o]:y}}else console.error(` unknown shell subcommand: ${o}`),process.exit(1);console.log(JSON.stringify({ok:u,settled:m,state:g},null,2));break}case"url":{await lo(d,{args:i});break}case"reload":{let r=!1,a=!1;try{await d.send({type:"evaluate",code:"window.__sootsimConsole?.clear()"});let g=await d.send({type:"evaluate",code:`;(async () => {
809
+ // in-place guest reload is only valid while the page still runs
810
+ // the engine build the server would serve NOW. the shell dev
811
+ // server has no HMR client, so a long-lived sim tab otherwise
812
+ // keeps a stale engine forever while builds churn underneath it.
813
+ // compare the inlined engine manifest against a fresh fetch of
814
+ // this page's html; any drift means the whole page must reload.
815
+ let engineStale = false
816
+ try {
817
+ const loaded = document.getElementById('__sootsim-engine-manifest')?.textContent
818
+ if (loaded) {
819
+ const res = await fetch(location.href, { cache: 'no-store' })
820
+ const html = await res.text()
821
+ const m = html.match(/<script[^>]*id="__sootsim-engine-manifest"[^>]*>([^<]*)<\\/script>/)
822
+ if (m && m[1] !== loaded) engineStale = true
823
+ }
824
+ } catch {}
825
+ const reloadExternalApp = window.SootSim?.bridges?.hotRemount?.reloadExternalApp
826
+ if (!engineStale && typeof reloadExternalApp === 'function') {
827
+ reloadExternalApp()
828
+ return { kind: 'external-app' }
829
+ }
830
+ window.location.reload()
831
+ return { kind: 'page', engineStale }
832
+ })()`});a=!!g&&g.kind==="external-app",r=!0,g&&g.engineStale&&console.log(" engine build changed since page load \u2014 full page reload")}catch{}console.log(" reloading...");let u=d,m=null;if(a)m=await Me(d,{timeoutMs:1e4,errorGraceMs:3e3});else{r&&await oe(300);let w=await Pt(F,R,N,{timeoutMs:3e4,simIdSource:j});w?(u=w,m=await Me(w,{timeoutMs:3e4,errorGraceMs:3e3})):(console.log(" \u26A0 reload: bridge never reconnected within 30000ms"),u=null)}if(m)if(m.ready){let g=m.source==="nodes-fallback"?" (no ready signal, node-count fallback)":"";console.log(` ready in ${m.elapsedMs}ms: ${m.nodes} nodes${g}`)}else if(m.source==="error-bail")console.log(` \u26A0 reload bailed after ${m.elapsedMs}ms: ${m.errors} console error(s), ready signal never fired`);else{let g=ho(m);console.log(` \u26A0 reload timed out after ${m.elapsedMs}ms \u2014 ${g} (nodes: ${m.nodes}, targets: ${m.targets}, errors: ${m.errors})`)}if(u)try{let g=await ge(u,10);if(u!==d&&u.close(),Array.isArray(g)&&g.length>0){console.log(`
833
+ \u26A0 ${g.length} error(s) during mount:
834
+ `);for(let w of g){let y=w.args.map(k=>typeof k=="object"?JSON.stringify(k):k).join(" ");if(console.log(` ${y}`),w.stack){let k=w.stack.split(`
835
+ `).slice(0,2);for(let L of k)console.log(` ${L.trim()}`)}}}}catch{}m&&!m.ready&&(process.exitCode=1);break}case"storage-clear":{if(await Le(d),await d.send({type:"evaluate",code:Je(!0)})!==!0){D(i)?A({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 a=await Me(d,{timeoutMs:1e4,errorGraceMs:3e3});if(D(i)){A({cleared:!0,ready:a.ready,reload:a}),a.ready||(process.exitCode=1);break}if(a.ready){let u=a.source==="nodes-fallback"?" (no ready signal, node-count fallback)":"";console.log(` cleared tenant storage; ready in ${a.elapsedMs}ms: ${a.nodes} nodes${u}`)}else if(a.source==="error-bail")console.log(` \u26A0 storage clear reloaded but bailed after ${a.elapsedMs}ms: ${a.errors} console error(s), ready signal never fired`);else{let u=ho(a);console.log(` \u26A0 storage clear reloaded but timed out after ${a.elapsedMs}ms \u2014 ${u} (nodes: ${a.nodes}, targets: ${a.targets}, errors: ${a.errors})`)}try{let u=await ge(d,10);if(Array.isArray(u)&&u.length>0){console.log(`
836
+ \u26A0 ${u.length} error(s) during mount:
837
+ `);for(let m of u){let g=m.args.map(w=>typeof w=="object"?JSON.stringify(w):w).join(" ");if(console.log(` ${g}`),m.stack){let w=m.stack.split(`
838
+ `).slice(0,2);for(let y of w)console.log(` ${y.trim()}`)}}}}catch{}a.ready||(process.exitCode=1);break}case"eval":case"js":{let o=l.slice(1).join(" ");if(o||(console.error(v("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)),e.includes("--tenant")){let m=l.slice(1).filter(w=>w!=="--tenant").join(" "),g=await d.send({type:"evaluate",code:`(async () => SootSim.bridges.test.evalInTenant(${JSON.stringify(m)}))()`});console.log(JSON.stringify(g,null,2));break}let n=o;n.startsWith("(async")||(n=`(async () => ${n})()`);let r=await d.send({type:"evaluate",code:n});console.log(JSON.stringify(r,null,2));let a=o.toLowerCase(),u=[];(a.includes("sootsim:gohome")||a.includes("gohome"))&&u.push("rnxsim shell home"),(a.includes("sootsim:appswitcher")||a.includes("appswitcher"))&&u.push("rnxsim shell switcher"),(a.includes("keyboard.isvisible")||a.includes("keyboard.getmode"))&&u.push("rnxsim debug state keyboard"),a.includes("interact.tap")&&u.push("rnxsim do tap <x> <y>"),a.includes("keyboard.type")&&u.push("rnxsim do type <text>"),(a.includes("keyboard.press")||a.includes("keyboard.dispatchkey"))&&u.push("rnxsim do key <name>"),a.includes("keyboard.dismiss")&&u.push("rnxsim do dismiss"),a.includes("dumptree")&&u.push("rnxsim get tree"),a.includes("dumpaccessibilitytree")&&u.push("rnxsim get a11y"),a.includes("getnodecount")&&u.push("rnxsim get count"),a.includes("findbytext")&&u.push("rnxsim find <text>"),(a.includes("findbytestid")||a.includes("findbyid"))&&u.push("rnxsim find --testid <id>"),a.includes("document.hidden")&&u.push("rnxsim debug state keyboard (includes tab health)"),u.length>0&&Q("prefer-cli-over-eval",u);break}case"globals":{let o=await d.send({type:"evaluate",code:`(async () => {
839
+ const globals = {}
840
+
841
+ // test bridge (proxy in worker mode)
842
+ const testMethods = [
843
+ 'findById', 'findByTestId', 'findByText', 'findByLabel', 'findByRole',
844
+ 'findAllByRole', 'findByA11yState', 'findAllByA11yState', 'findByHint',
845
+ 'findPressable', 'getStyle', 'getLayout', 'getAbsolutePosition', 'isVisible',
846
+ 'queryAll', 'dumpTree', 'dumpAccessibilityTree', 'getNodeCount', 'getShellState',
847
+ 'getScrollState', 'getScrollStateAt', 'scrollTo', 'waitForTree',
848
+ 'waitForScreenTransitions', 'debugByText', 'debugByTestId', 'debugHitAt',
849
+ 'debugGestureAt'
850
+ ]
851
+ globals['test (\u2192 __sootsimTest)'] = testMethods
852
+
853
+ // debug
854
+ if (window.__sootsimDebug) {
855
+ globals['debug (\u2192 __sootsimDebug)'] = Object.keys(window.__sootsimDebug)
856
+ }
857
+
858
+ // interact
859
+ if (window.__sootsimInteract) {
860
+ globals['interact (\u2192 __sootsimInteract)'] = Object.keys(window.__sootsimInteract)
861
+ }
862
+
863
+ // keyboard
864
+ if (window.__sootsimKeyboard) {
865
+ globals['keyboard (\u2192 __sootsimKeyboard)'] = Object.keys(window.__sootsimKeyboard)
866
+ }
867
+
868
+ // other globals
869
+ globals['other'] = [
870
+ 'root (\u2192 __sootsimRoot) - live node tree',
871
+ 'render() (\u2192 __sootsimForceRender) - force re-render'
872
+ ]
873
+
874
+ return globals
875
+ })()`});console.log(` rnx JS API:
876
+ `);for(let[n,r]of Object.entries(o)){console.log(` ${n}:`);for(let a of r)console.log(` .${a}`);console.log("")}console.log(` use: ${b("js")} <expression>`),console.log(` example: ${b("js")} test.findByText("Sign in")`);break}case"describe":{await Vt({bridge:d,args:e,positional:l});break}case"perf":{p==="debug"&&!t.internalPerfCommand&&(console.error(" `rnxsim debug perf` was removed. use `rnxsim perf shell ...`."),process.exit(1));let o=l[1];if(t.internalPerfCommand==="scroll"){if(!o||o==="--help"||o==="-h"){console.log(`
877
+ ${b("perf")} <start|stop> [options]
878
+
879
+ records per-frame scroll offsets from the tenant worker, shell worker,
880
+ and compositor worker. timestamps use the shared wall clock, while frame
881
+ sequences remain separate because the workers do not share a frame id.
882
+
883
+ options:
884
+ --limit <n> maximum samples retained per layer (default 6000)
885
+ --json emit every per-frame sample on stop
886
+
887
+ examples:
888
+ ${b("perf")} start
889
+ # ... perform consecutive swipes ...
890
+ ${b("perf")} stop
891
+ ${b("perf")} stop --json
892
+ `);break}if(o==="start"){let n=i.find((u,m)=>i[m-1]==="--limit"),r=n===void 0?6e3:Number(n);(!Number.isFinite(r)||r<120)&&(console.error(" error: --limit must be a number of at least 120"),process.exit(1));let a=await d.send({type:"evaluate",code:`(async () => {
893
+ const perf = window.SootSim?.bridges?.scrollPerf
894
+ if (!perf) return { error: 'scroll performance profile unavailable' }
895
+ await perf.start(${Math.floor(r)})
896
+ return { started: true }
897
+ })()`});a?.error&&(console.error(` error: ${a.error}`),process.exit(1)),console.log(` scroll profiling started: perform consecutive swipes, then run '${b("perf")} stop'`);break}if(o==="stop"){let n=await d.send({type:"evaluate",code:`(async () => {
898
+ const perf = window.SootSim?.bridges?.scrollPerf
899
+ if (!perf) return { error: 'scroll performance profile unavailable' }
900
+ return await perf.stop()
901
+ })()`});n?.error&&(console.error(` error: ${n.error}`),process.exit(1));let r=n;if(D(i)){A(r);break}console.log(` scroll performance trace:
902
+ `),console.log(` duration: ${r.stoppedAt-r.startedAt}ms (worker series are timestamp-aligned, not frame-paired)`),console.log(` samples: tenant ${r.layers.tenant.length} \xB7 shell ${r.layers.shell.length} \xB7 compositor ${r.layers.compositor.length}`),console.log(""),console.log(" offset and phase changes (--json includes every per-frame sample):"),console.log(" t(ms) layer surface node offsetY slotY phase paint");let a=[];for(let u of Object.values(r.layers)){let m=new Map;for(let g of u){let w=`${g.surfaceId}:${g.nodeId}`,y=`${g.offsetY}:${g.slotY??""}:${g.phase??""}`;m.get(w)!==y&&(m.set(w,y),a.push(g))}}a.sort((u,m)=>u.t-m.t||u.seq-m.seq);for(let u of a)console.log(` ${String(u.t-r.startedAt).padStart(5)} ${u.layer.padEnd(10)} ${u.surfaceId.padEnd(8)} ${String(u.nodeId).padStart(5)} ${u.offsetY.toFixed(2).padStart(8)} ${u.slotY===void 0?" -":u.slotY.toFixed(2).padStart(8)} ${(u.phase??"-").padEnd(8)} ${u.paint===void 0?"-":u.paint}`);break}console.error(` unknown scroll perf command: ${o}`),process.exit(1)}if(!o||o==="--help"||o==="-h"){console.log(`
903
+ ${b("perf")} \u2014 shell frame profiling (the worker that paints)
904
+
905
+ records per-painted-frame timing in the shell worker \u2014 the surface that
906
+ actually draws the app's pixels \u2014 merged with render-profile counters
907
+ (node visits, boundary records/replays, raster tier, blur ms, draw calls).
908
+
909
+ subcommands:
910
+ start begin recording (clears prior frames + counters)
911
+ stop stop recording and report results
912
+ transition <e> profile a shell transition (goHome, appSwitcher, lockScreen)
913
+
914
+ stop and transition accept --json for the full machine-readable payload.
915
+
916
+ examples:
917
+ ${b("perf")} start
918
+ # ... interact with the app ...
919
+ ${b("perf")} stop
920
+ ${b("perf")} stop --json
921
+ ${b("perf")} transition goHome
922
+ `);break}switch(o){case"start":{let n=await d.send({type:"evaluate",code:`(() => {
923
+ if (!window.__sootsimShellPerf) {
924
+ return { error: 'shell frame profile unavailable (__sootsimShellPerf missing on the page)' }
925
+ }
926
+ window.__sootsimShellPerf.start()
927
+ return { started: true }
928
+ })()`});n?.error&&(console.error(` error: ${n.error}`),process.exit(1)),console.log(` shell profiling started \u2014 interact with the app, then run '${b("perf")} stop'`);break}case"stop":{let n=await d.send({type:"evaluate",code:`(async () => {
929
+ if (!window.__sootsimShellPerf) {
930
+ return { error: 'shell frame profile unavailable (__sootsimShellPerf missing on the page)' }
931
+ }
932
+ return await window.__sootsimShellPerf.stop()
933
+ })()`});if(n?.error&&(console.error(` error: ${n.error}`),n.error==="timeout"&&console.error(" (shell worker did not answer within 5s \u2014 is a sim loaded?)"),process.exit(1)),D(i)){A(n);break}vo(n);break}case"transition":{let n=l[2];if(!n||!["goHome","appSwitcher","lockScreen"].includes(n)){console.log(`
934
+ ${b("perf")} transition <event> \u2014 profile a shell transition
935
+
936
+ events:
937
+ goHome swipe-to-home animation
938
+ appSwitcher app switcher card animation
939
+ lockScreen lock screen transition
940
+
941
+ note: uses 600ms capture window \u2014 may need --timeout 10000 flag
942
+
943
+ examples:
944
+ ${b("perf")} transition goHome --timeout 10000
945
+ ${b("perf")} transition appSwitcher
946
+ `);break}let a=`sootsim:${n}`;Te(` profiling ${n} transition...`),Te(" (use --timeout 10000 if this times out)");let u=await d.send({type:"evaluate",code:`(async () => {
947
+ if (!window.__sootsimShellPerf) {
948
+ return { error: 'shell frame profile unavailable (__sootsimShellPerf missing on the page)' }
949
+ }
950
+ window.__sootsimShellPerf.start()
951
+ // give a frame for profiling to engage before the event
952
+ await new Promise(r => requestAnimationFrame(() => r(undefined)))
953
+ window.dispatchEvent(new Event('${a}'))
954
+ // shell animations are ~300-500ms; fixed timing avoids complex
955
+ // animation-end detection
956
+ await new Promise(r => setTimeout(r, 600))
957
+ return await window.__sootsimShellPerf.stop()
958
+ })()`});if(u?.error&&(console.error(` error: ${u.error}`),process.exit(1)),D(i)){A(u);break}Te(` ${n} transition profiled:`),vo(u);break}default:console.error(` unknown perf subcommand: ${o}`),console.error(" valid: start, stop, transition"),/^--?reset$/.test(o)&&console.error(" note: 'perf start' already clears prior frames \u2014 no reset needed"),(o==="stats"||o==="frames"||o==="worst")&&(console.error(" note: the tenant sampler (stats/frames/worst) was removed \u2014 it hardcoded"),console.error(" layout/render/copy to zero because the shell worker owns every real paint."),console.error(" use 'perf start' / 'perf stop' (worst frames are in the stop report).")),process.exit(1)}break}case"errors":{let o=l[1];if(o==="clear"){await Le(d),D(i)?A({cleared:!0}):console.log(" error buffer cleared");break}let n=o?Number(o):20,r=await ge(d,n);if(D(i)){A(r);break}if(r.length===0){console.log(" no errors captured");break}console.log(` ${r.length} error(s):
959
+ `);for(let a of r){let u=ae(a.timestamp),m=a.args.map(g=>typeof g=="object"?JSON.stringify(g):g).join(" ");if(console.log(` [${u}] ${m}`),a.stack){let g=a.stack.split(`
960
+ `).slice(0,3);for(let w of g)console.log(` ${w.trim()}`)}}break}case"warnings":{let o=l[1]?Number(l[1]):20,n=await ht(d,o);if(D(i)){A(n);break}if(n.length===0){console.log(" no warnings captured");break}console.log(` ${n.length} warning(s):
961
+ `);for(let r of n){let a=ae(r.timestamp),u=r.args.map(m=>typeof m=="object"?JSON.stringify(m):m).join(" ");console.log(` [${a}] ${u}`)}break}case"animations":{let o=await X(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):
962
+ `);for(let n of o){let r=String(n.realm??"tenant").padEnd(6),a=String(n.kind).padEnd(10),u=typeof n.from=="number"&&typeof n.to=="number"?`${n.from.toFixed(2)}\u2192${n.to.toFixed(2)}`:"\u2014",m=Number(n.current??0).toFixed(2),g=typeof n.progress=="number"?`${Math.round(n.progress*100)}%`:"\u2014",w=`${Math.round(n.elapsedMs??0)}ms`,y=[n.loop?"loop":null,n.layoutBound?"layout":null,n.remoteDriven?"remote-driven":n.graphBacked?"graph":null,n.visible===!1?"offscreen":null].filter(Boolean),k=y.length>0?` [${y.join(" ")}]`:"";console.log(` #${n.id} ${r} ${a} ${u.padEnd(14)} cur=${m.padEnd(7)} ${g.padStart(4)} ${w}${k}`)}break}case"animation":{let o=l[1];(!o||o==="--help"||o==="-h")&&(console.error(` usage: ${b("animation")} <id>`),process.exit(1));let n=Number(o);Number.isFinite(n)||(console.error(` invalid id: ${o}`),process.exit(1));let r=await X(d,"getAnimation",n);console.log(JSON.stringify(r,null,2));break}case"stop-animation":{let o=l[1];(!o||o==="--help"||o==="-h")&&(console.error(` usage: ${b("stop-animation")} <id|all>`),process.exit(1));let n=o==="all"?"all":Number(o);n!=="all"&&!Number.isFinite(n)&&(console.error(` invalid id: ${o}`),process.exit(1));let r=await X(d,"stopAnimation",n);console.log(` stopped ${r??0} animation(s)`);break}case"requests":{let o=l[1];if(o==="clear"){await wt(d),D(i)?A({cleared:!0}):console.log(" request buffer cleared");break}let n=o==="all",r=n?l[2]:o,a=r?Number(r):20,u=await bt(d,{failed:!n,limit:a});if(D(i)){A(u);break}if(u.length===0){console.log(n?" no requests captured":" no failed requests captured");break}console.log(` ${u.length} ${n?"request(s)":"failed request(s)"}:
963
+ `);for(let m of u){let g=ae(m.timestamp);console.log(` [${g}] ${U(m)}`),m.responseBody?console.log(` ${m.responseBody}`):m.error&&console.log(` ${m.error}`)}break}case"network":{let o=l[1],n=null,r=null,a=!1,u=!1,m=1e3,g=!1,w=!1;for(let _=0;_<i.length;_++){let S=i[_];if(S==="--filter")n=i[_+1]??null,_++;else if(S==="--limit"){let T=Number(i[_+1]);Number.isFinite(T)&&(r=T),_++}else if(S==="--threshold"){let T=Number(i[_+1]);Number.isFinite(T)&&T>0&&(m=T),_++}else S==="--failed"?a=!0:S==="--slow"?u=!0:S==="--tail"||S==="-f"?g=!0:S==="--json"&&(w=!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 _=l[2];_||(console.error(" usage: rnxsim network get <id>"),process.exit(1));let S=await d.send({type:"evaluate",code:`(() => {
964
+ const obs = window.__sootsimObservability;
965
+ if (!obs) return null;
966
+ return obs.network.getSnapshot().find(e => e.id === ${JSON.stringify(_)}) || null;
967
+ })()`});S||(console.error(` no entry with id ${_}`),process.exit(1)),w?console.log(JSON.stringify(S,null,2)):bs(S);break}let y=r??(g?200:o?Number(o):20);Number.isFinite(y)||(console.error(` invalid limit: ${o} \u2014 \`network\` takes a numeric count (e.g. ${b("network")} 100).
968
+ to target a specific sim, use \`--sim ${o}\` instead.`),process.exit(1));let k=async()=>{let _=await d.send({type:"evaluate",code:`(() => {
969
+ const obs = window.__sootsimObservability;
970
+ if (!obs) return { ok: false };
971
+ return { ok: true, entries: obs.network.getSnapshot() };
972
+ })()`});if(!_||!_.ok)throw new Error("observability bridge not installed \u2014 is the engine running?");return _.entries??[]},L=_=>{let S=_;if(a&&(S=S.filter(T=>!!T.error||T.status!=null&&T.status>=400)),u&&(S=S.filter(T=>T.durationMs!=null&&T.durationMs>=m)),n){let T=n.toLowerCase();S=S.filter(M=>(M.displayUrl||M.url).toLowerCase().includes(T))}return u&&!g&&(S=[...S].sort((T,M)=>(M.durationMs??0)-(T.durationMs??0))),S};if(!g){let _=await k(),S=L(_).slice(-y);if(w){console.log(JSON.stringify(S,null,2));break}if(S.length===0){_.length===0?console.log(" no network requests captured"):console.log(u?` no requests slower than ${m}ms (${_.length} total \u2014 try --threshold <ms>)`:" no matching requests");break}console.log(u?` ${S.length} request(s) slower than ${m}ms (sorted by duration desc):
973
+ `:` ${S.length} request(s):
974
+ `);for(let T of S)bo(T);break}console.log(` tailing network (ctrl-c to stop)...
975
+ `);let V=new Set,G=!0,Y=()=>{G=!1};process.on("SIGINT",Y);try{for(;G;){let _=await k(),S=L(_);for(let T of S)T.durationMs!=null&&(V.has(T.id)||(V.add(T.id),w?console.log(JSON.stringify(T)):bo(T)));await oe(250)}}finally{process.off("SIGINT",Y)}break}case"logs":{let o=l[1],n=null,r=null,a=null,u=!1,m=!1,g=!1;for(let S=0;S<i.length;S++){let T=i[S];if(T==="--filter")n=i[S+1]??null,S++;else if(T==="--limit"){let M=Number(i[S+1]);Number.isFinite(M)&&(r=M),S++}else T==="--level"?(a=i[S+1]??null,S++):T==="--tail"||T==="-f"?u=!0:T==="--json"?m=!0:(T==="--internal"||T==="--all")&&(g=!0)}let w=a?new Set(a.split(",").map(S=>S.trim()).filter(S=>S==="log"||S==="info"||S==="warn"||S==="error"||S==="debug")):null;if(o==="clear"){await xt(d),console.log(" log buffer cleared");break}let y=!m&&process.stdout.isTTY===!0,k=r??(u?500:o?Number(o):50);Number.isFinite(k)||(console.error(` invalid limit: ${o} \u2014 \`logs\` takes a numeric count (e.g. ${b("logs")} 100).
976
+ to target a specific sim, use \`--sim ${o}\` instead.`),process.exit(1));let L=()=>$t(d),V=S=>St(S,{level:w,filter:n,showInternal:g});if(!u){let S=await L(),T=V(S).slice(-k);if(m){console.log(JSON.stringify(T,null,2));break}if(T.length===0){console.log(S.length===0?" no logs captured":" no matching logs");break}console.log(` ${T.length} log(s):
977
+ `);for(let M of T)$o(M,y);break}console.log(` tailing logs (ctrl-c to stop)...
978
+ `);let G=new Set,Y=!0,_=()=>{Y=!1};process.on("SIGINT",_);try{for(;Y;){let S=await L(),T=V(S);for(let M of T)G.has(M.id)||(G.add(M.id),m?console.log(JSON.stringify(M)):$o(M,y));await oe(250)}}finally{process.off("SIGINT",_)}break}default:console.error(` unknown subcommand: ${f}`),process.exit(1)}if(C.has(f)&&!e.includes("--no-wait")&&process.env.SOOTSIM_NO_AUTO_WAIT!=="1"&&!await it(d,f)&&await I(d),x.length>0&&ee(x),!P.has(f))try{await xe(d)}catch{}}catch(x){let o=x instanceof Error?x.message:String(x);console.error(` ${f??"inspect"} failed: ${o}`);let n=/^no sim connected with id ([^;]+)(?:; connected sims: .+)?$/.exec(o),r=/^command timed out after (\d+)s$/.exec(o),a=o.startsWith("sim disconnected:")||o.startsWith("bridge never reconnected")||o.startsWith("could not connect to ws://");if(n)await Ct(d,F,n[1]);else if(/^no sim connected$/.test(o))Bt(F);else if(r)if(await ms(d)){let m=f??"describe";process.stderr.write(` the sim is still responsive \u2014 '${m}' just exceeded the ${r[1]}s command budget.
979
+ the screen's node tree is large; narrow the query or raise the budget:
980
+ rnxsim ${m} --testid <id> # scope to one subtree
981
+ rnxsim find --testid <id> # targeted single-node lookup
982
+ rnxsim ${m} --timeout 60000 # raise per-command budget (ms)
983
+ `)}else yo();else if(a)yo();else{try{await _t(d)}catch{}try{await te({includeTail:!0})}catch{}try{await K({includeTail:!0})}catch{}}process.exit(1)}finally{d.close()}}export{Je as a,Eo as b,Fs as c,Ds as d,Bs as e,Cs as f,js as g,se as h,vo as i,Pr as j};