sootsim 0.1.148 → 0.1.150

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 (153) hide show
  1. package/dist-cli/bin.js +3 -3
  2. package/dist-cli/chunks/{agent-A5AQOHSI.js → agent-LSSBQD6J.js} +2 -2
  3. package/dist-cli/chunks/{agent-wrapper-S6AUOIXU.js → agent-wrapper-HYZ3VS4M.js} +2 -2
  4. package/dist-cli/chunks/{app-fonts-MQDZ55OI.js → app-fonts-XXHCZZVE.js} +2 -2
  5. package/dist-cli/chunks/{assert-USJNKN7R.js → assert-7I2ANKDG.js} +2 -2
  6. package/dist-cli/chunks/auto-bootstrap-YJM7QYAO.js +2 -0
  7. package/dist-cli/chunks/beta-EQOZMXP3.js +2 -0
  8. package/dist-cli/chunks/{camera-C4SKSA76.js → camera-4D7T4PZW.js} +2 -2
  9. package/dist-cli/chunks/{chunk-BCWW5RSQ.js → chunk-36L4ANT2.js} +1 -1
  10. package/dist-cli/chunks/{chunk-AXLTLDHE.js → chunk-3CENW2HN.js} +2 -2
  11. package/dist-cli/chunks/{chunk-A57WJDB2.js → chunk-3J5I64W6.js} +2 -2
  12. package/dist-cli/chunks/{chunk-BCRYE4YH.js → chunk-3K237XV5.js} +1 -1
  13. package/dist-cli/chunks/{chunk-KZ6AQHHA.js → chunk-3MWCUIK4.js} +2 -2
  14. package/dist-cli/chunks/{chunk-BWE6H36P.js → chunk-3RRDJNXM.js} +2 -2
  15. package/dist-cli/chunks/{chunk-TWOGFNQ7.js → chunk-45XLWBNT.js} +1 -1
  16. package/dist-cli/chunks/{chunk-NOBEILT5.js → chunk-5Q464MLB.js} +1 -1
  17. package/dist-cli/chunks/{chunk-ZNYPWEMX.js → chunk-65GDTEX7.js} +3 -3
  18. package/dist-cli/chunks/{chunk-YXZD545S.js → chunk-6SXJQK5R.js} +3 -3
  19. package/dist-cli/chunks/{chunk-PMM6MNCR.js → chunk-6UA5JZ4E.js} +2 -2
  20. package/dist-cli/chunks/{chunk-GXHVONDU.js → chunk-7YEISEQ2.js} +2 -2
  21. package/dist-cli/chunks/chunk-B43JOK5N.js +119 -0
  22. package/dist-cli/chunks/{chunk-IYRFX6KX.js → chunk-BFGPENAX.js} +1 -1
  23. package/dist-cli/chunks/{chunk-T4FJHKU4.js → chunk-BUKMAGA6.js} +2 -2
  24. package/dist-cli/chunks/{chunk-NK6RKGX2.js → chunk-BWVKFTFM.js} +1 -1
  25. package/dist-cli/chunks/{chunk-TYHRA7FX.js → chunk-CDLPRRMH.js} +2 -2
  26. package/dist-cli/chunks/{chunk-4T5Q2CUU.js → chunk-DNTULI35.js} +1 -1
  27. package/dist-cli/chunks/{chunk-G5BKDQGP.js → chunk-GXFEY4YV.js} +1 -1
  28. package/dist-cli/chunks/chunk-H5YQDCRA.js +1 -0
  29. package/dist-cli/chunks/{chunk-2SDVI2JB.js → chunk-IADOI73U.js} +2 -2
  30. package/dist-cli/chunks/{chunk-S3WEUJM3.js → chunk-IIJQQIAP.js} +2 -2
  31. package/dist-cli/chunks/{chunk-2OJ53PGA.js → chunk-JPWK6SFZ.js} +1 -1
  32. package/dist-cli/chunks/{chunk-ZMG6VGYA.js → chunk-KIDONDPE.js} +2 -2
  33. package/dist-cli/chunks/{chunk-U2U22DTV.js → chunk-KO4VABY3.js} +1 -1
  34. package/dist-cli/chunks/{chunk-23QZQBTT.js → chunk-LBZGVNQE.js} +1 -1
  35. package/dist-cli/chunks/{chunk-K4QZ6WX6.js → chunk-LPVQM4H7.js} +2 -2
  36. package/dist-cli/chunks/{chunk-XYFPDYAI.js → chunk-MFPT2P6I.js} +1 -1
  37. package/dist-cli/chunks/{chunk-F3MFOV7R.js → chunk-NHDDW7WP.js} +1 -1
  38. package/dist-cli/chunks/{chunk-4JVDEEJJ.js → chunk-NI2TIFUK.js} +1 -1
  39. package/dist-cli/chunks/{chunk-UK7GX57G.js → chunk-NISJ26VT.js} +7 -32
  40. package/dist-cli/chunks/{chunk-NMN4JPG2.js → chunk-NK5T7NYR.js} +1 -1
  41. package/dist-cli/chunks/{chunk-CN3ACF52.js → chunk-NSEXBZUW.js} +2 -2
  42. package/dist-cli/chunks/chunk-OYWQKX2A.js +2 -0
  43. package/dist-cli/chunks/{chunk-YONGHIDE.js → chunk-PFFELWZN.js} +2 -2
  44. package/dist-cli/chunks/{chunk-Y5E53BEN.js → chunk-PGAGVXOZ.js} +2 -2
  45. package/dist-cli/chunks/chunk-PHRIZLTZ.js +1 -0
  46. package/dist-cli/chunks/{chunk-7EBPIOTW.js → chunk-QIGU47UD.js} +1 -1
  47. package/dist-cli/chunks/{chunk-BDKC2GLL.js → chunk-VJRAGYZ6.js} +2 -2
  48. package/dist-cli/chunks/{chunk-474QHKFY.js → chunk-WNJOX4AQ.js} +2 -2
  49. package/dist-cli/chunks/chunk-WQF5CLFD.js +463 -0
  50. package/dist-cli/chunks/{chunk-IQVOFR7U.js → chunk-WZ5JKRIA.js} +2 -2
  51. package/dist-cli/chunks/chunk-YKWGZWBE.js +1 -0
  52. package/dist-cli/chunks/{chunk-XWUUFV45.js → chunk-YLSVHL4W.js} +2 -2
  53. package/dist-cli/chunks/{chunk-2B26APLC.js → chunk-YSN32GSR.js} +2 -2
  54. package/dist-cli/chunks/cli-version-QHAJ7OMR.js +2 -0
  55. package/dist-cli/chunks/{compat-7NMHHJXV.js → compat-EPSPO3GI.js} +3 -3
  56. package/dist-cli/chunks/{config-XKL7G2P3.js → config-7YGGAVYO.js} +2 -2
  57. package/dist-cli/chunks/{control-ZGD3NJES.js → control-TMFCD2NX.js} +2 -2
  58. package/dist-cli/chunks/{cpu-profile-ITFDFMIJ.js → cpu-profile-44YYVMOE.js} +2 -2
  59. package/dist-cli/chunks/{daemon-LHFCZTK6.js → daemon-4XLAN5CC.js} +2 -2
  60. package/dist-cli/chunks/{debug-C3X2PP3H.js → debug-MUYM2RWK.js} +3 -3
  61. package/dist-cli/chunks/{detox-ITXRK6EB.js → detox-NZJVVCA3.js} +2 -2
  62. package/dist-cli/chunks/{device-PBA26VX4.js → device-7HMHAQ2Q.js} +2 -2
  63. package/dist-cli/chunks/{diagnose-IWYHJJ7K.js → diagnose-FXVOC7LV.js} +2 -2
  64. package/dist-cli/chunks/drivers-GM6GJG7Q.js +2 -0
  65. package/dist-cli/chunks/{electron-6NRCOUQ3.js → electron-NKK6Z2F3.js} +3 -3
  66. package/dist-cli/chunks/flow-3E4SG5M7.js +2 -0
  67. package/dist-cli/chunks/help-VIYWVIUB.js +2 -0
  68. package/dist-cli/chunks/{hints-RBTS7PGP.js → hints-BLVNUKRX.js} +2 -2
  69. package/dist-cli/chunks/{home-paths-XKUYGHWD.js → home-paths-2QMRDV5X.js} +2 -2
  70. package/dist-cli/chunks/{inspect-7V5RQUJM.js → inspect-E6Z6N3PK.js} +34 -34
  71. package/dist-cli/chunks/install-U7C5NDWU.js +2 -0
  72. package/dist-cli/chunks/{install-desktop-MD77SEFP.js → install-desktop-O2E7FC4R.js} +3 -3
  73. package/dist-cli/chunks/{keys-LJMI7F3J.js → keys-GWXMM5CC.js} +2 -2
  74. package/dist-cli/chunks/{launch-RKUIUORR.js → launch-KWMHPASG.js} +3 -3
  75. package/dist-cli/chunks/{login-M7EXKPAT.js → login-AJO4L3ZI.js} +4 -4
  76. package/dist-cli/chunks/{logout-OVAZMIW5.js → logout-ZVGPEGAB.js} +2 -2
  77. package/dist-cli/chunks/{maestro-S4RQPFHB.js → maestro-4QX23OEI.js} +2 -2
  78. package/dist-cli/chunks/optional-demo-registry-LKCGAST6.js +2 -0
  79. package/dist-cli/chunks/{preview-QSIZ6KNZ.js → preview-CGBGA343.js} +2 -2
  80. package/dist-cli/chunks/{profile-6QQ3G5X7.js → profile-RLKDXLSK.js} +2 -2
  81. package/dist-cli/chunks/{react-HR7OT4NK.js → react-W2VGA55C.js} +2 -2
  82. package/dist-cli/chunks/{record-ZRSPOPCY.js → record-CF2HMY5Y.js} +2 -2
  83. package/dist-cli/chunks/runtime-A7DUL4IU.js +2 -0
  84. package/dist-cli/chunks/{runtime-delivery-MFVXZGIF.js → runtime-delivery-DZWXR2A5.js} +2 -2
  85. package/dist-cli/chunks/{screenshot-QNQ4TJ3I.js → screenshot-YV7USPJA.js} +2 -2
  86. package/dist-cli/chunks/{screenshot-mode-27K7PUTV.js → screenshot-mode-V27UKIG6.js} +2 -2
  87. package/dist-cli/chunks/{screenshots-LH7R6LV3.js → screenshots-BUOMYKKW.js} +2 -2
  88. package/dist-cli/chunks/{server-QQRPB6AJ.js → server-6EZSHZV3.js} +3 -3
  89. package/dist-cli/chunks/setup-repo-MCAZJVL5.js +2 -0
  90. package/dist-cli/chunks/{skills-KNFHQD77.js → skills-NXDCB76R.js} +2 -2
  91. package/dist-cli/chunks/{slides-GWMFQQAF.js → slides-6LF76Q4J.js} +2 -2
  92. package/dist-cli/chunks/{start-4INDW3QD.js → start-5VNJWI56.js} +4 -4
  93. package/dist-cli/chunks/store-SX54DA6L.js +2 -0
  94. package/dist-cli/chunks/telemetry-PHXMPEY3.js +2 -0
  95. package/dist-cli/chunks/{test-Q3CEHSD5.js → test-KPKJXRDI.js} +3 -3
  96. package/dist-cli/chunks/{three-mode-GTKSFFV7.js → three-mode-RWCVKNGM.js} +2 -2
  97. package/dist-cli/chunks/{timeline-NBDNN5SP.js → timeline-SRG5UM44.js} +2 -2
  98. package/dist-cli/chunks/{upgrade-UE7B726I.js → upgrade-LMUTKCI4.js} +2 -2
  99. package/dist-cli/chunks/upload-3YJQJYAD.js +2 -0
  100. package/dist-cli/chunks/{version-SS32LC2F.js → version-P4LKM55A.js} +2 -2
  101. package/dist-cli/chunks/web-5ZYKOZJG.js +2 -0
  102. package/dist-cli/chunks/{what-happened-NVKZVCHT.js → what-happened-AFWB7XTD.js} +2 -2
  103. package/dist-cli/chunks/{whoami-FWRWWX2E.js → whoami-YXJ6KECJ.js} +2 -2
  104. package/dist-lib/agent-daemon-client.cjs +1 -1
  105. package/dist-lib/agent-events.cjs +1 -1
  106. package/dist-lib/agent-sessions.cjs +1 -1
  107. package/dist-lib/attached-projects.cjs +1 -1
  108. package/dist-lib/auth/shared-session.cjs +1 -1
  109. package/dist-lib/backend-origin.cjs +1 -1
  110. package/dist-lib/beta.cjs +1 -1
  111. package/dist-lib/beta.mjs +1 -1
  112. package/dist-lib/bridge-constants.cjs +1 -1
  113. package/dist-lib/cli-constants.cjs +1 -1
  114. package/dist-lib/config.cjs +1 -1
  115. package/dist-lib/detox/index.cjs +1 -1
  116. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  117. package/dist-lib/home-paths.cjs +1 -1
  118. package/dist-lib/host/bridge-host.cjs +1 -1
  119. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  120. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  121. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  122. package/dist-lib/host/websocket-proxy.cjs +1 -1
  123. package/dist-lib/index.cjs +1 -1
  124. package/dist-lib/metro.cjs +1 -1
  125. package/dist-lib/profiles.cjs +1 -1
  126. package/dist-lib/render-mode.cjs +1 -1
  127. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  128. package/dist-lib/sdk.cjs +1 -1
  129. package/dist-lib/sdk.mjs +1 -1
  130. package/dist-lib/skills.cjs +156 -59
  131. package/dist-lib/vite.cjs +1 -1
  132. package/package.json +1 -1
  133. package/src/vite-plugin.ts +24 -0
  134. package/dist-cli/chunks/auto-bootstrap-CKH5ZZSJ.js +0 -2
  135. package/dist-cli/chunks/beta-Q6IKT5HT.js +0 -2
  136. package/dist-cli/chunks/chunk-2GROEF3J.js +0 -386
  137. package/dist-cli/chunks/chunk-CKOXSYJ6.js +0 -119
  138. package/dist-cli/chunks/chunk-JQFOV34Q.js +0 -1
  139. package/dist-cli/chunks/chunk-ROADBGFV.js +0 -2
  140. package/dist-cli/chunks/chunk-SY5JYGZE.js +0 -1
  141. package/dist-cli/chunks/chunk-V4EYA5L5.js +0 -1
  142. package/dist-cli/chunks/cli-version-5KMLKVRO.js +0 -2
  143. package/dist-cli/chunks/drivers-5B4IZBF3.js +0 -2
  144. package/dist-cli/chunks/flow-ITIKFOJJ.js +0 -2
  145. package/dist-cli/chunks/help-A26MVCNK.js +0 -2
  146. package/dist-cli/chunks/install-AJ3BWZ2Z.js +0 -2
  147. package/dist-cli/chunks/optional-demo-registry-DA3SDA2G.js +0 -2
  148. package/dist-cli/chunks/runtime-X5RH4ZUA.js +0 -2
  149. package/dist-cli/chunks/setup-repo-CTPFDKV3.js +0 -2
  150. package/dist-cli/chunks/store-SIN5AXHS.js +0 -2
  151. package/dist-cli/chunks/telemetry-QHL6TKNR.js +0 -2
  152. package/dist-cli/chunks/upload-UXXFJA3K.js +0 -2
  153. package/dist-cli/chunks/web-A3EW2IWT.js +0 -2
@@ -1,386 +0,0 @@
1
- /*! sootsim v0.1.148 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as je}from"./chunk-YONGHIDE.js";import{a as Be}from"./chunk-2SDVI2JB.js";import{a as Le}from"./chunk-T4FJHKU4.js";import{a as U,b as Ee,c as ie,d as ne,e as Me,f as oe,h as se,i as Ie,j as Pe}from"./chunk-UK7GX57G.js";import{g as Ce,n as Oe,p as De,t as Ne}from"./chunk-AXLTLDHE.js";import{e as _e}from"./chunk-BDKC2GLL.js";import{m as ke}from"./chunk-S3WEUJM3.js";import{m as xe,n as Te,o as $e,p as Fe}from"./chunk-7EBPIOTW.js";import{c as te,d as re,e as Se}from"./chunk-PMM6MNCR.js";import{a as Ae}from"./chunk-IYRFX6KX.js";import{a as Re}from"./chunk-23QZQBTT.js";import{d as ee,e as ve}from"./chunk-4JVDEEJJ.js";import{a as ye,b as Q}from"./chunk-Y5E53BEN.js";import{g as be}from"./chunk-NK6RKGX2.js";import*as _ from"fs";import{tmpdir as Ke}from"os";import*as y from"path";import*as b from"fs";import*as g from"path";import{spawnSync as rt}from"child_process";import*as A from"vm";var it=3e5,nt=`
3
- let input = '';
4
- process.stdin.on('data', (c) => { input += c });
5
- process.stdin.on('end', async () => {
6
- try {
7
- const req = JSON.parse(input);
8
- const res = await fetch(req.url, {
9
- method: req.method,
10
- headers: req.headers,
11
- body: req.body === undefined || req.body === null ? undefined : req.body,
12
- });
13
- const body = await res.text();
14
- const headers = {};
15
- for (const [k, v] of res.headers.entries()) {
16
- headers[k] = headers[k] ? headers[k] + ',' + v : v;
17
- }
18
- process.stdout.write(JSON.stringify({ ok: res.ok, status: res.status, body, headers }));
19
- } catch (err) {
20
- process.stdout.write(JSON.stringify({ __error: (err && err.message) || String(err) }));
21
- process.exitCode = 1;
22
- }
23
- });
24
- `;function D(n,e,t){if(t?.multipartForm)throw new Error("http: multipartForm is not supported by sootsim yet");let r={...process.env};for(let a of Object.keys(r))(a.startsWith("BUN_INSPECT")||a==="NODE_OPTIONS")&&delete r[a];let i=rt(process.execPath,["-e",nt],{input:JSON.stringify({url:n,method:e,headers:t?.headers,body:t?.body}),encoding:"utf8",timeout:it,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 s=o;if(s.__error)throw new Error(`http ${e} ${n} failed: ${s.__error}`);return s}var ot=/(?<!\\)\$\{([^$]*)\}/g,st=/\\(\$\{[^$]*\})/g,at=/^[A-Za-z_$][A-Za-z0-9_$]*$/,J=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)=>D(i,"GET",o),post:(i,o)=>D(i,"POST",o),put:(i,o)=>D(i,"PUT",o),delete:(i,o)=>D(i,"DELETE",o),request:(i,o)=>D(i,(o?.method??"GET").toUpperCase(),o)},console:{log:(...i)=>t(i.map(o=>typeof o=="string"?o:Ve(o)).join(" "))}};this.context=A.createContext(r),A.runInContext(`
25
- globalThis.__maestroScope = new Proxy(globalThis, {
26
- has() { return true },
27
- get(target, key) { return target[key] },
28
- })
29
- function json(text) { return JSON.parse(text) }
30
- function relativePoint(x, y) {
31
- var xPercent = Math.ceil(x * 100) + '%'
32
- var yPercent = Math.ceil(y * 100) + '%'
33
- return xPercent + ',' + yPercent
34
- }
35
- `,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 A.runInContext(`(function(){ with(__maestroScope){ return eval(\`${t}\`) } })()`,this.context)}syncEnvToContext(){let e=A.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&&at.test(i.trim()))throw new Error(`missing variable for flow placeholder: ${i.trim()}`);return Ve(o)}).replace(st,(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 Ve(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 We(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 K=1e4,H=393,N=852,Ue="__sootsimCliPerf";function f(n){return new Promise(e=>setTimeout(e,n))}function lt(n){return n?g.basename(n)===".maestro"?g.dirname(n):n:process.cwd()}function ct(n,e,t){let r=e.endsWith(".png")?e:`${e}.png`;if(g.isAbsolute(r))return r;if(t.mode==="flow"&&/[\\/]/.test(r)){let i=r.startsWith("./")||r.startsWith("../")?t.flowDir??process.cwd():lt(t.flowDir);return g.resolve(i,r)}return g.join(n,r)}function dt(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 ae(n){let[e,t]=n.split(",").map(i=>i.trim()),r=(i,o)=>i.endsWith("%")?Number.parseFloat(i)/100*o:Number.parseFloat(i);return{x:r(e,H),y:r(t,N)}}function ut(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 mt(n){let e=n.split(/^---$/m),t=e.length>1?e[e.length-1]:n,r=Ee.parse(t);return Array.isArray(r)?r:[]}var q=class{constructor(e,t){this.bridge=e;this.opts=t}stepDelay=0;js=new J({platform:"ios",onLog:e=>console.log(`[flow] js: ${e}`)});firstLaunchDone=!1;profilingEnabled=!1;recordingEnabled=!1;recordingAccessChecked=!1;recordingStartedAtMs=null;lastRecordingDurationMs=null;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"),s=e.find(l=>l.readyState==="open"),a=i??o??s;a&&(this.opts.simId=a.id,console.log(` [flow] sim rotated to ${a.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=K){let t=Date.now()+e,r=Date.now(),i=null,o=0,s=0,a=-1,l=r;for(;Date.now()<t;){try{let c=await this.evaluate(xe,8e3);if(o=0,c?.externalError)throw new Error(`app failed to load: ${c.externalError}`);if(c){let h=Date.now();c.nodes!==a&&(a=c.nodes,l=h);let I=c.flag===!0&&$e(c),w=c.flag!==!0&&Fe(c);if((I||w)&&c.externalReady!==!1&&!c.externalError&&!c.loadingText&&h-l>=Te)return}}catch(c){if(i=c instanceof Error?c:new Error(String(c)),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 m=Date.now()-r;m-s>=5e3&&(s=m,console.log(` [flow] waiting for app to be ready\u2026 (${Math.round(m/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||(await Be("flow --video",{originOverride:this.opts.billingOriginOverride,allowGitHubAuth:this.opts.allowGitHubRecording}),this.recordingAccessChecked=!0);let e=Date.now(),t=await this.evaluate(`(() => {
36
- const rec = window.__sootsimRecorder
37
- if (!rec) return { ok: false, error: 'recorder unavailable on this page' }
38
- const format = ${JSON.stringify(this.opts.recordingFormat??"webm")}
39
- if (rec.state() === 'recording') return { ok: true, format }
40
- return rec.start({ format, fps: 24 })
41
- })()`);if(!t?.ok)throw new Error(t?.error||"recording unavailable on this page");this.recordingStartedAtMs||(this.recordingStartedAtMs=e)}async startRecording(){this.recordingEnabled=!0,await this.ensureRecordingStarted()}prepareRecording(){this.recordingEnabled=!0}getLastRecordingDurationMs(){return this.lastRecordingDurationMs}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,new Error(t?.error||"recording stop failed");this.lastRecordingDurationMs=this.recordingStartedAtMs?Math.max(1,e-this.recordingStartedAtMs):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");b.mkdirSync(this.opts.recordingOutputDir,{recursive:!0});let s=(t.mime||this.opts.recordingFormat||"video/webm").includes("mp4")?"mp4":"webm",a=g.join(this.opts.recordingOutputDir,`sootsim-${Date.now()}.${s}`);return b.writeFileSync(a,Buffer.concat(r)),a}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 Pe({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){return this.evaluate(`(async () => {
42
- const test = window.__sootsimTest
43
- if (!test) return null
44
- let node = null
45
- if (${JSON.stringify(!!e.text)}) node = await test.findByText(${JSON.stringify(e.text||"")})
46
- if (!node && ${JSON.stringify(!!e.id)}) {
47
- node = (await test.findByTestId(${JSON.stringify(e.id||"")})) || (await test.findById(${JSON.stringify(e.id||"")}))
48
- }
49
- if (!node || !node.absolutePosition || !node.layout) return null
50
- return {
51
- nodeId: typeof node.nodeId === 'number' ? node.nodeId : null,
52
- id: node.id || null,
53
- testID: node.testID || null,
54
- text: node.text || null,
55
- absolutePosition: node.absolutePosition,
56
- layout: node.layout,
57
- isTextInput: !!node.isTextInput,
58
- }
59
- })()`)}async resolveTapTarget(e){return this.evaluate(`(async () => {
60
- const test = window.__sootsimTest
61
- if (!test?.resolveTapTarget) return null
62
- return await test.resolveTapTarget(${e})
63
- })()`)}async activatePressTarget(e){let t=e.id?{id:e.id,testID:e.id,text:null}:{id:null,testID:null,text:e.text??null};return this.evaluate(`(async () => {
64
- const test = window.__sootsimTest
65
- if (!test) return null
66
- const node = ${e.id?`(await test.findByTestId?.(${JSON.stringify(e.id)})) || (await test.findById?.(${JSON.stringify(e.id)}))`:`await test.findByText?.(${JSON.stringify(e.text||"")})`}
67
- let point = null
68
- if (node?.absolutePosition && node?.layout) {
69
- point = {
70
- x: node.absolutePosition.x + node.layout.width / 2,
71
- y: node.absolutePosition.y + node.layout.height / 2,
72
- }
73
- if (typeof node.nodeId === 'number' && test.resolveTapTarget) {
74
- const resolved = await test.resolveTapTarget(node.nodeId)
75
- if (
76
- resolved &&
77
- Number.isFinite(resolved.cx) &&
78
- Number.isFinite(resolved.cy)
79
- ) {
80
- point = { x: resolved.cx, y: resolved.cy }
81
- }
82
- }
83
- }
84
- ${e.id?`const direct = await test.activatePressById?.(${JSON.stringify(e.id)})`:`const direct = await test.activatePressByText?.(${JSON.stringify(e.text||"")})`}
85
- if (direct?.ok && point) {
86
- window.dispatchEvent(
87
- new CustomEvent('sootsim:agentAction', {
88
- detail: { type: 'tap', x: point.x, y: point.y, target: ${JSON.stringify(t)} },
89
- }),
90
- )
91
- }
92
- return direct || null
93
- })()`)}async activatePressAt(e,t){return this.evaluate(`(async () => {
94
- const test = window.__sootsimTest
95
- if (!test?.activatePressAt) return null
96
- const direct = await test.activatePressAt(${e}, ${t})
97
- if (direct?.ok) {
98
- window.dispatchEvent(
99
- new CustomEvent('sootsim:agentAction', {
100
- detail: { type: 'tap', x: ${e}, y: ${t} },
101
- }),
102
- )
103
- }
104
- return direct
105
- })()`)}async tap(e,t,r){return await this.bridge.send({type:"tap",simId:this.opts.simId,x:e,y:t,target:r})}async tapOn(e){let t=typeof e=="string"?{text:e}:e;if(t.point){let l=ae(t.point);(await this.activatePressAt(l.x,l.y))?.ok||await this.tap(l.x,l.y),await f(300);return}let r=5e3,i=150,o=Date.now()+r,s=await this.findElement({text:t.text,id:t.id});for(;!s&&Date.now()<o;)await f(i),s=await this.findElement({text:t.text,id:t.id});if(s){let l=s.isTextInput?4:1;for(let m=0;m<l;m++){let c=m===0?s:await this.findElement({text:t.text,id:t.id});if(!c)break;let h=typeof c.nodeId=="number"?await this.resolveTapTarget(c.nodeId):null,I=h?.cx??c.absolutePosition.x+c.layout.width/2,w=h?.cy??c.absolutePosition.y+c.layout.height/2;if((await this.tap(I,w,{id:t.id??h?.target?.id??c.id??null,testID:t.id??h?.target?.testID??c.testID??null,text:t.text??h?.target?.text??h?.target?.accessibilityLabel??c.text??c.accessibilityLabel??null,type:h?.target?.type??c.type??null}))?.hit===!0){if(await f(300),!c.isTextInput||await this.waitForFocusedTextInput(600))return;continue}break}}if((await this.activatePressTarget(t))?.ok){await f(300);return}throw new Error(`tapOn: element not found: ${JSON.stringify(t)}`)}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 () => {
106
- const interact = window.__sootsimInteract
107
- if (interact?.doubleTap) {
108
- return !!(await interact.doubleTap(${e}, ${t}, ${i}))
109
- }
110
- if (!interact?.tap) return false
111
- const first = await interact.tap(${e}, ${t})
112
- if (!first || first.hit === false) return false
113
- await new Promise((resolve) => setTimeout(resolve, ${i}))
114
- const second = await interact.tap(${e}, ${t})
115
- return !!second && second.hit !== false
116
- })()`))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<N)}async inputText(e){await this.waitForFocusedTextInput(),await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"type",text:e}),await f(200)}async waitForFocusedTextInput(e=1500){let t=Date.now()+e;for(;Date.now()<t;){try{if(await this.callTest("getFocusedNode"))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(`(() => {
117
- const keyboard =
118
- window.__sootsimKeyboard ??
119
- window.SootSim?.bridges?.keyboard ??
120
- null
121
- const test = window.__sootsimTest
122
- return {
123
- visible: !!keyboard?.isVisible?.(),
124
- focused: !!test?.isTextInputFocused?.(),
125
- }
126
- })()`);if(!t?.visible&&!t?.focused){await f(80);return}await f(80)}}async eraseText(e){for(let t=0;t<e;t++)await this.pressKey("Backspace");await f(100)}async waitFor(e){let t=Date.now()+(e.timeout||K);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||K}ms${i}`)}async takeScreenshot(e){try{await this.waitForVisualSettle()}catch{}await f(250);let t=dt(e),r=ct(this.opts.screenshotDir,t.path,{mode:this.opts.screenshotPathMode??"dir",flowDir:this.opts.flowDir});b.mkdirSync(g.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 a=(await this.bridge.send(o)).replace(/^data:image\/png;base64,/,""),l=Buffer.from(a,"base64");if(t.withFrame){let m=await this.readCurrentDeviceModel();if(!m)throw new Error("could not read current device model for framed screenshot");let c=await je(l,m);b.writeFileSync(r,c),console.log(`[flow] screenshot: ${r} (frame: ${m})`);return}b.writeFileSync(r,l),console.log(`[flow] screenshot: ${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 captureFailureScreenshot(e){b.mkdirSync(g.dirname(e),{recursive:!0});let r=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");b.writeFileSync(e,Buffer.from(r,"base64"))}async captureFailureBundle(e,t){b.mkdirSync(e,{recursive:!0});let r=(c,h)=>{try{b.writeFileSync(g.join(e,c),h)}catch{}},i=async c=>{try{return await this.bridge.send({type:"evaluate",simId:this.opts.simId,code:c})}catch{return null}},o=await i(`(async () => {
127
- const out = {
128
- simId: window.__sootsimBridge?.id ?? window.SootSim?.state?.simId ?? null,
129
- url: location.href,
130
- title: document.title,
131
- hidden: document.hidden,
132
- }
133
- try {
134
- const params = new URL(location.href).searchParams
135
- const bundle = params.get('bundle')
136
- if (bundle) {
137
- const baseMatch = bundle.match(/^https?:\\/\\/[^/]+/)
138
- if (baseMatch) {
139
- const res = await fetch(baseMatch[0] + '/', {
140
- headers: { 'expo-platform': 'ios' },
141
- cache: 'no-store',
142
- })
143
- if (res.ok) {
144
- out.manifest = await res.json().catch(() => null)
145
- }
146
- }
147
- }
148
- } catch {}
149
- return out
150
- })()`);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 h=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");r("screenshot.png",Buffer.from(h,"base64"))}catch{}let s=await i(`(async () => {
151
- const t = window.__sootsimTest
152
- const mainShell = window.SootSim?.bridges?.mainShell
153
- if (!t) return { error: 'no test bridge' }
154
- let shell = null
155
- try {
156
- shell = typeof mainShell?.getState === 'function' ? await mainShell.getState() : null
157
- } catch {}
158
- const all = await t.queryAll({ pruneHidden: true })
159
- return { shell, nodes: all, url: location.href, title: document.title }
160
- })()`);s&&r("describe.json",JSON.stringify(s,null,2));let a=await i("(async () => await window.__sootsimTest?.dumpAccessibilityTree?.(20))()");typeof a=="string"&&r("a11y.txt",a);let l=await i("(async () => await window.__sootsimTest?.dumpTree?.(15))()");typeof l=="string"&&r("tree.txt",l);let m=await i(`(() => {
161
- const c = window.__sootsimConsole
162
- return {
163
- errors: c?.getErrors?.() ?? [],
164
- warnings: c?.getWarnings?.() ?? [],
165
- requests: (window.__sootsimGetFailedRequests?.() ?? []),
166
- }
167
- })()`);return m&&r("console.json",JSON.stringify(m,null,2)),e}async swipe(e="UP",t=300){let r=H/2,i=N/2,o=200,s=r,a=i,l=r,m=i;switch(e.toUpperCase()){case"UP":a+=o,m-=o;break;case"DOWN":a-=o,m+=o;break;case"LEFT":s+=o,l-=o;break;case"RIGHT":s-=o,l+=o;break}let c=Math.max(10,Math.round(t/16));await this.drag(s,a,l,m,c,16)}async drag(e,t,r,i,o=12,s=16){if(!(await this.evaluate(`(async () => {
168
- const interact = window.__sootsimInteract
169
- if (!interact?.drag) return { ok: false }
170
- const value = await interact.drag(${e}, ${t}, ${r}, ${i}, ${Math.max(1,Math.round(o))}, ${Math.max(0,Math.round(s))})
171
- return { ok: !!value, value }
172
- })()`))?.ok)throw new Error("drag failed");await f(300)}async swipeCoords(e,t,r=300){let i=ae(e),o=ae(t),s=Math.max(10,Math.round(r/16));await this.drag(i.x,i.y,o.x,o.y,s,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,s=i.absolutePosition.y+i.layout.height/2,a=180,l=o,m=s;switch(t.toUpperCase()){case"UP":m-=a;break;case"DOWN":m+=a;break;case"LEFT":l-=a;break;case"RIGHT":l+=a;break}let c=Math.max(10,Math.round(r/16));await this.drag(o,s,l,m,c,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 () => {
173
- const interact = window.__sootsimInteract
174
- if (!interact?.pinch) return { ok: false, reason: 'no interact.pinch' }
175
- const ok = await interact.pinch(
176
- ${e.from[0]}, ${e.from[1]}, ${e.from[2]}, ${e.from[3]},
177
- ${e.to[0]}, ${e.to[1]}, ${e.to[2]}, ${e.to[3]},
178
- ${e.steps||12}, ${e.stepMs||16}
179
- )
180
- return { ok: !!ok, reason: ok ? null : 'pinch returned false' }
181
- })()`);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){await f(e)}async back(){try{await this.tapOn("\u2039")}catch{await this.tapOn("<")}}async scrollUntilVisible(e){let t=Date.now()+(e.timeout||15e3),r=e.direction?.toUpperCase()||"DOWN",i=r==="DOWN"?"UP":r==="UP"?"DOWN":r;for(;Date.now()<t;){let o=await this.findElement({text:e.element});if(o&&o.absolutePosition.y>=0&&o.absolutePosition.y+o.layout.height>0&&o.absolutePosition.y<N-50){if(e.centerElement){let s=N/2,a=o.absolutePosition.y-s;if(Math.abs(a)>100){let l=Math.min(150,Math.abs(a)*.5),m=a>0?s-l:s+l;await this.drag(H/2,s,H/2,m,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||K);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 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);if(t&&await this.evaluate(U,6e4),!this.firstLaunchDone&&!t)this.firstLaunchDone=!0,await this.waitForTree(3e4);else if(this.firstLaunchDone=!0,await this.evaluate("window.location.reload()").catch(()=>{}),await f(500),await this.refreshSimId(),await this.waitForTree(12e4),this.opts.onAfterLaunch)try{await this.opts.onAfterLaunch()}catch(r){console.warn(` warn: onAfterLaunch hook threw: ${r instanceof Error?r.message:r}`)}this.profilingEnabled&&await this.startProfile(),this.recordingEnabled&&(await this.waitForVisualSettle(),await this.ensureRecordingStarted())}async waitForVisualSettle(){try{await this.evaluate(`new Promise((resolve) => {
182
- requestAnimationFrame(() => {
183
- requestAnimationFrame(() => {
184
- requestAnimationFrame(() => {
185
- setTimeout(resolve, 180)
186
- })
187
- })
188
- })
189
- })`)}catch{await f(180)}}async startProfile(){await this.evaluate(`((sessionKey) => {
190
- const perf = window.__sootsimPerf
191
- const a11y = window.__sootsimA11y
192
- perf?.enableFrameStats?.(true)
193
- perf?.resetFrameStats?.()
194
- a11y?.resetProfile?.()
195
- window[sessionKey] = {
196
- active: true,
197
- mode: window.__sootsimRenderHost ? 'render-worker' : 'main-thread',
198
- lastSamples: [],
199
- startedAt: performance.now(),
200
- }
201
- })(${JSON.stringify(Ue)})`),this.profilingEnabled=!0}async stopProfile(){let e=await this.evaluate(`(async (sessionKey) => {
202
- const host = window.__sootsimRenderHost
203
- if (host?.flushSamples) {
204
- const perf = window.__sootsimPerf
205
- const session = window[sessionKey] || {}
206
- const priorSamples = session.active && Array.isArray(session.lastSamples)
207
- ? session.lastSamples
208
- : []
209
- const flushedSamples = await host.flushSamples()
210
- await perf?.disableFrameStats?.()
211
- const samples = priorSamples.concat(flushedSamples)
212
- window[sessionKey] = {
213
- ...session,
214
- active: false,
215
- mode: 'render-worker',
216
- lastSamples: samples,
217
- stoppedAt: performance.now(),
218
- }
219
-
220
- const frameTimes = samples.map((sample) => Number(sample?.[1]) || 0)
221
- const sorted = [...frameTimes].sort((a, b) => a - b)
222
- const worstFrames = samples
223
- .slice()
224
- .sort((a, b) => (Number(b?.[1]) || 0) - (Number(a?.[1]) || 0))
225
- .slice(0, 10)
226
- .map((sample) => [
227
- Number(sample?.[0]) || 0,
228
- Number(sample?.[1]) || 0,
229
- Number(sample?.[2]) || 0,
230
- Number(sample?.[3]) || 0,
231
- Number(sample?.[4]) || 0,
232
- ])
233
-
234
- return {
235
- mode: 'render-worker',
236
- frames: frameTimes.length,
237
- totalMs: frameTimes.reduce((sum, value) => sum + value, 0),
238
- avgMs: frameTimes.length ? frameTimes.reduce((sum, value) => sum + value, 0) / frameTimes.length : 0,
239
- maxMs: sorted[sorted.length - 1] || 0,
240
- layoutTotalMs: samples.reduce((sum, sample) => sum + (Number(sample?.[2]) || 0), 0),
241
- renderTotalMs: samples.reduce((sum, sample) => sum + (Number(sample?.[3]) || 0), 0),
242
- copyTotalMs: samples.reduce((sum, sample) => sum + (Number(sample?.[4]) || 0), 0),
243
- layoutAvgMs: frameTimes.length ? samples.reduce((sum, sample) => sum + (Number(sample?.[2]) || 0), 0) / frameTimes.length : 0,
244
- renderAvgMs: frameTimes.length ? samples.reduce((sum, sample) => sum + (Number(sample?.[3]) || 0), 0) / frameTimes.length : 0,
245
- copyAvgMs: frameTimes.length ? samples.reduce((sum, sample) => sum + (Number(sample?.[4]) || 0), 0) / frameTimes.length : 0,
246
- p50: sorted[Math.floor(sorted.length * 0.5)] || 0,
247
- p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
248
- p99: sorted[Math.floor(sorted.length * 0.99)] || 0,
249
- jankFrames: frameTimes.filter((value) => value > 16.67).length,
250
- sampleCount: frameTimes.length,
251
- worstFrames,
252
- }
253
- }
254
-
255
- const perf = window.__sootsimPerf
256
- const a11y = window.__sootsimA11y
257
- if (!perf && !a11y) return { error: 'no perf globals available' }
258
-
259
- const stoppedStats = await perf?.disableFrameStats?.()
260
- const frameStats = stoppedStats || await perf?.getFrameStats?.() || {}
261
- const profile = a11y?.profile?.() || {}
262
- const recent = Array.isArray(frameStats.recentFrames) ? frameStats.recentFrames : []
263
- const sorted = [...recent].sort((a, b) => a - b)
264
-
265
- return {
266
- mode: 'main-thread',
267
- frames: frameStats.frames || profile.syncCount || 0,
268
- totalMs: frameStats.totalMs || 0,
269
- avgMs: frameStats.totalMs && frameStats.frames ? frameStats.totalMs / frameStats.frames : profile.avgSyncMs || 0,
270
- maxMs: frameStats.maxMs || profile.maxSyncMs || 0,
271
- layoutTotalMs: frameStats.layoutTotalMs || 0,
272
- p50: sorted[Math.floor(sorted.length * 0.5)] || 0,
273
- p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
274
- p99: sorted[Math.floor(sorted.length * 0.99)] || 0,
275
- jankFrames: recent.filter((value) => value > 16.67).length,
276
- sampleCount: recent.length,
277
- worstFrames: recent.slice().sort((a, b) => b - a).slice(0, 10),
278
- }
279
- })(${JSON.stringify(Ue)})`);if(this.profilingEnabled=!1,e?.error)throw new Error(e.error);return e}async stopApp(){await this.evaluate(`(async () => {
280
- try { await (${U}) } catch {}
281
- try {
282
- const regs = await navigator.serviceWorker?.getRegistrations?.()
283
- await Promise.all((regs || []).map((reg) => reg.unregister()))
284
- } catch {}
285
- })()`)}async clearState(){await this.evaluate(`(async () => {
286
- await (${U})
287
- })()`)}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=g.resolve(this.opts.flowDir,t.file),i=b.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?We(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"?ut(e):e,i=Object.keys(r).find(s=>s!=="when")||Object.keys(r)[0];console.log(`[flow] step ${t+1}: ${i}`);let o;try{o=this.js.interpolateStep(r)}catch(s){if(this.isOptional(r)){console.log(`[flow] (optional, skipped: ${s.message.slice(0,80)})`);return}throw this.lastFailedStep={index:t,kind:i,target:r[i]},s}if(o.when&&!await this.evaluateWhen(o.when)){console.log("[flow] (when: predicate false, skipped)");return}try{let s=!!(o.extendedWaitUntil||o.waitFor||o.scrollUntilVisible||o.launchApp||o.runFlow||o.runScript),a=1e4,l=this.runStepInner(o);if(s)await l;else{let c=null,h=new Promise((I,w)=>{c=setTimeout(()=>{w(new Error(`step watchdog: ${i} made no progress in ${a}ms \u2014 bridge or bundle probably hung`))},a)});try{await Promise.race([l,h])}finally{c&&clearTimeout(c)}}let m=!!(o.assertVisible||o.assertNotVisible||o.extendedWaitUntil||o.waitFor);this.stepDelay>0&&!m&&await f(this.stepDelay)}catch(s){if(this.isOptional(o)){console.log(`[flow] (optional, skipped: ${s.message.slice(0,80)})`);return}throw this.lastFailedStep={index:t,kind:i,target:o[i]},s}}async runStepInner(e){if(e.tapOn)await this.tapOn(e.tapOn);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)await this.takeScreenshot(e.takeScreenshot);else 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)await this.waitForAnimationToEnd(typeof e.waitForAnimationToEnd=="number"?e.waitForAnimationToEnd: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,s=i?r:Math.min(r,1e3),a=0;for(;a<s&&await o();){for(let l=0;l<e.repeat.commands.length;l++)await this.runStep(e.repeat.commands[l],l);a++}}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,s=typeof t=="string"?void 0:t.when;if(s&&!await this.evaluateWhen(s)){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[a,l]of Object.entries(o))this.js.putEnv(a,l);if(r){let a=g.resolve(this.opts.flowDir,r),l=b.readFileSync(a,"utf8"),m=this.opts.flowDir;this.opts.flowDir=g.dirname(a);try{await this.runFlow(mt(l))}finally{this.opts.flowDir=m}}else if(i)for(let a=0;a<i.length;a++)await this.runStep(i[a],a)}finally{this.js.leaveEnvScope()}}else throw new Error(`unsupported flow step: ${JSON.stringify(e)}`)}async runFlow(e){let t=[],r=[],i=[];for(let s of e){let a=Object.keys(s);if(a.length===1&&a[0]==="onFlowStart"&&Array.isArray(s.onFlowStart)){t.push(...s.onFlowStart);continue}if(a.length===1&&a[0]==="onFlowComplete"&&Array.isArray(s.onFlowComplete)){r.push(...s.onFlowComplete);continue}i.push(s)}if(t.length>0){console.log(`[flow] onFlowStart (${t.length} steps)`);for(let s=0;s<t.length;s++)await this.runStep(t[s],s)}let o=null;try{await this.runFlowBody(i)}catch(s){o=s instanceof Error?s:new Error(String(s))}if(r.length>0){console.log(`[flow] onFlowComplete (${r.length} steps)`);for(let s=0;s<r.length;s++)try{await this.runStep(r[s],s)}catch(a){console.warn(`[flow] onFlowComplete step ${s+1} failed: ${a instanceof Error?a.message:a}`)}}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,s=Math.max(6e4,i+15e3,o+15e3);if(r.runFlow||r.launchApp){await this.runStep(r,t);continue}await Promise.race([this.runStep(r,t),new Promise((a,l)=>setTimeout(()=>l(new Error(`step ${t+1} (${Object.keys(r)[0]}) exceeded ${s}ms deadline`)),s))])}}};async function pt(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 Ae()).find(i=>i.name.toLowerCase()===e.toLowerCase());return r?String(r.preferredPort):e}async function ft(){let n=await _e(),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 He(n){(n.length===0||n.includes("--help")||n.includes("-h"))&&(console.log(`
288
- sootsim flow \u2014 run flows or manage a draft
289
-
290
- usage:
291
- sootsim flow <flow.yaml> [options]
292
- sootsim flow start
293
- sootsim flow keep
294
- sootsim flow end [--output <path>] [--validate] [--video]
295
- sootsim flow validate <path>
296
-
297
- options:
298
- --record record a webm artifact while the flow runs
299
- --profile capture perf stats while the flow runs
300
- --out <dir> output directory (default: /tmp/sootsim-recordings)
301
- --device <model> override the flow frontmatter device for this run
302
- --slow <ms> delay between steps for natural pacing
303
- --tail-wait <ms> hold the recording open after the last step so the
304
- final UI state is captured (default: smart idle up to
305
- 6000ms for --preview, fixed 2000ms for --record, 0 otherwise)
306
- --url <url> load this target before running the flow
307
- --screenshot-paths <mode>
308
- screenshot path mode: dir (default) or flow
309
- --no-shell capture every screenshot tenant-only (no status bar,
310
- keyboard, notification center, or other shell overlays).
311
- use for clean demo asset sets. per-step \`layers:\`
312
- still wins over this default.
313
- --shell-only inverse \u2014 capture shell chrome only
314
- --replace <m>=<f> replace a Metro module with a local file for this run
315
- --new open a fresh sim before running the flow
316
- --driver <id> when paired with --new, launch through a specific
317
- driver from the registry (e.g. playwright for
318
- hermetic CI runs); see 'sootsim list --drivers'
319
- --headless pass headless=true to the launch driver (useful
320
- with --driver playwright)
321
- --headed force a fresh, VISIBLE window for this run (implies
322
- --new; overrides --headless). use when you want to
323
- watch the flow run live even if the current sim is
324
- headless or stale
325
- --electron prefer opening the target in the desktop companion
326
- --sim <id> target a specific current sim
327
- --validate replay the drafted flow before clearing it
328
- --video replay and record the drafted flow before clearing it
329
- --preview record events+video, upload, and print /preview/<id>
330
- --preview-open open the uploaded preview link after a successful run
331
- --preview-origin <url>
332
- upload target for --preview (default: auto)
333
- --preview-public-origin <url>
334
- public link origin for --preview (default: sootsim.com
335
- for prod uploads)
336
- --owner <org> associate preview upload with a linked org repo
337
- --repo <repo> repo name for --owner; user must belong to the team
338
-
339
- frontmatter (top of flow.yaml between --- markers):
340
- app: 8081 load this target before the flow starts
341
- device: iphone-14 set the live device model for this flow run
342
- electron: true prefer the desktop companion sim for this flow
343
-
344
- default runtime:
345
- bridge-backed flow playback against the current sim
346
- if no current sim exists, flow opens the discovered target first
347
- recording and profiling both run on the same bridge-backed path
348
-
349
- examples:
350
- sootsim flow login.yaml
351
- sootsim flow demo.yaml --url 8081 --record --slow 500 --out ./recordings
352
- sootsim flow demo.yaml --sim a2
353
- sootsim flow start
354
- sootsim flow keep
355
- sootsim flow end --output ./flows/draft.yaml
356
- sootsim flow end --output ./flows/draft.yaml --validate
357
- sootsim flow end --output ./flows/draft.yaml --video
358
- sootsim flow validate ./flows/draft.yaml
359
-
360
- flow extension:
361
- takeScreenshot: hero
362
- takeScreenshot:
363
- path: marketing/hero
364
- withFrame: true
365
- `),process.exit(0));let e=n[0];_.existsSync(e)||(console.error(` error: ${e} not found`),process.exit(1));let t=p=>n.find((u,v)=>n[v-1]===p),r=n.includes("--profile"),i=n.includes("--headed"),o=n.includes("--new")||i,s=t("--out")||"/tmp/sootsim-recordings",a=t("--screenshots")||(t("--out")?s:"/tmp/sootsim-flow"),l=t("--screenshot-paths")==="flow"?"flow":"dir",m=n.includes("--no-shell")?"tenant":n.includes("--shell-only")?"shell":void 0,c=t("--device")?.trim()||"",h=n.includes("--slow")?+(t("--slow")||"500"):0,I=n.includes("--electron"),w=n.includes("--preview"),R=await Le(t("--preview-origin")),le=t("--preview-public-origin"),qe=n.includes("--preview-open"),ce=t("--owner")?.trim()||"",de=t("--repo")?.trim()||"",ze=n.flatMap((p,u)=>n[u-1]==="--replace"?["--replace",p]:[]),Ge=n.flatMap((p,u)=>n[u-1]==="--remap"?["--remap",p]:[]),$=n.includes("--record")||w,Ye=n.includes("--tail-wait")?Math.max(0,+(t("--tail-wait")||"2000")):$?w?6e3:2e3:0,Xe=_.readFileSync(e,"utf8"),{frontmatter:x,steps:E}=ie(Xe);E.length===0&&(console.error(" error: flow file must contain a YAML array of steps"),process.exit(1));let C=c||x.device||"",j=I||x.electron===!0,Ze=x.app===void 0||x.app===null?"":typeof x.app=="number"?String(x.app):x.app,z=await pt(Ze),ue={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"]},S=te(n,ue),Qe=t("--url")||"";j&&!Re()&&(console.error(" error: desktop companion not found. install or build it first with `bun run build:electron`"),process.exit(1));let me=j?"desktop companion":"bridge",et=z?` | target: ${z}`:"";console.log(`
366
- sootsim flow \u2014 ${y.basename(e)}
367
- ${E.length} steps | ${me}${et}${$?" | recording":""}${r?" | profiling":""}${h?` | ${h}ms delay`:""}
368
- `),w&&ye({event:"preview_flow_started",properties:{flowName:y.basename(e),stepCount:E.length,mode:me,electron:j,record:$,profile:r,previewOrigin:R}});let F=Qe||z||"",G=o||j&&S.simIdSource!=="flag",pe=t("--driver")||"",Y=!1,X=new Set,fe=!1;if(!F&&!G&&S.simIdSource==="none"){let p=Se(S);try{let u=await p.listSims(),v=u.find(W=>W.isPrimary&&W.readyState==="open"),V=u.find(W=>W.readyState==="open"),ge=v??V;ge&&(fe=!0,console.log(` reusing active sim: ${ge.id}`))}catch{}finally{p.close()}}if(!F&&!fe&&(G||S.simIdSource==="none")){let p=await ft();p||(console.error(" error: no current sim and no sootsim target found"),await Q(),process.exit(1)),F=p}if(F&&C){let p=new URL(await Ce(F));p.searchParams.set("device",C),F=p.toString()}if(F){let p=[F];if(p.push(...ze),p.push(...Ge),G&&p.push("--new"),S.simIdSource==="flag"&&S.simId&&p.push("--sim",S.simId),pe&&(p.push("--driver",pe),Y=!0),n.includes("--headless")&&!i&&p.push("--headless"),await De(p,{port:S.wsPort,timeoutMs:S.commandTimeoutMs}),Y){let u=ee();u&&X.add(u)}}let P=te(n,ue),L=P.simIdSource==="flag"?P.simId:ee()||P.simId,tt=P.simIdSource==="flag"?"flag":L?"saved":"none",k=re(P.wsPort,{commandTimeoutMs:P.commandTimeoutMs,simId:L,simIdSource:tt}),d,he=async()=>{if(!C)return!1;let p=await k.send({type:"evaluate",simId:d.simId,code:"window.location.href"});if(typeof p=="string"&&p.length>0){let u=new URL(p);u.searchParams.set("device",C),d.setSimRouteHint(u.toString())}return!!await k.send({type:"call",simId:d.simId,path:"SootSim.bridges.settings.set",args:["deviceModel",C]})};if(d=new q(k,{screenshotDir:a,flowDir:y.dirname(y.resolve(e)),screenshotPathMode:l,screenshotLayers:m,simId:L,recordingOutputDir:$?s:void 0,recordingFormat:w?"mp4":"webm",billingOriginOverride:w?R:void 0,allowGitHubRecording:$,onAfterLaunch:async()=>{await he()&&await d.waitForTree(12e4),w&&await k.send({type:"evaluate",simId:d.simId,code:`(() => {
369
- const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
370
- return r?.start?.() ?? false
371
- })()`})}}),h&&(d.stepDelay=h),d.js.putEnv("MAESTRO_FILENAME",y.basename(e,y.extname(e))),x.env&&typeof x.env=="object")for(let[p,u]of Object.entries(x.env))d.js.putEnv(p,u);let M=null,T=null,O=null,Z=null,B=0,we=!!E[0]?.launchApp;try{await d.waitForTree(12e4),await he()&&await d.waitForTree(12e4),w&&!we&&!process.env.SOOTSIM_PREVIEW_RESET_DONE&&await d.launchApp({clearState:!0}),$&&(we?d.prepareRecording():await d.startRecording()),r&&await d.startProfile(),w&&(await k.send({type:"evaluate",simId:d.simId,code:`(() => {
372
- const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
373
- return r?.start?.() ?? false
374
- })()`})||console.warn(" warn: eventRecorder.start() returned false \u2014 preview will upload bundle without replay events")),await d.runFlow(E),r&&(M=await d.stopProfile()),await d.waitForRecordingTail({maxMs:Ye,smart:w}),$&&(T=await d.stopRecording(),O=d.getLastRecordingDurationMs()),w&&(Z=await k.send({type:"evaluate",simId:d.simId,code:`(() => {
375
- const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
376
- return r?.stop?.() ?? []
377
- })()`}),console.log(` captured ${Z.length} replay events`));let u=E.filter(v=>"takeScreenshot"in v).length;console.log(`
378
- + completed (${E.length} steps)`),u>0&&console.log(` screenshots: ${u} \u2192 ${a}`),M&&Je(M),T&&console.log(` video: ${T}`),console.log()}catch(p){if(r&&!M)try{M=await d.stopProfile()}catch{}if($&&!T)try{T=await d.stopRecording(),O=d.getLastRecordingDurationMs()}catch(u){console.warn(` recording stop failed: ${u?.message||String(u)}`)}console.error(`
379
- x failed: ${p.message}
380
- `),M&&(console.log(" partial profile:"),Je(M)),T&&console.log(` partial video: ${T}`);try{let u=d.lastFailedStep,v=u?`step-${String(u.index+1).padStart(2,"0")}-${u.kind}`:"unstaged",V=y.join(a,v);await d.captureFailureBundle(V,{error:p,stepIndex:u?.index,stepKind:u?.kind,stepTarget:u?.target}),console.log(` failure bundle: ${V}`),console.log(" (contents: screenshot.png, describe.json, a11y.txt, tree.txt, console.json, error.json)")}catch(u){try{let v=y.join(a,"error.png");await d.captureFailureScreenshot(v),console.log(` error screenshot: ${v}`)}catch{}console.log(` (failure bundle capture failed: ${u instanceof Error?u.message:String(u)})`)}await ke(k,{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}`:""}`}),B=1}finally{k.close()}if(B===0&&w)try{let p=await wt(Z??[]),u=["--origin",R,"--events",p];le&&u.push("--public-origin",le),T&&u.push("--video",T),T&&O&&Number.isFinite(O)&&u.push("--video-duration-ms",String(Math.round(O))),d.simId&&u.push("--sim",d.simId),qe&&u.push("--open"),ce&&u.push("--owner",ce),de&&u.push("--repo",de),console.log(`
381
- preparing preview upload\u2026`);let{runUpload:v}=await import("./upload-UXXFJA3K.js");await v(u,{})}catch(p){console.error(` preview upload failed: ${p?.message||p}`),B=1}return Y?(d.simId&&X.add(d.simId),await ht(S.wsPort,S.commandTimeoutMs,[...X])):d.simId&&d.simId!==L&&ve(d.simId),await Q(),B}async function ht(n,e,t){let r=[...new Set(t.filter(Boolean))];if(r.length===0)return;let i=re(n,{commandTimeoutMs:e});try{let o=await i.listSims(),s=r.filter(l=>o.some(m=>m.id===l&&m.readyState==="open"));if(s.length===0)return;let a=await Ne(i,n,e,s);await Oe(o,s),a.closed.length>0&&console.log(` closed flow sim(s): ${a.closed.join(", ")}`),a.remaining.length>0&&console.warn(` warn: flow sim(s) still connected after close: ${a.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 wt(n){let{gzipSync:e}=await import("zlib"),t=n.map(o=>JSON.stringify(o)).join(`
382
- `)+(n.length?`
383
- `:""),r=e(Buffer.from(t,"utf8")),i=y.join(Ke(),`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 gt(n){let e=n[0],t=r=>n.find((i,o)=>n[o-1]===r);switch(e){case"start":{let{path:r,state:i}=Me();console.log(" flow draft started"),console.log(` session: ${r}`),console.log(` steps: ${i.steps.length}`);return}case"keep":case"good":{let r=se();if(r.active||(console.error(" no active flow draft \u2014 run `sootsim flow 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"),s=se();s.active&&s.kept&&console.log(` auto-kept trailing action: ${s.candidate.summary}`);let a=Ie(r||(i?bt():void 0));if(a.active||(console.error(" no active flow draft \u2014 run `sootsim flow start` first"),process.exit(1)),!a.valid){console.error(" flow draft is not valid:");for(let l of a.issues)console.error(` - ${l}`);console.error(" draft preserved \u2014 keep at least one real interaction or run `sootsim flow start` to reset"),process.exit(1)}if(i){let l=vt(n,a.outputPath),m=await He(l);if(m!==0){console.error(`
384
- validation failed \u2014 draft preserved so you can keep iterating`),process.exitCode=m;return}oe(),console.log(` flow draft validated (${a.stepCount} step${a.stepCount===1?"":"s"})`),a.outputPath&&console.log(` saved: ${a.outputPath}`),o&&console.log(" video: recorded during validation run");return}if(oe(),console.log(` flow draft ended (${a.stepCount} step${a.stepCount===1?"":"s"})`),a.outputPath){console.log(` saved: ${a.outputPath}`),console.log(` next: sootsim flow ${a.outputPath} --record`);return}console.log(""),process.stdout.write(a.yaml);return}case"validate":{let r=n[1];(!r||r.startsWith("-"))&&(console.error(" usage: sootsim flow validate <path>"),process.exit(1));let i=ne(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 yt(n){return n[0]==="--sim"&&n.length>=2?[...n.slice(2),"--sim",n[1]]:n}async function Kt(n){let e=yt(n),t=e[0];if(t==="start"||t==="keep"||t==="good"||t==="end"||t==="validate")return await gt(e),0;let r=await He(e);return r!==0&&(process.exitCode=r),r}function Je(n){let e=n.avgMs>0?(1e3/n.avgMs).toFixed(1):"?",t=n.sampleCount>0?(n.jankFrames/n.sampleCount*100).toFixed(1):"0";console.log(`
385
- profile:`),console.log(` frames: ${n.frames}`),console.log(` total: ${n.totalMs.toFixed(1)}ms`),console.log(` avg: ${n.avgMs.toFixed(2)}ms (${e} fps)`),console.log(` max: ${n.maxMs.toFixed(2)}ms`),n.layoutAvgMs!==void 0&&console.log(` breakdown: layout ${n.layoutAvgMs.toFixed(2)}ms | render ${n.renderAvgMs?.toFixed(2)||"0.00"}ms | copy ${n.copyAvgMs?.toFixed(2)||"0.00"}ms`),console.log(` p95: ${n.p95.toFixed(2)}ms`),console.log(` p99: ${n.p99.toFixed(2)}ms`),console.log(` jank: ${n.jankFrames}/${n.sampleCount} (${t}%) >16.67ms`);let r=Array.isArray(n.worstFrames)?n.worstFrames:[];if(r.length!==0){if(console.log(`
386
- worst frames:`),n.mode==="render-worker"){console.log(" total layout render copy t+");for(let i of r){let[o,s,a,l,m]=i;console.log(` ${s.toFixed(2).padStart(7)} ${a.toFixed(2).padStart(7)} ${l.toFixed(2).padStart(7)} ${m.toFixed(2).padStart(7)} ${String(o).padStart(5)}`)}return}console.log(` ${r.map(i=>i.toFixed(2)).join(", ")}`)}}function bt(){return y.join(Ke(),`sootsim-flow-draft-${Date.now()}.yaml`)}function vt(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{ft as a,He as b,yt as c,Kt as d};