sootsim 0.1.220 → 0.1.222

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 (141) hide show
  1. package/dist-cli/bin.js +4 -4
  2. package/dist-cli/chunks/{agent-LCKEPMVH.js → agent-PAMEKRPR.js} +2 -2
  3. package/dist-cli/chunks/{agent-wrapper-ND5JHQSI.js → agent-wrapper-OSAGK6VL.js} +2 -2
  4. package/dist-cli/chunks/{app-fonts-N2W5BQXE.js → app-fonts-22INL2EQ.js} +2 -2
  5. package/dist-cli/chunks/{assert-O3QO4ZFV.js → assert-52DZMSFX.js} +2 -2
  6. package/dist-cli/chunks/{auth-7VXPQOZP.js → auth-7GTFXSYJ.js} +2 -2
  7. package/dist-cli/chunks/beta-PHTIILYS.js +2 -0
  8. package/dist-cli/chunks/{camera-OROQGFMH.js → camera-6NU3NTOK.js} +2 -2
  9. package/dist-cli/chunks/{chunk-J3QE2UZI.js → chunk-22SK3UIK.js} +1 -1
  10. package/dist-cli/chunks/{chunk-VCLV5GYE.js → chunk-27GCMFBK.js} +2 -2
  11. package/dist-cli/chunks/chunk-2FWJGMXZ.js +1 -0
  12. package/dist-cli/chunks/{chunk-S6XSCI45.js → chunk-2J4S6MUC.js} +1 -1
  13. package/dist-cli/chunks/{chunk-UODAA57Q.js → chunk-3II53A2P.js} +2 -2
  14. package/dist-cli/chunks/{chunk-GWQWCFMR.js → chunk-74RYDROC.js} +2 -2
  15. package/dist-cli/chunks/{chunk-ZW5IAKXC.js → chunk-7NWA6IEO.js} +2 -2
  16. package/dist-cli/chunks/{chunk-XHPOQKUA.js → chunk-AJNNLP2G.js} +1 -1
  17. package/dist-cli/chunks/{chunk-PJ76I3KZ.js → chunk-ANJLN4OR.js} +1 -1
  18. package/dist-cli/chunks/{chunk-YRHLQY6J.js → chunk-BMDW2UP2.js} +2 -2
  19. package/dist-cli/chunks/{chunk-RWJM23VH.js → chunk-CYB4R5KY.js} +1 -1
  20. package/dist-cli/chunks/{chunk-KZUGDZ3Q.js → chunk-ELE7IY7O.js} +2 -2
  21. package/dist-cli/chunks/{chunk-RIB5CQ34.js → chunk-ER35PHK2.js} +1 -1
  22. package/dist-cli/chunks/{chunk-GBALEYV4.js → chunk-EXWBPQTP.js} +1 -1
  23. package/dist-cli/chunks/{chunk-UXLMOEFU.js → chunk-FXV56NIE.js} +2 -2
  24. package/dist-cli/chunks/chunk-G3WMTCYE.js +1 -0
  25. package/dist-cli/chunks/{chunk-UHEKB33X.js → chunk-HGXGAEMQ.js} +2 -2
  26. package/dist-cli/chunks/{chunk-U3OSSCTT.js → chunk-HZKDCAPT.js} +67 -67
  27. package/dist-cli/chunks/{chunk-3ZWOQPLC.js → chunk-IH2EGP5O.js} +1 -1
  28. package/dist-cli/chunks/chunk-J3KNXYXV.js +2 -0
  29. package/dist-cli/chunks/{chunk-64GMEXIP.js → chunk-JYAYD6GF.js} +2 -2
  30. package/dist-cli/chunks/{chunk-EFLOJBBN.js → chunk-KSNE3CXF.js} +3 -3
  31. package/dist-cli/chunks/{chunk-BXNMPK4X.js → chunk-LDIHELGQ.js} +2 -2
  32. package/dist-cli/chunks/{chunk-TH7ODXC5.js → chunk-LMHE7A45.js} +3 -3
  33. package/dist-cli/chunks/{chunk-BI3I5X3U.js → chunk-MMEXOEEB.js} +1 -1
  34. package/dist-cli/chunks/{chunk-3HJXCSYI.js → chunk-MMKHWL3Y.js} +2 -2
  35. package/dist-cli/chunks/{chunk-7TOHX4IF.js → chunk-NFGGDW7N.js} +1 -1
  36. package/dist-cli/chunks/{chunk-JMXBQ4RD.js → chunk-NPXZ3TTE.js} +3 -3
  37. package/dist-cli/chunks/{chunk-XKOYH7ES.js → chunk-OLBLBO7T.js} +1 -1
  38. package/dist-cli/chunks/{chunk-F5XBOFGK.js → chunk-OOAX7FH3.js} +2 -2
  39. package/dist-cli/chunks/{chunk-TEFCJZH5.js → chunk-OY3CGL2W.js} +1 -1
  40. package/dist-cli/chunks/{chunk-4JSQTD75.js → chunk-PKLWGFHZ.js} +1 -1
  41. package/dist-cli/chunks/{chunk-RTZNRPD4.js → chunk-PMEH3LVK.js} +3 -3
  42. package/dist-cli/chunks/{chunk-HAXE5SZL.js → chunk-PPNT77TR.js} +1 -1
  43. package/dist-cli/chunks/{chunk-OBWXIGPP.js → chunk-PT2YFQPS.js} +2 -2
  44. package/dist-cli/chunks/{chunk-OCEYXYKG.js → chunk-QPMDVJD4.js} +2 -2
  45. package/dist-cli/chunks/{chunk-ZU6ECPCC.js → chunk-SMSLWF32.js} +1 -1
  46. package/dist-cli/chunks/{chunk-FRQOTDD6.js → chunk-SSCVCJ44.js} +2 -2
  47. package/dist-cli/chunks/{chunk-NRHZHQOH.js → chunk-U72XOJWQ.js} +2 -2
  48. package/dist-cli/chunks/{chunk-6HBN4KIM.js → chunk-UQC3LPA5.js} +2 -2
  49. package/dist-cli/chunks/{chunk-NPK2TDEV.js → chunk-WDKBZZ66.js} +2 -2
  50. package/dist-cli/chunks/{chunk-KJVNP5B5.js → chunk-WVM3FQYU.js} +2 -2
  51. package/dist-cli/chunks/{chunk-PWLK4BGI.js → chunk-ZLIJSNSV.js} +2 -2
  52. package/dist-cli/chunks/cli-version-MKNW3K2G.js +2 -0
  53. package/dist-cli/chunks/{compat-NRYECFCC.js → compat-MY735YZN.js} +3 -3
  54. package/dist-cli/chunks/{config-4KKKEHH2.js → config-2O6FVTRD.js} +2 -2
  55. package/dist-cli/chunks/{control-ZH7X66II.js → control-USXHNAMY.js} +2 -2
  56. package/dist-cli/chunks/daemon-7VGXE5TR.js +2 -0
  57. package/dist-cli/chunks/{debug-Z66GNDYA.js → debug-JTEEZDTL.js} +3 -3
  58. package/dist-cli/chunks/{desktop-DO2BQKM4.js → desktop-3D3UEHO2.js} +3 -3
  59. package/dist-cli/chunks/{detox-66YMXFQ5.js → detox-CI2TC5QB.js} +2 -2
  60. package/dist-cli/chunks/{device-KPQXKN5R.js → device-DXUKJNRG.js} +2 -2
  61. package/dist-cli/chunks/{diagnose-OMCHVX2X.js → diagnose-J7YIKH7F.js} +2 -2
  62. package/dist-cli/chunks/drivers-GR5S424K.js +2 -0
  63. package/dist-cli/chunks/{film-PV6DPBRX.js → film-VI7LK5QA.js} +7 -7
  64. package/dist-cli/chunks/flow-VVZQZ2BI.js +2 -0
  65. package/dist-cli/chunks/help-GAD62NIJ.js +2 -0
  66. package/dist-cli/chunks/{home-paths-LGQZZOPD.js → home-paths-2MGU226G.js} +2 -2
  67. package/dist-cli/chunks/inspect-QGHM6JDA.js +2 -0
  68. package/dist-cli/chunks/install-desktop-QCXPIETA.js +2 -0
  69. package/dist-cli/chunks/{login-QQH2UU2S.js → login-6POY2KI5.js} +4 -4
  70. package/dist-cli/chunks/{logout-KMGAWWAS.js → logout-XVRICTOO.js} +2 -2
  71. package/dist-cli/chunks/{maestro-IKINYBBR.js → maestro-NMQPC4Z6.js} +3 -3
  72. package/dist-cli/chunks/{maestro-generate-NWVVHDBL.js → maestro-generate-RWOTTZWF.js} +3 -3
  73. package/dist-cli/chunks/{mode-T576L6ZK.js → mode-YJDSWYDP.js} +2 -2
  74. package/dist-cli/chunks/optional-demo-registry-VW3GGNEG.js +2 -0
  75. package/dist-cli/chunks/{perf-TRPZNIQH.js → perf-5C66OAUT.js} +2 -2
  76. package/dist-cli/chunks/{record-O5HUQAK4.js → record-SL3GFCYV.js} +3 -3
  77. package/dist-cli/chunks/runtime-HY2MH4YI.js +2 -0
  78. package/dist-cli/chunks/{screenshot-command-5FI7RD5L.js → screenshot-command-LDQ7ECBF.js} +3 -3
  79. package/dist-cli/chunks/{screenshots-capture-RLEAPJ45.js → screenshots-capture-RESSNVW3.js} +2 -2
  80. package/dist-cli/chunks/{serve-4SIWGY4S.js → serve-HJCCACDY.js} +2 -2
  81. package/dist-cli/chunks/{setup-LDHVGPS2.js → setup-XW3UMFWG.js} +3 -3
  82. package/dist-cli/chunks/{skills-CCIOVHHV.js → skills-XEEQG4WI.js} +2 -2
  83. package/dist-cli/chunks/{storage-HV7PNB7R.js → storage-7QRHSCU5.js} +2 -2
  84. package/dist-cli/chunks/store-FYM45VYV.js +2 -0
  85. package/dist-cli/chunks/telemetry-QX4FTNQ2.js +2 -0
  86. package/dist-cli/chunks/{timeline-NZY4TIYS.js → timeline-M7WJ3UPA.js} +2 -2
  87. package/dist-cli/chunks/{upgrade-3SRHX5MN.js → upgrade-JKF372UG.js} +2 -2
  88. package/dist-cli/chunks/upload-LGZORNQI.js +2 -0
  89. package/dist-cli/chunks/{version-EWVUUOUL.js → version-SU3MXXWF.js} +2 -2
  90. package/dist-cli/chunks/web-47OUBT5X.js +2 -0
  91. package/dist-cli/chunks/{what-happened-K2NQG7LZ.js → what-happened-J6IVUDEV.js} +2 -2
  92. package/dist-lib/agent-daemon-client.cjs +1 -1
  93. package/dist-lib/agent-events.cjs +1 -1
  94. package/dist-lib/agent-identity.cjs +1 -1
  95. package/dist-lib/agent-sessions.cjs +1 -1
  96. package/dist-lib/attached-projects.cjs +1 -1
  97. package/dist-lib/auth/shared-session.cjs +1 -1
  98. package/dist-lib/backend-origin.cjs +1 -1
  99. package/dist-lib/beta.cjs +1 -1
  100. package/dist-lib/beta.mjs +1 -1
  101. package/dist-lib/bridge-constants.cjs +1 -1
  102. package/dist-lib/cli-constants.cjs +1 -1
  103. package/dist-lib/config.cjs +1 -1
  104. package/dist-lib/detox/index.cjs +1 -1
  105. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  106. package/dist-lib/home-paths.cjs +1 -1
  107. package/dist-lib/host/bridge-host.cjs +1 -1
  108. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  109. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  110. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  111. package/dist-lib/host/websocket-proxy.cjs +1 -1
  112. package/dist-lib/index.cjs +1 -1
  113. package/dist-lib/jump-to-source-babel.cjs +1 -1
  114. package/dist-lib/menu.cjs +1 -1
  115. package/dist-lib/menu.mjs +1 -1
  116. package/dist-lib/metro.cjs +1 -1
  117. package/dist-lib/profiles.cjs +1 -1
  118. package/dist-lib/render-mode.cjs +1 -1
  119. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  120. package/dist-lib/sdk.cjs +1 -1
  121. package/dist-lib/sdk.mjs +1 -1
  122. package/dist-lib/skills.cjs +5 -5
  123. package/dist-lib/vite.cjs +1 -1
  124. package/package.json +1 -1
  125. package/dist-cli/chunks/beta-ZIOECOJB.js +0 -2
  126. package/dist-cli/chunks/chunk-AMUOGO6F.js +0 -1
  127. package/dist-cli/chunks/chunk-H7EGEWCF.js +0 -2
  128. package/dist-cli/chunks/chunk-VQ4VGI36.js +0 -1
  129. package/dist-cli/chunks/cli-version-MY4N7YDM.js +0 -2
  130. package/dist-cli/chunks/daemon-6QQWVRFD.js +0 -2
  131. package/dist-cli/chunks/drivers-T2AZY5KL.js +0 -2
  132. package/dist-cli/chunks/flow-BCJH7MUK.js +0 -2
  133. package/dist-cli/chunks/help-KRIPS56R.js +0 -2
  134. package/dist-cli/chunks/inspect-3XG2QTVU.js +0 -2
  135. package/dist-cli/chunks/install-desktop-SH73YM3O.js +0 -2
  136. package/dist-cli/chunks/optional-demo-registry-2F3PLJXV.js +0 -2
  137. package/dist-cli/chunks/runtime-RLXYAF2A.js +0 -2
  138. package/dist-cli/chunks/store-DF56QJJG.js +0 -2
  139. package/dist-cli/chunks/telemetry-OFJVUJ34.js +0 -2
  140. package/dist-cli/chunks/upload-ZKKGG3CU.js +0 -2
  141. package/dist-cli/chunks/web-OT6OKUVX.js +0 -2
@@ -1,13 +1,13 @@
1
- /*! sootsim v0.1.220 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as me,c as ge,d as we,e as Qe,f as ye,g as be,h as et,i as Se,j as tt}from"./chunk-JMXBQ4RD.js";import{a as Xe}from"./chunk-PWLK4BGI.js";import{a as it}from"./chunk-6HBN4KIM.js";import{a as rt}from"./chunk-F5XBOFGK.js";import{h as Ke,p as qe,r as Ye,v as Ze}from"./chunk-YRHLQY6J.js";import{f as He}from"./chunk-FRQOTDD6.js";import{a as Ce}from"./chunk-J3QE2UZI.js";import{h as fe,m as Ge}from"./chunk-KJVNP5B5.js";import{I as J,m as Ue,n as We,o as je,p as Ve}from"./chunk-RWJM23VH.js";import{g as pe,h as he,i as Je}from"./chunk-UHEKB33X.js";import{a as ze}from"./chunk-XHPOQKUA.js";import{a as De,b as de}from"./chunk-GWQWCFMR.js";import{d as ue,e as Ne}from"./chunk-ZU6ECPCC.js";import{g as Be,h as Le}from"./chunk-H7EGEWCF.js";import*as $ from"fs";import{createHash as Wt,randomUUID as jt}from"node:crypto";import{tmpdir as K}from"os";import*as w from"path";import*as S from"fs";import*as b from"path";var Ft="inset 0 0 0 0.5px #000, inset 0 0 0 2px #757575, inset 0 0 0 5px #212121",ot=1;function It(n){let e=Le(n),t=e.scale,r=e.statusBarHeight>0&&!e.dynamicIsland&&e.homeIndicatorHeight===0&&e.cornerRadius===0,i=e.width,o=e.height,a=r?e.width+58:e.width+e.bezelWidth*2,s=r?e.height+111+111:e.height+e.bezelWidth*2,l=9.5,u=ot,p=a+l*2,g=s+ot*2,F=l+(r?29:e.bezelWidth),m=r?111:e.bezelWidth,P=r?52:e.cornerRadius+e.bezelWidth,k=[{side:"right",top:e.hardwareButtons.lock.top,height:e.hardwareButtons.lock.height,width:e.hardwareButtons.width},{side:"left",top:e.hardwareButtons.ringToggle.top,height:e.hardwareButtons.ringToggle.height,width:e.hardwareButtons.width},{side:"left",top:e.hardwareButtons.volumeUp.top,height:e.hardwareButtons.volumeUp.height,width:e.hardwareButtons.width},{side:"left",top:e.hardwareButtons.volumeDown.top,height:e.hardwareButtons.volumeDown.height,width:e.hardwareButtons.width}];return{model:n,renderScale:t,outerWidth:Math.round(p*t),outerHeight:Math.round(g*t),logicalOuterWidth:p,logicalOuterHeight:g,logicalFrameWidth:a,logicalFrameHeight:s,logicalFrameLeft:l,logicalFrameTop:u,logicalScreenWidth:i,logicalScreenHeight:o,logicalScreenLeft:F,logicalScreenTop:m,logicalScreenRadius:r?0:e.cornerRadius,logicalFrameRadius:P,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:Ft,buttons:k,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 $t(n){let e=n.side==="right",t=e?"inset(-3px -3px -3px 0)":"inset(-3px 0 -3px -3px)";return`
1
+ /*! sootsim v0.1.222 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as me,c as ge,d as we,e as Qe,f as ye,g as be,h as et,i as Se,j as tt}from"./chunk-NPXZ3TTE.js";import{a as Xe}from"./chunk-ZLIJSNSV.js";import{a as nt}from"./chunk-UQC3LPA5.js";import{a as it}from"./chunk-OOAX7FH3.js";import{h as Ke,p as qe,r as Ye,v as Ze}from"./chunk-BMDW2UP2.js";import{f as He}from"./chunk-SSCVCJ44.js";import{a as Ce}from"./chunk-22SK3UIK.js";import{h as fe,m as Ge}from"./chunk-WVM3FQYU.js";import{I as J,m as je,n as Ue,o as We,p as Ve}from"./chunk-CYB4R5KY.js";import{g as pe,h as he,i as Je}from"./chunk-HGXGAEMQ.js";import{a as ze}from"./chunk-AJNNLP2G.js";import{a as De,b as de}from"./chunk-74RYDROC.js";import{d as ue,e as Ne}from"./chunk-SMSLWF32.js";import{g as Be,h as Le}from"./chunk-J3KNXYXV.js";import*as $ from"fs";import{createHash as Wt,randomUUID as Vt}from"node:crypto";import{tmpdir as K}from"os";import*as w from"path";import*as S from"fs";import*as b from"path";var Ft="inset 0 0 0 0.5px #000, inset 0 0 0 2px #757575, inset 0 0 0 5px #212121",ot=1;function It(r){let e=Le(r),t=e.scale,i=e.statusBarHeight>0&&!e.dynamicIsland&&e.homeIndicatorHeight===0&&e.cornerRadius===0,n=e.width,o=e.height,a=i?e.width+58:e.width+e.bezelWidth*2,s=i?e.height+111+111:e.height+e.bezelWidth*2,l=9.5,u=ot,p=a+l*2,g=s+ot*2,F=l+(i?29:e.bezelWidth),m=i?111:e.bezelWidth,P=i?52:e.cornerRadius+e.bezelWidth,k=[{side:"right",top:e.hardwareButtons.lock.top,height:e.hardwareButtons.lock.height,width:e.hardwareButtons.width},{side:"left",top:e.hardwareButtons.ringToggle.top,height:e.hardwareButtons.ringToggle.height,width:e.hardwareButtons.width},{side:"left",top:e.hardwareButtons.volumeUp.top,height:e.hardwareButtons.volumeUp.height,width:e.hardwareButtons.width},{side:"left",top:e.hardwareButtons.volumeDown.top,height:e.hardwareButtons.volumeDown.height,width:e.hardwareButtons.width}];return{model:r,renderScale:t,outerWidth:Math.round(p*t),outerHeight:Math.round(g*t),logicalOuterWidth:p,logicalOuterHeight:g,logicalFrameWidth:a,logicalFrameHeight:s,logicalFrameLeft:l,logicalFrameTop:u,logicalScreenWidth:n,logicalScreenHeight:o,logicalScreenLeft:F,logicalScreenTop:m,logicalScreenRadius:i?0:e.cornerRadius,logicalFrameRadius:P,frameBackground:i?"linear-gradient(180deg, #1b1c20 0%, #0f1012 42%, #050608 100%)":"#000000",frameOutline:i?"0 0 0 1px #1f2125":"0 0 0 1px #333",metallicRingShadow:i?null:Ft,buttons:k,legacyHomeButton:i?{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 $t(r){let e=r.side==="right",t=e?"inset(-3px -3px -3px 0)":"inset(-3px 0 -3px -3px)";return`
3
3
  <div
4
4
  aria-hidden="true"
5
5
  style="
6
6
  position:absolute;
7
- ${e?`right:-${n.width}px;`:`left:-${n.width}px;`}
8
- top:${n.top}px;
9
- width:${n.width}px;
10
- height:${n.height}px;
7
+ ${e?`right:-${r.width}px;`:`left:-${r.width}px;`}
8
+ top:${r.top}px;
9
+ width:${r.width}px;
10
+ height:${r.height}px;
11
11
  background-color:#212121;
12
12
  border-top-left-radius:${e?0:1.5}px;
13
13
  border-bottom-left-radius:${e?0:1.5}px;
@@ -24,33 +24,33 @@ import{a as me,c as ge,d as we,e as Qe,f as ye,g as be,h as et,i as Se,j as tt}f
24
24
  z-index:2;
25
25
  "
26
26
  ></div>
27
- `}function Pt(n,e){let t=n.buttons.map($t).join(""),r=n.metallicRingShadow?`
27
+ `}function Pt(r,e){let t=r.buttons.map($t).join(""),i=r.metallicRingShadow?`
28
28
  <div
29
29
  aria-hidden="true"
30
30
  style="
31
31
  position:absolute;
32
32
  inset:0;
33
- border-radius:${n.logicalFrameRadius}px;
34
- box-shadow:${n.metallicRingShadow};
33
+ border-radius:${r.logicalFrameRadius}px;
34
+ box-shadow:${r.metallicRingShadow};
35
35
  pointer-events:none;
36
36
  z-index:10;
37
37
  "
38
38
  ></div>
39
- `:"",i=n.legacyHomeButton?`
39
+ `:"",n=r.legacyHomeButton?`
40
40
  <div
41
41
  aria-hidden="true"
42
42
  style="
43
43
  position:absolute;
44
- top:${n.legacyHomeButton.top}px;
45
- left:${n.legacyHomeButton.left}px;
46
- width:${n.legacyHomeButton.size}px;
47
- height:${n.legacyHomeButton.size}px;
44
+ top:${r.legacyHomeButton.top}px;
45
+ left:${r.legacyHomeButton.left}px;
46
+ width:${r.legacyHomeButton.size}px;
47
+ height:${r.legacyHomeButton.size}px;
48
48
  border-radius:50%;
49
49
  background:
50
50
  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%);
51
51
  box-shadow:
52
52
  inset 0 0 0 1px rgba(255,255,255,0.06),
53
- inset 0 0 0 ${n.legacyHomeButton.ring}px rgba(184,192,204,0.45),
53
+ inset 0 0 0 ${r.legacyHomeButton.ring}px rgba(184,192,204,0.45),
54
54
  0 0 0 1px rgba(0,0,0,0.5);
55
55
  z-index:3;
56
56
  pointer-events:none;
@@ -68,7 +68,7 @@ import{a as me,c as ge,d as we,e as Qe,f as ye,g as be,h as et,i as Se,j as tt}f
68
68
  "
69
69
  ></div>
70
70
  </div>
71
- `:"",o=n.showHomeIndicator?`
71
+ `:"",o=r.showHomeIndicator?`
72
72
  <div
73
73
  aria-hidden="true"
74
74
  style="
@@ -76,7 +76,7 @@ import{a as me,c as ge,d as we,e as Qe,f as ye,g as be,h as et,i as Se,j as tt}f
76
76
  left:0;
77
77
  right:0;
78
78
  bottom:4px;
79
- height:${n.logicalHomeIndicatorStripHeight}px;
79
+ height:${r.logicalHomeIndicatorStripHeight}px;
80
80
  display:flex;
81
81
  align-items:center;
82
82
  justify-content:center;
@@ -101,8 +101,8 @@ import{a as me,c as ge,d as we,e as Qe,f as ye,g as be,h as et,i as Se,j as tt}f
101
101
  <style>
102
102
  html, body {
103
103
  margin: 0;
104
- width: ${n.outerWidth}px;
105
- height: ${n.outerHeight}px;
104
+ width: ${r.outerWidth}px;
105
+ height: ${r.outerHeight}px;
106
106
  background: transparent;
107
107
  }
108
108
  body {
@@ -120,8 +120,8 @@ import{a as me,c as ge,d as we,e as Qe,f as ye,g as be,h as et,i as Se,j as tt}f
120
120
  id="frame-export-root"
121
121
  style="
122
122
  position:relative;
123
- width:${n.outerWidth}px;
124
- height:${n.outerHeight}px;
123
+ width:${r.outerWidth}px;
124
+ height:${r.outerHeight}px;
125
125
  overflow:hidden;
126
126
  background:transparent;
127
127
  "
@@ -132,9 +132,9 @@ import{a as me,c as ge,d as we,e as Qe,f as ye,g as be,h as et,i as Se,j as tt}f
132
132
  position:absolute;
133
133
  top:0;
134
134
  left:0;
135
- width:${n.logicalOuterWidth}px;
136
- height:${n.logicalOuterHeight}px;
137
- transform:scale(${n.renderScale});
135
+ width:${r.logicalOuterWidth}px;
136
+ height:${r.logicalOuterHeight}px;
137
+ transform:scale(${r.renderScale});
138
138
  transform-origin:top left;
139
139
  overflow:visible;
140
140
  "
@@ -143,29 +143,29 @@ import{a as me,c as ge,d as we,e as Qe,f as ye,g as be,h as et,i as Se,j as tt}f
143
143
  id="frame"
144
144
  style="
145
145
  position:absolute;
146
- top:${n.logicalFrameTop}px;
147
- left:${n.logicalFrameLeft}px;
148
- width:${n.logicalFrameWidth}px;
149
- height:${n.logicalFrameHeight}px;
150
- border-radius:${n.logicalFrameRadius}px;
146
+ top:${r.logicalFrameTop}px;
147
+ left:${r.logicalFrameLeft}px;
148
+ width:${r.logicalFrameWidth}px;
149
+ height:${r.logicalFrameHeight}px;
150
+ border-radius:${r.logicalFrameRadius}px;
151
151
  box-sizing:border-box;
152
152
  overflow:visible;
153
- background:${n.frameBackground};
154
- box-shadow:${n.frameOutline};
153
+ background:${r.frameBackground};
154
+ box-shadow:${r.frameOutline};
155
155
  "
156
156
  >
157
157
  ${t}
158
- ${r}
159
158
  ${i}
159
+ ${n}
160
160
  <div
161
161
  id="screen"
162
162
  style="
163
163
  position:absolute;
164
- top:${n.logicalScreenTop}px;
165
- left:${n.logicalScreenLeft-n.logicalFrameLeft}px;
166
- width:${n.logicalScreenWidth}px;
167
- height:${n.logicalScreenHeight}px;
168
- border-radius:${n.logicalScreenRadius}px;
164
+ top:${r.logicalScreenTop}px;
165
+ left:${r.logicalScreenLeft-r.logicalFrameLeft}px;
166
+ width:${r.logicalScreenWidth}px;
167
+ height:${r.logicalScreenHeight}px;
168
+ border-radius:${r.logicalScreenRadius}px;
169
169
  overflow:hidden;
170
170
  background:#000;
171
171
  "
@@ -177,7 +177,7 @@ import{a as me,c as ge,d as we,e as Qe,f as ye,g as be,h as et,i as Se,j as tt}f
177
177
  </div>
178
178
  </div>
179
179
  </body>
180
- </html>`}async function st(n,e){let{chromium:t}=await import("playwright"),r=await t.launch({headless:!0});try{let i=await kt(r);try{return await i.compose(n,e)}finally{await i.close()}}finally{await r.close()}}async function kt(n){let e=new Map;async function t(r){let i=e.get(r);if(i)return i;let o=It(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(Pt(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 At}from"child_process";import*as N from"vm";var Mt=3e5,Rt=`
180
+ </html>`}async function st(r,e){let{chromium:t}=await import("playwright"),i=await t.launch({headless:!0});try{let n=await kt(i);try{return await n.compose(r,e)}finally{await n.close()}}finally{await i.close()}}async function kt(r){let e=new Map;async function t(i){let n=e.get(i);if(n)return n;let o=It(i),a=await r.newContext({viewport:{width:o.outerWidth,height:o.outerHeight},deviceScaleFactor:1}),s=await a.newPage(),l={layout:o,context:a,page:s};return e.set(i,l),l}return{async compose(i,n){let o=await t(n),a=`data:image/png;base64,${i.toString("base64")}`;return await o.page.setContent(Pt(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 i of e.values())await i.context.close();e.clear()}}}import{spawnSync as At}from"child_process";import*as N from"vm";var Mt=3e5,Rt=`
181
181
  let input = '';
182
182
  process.stdin.on('data', (c) => { input += c });
183
183
  process.stdin.on('end', async () => {
@@ -199,7 +199,7 @@ process.stdin.on('end', async () => {
199
199
  process.exitCode = 1;
200
200
  }
201
201
  });
202
- `;function G(n,e,t){if(t?.multipartForm)throw new Error("http: multipartForm is not supported by sootsim yet");let r={...process.env};for(let s of Object.keys(r))(s.startsWith("BUN_INSPECT")||s==="NODE_OPTIONS")&&delete r[s];let i=At(process.execPath,["-e",Rt],{input:JSON.stringify({url:n,method:e,headers:t?.headers,body:t?.body}),encoding:"utf8",timeout:Mt,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 Ot=/(?<!\\)\$\{([^$]*)\}/g,_t=/\\(\$\{[^$]*\})/g,Dt=/^[A-Za-z_$][A-Za-z0-9_$]*$/,X=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:at(o)).join(" "))}};this.context=N.createContext(r),N.runInContext(`
202
+ `;function G(r,e,t){if(t?.multipartForm)throw new Error("http: multipartForm is not supported by sootsim yet");let i={...process.env};for(let s of Object.keys(i))(s.startsWith("BUN_INSPECT")||s==="NODE_OPTIONS")&&delete i[s];let n=At(process.execPath,["-e",Rt],{input:JSON.stringify({url:r,method:e,headers:t?.headers,body:t?.body}),encoding:"utf8",timeout:Mt,maxBuffer:64*1024*1024,env:i});if(n.error)throw new Error(`http ${e} ${r} failed: ${n.error.message}`);let o;try{o=JSON.parse(n.stdout||"")}catch{throw new Error(`http ${e} ${r} failed: no response (${(n.stderr||"").trim().slice(0,200)})`)}let a=o;if(a.__error)throw new Error(`http ${e} ${r} failed: ${a.__error}`);return a}var Ot=/(?<!\\)\$\{([^$]*)\}/g,_t=/\\(\$\{[^$]*\})/g,Dt=/^[A-Za-z_$][A-Za-z0-9_$]*$/,X=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??(n=>console.log(`[flow] js: ${n}`)),i={output:this.output,maestro:this.maestro,http:{get:(n,o)=>G(n,"GET",o),post:(n,o)=>G(n,"POST",o),put:(n,o)=>G(n,"PUT",o),delete:(n,o)=>G(n,"DELETE",o),request:(n,o)=>G(n,(o?.method??"GET").toUpperCase(),o)},console:{log:(...n)=>t(n.map(o=>typeof o=="string"?o:at(o)).join(" "))}};this.context=N.createContext(i),N.runInContext(`
203
203
  globalThis.__maestroScope = new Proxy(globalThis, {
204
204
  has() { return true },
205
205
  get(target, key) { return target[key] },
@@ -210,13 +210,13 @@ process.stdin.on('end', async () => {
210
210
  var yPercent = Math.ceil(y * 100) + '%'
211
211
  return xPercent + ',' + yPercent
212
212
  }
213
- `,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 N.runInContext(`(function(){ with(__maestroScope){ return eval(\`${t}\`) } })()`,this.context)}syncEnvToContext(){let e=N.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(Ot,(r,i)=>{if(i.trim().length===0)return"";let o=this.evaluate(i);if(o===void 0&&Dt.test(i.trim()))throw new Error(`missing variable for flow placeholder: ${i.trim()}`);return at(o)}).replace(_t,(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 at(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 lt(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,te=393,C=852;function f(n){return new Promise(e=>setTimeout(e,n))}function Ee(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}function z(n,e){if(!Ee(n))return null;let t=n[e];return typeof t=="string"&&t.length>0?t:null}function Bt(n,e){return Ee(n)?n[e]===!0:!1}function Lt(n){if(!n)return null;let e=n.recentApps;if(Array.isArray(e))for(let r of e){let i=z(r,"id");if(i)return i}let t=n.surfaceBindings;return z(t,"app:one")||z(t,"app:two")||null}function Nt(n){return n?b.basename(n)===".maestro"?b.dirname(n):n:process.cwd()}function Ct(n,e,t){let r=e.endsWith(".png")?e:`${e}.png`;if(b.isAbsolute(r))return r;if(t.mode==="flow"&&/[\\/]/.test(r)){let i=r.startsWith("./")||r.startsWith("../")?t.flowDir??process.cwd():Nt(t.flowDir);return b.resolve(i,r)}return b.join(n,r)}function Ht(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??C)}}function ct(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 Ut(n){let e=n.split(/^---$/m),t=e.length>1?e[e.length-1]:n,r=Xe.parse(t);return Array.isArray(r)?r:[]}var re=class{constructor(e,t){this.bridge=e;this.opts=t}stepDelay=0;js=new X({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 waitForTree(e=Q){let t=Date.now()+e,r=Date.now(),i=null,o=0,a=0,s=-1,l=r;for(;Date.now()<t;){try{let p=await this.evaluate(Ue,8e3);if(o=0,p?.externalError)throw new Error(`app failed to load: ${p.externalError}`);if(p){let g=Date.now();p.nodes!==s&&(s=p.nodes,l=g);let F=p.flag===!0&&je(p),m=p.flag!==!0&&Ve(p);if((F||m)&&p.externalReady!==!1&&!p.externalError&&!p.loadingText&&g-l>=We)return}}catch(p){if(i=p instanceof Error?p:new Error(String(p)),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 \`sootsim list\`, then close it with \`sootsim close <id>\` or start a fresh one with \`sootsim open --new <port>\`.`);await this.refreshSimId()}let u=Date.now()-r;u-a>=5e3&&(a=u,console.log(` [flow] waiting for app to be ready\u2026 (${Math.round(u/1e3)}s)`)),await f(500)}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 it("flow --video",{originOverride:this.opts.billingOriginOverride,allowGitHubAuth:this.opts.allowGitHubRecording}),this.recordingAccessChecked=!0);let e=Date.now(),t=await this.evaluate(`(() => {
213
+ `,this.context);for(let[n,o]of Object.entries(process.env))o!==void 0&&this.envBinding.set(n,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,i]of e)this.envBinding.set(t,i)}}evaluate(e,t={}){let i=t.env;if(i&&Object.keys(i).length>0){this.enterEnvScope();try{for(let[n,o]of Object.entries(i))this.envBinding.set(n,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 N.runInContext(`(function(){ with(__maestroScope){ return eval(\`${t}\`) } })()`,this.context)}syncEnvToContext(){let e=N.runInContext("globalThis",this.context);for(let t of this.syncedEnvKeys)this.envBinding.has(t)||delete e[t];this.syncedEnvKeys=new Set;for(let[t,i]of this.envBinding)try{e[t]=i,this.syncedEnvKeys.add(t)}catch{}}evaluateStringTemplate(e){return e.replace(Ot,(i,n)=>{if(n.trim().length===0)return"";let o=this.evaluate(n);if(o===void 0&&Dt.test(n.trim()))throw new Error(`missing variable for flow placeholder: ${n.trim()}`);return at(o)}).replace(_t,(i,n)=>n)}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(i=>this.interpolateValue(i,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([i,n])=>[i,this.interpolateValue(n,i)])):e}};function at(r){if(r===void 0)return"undefined";if(r===null)return"null";if(typeof r=="object")try{return JSON.stringify(r)}catch{return String(r)}return String(r)}function lt(r){if(r==null)return!1;if(typeof r=="boolean")return r;let e=String(r);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,te=393,C=852;function f(r){return new Promise(e=>setTimeout(e,r))}function Ee(r){return!!(r&&typeof r=="object"&&!Array.isArray(r))}function z(r,e){if(!Ee(r))return null;let t=r[e];return typeof t=="string"&&t.length>0?t:null}function Bt(r,e){return Ee(r)?r[e]===!0:!1}function Lt(r){if(!r)return null;let e=r.recentApps;if(Array.isArray(e))for(let i of e){let n=z(i,"id");if(n)return n}let t=r.surfaceBindings;return z(t,"app:one")||z(t,"app:two")||null}function Nt(r){return r?b.basename(r)===".maestro"?b.dirname(r):r:process.cwd()}function Ct(r,e,t){let i=e.endsWith(".png")?e:`${e}.png`;if(b.isAbsolute(i))return i;if(t.mode==="flow"&&/[\\/]/.test(i)){let n=i.startsWith("./")||i.startsWith("../")?t.flowDir??process.cwd():Nt(t.flowDir);return b.resolve(n,i)}return b.join(r,i)}function Ht(r){if(typeof r=="string")return{path:r,withFrame:!1};let e=r.path?.trim()||r.name?.trim();if(!e)throw new Error("takeScreenshot object form requires path or name");return{path:e,withFrame:r.withFrame===!0,layers:r.layers}}function ee(r,e){let[t,i]=r.split(",").map(s=>s.trim()),n=(s,l)=>s.endsWith("%")?Number.parseFloat(s)/100*l:Number.parseFloat(s),o=e?.x??0,a=e?.y??0;return{x:o+n(t,e?.width??te),y:a+n(i,e?.height??C)}}function ct(r){switch(r){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{[r]:!0}}}function jt(r){let e=r.split(/^---$/m),t=e.length>1?e[e.length-1]:r,i=Xe.parse(t);return Array.isArray(i)?i:[]}var ie=class{constructor(e,t){this.bridge=e;this.opts=t}stepDelay=0;js=new X({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 i=t.searchParams.toString();return`${t.origin}${t.pathname}${i?`?${i}`:""}`}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 n=this.simRouteHint&&e.find(l=>l.readyState==="open"&&this.normalizeSimRoute(l.url||l.origin)===this.simRouteHint);if(!n)return;let o=e.find(l=>l.isPrimary&&l.readyState==="open"),a=e.find(l=>l.readyState==="open"),s=n??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 waitForTree(e=Q){let t=Date.now()+e,i=Date.now(),n=null,o=0,a=0,s=-1,l=i;for(;Date.now()<t;){try{let p=await this.evaluate(je,8e3);if(o=0,p?.externalError)throw new Error(`app failed to load: ${p.externalError}`);if(p){let g=Date.now();p.nodes!==s&&(s=p.nodes,l=g);let F=p.flag===!0&&We(p),m=p.flag!==!0&&Ve(p);if((F||m)&&p.externalReady!==!1&&!p.externalError&&!p.loadingText&&g-l>=Ue)return}}catch(p){if(n=p instanceof Error?p:new Error(String(p)),n.message.startsWith("app failed to load:"))throw n;if(o++,o>=4)throw new Error(`target sim is not responding to the bridge (${n.message}). it is likely a stale orphan \u2014 run \`sootsim list\`, then close it with \`sootsim close <id>\` or start a fresh one with \`sootsim open --new <port>\`.`);await this.refreshSimId()}let u=Date.now()-i;u-a>=5e3&&(a=u,console.log(` [flow] waiting for app to be ready\u2026 (${Math.round(u/1e3)}s)`)),await f(500)}throw n?.message.startsWith("app failed to load:")?n: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 nt("flow --video",{originOverride:this.opts.billingOriginOverride,allowGitHubAuth:this.opts.allowGitHubRecording}),this.recordingAccessChecked=!0);let e=Date.now(),t=await this.evaluate(`(() => {
214
214
  const rec = window.__sootsimRecorder
215
215
  if (!rec) return { ok: false, error: 'recorder unavailable on this page' }
216
216
  const format = ${JSON.stringify(this.opts.recordingFormat??"webm")}
217
217
  if (rec.state() === 'recording') return { ok: true, format }
218
218
  return rec.start({ format, fps: 24 })
219
- })()`);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);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");S.mkdirSync(this.opts.recordingOutputDir,{recursive:!0});let a=(t.mime||this.opts.recordingFormat||"video/webm").includes("mp4")?"mp4":"webm",s=b.join(this.opts.recordingOutputDir,`sootsim-${Date.now()}.${a}`);return S.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 Se({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 () => {
219
+ })()`);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 i=e[t];if(typeof i=="string")return i.slice(0,80);if(typeof i=="number"||typeof i=="boolean")return String(i);if(!i||typeof i!="object")return;let n=i,o=n.id??n.text??n.name??n.path;if(typeof o=="string"&&o)return o.slice(0,80);if(n.point&&typeof n.point=="string")return n.point.slice(0,80);if(typeof n.x=="number"&&typeof n.y=="number")return`${Math.round(n.x)}, ${Math.round(n.y)}`}recordFlowTraceStep(e){let t=Date.now(),i={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&&(i.error=e.error instanceof Error?e.error.message:String(e.error)),e.screenshotPath&&(i.screenshotPath=e.screenshotPath),this.flowTraceSteps.push(i)}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 i=[],n=0;for(;;){let l=await this.evaluate(`window.__sootsimRecorder.getBlobBase64({ offset: ${n}, chunk: 2097152 })`);if(!l||(i.push(Buffer.from(l.data,"base64")),n=l.offset,l.done))break}if(i.length===0)throw new Error("recording requested but no video buffer was produced");S.mkdirSync(this.opts.recordingOutputDir,{recursive:!0});let a=(t.mime||this.opts.recordingFormat||"video/webm").includes("mp4")?"mp4":"webm",s=b.join(this.opts.recordingOutputDir,`sootsim-${Date.now()}.${a}`);return S.writeFileSync(s,Buffer.concat(i)),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 i=await Se({bridge:this.bridge,simId:this.opts.simId,maxMs:t,pollMs:80,stablePolls:6,strict:!0});await this.waitForVisualSettle(),console.log(i.settled?` [flow] recording tail settled in ${i.elapsed}ms`:` [flow] recording tail reached ${i.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 () => {
220
220
  const test = window.__sootsimTest
221
221
  if (!test) return null
222
222
  let node = null
@@ -365,18 +365,18 @@ process.stdin.on('end', async () => {
365
365
  )
366
366
  }
367
367
  return direct
368
- })()`)}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,u=l?.cx??s.absolutePosition.x+s.layout.width/2,p=l?.cy??s.absolutePosition.y+s.layout.height/2;if((await this.tap(u,p,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=Math.max(0,Math.round(r));if(!await this.evaluate(`(async () => {
368
+ })()`)}async tap(e,t,i){return await this.bridge.send({type:"tap",simId:this.opts.simId,x:e,y:t,target:i})}async longPress(e,t,i,n){return await this.bridge.send({type:"longPress",simId:this.opts.simId,x:e,y:t,durationMs:i,target:n})}async waitForElement(e,t=5e3){let i=Date.now()+t,n=await this.findElement(e);for(;!n&&Date.now()<i;)await f(150),n=await this.findElement(e);if(!n)return n;let o=Date.now()+1200,a=n;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(n=s,!l)return n;a=s}return n}replayTargetForElement(e,t,i){return{id:e.id??i?.target?.id??t.id??null,testID:e.id??i?.target?.testID??t.testID??null,text:e.text??i?.target?.text??i?.target?.accessibilityLabel??t.text??t.accessibilityLabel??null,type:i?.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 i=typeof t.nodeId=="number"?await this.resolveTapTarget(t.nodeId):null,n=this.replayTargetForElement(e,t,i);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:n}:{x:i?.cx??t.absolutePosition.x+t.layout.width/2,y:i?.cy??t.absolutePosition.y+t.layout.height/2,element:t,target:n}}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 i=await this.waitForElement(t);if(i){let o=i.isTextInput?4:1;for(let a=0;a<o;a++){let s=a===0?i:await this.findElement({text:t.text,id:t.id});if(!s)break;let l=typeof s.nodeId=="number"?await this.resolveTapTarget(s.nodeId):null,u=l?.cx??s.absolutePosition.x+s.layout.width/2,p=l?.cy??s.absolutePosition.y+s.layout.height/2;if((await this.tap(u,p,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,i=await this.resolveInteractionPoint(t);if(!i)throw new Error(`longPressOn: element not found: ${JSON.stringify(t)}`);let n=await this.longPress(i.x,i.y,3e3,i.target);if(n?.ok===!1||n?.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,i=80){let n=Math.max(0,Math.round(i));if(!await this.evaluate(`(async () => {
369
369
  const interact = window.__sootsimInteract
370
370
  if (interact?.doubleTap) {
371
- return !!(await interact.doubleTap(${e}, ${t}, ${i}))
371
+ return !!(await interact.doubleTap(${e}, ${t}, ${n}))
372
372
  }
373
373
  if (!interact?.tap) return false
374
374
  const first = await interact.tap(${e}, ${t})
375
375
  if (!first || first.hit === false) return false
376
- await new Promise((resolve) => setTimeout(resolve, ${i}))
376
+ await new Promise((resolve) => setTimeout(resolve, ${n}))
377
377
  const second = await interact.tap(${e}, ${t})
378
378
  return !!second && second.hit !== false
379
- })()`))throw new Error(`doubleTapAtCoords failed at (${e}, ${t})`);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<C)}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(`(() => {
379
+ })()`))throw new Error(`doubleTapAtCoords failed at (${e}, ${t})`);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 i=await this.findElement(t),n=i?` (matched node at y=${Math.round(i.absolutePosition.y)} h=${Math.round(i.layout.height)} \u2014 off-screen)`:" (no matching node in tree)";throw new Error(`assertVisible: ${JSON.stringify(t)} not visible${n}`)}async assertNotVisible(e){let t=typeof e=="string"?{text:e}:e;if(await this.isElementVisible(t)){let i=await this.findElement(t),n=i?` at (${Math.round(i.absolutePosition.x)},${Math.round(i.absolutePosition.y)})`:"";throw new Error(`assertNotVisible: ${JSON.stringify(t)} IS visible${n}`)}}async isElementVisible(e){let t=await this.findElement(e);return!!(t&&t.absolutePosition.y+t.layout.height>0&&t.absolutePosition.y<C)}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 i=t.testID??null,n=e.testID??null;if(i&&n&&i===n)return!0;let o=t.id??null,a=e.id??null;return!!(o&&a&&o===a)}async waitForFocusedTextInput(e=1500,t){let i=Date.now()+e;for(;Date.now()<i;){try{let n=await this.callTest("getFocusedNode");if(n&&this.focusedTextInputMatches(n,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(`(() => {
380
380
  const keyboard =
381
381
  window.__sootsimKeyboard ??
382
382
  window.SootSim?.bridges?.keyboard ??
@@ -386,7 +386,7 @@ process.stdin.on('end', async () => {
386
386
  visible: !!keyboard?.isVisible?.(),
387
387
  focused: !!test?.isTextInputFocused?.(),
388
388
  }
389
- })()`);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()+(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=Ht(e),r=Ct(this.opts.screenshotDir,t.path,{mode:this.opts.screenshotPathMode??"dir",flowDir:this.opts.flowDir});S.mkdirSync(b.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 u=await this.readCurrentDeviceModel();if(!u)throw new Error("could not read current device model for framed screenshot");let p=await st(l,u);return S.writeFileSync(r,p),console.log(`[flow] screenshot: ${r} (frame: ${u})`),r}return S.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 Be)?null:t}async captureScreenshot(e){S.mkdirSync(b.dirname(e),{recursive:!0});let r=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");S.writeFileSync(e,Buffer.from(r,"base64"))}async captureFailureBundle(e,t){S.mkdirSync(e,{recursive:!0});let r=(p,g)=>{try{S.writeFileSync(b.join(e,p),g)}catch{}},i=async p=>{try{return await this.bridge.send({type:"evaluate",simId:this.opts.simId,code:p})}catch{return null}},o=await i(`(async () => {
389
+ })()`);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()+(e.timeout||Q);for(;Date.now()<t;){if(await this.findElement(e))return;await f(200)}let i=await this.findElement(e),n=i?` (matched node y=${Math.round(i.absolutePosition.y)} \u2014 still off-screen at deadline)`:"";throw new Error(`waitFor: ${JSON.stringify(e)} not found after ${e.timeout||Q}ms${n}`)}async takeScreenshot(e){if(!this.hasFreshVisualSettle())try{await this.waitForVisualSettle(),await f(250)}catch{}let t=Ht(e),i=Ct(this.opts.screenshotDir,t.path,{mode:this.opts.screenshotPathMode??"dir",flowDir:this.opts.flowDir});S.mkdirSync(b.dirname(i),{recursive:!0});let n=t.layers??this.opts.screenshotLayers,o={type:"screenshot",simId:this.opts.simId};n&&n!=="full"&&(o.layers=n);let s=(await this.bridge.send(o)).replace(/^data:image\/png;base64,/,""),l=Buffer.from(s,"base64");if(t.withFrame){let u=await this.readCurrentDeviceModel();if(!u)throw new Error("could not read current device model for framed screenshot");let p=await st(l,u);return S.writeFileSync(i,p),console.log(`[flow] screenshot: ${i} (frame: ${u})`),i}return S.writeFileSync(i,l),console.log(`[flow] screenshot: ${i}`),i}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 Be)?null:t}async captureScreenshot(e){S.mkdirSync(b.dirname(e),{recursive:!0});let i=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");S.writeFileSync(e,Buffer.from(i,"base64"))}async captureFailureBundle(e,t){S.mkdirSync(e,{recursive:!0});let i=(p,g)=>{try{S.writeFileSync(b.join(e,p),g)}catch{}},n=async p=>{try{return await this.bridge.send({type:"evaluate",simId:this.opts.simId,code:p})}catch{return null}},o=await n(`(async () => {
390
390
  const out = {
391
391
  simId: window.__sootsimBridge?.id ?? window.SootSim?.state?.simId ?? null,
392
392
  url: location.href,
@@ -410,7 +410,7 @@ process.stdin.on('end', async () => {
410
410
  }
411
411
  } catch {}
412
412
  return out
413
- })()`);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 g=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");r("screenshot.png",Buffer.from(g,"base64"))}catch{}let a=await i(`(async () => {
413
+ })()`);i("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 g=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");i("screenshot.png",Buffer.from(g,"base64"))}catch{}let a=await n(`(async () => {
414
414
  const t = window.__sootsimTest
415
415
  const mainShell = window.SootSim?.bridges?.mainShell
416
416
  if (!t) return { error: 'no test bridge' }
@@ -420,19 +420,19 @@ process.stdin.on('end', async () => {
420
420
  } catch {}
421
421
  const all = await t.queryAll({ pruneHidden: true })
422
422
  return { shell, nodes: all, url: location.href, title: document.title }
423
- })()`);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 u=await i(`(() => {
423
+ })()`);a&&i("describe.json",JSON.stringify(a,null,2));let s=await n("(async () => await window.__sootsimTest?.dumpAccessibilityTree?.(20))()");typeof s=="string"&&i("a11y.txt",s);let l=await n("(async () => await window.__sootsimTest?.dumpTree?.(15))()");typeof l=="string"&&i("tree.txt",l);let u=await n(`(() => {
424
424
  const c = window.__sootsimConsole
425
425
  return {
426
426
  errors: c?.getErrors?.() ?? [],
427
427
  warnings: c?.getWarnings?.() ?? [],
428
428
  requests: (window.__sootsimGetFailedRequests?.() ?? []),
429
429
  }
430
- })()`);return u&&r("console.json",JSON.stringify(u,null,2)),e}async swipe(e="UP",t=300){let r=te/2,i=C/2,o=200,a=r,s=i,l=r,u=i;switch(e.toUpperCase()){case"UP":s+=o,u-=o;break;case"DOWN":s-=o,u+=o;break;case"LEFT":a+=o,l-=o;break;case"RIGHT":a-=o,l+=o;break}let p=Math.max(10,Math.round(t/16));await this.drag(a,s,l,u,p,16)}async drag(e,t,r,i,o=12,a=16){if(!(await this.evaluate(`(async () => {
430
+ })()`);return u&&i("console.json",JSON.stringify(u,null,2)),e}async swipe(e="UP",t=300){let i=te/2,n=C/2,o=200,a=i,s=n,l=i,u=n;switch(e.toUpperCase()){case"UP":s+=o,u-=o;break;case"DOWN":s-=o,u+=o;break;case"LEFT":a+=o,l-=o;break;case"RIGHT":a-=o,l+=o;break}let p=Math.max(10,Math.round(t/16));await this.drag(a,s,l,u,p,16)}async drag(e,t,i,n,o=12,a=16){if(!(await this.evaluate(`(async () => {
431
431
  const interact = window.__sootsimInteract
432
432
  if (!interact?.drag) return { ok: false }
433
- const value = await interact.drag(${e}, ${t}, ${r}, ${i}, ${Math.max(1,Math.round(o))}, ${Math.max(0,Math.round(a))})
433
+ const value = await interact.drag(${e}, ${t}, ${i}, ${n}, ${Math.max(1,Math.round(o))}, ${Math.max(0,Math.round(a))})
434
434
  return { ok: !!value, value }
435
- })()`))?.ok)throw new Error("drag failed");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,u=a;switch(t.toUpperCase()){case"UP":u-=s;break;case"DOWN":u+=s;break;case"LEFT":l-=s;break;case"RIGHT":l+=s;break}let p=Math.max(10,Math.round(r/16));await this.drag(o,a,l,u,p,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.evaluate(`(async () => {
435
+ })()`))?.ok)throw new Error("drag failed");await f(300)}async swipeCoords(e,t,i=300){let n=ee(e),o=ee(t),a=Math.max(10,Math.round(i/16));await this.drag(n.x,n.y,o.x,o.y,a,16)}async swipeFrom(e,t="UP",i=300){let n=await this.findElement(e);if(!n)throw new Error(`swipeFrom: element not found: ${JSON.stringify(e)}`);let o=n.absolutePosition.x+n.layout.width/2,a=n.absolutePosition.y+n.layout.height/2,s=180,l=o,u=a;switch(t.toUpperCase()){case"UP":u-=s;break;case"DOWN":u+=s;break;case"LEFT":l-=s;break;case"RIGHT":l+=s;break}let p=Math.max(10,Math.round(i/16));await this.drag(o,a,l,u,p,16)}async scrollTo(e,t,i){let n=await this.callTest("scrollTo",e,t,i,!1);if(!n?.ok)throw new Error(`scrollTo failed: ${n?.reason||"unknown error"}`);await f(250)}async pinch(e){let t=await this.evaluate(`(async () => {
436
436
  const interact = window.__sootsimInteract
437
437
  if (!interact?.pinch) return { ok: false, reason: 'no interact.pinch' }
438
438
  const ok = await interact.pinch(
@@ -441,7 +441,7 @@ process.stdin.on('end', async () => {
441
441
  ${e.steps||12}, ${e.stepMs||16}
442
442
  )
443
443
  return { ok: !!ok, reason: ok ? null : 'pinch returned false' }
444
- })()`);if(!t?.ok)throw new Error(`pinch failed: ${t?.reason||"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 Se({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<C-50){if(e.centerElement){let a=C/2,s=o.absolutePosition.y-a;if(Math.abs(s)>100){let l=Math.min(150,Math.abs(s)*.5),u=s>0?a-l:a+l;await this.drag(te/2,a,te/2,u,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()+(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(e){if(e){let i=!1;for(let o=0;o<3&&!i;o++)try{i=await this.evaluate(me(!0),2e4)}catch{await f(1e3)}i||console.warn(" warn: tenant storage clear did not ack \u2014 hard-reloading anyway (worker reset follows)")}await this.evaluate("window.location.reload()").catch(()=>{}),await f(500),await this.refreshSimId()}async softReloadGuestApp(e){if(!await this.evaluate(me(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 (sootsim has no native process)");let t=!!(e&&typeof e=="object"&&e.clearState),r=Bt(e,"resetRuntime");if(!this.firstLaunchDone&&!t){if(this.firstLaunchDone=!0,r){let i=await J(this.bridge).catch(()=>null),o=i?.state==="home"&&i.activeApp==null;await this.softReloadGuestApp(!1),await this.waitForTree(12e4),o&&(await fe(this.bridge,"goHome",1e3),await this.waitForShellHome(1e3)),await this.launchShellAppFromHomeIfNeeded(e,o?{...i??{},state:"home",activeApp:null}:null)}else await this.launchShellAppFromHomeIfNeeded(e);await this.waitForTree(3e4)}else if(this.firstLaunchDone=!0,await this.reloadGuestApp(t),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) => {
444
+ })()`);if(!t?.ok)throw new Error(`pinch failed: ${t?.reason||"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 Se({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),i=e.direction?.toUpperCase()||"DOWN",n=i==="DOWN"?"UP":i==="UP"?"DOWN":i;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<C-50){if(e.centerElement){let a=C/2,s=o.absolutePosition.y-a;if(Math.abs(s)>100){let l=Math.min(150,Math.abs(s)*.5),u=s>0?a-l:a+l;await this.drag(te/2,a,te/2,u,10,16)}}return}await this.swipe(n,250),await f(500)}throw new Error(`scrollUntilVisible: "${e.element}" not found`)}async extendedWaitUntil(e){let t=Date.now()+(e.timeout||Q);for(;Date.now()<t;){let i=e.visible?await this.isElementVisible(typeof e.visible=="string"?{text:e.visible}:e.visible):!0,n=e.notVisible?!await this.isElementVisible(typeof e.notVisible=="string"?{text:e.notVisible}:e.notVisible):!0;if(i&&n)return;await f(200)}throw new Error("extendedWaitUntil timed out")}async reloadGuestApp(e){if(e){let n=!1;for(let o=0;o<3&&!n;o++)try{n=await this.evaluate(me(!0),2e4)}catch{await f(1e3)}n||console.warn(" warn: tenant storage clear did not ack \u2014 hard-reloading anyway (worker reset follows)")}await this.evaluate("window.location.reload()").catch(()=>{}),await f(500),await this.refreshSimId()}async softReloadGuestApp(e){if(!await this.evaluate(me(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(i){t=i,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 (sootsim has no native process)");let t=!!(e&&typeof e=="object"&&e.clearState),i=Bt(e,"resetRuntime");if(!this.firstLaunchDone&&!t){if(this.firstLaunchDone=!0,i){let n=await J(this.bridge).catch(()=>null),o=n?.state==="home"&&n.activeApp==null;await this.softReloadGuestApp(!1),await this.waitForTree(12e4),o&&(await fe(this.bridge,"goHome",1e3),await this.waitForShellHome(1e3)),await this.launchShellAppFromHomeIfNeeded(e,o?{...n??{},state:"home",activeApp:null}:null)}else await this.launchShellAppFromHomeIfNeeded(e);await this.waitForTree(3e4)}else if(this.firstLaunchDone=!0,await this.reloadGuestApp(t),await this.waitForTree(12e4),this.opts.onAfterLaunch)try{await this.opts.onAfterLaunch()}catch(n){console.warn(` warn: onAfterLaunch hook threw: ${n instanceof Error?n.message:n}`)}this.profilingEnabled&&await this.startProfile(),this.recordingEnabled&&(await this.waitForVisualSettle(),await this.ensureRecordingStarted())}async waitForVisualSettle(){try{await this.evaluate(`new Promise((resolve) => {
445
445
  requestAnimationFrame(() => {
446
446
  requestAnimationFrame(() => {
447
447
  requestAnimationFrame(() => {
@@ -449,7 +449,7 @@ process.stdin.on('end', async () => {
449
449
  })
450
450
  })
451
451
  })
452
- })`),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(Ee(e)){let r=z(e,"appId")||z(e,"id");if(r)return r}return Lt(t)||"connect"}async waitForShellAppLaunched(e,t){let r=Date.now()+t,i=null;for(;Date.now()<r;){try{i=await J(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 waitForShellHome(e){let t=Date.now()+e;for(;Date.now()<t;){let r=await J(this.bridge).catch(()=>null);if(r?.state==="home"&&r.activeApp==null&&r.showSwitcher===!1)return;await f(16)}}async launchShellAppFromHomeIfNeeded(e,t){let r=null;if(t)r=t;else try{r=await J(this.bridge)}catch{return!1}if(r?.state!=="home"||r.activeApp!=null)return!1;let i=this.resolveShellLaunchAppId(e,r);return this.recordingEnabled&&await this.ensureRecordingStarted(),await fe(this.bridge,"launchApp",1e3,i),await this.waitForShellAppLaunched(i,1e3),!0}async startProfile(){let e=await this.evaluate(`(() => {
452
+ })`),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(Ee(e)){let i=z(e,"appId")||z(e,"id");if(i)return i}return Lt(t)||"connect"}async waitForShellAppLaunched(e,t){let i=Date.now()+t,n=null;for(;Date.now()<i;){try{n=await J(this.bridge)}catch{n=null}if(n?.state==="app"&&n.activeApp===e&&n.showSwitcher===!1&&typeof n.launchProgress=="number"&&n.launchProgress>=.98)return;await f(16)}}async waitForShellHome(e){let t=Date.now()+e;for(;Date.now()<t;){let i=await J(this.bridge).catch(()=>null);if(i?.state==="home"&&i.activeApp==null&&i.showSwitcher===!1)return;await f(16)}}async launchShellAppFromHomeIfNeeded(e,t){let i=null;if(t)i=t;else try{i=await J(this.bridge)}catch{return!1}if(i?.state!=="home"||i.activeApp!=null)return!1;let n=this.resolveShellLaunchAppId(e,i);return this.recordingEnabled&&await this.ensureRecordingStarted(),await fe(this.bridge,"launchApp",1e3,n),await this.waitForShellAppLaunched(n,1e3),!0}async startProfile(){let e=await this.evaluate(`(() => {
453
453
  if (!window.__sootsimShellPerf) {
454
454
  return { error: "shell frame profile unavailable (__sootsimShellPerf missing on the page)" }
455
455
  }
@@ -460,7 +460,7 @@ process.stdin.on('end', async () => {
460
460
  return { error: "shell frame profile unavailable (__sootsimShellPerf missing on the page)" }
461
461
  }
462
462
  return await window.__sootsimShellPerf.stop()
463
- })()`);if(this.profilingEnabled=!1,e?.error)throw new Error(e.error);return e}async stopApp(){await this.reloadGuestApp(!1),await this.rearmCaptureAfterRuntimeReload()}async clearState(){await this.reloadGuestApp(!0),await this.rearmCaptureAfterRuntimeReload()}clearKeychain(){console.warn("[flow] clearKeychain: sootsim 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=b.resolve(this.opts.flowDir,t.file),i=S.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?lt(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"?ct(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),u=1e4,p=this.runStepInner(s),g;if(l){let m=await p;typeof m=="string"&&(g=m)}else{let m=null,P=new Promise((k,ne)=>{m=setTimeout(()=>{ne(new Error(`step watchdog: ${i} made no progress in ${u}ms \u2014 bridge or bundle probably hung`))},u)});try{let k=await Promise.race([p,P]);typeof k=="string"&&(g=k)}finally{m&&clearTimeout(m)}}let F=!!(s.assertVisible||s.assertNotVisible||s.extendedWaitUntil||s.waitFor);this.stepDelay>0&&!F&&await f(this.stepDelay),this.recordFlowTraceStep({stepIndex:t,stepName:i,targetLabel:a,startedAtMs:o,status:"success",screenshotPath:g})}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=b.resolve(this.opts.flowDir,r),l=S.readFileSync(s,"utf8"),u=this.opts.flowDir;this.opts.flowDir=b.dirname(s);try{await this.runFlow(Ut(l))}finally{this.opts.flowDir=u}}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"?ct(a):a,u=Object.keys(l).find(p=>p!=="when")??Object.keys(l)[0];return{index:s,name:u,target:this.flowStepTargetLabel(l,u)}})),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=Math.max(6e4,i+15e3,o+15e3);this.liveStatus&&(await this.liveStatus.waitWhilePaused(),await this.liveStatus.step(t,"running"));let s=Date.now(),l=async(u,p)=>{if(!this.liveStatus)return;let g=this.flowTraceSteps[this.flowTraceSteps.length-1],F=g&&g.stepIndex===t&&g.startedAtMs>=s;await this.liveStatus.step(t,u?"failure":F&&g.status==="skipped"?"skipped":"success",{durationMs:Date.now()-s,error:u?p instanceof Error?p.message.slice(0,300):String(p).slice(0,300):F&&g.error||void 0})};try{r.runFlow||r.launchApp?await this.runStep(r,t):await Promise.race([this.runStep(r,t),new Promise((u,p)=>setTimeout(()=>p(new Error(`step ${t+1} (${Object.keys(r)[0]}) exceeded ${a}ms deadline`)),a))])}catch(u){throw await l(!0,u),u}await l(!1)}}};var ie=class{constructor(e,t){this.bridge=e;this.flowName=t}disabled=!1;paused=!1;runId=`flr_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`;async push(e){if(!this.disabled)try{let t=await this.bridge.send({type:"flowStatus",status:{runId:this.runId,flowName:this.flowName,...e}});this.paused=t?.control?.paused===!0}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){await this.push({phase:"plan",state:"running",steps:e})}async step(e,t,r){await this.push({phase:"step",state:"running",step:{index:e,status:t,...r}})}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 Fe=null;function _r(){return Fe}var Ie=[];function Dr(){return Ie}async function Vt(n){if(!n)return"";let e=n.trim();if(!e)return"";if(/^\d+$/.test(e)||e.startsWith("http://")||e.startsWith("https://"))return e;let r=(await Ce()).find(i=>i.name.toLowerCase()===e.toLowerCase());return r?String(r.preferredPort):e}async function Jt(){let n=await He(),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 ut(n){Fe=null,Ie=[],(n.length===0||n.includes("--help")||n.includes("-h"))&&(console.log(`
463
+ })()`);if(this.profilingEnabled=!1,e?.error)throw new Error(e.error);return e}async stopApp(){await this.reloadGuestApp(!1),await this.rearmCaptureAfterRuntimeReload()}async clearState(){await this.reloadGuestApp(!0),await this.rearmCaptureAfterRuntimeReload()}clearKeychain(){console.warn("[flow] clearKeychain: sootsim has no keychain surface \u2014 no-op (warning)")}async copyTextFrom(e){let t=typeof e=="string"?{id:e}:e,i=await this.findElement(t);if(!i)throw new Error(`copyTextFrom: element not found: ${JSON.stringify(t)}`);let n=i.text??i.testID??"";this.js.setCopiedText(n),this.js.putEnv("maestroCopiedText",n),console.log(`[flow] copied text: ${JSON.stringify(n)}`)}evalScript(e){let i=/(?<!\\)\$\{[^$]*\}/.test(e)?this.js.evaluateStringTemplate(e):this.js.evaluate(e);i!==void 0&&i!==""&&console.log("[flow] evalScript ->",i)}runScript(e){let t=typeof e=="string"?{file:e}:e;if(!t.file)throw new Error("runScript requires a file");let i=b.resolve(this.opts.flowDir,t.file),n=S.readFileSync(i,"utf8");this.js.evaluate(n,{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 i=await this.callTest("openDeepLink",t);if(!i?.ok)throw new Error(`openLink failed: ${i?.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?lt(e.true):!0}isOptional(e){if(e.optional===!0)return!0;let i=Object.entries(e).find(([o])=>o!=="when"&&o!=="optional"),n=i?i[1]:void 0;return!!(n&&typeof n=="object"&&"optional"in n&&n.optional)}async runStep(e,t){let i=typeof e=="string"?ct(e):e,n=Object.keys(i).find(l=>l!=="when")||Object.keys(i)[0];console.log(`[flow] step ${t+1}: ${n}`);let o=Date.now(),a=this.flowStepTargetLabel(i,n),s;try{s=this.js.interpolateStep(i),a=this.flowStepTargetLabel(s,n)??a}catch(l){if(this.isOptional(i)){console.log(`[flow] (optional, skipped: ${l.message.slice(0,80)})`),this.recordFlowTraceStep({stepIndex:t,stepName:n,targetLabel:a,startedAtMs:o,status:"skipped",error:l});return}throw this.lastFailedStep={index:t,kind:n,target:i[n]},this.recordFlowTraceStep({stepIndex:t,stepName:n,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:n,targetLabel:a,startedAtMs:o,status:"skipped"});return}try{let l=!!(s.extendedWaitUntil||s.waitFor||s.scrollUntilVisible||s.launchApp||s.runFlow||s.runScript),u=1e4,p=this.runStepInner(s),g;if(l){let m=await p;typeof m=="string"&&(g=m)}else{let m=null,P=new Promise((k,re)=>{m=setTimeout(()=>{re(new Error(`step watchdog: ${n} made no progress in ${u}ms \u2014 bridge or bundle probably hung`))},u)});try{let k=await Promise.race([p,P]);typeof k=="string"&&(g=k)}finally{m&&clearTimeout(m)}}let F=!!(s.assertVisible||s.assertNotVisible||s.extendedWaitUntil||s.waitFor);this.stepDelay>0&&!F&&await f(this.stepDelay),this.recordFlowTraceStep({stepIndex:t,stepName:n,targetLabel:a,startedAtMs:o,status:"success",screenshotPath:g})}catch(l){if(this.isOptional(s)){console.log(`[flow] (optional, skipped: ${l.message.slice(0,80)})`),this.recordFlowTraceStep({stepIndex:t,stepName:n,targetLabel:a,startedAtMs:o,status:"skipped",error:l});return}throw this.lastFailedStep={index:t,kind:n,target:s[n]},this.recordFlowTraceStep({stepIndex:t,stepName:n,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,i=t==null||t===""?Number.MAX_SAFE_INTEGER:Number(t);if(!Number.isFinite(i))throw new Error(`repeat.times is not a number: ${t}`);let n=e.repeat.when??e.repeat.condition,o=async()=>n?this.evaluateWhen(n):!0,a=n?i:Math.min(i,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,i=typeof t=="string"?void 0:t.when;if(i&&!await this.evaluateWhen(i)){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,i=typeof t=="string"?t:t.file,n=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): ${i??"inline commands"}`);return}if(!i&&!n)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(i){let s=b.resolve(this.opts.flowDir,i),l=S.readFileSync(s,"utf8"),u=this.opts.flowDir;this.opts.flowDir=b.dirname(s);try{await this.runFlow(jt(l))}finally{this.opts.flowDir=u}}else if(n)for(let s=0;s<n.length;s++)await this.runStep(n[s],s)}finally{this.js.leaveEnvScope()}}else throw new Error(`unsupported flow step: ${JSON.stringify(e)}`)}}liveStatus=null;async runFlow(e){let t=[],i=[],n=[];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)){i.push(...a.onFlowComplete);continue}n.push(a)}if(this.liveStatus&&await this.liveStatus.plan(n.map((a,s)=>{let l=typeof a=="string"?ct(a):a,u=Object.keys(l).find(p=>p!=="when")??Object.keys(l)[0];return{index:s,name:u,target:this.flowStepTargetLabel(l,u)}})),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(n)}catch(a){o=a instanceof Error?a:new Error(String(a))}if(i.length>0){console.log(`[flow] onFlowComplete (${i.length} steps)`);for(let a=0;a<i.length;a++)try{await this.runStep(i[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 i=e[t],n=typeof i.wait=="number"?i.wait:0,o=typeof i.waitFor?.timeout=="number"?i.waitFor.timeout:0,a=Math.max(6e4,n+15e3,o+15e3);this.liveStatus&&(await this.liveStatus.waitWhilePaused(),await this.liveStatus.step(t,"running"));let s=Date.now(),l=async(u,p)=>{if(!this.liveStatus)return;let g=this.flowTraceSteps[this.flowTraceSteps.length-1],F=g&&g.stepIndex===t&&g.startedAtMs>=s;await this.liveStatus.step(t,u?"failure":F&&g.status==="skipped"?"skipped":"success",{durationMs:Date.now()-s,error:u?p instanceof Error?p.message.slice(0,300):String(p).slice(0,300):F&&g.error||void 0})};try{i.runFlow||i.launchApp?await this.runStep(i,t):await Promise.race([this.runStep(i,t),new Promise((u,p)=>setTimeout(()=>p(new Error(`step ${t+1} (${Object.keys(i)[0]}) exceeded ${a}ms deadline`)),a))])}catch(u){throw await l(!0,u),u}await l(!1)}}};function Ut(r){if(typeof r!="object"||r==null||!("control"in r))return!1;let e=r.control;return typeof e=="object"&&e!=null&&"paused"in e&&e.paused===!0}var ne=class{constructor(e,t,i){this.bridge=e;this.flowName=t;this.getSimId=i}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 i=await this.bridge.send({type:"flowStatus",simId:t,status:{runId:this.runId,flowName:this.flowName,...e}});this.paused=Ut(i)}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 i of this.completedSteps.values())await this.send({phase:"step",state:"running",step:i},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,i){let n={index:e,status:t,...i};await this.push({phase:"step",state:"running",step:n}),this.completedSteps.set(e,n)}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 Fe=null;function Di(){return Fe}var Ie=[];function Bi(){return Ie}async function Jt(r){if(!r)return"";let e=r.trim();if(!e)return"";if(/^\d+$/.test(e)||e.startsWith("http://")||e.startsWith("https://"))return e;let i=(await Ce()).find(n=>n.name.toLowerCase()===e.toLowerCase());return i?String(i.preferredPort):e}async function Gt(){let r=await He(),e=r.find(i=>i.patched);if(e)return`http://localhost:${e.port}/__soot/`;let t=r[0];return t?`http://localhost:${t.port}/__soot/`:null}async function ut(r){Fe=null,Ie=[],(r.length===0||r.includes("--help")||r.includes("-h"))&&(console.log(`
464
464
  sootsim maestro \u2014 author and run Maestro YAML flows
465
465
 
466
466
  usage:
@@ -540,28 +540,28 @@ flow extension:
540
540
  takeScreenshot:
541
541
  path: marketing/hero
542
542
  withFrame: true
543
- `),process.exit(0));let e=n[0];$.existsSync(e)||(console.error(` error: ${e} not found`),process.exit(1));let t=h=>n.find((c,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",u=n.includes("--no-shell")?"tenant":n.includes("--shell-only")?"shell":void 0,p=t("--device")?.trim()||"",g=n.includes("--slow")?+(t("--slow")||"500"):0,F=n.includes("--electron"),m=n.includes("--preview"),P=await rt(t("--preview-origin")),k=t("--preview-public-origin"),ne=n.includes("--preview-open"),$e=t("--owner")?.trim()||"",Pe=t("--repo")?.trim()||"",H=t("--billing-kind")?.trim()||"",pt=m?`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:${jt()}`}:flow:${Wt("sha256").update(w.relative(process.cwd(),w.resolve(e))).digest("hex").slice(0,16)}`:"";H&&H!=="test_run"&&(console.error(` error: invalid --billing-kind: ${H}`),process.exit(1));let ht=n.flatMap((h,c)=>n[c-1]==="--replace"?["--replace",h]:[]),ft=n.flatMap((h,c)=>n[c-1]==="--remap"?["--remap",h]:[]),M=n.includes("--record")||m,mt=n.includes("--tail-wait")?Math.max(0,+(t("--tail-wait")||"2000")):M?m?6e3:2e3:0,gt=$.readFileSync(e,"utf8"),{frontmatter:x,steps:R}=ge(gt);R.length===0&&(console.error(" error: flow file must contain a YAML array of steps"),process.exit(1));let U=p||x.device||"",ke=x.theme||"",q=F||x.electron===!0,wt=x.app===void 0||x.app===null?"":typeof x.app=="number"?String(x.app):x.app,oe=await Vt(wt),Ae={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=pe(n,Ae),yt=t("--url")||"";q&&!ze()&&(console.error(" error: desktop companion not found. install or build it first with `bun run build:electron`"),process.exit(1));let Me=q?"desktop companion":"bridge",bt=oe?` | target: ${oe}`:"";console.log(`
543
+ `),process.exit(0));let e=r[0];$.existsSync(e)||(console.error(` error: ${e} not found`),process.exit(1));let t=h=>r.find((c,y)=>r[y-1]===h),i=r.includes("--profile"),n=r.includes("--headed"),o=r.includes("--new")||n,a=t("--out")||"/tmp/sootsim-recordings",s=t("--screenshots")||(t("--out")?a:"/tmp/sootsim-flow"),l=t("--screenshot-paths")==="flow"?"flow":"dir",u=r.includes("--no-shell")?"tenant":r.includes("--shell-only")?"shell":void 0,p=t("--device")?.trim()||"",g=r.includes("--slow")?+(t("--slow")||"500"):0,F=r.includes("--electron"),m=r.includes("--preview"),P=await it(t("--preview-origin")),k=t("--preview-public-origin"),re=r.includes("--preview-open"),$e=t("--owner")?.trim()||"",Pe=t("--repo")?.trim()||"",H=t("--billing-kind")?.trim()||"",pt=m?`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:${Vt()}`}:flow:${Wt("sha256").update(w.relative(process.cwd(),w.resolve(e))).digest("hex").slice(0,16)}`:"";H&&H!=="test_run"&&(console.error(` error: invalid --billing-kind: ${H}`),process.exit(1));let ht=r.flatMap((h,c)=>r[c-1]==="--replace"?["--replace",h]:[]),ft=r.flatMap((h,c)=>r[c-1]==="--remap"?["--remap",h]:[]),M=r.includes("--record")||m,mt=r.includes("--tail-wait")?Math.max(0,+(t("--tail-wait")||"2000")):M?m?6e3:2e3:0,gt=$.readFileSync(e,"utf8"),{frontmatter:x,steps:R}=ge(gt);R.length===0&&(console.error(" error: flow file must contain a YAML array of steps"),process.exit(1));let j=p||x.device||"",ke=x.theme||"",q=F||x.electron===!0,wt=x.app===void 0||x.app===null?"":typeof x.app=="number"?String(x.app):x.app,oe=await Jt(wt),Ae={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=pe(r,Ae),yt=t("--url")||"";q&&!ze()&&(console.error(" error: desktop companion not found. install or build it first with `bun run build:electron`"),process.exit(1));let Me=q?"desktop companion":"bridge",bt=oe?` | target: ${oe}`:"";console.log(`
544
544
  sootsim maestro \u2014 ${w.basename(e)}
545
- ${R.length} steps | ${Me}${bt}${M?" | recording":""}${r?" | profiling":""}${g?` | ${g}ms delay`:""}
546
- `),m&&De({event:"preview_flow_started",properties:{flowName:w.basename(e),stepCount:R.length,mode:Me,electron:q,record:M,profile:r,previewOrigin:P}});let A=yt||oe||"",se=o||q&&v.simIdSource!=="flag",Re=t("--driver")||"",ae=!1,le=new Set,Oe=!1;if(!A&&!se&&v.simIdSource==="none"){let h=Je(v);try{let c=await h.listSims(),y=c.find(D=>D.isPrimary&&D.readyState==="open"),I=c.find(D=>D.readyState==="open"),V=y??I;V&&(Oe=!0,console.log(` reusing active sim: ${V.id}`))}catch{}finally{h.close()}}if(!A&&!Oe&&(se||v.simIdSource==="none")){let h=await Jt();h||(console.error(" error: no current sim and no sootsim target found"),await de(),process.exit(1)),A=h}if(A&&U){let h=new URL(await Ke(A));h.searchParams.set("device",U),A=h.toString()}if(A){let h=[A];if(h.push(...ht),h.push(...ft),se&&h.push("--new"),h.push("--no-describe"),v.simIdSource==="flag"&&v.simId&&h.push("--sim",v.simId),Re&&(h.push("--driver",Re),ae=!0),n.includes("--headless")&&!i&&h.push("--headless"),await Ye(h,{port:v.wsPort,timeoutMs:v.commandTimeoutMs}),ae){let c=ue();c&&le.add(c)}}let B=pe(n,Ae),Y=B.simIdSource==="flag"?B.simId:ue()||B.simId,St=B.simIdSource==="flag"?"flag":Y?"saved":"none",T=he(B.wsPort,{commandTimeoutMs:B.commandTimeoutMs,simId:Y,simIdSource:St}),d,_e=async()=>{if(ke&&await T.send({type:"call",simId:d.simId,path:"SootSim.bridges.settings.set",args:["colorScheme",ke]}),!U)return!1;let h=await T.send({type:"evaluate",simId:d.simId,code:"window.location.href"});if(typeof h=="string"&&h.length>0){let c=new URL(h);c.searchParams.set("device",U),d.setSimRouteHint(c.toString())}return!!await T.send({type:"call",simId:d.simId,path:"SootSim.bridges.settings.set",args:["deviceModel",U]})};if(d=new re(T,{screenshotDir:s,flowDir:w.dirname(w.resolve(e)),screenshotPathMode:l,screenshotLayers:u,simId:Y,recordingOutputDir:M?a:void 0,recordingFormat:m?"mp4":"webm",billingOriginOverride:m?P:void 0,allowGitHubRecording:m,requireRecordingEntitlement:m,onAfterLaunch:async()=>{await _e()&&await d.waitForTree(12e4),m&&await T.send({type:"evaluate",simId:d.simId,code:`(() => {
545
+ ${R.length} steps | ${Me}${bt}${M?" | recording":""}${i?" | profiling":""}${g?` | ${g}ms delay`:""}
546
+ `),m&&De({event:"preview_flow_started",properties:{flowName:w.basename(e),stepCount:R.length,mode:Me,electron:q,record:M,profile:i,previewOrigin:P}});let A=yt||oe||"",se=o||q&&v.simIdSource!=="flag",Re=t("--driver")||"",ae=!1,le=new Set,Oe=!1;if(!A&&!se&&v.simIdSource==="none"){let h=Je(v);try{let c=await h.listSims(),y=c.find(D=>D.isPrimary&&D.readyState==="open"),I=c.find(D=>D.readyState==="open"),V=y??I;V&&(Oe=!0,console.log(` reusing active sim: ${V.id}`))}catch{}finally{h.close()}}if(!A&&!Oe&&(se||v.simIdSource==="none")){let h=await Gt();h||(console.error(" error: no current sim and no sootsim target found"),await de(),process.exit(1)),A=h}if(A&&j){let h=new URL(await Ke(A));h.searchParams.set("device",j),A=h.toString()}if(A){let h=[A];if(h.push(...ht),h.push(...ft),se&&h.push("--new"),h.push("--no-describe"),v.simIdSource==="flag"&&v.simId&&h.push("--sim",v.simId),Re&&(h.push("--driver",Re),ae=!0),r.includes("--headless")&&!n&&h.push("--headless"),await Ye(h,{port:v.wsPort,timeoutMs:v.commandTimeoutMs}),ae){let c=ue();c&&le.add(c)}}let B=pe(r,Ae),Y=B.simIdSource==="flag"?B.simId:ue()||B.simId,St=B.simIdSource==="flag"?"flag":Y?"saved":"none",T=he(B.wsPort,{commandTimeoutMs:B.commandTimeoutMs,simId:Y,simIdSource:St}),d,_e=async()=>{if(ke&&await T.send({type:"call",simId:d.simId,path:"SootSim.bridges.settings.set",args:["colorScheme",ke]}),!j)return!1;let h=await T.send({type:"evaluate",simId:d.simId,code:"window.location.href"});if(typeof h=="string"&&h.length>0){let c=new URL(h);c.searchParams.set("device",j),d.setSimRouteHint(c.toString())}return!!await T.send({type:"call",simId:d.simId,path:"SootSim.bridges.settings.set",args:["deviceModel",j]})};if(d=new ie(T,{screenshotDir:s,flowDir:w.dirname(w.resolve(e)),screenshotPathMode:l,screenshotLayers:u,simId:Y,recordingOutputDir:M?a:void 0,recordingFormat:m?"mp4":"webm",billingOriginOverride:m?P:void 0,allowGitHubRecording:m,requireRecordingEntitlement:m,onAfterLaunch:async()=>{await _e()&&await d.waitForTree(12e4),m&&await T.send({type:"evaluate",simId:d.simId,code:`(() => {
547
547
  const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
548
548
  return r?.start?.() ?? false
549
- })()`})}}),g&&(d.stepDelay=g),d.liveStatus=new ie(T,w.basename(e)),d.js.putEnv("MAESTRO_FILENAME",w.basename(e,w.extname(e))),x.env&&typeof x.env=="object")for(let[h,c]of Object.entries(x.env))d.js.putEnv(h,c);let O=null,E=null,L=null,_=null,W=null,ce=null,j=0,Z=!!R[0]?.launchApp;try{Z||await d.waitForTree(12e4),await _e()&&!Z&&await d.waitForTree(12e4),m&&!Z&&!process.env.SOOTSIM_PREVIEW_RESET_DONE&&await d.launchApp({clearState:!0}),M&&(Z?d.prepareRecording():await d.startRecording()),r&&await d.startProfile(),m&&(await T.send({type:"evaluate",simId:d.simId,code:`(() => {
549
+ })()`})}}),g&&(d.stepDelay=g),d.liveStatus=new ne(T,w.basename(e),()=>d.simId),d.js.putEnv("MAESTRO_FILENAME",w.basename(e,w.extname(e))),x.env&&typeof x.env=="object")for(let[h,c]of Object.entries(x.env))d.js.putEnv(h,c);let O=null,E=null,L=null,_=null,U=null,ce=null,W=0,Z=!!R[0]?.launchApp;try{Z||await d.waitForTree(12e4),await _e()&&!Z&&await d.waitForTree(12e4),m&&!Z&&!process.env.SOOTSIM_PREVIEW_RESET_DONE&&await d.launchApp({clearState:!0}),M&&(Z?d.prepareRecording():await d.startRecording()),i&&await d.startProfile(),m&&(await T.send({type:"evaluate",simId:d.simId,code:`(() => {
550
550
  const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
551
551
  return r?.start?.() ?? false
552
- })()`})||console.warn(" warn: eventRecorder.start() returned false \u2014 preview will upload bundle without replay events")),await d.runFlow(R),r&&(O=await d.stopProfile()),await d.waitForRecordingTail({maxMs:mt,smart:m}),M&&(E=await d.stopRecording(),L=d.getLastRecordingDurationMs()),m&&(_=await T.send({type:"evaluate",simId:d.simId,code:`(() => {
552
+ })()`})||console.warn(" warn: eventRecorder.start() returned false \u2014 preview will upload bundle without replay events")),await d.runFlow(R),i&&(O=await d.stopProfile()),await d.waitForRecordingTail({maxMs:mt,smart:m}),M&&(E=await d.stopRecording(),L=d.getLastRecordingDurationMs()),m&&(_=await T.send({type:"evaluate",simId:d.simId,code:`(() => {
553
553
  const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
554
554
  return r?.stop?.() ?? []
555
- })()`}),console.log(` captured ${_.length} replay events`),W=w.join(s,"preview-final.png"),await d.captureScreenshot(W),console.log(` final screenshot: ${W}`));let c=R.filter(y=>y&&typeof y=="object"&&"takeScreenshot"in y).length;console.log(`
556
- + completed (${R.length} steps)`),c>0&&console.log(` screenshots: ${c} \u2192 ${s}`),O&&dt(O),E&&console.log(` video: ${E}`),console.log()}catch(h){if(r&&!O)try{O=await d.stopProfile()}catch{}if(M&&!E)try{E=await d.stopRecording(),L=d.getLastRecordingDurationMs()}catch(c){console.warn(` recording stop failed: ${c?.message||String(c)}`)}if(m&&!_)try{_=await T.send({type:"evaluate",simId:d.simId,code:`(() => {
555
+ })()`}),console.log(` captured ${_.length} replay events`),U=w.join(s,"preview-final.png"),await d.captureScreenshot(U),console.log(` final screenshot: ${U}`));let c=R.filter(y=>y&&typeof y=="object"&&"takeScreenshot"in y).length;console.log(`
556
+ + completed (${R.length} steps)`),c>0&&console.log(` screenshots: ${c} \u2192 ${s}`),O&&dt(O),E&&console.log(` video: ${E}`),console.log()}catch(h){if(i&&!O)try{O=await d.stopProfile()}catch{}if(M&&!E)try{E=await d.stopRecording(),L=d.getLastRecordingDurationMs()}catch(c){console.warn(` recording stop failed: ${c?.message||String(c)}`)}if(m&&!_)try{_=await T.send({type:"evaluate",simId:d.simId,code:`(() => {
557
557
  const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
558
558
  return r?.stop?.() ?? []
559
559
  })()`}),console.log(` captured ${_.length} partial replay events`)}catch(c){console.warn(` event recorder stop failed: ${c?.message||String(c)}`)}console.error(`
560
560
  x failed: ${h.message}
561
- `),O&&(console.log(" partial profile:"),dt(O)),E&&console.log(` partial video: ${E}`);try{let c=d.lastFailedStep,y=c?`step-${String(c.index+1).padStart(2,"0")}-${c.kind}`:"unstaged",I=w.join(s,y);await d.captureFailureBundle(I,{error:h,stepIndex:c?.index,stepKind:c?.kind,stepTarget:c?.target}),ce=I,console.log(` failure bundle: ${I}`),console.log(" (contents: screenshot.png, describe.json, a11y.txt, tree.txt, console.json, error.json)")}catch(c){try{let y=w.join(s,"error.png");await d.captureScreenshot(y),console.log(` error screenshot: ${y}`)}catch{}console.log(` (failure bundle capture failed: ${c instanceof Error?c.message:String(c)})`)}await Ge(T,{errorsCommand:`sootsim get errors 5${d.simId?` --sim ${d.simId}`:""}`,warningsCommand:`sootsim get warnings 5${d.simId?` --sim ${d.simId}`:""}`,requestsCommand:`sootsim get requests 5${d.simId?` --sim ${d.simId}`:""}`}),j=1}if(await d.liveStatus?.end(j===0?"passed":"failed"),m&&(j===0||E||_))try{let h=await zt(_??[]),c=["--origin",P,"--events",h];k&&c.push("--public-origin",k),E&&c.push("--video",E),W&&c.push("--screenshot",W),E&&L&&Number.isFinite(L)&&(c.push("--video-duration-ms",String(Math.round(L))),c.push("--recorded-duration-ms",String(Math.round(L))));let y=d.getLastRecordingStartedAtMs();y&&Number.isFinite(y)&&c.push("--recording-started-at-ms",String(Math.round(y))),v.wsPort&&c.push("--port",String(v.wsPort)),d.simId&&c.push("--sim",d.simId),ne&&c.push("--open"),$e&&c.push("--owner",$e),Pe&&c.push("--repo",Pe),c.push("--run-scope",pt),H&&c.push("--billing-kind",H),console.log(`
562
- preparing preview upload\u2026`);let I=d.getFlowTraceSteps();I.length>0&&c.push("--timeline-events",await Kt(I));let V=await qt(I,y);V&&c.push("--snapshot-manifest",V),ce&&c.push("--failure-bundle",ce);let D=d.getLastRecordingFrameStats();D&&c.push("--trace-frame-stats",await Yt(D));let{runUpload:vt}=await import("./upload-ZKKGG3CU.js");Fe=await vt(c,{})}catch(h){console.error(` preview upload failed: ${h?.message||h}`),j=1}return Ie=d.getFlowTraceSteps(),T.close(),ae?(d.simId&&le.add(d.simId),await Gt(v.wsPort,v.commandTimeoutMs,[...le])):d.simId&&d.simId!==Y&&Ne(d.simId),await de(),j}async function Gt(n,e,t){let r=[...new Set(t.filter(Boolean))];if(r.length===0)return;let i=he(n,{commandTimeoutMs:e});try{let o=await i.listSims(),a=r.filter(l=>o.some(u=>u.id===l&&u.readyState==="open"));if(a.length===0)return;let s=await Ze(i,n,e,a);await qe(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 zt(n){let{gzipSync:e}=await import("zlib"),t=n.map(o=>JSON.stringify(o)).join(`
563
- `)+(n.length?`
564
- `:""),r=e(Buffer.from(t,"utf8")),i=w.join(K(),`sootsim-events-${Date.now()}.jsonl.gz`);return $.writeFileSync(i,r),console.log(` events: ${n.length} written to ${i} (${r.length} bytes gz)`),i}async function Kt(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(`
561
+ `),O&&(console.log(" partial profile:"),dt(O)),E&&console.log(` partial video: ${E}`);try{let c=d.lastFailedStep,y=c?`step-${String(c.index+1).padStart(2,"0")}-${c.kind}`:"unstaged",I=w.join(s,y);await d.captureFailureBundle(I,{error:h,stepIndex:c?.index,stepKind:c?.kind,stepTarget:c?.target}),ce=I,console.log(` failure bundle: ${I}`),console.log(" (contents: screenshot.png, describe.json, a11y.txt, tree.txt, console.json, error.json)")}catch(c){try{let y=w.join(s,"error.png");await d.captureScreenshot(y),console.log(` error screenshot: ${y}`)}catch{}console.log(` (failure bundle capture failed: ${c instanceof Error?c.message:String(c)})`)}await Ge(T,{errorsCommand:`sootsim get errors 5${d.simId?` --sim ${d.simId}`:""}`,warningsCommand:`sootsim get warnings 5${d.simId?` --sim ${d.simId}`:""}`,requestsCommand:`sootsim get requests 5${d.simId?` --sim ${d.simId}`:""}`}),W=1}if(await d.liveStatus?.end(W===0?"passed":"failed"),m&&(W===0||E||_))try{let h=await Kt(_??[]),c=["--origin",P,"--events",h];k&&c.push("--public-origin",k),E&&c.push("--video",E),U&&c.push("--screenshot",U),E&&L&&Number.isFinite(L)&&(c.push("--video-duration-ms",String(Math.round(L))),c.push("--recorded-duration-ms",String(Math.round(L))));let y=d.getLastRecordingStartedAtMs();y&&Number.isFinite(y)&&c.push("--recording-started-at-ms",String(Math.round(y))),v.wsPort&&c.push("--port",String(v.wsPort)),d.simId&&c.push("--sim",d.simId),re&&c.push("--open"),$e&&c.push("--owner",$e),Pe&&c.push("--repo",Pe),c.push("--run-scope",pt),H&&c.push("--billing-kind",H),console.log(`
562
+ preparing preview upload\u2026`);let I=d.getFlowTraceSteps();I.length>0&&c.push("--timeline-events",await qt(I));let V=await Yt(I,y);V&&c.push("--snapshot-manifest",V),ce&&c.push("--failure-bundle",ce);let D=d.getLastRecordingFrameStats();D&&c.push("--trace-frame-stats",await Zt(D));let{runUpload:vt}=await import("./upload-LGZORNQI.js");Fe=await vt(c,{})}catch(h){console.error(` preview upload failed: ${h?.message||h}`),W=1}return Ie=d.getFlowTraceSteps(),T.close(),ae?(d.simId&&le.add(d.simId),await zt(v.wsPort,v.commandTimeoutMs,[...le])):d.simId&&d.simId!==Y&&Ne(d.simId),await de(),W}async function zt(r,e,t){let i=[...new Set(t.filter(Boolean))];if(i.length===0)return;let n=he(r,{commandTimeoutMs:e});try{let o=await n.listSims(),a=i.filter(l=>o.some(u=>u.id===l&&u.readyState==="open"));if(a.length===0)return;let s=await Ze(n,r,e,a);await qe(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{n.close()}}async function Kt(r){let{gzipSync:e}=await import("zlib"),t=r.map(o=>JSON.stringify(o)).join(`
563
+ `)+(r.length?`
564
+ `:""),i=e(Buffer.from(t,"utf8")),n=w.join(K(),`sootsim-events-${Date.now()}.jsonl.gz`);return $.writeFileSync(n,i),console.log(` events: ${r.length} written to ${n} (${i.length} bytes gz)`),n}async function qt(r){let{gzipSync:e}=await import("zlib"),t=r.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}:{}}})),i=t.map(a=>JSON.stringify(a)).join(`
565
565
  `)+`
566
- `,i=e(Buffer.from(r,"utf8")),o=w.join(K(),`sootsim-flow-steps-${Date.now()}.jsonl.gz`);return $.writeFileSync(o,i),console.log(` flow trace: ${t.length} step events written to ${o} (${i.length} bytes gz)`),o}async function qt(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(K(),`sootsim-flow-snapshots-${Date.now()}.json`);return $.writeFileSync(r,JSON.stringify(t)),console.log(` flow snapshots: ${t.length} written to ${r}`),r}async function Yt(n){let e=w.join(K(),`sootsim-frame-stats-${Date.now()}.json`);return $.writeFileSync(e,JSON.stringify(n)),console.log(` frame stats: written to ${e}`),e}async function Zt(n){let e=n[0],t=r=>n.find((i,o)=>n[o-1]===r);switch(e){case"start":{let{path:r,state:i}=Qe();console.log(" flow draft started"),console.log(` session: ${r}`),console.log(` steps: ${i.steps.length}`);return}case"keep":case"good":{let r=be();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=be();a.active&&a.kept&&console.log(` auto-kept trailing action: ${a.candidate.summary}`);let s=et(r||(i?Qt():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=er(n,s.outputPath),u=await ut(l);if(u!==0){console.error(`
567
- validation failed \u2014 draft preserved so you can keep iterating`),process.exitCode=u;return}ye(),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(ye(),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=we(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 Xt(n){return n[0]==="--sim"&&n.length>=2?[...n.slice(2),"--sim",n[1]]:n}async function Br(n){let e=Xt(n),t=e[0];if(t==="start"||t==="keep"||t==="good"||t==="end"||t==="validate")return await Zt(e),0;let r=await ut(e);return r!==0&&(process.exitCode=r),r}function dt(n){console.log(""),tt(n)}function Qt(){return w.join(K(),`sootsim-flow-draft-${Date.now()}.yaml`)}function er(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{st as a,kt as b,_r as c,Dr as d,Jt as e,ut as f,Xt as g,Br as h};
566
+ `,n=e(Buffer.from(i,"utf8")),o=w.join(K(),`sootsim-flow-steps-${Date.now()}.jsonl.gz`);return $.writeFileSync(o,n),console.log(` flow trace: ${t.length} step events written to ${o} (${n.length} bytes gz)`),o}async function Yt(r,e){if(!e)return null;let t=r.flatMap(n=>n.screenshotPath?[{id:`flow-step-${n.stepIndex}`,label:n.targetLabel??`Step ${n.stepIndex+1}`,kind:"interaction",t:Math.max(0,n.endedAtMs-e),path:n.screenshotPath}]:[]);if(t.length===0)return null;let i=w.join(K(),`sootsim-flow-snapshots-${Date.now()}.json`);return $.writeFileSync(i,JSON.stringify(t)),console.log(` flow snapshots: ${t.length} written to ${i}`),i}async function Zt(r){let e=w.join(K(),`sootsim-frame-stats-${Date.now()}.json`);return $.writeFileSync(e,JSON.stringify(r)),console.log(` frame stats: written to ${e}`),e}async function Xt(r){let e=r[0],t=i=>r.find((n,o)=>r[o-1]===i);switch(e){case"start":{let{path:i,state:n}=Qe();console.log(" flow draft started"),console.log(` session: ${i}`),console.log(` steps: ${n.steps.length}`);return}case"keep":case"good":{let i=be();if(i.active||(console.error(" no active flow draft \u2014 run `sootsim maestro start` first"),process.exit(1)),!i.kept){console.log(" no pending action to keep");return}console.log(` kept: ${i.candidate.summary}`),console.log(` steps: ${i.stepCount}`);return}case"end":{let i=t("--output")||(r[1]&&!r[1].startsWith("-")?r[1]:void 0),n=r.includes("--validate")||r.includes("--video"),o=r.includes("--video"),a=be();a.active&&a.kept&&console.log(` auto-kept trailing action: ${a.candidate.summary}`);let s=et(i||(n?ei():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(n){let l=ti(r,s.outputPath),u=await ut(l);if(u!==0){console.error(`
567
+ validation failed \u2014 draft preserved so you can keep iterating`),process.exitCode=u;return}ye(),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(ye(),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 i=r[1];(!i||i.startsWith("-"))&&(console.error(" usage: sootsim maestro validate <path>"),process.exit(1));let n=we(i);if(n.length>0){console.error(` x ${i} failed validation:`);for(let o of n)console.error(` - ${o}`);process.exit(1)}console.log(` + ${i} looks valid`);return}}}function Qt(r){return r[0]==="--sim"&&r.length>=2?[...r.slice(2),"--sim",r[1]]:r}async function Li(r){let e=Qt(r),t=e[0];if(t==="start"||t==="keep"||t==="good"||t==="end"||t==="validate")return await Xt(e),0;let i=await ut(e);return i!==0&&(process.exitCode=i),i}function dt(r){console.log(""),tt(r)}function ei(){return w.join(K(),`sootsim-flow-draft-${Date.now()}.yaml`)}function ti(r,e){if(!e)throw new Error("validated flow draft requires an output path");let t=[e];for(let i=1;i<r.length;i++){let n=r[i];if(!(n==="--validate"||n==="--video")){if(n==="--output"){i+=1;continue}i===1&&!n.startsWith("-")||t.push(n)}}return!t.includes("--record")&&r.includes("--video")&&t.push("--record"),t}export{st as a,kt as b,Di as c,Bi as d,Gt as e,ut as f,Qt as g,Li as h};
@@ -1,2 +1,2 @@
1
- /*! sootsim v0.1.220 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
1
+ /*! sootsim v0.1.222 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
2
  import{readFileSync as i}from"node:fs";import{fileURLToPath as e}from"node:url";var r=null;function l(){if(r!=null)return r;let o=[()=>e(import.meta.resolve("sootsim/package.json")),()=>e(new URL("../package.json",import.meta.url))];for(let n of o)try{let t=JSON.parse(i(n(),"utf8")).version;if(typeof t=="string"&&t)return r=t,r}catch{}return r="0.0.0",r}export{l as a};