rnxsim 0.1.366 → 0.1.367

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 (239) hide show
  1. package/README.md +14 -2
  2. package/cli/bin.ts +18 -0
  3. package/cli/bridge-flow-runner.ts +14 -151
  4. package/cli/commands/assert.ts +1 -1
  5. package/cli/commands/box/checkout-plane.ts +126 -0
  6. package/cli/commands/box/rnx-command.ts +68 -0
  7. package/cli/commands/box.ts +200 -0
  8. package/cli/commands/control.ts +12 -32
  9. package/cli/commands/do-chain.ts +412 -0
  10. package/cli/commands/flow.ts +0 -10
  11. package/cli/commands/inspect/core.ts +302 -725
  12. package/cli/commands/inspect/describe.ts +3 -76
  13. package/cli/commands/inspect/find.ts +3 -6
  14. package/cli/commands/inspect/get-layout.ts +14 -1
  15. package/cli/commands/inspect/resolve-target.ts +41 -47
  16. package/cli/commands/inspect/shared.ts +28 -123
  17. package/cli/commands/inspect/tree.ts +6 -15
  18. package/cli/commands/inspect/wait-ready.ts +2 -2
  19. package/cli/commands/inspect/wait-selector.ts +4 -8
  20. package/cli/commands/inspect.ts +23 -17
  21. package/cli/commands/install-desktop.ts +44 -7
  22. package/cli/commands/maestro-generate.ts +0 -2
  23. package/cli/commands/platform.ts +68 -0
  24. package/cli/commands/state.ts +5 -2
  25. package/cli/outbound-endpoints.ts +6 -1
  26. package/cli/parse-args.ts +13 -2
  27. package/cli/ws-bridge.ts +30 -2
  28. package/detox/index.ts +34 -17
  29. package/dist-cli/bin.js +5 -5
  30. package/dist-cli/chunks/{agent-SO6IOPRK.js → agent-EKKIAKP5.js} +2 -2
  31. package/dist-cli/chunks/{agent-wrapper-PMYCB2KO.js → agent-wrapper-MHLQUGA6.js} +2 -2
  32. package/dist-cli/chunks/{app-fonts-LULQGFY7.js → app-fonts-HN6ADRTQ.js} +2 -2
  33. package/dist-cli/chunks/{assert-WGNCD4ZU.js → assert-IMR6QCN6.js} +3 -3
  34. package/dist-cli/chunks/{auth-G7CCHH3M.js → auth-27LPMQNH.js} +2 -2
  35. package/dist-cli/chunks/{beta-N4LXL5TO.js → beta-6RXBB5AI.js} +2 -2
  36. package/dist-cli/chunks/box-DORLF3GP.js +1709 -0
  37. package/dist-cli/chunks/{camera-4JHCYBQS.js → camera-2G7JZ5DL.js} +2 -2
  38. package/dist-cli/chunks/{chunk-2UXU53MG.js → chunk-3QZJLNYY.js} +1 -1
  39. package/dist-cli/chunks/{chunk-YXXKSL6R.js → chunk-3VBVEDDA.js} +1 -1
  40. package/dist-cli/chunks/{chunk-ZJIS3CTW.js → chunk-4BWGLTKU.js} +2 -2
  41. package/dist-cli/chunks/chunk-4XSNO374.js +423 -0
  42. package/dist-cli/chunks/{chunk-RYIMSKDO.js → chunk-5DGMFUZG.js} +2 -2
  43. package/dist-cli/chunks/{chunk-M3BNCF7E.js → chunk-6DBS5EGX.js} +2 -2
  44. package/dist-cli/chunks/{chunk-ONORMKWX.js → chunk-6SO6I3D5.js} +2 -2
  45. package/dist-cli/chunks/chunk-75EFOPXE.js +32 -0
  46. package/dist-cli/chunks/{chunk-5NMCF5VF.js → chunk-A5AJFVOF.js} +1 -1
  47. package/dist-cli/chunks/{chunk-N3UC7HIX.js → chunk-AM2ODYAN.js} +1 -1
  48. package/dist-cli/chunks/{chunk-I6KIM6PN.js → chunk-AVOROGA3.js} +1 -1
  49. package/dist-cli/chunks/chunk-AXMMLO7D.js +130 -0
  50. package/dist-cli/chunks/{chunk-ORWP2E7R.js → chunk-BSEXEYNX.js} +2 -2
  51. package/dist-cli/chunks/{chunk-NQFJOCSF.js → chunk-CM6ZKZW7.js} +2 -2
  52. package/dist-cli/chunks/{chunk-ZMJ75EDG.js → chunk-DNVABCEC.js} +2 -2
  53. package/dist-cli/chunks/{chunk-2S7BKUP2.js → chunk-E33A4AIR.js} +2 -2
  54. package/dist-cli/chunks/{chunk-GXAB52K7.js → chunk-EFMOXYDD.js} +2 -2
  55. package/dist-cli/chunks/{chunk-TIAEYO6I.js → chunk-EV4P5UBP.js} +2 -2
  56. package/dist-cli/chunks/{chunk-JHXETDVC.js → chunk-G5IUIGGC.js} +1 -1
  57. package/dist-cli/chunks/chunk-GMLOCV3E.js +312 -0
  58. package/dist-cli/chunks/{chunk-ZLVRYXZ7.js → chunk-GRN2FHVW.js} +1 -1
  59. package/dist-cli/chunks/{chunk-A5FXX5PJ.js → chunk-HFFXPUEP.js} +1 -1
  60. package/dist-cli/chunks/chunk-HG6T4OOR.js +4 -0
  61. package/dist-cli/chunks/{chunk-OW5XHAA4.js → chunk-HNT2OXPZ.js} +1 -1
  62. package/dist-cli/chunks/chunk-IPEURNLI.js +24 -0
  63. package/dist-cli/chunks/chunk-IR44SFBA.js +5 -0
  64. package/dist-cli/chunks/chunk-JMSLXZFW.js +4 -0
  65. package/dist-cli/chunks/{chunk-EFR5DVNP.js → chunk-JPXQKLNH.js} +1 -1
  66. package/dist-cli/chunks/chunk-K3EC6JDE.js +4 -0
  67. package/dist-cli/chunks/{chunk-YGMEDJKJ.js → chunk-KHX65HAU.js} +2 -2
  68. package/dist-cli/chunks/{chunk-EQK5MJCU.js → chunk-LWOVKHRC.js} +2 -2
  69. package/dist-cli/chunks/{chunk-5OK3LCEJ.js → chunk-MQN5DWTI.js} +2 -2
  70. package/dist-cli/chunks/{chunk-TTASWLKM.js → chunk-N3BXQEUF.js} +1 -1
  71. package/dist-cli/chunks/{chunk-UCHW7ZHR.js → chunk-N5OSV26B.js} +2 -2
  72. package/dist-cli/chunks/chunk-PHNURIH3.js +4 -0
  73. package/dist-cli/chunks/{chunk-AFV32WZT.js → chunk-PP2KNVXP.js} +3 -3
  74. package/dist-cli/chunks/{chunk-XJU2QIRY.js → chunk-PROKNJVY.js} +2 -2
  75. package/dist-cli/chunks/chunk-QXLLY4IM.js +7 -0
  76. package/dist-cli/chunks/{chunk-HT6GFZOZ.js → chunk-RNQTOGM7.js} +1 -1
  77. package/dist-cli/chunks/{chunk-CN6XYYEA.js → chunk-RPNKKVBN.js} +27 -27
  78. package/dist-cli/chunks/{chunk-LN3RNW6X.js → chunk-RSNLI2NH.js} +2 -2
  79. package/dist-cli/chunks/{chunk-YCCCPFWT.js → chunk-RZGHV2WI.js} +2 -2
  80. package/dist-cli/chunks/chunk-SGGL3AFV.js +497 -0
  81. package/dist-cli/chunks/chunk-SH5ETJKG.js +4 -0
  82. package/dist-cli/chunks/{chunk-77ZHQJZR.js → chunk-T6J4YP56.js} +2 -2
  83. package/dist-cli/chunks/{chunk-MGDSJZ37.js → chunk-TWUE7WF5.js} +2 -2
  84. package/dist-cli/chunks/{chunk-SA6XVI55.js → chunk-U44VEQRN.js} +1 -1
  85. package/dist-cli/chunks/{chunk-IZKHOM37.js → chunk-URLVQHC3.js} +1 -1
  86. package/dist-cli/chunks/{chunk-GAJQSITE.js → chunk-VANZFTUE.js} +1 -1
  87. package/dist-cli/chunks/{chunk-EGAGZHO6.js → chunk-VB2YBH46.js} +1 -1
  88. package/dist-cli/chunks/{chunk-H23KWIKA.js → chunk-VFU2SJ7M.js} +2 -2
  89. package/dist-cli/chunks/{chunk-34IQM22N.js → chunk-VUBJ6FXU.js} +15 -15
  90. package/dist-cli/chunks/{chunk-NM2L2QV4.js → chunk-W5PATILQ.js} +2 -2
  91. package/dist-cli/chunks/chunk-WI5V4TYG.js +38 -0
  92. package/dist-cli/chunks/{chunk-6PL2CCGP.js → chunk-XTRHQAOV.js} +2 -2
  93. package/dist-cli/chunks/chunk-XWUTJLBM.js +27 -0
  94. package/dist-cli/chunks/{chunk-5DAIA77C.js → chunk-XYRUQQUR.js} +2 -2
  95. package/dist-cli/chunks/chunk-YBFB3RM7.js +4 -0
  96. package/dist-cli/chunks/chunk-YGQVQ2VG.js +4 -0
  97. package/dist-cli/chunks/{chunk-CTG7HBCA.js → chunk-YINACV32.js} +1 -1
  98. package/dist-cli/chunks/chunk-YV7ERO2V.js +5 -0
  99. package/dist-cli/chunks/{cleanup-KRIATKFH.js → cleanup-GVFHQ3KH.js} +2 -2
  100. package/dist-cli/chunks/cli-version-DPX5MA2M.js +4 -0
  101. package/dist-cli/chunks/{compat-6PTQ3QEA.js → compat-AYRTXYAM.js} +2 -2
  102. package/dist-cli/chunks/{config-ETGDUANO.js → config-K7LOOV62.js} +2 -2
  103. package/dist-cli/chunks/connect-H3CNY4IO.js +4 -0
  104. package/dist-cli/chunks/control-SMHZ2CF5.js +4 -0
  105. package/dist-cli/chunks/daemon-TEZUNI73.js +4 -0
  106. package/dist-cli/chunks/{debug-WIIB6ZKC.js → debug-ELGHG57T.js} +3 -3
  107. package/dist-cli/chunks/{desktop-TD7Q5LNB.js → desktop-4G7FK3MP.js} +3 -3
  108. package/dist-cli/chunks/{detox-7GNR33VM.js → detox-JKXGEJIZ.js} +2 -2
  109. package/dist-cli/chunks/{device-QOR3PGUF.js → device-IV3AR6KG.js} +2 -2
  110. package/dist-cli/chunks/{diagnose-RRCBLP6E.js → diagnose-3ERGF7EW.js} +2 -2
  111. package/dist-cli/chunks/{disk-cleanup-MJUGJPXT.js → disk-cleanup-ALFEVZ4B.js} +2 -2
  112. package/dist-cli/chunks/do-chain-K2B4OHM7.js +5 -0
  113. package/dist-cli/chunks/drivers-KJYXA3M3.js +4 -0
  114. package/dist-cli/chunks/env-2KF6IYZE.js +4 -0
  115. package/dist-cli/chunks/{film-D7Y64LID.js → film-UQXJFAD5.js} +3 -3
  116. package/dist-cli/chunks/flow-ASTUH56E.js +4 -0
  117. package/dist-cli/chunks/help-SNNYFELA.js +4 -0
  118. package/dist-cli/chunks/{hidden-runtime-alias-JGURVR2Z.js → hidden-runtime-alias-VJCWCFVO.js} +2 -2
  119. package/dist-cli/chunks/{home-paths-4ICFIGXO.js → home-paths-EGUZZ6J6.js} +2 -2
  120. package/dist-cli/chunks/inspect-XANAADQT.js +4 -0
  121. package/dist-cli/chunks/install-desktop-JKQA7UY6.js +4 -0
  122. package/dist-cli/chunks/{login-RU33QR2G.js → login-6KQGD7HK.js} +2 -2
  123. package/dist-cli/chunks/{logout-2IUG3Y5J.js → logout-2FCOVLBC.js} +2 -2
  124. package/dist-cli/chunks/{maestro-2MXTGG7I.js → maestro-HPSSEVJD.js} +3 -3
  125. package/dist-cli/chunks/{maestro-generate-2PYIFGLR.js → maestro-generate-KQQ6JHMR.js} +5 -5
  126. package/dist-cli/chunks/{mode-3DAPG3HF.js → mode-SH7KRZET.js} +2 -2
  127. package/dist-cli/chunks/{optional-demo-registry-BWSDJF2Z.js → optional-demo-registry-NAMCAVFX.js} +2 -2
  128. package/dist-cli/chunks/{perf-2TKPWB4N.js → perf-LWKAHXUL.js} +2 -2
  129. package/dist-cli/chunks/{permissions-5CSMHYNA.js → permissions-EZTKWTXV.js} +2 -2
  130. package/dist-cli/chunks/platform-KSOJIVN5.js +6 -0
  131. package/dist-cli/chunks/privacy-EJULWP7L.js +4 -0
  132. package/dist-cli/chunks/{record-I2HJCFP3.js → record-2IC7BAQN.js} +3 -3
  133. package/dist-cli/chunks/{report-issue-A4FZWBOC.js → report-issue-MMX6HOQO.js} +2 -2
  134. package/dist-cli/chunks/reset-PKFZA4NC.js +4 -0
  135. package/dist-cli/chunks/resolve-target-AFKU3BRE.js +4 -0
  136. package/dist-cli/chunks/runtime-XHWWPOIN.js +4 -0
  137. package/dist-cli/chunks/{screenshot-command-UFW5BFHP.js → screenshot-command-JYUXDVSA.js} +3 -3
  138. package/dist-cli/chunks/{screenshot-layers-5BIAL4YN.js → screenshot-layers-OGRY6AA3.js} +2 -2
  139. package/dist-cli/chunks/{screenshots-capture-EHYS3BV2.js → screenshots-capture-QHDN65XS.js} +2 -2
  140. package/dist-cli/chunks/{serve-O4FDM3AC.js → serve-W4BKAG4J.js} +3 -3
  141. package/dist-cli/chunks/setup-WJPMPSAC.js +4 -0
  142. package/dist-cli/chunks/sim-client-UOQGFBPO.js +4 -0
  143. package/dist-cli/chunks/{skills-ZK55SY32.js → skills-OPPXOD63.js} +2 -2
  144. package/dist-cli/chunks/state-TDAN7BOM.js +14 -0
  145. package/dist-cli/chunks/{storage-WP33ISEM.js → storage-CFB2YGLY.js} +2 -2
  146. package/dist-cli/chunks/store-4TEED4ZU.js +4 -0
  147. package/dist-cli/chunks/telemetry-S6N7CV6G.js +4 -0
  148. package/dist-cli/chunks/{timeline-DKGW5S4I.js → timeline-ASOOVP4C.js} +2 -2
  149. package/dist-cli/chunks/{upgrade-LL7G4B7G.js → upgrade-6MVJISHG.js} +2 -2
  150. package/dist-cli/chunks/upload-CBNIRFEW.js +4 -0
  151. package/dist-cli/chunks/{version-YLWR5G4F.js → version-5GS7CWRL.js} +2 -2
  152. package/dist-cli/chunks/{web-QELZ4CP6.js → web-QRRMYMV4.js} +2 -2
  153. package/dist-cli/chunks/welcome-33FXMAMB.js +5 -0
  154. package/dist-cli/chunks/{what-happened-MIOMZWM5.js → what-happened-GAZJGKXX.js} +2 -2
  155. package/dist-cli/chunks/ws-bridge-DIXUAPLQ.js +4 -0
  156. package/dist-lib/agent-daemon-client.cjs +1 -1
  157. package/dist-lib/agent-events.cjs +1 -1
  158. package/dist-lib/agent-identity.cjs +1 -1
  159. package/dist-lib/agent-sessions.cjs +1 -1
  160. package/dist-lib/attached-projects.cjs +1 -1
  161. package/dist-lib/auth/shared-session.cjs +1 -1
  162. package/dist-lib/backend-origin.cjs +1 -1
  163. package/dist-lib/beta.cjs +1 -1
  164. package/dist-lib/beta.mjs +1 -1
  165. package/dist-lib/bridge-constants.cjs +1 -1
  166. package/dist-lib/bridge-contract-input.cjs +336 -0
  167. package/dist-lib/bridge-contract-input.mjs +303 -0
  168. package/dist-lib/bridge-contract.cjs +29 -1
  169. package/dist-lib/bridge-contract.mjs +19 -0
  170. package/dist-lib/cli-constants.cjs +1 -1
  171. package/dist-lib/config.cjs +1 -1
  172. package/dist-lib/detox/index.cjs +32 -18
  173. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  174. package/dist-lib/home-paths.cjs +1 -1
  175. package/dist-lib/host/bridge-host.cjs +5 -1
  176. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  177. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  178. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  179. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  180. package/dist-lib/host/websocket-proxy.cjs +1 -1
  181. package/dist-lib/index.cjs +214 -594
  182. package/dist-lib/jump-to-source-babel.cjs +1 -1
  183. package/dist-lib/menu.cjs +1 -1
  184. package/dist-lib/menu.mjs +1 -1
  185. package/dist-lib/metro-production-bundle.cjs +1 -1
  186. package/dist-lib/metro-production-bundle.mjs +1 -1
  187. package/dist-lib/metro.cjs +1 -1
  188. package/dist-lib/profiles.cjs +1 -1
  189. package/dist-lib/public-brand.cjs +1 -1
  190. package/dist-lib/react-native-host-modules.cjs +1 -1
  191. package/dist-lib/react-native-host-modules.mjs +1 -1
  192. package/dist-lib/render-mode.cjs +1 -1
  193. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  194. package/dist-lib/sdk.cjs +273 -657
  195. package/dist-lib/sdk.mjs +271 -652
  196. package/dist-lib/skills.cjs +190 -287
  197. package/dist-lib/vite.cjs +1 -1
  198. package/package.json +9 -6
  199. package/skills/contrast/SKILL.md +3 -0
  200. package/skills/rnx-debug/SKILL.md +8 -0
  201. package/skills/rnx-test/SKILL.md +21 -0
  202. package/src/bridge-contract-input.ts +359 -0
  203. package/src/bridge-contract.ts +121 -1
  204. package/src/host/bridge-host.ts +7 -12
  205. package/src/index.ts +7 -0
  206. package/src/sim-client.ts +12 -3
  207. package/dist-cli/chunks/chunk-3X6IBUBX.js +0 -38
  208. package/dist-cli/chunks/chunk-7B37IZBN.js +0 -15
  209. package/dist-cli/chunks/chunk-DMPF2D24.js +0 -4
  210. package/dist-cli/chunks/chunk-DW37EVX5.js +0 -767
  211. package/dist-cli/chunks/chunk-DWFIH7CB.js +0 -32
  212. package/dist-cli/chunks/chunk-GUI3PDH2.js +0 -27
  213. package/dist-cli/chunks/chunk-KLF3K6ZZ.js +0 -4
  214. package/dist-cli/chunks/chunk-M5QCGLXR.js +0 -944
  215. package/dist-cli/chunks/chunk-M6SKQGAN.js +0 -5
  216. package/dist-cli/chunks/chunk-NAYLPOC5.js +0 -24
  217. package/dist-cli/chunks/chunk-VIND4SP3.js +0 -124
  218. package/dist-cli/chunks/chunk-XXNLYR64.js +0 -5
  219. package/dist-cli/chunks/chunk-ZFM24DOX.js +0 -4
  220. package/dist-cli/chunks/cli-version-SYGNHGFR.js +0 -4
  221. package/dist-cli/chunks/control-RBTNOLQM.js +0 -4
  222. package/dist-cli/chunks/daemon-N3SC5DK6.js +0 -4
  223. package/dist-cli/chunks/drivers-W6E3BZH4.js +0 -4
  224. package/dist-cli/chunks/flow-7QAE2V5Y.js +0 -4
  225. package/dist-cli/chunks/help-NLD6KWVG.js +0 -4
  226. package/dist-cli/chunks/inspect-C347BG52.js +0 -4
  227. package/dist-cli/chunks/install-desktop-YR6TWZYK.js +0 -4
  228. package/dist-cli/chunks/privacy-PWWC2BXO.js +0 -4
  229. package/dist-cli/chunks/reset-Y3PBPFYA.js +0 -4
  230. package/dist-cli/chunks/runtime-IC6NVVGA.js +0 -4
  231. package/dist-cli/chunks/setup-Y4QGSJBM.js +0 -4
  232. package/dist-cli/chunks/state-KFLAZNEY.js +0 -14
  233. package/dist-cli/chunks/store-VEE22CAY.js +0 -4
  234. package/dist-cli/chunks/telemetry-PZV4BISJ.js +0 -4
  235. package/dist-cli/chunks/upload-Y4C3YZDK.js +0 -4
  236. package/dist-cli/chunks/welcome-ZPKA5PZJ.js +0 -5
  237. package/dist-lib/mcp.cjs +0 -673
  238. package/dist-lib/mcp.mjs +0 -641
  239. package/src/mcp.ts +0 -791
@@ -1,944 +0,0 @@
1
- /*! rnx v0.1.366 | (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 jt,c as qt}from"./chunk-ZLVRYXZ7.js";import{a as Bt,b as Ct}from"./chunk-A5FXX5PJ.js";import{a as de}from"./chunk-XJU2QIRY.js";import{j as Dt}from"./chunk-7B37IZBN.js";import{a as oe,b as C,c as B,d as Me,e as ae,f as X,g as me,h as ye,i as At,j as Et,k as Ne,l as _t}from"./chunk-3X6IBUBX.js";import{A as Mt,B as Nt,C as Ft,F as Pt,H as Ot,J as pe,K as Rt,Q as We,a as Ie,b as mt,c as ft,d as gt,e as yt,f as ht,g as bt,h as wt,i as xt,j as $t,k as Ce,l as je,r as qe,s as St,t as vt,u as ge,v as kt,w as Te,x as Le,y as It,z as Tt}from"./chunk-DW37EVX5.js";import{a as Q}from"./chunk-NM2L2QV4.js";import{e as it,j as at,o as lt,q as ct,s as dt,t as ut,u as pt,v as ce}from"./chunk-GUI3PDH2.js";import{a as st}from"./chunk-KLF3K6ZZ.js";import{c as nt,d as Be,f as rt}from"./chunk-VIND4SP3.js";import{a as ue}from"./chunk-IZKHOM37.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 Bo,mkdirSync as Wt,readFileSync as Co,rmSync as Ke,writeFileSync as Jt}from"fs";import{tmpdir as jo}from"os";import{dirname as Ht,join as qo,resolve as Kt}from"path";import*as Fe from"fs";function Do(e){let t={},s=e,i=p=>Array.isArray(p)?p:[],d=e.match(/^---\n([\s\S]*?)\n---\n?/);if(d){try{t=de.parse(d[1])??{}}catch(b){console.warn(` warn: could not parse frontmatter: ${b.message}`)}s=e.slice(d[0].length);let p=de.parse(s);return{frontmatter:t,steps:i(p)}}if(/\n---\s*\n/.test(e))try{let p=de.parseAllDocuments(e);if(p.length>=2){let b=p[0].toJS(),h=p[p.length-1].toJS();return{frontmatter:b&&typeof b=="object"?b:{},steps:i(h)}}}catch(p){console.warn(` warn: could not parse multi-doc flow: ${p.message}`)}let r=de.parse(s);return{frontmatter:t,steps:i(r)}}var Lt=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(r=>Lt.has(r))&&(s+=1):typeof i=="string"&&Lt.has(i)&&(s+=1);return s===0&&t.push("no interaction steps found (expected at least one tapOn / inputText / pressKey / swipe / scroll)"),t}function Ps(e){if(!Fe.existsSync(e))return[`file not found: ${e}`];let t;try{t=Fe.readFileSync(e,"utf8")}catch(s){return[`cannot read file: ${s.message}`]}if(t.trim().length===0)return["file is empty"];try{let s=Do(t);return He(s.steps)}catch(s){return[`yaml parse error: ${s.message}`]}}var Ue=1;function Pe(){return Kt(process.env.SOOTSIM_FLOW_SESSION_PATH||qo(jo(),"sootsim-flow-session.json"))}function Ge(e){let t=Pe();Wt(Ht(t),{recursive:!0}),Jt(t,JSON.stringify(e,null,2)+`
10
- `)}function ze(){let e=Pe();if(!Bo(e))return null;try{let t=JSON.parse(Co(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 Bs(){let e=new Date().toISOString(),t={version:Ue,startedAt:e,updatedAt:e,steps:[],candidate:null};return Ge(t),{path:Pe(),state:t}}function Lo(){Ke(Pe(),{force:!0})}function Cs(){Lo()}function Oe(e){let t=ze();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 js(){let e=ze();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 Wo(e){return de.stringify(e).trimEnd()+`
11
- `}function qs(e){let t=ze();if(!t)return{active:!1};let s=Wo(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 d=null;return e&&(d=Kt(e),Wt(Ht(d),{recursive:!0}),Jt(d,s)),{active:!0,valid:!0,issues:[],yaml:s,stepCount:t.steps.length,outputPath:d}}import{existsSync as Jo,mkdirSync as Ho,readFileSync as Ko,rmSync as Ut,writeFileSync as Uo}from"fs";import{tmpdir as Go}from"os";import{dirname as zo,join as Yo,resolve as Xo}from"path";var he=1,Vo="SOOTSIM_INSPECT_NOTICE_PATH",Qo=300*1e3,Zo=15e3;function Gt(){return Xo(process.env[Vo]||Yo(Go(),"sootsim-inspect-notice-state.json"))}function es(e,t){return Object.fromEntries(Object.entries(e).filter(([,s])=>typeof s?.signature=="string"&&Number.isFinite(s?.updatedAt)&&t-s.updatedAt<=Qo))}function ts(e){let t=Gt();if(!Jo(t))return{version:he,entries:{}};try{let s=JSON.parse(Ko(t,"utf8"));return s.version!==he||!s.entries||typeof s.entries!="object"?(Ut(t,{force:!0}),{version:he,entries:{}}):{version:he,entries:es(s.entries,e)}}catch{return Ut(t,{force:!0}),{version:he,entries:{}}}}function os(e){let t=Gt();Ho(zo(t),{recursive:!0}),Uo(t,JSON.stringify(e,null,2)+`
12
- `)}function ss(e,t){let s=t.trim()||"default";return`${e}:${s}`}function Ye(e,t,s,i={}){let d=i.nowMs??Date.now(),r=i.cooldownMs??Zo,p=ts(d),b=ss(e,t),h=p.entries[b];return h&&h.signature===s&&d-h.updatedAt<r?!1:(p.entries[b]={signature:s,updatedAt:d},os(p),!0)}async function se({bridge:e,simId:t,maxMs:s,pollMs:i=50,stablePolls:d=3,strict:r=!1}){let p=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(d))}
17
- const strict = ${r?"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 layoutDirty = false
45
- let pendingFetches = 0
46
- let requestTotal = 0
47
- let requestInFlight = 0
48
- let renderStatsAvailable = false
49
- try {
50
- const stats = await window.__sootsimRenderHost?.queryStats?.()
51
- if (stats) {
52
- renderStatsAvailable = true
53
- animating =
54
- stats.hasActiveAnims === true ||
55
- stats.hasActiveNativeAnimations === true ||
56
- stats.hasPendingAnimationFrames === true
57
- layoutDirty =
58
- stats.layoutDirty === true && stats.renderRequested === true
59
- // a freshly-pushed screen showing a skeleton is layout-stable
60
- // but not actually settled \u2014 its data/images are still in
61
- // flight. treat bounded image-loader fetches as not-idle so
62
- // settle waits for real content, capped by the budget.
63
- const pf = stats.memory && stats.memory.imageLoader
64
- ? stats.memory.imageLoader.pendingFetches
65
- : 0
66
- pendingFetches = typeof pf === 'number' ? pf : 0
67
- }
68
- } catch {}
69
- try {
70
- const counts = await window.__sootsimTest?.getRequestCounts?.()
71
- requestTotal = typeof counts?.total === 'number' ? counts.total : 0
72
- requestInFlight = typeof counts?.inFlight === 'number' ? counts.inFlight : 0
73
- } catch {}
74
- const root = window.__sootsimRoot
75
- const nodes = []
76
- if (root) {
77
- const walk = (n) => {
78
- if (n.layout && n.layout.width > 0) {
79
- nodes.push(Math.round(n.layout.x) + ',' + Math.round(n.layout.y) + ',' + Math.round(n.layout.width))
80
- }
81
- for (const c of n.children || []) walk(c)
82
- }
83
- walk(root)
84
- }
85
- return { layout: nodes.join(';'), animating, layoutDirty, pendingFetches, renderStatsAvailable, requestTotal, requestInFlight }
86
- }
87
-
88
- // how long generic background network is allowed to keep us waiting AFTER
89
- // the screen is otherwise visually settled. apps with continuous traffic
90
- // (polling, realtime sockets, a tap that fires 20-50 fetches) never reach
91
- // requestInFlight===0 / a stable requestTotal, so requiring full network
92
- // quiet burns the ENTIRE budget on every command \u2014 the leading idle that
93
- // failed PR-preview recordings for network-heavy apps (3pc fight-pulse).
94
- // layout-stability + the image-loader already prove visible content
95
- // loaded (a data load changes layout; an image load shows in the loader),
96
- // so the generic request counters are a courtesy, not a gate: honor them
97
- // only within this grace once the screen is visually still.
98
- const networkQuietGraceMs = 1200
99
- let lastLayout = ''
100
- let lastRequestTotal = -1
101
- let stable = 0
102
- let visuallyStillSince = 0
103
- while (Date.now() < deadline) {
104
- const snapshot = await readSnapshot()
105
- const strictOk =
106
- !strict ||
107
- (snapshot.renderStatsAvailable && !snapshot.animating && !snapshot.layoutDirty)
108
- // visually settled: no animations, no image content loading, layout
109
- // unchanged since the last poll.
110
- const visuallyStill =
111
- strictOk && snapshot.pendingFetches === 0 && snapshot.layout === lastLayout
112
- // generic network quiet: nothing in flight and no new requests issued.
113
- const networkQuiet =
114
- snapshot.requestInFlight === 0 && snapshot.requestTotal === lastRequestTotal
115
- if (visuallyStill) {
116
- stable++
117
- if (visuallyStillSince === 0) visuallyStillSince = Date.now()
118
- // settle once the screen has held still long enough AND either the
119
- // network is genuinely quiet OR it has refused to quiet within the
120
- // grace (continuous background traffic must not block forever).
121
- if (
122
- stable >= requiredStablePolls &&
123
- (networkQuiet || Date.now() - visuallyStillSince >= networkQuietGraceMs)
124
- ) {
125
- return { settled: true, elapsed: Date.now() - start }
126
- }
127
- } else {
128
- stable = 0
129
- visuallyStillSince = 0
130
- }
131
- lastLayout = snapshot.layout
132
- lastRequestTotal = snapshot.requestTotal
133
- await sleep(pollMs)
134
- }
135
- return { settled: false, elapsed: Date.now() - start }
136
- })()`},{timeoutMs:s+1e3}),{elapsed:b,settled:h}=p??{};return{elapsed:typeof b=="number"?b:s,settled:h===!0}}var Re=`(() => {
137
- const spec = window.SootSim?.state?.engineSnapshot?.windowState?.deviceSpec
138
- return spec && spec.width > 0 && spec.height > 0
139
- ? { width: spec.width, height: spec.height }
140
- : null
141
- })()`,ns={initialWaitMs:3e3,deadlineMs:5e3,retryWaitMs:700},rs={initialWaitMs:1200,deadlineMs:2500,retryWaitMs:700};function is(e,t={}){return{...e?ns:rs,...t}}function fe(e){return!(!e||e.hit===!1||e.ok===!1||e.requestedTargetMatched===!1||e.pointerTapHandled===!1&&!e.keyboardOpened&&!e.isTextInput)}function as(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=is(!!t.agent,t.timing),i=0,d=null,r=null;try{await se({bridge:e,maxMs:s.initialWaitMs,pollMs:32,stablePolls:2})}catch{}let p=Date.now()+s.deadlineMs,b=null;for(;Date.now()<=p||i===0;){i++;let h=await t.resolve();if(d=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){r={hit:!1,reason:"offscreen",x:h.cx,y:h.cy,screen:h.screen};let w=`${Math.round(h.cx)},${Math.round(h.cy)}`;if(b===w)return{payload:h,result:r,attempts:i,failure:"missed"};b=w}else{b=null;let w=as(h,t.textFallback),g=await e.send({type:"evaluate",code:`(async () => {
142
- const t = window.__sootsimTest
143
- if (
144
- !t ||
145
- typeof t.inspectAt !== 'function' ||
146
- typeof t.resolveTapTarget !== 'function'
147
- ) {
148
- return { error: 'tap-target-inspection-unavailable' }
149
- }
150
- const requestedTarget = ${JSON.stringify(w)}
151
- const inspected = await t.inspectAt(${h.cx}, ${h.cy})
152
- const resolved =
153
- inspected && typeof inspected.nodeId === 'number'
154
- ? await t.resolveTapTarget(inspected.nodeId)
155
- : null
156
- const node = (resolved && resolved.target) || inspected
157
- const coordinateTarget = node
158
- ? {
159
- nodeId: node.nodeId ?? null,
160
- id: node.id ?? null,
161
- testID: node.testID ?? null,
162
- text: node.text ?? node.accessibilityLabel ?? null,
163
- type: node.type ?? null,
164
- }
165
- : null
166
- const coordinateAncestors = Array.isArray(inspected?.ancestors)
167
- ? inspected.ancestors
168
- : []
169
- const ancestorMatchesRequested = coordinateAncestors.some(
170
- (ancestor) =>
171
- (typeof requestedTarget.nodeId === 'number' &&
172
- ancestor?.nodeId === requestedTarget.nodeId) ||
173
- (requestedTarget.testID &&
174
- ancestor?.testID === requestedTarget.testID) ||
175
- (requestedTarget.id && ancestor?.id === requestedTarget.id),
176
- )
177
- const requestedTargetMatched =
178
- coordinateTarget === null
179
- ? false
180
- : typeof requestedTarget.nodeId === 'number' &&
181
- typeof coordinateTarget.nodeId === 'number'
182
- ? requestedTarget.nodeId === coordinateTarget.nodeId ||
183
- ancestorMatchesRequested
184
- : requestedTarget.testID && coordinateTarget.testID
185
- ? requestedTarget.testID === coordinateTarget.testID
186
- || ancestorMatchesRequested
187
- : requestedTarget.id && coordinateTarget.id
188
- ? requestedTarget.id === coordinateTarget.id
189
- || ancestorMatchesRequested
190
- : ancestorMatchesRequested
191
- if (!requestedTargetMatched) {
192
- return {
193
- requestedTargetMatched,
194
- requestedTarget,
195
- coordinateTarget,
196
- }
197
- }
198
- if (typeof t.activatePressAt !== 'function') {
199
- return { error: 'tap-target-activation-unavailable' }
200
- }
201
- const activation = await t.activatePressAt(
202
- ${h.cx},
203
- ${h.cy},
204
- requestedTarget.nodeId,
205
- )
206
- if (activation?.ok) {
207
- window.dispatchEvent(
208
- new CustomEvent('sootsim:agentAction', {
209
- detail: {
210
- type: 'tap',
211
- x: ${h.cx},
212
- y: ${h.cy},
213
- target: requestedTarget,
214
- },
215
- }),
216
- )
217
- }
218
- return {
219
- activation,
220
- requestedTargetMatched,
221
- requestedTarget,
222
- coordinateTarget,
223
- }
224
- })()`});if(g?.error)return{payload:h,result:{hit:!1,reason:g.error,requestedTarget:w},attempts:i,failure:"special"};if(g?.requestedTargetMatched===!1)return{payload:h,result:{hit:!1,reason:"target-covered",...g},attempts:i,failure:"missed"};let M=g?.activation?.tap??g?.activation,x=M&&typeof M=="object"?{...M,...g?.activation,...g}:{hit:!!M,...g};if(r=x,fe(x))return{payload:h,result:x,attempts:i}}let I=p-Date.now();if(I<=0)break;try{await se({bridge:e,maxMs:Math.min(I,s.retryWaitMs),pollMs:32,stablePolls:2})}catch{await new Promise(w=>setTimeout(w,Math.min(120,I)))}}return{payload:d,result:r,attempts:i,failure:d&&typeof d.cx=="number"?"missed":"not-found"}}async function zt(e,t,s,i){return e.send({type:"tap",x:t,y:s,...i?{target:i}:{}})}async function Yt(e,t,s={}){let i=JSON.stringify(t);return be(e,{agent:s.agent,timing:s.timing,resolve:()=>e.send({type:"evaluate",code:`(async () => {
225
- const t = window.__sootsimTest
226
- if (!t) return null
227
- const n = (await t.findByTestId(${i})) || (await t.findById(${i}))
228
- if (!n || !n.absolutePosition || !n.layout) return { cx: null }
229
- const resolved =
230
- typeof n.nodeId === 'number' && typeof t.resolveTapTarget === 'function'
231
- ? await t.resolveTapTarget(n.nodeId)
232
- : null
233
- const target = (resolved && resolved.target) || n
234
- const cx =
235
- resolved && typeof resolved.cx === 'number'
236
- ? resolved.cx
237
- : n.absolutePosition.x + (n.layout.width || 0) / 2
238
- const cy =
239
- resolved && typeof resolved.cy === 'number'
240
- ? resolved.cy
241
- : n.absolutePosition.y + (n.layout.height || 0) / 2
242
- const scr = ${Re}
243
- const offscreen =
244
- !!scr && (cx < 0 || cy < 0 || cx > scr.width || cy > scr.height)
245
- return {
246
- cx,
247
- cy,
248
- ...(offscreen ? { offscreen: true, screen: scr } : {}),
249
- match: {
250
- nodeId: n.nodeId ?? null,
251
- id: n.id,
252
- testID: n.testID,
253
- text: n.text ?? n.accessibilityLabel ?? null,
254
- type: n.type,
255
- },
256
- target: {
257
- nodeId: target.nodeId ?? null,
258
- id: target.id,
259
- testID: target.testID,
260
- text:
261
- target.text ??
262
- target.accessibilityLabel ??
263
- n.text ??
264
- n.accessibilityLabel ??
265
- null,
266
- type: target.type,
267
- },
268
- strategy: (resolved && resolved.strategy) || 'matched-node',
269
- }
270
- })()`})})}async function Xt(e,t,s={},i={}){let d=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 () => {
271
- const t = window.__sootsimTest
272
- if (!t) return { error: 'bridge-not-ready' }
273
- const F = ${d}
274
-
275
- const res = await t.queryTextCandidates({
276
- query: F.query,
277
- exact: !!F.exact,
278
- ...(F.role ? { role: F.role } : {}),
279
- })
280
-
281
- let candidates = res.candidates || []
282
-
283
- candidates = candidates.filter((c) => {
284
- const ax = c.info.absolutePosition && c.info.absolutePosition.x
285
- const ay = c.info.absolutePosition && c.info.absolutePosition.y
286
- if (F.minX !== null && !(ax >= F.minX)) return false
287
- if (F.maxX !== null && !(ax <= F.maxX)) return false
288
- if (F.minY !== null && !(ay >= F.minY)) return false
289
- if (F.maxY !== null && !(ay <= F.maxY)) return false
290
- if (F.within && !c.ancestorTestIDs.includes(F.within)) return false
291
- return true
292
- })
293
-
294
- if (F.near) {
295
- candidates.sort((a, b) => {
296
- const ax = (a.info.absolutePosition && a.info.absolutePosition.x) || 0
297
- const ay = (a.info.absolutePosition && a.info.absolutePosition.y) || 0
298
- const bx = (b.info.absolutePosition && b.info.absolutePosition.x) || 0
299
- const by = (b.info.absolutePosition && b.info.absolutePosition.y) || 0
300
- return (
301
- Math.hypot(ax - F.near.x, ay - F.near.y) -
302
- Math.hypot(bx - F.near.x, by - F.near.y)
303
- )
304
- })
305
- } else {
306
- candidates.sort((a, b) => {
307
- const ay = (a.info.absolutePosition && a.info.absolutePosition.y) || 0
308
- const by = (b.info.absolutePosition && b.info.absolutePosition.y) || 0
309
- if (Math.abs(ay - by) > 2) return ay - by
310
- const ax = (a.info.absolutePosition && a.info.absolutePosition.x) || 0
311
- const bx = (b.info.absolutePosition && b.info.absolutePosition.x) || 0
312
- return ax - bx
313
- })
314
- }
315
-
316
- const total = candidates.length
317
- if (total === 0) return { matched: 0, total: 0 }
318
-
319
- let idx = 0
320
- if (F.nth !== null) {
321
- idx = F.nth < 0 ? total + F.nth : F.nth
322
- if (idx < 0 || idx >= total) {
323
- return { matched: 0, total, nthOutOfRange: true, nth: F.nth }
324
- }
325
- } else if (total > 1 && !F.first && !F.near) {
326
- return {
327
- ambiguous: true,
328
- total,
329
- candidates: candidates.slice(0, 10).map((c, i) => ({
330
- idx: i,
331
- nodeId: c.info.nodeId,
332
- type: c.info.type,
333
- testID: c.info.testID,
334
- text: (c.info.text || '').slice(0, 60),
335
- abs: c.info.absolutePosition,
336
- layout: c.info.layout
337
- ? {
338
- width: Math.round(c.info.layout.width || 0),
339
- height: Math.round(c.info.layout.height || 0),
340
- }
341
- : null,
342
- ancestorTestIDs: (c.ancestorTestIDs || []).slice(0, 5),
343
- })),
344
- }
345
- }
346
-
347
- const picked = candidates[idx]
348
- const n = picked.info
349
- if (!n.absolutePosition || !n.layout) return { matched: 0, total }
350
-
351
- const resolved =
352
- typeof n.nodeId === 'number' &&
353
- typeof t.resolveTapTarget === 'function'
354
- ? await t.resolveTapTarget(n.nodeId)
355
- : null
356
- const target = (resolved && resolved.target) || n
357
- const cx =
358
- resolved && typeof resolved.cx === 'number'
359
- ? resolved.cx
360
- : n.absolutePosition.x + (n.layout.width || 0) / 2
361
- const cy =
362
- resolved && typeof resolved.cy === 'number'
363
- ? resolved.cy
364
- : n.absolutePosition.y + (n.layout.height || 0) / 2
365
- const scr = ${Re}
366
- const offscreen =
367
- !!scr && (cx < 0 || cy < 0 || cx > scr.width || cy > scr.height)
368
- return {
369
- cx,
370
- cy,
371
- ...(offscreen ? { offscreen: true, screen: scr } : {}),
372
- match: {
373
- nodeId: n.nodeId ?? null,
374
- id: n.id,
375
- testID: n.testID,
376
- type: n.type,
377
- },
378
- target: {
379
- nodeId: target.nodeId ?? null,
380
- id: target.id,
381
- testID: target.testID,
382
- text:
383
- target.text ??
384
- target.accessibilityLabel ??
385
- n.text ??
386
- n.accessibilityLabel ??
387
- null,
388
- type: target.type,
389
- },
390
- strategy: (resolved && resolved.strategy) || 'matched-node',
391
- total,
392
- idx,
393
- }
394
- })()`})})}async function Vt(e,t,s={}){let i=JSON.stringify(t);return be(e,{agent:s.agent,timing:s.timing,textFallback:t,resolve:async()=>{let d=await e.send({type:"evaluate",code:`(async () => {
395
- const t = window.__sootsimTest
396
- if (!t) return { error: 'bridge-not-ready' }
397
- const byTestId =
398
- (await t.findByTestId(${i})) || (await t.findById(${i}))
399
- if (byTestId && byTestId.absolutePosition && byTestId.layout) {
400
- return {
401
- strategy: 'testid',
402
- node: {
403
- nodeId: byTestId.nodeId ?? null,
404
- id: byTestId.id,
405
- testID: byTestId.testID,
406
- type: byTestId.type,
407
- text: byTestId.text,
408
- absolutePosition: byTestId.absolutePosition,
409
- layout: byTestId.layout,
410
- },
411
- screen: ${Re},
412
- }
413
- }
414
- const byText = await t.findByText(${i})
415
- if (byText && byText.absolutePosition && byText.layout) {
416
- return {
417
- strategy: 'text',
418
- node: {
419
- nodeId: byText.nodeId ?? null,
420
- id: byText.id,
421
- testID: byText.testID,
422
- type: byText.type,
423
- text: byText.text,
424
- absolutePosition: byText.absolutePosition,
425
- layout: byText.layout,
426
- },
427
- screen: ${Re},
428
- }
429
- }
430
- return { strategy: 'none' }
431
- })()`});if(!d||!("node"in d))return d;let r=d.node,p=r.absolutePosition.x+r.layout.width/2,b=r.absolutePosition.y+r.layout.height/2,h=d.screen??null,I=!!h&&(p<0||b<0||p>h.width||b>h.height);return{...d,cx:p,cy:b,...I?{offscreen:!0,screen:h}:{},target:{id:r.id,testID:r.testID,text:d.strategy==="text"?t:r.text,type:r.type}}}})}async function Qt(e,t={args:[]}){let s=await ft(e);if(C(t.args)){B(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 Zt(e){let{bridge:t,args:s,positional:i}=e,d=s.includes("--verbose")||s.includes("-v"),r=C(s),p=d&&!r,b=s.includes("--watch")||s.includes("-w"),h=1e3,I=s.includes("--compact"),w=s.includes("--no-xy"),g=s.includes("--no-clipped"),M=s.includes("--include-occluded"),x=Xe(s,"--testid-like"),_=Xe(s,"--only"),P=Xe(s,"--subtree"),c=i[1]&&!i[1].startsWith("-")?i[1]:void 0,D=c?/[*?]/.test(c):!1,R=!D&&!_?c:void 0,E=_??(D?c:void 0),J=async()=>{await me(t,{verbose:p});let T=await ht(t,{describe:!0,verbose:d,filter:R||"",testIdLike:x||void 0,onlyGlob:E||void 0,subtreeRoot:P||void 0,compact:I,hideXy:w,includeOccluded:M,fullText:r}),O=T?.tree,H=T?.shell,K=T?.keyboard;if(r){B({shell:H,tree:O??"",keyboard:K});return}if(H&&typeof H=="object"){let q=[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);q.length>0&&console.log(` shell: ${q.join(" ")}`)}if(typeof O=="string"&&O.startsWith("__SUBTREE_NOT_FOUND__:")){let q=O.slice(22);console.log(` subtree root not found: ${q}`),Q("subtree-root-not-found",q);return}if(!O){let q=T?.nodeCount??0;console.log(" no matching nodes found"),!(R||x||E||P)&&q<10&&Q("app-still-loading",q);return}let ee=O,te=0;if(g&&typeof ee=="string"){let q=ee.split(`
432
- `),le=[];for(let ve of q){if(ve.includes("(clipped:")){te+=1;continue}le.push(ve)}ee=le.join(`
433
- `)}console.log(ee),te>0&&console.log(` ${te} clipped row(s) hidden (omit --no-clipped to see)`);let ie=R||x||E||P;if((R||x||E)&&!b&&Q("describe-filter-context"),!ie&&!b&&O.split(`
434
- `).length>=80&&Q("describe-use-filters"),K&&K.visible){let q=K.spec,le=[q?.keyboardType?`type=${q.keyboardType}`:null,q?.returnKeyType&&q.returnKeyType!=="default"?`return=${q.returnKeyType}`:null,K.mode!=="letters"?`mode=${K.mode}`:null,K.shifted?"shift":null,K.capsLock?"caps":null,q?.autoCapitalize&&q.autoCapitalize!=="sentences"?`autoCap=${q.autoCapitalize}`:null,K.accessoryBarId?`accessory=${K.accessoryBarId}`:null].filter(Boolean);console.log(`
435
- keyboard: ${le.join(" ")||"visible"}`)}};if(b)for(console.log(` watching... (Ctrl+C to stop)
436
- `);;)console.clear(),await J(),await oe(h);else await J()}async function eo(e){let{bridge:t,args:s,effectiveArgs:i,positional:d,inspectUsage:r}=e,p=T=>{let O=i.indexOf(T);return O>=0&&O+1<i.length?i[O+1]:null},b=T=>i.includes(T),h=p("--testid")||p("--test-id"),I=p("--role"),w=p("--type"),g=p("--text"),M=b("--pressable"),x=b("--visible"),_=b("--interactive-targets")||b("--actions"),P=!h&&!I&&!w&&!g&&!M&&!x&&!_?d[1]:null,c=g??P,D=await $t(t,{testId:h,role:I,type:w,text:c,pressable:M,visible:x,interactive:_});D||(console.error(r("find","<text> | --text <t> | --testid <id> | --role <r> | --type <t> | --pressable | --visible | --interactive-targets")),process.exit(1));let{mode:R,result:E}=D,J=C(s),U=s.includes("--verbose")||s.includes("--dump");if(J)R==="interactive-targets"&&Array.isArray(E)?B(Ce(E).map(T=>({...T,tap:je(T)}))):B(E??null);else if(Array.isArray(E))if(E.length===0){console.log(` no ${R} nodes found`);let T=await t.send({type:"evaluate",code:"(async () => (await window.__sootsimTest?.getNodeCount?.()) || 0)()"});typeof T=="number"&&T<10&&Q("app-still-loading",T)}else if(R==="interactive-targets"){let T=Ce(E);console.log(` found ${T.length} interactive target${T.length===1?"":"s"} (sorted by score):`);for(let O of T.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)}"`:"",Se=O.accessibilityRole?`[${O.accessibilityRole}]`:O.type,q=je(O);console.log(` ${Se}${ee}${ie}${te} ${K} ${H}`),console.log(` \u2192 ${q}`),U&&console.log(Ve(JSON.stringify(O,null,2)," "))}T.length>20&&console.log(` ... and ${T.length-20} more`)}else{console.log(` found ${E.length} node${E.length===1?"":"s"} (${R}):`);for(let T of E.slice(0,20)){let O=T.absolutePosition?`@(${Math.round(T.absolutePosition.x)},${Math.round(T.absolutePosition.y)})`:"",H=T.layout?`${Math.round(T.layout.width)}x${Math.round(T.layout.height)}`:"?x?",K=T.text?` "${T.text.slice(0,30)}"`:"",ee=T.testID?` #${T.testID}`:"",te=T.pressable?" (tap)":"",ie=T.accessibilityRole?`[${T.accessibilityRole}]`:T.type;console.log(` ${ie}${K}${ee} ${H} ${O}${te}`),U&&console.log(Ve(JSON.stringify(T,null,2)," "))}E.length>20&&console.log(` ... and ${E.length-20} more`)}else if(E==null)console.log(` not found: ${c||h||I||w||""||R}`),h&&Q("wait-selector-for-missing-testid",h);else{let T=E;if(T.type&&T.absolutePosition){let O=`@(${Math.round(T.absolutePosition.x)},${Math.round(T.absolutePosition.y)})`,H=T.layout?`${Math.round(T.layout.width)}x${Math.round(T.layout.height)}`:"?x?",K=T.text?` "${T.text.slice(0,40)}"`:"",ee=T.testID?` #${T.testID}`:"",te=T.pressable?" (tap)":"",ie=T.accessibilityRole?`[${T.accessibilityRole}]`:T.type;console.log(` ${ie}${K}${ee} ${H} ${O}${te}`),U&&console.log(Ve(JSON.stringify(T,null,2)," "))}else console.log(JSON.stringify(E,null,2))}}function Ve(e,t){return e.split(`
437
- `).map(s=>t+s).join(`
438
- `)}async function to(e){let{bridge:t,args:s}=e,i=C(s);await me(t,{verbose:!i});let d=s.includes("--styling"),r=s.indexOf("--filter"),p=r>=0?s[r+1]:void 0,b=await bt(t,{styling:d,filter:p});if(i){B({count:b.length,elements:b});return}console.log(` layout (${b.length} element${b.length===1?"":"s"}):
439
- `),console.log(wt(b,{styling:d}))}async function oo(e,t={}){let s=await Ot(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:d,mode:r,shifted:p,capsLock:b,accessoryBarId:h}=s,I=[];I.push(`keyboard: ${i?"visible":"hidden"}`),d?(I.push(` type: ${d.keyboardType}`),I.push(` returnKey: ${d.returnKeyType}`),I.push(` autoCap: ${d.autoCapitalize}`),I.push(` autoCorrect: ${d.autoCorrect?"on":"off"}`),I.push(` appearance: ${d.keyboardAppearance}`),d.secureTextEntry&&I.push(" secureTextEntry: true"),d.enablesReturnKeyAutomatically&&I.push(` return: ${d.currentTextIsEmpty?"disabled (empty)":"enabled"}`)):I.push(" spec: <none> (shown via dev-tools with no TextInput)"),I.push(` mode: ${r}${p?" (shifted)":""}${b?" (caps)":""}`),h&&I.push(` accessoryBar: ${h}`),console.log(I.join(`
440
- `))}async function so(e){let t=await e.bridge.listSims(),s=e.args.includes("--all"),i=e.args.find((b,h)=>e.args[h-1]==="--bundle"),d=e.args.find((b,h)=>e.args[h-1]==="--app-port"),r=e.args.includes("--primary"),p=t.filter(b=>!(r&&!b.isPrimary||i&&!(b.url??"").includes(i)||d&&!(b.url??"").includes(`/rn/${d}`)||!s&&!i&&!d&&!r&&!(b.url&&(b.url.includes("bundle=")||b.url.includes("/index.bundle")))&&b.id!==e.simId));if(C(e.args)){B(p.map(b=>({...b,active:b.id===e.simId})));return}Dt(p,e.simId),p.length<t.length&&!C(e.args)&&console.log(` (${t.length-p.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 ls(e,t){return t<=0?"?":`${(e/t*100).toFixed(0)}%`}function cs(e){let t={},s=(i,d)=>{d&&(d.nodesRegistered!=null&&(t[`${i}.nodes`]=d.nodesRegistered),d.nodesDetached!=null&&(t[`${i}.detached`]=d.nodesDetached),d.objects&&(t[`${i}.paragraphs`]=d.objects.paragraphs,t[`${i}.yogaNodes`]=d.objects.yogaNodes,t[`${i}.pictures`]=d.objects.pictures,t[`${i}.rasterImages`]=d.objects.rasterImages),d.imageLoader&&(t[`${i}.imageCacheEntries`]=d.imageLoader.cacheEntries,t[`${i}.imagePixelBytes`]=d.imageLoader.cachePixelBytes),d.workerHeap&&(t[`${i}.heapBytes`]=d.workerHeap.usedJSHeapSize),d.wasmHeapBytes!=null&&(t[`${i}.wasmHeapBytes`]=d.wasmHeapBytes))};return s("tenant",e.tenant),s("shell",e.shell),s("compositor",e.compositor),e.hostHeap&&(t["host.heapBytes"]=e.hostHeap.usedJSHeapSize),t}function no(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(([d,r])=>`${d}:${r}`).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)} (${ls(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 ds(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 us(e,t,s){let i=e.indexOf(t);if(i===-1)return s;let d=Number(e[i+1]);return Number.isFinite(d)&&d>0?d:s}async function ro(e,t={args:[]}){let s=C(t.args),i=t.args.indexOf("--watch");if(i===-1){let P=await We(e);if(s){B(P);return}ds(P);return}let d=Number(t.args[i+1]),r=Number.isFinite(d)&&d>0?d:60,p=us(t.args,"--interval",5),b=[],h=Date.now(),I=null;for(s||console.log(` sampling every ${p}s for ${r}s \u2014 deltas per tick:`);;){let P=await We(e),c=(Date.now()-h)/1e3,D=cs(P);if(b.push({tSec:c,counters:D}),!s){let R=[];for(let[E,J]of Object.entries(D)){let U=I&&E in I?J-I[E]:null;if(U===null||U===0)continue;let T=U>0?"+":"-",O=E.endsWith("Bytes")?`${T}${re(Math.abs(U))}`:`${T}${Math.abs(U)}`;R.push(`${E} ${no(E,J)} (${O})`)}console.log(` t+${c.toFixed(0)}s ${R.length?R.join(" "):I?"no change":Object.entries(D).map(([E,J])=>`${E} ${no(E,J)}`).join(" ")}`)}if(I=D,c>=r)break;await new Promise(R=>setTimeout(R,p*1e3))}let w=b[0],g=b[b.length-1],M=Math.max(g.tSec-w.tSec,.001),x={};for(let P of Object.keys(g.counters))P in w.counters&&(x[P]=(g.counters[P]-w.counters[P])/M);if(s){B({samples:b,perSecond:x,elapsedSec:M});return}console.log(`
441
- slope over ${M.toFixed(0)}s:`);let _=Object.entries(x).filter(([,P])=>P!==0).sort((P,c)=>Math.abs(c[1])-Math.abs(P[1]));if(_.length===0){console.log(" all counters flat");return}for(let[P,c]of _){let D=P.endsWith("Bytes")?`${re(Math.abs(c))}/s${c<0?" (shrinking)":""}`:`${c>0?"+":""}${c.toFixed(2)}/s`;console.log(` ${P.padEnd(28)}${D}`)}}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 xe(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 d=e.indexOf("--text");if(d>=0&&e[d+1])return{mode:"text",value:e[d+1]};let r=t?.[1];return r&&!r.startsWith("-")&&!Number.isFinite(Number(r))?{mode:"testid",value:r}:null}async function Ae(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 () => {
442
- const t = window.__sootsimTest
443
- if (!t) return null
444
- const n = ${i}
445
- if (!n || !n.absolutePosition || !n.layout) return null
446
- const resolved =
447
- typeof n.nodeId === 'number' && typeof t.resolveTapTarget === 'function'
448
- ? await t.resolveTapTarget(n.nodeId)
449
- : null
450
- const cx =
451
- typeof resolved?.cx === 'number'
452
- ? resolved.cx
453
- : n.absolutePosition.x + (n.layout.width || 0) / 2
454
- const cy =
455
- typeof resolved?.cy === 'number'
456
- ? resolved.cy
457
- : n.absolutePosition.y + (n.layout.height || 0) / 2
458
- return {
459
- x: cx,
460
- y: cy,
461
- id: n.id ?? null,
462
- testID: n.testID ?? null,
463
- text: ${JSON.stringify(t.mode==="text")} ? ${s} : (n.text ?? n.accessibilityLabel ?? null),
464
- type: n.type ?? null,
465
- }
466
- })()`})??null}async function io(e,t={}){let{nav:s,route:i,keyboard:d,shell:r}=await Rt(e);if(t.json){console.log(JSON.stringify({shell:r??null,nav:s,route:i,keyboard:d},null,2));return}let p=[];if(r){let b=r.activeApp??r.state??"<none>",h=r.showSwitcher?" (app switcher open)":"",I=typeof r.launchProgress=="number"&&r.launchProgress<.98?` launching (${Math.round(r.launchProgress*100)}%)`:"";p.push(`shell: ${b}${h}${I}`)}else p.push("shell: <unavailable>");if(s){let b=s.transitionPhase!=="idle"?` (${s.transitionPhase}, ${s.activeTransitionCount} active)`:"";if(p.push(`nav: phase=${s.transitionPhase}${b}`),s.screens.length===0)p.push(" <no registered screens \u2014 app may not use react-native-screens>");else for(let h of s.screens){let I=h.isActive?"\u25B6":" ",w=h.routeName?` ${h.routeName}`:"",g=h.headerHeight>0?` header=${h.headerHeight}`:"",M=h.largeTitleState&&h.largeTitleState!=="expanded"?` large-title=${h.largeTitleState}`:"";p.push(` ${I} #${h.id}${w}${g}${M}`)}}else p.push("nav: <runtime not available>");if(p.push(`route: ${i?.currentPath??"<unavailable>"}`),i?.coveringPath&&p.push(`covered: a presented screen (${i.coveringPath}) is above this route`),d&&d.visible){let b=d.spec?.keyboardType??"default",h=d.spec?.returnKeyType??"default";p.push(`keyboard: visible (${b}, return=${h}, mode=${d.mode??"?"})`)}else p.push("keyboard: hidden");console.log(p.join(`
467
- `))}async function ao(e){let{bridge:t,args:s,positional:i}=e,d=i[1]?Number(i[1])*1e3:3e3,r=s.includes("--strict"),{elapsed:p,settled:b}=await se({bridge:t,maxMs:d,strict:r});console.log(b?` settled in ${p}ms`:` timed out after ${p}ms (may still be animating)`)}async function lo(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 co(e){let{bridge:t,args:s,positional:i}=e,d=s.includes("--boxes"),r=i[1]?Number(i[1]):d?50:5,{tree:p}=await gt(t,r,d?{format:"boxes"}:void 0);if(C(s)){B({depth:r,tree:p??null});return}console.log(typeof p=="string"?p:JSON.stringify(p,null,2))}async function uo(e,t={args:[]}){let s=await yt(e);if(C(t.args)){B(s);return}console.log(s.url)}async function po(e){let{wsPort:t,commandTimeoutMs:s,simId:i,simIdSource:d,positional:r}=e,p=r[1]?Number(r[1]):30,b=Math.max(1e3,(Number.isFinite(p)?p:30)*1e3),h=Math.max(1,Math.ceil(b/500));console.log(" waiting for sim reconnect...");let I=await At(t,s,i,{attempts:h,simIdSource:d});I||(console.error(" timed out waiting for sim reconnect"),process.exit(1)),I.bridge.close(),Oe({source:"inspect wait",step:{wait:b},summary:`wait ${Math.round(b/1e3)}s`}),console.log(` ready: ${I.count} nodes`)}var mo=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 Ee(e,t){let s=e.indexOf(t);if(s>=0&&s+1<e.length)return e[s+1]}function ps(e,t){if(!t.filter&&!t.equals)return!0;let s=e.data,i=[];if(s&&typeof s=="object")for(let r of["url","displayUrl","message","name","activeName","path","pathname","title","phase","event","type","kind"]){let p=s[r];typeof p=="string"&&p.length>0&&i.push(p)}let d=i.join(" ");return t.equals?i.some(r=>r===t.equals):t.filter?d.toLowerCase().includes(t.filter.toLowerCase()):!0}async function fo(e){let{bridge:t,args:s,positional:i,inspectUsage:d}=e,r=i[1];r||(console.error(d("event","<kind> [--max-ms 5000] [--filter <substring>] [--equals <exact>] [--since now|cursor]")),process.exit(1)),mo.has(r)||console.error(` warning: '${r}' is not a known timeline kind \u2014 waiting anyway. known: ${[...mo].sort().join(", ")}`);let p=Ee(s,"--max-ms"),b=p&&Number.isFinite(Number(p))?Math.max(100,Number(p)):5e3,h=Ee(s,"--filter"),I=Ee(s,"--equals"),w=Ee(s,"--since")??"now",g=s.includes("--json"),M=Date.now(),x=M+b,_=200,P=M;for(;Date.now()<x;){let D={kinds:[r],since:w==="cursor"?void 0:P,limit:50},R=await t.send({type:"evaluate",code:`(async () => {
468
- const t = window.SootSim?.bridges?.timeline
469
- if (!t) return { ok: false, error: 'timeline bridge missing' }
470
- return { ok: true, result: await t.recent(${JSON.stringify(D)}) }
471
- })()`});(!R||!R.ok)&&(console.error(` could not query timeline: ${R&&"error"in R?R.error:"unknown"}`),process.exit(1));let E=R.result.events??[];for(let J of E)if(ps(J,{filter:h,equals:I})){let U=Date.now()-M;console.log(g?JSON.stringify({found:!0,elapsedMs:U,event:J}):` ${r} event after ${U}ms${h?` (filter: ${h})`:""}${I?` (equals: ${I})`:""}`);return}R.result.watermark&&R.result.watermark>P&&(P=R.result.watermark),await new Promise(J=>setTimeout(J,_))}let c=Date.now()-M;g?console.log(JSON.stringify({found:!1,elapsedMs:c,kind:r,filter:h,equals:I})):console.error(` \u26A0 wait event ${r} timed out after ${c}ms${h?` (filter: ${h})`:""}${I?` (equals: ${I})`:""}`),process.exit(1)}async function go(e){let{bridge:t,args:s}=e,i=s.includes("--strict"),d=Ie(s,3e3),{elapsed:r,settled:p}=await se({bridge:t,maxMs:d,strict:i});p?console.log(` idle in ${r}ms`):(console.error(` \u26A0 wait idle timed out after ${r}ms (may still be animating)`),process.exit(1))}async function yo(e){let{bridge:t,args:s}=e,i=Ie(s,2e4),{ready:d,elapsedMs:r,nodes:p,targets:b,liveFrameActive:h,liveFrameChannels:I,flag:w,loadingText:g,externalReady:M,externalError:x,suppressedEntryError:_,errors:P,bridgeError:c}=await St(t,i,{onProgress(R){console.error(` still waiting after ${R.elapsedMs}ms \u2014 ${qe(R)} (nodes: ${R.nodes}, targets: ${R.targets}, live surfaces: ${R.liveFrameActive?R.liveFrameChannels:0}, errors: ${R.errors})`)}});if(d){let R=i-r,E=Math.max(100,Math.min(1e4,R)),J=await se({bridge:t,maxMs:E,pollMs:32,stablePolls:2});J.settled||(console.error(` \u26A0 wait ready timed out after ${r+J.elapsed}ms \u2014 app mounted but did not settle (nodes: ${p}, targets: ${b})`),process.exit(1)),console.log(` ready in ${r+J.elapsed}ms: ${p} nodes, ${b} targets${h?`, ${I} live surfaces`:""}`);return}let D=qe({externalError:x,loadingText:g,externalReady:M,flag:w,targets:b,suppressedEntryError:_,bridgeError:c});console.error(` \u26A0 wait ready timed out after ${r}ms \u2014 ${D} (nodes: ${p}, targets: ${b}, live surfaces: ${h?I:0}, errors: ${P})`),process.exit(1)}async function ho(e){let{bridge:t,args:s,positional:i,inspectUsage:d}=e,r=i[1];r||(console.error(d("selector","<testid> [--max-ms 5000] [--gone]")),process.exit(1));let p=s.indexOf("--max-ms"),b=p>=0&&s[p+1]?Math.max(100,Number(s[p+1])):5e3,h=s.includes("--gone"),{found:I,node:w,elapsed:g}=await vt(t,r,b,{gone:h});if(h){I?console.log(` #${r} gone after ${g}ms`):(console.error(` \u26A0 wait selector #${r} --gone timed out after ${g??b}ms (still present)`),process.exit(1));return}if(I&&w){let M=w.absolutePosition?`@(${Math.round(w.absolutePosition.x)},${Math.round(w.absolutePosition.y)})`:"",x=w.layout?`${Math.round(w.layout.width)}x${Math.round(w.layout.height)}`:"?x?";console.log(` found #${r} in ${g}ms ${x} ${M}`)}else console.error(` \u26A0 wait selector #${r} timed out after ${g??b}ms`),process.exit(1)}function No(e){return e==null?"\u2014":e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}K`:`${(e/1024/1024).toFixed(1)}M`}function Fo(e){return e==null?" \u2026":e<1e3?`${e}ms`.padStart(5):`${(e/1e3).toFixed(2)}s`.padStart(5)}function bo(){process.stderr.write(` the sim is not responding. recover it with:
472
- rnx close --sim <id> # force-close the wedged sim
473
- rnx list # confirm it's gone
474
- `)}async function $e(e,t){let s=await e.send({type:"perform",steps:[t]}),i=s?.steps?.[0],d=i?.error??s?.error;return{ok:s?.ok===!0,value:i?.value,...d?{error:d}:{}}}async function fs(e){try{return await e.send({type:"evaluate",code:"1"},{timeoutMs:3e3}),!0}catch{return!1}}async function gs(e,t){try{let s=await e.send({type:"evaluate",code:`(async () => {
475
- const t = window.__sootsimTest
476
- if (!t || typeof t.queryAll !== 'function') return []
477
- try {
478
- // queryAll is async in render-worker mode (the canonical mode now)
479
- // because the call has to round-trip the worker \u2014 must await it.
480
- // a sync result is still handled fine since await on a non-Promise
481
- // is a no-op.
482
- const nodes = await t.queryAll({})
483
- if (!Array.isArray(nodes)) return []
484
- const out = new Set()
485
- for (const n of nodes) {
486
- const id = n && (n.testID || n.id)
487
- if (typeof id === 'string' && id) out.add(id)
488
- }
489
- return Array.from(out)
490
- } catch {
491
- return []
492
- }
493
- })()`});if(!Array.isArray(s)||s.length===0)return;let i=t.toLowerCase(),d=s.map(r=>({id:r,score:ys(i,r.toLowerCase())})).filter(r=>r.score<i.length+4).sort((r,p)=>r.score-p.score).slice(0,5);if(d.length===0)return;console.error(" similar testIDs:");for(let r of d)console.error(` ${r.id}`)}catch{}}function ys(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 hs(e,t)-s}function hs(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 d=0;d<=t.length;d++)s[d]=d;for(let d=1;d<=e.length;d++){i[0]=d;for(let p=1;p<=t.length;p++)i[p]=Math.min(s[p]+1,i[p-1]+1,s[p-1]+(e[d-1]===t[p-1]?0:1));let r=s;s=i,i=r}return s[t.length]}function bs(e){return e.error?"err":e.status==null?" \u2026 ":String(e.status)}function wo(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 xo(e){let t=ae(e.startTs),s=bs(e).padEnd(3),i=e.method.padEnd(5),d=No(e.size).padStart(6),r=Fo(e.durationMs);console.log(` [${t}] ${s} ${i} ${d} ${r} ${e.displayUrl}`),e.error&&console.log(` error: ${e.error}`)}function ws(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",Fo(e.durationMs).trim()],["size",No(e.size)],["content-type",e.type??"\u2014"]];for(let[s,i]of t)console.log(` ${s.padEnd(13)} ${i}`)}var xs={error:"\x1B[31m",warn:"\x1B[33m",info:"\x1B[36m",debug:"\x1B[35m",log:"\x1B[37m"},$o="\x1B[0m",$s="\x1B[2m";function So(e,t){let s=ae(e.ts),i=e.level.toUpperCase().padEnd(5),d=e.args.join(" ");if(t){let r=xs[e.level];console.log(` ${$s}[${s}]${$o} ${r}${i}${$o} ${d}`)}else console.log(` [${s}] ${i} ${d}`);if(e.stack&&e.level==="error"){let r=e.stack.split(`
494
- `).slice(0,5);for(let p of r)console.log(` ${p.trim()}`)}}var Ss=120;async function vo(e,t){let s=e.find((M,x)=>e[x-1]==="--id"),i=e.find((M,x)=>e[x-1]==="--text");if(s||i){let M=await t.send({type:"evaluate",code:Bt({id:s,text:i})});if(!M)throw new Error(s?`no node with id "${s}"`:`no node matching text "${i}"`);let{x,y:_,w:P,h:c}=M;return{x,y:_,w:P,h:c}}let d=e.find((M,x)=>e[x-1]==="--area");if(d){let M=d.split(",").map(D=>Number(D.trim()));if(M.length!==4||M.some(D=>!Number.isFinite(D)))throw new Error(`--area expects x,y,w,h (got "${d}")`);let[x,_,P,c]=M;return{x,y:_,w:P,h:c}}let r=M=>{let x=e.find((P,c)=>e[c-1]===M);if(x==null)return null;let _=Number(x);return Number.isFinite(_)?_:null},p=r("--x"),b=r("--y"),h=r("--w"),I=r("--h");if(p!=null||b!=null||h!=null||I!=null)return{x:p??0,y:b??0,w:h??1,h:I??1};let g=e.filter((M,x)=>x>0&&!M.startsWith("-")&&e[x-1]!=="--output"&&e[x-1]!=="--area"&&e[x-1]!=="--id"&&e[x-1]!=="--text"&&e[x-1]!=="--x"&&e[x-1]!=="--y"&&e[x-1]!=="--w"&&e[x-1]!=="--h").map(Number).filter(M=>Number.isFinite(M));if(g.length>=2){let[M,x,_=1,P=1]=g;return{x:M,y:x,w:_,h:P}}return null}function ko(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 Io(e){let t=e.avgMs>0?(1e3/e.avgMs).toFixed(1):"?",s=e.jank&&typeof e.jank=="object"?e.jank:null,i=e.compositorProduction&&typeof e.compositorProduction=="object"?e.compositorProduction:null,d=i?.budgetMs??8;if(console.log(` shell frame profile:
495
- `),s){let M=(Array.isArray(s.compositor)?s.compositor:[]).reduce((x,_)=>x+(_.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 ${M} \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}%) >${d}ms \xB7 max ${s.shell?.maxMs??0}ms`);for(let g of Array.isArray(s.compositor)?s.compositor:[])console.log(` ${String(g.surfaceId).padEnd(12)} ${g.jankPaints}/${g.sampledPaints} compositor paints (${g.jankPct}%) >${d}ms \xB7 max ${g.maxMs}ms`)}else console.log(` jank: ${e.jankFrames} frames (${e.jankPct}%) >${d}ms`);if(console.log(` avg per frame: overlay ${e.avgOverlayMs}ms \xB7 aux ${e.avgAuxMs}ms \xB7 layout ${e.avgLayoutMs}ms`),i){let g=i.frames??{};console.log(""),console.log(` compositor production (${d}ms budget):`),console.log(` frames: ${g.count??0} \xB7 avg ${Number(g.avg??0).toFixed(2)} / p95 ${Number(g.p95??0).toFixed(2)} / max ${Number(g.max??0).toFixed(2)} ms \xB7 ${i.overBudget??0} over budget (${i.overBudgetPct??0}%)`);let M=[["javascript","javascript"],["layout","layout"],["paint","paint"],["prewarm","prewarm"],["texture upload","textureUpload"],["gpu submit","gpuSubmit"],["composite","composite"],["capture/readback","capture"]];for(let[P,c]of M){let D=i.phases?.[c];!D?.count||!D.max&&!D.avg||console.log(` ${P.padEnd(16)} avg ${Number(D.avg??0).toFixed(2)} / p95 ${Number(D.p95??0).toFixed(2)} / max ${Number(D.max??0).toFixed(2)} ms`)}let x=i.captureBetweenFrames;x?.count&&x.max>0&&console.log(` capture between p95 ${Number(x.p95??0).toFixed(2)} / max ${Number(x.max??0).toFixed(2)} ms between compositor rAF callbacks`);let _=Array.isArray(i.worstFrames)?i.worstFrames.slice(0,5):[];if(_.length>0){console.log(" worst frames:");for(let P of _){let c=P.phases??{};console.log(` ${Number(P.productionMs??0).toFixed(2)}ms frame ${P.frameToken??"?"} \xB7 js ${Number(c.javascriptMs??0).toFixed(2)} \xB7 layout ${Number(c.layoutMs??0).toFixed(2)} \xB7 paint ${Number(c.paintMs??0).toFixed(2)} \xB7 prewarm ${Number(c.prewarmMs??0).toFixed(2)} \xB7 upload ${Number(c.textureUploadMs??0).toFixed(2)} \xB7 submit ${Number(c.gpuSubmitMs??0).toFixed(2)} \xB7 composite ${Number(c.compositeMs??0).toFixed(2)} \xB7 capture ${Number(c.captureMs??0).toFixed(2)}`)}}}let r=e.cadence;r&&typeof r=="object"&&(console.log(""),console.log(` cadence (frame delivery, ${r.vsyncTicks} vsync ticks):`),console.log(` display clock: ${r.displayHz}hz \xB7 host rAF interval p50 ${r.hostIntervalP50} / p95 ${r.hostIntervalP95} / max ${r.hostIntervalMax} ms${r.hostGaps?` \xB7 ${r.hostGaps} gaps >1.5x (host rAF starved)`:""}`),console.log(` delivery lag: p50 ${r.deliveryLagP50} / p95 ${r.deliveryLagP95} / max ${r.deliveryLagMax} ms (vsync postMessage \u2192 shell receipt)`),console.log(` paint interval: p50 ${r.paintIntervalP50} / p95 ${r.paintIntervalP95} / max ${r.paintIntervalMax} ms${r.idleBreaks?` \xB7 ${r.idleBreaks} idle breaks excluded`:""}`));let p=e.compositorCadence;if(p&&typeof p=="object"){console.log(` compositor rAF: p50 ${p.p50} / p95 ${p.p95} / max ${p.max} ms \xB7 ${p.gaps} gaps >1.5x`);let g=(M,x)=>{x?.count&&console.log(` ${M}: ${x.count} samples \xB7 p50 ${x.p50.toFixed(2)} / p95 ${x.p95.toFixed(2)} / max ${x.max.toFixed(2)} ms`)};g("engine-empty rAF",p.phases?.uninterruptedEngineEmpty),g("rAF with CanvasKit flush",p.phases?.withCanvaskitFlush),g("rAF after CanvasKit flush",p.phases?.afterCanvaskitFlush),g("CanvasKit submission",p.canvaskitSubmission)}let b=Array.isArray(e.auxSurfaces)?e.auxSurfaces:[],h=e.graphiteCaches,I=e.decodedImageCache;if(h||I){let g=(M,x)=>{if(typeof x?.bytes!="number"||typeof x.limitBytes!="number")return;let _=typeof x.purgeableBytes=="number"?` \xB7 ${(x.purgeableBytes/1024/1024).toFixed(1)}MB purgeable`:"";console.log(` ${M.padEnd(29)} ${(x.bytes/1024/1024).toFixed(1)}MB/${(x.limitBytes/1024/1024).toFixed(1)}MB${_}`)};console.log(""),console.log(" device-wide caches:"),g("Graphite context resources",h?.contextResources??null),g("Graphite recorder resources",h?.recorderResources??null),g("Graphite image provider",h?.imageProvider??null),g("decoded image pixels",I??null),h?.imageProvider&&console.log(` ${"".padEnd(29)} ${h.imageProvider.entries} entries \xB7 ${h.imageProvider.uploads} uploads \xB7 ${h.imageProvider.evictions} evictions`),I&&console.log(` ${"".padEnd(29)} ${I.entries} entries/${I.maxEntries} max`)}if(b.length>0){console.log(""),console.log(" surfaces (last 100 frames):");for(let g of b)console.log(` ${String(g.surfaceId).padEnd(10)} ${String(g.frames).padStart(4)} paints avg ${g.avgMs}ms (layout ${g.avgLayoutMs}, render ${g.avgRenderMs}, flush ${g.avgFlushMs}) max ${g.maxMs}ms`)}ko("shell worker",e.renderProfile),ko("compositor worker",e.compositorRenderProfile);let w=Array.isArray(e.worstFrames)?e.worstFrames:[];if(w.length>0){console.log(""),console.log(" worst observations (shell and compositor series are unpaired):");for(let g of w){if(g.source==="compositor"){console.log(` ${String(g.totalMs).padStart(7)}ms compositor ${g.surfaceId} paint ${g.paint} \xB7 layout ${g.layoutMs} \xB7 render ${g.renderMs} \xB7 flush ${g.flushMs}`);continue}let M=(g.auxSurfaces??[]).map(x=>`${x.surfaceId} ${x.totalMs}ms (layout ${x.layoutMs}, render ${x.renderMs})`).join(" \xB7 ");console.log(` ${String(g.totalMs).padStart(7)}ms overlay ${g.overlayMs} \xB7 aux ${g.auxMs} \xB7 layout ${g.layoutMs}${M?` [${M}]`:""}`)}}}async function _e(e,t,s){let i=Date.now()+t,d=await pe(e,t);for(;;){if(s(d))return{settled:!0,state:d};if(Date.now()>=i)return{settled:!1,state:d};await oe(16),d=await pe(e)}}async function ot(e){return e.send({type:"evaluate",code:`(async () => {
496
- const kb = window.__sootsimKeyboard
497
- const test = window.__sootsimTest
498
- if (!kb) return { error: 'keyboard bridge not available' }
499
- const layout = typeof kb.getLayout === 'function' ? kb.getLayout() : null
500
- const secureTextEntry =
501
- !!layout?.spec?.secureTextEntry && layout?.spec?.keyboardType !== 'visible-password'
502
- const visible = kb.isVisible()
503
- const mode = kb.getMode()
504
- let focused = null
505
- if (test && typeof test.getFocusedNode === 'function') {
506
- try {
507
- focused = await test.getFocusedNode()
508
- } catch {}
509
- }
510
- let runtimeSnapshot = null
511
- if (test && typeof test.getFocusKeyboardSnapshot === 'function') {
512
- try {
513
- runtimeSnapshot = await test.getFocusKeyboardSnapshot()
514
- } catch {}
515
- }
516
- return {
517
- visible,
518
- mode,
519
- layout,
520
- hostedEditorFocused:
521
- typeof kb.hasHostedEditorFocus === 'function' && kb.hasHostedEditorFocus(),
522
- focusedInput: focused ? {
523
- nodeId: focused.nodeId ?? null,
524
- testID: focused.testID || null,
525
- id: focused.id || null,
526
- placeholder: focused.placeholder || null,
527
- secureTextEntry,
528
- text: secureTextEntry ? ${JSON.stringify(Z)} : (focused.text || null),
529
- } : null,
530
- phase: runtimeSnapshot?.keyboard?.phase ?? null,
531
- frame: runtimeSnapshot?.keyboard?.frame ?? null,
532
- focusedRect: runtimeSnapshot?.focused?.rect ?? null,
533
- }
534
- })()`}).then(t=>et(t))}function vs(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 ks(e,t=600,s={}){let i=Date.now()+t;for(;Date.now()<=i;){let d=await ot(e);if(vs(d,s.targetId??null,s.secureTextEntry??null))return d;await oe(30)}return ot(e)}async function De(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 rnx do tap-id/tap-text or rnx do type-into.`),process.exit(1)}async function To(e,t,s){return t==="appearance"?e.send({type:"evaluate",code:`(async () => {
535
- const requested = ${JSON.stringify(s??"toggle")}
536
- // the engine owns toggle + auto resolution (settingsStore is the single
537
- // source of truth). never infer the current scheme client-side \u2014 the old
538
- // documentElement '#333333' sniff is never set in embedded / shell-chrome
539
- // contexts, so 'toggle' read 'light' forever and stuck on the boot scheme.
540
- window.postMessage({ type: 'contrast-action', action: 'set-appearance', value: requested }, '*')
541
- // let the engine's message handler apply + publish window.__sootsimColorScheme
542
- await new Promise((r) => setTimeout(r, 60))
543
- const applied = window.__sootsimColorScheme?.resolved
544
- ?? (window.matchMedia?.('(prefers-color-scheme: dark)')?.matches ? 'dark' : 'light')
545
- const setting = window.__sootsimColorScheme?.setting ?? requested
546
- return { ok: true, requested, setting, applied }
547
- })()`}):t==="lock"?e.send({type:"evaluate",code:`(async () => {
548
- const toggleLock = window.SootSim?.bridges?.mainShell?.toggleLock
549
- if (typeof toggleLock !== 'function') {
550
- throw new Error('rnx mainShell.toggleLock bridge unavailable')
551
- }
552
- await toggleLock()
553
- return { ok: true, action: 'lock' }
554
- })()`}):e.send({type:"evaluate",code:`(async () => {
555
- window.dispatchEvent(new CustomEvent('sootsim:shake'))
556
- return { ok: true, action: 'shake' }
557
- })()`})}function Is(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 Ts(e){if(typeof e!="string")return null;let t=e.replace(/\s+/g," ").trim();return t?t.slice(0,80):null}function Po(...e){for(let t of e){if(typeof t!="string")continue;let s=t.trim();if(s)return s}return null}function Ms(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 `rnx maestro keep` to commit"))}function Mo(e,t,s){if(!s||s.hit===!1)return null;let i=Po(s.responderTestID,s.testID);if(i)return{step:{tapOn:{id:i}},summary:`tap #${i}`};let d=Ts(s.text);return d?{step:{tapOn:d},summary:`tap "${d}"`}:{step:{tapAtCoords:{x:e,y:t}},summary:`tap @${Math.round(e)},${Math.round(t)}`}}function tt(e,t,s){let i=Po(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 Ar(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,d=ct(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"]}),r=d.positional,p=r[0],b=s,h=typeof i[0]=="string"&&st.has(i[0]),I=h?i[0]:null,w=S=>{if(t.internalPerfCommand&&S==="perf")return`rnx perf ${t.internalPerfCommand}`;if(h&&S===i[0])return`rnx ${S}`;let o=b??nt(S)?.group;return o?`rnx ${o} ${S}`:`rnx ${S}`},g=(S,o)=>` usage: ${w(S)}${o?` ${o}`:""}`;if(!p||e.includes("--help")||e.includes("-h")){let S={bridgePort:7668,defaultShellUrl:at};if(b==="do"||b==="get"||b==="debug"||b==="wait"){let n=Be(b,S);n&&(console.log(`${n}
558
- `),process.exit(0))}if(I==="shell"){let n=rt("shell",S);n&&(console.log(`${n}
559
- `),process.exit(0))}let o=["do","get","debug","wait"].map(n=>Be(n,S)).filter(n=>n!=null).join(`
560
-
561
- `);console.log(`${o}
562
- `),process.exit(0)}let M=d.wsPort,x=d.simId,_=d.simIdSource,P=d.commandTimeoutMs;if(b==="get"&&p==="diagnosis"){let S=i.indexOf("diagnosis"),o=S>=0?[...i.slice(0,S),...i.slice(S+1)]:i,{runDiagnose:n}=await import("./diagnose-RRCBLP6E.js"),a=await n(["recent",...o],t);process.exitCode=a;return}if(b==="do"&&p==="scan"){let{runCamera:S}=await import("./camera-4JHCYBQS.js");process.exitCode=await S(i,{port:t.port});return}if(p==="list"&&i.some(S=>S==="--drivers"||S==="-D")){let{buildDriverListRows:S}=await import("./drivers-W6E3BZH4.js"),o=S();console.log(` available drivers (${o.length}):
563
- `);let n=Math.max(...o.map(l=>l.id.length),6),a=Math.max(...o.map(l=>l.kind.length),4);for(let l of o){let u=l.available?"\u2713":"\u2717",m=l.id.padEnd(n),f=l.kind.padEnd(a);console.log(` ${u} ${m} ${f} ${l.description}`),l.available&&l.detail?console.log(` ${l.detail}`):!l.available&&l.reason&&console.log(` unavailable: ${l.reason}`)}return}let c=dt(d),D=x||"default",R=new Set(["errors","warnings","requests","js","reload","globals","perf","storage-clear","list","wait","sleep"]),E=200;function J(S){let o=S.replace(/\s+/g," ").trim();if(!o)return"";if(/^<(!doctype html|html|\?xml)|<body[\s>]/i.test(o)){let a=/<title[^>]*>([^<]+)<\/title>/i.exec(S)?.[1]?.trim(),l=/<body[^>]*>([\s\S]*?)<\//i.exec(S)?.[1]?.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().slice(0,80),u=a||l||"html error page";return`<html ${S.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(S){let o=S.displayUrl||S.url;return S.status!=null?`${S.method} ${o} -> ${S.status}${S.statusText?` ${S.statusText}`:""}`:S.error?`${S.method} ${o} -> ${S.error}`:`${S.method} ${o}`}async function T(S){let o=ue()?400:200;try{let{settled:n,elapsed:a}=await se({bridge:S,maxMs:o,pollMs:32,stablePolls:2});n||process.stderr.write(` \u26A0 auto-wait timed out after ${a??o}ms \u2014 next command may see mid-animation state. use \`rnx do settle\` for a longer wait.
564
- `)}catch{}}function O(S,o){if(o.result?.reason==="offscreen"){let{x:n,y:a,screen:l}=o.result;console.error(` tap failed: ${S} resolved to (${Math.round(n)},${Math.round(a)}), outside the ${l?.width}x${l?.height} screen`),console.error(" the node exists but is scrolled out of view \u2014 scroll it on-screen first (rnx do scroll / swipe), then tap.");return}console.error(` tap failed: ${S} 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 c.send({type:"evaluate",code:`(() => ({
565
- console: ${Te},
566
- requests: window.__sootsimTest?.getRequestCounts?.() || null,
567
- }))()`})||{console:null,requests:null}}catch{return{console:null,requests:null}}}async function K(S={}){let o=S.counts!==void 0?S.counts:await X(c,"getRequestCounts");if(!o||typeof o!="object")return;let n=Math.max(0,Number(o.failed)||0);if(n===0||!S.includeTail&&!Ye("requests",D,String(n))||(console.log(`
568
- network: ${n} failed request${n===1?"":"s"}`),console.log(` inspect: ${w("requests")} 5`),!S.includeTail))return;let a=await X(c,"getFailedRequests",5);if(!(!Array.isArray(a)||a.length===0)){console.log(`
569
- recent failed requests:
570
- `);for(let l of a){let u=ae(l.timestamp);console.log(` [${u}] ${U(l)}`),l.responseBody?console.log(` ${J(l.responseBody)}`):l.error&&console.log(` ${l.error}`)}}}function ee(S){for(let o of S){let n=o.title?` (\u201C${o.title}\u201D)`:"";console.error(`
571
- note: ${o.label} is open${n} \u2014 taps/drags hit it, not the app`)}}async function te(S={}){let o=S.counts!==void 0?S.counts:await c.send({type:"evaluate",code:Te});if(!o||typeof o!="object")return;let n=o,a=Math.max(0,Number(n.errors)||0),l=Math.max(0,Number(n.warnings)||0);if(a===0&&l===0||!S.includeTail&&!Ye("console",D,`${a}:${l}`))return;let u=[];if(a>0&&u.push(`${a} console error${a===1?"":"s"}`),l>0&&u.push(`${l} console warning${l===1?"":"s"}`),console.error(`
572
- console: ${u.join(", ")}`),console.error(` inspect: ${w("errors")} 5`),l>0&&console.error(` inspect: ${w("warnings")} 5`),!S.includeTail||a===0)return;let m=await ge(c,5);if(!(!Array.isArray(m)||m.length===0)){console.error(`
573
- recent console errors:
574
- `);for(let f of m){let $=ae(f.timestamp),y=Array.isArray(f.args)?f.args.map(k=>typeof k=="object"?JSON.stringify(k):String(k)).join(" "):String(f);console.error(` [${$}] ${y}`)}}}let ie=["console","fetch","toast","alert","notification","screen","app-launch","keyboard","route","actionsheet","picker","shell","scroll","gesture","text-input","animation","reanimated"];async function Se(S){let o=it(),n=null;try{n=await pt(S,`(() => {
575
- const tl = window.SootSim && window.SootSim.bridges && window.SootSim.bridges.timeline
576
- if (!tl || typeof tl.summary !== 'function') return null
577
- const cursorKey = ${JSON.stringify(o)}
578
- const summary = tl.summary({ sinceCursor: cursorKey })
579
- let consoleSplit = null
580
- if (summary && summary.byKind && summary.byKind.console) {
581
- const events = tl.recent({ sinceCursor: cursorKey, kinds: 'console', limit: 100000 }).events
582
- consoleSplit = { error: 0, warn: 0 }
583
- for (const ev of events) {
584
- const lvl = ev && ev.data && ev.data.level
585
- if (lvl === 'error') consoleSplit.error++
586
- else if (lvl === 'warn') consoleSplit.warn++
587
- }
588
- }
589
- return summary ? { summary, consoleSplit } : null
590
- })()`)}catch{return}if(!n||!n.summary||!n.summary.total)return;let a=n.summary.byKind??{},l=[],u=new Set;for(let m of ie){let f=a[m];if(f)if(u.add(m),m==="console"&&n.consoleSplit){let{error:$,warn:y}=n.consoleSplit;$>0&&l.push(`${$} error${$===1?"":"s"}`),y>0&&l.push(`${y} warning${y===1?"":"s"}`)}else l.push(`${f} ${m}${f===1?"":"s"}`)}for(let[m,f]of Object.entries(a))!u.has(m)&&f&&l.push(`${f} ${m}${f===1?"":"s"}`);if(l.length!==0&&(console.error(`
591
- since last: ${l.join(" \xB7 ")} \u2014 rnx what-happened`),n.summary.lastAt))try{await ce(S,"SootSim.bridges.timeline.cursorAdvance",o,n.summary.lastAt)}catch{}}let q=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"]),ve=(e.includes("--verbose")||e.includes("-v"))&&!e.includes("--json");b==="do"&&p==="shell"&&(console.error(" `rnx do shell` was removed. use `rnx shell ...` instead."),process.exit(1)),q.has(p)&&await ut(c),le.has(p)&&await me(c,{verbose:ve});try{let S=q.has(p)?await Pt(c):[];switch(p){case"list":{lt(d.wsPort),await so({bridge:c,simId:x,args:i});break}case"tree":{await co({bridge:c,args:i,positional:r});break}case"a11y":{let o=await xt(c);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):
592
- `);for(let n of o){let a=[];if(a.push(`[${n.role}]`),n.label){let l=n.label.length>50?n.label.slice(0,47)+"...":n.label;a.push(`"${l}"`)}if(n.hint&&a.push(`(hint: "${n.hint}")`),n.testID&&a.push(`#${n.testID}`),n.state){let l=[];n.state.disabled&&l.push("disabled"),n.state.selected&&l.push("selected"),n.state.checked===!0&&l.push("checked"),n.state.checked==="mixed"&&l.push("mixed"),n.state.busy&&l.push("busy"),n.state.expanded===!0&&l.push("expanded"),n.state.expanded===!1&&l.push("collapsed"),l.length&&a.push(`{${l.join(", ")}}`)}n.position&&a.push(`@(${n.position.x},${n.position.y})`),n.size&&a.push(`${n.size.w}x${n.size.h}`),console.log(" "+a.join(" "))}}break}case"find":{await eo({bridge:c,args:e,effectiveArgs:i,positional:r,inspectUsage:g});break}case"count":{await Qt(c,{args:i});break}case"keyboard":{await oo(c,{json:e.includes("--json")});break}case"screens":{await io(c,{json:e.includes("--json")});break}case"memory":{await ro(c,{args:i});break}case"wait":{await po({wsPort:M,commandTimeoutMs:P,simId:x,simIdSource:_,positional:r});break}case"sleep":{await lo({positional:r,inspectUsage:g});break}case"settle":{await ao({bridge:c,args:e,positional:r});break}case"ready":{await yo({bridge:c,args:e});break}case"idle":{await go({bridge:c,args:e,positional:r});break}case"selector":{await ho({bridge:c,args:e,positional:r,inspectUsage:g});break}case"event":{await fo({bridge:c,args:e,positional:r,inspectUsage:g});break}case"layout":{let o=r[1];if(!o){await to({bridge:c,args:i});break}let n=await c.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(($,y)=>e[y-1]==="--output")||"/tmp/sootsim-inspect.png",a=await vo(e,c),l={type:"screenshot"};a&&(l.crop=a);let m=(await c.send(l)).replace(/^data:image\/png;base64,/,"");a&&console.log(` area: x=${a.x} y=${a.y} w=${a.w} h=${a.h}`),(await import("fs")).writeFileSync(n,Buffer.from(m,"base64")),console.log(` saved: ${n}`);break}case"sample-color":{let o=await vo(e,c);o||(console.error(g("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 c.send({type:"evaluate",code:Ct(o)});if(e.includes("--json"))console.log(JSON.stringify(n,null,2));else{let{r:a,g:l,b:u,a:m,hex:f,samples:$}=n,y=o.w===1&&o.h===1?`@(${o.x},${o.y})`:`@(${o.x},${o.y}) ${o.w}x${o.h}`;console.log(` ${f} rgba(${a}, ${l}, ${u}, ${m}) ${y} ${$} samples`)}break}case"node":{let o=r[1];o||(console.error(g("node","<matcher>")),console.error(" resolves testID, id, then text \u2014 dumps full node info as JSON"),process.exit(1));let n=await c.send({type:"evaluate",code:`(async () => {
593
- const t = window.__sootsimTest
594
- const q = ${JSON.stringify(o)}
595
- let node = null
596
- let via = null
597
- if (t.findByTestId) { node = await t.findByTestId(q); if (node) via = 'testID' }
598
- if (!node && t.findById) { node = await t.findById(q); if (node) via = 'id' }
599
- if (!node && t.findByText) { node = await t.findByText(q); if (node) via = 'text' }
600
- if (!node) return { matcher: q, found: false }
601
-
602
- // read the resolved transform (if any) off the style \u2014 useful
603
- // because canvas nodes often animate via transform and describe
604
- // output strips that.
605
- const transform =
606
- node.style && Array.isArray(node.style.transform)
607
- ? node.style.transform
608
- : node.style && node.style.transform
609
- ? node.style.transform
610
- : null
611
-
612
- // parent chain \u2014 walk up from the node so the JSON dump is
613
- // self-describing.
614
- const parentChain = []
615
- const root = window.__sootsimRoot
616
- if (root && node.id != null) {
617
- const findPath = (n, targetId, path) => {
618
- if (!n) return null
619
- if (n.id === targetId) return path
620
- if (n.children) {
621
- for (const child of n.children) {
622
- const nextPath = [
623
- ...path,
624
- {
625
- type: n.type || 'view',
626
- testID: n.props?.testID || null,
627
- text: n.text || null,
628
- },
629
- ]
630
- const found = findPath(child, targetId, nextPath)
631
- if (found) return found
632
- }
633
- }
634
- return null
635
- }
636
- const chain = findPath(root, node.id, [])
637
- if (chain) parentChain.push(...chain)
638
- }
639
-
640
- return {
641
- matcher: q,
642
- found: true,
643
- resolvedVia: via,
644
- node,
645
- transform,
646
- parentChain,
647
- }
648
- })()`});console.log(JSON.stringify(n,null,2));break}case"tap":{let o=Number(r[1]),n=Number(r[2]),a=xe(e,r);if(a){let m=await be(c,{agent:ue(),textFallback:a.mode==="text"?a.value:void 0,resolve:async()=>{let y=await Ae(c,a);return y?{cx:y.x,cy:y.y,match:{id:a.mode==="testid"?a.value:y.id??null,testID:a.mode==="testid"?a.value:y.testID??null,text:a.mode==="text"?a.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}}),f=m.payload;(!f||typeof f.cx!="number")&&(console.error(` not found: ${a.value}`),a.mode==="testid"&&Q("wait-selector-for-missing-testid",a.value),process.exit(1)),fe(m.result)||(O(`${a.mode} "${a.value}"`,m),process.exit(1));let $=Mo(f.cx,f.cy,m.result);$&&await W("inspect tap",$.step,$.summary),console.log(JSON.stringify({...m.attempts>1?{attempts:m.attempts}:{},...m.result},null,2));break}(!Number.isFinite(o)||!Number.isFinite(n))&&(console.error(g("tap","<testid> | <x> <y> | --testid <id> | --text <t>")),process.exit(1));let l=await zt(c,o,n),u=Mo(o,n,l);u&&await W("inspect tap",u.step,u.summary),console.log(JSON.stringify(l,null,2));break}case"drag":case"swipe":{let o=Number(r[1]),n=Number(r[2]),a=Number(r[3]),l=Number(r[4]),u=p==="swipe"?10:12,m=p==="swipe"?8:16,f=r[5]?Number(r[5]):u,$=r[6]?Number(r[6]):m;(!Number.isFinite(o)||!Number.isFinite(n)||!Number.isFinite(a)||!Number.isFinite(l)||!Number.isFinite(f)||!Number.isFinite($))&&(console.error(g(p,"<x1> <y1> <x2> <y2> [steps] [stepMs]")),process.exit(1));let y=await $e(c,{type:"drag",fromX:o,fromY:n,toX:a,toY:l,steps:Math.max(1,Math.round(f)),stepMs:Math.max(0,Math.round($))});if(y?.ok){let k=Math.max(1,Math.round(Math.max(1,f)*Math.max(0,$)));await W(`inspect ${p}`,{swipe:{start:`${o}, ${n}`,end:`${a}, ${l}`,duration:k}},`${p} ${o},${n} -> ${a},${l}`)}console.log(JSON.stringify(y,null,2));break}case"pinch":{let o=Number(r[1]),n=Number(r[2]),a=Number(r[3]),l=Number(r[4]),u=Number(r[5]),m=Number(r[6]),f=Number(r[7]),$=Number(r[8]),y=r[9]?Number(r[9]):12,k=r[10]?Number(r[10]):16;(!Number.isFinite(o)||!Number.isFinite(n)||!Number.isFinite(a)||!Number.isFinite(l)||!Number.isFinite(u)||!Number.isFinite(m)||!Number.isFinite(f)||!Number.isFinite($)||!Number.isFinite(y)||!Number.isFinite(k))&&(console.error(g("pinch","<x1> <y1> <x2> <y2> <x1'> <y1'> <x2'> <y2'> [steps] [stepMs]")),process.exit(1));let L=await $e(c,{type:"pinch",fromX1:o,fromY1:n,fromX2:a,fromY2:l,toX1:u,toY1:m,toX2:f,toY2:$,steps:Math.max(1,Math.round(y)),stepMs:Math.max(0,Math.round(k))});L?.ok&&await W("inspect pinch",{pinch:{from:[o,n,a,l],to:[u,m,f,$],steps:Math.max(1,Math.round(y)),stepMs:Math.max(0,Math.round(k))}},`pinch (${o},${n}) (${a},${l}) -> (${u},${m}) (${f},${$})`),console.log(JSON.stringify(L,null,2));break}case"tap-text":{let o=r[1];o||(console.error(g("tap-text","<text>")),process.exit(1));let n=Y=>{let j=e.indexOf(Y);return j>=0&&j+1<e.length?e[j+1]:null},a=Y=>e.includes(Y),l=n("--nth")??n("--index"),u=l!==null?Number(l):null;u!==null&&!Number.isFinite(u)&&(console.error(` --nth/--index requires an integer, got: ${l}`),process.exit(1));let m=n("--within"),f=n("--role"),$=a("--exact"),y=a("--first"),k=n("--min-y"),L=n("--max-y"),V=n("--min-x"),G=n("--max-x");for(let[Y,j]of[["--min-y",k],["--max-y",L],["--min-x",V],["--max-x",G]])j!==null&&!Number.isFinite(Number(j))&&(console.error(` ${Y} requires a number, got: ${j}`),process.exit(1));let z=e.indexOf("--near"),A=null;if(z>=0){let Y=Number(e[z+1]),j=Number(e[z+2]);(!Number.isFinite(Y)||!Number.isFinite(j))&&(console.error(" --near requires two numbers: --near <x> <y>"),process.exit(1)),A={x:Y,y:j}}let v={exact:$,role:f,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:A,nth:u,first:y},N=await Xt(c,o,v,{agent:ue()}),F=N.payload;if(F?.error==="bridge-not-ready"&&(console.error(" rnx test bridge not ready"),process.exit(1)),F?.ambiguous){let Y=F.candidates;console.error(` ambiguous: ${F.total} matches for "${o}"`);for(let j of Y){let ke=j.abs?`@(${Math.round(j.abs.x)},${Math.round(j.abs.y)})`:"",Oo=j.layout?` ${j.layout.width}x${j.layout.height}`:"",Ro=j.testID?` #${j.testID}`:"",Ao=j.text?` "${j.text}"`:"",Eo=j.ancestorTestIDs.length>0?` within ${j.ancestorTestIDs.slice(0,3).map(_o=>`#${_o}`).join(" > ")}`:"";console.error(` [${j.idx}] <${j.type}>${Ao}${Ro} ${ke}${Oo}${Eo}`)}F.total>Y.length&&console.error(` ... and ${F.total-Y.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)}F?.nthOutOfRange&&(console.error(` not found: nth ${F.nth} of ${F.total} match${F.total===1?"":"es"} for "${o}"`),process.exit(1)),(!F||typeof F.cx!="number")&&(console.error(` not found: ${o}`),process.exit(1)),fe(N.result)||(O(`text "${o}"`,N),process.exit(1));let ne=tt(o,{id:F.target?.id??null,testID:F.target?.testID??null,type:F.target?.type??null,cx:F.cx,cy:F.cy},"text");await W("inspect tap-text",ne.step,ne.summary),console.log(JSON.stringify({matched:F.match,tapped:{nodeId:F.target?.nodeId??null,id:F.target?.id??null,testID:F.target?.testID??null,type:F.target?.type??null,cx:F.cx,cy:F.cy},...F.strategy&&F.strategy!=="matched-node"?{strategy:F.strategy}:{},...F.total>1||u!==null?{nth:{index:F.idx,total:F.total}}:{},...N.attempts>1?{attempts:N.attempts}:{},result:N.result},null,2));break}case"tap-best":{let o=r[1];o||(console.error(g("tap-best","<query>")),process.exit(1));let n=await Vt(c,o,{agent:ue()}),a=n.payload;a||(console.error(` tap-best: no testID or visible text matched "${o}". try \`rnx find --interactive-targets\` to list candidates.`),process.exit(1)),"error"in a&&(console.error(` ${a.error}`),process.exit(1)),a.strategy==="none"&&(console.error(` tap-best: no testID or visible text matched "${o}". try \`rnx find --interactive-targets\` to list candidates.`),process.exit(1));let l=a.node;fe(n.result)||(O(`best "${o}"`,n),process.exit(1));let u=tt(o,{id:l.id,testID:l.testID,type:l.type,cx:a.cx,cy:a.cy},a.strategy==="testid"?"id":"text");await W("inspect tap-best",u.step,u.summary),console.log(JSON.stringify({matched:{strategy:a.strategy,nodeId:l.nodeId,id:l.id,testID:l.testID,type:l.type,text:l.text},tapped:{cx:a.cx,cy:a.cy},...n.attempts>1?{attempts:n.attempts}:{},result:n.result},null,2));break}case"tap-id":{let o=r[1];o||(console.error(g("tap-id","<id>")),process.exit(1));let n=await Yt(c,o,{agent:ue()}),a=n.payload;(!a||typeof a.cx!="number")&&(console.error(` not found: ${o}`),await gs(c,o),process.exit(1)),fe(n.result)||(O(`id "${o}"`,n),process.exit(1));let l=tt(o,{id:a.target?.id??null,testID:a.target?.testID??null,type:a.target?.type??null,cx:a.cx,cy:a.cy},"id");await W("inspect tap-id",l.step,l.summary),console.log(JSON.stringify({matched:a.match,tapped:{nodeId:a.target?.nodeId??null,id:a.target?.id??null,testID:a.target?.testID??null,type:a.target?.type??null,cx:a.cx,cy:a.cy},...a.strategy&&a.strategy!=="matched-node"?{strategy:a.strategy}:{},...n.attempts>1?{attempts:n.attempts}:{},result:n.result},null,2));break}case"type-into":{let o=r[1],n=r.slice(2).join(" ");(!o||!n)&&(console.error(g("type-into","<id> <text>")),process.exit(1));let a=JSON.stringify(o),l=await c.send({type:"evaluate",code:`(async () => {
649
- const t = window.__sootsimTest
650
- if (!t) return null
651
- const n = await (t.findByTestId(${a}) || t.findById(${a}))
652
- if (!n || !n.absolutePosition || !n.layout) return null
653
- return {
654
- cx: n.absolutePosition.x + (n.layout.width || 0) / 2,
655
- cy: n.absolutePosition.y + (n.layout.height || 0) / 2,
656
- id: n.id,
657
- testID: n.testID,
658
- type: n.type,
659
- isTextInput: !!n.isTextInput,
660
- secureTextEntry: !!n.secureTextEntry,
661
- placeholder: n.placeholder || null,
662
- }
663
- })()`});(!l||typeof l.cx!="number")&&(console.error(` not found: ${o}`),process.exit(1)),l.isTextInput||console.error(` warning: ${o} is not a text input (isTextInput: false)`);let u=await c.send({type:"tap",x:l.cx,y:l.cy,target:{id:l.id??o,testID:l.testID??o,text:null,type:l.type??null}}),m=l.secureTextEntry===!0,f=await ks(c,1e3,{targetId:o,secureTextEntry:m});f.visible||(console.error(` keyboard did not open after tapping ${o}`),process.exit(1));let $=f.focusedInput;$&&($.testID===o||$.id===o||(console.error(` focus routing mismatch after tap: requested ${JSON.stringify(o)} but focus is on ${JSON.stringify($.testID??$.id??null)}. did the tap land on an outer Pressable wrapper?`),process.exit(1))),await c.send({type:"keyboard",action:"type",text:n});let y=m||we(f),k=y?Z:Ze(n,f),L=y&&f.focusedInput?{...f.focusedInput,secureTextEntry:!0,text:typeof f.focusedInput.text=="string"?Z:f.focusedInput.text}:f.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:l.isTextInput,secureTextEntry:y,keyboardOpened:f.visible??u?.keyboardOpened??!1,focusedInput:L,typed:k},null,2));break}case"type":{let o=r.slice(1).join(" ");o||(console.error(g("type","<text>")),process.exit(1));let n=await De(c,"type");await c.send({type:"keyboard",action:"type",text:o});let a=Ze(o,n);await W("inspect type",{inputText:a},a===Z?`type ${Z}`:`type ${JSON.stringify(o)}`),console.log(a===Z?` typed: ${Z}`:` typed: ${JSON.stringify(o)}`);break}case"key":{let o=r[1];o||(console.error(g("key","<name>")),process.exit(1)),await De(c,"key"),await c.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=r.slice(1);o.length===0&&(console.error(g("key-sequence","<key> [<key> ...]")),process.exit(1)),await De(c,"key-sequence");for(let n of o)await c.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=r.slice(1);o.length===0&&(console.error(g("keycode","<code> [<code> ...]")),process.exit(1));let n=o.map(l=>({code:l,key:Is(l)})),a=n.filter(l=>!l.key);a.length>0&&(console.error(` unsupported keycode(s): ${a.map(l=>l.code).join(", ")}`),process.exit(1)),await De(c,"keycode");for(let l of n)await c.send({type:"keyboard",action:"press",text:l.key});await W("inspect keycode",{pressKey:n.map(l=>l.key).join(" ")},`keycode ${o.join(" ")}`),console.log(` pressed: ${o.join(", ")}`);break}case"dispatch":{let o=r[1];o||(console.error(g("dispatch","<char>")),process.exit(1)),await c.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 c.send({type:"keyboard",action:"dismiss"}),await W("inspect dismiss",{hideKeyboard:!0},"dismiss keyboard"),console.log(" keyboard dismissed");break}case"double-tap":{let o=Number(r[1]),n=Number(r[2]),a=xe(e,r);if(a){let $=await Ae(c,a);$||(console.error(` not found: ${a.value}`),a.mode==="testid"&&Q("wait-selector-for-missing-testid",a.value),process.exit(1)),o=$.x,n=$.y}let l=r[3]?Number(r[3]):80;(!Number.isFinite(o)||!Number.isFinite(n)||!Number.isFinite(l))&&(console.error(g("double-tap","<testid> | <x> <y> [gapMs] | --testid <id>")),process.exit(1));let u=Math.max(0,Math.round(l)),f={...await $e(c,{type:"doubleTap",x:o,y:n,gapMs:u}),gapMs:u};f?.ok&&await W("inspect double-tap",{doubleTapAtCoords:{x:o,y:n,gapMs:u}},`double-tap @${o},${n}`),console.log(JSON.stringify(f,null,2));break}case"long-press":{let o=Number(r[1]),n=Number(r[2]),a=xe(e,r),l=null;if(a){let y=await Ae(c,a);y||(console.error(` not found: ${a.value}`),a.mode==="testid"&&Q("wait-selector-for-missing-testid",a.value),process.exit(1)),o=y.x,n=y.y,l={id:y.id??null,testID:y.testID??null,text:y.text??null,type:y.type??null}}let u=a?r[1]:r[3],m=u?Number(u):600;(!Number.isFinite(o)||!Number.isFinite(n)||!Number.isFinite(m))&&(console.error(g("long-press","<testid> | <x> <y> [durationMs] | --testid <id>")),process.exit(1));let f=Math.max(0,Math.round(m)),$=await c.send({type:"longPress",x:o,y:n,durationMs:f,target:l});$?.ok&&await W("inspect long-press",{tapAtCoords:{x:o,y:n}},`long-press @${o},${n}`),console.log(JSON.stringify($,null,2));break}case"touch":{let o=r[1],n=Number(r[2]),a=Number(r[3]),l=r[4]?Number(r[4]):999,u=o==="down"?"touchDown":o==="move"?"touchMove":o==="up"?"touchUp":o==="cancel"?"touchCancel":null;u||(console.error(g("touch","<down|move|up|cancel> <x> <y> [pointerId]")),process.exit(1)),o!=="cancel"&&(!Number.isFinite(n)||!Number.isFinite(a))&&(console.error(g("touch","<down|move|up|cancel> <x> <y> [pointerId]")),process.exit(1));let m=Math.max(1,Math.round(l)),f=await $e(c,u==="touchCancel"?{type:u,pointerId:m}:{type:u,x:n,y:a,pointerId:m});f?.ok&&o!=="cancel"&&await W("inspect touch",{tapAtCoords:{x:n,y:a}},`touch ${o} @${n},${a}`),console.log(JSON.stringify(f,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=r[1],a=r[2]?Number(r[2]):220;(!n||!Number.isFinite(a))&&(console.error(g("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 l=await c.send({type:"evaluate",code:`(async () => {
664
- const spec = globalThis.__sootsimDeviceSpec || {}
665
- return {
666
- width: spec.width || window.innerWidth || 393,
667
- height: spec.height || window.innerHeight || 852,
668
- statusBarHeight: spec.statusBarHeight || 0,
669
- homeIndicatorHeight: spec.homeIndicatorHeight || 0,
670
- }
671
- })()`}),u=Number(l?.width)||393,m=Number(l?.height)||852,f=Number(l?.statusBarHeight)||0,$=Number(l?.homeIndicatorHeight)||0,y=Math.round(u/2),k=Math.round(m/2),L=Math.max(24,f+18),V=Math.max(24,$+18),G=18,z=Math.min(220,Math.round(m*.24)),A=Math.min(180,Math.round(u*.32)),v=y,N=k,F=y,ne=k;switch(n){case"scroll-up":N=k+Math.round(z/2),ne=k-Math.round(z/2);break;case"scroll-down":N=k-Math.round(z/2),ne=k+Math.round(z/2);break;case"scroll-left":v=y+Math.round(A/2),F=y-Math.round(A/2);break;case"scroll-right":v=y-Math.round(A/2),F=y+Math.round(A/2);break;case"swipe-from-left-edge":v=G,N=k,F=Math.min(u-G,G+A);break;case"swipe-from-right-edge":v=u-G,N=k,F=Math.max(G,u-G-A);break;case"swipe-from-top-edge":v=y,N=L,ne=Math.min(m-V,L+z);break;case"swipe-from-bottom-edge":v=y,N=m-V,ne=Math.max(L,m-V-z);break}let Y=Math.max(8,Math.round(a/16)),j=Math.max(1,Math.round(a/Y)),ke=await $e(c,{type:"drag",fromX:v,fromY:N,toX:F,toY:ne,steps:Y,stepMs:j});ke?.ok&&await W("inspect gesture",{swipe:{start:`${v}, ${N}`,end:`${F}, ${ne}`,duration:Math.max(1,Math.round(a))}},`gesture ${n}`),console.log(JSON.stringify({preset:n,from:{x:v,y:N},to:{x:F,y:ne},result:ke},null,2));break}case"scroll":{let o=xe(e),n=Ms(e),a=o?.mode==="testid"?o.value:n==null?r[1]:null,l=o||n!=null?1:2,u=Number(r[l]),m=Number(r[l+1]);(!a&&n==null||!Number.isFinite(u)||!Number.isFinite(m))&&(console.error(g("scroll","<id> <x> <y> | --testid <id> <x> <y> | --node-id <nodeId> <x> <y>")),process.exit(1));let f=await c.send({type:"evaluate",code:`(async () => {
672
- const t = window.__sootsimTest
673
- if (!t) return null
674
- const n = ${n!=null?`await t.inspectByNodeId(${JSON.stringify(n)})`:`await t.findByTestId(${JSON.stringify(a)})
675
- || await t.findById(${JSON.stringify(a)})`}
676
- if (!n || !n.absolutePosition || !n.layout) return null
677
- return {
678
- cx: n.absolutePosition.x + (n.layout.width || 0) / 2,
679
- cy: n.absolutePosition.y + (n.layout.height || 0) / 2,
680
- }
681
- })()`}),$=await X(c,"scrollTo",n!=null?{nodeId:n}:a,u,m,!1);if($?.ok){let y=n!=null?`node ${n}`:`#${a}`;await W("inspect scroll",{scrollTo:{...n!=null?{nodeId:n}:{id:a},x:u,y:m}},`scroll ${y} -> ${u},${m}`)}console.log(JSON.stringify({...$,...f?{at:{x:f.cx,y:f.cy}}:{}},null,2));break}case"state":{let o=r[1];if(s==="get"&&!o){let a=await X(c,"getRuntimeState"),l=await c.send({type:"evaluate",code:Te});if(a&&typeof a=="object"&&a.diagnostics&&(a.diagnostics.errors=l?.errors??0,a.diagnostics.warnings=l?.warnings??0),a&&typeof a=="object"&&a.shell==null)try{let u=await pe(c);u&&(a.shell=u)}catch{}console.log(JSON.stringify(a,null,2));break}if(!o||o==="--help"||o==="-h"){console.log(`
682
- ${w("state")} \u2014 dump raw runtime state
683
-
684
- subcommands:
685
- shell dump shell transition/layout state
686
- worker dump render-worker host/animation state
687
- keyboard dump keyboard visibility, mode, and focused input
688
- ownership dump surface ownership + pointerOnSurface delivery stats
689
- worklets dump tenant + shell worklet-runtime slot/handler counts
690
- scroll-input dump shell-owned scroll gesture and momentum state
691
- scroll-mirror dump shell scroll registry entries and offsets
692
- node <id> dump raw node info by id or testID
693
- scroll <id> dump scroll metrics and runtime state
694
- scroll-hit <x> <y> dump the nearest scroll ancestor at coordinates
695
- hit <x> <y> dump the hit-test ancestry at coordinates
696
- gesture <x> <y> dump gesture routing/debug info at coordinates
697
- gesture-seam dump shell-hosted gesture recognizer state/events
698
-
699
- examples:
700
- ${w("state")} shell
701
- ${w("state")} worker
702
- ${w("state")} keyboard
703
- ${w("state")} ownership
704
- ${w("state")} worklets
705
- ${w("state")} scroll-input
706
- ${w("state")} scroll-mirror
707
- ${w("state")} node photos
708
- ${w("state")} scroll feed
709
- ${w("state")} scroll-hit 360 420
710
- ${w("state")} hit 200 720
711
- `);break}let n;switch(o){case"shell":n=await pe(c,500);break;case"worker":n=await ce(c,"__sootsimRenderHost.queryStats");break;case"ownership":n=await c.send({type:"evaluate",code:`(() => {
712
- const h = window.__sootsimRenderHost
713
- if (!h || typeof h.getOwnershipSnapshot !== 'function') {
714
- return { error: 'getOwnershipSnapshot not available' }
715
- }
716
- return h.getOwnershipSnapshot()
717
- })()`});break;case"keyboard":n=await c.send({type:"evaluate",code:`(async () => {
718
- const kb = window.__sootsimKeyboard
719
- const test = window.__sootsimTest
720
- if (!kb) return { error: 'keyboard bridge not available' }
721
- const layout = typeof kb.getLayout === 'function' ? kb.getLayout() : null
722
- const secureTextEntry =
723
- !!layout?.spec?.secureTextEntry && layout?.spec?.keyboardType !== 'visible-password'
724
- const visible = kb.isVisible()
725
- const mode = kb.getMode()
726
- let focused = null
727
- if (test && typeof test.getFocusedNode === 'function') {
728
- try {
729
- focused = await test.getFocusedNode()
730
- } catch {}
731
- }
732
- return {
733
- visible,
734
- mode,
735
- layout,
736
- focusedInput: focused ? {
737
- nodeId: focused.nodeId ?? null,
738
- testID: focused.testID || null,
739
- id: focused.id || null,
740
- placeholder: focused.placeholder || null,
741
- secureTextEntry,
742
- text: secureTextEntry ? ${JSON.stringify(Z)} : (focused.text || null),
743
- } : null,
744
- }
745
- })()`}),n=et(n);break;case"node":{let a=r[2];a||(console.error(` usage: ${w("state")} node <id>`),process.exit(1)),n=await X(c,"findByTestId",a)||await X(c,"findById",a);break}case"scroll":{let a=r[2];a||(console.error(` usage: ${w("state")} scroll <id>`),process.exit(1)),n=await X(c,"getScrollState",a);break}case"scroll-hit":{let a=Number(r[2]),l=Number(r[3]);(!Number.isFinite(a)||!Number.isFinite(l))&&(console.error(` usage: ${w("state")} scroll-hit <x> <y>`),process.exit(1)),n=await X(c,"getScrollStateAt",a,l);break}case"hit":{let a=Number(r[2]),l=Number(r[3]);(!Number.isFinite(a)||!Number.isFinite(l))&&(console.error(` usage: ${w("state")} hit <x> <y>`),process.exit(1)),n=await X(c,"debugHitAt",a,l);break}case"gesture":{let a=Number(r[2]),l=Number(r[3]);(!Number.isFinite(a)||!Number.isFinite(l))&&(console.error(` usage: ${w("state")} gesture <x> <y>`),process.exit(1)),n=await X(c,"debugGestureAt",a,l);break}case"gesture-seam":n=await ce(c,"SootSim.bridges.mainShell.callTestBridge","getShellGestureSeamDebug");break;case"worklets":{let[a,l]=await Promise.all([X(c,"getWorkletSlotStats"),ce(c,"SootSim.bridges.mainShell.callTestBridge","getWorkletSlotStats")]);n={tenant:a,shell:l};break}case"scroll-input":n=await ce(c,"SootSim.bridges.mainShell.callTestBridge","getShellScrollInputDebug");break;case"scroll-mirror":n=await ce(c,"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=r[1];if(!o||o==="--help"||o==="-h"){console.log(`
746
- ${w("shell")} \u2014 run built-in shell commands
747
-
748
- subcommands:
749
- launch <appId> [waitMs] [--clear-state]
750
- launch app and wait for settled shell state
751
- home [waitMs] go home and wait for settled shell state
752
- switcher [waitMs] open switcher and wait for settled shell state
753
- open-card <appId> [waitMs]
754
- open a specific switcher card and wait for app settle
755
- appearance <light|dark|auto|toggle>
756
- update simulator appearance
757
- lock toggle device lock state
758
- shake trigger the simulator shake gesture
759
-
760
- examples:
761
- ${w("shell")} launch photos
762
- ${w("shell")} launch rn --clear-state
763
- ${w("shell")} launch photos 1500
764
- ${w("shell")} home 500
765
- ${w("shell")} switcher 800
766
- ${w("shell")} open-card clock 800
767
- ${w("shell")} appearance dark
768
- ${w("shell")} lock
769
- `);break}let n=o==="launch"||o==="open-card"||o==="home"||o==="switcher",a=o==="launch"||o==="open-card"?r[3]:r[2],l=a?Number(a):350;n&&(!Number.isFinite(l)||l<0)&&(console.error(g("shell",o==="launch"||o==="open-card"?"<launch|open-card> <appId> [settleMs]":"<home|switcher> [settleMs]")),process.exit(1));let u=!1,m=!1,f=null,$=e.includes("--clear-state");if(o==="launch"){let y=r[2];y||(console.error(g("shell","launch <appId> [settleMs] [--clear-state]")),process.exit(1)),$&&await c.send({type:"evaluate",code:Je(!0)}),u=!!await ye(c,"launchApp",l,y),{settled:m,state:f}=await _e(c,Math.round(l),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",$?{launchApp:{clearState:!0}}:{launchApp:{}},$?"launch app (clear state)":"launch app")}else if(o==="home")u=!!await ye(c,"goHome",l),{settled:m,state:f}=await _e(c,Math.round(l),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(c,"openSwitcher",l),{settled:m,state:f}=await _e(c,Math.round(l),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(Ss),f=await pe(c));else if(o==="open-card"){let y=r[2];y||(console.error(g("shell","open-card <appId> [settleMs]")),process.exit(1)),u=!!await ye(c,"openSwitcherCard",l,y),{settled:m,state:f}=await _e(c,Math.round(l),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=r[2];(!y||!["light","dark","auto","toggle"].includes(y))&&(console.error(g("shell","appearance <light|dark|auto|toggle>")),process.exit(1));let k=await To(c,"appearance",y);if(u=!!k?.ok,f={appearance:k},u){let L=k?.applied??y;console.log(` appearance: ${L}`)}}else if(o==="lock"||o==="shake"){let y=await To(c,o);u=!!y?.ok,f={[o]:y}}else console.error(` unknown shell subcommand: ${o}`),process.exit(1);console.log(JSON.stringify({ok:u,settled:m,state:f},null,2));break}case"url":{await uo(c,{args:i});break}case"reload":{let a=!1,l=!1;try{await c.send({type:"evaluate",code:"window.__sootsimConsole?.clear()"});let f=await c.send({type:"evaluate",code:`;(async () => {
770
- // in-place guest reload is only valid while the page still runs
771
- // the engine build the server would serve NOW. the shell dev
772
- // server has no HMR client, so a long-lived sim tab otherwise
773
- // keeps a stale engine forever while builds churn underneath it.
774
- // compare the inlined engine manifest against a fresh fetch of
775
- // this page's html; any drift means the whole page must reload.
776
- let engineStale = false
777
- try {
778
- const loaded = document.getElementById('__sootsim-engine-manifest')?.textContent
779
- if (loaded) {
780
- const res = await fetch(location.href, { cache: 'no-store' })
781
- const html = await res.text()
782
- const m = html.match(/<script[^>]*id="__sootsim-engine-manifest"[^>]*>([^<]*)<\\/script>/)
783
- if (m && m[1] !== loaded) engineStale = true
784
- }
785
- } catch {}
786
- const reloadExternalApp = window.SootSim?.bridges?.hotRemount?.reloadExternalApp
787
- if (!engineStale && typeof reloadExternalApp === 'function') {
788
- reloadExternalApp()
789
- return { kind: 'external-app' }
790
- }
791
- window.location.reload()
792
- return { kind: 'page', engineStale }
793
- })()`});l=!!f&&f.kind==="external-app",a=!0,f&&f.engineStale&&console.log(" engine build changed since page load \u2014 full page reload")}catch{}console.log(" reloading...");let u=c,m=null;if(l)m=await Ne(c,{timeoutMs:1e4,errorGraceMs:3e3});else{a&&await oe(300);let $=await Et(M,P,x,{timeoutMs:3e4,simIdSource:_});$?(u=$,m=await Ne($,{timeoutMs:3e4,errorGraceMs:3e3})):(console.log(" \u26A0 reload: bridge never reconnected within 30000ms"),u=null)}if(m)if(m.ready){let f=m.source==="nodes-fallback"?" (no ready signal, node-count fallback)":"";console.log(` ready in ${m.elapsedMs}ms: ${m.nodes} nodes${f}`)}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 f=wo(m);console.log(` \u26A0 reload timed out after ${m.elapsedMs}ms \u2014 ${f} (nodes: ${m.nodes}, targets: ${m.targets}, errors: ${m.errors})`)}if(u)try{let f=await ge(u,10);if(u!==c&&u.close(),Array.isArray(f)&&f.length>0){console.log(`
794
- \u26A0 ${f.length} error(s) during mount:
795
- `);for(let $ of f){let y=$.args.map(k=>typeof k=="object"?JSON.stringify(k):k).join(" ");if(console.log(` ${y}`),$.stack){let k=$.stack.split(`
796
- `).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(c),await c.send({type:"evaluate",code:Je(!0)})!==!0){C(i)?B({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 l=await Ne(c,{timeoutMs:1e4,errorGraceMs:3e3});if(C(i)){B({cleared:!0,ready:l.ready,reload:l}),l.ready||(process.exitCode=1);break}if(l.ready){let u=l.source==="nodes-fallback"?" (no ready signal, node-count fallback)":"";console.log(` cleared tenant storage; ready in ${l.elapsedMs}ms: ${l.nodes} nodes${u}`)}else if(l.source==="error-bail")console.log(` \u26A0 storage clear reloaded but bailed after ${l.elapsedMs}ms: ${l.errors} console error(s), ready signal never fired`);else{let u=wo(l);console.log(` \u26A0 storage clear reloaded but timed out after ${l.elapsedMs}ms \u2014 ${u} (nodes: ${l.nodes}, targets: ${l.targets}, errors: ${l.errors})`)}try{let u=await ge(c,10);if(Array.isArray(u)&&u.length>0){console.log(`
797
- \u26A0 ${u.length} error(s) during mount:
798
- `);for(let m of u){let f=m.args.map($=>typeof $=="object"?JSON.stringify($):$).join(" ");if(console.log(` ${f}`),m.stack){let $=m.stack.split(`
799
- `).slice(0,2);for(let y of $)console.log(` ${y.trim()}`)}}}}catch{}l.ready||(process.exitCode=1);break}case"js":{let o=r.slice(1).join(" ");if(o||(console.error(g("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(` ${w("js")} SootSim.bridges.test.findByText("Sign in")`),console.error(` ${w("js")} SootSim.bridges.debug.snapshot("before")`),console.error(` ${w("js")} SootSim.bridges.keyboard.type("hello")`),console.error(` ${w("js")} SootSim.state.root.children.length`),process.exit(1)),e.includes("--tenant")){let m=r.slice(1).filter($=>$!=="--tenant").join(" "),f=await c.send({type:"evaluate",code:`(async () => SootSim.bridges.test.evalInTenant(${JSON.stringify(m)}))()`});console.log(JSON.stringify(f,null,2));break}let n=o;n.startsWith("(async")||(n=`(async () => ${n})()`);let a=await c.send({type:"evaluate",code:n});console.log(JSON.stringify(a,null,2));let l=o.toLowerCase(),u=[];(l.includes("sootsim:gohome")||l.includes("gohome"))&&u.push("rnx shell home"),(l.includes("sootsim:appswitcher")||l.includes("appswitcher"))&&u.push("rnx shell switcher"),(l.includes("keyboard.isvisible")||l.includes("keyboard.getmode"))&&u.push("rnx debug state keyboard"),l.includes("interact.tap")&&u.push("rnx do tap <x> <y>"),l.includes("keyboard.type")&&u.push("rnx do type <text>"),(l.includes("keyboard.press")||l.includes("keyboard.dispatchkey"))&&u.push("rnx do key <name>"),l.includes("keyboard.dismiss")&&u.push("rnx do dismiss"),l.includes("dumptree")&&u.push("rnx get tree"),l.includes("dumpaccessibilitytree")&&u.push("rnx get a11y"),l.includes("getnodecount")&&u.push("rnx get count"),l.includes("findbytext")&&u.push("rnx find <text>"),(l.includes("findbytestid")||l.includes("findbyid"))&&u.push("rnx find --testid <id>"),l.includes("document.hidden")&&u.push("rnx debug state keyboard (includes tab health)"),u.length>0&&Q("prefer-cli-over-eval",u);break}case"globals":{let o=await c.send({type:"evaluate",code:`(async () => {
800
- const globals = {}
801
-
802
- // test bridge (proxy in worker mode)
803
- const testMethods = [
804
- 'findById', 'findByTestId', 'findByText', 'findByLabel', 'findByRole',
805
- 'findAllByRole', 'findByA11yState', 'findAllByA11yState', 'findByHint',
806
- 'findPressable', 'getStyle', 'getLayout', 'getAbsolutePosition', 'isVisible',
807
- 'queryAll', 'dumpTree', 'dumpAccessibilityTree', 'getNodeCount', 'getShellState',
808
- 'getScrollState', 'getScrollStateAt', 'scrollTo', 'waitForTree',
809
- 'waitForScreenTransitions', 'debugByText', 'debugByTestId', 'debugHitAt',
810
- 'debugGestureAt'
811
- ]
812
- globals['test (\u2192 __sootsimTest)'] = testMethods
813
-
814
- // debug
815
- if (window.__sootsimDebug) {
816
- globals['debug (\u2192 __sootsimDebug)'] = Object.keys(window.__sootsimDebug)
817
- }
818
-
819
- // interact
820
- if (window.__sootsimInteract) {
821
- globals['interact (\u2192 __sootsimInteract)'] = Object.keys(window.__sootsimInteract)
822
- }
823
-
824
- // keyboard
825
- if (window.__sootsimKeyboard) {
826
- globals['keyboard (\u2192 __sootsimKeyboard)'] = Object.keys(window.__sootsimKeyboard)
827
- }
828
-
829
- // other globals
830
- globals['other'] = [
831
- 'root (\u2192 __sootsimRoot) - live node tree',
832
- 'render() (\u2192 __sootsimForceRender) - force re-render'
833
- ]
834
-
835
- return globals
836
- })()`});console.log(` rnx JS API:
837
- `);for(let[n,a]of Object.entries(o)){console.log(` ${n}:`);for(let l of a)console.log(` .${l}`);console.log("")}console.log(` use: ${w("js")} <expression>`),console.log(` example: ${w("js")} test.findByText("Sign in")`);break}case"describe":{await Zt({bridge:c,args:e,positional:r});break}case"perf":{b==="debug"&&!t.internalPerfCommand&&(console.error(" `rnx debug perf` was removed. use `rnx perf shell ...`."),process.exit(1));let o=r[1];if(t.internalPerfCommand==="scroll"){if(!o||o==="--help"||o==="-h"){console.log(`
838
- ${w("perf")} <start|stop> [options]
839
-
840
- records per-frame scroll offsets from the tenant worker, shell worker,
841
- and compositor worker. timestamps use the shared wall clock, while frame
842
- sequences remain separate because the workers do not share a frame id.
843
-
844
- options:
845
- --limit <n> maximum samples retained per layer (default 6000)
846
- --json emit every per-frame sample on stop
847
-
848
- examples:
849
- ${w("perf")} start
850
- # ... perform consecutive swipes ...
851
- ${w("perf")} stop
852
- ${w("perf")} stop --json
853
- `);break}if(o==="start"){let n=i.find((u,m)=>i[m-1]==="--limit"),a=n===void 0?6e3:Number(n);(!Number.isFinite(a)||a<120)&&(console.error(" error: --limit must be a number of at least 120"),process.exit(1));let l=await c.send({type:"evaluate",code:`(async () => {
854
- const perf = window.SootSim?.bridges?.scrollPerf
855
- if (!perf) return { error: 'scroll performance profile unavailable' }
856
- await perf.start(${Math.floor(a)})
857
- return { started: true }
858
- })()`});l?.error&&(console.error(` error: ${l.error}`),process.exit(1)),console.log(` scroll profiling started: perform consecutive swipes, then run '${w("perf")} stop'`);break}if(o==="stop"){let n=await c.send({type:"evaluate",code:`(async () => {
859
- const perf = window.SootSim?.bridges?.scrollPerf
860
- if (!perf) return { error: 'scroll performance profile unavailable' }
861
- return await perf.stop()
862
- })()`});n?.error&&(console.error(` error: ${n.error}`),process.exit(1));let a=n;if(C(i)){B(a);break}console.log(` scroll performance trace:
863
- `),console.log(` duration: ${a.stoppedAt-a.startedAt}ms (worker series are timestamp-aligned, not frame-paired)`),console.log(` samples: tenant ${a.layers.tenant.length} \xB7 shell ${a.layers.shell.length} \xB7 compositor ${a.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 l=[];for(let u of Object.values(a.layers)){let m=new Map;for(let f of u){let $=`${f.surfaceId}:${f.nodeId}`,y=`${f.offsetY}:${f.slotY??""}:${f.phase??""}`;m.get($)!==y&&(m.set($,y),l.push(f))}}l.sort((u,m)=>u.t-m.t||u.seq-m.seq);for(let u of l)console.log(` ${String(u.t-a.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(`
864
- ${w("perf")} \u2014 shell frame profiling (the worker that paints)
865
-
866
- records per-painted-frame timing in the shell worker \u2014 the surface that
867
- actually draws the app's pixels \u2014 merged with render-profile counters
868
- (node visits, boundary records/replays, raster tier, blur ms, draw calls).
869
-
870
- subcommands:
871
- start begin recording (clears prior frames + counters)
872
- stop stop recording and report results
873
- transition <e> profile a shell transition (goHome, appSwitcher, lockScreen)
874
-
875
- stop and transition accept --json for the full machine-readable payload.
876
-
877
- examples:
878
- ${w("perf")} start
879
- # ... interact with the app ...
880
- ${w("perf")} stop
881
- ${w("perf")} stop --json
882
- ${w("perf")} transition goHome
883
- `);break}switch(o){case"start":{let n=await c.send({type:"evaluate",code:`(() => {
884
- if (!window.__sootsimShellPerf) {
885
- return { error: 'shell frame profile unavailable (__sootsimShellPerf missing on the page)' }
886
- }
887
- window.__sootsimShellPerf.start()
888
- return { started: true }
889
- })()`});n?.error&&(console.error(` error: ${n.error}`),process.exit(1)),console.log(` shell profiling started \u2014 interact with the app, then run '${w("perf")} stop'`);break}case"stop":{let n=await c.send({type:"evaluate",code:`(async () => {
890
- if (!window.__sootsimShellPerf) {
891
- return { error: 'shell frame profile unavailable (__sootsimShellPerf missing on the page)' }
892
- }
893
- return await window.__sootsimShellPerf.stop()
894
- })()`});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)),C(i)){B(n);break}Io(n);break}case"transition":{let n=r[2];if(!n||!["goHome","appSwitcher","lockScreen"].includes(n)){console.log(`
895
- ${w("perf")} transition <event> \u2014 profile a shell transition
896
-
897
- events:
898
- goHome swipe-to-home animation
899
- appSwitcher app switcher card animation
900
- lockScreen lock screen transition
901
-
902
- note: uses 600ms capture window \u2014 may need --timeout 10000 flag
903
-
904
- examples:
905
- ${w("perf")} transition goHome --timeout 10000
906
- ${w("perf")} transition appSwitcher
907
- `);break}let l=`sootsim:${n}`;Me(` profiling ${n} transition...`),Me(" (use --timeout 10000 if this times out)");let u=await c.send({type:"evaluate",code:`(async () => {
908
- if (!window.__sootsimShellPerf) {
909
- return { error: 'shell frame profile unavailable (__sootsimShellPerf missing on the page)' }
910
- }
911
- window.__sootsimShellPerf.start()
912
- // give a frame for profiling to engage before the event
913
- await new Promise(r => requestAnimationFrame(() => r(undefined)))
914
- window.dispatchEvent(new Event('${l}'))
915
- // shell animations are ~300-500ms; fixed timing avoids complex
916
- // animation-end detection
917
- await new Promise(r => setTimeout(r, 600))
918
- return await window.__sootsimShellPerf.stop()
919
- })()`});if(u?.error&&(console.error(` error: ${u.error}`),process.exit(1)),C(i)){B(u);break}Me(` ${n} transition profiled:`),Io(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=r[1];if(o==="clear"){await Le(c),C(i)?B({cleared:!0}):console.log(" error buffer cleared");break}let n=o?Number(o):20,a=await ge(c,n);if(C(i)){B(a);break}if(a.length===0){console.log(" no errors captured");break}console.log(` ${a.length} error(s):
920
- `);for(let l of a){let u=ae(l.timestamp),m=l.args.map(f=>typeof f=="object"?JSON.stringify(f):f).join(" ");if(console.log(` [${u}] ${m}`),l.stack){let f=l.stack.split(`
921
- `).slice(0,3);for(let $ of f)console.log(` ${$.trim()}`)}}break}case"warnings":{let o=r[1]?Number(r[1]):20,n=await kt(c,o);if(C(i)){B(n);break}if(n.length===0){console.log(" no warnings captured");break}console.log(` ${n.length} warning(s):
922
- `);for(let a of n){let l=ae(a.timestamp),u=a.args.map(m=>typeof m=="object"?JSON.stringify(m):m).join(" ");console.log(` [${l}] ${u}`)}break}case"animations":{let o=await X(c,"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):
923
- `);for(let n of o){let a=String(n.realm??"tenant").padEnd(6),l=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),f=typeof n.progress=="number"?`${Math.round(n.progress*100)}%`:"\u2014",$=`${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} ${a} ${l} ${u.padEnd(14)} cur=${m.padEnd(7)} ${f.padStart(4)} ${$}${k}`)}break}case"animation":{let o=r[1];(!o||o==="--help"||o==="-h")&&(console.error(` usage: ${w("animation")} <id>`),process.exit(1));let n=Number(o);Number.isFinite(n)||(console.error(` invalid id: ${o}`),process.exit(1));let a=await X(c,"getAnimation",n);console.log(JSON.stringify(a,null,2));break}case"stop-animation":{let o=r[1];(!o||o==="--help"||o==="-h")&&(console.error(` usage: ${w("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 a=await X(c,"stopAnimation",n);console.log(` stopped ${a??0} animation(s)`);break}case"requests":{let o=r[1];if(o==="clear"){await Tt(c),C(i)?B({cleared:!0}):console.log(" request buffer cleared");break}let n=o==="all",a=n?r[2]:o,l=a?Number(a):20,u=await It(c,{failed:!n,limit:l});if(C(i)){B(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)"}:
924
- `);for(let m of u){let f=ae(m.timestamp);console.log(` [${f}] ${U(m)}`),m.responseBody?console.log(` ${m.responseBody}`):m.error&&console.log(` ${m.error}`)}break}case"network":{let o=r[1],n=null,a=null,l=!1,u=!1,m=1e3,f=!1,$=!1;for(let A=0;A<i.length;A++){let v=i[A];if(v==="--filter")n=i[A+1]??null,A++;else if(v==="--limit"){let N=Number(i[A+1]);Number.isFinite(N)&&(a=N),A++}else if(v==="--threshold"){let N=Number(i[A+1]);Number.isFinite(N)&&N>0&&(m=N),A++}else v==="--failed"?l=!0:v==="--slow"?u=!0:v==="--tail"||v==="-f"?f=!0:v==="--json"&&($=!0)}if(o==="clear"){await c.send({type:"evaluate",code:'window.__sootsimObservability?.network.clear(); "cleared"'}),console.log(" network buffer cleared");break}if(o==="get"){let A=r[2];A||(console.error(" usage: rnx network get <id>"),process.exit(1));let v=await c.send({type:"evaluate",code:`(() => {
925
- const obs = window.__sootsimObservability;
926
- if (!obs) return null;
927
- return obs.network.getSnapshot().find(e => e.id === ${JSON.stringify(A)}) || null;
928
- })()`});v||(console.error(` no entry with id ${A}`),process.exit(1)),$?console.log(JSON.stringify(v,null,2)):ws(v);break}let y=a??(f?200:o?Number(o):20);Number.isFinite(y)||(console.error(` invalid limit: ${o} \u2014 \`network\` takes a numeric count (e.g. ${w("network")} 100).
929
- to target a specific sim, use \`--sim ${o}\` instead.`),process.exit(1));let k=async()=>{let A=await c.send({type:"evaluate",code:`(() => {
930
- const obs = window.__sootsimObservability;
931
- if (!obs) return { ok: false };
932
- return { ok: true, entries: obs.network.getSnapshot() };
933
- })()`});if(!A||!A.ok)throw new Error("observability bridge not installed \u2014 is the engine running?");return A.entries??[]},L=A=>{let v=A;if(l&&(v=v.filter(N=>!!N.error||N.status!=null&&N.status>=400)),u&&(v=v.filter(N=>N.durationMs!=null&&N.durationMs>=m)),n){let N=n.toLowerCase();v=v.filter(F=>(F.displayUrl||F.url).toLowerCase().includes(N))}return u&&!f&&(v=[...v].sort((N,F)=>(F.durationMs??0)-(N.durationMs??0))),v};if(!f){let A=await k(),v=L(A).slice(-y);if($){console.log(JSON.stringify(v,null,2));break}if(v.length===0){A.length===0?console.log(" no network requests captured"):console.log(u?` no requests slower than ${m}ms (${A.length} total \u2014 try --threshold <ms>)`:" no matching requests");break}console.log(u?` ${v.length} request(s) slower than ${m}ms (sorted by duration desc):
934
- `:` ${v.length} request(s):
935
- `);for(let N of v)xo(N);break}console.log(` tailing network (ctrl-c to stop)...
936
- `);let V=new Set,G=!0,z=()=>{G=!1};process.on("SIGINT",z);try{for(;G;){let A=await k(),v=L(A);for(let N of v)N.durationMs!=null&&(V.has(N.id)||(V.add(N.id),$?console.log(JSON.stringify(N)):xo(N)));await oe(250)}}finally{process.off("SIGINT",z)}break}case"logs":{let o=r[1],n=null,a=null,l=null,u=!1,m=!1,f=!1;for(let v=0;v<i.length;v++){let N=i[v];if(N==="--filter")n=i[v+1]??null,v++;else if(N==="--limit"){let F=Number(i[v+1]);Number.isFinite(F)&&(a=F),v++}else N==="--level"?(l=i[v+1]??null,v++):N==="--tail"||N==="-f"?u=!0:N==="--json"?m=!0:(N==="--internal"||N==="--all")&&(f=!0)}let $=l?new Set(l.split(",").map(v=>v.trim()).filter(v=>v==="log"||v==="info"||v==="warn"||v==="error"||v==="debug")):null;if(o==="clear"){await Nt(c),console.log(" log buffer cleared");break}let y=!m&&process.stdout.isTTY===!0,k=a??(u?500:o?Number(o):50);Number.isFinite(k)||(console.error(` invalid limit: ${o} \u2014 \`logs\` takes a numeric count (e.g. ${w("logs")} 100).
937
- to target a specific sim, use \`--sim ${o}\` instead.`),process.exit(1));let L=()=>Mt(c),V=v=>Ft(v,{level:$,filter:n,showInternal:f});if(!u){let v=await L(),N=V(v).slice(-k);if(m){console.log(JSON.stringify(N,null,2));break}if(N.length===0){console.log(v.length===0?" no logs captured":" no matching logs");break}console.log(` ${N.length} log(s):
938
- `);for(let F of N)So(F,y);break}console.log(` tailing logs (ctrl-c to stop)...
939
- `);let G=new Set,z=!0,A=()=>{z=!1};process.on("SIGINT",A);try{for(;z;){let v=await L(),N=V(v);for(let F of N)G.has(F.id)||(G.add(F.id),m?console.log(JSON.stringify(F)):So(F,y));await oe(250)}}finally{process.off("SIGINT",A)}break}default:console.error(` unknown subcommand: ${p}`),process.exit(1)}if(q.has(p)&&!e.includes("--no-wait")&&process.env.SOOTSIM_NO_AUTO_WAIT!=="1"&&!await mt(c,p)&&await T(c),S.length>0&&ee(S),!R.has(p))try{await Se(c)}catch{}}catch(S){let o=S instanceof Error?S.message:String(S);console.error(` ${p??"rnx"} failed: ${o}`);let n=/^no sim connected with id ([^;]+)(?:; connected sims: .+)?$/.exec(o),a=/^command timed out after (\d+)s$/.exec(o),l=o.startsWith("sim disconnected:")||o.startsWith("bridge never reconnected")||o.startsWith("could not connect to ws://");if(n)await qt(c,M,n[1]);else if(/^no sim connected$/.test(o))jt(M);else if(a)if(await fs(c)){let m=p??"describe";process.stderr.write(` the sim is still responsive \u2014 '${m}' just exceeded the ${a[1]}s command budget.
940
- the screen's node tree is large; narrow the query or raise the budget:
941
- rnx ${m} --testid <id> # scope to one subtree
942
- rnx find --testid <id> # targeted single-node lookup
943
- rnx ${m} --timeout 60000 # raise per-command budget (ms)
944
- `)}else bo();else if(l)bo();else{try{await _t(c)}catch{}try{await te({includeTail:!0})}catch{}try{await K({includeTail:!0})}catch{}}process.exit(1)}finally{c.close()}}export{Do as a,Ps as b,Bs as c,Cs as d,js as e,qs as f,se as g,Io as h,Ar as i};