sootsim 0.0.4 → 0.1.37

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 (165) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +24 -9
  3. package/dist-cli/bin.js +15 -20
  4. package/dist-cli/chunks/{agent-PJAOF4JS.js → agent-EQRQGSBL.js} +4 -4
  5. package/dist-cli/chunks/agent-wrapper-AWKZ67GN.js +15 -0
  6. package/dist-cli/chunks/{assert-P47NW4AF.js → assert-ZVGELUZB.js} +2 -2
  7. package/dist-cli/chunks/auto-bootstrap-UEOLNAWJ.js +2 -0
  8. package/dist-cli/chunks/beta-4MD7WSI4.js +2 -0
  9. package/dist-cli/chunks/chunk-2ZPJHSIJ.js +11 -0
  10. package/dist-cli/chunks/chunk-4IO3D5XG.js +2 -0
  11. package/dist-cli/chunks/chunk-4OHVCGMF.js +2 -0
  12. package/dist-cli/chunks/chunk-56BIMCDH.js +2 -0
  13. package/dist-cli/chunks/chunk-5FLDI6CV.js +66 -0
  14. package/dist-cli/chunks/{chunk-WWDJCKMI.js → chunk-B3RAGRK6.js} +1 -1
  15. package/dist-cli/chunks/chunk-BGAPLYMS.js +61 -0
  16. package/dist-cli/chunks/chunk-CX3ZIPD3.js +3 -0
  17. package/dist-cli/chunks/{chunk-I6XGFZPA.js → chunk-DSTV2VJT.js} +2 -2
  18. package/dist-cli/chunks/chunk-EDBFYOQB.js +2 -0
  19. package/dist-cli/chunks/chunk-ERLA3F77.js +1 -0
  20. package/dist-cli/chunks/chunk-FCQLQ7NA.js +117 -0
  21. package/dist-cli/chunks/chunk-H2HSOHXN.js +7 -0
  22. package/dist-cli/chunks/chunk-HYYMBXIX.js +2 -0
  23. package/dist-cli/chunks/chunk-JMGDVXAV.js +3 -0
  24. package/dist-cli/chunks/chunk-JMU5IGIU.js +1 -0
  25. package/dist-cli/chunks/chunk-KA5JJCWL.js +1 -0
  26. package/dist-cli/chunks/chunk-L4F4JRKJ.js +348 -0
  27. package/dist-cli/chunks/chunk-LDWXH43L.js +4 -0
  28. package/dist-cli/chunks/chunk-PERKPZ7T.js +4 -0
  29. package/dist-cli/chunks/chunk-PN6FWLD4.js +5 -0
  30. package/dist-cli/chunks/chunk-QD7YIVPS.js +64 -0
  31. package/dist-cli/chunks/chunk-QWKO62QM.js +2 -0
  32. package/dist-cli/chunks/{chunk-6SZMLFCR.js → chunk-QXMZNJV5.js} +1 -1
  33. package/dist-cli/chunks/chunk-R77F5J3X.js +4 -0
  34. package/dist-cli/chunks/chunk-RLNIKWFO.js +27 -0
  35. package/dist-cli/chunks/chunk-RX6RHGSI.js +2 -0
  36. package/dist-cli/chunks/chunk-S74RCIVB.js +2 -0
  37. package/dist-cli/chunks/chunk-SK4SOISL.js +1 -0
  38. package/dist-cli/chunks/{chunk-AFQBSK2J.js → chunk-T5L73GJB.js} +1 -1
  39. package/dist-cli/chunks/{chunk-432TMHBG.js → chunk-UIQ3536J.js} +1 -1
  40. package/dist-cli/chunks/chunk-URSEYCC5.js +16 -0
  41. package/dist-cli/chunks/chunk-WFXYY3DU.js +3 -0
  42. package/dist-cli/chunks/{chunk-DQKQYPIG.js → chunk-WHLHA5R5.js} +4 -4
  43. package/dist-cli/chunks/chunk-WLIVBPPY.js +3 -0
  44. package/dist-cli/chunks/{chunk-UQ3N6FZF.js → chunk-X6BP5JFC.js} +4 -4
  45. package/dist-cli/chunks/chunk-YFXTO4QX.js +5 -0
  46. package/dist-cli/chunks/{chunk-4XBPZQLW.js → chunk-Z5SVSAZO.js} +2 -2
  47. package/dist-cli/chunks/{chunk-5TTQKPGH.js → chunk-Z5X3PITK.js} +3 -3
  48. package/dist-cli/chunks/chunk-ZBOIGEGO.js +5 -0
  49. package/dist-cli/chunks/chunk-ZERYEI3L.js +17 -0
  50. package/dist-cli/chunks/{compat-ILLJ7VDL.js → compat-QQ3OJDBI.js} +2 -2
  51. package/dist-cli/chunks/{config-CDIAJIIT.js → config-LT27SC25.js} +2 -2
  52. package/dist-cli/chunks/control-3BO54QMO.js +2 -0
  53. package/dist-cli/chunks/cpu-profile-XEO3JCVB.js +22 -0
  54. package/dist-cli/chunks/daemon-3J2SAVQZ.js +83 -0
  55. package/dist-cli/chunks/{debug-6SMCTPMC.js → debug-OGQLIH4U.js} +4 -4
  56. package/dist-cli/chunks/demo-app-registry-5RZCXLWB.js +2 -0
  57. package/dist-cli/chunks/detox-Z2OSCIQU.js +49 -0
  58. package/dist-cli/chunks/device-RPTVD25S.js +16 -0
  59. package/dist-cli/chunks/diagnose-LAEXBNOQ.js +41 -0
  60. package/dist-cli/chunks/drivers-PSQUUAYC.js +2 -0
  61. package/dist-cli/chunks/electron-S2463O3P.js +18 -0
  62. package/dist-cli/chunks/flow-34YCVQDB.js +2 -0
  63. package/dist-cli/chunks/hints-E5PXPWFT.js +2 -0
  64. package/dist-cli/chunks/home-paths-F5SGBTRZ.js +2 -0
  65. package/dist-cli/chunks/inspect-EVGMEZ3G.js +1101 -0
  66. package/dist-cli/chunks/install-AM5PTJT3.js +2 -0
  67. package/dist-cli/chunks/install-desktop-ZNWYKTWQ.js +23 -0
  68. package/dist-cli/chunks/{keys-OWQ7SOTM.js → keys-5ETF6DYO.js} +2 -2
  69. package/dist-cli/chunks/{launch-WUEDHSO5.js → launch-DHUCNFX6.js} +3 -3
  70. package/dist-cli/chunks/login-KDR34JIP.js +26 -0
  71. package/dist-cli/chunks/logout-R6WIJYCW.js +2 -0
  72. package/dist-cli/chunks/maestro-ZOOJ2YVH.js +80 -0
  73. package/dist-cli/chunks/{preview-4RVHA2PP.js → preview-YFADHNBD.js} +2 -2
  74. package/dist-cli/chunks/profile-CQSC32HB.js +22 -0
  75. package/dist-cli/chunks/react-QSQD6CJE.js +30 -0
  76. package/dist-cli/chunks/{record-KEWLM5JR.js → record-IWLEYATN.js} +5 -5
  77. package/dist-cli/chunks/runtime-WKMNKYTN.js +25 -0
  78. package/dist-cli/chunks/screenshot-VJXHV57I.js +28 -0
  79. package/dist-cli/chunks/screenshot-mode-FA4VQ76K.js +17 -0
  80. package/dist-cli/chunks/screenshots-U4FQXHVK.js +70 -0
  81. package/dist-cli/chunks/server-7WZLM5NQ.js +35 -0
  82. package/dist-cli/chunks/setup-repo-3BXLAX5E.js +2 -0
  83. package/dist-cli/chunks/{skills-DJA6QEVR.js → skills-KO7RCY24.js} +2 -2
  84. package/dist-cli/chunks/start-EBD7T2GW.js +23 -0
  85. package/dist-cli/chunks/store-ONX3EBS4.js +2 -0
  86. package/dist-cli/chunks/telemetry-MFR7TUW7.js +2 -0
  87. package/dist-cli/chunks/{test-IWUHNFXV.js → test-OSVUG54G.js} +3 -3
  88. package/dist-cli/chunks/three-mode-MDBXZQG4.js +39 -0
  89. package/dist-cli/chunks/timeline-UJOKZKQR.js +22 -0
  90. package/dist-cli/chunks/upload-H2SMWP6T.js +2 -0
  91. package/dist-cli/chunks/what-happened-LFWH74FR.js +15 -0
  92. package/dist-cli/chunks/whoami-CUF56TLP.js +2 -0
  93. package/dist-lib/agent-daemon-client.cjs +6 -1
  94. package/dist-lib/agent-events.cjs +1 -1
  95. package/dist-lib/agent-sessions.cjs +42 -39
  96. package/dist-lib/attached-projects.cjs +30 -28
  97. package/dist-lib/auth/shared-session.cjs +35 -27
  98. package/dist-lib/backend-origin.cjs +1 -1
  99. package/dist-lib/bridge-constants.cjs +1 -1
  100. package/dist-lib/cli-constants.cjs +1 -1
  101. package/dist-lib/config.cjs +6 -2
  102. package/dist-lib/dev-bundle-resolution.cjs +7 -21
  103. package/dist-lib/home-paths.cjs +112 -30
  104. package/dist-lib/host/bridge-host.cjs +1817 -579
  105. package/dist-lib/host/fetch-proxy-handler.cjs +248 -0
  106. package/dist-lib/index.cjs +22 -22
  107. package/dist-lib/metro.cjs +22 -22
  108. package/dist-lib/profiles.cjs +246 -0
  109. package/dist-lib/render-mode.cjs +1 -1
  110. package/dist-lib/vite-base.cjs +3224 -764
  111. package/dist-lib/vite.cjs +1 -1
  112. package/package.json +11 -3
  113. package/dist-cli/chunks/agent-wrapper-STO7PLQD.js +0 -15
  114. package/dist-cli/chunks/auto-bootstrap-SC2LMI2H.js +0 -2
  115. package/dist-cli/chunks/chunk-47S5DXXX.js +0 -11
  116. package/dist-cli/chunks/chunk-4VXB2DBA.js +0 -119
  117. package/dist-cli/chunks/chunk-AUR2LTNX.js +0 -3
  118. package/dist-cli/chunks/chunk-BQRM4E66.js +0 -4
  119. package/dist-cli/chunks/chunk-C3QLIYCS.js +0 -16
  120. package/dist-cli/chunks/chunk-EHMSE3Q3.js +0 -2
  121. package/dist-cli/chunks/chunk-F4ARVCRR.js +0 -1
  122. package/dist-cli/chunks/chunk-HAKR72LJ.js +0 -2
  123. package/dist-cli/chunks/chunk-HGFIS26A.js +0 -2
  124. package/dist-cli/chunks/chunk-MQDPKSCK.js +0 -308
  125. package/dist-cli/chunks/chunk-MZPAJ5PQ.js +0 -1
  126. package/dist-cli/chunks/chunk-OAHMYSMD.js +0 -2
  127. package/dist-cli/chunks/chunk-QIP7LYQI.js +0 -5
  128. package/dist-cli/chunks/chunk-QQOBLF7O.js +0 -22
  129. package/dist-cli/chunks/chunk-SY74J6F4.js +0 -5
  130. package/dist-cli/chunks/chunk-UKYK63H6.js +0 -3
  131. package/dist-cli/chunks/chunk-UNFERMZ3.js +0 -27
  132. package/dist-cli/chunks/chunk-VGXARPIH.js +0 -3
  133. package/dist-cli/chunks/chunk-W3TYN64D.js +0 -62
  134. package/dist-cli/chunks/chunk-W7CYWXRZ.js +0 -4
  135. package/dist-cli/chunks/chunk-WRF43M33.js +0 -4
  136. package/dist-cli/chunks/chunk-WVBPATRA.js +0 -2
  137. package/dist-cli/chunks/chunk-XJF46GU2.js +0 -2
  138. package/dist-cli/chunks/chunk-ZF5FCFLD.js +0 -2
  139. package/dist-cli/chunks/chunk-ZKNI5MRD.js +0 -1
  140. package/dist-cli/chunks/control-7QGKUCAX.js +0 -2
  141. package/dist-cli/chunks/daemon-4BLYGM5N.js +0 -49
  142. package/dist-cli/chunks/demo-app-registry-HLI5UGGI.js +0 -2
  143. package/dist-cli/chunks/detox-R4G5INNB.js +0 -49
  144. package/dist-cli/chunks/device-YSLCWS4E.js +0 -16
  145. package/dist-cli/chunks/drivers-YIXRFFBQ.js +0 -2
  146. package/dist-cli/chunks/electron-JZOFO37G.js +0 -15
  147. package/dist-cli/chunks/flow-L7X5FGIN.js +0 -2
  148. package/dist-cli/chunks/hints-O4QR6UGI.js +0 -2
  149. package/dist-cli/chunks/home-paths-4YJJYGR6.js +0 -2
  150. package/dist-cli/chunks/inspect-DRFAUJUH.js +0 -1030
  151. package/dist-cli/chunks/install-BATRTWRI.js +0 -65
  152. package/dist-cli/chunks/install-desktop-6X474IQ3.js +0 -23
  153. package/dist-cli/chunks/install-dev-desktop-CAJHPRNP.js +0 -100
  154. package/dist-cli/chunks/login-54YJ2KH6.js +0 -26
  155. package/dist-cli/chunks/logout-XECXLEXW.js +0 -2
  156. package/dist-cli/chunks/maestro-PMHK6EHI.js +0 -75
  157. package/dist-cli/chunks/profile-3IVNHUS6.js +0 -22
  158. package/dist-cli/chunks/runtime-PJKHEB36.js +0 -25
  159. package/dist-cli/chunks/screenshot-BXRAQERZ.js +0 -26
  160. package/dist-cli/chunks/screenshot-mode-5IXEDIUS.js +0 -17
  161. package/dist-cli/chunks/screenshots-T4MQF3TB.js +0 -70
  162. package/dist-cli/chunks/server-CIP3LH45.js +0 -29
  163. package/dist-cli/chunks/store-SPC247DB.js +0 -2
  164. package/dist-cli/chunks/upload-UPD2RSYF.js +0 -2
  165. package/dist-cli/chunks/whoami-MCXFWKIH.js +0 -2
@@ -1,1030 +0,0 @@
1
- /*! sootsim v0.0.4 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as U}from"./chunk-VGXARPIH.js";import{a as Ne,b as _e}from"./chunk-AFQBSK2J.js";import{a as Y,b as E,c as C,d as z,e as ie,f as V,g as te,h as Ie,i as Fe,j as fe}from"./chunk-UQ3N6FZF.js";import{a as Te,e as ae}from"./chunk-I6XGFZPA.js";import{a as me,c as pe,d as xe}from"./chunk-4VXB2DBA.js";import{b as Ae,h as Pe}from"./chunk-47S5DXXX.js";import"./chunk-OAHMYSMD.js";import{a as Me}from"./chunk-5TTQKPGH.js";import"./chunk-WVBPATRA.js";import{a as we}from"./chunk-HGFIS26A.js";import{c as $e,e as Se,f as ke,h as ve}from"./chunk-C3QLIYCS.js";import"./chunk-W7CYWXRZ.js";import"./chunk-MZPAJ5PQ.js";import"./chunk-WRF43M33.js";import"./chunk-ZF5FCFLD.js";import"./chunk-SY74J6F4.js";import"./chunk-WWDJCKMI.js";import{existsSync as mt,mkdirSync as pt,readFileSync as ft,rmSync as Oe,writeFileSync as gt}from"fs";import{tmpdir as yt}from"os";import{dirname as bt,join as ht,resolve as wt}from"path";var oe=1,xt="SOOTSIM_INSPECT_NOTICE_PATH",$t=300*1e3,St=15e3;function Ee(){return wt(process.env[xt]||ht(yt(),"sootsim-inspect-notice-state.json"))}function kt(o,c){return Object.fromEntries(Object.entries(o).filter(([,i])=>typeof i?.signature=="string"&&Number.isFinite(i?.updatedAt)&&c-i.updatedAt<=$t))}function vt(o){let c=Ee();if(!mt(c))return{version:oe,entries:{}};try{let i=JSON.parse(ft(c,"utf8"));return i.version!==oe||!i.entries||typeof i.entries!="object"?(Oe(c,{force:!0}),{version:oe,entries:{}}):{version:oe,entries:kt(i.entries,o)}}catch{return Oe(c,{force:!0}),{version:oe,entries:{}}}}function Tt(o){let c=Ee();pt(bt(c),{recursive:!0}),gt(c,JSON.stringify(o,null,2)+`
3
- `)}function Mt(o,c){let i=c.trim()||"default";return`${o}:${i}`}function ge(o,c,i,d={}){let u=d.nowMs??Date.now(),a=d.cooldownMs??St,b=vt(u),k=Mt(o,c),$=b.entries[k];return $&&$.signature===i&&u-$.updatedAt<a?!1:(b.entries[k]={signature:i,updatedAt:u},Tt(b),!0)}async function Re(o,c={args:[]}){let i=await o.send({type:"evaluate",code:"(async () => await window.__sootsimTest.getNodeCount())()"}),d=typeof i=="number"?i:0;if(E(c.args)){C({nodes:d});return}console.log(` nodes: ${d}`)}function ye(o,c){let i=o.indexOf(c);return i>=0&&i+1<o.length?o[i+1]:null}async function Ce(o){let{bridge:c,args:i,positional:d}=o,u=i.includes("--verbose")||i.includes("-v"),a=E(i),b=u&&!a,k=i.includes("--watch")||i.includes("-w"),$=1e3,I=i.includes("--compact"),y=i.includes("--no-xy"),S=ye(i,"--testid-like"),A=ye(i,"--only"),v=ye(i,"--subtree"),j=d[1],l=j?/[*?]/.test(j):!1,R=!l&&!A?j:void 0,D=A??(l?j:void 0),q=async()=>{await ie(c,{verbose:b});let Z=`(async () => {
4
- const t = window.__sootsimTest
5
- const mainShell = window.SootSim?.bridges?.mainShell
6
- const kb = window.__sootsimKeyboard
7
- if (!t) return { error: 'no test bridge' }
8
-
9
- let shell = null
10
- try {
11
- shell = typeof mainShell?.getState === 'function' ? await mainShell.getState() : null
12
- } catch {}
13
-
14
- const tree = await t.dumpTree(12, ${JSON.stringify({describe:!0,verbose:u,filter:R||"",testIdLike:S||void 0,onlyGlob:D||void 0,subtreeRoot:v||void 0,compact:I,hideXy:y})})
15
- const nodeCount = (await t.getNodeCount?.()) || 0
16
- const keyboard = kb && typeof kb.getLayout === 'function' ? kb.getLayout() : null
17
- return { tree, shell, nodeCount, keyboard }
18
- })()`,x=await c.send({type:"evaluate",code:Z}),J=x?.tree,H=x?.shell,K=x?.keyboard;if(a){C({shell:H,tree:J??"",keyboard:K});return}if(H&&typeof H=="object"){let e=[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);e.length>0&&console.log(` shell: ${e.join(" ")}`)}if(typeof J=="string"&&J.startsWith("__SUBTREE_NOT_FOUND__:")){let e=J.slice(22);console.log(` subtree root not found: ${e}`),U("subtree-root-not-found",e);return}if(!J){let e=x?.nodeCount??0;console.log(" no matching nodes found"),!(R||S||D||v)&&e<10&&U("app-still-loading",e);return}if(console.log(J),!(R||S||D||v)&&!k&&J.split(`
19
- `).length>=80&&U("describe-use-filters"),K&&K.visible){let e=K.spec,t=[e?.keyboardType?`type=${e.keyboardType}`:null,e?.returnKeyType&&e.returnKeyType!=="default"?`return=${e.returnKeyType}`:null,K.mode!=="letters"?`mode=${K.mode}`:null,K.shifted?"shift":null,K.capsLock?"caps":null,e?.autoCapitalize&&e.autoCapitalize!=="sentences"?`autoCap=${e.autoCapitalize}`:null,K.accessoryBarId?`accessory=${K.accessoryBarId}`:null].filter(Boolean);console.log(`
20
- keyboard: ${t.join(" ")||"visible"}`)}};if(k)for(console.log(` watching... (Ctrl+C to stop)
21
- `);;)console.clear(),await q(),await Y($);else await q()}var Nt=["SOOTSIM_AGENT","CLAUDECODE","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE_SESSION_ID","CODEX_THREAD_ID","CURSOR_TRACE_ID","AIDER_MODEL"];function De(){if(process.env.SOOTSIM_AGENT==="0")return!1;for(let o of Nt){let c=process.env[o];if(c&&c.trim()&&c!=="0")return!0}return!1}async function Le(o){let{bridge:c,args:i,effectiveArgs:d,positional:u,inspectUsage:a}=o,b=x=>{let J=d.indexOf(x);return J>=0&&J+1<d.length?d[J+1]:null},k=x=>d.includes(x),$=b("--testid")||b("--test-id"),I=b("--role"),y=b("--type"),S=b("--text"),A=k("--pressable"),v=k("--visible"),j=!$&&!I&&!y&&!S&&!A&&!v?u[1]:null,l=S??j,R,D;$?(D="testid",R=`(async () => {
22
- const t = window.__sootsimTest
23
- return (await t.findByTestId(${JSON.stringify($)})) || (await t.findById(${JSON.stringify($)}))
24
- })()`):I?(D="role",R=`(async () => await window.__sootsimTest.queryAll({ hasRole: ${JSON.stringify(I)}, pruneHidden: true }))()`):y?(D="type",R=`(async () => await window.__sootsimTest.queryAll({ type: ${JSON.stringify(y)}, pruneHidden: true }))()`):A?(D="pressable",R=`(async () => {
25
- const t = window.__sootsimTest
26
- const all = await t.queryAll({ pruneHidden: true })
27
- return all.filter(n => n.pressable)
28
- })()`):v?(D="visible",R=`(async () => {
29
- const all = await window.__sootsimTest.queryAll({ pruneHidden: true })
30
- return all.filter(n => n.layout && n.layout.width > 0 && n.layout.height > 0)
31
- })()`):l?(D="text",R=`(async () => await window.__sootsimTest.findByText(${JSON.stringify(l)}))()`):(console.error(a("find","<text> | --text <t> | --testid <id> | --role <r> | --type <t> | --pressable | --visible")),process.exit(1));let q=await c.send({type:"evaluate",code:R}),ne=E(i),Z=i.includes("--verbose")||i.includes("--dump");if(ne)C(q??null);else if(Array.isArray(q))if(q.length===0){console.log(` no ${D} nodes found`);let x=await c.send({type:"evaluate",code:"(async () => (await window.__sootsimTest?.getNodeCount?.()) || 0)()"});typeof x=="number"&&x<10&&U("app-still-loading",x)}else{console.log(` found ${q.length} node${q.length===1?"":"s"} (${D}):`);for(let x of q.slice(0,20)){let J=x.absolutePosition?`@(${Math.round(x.absolutePosition.x)},${Math.round(x.absolutePosition.y)})`:"",H=x.layout?`${Math.round(x.layout.width)}x${Math.round(x.layout.height)}`:"?x?",K=x.text?` "${x.text.slice(0,30)}"`:"",Q=x.testID?` #${x.testID}`:"",e=x.pressable?" (tap)":"",t=x.accessibilityRole?`[${x.accessibilityRole}]`:x.type;console.log(` ${t}${K}${Q} ${H} ${J}${e}`),Z&&console.log(Be(JSON.stringify(x,null,2)," "))}q.length>20&&console.log(` ... and ${q.length-20} more`)}else if(q==null)console.log(` not found: ${l||$||I||y||""||D}`),$&&U("wait-selector-for-missing-testid",$);else{let x=q;if(x.type&&x.absolutePosition){let J=`@(${Math.round(x.absolutePosition.x)},${Math.round(x.absolutePosition.y)})`,H=x.layout?`${Math.round(x.layout.width)}x${Math.round(x.layout.height)}`:"?x?",K=x.text?` "${x.text.slice(0,40)}"`:"",Q=x.testID?` #${x.testID}`:"",e=x.pressable?" (tap)":"",t=x.accessibilityRole?`[${x.accessibilityRole}]`:x.type;console.log(` ${t}${K}${Q} ${H} ${J}${e}`),Z&&console.log(Be(JSON.stringify(x,null,2)," "))}else console.log(JSON.stringify(q,null,2))}}function Be(o,c){return o.split(`
32
- `).map(i=>c+i).join(`
33
- `)}async function je(o,c={}){let i=await o.send({type:"evaluate",code:`(() => {
34
- const kb = window.__sootsimKeyboard
35
- if (!kb || typeof kb.getLayout !== 'function') {
36
- return { error: 'keyboard bridge getLayout() not available' }
37
- }
38
- return kb.getLayout()
39
- })()`});if("error"in i&&(console.error(i.error),process.exit(1)),c.json){console.log(JSON.stringify(i,null,2));return}let{visible:d,spec:u,mode:a,shifted:b,capsLock:k,accessoryBarId:$}=i,I=[];I.push(`keyboard: ${d?"visible":"hidden"}`),u?(I.push(` type: ${u.keyboardType}`),I.push(` returnKey: ${u.returnKeyType}`),I.push(` autoCap: ${u.autoCapitalize}`),I.push(` autoCorrect: ${u.autoCorrect?"on":"off"}`),I.push(` appearance: ${u.keyboardAppearance}`),u.secureTextEntry&&I.push(" secureTextEntry: true"),u.enablesReturnKeyAutomatically&&I.push(` return: ${u.currentTextIsEmpty?"disabled (empty)":"enabled"}`)):I.push(" spec: <none> (shown via dev-tools with no TextInput)"),I.push(` mode: ${a}${b?" (shifted)":""}${k?" (caps)":""}`),$&&I.push(` accessoryBar: ${$}`),console.log(I.join(`
40
- `))}async function Je(o){let c=await o.bridge.listBrowsers();if(E(o.args)){C(c.map(i=>({...i,active:i.id===o.browserId})));return}Pe(c,o.browserId)}function X(o){return o<1024?`${o}B`:o<1024*1024?`${(o/1024).toFixed(1)}KB`:`${(o/1024/1024).toFixed(1)}MB`}function le(o,c){return c<=0?"?":`${(o/c*100).toFixed(0)}%`}async function He(o,c={args:[]}){let d=await o.send({type:"evaluate",code:`(async () => {
41
- const host = window.__sootsimRenderHost
42
- const stats = host?.queryStats ? await host.queryStats() : null
43
- const hostMem = performance.memory
44
- ? {
45
- usedJSHeapSize: performance.memory.usedJSHeapSize,
46
- totalJSHeapSize: performance.memory.totalJSHeapSize,
47
- jsHeapSizeLimit: performance.memory.jsHeapSizeLimit,
48
- }
49
- : null
50
- return {
51
- imageLoader: stats?.memory?.imageLoader ?? null,
52
- workerHeap: stats?.memory?.workerHeap ?? null,
53
- hostHeap: hostMem,
54
- }
55
- })()`})??{};if(E(c.args)){C(d);return}if(console.log(" memory:"),d.imageLoader){let u=d.imageLoader;console.log(" image-loader cache"),console.log(` entries: ${u.cacheEntries} / ${u.cacheMaxEntries} (${le(u.cacheEntries,u.cacheMaxEntries)})`),console.log(` pixel bytes: ${X(u.cachePixelBytes)} / ${X(u.cachePixelBudget)} (${le(u.cachePixelBytes,u.cachePixelBudget)})`),console.log(` pending: ${u.pendingFetches} fetches, ${u.pendingBytes} bytes`),console.log(` failed uris: ${u.failedUris}`),console.log(` snapshots: ${u.snapshots}`),console.log(` camera frames: ${u.cameraFrames}`)}else console.log(" image-loader cache: not available (engine pre-rebuild?)");if(d.workerHeap){let u=d.workerHeap;console.log(" worker heap (chrome only)"),console.log(` used: ${X(u.usedJSHeapSize)} / ${X(u.jsHeapSizeLimit)} (${le(u.usedJSHeapSize,u.jsHeapSizeLimit)})`),console.log(` total: ${X(u.totalJSHeapSize)}`)}if(d.hostHeap){let u=d.hostHeap;console.log(" host heap (chrome only)"),console.log(` used: ${X(u.usedJSHeapSize)} / ${X(u.jsHeapSizeLimit)} (${le(u.usedJSHeapSize,u.jsHeapSizeLimit)})`),console.log(` total: ${X(u.totalJSHeapSize)}`)}}function se(o){let c=o.indexOf("--testid");if(c>=0&&o[c+1])return{mode:"testid",value:o[c+1]};let i=o.indexOf("--test-id");if(i>=0&&o[i+1])return{mode:"testid",value:o[i+1]};let d=o.indexOf("--text");return d>=0&&o[d+1]?{mode:"text",value:o[d+1]}:null}async function ce(o,c){let i=JSON.stringify(c.value),d=c.mode==="testid"?`(await t.findByTestId(${i})) || (await t.findById(${i}))`:`await t.findByText(${i})`;return await o.send({type:"evaluate",code:`(async () => {
56
- const t = window.__sootsimTest
57
- if (!t) return null
58
- const n = ${d}
59
- if (!n || !n.absolutePosition || !n.layout) return null
60
- const resolved =
61
- typeof n.nodeId === 'number' && typeof t.resolveTapTarget === 'function'
62
- ? await t.resolveTapTarget(n.nodeId)
63
- : null
64
- const cx =
65
- typeof resolved?.cx === 'number'
66
- ? resolved.cx
67
- : n.absolutePosition.x + (n.layout.width || 0) / 2
68
- const cy =
69
- typeof resolved?.cy === 'number'
70
- ? resolved.cy
71
- : n.absolutePosition.y + (n.layout.height || 0) / 2
72
- return { x: cx, y: cy, testID: n.testID, text: n.text }
73
- })()`})??null}async function qe(o,c={}){let i=await o.send({type:"evaluate",code:`(async () => {
74
- const test = window.__sootsimTest
75
- const kb = window.__sootsimKeyboard
76
- const navSnap =
77
- test && typeof test.getNavigationSnapshot === 'function'
78
- ? test.getNavigationSnapshot()
79
- : null
80
- const keyboard =
81
- kb && typeof kb.getLayout === 'function'
82
- ? (() => {
83
- const layout = kb.getLayout()
84
- return layout ? {
85
- visible: layout.visible,
86
- mode: layout.mode,
87
- spec: layout.spec
88
- ? {
89
- keyboardType: layout.spec.keyboardType,
90
- returnKeyType: layout.spec.returnKeyType,
91
- }
92
- : null,
93
- } : null
94
- })()
95
- : null
96
- return { nav: navSnap, keyboard }
97
- })()`}),d=i?.nav??null,u=i?.keyboard??null,a=await V(o,500).catch(()=>null);if(c.json){console.log(JSON.stringify({shell:a??null,nav:d,keyboard:u},null,2));return}let b=[];if(a){let k=a.activeApp??a.state??"<none>",$=a.showSwitcher?" (app switcher open)":"",I=typeof a.launchProgress=="number"&&a.launchProgress<.98?` launching (${Math.round(a.launchProgress*100)}%)`:"";b.push(`shell: ${k}${$}${I}`)}else b.push("shell: <unavailable>");if(d){let k=d.transitionPhase!=="idle"?` (${d.transitionPhase}, ${d.activeTransitionCount} active)`:"";if(b.push(`nav: phase=${d.transitionPhase}${k}`),d.screens.length===0)b.push(" <no registered screens \u2014 app may not use react-native-screens>");else for(let $ of d.screens){let I=$.isActive?"\u25B6":" ",y=$.routeName?` ${$.routeName}`:"",S=$.headerHeight>0?` header=${$.headerHeight}`:"",A=$.largeTitleState&&$.largeTitleState!=="expanded"?` large-title=${$.largeTitleState}`:"";b.push(` ${I} #${$.id}${y}${S}${A}`)}}else b.push("nav: <runtime not available>");if(u&&u.visible){let k=u.spec?.keyboardType??"default",$=u.spec?.returnKeyType??"default";b.push(`keyboard: visible (${k}, return=${$}, mode=${u.mode??"?"})`)}else b.push("keyboard: hidden");console.log(b.join(`
98
- `))}async function ee({bridge:o,maxMs:c,pollMs:i=50,stablePolls:d=3,strict:u=!1}){let a=await o.send({type:"evaluate",code:`(async () => {
99
- const start = Date.now()
100
- const deadline = start + ${Math.max(0,Math.round(c))}
101
- const pollMs = ${Math.max(1,Math.round(i))}
102
- const requiredStablePolls = ${Math.max(1,Math.round(d))}
103
- const strict = ${u?"true":"false"}
104
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
105
- const readSnapshot = async () => {
106
- let animating = false
107
- try {
108
- const stats = await window.__sootsimRenderHost?.queryStats?.()
109
- if (stats) {
110
- animating =
111
- stats.hasActiveAnims === true ||
112
- stats.hasActiveNativeAnimations === true ||
113
- stats.hasPendingAnimationFrames === true
114
- }
115
- } catch {}
116
- const root = window.__sootsimRoot
117
- const nodes = []
118
- if (root) {
119
- const walk = (n) => {
120
- if (n.layout && n.layout.width > 0) {
121
- nodes.push(Math.round(n.layout.x) + ',' + Math.round(n.layout.y) + ',' + Math.round(n.layout.width))
122
- }
123
- for (const c of n.children || []) walk(c)
124
- }
125
- walk(root)
126
- }
127
- return { layout: nodes.join(';'), animating }
128
- }
129
-
130
- let lastLayout = ''
131
- let stable = 0
132
- while (Date.now() < deadline) {
133
- const snapshot = await readSnapshot()
134
- const strictOk = !strict || !snapshot.animating
135
- if (strictOk && snapshot.layout === lastLayout) {
136
- stable++
137
- if (stable >= requiredStablePolls) {
138
- return { settled: true, elapsed: Date.now() - start }
139
- }
140
- } else {
141
- stable = 0
142
- }
143
- lastLayout = snapshot.layout
144
- await sleep(pollMs)
145
- }
146
- return { settled: false, elapsed: Date.now() - start }
147
- })()`}),{elapsed:b,settled:k}=a??{};return{elapsed:typeof b=="number"?b:c,settled:k===!0}}async function We(o){let{bridge:c,args:i,positional:d}=o,u=d[1]?Number(d[1])*1e3:3e3,a=i.includes("--strict"),{elapsed:b,settled:k}=await ee({bridge:c,maxMs:u,strict:a});console.log(k?` settled in ${b}ms`:` timed out after ${b}ms (may still be animating)`)}async function ze(o){let c=o.positional[1]?Number(o.positional[1]):.5;(!Number.isFinite(c)||c<0)&&(console.error(o.inspectUsage("sleep","[seconds]")),process.exit(1)),await Y(c*1e3),console.log(` slept ${c}s`)}async function Ke(o){let{bridge:c,args:i,positional:d}=o,u=d[1]?Number(d[1]):5,a=await c.send({type:"evaluate",code:`(async () => await window.__sootsimTest.dumpTree(${u}))()`});if(E(i)){C({depth:u,tree:a??null});return}console.log(typeof a=="string"?a:JSON.stringify(a,null,2))}async function Ue(o,c={args:[]}){let i=await o.send({type:"evaluate",code:"window.location.href"}),d=typeof i=="string"?i:"";if(E(c.args)){C({url:d});return}console.log(d)}async function Ye(o){let{wsPort:c,commandTimeoutMs:i,browserId:d,positional:u}=o,a=u[1]?Number(u[1]):30,b=Math.max(1e3,(Number.isFinite(a)?a:30)*1e3),k=Math.max(1,Math.ceil(b/500));console.log(" waiting for browser reconnect...");let $=await Ie(c,i,d,{attempts:k});$||(console.error(" timed out waiting for browser reconnect"),process.exit(1)),$.bridge.close(),ae({source:"inspect wait",step:{wait:b},summary:`wait ${Math.round(b/1e3)}s`}),console.log(` ready: ${$.count} nodes`)}async function Ge(o){let{bridge:c,args:i}=o,d=i.includes("--strict"),u=i.indexOf("--max-ms"),a=u>=0&&i[u+1]?Math.max(100,Number(i[u+1])):3e3,{elapsed:b,settled:k}=await ee({bridge:c,maxMs:a,strict:d});k?console.log(` idle in ${b}ms`):(console.error(` \u26A0 wait idle timed out after ${b}ms (may still be animating)`),process.exit(1))}async function Xe(o){let{bridge:c,args:i}=o,d=2e4,u=i.indexOf("--max-ms");u>=0&&i[u+1]&&(d=Math.max(100,Number(i[u+1])));let a=Date.now(),b=a+d,k=`(async () => {
148
- const t = window.__sootsimTest
149
- let nodes = 0
150
- try { nodes = (await t?.getNodeCount?.()) || 0 } catch {}
151
- return {
152
- flag: (window).__sootsimExternalAppReady,
153
- at: (window).__sootsimExternalAppReadyAt || 0,
154
- nodes,
155
- }
156
- })()`,$={flag:void 0,at:0,nodes:0};for(;Date.now()<b;){try{$=await c.send({type:"evaluate",code:k})??$}catch{}if($.flag===!0){console.log(` ready in ${Date.now()-a}ms: ${$.nodes} nodes (flag)`);return}await new Promise(I=>setTimeout(I,150))}console.error(` \u26A0 wait ready timed out after ${Date.now()-a}ms \u2014 guest app did not emit sootsim:externalAppReady (nodes: ${$.nodes})`),process.exit(1)}async function Ve(o){let{bridge:c,args:i,positional:d,inspectUsage:u}=o,a=d[1];a||(console.error(u("wait selector","<testid> [--max-ms 5000]")),process.exit(1));let b=i.indexOf("--max-ms"),k=b>=0&&i[b+1]?Math.max(100,Number(i[b+1])):5e3,$=await c.send({type:"evaluate",code:`(async () => {
157
- const start = Date.now()
158
- const deadline = start + ${k}
159
- const t = window.__sootsimTest
160
- const find = async () => {
161
- try {
162
- return (await t?.findByTestId?.(${JSON.stringify(a)})) ||
163
- (await t?.findById?.(${JSON.stringify(a)})) || null
164
- } catch {}
165
- return null
166
- }
167
- while (Date.now() < deadline) {
168
- const node = await find()
169
- if (node && node.layout && node.layout.width > 0 && node.layout.height > 0) {
170
- return { found: true, node, elapsed: Date.now() - start }
171
- }
172
- await new Promise((r) => setTimeout(r, 80))
173
- }
174
- return { found: false, elapsed: Date.now() - start }
175
- })()`}),{found:I,node:y,elapsed:S}=$??{};if(I&&y){let A=y.absolutePosition?`@(${Math.round(y.absolutePosition.x)},${Math.round(y.absolutePosition.y)})`:"",v=y.layout?`${Math.round(y.layout.width)}x${Math.round(y.layout.height)}`:"?x?";console.log(` found #${a} in ${S}ms ${v} ${A}`)}else console.error(` \u26A0 wait selector #${a} timed out after ${S??k}ms`),process.exit(1)}function nt(o){return o==null?"\u2014":o<1024?`${o}B`:o<1024*1024?`${(o/1024).toFixed(1)}K`:`${(o/1024/1024).toFixed(1)}M`}function rt(o){return o==null?" \u2026":o<1e3?`${o}ms`.padStart(5):`${(o/1e3).toFixed(2)}s`.padStart(5)}function It(o){return o.error?"err":o.status==null?" \u2026 ":String(o.status)}function Ze(o){let c=new Date(o.startTs).toLocaleTimeString(),i=It(o).padEnd(3),d=o.method.padEnd(5),u=nt(o.size).padStart(6),a=rt(o.durationMs);console.log(` [${c}] ${i} ${d} ${u} ${a} ${o.displayUrl}`),o.error&&console.log(` error: ${o.error}`)}function Ft(o){let c=[["id",o.id],["source",o.source],["kind",o.kind],["method",o.method],["status",o.error?`error: ${o.error}`:`${o.status??"\u2014"} ${o.statusText??""}`.trim()],["url",o.url],["started",new Date(o.startTs).toLocaleTimeString()],["duration",rt(o.durationMs).trim()],["size",nt(o.size)],["content-type",o.type??"\u2014"]];for(let[i,d]of c)console.log(` ${i.padEnd(13)} ${d}`)}var At={error:"\x1B[31m",warn:"\x1B[33m",info:"\x1B[36m",debug:"\x1B[35m",log:"\x1B[37m"},Qe="\x1B[0m",Pt="\x1B[2m";function et(o,c){let i=new Date(o.ts).toLocaleTimeString(),d=o.level.toUpperCase().padEnd(5),u=o.args.join(" ");if(c){let a=At[o.level];console.log(` ${Pt}[${i}]${Qe} ${a}${d}${Qe} ${u}`)}else console.log(` [${i}] ${d} ${u}`);if(o.stack&&o.level==="error"){let a=o.stack.split(`
176
- `).slice(0,5);for(let b of a)console.log(` ${b.trim()}`)}}var G="__sootsimCliPerf",Ot=120;async function tt(o,c){let i=o.find((A,v)=>o[v-1]==="--id"),d=o.find((A,v)=>o[v-1]==="--text");if(i||d){let A=await c.send({type:"evaluate",code:Ne({id:i,text:d})});if(!A)throw new Error(i?`no node with id "${i}"`:`no node matching text "${d}"`);let{x:v,y:j,w:l,h:R}=A;return{x:v,y:j,w:l,h:R}}let u=o.find((A,v)=>o[v-1]==="--area");if(u){let A=u.split(",").map(D=>Number(D.trim()));if(A.length!==4||A.some(D=>!Number.isFinite(D)))throw new Error(`--area expects x,y,w,h (got "${u}")`);let[v,j,l,R]=A;return{x:v,y:j,w:l,h:R}}let a=A=>{let v=o.find((l,R)=>o[R-1]===A);if(v==null)return null;let j=Number(v);return Number.isFinite(j)?j:null},b=a("--x"),k=a("--y"),$=a("--w"),I=a("--h");if(b!=null||k!=null||$!=null||I!=null)return{x:b??0,y:k??0,w:$??1,h:I??1};let S=o.filter((A,v)=>v>0&&!A.startsWith("-")&&o[v-1]!=="--output"&&o[v-1]!=="--area"&&o[v-1]!=="--id"&&o[v-1]!=="--text"&&o[v-1]!=="--x"&&o[v-1]!=="--y"&&o[v-1]!=="--w"&&o[v-1]!=="--h").map(Number).filter(A=>Number.isFinite(A));if(S.length>=2){let[A,v,j=1,l=1]=S;return{x:A,y:v,w:j,h:l}}return null}function be(o){let c={"<8":0,"8-12":0,"12-16":0,"16-20":0,"20-33":0,">33":0};for(let i of o)i<8?c["<8"]++:i<12?c["8-12"]++:i<16?c["12-16"]++:i<20?c["16-20"]++:i<33?c["20-33"]++:c[">33"]++;console.log(" histogram:");for(let[i,d]of Object.entries(c)){let u="\u2588".repeat(Math.ceil(d/o.length*40));console.log(` ${i.padEnd(6)} ${u} ${d}`)}}async function de(o,c,i){let d=Date.now()+c,u=await V(o,c);for(;;){if(i(u))return{settled:!0,state:u};if(Date.now()>=d)return{settled:!1,state:u};await Y(16),u=await V(o)}}async function he(o){return o.send({type:"evaluate",code:`(async () => {
177
- const kb = window.__sootsimKeyboard
178
- const test = window.__sootsimTest
179
- if (!kb) return { error: 'keyboard bridge not available' }
180
- const visible = kb.isVisible()
181
- const mode = kb.getMode()
182
- let focused = null
183
- if (test && typeof test.getFocusedNode === 'function') {
184
- try {
185
- focused = await test.getFocusedNode()
186
- } catch {}
187
- }
188
- let runtimeSnapshot = null
189
- if (test && typeof test.getFocusKeyboardSnapshot === 'function') {
190
- try {
191
- runtimeSnapshot = await test.getFocusKeyboardSnapshot()
192
- } catch {}
193
- }
194
- return {
195
- visible,
196
- mode,
197
- focusedInput: focused ? {
198
- nodeId: focused.nodeId ?? null,
199
- testID: focused.testID || null,
200
- id: focused.id || null,
201
- placeholder: focused.placeholder || null,
202
- text: focused.text || null,
203
- } : null,
204
- phase: runtimeSnapshot?.keyboard?.phase ?? null,
205
- frame: runtimeSnapshot?.keyboard?.frame ?? null,
206
- focusedRect: runtimeSnapshot?.focused?.rect ?? null,
207
- }
208
- })()`})}async function Et(o,c=600){let i=Date.now()+c;for(;Date.now()<=i;){let d=await he(o);if(d.visible)return d;await Y(30)}return he(o)}async function ue(o,c){let i=await he(o);if(i.visible)return i;console.error(` ${c} requires the iOS keyboard to be visible. focus an input first with sootsim do tap-id/tap-text or sootsim do type-into.`),process.exit(1)}async function ot(o,c,i){return c==="appearance"?o.send({type:"evaluate",code:`(async () => {
209
- const requested = ${JSON.stringify(i??"toggle")}
210
- const rootBg = (document.documentElement?.style?.background || '').toLowerCase()
211
- const inferredCurrent = rootBg.includes('33') ? 'dark' : 'light'
212
- let applied = requested
213
- if (requested === 'toggle') {
214
- applied = inferredCurrent === 'dark' ? 'light' : 'dark'
215
- } else if (requested === 'auto') {
216
- applied = window.matchMedia?.('(prefers-color-scheme: dark)')?.matches ? 'dark' : 'light'
217
- }
218
- window.postMessage({ type: 'soot-action', action: 'set-appearance', value: applied }, '*')
219
- return { ok: true, requested, applied }
220
- })()`}):o.send({type:"evaluate",code:`(async () => {
221
- window.dispatchEvent(new CustomEvent(${JSON.stringify(c==="lock"?"sootsim:toggleLock":"sootsim:shake")}))
222
- return { ok: true, action: ${JSON.stringify(c)} }
223
- })()`})}function Rt(o){let c={Enter:"return",NumpadEnter:"return",Backspace:"delete",Delete:"delete",Space:"space",ShiftLeft:"shift",ShiftRight:"shift"};if(c[o])return c[o];let i=o.match(/^Digit([0-9])$/);if(i)return i[1];let d=o.match(/^Key([A-Z])$/);return d?d[1].toLowerCase():null}function Ct(o){if(typeof o!="string")return null;let c=o.replace(/\s+/g," ").trim();return c?c.slice(0,80):null}function at(...o){for(let c of o){if(typeof c!="string")continue;let i=c.trim();if(i)return i}return null}async function L(o,c,i){ae({source:o,step:c,summary:i})}function Dt(o,c,i){if(!i||i.hit===!1)return null;let d=at(i.responderTestID,i.testID);if(d)return{step:{tapOn:{id:d}},summary:`tap #${d}`};let u=Ct(i.text);return u?{step:{tapOn:u},summary:`tap "${u}"`}:{step:{tapAtCoords:{x:o,y:c}},summary:`tap @${Math.round(o)},${Math.round(c)}`}}function st(o,c,i){let d=at(c?.testID,c?.id);return d?{step:{tapOn:{id:d}},summary:`tap #${d}`}:i==="id"?{step:{tapOn:{id:o}},summary:`tap #${o}`}:{step:{tapOn:o},summary:`tap "${o}"`}}async function rs(o,c){let i=o[0]==="get"||o[0]==="do"||o[0]==="debug"||o[0]==="wait"?o[0]:null,d=i?o.slice(1):o,u=$e(d,{port:c.port,commandTimeoutMs:c.timeoutMs,stripBooleanFlags:["--verbose","-v","--help","-h","--clear-state","--json","--all","--watch","-w","--strict","--no-wait","--dump","--failed","--tail","-f","--internal"],stripValueFlags:["--output","--nth","--index","--testid","--test-id","--text","--max-ms","--filter","--limit","--level"]}),a=u.positional,b=a[0],k=i==="get"||i==="do"||i==="debug"||i==="wait"?i:"inspect",$=typeof d[0]=="string"&&xe.has(d[0]),I=$?d[0]:null,y=e=>$&&e===d[0]?`sootsim ${e}`:`sootsim ${k} ${e}`,S=(e,t)=>` usage: ${y(e)}${t?` ${t}`:""}`;if(!b||o.includes("--help")||o.includes("-h")){let e={bridgePort:7668,defaultShellUrl:we};if(k==="do"||k==="get"||k==="debug"||k==="wait"){let r=me(k,e);r&&(console.log(`${r}
224
- `),process.exit(0))}if(I==="shell"){let r=pe("shell",e);r&&(console.log(`${r}
225
- `),process.exit(0))}let t=pe("inspect",e),s=["do","get","debug","wait"].map(r=>me(r,e)).filter(r=>r!=null).join(`
226
-
227
- `);console.log(`${t??""}
228
-
229
- ${s}
230
- `),process.exit(0)}let A=u.wsPort,v=u.browserId,j=u.commandTimeoutMs;if(b==="list"&&d.some(e=>e==="--drivers"||e==="-D")){let{buildDriverListRows:e}=await import("./drivers-YIXRFFBQ.js"),t=e();console.log(` available drivers (${t.length}):
231
- `);let s=Math.max(...t.map(n=>n.id.length),6),r=Math.max(...t.map(n=>n.kind.length),4);for(let n of t){let m=n.available?"\u2713":"\u2717",p=n.id.padEnd(s),h=n.kind.padEnd(r);console.log(` ${m} ${p} ${h} ${n.description}`),n.available&&n.detail?console.log(` ${n.detail}`):!n.available&&n.reason&&console.log(` unavailable: ${n.reason}`)}return}let l=Se(u),R=v||"default",D=new Set(["errors","warnings","requests","js","eval","reload","globals","perf","list","wait","sleep"]);function q(e){let t=e.displayUrl||e.url;return e.status!=null?`${e.method} ${t} -> ${e.status}${e.statusText?` ${e.statusText}`:""}`:e.error?`${e.method} ${t} -> ${e.error}`:`${e.method} ${t}`}async function ne(e){let t=De()?1200:350;try{let{settled:s,elapsed:r}=await ee({bridge:e,maxMs:t,pollMs:32,stablePolls:2});s||process.stderr.write(` \u26A0 auto-wait timed out after ${r??t}ms \u2014 next command may see mid-animation state. use \`sootsim do settle\` for a longer wait.
232
- `)}catch{}}async function Z(){try{return await l.send({type:"evaluate",code:`(() => ({
233
- console: window.__sootsimConsole?.count?.() || null,
234
- requests: window.__sootsimTest?.getRequestCounts?.() || null,
235
- }))()`})||{console:null,requests:null}}catch{return{console:null,requests:null}}}async function x(e={}){let t=e.counts!==void 0?e.counts:await z(l,"getRequestCounts");if(!t||typeof t!="object")return;let s=Math.max(0,Number(t.failed)||0);if(s===0||!e.includeTail&&!ge("requests",R,String(s))||(console.log(`
236
- network: ${s} failed request${s===1?"":"s"}`),console.log(` inspect: ${y("requests")} 5`),!e.includeTail))return;let r=await z(l,"getFailedRequests",5);if(!(!Array.isArray(r)||r.length===0)){console.log(`
237
- recent failed requests:
238
- `);for(let n of r){let m=new Date(n.timestamp).toLocaleTimeString();console.log(` [${m}] ${q(n)}`),n.responseBody?console.log(` ${n.responseBody}`):n.error&&console.log(` ${n.error}`)}}}async function J(e={}){let t=e.counts!==void 0?e.counts:await l.send({type:"evaluate",code:"window.__sootsimConsole?.count?.() || { errors: 0, warnings: 0, total: 0 }"});if(!t||typeof t!="object")return;let s=t,r=Math.max(0,Number(s.errors)||0),n=Math.max(0,Number(s.warnings)||0);if(r===0&&n===0||!e.includeTail&&!ge("console",R,`${r}:${n}`))return;let m=[];if(r>0&&m.push(`${r} console error${r===1?"":"s"}`),n>0&&m.push(`${n} console warning${n===1?"":"s"}`),console.log(`
239
- console: ${m.join(", ")}`),console.log(` inspect: ${y("errors")} 5`),n>0&&console.log(` inspect: ${y("warnings")} 5`),!e.includeTail||r===0)return;let p=await l.send({type:"evaluate",code:"window.__sootsimConsole?.getErrors?.(5) || []"});if(!(!Array.isArray(p)||p.length===0)){console.log(`
240
- recent console errors:
241
- `);for(let h of p){let f=new Date(h.timestamp).toLocaleTimeString(),w=Array.isArray(h.args)?h.args.map(O=>typeof O=="object"?JSON.stringify(O):String(O)).join(" "):String(h);console.log(` [${f}] ${w}`)}}}let H=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"]),K=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"]),Q=(o.includes("--verbose")||o.includes("-v"))&&!o.includes("--json");k==="do"&&b==="shell"&&(console.error(" `sootsim do shell` was removed. use `sootsim shell ...` instead."),process.exit(1)),H.has(b)&&await ke(l),K.has(b)&&await ie(l,{verbose:Q});try{switch(b){case"list":{await Je({bridge:l,browserId:v,args:d});break}case"tree":{await Ke({bridge:l,args:d,positional:a});break}case"a11y":{let e=a[1]?Number(a[1]):5,t=await l.send({type:"evaluate",code:`(async () => {
242
- const t = window.__sootsimTest
243
- if (!t) return []
244
- const all = await t.queryAll({ pruneHidden: true })
245
- return all.filter(n => {
246
- // skip zero-size nodes
247
- if (!n.layout || n.layout.width <= 0 || n.layout.height <= 0) return false
248
- // keep nodes with explicit accessibility roles or labels
249
- if (n.accessibilityRole) return true
250
- if (n.accessibilityHint) return true
251
- if (n.isTextInput) return true
252
- if (n.pressable) return true
253
- // keep text leaf nodes
254
- if (n.type === 'text' && n.text) return true
255
- // keep views with intentional labels (not auto-derived)
256
- if (n.accessibilityLabel && n.accessibilityLabel.length <= 30
257
- && n.accessibilityLabel !== n.text) return true
258
- // skip container views without role (just concatenated child text)
259
- return false
260
- }).map(n => ({
261
- role: n.accessibilityRole || (n.pressable ? 'button' : n.isTextInput ? 'textfield' : n.type === 'text' ? 'statictext' : 'none'),
262
- label: n.accessibilityLabel || n.text || null,
263
- hint: n.accessibilityHint || null,
264
- state: n.accessibilityState || null,
265
- testID: n.testID || null,
266
- position: n.absolutePosition ? { x: Math.round(n.absolutePosition.x), y: Math.round(n.absolutePosition.y) } : null,
267
- size: n.layout ? { w: Math.round(n.layout.width), h: Math.round(n.layout.height) } : null,
268
- }))
269
- })()`});if(!Array.isArray(t)||t.length===0){console.log(" no accessible nodes found");break}if(o.includes("--json"))console.log(JSON.stringify(t,null,2));else{console.log(` accessibility tree (${t.length} nodes):
270
- `);for(let s of t){let r=[];if(r.push(`[${s.role}]`),s.label){let n=s.label.length>50?s.label.slice(0,47)+"...":s.label;r.push(`"${n}"`)}if(s.hint&&r.push(`(hint: "${s.hint}")`),s.testID&&r.push(`#${s.testID}`),s.state){let n=[];s.state.disabled&&n.push("disabled"),s.state.selected&&n.push("selected"),s.state.checked===!0&&n.push("checked"),s.state.checked==="mixed"&&n.push("mixed"),s.state.busy&&n.push("busy"),s.state.expanded===!0&&n.push("expanded"),s.state.expanded===!1&&n.push("collapsed"),n.length&&r.push(`{${n.join(", ")}}`)}s.position&&r.push(`@(${s.position.x},${s.position.y})`),s.size&&r.push(`${s.size.w}x${s.size.h}`),console.log(" "+r.join(" "))}}break}case"find":{await Le({bridge:l,args:o,effectiveArgs:d,positional:a,inspectUsage:S});break}case"count":{await Re(l,{args:d});break}case"keyboard":{await je(l,{json:o.includes("--json")});break}case"screens":{await qe(l,{json:o.includes("--json")});break}case"memory":{await He(l,{args:d});break}case"wait":{await Ye({wsPort:A,commandTimeoutMs:j,browserId:v,positional:a});break}case"sleep":{await ze({positional:a,inspectUsage:S});break}case"settle":{await We({bridge:l,args:o,positional:a});break}case"ready":{await Xe({bridge:l,args:o});break}case"idle":{await Ge({bridge:l,args:o,positional:a});break}case"selector":{await Ve({bridge:l,args:o,positional:a,inspectUsage:S});break}case"layout":{let e=a[1];e||(console.error(S("layout","<id>")),process.exit(1));let t=await l.send({type:"evaluate",code:`(async () => await window.__sootsimTest.getLayout(${JSON.stringify(e)}))()`});console.log(JSON.stringify(t,null,2));break}case"capture":case"screenshot":{let t=o.find((h,f)=>o[f-1]==="--output")||"/tmp/sootsim-inspect.png",s=await tt(o,l),r={type:"screenshot"};s&&(r.crop=s);let m=(await l.send(r)).replace(/^data:image\/png;base64,/,"");s&&console.log(` area: x=${s.x} y=${s.y} w=${s.w} h=${s.h}`),(await import("fs")).writeFileSync(t,Buffer.from(m,"base64")),console.log(` saved: ${t}`);break}case"sample-color":{let e=await tt(o,l);e||(console.error(S("sample-color","<x> <y> [w] [h] | --id <testID> | --text <text>")),console.error(" samples an averaged color from the canvas. coords are logical sootsim units."),process.exit(1));let t=await l.send({type:"evaluate",code:_e(e)});if(o.includes("--json"))console.log(JSON.stringify(t,null,2));else{let{r:s,g:r,b:n,a:m,hex:p,samples:h}=t,f=e.w===1&&e.h===1?`@(${e.x},${e.y})`:`@(${e.x},${e.y}) ${e.w}x${e.h}`;console.log(` ${p} rgba(${s}, ${r}, ${n}, ${m}) ${f} ${h} samples`)}break}case"node":{let e=a[1];e||(console.error(S("node","<matcher>")),console.error(" resolves testID, id, then text \u2014 dumps full node info as JSON"),process.exit(1));let t=await l.send({type:"evaluate",code:`(async () => {
271
- const t = window.__sootsimTest
272
- const q = ${JSON.stringify(e)}
273
- let node = null
274
- let via = null
275
- if (t.findByTestId) { node = await t.findByTestId(q); if (node) via = 'testID' }
276
- if (!node && t.findById) { node = await t.findById(q); if (node) via = 'id' }
277
- if (!node && t.findByText) { node = await t.findByText(q); if (node) via = 'text' }
278
- if (!node) return { matcher: q, found: false }
279
-
280
- // read the resolved transform (if any) off the style \u2014 useful
281
- // because canvas nodes often animate via transform and describe
282
- // output strips that.
283
- const transform =
284
- node.style && Array.isArray(node.style.transform)
285
- ? node.style.transform
286
- : node.style && node.style.transform
287
- ? node.style.transform
288
- : null
289
-
290
- // parent chain \u2014 walk up from the node so the JSON dump is
291
- // self-describing.
292
- const parentChain = []
293
- const root = window.__sootsimRoot
294
- if (root && node.id != null) {
295
- const findPath = (n, targetId, path) => {
296
- if (!n) return null
297
- if (n.id === targetId) return path
298
- if (n.children) {
299
- for (const child of n.children) {
300
- const nextPath = [
301
- ...path,
302
- {
303
- type: n.type || 'view',
304
- testID: n.props?.testID || null,
305
- text: n.text || null,
306
- },
307
- ]
308
- const found = findPath(child, targetId, nextPath)
309
- if (found) return found
310
- }
311
- }
312
- return null
313
- }
314
- const chain = findPath(root, node.id, [])
315
- if (chain) parentChain.push(...chain)
316
- }
317
-
318
- return {
319
- matcher: q,
320
- found: true,
321
- resolvedVia: via,
322
- node,
323
- transform,
324
- parentChain,
325
- }
326
- })()`});console.log(JSON.stringify(t,null,2));break}case"tap":{let e=Number(a[1]),t=Number(a[2]),s=se(o);if(s){let m=await ce(l,s);m||(console.error(` not found: ${s.value}`),s.mode==="testid"&&U("wait-selector-for-missing-testid",s.value),process.exit(1)),e=m.x,t=m.y}(!Number.isFinite(e)||!Number.isFinite(t))&&(console.error(S("tap","<x> <y> | --testid <id> | --text <t>")),process.exit(1));let r=await l.send({type:"tap",x:e,y:t}),n=Dt(e,t,r);n&&await L("inspect tap",n.step,n.summary),console.log(JSON.stringify(r,null,2));break}case"drag":case"swipe":{let e=Number(a[1]),t=Number(a[2]),s=Number(a[3]),r=Number(a[4]),n=b==="swipe"?10:12,m=b==="swipe"?8:16,p=a[5]?Number(a[5]):n,h=a[6]?Number(a[6]):m;(!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(p)||!Number.isFinite(h))&&(console.error(S(b,"<x1> <y1> <x2> <y2> [steps] [stepMs]")),process.exit(1));let f=await l.send({type:"evaluate",code:`(async () => {
327
- const interact = window.__sootsimInteract
328
- if (!interact?.drag) return { ok: false, reason: 'no interact.drag' }
329
- const value = await interact.drag(${e}, ${t}, ${s}, ${r}, ${Math.max(1,Math.round(p))}, ${Math.max(0,Math.round(h))})
330
- return { ok: !!value, value }
331
- })()`});if(f?.ok){let w=Math.max(1,Math.round(Math.max(1,p)*Math.max(0,h)));await L(`inspect ${b}`,{swipe:{start:`${e}, ${t}`,end:`${s}, ${r}`,duration:w}},`${b} ${e},${t} -> ${s},${r}`)}console.log(JSON.stringify(f,null,2));break}case"pinch":{let e=Number(a[1]),t=Number(a[2]),s=Number(a[3]),r=Number(a[4]),n=Number(a[5]),m=Number(a[6]),p=Number(a[7]),h=Number(a[8]),f=a[9]?Number(a[9]):12,w=a[10]?Number(a[10]):16;(!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(n)||!Number.isFinite(m)||!Number.isFinite(p)||!Number.isFinite(h)||!Number.isFinite(f)||!Number.isFinite(w))&&(console.error(S("pinch","<x1> <y1> <x2> <y2> <x1'> <y1'> <x2'> <y2'> [steps] [stepMs]")),process.exit(1));let O=await l.send({type:"evaluate",code:`(async () => {
332
- const interact = window.__sootsimInteract
333
- if (!interact?.pinch) return { ok: false, reason: 'no interact.pinch' }
334
- const value = await interact.pinch(${e}, ${t}, ${s}, ${r}, ${n}, ${m}, ${p}, ${h}, ${Math.max(1,Math.round(f))}, ${Math.max(0,Math.round(w))})
335
- return { ok: !!value, value }
336
- })()`});O?.ok&&await L("inspect pinch",{pinch:{from:[e,t,s,r],to:[n,m,p,h],steps:Math.max(1,Math.round(f)),stepMs:Math.max(0,Math.round(w))}},`pinch (${e},${t}) (${s},${r}) -> (${n},${m}) (${p},${h})`),console.log(JSON.stringify(O,null,2));break}case"tap-text":{let e=a[1];e||(console.error(S("tap-text","<text>")),process.exit(1));let t=_=>{let P=o.indexOf(_);return P>=0&&P+1<o.length?o[P+1]:null},s=_=>o.includes(_),r=t("--nth")??t("--index"),n=r!==null?Number(r):null;n!==null&&!Number.isFinite(n)&&(console.error(` --nth/--index requires an integer, got: ${r}`),process.exit(1));let m=t("--within"),p=t("--role"),h=s("--exact"),f=s("--first"),w=t("--min-y"),O=t("--max-y"),B=t("--min-x"),N=t("--max-x");for(let[_,P]of[["--min-y",w],["--max-y",O],["--min-x",B],["--max-x",N]])P!==null&&!Number.isFinite(Number(P))&&(console.error(` ${_} requires a number, got: ${P}`),process.exit(1));let M=o.indexOf("--near"),F=null;if(M>=0){let _=Number(o[M+1]),P=Number(o[M+2]);(!Number.isFinite(_)||!Number.isFinite(P))&&(console.error(" --near requires two numbers: --near <x> <y>"),process.exit(1)),F={x:_,y:P}}let W=JSON.stringify({query:e,exact:h,role:p,within:m,minX:B!==null?Number(B):null,maxX:N!==null?Number(N):null,minY:w!==null?Number(w):null,maxY:O!==null?Number(O):null,near:F,nth:n,first:f}),g=await l.send({type:"evaluate",code:`(async () => {
337
- const t = window.__sootsimTest
338
- if (!t) return { error: 'bridge-not-ready' }
339
- const F = ${W}
340
-
341
- const res = await t.queryTextCandidates({
342
- query: F.query,
343
- exact: !!F.exact,
344
- ...(F.role ? { role: F.role } : {}),
345
- })
346
-
347
- let candidates = res.candidates || []
348
-
349
- candidates = candidates.filter((c) => {
350
- const ax = c.info.absolutePosition && c.info.absolutePosition.x
351
- const ay = c.info.absolutePosition && c.info.absolutePosition.y
352
- if (F.minX !== null && !(ax >= F.minX)) return false
353
- if (F.maxX !== null && !(ax <= F.maxX)) return false
354
- if (F.minY !== null && !(ay >= F.minY)) return false
355
- if (F.maxY !== null && !(ay <= F.maxY)) return false
356
- if (F.within && !c.ancestorTestIDs.includes(F.within)) return false
357
- return true
358
- })
359
-
360
- if (F.near) {
361
- candidates.sort((a, b) => {
362
- const ax = (a.info.absolutePosition && a.info.absolutePosition.x) || 0
363
- const ay = (a.info.absolutePosition && a.info.absolutePosition.y) || 0
364
- const bx = (b.info.absolutePosition && b.info.absolutePosition.x) || 0
365
- const by = (b.info.absolutePosition && b.info.absolutePosition.y) || 0
366
- return (
367
- Math.hypot(ax - F.near.x, ay - F.near.y) -
368
- Math.hypot(bx - F.near.x, by - F.near.y)
369
- )
370
- })
371
- } else {
372
- candidates.sort((a, b) => {
373
- const ay = (a.info.absolutePosition && a.info.absolutePosition.y) || 0
374
- const by = (b.info.absolutePosition && b.info.absolutePosition.y) || 0
375
- if (Math.abs(ay - by) > 2) return ay - by
376
- const ax = (a.info.absolutePosition && a.info.absolutePosition.x) || 0
377
- const bx = (b.info.absolutePosition && b.info.absolutePosition.x) || 0
378
- return ax - bx
379
- })
380
- }
381
-
382
- const total = candidates.length
383
- if (total === 0) return { matched: 0, total: 0 }
384
-
385
- let idx = 0
386
- if (F.nth !== null) {
387
- idx = F.nth < 0 ? total + F.nth : F.nth
388
- if (idx < 0 || idx >= total) {
389
- return { matched: 0, total, nthOutOfRange: true, nth: F.nth }
390
- }
391
- } else if (total > 1 && !F.first && !F.near) {
392
- return {
393
- ambiguous: true,
394
- total,
395
- candidates: candidates.slice(0, 10).map((c, i) => ({
396
- idx: i,
397
- nodeId: c.info.nodeId,
398
- type: c.info.type,
399
- testID: c.info.testID,
400
- text: (c.info.text || '').slice(0, 60),
401
- abs: c.info.absolutePosition,
402
- layout: c.info.layout
403
- ? {
404
- width: Math.round(c.info.layout.width || 0),
405
- height: Math.round(c.info.layout.height || 0),
406
- }
407
- : null,
408
- ancestorTestIDs: (c.ancestorTestIDs || []).slice(0, 5),
409
- })),
410
- }
411
- }
412
-
413
- const picked = candidates[idx]
414
- const n = picked.info
415
- if (!n.absolutePosition || !n.layout) return { matched: 0, total }
416
-
417
- const resolved =
418
- typeof n.nodeId === 'number' &&
419
- typeof t.resolveTapTarget === 'function'
420
- ? await t.resolveTapTarget(n.nodeId)
421
- : null
422
- const target = (resolved && resolved.target) || n
423
- const cx =
424
- resolved && typeof resolved.cx === 'number'
425
- ? resolved.cx
426
- : n.absolutePosition.x + (n.layout.width || 0) / 2
427
- const cy =
428
- resolved && typeof resolved.cy === 'number'
429
- ? resolved.cy
430
- : n.absolutePosition.y + (n.layout.height || 0) / 2
431
- return {
432
- cx,
433
- cy,
434
- match: {
435
- nodeId: n.nodeId ?? null,
436
- id: n.id,
437
- testID: n.testID,
438
- type: n.type,
439
- },
440
- target: {
441
- nodeId: target.nodeId ?? null,
442
- id: target.id,
443
- testID: target.testID,
444
- type: target.type,
445
- },
446
- strategy: (resolved && resolved.strategy) || 'matched-node',
447
- total,
448
- idx,
449
- }
450
- })()`});if(g?.error==="bridge-not-ready"&&(console.error(" sootsim test bridge not ready"),process.exit(1)),g?.ambiguous){let _=g.candidates;console.error(` ambiguous: ${g.total} matches for "${e}"`);for(let P of _){let re=P.abs?`@(${Math.round(P.abs.x)},${Math.round(P.abs.y)})`:"",it=P.layout?` ${P.layout.width}x${P.layout.height}`:"",lt=P.testID?` #${P.testID}`:"",ct=P.text?` "${P.text}"`:"",dt=P.ancestorTestIDs.length>0?` within ${P.ancestorTestIDs.slice(0,3).map(ut=>`#${ut}`).join(" > ")}`:"";console.error(` [${P.idx}] <${P.type}>${ct}${lt} ${re}${it}${dt}`)}g.total>_.length&&console.error(` ... and ${g.total-_.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)}g?.nthOutOfRange&&(console.error(` not found: nth ${g.nth} of ${g.total} match${g.total===1?"":"es"} for "${e}"`),process.exit(1)),(!g||typeof g.cx!="number")&&(console.error(` not found: ${e}`),process.exit(1));let T=await l.send({type:"tap",x:g.cx,y:g.cy});if(T?.hit!==!1&&T?.ok!==!1){let _=st(e,{id:g.target?.id??null,testID:g.target?.testID??null,type:g.target?.type??null,cx:g.cx,cy:g.cy},"text");await L("inspect tap-text",_.step,_.summary)}console.log(JSON.stringify({matched:g.match,tapped:{nodeId:g.target?.nodeId??null,id:g.target?.id??null,testID:g.target?.testID??null,type:g.target?.type??null,cx:g.cx,cy:g.cy},...g.strategy&&g.strategy!=="matched-node"?{strategy:g.strategy}:{},...g.total>1||n!==null?{nth:{index:g.idx,total:g.total}}:{},result:T},null,2));break}case"tap-id":{let e=a[1];e||(console.error(S("tap-id","<id>")),process.exit(1));let t=JSON.stringify(e),s=await l.send({type:"evaluate",code:`(async () => {
451
- const t = window.__sootsimTest
452
- if (!t) return null
453
- const n = (await t.findByTestId(${t})) || (await t.findById(${t}))
454
- if (!n || !n.absolutePosition || !n.layout) return { cx: null }
455
- const resolved =
456
- typeof n.nodeId === 'number' && typeof t.resolveTapTarget === 'function'
457
- ? await t.resolveTapTarget(n.nodeId)
458
- : null
459
- const target = (resolved && resolved.target) || n
460
- const cx =
461
- resolved && typeof resolved.cx === 'number'
462
- ? resolved.cx
463
- : n.absolutePosition.x + (n.layout.width || 0) / 2
464
- const cy =
465
- resolved && typeof resolved.cy === 'number'
466
- ? resolved.cy
467
- : n.absolutePosition.y + (n.layout.height || 0) / 2
468
- return {
469
- cx,
470
- cy,
471
- match: {
472
- nodeId: n.nodeId ?? null,
473
- id: n.id,
474
- testID: n.testID,
475
- type: n.type,
476
- },
477
- target: {
478
- nodeId: target.nodeId ?? null,
479
- id: target.id,
480
- testID: target.testID,
481
- type: target.type,
482
- },
483
- strategy: (resolved && resolved.strategy) || 'matched-node',
484
- }
485
- })()`});(!s||typeof s.cx!="number")&&(console.error(` not found: ${e}`),process.exit(1));let r=await l.send({type:"tap",x:s.cx,y:s.cy});if(r?.hit!==!1&&r?.ok!==!1){let n=st(e,{id:s.target?.id??null,testID:s.target?.testID??null,type:s.target?.type??null,cx:s.cx,cy:s.cy},"id");await L("inspect tap-id",n.step,n.summary)}console.log(JSON.stringify({matched:s.match,tapped:{nodeId:s.target?.nodeId??null,id:s.target?.id??null,testID:s.target?.testID??null,type:s.target?.type??null,cx:s.cx,cy:s.cy},...s.strategy&&s.strategy!=="matched-node"?{strategy:s.strategy}:{},result:r},null,2));break}case"type-into":{let e=a[1],t=a.slice(2).join(" ");(!e||!t)&&(console.error(S("type-into","<id> <text>")),process.exit(1));let s=JSON.stringify(e),r=await l.send({type:"evaluate",code:`(async () => {
486
- const t = window.__sootsimTest
487
- if (!t) return null
488
- const n = await (t.findByTestId(${s}) || t.findById(${s}))
489
- if (!n || !n.absolutePosition || !n.layout) return null
490
- return {
491
- cx: n.absolutePosition.x + (n.layout.width || 0) / 2,
492
- cy: n.absolutePosition.y + (n.layout.height || 0) / 2,
493
- testID: n.testID,
494
- isTextInput: !!n.isTextInput,
495
- placeholder: n.placeholder || null,
496
- }
497
- })()`});(!r||typeof r.cx!="number")&&(console.error(` not found: ${e}`),process.exit(1)),r.isTextInput||console.error(` warning: ${e} is not a text input (isTextInput: false)`);let n=await l.send({type:"tap",x:r.cx,y:r.cy}),m=await Et(l);m.visible||(console.error(` keyboard did not open after tapping ${e}`),process.exit(1));let p=m.focusedInput;p&&(p.testID===e||p.id===e||(console.error(` focus routing mismatch after tap: requested ${JSON.stringify(e)} but focus is on ${JSON.stringify(p.testID??p.id??null)}. did the tap land on an outer Pressable wrapper?`),process.exit(1))),await l.send({type:"keyboard",action:"type",text:t}),await L("inspect type-into",{tapOn:{id:e},inputText:t},`type-into #${e} ${JSON.stringify(t)}`),console.log(JSON.stringify({target:e,isTextInput:r.isTextInput,keyboardOpened:m.visible??n?.keyboardOpened??!1,focusedInput:m.focusedInput??null,typed:t},null,2));break}case"type":{let e=a.slice(1).join(" ");e||(console.error(S("type","<text>")),process.exit(1)),await ue(l,"type"),await l.send({type:"keyboard",action:"type",text:e}),await L("inspect type",{inputText:e},`type ${JSON.stringify(e)}`),console.log(` typed: ${JSON.stringify(e)}`);break}case"key":{let e=a[1];e||(console.error(S("key","<name>")),process.exit(1)),await ue(l,"key"),await l.send({type:"keyboard",action:"press",text:e}),await L("inspect key",{pressKey:e},`key ${e}`),console.log(` pressed: ${e}`);break}case"key-sequence":{let e=a.slice(1);e.length===0&&(console.error(S("key-sequence","<key> [<key> ...]")),process.exit(1)),await ue(l,"key-sequence");for(let t of e)await l.send({type:"keyboard",action:"press",text:t});await L("inspect key-sequence",{pressKey:e.join(" ")},`key-sequence ${e.join(" ")}`),console.log(` pressed: ${e.join(", ")}`);break}case"keycode":{let e=a.slice(1);e.length===0&&(console.error(S("keycode","<code> [<code> ...]")),process.exit(1));let t=e.map(r=>({code:r,key:Rt(r)})),s=t.filter(r=>!r.key);s.length>0&&(console.error(` unsupported keycode(s): ${s.map(r=>r.code).join(", ")}`),process.exit(1)),await ue(l,"keycode");for(let r of t)await l.send({type:"keyboard",action:"press",text:r.key});await L("inspect keycode",{pressKey:t.map(r=>r.key).join(" ")},`keycode ${e.join(" ")}`),console.log(` pressed: ${e.join(", ")}`);break}case"dispatch":{let e=a[1];e||(console.error(S("dispatch","<char>")),process.exit(1)),await l.send({type:"keyboard",action:"dispatchKey",text:e}),await L("inspect dispatch",{dispatchKey:e},`dispatch ${JSON.stringify(e)}`),console.log(` dispatched: ${e}`);break}case"dismiss":{await l.send({type:"keyboard",action:"dismiss"}),await L("inspect dismiss",{hideKeyboard:!0},"dismiss keyboard"),console.log(" keyboard dismissed");break}case"double-tap":{let e=Number(a[1]),t=Number(a[2]),s=se(o);if(s){let p=await ce(l,s);p||(console.error(` not found: ${s.value}`),s.mode==="testid"&&U("wait-selector-for-missing-testid",s.value),process.exit(1)),e=p.x,t=p.y}let r=a[3]?Number(a[3]):80;(!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(r))&&(console.error(S("double-tap","<x> <y> [gapMs] | --testid <id>")),process.exit(1));let n=Math.max(0,Math.round(r)),m=await l.send({type:"evaluate",code:`(async () => {
498
- const interact = window.__sootsimInteract
499
- if (interact?.doubleTap) {
500
- return {
501
- ok: !!(await interact.doubleTap(${e}, ${t}, ${n})),
502
- gapMs: ${n},
503
- }
504
- }
505
- if (!interact?.tap) {
506
- return { ok: false, reason: 'no interact.tap', gapMs: ${n} }
507
- }
508
- const first = await interact.tap(${e}, ${t})
509
- if (!first || first.hit === false) {
510
- return { ok: false, reason: 'first tap missed', gapMs: ${n}, first }
511
- }
512
- await new Promise((resolve) => setTimeout(resolve, ${n}))
513
- const second = await interact.tap(${e}, ${t})
514
- return {
515
- ok: !!second && second.hit !== false,
516
- gapMs: ${n},
517
- first,
518
- second,
519
- }
520
- })()`});m?.ok&&await L("inspect double-tap",{doubleTapAtCoords:{x:e,y:t,gapMs:n}},`double-tap @${e},${t}`),console.log(JSON.stringify(m,null,2));break}case"long-press":{let e=Number(a[1]),t=Number(a[2]),s=se(o);if(s){let m=await ce(l,s);m||(console.error(` not found: ${s.value}`),s.mode==="testid"&&U("wait-selector-for-missing-testid",s.value),process.exit(1)),e=m.x,t=m.y}let r=a[3]?Number(a[3]):600;(!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(r))&&(console.error(S("long-press","<x> <y> [durationMs] | --testid <id>")),process.exit(1));let n=await l.send({type:"evaluate",code:`(async () => {
521
- const interact = window.__sootsimInteract
522
- if (!interact?.longPress) return { ok: false, reason: 'no interact.longPress' }
523
- const value = await interact.longPress(${e}, ${t}, ${Math.max(0,Math.round(r))})
524
- return { ok: !!value, value }
525
- })()`});n?.ok&&await L("inspect long-press",{tapAtCoords:{x:e,y:t}},`long-press @${e},${t}`),console.log(JSON.stringify(n,null,2));break}case"touch":{let e=a[1],t=Number(a[2]),s=Number(a[3]),r=a[4]?Number(a[4]):999,n=e==="down"?"touchDown":e==="move"?"touchMove":e==="up"?"touchUp":e==="cancel"?"touchCancel":null;n||(console.error(S("touch","<down|move|up|cancel> <x> <y> [pointerId]")),process.exit(1)),e!=="cancel"&&(!Number.isFinite(t)||!Number.isFinite(s))&&(console.error(S("touch","<down|move|up|cancel> <x> <y> [pointerId]")),process.exit(1));let m=e==="down"?"tap":e==="move"?"move":null,p=m&&Number.isFinite(t)&&Number.isFinite(s)?`window.dispatchEvent(new CustomEvent('sootsim:agentAction', { detail: { type: '${m}', x: ${t}, y: ${s} } }));`:"",h=await l.send({type:"evaluate",code:`(async () => {
526
- ${p}
527
- const interact = window.__sootsimInteract
528
- if (!interact?.${n}) return { ok: false, reason: 'no interact.${n}' }
529
- const value = ${e==="cancel"?`await interact.${n}(${Math.max(1,Math.round(r))})`:`await interact.${n}(${t}, ${s}, ${Math.max(1,Math.round(r))})`}
530
- return { ok: !!value, value }
531
- })()`});h?.ok&&e!=="cancel"&&await L("inspect touch",{tapAtCoords:{x:t,y:s}},`touch ${e} @${t},${s}`),console.log(JSON.stringify(h,null,2));break}case"gesture":{let e=a[1],t=a[2]?Number(a[2]):220;(!e||!Number.isFinite(t))&&(console.error(S("gesture","<preset> [durationMs]")),process.exit(1));let s=await l.send({type:"evaluate",code:`(async () => {
532
- const spec = globalThis.__sootsimDeviceSpec || {}
533
- return {
534
- width: spec.width || window.innerWidth || 393,
535
- height: spec.height || window.innerHeight || 852,
536
- statusBarHeight: spec.statusBarHeight || 0,
537
- homeIndicatorHeight: spec.homeIndicatorHeight || 0,
538
- }
539
- })()`}),r=Number(s?.width)||393,n=Number(s?.height)||852,m=Number(s?.statusBarHeight)||0,p=Number(s?.homeIndicatorHeight)||0,h=Math.round(r/2),f=Math.round(n/2),w=Math.max(24,m+18),O=Math.max(24,p+18),B=18,N=Math.min(220,Math.round(n*.24)),M=Math.min(180,Math.round(r*.32)),F=h,W=f,g=h,T=f;switch(e){case"scroll-up":W=f+Math.round(N/2),T=f-Math.round(N/2);break;case"scroll-down":W=f-Math.round(N/2),T=f+Math.round(N/2);break;case"scroll-left":F=h+Math.round(M/2),g=h-Math.round(M/2);break;case"scroll-right":F=h-Math.round(M/2),g=h+Math.round(M/2);break;case"swipe-from-left-edge":F=B,W=f,g=Math.min(r-B,B+M);break;case"swipe-from-right-edge":F=r-B,W=f,g=Math.max(B,r-B-M);break;case"swipe-from-top-edge":F=h,W=w,T=Math.min(n-O,w+N);break;case"swipe-from-bottom-edge":F=h,W=n-O,T=Math.max(w,n-O-N);break;default:console.error(` unknown gesture preset: ${e}`),process.exit(1)}let _=Math.max(8,Math.round(t/16)),P=Math.max(1,Math.round(t/_)),re=await l.send({type:"evaluate",code:`(async () => {
540
- const interact = window.__sootsimInteract
541
- if (!interact?.drag) return { ok: false, reason: 'no interact.drag' }
542
- const value = await interact.drag(${F}, ${W}, ${g}, ${T}, ${_}, ${P})
543
- return { ok: !!value, value }
544
- })()`});re?.ok&&await L("inspect gesture",{swipe:{start:`${F}, ${W}`,end:`${g}, ${T}`,duration:Math.max(1,Math.round(t))}},`gesture ${e}`),console.log(JSON.stringify({preset:e,from:{x:F,y:W},to:{x:g,y:T},result:re},null,2));break}case"scroll":{let e=se(o),t=e?.mode==="testid"?e.value:a[1],s=Number(a[e?1:2]),r=Number(a[e?2:3]);(!t||!Number.isFinite(s)||!Number.isFinite(r))&&(console.error(S("scroll","<id> <dx> <dy> | --testid <id> <dx> <dy>")),process.exit(1));let n=await l.send({type:"evaluate",code:`(async () => {
545
- const t = window.__sootsimTest
546
- if (!t) return null
547
- const n = await t.findByTestId(${JSON.stringify(t)})
548
- || await t.findById(${JSON.stringify(t)})
549
- if (!n || !n.absolutePosition || !n.layout) return null
550
- return {
551
- cx: n.absolutePosition.x + (n.layout.width || 0) / 2,
552
- cy: n.absolutePosition.y + (n.layout.height || 0) / 2,
553
- }
554
- })()`}),m=await z(l,"scrollTo",t,s,r,!1);m?.ok&&await L("inspect scroll",{scrollTo:{id:t,x:s,y:r}},`scroll ${t} -> ${s},${r}`),console.log(JSON.stringify({...m,...n?{at:{x:n.cx,y:n.cy}}:{}},null,2));break}case"state":{let e=a[1];if(i==="get"&&!e){let s=await z(l,"getSessionState"),r=await l.send({type:"evaluate",code:`({
555
- errors: window.__sootsimConsole?.getErrors?.()?.length ?? 0,
556
- warnings: window.__sootsimConsole?.getWarnings?.()?.length ?? 0,
557
- })`});s&&typeof s=="object"&&s.diagnostics&&(s.diagnostics.errors=r?.errors??0,s.diagnostics.warnings=r?.warnings??0),console.log(JSON.stringify(s,null,2));break}if(!e||e==="--help"||e==="-h"){console.log(`
558
- ${y("state")} \u2014 dump raw runtime state
559
-
560
- subcommands:
561
- shell dump shell transition/layout state
562
- worker dump render-worker host/animation state
563
- keyboard dump keyboard visibility, mode, and focused input
564
- ownership dump surface ownership + pointerOnSurface delivery stats
565
- node <id> dump raw node info by id or testID
566
- scroll <id> dump scroll metrics and runtime state
567
- scroll-hit <x> <y> dump the nearest scroll ancestor at coordinates
568
- hit <x> <y> dump the hit-test ancestry at coordinates
569
- gesture <x> <y> dump gesture routing/debug info at coordinates
570
-
571
- examples:
572
- ${y("state")} shell
573
- ${y("state")} worker
574
- ${y("state")} keyboard
575
- ${y("state")} ownership
576
- ${y("state")} node photos
577
- ${y("state")} scroll feed
578
- ${y("state")} scroll-hit 360 420
579
- ${y("state")} hit 200 720
580
- `);break}let t;switch(e){case"shell":t=await V(l,500);break;case"worker":t=await ve(l,"__sootsimRenderHost.queryStats");break;case"ownership":t=await l.send({type:"evaluate",code:`(() => {
581
- const h = window.__sootsimRenderHost
582
- if (!h || typeof h.getOwnershipSnapshot !== 'function') {
583
- return { error: 'getOwnershipSnapshot not available' }
584
- }
585
- return h.getOwnershipSnapshot()
586
- })()`});break;case"keyboard":t=await l.send({type:"evaluate",code:`(async () => {
587
- const kb = window.__sootsimKeyboard
588
- const test = window.__sootsimTest
589
- if (!kb) return { error: 'keyboard bridge not available' }
590
- const layout = typeof kb.getLayout === 'function' ? kb.getLayout() : null
591
- const visible = kb.isVisible()
592
- const mode = kb.getMode()
593
- let focused = null
594
- if (test && typeof test.getFocusedNode === 'function') {
595
- try {
596
- focused = await test.getFocusedNode()
597
- } catch {}
598
- }
599
- return {
600
- visible,
601
- mode,
602
- layout,
603
- focusedInput: focused ? {
604
- nodeId: focused.nodeId ?? null,
605
- testID: focused.testID || null,
606
- id: focused.id || null,
607
- placeholder: focused.placeholder || null,
608
- text: focused.text || null,
609
- } : null,
610
- }
611
- })()`});break;case"node":{let s=a[2];s||(console.error(` usage: ${y("state")} node <id>`),process.exit(1)),t=await z(l,"findByTestId",s)||await z(l,"findById",s);break}case"scroll":{let s=a[2];s||(console.error(` usage: ${y("state")} scroll <id>`),process.exit(1)),t=await z(l,"getScrollState",s);break}case"scroll-hit":{let s=Number(a[2]),r=Number(a[3]);(!Number.isFinite(s)||!Number.isFinite(r))&&(console.error(` usage: ${y("state")} scroll-hit <x> <y>`),process.exit(1)),t=await z(l,"getScrollStateAt",s,r);break}case"hit":{let s=Number(a[2]),r=Number(a[3]);(!Number.isFinite(s)||!Number.isFinite(r))&&(console.error(` usage: ${y("state")} hit <x> <y>`),process.exit(1)),t=await z(l,"debugHitAt",s,r);break}case"gesture":{let s=Number(a[2]),r=Number(a[3]);(!Number.isFinite(s)||!Number.isFinite(r))&&(console.error(` usage: ${y("state")} gesture <x> <y>`),process.exit(1)),t=await z(l,"debugGestureAt",s,r);break}default:console.error(` unknown state subcommand: ${e}`),process.exit(1)}console.log(JSON.stringify(t,null,2));break}case"shell":{let e=a[1];if(!e||e==="--help"||e==="-h"){console.log(`
612
- ${y("shell")} \u2014 run built-in shell commands
613
-
614
- subcommands:
615
- launch <appId> [waitMs] [--clear-state]
616
- launch app and wait for settled shell state
617
- home [waitMs] go home and wait for settled shell state
618
- switcher [waitMs] open switcher and wait for settled shell state
619
- open-card <appId> [waitMs]
620
- open a specific switcher card and wait for app settle
621
- appearance <light|dark|auto|toggle>
622
- update simulator appearance
623
- lock toggle device lock state
624
- shake trigger the simulator shake gesture
625
-
626
- examples:
627
- ${y("shell")} launch photos
628
- ${y("shell")} launch rn --clear-state
629
- ${y("shell")} launch photos 1500
630
- ${y("shell")} home 500
631
- ${y("shell")} switcher 800
632
- ${y("shell")} open-card clock 800
633
- ${y("shell")} appearance dark
634
- ${y("shell")} lock
635
- `);break}let t=e==="launch"||e==="open-card"||e==="home"||e==="switcher",s=e==="launch"||e==="open-card"?a[3]:a[2],r=s?Number(s):350;t&&(!Number.isFinite(r)||r<0)&&(console.error(S("shell",e==="launch"||e==="open-card"?"<launch|open-card> <appId> [settleMs]":"<home|switcher> [settleMs]")),process.exit(1));let n=!1,m=!1,p=null,h=o.includes("--clear-state");if(e==="launch"){let f=a[2];f||(console.error(S("shell","launch <appId> [settleMs] [--clear-state]")),process.exit(1)),h&&await l.send({type:"evaluate",code:Te}),n=!!await te(l,"launchApp",r,f),{settled:m,state:p}=await de(l,Math.round(r),w=>!!w&&w.state==="app"&&w.activeApp===f&&w.showSwitcher===!1&&w.switcherPhase==="idle"&&typeof w.launchProgress=="number"&&w.launchProgress>=.98),n&&await L("inspect shell launch",h?{launchApp:{clearState:!0}}:{launchApp:{}},h?"launch app (clear state)":"launch app")}else if(e==="home")n=!!await te(l,"goHome",r),{settled:m,state:p}=await de(l,Math.round(r),f=>!!f&&f.state==="home"&&f.activeApp==null&&f.showSwitcher===!1&&f.switcherPhase==="idle"&&typeof f.launchProgress=="number"&&f.launchProgress>=.98);else if(e==="switcher")n=!!await te(l,"openSwitcher",r),{settled:m,state:p}=await de(l,Math.round(r),f=>!!f&&f.state==="app"&&f.showSwitcher===!0&&f.switcherPhase==="idle"&&typeof f.zoomLevel=="number"&&Math.abs(f.zoomLevel)<=.02&&typeof f.horizontalZoom=="number"&&Math.abs(f.horizontalZoom)<=.02),m&&(await Y(Ot),p=await V(l));else if(e==="open-card"){let f=a[2];f||(console.error(S("shell","open-card <appId> [settleMs]")),process.exit(1)),n=!!await te(l,"openSwitcherCard",r,f),{settled:m,state:p}=await de(l,Math.round(r),w=>!!w&&w.state==="app"&&w.activeApp===f&&w.showSwitcher===!1&&w.switcherPhase==="idle"&&typeof w.zoomLevel=="number"&&w.zoomLevel>=.98&&typeof w.horizontalZoom=="number"&&w.horizontalZoom>=.98),n&&await L("inspect shell open-card",{openSwitcherCard:{appId:f}},`open switcher card ${f}`)}else if(e==="appearance"){let f=a[2];(!f||!["light","dark","auto","toggle"].includes(f))&&(console.error(S("shell","appearance <light|dark|auto|toggle>")),process.exit(1));let w=await ot(l,"appearance",f);n=!!w?.ok,p={appearance:w}}else if(e==="lock"||e==="shake"){let f=await ot(l,e);n=!!f?.ok,p={[e]:f}}else console.error(` unknown shell subcommand: ${e}`),process.exit(1);console.log(JSON.stringify({ok:n,settled:m,state:p},null,2));break}case"url":{await Ue(l,{args:d});break}case"reload":{let s=!1,r=!1;try{await l.send({type:"evaluate",code:"window.__sootsimConsole?.clear()"});let p=await l.send({type:"evaluate",code:`;(() => {
636
- const reloadExternalApp = window.SootSim?.bridges?.hotRemount?.reloadExternalApp
637
- if (typeof reloadExternalApp === 'function') {
638
- reloadExternalApp()
639
- return { kind: 'external-app' }
640
- }
641
- window.location.reload()
642
- return { kind: 'page' }
643
- })()`});r=!!p&&p.kind==="external-app",s=!0}catch{}console.log(" reloading...");let n=l,m=null;if(r)m=await fe(l,{timeoutMs:1e4,errorGraceMs:3e3});else{s&&await Y(300);let p=await Fe(A,j,v,{timeoutMs:1e4});p?(n=p,m=await fe(p,{timeoutMs:1e4,errorGraceMs:3e3})):(console.log(" \u26A0 reload: bridge never reconnected within 10000ms"),n=null)}if(m)if(m.ready){let p=m.source==="nodes-fallback"?" (no ready signal, node-count fallback)":"";console.log(` ready in ${m.elapsedMs}ms: ${m.nodes} nodes${p}`)}else m.source==="error-bail"?console.log(` \u26A0 reload bailed after ${m.elapsedMs}ms: ${m.errors} console error(s), ready signal never fired`):console.log(` \u26A0 reload timed out after ${m.elapsedMs}ms (${m.nodes} nodes, ${m.errors} errors)`);if(n)try{let p=await n.send({type:"evaluate",code:"window.__sootsimConsole?.getErrors(10) || []"});if(n!==l&&n.close(),Array.isArray(p)&&p.length>0){console.log(`
644
- \u26A0 ${p.length} error(s) during mount:
645
- `);for(let h of p){let f=h.args.map(w=>typeof w=="object"?JSON.stringify(w):w).join(" ");if(console.log(` ${f}`),h.stack){let w=h.stack.split(`
646
- `).slice(0,2);for(let O of w)console.log(` ${O.trim()}`)}}}}catch{}m&&!m.ready&&(process.exitCode=1);break}case"eval":case"js":{let e=a.slice(1).join(" ");e||(console.error(S("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(` ${y("js")} SootSim.bridges.test.findByText("Sign in")`),console.error(` ${y("js")} SootSim.bridges.debug.snapshot("before")`),console.error(` ${y("js")} SootSim.bridges.keyboard.type("hello")`),console.error(` ${y("js")} SootSim.state.root.children.length`),process.exit(1));let t=e;t.startsWith("(async")||(t=`(async () => ${t})()`);let s=await l.send({type:"evaluate",code:t});console.log(JSON.stringify(s,null,2));let r=e.toLowerCase(),n=[];(r.includes("sootsim:gohome")||r.includes("gohome"))&&n.push("sootsim shell home"),(r.includes("sootsim:appswitcher")||r.includes("appswitcher"))&&n.push("sootsim shell switcher"),(r.includes("keyboard.isvisible")||r.includes("keyboard.getmode"))&&n.push("sootsim debug state keyboard"),r.includes("interact.tap")&&n.push("sootsim do tap <x> <y>"),r.includes("keyboard.type")&&n.push("sootsim do type <text>"),(r.includes("keyboard.press")||r.includes("keyboard.dispatchkey"))&&n.push("sootsim do key <name>"),r.includes("keyboard.dismiss")&&n.push("sootsim do dismiss"),r.includes("dumptree")&&n.push("sootsim get tree"),r.includes("dumpaccessibilitytree")&&n.push("sootsim get a11y"),r.includes("getnodecount")&&n.push("sootsim get count"),r.includes("findbytext")&&n.push("sootsim find <text>"),(r.includes("findbytestid")||r.includes("findbyid"))&&n.push("sootsim find --testid <id>"),r.includes("document.hidden")&&n.push("sootsim debug state keyboard (includes tab health)"),n.length>0&&U("prefer-cli-over-eval",n);break}case"globals":{let e=await l.send({type:"evaluate",code:`(async () => {
647
- const globals = {}
648
-
649
- // test bridge (proxy in worker mode)
650
- const testMethods = [
651
- 'findById', 'findByTestId', 'findByText', 'findByLabel', 'findByRole',
652
- 'findAllByRole', 'findByA11yState', 'findAllByA11yState', 'findByHint',
653
- 'findPressable', 'getStyle', 'getLayout', 'getAbsolutePosition', 'isVisible',
654
- 'queryAll', 'dumpTree', 'dumpAccessibilityTree', 'getNodeCount', 'getShellState',
655
- 'getScrollState', 'getScrollStateAt', 'scrollTo', 'waitForTree',
656
- 'waitForScreenTransitions', 'debugByText', 'debugByTestId', 'debugHitAt',
657
- 'debugGestureAt'
658
- ]
659
- globals['test (\u2192 __sootsimTest)'] = testMethods
660
-
661
- // debug
662
- if (window.__sootsimDebug) {
663
- globals['debug (\u2192 __sootsimDebug)'] = Object.keys(window.__sootsimDebug)
664
- }
665
-
666
- // interact
667
- if (window.__sootsimInteract) {
668
- globals['interact (\u2192 __sootsimInteract)'] = Object.keys(window.__sootsimInteract)
669
- }
670
-
671
- // keyboard
672
- if (window.__sootsimKeyboard) {
673
- globals['keyboard (\u2192 __sootsimKeyboard)'] = Object.keys(window.__sootsimKeyboard)
674
- }
675
-
676
- // other globals
677
- globals['other'] = [
678
- 'root (\u2192 __sootsimRoot) - live node tree',
679
- 'render() (\u2192 __sootsimForceRender) - force re-render'
680
- ]
681
-
682
- return globals
683
- })()`});console.log(` sootsim JS API:
684
- `);for(let[t,s]of Object.entries(e)){console.log(` ${t}:`);for(let r of s)console.log(` .${r}`);console.log("")}console.log(` use: ${y("js")} <expression>`),console.log(` example: ${y("js")} test.findByText("Sign in")`);break}case"describe":{await Ce({bridge:l,args:o,positional:a});break}case"perf":{let e=a[1];if(!e||e==="--help"||e==="-h"){console.log(`
685
- ${y("perf")} \u2014 performance profiling
686
-
687
- subcommands:
688
- stats one-shot stats (zero overhead query)
689
- start begin recording frame times
690
- stop stop recording and report results
691
- frames [n] get last N frame times (default: 50)
692
- transition <e> profile a shell transition (goHome, appSwitcher, lockScreen)
693
-
694
- examples:
695
- ${y("perf")} stats
696
- ${y("perf")} start
697
- # ... interact with the app ...
698
- ${y("perf")} stop
699
- ${y("perf")} transition goHome
700
- `);break}switch(e){case"stats":{let t=await l.send({type:"evaluate",code:`(async () => {
701
- // worker mode (host exposes these)
702
- if (window.__sootsimPerfStats) {
703
- return await window.__sootsimPerfStats()
704
- }
705
- // main-thread mode
706
- const perf = window.__sootsimPerf
707
- const a11y = window.__sootsimA11y
708
- if (!perf && !a11y) return { error: 'no perf globals available' }
709
-
710
- const frameStats = perf?.getFrameStats?.() || {}
711
- const profile = a11y?.profile?.() || {}
712
- const nodeCount = await window.__sootsimTest?.getNodeCount?.() || 0
713
-
714
- return {
715
- frames: frameStats.frames || profile.syncCount || 0,
716
- avgMs: frameStats.totalMs && frameStats.frames
717
- ? (frameStats.totalMs / frameStats.frames).toFixed(2)
718
- : profile.avgSyncMs?.toFixed(2) || '?',
719
- maxMs: frameStats.maxMs?.toFixed(2) || profile.maxSyncMs?.toFixed(2) || '?',
720
- layoutMs: frameStats.layoutTotalMs?.toFixed(2) || '?',
721
- nodeCount,
722
- jankFrames: frameStats.recentFrames?.filter(f => f > 16.67).length || 0,
723
- recentCount: frameStats.recentFrames?.length || 0,
724
- }
725
- })()`});t.error&&(console.error(` error: ${t.error}`),process.exit(1));let s=t.avgMs!=="?"?(1e3/parseFloat(t.avgMs)).toFixed(1):"?";console.log(" perf stats:"),console.log(` frames: ${t.frames}`),console.log(` avg: ${t.avgMs}ms (${s} fps)`),console.log(` max: ${t.maxMs}ms`),console.log(` layout: ${t.layoutMs}ms total`),console.log(` nodes: ${t.nodeCount}`),t.recentCount>0&&console.log(` jank: ${t.jankFrames}/${t.recentCount} frames >16.67ms`);break}case"start":{await l.send({type:"evaluate",code:`(async () => {
726
- // worker mode
727
- if (window.__sootsimPerfStart && window.__sootsimRenderHost) {
728
- const result = window.__sootsimPerfStart()
729
- window.${G} = {
730
- active: true,
731
- mode: 'render-worker',
732
- lastSamples: [],
733
- startedAt: performance.now(),
734
- }
735
- return result
736
- }
737
- // main-thread mode
738
- window.__sootsimPerf?.enableFrameStats?.(true)
739
- window.__sootsimA11y?.resetProfile?.()
740
- window.${G} = {
741
- active: true,
742
- mode: 'main-thread',
743
- lastSamples: [],
744
- startedAt: performance.now(),
745
- }
746
- return { started: true }
747
- })()`}),console.log(` profiling started \u2014 interact with the app, then run '${y("perf")} stop'`);break}case"stop":{let t=await l.send({type:"evaluate",code:`(async () => {
748
- // worker mode
749
- if (window.__sootsimRenderHost) {
750
- const session = window.${G} || {}
751
- const priorSamples = session.active && Array.isArray(session.lastSamples)
752
- ? session.lastSamples
753
- : []
754
- const flushedSamples = await window.__sootsimRenderHost.flushSamples()
755
- const samples = priorSamples.concat(flushedSamples)
756
- window.${G} = {
757
- ...session,
758
- active: false,
759
- mode: 'render-worker',
760
- lastSamples: samples,
761
- stoppedAt: performance.now(),
762
- }
763
-
764
- const frameTimes = samples.map(sample => sample[1])
765
- const layoutTimes = samples.map(sample => sample[2])
766
- const renderTimes = samples.map(sample => sample[3])
767
- const copyTimes = samples.map(sample => sample[4])
768
- const auxTimes = samples.map(sample => sample[5] || 0)
769
- const otherTimes = samples.map(sample => sample[6] || 0)
770
- const sorted = [...frameTimes].sort((a, b) => a - b)
771
- const total = frameTimes.reduce((a, b) => a + b, 0)
772
- const avg = frameTimes.length > 0 ? total / frameTimes.length : 0
773
- const max = Math.max(...frameTimes, 0)
774
- const layoutTotal = layoutTimes.reduce((a, b) => a + b, 0)
775
- const renderTotal = renderTimes.reduce((a, b) => a + b, 0)
776
- const copyTotal = copyTimes.reduce((a, b) => a + b, 0)
777
- const auxTotal = auxTimes.reduce((a, b) => a + b, 0)
778
- const otherTotal = otherTimes.reduce((a, b) => a + b, 0)
779
-
780
- return {
781
- mode: 'render-worker',
782
- frames: frameTimes.length,
783
- totalMs: total,
784
- avgMs: avg,
785
- maxMs: max,
786
- layoutTotalMs: layoutTotal,
787
- renderTotalMs: renderTotal,
788
- copyTotalMs: copyTotal,
789
- auxTotalMs: auxTotal,
790
- otherTotalMs: otherTotal,
791
- layoutAvgMs: frameTimes.length > 0 ? layoutTotal / frameTimes.length : 0,
792
- renderAvgMs: frameTimes.length > 0 ? renderTotal / frameTimes.length : 0,
793
- copyAvgMs: frameTimes.length > 0 ? copyTotal / frameTimes.length : 0,
794
- auxAvgMs: frameTimes.length > 0 ? auxTotal / frameTimes.length : 0,
795
- otherAvgMs: frameTimes.length > 0 ? otherTotal / frameTimes.length : 0,
796
- p50: sorted[Math.floor(sorted.length * 0.5)] || 0,
797
- p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
798
- p99: sorted[Math.floor(sorted.length * 0.99)] || 0,
799
- jankFrames: frameTimes.filter((f) => f > 16.67).length,
800
- sampleCount: frameTimes.length,
801
- }
802
- }
803
- // main-thread mode
804
- const perf = window.__sootsimPerf
805
- const a11y = window.__sootsimA11y
806
- if (!perf && !a11y) return { error: 'no perf globals' }
807
-
808
- const frameStats = perf?.getFrameStats?.() || {}
809
- const profile = a11y?.profile?.() || {}
810
-
811
- // calculate distribution
812
- const recent = frameStats.recentFrames || []
813
- const sorted = [...recent].sort((a, b) => a - b)
814
- const p50 = sorted[Math.floor(sorted.length * 0.5)] || 0
815
- const p95 = sorted[Math.floor(sorted.length * 0.95)] || 0
816
- const p99 = sorted[Math.floor(sorted.length * 0.99)] || 0
817
-
818
- // disable collection
819
- perf?.disableFrameStats?.()
820
- window.${G} = {
821
- ...(window.${G} || {}),
822
- active: false,
823
- mode: 'main-thread',
824
- lastSamples: recent.map((ms, index) => [index, ms, 0, 0, 0, 0, 0]),
825
- stoppedAt: performance.now(),
826
- }
827
-
828
- return {
829
- mode: 'main-thread',
830
- frames: frameStats.frames || profile.syncCount || 0,
831
- totalMs: frameStats.totalMs || 0,
832
- avgMs: frameStats.totalMs && frameStats.frames
833
- ? frameStats.totalMs / frameStats.frames
834
- : profile.avgSyncMs || 0,
835
- maxMs: frameStats.maxMs || profile.maxSyncMs || 0,
836
- layoutTotalMs: frameStats.layoutTotalMs || 0,
837
- p50, p95, p99,
838
- jankFrames: recent.filter(f => f > 16.67).length,
839
- sampleCount: recent.length,
840
- }
841
- })()`});t.error&&(console.error(` error: ${t.error}`),process.exit(1));let s=t.avgMs>0?(1e3/t.avgMs).toFixed(1):"?",r=t.sampleCount>0?(t.jankFrames/t.sampleCount*100).toFixed(1):"0";console.log(` profiling stopped:
842
- `),console.log(` frames: ${t.frames}`),console.log(` total: ${t.totalMs.toFixed(1)}ms`),console.log(` avg: ${t.avgMs.toFixed(2)}ms (${s} fps)`),console.log(` max: ${t.maxMs.toFixed(2)}ms`),console.log(""),t.layoutAvgMs!==void 0&&(console.log(" breakdown (avg per frame):"),console.log(` layout: ${t.layoutAvgMs.toFixed(2)}ms`),console.log(` render: ${t.renderAvgMs.toFixed(2)}ms`),console.log(` copy: ${t.copyAvgMs.toFixed(2)}ms`),t.auxAvgMs!==void 0&&console.log(` aux: ${t.auxAvgMs.toFixed(2)}ms`),t.otherAvgMs!==void 0&&console.log(` other: ${t.otherAvgMs.toFixed(2)}ms`),console.log("")),console.log(` distribution (${t.sampleCount} samples):`),console.log(` p50: ${t.p50.toFixed(2)}ms`),console.log(` p95: ${t.p95.toFixed(2)}ms`),console.log(` p99: ${t.p99.toFixed(2)}ms`),console.log(` jank: ${t.jankFrames} frames (${r}%) >16.67ms`);break}case"frames":{let t=a[2]?Number(a[2]):50;(!Number.isFinite(t)||t<=0)&&(console.error(` error: expected a positive frame count, got "${a[2]}"`),process.exit(1));let s=await l.send({type:"evaluate",code:`(async () => {
843
- if (window.__sootsimRenderHost) {
844
- const session = window.${G} || {}
845
- if (session.active) {
846
- const priorSamples = Array.isArray(session.lastSamples) ? session.lastSamples : []
847
- const flushedSamples = await window.__sootsimRenderHost.flushSamples()
848
- const samples = priorSamples.concat(flushedSamples)
849
- window.__sootsimRenderHost.startSampling()
850
- window.${G} = {
851
- ...session,
852
- active: true,
853
- mode: 'render-worker',
854
- lastSamples: samples,
855
- lastFlushAt: performance.now(),
856
- }
857
- return {
858
- mode: 'render-worker',
859
- live: true,
860
- samples: samples.slice(-${t}),
861
- }
862
- }
863
- return {
864
- mode: 'render-worker',
865
- live: false,
866
- samples: (session.lastSamples || []).slice(-${t}),
867
- }
868
- }
869
- // main-thread mode
870
- const perf = window.__sootsimPerf
871
- if (!perf) return { error: 'no __sootsimPerf (try "perf start" first)' }
872
- const stats = perf.getFrameStats?.() || {}
873
- return {
874
- mode: 'main-thread',
875
- frames: (stats.recentFrames || []).slice(-${t}),
876
- }
877
- })()`});if(s.error&&(console.error(` error: ${s.error}`),process.exit(1)),s.mode==="render-worker"){let n=Array.isArray(s.samples)?s.samples:[];if(n.length===0){console.log(` no frame data \u2014 run '${y("perf")} start' first`);break}console.log(` last ${n.length} sampled frames (ms):`),console.log(" total layout render copy aux other t+");for(let[m,p,h,f,w,O,B]of n)console.log(` ${p.toFixed(2).padStart(7)} ${h.toFixed(2).padStart(7)} ${f.toFixed(2).padStart(7)} ${w.toFixed(2).padStart(7)} ${O.toFixed(2).padStart(6)} ${B.toFixed(2).padStart(7)} ${String(m).padStart(5)}`);console.log(""),be(n.map(m=>m[1])),s.live&&console.log(" sampling continues");break}let r=Array.isArray(s.frames)?s.frames:Array.isArray(s)?s:[];if(r.length===0){console.log(` no frame data \u2014 run '${y("perf")} start' first`);break}console.log(` last ${r.length} frame times (ms):`),console.log(` ${r.map(n=>n.toFixed(2)).join(", ")}`),be(r);break}case"worst":{let t=a[2]?Number(a[2]):20;(!Number.isFinite(t)||t<=0)&&(console.error(` error: expected a positive frame count, got "${a[2]}"`),process.exit(1));let s=await l.send({type:"evaluate",code:`(async () => {
878
- if (window.__sootsimRenderHost) {
879
- const session = window.${G} || {}
880
- if (session.active) {
881
- const priorSamples = Array.isArray(session.lastSamples) ? session.lastSamples : []
882
- const flushedSamples = await window.__sootsimRenderHost.flushSamples()
883
- const samples = priorSamples.concat(flushedSamples)
884
- window.__sootsimRenderHost.startSampling()
885
- window.${G} = {
886
- ...session,
887
- active: true,
888
- mode: 'render-worker',
889
- lastSamples: samples,
890
- lastFlushAt: performance.now(),
891
- }
892
- return {
893
- mode: 'render-worker',
894
- live: true,
895
- samples: samples
896
- .slice()
897
- .sort((a, b) => b[1] - a[1])
898
- .slice(0, ${t}),
899
- }
900
- }
901
- const samples = Array.isArray(session.lastSamples) ? session.lastSamples : []
902
- return {
903
- mode: 'render-worker',
904
- live: false,
905
- samples: samples
906
- .slice()
907
- .sort((a, b) => b[1] - a[1])
908
- .slice(0, ${t}),
909
- }
910
- }
911
- const perf = window.__sootsimPerf
912
- if (!perf) return { error: 'no __sootsimPerf (try "perf start" first)' }
913
- const stats = perf.getFrameStats?.() || {}
914
- const recent = Array.isArray(stats.recentFrames) ? stats.recentFrames : []
915
- return {
916
- mode: 'main-thread',
917
- frames: recent.slice().sort((a, b) => b - a).slice(0, ${t}),
918
- }
919
- })()`});if(s.error&&(console.error(` error: ${s.error}`),process.exit(1)),s.mode==="render-worker"){let n=Array.isArray(s.samples)?s.samples:[];if(n.length===0){console.log(` no frame data \u2014 run '${y("perf")} start' first`);break}console.log(` worst ${n.length} sampled frames (ms):`),console.log(" total layout render copy aux other t+");for(let[m,p,h,f,w,O,B]of n)console.log(` ${p.toFixed(2).padStart(7)} ${h.toFixed(2).padStart(7)} ${f.toFixed(2).padStart(7)} ${w.toFixed(2).padStart(7)} ${O.toFixed(2).padStart(6)} ${B.toFixed(2).padStart(7)} ${String(m).padStart(5)}`);s.live&&(console.log(""),console.log(" sampling continues"));break}let r=Array.isArray(s.frames)?s.frames:Array.isArray(s)?s:[];if(r.length===0){console.log(` no frame data \u2014 run '${y("perf")} start' first`);break}console.log(` worst ${r.length} frame times (ms):`),console.log(` ${r.map(n=>n.toFixed(2)).join(", ")}`);break}case"transition":{let t=a[2];if(!t||!["goHome","appSwitcher","lockScreen"].includes(t)){console.log(`
920
- ${y("perf")} transition <event> \u2014 profile a shell transition
921
-
922
- events:
923
- goHome swipe-to-home animation
924
- appSwitcher app switcher card animation
925
- lockScreen lock screen transition
926
-
927
- note: uses 600ms capture window \u2014 may need --timeout 10000 flag
928
-
929
- examples:
930
- ${y("perf")} transition goHome --timeout 10000
931
- ${y("perf")} transition appSwitcher
932
- `);break}let r=`sootsim:${t}`;console.log(` profiling ${t} transition...`),console.log(" (use --timeout 10000 if this times out)");let n=await l.send({type:"evaluate",code:`(async () => {
933
- // only supported in render-worker mode
934
- if (!window.__sootsimRenderHost) {
935
- return { error: 'transition profiling requires render-worker mode' }
936
- }
937
-
938
- // start sampling
939
- window.__sootsimRenderHost.startSampling()
940
-
941
- // give a frame for sampling to start
942
- await new Promise(r => requestAnimationFrame(() => r(undefined)))
943
-
944
- // dispatch the shell event
945
- window.dispatchEvent(new Event('${r}'))
946
-
947
- // wait 600ms for transition to complete (shell animations are ~300-500ms)
948
- // using fixed timing avoids complex animation-end detection
949
- await new Promise(r => setTimeout(r, 600))
950
-
951
- // flush samples and compute stats
952
- const samples = await window.__sootsimRenderHost.flushSamples()
953
- const frameTimes = samples.map(s => s[1])
954
- const layoutTimes = samples.map(s => s[2])
955
- const renderTimes = samples.map(s => s[3])
956
- const copyTimes = samples.map(s => s[4])
957
- const auxTimes = samples.map(s => s[5] || 0)
958
- const otherTimes = samples.map(s => s[6] || 0)
959
- const sorted = [...frameTimes].sort((a, b) => a - b)
960
- const total = frameTimes.reduce((a, b) => a + b, 0)
961
- const avg = frameTimes.length > 0 ? total / frameTimes.length : 0
962
- const max = Math.max(...frameTimes, 0)
963
- const layoutTotal = layoutTimes.reduce((a, b) => a + b, 0)
964
- const renderTotal = renderTimes.reduce((a, b) => a + b, 0)
965
- const copyTotal = copyTimes.reduce((a, b) => a + b, 0)
966
- const auxTotal = auxTimes.reduce((a, b) => a + b, 0)
967
- const otherTotal = otherTimes.reduce((a, b) => a + b, 0)
968
-
969
- return {
970
- event: '${t}',
971
- frames: frameTimes.length,
972
- totalMs: total,
973
- avgMs: avg,
974
- maxMs: max,
975
- layoutTotalMs: layoutTotal,
976
- renderTotalMs: renderTotal,
977
- copyTotalMs: copyTotal,
978
- auxTotalMs: auxTotal,
979
- otherTotalMs: otherTotal,
980
- layoutAvgMs: frameTimes.length > 0 ? layoutTotal / frameTimes.length : 0,
981
- renderAvgMs: frameTimes.length > 0 ? renderTotal / frameTimes.length : 0,
982
- copyAvgMs: frameTimes.length > 0 ? copyTotal / frameTimes.length : 0,
983
- auxAvgMs: frameTimes.length > 0 ? auxTotal / frameTimes.length : 0,
984
- otherAvgMs: frameTimes.length > 0 ? otherTotal / frameTimes.length : 0,
985
- p50: sorted[Math.floor(sorted.length * 0.5)] || 0,
986
- p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
987
- p99: sorted[Math.floor(sorted.length * 0.99)] || 0,
988
- jankFrames: frameTimes.filter(f => f > 16.67).length,
989
- samples,
990
- }
991
- })()`});if(n.error&&(console.error(` error: ${n.error}`),process.exit(1)),n.warning&&console.log(` warning: ${n.warning}`),n.frames===0){console.log(" no frames captured");break}let m=n.avgMs>0?(1e3/n.avgMs).toFixed(1):"?",p=n.frames>0?(n.jankFrames/n.frames*100).toFixed(1):"0";console.log(` ${t} transition profiled:
992
-
993
- frames: ${n.frames}
994
- total: ${n.totalMs.toFixed(1)}ms
995
- avg: ${n.avgMs.toFixed(2)}ms (${m} fps)
996
- max: ${n.maxMs.toFixed(2)}ms
997
-
998
- breakdown (avg per frame):
999
- layout: ${n.layoutAvgMs?.toFixed(2)||"?"}ms
1000
- render: ${n.renderAvgMs?.toFixed(2)||"?"}ms
1001
- copy: ${n.copyAvgMs?.toFixed(2)||"?"}ms
1002
- aux: ${n.auxAvgMs?.toFixed(2)||"?"}ms
1003
- other: ${n.otherAvgMs?.toFixed(2)||"?"}ms
1004
-
1005
- distribution (${n.frames} samples):
1006
- p50: ${n.p50.toFixed(2)}ms
1007
- p95: ${n.p95.toFixed(2)}ms
1008
- p99: ${n.p99.toFixed(2)}ms
1009
- jank: ${n.jankFrames} frames (${p}%) >16.67ms`),Array.isArray(n.samples)&&n.samples.length>0&&(console.log(""),be(n.samples.map(h=>h[1])));break}default:console.error(` unknown perf subcommand: ${e}`),process.exit(1)}break}case"errors":{let e=a[1];if(e==="clear"){await l.send({type:"evaluate",code:'window.__sootsimConsole?.clear(); "cleared"'}),E(d)?C({cleared:!0}):console.log(" error buffer cleared");break}let t=e?Number(e):20,s=await l.send({type:"evaluate",code:`window.__sootsimConsole?.getErrors(${t}) || []`}),r=Array.isArray(s)?s:[];if(E(d)){C(r);break}if(r.length===0){console.log(" no errors captured");break}console.log(` ${r.length} error(s):
1010
- `);for(let n of r){let m=new Date(n.timestamp).toLocaleTimeString(),p=n.args.map(h=>typeof h=="object"?JSON.stringify(h):h).join(" ");if(console.log(` [${m}] ${p}`),n.stack){let h=n.stack.split(`
1011
- `).slice(0,3);for(let f of h)console.log(` ${f.trim()}`)}}break}case"warnings":{let e=a[1]?Number(a[1]):20,t=await l.send({type:"evaluate",code:`window.__sootsimConsole?.getWarnings(${e}) || []`}),s=Array.isArray(t)?t:[];if(E(d)){C(s);break}if(s.length===0){console.log(" no warnings captured");break}console.log(` ${s.length} warning(s):
1012
- `);for(let r of s){let n=new Date(r.timestamp).toLocaleTimeString(),m=r.args.map(p=>typeof p=="object"?JSON.stringify(p):p).join(" ");console.log(` [${n}] ${m}`)}break}case"animations":{let e=await z(l,"listAnimations")??[];if(o.includes("--json")){console.log(JSON.stringify(e,null,2));break}if(e.length===0){console.log(" no active animations");break}console.log(` ${e.length} active animation(s):
1013
- `);for(let t of e){let s=String(t.kind).padEnd(6),r=`${Number(t.from).toFixed(2)}\u2192${Number(t.to).toFixed(2)}`,n=Number(t.current??0).toFixed(2),m=`${Math.round((t.progress??0)*100)}%`,p=`${Math.round(t.elapsedMs??0)}ms`,h=t.loop?" loop":"",f=t.layoutBound?" layout":"";console.log(` #${t.id} ${s} ${r.padEnd(14)} cur=${n.padEnd(7)} ${m.padStart(4)} ${p}${h}${f}`)}break}case"animation":{let e=a[1];(!e||e==="--help"||e==="-h")&&(console.error(` usage: ${y("animation")} <id>`),process.exit(1));let t=Number(e);Number.isFinite(t)||(console.error(` invalid id: ${e}`),process.exit(1));let s=await z(l,"getAnimation",t);console.log(JSON.stringify(s,null,2));break}case"stop-animation":{let e=a[1];(!e||e==="--help"||e==="-h")&&(console.error(` usage: ${y("stop-animation")} <id|all>`),process.exit(1));let t=e==="all"?"all":Number(e);t!=="all"&&!Number.isFinite(t)&&(console.error(` invalid id: ${e}`),process.exit(1));let s=await z(l,"stopAnimation",t);console.log(` stopped ${s??0} animation(s)`);break}case"requests":{let e=a[1];if(e==="clear"){await z(l,"clearRequests"),E(d)?C({cleared:!0}):console.log(" request buffer cleared");break}let t=e==="all",s=t?a[2]:e,r=s?Number(s):20,n=t?await z(l,"getRequests",r):await z(l,"getFailedRequests",r),m=Array.isArray(n)?n:[];if(E(d)){C(m);break}if(m.length===0){console.log(t?" no requests captured":" no failed requests captured");break}console.log(` ${m.length} ${t?"request(s)":"failed request(s)"}:
1014
- `);for(let p of m){let h=new Date(p.timestamp).toLocaleTimeString();console.log(` [${h}] ${q(p)}`),p.responseBody?console.log(` ${p.responseBody}`):p.error&&console.log(` ${p.error}`)}break}case"network":{let e=a[1],t=null,s=null,r=!1,n=!1,m=!1;for(let N=0;N<d.length;N++){let M=d[N];if(M==="--filter")t=d[N+1]??null,N++;else if(M==="--limit"){let F=Number(d[N+1]);Number.isFinite(F)&&(s=F),N++}else M==="--failed"?r=!0:M==="--tail"||M==="-f"?n=!0:M==="--json"&&(m=!0)}if(e==="clear"){await l.send({type:"evaluate",code:'window.__sootsimObservability?.network.clear(); "cleared"'}),console.log(" network buffer cleared");break}if(e==="get"){let N=a[2];N||(console.error(" usage: sootsim network get <id>"),process.exit(1));let M=await l.send({type:"evaluate",code:`(() => {
1015
- const obs = window.__sootsimObservability;
1016
- if (!obs) return null;
1017
- return obs.network.getSnapshot().find(e => e.id === ${JSON.stringify(N)}) || null;
1018
- })()`});M||(console.error(` no entry with id ${N}`),process.exit(1)),m?console.log(JSON.stringify(M,null,2)):Ft(M);break}let p=s??(n?200:e?Number(e):20);Number.isFinite(p)||(console.error(` invalid limit: ${e}`),process.exit(1));let h=async()=>{let N=await l.send({type:"evaluate",code:`(() => {
1019
- const obs = window.__sootsimObservability;
1020
- if (!obs) return { ok: false };
1021
- return { ok: true, entries: obs.network.getSnapshot() };
1022
- })()`});if(!N||!N.ok)throw new Error("observability bridge not installed \u2014 is the engine running?");return N.entries??[]},f=N=>{let M=N;if(r&&(M=M.filter(F=>!!F.error||F.status!=null&&F.status>=400)),t){let F=t.toLowerCase();M=M.filter(W=>(W.displayUrl||W.url).toLowerCase().includes(F))}return M};if(!n){let N=await h(),M=f(N).slice(-p);if(m){console.log(JSON.stringify(M,null,2));break}if(M.length===0){console.log(N.length===0?" no network requests captured":" no matching requests");break}console.log(` ${M.length} request(s):
1023
- `);for(let F of M)Ze(F);break}console.log(` tailing network (ctrl-c to stop)...
1024
- `);let w=new Set,O=!0,B=()=>{O=!1};process.on("SIGINT",B);try{for(;O;){let N=await h(),M=f(N);for(let F of M)F.durationMs!=null&&(w.has(F.id)||(w.add(F.id),m?console.log(JSON.stringify(F)):Ze(F)));await Y(250)}}finally{process.off("SIGINT",B)}break}case"logs":{let e=a[1],t=null,s=null,r=null,n=!1,m=!1,p=!1;for(let g=0;g<d.length;g++){let T=d[g];if(T==="--filter")t=d[g+1]??null,g++;else if(T==="--limit"){let _=Number(d[g+1]);Number.isFinite(_)&&(s=_),g++}else T==="--level"?(r=d[g+1]??null,g++):T==="--tail"||T==="-f"?n=!0:T==="--json"?m=!0:(T==="--internal"||T==="--all")&&(p=!0)}let h=r?new Set(r.split(",").map(g=>g.trim()).filter(g=>g==="log"||g==="info"||g==="warn"||g==="error"||g==="debug")):null;if(e==="clear"){await l.send({type:"evaluate",code:'window.__sootsimObservability?.logs.clear(); "cleared"'}),console.log(" log buffer cleared");break}let f=!m&&process.stdout.isTTY===!0,w=s??(n?500:e?Number(e):50);Number.isFinite(w)||(console.error(` invalid limit: ${e}`),process.exit(1));let O=async()=>{let g=await l.send({type:"evaluate",code:`(() => {
1025
- const obs = window.__sootsimObservability;
1026
- if (!obs) return { ok: false };
1027
- return { ok: true, entries: obs.logs.getSnapshot() };
1028
- })()`});if(!g||!g.ok)throw new Error("observability bridge not installed \u2014 is the engine running?");return g.entries??[]},B=g=>{let T=g.args[0];return typeof T!="string"?!1:T.startsWith("[sootsim]")},N=g=>{let T=g;if(p||(T=T.filter(_=>!B(_))),h&&(T=T.filter(_=>h.has(_.level))),t){let _=t.toLowerCase();T=T.filter(P=>P.args.join(" ").toLowerCase().includes(_))}return T};if(!n){let g=await O(),T=N(g).slice(-w);if(m){console.log(JSON.stringify(T,null,2));break}if(T.length===0){console.log(g.length===0?" no logs captured":" no matching logs");break}console.log(` ${T.length} log(s):
1029
- `);for(let _ of T)et(_,f);break}console.log(` tailing logs (ctrl-c to stop)...
1030
- `);let M=new Set,F=!0,W=()=>{F=!1};process.on("SIGINT",W);try{for(;F;){let g=await O(),T=N(g);for(let _ of T)M.has(_.id)||(M.add(_.id),m?console.log(JSON.stringify(_)):et(_,f));await Y(250)}}finally{process.off("SIGINT",W)}break}default:console.error(` unknown subcommand: ${b}`),process.exit(1)}if(H.has(b)&&!o.includes("--no-wait")&&process.env.SOOTSIM_NO_AUTO_WAIT!=="1"&&await ne(l),!D.has(b)&&!E(d)){let e=await Z();try{await J({counts:e.console})}catch{}try{await x({counts:e.requests})}catch{}}}catch(e){let t=e instanceof Error?e.message:String(e);if(console.error(` ${b??"inspect"} failed: ${t}`),/^no browser connected( with id .+)?$/.test(t))Ae(A);else{try{await Me(l)}catch{}try{await J({includeTail:!0})}catch{}try{await x({includeTail:!0})}catch{}}process.exit(1)}finally{l.close()}}export{rs as runInspect};