rnxsim 0.1.354 → 0.1.355

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 (176) hide show
  1. package/cli/bridge-flow-runner.ts +44 -51
  2. package/cli/commands/inspect/settling.ts +9 -2
  3. package/cli/outbound-endpoints.ts +1 -1
  4. package/detox/index.ts +144 -74
  5. package/detox/proof-frame.cjs +107 -0
  6. package/dist-cli/bin.js +5 -5
  7. package/dist-cli/chunks/{agent-FB7RPXO6.js → agent-2MW7ZKUX.js} +2 -2
  8. package/dist-cli/chunks/{agent-wrapper-LFU3XEIG.js → agent-wrapper-XYQBKV24.js} +2 -2
  9. package/dist-cli/chunks/{app-fonts-FK6SETRG.js → app-fonts-SXIZFMPY.js} +2 -2
  10. package/dist-cli/chunks/{assert-3KQYZDDK.js → assert-R324GCRG.js} +2 -2
  11. package/dist-cli/chunks/{auth-RFE3J27C.js → auth-INKYLYRZ.js} +2 -2
  12. package/dist-cli/chunks/{beta-XVY4WOYH.js → beta-BQHBSKA5.js} +2 -2
  13. package/dist-cli/chunks/{camera-JROBX5GM.js → camera-UPRFBRPF.js} +2 -2
  14. package/dist-cli/chunks/{chunk-MIK6LMG4.js → chunk-23TG7DLH.js} +1 -1
  15. package/dist-cli/chunks/{chunk-JT4IMNCO.js → chunk-247ZSWTI.js} +2 -2
  16. package/dist-cli/chunks/chunk-2GLEESND.js +535 -0
  17. package/dist-cli/chunks/{chunk-7WANPS3W.js → chunk-2Z2S3C6A.js} +2 -2
  18. package/dist-cli/chunks/{chunk-JJOHJNUQ.js → chunk-42LIUAHU.js} +2 -2
  19. package/dist-cli/chunks/{chunk-UI2IFVHB.js → chunk-6EC3D5IG.js} +1 -1
  20. package/dist-cli/chunks/{chunk-JXNR2KAB.js → chunk-6WCDWBG6.js} +2 -2
  21. package/dist-cli/chunks/{chunk-IGV4KCCM.js → chunk-7URIRES5.js} +2 -2
  22. package/dist-cli/chunks/{chunk-JT435OOM.js → chunk-AY4OA5UI.js} +2 -2
  23. package/dist-cli/chunks/{chunk-FEHHM2LV.js → chunk-BUOAYILA.js} +12 -5
  24. package/dist-cli/chunks/{chunk-N3CE6AZP.js → chunk-CK3M7MAL.js} +2 -2
  25. package/dist-cli/chunks/{chunk-Y4GUWO3X.js → chunk-CRE3V3EG.js} +1 -1
  26. package/dist-cli/chunks/{chunk-YIUIFZAE.js → chunk-CUXVUSZS.js} +2 -2
  27. package/dist-cli/chunks/{chunk-ZNABCRWX.js → chunk-EQEEPP5A.js} +2 -2
  28. package/dist-cli/chunks/{chunk-QRYTCPNO.js → chunk-EZXNGHZT.js} +2 -2
  29. package/dist-cli/chunks/{chunk-LETVUC6M.js → chunk-F6S4Z7N7.js} +1 -1
  30. package/dist-cli/chunks/{chunk-HIYCRDUP.js → chunk-FDI226G4.js} +2 -2
  31. package/dist-cli/chunks/{chunk-X2DJK3TB.js → chunk-FF2CEKZF.js} +2 -2
  32. package/dist-cli/chunks/{chunk-ATQPDEED.js → chunk-FFNFGVGH.js} +2 -2
  33. package/dist-cli/chunks/{chunk-UVIWE3LD.js → chunk-FPWDC2DE.js} +1 -1
  34. package/dist-cli/chunks/{chunk-PHIYWV44.js → chunk-GE7GYFE4.js} +2 -2
  35. package/dist-cli/chunks/{chunk-37S36DFW.js → chunk-GFDFVKVW.js} +1 -1
  36. package/dist-cli/chunks/{chunk-JWXAXCC6.js → chunk-GWL4KMTK.js} +2 -2
  37. package/dist-cli/chunks/{chunk-CKKDXTKV.js → chunk-IAVHAWDL.js} +1 -1
  38. package/dist-cli/chunks/{chunk-4OS3SXPZ.js → chunk-IJGL6T4M.js} +2 -2
  39. package/dist-cli/chunks/{chunk-FPH4TYZO.js → chunk-JE6NXNGL.js} +3 -3
  40. package/dist-cli/chunks/{chunk-OKFSCCFC.js → chunk-JP2YS7LC.js} +1 -1
  41. package/dist-cli/chunks/{chunk-766UIGCS.js → chunk-JYQNEVHV.js} +2 -2
  42. package/dist-cli/chunks/{chunk-B7OMSJXC.js → chunk-KLVSEUJP.js} +2 -2
  43. package/dist-cli/chunks/{chunk-4AQCDL24.js → chunk-LJCBPR7S.js} +2 -2
  44. package/dist-cli/chunks/{chunk-CUK6Y2RR.js → chunk-LQEC53JM.js} +2 -2
  45. package/dist-cli/chunks/{chunk-24DA3Y2Z.js → chunk-MCAQZI3R.js} +1 -1
  46. package/dist-cli/chunks/{chunk-ZJUFI3R7.js → chunk-MKHCGQSF.js} +1 -1
  47. package/dist-cli/chunks/{chunk-GNKXRXND.js → chunk-N532KCKW.js} +2 -2
  48. package/dist-cli/chunks/{chunk-BNXXNT3I.js → chunk-NCF3QNJG.js} +2 -2
  49. package/dist-cli/chunks/{chunk-THFM2CFT.js → chunk-PYSIEEKP.js} +1 -1
  50. package/dist-cli/chunks/{chunk-TJRKLRNP.js → chunk-QWJD2CAJ.js} +1 -1
  51. package/dist-cli/chunks/{chunk-SLD2EMLZ.js → chunk-QYIT7H6Q.js} +2 -2
  52. package/dist-cli/chunks/{chunk-QQNNY43R.js → chunk-S27I7H2K.js} +1 -1
  53. package/dist-cli/chunks/{chunk-EWPX6LEN.js → chunk-S4K3TDYB.js} +2 -2
  54. package/dist-cli/chunks/{chunk-YXBNGSG6.js → chunk-SEWNI4GS.js} +1 -1
  55. package/dist-cli/chunks/{chunk-ENPWD62S.js → chunk-SJEAA2FW.js} +2 -2
  56. package/dist-cli/chunks/{chunk-P4GCLNFM.js → chunk-TADYO7TY.js} +2 -2
  57. package/dist-cli/chunks/chunk-UIBR3GXC.js +4 -0
  58. package/dist-cli/chunks/{chunk-UAYXEP74.js → chunk-VEMZUXVR.js} +1 -1
  59. package/dist-cli/chunks/{chunk-3RW6W3ZO.js → chunk-VWPXXB6U.js} +1 -1
  60. package/dist-cli/chunks/{chunk-IUL2WUWW.js → chunk-W3QLC24Z.js} +2 -2
  61. package/dist-cli/chunks/{chunk-LRVL5MAX.js → chunk-WUYI4PVY.js} +1 -1
  62. package/dist-cli/chunks/{chunk-LC77IVGY.js → chunk-X36BQCH5.js} +2 -2
  63. package/dist-cli/chunks/{chunk-77CBLMD4.js → chunk-XFPGXEKW.js} +1 -1
  64. package/dist-cli/chunks/{chunk-3QLERZYJ.js → chunk-XZJNPATS.js} +2 -2
  65. package/dist-cli/chunks/{chunk-GYGDIT5V.js → chunk-Y3D3DCQV.js} +2 -2
  66. package/dist-cli/chunks/{chunk-LCPZNPIB.js → chunk-Y5BP72QO.js} +1 -1
  67. package/dist-cli/chunks/{chunk-HUU7ZUQK.js → chunk-ZNWLFYZK.js} +2 -2
  68. package/dist-cli/chunks/{chunk-IICFLREN.js → chunk-ZOFRHAGX.js} +1 -1
  69. package/dist-cli/chunks/{chunk-UX6D4X6B.js → chunk-ZQF3PK76.js} +2 -2
  70. package/dist-cli/chunks/{cleanup-F74ISXJC.js → cleanup-5FGGUP6U.js} +2 -2
  71. package/dist-cli/chunks/cli-version-JP47UGY6.js +4 -0
  72. package/dist-cli/chunks/{compat-C3RGYGXL.js → compat-J4OEALGF.js} +2 -2
  73. package/dist-cli/chunks/{config-CDY2RB7Q.js → config-MCH2R7WG.js} +2 -2
  74. package/dist-cli/chunks/{control-J35HAFZA.js → control-NPWFRKZS.js} +2 -2
  75. package/dist-cli/chunks/daemon-M26NJFNC.js +4 -0
  76. package/dist-cli/chunks/{debug-3P2DUTUQ.js → debug-7NHPYUX6.js} +3 -3
  77. package/dist-cli/chunks/{desktop-XIXW34VW.js → desktop-EIBJC5EU.js} +3 -3
  78. package/dist-cli/chunks/{detox-KAKTJ4P4.js → detox-ZFEQKHDT.js} +2 -2
  79. package/dist-cli/chunks/{device-4MAWLZMR.js → device-JM7QMQFQ.js} +2 -2
  80. package/dist-cli/chunks/{diagnose-A3R7HUYA.js → diagnose-DCMU2GAD.js} +2 -2
  81. package/dist-cli/chunks/{disk-cleanup-5R7JYCO6.js → disk-cleanup-RPW5MYGM.js} +2 -2
  82. package/dist-cli/chunks/drivers-DW3CQUTK.js +4 -0
  83. package/dist-cli/chunks/{film-GY5U752Q.js → film-NRGBZSC7.js} +3 -3
  84. package/dist-cli/chunks/flow-76SLGQCI.js +4 -0
  85. package/dist-cli/chunks/help-GUYB5XWH.js +4 -0
  86. package/dist-cli/chunks/{hidden-runtime-alias-HSGN3GN4.js → hidden-runtime-alias-GSZG7QFD.js} +2 -2
  87. package/dist-cli/chunks/{home-paths-BIUN4CBO.js → home-paths-OGXLRRTG.js} +2 -2
  88. package/dist-cli/chunks/inspect-URTBYLXV.js +4 -0
  89. package/dist-cli/chunks/install-desktop-BINBAGSN.js +4 -0
  90. package/dist-cli/chunks/{login-WKNMS4GG.js → login-A7JSAMON.js} +2 -2
  91. package/dist-cli/chunks/{logout-6UFUOESK.js → logout-EBUWNT63.js} +2 -2
  92. package/dist-cli/chunks/{maestro-SJGV7B3W.js → maestro-OEXXVYMW.js} +3 -3
  93. package/dist-cli/chunks/{maestro-generate-PMF2LLKX.js → maestro-generate-DKH6IUTC.js} +3 -3
  94. package/dist-cli/chunks/{mode-MN7LZCLB.js → mode-YKX2UTBX.js} +2 -2
  95. package/dist-cli/chunks/{optional-demo-registry-HFA27YSP.js → optional-demo-registry-W4Z54NYF.js} +2 -2
  96. package/dist-cli/chunks/{perf-XGANSJT3.js → perf-EJDB2NWH.js} +2 -2
  97. package/dist-cli/chunks/{permissions-25UWEJKW.js → permissions-MXUT3YR6.js} +2 -2
  98. package/dist-cli/chunks/privacy-JIJOFIGM.js +4 -0
  99. package/dist-cli/chunks/{record-MA3AI752.js → record-STFUL6CS.js} +3 -3
  100. package/dist-cli/chunks/{report-issue-4DTESWE2.js → report-issue-TE2QTEMZ.js} +2 -2
  101. package/dist-cli/chunks/reset-LAIGONON.js +4 -0
  102. package/dist-cli/chunks/runtime-ZS3FBQLG.js +4 -0
  103. package/dist-cli/chunks/{screenshot-command-JUXMWXS5.js → screenshot-command-SRW3HXF7.js} +3 -3
  104. package/dist-cli/chunks/{screenshot-layers-DJF2E4PE.js → screenshot-layers-IULR35XJ.js} +2 -2
  105. package/dist-cli/chunks/{screenshots-capture-UGZU5GOW.js → screenshots-capture-54GFQLXS.js} +2 -2
  106. package/dist-cli/chunks/{serve-H7GNKJSM.js → serve-WJAOT43K.js} +2 -2
  107. package/dist-cli/chunks/setup-36ACJ5FT.js +4 -0
  108. package/dist-cli/chunks/{skills-4JGPOSFE.js → skills-DW5GLHAT.js} +2 -2
  109. package/dist-cli/chunks/{state-DEAQFKVP.js → state-IW4THIPU.js} +2 -2
  110. package/dist-cli/chunks/{storage-Y6F5NTGH.js → storage-F4RQZFTZ.js} +2 -2
  111. package/dist-cli/chunks/store-MTN4TPL6.js +4 -0
  112. package/dist-cli/chunks/telemetry-CJSVYHLI.js +4 -0
  113. package/dist-cli/chunks/{timeline-HOHYYDOC.js → timeline-IX3HVS22.js} +2 -2
  114. package/dist-cli/chunks/{upgrade-QF5YHLSG.js → upgrade-T4LWQ2JA.js} +2 -2
  115. package/dist-cli/chunks/upload-LHWECFWH.js +4 -0
  116. package/dist-cli/chunks/{version-PDCKYJLB.js → version-MNRMHJ64.js} +2 -2
  117. package/dist-cli/chunks/{web-C5EUAFFW.js → web-ARKJI3PY.js} +2 -2
  118. package/dist-cli/chunks/welcome-XH657K2V.js +5 -0
  119. package/dist-cli/chunks/{what-happened-L56ZFIMJ.js → what-happened-EBK5NZFI.js} +2 -2
  120. package/dist-lib/agent-daemon-client.cjs +1 -1
  121. package/dist-lib/agent-events.cjs +1 -1
  122. package/dist-lib/agent-identity.cjs +1 -1
  123. package/dist-lib/agent-sessions.cjs +1 -1
  124. package/dist-lib/attached-projects.cjs +1 -1
  125. package/dist-lib/auth/shared-session.cjs +1 -1
  126. package/dist-lib/backend-origin.cjs +1 -1
  127. package/dist-lib/beta.cjs +1 -1
  128. package/dist-lib/beta.mjs +1 -1
  129. package/dist-lib/bridge-constants.cjs +1 -1
  130. package/dist-lib/bridge-contract.cjs +1 -1
  131. package/dist-lib/cli-constants.cjs +1 -1
  132. package/dist-lib/config.cjs +1 -1
  133. package/dist-lib/detox/index.cjs +196 -54
  134. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  135. package/dist-lib/home-paths.cjs +1 -1
  136. package/dist-lib/host/bridge-host.cjs +1 -1
  137. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  138. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  139. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  140. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  141. package/dist-lib/host/websocket-proxy.cjs +1 -1
  142. package/dist-lib/index.cjs +10 -3
  143. package/dist-lib/jump-to-source-babel.cjs +1 -1
  144. package/dist-lib/menu.cjs +1 -1
  145. package/dist-lib/menu.mjs +1 -1
  146. package/dist-lib/metro-production-bundle.cjs +1 -1
  147. package/dist-lib/metro-production-bundle.mjs +1 -1
  148. package/dist-lib/metro.cjs +1 -1
  149. package/dist-lib/profiles.cjs +1 -1
  150. package/dist-lib/public-brand.cjs +1 -1
  151. package/dist-lib/react-native-host-modules.cjs +1 -1
  152. package/dist-lib/react-native-host-modules.mjs +1 -1
  153. package/dist-lib/render-mode.cjs +1 -1
  154. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  155. package/dist-lib/sdk.cjs +10 -3
  156. package/dist-lib/sdk.mjs +10 -3
  157. package/dist-lib/skills.cjs +4735 -196
  158. package/dist-lib/vite.cjs +1 -1
  159. package/package.json +1 -1
  160. package/dist-cli/chunks/chunk-BAWV2UEF.js +0 -543
  161. package/dist-cli/chunks/chunk-YATZ7U4S.js +0 -4
  162. package/dist-cli/chunks/cli-version-VSDCFXXN.js +0 -4
  163. package/dist-cli/chunks/daemon-DLLEODJY.js +0 -4
  164. package/dist-cli/chunks/drivers-BB3BRKDS.js +0 -4
  165. package/dist-cli/chunks/flow-ALMSRBVL.js +0 -4
  166. package/dist-cli/chunks/help-3ZL7MRUX.js +0 -4
  167. package/dist-cli/chunks/inspect-RCU7XVAO.js +0 -4
  168. package/dist-cli/chunks/install-desktop-LYVKLTCU.js +0 -4
  169. package/dist-cli/chunks/privacy-SIDMP5EF.js +0 -4
  170. package/dist-cli/chunks/reset-GPHG5XN3.js +0 -4
  171. package/dist-cli/chunks/runtime-VOEIOODA.js +0 -4
  172. package/dist-cli/chunks/setup-G2WYLPM6.js +0 -4
  173. package/dist-cli/chunks/store-3EQT7VU6.js +0 -4
  174. package/dist-cli/chunks/telemetry-FANCQHKG.js +0 -4
  175. package/dist-cli/chunks/upload-QKJHFAX7.js +0 -4
  176. package/dist-cli/chunks/welcome-3CQ2GE4F.js +0 -5
@@ -1,543 +0,0 @@
1
- /*! rnx v0.1.354 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import { createRequire as __sootsimCreateRequire } from 'node:module'
3
- var require = __sootsimCreateRequire(import.meta.url)
4
- import{a as nt}from"./chunk-3RW6W3ZO.js";import{a as st}from"./chunk-JT4IMNCO.js";import{e as ot}from"./chunk-7WANPS3W.js";import{a as Qe,b as fe,c as me,d as tt,e as ge,f as we,g as rt,h as ye,i as it}from"./chunk-FEHHM2LV.js";import{a as et}from"./chunk-ATQPDEED.js";import{g as qe,h as Ye,p as ze,r as Xe,v as Ze}from"./chunk-B7OMSJXC.js";import{k as Ne}from"./chunk-IGV4KCCM.js";import{h as Je,m as Ge}from"./chunk-766UIGCS.js";import{J as he,m as He,n as Ue,o as We,p as je,q as Ve}from"./chunk-UAYXEP74.js";import{b as Ce}from"./chunk-77CBLMD4.js";import{a as Oe,b as _e,c as De}from"./chunk-X2DJK3TB.js";import{g as ce,h as Be,q as ue,r as pe,s as Le}from"./chunk-JJOHJNUQ.js";import{a as Ke}from"./chunk-Y4GUWO3X.js";import*as P from"fs";import{createHash as qt,randomUUID as Yt}from"node:crypto";import{tmpdir as Y}from"os";import*as w from"path";import*as x from"fs";import*as S from"path";var $t="inset 0 0 0 0.5px #000, inset 0 0 0 2px #757575, inset 0 0 0 5px #212121",lt=1;function At(n){let e=De(n),t=e.scale,r=e.statusBarHeight>0&&!e.dynamicIsland&&e.homeIndicatorHeight===0&&e.cornerRadius===0,i=e.width,o=e.height,a=Oe(e),s=r?e.width+58:a.frameWidth,l=r?e.height+111+111:a.frameHeight,p=9.5,u=lt,m=s+p*2,b=l+lt*2,g=p+(r?29:a.screenLeft),A=r?111:a.screenTop,k=r?52:a.frameRadius,H=[{side:e.hardwareButtons.lock.side,top:e.hardwareButtons.lock.top,height:e.hardwareButtons.lock.height,width:e.hardwareButtons.width},{side:e.hardwareButtons.ringToggle.side,top:e.hardwareButtons.ringToggle.top,height:e.hardwareButtons.ringToggle.height,width:e.hardwareButtons.width},{side:e.hardwareButtons.volumeUp.side,top:e.hardwareButtons.volumeUp.top,height:e.hardwareButtons.volumeUp.height,width:e.hardwareButtons.width},{side:e.hardwareButtons.volumeDown.side,top:e.hardwareButtons.volumeDown.top,height:e.hardwareButtons.volumeDown.height,width:e.hardwareButtons.width}];return{model:n,renderScale:t,outerWidth:Math.round(m*t),outerHeight:Math.round(b*t),logicalOuterWidth:m,logicalOuterHeight:b,logicalFrameWidth:s,logicalFrameHeight:l,logicalFrameLeft:p,logicalFrameTop:u,logicalScreenWidth:i,logicalScreenHeight:o,logicalScreenLeft:g,logicalScreenTop:A,logicalScreenRadius:r?0:a.screenRadius,logicalFrameRadius:k,frameBackground:r?"linear-gradient(180deg, #1b1c20 0%, #0f1012 42%, #050608 100%)":"#000000",frameOutline:r?"0 0 0 1px #1f2125":"0 0 0 1px #333",metallicRingShadow:r?null:$t,buttons:H,legacyHomeButton:r?{top:111+e.height+47/2,left:e.width/2-64/2+29,size:64,ring:1.5}:null,showHomeIndicator:e.homeIndicatorHeight>0,logicalHomeIndicatorStripHeight:e.homeIndicatorHeight}}function Rt(n){let e=n.side==="right",t=e?"inset(-3px -3px -3px 0)":"inset(-3px 0 -3px -3px)";return`
5
- <div
6
- aria-hidden="true"
7
- style="
8
- position:absolute;
9
- ${e?`right:-${n.width}px;`:`left:-${n.width}px;`}
10
- top:${n.top}px;
11
- width:${n.width}px;
12
- height:${n.height}px;
13
- background-color:#212121;
14
- border-top-left-radius:${e?0:1.5}px;
15
- border-bottom-left-radius:${e?0:1.5}px;
16
- border-top-right-radius:${e?1.5:0}px;
17
- border-bottom-right-radius:${e?1.5:0}px;
18
- box-shadow:
19
- inset 0 0.5px 0 #616161,
20
- inset 0 -0.5px 0 #3F3F3F,
21
- ${e?"inset -0.5px 0 0 #3F3F3F,":"inset 0.5px 0 0 #3F3F3F,"}
22
- 0 0 0 0.5px #676767,
23
- 0 0 0 1.5px #000;
24
- clip-path:${t};
25
- pointer-events:none;
26
- z-index:2;
27
- "
28
- ></div>
29
- `}function Mt(n,e){let t=n.buttons.map(Rt).join(""),r=n.metallicRingShadow?`
30
- <div
31
- aria-hidden="true"
32
- style="
33
- position:absolute;
34
- inset:0;
35
- border-radius:${n.logicalFrameRadius}px;
36
- box-shadow:${n.metallicRingShadow};
37
- pointer-events:none;
38
- z-index:10;
39
- "
40
- ></div>
41
- `:"",i=n.legacyHomeButton?`
42
- <div
43
- aria-hidden="true"
44
- style="
45
- position:absolute;
46
- top:${n.legacyHomeButton.top}px;
47
- left:${n.legacyHomeButton.left}px;
48
- width:${n.legacyHomeButton.size}px;
49
- height:${n.legacyHomeButton.size}px;
50
- border-radius:50%;
51
- background:
52
- radial-gradient(circle at 35% 32%, rgba(62,64,68,0.35) 0%, rgba(17,18,20,0.98) 72%, rgba(8,9,11,1) 100%);
53
- box-shadow:
54
- inset 0 0 0 1px rgba(255,255,255,0.06),
55
- inset 0 0 0 ${n.legacyHomeButton.ring}px rgba(184,192,204,0.45),
56
- 0 0 0 1px rgba(0,0,0,0.5);
57
- z-index:3;
58
- pointer-events:none;
59
- display:flex;
60
- align-items:center;
61
- justify-content:center;
62
- "
63
- >
64
- <div
65
- style="
66
- width:16px;
67
- height:16px;
68
- border-radius:4px;
69
- box-shadow:inset 0 0 0 1.5px rgba(188,194,202,0.5);
70
- "
71
- ></div>
72
- </div>
73
- `:"",o=n.showHomeIndicator?`
74
- <div
75
- aria-hidden="true"
76
- style="
77
- position:absolute;
78
- left:0;
79
- right:0;
80
- bottom:4px;
81
- height:${n.logicalHomeIndicatorStripHeight}px;
82
- display:flex;
83
- align-items:center;
84
- justify-content:center;
85
- pointer-events:none;
86
- z-index:10;
87
- "
88
- >
89
- <div
90
- style="
91
- width:134px;
92
- height:5px;
93
- border-radius:2.5px;
94
- background-color:rgb(150, 150, 150);
95
- opacity:0.5;
96
- "
97
- ></div>
98
- </div>
99
- `:"";return`<!doctype html>
100
- <html>
101
- <head>
102
- <meta charset="utf-8" />
103
- <style>
104
- html, body {
105
- margin: 0;
106
- width: ${n.outerWidth}px;
107
- height: ${n.outerHeight}px;
108
- background: transparent;
109
- }
110
- body {
111
- overflow: hidden;
112
- }
113
- img {
114
- display: block;
115
- width: 100%;
116
- height: 100%;
117
- }
118
- </style>
119
- </head>
120
- <body>
121
- <div
122
- id="frame-export-root"
123
- style="
124
- position:relative;
125
- width:${n.outerWidth}px;
126
- height:${n.outerHeight}px;
127
- overflow:hidden;
128
- background:transparent;
129
- "
130
- >
131
- <div
132
- id="frame-scale-layer"
133
- style="
134
- position:absolute;
135
- top:0;
136
- left:0;
137
- width:${n.logicalOuterWidth}px;
138
- height:${n.logicalOuterHeight}px;
139
- transform:scale(${n.renderScale});
140
- transform-origin:top left;
141
- overflow:visible;
142
- "
143
- >
144
- <div
145
- id="frame"
146
- style="
147
- position:absolute;
148
- top:${n.logicalFrameTop}px;
149
- left:${n.logicalFrameLeft}px;
150
- width:${n.logicalFrameWidth}px;
151
- height:${n.logicalFrameHeight}px;
152
- border-radius:${n.logicalFrameRadius}px;
153
- box-sizing:border-box;
154
- overflow:visible;
155
- background:${n.frameBackground};
156
- box-shadow:${n.frameOutline};
157
- "
158
- >
159
- ${t}
160
- ${r}
161
- ${i}
162
- <div
163
- id="screen"
164
- style="
165
- position:absolute;
166
- top:${n.logicalScreenTop}px;
167
- left:${n.logicalScreenLeft-n.logicalFrameLeft}px;
168
- width:${n.logicalScreenWidth}px;
169
- height:${n.logicalScreenHeight}px;
170
- border-radius:${n.logicalScreenRadius}px;
171
- overflow:hidden;
172
- background:#000;
173
- "
174
- >
175
- <img src="${e}" alt="" />
176
- ${o}
177
- </div>
178
- </div>
179
- </div>
180
- </div>
181
- </body>
182
- </html>`}async function dt(n,e){let{chromium:t}=await import("playwright"),r=await nt(i=>t.launch(i),{headless:!0});try{let i=await Ot(r);try{return await i.compose(n,e)}finally{await i.close()}}finally{await r.close()}}async function Ot(n){let e=new Map;async function t(r){let i=e.get(r);if(i)return i;let o=At(r),a=await n.newContext({viewport:{width:o.outerWidth,height:o.outerHeight},deviceScaleFactor:1}),s=await a.newPage(),l={layout:o,context:a,page:s};return e.set(r,l),l}return{async compose(r,i){let o=await t(i),a=`data:image/png;base64,${r.toString("base64")}`;return await o.page.setContent(Mt(o.layout,a),{waitUntil:"load"}),await o.page.waitForTimeout(20),await o.page.screenshot({type:"png",clip:{x:0,y:0,width:o.layout.outerWidth,height:o.layout.outerHeight},omitBackground:!0})},async close(){for(let r of e.values())await r.context.close();e.clear()}}}import{spawnSync as _t}from"child_process";import*as C from"vm";var Dt=3e5,Bt=`
183
- let input = '';
184
- process.stdin.on('data', (c) => { input += c });
185
- process.stdin.on('end', async () => {
186
- try {
187
- const req = JSON.parse(input);
188
- const res = await fetch(req.url, {
189
- method: req.method,
190
- headers: req.headers,
191
- body: req.body === undefined || req.body === null ? undefined : req.body,
192
- });
193
- const body = await res.text();
194
- const headers = {};
195
- for (const [k, v] of res.headers.entries()) {
196
- headers[k] = headers[k] ? headers[k] + ',' + v : v;
197
- }
198
- process.stdout.write(JSON.stringify({ ok: res.ok, status: res.status, body, headers }));
199
- } catch (err) {
200
- process.stdout.write(JSON.stringify({ __error: (err && err.message) || String(err) }));
201
- process.exitCode = 1;
202
- }
203
- });
204
- `;function G(n,e,t){if(t?.multipartForm)throw new Error("http: multipartForm is not supported by rnx yet");let r={...process.env};for(let s of Object.keys(r))(s.startsWith("BUN_INSPECT")||s==="NODE_OPTIONS")&&delete r[s];let i=_t(process.execPath,["-e",Bt],{input:JSON.stringify({url:n,method:e,headers:t?.headers,body:t?.body}),encoding:"utf8",timeout:Dt,maxBuffer:64*1024*1024,env:r});if(i.error)throw new Error(`http ${e} ${n} failed: ${i.error.message}`);let o;try{o=JSON.parse(i.stdout||"")}catch{throw new Error(`http ${e} ${n} failed: no response (${(i.stderr||"").trim().slice(0,200)})`)}let a=o;if(a.__error)throw new Error(`http ${e} ${n} failed: ${a.__error}`);return a}var Lt=/(?<!\\)\$\{([^$]*)\}/g,Ct=/\\(\$\{[^$]*\})/g,Nt=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Z=class{context;envBinding=new Map;envScopeStack=[];syncedEnvKeys=new Set;output={};maestro;constructor(e={}){this.maestro={copiedText:null,platform:e.platform??"ios"};let t=e.onLog??(i=>console.log(`[flow] js: ${i}`)),r={output:this.output,maestro:this.maestro,http:{get:(i,o)=>G(i,"GET",o),post:(i,o)=>G(i,"POST",o),put:(i,o)=>G(i,"PUT",o),delete:(i,o)=>G(i,"DELETE",o),request:(i,o)=>G(i,(o?.method??"GET").toUpperCase(),o)},console:{log:(...i)=>t(i.map(o=>typeof o=="string"?o:ct(o)).join(" "))}};this.context=C.createContext(r),C.runInContext(`
205
- globalThis.__maestroScope = new Proxy(globalThis, {
206
- has() { return true },
207
- get(target, key) { return target[key] },
208
- })
209
- function json(text) { return JSON.parse(text) }
210
- function relativePoint(x, y) {
211
- var xPercent = Math.ceil(x * 100) + '%'
212
- var yPercent = Math.ceil(y * 100) + '%'
213
- return xPercent + ',' + yPercent
214
- }
215
- `,this.context);for(let[i,o]of Object.entries(process.env))o!==void 0&&this.envBinding.set(i,o)}putEnv(e,t){this.envBinding.set(e,t)}setCopiedText(e){this.maestro.copiedText=e}enterEnvScope(){this.envScopeStack.push(new Map(this.envBinding))}leaveEnvScope(){let e=this.envScopeStack.pop();if(e){this.envBinding.clear();for(let[t,r]of e)this.envBinding.set(t,r)}}evaluate(e,t={}){let r=t.env;if(r&&Object.keys(r).length>0){this.enterEnvScope();try{for(let[i,o]of Object.entries(r))this.envBinding.set(i,o);return this.evalRaw(e)}finally{this.leaveEnvScope()}}return this.evalRaw(e)}evalRaw(e){this.syncEnvToContext();let t=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${");return C.runInContext(`(function(){ with(__maestroScope){ return eval(\`${t}\`) } })()`,this.context)}syncEnvToContext(){let e=C.runInContext("globalThis",this.context);for(let t of this.syncedEnvKeys)this.envBinding.has(t)||delete e[t];this.syncedEnvKeys=new Set;for(let[t,r]of this.envBinding)try{e[t]=r,this.syncedEnvKeys.add(t)}catch{}}evaluateStringTemplate(e){return e.replace(Lt,(r,i)=>{if(i.trim().length===0)return"";let o=this.evaluate(i);if(o===void 0&&Nt.test(i.trim()))throw new Error(`missing variable for flow placeholder: ${i.trim()}`);return ct(o)}).replace(Ct,(r,i)=>i)}interpolateStep(e){return this.interpolateValue(e,null)}interpolateValue(e,t){return typeof e=="string"?t==="evalScript"?e:this.evaluateStringTemplate(e):Array.isArray(e)?t==="commands"||t==="onFlowStart"||t==="onFlowComplete"?e:e.map(r=>this.interpolateValue(r,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,i])=>[r,this.interpolateValue(i,r)])):e}};function ct(n){if(n===void 0)return"undefined";if(n===null)return"null";if(typeof n=="object")try{return JSON.stringify(n)}catch{return String(n)}return String(n)}function ut(n){if(n==null)return!1;if(typeof n=="boolean")return n;let e=String(n);if(e.trim().length===0||e.toLowerCase()==="false"||e==="undefined"||e==="null")return!1;let t=Number(e);return!(!Number.isNaN(t)&&t===0)}var Q=1e4,Ht=Math.min(10,Math.max(1,Number(process.env.SOOTSIM_FLOW_TIMEOUT_SCALE)||1)),K=n=>Math.round(n*Ht),te=393,N=852;function f(n){return new Promise(e=>setTimeout(e,n))}function xe(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}function q(n,e){if(!xe(n))return null;let t=n[e];return typeof t=="string"&&t.length>0?t:null}function Ut(n,e){return xe(n)?n[e]===!0:!1}function Wt(n){if(!n)return null;let e=n.recentApps;if(Array.isArray(e))for(let r of e){let i=q(r,"id");if(i)return i}let t=n.surfaceBindings;return q(t,"app:one")||q(t,"app:two")||null}function jt(n){return n?S.basename(n)===".maestro"?S.dirname(n):n:process.cwd()}function Vt(n,e,t){let r=e.endsWith(".png")?e:`${e}.png`;if(S.isAbsolute(r))return r;if(t.mode==="flow"&&/[\\/]/.test(r)){let i=r.startsWith("./")||r.startsWith("../")?t.flowDir??process.cwd():jt(t.flowDir);return S.resolve(i,r)}return S.join(n,r)}function Jt(n){if(typeof n=="string")return{path:n,withFrame:!1};let e=n.path?.trim()||n.name?.trim();if(!e)throw new Error("takeScreenshot object form requires path or name");return{path:e,withFrame:n.withFrame===!0,layers:n.layers}}function ee(n,e){let[t,r]=n.split(",").map(s=>s.trim()),i=(s,l)=>s.endsWith("%")?Number.parseFloat(s)/100*l:Number.parseFloat(s),o=e?.x??0,a=e?.y??0;return{x:o+i(t,e?.width??te),y:a+i(r,e?.height??N)}}function pt(n){switch(n){case"back":return{back:!0};case"hideKeyboard":return{hideKeyboard:!0};case"waitForAnimationToEnd":return{waitForAnimationToEnd:!0};case"stopApp":return{stopApp:!0};case"clearState":return{clearState:!0};case"clearKeychain":return{clearKeychain:!0};case"eraseText":return{eraseText:50};case"scroll":case"scrollDown":return{scroll:{direction:"DOWN"}};case"scrollUp":return{scroll:{direction:"UP"}};default:return{[n]:!0}}}function Gt(n){let e=n.split(/^---$/m),t=e.length>1?e[e.length-1]:n,r=et.parse(t);return Array.isArray(r)?r:[]}var re=class{constructor(e,t){this.bridge=e;this.opts=t}stepDelay=0;js=new Z({platform:"ios",onLog:e=>console.log(`[flow] js: ${e}`)});firstLaunchDone=!1;profilingEnabled=!1;recordingEnabled=!1;recordingAccessChecked=!1;recordingStartedAtMs=null;lastRecordingStartedAtMs=null;lastRecordingDurationMs=null;lastRecordingFrameStats=null;flowTraceSteps=[];lastVisualSettledAtMs=0;simRouteHint=null;lastFailedStep=null;get simId(){return this.opts.simId}setSimRouteHint(e){this.simRouteHint=this.normalizeSimRoute(e)}normalizeSimRoute(e){if(!e)return null;try{let t=new URL(e);t.searchParams.delete("inspectOpen");let r=t.searchParams.toString();return`${t.origin}${t.pathname}${r?`?${r}`:""}`}catch{return e}}async refreshSimId(){if(this.opts.simId)try{let e=await this.bridge.listSims(),t=e.find(l=>l.id===this.opts.simId);if(t&&(this.simRouteHint=this.normalizeSimRoute(t.url||t.origin)),e.find(l=>l.id===this.opts.simId&&l.readyState==="open")||!this.simRouteHint)return;let i=this.simRouteHint&&e.find(l=>l.readyState==="open"&&this.normalizeSimRoute(l.url||l.origin)===this.simRouteHint);if(!i)return;let o=e.find(l=>l.isPrimary&&l.readyState==="open"),a=e.find(l=>l.readyState==="open"),s=i??o??a;s&&(this.opts.simId=s.id,console.log(` [flow] sim rotated to ${s.id}`))}catch{}}async evaluate(e,t){return this.bridge.send({type:"evaluate",simId:this.opts.simId,code:e},t?{timeoutMs:t}:void 0)}async callTest(e,...t){return this.bridge.send({type:"call",simId:this.opts.simId,path:`__sootsimTest.${e}`,args:t})}async perform(e){return this.bridge.send({type:"perform",simId:this.opts.simId,steps:e})}async waitForTree(e=Q){let t=Date.now()+K(e),r=Date.now(),i=null,o=0,a=0,s=-1,l=r;for(;Date.now()<t;){try{let u=await this.evaluate(He,8e3);if(o=0,u?.externalError)throw new Error(`app failed to load: ${u.externalError}`);if(u){let m=Date.now();u.nodes!==s&&(s=u.nodes,l=m);let b=u.flag===!0&&je(u),g=u.flag!==!0&&Ve(u);if((b||g)&&u.externalReady!==!1&&!u.externalError&&!u.loadingText&&m-l>=Ue)return}}catch(u){if(i=u instanceof Error?u:new Error(String(u)),i.message.startsWith("app failed to load:"))throw i;if(o++,o>=4)throw new Error(`target sim is not responding to the bridge (${i.message}). it is likely a stale orphan \u2014 run \`rnx list\`, then close it with \`rnx close <id>\` or start a fresh one with \`rnx open --new <port>\`.`);await this.refreshSimId()}let p=Date.now()-r;p-a>=5e3&&(a=p,console.log(` [flow] waiting for app to be ready\u2026 (${Math.round(p/1e3)}s)`)),await f(We)}throw i?.message.startsWith("app failed to load:")?i:new Error(`app not ready after ${e}ms`)}async ensureRecordingStarted(){if(!this.opts.recordingOutputDir)throw new Error("recording output directory not configured");this.recordingAccessChecked||(this.opts.requireRecordingEntitlement&&await st("flow --video",{originOverride:this.opts.billingOriginOverride,allowGitHubAuth:this.opts.allowGitHubRecording}),this.recordingAccessChecked=!0);let e=Date.now(),t=await this.evaluate(`(() => {
216
- const rec = window.__sootsimRecorder
217
- if (!rec) return { ok: false, error: 'recorder unavailable on this page' }
218
- const format = ${JSON.stringify(this.opts.recordingFormat??"webm")}
219
- if (rec.state() === 'recording') return { ok: true, format }
220
- return rec.start({ format, fps: 24 })
221
- })()`);if(!t?.ok)throw new Error(t?.error||"recording unavailable on this page");this.recordingStartedAtMs||(this.recordingStartedAtMs=typeof t.startedAtMs=="number"&&Number.isFinite(t.startedAtMs)?t.startedAtMs:e)}async startRecording(){this.recordingEnabled=!0,await this.ensureRecordingStarted()}prepareRecording(){this.recordingEnabled=!0}getLastRecordingDurationMs(){return this.lastRecordingDurationMs}getLastRecordingStartedAtMs(){return this.lastRecordingStartedAtMs}getLastRecordingFrameStats(){return this.lastRecordingFrameStats}getFlowTraceSteps(){return[...this.flowTraceSteps]}flowStepTargetLabel(e,t){if(t==="inputText"||t==="runScript"||t==="evalScript")return;let r=e[t];if(typeof r=="string")return r.slice(0,80);if(typeof r=="number"||typeof r=="boolean")return String(r);if(!r||typeof r!="object")return;let i=r,o=i.id??i.text??i.name??i.path;if(typeof o=="string"&&o)return o.slice(0,80);let a=i.visible??i.notVisible;if(typeof a=="string"&&a)return a.slice(0,80);if(a&&typeof a=="object"){let s=a,l=s.id??s.text;if(typeof l=="string"&&l)return l.slice(0,80)}if(i.point&&typeof i.point=="string")return i.point.slice(0,80);if(typeof i.x=="number"&&typeof i.y=="number")return`${Math.round(i.x)}, ${Math.round(i.y)}`}recordFlowTraceStep(e){let t=Date.now(),r={stepIndex:e.stepIndex,stepName:e.stepName,...e.targetLabel?{targetLabel:e.targetLabel}:{},startedAtMs:e.startedAtMs,endedAtMs:t,durationMs:Math.max(0,t-e.startedAtMs),status:e.status};e.error!=null&&(r.error=e.error instanceof Error?e.error.message:String(e.error)),e.screenshotPath&&(r.screenshotPath=e.screenshotPath),this.flowTraceSteps.push(r)}async stopRecording(){if(!this.recordingEnabled||!this.opts.recordingOutputDir)return null;this.recordingEnabled=!1;let e=Date.now(),t=await this.evaluate("window.__sootsimRecorder.stop()");if(!t?.ok)throw this.recordingStartedAtMs=null,this.lastRecordingFrameStats=null,new Error(t?.error||"recording stop failed");this.lastRecordingStartedAtMs=this.recordingStartedAtMs,this.lastRecordingDurationMs=this.recordingStartedAtMs?Math.max(1,e-this.recordingStartedAtMs):null,this.lastRecordingFrameStats=t.frameStats??null,this.recordingStartedAtMs=null;let r=[],i=0;for(;;){let l=await this.evaluate(`window.__sootsimRecorder.getBlobBase64({ offset: ${i}, chunk: 2097152 })`);if(!l||(r.push(Buffer.from(l.data,"base64")),i=l.offset,l.done))break}if(r.length===0)throw new Error("recording requested but no video buffer was produced");x.mkdirSync(this.opts.recordingOutputDir,{recursive:!0});let a=(t.mime||this.opts.recordingFormat||"video/webm").includes("mp4")?"mp4":"webm",s=S.join(this.opts.recordingOutputDir,`sootsim-${Date.now()}.${a}`);return x.writeFileSync(s,Buffer.concat(r)),s}async waitForRecordingTail(e){if(!this.recordingEnabled)return;let t=Math.max(0,Math.round(e.maxMs));if(t<=0)return;if(!e.smart){await f(t);return}let r=await ye({bridge:this.bridge,simId:this.opts.simId,maxMs:t,pollMs:80,stablePolls:6,strict:!0});await this.waitForVisualSettle(),console.log(r.settled?` [flow] recording tail settled in ${r.elapsed}ms`:` [flow] recording tail reached ${r.elapsed}ms budget`)}async findElement(e){if(e.childOf!=null||typeof e.index=="number")return this.findElementScoped(e);let t=!!e.text&&/[.*+?^$()[\]{}|\\]/.test(e.text);return this.evaluate(`(async () => {
222
- const test = window.__sootsimTest
223
- if (!test) return null
224
- let node = null
225
- if (${JSON.stringify(!!e.text)}) {
226
- node = await test.findByText(${JSON.stringify(e.text||"")})
227
- // maestro matches a text selector against the element's ACCESSIBILITY
228
- // text too, not just rendered glyphs \u2014 icon-only buttons (e.g. bluesky's
229
- // "Pin to Home" / "Mute accounts" pin/menu controls) carry the label on
230
- // accessibilityLabel with no visible text node, so findByText misses
231
- // them. fall back to an exact a11y-label match, mirroring the real
232
- // driver. findByLabel resolves a node, but its info shape omits nodeId/
233
- // isTextInput; re-resolve through findByTestId/findById when it exposes
234
- // an id so tapOn still gets a resolveTapTarget-able nodeId.
235
- if (!node) {
236
- const labelled = await test.findByLabel?.(${JSON.stringify(e.text||"")})
237
- if (labelled) {
238
- const reId = labelled.testID || labelled.id
239
- node =
240
- (reId &&
241
- ((await test.findByTestId?.(reId)) || (await test.findById?.(reId)))) ||
242
- labelled
243
- }
244
- }
245
- if (!node && ${JSON.stringify(t)} && test.queryAll) {
246
- // regex selector fallback: match the pattern against each visible
247
- // node's text; prefer the narrowest matching node so a tight <text>
248
- // wins over a wide container that merely contains it.
249
- let re = null
250
- try { re = new RegExp(${JSON.stringify(e.text||"")}) } catch (e) { re = null }
251
- if (re) {
252
- const all = (await test.queryAll({ pruneHidden: true })) || []
253
- const hits = all.filter(
254
- (n) =>
255
- n && n.absolutePosition && n.layout &&
256
- typeof n.text === 'string' && re.test(n.text),
257
- )
258
- hits.sort((a, b) => (a.text || '').length - (b.text || '').length)
259
- if (hits[0]) node = hits[0]
260
- }
261
- }
262
- }
263
- if (!node && ${JSON.stringify(!!e.id)}) {
264
- node = (await test.findByTestId(${JSON.stringify(e.id||"")})) || (await test.findById(${JSON.stringify(e.id||"")}))
265
- }
266
- if (!node || !node.absolutePosition || !node.layout) return null
267
- return {
268
- nodeId: typeof node.nodeId === 'number' ? node.nodeId : null,
269
- id: node.id || null,
270
- testID: node.testID || null,
271
- text: node.text || null,
272
- absolutePosition: node.absolutePosition,
273
- layout: node.layout,
274
- isTextInput: !!node.isTextInput,
275
- }
276
- })()`)}async findElementScoped(e){let t=typeof e.index=="number"?e.index:0;return this.evaluate(`(async () => {
277
- const test = window.__sootsimTest
278
- if (!test || !test.queryAll) return null
279
- // NOT pruneHidden: that over-filters (it dropped every postDropdownBtn in a
280
- // feed and made index:0 resolve to nothing \u2014 worse than findByTestId). reach
281
- // for the same set findByTestId sees, then PREFER on-screen ones below.
282
- const filter = {}
283
- if (${JSON.stringify(!!e.id)}) filter.hasId = ${JSON.stringify(e.id||"")}
284
- if (${JSON.stringify(!!e.text)}) filter.hasText = ${JSON.stringify(e.text||"")}
285
- let candidates = (await test.queryAll(filter)) || []
286
- // a11y-label fallback (icon-only buttons) for text matchers, mirroring
287
- // findElement's simple path.
288
- if (${JSON.stringify(!!e.text)} && candidates.length === 0) {
289
- const all = (await test.queryAll({})) || []
290
- candidates = all.filter((n) => (n.accessibilityLabel || '') === ${JSON.stringify(e.text||"")})
291
- }
292
- candidates = candidates.filter((n) => n && n.absolutePosition && n.layout)
293
- // prefer on-screen matches (findByTestId's visible-first behavior); only
294
- // fall back to off-screen ones when nothing is on-screen, so index: still
295
- // resolves a target that needs scrolling into view.
296
- const onScreen = candidates.filter((n) => {
297
- const cy = n.absolutePosition.y + n.layout.height / 2
298
- return cy > 0 && cy < ${N}
299
- })
300
- if (onScreen.length > 0) candidates = onScreen
301
- ${e.childOf?`
302
- const container = ${e.childOf.id?`(await test.findByTestId(${JSON.stringify(e.childOf.id)})) || (await test.findById(${JSON.stringify(e.childOf.id)}))`:`await test.findByText(${JSON.stringify(e.childOf.text||"")})`}
303
- if (!container || !container.absolutePosition || !container.layout) return null
304
- const x0 = container.absolutePosition.x
305
- const y0 = container.absolutePosition.y
306
- const x1 = x0 + container.layout.width
307
- const y1 = y0 + container.layout.height
308
- candidates = candidates.filter((n) => {
309
- const cx = n.absolutePosition.x + n.layout.width / 2
310
- const cy = n.absolutePosition.y + n.layout.height / 2
311
- return cx >= x0 && cx <= x1 && cy >= y0 && cy <= y1
312
- })`:""}
313
- const node = candidates[${t}]
314
- if (!node) return null
315
- return {
316
- nodeId: typeof node.nodeId === 'number' ? node.nodeId : null,
317
- id: node.id || null,
318
- testID: node.testID || null,
319
- text: node.text || null,
320
- absolutePosition: node.absolutePosition,
321
- layout: node.layout,
322
- isTextInput: !!node.isTextInput,
323
- }
324
- })()`)}async resolveTapTarget(e){return this.evaluate(`(async () => {
325
- const test = window.__sootsimTest
326
- if (!test?.resolveTapTarget) return null
327
- return await test.resolveTapTarget(${e})
328
- })()`)}async activatePressTarget(e){let t=e.id?{id:e.id,testID:e.id,text:null}:{id:null,testID:null,text:e.text??null};return this.evaluate(`(async () => {
329
- const test = window.__sootsimTest
330
- if (!test) return null
331
- const node = ${e.id?`(await test.findByTestId?.(${JSON.stringify(e.id)})) || (await test.findById?.(${JSON.stringify(e.id)}))`:`await test.findByText?.(${JSON.stringify(e.text||"")})`}
332
- let point = null
333
- if (node?.absolutePosition && node?.layout) {
334
- point = {
335
- x: node.absolutePosition.x + node.layout.width / 2,
336
- y: node.absolutePosition.y + node.layout.height / 2,
337
- }
338
- if (typeof node.nodeId === 'number' && test.resolveTapTarget) {
339
- const resolved = await test.resolveTapTarget(node.nodeId)
340
- if (
341
- resolved &&
342
- Number.isFinite(resolved.cx) &&
343
- Number.isFinite(resolved.cy)
344
- ) {
345
- point = { x: resolved.cx, y: resolved.cy }
346
- }
347
- }
348
- }
349
- ${e.id?`const direct = await test.activatePressById?.(${JSON.stringify(e.id)})`:`const direct = await test.activatePressByText?.(${JSON.stringify(e.text||"")})`}
350
- if (direct?.ok && point) {
351
- window.dispatchEvent(
352
- new CustomEvent('sootsim:agentAction', {
353
- detail: { type: 'tap', x: point.x, y: point.y, target: ${JSON.stringify(t)} },
354
- }),
355
- )
356
- }
357
- return direct || null
358
- })()`)}async activatePressAt(e,t){return this.evaluate(`(async () => {
359
- const test = window.__sootsimTest
360
- if (!test?.activatePressAt) return null
361
- const direct = await test.activatePressAt(${e}, ${t})
362
- if (direct?.ok) {
363
- window.dispatchEvent(
364
- new CustomEvent('sootsim:agentAction', {
365
- detail: { type: 'tap', x: ${e}, y: ${t} },
366
- }),
367
- )
368
- }
369
- return direct
370
- })()`)}async tap(e,t,r){return await this.bridge.send({type:"tap",simId:this.opts.simId,x:e,y:t,target:r})}async longPress(e,t,r,i){return await this.bridge.send({type:"longPress",simId:this.opts.simId,x:e,y:t,durationMs:r,target:i})}async waitForElement(e,t=5e3){let r=Date.now()+t,i=await this.findElement(e);for(;!i&&Date.now()<r;)await f(150),i=await this.findElement(e);if(!i)return i;let o=Date.now()+1200,a=i;for(;Date.now()<o;){await f(120);let s=await this.findElement(e);if(!s)break;let l=Math.abs(s.absolutePosition.x-a.absolutePosition.x)>.5||Math.abs(s.absolutePosition.y-a.absolutePosition.y)>.5||Math.abs(s.layout.width-a.layout.width)>.5||Math.abs(s.layout.height-a.layout.height)>.5;if(i=s,!l)return i;a=s}return i}replayTargetForElement(e,t,r){return{id:e.id??r?.target?.id??t.id??null,testID:e.id??r?.target?.testID??t.testID??null,text:e.text??r?.target?.text??r?.target?.accessibilityLabel??t.text??t.accessibilityLabel??null,type:r?.target?.type??t.type??null}}async resolveInteractionPoint(e){if(e.point&&!e.id&&!e.text&&e.index===void 0&&!e.childOf)return{...ee(e.point),element:null,target:void 0};let t=await this.waitForElement(e);if(!t)return null;let r=typeof t.nodeId=="number"?await this.resolveTapTarget(t.nodeId):null,i=this.replayTargetForElement(e,t,r);return e.point?{...ee(e.point,{x:t.absolutePosition.x,y:t.absolutePosition.y,width:t.layout.width,height:t.layout.height}),element:t,target:i}:{x:r?.cx??t.absolutePosition.x+t.layout.width/2,y:r?.cy??t.absolutePosition.y+t.layout.height/2,element:t,target:i}}async tapOn(e){let t=typeof e=="string"?{text:e}:e;if(t.point){let o=await this.resolveInteractionPoint(t);if(!o)throw new Error(`tapOn: element not found: ${JSON.stringify(t)}`);(await this.activatePressAt(o.x,o.y))?.ok||await this.tap(o.x,o.y,o.target),await f(300);return}let r=await this.waitForElement(t);if(r){let o=r.isTextInput?4:1;for(let a=0;a<o;a++){let s=a===0?r:await this.findElement({text:t.text,id:t.id});if(!s)break;let l=typeof s.nodeId=="number"?await this.resolveTapTarget(s.nodeId):null,p=l?.cx??s.absolutePosition.x+s.layout.width/2,u=l?.cy??s.absolutePosition.y+s.layout.height/2;if((await this.tap(p,u,this.replayTargetForElement(t,s,l)))?.hit===!0){if(await f(300),!s.isTextInput||await this.waitForFocusedTextInput(600,s))return;continue}break}}if((await this.activatePressTarget(t))?.ok){await f(300);return}throw new Error(`tapOn: element not found: ${JSON.stringify(t)}`)}async longPressOn(e){let t=typeof e=="string"?{text:e}:e,r=await this.resolveInteractionPoint(t);if(!r)throw new Error(`longPressOn: element not found: ${JSON.stringify(t)}`);let i=await this.longPress(r.x,r.y,3e3,r.target);if(i?.ok===!1||i?.value===!1)throw new Error(`longPressOn: long press missed: ${JSON.stringify(t)}`);await f(300)}async tapAtCoords(e,t){await this.tap(e,t),await f(300)}async doubleTapAtCoords(e,t,r=80){let i=await this.perform([{type:"doubleTap",x:e,y:t,gapMs:Math.max(0,Math.round(r))}]);if(!i?.ok)throw new Error(`doubleTapAtCoords failed at (${e}, ${t}): ${i?.error??"double tap missed"}`);await f(300)}async assertVisible(e){let t=typeof e=="string"?{text:e}:e;for(let o=0;o<15;o++){if(await this.isElementVisible(t))return;await f(200)}let r=await this.findElement(t),i=r?` (matched node at y=${Math.round(r.absolutePosition.y)} h=${Math.round(r.layout.height)} \u2014 off-screen)`:" (no matching node in tree)";throw new Error(`assertVisible: ${JSON.stringify(t)} not visible${i}`)}async assertNotVisible(e){let t=typeof e=="string"?{text:e}:e;if(await this.isElementVisible(t)){let r=await this.findElement(t),i=r?` at (${Math.round(r.absolutePosition.x)},${Math.round(r.absolutePosition.y)})`:"";throw new Error(`assertNotVisible: ${JSON.stringify(t)} IS visible${i}`)}}async isElementVisible(e){let t=await this.findElement(e);return!!(t&&t.absolutePosition.y+t.layout.height>0&&t.absolutePosition.y<N)}async inputText(e){if(!await this.waitForFocusedTextInput())throw new Error("inputText: no focused TextInput; tap the input and wait for focus before typing");await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"type",text:e}),await f(200)}focusedTextInputMatches(e,t){if(!t||typeof t.nodeId=="number"&&typeof e.nodeId=="number"&&t.nodeId===e.nodeId)return!0;let r=t.testID??null,i=e.testID??null;if(r&&i&&r===i)return!0;let o=t.id??null,a=e.id??null;return!!(o&&a&&o===a)}async waitForFocusedTextInput(e=1500,t){let r=Date.now()+e;for(;Date.now()<r;){try{let i=await this.callTest("getFocusedNode");if(i&&this.focusedTextInputMatches(i,t))return!0}catch{}await f(50)}return!1}async pressKey(e){await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"press",text:e}),await f(120)}async dispatchKey(e){await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"dispatchKey",text:e}),await f(120)}async hideKeyboard(){try{await this.callTest("blurFocusedTextInput")}catch{}await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"dismiss"});let e=Date.now()+3e3;for(;Date.now()<e;){let t=await this.evaluate(`(() => {
371
- const keyboard =
372
- window.__sootsimKeyboard ??
373
- window.SootSim?.bridges?.keyboard ??
374
- null
375
- const test = window.__sootsimTest
376
- return {
377
- visible: !!keyboard?.isVisible?.(),
378
- focused: !!test?.isTextInputFocused?.(),
379
- }
380
- })()`);if(!t?.visible&&!t?.focused){await f(80);return}await f(80)}}async eraseText(e){for(let t=0;t<e;t++)await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"dispatchKey",text:"Backspace"});await f(100)}async waitFor(e){let t=Date.now()+K(e.timeout||Q);for(;Date.now()<t;){if(await this.findElement(e))return;await f(200)}let r=await this.findElement(e),i=r?` (matched node y=${Math.round(r.absolutePosition.y)} \u2014 still off-screen at deadline)`:"";throw new Error(`waitFor: ${JSON.stringify(e)} not found after ${e.timeout||Q}ms${i}`)}async takeScreenshot(e){if(!this.hasFreshVisualSettle())try{await this.waitForVisualSettle(),await f(250)}catch{}let t=Jt(e),r=Vt(this.opts.screenshotDir,t.path,{mode:this.opts.screenshotPathMode??"dir",flowDir:this.opts.flowDir});x.mkdirSync(S.dirname(r),{recursive:!0});let i=t.layers??this.opts.screenshotLayers,o={type:"screenshot",simId:this.opts.simId};i&&i!=="full"&&(o.layers=i);let s=(await this.bridge.send(o)).replace(/^data:image\/png;base64,/,""),l=Buffer.from(s,"base64");if(t.withFrame){let p=await this.readCurrentDeviceModel();if(!p)throw new Error("could not read current device model for framed screenshot");let u=await dt(l,p);return x.writeFileSync(r,u),console.log(`[flow] screenshot: ${r} (frame: ${p})`),r}return x.writeFileSync(r,l),console.log(`[flow] screenshot: ${r}`),r}async readCurrentDeviceModel(){let e=await this.bridge.send({type:"call",simId:this.opts.simId,path:"SootSim.bridges.settings.get",args:[]}),t=e&&typeof e.deviceModel=="string"?e.deviceModel:null;return!t||!(t in _e)?null:t}async captureScreenshot(e){x.mkdirSync(S.dirname(e),{recursive:!0});let r=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");x.writeFileSync(e,Buffer.from(r,"base64"))}async captureFailureBundle(e,t){x.mkdirSync(e,{recursive:!0});let r=(u,m)=>{try{x.writeFileSync(S.join(e,u),m)}catch{}},i=async u=>{try{return await this.bridge.send({type:"evaluate",simId:this.opts.simId,code:u})}catch{return null}},o=await i(`(async () => {
381
- const out = {
382
- simId: window.__sootsimBridge?.id ?? window.SootSim?.state?.simId ?? null,
383
- url: location.href,
384
- title: document.title,
385
- hidden: document.hidden,
386
- }
387
- try {
388
- const params = new URL(location.href).searchParams
389
- const bundle = params.get('bundle')
390
- if (bundle) {
391
- const baseMatch = bundle.match(/^https?:\\/\\/[^/]+/)
392
- if (baseMatch) {
393
- const res = await fetch(baseMatch[0] + '/', {
394
- headers: { 'expo-platform': 'ios' },
395
- cache: 'no-store',
396
- })
397
- if (res.ok) {
398
- out.manifest = await res.json().catch(() => null)
399
- }
400
- }
401
- }
402
- } catch {}
403
- return out
404
- })()`);r("error.json",JSON.stringify({message:t.error.message,stack:t.error.stack,stepIndex:t.stepIndex,stepKind:t.stepKind,stepTarget:t.stepTarget,capturedAt:new Date().toISOString(),sim:o??null},null,2));try{let m=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");r("screenshot.png",Buffer.from(m,"base64"))}catch{}let a=await i(`(async () => {
405
- const t = window.__sootsimTest
406
- const mainShell = window.SootSim?.bridges?.mainShell
407
- if (!t) return { error: 'no test bridge' }
408
- let shell = null
409
- try {
410
- shell = typeof mainShell?.getState === 'function' ? await mainShell.getState() : null
411
- } catch {}
412
- const all = await t.queryAll({ pruneHidden: true })
413
- return { shell, nodes: all, url: location.href, title: document.title }
414
- })()`);a&&r("describe.json",JSON.stringify(a,null,2));let s=await i("(async () => await window.__sootsimTest?.dumpAccessibilityTree?.(20))()");typeof s=="string"&&r("a11y.txt",s);let l=await i("(async () => await window.__sootsimTest?.dumpTree?.(15))()");typeof l=="string"&&r("tree.txt",l);let p=await i(`(() => {
415
- const c = window.__sootsimConsole
416
- return {
417
- errors: c?.getErrors?.() ?? [],
418
- warnings: c?.getWarnings?.() ?? [],
419
- requests: (window.__sootsimGetFailedRequests?.() ?? []),
420
- }
421
- })()`);return p&&r("console.json",JSON.stringify(p,null,2)),e}async swipe(e="UP",t=300){let r=te/2,i=N/2,o=200,a=r,s=i,l=r,p=i;switch(e.toUpperCase()){case"UP":s+=o,p-=o;break;case"DOWN":s-=o,p+=o;break;case"LEFT":a+=o,l-=o;break;case"RIGHT":a-=o,l+=o;break}let u=Math.max(10,Math.round(t/16));await this.drag(a,s,l,p,u,16)}async drag(e,t,r,i,o=12,a=16){let s=await this.perform([{type:"drag",fromX:e,fromY:t,toX:r,toY:i,steps:Math.max(1,Math.round(o)),stepMs:Math.max(0,Math.round(a))}]);if(!s?.ok)throw new Error(`drag failed: ${s?.error??"drag missed"}`);await f(300)}async swipeCoords(e,t,r=300){let i=ee(e),o=ee(t),a=Math.max(10,Math.round(r/16));await this.drag(i.x,i.y,o.x,o.y,a,16)}async swipeFrom(e,t="UP",r=300){let i=await this.findElement(e);if(!i)throw new Error(`swipeFrom: element not found: ${JSON.stringify(e)}`);let o=i.absolutePosition.x+i.layout.width/2,a=i.absolutePosition.y+i.layout.height/2,s=180,l=o,p=a;switch(t.toUpperCase()){case"UP":p-=s;break;case"DOWN":p+=s;break;case"LEFT":l-=s;break;case"RIGHT":l+=s;break}let u=Math.max(10,Math.round(r/16));await this.drag(o,a,l,p,u,16)}async scrollTo(e,t,r){let i=await this.callTest("scrollTo",e,t,r,!1);if(!i?.ok)throw new Error(`scrollTo failed: ${i?.reason||"unknown error"}`);await f(250)}async pinch(e){let t=await this.perform([{type:"pinch",fromX1:e.from[0],fromY1:e.from[1],fromX2:e.from[2],fromY2:e.from[3],toX1:e.to[0],toY1:e.to[1],toX2:e.to[2],toY2:e.to[3],steps:e.steps||12,stepMs:e.stepMs||16}]);if(!t?.ok)throw new Error(`pinch failed: ${t?.error||"unknown error"}`);await f(250)}async dumpTree(e=6){let t=await this.bridge.send({type:"tree",simId:this.opts.simId,depth:e});return console.log("[flow] tree:"),console.log(typeof t=="string"?t:JSON.stringify(t,null,2)),typeof t=="string"?t:JSON.stringify(t)}async assertTreeContains(e){if(!(await this.dumpTree(8)).includes(e))throw new Error(`assertTreeContains: "${e}" not in tree`)}async waitForAnimationToEnd(e=2e3){let t=Math.max(0,Math.round(e));if(t<=0)return;(await ye({bridge:this.bridge,simId:this.opts.simId,maxMs:t,pollMs:32,stablePolls:2,strict:!0})).settled&&this.markVisualSettled()}async back(){try{await this.tapOn("\u2039")}catch{await this.tapOn("<")}}async scrollUntilVisible(e){let t=Date.now()+(e.timeout||15e3),r=e.direction?.toUpperCase()||"DOWN",i=r==="DOWN"?"UP":r==="UP"?"DOWN":r;for(;Date.now()<t;){let o=await this.findElement({text:e.element});if(o&&o.absolutePosition.y>=0&&o.absolutePosition.y+o.layout.height>0&&o.absolutePosition.y<N-50){if(e.centerElement){let a=N/2,s=o.absolutePosition.y-a;if(Math.abs(s)>100){let l=Math.min(150,Math.abs(s)*.5),p=s>0?a-l:a+l;await this.drag(te/2,a,te/2,p,10,16)}}return}await this.swipe(i,250),await f(500)}throw new Error(`scrollUntilVisible: "${e.element}" not found`)}async extendedWaitUntil(e){let t=Date.now()+K(e.timeout||Q);for(;Date.now()<t;){let r=e.visible?await this.isElementVisible(typeof e.visible=="string"?{text:e.visible}:e.visible):!0,i=e.notVisible?!await this.isElementVisible(typeof e.notVisible=="string"?{text:e.notVisible}:e.notVisible):!0;if(r&&i)return;await f(200)}throw new Error("extendedWaitUntil timed out")}async reloadGuestApp(){await this.evaluate("window.location.reload()").catch(()=>{}),await f(500),await this.refreshSimId()}async resetGuestAppData(){let e=await this.bridge.send({type:"reset",simId:this.opts.simId,resetOptions:{strategy:"data"}},{timeoutMs:12e4});if(!e.ok)throw new Error(e.error??"guest app data reset failed");if(!e.relaunched)throw new Error("guest app data reset did not relaunch the app");if(e.workerReloaded!==!0)throw new Error("guest app data reset did not replace the tenant worker")}async softReloadGuestApp(e){if(!await this.evaluate(Qe(e),12e4))throw new Error("guest app soft reload bridge unavailable")}async rearmCaptureAfterRuntimeReload(){if(!this.recordingEnabled&&!this.profilingEnabled)return;let e=Date.now()+1e4,t=null;for(;Date.now()<e;){await this.refreshSimId();try{this.recordingEnabled&&await this.ensureRecordingStarted(),this.profilingEnabled&&await this.startProfile();return}catch(r){t=r,await f(250)}}throw new Error(`capture re-arm failed after app reload: ${t instanceof Error?t.message:String(t)}`)}async launchApp(e){await this.refreshSimId(),e&&typeof e=="object"&&e.arguments&&console.log("[flow] launchApp.arguments ignored (rnx has no native process)");let t=!!(e&&typeof e=="object"&&e.clearState),r=Ut(e,"resetRuntime");if(!this.firstLaunchDone&&!t)this.firstLaunchDone=!0,r?(await this.launchShellAppFromHomeIfNeeded(e)&&await this.waitForTree(12e4),await this.softReloadGuestApp(!1),await this.waitForTree(12e4)):await this.launchShellAppFromHomeIfNeeded(e),await this.waitForTree(3e4);else if(this.firstLaunchDone=!0,t?await this.resetGuestAppData():await this.reloadGuestApp(),await this.waitForTree(12e4),this.opts.onAfterLaunch)try{await this.opts.onAfterLaunch()}catch(i){console.warn(` warn: onAfterLaunch hook threw: ${i instanceof Error?i.message:i}`)}this.profilingEnabled&&await this.startProfile(),this.recordingEnabled&&(await this.waitForVisualSettle(),await this.ensureRecordingStarted())}async waitForVisualSettle(){try{await this.evaluate(`new Promise((resolve) => {
422
- requestAnimationFrame(() => {
423
- requestAnimationFrame(() => {
424
- requestAnimationFrame(() => {
425
- setTimeout(resolve, 180)
426
- })
427
- })
428
- })
429
- })`),this.markVisualSettled()}catch{await f(180),this.markVisualSettled()}}markVisualSettled(){this.lastVisualSettledAtMs=Date.now()}hasFreshVisualSettle(){return Date.now()-this.lastVisualSettledAtMs<750}resolveShellLaunchAppId(e,t){if(typeof e=="string"&&e.length>0)return e;if(xe(e)){let r=q(e,"appId")||q(e,"id");if(r)return r}return Wt(t)||"connect"}async waitForShellAppLaunched(e,t){let r=Date.now()+t,i=null;for(;Date.now()<r;){try{i=await he(this.bridge)}catch{i=null}if(i?.state==="app"&&i.activeApp===e&&i.showSwitcher===!1&&typeof i.launchProgress=="number"&&i.launchProgress>=.98)return;await f(16)}}async launchShellAppFromHomeIfNeeded(e){let t=null;try{t=await he(this.bridge)}catch{return!1}if(t?.state!=="home"||t.activeApp!=null)return!1;let r=this.resolveShellLaunchAppId(e,t);return this.recordingEnabled&&await this.ensureRecordingStarted(),await Je(this.bridge,"launchApp",1e3,r),await this.waitForShellAppLaunched(r,1e3),!0}async startProfile(){let e=await this.evaluate(`(() => {
430
- if (!window.__sootsimShellPerf) {
431
- return { error: "shell frame profile unavailable (__sootsimShellPerf missing on the page)" }
432
- }
433
- window.__sootsimShellPerf.start()
434
- return { started: true }
435
- })()`);if(e?.error)throw new Error(e.error);this.profilingEnabled=!0}async stopProfile(){let e=await this.evaluate(`(async () => {
436
- if (!window.__sootsimShellPerf) {
437
- return { error: "shell frame profile unavailable (__sootsimShellPerf missing on the page)" }
438
- }
439
- return await window.__sootsimShellPerf.stop()
440
- })()`);if(this.profilingEnabled=!1,e?.error)throw new Error(e.error);return e}async stopApp(){await this.reloadGuestApp(),await this.rearmCaptureAfterRuntimeReload()}async clearState(){await this.resetGuestAppData(),await this.rearmCaptureAfterRuntimeReload()}clearKeychain(){console.warn("[flow] clearKeychain: rnx has no keychain surface \u2014 no-op (warning)")}async copyTextFrom(e){let t=typeof e=="string"?{id:e}:e,r=await this.findElement(t);if(!r)throw new Error(`copyTextFrom: element not found: ${JSON.stringify(t)}`);let i=r.text??r.testID??"";this.js.setCopiedText(i),this.js.putEnv("maestroCopiedText",i),console.log(`[flow] copied text: ${JSON.stringify(i)}`)}evalScript(e){let r=/(?<!\\)\$\{[^$]*\}/.test(e)?this.js.evaluateStringTemplate(e):this.js.evaluate(e);r!==void 0&&r!==""&&console.log("[flow] evalScript ->",r)}runScript(e){let t=typeof e=="string"?{file:e}:e;if(!t.file)throw new Error("runScript requires a file");let r=S.resolve(this.opts.flowDir,t.file),i=x.readFileSync(r,"utf8");this.js.evaluate(i,{env:t.env}),console.log(`[flow] runScript: ${t.file} done`)}async openLink(e){let t=typeof e=="string"?e:e.link;if(!t)throw new Error("openLink: missing link");let r=await this.callTest("openDeepLink",t);if(!r?.ok)throw new Error(`openLink failed: ${r?.error||"no test bridge"}`);await f(300)}async evaluateWhen(e){if(e.visible!==void 0){let t=typeof e.visible=="string"?{text:e.visible}:e.visible;return!!await this.findElement(t)}if(e.notVisible!==void 0){let t=typeof e.notVisible=="string"?{text:e.notVisible}:e.notVisible;return!await this.findElement(t)}return e.platform!==void 0?e.platform.toLowerCase()===this.js.maestro.platform.toLowerCase():e.true!==void 0?ut(e.true):!0}isOptional(e){if(e.optional===!0)return!0;let r=Object.entries(e).find(([o])=>o!=="when"&&o!=="optional"),i=r?r[1]:void 0;return!!(i&&typeof i=="object"&&"optional"in i&&i.optional)}async runStep(e,t){let r=typeof e=="string"?pt(e):e,i=Object.keys(r).find(l=>l!=="when")||Object.keys(r)[0];console.log(`[flow] step ${t+1}: ${i}`);let o=Date.now(),a=this.flowStepTargetLabel(r,i),s;try{s=this.js.interpolateStep(r),a=this.flowStepTargetLabel(s,i)??a}catch(l){if(this.isOptional(r)){console.log(`[flow] (optional, skipped: ${l.message.slice(0,80)})`),this.recordFlowTraceStep({stepIndex:t,stepName:i,targetLabel:a,startedAtMs:o,status:"skipped",error:l});return}throw this.lastFailedStep={index:t,kind:i,target:r[i]},this.recordFlowTraceStep({stepIndex:t,stepName:i,targetLabel:a,startedAtMs:o,status:"failure",error:l}),l}if(s.when&&!await this.evaluateWhen(s.when)){console.log("[flow] (when: predicate false, skipped)"),this.recordFlowTraceStep({stepIndex:t,stepName:i,targetLabel:a,startedAtMs:o,status:"skipped"});return}try{let l=!!(s.extendedWaitUntil||s.waitFor||s.scrollUntilVisible||s.launchApp||s.runFlow||s.runScript),p=1e4,u=this.runStepInner(s),m;if(l){let g=await u;typeof g=="string"&&(m=g)}else{let g=null,A=new Promise((k,H)=>{g=setTimeout(()=>{H(new Error(`step watchdog: ${i} made no progress in ${p}ms \u2014 bridge or bundle probably hung`))},p)});try{let k=await Promise.race([u,A]);typeof k=="string"&&(m=k)}finally{g&&clearTimeout(g)}}let b=!!(s.assertVisible||s.assertNotVisible||s.extendedWaitUntil||s.waitFor);this.stepDelay>0&&!b&&await f(this.stepDelay),this.recordFlowTraceStep({stepIndex:t,stepName:i,targetLabel:a,startedAtMs:o,status:"success",screenshotPath:m})}catch(l){if(this.isOptional(s)){console.log(`[flow] (optional, skipped: ${l.message.slice(0,80)})`),this.recordFlowTraceStep({stepIndex:t,stepName:i,targetLabel:a,startedAtMs:o,status:"skipped",error:l});return}throw this.lastFailedStep={index:t,kind:i,target:s[i]},this.recordFlowTraceStep({stepIndex:t,stepName:i,targetLabel:a,startedAtMs:o,status:"failure",error:l}),l}}async runStepInner(e){if(e.tapOn)await this.tapOn(e.tapOn);else if(e.longPressOn)await this.longPressOn(e.longPressOn);else if(e.scrollUntilVisible)await this.scrollUntilVisible(e.scrollUntilVisible);else if(e.extendedWaitUntil)await this.extendedWaitUntil(e.extendedWaitUntil);else if(e.assertVisible)await this.assertVisible(e.assertVisible);else if(e.assertNotVisible)await this.assertNotVisible(e.assertNotVisible);else if(e.inputText)await this.inputText(e.inputText);else if(e.pressKey)await this.pressKey(e.pressKey);else if(e.dispatchKey)await this.dispatchKey(e.dispatchKey);else if(e.waitFor)await this.waitFor(e.waitFor);else{if(e.takeScreenshot)return this.takeScreenshot(e.takeScreenshot);if(e.swipe)e.swipe.start&&e.swipe.end?await this.swipeCoords(e.swipe.start,e.swipe.end,e.swipe.duration):e.swipe.from?await this.swipeFrom(e.swipe.from,e.swipe.direction,e.swipe.duration):await this.swipe(e.swipe.direction,e.swipe.duration);else if(e.scroll)await this.swipe(e.scroll.direction==="DOWN"?"UP":"DOWN");else if(e.scrollTo){let t=typeof e.scrollTo.nodeId=="number"?{nodeId:e.scrollTo.nodeId}:e.scrollTo.id;if(!t)throw new Error("scrollTo requires id or nodeId");await this.scrollTo(t,e.scrollTo.x,e.scrollTo.y)}else if(e.pinch)await this.pinch(e.pinch);else if(e.waitForAnimationToEnd){let t=e.waitForAnimationToEnd;await this.waitForAnimationToEnd(typeof t=="number"?t:typeof t=="object"&&typeof t.timeout=="number"?t.timeout:2e3)}else if(e.back)await this.back();else if(e.hideKeyboard)await this.hideKeyboard();else if(e.launchApp)await this.launchApp(e.launchApp);else if(typeof e.wait=="number")await f(e.wait);else if(e.dumpTree)await this.dumpTree(e.dumpTree);else if(e.tapAtCoords)await this.tapAtCoords(e.tapAtCoords.x,e.tapAtCoords.y);else if(e.doubleTapAtCoords)await this.doubleTapAtCoords(e.doubleTapAtCoords.x,e.doubleTapAtCoords.y,e.doubleTapAtCoords.gapMs);else if(e.assertTreeContains)await this.assertTreeContains(e.assertTreeContains);else if(typeof e.eraseText=="number")await this.eraseText(e.eraseText);else if(e.repeat&&Array.isArray(e.repeat.commands)){let t=e.repeat.times,r=t==null||t===""?Number.MAX_SAFE_INTEGER:Number(t);if(!Number.isFinite(r))throw new Error(`repeat.times is not a number: ${t}`);let i=e.repeat.when??e.repeat.condition,o=async()=>i?this.evaluateWhen(i):!0,a=i?r:Math.min(r,1e3),s=0;for(;s<a&&await o();){for(let l=0;l<e.repeat.commands.length;l++)await this.runStep(e.repeat.commands[l],l);s++}}else if(e.stopApp!==void 0)await this.stopApp();else if(e.clearState!==void 0)await this.clearState();else if(e.clearKeychain!==void 0)this.clearKeychain();else if(e.copyTextFrom!==void 0)await this.copyTextFrom(e.copyTextFrom);else if(typeof e.evalScript=="string")this.evalScript(e.evalScript);else if(e.runScript){let t=e.runScript,r=typeof t=="string"?void 0:t.when;if(r&&!await this.evaluateWhen(r)){console.log("[flow] runScript skipped (when predicate false)");return}this.runScript(t)}else if(e.openLink!==void 0)await this.openLink(e.openLink);else if(e.runFlow){let t=e.runFlow,r=typeof t=="string"?t:t.file,i=typeof t=="string"?void 0:t.commands,o=typeof t=="string"?void 0:t.env,a=typeof t=="string"?void 0:t.when;if(a&&!await this.evaluateWhen(a)){console.log(`[flow] runFlow skipped (when predicate false): ${r??"inline commands"}`);return}if(!r&&!i)throw new Error("runFlow requires either file or commands");this.js.enterEnvScope();try{if(o)for(let[s,l]of Object.entries(o))this.js.putEnv(s,l);if(r){let s=S.resolve(this.opts.flowDir,r),l=x.readFileSync(s,"utf8"),p=this.opts.flowDir;this.opts.flowDir=S.dirname(s);try{await this.runFlow(Gt(l))}finally{this.opts.flowDir=p}}else if(i)for(let s=0;s<i.length;s++)await this.runStep(i[s],s)}finally{this.js.leaveEnvScope()}}else throw new Error(`unsupported flow step: ${JSON.stringify(e)}`)}}liveStatus=null;async runFlow(e){let t=[],r=[],i=[];for(let a of e){let s=Object.keys(a);if(s.length===1&&s[0]==="onFlowStart"&&Array.isArray(a.onFlowStart)){t.push(...a.onFlowStart);continue}if(s.length===1&&s[0]==="onFlowComplete"&&Array.isArray(a.onFlowComplete)){r.push(...a.onFlowComplete);continue}i.push(a)}if(this.liveStatus&&await this.liveStatus.plan(i.map((a,s)=>{let l=typeof a=="string"?pt(a):a,p=Object.keys(l).find(u=>u!=="when")??Object.keys(l)[0];return{index:s,name:p,target:this.flowStepTargetLabel(l,p)}})),t.length>0){console.log(`[flow] onFlowStart (${t.length} steps)`);for(let a=0;a<t.length;a++)await this.runStep(t[a],a)}let o=null;try{await this.runFlowBody(i)}catch(a){o=a instanceof Error?a:new Error(String(a))}if(r.length>0){console.log(`[flow] onFlowComplete (${r.length} steps)`);for(let a=0;a<r.length;a++)try{await this.runStep(r[a],a)}catch(s){console.warn(`[flow] onFlowComplete step ${a+1} failed: ${s instanceof Error?s.message:s}`)}}if(o)throw o}async runFlowBody(e){for(let t=0;t<e.length;t++){let r=e[t],i=typeof r.wait=="number"?r.wait:0,o=typeof r.waitFor?.timeout=="number"?r.waitFor.timeout:0,a=typeof r.extendedWaitUntil?.timeout=="number"?r.extendedWaitUntil.timeout:0,s=Math.max(6e4,i+15e3,K(o)+15e3,K(a)+15e3);this.liveStatus&&(await this.liveStatus.waitWhilePaused(),await this.liveStatus.step(t,"running"));let l=Date.now(),p=async(u,m)=>{if(!this.liveStatus)return;let b=this.flowTraceSteps[this.flowTraceSteps.length-1],g=b&&b.stepIndex===t&&b.startedAtMs>=l;await this.liveStatus.step(t,u?"failure":g&&b.status==="skipped"?"skipped":"success",{durationMs:Date.now()-l,error:u?m instanceof Error?m.message.slice(0,300):String(m).slice(0,300):g&&b.error||void 0})};try{r.runFlow||r.launchApp?await this.runStep(r,t):await Promise.race([this.runStep(r,t),new Promise((u,m)=>setTimeout(()=>m(new Error(`step ${t+1} (${Object.keys(r)[0]}) exceeded ${s}ms deadline`)),s))])}catch(u){let m=this.flowTraceSteps[this.flowTraceSteps.length-1];if(!(m&&m.stepIndex===t&&m.startedAtMs>=l)){let b=Object.keys(r)[0];this.lastFailedStep={index:t,kind:b,target:r[b]},this.recordFlowTraceStep({stepIndex:t,stepName:b,targetLabel:this.flowStepTargetLabel(r,b),startedAtMs:l,status:"failure",error:u})}throw await p(!0,u),u}await p(!1)}}};function Kt(n){if(typeof n!="object"||n==null||!("control"in n))return!1;let e=n.control;return typeof e=="object"&&e!=null&&"paused"in e&&e.paused===!0}var ie=class{constructor(e,t,r){this.bridge=e;this.flowName=t;this.getSimId=r}disabled=!1;paused=!1;lastSimId;plannedSteps=null;completedSteps=new Map;runId=`flr_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`;async send(e,t){let r=await this.bridge.send({type:"flowStatus",simId:t,status:{runId:this.runId,flowName:this.flowName,...e}});this.paused=Kt(r)}async push(e){if(!this.disabled)try{let t=this.getSimId?.();if(t!==this.lastSimId&&this.lastSimId!=null&&this.plannedSteps&&e.phase!=="plan"){await this.send({phase:"plan",state:"running",steps:this.plannedSteps},t);for(let r of this.completedSteps.values())await this.send({phase:"step",state:"running",step:r},t)}this.lastSimId=t,await this.send(e,t)}catch(t){this.disabled=!0,console.log(`[flow] live status unavailable (${t instanceof Error?t.message.slice(0,120):t}) \u2014 continuing without the devtools rail`)}}async plan(e){this.plannedSteps=e.map(t=>({...t})),this.completedSteps.clear(),await this.push({phase:"plan",state:"running",steps:e})}async step(e,t,r){let i={index:e,status:t,...r};await this.push({phase:"step",state:"running",step:i}),this.completedSteps.set(e,i)}async end(e){await this.push({phase:"end",state:e})}async waitWhilePaused(){if(!this.disabled)for(;this.paused;){for(console.log("[flow] paused from devtools \u2014 waiting\u2026");this.paused&&!this.disabled;)await new Promise(e=>setTimeout(e,400)),await this.push({phase:"heartbeat",state:"paused"});this.disabled||console.log("[flow] resumed")}}};var Te=null;function Hr(){return Te}var Ee=[];function Ur(){return Ee}async function zt(n){if(!n)return{target:""};let e=n.trim();if(!e)return{target:""};if(/^\d+$/.test(e))return{target:e};if(e.startsWith("http://")||e.startsWith("https://"))return{target:e};let r=(await Ce()).find(i=>i.name.toLowerCase()===e.toLowerCase());return r?{target:String(r.preferredPort),runtimeConfig:r.runtimeConfig}:{target:e}}async function Xt(){let n=await Ne(),e=n.find(r=>r.patched);if(e)return`http://localhost:${e.port}/__soot/`;let t=n[0];return t?`http://localhost:${t.port}/__soot/`:null}async function ft(n){Te=null,Ee=[],(n.length===0||n.includes("--help")||n.includes("-h"))&&(console.log(`
441
- sootsim maestro \u2014 author and run Maestro YAML flows
442
-
443
- usage:
444
- sootsim maestro test <flow.yaml> [options]
445
- sootsim maestro start
446
- sootsim maestro keep
447
- sootsim maestro end [--output <path>] [--validate] [--video]
448
- sootsim maestro validate <path>
449
-
450
- options:
451
- --record record a webm artifact while the flow runs
452
- --profile capture perf stats while the flow runs
453
- --out <dir> output directory (default: /tmp/sootsim-recordings)
454
- --device <model> override the flow frontmatter device for this run
455
- --slow <ms> delay between steps for natural pacing
456
- --tail-wait <ms> hold the recording open after the last step so the
457
- final UI state is captured (default: smart idle up to
458
- 6000ms for --preview, fixed 2000ms for --record, 0 otherwise)
459
- --url <url> load this target before running the flow
460
- --screenshot-paths <mode>
461
- screenshot path mode: dir (default) or flow
462
- --no-shell capture every screenshot tenant-only (no status bar,
463
- keyboard, notification center, or other shell overlays).
464
- use for clean demo asset sets. per-step \`layers:\`
465
- still wins over this default.
466
- --shell-only inverse \u2014 capture shell chrome only
467
- --replace <m>=<f> replace a Metro module with a local file for this run
468
- --new open a fresh sim before running the flow
469
- --driver <id> when paired with --new, use playwright or electron;
470
- browser sims default to isolated playwright
471
- --headless pass headless=true to the launch driver (useful
472
- with --driver playwright)
473
- --headed force a fresh, VISIBLE window for this run (implies
474
- --new; overrides --headless). use when you want to
475
- watch the flow run live even if the current sim is
476
- headless or stale
477
- --electron prefer opening the target in the desktop companion
478
- --sim <id> target a specific current sim
479
- --validate replay the drafted flow before clearing it
480
- --video replay and record the drafted flow before clearing it
481
- --preview record events+video, upload, and print /preview/<id>
482
- --preview-open open the uploaded preview link after a successful run
483
- --preview-origin <url>
484
- upload target for --preview (default: auto)
485
- --preview-public-origin <url>
486
- public link origin for --preview (default: sootsim.com
487
- for prod uploads)
488
- --billing-kind test_run
489
- meter the chained preview upload as a test run
490
- --owner <org> associate preview upload with a linked org repo
491
- --repo <repo> repo name for --owner; user must belong to the team
492
-
493
- frontmatter (top of flow.yaml between --- markers):
494
- app: 8081 load this target before the flow starts
495
- device: iphone-14 set the live device model for this flow run
496
- electron: true prefer the desktop companion sim for this flow
497
-
498
- default runtime:
499
- bridge-backed flow playback against the current sim
500
- if no current sim exists, flow opens the discovered target first
501
- recording and profiling both run on the same bridge-backed path
502
-
503
- examples:
504
- sootsim maestro test login.yaml
505
- sootsim maestro test demo.yaml --url 8081 --record --slow 500 --out ./recordings
506
- sootsim maestro test demo.yaml --sim a2
507
- sootsim maestro start
508
- sootsim maestro keep
509
- sootsim maestro end --output ./.maestro/draft.yaml
510
- sootsim maestro end --output ./.maestro/draft.yaml --validate
511
- sootsim maestro end --output ./.maestro/draft.yaml --video
512
- sootsim maestro validate ./.maestro/draft.yaml
513
-
514
- flow extension:
515
- takeScreenshot: hero
516
- takeScreenshot:
517
- path: marketing/hero
518
- withFrame: true
519
- `),process.exit(0));let e=n[0];P.existsSync(e)||(console.error(` error: ${e} not found`),process.exit(1));let t=h=>n.find((d,y)=>n[y-1]===h),r=n.includes("--profile"),i=n.includes("--headed"),o=n.includes("--new")||i,a=t("--out")||"/tmp/sootsim-recordings",s=t("--screenshots")||(t("--out")?a:"/tmp/sootsim-flow"),l=t("--screenshot-paths")==="flow"?"flow":"dir",p=n.includes("--no-shell")?"tenant":n.includes("--shell-only")?"shell":void 0,u=t("--device")?.trim()||"",m=n.includes("--slow")?+(t("--slow")||"500"):0,b=n.includes("--electron"),g=n.includes("--preview"),A=g?await ot(t("--preview-origin")):"",k=t("--preview-public-origin"),H=n.includes("--preview-open"),Fe=t("--owner")?.trim()||"",Ie=t("--repo")?.trim()||"",U=t("--billing-kind")?.trim()||"",mt=g?`maestro:${process.env.GITHUB_RUN_ID?`github:${process.env.GITHUB_RUN_ID}:attempt:${process.env.GITHUB_RUN_ATTEMPT||"1"}:job:${process.env.GITHUB_JOB||"preview"}`:`local:${Yt()}`}:flow:${qt("sha256").update(w.relative(process.cwd(),w.resolve(e))).digest("hex").slice(0,16)}`:"";U&&U!=="test_run"&&(console.error(` error: invalid --billing-kind: ${U}`),process.exit(1));let gt=n.flatMap((h,d)=>n[d-1]==="--replace"?["--replace",h]:[]),wt=n.flatMap((h,d)=>n[d-1]==="--remap"?["--remap",h]:[]),_=n.includes("--record")||g,yt=n.includes("--tail-wait")?Math.max(0,+(t("--tail-wait")||"2000")):_?g?6e3:2e3:0,bt=P.readFileSync(e,"utf8"),{frontmatter:T,steps:D}=fe(bt);D.length===0&&(console.error(" error: flow file must contain a YAML array of steps"),process.exit(1));let W=u||T.device||"",Pe=T.theme||"",ne=b||T.electron===!0,St=T.app===void 0||T.app===null?"":typeof T.app=="number"?String(T.app):T.app,ke=await zt(St),oe=ke.target,$e={stripBooleanFlags:["--record","--profile","--electron","--new","--preview","--preview-open","--headless","--headed"],stripValueFlags:["--out","--device","--slow","--tail-wait","--url","--replace","--remap","--screenshots","--screenshot-paths","--preview-origin","--preview-public-origin","--driver","--billing-kind","--owner","--repo"]},v=ue(n,$e),vt=t("--url")||"";ne&&!Ke()&&(console.error(" error: desktop companion not found. install or build it first with `bun run build:electron`"),process.exit(1));let xt=ne?"desktop companion":"bridge",Tt=oe?` | target: ${oe}`:"";console.log(`
520
- sootsim maestro \u2014 ${w.basename(e)}
521
- ${D.length} steps | ${xt}${Tt}${_?" | recording":""}${r?" | profiling":""}${m?` | ${m}ms delay`:""}
522
- `);let $=vt||oe||"",se=o||ne&&v.simIdSource!=="flag",Ae=t("--driver")||"",ae=!1,le=new Set,Re=!1;if(!$&&!se&&v.simIdSource==="none"){let h=Le(v);try{let d=await h.listSims(),y=d.find(O=>O.isPrimary&&O.readyState==="open"),I=d.find(O=>O.readyState==="open"),J=y??I;J&&(Re=!0,console.log(` reusing active sim: ${J.id}`))}catch{}finally{h.close()}}if(!$&&!Re&&(se||v.simIdSource==="none")){let h=await Xt();h||(console.error(" error: no current sim and no sootsim target found"),process.exit(1)),$=h}if($&&W){let h=new URL(await Ye($,qe(v.wsPort)));h.searchParams.set("device",W),$=h.toString()}if($){let h=[$];if(h.push(...gt),h.push(...wt),se&&h.push("--new"),h.push("--no-describe"),v.simIdSource==="flag"&&v.simId&&h.push("--sim",v.simId),Ae&&(h.push("--driver",Ae),ae=!0),n.includes("--headless")&&!i&&h.push("--headless"),await Xe(h,{port:v.wsPort,timeoutMs:v.commandTimeoutMs,runtimeConfig:ke.runtimeConfig}),ae){let d=ce();d&&le.add(d)}}let B=ue(n,$e),z=B.simIdSource==="flag"?B.simId:ce()||B.simId,Et=B.simIdSource==="flag"?"flag":z?"saved":"none",E=pe(B.wsPort,{commandTimeoutMs:B.commandTimeoutMs,simId:z,simIdSource:Et}),c,Me=async()=>{let h=T.env?.SOOTSIM_STATUS_BAR_TIME;if(h){if(!/^(?:[1-9]|1[0-2]):[0-5][0-9]$/.test(h))throw new Error("SOOTSIM_STATUS_BAR_TIME must be a 12-hour time such as 9:41");await E.send({type:"evaluate",simId:c.simId,code:`window.dispatchEvent(new CustomEvent('sootsim:statusBarOverride', { detail: { time: ${JSON.stringify(h)} } }))`})}if(Pe&&await E.send({type:"call",simId:c.simId,path:"SootSim.bridges.settings.set",args:["colorScheme",Pe]}),!W)return!1;let d=await E.send({type:"evaluate",simId:c.simId,code:"window.location.href"});if(typeof d=="string"&&d.length>0){let y=new URL(d);y.searchParams.set("device",W),c.setSimRouteHint(y.toString())}return!!await E.send({type:"call",simId:c.simId,path:"SootSim.bridges.settings.set",args:["deviceModel",W]})};if(c=new re(E,{screenshotDir:s,flowDir:w.dirname(w.resolve(e)),screenshotPathMode:l,screenshotLayers:p,simId:z,recordingOutputDir:_?a:void 0,recordingFormat:g?"mp4":"webm",billingOriginOverride:g?A:void 0,allowGitHubRecording:g,requireRecordingEntitlement:g,onAfterLaunch:async()=>{await Me()&&await c.waitForTree(12e4),g&&await E.send({type:"evaluate",simId:c.simId,code:`(() => {
523
- const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
524
- return r?.start?.() ?? false
525
- })()`})}}),m&&(c.stepDelay=m),c.liveStatus=new ie(E,w.basename(e),()=>c.simId),c.js.putEnv("MAESTRO_FILENAME",w.basename(e,w.extname(e))),T.env&&typeof T.env=="object")for(let[h,d]of Object.entries(T.env))c.js.putEnv(h,d);let R=null,F=null,L=null,M=null,j=null,de=null,V=0,X=!!D[0]?.launchApp;try{X||await c.waitForTree(12e4),await Me()&&!X&&await c.waitForTree(12e4),g&&!X&&!process.env.SOOTSIM_PREVIEW_RESET_DONE&&await c.launchApp({clearState:!0}),_&&(X?c.prepareRecording():await c.startRecording()),r&&await c.startProfile(),g&&(await E.send({type:"evaluate",simId:c.simId,code:`(() => {
526
- const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
527
- return r?.start?.() ?? false
528
- })()`})||console.warn(" warn: eventRecorder.start() returned false \u2014 preview will upload bundle without replay events")),await c.runFlow(D),r&&(R=await c.stopProfile()),await c.waitForRecordingTail({maxMs:yt,smart:g}),_&&(F=await c.stopRecording(),L=c.getLastRecordingDurationMs()),g&&(M=await E.send({type:"evaluate",simId:c.simId,code:`(() => {
529
- const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
530
- return r?.stop?.() ?? []
531
- })()`}),console.log(` captured ${M.length} replay events`),j=w.join(s,"preview-final.png"),await c.captureScreenshot(j),console.log(` final screenshot: ${j}`));let d=D.filter(y=>y&&typeof y=="object"&&"takeScreenshot"in y).length;console.log(`
532
- + completed (${D.length} steps)`),d>0&&console.log(` screenshots: ${d} \u2192 ${s}`),R&&ht(R),F&&console.log(` video: ${F}`),console.log()}catch(h){if(r&&!R)try{R=await c.stopProfile()}catch{}if(_&&!F)try{F=await c.stopRecording(),L=c.getLastRecordingDurationMs()}catch(d){console.warn(` recording stop failed: ${d?.message||String(d)}`)}if(g&&!M)try{M=await E.send({type:"evaluate",simId:c.simId,code:`(() => {
533
- const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
534
- return r?.stop?.() ?? []
535
- })()`}),console.log(` captured ${M.length} partial replay events`)}catch(d){console.warn(` event recorder stop failed: ${d?.message||String(d)}`)}console.error(`
536
- x failed: ${h.message}
537
- `),R&&(console.log(" partial profile:"),ht(R)),F&&console.log(` partial video: ${F}`);try{let d=c.lastFailedStep,y=d?`step-${String(d.index+1).padStart(2,"0")}-${d.kind}`:"unstaged",I=w.join(s,y);await c.captureFailureBundle(I,{error:h,stepIndex:d?.index,stepKind:d?.kind,stepTarget:d?.target}),de=I,console.log(` failure bundle: ${I}`),console.log(" (contents: screenshot.png, describe.json, a11y.txt, tree.txt, console.json, error.json)")}catch(d){try{let y=w.join(s,"error.png");await c.captureScreenshot(y),console.log(` error screenshot: ${y}`)}catch{}console.log(` (failure bundle capture failed: ${d instanceof Error?d.message:String(d)})`)}await Ge(E,{errorsCommand:`sootsim get errors 5${c.simId?` --sim ${c.simId}`:""}`,warningsCommand:`sootsim get warnings 5${c.simId?` --sim ${c.simId}`:""}`,requestsCommand:`sootsim get requests 5${c.simId?` --sim ${c.simId}`:""}`}),V=1}if(await c.liveStatus?.end(V===0?"passed":"failed"),g&&(V===0||F||M))try{let h=await Qt(M??[]),d=["--origin",A,"--events",h];k&&d.push("--public-origin",k),F&&d.push("--video",F),j&&d.push("--screenshot",j),F&&L&&Number.isFinite(L)&&(d.push("--video-duration-ms",String(Math.round(L))),d.push("--recorded-duration-ms",String(Math.round(L))));let y=c.getLastRecordingStartedAtMs();y&&Number.isFinite(y)&&d.push("--recording-started-at-ms",String(Math.round(y))),v.wsPort&&d.push("--port",String(v.wsPort)),c.simId&&d.push("--sim",c.simId),H&&d.push("--open"),Fe&&d.push("--owner",Fe),Ie&&d.push("--repo",Ie),d.push("--run-scope",mt),U&&d.push("--billing-kind",U),console.log(`
538
- preparing preview upload\u2026`);let I=c.getFlowTraceSteps();I.length>0&&d.push("--timeline-events",await er(I));let J=await tr(I,y);J&&d.push("--snapshot-manifest",J),de&&d.push("--failure-bundle",de);let O=c.getLastRecordingFrameStats();O&&d.push("--trace-frame-stats",await rr(O));let{runUpload:Ft}=await import("./upload-QKJHFAX7.js");Te=await Ft(d,{})}catch(h){console.error(` preview upload failed: ${h?.message||h}`),V=1}return Ee=c.getFlowTraceSteps(),E.close(),ae?(c.simId&&le.add(c.simId),await Zt(v.wsPort,v.commandTimeoutMs,[...le])):c.simId&&c.simId!==z&&Be(c.simId),V}async function Zt(n,e,t){let r=[...new Set(t.filter(Boolean))];if(r.length===0)return;let i=pe(n,{commandTimeoutMs:e});try{let o=await i.listSims(),a=r.filter(l=>o.some(p=>p.id===l&&p.readyState==="open"));if(a.length===0)return;let s=await Ze(i,n,e,a);await ze(o,a),s.closed.length>0&&console.log(` closed flow sim(s): ${s.closed.join(", ")}`),s.remaining.length>0&&console.warn(` warn: flow sim(s) still connected after close: ${s.remaining.join(", ")}`)}catch(o){console.warn(` warn: failed to close flow sim(s): ${o instanceof Error?o.message:String(o)}`)}finally{i.close()}}async function Qt(n){let{gzipSync:e}=await import("zlib"),t=n.map(o=>JSON.stringify(o)).join(`
539
- `)+(n.length?`
540
- `:""),r=e(Buffer.from(t,"utf8")),i=w.join(Y(),`sootsim-events-${Date.now()}.jsonl.gz`);return P.writeFileSync(i,r),console.log(` events: ${n.length} written to ${i} (${r.length} bytes gz)`),i}async function er(n){let{gzipSync:e}=await import("zlib"),t=n.map((a,s)=>({schemaVersion:1,t:a.endedAtMs,seq:1e6+s,context:"host",kind:"flow-step",id:`flow-step-${a.stepIndex}`,data:{stepIndex:a.stepIndex,stepNumber:a.stepIndex+1,stepName:a.stepName,...a.targetLabel?{targetLabel:a.targetLabel}:{},status:a.status,durationMs:a.durationMs,startedAtMs:a.startedAtMs,endedAtMs:a.endedAtMs,...a.error?{error:a.error}:{}}})),r=t.map(a=>JSON.stringify(a)).join(`
541
- `)+`
542
- `,i=e(Buffer.from(r,"utf8")),o=w.join(Y(),`sootsim-flow-steps-${Date.now()}.jsonl.gz`);return P.writeFileSync(o,i),console.log(` flow trace: ${t.length} step events written to ${o} (${i.length} bytes gz)`),o}async function tr(n,e){if(!e)return null;let t=n.flatMap(i=>i.screenshotPath?[{id:`flow-step-${i.stepIndex}`,label:i.targetLabel??`Step ${i.stepIndex+1}`,kind:"interaction",t:Math.max(0,i.endedAtMs-e),path:i.screenshotPath}]:[]);if(t.length===0)return null;let r=w.join(Y(),`sootsim-flow-snapshots-${Date.now()}.json`);return P.writeFileSync(r,JSON.stringify(t)),console.log(` flow snapshots: ${t.length} written to ${r}`),r}async function rr(n){let e=w.join(Y(),`sootsim-frame-stats-${Date.now()}.json`);return P.writeFileSync(e,JSON.stringify(n)),console.log(` frame stats: written to ${e}`),e}async function ir(n){let e=n[0],t=r=>n.find((i,o)=>n[o-1]===r);switch(e){case"start":{let{path:r,state:i}=tt();console.log(" flow draft started"),console.log(` session: ${r}`),console.log(` steps: ${i.steps.length}`);return}case"keep":{let r=we();if(r.active||(console.error(" no active flow draft \u2014 run `sootsim maestro start` first"),process.exit(1)),!r.kept){console.log(" no pending action to keep");return}console.log(` kept: ${r.candidate.summary}`),console.log(` steps: ${r.stepCount}`);return}case"end":{let r=t("--output")||(n[1]&&!n[1].startsWith("-")?n[1]:void 0),i=n.includes("--validate")||n.includes("--video"),o=n.includes("--video"),a=we();a.active&&a.kept&&console.log(` auto-kept trailing action: ${a.candidate.summary}`);let s=rt(r||(i?or():void 0));if(s.active||(console.error(" no active flow draft \u2014 run `sootsim maestro start` first"),process.exit(1)),!s.valid){console.error(" flow draft is not valid:");for(let l of s.issues)console.error(` - ${l}`);console.error(" draft preserved \u2014 keep at least one real interaction or run `sootsim maestro start` to reset"),process.exit(1)}if(i){let l=sr(n,s.outputPath),p=await ft(l);if(p!==0){console.error(`
543
- validation failed \u2014 draft preserved so you can keep iterating`),process.exitCode=p;return}ge(),console.log(` flow draft validated (${s.stepCount} step${s.stepCount===1?"":"s"})`),s.outputPath&&console.log(` saved: ${s.outputPath}`),o&&console.log(" video: recorded during validation run");return}if(ge(),console.log(` flow draft ended (${s.stepCount} step${s.stepCount===1?"":"s"})`),s.outputPath){console.log(` saved: ${s.outputPath}`),console.log(` next: sootsim maestro test ${s.outputPath} --record`);return}console.log(""),process.stdout.write(s.yaml);return}case"validate":{let r=n[1];(!r||r.startsWith("-"))&&(console.error(" usage: sootsim maestro validate <path>"),process.exit(1));let i=me(r);if(i.length>0){console.error(` x ${r} failed validation:`);for(let o of i)console.error(` - ${o}`);process.exit(1)}console.log(` + ${r} looks valid`);return}}}function nr(n){return n[0]==="--sim"&&n.length>=2?[...n.slice(2),"--sim",n[1]]:n}async function Wr(n){let e=nr(n),t=e[0];if(t==="start"||t==="keep"||t==="good"||t==="end"||t==="validate")return await ir(e),0;let r=await ft(e);return r!==0&&(process.exitCode=r),r}function ht(n){console.log(""),it(n)}function or(){return w.join(Y(),`sootsim-flow-draft-${Date.now()}.yaml`)}function sr(n,e){if(!e)throw new Error("validated flow draft requires an output path");let t=[e];for(let r=1;r<n.length;r++){let i=n[r];if(!(i==="--validate"||i==="--video")){if(i==="--output"){r+=1;continue}r===1&&!i.startsWith("-")||t.push(i)}}return!t.includes("--record")&&n.includes("--video")&&t.push("--record"),t}export{dt as a,Ot as b,Hr as c,Ur as d,zt as e,Xt as f,ft as g,nr as h,Wr as i};